tokenusage-cli 0.1.0 → 0.2.0

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +39 -19
  2. package/LICENSE +22 -22
  3. package/README.md +94 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +181 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,236 +1,236 @@
1
- "use strict";
2
-
3
- /**
4
- * Wrapped aggregator — turns a list of queue.jsonl rows into a year-end
5
- * summary suitable for the `tracker wrapped` CLI command and the
6
- * /wrapped dashboard page.
7
- *
8
- * Input rows: { source, model, hour_start, input_tokens, cached_input_tokens,
9
- * cache_creation_input_tokens, output_tokens,
10
- * reasoning_output_tokens, total_tokens, conversation_count, ... }
11
- *
12
- * Output is a plain object (JSON-serializable) — no UI or stringification
13
- * concerns leak in here so the same aggregator powers the CLI and the
14
- * React Wrapped page.
15
- */
16
-
17
- // Lazy require to avoid loading the full local-api module (and its pricing
18
- // tables) until rows are actually aggregated. local-api.js itself requires
19
- // this module lazily inside a handler, so there is no top-level cycle either
20
- // way — but keeping this lazy preserves wrapped-aggregator as a light import.
21
- function normalizeQueueRow(row) {
22
- return require("./local-api").normalizeQueueRow(row);
23
- }
24
-
25
- function isFiniteNumber(n) {
26
- return typeof n === "number" && Number.isFinite(n);
27
- }
28
-
29
- function rowTokens(row) {
30
- return isFiniteNumber(row.billable_total_tokens)
31
- ? row.billable_total_tokens
32
- : isFiniteNumber(row.total_tokens)
33
- ? row.total_tokens
34
- : 0;
35
- }
36
-
37
- function rowDay(row) {
38
- // hour_start is ISO 8601 UTC. Slice to YYYY-MM-DD.
39
- return typeof row.hour_start === "string" ? row.hour_start.slice(0, 10) : null;
40
- }
41
-
42
- function rowYear(row) {
43
- const d = rowDay(row);
44
- if (!d) return null;
45
- return Number(d.slice(0, 4));
46
- }
47
-
48
- function isoHour(row) {
49
- // "2026-04-05T14:30:00.000Z" → 14
50
- if (typeof row.hour_start !== "string") return null;
51
- const m = /T(\d{2}):/.exec(row.hour_start);
52
- return m ? Number(m[1]) : null;
53
- }
54
-
55
- function topByValue(map, n) {
56
- return Array.from(map.entries())
57
- .sort((a, b) => b[1] - a[1])
58
- .slice(0, n);
59
- }
60
-
61
- /**
62
- * Compute a year-end Wrapped summary from queue rows.
63
- *
64
- * @param {Array} rows — Array of queue.jsonl objects.
65
- * @param {Object} [opts]
66
- * @param {number} [opts.year] — Restrict to a single calendar year (UTC).
67
- * Defaults to the most-recent year present.
68
- * @returns {Object} Wrapped summary.
69
- */
70
- function aggregateWrapped(rows, opts = {}) {
71
- // queue.jsonl is append-only: each sync re-emits the cumulative totals for
72
- // every touched (source, model, hour_start). Naively summing every row
73
- // double-counts every previously synced bucket. Keep only the latest entry
74
- // per tuple — same dedup rule that local-api.js readQueueData enforces for
75
- // the dashboard. This makes `tracker wrapped` totals match what the
76
- // /wrapped dashboard page shows.
77
- const dedup = new Map();
78
- for (const row of Array.isArray(rows) ? rows : []) {
79
- if (!row || typeof row !== "object") continue;
80
- const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
81
- // Apply the same legacy-row corrections (codex inclusive-input, cursor
82
- // billable=0) as local-api.js readQueueData so `tracker wrapped` matches
83
- // the dashboard for identical data.
84
- dedup.set(key, normalizeQueueRow(row));
85
- }
86
- const all = Array.from(dedup.values());
87
-
88
- // Decide year to summarize. Prefer caller's year; otherwise the most
89
- // recent year that has data — which during a sync rollover may be the
90
- // current year (even if it has only a week of data).
91
- let year = isFiniteNumber(opts.year) ? Math.floor(opts.year) : null;
92
- if (year == null) {
93
- let latest = null;
94
- for (const r of all) {
95
- const y = rowYear(r);
96
- if (y != null && (latest == null || y > latest)) latest = y;
97
- }
98
- year = latest ?? new Date().getUTCFullYear();
99
- }
100
-
101
- const filtered = all.filter((r) => rowYear(r) === year);
102
-
103
- if (filtered.length === 0) {
104
- return {
105
- year,
106
- range: { from: null, to: null },
107
- totals: { tokens: 0, conversations: 0, sources: 0, models: 0, active_days: 0 },
108
- top: { sources: [], models: [], days: [] },
109
- peak_hour: null,
110
- longest_streak: { days: 0, from: null, to: null },
111
- highlights: [],
112
- };
113
- }
114
-
115
- // Group: source, model, day, hour-of-day
116
- const tokensBySource = new Map();
117
- const tokensByModel = new Map();
118
- const tokensByDay = new Map();
119
- const tokensByHourOfDay = new Map();
120
- let totalTokens = 0;
121
- let totalConvs = 0;
122
- let earliest = null;
123
- let latest = null;
124
-
125
- for (const row of filtered) {
126
- const t = rowTokens(row);
127
- totalTokens += t;
128
- if (isFiniteNumber(row.conversation_count)) totalConvs += row.conversation_count;
129
- if (row.source) tokensBySource.set(row.source, (tokensBySource.get(row.source) || 0) + t);
130
- if (row.model) tokensByModel.set(row.model, (tokensByModel.get(row.model) || 0) + t);
131
- const day = rowDay(row);
132
- if (day) tokensByDay.set(day, (tokensByDay.get(day) || 0) + t);
133
- const h = isoHour(row);
134
- if (h != null) tokensByHourOfDay.set(h, (tokensByHourOfDay.get(h) || 0) + t);
135
- if (row.hour_start) {
136
- if (!earliest || row.hour_start < earliest) earliest = row.hour_start;
137
- if (!latest || row.hour_start > latest) latest = row.hour_start;
138
- }
139
- }
140
-
141
- // Longest consecutive day streak among days with non-zero tokens.
142
- const activeDays = Array.from(tokensByDay.keys()).sort();
143
- let longestStreak = { days: 0, from: null, to: null };
144
- if (activeDays.length > 0) {
145
- let runStart = activeDays[0];
146
- let runPrev = activeDays[0];
147
- let runLen = 1;
148
- const stepDay = (iso, delta) => {
149
- const dt = new Date(iso + "T00:00:00Z");
150
- dt.setUTCDate(dt.getUTCDate() + delta);
151
- return dt.toISOString().slice(0, 10);
152
- };
153
- longestStreak = { days: 1, from: runStart, to: runStart };
154
- for (let i = 1; i < activeDays.length; i++) {
155
- const day = activeDays[i];
156
- if (day === stepDay(runPrev, 1)) {
157
- runLen++;
158
- runPrev = day;
159
- } else {
160
- runStart = day;
161
- runPrev = day;
162
- runLen = 1;
163
- }
164
- if (runLen > longestStreak.days) {
165
- longestStreak = { days: runLen, from: runStart, to: runPrev };
166
- }
167
- }
168
- }
169
-
170
- // Peak hour-of-day (UTC).
171
- let peakHour = null;
172
- if (tokensByHourOfDay.size > 0) {
173
- const top = topByValue(tokensByHourOfDay, 1)[0];
174
- peakHour = { hour: top[0], tokens: top[1] };
175
- }
176
-
177
- const topSources = topByValue(tokensBySource, 5).map(([source, tokens]) => ({
178
- source,
179
- tokens,
180
- share: totalTokens > 0 ? tokens / totalTokens : 0,
181
- }));
182
- const topModels = topByValue(tokensByModel, 5).map(([model, tokens]) => ({
183
- model,
184
- tokens,
185
- share: totalTokens > 0 ? tokens / totalTokens : 0,
186
- }));
187
- const topDays = topByValue(tokensByDay, 5).map(([day, tokens]) => ({ day, tokens }));
188
-
189
- // Highlights — short, share-friendly one-liners derived from the numbers.
190
- const highlights = [];
191
- if (topModels.length > 0) {
192
- const m = topModels[0];
193
- highlights.push(`${m.model} powered ${(m.share * 100).toFixed(0)}% of your year.`);
194
- }
195
- if (topDays.length > 0) {
196
- const d = topDays[0];
197
- highlights.push(`Your busiest day was ${d.day} (${formatCompact(d.tokens)} tokens).`);
198
- }
199
- if (peakHour) {
200
- highlights.push(`You hit peak flow around ${String(peakHour.hour).padStart(2, "0")}:00 UTC.`);
201
- }
202
- if (longestStreak.days >= 2) {
203
- highlights.push(`Longest streak: ${longestStreak.days} consecutive days of coding with AI.`);
204
- }
205
- if (tokensBySource.size >= 4) {
206
- highlights.push(`You touched ${tokensBySource.size} different AI tools — that's range.`);
207
- }
208
-
209
- return {
210
- year,
211
- range: { from: earliest, to: latest },
212
- totals: {
213
- tokens: totalTokens,
214
- conversations: totalConvs,
215
- sources: tokensBySource.size,
216
- models: tokensByModel.size,
217
- active_days: activeDays.length,
218
- },
219
- top: { sources: topSources, models: topModels, days: topDays },
220
- peak_hour: peakHour,
221
- longest_streak: longestStreak,
222
- highlights,
223
- };
224
- }
225
-
226
- function formatCompact(n) {
227
- if (!Number.isFinite(n)) return "0";
228
- const abs = Math.abs(n);
229
- if (abs >= 1e12) return (n / 1e12).toFixed(2).replace(/\.?0+$/, "") + "T";
230
- if (abs >= 1e9) return (n / 1e9).toFixed(2).replace(/\.?0+$/, "") + "B";
231
- if (abs >= 1e6) return (n / 1e6).toFixed(2).replace(/\.?0+$/, "") + "M";
232
- if (abs >= 1e3) return (n / 1e3).toFixed(2).replace(/\.?0+$/, "") + "K";
233
- return String(Math.round(n));
234
- }
235
-
236
- module.exports = { aggregateWrapped, formatCompact };
1
+ "use strict";
2
+
3
+ /**
4
+ * Wrapped aggregator — turns a list of queue.jsonl rows into a year-end
5
+ * summary suitable for the `tracker wrapped` CLI command and the
6
+ * /wrapped dashboard page.
7
+ *
8
+ * Input rows: { source, model, hour_start, input_tokens, cached_input_tokens,
9
+ * cache_creation_input_tokens, output_tokens,
10
+ * reasoning_output_tokens, total_tokens, conversation_count, ... }
11
+ *
12
+ * Output is a plain object (JSON-serializable) — no UI or stringification
13
+ * concerns leak in here so the same aggregator powers the CLI and the
14
+ * React Wrapped page.
15
+ */
16
+
17
+ // Lazy require to avoid loading the full local-api module (and its pricing
18
+ // tables) until rows are actually aggregated. local-api.js itself requires
19
+ // this module lazily inside a handler, so there is no top-level cycle either
20
+ // way — but keeping this lazy preserves wrapped-aggregator as a light import.
21
+ function normalizeQueueRow(row) {
22
+ return require("./local-api").normalizeQueueRow(row);
23
+ }
24
+
25
+ function isFiniteNumber(n) {
26
+ return typeof n === "number" && Number.isFinite(n);
27
+ }
28
+
29
+ function rowTokens(row) {
30
+ return isFiniteNumber(row.billable_total_tokens)
31
+ ? row.billable_total_tokens
32
+ : isFiniteNumber(row.total_tokens)
33
+ ? row.total_tokens
34
+ : 0;
35
+ }
36
+
37
+ function rowDay(row) {
38
+ // hour_start is ISO 8601 UTC. Slice to YYYY-MM-DD.
39
+ return typeof row.hour_start === "string" ? row.hour_start.slice(0, 10) : null;
40
+ }
41
+
42
+ function rowYear(row) {
43
+ const d = rowDay(row);
44
+ if (!d) return null;
45
+ return Number(d.slice(0, 4));
46
+ }
47
+
48
+ function isoHour(row) {
49
+ // "2026-04-05T14:30:00.000Z" → 14
50
+ if (typeof row.hour_start !== "string") return null;
51
+ const m = /T(\d{2}):/.exec(row.hour_start);
52
+ return m ? Number(m[1]) : null;
53
+ }
54
+
55
+ function topByValue(map, n) {
56
+ return Array.from(map.entries())
57
+ .sort((a, b) => b[1] - a[1])
58
+ .slice(0, n);
59
+ }
60
+
61
+ /**
62
+ * Compute a year-end Wrapped summary from queue rows.
63
+ *
64
+ * @param {Array} rows — Array of queue.jsonl objects.
65
+ * @param {Object} [opts]
66
+ * @param {number} [opts.year] — Restrict to a single calendar year (UTC).
67
+ * Defaults to the most-recent year present.
68
+ * @returns {Object} Wrapped summary.
69
+ */
70
+ function aggregateWrapped(rows, opts = {}) {
71
+ // queue.jsonl is append-only: each sync re-emits the cumulative totals for
72
+ // every touched (source, model, hour_start). Naively summing every row
73
+ // double-counts every previously synced bucket. Keep only the latest entry
74
+ // per tuple — same dedup rule that local-api.js readQueueData enforces for
75
+ // the dashboard. This makes `tracker wrapped` totals match what the
76
+ // /wrapped dashboard page shows.
77
+ const dedup = new Map();
78
+ for (const row of Array.isArray(rows) ? rows : []) {
79
+ if (!row || typeof row !== "object") continue;
80
+ const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
81
+ // Apply the same legacy-row corrections (codex inclusive-input, cursor
82
+ // billable=0) as local-api.js readQueueData so `tracker wrapped` matches
83
+ // the dashboard for identical data.
84
+ dedup.set(key, normalizeQueueRow(row));
85
+ }
86
+ const all = Array.from(dedup.values());
87
+
88
+ // Decide year to summarize. Prefer caller's year; otherwise the most
89
+ // recent year that has data — which during a sync rollover may be the
90
+ // current year (even if it has only a week of data).
91
+ let year = isFiniteNumber(opts.year) ? Math.floor(opts.year) : null;
92
+ if (year == null) {
93
+ let latest = null;
94
+ for (const r of all) {
95
+ const y = rowYear(r);
96
+ if (y != null && (latest == null || y > latest)) latest = y;
97
+ }
98
+ year = latest ?? new Date().getUTCFullYear();
99
+ }
100
+
101
+ const filtered = all.filter((r) => rowYear(r) === year);
102
+
103
+ if (filtered.length === 0) {
104
+ return {
105
+ year,
106
+ range: { from: null, to: null },
107
+ totals: { tokens: 0, conversations: 0, sources: 0, models: 0, active_days: 0 },
108
+ top: { sources: [], models: [], days: [] },
109
+ peak_hour: null,
110
+ longest_streak: { days: 0, from: null, to: null },
111
+ highlights: [],
112
+ };
113
+ }
114
+
115
+ // Group: source, model, day, hour-of-day
116
+ const tokensBySource = new Map();
117
+ const tokensByModel = new Map();
118
+ const tokensByDay = new Map();
119
+ const tokensByHourOfDay = new Map();
120
+ let totalTokens = 0;
121
+ let totalConvs = 0;
122
+ let earliest = null;
123
+ let latest = null;
124
+
125
+ for (const row of filtered) {
126
+ const t = rowTokens(row);
127
+ totalTokens += t;
128
+ if (isFiniteNumber(row.conversation_count)) totalConvs += row.conversation_count;
129
+ if (row.source) tokensBySource.set(row.source, (tokensBySource.get(row.source) || 0) + t);
130
+ if (row.model) tokensByModel.set(row.model, (tokensByModel.get(row.model) || 0) + t);
131
+ const day = rowDay(row);
132
+ if (day) tokensByDay.set(day, (tokensByDay.get(day) || 0) + t);
133
+ const h = isoHour(row);
134
+ if (h != null) tokensByHourOfDay.set(h, (tokensByHourOfDay.get(h) || 0) + t);
135
+ if (row.hour_start) {
136
+ if (!earliest || row.hour_start < earliest) earliest = row.hour_start;
137
+ if (!latest || row.hour_start > latest) latest = row.hour_start;
138
+ }
139
+ }
140
+
141
+ // Longest consecutive day streak among days with non-zero tokens.
142
+ const activeDays = Array.from(tokensByDay.keys()).sort();
143
+ let longestStreak = { days: 0, from: null, to: null };
144
+ if (activeDays.length > 0) {
145
+ let runStart = activeDays[0];
146
+ let runPrev = activeDays[0];
147
+ let runLen = 1;
148
+ const stepDay = (iso, delta) => {
149
+ const dt = new Date(iso + "T00:00:00Z");
150
+ dt.setUTCDate(dt.getUTCDate() + delta);
151
+ return dt.toISOString().slice(0, 10);
152
+ };
153
+ longestStreak = { days: 1, from: runStart, to: runStart };
154
+ for (let i = 1; i < activeDays.length; i++) {
155
+ const day = activeDays[i];
156
+ if (day === stepDay(runPrev, 1)) {
157
+ runLen++;
158
+ runPrev = day;
159
+ } else {
160
+ runStart = day;
161
+ runPrev = day;
162
+ runLen = 1;
163
+ }
164
+ if (runLen > longestStreak.days) {
165
+ longestStreak = { days: runLen, from: runStart, to: runPrev };
166
+ }
167
+ }
168
+ }
169
+
170
+ // Peak hour-of-day (UTC).
171
+ let peakHour = null;
172
+ if (tokensByHourOfDay.size > 0) {
173
+ const top = topByValue(tokensByHourOfDay, 1)[0];
174
+ peakHour = { hour: top[0], tokens: top[1] };
175
+ }
176
+
177
+ const topSources = topByValue(tokensBySource, 5).map(([source, tokens]) => ({
178
+ source,
179
+ tokens,
180
+ share: totalTokens > 0 ? tokens / totalTokens : 0,
181
+ }));
182
+ const topModels = topByValue(tokensByModel, 5).map(([model, tokens]) => ({
183
+ model,
184
+ tokens,
185
+ share: totalTokens > 0 ? tokens / totalTokens : 0,
186
+ }));
187
+ const topDays = topByValue(tokensByDay, 5).map(([day, tokens]) => ({ day, tokens }));
188
+
189
+ // Highlights — short, share-friendly one-liners derived from the numbers.
190
+ const highlights = [];
191
+ if (topModels.length > 0) {
192
+ const m = topModels[0];
193
+ highlights.push(`${m.model} powered ${(m.share * 100).toFixed(0)}% of your year.`);
194
+ }
195
+ if (topDays.length > 0) {
196
+ const d = topDays[0];
197
+ highlights.push(`Your busiest day was ${d.day} (${formatCompact(d.tokens)} tokens).`);
198
+ }
199
+ if (peakHour) {
200
+ highlights.push(`You hit peak flow around ${String(peakHour.hour).padStart(2, "0")}:00 UTC.`);
201
+ }
202
+ if (longestStreak.days >= 2) {
203
+ highlights.push(`Longest streak: ${longestStreak.days} consecutive days of coding with AI.`);
204
+ }
205
+ if (tokensBySource.size >= 4) {
206
+ highlights.push(`You touched ${tokensBySource.size} different AI tools — that's range.`);
207
+ }
208
+
209
+ return {
210
+ year,
211
+ range: { from: earliest, to: latest },
212
+ totals: {
213
+ tokens: totalTokens,
214
+ conversations: totalConvs,
215
+ sources: tokensBySource.size,
216
+ models: tokensByModel.size,
217
+ active_days: activeDays.length,
218
+ },
219
+ top: { sources: topSources, models: topModels, days: topDays },
220
+ peak_hour: peakHour,
221
+ longest_streak: longestStreak,
222
+ highlights,
223
+ };
224
+ }
225
+
226
+ function formatCompact(n) {
227
+ if (!Number.isFinite(n)) return "0";
228
+ const abs = Math.abs(n);
229
+ if (abs >= 1e12) return (n / 1e12).toFixed(2).replace(/\.?0+$/, "") + "T";
230
+ if (abs >= 1e9) return (n / 1e9).toFixed(2).replace(/\.?0+$/, "") + "B";
231
+ if (abs >= 1e6) return (n / 1e6).toFixed(2).replace(/\.?0+$/, "") + "M";
232
+ if (abs >= 1e3) return (n / 1e3).toFixed(2).replace(/\.?0+$/, "") + "K";
233
+ return String(Math.round(n));
234
+ }
235
+
236
+ module.exports = { aggregateWrapped, formatCompact };