@aiusage/cli 1.3.0 → 1.4.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 +212 -28
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { createInterface as createInterface3 } from "node:readline";
|
|
|
12
12
|
import { hostname as hostname3 } from "node:os";
|
|
13
13
|
|
|
14
14
|
// src/scanners/claude.ts
|
|
15
|
-
import { readdir as readdir2, open } from "node:fs/promises";
|
|
15
|
+
import { readdir as readdir2, open, readFile } from "node:fs/promises";
|
|
16
16
|
import { join as join2 } from "node:path";
|
|
17
17
|
import { homedir } from "node:os";
|
|
18
18
|
import { createInterface } from "node:readline";
|
|
@@ -95,7 +95,7 @@ async function runWithConcurrency(items, concurrency, worker) {
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
// src/scanners/claude.ts
|
|
98
|
-
var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
98
|
+
var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024, STATS_CACHE_DEFAULT_INPUT_RATIO = 0.7;
|
|
99
99
|
function getClaudeProjectDirs(claudeDir) {
|
|
100
100
|
if (claudeDir) return [claudeDir];
|
|
101
101
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
@@ -155,6 +155,17 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
155
155
|
costUSD: usage.costUSD
|
|
156
156
|
});
|
|
157
157
|
}
|
|
158
|
+
let missingDates = [...targetDateSet].filter((d) => groupedByDate.get(d)?.size === 0);
|
|
159
|
+
if (missingDates.length > 0) {
|
|
160
|
+
let remaining = new Set(missingDates);
|
|
161
|
+
for (let baseDir of baseDirs) {
|
|
162
|
+
if (remaining.size === 0) break;
|
|
163
|
+
let statsCachePath = join2(baseDir, "..", "stats-cache.json");
|
|
164
|
+
await fillFromStatsCache(statsCachePath, remaining, groupedByDate);
|
|
165
|
+
for (let d of remaining)
|
|
166
|
+
groupedByDate.get(d).size > 0 && remaining.delete(d);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
158
169
|
return new Map(
|
|
159
170
|
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
160
171
|
);
|
|
@@ -211,6 +222,48 @@ async function processJsonlFile(filePath, fallbackFields, targetDateSet, project
|
|
|
211
222
|
await fh.close();
|
|
212
223
|
}
|
|
213
224
|
}
|
|
225
|
+
async function fillFromStatsCache(statsCachePath, missingDates, groupedByDate) {
|
|
226
|
+
let raw;
|
|
227
|
+
try {
|
|
228
|
+
raw = await readFile(statsCachePath, "utf-8");
|
|
229
|
+
} catch {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
let cache;
|
|
233
|
+
try {
|
|
234
|
+
cache = JSON.parse(raw);
|
|
235
|
+
} catch {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
let inputRatios = {};
|
|
239
|
+
for (let [model, usage] of Object.entries(cache.modelUsage ?? {})) {
|
|
240
|
+
let inp = usage.inputTokens ?? 0, out = usage.outputTokens ?? 0, total = inp + out;
|
|
241
|
+
total > 0 && (inputRatios[model] = inp / total);
|
|
242
|
+
}
|
|
243
|
+
for (let entry of cache.dailyModelTokens ?? []) {
|
|
244
|
+
let { date, tokensByModel } = entry;
|
|
245
|
+
if (!missingDates.has(date)) continue;
|
|
246
|
+
let grouped = groupedByDate.get(date);
|
|
247
|
+
if (grouped)
|
|
248
|
+
for (let [rawModel, totalTokens] of Object.entries(tokensByModel)) {
|
|
249
|
+
if (!totalTokens) continue;
|
|
250
|
+
let model = normalizeModelName(rawModel), ratio = inputRatios[rawModel] ?? inputRatios[model] ?? STATS_CACHE_DEFAULT_INPUT_RATIO, inputTokens = Math.round(totalTokens * ratio), outputTokens = totalTokens - inputTokens, key = `${model}|unknown`, existing = grouped.get(key);
|
|
251
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.outputTokens += outputTokens) : grouped.set(key, {
|
|
252
|
+
provider: "anthropic",
|
|
253
|
+
product: "claude-code",
|
|
254
|
+
channel: "cli",
|
|
255
|
+
model,
|
|
256
|
+
project: "unknown",
|
|
257
|
+
eventCount: 1,
|
|
258
|
+
inputTokens,
|
|
259
|
+
cachedInputTokens: 0,
|
|
260
|
+
cacheWriteTokens: 0,
|
|
261
|
+
outputTokens,
|
|
262
|
+
reasoningOutputTokens: 0
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
214
267
|
function parseTimestamp(value) {
|
|
215
268
|
if (!value) return null;
|
|
216
269
|
try {
|
|
@@ -362,7 +415,7 @@ function toDateKey2(date) {
|
|
|
362
415
|
}
|
|
363
416
|
|
|
364
417
|
// src/scanners/copilot.ts
|
|
365
|
-
import { readFile } from "node:fs/promises";
|
|
418
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
366
419
|
import { join as join4 } from "node:path";
|
|
367
420
|
import { homedir as homedir3 } from "node:os";
|
|
368
421
|
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
@@ -372,7 +425,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
372
425
|
for (let filePath of files) {
|
|
373
426
|
let content;
|
|
374
427
|
try {
|
|
375
|
-
content = await
|
|
428
|
+
content = await readFile2(filePath, "utf-8");
|
|
376
429
|
} catch {
|
|
377
430
|
continue;
|
|
378
431
|
}
|
|
@@ -586,7 +639,7 @@ async function scanCursorDates(targetDates) {
|
|
|
586
639
|
}
|
|
587
640
|
|
|
588
641
|
// src/scanners/gemini.ts
|
|
589
|
-
import { readFile as
|
|
642
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
590
643
|
import { join as join6 } from "node:path";
|
|
591
644
|
import { homedir as homedir5 } from "node:os";
|
|
592
645
|
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -596,7 +649,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
596
649
|
for (let filePath of files) {
|
|
597
650
|
let content;
|
|
598
651
|
try {
|
|
599
|
-
content = await
|
|
652
|
+
content = await readFile3(filePath, "utf-8");
|
|
600
653
|
} catch {
|
|
601
654
|
continue;
|
|
602
655
|
}
|
|
@@ -649,7 +702,7 @@ function extractTokens(msg) {
|
|
|
649
702
|
}
|
|
650
703
|
|
|
651
704
|
// src/scanners/qwen.ts
|
|
652
|
-
import { readFile as
|
|
705
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
653
706
|
import { join as join7, basename as basename2, dirname } from "node:path";
|
|
654
707
|
import { homedir as homedir6 } from "node:os";
|
|
655
708
|
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
@@ -659,7 +712,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
659
712
|
for (let filePath of files) {
|
|
660
713
|
let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
|
|
661
714
|
try {
|
|
662
|
-
content = await
|
|
715
|
+
content = await readFile4(filePath, "utf-8");
|
|
663
716
|
} catch {
|
|
664
717
|
continue;
|
|
665
718
|
}
|
|
@@ -709,7 +762,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
709
762
|
}
|
|
710
763
|
|
|
711
764
|
// src/scanners/kimi.ts
|
|
712
|
-
import { readFile as
|
|
765
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
713
766
|
import { join as join8, basename as basename3, dirname as dirname2 } from "node:path";
|
|
714
767
|
import { homedir as homedir7 } from "node:os";
|
|
715
768
|
async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -719,7 +772,7 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
|
719
772
|
for (let filePath of files) {
|
|
720
773
|
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
|
|
721
774
|
try {
|
|
722
|
-
content = await
|
|
775
|
+
content = await readFile5(filePath, "utf-8");
|
|
723
776
|
} catch {
|
|
724
777
|
continue;
|
|
725
778
|
}
|
|
@@ -776,7 +829,7 @@ function resolveKimiProject(hash, workspaceMap, aliases) {
|
|
|
776
829
|
async function loadWorkspaceMap(kimiHome) {
|
|
777
830
|
let map = /* @__PURE__ */ new Map();
|
|
778
831
|
try {
|
|
779
|
-
let raw = await
|
|
832
|
+
let raw = await readFile5(join8(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
780
833
|
if (config.workspaces)
|
|
781
834
|
for (let [hash, info] of Object.entries(config.workspaces))
|
|
782
835
|
info.path && map.set(hash, info.path);
|
|
@@ -786,7 +839,7 @@ async function loadWorkspaceMap(kimiHome) {
|
|
|
786
839
|
}
|
|
787
840
|
|
|
788
841
|
// src/scanners/amp.ts
|
|
789
|
-
import { readFile as
|
|
842
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
790
843
|
import { join as join9 } from "node:path";
|
|
791
844
|
import { homedir as homedir8 } from "node:os";
|
|
792
845
|
function resolveAmpDir(baseDir) {
|
|
@@ -806,7 +859,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
|
806
859
|
for (let filePath of threadFiles) {
|
|
807
860
|
let raw;
|
|
808
861
|
try {
|
|
809
|
-
raw = await
|
|
862
|
+
raw = await readFile6(filePath, "utf-8");
|
|
810
863
|
} catch {
|
|
811
864
|
continue;
|
|
812
865
|
}
|
|
@@ -891,7 +944,7 @@ function processMessages(thread, dates, grouped) {
|
|
|
891
944
|
}
|
|
892
945
|
|
|
893
946
|
// src/scanners/droid.ts
|
|
894
|
-
import { readFile as
|
|
947
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
895
948
|
import { join as join10, dirname as dirname3, basename as basename4 } from "node:path";
|
|
896
949
|
import { homedir as homedir9 } from "node:os";
|
|
897
950
|
function extractProjectFromSlug(dirPath) {
|
|
@@ -905,7 +958,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
905
958
|
for (let jsonlPath of files) {
|
|
906
959
|
let content;
|
|
907
960
|
try {
|
|
908
|
-
content = await
|
|
961
|
+
content = await readFile7(jsonlPath, "utf-8");
|
|
909
962
|
} catch {
|
|
910
963
|
continue;
|
|
911
964
|
}
|
|
@@ -924,7 +977,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
924
977
|
if (!dayMap) continue;
|
|
925
978
|
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join10(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
926
979
|
try {
|
|
927
|
-
settingsRaw = await
|
|
980
|
+
settingsRaw = await readFile7(settingsPath, "utf-8");
|
|
928
981
|
} catch {
|
|
929
982
|
continue;
|
|
930
983
|
}
|
|
@@ -961,7 +1014,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
961
1014
|
}
|
|
962
1015
|
|
|
963
1016
|
// src/scanners/opencode.ts
|
|
964
|
-
import { readFile as
|
|
1017
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
965
1018
|
import { homedir as homedir10 } from "node:os";
|
|
966
1019
|
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
967
1020
|
let dates = new Set(targetDates), dir = baseDir ?? `${homedir10()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
|
|
@@ -970,7 +1023,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
970
1023
|
for (let filePath of files) {
|
|
971
1024
|
let raw;
|
|
972
1025
|
try {
|
|
973
|
-
raw = await
|
|
1026
|
+
raw = await readFile8(filePath, "utf-8");
|
|
974
1027
|
} catch {
|
|
975
1028
|
continue;
|
|
976
1029
|
}
|
|
@@ -1013,7 +1066,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
1013
1066
|
}
|
|
1014
1067
|
|
|
1015
1068
|
// src/scanners/pi.ts
|
|
1016
|
-
import { readFile as
|
|
1069
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
1017
1070
|
import { join as join11, basename as basename5, dirname as dirname4 } from "node:path";
|
|
1018
1071
|
import { homedir as homedir11 } from "node:os";
|
|
1019
1072
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -1023,7 +1076,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
1023
1076
|
for (let filePath of files) {
|
|
1024
1077
|
let content;
|
|
1025
1078
|
try {
|
|
1026
|
-
content = await
|
|
1079
|
+
content = await readFile9(filePath, "utf-8");
|
|
1027
1080
|
} catch {
|
|
1028
1081
|
continue;
|
|
1029
1082
|
}
|
|
@@ -1138,8 +1191,88 @@ function createEmptyTotals() {
|
|
|
1138
1191
|
};
|
|
1139
1192
|
}
|
|
1140
1193
|
|
|
1194
|
+
// src/scanners/anthropic-admin-api.ts
|
|
1195
|
+
var ADMIN_API_BASE = "https://api.anthropic.com", USAGE_ENDPOINT = "/v1/organizations/usage_report/messages", MAX_DAYS_PER_REQUEST = 31;
|
|
1196
|
+
async function scanAnthropicApiDates(targetDates, adminApiKey) {
|
|
1197
|
+
if (!targetDates.length || !adminApiKey)
|
|
1198
|
+
return new Map(targetDates.map((d) => [d, []]));
|
|
1199
|
+
let sorted = [...new Set(targetDates)].sort(), grouped = new Map(sorted.map((d) => [d, []])), chunks = chunkDateRange(sorted[0], sorted[sorted.length - 1]);
|
|
1200
|
+
for (let { startingAt, endingAt } of chunks)
|
|
1201
|
+
await fetchAndMerge(startingAt, endingAt, adminApiKey, sorted, grouped);
|
|
1202
|
+
return grouped;
|
|
1203
|
+
}
|
|
1204
|
+
async function fetchAndMerge(startingAt, endingAt, adminApiKey, targetDates, grouped) {
|
|
1205
|
+
let nextPage = null;
|
|
1206
|
+
do {
|
|
1207
|
+
let url = buildUrl(startingAt, endingAt, nextPage), resp;
|
|
1208
|
+
try {
|
|
1209
|
+
resp = await fetch(url, {
|
|
1210
|
+
headers: {
|
|
1211
|
+
"x-api-key": adminApiKey,
|
|
1212
|
+
"anthropic-version": "2023-06-01"
|
|
1213
|
+
}
|
|
1214
|
+
});
|
|
1215
|
+
} catch (err) {
|
|
1216
|
+
throw new Error(`Anthropic Admin API request failed: ${err}`);
|
|
1217
|
+
}
|
|
1218
|
+
if (!resp.ok) {
|
|
1219
|
+
let body = await resp.text().catch(() => "");
|
|
1220
|
+
throw new Error(`Anthropic Admin API error ${resp.status}: ${body}`);
|
|
1221
|
+
}
|
|
1222
|
+
let data = await resp.json();
|
|
1223
|
+
for (let bucket of data.data) {
|
|
1224
|
+
let date = bucket.starting_at.slice(0, 10);
|
|
1225
|
+
if (!targetDates.includes(date)) continue;
|
|
1226
|
+
let breakdowns = grouped.get(date);
|
|
1227
|
+
for (let result of bucket.results) {
|
|
1228
|
+
if (!result.model) continue;
|
|
1229
|
+
let model = normalizeModelName(result.model), inputTokens = result.uncached_input_tokens ?? 0, cachedInputTokens = result.cache_read_input_tokens ?? 0, cacheWrite5m = result.cache_creation?.ephemeral_5m_input_tokens ?? 0, cacheWrite1h = result.cache_creation?.ephemeral_1h_input_tokens ?? 0, cacheWriteTokens = cacheWrite5m + cacheWrite1h, outputTokens = result.output_tokens ?? 0;
|
|
1230
|
+
if (inputTokens + outputTokens + cachedInputTokens + cacheWriteTokens === 0) continue;
|
|
1231
|
+
let existing = breakdowns.find((b) => b.model === model);
|
|
1232
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cachedInputTokens, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + cacheWrite5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + cacheWrite1h, existing.outputTokens += outputTokens) : breakdowns.push({
|
|
1233
|
+
provider: "anthropic",
|
|
1234
|
+
product: "claude-code",
|
|
1235
|
+
channel: "cli",
|
|
1236
|
+
model,
|
|
1237
|
+
project: "unknown",
|
|
1238
|
+
eventCount: 1,
|
|
1239
|
+
inputTokens,
|
|
1240
|
+
cachedInputTokens,
|
|
1241
|
+
cacheWriteTokens,
|
|
1242
|
+
cacheWrite5mTokens: cacheWrite5m,
|
|
1243
|
+
cacheWrite1hTokens: cacheWrite1h,
|
|
1244
|
+
outputTokens,
|
|
1245
|
+
reasoningOutputTokens: 0
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
nextPage = data.has_more ? data.next_page : null;
|
|
1250
|
+
} while (nextPage);
|
|
1251
|
+
}
|
|
1252
|
+
function buildUrl(startingAt, endingAt, page) {
|
|
1253
|
+
let params = new URLSearchParams({
|
|
1254
|
+
starting_at: startingAt,
|
|
1255
|
+
ending_at: endingAt,
|
|
1256
|
+
bucket_width: "1d"
|
|
1257
|
+
});
|
|
1258
|
+
return params.append("group_by[]", "model"), page && params.set("page", page), `${ADMIN_API_BASE}${USAGE_ENDPOINT}?${params}`;
|
|
1259
|
+
}
|
|
1260
|
+
function chunkDateRange(startDate, endDate) {
|
|
1261
|
+
let chunks = [], current = /* @__PURE__ */ new Date(`${startDate}T00:00:00Z`), end = /* @__PURE__ */ new Date(`${endDate}T00:00:00Z`);
|
|
1262
|
+
for (end.setUTCDate(end.getUTCDate() + 1); current < end; ) {
|
|
1263
|
+
let chunkEnd = new Date(current);
|
|
1264
|
+
chunkEnd.setUTCDate(chunkEnd.getUTCDate() + MAX_DAYS_PER_REQUEST);
|
|
1265
|
+
let actualEnd = chunkEnd < end ? chunkEnd : end;
|
|
1266
|
+
chunks.push({
|
|
1267
|
+
startingAt: current.toISOString().replace(".000Z", "Z"),
|
|
1268
|
+
endingAt: actualEnd.toISOString().replace(".000Z", "Z")
|
|
1269
|
+
}), current = actualEnd;
|
|
1270
|
+
}
|
|
1271
|
+
return chunks;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1141
1274
|
// src/report.ts
|
|
1142
|
-
import { readdir as readdir5, readFile as
|
|
1275
|
+
import { readdir as readdir5, readFile as readFile10 } from "node:fs/promises";
|
|
1143
1276
|
import { homedir as homedir12 } from "node:os";
|
|
1144
1277
|
import { join as join12 } from "node:path";
|
|
1145
1278
|
async function buildLocalReport(range, options = {}) {
|
|
@@ -1394,7 +1527,7 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
1394
1527
|
}
|
|
1395
1528
|
async function safeReadUtf8(filePath) {
|
|
1396
1529
|
try {
|
|
1397
|
-
return await
|
|
1530
|
+
return await readFile10(filePath, "utf-8");
|
|
1398
1531
|
} catch {
|
|
1399
1532
|
return null;
|
|
1400
1533
|
}
|
|
@@ -1747,7 +1880,7 @@ function fmtDateShort(dateStr) {
|
|
|
1747
1880
|
}
|
|
1748
1881
|
|
|
1749
1882
|
// src/config.ts
|
|
1750
|
-
import { mkdir, readFile as
|
|
1883
|
+
import { mkdir, readFile as readFile11, writeFile } from "node:fs/promises";
|
|
1751
1884
|
import { homedir as homedir13, hostname } from "node:os";
|
|
1752
1885
|
import { basename as basename6, join as join13 } from "node:path";
|
|
1753
1886
|
var CONFIG_DIR = join13(homedir13(), ".aiusage"), CONFIG_PATH = join13(CONFIG_DIR, "config.json");
|
|
@@ -1776,7 +1909,7 @@ function migrateConfig(config) {
|
|
|
1776
1909
|
}
|
|
1777
1910
|
async function readConfig() {
|
|
1778
1911
|
try {
|
|
1779
|
-
let raw = await
|
|
1912
|
+
let raw = await readFile11(CONFIG_PATH, "utf-8");
|
|
1780
1913
|
return migrateConfig(JSON.parse(raw));
|
|
1781
1914
|
} catch {
|
|
1782
1915
|
return {};
|
|
@@ -1844,6 +1977,12 @@ function setConfigValue(config, keyPath, values) {
|
|
|
1844
1977
|
throw new Error("emoji only supports true or false");
|
|
1845
1978
|
return next.emoji = value === "true", next;
|
|
1846
1979
|
}
|
|
1980
|
+
if (keyPath === "anthropic-admin-key") {
|
|
1981
|
+
let value = requireSingleValue(keyPath, values);
|
|
1982
|
+
if (!value.startsWith("sk-ant-admin"))
|
|
1983
|
+
throw new Error("anthropic-admin-key must start with sk-ant-admin (obtain from console.anthropic.com \u2192 Settings \u2192 Admin Keys)");
|
|
1984
|
+
return next.anthropicAdminKey = value, next;
|
|
1985
|
+
}
|
|
1847
1986
|
throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u9879: ${keyPath}`);
|
|
1848
1987
|
}
|
|
1849
1988
|
function requireSingleValue(keyPath, values) {
|
|
@@ -1942,7 +2081,7 @@ async function requestJson(url, init) {
|
|
|
1942
2081
|
}
|
|
1943
2082
|
|
|
1944
2083
|
// src/schedule.ts
|
|
1945
|
-
import { mkdir as mkdir2, readFile as
|
|
2084
|
+
import { mkdir as mkdir2, readFile as readFile12, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
1946
2085
|
import { execFile } from "node:child_process";
|
|
1947
2086
|
import { promisify } from "node:util";
|
|
1948
2087
|
import { homedir as homedir14, platform, tmpdir as tmpdir2 } from "node:os";
|
|
@@ -2046,7 +2185,7 @@ async function getLaunchdStatus() {
|
|
|
2046
2185
|
return { enabled: !1 };
|
|
2047
2186
|
}
|
|
2048
2187
|
try {
|
|
2049
|
-
let content = await
|
|
2188
|
+
let content = await readFile12(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
|
|
2050
2189
|
return {
|
|
2051
2190
|
enabled: !0,
|
|
2052
2191
|
interval,
|
|
@@ -2276,7 +2415,7 @@ async function runDoctor(lang = "zh") {
|
|
|
2276
2415
|
}
|
|
2277
2416
|
|
|
2278
2417
|
// src/project.ts
|
|
2279
|
-
import { open as open3, readdir as readdir7, readFile as
|
|
2418
|
+
import { open as open3, readdir as readdir7, readFile as readFile13 } from "node:fs/promises";
|
|
2280
2419
|
import { join as join16 } from "node:path";
|
|
2281
2420
|
import { homedir as homedir16 } from "node:os";
|
|
2282
2421
|
async function discoverProjects(projectAliases) {
|
|
@@ -2438,7 +2577,7 @@ async function discoverCopilotProjects() {
|
|
|
2438
2577
|
async function discoverGeminiProjects() {
|
|
2439
2578
|
let filePath = join16(homedir16(), ".gemini", "projects.json");
|
|
2440
2579
|
try {
|
|
2441
|
-
let raw = await
|
|
2580
|
+
let raw = await readFile13(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
2442
2581
|
if (!projects || typeof projects != "object") return [];
|
|
2443
2582
|
let names = [];
|
|
2444
2583
|
for (let [path, _name] of Object.entries(projects)) {
|
|
@@ -2515,6 +2654,9 @@ try {
|
|
|
2515
2654
|
let zh2 = (await readConfig()).lang === "zh";
|
|
2516
2655
|
console.error(`${zh2 ? "\u672A\u77E5\u5B50\u547D\u4EE4" : "Unknown subcommand"}: project ${sub}`), console.log(zh2 ? "\u53EF\u7528: aiusage project list, aiusage project alias <\u9879\u76EE\u540D> <\u522B\u540D>" : "Available: aiusage project list, aiusage project alias <name> <alias>"), process.exitCode = 1;
|
|
2517
2656
|
}
|
|
2657
|
+
} else if (command === "import") {
|
|
2658
|
+
let parsed = parseArgs(argv.slice(1));
|
|
2659
|
+
await runImport(parsed.flags);
|
|
2518
2660
|
} else if (command === "setup")
|
|
2519
2661
|
console.log(`To deploy the server, clone the repo and run the setup wizard:
|
|
2520
2662
|
`), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
|
|
@@ -2658,6 +2800,48 @@ async function runSync(flags) {
|
|
|
2658
2800
|
results: uploadResults
|
|
2659
2801
|
}, null, 2));
|
|
2660
2802
|
}
|
|
2803
|
+
async function runImport(flags) {
|
|
2804
|
+
let config = await readConfig(), adminKey = resolveOptionalString(flags.key, config.anthropicAdminKey);
|
|
2805
|
+
if (!adminKey)
|
|
2806
|
+
throw new Error(
|
|
2807
|
+
`Anthropic Admin API key required.
|
|
2808
|
+
Option 1: aiusage config set anthropic-admin-key sk-ant-admin...
|
|
2809
|
+
Option 2: aiusage import --key sk-ant-admin... --start DATE --end DATE
|
|
2810
|
+
Get your Admin key at: console.anthropic.com \u2192 Settings \u2192 Admin Keys`
|
|
2811
|
+
);
|
|
2812
|
+
let startDate = resolveOptionalString(flags.start, void 0), endDate = resolveOptionalString(flags.end, void 0);
|
|
2813
|
+
if (!startDate) throw new Error("--start DATE is required (e.g. --start 2025-11-01)");
|
|
2814
|
+
if (!endDate) throw new Error("--end DATE is required (e.g. --end 2026-01-08)");
|
|
2815
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate))
|
|
2816
|
+
throw new Error("Dates must be in YYYY-MM-DD format");
|
|
2817
|
+
if (startDate > endDate) throw new Error("--start must be before --end");
|
|
2818
|
+
let targetName = resolveOptionalString(flags.target, void 0), allTargets = config.targets ?? [];
|
|
2819
|
+
if (allTargets.length === 0) throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
|
|
2820
|
+
let targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll");
|
|
2821
|
+
console.log(`Fetching Anthropic API usage: ${startDate} \u2192 ${endDate}`);
|
|
2822
|
+
let dateRange = buildDateRange(startDate, endDate), apiResults = await scanAnthropicApiDates(dateRange, adminKey), allDays = dateRange.map((date) => ({ usageDate: date, breakdowns: apiResults.get(date) ?? [] })).filter((d) => d.breakdowns.length > 0);
|
|
2823
|
+
if (allDays.length === 0) {
|
|
2824
|
+
console.log("No usage data returned from Anthropic API for the specified range.");
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
console.log(`Found data for ${allDays.length} days. Uploading...`);
|
|
2828
|
+
for (let target of targets) {
|
|
2829
|
+
if (!target.deviceToken) {
|
|
2830
|
+
console.log(`Skipping "${target.name}": not enrolled (missing deviceToken)`);
|
|
2831
|
+
continue;
|
|
2832
|
+
}
|
|
2833
|
+
let BATCH_SIZE = 30, totalProcessed = 0;
|
|
2834
|
+
for (let i = 0; i < allDays.length; i += BATCH_SIZE) {
|
|
2835
|
+
let batch = allDays.slice(i, i + BATCH_SIZE), response = await uploadDailyUsage(
|
|
2836
|
+
target.apiBaseUrl,
|
|
2837
|
+
{ siteId: target.siteId, deviceId, deviceAlias: config.deviceAlias, deviceToken: target.deviceToken },
|
|
2838
|
+
batch
|
|
2839
|
+
);
|
|
2840
|
+
totalProcessed += response.daysProcessed;
|
|
2841
|
+
}
|
|
2842
|
+
console.log(`Uploaded ${totalProcessed} days to "${target.name}"`);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2661
2845
|
async function runInit(flags) {
|
|
2662
2846
|
let config = await readConfig(), next = {
|
|
2663
2847
|
...config,
|