tokenusage-cli 0.3.0 → 0.4.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 (47) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +52 -11
  3. package/bin/tokenusage.js +14 -2
  4. package/package.json +1 -2
  5. package/src/cli.js +325 -78
  6. package/src/commands/device-login.js +3 -3
  7. package/src/commands/init.js +343 -153
  8. package/src/commands/pause.js +11 -23
  9. package/src/commands/reconcile.js +485 -0
  10. package/src/commands/sessions.js +57 -14
  11. package/src/commands/sync.js +69 -15
  12. package/src/commands/uninstall.js +6 -9
  13. package/src/commands/upload.js +147 -0
  14. package/src/lib/cli-errors.js +33 -0
  15. package/src/lib/cli-ui.js +93 -0
  16. package/src/lib/queue-row-normalize.js +55 -0
  17. package/src/lib/scheduled-task.js +597 -75
  18. package/src/lib/antigravity-paths.js +0 -48
  19. package/src/lib/async-queue-reader.js +0 -138
  20. package/src/lib/atomic-json.js +0 -27
  21. package/src/lib/bearer-token.js +0 -11
  22. package/src/lib/cloud-account.js +0 -541
  23. package/src/lib/codex-context-breakdown.js +0 -806
  24. package/src/lib/context-health.js +0 -124
  25. package/src/lib/grok-context-breakdown.js +0 -890
  26. package/src/lib/heatmap-compact.js +0 -114
  27. package/src/lib/local-api.js +0 -3574
  28. package/src/lib/outcomes-engine.js +0 -253
  29. package/src/lib/pet-packages.js +0 -722
  30. package/src/lib/skill-usage.js +0 -267
  31. package/src/lib/skills-manager.js +0 -1591
  32. package/src/lib/source-metadata.js +0 -48
  33. package/src/lib/subscription-manager.js +0 -293
  34. package/src/lib/wrapped-aggregator.js +0 -236
  35. package/test/audit-fixes.test.js +0 -249
  36. package/test/branding.test.js +0 -24
  37. package/test/cli-options.test.js +0 -43
  38. package/test/cli-smoke.test.js +0 -53
  39. package/test/cli-ui.test.js +0 -47
  40. package/test/collection-controls.test.js +0 -255
  41. package/test/ingest-sanitize.test.js +0 -162
  42. package/test/packaging.test.js +0 -107
  43. package/test/quiet-warnings.test.js +0 -53
  44. package/test/runtime-copy.test.js +0 -111
  45. package/test/session-upload.test.js +0 -427
  46. package/test/trae-db.test.js +0 -67
  47. package/test/zstd-native.test.js +0 -36
@@ -1,48 +0,0 @@
1
- const ACCOUNT_LEVEL_SOURCES = new Set(["cursor", "trae-cn"]);
2
-
3
- function normalizeSource(value) {
4
- return String(value || "").trim().toLowerCase();
5
- }
6
-
7
- function getSourceScope(source) {
8
- return ACCOUNT_LEVEL_SOURCES.has(normalizeSource(source)) ? "account" : "local";
9
- }
10
-
11
- function isAccountLevelSource(source) {
12
- return getSourceScope(source) === "account";
13
- }
14
-
15
- function normalizeUsageScope(value) {
16
- const raw = String(value || "").trim().toLowerCase();
17
- if (!raw || raw === "all" || raw === "raw") return "all";
18
- if (raw === "personal" || raw === "local") return "personal";
19
- return "all";
20
- }
21
-
22
- function filterRowsByUsageScope(rows, scope = "all") {
23
- const normalizedScope = normalizeUsageScope(scope);
24
- if (normalizedScope === "all") return Array.isArray(rows) ? rows : [];
25
- return (Array.isArray(rows) ? rows : []).filter((row) => !isAccountLevelSource(row?.source));
26
- }
27
-
28
- function listExcludedSources(rows, scope = "all") {
29
- const normalizedScope = normalizeUsageScope(scope);
30
- if (normalizedScope === "all") return [];
31
- const seen = new Set();
32
- const out = [];
33
- for (const row of Array.isArray(rows) ? rows : []) {
34
- const source = normalizeSource(row?.source);
35
- if (!source || seen.has(source) || !isAccountLevelSource(source)) continue;
36
- seen.add(source);
37
- out.push({ source, source_scope: getSourceScope(source), reason: "account_level_source" });
38
- }
39
- return out.sort((a, b) => a.source.localeCompare(b.source));
40
- }
41
-
42
- module.exports = {
43
- getSourceScope,
44
- isAccountLevelSource,
45
- normalizeUsageScope,
46
- filterRowsByUsageScope,
47
- listExcludedSources,
48
- };
@@ -1,293 +0,0 @@
1
- const path = require("node:path");
2
- const fs = require("node:fs/promises");
3
- const crypto = require("node:crypto");
4
-
5
- const { readJsonStrict, writeFileAtomic, chmod600IfPossible } = require("./fs");
6
-
7
- // Manual subscription manager: user-entered billing plans (service, plan,
8
- // auto-renew flag, next renewal/expiry timestamp). Distinct from
9
- // subscriptions.js (auto-detected local plan tiers) and usage-limits.js
10
- // (rate-limit window resets) — see issue #460.
11
- const STORE_FILE = "subscription-manager.json";
12
- const STORE_VERSION = 1;
13
- const MAX_TEXT_LENGTH = 120;
14
- const CYCLE_UNITS = new Set(["weekly", "monthly", "yearly"]);
15
-
16
- function resolveSubscriptionsPath(trackerDir) {
17
- return path.join(trackerDir, STORE_FILE);
18
- }
19
-
20
- function normalizeText(value, { required, field, maxLength = MAX_TEXT_LENGTH } = {}) {
21
- if (value === null || value === undefined) {
22
- if (required) throw new Error(`${field} is required`);
23
- return null;
24
- }
25
- if (typeof value !== "string") throw new Error(`${field} must be a string`);
26
- const trimmed = value.trim();
27
- if (!trimmed) {
28
- if (required) throw new Error(`${field} is required`);
29
- return null;
30
- }
31
- if (trimmed.length > maxLength) {
32
- throw new Error(`${field} must be at most ${maxLength} characters`);
33
- }
34
- return trimmed;
35
- }
36
-
37
- // Accepts epoch milliseconds or any Date-parseable string. Stored values are
38
- // UTC ISO strings truncated to whole minutes so comparisons stay clean and a
39
- // second-level drift between input formats never changes the billed minute.
40
- function normalizeBillingTime(value, { field = "nextBillingAt", required = true } = {}) {
41
- let ms;
42
- if (value === null || value === undefined) {
43
- if (required) throw new Error(`${field} is required`);
44
- return null;
45
- }
46
- if (typeof value === "number") {
47
- ms = value;
48
- } else if (typeof value === "string") {
49
- const trimmed = value.trim();
50
- if (!trimmed) {
51
- if (required) throw new Error(`${field} is required`);
52
- return null;
53
- }
54
- ms = new Date(trimmed).getTime();
55
- } else {
56
- throw new Error(`${field} is required`);
57
- }
58
- if (!Number.isFinite(ms)) throw new Error(`${field} must be a valid date`);
59
- return new Date(Math.floor(ms / 60000) * 60000).toISOString();
60
- }
61
-
62
- // Billing cycle length. Drives the progress bar span and how far an
63
- // auto-renew subscription rolls forward after a recorded renewal passes.
64
- // Defaults to monthly so pre-cycle records keep their original semantics.
65
- function normalizeCycle(value) {
66
- if (value === null || value === undefined) return "monthly";
67
- if (typeof value !== "string" || !CYCLE_UNITS.has(value)) {
68
- throw new Error("cycle must be one of: weekly, monthly, yearly");
69
- }
70
- return value;
71
- }
72
-
73
- function normalizeSubscriptionFields(fields) {
74
- if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
75
- throw new Error("subscription must be an object");
76
- }
77
- if (typeof fields.autoRenew !== "boolean") {
78
- throw new Error("autoRenew must be a boolean");
79
- }
80
- return {
81
- service: normalizeText(fields.service, { required: true, field: "service" }),
82
- plan: normalizeText(fields.plan ?? null, { required: false, field: "plan" }),
83
- // Optional link to a usage-limits provider row (e.g. "codex"). The value
84
- // is a limits provider id but is not validated against the canonical list
85
- // here — the backend stays lenient, the dropdown constrains it in the UI.
86
- provider: normalizeText(fields.provider ?? null, {
87
- required: false,
88
- field: "provider",
89
- maxLength: 64,
90
- }),
91
- autoRenew: fields.autoRenew,
92
- cycle: normalizeCycle(fields.cycle),
93
- nextBillingAt: normalizeBillingTime(fields.nextBillingAt),
94
- // Billing anchor: the day the subscription started. The dashboard derives
95
- // every cycle boundary from this date, so month-end anchors (Jan 31) stay
96
- // stable instead of drifting after the first clamped month. Optional:
97
- // records created before the field existed fall back to a derived anchor.
98
- startedAt:
99
- fields.startedAt === undefined
100
- ? null
101
- : normalizeBillingTime(fields.startedAt, { field: "startedAt", required: false }),
102
- };
103
- }
104
-
105
- function isValidStoredRecord(record) {
106
- if (!record || typeof record !== "object" || Array.isArray(record)) return false;
107
- if (typeof record.id !== "string" || !record.id) return false;
108
- if (typeof record.service !== "string" || !record.service) return false;
109
- if (typeof record.autoRenew !== "boolean") return false;
110
- if (typeof record.nextBillingAt !== "string") return false;
111
- return Number.isFinite(new Date(record.nextBillingAt).getTime());
112
- }
113
-
114
- // Read the store. Any state other than a clean file or a plainly missing one
115
- // must never collapse into an empty store on its own: the next write would
116
- // silently destroy every stored subscription (user-entered data that cannot
117
- // be rebuilt from logs). Reads surface the damage as an error; only the write
118
- // path may recover, and only after backing the original file up.
119
- async function readStore(filePath, { forWrite = false } = {}) {
120
- const { status, value, error } = await readJsonStrict(filePath);
121
- if (status === "missing") {
122
- return { store: { version: STORE_VERSION, items: [] }, needsBackup: false };
123
- }
124
- if (status === "error") {
125
- // Unreadable (permissions, I/O error): refuse — a blind overwrite would
126
- // destroy data we were never able to see.
127
- throw new Error(`Cannot read subscription store: ${error?.message || String(error)}`);
128
- }
129
- if (status === "invalid" || !value || typeof value !== "object" || Array.isArray(value)) {
130
- if (!forWrite) {
131
- throw new Error("Subscription store is corrupted (invalid JSON)");
132
- }
133
- return { store: { version: STORE_VERSION, items: [] }, needsBackup: true };
134
- }
135
- if (!Array.isArray(value.items)) {
136
- // Valid JSON object without a usable items array: nothing recoverable
137
- // inside, so an empty store is honest. If the key exists with a wrong
138
- // type, keep the file backed up before a write replaces it.
139
- return {
140
- store: { version: STORE_VERSION, items: [] },
141
- needsBackup: value.items !== undefined,
142
- };
143
- }
144
- const items = [];
145
- let dropped = false;
146
- for (const item of value.items) {
147
- if (isValidStoredRecord(item)) {
148
- items.push(item);
149
- } else {
150
- dropped = true;
151
- }
152
- }
153
- const version = Number.isFinite(value.version) ? value.version : STORE_VERSION;
154
- return { store: { version, items }, needsBackup: dropped };
155
- }
156
-
157
- // A write is about to replace a store that contained unreadable data — keep
158
- // a copy around first so nothing is lost without a trace. Copy (not rename):
159
- // if the replacement write then fails, the canonical path must still hold the
160
- // damaged original, otherwise the next write would treat it as missing and
161
- // start from an empty store.
162
- async function backupDamagedStore(filePath) {
163
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
164
- try {
165
- await fs.copyFile(filePath, `${filePath}.corrupt-${stamp}`);
166
- } catch (e) {
167
- if (e?.code !== "ENOENT") {
168
- throw new Error(`Cannot back up the damaged subscription store: ${e?.message || String(e)}`);
169
- }
170
- }
171
- }
172
-
173
- async function loadStoreForWrite(filePath) {
174
- const { store, needsBackup } = await readStore(filePath, { forWrite: true });
175
- if (needsBackup) await backupDamagedStore(filePath);
176
- return store;
177
- }
178
-
179
- async function writeStore(filePath, store) {
180
- // Private from creation: the 0o600 applies to the tmp file before the
181
- // rename, so a crash before the fallback chmod cannot leave a
182
- // world-readable store behind.
183
- await writeFileAtomic(filePath, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
184
- await chmod600IfPossible(filePath);
185
- }
186
-
187
- function sortByNextBillingAt(items) {
188
- return [...items].sort((a, b) =>
189
- new Date(a.nextBillingAt).getTime() - new Date(b.nextBillingAt).getTime(),
190
- );
191
- }
192
-
193
- // One subscription per tool: the dashboard derives the subscription's name
194
- // and inline progress row from the linked provider, so two records sharing a
195
- // provider cannot be displayed. Enforced inside the store lock's
196
- // read-modify-write transaction — the frontend picker cannot cover concurrent
197
- // requests, stale pages, or direct API calls. `excludeId` lets an update
198
- // re-save its own provider.
199
- function assertProviderAvailable(items, provider, excludeId = null) {
200
- if (!provider) return;
201
- const conflict = items.find(
202
- (item) => item.provider === provider && item.id !== excludeId,
203
- );
204
- if (conflict) {
205
- throw new Error(
206
- `Provider "${provider}" already has a subscription (${conflict.id})`,
207
- );
208
- }
209
- }
210
-
211
- // In-process FIFO queue per store file. Every mutation is a full
212
- // read-modify-write transaction; without serialization two concurrent writes
213
- // read the same snapshot and the later one silently drops the earlier change
214
- // (issue: 30 concurrent creates survived as a single record). The queue keeps
215
- // independent store files unblocked while ordering operations on the same one.
216
- const storeLocks = new Map();
217
-
218
- function withStoreLock(filePath, operation) {
219
- const previous = storeLocks.get(filePath) || Promise.resolve();
220
- // Run even if the previous transaction rejected; its error already reached
221
- // its own caller and must not wedge the queue.
222
- const run = previous.then(operation, operation);
223
- storeLocks.set(filePath, run.then(() => undefined, () => undefined));
224
- return run;
225
- }
226
-
227
- async function listSubscriptions({ trackerDir }) {
228
- const { store } = await readStore(resolveSubscriptionsPath(trackerDir));
229
- return sortByNextBillingAt(store.items);
230
- }
231
-
232
- async function createSubscription({ trackerDir, fields }) {
233
- // Validate before taking the lock so a bad payload never queues a write.
234
- const normalized = normalizeSubscriptionFields(fields);
235
- const filePath = resolveSubscriptionsPath(trackerDir);
236
- return withStoreLock(filePath, async () => {
237
- const now = new Date().toISOString();
238
- const record = {
239
- id: crypto.randomUUID(),
240
- ...normalized,
241
- createdAt: now,
242
- updatedAt: now,
243
- };
244
- const store = await loadStoreForWrite(filePath);
245
- assertProviderAvailable(store.items, normalized.provider);
246
- store.items.push(record);
247
- await writeStore(filePath, store);
248
- return record;
249
- });
250
- }
251
-
252
- async function updateSubscription({ trackerDir, id, fields }) {
253
- if (typeof id !== "string" || !id) throw new Error("id is required");
254
- const filePath = resolveSubscriptionsPath(trackerDir);
255
- return withStoreLock(filePath, async () => {
256
- const store = await loadStoreForWrite(filePath);
257
- const index = store.items.findIndex((item) => item.id === id);
258
- if (index === -1) throw new Error("Subscription not found");
259
- const existing = store.items[index];
260
- // Merge over the existing record so callers may send only changed fields.
261
- const merged = normalizeSubscriptionFields({ ...existing, ...(fields || {}) });
262
- assertProviderAvailable(store.items, merged.provider, id);
263
- const record = {
264
- ...existing,
265
- ...merged,
266
- updatedAt: new Date().toISOString(),
267
- };
268
- store.items[index] = record;
269
- await writeStore(filePath, store);
270
- return record;
271
- });
272
- }
273
-
274
- async function deleteSubscription({ trackerDir, id }) {
275
- if (typeof id !== "string" || !id) throw new Error("id is required");
276
- const filePath = resolveSubscriptionsPath(trackerDir);
277
- return withStoreLock(filePath, async () => {
278
- const store = await loadStoreForWrite(filePath);
279
- const index = store.items.findIndex((item) => item.id === id);
280
- if (index === -1) throw new Error("Subscription not found");
281
- store.items.splice(index, 1);
282
- await writeStore(filePath, store);
283
- return { removed: true };
284
- });
285
- }
286
-
287
- module.exports = {
288
- listSubscriptions,
289
- createSubscription,
290
- updateSubscription,
291
- deleteSubscription,
292
- resolveSubscriptionsPath,
293
- };
@@ -1,236 +0,0 @@
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 };