@anthonyhan/token-pilot 0.0.0-stage → 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.
@@ -0,0 +1,200 @@
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
+ import http from 'node:http';
10
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { spawn } from 'node:child_process';
14
+ import { Collector } from '../core/collector.js';
15
+ import { autoOverrides } from '../core/price-fetch.js';
16
+ import { buildDashboardData } from '../core/aggregate.js';
17
+ import { loadPricingWithOverrides } from '../core/pricing.js';
18
+ import { loadConfig, saveConfig, fxRate, monthlyBudgetCny, DATA_PATH, CONFIG_DIR } from '../core/config.js';
19
+ import { notify } from '../core/alert.js';
20
+ import { applyClaudeAutoCompact } from '../core/autocompact.js';
21
+ import { installRtk, uninstallRtk, rtkInstalled } from '../core/rtk.js';
22
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
+ const WEB_DIR = path.resolve(__dirname, '../../web');
24
+ export function readWebAsset(name) {
25
+ const p = path.join(WEB_DIR, name);
26
+ if (!existsSync(p))
27
+ return null;
28
+ return readFileSync(p, 'utf8');
29
+ }
30
+ export function injectData(html, data) {
31
+ const json = JSON.stringify(data).replace(/</g, '\\u003c');
32
+ return html.replace('window.__TP_DATA__=null;', `window.__TP_DATA__=${json};`);
33
+ }
34
+ export function writeDashboardDataFile(data) {
35
+ mkdirSync(CONFIG_DIR, { recursive: true });
36
+ writeFileSync(DATA_PATH, JSON.stringify(data), 'utf8');
37
+ }
38
+ export async function refreshOnce(state) {
39
+ const cfg = loadConfig();
40
+ const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fxRate(cfg));
41
+ const { events, contentEvents } = await state.collector.sync();
42
+ const data = await buildDashboardData(events, cfg, pricing, contentEvents ?? []);
43
+ state.data = data;
44
+ writeDashboardDataFile(data);
45
+ // 预算告警(每跨一次阈值提醒一次)
46
+ if (data.budget) {
47
+ const threshold = cfg.alertOnPercent ?? 80;
48
+ const pct = data.budget.pct;
49
+ if (pct >= threshold && Math.floor(pct / 10) > Math.floor(state.lastAlertPct / 10)) {
50
+ notify('token-pilot 预算告警', `本月已用 ${pct.toFixed(0)}%(${data.budget.spentCny.toFixed(0)} / ${data.budget.monthlyCny.toFixed(0)} 元)`);
51
+ }
52
+ state.lastAlertPct = pct;
53
+ }
54
+ // 自动压缩提醒(开关开着时):超阈值会话发系统通知,单会话 30min 冷却
55
+ const ac = cfg.autoCompact;
56
+ if (ac?.enabled && data.live.sessions.some((s) => s.needsCompact)) {
57
+ if (!state.compactNotifiedAt)
58
+ state.compactNotifiedAt = new Map();
59
+ const threshold = ac.thresholdTokens ?? 100_000;
60
+ for (const s of data.live.sessions) {
61
+ if (!s.needsCompact)
62
+ continue;
63
+ const last = state.compactNotifiedAt.get(s.key) ?? 0;
64
+ if (Date.now() - last < 30 * 60_000)
65
+ continue;
66
+ state.compactNotifiedAt.set(s.key, Date.now());
67
+ notify('token-pilot · 该压缩上下文了', `${s.agent} 会话上下文 ${Math.round((s.ctxTokens ?? threshold) / 1000)}K tokens,后续每轮都全量重发。到对应窗口跑 /compact 可立即降本。`);
68
+ }
69
+ }
70
+ return data;
71
+ }
72
+ function readBody(req) {
73
+ return new Promise((resolve, reject) => {
74
+ let buf = '';
75
+ req.on('data', (c) => { buf += c; if (buf.length > 1_000_000)
76
+ req.destroy(); });
77
+ req.on('end', () => resolve(buf));
78
+ req.on('error', reject);
79
+ });
80
+ }
81
+ export async function serve(port = 17895) {
82
+ const state = { collector: new Collector(), data: null, refreshing: false, lastAlertPct: 0 };
83
+ const refresh = async () => {
84
+ if (state.refreshing)
85
+ return;
86
+ state.refreshing = true;
87
+ try {
88
+ await refreshOnce(state);
89
+ }
90
+ catch { /* 下一轮再来 */ }
91
+ finally {
92
+ state.refreshing = false;
93
+ }
94
+ };
95
+ await refresh();
96
+ setInterval(refresh, 10_000);
97
+ const server = http.createServer(async (req, res) => {
98
+ const url = (req.url ?? '/').split('?')[0];
99
+ try {
100
+ if (url === '/api/data') {
101
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
102
+ res.end(JSON.stringify(state.data ?? {}));
103
+ return;
104
+ }
105
+ if (url === '/api/config' && req.method === 'GET') {
106
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
107
+ res.end(JSON.stringify(loadConfig()));
108
+ return;
109
+ }
110
+ if (url === '/api/config' && req.method === 'POST') {
111
+ const body = await readBody(req);
112
+ const patch = JSON.parse(body);
113
+ const cur = loadConfig();
114
+ const next = { ...cur, ...patch };
115
+ // 用户明示后,写 Claude Code 的 autoCompactEnabled
116
+ if (next.autoCompact?.applyClaudeCode) {
117
+ const r = applyClaudeAutoCompact(next.autoCompact.enabled);
118
+ if (!r.ok) {
119
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
120
+ res.end(JSON.stringify({ ok: false, error: r.message }));
121
+ return;
122
+ }
123
+ }
124
+ // RTK 安装层:勾选且未装 → 装;取消勾选且已装 → 卸
125
+ if (next.autoCompact && typeof next.autoCompact.installRtk === 'boolean') {
126
+ const installed = await rtkInstalled();
127
+ if (next.autoCompact.installRtk && !installed) {
128
+ const r = await installRtk();
129
+ if (!r.ok) {
130
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
131
+ res.end(JSON.stringify({ ok: false, error: r.message }));
132
+ return;
133
+ }
134
+ }
135
+ else if (!next.autoCompact.installRtk && installed) {
136
+ await uninstallRtk();
137
+ }
138
+ }
139
+ saveConfig(next);
140
+ await refresh();
141
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
142
+ res.end(JSON.stringify({ ok: true }));
143
+ return;
144
+ }
145
+ if (url === '/' || url === '/index.html') {
146
+ const html = readWebAsset('dashboard.html');
147
+ if (!html || !state.data) {
148
+ res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
149
+ res.end('看板资源未就绪');
150
+ return;
151
+ }
152
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
153
+ res.end(injectData(html, state.data));
154
+ return;
155
+ }
156
+ if (url === '/panel') {
157
+ const html = readWebAsset('panel.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
+ res.writeHead(404);
168
+ res.end('not found');
169
+ }
170
+ catch (e) {
171
+ res.writeHead(500);
172
+ res.end(String(e));
173
+ }
174
+ });
175
+ await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));
176
+ console.log(`token-pilot serve · http://127.0.0.1:${port}(数据不出本机)`);
177
+ console.log(`菜单栏面板预览:http://127.0.0.1:${port}/panel`);
178
+ // 自动打开看板
179
+ try {
180
+ const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
181
+ const args = process.platform === 'win32' ? ['/c', 'start', `http://127.0.0.1:${port}`] : [`http://127.0.0.1:${port}`];
182
+ spawn(opener, args, { detached: true, stdio: 'ignore' }).unref();
183
+ }
184
+ catch { /* 手动打开即可 */ }
185
+ }
186
+ // dash 命令:静态 bake 一份带数据的 HTML(不起服务)
187
+ export async function bakeDashboard() {
188
+ const state = { collector: new Collector(), data: null, refreshing: false, lastAlertPct: 0 };
189
+ const data = await refreshOnce(state);
190
+ const html = readWebAsset('dashboard.html');
191
+ if (!html)
192
+ throw new Error('web/dashboard.html 不存在');
193
+ const out = path.join(CONFIG_DIR, 'dashboard.html');
194
+ writeFileSync(out, injectData(html, data), 'utf8');
195
+ return out;
196
+ }
197
+ export function budgetLine(cfg) {
198
+ const b = monthlyBudgetCny(cfg);
199
+ return b ? `¥${b}` : '未设置';
200
+ }