@anthonyhan/token-pilot 0.4.12 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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」直接打一次接口。
@@ -19,8 +19,12 @@ import { workbuddyAdapter, workbuddyAiAdapter } from '../adapters/workbuddy.js';
19
19
  import { CONFIG_DIR } from './config.js';
20
20
  export const ALL_ADAPTERS = [claudeCodeAdapter, codexAdapter, kimiCodeAdapter, opencodeAdapter, piAdapter, volcArkAdapter, dshAdapter, workbuddyAdapter, workbuddyAiAdapter];
21
21
  const CACHE_PATH = path.join(CONFIG_DIR, 'events-cache.json');
22
- /** 同时打开的文件数上限。SSD 上 32 已经能吃到 IO 带宽,再高只是徒增内存峰值。 */
23
- const FILE_CONCURRENCY = 32;
22
+ /**
23
+ * 同时打开的文件数上限。
24
+ * 这里从 32 降到 4:用户的 rollout / trace 里有 100–300MB 单文件,
25
+ * 32 路并发会把「整文件读取 + 行数组」叠加到数 GB;流式读取后 4 路足够。
26
+ */
27
+ const FILE_CONCURRENCY = 4;
24
28
  /** 限并发的 map,保持结果顺序无关(本项目只关心副作用) */
25
29
  async function mapWithConcurrency(items, limit, fn) {
26
30
  let cursor = 0;
@@ -218,7 +218,7 @@ export async function runDoctor() {
218
218
  level: 'info',
219
219
  title: 'RTK 来源提示',
220
220
  detail: st.detail,
221
- fix: '要看板代装 rtk-oss,需先卸载现有的 rtk',
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
+ }