@anthonyhan/token-pilot 0.2.4 → 0.3.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
@@ -10,7 +10,7 @@
10
10
 
11
11
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
12
12
  [![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Windows-lightgrey)](#-状态栏应用)
13
- [![Tests](https://img.shields.io/badge/tests-40%20passing-brightgreen)](tests/)
13
+ [![Tests](https://img.shields.io/badge/tests-42%20passing-brightgreen)](tests/)
14
14
  [![Accuracy](https://img.shields.io/badge/对账脚本-逐项一致-blue)](#-数据准确性)
15
15
 
16
16
  [快速开始](#-快速开始) · [状态栏应用](#-状态栏应用) · [数据准确性](#-数据准确性) · [什么时候别用它](#-什么时候别用它) · [TODO](#-todo-list) · [English](README-en.md) · [llms.txt](llms.txt)
@@ -23,7 +23,7 @@
23
23
 
24
24
  > 状态栏常驻 `⚡ ¥今日 · 预算%`。左键弹面板,「打开完整看板」看全部。我的真实 10 月:**810M tokens · ¥2,546 · 12,685 次调用**([怎么算的](#-数据准确性))。
25
25
 
26
- > ⚠️ **注意**:npm 上的 \`token-pilot\` 是别人的同名包(MCP 代码导航工具,会往 Claude Code 写 hooks)。**我们的包叫 \`@anthonyhan/token-pilot\`**,别装错:
26
+ > ⚠️ npm 上另有一个**别人家的** `token-pilot`(MCP 代码导航工具,会往 Claude Code 写 hooks)。我们的包是 **`@anthonyhan/token-pilot`**,下面命令都带 scope,照抄即可。
27
27
 
28
28
  ## 🚀 快速开始
29
29
 
@@ -40,9 +40,25 @@ token-pilot month # 本月账单 + 月底预测 + 打转检测 + 省钱建
40
40
 
41
41
  ### 状态栏应用
42
42
 
43
- [Releases](../../releases) 下载 `.dmg`(macOS Apple Silicon)/ `.msi`(Windows x64)。安装启动后**只在状态栏显示一个闪电图标**——无 Dock 图标、无启动窗口;左键弹面板,右键出菜单。
43
+ 安装启动后**只在状态栏显示一个闪电图标**——无 Dock 图标、无启动窗口;左键弹面板,右键出菜单。
44
44
 
45
- > 未签名:macOS 首次打开需右键 → 打开;Windows SmartScreen 选「仍要运行」。自己构建:`cd menubar && npm install && npx tauri build`
45
+ **macOS(Apple Silicon / Intel)**:
46
+
47
+ ```bash
48
+ # 方式一:Homebrew(推荐,自动处理 Gatekeeper,装完即用)
49
+ brew install --cask anthonyhann/token-pilot/token-pilot
50
+ ```
51
+
52
+ ```bash
53
+ # 方式二:Releases 手动下载 .dmg,拖入「应用程序」后跑一次(解决未签名的「已损坏」误报)
54
+ xattr -dr com.apple.quarantine /Applications/token-pilot.app
55
+ ```
56
+
57
+ **Windows**:Releases 下载 `.msi`,SmartScreen 选「仍要运行」。
58
+
59
+ > 长期解:Apple 开发者签名+公证($99/年)在 TODO 里,有赞助再开。
60
+
61
+ 自己构建:`cd menubar && npm install && npx tauri build`
46
62
 
47
63
  ## ✨ 它能做什么
48
64
 
@@ -53,6 +69,7 @@ token-pilot month # 本月账单 + 月底预测 + 打转检测 + 省钱建
53
69
  | Agent 打转 | 不用说话 | 自动揪出「单会话 ≥30 次调用」的死循环,算出浪费金额 |
54
70
  | 想省钱 | 看「省钱建议」卡 | 贵模型干轻活 → 迁移建议+每月省多少;低缓存命中 → 优化空间;本月缓存帮你省了多少 |
55
71
  | 上下文太长 | 自动提醒 / 点徽标 | 会话超 100K 上下文标记「该压缩」,可写 Claude Code autoCompact / 一键装 RTK 输出压缩层 |
72
+ | 想知道能省多少 | 看「压缩潜力」板块 | 本月陈旧输出/重复读取/超长输出各浪费多少钱,按模式拆分 + 列出最浪费的 5 个会话 |
56
73
  | 核对价格 | `token-pilot prices` | 每个在用模型的单价来源(目录价/人工覆写/自动补价待核对) |
57
74
  | 谁在烧 | 看「宿主/模型/项目榜」 | 哪个工具、哪个模型、哪个项目花最多,一目了然 |
58
75
  | 国产模型 | 不用配置 | DeepSeek/GLM/Kimi/Qwen 走宿主日志 model 字段自动归一 |
@@ -66,7 +83,7 @@ token-pilot month # 本月账单 + 月底预测 + 打转检测 + 省钱建
66
83
  ```bash
67
84
  python3 scripts/reconcile.py month # 第三方视角独立重算原始日志,与 CLI 逐项对账
68
85
  python3 scripts/verify-dashboard.py # 看板 36 项算法不变量校验
69
- npm test # 40 个单元测试(定价/采集口径/聚合/注入)
86
+ npm test # 42 个单元测试(定价/采集口径/聚合/注入/熔断)
70
87
  ```
71
88
 
72
89
  实测修过的口径坑(2026-10-21,本机 4787 个日志文件):
@@ -80,7 +97,7 @@ npm test # 40 个单元测试(定价/采集口径
80
97
  ## 📊 凭什么信我
81
98
 
82
99
  - 我自己的 AI 账单就是它管的:本月 **¥2,546 / 810M tokens**(2026-10-21,上方截图即本机实时数据)
83
- - 36 项看板算法不变量 + 22 个单测 + 独立对账脚本,全部开箱可跑
100
+ - 36 项看板算法不变量 + 42 个单测 + 独立对账脚本,全部开箱可跑
84
101
  - 诚实披露速率口径:日志按「调用完成时刻」记账,生成中的调用完成前不计入(看板内有注明)
85
102
 
86
103
  ## ⚠️ 什么时候别用它
@@ -109,7 +126,14 @@ token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝
109
126
 
110
127
  ## 📝 更新日志
111
128
 
112
- - **2026-10-21** v0.1.0:首版 → CLI 账单 + 本地看板 + macOS/Windows 状态栏应用,三形态一次给齐
129
+ 完整分版本说明见 [RELEASE_NOTES.md](RELEASE_NOTES.md)(也是客户端自动更新弹窗的文案来源)。
130
+
131
+ - **v0.2.6** 激活自动更新链路 + 打转熔断主动通知(含防轰炸)
132
+ - **v0.2.5** npm scope 校正为 `@anthonyhann`,包可运行性修复
133
+ - **v0.2.3** 2B 压缩执行第一层(自动压缩 + autoCompact 写入 + RTK)、价格核对台
134
+ - **v0.2.1** 定价表对齐 8 家官方目录价、DeepSeek 分时、面板布局修复
135
+ - **v0.2.0** 压缩潜力量化、9 源采集覆盖、三处口径修复
136
+ - **v0.1.0** 首版 → CLI 账单 + 本地看板 + macOS/Windows 状态栏应用,三形态一次给齐
113
137
 
114
138
  ## ✅ TODO LIST
115
139
 
@@ -124,16 +148,17 @@ token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝
124
148
  **节流(Step 2)**
125
149
  - [x] 2A 压缩潜力量化(规则引擎:陈旧输出/重复读取/超长输出 → 本月可省多少,实测 $63-95)
126
150
  - [x] 2B 压缩执行第一层:自动压缩提醒 + Claude autoCompact 写入 + RTK 一键安装
151
+ - [x] 异常重试自动熔断提醒(`breaker.ts`:单会话 ≥30 次调用即主动通知,每轮最多提 1 个防首跑轰炸)
127
152
  - [ ] 2B 压缩执行第二层:代理网关(LiteLLM/自研,视数据再定)
128
153
  - [ ] 低价模型路由(本地代理层,可选开启,默认不动你任何配置)
129
- - [ ] 异常重试自动熔断提醒(已有检测,加主动通知策略)
130
154
 
131
155
  **平台与工程**
132
- - [x] macOS 状态栏应用(arm64 .app/.dmg)
133
- - [x] Windows 核查 + 分平台图标 + CI
134
- - [ ] Windows .msi 实机验证(Actions 产物)
135
- - [ ] Intel Mac 包(universal2)
136
- - [ ] 自动更新(tauri-updater)
156
+ - [x] macOS 状态栏应用(arm64 + Intel x64 双架构 .app/.dmg)
157
+ - [x] Windows 核查 + 分平台图标 + CI(`.msi` 由 Actions 产出)
158
+ - [x] 自动更新(tauri-updater,v0.2.6 起生效,三平台共用一份 `latest.json`)
159
+ - [x] CI 自动发布:打 tag 后三平台产物 + 合并版 `latest.json` 自动进 Release,并回写 brew cask
160
+ - [ ] Windows `.msi` 实机安装验证(目前只验证到 Actions 产物层)
161
+ - [ ] 统一二进制(universal2 单包替代 arm64/x64 两个 dmg)
137
162
  - [ ] 签名与公证(Apple Developer $99/年,有赞助再开)
138
163
 
139
164
  ## English
package/dist/cli/index.js CHANGED
@@ -11,6 +11,7 @@ import { writeSummary } from '../core/metrics.js';
11
11
  import { collectAll, collectCached, acquireSyncLock, releaseSyncLock } from '../core/collector.js';
12
12
  import { hasKnownPrice, priceFor } from '../core/pricing.js';
13
13
  import { trackUnknown, loadUnknown } from '../core/unknown-models.js';
14
+ import { notifyRetryLoops } from '../core/breaker.js';
14
15
  import { autoFetchPrices, autoOverrides } from '../core/price-fetch.js';
15
16
  import { buildDashboardData } from '../core/aggregate.js';
16
17
  import { serve, bakeDashboard, writeDashboardDataFile } from './serve.js';
@@ -149,6 +150,13 @@ async function cmdSync() {
149
150
  for (const n of fetched)
150
151
  console.log(` + ${n}`);
151
152
  }
153
+ // 打转熔断通知(菜单栏 sync 路径)
154
+ try {
155
+ const weekAgo = Date.now() - 7 * 86400_000;
156
+ const alerts = detectRetryLoops(events.filter((e) => e.timestamp >= weekAgo), (m, u) => costOf(m, u, pricing), { minCallsPerSession: 30, minCostUsd: 0.3 });
157
+ notifyRetryLoops(alerts);
158
+ }
159
+ catch { /* 不阻塞 */ }
152
160
  const data = await buildDashboardData(events, cfg, loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx), contentEvents);
153
161
  writeDashboardDataFile(data);
154
162
  console.log(`token-pilot sync · ${detected.length} 宿主 · 解析 ${parsedFiles} 文件 / 缓存命中 ${cachedFiles}`);
package/dist/cli/serve.js CHANGED
@@ -18,6 +18,9 @@ import { loadPricingWithOverrides } from '../core/pricing.js';
18
18
  import { loadConfig, saveConfig, fxRate, monthlyBudgetCny, DATA_PATH, CONFIG_DIR } from '../core/config.js';
19
19
  import { notify } from '../core/alert.js';
20
20
  import { applyClaudeAutoCompact } from '../core/autocompact.js';
21
+ import { costOf } from '../core/pricing.js';
22
+ import { detectRetryLoops } from '../core/retry-detector.js';
23
+ import { notifyRetryLoops } from '../core/breaker.js';
21
24
  import { installRtk, uninstallRtk, rtkInstalled } from '../core/rtk.js';
22
25
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
26
  const WEB_DIR = path.resolve(__dirname, '../../web');
@@ -51,6 +54,14 @@ export async function refreshOnce(state) {
51
54
  }
52
55
  state.lastAlertPct = pct;
53
56
  }
57
+ // 打转熔断:近 7 天检测到打转就主动通知(每会话每天一次)
58
+ try {
59
+ const weekAgo = Date.now() - 7 * 86400_000;
60
+ const weekEvents = (await state.collector.sync()).events.filter((e) => e.timestamp >= weekAgo);
61
+ const alerts = detectRetryLoops(weekEvents, (m, u) => costOf(m, u, pricing), { minCallsPerSession: 30, minCostUsd: 0.3 });
62
+ notifyRetryLoops(alerts);
63
+ }
64
+ catch { /* 不阻塞 */ }
54
65
  // 自动压缩提醒(开关开着时):超阈值会话发系统通知,单会话 30min 冷却
55
66
  const ac = cfg.autoCompact;
56
67
  if (ac?.enabled && data.live.sessions.some((s) => s.needsCompact)) {
@@ -478,16 +478,8 @@ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents
478
478
  sessions: comp.sessions.map((s) => ({ key: s.key, agent: s.agent, wasteCny: s.wasteUsd * fx, items: s.items, topPatterns: s.topPatterns })),
479
479
  }
480
480
  : null;
481
- // 压缩潜力够大才进省钱建议卡(第 4 张)
482
- if (compression && compression.potentialCny >= 5) {
483
- savings.push({
484
- kind: 'pos',
485
- icon: 'cache',
486
- title: '上下文压缩空间',
487
- desc: `本月 ${compression.itemCount} 处上下文重发可压缩(陈旧输出/重复读取/超长日志),若压缩约省 ${fmtCny(compression.potentialCny)}–${fmtCny(compression.potentialCnyMax)}。运行 token-pilot compress-report 看明细。`,
488
- amount: `约省 ${fmtCny(compression.potentialCny)}/月`,
489
- });
490
- }
481
+ // 压缩潜力不再塞进省钱建议卡:看板已有独立的「压缩潜力」板块
482
+ // (带模式拆分 + 最浪费会话),原先这里再放一张会让同一件事重复出现。
491
483
  // ---------- 2B:该 compact 了(活跃会话上下文超阈值) ----------
492
484
  const COMPACT_AT = 100_000;
493
485
  const needCompact = live.sessions.filter((s) => s.needsCompact);
@@ -0,0 +1,49 @@
1
+ // 打转熔断通知策略 — 检测到的打转会话主动弹系统通知(每会话每天最多一次,不轰炸)
2
+ // 状态落盘 ~/.token-pilot/alerted-sessions.json(CLI sync 是短命进程,必须持久化冷却)
3
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { CONFIG_DIR } from './config.js';
6
+ import { notify } from './alert.js';
7
+ const STATE_PATH = path.join(CONFIG_DIR, 'alerted-sessions.json');
8
+ const COOLDOWN_MS = 86400_000; // 每会话每天最多一次
9
+ function load() {
10
+ if (!existsSync(STATE_PATH))
11
+ return { sessions: {} };
12
+ try {
13
+ return JSON.parse(readFileSync(STATE_PATH, 'utf8'));
14
+ }
15
+ catch {
16
+ return { sessions: {} };
17
+ }
18
+ }
19
+ function save(s) {
20
+ mkdirSync(CONFIG_DIR, { recursive: true });
21
+ writeFileSync(STATE_PATH, JSON.stringify(s), 'utf8');
22
+ }
23
+ // 对检测到的打转会话发通知;返回新通知的会话数
24
+ export function notifyRetryLoops(alerts, now = Date.now()) {
25
+ if (alerts.length === 0)
26
+ return 0;
27
+ const state = load();
28
+ // 每次最多通知 1 个(最严重的):首次运行不清历史账,防通知轰炸
29
+ const sorted = [...alerts].sort((a, b) => b.totalCostUsd - a.totalCostUsd);
30
+ let sent = 0;
31
+ for (const a of sorted) {
32
+ const key = `${a.agent}:${a.sessionId}`;
33
+ const last = state.sessions[key] ?? 0;
34
+ if (now - last < COOLDOWN_MS)
35
+ continue;
36
+ state.sessions[key] = now;
37
+ notify('token-pilot · 检测到打转', `${a.agent} 一个会话重复调用 ${a.calls} 次(烧 ¥${(a.totalCostUsd * 7.2).toFixed(0)}),疑似死循环,建议人工介入。`);
38
+ sent++;
39
+ break; // 最多 1 个
40
+ }
41
+ // 冷却外的其余会话也标记为已通知(不清历史账)
42
+ for (const a of sorted) {
43
+ const key = `${a.agent}:${a.sessionId}`;
44
+ if (!state.sessions[key])
45
+ state.sessions[key] = now;
46
+ }
47
+ save(state);
48
+ return sent;
49
+ }
@@ -2,7 +2,10 @@
2
2
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
- export const CONFIG_DIR = path.join(os.homedir(), '.token-pilot');
5
+ // 状态目录:测试用 TOKEN_PILOT_HOME 隔离到临时目录,避免碰用户真实数据
6
+ export const CONFIG_DIR = process.env.TOKEN_PILOT_HOME
7
+ ? path.resolve(process.env.TOKEN_PILOT_HOME)
8
+ : path.join(os.homedir(), '.token-pilot');
6
9
  export const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
7
10
  export const DATA_PATH = path.join(CONFIG_DIR, 'dashboard-data.json');
8
11
  export function loadConfig() {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@anthonyhan/token-pilot",
3
- "version": "0.2.4",
4
- "description": "\u4f60\u6240\u6709 AI \u5de5\u5177\u7684\u672c\u5730\u8d26\u5355 + \u9884\u7b97\u63a7\u5236\u5668 \u2014 \u53ea\u8bfb\u672c\u5730\u65e5\u5fd7\uff0c\u96f6\u5165\u4fb5\uff0c\u4e0d\u51fa\u672c\u673a",
3
+ "version": "0.3.1",
4
+ "description": "你所有 AI 工具的本地账单 + 预算控制器 — 只读本地日志,零入侵,不出本机",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "token-pilot": "./bin/token-pilot.js"
@@ -9,6 +9,8 @@
9
9
  "scripts": {
10
10
  "build": "tsc",
11
11
  "dev": "tsc --watch",
12
+ "sync:assets": "node scripts/sync-web-assets.js",
13
+ "verify:assets": "node scripts/sync-web-assets.js --check",
12
14
  "today": "npx tsx src/cli/index.ts today",
13
15
  "test": "npx tsx --test tests/*.test.ts",
14
16
  "prepublishOnly": "npm run build"
@@ -28,6 +30,7 @@
28
30
  "files": [
29
31
  "dist",
30
32
  "pricing",
31
- "bin"
33
+ "bin",
34
+ "web"
32
35
  ]
33
36
  }