@aiusage/cli 1.2.3 → 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 +273 -67
- 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";
|
|
@@ -28,9 +28,13 @@ function parseTs(value) {
|
|
|
28
28
|
function dateKey(date) {
|
|
29
29
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
let parts =
|
|
33
|
-
return
|
|
31
|
+
function resolveProjectFields(rawPath, aliases) {
|
|
32
|
+
let parts = rawPath.split("/").filter(Boolean), display = parts[parts.length - 1] || "unknown", alias = aliases?.[rawPath] ?? aliases?.[display];
|
|
33
|
+
return {
|
|
34
|
+
project: rawPath || "unknown",
|
|
35
|
+
projectDisplay: display,
|
|
36
|
+
projectAlias: alias
|
|
37
|
+
};
|
|
34
38
|
}
|
|
35
39
|
async function walkFiles(dir, ext) {
|
|
36
40
|
let result = [];
|
|
@@ -91,7 +95,7 @@ async function runWithConcurrency(items, concurrency, worker) {
|
|
|
91
95
|
}
|
|
92
96
|
|
|
93
97
|
// src/scanners/claude.ts
|
|
94
|
-
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;
|
|
95
99
|
function getClaudeProjectDirs(claudeDir) {
|
|
96
100
|
if (claudeDir) return [claudeDir];
|
|
97
101
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
@@ -115,18 +119,18 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
115
119
|
continue;
|
|
116
120
|
}
|
|
117
121
|
for (let projDir of projectDirs) {
|
|
118
|
-
let projectPath = join2(baseDir, projDir),
|
|
122
|
+
let projectPath = join2(baseDir, projDir), fields = resolveProject(projectPath, projectAliases), jsonlFiles = [];
|
|
119
123
|
try {
|
|
120
124
|
await walkForJsonl(projectPath, jsonlFiles);
|
|
121
125
|
} catch {
|
|
122
126
|
continue;
|
|
123
127
|
}
|
|
124
128
|
for (let filePath of jsonlFiles)
|
|
125
|
-
fileJobs.push({ filePath,
|
|
129
|
+
fileJobs.push({ filePath, projectFields: fields });
|
|
126
130
|
}
|
|
127
131
|
}
|
|
128
132
|
await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
|
|
129
|
-
await processJsonlFile(job.filePath, job.
|
|
133
|
+
await processJsonlFile(job.filePath, job.projectFields, targetDateSet, projectAliases, deduped);
|
|
130
134
|
});
|
|
131
135
|
for (let [dedupeKey, usage] of deduped.entries()) {
|
|
132
136
|
let [usageDate] = dedupeKey.split("|", 1), grouped = groupedByDate.get(usageDate);
|
|
@@ -138,6 +142,8 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
138
142
|
channel: "cli",
|
|
139
143
|
model: usage.model,
|
|
140
144
|
project: usage.project,
|
|
145
|
+
projectDisplay: usage.projectDisplay,
|
|
146
|
+
projectAlias: usage.projectAlias,
|
|
141
147
|
eventCount: 1,
|
|
142
148
|
inputTokens: usage.inputTokens,
|
|
143
149
|
cachedInputTokens: usage.cachedInputTokens,
|
|
@@ -149,11 +155,22 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
149
155
|
costUSD: usage.costUSD
|
|
150
156
|
});
|
|
151
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
|
+
}
|
|
152
169
|
return new Map(
|
|
153
170
|
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
154
171
|
);
|
|
155
172
|
}
|
|
156
|
-
async function processJsonlFile(filePath,
|
|
173
|
+
async function processJsonlFile(filePath, fallbackFields, targetDateSet, projectAliases, deduped) {
|
|
157
174
|
let fh;
|
|
158
175
|
try {
|
|
159
176
|
fh = await open(filePath, "r");
|
|
@@ -185,12 +202,14 @@ async function processJsonlFile(filePath, fallbackProject, targetDateSet, projec
|
|
|
185
202
|
if (!requestId) continue;
|
|
186
203
|
let usage = message.usage, model = normalizeModelName(rawModel);
|
|
187
204
|
usage.speed === "fast" && (model = `${model}-fast`);
|
|
188
|
-
let
|
|
205
|
+
let recordFields = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackFields, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
|
|
189
206
|
cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
|
|
190
207
|
let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
|
|
191
208
|
existing ? (existing.model = model, existing.inputTokens = Math.max(existing.inputTokens, usage.input_tokens ?? 0), existing.cacheWrite5mTokens = Math.max(existing.cacheWrite5mTokens, cache5m), existing.cacheWrite1hTokens = Math.max(existing.cacheWrite1hTokens, cache1h), existing.cachedInputTokens = Math.max(existing.cachedInputTokens, usage.cache_read_input_tokens ?? 0), existing.outputTokens = Math.max(existing.outputTokens, usage.output_tokens ?? 0), existing.costUSD = Math.max(existing.costUSD, costUSD)) : deduped.set(dedupeKey, {
|
|
192
209
|
model,
|
|
193
|
-
project:
|
|
210
|
+
project: recordFields.project,
|
|
211
|
+
projectDisplay: recordFields.projectDisplay,
|
|
212
|
+
projectAlias: recordFields.projectAlias,
|
|
194
213
|
inputTokens: usage.input_tokens ?? 0,
|
|
195
214
|
cacheWrite5mTokens: cache5m,
|
|
196
215
|
cacheWrite1hTokens: cache1h,
|
|
@@ -203,6 +222,48 @@ async function processJsonlFile(filePath, fallbackProject, targetDateSet, projec
|
|
|
203
222
|
await fh.close();
|
|
204
223
|
}
|
|
205
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
|
+
}
|
|
206
267
|
function parseTimestamp(value) {
|
|
207
268
|
if (!value) return null;
|
|
208
269
|
try {
|
|
@@ -221,8 +282,8 @@ function extractProjectFromCwd(cwd) {
|
|
|
221
282
|
return parts[parts.length - 1] || "unknown";
|
|
222
283
|
}
|
|
223
284
|
function resolveProject(rawPath, aliases) {
|
|
224
|
-
let project = extractProjectFromCwd(rawPath);
|
|
225
|
-
return
|
|
285
|
+
let project = extractProjectFromCwd(rawPath), alias = aliases?.[rawPath] ?? aliases?.[project];
|
|
286
|
+
return { project: rawPath, projectDisplay: project, projectAlias: alias };
|
|
226
287
|
}
|
|
227
288
|
async function walkForJsonl(dir, result) {
|
|
228
289
|
let entries = await readdir2(dir, { withFileTypes: !0 });
|
|
@@ -262,7 +323,7 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
|
|
|
262
323
|
let rl = createInterface2({
|
|
263
324
|
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
264
325
|
crlfDelay: 1 / 0
|
|
265
|
-
}), currentModel = "unknown",
|
|
326
|
+
}), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
|
|
266
327
|
for await (let line of rl) {
|
|
267
328
|
if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
|
|
268
329
|
let record;
|
|
@@ -273,7 +334,7 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
|
|
|
273
334
|
}
|
|
274
335
|
if (record.type === "turn_context") {
|
|
275
336
|
let rawModel = record.payload?.model ?? currentModel;
|
|
276
|
-
rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (
|
|
337
|
+
rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
|
|
277
338
|
continue;
|
|
278
339
|
}
|
|
279
340
|
if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
|
|
@@ -295,13 +356,15 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
|
|
|
295
356
|
previousTotal = total;
|
|
296
357
|
let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), grouped = groupedByDate.get(usageDate);
|
|
297
358
|
if (!grouped) continue;
|
|
298
|
-
let key = `${currentModel}|${
|
|
359
|
+
let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
|
|
299
360
|
existing ? (existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += last.cached_input_tokens ?? 0, existing.outputTokens += last.output_tokens ?? 0, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0) : grouped.set(key, {
|
|
300
361
|
provider: "openai",
|
|
301
362
|
product: "codex",
|
|
302
363
|
channel: "cli",
|
|
303
364
|
model: currentModel,
|
|
304
|
-
project:
|
|
365
|
+
project: currentProjectFields.project,
|
|
366
|
+
projectDisplay: currentProjectFields.projectDisplay,
|
|
367
|
+
projectAlias: currentProjectFields.projectAlias,
|
|
305
368
|
eventCount: 1,
|
|
306
369
|
inputTokens: nonCachedInput,
|
|
307
370
|
cachedInputTokens: last.cached_input_tokens ?? 0,
|
|
@@ -350,13 +413,9 @@ function toDateKey2(date) {
|
|
|
350
413
|
let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
|
|
351
414
|
return `${year}-${month}-${day}`;
|
|
352
415
|
}
|
|
353
|
-
function extractProject(cwd, aliases) {
|
|
354
|
-
let parts = cwd.split("/").filter(Boolean), project = parts[parts.length - 1] || "unknown";
|
|
355
|
-
return aliases?.[cwd] ?? aliases?.[project] ?? project;
|
|
356
|
-
}
|
|
357
416
|
|
|
358
417
|
// src/scanners/copilot.ts
|
|
359
|
-
import { readFile } from "node:fs/promises";
|
|
418
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
360
419
|
import { join as join4 } from "node:path";
|
|
361
420
|
import { homedir as homedir3 } from "node:os";
|
|
362
421
|
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
@@ -366,11 +425,11 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
366
425
|
for (let filePath of files) {
|
|
367
426
|
let content;
|
|
368
427
|
try {
|
|
369
|
-
content = await
|
|
428
|
+
content = await readFile2(filePath, "utf-8");
|
|
370
429
|
} catch {
|
|
371
430
|
continue;
|
|
372
431
|
}
|
|
373
|
-
let
|
|
432
|
+
let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
|
|
374
433
|
`);
|
|
375
434
|
for (let line of lines) {
|
|
376
435
|
if (!line.trim()) continue;
|
|
@@ -382,7 +441,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
382
441
|
}
|
|
383
442
|
if (obj.type === "session.start" || obj.type === "session.resume") {
|
|
384
443
|
let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
|
|
385
|
-
raw && (
|
|
444
|
+
raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
|
|
386
445
|
}
|
|
387
446
|
if (obj.type !== "session.shutdown") continue;
|
|
388
447
|
let ts = parseTs(obj.timestamp);
|
|
@@ -397,13 +456,15 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
397
456
|
let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
|
|
398
457
|
accumulate(
|
|
399
458
|
dayMap,
|
|
400
|
-
`${model}|${
|
|
459
|
+
`${model}|${sessionProjectFields.project}`,
|
|
401
460
|
{
|
|
402
461
|
provider: "github",
|
|
403
462
|
product: "copilot-cli",
|
|
404
463
|
channel: "cli",
|
|
405
464
|
model,
|
|
406
|
-
project:
|
|
465
|
+
project: sessionProjectFields.project,
|
|
466
|
+
projectDisplay: sessionProjectFields.projectDisplay,
|
|
467
|
+
projectAlias: sessionProjectFields.projectAlias,
|
|
407
468
|
inputTokens: 0,
|
|
408
469
|
cachedInputTokens: 0,
|
|
409
470
|
cacheWriteTokens: 0,
|
|
@@ -565,6 +626,7 @@ async function scanCursorDates(targetDates) {
|
|
|
565
626
|
channel: "ide",
|
|
566
627
|
model,
|
|
567
628
|
project: "unknown",
|
|
629
|
+
projectDisplay: "unknown",
|
|
568
630
|
eventCount: 1,
|
|
569
631
|
inputTokens,
|
|
570
632
|
cachedInputTokens: cacheRead,
|
|
@@ -577,7 +639,7 @@ async function scanCursorDates(targetDates) {
|
|
|
577
639
|
}
|
|
578
640
|
|
|
579
641
|
// src/scanners/gemini.ts
|
|
580
|
-
import { readFile as
|
|
642
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
581
643
|
import { join as join6 } from "node:path";
|
|
582
644
|
import { homedir as homedir5 } from "node:os";
|
|
583
645
|
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -587,7 +649,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
587
649
|
for (let filePath of files) {
|
|
588
650
|
let content;
|
|
589
651
|
try {
|
|
590
|
-
content = await
|
|
652
|
+
content = await readFile3(filePath, "utf-8");
|
|
591
653
|
} catch {
|
|
592
654
|
continue;
|
|
593
655
|
}
|
|
@@ -613,6 +675,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
613
675
|
channel: "cli",
|
|
614
676
|
model,
|
|
615
677
|
project: "unknown",
|
|
678
|
+
projectDisplay: "unknown",
|
|
616
679
|
inputTokens: 0,
|
|
617
680
|
cachedInputTokens: 0,
|
|
618
681
|
cacheWriteTokens: 0,
|
|
@@ -639,7 +702,7 @@ function extractTokens(msg) {
|
|
|
639
702
|
}
|
|
640
703
|
|
|
641
704
|
// src/scanners/qwen.ts
|
|
642
|
-
import { readFile as
|
|
705
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
643
706
|
import { join as join7, basename as basename2, dirname } from "node:path";
|
|
644
707
|
import { homedir as homedir6 } from "node:os";
|
|
645
708
|
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
@@ -649,7 +712,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
649
712
|
for (let filePath of files) {
|
|
650
713
|
let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
|
|
651
714
|
try {
|
|
652
|
-
content = await
|
|
715
|
+
content = await readFile4(filePath, "utf-8");
|
|
653
716
|
} catch {
|
|
654
717
|
continue;
|
|
655
718
|
}
|
|
@@ -673,16 +736,18 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
673
736
|
}
|
|
674
737
|
let u = obj.usageMetadata;
|
|
675
738
|
if (!u) continue;
|
|
676
|
-
let model = obj.model ?? "unknown",
|
|
739
|
+
let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
|
|
677
740
|
accumulate(
|
|
678
741
|
dayMap,
|
|
679
|
-
`${model}|${project}`,
|
|
742
|
+
`${model}|${fields.project}`,
|
|
680
743
|
{
|
|
681
744
|
provider: "alibaba",
|
|
682
745
|
product: "qwen-code",
|
|
683
746
|
channel: "cli",
|
|
684
747
|
model,
|
|
685
|
-
project,
|
|
748
|
+
project: fields.project,
|
|
749
|
+
projectDisplay: fields.projectDisplay,
|
|
750
|
+
projectAlias: fields.projectAlias,
|
|
686
751
|
inputTokens: 0,
|
|
687
752
|
cachedInputTokens: 0,
|
|
688
753
|
cacheWriteTokens: 0,
|
|
@@ -697,7 +762,7 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
697
762
|
}
|
|
698
763
|
|
|
699
764
|
// src/scanners/kimi.ts
|
|
700
|
-
import { readFile as
|
|
765
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
701
766
|
import { join as join8, basename as basename3, dirname as dirname2 } from "node:path";
|
|
702
767
|
import { homedir as homedir7 } from "node:os";
|
|
703
768
|
async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -705,9 +770,9 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
|
705
770
|
if (files.length === 0) return emptyResult(dates);
|
|
706
771
|
let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
707
772
|
for (let filePath of files) {
|
|
708
|
-
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir),
|
|
773
|
+
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
|
|
709
774
|
try {
|
|
710
|
-
content = await
|
|
775
|
+
content = await readFile5(filePath, "utf-8");
|
|
711
776
|
} catch {
|
|
712
777
|
continue;
|
|
713
778
|
}
|
|
@@ -736,13 +801,15 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
|
736
801
|
let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
|
|
737
802
|
accumulate(
|
|
738
803
|
dayMap,
|
|
739
|
-
`${currentModel}|${project}`,
|
|
804
|
+
`${currentModel}|${projectFields.project}`,
|
|
740
805
|
{
|
|
741
806
|
provider: "moonshot",
|
|
742
807
|
product: "kimi-code",
|
|
743
808
|
channel: "cli",
|
|
744
809
|
model: currentModel,
|
|
745
|
-
project,
|
|
810
|
+
project: projectFields.project,
|
|
811
|
+
projectDisplay: projectFields.projectDisplay,
|
|
812
|
+
projectAlias: projectFields.projectAlias,
|
|
746
813
|
inputTokens: 0,
|
|
747
814
|
cachedInputTokens: 0,
|
|
748
815
|
cacheWriteTokens: 0,
|
|
@@ -757,12 +824,12 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
|
757
824
|
}
|
|
758
825
|
function resolveKimiProject(hash, workspaceMap, aliases) {
|
|
759
826
|
let wsPath = workspaceMap.get(hash);
|
|
760
|
-
return wsPath ?
|
|
827
|
+
return wsPath ? resolveProjectFields(wsPath, aliases) : resolveProjectFields(hash, aliases);
|
|
761
828
|
}
|
|
762
829
|
async function loadWorkspaceMap(kimiHome) {
|
|
763
830
|
let map = /* @__PURE__ */ new Map();
|
|
764
831
|
try {
|
|
765
|
-
let raw = await
|
|
832
|
+
let raw = await readFile5(join8(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
766
833
|
if (config.workspaces)
|
|
767
834
|
for (let [hash, info] of Object.entries(config.workspaces))
|
|
768
835
|
info.path && map.set(hash, info.path);
|
|
@@ -772,7 +839,7 @@ async function loadWorkspaceMap(kimiHome) {
|
|
|
772
839
|
}
|
|
773
840
|
|
|
774
841
|
// src/scanners/amp.ts
|
|
775
|
-
import { readFile as
|
|
842
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
776
843
|
import { join as join9 } from "node:path";
|
|
777
844
|
import { homedir as homedir8 } from "node:os";
|
|
778
845
|
function resolveAmpDir(baseDir) {
|
|
@@ -792,7 +859,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
|
792
859
|
for (let filePath of threadFiles) {
|
|
793
860
|
let raw;
|
|
794
861
|
try {
|
|
795
|
-
raw = await
|
|
862
|
+
raw = await readFile6(filePath, "utf-8");
|
|
796
863
|
} catch {
|
|
797
864
|
continue;
|
|
798
865
|
}
|
|
@@ -832,6 +899,7 @@ function processLedger(thread, events, dates, grouped) {
|
|
|
832
899
|
channel: "cli",
|
|
833
900
|
model,
|
|
834
901
|
project: "unknown",
|
|
902
|
+
projectDisplay: "unknown",
|
|
835
903
|
inputTokens: 0,
|
|
836
904
|
cachedInputTokens: 0,
|
|
837
905
|
cacheWriteTokens: 0,
|
|
@@ -863,6 +931,7 @@ function processMessages(thread, dates, grouped) {
|
|
|
863
931
|
channel: "cli",
|
|
864
932
|
model,
|
|
865
933
|
project: "unknown",
|
|
934
|
+
projectDisplay: "unknown",
|
|
866
935
|
inputTokens: 0,
|
|
867
936
|
cachedInputTokens: 0,
|
|
868
937
|
cacheWriteTokens: 0,
|
|
@@ -875,7 +944,7 @@ function processMessages(thread, dates, grouped) {
|
|
|
875
944
|
}
|
|
876
945
|
|
|
877
946
|
// src/scanners/droid.ts
|
|
878
|
-
import { readFile as
|
|
947
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
879
948
|
import { join as join10, dirname as dirname3, basename as basename4 } from "node:path";
|
|
880
949
|
import { homedir as homedir9 } from "node:os";
|
|
881
950
|
function extractProjectFromSlug(dirPath) {
|
|
@@ -889,7 +958,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
889
958
|
for (let jsonlPath of files) {
|
|
890
959
|
let content;
|
|
891
960
|
try {
|
|
892
|
-
content = await
|
|
961
|
+
content = await readFile7(jsonlPath, "utf-8");
|
|
893
962
|
} catch {
|
|
894
963
|
continue;
|
|
895
964
|
}
|
|
@@ -908,7 +977,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
908
977
|
if (!dayMap) continue;
|
|
909
978
|
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join10(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
910
979
|
try {
|
|
911
|
-
settingsRaw = await
|
|
980
|
+
settingsRaw = await readFile7(settingsPath, "utf-8");
|
|
912
981
|
} catch {
|
|
913
982
|
continue;
|
|
914
983
|
}
|
|
@@ -920,7 +989,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
920
989
|
}
|
|
921
990
|
let usage = settings.tokenUsage;
|
|
922
991
|
if (!usage) continue;
|
|
923
|
-
let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir),
|
|
992
|
+
let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
|
|
924
993
|
accumulate(
|
|
925
994
|
dayMap,
|
|
926
995
|
`${model}|${project}`,
|
|
@@ -930,6 +999,8 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
930
999
|
channel: "cli",
|
|
931
1000
|
model,
|
|
932
1001
|
project,
|
|
1002
|
+
projectDisplay: rawProject,
|
|
1003
|
+
projectAlias: alias,
|
|
933
1004
|
inputTokens: 0,
|
|
934
1005
|
cachedInputTokens: 0,
|
|
935
1006
|
cacheWriteTokens: 0,
|
|
@@ -943,7 +1014,7 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
943
1014
|
}
|
|
944
1015
|
|
|
945
1016
|
// src/scanners/opencode.ts
|
|
946
|
-
import { readFile as
|
|
1017
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
947
1018
|
import { homedir as homedir10 } from "node:os";
|
|
948
1019
|
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
949
1020
|
let dates = new Set(targetDates), dir = baseDir ?? `${homedir10()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
|
|
@@ -952,7 +1023,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
952
1023
|
for (let filePath of files) {
|
|
953
1024
|
let raw;
|
|
954
1025
|
try {
|
|
955
|
-
raw = await
|
|
1026
|
+
raw = await readFile8(filePath, "utf-8");
|
|
956
1027
|
} catch {
|
|
957
1028
|
continue;
|
|
958
1029
|
}
|
|
@@ -970,16 +1041,18 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
970
1041
|
if (!ts) continue;
|
|
971
1042
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
972
1043
|
if (!dayMap) continue;
|
|
973
|
-
let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root,
|
|
1044
|
+
let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, fields = rootPath ? resolveProjectFields(rootPath, projectAliases) : { project: "unknown", projectDisplay: "unknown" };
|
|
974
1045
|
accumulate(
|
|
975
1046
|
dayMap,
|
|
976
|
-
`${model}|${project}`,
|
|
1047
|
+
`${model}|${fields.project}`,
|
|
977
1048
|
{
|
|
978
1049
|
provider: "opencode",
|
|
979
1050
|
product: "opencode",
|
|
980
1051
|
channel: "cli",
|
|
981
1052
|
model,
|
|
982
|
-
project,
|
|
1053
|
+
project: fields.project,
|
|
1054
|
+
projectDisplay: fields.projectDisplay,
|
|
1055
|
+
projectAlias: fields.projectAlias,
|
|
983
1056
|
inputTokens: 0,
|
|
984
1057
|
cachedInputTokens: 0,
|
|
985
1058
|
cacheWriteTokens: 0,
|
|
@@ -993,7 +1066,7 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
993
1066
|
}
|
|
994
1067
|
|
|
995
1068
|
// src/scanners/pi.ts
|
|
996
|
-
import { readFile as
|
|
1069
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
997
1070
|
import { join as join11, basename as basename5, dirname as dirname4 } from "node:path";
|
|
998
1071
|
import { homedir as homedir11 } from "node:os";
|
|
999
1072
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
@@ -1003,11 +1076,11 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
1003
1076
|
for (let filePath of files) {
|
|
1004
1077
|
let content;
|
|
1005
1078
|
try {
|
|
1006
|
-
content = await
|
|
1079
|
+
content = await readFile9(filePath, "utf-8");
|
|
1007
1080
|
} catch {
|
|
1008
1081
|
continue;
|
|
1009
1082
|
}
|
|
1010
|
-
let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir),
|
|
1083
|
+
let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
|
|
1011
1084
|
for (let line of content.split(`
|
|
1012
1085
|
`)) {
|
|
1013
1086
|
if (!line.trim()) continue;
|
|
@@ -1018,7 +1091,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
1018
1091
|
continue;
|
|
1019
1092
|
}
|
|
1020
1093
|
if (obj.type === "session" && obj.cwd) {
|
|
1021
|
-
|
|
1094
|
+
sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
|
|
1022
1095
|
continue;
|
|
1023
1096
|
}
|
|
1024
1097
|
if (obj.type !== "message") continue;
|
|
@@ -1037,13 +1110,15 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
1037
1110
|
let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
|
|
1038
1111
|
accumulate(
|
|
1039
1112
|
dayMap,
|
|
1040
|
-
`${model}|${
|
|
1113
|
+
`${model}|${sessionProjectFields.project}`,
|
|
1041
1114
|
{
|
|
1042
1115
|
provider: "inflection",
|
|
1043
1116
|
product: "pi",
|
|
1044
1117
|
channel: "cli",
|
|
1045
1118
|
model,
|
|
1046
|
-
project:
|
|
1119
|
+
project: sessionProjectFields.project,
|
|
1120
|
+
projectDisplay: sessionProjectFields.projectDisplay,
|
|
1121
|
+
projectAlias: sessionProjectFields.projectAlias,
|
|
1047
1122
|
inputTokens: 0,
|
|
1048
1123
|
cachedInputTokens: 0,
|
|
1049
1124
|
cacheWriteTokens: 0,
|
|
@@ -1116,8 +1191,88 @@ function createEmptyTotals() {
|
|
|
1116
1191
|
};
|
|
1117
1192
|
}
|
|
1118
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
|
+
|
|
1119
1274
|
// src/report.ts
|
|
1120
|
-
import { readdir as readdir5, readFile as
|
|
1275
|
+
import { readdir as readdir5, readFile as readFile10 } from "node:fs/promises";
|
|
1121
1276
|
import { homedir as homedir12 } from "node:os";
|
|
1122
1277
|
import { join as join12 } from "node:path";
|
|
1123
1278
|
async function buildLocalReport(range, options = {}) {
|
|
@@ -1372,7 +1527,7 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
1372
1527
|
}
|
|
1373
1528
|
async function safeReadUtf8(filePath) {
|
|
1374
1529
|
try {
|
|
1375
|
-
return await
|
|
1530
|
+
return await readFile10(filePath, "utf-8");
|
|
1376
1531
|
} catch {
|
|
1377
1532
|
return null;
|
|
1378
1533
|
}
|
|
@@ -1725,7 +1880,7 @@ function fmtDateShort(dateStr) {
|
|
|
1725
1880
|
}
|
|
1726
1881
|
|
|
1727
1882
|
// src/config.ts
|
|
1728
|
-
import { mkdir, readFile as
|
|
1883
|
+
import { mkdir, readFile as readFile11, writeFile } from "node:fs/promises";
|
|
1729
1884
|
import { homedir as homedir13, hostname } from "node:os";
|
|
1730
1885
|
import { basename as basename6, join as join13 } from "node:path";
|
|
1731
1886
|
var CONFIG_DIR = join13(homedir13(), ".aiusage"), CONFIG_PATH = join13(CONFIG_DIR, "config.json");
|
|
@@ -1754,7 +1909,7 @@ function migrateConfig(config) {
|
|
|
1754
1909
|
}
|
|
1755
1910
|
async function readConfig() {
|
|
1756
1911
|
try {
|
|
1757
|
-
let raw = await
|
|
1912
|
+
let raw = await readFile11(CONFIG_PATH, "utf-8");
|
|
1758
1913
|
return migrateConfig(JSON.parse(raw));
|
|
1759
1914
|
} catch {
|
|
1760
1915
|
return {};
|
|
@@ -1822,6 +1977,12 @@ function setConfigValue(config, keyPath, values) {
|
|
|
1822
1977
|
throw new Error("emoji only supports true or false");
|
|
1823
1978
|
return next.emoji = value === "true", next;
|
|
1824
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
|
+
}
|
|
1825
1986
|
throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u9879: ${keyPath}`);
|
|
1826
1987
|
}
|
|
1827
1988
|
function requireSingleValue(keyPath, values) {
|
|
@@ -1920,7 +2081,7 @@ async function requestJson(url, init) {
|
|
|
1920
2081
|
}
|
|
1921
2082
|
|
|
1922
2083
|
// src/schedule.ts
|
|
1923
|
-
import { mkdir as mkdir2, readFile as
|
|
2084
|
+
import { mkdir as mkdir2, readFile as readFile12, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
1924
2085
|
import { execFile } from "node:child_process";
|
|
1925
2086
|
import { promisify } from "node:util";
|
|
1926
2087
|
import { homedir as homedir14, platform, tmpdir as tmpdir2 } from "node:os";
|
|
@@ -2024,7 +2185,7 @@ async function getLaunchdStatus() {
|
|
|
2024
2185
|
return { enabled: !1 };
|
|
2025
2186
|
}
|
|
2026
2187
|
try {
|
|
2027
|
-
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];
|
|
2028
2189
|
return {
|
|
2029
2190
|
enabled: !0,
|
|
2030
2191
|
interval,
|
|
@@ -2254,7 +2415,7 @@ async function runDoctor(lang = "zh") {
|
|
|
2254
2415
|
}
|
|
2255
2416
|
|
|
2256
2417
|
// src/project.ts
|
|
2257
|
-
import { open as open3, readdir as readdir7, readFile as
|
|
2418
|
+
import { open as open3, readdir as readdir7, readFile as readFile13 } from "node:fs/promises";
|
|
2258
2419
|
import { join as join16 } from "node:path";
|
|
2259
2420
|
import { homedir as homedir16 } from "node:os";
|
|
2260
2421
|
async function discoverProjects(projectAliases) {
|
|
@@ -2416,7 +2577,7 @@ async function discoverCopilotProjects() {
|
|
|
2416
2577
|
async function discoverGeminiProjects() {
|
|
2417
2578
|
let filePath = join16(homedir16(), ".gemini", "projects.json");
|
|
2418
2579
|
try {
|
|
2419
|
-
let raw = await
|
|
2580
|
+
let raw = await readFile13(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
2420
2581
|
if (!projects || typeof projects != "object") return [];
|
|
2421
2582
|
let names = [];
|
|
2422
2583
|
for (let [path, _name] of Object.entries(projects)) {
|
|
@@ -2493,6 +2654,9 @@ try {
|
|
|
2493
2654
|
let zh2 = (await readConfig()).lang === "zh";
|
|
2494
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;
|
|
2495
2656
|
}
|
|
2657
|
+
} else if (command === "import") {
|
|
2658
|
+
let parsed = parseArgs(argv.slice(1));
|
|
2659
|
+
await runImport(parsed.flags);
|
|
2496
2660
|
} else if (command === "setup")
|
|
2497
2661
|
console.log(`To deploy the server, clone the repo and run the setup wizard:
|
|
2498
2662
|
`), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
|
|
@@ -2528,7 +2692,7 @@ async function runScan(date, isJson) {
|
|
|
2528
2692
|
for (let [provider, breakdowns] of byProvider) {
|
|
2529
2693
|
console.log(`\u2500\u2500 ${provider} \u2500\u2500`);
|
|
2530
2694
|
for (let b of breakdowns.sort((a, c) => c.inputTokens - a.inputTokens))
|
|
2531
|
-
console.log(` ${b.model} | ${b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
|
|
2695
|
+
console.log(` ${b.model} | ${b.projectAlias ?? b.projectDisplay ?? b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
|
|
2532
2696
|
console.log();
|
|
2533
2697
|
}
|
|
2534
2698
|
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)}`);
|
|
@@ -2636,6 +2800,48 @@ async function runSync(flags) {
|
|
|
2636
2800
|
results: uploadResults
|
|
2637
2801
|
}, null, 2));
|
|
2638
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
|
+
}
|
|
2639
2845
|
async function runInit(flags) {
|
|
2640
2846
|
let config = await readConfig(), next = {
|
|
2641
2847
|
...config,
|