@anthonyhan/token-pilot 0.2.3 → 0.2.4

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 (161) hide show
  1. package/bin/token-pilot.js +10 -7
  2. package/dist/adapters/claude-code.js +251 -0
  3. package/dist/adapters/codex.js +163 -0
  4. package/dist/adapters/dsh.js +163 -0
  5. package/dist/adapters/kimi-code.js +165 -0
  6. package/dist/adapters/opencode.js +126 -0
  7. package/dist/adapters/pi.js +119 -0
  8. package/dist/adapters/qoder.js +51 -0
  9. package/dist/adapters/types.js +7 -0
  10. package/dist/adapters/volc-ark.js +92 -0
  11. package/dist/adapters/workbuddy.js +144 -0
  12. package/dist/cli/index.js +278 -0
  13. package/dist/cli/serve.js +200 -0
  14. package/dist/core/aggregate.js +821 -0
  15. package/dist/core/alert.js +32 -0
  16. package/dist/core/autocompact.js +40 -0
  17. package/dist/core/budget.js +23 -0
  18. package/dist/core/collector.js +213 -0
  19. package/dist/core/compression.js +129 -0
  20. package/dist/core/config.js +41 -0
  21. package/dist/core/contract.js +4 -0
  22. package/dist/core/metrics.js +53 -0
  23. package/dist/core/price-fetch.js +128 -0
  24. package/dist/core/pricing.js +156 -0
  25. package/dist/core/registry.js +144 -0
  26. package/dist/core/retry-detector.js +41 -0
  27. package/dist/core/rtk.js +58 -0
  28. package/dist/core/savings.js +43 -0
  29. package/dist/core/schema.js +3 -0
  30. package/dist/core/unknown-models.js +50 -0
  31. package/package.json +16 -6
  32. package/.github/FUNDING.yml +0 -3
  33. package/.github/workflows/build-desktop.yml +0 -68
  34. package/.idea/go.imports.xml +0 -10
  35. package/.idea/modules.xml +0 -8
  36. package/.idea/sonarlint/vulnerabilitystore/default/index.pb +0 -0
  37. package/.idea/thriftCompilerAssist.xml +0 -6
  38. package/.idea/token-pilot.iml +0 -9
  39. package/.idea/vcs.xml +0 -6
  40. package/README-en.md +0 -127
  41. package/docs/assets/dashboard.png +0 -0
  42. package/docs/assets/icon.png +0 -0
  43. package/docs/assets/menubar-panel.png +0 -0
  44. package/docs/assets/sponsor-alipay.png +0 -0
  45. package/docs/assets/sponsor-wechat.png +0 -0
  46. package/llms.txt +0 -40
  47. package/menubar/package-lock.json +0 -248
  48. package/menubar/package.json +0 -16
  49. package/menubar/src/dashboard.html +0 -1266
  50. package/menubar/src/index.html +0 -674
  51. package/menubar/src-tauri/Cargo.lock +0 -4963
  52. package/menubar/src-tauri/Cargo.toml +0 -15
  53. package/menubar/src-tauri/build.rs +0 -3
  54. package/menubar/src-tauri/gen/schemas/acl-manifests.json +0 -1
  55. package/menubar/src-tauri/gen/schemas/capabilities.json +0 -1
  56. package/menubar/src-tauri/gen/schemas/desktop-schema.json +0 -2526
  57. package/menubar/src-tauri/gen/schemas/macOS-schema.json +0 -2526
  58. package/menubar/src-tauri/icons/128x128.png +0 -0
  59. package/menubar/src-tauri/icons/128x128@2x.png +0 -0
  60. package/menubar/src-tauri/icons/32x32.png +0 -0
  61. package/menubar/src-tauri/icons/64x64.png +0 -0
  62. package/menubar/src-tauri/icons/Square107x107Logo.png +0 -0
  63. package/menubar/src-tauri/icons/Square142x142Logo.png +0 -0
  64. package/menubar/src-tauri/icons/Square150x150Logo.png +0 -0
  65. package/menubar/src-tauri/icons/Square284x284Logo.png +0 -0
  66. package/menubar/src-tauri/icons/Square30x30Logo.png +0 -0
  67. package/menubar/src-tauri/icons/Square310x310Logo.png +0 -0
  68. package/menubar/src-tauri/icons/Square44x44Logo.png +0 -0
  69. package/menubar/src-tauri/icons/Square71x71Logo.png +0 -0
  70. package/menubar/src-tauri/icons/Square89x89Logo.png +0 -0
  71. package/menubar/src-tauri/icons/StoreLogo.png +0 -0
  72. package/menubar/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml +0 -5
  73. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png +0 -0
  74. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  75. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png +0 -0
  76. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png +0 -0
  77. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  78. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png +0 -0
  79. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png +0 -0
  80. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  81. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png +0 -0
  82. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png +0 -0
  83. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  84. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  85. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png +0 -0
  86. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  87. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  88. package/menubar/src-tauri/icons/android/values/ic_launcher_background.xml +0 -4
  89. package/menubar/src-tauri/icons/icon.icns +0 -0
  90. package/menubar/src-tauri/icons/icon.ico +0 -0
  91. package/menubar/src-tauri/icons/icon.png +0 -0
  92. package/menubar/src-tauri/icons/ios/AppIcon-20x20@1x.png +0 -0
  93. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x-1.png +0 -0
  94. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x.png +0 -0
  95. package/menubar/src-tauri/icons/ios/AppIcon-20x20@3x.png +0 -0
  96. package/menubar/src-tauri/icons/ios/AppIcon-29x29@1x.png +0 -0
  97. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x-1.png +0 -0
  98. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x.png +0 -0
  99. package/menubar/src-tauri/icons/ios/AppIcon-29x29@3x.png +0 -0
  100. package/menubar/src-tauri/icons/ios/AppIcon-40x40@1x.png +0 -0
  101. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x-1.png +0 -0
  102. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x.png +0 -0
  103. package/menubar/src-tauri/icons/ios/AppIcon-40x40@3x.png +0 -0
  104. package/menubar/src-tauri/icons/ios/AppIcon-512@2x.png +0 -0
  105. package/menubar/src-tauri/icons/ios/AppIcon-60x60@2x.png +0 -0
  106. package/menubar/src-tauri/icons/ios/AppIcon-60x60@3x.png +0 -0
  107. package/menubar/src-tauri/icons/ios/AppIcon-76x76@1x.png +0 -0
  108. package/menubar/src-tauri/icons/ios/AppIcon-76x76@2x.png +0 -0
  109. package/menubar/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png +0 -0
  110. package/menubar/src-tauri/icons/tray-win.png +0 -0
  111. package/menubar/src-tauri/icons/tray.png +0 -0
  112. package/menubar/src-tauri/src/main.rs +0 -486
  113. package/menubar/src-tauri/tauri.conf.json +0 -56
  114. package/scripts/gen-icons.py +0 -153
  115. package/scripts/reconcile.py +0 -162
  116. package/scripts/verify-dashboard.py +0 -101
  117. package/src/adapters/claude-code.ts +0 -246
  118. package/src/adapters/codex.ts +0 -166
  119. package/src/adapters/dsh.ts +0 -156
  120. package/src/adapters/kimi-code.ts +0 -164
  121. package/src/adapters/opencode.ts +0 -120
  122. package/src/adapters/pi.ts +0 -99
  123. package/src/adapters/qoder.ts +0 -43
  124. package/src/adapters/types.ts +0 -39
  125. package/src/adapters/volc-ark.ts +0 -102
  126. package/src/adapters/workbuddy.ts +0 -135
  127. package/src/cli/index.ts +0 -294
  128. package/src/cli/serve.ts +0 -209
  129. package/src/core/aggregate.ts +0 -821
  130. package/src/core/alert.ts +0 -33
  131. package/src/core/autocompact.ts +0 -46
  132. package/src/core/budget.ts +0 -42
  133. package/src/core/collector.ts +0 -209
  134. package/src/core/compression.ts +0 -163
  135. package/src/core/config.ts +0 -71
  136. package/src/core/contract.ts +0 -181
  137. package/src/core/metrics.ts +0 -72
  138. package/src/core/price-fetch.ts +0 -112
  139. package/src/core/pricing.ts +0 -182
  140. package/src/core/registry.ts +0 -141
  141. package/src/core/retry-detector.ts +0 -64
  142. package/src/core/rtk.ts +0 -58
  143. package/src/core/savings.ts +0 -55
  144. package/src/core/schema.ts +0 -66
  145. package/src/core/unknown-models.ts +0 -64
  146. package/tests/adapters-dsh.test.ts +0 -35
  147. package/tests/adapters-opencode.test.ts +0 -39
  148. package/tests/adapters-pi.test.ts +0 -33
  149. package/tests/adapters-workbuddy.test.ts +0 -34
  150. package/tests/adapters.test.ts +0 -45
  151. package/tests/aggregate.test.ts +0 -153
  152. package/tests/compression.test.ts +0 -71
  153. package/tests/fixtures/claude-session.jsonl +0 -9
  154. package/tests/fixtures/codex-rollout.jsonl +0 -5
  155. package/tests/fixtures/kimi-wire.jsonl +0 -6
  156. package/tests/pricing-timebased.test.ts +0 -51
  157. package/tests/pricing.test.ts +0 -73
  158. package/tests/serve.test.ts +0 -29
  159. package/tsconfig.json +0 -19
  160. package/web/dashboard.html +0 -1266
  161. package/web/panel.html +0 -674
@@ -1,141 +0,0 @@
1
- // 数据源注册表 — 25 个源、6 档,驱动「适配器状态」模块与宿主用量榜的分档标签
2
- // 状态语义:on=有数据接入 · part=部分支持/验证中 · off=未配置 · sub=仅检测/订阅登记
3
-
4
- import { promises as fs } from 'node:fs';
5
- import path from 'node:path';
6
- import os from 'node:os';
7
- import type { AdapterChip, AdapterTier } from './contract.ts';
8
- import type { TokenPilotConfig } from './config.ts';
9
-
10
- const HOME = os.homedir();
11
-
12
- async function exists(p: string): Promise<boolean> {
13
- try { await fs.access(p); return true; } catch { return false; }
14
- }
15
-
16
- async function countMatching(dir: string, match: (name: string, isDir: boolean) => boolean, depth = 6): Promise<number> {
17
- let n = 0;
18
- async function walk(d: string, lv: number) {
19
- if (lv > depth) return;
20
- let entries;
21
- try { entries = await fs.readdir(d, { withFileTypes: true }); } catch { return; }
22
- for (const e of entries) {
23
- if (match(e.name, e.isDirectory())) n++;
24
- if (e.isDirectory()) await walk(path.join(d, e.name), lv + 1);
25
- }
26
- }
27
- await walk(dir, 0);
28
- return n;
29
- }
30
-
31
- export interface HostTierInfo { label: string; cls: 'tier-1' | 'tier-2' | 'tier-0' }
32
-
33
- // 宿主用量榜的分档标签
34
- export const HOST_TIERS: Record<string, HostTierInfo> = {
35
- 'claude-code': { label: '一档', cls: 'tier-1' },
36
- 'kimi-code': { label: '一档', cls: 'tier-1' },
37
- 'codex': { label: '一档', cls: 'tier-1' },
38
- 'pi': { label: '一档', cls: 'tier-1' },
39
- 'dsh': { label: '一档', cls: 'tier-1' },
40
- 'workbuddy': { label: '一档', cls: 'tier-1' },
41
- 'workbuddy-ai': { label: '一档', cls: 'tier-1' },
42
- 'volc-ark': { label: '四档', cls: 'tier-2' },
43
- 'opencode': { label: '二档', cls: 'tier-2' },
44
- 'qoder': { label: '无 token', cls: 'tier-0' },
45
- };
46
-
47
- export async function buildAdapterTiers(cfg: TokenPilotConfig): Promise<AdapterTier[]> {
48
- // ---- 一档:本地日志直读 ----
49
- const claudeDir = path.join(HOME, '.claude', 'projects');
50
- const dshDir = path.join(HOME, '.dsh', 'sessions');
51
- const kimiDir = path.join(HOME, '.kimi-code', 'sessions');
52
- const codexDir = path.join(HOME, '.codex', 'sessions');
53
- const piDir = path.join(HOME, '.pi');
54
-
55
- const [hasClaude, hasKimi, hasCodex, hasPi, hasDsh] = await Promise.all([
56
- exists(claudeDir), exists(kimiDir), exists(codexDir), exists(piDir), exists(dshDir),
57
- ]);
58
-
59
- const tier1: AdapterChip[] = [];
60
- if (hasClaude) {
61
- const n = await countMatching(claudeDir, (name, isDir) => !isDir && name.endsWith('.jsonl'));
62
- tier1.push({ name: 'Claude Code', status: 'on', hint: `${n.toLocaleString()} 个日志` });
63
- }
64
- if (hasKimi) {
65
- const n = await countMatching(kimiDir, (name, isDir) => isDir && name.startsWith('session_'), 2);
66
- tier1.push({ name: 'Kimi Code', status: 'on', hint: `${n} 个会话` });
67
- }
68
- if (hasCodex) {
69
- const n = await countMatching(codexDir, (name, isDir) => !isDir && name.endsWith('.jsonl'));
70
- tier1.push({ name: 'Codex', status: 'on', hint: `${n} 个 rollout` });
71
- }
72
- // WorkBuddy 双变体(traces 目录存在即接)
73
- for (const [dir, name] of [[path.join(HOME, '.workbuddy', 'traces'), 'WorkBuddy'], [path.join(HOME, '.workbuddy-ai', 'traces'), 'WorkBuddy AI']] as const) {
74
- if (await exists(dir)) {
75
- const n = await countMatching(dir, (nm, isDir) => !isDir && nm.endsWith('.jsonl'));
76
- tier1.push({ name, status: 'on', hint: `${n} 个 trace` });
77
- }
78
- }
79
- if (hasDsh) {
80
- const n = await countMatching(dshDir, (name, isDir) => !isDir && name === 'session.v4.jsonl.zstd');
81
- tier1.push({ name: 'DeepSeek Harness', status: 'on', hint: `${n} 个会话(zstd)` });
82
- }
83
- if (hasPi) {
84
- const n = await countMatching(piDir, (name, isDir) => !isDir && name.endsWith('.jsonl'));
85
- tier1.push({ name: 'pi', status: 'on', hint: `${n} 个会话` });
86
- }
87
-
88
- // ---- 二档:SQLite 直读 ----
89
- const opencodeDb = path.join(HOME, '.local', 'share', 'opencode', 'opencode.db');
90
- const cursorDir = path.join(HOME, '.cursor');
91
- const tier2: AdapterChip[] = [];
92
- if (await exists(opencodeDb)) tier2.push({ name: 'OpenCode', status: 'on', hint: 'opencode.db 直读' });
93
- if (await exists(cursorDir)) tier2.push({ name: 'Cursor', status: 'sub', hint: '无 token 用量数据' });
94
-
95
- // ---- 特殊:仅会话数 ----
96
- const qoderDir = path.join(HOME, '.qoder');
97
- const special: AdapterChip[] = [];
98
- if (await exists(qoderDir)) {
99
- const n = await countMatching(qoderDir, (name, isDir) => isDir && /sess/i.test(name), 5);
100
- special.push({ name: 'Qoder', status: 'sub', hint: `${n} 个会话 · 无 token/模型` });
101
- }
102
-
103
- // ---- 四档:云端用量 API ----
104
- const hasDoubao = (cfg.cloudApis ?? []).some((a) => /doubao|豆包|火山/i.test(a.name)) || await exists(path.join(HOME, '.arkcli'));
105
- const tier4: AdapterChip[] = [
106
- { name: 'Doubao · 火山', status: hasDoubao ? 'on' : 'off', hint: hasDoubao ? 'arkcli 日粒度' : '未配置' },
107
- { name: 'OpenAI API', status: 'off', hint: '未配置' },
108
- { name: 'Kimi 开放平台', status: 'off', hint: '未配置' },
109
- ];
110
-
111
- // ---- 五档:仅检测(不写本地用量日志) ----
112
- const detectOnly: [string, string][] = [
113
- ['Antigravity', '.antigravity'], ['Augment', '.augment'], ['CodeBuddy', '.codebuddy'],
114
- ['Copilot', '.copilot'], ['Kilo', '.kilo'], ['Qwen Code', '.qwen'],
115
- ['Trae', '.trae'], ['Windsurf', '.windsurf'], ['ZCode', '.zcode'],
116
- ['Hermes', '.hermes'], ['Cline', '.cline'], ['Kimi (agents)', '.kimi'],
117
- ['Zed', '.config/zed'], ['Ollama', '.ollama'],
118
- ];
119
- const tier5: AdapterChip[] = [];
120
- for (const [name, dir] of detectOnly) {
121
- if (await exists(path.join(HOME, dir))) tier5.push({ name, status: 'sub' });
122
- }
123
-
124
- // ---- 六档:订阅登记 ----
125
- const subs = cfg.subscriptions ?? [];
126
- const tier6: AdapterChip[] = subs.length > 0
127
- ? subs.map((s) => ({ name: s.name, status: 'sub' as const, hint: `订阅 ¥${s.monthlyCny}/月` }))
128
- : [
129
- { name: 'Kimi.app', status: 'sub', hint: '未登记' },
130
- { name: 'ChatGPT.app', status: 'sub', hint: '未登记' },
131
- ];
132
-
133
- const tiers: AdapterTier[] = [];
134
- if (tier1.length) tiers.push({ key: 'local', label: '一档 · 本地日志直读', count: `${tier1.length} · 全量 token + 模型`, chips: tier1 });
135
- if (tier2.length) tiers.push({ key: 'local', label: '二档 · SQLite 直读', count: `${tier2.length}`, chips: tier2 });
136
- if (special.length) tiers.push({ key: 'detect', label: '特殊 · 仅会话数', count: `${special.length} · 无 token / 模型`, chips: special });
137
- tiers.push({ key: 'cloud', label: '四档 · 云端用量 API', count: `${tier4.length}`, chips: tier4 });
138
- if (tier5.length) tiers.push({ key: 'detect', label: '五档 · 仅检测', count: `${tier5.length} · 不写本地用量日志`, chips: tier5 });
139
- tiers.push({ key: 'sub', label: '六档 · 订阅登记', count: `${tier6.length} · 桌面端为瘦客户端`, chips: tier6 });
140
- return tiers;
141
- }
@@ -1,64 +0,0 @@
1
- // 异常重试/打转检测 — 识别"同一 session 反复重试、token 在烧但没产出"
2
-
3
- import type { UsageEvent } from './schema.ts';
4
-
5
- export interface RetryAlert {
6
- sessionId: string;
7
- agent: string;
8
- model: string;
9
- calls: number; // 该 session 的调用次数
10
- totalTokens: number;
11
- totalCostUsd: number;
12
- reason: string; // 为什么判定为打转
13
- }
14
-
15
- export interface RetryDetectOptions {
16
- minCallsPerSession?: number; // 一个 session 超过多少次调用算可疑(默认 50)
17
- minCostUsd?: number; // 该 session 花费超过多少美元才算(默认 1)
18
- }
19
-
20
- // 检测"打转"会话:单个 session 调用次数异常多,往往意味着 Agent 在死循环/重试
21
- export function detectRetryLoops(
22
- events: UsageEvent[],
23
- costOfFn: (model: string, usage: UsageEvent['usage']) => { totalUsd: number },
24
- opts: RetryDetectOptions = {}
25
- ): RetryAlert[] {
26
- const minCalls = opts.minCallsPerSession ?? 50;
27
- const minCost = opts.minCostUsd ?? 1.0;
28
-
29
- // 按 session 聚合
30
- const bySession = new Map<string, UsageEvent[]>();
31
- for (const e of events) {
32
- const arr = bySession.get(e.sessionId) ?? [];
33
- arr.push(e);
34
- bySession.set(e.sessionId, arr);
35
- }
36
-
37
- const alerts: RetryAlert[] = [];
38
- for (const [sessionId, evs] of bySession) {
39
- if (evs.length < minCalls) continue;
40
- let tokens = 0;
41
- let cost = 0;
42
- const models = new Set<string>();
43
- let agent = '';
44
- for (const e of evs) {
45
- tokens += e.usage.totalTokens;
46
- cost += costOfFn(e.model, e.usage).totalUsd;
47
- models.add(e.model);
48
- agent = e.agent;
49
- }
50
- if (cost < minCost) continue;
51
-
52
- alerts.push({
53
- sessionId,
54
- agent,
55
- model: [...models].join(','),
56
- calls: evs.length,
57
- totalTokens: tokens,
58
- totalCostUsd: cost,
59
- reason: `单会话 ${evs.length} 次调用,烧 $${cost.toFixed(2)},疑似打转/死循环`,
60
- });
61
- }
62
- // 按花费降序
63
- return alerts.sort((a, b) => b.totalCostUsd - a.totalCostUsd);
64
- }
package/src/core/rtk.ts DELETED
@@ -1,58 +0,0 @@
1
- // RTK(Rust Token Killer)接入层 — 用户显式勾选才安装;rtk-oss 纯 Apache 版
2
- // 原则:少采集/不拦截——rtk 是独立的输出压缩工具,token-pilot 只负责装/检测/卸载,不嵌进请求链。
3
-
4
- import { execFile } from 'node:child_process';
5
- import { promisify } from 'node:util';
6
-
7
- const execFileP = promisify(execFile);
8
-
9
- export async function rtkInstalled(): Promise<boolean> {
10
- try {
11
- const r = await execFileP('rtk', ['--version'], { timeout: 5000 });
12
- return (r.stdout + r.stderr).length > 0;
13
- } catch {
14
- return false;
15
- }
16
- }
17
-
18
- export interface RtkInstallResult {
19
- ok: boolean;
20
- message: string;
21
- }
22
-
23
- // 安装 rtk-oss(纯 Apache 版):macOS/Linux 走 brew,Windows 走 winget
24
- export async function installRtk(): Promise<RtkInstallResult> {
25
- const platform = process.platform;
26
- try {
27
- if (platform === 'win32') {
28
- await execFileP('winget', ['install', '--id', 'rtk-ai.rtk-oss', '-e', '--accept-source-agreements', '--accept-package-agreements'], { timeout: 300_000 });
29
- } else {
30
- // 优先 rtk-oss tap;没有 tap 就 brew 主仓库的 rtk
31
- try {
32
- await execFileP('brew', ['install', 'rtk-ai/tap/rtk-oss'], { timeout: 300_000 });
33
- } catch {
34
- await execFileP('brew', ['install', 'rtk'], { timeout: 300_000 });
35
- }
36
- }
37
- const ok = await rtkInstalled();
38
- return ok
39
- ? { ok: true, message: 'RTK 已安装(rtk --version 验证通过)' }
40
- : { ok: false, message: '安装命令执行了但 rtk --version 未通过,请手动检查' };
41
- } catch (e) {
42
- return { ok: false, message: `安装失败:${String(e).slice(0, 200)}` };
43
- }
44
- }
45
-
46
- export async function uninstallRtk(): Promise<RtkInstallResult> {
47
- try {
48
- if (process.platform === 'win32') {
49
- await execFileP('winget', ['uninstall', '--id', 'rtk-ai.rtk-oss', '-e'], { timeout: 180_000 });
50
- } else {
51
- try { await execFileP('brew', ['uninstall', 'rtk-oss'], { timeout: 180_000 }); }
52
- catch { await execFileP('brew', ['uninstall', 'rtk'], { timeout: 180_000 }); }
53
- }
54
- return { ok: true, message: '已卸载 RTK' };
55
- } catch (e) {
56
- return { ok: false, message: `卸载失败:${String(e).slice(0, 200)}` };
57
- }
58
- }
@@ -1,55 +0,0 @@
1
- // 省钱建议 — 事后分析(不拦截、不代理),符合"少采集/本地化"原则
2
- // 逻辑:检测到贵模型在做轻量任务 → 建议换便宜模型,估算能省多少
3
-
4
- import type { UsageEvent } from './schema.ts';
5
- import { priceFor } from './pricing.ts';
6
-
7
- export interface SavingsAdvice {
8
- observation: string;
9
- suggestion: string;
10
- estimatedSavingsUsdPerMonth: number;
11
- }
12
-
13
- // 找"贵模型干轻活"的浪费:贵模型的高频低输出调用
14
- export function savingsAdvice(events: UsageEvent[]): SavingsAdvice[] {
15
- const advice: SavingsAdvice[] = [];
16
-
17
- // 按模型聚合
18
- const byModel = new Map<string, { events: number; outputTokens: number; cost: number }>();
19
- for (const e of events) {
20
- const m = byModel.get(e.model) ?? { events: 0, outputTokens: 0, cost: 0 };
21
- m.events++;
22
- m.outputTokens += e.usage.outputTokens;
23
- m.cost += 0; // cost 由调用方算,这里先记事件数
24
- byModel.set(e.model, m);
25
- }
26
-
27
- // 找最贵的模型
28
- const models = [...byModel.keys()];
29
- const expensive = models
30
- .map((m) => ({ m, p: priceFor(m) }))
31
- .filter((x) => x.p.output >= 15)
32
- .sort((a, b) => b.p.output - a.p.output);
33
-
34
- for (const { m, p } of expensive) {
35
- const agg = byModel.get(m)!;
36
- // 平均每次调用 output 很少(<500 token)说明是轻量任务
37
- const avgOut = agg.events > 0 ? agg.outputTokens / agg.events : 0;
38
- if (avgOut < 500 && agg.events > 100) {
39
- // 找一个便宜替代
40
- const cheaper = models
41
- .map((mm) => ({ mm, p: priceFor(mm) }))
42
- .filter((x) => x.p.output < p.output * 0.4)
43
- .sort((a, b) => a.p.output - b.p.output)[0];
44
- if (cheaper) {
45
- const cheapCost = agg.events * ((agg.outputTokens / agg.events / 1_000_000) * cheaper.p.output);
46
- advice.push({
47
- observation: `${m} 有 ${agg.events} 次调用,平均每次只输出 ${avgOut.toFixed(0)} token(轻量任务)`,
48
- suggestion: `这类轻量任务可换 ${cheaper.mm},输出单价 $${p.output} → $${cheaper.p.output}/1M`,
49
- estimatedSavingsUsdPerMonth: Math.max(0, (agg.events * avgOut / 1_000_000) * (p.output - cheaper.p.output)),
50
- });
51
- }
52
- }
53
- }
54
- return advice;
55
- }
@@ -1,66 +0,0 @@
1
- // UsageEvent — 统一用量事件 schema,字段对齐 LoongSuite Pilot 的 gen_ai.usage.* 语义约定
2
- // 参考:loongsuite-pilot src/types/events.ts(已预留 cost 字段,我们填上)
3
-
4
- export interface UsageTokens {
5
- inputTokens: number;
6
- outputTokens: number;
7
- cacheReadTokens: number;
8
- cacheCreationTokens: number;
9
- totalTokens: number;
10
- }
11
-
12
- export interface UsageCost {
13
- inputUsd: number;
14
- outputUsd: number;
15
- cacheReadUsd: number;
16
- cacheCreationUsd: number;
17
- totalUsd: number;
18
- }
19
-
20
- export interface UsageEvent {
21
- // 来源
22
- agent: string; // 'claude-code' | 'codex' | 'kimi-code' | 'qoder' | ...
23
- agentVersion?: string;
24
-
25
- // 标识
26
- sessionId: string;
27
- turnId?: string;
28
- eventId: string;
29
- timestamp: number; // unix ms
30
-
31
- // 模型
32
- provider: string; // 'anthropic' | 'deepseek' | 'glm' | 'kimi' | ...
33
- model: string; // 'claude-sonnet-4-6' | 'deepseek-v4.1-flash' | ...
34
-
35
- // 用量
36
- usage: UsageTokens;
37
-
38
- // 成本(成本层填,采集层不填)
39
- cost?: UsageCost;
40
-
41
- // 上下文
42
- workspace?: string; // 项目路径(用于"哪个项目烧钱")
43
- sessionTitle?: string; // 会话首条用户消息摘要(可选,用于实时会话行)
44
- }
45
-
46
- // 一个宿主一天/一段时间的聚合
47
- export interface UsageSummary {
48
- agent: string;
49
- date: string; // YYYY-MM-DD
50
- models: Record<string, UsageTokens & { cost?: UsageCost }>;
51
- totalTokens: UsageTokens;
52
- totalCostUsd?: number;
53
- sessions: number;
54
- }
55
-
56
- // 内容流事件 —— 只记尺寸,不落内容(少采集红线)
57
- // 用于压缩潜力检测:tool 输出的体积与存活轮数
58
- export interface ContentEvent {
59
- agent: string;
60
- sessionId: string;
61
- timestamp: number; // unix ms
62
- kind: 'tool_use' | 'tool_result';
63
- tool?: string; // 'Read' | 'Bash' | ...
64
- targetPath?: string; // 读取/操作的文件路径(重复读取检测用)
65
- sizeBytes: number; // 内容的 JSON 序列化尺寸
66
- }
@@ -1,64 +0,0 @@
1
- // 未知模型追踪 + 状态
2
- // 采集到的模型在定价表与覆写里都找不到时,记进 ~/.token-pilot/unknown-models.json,
3
- // 由 price-fetch 每天自动上网查价补全,人工随时可在设置弹窗核对修改。
4
-
5
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
6
- import path from 'node:path';
7
- import { CONFIG_DIR } from './config.ts';
8
-
9
- const UNKNOWN_PATH = path.join(CONFIG_DIR, 'unknown-models.json');
10
-
11
- export interface UnknownModel {
12
- model: string;
13
- firstSeen: number;
14
- lastSeen: number;
15
- calls: number;
16
- agents: string[];
17
- // 自动补价状态
18
- autoPrice?: { input: number; output: number; cacheRead?: number }; // ¥/1M
19
- source?: string; // 价格来源 URL
20
- fetchedAt?: number;
21
- needsReview?: boolean; // 自动填充的都要人工核对
22
- failedAttempts?: number;
23
- }
24
-
25
- type State = Record<string, UnknownModel>;
26
-
27
- export function loadUnknown(): State {
28
- if (!existsSync(UNKNOWN_PATH)) return {};
29
- try { return JSON.parse(readFileSync(UNKNOWN_PATH, 'utf8')); } catch { return {}; }
30
- }
31
-
32
- export function saveUnknown(s: State): void {
33
- mkdirSync(CONFIG_DIR, { recursive: true });
34
- writeFileSync(UNKNOWN_PATH, JSON.stringify(s, null, 2) + '\n', 'utf8');
35
- }
36
-
37
- export function trackUnknown(model: string, agent: string, now = Date.now()): void {
38
- const s = loadUnknown();
39
- const u = s[model] ?? { model, firstSeen: now, lastSeen: now, calls: 0, agents: [] };
40
- u.lastSeen = now;
41
- u.calls++;
42
- if (!u.agents.includes(agent)) u.agents.push(agent);
43
- s[model] = u;
44
- saveUnknown(s);
45
- }
46
-
47
- export function markPriced(model: string, price: { input: number; output: number; cacheRead?: number }, source: string): void {
48
- const s = loadUnknown();
49
- const u = s[model];
50
- if (!u) return;
51
- u.autoPrice = price;
52
- u.source = source;
53
- u.fetchedAt = Date.now();
54
- u.needsReview = true;
55
- saveUnknown(s);
56
- }
57
-
58
- export function markFailed(model: string): void {
59
- const s = loadUnknown();
60
- const u = s[model];
61
- if (!u) return;
62
- u.failedAttempts = (u.failedAttempts ?? 0) + 1;
63
- saveUnknown(s);
64
- }
@@ -1,35 +0,0 @@
1
- // dsh adapter 测试:zstd 压缩 fixture + 步级事件口径
2
-
3
- import { test } from 'node:test';
4
- import assert from 'node:assert/strict';
5
- import { execFileSync } from 'node:child_process';
6
- import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
7
- import { tmpdir } from 'node:os';
8
- import path from 'node:path';
9
- import { dshAdapter } from '../src/adapters/dsh.ts';
10
-
11
- test('dsh:zstd 解压 + 逐步独立事件 + model 提取 + 全零过滤', async () => {
12
- const dir = mkdtempSync(path.join(tmpdir(), 'tp-dsh-'));
13
- const raw = [
14
- JSON.stringify({ type: 'rec', seq: 1, time: Date.now(), data: { turn: 1, step: 1, usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 900, totalTokens: 1000 }, message: { role: 'assistant', content: [{ type: 'toolCall', name: 'bash', arguments: { model: 'kimi-k3' } }] } } }),
15
- JSON.stringify({ type: 'rec', seq: 2, time: Date.now(), data: { turn: 1, step: 2, usage: { inputTokens: 200, outputTokens: 80, cacheReadTokens: 950, totalTokens: 1150 }, message: { role: 'assistant', content: [{ model: 'kimi-k3' }] } } }),
16
- // 全零过滤
17
- JSON.stringify({ type: 'rec', seq: 3, time: Date.now(), data: { turn: 1, step: 3, usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 } } }),
18
- // 无 usage
19
- JSON.stringify({ type: 'rec', seq: 4, time: Date.now(), data: { turn: 1 } }),
20
- ].join('\n');
21
- const zf = path.join(dir, 'session.v4.jsonl.zstd');
22
- const plain = path.join(dir, 'plain.jsonl');
23
- writeFileSync(plain, raw);
24
- execFileSync('zstd', ['-q', '-f', plain, '-o', zf]);
25
-
26
- const events = await dshAdapter.readFileEvents!(zf, 0);
27
- assert.equal(events.length, 2);
28
- assert.equal(events[0].agent, 'dsh');
29
- assert.equal(events[0].model, 'kimi-k3');
30
- assert.equal(events[0].usage.inputTokens, 100);
31
- assert.equal(events[1].usage.inputTokens, 200);
32
- // 逐步独立:两步都保留(不是取最大)
33
- assert.ok(events[0].eventId !== events[1].eventId);
34
- rmSync(dir, { recursive: true, force: true });
35
- });
@@ -1,39 +0,0 @@
1
- // OpenCode adapter 测试:建临时 SQLite fixture,验证口径(input 不并入缓存、role 过滤、modelID 提取)
2
-
3
- import { test } from 'node:test';
4
- import assert from 'node:assert/strict';
5
- import { DatabaseSync } from 'node:sqlite';
6
- import { mkdtempSync, rmSync } from 'node:fs';
7
- import { tmpdir } from 'node:os';
8
- import path from 'node:path';
9
- import { opencodeAdapter } from '../src/adapters/opencode.ts';
10
-
11
- test('opencode:只取 assistant 带 tokens 的消息,缓存独立计价不并入 input', async () => {
12
- const dir = mkdtempSync(path.join(tmpdir(), 'tp-oc-'));
13
- const dbPath = path.join(dir, 'opencode.db');
14
- const db = new DatabaseSync(dbPath);
15
- db.exec(`CREATE TABLE message (id text PRIMARY KEY, session_id text, time_created integer, data text)`);
16
- const now = Date.now();
17
- const rows = [
18
- // 正常 assistant 事件
19
- ['m1', 's1', now, JSON.stringify({ role: 'assistant', modelID: 'glm-5.3-flash', providerID: 'mccodex', path: { cwd: '/proj' }, tokens: { total: 1000, input: 300, output: 200, cache: { write: 0, read: 500 } } })],
20
- // user 消息(应过滤)
21
- ['m2', 's1', now, JSON.stringify({ role: 'user', tokens: { total: 10, input: 10, output: 0 } })],
22
- // assistant 无 tokens(应过滤)
23
- ['m3', 's1', now, JSON.stringify({ role: 'assistant' })],
24
- // 全零 tokens(应过滤)
25
- ['m4', 's1', now, JSON.stringify({ role: 'assistant', tokens: { total: 0, input: 0, output: 0, cache: { read: 0, write: 0 } } })],
26
- ];
27
- for (const r of rows) db.prepare('INSERT INTO message VALUES (?,?,?,?)').run(...(r as [string, string, number, string]));
28
- db.close();
29
-
30
- const events = await opencodeAdapter.readFileEvents!(dbPath, 0);
31
- assert.equal(events.length, 1);
32
- const e = events[0];
33
- assert.equal(e.model, 'glm-5.3-flash');
34
- assert.equal(e.usage.inputTokens, 300); // 不并入 cacheRead
35
- assert.equal(e.usage.cacheReadTokens, 500);
36
- assert.equal(e.usage.totalTokens, 1000);
37
- assert.equal(e.workspace, '/proj');
38
- rmSync(dir, { recursive: true, force: true });
39
- });
@@ -1,33 +0,0 @@
1
- // pi / volc-ark adapter 测试
2
-
3
- import { test } from 'node:test';
4
- import assert from 'node:assert/strict';
5
- import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
6
- import { tmpdir } from 'node:os';
7
- import path from 'node:path';
8
- import { piAdapter } from '../src/adapters/pi.ts';
9
-
10
- test('pi:只取 role=assistant 且有非零 usage 的消息;全零(代理常见)不计', async () => {
11
- const dir = mkdtempSync(path.join(tmpdir(), 'tp-pi-'));
12
- const f = path.join(dir, 'sess1.jsonl');
13
- const now = new Date().toISOString();
14
- writeFileSync(f, [
15
- JSON.stringify({ type: 'session', id: 's1', timestamp: now }),
16
- JSON.stringify({ type: 'message', id: 'a1', timestamp: now, message: { role: 'assistant', model: 'gpt-5.4', provider: 'mccodex', usage: { input: 100, output: 50, cacheRead: 900, cacheWrite: 0 } } }),
17
- // 全零(coding-plan 代理常见)——应过滤
18
- JSON.stringify({ type: 'message', id: 'a2', timestamp: now, message: { role: 'assistant', model: 'ark-code-latest', usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } }),
19
- // user 消息——应过滤
20
- JSON.stringify({ type: 'message', id: 'u1', timestamp: now, message: { role: 'user', content: [{ type: 'text', text: 'hi' }] } }),
21
- '',
22
- ].join('\n'));
23
-
24
- const events = await piAdapter.readFileEvents!(f, 0);
25
- assert.equal(events.length, 1);
26
- const e = events[0];
27
- assert.equal(e.agent, 'pi');
28
- assert.equal(e.model, 'gpt-5.4');
29
- assert.equal(e.usage.inputTokens, 100);
30
- assert.equal(e.usage.cacheReadTokens, 900);
31
- assert.equal(e.usage.totalTokens, 1050);
32
- rmSync(dir, { recursive: true, force: true });
33
- });
@@ -1,34 +0,0 @@
1
- // workbuddy adapter 测试:trace_end.summary.modelInfo 口径
2
-
3
- import { test } from 'node:test';
4
- import assert from 'node:assert/strict';
5
- import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
6
- import { tmpdir } from 'node:os';
7
- import path from 'node:path';
8
- import { workbuddyAdapter } from '../src/adapters/workbuddy.ts';
9
-
10
- test('workbuddy:trace_end modelInfo 拆分(input 不含 cached),全零/缺 modelInfo 过滤', async () => {
11
- const dir = mkdtempSync(path.join(tmpdir(), 'tp-wb-'));
12
- const f = path.join(dir, 'trace_x.jsonl');
13
- const now = new Date().toISOString();
14
- writeFileSync(f, [
15
- JSON.stringify({ type: 'trace_start', trace: { traceId: 't1' } }),
16
- // 正常:input=1000, cached=800, output=100 → fresh input 应为 200
17
- JSON.stringify({ type: 'trace_end', summary: { sessionId: 's1', endedAt: now, modelInfo: { models: ['hy3'], totalInputTokens: 1000, totalCachedTokens: 800, totalOutputTokens: 100, callCount: 5 } } }),
18
- // 全零过滤
19
- JSON.stringify({ type: 'trace_end', summary: { sessionId: 's2', endedAt: now, modelInfo: { models: ['hy3'], totalInputTokens: 0, totalCachedTokens: 0, totalOutputTokens: 0, callCount: 0 } } }),
20
- // 无 modelInfo 过滤
21
- JSON.stringify({ type: 'trace_end', summary: { sessionId: 's3', endedAt: now } }),
22
- ].join('\n'));
23
-
24
- const events = await workbuddyAdapter.readFileEvents!(f, 0);
25
- assert.equal(events.length, 1);
26
- const e = events[0];
27
- assert.equal(e.agent, 'workbuddy');
28
- assert.equal(e.model, 'hy3');
29
- assert.equal(e.provider, 'hunyuan');
30
- assert.equal(e.usage.inputTokens, 200);
31
- assert.equal(e.usage.cacheReadTokens, 800);
32
- assert.equal(e.usage.outputTokens, 100);
33
- rmSync(dir, { recursive: true, force: true });
34
- });
@@ -1,45 +0,0 @@
1
- // Adapter 测试:fixtures 驱动,验证去重/过滤/缓存拆分口径
2
-
3
- import { test } from 'node:test';
4
- import assert from 'node:assert/strict';
5
- import path from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import { claudeCodeAdapter } from '../src/adapters/claude-code.ts';
8
- import { codexAdapter } from '../src/adapters/codex.ts';
9
- import { kimiCodeAdapter } from '../src/adapters/kimi-code.ts';
10
-
11
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
- const fx = (name: string) => path.join(__dirname, 'fixtures', name);
13
-
14
- test('claude-code:流式快照按 message.id 去重,取最大(全零快照被丢弃)', async () => {
15
- const events = await claudeCodeAdapter.readFileEvents!(fx('claude-session.jsonl'));
16
- assert.equal(events.length, 1, '3 行同 id 快照 + 1 synthetic + 1 summary → 1 事件');
17
- const e = events[0];
18
- assert.equal(e.eventId, 'msg-dup-1');
19
- assert.equal(e.usage.outputTokens, 4263);
20
- assert.equal(e.usage.cacheReadTokens, 93760);
21
- assert.equal(e.usage.inputTokens, 239);
22
- assert.equal(e.sessionTitle, '修复登录页样式');
23
- assert.equal(e.workspace, '/Users/test/myproj');
24
- assert.equal(e.provider, 'anthropic');
25
- });
26
-
27
- test('kimi-code:只认 usage.record;input 只算 inputOther(缓存不重复计)', async () => {
28
- const events = await kimiCodeAdapter.readFileEvents!(fx('kimi-wire.jsonl'));
29
- assert.equal(events.length, 2, 'agent.message.appended 里伪造的 usage 不得计入');
30
- const [e1, e2] = events;
31
- assert.equal(e1.usage.inputTokens, 42369);
32
- assert.equal(e1.usage.totalTokens, 42369 + 172);
33
- assert.equal(e2.usage.cacheReadTokens, 42240);
34
- assert.equal(e2.usage.totalTokens, 203 + 320 + 42240);
35
- });
36
-
37
- test('codex:input 拆出 cached 子集(input − cached)', async () => {
38
- const events = await codexAdapter.readFileEvents!(fx('codex-rollout.jsonl'));
39
- assert.equal(events.length, 2, 'response_item 不计');
40
- const [e1] = events;
41
- assert.equal(e1.usage.inputTokens, 56369 - 5760);
42
- assert.equal(e1.usage.cacheReadTokens, 5760);
43
- // total 语义 = record.total_tokens = input + output
44
- assert.equal(e1.usage.totalTokens, 56369 + 956);
45
- });