@anthonyhan/token-pilot 0.4.12 → 0.5.0
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 +26 -2
- package/dist/cli/index.js +97 -2
- package/dist/cli/serve.js +110 -0
- package/dist/core/doctor.js +17 -1
- package/dist/core/optimizer/bili.js +123 -0
- package/dist/core/optimizer/hosts.js +367 -0
- package/dist/core/optimizer/index.js +588 -0
- package/dist/core/optimizer/state.js +169 -0
- package/dist/core/optimizer/types.js +5 -0
- package/dist/core/rtk.js +202 -28
- package/package.json +2 -2
- package/web/dashboard.html +452 -16
package/README.md
CHANGED
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
[](#-状态栏应用)
|
|
13
13
|
[](tests/)
|
|
14
14
|
[](#-数据准确性)
|
|
15
|
+
[](#状态栏应用)
|
|
16
|
+
|
|
17
|
+
> 它**不是**云服务,也不是代理:不注册、不上传、不改你的请求——只在你本机读日志算账。账单算不准,一切免谈,所以[对账脚本逐项一致](#-数据准确性)是本项目第一优先级。
|
|
15
18
|
|
|
16
19
|
[快速开始](#-快速开始) · [状态栏应用](#-状态栏应用) · [数据准确性](#-数据准确性) · [什么时候别用它](#-什么时候别用它) · [讨论](https://github.com/anthonyhann/token-pilot/discussions) · [贡献](CONTRIBUTING.md) · [English](README-en.md)
|
|
17
20
|
|
|
@@ -92,6 +95,26 @@ xattr -dr com.apple.quarantine /Applications/token-pilot.app
|
|
|
92
95
|
|
|
93
96
|
**兼容你的工具链:** Claude Code ✅ · Codex ✅ · Kimi Code ✅ · OpenCode ✅(全量 token)· DeepSeek/GLM/Kimi/Qwen/MiniMax/混元/MiMo/LongCat/Doubao ✅(模型归一)· 其余 12 款仅检测 · 桌面订阅端记固定月费
|
|
94
97
|
|
|
98
|
+
## 🧰 省 token 控制台
|
|
99
|
+
|
|
100
|
+
看板里的「省 token 控制台」把两件事接在一起:
|
|
101
|
+
|
|
102
|
+
- **RTK**:在工具输出进入上下文前压缩命令、测试、搜索和文件读取结果。
|
|
103
|
+
- **billion-context**:在长会话中折叠旧上下文,支持搜索/回读,降低每轮重发成本。
|
|
104
|
+
|
|
105
|
+
入口:
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
token-pilot optimize scan # 扫描本机 Agent / CLI / 桌面端
|
|
109
|
+
token-pilot optimize plan # 生成可审阅的接入计划
|
|
110
|
+
token-pilot optimize apply # 执行计划(宿主配置按事务备份)
|
|
111
|
+
token-pilot optimize rollback # 一键恢复接入前配置
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
看板里可以勾选宿主、预览每一步会写什么、失败只回滚对应宿主。**外部已有的 RTK/bili 只使用、不擅自卸载**;桌面端没有稳定接入缝的宿主会明确标为「不可接管」,不会把失败包装成成功。
|
|
115
|
+
|
|
116
|
+
> 边界:billion-context 的 MIT 许可证带额外署名条款;RTK 的代理/引擎部分有 BUSL-1.1。token-pilot 按需调用上游安装命令,不把它们的二进制打包进 npm/cask。
|
|
117
|
+
|
|
95
118
|
## 📈 数据准确性
|
|
96
119
|
|
|
97
120
|
账单工具不准就是误导。所以准确性**可验证**:
|
|
@@ -99,7 +122,7 @@ xattr -dr com.apple.quarantine /Applications/token-pilot.app
|
|
|
99
122
|
```bash
|
|
100
123
|
python3 scripts/reconcile.py month # 第三方视角独立重算原始日志,与 CLI 逐项对账
|
|
101
124
|
python3 scripts/verify-dashboard.py # 看板 36 项算法不变量校验
|
|
102
|
-
npm test #
|
|
125
|
+
npm test # 151 个单元测试(定价/采集口径/聚合/注入/熔断/RTK/额度/并发/省 token)
|
|
103
126
|
```
|
|
104
127
|
|
|
105
128
|
实测修过的口径坑(2026-10-21,本机 4787 个日志文件):
|
|
@@ -113,7 +136,7 @@ npm test # 69 个单元测试(定价/采集口径
|
|
|
113
136
|
## 📊 凭什么信我
|
|
114
137
|
|
|
115
138
|
- 我自己的 AI 账单就是它管的:本月 **¥8,265 / 47.8 亿 tokens**(2026-10-29 本机实时数据)
|
|
116
|
-
- 36 项看板算法不变量 +
|
|
139
|
+
- 36 项看板算法不变量 + 151 个单测 + 独立对账脚本,全部开箱可跑
|
|
117
140
|
- 诚实披露速率口径:日志按「调用完成时刻」记账,生成中的调用完成前不计入(看板内有注明)
|
|
118
141
|
|
|
119
142
|
## ⚠️ 什么时候别用它
|
|
@@ -282,6 +305,7 @@ token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝
|
|
|
282
305
|
**节流(Step 2)**
|
|
283
306
|
- [x] 2A 压缩潜力量化(规则引擎:陈旧输出/重复读取/超长输出 → 本月可省多少,实测 $63-95)
|
|
284
307
|
- [x] 2B 压缩执行第一层:自动压缩提醒 + Claude autoCompact 写入 + RTK 安装(含 engine 的完整版;自动接 hook,改动 settings.json 前备份、失败还原)
|
|
308
|
+
- [x] 省 token 控制台:RTK / billion-context 宿主扫描、接入计划、配置事务回滚、桌面端 Tauri 命令桥
|
|
285
309
|
- [x] 异常重试自动熔断提醒(`breaker.ts`:单会话 ≥30 次调用即主动通知,每轮最多提 1 个防首跑轰炸)
|
|
286
310
|
- [⏸] 2B 压缩执行第二层:代理网关(LiteLLM / 自研)
|
|
287
311
|
- 卡点不是技术,是**边界**:本地代理会接管你所有 AI 工具的请求链路。要做就得先回答「失败怎么无感回退」「改了网络出问题怎么一键还原」「凭什么让用户信它不劫持 key」。这三条没有令人信服的答案之前不做——**宁可不做,也不能做一个会偷偷影响你网络的中间层**
|
package/dist/cli/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// token-pilot CLI — 多宿主聚合
|
|
3
|
-
// 命令:today | month | report | sync | dash | serve
|
|
3
|
+
// 命令:today | month | report | sync | dash | serve | optimize
|
|
4
4
|
import { costOf, loadPricingWithOverrides } from '../core/pricing.js';
|
|
5
5
|
import { progressBar } from '../core/budget.js';
|
|
6
6
|
import { detectRetryLoops } from '../core/retry-detector.js';
|
|
@@ -15,6 +15,7 @@ import { notifyRetryLoops } from '../core/breaker.js';
|
|
|
15
15
|
import { autoFetchPrices, autoOverrides } from '../core/price-fetch.js';
|
|
16
16
|
import { buildDashboardData } from '../core/aggregate.js';
|
|
17
17
|
import { serve, bakeDashboard, writeDashboardDataFile } from './serve.js';
|
|
18
|
+
import { applyOptimizerSelection, buildOptimizerPlan, rollbackOptimizer, scanOptimizer, } from '../core/optimizer/index.js';
|
|
18
19
|
function startOfToday() {
|
|
19
20
|
const d = new Date();
|
|
20
21
|
d.setHours(0, 0, 0, 0);
|
|
@@ -260,6 +261,98 @@ async function cmdCompressReport() {
|
|
|
260
261
|
console.log('\n建议:上下文压缩代理可把这部分省下来(规则法已验证 −29%~−48% 输入)。');
|
|
261
262
|
console.log('');
|
|
262
263
|
}
|
|
264
|
+
function optimizeProfile(raw) {
|
|
265
|
+
return raw === 'deep' ? 'deep' : 'safe';
|
|
266
|
+
}
|
|
267
|
+
function stepLine(s) {
|
|
268
|
+
const icon = s.state === 'ok' ? '✓' : s.state === 'failed' ? '✗' : s.state === 'skipped' ? '·' : '○';
|
|
269
|
+
return ` ${icon} ${s.title}${s.command ? `\n ${s.command}` : ''}${s.message ? `\n ${s.message}` : ''}`;
|
|
270
|
+
}
|
|
271
|
+
async function cmdOptimize() {
|
|
272
|
+
const sub = process.argv[3] ?? 'scan';
|
|
273
|
+
const json = process.argv.includes('--json');
|
|
274
|
+
const profile = optimizeProfile(process.argv[process.argv.indexOf('--profile') + 1]);
|
|
275
|
+
const hostIds = [];
|
|
276
|
+
for (let i = 0; i < process.argv.length; i++) {
|
|
277
|
+
if (process.argv[i] === '--host' && process.argv[i + 1])
|
|
278
|
+
hostIds.push(process.argv[i + 1]);
|
|
279
|
+
}
|
|
280
|
+
if (sub === 'scan' || sub === 'status') {
|
|
281
|
+
const scan = await scanOptimizer();
|
|
282
|
+
if (json) {
|
|
283
|
+
console.log(JSON.stringify(scan, null, 2));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
console.log('\ntoken-pilot · 省 token 扫描\n');
|
|
287
|
+
for (const e of scan.engines) {
|
|
288
|
+
console.log(`${e.installed ? '✓' : '○'} ${e.name} ${e.version || ''} · ${e.detail}`);
|
|
289
|
+
}
|
|
290
|
+
console.log('');
|
|
291
|
+
const installed = scan.hosts.filter((h) => h.installed);
|
|
292
|
+
if (!installed.length) {
|
|
293
|
+
console.log('没有检测到受支持的 Agent/CLI。');
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
for (const h of installed) {
|
|
297
|
+
const flags = [
|
|
298
|
+
h.rtkSupported ? (h.rtkConfigured ? 'RTK✓' : 'RTK') : '',
|
|
299
|
+
h.biliMode === 'plugin' ? (h.biliConfigured ? 'bili✓' : 'bili') : h.biliMode,
|
|
300
|
+
].filter(Boolean).join(' · ');
|
|
301
|
+
console.log(` ${h.name.padEnd(18)} ${h.support.padEnd(10)} ${flags}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
console.log(`\n可一键:${scan.summary.auto} · 引导:${scan.summary.assisted} · 不支持:${scan.summary.unsupported}`);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (sub === 'plan') {
|
|
308
|
+
const scan = await scanOptimizer();
|
|
309
|
+
const plan = buildOptimizerPlan(scan, profile, hostIds.length ? hostIds : undefined);
|
|
310
|
+
if (json) {
|
|
311
|
+
console.log(JSON.stringify(plan, null, 2));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
console.log('\ntoken-pilot · 省 token 接入计划\n');
|
|
315
|
+
if (!plan.steps.length) {
|
|
316
|
+
console.log('没有可执行的步骤。');
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
for (const s of plan.steps)
|
|
320
|
+
console.log(stepLine(s));
|
|
321
|
+
console.log('\n确认后执行:token-pilot optimize apply --profile ' + profile);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (sub === 'apply') {
|
|
325
|
+
const r = await applyOptimizerSelection(profile, hostIds.length ? hostIds : undefined);
|
|
326
|
+
if (json) {
|
|
327
|
+
console.log(JSON.stringify(r, null, 2));
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
console.log('\ntoken-pilot · 执行省 token 计划\n');
|
|
331
|
+
for (const s of r.steps)
|
|
332
|
+
console.log(stepLine(s));
|
|
333
|
+
console.log(`\n${r.ok ? '✓' : '✗'} ${r.message}`);
|
|
334
|
+
}
|
|
335
|
+
if (!r.ok)
|
|
336
|
+
process.exitCode = 1;
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (sub === 'rollback') {
|
|
340
|
+
const r = await rollbackOptimizer();
|
|
341
|
+
if (json) {
|
|
342
|
+
console.log(JSON.stringify(r, null, 2));
|
|
343
|
+
}
|
|
344
|
+
else {
|
|
345
|
+
console.log('\ntoken-pilot · 回滚省 token 接入\n');
|
|
346
|
+
for (const s of r.steps)
|
|
347
|
+
console.log(stepLine(s));
|
|
348
|
+
console.log(`\n${r.ok ? '✓' : '✗'} ${r.message}`);
|
|
349
|
+
}
|
|
350
|
+
if (!r.ok)
|
|
351
|
+
process.exitCode = 1;
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
console.log('用法:token-pilot optimize [scan|plan|apply|status|rollback] [--profile safe|deep] [--host id] [--json]');
|
|
355
|
+
}
|
|
263
356
|
async function main() {
|
|
264
357
|
const cmd = process.argv[2] ?? 'today';
|
|
265
358
|
// 报版本:用户想确认装的是哪一版(也方便 issue 里贴环境)
|
|
@@ -281,6 +374,8 @@ async function main() {
|
|
|
281
374
|
return cmdPrices();
|
|
282
375
|
if (cmd === 'compress-report')
|
|
283
376
|
return cmdCompressReport();
|
|
377
|
+
if (cmd === 'optimize')
|
|
378
|
+
return cmdOptimize();
|
|
284
379
|
if (cmd === 'quota') {
|
|
285
380
|
const { collectQuota } = await import('../core/quota/index.js');
|
|
286
381
|
const { formatQuota } = await import('../core/quota/format.js');
|
|
@@ -324,7 +419,7 @@ async function main() {
|
|
|
324
419
|
if (cmd === 'today' || cmd === 'month' || cmd === 'report' || cmd === 'all') {
|
|
325
420
|
return cmdReport(cmd === 'all' ? 'all' : cmd);
|
|
326
421
|
}
|
|
327
|
-
console.log('用法:token-pilot [today|month|report|sync|dash|serve|prices|quota|doctor|version]');
|
|
422
|
+
console.log('用法:token-pilot [today|month|report|sync|dash|serve|prices|quota|doctor|compress-report|optimize|version]');
|
|
328
423
|
}
|
|
329
424
|
main().catch((e) => {
|
|
330
425
|
console.error('错误:', e.message);
|
package/dist/cli/serve.js
CHANGED
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
// GET /api/data DashboardData JSON(前端轮询)
|
|
6
6
|
// GET /api/config 当前配置
|
|
7
7
|
// POST /api/config 保存配置(设置弹窗写回)
|
|
8
|
+
// GET /api/optimizer/scan 扫宿主 / 引擎状态
|
|
9
|
+
// POST /api/optimizer/plan 生成接入计划
|
|
10
|
+
// POST /api/optimizer/apply 异步执行接入
|
|
11
|
+
// POST /api/optimizer/rollback 异步回滚
|
|
8
12
|
// 后台每 10s 增量采集 + 重聚合,同时写 ~/.token-pilot/dashboard-data.json 给 Tauri 菜单栏。
|
|
9
13
|
import http from 'node:http';
|
|
10
14
|
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
@@ -22,6 +26,7 @@ import { costOf } from '../core/pricing.js';
|
|
|
22
26
|
import { detectRetryLoops } from '../core/retry-detector.js';
|
|
23
27
|
import { notifyRetryLoops } from '../core/breaker.js';
|
|
24
28
|
import { installRtk, uninstallRtk, rtkStatus } from '../core/rtk.js';
|
|
29
|
+
import { applyOptimizerSelection, buildOptimizerPlan, rollbackOptimizer, scanOptimizer, } from '../core/optimizer/index.js';
|
|
25
30
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
26
31
|
const WEB_DIR = path.resolve(__dirname, '../../web');
|
|
27
32
|
export function readWebAsset(name) {
|
|
@@ -91,6 +96,8 @@ function readBody(req) {
|
|
|
91
96
|
}
|
|
92
97
|
export async function serve(port = 17895) {
|
|
93
98
|
const state = { collector: new Collector(), data: null, refreshing: false, lastAlertPct: 0 };
|
|
99
|
+
const optimizerJobs = new Map();
|
|
100
|
+
let optimizerRunning = false;
|
|
94
101
|
const refresh = async () => {
|
|
95
102
|
if (state.refreshing)
|
|
96
103
|
return;
|
|
@@ -113,6 +120,109 @@ export async function serve(port = 17895) {
|
|
|
113
120
|
res.end(JSON.stringify(state.data ?? {}));
|
|
114
121
|
return;
|
|
115
122
|
}
|
|
123
|
+
if (url === '/api/optimizer/scan' && req.method === 'GET') {
|
|
124
|
+
const scan = await scanOptimizer();
|
|
125
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
126
|
+
res.end(JSON.stringify(scan));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (url === '/api/optimizer/plan' && req.method === 'POST') {
|
|
130
|
+
const body = await readBody(req);
|
|
131
|
+
const payload = JSON.parse(body || '{}');
|
|
132
|
+
const scan = await scanOptimizer();
|
|
133
|
+
const plan = buildOptimizerPlan(scan, payload.profile === 'deep' ? 'deep' : 'safe', Array.isArray(payload.hostIds) ? payload.hostIds.filter((x) => typeof x === 'string') : undefined);
|
|
134
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
135
|
+
res.end(JSON.stringify(plan));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (url === '/api/optimizer/apply' && req.method === 'POST') {
|
|
139
|
+
if (optimizerRunning) {
|
|
140
|
+
res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' });
|
|
141
|
+
res.end(JSON.stringify({ ok: false, error: '已有省 token 任务在运行' }));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const body = await readBody(req);
|
|
145
|
+
const payload = JSON.parse(body || '{}');
|
|
146
|
+
const job = {
|
|
147
|
+
id: `job-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
|
|
148
|
+
kind: 'apply',
|
|
149
|
+
status: 'running',
|
|
150
|
+
startedAt: Date.now(),
|
|
151
|
+
message: '正在执行接入计划…',
|
|
152
|
+
steps: [],
|
|
153
|
+
};
|
|
154
|
+
optimizerJobs.set(job.id, job);
|
|
155
|
+
optimizerRunning = true;
|
|
156
|
+
void (async () => {
|
|
157
|
+
try {
|
|
158
|
+
const r = await applyOptimizerSelection(payload.profile === 'deep' ? 'deep' : 'safe', Array.isArray(payload.hostIds) ? payload.hostIds.filter((x) => typeof x === 'string') : undefined);
|
|
159
|
+
job.status = r.ok ? 'ok' : 'failed';
|
|
160
|
+
job.message = r.message;
|
|
161
|
+
job.steps = r.steps;
|
|
162
|
+
job.scan = r.scan;
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
job.status = 'failed';
|
|
166
|
+
job.message = e instanceof Error ? e.message : String(e);
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
job.finishedAt = Date.now();
|
|
170
|
+
optimizerRunning = false;
|
|
171
|
+
}
|
|
172
|
+
})();
|
|
173
|
+
res.writeHead(202, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
174
|
+
res.end(JSON.stringify({ ok: true, jobId: job.id }));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (url === '/api/optimizer/rollback' && req.method === 'POST') {
|
|
178
|
+
if (optimizerRunning) {
|
|
179
|
+
res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' });
|
|
180
|
+
res.end(JSON.stringify({ ok: false, error: '已有省 token 任务在运行' }));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const job = {
|
|
184
|
+
id: `job-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
|
|
185
|
+
kind: 'rollback',
|
|
186
|
+
status: 'running',
|
|
187
|
+
startedAt: Date.now(),
|
|
188
|
+
message: '正在回滚接入配置…',
|
|
189
|
+
steps: [],
|
|
190
|
+
};
|
|
191
|
+
optimizerJobs.set(job.id, job);
|
|
192
|
+
optimizerRunning = true;
|
|
193
|
+
void (async () => {
|
|
194
|
+
try {
|
|
195
|
+
const r = await rollbackOptimizer();
|
|
196
|
+
job.status = r.ok ? 'ok' : 'failed';
|
|
197
|
+
job.message = r.message;
|
|
198
|
+
job.steps = r.steps;
|
|
199
|
+
job.scan = r.scan;
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
job.status = 'failed';
|
|
203
|
+
job.message = e instanceof Error ? e.message : String(e);
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
job.finishedAt = Date.now();
|
|
207
|
+
optimizerRunning = false;
|
|
208
|
+
}
|
|
209
|
+
})();
|
|
210
|
+
res.writeHead(202, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
211
|
+
res.end(JSON.stringify({ ok: true, jobId: job.id }));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (url === '/api/optimizer/job' && req.method === 'GET') {
|
|
215
|
+
const id = new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('id') ?? '';
|
|
216
|
+
const job = optimizerJobs.get(id);
|
|
217
|
+
if (!job) {
|
|
218
|
+
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
|
|
219
|
+
res.end(JSON.stringify({ ok: false, error: '任务不存在或已过期' }));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
223
|
+
res.end(JSON.stringify(job));
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
116
226
|
// 测试连接:用「本次输入的 key」直接打一次接口。
|
|
117
227
|
// 必须先于保存就能测——否则用户得先存一个可能错的 key 才能验证。
|
|
118
228
|
// 测试连接:用「本次输入的 key」直接打一次接口。
|
package/dist/core/doctor.js
CHANGED
|
@@ -218,7 +218,7 @@ export async function runDoctor() {
|
|
|
218
218
|
level: 'info',
|
|
219
219
|
title: 'RTK 来源提示',
|
|
220
220
|
detail: st.detail,
|
|
221
|
-
fix: '
|
|
221
|
+
fix: '系统已有 RTK 可直接使用;本工具不会接管/卸载外部安装',
|
|
222
222
|
});
|
|
223
223
|
}
|
|
224
224
|
else {
|
|
@@ -233,6 +233,22 @@ export async function runDoctor() {
|
|
|
233
233
|
catch {
|
|
234
234
|
/* RTK 检测失败不影响整体自检 */
|
|
235
235
|
}
|
|
236
|
+
// ── 7b. 省 token 控制台已接管的宿主 ──
|
|
237
|
+
try {
|
|
238
|
+
const { loadOptimizerState } = await import('./optimizer/state.js');
|
|
239
|
+
const managed = Object.keys(loadOptimizerState().hosts);
|
|
240
|
+
if (managed.length > 0) {
|
|
241
|
+
push({
|
|
242
|
+
level: 'ok',
|
|
243
|
+
title: `省 token 已接管 ${managed.length} 个宿主`,
|
|
244
|
+
detail: managed.join('、'),
|
|
245
|
+
fix: '看板「省 token 控制台」可查看计划/回滚',
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
/* 状态文件损坏不影响整体自检 */
|
|
251
|
+
}
|
|
236
252
|
// ── 8. 额度监控:有哪些平台可读、哪些缺凭证 ──
|
|
237
253
|
try {
|
|
238
254
|
const { collectQuota } = await import('./quota/index.js');
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// billion-context 引擎适配层
|
|
2
|
+
//
|
|
3
|
+
// 只调用上游官方命令:npm 安装、bili plugin install/remove、bili doctor。
|
|
4
|
+
// 不在这里手写宿主 JSON/TOML;配置副作用交给上游,token-pilot 负责备份/验证/回滚。
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
const execFileP = promisify(execFile);
|
|
11
|
+
async function run(cmd, args, timeout = 30_000) {
|
|
12
|
+
try {
|
|
13
|
+
const r = await execFileP(cmd, args, {
|
|
14
|
+
timeout,
|
|
15
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
16
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
17
|
+
});
|
|
18
|
+
return { ok: true, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() };
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
const err = e;
|
|
22
|
+
return { ok: false, out: (err.stdout || '').trim(), err: (err.stderr || err.message || String(e)).trim() };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export function biliPath() {
|
|
26
|
+
// 不依赖 PATH 也能调用:bili 的推荐安装位置在 ~/.local/bin。
|
|
27
|
+
const local = path.join(os.homedir(), '.local', 'bin', process.platform === 'win32' ? 'bili.cmd' : 'bili');
|
|
28
|
+
return existsSync(local) ? local : 'bili';
|
|
29
|
+
}
|
|
30
|
+
export async function biliStatus() {
|
|
31
|
+
const p = biliPath();
|
|
32
|
+
const ver = await run(p, ['--version'], 8_000);
|
|
33
|
+
if (!ver.ok) {
|
|
34
|
+
return {
|
|
35
|
+
id: 'bili',
|
|
36
|
+
name: 'billion-context',
|
|
37
|
+
installed: false,
|
|
38
|
+
usable: false,
|
|
39
|
+
version: '',
|
|
40
|
+
source: 'none',
|
|
41
|
+
detail: '未安装',
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const version = (ver.out.split('\n')[0] || '').replace(/^bili\s*/i, '').trim();
|
|
45
|
+
return {
|
|
46
|
+
id: 'bili',
|
|
47
|
+
name: 'billion-context',
|
|
48
|
+
installed: true,
|
|
49
|
+
usable: true,
|
|
50
|
+
version,
|
|
51
|
+
source: 'foreign',
|
|
52
|
+
detail: `已安装 ${version || '(版本未知)'}`,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function nodeSupportsBili() {
|
|
56
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
57
|
+
return major >= 20;
|
|
58
|
+
}
|
|
59
|
+
export async function installBili() {
|
|
60
|
+
if (!nodeSupportsBili()) {
|
|
61
|
+
return {
|
|
62
|
+
ok: false,
|
|
63
|
+
message: `billion-context 需要 Node.js >= 20;当前 token-pilot 运行在 ${process.version}。请先升级 Node,或只启用 RTK。`,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
67
|
+
const args = process.platform === 'win32'
|
|
68
|
+
? ['install', '-g', 'billion-context']
|
|
69
|
+
: ['install', '-g', 'billion-context', `--prefix=${path.join(os.homedir(), '.local')}`];
|
|
70
|
+
const r = await run(npmCmd, args, 300_000);
|
|
71
|
+
if (!r.ok) {
|
|
72
|
+
return { ok: false, message: `billion-context 安装失败:${firstLines(r.err, 3) || '未知原因'}` };
|
|
73
|
+
}
|
|
74
|
+
const st = await biliStatus();
|
|
75
|
+
if (!st.installed) {
|
|
76
|
+
return {
|
|
77
|
+
ok: false,
|
|
78
|
+
message: 'npm 安装命令执行了,但 bili 命令仍不可用。请检查 PATH 或重新打开终端后重试。',
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return { ok: true, message: `billion-context 已安装(${st.version || '版本未知'})` };
|
|
82
|
+
}
|
|
83
|
+
export async function biliPluginInstall(client) {
|
|
84
|
+
const r = await run(biliPath(), ['plugin', 'install', client], 120_000);
|
|
85
|
+
if (!r.ok) {
|
|
86
|
+
return { ok: false, message: `bili plugin install ${client} 失败:${firstLines(r.err || r.out, 3)}` };
|
|
87
|
+
}
|
|
88
|
+
return { ok: true, message: (r.out || `bili 插件已接入 ${client}`).split('\n').slice(0, 3).join(' / ') };
|
|
89
|
+
}
|
|
90
|
+
export async function biliPluginRemove(client) {
|
|
91
|
+
const r = await run(biliPath(), ['plugin', 'remove', client], 120_000);
|
|
92
|
+
if (!r.ok) {
|
|
93
|
+
return { ok: false, message: `bili plugin remove ${client} 失败:${firstLines(r.err || r.out, 3)}` };
|
|
94
|
+
}
|
|
95
|
+
return { ok: true, message: (r.out || `已移除 ${client} 的 bili 插件`).split('\n').slice(0, 3).join(' / ') };
|
|
96
|
+
}
|
|
97
|
+
export async function biliPluginList() {
|
|
98
|
+
return run(biliPath(), ['plugin', 'list'], 30_000);
|
|
99
|
+
}
|
|
100
|
+
export async function biliDoctor() {
|
|
101
|
+
return run(biliPath(), ['doctor'], 60_000);
|
|
102
|
+
}
|
|
103
|
+
export function isBiliPluginListed(listOutput, client) {
|
|
104
|
+
if (!listOutput)
|
|
105
|
+
return false;
|
|
106
|
+
const needle = client.toLowerCase();
|
|
107
|
+
return listOutput
|
|
108
|
+
.split('\n')
|
|
109
|
+
.some((line) => {
|
|
110
|
+
const s = line.toLowerCase();
|
|
111
|
+
if (!s.includes(needle))
|
|
112
|
+
return false;
|
|
113
|
+
if (/not\s+installed|未安装|disabled|not\s+enabled/.test(s))
|
|
114
|
+
return false;
|
|
115
|
+
// Claude 的旧 companion 只装了 MCP,不等于 native block;仍需要重跑 install
|
|
116
|
+
if (/mcp only|legacy companion|companion posture/.test(s))
|
|
117
|
+
return false;
|
|
118
|
+
return /(\[ok\]|✓|✔|installed|enabled|\byes\b|已接入|已安装)/i.test(line);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function firstLines(s, n) {
|
|
122
|
+
return s.split('\n').map((x) => x.trim()).filter(Boolean).slice(0, n).join(' / ').slice(0, 400);
|
|
123
|
+
}
|