@aiusage/cli 0.2.0 → 0.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/README.md +13 -6
- package/dist/cli.js +359 -170
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -32,16 +32,19 @@ aiusage --help
|
|
|
32
32
|
Local usage report. No cloud upload required.
|
|
33
33
|
|
|
34
34
|
```bash
|
|
35
|
-
aiusage report
|
|
36
|
-
aiusage report --range 1m
|
|
37
|
-
aiusage report --range 3m
|
|
38
|
-
aiusage report --range all
|
|
39
|
-
aiusage report --
|
|
35
|
+
aiusage report # default: last 7 days, English, compact
|
|
36
|
+
aiusage report --range 1m # last 30 days
|
|
37
|
+
aiusage report --range 3m # last 90 days
|
|
38
|
+
aiusage report --range all # all history
|
|
39
|
+
aiusage report --detail # show all columns, top models, pricing notes
|
|
40
|
+
aiusage report --lang zh # Chinese output
|
|
41
|
+
aiusage report --no-emoji # disable emoji in title
|
|
42
|
+
aiusage report --json # JSON output
|
|
40
43
|
```
|
|
41
44
|
|
|
42
45
|
Reads data from `~/.claude/projects` (Claude Code) and `~/.codex` (Codex).
|
|
43
46
|
|
|
44
|
-
|
|
47
|
+
**Compact mode** (default) shows Sources and Daily tables with merged Cache column and 2-decimal cost. **Detail mode** (`--detail`) expands all columns (CacheRead, CacheWrite, Reasoning), adds Top Models and Pricing Notes sections, and shows 4-decimal cost.
|
|
45
48
|
|
|
46
49
|
### scan
|
|
47
50
|
|
|
@@ -122,11 +125,15 @@ aiusage doctor
|
|
|
122
125
|
Manage local settings.
|
|
123
126
|
|
|
124
127
|
```bash
|
|
128
|
+
aiusage config set lang zh # default language: en or zh
|
|
129
|
+
aiusage config set emoji false # disable emoji in report title
|
|
125
130
|
aiusage config set device.alias "MacBook Pro 工作机"
|
|
126
131
|
aiusage config set privacy.projectVisibility masked
|
|
127
132
|
aiusage config set project.alias /Users/me/Projects/MyApp MyApp
|
|
128
133
|
```
|
|
129
134
|
|
|
135
|
+
CLI flags (`--lang`, `--no-emoji`) override config values for a single run.
|
|
136
|
+
|
|
130
137
|
## Configuration
|
|
131
138
|
|
|
132
139
|
Config file: `~/.aiusage/config.json`
|
package/dist/cli.js
CHANGED
|
@@ -364,7 +364,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
364
364
|
} catch {
|
|
365
365
|
continue;
|
|
366
366
|
}
|
|
367
|
-
let messages = session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.
|
|
367
|
+
let messages = session.messages ?? session.history ?? session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.model ?? session.data?.model ?? "unknown", fallbackTs = session.createTime ?? session.startTime ?? session.data?.createTime;
|
|
368
368
|
for (let msg of messages) {
|
|
369
369
|
let tokens = extractTokens(msg);
|
|
370
370
|
if (!tokens) continue;
|
|
@@ -394,7 +394,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
394
394
|
}
|
|
395
395
|
function extractTokens(msg) {
|
|
396
396
|
if (msg.tokens) {
|
|
397
|
-
let
|
|
397
|
+
let t2 = msg.tokens, cached2 = t2.cached ?? 0, input = Math.max((t2.input ?? 0) - cached2, 0), thoughts = t2.thoughts ?? 0, output = Math.max((t2.output ?? 0) - thoughts, 0);
|
|
398
398
|
return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
|
|
399
399
|
}
|
|
400
400
|
let u = msg.usage ?? msg.usageMetadata;
|
|
@@ -931,72 +931,6 @@ async function buildLocalReport(range, options = {}) {
|
|
|
931
931
|
pricingWarnings: [...pricingWarnings].sort()
|
|
932
932
|
};
|
|
933
933
|
}
|
|
934
|
-
function renderLocalReport(report) {
|
|
935
|
-
let lines = [];
|
|
936
|
-
if (lines.push("\u{1F4CA} AIUsage \u672C\u5730\u7EDF\u8BA1"), lines.push(`\u8303\u56F4 ${report.rangeLabel}`), lines.push(`\u65F6\u95F4 ${report.startDate ?? "-"} ~ ${report.endDate ?? "-"}`), lines.push(`\u8BF7\u6C42\u5929\u6570 ${fmtInt(report.requestedDays)}`), lines.push(`\u6709\u6548\u5929\u6570 ${fmtInt(report.daysWithData)}`), lines.push(""), report.requestedDays === 0 || report.daysWithData === 0)
|
|
937
|
-
return lines.push("\u8BE5\u8303\u56F4\u6682\u65E0\u672C\u5730 token \u6570\u636E\u3002"), lines.join(`
|
|
938
|
-
`);
|
|
939
|
-
if (lines.push("Summary"), lines.push(renderTable(
|
|
940
|
-
["Metric", "Value"],
|
|
941
|
-
[
|
|
942
|
-
["Events", fmtInt(report.totals.eventCount)],
|
|
943
|
-
["Input", fmtToken(report.totals.inputTokens)],
|
|
944
|
-
["CacheRead", fmtToken(report.totals.cachedInputTokens)],
|
|
945
|
-
["CacheWrite", fmtToken(report.totals.cacheWriteTokens)],
|
|
946
|
-
["Output", fmtToken(report.totals.outputTokens)],
|
|
947
|
-
["Reasoning", fmtToken(report.totals.reasoningOutputTokens)],
|
|
948
|
-
["TotalTokens", fmtToken(report.totals.totalTokens)],
|
|
949
|
-
["CostUsd", fmtUsd(report.totals.estimatedCostUsd)]
|
|
950
|
-
],
|
|
951
|
-
["left", "right"]
|
|
952
|
-
)), lines.push(""), lines.push("By Source"), lines.push(renderTable(
|
|
953
|
-
["Source", "Events", "Input", "CacheRead", "CacheWrite", "Output", "Reasoning", "Total", "Cost"],
|
|
954
|
-
report.bySource.map((item) => [
|
|
955
|
-
item.source,
|
|
956
|
-
fmtInt(item.eventCount),
|
|
957
|
-
fmtToken(item.inputTokens),
|
|
958
|
-
fmtToken(item.cachedInputTokens),
|
|
959
|
-
fmtToken(item.cacheWriteTokens),
|
|
960
|
-
fmtToken(item.outputTokens),
|
|
961
|
-
fmtToken(item.reasoningOutputTokens),
|
|
962
|
-
fmtToken(item.totalTokens),
|
|
963
|
-
fmtUsd(item.estimatedCostUsd)
|
|
964
|
-
]),
|
|
965
|
-
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
966
|
-
)), lines.push(""), lines.push("By Day"), lines.push(renderTable(
|
|
967
|
-
["Date", "Events", "Input", "CacheRead", "CacheWrite", "Output", "Reasoning", "Total", "Cost"],
|
|
968
|
-
report.daily.map((item) => [
|
|
969
|
-
item.usageDate,
|
|
970
|
-
fmtInt(item.eventCount),
|
|
971
|
-
fmtToken(item.inputTokens),
|
|
972
|
-
fmtToken(item.cachedInputTokens),
|
|
973
|
-
fmtToken(item.cacheWriteTokens),
|
|
974
|
-
fmtToken(item.outputTokens),
|
|
975
|
-
fmtToken(item.reasoningOutputTokens),
|
|
976
|
-
fmtToken(item.totalTokens),
|
|
977
|
-
fmtUsd(item.estimatedCostUsd)
|
|
978
|
-
]),
|
|
979
|
-
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
980
|
-
)), lines.push(""), lines.push("Top Models"), lines.push(renderTable(
|
|
981
|
-
["Model", "Source", "Events", "Total", "Input", "Output", "Cost"],
|
|
982
|
-
report.byModel.slice(0, 12).map((item) => [
|
|
983
|
-
item.model,
|
|
984
|
-
item.source,
|
|
985
|
-
fmtInt(item.eventCount),
|
|
986
|
-
fmtToken(item.totalTokens),
|
|
987
|
-
fmtToken(item.inputTokens),
|
|
988
|
-
fmtToken(item.outputTokens),
|
|
989
|
-
fmtUsd(item.estimatedCostUsd)
|
|
990
|
-
]),
|
|
991
|
-
["left", "left", "right", "right", "right", "right", "right"]
|
|
992
|
-
)), report.pricingWarnings.length > 0) {
|
|
993
|
-
lines.push(""), lines.push("Pricing Notes");
|
|
994
|
-
for (let warning of report.pricingWarnings)
|
|
995
|
-
lines.push(`- ${warning}`);
|
|
996
|
-
}
|
|
997
|
-
return lines.join(`
|
|
998
|
-
`);
|
|
999
|
-
}
|
|
1000
934
|
function parseReportRange(value) {
|
|
1001
935
|
if (value === void 0 || value === !0) return "7d";
|
|
1002
936
|
if (value === "7d" || value === "1m" || value === "3m" || value === "all") return value;
|
|
@@ -1024,7 +958,46 @@ function buildPresetDates(range) {
|
|
|
1024
958
|
}
|
|
1025
959
|
async function discoverAllDates() {
|
|
1026
960
|
let dates = /* @__PURE__ */ new Set();
|
|
1027
|
-
return await Promise.all([
|
|
961
|
+
return await Promise.all([
|
|
962
|
+
discoverClaudeDates(dates),
|
|
963
|
+
discoverCodexDates(dates),
|
|
964
|
+
discoverGeminiDates(dates)
|
|
965
|
+
]), [...dates].sort();
|
|
966
|
+
}
|
|
967
|
+
async function discoverGeminiDates(dates) {
|
|
968
|
+
let baseDir = join10(homedir11(), ".gemini", "tmp"), files = [];
|
|
969
|
+
try {
|
|
970
|
+
await walkForGeminiJsonl(baseDir, files);
|
|
971
|
+
} catch {
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
for (let filePath of files) {
|
|
975
|
+
let content = await safeReadUtf8(filePath);
|
|
976
|
+
if (!content) continue;
|
|
977
|
+
let session;
|
|
978
|
+
try {
|
|
979
|
+
session = JSON.parse(content);
|
|
980
|
+
} catch {
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
let messages = session.messages ?? session.history ?? [];
|
|
984
|
+
for (let msg of messages) {
|
|
985
|
+
let ts = parseTimestamp3(msg.timestamp);
|
|
986
|
+
ts && dates.add(toDateKey3(ts));
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
async function walkForGeminiJsonl(dir, result) {
|
|
991
|
+
let entries;
|
|
992
|
+
try {
|
|
993
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
994
|
+
} catch {
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
for (let entry of entries) {
|
|
998
|
+
let fullPath = join10(dir, entry.name);
|
|
999
|
+
entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
|
|
1000
|
+
}
|
|
1028
1001
|
}
|
|
1029
1002
|
async function discoverClaudeDates(dates) {
|
|
1030
1003
|
let baseDir = join10(homedir11(), ".claude", "projects"), projectDirs;
|
|
@@ -1155,38 +1128,6 @@ function createEmptyTotals2() {
|
|
|
1155
1128
|
function mergeTotals(target, source) {
|
|
1156
1129
|
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;
|
|
1157
1130
|
}
|
|
1158
|
-
function fmtInt(value) {
|
|
1159
|
-
return value.toLocaleString("en-US");
|
|
1160
|
-
}
|
|
1161
|
-
function fmtToken(value) {
|
|
1162
|
-
let abs = Math.abs(value);
|
|
1163
|
-
return abs < 1e3 ? fmtInt(value) : abs < 1e6 ? formatCompact(value / 1e3, "K") : abs < 1e9 ? formatCompact(value / 1e6, "M") : formatCompact(value / 1e9, "B");
|
|
1164
|
-
}
|
|
1165
|
-
function fmtUsd(value) {
|
|
1166
|
-
return `$${value.toFixed(4)}`;
|
|
1167
|
-
}
|
|
1168
|
-
function formatCompact(value, suffix) {
|
|
1169
|
-
let digits = Math.abs(value) >= 100 ? 1 : 2;
|
|
1170
|
-
return `${value.toFixed(digits).replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1")}${suffix}`;
|
|
1171
|
-
}
|
|
1172
|
-
function renderTable(headers, rows, aligns) {
|
|
1173
|
-
if (rows.length === 0)
|
|
1174
|
-
return "(\u6682\u65E0\u6570\u636E)";
|
|
1175
|
-
let widths = headers.map(
|
|
1176
|
-
(header, index) => Math.max(
|
|
1177
|
-
header.length,
|
|
1178
|
-
...rows.map((row) => truncate(row[index] ?? "").length)
|
|
1179
|
-
)
|
|
1180
|
-
), formatRow = (row) => row.map((value, index) => {
|
|
1181
|
-
let cell = truncate(value ?? "", 42);
|
|
1182
|
-
return aligns[index] === "right" ? cell.padStart(widths[index], " ") : cell.padEnd(widths[index], " ");
|
|
1183
|
-
}).join(" "), divider = widths.map((width) => "-".repeat(width)).join(" ");
|
|
1184
|
-
return [formatRow(headers), divider, ...rows.map(formatRow)].join(`
|
|
1185
|
-
`);
|
|
1186
|
-
}
|
|
1187
|
-
function truncate(value, maxLength = 42) {
|
|
1188
|
-
return value.length <= maxLength ? value : `${value.slice(0, maxLength - 1)}\u2026`;
|
|
1189
|
-
}
|
|
1190
1131
|
var CLAUDE_PRICING = {
|
|
1191
1132
|
"claude-opus-4-6": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1192
1133
|
"claude-opus-4-5": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
@@ -1254,6 +1195,11 @@ var CLAUDE_PRICING = {
|
|
|
1254
1195
|
"text-embedding-3-large": { input: 0.13, cached_input: null, output: 0, estimated: !1 },
|
|
1255
1196
|
"text-embedding-ada-002": { input: 0.1, cached_input: null, output: 0, estimated: !1 },
|
|
1256
1197
|
"codex-mini-latest": { input: 1.5, cached_input: 0.375, output: 6, estimated: !1 }
|
|
1198
|
+
}, GEMINI_PRICING = {
|
|
1199
|
+
"gemini-3-flash": { input: 0.1, cache_read: 0.025, output: 0.4 },
|
|
1200
|
+
"gemini-2.0-flash": { input: 0.1, cache_read: 0.025, output: 0.4 },
|
|
1201
|
+
"gemini-1.5-flash": { input: 0.075, cache_read: 0.01875, output: 0.3 },
|
|
1202
|
+
"gemini-1.5-pro": { input: 3.5, cache_read: 0.875, output: 10.5 }
|
|
1257
1203
|
};
|
|
1258
1204
|
function toBreakdownTotals(breakdown, warnings) {
|
|
1259
1205
|
let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings);
|
|
@@ -1284,6 +1230,13 @@ function calculateBreakdownCost(breakdown, warnings) {
|
|
|
1284
1230
|
let pricing = OPENAI_PRICING[resolved.model];
|
|
1285
1231
|
return resolved.normalized ? warnings.add(`${breakdown.model} \u5DF2\u6309 ${resolved.model} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`) : pricing.estimated && warnings.add(`${breakdown.model} \u672A\u5728\u516C\u5F00\u4EF7\u76EE\u8868\u5355\u5217\uFF0C\u5F53\u524D\u6309 GPT-5 \u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`), breakdown.inputTokens / 1e6 * pricing.input + breakdown.cachedInputTokens / 1e6 * (pricing.cached_input ?? 0) + breakdown.outputTokens / 1e6 * pricing.output;
|
|
1286
1232
|
}
|
|
1233
|
+
if (breakdown.provider === "google" && breakdown.product === "gemini-cli") {
|
|
1234
|
+
let resolved = resolveModel(breakdown.model, GEMINI_PRICING);
|
|
1235
|
+
if (!resolved)
|
|
1236
|
+
return warnings.add(`Gemini \u6A21\u578B ${breakdown.model} \u672A\u914D\u7F6E\u516C\u5F00\u5355\u4EF7\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`), 0;
|
|
1237
|
+
let pricing = GEMINI_PRICING[resolved.model];
|
|
1238
|
+
return resolved.normalized && warnings.add(`${breakdown.model} \u5DF2\u6309 ${resolved.model} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`), breakdown.inputTokens / 1e6 * pricing.input + breakdown.cachedInputTokens / 1e6 * pricing.cache_read + breakdown.outputTokens / 1e6 * pricing.output;
|
|
1239
|
+
}
|
|
1287
1240
|
return warnings.add(`${breakdown.provider}/${breakdown.product} \u6682\u65E0\u672C\u5730\u5B9A\u4EF7\u7B56\u7565\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`), 0;
|
|
1288
1241
|
}
|
|
1289
1242
|
function resolveModel(model, pricingTable) {
|
|
@@ -1295,6 +1248,190 @@ function resolveModel(model, pricingTable) {
|
|
|
1295
1248
|
return null;
|
|
1296
1249
|
}
|
|
1297
1250
|
|
|
1251
|
+
// src/i18n.ts
|
|
1252
|
+
var en = {
|
|
1253
|
+
reportTitle: "AIUsage Report",
|
|
1254
|
+
period: "Period",
|
|
1255
|
+
events: "Events",
|
|
1256
|
+
tokens: "Tokens",
|
|
1257
|
+
cost: "Cost",
|
|
1258
|
+
sources: "Sources",
|
|
1259
|
+
daily: "Daily",
|
|
1260
|
+
topModels: "Top Models",
|
|
1261
|
+
pricingNotes: "Pricing Notes",
|
|
1262
|
+
noData: "No token data in this range.",
|
|
1263
|
+
rangeLast7d: "Last 7 days",
|
|
1264
|
+
rangeLast1m: "Last 30 days",
|
|
1265
|
+
rangeLast3m: "Last 90 days",
|
|
1266
|
+
rangeAll: "All time",
|
|
1267
|
+
hdrSource: "Source",
|
|
1268
|
+
hdrDate: "Date",
|
|
1269
|
+
hdrModel: "Model",
|
|
1270
|
+
hdrEvents: "Events",
|
|
1271
|
+
hdrInput: "Input",
|
|
1272
|
+
hdrCache: "Cache",
|
|
1273
|
+
hdrCacheRead: "CacheRead",
|
|
1274
|
+
hdrCacheWrite: "CacheWrite",
|
|
1275
|
+
hdrOutput: "Output",
|
|
1276
|
+
hdrReasoning: "Reasoning",
|
|
1277
|
+
hdrTotal: "Total",
|
|
1278
|
+
hdrCost: "Cost"
|
|
1279
|
+
}, zh = {
|
|
1280
|
+
reportTitle: "AIUsage \u62A5\u544A",
|
|
1281
|
+
period: "\u65F6\u6BB5",
|
|
1282
|
+
events: "\u4E8B\u4EF6",
|
|
1283
|
+
tokens: "\u4EE4\u724C",
|
|
1284
|
+
cost: "\u8D39\u7528",
|
|
1285
|
+
sources: "\u6765\u6E90",
|
|
1286
|
+
daily: "\u6BCF\u65E5",
|
|
1287
|
+
topModels: "\u6A21\u578B\u6392\u884C",
|
|
1288
|
+
pricingNotes: "\u5B9A\u4EF7\u8BF4\u660E",
|
|
1289
|
+
noData: "\u8BE5\u8303\u56F4\u6682\u65E0 token \u6570\u636E\u3002",
|
|
1290
|
+
rangeLast7d: "\u6700\u8FD1 7 \u5929",
|
|
1291
|
+
rangeLast1m: "\u6700\u8FD1 30 \u5929",
|
|
1292
|
+
rangeLast3m: "\u6700\u8FD1 90 \u5929",
|
|
1293
|
+
rangeAll: "\u5168\u90E8\u5386\u53F2",
|
|
1294
|
+
hdrSource: "\u6765\u6E90",
|
|
1295
|
+
hdrDate: "\u65E5\u671F",
|
|
1296
|
+
hdrModel: "\u6A21\u578B",
|
|
1297
|
+
hdrEvents: "\u4E8B\u4EF6",
|
|
1298
|
+
hdrInput: "\u8F93\u5165",
|
|
1299
|
+
hdrCache: "\u7F13\u5B58",
|
|
1300
|
+
hdrCacheRead: "\u7F13\u5B58\u8BFB",
|
|
1301
|
+
hdrCacheWrite: "\u7F13\u5B58\u5199",
|
|
1302
|
+
hdrOutput: "\u8F93\u51FA",
|
|
1303
|
+
hdrReasoning: "\u63A8\u7406",
|
|
1304
|
+
hdrTotal: "\u5408\u8BA1",
|
|
1305
|
+
hdrCost: "\u8D39\u7528"
|
|
1306
|
+
}, tables = { en, zh };
|
|
1307
|
+
function t(lang) {
|
|
1308
|
+
return tables[lang];
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// src/render.ts
|
|
1312
|
+
function renderReport(report, opts) {
|
|
1313
|
+
let s = t(opts.lang), lines = [], title = opts.emoji ? `\u{1F4CA} ${s.reportTitle}` : s.reportTitle;
|
|
1314
|
+
lines.push(title), lines.push("\u2500".repeat(title.length));
|
|
1315
|
+
let rangeLabel = getRangeLabel2(report.range, opts.lang), periodStart = report.startDate ? fmtDateShort(report.startDate) : "-", periodEnd = report.endDate ? fmtDateShort(report.endDate) : "-";
|
|
1316
|
+
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)
|
|
1317
|
+
return lines.push(""), lines.push(s.noData), lines.join(`
|
|
1318
|
+
`);
|
|
1319
|
+
if (lines.push(""), lines.push(s.sources), opts.detail ? lines.push(renderTable(
|
|
1320
|
+
[s.hdrSource, s.hdrEvents, s.hdrInput, s.hdrCacheRead, s.hdrCacheWrite, s.hdrOutput, s.hdrReasoning, s.hdrTotal, s.hdrCost],
|
|
1321
|
+
report.bySource.map((r) => [
|
|
1322
|
+
r.source,
|
|
1323
|
+
fmtInt(r.eventCount),
|
|
1324
|
+
fmtToken(r.inputTokens),
|
|
1325
|
+
fmtToken(r.cachedInputTokens),
|
|
1326
|
+
fmtToken(r.cacheWriteTokens),
|
|
1327
|
+
fmtToken(r.outputTokens),
|
|
1328
|
+
fmtToken(r.reasoningOutputTokens),
|
|
1329
|
+
fmtToken(r.totalTokens),
|
|
1330
|
+
fmtUsd(r.estimatedCostUsd, !0)
|
|
1331
|
+
]),
|
|
1332
|
+
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
1333
|
+
)) : lines.push(renderTable(
|
|
1334
|
+
[s.hdrSource, s.hdrEvents, s.hdrInput, s.hdrCache, s.hdrOutput, s.hdrTotal, s.hdrCost],
|
|
1335
|
+
report.bySource.map((r) => [
|
|
1336
|
+
r.source,
|
|
1337
|
+
fmtInt(r.eventCount),
|
|
1338
|
+
fmtToken(r.inputTokens),
|
|
1339
|
+
fmtToken(r.cachedInputTokens + r.cacheWriteTokens),
|
|
1340
|
+
fmtToken(r.outputTokens),
|
|
1341
|
+
fmtToken(r.totalTokens),
|
|
1342
|
+
fmtUsd(r.estimatedCostUsd, !1)
|
|
1343
|
+
]),
|
|
1344
|
+
["left", "right", "right", "right", "right", "right", "right"]
|
|
1345
|
+
)), lines.push(""), lines.push(s.daily), opts.detail ? lines.push(renderTable(
|
|
1346
|
+
[s.hdrDate, s.hdrEvents, s.hdrInput, s.hdrCacheRead, s.hdrCacheWrite, s.hdrOutput, s.hdrReasoning, s.hdrTotal, s.hdrCost],
|
|
1347
|
+
report.daily.map((r) => [
|
|
1348
|
+
r.usageDate,
|
|
1349
|
+
fmtInt(r.eventCount),
|
|
1350
|
+
fmtToken(r.inputTokens),
|
|
1351
|
+
fmtToken(r.cachedInputTokens),
|
|
1352
|
+
fmtToken(r.cacheWriteTokens),
|
|
1353
|
+
fmtToken(r.outputTokens),
|
|
1354
|
+
fmtToken(r.reasoningOutputTokens),
|
|
1355
|
+
fmtToken(r.totalTokens),
|
|
1356
|
+
fmtUsd(r.estimatedCostUsd, !0)
|
|
1357
|
+
]),
|
|
1358
|
+
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
1359
|
+
)) : lines.push(renderTable(
|
|
1360
|
+
[s.hdrDate, s.hdrEvents, s.hdrInput, s.hdrCache, s.hdrOutput, s.hdrTotal, s.hdrCost],
|
|
1361
|
+
report.daily.map((r) => [
|
|
1362
|
+
r.usageDate,
|
|
1363
|
+
fmtInt(r.eventCount),
|
|
1364
|
+
fmtToken(r.inputTokens),
|
|
1365
|
+
fmtToken(r.cachedInputTokens + r.cacheWriteTokens),
|
|
1366
|
+
fmtToken(r.outputTokens),
|
|
1367
|
+
fmtToken(r.totalTokens),
|
|
1368
|
+
fmtUsd(r.estimatedCostUsd, !1)
|
|
1369
|
+
]),
|
|
1370
|
+
["left", "right", "right", "right", "right", "right", "right"]
|
|
1371
|
+
)), opts.detail && report.byModel.length > 0 && (lines.push(""), lines.push(s.topModels), lines.push(renderTable(
|
|
1372
|
+
[s.hdrModel, s.hdrSource, s.hdrEvents, s.hdrTotal, s.hdrInput, s.hdrOutput, s.hdrCost],
|
|
1373
|
+
report.byModel.slice(0, 12).map((r) => [
|
|
1374
|
+
r.model,
|
|
1375
|
+
r.source,
|
|
1376
|
+
fmtInt(r.eventCount),
|
|
1377
|
+
fmtToken(r.totalTokens),
|
|
1378
|
+
fmtToken(r.inputTokens),
|
|
1379
|
+
fmtToken(r.outputTokens),
|
|
1380
|
+
fmtUsd(r.estimatedCostUsd, !0)
|
|
1381
|
+
]),
|
|
1382
|
+
["left", "left", "right", "right", "right", "right", "right"]
|
|
1383
|
+
))), opts.detail && report.pricingWarnings.length > 0) {
|
|
1384
|
+
lines.push(""), lines.push(s.pricingNotes);
|
|
1385
|
+
for (let w of report.pricingWarnings)
|
|
1386
|
+
lines.push(`- ${w}`);
|
|
1387
|
+
}
|
|
1388
|
+
return lines.join(`
|
|
1389
|
+
`);
|
|
1390
|
+
}
|
|
1391
|
+
function getRangeLabel2(range, lang) {
|
|
1392
|
+
let s = t(lang);
|
|
1393
|
+
switch (range) {
|
|
1394
|
+
case "7d":
|
|
1395
|
+
return s.rangeLast7d;
|
|
1396
|
+
case "1m":
|
|
1397
|
+
return s.rangeLast1m;
|
|
1398
|
+
case "3m":
|
|
1399
|
+
return s.rangeLast3m;
|
|
1400
|
+
case "all":
|
|
1401
|
+
return s.rangeAll;
|
|
1402
|
+
default:
|
|
1403
|
+
return range;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
function renderTable(headers, rows, aligns) {
|
|
1407
|
+
if (rows.length === 0) return "(no data)";
|
|
1408
|
+
let widths = headers.map(
|
|
1409
|
+
(h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
|
|
1410
|
+
), fmtRow = (row) => row.map((val, i) => {
|
|
1411
|
+
let cell = val ?? "";
|
|
1412
|
+
return aligns[i] === "right" ? cell.padStart(widths[i]) : cell.padEnd(widths[i]);
|
|
1413
|
+
}).join(" "), divider = widths.map((w) => "\u2500".repeat(w)).join(" ");
|
|
1414
|
+
return [fmtRow(headers), divider, ...rows.map(fmtRow)].join(`
|
|
1415
|
+
`);
|
|
1416
|
+
}
|
|
1417
|
+
function fmtInt(n) {
|
|
1418
|
+
return n.toLocaleString("en-US");
|
|
1419
|
+
}
|
|
1420
|
+
function fmtToken(n) {
|
|
1421
|
+
let abs = Math.abs(n);
|
|
1422
|
+
return abs < 1e3 ? fmtInt(n) : abs < 1e6 ? fmtCompact(n / 1e3, "K") : abs < 1e9 ? fmtCompact(n / 1e6, "M") : fmtCompact(n / 1e9, "B");
|
|
1423
|
+
}
|
|
1424
|
+
function fmtCompact(value, suffix) {
|
|
1425
|
+
let digits = Math.abs(value) >= 100 ? 1 : 2;
|
|
1426
|
+
return `${value.toFixed(digits).replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1")}${suffix}`;
|
|
1427
|
+
}
|
|
1428
|
+
function fmtUsd(value, detail) {
|
|
1429
|
+
return `$${value.toFixed(detail ? 4 : 2)}`;
|
|
1430
|
+
}
|
|
1431
|
+
function fmtDateShort(dateStr) {
|
|
1432
|
+
return (/* @__PURE__ */ new Date(dateStr + "T00:00:00")).toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1298
1435
|
// src/config.ts
|
|
1299
1436
|
import { mkdir, readFile as readFile12, writeFile } from "node:fs/promises";
|
|
1300
1437
|
import { homedir as homedir12, hostname } from "node:os";
|
|
@@ -1303,10 +1440,30 @@ var CONFIG_DIR = join11(homedir12(), ".aiusage"), CONFIG_PATH = join11(CONFIG_DI
|
|
|
1303
1440
|
function getConfigPath() {
|
|
1304
1441
|
return CONFIG_PATH;
|
|
1305
1442
|
}
|
|
1443
|
+
function migrateConfig(config) {
|
|
1444
|
+
if (config.targets || !config.apiBaseUrl) return config;
|
|
1445
|
+
let target = {
|
|
1446
|
+
name: "default",
|
|
1447
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
1448
|
+
siteId: config.siteId,
|
|
1449
|
+
deviceToken: config.deviceToken,
|
|
1450
|
+
lastSuccessfulUploadAt: config.lastSuccessfulUploadAt
|
|
1451
|
+
};
|
|
1452
|
+
return {
|
|
1453
|
+
deviceId: config.deviceId,
|
|
1454
|
+
deviceAlias: config.deviceAlias,
|
|
1455
|
+
lookbackDays: config.lookbackDays,
|
|
1456
|
+
projectAliases: config.projectAliases,
|
|
1457
|
+
privacy: config.privacy,
|
|
1458
|
+
lang: config.lang,
|
|
1459
|
+
emoji: config.emoji,
|
|
1460
|
+
targets: [target]
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1306
1463
|
async function readConfig() {
|
|
1307
1464
|
try {
|
|
1308
1465
|
let raw = await readFile12(CONFIG_PATH, "utf-8");
|
|
1309
|
-
return JSON.parse(raw);
|
|
1466
|
+
return migrateConfig(JSON.parse(raw));
|
|
1310
1467
|
} catch {
|
|
1311
1468
|
return {};
|
|
1312
1469
|
}
|
|
@@ -1324,18 +1481,28 @@ function detectDeviceId() {
|
|
|
1324
1481
|
function getLocalTimezone() {
|
|
1325
1482
|
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1326
1483
|
}
|
|
1484
|
+
function findTarget(config, name) {
|
|
1485
|
+
let targets = config.targets ?? [];
|
|
1486
|
+
return name ? targets.find((t2) => t2.name === name) : targets[0];
|
|
1487
|
+
}
|
|
1488
|
+
function findTargetOrThrow(config, name) {
|
|
1489
|
+
let target = findTarget(config, name);
|
|
1490
|
+
if (!target)
|
|
1491
|
+
throw new Error(
|
|
1492
|
+
name ? `\u672A\u627E\u5230\u76EE\u6807 "${name}"\uFF0C\u53EF\u7528: ${(config.targets ?? []).map((t2) => t2.name).join(", ") || "(\u65E0)"}` : "\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll"
|
|
1493
|
+
);
|
|
1494
|
+
return target;
|
|
1495
|
+
}
|
|
1496
|
+
function upsertTarget(config, target) {
|
|
1497
|
+
let next = structuredClone(config), targets = next.targets ?? [], idx = targets.findIndex((t2) => t2.name === target.name);
|
|
1498
|
+
return idx >= 0 ? targets[idx] = target : targets.push(target), next.targets = targets, next;
|
|
1499
|
+
}
|
|
1327
1500
|
function setConfigValue(config, keyPath, values) {
|
|
1328
1501
|
let next = structuredClone(config);
|
|
1329
|
-
if (keyPath === "server" || keyPath === "apiBaseUrl")
|
|
1330
|
-
return next.apiBaseUrl = normalizeServerUrl(requireSingleValue(keyPath, values)), next;
|
|
1331
|
-
if (keyPath === "siteId")
|
|
1332
|
-
return next.siteId = requireSingleValue(keyPath, values), next;
|
|
1333
1502
|
if (keyPath === "device.id")
|
|
1334
1503
|
return next.deviceId = requireSingleValue(keyPath, values), next;
|
|
1335
1504
|
if (keyPath === "device.alias")
|
|
1336
1505
|
return next.deviceAlias = requireSingleValue(keyPath, values), next;
|
|
1337
|
-
if (keyPath === "device.token")
|
|
1338
|
-
return next.deviceToken = requireSingleValue(keyPath, values), next;
|
|
1339
1506
|
if (keyPath === "lookbackDays")
|
|
1340
1507
|
return next.lookbackDays = parsePositiveInt(requireSingleValue(keyPath, values), keyPath), next;
|
|
1341
1508
|
if (keyPath === "privacy.projectVisibility") {
|
|
@@ -1351,6 +1518,18 @@ function setConfigValue(config, keyPath, values) {
|
|
|
1351
1518
|
if (!alias) throw new Error("project.alias \u522B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
1352
1519
|
return next.projectAliases = { ...next.projectAliases ?? {}, [from]: alias }, next;
|
|
1353
1520
|
}
|
|
1521
|
+
if (keyPath === "lang") {
|
|
1522
|
+
let value = requireSingleValue(keyPath, values);
|
|
1523
|
+
if (value !== "en" && value !== "zh")
|
|
1524
|
+
throw new Error("lang only supports en or zh");
|
|
1525
|
+
return next.lang = value, next;
|
|
1526
|
+
}
|
|
1527
|
+
if (keyPath === "emoji") {
|
|
1528
|
+
let value = requireSingleValue(keyPath, values);
|
|
1529
|
+
if (value !== "true" && value !== "false")
|
|
1530
|
+
throw new Error("emoji only supports true or false");
|
|
1531
|
+
return next.emoji = value === "true", next;
|
|
1532
|
+
}
|
|
1354
1533
|
throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u9879: ${keyPath}`);
|
|
1355
1534
|
}
|
|
1356
1535
|
function requireSingleValue(keyPath, values) {
|
|
@@ -1662,33 +1841,22 @@ async function runDoctor() {
|
|
|
1662
1841
|
} catch {
|
|
1663
1842
|
checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "fail", message: "\u672A\u627E\u5230\uFF0C\u8BF7\u5148\u6267\u884C aiusage init" });
|
|
1664
1843
|
}
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
["deviceToken", "\u8BBE\u5907\u4EE4\u724C", "\u8BF7\u6267\u884C aiusage enroll"]
|
|
1670
|
-
];
|
|
1671
|
-
for (let [key, label, hint] of fields) {
|
|
1672
|
-
let value = config[key];
|
|
1673
|
-
if (value) {
|
|
1674
|
-
let display = key === "deviceToken" ? `${String(value).slice(0, 12)}\u2026` : String(value);
|
|
1675
|
-
checks.push({ name: label, status: "ok", message: display });
|
|
1676
|
-
} else
|
|
1677
|
-
checks.push({
|
|
1678
|
-
name: label,
|
|
1679
|
-
status: key === "deviceToken" ? "fail" : "warn",
|
|
1680
|
-
message: `\u672A\u914D\u7F6E\uFF0C${hint}`
|
|
1681
|
-
});
|
|
1682
|
-
}
|
|
1683
|
-
if (config.apiBaseUrl)
|
|
1684
|
-
try {
|
|
1685
|
-
let health = await fetchHealth(config.apiBaseUrl);
|
|
1686
|
-
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "ok", message: `${health.siteId} (v${health.version})` });
|
|
1687
|
-
} catch (err) {
|
|
1688
|
-
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "fail", message: err instanceof Error ? err.message : String(err) });
|
|
1689
|
-
}
|
|
1844
|
+
config.deviceId ? checks.push({ name: "\u8BBE\u5907 ID", status: "ok", message: config.deviceId }) : checks.push({ name: "\u8BBE\u5907 ID", status: "warn", message: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage init" });
|
|
1845
|
+
let targets = config.targets ?? [];
|
|
1846
|
+
if (targets.length === 0)
|
|
1847
|
+
checks.push({ name: "\u4E0A\u62A5\u76EE\u6807", status: "warn", message: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage enroll" });
|
|
1690
1848
|
else
|
|
1691
|
-
|
|
1849
|
+
for (let target of targets) {
|
|
1850
|
+
let prefix = `[${target.name}]`;
|
|
1851
|
+
target.deviceToken ? checks.push({ name: `${prefix} \u8BBE\u5907\u4EE4\u724C`, status: "ok", message: `${target.deviceToken.slice(0, 12)}\u2026` }) : checks.push({ name: `${prefix} \u8BBE\u5907\u4EE4\u724C`, status: "fail", message: "\u672A\u6CE8\u518C" });
|
|
1852
|
+
try {
|
|
1853
|
+
let health = await fetchHealth(target.apiBaseUrl);
|
|
1854
|
+
checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "ok", message: health.siteId });
|
|
1855
|
+
} catch (err) {
|
|
1856
|
+
checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "fail", message: err instanceof Error ? err.message : String(err) });
|
|
1857
|
+
}
|
|
1858
|
+
target.lastSuccessfulUploadAt ? checks.push({ name: `${prefix} \u4E0A\u6B21\u540C\u6B65`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ name: `${prefix} \u4E0A\u6B21\u540C\u6B65`, status: "warn", message: "\u6682\u65E0\u8BB0\u5F55" });
|
|
1859
|
+
}
|
|
1692
1860
|
let scannerDirs = [
|
|
1693
1861
|
[join13(homedir14(), ".claude", "projects"), "Claude \u65E5\u5FD7"],
|
|
1694
1862
|
[join13(homedir14(), ".codex"), "Codex \u65E5\u5FD7"]
|
|
@@ -1704,7 +1872,7 @@ async function runDoctor() {
|
|
|
1704
1872
|
name: "\u5B9A\u65F6\u540C\u6B65",
|
|
1705
1873
|
status: "ok",
|
|
1706
1874
|
message: schedule.intervalLabel ? `\u6BCF ${schedule.intervalLabel}` : "\u5DF2\u542F\u7528"
|
|
1707
|
-
}) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }),
|
|
1875
|
+
}) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }), checks;
|
|
1708
1876
|
}
|
|
1709
1877
|
|
|
1710
1878
|
// src/cli.ts
|
|
@@ -1720,7 +1888,7 @@ try {
|
|
|
1720
1888
|
await runReport(parsed.flags);
|
|
1721
1889
|
} else if (command === "health") {
|
|
1722
1890
|
let parsed = parseArgs(argv.slice(1));
|
|
1723
|
-
await runHealth(parsed.flags
|
|
1891
|
+
await runHealth(parsed.flags);
|
|
1724
1892
|
} else if (command === "enroll") {
|
|
1725
1893
|
let parsed = parseArgs(argv.slice(1));
|
|
1726
1894
|
await runEnroll(parsed.flags);
|
|
@@ -1781,26 +1949,34 @@ async function runReport(flags) {
|
|
|
1781
1949
|
console.log(JSON.stringify(report, null, 2));
|
|
1782
1950
|
return;
|
|
1783
1951
|
}
|
|
1784
|
-
|
|
1952
|
+
let lang = (typeof flags.lang == "string" ? flags.lang : config.lang) || "en";
|
|
1953
|
+
if (lang !== "en" && lang !== "zh") throw new Error("--lang only supports en or zh");
|
|
1954
|
+
let emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
|
|
1955
|
+
console.log(renderReport(report, { lang, emoji, detail }));
|
|
1785
1956
|
}
|
|
1786
1957
|
function fmt(n) {
|
|
1787
1958
|
return n.toLocaleString("en-US");
|
|
1788
1959
|
}
|
|
1789
|
-
async function runHealth(
|
|
1790
|
-
let config = await readConfig()
|
|
1960
|
+
async function runHealth(flags) {
|
|
1961
|
+
let config = await readConfig();
|
|
1962
|
+
if (typeof flags.server == "string") {
|
|
1963
|
+
let health2 = await fetchHealth(normalizeServerUrl(flags.server));
|
|
1964
|
+
console.log(JSON.stringify(health2, null, 2));
|
|
1965
|
+
return;
|
|
1966
|
+
}
|
|
1967
|
+
let targetName = resolveOptionalString(flags.target, void 0), target = findTargetOrThrow(config, targetName), health = await fetchHealth(target.apiBaseUrl);
|
|
1791
1968
|
console.log(JSON.stringify(health, null, 2));
|
|
1792
1969
|
}
|
|
1793
1970
|
async function runEnroll(flags) {
|
|
1794
|
-
let config = await readConfig(), apiBaseUrl = resolveServer(flags.server,
|
|
1795
|
-
|
|
1796
|
-
...config,
|
|
1971
|
+
let config = await readConfig(), apiBaseUrl = resolveServer(flags.server, void 0), siteId = resolveRequiredString(flags["site-id"] ?? flags.siteId, void 0, "\u7F3A\u5C11 --site-id"), enrollToken = resolveRequiredString(flags["enroll-token"], void 0, "\u7F3A\u5C11 --enroll-token"), deviceId = resolveOptionalString(flags["device-id"], config.deviceId) ?? detectDeviceId(), deviceAlias = resolveOptionalString(flags["device-name"] ?? flags["device-alias"], config.deviceAlias), targetName = resolveOptionalString(flags.target ?? flags.name, void 0) ?? deriveTargetName(apiBaseUrl), response = await enrollDevice(apiBaseUrl, { siteId, deviceId, deviceAlias, enrollToken }), target = {
|
|
1972
|
+
name: targetName,
|
|
1797
1973
|
apiBaseUrl,
|
|
1798
1974
|
siteId,
|
|
1799
|
-
deviceId,
|
|
1800
|
-
deviceAlias,
|
|
1801
1975
|
deviceToken: response.deviceToken,
|
|
1802
|
-
|
|
1803
|
-
}
|
|
1976
|
+
lastSuccessfulUploadAt: void 0
|
|
1977
|
+
}, next = upsertTarget(config, target);
|
|
1978
|
+
next.deviceId = deviceId, next.deviceAlias = deviceAlias, next.lookbackDays = config.lookbackDays ?? 7, await writeConfig(next), console.log(JSON.stringify({
|
|
1979
|
+
target: targetName,
|
|
1804
1980
|
siteId: response.siteId,
|
|
1805
1981
|
deviceId: response.deviceId,
|
|
1806
1982
|
issuedAt: response.issuedAt,
|
|
@@ -1808,7 +1984,10 @@ async function runEnroll(flags) {
|
|
|
1808
1984
|
}, null, 2));
|
|
1809
1985
|
}
|
|
1810
1986
|
async function runSync(flags) {
|
|
1811
|
-
let config = await readConfig(),
|
|
1987
|
+
let config = await readConfig(), allTargets = config.targets ?? [];
|
|
1988
|
+
if (allTargets.length === 0)
|
|
1989
|
+
throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
|
|
1990
|
+
let deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C enroll"), targetName = resolveOptionalString(flags.target, void 0), targets = targetName ? [findTargetOrThrow(config, targetName)] : allTargets, requestedDate = typeof flags.date == "string" ? flags.date : void 0, fromDate = typeof flags.from == "string" ? flags.from : void 0, toDate = typeof flags.to == "string" ? flags.to : void 0, includeToday = !!flags.today, targetDates;
|
|
1812
1991
|
if (requestedDate)
|
|
1813
1992
|
targetDates = [requestedDate];
|
|
1814
1993
|
else if (fromDate)
|
|
@@ -1824,35 +2003,38 @@ async function runSync(flags) {
|
|
|
1824
2003
|
return;
|
|
1825
2004
|
}
|
|
1826
2005
|
console.log(`\u53D1\u73B0 ${allDays.length} \u5929\u6709\u6570\u636E\uFF0C\u5F00\u59CB\u4E0A\u4F20 ...`);
|
|
1827
|
-
let
|
|
1828
|
-
for (let
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
)
|
|
1836
|
-
|
|
2006
|
+
let uploadResults = [];
|
|
2007
|
+
for (let target of targets) {
|
|
2008
|
+
if (!target.deviceToken) {
|
|
2009
|
+
console.log(`\u8DF3\u8FC7 "${target.name}"\uFF1A\u672A\u6CE8\u518C\uFF08\u7F3A\u5C11 deviceToken\uFF09`);
|
|
2010
|
+
continue;
|
|
2011
|
+
}
|
|
2012
|
+
targets.length > 1 && console.log(`\u4E0A\u4F20\u81F3 "${target.name}" (${target.apiBaseUrl}) ...`);
|
|
2013
|
+
let BATCH_SIZE = 30, totalProcessed = 0, allCostSummary = {};
|
|
2014
|
+
for (let i = 0; i < allDays.length; i += BATCH_SIZE) {
|
|
2015
|
+
let batch = allDays.slice(i, i + BATCH_SIZE), totalBatches = Math.ceil(allDays.length / BATCH_SIZE);
|
|
2016
|
+
if (totalBatches > 1) {
|
|
2017
|
+
let batchNum = Math.floor(i / BATCH_SIZE) + 1;
|
|
2018
|
+
console.log(` \u6279\u6B21 ${batchNum}/${totalBatches}: ${batch[0].usageDate} ~ ${batch[batch.length - 1].usageDate}`);
|
|
2019
|
+
}
|
|
2020
|
+
let response = await uploadDailyUsage(
|
|
2021
|
+
target.apiBaseUrl,
|
|
2022
|
+
{ siteId: target.siteId, deviceId, deviceAlias: config.deviceAlias, deviceToken: target.deviceToken },
|
|
2023
|
+
batch
|
|
2024
|
+
);
|
|
2025
|
+
totalProcessed += response.daysProcessed, Object.assign(allCostSummary, response.costSummary);
|
|
2026
|
+
}
|
|
2027
|
+
target.lastSuccessfulUploadAt = (/* @__PURE__ */ new Date()).toISOString(), uploadResults.push({ target: target.name, daysProcessed: totalProcessed, costSummary: allCostSummary });
|
|
1837
2028
|
}
|
|
1838
|
-
await writeConfig({
|
|
1839
|
-
|
|
1840
|
-
apiBaseUrl,
|
|
1841
|
-
siteId,
|
|
1842
|
-
deviceId,
|
|
1843
|
-
deviceToken,
|
|
1844
|
-
lastSuccessfulUploadAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1845
|
-
}), console.log(JSON.stringify({
|
|
2029
|
+
await writeConfig(config), console.log(JSON.stringify({
|
|
2030
|
+
targets: uploadResults.map((r) => r.target),
|
|
1846
2031
|
uploadedDays: allDays.map((day) => day.usageDate),
|
|
1847
|
-
|
|
1848
|
-
costSummary: allCostSummary
|
|
2032
|
+
results: uploadResults
|
|
1849
2033
|
}, null, 2));
|
|
1850
2034
|
}
|
|
1851
2035
|
async function runInit(flags) {
|
|
1852
2036
|
let config = await readConfig(), next = {
|
|
1853
2037
|
...config,
|
|
1854
|
-
apiBaseUrl: typeof flags.server == "string" ? normalizeServerUrl(flags.server) : config.apiBaseUrl,
|
|
1855
|
-
siteId: resolveOptionalString(flags["site-id"] ?? flags.siteId, config.siteId),
|
|
1856
2038
|
deviceId: resolveOptionalString(flags["device-id"], config.deviceId) ?? detectDeviceId(),
|
|
1857
2039
|
deviceAlias: resolveOptionalString(flags["device-name"] ?? flags["device-alias"], config.deviceAlias) ?? hostname3(),
|
|
1858
2040
|
lookbackDays: typeof flags.lookback == "string" ? parsePositiveInt2(flags.lookback, "--lookback") : config.lookbackDays ?? 7
|
|
@@ -1887,7 +2069,7 @@ async function runConfigSet(args) {
|
|
|
1887
2069
|
function printHelp() {
|
|
1888
2070
|
let initialized = existsSync(getConfigPath());
|
|
1889
2071
|
console.log(`aiusage v${getVersion()}
|
|
1890
|
-
`), console.log("Usage: aiusage <command>"), console.log(""), console.log("Commands:"), console.log(" aiusage init [--
|
|
2072
|
+
`), console.log("Usage: aiusage <command>"), console.log(""), console.log("Commands:"), console.log(" aiusage init [--device-id ID] [--device-name NAME] [--lookback N]"), console.log(" aiusage enroll --server URL --site-id ID --enroll-token TOKEN [--target NAME]"), console.log(" aiusage sync [--target NAME] [--date YYYY-MM-DD] [--from YYYY-MM-DD [--to YYYY-MM-DD]] [--lookback N] [--today]"), console.log(" aiusage health [--target NAME] [--server URL]"), console.log(" aiusage scan [--date YYYY-MM-DD] [--json]"), console.log(" aiusage report [--range 7d|1m|3m|all] [--detail] [--lang en|zh] [--no-emoji] [--json]"), console.log(" aiusage schedule [on|off|status] [--every 5m]"), console.log(" aiusage doctor"), console.log(" aiusage config set <key> <value...>"), console.log(""), console.log(`\u914D\u7F6E\u6587\u4EF6: ${getConfigPath()}${initialized ? "" : " (\u5C1A\u672A\u521D\u59CB\u5316)"}`);
|
|
1891
2073
|
}
|
|
1892
2074
|
function parseArgs(args) {
|
|
1893
2075
|
let flags = {}, positionals = [];
|
|
@@ -1938,6 +2120,13 @@ function getClosedDates(lookbackDays) {
|
|
|
1938
2120
|
}
|
|
1939
2121
|
return dates;
|
|
1940
2122
|
}
|
|
2123
|
+
function deriveTargetName(url) {
|
|
2124
|
+
try {
|
|
2125
|
+
return new URL(url).hostname.split(".")[0] || "default";
|
|
2126
|
+
} catch {
|
|
2127
|
+
return "default";
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
1941
2130
|
function resolveServer(flagValue, configValue) {
|
|
1942
2131
|
let value = resolveOptionalString(flagValue, configValue);
|
|
1943
2132
|
if (!value) throw new Error("\u7F3A\u5C11\u670D\u52A1\u7AEF\u5730\u5740\uFF0C\u8BF7\u4F20 --server \u6216\u5148\u6267\u884C init");
|