@aiusage/cli 0.4.0 → 0.4.2

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.
Files changed (3) hide show
  1. package/README.zh-CN.md +153 -0
  2. package/dist/cli.js +135 -91
  3. package/package.json +1 -1
@@ -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
@@ -610,9 +610,9 @@ function processLedger(thread, events, dates, grouped) {
610
610
  }
611
611
  }
612
612
  function processMessages(thread, dates, grouped) {
613
- let msgs = thread.messages;
614
- if (!msgs) return;
615
- let entries = Array.isArray(msgs) ? msgs : Object.values(msgs);
613
+ let msgs2 = thread.messages;
614
+ if (!msgs2) return;
615
+ let entries = Array.isArray(msgs2) ? msgs2 : Object.values(msgs2);
616
616
  for (let msg of entries) {
617
617
  let usage = msg.usage;
618
618
  if (!usage) continue;
@@ -759,49 +759,22 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
759
759
  return finalize(grouped);
760
760
  }
761
761
 
762
- // src/scanners/openclaw.ts
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 resolveInput(u) {
767
- return u.input ?? u.inputTokens ?? u.input_tokens ?? u.promptTokens ?? u.prompt_tokens ?? 0;
768
- }
769
- function resolveOutput(u) {
770
- return u.output ?? u.outputTokens ?? u.output_tokens ?? u.completionTokens ?? u.completion_tokens ?? 0;
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 agentName = agentNameFromPath(filePath), project = projectAliases?.[agentName] ?? agentName;
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 ?? msg.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
- let model = msg.model ?? obj.model ?? "unknown", input = resolveInput(usage), output = resolveOutput(usage), cached2 = resolveCached(usage);
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}|${project}`,
807
+ `${model}|${sessionProject}`,
827
808
  {
828
- provider: "openclaw",
829
- product: "openclaw",
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
- scanOpenclawDates(uniqueDates, void 0, options.projectAliases)
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 join10 } from "node:path";
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) {
@@ -965,7 +954,7 @@ async function discoverAllDates() {
965
954
  ]), [...dates].sort();
966
955
  }
967
956
  async function discoverGeminiDates(dates) {
968
- let baseDir = join10(homedir11(), ".gemini", "tmp"), files = [];
957
+ let baseDir = join11(homedir11(), ".gemini", "tmp"), files = [];
969
958
  try {
970
959
  await walkForGeminiJsonl(baseDir, files);
971
960
  } catch {
@@ -995,12 +984,12 @@ async function walkForGeminiJsonl(dir, result) {
995
984
  return;
996
985
  }
997
986
  for (let entry of entries) {
998
- let fullPath = join10(dir, entry.name);
987
+ let fullPath = join11(dir, entry.name);
999
988
  entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
1000
989
  }
1001
990
  }
1002
991
  async function discoverClaudeDates(dates) {
1003
- let baseDir = join10(homedir11(), ".claude", "projects"), projectDirs;
992
+ let baseDir = join11(homedir11(), ".claude", "projects"), projectDirs;
1004
993
  try {
1005
994
  projectDirs = await readdir5(baseDir);
1006
995
  } catch {
@@ -1009,7 +998,7 @@ async function discoverClaudeDates(dates) {
1009
998
  for (let projectDir of projectDirs) {
1010
999
  let jsonlFiles = [];
1011
1000
  try {
1012
- await walkForClaudeJsonl(join10(baseDir, projectDir), jsonlFiles);
1001
+ await walkForClaudeJsonl(join11(baseDir, projectDir), jsonlFiles);
1013
1002
  } catch {
1014
1003
  continue;
1015
1004
  }
@@ -1032,7 +1021,7 @@ async function discoverClaudeDates(dates) {
1032
1021
  }
1033
1022
  }
1034
1023
  async function discoverCodexDates(dates) {
1035
- let baseDir = join10(homedir11(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1024
+ let baseDir = join11(homedir11(), ".codex"), files = await collectCodexSessionFiles(baseDir);
1036
1025
  for (let filePath of files) {
1037
1026
  let content = await safeReadUtf8(filePath);
1038
1027
  if (content)
@@ -1054,17 +1043,17 @@ async function discoverCodexDates(dates) {
1054
1043
  async function collectCodexSessionFiles(baseDir) {
1055
1044
  let paths = [];
1056
1045
  try {
1057
- let archivedFiles = await readdir5(join10(baseDir, "archived_sessions"));
1046
+ let archivedFiles = await readdir5(join11(baseDir, "archived_sessions"));
1058
1047
  for (let file of archivedFiles)
1059
- file.endsWith(".jsonl") && paths.push(join10(baseDir, "archived_sessions", file));
1048
+ file.endsWith(".jsonl") && paths.push(join11(baseDir, "archived_sessions", file));
1060
1049
  } catch {
1061
1050
  }
1062
- return await walkForCodexJsonl(join10(baseDir, "sessions"), paths), paths;
1051
+ return await walkForCodexJsonl(join11(baseDir, "sessions"), paths), paths;
1063
1052
  }
1064
1053
  async function walkForClaudeJsonl(dir, result) {
1065
1054
  let entries = await readdir5(dir, { withFileTypes: !0 });
1066
1055
  for (let entry of entries) {
1067
- let fullPath = join10(dir, entry.name);
1056
+ let fullPath = join11(dir, entry.name);
1068
1057
  entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
1069
1058
  }
1070
1059
  }
@@ -1076,7 +1065,7 @@ async function walkForCodexJsonl(dir, result) {
1076
1065
  return;
1077
1066
  }
1078
1067
  for (let entry of entries) {
1079
- let fullPath = join10(dir, entry.name);
1068
+ let fullPath = join11(dir, entry.name);
1080
1069
  entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
1081
1070
  }
1082
1071
  }
@@ -1435,8 +1424,8 @@ function fmtDateShort(dateStr) {
1435
1424
  // src/config.ts
1436
1425
  import { mkdir, readFile as readFile12, writeFile } from "node:fs/promises";
1437
1426
  import { homedir as homedir12, hostname } from "node:os";
1438
- import { basename as basename6, join as join11 } from "node:path";
1439
- var CONFIG_DIR = join11(homedir12(), ".aiusage"), CONFIG_PATH = join11(CONFIG_DIR, "config.json");
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");
1440
1429
  function getConfigPath() {
1441
1430
  return CONFIG_PATH;
1442
1431
  }
@@ -1632,8 +1621,8 @@ import { mkdir as mkdir2, readFile as readFile13, stat, unlink, writeFile as wri
1632
1621
  import { execFile } from "node:child_process";
1633
1622
  import { promisify } from "node:util";
1634
1623
  import { homedir as homedir13, platform, tmpdir } from "node:os";
1635
- import { join as join12, resolve as resolve2 } from "node:path";
1636
- var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join12(homedir13(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join12(homedir13(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
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";
1637
1626
  function parseInterval(value) {
1638
1627
  let match = value.match(/^(\d+)(m|h|d)$/);
1639
1628
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -1678,7 +1667,7 @@ function resolveCommandPaths() {
1678
1667
  }
1679
1668
  async function enableLaunchd(intervalSeconds) {
1680
1669
  let { nodePath, scriptPath } = resolveCommandPaths();
1681
- await mkdir2(join12(homedir13(), ".aiusage"), { recursive: !0 });
1670
+ await mkdir2(join13(homedir13(), ".aiusage"), { recursive: !0 });
1682
1671
  let plist = [
1683
1672
  '<?xml version="1.0" encoding="UTF-8"?>',
1684
1673
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -1732,20 +1721,23 @@ async function getLaunchdStatus() {
1732
1721
  return { enabled: !1 };
1733
1722
  }
1734
1723
  try {
1735
- let match = (await readFile13(PLIST_PATH, "utf-8")).match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0;
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];
1736
1725
  return {
1737
1726
  enabled: !0,
1738
1727
  interval,
1739
1728
  intervalLabel: interval ? formatInterval(interval) : void 0,
1740
- path: PLIST_PATH
1729
+ path: PLIST_PATH,
1730
+ command: command2,
1731
+ logPath,
1732
+ includeToday
1741
1733
  };
1742
1734
  } catch {
1743
1735
  return { enabled: !1 };
1744
1736
  }
1745
1737
  }
1746
1738
  async function enableCron(intervalSeconds) {
1747
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join12(homedir13(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
1748
- await mkdir2(join12(homedir13(), ".aiusage"), { recursive: !0 });
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 });
1749
1741
  let existing = "";
1750
1742
  try {
1751
1743
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -1789,18 +1781,21 @@ async function getCronStatus() {
1789
1781
  let { stdout } = await execFileAsync("crontab", ["-l"]), line = stdout.split(`
1790
1782
  `).find((l) => l.includes(CRON_MARKER));
1791
1783
  if (!line) return { enabled: !1 };
1792
- 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];
1793
1785
  return {
1794
1786
  enabled: !0,
1795
1787
  interval,
1796
- intervalLabel: interval ? formatInterval(interval) : void 0
1788
+ intervalLabel: interval ? formatInterval(interval) : void 0,
1789
+ command: command2,
1790
+ logPath,
1791
+ includeToday
1797
1792
  };
1798
1793
  } catch {
1799
1794
  return { enabled: !1 };
1800
1795
  }
1801
1796
  }
1802
1797
  async function writeCrontab(content) {
1803
- let tmpFile = join12(tmpdir(), `aiusage-cron-${Date.now()}`);
1798
+ let tmpFile = join13(tmpdir(), `aiusage-cron-${Date.now()}`);
1804
1799
  await writeFile2(tmpFile, content, "utf-8");
1805
1800
  try {
1806
1801
  await execFileAsync("crontab", [tmpFile]);
@@ -1833,46 +1828,92 @@ function escapeXml(value) {
1833
1828
  // src/doctor.ts
1834
1829
  import { stat as stat2 } from "node:fs/promises";
1835
1830
  import { homedir as homedir14 } from "node:os";
1836
- import { join as join13 } from "node:path";
1837
- async function runDoctor() {
1838
- let checks = [], config = await readConfig(), configPath = getConfigPath();
1831
+ import { join as join14 } from "node:path";
1832
+ var msgs = {
1833
+ en: {
1834
+ config: "Config",
1835
+ configMissing: "Not found, run aiusage init first",
1836
+ deviceId: "Device ID",
1837
+ deviceIdMissing: "Not configured, run aiusage init",
1838
+ targetMissing: "Not configured, run aiusage enroll",
1839
+ targets: "Targets",
1840
+ deviceToken: "Device token",
1841
+ tokenMissing: "Not registered",
1842
+ server: "Server",
1843
+ lastSync: "Last sync",
1844
+ lastSyncNone: "No record",
1845
+ noUsage: "No usage detected",
1846
+ schedule: "Schedule",
1847
+ scheduleEvery: "every",
1848
+ scheduleEnabled: "Enabled",
1849
+ scheduleOff: "Not enabled, run aiusage schedule on"
1850
+ },
1851
+ zh: {
1852
+ config: "\u914D\u7F6E\u6587\u4EF6",
1853
+ configMissing: "\u672A\u627E\u5230\uFF0C\u8BF7\u5148\u6267\u884C aiusage init",
1854
+ deviceId: "\u8BBE\u5907 ID",
1855
+ deviceIdMissing: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage init",
1856
+ targetMissing: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage enroll",
1857
+ targets: "\u4E0A\u62A5\u76EE\u6807",
1858
+ deviceToken: "\u8BBE\u5907\u4EE4\u724C",
1859
+ tokenMissing: "\u672A\u6CE8\u518C",
1860
+ server: "\u670D\u52A1\u7AEF",
1861
+ lastSync: "\u4E0A\u6B21\u540C\u6B65",
1862
+ lastSyncNone: "\u6682\u65E0\u8BB0\u5F55",
1863
+ noUsage: "\u672A\u68C0\u6D4B\u5230\u4F7F\u7528\u8BB0\u5F55",
1864
+ schedule: "\u5B9A\u65F6\u540C\u6B65",
1865
+ scheduleEvery: "\u6BCF",
1866
+ scheduleEnabled: "\u5DF2\u542F\u7528",
1867
+ scheduleOff: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on"
1868
+ }
1869
+ };
1870
+ async function runDoctor(lang = "zh") {
1871
+ let s = msgs[lang], checks = [], config = await readConfig(), configPath = getConfigPath();
1839
1872
  try {
1840
- await stat2(configPath), checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "ok", message: configPath });
1873
+ await stat2(configPath), checks.push({ name: s.config, status: "ok", message: configPath });
1841
1874
  } catch {
1842
- checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "fail", message: "\u672A\u627E\u5230\uFF0C\u8BF7\u5148\u6267\u884C aiusage init" });
1875
+ checks.push({ name: s.config, status: "fail", message: s.configMissing });
1843
1876
  }
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" });
1877
+ config.deviceId ? checks.push({ name: s.deviceId, status: "ok", message: config.deviceId }) : checks.push({ name: s.deviceId, status: "warn", message: s.deviceIdMissing });
1845
1878
  let targets = config.targets ?? [];
1846
1879
  if (targets.length === 0)
1847
- checks.push({ name: "\u4E0A\u62A5\u76EE\u6807", status: "warn", message: "\u672A\u914D\u7F6E\uFF0C\u8BF7\u6267\u884C aiusage enroll" });
1880
+ checks.push({ name: s.targets, status: "warn", message: s.targetMissing });
1848
1881
  else
1849
1882
  for (let target of targets) {
1850
1883
  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" });
1884
+ target.deviceToken ? checks.push({ name: `${prefix} ${s.deviceToken}`, status: "ok", message: `${target.deviceToken.slice(0, 12)}\u2026` }) : checks.push({ name: `${prefix} ${s.deviceToken}`, status: "fail", message: s.tokenMissing });
1852
1885
  try {
1853
1886
  let health = await fetchHealth(target.apiBaseUrl);
1854
- checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "ok", message: health.siteId });
1887
+ checks.push({ name: `${prefix} ${s.server}`, status: "ok", message: health.siteId });
1855
1888
  } catch (err) {
1856
- checks.push({ name: `${prefix} \u670D\u52A1\u7AEF`, status: "fail", message: err instanceof Error ? err.message : String(err) });
1889
+ checks.push({ name: `${prefix} ${s.server}`, status: "fail", message: err instanceof Error ? err.message : String(err) });
1857
1890
  }
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" });
1891
+ target.lastSuccessfulUploadAt ? checks.push({ name: `${prefix} ${s.lastSync}`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ name: `${prefix} ${s.lastSync}`, status: "warn", message: s.lastSyncNone });
1859
1892
  }
1860
- let scannerDirs = [
1861
- [join13(homedir14(), ".claude", "projects"), "Claude \u65E5\u5FD7"],
1862
- [join13(homedir14(), ".codex"), "Codex \u65E5\u5FD7"]
1893
+ let home = homedir14(), scannerDirs = [
1894
+ [join14(home, ".claude", "projects"), "Claude Code"],
1895
+ [join14(home, ".codex"), "Codex CLI"],
1896
+ [join14(home, ".copilot", "session-state"), "Copilot CLI"],
1897
+ [join14(home, ".gemini", "tmp"), "Gemini CLI"],
1898
+ [join14(home, ".qwen", "tmp"), "Qwen Code"],
1899
+ [join14(home, ".kimi", "sessions"), "Kimi Code"],
1900
+ [join14(home, ".local", "share", "amp", "threads"), "Amp"],
1901
+ [join14(home, ".factory", "sessions"), "Droid"],
1902
+ [join14(home, ".local", "share", "opencode"), "OpenCode"],
1903
+ [join14(home, ".pi", "agent", "sessions"), "Pi"]
1863
1904
  ];
1864
1905
  for (let [dir, label] of scannerDirs)
1865
1906
  try {
1866
1907
  await stat2(dir), checks.push({ name: label, status: "ok", message: dir });
1867
1908
  } catch {
1868
- checks.push({ name: label, status: "warn", message: "\u76EE\u5F55\u4E0D\u5B58\u5728\uFF08\u672A\u4F7F\u7528\u53EF\u5FFD\u7565\uFF09" });
1909
+ checks.push({ name: label, status: "warn", message: s.noUsage });
1869
1910
  }
1870
1911
  let schedule = await getScheduleStatus();
1871
1912
  return schedule.enabled ? checks.push({
1872
- name: "\u5B9A\u65F6\u540C\u6B65",
1913
+ name: s.schedule,
1873
1914
  status: "ok",
1874
- message: schedule.intervalLabel ? `\u6BCF ${schedule.intervalLabel}` : "\u5DF2\u542F\u7528"
1875
- }) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }), checks;
1915
+ message: schedule.intervalLabel ? `${s.scheduleEvery} ${schedule.intervalLabel}` : s.scheduleEnabled
1916
+ }) : checks.push({ name: s.schedule, status: "warn", message: s.scheduleOff }), checks;
1876
1917
  }
1877
1918
 
1878
1919
  // src/cli.ts
@@ -1911,7 +1952,10 @@ try {
1911
1952
  let parsed = parseArgs(argv.slice(1));
1912
1953
  await runSchedule("on", parsed.flags);
1913
1954
  }
1914
- } else command === "doctor" ? await runDoctorCommand() : command === "config" && argv[1] === "set" ? await runConfigSet(argv.slice(2)) : command === "setup" ? (console.log(`To deploy the server, clone the repo and run the setup wizard:
1955
+ } else if (command === "doctor") {
1956
+ let parsed = parseArgs(argv.slice(1));
1957
+ await runDoctorCommand(parsed.flags);
1958
+ } else command === "config" && argv[1] === "set" ? await runConfigSet(argv.slice(2)) : command === "setup" ? (console.log(`To deploy the server, clone the repo and run the setup wizard:
1915
1959
  `), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
1916
1960
  `), console.log("See: https://github.com/ennann/aiusage#deploy-your-own-server")) : printHelp();
1917
1961
  } catch (error) {
@@ -2049,11 +2093,11 @@ async function runSchedule(sub, flags) {
2049
2093
  await disableSchedule(), console.log("\u5B9A\u65F6\u540C\u6B65\u5DF2\u5173\u95ED\u3002");
2050
2094
  else {
2051
2095
  let status = await getScheduleStatus();
2052
- 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]"));
2096
+ 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]"));
2053
2097
  }
2054
2098
  }
2055
- async function runDoctorCommand() {
2056
- let checks = await runDoctor();
2099
+ async function runDoctorCommand(flags) {
2100
+ let config = await readConfig(), lang = (typeof flags.lang == "string" ? flags.lang : config.lang) || "en", checks = await runDoctor(lang);
2057
2101
  for (let check of checks) {
2058
2102
  let icon = check.status === "ok" ? "\u2713" : check.status === "warn" ? "\u26A0" : "\u2717";
2059
2103
  console.log(`${icon} ${check.name}: ${check.message}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiusage/cli",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Track and sync AI tool token usage across devices.",
5
5
  "license": "MIT",
6
6
  "private": false,