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.

fix(costs): every area adds up — seats, accounts, Grok Build, missions, speech metering (BUG-178)

rubenluetke10-beep19f10327d53c
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 7bfbf226a9..cf89477aa4 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -12713,3 +12713,80 @@ never the boot.
`pythonw` parent before it re-execs through the branded exe is the price of a
branded taskbar button (`icon_utils.maybe_reexec_through_branded_launcher`);
a shortcut that targets the in-venv branded exe directly skips it.
+
+---
+
+## BUG-178: the Costs section could not add up — a stuck filter emptied an area, seats read as "$0.00", Grok Build and three Claude accounts were never counted, and speech metering leaked (HIGH, FIXED 2026-08-25)
+
+**Symptom (maintainer, 2026-08-25).** Overall showed "Total spend $18.41"
+over a provider table summing to $6,000+; Agentic IDE showed "$0.00 —
+$4,452 on a subscription"; the "{name}" tab showed "0 calls" although it had
+worked an hour earlier; "{name} Voice" showed nothing; "Unpriced tokens
+16.73M". "The calculations simply do not add up."
+
+**Root causes (four deep-dive audits, one per area).**
+
+1. *Headline.* `CostsView` subtracted the seat-covered amount and showed only
+ what an API key was billed. The API-equivalent of everything is the
+ number the maintainer asked for; the split is the sub-line now.
+2. *Stuck filter.* `pickArea` cleared only surfaces and roles, so a provider
+ chosen inside Agentic IDE (`claude-cli`) survived the switch to "{name}"
+ where no row can match it. Every row filter is cleared with the area, and
+ an empty area under a row filter now says so with a one-click clear.
+3. *Missing accounts.* The CLI index scanned `~/.claude` only. Two further
+ Claude subscriptions run with their own config directories under
+ `agent-accounts/claude/<id>/` and held 396 session files / 6.5 billion
+ tokens nobody counted. `_account_roots` adds every managed account and
+ every leftover folder of a deleted one.
+4. *Grok Build invisible.* `~/.grok/sessions/**/updates.jsonl` (608 MB) had
+ no reader. `turn_completed` carries per-turn usage in the OpenAI
+ convention (input includes cache reads); `prompt_id` is the identity.
+ New `AGENT_GROK` reader; xAI's cache-read discount measured from its own
+ `costUsdTicks` is 25 %, not 10 %.
+5. *Seats priced as free.* `price_entry` returned `(0.0, "free")` for
+ `SUBSCRIPTION_PROVIDERS`. A seat is worth its API-equivalent and is
+ labelled `subscription`; "free" is for local engines and `:free` models.
+6. *Missions.* `WorkerDraftReady` carries no CLI or model; both live on
+ `WorkerSpawned` for the same `worker_id`. 64 drafts (1.78M tokens) were
+ unpriced and 189 seat quotes passed as billed. The reader joins the two,
+ the CLI's short names (`sonnet`/`opus`/`haiku`) resolve via
+ `MODEL_ALIASES`, and the Claude worker's turn count no longer lands in a
+ token column.
+7. *Codex cache hits twice.* `_agent_chat_entries` summed `input_tokens`
+ and `cached_input_tokens` for the Codex runner; only OpenAI-convention
+ runners subtract. Same class as BUG-177, second reader.
+8. *Voice pipeline cache blind.* `manager.py` read `input_tokens` and
+ `output_tokens` only; the plugins report `cache_hit_tokens` and the
+ OpenAI plugin counted them inside the input. `BrainTurnCompleted` carries
+ `tokens_cached`, the OpenAI plugin honours the canonical contract (input =
+ uncached), and grok-4.5 — 82 calls at $0.00 — has a rate.
+9. *Speech metering leaks.* `set_stt_provider` and the live language switch
+ replaced the metered STT with a bare one; dictation and the realtime
+ surface voice were never wrapped; nothing flushed outside a classic turn
+ or at session end. All four wrapped; flush before `VoiceSessionEnded`
+ and after 20 s of idle.
+10. *Index hygiene.* Codex fork replays inserted rows before their file's
+ `turn_context` (130 rows / 16.4M tokens with no model) — backfilled from
+ the session; rows of deleted transcripts lived forever (446 rows / 88M
+ tokens) — pruned when the file's root is readable and the file is gone;
+ `kimi-k2.5:cloud` and `codex-auto-review` priced; the report cache now
+ keys on the index file too.
+
+**Numbers on the same machine, before → after.** Agentic IDE $4,452 (one
+account, Claude only) → $12.6k API-equivalent across two seats, Codex, Kimi
+and Grok Build; unpriced tokens 16.7M → agy's 1.4M (the one CLI that writes
+no model id, named as such).
+
+**Still open, deliberately.** GLM panes run the Claude binary against z.ai
+with no config dir of their own and are counted as Claude Code at Anthropic
+rates (12× too high) — a spawn-side fix (own `CLAUDE_CONFIG_DIR`), T3. A
+chat turn or mission worker that drives a vendor CLI is counted once by its
+surface and once by the index; latent while the chat store holds one turn,
+needs the vendor session id persisted on both sides. Per-account
+attribution ("which seat burned this") needs an account column. An
+index-state endpoint ("63 % of 12.7 GB read") does not exist yet.
+
+**Lesson.** A spend report has as many readers as the app has ways to spend,
+and every reader is a place to be wrong in its own way. The audit that found
+these was one agent per area with the real databases in front of it, not a
+walk through the code.
diff --git a/jarvis/brain/cost.py b/jarvis/brain/cost.py
index 0d56ce4607..b2708c6706 100644
--- a/jarvis/brain/cost.py
+++ b/jarvis/brain/cost.py
@@ -39,9 +39,12 @@ If a model is missing here AND in the feed, ``calculate_cost_usd`` returns
mandatory so that missing entries become visible rather than silently
turning into a "free" banner.
-Aliases are NOT mapped here — callers must pass the canonical model name
-(e.g. ``claude-opus-4-7-20251022`` instead of ``opus``). PROVIDER_ALIASES
-in ``manager.py`` is for provider names, not model IDs.
+Only the three short names a coding CLI accepts on its command line
+(``sonnet`` / ``opus`` / ``haiku``) are mapped, in ``MODEL_ALIASES``: mission
+workers are spawned with exactly those, and 64 drafts holding 1.78M tokens
+sat unpriced because "sonnet" matched nothing (2026-08-25). Every other
+caller passes the canonical id. PROVIDER_ALIASES in ``manager.py`` is for
+provider names, not model IDs.
"""
from __future__ import annotations
@@ -62,6 +65,10 @@ log = logging.getLogger(__name__)
PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
# ── Anthropic Claude (Frontier: Fable 5, Sonnet 4.6, Haiku 4.5) ──
"claude-fable-5": (10.0, 50.0),
+ # Claude 5 family (feed-verified 2026-08-25; the CLIs' "opus" / "sonnet"
+ # aliases resolve here via MODEL_ALIASES).
+ "claude-opus-5": (5.0, 25.0),
+ "claude-sonnet-5": (2.0, 10.0),
"claude-opus-4-8": (15.0, 75.0),
"claude-opus-4-7-20251022": (15.0, 75.0),
"claude-opus-4-7": (15.0, 75.0),
@@ -104,6 +111,12 @@ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
"gemini-live-2.5-flash-native-audio": (0.50, 2.0),
# ── OpenAI (Frontier: GPT-5.5 + 5.5-pro, released 2026-04-23) ──
"gpt-5.5": (5.0, 30.0),
+ # Not a vendor model: Codex's review pass, which runs on the session's own
+ # model. Tracks gpt-5.6-sol, the default that pass runs on.
+ "codex-auto-review": (2.0, 10.0),
+ # Moonshot Kimi, as Codex names it when routed through Ollama
+ # ("kimi-k2.5:cloud" — the variant tag is stripped in resolve_rates).
+ "kimi-k2.5": (0.6, 3.0),
"gpt-5.5-pro": (30.0, 180.0), # corrected 2026-07-28 (OpenRouter feed)
# Realtime API — TEXT rates; audio rates in the realtime table below.
"gpt-realtime-2.1": (4.0, 16.0),
@@ -117,6 +130,15 @@ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
# smarter than 4.20; older entries kept for historical
# cost-tracking analysis) ────────────────────────────────────────
"grok-4.3": (1.25, 2.50),
+ # 82 voice calls ran on grok-4.5 with no row here and were recorded at
+ # $0.00 (2026-08-25). Rate from the OpenRouter feed for x-ai/grok-4.5,
+ # which mirrors xAI's list price.
+ "grok-4.5": (2.0, 6.0),
+ # Grok Build's transcripts name the model "grok-4.6-build". Rates confirmed
+ # to the cent against xAI's own costUsdTicks in those transcripts
+ # (2026-08-25): $2 uncached in / $0.50 cached / $6 out.
+ "grok-4.6": (2.0, 6.0),
+ "grok-4.6-build": (2.0, 6.0),
"grok-4.20": (2.0, 6.0),
"grok-4-0709": (5.0, 15.0),
"grok-4": (5.0, 15.0),
@@ -161,6 +183,9 @@ CACHE_READ_FRACTION_DEFAULT = 0.10
CACHE_READ_FRACTION_BY_PREFIX: tuple[tuple[str, float], ...] = (
("gemini", 0.25),
("google/", 0.25),
+ # Measured from xAI's own costUsdTicks (2026-08-25): a quarter, not a tenth.
+ ("grok", 0.25),
+ ("x-ai/", 0.25),
)
@@ -315,6 +340,16 @@ def feed_rates(model: str) -> tuple[float, float] | None:
return _feed_by_name.get(_norm(model))
+#: The short names a vendor CLI resolves to its current model of that
+#: family. Kept to the frontier entry of each family so a spawn that said
+#: "sonnet" is priced as the Sonnet the CLI actually ran.
+MODEL_ALIASES: dict[str, str] = {
+ "sonnet": "claude-sonnet-5",
+ "opus": "claude-opus-5",
+ "haiku": "claude-haiku-4-5",
+}
+
+
def resolve_rates(model: str | None) -> tuple[float, float] | None:
"""The (in, out) USD-per-1M-token rates for ``model``, or ``None``.
@@ -325,9 +360,20 @@ def resolve_rates(model: str | None) -> tuple[float, float] | None:
"""
if not model:
return None
+ model = MODEL_ALIASES.get(model.strip().casefold(), model)
if "/" in model:
- return feed_rates(model) or PRICING_USD_PER_MTOK.get(model)
- return PRICING_USD_PER_MTOK.get(model) or feed_rates(model)
+ rates = feed_rates(model) or PRICING_USD_PER_MTOK.get(model)
+ else:
+ rates = PRICING_USD_PER_MTOK.get(model) or feed_rates(model)
+ if rates is not None:
+ return rates
+ # An Ollama-style variant tag ("kimi-k2.5:cloud", "qwen3:32b") prices as
+ # the untagged model. ":free" is not a variant — it is the free tier and
+ # price_entry settles it before ever asking here — so it stays unknown.
+ base, sep, tag = model.partition(":")
+ if sep and tag and tag != "free":
+ return resolve_rates(base)
+ return None
async def ensure_pricing_for(model: str | None, *, timeout_s: float = 3.0) -> bool:
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 892d16ef1d..722a51f06a 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -71,8 +71,10 @@ from jarvis.core.protocols import (
BrainRequest,
CostRecord,
ImageBlock,
+ ReasoningEffort,
Tool,
)
+from jarvis.brain.turn_override import TurnOverride
from jarvis.core.redact import safe_preview
from jarvis.core.turn_language import (
DEFAULT_LOCALE,
@@ -142,6 +144,13 @@ _TURN_HISTORY_OVERRIDE: ContextVar[tuple[BrainMessage, ...] | None] = ContextVar
"jarvis.brain.manager.turn_history_override",
default=None,
)
+#: The typed chat's per-turn pick (jarvis/brain/turn_override.py): read where
+#: the chain, the tool surface and the dispatcher are built; never persisted on
+#: the manager, so a concurrent voice turn keeps its own brain.
+_TURN_OVERRIDE: ContextVar[TurnOverride | None] = ContextVar(
+ "jarvis.brain.manager.turn_override",
+ default=None,
+)
class _SkillTurnState:
@@ -3350,9 +3359,16 @@ class BrainManager:
log.warning("No credential-ready, tool-capable Tool Model is available.")
return ready
- def _get_brain(self, name: str, model: str | None = None) -> Brain:
- """Retrieves a Brain instance from the cache, or builds a new one."""
- key = (name, model)
+ def _get_brain(
+ self, name: str, model: str | None = None, *, scope: str | None = None
+ ) -> Brain:
+ """Retrieves a Brain instance from the cache, or builds a new one.
+
+ ``scope`` namespaces the cache entry (``"<name>@<scope>"``): a turn
+ under a ``TurnOverride`` gets its own instance, so its client — and
+ the credential that client resolved — is never the voice brain's.
+ """
+ key = (name if scope is None else f"{name}@{scope}", model)
if key in self._brain_cache:
return self._brain_cache[key]
@@ -3436,7 +3452,7 @@ class BrainManager:
tools_override: dict[str, Tool] | None = None,
max_turns: int | None = None,
deadline_s: float | None = None,
- reasoning_effort: Literal["none"] | None = None,
+ reasoning_effort: ReasoningEffort | None = None,
delegated_voice: bool = False,
tool_context: dict[str, Any] | None = None,
) -> BrainDispatcher:
@@ -3491,6 +3507,30 @@ class BrainManager:
**kwargs,
)
+ def _apply_turn_override_tools(
+ self, tools: dict[str, Tool] | None, override: TurnOverride
+ ) -> dict[str, Tool]:
+ """The turn's tool surface plus the override's extra hands, then its filter."""
+ base: dict[str, Tool] = dict(tools) if tools is not None else dict(self._tools)
+ base.update(override.tools_extra)
+ if override.tool_filter is not None:
+ base = override.tool_filter(base)
+ return base
+
+ @staticmethod
+ def _override_dispatch_kwargs(override: TurnOverride | None) -> dict[str, Any]:
+ """Dispatcher kwargs for a caller-picked turn; ``{}`` for a classic one."""
+ if override is None:
+ return {}
+ kwargs: dict[str, Any] = {}
+ if override.reasoning_effort is not None:
+ kwargs["reasoning_effort"] = override.reasoning_effort
+ if override.tool_context:
+ kwargs["tool_context"] = dict(override.tool_context)
+ if override.max_turns is not None:
+ kwargs["max_turns"] = override.max_turns
+ return kwargs
+
def _build_tool_ack_emitter(
self, user_text: str
) -> Callable[[str, dict[str, Any]], Awaitable[None]] | None:
@@ -4489,8 +4529,13 @@ class BrainManager:
providers[canonical] = BrainProviderConfig(**data)
# Drop cached instances for this provider so the new model is used; lift
- # any session-level deactivation (mirrors ``reactivate_provider``).
- for key in [k for k in self._brain_cache if k[0] == canonical]:
+ # any session-level deactivation (mirrors ``reactivate_provider``). The
+ # scoped instances of a per-turn override ("<name>@<scope>") go too.
+ for key in [
+ k
+ for k in self._brain_cache
+ if k[0] == canonical or str(k[0]).startswith(canonical + "@")
+ ]:
self._brain_cache.pop(key, None)
self._dead_providers.discard(canonical)
self._dead_provider_models = {
@@ -10100,12 +10145,15 @@ class BrainManager:
)
def _first_tool_capable_provider(
- self, level: str
+ self, level: str, *, exclude: str | None = None
) -> tuple[str, str | None] | None:
"""First AVAILABLE provider that can emit tool_calls — used to lead a
tool/action turn when the active talker cannot. deep_brain first, then a
stable cross-provider order. Returns (name, model) or None when no
- tool-capable provider is reachable (then the chain stays unchanged)."""
+ tool-capable provider is reachable (then the chain stays unchanged).
+ ``exclude`` names the talker being led (the active brain by default;
+ a per-turn pick under an override)."""
+ skip = exclude if exclude is not None else self._active_name
available = set(self._registry.available())
order: list[str] = []
db = self._config.brain.deep_brain
@@ -10114,7 +10162,7 @@ class BrainManager:
order += ["gemini", "claude-api", "openai", "openrouter", "grok", "nvidia"]
seen: set[str] = set()
for name in order:
- if name in seen or name == self._active_name or name not in available:
+ if name in seen or name == skip or name not in available:
continue
seen.add(name)
# Skip providers dead-listed or rate-limited THIS session — the
@@ -10156,6 +10204,38 @@ class BrainManager:
pass
return False
+ def _override_chain(
+ self, override: TurnOverride, level: str
+ ) -> list[tuple[str, str | None]]:
+ """The chain for a caller-picked turn: exactly the pick, no stand-in.
+
+ A person who chose a model in the chat gets that model or an honest
+ error — never a silent cross-provider fallback (the "wrong model used,
+ shown right" defect, anti-drift mandate 2026-06-29). The one thing kept
+ from the normal chain is the intelligent-router lead: when the pick
+ cannot emit tool_calls at all, a tool-capable provider leads the turn
+ and falls through to the pick for the answer, exactly as for a
+ tool-incapable voice brain (``_router_lead_key``).
+ """
+ pick: tuple[str, str | None] = (override.provider, override.model)
+ chain: list[tuple[str, str | None]] = [pick]
+ intelligent = bool(getattr(self._config.brain.routing, "intelligent_router", True))
+ if (
+ intelligent
+ and getattr(self, "_turn_substantive", False)
+ and not self._brain_can_call_tools(override.provider, override.model)
+ ):
+ helper = self._first_tool_capable_provider(level, exclude=override.provider)
+ if helper is not None:
+ log.info(
+ "Intelligent router: picked %s cannot call tools — %s leads this "
+ "turn and picks the tool (falls through to %s if none).",
+ override.provider, helper[0], override.provider,
+ )
+ self._router_lead_key = helper
+ chain.insert(0, helper)
+ return chain
+
def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
"""Returns a prioritised list of (provider, model) attempts."""
active = self._active_name
@@ -10165,6 +10245,10 @@ class BrainManager:
# intelligent-router lead.
self._router_lead_key: tuple[str, str | None] | None = None
+ override = _TURN_OVERRIDE.get()
+ if override is not None:
+ return self._override_chain(override, level)
+
# Capability-driven tool delegation (NOT a per-provider hardcode): the
# subscription-CLI brains (Codex over the ChatGPT login, Antigravity over
# the Google login) cannot emit tool_calls — can_call_tools() == False —
@@ -10311,6 +10395,7 @@ class BrainManager:
history_override: Iterable[BrainMessage] | None = None,
force_output_language: str | None = None,
consume_pending_voice_attachments: bool = False,
+ turn_override: TurnOverride | None = None,
) -> str:
"""Generate a turn, optionally leaving its public response event to the caller.
@@ -10320,11 +10405,15 @@ class BrainManager:
``history_override`` supplies caller-owned context for this turn without
mutating the manager's shared conversation buffer; combine it with
``use_history=False`` when the caller owns history persistence too.
+ ``turn_override`` runs the turn on a caller-picked provider / model /
+ effort with extra tools and tool context (the typed chat's pick) —
+ the live brain, its config and its dead-lists are left untouched.
"""
token = _PUBLISH_RESPONSE_EVENT.set(bool(publish_response))
history_token = _TURN_HISTORY_OVERRIDE.set(
tuple(history_override) if history_override is not None else None
)
+ override_token = _TURN_OVERRIDE.set(turn_override)
skill_state = _SkillTurnState(self)
skill_token = _SKILL_TURN_STATE.set(skill_state)
try:
@@ -10353,6 +10442,7 @@ class BrainManager:
self._skill_turn_source_fallback = skill_state.source
self._skill_injected_inline_fallback = skill_state.injected_inline
_SKILL_TURN_STATE.reset(skill_token)
+ _TURN_OVERRIDE.reset(override_token)
_TURN_HISTORY_OVERRIDE.reset(history_token)
_PUBLISH_RESPONSE_EVENT.reset(token)
@@ -10909,6 +10999,15 @@ class BrainManager:
", ".join(contextual_tool_names),
)
forced_spawn = None
+ elif (
+ _TURN_OVERRIDE.get() is not None
+ and not _TURN_OVERRIDE.get().allow_force_spawn # type: ignore[union-attr]
+ and not self._is_explicit_heavy_request(user_text)
+ ):
+ # A caller-picked turn (the typed chat) IS the worker in its folder:
+ # the heuristic must not hand its work to a background mission. An
+ # explicit "spawn an agent for this" still spawns.
+ forced_spawn = None
else:
forced_spawn = await self._force_spawn_worker(
user_text, trace_id=turn_trace_id, source_layer=source_layer,
@@ -11136,6 +11235,9 @@ class BrainManager:
return await self._provider_down_reply(trace_uuid, cause="missing_key")
history_override = _TURN_HISTORY_OVERRIDE.get()
+ # The typed chat's pick, if any: its own credential scope and no
+ # dead-listing — a chat key that fails must not silence the voice brain.
+ turn_override = _TURN_OVERRIDE.get()
history = (
list(history_override)
if history_override is not None
@@ -11307,14 +11409,16 @@ class BrainManager:
# Skip providers already marked dead in THIS turn.
# Example: gemini-fast fails with missing_key → gemini-deep would
# still be in the chain but would fail for the same reason. Skip
- # saves an avoidable subprocess/network call.
- if prov_name in self._dead_providers:
+ # saves an avoidable subprocess/network call. An overridden turn
+ # runs on its own credential scope, so the voice brain's dead-list
+ # is not its truth.
+ if turn_override is None and prov_name in self._dead_providers:
continue
# Model-scoped dead-list: this exact (provider, model) took a
# billing rejection earlier THIS turn but the provider itself
# was kept alive because another model was still untried — see
# `_dead_provider_models`.
- if (prov_name, model) in self._dead_provider_models:
+ if turn_override is None and (prov_name, model) in self._dead_provider_models:
continue
# Circuit breaker: skip rate-limited providers during cooldown
if not self._rate_tracker.is_available(prov_name, model):
@@ -11325,15 +11429,24 @@ class BrainManager:
continue
try:
- brain = self._get_brain(prov_name, model)
+ brain = self._get_brain(
+ prov_name,
+ model,
+ scope=turn_override.credential_scope if turn_override else None,
+ )
except Exception as exc: # noqa: BLE001
last_exc = exc
msg = str(exc)
kind = _classify_provider_error(msg, default="init_fail")
# On missing_key: remove provider from the chain for the rest
# of the session. Prevents each voice turn from running 8x
- # sequentially against the same missing keys.
- if kind in _DEAD_LIST_KINDS and prov_name not in self._dead_providers:
+ # sequentially against the same missing keys. Never for an
+ # overridden turn: its key is the chat's, not the voice's.
+ if (
+ turn_override is None
+ and kind in _DEAD_LIST_KINDS
+ and prov_name not in self._dead_providers
+ ):
self._dead_providers.add(prov_name)
if kind == "missing_key":
log.warning(
@@ -11494,6 +11607,13 @@ class BrainManager:
_turn_tools = self._hide_screenshot_for_blind_brain(
_turn_tools, brain, prov_name=prov_name, model=model
)
+ if turn_override is not None:
+ # The caller's extra hands (a chat's folder tools) join the
+ # surface AFTER every gate above, and a plan-mode filter runs
+ # last — the gates decide what Jarvis may reach for, the
+ # override only adds a folder and, in plan mode, takes the
+ # writing hands away.
+ _turn_tools = self._apply_turn_override_tools(_turn_tools, turn_override)
# Active-model self-awareness: stamp the provider/model that is about
# to answer so _build_system_prompt injects the correct, specific
# self-identity (anti-"I'm Gemini" hallucination, forensic 2026-06-20).
@@ -11517,7 +11637,7 @@ class BrainManager:
"delegated_voice": True,
}
if prefer_tool_model
- else {}
+ else self._override_dispatch_kwargs(turn_override)
)
disp = self._build_dispatcher(
brain, tools_override=_turn_tools, **_disp_kwargs
@@ -11693,6 +11813,9 @@ class BrainManager:
# die Voice-Session-DB.
tokens_in_total = int(agg.usage.get("input_tokens", 0)) if agg.usage else 0
tokens_out_total = int(agg.usage.get("output_tokens", 0)) if agg.usage else 0
+ # Every plugin reports cache hits under the protocol key and
+ # keeps ``input_tokens`` to the uncached share.
+ tokens_cached_total = int(agg.usage.get("cache_hit_tokens", 0)) if agg.usage else 0
cost_usd_total = 0.0
try:
from jarvis.brain.cost import (
@@ -11703,9 +11826,11 @@ class BrainManager:
# from the provider feed — ONE refresh per model per
# process (capped at 3 s), so a new generation stops
# shipping as "$0.00" until someone edits the table.
- if tokens_in_total > 0 or tokens_out_total > 0:
+ if tokens_in_total > 0 or tokens_out_total > 0 or tokens_cached_total > 0:
await ensure_pricing_for(model)
- cost_usd_total = calculate_cost_usd(model, tokens_in_total, tokens_out_total)
+ cost_usd_total = calculate_cost_usd(
+ model, tokens_in_total, tokens_out_total, tokens_cached_total
+ )
if cost_usd_total == 0.0 and tokens_in_total > 0:
# An unknown model prices as $0.00 and every surface
# then renders the turn as free — that silence is how
@@ -11733,10 +11858,20 @@ class BrainManager:
model=model,
tokens_in=tokens_in_total,
tokens_out=tokens_out_total,
+ tokens_cached=tokens_cached_total,
cost_usd=cost_usd_total,
text_len=len(response_text or ""),
finish_reason=str(getattr(agg, "finish_reason", "ok") or "ok"),
))
+ if turn_override is not None:
+ turn_override.receipt.record(
+ provider=prov_name,
+ model=model,
+ tokens_in=tokens_in_total,
+ tokens_out=tokens_out_total,
+ cost_usd=cost_usd_total,
+ finish_reason=str(getattr(agg, "finish_reason", "ok") or "ok"),
+ )
if idx > 0:
log.info(
@@ -11765,7 +11900,11 @@ class BrainManager:
(prov_name, model, "rate_limit", "HTTP 429"))
else:
log.warning("Brain %s(%s) fehlgeschlagen: %s", prov_name, model, exc)
- if kind in _DEAD_LIST_KINDS and prov_name not in self._dead_providers:
+ if (
+ turn_override is None
+ and kind in _DEAD_LIST_KINDS
+ and prov_name not in self._dead_providers
+ ):
# account_blocked (e.g. a bare 402) is model-scoped when
# the SAME provider still has an untried model later in
# this turn's chain (a capped paid model with a funded
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index a07260d441..f3a2bb0e56 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1449,6 +1449,11 @@ class BrainTurnStarted(Event):
class BrainTurnCompleted(Event):
tokens_in: int = 0
tokens_out: int = 0
+ #: Prompt tokens served from the vendor's cache, billed at a fraction of
+ #: the input rate. Kept apart from ``tokens_in`` (which is the UNCACHED
+ #: share) so the ledger can price a voice session honestly — one that
+ #: re-sends its whole context every turn is mostly cache hits.
+ tokens_cached: int = 0
cost_usd: float = 0.0
text_len: int = 0
finish_reason: str = ""
diff --git a/jarvis/costs/aggregate.py b/jarvis/costs/aggregate.py
index 5e4690caf7..44cbe68338 100644
--- a/jarvis/costs/aggregate.py
+++ b/jarvis/costs/aggregate.py
@@ -40,6 +40,39 @@ def bucket_ms_for(since_ms: int, until_ms: int) -> int:
return _HOUR_MS if (until_ms - since_ms) <= _HOURLY_RANGE_MS else _DAY_MS
+def day_key(ts_ms: int) -> str:
+ """The local calendar day a timestamp belongs to, as ``YYYY-MM-DD``.
+
+ Local, not UTC: a person asks "what did yesterday cost", and yesterday
+ ends when their clock says midnight, not when Greenwich agrees.
+ """
+ return datetime.fromtimestamp(max(0, ts_ms) / 1000).strftime("%Y-%m-%d")
+
+
+def day_bounds_ms(key: str) -> tuple[int, int]:
+ """``(start, end)`` in epoch ms for the local day :func:`day_key` named.
+
+ The end is the last millisecond OF that day, not the next midnight, so a
+ range built from it can never pull one call of the following day in.
+ """
+ start = datetime.strptime(key, "%Y-%m-%d")
+ end = start + timedelta(days=1)
+ return int(start.timestamp() * 1000), int(end.timestamp() * 1000) - 1
+
+
+def group_by_day(entries: list[CostEntry]) -> list[tuple[str, list[CostEntry]]]:
+ """Every line item filed under its local day, newest day first.
+
+ The section's daily report is built on this rather than on the time
+ series: a series bucket carries sums, and a day report needs the rows
+ themselves to break the day down by model, provider, area and session.
+ """
+ days: dict[str, list[CostEntry]] = defaultdict(list)
+ for entry in entries:
+ days[day_key(entry.ts_ms)].append(entry)
+ return sorted(days.items(), key=lambda kv: kv[0], reverse=True)
+
+
@dataclass(slots=True)
class Bucket:
"""Running totals for one group key."""
@@ -58,6 +91,9 @@ class Bucket:
#: model's row can say what it consumed when it has no tokens to show.
chars: int = 0
audio_ms: int = 0
+ #: Every price source seen in the bucket, so a $0.00 row can say whether
+ #: it is a local engine (free) or a vendor with no published rate (unknown).
+ price_sources: set[str] = field(default_factory=set)
#: Secondary dimension — which providers/models/roles fed this bucket.
members: dict[str, float] = field(default_factory=lambda: defaultdict(float))
@@ -73,6 +109,7 @@ class Bucket:
self.gap_tokens += entry.tokens_total
if entry.price_source == "subscription":
self.subscription_usd += entry.cost_usd
+ self.price_sources.add(entry.price_source)
self.last_ts_ms = max(self.last_ts_ms, entry.ts_ms)
if member:
self.members[member] += entry.cost_usd
@@ -92,6 +129,7 @@ class Bucket:
"subscription_usd": round(self.subscription_usd, 6),
"chars": self.chars,
"audio_ms": self.audio_ms,
+ "price_sources": sorted(self.price_sources),
"last_ts_ms": self.last_ts_ms,
"cost_share": round(self.cost_usd / total_cost, 6) if total_cost > 0 else 0.0,
"token_share": round(tokens / total_tokens, 6) if total_tokens > 0 else 0.0,
@@ -300,8 +338,9 @@ def _bucket(store: dict[str, Bucket], key: str) -> Bucket:
def _stamp(ts_ms: int, hourly: bool) -> str:
"""Local-time bucket key — the user reasons in their own day, not UTC."""
- dt = datetime.fromtimestamp(max(0, ts_ms) / 1000)
- return dt.strftime("%Y-%m-%dT%H:00") if hourly else dt.strftime("%Y-%m-%d")
+ if not hourly:
+ return day_key(ts_ms)
+ return datetime.fromtimestamp(max(0, ts_ms) / 1000).strftime("%Y-%m-%dT%H:00")
def _ranked(
@@ -311,7 +350,14 @@ def _ranked(
store.values(),
# Cost first; a bucket that spent nothing still ranks by the tokens it
# burned, which is what makes unpriced models visible at all.
- key=lambda b: (-b.cost_usd, -(b.tokens_in + b.tokens_out + b.tokens_cached)),
+ # Speech rows carry no tokens and are often free, so their volume
+ # (characters, audio) breaks the tie — or the busiest voice is the one
+ # the top-N cut drops.
+ key=lambda b: (
+ -b.cost_usd,
+ -(b.tokens_in + b.tokens_out + b.tokens_cached),
+ -(b.chars + b.audio_ms),
+ ),
)
return [b.to_dict(total_cost, total_tokens) for b in rows[:limit]]
diff --git a/jarvis/costs/cli_usage_index.py b/jarvis/costs/cli_usage_index.py
index d2f17be6b7..60421ca4af 100644
--- a/jarvis/costs/cli_usage_index.py
+++ b/jarvis/costs/cli_usage_index.py
@@ -121,7 +121,16 @@ AGENT_CODEX = "codex-cli"
AGENT_AGY = "agy-cli"
"""The agy CLI (both generations of its data root)."""
-AGENTS: tuple[str, ...] = (AGENT_CLAUDE, AGENT_CODEX, AGENT_AGY)
+AGENT_GROK = "grok-cli"
+"""Grok Build (``~/.grok``). ``sessions/<url-encoded cwd>/<uuid>/updates.jsonl``
+carries one ``turn_completed`` record per turn with a usage block that is
+per-turn (verified against three turn_started/turn_completed pairs) and
+follows the OpenAI convention — ``inputTokens`` INCLUDES ``cachedReadTokens``.
+``prompt_id`` identifies the turn wherever it is written. The model is the
+single key of ``usage.modelUsage``; cwd and session id come from the folder's
+``summary.json``. 608 MB of these were read by nothing until 2026-08-25."""
+
+AGENTS: tuple[str, ...] = (AGENT_CLAUDE, AGENT_CODEX, AGENT_AGY, AGENT_GROK)
#: Filename of the index, relative to the data dir.
DB_NAME = "cli_usage_index.db"
@@ -162,6 +171,7 @@ _AGY_KEY_MAP = {
_CLAUDE_MARK = b'"usage"'
_CODEX_MARKS = (b'"token_count"', b'"turn_context"', b'"session_meta"')
_AGY_MARK = b'"token_usage"'
+_GROK_MARK = b'"turn_completed"'
_LABEL_MAX = 90
_DB_TIMEOUT_S = 5.0
@@ -212,6 +222,7 @@ CREATE TABLE IF NOT EXISTS cli_turns (
PRIMARY KEY (agent, dedup_key)
);
CREATE INDEX IF NOT EXISTS idx_cli_turns_ts ON cli_turns (ts_ms);
+CREATE INDEX IF NOT EXISTS idx_cli_turns_session ON cli_turns (agent, session_id);
"""
# A duplicate is ignored except for one field: a row indexed without a model
@@ -423,28 +434,81 @@ class _Candidate:
mtime_ns: int
+def _account_roots(platform: str) -> list[Path]:
+ """Every extra login of a CLI the app manages (:mod:`jarvis.agent_accounts`).
+
+ A second subscription runs with its own config directory under the app's
+ data dir, and the CLI writes that account's transcripts THERE, not under
+ ``~/.claude``. Three such accounts held 724 session files nobody counted
+ (2026-08-25). The registry is optional here: the index must work on a
+ machine — or in a test — where it cannot be loaded.
+ """
+ try:
+ from jarvis import agent_accounts
+ except Exception as exc: # noqa: BLE001 — the index never needs the registry to run
+ log.debug("cli usage index: account registry unavailable (%s)", exc)
+ return []
+ roots: list[Path] = []
+ try:
+ if platform in agent_accounts.platforms():
+ roots.extend(
+ Path(account.config_dir)
+ for account in agent_accounts.list_accounts(platform) # type: ignore[arg-type]
+ if not account.builtin
+ )
+ except Exception as exc: # noqa: BLE001 — a broken store must not stop the scan
+ log.warning("cli usage index: could not list %s accounts (%s)", platform, exc)
+ # A deleted account keeps its directory unless the user asked to remove
+ # the files, and its spend was real. Every directory under the platform's
+ # accounts folder counts, registered or not.
+ try:
+ from jarvis.core.paths import user_data_dir
+
+ folder = user_data_dir() / "agent-accounts" / platform
+ if folder.is_dir():
+ roots.extend(p for p in folder.iterdir() if p.is_dir())
+ except Exception as exc: # noqa: BLE001 — same rule: the scan goes on
+ log.debug("cli usage index: accounts folder for %s unreadable (%s)", platform, exc)
+ return roots
+
+
+def _dedup_paths(paths: list[Path]) -> list[Path]:
+ seen: set[str] = set()
+ out: list[Path] = []
+ for path in paths:
+ key = _key_of(path)
+ if key not in seen:
+ seen.add(key)
+ out.append(path)
+ return out
+
+
def _claude_roots(home: Path | None) -> list[Path]:
- """Claude Code config dirs: the CLI's own override first, then the default."""
+ """Claude Code config dirs: the CLI's own override, the default, and every
+ managed account's directory."""
if home is not None:
return [home / ".claude"]
roots: list[Path] = []
override = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
if override:
roots.append(Path(override).expanduser())
- default = Path.home() / ".claude"
- if default not in roots:
- roots.append(default)
- return roots
+ roots.append(Path.home() / ".claude")
+ roots.extend(_account_roots("claude"))
+ return _dedup_paths(roots)
def _codex_roots(home: Path | None) -> list[Path]:
- """``CODEX_HOME`` when the CLI is pointed elsewhere, else the default."""
+ """``CODEX_HOME`` when the CLI is pointed elsewhere, the default, and every
+ managed account's directory."""
if home is not None:
return [home / ".codex"]
+ roots: list[Path] = []
override = os.environ.get("CODEX_HOME", "").strip()
if override:
- return [Path(override).expanduser()]
- return [Path.home() / ".codex"]
+ roots.append(Path(override).expanduser())
+ roots.append(Path.home() / ".codex")
+ roots.extend(_account_roots("codex"))
+ return _dedup_paths(roots)
def _agy_roots(home: Path | None) -> list[Path]:
@@ -453,6 +517,19 @@ def _agy_roots(home: Path | None) -> list[Path]:
return [base / ".kimi", base / ".kimi-code"]
+def _grok_roots(home: Path | None) -> list[Path]:
+ """``GROK_HOME`` when set, the default, and every managed account."""
+ if home is not None:
+ return [home / ".grok"]
+ roots: list[Path] = []
+ override = os.environ.get("GROK_HOME", "").strip()
+ if override:
+ roots.append(Path(override).expanduser())
+ roots.append(Path.home() / ".grok")
+ roots.extend(_account_roots("grok-build"))
+ return _dedup_paths(roots)
+
+
#: ``agent -> (root resolver, glob patterns relative to the root)``. Patterns
#: are explicit rather than ``rglob`` so discovery walks only the directories
#: that can hold transcripts.
@@ -465,6 +542,8 @@ _LAYOUTS: tuple[tuple[str, str], ...] = (
(AGENT_AGY, "sessions/*/*/wire.jsonl"),
# agy, current layout (``sessions/<wd_...>/<session>/agents/<name>/wire.jsonl``).
(AGENT_AGY, "sessions/*/*/agents/*/wire.jsonl"),
+ # Grok Build: one folder per session under a url-encoded cwd.
+ (AGENT_GROK, "sessions/*/*/updates.jsonl"),
)
@@ -473,6 +552,8 @@ def _roots_for(agent: str, home: Path | None) -> list[Path]:
return _claude_roots(home)
if agent == AGENT_CODEX:
return _codex_roots(home)
+ if agent == AGENT_GROK:
+ return _grok_roots(home)
return _agy_roots(home)
@@ -753,6 +834,66 @@ def _agy_row(
)
+def _grok_row(
+ record: Mapping[str, Any], offset: int, cand: _Candidate, cursor: _Cursor
+) -> _Row | None:
+ params = _payload(record, "params")
+ update = _payload(params, "update")
+ if update.get("sessionUpdate") != "turn_completed":
+ return None
+ usage = update.get("usage")
+ if not isinstance(usage, Mapping):
+ return None
+ cached = _int(usage.get("cachedReadTokens"))
+ tokens_in = max(0, _int(usage.get("inputTokens")) - cached) + _int(
+ usage.get("cacheCreationTokens")
+ )
+ tokens_out = _int(usage.get("outputTokens"))
+ if tokens_in + tokens_out + cached <= 0:
+ return None
+ model = cursor.model
+ per_model = usage.get("modelUsage")
+ if isinstance(per_model, Mapping) and per_model:
+ model = str(next(iter(per_model.keys())) or model)
+ session_id = str(params.get("sessionId") or cursor.session_id)
+ prompt_id = str(update.get("prompt_id") or "")
+ dedup = f"{session_id}:{prompt_id}" if session_id and prompt_id else f"{cand.key}:{offset}"
+ return (
+ cand.agent,
+ dedup,
+ cand.key,
+ session_id,
+ _epoch_ms(record.get("timestamp")),
+ model,
+ tokens_in,
+ tokens_out,
+ cached,
+ cursor.cwd,
+ cursor.label,
+ )
+
+
+def _grok_context(path: Path) -> tuple[str, str, str, str]:
+ """``(session_id, cwd, label, model)`` from the folder's ``summary.json``."""
+ folder = path.parent
+ session_id = folder.name
+ cwd = ""
+ model = ""
+ summary = folder / "summary.json"
+ try:
+ if summary.is_file():
+ parsed = json.loads(summary.read_text(encoding="utf-8", errors="replace"))
+ if isinstance(parsed, dict):
+ info = parsed.get("info") if isinstance(parsed.get("info"), dict) else {}
+ session_id = str(info.get("id") or session_id)
+ cwd = str(info.get("cwd") or "")
+ model = str(parsed.get("current_model_id") or "")
+ except (OSError, ValueError) as exc:
+ log.debug("cli usage index: %s unreadable (%s)", summary, exc)
+ label = _clip(Path(cwd).name if cwd else session_id)
+ return session_id, cwd, label, model
+
+
def _agy_session_dir(path: Path) -> Path:
"""The session folder of a ``wire.jsonl``, in either layout."""
if path.parent.parent.name == "agents":
@@ -806,6 +947,9 @@ def _scan(cand: _Candidate, start: int, cursor: _Cursor, deadline: float) -> _Fi
reader = _LineReader(None, start)
if cand.agent == AGENT_AGY and not cursor.session_id:
cursor.session_id, cursor.cwd, cursor.label = _agy_context(cand.path)
+ if cand.agent == AGENT_GROK and not cursor.session_id:
+ cursor.session_id, cursor.cwd, cursor.label, model = _grok_context(cand.path)
+ cursor.model = cursor.model or model
failed = False
try:
with cand.path.open("rb") as fh:
@@ -844,6 +988,8 @@ def _wanted(agent: str, raw: bytes) -> bool:
return _CLAUDE_MARK in raw
if agent == AGENT_CODEX:
return any(mark in raw for mark in _CODEX_MARKS)
+ if agent == AGENT_GROK:
+ return _GROK_MARK in raw
return _AGY_MARK in raw
@@ -854,6 +1000,8 @@ def _row_for(
return _claude_row(record, cand, cursor)
if agent == AGENT_CODEX:
return _codex_row(record, offset, cand, cursor)
+ if agent == AGENT_GROK:
+ return _grok_row(record, offset, cand, cursor)
return _agy_row(record, offset, cand, cursor)
@@ -938,6 +1086,60 @@ def _open_ro(path: Path) -> sqlite3.Connection | None:
return None
+def _backfill_models(conn: sqlite3.Connection, keys: list[str]) -> None:
+ """Give model-less rows of the files just scanned the model their session
+ recorded elsewhere.
+
+ A Codex fork replays its parent before its own ``turn_context``, so those
+ rows are inserted with no model, and the parent file — scanned later or
+ earlier — is where the model lives. Scoped to the scanned files so a
+ refresh never pays for the whole table (the unscoped sweep took 12 s on
+ 132k rows, 2026-08-25).
+ """
+ sql = (
+ "UPDATE cli_turns SET model = ("
+ " SELECT t2.model FROM cli_turns t2"
+ " WHERE t2.agent = cli_turns.agent AND t2.session_id = cli_turns.session_id"
+ " AND t2.model <> '' ORDER BY t2.ts_ms LIMIT 1)"
+ " WHERE model = '' AND session_id <> '' AND path = ? AND EXISTS ("
+ " SELECT 1 FROM cli_turns t3 WHERE t3.agent = cli_turns.agent"
+ " AND t3.session_id = cli_turns.session_id AND t3.model <> '')"
+ )
+ conn.executemany(sql, [(key,) for key in keys])
+
+
+def _prune_vanished(
+ conn: sqlite3.Connection,
+ candidates: list[_Candidate],
+ known: dict[str, sqlite3.Row],
+ home: Path | None,
+) -> None:
+ """Drop the rows of transcripts that no longer exist.
+
+ ``_drop_rows`` only fires when a file SHRANK; a deleted file kept its rows
+ forever (446 rows / 88M tokens from six vanished transcripts,
+ 2026-08-25). Pruning is limited to roots that are readable right now, so
+ an unmounted drive or a transient permission error never wipes history.
+ """
+ live: list[str] = []
+ for agent, _pattern in _LAYOUTS:
+ for root_dir in _roots_for(agent, home):
+ try:
+ if root_dir.is_dir():
+ live.append(_key_of(root_dir))
+ except OSError:
+ continue
+ if not live:
+ return
+ fresh = {c.key for c in candidates}
+ for key in list(known):
+ if key in fresh or not any(key.startswith(r) for r in live):
+ continue
+ _drop_rows(conn, key)
+ conn.execute("DELETE FROM indexed_files WHERE path = ?", (key,))
+ known.pop(key, None)
+
+
def _resume_rows(conn: sqlite3.Connection) -> dict[str, sqlite3.Row]:
try:
return {
@@ -994,8 +1196,10 @@ def refresh(
turns_added = 0
errors = 0
complete = True
+ scanned_keys: list[str] = []
try:
known = _resume_rows(conn)
+ _prune_vanished(conn, candidates, known, home)
pending = _pending(candidates, known, since_ms)
# Newest first: the file a user just closed is the one whose numbers
# they are looking at, and it is the one most likely to be small.
@@ -1012,6 +1216,7 @@ def refresh(
_drop_rows(conn, cand.key)
scan = _scan(cand, start, cursor, deadline)
scanned += 1
+ scanned_keys.append(cand.key)
bytes_read += scan.bytes_read
if scan.failed:
errors += 1
@@ -1020,6 +1225,8 @@ def refresh(
turns_added += _commit_file(conn, cand, scan)
if scan.reason == "deadline":
break
+ if scanned_keys:
+ _backfill_models(conn, scanned_keys)
except sqlite3.Error as exc:
log.warning("cli usage index: refresh aborted (%s)", exc)
errors += 1
@@ -1238,6 +1445,14 @@ def _commit_file(conn: sqlite3.Connection, cand: _Candidate, scan: _FileScan) ->
if scan.rows:
conn.executemany(_INSERT_TURN, scan.rows)
added = conn.total_changes - before
+ if scan.cursor.model:
+ # A replayed prefix lands before the file's ``turn_context``; the
+ # context that follows is authoritative for every row in the
+ # file (130 Codex rows / 16.4M tokens sat unpriced, 2026-08-25).
+ conn.execute(
+ "UPDATE cli_turns SET model = ? WHERE path = ? AND agent = ? AND model = ''",
+ (scan.cursor.model, cand.key, cand.agent),
+ )
conn.execute(
_UPSERT_FILE,
(
@@ -1269,6 +1484,7 @@ __all__ = [
"AGENT_AGY",
"AGENT_CLAUDE",
"AGENT_CODEX",
+ "AGENT_GROK",
"DB_NAME",
"CliRollup",
"CliTurn",
diff --git a/jarvis/costs/model.py b/jarvis/costs/model.py
index 0c78b5b150..b32d015f5b 100644
--- a/jarvis/costs/model.py
+++ b/jarvis/costs/model.py
@@ -80,6 +80,16 @@ SURFACES: tuple[str, ...] = (
SURFACE_JARVIS_VOICE,
)
+# Runners whose usage object follows the OpenAI convention: ``input_tokens``
+# INCLUDES the cached share, so the cached count is subtracted before pricing.
+# Anthropic-style runners report the two disjoint and need nothing.
+OPENAI_CONVENTION_RUNNERS: frozenset[str] = frozenset({"codex-cli"})
+
+# Mission workers name their CLI in ``WorkerSpawned`` with the bare vendor
+# word, not the ``-cli`` runner id the chat surface uses. Every one of these
+# runs on a monthly seat; the amount the worker reports is an API-equivalent.
+MISSION_SUBSCRIPTION_CLIS: frozenset[str] = frozenset({"claude", "codex", "agy", "gemini"})
+
PriceSource = Literal["recorded", "derived", "free", "unknown", "subscription"]
# Providers that run on the user's own hardware: 0.00 is the correct price,
@@ -216,8 +226,10 @@ def price_entry(
for a coding agent they are nine tenths of every bill.
"""
tokens = max(0, tokens_in) + max(0, tokens_out) + max(0, tokens_cached)
- if subscription and tokens > 0:
+ if subscription and (tokens > 0 or recorded_usd > 0):
if recorded_usd > 0:
+ # A seat that quotes its own API-equivalent (Claude Code does)
+ # is a subscription row even when it reports no token count.
return float(recorded_usd), "subscription"
# Lazy, like the branch below: a report of nothing but priced seats
# never has to load the catalogue.
@@ -238,8 +250,21 @@ def price_entry(
return 0.0, "recorded"
key = (provider or "").strip().casefold()
- if key in LOCAL_PROVIDERS or key in SUBSCRIPTION_PROVIDERS:
+ if key in LOCAL_PROVIDERS:
return 0.0, "free"
+ if key in SUBSCRIPTION_PROVIDERS:
+ # A seat is not free: the work is worth its API-equivalent and the
+ # label says a subscription covered it. "$0.00 free" for a paid seat
+ # was the one thing the maintainer asked never to see (2026-08-25).
+ return price_entry(
+ provider=provider,
+ model=model,
+ tokens_in=tokens_in,
+ tokens_out=tokens_out,
+ recorded_usd=recorded_usd,
+ subscription=True,
+ tokens_cached=tokens_cached,
+ )
if model.strip().casefold().endswith(":free"):
return 0.0, "free"
diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.py
index 2e3e425a50..600002f729 100644
--- a/jarvis/costs/sources.py
+++ b/jarvis/costs/sources.py
@@ -18,6 +18,8 @@ from dataclasses import dataclass
from pathlib import Path
from .model import (
+ MISSION_SUBSCRIPTION_CLIS,
+ OPENAI_CONVENTION_RUNNERS,
ROLE_AGENT,
ROLE_PIPELINE,
ROLE_REALTIME,
@@ -62,7 +64,13 @@ class CostSources:
cli_index_dir: Path | None = None
def existing(self) -> list[Path]:
- candidates = (self.sessions_db, self.missions_db, self.agent_chat_db)
+ candidates = [self.sessions_db, self.missions_db, self.agent_chat_db]
+ if self.cli_index_dir is not None:
+ # The index is a source like the others: a refresh that adds
+ # thousands of CLI turns must invalidate a cached report.
+ from .cli_usage_index import DB_NAME
+
+ candidates.append(self.cli_index_dir / DB_NAME)
return [p for p in candidates if p and p.exists()]
def newest_mtime(self) -> float:
@@ -204,6 +212,7 @@ def _voice_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[
model=str(payload.get("model") or ""),
tokens_in=_int(payload.get("tokens_in")),
tokens_out=_int(payload.get("tokens_out")),
+ tokens_cached=_int(payload.get("tokens_cached")),
recorded_usd=_float(payload.get("cost_usd")),
ref_id=str(row["session_id"] or ""),
label=_clip((turn or {}).get("user_text")),
@@ -255,6 +264,7 @@ def _voice_entry(
recorded_usd: float,
ref_id: str,
label: str,
+ tokens_cached: int = 0,
) -> CostEntry:
cost, source = price_entry(
provider=provider,
@@ -262,6 +272,7 @@ def _voice_entry(
tokens_in=tokens_in,
tokens_out=tokens_out,
recorded_usd=recorded_usd,
+ tokens_cached=tokens_cached,
)
return CostEntry(
ts_ms=ts_ms,
@@ -271,7 +282,7 @@ def _voice_entry(
model=model,
tokens_in=tokens_in,
tokens_out=tokens_out,
- tokens_cached=0,
+ tokens_cached=tokens_cached,
cost_usd=cost,
price_source=source,
ref_id=ref_id,
@@ -375,6 +386,12 @@ def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iter
continue
session = sessions.get(str(row["session_id"] or ""))
start = starts.get(str(payload.get("turn_id") or ""), {})
+ if start.get("runner", "") in OPENAI_CONVENTION_RUNNERS:
+ # Same asymmetry the CLI index documents: the OpenAI usage
+ # object counts cache hits INSIDE input_tokens. Summing both
+ # billed every cached token twice. Never applied to Claude or
+ # agy, which report the two disjoint.
+ tokens_in = max(0, tokens_in - tokens_cached)
session_provider = str(session["provider"] if session is not None else "")
provider = start.get("provider") or session_provider or "agent-cli"
model = start.get("model") or str(session["model"] if session is not None else "")
@@ -415,10 +432,17 @@ def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iter
def _mission_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:
"""Autonomous worker spend, per draft the worker delivered.
- ``WorkerDraftReady`` carries the worker's own ``tokens_used`` / ``cost_usd``.
- A worker driven by a subscription CLI reports zeros — that is the honest
- number (the seat is paid monthly), and it is labelled as such rather than
- left looking like missing data.
+ ``WorkerDraftReady`` carries the worker's own ``tokens_used`` / ``cost_usd``
+ and NOTHING about who did the work: the CLI and the model live on the
+ ``WorkerSpawned`` event of the same ``worker_id``, so the two are joined
+ here. Without the join every draft was a nameless "mission-worker" with
+ no rate (64 unpriced drafts, 2026-08-25), and a Claude Code seat's own
+ API-equivalent quote passed as money that moved.
+
+ ``tokens_used`` is not always tokens: the Claude worker reports its TURN
+ count there (1-31 per draft against a three-figure cost). A row whose
+ recorded cost could not possibly come from that many tokens is emitted
+ cost-only rather than writing a turn count into a token column.
"""
conn = _connect(path)
if conn is None:
@@ -430,6 +454,20 @@ def _mission_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterato
str(r["id"]): _clip(r["prompt"])
for r in conn.execute("SELECT id, prompt FROM missions")
}
+ spawned: dict[str, tuple[str, str]] = {}
+ for r in conn.execute(
+ "SELECT worker_id, payload_json FROM mission_events WHERE event_type = 'WorkerSpawned'"
+ ):
+ try:
+ meta = json.loads(r["payload_json"] or "{}")
+ except (TypeError, ValueError):
+ continue
+ if not isinstance(meta, dict):
+ continue
+ step = meta.get("step") if isinstance(meta.get("step"), dict) else {}
+ cli = str(meta.get("cli") or step.get("worker_cli") or "")
+ model = str(meta.get("model") or step.get("model") or "")
+ spawned[str(r["worker_id"] or "")] = (cli, model)
for row in conn.execute(
"SELECT mission_id, worker_id, ts_ms, payload_json FROM mission_events "
"WHERE event_type = 'WorkerDraftReady' AND ts_ms BETWEEN ? AND ?",
@@ -446,14 +484,20 @@ def _mission_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterato
recorded = _float(payload.get("cost_usd"))
if tokens <= 0 and recorded <= 0:
continue
- provider = str(payload.get("provider") or "mission-worker")
- model = str(payload.get("model") or "")
+ cli, spawned_model = spawned.get(str(row["worker_id"] or ""), ("", ""))
+ provider = str(payload.get("provider") or (f"{cli}-cli" if cli else "mission-worker"))
+ model = str(payload.get("model") or spawned_model)
+ # A turn count masquerading as tokens: no model call costs more
+ # than a cent per token. Keep the money, drop the fake quantity.
+ if recorded > 0 and tokens > 0 and recorded / tokens > 0.01:
+ tokens = 0
cost, source = price_entry(
provider=provider,
model=model,
tokens_in=tokens,
tokens_out=0,
recorded_usd=recorded,
+ subscription=cli in MISSION_SUBSCRIPTION_CLIS,
)
mission_id = str(row["mission_id"] or "")
yield CostEntry(
diff --git a/jarvis/costs/speech_rates.py b/jarvis/costs/speech_rates.py
index 9184644137..9c860de4f3 100644
--- a/jarvis/costs/speech_rates.py
+++ b/jarvis/costs/speech_rates.py
@@ -42,6 +42,7 @@ LOCAL_SPEECH_PROVIDERS: frozenset[str] = frozenset(
"faster-whisper", # jarvis/plugins/stt/fwhisper.py
"nemotron-local", # jarvis/plugins/stt/nemotron_local.py
"piper-local", # jarvis/plugins/tts/piper_local.py
+ "sapi5", # jarvis/plugins/tts/inworld_tts.py — Windows emergency voice
}
)
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index 4f2e885e8e..08d943ab69 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -452,14 +452,20 @@ async def _stream_via_responses(
elif etype in ("response.completed", "response.incomplete"):
usage = getattr(getattr(event, "response", None), "usage", None)
if usage is not None:
+ details = getattr(usage, "input_tokens_details", None)
+ cached = int(getattr(details, "cached_tokens", 0) or 0)
usage_payload = {
- "input_tokens": int(getattr(usage, "input_tokens", 0) or 0),
+ # The canonical cost contract (gemini.py does the same):
+ # ``input_tokens`` is the UNCACHED share. OpenAI counts
+ # cache hits inside its input figure; leaving them there
+ # billed every hit at the full rate (2026-08-25).
+ "input_tokens": max(
+ int(getattr(usage, "input_tokens", 0) or 0) - cached, 0
+ ),
"output_tokens": int(
getattr(usage, "output_tokens", 0) or 0
),
}
- details = getattr(usage, "input_tokens_details", None)
- cached = int(getattr(details, "cached_tokens", 0) or 0)
if cached > 0:
usage_payload["cache_hit_tokens"] = cached
elif etype in ("response.failed", "error"):
@@ -645,16 +651,18 @@ async def stream_complete(
# Usage info (OpenAI delivers this in the last chunk)
usage = getattr(chunk, "usage", None)
if usage is not None:
- usage_payload = {
- "input_tokens": int(getattr(usage, "prompt_tokens", 0) or 0),
- "output_tokens": int(getattr(usage, "completion_tokens", 0) or 0),
- }
# Cache hits were invisible on this path (2026-07-28 cost audit:
# 84% of tool-loop tokens ran through OpenAI-protocol gateways) —
# without the protocol's cache_hit_tokens key nobody can measure
# whether a prompt-cache change works or what a turn really cost.
details = getattr(usage, "prompt_tokens_details", None)
cached = int(getattr(details, "cached_tokens", 0) or 0)
+ usage_payload = {
+ # ``prompt_tokens`` INCLUDES the cached share; the contract
+ # wants the uncached one (see the Responses path above).
+ "input_tokens": max(int(getattr(usage, "prompt_tokens", 0) or 0) - cached, 0),
+ "output_tokens": int(getattr(usage, "completion_tokens", 0) or 0),
+ }
if cached > 0:
usage_payload["cache_hit_tokens"] = cached
yield BrainDelta(usage=usage_payload)
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index bd04be4039..9c73679e56 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -1158,6 +1158,7 @@ def _payload_for(event: Event) -> dict[str, Any]:
"model",
"intent_level",
"tokens_in",
+ "tokens_cached",
"tokens_out",
"cost_usd",
# SpeechUsageRecorded: speech bills by audio second and by character,
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 4f2306062a..2f8bcd8823 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -3189,7 +3189,11 @@ class SpeechPipeline:
return False
previous = getattr(self, "_utterance_stt", None)
- self._utterance_stt = rebuilt
+ # Re-wrapped like ``set_tts`` does, or hearing spend would stop being
+ # recorded the first time someone changed the STT provider.
+ self._utterance_stt = meter_stt(
+ rebuilt, getattr(self, "_speech_spend", None), trace_id=self._speech_trace
+ )
# A lightweight/cloud-first pipeline has no local preview recognizer,
# so its preview must follow the selected provider. A heavy wake path
# keeps its dedicated local probe.
@@ -3259,7 +3263,10 @@ class SpeechPipeline:
log.debug("STT dictionary wrapper unavailable on live switch: %s", exc)
previous = self._utterance_stt
- self._utterance_stt = rebuilt
+ # Same rule as ``set_stt_provider``: the meter wraps the new instance.
+ self._utterance_stt = meter_stt(
+ rebuilt, getattr(self, "_speech_spend", None), trace_id=self._speech_trace
+ )
# The preview probe follows only when it was the SAME object — in the
# local-Whisper path it is the wake model, which must keep its own
# language (AP-27: the wake never rides on the utterance setting).
@@ -8362,6 +8369,12 @@ class SpeechPipeline:
)
except Exception: # noqa: BLE001 — teardown must never crash
log.debug("Workspace brief teardown failed", exc_info=True)
+ # Whatever was spoken after the last utterance (the goodbye, a
+ # late announcement) is settled BEFORE the session closes, or
+ # the recorder has no open session to file it under.
+ spend = getattr(self, "_speech_spend", None)
+ if spend is not None:
+ spend.flush()
await self._publish_event(
VoiceSessionEnded(
source_layer="speech.pipeline",
@@ -10521,6 +10534,11 @@ class SpeechPipeline:
except Exception as exc: # noqa: BLE001 — corrections are not load-bearing
log.warning("STT dictionary wrapper unavailable for dictation: %s", exc)
+ # Dictation transcribes minute-long buffers; unmetered it was the
+ # largest invisible hearing cost on a pipeline box.
+ instance = meter_stt(
+ instance, getattr(self, "_speech_spend", None), trace_id=self._speech_trace
+ )
self._dictation_stt_instance = instance
return instance
@@ -16438,6 +16456,13 @@ class SpeechPipeline:
built = build_realtime_surface_tts(self._config, key)
except Exception: # noqa: BLE001 — the emergency voice must never break the turn
built = None
+ if built is not None:
+ # Every readback and announcement spoken DURING a realtime call
+ # goes through this voice; on a realtime-first box that is nearly
+ # all of the TTS spend, and it was the one voice nobody metered.
+ built = meter_tts(
+ built, getattr(self, "_speech_spend", None), trace_id=self._speech_trace
+ )
self._realtime_surface_tts_cache = (key, built)
return built
diff --git a/jarvis/speech/usage_sink.py b/jarvis/speech/usage_sink.py
index 58ecc45335..e3204610a4 100644
--- a/jarvis/speech/usage_sink.py
+++ b/jarvis/speech/usage_sink.py
@@ -49,18 +49,32 @@ class SpeechSpendRecorder:
a turn that ended in a way that never reached it.
"""
+ #: A bucket older than this when the next call arrives belongs to an
+ #: earlier moment — an announcement spoken between turns, a readback
+ #: during a realtime call — and is settled on its own rather than folded
+ #: into whatever turn happens to end next.
+ IDLE_FLUSH_S = 20.0
+
def __init__(self, bus: Any | None) -> None:
"""``bus`` is anything with an awaitable ``publish`` — typed loosely so
this module never drags the bus implementation onto the import path."""
self._bus = bus
self._trace = ""
self._buckets: dict[tuple[str, str, str], _Bucket] = {}
+ self._last_record_s = 0.0
# -- UsageSink ---------------------------------------------------------
def record(self, usage: SpeechUsage) -> None:
"""Take one metered call. Must not block and must not raise."""
try:
+ now_s = time.monotonic()
+ if self._buckets and now_s - self._last_record_s > self.IDLE_FLUSH_S:
+ # Out-of-turn speech has no turn boundary to flush it; time is
+ # the boundary then. Realtime calls speak all their readbacks
+ # this way (trace_id is "" outside the classic pipeline).
+ self.flush()
+ self._last_record_s = now_s
if usage.trace_id and usage.trace_id != self._trace:
# A new turn began without anyone flushing the last one.
self.flush()
diff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.py
index 07742be815..021388cdc3 100644
--- a/jarvis/ui/web/costs_routes.py
+++ b/jarvis/ui/web/costs_routes.py
@@ -3,6 +3,7 @@
Endpoints::
GET /api/costs/summary Totals + every breakdown for a time range
+ GET /api/costs/daily One row per calendar day — the section's ledger
GET /api/costs/entries The individual line items behind those totals
GET /api/costs/pricing The rate card each seen model was priced with
@@ -30,7 +31,7 @@ from fastapi import APIRouter, Query, Request
from pydantic import BaseModel, Field
from jarvis.costs import CostEntry, CostSources, build_report, collect_entries, default_sources
-from jarvis.costs.aggregate import bucket_ms_for, filter_entries
+from jarvis.costs.aggregate import bucket_ms_for, day_bounds_ms, filter_entries, group_by_day
from jarvis.costs.model import ROLES, SURFACES
log = logging.getLogger(__name__)
@@ -62,6 +63,8 @@ class Bucket(BaseModel):
chars: int = 0
"""Characters synthesised — only speech rows carry these two."""
audio_ms: int = 0
+ price_sources: list[str] = Field(default_factory=list)
+ """How the bucket's rows were priced (free / derived / unknown / …)."""
last_ts_ms: int
cost_share: float
token_share: float
@@ -141,6 +144,31 @@ class CostSummary(BaseModel):
"""Which stores actually existed — an empty section is explainable."""
+class DayRow(BaseModel):
+ """One calendar day of spend, already broken down.
+
+ The section shows ONE of these per day rather than one row per session:
+ a session row carries the timestamp of its FIRST call, so a long morning
+ run sorts below a short one started later and the day's real work reads
+ as if it never happened. A day has no such ambiguity.
+ """
+
+ date: str
+ """Local ``YYYY-MM-DD`` — the day as the person's own clock drew it."""
+ since_ms: int
+ until_ms: int
+ totals: Totals
+ by_model: list[Bucket]
+ by_provider: list[Bucket]
+ by_role: list[Bucket]
+ by_surface: list[Bucket]
+
+
+class DailyLedger(BaseModel):
+ days: list[DayRow]
+ currency: Currency
+
+
class EntryRow(BaseModel):
ts_ms: int
surface: str
@@ -402,6 +430,78 @@ async def get_summary(
return CostSummary.model_validate(payload)
+# How many rows a day keeps of each dimension. A day is read at a glance —
+# the models are what people scan (which one did the work), so it keeps more
+# of them; providers and areas are a handful anyway.
+_DAY_TOP_MODELS = 12
+_DAY_TOP_PROVIDERS = 8
+
+
[email protected]("/daily", response_model=DailyLedger, summary="One row per calendar day")
+async def get_daily(
+ request: Request,
+ days: Annotated[int, Query(ge=0, le=3650)] = 30,
+ since_ms: Annotated[int | None, Query(ge=0)] = None,
+ until_ms: Annotated[int | None, Query(ge=0)] = None,
+ provider: Annotated[list[str] | None, Query()] = None,
+ model: Annotated[list[str] | None, Query()] = None,
+ role: Annotated[list[str] | None, Query()] = None,
+ surface: Annotated[list[str] | None, Query()] = None,
+ ref: Annotated[list[str] | None, Query()] = None,
+ search: str = "",
+) -> DailyLedger:
+ """The daily ledger: one entry per day, newest first.
+
+ Every source feeds it — an API-billed voice turn, a mission worker and a
+ coding CLI on a monthly seat all land in the same day. Nothing here is
+ vendor-specific: the day names whichever models it actually saw.
+
+ The per-day breakdowns come from :func:`build_report` over that day's own
+ rows, so a day's numbers are computed exactly the way the section's
+ headline numbers are and cannot drift from them.
+ """
+ sources = _sources(request)
+ start, end = _range(days, since_ms, until_ms)
+ entries = filter_entries(
+ _cache.get(sources, start, end),
+ providers=_split(provider),
+ models=_split(model),
+ roles=_split(role),
+ surfaces=_split(surface),
+ refs=_split(ref),
+ search=search,
+ )
+ rows: list[DayRow] = []
+ for key, day_entries in group_by_day(entries):
+ day_start, day_end = day_bounds_ms(key)
+ # ``build_report`` reads first/last from the ends of the list, and the
+ # collector concatenates one source after another rather than merging
+ # them, so a day has to be put in order before it can say when it
+ # started and when it stopped.
+ day_entries.sort(key=lambda e: e.ts_ms)
+ report = build_report(
+ day_entries,
+ since_ms=day_start,
+ until_ms=day_end,
+ top_n=_DAY_TOP_MODELS,
+ )
+ rows.append(
+ DayRow(
+ date=key,
+ since_ms=day_start,
+ until_ms=day_end,
+ totals=Totals.model_validate(report.totals),
+ by_model=[Bucket.model_validate(b) for b in report.by_model],
+ by_provider=[
+ Bucket.model_validate(b) for b in report.by_provider[:_DAY_TOP_PROVIDERS]
+ ],
+ by_role=[Bucket.model_validate(b) for b in report.by_role],
+ by_surface=[Bucket.model_validate(b) for b in report.by_surface],
+ )
+ )
+ return DailyLedger(days=rows, currency=_currency())
+
+
@router.get("/entries", response_model=EntriesPage, summary="Individual spend line items")
async def get_entries(
request: Request,
@@ -460,7 +560,12 @@ async def get_pricing(
sources = _sources(request)
start, end = _range(days, None, None)
- seen = {e.model for e in _cache.get(sources, start, end) if e.model}
+ # A row without a model id is exactly what makes gap_tokens non-zero,
+ # so it is listed by its provider rather than silently dropped.
+ seen = {
+ e.model or f"({e.provider} — no model recorded)"
+ for e in _cache.get(sources, start, end)
+ }
rows: list[RateRow] = []
for name in sorted(seen):
rates = resolve_rates(name)
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
index c57b14db59..996515f591 100644
--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
@@ -56,6 +56,8 @@ export interface CostBucket {
/** Speech only: characters spoken and audio heard. Zero on token rows. */
chars: number;
audio_ms: number;
+ /** Every price source seen in the bucket: free, derived, recorded, unknown, subscription. */
+ price_sources: string[];
last_ts_ms: number;
cost_share: number;
token_share: number;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index e662f8ba4f..360fab0a9c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5381,6 +5381,11 @@
"col_share": "Anteil",
"col_cost": "Kosten",
"col_calls": "Aufrufe",
+ "speech_area_note": "Hören und Sprechen werden in Audiosekunden und Zeichen abgerechnet — nie in Tokens. Ein Sprache-zu-Sprache-Modell hat kein eigenes Ohr und keinen eigenen Mund; seine Turns stehen unter {name} → Realtime-Stimme. Eine Zeile mit 0,00 $ ist entweder eine lokale Engine (kostenlos) oder ein Anbieter ohne veröffentlichten Tarif — die Spalte „Tarif“ sagt, was zutrifft.",
+ "col_rate": "Tarif",
+ "stat_total_hint_seat_only": "API-Gegenwert — vollständig durch Abos gedeckt, nichts über einen Key abgerechnet",
+ "empty_filtered": "In diesem Bereich passt mit den aktiven Filtern nichts.",
+ "empty_filtered_action": "Bereich behalten, Filter entfernen",
"speech_models_title": "Sprachmodelle",
"speech_models_subtitle": "Was jedes Ohr und jeder Mund verbraucht hat, zum On-Demand-API-Preis des Anbieters — als würde jeder Aufruf einzeln abgerechnet.",
"speech_models_empty": "In diesem Zeitraum lief kein Sprachmodell. Sprache-zu-Sprache-Modelle haben kein eigenes Ohr und keinen eigenen Mund und tauchen hier nie auf.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index f3e37e3879..42f5ada626 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5381,6 +5381,11 @@
"col_share": "Share",
"col_cost": "Cost",
"col_calls": "Calls",
+ "speech_area_note": "Hearing and speaking are billed in audio seconds and characters — never tokens. A speech-to-speech model has no separate ear or mouth, so its turns sit under {name} → Realtime voice. A row at $0.00 is either a local engine (free) or a vendor that publishes no rate — the Rate column says which.",
+ "col_rate": "Rate",
+ "stat_total_hint_seat_only": "API-equivalent — fully covered by subscriptions, nothing billed to a key",
+ "empty_filtered": "Nothing matches inside this area with the filters that are on.",
+ "empty_filtered_action": "Keep the area, drop the filters",
"speech_models_title": "Speech models",
"speech_models_subtitle": "What each ear and mouth consumed, priced at the vendor's on-demand API rate — as if every call were billed on its own.",
"speech_models_empty": "No speech model has run in this period. Speech-to-speech models have no separate ear or mouth and never appear here.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index e7ff24fcc9..7d83ae3b6a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5379,6 +5379,11 @@
"col_share": "Parte",
"col_cost": "Coste",
"col_calls": "Llamadas",
+ "speech_area_note": "Escuchar y hablar se facturan en segundos de audio y caracteres — nunca en tokens. Un modelo voz a voz no tiene oído ni boca propios; sus turnos están en {name} → Voz en tiempo real. Una fila a $0,00 es un motor local (gratis) o un proveedor sin tarifa publicada — la columna «Tarifa» lo indica.",
+ "col_rate": "Tarifa",
+ "stat_total_hint_seat_only": "Equivalente API — cubierto por completo por suscripciones, nada facturado a una clave",
+ "empty_filtered": "Nada coincide en esta área con los filtros activos.",
+ "empty_filtered_action": "Mantener el área, quitar los filtros",
"speech_models_title": "Modelos de voz",
"speech_models_subtitle": "Lo que consumió cada oído y cada boca, al precio de API bajo demanda del proveedor — como si cada llamada se facturara por separado.",
"speech_models_empty": "Ningún modelo de voz se ejecutó en este periodo. Los modelos voz a voz no tienen oído ni boca propios y nunca aparecen aquí.",
diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsx
index 31aee7eba2..a81d177ef0 100644
--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx
@@ -147,10 +147,20 @@ export function CostsView() {
const group = SURFACE_GROUPS.find((g) => g.id === id);
if (!group) return;
setVisible(ENTRY_PAGE);
- // Roles are cleared with the area: "pipeline brain" means nothing once you
- // are looking at the speech layer, and a stale role filter would silently
- // empty the new area.
- setFilters((f) => ({ ...f, surfaces: [...group.surfaces], roles: [] }));
+ // Every row-level filter is cleared with the area, not just roles: a
+ // provider picked inside Agentic IDE ("claude-cli") carried over to the
+ // assistant's area, where no row can ever match it, and the tab showed
+ // "0 calls" as if nothing had been spent (maintainer, 2026-08-25). An
+ // area switch is a fresh question; only the time range and the search
+ // box survive it.
+ setFilters((f) => ({
+ ...f,
+ surfaces: [...group.surfaces],
+ roles: [],
+ providers: [],
+ models: [],
+ refs: [],
+ }));
};
const topSpender = data?.by_provider[0];
@@ -266,6 +276,33 @@ export function CostsView() {
<EmptyRow>{t("costs_view.load_error")}</EmptyRow>
) : null}
+ {/*
+ An empty report under a row filter is indistinguishable from
+ "nothing was spent" — the tab looked broken for a day because a
+ provider picked in another area was still on (2026-08-25). Name
+ the cause and offer the one click that fixes it.
+ */}
+ {data &&
+ !summary.isLoading &&
+ (totals?.entries ?? 0) === 0 &&
+ (filters.providers.length > 0 ||
+ filters.models.length > 0 ||
+ filters.roles.length > 0 ||
+ filters.refs.length > 0) ? (
+ <EmptyRow>
+ <span>{t("costs_view.empty_filtered")}</span>{" "}
+ <button
+ type="button"
+ className="underline underline-offset-2 hover:text-foreground"
+ onClick={() =>
+ setFilters((f) => ({ ...f, providers: [], models: [], roles: [], refs: [] }))
+ }
+ >
+ {t("costs_view.empty_filtered_action")}
+ </button>
+ </EmptyRow>
+ ) : null}
+
{/* ---------------------------------------------------------------
Headline numbers. Cost and tokens sit side by side on purpose:
the cheapest provider is often the loudest token consumer, and
@@ -273,24 +310,26 @@ export function CostsView() {
--------------------------------------------------------------- */}
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{/*
- Money that actually left the account. A monthly seat can be worth
- orders of magnitude more than the metered spend beside it — the
- coding CLIs alone run to four figures a month at API rates — so
- adding the two into one headline would read as a bill nobody got.
- The seat's worth is named on the line below instead, which is the
- answer to a different question and deserves its own words.
+ Everything the work was worth at API list price — metered calls
+ AND the seat-covered ones. Showing only the metered part put
+ "$18" over a table that summed to six thousand and read as a lie
+ (maintainer, 2026-08-25). The split — what an API key was billed
+ vs. what a subscription covered — is the line below, which is the
+ answer to "did money leave the account".
*/}
<StatTile
icon={<Coins className="h-4 w-4" />}
label={t("costs_view.stat_total")}
- value={money(billed)}
+ value={money(totals?.cost_usd ?? 0)}
hint={
- seat > 0
- ? fill(t("costs_view.stat_total_hint_seat"), {
- perDay: money(perDay),
- seat: money(seat),
- })
- : fill(t("costs_view.stat_total_hint"), { perDay: money(perDay) })
+ seat > 0 && billed <= 0
+ ? t("costs_view.stat_total_hint_seat_only")
+ : seat > 0
+ ? fill(t("costs_view.stat_total_hint_seat"), {
+ billed: money(billed),
+ seat: money(seat),
+ })
+ : fill(t("costs_view.stat_total_hint"), { perDay: money(perDay) })
}
loading={summary.isLoading}
/>
@@ -427,6 +466,9 @@ export function CostsView() {
{area?.id === "jarvis-voice" ? (
<Panel>
<div className="px-4 pt-4">
+ <p className="mb-3 text-xs leading-relaxed text-muted-foreground">
+ {t("costs_view.speech_area_note")}
+ </p>
<PanelHeader
title={t("costs_view.speech_models_title")}
subtitle={t("costs_view.speech_models_subtitle")}
@@ -926,6 +968,7 @@ function SpeechModelsTable({
{ id: "spoken", label: t("costs_view.col_spoken"), width: "110px", align: "right" },
{ id: "cost", label: t("costs_view.col_api_cost"), width: "110px", align: "right" },
{ id: "per_call", label: t("costs_view.col_per_call"), width: "110px", align: "right" },
+ { id: "rate", label: t("costs_view.col_rate"), width: "110px", align: "right" },
];
if (!loading && rows.length === 0) {
@@ -972,6 +1015,18 @@ function SpeechModelsTable({
<Cell align="right" muted>
<span className="tabular-nums">{money(perCall)}</span>
</Cell>
+ <Cell align="right" muted>
+ {/* "$0.00" means two different things; the worst case is named. */}
+ <span>
+ {t(
+ priceSourceLabelKey(
+ row.price_sources.includes("unknown")
+ ? "unknown"
+ : (row.price_sources[0] ?? "recorded"),
+ ),
+ )}
+ </span>
+ </Cell>
</TableRow>
);
})}
diff --git a/tests/unit/costs/test_cli_usage_index.py b/tests/unit/costs/test_cli_usage_index.py
index 52c8d60bd6..94dfff5aeb 100644
--- a/tests/unit/costs/test_cli_usage_index.py
+++ b/tests/unit/costs/test_cli_usage_index.py
@@ -497,9 +497,9 @@ def test_codex_fork_replays_its_parent_but_is_counted_once(tmp_path: Path) -> No
# Two real calls in the parent, one new call in the fork. Not five.
assert len(turns) == 3
assert {t.session_id for t in turns} == {parent}
- # The replayed rows had no model; the parent's copy supplied it.
- assert sum(1 for t in turns if t.model == "gpt-5.6-terra") == 2
- assert sum(1 for t in turns if t.model == "") == 1
+ # The replayed rows had no model; the parent's copy supplied it — and the
+ # fork's own new turn inherits the session's model as well.
+ assert {t.model for t in turns} == {"gpt-5.6-terra"}
def test_an_index_built_under_an_older_rule_is_rebuilt(tmp_path: Path) -> None:
@@ -827,3 +827,169 @@ def test_rollup_totals_match_the_raw_turns(tmp_path: Path) -> None:
def test_rollup_of_an_absent_index_is_empty(tmp_path: Path) -> None:
"""A machine that has never indexed returns nothing, not an error."""
assert _rolled(tmp_path / "nothing") == []
+
+
+# ---------------------------------------------------------------------------
+# Grok Build
+# ---------------------------------------------------------------------------
+
+
+def _grok_update_line(
+ *,
+ session: str,
+ prompt_id: str,
+ ts: int = 1_786_719_765,
+ input_tokens: int = 1_000,
+ cached: int = 900,
+ output: int = 50,
+ model: str = "grok-4.6-build",
+) -> str:
+ usage = {
+ "inputTokens": input_tokens,
+ "outputTokens": output,
+ "cachedReadTokens": cached,
+ "cacheCreationTokens": 0,
+ "reasoningTokens": 10,
+ "modelCalls": 3,
+ "modelUsage": {model: {"inputTokens": input_tokens}},
+ }
+ return json.dumps(
+ {
+ "timestamp": ts,
+ "method": "_x.ai/session/update",
+ "params": {
+ "sessionId": session,
+ "update": {
+ "sessionUpdate": "turn_completed",
+ "prompt_id": prompt_id,
+ "usage": usage,
+ },
+ },
+ }
+ )
+
+
+def _grok_session(home: Path, session: str, cwd: str = "/work/grok-app") -> Path:
+ folder = home / ".grok" / "sessions" / "C%3A%5Cwork%5Cgrok-app" / session
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "summary.json").write_text(
+ json.dumps({"info": {"id": session, "cwd": cwd}, "current_model_id": "grok-4.6"}),
+ encoding="utf-8",
+ )
+ return folder / "updates.jsonl"
+
+
+def test_grok_turn_completed_is_one_row_per_turn(tmp_path: Path) -> None:
+ """Per-turn usage; ``inputTokens`` includes the cached share (OpenAI style)."""
+ from jarvis.costs.cli_usage_index import AGENT_GROK
+
+ data = tmp_path / "data"
+ session = "01a000c5-0f40-7652-9519-acd71f097d48"
+ _write(
+ _grok_session(tmp_path, session),
+ [
+ json.dumps({"timestamp": 1, "method": "_x.ai/session/update",
+ "params": {
+ "sessionId": session,
+ "update": {"sessionUpdate": "turn_started"},
+ }}),
+ _grok_update_line(session=session, prompt_id="p-1"),
+ _grok_update_line(session=session, prompt_id="p-2", input_tokens=500, cached=0),
+ ],
+ )
+
+ refresh(data_dir=data, home=tmp_path)
+
+ turns = _all(data)
+ assert len(turns) == 2
+ assert {t.agent for t in turns} == {AGENT_GROK}
+ assert sorted(t.tokens_in for t in turns) == [100, 500]
+ assert sorted(t.tokens_cached for t in turns) == [0, 900]
+ assert {t.model for t in turns} == {"grok-4.6-build"}
+ assert {t.session_id for t in turns} == {session}
+ assert {t.cwd for t in turns} == {"/work/grok-app"}
+ assert {t.label for t in turns} == {"grok-app"}
+
+
+def test_grok_replayed_turn_counts_once(tmp_path: Path) -> None:
+ """The same prompt_id written twice (a resumed session) is one turn."""
+ data = tmp_path / "data"
+ session = "01a000c5-0f40-7652-9519-acd71f097d48"
+ _write(
+ _grok_session(tmp_path, session),
+ [_grok_update_line(session=session, prompt_id="p-1"),
+ _grok_update_line(session=session, prompt_id="p-1", ts=1_786_719_999)],
+ )
+
+ refresh(data_dir=data, home=tmp_path)
+
+ assert len(_all(data)) == 1
+
+
+# ---------------------------------------------------------------------------
+# Housekeeping: vanished transcripts, model backfill
+# ---------------------------------------------------------------------------
+
+
+def test_a_transcript_that_disappeared_loses_its_rows(tmp_path: Path) -> None:
+ import sqlite3
+
+ from jarvis.costs.cli_usage_index import index_db_path
+
+ data = tmp_path / "data"
+ session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
+ path = _codex_path(tmp_path, session)
+ _write(path, [*_codex_prelude(session), _codex_token_line()])
+ refresh(data_dir=data, home=tmp_path)
+ assert len(_all(data)) == 1
+
+ path.unlink()
+ refresh(data_dir=data, home=tmp_path)
+
+ assert _all(data) == []
+ with sqlite3.connect(index_db_path(data)) as conn:
+ assert conn.execute("SELECT COUNT(*) FROM indexed_files").fetchone()[0] == 0
+
+
+def test_an_unreadable_root_never_prunes(tmp_path: Path) -> None:
+ """A root that vanished entirely (unmounted drive) keeps its history."""
+ import shutil
+
+ data = tmp_path / "data"
+ session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
+ _write(_codex_path(tmp_path, session), [*_codex_prelude(session), _codex_token_line()])
+ refresh(data_dir=data, home=tmp_path)
+
+ shutil.rmtree(tmp_path / ".codex")
+ refresh(data_dir=data, home=tmp_path)
+
+ assert len(_all(data)) == 1
+
+
+def test_codex_rows_before_the_first_turn_context_get_the_model(tmp_path: Path) -> None:
+ """A fork replays its parent BEFORE its own turn_context; the model that
+ follows is the file's, so the replayed rows inherit it."""
+ data = tmp_path / "data"
+ session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
+ meta = json.dumps(
+ {"timestamp": "2026-08-13T15:05:44.589Z", "type": "session_meta",
+ "payload": {"session_id": session, "cwd": "/work/downloads"}}
+ )
+ context = json.dumps(
+ {"timestamp": "2026-08-13T15:05:53.434Z", "type": "turn_context",
+ "payload": {"model": "gpt-5.6-terra", "cwd": "/work/downloads"}}
+ )
+ _write(
+ _codex_path(tmp_path, session),
+ [
+ meta,
+ _codex_token_line(turn=1),
+ _codex_token_line(turn=2),
+ context,
+ _codex_token_line(turn=3),
+ ],
+ )
+
+ refresh(data_dir=data, home=tmp_path)
+
+ assert {t.model for t in _all(data)} == {"gpt-5.6-terra"}
diff --git a/tests/unit/costs/test_cost_read_model.py b/tests/unit/costs/test_cost_read_model.py
index 2cbffb60f3..d49c2b8468 100644
--- a/tests/unit/costs/test_cost_read_model.py
+++ b/tests/unit/costs/test_cost_read_model.py
@@ -518,3 +518,131 @@ def test_filters_narrow_the_entries(sources: CostSources) -> None:
def test_empty_filters_keep_everything(sources: CostSources) -> None:
entries = collect_entries(sources)
assert filter_entries(entries) == entries
+
+
+# ---------------------------------------------------------------------------
+# Missions: who did the work lives on WorkerSpawned, not on the draft
+# ---------------------------------------------------------------------------
+
+
+def _missions_db_with_spawn(path: Path) -> None:
+ conn = sqlite3.connect(path)
+ conn.executescript(_MISSIONS_DDL)
+ conn.execute(
+ "INSERT INTO missions (id, prompt, state, created_ms, cost_usd) VALUES (?,?,?,?,?)",
+ ("m-2", "write the tests", "done", T0, 0.0),
+ )
+ spawn = {
+ "event_type": "WorkerSpawned",
+ "worker_id": "w-9",
+ "step": {"worker_cli": "claude", "model": "sonnet"},
+ "cli": "claude",
+ "model": "sonnet",
+ }
+ rows = [
+ ("m-2", "w-9", "WorkerSpawned", T0 + 1_000, json.dumps(spawn)),
+ # A Claude Code seat quoting its own API-equivalent, and reporting its
+ # TURN count in the token slot (real shape, 2026-08-25).
+ ("m-2", "w-9", "WorkerDraftReady", T0 + 5_000,
+ json.dumps({"tokens_used": 4, "cost_usd": 3.15})),
+ # The same worker on a draft that reported tokens but no price.
+ ("m-2", "w-9", "WorkerDraftReady", T0 + 6_000,
+ json.dumps({"tokens_used": 33_000, "cost_usd": 0.0})),
+ ]
+ conn.executemany(
+ "INSERT INTO mission_events (mission_id, worker_id, event_type, ts_ms, payload_json) "
+ "VALUES (?,?,?,?,?)",
+ rows,
+ )
+ conn.commit()
+ conn.close()
+
+
+def test_mission_draft_takes_cli_and_model_from_its_spawn(tmp_path: Path) -> None:
+ path = tmp_path / "missions.db"
+ _missions_db_with_spawn(path)
+ rows = collect_entries(CostSources(missions_db=path))
+ assert len(rows) == 2
+ assert {e.provider for e in rows} == {"claude-cli"}
+ assert {e.model for e in rows} == {"sonnet"}
+
+
+def test_mission_seat_quote_is_subscription_not_billed(tmp_path: Path) -> None:
+ path = tmp_path / "missions.db"
+ _missions_db_with_spawn(path)
+ quoted = next(e for e in collect_entries(CostSources(missions_db=path)) if e.cost_usd == 3.15)
+ assert quoted.price_source == "subscription"
+ # 4 "tokens" for $3.15 is a turn count; it must not land in a token column.
+ assert quoted.tokens_in == 0
+
+
+def test_mission_short_model_name_is_priced_not_a_gap(tmp_path: Path) -> None:
+ path = tmp_path / "missions.db"
+ _missions_db_with_spawn(path)
+ tokens_only = next(
+ e for e in collect_entries(CostSources(missions_db=path)) if e.tokens_in == 33_000
+ )
+ assert tokens_only.price_source == "subscription"
+ assert tokens_only.cost_usd > 0
+
+
+# ---------------------------------------------------------------------------
+# Agent chat: the OpenAI usage convention counts cache hits inside the input
+# ---------------------------------------------------------------------------
+
+
+def _agent_chat_db_two_runners(path: Path) -> None:
+ conn = sqlite3.connect(path)
+ conn.executescript(_AGENT_CHAT_DDL)
+ conn.execute(
+ "INSERT INTO agent_chat_sessions (session_id, title, provider, model, created_ms, "
+ "updated_ms) VALUES (?,?,?,?,?,?)",
+ ("chat-2", "Two runners", "claude", "claude-opus-4-7-20251022", T0, T0),
+ )
+ events = [
+ ("chat-2", 1, T0 + 1_000, "turn_started", json.dumps(
+ {"turn_id": "t-codex", "runner": "codex-cli", "provider": "codex",
+ "model": "gpt-5.5"})),
+ ("chat-2", 2, T0 + 2_000, "turn_finished", json.dumps(
+ {"turn_id": "t-codex", "status": "done", "cost_usd": 0.0,
+ "usage": {"input_tokens": 1_000, "cached_input_tokens": 900,
+ "output_tokens": 10}})),
+ ("chat-2", 3, T0 + 3_000, "turn_started", json.dumps(
+ {"turn_id": "t-claude", "runner": "claude-cli", "provider": "claude",
+ "model": "claude-opus-4-7-20251022"})),
+ ("chat-2", 4, T0 + 4_000, "turn_finished", json.dumps(
+ {"turn_id": "t-claude", "status": "done", "cost_usd": 0.0,
+ "usage": {"input_tokens": 1_000, "cache_read_input_tokens": 900,
+ "output_tokens": 10}})),
+ ]
+ conn.executemany(
+ "INSERT INTO agent_chat_events (session_id, seq, ts_ms, kind, payload) VALUES (?,?,?,?,?)",
+ events,
+ )
+ conn.commit()
+ conn.close()
+
+
+def test_codex_cache_hits_are_subtracted_from_input_but_claude_ones_are_not(
+ tmp_path: Path,
+) -> None:
+ path = tmp_path / "agent_chat.db"
+ _agent_chat_db_two_runners(path)
+ rows = {e.model: e for e in collect_entries(CostSources(agent_chat_db=path))}
+ assert rows["gpt-5.5"].tokens_in == 100
+ assert rows["gpt-5.5"].tokens_cached == 900
+ assert rows["claude-opus-4-7-20251022"].tokens_in == 1_000
+ assert rows["claude-opus-4-7-20251022"].tokens_cached == 900
+
+
+def test_a_subscription_provider_is_priced_not_free() -> None:
+ """A paid seat is worth its API-equivalent; "$0.00 free" is for local engines."""
+ cost, source = price_entry(
+ provider="codex-subscription-realtime",
+ model="gpt-5.5",
+ tokens_in=1_000_000,
+ tokens_out=0,
+ recorded_usd=0.0,
+ )
+ assert source == "subscription"
+ assert cost > 0
diff --git a/tests/unit/test_brain_cost.py b/tests/unit/test_brain_cost.py
index 16e8ebb221..e0d550b717 100644
--- a/tests/unit/test_brain_cost.py
+++ b/tests/unit/test_brain_cost.py
@@ -148,3 +148,33 @@ class TestCalculateRealtimeCostUsd:
for model, rates in REALTIME_AUDIO_PRICING_USD_PER_MTOK.items():
assert len(rates) == 2, f"{model}: expected (in, out)"
assert rates[0] >= 0.0 and rates[1] >= 0.0
+
+
+def test_table_prices_the_models_the_workers_actually_run() -> None:
+ """Static table only — a network feed must not be what keeps these priced."""
+ from jarvis.brain.cost import MODEL_ALIASES, PRICING_USD_PER_MTOK
+
+ assert "grok-4.5" in PRICING_USD_PER_MTOK
+ for alias, canonical in MODEL_ALIASES.items():
+ assert canonical in PRICING_USD_PER_MTOK, (alias, canonical)
+
+
+def test_a_variant_tag_prices_as_the_untagged_model() -> None:
+ from jarvis.brain.cost import resolve_rates
+
+ assert resolve_rates("kimi-k2.5:cloud") == resolve_rates("kimi-k2.5")
+ assert resolve_rates("kimi-k2.5:cloud") is not None
+
+
+def test_a_free_tag_stays_unknown_to_the_rate_table() -> None:
+ """``:free`` is the free tier, settled by price_entry, never a variant."""
+ from jarvis.brain.cost import resolve_rates
+
+ assert resolve_rates("kimi-k2.5:free") is None
+
+
+def test_grok_cache_reads_bill_at_a_quarter() -> None:
+ from jarvis.brain.cost import cache_read_fraction
+
+ assert cache_read_fraction("grok-4.6-build") == 0.25
+ assert cache_read_fraction("gpt-5.5") == 0.10