@aiusage/cli 0.3.0 → 0.4.1
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.zh-CN.md +153 -0
- package/dist/cli.js +221 -138
- package/package.json +1 -1
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# @aiusage/cli
|
|
2
|
+
|
|
3
|
+
`@aiusage/cli` 是 AIUsage 命令行工具,用于:
|
|
4
|
+
|
|
5
|
+
- 扫描本地 AI 编程工具的 Token 用量(Claude Code、Codex、Copilot CLI、Gemini CLI、Qwen Code、Kimi Code、Amp、Droid、OpenCode、Pi)
|
|
6
|
+
- 生成本地用量报告(最近 7 天、30 天、90 天或全部历史)
|
|
7
|
+
- 定时自动同步数据到 AIUsage Worker
|
|
8
|
+
- 诊断配置与连接问题
|
|
9
|
+
|
|
10
|
+
## 安装
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install -g @aiusage/cli
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
或通过 `npx` 直接运行:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @aiusage/cli --help
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
安装后:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
aiusage --help
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 命令
|
|
29
|
+
|
|
30
|
+
### report
|
|
31
|
+
|
|
32
|
+
本地用量报告,无需服务端。
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
aiusage report # 默认: 最近 7 天,英文,紧凑模式
|
|
36
|
+
aiusage report --range 1m # 最近 30 天
|
|
37
|
+
aiusage report --range 3m # 最近 90 天
|
|
38
|
+
aiusage report --range all # 全部历史
|
|
39
|
+
aiusage report --detail # 展示全部列、热门模型、定价说明
|
|
40
|
+
aiusage report --lang zh # 中文输出
|
|
41
|
+
aiusage report --no-emoji # 禁用标题 emoji
|
|
42
|
+
aiusage report --json # JSON 输出
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
**紧凑模式**(默认)显示来源和每日汇总表,合并缓存列,保留 2 位小数成本。**详细模式**(`--detail`)展开所有列(CacheRead、CacheWrite、Reasoning),增加热门模型和定价说明,显示 4 位小数成本。
|
|
46
|
+
|
|
47
|
+
### scan
|
|
48
|
+
|
|
49
|
+
扫描单日数据并打印明细。
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
aiusage scan --date 2026-03-31
|
|
53
|
+
aiusage scan --date 2026-03-31 --json
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
省略 `--date` 时默认扫描昨天。
|
|
57
|
+
|
|
58
|
+
### init
|
|
59
|
+
|
|
60
|
+
初始化本地配置。
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
aiusage init --server https://your-worker.example.com --site-id your-site-id
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### health
|
|
67
|
+
|
|
68
|
+
测试与 Worker 的连通性。
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
aiusage health
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### enroll
|
|
75
|
+
|
|
76
|
+
将本设备注册到 Worker。
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
aiusage enroll \
|
|
80
|
+
--server https://your-worker.example.com \
|
|
81
|
+
--site-id your-site-id \
|
|
82
|
+
--enroll-token your-enroll-token \
|
|
83
|
+
--device-name "MacBook Pro"
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### sync
|
|
87
|
+
|
|
88
|
+
上传用量数据到 Worker。默认覆盖最近 7 个已结束的日期。
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
aiusage sync
|
|
92
|
+
aiusage sync --today # 包含今日实时数据
|
|
93
|
+
aiusage sync --date 2026-03-31
|
|
94
|
+
aiusage sync --lookback 14
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
使用 `--today` 上传当日(未完成)数据。服务端使用 upsert,部分数据会在下次同步时更新。
|
|
98
|
+
|
|
99
|
+
### schedule
|
|
100
|
+
|
|
101
|
+
管理定时同步。macOS 使用 `launchd`,Linux 使用 `cron`。
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
aiusage schedule on # 启用,默认每 5 分钟
|
|
105
|
+
aiusage schedule on --every 30m # 自定义间隔
|
|
106
|
+
aiusage schedule off # 关闭
|
|
107
|
+
aiusage schedule status # 查看当前定时任务详情
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
支持间隔:`5m` – `1d`。定时同步始终包含今日实时数据(`--today`),确保看板数据及时更新。
|
|
111
|
+
|
|
112
|
+
`schedule status` 输出示例:
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
状态: 已启用
|
|
116
|
+
间隔: 每 5m
|
|
117
|
+
含今日: 是
|
|
118
|
+
命令: /usr/local/bin/node /usr/local/bin/aiusage sync --today
|
|
119
|
+
配置: ~/Library/LaunchAgents/com.aiusage.sync.plist
|
|
120
|
+
日志: ~/.aiusage/sync.log
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### doctor
|
|
124
|
+
|
|
125
|
+
运行诊断检查,包括配置、服务端连通性、扫描目录和定时任务状态。
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
aiusage doctor
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### config set
|
|
132
|
+
|
|
133
|
+
管理本地设置。
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
aiusage config set lang zh # 默认语言: en 或 zh
|
|
137
|
+
aiusage config set emoji false # 禁用报告标题 emoji
|
|
138
|
+
aiusage config set device.alias "MacBook Pro 工作机"
|
|
139
|
+
aiusage config set privacy.projectVisibility masked
|
|
140
|
+
aiusage config set project.alias /Users/me/Projects/MyApp MyApp
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
CLI 标志(`--lang`、`--no-emoji`)会覆盖配置值(仅当次生效)。
|
|
144
|
+
|
|
145
|
+
## 配置
|
|
146
|
+
|
|
147
|
+
配置文件:`~/.aiusage/config.json`
|
|
148
|
+
|
|
149
|
+
同步日志(定时任务启用时):`~/.aiusage/sync.log`
|
|
150
|
+
|
|
151
|
+
## 许可证
|
|
152
|
+
|
|
153
|
+
MIT
|
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;
|
|
@@ -759,49 +759,22 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
759
759
|
return finalize(grouped);
|
|
760
760
|
}
|
|
761
761
|
|
|
762
|
-
// src/scanners/
|
|
762
|
+
// src/scanners/pi.ts
|
|
763
763
|
import { readFile as readFile10 } from "node:fs/promises";
|
|
764
|
-
import { basename as basename5, dirname as dirname4 } from "node:path";
|
|
764
|
+
import { join as join10, basename as basename5, dirname as dirname4 } from "node:path";
|
|
765
765
|
import { homedir as homedir10 } from "node:os";
|
|
766
|
-
function
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
}
|
|
772
|
-
function resolveCached(u) {
|
|
773
|
-
return u.cacheRead ?? u.cache_read ?? u.cache_read_input_tokens ?? 0;
|
|
774
|
-
}
|
|
775
|
-
function agentNameFromPath(filePath) {
|
|
776
|
-
let sessionsDir = dirname4(filePath), agentDir = dirname4(sessionsDir);
|
|
777
|
-
return basename5(agentDir) || "unknown";
|
|
778
|
-
}
|
|
779
|
-
function collectBaseDirs(baseDir) {
|
|
780
|
-
if (baseDir) return [baseDir];
|
|
781
|
-
let home = homedir10();
|
|
782
|
-
return [
|
|
783
|
-
`${home}/.openclaw/agents`,
|
|
784
|
-
`${home}/.clawdbot`,
|
|
785
|
-
`${home}/.moltbot`,
|
|
786
|
-
`${home}/.moldbot`
|
|
787
|
-
];
|
|
788
|
-
}
|
|
789
|
-
async function scanOpenclawDates(targetDates, baseDir, projectAliases) {
|
|
790
|
-
let dates = new Set(targetDates), dirs = collectBaseDirs(baseDir), allFiles = [];
|
|
791
|
-
for (let d of dirs) {
|
|
792
|
-
let found = await walkFiles(d, ".jsonl");
|
|
793
|
-
allFiles = allFiles.concat(found);
|
|
794
|
-
}
|
|
795
|
-
if (allFiles.length === 0) return emptyResult(dates);
|
|
796
|
-
let grouped = initDateMap(dates);
|
|
797
|
-
for (let filePath of allFiles) {
|
|
766
|
+
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
767
|
+
let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
|
|
768
|
+
if (files.length === 0) return emptyResult(dates);
|
|
769
|
+
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
770
|
+
for (let filePath of files) {
|
|
798
771
|
let content;
|
|
799
772
|
try {
|
|
800
773
|
content = await readFile10(filePath, "utf-8");
|
|
801
774
|
} catch {
|
|
802
775
|
continue;
|
|
803
776
|
}
|
|
804
|
-
let
|
|
777
|
+
let parentDir = dirname4(filePath), encodedCwd = basename5(parentDir), sessionProject = extractProjectFromEncoded(encodedCwd);
|
|
805
778
|
for (let line of content.split(`
|
|
806
779
|
`)) {
|
|
807
780
|
if (!line.trim()) continue;
|
|
@@ -811,25 +784,33 @@ async function scanOpenclawDates(targetDates, baseDir, projectAliases) {
|
|
|
811
784
|
} catch {
|
|
812
785
|
continue;
|
|
813
786
|
}
|
|
787
|
+
if (obj.type === "session" && obj.cwd) {
|
|
788
|
+
sessionProject = projectFromPath(obj.cwd, projectAliases);
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
814
791
|
if (obj.type !== "message") continue;
|
|
815
792
|
let msg = obj.message;
|
|
816
793
|
if (!msg || msg.role !== "assistant") continue;
|
|
817
794
|
let usage = msg.usage;
|
|
818
|
-
if (!usage) continue;
|
|
819
|
-
let ts = parseTs(obj.timestamp
|
|
795
|
+
if (!usage || usage.input == null && usage.output == null) continue;
|
|
796
|
+
let ts = parseTs(obj.timestamp);
|
|
820
797
|
if (!ts) continue;
|
|
821
798
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
822
799
|
if (!dayMap) continue;
|
|
823
|
-
|
|
800
|
+
if (obj.id) {
|
|
801
|
+
if (seen.has(obj.id)) continue;
|
|
802
|
+
seen.add(obj.id);
|
|
803
|
+
}
|
|
804
|
+
let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
|
|
824
805
|
accumulate(
|
|
825
806
|
dayMap,
|
|
826
|
-
`${model}|${
|
|
807
|
+
`${model}|${sessionProject}`,
|
|
827
808
|
{
|
|
828
|
-
provider: "
|
|
829
|
-
product: "
|
|
809
|
+
provider: "inflection",
|
|
810
|
+
product: "pi",
|
|
830
811
|
channel: "cli",
|
|
831
812
|
model,
|
|
832
|
-
project,
|
|
813
|
+
project: sessionProject,
|
|
833
814
|
inputTokens: 0,
|
|
834
815
|
cachedInputTokens: 0,
|
|
835
816
|
cacheWriteTokens: 0,
|
|
@@ -842,6 +823,14 @@ async function scanOpenclawDates(targetDates, baseDir, projectAliases) {
|
|
|
842
823
|
}
|
|
843
824
|
return finalize(grouped);
|
|
844
825
|
}
|
|
826
|
+
function getSessionsDir() {
|
|
827
|
+
let envDir = process.env.PI_CODING_AGENT_DIR;
|
|
828
|
+
return envDir ? join10(envDir, "sessions") : join10(homedir10(), ".pi", "agent", "sessions");
|
|
829
|
+
}
|
|
830
|
+
function extractProjectFromEncoded(encoded) {
|
|
831
|
+
let parts = encoded.split("-").filter(Boolean);
|
|
832
|
+
return parts.length > 0 ? parts[parts.length - 1] : "unknown";
|
|
833
|
+
}
|
|
845
834
|
|
|
846
835
|
// src/scan.ts
|
|
847
836
|
async function scanDate(targetDate, options = {}) {
|
|
@@ -865,7 +854,7 @@ async function scanDates(targetDates, options = {}) {
|
|
|
865
854
|
scanAmpDates(uniqueDates, void 0, options.projectAliases),
|
|
866
855
|
scanDroidDates(uniqueDates, void 0, options.projectAliases),
|
|
867
856
|
scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
|
|
868
|
-
|
|
857
|
+
scanPiDates(uniqueDates, void 0, options.projectAliases)
|
|
869
858
|
], results = await Promise.all(scanners);
|
|
870
859
|
return uniqueDates.map((usageDate) => {
|
|
871
860
|
let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
|
|
@@ -896,7 +885,7 @@ function createEmptyTotals() {
|
|
|
896
885
|
// src/report.ts
|
|
897
886
|
import { readdir as readdir5, readFile as readFile11 } from "node:fs/promises";
|
|
898
887
|
import { homedir as homedir11 } from "node:os";
|
|
899
|
-
import { join as
|
|
888
|
+
import { join as join11 } from "node:path";
|
|
900
889
|
async function buildLocalReport(range, options = {}) {
|
|
901
890
|
let requestedDates = range === "all" ? await discoverAllDates() : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
|
|
902
891
|
for (let result of results) {
|
|
@@ -958,10 +947,49 @@ function buildPresetDates(range) {
|
|
|
958
947
|
}
|
|
959
948
|
async function discoverAllDates() {
|
|
960
949
|
let dates = /* @__PURE__ */ new Set();
|
|
961
|
-
return await Promise.all([
|
|
950
|
+
return await Promise.all([
|
|
951
|
+
discoverClaudeDates(dates),
|
|
952
|
+
discoverCodexDates(dates),
|
|
953
|
+
discoverGeminiDates(dates)
|
|
954
|
+
]), [...dates].sort();
|
|
955
|
+
}
|
|
956
|
+
async function discoverGeminiDates(dates) {
|
|
957
|
+
let baseDir = join11(homedir11(), ".gemini", "tmp"), files = [];
|
|
958
|
+
try {
|
|
959
|
+
await walkForGeminiJsonl(baseDir, files);
|
|
960
|
+
} catch {
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
for (let filePath of files) {
|
|
964
|
+
let content = await safeReadUtf8(filePath);
|
|
965
|
+
if (!content) continue;
|
|
966
|
+
let session;
|
|
967
|
+
try {
|
|
968
|
+
session = JSON.parse(content);
|
|
969
|
+
} catch {
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
let messages = session.messages ?? session.history ?? [];
|
|
973
|
+
for (let msg of messages) {
|
|
974
|
+
let ts = parseTimestamp3(msg.timestamp);
|
|
975
|
+
ts && dates.add(toDateKey3(ts));
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
async function walkForGeminiJsonl(dir, result) {
|
|
980
|
+
let entries;
|
|
981
|
+
try {
|
|
982
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
983
|
+
} catch {
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
for (let entry of entries) {
|
|
987
|
+
let fullPath = join11(dir, entry.name);
|
|
988
|
+
entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
|
|
989
|
+
}
|
|
962
990
|
}
|
|
963
991
|
async function discoverClaudeDates(dates) {
|
|
964
|
-
let baseDir =
|
|
992
|
+
let baseDir = join11(homedir11(), ".claude", "projects"), projectDirs;
|
|
965
993
|
try {
|
|
966
994
|
projectDirs = await readdir5(baseDir);
|
|
967
995
|
} catch {
|
|
@@ -970,7 +998,7 @@ async function discoverClaudeDates(dates) {
|
|
|
970
998
|
for (let projectDir of projectDirs) {
|
|
971
999
|
let jsonlFiles = [];
|
|
972
1000
|
try {
|
|
973
|
-
await walkForClaudeJsonl(
|
|
1001
|
+
await walkForClaudeJsonl(join11(baseDir, projectDir), jsonlFiles);
|
|
974
1002
|
} catch {
|
|
975
1003
|
continue;
|
|
976
1004
|
}
|
|
@@ -993,7 +1021,7 @@ async function discoverClaudeDates(dates) {
|
|
|
993
1021
|
}
|
|
994
1022
|
}
|
|
995
1023
|
async function discoverCodexDates(dates) {
|
|
996
|
-
let baseDir =
|
|
1024
|
+
let baseDir = join11(homedir11(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
997
1025
|
for (let filePath of files) {
|
|
998
1026
|
let content = await safeReadUtf8(filePath);
|
|
999
1027
|
if (content)
|
|
@@ -1015,17 +1043,17 @@ async function discoverCodexDates(dates) {
|
|
|
1015
1043
|
async function collectCodexSessionFiles(baseDir) {
|
|
1016
1044
|
let paths = [];
|
|
1017
1045
|
try {
|
|
1018
|
-
let archivedFiles = await readdir5(
|
|
1046
|
+
let archivedFiles = await readdir5(join11(baseDir, "archived_sessions"));
|
|
1019
1047
|
for (let file of archivedFiles)
|
|
1020
|
-
file.endsWith(".jsonl") && paths.push(
|
|
1048
|
+
file.endsWith(".jsonl") && paths.push(join11(baseDir, "archived_sessions", file));
|
|
1021
1049
|
} catch {
|
|
1022
1050
|
}
|
|
1023
|
-
return await walkForCodexJsonl(
|
|
1051
|
+
return await walkForCodexJsonl(join11(baseDir, "sessions"), paths), paths;
|
|
1024
1052
|
}
|
|
1025
1053
|
async function walkForClaudeJsonl(dir, result) {
|
|
1026
1054
|
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
1027
1055
|
for (let entry of entries) {
|
|
1028
|
-
let fullPath =
|
|
1056
|
+
let fullPath = join11(dir, entry.name);
|
|
1029
1057
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1030
1058
|
}
|
|
1031
1059
|
}
|
|
@@ -1037,7 +1065,7 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
1037
1065
|
return;
|
|
1038
1066
|
}
|
|
1039
1067
|
for (let entry of entries) {
|
|
1040
|
-
let fullPath =
|
|
1068
|
+
let fullPath = join11(dir, entry.name);
|
|
1041
1069
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1042
1070
|
}
|
|
1043
1071
|
}
|
|
@@ -1156,6 +1184,11 @@ var CLAUDE_PRICING = {
|
|
|
1156
1184
|
"text-embedding-3-large": { input: 0.13, cached_input: null, output: 0, estimated: !1 },
|
|
1157
1185
|
"text-embedding-ada-002": { input: 0.1, cached_input: null, output: 0, estimated: !1 },
|
|
1158
1186
|
"codex-mini-latest": { input: 1.5, cached_input: 0.375, output: 6, estimated: !1 }
|
|
1187
|
+
}, GEMINI_PRICING = {
|
|
1188
|
+
"gemini-3-flash": { input: 0.1, cache_read: 0.025, output: 0.4 },
|
|
1189
|
+
"gemini-2.0-flash": { input: 0.1, cache_read: 0.025, output: 0.4 },
|
|
1190
|
+
"gemini-1.5-flash": { input: 0.075, cache_read: 0.01875, output: 0.3 },
|
|
1191
|
+
"gemini-1.5-pro": { input: 3.5, cache_read: 0.875, output: 10.5 }
|
|
1159
1192
|
};
|
|
1160
1193
|
function toBreakdownTotals(breakdown, warnings) {
|
|
1161
1194
|
let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings);
|
|
@@ -1186,6 +1219,13 @@ function calculateBreakdownCost(breakdown, warnings) {
|
|
|
1186
1219
|
let pricing = OPENAI_PRICING[resolved.model];
|
|
1187
1220
|
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;
|
|
1188
1221
|
}
|
|
1222
|
+
if (breakdown.provider === "google" && breakdown.product === "gemini-cli") {
|
|
1223
|
+
let resolved = resolveModel(breakdown.model, GEMINI_PRICING);
|
|
1224
|
+
if (!resolved)
|
|
1225
|
+
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;
|
|
1226
|
+
let pricing = GEMINI_PRICING[resolved.model];
|
|
1227
|
+
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;
|
|
1228
|
+
}
|
|
1189
1229
|
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;
|
|
1190
1230
|
}
|
|
1191
1231
|
function resolveModel(model, pricingTable) {
|
|
@@ -1384,15 +1424,35 @@ function fmtDateShort(dateStr) {
|
|
|
1384
1424
|
// src/config.ts
|
|
1385
1425
|
import { mkdir, readFile as readFile12, writeFile } from "node:fs/promises";
|
|
1386
1426
|
import { homedir as homedir12, hostname } from "node:os";
|
|
1387
|
-
import { basename as basename6, join as
|
|
1388
|
-
var CONFIG_DIR =
|
|
1427
|
+
import { basename as basename6, join as join12 } from "node:path";
|
|
1428
|
+
var CONFIG_DIR = join12(homedir12(), ".aiusage"), CONFIG_PATH = join12(CONFIG_DIR, "config.json");
|
|
1389
1429
|
function getConfigPath() {
|
|
1390
1430
|
return CONFIG_PATH;
|
|
1391
1431
|
}
|
|
1432
|
+
function migrateConfig(config) {
|
|
1433
|
+
if (config.targets || !config.apiBaseUrl) return config;
|
|
1434
|
+
let target = {
|
|
1435
|
+
name: "default",
|
|
1436
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
1437
|
+
siteId: config.siteId,
|
|
1438
|
+
deviceToken: config.deviceToken,
|
|
1439
|
+
lastSuccessfulUploadAt: config.lastSuccessfulUploadAt
|
|
1440
|
+
};
|
|
1441
|
+
return {
|
|
1442
|
+
deviceId: config.deviceId,
|
|
1443
|
+
deviceAlias: config.deviceAlias,
|
|
1444
|
+
lookbackDays: config.lookbackDays,
|
|
1445
|
+
projectAliases: config.projectAliases,
|
|
1446
|
+
privacy: config.privacy,
|
|
1447
|
+
lang: config.lang,
|
|
1448
|
+
emoji: config.emoji,
|
|
1449
|
+
targets: [target]
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1392
1452
|
async function readConfig() {
|
|
1393
1453
|
try {
|
|
1394
1454
|
let raw = await readFile12(CONFIG_PATH, "utf-8");
|
|
1395
|
-
return JSON.parse(raw);
|
|
1455
|
+
return migrateConfig(JSON.parse(raw));
|
|
1396
1456
|
} catch {
|
|
1397
1457
|
return {};
|
|
1398
1458
|
}
|
|
@@ -1410,18 +1470,28 @@ function detectDeviceId() {
|
|
|
1410
1470
|
function getLocalTimezone() {
|
|
1411
1471
|
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1412
1472
|
}
|
|
1473
|
+
function findTarget(config, name) {
|
|
1474
|
+
let targets = config.targets ?? [];
|
|
1475
|
+
return name ? targets.find((t2) => t2.name === name) : targets[0];
|
|
1476
|
+
}
|
|
1477
|
+
function findTargetOrThrow(config, name) {
|
|
1478
|
+
let target = findTarget(config, name);
|
|
1479
|
+
if (!target)
|
|
1480
|
+
throw new Error(
|
|
1481
|
+
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"
|
|
1482
|
+
);
|
|
1483
|
+
return target;
|
|
1484
|
+
}
|
|
1485
|
+
function upsertTarget(config, target) {
|
|
1486
|
+
let next = structuredClone(config), targets = next.targets ?? [], idx = targets.findIndex((t2) => t2.name === target.name);
|
|
1487
|
+
return idx >= 0 ? targets[idx] = target : targets.push(target), next.targets = targets, next;
|
|
1488
|
+
}
|
|
1413
1489
|
function setConfigValue(config, keyPath, values) {
|
|
1414
1490
|
let next = structuredClone(config);
|
|
1415
|
-
if (keyPath === "server" || keyPath === "apiBaseUrl")
|
|
1416
|
-
return next.apiBaseUrl = normalizeServerUrl(requireSingleValue(keyPath, values)), next;
|
|
1417
|
-
if (keyPath === "siteId")
|
|
1418
|
-
return next.siteId = requireSingleValue(keyPath, values), next;
|
|
1419
1491
|
if (keyPath === "device.id")
|
|
1420
1492
|
return next.deviceId = requireSingleValue(keyPath, values), next;
|
|
1421
1493
|
if (keyPath === "device.alias")
|
|
1422
1494
|
return next.deviceAlias = requireSingleValue(keyPath, values), next;
|
|
1423
|
-
if (keyPath === "device.token")
|
|
1424
|
-
return next.deviceToken = requireSingleValue(keyPath, values), next;
|
|
1425
1495
|
if (keyPath === "lookbackDays")
|
|
1426
1496
|
return next.lookbackDays = parsePositiveInt(requireSingleValue(keyPath, values), keyPath), next;
|
|
1427
1497
|
if (keyPath === "privacy.projectVisibility") {
|
|
@@ -1551,8 +1621,8 @@ import { mkdir as mkdir2, readFile as readFile13, stat, unlink, writeFile as wri
|
|
|
1551
1621
|
import { execFile } from "node:child_process";
|
|
1552
1622
|
import { promisify } from "node:util";
|
|
1553
1623
|
import { homedir as homedir13, platform, tmpdir } from "node:os";
|
|
1554
|
-
import { join as
|
|
1555
|
-
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH =
|
|
1624
|
+
import { join as join13, resolve as resolve2 } from "node:path";
|
|
1625
|
+
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join13(homedir13(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join13(homedir13(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
|
|
1556
1626
|
function parseInterval(value) {
|
|
1557
1627
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
1558
1628
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -1597,7 +1667,7 @@ function resolveCommandPaths() {
|
|
|
1597
1667
|
}
|
|
1598
1668
|
async function enableLaunchd(intervalSeconds) {
|
|
1599
1669
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
1600
|
-
await mkdir2(
|
|
1670
|
+
await mkdir2(join13(homedir13(), ".aiusage"), { recursive: !0 });
|
|
1601
1671
|
let plist = [
|
|
1602
1672
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
1603
1673
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -1651,20 +1721,23 @@ async function getLaunchdStatus() {
|
|
|
1651
1721
|
return { enabled: !1 };
|
|
1652
1722
|
}
|
|
1653
1723
|
try {
|
|
1654
|
-
let
|
|
1724
|
+
let content = await readFile13(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];
|
|
1655
1725
|
return {
|
|
1656
1726
|
enabled: !0,
|
|
1657
1727
|
interval,
|
|
1658
1728
|
intervalLabel: interval ? formatInterval(interval) : void 0,
|
|
1659
|
-
path: PLIST_PATH
|
|
1729
|
+
path: PLIST_PATH,
|
|
1730
|
+
command: command2,
|
|
1731
|
+
logPath,
|
|
1732
|
+
includeToday
|
|
1660
1733
|
};
|
|
1661
1734
|
} catch {
|
|
1662
1735
|
return { enabled: !1 };
|
|
1663
1736
|
}
|
|
1664
1737
|
}
|
|
1665
1738
|
async function enableCron(intervalSeconds) {
|
|
1666
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
1667
|
-
await mkdir2(
|
|
1739
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join13(homedir13(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
1740
|
+
await mkdir2(join13(homedir13(), ".aiusage"), { recursive: !0 });
|
|
1668
1741
|
let existing = "";
|
|
1669
1742
|
try {
|
|
1670
1743
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -1708,18 +1781,21 @@ async function getCronStatus() {
|
|
|
1708
1781
|
let { stdout } = await execFileAsync("crontab", ["-l"]), line = stdout.split(`
|
|
1709
1782
|
`).find((l) => l.includes(CRON_MARKER));
|
|
1710
1783
|
if (!line) return { enabled: !1 };
|
|
1711
|
-
let interval = cronToSeconds(line);
|
|
1784
|
+
let interval = cronToSeconds(line), includeToday = line.includes("--today"), logPath = line.match(/>>\s*(\S+)/)?.[1], command2 = line.match(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(.+?)(?:\s*>>)/)?.[1];
|
|
1712
1785
|
return {
|
|
1713
1786
|
enabled: !0,
|
|
1714
1787
|
interval,
|
|
1715
|
-
intervalLabel: interval ? formatInterval(interval) : void 0
|
|
1788
|
+
intervalLabel: interval ? formatInterval(interval) : void 0,
|
|
1789
|
+
command: command2,
|
|
1790
|
+
logPath,
|
|
1791
|
+
includeToday
|
|
1716
1792
|
};
|
|
1717
1793
|
} catch {
|
|
1718
1794
|
return { enabled: !1 };
|
|
1719
1795
|
}
|
|
1720
1796
|
}
|
|
1721
1797
|
async function writeCrontab(content) {
|
|
1722
|
-
let tmpFile =
|
|
1798
|
+
let tmpFile = join13(tmpdir(), `aiusage-cron-${Date.now()}`);
|
|
1723
1799
|
await writeFile2(tmpFile, content, "utf-8");
|
|
1724
1800
|
try {
|
|
1725
1801
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -1752,7 +1828,7 @@ function escapeXml(value) {
|
|
|
1752
1828
|
// src/doctor.ts
|
|
1753
1829
|
import { stat as stat2 } from "node:fs/promises";
|
|
1754
1830
|
import { homedir as homedir14 } from "node:os";
|
|
1755
|
-
import { join as
|
|
1831
|
+
import { join as join14 } from "node:path";
|
|
1756
1832
|
async function runDoctor() {
|
|
1757
1833
|
let checks = [], config = await readConfig(), configPath = getConfigPath();
|
|
1758
1834
|
try {
|
|
@@ -1760,36 +1836,25 @@ async function runDoctor() {
|
|
|
1760
1836
|
} catch {
|
|
1761
1837
|
checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "fail", message: "\u672A\u627E\u5230\uFF0C\u8BF7\u5148\u6267\u884C aiusage init" });
|
|
1762
1838
|
}
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
["deviceToken", "\u8BBE\u5907\u4EE4\u724C", "\u8BF7\u6267\u884C aiusage enroll"]
|
|
1768
|
-
];
|
|
1769
|
-
for (let [key, label, hint] of fields) {
|
|
1770
|
-
let value = config[key];
|
|
1771
|
-
if (value) {
|
|
1772
|
-
let display = key === "deviceToken" ? `${String(value).slice(0, 12)}\u2026` : String(value);
|
|
1773
|
-
checks.push({ name: label, status: "ok", message: display });
|
|
1774
|
-
} else
|
|
1775
|
-
checks.push({
|
|
1776
|
-
name: label,
|
|
1777
|
-
status: key === "deviceToken" ? "fail" : "warn",
|
|
1778
|
-
message: `\u672A\u914D\u7F6E\uFF0C${hint}`
|
|
1779
|
-
});
|
|
1780
|
-
}
|
|
1781
|
-
if (config.apiBaseUrl)
|
|
1782
|
-
try {
|
|
1783
|
-
let health = await fetchHealth(config.apiBaseUrl);
|
|
1784
|
-
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "ok", message: `${health.siteId} (v${health.version})` });
|
|
1785
|
-
} catch (err) {
|
|
1786
|
-
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "fail", message: err instanceof Error ? err.message : String(err) });
|
|
1787
|
-
}
|
|
1839
|
+
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" });
|
|
1840
|
+
let targets = config.targets ?? [];
|
|
1841
|
+
if (targets.length === 0)
|
|
1842
|
+
checks.push({ name: "\u4E0A\u62A5\u76EE\u6807", status: "warn", message: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage enroll" });
|
|
1788
1843
|
else
|
|
1789
|
-
|
|
1844
|
+
for (let target of targets) {
|
|
1845
|
+
let prefix = `[${target.name}]`;
|
|
1846
|
+
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" });
|
|
1847
|
+
try {
|
|
1848
|
+
let health = await fetchHealth(target.apiBaseUrl);
|
|
1849
|
+
checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "ok", message: health.siteId });
|
|
1850
|
+
} catch (err) {
|
|
1851
|
+
checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "fail", message: err instanceof Error ? err.message : String(err) });
|
|
1852
|
+
}
|
|
1853
|
+
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" });
|
|
1854
|
+
}
|
|
1790
1855
|
let scannerDirs = [
|
|
1791
|
-
[
|
|
1792
|
-
[
|
|
1856
|
+
[join14(homedir14(), ".claude", "projects"), "Claude \u65E5\u5FD7"],
|
|
1857
|
+
[join14(homedir14(), ".codex"), "Codex \u65E5\u5FD7"]
|
|
1793
1858
|
];
|
|
1794
1859
|
for (let [dir, label] of scannerDirs)
|
|
1795
1860
|
try {
|
|
@@ -1802,7 +1867,7 @@ async function runDoctor() {
|
|
|
1802
1867
|
name: "\u5B9A\u65F6\u540C\u6B65",
|
|
1803
1868
|
status: "ok",
|
|
1804
1869
|
message: schedule.intervalLabel ? `\u6BCF ${schedule.intervalLabel}` : "\u5DF2\u542F\u7528"
|
|
1805
|
-
}) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }),
|
|
1870
|
+
}) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }), checks;
|
|
1806
1871
|
}
|
|
1807
1872
|
|
|
1808
1873
|
// src/cli.ts
|
|
@@ -1818,7 +1883,7 @@ try {
|
|
|
1818
1883
|
await runReport(parsed.flags);
|
|
1819
1884
|
} else if (command === "health") {
|
|
1820
1885
|
let parsed = parseArgs(argv.slice(1));
|
|
1821
|
-
await runHealth(parsed.flags
|
|
1886
|
+
await runHealth(parsed.flags);
|
|
1822
1887
|
} else if (command === "enroll") {
|
|
1823
1888
|
let parsed = parseArgs(argv.slice(1));
|
|
1824
1889
|
await runEnroll(parsed.flags);
|
|
@@ -1887,21 +1952,26 @@ async function runReport(flags) {
|
|
|
1887
1952
|
function fmt(n) {
|
|
1888
1953
|
return n.toLocaleString("en-US");
|
|
1889
1954
|
}
|
|
1890
|
-
async function runHealth(
|
|
1891
|
-
let config = await readConfig()
|
|
1955
|
+
async function runHealth(flags) {
|
|
1956
|
+
let config = await readConfig();
|
|
1957
|
+
if (typeof flags.server == "string") {
|
|
1958
|
+
let health2 = await fetchHealth(normalizeServerUrl(flags.server));
|
|
1959
|
+
console.log(JSON.stringify(health2, null, 2));
|
|
1960
|
+
return;
|
|
1961
|
+
}
|
|
1962
|
+
let targetName = resolveOptionalString(flags.target, void 0), target = findTargetOrThrow(config, targetName), health = await fetchHealth(target.apiBaseUrl);
|
|
1892
1963
|
console.log(JSON.stringify(health, null, 2));
|
|
1893
1964
|
}
|
|
1894
1965
|
async function runEnroll(flags) {
|
|
1895
|
-
let config = await readConfig(), apiBaseUrl = resolveServer(flags.server,
|
|
1896
|
-
|
|
1897
|
-
...config,
|
|
1966
|
+
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 = {
|
|
1967
|
+
name: targetName,
|
|
1898
1968
|
apiBaseUrl,
|
|
1899
1969
|
siteId,
|
|
1900
|
-
deviceId,
|
|
1901
|
-
deviceAlias,
|
|
1902
1970
|
deviceToken: response.deviceToken,
|
|
1903
|
-
|
|
1904
|
-
}
|
|
1971
|
+
lastSuccessfulUploadAt: void 0
|
|
1972
|
+
}, next = upsertTarget(config, target);
|
|
1973
|
+
next.deviceId = deviceId, next.deviceAlias = deviceAlias, next.lookbackDays = config.lookbackDays ?? 7, await writeConfig(next), console.log(JSON.stringify({
|
|
1974
|
+
target: targetName,
|
|
1905
1975
|
siteId: response.siteId,
|
|
1906
1976
|
deviceId: response.deviceId,
|
|
1907
1977
|
issuedAt: response.issuedAt,
|
|
@@ -1909,7 +1979,10 @@ async function runEnroll(flags) {
|
|
|
1909
1979
|
}, null, 2));
|
|
1910
1980
|
}
|
|
1911
1981
|
async function runSync(flags) {
|
|
1912
|
-
let config = await readConfig(),
|
|
1982
|
+
let config = await readConfig(), allTargets = config.targets ?? [];
|
|
1983
|
+
if (allTargets.length === 0)
|
|
1984
|
+
throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
|
|
1985
|
+
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;
|
|
1913
1986
|
if (requestedDate)
|
|
1914
1987
|
targetDates = [requestedDate];
|
|
1915
1988
|
else if (fromDate)
|
|
@@ -1925,35 +1998,38 @@ async function runSync(flags) {
|
|
|
1925
1998
|
return;
|
|
1926
1999
|
}
|
|
1927
2000
|
console.log(`\u53D1\u73B0 ${allDays.length} \u5929\u6709\u6570\u636E\uFF0C\u5F00\u59CB\u4E0A\u4F20 ...`);
|
|
1928
|
-
let
|
|
1929
|
-
for (let
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
)
|
|
1937
|
-
|
|
2001
|
+
let uploadResults = [];
|
|
2002
|
+
for (let target of targets) {
|
|
2003
|
+
if (!target.deviceToken) {
|
|
2004
|
+
console.log(`\u8DF3\u8FC7 "${target.name}"\uFF1A\u672A\u6CE8\u518C\uFF08\u7F3A\u5C11 deviceToken\uFF09`);
|
|
2005
|
+
continue;
|
|
2006
|
+
}
|
|
2007
|
+
targets.length > 1 && console.log(`\u4E0A\u4F20\u81F3 "${target.name}" (${target.apiBaseUrl}) ...`);
|
|
2008
|
+
let BATCH_SIZE = 30, totalProcessed = 0, allCostSummary = {};
|
|
2009
|
+
for (let i = 0; i < allDays.length; i += BATCH_SIZE) {
|
|
2010
|
+
let batch = allDays.slice(i, i + BATCH_SIZE), totalBatches = Math.ceil(allDays.length / BATCH_SIZE);
|
|
2011
|
+
if (totalBatches > 1) {
|
|
2012
|
+
let batchNum = Math.floor(i / BATCH_SIZE) + 1;
|
|
2013
|
+
console.log(` \u6279\u6B21 ${batchNum}/${totalBatches}: ${batch[0].usageDate} ~ ${batch[batch.length - 1].usageDate}`);
|
|
2014
|
+
}
|
|
2015
|
+
let response = await uploadDailyUsage(
|
|
2016
|
+
target.apiBaseUrl,
|
|
2017
|
+
{ siteId: target.siteId, deviceId, deviceAlias: config.deviceAlias, deviceToken: target.deviceToken },
|
|
2018
|
+
batch
|
|
2019
|
+
);
|
|
2020
|
+
totalProcessed += response.daysProcessed, Object.assign(allCostSummary, response.costSummary);
|
|
2021
|
+
}
|
|
2022
|
+
target.lastSuccessfulUploadAt = (/* @__PURE__ */ new Date()).toISOString(), uploadResults.push({ target: target.name, daysProcessed: totalProcessed, costSummary: allCostSummary });
|
|
1938
2023
|
}
|
|
1939
|
-
await writeConfig({
|
|
1940
|
-
|
|
1941
|
-
apiBaseUrl,
|
|
1942
|
-
siteId,
|
|
1943
|
-
deviceId,
|
|
1944
|
-
deviceToken,
|
|
1945
|
-
lastSuccessfulUploadAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1946
|
-
}), console.log(JSON.stringify({
|
|
2024
|
+
await writeConfig(config), console.log(JSON.stringify({
|
|
2025
|
+
targets: uploadResults.map((r) => r.target),
|
|
1947
2026
|
uploadedDays: allDays.map((day) => day.usageDate),
|
|
1948
|
-
|
|
1949
|
-
costSummary: allCostSummary
|
|
2027
|
+
results: uploadResults
|
|
1950
2028
|
}, null, 2));
|
|
1951
2029
|
}
|
|
1952
2030
|
async function runInit(flags) {
|
|
1953
2031
|
let config = await readConfig(), next = {
|
|
1954
2032
|
...config,
|
|
1955
|
-
apiBaseUrl: typeof flags.server == "string" ? normalizeServerUrl(flags.server) : config.apiBaseUrl,
|
|
1956
|
-
siteId: resolveOptionalString(flags["site-id"] ?? flags.siteId, config.siteId),
|
|
1957
2033
|
deviceId: resolveOptionalString(flags["device-id"], config.deviceId) ?? detectDeviceId(),
|
|
1958
2034
|
deviceAlias: resolveOptionalString(flags["device-name"] ?? flags["device-alias"], config.deviceAlias) ?? hostname3(),
|
|
1959
2035
|
lookbackDays: typeof flags.lookback == "string" ? parsePositiveInt2(flags.lookback, "--lookback") : config.lookbackDays ?? 7
|
|
@@ -1968,7 +2044,7 @@ async function runSchedule(sub, flags) {
|
|
|
1968
2044
|
await disableSchedule(), console.log("\u5B9A\u65F6\u540C\u6B65\u5DF2\u5173\u95ED\u3002");
|
|
1969
2045
|
else {
|
|
1970
2046
|
let status = await getScheduleStatus();
|
|
1971
|
-
status.enabled ? (console.log("\u72B6\u6001: \u5DF2\u542F\u7528"), status.intervalLabel && console.log(`\u95F4\u9694: \u6BCF ${status.intervalLabel}`), status.path && console.log(`\u914D\u7F6E: ${status.path}`)) : (console.log("\u72B6\u6001: \u672A\u542F\u7528"), console.log("\u542F\u7528: aiusage schedule [--every 5m]"));
|
|
2047
|
+
status.enabled ? (console.log("\u72B6\u6001: \u5DF2\u542F\u7528"), status.intervalLabel && console.log(`\u95F4\u9694: \u6BCF ${status.intervalLabel}`), console.log(`\u542B\u4ECA\u65E5: ${status.includeToday ? "\u662F" : "\u5426"}`), status.command && console.log(`\u547D\u4EE4: ${status.command}`), status.path && console.log(`\u914D\u7F6E: ${status.path}`), status.logPath && console.log(`\u65E5\u5FD7: ${status.logPath}`)) : (console.log("\u72B6\u6001: \u672A\u542F\u7528"), console.log("\u542F\u7528: aiusage schedule on [--every 5m]"));
|
|
1972
2048
|
}
|
|
1973
2049
|
}
|
|
1974
2050
|
async function runDoctorCommand() {
|
|
@@ -1988,7 +2064,7 @@ async function runConfigSet(args) {
|
|
|
1988
2064
|
function printHelp() {
|
|
1989
2065
|
let initialized = existsSync(getConfigPath());
|
|
1990
2066
|
console.log(`aiusage v${getVersion()}
|
|
1991
|
-
`), console.log("Usage: aiusage <command>"), console.log(""), console.log("Commands:"), console.log(" aiusage init [--
|
|
2067
|
+
`), 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)"}`);
|
|
1992
2068
|
}
|
|
1993
2069
|
function parseArgs(args) {
|
|
1994
2070
|
let flags = {}, positionals = [];
|
|
@@ -2039,6 +2115,13 @@ function getClosedDates(lookbackDays) {
|
|
|
2039
2115
|
}
|
|
2040
2116
|
return dates;
|
|
2041
2117
|
}
|
|
2118
|
+
function deriveTargetName(url) {
|
|
2119
|
+
try {
|
|
2120
|
+
return new URL(url).hostname.split(".")[0] || "default";
|
|
2121
|
+
} catch {
|
|
2122
|
+
return "default";
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2042
2125
|
function resolveServer(flagValue, configValue) {
|
|
2043
2126
|
let value = resolveOptionalString(flagValue, configValue);
|
|
2044
2127
|
if (!value) throw new Error("\u7F3A\u5C11\u670D\u52A1\u7AEF\u5730\u5740\uFF0C\u8BF7\u4F20 --server \u6216\u5148\u6267\u884C init");
|