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