@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,135 +0,0 @@
1
- // WorkBuddy / WorkBuddy AI adapter — 只读解析 ~/.workbuddy{,-ai}/traces/*/**\/*.jsonl
2
- // 结构:OTel 风格 trace 文件;trace_end.summary.modelInfo 有完整用量:
3
- // { models, totalInputTokens, totalOutputTokens, totalCachedTokens, callCount }
4
- // 口径:trace 级聚合(一个 trace = 一次 Agent 工作流),逐调用粒度不可得——如实标注。
5
-
6
- import { promises as fs } from 'node:fs';
7
- import path from 'node:path';
8
- import os from 'node:os';
9
- import type { UsageEvent } from '../core/schema.ts';
10
- import type { Adapter } from './types.ts';
11
-
12
- const HOME = os.homedir();
13
- const ROOTS: [string, string][] = [
14
- [path.join(HOME, '.workbuddy', 'traces'), 'workbuddy'],
15
- [path.join(HOME, '.workbuddy-ai', 'traces'), 'workbuddy-ai'],
16
- ];
17
-
18
- interface WbSummary {
19
- sessionId?: string;
20
- startedAt?: string;
21
- endedAt?: string;
22
- modelInfo?: {
23
- models?: string[];
24
- totalInputTokens?: number;
25
- totalOutputTokens?: number;
26
- totalCachedTokens?: number;
27
- callCount?: number;
28
- };
29
- }
30
-
31
- interface WbLine {
32
- type?: string;
33
- summary?: WbSummary;
34
- }
35
-
36
- async function* walkJsonl(dir: string): AsyncGenerator<string> {
37
- let entries: fs.Dirent[];
38
- try { entries = await fs.readdir(dir, { withFileTypes: true }); } catch { return; }
39
- for (const e of entries) {
40
- const full = path.join(dir, e.name);
41
- if (e.isDirectory()) yield* walkJsonl(full);
42
- else if (e.isFile() && e.name.endsWith('.jsonl')) yield full;
43
- }
44
- }
45
-
46
- function parseTraceEnd(line: string, file: string, agent: string): UsageEvent | null {
47
- if (!line.includes('"trace_end"') || !line.includes('modelInfo')) return null;
48
- let d: WbLine;
49
- try { d = JSON.parse(line); } catch { return null; }
50
- if (d.type !== 'trace_end') return null;
51
- const s = d.summary;
52
- const mi = s?.modelInfo;
53
- if (!s || !mi || !mi.models?.length) return null;
54
-
55
- const totalIn = mi.totalInputTokens ?? 0;
56
- const cacheRead = mi.totalCachedTokens ?? 0;
57
- const input = Math.max(totalIn - cacheRead, 0);
58
- const output = mi.totalOutputTokens ?? 0;
59
- if (input + cacheRead + output === 0) return null;
60
-
61
- const model = mi.models[0];
62
- return {
63
- agent,
64
- sessionId: s.sessionId ?? path.basename(file, '.jsonl'),
65
- eventId: path.basename(file, '.jsonl'),
66
- timestamp: s.endedAt ? new Date(s.endedAt).getTime() : 0,
67
- provider: providerFromModel(model),
68
- model,
69
- usage: {
70
- inputTokens: input,
71
- outputTokens: output,
72
- cacheReadTokens: cacheRead,
73
- cacheCreationTokens: 0,
74
- totalTokens: input + output + cacheRead,
75
- },
76
- };
77
- }
78
-
79
- function providerFromModel(model: string): string {
80
- const m = model.toLowerCase();
81
- if (m.startsWith('hy') || m.includes('hunyuan')) return 'hunyuan';
82
- if (m.includes('glm')) return 'glm';
83
- if (m.includes('deepseek')) return 'deepseek';
84
- if (m.includes('kimi')) return 'kimi';
85
- if (m.includes('claude')) return 'anthropic';
86
- if (m.includes('gpt')) return 'openai';
87
- return 'unknown';
88
- }
89
-
90
- async function readFileEvents(file: string, sinceMs: number, agent: string): Promise<UsageEvent[]> {
91
- let content: string;
92
- try { content = await fs.readFile(file, 'utf8'); } catch { return []; }
93
- const events: UsageEvent[] = [];
94
- for (const line of content.split('\n')) {
95
- if (!line.trim()) continue;
96
- const ev = parseTraceEnd(line, file, agent);
97
- if (ev && ev.timestamp >= sinceMs) events.push(ev);
98
- }
99
- return events;
100
- }
101
-
102
- function makeAdapter(root: string, agentId: string, displayName: string): Adapter {
103
- return {
104
- meta: { id: agentId, displayName, detectPaths: [path.dirname(root)] },
105
- async detect() {
106
- try { await fs.access(root); return true; } catch { return false; }
107
- },
108
- async listFiles() {
109
- const out: string[] = [];
110
- for await (const f of walkJsonl(root)) out.push(f);
111
- return out;
112
- },
113
- async readFileEvents(file: string, sinceMs = 0) {
114
- return readFileEvents(file, sinceMs, agentId);
115
- },
116
- async readEvents(sinceMs = 0) {
117
- return readFileEventsList(await this.listFiles!(), sinceMs, agentId);
118
- },
119
- };
120
- }
121
-
122
- async function readFileEventsList(files: string[], sinceMs: number, agent: string): Promise<UsageEvent[]> {
123
- const events: UsageEvent[] = [];
124
- for (const file of files) {
125
- try {
126
- const st = await fs.stat(file);
127
- if (st.mtimeMs < sinceMs) continue;
128
- } catch { continue; }
129
- events.push(...(await readFileEvents(file, sinceMs, agent)));
130
- }
131
- return events;
132
- }
133
-
134
- export const workbuddyAdapter = makeAdapter(ROOTS[0][0], 'workbuddy', 'WorkBuddy');
135
- export const workbuddyAiAdapter = makeAdapter(ROOTS[1][0], 'workbuddy-ai', 'WorkBuddy AI');
package/src/cli/index.ts DELETED
@@ -1,294 +0,0 @@
1
- #!/usr/bin/env node
2
- // token-pilot CLI — 多宿主聚合
3
- // 命令:today | month | report | sync | dash | serve
4
-
5
- import { costOf, loadPricingWithOverrides } from '../core/pricing.ts';
6
- import { progressBar } from '../core/budget.ts';
7
- import { detectRetryLoops } from '../core/retry-detector.ts';
8
- import { savingsAdvice } from '../core/savings.ts';
9
- import { notify } from '../core/alert.ts';
10
- import { loadConfig, fxRate, monthlyBudgetCny } from '../core/config.ts';
11
- import { writeSummary } from '../core/metrics.ts';
12
- import { collectAll, collectCached, acquireSyncLock, releaseSyncLock } from '../core/collector.ts';
13
- import { hasKnownPrice, priceFor } from '../core/pricing.ts';
14
- import { trackUnknown, loadUnknown } from '../core/unknown-models.ts';
15
- import { autoFetchPrices, autoOverrides } from '../core/price-fetch.ts';
16
- import { buildDashboardData } from '../core/aggregate.ts';
17
- import { serve, bakeDashboard, writeDashboardDataFile } from './serve.ts';
18
- import type { UsageEvent } from '../core/schema.ts';
19
-
20
- function startOfToday(): number {
21
- const d = new Date();
22
- d.setHours(0, 0, 0, 0);
23
- return d.getTime();
24
- }
25
- function startOfMonth(): number {
26
- const d = new Date();
27
- d.setDate(1);
28
- d.setHours(0, 0, 0, 0);
29
- return d.getTime();
30
- }
31
-
32
- interface CellAgg {
33
- tokens: number;
34
- cost: number;
35
- events: number;
36
- }
37
- interface Agg {
38
- tokens: number;
39
- cost: number;
40
- events: number;
41
- byAgent: Map<string, CellAgg>;
42
- byModel: Map<string, CellAgg>;
43
- }
44
-
45
- function aggregate(events: UsageEvent[]): Agg {
46
- const agg: Agg = { tokens: 0, cost: 0, events: events.length, byAgent: new Map(), byModel: new Map() };
47
- for (const e of events) {
48
- const c = costOf(e.model, e.usage, undefined, e.timestamp);
49
- const tok = e.usage.totalTokens;
50
- agg.tokens += tok;
51
- agg.cost += c.totalUsd;
52
- for (const [map, key] of [[agg.byAgent, e.agent], [agg.byModel, e.model]] as const) {
53
- const cell = map.get(key) ?? { tokens: 0, cost: 0, events: 0 };
54
- cell.tokens += tok;
55
- cell.cost += c.totalUsd;
56
- cell.events += 1;
57
- map.set(key, cell);
58
- }
59
- }
60
- return agg;
61
- }
62
-
63
- function fmtUsd(n: number): string {
64
- return '$' + n.toFixed(2);
65
- }
66
- function fmtTokens(n: number): string {
67
- if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';
68
- if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
69
- return String(n);
70
- }
71
-
72
- function printMap(title: string, map: Map<string, CellAgg>) {
73
- console.log(title);
74
- const sorted = [...map.entries()].sort((a, b) => b[1].cost - a[1].cost);
75
- for (const [key, c] of sorted) {
76
- console.log(` ${key.padEnd(30)} ${fmtTokens(c.tokens).padStart(9)} tokens ${fmtUsd(c.cost).padStart(9)} ${c.events} 次`);
77
- }
78
- }
79
-
80
- async function cmdReport(cmd: string) {
81
- const since = cmd === 'today' ? startOfToday() : cmd === 'month' ? startOfMonth() : 0;
82
- const label = cmd === 'today' ? '今天' : cmd === 'month' ? '本月' : '全部';
83
- console.log(`\ntoken-pilot · ${label}\n`);
84
-
85
- const { events: allEvents, detected } = await collectAll(since);
86
- console.log(`已检测宿主:${detected.join('、') || '无'}\n`);
87
-
88
- if (allEvents.length === 0) {
89
- console.log('该时段无用量记录');
90
- return;
91
- }
92
-
93
- const agg = aggregate(allEvents);
94
- printMap('按宿主:', agg.byAgent);
95
- console.log('');
96
- printMap('按模型:', agg.byModel);
97
- console.log('');
98
- console.log(`合计:${fmtTokens(agg.tokens)} tokens · ${fmtUsd(agg.cost)} · ${agg.events} 次调用`);
99
-
100
- const cfg = loadConfig();
101
- const budgetCny = monthlyBudgetCny(cfg);
102
- if (budgetCny) {
103
- const { events: monthEvents } = await collectAll(startOfMonth());
104
- const monthCostUsd = monthEvents.reduce((s, e) => s + costOf(e.model, e.usage, undefined, e.timestamp).totalUsd, 0);
105
- const monthCostCny = monthCostUsd * fxRate(cfg);
106
- const pct = (monthCostCny / budgetCny) * 100;
107
- const forecast = (monthCostCny / new Date().getDate()) * new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
108
- console.log('');
109
- console.log(`预算:¥${monthCostCny.toFixed(0)} / ¥${budgetCny} ${progressBar(pct)}`);
110
- console.log(`照这个速度,月底预计:¥${forecast.toFixed(0)}${forecast > budgetCny ? '(预计超支)' : ''}`);
111
- const threshold = cfg.alertOnPercent ?? 80;
112
- if (pct >= threshold) {
113
- notify('token-pilot 预算告警', `本月已用 ${pct.toFixed(0)}%(¥${monthCostCny.toFixed(0)} / ¥${budgetCny})`);
114
- }
115
- } else if (cmd === 'month') {
116
- const today = new Date().getDate();
117
- const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
118
- console.log(`\n照这个速度,月底预计:${fmtUsd((agg.cost / today) * daysInMonth)}`);
119
- }
120
-
121
- // 同步写 summary(兼容菜单栏旧路径)
122
- try {
123
- const todayEvents = allEvents.filter((e) => e.timestamp >= startOfToday());
124
- const monthEvents = cmd === 'month' ? allEvents : (await collectAll(startOfMonth())).events;
125
- writeSummary(todayEvents, monthEvents, undefined);
126
- } catch { /* 不阻塞 */ }
127
-
128
- if (cmd === 'report' || cmd === 'month') {
129
- const alerts = detectRetryLoops(allEvents, (m, u) => costOf(m, u));
130
- if (alerts.length > 0) {
131
- console.log('\n打转/异常重试检测:');
132
- for (const a of alerts.slice(0, 5)) {
133
- console.log(` ⚠️ ${a.agent} · ${a.model} · ${a.calls} 次 · ${fmtUsd(a.totalCostUsd)} — ${a.reason}`);
134
- }
135
- }
136
- const savings = savingsAdvice(allEvents);
137
- if (savings.length > 0) {
138
- console.log('\n省钱建议:');
139
- for (const s of savings) {
140
- console.log(` 💡 ${s.observation}`);
141
- console.log(` ${s.suggestion}(约省 ${fmtUsd(s.estimatedSavingsUsdPerMonth)}/月)`);
142
- }
143
- }
144
- }
145
- console.log('');
146
- }
147
-
148
- async function cmdSync(): Promise<void> {
149
- // 单飞:已有 sync 在跑直接退出(菜单栏 60s 定时器叠加 spawn 也不会堆积)
150
- if (!(await acquireSyncLock())) {
151
- console.log('已有 sync 在运行,跳过');
152
- return;
153
- }
154
- try {
155
- const cfg = loadConfig();
156
- const fx = fxRate(cfg);
157
- const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
158
- const { events, contentEvents, detected, parsedFiles, cachedFiles } = await collectCached(0);
159
-
160
- // 未知模型追踪:定价表+覆写都没有的,记账待补价
161
- const seen = new Set<string>();
162
- for (const e of events) {
163
- if (seen.has(e.model)) continue;
164
- seen.add(e.model);
165
- if (!hasKnownPrice(e.model, pricing)) trackUnknown(e.model, e.agent);
166
- }
167
- // 每天最多一次自动查价补全
168
- const fetched = await maybeAutoFetch(fx);
169
- if (fetched.length > 0) {
170
- console.log('自动补价(待核对):');
171
- for (const n of fetched) console.log(` + ${n}`);
172
- }
173
-
174
- const data = await buildDashboardData(events, cfg, loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx), contentEvents);
175
- writeDashboardDataFile(data);
176
- console.log(`token-pilot sync · ${detected.length} 宿主 · 解析 ${parsedFiles} 文件 / 缓存命中 ${cachedFiles}`);
177
- console.log(`今日:¥${data.hero.today.costCny.toFixed(2)} · ${data.hero.today.calls} 次调用 · 托盘:${data.trayTitle}`);
178
- } finally {
179
- await releaseSyncLock();
180
- }
181
- }
182
-
183
- // 自动补价节流:每天最多一次(状态落盘,跨进程生效)
184
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
185
- import path from 'node:path';
186
- import { CONFIG_DIR } from '../core/config.ts';
187
- const FETCH_STATE = path.join(CONFIG_DIR, 'price-fetch-state.json');
188
- async function maybeAutoFetch(fx: number): Promise<string[]> {
189
- const today = new Date().toISOString().slice(0, 10);
190
- try {
191
- if (existsSync(FETCH_STATE)) {
192
- const s = JSON.parse(readFileSync(FETCH_STATE, 'utf8'));
193
- if (s.lastRun === today) return [];
194
- }
195
- } catch { /* 重来 */ }
196
- const notes = await autoFetchPrices(fx, 3);
197
- try { writeFileSync(FETCH_STATE, JSON.stringify({ lastRun: today }), 'utf8'); } catch { /* 忽略 */ }
198
- return notes;
199
- }
200
-
201
- async function cmdDash(): Promise<void> {
202
- const out = await bakeDashboard();
203
- console.log(`已生成 ${out}`);
204
- try {
205
- const { spawn } = await import('node:child_process');
206
- spawn('open', [out], { detached: true, stdio: 'ignore' }).unref();
207
- } catch { /* 手动打开 */ }
208
- }
209
-
210
- // 价格核对台:每个在用的模型当前按什么价算、价格从哪来
211
- function cmdPrices(): void {
212
- const cfg = loadConfig();
213
- const fx = fxRate(cfg);
214
- const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
215
- const unknown = loadUnknown();
216
-
217
- console.log('\ntoken-pilot · 价格核对台(¥ / 1M tokens)\n');
218
- console.log(' 模型'.padEnd(34) + '输入'.padStart(8) + '输出'.padStart(8) + '缓存读'.padStart(8) + ' 来源');
219
-
220
- const rows = new Set<string>([...Object.keys(pricing.models), ...Object.keys(unknown)]);
221
- const lines: string[] = [];
222
- for (const m of rows) {
223
- const p = priceFor(m, pricing);
224
- const inC = (p.input * fx).toFixed(2);
225
- const outC = (p.output * fx).toFixed(2);
226
- const crC = ((p.cacheRead ?? p.input * 0.1) * fx).toFixed(2);
227
- let src = '目录价';
228
- if (cfg.priceOverrides?.[m]) src = '人工覆写 ✓';
229
- else if (unknown[m]?.autoPrice) src = `自动填充·待核对(${unknown[m].source ?? ''})`;
230
- else if (!hasKnownPrice(m)) src = '⚠️ 无定价,按 fallback 估';
231
- lines.push(` ${m.padEnd(32)}${inC.padStart(8)}${outC.padStart(8)}${crC.padStart(8)} ${src}`);
232
- }
233
- lines.sort().forEach((l) => console.log(l));
234
- const pending = Object.values(unknown).filter((u) => u.autoPrice && u.needsReview);
235
- if (pending.length) {
236
- console.log(`\n ${pending.length} 个自动填充待核对 → 看板「数据设置」里可直接改`);
237
- }
238
- console.log('');
239
- }
240
-
241
- // 压缩潜力报告(CLI 明细版)
242
- async function cmdCompressReport(): Promise<void> {
243
- const cfg = loadConfig();
244
- const fx = fxRate(cfg);
245
- const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
246
- const { events, contentEvents } = await collectCached(0);
247
- const { computeCompression } = await import('../core/compression.ts');
248
- const r = computeCompression(events, contentEvents, pricing);
249
- console.log('\ntoken-pilot · 压缩潜力报告(本月)\n');
250
- if (r.itemCount === 0) {
251
- console.log('未发现明显可压缩的上下文浪费。');
252
- return;
253
- }
254
- console.log(`可压缩空间(估算):$${r.potentialUsd.toFixed(2)} – $${r.potentialUsdMax.toFixed(2)} / 月`);
255
- console.log(`模式拆分:陈旧 tool 输出 $${r.patterns.stale.toFixed(2)} · 重复读取 $${r.patterns.reread.toFixed(2)} · 超长输出 $${r.patterns.long.toFixed(2)}`);
256
- console.log('\n最浪费的会话:');
257
- for (const s of r.sessions) {
258
- console.log(` ${s.agent} · ${s.key.slice(-16)} · $${s.wasteUsd.toFixed(2)} · ${s.items} 处 · ${s.topPatterns.join('/')}`);
259
- }
260
- // 2B:当前活跃会话里该 compact 的
261
- const { buildDashboardData } = await import('../core/aggregate.ts');
262
- const data = await buildDashboardData(events, cfg, pricing, contentEvents);
263
- const hot = data.live.sessions.filter((x) => x.needsCompact);
264
- if (hot.length) {
265
- console.log('\n当前该压缩的活跃会话(上下文 >100K,继续在烧):');
266
- for (const x of hot) {
267
- console.log(` ${x.agent} · ${x.label.slice(0, 40)} · 上下文 ${Math.round((x.ctxTokens ?? 0) / 1000)}K → 跑 /compact`);
268
- }
269
- }
270
- console.log('\n建议:上下文压缩代理可把这部分省下来(规则法已验证 −29%~−48% 输入)。');
271
- console.log('');
272
- }
273
-
274
- async function main() {
275
- const cmd = process.argv[2] ?? 'today';
276
- if (cmd === 'serve') {
277
- const port = Number(process.argv[3] ?? 17895);
278
- await serve(port);
279
- return;
280
- }
281
- if (cmd === 'sync') return cmdSync();
282
- if (cmd === 'dash') return cmdDash();
283
- if (cmd === 'prices') return cmdPrices();
284
- if (cmd === 'compress-report') return cmdCompressReport();
285
- if (cmd === 'today' || cmd === 'month' || cmd === 'report' || cmd === 'all') {
286
- return cmdReport(cmd === 'all' ? 'all' : cmd);
287
- }
288
- console.log('用法:token-pilot [today|month|report|sync|dash|serve]');
289
- }
290
-
291
- main().catch((e) => {
292
- console.error('错误:', e.message);
293
- process.exit(1);
294
- });
package/src/cli/serve.ts DELETED
@@ -1,209 +0,0 @@
1
- // token-pilot serve — 本地 HTTP 服务(默认 127.0.0.1:17895)
2
- // 路由:
3
- // GET / 完整看板(注入当前数据)
4
- // GET /panel 菜单栏面板预览
5
- // GET /api/data DashboardData JSON(前端轮询)
6
- // GET /api/config 当前配置
7
- // POST /api/config 保存配置(设置弹窗写回)
8
- // 后台每 10s 增量采集 + 重聚合,同时写 ~/.token-pilot/dashboard-data.json 给 Tauri 菜单栏。
9
-
10
- import http from 'node:http';
11
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
12
- import path from 'node:path';
13
- import { fileURLToPath } from 'node:url';
14
- import { spawn } from 'node:child_process';
15
- import { Collector } from '../core/collector.ts';
16
- import { autoOverrides } from '../core/price-fetch.ts';
17
- import { buildDashboardData } from '../core/aggregate.ts';
18
- import { loadPricingWithOverrides } from '../core/pricing.ts';
19
- import { loadConfig, saveConfig, fxRate, monthlyBudgetCny, DATA_PATH, CONFIG_DIR } from '../core/config.ts';
20
- import { notify } from '../core/alert.ts';
21
- import { applyClaudeAutoCompact } from '../core/autocompact.ts';
22
- import { installRtk, uninstallRtk, rtkInstalled } from '../core/rtk.ts';
23
- import type { DashboardData } from '../core/contract.ts';
24
- import type { TokenPilotConfig } from '../core/config.ts';
25
-
26
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
- const WEB_DIR = path.resolve(__dirname, '../../web');
28
-
29
- export function readWebAsset(name: string): string | null {
30
- const p = path.join(WEB_DIR, name);
31
- if (!existsSync(p)) return null;
32
- return readFileSync(p, 'utf8');
33
- }
34
-
35
- export function injectData(html: string, data: DashboardData): string {
36
- const json = JSON.stringify(data).replace(/</g, '\\u003c');
37
- return html.replace('window.__TP_DATA__=null;', `window.__TP_DATA__=${json};`);
38
- }
39
-
40
- export function writeDashboardDataFile(data: DashboardData): void {
41
- mkdirSync(CONFIG_DIR, { recursive: true });
42
- writeFileSync(DATA_PATH, JSON.stringify(data), 'utf8');
43
- }
44
-
45
- export interface ServeState {
46
- collector: Collector;
47
- data: DashboardData | null;
48
- refreshing: boolean;
49
- lastAlertPct: number;
50
- compactNotifiedAt?: Map<string, number>;
51
- }
52
-
53
- export async function refreshOnce(state: ServeState): Promise<DashboardData> {
54
- const cfg = loadConfig();
55
- const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fxRate(cfg));
56
- const { events, contentEvents } = await state.collector.sync();
57
- const data = await buildDashboardData(events, cfg, pricing, contentEvents ?? []);
58
- state.data = data;
59
- writeDashboardDataFile(data);
60
- // 预算告警(每跨一次阈值提醒一次)
61
- if (data.budget) {
62
- const threshold = cfg.alertOnPercent ?? 80;
63
- const pct = data.budget.pct;
64
- if (pct >= threshold && Math.floor(pct / 10) > Math.floor(state.lastAlertPct / 10)) {
65
- notify('token-pilot 预算告警', `本月已用 ${pct.toFixed(0)}%(${data.budget.spentCny.toFixed(0)} / ${data.budget.monthlyCny.toFixed(0)} 元)`);
66
- }
67
- state.lastAlertPct = pct;
68
- }
69
-
70
- // 自动压缩提醒(开关开着时):超阈值会话发系统通知,单会话 30min 冷却
71
- const ac = cfg.autoCompact;
72
- if (ac?.enabled && data.live.sessions.some((s) => s.needsCompact)) {
73
- if (!state.compactNotifiedAt) state.compactNotifiedAt = new Map();
74
- const threshold = ac.thresholdTokens ?? 100_000;
75
- for (const s of data.live.sessions) {
76
- if (!s.needsCompact) continue;
77
- const last = state.compactNotifiedAt.get(s.key) ?? 0;
78
- if (Date.now() - last < 30 * 60_000) continue;
79
- state.compactNotifiedAt.set(s.key, Date.now());
80
- notify(
81
- 'token-pilot · 该压缩上下文了',
82
- `${s.agent} 会话上下文 ${Math.round((s.ctxTokens ?? threshold) / 1000)}K tokens,后续每轮都全量重发。到对应窗口跑 /compact 可立即降本。`,
83
- );
84
- }
85
- }
86
- return data;
87
- }
88
-
89
- function readBody(req: http.IncomingMessage): Promise<string> {
90
- return new Promise((resolve, reject) => {
91
- let buf = '';
92
- req.on('data', (c) => { buf += c; if (buf.length > 1_000_000) req.destroy(); });
93
- req.on('end', () => resolve(buf));
94
- req.on('error', reject);
95
- });
96
- }
97
-
98
- export async function serve(port = 17895): Promise<void> {
99
- const state: ServeState = { collector: new Collector(), data: null, refreshing: false, lastAlertPct: 0 };
100
-
101
- const refresh = async () => {
102
- if (state.refreshing) return;
103
- state.refreshing = true;
104
- try { await refreshOnce(state); } catch { /* 下一轮再来 */ } finally { state.refreshing = false; }
105
- };
106
- await refresh();
107
- setInterval(refresh, 10_000);
108
-
109
- const server = http.createServer(async (req, res) => {
110
- const url = (req.url ?? '/').split('?')[0];
111
- try {
112
- if (url === '/api/data') {
113
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
114
- res.end(JSON.stringify(state.data ?? {}));
115
- return;
116
- }
117
- if (url === '/api/config' && req.method === 'GET') {
118
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
119
- res.end(JSON.stringify(loadConfig()));
120
- return;
121
- }
122
- if (url === '/api/config' && req.method === 'POST') {
123
- const body = await readBody(req);
124
- const patch = JSON.parse(body) as Partial<TokenPilotConfig>;
125
- const cur = loadConfig();
126
- const next: TokenPilotConfig = { ...cur, ...patch };
127
- // 用户明示后,写 Claude Code 的 autoCompactEnabled
128
- if (next.autoCompact?.applyClaudeCode) {
129
- const r = applyClaudeAutoCompact(next.autoCompact.enabled);
130
- if (!r.ok) {
131
- res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
132
- res.end(JSON.stringify({ ok: false, error: r.message }));
133
- return;
134
- }
135
- }
136
- // RTK 安装层:勾选且未装 → 装;取消勾选且已装 → 卸
137
- if (next.autoCompact && typeof next.autoCompact.installRtk === 'boolean') {
138
- const installed = await rtkInstalled();
139
- if (next.autoCompact.installRtk && !installed) {
140
- const r = await installRtk();
141
- if (!r.ok) {
142
- res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
143
- res.end(JSON.stringify({ ok: false, error: r.message }));
144
- return;
145
- }
146
- } else if (!next.autoCompact.installRtk && installed) {
147
- await uninstallRtk();
148
- }
149
- }
150
- saveConfig(next);
151
- await refresh();
152
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
153
- res.end(JSON.stringify({ ok: true }));
154
- return;
155
- }
156
- if (url === '/' || url === '/index.html') {
157
- const html = readWebAsset('dashboard.html');
158
- if (!html || !state.data) {
159
- res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
160
- res.end('看板资源未就绪');
161
- return;
162
- }
163
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
164
- res.end(injectData(html, state.data));
165
- return;
166
- }
167
- if (url === '/panel') {
168
- const html = readWebAsset('panel.html');
169
- if (!html || !state.data) {
170
- res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
171
- res.end('面板资源未就绪');
172
- return;
173
- }
174
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
175
- res.end(injectData(html, state.data));
176
- return;
177
- }
178
- res.writeHead(404); res.end('not found');
179
- } catch (e) {
180
- res.writeHead(500); res.end(String(e));
181
- }
182
- });
183
-
184
- await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
185
- console.log(`token-pilot serve · http://127.0.0.1:${port}(数据不出本机)`);
186
- console.log(`菜单栏面板预览:http://127.0.0.1:${port}/panel`);
187
- // 自动打开看板
188
- try {
189
- const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
190
- const args = process.platform === 'win32' ? ['/c', 'start', `http://127.0.0.1:${port}`] : [`http://127.0.0.1:${port}`];
191
- spawn(opener, args, { detached: true, stdio: 'ignore' }).unref();
192
- } catch { /* 手动打开即可 */ }
193
- }
194
-
195
- // dash 命令:静态 bake 一份带数据的 HTML(不起服务)
196
- export async function bakeDashboard(): Promise<string> {
197
- const state: ServeState = { collector: new Collector(), data: null, refreshing: false, lastAlertPct: 0 };
198
- const data = await refreshOnce(state);
199
- const html = readWebAsset('dashboard.html');
200
- if (!html) throw new Error('web/dashboard.html 不存在');
201
- const out = path.join(CONFIG_DIR, 'dashboard.html');
202
- writeFileSync(out, injectData(html, data), 'utf8');
203
- return out;
204
- }
205
-
206
- export function budgetLine(cfg: TokenPilotConfig): string {
207
- const b = monthlyBudgetCny(cfg);
208
- return b ? `¥${b}` : '未设置';
209
- }