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