@aiusage/cli 1.6.1 → 1.6.4

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
@@ -18,10 +18,16 @@ import { homedir } from "node:os";
18
18
  // src/scanners/utils.ts
19
19
  import { readdir } from "node:fs/promises";
20
20
  import { join } from "node:path";
21
+ var MIN_VALID_MS = Date.UTC(2015, 0, 1);
21
22
  function parseTs(value) {
22
- if (value == null) return null;
23
- let d = new Date(value);
24
- return isNaN(d.getTime()) ? null : d;
23
+ if (value == null || value === "") return null;
24
+ let input = value;
25
+ if (typeof value == "number" || /^\d+(\.\d+)?$/.test(value)) {
26
+ let num = typeof value == "number" ? value : Number(value);
27
+ input = num < 1e12 ? num * 1e3 : num;
28
+ }
29
+ let d = new Date(input), t2 = d.getTime();
30
+ return isNaN(t2) || t2 < MIN_VALID_MS ? null : d;
25
31
  }
26
32
  function dateKey(date) {
27
33
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
@@ -360,7 +366,7 @@ async function walkForJsonl(dir, result) {
360
366
  }
361
367
 
362
368
  // src/scanners/codex.ts
363
- import { readdir as readdir4, open as open2 } from "node:fs/promises";
369
+ import { readdir as readdir4, open as open2, readFile as readFile3 } from "node:fs/promises";
364
370
  import { join as join4 } from "node:path";
365
371
  import { homedir as homedir3 } from "node:os";
366
372
  import { createInterface as createInterface2 } from "node:readline";
@@ -368,17 +374,17 @@ var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
368
374
  async function scanCodexDates(targetDates, codexDir, projectAliases) {
369
375
  let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
370
376
  for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
371
- let baseDir = codexDir ?? join4(homedir3(), ".codex"), sessionFiles = await collectSessionFiles(baseDir);
377
+ let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
372
378
  if (sessionFiles.length === 0)
373
379
  return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
374
380
  let globalSeenSigs = /* @__PURE__ */ new Set();
375
381
  return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
376
- await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs);
382
+ await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier);
377
383
  }), new Map(
378
384
  [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
379
385
  );
380
386
  }
381
- async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs) {
387
+ async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier) {
382
388
  let fh;
383
389
  try {
384
390
  fh = await open2(filePath, "r");
@@ -400,7 +406,7 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
400
406
  }
401
407
  if (record.type === "turn_context") {
402
408
  let rawModel = record.payload?.model ?? currentModel;
403
- rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
409
+ rawModel !== "<synthetic>" && (currentModel = applyCodexServiceTier(normalizeModelName(rawModel), serviceTier)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
404
410
  continue;
405
411
  }
406
412
  if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
@@ -410,7 +416,9 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
410
416
  if (!ts) continue;
411
417
  let usageDate = toDateKey2(ts);
412
418
  if (!targetDateSet.has(usageDate)) continue;
413
- let total = info.total_token_usage, signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
419
+ let total = info.total_token_usage;
420
+ if ((total.input_tokens ?? 0) + (total.cached_input_tokens ?? 0) + (total.output_tokens ?? 0) + (total.reasoning_output_tokens ?? 0) + (total.total_tokens ?? 0) === 0) continue;
421
+ let signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
414
422
  if (globalSeenSigs.has(signature)) continue;
415
423
  globalSeenSigs.add(signature);
416
424
  let last = info.last_token_usage ?? {
@@ -454,6 +462,19 @@ async function collectSessionFiles(baseDir) {
454
462
  let sessionsDir = join4(baseDir, "sessions");
455
463
  return await walkDir(sessionsDir, paths), paths;
456
464
  }
465
+ async function detectCodexServiceTier(baseDir) {
466
+ let config = "";
467
+ try {
468
+ config = await readFile3(join4(baseDir, "config.toml"), "utf-8");
469
+ } catch {
470
+ return null;
471
+ }
472
+ let serviceTier = config.match(/^\s*service_tier\s*=\s*["']([^"']+)["']/m)?.[1]?.trim().toLowerCase();
473
+ return serviceTier === "priority" ? "priority" : serviceTier === "fast" || config.match(/^\s*fast_mode\s*=\s*(true|false)\s*$/m)?.[1] === "true" ? "fast" : null;
474
+ }
475
+ function applyCodexServiceTier(model, serviceTier) {
476
+ return !serviceTier || model.endsWith("-fast") || model.endsWith("-priority") ? model : model === "gpt-5.5" || model === "gpt-5.4" ? `${model}-${serviceTier}` : model;
477
+ }
457
478
  async function walkDir(dir, result) {
458
479
  let entries;
459
480
  try {
@@ -481,7 +502,7 @@ function toDateKey2(date) {
481
502
  }
482
503
 
483
504
  // src/scanners/copilot.ts
484
- import { readFile as readFile3 } from "node:fs/promises";
505
+ import { readFile as readFile4 } from "node:fs/promises";
485
506
  import { join as join5 } from "node:path";
486
507
  import { homedir as homedir4 } from "node:os";
487
508
  async function scanCopilotDates(targetDates, baseDir, projectAliases) {
@@ -491,7 +512,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
491
512
  for (let filePath of files) {
492
513
  let content;
493
514
  try {
494
- content = await readFile3(filePath, "utf-8");
515
+ content = await readFile4(filePath, "utf-8");
495
516
  } catch {
496
517
  continue;
497
518
  }
@@ -546,7 +567,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
546
567
  }
547
568
 
548
569
  // src/scanners/copilot-vscode.ts
549
- import { readFile as readFile4 } from "node:fs/promises";
570
+ import { readFile as readFile5 } from "node:fs/promises";
550
571
  import { basename as basename2, dirname, join as join6 } from "node:path";
551
572
  import { homedir as homedir5 } from "node:os";
552
573
  async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
@@ -556,7 +577,7 @@ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, work
556
577
  for (let filePath of logFiles) {
557
578
  let content;
558
579
  try {
559
- content = await readFile4(filePath, "utf-8");
580
+ content = await readFile5(filePath, "utf-8");
560
581
  } catch {
561
582
  continue;
562
583
  }
@@ -621,7 +642,7 @@ function extractFileUriPath(line) {
621
642
  async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
622
643
  let content;
623
644
  try {
624
- content = await readFile4(filePath, "utf-8");
645
+ content = await readFile5(filePath, "utf-8");
625
646
  } catch {
626
647
  return;
627
648
  }
@@ -663,7 +684,7 @@ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, proj
663
684
  async function readWorkspaceFolderPath(sessionFilePath) {
664
685
  let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
665
686
  try {
666
- content = await readFile4(workspaceJsonPath, "utf-8");
687
+ content = await readFile5(workspaceJsonPath, "utf-8");
667
688
  } catch {
668
689
  return null;
669
690
  }
@@ -838,7 +859,7 @@ async function scanCursorDates(targetDates) {
838
859
  }
839
860
 
840
861
  // src/scanners/gemini.ts
841
- import { readFile as readFile5 } from "node:fs/promises";
862
+ import { readFile as readFile6 } from "node:fs/promises";
842
863
  import { basename as basename3, join as join8 } from "node:path";
843
864
  import { homedir as homedir7 } from "node:os";
844
865
  async function scanGeminiDates(targetDates, baseDir, projectAliases) {
@@ -849,7 +870,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
849
870
  if (basename3(filePath) === "logs.json") continue;
850
871
  let content;
851
872
  try {
852
- content = await readFile5(filePath, "utf-8");
873
+ content = await readFile6(filePath, "utf-8");
853
874
  } catch {
854
875
  continue;
855
876
  }
@@ -894,7 +915,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
894
915
  async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
895
916
  let content;
896
917
  try {
897
- content = await readFile5(filePath, "utf-8");
918
+ content = await readFile6(filePath, "utf-8");
898
919
  } catch {
899
920
  return;
900
921
  }
@@ -945,7 +966,7 @@ function extractTokens(msg) {
945
966
  }
946
967
 
947
968
  // src/scanners/qwen.ts
948
- import { readFile as readFile6 } from "node:fs/promises";
969
+ import { readFile as readFile7 } from "node:fs/promises";
949
970
  import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
950
971
  import { homedir as homedir8 } from "node:os";
951
972
  async function scanQwenDates(targetDates, baseDir, projectAliases) {
@@ -955,7 +976,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
955
976
  for (let filePath of files) {
956
977
  let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
957
978
  try {
958
- content = await readFile6(filePath, "utf-8");
979
+ content = await readFile7(filePath, "utf-8");
959
980
  } catch {
960
981
  continue;
961
982
  }
@@ -1005,7 +1026,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
1005
1026
  }
1006
1027
 
1007
1028
  // src/scanners/kimi.ts
1008
- import { readFile as readFile7 } from "node:fs/promises";
1029
+ import { readFile as readFile8 } from "node:fs/promises";
1009
1030
  import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
1010
1031
  import { homedir as homedir9 } from "node:os";
1011
1032
  async function scanKimiDates(targetDates, baseDir, projectAliases) {
@@ -1015,7 +1036,7 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
1015
1036
  for (let filePath of files) {
1016
1037
  let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
1017
1038
  try {
1018
- content = await readFile7(filePath, "utf-8");
1039
+ content = await readFile8(filePath, "utf-8");
1019
1040
  } catch {
1020
1041
  continue;
1021
1042
  }
@@ -1072,7 +1093,7 @@ function resolveKimiProject(hash, workspaceMap, aliases2) {
1072
1093
  async function loadWorkspaceMap(kimiHome) {
1073
1094
  let map = /* @__PURE__ */ new Map();
1074
1095
  try {
1075
- let raw = await readFile7(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
1096
+ let raw = await readFile8(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
1076
1097
  if (config.workspaces)
1077
1098
  for (let [hash, info] of Object.entries(config.workspaces))
1078
1099
  info.path && map.set(hash, info.path);
@@ -1082,7 +1103,7 @@ async function loadWorkspaceMap(kimiHome) {
1082
1103
  }
1083
1104
 
1084
1105
  // src/scanners/amp.ts
1085
- import { readFile as readFile8 } from "node:fs/promises";
1106
+ import { readFile as readFile9 } from "node:fs/promises";
1086
1107
  import { join as join11 } from "node:path";
1087
1108
  import { homedir as homedir10 } from "node:os";
1088
1109
  function resolveAmpDir(baseDir) {
@@ -1102,7 +1123,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
1102
1123
  for (let filePath of threadFiles) {
1103
1124
  let raw;
1104
1125
  try {
1105
- raw = await readFile8(filePath, "utf-8");
1126
+ raw = await readFile9(filePath, "utf-8");
1106
1127
  } catch {
1107
1128
  continue;
1108
1129
  }
@@ -1187,7 +1208,7 @@ function processMessages(thread, dates, grouped) {
1187
1208
  }
1188
1209
 
1189
1210
  // src/scanners/droid.ts
1190
- import { readFile as readFile9 } from "node:fs/promises";
1211
+ import { readFile as readFile10 } from "node:fs/promises";
1191
1212
  import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
1192
1213
  import { homedir as homedir11 } from "node:os";
1193
1214
  function extractProjectFromSlug(dirPath) {
@@ -1201,7 +1222,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
1201
1222
  for (let jsonlPath of files) {
1202
1223
  let content;
1203
1224
  try {
1204
- content = await readFile9(jsonlPath, "utf-8");
1225
+ content = await readFile10(jsonlPath, "utf-8");
1205
1226
  } catch {
1206
1227
  continue;
1207
1228
  }
@@ -1220,7 +1241,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
1220
1241
  if (!dayMap) continue;
1221
1242
  let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
1222
1243
  try {
1223
- settingsRaw = await readFile9(settingsPath, "utf-8");
1244
+ settingsRaw = await readFile10(settingsPath, "utf-8");
1224
1245
  } catch {
1225
1246
  continue;
1226
1247
  }
@@ -1257,7 +1278,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
1257
1278
  }
1258
1279
 
1259
1280
  // src/scanners/opencode.ts
1260
- import { readFile as readFile10 } from "node:fs/promises";
1281
+ import { readFile as readFile11 } from "node:fs/promises";
1261
1282
  import { homedir as homedir12 } from "node:os";
1262
1283
  async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1263
1284
  let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
@@ -1266,7 +1287,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1266
1287
  for (let filePath of files) {
1267
1288
  let raw;
1268
1289
  try {
1269
- raw = await readFile10(filePath, "utf-8");
1290
+ raw = await readFile11(filePath, "utf-8");
1270
1291
  } catch {
1271
1292
  continue;
1272
1293
  }
@@ -1309,7 +1330,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1309
1330
  }
1310
1331
 
1311
1332
  // src/scanners/pi.ts
1312
- import { readFile as readFile11 } from "node:fs/promises";
1333
+ import { readFile as readFile12 } from "node:fs/promises";
1313
1334
  import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
1314
1335
  import { homedir as homedir13 } from "node:os";
1315
1336
  async function scanPiDates(targetDates, baseDir, projectAliases) {
@@ -1319,7 +1340,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1319
1340
  for (let filePath of files) {
1320
1341
  let content;
1321
1342
  try {
1322
- content = await readFile11(filePath, "utf-8");
1343
+ content = await readFile12(filePath, "utf-8");
1323
1344
  } catch {
1324
1345
  continue;
1325
1346
  }
@@ -1517,7 +1538,7 @@ function chunkDateRange(startDate, endDate) {
1517
1538
  }
1518
1539
 
1519
1540
  // src/scanners/anthropic-csv.ts
1520
- import { readFile as readFile12 } from "node:fs/promises";
1541
+ import { readFile as readFile13 } from "node:fs/promises";
1521
1542
  async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
1522
1543
  if (!targetDates.length) return /* @__PURE__ */ new Map();
1523
1544
  let targetDateSet = new Set(targetDates), grouped = new Map(
@@ -1526,7 +1547,7 @@ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
1526
1547
  for (let filePath of csvFilePaths) {
1527
1548
  let content;
1528
1549
  try {
1529
- content = await readFile12(filePath, "utf-8");
1550
+ content = await readFile13(filePath, "utf-8");
1530
1551
  } catch {
1531
1552
  continue;
1532
1553
  }
@@ -1584,7 +1605,7 @@ function parseCsv(content) {
1584
1605
  }
1585
1606
 
1586
1607
  // src/report.ts
1587
- import { readdir as readdir6, readFile as readFile13 } from "node:fs/promises";
1608
+ import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
1588
1609
  import { homedir as homedir14 } from "node:os";
1589
1610
  import { basename as basename8, join as join14 } from "node:path";
1590
1611
 
@@ -1592,6 +1613,14 @@ import { basename as basename8, join as join14 } from "node:path";
1592
1613
  var anthropic = {
1593
1614
  "claude-code": {
1594
1615
  models: {
1616
+ "claude-opus-4-8": {
1617
+ currency: "USD",
1618
+ input_per_million: 5,
1619
+ output_per_million: 25,
1620
+ cache_write_5m_per_million: 6.25,
1621
+ cache_write_1h_per_million: 10,
1622
+ cached_input_per_million: 0.5
1623
+ },
1595
1624
  "claude-opus-4-7": {
1596
1625
  currency: "USD",
1597
1626
  input_per_million: 5,
@@ -2370,7 +2399,7 @@ var inflection = {
2370
2399
  };
2371
2400
 
2372
2401
  // ../shared/src/pricing/catalog.ts
2373
- var PRICING_VERSION = "2026-05-24-unified-v1", aliases = {
2402
+ var PRICING_VERSION = "2026-06-22-codex-tier-v1", aliases = {
2374
2403
  "claude-opus-4-7-20260201": "claude-opus-4-7",
2375
2404
  "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
2376
2405
  "claude-opus-4-6-20250301": "claude-opus-4-6",
@@ -2402,10 +2431,20 @@ var PRICING_VERSION = "2026-05-24-unified-v1", aliases = {
2402
2431
  };
2403
2432
 
2404
2433
  // ../shared/src/pricing/calculate.ts
2405
- var FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
2434
+ var ANTHROPIC_FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
2435
+ "claude-opus-4-8",
2406
2436
  "claude-opus-4-7",
2407
2437
  "claude-opus-4-6"
2408
- ]);
2438
+ ]), OPENAI_CODEX_TIER_MULTIPLIERS = {
2439
+ "gpt-5.5": 2.5,
2440
+ "gpt-5.4": 2
2441
+ };
2442
+ function splitServiceTierSuffix(model) {
2443
+ return model.endsWith("-priority") ? { baseModel: model.replace(/-priority$/, ""), tier: "priority" } : model.endsWith("-fast") ? { baseModel: model.replace(/-fast$/, ""), tier: "fast" } : { baseModel: model, tier: null };
2444
+ }
2445
+ function getServiceTierMultiplier(provider, product, resolvedModel, tier) {
2446
+ return tier ? provider === "openai" && product === "codex" ? OPENAI_CODEX_TIER_MULTIPLIERS[resolvedModel] ?? 1 : tier === "fast" && FAST_SUPPORTED.has(resolvedModel) ? ANTHROPIC_FAST_MULTIPLIER : 1 : 1;
2447
+ }
2409
2448
  function resolveModelPricing(catalog2, provider, product, model) {
2410
2449
  let models = catalog2.providers[provider]?.[product]?.models;
2411
2450
  if (!models) return null;
@@ -2439,13 +2478,13 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2439
2478
  let cat = options.catalog ?? catalog;
2440
2479
  if (tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens + tokens.outputTokens === 0)
2441
2480
  return { estimatedCostUsd: 0, costStatus: "exact", pricingVersion: cat.version };
2442
- let isFast = model.endsWith("-fast"), baseModel = isFast ? model.replace(/-fast$/, "") : model, resolved = resolveModelPricing(cat, provider, product, baseModel);
2481
+ let { baseModel, tier } = splitServiceTierSuffix(model), resolved = resolveModelPricing(cat, provider, product, baseModel);
2443
2482
  if (!resolved)
2444
2483
  return { estimatedCostUsd: 0, costStatus: "unavailable", pricingVersion: cat.version };
2445
2484
  let { resolvedModel, pricing, normalized } = resolved, costStatus = normalized ? "estimated" : "exact", unit, matchedTierIndex;
2446
2485
  if (pricing.tiers && pricing.tiers.length > 0) {
2447
- let totalIn = tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens, { tier, index } = selectTier(pricing.tiers, totalIn);
2448
- unit = tier, matchedTierIndex = index;
2486
+ let totalIn = tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens, { tier: tier2, index } = selectTier(pricing.tiers, totalIn);
2487
+ unit = tier2, matchedTierIndex = index;
2449
2488
  } else
2450
2489
  unit = {
2451
2490
  input_per_million: pricing.input_per_million ?? 0,
@@ -2456,7 +2495,7 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2456
2495
  };
2457
2496
  let cw5Rate = unit.cache_write_5m_per_million ?? pricing.cache_write_5m_per_million ?? 0, cw1hRate = unit.cache_write_1h_per_million ?? pricing.cache_write_1h_per_million ?? 0, cachedRate = unit.cached_input_per_million ?? pricing.cached_input_per_million ?? 0, raw = tokens.inputTokens / 1e6 * (unit.input_per_million ?? 0) + tokens.cachedInputTokens / 1e6 * (cachedRate ?? 0) + (tokens.cacheWrite5mTokens ?? tokens.cacheWriteTokens) / 1e6 * cw5Rate + (tokens.cacheWrite1hTokens ?? 0) / 1e6 * cw1hRate + tokens.outputTokens / 1e6 * (unit.output_per_million ?? 0);
2458
2497
  raw = toUsd(raw, pricing.currency, cat);
2459
- let finalCost = isFast && FAST_SUPPORTED.has(resolvedModel) ? raw * FAST_MULTIPLIER : raw;
2498
+ let finalCost = raw * getServiceTierMultiplier(provider, product, resolvedModel, tier);
2460
2499
  return {
2461
2500
  estimatedCostUsd: Math.round(finalCost * 1e4) / 1e4,
2462
2501
  costStatus,
@@ -2468,13 +2507,13 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2468
2507
 
2469
2508
  // src/report.ts
2470
2509
  async function buildLocalReport(range, options = {}) {
2471
- 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 });
2510
+ let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(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 });
2472
2511
  for (let result of results) {
2473
2512
  let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
2474
2513
  if (hasData) {
2475
2514
  daysWithData += 1;
2476
2515
  for (let breakdown of result.breakdowns) {
2477
- let breakdownTotals = toBreakdownTotals(breakdown, pricingWarnings);
2516
+ let breakdownTotals = toBreakdownTotals(breakdown, pricingWarnings, options.pricingCatalog);
2478
2517
  dayTotals.estimatedCostUsd += breakdownTotals.estimatedCostUsd, mergeTotals(totals, breakdownTotals), mergeTotals(getOrCreate(bySource, `${breakdown.provider}/${breakdown.product}`), breakdownTotals), mergeTotals(
2479
2518
  getOrCreate(byModel, `${breakdown.provider}/${breakdown.product}|${breakdown.model}`),
2480
2519
  breakdownTotals
@@ -2498,6 +2537,10 @@ async function buildLocalReport(range, options = {}) {
2498
2537
  let [source, model] = key.split("|");
2499
2538
  return { source, model, ...summary };
2500
2539
  }).sort((a, b) => b.estimatedCostUsd - a.estimatedCostUsd || b.totalTokens - a.totalTokens),
2540
+ pricing: options.pricingInfo ?? {
2541
+ source: "bundled",
2542
+ version: options.pricingCatalog?.version ?? "bundled"
2543
+ },
2501
2544
  pricingWarnings: [...pricingWarnings].sort()
2502
2545
  };
2503
2546
  }
@@ -2525,7 +2568,7 @@ function buildPresetDates(range) {
2525
2568
  let days = range === "7d" ? 7 : range === "1m" ? 30 : 90, today = getTodayLocalDate(), result = [];
2526
2569
  for (let offset = days - 1; offset >= 0; offset -= 1) {
2527
2570
  let day = new Date(today);
2528
- day.setDate(today.getDate() - offset), result.push(toDateKey3(day));
2571
+ day.setDate(today.getDate() - offset), result.push(dateKey(day));
2529
2572
  }
2530
2573
  return result;
2531
2574
  }
@@ -2561,8 +2604,8 @@ async function discoverGenericJsonlDates(baseDir, dates) {
2561
2604
  } catch {
2562
2605
  continue;
2563
2606
  }
2564
- let ts = parseTimestamp3(record.timestamp);
2565
- ts && dates.add(toDateKey3(ts));
2607
+ let ts = parseTs(record.timestamp);
2608
+ ts && dates.add(dateKey(ts));
2566
2609
  }
2567
2610
  }
2568
2611
  }
@@ -2578,13 +2621,13 @@ async function discoverGenericJsonDates(baseDir, dates) {
2578
2621
  } catch {
2579
2622
  continue;
2580
2623
  }
2581
- let topTs = parseTimestamp3(data.timestamp ?? data.createTime);
2582
- topTs && dates.add(toDateKey3(topTs));
2624
+ let topTs = parseTs(data.timestamp ?? data.createTime);
2625
+ topTs && dates.add(dateKey(topTs));
2583
2626
  let msgs2 = data.messages ?? data.history ?? [];
2584
2627
  if (Array.isArray(msgs2))
2585
2628
  for (let msg of msgs2) {
2586
- let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
2587
- ts && dates.add(toDateKey3(ts));
2629
+ let ts = parseTs(msg.timestamp ?? msg.createTime);
2630
+ ts && dates.add(dateKey(ts));
2588
2631
  }
2589
2632
  }
2590
2633
  }
@@ -2614,13 +2657,13 @@ async function discoverGeminiDates(dates) {
2614
2657
  }
2615
2658
  if (Array.isArray(session)) {
2616
2659
  for (let row of session) {
2617
- let ts = parseTimestamp3(row.timestamp);
2618
- ts && dates.add(toDateKey3(ts));
2660
+ let ts = parseTs(row.timestamp);
2661
+ ts && dates.add(dateKey(ts));
2619
2662
  }
2620
2663
  continue;
2621
2664
  }
2622
- let topLevelTs = parseTimestamp3(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
2623
- topLevelTs && dates.add(toDateKey3(topLevelTs));
2665
+ let topLevelTs = parseTs(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
2666
+ topLevelTs && dates.add(dateKey(topLevelTs));
2624
2667
  let messages = [
2625
2668
  ...session.messages ?? [],
2626
2669
  ...session.history ?? [],
@@ -2628,8 +2671,8 @@ async function discoverGeminiDates(dates) {
2628
2671
  ...session.data?.history ?? []
2629
2672
  ];
2630
2673
  for (let msg of messages) {
2631
- let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
2632
- ts && dates.add(toDateKey3(ts));
2674
+ let ts = parseTs(msg.timestamp ?? msg.createTime);
2675
+ ts && dates.add(dateKey(ts));
2633
2676
  }
2634
2677
  }
2635
2678
  }
@@ -2655,8 +2698,8 @@ async function discoverCopilotVscodeDates(dates) {
2655
2698
  for (let line of content.split(`
2656
2699
  `)) {
2657
2700
  if (!line.includes("ccreq:") || !line.includes("| success |")) continue;
2658
- let ts = parseTimestamp3(line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/)?.[1]?.replace(" ", "T"));
2659
- ts && dates.add(toDateKey3(ts));
2701
+ let ts = parseTs(line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/)?.[1]?.replace(" ", "T"));
2702
+ ts && dates.add(dateKey(ts));
2660
2703
  }
2661
2704
  }
2662
2705
  let sessionFiles = [];
@@ -2673,8 +2716,8 @@ async function discoverCopilotVscodeDates(dates) {
2673
2716
  }
2674
2717
  for (let request of session.requests ?? []) {
2675
2718
  if ((request.response?.length ?? 0) === 0 || request.result?.errorDetails?.responseIsIncomplete) continue;
2676
- let ts = parseTimestamp3(request.timestamp);
2677
- ts && dates.add(toDateKey3(ts));
2719
+ let ts = parseTs(request.timestamp);
2720
+ ts && dates.add(dateKey(ts));
2678
2721
  }
2679
2722
  }
2680
2723
  }
@@ -2691,8 +2734,8 @@ async function discoverAntigravityDates(dates) {
2691
2734
  } catch {
2692
2735
  continue;
2693
2736
  }
2694
- let ts = parseTimestamp3(data.updatedAt);
2695
- ts && dates.add(toDateKey3(ts));
2737
+ let ts = parseTs(data.updatedAt);
2738
+ ts && dates.add(dateKey(ts));
2696
2739
  }
2697
2740
  for (let filePath of browserFiles) {
2698
2741
  if (basename8(filePath) !== "metadata.json") continue;
@@ -2704,8 +2747,8 @@ async function discoverAntigravityDates(dates) {
2704
2747
  } catch {
2705
2748
  continue;
2706
2749
  }
2707
- let ts = parseTimestamp3(data.highlights?.[0]?.start_time ?? data.highlights?.[0]?.end_time);
2708
- ts && dates.add(toDateKey3(ts));
2750
+ let ts = parseTs(data.highlights?.[0]?.start_time ?? data.highlights?.[0]?.end_time);
2751
+ ts && dates.add(dateKey(ts));
2709
2752
  }
2710
2753
  }
2711
2754
  async function discoverClaudeDates(dates) {
@@ -2739,8 +2782,8 @@ async function discoverClaudeDates(dates) {
2739
2782
  } catch {
2740
2783
  continue;
2741
2784
  }
2742
- let ts = parseTimestamp3(record.timestamp);
2743
- ts && dates.add(toDateKey3(ts));
2785
+ let ts = parseTs(record.timestamp);
2786
+ ts && dates.add(dateKey(ts));
2744
2787
  }
2745
2788
  }
2746
2789
  }
@@ -2761,8 +2804,8 @@ async function discoverCodexDates(dates) {
2761
2804
  continue;
2762
2805
  }
2763
2806
  if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
2764
- let ts = parseTimestamp3(record.timestamp);
2765
- ts && dates.add(toDateKey3(ts));
2807
+ let ts = parseTs(record.timestamp);
2808
+ ts && dates.add(dateKey(ts));
2766
2809
  }
2767
2810
  }
2768
2811
  }
@@ -2797,24 +2840,15 @@ async function walkForCodexJsonl(dir, result) {
2797
2840
  }
2798
2841
  async function safeReadUtf8(filePath) {
2799
2842
  try {
2800
- return await readFile13(filePath, "utf-8");
2843
+ return await readFile14(filePath, "utf-8");
2801
2844
  } catch {
2802
2845
  return null;
2803
2846
  }
2804
2847
  }
2805
- function parseTimestamp3(value) {
2806
- if (value == null || value === "") return null;
2807
- let date = new Date(value);
2808
- return Number.isNaN(date.getTime()) ? null : date;
2809
- }
2810
2848
  function getTodayLocalDate() {
2811
2849
  let now = /* @__PURE__ */ new Date();
2812
2850
  return new Date(now.getFullYear(), now.getMonth(), now.getDate());
2813
2851
  }
2814
- function toDateKey3(date) {
2815
- let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
2816
- return `${year}-${month}-${day}`;
2817
- }
2818
2852
  function getOrCreate(map, key) {
2819
2853
  let existing = map.get(key);
2820
2854
  if (existing) return existing;
@@ -2843,8 +2877,8 @@ function createEmptyTotals2() {
2843
2877
  function mergeTotals(target, source) {
2844
2878
  return target.eventCount += source.eventCount, target.inputTokens += source.inputTokens, target.cachedInputTokens += source.cachedInputTokens, target.cacheWriteTokens += source.cacheWriteTokens, target.outputTokens += source.outputTokens, target.reasoningOutputTokens += source.reasoningOutputTokens, target.totalTokens += source.totalTokens, target.estimatedCostUsd += source.estimatedCostUsd, target;
2845
2879
  }
2846
- function toBreakdownTotals(breakdown, warnings) {
2847
- let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings);
2880
+ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
2881
+ let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings, pricingCatalog);
2848
2882
  return {
2849
2883
  eventCount: breakdown.eventCount,
2850
2884
  inputTokens: breakdown.inputTokens,
@@ -2856,7 +2890,7 @@ function toBreakdownTotals(breakdown, warnings) {
2856
2890
  estimatedCostUsd
2857
2891
  };
2858
2892
  }
2859
- function calculateBreakdownCost(breakdown, warnings) {
2893
+ function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2860
2894
  if (breakdown.costUSD != null && breakdown.costUSD > 0)
2861
2895
  return breakdown.costUSD;
2862
2896
  let result = calculateCost(
@@ -2870,7 +2904,8 @@ function calculateBreakdownCost(breakdown, warnings) {
2870
2904
  cacheWrite5mTokens: breakdown.cacheWrite5mTokens,
2871
2905
  cacheWrite1hTokens: breakdown.cacheWrite1hTokens,
2872
2906
  outputTokens: breakdown.outputTokens
2873
- }
2907
+ },
2908
+ pricingCatalog ? { catalog: pricingCatalog } : {}
2874
2909
  );
2875
2910
  return result.costStatus === "unavailable" ? warnings.add(`${breakdown.provider}/${breakdown.product}/${breakdown.model} \u6682\u65E0\u5B9A\u4EF7\u914D\u7F6E\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`) : result.costStatus === "estimated" && result.resolvedModel && result.resolvedModel !== breakdown.model && warnings.add(`${breakdown.model} \u5DF2\u6309 ${result.resolvedModel} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`), result.estimatedCostUsd;
2876
2911
  }
@@ -2882,6 +2917,7 @@ var en = {
2882
2917
  events: "Events",
2883
2918
  tokens: "Tokens",
2884
2919
  cost: "Cost",
2920
+ pricing: "Pricing",
2885
2921
  sources: "Sources",
2886
2922
  daily: "Daily",
2887
2923
  topModels: "Top Models",
@@ -2910,6 +2946,7 @@ var en = {
2910
2946
  events: "\u4E8B\u4EF6",
2911
2947
  tokens: "\u4EE4\u724C",
2912
2948
  cost: "\u8D39\u7528",
2949
+ pricing: "\u5B9A\u4EF7",
2913
2950
  sources: "\u6765\u6E90",
2914
2951
  daily: "\u6BCF\u65E5",
2915
2952
  topModels: "\u6A21\u578B\u6392\u884C",
@@ -2942,7 +2979,7 @@ function renderReport(report, opts) {
2942
2979
  let s = t(opts.lang), lines = [], title = opts.emoji ? `\u{1F4CA} ${s.reportTitle}` : s.reportTitle;
2943
2980
  lines.push(title), lines.push("\u2500".repeat(title.length));
2944
2981
  let rangeLabel = getRangeLabel2(report.range, opts.lang), periodStart = report.startDate ? fmtDateShort(report.startDate) : "-", periodEnd = report.endDate ? fmtDateShort(report.endDate) : "-";
2945
- if (lines.push(`${s.period.padEnd(10)}${rangeLabel} (${periodStart} \u2013 ${periodEnd})`), lines.push(`${s.events.padEnd(10)}${fmtInt(report.totals.eventCount)}`), lines.push(`${s.tokens.padEnd(10)}${fmtToken(report.totals.totalTokens)}`), lines.push(`${s.cost.padEnd(10)}${fmtUsd(report.totals.estimatedCostUsd, opts.detail)}`), report.daysWithData === 0)
2982
+ if (lines.push(`${s.period.padEnd(10)}${rangeLabel} (${periodStart} \u2013 ${periodEnd})`), lines.push(`${s.events.padEnd(10)}${fmtInt(report.totals.eventCount)}`), lines.push(`${s.tokens.padEnd(10)}${fmtToken(report.totals.totalTokens)}`), lines.push(`${s.cost.padEnd(10)}${fmtUsd(report.totals.estimatedCostUsd, opts.detail)}`), lines.push(`${s.pricing.padEnd(10)}${formatPricing(report.pricing)}`), report.daysWithData === 0)
2946
2983
  return lines.push(""), lines.push(s.noData), lines.join(`
2947
2984
  `);
2948
2985
  if (lines.push(""), lines.push(s.sources), opts.detail ? lines.push(renderTable(
@@ -3034,6 +3071,9 @@ function getRangeLabel2(range, lang) {
3034
3071
  return range;
3035
3072
  }
3036
3073
  }
3074
+ function formatPricing(pricing) {
3075
+ return `${pricing.source === "remote" ? "remote" : pricing.source === "cache" ? "cache" : "bundled"} ${pricing.version}`;
3076
+ }
3037
3077
  function displayWidth(str) {
3038
3078
  let w = 0;
3039
3079
  for (let ch of str) {
@@ -3080,7 +3120,7 @@ function fmtDateShort(dateStr) {
3080
3120
  }
3081
3121
 
3082
3122
  // src/config.ts
3083
- import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
3123
+ import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
3084
3124
  import { homedir as homedir15, hostname } from "node:os";
3085
3125
  import { basename as basename9, join as join15 } from "node:path";
3086
3126
  var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
@@ -3102,6 +3142,7 @@ function migrateConfig(config) {
3102
3142
  lookbackDays: config.lookbackDays,
3103
3143
  projectAliases: config.projectAliases,
3104
3144
  privacy: config.privacy,
3145
+ pricing: config.pricing,
3105
3146
  lang: config.lang,
3106
3147
  emoji: config.emoji,
3107
3148
  targets: [target]
@@ -3109,7 +3150,7 @@ function migrateConfig(config) {
3109
3150
  }
3110
3151
  async function readConfig() {
3111
3152
  try {
3112
- let raw = await readFile14(CONFIG_PATH, "utf-8");
3153
+ let raw = await readFile15(CONFIG_PATH, "utf-8");
3113
3154
  return migrateConfig(JSON.parse(raw));
3114
3155
  } catch {
3115
3156
  return {};
@@ -3158,6 +3199,21 @@ function setConfigValue(config, keyPath, values) {
3158
3199
  throw new Error("privacy.projectVisibility \u4EC5\u652F\u6301 hidden\u3001masked\u3001plain");
3159
3200
  return next.privacy = { ...next.privacy ?? {}, projectVisibility: value }, next;
3160
3201
  }
3202
+ if (keyPath === "pricing.mode") {
3203
+ let value = requireSingleValue(keyPath, values);
3204
+ if (value !== "auto" && value !== "manual" && value !== "offline")
3205
+ throw new Error("pricing.mode \u4EC5\u652F\u6301 auto\u3001manual\u3001offline");
3206
+ return next.pricing = { ...next.pricing ?? {}, mode: value }, next;
3207
+ }
3208
+ if (keyPath === "pricing.url") {
3209
+ let value = requireSingleValue(keyPath, values);
3210
+ return next.pricing = { ...next.pricing ?? {} }, value === "default" || value === "none" || value === "off" ? delete next.pricing.url : next.pricing.url = normalizeServerUrl(value), next;
3211
+ }
3212
+ if (keyPath === "pricing.cacheTtlHours")
3213
+ return next.pricing = {
3214
+ ...next.pricing ?? {},
3215
+ cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
3216
+ }, next;
3161
3217
  if (keyPath === "project.alias") {
3162
3218
  if (values.length < 2)
3163
3219
  throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
@@ -3281,7 +3337,7 @@ async function requestJson(url, init) {
3281
3337
  }
3282
3338
 
3283
3339
  // src/schedule.ts
3284
- import { mkdir as mkdir2, readFile as readFile15, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
3340
+ import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
3285
3341
  import { execFile } from "node:child_process";
3286
3342
  import { promisify } from "node:util";
3287
3343
  import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
@@ -3385,7 +3441,7 @@ async function getLaunchdStatus() {
3385
3441
  return { enabled: !1 };
3386
3442
  }
3387
3443
  try {
3388
- 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];
3444
+ let content = await readFile16(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];
3389
3445
  return {
3390
3446
  enabled: !0,
3391
3447
  interval,
@@ -3618,7 +3674,7 @@ async function runDoctor(lang = "zh") {
3618
3674
  }
3619
3675
 
3620
3676
  // src/project.ts
3621
- import { open as open3, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
3677
+ import { open as open3, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
3622
3678
  import { basename as basename10, join as join18 } from "node:path";
3623
3679
  import { homedir as homedir18 } from "node:os";
3624
3680
  async function discoverProjects(projectAliases) {
@@ -3791,7 +3847,7 @@ async function discoverCopilotProjects() {
3791
3847
  async function discoverGeminiProjects() {
3792
3848
  let filePath = join18(homedir18(), ".gemini", "projects.json");
3793
3849
  try {
3794
- let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
3850
+ let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
3795
3851
  if (!projects || typeof projects != "object") return [];
3796
3852
  let names = [];
3797
3853
  for (let [path, _name] of Object.entries(projects)) {
@@ -3806,7 +3862,7 @@ async function discoverGeminiProjects() {
3806
3862
  async function discoverCursorProjects() {
3807
3863
  let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
3808
3864
  try {
3809
- let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
3865
+ let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
3810
3866
  for (let uri of workspaceUris) {
3811
3867
  let name = nameFromFileUri(uri);
3812
3868
  name && projects.add(name);
@@ -3825,7 +3881,7 @@ async function discoverCopilotVscodeProjects() {
3825
3881
  for (let filePath of files) {
3826
3882
  let content;
3827
3883
  try {
3828
- content = await readFile16(filePath, "utf-8");
3884
+ content = await readFile17(filePath, "utf-8");
3829
3885
  } catch {
3830
3886
  continue;
3831
3887
  }
@@ -3849,7 +3905,7 @@ async function discoverAntigravityProjects() {
3849
3905
  if (!entry.isDirectory()) continue;
3850
3906
  let metadataPath = join18(dir, entry.name, "metadata.json");
3851
3907
  try {
3852
- let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3908
+ let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3853
3909
  name && name !== "unknown" && projects.add(name);
3854
3910
  } catch {
3855
3911
  continue;
@@ -3924,6 +3980,106 @@ function shortHash(p) {
3924
3980
  return p ? createHash("sha1").update(p).digest("hex").slice(0, 8) : "00000000";
3925
3981
  }
3926
3982
 
3983
+ // src/pricing.ts
3984
+ import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
3985
+ import { homedir as homedir19 } from "node:os";
3986
+ import { join as join19 } from "node:path";
3987
+ var CACHE_DIR = join19(homedir19(), ".aiusage"), CACHE_PATH = join19(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
3988
+ "https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
3989
+ "https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
3990
+ "https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
3991
+ "https://unpkg.com/@aiusage/pricing@latest/catalog.json"
3992
+ ];
3993
+ async function resolvePricingCatalog(config, options = {}) {
3994
+ let mode = config.pricing?.mode ?? "auto", cache = await readPricingCache(), ttlHours = config.pricing?.cacheTtlHours ?? DEFAULT_CACHE_TTL_HOURS;
3995
+ if (!options.forceRefresh && cache && (mode === "manual" || mode === "offline" || isCacheFresh(cache, ttlHours)))
3996
+ return fromCache(cache);
3997
+ if ((mode !== "offline" || options.forceRefresh) && (mode === "auto" || options.forceRefresh)) {
3998
+ let candidates = getPricingUrls(config, options);
3999
+ for (let url of candidates)
4000
+ try {
4001
+ let catalog2 = await fetchPricingCatalog(url), fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
4002
+ return await writePricingCache({ fetchedAt, sourceUrl: url, catalog: catalog2 }), {
4003
+ catalog: catalog2,
4004
+ info: { source: "remote", version: catalog2.version, url, fetchedAt }
4005
+ };
4006
+ } catch {
4007
+ }
4008
+ }
4009
+ return cache ? fromCache(cache) : {
4010
+ catalog,
4011
+ info: { source: "bundled", version: catalog.version }
4012
+ };
4013
+ }
4014
+ async function getPricingStatus(config) {
4015
+ let cache = await readPricingCache();
4016
+ return {
4017
+ mode: config.pricing?.mode ?? "auto",
4018
+ configuredUrl: config.pricing?.url,
4019
+ cachePath: CACHE_PATH,
4020
+ cache: cache ? {
4021
+ version: cache.catalog.version,
4022
+ sourceUrl: cache.sourceUrl,
4023
+ fetchedAt: cache.fetchedAt
4024
+ } : void 0,
4025
+ bundled: {
4026
+ version: catalog.version
4027
+ }
4028
+ };
4029
+ }
4030
+ function getPricingUrls(config, options) {
4031
+ let urls = [
4032
+ options.explicitUrl,
4033
+ config.pricing?.url,
4034
+ options.target?.apiBaseUrl ? `${options.target.apiBaseUrl}/api/v1/public/pricing` : void 0,
4035
+ ...NPM_CDN_URLS
4036
+ ].filter((url) => !!url);
4037
+ return [...new Set(urls.map((url) => url.trim()).filter(Boolean))];
4038
+ }
4039
+ function isCacheFresh(cache, ttlHours) {
4040
+ let fetched = new Date(cache.fetchedAt).getTime();
4041
+ return Number.isFinite(fetched) ? Date.now() - fetched < ttlHours * 60 * 60 * 1e3 : !1;
4042
+ }
4043
+ function fromCache(cache) {
4044
+ return {
4045
+ catalog: cache.catalog,
4046
+ info: {
4047
+ source: "cache",
4048
+ version: cache.catalog.version,
4049
+ url: cache.sourceUrl,
4050
+ fetchedAt: cache.fetchedAt
4051
+ }
4052
+ };
4053
+ }
4054
+ async function readPricingCache() {
4055
+ try {
4056
+ let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
4057
+ return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
4058
+ } catch {
4059
+ return null;
4060
+ }
4061
+ }
4062
+ async function writePricingCache(cache) {
4063
+ await mkdir3(CACHE_DIR, { recursive: !0 }), await writeFile3(CACHE_PATH, `${JSON.stringify(cache, null, 2)}
4064
+ `, "utf-8");
4065
+ }
4066
+ async function fetchPricingCatalog(url) {
4067
+ let response = await fetch(url, {
4068
+ headers: { Accept: "application/json" },
4069
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
4070
+ });
4071
+ if (!response.ok) throw new Error(`pricing fetch failed: ${response.status}`);
4072
+ let data = await response.json();
4073
+ return assertPricingCatalog(data), data;
4074
+ }
4075
+ function assertPricingCatalog(value) {
4076
+ let catalog2 = value;
4077
+ if (!catalog2 || typeof catalog2 != "object") throw new Error("invalid pricing catalog");
4078
+ if (!catalog2.version || typeof catalog2.version != "string") throw new Error("invalid pricing catalog version");
4079
+ if (!catalog2.providers || typeof catalog2.providers != "object") throw new Error("invalid pricing catalog providers");
4080
+ if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
4081
+ }
4082
+
3927
4083
  // src/cli.ts
3928
4084
  var argv = process.argv.slice(2), command = argv[0];
3929
4085
  await (async () => {
@@ -3974,6 +4130,17 @@ await (async () => {
3974
4130
  let parsed = parseArgs(argv.slice(1));
3975
4131
  if (parsed.flags.help) return helpForSubcommand("doctor");
3976
4132
  await runDoctorCommand(parsed.flags);
4133
+ } else if (command === "pricing") {
4134
+ let sub = argv[1], parsed = parseArgs(argv.slice(2));
4135
+ if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("pricing");
4136
+ if (sub === "update")
4137
+ await runPricingUpdate(parsed.flags);
4138
+ else if (sub === "status" || sub === void 0)
4139
+ await runPricingStatus(parsed.flags);
4140
+ else {
4141
+ let zh2 = (await readConfig()).lang === "zh";
4142
+ throw new Error(`${zh2 ? "\u672A\u77E5\u5B50\u547D\u4EE4" : "Unknown subcommand"}: pricing ${sub}`);
4143
+ }
3977
4144
  } else if (command === "config" && argv[1] === "set")
3978
4145
  await runConfigSet(argv.slice(2));
3979
4146
  else if (command === "project") {
@@ -4053,7 +4220,15 @@ function printScanResult(result, zh2) {
4053
4220
  async function runReport(flags, positionals = []) {
4054
4221
  let config = await readConfig();
4055
4222
  assertNoPositionals("report", positionals, config.lang === "zh");
4056
- let { dates, range } = resolveDateParams(flags, config), report = await buildLocalReport(range, { projectAliases: config.projectAliases, dates });
4223
+ let { dates, range } = resolveDateParams(flags, config), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
4224
+ explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
4225
+ target: pricingTarget
4226
+ }), report = await buildLocalReport(range, {
4227
+ projectAliases: config.projectAliases,
4228
+ dates,
4229
+ pricingCatalog: pricing.catalog,
4230
+ pricingInfo: pricing.info
4231
+ });
4057
4232
  if (flags.json) {
4058
4233
  console.log(JSON.stringify(report, null, 2));
4059
4234
  return;
@@ -4252,6 +4427,25 @@ async function runDoctorCommand(flags) {
4252
4427
  }
4253
4428
  checks.filter((c) => c.status === "fail").length > 0 && (process.exitCode = 1);
4254
4429
  }
4430
+ async function runPricingStatus(flags) {
4431
+ let config = await readConfig(), status = await getPricingStatus(config);
4432
+ if (flags.json) {
4433
+ console.log(JSON.stringify(status, null, 2));
4434
+ return;
4435
+ }
4436
+ console.log(`\u6A21\u5F0F: ${status.mode}`), status.configuredUrl && console.log(`\u914D\u7F6E\u6E90: ${status.configuredUrl}`), console.log(`\u7F13\u5B58: ${status.cachePath}`), status.cache ? (console.log(`\u7F13\u5B58\u7248\u672C: ${status.cache.version}`), console.log(`\u7F13\u5B58\u6765\u6E90: ${status.cache.sourceUrl}`), console.log(`\u7F13\u5B58\u65F6\u95F4: ${status.cache.fetchedAt}`)) : console.log("\u7F13\u5B58\u7248\u672C: (\u65E0)"), console.log(`\u5185\u7F6E\u7248\u672C: ${status.bundled.version}`);
4437
+ }
4438
+ async function runPricingUpdate(flags) {
4439
+ let config = await readConfig(), targetName = resolveOptionalString(flags.target, void 0), target = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
4440
+ forceRefresh: !0,
4441
+ explicitUrl: resolveOptionalString(flags.url, void 0),
4442
+ target
4443
+ });
4444
+ console.log(JSON.stringify({
4445
+ cachePath: (await getPricingStatus(config)).cachePath,
4446
+ pricing: pricing.info
4447
+ }, null, 2));
4448
+ }
4255
4449
  async function runConfigSet(args) {
4256
4450
  let [keyPath, ...values] = args;
4257
4451
  if (!keyPath) throw new Error("config set \u7F3A\u5C11\u914D\u7F6E\u9879");
@@ -4314,6 +4508,7 @@ function printHelp(zh2 = !1) {
4314
4508
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4315
4509
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
4316
4510
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
4511
+ ["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
4317
4512
  ["schedule [on|off|status] [--every 5m]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
4318
4513
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
4319
4514
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"],
@@ -4326,6 +4521,7 @@ function printHelp(zh2 = !1) {
4326
4521
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4327
4522
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
4328
4523
  ["project [list|alias]", "Project management & aliases"],
4524
+ ["pricing [status|update] [--url URL]", "Pricing catalog management"],
4329
4525
  ["schedule [on|off|status] [--every 5m]", "Scheduled sync management"],
4330
4526
  ["doctor", "Run diagnostics"],
4331
4527
  ["config set <key> <value>", "Update config"],
@@ -4346,6 +4542,7 @@ function printUsageHint(zh2 = !1) {
4346
4542
  ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
4347
4543
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4348
4544
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
4545
+ ["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
4349
4546
  ["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
4350
4547
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
4351
4548
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
@@ -4354,6 +4551,7 @@ function printUsageHint(zh2 = !1) {
4354
4551
  ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
4355
4552
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4356
4553
  ["project [list|alias]", "Project management & aliases"],
4554
+ ["pricing [status|update]", "Pricing catalog management"],
4357
4555
  ["schedule [on|off|status]", "Scheduled sync management"],
4358
4556
  ["doctor", "Run diagnostics"],
4359
4557
  ["config set <key> <value>", "Update config"]