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(realtime): meter the Live channel and stop the quadratic context re-billing
Ruben Lütkee659fc7757e1
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex c0b7877d7d..526c31d9b6 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -20,6 +20,80 @@ _MODEL = "gemini-3.1-flash-live-preview"_INPUT_RATE = 16_000_OUTPUT_RATE = 24_000+# Live sessions accumulate audio (~25 tok/s) plus transcripts plus tool+# traffic and re-bill the FULL context on every model turn — without a+# sliding window that is quadratic in call length, and it is also what+# makes Gemini end long calls via GoAway when the context ceiling nears.+# Compression trades verbatim recall of the oldest audio for a bounded+# context; the orchestrator separately keeps a 20-turn text transcript for+# rebuilds, so nothing the user said is lost to the conversation logic.+_COMPRESSION_TRIGGER_TOKENS = 32_000+_COMPRESSION_TARGET_TOKENS = 16_000+++def _compression_kwargs(types: Any) -> dict[str, Any]:+ """Sliding-window compression config, or {} on an SDK without it.++ Probed by SDK capability, never a model-name pin (AP-21) — same pattern+ as the HistoryConfig probe above. Without compression the Live API+ re-bills the whole accumulated call (audio in AND out) on every model+ turn AND hard-ends long calls at the context ceiling.+ """+ compression_cls = getattr(types, "ContextWindowCompressionConfig", None)+ sliding_cls = getattr(types, "SlidingWindow", None)+ if compression_cls is None or sliding_cls is None:+ log.info(+ "gemini-live: installed google-genai SDK has no context-window "+ "compression; long calls re-bill their full history each turn"+ )+ return {}+ return {+ "context_window_compression": compression_cls(+ trigger_tokens=_COMPRESSION_TRIGGER_TOKENS,+ sliding_window=sliding_cls(+ target_tokens=_COMPRESSION_TARGET_TOKENS+ ),+ )+ }+++def _usage_from_metadata(md: Any) -> dict[str, int] | None:+ """Token counts of one generation as a flat dict, or None when empty.++ Modality detail lists are optional on the wire; totals are authoritative.+ Keys: input_total/output_total plus the text/audio split when reported.+ """+ def _count(value: Any) -> int:+ try:+ return int(value or 0)+ except (TypeError, ValueError):+ return 0++ total_in = _count(getattr(md, "prompt_token_count", None))+ total_out = _count(getattr(md, "response_token_count", None))+ if total_in <= 0 and total_out <= 0:+ return None+ usage = {+ "input_total": total_in,+ "output_total": total_out,+ "input_text": 0,+ "input_audio": 0,+ "output_text": 0,+ "output_audio": 0,+ }+ for attr, text_key, audio_key in (+ ("prompt_tokens_details", "input_text", "input_audio"),+ ("response_tokens_details", "output_text", "output_audio"),+ ):+ for detail in tuple(getattr(md, attr, None) or ()):+ modality = getattr(detail, "modality", None)+ name = str(getattr(modality, "name", None) or modality or "").upper()+ count = _count(getattr(detail, "token_count", None))+ if count <= 0:+ continue+ usage[audio_key if "AUDIO" in name else text_key] += count+ return usage+@dataclass(frozen=True, slots=True)class _PcmChunk:@@ -42,6 +116,10 @@ class _ProviderEvent:call_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = None+ # Token counts of one finished generation (see _usage_from_metadata).+ # The Live channel was previously the only brain path whose spend was+ # invisible to the recorder — 100% of Live-API tokens went unmetered.+ usage: dict[str, int] | None = Noneclass _GeminiLiveSession:@@ -84,6 +162,11 @@ class _GeminiLiveSession:self._client = clientself.session_id = session_idself._closed = False+ # Latest usage_metadata snapshot of the CURRENT generation. Emitted+ # once per generation boundary (tool call, turn end, barge-in) so the+ # orchestrator can sum generations without double counting the+ # progressive snapshots some SDK versions repeat mid-generation.+ self._pending_usage: dict[str, int] | None = Noneasync def send_audio(self, chunk: Any) -> None:from google.genai import types # lazy (AP-26)@@ -121,10 +204,21 @@ class _GeminiLiveSession:audio=_PcmChunk(pcm=bytes(data), sample_rate=_OUTPUT_RATE),)+ usage_metadata = getattr(message, "usage_metadata", None)+ if usage_metadata is not None:+ usage = _usage_from_metadata(usage_metadata)+ if usage is not None:+ self._pending_usage = usage+tool_call = getattr(message, "tool_call", None)function_calls = tuple(getattr(tool_call, "function_calls", None) or ())+ if function_calls and self._pending_usage is not None:+ # A tool call ends this generation; report its usage now so+ # the follow-up generation's snapshot cannot overwrite it.+ yield _ProviderEvent(type="usage", usage=self._pending_usage)+ self._pending_usage = Nonefor function_call in function_calls:raw_args = getattr(function_call, "args", None) or {}if hasattr(raw_args, "model_dump"):@@ -158,6 +252,13 @@ class _GeminiLiveSession:# the same server-content message. Emit it first so the shared# session closes the old turn before adopting the new words.if bool(getattr(content, "interrupted", False)):+ if self._pending_usage is not None:+ # Barge-in ends the generation; its tokens were+ # still billed.+ yield _ProviderEvent(+ type="usage", usage=self._pending_usage+ )+ self._pending_usage = Noneyield _ProviderEvent(type="interrupted")input_transcription = getattr(@@ -193,6 +294,11 @@ class _GeminiLiveSession:"may have been cut short by the server",reason_name,)+ if self._pending_usage is not None:+ yield _ProviderEvent(+ type="usage", usage=self._pending_usage+ )+ self._pending_usage = Noneif not function_calls:yield _ProviderEvent(type="turn_complete")@@ -522,6 +628,7 @@ class GeminiLiveProvider:if seed_declaredelse {}),+ **_compression_kwargs(types),)connection_cm = client.aio.live.connect(model=str(getattr(cfg, "model", "") or _MODEL),diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex b9740f4afb..d2b0901b41 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -112,6 +112,43 @@ class _ProviderEvent:call_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = None+ # Token counts of one finished response (see _usage_from_response) —+ # previously discarded, leaving 100% of Realtime-API spend unmetered.+ usage: dict[str, int] | None = None+++def _usage_from_response(response: Any) -> dict[str, int] | None:+ """Token counts of one response.done payload, or None when empty.++ ``input_cached`` rides along because OpenAI bills cached input at a+ tenth of the text rate — pricing it as fresh input would overstate the+ dominant share of a long call.+ """+ usage_obj = getattr(response, "usage", None)+ if usage_obj is None:+ return None++ def _count(value: Any) -> int:+ try:+ return int(value or 0)+ except (TypeError, ValueError):+ return 0++ total_in = _count(getattr(usage_obj, "input_tokens", None))+ total_out = _count(getattr(usage_obj, "output_tokens", None))+ if total_in <= 0 and total_out <= 0:+ return None+ in_details = getattr(usage_obj, "input_token_details", None)+ out_details = getattr(usage_obj, "output_token_details", None)+ return {+ "input_total": total_in,+ "output_total": total_out,+ "input_text": _count(getattr(in_details, "text_tokens", None)),+ "input_audio": _count(getattr(in_details, "audio_tokens", None)),+ "input_cached": _count(getattr(in_details, "cached_tokens", None)),+ "output_text": _count(getattr(out_details, "text_tokens", None)),+ "output_audio": _count(getattr(out_details, "audio_tokens", None)),+ }def _error_code(event: Any) -> str:@@ -475,6 +512,12 @@ class _OpenAIRealtimeSession:elif len(self._accepted_response_ids) == 1:self._accepted_response_ids.pop()self._response_idle.set()+ usage = _usage_from_response(getattr(event, "response", None))+ if usage is not None:+ # Every response bills its own pass over the session context,+ # including tool-call generations that never reach+ # turn_complete — report each one.+ yield _ProviderEvent(type="usage", usage=usage)status_error = _response_status_error(event)if status_error:# response.done is emitted for completed, failed, and@@ -557,6 +600,15 @@ class _OpenAIRealtimeSession:if isinstance(tool, dict) and tool.get("name")]update["tool_choice"] = "auto" if update["tools"] else "none"+ if self._session_contract is not None:+ # The orchestrator rebuilds its ~20k-character instruction block+ # every turn even when nothing in it changed. Re-sending an+ # identical value is pure cost: it invalidates the provider's+ # prompt-cache prefix and re-bills the block at the fresh-input+ # rate. Only differences travel.+ for key in ("instructions", "tools", "tool_choice"):+ if key in update and self._session_contract.get(key) == update[key]:+ del update[key]if len(update) > 1:if self._session_contract is not None:for key in ("instructions", "tools", "tool_choice"):diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 97ba80d381..78ed9b13b4 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -459,6 +459,13 @@ def _requires_jarvis_action(text: str) -> bool:return plan_turn(text).requires_orchestrator+# Ceiling for a delegate reply injected into the provider context. ~4 000+# characters is roughly three spoken minutes — far beyond any real voice+# answer, small enough to stop a runaway tool result from riding along in+# every later turn of the call.+_DELEGATE_RESULT_MAX_CHARS = 4_000++def _delegate_result_prompt(text: str,*,@@ -476,6 +483,17 @@ def _delegate_result_prompt("""language_name = _LANGUAGE_NAMES.get(language, "the conversation language")status = "success" if success else "failure"+ # The injected result lives in the provider context for the REST OF THE+ # CALL and is re-billed as input on every later turn (at audio-session+ # rates). A spoken reply is short by design; only a pathological+ # delegate answer exceeds this, and its tail would never be voiced+ # anyway. Cut at a sentence boundary where one exists.+ if len(text) > _DELEGATE_RESULT_MAX_CHARS:+ cut = text[:_DELEGATE_RESULT_MAX_CHARS]+ dot = cut.rfind(". ")+ if dot > _DELEGATE_RESULT_MAX_CHARS // 2:+ cut = cut[: dot + 1]+ text = cut + " [result shortened]"framing = (("This is the outcome of the user's earlier request, which finished "@@ -1049,6 +1067,13 @@ class RealtimeVoiceSession:self._failure_detail = ""self._active_model = ""self._active_voice = ""+ # Live-channel token usage accumulated since the last published turn.+ # Providers report one "usage" event per finished generation; a turn+ # may span several generations (tool call + rendering), so the fold+ # is a plain per-key sum. Without this the Live API's own spend —+ # audio in AND out, re-billed context included — never reached the+ # recorder at all (2026-07-28 cost audit: 100% unmetered).+ self._turn_usage: dict[str, int] = {}self._turn_id = ""self._turn_trace_id = Noneself._latency_tracker: Any = None@@ -2397,6 +2422,12 @@ class RealtimeVoiceSession:)for chunk in self._gate.release_available():await self._emit_audio(chunk)+ elif event.type == "usage" and event.usage is not None:+ for key, value in event.usage.items():+ if isinstance(value, int) and value > 0:+ self._turn_usage[key] = (+ self._turn_usage.get(key, 0) + value+ )elif event.type == "audio_delta" and event.audio is not None:delegate_state = self._delegate_turns.get(self._turn_id)if (@@ -3527,6 +3558,65 @@ class RealtimeVoiceSession:else {})+ async def _publish_live_usage(self) -> None:+ """Meter the Live channel's own tokens into the current turn.++ Audio tokens bill at 4-40x the text rate, so the split matters;+ counts the provider could not split are priced as text — a floor,+ never an overstatement. Cached input (OpenAI reports it) bills at a+ tenth of the fresh text rate. The recorder SUMS BrainTurnCompleted+ events per turn, so this adds cleanly on top of any delegate spend.+ Accumulation resets here; usage between turns folds into the next+ published turn rather than vanishing.+ """+ usage, self._turn_usage = self._turn_usage, {}+ if not usage or self._bus is None:+ return+ try:+ from jarvis.brain.cost import (+ PRICING_USD_PER_MTOK,+ calculate_realtime_cost_usd,+ )+ from jarvis.core.events import BrainTurnCompleted++ text_in = usage.get("input_text", 0)+ audio_in = usage.get("input_audio", 0)+ text_out = usage.get("output_text", 0)+ audio_out = usage.get("output_audio", 0)+ cached_in = usage.get("input_cached", 0)+ total_in = max(usage.get("input_total", 0), text_in + audio_in)+ total_out = max(usage.get("output_total", 0), text_out + audio_out)+ unsplit_in = max(0, total_in - text_in - audio_in)+ unsplit_out = max(0, total_out - text_out - audio_out)+ fresh_text_in = max(0, text_in + unsplit_in - cached_in)+ cost = calculate_realtime_cost_usd(+ self._active_model,+ fresh_text_in,+ text_out + unsplit_out,+ audio_in,+ audio_out,+ )+ rates = PRICING_USD_PER_MTOK.get(self._active_model)+ if cached_in > 0 and rates is not None:+ cost += cached_in * rates[0] * 0.1 / 1_000_000+ await self._bus.publish(+ BrainTurnCompleted(+ **self._event_trace_kwargs(),+ source_layer=f"realtime.{self.active_provider}",+ tokens_in=total_in,+ tokens_out=total_out,+ cost_usd=cost,+ finish_reason="realtime_usage",+ provider=self.active_provider,+ model=self._active_model,+ )+ )+ except Exception: # noqa: BLE001 -- metering never breaks the call+ log.debug(+ "realtime[%s] failed to publish live usage", self.session_id,+ exc_info=True,+ )+def _turn_has_activity(self) -> bool:return bool(self._input_turn_observed@@ -3819,6 +3909,7 @@ class RealtimeVoiceSession:VoiceTurnCompleted,)+ await self._publish_live_usage()if external_update is not None:# This was an out-of-band status/readback, not a user turn.# Preserve the existing SpeechSpoken track while recordingdiff --git a/tests/unit/realtime/test_live_usage_metering.py b/tests/unit/realtime/test_live_usage_metering.pynew file mode 100644index 0000000000..9769a8a031--- /dev/null+++ b/tests/unit/realtime/test_live_usage_metering.py@@ -0,0 +1,245 @@+"""Live-channel token metering + context hygiene (2026-07-28 cost audit).++Before these changes the Live/Realtime APIs' own spend — audio tokens at+4-40x text rates, full-context re-billing every turn — never reached the+recorder: providers discarded ``usage_metadata`` / ``response.usage``+entirely, and 57% of recorded realtime turns showed 0 tokens.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.plugins.realtime.gemini_live import (+ _COMPRESSION_TARGET_TOKENS,+ _COMPRESSION_TRIGGER_TOKENS,+ _compression_kwargs,+ _GeminiLiveSession,+ _usage_from_metadata,+)+from jarvis.plugins.realtime.openai_realtime import _usage_from_response+from jarvis.realtime.session import (+ _DELEGATE_RESULT_MAX_CHARS,+ RealtimeVoiceSession,+ _delegate_result_prompt,+)+++def _modality(name: str, count: int) -> SimpleNamespace:+ return SimpleNamespace(modality=SimpleNamespace(name=name), token_count=count)+++class TestGeminiUsageExtraction:+ def test_totals_and_modality_split(self) -> None:+ md = SimpleNamespace(+ prompt_token_count=1200,+ response_token_count=300,+ prompt_tokens_details=[+ _modality("TEXT", 400),+ _modality("AUDIO", 800),+ ],+ response_tokens_details=[_modality("AUDIO", 300)],+ )+ usage = _usage_from_metadata(md)+ assert usage == {+ "input_total": 1200,+ "output_total": 300,+ "input_text": 400,+ "input_audio": 800,+ "output_text": 0,+ "output_audio": 300,+ }++ def test_empty_metadata_returns_none(self) -> None:+ md = SimpleNamespace(+ prompt_token_count=0,+ response_token_count=None,+ prompt_tokens_details=None,+ response_tokens_details=None,+ )+ assert _usage_from_metadata(md) is None++ def test_missing_detail_lists_keep_totals(self) -> None:+ md = SimpleNamespace(+ prompt_token_count=50,+ response_token_count=10,+ prompt_tokens_details=None,+ response_tokens_details=None,+ )+ usage = _usage_from_metadata(md)+ assert usage is not None+ assert usage["input_total"] == 50+ assert usage["input_audio"] == 0+++class TestCompressionConfig:+ def test_sdk_with_compression_gets_sliding_window(self) -> None:+ captured: dict = {}++ class Compression:+ def __init__(self, *, trigger_tokens, sliding_window):+ captured["trigger"] = trigger_tokens+ captured["window"] = sliding_window++ class Sliding:+ def __init__(self, *, target_tokens):+ captured["target"] = target_tokens++ types = SimpleNamespace(+ ContextWindowCompressionConfig=Compression, SlidingWindow=Sliding+ )+ kwargs = _compression_kwargs(types)+ assert "context_window_compression" in kwargs+ assert captured["trigger"] == _COMPRESSION_TRIGGER_TOKENS+ assert captured["target"] == _COMPRESSION_TARGET_TOKENS++ def test_sdk_without_compression_degrades_to_empty(self) -> None:+ assert _compression_kwargs(SimpleNamespace()) == {}+++async def test_gemini_receive_reports_usage_at_the_turn_boundary() -> None:+ messages = [+ SimpleNamespace(+ data=None,+ server_content=None,+ tool_call=None,+ go_away=None,+ usage_metadata=SimpleNamespace(+ prompt_token_count=1000,+ response_token_count=200,+ prompt_tokens_details=[_modality("AUDIO", 1000)],+ response_tokens_details=[_modality("AUDIO", 200)],+ ),+ ),+ SimpleNamespace(+ data=None,+ server_content=SimpleNamespace(+ output_transcription=None,+ input_transcription=None,+ interrupted=False,+ turn_complete=True,+ turn_complete_reason=None,+ ),+ tool_call=None,+ go_away=None,+ usage_metadata=None,+ ),+ ]+ calls = 0++ async def fake_receive():+ nonlocal calls+ calls += 1+ if calls == 1:+ for message in messages:+ yield message++ session = _GeminiLiveSession(+ session=SimpleNamespace(receive=fake_receive),+ connection_cm=SimpleNamespace(),+ client=SimpleNamespace(),+ session_id="s1",+ )+ events = [event async for event in session.receive()]+ kinds = [event.type for event in events]+ # Usage must be reported before the boundary event that closes the turn.+ assert kinds.index("usage") < kinds.index("turn_complete")+ usage_event = next(event for event in events if event.type == "usage")+ assert usage_event.usage is not None+ assert usage_event.usage["input_audio"] == 1000+++class TestOpenAIUsageExtraction:+ def test_split_including_cached(self) -> None:+ response = SimpleNamespace(+ usage=SimpleNamespace(+ input_tokens=5000,+ output_tokens=400,+ input_token_details=SimpleNamespace(+ text_tokens=3000, audio_tokens=2000, cached_tokens=2500+ ),+ output_token_details=SimpleNamespace(+ text_tokens=100, audio_tokens=300+ ),+ )+ )+ usage = _usage_from_response(response)+ assert usage == {+ "input_total": 5000,+ "output_total": 400,+ "input_text": 3000,+ "input_audio": 2000,+ "input_cached": 2500,+ "output_text": 100,+ "output_audio": 300,+ }++ def test_no_usage_returns_none(self) -> None:+ assert _usage_from_response(SimpleNamespace(usage=None)) is None+ assert _usage_from_response(None) is None+++class TestDelegateResultCap:+ def test_short_result_passes_verbatim(self) -> None:+ prompt = _delegate_result_prompt("All done.", language="en", success=True)+ assert "All done." in prompt+ assert "[result shortened]" not in prompt++ def test_runaway_result_is_capped(self) -> None:+ text = "A sentence about something. " * 1000+ prompt = _delegate_result_prompt(text, language="en", success=True)+ assert "[result shortened]" in prompt+ # Framing adds ~1.2k chars; the injected payload stays bounded.+ assert len(prompt) < _DELEGATE_RESULT_MAX_CHARS + 2000+++class _FakeBus:+ def __init__(self) -> None:+ self.published: list = []++ async def publish(self, event) -> None:+ self.published.append(event)+++def _bare_session(usage: dict[str, int], model: str) -> RealtimeVoiceSession:+ session = object.__new__(RealtimeVoiceSession)+ session._turn_usage = dict(usage)+ session._bus = _FakeBus()+ session._active_model = model+ session._turn_trace_id = None+ session.session_id = "s-test"+ # active_provider is a read-only property over the provider's name.+ session._provider = SimpleNamespace(name="gemini-live")+ return session+++async def test_publish_live_usage_prices_audio_and_resets() -> None:+ session = _bare_session(+ {+ "input_total": 1_000_000,+ "output_total": 1_000_000,+ "input_audio": 1_000_000,+ "output_audio": 1_000_000,+ },+ "gemini-3.1-flash-live-preview",+ )+ await session._publish_live_usage()+ events = session._bus.published+ assert len(events) == 1+ event = events[0]+ assert event.tokens_in == 1_000_000+ assert event.tokens_out == 1_000_000+ # Audio rates for the live model: $3/M in + $12/M out.+ assert event.cost_usd == pytest.approx(15.0)+ assert event.provider == "gemini-live"+ assert session._turn_usage == {}+++async def test_publish_live_usage_without_usage_is_silent() -> None:+ session = _bare_session({}, "gemini-3.1-flash-live-preview")+ await session._publish_live_usage()+ assert session._bus.published == []