@aiusage/cli 1.6.2 → 1.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +283 -94
- package/package.json +3 -2
- package/pricing-catalog.json +1105 -0
package/dist/cli.js
CHANGED
|
@@ -18,10 +18,16 @@ import { homedir } from "node:os";
|
|
|
18
18
|
// src/scanners/utils.ts
|
|
19
19
|
import { readdir } from "node:fs/promises";
|
|
20
20
|
import { join } from "node:path";
|
|
21
|
+
var MIN_VALID_MS = Date.UTC(2015, 0, 1);
|
|
21
22
|
function parseTs(value) {
|
|
22
|
-
if (value == null) return null;
|
|
23
|
-
let
|
|
24
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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-
|
|
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
|
|
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
|
|
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 =
|
|
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 =
|
|
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" ? [
|
|
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(
|
|
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 =
|
|
2574
|
-
ts && dates.add(
|
|
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 =
|
|
2591
|
-
topTs && dates.add(
|
|
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 =
|
|
2596
|
-
ts && dates.add(
|
|
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 =
|
|
2627
|
-
ts && dates.add(
|
|
2660
|
+
let ts = parseTs(row.timestamp);
|
|
2661
|
+
ts && dates.add(dateKey(ts));
|
|
2628
2662
|
}
|
|
2629
2663
|
continue;
|
|
2630
2664
|
}
|
|
2631
|
-
let topLevelTs =
|
|
2632
|
-
topLevelTs && dates.add(
|
|
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 =
|
|
2641
|
-
ts && dates.add(
|
|
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 =
|
|
2668
|
-
ts && dates.add(
|
|
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 =
|
|
2686
|
-
ts && dates.add(
|
|
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 =
|
|
2704
|
-
ts && dates.add(
|
|
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 =
|
|
2717
|
-
ts && dates.add(
|
|
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 =
|
|
2752
|
-
ts && dates.add(
|
|
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 =
|
|
2774
|
-
ts && dates.add(
|
|
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
|
|
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) {
|
|
@@ -3089,7 +3120,7 @@ function fmtDateShort(dateStr) {
|
|
|
3089
3120
|
}
|
|
3090
3121
|
|
|
3091
3122
|
// src/config.ts
|
|
3092
|
-
import { mkdir, readFile as
|
|
3123
|
+
import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
|
|
3093
3124
|
import { homedir as homedir15, hostname } from "node:os";
|
|
3094
3125
|
import { basename as basename9, join as join15 } from "node:path";
|
|
3095
3126
|
var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
|
|
@@ -3111,6 +3142,7 @@ function migrateConfig(config) {
|
|
|
3111
3142
|
lookbackDays: config.lookbackDays,
|
|
3112
3143
|
projectAliases: config.projectAliases,
|
|
3113
3144
|
privacy: config.privacy,
|
|
3145
|
+
pricing: config.pricing,
|
|
3114
3146
|
lang: config.lang,
|
|
3115
3147
|
emoji: config.emoji,
|
|
3116
3148
|
targets: [target]
|
|
@@ -3118,7 +3150,7 @@ function migrateConfig(config) {
|
|
|
3118
3150
|
}
|
|
3119
3151
|
async function readConfig() {
|
|
3120
3152
|
try {
|
|
3121
|
-
let raw = await
|
|
3153
|
+
let raw = await readFile15(CONFIG_PATH, "utf-8");
|
|
3122
3154
|
return migrateConfig(JSON.parse(raw));
|
|
3123
3155
|
} catch {
|
|
3124
3156
|
return {};
|
|
@@ -3167,6 +3199,21 @@ function setConfigValue(config, keyPath, values) {
|
|
|
3167
3199
|
throw new Error("privacy.projectVisibility \u4EC5\u652F\u6301 hidden\u3001masked\u3001plain");
|
|
3168
3200
|
return next.privacy = { ...next.privacy ?? {}, projectVisibility: value }, next;
|
|
3169
3201
|
}
|
|
3202
|
+
if (keyPath === "pricing.mode") {
|
|
3203
|
+
let value = requireSingleValue(keyPath, values);
|
|
3204
|
+
if (value !== "auto" && value !== "manual" && value !== "offline")
|
|
3205
|
+
throw new Error("pricing.mode \u4EC5\u652F\u6301 auto\u3001manual\u3001offline");
|
|
3206
|
+
return next.pricing = { ...next.pricing ?? {}, mode: value }, next;
|
|
3207
|
+
}
|
|
3208
|
+
if (keyPath === "pricing.url") {
|
|
3209
|
+
let value = requireSingleValue(keyPath, values);
|
|
3210
|
+
return next.pricing = { ...next.pricing ?? {} }, value === "default" || value === "none" || value === "off" ? delete next.pricing.url : next.pricing.url = normalizeServerUrl(value), next;
|
|
3211
|
+
}
|
|
3212
|
+
if (keyPath === "pricing.cacheTtlHours")
|
|
3213
|
+
return next.pricing = {
|
|
3214
|
+
...next.pricing ?? {},
|
|
3215
|
+
cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
|
|
3216
|
+
}, next;
|
|
3170
3217
|
if (keyPath === "project.alias") {
|
|
3171
3218
|
if (values.length < 2)
|
|
3172
3219
|
throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
|
|
@@ -3290,7 +3337,7 @@ async function requestJson(url, init) {
|
|
|
3290
3337
|
}
|
|
3291
3338
|
|
|
3292
3339
|
// src/schedule.ts
|
|
3293
|
-
import { mkdir as mkdir2, readFile as
|
|
3340
|
+
import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
3294
3341
|
import { execFile } from "node:child_process";
|
|
3295
3342
|
import { promisify } from "node:util";
|
|
3296
3343
|
import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
|
|
@@ -3394,7 +3441,7 @@ async function getLaunchdStatus() {
|
|
|
3394
3441
|
return { enabled: !1 };
|
|
3395
3442
|
}
|
|
3396
3443
|
try {
|
|
3397
|
-
let content = await
|
|
3444
|
+
let content = await readFile16(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
|
|
3398
3445
|
return {
|
|
3399
3446
|
enabled: !0,
|
|
3400
3447
|
interval,
|
|
@@ -3627,7 +3674,7 @@ async function runDoctor(lang = "zh") {
|
|
|
3627
3674
|
}
|
|
3628
3675
|
|
|
3629
3676
|
// src/project.ts
|
|
3630
|
-
import { open as open3, readdir as readdir8, readFile as
|
|
3677
|
+
import { open as open3, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
|
|
3631
3678
|
import { basename as basename10, join as join18 } from "node:path";
|
|
3632
3679
|
import { homedir as homedir18 } from "node:os";
|
|
3633
3680
|
async function discoverProjects(projectAliases) {
|
|
@@ -3800,7 +3847,7 @@ async function discoverCopilotProjects() {
|
|
|
3800
3847
|
async function discoverGeminiProjects() {
|
|
3801
3848
|
let filePath = join18(homedir18(), ".gemini", "projects.json");
|
|
3802
3849
|
try {
|
|
3803
|
-
let raw = await
|
|
3850
|
+
let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
3804
3851
|
if (!projects || typeof projects != "object") return [];
|
|
3805
3852
|
let names = [];
|
|
3806
3853
|
for (let [path, _name] of Object.entries(projects)) {
|
|
@@ -3815,7 +3862,7 @@ async function discoverGeminiProjects() {
|
|
|
3815
3862
|
async function discoverCursorProjects() {
|
|
3816
3863
|
let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
|
|
3817
3864
|
try {
|
|
3818
|
-
let raw = await
|
|
3865
|
+
let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
|
|
3819
3866
|
for (let uri of workspaceUris) {
|
|
3820
3867
|
let name = nameFromFileUri(uri);
|
|
3821
3868
|
name && projects.add(name);
|
|
@@ -3834,7 +3881,7 @@ async function discoverCopilotVscodeProjects() {
|
|
|
3834
3881
|
for (let filePath of files) {
|
|
3835
3882
|
let content;
|
|
3836
3883
|
try {
|
|
3837
|
-
content = await
|
|
3884
|
+
content = await readFile17(filePath, "utf-8");
|
|
3838
3885
|
} catch {
|
|
3839
3886
|
continue;
|
|
3840
3887
|
}
|
|
@@ -3858,7 +3905,7 @@ async function discoverAntigravityProjects() {
|
|
|
3858
3905
|
if (!entry.isDirectory()) continue;
|
|
3859
3906
|
let metadataPath = join18(dir, entry.name, "metadata.json");
|
|
3860
3907
|
try {
|
|
3861
|
-
let raw = await
|
|
3908
|
+
let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
|
|
3862
3909
|
name && name !== "unknown" && projects.add(name);
|
|
3863
3910
|
} catch {
|
|
3864
3911
|
continue;
|
|
@@ -3933,6 +3980,106 @@ function shortHash(p) {
|
|
|
3933
3980
|
return p ? createHash("sha1").update(p).digest("hex").slice(0, 8) : "00000000";
|
|
3934
3981
|
}
|
|
3935
3982
|
|
|
3983
|
+
// src/pricing.ts
|
|
3984
|
+
import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
|
|
3985
|
+
import { homedir as homedir19 } from "node:os";
|
|
3986
|
+
import { join as join19 } from "node:path";
|
|
3987
|
+
var CACHE_DIR = join19(homedir19(), ".aiusage"), CACHE_PATH = join19(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
|
|
3988
|
+
"https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
|
|
3989
|
+
"https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
|
|
3990
|
+
"https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
|
|
3991
|
+
"https://unpkg.com/@aiusage/pricing@latest/catalog.json"
|
|
3992
|
+
];
|
|
3993
|
+
async function resolvePricingCatalog(config, options = {}) {
|
|
3994
|
+
let mode = config.pricing?.mode ?? "auto", cache = await readPricingCache(), ttlHours = config.pricing?.cacheTtlHours ?? DEFAULT_CACHE_TTL_HOURS;
|
|
3995
|
+
if (!options.forceRefresh && cache && (mode === "manual" || mode === "offline" || isCacheFresh(cache, ttlHours)))
|
|
3996
|
+
return fromCache(cache);
|
|
3997
|
+
if ((mode !== "offline" || options.forceRefresh) && (mode === "auto" || options.forceRefresh)) {
|
|
3998
|
+
let candidates = getPricingUrls(config, options);
|
|
3999
|
+
for (let url of candidates)
|
|
4000
|
+
try {
|
|
4001
|
+
let catalog2 = await fetchPricingCatalog(url), fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4002
|
+
return await writePricingCache({ fetchedAt, sourceUrl: url, catalog: catalog2 }), {
|
|
4003
|
+
catalog: catalog2,
|
|
4004
|
+
info: { source: "remote", version: catalog2.version, url, fetchedAt }
|
|
4005
|
+
};
|
|
4006
|
+
} catch {
|
|
4007
|
+
}
|
|
4008
|
+
}
|
|
4009
|
+
return cache ? fromCache(cache) : {
|
|
4010
|
+
catalog,
|
|
4011
|
+
info: { source: "bundled", version: catalog.version }
|
|
4012
|
+
};
|
|
4013
|
+
}
|
|
4014
|
+
async function getPricingStatus(config) {
|
|
4015
|
+
let cache = await readPricingCache();
|
|
4016
|
+
return {
|
|
4017
|
+
mode: config.pricing?.mode ?? "auto",
|
|
4018
|
+
configuredUrl: config.pricing?.url,
|
|
4019
|
+
cachePath: CACHE_PATH,
|
|
4020
|
+
cache: cache ? {
|
|
4021
|
+
version: cache.catalog.version,
|
|
4022
|
+
sourceUrl: cache.sourceUrl,
|
|
4023
|
+
fetchedAt: cache.fetchedAt
|
|
4024
|
+
} : void 0,
|
|
4025
|
+
bundled: {
|
|
4026
|
+
version: catalog.version
|
|
4027
|
+
}
|
|
4028
|
+
};
|
|
4029
|
+
}
|
|
4030
|
+
function getPricingUrls(config, options) {
|
|
4031
|
+
let urls = [
|
|
4032
|
+
options.explicitUrl,
|
|
4033
|
+
config.pricing?.url,
|
|
4034
|
+
options.target?.apiBaseUrl ? `${options.target.apiBaseUrl}/api/v1/public/pricing` : void 0,
|
|
4035
|
+
...NPM_CDN_URLS
|
|
4036
|
+
].filter((url) => !!url);
|
|
4037
|
+
return [...new Set(urls.map((url) => url.trim()).filter(Boolean))];
|
|
4038
|
+
}
|
|
4039
|
+
function isCacheFresh(cache, ttlHours) {
|
|
4040
|
+
let fetched = new Date(cache.fetchedAt).getTime();
|
|
4041
|
+
return Number.isFinite(fetched) ? Date.now() - fetched < ttlHours * 60 * 60 * 1e3 : !1;
|
|
4042
|
+
}
|
|
4043
|
+
function fromCache(cache) {
|
|
4044
|
+
return {
|
|
4045
|
+
catalog: cache.catalog,
|
|
4046
|
+
info: {
|
|
4047
|
+
source: "cache",
|
|
4048
|
+
version: cache.catalog.version,
|
|
4049
|
+
url: cache.sourceUrl,
|
|
4050
|
+
fetchedAt: cache.fetchedAt
|
|
4051
|
+
}
|
|
4052
|
+
};
|
|
4053
|
+
}
|
|
4054
|
+
async function readPricingCache() {
|
|
4055
|
+
try {
|
|
4056
|
+
let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
|
|
4057
|
+
return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
|
|
4058
|
+
} catch {
|
|
4059
|
+
return null;
|
|
4060
|
+
}
|
|
4061
|
+
}
|
|
4062
|
+
async function writePricingCache(cache) {
|
|
4063
|
+
await mkdir3(CACHE_DIR, { recursive: !0 }), await writeFile3(CACHE_PATH, `${JSON.stringify(cache, null, 2)}
|
|
4064
|
+
`, "utf-8");
|
|
4065
|
+
}
|
|
4066
|
+
async function fetchPricingCatalog(url) {
|
|
4067
|
+
let response = await fetch(url, {
|
|
4068
|
+
headers: { Accept: "application/json" },
|
|
4069
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
4070
|
+
});
|
|
4071
|
+
if (!response.ok) throw new Error(`pricing fetch failed: ${response.status}`);
|
|
4072
|
+
let data = await response.json();
|
|
4073
|
+
return assertPricingCatalog(data), data;
|
|
4074
|
+
}
|
|
4075
|
+
function assertPricingCatalog(value) {
|
|
4076
|
+
let catalog2 = value;
|
|
4077
|
+
if (!catalog2 || typeof catalog2 != "object") throw new Error("invalid pricing catalog");
|
|
4078
|
+
if (!catalog2.version || typeof catalog2.version != "string") throw new Error("invalid pricing catalog version");
|
|
4079
|
+
if (!catalog2.providers || typeof catalog2.providers != "object") throw new Error("invalid pricing catalog providers");
|
|
4080
|
+
if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
|
|
4081
|
+
}
|
|
4082
|
+
|
|
3936
4083
|
// src/cli.ts
|
|
3937
4084
|
var argv = process.argv.slice(2), command = argv[0];
|
|
3938
4085
|
await (async () => {
|
|
@@ -3983,6 +4130,17 @@ await (async () => {
|
|
|
3983
4130
|
let parsed = parseArgs(argv.slice(1));
|
|
3984
4131
|
if (parsed.flags.help) return helpForSubcommand("doctor");
|
|
3985
4132
|
await runDoctorCommand(parsed.flags);
|
|
4133
|
+
} else if (command === "pricing") {
|
|
4134
|
+
let sub = argv[1], parsed = parseArgs(argv.slice(2));
|
|
4135
|
+
if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("pricing");
|
|
4136
|
+
if (sub === "update")
|
|
4137
|
+
await runPricingUpdate(parsed.flags);
|
|
4138
|
+
else if (sub === "status" || sub === void 0)
|
|
4139
|
+
await runPricingStatus(parsed.flags);
|
|
4140
|
+
else {
|
|
4141
|
+
let zh2 = (await readConfig()).lang === "zh";
|
|
4142
|
+
throw new Error(`${zh2 ? "\u672A\u77E5\u5B50\u547D\u4EE4" : "Unknown subcommand"}: pricing ${sub}`);
|
|
4143
|
+
}
|
|
3986
4144
|
} else if (command === "config" && argv[1] === "set")
|
|
3987
4145
|
await runConfigSet(argv.slice(2));
|
|
3988
4146
|
else if (command === "project") {
|
|
@@ -4062,7 +4220,15 @@ function printScanResult(result, zh2) {
|
|
|
4062
4220
|
async function runReport(flags, positionals = []) {
|
|
4063
4221
|
let config = await readConfig();
|
|
4064
4222
|
assertNoPositionals("report", positionals, config.lang === "zh");
|
|
4065
|
-
let { dates, range } = resolveDateParams(flags, config),
|
|
4223
|
+
let { dates, range } = resolveDateParams(flags, config), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
|
|
4224
|
+
explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
|
|
4225
|
+
target: pricingTarget
|
|
4226
|
+
}), report = await buildLocalReport(range, {
|
|
4227
|
+
projectAliases: config.projectAliases,
|
|
4228
|
+
dates,
|
|
4229
|
+
pricingCatalog: pricing.catalog,
|
|
4230
|
+
pricingInfo: pricing.info
|
|
4231
|
+
});
|
|
4066
4232
|
if (flags.json) {
|
|
4067
4233
|
console.log(JSON.stringify(report, null, 2));
|
|
4068
4234
|
return;
|
|
@@ -4261,6 +4427,25 @@ async function runDoctorCommand(flags) {
|
|
|
4261
4427
|
}
|
|
4262
4428
|
checks.filter((c) => c.status === "fail").length > 0 && (process.exitCode = 1);
|
|
4263
4429
|
}
|
|
4430
|
+
async function runPricingStatus(flags) {
|
|
4431
|
+
let config = await readConfig(), status = await getPricingStatus(config);
|
|
4432
|
+
if (flags.json) {
|
|
4433
|
+
console.log(JSON.stringify(status, null, 2));
|
|
4434
|
+
return;
|
|
4435
|
+
}
|
|
4436
|
+
console.log(`\u6A21\u5F0F: ${status.mode}`), status.configuredUrl && console.log(`\u914D\u7F6E\u6E90: ${status.configuredUrl}`), console.log(`\u7F13\u5B58: ${status.cachePath}`), status.cache ? (console.log(`\u7F13\u5B58\u7248\u672C: ${status.cache.version}`), console.log(`\u7F13\u5B58\u6765\u6E90: ${status.cache.sourceUrl}`), console.log(`\u7F13\u5B58\u65F6\u95F4: ${status.cache.fetchedAt}`)) : console.log("\u7F13\u5B58\u7248\u672C: (\u65E0)"), console.log(`\u5185\u7F6E\u7248\u672C: ${status.bundled.version}`);
|
|
4437
|
+
}
|
|
4438
|
+
async function runPricingUpdate(flags) {
|
|
4439
|
+
let config = await readConfig(), targetName = resolveOptionalString(flags.target, void 0), target = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
|
|
4440
|
+
forceRefresh: !0,
|
|
4441
|
+
explicitUrl: resolveOptionalString(flags.url, void 0),
|
|
4442
|
+
target
|
|
4443
|
+
});
|
|
4444
|
+
console.log(JSON.stringify({
|
|
4445
|
+
cachePath: (await getPricingStatus(config)).cachePath,
|
|
4446
|
+
pricing: pricing.info
|
|
4447
|
+
}, null, 2));
|
|
4448
|
+
}
|
|
4264
4449
|
async function runConfigSet(args) {
|
|
4265
4450
|
let [keyPath, ...values] = args;
|
|
4266
4451
|
if (!keyPath) throw new Error("config set \u7F3A\u5C11\u914D\u7F6E\u9879");
|
|
@@ -4323,6 +4508,7 @@ function printHelp(zh2 = !1) {
|
|
|
4323
4508
|
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
4324
4509
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
|
|
4325
4510
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
4511
|
+
["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
4326
4512
|
["schedule [on|off|status] [--every 5m]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
|
|
4327
4513
|
["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
|
|
4328
4514
|
["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"],
|
|
@@ -4335,6 +4521,7 @@ function printHelp(zh2 = !1) {
|
|
|
4335
4521
|
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
4336
4522
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
|
|
4337
4523
|
["project [list|alias]", "Project management & aliases"],
|
|
4524
|
+
["pricing [status|update] [--url URL]", "Pricing catalog management"],
|
|
4338
4525
|
["schedule [on|off|status] [--every 5m]", "Scheduled sync management"],
|
|
4339
4526
|
["doctor", "Run diagnostics"],
|
|
4340
4527
|
["config set <key> <value>", "Update config"],
|
|
@@ -4355,6 +4542,7 @@ function printUsageHint(zh2 = !1) {
|
|
|
4355
4542
|
["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
|
|
4356
4543
|
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
4357
4544
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
4545
|
+
["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
4358
4546
|
["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
|
|
4359
4547
|
["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
|
|
4360
4548
|
["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
|
|
@@ -4363,6 +4551,7 @@ function printUsageHint(zh2 = !1) {
|
|
|
4363
4551
|
["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
|
|
4364
4552
|
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
4365
4553
|
["project [list|alias]", "Project management & aliases"],
|
|
4554
|
+
["pricing [status|update]", "Pricing catalog management"],
|
|
4366
4555
|
["schedule [on|off|status]", "Scheduled sync management"],
|
|
4367
4556
|
["doctor", "Run diagnostics"],
|
|
4368
4557
|
["config set <key> <value>", "Update config"]
|