@aiusage/cli 1.4.4 → 1.5.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.
package/dist/cli.js CHANGED
@@ -10,11 +10,10 @@ var __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof
10
10
  import { createInterface as createInterface3 } from "node:readline";
11
11
  import { hostname as hostname3 } from "node:os";
12
12
 
13
- // src/scanners/claude.ts
14
- import { readdir as readdir2, open, readFile } from "node:fs/promises";
13
+ // src/scanners/antigravity.ts
14
+ import { readdir as readdir2, readFile } from "node:fs/promises";
15
15
  import { join as join2 } from "node:path";
16
16
  import { homedir } from "node:os";
17
- import { createInterface } from "node:readline";
18
17
 
19
18
  // src/scanners/utils.ts
20
19
  import { readdir } from "node:fs/promises";
@@ -27,6 +26,10 @@ function parseTs(value) {
27
26
  function dateKey(date) {
28
27
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
29
28
  }
29
+ function projectFromPath(raw, aliases) {
30
+ let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
31
+ return aliases?.[raw] ?? aliases?.[name] ?? name;
32
+ }
30
33
  function resolveProjectFields(rawPath, aliases) {
31
34
  let parts = rawPath.split("/").filter(Boolean), display = parts[parts.length - 1] || "unknown", alias = aliases?.[rawPath] ?? aliases?.[display];
32
35
  return {
@@ -93,32 +96,100 @@ async function runWithConcurrency(items, concurrency, worker) {
93
96
  );
94
97
  }
95
98
 
99
+ // src/scanners/antigravity.ts
100
+ async function scanAntigravityDates(targetDates, baseDir) {
101
+ let dates = new Set(targetDates), dir = baseDir ?? join2(homedir(), ".gemini", "antigravity"), grouped = initDateMap(dates), sessionDates = /* @__PURE__ */ new Map();
102
+ if (await collectBrainSessionDates(join2(dir, "brain"), sessionDates), await collectBrowserSessionDates(join2(dir, "browser_recordings"), sessionDates), sessionDates.size === 0) return emptyResult(dates);
103
+ for (let timestamp of sessionDates.values()) {
104
+ let dayMap = grouped.get(dateKey(timestamp));
105
+ dayMap && accumulate(
106
+ dayMap,
107
+ "unknown|unknown",
108
+ {
109
+ provider: "google",
110
+ product: "antigravity",
111
+ channel: "ide",
112
+ model: "unknown",
113
+ project: "unknown",
114
+ inputTokens: 0,
115
+ cachedInputTokens: 0,
116
+ cacheWriteTokens: 0,
117
+ outputTokens: 0,
118
+ reasoningOutputTokens: 0
119
+ },
120
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
121
+ );
122
+ }
123
+ return finalize(grouped);
124
+ }
125
+ async function collectBrainSessionDates(dir, sessionDates) {
126
+ let entries;
127
+ try {
128
+ entries = await readdir2(dir, { withFileTypes: !0 });
129
+ } catch {
130
+ return;
131
+ }
132
+ for (let entry of entries) {
133
+ if (!entry.isDirectory()) continue;
134
+ let taskMetadata = await readJson(join2(dir, entry.name, "task.md.metadata.json")), timestamp = parseTs(taskMetadata?.updatedAt);
135
+ timestamp && upsertSessionDate(sessionDates, entry.name, timestamp);
136
+ }
137
+ }
138
+ async function collectBrowserSessionDates(dir, sessionDates) {
139
+ let entries;
140
+ try {
141
+ entries = await readdir2(dir, { withFileTypes: !0 });
142
+ } catch {
143
+ return;
144
+ }
145
+ for (let entry of entries) {
146
+ if (!entry.isDirectory()) continue;
147
+ let metadata = await readJson(join2(dir, entry.name, "metadata.json")), timestamp = parseTs(metadata?.highlights?.[0]?.start_time ?? metadata?.highlights?.[0]?.end_time);
148
+ timestamp && upsertSessionDate(sessionDates, entry.name, timestamp);
149
+ }
150
+ }
151
+ async function readJson(filePath) {
152
+ try {
153
+ return JSON.parse(await readFile(filePath, "utf-8"));
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+ function upsertSessionDate(sessionDates, sessionId, timestamp) {
159
+ let existing = sessionDates.get(sessionId);
160
+ (!existing || timestamp < existing) && sessionDates.set(sessionId, timestamp);
161
+ }
162
+
96
163
  // src/scanners/claude.ts
164
+ import { readdir as readdir3, open, readFile as readFile2 } from "node:fs/promises";
165
+ import { join as join3 } from "node:path";
166
+ import { homedir as homedir2 } from "node:os";
167
+ import { createInterface } from "node:readline";
97
168
  var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024, STATS_CACHE_DEFAULT_INPUT_RATIO = 0.7;
98
169
  function getClaudeProjectDirs(claudeDir) {
99
170
  if (claudeDir) return [claudeDir];
100
171
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
101
172
  if (envVar)
102
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join2(p, "projects"));
103
- let home = homedir();
173
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join3(p, "projects"));
174
+ let home = homedir2();
104
175
  return [
105
- join2(home, ".config", "claude", "projects"),
106
- join2(home, ".claude", "projects")
176
+ join3(home, ".config", "claude", "projects"),
177
+ join3(home, ".claude", "projects")
107
178
  ];
108
179
  }
109
180
  async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
110
181
  let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
111
182
  for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
112
- let baseDirs = getClaudeProjectDirs(claudeDir), deduped = /* @__PURE__ */ new Map(), fileJobs = [];
183
+ let baseDirs = getClaudeProjectDirs(claudeDir), processedHashes = /* @__PURE__ */ new Set(), sessionSets = /* @__PURE__ */ new Map(), fileJobs = [];
113
184
  for (let baseDir of baseDirs) {
114
185
  let projectDirs;
115
186
  try {
116
- projectDirs = await readdir2(baseDir);
187
+ projectDirs = await readdir3(baseDir);
117
188
  } catch {
118
189
  continue;
119
190
  }
120
191
  for (let projDir of projectDirs) {
121
- let projectPath = join2(baseDir, projDir), fields = resolveProject(projectPath, projectAliases), jsonlFiles = [];
192
+ let projectPath = join3(baseDir, projDir), fields = resolveProject(projectPath, projectAliases), jsonlFiles = [];
122
193
  try {
123
194
  await walkForJsonl(projectPath, jsonlFiles);
124
195
  } catch {
@@ -129,48 +200,30 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
129
200
  }
130
201
  }
131
202
  await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
132
- await processJsonlFile(job.filePath, job.projectFields, targetDateSet, projectAliases, deduped);
203
+ await processJsonlFile(job.filePath, job.projectFields, targetDateSet, projectAliases, groupedByDate, processedHashes, sessionSets);
133
204
  });
134
- for (let [dedupeKey, usage] of deduped.entries()) {
135
- let [usageDate] = dedupeKey.split("|", 1), grouped = groupedByDate.get(usageDate);
136
- if (!grouped) continue;
137
- let cacheWriteTokens = usage.cacheWrite5mTokens + usage.cacheWrite1hTokens, key = `${usage.model}|${usage.project}`, existing = grouped.get(key);
138
- existing ? (existing.eventCount += 1, existing.inputTokens += usage.inputTokens, existing.cachedInputTokens += usage.cachedInputTokens, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + usage.cacheWrite5mTokens, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + usage.cacheWrite1hTokens, existing.outputTokens += usage.outputTokens, existing.costUSD = (existing.costUSD ?? 0) + usage.costUSD) : grouped.set(key, {
139
- provider: "anthropic",
140
- product: "claude-code",
141
- channel: "cli",
142
- model: usage.model,
143
- project: usage.project,
144
- projectDisplay: usage.projectDisplay,
145
- projectAlias: usage.projectAlias,
146
- eventCount: 1,
147
- inputTokens: usage.inputTokens,
148
- cachedInputTokens: usage.cachedInputTokens,
149
- cacheWriteTokens,
150
- cacheWrite5mTokens: usage.cacheWrite5mTokens,
151
- cacheWrite1hTokens: usage.cacheWrite1hTokens,
152
- outputTokens: usage.outputTokens,
153
- reasoningOutputTokens: 0,
154
- costUSD: usage.costUSD
155
- });
156
- }
157
205
  let missingDates = [...targetDateSet].filter((d) => groupedByDate.get(d)?.size === 0);
158
206
  if (missingDates.length > 0) {
159
207
  let remaining = new Set(missingDates);
160
208
  for (let baseDir of baseDirs) {
161
209
  if (remaining.size === 0) break;
162
- let statsCachePath = join2(baseDir, "..", "stats-cache.json");
210
+ let statsCachePath = join3(baseDir, "..", "stats-cache.json");
163
211
  await fillFromStatsCache(statsCachePath, remaining, groupedByDate);
164
212
  for (let d of remaining)
165
213
  groupedByDate.get(d).size > 0 && remaining.delete(d);
166
214
  }
167
215
  }
216
+ for (let [usageDate, grouped] of groupedByDate.entries())
217
+ for (let [key, breakdown] of grouped.entries()) {
218
+ let sessionSetKey = `${usageDate}|${key}`;
219
+ breakdown.sessionCount = sessionSets.get(sessionSetKey)?.size ?? 0;
220
+ }
168
221
  return new Map(
169
222
  [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
170
223
  );
171
224
  }
172
- async function processJsonlFile(filePath, fallbackFields, targetDateSet, projectAliases, deduped) {
173
- let fh;
225
+ async function processJsonlFile(filePath, fallbackFields, targetDateSet, projectAliases, groupedByDate, processedHashes, sessionSets) {
226
+ let fallbackSessionId = filePath.replace(/^.*[\\/]/, "").replace(/\.jsonl$/, ""), fh;
174
227
  try {
175
228
  fh = await open(filePath, "r");
176
229
  } catch {
@@ -197,23 +250,37 @@ async function processJsonlFile(filePath, fallbackFields, targetDateSet, project
197
250
  if (!message?.usage) continue;
198
251
  let rawModel = message.model ?? "unknown";
199
252
  if (rawModel === "<synthetic>") continue;
200
- let requestId = record.requestId ?? message.id ?? record.uuid;
201
- if (!requestId) continue;
253
+ let messageId = message.id, requestId = record.requestId;
254
+ if (messageId && requestId) {
255
+ let hash = `${messageId}:${requestId}`;
256
+ if (processedHashes.has(hash)) continue;
257
+ processedHashes.add(hash);
258
+ }
202
259
  let usage = message.usage, model = normalizeModelName(rawModel);
203
260
  usage.speed === "fast" && (model = `${model}-fast`);
204
- let recordFields = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackFields, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
261
+ let recordFields = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackFields, sessionId = record.sessionId ?? fallbackSessionId, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
205
262
  cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
206
- let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
207
- existing ? (existing.model = model, existing.inputTokens = Math.max(existing.inputTokens, usage.input_tokens ?? 0), existing.cacheWrite5mTokens = Math.max(existing.cacheWrite5mTokens, cache5m), existing.cacheWrite1hTokens = Math.max(existing.cacheWrite1hTokens, cache1h), existing.cachedInputTokens = Math.max(existing.cachedInputTokens, usage.cache_read_input_tokens ?? 0), existing.outputTokens = Math.max(existing.outputTokens, usage.output_tokens ?? 0), existing.costUSD = Math.max(existing.costUSD, costUSD)) : deduped.set(dedupeKey, {
263
+ let grouped = groupedByDate.get(usageDate);
264
+ if (!grouped) continue;
265
+ let cacheWriteTokens = cache5m + cache1h, key = `${model}|${recordFields.project}`, sessionSetKey = `${usageDate}|${key}`;
266
+ sessionSets.has(sessionSetKey) || sessionSets.set(sessionSetKey, /* @__PURE__ */ new Set()), sessionSets.get(sessionSetKey).add(sessionId);
267
+ let existing = grouped.get(key);
268
+ existing ? (existing.eventCount += 1, existing.inputTokens += usage.input_tokens ?? 0, existing.cachedInputTokens += usage.cache_read_input_tokens ?? 0, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + cache5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + cache1h, existing.outputTokens += usage.output_tokens ?? 0, existing.costUSD = (existing.costUSD ?? 0) + costUSD) : grouped.set(key, {
269
+ provider: "anthropic",
270
+ product: "claude-code",
271
+ channel: "cli",
208
272
  model,
209
273
  project: recordFields.project,
210
274
  projectDisplay: recordFields.projectDisplay,
211
275
  projectAlias: recordFields.projectAlias,
276
+ eventCount: 1,
212
277
  inputTokens: usage.input_tokens ?? 0,
278
+ cachedInputTokens: usage.cache_read_input_tokens ?? 0,
279
+ cacheWriteTokens,
213
280
  cacheWrite5mTokens: cache5m,
214
281
  cacheWrite1hTokens: cache1h,
215
- cachedInputTokens: usage.cache_read_input_tokens ?? 0,
216
282
  outputTokens: usage.output_tokens ?? 0,
283
+ reasoningOutputTokens: 0,
217
284
  costUSD
218
285
  });
219
286
  }
@@ -224,7 +291,7 @@ async function processJsonlFile(filePath, fallbackFields, targetDateSet, project
224
291
  async function fillFromStatsCache(statsCachePath, missingDates, groupedByDate) {
225
292
  let raw;
226
293
  try {
227
- raw = await readFile(statsCachePath, "utf-8");
294
+ raw = await readFile2(statsCachePath, "utf-8");
228
295
  } catch {
229
296
  return;
230
297
  }
@@ -285,23 +352,23 @@ function resolveProject(rawPath, aliases) {
285
352
  return { project: rawPath, projectDisplay: project, projectAlias: alias };
286
353
  }
287
354
  async function walkForJsonl(dir, result) {
288
- let entries = await readdir2(dir, { withFileTypes: !0 });
355
+ let entries = await readdir3(dir, { withFileTypes: !0 });
289
356
  for (let entry of entries) {
290
- let fullPath = join2(dir, entry.name);
357
+ let fullPath = join3(dir, entry.name);
291
358
  entry.isDirectory() ? await walkForJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
292
359
  }
293
360
  }
294
361
 
295
362
  // src/scanners/codex.ts
296
- import { readdir as readdir3, open as open2 } from "node:fs/promises";
297
- import { join as join3 } from "node:path";
298
- import { homedir as homedir2 } from "node:os";
363
+ import { readdir as readdir4, open as open2 } from "node:fs/promises";
364
+ import { join as join4 } from "node:path";
365
+ import { homedir as homedir3 } from "node:os";
299
366
  import { createInterface as createInterface2 } from "node:readline";
300
367
  var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
301
368
  async function scanCodexDates(targetDates, codexDir, projectAliases) {
302
369
  let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
303
370
  for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
304
- let baseDir = codexDir ?? join3(homedir2(), ".codex"), sessionFiles = await collectSessionFiles(baseDir);
371
+ let baseDir = codexDir ?? join4(homedir3(), ".codex"), sessionFiles = await collectSessionFiles(baseDir);
305
372
  if (sessionFiles.length === 0)
306
373
  return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
307
374
  let globalSeenSigs = /* @__PURE__ */ new Set();
@@ -377,25 +444,25 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
377
444
  }
378
445
  }
379
446
  async function collectSessionFiles(baseDir) {
380
- let paths = [], archivedDir = join3(baseDir, "archived_sessions");
447
+ let paths = [], archivedDir = join4(baseDir, "archived_sessions");
381
448
  try {
382
- let files = await readdir3(archivedDir);
449
+ let files = await readdir4(archivedDir);
383
450
  for (let f of files)
384
- f.endsWith(".jsonl") && paths.push(join3(archivedDir, f));
451
+ f.endsWith(".jsonl") && paths.push(join4(archivedDir, f));
385
452
  } catch {
386
453
  }
387
- let sessionsDir = join3(baseDir, "sessions");
454
+ let sessionsDir = join4(baseDir, "sessions");
388
455
  return await walkDir(sessionsDir, paths), paths;
389
456
  }
390
457
  async function walkDir(dir, result) {
391
458
  let entries;
392
459
  try {
393
- entries = await readdir3(dir, { withFileTypes: !0 });
460
+ entries = await readdir4(dir, { withFileTypes: !0 });
394
461
  } catch {
395
462
  return;
396
463
  }
397
464
  for (let entry of entries) {
398
- let fullPath = join3(dir, entry.name);
465
+ let fullPath = join4(dir, entry.name);
399
466
  entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
400
467
  }
401
468
  }
@@ -414,17 +481,17 @@ function toDateKey2(date) {
414
481
  }
415
482
 
416
483
  // src/scanners/copilot.ts
417
- import { readFile as readFile2 } from "node:fs/promises";
418
- import { join as join4 } from "node:path";
419
- import { homedir as homedir3 } from "node:os";
484
+ import { readFile as readFile3 } from "node:fs/promises";
485
+ import { join as join5 } from "node:path";
486
+ import { homedir as homedir4 } from "node:os";
420
487
  async function scanCopilotDates(targetDates, baseDir, projectAliases) {
421
- let dates = new Set(targetDates), dir = baseDir ?? join4(homedir3(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
488
+ let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
422
489
  if (files.length === 0) return emptyResult(dates);
423
490
  let grouped = initDateMap(dates);
424
491
  for (let filePath of files) {
425
492
  let content;
426
493
  try {
427
- content = await readFile2(filePath, "utf-8");
494
+ content = await readFile3(filePath, "utf-8");
428
495
  } catch {
429
496
  continue;
430
497
  }
@@ -478,21 +545,154 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
478
545
  return finalize(grouped);
479
546
  }
480
547
 
548
+ // src/scanners/copilot-vscode.ts
549
+ import { readFile as readFile4 } from "node:fs/promises";
550
+ import { basename as basename2, dirname, join as join6 } from "node:path";
551
+ import { homedir as homedir5 } from "node:os";
552
+ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
553
+ let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"), logFiles = (await walkFiles(dir, ".log")).filter((filePath) => basename2(filePath) === "GitHub Copilot Chat.log"), sessionFiles = (await walkFiles(workspaceDir, ".json")).filter((filePath) => filePath.includes("/chatSessions/"));
554
+ if (logFiles.length === 0 && sessionFiles.length === 0) return emptyResult(dates);
555
+ let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
556
+ for (let filePath of logFiles) {
557
+ let content;
558
+ try {
559
+ content = await readFile4(filePath, "utf-8");
560
+ } catch {
561
+ continue;
562
+ }
563
+ let sessionProject = "unknown";
564
+ for (let line of content.split(`
565
+ `)) {
566
+ if (!line.trim()) continue;
567
+ let projectPath = extractFileUriPath(line);
568
+ projectPath && (sessionProject = projectFromPath(projectPath, projectAliases));
569
+ let event = extractSuccessEvent(line);
570
+ if (!event) continue;
571
+ let dayMap = grouped.get(dateKey(event.timestamp));
572
+ if (!dayMap) continue;
573
+ let dedupeKey = `${event.requestId}|${event.timestamp.toISOString()}|${event.model}|${sessionProject}`;
574
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
575
+ dayMap,
576
+ `${event.model}|${sessionProject}`,
577
+ {
578
+ provider: "github",
579
+ product: "copilot-vscode",
580
+ channel: "ide",
581
+ model: event.model,
582
+ project: sessionProject,
583
+ inputTokens: 0,
584
+ cachedInputTokens: 0,
585
+ cacheWriteTokens: 0,
586
+ outputTokens: 0,
587
+ reasoningOutputTokens: 0
588
+ },
589
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
590
+ ));
591
+ }
592
+ }
593
+ for (let filePath of sessionFiles)
594
+ await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
595
+ return finalize(grouped);
596
+ }
597
+ function extractSuccessEvent(line) {
598
+ if (!line.includes("ccreq:") || !line.includes("| success |")) return null;
599
+ let timestampMatch = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/);
600
+ if (!timestampMatch) return null;
601
+ let timestamp = new Date(timestampMatch[1].replace(" ", "T"));
602
+ if (Number.isNaN(timestamp.getTime())) return null;
603
+ let parts = line.split("|").map((part) => part.trim());
604
+ if (parts.length < 3 || parts[1] !== "success") return null;
605
+ let requestId = parts[0].match(/ccreq:([^.|\s]+)/)?.[1] ?? `${timestamp.getTime()}`, model = normalizeModel(parts[2]);
606
+ return model ? { requestId, timestamp, model } : null;
607
+ }
608
+ function normalizeModel(raw) {
609
+ let parts = raw.split("->").map((part) => part.trim()).filter(Boolean);
610
+ return parts[parts.length - 1] ?? raw.trim();
611
+ }
612
+ function extractFileUriPath(line) {
613
+ let match = line.match(/file:\/\/\/([^\s.]+(?:\.[^\s.]+)?)/);
614
+ if (!match) return null;
615
+ try {
616
+ return decodeURIComponent(`/${match[1]}`);
617
+ } catch {
618
+ return `/${match[1]}`;
619
+ }
620
+ }
621
+ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
622
+ let content;
623
+ try {
624
+ content = await readFile4(filePath, "utf-8");
625
+ } catch {
626
+ return;
627
+ }
628
+ let session;
629
+ try {
630
+ session = JSON.parse(content);
631
+ } catch {
632
+ return;
633
+ }
634
+ let workspacePath = await readWorkspaceFolderPath(filePath), project = workspacePath ? projectFromPath(workspacePath, projectAliases) : "unknown";
635
+ for (let request of session.requests ?? []) {
636
+ if (!request.response?.length || request.result?.errorDetails?.responseIsIncomplete) continue;
637
+ let model = normalizeWorkspaceModel(request.modelId);
638
+ if (!model) continue;
639
+ let timestamp = new Date(request.timestamp ?? 0);
640
+ if (Number.isNaN(timestamp.getTime())) continue;
641
+ let dayMap = grouped.get(dateKey(timestamp));
642
+ if (!dayMap) continue;
643
+ let dedupeKey = `${request.requestId ?? `${timestamp.getTime()}`}|${timestamp.toISOString()}|${model}|${project}`;
644
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
645
+ dayMap,
646
+ `${model}|${project}`,
647
+ {
648
+ provider: "github",
649
+ product: "copilot-vscode",
650
+ channel: "ide",
651
+ model,
652
+ project,
653
+ inputTokens: 0,
654
+ cachedInputTokens: 0,
655
+ cacheWriteTokens: 0,
656
+ outputTokens: 0,
657
+ reasoningOutputTokens: 0
658
+ },
659
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
660
+ ));
661
+ }
662
+ }
663
+ async function readWorkspaceFolderPath(sessionFilePath) {
664
+ let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
665
+ try {
666
+ content = await readFile4(workspaceJsonPath, "utf-8");
667
+ } catch {
668
+ return null;
669
+ }
670
+ try {
671
+ let raw = JSON.parse(content).folder;
672
+ return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
673
+ } catch {
674
+ return null;
675
+ }
676
+ }
677
+ function normalizeWorkspaceModel(raw) {
678
+ return raw ? raw.replace(/^copilot\//, "").trim() : "";
679
+ }
680
+
481
681
  // src/scanners/cursor.ts
482
682
  import { existsSync } from "node:fs";
483
683
  import { copyFile, mkdtemp, rm } from "node:fs/promises";
484
- import { homedir as homedir4, tmpdir } from "node:os";
485
- import { join as join5, resolve } from "node:path";
486
- var CURSOR_CONFIG_DIR_ENV = "CURSOR_CONFIG_DIR", CURSOR_STATE_DB_PATH_ENV = "CURSOR_STATE_DB_PATH", CURSOR_WEB_BASE_URL_ENV = "CURSOR_WEB_BASE_URL", CURSOR_STATE_DB_RELATIVE = join5("User", "globalStorage", "state.vscdb"), CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
684
+ import { homedir as homedir6, tmpdir } from "node:os";
685
+ import { join as join7, resolve } from "node:path";
686
+ var CURSOR_CONFIG_DIR_ENV = "CURSOR_CONFIG_DIR", CURSOR_STATE_DB_PATH_ENV = "CURSOR_STATE_DB_PATH", CURSOR_WEB_BASE_URL_ENV = "CURSOR_WEB_BASE_URL", CURSOR_STATE_DB_RELATIVE = join7("User", "globalStorage", "state.vscdb"), CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
487
687
  function getDefaultDbPath() {
488
688
  if (process.platform === "darwin")
489
- return join5(homedir4(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
689
+ return join7(homedir6(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
490
690
  if (process.platform === "win32") {
491
- let appData = process.env.APPDATA?.trim() || join5(homedir4(), "AppData", "Roaming");
492
- return join5(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
691
+ let appData = process.env.APPDATA?.trim() || join7(homedir6(), "AppData", "Roaming");
692
+ return join7(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
493
693
  }
494
- let xdg = process.env.XDG_CONFIG_HOME?.trim() || join5(homedir4(), ".config");
495
- return join5(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
694
+ let xdg = process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config");
695
+ return join7(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
496
696
  }
497
697
  function findDbPath() {
498
698
  let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
@@ -502,7 +702,7 @@ function findDbPath() {
502
702
  }
503
703
  let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
504
704
  let r = resolve(v.trim());
505
- return r.endsWith(".vscdb") ? r : join5(r, CURSOR_STATE_DB_RELATIVE);
705
+ return r.endsWith(".vscdb") ? r : join7(r, CURSOR_STATE_DB_RELATIVE);
506
706
  }) : [getDefaultDbPath()];
507
707
  for (let c of candidates)
508
708
  if (existsSync(c)) return c;
@@ -518,7 +718,7 @@ function readAuthFromDb(dbPath) {
518
718
  }
519
719
  }
520
720
  async function withSnapshot(dbPath, cb) {
521
- let dir = await mkdtemp(join5(tmpdir(), "aiusage-cursor-")), snap = join5(dir, "state.vscdb");
721
+ let dir = await mkdtemp(join7(tmpdir(), "aiusage-cursor-")), snap = join7(dir, "state.vscdb");
522
722
  await copyFile(dbPath, snap);
523
723
  for (let suffix of ["-shm", "-wal"])
524
724
  existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
@@ -638,17 +838,18 @@ async function scanCursorDates(targetDates) {
638
838
  }
639
839
 
640
840
  // src/scanners/gemini.ts
641
- import { readFile as readFile3 } from "node:fs/promises";
642
- import { join as join6 } from "node:path";
643
- import { homedir as homedir5 } from "node:os";
841
+ import { readFile as readFile5 } from "node:fs/promises";
842
+ import { basename as basename3, join as join8 } from "node:path";
843
+ import { homedir as homedir7 } from "node:os";
644
844
  async function scanGeminiDates(targetDates, baseDir, projectAliases) {
645
- let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
845
+ let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
646
846
  if (files.length === 0) return emptyResult(dates);
647
- let grouped = initDateMap(dates);
847
+ let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
648
848
  for (let filePath of files) {
849
+ if (basename3(filePath) === "logs.json") continue;
649
850
  let content;
650
851
  try {
651
- content = await readFile3(filePath, "utf-8");
852
+ content = await readFile5(filePath, "utf-8");
652
853
  } catch {
653
854
  continue;
654
855
  }
@@ -665,7 +866,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
665
866
  let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
666
867
  if (!ts) continue;
667
868
  let dk = dateKey(ts), dayMap = grouped.get(dk);
668
- dayMap && accumulate(
869
+ dayMap && (tokenBackedDates.add(dk), accumulate(
669
870
  dayMap,
670
871
  `${model}|unknown`,
671
872
  {
@@ -682,11 +883,54 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
682
883
  reasoningOutputTokens: 0
683
884
  },
684
885
  tokens
685
- );
886
+ ));
686
887
  }
687
888
  }
889
+ let logFiles = files.filter((filePath) => basename3(filePath) === "logs.json");
890
+ for (let filePath of logFiles)
891
+ await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
688
892
  return finalize(grouped);
689
893
  }
894
+ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
895
+ let content;
896
+ try {
897
+ content = await readFile5(filePath, "utf-8");
898
+ } catch {
899
+ return;
900
+ }
901
+ let rows;
902
+ try {
903
+ rows = JSON.parse(content);
904
+ } catch {
905
+ return;
906
+ }
907
+ if (Array.isArray(rows))
908
+ for (let row of rows) {
909
+ if (row.type && row.type !== "user") continue;
910
+ let ts = parseTs(row.timestamp);
911
+ if (!ts) continue;
912
+ let dk = dateKey(ts);
913
+ if (tokenBackedDates.has(dk)) continue;
914
+ let dayMap = grouped.get(dk);
915
+ dayMap && accumulate(
916
+ dayMap,
917
+ "unknown|unknown",
918
+ {
919
+ provider: "google",
920
+ product: "gemini-cli",
921
+ channel: "cli",
922
+ model: "unknown",
923
+ project: "unknown",
924
+ inputTokens: 0,
925
+ cachedInputTokens: 0,
926
+ cacheWriteTokens: 0,
927
+ outputTokens: 0,
928
+ reasoningOutputTokens: 0
929
+ },
930
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
931
+ );
932
+ }
933
+ }
690
934
  function extractTokens(msg) {
691
935
  if (msg.tokens) {
692
936
  let t2 = msg.tokens, cached2 = t2.cached ?? 0, input = Math.max((t2.input ?? 0) - cached2, 0), thoughts = t2.thoughts ?? 0, output = Math.max((t2.output ?? 0) - thoughts, 0);
@@ -701,17 +945,17 @@ function extractTokens(msg) {
701
945
  }
702
946
 
703
947
  // src/scanners/qwen.ts
704
- import { readFile as readFile4 } from "node:fs/promises";
705
- import { join as join7, basename as basename2, dirname } from "node:path";
706
- import { homedir as homedir6 } from "node:os";
948
+ import { readFile as readFile6 } from "node:fs/promises";
949
+ import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
950
+ import { homedir as homedir8 } from "node:os";
707
951
  async function scanQwenDates(targetDates, baseDir, projectAliases) {
708
- let dates = new Set(targetDates), dir = baseDir ?? join7(homedir6(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
952
+ let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
709
953
  if (files.length === 0) return emptyResult(dates);
710
954
  let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
711
955
  for (let filePath of files) {
712
- let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
956
+ let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
713
957
  try {
714
- content = await readFile4(filePath, "utf-8");
958
+ content = await readFile6(filePath, "utf-8");
715
959
  } catch {
716
960
  continue;
717
961
  }
@@ -761,17 +1005,17 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
761
1005
  }
762
1006
 
763
1007
  // src/scanners/kimi.ts
764
- import { readFile as readFile5 } from "node:fs/promises";
765
- import { join as join8, basename as basename3, dirname as dirname2 } from "node:path";
766
- import { homedir as homedir7 } from "node:os";
1008
+ import { readFile as readFile7 } from "node:fs/promises";
1009
+ import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
1010
+ import { homedir as homedir9 } from "node:os";
767
1011
  async function scanKimiDates(targetDates, baseDir, projectAliases) {
768
- let dates = new Set(targetDates), kimiHome = baseDir ?? join8(homedir7(), ".kimi"), sessionsDir = join8(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
1012
+ let dates = new Set(targetDates), kimiHome = baseDir ?? join10(homedir9(), ".kimi"), sessionsDir = join10(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
769
1013
  if (files.length === 0) return emptyResult(dates);
770
1014
  let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
771
1015
  for (let filePath of files) {
772
- let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
1016
+ let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
773
1017
  try {
774
- content = await readFile5(filePath, "utf-8");
1018
+ content = await readFile7(filePath, "utf-8");
775
1019
  } catch {
776
1020
  continue;
777
1021
  }
@@ -828,7 +1072,7 @@ function resolveKimiProject(hash, workspaceMap, aliases) {
828
1072
  async function loadWorkspaceMap(kimiHome) {
829
1073
  let map = /* @__PURE__ */ new Map();
830
1074
  try {
831
- let raw = await readFile5(join8(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
1075
+ let raw = await readFile7(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
832
1076
  if (config.workspaces)
833
1077
  for (let [hash, info] of Object.entries(config.workspaces))
834
1078
  info.path && map.set(hash, info.path);
@@ -838,15 +1082,15 @@ async function loadWorkspaceMap(kimiHome) {
838
1082
  }
839
1083
 
840
1084
  // src/scanners/amp.ts
841
- import { readFile as readFile6 } from "node:fs/promises";
842
- import { join as join9 } from "node:path";
843
- import { homedir as homedir8 } from "node:os";
1085
+ import { readFile as readFile8 } from "node:fs/promises";
1086
+ import { join as join11 } from "node:path";
1087
+ import { homedir as homedir10 } from "node:os";
844
1088
  function resolveAmpDir(baseDir) {
845
1089
  if (baseDir) return baseDir;
846
1090
  let ampDataDir = process.env.AMP_DATA_DIR;
847
- if (ampDataDir) return join9(ampDataDir, "threads");
1091
+ if (ampDataDir) return join11(ampDataDir, "threads");
848
1092
  let xdgDataHome = process.env.XDG_DATA_HOME;
849
- return xdgDataHome ? join9(xdgDataHome, "amp", "threads") : join9(homedir8(), ".local", "share", "amp", "threads");
1093
+ return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
850
1094
  }
851
1095
  async function scanAmpDates(targetDates, baseDir, _projectAliases) {
852
1096
  let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
@@ -858,7 +1102,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
858
1102
  for (let filePath of threadFiles) {
859
1103
  let raw;
860
1104
  try {
861
- raw = await readFile6(filePath, "utf-8");
1105
+ raw = await readFile8(filePath, "utf-8");
862
1106
  } catch {
863
1107
  continue;
864
1108
  }
@@ -943,21 +1187,21 @@ function processMessages(thread, dates, grouped) {
943
1187
  }
944
1188
 
945
1189
  // src/scanners/droid.ts
946
- import { readFile as readFile7 } from "node:fs/promises";
947
- import { join as join10, dirname as dirname3, basename as basename4 } from "node:path";
948
- import { homedir as homedir9 } from "node:os";
1190
+ import { readFile as readFile9 } from "node:fs/promises";
1191
+ import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
1192
+ import { homedir as homedir11 } from "node:os";
949
1193
  function extractProjectFromSlug(dirPath) {
950
- let parts = basename4(dirPath).split("-").filter(Boolean);
1194
+ let parts = basename6(dirPath).split("-").filter(Boolean);
951
1195
  return parts[parts.length - 1] || "unknown";
952
1196
  }
953
1197
  async function scanDroidDates(targetDates, baseDir, projectAliases) {
954
- let dates = new Set(targetDates), dir = baseDir ?? join10(homedir9(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
1198
+ let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
955
1199
  if (files.length === 0) return emptyResult(dates);
956
1200
  let grouped = initDateMap(dates);
957
1201
  for (let jsonlPath of files) {
958
1202
  let content;
959
1203
  try {
960
- content = await readFile7(jsonlPath, "utf-8");
1204
+ content = await readFile9(jsonlPath, "utf-8");
961
1205
  } catch {
962
1206
  continue;
963
1207
  }
@@ -974,9 +1218,9 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
974
1218
  if (!ts) continue;
975
1219
  let dk = dateKey(ts), dayMap = grouped.get(dk);
976
1220
  if (!dayMap) continue;
977
- let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join10(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
1221
+ let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
978
1222
  try {
979
- settingsRaw = await readFile7(settingsPath, "utf-8");
1223
+ settingsRaw = await readFile9(settingsPath, "utf-8");
980
1224
  } catch {
981
1225
  continue;
982
1226
  }
@@ -1013,16 +1257,16 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
1013
1257
  }
1014
1258
 
1015
1259
  // src/scanners/opencode.ts
1016
- import { readFile as readFile8 } from "node:fs/promises";
1017
- import { homedir as homedir10 } from "node:os";
1260
+ import { readFile as readFile10 } from "node:fs/promises";
1261
+ import { homedir as homedir12 } from "node:os";
1018
1262
  async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1019
- let dates = new Set(targetDates), dir = baseDir ?? `${homedir10()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
1263
+ let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
1020
1264
  if (files.length === 0) return emptyResult(dates);
1021
1265
  let grouped = initDateMap(dates);
1022
1266
  for (let filePath of files) {
1023
1267
  let raw;
1024
1268
  try {
1025
- raw = await readFile8(filePath, "utf-8");
1269
+ raw = await readFile10(filePath, "utf-8");
1026
1270
  } catch {
1027
1271
  continue;
1028
1272
  }
@@ -1065,9 +1309,9 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1065
1309
  }
1066
1310
 
1067
1311
  // src/scanners/pi.ts
1068
- import { readFile as readFile9 } from "node:fs/promises";
1069
- import { join as join11, basename as basename5, dirname as dirname4 } from "node:path";
1070
- import { homedir as homedir11 } from "node:os";
1312
+ import { readFile as readFile11 } from "node:fs/promises";
1313
+ import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
1314
+ import { homedir as homedir13 } from "node:os";
1071
1315
  async function scanPiDates(targetDates, baseDir, projectAliases) {
1072
1316
  let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
1073
1317
  if (files.length === 0) return emptyResult(dates);
@@ -1075,11 +1319,11 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1075
1319
  for (let filePath of files) {
1076
1320
  let content;
1077
1321
  try {
1078
- content = await readFile9(filePath, "utf-8");
1322
+ content = await readFile11(filePath, "utf-8");
1079
1323
  } catch {
1080
1324
  continue;
1081
1325
  }
1082
- let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
1326
+ let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
1083
1327
  for (let line of content.split(`
1084
1328
  `)) {
1085
1329
  if (!line.trim()) continue;
@@ -1132,7 +1376,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1132
1376
  }
1133
1377
  function getSessionsDir() {
1134
1378
  let envDir = process.env.PI_CODING_AGENT_DIR;
1135
- return envDir ? join11(envDir, "sessions") : join11(homedir11(), ".pi", "agent", "sessions");
1379
+ return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
1136
1380
  }
1137
1381
  function extractProjectFromEncoded(encoded) {
1138
1382
  let parts = encoded.split("-").filter(Boolean);
@@ -1152,9 +1396,11 @@ async function scanDates(targetDates, options = {}) {
1152
1396
  let uniqueDates = [...new Set(targetDates)];
1153
1397
  if (uniqueDates.length === 0) return [];
1154
1398
  let scanners = [
1399
+ scanAntigravityDates(uniqueDates),
1155
1400
  scanClaudeDates(uniqueDates, void 0, options.projectAliases),
1156
1401
  scanCodexDates(uniqueDates, void 0, options.projectAliases),
1157
1402
  scanCopilotDates(uniqueDates, void 0, options.projectAliases),
1403
+ scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
1158
1404
  scanCursorDates(uniqueDates),
1159
1405
  scanGeminiDates(uniqueDates, void 0, options.projectAliases),
1160
1406
  scanQwenDates(uniqueDates, void 0, options.projectAliases),
@@ -1270,14 +1516,81 @@ function chunkDateRange(startDate, endDate) {
1270
1516
  return chunks;
1271
1517
  }
1272
1518
 
1519
+ // src/scanners/anthropic-csv.ts
1520
+ import { readFile as readFile12 } from "node:fs/promises";
1521
+ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
1522
+ if (!targetDates.length) return /* @__PURE__ */ new Map();
1523
+ let targetDateSet = new Set(targetDates), grouped = new Map(
1524
+ targetDates.map((d) => [d, /* @__PURE__ */ new Map()])
1525
+ );
1526
+ for (let filePath of csvFilePaths) {
1527
+ let content;
1528
+ try {
1529
+ content = await readFile12(filePath, "utf-8");
1530
+ } catch {
1531
+ continue;
1532
+ }
1533
+ let rows = parseCsv(content);
1534
+ for (let row of rows) {
1535
+ if (!targetDateSet.has(row.usage_date_utc) || row.usage_input_tokens_no_cache + row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h + row.usage_input_tokens_cache_read + row.usage_output_tokens === 0) continue;
1536
+ let model = normalizeModelName(row.model_version), product = workspaceToProduct(row.workspace), key = `${model}|${product}`, byModel = grouped.get(row.usage_date_utc), existing = byModel.get(key), cacheWriteTokens = row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h;
1537
+ existing ? (existing.eventCount += 1, existing.inputTokens += row.usage_input_tokens_no_cache, existing.cachedInputTokens += row.usage_input_tokens_cache_read, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + row.usage_input_tokens_cache_write_5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + row.usage_input_tokens_cache_write_1h, existing.outputTokens += row.usage_output_tokens) : byModel.set(key, {
1538
+ provider: "anthropic",
1539
+ product,
1540
+ channel: "cli",
1541
+ model,
1542
+ project: "unknown",
1543
+ eventCount: 1,
1544
+ inputTokens: row.usage_input_tokens_no_cache,
1545
+ cachedInputTokens: row.usage_input_tokens_cache_read,
1546
+ cacheWriteTokens,
1547
+ cacheWrite5mTokens: row.usage_input_tokens_cache_write_5m,
1548
+ cacheWrite1hTokens: row.usage_input_tokens_cache_write_1h,
1549
+ outputTokens: row.usage_output_tokens,
1550
+ reasoningOutputTokens: 0
1551
+ });
1552
+ }
1553
+ }
1554
+ return new Map(
1555
+ [...grouped.entries()].map(([date, byModel]) => [date, [...byModel.values()]])
1556
+ );
1557
+ }
1558
+ function workspaceToProduct(workspace) {
1559
+ let w = workspace.trim().toLowerCase();
1560
+ return "claude-code";
1561
+ }
1562
+ function parseCsv(content) {
1563
+ let lines = content.split(`
1564
+ `).map((l) => l.trim()).filter(Boolean);
1565
+ if (lines.length < 2) return [];
1566
+ let headers = lines[0].split(",").map((h) => h.trim()), rows = [];
1567
+ for (let i = 1; i < lines.length; i++) {
1568
+ let values = lines[i].split(","), row = {};
1569
+ for (let j = 0; j < headers.length; j++)
1570
+ row[headers[j]] = values[j]?.trim() ?? "";
1571
+ let date = row.usage_date_utc;
1572
+ !date || !/^\d{4}-\d{2}-\d{2}$/.test(date) || rows.push({
1573
+ usage_date_utc: date,
1574
+ model_version: row.model_version ?? "",
1575
+ workspace: row.workspace ?? "",
1576
+ usage_input_tokens_no_cache: parseInt(row.usage_input_tokens_no_cache ?? "0", 10) || 0,
1577
+ usage_input_tokens_cache_write_5m: parseInt(row.usage_input_tokens_cache_write_5m ?? "0", 10) || 0,
1578
+ usage_input_tokens_cache_write_1h: parseInt(row.usage_input_tokens_cache_write_1h ?? "0", 10) || 0,
1579
+ usage_input_tokens_cache_read: parseInt(row.usage_input_tokens_cache_read ?? "0", 10) || 0,
1580
+ usage_output_tokens: parseInt(row.usage_output_tokens ?? "0", 10) || 0
1581
+ });
1582
+ }
1583
+ return rows;
1584
+ }
1585
+
1273
1586
  // src/report.ts
1274
- import { readdir as readdir5, readFile as readFile10 } from "node:fs/promises";
1275
- import { homedir as homedir12 } from "node:os";
1276
- import { join as join12 } from "node:path";
1587
+ import { readdir as readdir6, readFile as readFile13 } from "node:fs/promises";
1588
+ import { homedir as homedir14 } from "node:os";
1589
+ import { basename as basename8, join as join14 } from "node:path";
1277
1590
  async function buildLocalReport(range, options = {}) {
1278
1591
  let requestedDates = range === "all" ? await discoverAllDates() : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
1279
1592
  for (let result of results) {
1280
- let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = dayTotals.totalTokens > 0;
1593
+ let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
1281
1594
  if (hasData) {
1282
1595
  daysWithData += 1;
1283
1596
  for (let breakdown of result.breakdowns) {
@@ -1334,18 +1647,20 @@ function buildPresetDates(range) {
1334
1647
  return result;
1335
1648
  }
1336
1649
  async function discoverAllDates() {
1337
- let dates = /* @__PURE__ */ new Set(), home = homedir12();
1650
+ let dates = /* @__PURE__ */ new Set(), home = homedir14();
1338
1651
  return await Promise.all([
1339
1652
  discoverClaudeDates(dates),
1340
1653
  discoverCodexDates(dates),
1341
1654
  discoverGeminiDates(dates),
1342
- discoverGenericJsonlDates(join12(home, ".copilot", "session-state"), dates),
1343
- discoverGenericJsonlDates(join12(home, ".qwen", "tmp"), dates),
1344
- discoverGenericJsonlDates(join12(home, ".kimi", "sessions"), dates),
1345
- discoverGenericJsonDates(join12(home, ".local", "share", "amp", "threads"), dates),
1346
- discoverGenericJsonlDates(join12(home, ".factory", "sessions"), dates),
1347
- discoverGenericJsonDates(join12(home, ".local", "share", "opencode"), dates),
1348
- discoverGenericJsonlDates(join12(home, ".pi", "agent", "sessions"), dates)
1655
+ discoverCopilotVscodeDates(dates),
1656
+ discoverAntigravityDates(dates),
1657
+ discoverGenericJsonlDates(join14(home, ".copilot", "session-state"), dates),
1658
+ discoverGenericJsonlDates(join14(home, ".qwen", "tmp"), dates),
1659
+ discoverGenericJsonlDates(join14(home, ".kimi", "sessions"), dates),
1660
+ discoverGenericJsonDates(join14(home, ".local", "share", "amp", "threads"), dates),
1661
+ discoverGenericJsonlDates(join14(home, ".factory", "sessions"), dates),
1662
+ discoverGenericJsonDates(join14(home, ".local", "share", "opencode"), dates),
1663
+ discoverGenericJsonlDates(join14(home, ".pi", "agent", "sessions"), dates)
1349
1664
  ]), [...dates].sort();
1350
1665
  }
1351
1666
  async function discoverGenericJsonlDates(baseDir, dates) {
@@ -1393,22 +1708,18 @@ async function discoverGenericJsonDates(baseDir, dates) {
1393
1708
  async function walkForFiles(dir, ext, result) {
1394
1709
  let entries;
1395
1710
  try {
1396
- entries = await readdir5(dir, { withFileTypes: !0 });
1711
+ entries = await readdir6(dir, { withFileTypes: !0 });
1397
1712
  } catch {
1398
1713
  return;
1399
1714
  }
1400
1715
  for (let entry of entries) {
1401
- let fullPath = join12(dir, entry.name);
1716
+ let fullPath = join14(dir, entry.name);
1402
1717
  entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
1403
1718
  }
1404
1719
  }
1405
1720
  async function discoverGeminiDates(dates) {
1406
- let baseDir = join12(homedir12(), ".gemini", "tmp"), files = [];
1407
- try {
1408
- await walkForGeminiJsonl(baseDir, files);
1409
- } catch {
1410
- return;
1411
- }
1721
+ let baseDir = join14(homedir14(), ".gemini", "tmp"), files = [];
1722
+ await walkForGeminiJsonl(baseDir, files);
1412
1723
  for (let filePath of files) {
1413
1724
  let content = await safeReadUtf8(filePath);
1414
1725
  if (!content) continue;
@@ -1418,9 +1729,23 @@ async function discoverGeminiDates(dates) {
1418
1729
  } catch {
1419
1730
  continue;
1420
1731
  }
1421
- let messages = session.messages ?? session.history ?? [];
1732
+ if (Array.isArray(session)) {
1733
+ for (let row of session) {
1734
+ let ts = parseTimestamp3(row.timestamp);
1735
+ ts && dates.add(toDateKey3(ts));
1736
+ }
1737
+ continue;
1738
+ }
1739
+ let topLevelTs = parseTimestamp3(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
1740
+ topLevelTs && dates.add(toDateKey3(topLevelTs));
1741
+ let messages = [
1742
+ ...session.messages ?? [],
1743
+ ...session.history ?? [],
1744
+ ...session.data?.messages ?? [],
1745
+ ...session.data?.history ?? []
1746
+ ];
1422
1747
  for (let msg of messages) {
1423
- let ts = parseTimestamp3(msg.timestamp);
1748
+ let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
1424
1749
  ts && dates.add(toDateKey3(ts));
1425
1750
  }
1426
1751
  }
@@ -1428,31 +1753,94 @@ async function discoverGeminiDates(dates) {
1428
1753
  async function walkForGeminiJsonl(dir, result) {
1429
1754
  let entries;
1430
1755
  try {
1431
- entries = await readdir5(dir, { withFileTypes: !0 });
1756
+ entries = await readdir6(dir, { withFileTypes: !0 });
1432
1757
  } catch {
1433
1758
  return;
1434
1759
  }
1435
1760
  for (let entry of entries) {
1436
- let fullPath = join12(dir, entry.name);
1761
+ let fullPath = join14(dir, entry.name);
1437
1762
  entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
1438
1763
  }
1439
1764
  }
1765
+ async function discoverCopilotVscodeDates(dates) {
1766
+ let home = homedir14(), logFiles = [];
1767
+ await walkForFiles(join14(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
1768
+ for (let filePath of logFiles) {
1769
+ if (basename8(filePath) !== "GitHub Copilot Chat.log") continue;
1770
+ let content = await safeReadUtf8(filePath);
1771
+ if (content)
1772
+ for (let line of content.split(`
1773
+ `)) {
1774
+ if (!line.includes("ccreq:") || !line.includes("| success |")) continue;
1775
+ let ts = parseTimestamp3(line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/)?.[1]?.replace(" ", "T"));
1776
+ ts && dates.add(toDateKey3(ts));
1777
+ }
1778
+ }
1779
+ let sessionFiles = [];
1780
+ await walkForFiles(join14(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
1781
+ for (let filePath of sessionFiles) {
1782
+ if (!filePath.includes("/chatSessions/")) continue;
1783
+ let content = await safeReadUtf8(filePath);
1784
+ if (!content) continue;
1785
+ let session;
1786
+ try {
1787
+ session = JSON.parse(content);
1788
+ } catch {
1789
+ continue;
1790
+ }
1791
+ for (let request of session.requests ?? []) {
1792
+ if ((request.response?.length ?? 0) === 0 || request.result?.errorDetails?.responseIsIncomplete) continue;
1793
+ let ts = parseTimestamp3(request.timestamp);
1794
+ ts && dates.add(toDateKey3(ts));
1795
+ }
1796
+ }
1797
+ }
1798
+ async function discoverAntigravityDates(dates) {
1799
+ let home = homedir14(), brainFiles = [], browserFiles = [];
1800
+ await walkForFiles(join14(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join14(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
1801
+ for (let filePath of brainFiles) {
1802
+ if (basename8(filePath) !== "task.md.metadata.json") continue;
1803
+ let content = await safeReadUtf8(filePath);
1804
+ if (!content) continue;
1805
+ let data;
1806
+ try {
1807
+ data = JSON.parse(content);
1808
+ } catch {
1809
+ continue;
1810
+ }
1811
+ let ts = parseTimestamp3(data.updatedAt);
1812
+ ts && dates.add(toDateKey3(ts));
1813
+ }
1814
+ for (let filePath of browserFiles) {
1815
+ if (basename8(filePath) !== "metadata.json") continue;
1816
+ let content = await safeReadUtf8(filePath);
1817
+ if (!content) continue;
1818
+ let data;
1819
+ try {
1820
+ data = JSON.parse(content);
1821
+ } catch {
1822
+ continue;
1823
+ }
1824
+ let ts = parseTimestamp3(data.highlights?.[0]?.start_time ?? data.highlights?.[0]?.end_time);
1825
+ ts && dates.add(toDateKey3(ts));
1826
+ }
1827
+ }
1440
1828
  async function discoverClaudeDates(dates) {
1441
- let home = homedir12(), baseDirs = [
1442
- join12(home, ".config", "claude", "projects"),
1443
- join12(home, ".claude", "projects")
1829
+ let home = homedir14(), baseDirs = [
1830
+ join14(home, ".config", "claude", "projects"),
1831
+ join14(home, ".claude", "projects")
1444
1832
  ];
1445
1833
  for (let baseDir of baseDirs) {
1446
1834
  let projectDirs;
1447
1835
  try {
1448
- projectDirs = await readdir5(baseDir);
1836
+ projectDirs = await readdir6(baseDir);
1449
1837
  } catch {
1450
1838
  continue;
1451
1839
  }
1452
1840
  for (let projectDir of projectDirs) {
1453
1841
  let jsonlFiles = [];
1454
1842
  try {
1455
- await walkForClaudeJsonl(join12(baseDir, projectDir), jsonlFiles);
1843
+ await walkForClaudeJsonl(join14(baseDir, projectDir), jsonlFiles);
1456
1844
  } catch {
1457
1845
  continue;
1458
1846
  }
@@ -1476,7 +1864,7 @@ async function discoverClaudeDates(dates) {
1476
1864
  }
1477
1865
  }
1478
1866
  async function discoverCodexDates(dates) {
1479
- let baseDir = join12(homedir12(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1867
+ let baseDir = join14(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1480
1868
  for (let filePath of files) {
1481
1869
  let content = await safeReadUtf8(filePath);
1482
1870
  if (content)
@@ -1498,41 +1886,41 @@ async function discoverCodexDates(dates) {
1498
1886
  async function collectCodexSessionFiles(baseDir) {
1499
1887
  let paths = [];
1500
1888
  try {
1501
- let archivedFiles = await readdir5(join12(baseDir, "archived_sessions"));
1889
+ let archivedFiles = await readdir6(join14(baseDir, "archived_sessions"));
1502
1890
  for (let file of archivedFiles)
1503
- file.endsWith(".jsonl") && paths.push(join12(baseDir, "archived_sessions", file));
1891
+ file.endsWith(".jsonl") && paths.push(join14(baseDir, "archived_sessions", file));
1504
1892
  } catch {
1505
1893
  }
1506
- return await walkForCodexJsonl(join12(baseDir, "sessions"), paths), paths;
1894
+ return await walkForCodexJsonl(join14(baseDir, "sessions"), paths), paths;
1507
1895
  }
1508
1896
  async function walkForClaudeJsonl(dir, result) {
1509
- let entries = await readdir5(dir, { withFileTypes: !0 });
1897
+ let entries = await readdir6(dir, { withFileTypes: !0 });
1510
1898
  for (let entry of entries) {
1511
- let fullPath = join12(dir, entry.name);
1899
+ let fullPath = join14(dir, entry.name);
1512
1900
  entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
1513
1901
  }
1514
1902
  }
1515
1903
  async function walkForCodexJsonl(dir, result) {
1516
1904
  let entries;
1517
1905
  try {
1518
- entries = await readdir5(dir, { withFileTypes: !0 });
1906
+ entries = await readdir6(dir, { withFileTypes: !0 });
1519
1907
  } catch {
1520
1908
  return;
1521
1909
  }
1522
1910
  for (let entry of entries) {
1523
- let fullPath = join12(dir, entry.name);
1911
+ let fullPath = join14(dir, entry.name);
1524
1912
  entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
1525
1913
  }
1526
1914
  }
1527
1915
  async function safeReadUtf8(filePath) {
1528
1916
  try {
1529
- return await readFile10(filePath, "utf-8");
1917
+ return await readFile13(filePath, "utf-8");
1530
1918
  } catch {
1531
1919
  return null;
1532
1920
  }
1533
1921
  }
1534
1922
  function parseTimestamp3(value) {
1535
- if (!value) return null;
1923
+ if (value == null || value === "") return null;
1536
1924
  let date = new Date(value);
1537
1925
  return Number.isNaN(date.getTime()) ? null : date;
1538
1926
  }
@@ -1879,10 +2267,10 @@ function fmtDateShort(dateStr) {
1879
2267
  }
1880
2268
 
1881
2269
  // src/config.ts
1882
- import { mkdir, readFile as readFile11, writeFile } from "node:fs/promises";
1883
- import { homedir as homedir13, hostname } from "node:os";
1884
- import { basename as basename6, join as join13 } from "node:path";
1885
- var CONFIG_DIR = join13(homedir13(), ".aiusage"), CONFIG_PATH = join13(CONFIG_DIR, "config.json");
2270
+ import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
2271
+ import { homedir as homedir15, hostname } from "node:os";
2272
+ import { basename as basename9, join as join15 } from "node:path";
2273
+ var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
1886
2274
  function getConfigPath() {
1887
2275
  return CONFIG_PATH;
1888
2276
  }
@@ -1908,7 +2296,7 @@ function migrateConfig(config) {
1908
2296
  }
1909
2297
  async function readConfig() {
1910
2298
  try {
1911
- let raw = await readFile11(CONFIG_PATH, "utf-8");
2299
+ let raw = await readFile14(CONFIG_PATH, "utf-8");
1912
2300
  return migrateConfig(JSON.parse(raw));
1913
2301
  } catch {
1914
2302
  return {};
@@ -2001,13 +2389,13 @@ import { hostname as hostname2 } from "node:os";
2001
2389
 
2002
2390
  // src/version.ts
2003
2391
  import { readFileSync } from "node:fs";
2004
- import { resolve as resolve2, dirname as dirname5 } from "node:path";
2392
+ import { resolve as resolve2, dirname as dirname6 } from "node:path";
2005
2393
  import { fileURLToPath } from "node:url";
2006
2394
  var cached;
2007
2395
  function getVersion() {
2008
2396
  if (cached !== void 0) return cached;
2009
2397
  try {
2010
- let pkg = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "package.json");
2398
+ let pkg = resolve2(dirname6(fileURLToPath(import.meta.url)), "..", "package.json");
2011
2399
  cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
2012
2400
  } catch {
2013
2401
  cached = "unknown";
@@ -2080,12 +2468,12 @@ async function requestJson(url, init) {
2080
2468
  }
2081
2469
 
2082
2470
  // src/schedule.ts
2083
- import { mkdir as mkdir2, readFile as readFile12, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
2471
+ import { mkdir as mkdir2, readFile as readFile15, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
2084
2472
  import { execFile } from "node:child_process";
2085
2473
  import { promisify } from "node:util";
2086
- import { homedir as homedir14, platform, tmpdir as tmpdir2 } from "node:os";
2087
- import { join as join14, resolve as resolve3 } from "node:path";
2088
- var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join14(homedir14(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join14(homedir14(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
2474
+ import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
2475
+ import { join as join16, resolve as resolve3 } from "node:path";
2476
+ var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join16(homedir16(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join16(homedir16(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
2089
2477
  function parseInterval(value) {
2090
2478
  let match = value.match(/^(\d+)(m|h|d)$/);
2091
2479
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -2130,7 +2518,7 @@ function resolveCommandPaths() {
2130
2518
  }
2131
2519
  async function enableLaunchd(intervalSeconds) {
2132
2520
  let { nodePath, scriptPath } = resolveCommandPaths();
2133
- await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
2521
+ await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
2134
2522
  let plist = [
2135
2523
  '<?xml version="1.0" encoding="UTF-8"?>',
2136
2524
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -2184,7 +2572,7 @@ async function getLaunchdStatus() {
2184
2572
  return { enabled: !1 };
2185
2573
  }
2186
2574
  try {
2187
- let content = await readFile12(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
2575
+ let content = await readFile15(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
2188
2576
  return {
2189
2577
  enabled: !0,
2190
2578
  interval,
@@ -2199,8 +2587,8 @@ async function getLaunchdStatus() {
2199
2587
  }
2200
2588
  }
2201
2589
  async function enableCron(intervalSeconds) {
2202
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join14(homedir14(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
2203
- await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
2590
+ let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join16(homedir16(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
2591
+ await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
2204
2592
  let existing = "";
2205
2593
  try {
2206
2594
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -2258,7 +2646,7 @@ async function getCronStatus() {
2258
2646
  }
2259
2647
  }
2260
2648
  async function writeCrontab(content) {
2261
- let tmpFile = join14(tmpdir2(), `aiusage-cron-${Date.now()}`);
2649
+ let tmpFile = join16(tmpdir2(), `aiusage-cron-${Date.now()}`);
2262
2650
  await writeFile2(tmpFile, content, "utf-8");
2263
2651
  try {
2264
2652
  await execFileAsync("crontab", [tmpFile]);
@@ -2289,9 +2677,9 @@ function escapeXml(value) {
2289
2677
  }
2290
2678
 
2291
2679
  // src/doctor.ts
2292
- import { readdir as readdir6, stat as stat2 } from "node:fs/promises";
2293
- import { homedir as homedir15 } from "node:os";
2294
- import { join as join15 } from "node:path";
2680
+ import { readdir as readdir7, stat as stat2 } from "node:fs/promises";
2681
+ import { homedir as homedir17 } from "node:os";
2682
+ import { join as join17 } from "node:path";
2295
2683
  var msgs = {
2296
2684
  en: {
2297
2685
  groupConfig: "Configuration",
@@ -2347,13 +2735,13 @@ async function countFiles(dir, exts, cap = 1e3) {
2347
2735
  for (; queue.length > 0 && count < cap; ) {
2348
2736
  let current = queue.pop(), entries;
2349
2737
  try {
2350
- entries = await readdir6(current, { withFileTypes: !0 });
2738
+ entries = await readdir7(current, { withFileTypes: !0 });
2351
2739
  } catch {
2352
2740
  continue;
2353
2741
  }
2354
2742
  for (let e of entries) {
2355
2743
  if (count >= cap) break;
2356
- let full = join15(current, e.name);
2744
+ let full = join17(current, e.name);
2357
2745
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
2358
2746
  }
2359
2747
  }
@@ -2382,17 +2770,20 @@ async function runDoctor(lang = "zh") {
2382
2770
  }
2383
2771
  target.lastSuccessfulUploadAt ? checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "warn", message: s.lastSyncNone });
2384
2772
  }
2385
- let g3 = s.groupTools, home = homedir15(), tools = [
2386
- { dir: join15(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
2387
- { dir: join15(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
2388
- { dir: join15(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
2389
- { dir: join15(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
2390
- { dir: join15(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
2391
- { dir: join15(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
2392
- { dir: join15(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
2393
- { dir: join15(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
2394
- { dir: join15(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
2395
- { dir: join15(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
2773
+ let g3 = s.groupTools, home = homedir17(), tools = [
2774
+ { dir: join17(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
2775
+ { dir: join17(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
2776
+ { dir: join17(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
2777
+ { dir: join17(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
2778
+ { dir: join17(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
2779
+ { dir: join17(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
2780
+ { dir: join17(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
2781
+ { dir: join17(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
2782
+ { dir: join17(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
2783
+ { dir: join17(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
2784
+ { dir: join17(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
2785
+ { dir: join17(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
2786
+ { dir: join17(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
2396
2787
  ];
2397
2788
  for (let tool of tools) {
2398
2789
  try {
@@ -2414,9 +2805,9 @@ async function runDoctor(lang = "zh") {
2414
2805
  }
2415
2806
 
2416
2807
  // src/project.ts
2417
- import { open as open3, readdir as readdir7, readFile as readFile13 } from "node:fs/promises";
2418
- import { join as join16 } from "node:path";
2419
- import { homedir as homedir16 } from "node:os";
2808
+ import { open as open3, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
2809
+ import { basename as basename10, join as join18 } from "node:path";
2810
+ import { homedir as homedir18 } from "node:os";
2420
2811
  async function discoverProjects(projectAliases) {
2421
2812
  let projectMap = /* @__PURE__ */ new Map();
2422
2813
  function add(name, source) {
@@ -2433,8 +2824,16 @@ async function discoverProjects(projectAliases) {
2433
2824
  // Copilot CLI: ~/.copilot/session-state/{sessionId}/events.jsonl
2434
2825
  // 首行 session.start 含 data.context.gitRoot / cwd
2435
2826
  discoverCopilotProjects().then((names) => names.forEach((n) => add(n, "copilot"))),
2827
+ // Cursor: ~/Library/Application Support/Cursor/User/globalStorage/storage.json
2828
+ // 读取 workspace/profile 关联记录来发现近期项目
2829
+ discoverCursorProjects().then((names) => names.forEach((n) => add(n, "cursor"))),
2830
+ // Copilot VS Code: VS Code 扩展日志中的 file:/// 工作区路径
2831
+ discoverCopilotVscodeProjects().then((names) => names.forEach((n) => add(n, "copilot-vscode"))),
2436
2832
  // Gemini CLI: ~/.gemini/projects.json 含 { projects: { path: name } }
2437
- discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini")))
2833
+ discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini"))),
2834
+ // Antigravity: ~/.gemini/antigravity/knowledge/*/metadata.json
2835
+ // 仅读取知识项元数据标题,不读取对话内容
2836
+ discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity")))
2438
2837
  ]);
2439
2838
  let results = [];
2440
2839
  for (let [name, sources] of projectMap) {
@@ -2452,20 +2851,20 @@ async function discoverClaudeProjects() {
2452
2851
  for (let baseDir of getClaudeDirs()) {
2453
2852
  let entries;
2454
2853
  try {
2455
- entries = await readdir7(baseDir, { withFileTypes: !0 });
2854
+ entries = await readdir8(baseDir, { withFileTypes: !0 });
2456
2855
  } catch {
2457
2856
  continue;
2458
2857
  }
2459
2858
  for (let entry of entries) {
2460
2859
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
2461
- let projectDir = join16(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
2860
+ let projectDir = join18(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
2462
2861
  name && name !== "unknown" && names.push(name);
2463
2862
  }
2464
2863
  }
2465
2864
  return names;
2466
2865
  }
2467
2866
  async function discoverCodexProjects() {
2468
- let sessionsDir = join16(homedir16(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
2867
+ let sessionsDir = join18(homedir18(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
2469
2868
  for (let filePath of files) {
2470
2869
  let name = await extractCwdFromSessionMeta(filePath);
2471
2870
  name && name !== "unknown" && projects.add(name);
@@ -2490,17 +2889,20 @@ async function extractCwdFromSessionMeta(filePath) {
2490
2889
  }
2491
2890
  }
2492
2891
  async function walkJsonlFiles(dir) {
2892
+ return walkFiles2(dir, ".jsonl");
2893
+ }
2894
+ async function walkFiles2(dir, ext) {
2493
2895
  let result = [];
2494
2896
  async function walk2(d) {
2495
2897
  let entries;
2496
2898
  try {
2497
- entries = await readdir7(d, { withFileTypes: !0 });
2899
+ entries = await readdir8(d, { withFileTypes: !0 });
2498
2900
  } catch {
2499
2901
  return;
2500
2902
  }
2501
2903
  for (let entry of entries) {
2502
- let full = join16(d, entry.name);
2503
- entry.isDirectory() ? await walk2(full) : entry.name.endsWith(".jsonl") && result.push(full);
2904
+ let full = join18(d, entry.name);
2905
+ entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
2504
2906
  }
2505
2907
  }
2506
2908
  return await walk2(dir), result;
@@ -2536,23 +2938,23 @@ async function extractCwdFromFirstJsonl(dir) {
2536
2938
  async function findFirstJsonl(dir) {
2537
2939
  let entries;
2538
2940
  try {
2539
- entries = await readdir7(dir, { withFileTypes: !0 });
2941
+ entries = await readdir8(dir, { withFileTypes: !0 });
2540
2942
  } catch {
2541
2943
  return;
2542
2944
  }
2543
2945
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
2544
- if (topJsonl) return join16(dir, topJsonl.name);
2946
+ if (topJsonl) return join18(dir, topJsonl.name);
2545
2947
  for (let entry of entries)
2546
2948
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
2547
2949
  try {
2548
- let sub = (await readdir7(join16(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
2549
- if (sub) return join16(dir, entry.name, sub);
2950
+ let sub = (await readdir8(join18(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
2951
+ if (sub) return join18(dir, entry.name, sub);
2550
2952
  } catch {
2551
2953
  continue;
2552
2954
  }
2553
2955
  }
2554
2956
  async function discoverCopilotProjects() {
2555
- let dir = join16(homedir16(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
2957
+ let dir = join18(homedir18(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
2556
2958
  for (let filePath of files) {
2557
2959
  let fh;
2558
2960
  try {
@@ -2574,9 +2976,9 @@ async function discoverCopilotProjects() {
2574
2976
  return [...projects];
2575
2977
  }
2576
2978
  async function discoverGeminiProjects() {
2577
- let filePath = join16(homedir16(), ".gemini", "projects.json");
2979
+ let filePath = join18(homedir18(), ".gemini", "projects.json");
2578
2980
  try {
2579
- let raw = await readFile13(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
2981
+ let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
2580
2982
  if (!projects || typeof projects != "object") return [];
2581
2983
  let names = [];
2582
2984
  for (let [path, _name] of Object.entries(projects)) {
@@ -2588,14 +2990,87 @@ async function discoverGeminiProjects() {
2588
2990
  return [];
2589
2991
  }
2590
2992
  }
2993
+ async function discoverCursorProjects() {
2994
+ let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
2995
+ try {
2996
+ let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
2997
+ for (let uri of workspaceUris) {
2998
+ let name = nameFromFileUri(uri);
2999
+ name && projects.add(name);
3000
+ }
3001
+ for (let folder of data.backupWorkspaces?.folders ?? []) {
3002
+ let name = nameFromFileUri(folder.folderUri);
3003
+ name && projects.add(name);
3004
+ }
3005
+ return [...projects];
3006
+ } catch {
3007
+ return [];
3008
+ }
3009
+ }
3010
+ async function discoverCopilotVscodeProjects() {
3011
+ let dir = join18(homedir18(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
3012
+ for (let filePath of files) {
3013
+ let content;
3014
+ try {
3015
+ content = await readFile16(filePath, "utf-8");
3016
+ } catch {
3017
+ continue;
3018
+ }
3019
+ for (let line of content.split(`
3020
+ `)) {
3021
+ let match = line.match(/file:\/\/\/[^\s]+/), name = nameFromFileUri(match?.[0]);
3022
+ name && projects.add(name);
3023
+ }
3024
+ }
3025
+ return [...projects];
3026
+ }
3027
+ async function discoverAntigravityProjects() {
3028
+ let dir = join18(homedir18(), ".gemini", "antigravity", "knowledge"), entries;
3029
+ try {
3030
+ entries = await readdir8(dir, { withFileTypes: !0 });
3031
+ } catch {
3032
+ return [];
3033
+ }
3034
+ let projects = /* @__PURE__ */ new Set();
3035
+ for (let entry of entries) {
3036
+ if (!entry.isDirectory()) continue;
3037
+ let metadataPath = join18(dir, entry.name, "metadata.json");
3038
+ try {
3039
+ let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3040
+ name && name !== "unknown" && projects.add(name);
3041
+ } catch {
3042
+ continue;
3043
+ }
3044
+ }
3045
+ return [...projects];
3046
+ }
3047
+ function nameFromFileUri(raw) {
3048
+ let path = pathFromFileUri(raw);
3049
+ if (!path) return;
3050
+ let name = basename10(path);
3051
+ return name && name !== "unknown" ? name : void 0;
3052
+ }
3053
+ function pathFromFileUri(raw) {
3054
+ if (raw) {
3055
+ if (raw.startsWith("file:///")) {
3056
+ let cleaned = raw.replace(/[.).,;:]+$/, "");
3057
+ try {
3058
+ return decodeURIComponent(cleaned.replace(/^file:\/\//, ""));
3059
+ } catch {
3060
+ return cleaned.replace(/^file:\/\//, "");
3061
+ }
3062
+ }
3063
+ return raw;
3064
+ }
3065
+ }
2591
3066
  function getClaudeDirs() {
2592
3067
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
2593
3068
  if (envVar)
2594
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
2595
- let home = homedir16();
3069
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join18(p, "projects"));
3070
+ let home = homedir18();
2596
3071
  return [
2597
- join16(home, ".config", "claude", "projects"),
2598
- join16(home, ".claude", "projects")
3072
+ join18(home, ".config", "claude", "projects"),
3073
+ join18(home, ".claude", "projects")
2599
3074
  ];
2600
3075
  }
2601
3076
 
@@ -2655,7 +3130,7 @@ try {
2655
3130
  }
2656
3131
  } else if (command === "import") {
2657
3132
  let parsed = parseArgs(argv.slice(1));
2658
- await runImport(parsed.flags);
3133
+ await runImport(parsed.flags, parsed.positionals);
2659
3134
  } else if (command === "setup")
2660
3135
  console.log(`To deploy the server, clone the repo and run the setup wizard:
2661
3136
  `), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
@@ -2802,31 +3277,51 @@ async function runSync(flags) {
2802
3277
  results: uploadResults
2803
3278
  }, null, 2));
2804
3279
  }
2805
- async function runImport(flags) {
2806
- let config = await readConfig(), adminKey = resolveOptionalString(flags.key, config.anthropicAdminKey);
2807
- if (!adminKey)
2808
- throw new Error(
2809
- `Anthropic Admin API key required.
2810
- Option 1: aiusage config set anthropic-admin-key sk-ant-admin...
2811
- Option 2: aiusage import --key sk-ant-admin... --start DATE --end DATE
2812
- Get your Admin key at: console.anthropic.com \u2192 Settings \u2192 Admin Keys`
2813
- );
2814
- let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0);
2815
- if (!startDate) throw new Error("--start DATE is required (e.g. --start 2025-11-01)");
2816
- if (!endDate) throw new Error("--end DATE is required (e.g. --end 2026-01-08)");
2817
- if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
2818
- throw new Error("Dates must be in YYYY-MM-DD format");
2819
- if (startDate > endDate) throw new Error("--start must be before --end");
2820
- let targetName = resolveOptionalString(flags.target, void 0), allTargets = config.targets ?? [];
3280
+ async function runImport(flags, positionals = []) {
3281
+ let config = await readConfig(), targetName = resolveOptionalString(flags.target, void 0), allTargets = config.targets ?? [];
2821
3282
  if (allTargets.length === 0) throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
2822
- let targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll");
2823
- console.log(`Fetching Anthropic API usage: ${startDate} \u2192 ${endDate}`);
2824
- let dateRange = buildDateRange(startDate, endDate), apiResults = await scanAnthropicApiDates(dateRange, adminKey), allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: apiResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0);
2825
- if (allDays.length === 0) {
2826
- console.log("No usage data returned from Anthropic API for the specified range.");
2827
- return;
3283
+ let targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll"), csvFiles = positionals.filter((p) => p.endsWith(".csv")), allDays;
3284
+ if (csvFiles.length > 0) {
3285
+ console.log(`Importing from ${csvFiles.length} CSV file(s)...`);
3286
+ let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0), dateRange;
3287
+ if (startDate && endDate) {
3288
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
3289
+ throw new Error("Dates must be in YYYY-MM-DD format");
3290
+ if (startDate > endDate) throw new Error("--start must be before --end");
3291
+ dateRange = buildDateRange(startDate, endDate);
3292
+ } else
3293
+ dateRange = buildDateRange("2020-01-01", "2030-12-31");
3294
+ let csvResults = await scanAnthropicCsvDates(dateRange, csvFiles);
3295
+ if (allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: csvResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0), allDays.length === 0) {
3296
+ console.log("No usage data found in the provided CSV files.");
3297
+ return;
3298
+ }
3299
+ console.log(`Found data for ${allDays.length} days across CSV files.`);
3300
+ } else {
3301
+ let adminKey = resolveOptionalString(flags.key, config.anthropicAdminKey);
3302
+ if (!adminKey)
3303
+ throw new Error(
3304
+ `Provide CSV files or an Anthropic Admin API key.
3305
+ CSV: aiusage import /path/to/*.csv
3306
+ API: aiusage import --key sk-ant-admin... --start DATE --end DATE
3307
+ aiusage config set anthropic-admin-key sk-ant-admin...
3308
+ Download CSVs at: https://platform.claude.com/usage?date=YYYY-MM
3309
+ Get Admin key at: console.anthropic.com \u2192 Settings \u2192 Admin Keys`
3310
+ );
3311
+ let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0);
3312
+ if (!startDate) throw new Error("--start DATE is required (e.g. --start 2025-11-01)");
3313
+ if (!endDate) throw new Error("--end DATE is required (e.g. --end 2026-01-08)");
3314
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
3315
+ throw new Error("Dates must be in YYYY-MM-DD format");
3316
+ if (startDate > endDate) throw new Error("--start must be before --end");
3317
+ console.log(`Fetching Anthropic API usage: ${startDate} \u2192 ${endDate}`);
3318
+ let dateRange = buildDateRange(startDate, endDate), apiResults = await scanAnthropicApiDates(dateRange, adminKey);
3319
+ if (allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: apiResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0), allDays.length === 0) {
3320
+ console.log("No usage data returned from Anthropic API for the specified range.");
3321
+ return;
3322
+ }
3323
+ console.log(`Found data for ${allDays.length} days. Uploading...`);
2828
3324
  }
2829
- console.log(`Found data for ${allDays.length} days. Uploading...`);
2830
3325
  for (let target of targets) {
2831
3326
  if (!target.deviceToken) {
2832
3327
  console.log(`Skipping "${target.name}": not enrolled (missing deviceToken)`);