@aiusage/cli 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof
7
7
  });
8
8
 
9
9
  // src/cli.ts
10
- import { createInterface as createInterface3 } from "node:readline";
10
+ import { createInterface as createInterface4 } from "node:readline";
11
11
  import { hostname as hostname3 } from "node:os";
12
12
 
13
13
  // src/scanners/antigravity.ts
@@ -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
 
@@ -2378,7 +2399,7 @@ var inflection = {
2378
2399
  };
2379
2400
 
2380
2401
  // ../shared/src/pricing/catalog.ts
2381
- var PRICING_VERSION = "2026-05-29-unified-v1", aliases = {
2402
+ var PRICING_VERSION = "2026-06-22-codex-tier-v1", aliases = {
2382
2403
  "claude-opus-4-7-20260201": "claude-opus-4-7",
2383
2404
  "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
2384
2405
  "claude-opus-4-6-20250301": "claude-opus-4-6",
@@ -2410,11 +2431,20 @@ var PRICING_VERSION = "2026-05-29-unified-v1", aliases = {
2410
2431
  };
2411
2432
 
2412
2433
  // ../shared/src/pricing/calculate.ts
2413
- var FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
2434
+ var ANTHROPIC_FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
2414
2435
  "claude-opus-4-8",
2415
2436
  "claude-opus-4-7",
2416
2437
  "claude-opus-4-6"
2417
- ]);
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
+ }
2418
2448
  function resolveModelPricing(catalog2, provider, product, model) {
2419
2449
  let models = catalog2.providers[provider]?.[product]?.models;
2420
2450
  if (!models) return null;
@@ -2448,13 +2478,13 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2448
2478
  let cat = options.catalog ?? catalog;
2449
2479
  if (tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens + tokens.outputTokens === 0)
2450
2480
  return { estimatedCostUsd: 0, costStatus: "exact", pricingVersion: cat.version };
2451
- 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);
2452
2482
  if (!resolved)
2453
2483
  return { estimatedCostUsd: 0, costStatus: "unavailable", pricingVersion: cat.version };
2454
2484
  let { resolvedModel, pricing, normalized } = resolved, costStatus = normalized ? "estimated" : "exact", unit, matchedTierIndex;
2455
2485
  if (pricing.tiers && pricing.tiers.length > 0) {
2456
- let totalIn = tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens, { tier, index } = selectTier(pricing.tiers, totalIn);
2457
- 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;
2458
2488
  } else
2459
2489
  unit = {
2460
2490
  input_per_million: pricing.input_per_million ?? 0,
@@ -2465,7 +2495,7 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2465
2495
  };
2466
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);
2467
2497
  raw = toUsd(raw, pricing.currency, cat);
2468
- let finalCost = isFast && FAST_SUPPORTED.has(resolvedModel) ? raw * FAST_MULTIPLIER : raw;
2498
+ let finalCost = raw * getServiceTierMultiplier(provider, product, resolvedModel, tier);
2469
2499
  return {
2470
2500
  estimatedCostUsd: Math.round(finalCost * 1e4) / 1e4,
2471
2501
  costStatus,
@@ -2477,13 +2507,13 @@ function calculateCost(provider, product, model, tokens, options = {}) {
2477
2507
 
2478
2508
  // src/report.ts
2479
2509
  async function buildLocalReport(range, options = {}) {
2480
- 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 });
2481
2511
  for (let result of results) {
2482
2512
  let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
2483
2513
  if (hasData) {
2484
2514
  daysWithData += 1;
2485
2515
  for (let breakdown of result.breakdowns) {
2486
- let breakdownTotals = toBreakdownTotals(breakdown, pricingWarnings);
2516
+ let breakdownTotals = toBreakdownTotals(breakdown, pricingWarnings, options.pricingCatalog);
2487
2517
  dayTotals.estimatedCostUsd += breakdownTotals.estimatedCostUsd, mergeTotals(totals, breakdownTotals), mergeTotals(getOrCreate(bySource, `${breakdown.provider}/${breakdown.product}`), breakdownTotals), mergeTotals(
2488
2518
  getOrCreate(byModel, `${breakdown.provider}/${breakdown.product}|${breakdown.model}`),
2489
2519
  breakdownTotals
@@ -2507,6 +2537,10 @@ async function buildLocalReport(range, options = {}) {
2507
2537
  let [source, model] = key.split("|");
2508
2538
  return { source, model, ...summary };
2509
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
+ },
2510
2544
  pricingWarnings: [...pricingWarnings].sort()
2511
2545
  };
2512
2546
  }
@@ -2534,7 +2568,7 @@ function buildPresetDates(range) {
2534
2568
  let days = range === "7d" ? 7 : range === "1m" ? 30 : 90, today = getTodayLocalDate(), result = [];
2535
2569
  for (let offset = days - 1; offset >= 0; offset -= 1) {
2536
2570
  let day = new Date(today);
2537
- day.setDate(today.getDate() - offset), result.push(toDateKey3(day));
2571
+ day.setDate(today.getDate() - offset), result.push(dateKey(day));
2538
2572
  }
2539
2573
  return result;
2540
2574
  }
@@ -2570,8 +2604,8 @@ async function discoverGenericJsonlDates(baseDir, dates) {
2570
2604
  } catch {
2571
2605
  continue;
2572
2606
  }
2573
- let ts = parseTimestamp3(record.timestamp);
2574
- ts && dates.add(toDateKey3(ts));
2607
+ let ts = parseTs(record.timestamp);
2608
+ ts && dates.add(dateKey(ts));
2575
2609
  }
2576
2610
  }
2577
2611
  }
@@ -2587,13 +2621,13 @@ async function discoverGenericJsonDates(baseDir, dates) {
2587
2621
  } catch {
2588
2622
  continue;
2589
2623
  }
2590
- let topTs = parseTimestamp3(data.timestamp ?? data.createTime);
2591
- topTs && dates.add(toDateKey3(topTs));
2624
+ let topTs = parseTs(data.timestamp ?? data.createTime);
2625
+ topTs && dates.add(dateKey(topTs));
2592
2626
  let msgs2 = data.messages ?? data.history ?? [];
2593
2627
  if (Array.isArray(msgs2))
2594
2628
  for (let msg of msgs2) {
2595
- let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
2596
- ts && dates.add(toDateKey3(ts));
2629
+ let ts = parseTs(msg.timestamp ?? msg.createTime);
2630
+ ts && dates.add(dateKey(ts));
2597
2631
  }
2598
2632
  }
2599
2633
  }
@@ -2623,13 +2657,13 @@ async function discoverGeminiDates(dates) {
2623
2657
  }
2624
2658
  if (Array.isArray(session)) {
2625
2659
  for (let row of session) {
2626
- let ts = parseTimestamp3(row.timestamp);
2627
- ts && dates.add(toDateKey3(ts));
2660
+ let ts = parseTs(row.timestamp);
2661
+ ts && dates.add(dateKey(ts));
2628
2662
  }
2629
2663
  continue;
2630
2664
  }
2631
- let topLevelTs = parseTimestamp3(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
2632
- topLevelTs && dates.add(toDateKey3(topLevelTs));
2665
+ let topLevelTs = parseTs(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
2666
+ topLevelTs && dates.add(dateKey(topLevelTs));
2633
2667
  let messages = [
2634
2668
  ...session.messages ?? [],
2635
2669
  ...session.history ?? [],
@@ -2637,8 +2671,8 @@ async function discoverGeminiDates(dates) {
2637
2671
  ...session.data?.history ?? []
2638
2672
  ];
2639
2673
  for (let msg of messages) {
2640
- let ts = parseTimestamp3(msg.timestamp ?? msg.createTime);
2641
- ts && dates.add(toDateKey3(ts));
2674
+ let ts = parseTs(msg.timestamp ?? msg.createTime);
2675
+ ts && dates.add(dateKey(ts));
2642
2676
  }
2643
2677
  }
2644
2678
  }
@@ -2664,8 +2698,8 @@ async function discoverCopilotVscodeDates(dates) {
2664
2698
  for (let line of content.split(`
2665
2699
  `)) {
2666
2700
  if (!line.includes("ccreq:") || !line.includes("| success |")) continue;
2667
- let ts = parseTimestamp3(line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/)?.[1]?.replace(" ", "T"));
2668
- 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));
2669
2703
  }
2670
2704
  }
2671
2705
  let sessionFiles = [];
@@ -2682,8 +2716,8 @@ async function discoverCopilotVscodeDates(dates) {
2682
2716
  }
2683
2717
  for (let request of session.requests ?? []) {
2684
2718
  if ((request.response?.length ?? 0) === 0 || request.result?.errorDetails?.responseIsIncomplete) continue;
2685
- let ts = parseTimestamp3(request.timestamp);
2686
- ts && dates.add(toDateKey3(ts));
2719
+ let ts = parseTs(request.timestamp);
2720
+ ts && dates.add(dateKey(ts));
2687
2721
  }
2688
2722
  }
2689
2723
  }
@@ -2700,8 +2734,8 @@ async function discoverAntigravityDates(dates) {
2700
2734
  } catch {
2701
2735
  continue;
2702
2736
  }
2703
- let ts = parseTimestamp3(data.updatedAt);
2704
- ts && dates.add(toDateKey3(ts));
2737
+ let ts = parseTs(data.updatedAt);
2738
+ ts && dates.add(dateKey(ts));
2705
2739
  }
2706
2740
  for (let filePath of browserFiles) {
2707
2741
  if (basename8(filePath) !== "metadata.json") continue;
@@ -2713,8 +2747,8 @@ async function discoverAntigravityDates(dates) {
2713
2747
  } catch {
2714
2748
  continue;
2715
2749
  }
2716
- let ts = parseTimestamp3(data.highlights?.[0]?.start_time ?? data.highlights?.[0]?.end_time);
2717
- 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));
2718
2752
  }
2719
2753
  }
2720
2754
  async function discoverClaudeDates(dates) {
@@ -2748,8 +2782,8 @@ async function discoverClaudeDates(dates) {
2748
2782
  } catch {
2749
2783
  continue;
2750
2784
  }
2751
- let ts = parseTimestamp3(record.timestamp);
2752
- ts && dates.add(toDateKey3(ts));
2785
+ let ts = parseTs(record.timestamp);
2786
+ ts && dates.add(dateKey(ts));
2753
2787
  }
2754
2788
  }
2755
2789
  }
@@ -2770,8 +2804,8 @@ async function discoverCodexDates(dates) {
2770
2804
  continue;
2771
2805
  }
2772
2806
  if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
2773
- let ts = parseTimestamp3(record.timestamp);
2774
- ts && dates.add(toDateKey3(ts));
2807
+ let ts = parseTs(record.timestamp);
2808
+ ts && dates.add(dateKey(ts));
2775
2809
  }
2776
2810
  }
2777
2811
  }
@@ -2806,24 +2840,15 @@ async function walkForCodexJsonl(dir, result) {
2806
2840
  }
2807
2841
  async function safeReadUtf8(filePath) {
2808
2842
  try {
2809
- return await readFile13(filePath, "utf-8");
2843
+ return await readFile14(filePath, "utf-8");
2810
2844
  } catch {
2811
2845
  return null;
2812
2846
  }
2813
2847
  }
2814
- function parseTimestamp3(value) {
2815
- if (value == null || value === "") return null;
2816
- let date = new Date(value);
2817
- return Number.isNaN(date.getTime()) ? null : date;
2818
- }
2819
2848
  function getTodayLocalDate() {
2820
2849
  let now = /* @__PURE__ */ new Date();
2821
2850
  return new Date(now.getFullYear(), now.getMonth(), now.getDate());
2822
2851
  }
2823
- function toDateKey3(date) {
2824
- let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
2825
- return `${year}-${month}-${day}`;
2826
- }
2827
2852
  function getOrCreate(map, key) {
2828
2853
  let existing = map.get(key);
2829
2854
  if (existing) return existing;
@@ -2852,8 +2877,8 @@ function createEmptyTotals2() {
2852
2877
  function mergeTotals(target, source) {
2853
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;
2854
2879
  }
2855
- function toBreakdownTotals(breakdown, warnings) {
2856
- let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings);
2880
+ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
2881
+ let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings, pricingCatalog);
2857
2882
  return {
2858
2883
  eventCount: breakdown.eventCount,
2859
2884
  inputTokens: breakdown.inputTokens,
@@ -2865,7 +2890,7 @@ function toBreakdownTotals(breakdown, warnings) {
2865
2890
  estimatedCostUsd
2866
2891
  };
2867
2892
  }
2868
- function calculateBreakdownCost(breakdown, warnings) {
2893
+ function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2869
2894
  if (breakdown.costUSD != null && breakdown.costUSD > 0)
2870
2895
  return breakdown.costUSD;
2871
2896
  let result = calculateCost(
@@ -2879,7 +2904,8 @@ function calculateBreakdownCost(breakdown, warnings) {
2879
2904
  cacheWrite5mTokens: breakdown.cacheWrite5mTokens,
2880
2905
  cacheWrite1hTokens: breakdown.cacheWrite1hTokens,
2881
2906
  outputTokens: breakdown.outputTokens
2882
- }
2907
+ },
2908
+ pricingCatalog ? { catalog: pricingCatalog } : {}
2883
2909
  );
2884
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;
2885
2911
  }
@@ -2891,6 +2917,7 @@ var en = {
2891
2917
  events: "Events",
2892
2918
  tokens: "Tokens",
2893
2919
  cost: "Cost",
2920
+ pricing: "Pricing",
2894
2921
  sources: "Sources",
2895
2922
  daily: "Daily",
2896
2923
  topModels: "Top Models",
@@ -2919,6 +2946,7 @@ var en = {
2919
2946
  events: "\u4E8B\u4EF6",
2920
2947
  tokens: "\u4EE4\u724C",
2921
2948
  cost: "\u8D39\u7528",
2949
+ pricing: "\u5B9A\u4EF7",
2922
2950
  sources: "\u6765\u6E90",
2923
2951
  daily: "\u6BCF\u65E5",
2924
2952
  topModels: "\u6A21\u578B\u6392\u884C",
@@ -2951,7 +2979,7 @@ function renderReport(report, opts) {
2951
2979
  let s = t(opts.lang), lines = [], title = opts.emoji ? `\u{1F4CA} ${s.reportTitle}` : s.reportTitle;
2952
2980
  lines.push(title), lines.push("\u2500".repeat(title.length));
2953
2981
  let rangeLabel = getRangeLabel2(report.range, opts.lang), periodStart = report.startDate ? fmtDateShort(report.startDate) : "-", periodEnd = report.endDate ? fmtDateShort(report.endDate) : "-";
2954
- 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)
2955
2983
  return lines.push(""), lines.push(s.noData), lines.join(`
2956
2984
  `);
2957
2985
  if (lines.push(""), lines.push(s.sources), opts.detail ? lines.push(renderTable(
@@ -3043,6 +3071,9 @@ function getRangeLabel2(range, lang) {
3043
3071
  return range;
3044
3072
  }
3045
3073
  }
3074
+ function formatPricing(pricing) {
3075
+ return `${pricing.source === "remote" ? "remote" : pricing.source === "cache" ? "cache" : "bundled"} ${pricing.version}`;
3076
+ }
3046
3077
  function displayWidth(str) {
3047
3078
  let w = 0;
3048
3079
  for (let ch of str) {
@@ -3088,11 +3119,566 @@ function fmtDateShort(dateStr) {
3088
3119
  return (/* @__PURE__ */ new Date(dateStr + "T00:00:00")).toLocaleDateString("en-US", { month: "short", day: "numeric" });
3089
3120
  }
3090
3121
 
3091
- // src/config.ts
3092
- import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
3093
- import { homedir as homedir15, hostname } from "node:os";
3122
+ // src/activity.ts
3123
+ import { open as open3, readdir as readdir7 } from "node:fs/promises";
3124
+ import { createInterface as createInterface3 } from "node:readline";
3125
+ import { homedir as homedir15 } from "node:os";
3094
3126
  import { basename as basename9, join as join15 } from "node:path";
3095
- var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
3127
+ var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
3128
+ async function buildActivityReport(range, options = {}) {
3129
+ let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
3130
+ scanCodexActivity(targetDates, options),
3131
+ scanClaudeActivity(targetDates, options)
3132
+ ]), items = [...codex.items, ...claude.items].sort(sortActivityItems), requestedDates = options.dates?.slice().sort(), itemDates = [...new Set(items.map((item) => item.usageDate))].sort(), reportDates = requestedDates ?? itemDates, daily = reportDates.map((usageDate) => {
3133
+ let dayItems = items.filter((item) => item.usageDate === usageDate);
3134
+ return {
3135
+ usageDate,
3136
+ exactCount: sumByConfidence(dayItems, "exact"),
3137
+ proxyCount: sumByConfidence(dayItems, "proxy")
3138
+ };
3139
+ }).filter((day) => requestedDates || day.exactCount > 0 || day.proxyCount > 0);
3140
+ return {
3141
+ range,
3142
+ rangeLabel: getRangeLabel3(range),
3143
+ startDate: reportDates[0],
3144
+ endDate: reportDates[reportDates.length - 1],
3145
+ requestedDays: reportDates.length,
3146
+ daysWithData: daily.filter((day) => day.exactCount > 0 || day.proxyCount > 0).length,
3147
+ totals: {
3148
+ exactCount: sumByConfidence(items, "exact"),
3149
+ proxyCount: sumByConfidence(items, "proxy"),
3150
+ userMessageCount: codex.stats.userMessages.size + claude.stats.userMessages.size,
3151
+ filesScanned: codex.stats.filesScanned + claude.stats.filesScanned,
3152
+ sessionsScanned: (/* @__PURE__ */ new Set([...codex.stats.sessions, ...claude.stats.sessions])).size
3153
+ },
3154
+ daily,
3155
+ bySource: summarize(items, (item) => item.source, (item) => item.source),
3156
+ byKind: summarize(items, (item) => item.kind, (item) => labelKind(item.kind)),
3157
+ topTools: summarize(
3158
+ items.filter((item) => isToolLikeKind(item.kind)),
3159
+ (item) => `${item.source}|${item.name}`,
3160
+ (item) => `${item.name} (${item.source})`,
3161
+ 12
3162
+ ),
3163
+ topSkills: summarize(
3164
+ items.filter((item) => item.kind === "skill_call" || item.kind === "skill_proxy"),
3165
+ (item) => `${item.source}|${item.name}|${item.confidence}`,
3166
+ (item) => `${item.name} (${item.confidence === "proxy" ? "proxy" : item.source})`,
3167
+ 12
3168
+ ),
3169
+ topAgents: summarize(
3170
+ items.filter((item) => item.kind === "agent_call"),
3171
+ (item) => `${item.source}|${item.name}`,
3172
+ (item) => `${item.name} (${item.source})`,
3173
+ 12
3174
+ ),
3175
+ items,
3176
+ notes: [
3177
+ "Claude Code \u7684 Skill/Agent \u6765\u81EA\u7ED3\u6784\u5316 tool_use\uFF0C\u53E3\u5F84\u4E3A exact\u3002",
3178
+ "Codex \u7684 skill_proxy \u6765\u81EA\u547D\u4EE4\u4E2D\u8BFB\u53D6 SKILL.md \u7684\u75D5\u8FF9\uFF0C\u53EA\u80FD\u8868\u793A\u4EE3\u7406\u4FE1\u53F7\u3002",
3179
+ "\u8BE5\u62A5\u544A\u53EA\u8BFB\u53D6\u672C\u5730 Session\uFF0C\u4E0D\u53C2\u4E0E sync\uFF0C\u4E5F\u4E0D\u6539\u53D8\u670D\u52A1\u7AEF schema\u3002"
3180
+ ]
3181
+ };
3182
+ }
3183
+ function renderActivityReport(report, opts) {
3184
+ let lines = [], title = opts.emoji ? "\u{1F9ED} AIUsage Activity" : "AIUsage Activity";
3185
+ if (lines.push(title), lines.push("\u2500".repeat(stripAnsi(title).length)), lines.push(`\u5468\u671F ${report.rangeLabel} (${report.startDate ?? "-"} ~ ${report.endDate ?? "-"})`), lines.push(`\u786E\u5207\u4E8B\u4EF6 ${fmt(report.totals.exactCount)}`), lines.push(`\u4EE3\u7406\u4FE1\u53F7 ${fmt(report.totals.proxyCount)}`), lines.push(`\u7528\u6237\u6D88\u606F ${fmt(report.totals.userMessageCount)}`), lines.push(`Session ${fmt(report.totals.sessionsScanned)}`), lines.push(`\u6587\u4EF6 ${fmt(report.totals.filesScanned)}`), report.daysWithData === 0)
3186
+ return lines.push(""), lines.push("\u8BE5\u8303\u56F4\u65E0\u6D3B\u52A8\u6570\u636E\u3002"), lines.join(`
3187
+ `);
3188
+ lines.push(""), lines.push("\u6309\u6765\u6E90");
3189
+ for (let row of report.bySource)
3190
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3191
+ lines.push(""), lines.push("\u6309\u7C7B\u578B");
3192
+ for (let row of report.byKind)
3193
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3194
+ if (report.topTools.length > 0) {
3195
+ lines.push(""), lines.push("Top \u5DE5\u5177");
3196
+ for (let row of report.topTools)
3197
+ lines.push(` ${row.label}: ${fmt(row.count)}`);
3198
+ }
3199
+ if (report.topSkills.length > 0) {
3200
+ lines.push(""), lines.push("Top Skill");
3201
+ for (let row of report.topSkills)
3202
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3203
+ }
3204
+ if (report.topAgents.length > 0) {
3205
+ lines.push(""), lines.push("Top Subagent");
3206
+ for (let row of report.topAgents)
3207
+ lines.push(` ${row.label}: ${fmt(row.count)}`);
3208
+ }
3209
+ if (opts.detail && report.daily.length > 0) {
3210
+ lines.push(""), lines.push("\u6BCF\u65E5");
3211
+ for (let day of report.daily)
3212
+ lines.push(` ${day.usageDate}: exact ${fmt(day.exactCount)} / proxy ${fmt(day.proxyCount)}`);
3213
+ }
3214
+ if (opts.detail) {
3215
+ lines.push(""), lines.push("\u53E3\u5F84");
3216
+ for (let note of report.notes) lines.push(` - ${note}`);
3217
+ }
3218
+ return lines.join(`
3219
+ `);
3220
+ }
3221
+ async function scanCodexActivity(targetDates, options) {
3222
+ let baseDir = options.codexDir ?? join15(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
3223
+ return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
3224
+ await processCodexFile2(filePath, acc);
3225
+ }), finalizeActivity(acc);
3226
+ }
3227
+ async function processCodexFile2(filePath, acc) {
3228
+ let fh;
3229
+ try {
3230
+ fh = await open3(filePath, "r");
3231
+ } catch {
3232
+ return;
3233
+ }
3234
+ let sessionId = basename9(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
3235
+ try {
3236
+ let rl = createInterface3({
3237
+ input: fh.createReadStream({ encoding: "utf-8" }),
3238
+ crlfDelay: 1 / 0
3239
+ });
3240
+ for await (let line of rl) {
3241
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES3) continue;
3242
+ let record;
3243
+ try {
3244
+ record = JSON.parse(line);
3245
+ } catch {
3246
+ continue;
3247
+ }
3248
+ if (record.type === "session_meta") {
3249
+ let id = stringValue(record.payload?.id);
3250
+ id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
3251
+ continue;
3252
+ }
3253
+ if (record.type === "turn_context") {
3254
+ let cwd = stringValue(record.payload?.cwd);
3255
+ cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
3256
+ continue;
3257
+ }
3258
+ let ts = parseTs(record.timestamp);
3259
+ if (!ts) continue;
3260
+ let usageDate = dateKey(ts);
3261
+ if (acceptsDate(acc, usageDate)) {
3262
+ if (record.type === "response_item") {
3263
+ handleCodexResponseItem(record.payload?.item ?? record.payload, usageDate, projectFields, sessionId, filePath, record.timestamp ?? "", acc);
3264
+ continue;
3265
+ }
3266
+ record.type === "event_msg" && handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc);
3267
+ }
3268
+ }
3269
+ } finally {
3270
+ await fh.close();
3271
+ }
3272
+ }
3273
+ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, filePath, timestamp, acc) {
3274
+ if (!item?.type) return;
3275
+ let callId = item.call_id, baseKey = callId ? `codex:${item.type}:${callId}` : `codex:${filePath}:${usageDate}:${item.type}:${item.name ?? ""}:${item.arguments ?? ""}`;
3276
+ if (item.type === "message") {
3277
+ item.role === "user" && hasCodexUserMessageContent(item.content) && addUserMessage(acc, {
3278
+ provider: "openai",
3279
+ product: "codex",
3280
+ sessionId,
3281
+ timestamp,
3282
+ content: extractCodexMessageText(item.content),
3283
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:${JSON.stringify(item.content ?? "")}`
3284
+ });
3285
+ return;
3286
+ }
3287
+ if (item.type === "function_call") {
3288
+ let name = item.name ?? "unknown", args = parseJsonObject(item.arguments), kind = name === "spawn_agent" ? "agent_call" : "function_call";
3289
+ addActivity(acc, {
3290
+ usageDate,
3291
+ provider: "openai",
3292
+ product: "codex",
3293
+ projectFields,
3294
+ sessionId,
3295
+ kind,
3296
+ name: kind === "agent_call" ? stringValue(args.agent_type) ?? name : name,
3297
+ confidence: "exact",
3298
+ dedupeKey: baseKey
3299
+ });
3300
+ for (let skillName of extractSkillProxyNames(item.arguments))
3301
+ addActivity(acc, {
3302
+ usageDate,
3303
+ provider: "openai",
3304
+ product: "codex",
3305
+ projectFields,
3306
+ sessionId,
3307
+ kind: "skill_proxy",
3308
+ name: skillName,
3309
+ confidence: "proxy",
3310
+ dedupeKey: `${baseKey}:skill:${skillName}`
3311
+ });
3312
+ return;
3313
+ }
3314
+ if (item.type === "custom_tool_call") {
3315
+ addActivity(acc, {
3316
+ usageDate,
3317
+ provider: "openai",
3318
+ product: "codex",
3319
+ projectFields,
3320
+ sessionId,
3321
+ kind: "custom_tool_call",
3322
+ name: item.name ?? "unknown",
3323
+ confidence: "exact",
3324
+ dedupeKey: baseKey
3325
+ });
3326
+ return;
3327
+ }
3328
+ (item.type === "web_search_call" || item.type === "tool_search_call" || item.type === "image_generation_call") && addActivity(acc, {
3329
+ usageDate,
3330
+ provider: "openai",
3331
+ product: "codex",
3332
+ projectFields,
3333
+ sessionId,
3334
+ kind: item.type === "web_search_call" ? "web_search" : item.type === "tool_search_call" ? "tool_search" : "image_generation",
3335
+ name: item.name ?? item.type,
3336
+ confidence: "exact",
3337
+ dedupeKey: baseKey
3338
+ });
3339
+ }
3340
+ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc) {
3341
+ let payloadType = record.payload?.type;
3342
+ if (payloadType === "user_message") {
3343
+ addUserMessage(acc, {
3344
+ provider: "openai",
3345
+ product: "codex",
3346
+ sessionId,
3347
+ timestamp: record.timestamp ?? "",
3348
+ content: stringValue(record.payload?.message),
3349
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
3350
+ });
3351
+ return;
3352
+ }
3353
+ let kind = payloadType === "task_started" || payloadType === "task_complete" ? "task" : payloadType === "context_compacted" ? "compaction" : payloadType === "thread_rolled_back" ? "rollback" : payloadType === "turn_aborted" ? "interruption" : payloadType === "mcp_tool_call_end" ? "mcp_tool_call" : void 0;
3354
+ if (!kind) return;
3355
+ let callId = stringValue(record.payload?.call_id);
3356
+ addActivity(acc, {
3357
+ usageDate,
3358
+ provider: "openai",
3359
+ product: "codex",
3360
+ projectFields,
3361
+ sessionId,
3362
+ kind,
3363
+ name: payloadType ?? kind,
3364
+ confidence: "exact",
3365
+ dedupeKey: callId ? `codex:event:${callId}:${payloadType}` : `codex:event:${filePath}:${usageDate}:${sessionId}:${payloadType}:${record.timestamp ?? ""}`
3366
+ });
3367
+ }
3368
+ async function scanClaudeActivity(targetDates, options) {
3369
+ let acc = createAccumulator(targetDates, options.projectAliases), fileJobs = [];
3370
+ for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
3371
+ let projectDirs;
3372
+ try {
3373
+ projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
3374
+ } catch {
3375
+ continue;
3376
+ }
3377
+ for (let entry of projectDirs) {
3378
+ if (!entry.isDirectory()) continue;
3379
+ let projectPath = join15(baseDir, entry.name), jsonlFiles = [];
3380
+ await walkJsonl(projectPath, jsonlFiles);
3381
+ let fields = resolveClaudeProject(projectPath, acc.projectAliases);
3382
+ for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
3383
+ }
3384
+ }
3385
+ return acc.stats.filesScanned = fileJobs.length, await runWithConcurrency(fileJobs, FILE_CONCURRENCY3, async (job) => {
3386
+ await processClaudeFile(job.filePath, job.projectFields, acc);
3387
+ }), finalizeActivity(acc);
3388
+ }
3389
+ async function processClaudeFile(filePath, fallbackFields, acc) {
3390
+ let fh;
3391
+ try {
3392
+ fh = await open3(filePath, "r");
3393
+ } catch {
3394
+ return;
3395
+ }
3396
+ let fallbackSessionId = basename9(filePath).replace(/\.jsonl$/, "");
3397
+ try {
3398
+ let rl = createInterface3({
3399
+ input: fh.createReadStream({ encoding: "utf-8" }),
3400
+ crlfDelay: 1 / 0
3401
+ });
3402
+ for await (let line of rl) {
3403
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES3) continue;
3404
+ let record;
3405
+ try {
3406
+ record = JSON.parse(line);
3407
+ } catch {
3408
+ continue;
3409
+ }
3410
+ let ts = parseTs(record.timestamp);
3411
+ if (!ts) continue;
3412
+ let usageDate = dateKey(ts);
3413
+ if (!acceptsDate(acc, usageDate)) continue;
3414
+ let sessionId = record.sessionId ?? fallbackSessionId;
3415
+ acc.stats.sessions.add(`claude:${sessionId}`);
3416
+ let projectFields = record.cwd ? resolveProjectFields(record.cwd, acc.projectAliases) : fallbackFields;
3417
+ isClaudeUserMessage(record) && addUserMessage(acc, {
3418
+ provider: "anthropic",
3419
+ product: "claude-code",
3420
+ sessionId,
3421
+ timestamp: record.timestamp ?? "",
3422
+ content: extractClaudeMessageText(record.message?.content),
3423
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:user:${record.timestamp ?? ""}`,
3424
+ id: record.uuid
3425
+ });
3426
+ let blocks = Array.isArray(record.message?.content) ? record.message.content : [];
3427
+ for (let block of blocks) {
3428
+ if (block?.type !== "tool_use") continue;
3429
+ let name = block.name ?? "unknown", kind = classifyClaudeTool(name), metricName = getClaudeMetricName(name, block.input), dedupeKey = block.id ? `claude:tool:${block.id}` : `claude:tool:${filePath}:${usageDate}:${sessionId}:${name}:${JSON.stringify(block.input ?? {})}`;
3430
+ addActivity(acc, {
3431
+ usageDate,
3432
+ provider: "anthropic",
3433
+ product: "claude-code",
3434
+ projectFields,
3435
+ sessionId,
3436
+ kind,
3437
+ name: metricName,
3438
+ confidence: "exact",
3439
+ dedupeKey
3440
+ });
3441
+ }
3442
+ }
3443
+ } finally {
3444
+ await fh.close();
3445
+ }
3446
+ }
3447
+ function createAccumulator(targetDates, projectAliases) {
3448
+ return {
3449
+ targetDates,
3450
+ projectAliases,
3451
+ items: /* @__PURE__ */ new Map(),
3452
+ seen: /* @__PURE__ */ new Set(),
3453
+ stats: {
3454
+ filesScanned: 0,
3455
+ sessions: /* @__PURE__ */ new Set(),
3456
+ userMessages: /* @__PURE__ */ new Set()
3457
+ }
3458
+ };
3459
+ }
3460
+ function finalizeActivity(acc) {
3461
+ return {
3462
+ items: [...acc.items.values()],
3463
+ stats: acc.stats
3464
+ };
3465
+ }
3466
+ function addActivity(acc, input) {
3467
+ if (acc.seen.has(input.dedupeKey)) return;
3468
+ acc.seen.add(input.dedupeKey);
3469
+ let source = `${input.provider}/${input.product}`, key = [
3470
+ input.usageDate,
3471
+ source,
3472
+ input.projectFields.project,
3473
+ input.kind,
3474
+ input.name,
3475
+ input.confidence
3476
+ ].join("|"), existing = acc.items.get(key);
3477
+ if (existing) {
3478
+ existing.count += 1;
3479
+ return;
3480
+ }
3481
+ acc.items.set(key, {
3482
+ usageDate: input.usageDate,
3483
+ provider: input.provider,
3484
+ product: input.product,
3485
+ source,
3486
+ project: input.projectFields.project,
3487
+ projectDisplay: input.projectFields.projectDisplay,
3488
+ projectAlias: input.projectFields.projectAlias,
3489
+ kind: input.kind,
3490
+ name: input.name,
3491
+ count: 1,
3492
+ confidence: input.confidence
3493
+ });
3494
+ }
3495
+ function addUserMessage(acc, input) {
3496
+ let source = `${input.provider}/${input.product}`, normalized = normalizeMessageText(input.content), key = input.id ? `${source}:user_message:${input.id}` : normalized ? `${source}:user_message:${input.sessionId}:${input.timestamp}:${normalized}` : `${source}:user_message:${input.fallbackKey}`;
3497
+ acc.stats.userMessages.add(key);
3498
+ }
3499
+ function acceptsDate(acc, usageDate) {
3500
+ return !acc.targetDates || acc.targetDates.has(usageDate);
3501
+ }
3502
+ async function collectCodexSessionFiles2(baseDir) {
3503
+ let paths = [];
3504
+ try {
3505
+ let files = await readdir7(join15(baseDir, "archived_sessions"));
3506
+ for (let file of files)
3507
+ file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
3508
+ } catch {
3509
+ }
3510
+ return await walkJsonl(join15(baseDir, "sessions"), paths), paths;
3511
+ }
3512
+ function getClaudeProjectDirs2(configured) {
3513
+ if (configured?.length) return configured;
3514
+ let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
3515
+ if (envVar)
3516
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join15(p, "projects"));
3517
+ let home = homedir15();
3518
+ return [
3519
+ join15(home, ".config", "claude", "projects"),
3520
+ join15(home, ".claude", "projects")
3521
+ ];
3522
+ }
3523
+ async function walkJsonl(dir, result) {
3524
+ let entries;
3525
+ try {
3526
+ entries = await readdir7(dir, { withFileTypes: !0 });
3527
+ } catch {
3528
+ return;
3529
+ }
3530
+ for (let entry of entries) {
3531
+ let fullPath = join15(dir, entry.name);
3532
+ entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
3533
+ }
3534
+ }
3535
+ function resolveClaudeProject(projectPath, aliases2) {
3536
+ let rawName = basename9(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
3537
+ return {
3538
+ project: projectPath,
3539
+ projectDisplay: display,
3540
+ projectAlias: alias
3541
+ };
3542
+ }
3543
+ function classifyClaudeTool(name) {
3544
+ return name === "Skill" ? "skill_call" : name === "Agent" ? "agent_call" : name === "WebSearch" || name === "WebFetch" ? "web_search" : name === "ToolSearch" ? "tool_search" : name === "TaskCreate" || name === "TaskUpdate" || name === "TaskList" || name === "TaskStop" ? "task" : "tool_call";
3545
+ }
3546
+ function getClaudeMetricName(toolName, input) {
3547
+ return toolName === "Skill" ? stringValue(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue(input?.description) ?? stringValue(input?.subagent_type) ?? "unknown" : toolName;
3548
+ }
3549
+ function isClaudeUserMessage(record) {
3550
+ if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
3551
+ let content = record.message.content;
3552
+ return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue(block.text));
3553
+ }
3554
+ function hasCodexUserMessageContent(content) {
3555
+ return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 ? !1 : content.some((block) => block?.type === "input_text" || block?.type === "text");
3556
+ }
3557
+ function extractCodexMessageText(content) {
3558
+ return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue(block.text)).filter(Boolean).join(`
3559
+ `) || void 0;
3560
+ }
3561
+ function extractClaudeMessageText(content) {
3562
+ return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join(`
3563
+ `) || void 0;
3564
+ }
3565
+ function normalizeMessageText(value) {
3566
+ return value?.replace(/\s+/g, " ").trim() || void 0;
3567
+ }
3568
+ function extractSkillProxyNames(rawArguments) {
3569
+ if (!rawArguments) return [];
3570
+ let args = parseJsonObject(rawArguments), command2 = stringValue(args.cmd) ?? stringValue(args.command) ?? "";
3571
+ if (!command2.includes("SKILL.md")) return [];
3572
+ let names = /* @__PURE__ */ new Set();
3573
+ for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
3574
+ names.add(skillNameFromPath(match[1]));
3575
+ return [...names];
3576
+ }
3577
+ function parseJsonObject(raw) {
3578
+ if (!raw) return {};
3579
+ try {
3580
+ let parsed = JSON.parse(raw);
3581
+ return parsed && typeof parsed == "object" && !Array.isArray(parsed) ? parsed : {};
3582
+ } catch {
3583
+ return {};
3584
+ }
3585
+ }
3586
+ function skillNameFromPath(rawPath) {
3587
+ let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
3588
+ return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
3589
+ }
3590
+ function stringValue(value) {
3591
+ return typeof value == "string" && value.length > 0 ? value : void 0;
3592
+ }
3593
+ function summarize(items, keyFn, labelFn, limit) {
3594
+ let grouped = /* @__PURE__ */ new Map();
3595
+ for (let item of items) {
3596
+ let key = keyFn(item), existing = grouped.get(key);
3597
+ if (existing) {
3598
+ existing.count += item.count, item.confidence === "exact" ? existing.exactCount += item.count : existing.proxyCount += item.count;
3599
+ continue;
3600
+ }
3601
+ grouped.set(key, {
3602
+ key,
3603
+ label: labelFn(item),
3604
+ count: item.count,
3605
+ exactCount: item.confidence === "exact" ? item.count : 0,
3606
+ proxyCount: item.confidence === "proxy" ? item.count : 0
3607
+ });
3608
+ }
3609
+ let rows = [...grouped.values()].sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
3610
+ return limit ? rows.slice(0, limit) : rows;
3611
+ }
3612
+ function sumByConfidence(items, confidence) {
3613
+ return items.reduce((sum, item) => sum + (item.confidence === confidence ? item.count : 0), 0);
3614
+ }
3615
+ function isToolLikeKind(kind) {
3616
+ return kind === "function_call" || kind === "custom_tool_call" || kind === "tool_call" || kind === "web_search" || kind === "tool_search" || kind === "image_generation" || kind === "mcp_tool_call";
3617
+ }
3618
+ function labelKind(kind) {
3619
+ switch (kind) {
3620
+ case "function_call":
3621
+ return "Function Call";
3622
+ case "custom_tool_call":
3623
+ return "Custom Tool Call";
3624
+ case "tool_call":
3625
+ return "Tool Call";
3626
+ case "skill_call":
3627
+ return "Skill";
3628
+ case "skill_proxy":
3629
+ return "Skill Proxy";
3630
+ case "agent_call":
3631
+ return "Subagent";
3632
+ case "web_search":
3633
+ return "Web Search";
3634
+ case "tool_search":
3635
+ return "Tool Search";
3636
+ case "image_generation":
3637
+ return "Image Generation";
3638
+ case "task":
3639
+ return "Task";
3640
+ case "compaction":
3641
+ return "Context Compaction";
3642
+ case "rollback":
3643
+ return "Rollback";
3644
+ case "interruption":
3645
+ return "Interruption";
3646
+ case "mcp_tool_call":
3647
+ return "MCP Tool";
3648
+ }
3649
+ }
3650
+ function getRangeLabel3(range) {
3651
+ switch (range) {
3652
+ case "7d":
3653
+ return "\u6700\u8FD1 7 \u5929";
3654
+ case "1m":
3655
+ return "\u6700\u8FD1 30 \u5929";
3656
+ case "3m":
3657
+ return "\u6700\u8FD1 90 \u5929";
3658
+ case "all":
3659
+ return "\u5168\u90E8\u5386\u53F2";
3660
+ case "today":
3661
+ return "\u4ECA\u5929";
3662
+ }
3663
+ }
3664
+ function sortActivityItems(a, b) {
3665
+ return a.usageDate.localeCompare(b.usageDate) || a.source.localeCompare(b.source) || a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name);
3666
+ }
3667
+ function formatSummaryCount(row) {
3668
+ return row.proxyCount === 0 ? fmt(row.exactCount) : row.exactCount === 0 ? `${fmt(row.proxyCount)} proxy` : `${fmt(row.exactCount)} exact / ${fmt(row.proxyCount)} proxy`;
3669
+ }
3670
+ function fmt(n) {
3671
+ return n.toLocaleString("en-US");
3672
+ }
3673
+ function stripAnsi(s) {
3674
+ return s.replace(/\x1b\[[0-9;]*m/g, "");
3675
+ }
3676
+
3677
+ // src/config.ts
3678
+ import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
3679
+ import { homedir as homedir16, hostname } from "node:os";
3680
+ import { basename as basename10, join as join16 } from "node:path";
3681
+ var CONFIG_DIR = join16(homedir16(), ".aiusage"), CONFIG_PATH = join16(CONFIG_DIR, "config.json");
3096
3682
  function getConfigPath() {
3097
3683
  return CONFIG_PATH;
3098
3684
  }
@@ -3111,6 +3697,7 @@ function migrateConfig(config) {
3111
3697
  lookbackDays: config.lookbackDays,
3112
3698
  projectAliases: config.projectAliases,
3113
3699
  privacy: config.privacy,
3700
+ pricing: config.pricing,
3114
3701
  lang: config.lang,
3115
3702
  emoji: config.emoji,
3116
3703
  targets: [target]
@@ -3118,7 +3705,7 @@ function migrateConfig(config) {
3118
3705
  }
3119
3706
  async function readConfig() {
3120
3707
  try {
3121
- let raw = await readFile14(CONFIG_PATH, "utf-8");
3708
+ let raw = await readFile15(CONFIG_PATH, "utf-8");
3122
3709
  return migrateConfig(JSON.parse(raw));
3123
3710
  } catch {
3124
3711
  return {};
@@ -3167,6 +3754,21 @@ function setConfigValue(config, keyPath, values) {
3167
3754
  throw new Error("privacy.projectVisibility \u4EC5\u652F\u6301 hidden\u3001masked\u3001plain");
3168
3755
  return next.privacy = { ...next.privacy ?? {}, projectVisibility: value }, next;
3169
3756
  }
3757
+ if (keyPath === "pricing.mode") {
3758
+ let value = requireSingleValue(keyPath, values);
3759
+ if (value !== "auto" && value !== "manual" && value !== "offline")
3760
+ throw new Error("pricing.mode \u4EC5\u652F\u6301 auto\u3001manual\u3001offline");
3761
+ return next.pricing = { ...next.pricing ?? {}, mode: value }, next;
3762
+ }
3763
+ if (keyPath === "pricing.url") {
3764
+ let value = requireSingleValue(keyPath, values);
3765
+ return next.pricing = { ...next.pricing ?? {} }, value === "default" || value === "none" || value === "off" ? delete next.pricing.url : next.pricing.url = normalizeServerUrl(value), next;
3766
+ }
3767
+ if (keyPath === "pricing.cacheTtlHours")
3768
+ return next.pricing = {
3769
+ ...next.pricing ?? {},
3770
+ cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
3771
+ }, next;
3170
3772
  if (keyPath === "project.alias") {
3171
3773
  if (values.length < 2)
3172
3774
  throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
@@ -3290,12 +3892,12 @@ async function requestJson(url, init) {
3290
3892
  }
3291
3893
 
3292
3894
  // src/schedule.ts
3293
- import { mkdir as mkdir2, readFile as readFile15, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
3895
+ import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
3294
3896
  import { execFile } from "node:child_process";
3295
3897
  import { promisify } from "node:util";
3296
- import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
3297
- import { join as join16, resolve as resolve3 } from "node:path";
3298
- 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";
3898
+ import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
3899
+ import { join as join17, resolve as resolve3 } from "node:path";
3900
+ var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join17(homedir17(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join17(homedir17(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
3299
3901
  function parseInterval(value) {
3300
3902
  let match = value.match(/^(\d+)(m|h|d)$/);
3301
3903
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -3340,7 +3942,7 @@ function resolveCommandPaths() {
3340
3942
  }
3341
3943
  async function enableLaunchd(intervalSeconds) {
3342
3944
  let { nodePath, scriptPath } = resolveCommandPaths();
3343
- await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
3945
+ await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
3344
3946
  let plist = [
3345
3947
  '<?xml version="1.0" encoding="UTF-8"?>',
3346
3948
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -3394,7 +3996,7 @@ async function getLaunchdStatus() {
3394
3996
  return { enabled: !1 };
3395
3997
  }
3396
3998
  try {
3397
- 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];
3999
+ 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];
3398
4000
  return {
3399
4001
  enabled: !0,
3400
4002
  interval,
@@ -3409,8 +4011,8 @@ async function getLaunchdStatus() {
3409
4011
  }
3410
4012
  }
3411
4013
  async function enableCron(intervalSeconds) {
3412
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join16(homedir16(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
3413
- await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
4014
+ let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join17(homedir17(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
4015
+ await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
3414
4016
  let existing = "";
3415
4017
  try {
3416
4018
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -3468,7 +4070,7 @@ async function getCronStatus() {
3468
4070
  }
3469
4071
  }
3470
4072
  async function writeCrontab(content) {
3471
- let tmpFile = join16(tmpdir2(), `aiusage-cron-${Date.now()}`);
4073
+ let tmpFile = join17(tmpdir2(), `aiusage-cron-${Date.now()}`);
3472
4074
  await writeFile2(tmpFile, content, "utf-8");
3473
4075
  try {
3474
4076
  await execFileAsync("crontab", [tmpFile]);
@@ -3499,9 +4101,9 @@ function escapeXml(value) {
3499
4101
  }
3500
4102
 
3501
4103
  // src/doctor.ts
3502
- import { readdir as readdir7, stat as stat2 } from "node:fs/promises";
3503
- import { homedir as homedir17 } from "node:os";
3504
- import { join as join17 } from "node:path";
4104
+ import { readdir as readdir8, stat as stat2 } from "node:fs/promises";
4105
+ import { homedir as homedir18 } from "node:os";
4106
+ import { join as join18 } from "node:path";
3505
4107
  var msgs = {
3506
4108
  en: {
3507
4109
  groupConfig: "Configuration",
@@ -3557,13 +4159,13 @@ async function countFiles(dir, exts, cap = 1e3) {
3557
4159
  for (; queue.length > 0 && count < cap; ) {
3558
4160
  let current = queue.pop(), entries;
3559
4161
  try {
3560
- entries = await readdir7(current, { withFileTypes: !0 });
4162
+ entries = await readdir8(current, { withFileTypes: !0 });
3561
4163
  } catch {
3562
4164
  continue;
3563
4165
  }
3564
4166
  for (let e of entries) {
3565
4167
  if (count >= cap) break;
3566
- let full = join17(current, e.name);
4168
+ let full = join18(current, e.name);
3567
4169
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
3568
4170
  }
3569
4171
  }
@@ -3592,20 +4194,20 @@ async function runDoctor(lang = "zh") {
3592
4194
  }
3593
4195
  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 });
3594
4196
  }
3595
- let g3 = s.groupTools, home = homedir17(), tools = [
3596
- { dir: join17(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
3597
- { dir: join17(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
3598
- { dir: join17(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
3599
- { dir: join17(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
3600
- { dir: join17(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
3601
- { dir: join17(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
3602
- { dir: join17(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
3603
- { dir: join17(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
3604
- { dir: join17(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
3605
- { dir: join17(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
3606
- { dir: join17(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
3607
- { dir: join17(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
3608
- { dir: join17(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
4197
+ let g3 = s.groupTools, home = homedir18(), tools = [
4198
+ { dir: join18(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
4199
+ { dir: join18(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
4200
+ { dir: join18(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
4201
+ { dir: join18(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
4202
+ { dir: join18(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
4203
+ { dir: join18(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
4204
+ { dir: join18(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
4205
+ { dir: join18(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
4206
+ { dir: join18(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
4207
+ { dir: join18(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
4208
+ { dir: join18(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
4209
+ { dir: join18(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
4210
+ { dir: join18(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
3609
4211
  ];
3610
4212
  for (let tool of tools) {
3611
4213
  try {
@@ -3627,9 +4229,9 @@ async function runDoctor(lang = "zh") {
3627
4229
  }
3628
4230
 
3629
4231
  // src/project.ts
3630
- import { open as open3, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
3631
- import { basename as basename10, join as join18 } from "node:path";
3632
- import { homedir as homedir18 } from "node:os";
4232
+ import { open as open4, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
4233
+ import { basename as basename11, join as join19 } from "node:path";
4234
+ import { homedir as homedir19 } from "node:os";
3633
4235
  async function discoverProjects(projectAliases) {
3634
4236
  let projectMap = /* @__PURE__ */ new Map();
3635
4237
  function add(name, source) {
@@ -3673,20 +4275,20 @@ async function discoverClaudeProjects() {
3673
4275
  for (let baseDir of getClaudeDirs()) {
3674
4276
  let entries;
3675
4277
  try {
3676
- entries = await readdir8(baseDir, { withFileTypes: !0 });
4278
+ entries = await readdir9(baseDir, { withFileTypes: !0 });
3677
4279
  } catch {
3678
4280
  continue;
3679
4281
  }
3680
4282
  for (let entry of entries) {
3681
4283
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
3682
- let projectDir = join18(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
4284
+ let projectDir = join19(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
3683
4285
  name && name !== "unknown" && names.push(name);
3684
4286
  }
3685
4287
  }
3686
4288
  return names;
3687
4289
  }
3688
4290
  async function discoverCodexProjects() {
3689
- let sessionsDir = join18(homedir18(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
4291
+ let sessionsDir = join19(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
3690
4292
  for (let filePath of files) {
3691
4293
  let name = await extractCwdFromSessionMeta(filePath);
3692
4294
  name && name !== "unknown" && projects.add(name);
@@ -3696,7 +4298,7 @@ async function discoverCodexProjects() {
3696
4298
  async function extractCwdFromSessionMeta(filePath) {
3697
4299
  let fh;
3698
4300
  try {
3699
- fh = await open3(filePath, "r");
4301
+ fh = await open4(filePath, "r");
3700
4302
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3701
4303
  if (bytesRead === 0) return;
3702
4304
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3718,12 +4320,12 @@ async function walkFiles2(dir, ext) {
3718
4320
  async function walk2(d) {
3719
4321
  let entries;
3720
4322
  try {
3721
- entries = await readdir8(d, { withFileTypes: !0 });
4323
+ entries = await readdir9(d, { withFileTypes: !0 });
3722
4324
  } catch {
3723
4325
  return;
3724
4326
  }
3725
4327
  for (let entry of entries) {
3726
- let full = join18(d, entry.name);
4328
+ let full = join19(d, entry.name);
3727
4329
  entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
3728
4330
  }
3729
4331
  }
@@ -3734,7 +4336,7 @@ async function extractCwdFromFirstJsonl(dir) {
3734
4336
  if (!jsonlPath) return;
3735
4337
  let fh;
3736
4338
  try {
3737
- fh = await open3(jsonlPath, "r");
4339
+ fh = await open4(jsonlPath, "r");
3738
4340
  let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3739
4341
  if (bytesRead === 0) return;
3740
4342
  let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3760,27 +4362,27 @@ async function extractCwdFromFirstJsonl(dir) {
3760
4362
  async function findFirstJsonl(dir) {
3761
4363
  let entries;
3762
4364
  try {
3763
- entries = await readdir8(dir, { withFileTypes: !0 });
4365
+ entries = await readdir9(dir, { withFileTypes: !0 });
3764
4366
  } catch {
3765
4367
  return;
3766
4368
  }
3767
4369
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
3768
- if (topJsonl) return join18(dir, topJsonl.name);
4370
+ if (topJsonl) return join19(dir, topJsonl.name);
3769
4371
  for (let entry of entries)
3770
4372
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
3771
4373
  try {
3772
- let sub = (await readdir8(join18(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
3773
- if (sub) return join18(dir, entry.name, sub);
4374
+ let sub = (await readdir9(join19(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
4375
+ if (sub) return join19(dir, entry.name, sub);
3774
4376
  } catch {
3775
4377
  continue;
3776
4378
  }
3777
4379
  }
3778
4380
  async function discoverCopilotProjects() {
3779
- let dir = join18(homedir18(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
4381
+ let dir = join19(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
3780
4382
  for (let filePath of files) {
3781
4383
  let fh;
3782
4384
  try {
3783
- fh = await open3(filePath, "r");
4385
+ fh = await open4(filePath, "r");
3784
4386
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3785
4387
  if (bytesRead === 0) continue;
3786
4388
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3798,9 +4400,9 @@ async function discoverCopilotProjects() {
3798
4400
  return [...projects];
3799
4401
  }
3800
4402
  async function discoverGeminiProjects() {
3801
- let filePath = join18(homedir18(), ".gemini", "projects.json");
4403
+ let filePath = join19(homedir19(), ".gemini", "projects.json");
3802
4404
  try {
3803
- let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
4405
+ let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
3804
4406
  if (!projects || typeof projects != "object") return [];
3805
4407
  let names = [];
3806
4408
  for (let [path, _name] of Object.entries(projects)) {
@@ -3813,9 +4415,9 @@ async function discoverGeminiProjects() {
3813
4415
  }
3814
4416
  }
3815
4417
  async function discoverCursorProjects() {
3816
- let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
4418
+ let storagePath = join19(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
3817
4419
  try {
3818
- let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
4420
+ let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
3819
4421
  for (let uri of workspaceUris) {
3820
4422
  let name = nameFromFileUri(uri);
3821
4423
  name && projects.add(name);
@@ -3830,11 +4432,11 @@ async function discoverCursorProjects() {
3830
4432
  }
3831
4433
  }
3832
4434
  async function discoverCopilotVscodeProjects() {
3833
- 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();
4435
+ let dir = join19(homedir19(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
3834
4436
  for (let filePath of files) {
3835
4437
  let content;
3836
4438
  try {
3837
- content = await readFile16(filePath, "utf-8");
4439
+ content = await readFile17(filePath, "utf-8");
3838
4440
  } catch {
3839
4441
  continue;
3840
4442
  }
@@ -3847,18 +4449,18 @@ async function discoverCopilotVscodeProjects() {
3847
4449
  return [...projects];
3848
4450
  }
3849
4451
  async function discoverAntigravityProjects() {
3850
- let dir = join18(homedir18(), ".gemini", "antigravity", "knowledge"), entries;
4452
+ let dir = join19(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
3851
4453
  try {
3852
- entries = await readdir8(dir, { withFileTypes: !0 });
4454
+ entries = await readdir9(dir, { withFileTypes: !0 });
3853
4455
  } catch {
3854
4456
  return [];
3855
4457
  }
3856
4458
  let projects = /* @__PURE__ */ new Set();
3857
4459
  for (let entry of entries) {
3858
4460
  if (!entry.isDirectory()) continue;
3859
- let metadataPath = join18(dir, entry.name, "metadata.json");
4461
+ let metadataPath = join19(dir, entry.name, "metadata.json");
3860
4462
  try {
3861
- let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
4463
+ let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3862
4464
  name && name !== "unknown" && projects.add(name);
3863
4465
  } catch {
3864
4466
  continue;
@@ -3869,7 +4471,7 @@ async function discoverAntigravityProjects() {
3869
4471
  function nameFromFileUri(raw) {
3870
4472
  let path = pathFromFileUri(raw);
3871
4473
  if (!path) return;
3872
- let name = basename10(path);
4474
+ let name = basename11(path);
3873
4475
  return name && name !== "unknown" ? name : void 0;
3874
4476
  }
3875
4477
  function pathFromFileUri(raw) {
@@ -3888,11 +4490,11 @@ function pathFromFileUri(raw) {
3888
4490
  function getClaudeDirs() {
3889
4491
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
3890
4492
  if (envVar)
3891
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join18(p, "projects"));
3892
- let home = homedir18();
4493
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join19(p, "projects"));
4494
+ let home = homedir19();
3893
4495
  return [
3894
- join18(home, ".config", "claude", "projects"),
3895
- join18(home, ".claude", "projects")
4496
+ join19(home, ".config", "claude", "projects"),
4497
+ join19(home, ".claude", "projects")
3896
4498
  ];
3897
4499
  }
3898
4500
 
@@ -3933,6 +4535,106 @@ function shortHash(p) {
3933
4535
  return p ? createHash("sha1").update(p).digest("hex").slice(0, 8) : "00000000";
3934
4536
  }
3935
4537
 
4538
+ // src/pricing.ts
4539
+ import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
4540
+ import { homedir as homedir20 } from "node:os";
4541
+ import { join as join20 } from "node:path";
4542
+ var CACHE_DIR = join20(homedir20(), ".aiusage"), CACHE_PATH = join20(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
4543
+ "https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
4544
+ "https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
4545
+ "https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
4546
+ "https://unpkg.com/@aiusage/pricing@latest/catalog.json"
4547
+ ];
4548
+ async function resolvePricingCatalog(config, options = {}) {
4549
+ let mode = config.pricing?.mode ?? "auto", cache = await readPricingCache(), ttlHours = config.pricing?.cacheTtlHours ?? DEFAULT_CACHE_TTL_HOURS;
4550
+ if (!options.forceRefresh && cache && (mode === "manual" || mode === "offline" || isCacheFresh(cache, ttlHours)))
4551
+ return fromCache(cache);
4552
+ if ((mode !== "offline" || options.forceRefresh) && (mode === "auto" || options.forceRefresh)) {
4553
+ let candidates = getPricingUrls(config, options);
4554
+ for (let url of candidates)
4555
+ try {
4556
+ let catalog2 = await fetchPricingCatalog(url), fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
4557
+ return await writePricingCache({ fetchedAt, sourceUrl: url, catalog: catalog2 }), {
4558
+ catalog: catalog2,
4559
+ info: { source: "remote", version: catalog2.version, url, fetchedAt }
4560
+ };
4561
+ } catch {
4562
+ }
4563
+ }
4564
+ return cache ? fromCache(cache) : {
4565
+ catalog,
4566
+ info: { source: "bundled", version: catalog.version }
4567
+ };
4568
+ }
4569
+ async function getPricingStatus(config) {
4570
+ let cache = await readPricingCache();
4571
+ return {
4572
+ mode: config.pricing?.mode ?? "auto",
4573
+ configuredUrl: config.pricing?.url,
4574
+ cachePath: CACHE_PATH,
4575
+ cache: cache ? {
4576
+ version: cache.catalog.version,
4577
+ sourceUrl: cache.sourceUrl,
4578
+ fetchedAt: cache.fetchedAt
4579
+ } : void 0,
4580
+ bundled: {
4581
+ version: catalog.version
4582
+ }
4583
+ };
4584
+ }
4585
+ function getPricingUrls(config, options) {
4586
+ let urls = [
4587
+ options.explicitUrl,
4588
+ config.pricing?.url,
4589
+ options.target?.apiBaseUrl ? `${options.target.apiBaseUrl}/api/v1/public/pricing` : void 0,
4590
+ ...NPM_CDN_URLS
4591
+ ].filter((url) => !!url);
4592
+ return [...new Set(urls.map((url) => url.trim()).filter(Boolean))];
4593
+ }
4594
+ function isCacheFresh(cache, ttlHours) {
4595
+ let fetched = new Date(cache.fetchedAt).getTime();
4596
+ return Number.isFinite(fetched) ? Date.now() - fetched < ttlHours * 60 * 60 * 1e3 : !1;
4597
+ }
4598
+ function fromCache(cache) {
4599
+ return {
4600
+ catalog: cache.catalog,
4601
+ info: {
4602
+ source: "cache",
4603
+ version: cache.catalog.version,
4604
+ url: cache.sourceUrl,
4605
+ fetchedAt: cache.fetchedAt
4606
+ }
4607
+ };
4608
+ }
4609
+ async function readPricingCache() {
4610
+ try {
4611
+ let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
4612
+ return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
4613
+ } catch {
4614
+ return null;
4615
+ }
4616
+ }
4617
+ async function writePricingCache(cache) {
4618
+ await mkdir3(CACHE_DIR, { recursive: !0 }), await writeFile3(CACHE_PATH, `${JSON.stringify(cache, null, 2)}
4619
+ `, "utf-8");
4620
+ }
4621
+ async function fetchPricingCatalog(url) {
4622
+ let response = await fetch(url, {
4623
+ headers: { Accept: "application/json" },
4624
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
4625
+ });
4626
+ if (!response.ok) throw new Error(`pricing fetch failed: ${response.status}`);
4627
+ let data = await response.json();
4628
+ return assertPricingCatalog(data), data;
4629
+ }
4630
+ function assertPricingCatalog(value) {
4631
+ let catalog2 = value;
4632
+ if (!catalog2 || typeof catalog2 != "object") throw new Error("invalid pricing catalog");
4633
+ if (!catalog2.version || typeof catalog2.version != "string") throw new Error("invalid pricing catalog version");
4634
+ if (!catalog2.providers || typeof catalog2.providers != "object") throw new Error("invalid pricing catalog providers");
4635
+ if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
4636
+ }
4637
+
3936
4638
  // src/cli.ts
3937
4639
  var argv = process.argv.slice(2), command = argv[0];
3938
4640
  await (async () => {
@@ -3947,6 +4649,10 @@ await (async () => {
3947
4649
  let parsed = parseArgs(argv.slice(1));
3948
4650
  if (parsed.flags.help) return helpForSubcommand("report");
3949
4651
  await runReport(parsed.flags, parsed.positionals);
4652
+ } else if (command === "activity") {
4653
+ let parsed = parseArgs(argv.slice(1));
4654
+ if (parsed.flags.help) return helpForSubcommand("activity");
4655
+ await runActivity(parsed.flags, parsed.positionals);
3950
4656
  } else if (command === "health") {
3951
4657
  let parsed = parseArgs(argv.slice(1));
3952
4658
  if (parsed.flags.help) return helpForSubcommand("health");
@@ -3983,6 +4689,17 @@ await (async () => {
3983
4689
  let parsed = parseArgs(argv.slice(1));
3984
4690
  if (parsed.flags.help) return helpForSubcommand("doctor");
3985
4691
  await runDoctorCommand(parsed.flags);
4692
+ } else if (command === "pricing") {
4693
+ let sub = argv[1], parsed = parseArgs(argv.slice(2));
4694
+ if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("pricing");
4695
+ if (sub === "update")
4696
+ await runPricingUpdate(parsed.flags);
4697
+ else if (sub === "status" || sub === void 0)
4698
+ await runPricingStatus(parsed.flags);
4699
+ else {
4700
+ let zh2 = (await readConfig()).lang === "zh";
4701
+ throw new Error(`${zh2 ? "\u672A\u77E5\u5B50\u547D\u4EE4" : "Unknown subcommand"}: pricing ${sub}`);
4702
+ }
3986
4703
  } else if (command === "config" && argv[1] === "set")
3987
4704
  await runConfigSet(argv.slice(2));
3988
4705
  else if (command === "project") {
@@ -4054,15 +4771,23 @@ function printScanResult(result, zh2) {
4054
4771
  for (let [provider, breakdowns] of byProvider) {
4055
4772
  console.log(`\u2500\u2500 ${provider} \u2500\u2500`);
4056
4773
  for (let b of breakdowns.sort((a, c) => c.inputTokens - a.inputTokens))
4057
- 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)}`);
4774
+ console.log(` ${b.model} | ${b.projectAlias ?? b.projectDisplay ?? b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt2(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(b.outputTokens)} \u63A8\u7406: ${fmt2(b.reasoningOutputTokens)}`);
4058
4775
  console.log();
4059
4776
  }
4060
- 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)}`), console.log();
4777
+ console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt2(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(result.totals.outputTokens)} \u63A8\u7406: ${fmt2(result.totals.reasoningOutputTokens)}`), console.log();
4061
4778
  }
4062
4779
  async function runReport(flags, positionals = []) {
4063
4780
  let config = await readConfig();
4064
4781
  assertNoPositionals("report", positionals, config.lang === "zh");
4065
- let { dates, range } = resolveDateParams(flags, config), report = await buildLocalReport(range, { projectAliases: config.projectAliases, dates });
4782
+ let { dates, range } = resolveDateParams(flags, config), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
4783
+ explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
4784
+ target: pricingTarget
4785
+ }), report = await buildLocalReport(range, {
4786
+ projectAliases: config.projectAliases,
4787
+ dates,
4788
+ pricingCatalog: pricing.catalog,
4789
+ pricingInfo: pricing.info
4790
+ });
4066
4791
  if (flags.json) {
4067
4792
  console.log(JSON.stringify(report, null, 2));
4068
4793
  return;
@@ -4070,7 +4795,21 @@ async function runReport(flags, positionals = []) {
4070
4795
  let lang = resolveGlobalLang(flags, config), emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
4071
4796
  console.log(renderReport(report, { lang, emoji, detail }));
4072
4797
  }
4073
- function fmt(n) {
4798
+ async function runActivity(flags, positionals = []) {
4799
+ let config = await readConfig();
4800
+ assertNoPositionals("activity", positionals, config.lang === "zh");
4801
+ let { dates, range } = resolveDateParams(flags, config), report = await buildActivityReport(range, {
4802
+ projectAliases: config.projectAliases,
4803
+ dates
4804
+ });
4805
+ if (flags.json) {
4806
+ console.log(JSON.stringify(report, null, 2));
4807
+ return;
4808
+ }
4809
+ let emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
4810
+ console.log(renderActivityReport(report, { emoji, detail }));
4811
+ }
4812
+ function fmt2(n) {
4074
4813
  return n.toLocaleString("en-US");
4075
4814
  }
4076
4815
  async function runHealth(flags) {
@@ -4106,7 +4845,7 @@ async function runEnroll(flags) {
4106
4845
  }, null, 2));
4107
4846
  }
4108
4847
  function prompt(question) {
4109
- let rl = createInterface3({ input: process.stdin, output: process.stdout });
4848
+ let rl = createInterface4({ input: process.stdin, output: process.stdout });
4110
4849
  return new Promise((resolve4) => {
4111
4850
  rl.question(question, (answer) => {
4112
4851
  rl.close(), resolve4(answer.trim());
@@ -4261,6 +5000,25 @@ async function runDoctorCommand(flags) {
4261
5000
  }
4262
5001
  checks.filter((c) => c.status === "fail").length > 0 && (process.exitCode = 1);
4263
5002
  }
5003
+ async function runPricingStatus(flags) {
5004
+ let config = await readConfig(), status = await getPricingStatus(config);
5005
+ if (flags.json) {
5006
+ console.log(JSON.stringify(status, null, 2));
5007
+ return;
5008
+ }
5009
+ 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}`);
5010
+ }
5011
+ async function runPricingUpdate(flags) {
5012
+ let config = await readConfig(), targetName = resolveOptionalString(flags.target, void 0), target = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
5013
+ forceRefresh: !0,
5014
+ explicitUrl: resolveOptionalString(flags.url, void 0),
5015
+ target
5016
+ });
5017
+ console.log(JSON.stringify({
5018
+ cachePath: (await getPricingStatus(config)).cachePath,
5019
+ pricing: pricing.info
5020
+ }, null, 2));
5021
+ }
4264
5022
  async function runConfigSet(args) {
4265
5023
  let [keyPath, ...values] = args;
4266
5024
  if (!keyPath) throw new Error("config set \u7F3A\u5C11\u914D\u7F6E\u9879");
@@ -4320,9 +5078,11 @@ function printHelp(zh2 = !1) {
4320
5078
  let cmds = zh2 ? [
4321
5079
  ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
4322
5080
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
5081
+ ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
4323
5082
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4324
5083
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
4325
5084
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
5085
+ ["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
4326
5086
  ["schedule [on|off|status] [--every 5m]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
4327
5087
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
4328
5088
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"],
@@ -4332,9 +5092,11 @@ function printHelp(zh2 = !1) {
4332
5092
  ] : [
4333
5093
  ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "Scan usage breakdown"],
4334
5094
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
5095
+ ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
4335
5096
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4336
5097
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
4337
5098
  ["project [list|alias]", "Project management & aliases"],
5099
+ ["pricing [status|update] [--url URL]", "Pricing catalog management"],
4338
5100
  ["schedule [on|off|status] [--every 5m]", "Scheduled sync management"],
4339
5101
  ["doctor", "Run diagnostics"],
4340
5102
  ["config set <key> <value>", "Update config"],
@@ -4353,16 +5115,20 @@ function printUsageHint(zh2 = !1) {
4353
5115
  let cmds = zh2 ? [
4354
5116
  ["scan [--date YYYY-MM-DD|--range 1m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
4355
5117
  ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
5118
+ ["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
4356
5119
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4357
5120
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
5121
+ ["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
4358
5122
  ["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
4359
5123
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
4360
5124
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
4361
5125
  ] : [
4362
5126
  ["scan [--date YYYY-MM-DD|--range 1m]", "Scan usage breakdown"],
4363
5127
  ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
5128
+ ["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
4364
5129
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4365
5130
  ["project [list|alias]", "Project management & aliases"],
5131
+ ["pricing [status|update]", "Pricing catalog management"],
4366
5132
  ["schedule [on|off|status]", "Scheduled sync management"],
4367
5133
  ["doctor", "Run diagnostics"],
4368
5134
  ["config set <key> <value>", "Update config"]