Open History to see the last commit
1/**
2 * Merges per-environment usage summaries into the single view the page renders.
3 *
4 * Pure, so the de-duplication and derivation rules can be tested without a
5 * connected environment.
6 *
7 * @module usageMerge
8 */
9import {
10 USAGE_MERGE_COMPATIBLE_SINCE,
11 type EnvironmentId,
12 type UsageBucket,
13 type UsageProviderKind,
14 type UsageSourceFingerprint,
15 type UsageSummary,
16} from "@t3tools/contracts";
17
18export interface EnvironmentUsage {
19 readonly environmentId: EnvironmentId;
20 readonly label: string;
21 readonly summary: UsageSummary;
22}
23
24export interface ProviderTotals {
25 readonly provider: UsageProviderKind;
26 readonly costUsd: number;
27 readonly totalTokens: number;
28 readonly records: number;
29 readonly sessions: number;
30 readonly costShare: number;
31 readonly tokenShare: number;
32}
33
34export interface ModelTotals {
35 readonly model: string;
36 readonly provider: UsageProviderKind;
37 readonly costUsd: number;
38 readonly totalTokens: number;
39 readonly records: number;
40 readonly costShare: number;
41}
42
43export interface DailyTotals {
44 readonly day: string;
45 readonly costUsd: number;
46 readonly totalTokens: number;
47 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
48}
49
50export interface HourlyTotals {
51 readonly day: string;
52 readonly hourStart: string;
53 readonly costUsd: number;
54 readonly totalTokens: number;
55 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
56}
57
58export interface CostQuality {
59 readonly providerReportedShare: number;
60 readonly modelPricedShare: number;
61 readonly unpricedShare: number;
62 readonly cacheSavingsUsd: number;
63}
64
65export interface MergedUsage {
66 readonly costUsd: number;
67 readonly uncachedInputTokens: number;
68 readonly cachedInputTokens: number;
69 readonly cacheCreationTokens: number;
70 readonly outputTokens: number;
71 readonly reasoningTokens: number;
72 readonly totalTokens: number;
73 readonly records: number;
74 readonly sessions: number;
75 readonly providers: readonly ProviderTotals[];
76 readonly models: readonly ModelTotals[];
77 readonly daily: readonly DailyTotals[];
78 readonly hourly: readonly HourlyTotals[];
79 readonly costQuality: CostQuality;
80 /** Environments whose data was dropped as a duplicate of another's. */
81 readonly duplicateSources: readonly string[];
82 readonly contributingEnvironments: readonly EnvironmentId[];
83 readonly staleEnvironments: readonly EnvironmentId[];
84}
85
86/**
87 * Two sources are the same physical transcript directory only when host,
88 * provider, path and filesystem identity all agree.
89 *
90 * `volumeId` is what stops two machines that happen to share a hostname and a
91 * home path, which is every Mac in a fleet, from collapsing into one source and
92 * having one of them silently dropped.
93 */
94function fingerprintKey(fingerprint: UsageSourceFingerprint): string {
95 return [
96 fingerprint.hostId,
97 fingerprint.provider,
98 fingerprint.resolvedHomePath,
99 fingerprint.volumeId,
100 ].join(" ");
101}
102
103/**
104 * Decides which environment owns each physical transcript directory.
105 *
106 * Several environments on one machine (worktree servers, for instance) resolve
107 * the same provider home and would otherwise double count every token. The
108 * first environment in a stable order claims a fingerprint; the rest have that
109 * provider's buckets dropped. Environments are sorted by id so the winner does
110 * not change between renders.
111 */
112function claimSources(environments: readonly EnvironmentUsage[]): {
113 readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
114 readonly duplicates: readonly string[];
115} {
116 const ownerByFingerprint = new Map<string, EnvironmentId>();
117 const duplicates: string[] = [];
118
119 const ordered = [...environments].sort((a, b) => a.environmentId.localeCompare(b.environmentId));
120
121 for (const environment of ordered) {
122 for (const source of environment.summary.sources) {
123 if (source.status === "missing") continue;
124 const key = fingerprintKey(source.fingerprint);
125 if (ownerByFingerprint.has(key)) {
126 duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
127 continue;
128 }
129 ownerByFingerprint.set(key, environment.environmentId);
130 }
131 }
132
133 return { ownerByFingerprint, duplicates };
134}
135
136/** Sources this environment owns after fingerprint claims, plus their buckets. */
137function ownedContribution(
138 environment: EnvironmentUsage,
139 ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
140): {
141 readonly buckets: readonly UsageBucket[];
142 readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
143} {
144 const ownedProviders = new Set<UsageProviderKind>();
145 const sessionsByProvider = new Map<UsageProviderKind, number>();
146 for (const source of environment.summary.sources) {
147 if (source.status === "missing") continue;
148 const key = fingerprintKey(source.fingerprint);
149 if (ownerByFingerprint.get(key) === environment.environmentId) {
150 const provider = source.fingerprint.provider;
151 ownedProviders.add(provider);
152 // Distinct within a directory. Summing per-bucket session counts instead
153 // would count a session once per day and model it spans.
154 sessionsByProvider.set(
155 provider,
156 (sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,
157 );
158 }
159 }
160 return {
161 buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
162 sessionsByProvider,
163 };
164}
165
166function bucketTokens(bucket: UsageBucket): number {
167 // reasoningTokens is a subset of outputTokens and must not be added again.
168 return (
169 bucket.totals.uncachedInputTokens +
170 bucket.totals.cachedInputTokens +
171 bucket.totals.cacheCreationTokens +
172 bucket.totals.outputTokens
173 );
174}
175
176function isCompatibleContractVersion(version: number, expected: number): boolean {
177 return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected;
178}
179
180const EMPTY_MERGED: MergedUsage = {
181 costUsd: 0,
182 uncachedInputTokens: 0,
183 cachedInputTokens: 0,
184 cacheCreationTokens: 0,
185 outputTokens: 0,
186 reasoningTokens: 0,
187 totalTokens: 0,
188 records: 0,
189 sessions: 0,
190 providers: [],
191 models: [],
192 daily: [],
193 hourly: [],
194 costQuality: {
195 providerReportedShare: 0,
196 modelPricedShare: 0,
197 unpricedShare: 0,
198 cacheSavingsUsd: 0,
199 },
200 duplicateSources: [],
201 contributingEnvironments: [],
202 staleEnvironments: [],
203};
204
205/**
206 * Merges every connected environment's summary.
207 *
208 * `expectedContractVersion` guards against an environment running older server
209 * code: rather than blocking the page, incompatible data is excluded and its
210 * id is reported so the UI can say coverage is partial. Versions in
211 * [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
212 * provider expansion does not drop Claude/Codex totals from older servers.
213 */
214export function mergeUsage(
215 environments: readonly EnvironmentUsage[],
216 expectedContractVersion: number,
217): MergedUsage {
218 if (environments.length === 0) return EMPTY_MERGED;
219
220 const current: EnvironmentUsage[] = [];
221 const staleEnvironments: EnvironmentId[] = [];
222 for (const environment of environments) {
223 if (isCompatibleContractVersion(environment.summary.contractVersion, expectedContractVersion)) {
224 current.push(environment);
225 } else {
226 staleEnvironments.push(environment.environmentId);
227 }
228 }
229
230 const { ownerByFingerprint, duplicates } = claimSources(current);
231
232 let costUsd = 0;
233 let uncachedInputTokens = 0;
234 let cachedInputTokens = 0;
235 let cacheCreationTokens = 0;
236 let outputTokens = 0;
237 let reasoningTokens = 0;
238 let records = 0;
239 let sessions = 0;
240 let cacheSavingsUsd = 0;
241 let providerReportedRecords = 0;
242 let unpricedRecords = 0;
243
244 const providerAccumulator = new Map<
245 UsageProviderKind,
246 { costUsd: number; totalTokens: number; records: number; sessions: number }
247 >();
248 const modelAccumulator = new Map<
249 string,
250 { provider: UsageProviderKind; costUsd: number; totalTokens: number; records: number }
251 >();
252 const dailyAccumulator = new Map<
253 string,
254 {
255 costUsd: number;
256 totalTokens: number;
257 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
258 }
259 >();
260 const hourlyAccumulator = new Map<
261 string,
262 {
263 day: string;
264 hourStart: string;
265 costUsd: number;
266 totalTokens: number;
267 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
268 }
269 >();
270 const contributingEnvironments: EnvironmentId[] = [];
271
272 for (const environment of current) {
273 const { buckets, sessionsByProvider } = ownedContribution(environment, ownerByFingerprint);
274 if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
275
276 for (const [providerKind, providerSessions] of sessionsByProvider) {
277 sessions += providerSessions;
278 if (providerSessions === 0) continue;
279 const provider = providerAccumulator.get(providerKind) ?? {
280 costUsd: 0,
281 totalTokens: 0,
282 records: 0,
283 sessions: 0,
284 };
285 provider.sessions += providerSessions;
286 providerAccumulator.set(providerKind, provider);
287 }
288
289 for (const bucket of buckets) {
290 const tokens = bucketTokens(bucket);
291
292 costUsd += bucket.costUsd;
293 cacheSavingsUsd += bucket.cacheSavingsUsd;
294 uncachedInputTokens += bucket.totals.uncachedInputTokens;
295 cachedInputTokens += bucket.totals.cachedInputTokens;
296 cacheCreationTokens += bucket.totals.cacheCreationTokens;
297 outputTokens += bucket.totals.outputTokens;
298 reasoningTokens += bucket.totals.reasoningTokens;
299 records += bucket.records;
300 unpricedRecords += bucket.unpricedRecords;
301 if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records;
302
303 const provider = providerAccumulator.get(bucket.provider) ?? {
304 costUsd: 0,
305 totalTokens: 0,
306 records: 0,
307 sessions: 0,
308 };
309 provider.costUsd += bucket.costUsd;
310 provider.totalTokens += tokens;
311 provider.records += bucket.records;
312 providerAccumulator.set(bucket.provider, provider);
313
314 const modelKey = `${bucket.provider} ${bucket.model}`;
315 const model = modelAccumulator.get(modelKey) ?? {
316 provider: bucket.provider,
317 costUsd: 0,
318 totalTokens: 0,
319 records: 0,
320 };
321 model.costUsd += bucket.costUsd;
322 model.totalTokens += tokens;
323 model.records += bucket.records;
324 modelAccumulator.set(modelKey, model);
325
326 const day = dailyAccumulator.get(bucket.day) ?? {
327 costUsd: 0,
328 totalTokens: 0,
329 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
330 };
331 day.costUsd += bucket.costUsd;
332 day.totalTokens += tokens;
333 const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 };
334 dayProvider.costUsd += bucket.costUsd;
335 dayProvider.totalTokens += tokens;
336 day.byProvider.set(bucket.provider, dayProvider);
337 dailyAccumulator.set(bucket.day, day);
338
339 if (bucket.hourStart !== undefined) {
340 const hour = hourlyAccumulator.get(bucket.hourStart) ?? {
341 day: bucket.day,
342 hourStart: bucket.hourStart,
343 costUsd: 0,
344 totalTokens: 0,
345 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
346 };
347 hour.costUsd += bucket.costUsd;
348 hour.totalTokens += tokens;
349 const hourProvider = hour.byProvider.get(bucket.provider) ?? {
350 costUsd: 0,
351 totalTokens: 0,
352 };
353 hourProvider.costUsd += bucket.costUsd;
354 hourProvider.totalTokens += tokens;
355 hour.byProvider.set(bucket.provider, hourProvider);
356 hourlyAccumulator.set(bucket.hourStart, hour);
357 }
358 }
359 }
360
361 const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens;
362
363 const providers: ProviderTotals[] = [...providerAccumulator.entries()]
364 .map(([provider, totals]) => ({
365 provider,
366 costUsd: totals.costUsd,
367 totalTokens: totals.totalTokens,
368 records: totals.records,
369 sessions: totals.sessions,
370 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
371 tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
372 }))
373 .sort((a, b) => b.costUsd - a.costUsd);
374
375 const models: ModelTotals[] = [...modelAccumulator.entries()]
376 .map(([key, totals]) => ({
377 model: key.slice(key.indexOf(" ") + 1),
378 provider: totals.provider,
379 costUsd: totals.costUsd,
380 totalTokens: totals.totalTokens,
381 records: totals.records,
382 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
383 }))
384 .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens);
385
386 const daily: DailyTotals[] = [...dailyAccumulator.entries()]
387 .map(([day, totals]) => ({
388 day,
389 costUsd: totals.costUsd,
390 totalTokens: totals.totalTokens,
391 byProvider: totals.byProvider,
392 }))
393 .sort((a, b) => a.day.localeCompare(b.day));
394
395 const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) =>
396 a.hourStart.localeCompare(b.hourStart),
397 );
398
399 return {
400 costUsd,
401 uncachedInputTokens,
402 cachedInputTokens,
403 cacheCreationTokens,
404 outputTokens,
405 reasoningTokens,
406 totalTokens,
407 records,
408 sessions,
409 providers,
410 models,
411 daily,
412 hourly,
413 costQuality: {
414 providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,
415 unpricedShare: records === 0 ? 0 : unpricedRecords / records,
416 modelPricedShare:
417 records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records,
418 cacheSavingsUsd,
419 },
420 duplicateSources: duplicates,
421 contributingEnvironments,
422 staleEnvironments,
423 };
424}