@aiusage/cli 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +61 -39
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -28,9 +28,13 @@ function parseTs(value) {
28
28
  function dateKey(date) {
29
29
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
30
30
  }
31
- function projectFromPath(raw, aliases) {
32
- let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
33
- return aliases?.[raw] ?? aliases?.[name] ?? name;
31
+ function resolveProjectFields(rawPath, aliases) {
32
+ let parts = rawPath.split("/").filter(Boolean), display = parts[parts.length - 1] || "unknown", alias = aliases?.[rawPath] ?? aliases?.[display];
33
+ return {
34
+ project: rawPath || "unknown",
35
+ projectDisplay: display,
36
+ projectAlias: alias
37
+ };
34
38
  }
35
39
  async function walkFiles(dir, ext) {
36
40
  let result = [];
@@ -115,18 +119,18 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
115
119
  continue;
116
120
  }
117
121
  for (let projDir of projectDirs) {
118
- let projectPath = join2(baseDir, projDir), project = resolveProject(projectPath, projectAliases), jsonlFiles = [];
122
+ let projectPath = join2(baseDir, projDir), fields = resolveProject(projectPath, projectAliases), jsonlFiles = [];
119
123
  try {
120
124
  await walkForJsonl(projectPath, jsonlFiles);
121
125
  } catch {
122
126
  continue;
123
127
  }
124
128
  for (let filePath of jsonlFiles)
125
- fileJobs.push({ filePath, project });
129
+ fileJobs.push({ filePath, projectFields: fields });
126
130
  }
127
131
  }
128
132
  await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
129
- await processJsonlFile(job.filePath, job.project, targetDateSet, projectAliases, deduped);
133
+ await processJsonlFile(job.filePath, job.projectFields, targetDateSet, projectAliases, deduped);
130
134
  });
131
135
  for (let [dedupeKey, usage] of deduped.entries()) {
132
136
  let [usageDate] = dedupeKey.split("|", 1), grouped = groupedByDate.get(usageDate);
@@ -138,6 +142,8 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
138
142
  channel: "cli",
139
143
  model: usage.model,
140
144
  project: usage.project,
145
+ projectDisplay: usage.projectDisplay,
146
+ projectAlias: usage.projectAlias,
141
147
  eventCount: 1,
142
148
  inputTokens: usage.inputTokens,
143
149
  cachedInputTokens: usage.cachedInputTokens,
@@ -153,7 +159,7 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
153
159
  [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
154
160
  );
155
161
  }
156
- async function processJsonlFile(filePath, fallbackProject, targetDateSet, projectAliases, deduped) {
162
+ async function processJsonlFile(filePath, fallbackFields, targetDateSet, projectAliases, deduped) {
157
163
  let fh;
158
164
  try {
159
165
  fh = await open(filePath, "r");
@@ -185,12 +191,14 @@ async function processJsonlFile(filePath, fallbackProject, targetDateSet, projec
185
191
  if (!requestId) continue;
186
192
  let usage = message.usage, model = normalizeModelName(rawModel);
187
193
  usage.speed === "fast" && (model = `${model}-fast`);
188
- let recordProject = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackProject, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
194
+ 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;
189
195
  cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
190
196
  let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
191
197
  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, {
192
198
  model,
193
- project: recordProject,
199
+ project: recordFields.project,
200
+ projectDisplay: recordFields.projectDisplay,
201
+ projectAlias: recordFields.projectAlias,
194
202
  inputTokens: usage.input_tokens ?? 0,
195
203
  cacheWrite5mTokens: cache5m,
196
204
  cacheWrite1hTokens: cache1h,
@@ -221,8 +229,8 @@ function extractProjectFromCwd(cwd) {
221
229
  return parts[parts.length - 1] || "unknown";
222
230
  }
223
231
  function resolveProject(rawPath, aliases) {
224
- let project = extractProjectFromCwd(rawPath);
225
- return aliases?.[rawPath] ?? aliases?.[project] ?? project;
232
+ let project = extractProjectFromCwd(rawPath), alias = aliases?.[rawPath] ?? aliases?.[project];
233
+ return { project: rawPath, projectDisplay: project, projectAlias: alias };
226
234
  }
227
235
  async function walkForJsonl(dir, result) {
228
236
  let entries = await readdir2(dir, { withFileTypes: !0 });
@@ -262,7 +270,7 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
262
270
  let rl = createInterface2({
263
271
  input: fh.createReadStream({ encoding: "utf-8" }),
264
272
  crlfDelay: 1 / 0
265
- }), currentModel = "unknown", currentProject = "unknown", previousTotal = {};
273
+ }), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
266
274
  for await (let line of rl) {
267
275
  if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
268
276
  let record;
@@ -273,7 +281,7 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
273
281
  }
274
282
  if (record.type === "turn_context") {
275
283
  let rawModel = record.payload?.model ?? currentModel;
276
- rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (currentProject = extractProject(record.payload.cwd, projectAliases));
284
+ rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
277
285
  continue;
278
286
  }
279
287
  if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
@@ -295,13 +303,15 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
295
303
  previousTotal = total;
296
304
  let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), grouped = groupedByDate.get(usageDate);
297
305
  if (!grouped) continue;
298
- let key = `${currentModel}|${currentProject}`, existing = grouped.get(key);
306
+ let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
299
307
  existing ? (existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += last.cached_input_tokens ?? 0, existing.outputTokens += last.output_tokens ?? 0, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0) : grouped.set(key, {
300
308
  provider: "openai",
301
309
  product: "codex",
302
310
  channel: "cli",
303
311
  model: currentModel,
304
- project: currentProject,
312
+ project: currentProjectFields.project,
313
+ projectDisplay: currentProjectFields.projectDisplay,
314
+ projectAlias: currentProjectFields.projectAlias,
305
315
  eventCount: 1,
306
316
  inputTokens: nonCachedInput,
307
317
  cachedInputTokens: last.cached_input_tokens ?? 0,
@@ -350,10 +360,6 @@ function toDateKey2(date) {
350
360
  let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
351
361
  return `${year}-${month}-${day}`;
352
362
  }
353
- function extractProject(cwd, aliases) {
354
- let parts = cwd.split("/").filter(Boolean), project = parts[parts.length - 1] || "unknown";
355
- return aliases?.[cwd] ?? aliases?.[project] ?? project;
356
- }
357
363
 
358
364
  // src/scanners/copilot.ts
359
365
  import { readFile } from "node:fs/promises";
@@ -370,7 +376,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
370
376
  } catch {
371
377
  continue;
372
378
  }
373
- let sessionProject = "unknown", lines = content.split(`
379
+ let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
374
380
  `);
375
381
  for (let line of lines) {
376
382
  if (!line.trim()) continue;
@@ -382,7 +388,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
382
388
  }
383
389
  if (obj.type === "session.start" || obj.type === "session.resume") {
384
390
  let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
385
- raw && (sessionProject = projectFromPath(raw, projectAliases));
391
+ raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
386
392
  }
387
393
  if (obj.type !== "session.shutdown") continue;
388
394
  let ts = parseTs(obj.timestamp);
@@ -397,13 +403,15 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
397
403
  let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
398
404
  accumulate(
399
405
  dayMap,
400
- `${model}|${sessionProject}`,
406
+ `${model}|${sessionProjectFields.project}`,
401
407
  {
402
408
  provider: "github",
403
409
  product: "copilot-cli",
404
410
  channel: "cli",
405
411
  model,
406
- project: sessionProject,
412
+ project: sessionProjectFields.project,
413
+ projectDisplay: sessionProjectFields.projectDisplay,
414
+ projectAlias: sessionProjectFields.projectAlias,
407
415
  inputTokens: 0,
408
416
  cachedInputTokens: 0,
409
417
  cacheWriteTokens: 0,
@@ -565,6 +573,7 @@ async function scanCursorDates(targetDates) {
565
573
  channel: "ide",
566
574
  model,
567
575
  project: "unknown",
576
+ projectDisplay: "unknown",
568
577
  eventCount: 1,
569
578
  inputTokens,
570
579
  cachedInputTokens: cacheRead,
@@ -613,6 +622,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
613
622
  channel: "cli",
614
623
  model,
615
624
  project: "unknown",
625
+ projectDisplay: "unknown",
616
626
  inputTokens: 0,
617
627
  cachedInputTokens: 0,
618
628
  cacheWriteTokens: 0,
@@ -673,16 +683,18 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
673
683
  }
674
684
  let u = obj.usageMetadata;
675
685
  if (!u) continue;
676
- let model = obj.model ?? "unknown", project = obj.cwd ? projectFromPath(obj.cwd, projectAliases) : projectFromPath(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
686
+ let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
677
687
  accumulate(
678
688
  dayMap,
679
- `${model}|${project}`,
689
+ `${model}|${fields.project}`,
680
690
  {
681
691
  provider: "alibaba",
682
692
  product: "qwen-code",
683
693
  channel: "cli",
684
694
  model,
685
- project,
695
+ project: fields.project,
696
+ projectDisplay: fields.projectDisplay,
697
+ projectAlias: fields.projectAlias,
686
698
  inputTokens: 0,
687
699
  cachedInputTokens: 0,
688
700
  cacheWriteTokens: 0,
@@ -705,7 +717,7 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
705
717
  if (files.length === 0) return emptyResult(dates);
706
718
  let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
707
719
  for (let filePath of files) {
708
- let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), project = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
720
+ let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
709
721
  try {
710
722
  content = await readFile4(filePath, "utf-8");
711
723
  } catch {
@@ -736,13 +748,15 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
736
748
  let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
737
749
  accumulate(
738
750
  dayMap,
739
- `${currentModel}|${project}`,
751
+ `${currentModel}|${projectFields.project}`,
740
752
  {
741
753
  provider: "moonshot",
742
754
  product: "kimi-code",
743
755
  channel: "cli",
744
756
  model: currentModel,
745
- project,
757
+ project: projectFields.project,
758
+ projectDisplay: projectFields.projectDisplay,
759
+ projectAlias: projectFields.projectAlias,
746
760
  inputTokens: 0,
747
761
  cachedInputTokens: 0,
748
762
  cacheWriteTokens: 0,
@@ -757,7 +771,7 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
757
771
  }
758
772
  function resolveKimiProject(hash, workspaceMap, aliases) {
759
773
  let wsPath = workspaceMap.get(hash);
760
- return wsPath ? projectFromPath(wsPath, aliases) : projectFromPath(hash, aliases);
774
+ return wsPath ? resolveProjectFields(wsPath, aliases) : resolveProjectFields(hash, aliases);
761
775
  }
762
776
  async function loadWorkspaceMap(kimiHome) {
763
777
  let map = /* @__PURE__ */ new Map();
@@ -832,6 +846,7 @@ function processLedger(thread, events, dates, grouped) {
832
846
  channel: "cli",
833
847
  model,
834
848
  project: "unknown",
849
+ projectDisplay: "unknown",
835
850
  inputTokens: 0,
836
851
  cachedInputTokens: 0,
837
852
  cacheWriteTokens: 0,
@@ -863,6 +878,7 @@ function processMessages(thread, dates, grouped) {
863
878
  channel: "cli",
864
879
  model,
865
880
  project: "unknown",
881
+ projectDisplay: "unknown",
866
882
  inputTokens: 0,
867
883
  cachedInputTokens: 0,
868
884
  cacheWriteTokens: 0,
@@ -920,7 +936,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
920
936
  }
921
937
  let usage = settings.tokenUsage;
922
938
  if (!usage) continue;
923
- let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), project = projectAliases?.[rawProject] ?? rawProject;
939
+ let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
924
940
  accumulate(
925
941
  dayMap,
926
942
  `${model}|${project}`,
@@ -930,6 +946,8 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
930
946
  channel: "cli",
931
947
  model,
932
948
  project,
949
+ projectDisplay: rawProject,
950
+ projectAlias: alias,
933
951
  inputTokens: 0,
934
952
  cachedInputTokens: 0,
935
953
  cacheWriteTokens: 0,
@@ -970,16 +988,18 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
970
988
  if (!ts) continue;
971
989
  let dk = dateKey(ts), dayMap = grouped.get(dk);
972
990
  if (!dayMap) continue;
973
- let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, project = rootPath ? projectFromPath(rootPath, projectAliases) : "unknown";
991
+ let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, fields = rootPath ? resolveProjectFields(rootPath, projectAliases) : { project: "unknown", projectDisplay: "unknown" };
974
992
  accumulate(
975
993
  dayMap,
976
- `${model}|${project}`,
994
+ `${model}|${fields.project}`,
977
995
  {
978
996
  provider: "opencode",
979
997
  product: "opencode",
980
998
  channel: "cli",
981
999
  model,
982
- project,
1000
+ project: fields.project,
1001
+ projectDisplay: fields.projectDisplay,
1002
+ projectAlias: fields.projectAlias,
983
1003
  inputTokens: 0,
984
1004
  cachedInputTokens: 0,
985
1005
  cacheWriteTokens: 0,
@@ -1007,7 +1027,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1007
1027
  } catch {
1008
1028
  continue;
1009
1029
  }
1010
- let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir), sessionProject = extractProjectFromEncoded(encodedCwd);
1030
+ let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
1011
1031
  for (let line of content.split(`
1012
1032
  `)) {
1013
1033
  if (!line.trim()) continue;
@@ -1018,7 +1038,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1018
1038
  continue;
1019
1039
  }
1020
1040
  if (obj.type === "session" && obj.cwd) {
1021
- sessionProject = projectFromPath(obj.cwd, projectAliases);
1041
+ sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
1022
1042
  continue;
1023
1043
  }
1024
1044
  if (obj.type !== "message") continue;
@@ -1037,13 +1057,15 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1037
1057
  let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
1038
1058
  accumulate(
1039
1059
  dayMap,
1040
- `${model}|${sessionProject}`,
1060
+ `${model}|${sessionProjectFields.project}`,
1041
1061
  {
1042
1062
  provider: "inflection",
1043
1063
  product: "pi",
1044
1064
  channel: "cli",
1045
1065
  model,
1046
- project: sessionProject,
1066
+ project: sessionProjectFields.project,
1067
+ projectDisplay: sessionProjectFields.projectDisplay,
1068
+ projectAlias: sessionProjectFields.projectAlias,
1047
1069
  inputTokens: 0,
1048
1070
  cachedInputTokens: 0,
1049
1071
  cacheWriteTokens: 0,
@@ -2528,7 +2550,7 @@ async function runScan(date, isJson) {
2528
2550
  for (let [provider, breakdowns] of byProvider) {
2529
2551
  console.log(`\u2500\u2500 ${provider} \u2500\u2500`);
2530
2552
  for (let b of breakdowns.sort((a, c) => c.inputTokens - a.inputTokens))
2531
- console.log(` ${b.model} | ${b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
2553
+ console.log(` ${b.model} | ${b.projectAlias ?? b.projectDisplay ?? b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
2532
2554
  console.log();
2533
2555
  }
2534
2556
  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)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiusage/cli",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "description": "Track and sync AI tool token usage across devices.",
5
5
  "license": "MIT",
6
6
  "private": false,