magpie-multi-usage 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,643 @@
1
+ import { sha256CanonicalJson } from "./atomic-fs.mjs";
2
+
3
+ export const SCHEMA_VERSION = 1;
4
+ const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
5
+ const MONTH_PATTERN = /^\d{4}-\d{2}$/;
6
+
7
+ export class AggregatorError extends Error {
8
+ constructor(code, message, options) {
9
+ super(message, options);
10
+ this.name = "AggregatorError";
11
+ this.code = code;
12
+ }
13
+ }
14
+
15
+ function roundCost(value) {
16
+ return Math.round(value * 1e8) / 1e8;
17
+ }
18
+
19
+ function defineProp(target, key, value) {
20
+ Object.defineProperty(target, key, {
21
+ value,
22
+ enumerable: true,
23
+ configurable: true,
24
+ writable: true,
25
+ });
26
+ }
27
+
28
+ function sortNullMap(map) {
29
+ const out = Object.create(null);
30
+ for (const key of Object.keys(map).sort()) {
31
+ defineProp(out, key, map[key]);
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /**
37
+ * Verify that a YYYY-MM-DD string represents an actual Gregorian calendar date.
38
+ */
39
+ export function isValidCalendarDay(dayString) {
40
+ if (typeof dayString !== "string" || !DAY_PATTERN.test(dayString)) {
41
+ return false;
42
+ }
43
+ const [y, m, d] = dayString.split("-").map(Number);
44
+ if (m < 1 || m > 12 || d < 1 || d > 31) {
45
+ return false;
46
+ }
47
+ const dt = new Date(Date.UTC(y, m - 1, d));
48
+ return (
49
+ dt.getUTCFullYear() === y &&
50
+ dt.getUTCMonth() + 1 === m &&
51
+ dt.getUTCDate() === d
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Verify that a YYYY-MM string represents a valid calendar month (01..12).
57
+ */
58
+ export function isValidCalendarMonth(monthString) {
59
+ if (typeof monthString !== "string" || !MONTH_PATTERN.test(monthString)) {
60
+ return false;
61
+ }
62
+ const month = Number(monthString.slice(5, 7));
63
+ return month >= 1 && month <= 12;
64
+ }
65
+
66
+ function assertNonNegativeNumber(value, fieldName, fallback = 0) {
67
+ if (value === undefined || value === null || value === "") {
68
+ return fallback;
69
+ }
70
+ const num = Number(value);
71
+ if (!Number.isFinite(num) || num < 0) {
72
+ throw new AggregatorError("INVALID_METRIC", `${fieldName} must be a non-negative finite number.`);
73
+ }
74
+ return num;
75
+ }
76
+
77
+ function normalizeLabel(value, fallback = "unknown") {
78
+ if (typeof value !== "string") {
79
+ return fallback;
80
+ }
81
+ const trimmed = value.trim();
82
+ return trimmed || fallback;
83
+ }
84
+
85
+ function formatModelKey(provider, model) {
86
+ const cleanProvider = typeof provider === "string" ? provider.trim() : "";
87
+ const cleanModel = typeof model === "string" ? model.trim() : "";
88
+ if (!cleanModel) {
89
+ return cleanProvider ? `${cleanProvider}/unknown` : "unknown";
90
+ }
91
+ if (!cleanProvider) {
92
+ return cleanModel;
93
+ }
94
+ if (cleanModel.startsWith(`${cleanProvider}/`)) {
95
+ return cleanModel;
96
+ }
97
+ return `${cleanProvider}/${cleanModel}`;
98
+ }
99
+
100
+ /**
101
+ * Format an ISO timestamp (or Date / epoch ms) into YYYY-MM-DD and YYYY-MM in
102
+ * the requested timezone (defaults to the local runtime timezone).
103
+ */
104
+ export function formatLocalDateParts(timestamp, timeZone) {
105
+ const date = timestamp instanceof Date ? timestamp : new Date(timestamp);
106
+ if (Number.isNaN(date.getTime())) {
107
+ throw new AggregatorError("INVALID_TIMESTAMP", `Invalid timestamp: ${String(timestamp)}`);
108
+ }
109
+
110
+ const formatter = new Intl.DateTimeFormat("en-CA", {
111
+ timeZone,
112
+ year: "numeric",
113
+ month: "2-digit",
114
+ day: "2-digit",
115
+ });
116
+ const parts = formatter.formatToParts(date);
117
+ const year = parts.find((p) => p.type === "year")?.value;
118
+ const month = parts.find((p) => p.type === "month")?.value;
119
+ const day = parts.find((p) => p.type === "day")?.value;
120
+
121
+ if (!year || !month || !day) {
122
+ throw new AggregatorError("INVALID_TIMESTAMP", `Unable to format date parts for ${date.toISOString()}`);
123
+ }
124
+
125
+ return {
126
+ iso: date.toISOString(),
127
+ day: `${year}-${month}-${day}`,
128
+ month: `${year}-${month}`,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Normalize a raw Magpie feed row into a strictly non-sensitive ledger record.
134
+ * Strips all unapproved fields and validates calendar date/month consistency.
135
+ */
136
+ export function normalizeFeedRow(rawRow, { timeZone } = {}) {
137
+ if (rawRow === null || typeof rawRow !== "object" || Array.isArray(rawRow)) {
138
+ throw new AggregatorError("INVALID_ROW", "Feed row must be an object.");
139
+ }
140
+
141
+ const id = typeof rawRow.id === "string" ? rawRow.id.trim() : "";
142
+ if (!id) {
143
+ throw new AggregatorError("INVALID_ROW", "Feed row must include a non-empty string id.");
144
+ }
145
+
146
+ const rawTime = rawRow.t ?? rawRow.time ?? rawRow.timestamp;
147
+ if (rawTime === undefined || rawTime === null || rawTime === "") {
148
+ throw new AggregatorError("INVALID_ROW", `Feed row ${id} is missing timestamp t.`);
149
+ }
150
+ const dateParts = formatLocalDateParts(rawTime, timeZone);
151
+
152
+ let day = dateParts.day;
153
+ if (rawRow.day !== undefined && rawRow.day !== null && rawRow.day !== "") {
154
+ if (!isValidCalendarDay(rawRow.day)) {
155
+ throw new AggregatorError("INVALID_ROW", `Feed row ${id} has an invalid calendar day: ${String(rawRow.day)}`);
156
+ }
157
+ day = rawRow.day;
158
+ }
159
+
160
+ let month = day.slice(0, 7);
161
+ if (rawRow.month !== undefined && rawRow.month !== null && rawRow.month !== "") {
162
+ if (!isValidCalendarMonth(rawRow.month) || rawRow.month !== day.slice(0, 7)) {
163
+ throw new AggregatorError(
164
+ "INVALID_ROW",
165
+ `Feed row ${id} has month ${String(rawRow.month)} inconsistent with day ${day}.`,
166
+ );
167
+ }
168
+ month = rawRow.month;
169
+ }
170
+
171
+ const input = assertNonNegativeNumber(rawRow.in ?? rawRow.input, "in");
172
+ const output = assertNonNegativeNumber(rawRow.out ?? rawRow.output, "out");
173
+ const cacheRead = assertNonNegativeNumber(rawRow.cache_read ?? rawRow.cacheRead, "cache_read");
174
+ const cacheWrite = assertNonNegativeNumber(rawRow.cache_write ?? rawRow.cacheWrite, "cache_write");
175
+ const cost = roundCost(assertNonNegativeNumber(rawRow.cost, "cost"));
176
+
177
+ const statusRaw = rawRow.status === undefined || rawRow.status === null ? 200 : Number(rawRow.status);
178
+ if (!Number.isInteger(statusRaw) || statusRaw < 0) {
179
+ throw new AggregatorError("INVALID_ROW", `Feed row ${id} has an invalid status.`);
180
+ }
181
+
182
+ const seq = Number.isInteger(rawRow.seq) && rawRow.seq >= 0 ? rawRow.seq : null;
183
+
184
+ const record = {
185
+ id,
186
+ t: dateParts.iso,
187
+ day,
188
+ month,
189
+ agent: normalizeLabel(rawRow.agent, "unknown"),
190
+ provider: normalizeLabel(rawRow.provider, "unknown"),
191
+ model: normalizeLabel(rawRow.model, "unknown"),
192
+ in: input,
193
+ out: output,
194
+ cacheRead,
195
+ cacheWrite,
196
+ cost,
197
+ status: statusRaw,
198
+ canceled: Boolean(rawRow.canceled),
199
+ via: typeof rawRow.via === "string" ? rawRow.via.trim() : "",
200
+ };
201
+ if (seq !== null) {
202
+ record.seq = seq;
203
+ }
204
+ return record;
205
+ }
206
+
207
+ /**
208
+ * Matches Magpie's error counting rule:
209
+ * failed if not canceled and (status >= 400 or status === 0).
210
+ */
211
+ export function isErrorRow(row) {
212
+ return !row.canceled && (row.status >= 400 || row.status === 0);
213
+ }
214
+
215
+ function createEmptyBucket() {
216
+ return {
217
+ calls: 0,
218
+ errors: 0,
219
+ input: 0,
220
+ output: 0,
221
+ cacheRead: 0,
222
+ cacheWrite: 0,
223
+ cost: 0,
224
+ };
225
+ }
226
+
227
+ function createEmptyDayBucket() {
228
+ return {
229
+ calls: 0,
230
+ errors: 0,
231
+ excludedForwarded: 0,
232
+ input: 0,
233
+ output: 0,
234
+ cacheRead: 0,
235
+ cacheWrite: 0,
236
+ cost: 0,
237
+ byModel: Object.create(null),
238
+ byAgent: Object.create(null),
239
+ byProvider: Object.create(null),
240
+ };
241
+ }
242
+
243
+ function addMetrics(target, delta) {
244
+ target.calls += delta.calls;
245
+ target.errors += delta.errors;
246
+ target.input += delta.input;
247
+ target.output += delta.output;
248
+ target.cacheRead += delta.cacheRead;
249
+ target.cacheWrite += delta.cacheWrite;
250
+ target.cost = roundCost(target.cost + delta.cost);
251
+ }
252
+
253
+ function addRowToBreakdown(map, key, row, errored) {
254
+ if (!Object.prototype.hasOwnProperty.call(map, key)) {
255
+ defineProp(map, key, createEmptyBucket());
256
+ }
257
+ addMetrics(map[key], {
258
+ calls: 1,
259
+ errors: errored ? 1 : 0,
260
+ input: row.in,
261
+ output: row.out,
262
+ cacheRead: row.cacheRead,
263
+ cacheWrite: row.cacheWrite,
264
+ cost: row.cost,
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Compute stable content SHA-256 for a monthly snapshot, excluding volatile
270
+ * metadata (revision, updatedAt) so unchanged months trigger zero writes.
271
+ */
272
+ export function computeMonthContentHash(snapshot) {
273
+ return sha256CanonicalJson({
274
+ schemaVersion: snapshot.schemaVersion,
275
+ deviceId: snapshot.deviceId,
276
+ month: snapshot.month,
277
+ days: snapshot.days,
278
+ });
279
+ }
280
+
281
+ /**
282
+ * Build a schemaVersion 1 monthly aggregate snapshot (<YYYY-MM>.json) from
283
+ * normalized local rows.
284
+ */
285
+ export function buildMonthlySnapshot({
286
+ deviceId,
287
+ month,
288
+ rows = [],
289
+ revision = 1,
290
+ updatedAt = new Date().toISOString(),
291
+ filterForwarded = true,
292
+ }) {
293
+ if (!deviceId || typeof deviceId !== "string") {
294
+ throw new AggregatorError("INVALID_DEVICE_ID", "deviceId is required.");
295
+ }
296
+ if (!isValidCalendarMonth(month)) {
297
+ throw new AggregatorError("INVALID_MONTH", `Invalid month format: ${month}`);
298
+ }
299
+
300
+ const days = Object.create(null);
301
+ for (const row of rows) {
302
+ if (row.month !== month) {
303
+ continue;
304
+ }
305
+ if (!Object.prototype.hasOwnProperty.call(days, row.day)) {
306
+ defineProp(days, row.day, createEmptyDayBucket());
307
+ }
308
+ const dayBucket = days[row.day];
309
+
310
+ if (filterForwarded && row.via !== "") {
311
+ dayBucket.excludedForwarded += 1;
312
+ continue;
313
+ }
314
+
315
+ const errored = isErrorRow(row);
316
+ addMetrics(dayBucket, {
317
+ calls: 1,
318
+ errors: errored ? 1 : 0,
319
+ input: row.in,
320
+ output: row.out,
321
+ cacheRead: row.cacheRead,
322
+ cacheWrite: row.cacheWrite,
323
+ cost: row.cost,
324
+ });
325
+
326
+ addRowToBreakdown(dayBucket.byModel, formatModelKey(row.provider, row.model), row, errored);
327
+ addRowToBreakdown(dayBucket.byAgent, row.agent || "unknown", row, errored);
328
+ addRowToBreakdown(dayBucket.byProvider, row.provider || "unknown", row, errored);
329
+ }
330
+
331
+ const sortedDays = Object.create(null);
332
+ for (const dayKey of Object.keys(days).sort()) {
333
+ const bucket = days[dayKey];
334
+ defineProp(sortedDays, dayKey, {
335
+ ...bucket,
336
+ byModel: sortNullMap(bucket.byModel),
337
+ byAgent: sortNullMap(bucket.byAgent),
338
+ byProvider: sortNullMap(bucket.byProvider),
339
+ });
340
+ }
341
+
342
+ const snapshot = {
343
+ schemaVersion: SCHEMA_VERSION,
344
+ deviceId,
345
+ month,
346
+ revision,
347
+ updatedAt,
348
+ days: sortedDays,
349
+ };
350
+
351
+ return {
352
+ snapshot,
353
+ sha256: computeMonthContentHash(snapshot),
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Build a schemaVersion 1 device manifest (manifest.json) from monthly snapshots.
359
+ */
360
+ export function buildDeviceManifest({
361
+ deviceId,
362
+ displayName,
363
+ platform = process.platform,
364
+ pluginVersion = "0.1.1",
365
+ revision = 1,
366
+ updatedAt = new Date().toISOString(),
367
+ snapshots = [],
368
+ }) {
369
+ if (!deviceId || typeof deviceId !== "string") {
370
+ throw new AggregatorError("INVALID_DEVICE_ID", "deviceId is required.");
371
+ }
372
+
373
+ const months = Object.create(null);
374
+ let firstDay = null;
375
+ let lastDay = null;
376
+
377
+ const sortedSnapshots = [...snapshots].sort((a, b) => a.month.localeCompare(b.month));
378
+ for (const snap of sortedSnapshots) {
379
+ const dayKeys = Object.keys(snap.days || {}).sort();
380
+ if (dayKeys.length === 0) {
381
+ continue;
382
+ }
383
+ let calls = 0;
384
+ for (const dayKey of dayKeys) {
385
+ calls += snap.days[dayKey].calls || 0;
386
+ if (firstDay === null || dayKey < firstDay) {
387
+ firstDay = dayKey;
388
+ }
389
+ if (lastDay === null || dayKey > lastDay) {
390
+ lastDay = dayKey;
391
+ }
392
+ }
393
+ defineProp(months, snap.month, {
394
+ sha256: computeMonthContentHash(snap),
395
+ days: dayKeys.length,
396
+ calls,
397
+ });
398
+ }
399
+
400
+ return {
401
+ schemaVersion: SCHEMA_VERSION,
402
+ deviceId,
403
+ displayName: typeof displayName === "string" && displayName.trim() ? displayName.trim() : deviceId,
404
+ platform,
405
+ pluginVersion,
406
+ revision,
407
+ updatedAt,
408
+ coverage: {
409
+ firstDay,
410
+ lastDay,
411
+ },
412
+ months,
413
+ };
414
+ }
415
+
416
+ function shiftCalendarDay(dayString, offsetDays) {
417
+ if (!isValidCalendarDay(dayString)) {
418
+ throw new AggregatorError("INVALID_DAY", `Invalid YYYY-MM-DD date: ${dayString}`);
419
+ }
420
+ const [y, m, d] = dayString.split("-").map(Number);
421
+ const utcDate = new Date(Date.UTC(y, m - 1, d + offsetDays));
422
+ const yy = String(utcDate.getUTCFullYear()).padStart(4, "0");
423
+ const mm = String(utcDate.getUTCMonth() + 1).padStart(2, "0");
424
+ const dd = String(utcDate.getUTCDate()).padStart(2, "0");
425
+ return `${yy}-${mm}-${dd}`;
426
+ }
427
+
428
+ /**
429
+ * Resolve inclusive YYYY-MM-DD bounds for supported dashboard ranges.
430
+ */
431
+ export function getDateRangeBounds(range, todayDay) {
432
+ if (range === "all") {
433
+ return { startDay: null, endDay: null };
434
+ }
435
+ if (!isValidCalendarDay(todayDay)) {
436
+ throw new AggregatorError("INVALID_DAY", `todayDay must be a valid YYYY-MM-DD date, got: ${todayDay}`);
437
+ }
438
+ if (range === "today") {
439
+ return { startDay: todayDay, endDay: todayDay };
440
+ }
441
+ if (range === "7d") {
442
+ return { startDay: shiftCalendarDay(todayDay, -6), endDay: todayDay };
443
+ }
444
+ if (range === "30d") {
445
+ return { startDay: shiftCalendarDay(todayDay, -29), endDay: todayDay };
446
+ }
447
+ throw new AggregatorError("INVALID_RANGE", `Unsupported range: ${range}`);
448
+ }
449
+
450
+ function computeTotalTokens(metrics) {
451
+ return metrics.input + metrics.output + metrics.cacheRead + metrics.cacheWrite;
452
+ }
453
+
454
+ /**
455
+ * Matches Magpie's Totals.HitRate() formula (internal/usage/usage.go):
456
+ * cacheRead / (input + cacheRead + cacheWrite).
457
+ */
458
+ export function computeCacheHitRatio(metrics) {
459
+ const denom = metrics.input + metrics.cacheRead + metrics.cacheWrite;
460
+ if (denom <= 0) {
461
+ return 0;
462
+ }
463
+ return Math.round((metrics.cacheRead / denom) * 10000) / 10000;
464
+ }
465
+
466
+ function mergeBreakdownMap(targetMap, sourceMap) {
467
+ if (!sourceMap || typeof sourceMap !== "object") {
468
+ return;
469
+ }
470
+ for (const key of Object.keys(sourceMap)) {
471
+ const bucket = sourceMap[key];
472
+ if (!bucket || typeof bucket !== "object") {
473
+ continue;
474
+ }
475
+ if (!Object.prototype.hasOwnProperty.call(targetMap, key)) {
476
+ defineProp(targetMap, key, createEmptyBucket());
477
+ }
478
+ addMetrics(targetMap[key], {
479
+ calls: bucket.calls || 0,
480
+ errors: bucket.errors || 0,
481
+ input: bucket.input || 0,
482
+ output: bucket.output || 0,
483
+ cacheRead: bucket.cacheRead || 0,
484
+ cacheWrite: bucket.cacheWrite || 0,
485
+ cost: bucket.cost || 0,
486
+ });
487
+ }
488
+ }
489
+
490
+ function sortBreakdownEntries(map) {
491
+ return Object.keys(map)
492
+ .map((name) => {
493
+ const metrics = map[name];
494
+ return {
495
+ name,
496
+ ...metrics,
497
+ totalTokens: computeTotalTokens(metrics),
498
+ };
499
+ })
500
+ .sort((a, b) => b.totalTokens - a.totalTokens || b.cost - a.cost || a.name.localeCompare(b.name));
501
+ }
502
+
503
+ /**
504
+ * Aggregate local and cached remote device snapshots across a date range and
505
+ * optional device filter.
506
+ */
507
+ export function aggregateDevices({
508
+ devices = [],
509
+ range = "7d",
510
+ deviceFilter = "all",
511
+ todayDay = formatLocalDateParts(new Date()).day,
512
+ } = {}) {
513
+ const bounds = getDateRangeBounds(range, todayDay);
514
+
515
+ const combinedTotals = {
516
+ ...createEmptyBucket(),
517
+ excludedForwarded: 0,
518
+ };
519
+ const dailyMap = Object.create(null);
520
+ const modelMap = Object.create(null);
521
+ const agentMap = Object.create(null);
522
+ const providerMap = Object.create(null);
523
+ const deviceSummaries = [];
524
+
525
+ for (const device of devices) {
526
+ const deviceTotals = {
527
+ ...createEmptyBucket(),
528
+ excludedForwarded: 0,
529
+ };
530
+ let coverageFirstDay = null;
531
+ let coverageLastDay = null;
532
+
533
+ const included = deviceFilter === "all" || deviceFilter === device.deviceId;
534
+
535
+ for (const snapshot of device.months || []) {
536
+ const days = snapshot?.days || {};
537
+ for (const dayKey of Object.keys(days)) {
538
+ if (!isValidCalendarDay(dayKey)) {
539
+ continue;
540
+ }
541
+ const dayBucket = days[dayKey];
542
+ if (!dayBucket || typeof dayBucket !== "object") {
543
+ continue;
544
+ }
545
+ if (coverageFirstDay === null || dayKey < coverageFirstDay) {
546
+ coverageFirstDay = dayKey;
547
+ }
548
+ if (coverageLastDay === null || dayKey > coverageLastDay) {
549
+ coverageLastDay = dayKey;
550
+ }
551
+
552
+ if (bounds.startDay && dayKey < bounds.startDay) {
553
+ continue;
554
+ }
555
+ if (bounds.endDay && dayKey > bounds.endDay) {
556
+ continue;
557
+ }
558
+
559
+ const delta = {
560
+ calls: dayBucket.calls || 0,
561
+ errors: dayBucket.errors || 0,
562
+ input: dayBucket.input || 0,
563
+ output: dayBucket.output || 0,
564
+ cacheRead: dayBucket.cacheRead || 0,
565
+ cacheWrite: dayBucket.cacheWrite || 0,
566
+ cost: dayBucket.cost || 0,
567
+ };
568
+ const excluded = dayBucket.excludedForwarded || 0;
569
+
570
+ addMetrics(deviceTotals, delta);
571
+ deviceTotals.excludedForwarded += excluded;
572
+
573
+ if (included) {
574
+ addMetrics(combinedTotals, delta);
575
+ combinedTotals.excludedForwarded += excluded;
576
+
577
+ if (!Object.prototype.hasOwnProperty.call(dailyMap, dayKey)) {
578
+ defineProp(dailyMap, dayKey, { ...createEmptyBucket(), excludedForwarded: 0 });
579
+ }
580
+ addMetrics(dailyMap[dayKey], delta);
581
+ dailyMap[dayKey].excludedForwarded += excluded;
582
+
583
+ mergeBreakdownMap(modelMap, dayBucket.byModel);
584
+ mergeBreakdownMap(agentMap, dayBucket.byAgent);
585
+ mergeBreakdownMap(providerMap, dayBucket.byProvider);
586
+ }
587
+ }
588
+ }
589
+
590
+ const safeName = typeof device.displayName === "string" && device.displayName.trim()
591
+ ? device.displayName.trim()
592
+ : String(device.deviceId || "unknown");
593
+
594
+ deviceSummaries.push({
595
+ deviceId: String(device.deviceId || ""),
596
+ displayName: safeName,
597
+ isLocal: Boolean(device.isLocal),
598
+ status: device.status || (coverageFirstDay ? "ok" : "empty"),
599
+ lastSyncedAt: device.lastSyncedAt || null,
600
+ lastError: device.lastError || null,
601
+ coverage: {
602
+ firstDay: coverageFirstDay,
603
+ lastDay: coverageLastDay,
604
+ },
605
+ totals: {
606
+ ...deviceTotals,
607
+ totalTokens: computeTotalTokens(deviceTotals),
608
+ cacheHitRatio: computeCacheHitRatio(deviceTotals),
609
+ },
610
+ });
611
+ }
612
+
613
+ deviceSummaries.sort((a, b) => {
614
+ if (a.isLocal !== b.isLocal) {
615
+ return a.isLocal ? -1 : 1;
616
+ }
617
+ return b.totals.totalTokens - a.totals.totalTokens || a.displayName.localeCompare(b.displayName);
618
+ });
619
+
620
+ const daily = Object.keys(dailyMap)
621
+ .sort()
622
+ .map((day) => ({
623
+ day,
624
+ ...dailyMap[day],
625
+ totalTokens: computeTotalTokens(dailyMap[day]),
626
+ }));
627
+
628
+ return {
629
+ range,
630
+ deviceFilter,
631
+ bounds,
632
+ totals: {
633
+ ...combinedTotals,
634
+ totalTokens: computeTotalTokens(combinedTotals),
635
+ cacheHitRatio: computeCacheHitRatio(combinedTotals),
636
+ },
637
+ devices: deviceSummaries,
638
+ daily,
639
+ topModels: sortBreakdownEntries(modelMap),
640
+ topAgents: sortBreakdownEntries(agentMap),
641
+ topProviders: sortBreakdownEntries(providerMap),
642
+ };
643
+ }