@aiusage/cli 1.4.4 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
- 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 });
1591
+ let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [toDateKey3(getTodayLocalDate())] : 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) {
@@ -1308,10 +1621,11 @@ async function buildLocalReport(range, options = {}) {
1308
1621
  pricingWarnings: [...pricingWarnings].sort()
1309
1622
  };
1310
1623
  }
1311
- function parseReportRange(value) {
1624
+ function parseReportRange(value, today) {
1625
+ if (today) return "today";
1312
1626
  if (value === void 0 || value === !0) return "7d";
1313
- if (value === "7d" || value === "1m" || value === "3m" || value === "all") return value;
1314
- throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u3001all");
1627
+ if (value === "7d" || value === "1m" || value === "3m" || value === "all" || value === "today") return value;
1628
+ throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u3001all\u3001today");
1315
1629
  }
1316
1630
  function getRangeLabel(range) {
1317
1631
  switch (range) {
@@ -1334,18 +1648,20 @@ function buildPresetDates(range) {
1334
1648
  return result;
1335
1649
  }
1336
1650
  async function discoverAllDates() {
1337
- let dates = /* @__PURE__ */ new Set(), home = homedir12();
1651
+ let dates = /* @__PURE__ */ new Set(), home = homedir14();
1338
1652
  return await Promise.all([
1339
1653
  discoverClaudeDates(dates),
1340
1654
  discoverCodexDates(dates),
1341
1655
  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)
1656
+ discoverCopilotVscodeDates(dates),
1657
+ discoverAntigravityDates(dates),
1658
+ discoverGenericJsonlDates(join14(home, ".copilot", "session-state"), dates),
1659
+ discoverGenericJsonlDates(join14(home, ".qwen", "tmp"), dates),
1660
+ discoverGenericJsonlDates(join14(home, ".kimi", "sessions"), dates),
1661
+ discoverGenericJsonDates(join14(home, ".local", "share", "amp", "threads"), dates),
1662
+ discoverGenericJsonlDates(join14(home, ".factory", "sessions"), dates),
1663
+ discoverGenericJsonDates(join14(home, ".local", "share", "opencode"), dates),
1664
+ discoverGenericJsonlDates(join14(home, ".pi", "agent", "sessions"), dates)
1349
1665
  ]), [...dates].sort();
1350
1666
  }
1351
1667
  async function discoverGenericJsonlDates(baseDir, dates) {
@@ -1393,22 +1709,18 @@ async function discoverGenericJsonDates(baseDir, dates) {
1393
1709
  async function walkForFiles(dir, ext, result) {
1394
1710
  let entries;
1395
1711
  try {
1396
- entries = await readdir5(dir, { withFileTypes: !0 });
1712
+ entries = await readdir6(dir, { withFileTypes: !0 });
1397
1713
  } catch {
1398
1714
  return;
1399
1715
  }
1400
1716
  for (let entry of entries) {
1401
- let fullPath = join12(dir, entry.name);
1717
+ let fullPath = join14(dir, entry.name);
1402
1718
  entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
1403
1719
  }
1404
1720
  }
1405
1721
  async function discoverGeminiDates(dates) {
1406
- let baseDir = join12(homedir12(), ".gemini", "tmp"), files = [];
1407
- try {
1408
- await walkForGeminiJsonl(baseDir, files);
1409
- } catch {
1410
- return;
1411
- }
1722
+ let baseDir = join14(homedir14(), ".gemini", "tmp"), files = [];
1723
+ await walkForGeminiJsonl(baseDir, files);
1412
1724
  for (let filePath of files) {
1413
1725
  let content = await safeReadUtf8(filePath);
1414
1726
  if (!content) continue;
@@ -1418,9 +1730,23 @@ async function discoverGeminiDates(dates) {
1418
1730
  } catch {
1419
1731
  continue;
1420
1732
  }
1421
- let messages = session.messages ?? session.history ?? [];
1733
+ if (Array.isArray(session)) {
1734
+ for (let row of session) {
1735
+ let ts = parseTimestamp3(row.timestamp);
1736
+ ts && dates.add(toDateKey3(ts));
1737
+ }
1738
+ continue;
1739
+ }
1740
+ let topLevelTs = parseTimestamp3(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
1741
+ topLevelTs && dates.add(toDateKey3(topLevelTs));
1742
+ let messages = [
1743
+ ...session.messages ?? [],
1744
+ ...session.history ?? [],
1745
+ ...session.data?.messages ?? [],
1746
+ ...session.data?.history ?? []
1747
+ ];
1422
1748
  for (let msg of messages) {
1423
- let ts = parseTimestamp3(msg.timestamp);
1749
+ let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
1424
1750
  ts && dates.add(toDateKey3(ts));
1425
1751
  }
1426
1752
  }
@@ -1428,31 +1754,94 @@ async function discoverGeminiDates(dates) {
1428
1754
  async function walkForGeminiJsonl(dir, result) {
1429
1755
  let entries;
1430
1756
  try {
1431
- entries = await readdir5(dir, { withFileTypes: !0 });
1757
+ entries = await readdir6(dir, { withFileTypes: !0 });
1432
1758
  } catch {
1433
1759
  return;
1434
1760
  }
1435
1761
  for (let entry of entries) {
1436
- let fullPath = join12(dir, entry.name);
1762
+ let fullPath = join14(dir, entry.name);
1437
1763
  entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
1438
1764
  }
1439
1765
  }
1766
+ async function discoverCopilotVscodeDates(dates) {
1767
+ let home = homedir14(), logFiles = [];
1768
+ await walkForFiles(join14(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
1769
+ for (let filePath of logFiles) {
1770
+ if (basename8(filePath) !== "GitHub Copilot Chat.log") continue;
1771
+ let content = await safeReadUtf8(filePath);
1772
+ if (content)
1773
+ for (let line of content.split(`
1774
+ `)) {
1775
+ if (!line.includes("ccreq:") || !line.includes("| success |")) continue;
1776
+ let ts = parseTimestamp3(line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/)?.[1]?.replace(" ", "T"));
1777
+ ts && dates.add(toDateKey3(ts));
1778
+ }
1779
+ }
1780
+ let sessionFiles = [];
1781
+ await walkForFiles(join14(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
1782
+ for (let filePath of sessionFiles) {
1783
+ if (!filePath.includes("/chatSessions/")) continue;
1784
+ let content = await safeReadUtf8(filePath);
1785
+ if (!content) continue;
1786
+ let session;
1787
+ try {
1788
+ session = JSON.parse(content);
1789
+ } catch {
1790
+ continue;
1791
+ }
1792
+ for (let request of session.requests ?? []) {
1793
+ if ((request.response?.length ?? 0) === 0 || request.result?.errorDetails?.responseIsIncomplete) continue;
1794
+ let ts = parseTimestamp3(request.timestamp);
1795
+ ts && dates.add(toDateKey3(ts));
1796
+ }
1797
+ }
1798
+ }
1799
+ async function discoverAntigravityDates(dates) {
1800
+ let home = homedir14(), brainFiles = [], browserFiles = [];
1801
+ await walkForFiles(join14(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join14(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
1802
+ for (let filePath of brainFiles) {
1803
+ if (basename8(filePath) !== "task.md.metadata.json") continue;
1804
+ let content = await safeReadUtf8(filePath);
1805
+ if (!content) continue;
1806
+ let data;
1807
+ try {
1808
+ data = JSON.parse(content);
1809
+ } catch {
1810
+ continue;
1811
+ }
1812
+ let ts = parseTimestamp3(data.updatedAt);
1813
+ ts && dates.add(toDateKey3(ts));
1814
+ }
1815
+ for (let filePath of browserFiles) {
1816
+ if (basename8(filePath) !== "metadata.json") continue;
1817
+ let content = await safeReadUtf8(filePath);
1818
+ if (!content) continue;
1819
+ let data;
1820
+ try {
1821
+ data = JSON.parse(content);
1822
+ } catch {
1823
+ continue;
1824
+ }
1825
+ let ts = parseTimestamp3(data.highlights?.[0]?.start_time ?? data.highlights?.[0]?.end_time);
1826
+ ts && dates.add(toDateKey3(ts));
1827
+ }
1828
+ }
1440
1829
  async function discoverClaudeDates(dates) {
1441
- let home = homedir12(), baseDirs = [
1442
- join12(home, ".config", "claude", "projects"),
1443
- join12(home, ".claude", "projects")
1830
+ let home = homedir14(), baseDirs = [
1831
+ join14(home, ".config", "claude", "projects"),
1832
+ join14(home, ".claude", "projects")
1444
1833
  ];
1445
1834
  for (let baseDir of baseDirs) {
1446
1835
  let projectDirs;
1447
1836
  try {
1448
- projectDirs = await readdir5(baseDir);
1837
+ projectDirs = await readdir6(baseDir);
1449
1838
  } catch {
1450
1839
  continue;
1451
1840
  }
1452
1841
  for (let projectDir of projectDirs) {
1453
1842
  let jsonlFiles = [];
1454
1843
  try {
1455
- await walkForClaudeJsonl(join12(baseDir, projectDir), jsonlFiles);
1844
+ await walkForClaudeJsonl(join14(baseDir, projectDir), jsonlFiles);
1456
1845
  } catch {
1457
1846
  continue;
1458
1847
  }
@@ -1476,7 +1865,7 @@ async function discoverClaudeDates(dates) {
1476
1865
  }
1477
1866
  }
1478
1867
  async function discoverCodexDates(dates) {
1479
- let baseDir = join12(homedir12(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1868
+ let baseDir = join14(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1480
1869
  for (let filePath of files) {
1481
1870
  let content = await safeReadUtf8(filePath);
1482
1871
  if (content)
@@ -1498,41 +1887,41 @@ async function discoverCodexDates(dates) {
1498
1887
  async function collectCodexSessionFiles(baseDir) {
1499
1888
  let paths = [];
1500
1889
  try {
1501
- let archivedFiles = await readdir5(join12(baseDir, "archived_sessions"));
1890
+ let archivedFiles = await readdir6(join14(baseDir, "archived_sessions"));
1502
1891
  for (let file of archivedFiles)
1503
- file.endsWith(".jsonl") && paths.push(join12(baseDir, "archived_sessions", file));
1892
+ file.endsWith(".jsonl") && paths.push(join14(baseDir, "archived_sessions", file));
1504
1893
  } catch {
1505
1894
  }
1506
- return await walkForCodexJsonl(join12(baseDir, "sessions"), paths), paths;
1895
+ return await walkForCodexJsonl(join14(baseDir, "sessions"), paths), paths;
1507
1896
  }
1508
1897
  async function walkForClaudeJsonl(dir, result) {
1509
- let entries = await readdir5(dir, { withFileTypes: !0 });
1898
+ let entries = await readdir6(dir, { withFileTypes: !0 });
1510
1899
  for (let entry of entries) {
1511
- let fullPath = join12(dir, entry.name);
1900
+ let fullPath = join14(dir, entry.name);
1512
1901
  entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
1513
1902
  }
1514
1903
  }
1515
1904
  async function walkForCodexJsonl(dir, result) {
1516
1905
  let entries;
1517
1906
  try {
1518
- entries = await readdir5(dir, { withFileTypes: !0 });
1907
+ entries = await readdir6(dir, { withFileTypes: !0 });
1519
1908
  } catch {
1520
1909
  return;
1521
1910
  }
1522
1911
  for (let entry of entries) {
1523
- let fullPath = join12(dir, entry.name);
1912
+ let fullPath = join14(dir, entry.name);
1524
1913
  entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
1525
1914
  }
1526
1915
  }
1527
1916
  async function safeReadUtf8(filePath) {
1528
1917
  try {
1529
- return await readFile10(filePath, "utf-8");
1918
+ return await readFile13(filePath, "utf-8");
1530
1919
  } catch {
1531
1920
  return null;
1532
1921
  }
1533
1922
  }
1534
1923
  function parseTimestamp3(value) {
1535
- if (!value) return null;
1924
+ if (value == null || value === "") return null;
1536
1925
  let date = new Date(value);
1537
1926
  return Number.isNaN(date.getTime()) ? null : date;
1538
1927
  }
@@ -1710,6 +2099,7 @@ var en = {
1710
2099
  rangeLast1m: "Last 30 days",
1711
2100
  rangeLast3m: "Last 90 days",
1712
2101
  rangeAll: "All time",
2102
+ rangeToday: "Today",
1713
2103
  hdrSource: "Source",
1714
2104
  hdrDate: "Date",
1715
2105
  hdrModel: "Model",
@@ -1737,6 +2127,7 @@ var en = {
1737
2127
  rangeLast1m: "\u6700\u8FD1 30 \u5929",
1738
2128
  rangeLast3m: "\u6700\u8FD1 90 \u5929",
1739
2129
  rangeAll: "\u5168\u90E8\u5386\u53F2",
2130
+ rangeToday: "\u4ECA\u5929",
1740
2131
  hdrSource: "\u6765\u6E90",
1741
2132
  hdrDate: "\u65E5\u671F",
1742
2133
  hdrModel: "\u6A21\u578B",
@@ -1845,17 +2236,35 @@ function getRangeLabel2(range, lang) {
1845
2236
  return s.rangeLast3m;
1846
2237
  case "all":
1847
2238
  return s.rangeAll;
2239
+ case "today":
2240
+ return s.rangeToday;
1848
2241
  default:
1849
2242
  return range;
1850
2243
  }
1851
2244
  }
2245
+ function displayWidth(str) {
2246
+ let w = 0;
2247
+ for (let ch of str) {
2248
+ let code = ch.codePointAt(0);
2249
+ code >= 11904 && code <= 40959 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65103 || code >= 65281 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 131072 && code <= 195103 ? w += 2 : w += 1;
2250
+ }
2251
+ return w;
2252
+ }
2253
+ function padStartDisplay(str, width) {
2254
+ let gap = width - displayWidth(str);
2255
+ return gap > 0 ? " ".repeat(gap) + str : str;
2256
+ }
2257
+ function padEndDisplay(str, width) {
2258
+ let gap = width - displayWidth(str);
2259
+ return gap > 0 ? str + " ".repeat(gap) : str;
2260
+ }
1852
2261
  function renderTable(headers, rows, aligns) {
1853
2262
  if (rows.length === 0) return "(no data)";
1854
2263
  let widths = headers.map(
1855
- (h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
2264
+ (h, i) => Math.max(displayWidth(h), ...rows.map((r) => displayWidth(r[i] ?? "")))
1856
2265
  ), fmtRow = (row) => row.map((val, i) => {
1857
2266
  let cell = val ?? "";
1858
- return aligns[i] === "right" ? cell.padStart(widths[i]) : cell.padEnd(widths[i]);
2267
+ return aligns[i] === "right" ? padStartDisplay(cell, widths[i]) : padEndDisplay(cell, widths[i]);
1859
2268
  }).join(" "), divider = widths.map((w) => "\u2500".repeat(w)).join(" ");
1860
2269
  return [fmtRow(headers), divider, ...rows.map(fmtRow)].join(`
1861
2270
  `);
@@ -1879,10 +2288,10 @@ function fmtDateShort(dateStr) {
1879
2288
  }
1880
2289
 
1881
2290
  // 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");
2291
+ import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
2292
+ import { homedir as homedir15, hostname } from "node:os";
2293
+ import { basename as basename9, join as join15 } from "node:path";
2294
+ var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
1886
2295
  function getConfigPath() {
1887
2296
  return CONFIG_PATH;
1888
2297
  }
@@ -1908,7 +2317,7 @@ function migrateConfig(config) {
1908
2317
  }
1909
2318
  async function readConfig() {
1910
2319
  try {
1911
- let raw = await readFile11(CONFIG_PATH, "utf-8");
2320
+ let raw = await readFile14(CONFIG_PATH, "utf-8");
1912
2321
  return migrateConfig(JSON.parse(raw));
1913
2322
  } catch {
1914
2323
  return {};
@@ -2001,13 +2410,13 @@ import { hostname as hostname2 } from "node:os";
2001
2410
 
2002
2411
  // src/version.ts
2003
2412
  import { readFileSync } from "node:fs";
2004
- import { resolve as resolve2, dirname as dirname5 } from "node:path";
2413
+ import { resolve as resolve2, dirname as dirname6 } from "node:path";
2005
2414
  import { fileURLToPath } from "node:url";
2006
2415
  var cached;
2007
2416
  function getVersion() {
2008
2417
  if (cached !== void 0) return cached;
2009
2418
  try {
2010
- let pkg = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "package.json");
2419
+ let pkg = resolve2(dirname6(fileURLToPath(import.meta.url)), "..", "package.json");
2011
2420
  cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
2012
2421
  } catch {
2013
2422
  cached = "unknown";
@@ -2080,12 +2489,12 @@ async function requestJson(url, init) {
2080
2489
  }
2081
2490
 
2082
2491
  // src/schedule.ts
2083
- import { mkdir as mkdir2, readFile as readFile12, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
2492
+ import { mkdir as mkdir2, readFile as readFile15, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
2084
2493
  import { execFile } from "node:child_process";
2085
2494
  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";
2495
+ import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
2496
+ import { join as join16, resolve as resolve3 } from "node:path";
2497
+ 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
2498
  function parseInterval(value) {
2090
2499
  let match = value.match(/^(\d+)(m|h|d)$/);
2091
2500
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -2130,7 +2539,7 @@ function resolveCommandPaths() {
2130
2539
  }
2131
2540
  async function enableLaunchd(intervalSeconds) {
2132
2541
  let { nodePath, scriptPath } = resolveCommandPaths();
2133
- await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
2542
+ await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
2134
2543
  let plist = [
2135
2544
  '<?xml version="1.0" encoding="UTF-8"?>',
2136
2545
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -2184,7 +2593,7 @@ async function getLaunchdStatus() {
2184
2593
  return { enabled: !1 };
2185
2594
  }
2186
2595
  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];
2596
+ 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
2597
  return {
2189
2598
  enabled: !0,
2190
2599
  interval,
@@ -2199,8 +2608,8 @@ async function getLaunchdStatus() {
2199
2608
  }
2200
2609
  }
2201
2610
  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 });
2611
+ let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join16(homedir16(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
2612
+ await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
2204
2613
  let existing = "";
2205
2614
  try {
2206
2615
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -2258,7 +2667,7 @@ async function getCronStatus() {
2258
2667
  }
2259
2668
  }
2260
2669
  async function writeCrontab(content) {
2261
- let tmpFile = join14(tmpdir2(), `aiusage-cron-${Date.now()}`);
2670
+ let tmpFile = join16(tmpdir2(), `aiusage-cron-${Date.now()}`);
2262
2671
  await writeFile2(tmpFile, content, "utf-8");
2263
2672
  try {
2264
2673
  await execFileAsync("crontab", [tmpFile]);
@@ -2289,9 +2698,9 @@ function escapeXml(value) {
2289
2698
  }
2290
2699
 
2291
2700
  // 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";
2701
+ import { readdir as readdir7, stat as stat2 } from "node:fs/promises";
2702
+ import { homedir as homedir17 } from "node:os";
2703
+ import { join as join17 } from "node:path";
2295
2704
  var msgs = {
2296
2705
  en: {
2297
2706
  groupConfig: "Configuration",
@@ -2347,13 +2756,13 @@ async function countFiles(dir, exts, cap = 1e3) {
2347
2756
  for (; queue.length > 0 && count < cap; ) {
2348
2757
  let current = queue.pop(), entries;
2349
2758
  try {
2350
- entries = await readdir6(current, { withFileTypes: !0 });
2759
+ entries = await readdir7(current, { withFileTypes: !0 });
2351
2760
  } catch {
2352
2761
  continue;
2353
2762
  }
2354
2763
  for (let e of entries) {
2355
2764
  if (count >= cap) break;
2356
- let full = join15(current, e.name);
2765
+ let full = join17(current, e.name);
2357
2766
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
2358
2767
  }
2359
2768
  }
@@ -2382,17 +2791,20 @@ async function runDoctor(lang = "zh") {
2382
2791
  }
2383
2792
  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
2793
  }
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"] }
2794
+ let g3 = s.groupTools, home = homedir17(), tools = [
2795
+ { dir: join17(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
2796
+ { dir: join17(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
2797
+ { dir: join17(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
2798
+ { dir: join17(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
2799
+ { dir: join17(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
2800
+ { dir: join17(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
2801
+ { dir: join17(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
2802
+ { dir: join17(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
2803
+ { dir: join17(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
2804
+ { dir: join17(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
2805
+ { dir: join17(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
2806
+ { dir: join17(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
2807
+ { dir: join17(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
2396
2808
  ];
2397
2809
  for (let tool of tools) {
2398
2810
  try {
@@ -2414,9 +2826,9 @@ async function runDoctor(lang = "zh") {
2414
2826
  }
2415
2827
 
2416
2828
  // 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";
2829
+ import { open as open3, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
2830
+ import { basename as basename10, join as join18 } from "node:path";
2831
+ import { homedir as homedir18 } from "node:os";
2420
2832
  async function discoverProjects(projectAliases) {
2421
2833
  let projectMap = /* @__PURE__ */ new Map();
2422
2834
  function add(name, source) {
@@ -2433,8 +2845,16 @@ async function discoverProjects(projectAliases) {
2433
2845
  // Copilot CLI: ~/.copilot/session-state/{sessionId}/events.jsonl
2434
2846
  // 首行 session.start 含 data.context.gitRoot / cwd
2435
2847
  discoverCopilotProjects().then((names) => names.forEach((n) => add(n, "copilot"))),
2848
+ // Cursor: ~/Library/Application Support/Cursor/User/globalStorage/storage.json
2849
+ // 读取 workspace/profile 关联记录来发现近期项目
2850
+ discoverCursorProjects().then((names) => names.forEach((n) => add(n, "cursor"))),
2851
+ // Copilot VS Code: VS Code 扩展日志中的 file:/// 工作区路径
2852
+ discoverCopilotVscodeProjects().then((names) => names.forEach((n) => add(n, "copilot-vscode"))),
2436
2853
  // Gemini CLI: ~/.gemini/projects.json 含 { projects: { path: name } }
2437
- discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini")))
2854
+ discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini"))),
2855
+ // Antigravity: ~/.gemini/antigravity/knowledge/*/metadata.json
2856
+ // 仅读取知识项元数据标题,不读取对话内容
2857
+ discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity")))
2438
2858
  ]);
2439
2859
  let results = [];
2440
2860
  for (let [name, sources] of projectMap) {
@@ -2452,20 +2872,20 @@ async function discoverClaudeProjects() {
2452
2872
  for (let baseDir of getClaudeDirs()) {
2453
2873
  let entries;
2454
2874
  try {
2455
- entries = await readdir7(baseDir, { withFileTypes: !0 });
2875
+ entries = await readdir8(baseDir, { withFileTypes: !0 });
2456
2876
  } catch {
2457
2877
  continue;
2458
2878
  }
2459
2879
  for (let entry of entries) {
2460
2880
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
2461
- let projectDir = join16(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
2881
+ let projectDir = join18(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
2462
2882
  name && name !== "unknown" && names.push(name);
2463
2883
  }
2464
2884
  }
2465
2885
  return names;
2466
2886
  }
2467
2887
  async function discoverCodexProjects() {
2468
- let sessionsDir = join16(homedir16(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
2888
+ let sessionsDir = join18(homedir18(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
2469
2889
  for (let filePath of files) {
2470
2890
  let name = await extractCwdFromSessionMeta(filePath);
2471
2891
  name && name !== "unknown" && projects.add(name);
@@ -2490,17 +2910,20 @@ async function extractCwdFromSessionMeta(filePath) {
2490
2910
  }
2491
2911
  }
2492
2912
  async function walkJsonlFiles(dir) {
2913
+ return walkFiles2(dir, ".jsonl");
2914
+ }
2915
+ async function walkFiles2(dir, ext) {
2493
2916
  let result = [];
2494
2917
  async function walk2(d) {
2495
2918
  let entries;
2496
2919
  try {
2497
- entries = await readdir7(d, { withFileTypes: !0 });
2920
+ entries = await readdir8(d, { withFileTypes: !0 });
2498
2921
  } catch {
2499
2922
  return;
2500
2923
  }
2501
2924
  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);
2925
+ let full = join18(d, entry.name);
2926
+ entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
2504
2927
  }
2505
2928
  }
2506
2929
  return await walk2(dir), result;
@@ -2536,23 +2959,23 @@ async function extractCwdFromFirstJsonl(dir) {
2536
2959
  async function findFirstJsonl(dir) {
2537
2960
  let entries;
2538
2961
  try {
2539
- entries = await readdir7(dir, { withFileTypes: !0 });
2962
+ entries = await readdir8(dir, { withFileTypes: !0 });
2540
2963
  } catch {
2541
2964
  return;
2542
2965
  }
2543
2966
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
2544
- if (topJsonl) return join16(dir, topJsonl.name);
2967
+ if (topJsonl) return join18(dir, topJsonl.name);
2545
2968
  for (let entry of entries)
2546
2969
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
2547
2970
  try {
2548
- let sub = (await readdir7(join16(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
2549
- if (sub) return join16(dir, entry.name, sub);
2971
+ let sub = (await readdir8(join18(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
2972
+ if (sub) return join18(dir, entry.name, sub);
2550
2973
  } catch {
2551
2974
  continue;
2552
2975
  }
2553
2976
  }
2554
2977
  async function discoverCopilotProjects() {
2555
- let dir = join16(homedir16(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
2978
+ let dir = join18(homedir18(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
2556
2979
  for (let filePath of files) {
2557
2980
  let fh;
2558
2981
  try {
@@ -2574,9 +2997,9 @@ async function discoverCopilotProjects() {
2574
2997
  return [...projects];
2575
2998
  }
2576
2999
  async function discoverGeminiProjects() {
2577
- let filePath = join16(homedir16(), ".gemini", "projects.json");
3000
+ let filePath = join18(homedir18(), ".gemini", "projects.json");
2578
3001
  try {
2579
- let raw = await readFile13(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
3002
+ let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
2580
3003
  if (!projects || typeof projects != "object") return [];
2581
3004
  let names = [];
2582
3005
  for (let [path, _name] of Object.entries(projects)) {
@@ -2588,14 +3011,87 @@ async function discoverGeminiProjects() {
2588
3011
  return [];
2589
3012
  }
2590
3013
  }
3014
+ async function discoverCursorProjects() {
3015
+ let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
3016
+ try {
3017
+ let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
3018
+ for (let uri of workspaceUris) {
3019
+ let name = nameFromFileUri(uri);
3020
+ name && projects.add(name);
3021
+ }
3022
+ for (let folder of data.backupWorkspaces?.folders ?? []) {
3023
+ let name = nameFromFileUri(folder.folderUri);
3024
+ name && projects.add(name);
3025
+ }
3026
+ return [...projects];
3027
+ } catch {
3028
+ return [];
3029
+ }
3030
+ }
3031
+ async function discoverCopilotVscodeProjects() {
3032
+ 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();
3033
+ for (let filePath of files) {
3034
+ let content;
3035
+ try {
3036
+ content = await readFile16(filePath, "utf-8");
3037
+ } catch {
3038
+ continue;
3039
+ }
3040
+ for (let line of content.split(`
3041
+ `)) {
3042
+ let match = line.match(/file:\/\/\/[^\s]+/), name = nameFromFileUri(match?.[0]);
3043
+ name && projects.add(name);
3044
+ }
3045
+ }
3046
+ return [...projects];
3047
+ }
3048
+ async function discoverAntigravityProjects() {
3049
+ let dir = join18(homedir18(), ".gemini", "antigravity", "knowledge"), entries;
3050
+ try {
3051
+ entries = await readdir8(dir, { withFileTypes: !0 });
3052
+ } catch {
3053
+ return [];
3054
+ }
3055
+ let projects = /* @__PURE__ */ new Set();
3056
+ for (let entry of entries) {
3057
+ if (!entry.isDirectory()) continue;
3058
+ let metadataPath = join18(dir, entry.name, "metadata.json");
3059
+ try {
3060
+ let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3061
+ name && name !== "unknown" && projects.add(name);
3062
+ } catch {
3063
+ continue;
3064
+ }
3065
+ }
3066
+ return [...projects];
3067
+ }
3068
+ function nameFromFileUri(raw) {
3069
+ let path = pathFromFileUri(raw);
3070
+ if (!path) return;
3071
+ let name = basename10(path);
3072
+ return name && name !== "unknown" ? name : void 0;
3073
+ }
3074
+ function pathFromFileUri(raw) {
3075
+ if (raw) {
3076
+ if (raw.startsWith("file:///")) {
3077
+ let cleaned = raw.replace(/[.).,;:]+$/, "");
3078
+ try {
3079
+ return decodeURIComponent(cleaned.replace(/^file:\/\//, ""));
3080
+ } catch {
3081
+ return cleaned.replace(/^file:\/\//, "");
3082
+ }
3083
+ }
3084
+ return raw;
3085
+ }
3086
+ }
2591
3087
  function getClaudeDirs() {
2592
3088
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
2593
3089
  if (envVar)
2594
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
2595
- let home = homedir16();
3090
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join18(p, "projects"));
3091
+ let home = homedir18();
2596
3092
  return [
2597
- join16(home, ".config", "claude", "projects"),
2598
- join16(home, ".claude", "projects")
3093
+ join18(home, ".config", "claude", "projects"),
3094
+ join18(home, ".claude", "projects")
2599
3095
  ];
2600
3096
  }
2601
3097
 
@@ -2655,7 +3151,7 @@ try {
2655
3151
  }
2656
3152
  } else if (command === "import") {
2657
3153
  let parsed = parseArgs(argv.slice(1));
2658
- await runImport(parsed.flags);
3154
+ await runImport(parsed.flags, parsed.positionals);
2659
3155
  } else if (command === "setup")
2660
3156
  console.log(`To deploy the server, clone the repo and run the setup wizard:
2661
3157
  `), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
@@ -2698,14 +3194,12 @@ async function runScan(date, isJson) {
2698
3194
  console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt(result.totals.outputTokens)} \u63A8\u7406: ${fmt(result.totals.reasoningOutputTokens)}`);
2699
3195
  }
2700
3196
  async function runReport(flags) {
2701
- let config = await readConfig(), range = parseReportRange(flags.range), report = await buildLocalReport(range, { projectAliases: config.projectAliases });
3197
+ let config = await readConfig(), { dates, range } = resolveDateParams(flags, config), report = await buildLocalReport(range, { projectAliases: config.projectAliases, dates });
2702
3198
  if (flags.json) {
2703
3199
  console.log(JSON.stringify(report, null, 2));
2704
3200
  return;
2705
3201
  }
2706
- let lang = (typeof flags.lang == "string" ? flags.lang : config.lang) || "en";
2707
- if (lang !== "en" && lang !== "zh") throw new Error("--lang only supports en or zh");
2708
- let emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
3202
+ let lang = resolveGlobalLang(flags, config), emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
2709
3203
  console.log(renderReport(report, { lang, emoji, detail }));
2710
3204
  }
2711
3205
  function fmt(n) {
@@ -2755,17 +3249,7 @@ async function runSync(flags) {
2755
3249
  let config = await readConfig(), allTargets = config.targets ?? [];
2756
3250
  if (allTargets.length === 0)
2757
3251
  throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
2758
- let deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll"), targetName = resolveOptionalString(flags.target, void 0), targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, requestedDate = typeof flags.date == "string" ? flags.date : void 0, fromDate = typeof flags.from == "string" ? flags.from : void 0, toDate = typeof flags.to == "string" ? flags.to : void 0, targetDates;
2759
- if (requestedDate)
2760
- targetDates = [requestedDate];
2761
- else if (fromDate)
2762
- targetDates = buildDateRange(fromDate, toDate ?? getTodayDate());
2763
- else if (flags.today === !0)
2764
- targetDates = [getTodayDate()];
2765
- else {
2766
- let lookbackDays = typeof flags.lookback == "string" ? parsePositiveInt2(flags.lookback, "--lookback") : defaultLookbackDays(config);
2767
- targetDates = getClosedDates(lookbackDays), targetDates.push(getTodayDate());
2768
- }
3252
+ let deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll"), targetName = resolveOptionalString(flags.target, void 0), targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, { dates: targetDates } = resolveDateParams(flags, config);
2769
3253
  console.log(`\u626B\u63CF ${targetDates.length} \u5929 (${targetDates[0]} ~ ${targetDates[targetDates.length - 1]}) ...`);
2770
3254
  let allDays = (await scanDates(targetDates, { projectAliases: config.projectAliases })).filter((r) => r.breakdowns.length > 0).map((r) => ({ usageDate: r.usageDate, breakdowns: r.breakdowns }));
2771
3255
  if (allDays.length === 0) {
@@ -2802,31 +3286,51 @@ async function runSync(flags) {
2802
3286
  results: uploadResults
2803
3287
  }, null, 2));
2804
3288
  }
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 ?? [];
3289
+ async function runImport(flags, positionals = []) {
3290
+ let config = await readConfig(), targetName = resolveOptionalString(flags.target, void 0), allTargets = config.targets ?? [];
2821
3291
  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;
3292
+ 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;
3293
+ if (csvFiles.length > 0) {
3294
+ console.log(`Importing from ${csvFiles.length} CSV file(s)...`);
3295
+ let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0), dateRange;
3296
+ if (startDate && endDate) {
3297
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
3298
+ throw new Error("Dates must be in YYYY-MM-DD format");
3299
+ if (startDate > endDate) throw new Error("--start must be before --end");
3300
+ dateRange = buildDateRange(startDate, endDate);
3301
+ } else
3302
+ dateRange = buildDateRange("2020-01-01", "2030-12-31");
3303
+ let csvResults = await scanAnthropicCsvDates(dateRange, csvFiles);
3304
+ if (allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: csvResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0), allDays.length === 0) {
3305
+ console.log("No usage data found in the provided CSV files.");
3306
+ return;
3307
+ }
3308
+ console.log(`Found data for ${allDays.length} days across CSV files.`);
3309
+ } else {
3310
+ let adminKey = resolveOptionalString(flags.key, config.anthropicAdminKey);
3311
+ if (!adminKey)
3312
+ throw new Error(
3313
+ `Provide CSV files or an Anthropic Admin API key.
3314
+ CSV: aiusage import /path/to/*.csv
3315
+ API: aiusage import --key sk-ant-admin... --start DATE --end DATE
3316
+ aiusage config set anthropic-admin-key sk-ant-admin...
3317
+ Download CSVs at: https://platform.claude.com/usage?date=YYYY-MM
3318
+ Get Admin key at: console.anthropic.com \u2192 Settings \u2192 Admin Keys`
3319
+ );
3320
+ let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0);
3321
+ if (!startDate) throw new Error("--start DATE is required (e.g. --start 2025-11-01)");
3322
+ if (!endDate) throw new Error("--end DATE is required (e.g. --end 2026-01-08)");
3323
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
3324
+ throw new Error("Dates must be in YYYY-MM-DD format");
3325
+ if (startDate > endDate) throw new Error("--start must be before --end");
3326
+ console.log(`Fetching Anthropic API usage: ${startDate} \u2192 ${endDate}`);
3327
+ let dateRange = buildDateRange(startDate, endDate), apiResults = await scanAnthropicApiDates(dateRange, adminKey);
3328
+ if (allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: apiResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0), allDays.length === 0) {
3329
+ console.log("No usage data returned from Anthropic API for the specified range.");
3330
+ return;
3331
+ }
3332
+ console.log(`Found data for ${allDays.length} days. Uploading...`);
2828
3333
  }
2829
- console.log(`Found data for ${allDays.length} days. Uploading...`);
2830
3334
  for (let target of targets) {
2831
3335
  if (!target.deviceToken) {
2832
3336
  console.log(`Skipping "${target.name}": not enrolled (missing deviceToken)`);
@@ -2937,9 +3441,9 @@ function printHelp(zh2 = !1) {
2937
3441
  `);
2938
3442
  let cmds = zh2 ? [
2939
3443
  ["scan [--date YYYY-MM-DD] [--json]", "\u626B\u63CF\u67D0\u65E5\u7528\u91CF\u660E\u7EC6"],
2940
- ["report [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
2941
- ["sync [--today] [--lookback N] [--date YYYY-MM-DD]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
2942
- ["sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u4E0A\u4F20\u6307\u5B9A\u65E5\u671F\u8303\u56F4"],
3444
+ ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
3445
+ ["sync [--today] [--range 7d|1m|3m|all]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
3446
+ ["report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
2943
3447
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
2944
3448
  ["schedule [on|off|status] [--every 5m]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
2945
3449
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
@@ -2949,9 +3453,9 @@ function printHelp(zh2 = !1) {
2949
3453
  ["health [--server URL]", "\u6D4B\u8BD5\u670D\u52A1\u7AEF\u8FDE\u901A\u6027"]
2950
3454
  ] : [
2951
3455
  ["scan [--date YYYY-MM-DD] [--json]", "Scan daily usage breakdown"],
2952
- ["report [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
2953
- ["sync [--today] [--lookback N] [--date YYYY-MM-DD]", "Upload usage to server"],
2954
- ["sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Upload specific date range"],
3456
+ ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
3457
+ ["sync [--today] [--range 7d|1m|3m|all]", "Upload usage to server"],
3458
+ ["report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
2955
3459
  ["project [list|alias]", "Project management & aliases"],
2956
3460
  ["schedule [on|off|status] [--every 5m]", "Scheduled sync management"],
2957
3461
  ["doctor", "Run diagnostics"],
@@ -2970,16 +3474,16 @@ function printUsageHint(zh2 = !1) {
2970
3474
  `);
2971
3475
  let cmds = zh2 ? [
2972
3476
  ["scan [--date YYYY-MM-DD]", "\u626B\u63CF\u67D0\u65E5\u7528\u91CF\u660E\u7EC6"],
2973
- ["report [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
2974
- ["sync [--today]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
3477
+ ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
3478
+ ["sync [--today] [--range 7d|1m|3m|all]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
2975
3479
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
2976
3480
  ["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
2977
3481
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
2978
3482
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
2979
3483
  ] : [
2980
3484
  ["scan [--date YYYY-MM-DD]", "Scan daily usage breakdown"],
2981
- ["report [--range 7d|1m|3m|all]", "Local usage report"],
2982
- ["sync [--today]", "Upload usage to server"],
3485
+ ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
3486
+ ["sync [--today] [--range 7d|1m|3m|all]", "Upload usage to server"],
2983
3487
  ["project [list|alias]", "Project management & aliases"],
2984
3488
  ["schedule [on|off|status]", "Scheduled sync management"],
2985
3489
  ["doctor", "Run diagnostics"],
@@ -3019,6 +3523,29 @@ function getYesterdayDate() {
3019
3523
  let yesterday = /* @__PURE__ */ new Date();
3020
3524
  return yesterday.setDate(yesterday.getDate() - 1), localDateKey(yesterday);
3021
3525
  }
3526
+ function resolveDateParams(flags, config) {
3527
+ let requestedDate = typeof flags.date == "string" ? flags.date : void 0, fromDate = typeof flags.from == "string" ? flags.from : typeof flags.start == "string" ? flags.start : void 0, toDate = typeof flags.to == "string" ? flags.to : typeof flags.end == "string" ? flags.end : void 0;
3528
+ if (requestedDate)
3529
+ return { dates: [requestedDate], range: "today" };
3530
+ if (fromDate)
3531
+ return { dates: buildDateRange(fromDate, toDate ?? getTodayDate()), range: "all" };
3532
+ if (flags.today === !0)
3533
+ return { dates: [getTodayDate()], range: "today" };
3534
+ let rangeFlag = flags.range;
3535
+ if (typeof rangeFlag == "string")
3536
+ return { range: parseReportRange(rangeFlag) };
3537
+ if (typeof flags.lookback == "string") {
3538
+ let lookbackDays2 = parsePositiveInt2(flags.lookback, "--lookback"), dates2 = getClosedDates(lookbackDays2);
3539
+ return dates2.push(getTodayDate()), { dates: dates2, range: "7d" };
3540
+ }
3541
+ let lookbackDays = defaultLookbackDays(config), dates = getClosedDates(lookbackDays);
3542
+ return dates.push(getTodayDate()), { dates, range: "7d" };
3543
+ }
3544
+ function resolveGlobalLang(flags, config) {
3545
+ let lang = (typeof flags.lang == "string" ? flags.lang : config.lang) || "en";
3546
+ if (lang !== "en" && lang !== "zh") throw new Error("--lang only supports en or zh");
3547
+ return lang;
3548
+ }
3022
3549
  function getTodayDate() {
3023
3550
  return localDateKey(/* @__PURE__ */ new Date());
3024
3551
  }