Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: attribute nested Grok and Antigravity CLI usage in cost reports (#5831)

Adam Eivyc42f0bf303ad
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 18f99bd3b8..ba0e0a69a1 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -833,8 +833,10 @@ function InternalUsageMetrics() {
Informational estimate of what this usage would have cost under API billing (PortOS runs on subscriptions).
{' '}<span className="text-gray-400">Measured</span> rows are the provider CLI&rsquo;s own per-message counts, read from its local
transcript — full per-turn input, output, and prompt-cache reads/writes, each priced at its own rate.
- {' '}<span className="text-gray-400">Estimated</span> rows are runs with no readable transcript (local models, or a provider
- that writes none): input is approximated from the initial prompt only and cache traffic is not counted, so those rows
+ {' '}Grok rows are measured the same way once a turn completes; a run killed mid-turn falls back to its chat history.
+ {' '}<span className="text-gray-400">Estimated</span> rows are runs with no token counts to read: Antigravity writes a
+ session transcript but no token fields, so its rows are sized from that transcript&rsquo;s text, and a run with no session
+ file at all (local models) is approximated from the initial prompt only with no cache traffic counted — those rows
understate real usage substantially.
Rates are as of {report?.pricingAsOf || 'the last update'} and exclude batch and long-context tiers.
{' '}Rows marked ~ use an approximated rate.
diff --git a/server/lib/README.md b/server/lib/README.md
index 22b80f4c0b..a1e784f7b9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -175,7 +175,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `APP_FEATURE_IDS`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. |
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)` and `gatewayForProvider(config)` → row or null. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) and `client/src/utils/providers.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. Dependency-light: imports nothing. |
-| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
+| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. |
| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |
| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `reapIdleDaemons(now?)` → the names stopped, and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |
diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.js
index 3c8fa2a9e3..3a8259c43c 100644
--- a/server/lib/providerTranscriptUsage.js
+++ b/server/lib/providerTranscriptUsage.js
@@ -402,3 +402,321 @@ export function totalTranscriptTokens(totals) {
return num(totals?.tokensIn) + num(totals?.tokensOut)
+ num(totals?.cacheReadTokens) + num(totals?.cacheWriteTokens);
}
+
+/**
+ * ---------------------------------------------------------------------------
+ * Grok
+ * ---------------------------------------------------------------------------
+ *
+ * `~/.grok/sessions/<encodeURIComponent(cwd)>/<session-id>/`
+ *
+ * summary.json — `info.id`, `info.cwd`, `created_at`, `updated_at`,
+ * `last_active_at`, `current_model_id`, `num_messages`.
+ * updates.jsonl — the ACP-style event stream. One JSON envelope per line
+ * (`timestamp` in epoch SECONDS, `params._meta.agentTimestampMs`
+ * in ms). A `params.update.sessionUpdate === 'turn_completed'`
+ * line carries the real billed counts in `usage`.
+ * chat_history.jsonl — role-tagged messages with NO timestamps; the fallback
+ * when a run was killed before any turn completed.
+ *
+ * **Two traps, both load-bearing:**
+ *
+ * 1. Streaming chunks carry `_meta.totalTokens`, which is CONTEXT-WINDOW
+ * OCCUPANCY (it jumps when a tool result is appended and falls after a
+ * compaction). It is not billed and is never read here.
+ * 2. `turn_completed.usage` has been observed in BOTH shapes across grok
+ * versions: per-prompt on this install (measured: 44 of 46 multi-turn
+ * sessions are non-monotonic in `totalTokens`, so each block describes only
+ * its own prompt), and cumulative-for-the-session in the shape #5831 was
+ * filed against. Summing a cumulative stream inflates by its turn count, so
+ * `parseGrokTurns` detects the shape (see `looksCumulative`) and converts a
+ * cumulative stream to per-prompt deltas before summing. One code path,
+ * both formats, no double-count either way.
+ *
+ * `inputTokens` INCLUDES `cachedReadTokens` and `outputTokens` INCLUDES
+ * `reasoningTokens` — verified over 373 real turns (0 counterexamples, and
+ * `totalTokens === inputTokens + outputTokens` in every one). So the cached
+ * portion is split out to be priced at the cache-read tier, and reasoning is
+ * NOT added on top of output; doing either would over-bill.
+ */
+
+/** Grok's per-cwd session folder is `encodeURIComponent(cwd)`. */
+export function decodeGrokSessionDir(dirName) {
+ // A folder name that isn't valid percent-encoding isn't one of grok's —
+ // decodeURIComponent has no non-throwing form, so this catch IS the test.
+ try {
+ return decodeURIComponent(String(dirName || ''));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Epoch-ms for an updates.jsonl envelope. `params._meta.agentTimestampMs` is
+ * already ms; the envelope's own `timestamp` is epoch SECONDS (a 10-digit
+ * value), which would land in 1970 if read as ms.
+ */
+function grokEventMs(line) {
+ const meta = line?.params?._meta;
+ if (typeof meta?.agentTimestampMs === 'number' && Number.isFinite(meta.agentTimestampMs)) {
+ return meta.agentTimestampMs;
+ }
+ const ts = line?.timestamp;
+ if (typeof ts !== 'number' || !Number.isFinite(ts)) return null;
+ return ts < 1e11 ? Math.round(ts * 1000) : ts;
+}
+
+/** The four billable buckets of one grok `usage` block, cache tiers split out. */
+const grokBuckets = (usage) => ({
+ messages: 1,
+ // `inputTokens` includes the cached read — split so each tier prices at its
+ // own rate instead of billing cache reads as fresh input.
+ tokensIn: Math.max(0, num(usage?.inputTokens) - num(usage?.cachedReadTokens)),
+ // `reasoningTokens` is a SUBSET of `outputTokens`, not an addition.
+ tokensOut: num(usage?.outputTokens),
+ cacheReadTokens: num(usage?.cachedReadTokens),
+ cacheWriteTokens: num(usage?.cacheCreationTokens)
+});
+
+/**
+ * True when every consecutive pair of turns is non-decreasing in all three
+ * independently-moving fields — the signature of a cumulative stream.
+ *
+ * Requires at least three turns: two per-prompt turns are non-decreasing by
+ * coincidence often enough to matter, three are not (0 of 39 real sessions with
+ * >=3 turns are monotonic in all three fields, while a cumulative stream is
+ * monotonic in all of them by construction).
+ */
+function looksCumulative(usages) {
+ if (usages.length < 3) return false;
+ const fields = ['inputTokens', 'outputTokens', 'cachedReadTokens'];
+ return fields.every((field) => usages.every((usage, i) => (
+ i === 0 || num(usages[i - 1][field]) <= num(usage[field])
+ )));
+}
+
+/**
+ * Parse a grok session's `updates.jsonl` into billed totals.
+ *
+ * @param {string} jsonlText raw file contents (may end mid-line)
+ * @param {{ from?: number|null, to?: number|null, exclude?: {has:(k:string)=>boolean}|null }} [opts]
+ * `from`/`to` are epoch-ms bounds; `exclude` holds prompt keys already billed
+ * to another run (the same claim mechanism the Claude parser uses).
+ * @returns {{ sessionId: string|null, model: string|null, models: string[],
+ * byModel: object, messages: number, tokensIn: number, tokensOut: number,
+ * cacheReadTokens: number, cacheWriteTokens: number, countedKeys: string[],
+ * turns: number }} `turns` is the number of `turn_completed` events SEEN
+ * (before windowing) — the sentinel that separates "this session recorded no
+ * billed turn, fall back to chat_history" from "it did, and this window's
+ * share of it is legitimately zero".
+ */
+export function parseGrokTurns(jsonlText, { from = null, to = null, exclude = null } = {}) {
+ const totals = emptyTotals();
+ const byModel = new Map();
+ const counted = [];
+ let sessionId = null;
+
+ // Every turn_completed in file order — the whole sequence is needed before
+ // any of it can be billed, because the cumulative test is a property of the
+ // sequence, not of one line.
+ const turns = [];
+ for (const line of parseJsonLines(jsonlText)) {
+ const update = line?.params?.update;
+ if (!update || typeof update !== 'object') continue;
+ if (typeof line.params?.sessionId === 'string') sessionId ??= line.params.sessionId;
+ if (update.sessionUpdate !== 'turn_completed') continue;
+ const usage = update.usage;
+ if (!usage || typeof usage !== 'object') continue;
+ turns.push({
+ // `prompt_id` is unique per turn on every observed session; the ordinal
+ // fallback keeps a turn that lacks one claimable rather than unbillable.
+ key: typeof update.prompt_id === 'string' && update.prompt_id ? update.prompt_id : `#${turns.length}`,
+ ms: grokEventMs(line),
+ usage
+ });
+ }
+
+ const cumulative = looksCumulative(turns.map((turn) => turn.usage));
+
+ for (const [index, turn] of turns.entries()) {
+ // A cumulative snapshot describes the session so far, so this turn's own
+ // share is its delta against the previous snapshot (turn 0's baseline is a
+ // fresh session, i.e. zero). A per-prompt block already IS its own share.
+ const previous = cumulative && index > 0 ? turns[index - 1].usage : null;
+ const usage = previous
+ ? Object.fromEntries(Object.keys(turn.usage)
+ .filter((field) => typeof turn.usage[field] === 'number')
+ .map((field) => [field, Math.max(0, turn.usage[field] - num(previous[field]))]))
+ : turn.usage;
+
+ // A turn with no readable timestamp can't be placed in a run's window —
+ // excluded whenever a bound is supplied, for the same reason the Claude
+ // parser drops a timestamp-less message: accepting it hands the same tokens
+ // to every run that ever reads this file.
+ if (!inWindow(turn.ms, from, to)) continue;
+ if (exclude?.has(turn.key)) continue;
+
+ const buckets = grokBuckets(usage);
+ if (totalTranscriptTokens(buckets) === 0) continue;
+ counted.push(turn.key);
+ for (const field of Object.keys(totals)) totals[field] += buckets[field];
+
+ // `modelUsage` names the model(s) the turn actually called. In cumulative
+ // mode its per-model figures are cumulative too, so bucket the DELTA'd
+ // aggregate under the named model rather than re-reading the raw block.
+ // A turn that called several models is attributed to the first: grok bills
+ // one turn as a unit, and splitting the delta across models would need
+ // per-model deltas the cumulative shape doesn't reliably provide.
+ const bucketKey = Object.keys(turn.usage.modelUsage || {})[0] ?? UNKNOWN_MODEL;
+ if (!byModel.has(bucketKey)) byModel.set(bucketKey, emptyTotals());
+ const bucket = byModel.get(bucketKey);
+ for (const field of Object.keys(bucket)) bucket[field] += buckets[field];
+ }
+
+ const models = [...byModel.keys()].filter((model) => model !== UNKNOWN_MODEL);
+ return {
+ sessionId,
+ model: models[0] ?? null,
+ models,
+ byModel: Object.fromEntries(byModel),
+ ...totals,
+ countedKeys: counted,
+ turns: turns.length
+ };
+}
+
+/** Flatten grok's `content`, which is either a string or `[{ type, text }]`. */
+function grokText(content) {
+ if (typeof content === 'string') return content;
+ if (!Array.isArray(content)) return '';
+ return content.map((part) => (typeof part?.text === 'string' ? part.text : '')).join('');
+}
+
+/**
+ * Chars-in / chars-out for a grok session with no completed turn — a run that
+ * was killed or interrupted before `turn_completed` was written. There are no
+ * timestamps in this file, so it is billed whole-session or not at all; the
+ * caller windows it by `summary.json` and claims the session id so two
+ * overlapping runs can't both take it.
+ *
+ * `user` and `tool_result` are what the model READ; `assistant` and the
+ * `reasoning` summaries are what it WROTE. `encrypted_content` on a reasoning
+ * entry is an opaque blob, not text, and is excluded — its length says nothing
+ * about the token count it stands for.
+ *
+ * @returns {{ model: string|null, charsIn: number, charsOut: number, messages: number }}
+ */
+export function parseGrokChatHistory(jsonlText) {
+ let charsIn = 0;
+ let charsOut = 0;
+ let messages = 0;
+ let model = null;
+
+ for (const entry of parseJsonLines(jsonlText)) {
+ switch (entry.type) {
+ case 'user':
+ case 'tool_result':
+ charsIn += grokText(entry.content).length;
+ break;
+ case 'assistant': {
+ charsOut += grokText(entry.content).length;
+ for (const call of entry.tool_calls || []) {
+ charsOut += typeof call?.arguments === 'string' ? call.arguments.length : 0;
+ }
+ if (typeof entry.model_id === 'string' && entry.model_id) model = entry.model_id;
+ messages += 1;
+ break;
+ }
+ case 'reasoning':
+ charsOut += grokText(entry.summary).length;
+ break;
+ default:
+ break;
+ }
+ }
+
+ return { model, charsIn, charsOut, messages };
+}
+
+/**
+ * ---------------------------------------------------------------------------
+ * Antigravity (`agy`)
+ * ---------------------------------------------------------------------------
+ *
+ * `~/.gemini/antigravity-cli/`
+ *
+ * history.jsonl — `{ timestamp (epoch ms), workspace, conversationId? }`.
+ * Only the lines carrying a `conversationId` name a run.
+ * brain/<conversationId>/.system_generated/logs/transcript.jsonl — the steps.
+ *
+ * The transcript carries NO token fields at all, so these rows are honest
+ * chars/4 ESTIMATES and must never be presented as measured. `PLANNER_RESPONSE`
+ * is the model speaking (content + thinking + tool-call arguments → output);
+ * every other step type is text handed TO the model — a user turn, a system
+ * message, or a tool result such as `VIEW_FILE`/`GREP_SEARCH` (→ input). Note
+ * those tool-result steps carry `source: 'MODEL'` even though the text is the
+ * tool's, which is why the split keys off `type`, not `source`.
+ *
+ * @param {string} jsonlText raw file contents (may end mid-line)
+ * @param {{ from?: number|null, to?: number|null, exclude?: {has:(k:string)=>boolean}|null }} [opts]
+ * @returns {{ charsIn: number, charsOut: number, messages: number,
+ * countedKeys: string[], steps: number }} `steps` is the number of steps SEEN
+ * before windowing — the sentinel separating "unreadable/empty transcript"
+ * from "read, and this window's share is zero".
+ */
+export function parseAgyTranscript(jsonlText, { from = null, to = null, exclude = null } = {}) {
+ let charsIn = 0;
+ let charsOut = 0;
+ let messages = 0;
+ let steps = 0;
+ const counted = [];
+
+ for (const [index, entry] of parseJsonLines(jsonlText).entries()) {
+ if (typeof entry.type !== 'string') continue;
+ steps += 1;
+ if (!inWindow(toEpoch(entry.created_at), from, to)) continue;
+ // `step_index` is the CLI's own ordinal and is stable across appends; the
+ // parse ordinal only fills in for a step that somehow lacks one.
+ const key = Number.isFinite(entry.step_index) ? `step-${entry.step_index}` : `#${index}`;
+ if (exclude?.has(key)) continue;
+
+ let chars = typeof entry.content === 'string' ? entry.content.length : 0;
+ if (entry.type === 'PLANNER_RESPONSE') {
+ chars += typeof entry.thinking === 'string' ? entry.thinking.length : 0;
+ for (const call of entry.tool_calls || []) {
+ chars += typeof call?.args === 'object' ? JSON.stringify(call.args).length : 0;
+ }
+ charsOut += chars;
+ messages += 1;
+ } else {
+ charsIn += chars;
+ }
+ counted.push(key);
+ }
+
+ return { charsIn, charsOut, messages, countedKeys: counted, steps };
+}
+
+/**
+ * The conversations `agy` recorded, from `~/.gemini/antigravity-cli/history.jsonl`.
+ * Only lines carrying a `conversationId` name a brain transcript; the rest are
+ * slash-command echoes. `timestamp` is epoch ms.
+ *
+ * @param {string} jsonlText
+ * @returns {Array<{ conversationId: string, workspace: string|null, timestamp: number|null }>}
+ */
+export function parseAgyHistory(jsonlText) {
+ const seen = new Set();
+ const out = [];
+ for (const entry of parseJsonLines(jsonlText)) {
+ const id = entry?.conversationId;
+ if (typeof id !== 'string' || !id || seen.has(id)) continue;
+ seen.add(id);
+ out.push({
+ conversationId: id,
+ workspace: typeof entry.workspace === 'string' ? entry.workspace : null,
+ timestamp: typeof entry.timestamp === 'number' && Number.isFinite(entry.timestamp) ? entry.timestamp : null
+ });
+ }
+ return out;
+}
diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.js
index cf0ecec241..2898fcb145 100644
--- a/server/lib/providerTranscriptUsage.test.js
+++ b/server/lib/providerTranscriptUsage.test.js
@@ -1,8 +1,13 @@
import { describe, it, expect } from 'vitest';
import {
claudeProjectSlug,
+ decodeGrokSessionDir,
+ parseAgyHistory,
+ parseAgyTranscript,
parseClaudeTranscript,
parseCodexRollout,
+ parseGrokChatHistory,
+ parseGrokTurns,
totalTranscriptTokens,
UNKNOWN_MODEL
} from './providerTranscriptUsage.js';
@@ -451,3 +456,234 @@ describe('Codex message count under a window', () => {
expect(parseCodexRollout(text).messages).toBe(1);
});
});
+
+// ---------------------------------------------------------------------------
+// Grok — ~/.grok/sessions/<encodeURIComponent(cwd)>/<session-id>/
+// ---------------------------------------------------------------------------
+
+const GROK_MODEL = 'example-grok-model';
+
+/** One `updates.jsonl` envelope carrying a completed turn. */
+const grokTurn = ({
+ promptId = 'prompt-1',
+ seconds = 1_800_000_000,
+ input = 15_000,
+ output = 1_800,
+ cachedRead = 11_000,
+ cacheCreation = 0,
+ reasoning = 800,
+ model = GROK_MODEL,
+ ms = null
+} = {}) => JSON.stringify({
+ timestamp: seconds,
+ method: '_x.ai/session/update',
+ params: {
+ sessionId: 'session-aaaa',
+ update: {
+ sessionUpdate: 'turn_completed',
+ prompt_id: promptId,
+ stop_reason: 'end_turn',
+ usage: {
+ inputTokens: input,
+ outputTokens: output,
+ totalTokens: input + output,
+ cachedReadTokens: cachedRead,
+ cacheCreationTokens: cacheCreation,
+ reasoningTokens: reasoning,
+ modelUsage: { [model]: { inputTokens: input, outputTokens: output } }
+ }
+ },
+ ...(ms == null ? {} : { _meta: { eventId: 'evt-1', agentTimestampMs: ms } })
+ }
+});
+
+/** A streaming chunk carrying CONTEXT-WINDOW OCCUPANCY, which is never billed. */
+const grokChunk = (totalTokens) => JSON.stringify({
+ timestamp: 1_800_000_000,
+ method: '_x.ai/session/update',
+ params: {
+ sessionId: 'session-aaaa',
+ update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'hi' } },
+ _meta: { totalTokens }
+ }
+});
+
+describe('parseGrokTurns', () => {
+ it('bills a completed turn with the cache tier split out of input', () => {
+ const parsed = parseGrokTurns(grokTurn());
+ // `inputTokens` INCLUDES `cachedReadTokens`, so the fresh input is the
+ // difference; billing both whole would charge cache reads at full rate.
+ expect(parsed.tokensIn).toBe(4_000);
+ expect(parsed.cacheReadTokens).toBe(11_000);
+ // `reasoningTokens` is a SUBSET of `outputTokens`, never an addition.
+ expect(parsed.tokensOut).toBe(1_800);
+ expect(parsed.cacheWriteTokens).toBe(0);
+ expect(parsed.byModel[GROK_MODEL].tokensOut).toBe(1_800);
+ expect(parsed.model).toBe(GROK_MODEL);
+ expect(parsed.sessionId).toBe('session-aaaa');
+ });
+
+ it('never bills the _meta.totalTokens context-window occupancy', () => {
+ const parsed = parseGrokTurns([grokChunk(950_000), grokChunk(1_200_000)].join('\n'));
+ expect(totalTranscriptTokens(parsed)).toBe(0);
+ // Sentinel: no turn was recorded at all, so the caller falls back to chat
+ // history rather than reporting a measured zero.
+ expect(parsed.turns).toBe(0);
+ });
+
+ it('sums per-prompt turns without treating them as cumulative', () => {
+ const text = [
+ grokTurn({ promptId: 'p1', input: 10_000, cachedRead: 6_000, output: 500 }),
+ grokTurn({ promptId: 'p2', input: 4_000, cachedRead: 1_000, output: 100 })
+ ].join('\n');
+ const parsed = parseGrokTurns(text);
+ expect(parsed.tokensIn).toBe(4_000 + 3_000);
+ expect(parsed.tokensOut).toBe(600);
+ expect(parsed.countedKeys).toEqual(['p1', 'p2']);
+ });
+
+ it('converts a cumulative-for-the-session stream to per-turn deltas', () => {
+ // Every field non-decreasing across three or more turns is the cumulative
+ // signature. Summing the raw snapshots here would bill 60k input for a
+ // session that really used 30k — the #5831 double-count hazard.
+ const text = [
+ grokTurn({ promptId: 'p1', input: 10_000, cachedRead: 5_000, output: 100 }),
+ grokTurn({ promptId: 'p2', input: 20_000, cachedRead: 9_000, output: 300 }),
+ grokTurn({ promptId: 'p3', input: 30_000, cachedRead: 12_000, output: 400 })
+ ].join('\n');
+ const parsed = parseGrokTurns(text);
+ expect(parsed.tokensIn).toBe(30_000 - 12_000);
+ expect(parsed.tokensOut).toBe(400);
+ expect(parsed.cacheReadTokens).toBe(12_000);
+ });
+
+ it('windows turns by the epoch-seconds envelope timestamp', () => {
+ const text = [
+ grokTurn({ promptId: 'p1', seconds: 1_800_000_000, output: 111 }),
+ grokTurn({ promptId: 'p2', seconds: 1_800_003_600, output: 222 })
+ ].join('\n');
+ const parsed = parseGrokTurns(text, { from: 1_800_003_000_000, to: 1_800_004_000_000 });
+ expect(parsed.tokensOut).toBe(222);
+ expect(parsed.countedKeys).toEqual(['p2']);
+ });
+
+ it('prefers the millisecond _meta timestamp when present', () => {
+ // A 10-digit envelope `timestamp` is SECONDS; read as ms it lands in 1970
+ // and every window check fails.
+ const text = grokTurn({ promptId: 'p1', seconds: 1_800_000_000, ms: 1_800_000_000_500, output: 42 });
+ expect(parseGrokTurns(text, { from: 1_800_000_000_000, to: 1_800_000_001_000 }).tokensOut).toBe(42);
+ });
+
+ it('skips turns another run already claimed', () => {
+ const text = [
+ grokTurn({ promptId: 'p1', output: 111 }),
+ grokTurn({ promptId: 'p2', output: 222 })
+ ].join('\n');
+ const parsed = parseGrokTurns(text, { exclude: new Set(['p1']) });
+ expect(parsed.tokensOut).toBe(222);
+ expect(parsed.countedKeys).toEqual(['p2']);
+ });
+
+ it('tolerates a truncated trailing line from a session still being written', () => {
+ const text = `${grokTurn({ promptId: 'p1', output: 111 })}\n{"timestamp":18000000`;
+ expect(parseGrokTurns(text).tokensOut).toBe(111);
+ });
+});
+
+describe('parseGrokChatHistory', () => {
+ it('splits chars by role for the no-completed-turn fallback', () => {
+ const text = [
+ JSON.stringify({ type: 'user', content: [{ type: 'text', text: 'a'.repeat(40) }] }),
+ JSON.stringify({ type: 'assistant', content: 'b'.repeat(20), model_id: GROK_MODEL, tool_calls: [{ id: 't1', name: 'read', arguments: 'c'.repeat(8) }] }),
+ JSON.stringify({ type: 'reasoning', summary: [{ type: 'summary_text', text: 'd'.repeat(12) }], encrypted_content: 'e'.repeat(5000) }),
+ JSON.stringify({ type: 'tool_result', tool_call_id: 't1', content: 'f'.repeat(60) })
+ ].join('\n');
+ const parsed = parseGrokChatHistory(text);
+ expect(parsed.charsIn).toBe(100);
+ // `encrypted_content` is an opaque blob, not text — its 5000 chars say
+ // nothing about the tokens it stands for and must not inflate the estimate.
+ expect(parsed.charsOut).toBe(40);
+ expect(parsed.model).toBe(GROK_MODEL);
+ expect(parsed.messages).toBe(1);
+ });
+});
+
+describe('decodeGrokSessionDir', () => {
+ it('round-trips an encodeURIComponent-ed workspace path', () => {
+ const cwd = '/tmp/example-workspace/sub dir';
+ expect(decodeGrokSessionDir(encodeURIComponent(cwd))).toBe(cwd);
+ });
+
+ it('returns null for a folder name that is not valid percent-encoding', () => {
+ expect(decodeGrokSessionDir('%zz-not-encoded')).toBeNull();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Antigravity — ~/.gemini/antigravity-cli/
+// ---------------------------------------------------------------------------
+
+const agyStep = ({ index = 0, type = 'GENERIC', createdAt = '2026-07-01T10:00:00Z', content = '', thinking = null, toolCalls = null }) => JSON.stringify({
+ step_index: index,
+ source: type === 'USER_INPUT' ? 'USER_EXPLICIT' : 'MODEL',
+ type,
+ status: 'DONE',
+ created_at: createdAt,
+ ...(content ? { content } : {}),
+ ...(thinking ? { thinking } : {}),
+ ...(toolCalls ? { tool_calls: toolCalls } : {})
+});
+
+describe('parseAgyTranscript', () => {
+ it('counts PLANNER_RESPONSE as output and every other step as input', () => {
+ const text = [
+ agyStep({ index: 0, type: 'USER_INPUT', content: 'u'.repeat(40) }),
+ agyStep({ index: 1, type: 'PLANNER_RESPONSE', content: 'p'.repeat(10), thinking: 't'.repeat(6), toolCalls: [{ name: 'ls', args: { path: '/tmp/example-workspace' } }] }),
+ // A tool RESULT carries `source: 'MODEL'` but the text is the tool's, and
+ // it is what the model reads next — so the split keys off `type`.
+ agyStep({ index: 2, type: 'VIEW_FILE', content: 'v'.repeat(100) })
+ ].join('\n');
+ const parsed = parseAgyTranscript(text);
+ expect(parsed.charsIn).toBe(140);
+ expect(parsed.charsOut).toBe(16 + JSON.stringify({ path: '/tmp/example-workspace' }).length);
+ expect(parsed.messages).toBe(1);
+ expect(parsed.countedKeys).toEqual(['step-0', 'step-1', 'step-2']);
+ });
+
+ it('windows steps by created_at and reports how many it saw', () => {
+ const text = [
+ agyStep({ index: 0, type: 'GENERIC', createdAt: '2026-07-01T09:00:00Z', content: 'a'.repeat(80) }),
+ agyStep({ index: 1, type: 'GENERIC', createdAt: '2026-07-01T10:00:00Z', content: 'b'.repeat(40) })
+ ].join('\n');
+ const parsed = parseAgyTranscript(text, {
+ from: Date.parse('2026-07-01T09:30:00Z'),
+ to: Date.parse('2026-07-01T10:30:00Z')
+ });
+ expect(parsed.charsIn).toBe(40);
+ // Sentinel: two steps were READ, this window's share is one of them —
+ // distinct from an unreadable transcript, which yields no result at all.
+ expect(parsed.steps).toBe(2);
+ expect(parsed.countedKeys).toEqual(['step-1']);
+ });
+
+ it('skips steps another run already claimed', () => {
+ const text = [
+ agyStep({ index: 0, content: 'a'.repeat(80) }),
+ agyStep({ index: 1, content: 'b'.repeat(40) })
+ ].join('\n');
+ expect(parseAgyTranscript(text, { exclude: new Set(['step-0']) }).charsIn).toBe(40);
+ });
+});
+
+describe('parseAgyHistory', () => {
+ it('keeps only the lines that name a conversation, once each', () => {
+ const text = [
+ JSON.stringify({ display: '/status', timestamp: 1_800_000_000_000, type: 'slash_command', workspace: '/tmp/example-workspace' }),
+ JSON.stringify({ display: 'do the thing', timestamp: 1_800_000_001_000, workspace: '/tmp/example-workspace', conversationId: 'conv-aaaa' }),
+ JSON.stringify({ display: 'again', timestamp: 1_800_000_002_000, workspace: '/tmp/example-workspace', conversationId: 'conv-aaaa' })
+ ].join('\n');
+ expect(parseAgyHistory(text)).toEqual([
+ { conversationId: 'conv-aaaa', workspace: '/tmp/example-workspace', timestamp: 1_800_000_001_000 }
+ ]);
+ });
+});
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 4b5bbca5dc..9cae041006 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -112,7 +112,7 @@ router.get('/backfill', asyncHandler(async (req, res) => {
}));
router.post('/backfill', asyncHandler(async (req, res) => {
- res.status(202).json(startHistoricalUsageBackfill());
+ res.status(202).json(await startHistoricalUsageBackfill());
}));
// POST /api/usage/session - Record a session
diff --git a/server/services/usage.js b/server/services/usage.js
index fa4db4914a..8f465ba33d 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -306,6 +306,15 @@ export function getReconciledUsageRunIds() {
return Object.keys(usageData?.reconciledRuns || {});
}
+/**
+ * Run ids whose NESTED-session (sibling-family) attribution has already landed.
+ * A separate marker from `reconciledRuns` on purpose: the sibling pass has to be
+ * able to run on a run whose own transcript was reconciled long ago (#5831).
+ */
+export function getSiblingReconciledUsageRunIds() {
+ return Object.keys(usageData?.siblingReconciledRuns || {});
+}
+
export async function markUsageRunReconciled(runId) {
if (!runId) return;
if (!usageData) await loadUsage();
@@ -316,27 +325,47 @@ export async function markUsageRunReconciled(runId) {
}
/**
- * Replace historical per-run estimates with transcript measurements.
+ * Replace historical per-run estimates with transcript measurements, and add
+ * the nested-CLI sessions a run's own provider never accounted for.
*
- * The original estimate is subtracted from the exact configured provider/model
- * bucket that received it, then the measured records are added. Flat day totals
- * are rebuilt from the provider split so report residual reconciliation cannot
- * resurrect the removed estimate as a synthetic legacy row.
+ * Two independent halves, each with its own idempotency marker:
+ *
+ * PARENT (`estimate` + `measured`, keyed by `reconciledRuns`) — the original
+ * estimate is subtracted from the exact configured provider/model bucket
+ * that received it, then the measured records are added.
+ * SIBLING (`siblings`, keyed by `siblingReconciledRuns`) — a nested reviewer
+ * CLI's session is a pure ADDITION to ITS OWN provider's bucket. It has no
+ * estimate to remove (nothing ever recorded it), and it must never land in
+ * the parent's bucket — that is exactly the mis-attribution #5831 fixes.
+ * A sibling-only correction therefore does not require a pre-existing day
+ * bucket for the parent provider; the target bucket is created on demand.
+ *
+ * Flat day totals are rebuilt from the provider split so report residual
+ * reconciliation cannot resurrect the removed estimate as a synthetic legacy row.
*/
export async function applyHistoricalUsageCorrections(corrections = []) {
if (!usageData) await loadUsage();
usageData.reconciledRuns ??= {};
+ // Additive: absent on every install that predates the sibling scan, which
+ // reads as "no run has had its nested sessions attributed yet".
+ usageData.siblingReconciledRuns ??= {};
let corrected = 0;
const correctedRunIds = [];
+ const pendingParent = (correction) => Boolean(correction?.measured)
+ && !usageData.reconciledRuns[correction.runId]
+ && Boolean(usageData.dailyActivity?.[correction.day]?.byProvider?.[correction.providerId]);
+ const pendingSiblings = (correction) => (correction?.siblings?.length > 0)
+ && !usageData.siblingReconciledRuns[correction.runId];
const eligible = corrections.filter((correction) => {
const { runId, day: dayKey, providerId } = correction || {};
- return runId && !usageData.reconciledRuns[runId] && dayKey && providerId
- && usageData.dailyActivity?.[dayKey]?.byProvider?.[providerId];
+ if (!runId || !dayKey || !providerId) return false;
+ return pendingParent(correction) || pendingSiblings(correction);
});
const providerScopes = new Map();
const modelScopes = new Map();
for (const [index, correction] of eligible.entries()) {
if (index > 0 && index % BACKFILL_YIELD_INTERVAL === 0) await yieldToEventLoop();
+ if (!pendingParent(correction)) continue;
const providerKey = `${correction.day}\u0000${correction.providerId}`;
const providerDay = usageData.dailyActivity[correction.day].byProvider[correction.providerId];
if (!providerScopes.has(providerKey)) {
@@ -353,59 +382,116 @@ export async function applyHistoricalUsageCorrections(corrections = []) {
}
}
+ // Add one usage record to its OWN provider's day bucket and to the flat
+ // all-time rollups. Shared by the parent swap and the sibling add — the only
+ // difference between them is which bucket `record.providerId` names.
+ const addRecord = (day, record) => {
+ const bucket = providerDayBucket(day, record.providerId);
+ const hadProviderCounts = hasUsageCounts(bucket);
+ adjustCounts(bucket, record, 1);
+ bucket.source = hadProviderCounts
+ ? mergeSource(bucket.source, record.source || 'measured')
+ : (record.source || 'measured');
+ if (record?.model) {
+ const target = modelDayBucket(bucket, record.model);
+ const hadCounts = hasUsageCounts(target);
+ adjustCounts(target, record, 1);
+ target.source = hadCounts
+ ? mergeSource(target.source, record.source || 'measured')
+ : (record.source || 'measured');
+ }
+ usageData.totalMessages = Math.max(0, (usageData.totalMessages || 0) + (record.messages || 0));
+ usageData.totalTokens.input = Math.max(0, (usageData.totalTokens.input || 0)
+ + (record.tokensIn || 0) + (record.cacheReadTokens || 0) + (record.cacheWriteTokens || 0));
+ usageData.totalTokens.output = Math.max(0, (usageData.totalTokens.output || 0) + (record.tokensOut || 0));
+ usageData.byProvider[record.providerId] ??= { name: bucket.name, sessions: 0, messages: 0, tokens: 0 };
+ usageData.byProvider[record.providerId].messages += record.messages || 0;
+ usageData.byProvider[record.providerId].tokens += record.tokensOut || 0;
+ if (record?.model) {
+ usageData.byModel[record.model] ??= { sessions: 0, messages: 0, tokens: 0 };
+ usageData.byModel[record.model].messages += record.messages || 0;
+ usageData.byModel[record.model].tokens += record.tokensOut || 0;
+ }
+ };
+
for (const [index, correction] of eligible.entries()) {
if (index > 0 && index % BACKFILL_YIELD_INTERVAL === 0) await yieldToEventLoop();
const { runId, day: dayKey, providerId, model, estimate, measured } = correction || {};
- const day = usageData.dailyActivity?.[dayKey];
- const providerDay = day?.byProvider?.[providerId];
+ const applyParent = pendingParent(correction);
+ const applySiblings = pendingSiblings(correction);
+ // A sibling-only correction can target a day that has no bucket for the
+ // PARENT provider (the run may predate provider/model breakdowns entirely),
+ // so the day itself is created on demand rather than required.
+ if (!usageData.dailyActivity[dayKey]) {
+ usageData.dailyActivity[dayKey] = { sessions: 0, messages: 0, tokens: 0, byProvider: {} };
+ cacheActivityDay(dayKey);
+ }
+ const day = usageData.dailyActivity[dayKey];
- const measuredRecords = Array.isArray(measured) ? measured : [measured];
- const measuredTotals = recordTotals(measuredRecords);
- const oldModelDay = model ? providerDay.byModel?.[model] : null;
+ if (applyParent) {
+ const providerDay = day.byProvider[providerId];
+ const measuredRecords = Array.isArray(measured) ? measured : [measured];
+ const measuredTotals = recordTotals(measuredRecords);
+ const oldModelDay = model ? providerDay.byModel?.[model] : null;
- adjustCounts(providerDay, estimate, -1);
- if (oldModelDay) {
- adjustCounts(oldModelDay, estimate, -1);
- }
+ adjustCounts(providerDay, estimate, -1);
+ if (oldModelDay) {
+ adjustCounts(oldModelDay, estimate, -1);
+ }
- for (const record of measuredRecords) {
- adjustCounts(providerDay, record, 1);
- if (record?.model) {
- const target = modelDayBucket(providerDay, record.model);
- const hadCounts = hasUsageCounts(target);
- adjustCounts(target, record, 1);
- target.source = hadCounts ? mergeSource(target.source, 'measured') : 'measured';
+ for (const record of measuredRecords) {
+ adjustCounts(providerDay, record, 1);
+ if (record?.model) {
+ const target = modelDayBucket(providerDay, record.model);
+ const hadCounts = hasUsageCounts(target);
+ adjustCounts(target, record, 1);
+ target.source = hadCounts ? mergeSource(target.source, 'measured') : 'measured';
+ }
}
- }
- const delta = {
- messages: measuredTotals.messages - (estimate?.messages || 0),
- tokensIn: measuredTotals.tokensIn + measuredTotals.cacheReadTokens + measuredTotals.cacheWriteTokens
- - (estimate?.tokensIn || 0),
- tokensOut: measuredTotals.tokensOut - (estimate?.tokensOut || 0)
- };
- usageData.totalMessages = Math.max(0, (usageData.totalMessages || 0) + delta.messages);
- usageData.totalTokens.input = Math.max(0, (usageData.totalTokens.input || 0) + delta.tokensIn);
- usageData.totalTokens.output = Math.max(0, (usageData.totalTokens.output || 0) + delta.tokensOut);
-
- const allProvider = usageData.byProvider?.[providerId];
- if (allProvider) {
- allProvider.messages = Math.max(0, (allProvider.messages || 0) + delta.messages);
- allProvider.tokens = Math.max(0, (allProvider.tokens || 0) + delta.tokensOut);
- }
- if (model && usageData.byModel?.[model]) {
- usageData.byModel[model].messages = Math.max(0, (usageData.byModel[model].messages || 0) - (estimate?.messages || 0));
- usageData.byModel[model].tokens = Math.max(0, (usageData.byModel[model].tokens || 0) - (estimate?.tokensOut || 0));
+ const delta = {
+ messages: measuredTotals.messages - (estimate?.messages || 0),
+ tokensIn: measuredTotals.tokensIn + measuredTotals.cacheReadTokens + measuredTotals.cacheWriteTokens
+ - (estimate?.tokensIn || 0),
+ tokensOut: measuredTotals.tokensOut - (estimate?.tokensOut || 0)
+ };
+ usageData.totalMessages = Math.max(0, (usageData.totalMessages || 0) + delta.messages);
+ usageData.totalTokens.input = Math.max(0, (usageData.totalTokens.input || 0) + delta.tokensIn);
+ usageData.totalTokens.output = Math.max(0, (usageData.totalTokens.output || 0) + delta.tokensOut);
+
+ const allProvider = usageData.byProvider?.[providerId];
+ if (allProvider) {
+ allProvider.messages = Math.max(0, (allProvider.messages || 0) + delta.messages);
+ allProvider.tokens = Math.max(0, (allProvider.tokens || 0) + delta.tokensOut);
+ }
+ if (model && usageData.byModel?.[model]) {
+ usageData.byModel[model].messages = Math.max(0, (usageData.byModel[model].messages || 0) - (estimate?.messages || 0));
+ usageData.byModel[model].tokens = Math.max(0, (usageData.byModel[model].tokens || 0) - (estimate?.tokensOut || 0));
+ }
+ for (const record of measuredRecords) {
+ if (!record?.model) continue;
+ usageData.byModel[record.model] ??= { sessions: 0, messages: 0, tokens: 0 };
+ usageData.byModel[record.model].messages += record.messages || 0;
+ usageData.byModel[record.model].tokens += record.tokensOut || 0;
+ }
+ usageData.reconciledRuns[runId] = new Date().toISOString();
}
- for (const record of measuredRecords) {
- if (!record?.model) continue;
- usageData.byModel[record.model] ??= { sessions: 0, messages: 0, tokens: 0 };
- usageData.byModel[record.model].messages += record.messages || 0;
- usageData.byModel[record.model].tokens += record.tokensOut || 0;
+
+ if (applySiblings) {
+ // Routed by `record.providerId`, never the run's provider: a nested grok
+ // review inside a Claude run is grok's spend. There is no estimate to
+ // remove — nothing ever recorded these tokens at all.
+ for (const record of correction.siblings) {
+ if (!record?.providerId) continue;
+ addRecord(day, record);
+ }
}
+ // Marked whenever this run's sibling pass actually ran — including a run
+ // whose only correction was the parent swap — so a second backfill can't
+ // add the same nested session twice.
+ if (correction.siblingScanned) usageData.siblingReconciledRuns[runId] = new Date().toISOString();
rebuildDayTotals(day);
- usageData.reconciledRuns[runId] = new Date().toISOString();
corrected++;
correctedRunIds.push(runId);
}
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index afe75b2d15..870f481152 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -1151,6 +1151,79 @@ describe('usage.js — historical transcript corrections (#3156)', () => {
});
expect(report.providers.some((provider) => provider.id === 'legacy')).toBe(false);
});
+
+ // #5831 — a nested `--review-with grok` pass inside this Claude run. The
+ // tokens belong to grok, and the run's own measured Claude counts must not
+ // move a single token.
+ it('routes a sibling record to its own provider without touching the parent', async () => {
+ const parentCorrection = {
+ runId: 'run-example-1',
+ day: dayKey,
+ providerId,
+ model,
+ estimate: { messages: 1, tokensIn: 20, tokensOut: 50 },
+ measured: [{ providerId, model, messages: 2, tokensIn: 100, tokensOut: 200, cacheReadTokens: 1000, cacheWriteTokens: 10, source: 'measured' }],
+ siblings: [{
+ providerId: 'grok-cli',
+ role: 'sibling',
+ model: 'example-grok-model',
+ messages: 1,
+ tokensIn: 3000,
+ tokensOut: 700,
+ cacheReadTokens: 6000,
+ cacheWriteTokens: 0,
+ source: 'measured'
+ }],
+ siblingScanned: true
+ };
+
+ expect(await applyHistoricalUsageCorrections([parentCorrection])).toMatchObject({ corrected: 1 });
+ const day = getUsage().dailyActivity[dayKey];
+ expect(day.byProvider[providerId]).toMatchObject({ tokensIn: 100, tokensOut: 200, cacheReadTokens: 1000 });
+ expect(day.byProvider['grok-cli']).toMatchObject({
+ messages: 1,
+ tokensIn: 3000,
+ tokensOut: 700,
+ cacheReadTokens: 6000,
+ source: 'measured'
+ });
+ expect(day.byProvider['grok-cli'].byModel['example-grok-model']).toMatchObject({ tokensOut: 700 });
+ // Both halves are idempotent, under their own independent markers.
+ const afterFirst = structuredClone(getUsage());
+ expect(await applyHistoricalUsageCorrections([parentCorrection])).toMatchObject({ corrected: 0 });
+ expect(getUsage()).toEqual(afterFirst);
+ });
+
+ // The parent pass ran long ago, so there is no estimate left to remove and no
+ // reason to require a bucket for the parent provider on the target day.
+ it('applies a sibling-only correction on a day with no parent bucket', async () => {
+ const correction = {
+ runId: 'run-example-2',
+ day: '2026-07-05',
+ providerId,
+ model,
+ estimate: null,
+ measured: null,
+ siblings: [{
+ providerId: 'antigravity-cli',
+ role: 'sibling',
+ model: 'example-agy-model',
+ messages: 1,
+ tokensIn: 100,
+ tokensOut: 50,
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ source: 'estimate'
+ }],
+ siblingScanned: true
+ };
+
+ expect(await applyHistoricalUsageCorrections([correction])).toMatchObject({ corrected: 1 });
+ const day = getUsage().dailyActivity['2026-07-05'];
+ expect(day.byProvider[providerId]).toBeUndefined();
+ expect(day.byProvider['antigravity-cli']).toMatchObject({ tokensIn: 100, tokensOut: 50, source: 'estimate' });
+ expect(day).toMatchObject({ messages: 1, tokensOut: 50, tokens: 50 });
+ });
});
diff --git a/server/services/usageBackfill.js b/server/services/usageBackfill.js
index 2219086e28..f9a6550806 100644
--- a/server/services/usageBackfill.js
+++ b/server/services/usageBackfill.js
@@ -3,8 +3,10 @@ import { homedir } from 'os';
import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
import {
applyHistoricalUsageCorrections,
- getReconciledUsageRunIds
+ getReconciledUsageRunIds,
+ getSiblingReconciledUsageRunIds
} from './usage.js';
+import { listProviders } from './providers.js';
import { mergeUsageClaims, snapshotUsageClaims } from './usageReconciler.js';
let job = {
@@ -24,8 +26,18 @@ const markRunMetadata = async (corrections) => {
for (const correction of corrections) {
const metadata = await readJSONFile(correction.metadataPath, null);
if (!metadata) continue;
- metadata.usageReconciled = true;
- metadata.usageReconciledAt = new Date().toISOString();
+ const now = new Date().toISOString();
+ // The two passes carry independent markers. A sibling-only correction must
+ // NOT stamp `usageReconciled` — that would tell a later backfill the run's
+ // own estimate had already been replaced when it never was.
+ if (correction.measured) {
+ metadata.usageReconciled = true;
+ metadata.usageReconciledAt = now;
+ }
+ if (correction.siblingScanned) {
+ metadata.usageSiblingsReconciled = true;
+ metadata.usageSiblingsReconciledAt = now;
+ }
await atomicWrite(correction.metadataPath, metadata);
}
};
@@ -38,10 +50,11 @@ export function getHistoricalUsageBackfillStatus() {
* Start the one-shot historical repair. The explicit POST route is the only
* caller; no boot hook or schedule invokes this function.
*/
-export function startHistoricalUsageBackfill({
+export async function startHistoricalUsageBackfill({
runsDir = PATHS.runs,
home = homedir(),
- WorkerClass = Worker
+ WorkerClass = Worker,
+ providers = null
} = {}) {
if (job.status === 'running') return publicJob();
@@ -56,11 +69,20 @@ export function startHistoricalUsageBackfill({
completedAt: null
};
+ // Resolved HERE, not inside the worker: the toolkit singleton that backs
+ // `listProviders()` is never initialized in a worker thread, so a worker-side
+ // lookup would silently find no provider to attribute a nested session to.
+ // `job.status` is already `running` above, so the await can't let a second
+ // POST start a duplicate scan.
+ const providerList = providers ?? await listProviders().catch(() => []);
+
const worker = new WorkerClass(new URL('./usageBackfillWorker.js', import.meta.url), {
workerData: {
runsDir,
home,
reconciledRunIds: getReconciledUsageRunIds(),
+ siblingReconciledRunIds: getSiblingReconciledUsageRunIds(),
+ providers: providerList,
// The worker gets its own empty copy of usageReconciler.js's claim
// ledger (a separate module instance) — seed it from this thread's
// ledger so a message the live completion path already billed isn't
@@ -107,6 +129,7 @@ export function startHistoricalUsageBackfill({
return publicJob();
}
+
export function __resetHistoricalUsageBackfillForTests() {
job = {
status: 'idle',
diff --git a/server/services/usageBackfill.test.js b/server/services/usageBackfill.test.js
index 63fd6d2f14..003fad9a66 100644
--- a/server/services/usageBackfill.test.js
+++ b/server/services/usageBackfill.test.js
@@ -12,7 +12,14 @@ vi.mock('./usage.js', () => ({
corrected: 1,
correctedRunIds: ['run-example-1']
}),
- getReconciledUsageRunIds: vi.fn().mockReturnValue(['run-live'])
+ getReconciledUsageRunIds: vi.fn().mockReturnValue(['run-live']),
+ getSiblingReconciledUsageRunIds: vi.fn().mockReturnValue(['run-siblings-done'])
+}));
+
+vi.mock('./providers.js', () => ({
+ listProviders: vi.fn().mockResolvedValue([
+ { id: 'grok-cli', type: 'cli', command: 'grok', enabled: true, defaultModel: 'example-grok-model' }
+ ])
}));
const {
@@ -41,7 +48,7 @@ beforeEach(() => {
describe('historical usage backfill job', () => {
it('runs scanning off-thread and exposes progress through status', async () => {
- const started = startHistoricalUsageBackfill({
+ const started = await startHistoricalUsageBackfill({
runsDir: '/example/runs',
home: '/example/home',
WorkerClass: FakeWorker
@@ -52,8 +59,15 @@ describe('historical usage backfill job', () => {
expect(worker.options.workerData).toMatchObject({
runsDir: '/example/runs',
home: '/example/home',
- reconciledRunIds: ['run-live']
+ reconciledRunIds: ['run-live'],
+ // The sibling pass has its own marker so it can run on a run whose own
+ // transcript was reconciled long ago (#5831).
+ siblingReconciledRunIds: ['run-siblings-done']
});
+ // The provider list is resolved on THIS thread: the worker never has an
+ // initialized toolkit, so a worker-side lookup would find no provider to
+ // attribute a nested session to.
+ expect(worker.options.workerData.providers).toHaveLength(1);
worker.emit('message', { type: 'progress', progress: { processed: 2, total: 5, found: 1 } });
await vi.waitFor(() => expect(getHistoricalUsageBackfillStatus()).toMatchObject({
diff --git a/server/services/usageBackfillWorker.js b/server/services/usageBackfillWorker.js
index 9cf0ff3ffb..baf2cb9ef7 100644
--- a/server/services/usageBackfillWorker.js
+++ b/server/services/usageBackfillWorker.js
@@ -9,18 +9,48 @@ const listRunIds = async (runsDir) => readdir(runsDir, { withFileTypes: true })
.then((entries) => entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name))
.catch(() => []);
-const isMeasured = (record) => (Array.isArray(record) ? record : [record])
- .some((entry) => entry?.source === 'measured');
+const asList = (records) => (Array.isArray(records) ? records.flat(Infinity) : [records]);
+
+/**
+ * Is this correction worth persisting?
+ *
+ * A `measured` parent record is the original #3124 case. A `source: 'estimate'`
+ * record from a TRANSCRIPT is not the same thing as the prompt/stdout estimate
+ * it replaces — Antigravity writes no token counts at all, so every one of its
+ * rows is chars/4 of the real transcript, which is still far closer to the truth
+ * than chars/4 of the task description. Dropping those would leave `agy` spend
+ * permanently invisible, so a sibling record counts regardless of its source.
+ */
+const isWorthRecording = (records, siblings) => siblings.length > 0
+ || records.some((entry) => entry?.source === 'measured' || entry?.source === 'mixed');
/**
* Read historical run artifacts and produce estimate→measurement corrections.
* This function runs inside a worker in production so parsing large JSONL files
* never blocks the server event loop; it is exported for fixture-based tests.
+ *
+ * Two independent passes share one walk of the run directory:
+ *
+ * parent — replace a run's own prompt/stdout estimate with its CLI's measured
+ * counts. Runs once per run (`reconciledRunIds` / `usageReconciled`).
+ * sibling — attribute a nested reviewer CLI's session (a `--review-with`
+ * grok/antigravity pass leaves a session but never a PortOS run) to
+ * ITS provider. This must run even on a run whose parent pass is
+ * already done, so it carries its own marker
+ * (`siblingReconciledRunIds` / `usageSiblingsReconciled`) — without
+ * a separate one, either every already-measured Claude run stays
+ * blind to its nested grok spend, or the parent swap re-applies.
+ *
+ * @param {{ providers?: Array<object> }} args `providers` is the install's
+ * provider list, passed in from the main thread: the toolkit singleton this
+ * worker would need to resolve it itself is never initialized here.
*/
export async function scanHistoricalUsage({
runsDir,
home,
reconciledRunIds = [],
+ siblingReconciledRunIds = [],
+ providers = null,
claimsSeed = null,
onProgress = () => {}
}) {
@@ -32,17 +62,25 @@ export async function scanHistoricalUsage({
// sibling `claimsSnapshot` in the return value).
if (claimsSeed) mergeUsageClaims(claimsSeed);
const reconciled = new Set(reconciledRunIds);
+ const siblingReconciled = new Set(siblingReconciledRunIds);
+ const canScanSiblings = Array.isArray(providers) && providers.length > 0;
const candidates = [];
for (const runId of await listRunIds(runsDir)) {
- if (reconciled.has(runId)) continue;
const metadataPath = join(runsDir, runId, 'metadata.json');
const metadata = await readJSONFile(metadataPath, null);
- if (!metadata || metadata.usageReconciled || !metadata.providerId || !metadata.workspacePath
+ if (!metadata || !metadata.providerId || !metadata.workspacePath
|| typeof metadata.startTime !== 'string' || typeof metadata.endTime !== 'string'
- || !Number.isFinite(Date.parse(metadata.startTime)) || !Number.isFinite(Date.parse(metadata.endTime))
- || !transcriptFamily(metadata)) continue;
- candidates.push({ runId, metadataPath, metadata });
+ || !Number.isFinite(Date.parse(metadata.startTime)) || !Number.isFinite(Date.parse(metadata.endTime))) continue;
+ const parentPending = !reconciled.has(runId) && !metadata.usageReconciled
+ && Boolean(transcriptFamily(metadata));
+ // The sibling pass has no parent-family precondition: an Ollama-backed run
+ // that bash-launched `grok` for its review leaves a grok session and writes
+ // no transcript of its own.
+ const siblingPending = canScanSiblings
+ && !siblingReconciled.has(runId) && !metadata.usageSiblingsReconciled;
+ if (!parentPending && !siblingPending) continue;
+ candidates.push({ runId, metadataPath, metadata, parentPending, siblingPending });
}
candidates.sort((a, b) => Date.parse(a.metadata.startTime) - Date.parse(b.metadata.startTime));
@@ -58,16 +96,31 @@ export async function scanHistoricalUsage({
cacheReadTokens: 0,
cacheWriteTokens: 0
};
- const measured = await reconcileRunUsage(candidate.metadata, estimate, { home });
- if (isMeasured(measured)) {
+ const records = asList(await reconcileRunUsage(candidate.metadata, estimate, {
+ home,
+ providers: candidate.siblingPending ? providers : null
+ }));
+ const siblings = records.filter((entry) => entry?.role === 'sibling');
+ // A run whose parent pass already ran still gets its transcript re-read (the
+ // sibling scan shares one reconcile call), but those parent records must be
+ // discarded — re-applying the swap would subtract an estimate that is no
+ // longer in the bucket.
+ const parentRecords = candidate.parentPending
+ ? records.filter((entry) => entry?.role !== 'sibling')
+ : [];
+ if (isWorthRecording(parentRecords, siblings)) {
corrections.push({
runId: candidate.runId,
metadataPath: candidate.metadataPath,
day: candidate.metadata.endTime.slice(0, 10),
providerId: candidate.metadata.providerId,
model: candidate.metadata.model ?? null,
- estimate,
- measured
+ // Null when the parent pass already ran — the day bucket holds measured
+ // counts by then, and there is no estimate left to remove.
+ estimate: parentRecords.length ? estimate : null,
+ measured: parentRecords.length ? parentRecords : null,
+ siblings,
+ siblingScanned: candidate.siblingPending
});
}
processed++;
diff --git a/server/services/usageBackfillWorker.test.js b/server/services/usageBackfillWorker.test.js
index 9a4b901ddc..2c172b0097 100644
--- a/server/services/usageBackfillWorker.test.js
+++ b/server/services/usageBackfillWorker.test.js
@@ -97,3 +97,87 @@ describe('historical usage worker', () => {
expect(result.corrections).toEqual([]);
});
});
+
+// A nested `--review-with grok` pass leaves a grok session but never a PortOS
+// run, so historical repair has to find it under the PARENT run's window and
+// attribute it to grok — including on a run whose own transcript was
+// reconciled long ago (#5831).
+describe('historical sibling-family attribution', () => {
+ const GROK_MODEL = 'example-grok-model';
+ const GROK_PROVIDER = { id: 'grok-cli', type: 'cli', command: 'grok', enabled: true, defaultModel: GROK_MODEL };
+ const CLAUDE_PROVIDER = { id: 'claude-code-tui', type: 'tui', command: 'claude', enabled: true, defaultModel: 'claude-opus-5' };
+
+ const writeGrokSession = async () => {
+ const dir = join(home, '.grok', 'sessions', encodeURIComponent(workspace), 'session-aaaa');
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'updates.jsonl'), JSON.stringify({
+ timestamp: Math.round(Date.parse('2026-07-01T10:05:00.000Z') / 1000),
+ method: '_x.ai/session/update',
+ params: {
+ sessionId: 'session-aaaa',
+ update: {
+ sessionUpdate: 'turn_completed',
+ prompt_id: 'prompt-1',
+ usage: {
+ inputTokens: 9_000,
+ outputTokens: 700,
+ totalTokens: 9_700,
+ cachedReadTokens: 6_000,
+ cacheCreationTokens: 0,
+ reasoningTokens: 0,
+ modelUsage: { [GROK_MODEL]: { inputTokens: 9_000, outputTokens: 700 } }
+ }
+ },
+ _meta: { agentTimestampMs: Date.parse('2026-07-01T10:05:00.000Z') }
+ }
+ }));
+ };
+
+ const reconciledRun = {
+ providerId: 'claude-code-tui',
+ model: 'claude-opus-5',
+ workspacePath: workspace,
+ promptLength: 80,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z',
+ usageReconciled: true
+ };
+
+ it('attributes a nested grok session on a run whose parent pass already ran', async () => {
+ await writeRun('run-already-measured', reconciledRun);
+ await writeGrokSession();
+
+ const result = await scanHistoricalUsage({ runsDir: root, home, providers: [CLAUDE_PROVIDER, GROK_PROVIDER] });
+ expect(result.corrections).toHaveLength(1);
+ const [correction] = result.corrections;
+ // No parent half: the run's own estimate was replaced long ago, so there is
+ // nothing left to subtract and re-applying the swap would corrupt the day.
+ expect(correction.measured).toBeNull();
+ expect(correction.estimate).toBeNull();
+ expect(correction.siblings).toHaveLength(1);
+ expect(correction.siblings[0]).toMatchObject({
+ providerId: 'grok-cli',
+ role: 'sibling',
+ source: 'measured',
+ tokensIn: 3_000,
+ cacheReadTokens: 6_000,
+ tokensOut: 700
+ });
+ });
+
+ it('leaves an already-sibling-scanned run alone', async () => {
+ await writeRun('run-already-scanned', { ...reconciledRun, usageSiblingsReconciled: true });
+ await writeGrokSession();
+
+ const result = await scanHistoricalUsage({ runsDir: root, home, providers: [CLAUDE_PROVIDER, GROK_PROVIDER] });
+ expect(result.corrections).toEqual([]);
+ });
+
+ it('does no sibling work at all when the install has no provider list', async () => {
+ await writeRun('run-already-measured', reconciledRun);
+ await writeGrokSession();
+
+ const result = await scanHistoricalUsage({ runsDir: root, home });
+ expect(result.corrections).toEqual([]);
+ });
+});
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index d2f7f12229..6a8bb0e34f 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -17,6 +17,18 @@
* candidate set is exact; each session file is then windowed by timestamp.
* Codex — rollouts are filed by date, so we scan the run's date directories
* and keep sessions whose `session_meta.cwd` matches.
+ * Grok — sessions live under `encodeURIComponent(cwd)`, so that lookup is
+ * exact too; turns are windowed by the event stream's own timestamps.
+ * Antigravity — `history.jsonl` maps a workspace to a conversation id, and
+ * the brain transcript it names carries per-step timestamps.
+ *
+ * The scan is NOT limited to the run's own provider family. A CoS task that
+ * ships a PR with `--review-with grok,antigravity` bash-launches those CLIs as
+ * children of the parent agent: they leave a session on disk but never become a
+ * PortOS run, so nothing else would ever account for that spend and the parent's
+ * chars/4 estimate cannot see it. Every family's store is therefore searched in
+ * the run's workspace and window, and each session is billed to ITS OWN
+ * configured provider (#5831) — never folded into the parent's row.
*
* When nothing matches (a provider that writes no transcript, an unreadable
* home directory, an ambiguous window) the caller falls back to the existing
@@ -34,10 +46,16 @@ import { isFreeModelId, resolveModelRates } from '../lib/modelPricing.js';
import {
UNKNOWN_MODEL,
claudeProjectSlug,
+ decodeGrokSessionDir,
+ parseAgyTranscript,
parseClaudeTranscript,
parseCodexRollout,
+ parseAgyHistory,
+ parseGrokChatHistory,
+ parseGrokTurns,
totalTranscriptTokens
} from '../lib/providerTranscriptUsage.js';
+import { familyForProvider } from '../lib/providerFamilies.js';
import { markUsageRunReconciled, recordRunUsage } from './usage.js';
// Widen the correlation window past the recorded run bounds: the CLI writes its
@@ -121,8 +139,28 @@ const cwdMatches = (transcriptCwd, workspacePath) => {
return transcriptCwd.startsWith(`${workspacePath}/`);
};
+/**
+ * Does a session that ran `[startMs, endMs]` overlap the run window `[from, to]`?
+ * Used only where a store has no per-message timestamps (grok's chat_history),
+ * so the session is placed by its own summary. A session with no readable start
+ * cannot be placed at all and is NOT billed — the same rule `inWindow` applies
+ * to a timestamp-less message, for the same reason: attributing it would hand
+ * the same tokens to every run that ever reads the file.
+ */
+const windowOverlaps = (startMs, endMs, from, to) => {
+ if (!Number.isFinite(startMs)) return false;
+ const end = Number.isFinite(endMs) ? Math.max(endMs, startMs) : startMs;
+ if (from != null && end < from) return false;
+ if (to != null && startMs > to) return false;
+ return true;
+};
+
const CLAUDE_ID = /claude/i;
const CODEX_ID = /codex/i;
+const GROK_ID = /grok/i;
+// `agy` is a three-letter binary name, so it needs word boundaries or it would
+// match inside an unrelated id; `antigravity` is the long form of the same CLI.
+const AGY_ID = /(^|[^a-z0-9])agy([^a-z0-9]|$)|antigravity/i;
/**
* Which model id to record for a measured bucket.
@@ -167,12 +205,16 @@ function attributedModel(recordedModel, transcriptModel, singleModel) {
/**
* Which transcript family a provider writes, or null for providers that write
- * none (ollama, LM Studio, agy, grok, any API provider). Keyed off the provider
- * id and command, mirroring `providerModels.js`'s predicates — but kept local so
- * this service stays reachable from the completion hook without pulling in the
+ * none (ollama, LM Studio, any API provider). Keyed off the provider id and
+ * command, mirroring `providerModels.js`'s predicates — but kept local so this
+ * service stays reachable from the completion hook without pulling in the
* provider graph.
+ *
+ * The ids match `lib/providerFamilies.js`'s family ids on purpose: a sibling
+ * session found in a run's workspace is mapped back to an enabled provider
+ * through `familyForProvider`, so the two vocabularies have to agree.
* @param {{ providerId?: string|null, command?: string|null }} run
- * @returns {'claude'|'codex'|null}
+ * @returns {'claude'|'codex'|'grok'|'agy'|null}
*/
export function transcriptFamily({ providerId = null, command = null } = {}) {
const haystack = `${providerId || ''} ${command || ''}`;
@@ -180,10 +222,18 @@ export function transcriptFamily({ providerId = null, command = null } = {}) {
// but check codex first so a hypothetical `codex-claude` wrapper resolves to
// the CLI that actually writes the rollout.
if (CODEX_ID.test(haystack)) return 'codex';
+ if (GROK_ID.test(haystack)) return 'grok';
+ if (AGY_ID.test(haystack)) return 'agy';
if (CLAUDE_ID.test(haystack)) return 'claude';
return null;
}
+/** Every family whose CLI writes a readable session store. */
+export const TRANSCRIPT_FAMILIES = ['claude', 'codex', 'grok', 'agy'];
+
+/** `reconcileRunUsage` returns one record or several — normalize to a list. */
+const asRecordList = (records) => (Array.isArray(records) ? records : [records]);
+
/** List a directory, returning [] when it doesn't exist or can't be read. */
const listDir = async (dir) => readdir(dir).catch(() => []);
@@ -226,11 +276,15 @@ function codexDateDirs(root, fromMs, toMs) {
* @param {string} run.workspacePath cwd the run executed in
* @param {string|null} run.startTime ISO
* @param {string|null} run.endTime ISO
- * @param {'claude'|'codex'} run.family
+ * @param {'claude'|'codex'|'grok'|'agy'} run.family
* @param {string} [run.home] override for tests
- * @returns {Promise<null|{ source: 'measured', family: string, sessions: number,
- * model: string|null, messages: number, tokensIn: number, tokensOut: number,
- * cacheReadTokens: number, cacheWriteTokens: number }>}
+ * @returns {Promise<null|{ source: 'measured'|'estimate'|'mixed', family: string,
+ * sessions: number, model: string|null, messages: number, tokensIn: number,
+ * tokensOut: number, cacheReadTokens: number, cacheWriteTokens: number,
+ * byModel: object }>} `source` reflects what was actually read: grok is
+ * measured from a completed turn but estimated from chat history when a run
+ * died mid-turn, and Antigravity is always an estimate (it writes no token
+ * counts anywhere).
*/
export async function readMeasuredUsage({ workspacePath, startTime, endTime, family, home = homedir() } = {}) {
if (!workspacePath || !family) return null;
@@ -257,8 +311,15 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
// aggregate at the majority model.
const byModel = new Map();
- const fold = (parsed) => {
+ // How each folded session's counts were obtained. Grok can contribute both
+ // (a completed turn is measured; a killed session's chat_history is chars/4),
+ // and Antigravity is always an estimate — so the record's `source` is derived
+ // from what actually landed rather than assumed.
+ const sourcesSeen = new Set();
+
+ const fold = (parsed, source = 'measured') => {
if (!parsed || totalTranscriptTokens(parsed) === 0) return;
+ sourcesSeen.add(source);
totals.sessions += 1;
totals.messages += parsed.messages || 0;
totals.tokensIn += parsed.tokensIn || 0;
@@ -330,6 +391,87 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
reserveFrom(path, parsed);
fold(parsed);
}
+ } else if (family === 'grok') {
+ // `~/.grok/sessions/<encodeURIComponent(cwd)>/<session-id>/`. Decoding the
+ // folder name is an exact cwd lookup with no summary read, so an unrelated
+ // repo's sessions are never opened.
+ const sessionsRoot = join(home, '.grok', 'sessions');
+ for (const dirName of await listDir(sessionsRoot)) {
+ if (!cwdMatches(decodeGrokSessionDir(dirName), workspacePath)) continue;
+ const cwdDir = join(sessionsRoot, dirName);
+ for (const sessionId of await listDir(cwdDir)) {
+ const sessionDir = join(cwdDir, sessionId);
+ const updatesPath = join(sessionDir, 'updates.jsonl');
+ const updatesText = await tryReadFile(updatesPath);
+ // Sentinel, not truthiness: `turns > 0` means the session DID record
+ // billed turns, so it is measured even when this run's window share is
+ // zero. Falling through to the chars/4 estimate there would bill the
+ // same session twice, once per shape.
+ const parsed = updatesText
+ ? parseGrokTurns(updatesText, { from, to, exclude: excludeFor(updatesPath) })
+ : null;
+ if (parsed?.turns) {
+ reserveFrom(updatesPath, parsed);
+ fold(parsed, 'measured');
+ continue;
+ }
+
+ // No `turn_completed` at all — a run killed or interrupted mid-turn.
+ // chat_history.jsonl carries no timestamps, so the session is placed by
+ // summary.json and billed whole or not at all; the session-level claim
+ // is what stops two overlapping runs from each taking it.
+ const summary = await readJSONFile(join(sessionDir, 'summary.json'), null);
+ if (!summary) continue;
+ const startedMs = Date.parse(summary.created_at || '');
+ const endedMs = Date.parse(summary.last_active_at || summary.updated_at || summary.created_at || '');
+ if (!windowOverlaps(startedMs, endedMs, from, to)) continue;
+ const chatPath = join(sessionDir, 'chat_history.jsonl');
+ const chatText = await tryReadFile(chatPath);
+ if (!chatText) continue;
+ const claimKey = `${chatPath}:session`;
+ if (claimedMessages.has(claimKey)) continue;
+ const chat = parseGrokChatHistory(chatText);
+ const estimated = {
+ messages: chat.messages,
+ tokensIn: estimateTokensFromChars(chat.charsIn),
+ tokensOut: estimateTokensFromChars(chat.charsOut),
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0
+ };
+ if (totalTranscriptTokens(estimated) === 0) continue;
+ claimedMessages.add(claimKey);
+ reserved.push(claimKey);
+ const named = chat.model || summary.current_model_id || null;
+ const modelKey = named ?? UNKNOWN_MODEL;
+ fold({ ...estimated, models: named ? [named] : [], byModel: { [modelKey]: { ...estimated } } }, 'estimate');
+ }
+ }
+ } else if (family === 'agy') {
+ // Antigravity writes no token counts anywhere, so every row it produces is
+ // an honest chars/4 estimate. `history.jsonl` is the only cwd-keyed index;
+ // the brain transcript it points at carries the per-step timestamps that
+ // place the work inside a run's window.
+ const root = join(home, '.gemini', 'antigravity-cli');
+ const historyText = await tryReadFile(join(root, 'history.jsonl'));
+ for (const conversation of historyText ? parseAgyHistory(historyText) : []) {
+ if (!cwdMatches(conversation.workspace, workspacePath)) continue;
+ const transcriptPath = join(root, 'brain', conversation.conversationId, '.system_generated', 'logs', 'transcript.jsonl');
+ const text = await tryReadFile(transcriptPath);
+ if (!text) continue;
+ const parsed = parseAgyTranscript(text, { from, to, exclude: excludeFor(transcriptPath) });
+ const estimated = {
+ messages: parsed.messages,
+ tokensIn: estimateTokensFromChars(parsed.charsIn),
+ tokensOut: estimateTokensFromChars(parsed.charsOut),
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0
+ };
+ if (totalTranscriptTokens(estimated) === 0) continue;
+ reserveFrom(transcriptPath, parsed);
+ // No model is named anywhere in the transcript — the UNKNOWN_MODEL bucket
+ // lets the caller attribute it to the provider's own configured model.
+ fold({ ...estimated, models: [], byModel: { [UNKNOWN_MODEL]: { ...estimated } } }, 'estimate');
+ }
} else {
const sessionsRoot = join(home, '.codex', 'sessions');
for (const dir of codexDateDirs(sessionsRoot, from ?? Date.now(), to ?? from ?? Date.now())) {
@@ -411,89 +553,172 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
}
totals.model = [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
totals.byModel = Object.fromEntries(byModel);
+ totals.source = sourcesSeen.size === 1 ? [...sourcesSeen][0] : 'mixed';
return totals;
}
/**
- * Measured counts for a completed run, or the caller's estimate when no
- * transcript can be attributed. Always resolves — a transcript read must never
- * fail the run it describes — and always returns a usable record, so a run with
- * no transcript still contributes its estimate rather than recording nothing.
+ * Turn a `readMeasuredUsage` result into the per-model usage records
+ * `recordRunUsage` persists. `recordedModel` is what PortOS launched (or, for a
+ * sibling family, that provider's configured default) — used to name a bucket
+ * the transcript itself left unnamed.
*
- * @param {object} run PortOS run metadata (`providerId`, `model`,
- * `workspacePath`, `startTime`, `endTime`)
- * @param {{ tokensIn: number, tokensOut: number }} estimate fallback counts
- * Returns a single record, or an ARRAY of them when the transcript names more
- * than one model (a mid-run `/model` switch or a fallback) — `recordRunUsage`
- * accepts either, and splitting is what keeps each model priced at its own rate.
+ * Returns an ARRAY when the transcript named models (one record per model, so
+ * each is priced at its own rate) and a single record when it named none —
+ * the shape `reconcileRunUsage` has always handed back, kept as-is so a caller
+ * destructuring one form keeps working.
*
- * @param {{ home?: string }} [opts]
- * @returns {Promise<{ providerId: string|null, model: string|null, messages: number,
- * tokensIn: number, tokensOut: number, cacheReadTokens: number,
- * cacheWriteTokens: number, source: 'measured'|'estimate' }
- * | Array<object>>}
+ * `role` marks each record `parent` (the run's own provider) or `sibling` (a
+ * nested CLI's session found in the same workspace and window). The historical
+ * backfill needs that split — a parent record REPLACES an earlier estimate,
+ * while a sibling record is a pure addition to a different provider's bucket —
+ * and provider ids alone can't express it. `recordRunUsage` reads only the
+ * count fields, so the marker never reaches usage.json.
*/
-export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}) {
- const fallback = {
- providerId: run?.providerId ?? null,
- model: run?.model ?? null,
- messages: 1,
- tokensIn: Math.max(0, estimate?.tokensIn || 0),
- tokensOut: Math.max(0, estimate?.tokensOut || 0),
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- source: 'estimate'
- };
-
- const family = transcriptFamily({ providerId: run?.providerId, command: run?.command });
- if (!family) return fallback;
-
- // Best-effort: an unreadable home dir, a permissions error, or a CLI format
- // change must degrade to the estimate, never throw into the completion hook.
- const measured = await readMeasuredUsage({
- workspacePath: run?.workspacePath,
- startTime: run?.startTime,
- endTime: run?.endTime,
- family,
- home
- }).catch((err) => {
- console.error(`❌ Usage reconcile failed for ${run?.providerId}: ${err.message}`);
- return null;
- });
- if (!measured) return fallback;
-
- // A session can switch models mid-run, so split the record per model the
- // transcript actually names — billing every token at the launch-time model
- // would price a run that started on Opus and finished on Haiku entirely at
- // Opus rates. `byModel` is authoritative when present; fall back to one
- // aggregate record when the transcript named no model at all.
+function recordsFromMeasured(providerId, recordedModel, measured, role) {
+ // A family that mixed a measured session with an estimated one reports
+ // `mixed` on every record it produced: the two shapes fold into the same
+ // per-model buckets, so no record can honestly claim to be purely measured.
+ const source = measured.source || 'measured';
const perModel = Object.entries(measured.byModel || {});
if (perModel.length > 0) {
return perModel.map(([model, bucket]) => ({
- providerId: run?.providerId ?? null,
- model: attributedModel(run?.model ?? null, model, perModel.length === 1),
+ providerId,
+ role,
+ model: attributedModel(recordedModel ?? null, model, perModel.length === 1),
messages: bucket.messages || 0,
tokensIn: bucket.tokensIn,
tokensOut: bucket.tokensOut,
cacheReadTokens: bucket.cacheReadTokens,
cacheWriteTokens: bucket.cacheWriteTokens,
- source: 'measured'
+ source
}));
}
-
- return {
- providerId: run?.providerId ?? null,
+ return [{
+ providerId,
+ role,
// Prefer the model PortOS recorded (it carries the provider's own id shape,
// e.g. a Bedrock-prefixed id the pricing table resolves); fall back to the
// transcript's when PortOS captured none.
- model: run?.model ?? measured.model ?? null,
+ model: recordedModel ?? measured.model ?? null,
messages: measured.messages || 1,
tokensIn: measured.tokensIn,
tokensOut: measured.tokensOut,
cacheReadTokens: measured.cacheReadTokens,
cacheWriteTokens: measured.cacheWriteTokens,
- source: 'measured'
- };
+ source
+ }];
+}
+
+/**
+ * The enabled provider a sibling family's sessions should be billed to, or null
+ * when this install has none configured for that family.
+ *
+ * Null is the right answer for "no match" — inventing an `unknown grok` bucket
+ * would put spend on the cost report that no configured provider can explain.
+ * A `cli` record is preferred over a `tui` one (both drive the same binary, and
+ * a nested reviewer is always launched headless); `api` records are excluded
+ * outright because an API provider writes no local session file. Among several,
+ * the one whose configured model the transcript actually names wins, so an
+ * install with a light and a heavy grok provider attributes to the right one.
+ *
+ * @param {Array<object>} providers the install's provider records (`listProviders()`)
+ * @param {string} family a `TRANSCRIPT_FAMILIES` id
+ * @param {object} measured the `readMeasuredUsage` result, for its model names
+ */
+export function resolveFamilyProvider(providers, family, measured = null) {
+ const candidates = (providers || []).filter((provider) => (
+ provider?.enabled !== false && familyForProvider(provider) === family
+ ));
+ const byType = (type) => candidates.filter((provider) => provider.type === type);
+ const pool = byType('cli').length ? byType('cli') : byType('tui');
+ if (pool.length === 0) return null;
+ const named = new Set([measured?.model, ...Object.keys(measured?.byModel || {})]
+ .filter((model) => model && model !== UNKNOWN_MODEL));
+ return pool.find((provider) => named.has(provider.defaultModel)) ?? pool[0];
+}
+
+/**
+ * Measured counts for a completed run, or the caller's estimate when no
+ * transcript can be attributed. Always resolves — a transcript read must never
+ * fail the run it describes — and always returns a usable record, so a run with
+ * no transcript still contributes its estimate rather than recording nothing.
+ *
+ * **The scan is not limited to the run's own provider family.** A CoS task that
+ * ships a PR with `--review-with grok,antigravity` bash-launches those CLIs as
+ * CHILDREN of the parent agent — slashdo's review loop never becomes a PortOS
+ * run of its own, so nothing else would ever record that spend, and the parent's
+ * chars/4 estimate cannot see it either. Every family's session store is
+ * therefore searched in the run's workspace and window, and each session is
+ * attributed to ITS OWN provider (#5831). The per-message claim ledger stays
+ * the exclusivity mechanism, so a nested session is billed exactly once no
+ * matter how many overlapping runs can see it.
+ *
+ * @param {object} run PortOS run metadata (`providerId`, `model`,
+ * `workspacePath`, `startTime`, `endTime`)
+ * @param {{ tokensIn: number, tokensOut: number }} estimate fallback counts
+ * Returns a single record, or an ARRAY of them when the transcript names more
+ * than one model (a mid-run `/model` switch or a fallback), or when a sibling
+ * family's session was found — `recordRunUsage` accepts either, and splitting is
+ * what keeps each model and each provider priced on its own row.
+ *
+ * @param {{ home?: string, providers?: Array<object>|null }} [opts] `providers`
+ * enables the sibling scan; omitting it reconciles the parent family only
+ * (which is what a caller with no access to the provider list should do).
+ * @returns {Promise<object|Array<object>>}
+ */
+export async function reconcileRunUsage(run, estimate, { home = homedir(), providers = null } = {}) {
+ const workspacePath = run?.workspacePath;
+ const startTime = run?.startTime;
+ const endTime = run?.endTime;
+
+ // Best-effort: an unreadable home dir, a permissions error, or a CLI format
+ // change must degrade to the estimate, never throw into the completion hook.
+ const readFamily = (family) => readMeasuredUsage({ workspacePath, startTime, endTime, family, home })
+ .catch((err) => {
+ console.error(`❌ Usage reconcile failed for ${run?.providerId} (${family}): ${err.message}`);
+ return null;
+ });
+
+ const family = transcriptFamily({ providerId: run?.providerId, command: run?.command });
+ const measured = family ? await readFamily(family) : null;
+ const parent = measured
+ ? recordsFromMeasured(run?.providerId ?? null, run?.model ?? null, measured, 'parent')
+ : {
+ providerId: run?.providerId ?? null,
+ role: 'parent',
+ model: run?.model ?? null,
+ messages: 1,
+ tokensIn: Math.max(0, estimate?.tokensIn || 0),
+ tokensOut: Math.max(0, estimate?.tokensOut || 0),
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ source: 'estimate'
+ };
+
+ const siblings = [];
+ for (const sibling of Array.isArray(providers) && providers.length ? TRANSCRIPT_FAMILIES : []) {
+ if (sibling === family) continue;
+ // Resolve BEFORE reading. No enabled provider for this family means the
+ // session is skipped rather than opened as an `unknown` bucket the cost
+ // report can't explain — and skipping it before the read matters: a read
+ // CLAIMS the messages it folded, so reading first and discarding after
+ // would strand those keys and stop a later, correctly-configured run from
+ // ever billing them.
+ if (!resolveFamilyProvider(providers, sibling)) continue;
+ const siblingUsage = await readFamily(sibling);
+ if (!siblingUsage) continue;
+ // Re-resolve now that the transcript's model names can break a tie between
+ // several configured providers of the same family.
+ const provider = resolveFamilyProvider(providers, sibling, siblingUsage);
+ if (!provider) continue;
+ siblings.push(...asRecordList(recordsFromMeasured(provider.id, provider.defaultModel ?? null, siblingUsage, 'sibling')));
+ console.log(`💸 Nested ${sibling} session billed to ${provider.id} for run ${run?.id || 'unknown'}`);
+ }
+
+ // The parent's shape is preserved when nothing nested was found, so a caller
+ // that destructures a single record keeps working on every existing path.
+ return siblings.length ? [...asRecordList(parent), ...siblings] : parent;
}
/**
@@ -512,16 +737,25 @@ export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}
* @param {{ home?: string }} [opts] `home` overrides the transcript root (tests)
* @returns {Promise<void>}
*/
-export async function recordCompletedRunUsage(metadata, output, { home = homedir() } = {}) {
+export async function recordCompletedRunUsage(metadata, output, { home = homedir(), providers = null } = {}) {
if (!metadata?.providerId) return;
const estimate = {
tokensOut: estimateTokens(output),
tokensIn: estimateTokensFromChars(metadata.promptLength)
};
+ // The provider list enables the sibling-family scan (a nested `--review-with`
+ // grok/agy pass leaves a session but no PortOS run). Imported lazily and
+ // defensively: this module is also loaded inside the backfill worker thread,
+ // where the toolkit singleton is never initialized — that path is handed its
+ // providers through `workerData` instead, and must not drag the provider
+ // graph in at import time.
+ const resolved = providers ?? await import('./providers.js')
+ .then((module) => module.listProviders())
+ .catch(() => null);
// One catch for the whole chain: whatever fails — reading a transcript or
// persisting the record — usage accounting must not surface as a run failure.
- await reconcileRunUsage(metadata, estimate, { home })
+ await reconcileRunUsage(metadata, estimate, { home, providers: resolved })
.then(recordRunUsage)
.then(async () => {
if (!metadata?.id) return;
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index 9f9451f366..9b9c1b487c 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -14,6 +14,7 @@ const {
readMeasuredUsage,
reconcileRunUsage,
recordCompletedRunUsage,
+ resolveFamilyProvider,
__resetUsageClaims
} = await import('./usageReconciler.js');
@@ -106,8 +107,16 @@ describe('transcriptFamily', () => {
expect(transcriptFamily({ providerId: 'custom', command: '/usr/local/bin/claude' })).toBe('claude');
});
+ it('maps grok and antigravity provider ids to their own families', () => {
+ expect(transcriptFamily({ providerId: 'grok-cli' })).toBe('grok');
+ expect(transcriptFamily({ providerId: 'grok-tui' })).toBe('grok');
+ expect(transcriptFamily({ providerId: 'antigravity-cli' })).toBe('agy');
+ expect(transcriptFamily({ providerId: 'custom', command: '/usr/local/bin/agy' })).toBe('agy');
+ });
+
it('returns null for providers that write no transcript', () => {
- for (const providerId of ['ollama', 'lmstudio', 'agy', 'grok', 'kimi', '', null]) {
+ // `legacy` would match the `agy` binary name without word boundaries.
+ for (const providerId of ['ollama', 'lmstudio', 'kimi', 'legacy', '', null]) {
expect(transcriptFamily({ providerId })).toBeNull();
}
});
@@ -251,8 +260,10 @@ describe('reconcileRunUsage', () => {
const result = await reconcileRunUsage(run, { tokensIn: 30, tokensOut: 9999 }, { home });
// One model in the transcript → one record, carrying PortOS's model id.
+ // `role` marks it as the run's OWN provider rather than a nested CLI's.
expect(result).toEqual([{
providerId: 'claude-code-tui',
+ role: 'parent',
model: 'claude-opus-5',
messages: 2,
tokensIn: 15,
@@ -947,3 +958,261 @@ describe('keyless-line claims survive the file changing shape', () => {
expect((first?.tokensOut || 0) + (second?.tokensOut || 0)).toBe(100);
});
});
+
+// ---------------------------------------------------------------------------
+// Nested reviewer CLIs — grok and Antigravity (#5831)
+//
+// A CoS task that ships a PR with `--review-with grok,antigravity` bash-launches
+// those CLIs as CHILDREN of the parent agent. They leave a session on disk but
+// never become a PortOS run, so the parent's chars/4 estimate is the only thing
+// that ever gets recorded — and it can't see them.
+// ---------------------------------------------------------------------------
+
+const GROK_MODEL = 'example-grok-model';
+const GROK_PROVIDER = { id: 'grok-cli', type: 'cli', command: 'grok', enabled: true, defaultModel: GROK_MODEL };
+const AGY_PROVIDER = { id: 'antigravity-cli', type: 'cli', command: 'agy', enabled: true, defaultModel: 'example-agy-model' };
+const CLAUDE_PROVIDER = { id: 'claude-code', type: 'cli', command: 'claude', enabled: true, defaultModel: 'claude-opus-5' };
+
+const grokTurnLine = ({ promptId = 'prompt-1', ms, input = 15_000, cachedRead = 11_000, output = 1_800 }) => JSON.stringify({
+ timestamp: Math.round(ms / 1000),
+ method: '_x.ai/session/update',
+ params: {
+ sessionId: 'session-aaaa',
+ update: {
+ sessionUpdate: 'turn_completed',
+ prompt_id: promptId,
+ usage: {
+ inputTokens: input,
+ outputTokens: output,
+ totalTokens: input + output,
+ cachedReadTokens: cachedRead,
+ cacheCreationTokens: 0,
+ reasoningTokens: 0,
+ modelUsage: { [GROK_MODEL]: { inputTokens: input, outputTokens: output } }
+ }
+ },
+ _meta: { eventId: 'evt-1', agentTimestampMs: ms }
+ }
+});
+
+const writeGrokSession = async ({ sessionId = 'session-aaaa', cwd = WORKSPACE, updates = null, chat = null, summary = null }) => {
+ const dir = join(home, '.grok', 'sessions', encodeURIComponent(cwd), sessionId);
+ await mkdir(dir, { recursive: true });
+ if (updates) await writeFile(join(dir, 'updates.jsonl'), updates.join('\n'));
+ if (chat) await writeFile(join(dir, 'chat_history.jsonl'), chat.join('\n'));
+ if (summary) await writeFile(join(dir, 'summary.json'), JSON.stringify(summary));
+};
+
+const writeAgySession = async ({ conversationId = 'conv-aaaa', workspace = WORKSPACE, steps = [] }) => {
+ const root = join(home, '.gemini', 'antigravity-cli');
+ await mkdir(root, { recursive: true });
+ await writeFile(join(root, 'history.jsonl'), [
+ JSON.stringify({ display: '/status', timestamp: 1_800_000_000_000, type: 'slash_command', workspace }),
+ JSON.stringify({ display: 'review this', timestamp: 1_800_000_000_000, workspace, conversationId })
+ ].join('\n'));
+ const brain = join(root, 'brain', conversationId, '.system_generated', 'logs');
+ await mkdir(brain, { recursive: true });
+ await writeFile(join(brain, 'transcript.jsonl'), steps.join('\n'));
+};
+
+const agyStepLine = ({ index, type, createdAt, content }) => JSON.stringify({
+ step_index: index,
+ source: type === 'USER_INPUT' ? 'USER_EXPLICIT' : 'MODEL',
+ type,
+ status: 'DONE',
+ created_at: createdAt,
+ content
+});
+
+const RUN_WINDOW = { startTime: '2026-07-01T10:00:00.000Z', endTime: '2026-07-01T10:30:00.000Z' };
+const IN_WINDOW_MS = Date.parse('2026-07-01T10:10:00.000Z');
+const grokRun = { providerId: 'grok-cli', model: GROK_MODEL, workspacePath: WORKSPACE, ...RUN_WINDOW };
+const claudeRun = { providerId: 'claude-code', model: 'claude-opus-5', workspacePath: WORKSPACE, ...RUN_WINDOW };
+
+describe('resolveFamilyProvider', () => {
+ it('prefers a cli record over a tui one and never an api one', () => {
+ const providers = [
+ { id: 'grok', type: 'api', enabled: true, defaultModel: 'grok-4' },
+ { id: 'grok-tui', type: 'tui', command: 'grok', enabled: true, defaultModel: GROK_MODEL },
+ GROK_PROVIDER
+ ];
+ expect(resolveFamilyProvider(providers, 'grok')?.id).toBe('grok-cli');
+ });
+
+ it('falls back to a tui record when no cli one is configured', () => {
+ const providers = [{ id: 'grok-tui', type: 'tui', command: 'grok', enabled: true, defaultModel: GROK_MODEL }];
+ expect(resolveFamilyProvider(providers, 'grok')?.id).toBe('grok-tui');
+ });
+
+ it('breaks a tie with the model the transcript actually names', () => {
+ const providers = [
+ { id: 'grok-light', type: 'cli', command: 'grok', enabled: true, defaultModel: 'other-grok-model' },
+ GROK_PROVIDER
+ ];
+ const measured = { model: GROK_MODEL, byModel: { [GROK_MODEL]: {} } };
+ expect(resolveFamilyProvider(providers, 'grok', measured)?.id).toBe('grok-cli');
+ });
+
+ it('returns null when the family has no enabled provider', () => {
+ expect(resolveFamilyProvider([{ ...GROK_PROVIDER, enabled: false }], 'grok')).toBeNull();
+ expect(resolveFamilyProvider([CLAUDE_PROVIDER], 'grok')).toBeNull();
+ });
+});
+
+describe('grok sessions', () => {
+ it('measures a first-class grok run from its completed turns', async () => {
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ const [record] = await reconcileRunUsage(grokRun, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.source).toBe('measured');
+ expect(record.providerId).toBe('grok-cli');
+ expect(record.tokensIn).toBe(4_000);
+ expect(record.cacheReadTokens).toBe(11_000);
+ expect(record.tokensOut).toBe(1_800);
+ expect(record.model).toBe(GROK_MODEL);
+ });
+
+ it('estimates from chat history when the run died before any turn completed', async () => {
+ await writeGrokSession({
+ summary: {
+ info: { id: 'session-aaaa', cwd: WORKSPACE },
+ created_at: '2026-07-01T10:05:00.000Z',
+ last_active_at: '2026-07-01T10:20:00.000Z',
+ current_model_id: GROK_MODEL
+ },
+ chat: [
+ JSON.stringify({ type: 'user', content: [{ type: 'text', text: 'a'.repeat(400) }] }),
+ JSON.stringify({ type: 'assistant', content: 'b'.repeat(200), model_id: GROK_MODEL })
+ ]
+ });
+ const [record] = await reconcileRunUsage(grokRun, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.source).toBe('estimate');
+ expect(record.tokensIn).toBe(100);
+ expect(record.tokensOut).toBe(50);
+ expect(record.model).toBe(GROK_MODEL);
+ });
+
+ it('does not stack a chat-history estimate on a session that already recorded a turn', async () => {
+ await writeGrokSession({
+ updates: [grokTurnLine({ ms: IN_WINDOW_MS, input: 1_000, cachedRead: 0, output: 10 })],
+ summary: { info: { id: 'session-aaaa', cwd: WORKSPACE }, created_at: '2026-07-01T10:05:00.000Z' },
+ chat: [JSON.stringify({ type: 'user', content: 'x'.repeat(4_000) })]
+ });
+ const [record] = await reconcileRunUsage(grokRun, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.source).toBe('measured');
+ expect(record.tokensIn).toBe(1_000);
+ });
+
+ it('ignores a session from another workspace', async () => {
+ await writeGrokSession({ cwd: '/tmp/other-workspace', updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ const record = await reconcileRunUsage(grokRun, { tokensIn: 7, tokensOut: 9 }, { home });
+ expect(record.source).toBe('estimate');
+ expect(record.tokensIn).toBe(7);
+ });
+});
+
+describe('nested sibling-family attribution', () => {
+ it('bills a nested grok review to grok, not to the Claude parent', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ]);
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+
+ const records = await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, {
+ home,
+ providers: [CLAUDE_PROVIDER, GROK_PROVIDER]
+ });
+ const byProvider = Object.fromEntries(records.map((record) => [record.providerId, record]));
+ expect(Object.keys(byProvider).sort()).toEqual(['claude-code', 'grok-cli']);
+ // The nested grok tokens must not appear anywhere on the Claude row.
+ expect(byProvider['claude-code'].tokensOut).toBe(50);
+ expect(byProvider['claude-code'].cacheReadTokens).toBe(1000);
+ expect(byProvider['grok-cli'].tokensOut).toBe(1_800);
+ expect(byProvider['grok-cli'].cacheReadTokens).toBe(11_000);
+ expect(byProvider['grok-cli'].source).toBe('measured');
+ });
+
+ it('bills a nested Antigravity review as an estimate on the agy provider', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ]);
+ await writeAgySession({
+ steps: [
+ agyStepLine({ index: 0, type: 'USER_INPUT', createdAt: '2026-07-01T10:05:00Z', content: 'u'.repeat(400) }),
+ agyStepLine({ index: 1, type: 'PLANNER_RESPONSE', createdAt: '2026-07-01T10:06:00Z', content: 'p'.repeat(200) })
+ ]
+ });
+
+ const records = await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, {
+ home,
+ providers: [CLAUDE_PROVIDER, AGY_PROVIDER]
+ });
+ const agy = records.find((record) => record.providerId === 'antigravity-cli');
+ // Antigravity writes no token counts at all — this row is honest chars/4 of
+ // the real transcript and must never claim to be measured.
+ expect(agy.source).toBe('estimate');
+ expect(agy.tokensIn).toBe(100);
+ expect(agy.tokensOut).toBe(50);
+ // The transcript names no model, so the provider's own default is used.
+ expect(agy.model).toBe('example-agy-model');
+ });
+
+ it('skips a family with no enabled provider instead of opening an unknown bucket', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ]);
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+
+ const records = await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, {
+ home,
+ providers: [CLAUDE_PROVIDER]
+ });
+ for (const record of [records].flat()) expect(record.providerId).toBe('claude-code');
+ });
+
+ it('leaves a skipped family claimable by a later, configured run', async () => {
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ // First run: grok is not configured, so the session is skipped — and its
+ // turns must NOT be claimed, or they would be unbillable forever.
+ await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, { home, providers: [CLAUDE_PROVIDER] });
+ const records = await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, {
+ home,
+ providers: [CLAUDE_PROVIDER, GROK_PROVIDER]
+ });
+ expect(records.find((record) => record.providerId === 'grok-cli').tokensOut).toBe(1_800);
+ });
+
+ it('bills a nested session once across two overlapping runs in one cwd', async () => {
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ const providers = [CLAUDE_PROVIDER, GROK_PROVIDER];
+ const first = [await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, { home, providers })].flat();
+ const second = [await reconcileRunUsage(
+ { ...claudeRun, startTime: '2026-07-01T10:05:00.000Z', endTime: '2026-07-01T10:35:00.000Z' },
+ { tokensIn: 1, tokensOut: 1 },
+ { home, providers }
+ )].flat();
+ expect(first.find((record) => record.providerId === 'grok-cli').tokensOut).toBe(1_800);
+ expect(second.find((record) => record.providerId === 'grok-cli')).toBeUndefined();
+ });
+
+ it('reconciles the parent family only when no provider list is supplied', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ]);
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ const records = [await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, { home })].flat();
+ expect(records).toHaveLength(1);
+ expect(records[0].providerId).toBe('claude-code');
+ });
+
+ it('finds a nested session under a parent whose own provider writes no transcript', async () => {
+ await writeGrokSession({ updates: [grokTurnLine({ ms: IN_WINDOW_MS })] });
+ const records = [await reconcileRunUsage(
+ { providerId: 'ollama-local', model: 'qwen3.6:35b', workspacePath: WORKSPACE, ...RUN_WINDOW },
+ { tokensIn: 3, tokensOut: 4 },
+ { home, providers: [GROK_PROVIDER] }
+ )].flat();
+ // The parent keeps its estimate; the nested grok review gets its own row.
+ expect(records.find((record) => record.providerId === 'ollama-local').source).toBe('estimate');
+ expect(records.find((record) => record.providerId === 'grok-cli').tokensOut).toBe(1_800);
+ });
+});