The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { UsageTokenTotals } from "@t3tools/contracts"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Path from "effect/Path"; |
| 4 | |
| 5 | import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; |
| 6 | import { |
| 7 | tokenCount, |
| 8 | totalTokens, |
| 9 | type ProviderUsageReader, |
| 10 | type TranscriptUsageFormat, |
| 11 | type UsageRecord, |
| 12 | } from "@t3tools/provider-core/server/usage"; |
| 13 | |
| 14 | import type { GrokSettings } from "../settings.ts"; |
| 15 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 16 | |
| 17 | export const GROK_COST_USD_TICKS_PER_DOLLAR = 10_000_000_000; |
| 18 | |
| 19 | function grokCostTicksToUsd(ticks: unknown): number | null { |
| 20 | if (typeof ticks !== "number" || !Number.isFinite(ticks) || ticks < 0) return null; |
| 21 | return ticks / GROK_COST_USD_TICKS_PER_DOLLAR; |
| 22 | } |
| 23 | |
| 24 | interface GrokUsageTotals { |
| 25 | readonly inputTokens: number; |
| 26 | readonly outputTokens: number; |
| 27 | readonly cachedReadTokens: number; |
| 28 | readonly cacheCreationTokens: number; |
| 29 | readonly reasoningTokens: number; |
| 30 | readonly costUsdTicks: number | null; |
| 31 | } |
| 32 | |
| 33 | function readGrokUsageTotals(value: unknown): GrokUsageTotals | null { |
| 34 | if (typeof value !== "object" || value === null) return null; |
| 35 | const record = value as Record<string, unknown>; |
| 36 | return { |
| 37 | inputTokens: tokenCount(record["inputTokens"]), |
| 38 | outputTokens: tokenCount(record["outputTokens"]), |
| 39 | cachedReadTokens: tokenCount(record["cachedReadTokens"]), |
| 40 | cacheCreationTokens: tokenCount(record["cacheCreationTokens"]), |
| 41 | reasoningTokens: tokenCount(record["reasoningTokens"]), |
| 42 | costUsdTicks: |
| 43 | typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"]) |
| 44 | ? record["costUsdTicks"] |
| 45 | : null, |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals { |
| 50 | const cachedInputTokens = totals.cachedReadTokens; |
| 51 | const cacheCreationTokens = totals.cacheCreationTokens; |
| 52 | // Grok reports `inputTokens` inclusive of the cached portion, matching Codex. |
| 53 | const uncachedInputTokens = Math.max( |
| 54 | 0, |
| 55 | totals.inputTokens - cachedInputTokens - cacheCreationTokens, |
| 56 | ); |
| 57 | const outputTokens = totals.outputTokens; |
| 58 | return { |
| 59 | uncachedInputTokens, |
| 60 | cachedInputTokens, |
| 61 | cacheCreationTokens, |
| 62 | outputTokens, |
| 63 | reasoningTokens: Math.min(outputTokens, totals.reasoningTokens), |
| 64 | }; |
| 65 | } |
| 66 | |
| 67 | export function parseGrokLine(line: string): readonly UsageRecord[] { |
| 68 | let parsed: unknown; |
| 69 | try { |
| 70 | parsed = JSON.parse(line); |
| 71 | } catch { |
| 72 | return []; |
| 73 | } |
| 74 | return parseGrokRecord(parsed); |
| 75 | } |
| 76 | |
| 77 | function parseGrokRecord(parsed: unknown): readonly UsageRecord[] { |
| 78 | if (typeof parsed !== "object" || parsed === null) return []; |
| 79 | |
| 80 | const record = parsed as Record<string, unknown>; |
| 81 | const params = record["params"]; |
| 82 | if (typeof params !== "object" || params === null) return []; |
| 83 | const paramsRecord = params as Record<string, unknown>; |
| 84 | |
| 85 | const update = paramsRecord["update"]; |
| 86 | if (typeof update !== "object" || update === null) return []; |
| 87 | const updateRecord = update as Record<string, unknown>; |
| 88 | if (updateRecord["sessionUpdate"] !== "turn_completed") return []; |
| 89 | |
| 90 | const usage = updateRecord["usage"]; |
| 91 | if (typeof usage !== "object" || usage === null) return []; |
| 92 | const usageRecord = usage as Record<string, unknown>; |
| 93 | |
| 94 | const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : ""; |
| 95 | // T3's prompt ids restart with each Grok process, so a resumed session reuses them. |
| 96 | const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null; |
| 97 | |
| 98 | const meta = paramsRecord["_meta"]; |
| 99 | let timestampMs: number | null = null; |
| 100 | if (typeof meta === "object" && meta !== null) { |
| 101 | const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"]; |
| 102 | if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) { |
| 103 | timestampMs = agentTimestampMs; |
| 104 | } |
| 105 | } |
| 106 | if (timestampMs === null) { |
| 107 | const timestamp = record["timestamp"]; |
| 108 | if (typeof timestamp === "number" && Number.isFinite(timestamp)) { |
| 109 | timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000; |
| 110 | } |
| 111 | } |
| 112 | if (timestampMs === null) return []; |
| 113 | |
| 114 | const topLevel = readGrokUsageTotals(usageRecord); |
| 115 | if (topLevel === null) return []; |
| 116 | |
| 117 | const modelUsage = usageRecord["modelUsage"]; |
| 118 | const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = []; |
| 119 | if (typeof modelUsage === "object" && modelUsage !== null) { |
| 120 | for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) { |
| 121 | if (model.length === 0) continue; |
| 122 | const totals = readGrokUsageTotals(raw); |
| 123 | if (totals === null) continue; |
| 124 | modelEntries.push({ model, totals }); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | if (modelEntries.length === 0) { |
| 129 | if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return []; |
| 130 | return [ |
| 131 | { |
| 132 | provider: "grok", |
| 133 | timestampMs, |
| 134 | model: "grok", |
| 135 | sessionId, |
| 136 | totals: grokTotalsToUsage(topLevel), |
| 137 | reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks), |
| 138 | speed: "standard", |
| 139 | // No prompt id means we cannot tell two same-second updates apart. |
| 140 | dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${timestampMs}:grok`, |
| 141 | }, |
| 142 | ]; |
| 143 | } |
| 144 | |
| 145 | const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks); |
| 146 | let usedTickedCostUsd = 0; |
| 147 | let untickedTokenDenominator = 0; |
| 148 | for (const entry of modelEntries) { |
| 149 | const tokens = totalTokens(grokTotalsToUsage(entry.totals)); |
| 150 | if (tokens === 0) continue; |
| 151 | if (entry.totals.costUsdTicks !== null) { |
| 152 | usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0; |
| 153 | } else { |
| 154 | untickedTokenDenominator += tokens; |
| 155 | } |
| 156 | } |
| 157 | const remainingCostUsd = |
| 158 | topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd); |
| 159 | |
| 160 | const results: UsageRecord[] = []; |
| 161 | for (const entry of modelEntries) { |
| 162 | const totals = grokTotalsToUsage(entry.totals); |
| 163 | if (totalTokens(totals) === 0) continue; |
| 164 | |
| 165 | let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks); |
| 166 | if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) { |
| 167 | reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator); |
| 168 | } |
| 169 | |
| 170 | results.push({ |
| 171 | provider: "grok", |
| 172 | timestampMs, |
| 173 | model: entry.model, |
| 174 | sessionId, |
| 175 | totals, |
| 176 | reportedCostUsd, |
| 177 | speed: "standard", |
| 178 | dedupeKey: |
| 179 | promptId === null ? null : `${sessionId}:${promptId}:${timestampMs}:${entry.model}`, |
| 180 | }); |
| 181 | } |
| 182 | return results; |
| 183 | } |
| 184 | |
| 185 | export const grokUsageFormat: TranscriptUsageFormat<void> = { |
| 186 | selectFields: { |
| 187 | timestamp: true, |
| 188 | params: { |
| 189 | sessionId: true, |
| 190 | _meta: { agentTimestampMs: true }, |
| 191 | update: { sessionUpdate: true, prompt_id: true, usage: true }, |
| 192 | }, |
| 193 | }, |
| 194 | usageMarkers: ['"turn_completed"'], |
| 195 | parseLine: (line) => parseGrokLine(line), |
| 196 | parseProjected: (projected) => parseGrokRecord(projected), |
| 197 | }; |
| 198 | |
| 199 | export const grokUsageReader: ProviderUsageReader<GrokSettings, Path.Path> = { |
| 200 | kind: "transcripts", |
| 201 | provider: "grok", |
| 202 | format: grokUsageFormat, |
| 203 | directories: Effect.fn("grokUsageReader.directories")(function* ({ environment }) { |
| 204 | const path = yield* Path.Path; |
| 205 | const homeDirectory = yield* HostProcess.HomeDirectory; |
| 206 | const home = expandHomePath( |
| 207 | environment.GROK_HOME?.trim() || path.join(homeDirectory, ".grok"), |
| 208 | homeDirectory, |
| 209 | ); |
| 210 | // Only updates.jsonl carries usage; skip large chat_history and events logs. |
| 211 | return [{ dir: path.resolve(home, "sessions"), fileName: "updates.jsonl" }]; |
| 212 | }), |
| 213 | }; |