The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | USAGE_MERGE_COMPATIBLE_SINCE, |
| 3 | type EnvironmentId, |
| 4 | type UsageBucket, |
| 5 | type UsageProviderKind, |
| 6 | type UsageSource, |
| 7 | type UsageSourceFingerprint, |
| 8 | type UsageSummary, |
| 9 | type UsageTokenTotals, |
| 10 | } from "@t3tools/contracts"; |
| 11 | |
| 12 | export interface EnvironmentUsage { |
| 13 | readonly environmentId: EnvironmentId; |
| 14 | readonly label: string; |
| 15 | readonly summary: UsageSummary; |
| 16 | } |
| 17 | |
| 18 | export interface ProviderTotals { |
| 19 | readonly provider: UsageProviderKind; |
| 20 | readonly costUsd: number; |
| 21 | readonly totalTokens: number; |
| 22 | readonly records: number; |
| 23 | readonly sessions: number; |
| 24 | readonly costShare: number; |
| 25 | readonly tokenShare: number; |
| 26 | } |
| 27 | |
| 28 | export interface ModelTotals { |
| 29 | readonly model: string; |
| 30 | readonly provider: UsageProviderKind; |
| 31 | readonly costUsd: number; |
| 32 | readonly totalTokens: number; |
| 33 | readonly tokens: UsageTokenTotals; |
| 34 | readonly records: number; |
| 35 | readonly unpricedRecords: number; |
| 36 | readonly unpricedTokens: number; |
| 37 | readonly costShare: number; |
| 38 | readonly tokenShare: number; |
| 39 | } |
| 40 | |
| 41 | /** When every record lacks rates, costUsd is unknown and must not be displayed as a dollar figure. */ |
| 42 | export function isModelCostUnknown(model: ModelTotals): boolean { |
| 43 | return model.records > 0 && model.unpricedRecords >= model.records; |
| 44 | } |
| 45 | |
| 46 | export interface DailyTotals { |
| 47 | readonly day: string; |
| 48 | readonly costUsd: number; |
| 49 | readonly totalTokens: number; |
| 50 | readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>; |
| 51 | } |
| 52 | |
| 53 | export interface HourlyTotals { |
| 54 | readonly day: string; |
| 55 | readonly hourStart: string; |
| 56 | readonly costUsd: number; |
| 57 | readonly totalTokens: number; |
| 58 | readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>; |
| 59 | } |
| 60 | |
| 61 | export interface CostQuality { |
| 62 | readonly providerReportedShare: number; |
| 63 | readonly modelPricedShare: number; |
| 64 | readonly unpricedShare: number; |
| 65 | readonly cacheSavingsUsd: number; |
| 66 | } |
| 67 | |
| 68 | export interface CategoryCost { |
| 69 | readonly input: number; |
| 70 | readonly cacheRead: number; |
| 71 | readonly cacheWrite: number; |
| 72 | readonly output: number; |
| 73 | readonly unsplit: number; |
| 74 | } |
| 75 | |
| 76 | export interface SpeedCost { |
| 77 | readonly standard: number; |
| 78 | readonly fast: number; |
| 79 | readonly ultrafast: number; |
| 80 | readonly premium: number; |
| 81 | } |
| 82 | |
| 83 | export interface UsageContractMismatch { |
| 84 | readonly environmentId: EnvironmentId; |
| 85 | readonly direction: "serverBehind" | "clientBehind"; |
| 86 | readonly contractVersion: number; |
| 87 | } |
| 88 | |
| 89 | export interface MergedUsage { |
| 90 | readonly costUsd: number; |
| 91 | readonly uncachedInputTokens: number; |
| 92 | readonly cachedInputTokens: number; |
| 93 | readonly cacheCreationTokens: number; |
| 94 | readonly outputTokens: number; |
| 95 | readonly reasoningTokens: number; |
| 96 | readonly totalTokens: number; |
| 97 | readonly records: number; |
| 98 | readonly sessions: number; |
| 99 | readonly providers: readonly ProviderTotals[]; |
| 100 | readonly models: readonly ModelTotals[]; |
| 101 | readonly daily: readonly DailyTotals[]; |
| 102 | readonly hourly: readonly HourlyTotals[]; |
| 103 | readonly costQuality: CostQuality; |
| 104 | readonly categoryCost: CategoryCost; |
| 105 | readonly speedCost: SpeedCost; |
| 106 | readonly duplicateSources: readonly string[]; |
| 107 | readonly contributingEnvironments: readonly EnvironmentId[]; |
| 108 | readonly contractMismatches: readonly UsageContractMismatch[]; |
| 109 | } |
| 110 | |
| 111 | // volumeId distinguishes machines sharing a hostname and home path. |
| 112 | function fingerprintKey(fingerprint: UsageSourceFingerprint): string { |
| 113 | return [ |
| 114 | fingerprint.hostId, |
| 115 | fingerprint.provider, |
| 116 | fingerprint.resolvedHomePath, |
| 117 | fingerprint.volumeId, |
| 118 | ].join(" "); |
| 119 | } |
| 120 | |
| 121 | // Sources are one directory when either their legacy key or their physicalSourceId matches. |
| 122 | // physicalSourceId joins a directory read natively by Windows and through a WSL mount (path |
| 123 | // and dev:ino both differ); the legacy key still joins installs whose host scopes differ. |
| 124 | function sourceIdentity( |
| 125 | environments: readonly EnvironmentUsage[], |
| 126 | ): (fingerprint: UsageSourceFingerprint) => string { |
| 127 | const parent = new Map<string, string>(); |
| 128 | const find = (key: string): string => { |
| 129 | const next = parent.get(key); |
| 130 | if (next === undefined || next === key) return key; |
| 131 | const root = find(next); |
| 132 | parent.set(key, root); |
| 133 | return root; |
| 134 | }; |
| 135 | for (const environment of environments) { |
| 136 | for (const { fingerprint } of environment.summary.sources) { |
| 137 | if (fingerprint.physicalSourceId === undefined) continue; |
| 138 | const legacy = find(fingerprintKey(fingerprint)); |
| 139 | const physical = find(`\u0000${fingerprint.provider}\u0000${fingerprint.physicalSourceId}`); |
| 140 | if (legacy !== physical) parent.set(legacy, physical); |
| 141 | } |
| 142 | } |
| 143 | return (fingerprint) => find(fingerprintKey(fingerprint)); |
| 144 | } |
| 145 | |
| 146 | function bucketsForSource(summary: UsageSummary, source: UsageSource): readonly UsageBucket[] { |
| 147 | const providerSources = summary.sources.filter( |
| 148 | (entry) => entry.fingerprint.provider === source.fingerprint.provider, |
| 149 | ); |
| 150 | return summary.buckets.filter( |
| 151 | (bucket) => |
| 152 | bucket.provider === source.fingerprint.provider && |
| 153 | (bucket.sourcePath === source.fingerprint.resolvedHomePath || |
| 154 | (bucket.sourcePath === undefined && providerSources.length === 1)), |
| 155 | ); |
| 156 | } |
| 157 | |
| 158 | function bucketKey(bucket: UsageBucket): string { |
| 159 | return JSON.stringify([bucket.day, bucket.hourStart ?? null, bucket.provider, bucket.model]); |
| 160 | } |
| 161 | |
| 162 | function claimSources( |
| 163 | environments: readonly EnvironmentUsage[], |
| 164 | sourceKey: (fingerprint: UsageSourceFingerprint) => string, |
| 165 | ): { |
| 166 | readonly ownerScanByFingerprint: ReadonlyMap<string, { readonly source: UsageSource }>; |
| 167 | readonly supplementalBucketsByEnvironment: ReadonlyMap<EnvironmentId, ReadonlySet<UsageBucket>>; |
| 168 | readonly sessionsByFingerprint: ReadonlyMap<string, number>; |
| 169 | readonly duplicates: readonly string[]; |
| 170 | } { |
| 171 | const ownerScanByFingerprint = new Map< |
| 172 | string, |
| 173 | { environment: EnvironmentUsage; source: UsageSource } |
| 174 | >(); |
| 175 | const seenBucketKeysByFingerprint = new Map<string, Set<string>>(); |
| 176 | const supplementalBucketsByEnvironment = new Map<EnvironmentId, Set<UsageBucket>>(); |
| 177 | const sessionsByFingerprint = new Map<string, number>(); |
| 178 | const duplicates: string[] = []; |
| 179 | |
| 180 | const ordered = [...environments].sort( |
| 181 | (a, b) => |
| 182 | (Date.parse(b.summary.readAt) || 0) - (Date.parse(a.summary.readAt) || 0) || |
| 183 | a.environmentId.localeCompare(b.environmentId), |
| 184 | ); |
| 185 | |
| 186 | for (const status of ["ok", "partial", "failed"] as const) { |
| 187 | for (const environment of ordered) { |
| 188 | for (const source of environment.summary.sources) { |
| 189 | if (source.status !== status) continue; |
| 190 | const key = sourceKey(source.fingerprint); |
| 191 | if (ownerScanByFingerprint.has(key)) { |
| 192 | duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`); |
| 193 | continue; |
| 194 | } |
| 195 | ownerScanByFingerprint.set(key, { environment, source }); |
| 196 | sessionsByFingerprint.set(key, source.distinctSessions); |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // Keep cells unique to newer partial scans; aggregates cannot reconcile overlapping records without double-counting. |
| 202 | for (const environment of ordered) { |
| 203 | for (const source of environment.summary.sources) { |
| 204 | if (source.status !== "partial") continue; |
| 205 | const key = sourceKey(source.fingerprint); |
| 206 | const owner = ownerScanByFingerprint.get(key); |
| 207 | // A scan under another model filter counts different records, so its cells are not missing ones. |
| 208 | if ( |
| 209 | owner?.source.status !== "ok" || |
| 210 | Date.parse(environment.summary.readAt) <= Date.parse(owner.environment.summary.readAt) || |
| 211 | JSON.stringify(environment.summary.modelFilter) !== |
| 212 | JSON.stringify(owner.environment.summary.modelFilter) |
| 213 | ) { |
| 214 | continue; |
| 215 | } |
| 216 | let seen = seenBucketKeysByFingerprint.get(key); |
| 217 | if (seen === undefined) { |
| 218 | seen = new Set(bucketsForSource(owner.environment.summary, owner.source).map(bucketKey)); |
| 219 | seenBucketKeysByFingerprint.set(key, seen); |
| 220 | } |
| 221 | const supplemental = |
| 222 | supplementalBucketsByEnvironment.get(environment.environmentId) ?? new Set<UsageBucket>(); |
| 223 | let added = false; |
| 224 | for (const bucket of bucketsForSource(environment.summary, source)) { |
| 225 | const cell = bucketKey(bucket); |
| 226 | if (seen.has(cell)) continue; |
| 227 | seen.add(cell); |
| 228 | supplemental.add(bucket); |
| 229 | added = true; |
| 230 | } |
| 231 | if (!added) continue; |
| 232 | supplementalBucketsByEnvironment.set(environment.environmentId, supplemental); |
| 233 | sessionsByFingerprint.set( |
| 234 | key, |
| 235 | Math.max(sessionsByFingerprint.get(key) ?? 0, source.distinctSessions), |
| 236 | ); |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | return { |
| 241 | ownerScanByFingerprint, |
| 242 | supplementalBucketsByEnvironment, |
| 243 | sessionsByFingerprint, |
| 244 | duplicates, |
| 245 | }; |
| 246 | } |
| 247 | |
| 248 | function ownedContribution( |
| 249 | environment: EnvironmentUsage, |
| 250 | ownerScanByFingerprint: ReadonlyMap<string, { readonly source: UsageSource }>, |
| 251 | supplementalBuckets: ReadonlySet<UsageBucket>, |
| 252 | sessionsByFingerprint: ReadonlyMap<string, number>, |
| 253 | sourceKey: (fingerprint: UsageSourceFingerprint) => string, |
| 254 | ): { |
| 255 | readonly buckets: readonly UsageBucket[]; |
| 256 | readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>; |
| 257 | } { |
| 258 | const ownedProviders = new Set<UsageProviderKind>(); |
| 259 | const ownedSources = new Set<string>(); |
| 260 | const sessionsByProvider = new Map<UsageProviderKind, number>(); |
| 261 | for (const source of environment.summary.sources) { |
| 262 | if (source.status === "missing") continue; |
| 263 | const key = sourceKey(source.fingerprint); |
| 264 | // By source, not environment: one server can reach a directory through two |
| 265 | // mounts, and only the winning reading may count. |
| 266 | if (ownerScanByFingerprint.get(key)?.source === source) { |
| 267 | const provider = source.fingerprint.provider; |
| 268 | ownedProviders.add(provider); |
| 269 | ownedSources.add(`${provider}\u0000${source.fingerprint.resolvedHomePath}`); |
| 270 | // Count distinct sessions per directory; bucket sums overcount sessions spanning days/models. |
| 271 | sessionsByProvider.set( |
| 272 | provider, |
| 273 | (sessionsByProvider.get(provider) ?? 0) + |
| 274 | (sessionsByFingerprint.get(key) ?? source.distinctSessions), |
| 275 | ); |
| 276 | } |
| 277 | } |
| 278 | return { |
| 279 | buckets: environment.summary.buckets.filter( |
| 280 | (bucket) => |
| 281 | supplementalBuckets.has(bucket) || |
| 282 | (bucket.sourcePath === undefined |
| 283 | ? ownedProviders.has(bucket.provider) |
| 284 | : ownedSources.has(`${bucket.provider}\u0000${bucket.sourcePath}`)), |
| 285 | ), |
| 286 | sessionsByProvider, |
| 287 | }; |
| 288 | } |
| 289 | |
| 290 | function bucketTokens(bucket: UsageBucket): number { |
| 291 | // reasoningTokens is a subset of outputTokens and must not be added again. |
| 292 | return ( |
| 293 | bucket.totals.uncachedInputTokens + |
| 294 | bucket.totals.cachedInputTokens + |
| 295 | bucket.totals.cacheCreationTokens + |
| 296 | bucket.totals.outputTokens |
| 297 | ); |
| 298 | } |
| 299 | |
| 300 | export function isCompatibleUsageContractVersion(version: number, expected: number): boolean { |
| 301 | return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected; |
| 302 | } |
| 303 | |
| 304 | const EMPTY_MERGED: MergedUsage = { |
| 305 | costUsd: 0, |
| 306 | uncachedInputTokens: 0, |
| 307 | cachedInputTokens: 0, |
| 308 | cacheCreationTokens: 0, |
| 309 | outputTokens: 0, |
| 310 | reasoningTokens: 0, |
| 311 | totalTokens: 0, |
| 312 | records: 0, |
| 313 | sessions: 0, |
| 314 | providers: [], |
| 315 | models: [], |
| 316 | daily: [], |
| 317 | hourly: [], |
| 318 | costQuality: { |
| 319 | providerReportedShare: 0, |
| 320 | modelPricedShare: 0, |
| 321 | unpricedShare: 0, |
| 322 | cacheSavingsUsd: 0, |
| 323 | }, |
| 324 | categoryCost: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, unsplit: 0 }, |
| 325 | speedCost: { standard: 0, fast: 0, ultrafast: 0, premium: 0 }, |
| 326 | duplicateSources: [], |
| 327 | contributingEnvironments: [], |
| 328 | contractMismatches: [], |
| 329 | }; |
| 330 | |
| 331 | export function mergeUsage( |
| 332 | environments: readonly EnvironmentUsage[], |
| 333 | expectedContractVersion: number, |
| 334 | ): MergedUsage { |
| 335 | if (environments.length === 0) return EMPTY_MERGED; |
| 336 | |
| 337 | const current: EnvironmentUsage[] = []; |
| 338 | const contractMismatches: UsageContractMismatch[] = []; |
| 339 | for (const environment of environments) { |
| 340 | if ( |
| 341 | isCompatibleUsageContractVersion(environment.summary.contractVersion, expectedContractVersion) |
| 342 | ) { |
| 343 | current.push(environment); |
| 344 | } else { |
| 345 | contractMismatches.push({ |
| 346 | environmentId: environment.environmentId, |
| 347 | direction: |
| 348 | environment.summary.contractVersion < expectedContractVersion |
| 349 | ? "serverBehind" |
| 350 | : "clientBehind", |
| 351 | contractVersion: environment.summary.contractVersion, |
| 352 | }); |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | const sourceKey = sourceIdentity(current); |
| 357 | const { |
| 358 | ownerScanByFingerprint, |
| 359 | supplementalBucketsByEnvironment, |
| 360 | sessionsByFingerprint, |
| 361 | duplicates, |
| 362 | } = claimSources(current, sourceKey); |
| 363 | |
| 364 | let costUsd = 0; |
| 365 | let uncachedInputTokens = 0; |
| 366 | let cachedInputTokens = 0; |
| 367 | let cacheCreationTokens = 0; |
| 368 | let outputTokens = 0; |
| 369 | let reasoningTokens = 0; |
| 370 | let records = 0; |
| 371 | let sessions = 0; |
| 372 | let cacheSavingsUsd = 0; |
| 373 | let providerReportedRecords = 0; |
| 374 | let unpricedRecords = 0; |
| 375 | const categoryCost = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 }; |
| 376 | const speedCost = { fast: 0, ultrafast: 0, premium: 0 }; |
| 377 | |
| 378 | const providerAccumulator = new Map< |
| 379 | UsageProviderKind, |
| 380 | { costUsd: number; totalTokens: number; records: number; sessions: number } |
| 381 | >(); |
| 382 | const modelAccumulator = new Map< |
| 383 | string, |
| 384 | { |
| 385 | provider: UsageProviderKind; |
| 386 | costUsd: number; |
| 387 | totalTokens: number; |
| 388 | tokens: UsageTokenTotals; |
| 389 | records: number; |
| 390 | unpricedRecords: number; |
| 391 | unpricedTokens: number; |
| 392 | } |
| 393 | >(); |
| 394 | const dailyAccumulator = new Map< |
| 395 | string, |
| 396 | { |
| 397 | costUsd: number; |
| 398 | totalTokens: number; |
| 399 | byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>; |
| 400 | } |
| 401 | >(); |
| 402 | const hourlyAccumulator = new Map< |
| 403 | string, |
| 404 | { |
| 405 | day: string; |
| 406 | hourStart: string; |
| 407 | costUsd: number; |
| 408 | totalTokens: number; |
| 409 | byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>; |
| 410 | } |
| 411 | >(); |
| 412 | const contributingEnvironments: EnvironmentId[] = []; |
| 413 | |
| 414 | for (const environment of current) { |
| 415 | const { buckets, sessionsByProvider } = ownedContribution( |
| 416 | environment, |
| 417 | ownerScanByFingerprint, |
| 418 | supplementalBucketsByEnvironment.get(environment.environmentId) ?? new Set(), |
| 419 | sessionsByFingerprint, |
| 420 | sourceKey, |
| 421 | ); |
| 422 | if (buckets.length > 0) contributingEnvironments.push(environment.environmentId); |
| 423 | |
| 424 | for (const [providerKind, providerSessions] of sessionsByProvider) { |
| 425 | sessions += providerSessions; |
| 426 | if (providerSessions === 0) continue; |
| 427 | const provider = providerAccumulator.get(providerKind) ?? { |
| 428 | costUsd: 0, |
| 429 | totalTokens: 0, |
| 430 | records: 0, |
| 431 | sessions: 0, |
| 432 | }; |
| 433 | provider.sessions += providerSessions; |
| 434 | providerAccumulator.set(providerKind, provider); |
| 435 | } |
| 436 | |
| 437 | for (const bucket of buckets) { |
| 438 | const tokens = bucketTokens(bucket); |
| 439 | |
| 440 | costUsd += bucket.costUsd; |
| 441 | cacheSavingsUsd += bucket.cacheSavingsUsd; |
| 442 | uncachedInputTokens += bucket.totals.uncachedInputTokens; |
| 443 | cachedInputTokens += bucket.totals.cachedInputTokens; |
| 444 | cacheCreationTokens += bucket.totals.cacheCreationTokens; |
| 445 | outputTokens += bucket.totals.outputTokens; |
| 446 | reasoningTokens += bucket.totals.reasoningTokens; |
| 447 | records += bucket.records; |
| 448 | unpricedRecords += bucket.unpricedRecords; |
| 449 | if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records; |
| 450 | if (bucket.categoryCostUsd !== undefined) { |
| 451 | categoryCost.input += bucket.categoryCostUsd.input; |
| 452 | categoryCost.cacheRead += bucket.categoryCostUsd.cacheRead; |
| 453 | categoryCost.cacheWrite += bucket.categoryCostUsd.cacheWrite; |
| 454 | categoryCost.output += bucket.categoryCostUsd.output; |
| 455 | } |
| 456 | speedCost.fast += bucket.fastCostUsd ?? 0; |
| 457 | speedCost.ultrafast += bucket.ultrafastCostUsd ?? 0; |
| 458 | speedCost.premium += bucket.speedPremiumUsd ?? 0; |
| 459 | |
| 460 | const provider = providerAccumulator.get(bucket.provider) ?? { |
| 461 | costUsd: 0, |
| 462 | totalTokens: 0, |
| 463 | records: 0, |
| 464 | sessions: 0, |
| 465 | }; |
| 466 | provider.costUsd += bucket.costUsd; |
| 467 | provider.totalTokens += tokens; |
| 468 | provider.records += bucket.records; |
| 469 | providerAccumulator.set(bucket.provider, provider); |
| 470 | |
| 471 | const modelKey = `${bucket.provider} ${bucket.model}`; |
| 472 | const model = modelAccumulator.get(modelKey) ?? { |
| 473 | provider: bucket.provider, |
| 474 | costUsd: 0, |
| 475 | totalTokens: 0, |
| 476 | tokens: { |
| 477 | uncachedInputTokens: 0, |
| 478 | cachedInputTokens: 0, |
| 479 | cacheCreationTokens: 0, |
| 480 | outputTokens: 0, |
| 481 | reasoningTokens: 0, |
| 482 | }, |
| 483 | records: 0, |
| 484 | unpricedRecords: 0, |
| 485 | unpricedTokens: 0, |
| 486 | }; |
| 487 | model.costUsd += bucket.costUsd; |
| 488 | model.totalTokens += tokens; |
| 489 | model.tokens = { |
| 490 | uncachedInputTokens: model.tokens.uncachedInputTokens + bucket.totals.uncachedInputTokens, |
| 491 | cachedInputTokens: model.tokens.cachedInputTokens + bucket.totals.cachedInputTokens, |
| 492 | cacheCreationTokens: model.tokens.cacheCreationTokens + bucket.totals.cacheCreationTokens, |
| 493 | outputTokens: model.tokens.outputTokens + bucket.totals.outputTokens, |
| 494 | reasoningTokens: model.tokens.reasoningTokens + bucket.totals.reasoningTokens, |
| 495 | }; |
| 496 | model.records += bucket.records; |
| 497 | model.unpricedRecords += bucket.unpricedRecords; |
| 498 | if (bucket.unpricedTokens !== undefined) { |
| 499 | model.unpricedTokens += bucket.unpricedTokens; |
| 500 | } else if (bucket.records > 0) { |
| 501 | model.unpricedTokens += (tokens * bucket.unpricedRecords) / bucket.records; |
| 502 | } |
| 503 | modelAccumulator.set(modelKey, model); |
| 504 | |
| 505 | const day = dailyAccumulator.get(bucket.day) ?? { |
| 506 | costUsd: 0, |
| 507 | totalTokens: 0, |
| 508 | byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(), |
| 509 | }; |
| 510 | day.costUsd += bucket.costUsd; |
| 511 | day.totalTokens += tokens; |
| 512 | const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 }; |
| 513 | dayProvider.costUsd += bucket.costUsd; |
| 514 | dayProvider.totalTokens += tokens; |
| 515 | day.byProvider.set(bucket.provider, dayProvider); |
| 516 | dailyAccumulator.set(bucket.day, day); |
| 517 | |
| 518 | if (bucket.hourStart !== undefined) { |
| 519 | const hour = hourlyAccumulator.get(bucket.hourStart) ?? { |
| 520 | day: bucket.day, |
| 521 | hourStart: bucket.hourStart, |
| 522 | costUsd: 0, |
| 523 | totalTokens: 0, |
| 524 | byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(), |
| 525 | }; |
| 526 | hour.costUsd += bucket.costUsd; |
| 527 | hour.totalTokens += tokens; |
| 528 | const hourProvider = hour.byProvider.get(bucket.provider) ?? { |
| 529 | costUsd: 0, |
| 530 | totalTokens: 0, |
| 531 | }; |
| 532 | hourProvider.costUsd += bucket.costUsd; |
| 533 | hourProvider.totalTokens += tokens; |
| 534 | hour.byProvider.set(bucket.provider, hourProvider); |
| 535 | hourlyAccumulator.set(bucket.hourStart, hour); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens; |
| 541 | |
| 542 | const providers: ProviderTotals[] = [...providerAccumulator.entries()] |
| 543 | .map(([provider, totals]) => ({ |
| 544 | provider, |
| 545 | costUsd: totals.costUsd, |
| 546 | totalTokens: totals.totalTokens, |
| 547 | records: totals.records, |
| 548 | sessions: totals.sessions, |
| 549 | costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd, |
| 550 | tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens, |
| 551 | })) |
| 552 | .sort((a, b) => b.costUsd - a.costUsd); |
| 553 | |
| 554 | const models: ModelTotals[] = [...modelAccumulator.entries()] |
| 555 | .map(([key, totals]) => ({ |
| 556 | model: key.slice(key.indexOf(" ") + 1), |
| 557 | provider: totals.provider, |
| 558 | costUsd: totals.costUsd, |
| 559 | totalTokens: totals.totalTokens, |
| 560 | tokens: totals.tokens, |
| 561 | records: totals.records, |
| 562 | unpricedRecords: totals.unpricedRecords, |
| 563 | unpricedTokens: totals.unpricedTokens, |
| 564 | costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd, |
| 565 | tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens, |
| 566 | })) |
| 567 | .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens); |
| 568 | |
| 569 | const daily: DailyTotals[] = [...dailyAccumulator.entries()] |
| 570 | .map(([day, totals]) => ({ |
| 571 | day, |
| 572 | costUsd: totals.costUsd, |
| 573 | totalTokens: totals.totalTokens, |
| 574 | byProvider: totals.byProvider, |
| 575 | })) |
| 576 | .sort((a, b) => a.day.localeCompare(b.day)); |
| 577 | |
| 578 | const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) => |
| 579 | a.hourStart.localeCompare(b.hourStart), |
| 580 | ); |
| 581 | |
| 582 | return { |
| 583 | costUsd, |
| 584 | uncachedInputTokens, |
| 585 | cachedInputTokens, |
| 586 | cacheCreationTokens, |
| 587 | outputTokens, |
| 588 | reasoningTokens, |
| 589 | totalTokens, |
| 590 | records, |
| 591 | sessions, |
| 592 | providers, |
| 593 | models, |
| 594 | daily, |
| 595 | hourly, |
| 596 | costQuality: { |
| 597 | providerReportedShare: records === 0 ? 0 : providerReportedRecords / records, |
| 598 | unpricedShare: records === 0 ? 0 : unpricedRecords / records, |
| 599 | modelPricedShare: |
| 600 | records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records, |
| 601 | cacheSavingsUsd, |
| 602 | }, |
| 603 | categoryCost: { |
| 604 | ...categoryCost, |
| 605 | unsplit: Math.max( |
| 606 | 0, |
| 607 | costUsd - |
| 608 | categoryCost.input - |
| 609 | categoryCost.cacheRead - |
| 610 | categoryCost.cacheWrite - |
| 611 | categoryCost.output, |
| 612 | ), |
| 613 | }, |
| 614 | speedCost: { |
| 615 | ...speedCost, |
| 616 | standard: Math.max(0, costUsd - speedCost.fast - speedCost.ultrafast), |
| 617 | }, |
| 618 | duplicateSources: duplicates, |
| 619 | contributingEnvironments, |
| 620 | contractMismatches, |
| 621 | }; |
| 622 | } |