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.

feat(costs): speech spend gets a surface, an event and a reader

rubenluetke10-beepd92ff4759137
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 7cfb037140..a07260d441 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1572,6 +1572,35 @@ class LatencyTurnComplete(Event):
errors: tuple[str, ...] = field(default_factory=tuple)
+@dataclass(frozen=True, slots=True)
+class SpeechUsageRecorded(Event):
+ """What one turn spent on hearing and on speaking.
+
+ The speech layer does not bill by token: an STT provider charges per
+ audio second and a TTS provider per character, which is why none of this
+ fits the token counters on :class:`BrainTurnCompleted` and why speech
+ spend was invisible until now.
+
+ One event per turn per (stage, provider, voice) — the aggregator behind
+ the metered providers sums a turn's sentence-by-sentence synthesis calls
+ before publishing, so a chatty streaming turn still costs the recorder two
+ rows rather than fifteen.
+ """
+
+ #: ``"stt"`` (hearing) or ``"tts"`` (speaking).
+ stage: str = ""
+ provider: str = ""
+ #: The TTS voice or the STT model — whichever the provider bills by.
+ voice: str = ""
+ #: What TTS bills by.
+ chars: int = 0
+ #: What STT bills by.
+ audio_ms: float = 0.0
+ cost_usd: float = 0.0
+ #: How trustworthy ``cost_usd`` is — see :mod:`jarvis.costs.model`.
+ price_source: str = "unknown"
+
+
@dataclass(frozen=True, slots=True)
class VoiceBootStatus(Event):
"""Voice warm-up readiness signal — drives the UI "voice starting" badge.
diff --git a/jarvis/costs/model.py b/jarvis/costs/model.py
index 542010570f..11e9a40e64 100644
--- a/jarvis/costs/model.py
+++ b/jarvis/costs/model.py
@@ -36,6 +36,11 @@ from typing import Any, Literal
SURFACE_VOICE = "voice"
SURFACE_AGENT_CHAT = "agent-chat"
SURFACE_MISSION = "mission"
+#: The speech layer. Its own surface because it does not bill by token:
+#: hearing costs audio seconds, speaking costs characters.
+SURFACE_JARVIS_VOICE = "jarvis-voice"
+#: Coding agents driven by a vendor CLI, indexed from their session logs.
+SURFACE_AGENTIC_IDE = "agentic-ide"
ROLE_REALTIME = "realtime"
"""Speech-to-speech model — audio tokens, billed per Live/Realtime API rates."""
@@ -50,6 +55,8 @@ ROLE_AGENT = "agent"
"""A coding-agent turn (Claude Code, Codex, …) run from the chat surface."""
ROLE_WORKER = "worker"
+ROLE_STT = "stt"
+ROLE_TTS = "tts"
"""An autonomous mission worker."""
ROLES: tuple[str, ...] = (ROLE_REALTIME, ROLE_TOOL, ROLE_PIPELINE, ROLE_AGENT, ROLE_WORKER)
diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.py
index 7c909838ad..4b681163da 100644
--- a/jarvis/costs/sources.py
+++ b/jarvis/costs/sources.py
@@ -21,10 +21,13 @@ from .model import (
ROLE_AGENT,
ROLE_PIPELINE,
ROLE_REALTIME,
+ ROLE_STT,
ROLE_TOOL,
+ ROLE_TTS,
ROLE_WORKER,
SUBSCRIPTION_RUNNERS,
SURFACE_AGENT_CHAT,
+ SURFACE_JARVIS_VOICE,
SURFACE_MISSION,
SURFACE_VOICE,
CostEntry,
@@ -472,6 +475,78 @@ def _mission_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterato
# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
+# Speech — sessions.db, but nothing like the token path above
+# ---------------------------------------------------------------------------
+
+
+def _speech_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:
+ """What a turn spent on hearing and on speaking.
+
+ These rows carry no tokens and never will: an STT provider bills per audio
+ second and a TTS provider per character. Writing those quantities into the
+ token columns would make them add up with the brain's tokens, which is a
+ different unit and a wrong number. They stay zero, the cost is real, and
+ the quantity that WAS billed goes into the label so the line item can say
+ what was actually bought.
+ """
+ conn = _connect(path)
+ if conn is None:
+ return
+ try:
+ if not _has_table(conn, "voice_events"):
+ return
+ for row in conn.execute(
+ "SELECT session_id, ts_ms, payload_json FROM voice_events "
+ "WHERE kind = 'SpeechUsageRecorded' AND ts_ms BETWEEN ? AND ?",
+ (since_ms, until_ms),
+ ):
+ try:
+ payload = json.loads(row["payload_json"] or "{}")
+ except (TypeError, ValueError) as exc:
+ log.debug("cost read model: unparsable speech payload (%s)", exc)
+ continue
+ if not isinstance(payload, dict):
+ continue
+ stage = str(payload.get("stage") or "")
+ if stage not in (ROLE_STT, ROLE_TTS):
+ continue
+ chars = _int(payload.get("chars"))
+ audio_ms = _float(payload.get("audio_ms"))
+ if chars <= 0 and audio_ms <= 0:
+ continue
+ source = str(payload.get("price_source") or "unknown")
+ yield CostEntry(
+ ts_ms=_int(row["ts_ms"]),
+ surface=SURFACE_JARVIS_VOICE,
+ role=stage,
+ provider=str(payload.get("provider") or "speech"),
+ model=str(payload.get("voice") or ""),
+ tokens_in=0,
+ tokens_out=0,
+ tokens_cached=0,
+ cost_usd=_float(payload.get("cost_usd")),
+ # The meter priced it against the vendor's own unit; re-deriving
+ # it here from a token rate would be nonsense.
+ price_source=source, # type: ignore[arg-type]
+ ref_id=str(row["session_id"] or ""),
+ label=_speech_label(stage, chars, audio_ms),
+ )
+ except sqlite3.Error as exc:
+ log.warning("cost read model: speech source failed (%s)", exc)
+ finally:
+ conn.close()
+
+
+def _speech_label(stage: str, chars: int, audio_ms: float) -> str:
+ """The quantity that was billed, in the unit it was billed in."""
+ if stage == ROLE_TTS and chars > 0:
+ return f"{chars:,} characters spoken".replace(",", " ")
+ if audio_ms > 0:
+ return f"{audio_ms / 1000:.1f} s heard"
+ return ""
+
+
def collect_entries(
sources: CostSources,
*,
@@ -483,5 +558,6 @@ def collect_entries(
entries.extend(_voice_entries(sources.sessions_db, since_ms, until_ms))
entries.extend(_agent_chat_entries(sources.agent_chat_db, since_ms, until_ms))
entries.extend(_mission_entries(sources.missions_db, since_ms, until_ms))
+ entries.extend(_speech_entries(sources.sessions_db, since_ms, until_ms))
entries.sort(key=lambda e: e.ts_ms)
return entries
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index 34e487fcdd..bd04be4039 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -106,6 +106,10 @@ _RAW_EVENT_KINDS: frozenset[str] = frozenset(
# Transcription view only shows the conversational reply and silently
# drops everything else the user actually heard (2026-06-15).
"SpeechSpoken",
+ # What the turn spent on hearing and speaking. Already aggregated per
+ # turn by the speech meter, so this is two rows a turn at most — the
+ # per-frame audio streams stay excluded, as the note below says.
+ "SpeechUsageRecorded",
# Run Inspector forensic events (2026-06-17). The recorder is a read-only
# wildcard subscriber, so persisting these adds no hot-path cost; they
# power the latency waterfall, decision path, and error panel. _payload_for
@@ -1156,6 +1160,13 @@ def _payload_for(event: Event) -> dict[str, Any]:
"tokens_in",
"tokens_out",
"cost_usd",
+ # SpeechUsageRecorded: speech bills by audio second and by character,
+ # never by token, so it needs its own fields. ``voice`` is already
+ # whitelisted below for SpeechSpoken and carries this too.
+ "stage",
+ "chars",
+ "audio_ms",
+ "price_source",
"text_len",
"finish_reason",
# SpeechSpoken: the phrase-kind tag (timeout / announcement / clarify /