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(realtime): compact instruction profile for self-hosted realtime brains
rubenluetke10-beep4384b0922c41
diff --git a/jarvis/brain/persona_loader.py b/jarvis/brain/persona_loader.pyindex a972fb4ed9..5f6ff0f08b 100644--- a/jarvis/brain/persona_loader.py+++ b/jarvis/brain/persona_loader.py@@ -1,22 +1,28 @@-"""Persona-Loader: extrahiert den System-Prompt-Block aus `JARVIS_PERSONA.md`.--`JARVIS_PERSONA.md` ist das autoritative Handbuch für die Jarvis-Voice-Persona-(10 Sprechmuster, OUTPUT RULES, INTERACTION PATTERNS). Der eigentliche-System-Prompt liegt als Plain-Text innerhalb des ersten Code-Fence (```) nach-der Zeile `## System-Prompt`. Alles drumherum (Doku, Router-Empfehlung,-Quellen) ist Metadaten — nicht für das LLM.--Dieser Loader:--1. Liest die MD-Datei einmal und cached das Ergebnis (`lru_cache`).-2. Extrahiert den ersten Fence nach der Marker-Section.-3. Liefert den Plain-Text zurück — bereit für `_build_system_prompt()`.--Robust gegen:-- Fehlende Datei → leerer String (silent fallback, keine Exception in der- Brain-Init-Pfad).-- Fehlender Code-Fence → leerer String.-- CRLF-Line-Endings → werden normalisiert.+"""Persona loader: extracts the system-prompt block from `JARVIS_PERSONA.md`.++`JARVIS_PERSONA.md` is the authoritative handbook for the voice persona+(speech patterns, OUTPUT RULES, INTERACTION PATTERNS). The actual system+prompt is the plain text inside the first code fence (```) after the line+`## System-Prompt`. Everything around it (docs, router notes, sources) is+maintainer metadata — never sent to the LLM.++A second, much shorter block lives after `## System-Prompt (Compact)`: the+distilled persona for small self-hosted realtime brains, where the full 15k+characters cost multiple seconds of prompt processing EVERY turn (7.8 s+measured against qwen2.5:7b, 2026-08-07). Missing compact section falls back+to the full block — honest, never a silent truncation.++This loader:++1. Reads the MD file once and caches the result (`lru_cache`).+2. Extracts the first fence after the requested marker section.+3. Returns the plain text — ready for `_build_system_prompt()`.++Robust against:+- Missing file → empty string (silent fallback, no exception on the+ brain-init path).+- Missing code fence → empty string.+- CRLF line endings → normalized."""from __future__ import annotations@@ -28,22 +34,23 @@ log = logging.getLogger(__name__)_PERSONA_MD_FILENAME = "JARVIS_PERSONA.md"_SECTION_MARKER = "## System-Prompt"+_COMPACT_SECTION_MARKER = "## System-Prompt (Compact)"_FENCE = "```"def _persona_md_path() -> Path:- """Pfad zur autoritativen `JARVIS_PERSONA.md` im `jarvis/brain/`-Package."""+ """Path to the authoritative `JARVIS_PERSONA.md` in the `jarvis/brain/` package."""return Path(__file__).resolve().parent / _PERSONA_MD_FILENAME-def _extract_fence_after_marker(content: str) -> str:- """Holt den ersten ```...```-Block nach der Zeile `## System-Prompt`.+def _extract_fence_after_marker(content: str, marker: str = _SECTION_MARKER) -> str:+ """The first ```...``` block after the given marker line.- Wenn der Marker oder der Fence fehlt, liefert die Funktion einen leeren- String — der Aufrufer entscheidet, ob das tolerabel ist.+ When the marker or the fence is missing, the function returns an empty+ string — the caller decides whether that is tolerable."""normalized = content.replace("\r\n", "\n")- marker_idx = normalized.find(_SECTION_MARKER)+ marker_idx = normalized.find(marker)if marker_idx == -1:return ""tail = normalized[marker_idx:]@@ -51,7 +58,7 @@ def _extract_fence_after_marker(content: str) -> str:if open_idx == -1:return ""body_start = open_idx + len(_FENCE)- # Zeilenumbruch nach dem Opening-Fence überspringen.+ # Skip the line break after the opening fence.newline_after_open = tail.find("\n", body_start)if newline_after_open == -1:return ""@@ -62,34 +69,52 @@ def _extract_fence_after_marker(content: str) -> str:return tail[body_start:close_idx].rstrip()-@lru_cache(maxsize=1)-def load_persona_prompt() -> str:- """System-Prompt-Block aus `JARVIS_PERSONA.md` — gecacht über Prozess-Leben.-- Return: Prompt-Text oder leerer String wenn Datei/Fence nicht gefunden.- """+def _read_persona_md() -> str:path = _persona_md_path()try:- content = path.read_text(encoding="utf-8")+ return path.read_text(encoding="utf-8")except FileNotFoundError:- log.warning("JARVIS_PERSONA.md fehlt an %s — Persona-Layer leer.", path)+ log.warning("JARVIS_PERSONA.md missing at %s — persona layer empty.", path)return ""except OSError as exc:- log.warning("JARVIS_PERSONA.md nicht lesbar (%s) — Persona-Layer leer.", exc)+ log.warning("JARVIS_PERSONA.md unreadable (%s) — persona layer empty.", exc)return ""- block = _extract_fence_after_marker(content)++@lru_cache(maxsize=1)+def load_persona_prompt() -> str:+ """System-prompt block from `JARVIS_PERSONA.md` — cached for the process."""+ block = _extract_fence_after_marker(_read_persona_md())if not block:log.warning(- "JARVIS_PERSONA.md: Section '%s' oder Code-Fence fehlt — Persona-Layer leer.",+ "JARVIS_PERSONA.md: section '%s' or code fence missing — persona layer empty.",_SECTION_MARKER,)return block+@lru_cache(maxsize=1)+def load_compact_persona_prompt() -> str:+ """The distilled persona for small self-hosted brains — cached.++ Falls back to the FULL block when the compact section is absent: a+ persona that silently shrank to nothing would change the voice, while a+ temporarily slower prompt merely changes latency.+ """+ compact = _extract_fence_after_marker(_read_persona_md(), _COMPACT_SECTION_MARKER)+ if compact:+ return compact+ log.info(+ "JARVIS_PERSONA.md: no '%s' section — compact requests use the full persona.",+ _COMPACT_SECTION_MARKER,+ )+ return load_persona_prompt()++def invalidate_cache() -> None:- """Cache invalidieren — für Tests oder Hot-Reload nach MD-Edit."""+ """Invalidate the caches — for tests or hot reload after an MD edit."""load_persona_prompt.cache_clear()+ load_compact_persona_prompt.cache_clear()# ---------------------------------------------------------------------------@@ -150,11 +175,18 @@ def default_persona_prompt() -> str:return load_persona_prompt()-def load_effective_persona_prompt() -> str:- """The persona block the brain should use: custom override if set, else default."""+def load_effective_persona_prompt(*, compact: bool = False) -> str:+ """The persona block the brain should use: custom override if set, else default.++ The custom override wins EVEN in compact mode — the user chose those+ exact words for their assistant, and user autonomy outranks the latency+ optimization (the trade-off is documented on the settings surface).+ """custom = read_custom_prompt()if custom is not None:return custom+ if compact:+ return load_compact_persona_prompt()return default_persona_prompt()diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 9fc6f19cb1..2f284c1382 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1371,6 +1371,12 @@ class LocalRealtimeProvider:# and quietly routing a call into one the user did not pick is the opposite# of what a local card is for.implicit_usage_fallback_allowed = False+ # Small self-hosted brains prefill the whole instruction block EVERY turn;+ # the full ~24k-char profile cost 7.8 s of LLM time per answer against+ # qwen2.5:7b (live 2026-08-07). The session builder honors this capability+ # with the distilled persona and a prefix-cache-friendly static-first+ # ordering (AP-21: a declared capability, never a provider-name check).+ prefers_compact_instructions = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATE# EMPTY, not absent. The keyless path is chosen by this tuple being emptydiff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 83a63a99f0..fa9a5cff8a 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -1057,10 +1057,22 @@ def _session_instructions(preferences: str = "",skill_directive: str = "",workspace_directive: str = "",+ compact: bool = False,) -> str:+ """Assemble the session instructions; ``compact`` is the small-brain profile.++ ``compact`` is requested by a provider capability+ (``prefers_compact_instructions``, AP-21 — today the self-hosted card): a+ 7B brain spends multiple seconds prefilling the full ~24k-char block+ EVERY turn (7.8 s live, 2026-08-07). The compact profile swaps in the+ distilled persona and shortened static guards, and orders the assembly+ static-first / dynamic-last so a prefix-caching server (Ollama) reuses+ the unchanged head across turns and only re-reads the per-turn tail.+ Cloud providers keep the exact historical text and ordering.+ """from jarvis.brain.persona_loader import load_effective_persona_prompt- persona = _realtime_persona(load_effective_persona_prompt())+ persona = _realtime_persona(load_effective_persona_prompt(compact=compact))# The block is re-sent with every per-turn session update, so this stays# current across long sessions. Without it the model must either# hallucinate calendar answers or delegate a trivial "what day is@@ -1128,6 +1140,24 @@ def _session_instructions("you to check or look it up, that is an explicit action request ""for your action function.")+ if compact:+ # Same contracts, an eighth of the words: the full guards teach with+ # incident detail a frontier model benefits from and a 7B model pays+ # prefill time for. The action-request hand-off sentence survives in+ # both because it is load-bearing for routing.+ freshness_line = (+ "Your built-in knowledge is months to years out of date. For "+ "time-sensitive facts, reason from the current date given below, "+ "mark such answers as possibly outdated, and offer to check. A "+ "request to check or look something up is an action request for "+ "your action function, not world knowledge."+ )+ precision_line = (+ "Never present a remembered niche figure (measurements, specs, "+ "capacities) as exact, and never rest a flat verdict on one; "+ "give an estimate clearly marked as such and offer to check the "+ "real numbers."+ )language_name = _LANGUAGE_NAMES.get(language, "the user's language")input_language_name = _LANGUAGE_NAMES.get(input_language)if input_language_name:@@ -1150,6 +1180,35 @@ def _session_instructions("turn is only a one- or two-word interjection, keep replying in "f"{language_name}, the current conversation language.")+ identity_line = (+ "Runtime identity: this voice session is using the Realtime engine"+ + (f", provider {provider}" if provider else "")+ + (f", model {model}" if model else "")+ + ". If the user asks which engine, provider, or model is active, "+ "answer from this runtime identity exactly; do not describe the "+ "classic text brain configuration."+ )+ if compact:+ # Static-first / dynamic-last: everything that is identical from turn+ # to turn forms one stable prefix, so Ollama's KV prefix cache skips+ # re-reading it; only the tail (workspace roster, skill, clock,+ # language) changes between per-turn session updates.+ parts = [+ persona,+ preferences,+ _ONE_SPEAKER_DIRECTIVE,+ tool_directive,+ _REALTIME_SAFETY_APPENDIX,+ freshness_line,+ precision_line,+ identity_line,+ workspace_directive,+ skill_directive,+ input_directive,+ clock_line,+ language_directive,+ ]+ return "\n\n".join(part for part in parts if part)parts = [persona,# The user's own standing instructions come right after the persona and@@ -1174,14 +1233,7 @@ def _session_instructions(clock_line,freshness_line,precision_line,- (- "Runtime identity: this voice session is using the Realtime engine"- + (f", provider {provider}" if provider else "")- + (f", model {model}" if model else "")- + ". If the user asks which engine, provider, or model is active, "- "answer from this runtime identity exactly; do not describe the "- "classic text brain configuration."- ),+ identity_line,language_directive,]return "\n\n".join(part for part in parts if part)@@ -2085,6 +2137,12 @@ class RealtimeVoiceSession:tool_directive=self._tool_directive(provider=provider),preferences=_preferences_block(self._config),workspace_directive=self._workspace_directive(),+ # Capability, never a provider-name check (AP-21): a small+ # self-hosted brain asks for the compact profile so it is+ # not prefilling 24k chars per turn.+ compact=bool(+ getattr(provider, "prefers_compact_instructions", False)+ ),),language=self._language,input_language=self._input_language,@@ -2178,6 +2236,11 @@ class RealtimeVoiceSession:self._provider = providerself._session = sessionself._active_model = model+ # Captured at accept so every per-turn instruction rebuild keeps+ # the profile the accepted provider asked for.+ self._compact_instructions = bool(+ getattr(provider, "prefers_compact_instructions", False)+ )# Retained for the per-turn "which voice spoke" transcript label.self._active_voice = voiceself._input_sample_rate = input_rate@@ -2948,6 +3011,9 @@ class RealtimeVoiceSession:# call, and a roster naming a terminal that is# gone is worse than none.workspace_directive=self._workspace_directive(),+ compact=getattr(+ self, "_compact_instructions", False+ ),),"language": new_language,# For append-only transports: the turn-scopeddiff --git a/tests/unit/brain/test_persona_loader.py b/tests/unit/brain/test_persona_loader.pyindex 8d23c5aafc..ef20f03463 100644--- a/tests/unit/brain/test_persona_loader.py+++ b/tests/unit/brain/test_persona_loader.py@@ -104,6 +104,55 @@ def test_load_persona_prompt_extracts_real_persona(monkeypatch) -> None:assert "Goodbye" in prompt or "Auf Wiedersehen" in prompt # i18n-allow+def test_compact_persona_is_a_real_distillation() -> None:+ """The compact block exists in the shipped MD, keeps the load-bearing+ rules, and is a fraction of the full block's size (the entire point:+ 7.8 s of 7B prefill per turn measured 2026-08-07)."""+ invalidate_cache()+ try:+ full = load_persona_prompt()+ compact = pl.load_compact_persona_prompt()+ finally:+ invalidate_cache()+ assert compact+ assert compact != full+ assert len(compact) < len(full) / 4+ assert "JARVIS" not in compact # name-neutral, like the full block+ assert "voice companion" in compact+ # The strict spoken-output core must survive the distillation.+ assert "digit" in compact+ assert "Markdown" in compact+++def test_compact_falls_back_to_full_when_section_missing(+ monkeypatch, tmp_path+) -> None:+ """A persona that silently shrank to nothing would change the voice;+ a missing compact section must serve the full block instead."""+ invalidate_cache()+ md_file = tmp_path / "JARVIS_PERSONA.md"+ md_file.write_text(+ "## System-Prompt\n```\nFull only.\n```\n", encoding="utf-8"+ )+ monkeypatch.setattr(pl, "_persona_md_path", lambda: md_file)+ try:+ assert pl.load_compact_persona_prompt() == "Full only."+ finally:+ invalidate_cache()+++def test_custom_override_wins_even_in_compact_mode(monkeypatch, tmp_path) -> None:+ """User autonomy outranks the latency optimization: their exact words+ stay, whatever profile the provider asked for."""+ invalidate_cache()+ monkeypatch.setattr(pl, "read_custom_prompt", lambda: "My own words.")+ try:+ assert pl.load_effective_persona_prompt(compact=True) == "My own words."+ assert pl.load_effective_persona_prompt(compact=False) == "My own words."+ finally:+ invalidate_cache()++def test_load_persona_prompt_missing_file_returns_empty(monkeypatch, tmp_path) -> None:"""When the MD is missing, the loader returns an empty string — no raise."""invalidate_cache()diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex fbc712ae51..016bc45ce8 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -5084,7 +5084,9 @@ def test_session_instructions_place_preferences_between_persona_and_directives(from jarvis.realtime import session as session_modmonkeypatch.setattr(- persona_loader, "load_effective_persona_prompt", lambda: "PERSONA_MARKER"+ persona_loader,+ "load_effective_persona_prompt",+ lambda *, compact=False: "PERSONA_MARKER",)text = session_mod._session_instructions("de",@@ -5110,7 +5112,7 @@ def test_session_instructions_never_teach_native_voice_pipeline_control_tokens(monkeypatch.setattr(persona_loader,"load_effective_persona_prompt",- lambda: (+ lambda *, compact=False: ("IDENTITY\n\n""ENDING THE CALL\n"f"Say goodbye and append {END_CALL_SIGNAL}.\n\n"@@ -5139,7 +5141,9 @@ def test_session_instructions_anchor_clock_and_stale_knowledge_guard(monkeypatchfrom jarvis.realtime import session as session_modmonkeypatch.setattr(- persona_loader, "load_effective_persona_prompt", lambda: "PERSONA_MARKER"+ persona_loader,+ "load_effective_persona_prompt",+ lambda *, compact=False: "PERSONA_MARKER",)text = session_mod._session_instructions("en")assert datetime.now().astimezone().strftime("%Y-%m-%d") in text@@ -5160,7 +5164,9 @@ def test_session_instructions_carry_the_precision_guard(monkeypatch):from jarvis.realtime import session as session_modmonkeypatch.setattr(- persona_loader, "load_effective_persona_prompt", lambda: "PERSONA_MARKER"+ persona_loader,+ "load_effective_persona_prompt",+ lambda *, compact=False: "PERSONA_MARKER",)text = session_mod._session_instructions("en")assert "Precision guard" in textdiff --git a/tests/unit/realtime/test_session_compact_instructions.py b/tests/unit/realtime/test_session_compact_instructions.pynew file mode 100644index 0000000000..290731af04--- /dev/null+++ b/tests/unit/realtime/test_session_compact_instructions.py@@ -0,0 +1,149 @@+"""The compact instruction profile for small self-hosted realtime brains.++A 7B brain prefills the ENTIRE instruction block every turn; the full+~24k-char profile cost 7.8 s of LLM time per answer (live 2026-08-07,+qwen2.5:7b behind the local-realtime server). What these tests pin:++- compact is a real reduction, not a cosmetic one;+- the assembly is static-first / dynamic-last so a prefix-caching server+ (Ollama) only re-reads the per-turn tail;+- cloud providers keep the exact historical text (flag absent = byte-equal+ to the pre-compact behavior);+- the session captures the capability at accept and uses it per turn.+"""++from __future__ import annotations++import asyncio++import pytest++from jarvis.brain.persona_loader import invalidate_cache+from jarvis.realtime.session import RealtimeVoiceSession, _session_instructions++from .test_session import FakeProvider, _cfg++[email protected](autouse=True)+def _fresh_persona_cache():+ invalidate_cache()+ yield+ invalidate_cache()+++def _build(compact: bool) -> str:+ return _session_instructions(+ "de",+ input_language="auto",+ provider="p",+ model="m",+ language_is_pinned=True,+ tool_directive="TOOL DIRECTIVE",+ preferences="PREFS",+ workspace_directive="WORKSPACE ROSTER",+ skill_directive="SKILL BODY",+ compact=compact,+ )+++def test_compact_is_a_real_reduction() -> None:+ full = _build(compact=False)+ compact = _build(compact=True)+ assert len(compact) < len(full) * 0.6+ # The load-bearing pieces survive.+ assert "TOOL DIRECTIVE" in compact+ assert "PREFS" in compact+ assert "Reply only in German" in compact+++def test_compact_orders_static_first_dynamic_last() -> None:+ """The per-turn dynamic pieces must sit BEHIND every static block, so+ the unchanged head stays a byte-stable prefix across session updates."""+ compact = _build(compact=True)+ static_markers = ["voice companion", "TOOL DIRECTIVE", "Runtime identity"]+ dynamic_markers = [+ "WORKSPACE ROSTER",+ "SKILL BODY",+ "Current local date and time",+ "Reply only in German",+ ]+ last_static = max(compact.index(marker) for marker in static_markers)+ first_dynamic = min(compact.index(marker) for marker in dynamic_markers)+ assert last_static < first_dynamic+++def test_compact_head_is_stable_across_turn_rebuilds() -> None:+ """Two rebuilds that differ only in per-turn dynamics share their whole+ static head — the property Ollama's prefix cache actually exploits."""+ first = _session_instructions(+ "de",+ tool_directive="TOOL DIRECTIVE",+ preferences="PREFS",+ workspace_directive="ROSTER ONE",+ compact=True,+ )+ second = _session_instructions(+ "en",+ tool_directive="TOOL DIRECTIVE",+ preferences="PREFS",+ workspace_directive="ROSTER TWO",+ compact=True,+ )+ head = first[: first.index("ROSTER ONE")]+ assert second.startswith(head)+++def test_flag_absent_means_the_historical_profile() -> None:+ """``compact`` defaults off: providers that never declared the+ capability get a byte-identical prompt to the explicit False path."""+ assert _build(compact=False) == _session_instructions(+ "de",+ input_language="auto",+ provider="p",+ model="m",+ language_is_pinned=True,+ tool_directive="TOOL DIRECTIVE",+ preferences="PREFS",+ workspace_directive="WORKSPACE ROSTER",+ skill_directive="SKILL BODY",+ )+++class _CompactProvider(FakeProvider):+ name = "compact-family"+ prefers_compact_instructions = True+++async def test_session_captures_the_capability_at_accept():+ provider = _CompactProvider([])+ sess = RealtimeVoiceSession(+ session_id="compact-capture",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ providers=[provider],+ config=_cfg(),+ bus=None,+ )+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.end(reason="test")+ assert sess._compact_instructions is True+ # The provider actually received the compact block at open.+ opened = provider.opened_with+ assert len(opened.instructions) < 15_000+++async def test_session_defaults_to_the_full_profile():+ provider = FakeProvider([])+ sess = RealtimeVoiceSession(+ session_id="full-capture",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ providers=[provider],+ config=_cfg(),+ bus=None,+ )+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.end(reason="test")+ assert sess._compact_instructions is False