@anthonyhan/token-pilot 0.3.4 → 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.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <div align="center">
2
2
 
3
- <img src="docs/assets/icon.png" width="96" alt="token-pilot —— 所有 AI 工具的本地账单,本月实测 ¥7,328 / 38 亿 tokens">
3
+ <img src="docs/assets/icon.png" width="96" alt="token-pilot —— 所有 AI 工具的本地账单,本月实测 ¥8,265 / 48 亿 tokens">
4
4
 
5
5
  # token-pilot ⚡
6
6
 
@@ -13,7 +13,7 @@
13
13
  [![Tests](https://img.shields.io/badge/tests-42%20passing-brightgreen)](tests/)
14
14
  [![Accuracy](https://img.shields.io/badge/对账脚本-逐项一致-blue)](#-数据准确性)
15
15
 
16
- [快速开始](#-快速开始) · [状态栏应用](#-状态栏应用) · [数据准确性](#-数据准确性) · [什么时候别用它](#-什么时候别用它) · [TODO](#-todo-list) · [English](README-en.md) · [llms.txt](llms.txt)
16
+ [快速开始](#-快速开始) · [状态栏应用](#-状态栏应用) · [数据准确性](#-数据准确性) · [什么时候别用它](#-什么时候别用它) · [讨论](https://github.com/anthonyhann/token-pilot/discussions) · [贡献](CONTRIBUTING.md) · [English](README-en.md)
17
17
 
18
18
  </div>
19
19
 
@@ -21,7 +21,7 @@
21
21
 
22
22
  ![状态栏面板](docs/assets/menubar-panel.png)
23
23
 
24
- > 状态栏常驻 `⚡ ¥今日 · 预算%`。左键弹面板,「打开完整看板」看全部。我的真实 10 月:**38.1 亿 tokens · ¥7,328 · 27,450 次调用**([怎么算的](#-数据准确性))。
24
+ > 状态栏常驻 `⚡ ¥今日 · 预算%`。左键弹面板,「打开完整看板」看全部。我的真实 10 月:**47.8 亿 tokens · ¥8,265 · 32,643 次调用**([怎么算的](#-数据准确性))。
25
25
 
26
26
  > ⚠️ npm 上另有一个**别人家的** `token-pilot`(MCP 代码导航工具,会往 Claude Code 写 hooks)。我们的包是 **`@anthonyhan/token-pilot`**,下面命令都带 scope,照抄即可。
27
27
 
@@ -60,7 +60,22 @@ xattr -dr com.apple.quarantine /Applications/token-pilot.app
60
60
 
61
61
  自己构建:`cd menubar && npm install && npx tauri build`
62
62
 
63
- ## ✨ 它能做什么
63
+ ## 🎯 为什么做这个
64
+
65
+ 我同时用 Claude Code、Codex 和 Kimi Code 跑国产模型,账单散在三个地方:Claude 记一笔、Codex 记一笔、Kimi 记一笔,没有一个地方能回答「这个月总共烧了多少」。
66
+
67
+ 试过几个现有方案,都不合用:
68
+
69
+ | 方案 | 国产模型 | 只读本地 | 状态栏 | 卡在哪 |
70
+ |---|---|---|---|---|
71
+ | ccusage | 部分 | ✅ | ❌ | 以 Claude Code 为主,`deepseek-v4.1-flash` 这类模型的归一路径不全 |
72
+ | 各工具自带用量页 | ✅ | — | ❌ | 每个工具各看各的,没法合并成一张账单 |
73
+ | 商业账单 / 代理类工具 | ❌ | ❌ | ✅ | 要把日志或请求过一遍云端,我不放心把完整会话历史交出去 |
74
+ | **token-pilot** | **9 家** | **✅** | **✅** | — |
75
+
76
+ 核心区别只有一句:**它把国产模型和海外模型放在同一张账单里,而且全程不出本机。**
77
+
78
+ ## ✨ 功能清单:它能做什么
64
79
 
65
80
  | 场景 | 你说 | 它做 |
66
81
  |---|---|---|
@@ -70,6 +85,7 @@ xattr -dr com.apple.quarantine /Applications/token-pilot.app
70
85
  | 想省钱 | 看「省钱建议」卡 | 贵模型干轻活 → 迁移建议+每月省多少;低缓存命中 → 优化空间;本月缓存帮你省了多少 |
71
86
  | 上下文太长 | 自动提醒 / 点徽标 | 会话超 100K 上下文标记「该压缩」,可写 Claude Code autoCompact / 装 RTK 输出压缩层(含压缩引擎,装完自动 `rtk init -g` 接入 Claude Code hook) |
72
87
  | 想知道能省多少 | 看「压缩潜力」板块 | 本月陈旧输出/重复读取/超长输出各浪费多少钱,按模式拆分 + 列出最浪费的 5 个会话 |
88
+ | 还够不够用 | 看「订阅额度与余额」板块 / `token-pilot quota` | 火山 Agent/Coding Plan、OpenCode Go、GLM 的额度窗口;DeepSeek 等现金余额。**比线性节奏快还是慢**会直接标出来 |
73
89
  | 核对价格 | `token-pilot prices` | 每个在用模型的单价来源(目录价/人工覆写/自动补价待核对) |
74
90
  | 谁在烧 | 看「宿主/模型/项目榜」 | 哪个工具、哪个模型、哪个项目花最多,一目了然 |
75
91
  | 国产模型 | 不用配置 | DeepSeek/GLM/Kimi/Qwen 走宿主日志 model 字段自动归一 |
@@ -83,7 +99,7 @@ xattr -dr com.apple.quarantine /Applications/token-pilot.app
83
99
  ```bash
84
100
  python3 scripts/reconcile.py month # 第三方视角独立重算原始日志,与 CLI 逐项对账
85
101
  python3 scripts/verify-dashboard.py # 看板 36 项算法不变量校验
86
- npm test # 49 个单元测试(定价/采集口径/聚合/注入/熔断/RTK)
102
+ npm test # 69 个单元测试(定价/采集口径/聚合/注入/熔断/RTK/额度/并发)
87
103
  ```
88
104
 
89
105
  实测修过的口径坑(2026-10-21,本机 4787 个日志文件):
@@ -96,8 +112,8 @@ npm test # 49 个单元测试(定价/采集口径
96
112
 
97
113
  ## 📊 凭什么信我
98
114
 
99
- - 我自己的 AI 账单就是它管的:本月 **¥7,328 / 38.1 亿 tokens**(2026-10-27 本机实时数据)
100
- - 36 项看板算法不变量 + 49 个单测 + 独立对账脚本,全部开箱可跑
115
+ - 我自己的 AI 账单就是它管的:本月 **¥8,265 / 47.8 亿 tokens**(2026-10-29 本机实时数据)
116
+ - 36 项看板算法不变量 + 69 个单测 + 独立对账脚本,全部开箱可跑
101
117
  - 诚实披露速率口径:日志按「调用完成时刻」记账,生成中的调用完成前不计入(看板内有注明)
102
118
 
103
119
  ## ⚠️ 什么时候别用它
@@ -106,6 +122,50 @@ npm test # 49 个单元测试(定价/采集口径
106
122
  - **桌面订阅 App**(Kimi.app / ChatGPT.app)——不按 token 计费,只能登记固定月费
107
123
  - **想拦在请求前面节流**——它是事后分析,不拦截请求(拦截需要代理层,在 Roadmap)
108
124
 
125
+ ## 🔋 订阅额度与余额
126
+
127
+ 账单回答「花了多少钱」,额度回答「还能用多少」。后者来自平台自己的接口,不是本地推算。
128
+
129
+ | 平台 | 能拿到什么 | 数据来源 |
130
+ |---|---|---|
131
+ | **OpenCode Go** | 滚动 / 本周 / 本月三个窗口的已用百分比 | 官方接口,用 OpenCode 自己的登录态 |
132
+ | **火山方舟** | Agent Plan 的额度绝对值 + 百分比;Coding Plan 的百分比 | 官方 CLI `arkcli usage plan` |
133
+ | **智谱 GLM** | 额度窗口 + 套餐档位 | 官方接口 |
134
+ | **DeepSeek / Moonshot** | 现金余额 | 官方余额接口 |
135
+ | **MiniMax** | Token Plan 剩余量 | 官方接口 |
136
+
137
+ **凭证从哪来**(三级降级,装了哪个用哪个):
138
+
139
+ 1. 你在看板「数据设置」里填的 key —— 永远可用
140
+ 2. 平台自己的登录凭据(如 OpenCode 的 `~/.local/share/opencode/auth.json`)—— 装了该工具就有
141
+ 3. [CC Switch](https://github.com/farion1231/cc-switch) 的配置 —— **装了才自动读取,不装完全可以正常用**
142
+
143
+ > 第 3 层是便利不是依赖:不装 CC Switch 的用户,填一次 key 就能获得全部额度功能。
144
+
145
+ **诚实说明**:Coding Plan 类套餐平台只下发百分比,不发绝对值。所以看板上不会出现「已用 1500/20000」这种编造的数字——有什么显示什么。
146
+
147
+ **节奏判断**:单看「已用 60%」没意义,知道「窗口才过 40% 就已经用了 60%」才知道该不该踩刹车。所以有窗口长度和重置时间的平台,会额外标注「比线性节奏快/慢 N%」。
148
+
149
+ ## 🧩 它和别的工具有什么不同
150
+
151
+ 省 token 这件事分好几个环节,token-pilot 只做其中一环——**算清楚钱**。想省得更多,通常要几个工具配合:
152
+
153
+ | 环节 | 谁负责 | 典型效果 |
154
+ |---|---|---|
155
+ | **花了多少钱** | **token-pilot**(本工具) | 多宿主合并账单、预算告警、算出浪费了多少 |
156
+ | 命令输出太大 | [RTK](https://www.rtk-ai.app/) 输出压缩层 | 已内置支持,看板勾选即可装 |
157
+ | 读代码浪费上下文 | AST 结构化读取类工具(见下) | 大文件从「整篇读」变成「先看结构,再读需要的符号」|
158
+ | 模型回复太长 | 精简输出类 skill | 只影响输出 token,与输入侧不重叠 |
159
+
160
+ **关于重名:** npm 上有一个**同名的 `token-pilot`**([Digital-Threads/token-pilot](https://github.com/Digital-Threads/token-pilot)),它做的是上面第三行那件事——用 AST 让 AI 少读代码。**它不统计花费,本工具也不读代码结构**,两者解决的是同一个成本问题的不同环节,可以一起用。
161
+
162
+ 本工具的正确包名是带 scope 的 **`@anthonyhan/token-pilot`**,安装命令都在上面,照抄即可。
163
+
164
+ ## 💬 参与讨论
165
+
166
+ - **[Discussions](https://github.com/anthonyhann/token-pilot/discussions)** ——「这个模型算得对不对」「能不能支持某某工具」这类问题放这里,比开 issue 合适
167
+ - **[Issues](https://github.com/anthonyhann/token-pilot/issues/new/choose)** ——数据算错、功能异常
168
+
109
169
  ## 💰 支持这个项目
110
170
 
111
171
  token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝杯咖啡:
package/dist/cli/index.js CHANGED
@@ -262,6 +262,12 @@ async function cmdCompressReport() {
262
262
  }
263
263
  async function main() {
264
264
  const cmd = process.argv[2] ?? 'today';
265
+ // 报版本:用户想确认装的是哪一版(也方便 issue 里贴环境)
266
+ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
267
+ const { APP_VERSION } = await import('../core/version.js');
268
+ console.log(APP_VERSION);
269
+ return;
270
+ }
265
271
  if (cmd === 'serve') {
266
272
  const port = Number(process.argv[3] ?? 17895);
267
273
  await serve(port);
@@ -275,10 +281,26 @@ async function main() {
275
281
  return cmdPrices();
276
282
  if (cmd === 'compress-report')
277
283
  return cmdCompressReport();
284
+ if (cmd === 'quota') {
285
+ const { collectQuota } = await import('../core/quota/index.js');
286
+ const { formatQuota } = await import('../core/quota/format.js');
287
+ const snap = await collectQuota(process.argv.includes('--force'));
288
+ console.log(formatQuota(snap));
289
+ return;
290
+ }
291
+ if (cmd === 'doctor') {
292
+ const { runDoctor, formatDoctor } = await import('../core/doctor.js');
293
+ const report = await runDoctor();
294
+ console.log(formatDoctor(report));
295
+ // 有 error 时返回非 0,方便脚本判断
296
+ if (report.error > 0)
297
+ process.exitCode = 1;
298
+ return;
299
+ }
278
300
  if (cmd === 'today' || cmd === 'month' || cmd === 'report' || cmd === 'all') {
279
301
  return cmdReport(cmd === 'all' ? 'all' : cmd);
280
302
  }
281
- console.log('用法:token-pilot [today|month|report|sync|dash|serve]');
303
+ console.log('用法:token-pilot [today|month|report|sync|dash|serve|prices|quota|doctor|version]');
282
304
  }
283
305
  main().catch((e) => {
284
306
  console.error('错误:', e.message);
@@ -6,6 +6,7 @@ import { detectRetryLoops } from './retry-detector.js';
6
6
  import { savingsAdvice } from './savings.js';
7
7
  import { computeCompression } from './compression.js';
8
8
  import { buildAdapterTiers, HOST_TIERS } from './registry.js';
9
+ import { APP_VERSION } from './version.js';
9
10
  const AGENT_NAMES = {
10
11
  'claude-code': 'Claude Code',
11
12
  'kimi-code': 'Kimi Code',
@@ -501,7 +502,21 @@ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents
501
502
  const trayTitle = budget
502
503
  ? `${fmtCny(today.costUsd * fx)} · ${Math.round(budget.pct)}%`
503
504
  : fmtCny(today.costUsd * fx);
505
+ // 额度是可选能力:外部接口慢或挂掉都不能拖住账单。
506
+ // 8 秒超时,超时就给 null,看板照常显示。
507
+ let quota = null;
508
+ try {
509
+ const { collectQuota } = await import('./quota/index.js');
510
+ quota = await Promise.race([
511
+ collectQuota(),
512
+ new Promise((resolve) => setTimeout(() => resolve(null), 8000)),
513
+ ]);
514
+ }
515
+ catch {
516
+ quota = null;
517
+ }
504
518
  return {
519
+ appVersion: APP_VERSION,
505
520
  generatedAt: nowMs,
506
521
  usdToCny: fx,
507
522
  dateLabel: `${now.getMonth() + 1}月${now.getDate()}日 周${WD[now.getDay()]}`,
@@ -519,6 +534,7 @@ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents
519
534
  savings,
520
535
  compression,
521
536
  adapters,
537
+ quota,
522
538
  settings,
523
539
  };
524
540
  }
@@ -19,10 +19,31 @@ import { workbuddyAdapter, workbuddyAiAdapter } from '../adapters/workbuddy.js';
19
19
  import { CONFIG_DIR } from './config.js';
20
20
  export const ALL_ADAPTERS = [claudeCodeAdapter, codexAdapter, kimiCodeAdapter, opencodeAdapter, piAdapter, volcArkAdapter, dshAdapter, workbuddyAdapter, workbuddyAiAdapter];
21
21
  const CACHE_PATH = path.join(CONFIG_DIR, 'events-cache.json');
22
+ /** 同时打开的文件数上限。SSD 上 32 已经能吃到 IO 带宽,再高只是徒增内存峰值。 */
23
+ const FILE_CONCURRENCY = 32;
24
+ /** 限并发的 map,保持结果顺序无关(本项目只关心副作用) */
25
+ async function mapWithConcurrency(items, limit, fn) {
26
+ let cursor = 0;
27
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
28
+ for (;;) {
29
+ const i = cursor++;
30
+ if (i >= items.length)
31
+ return;
32
+ await fn(items[i]);
33
+ }
34
+ });
35
+ await Promise.all(workers);
36
+ }
22
37
  const LOCK_PATH = path.join(CONFIG_DIR, 'sync.lock');
23
38
  const WINDOW_MS = 40 * 86400_000;
24
39
  const LOCK_TTL_MS = 120_000;
25
40
  // ---------- 单飞锁 ----------
41
+ /// 抢锁。返回 true = 抢到了(调用方负责 release)。
42
+ ///
43
+ /// 写锁失败(目录只读、沙箱 EPERM、磁盘满)不能让整次 sync 崩掉:
44
+ /// 锁只是防多进程叠加的优化,拿不到就退化成本次不加锁跑——总比看板
45
+ /// 直接返回 {} 什么都看不到强。这里吞掉写错误,只在拿不到时返回 true,
46
+ /// 由调用方的 finally 里的 release 自行忽略"文件不存在"。
26
47
  export async function acquireSyncLock() {
27
48
  try {
28
49
  const raw = await fs.readFile(LOCK_PATH, 'utf8');
@@ -39,10 +60,15 @@ export async function acquireSyncLock() {
39
60
  }
40
61
  }
41
62
  catch {
42
- // 无锁文件
63
+ // 无锁文件(或读不到)
64
+ }
65
+ try {
66
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
67
+ await fs.writeFile(LOCK_PATH, JSON.stringify({ pid: process.pid, ts: Date.now() }), 'utf8');
68
+ }
69
+ catch {
70
+ // 写不了锁文件:不加锁也要继续,不能因为锁而拿不到数据
43
71
  }
44
- await fs.mkdir(CONFIG_DIR, { recursive: true });
45
- await fs.writeFile(LOCK_PATH, JSON.stringify({ pid: process.pid, ts: Date.now() }), 'utf8');
46
72
  return true;
47
73
  }
48
74
  export async function releaseSyncLock() {
@@ -87,7 +113,10 @@ export async function collectCached(sinceMs = 0) {
87
113
  catch {
88
114
  continue;
89
115
  }
90
- await Promise.all(files.map(async (f) => {
116
+ // 并发上限:曾经直接 Promise.all 全部文件,6481 个 jsonl 同时打开会瞬间
117
+ // 耗尽 4GB 堆导致 sync 直接 OOM 崩溃(本机实测,2026-10-29)。
118
+ // 限流后逐个文件的内存占用能被 GC 及时回收,峰值降到百 MB 量级。
119
+ await mapWithConcurrency(files, FILE_CONCURRENCY, async (f) => {
91
120
  let mtime = 0;
92
121
  try {
93
122
  mtime = (await fs.stat(f)).mtimeMs;
@@ -114,7 +143,7 @@ export async function collectCached(sinceMs = 0) {
114
143
  }
115
144
  nextFiles[f] = { mtime, adapter: ad.meta.id, events, content: contentEv };
116
145
  parsed++;
117
- }));
146
+ });
118
147
  }
119
148
  else {
120
149
  // 无文件级能力的 adapter:全量读(目前没有这种)
@@ -1,4 +1 @@
1
- // DashboardData — 前端数据契约
2
- // 两个前端(完整看板 / 菜单栏面板)都只吃这一份数据。
3
- // 金额一律给 USD 原始值 + 由前端按 usdToCny 折算展示;CNY 派生值在带 Cny 后缀的字段直接给好。
4
1
  export {};
@@ -0,0 +1,249 @@
1
+ // doctor — 环境与配置自检
2
+ //
3
+ // 为什么需要:token-pilot 的数据来自十几个不同的日志路径,任何一个读不到,
4
+ // 用户看到的账单就是不完整的。而这类问题**没有任何东西会报错**——路径不存在
5
+ // 只是静默少读,账单照常显示,只是数字偏小。用户不会怀疑「我的工具没工作」,
6
+ // 只会觉得「这个月花得少」。
7
+ //
8
+ // 所以 doctor 的核心职责是:把「你以为在读但实际没读到」的地方摊开来说清楚。
9
+ import { existsSync, readFileSync, statSync } from 'node:fs';
10
+ import { CONFIG_DIR, CONFIG_PATH, DATA_PATH, loadConfig } from './config.js';
11
+ import { loadPricing } from './pricing.js';
12
+ import { ALL_ADAPTERS } from './collector.js';
13
+ import path from 'node:path';
14
+ import os from 'node:os';
15
+ const marker = (lv) => (lv === 'ok' ? '✅' : lv === 'warn' ? '⚠️ ' : lv === 'error' ? '❌' : 'ℹ️ ');
16
+ /** 把 ~ 展开成实际路径 */
17
+ function expandHome(p) {
18
+ return p.startsWith('~') ? path.join(os.homedir(), p.slice(1)) : p;
19
+ }
20
+ /** 数据文件距今多久(分钟) */
21
+ function dataAgeMinutes() {
22
+ try {
23
+ const st = statSync(DATA_PATH);
24
+ return Math.floor((Date.now() - st.mtimeMs) / 60000);
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ export async function runDoctor() {
31
+ const items = [];
32
+ const push = (i) => items.push(i);
33
+ // ── 1. 数据目录 ──
34
+ if (existsSync(CONFIG_DIR)) {
35
+ push({ level: 'ok', title: '数据目录', detail: CONFIG_DIR });
36
+ }
37
+ else {
38
+ push({
39
+ level: 'warn',
40
+ title: '数据目录',
41
+ detail: `${CONFIG_DIR} 还不存在(首次运行后自动创建)`,
42
+ fix: '跑一次 `token-pilot sync` 就会建好',
43
+ });
44
+ }
45
+ // ── 2. 采集宿主:逐个检测,重点说清「装了但读不到」 ──
46
+ const detected = [];
47
+ const missing = [];
48
+ for (const ad of ALL_ADAPTERS) {
49
+ let yes = false;
50
+ try {
51
+ yes = await ad.detect();
52
+ }
53
+ catch {
54
+ yes = false;
55
+ }
56
+ if (yes)
57
+ detected.push(ad.meta.displayName);
58
+ else
59
+ missing.push(ad.meta.displayName);
60
+ }
61
+ if (detected.length > 0) {
62
+ push({
63
+ level: 'ok',
64
+ title: `可读宿主 ${detected.length} 个`,
65
+ detail: detected.join('、'),
66
+ });
67
+ }
68
+ else {
69
+ push({
70
+ level: 'error',
71
+ title: '没有检测到任何可读宿主',
72
+ detail: '所有 adapter 的检测路径都不存在,账单会是空的',
73
+ fix: '确认你用的 AI 工具确实写本地日志;token-pilot 只读 ~/.claude、~/.codex 等目录',
74
+ });
75
+ }
76
+ if (missing.length > 0) {
77
+ push({
78
+ level: 'info',
79
+ title: `未检测到 ${missing.length} 个宿主`,
80
+ detail: missing.join('、'),
81
+ });
82
+ }
83
+ // ── 3. 数据新鲜度:过期的账单会误导预算判断 ──
84
+ const age = dataAgeMinutes();
85
+ if (age === null) {
86
+ push({
87
+ level: 'warn',
88
+ title: '看板数据尚未生成',
89
+ detail: DATA_PATH,
90
+ fix: '跑 `token-pilot sync` 或 `token-pilot dash`',
91
+ });
92
+ }
93
+ else if (age > 60 * 24) {
94
+ push({
95
+ level: 'warn',
96
+ title: '看板数据超过一天没更新',
97
+ detail: `最后一次生成在 ${Math.floor(age / 60)} 小时前`,
98
+ fix: '桌面端会自动刷新;命令行用户请在 cron 里跑 `token-pilot sync`',
99
+ });
100
+ }
101
+ else {
102
+ push({ level: 'ok', title: '看板数据新鲜', detail: `${age} 分钟前更新` });
103
+ }
104
+ // ── 4. 定价覆盖度:这是账单准确性的根基 ──
105
+ try {
106
+ const pricing = loadPricing();
107
+ const names = Object.keys(pricing.models ?? {});
108
+ const overrideCount = Object.keys(loadConfig().priceOverrides ?? {}).length;
109
+ push({
110
+ level: names.length >= 10 ? 'ok' : 'warn',
111
+ title: `定价表覆盖 ${names.length} 个模型`,
112
+ detail: overrideCount > 0
113
+ ? `其中 ${overrideCount} 个被人工覆写(覆写优先于目录价)`
114
+ : '全部使用内置目录价',
115
+ fix: names.length < 10
116
+ ? '定价表偏小,未知模型会按 fallback 价估算,金额可能偏差'
117
+ : undefined,
118
+ });
119
+ }
120
+ catch (e) {
121
+ push({
122
+ level: 'error',
123
+ title: '定价表读取失败',
124
+ detail: String(e).slice(0, 120),
125
+ fix: '`pricing/models.json` 可能损坏,重新安装或从仓库恢复',
126
+ });
127
+ }
128
+ // ── 5. 预算配置 ──
129
+ const cfg = loadConfig();
130
+ if (cfg.monthlyBudgetCny && cfg.monthlyBudgetCny > 0) {
131
+ push({
132
+ level: 'ok',
133
+ title: '已设置月度预算',
134
+ detail: `¥${cfg.monthlyBudgetCny} · 超支达阈值会提醒`,
135
+ });
136
+ }
137
+ else {
138
+ push({
139
+ level: 'info',
140
+ title: '未设置月度预算',
141
+ detail: '设置后托盘会常驻显示「¥今日 · 预算%」,超支时主动提醒',
142
+ fix: '看板 → 数据设置 → 月度预算',
143
+ });
144
+ }
145
+ // ── 6. 配置文件本身是否合法 ──
146
+ if (existsSync(CONFIG_PATH)) {
147
+ try {
148
+ JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
149
+ push({ level: 'ok', title: '配置文件格式正确', detail: CONFIG_PATH });
150
+ }
151
+ catch {
152
+ push({
153
+ level: 'error',
154
+ title: '配置文件不是合法 JSON',
155
+ detail: CONFIG_PATH,
156
+ fix: '备份后删除它,token-pilot 会重建默认配置',
157
+ });
158
+ }
159
+ }
160
+ // ── 7. RTK:装了没 / 是哪个来源 ──
161
+ try {
162
+ const { rtkStatus } = await import('./rtk.js');
163
+ const st = await rtkStatus();
164
+ if (st.source === 'ours') {
165
+ push({ level: 'ok', title: 'RTK 输出压缩层', detail: st.detail });
166
+ }
167
+ else if (st.source === 'foreign') {
168
+ push({
169
+ level: 'info',
170
+ title: 'RTK 来源提示',
171
+ detail: st.detail,
172
+ fix: '要看板代装 rtk-oss,需先卸载现有的 rtk',
173
+ });
174
+ }
175
+ else {
176
+ push({
177
+ level: 'info',
178
+ title: '未安装 RTK 输出压缩层',
179
+ detail: '装上后命令输出会先压缩再进上下文,明显降低 token 消耗',
180
+ fix: '看板 → 数据设置 → 勾选 RTK(也可手动 `brew install rtk`)',
181
+ });
182
+ }
183
+ }
184
+ catch {
185
+ /* RTK 检测失败不影响整体自检 */
186
+ }
187
+ // ── 8. 额度监控:有哪些平台可读、哪些缺凭证 ──
188
+ try {
189
+ const { collectQuota } = await import('./quota/index.js');
190
+ const snap = await collectQuota(true);
191
+ const okList = snap.providers.filter((p) => p.ok);
192
+ const failList = snap.providers.filter((p) => !p.ok);
193
+ if (okList.length > 0) {
194
+ push({
195
+ level: 'ok',
196
+ title: `额度可读 ${okList.length} 个平台`,
197
+ detail: okList.map((p) => p.displayName).join('、'),
198
+ });
199
+ }
200
+ if (failList.length > 0) {
201
+ // 这些都是「可选能力」,用 info 不用 warn——不配也不影响账单
202
+ push({
203
+ level: 'info',
204
+ title: `${failList.length} 个平台额度暂不可读`,
205
+ detail: failList.map((p) => `${p.displayName}:${p.error ?? '未知原因'}`).join(';'),
206
+ fix: '在看板「数据设置」里填对应 API Key,或确认该平台的 CLI 已登录',
207
+ });
208
+ }
209
+ }
210
+ catch {
211
+ /* 额度检测失败不影响自检主流程 */
212
+ }
213
+ // ── 汇总 ──
214
+ const ok = items.filter((i) => i.level === 'ok').length;
215
+ const warn = items.filter((i) => i.level === 'warn').length;
216
+ const error = items.filter((i) => i.level === 'error').length;
217
+ // 建议只取 error/warn,且每条带 fix
218
+ const advice = items
219
+ .filter((i) => (i.level === 'error' || i.level === 'warn') && i.fix)
220
+ .sort((a, b) => (a.level === 'error' ? -1 : 1) - (b.level === 'error' ? -1 : 1))
221
+ .map((i) => i.fix);
222
+ return { items, ok, warn, error, advice };
223
+ }
224
+ export function formatDoctor(r) {
225
+ const lines = [];
226
+ lines.push('');
227
+ lines.push('token-pilot · 环境自检');
228
+ lines.push('');
229
+ for (const i of r.items) {
230
+ lines.push(` ${marker(i.level)} ${i.title}`);
231
+ lines.push(` ${i.detail}`);
232
+ if (i.fix)
233
+ lines.push(` → ${i.fix}`);
234
+ }
235
+ lines.push('');
236
+ lines.push(` 合计:${r.ok} 项正常 · ${r.warn} 项建议处理 · ${r.error} 项有问题`);
237
+ if (r.advice.length > 0) {
238
+ lines.push('');
239
+ lines.push(' 接下来可以做:');
240
+ for (const a of r.advice.slice(0, 5))
241
+ lines.push(` · ${a}`);
242
+ }
243
+ else {
244
+ lines.push('');
245
+ lines.push(' 一切就绪,没有需要处理的项。');
246
+ }
247
+ lines.push('');
248
+ return lines.join('\n');
249
+ }
@@ -0,0 +1,139 @@
1
+ // 凭证解析:三层优先级,确保「不装 CC Switch 也能用」
2
+ //
3
+ // ① from-config —— 用户在 token-pilot 设置里填的 key。永远可用。
4
+ // ② from-native —— 各平台自己的凭证文件(OpenCode auth.json、Kimi credentials、
5
+ // arkcli profile...)。装了该平台工具就有。
6
+ // ③ from-ccswitch —— CC Switch 数据库。装了才有,只作为「省去手填」的便利。
7
+ //
8
+ // 关键约束:任何额度 provider 都必须能在只有 ① 的情况下工作。
9
+ // ③ 是锦上添花,绝不是必需品——这是产品决策,不是技术妥协。
10
+ import { existsSync, readFileSync } from 'node:fs';
11
+ import { execFile } from 'node:child_process';
12
+ import { promisify } from 'node:util';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { loadConfig } from '../config.js';
16
+ const execFileP = promisify(execFile);
17
+ /** 从 token-pilot 自己的配置读(优先级最高,用户显式填的) */
18
+ export function fromConfig(providerId) {
19
+ const cfg = loadConfig();
20
+ const key = cfg.quotaKeys?.[providerId];
21
+ if (!key || !key.trim())
22
+ return null;
23
+ return { key: key.trim(), origin: 'config', detail: '来自 token-pilot 设置' };
24
+ }
25
+ /** 各平台的原生凭证位置(不依赖 CC Switch) */
26
+ const NATIVE_PATHS = {
27
+ deepseek: [
28
+ {
29
+ file: '~/.config/token-pilot/keys.json',
30
+ pick: (d) => d?.deepseek ?? null,
31
+ },
32
+ ],
33
+ moonshot: [
34
+ {
35
+ file: '~/.config/token-pilot/keys.json',
36
+ pick: (d) => d?.moonshot ?? null,
37
+ },
38
+ ],
39
+ };
40
+ function expandHome(p) {
41
+ return p.startsWith('~') ? path.join(os.homedir(), p.slice(1)) : p;
42
+ }
43
+ export function fromNative(providerId) {
44
+ const specs = NATIVE_PATHS[providerId];
45
+ if (!specs)
46
+ return null;
47
+ for (const spec of specs) {
48
+ const p = expandHome(spec.file);
49
+ if (!existsSync(p))
50
+ continue;
51
+ try {
52
+ const key = spec.pick(JSON.parse(readFileSync(p, 'utf8')));
53
+ if (key && key.trim()) {
54
+ return { key: key.trim(), origin: 'native', detail: `来自 ${spec.file}` };
55
+ }
56
+ }
57
+ catch {
58
+ /* 单个来源解析失败不影响其它来源 */
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * 从 CC Switch 数据库读(可选增强)。
65
+ *
66
+ * 表结构:providers(id, name, app_type, settings_config)
67
+ * settings_config 是 JSON,env 字段里存 ANTHROPIC_AUTH_TOKEN / OPENAI_API_KEY 等。
68
+ *
69
+ * 只读模式打开,绝不写入。用 CLI 读而不是引入 sqlite 依赖——
70
+ * 我们的原则是零运行时依赖。
71
+ */
72
+ export async function fromCcSwitch(providerNamePattern) {
73
+ const dbPath = path.join(os.homedir(), '.cc-switch', 'cc-switch.db');
74
+ if (!existsSync(dbPath))
75
+ return null;
76
+ try {
77
+ // 用 python3 的 sqlite3(macOS/Linux 自带),避免引入 npm 依赖
78
+ const script = `
79
+ import sqlite3, json, sys, re
80
+ con = sqlite3.connect('file:${dbPath}?mode=ro', uri=True)
81
+ cur = con.cursor()
82
+ cur.execute("SELECT name, settings_config FROM providers")
83
+ pat = re.compile(sys.argv[1], re.I)
84
+ for name, cfg in cur.fetchall():
85
+ if not pat.search(name or ''):
86
+ continue
87
+ try:
88
+ d = json.loads(cfg) if isinstance(cfg, str) else cfg
89
+ except Exception:
90
+ continue
91
+ env = (d or {}).get('env') or {}
92
+ for k, v in env.items():
93
+ ku = k.upper()
94
+ if ('KEY' in ku or 'TOKEN' in ku) and isinstance(v, str) and v.strip():
95
+ print(json.dumps({'name': name, 'envKey': k, 'value': v.strip()}))
96
+ sys.exit(0)
97
+ print('')
98
+ `;
99
+ const { stdout } = await execFileP('python3', ['-c', script, providerNamePattern], {
100
+ timeout: 8000,
101
+ });
102
+ const line = stdout.trim();
103
+ if (!line || line === '""')
104
+ return null;
105
+ const parsed = JSON.parse(line);
106
+ return {
107
+ key: parsed.value,
108
+ origin: 'ccswitch',
109
+ detail: `来自 CC Switch 的「${parsed.name}」配置`,
110
+ };
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ /**
117
+ * 三层依次尝试。全部失败返回 null,调用方负责给出「去哪里填」的提示。
118
+ */
119
+ export async function resolveKey(providerId, ccSwitchPattern) {
120
+ return (fromConfig(providerId) ??
121
+ fromNative(providerId) ??
122
+ (ccSwitchPattern ? await fromCcSwitch(ccSwitchPattern) : null));
123
+ }
124
+ /** 读取火山 profile 列表(判断有没有订阅,不需要 arkcli 登录态之外的权限) */
125
+ export async function volcProfiles() {
126
+ try {
127
+ const { stdout } = await execFileP('arkcli', ['profile', 'list', '--format', 'json'], {
128
+ timeout: 15_000,
129
+ });
130
+ const d = JSON.parse(stdout);
131
+ return {
132
+ defaultProfile: d.default_profile,
133
+ names: (d.profiles ?? []).map((p) => p.name),
134
+ };
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }