@anthonyhan/token-pilot 0.4.11 → 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
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
// 省 token 编排层
|
|
2
|
+
//
|
|
3
|
+
// 一套扫描 -> 计划 -> 应用 -> 验证 -> 回滚的闭环。
|
|
4
|
+
// 原则:
|
|
5
|
+
// - 能用上游官方命令就不手写宿主配置;
|
|
6
|
+
// - 每个宿主独立事务,失败只回滚它自己;
|
|
7
|
+
// - 外部已有的 RTK/bili 只使用、不擅自卸载;
|
|
8
|
+
// - 桌面端没有接入缝的宿主明确标 unsupported,不伪造成成功。
|
|
9
|
+
import { execFile } from 'node:child_process';
|
|
10
|
+
import { existsSync } from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
import { HOST_RECIPES } from './hosts.js';
|
|
16
|
+
import { configureRtkAgent, installRtkBinary, isRtkAgentConfigured, rtkInitArgs, rtkStatus, unconfigureRtkAgent, } from '../rtk.js';
|
|
17
|
+
import { biliPluginInstall, biliPluginList, biliPluginRemove, biliStatus, installBili, isBiliPluginListed, nodeSupportsBili, } from './bili.js';
|
|
18
|
+
import { beginTransaction, captureAfterHashes, captureAfterHashesFor, loadOptimizerState, rollbackTransaction, saveOptimizerState, snapshotPath, } from './state.js';
|
|
19
|
+
const execFileP = promisify(execFile);
|
|
20
|
+
const HOME = os.homedir();
|
|
21
|
+
/**
|
|
22
|
+
* 宿主配方里的路径有两种写法:'~/.foo' 和 '.foo'。
|
|
23
|
+
* 两者都必须相对 HOME;不能相对进程 cwd,否则事务会备份到仓库目录里。
|
|
24
|
+
*/
|
|
25
|
+
export function resolveOptimizerPath(p, home = HOME) {
|
|
26
|
+
if (p === '~')
|
|
27
|
+
return home;
|
|
28
|
+
if (p.startsWith('~/'))
|
|
29
|
+
return path.join(home, p.slice(2));
|
|
30
|
+
if (path.isAbsolute(p))
|
|
31
|
+
return p;
|
|
32
|
+
return path.join(home, p);
|
|
33
|
+
}
|
|
34
|
+
function expandHome(p) {
|
|
35
|
+
return resolveOptimizerPath(p, HOME);
|
|
36
|
+
}
|
|
37
|
+
async function which(cmd) {
|
|
38
|
+
const bin = process.platform === 'win32' ? 'where' : 'which';
|
|
39
|
+
try {
|
|
40
|
+
const r = await execFileP(bin, [cmd], { timeout: 4_000 });
|
|
41
|
+
const line = (r.stdout || '').split('\n').map((s) => s.trim()).find(Boolean);
|
|
42
|
+
return line || undefined;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function commandVersion(cmd) {
|
|
49
|
+
try {
|
|
50
|
+
const r = await execFileP(cmd, ['--version'], { timeout: 4_000, maxBuffer: 512 * 1024 });
|
|
51
|
+
return (r.stdout || r.stderr || '').split('\n').map((s) => s.trim()).find(Boolean);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function firstExisting(paths) {
|
|
58
|
+
return paths.find((p) => {
|
|
59
|
+
if (!p)
|
|
60
|
+
return false;
|
|
61
|
+
try {
|
|
62
|
+
return existsSync(expandHome(p));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function findMacApp(appName) {
|
|
70
|
+
if (process.platform !== 'darwin')
|
|
71
|
+
return undefined;
|
|
72
|
+
const candidates = [
|
|
73
|
+
path.join('/Applications', appName),
|
|
74
|
+
path.join(HOME, 'Applications', appName),
|
|
75
|
+
];
|
|
76
|
+
return firstExisting(candidates);
|
|
77
|
+
}
|
|
78
|
+
function findWinApp(rel) {
|
|
79
|
+
if (process.platform !== 'win32')
|
|
80
|
+
return undefined;
|
|
81
|
+
const roots = [process.env.LOCALAPPDATA, process.env.APPDATA, process.env.ProgramFiles].filter(Boolean);
|
|
82
|
+
return firstExisting(roots.map((r) => path.join(r, rel)));
|
|
83
|
+
}
|
|
84
|
+
async function rtkEngineStatus() {
|
|
85
|
+
const st = await rtkStatus();
|
|
86
|
+
return {
|
|
87
|
+
id: 'rtk',
|
|
88
|
+
name: 'RTK',
|
|
89
|
+
installed: st.installed,
|
|
90
|
+
usable: st.installed && st.edition !== 'oss',
|
|
91
|
+
version: st.version,
|
|
92
|
+
source: st.source,
|
|
93
|
+
detail: st.detail,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
async function biliEngineStatus() {
|
|
97
|
+
const st = await biliStatus();
|
|
98
|
+
const state = loadOptimizerState();
|
|
99
|
+
const rec = state.engines.bili;
|
|
100
|
+
return {
|
|
101
|
+
...st,
|
|
102
|
+
source: rec?.installedByUs ? 'ours' : st.source,
|
|
103
|
+
detail: rec?.installedByUs ? `${st.detail}(由 token-pilot 安装)` : st.detail,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function hostSupport(recipe) {
|
|
107
|
+
if (recipe.support === 'unsupported')
|
|
108
|
+
return 'unsupported';
|
|
109
|
+
if (recipe.rtkAgent || recipe.bili?.mode === 'plugin')
|
|
110
|
+
return 'auto';
|
|
111
|
+
if (recipe.bili?.mode === 'launcher' || recipe.bili?.mode === 'assisted')
|
|
112
|
+
return 'assisted';
|
|
113
|
+
return recipe.support;
|
|
114
|
+
}
|
|
115
|
+
async function detectHost(recipe, biliList, state) {
|
|
116
|
+
let detectedAt;
|
|
117
|
+
let version;
|
|
118
|
+
for (const cmd of recipe.commands ?? []) {
|
|
119
|
+
const p = await which(cmd);
|
|
120
|
+
if (p) {
|
|
121
|
+
detectedAt = p;
|
|
122
|
+
version = await commandVersion(cmd);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (!detectedAt) {
|
|
127
|
+
detectedAt = firstExisting(recipe.paths ?? []);
|
|
128
|
+
}
|
|
129
|
+
if (!detectedAt) {
|
|
130
|
+
for (const app of recipe.macApps ?? []) {
|
|
131
|
+
detectedAt = findMacApp(app);
|
|
132
|
+
if (detectedAt)
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!detectedAt) {
|
|
137
|
+
for (const p of recipe.winPaths ?? []) {
|
|
138
|
+
detectedAt = findWinApp(p);
|
|
139
|
+
if (detectedAt)
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const installed = !!detectedAt;
|
|
144
|
+
const rtkSupported = !!recipe.rtkAgent;
|
|
145
|
+
const rtkConfigured = !!(recipe.rtkAgent && isRtkAgentConfigured(recipe.rtkAgent));
|
|
146
|
+
const biliMode = recipe.bili?.mode ?? 'none';
|
|
147
|
+
const biliClient = recipe.bili?.client;
|
|
148
|
+
const biliConfigured = !!((biliClient && isBiliPluginListed(biliList, biliClient)) ||
|
|
149
|
+
(biliClient && state.hosts[recipe.id]?.biliConfiguredByUs));
|
|
150
|
+
const support = hostSupport(recipe);
|
|
151
|
+
return {
|
|
152
|
+
id: recipe.id,
|
|
153
|
+
name: recipe.name,
|
|
154
|
+
kind: recipe.kind,
|
|
155
|
+
installed,
|
|
156
|
+
detectedAt,
|
|
157
|
+
version,
|
|
158
|
+
support,
|
|
159
|
+
risk: recipe.risk,
|
|
160
|
+
detail: recipe.detail,
|
|
161
|
+
requiresRestart: recipe.requiresRestart,
|
|
162
|
+
rtkSupported,
|
|
163
|
+
rtkConfigured,
|
|
164
|
+
biliMode,
|
|
165
|
+
biliClient,
|
|
166
|
+
biliConfigured,
|
|
167
|
+
selectedByDefault: !!(installed && support === 'auto' && recipe.defaultSelected !== false),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export async function scanOptimizer() {
|
|
171
|
+
const state = loadOptimizerState();
|
|
172
|
+
const [rtk, bili] = await Promise.all([rtkEngineStatus(), biliEngineStatus()]);
|
|
173
|
+
const list = bili.installed ? await biliPluginList() : { ok: false, out: '', err: '' };
|
|
174
|
+
const hosts = await Promise.all(HOST_RECIPES.map((r) => detectHost(r, list.out, state)));
|
|
175
|
+
const installedHosts = hosts.filter((h) => h.installed);
|
|
176
|
+
const summary = {
|
|
177
|
+
detected: installedHosts.length,
|
|
178
|
+
auto: installedHosts.filter((h) => h.support === 'auto').length,
|
|
179
|
+
assisted: installedHosts.filter((h) => h.support === 'assisted').length,
|
|
180
|
+
unsupported: installedHosts.filter((h) => h.support === 'unsupported').length,
|
|
181
|
+
selected: installedHosts.filter((h) => h.selectedByDefault).length,
|
|
182
|
+
};
|
|
183
|
+
state.lastScanAt = Date.now();
|
|
184
|
+
saveOptimizerState(state);
|
|
185
|
+
return {
|
|
186
|
+
generatedAt: Date.now(),
|
|
187
|
+
engines: [rtk, bili],
|
|
188
|
+
hosts,
|
|
189
|
+
summary,
|
|
190
|
+
managedHostIds: Object.keys(state.hosts),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function stepId(parts) {
|
|
194
|
+
return parts.join(':') + ':' + crypto.randomBytes(3).toString('hex');
|
|
195
|
+
}
|
|
196
|
+
function configureRtkStep(host, agent) {
|
|
197
|
+
return {
|
|
198
|
+
id: stepId(['rtk', host.id]),
|
|
199
|
+
engine: 'rtk',
|
|
200
|
+
hostId: host.id,
|
|
201
|
+
kind: 'configure-host',
|
|
202
|
+
title: `接入 ${host.name} 的 RTK hook`,
|
|
203
|
+
detail: `执行 rtk init,并让 ${host.name} 的工具输出先进压缩层。`,
|
|
204
|
+
risk: 'low',
|
|
205
|
+
requiresRestart: !!host.requiresRestart,
|
|
206
|
+
command: `rtk ${rtkInitArgs(agent).join(' ')}`,
|
|
207
|
+
state: 'pending',
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function configureBiliStep(host, client) {
|
|
211
|
+
return {
|
|
212
|
+
id: stepId(['bili', host.id]),
|
|
213
|
+
engine: 'bili',
|
|
214
|
+
hostId: host.id,
|
|
215
|
+
kind: 'configure-host',
|
|
216
|
+
title: `接入 ${host.name} 的 billion-context`,
|
|
217
|
+
detail: `执行 bili plugin install ${client},由 bili 管理会话压缩。`,
|
|
218
|
+
risk: 'medium',
|
|
219
|
+
requiresRestart: !!host.requiresRestart,
|
|
220
|
+
command: `bili plugin install ${client}`,
|
|
221
|
+
state: 'pending',
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
function manualStep(host, detail) {
|
|
225
|
+
return {
|
|
226
|
+
id: stepId(['manual', host.id]),
|
|
227
|
+
hostId: host.id,
|
|
228
|
+
kind: 'manual',
|
|
229
|
+
title: `${host.name} 需要手动启用`,
|
|
230
|
+
detail,
|
|
231
|
+
risk: host.risk,
|
|
232
|
+
requiresRestart: !!host.requiresRestart,
|
|
233
|
+
state: 'pending',
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
export function buildOptimizerPlan(scan, profile, hostIds) {
|
|
237
|
+
const selectedIds = hostIds?.length
|
|
238
|
+
? hostIds
|
|
239
|
+
: scan.hosts.filter((h) => h.selectedByDefault).map((h) => h.id);
|
|
240
|
+
const selected = new Set(selectedIds);
|
|
241
|
+
const hosts = scan.hosts.filter((h) => h.installed && selected.has(h.id) && h.support !== 'unsupported');
|
|
242
|
+
const steps = [];
|
|
243
|
+
const rtk = scan.engines.find((e) => e.id === 'rtk');
|
|
244
|
+
const bili = scan.engines.find((e) => e.id === 'bili');
|
|
245
|
+
const needRtk = hosts.some((h) => h.rtkSupported && !h.rtkConfigured);
|
|
246
|
+
const needBili = hosts.some((h) => h.biliMode === 'plugin' && !h.biliConfigured);
|
|
247
|
+
if (needRtk && !rtk.installed) {
|
|
248
|
+
steps.push({
|
|
249
|
+
id: stepId(['install', 'rtk']),
|
|
250
|
+
engine: 'rtk',
|
|
251
|
+
kind: 'install-engine',
|
|
252
|
+
title: '安装 RTK',
|
|
253
|
+
detail: '安装带压缩引擎的 RTK;外部已有版本时只使用、不重复安装。',
|
|
254
|
+
risk: 'low',
|
|
255
|
+
state: 'pending',
|
|
256
|
+
command: process.platform === 'win32' ? 'winget install rtk-ai.rtk' : 'brew install rtk',
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
else if (needRtk && !rtk.usable) {
|
|
260
|
+
steps.push({
|
|
261
|
+
id: stepId(['manual', 'rtk-oss']),
|
|
262
|
+
engine: 'rtk',
|
|
263
|
+
kind: 'manual',
|
|
264
|
+
title: '先处理 rtk-oss',
|
|
265
|
+
detail: '检测到 rtk-oss(不含压缩引擎),与完整版互斥;请先卸载后再执行计划。',
|
|
266
|
+
risk: 'medium',
|
|
267
|
+
state: 'pending',
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
if (needBili && !bili.installed) {
|
|
271
|
+
steps.push({
|
|
272
|
+
id: stepId(['install', 'bili']),
|
|
273
|
+
engine: 'bili',
|
|
274
|
+
kind: 'install-engine',
|
|
275
|
+
title: '安装 billion-context',
|
|
276
|
+
detail: nodeSupportsBili()
|
|
277
|
+
? '通过 npm 安装;代理由 bili 自己管理,token-pilot 不接管请求内容。'
|
|
278
|
+
: `bili 需要 Node.js >= 20,当前为 ${process.version};计划执行时会明确失败,不会假装成功。`,
|
|
279
|
+
risk: 'medium',
|
|
280
|
+
state: 'pending',
|
|
281
|
+
command: process.platform === 'win32'
|
|
282
|
+
? 'npm install -g billion-context'
|
|
283
|
+
: 'npm install -g billion-context --prefix=~/.local',
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
for (const h of hosts) {
|
|
287
|
+
const recipe = HOST_RECIPES.find((r) => r.id === h.id);
|
|
288
|
+
if (!recipe)
|
|
289
|
+
continue;
|
|
290
|
+
if (h.rtkSupported && !h.rtkConfigured && recipe.rtkAgent) {
|
|
291
|
+
steps.push(configureRtkStep(h, recipe.rtkAgent));
|
|
292
|
+
}
|
|
293
|
+
if (h.biliMode === 'plugin' && !h.biliConfigured && h.biliClient) {
|
|
294
|
+
steps.push(configureBiliStep(h, h.biliClient));
|
|
295
|
+
}
|
|
296
|
+
if (profile === 'deep' && (h.biliMode === 'launcher' || h.biliMode === 'assisted')) {
|
|
297
|
+
steps.push(manualStep(h, h.biliMode === 'launcher'
|
|
298
|
+
? `完整 bili 压缩需要用 \`bili ${h.biliClient ?? '<client>'}\` 启动;不会偷偷改你的登录链路。`
|
|
299
|
+
: (recipe.bili?.detail ?? '该宿主需要应用级代理或自定义 provider,当前不自动写系统代理。')));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (hosts.length === 0) {
|
|
303
|
+
steps.push({
|
|
304
|
+
id: stepId(['empty']),
|
|
305
|
+
kind: 'manual',
|
|
306
|
+
title: '没有可自动适配的宿主',
|
|
307
|
+
detail: '先安装/打开一个受支持的 Agent 或 CLI,再重新扫描。',
|
|
308
|
+
risk: 'low',
|
|
309
|
+
state: 'pending',
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
const summary = {
|
|
313
|
+
...scan.summary,
|
|
314
|
+
selected: hosts.length,
|
|
315
|
+
};
|
|
316
|
+
return {
|
|
317
|
+
id: `plan-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`,
|
|
318
|
+
createdAt: Date.now(),
|
|
319
|
+
profile,
|
|
320
|
+
hostIds: hosts.map((h) => h.id),
|
|
321
|
+
engines: scan.engines,
|
|
322
|
+
hosts: scan.hosts,
|
|
323
|
+
steps,
|
|
324
|
+
summary,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
async function snapshotHostFiles(hostId, tx) {
|
|
328
|
+
const recipe = HOST_RECIPES.find((r) => r.id === hostId);
|
|
329
|
+
if (!recipe)
|
|
330
|
+
return [];
|
|
331
|
+
const out = [];
|
|
332
|
+
for (const p of recipe.configPaths ?? []) {
|
|
333
|
+
out.push(...snapshotPath(tx, expandHome(p)));
|
|
334
|
+
}
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
function riskOrder(r) {
|
|
338
|
+
return r === 'low' ? 0 : r === 'medium' ? 1 : 2;
|
|
339
|
+
}
|
|
340
|
+
export async function applyOptimizerPlan(plan) {
|
|
341
|
+
const state = loadOptimizerState();
|
|
342
|
+
const tx = beginTransaction(`apply ${plan.id}`);
|
|
343
|
+
const hostFiles = new Map();
|
|
344
|
+
const originalHosts = new Map();
|
|
345
|
+
const successes = new Map();
|
|
346
|
+
let engineFailure = false;
|
|
347
|
+
const sorted = [...plan.steps].sort((a, b) => {
|
|
348
|
+
if (a.kind === 'install-engine' && b.kind !== 'install-engine')
|
|
349
|
+
return -1;
|
|
350
|
+
if (b.kind === 'install-engine' && a.kind !== 'install-engine')
|
|
351
|
+
return 1;
|
|
352
|
+
return riskOrder(a.risk) - riskOrder(b.risk);
|
|
353
|
+
});
|
|
354
|
+
for (const step of sorted) {
|
|
355
|
+
if (step.kind === 'manual') {
|
|
356
|
+
step.state = 'skipped';
|
|
357
|
+
step.message = step.detail;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
step.state = 'running';
|
|
361
|
+
try {
|
|
362
|
+
if (step.kind === 'install-engine' && step.engine === 'rtk') {
|
|
363
|
+
const before = await rtkStatus();
|
|
364
|
+
const r = await installRtkBinary();
|
|
365
|
+
if (!r.ok)
|
|
366
|
+
throw new Error(r.message);
|
|
367
|
+
const after = await rtkStatus();
|
|
368
|
+
state.engines.rtk = {
|
|
369
|
+
installedByUs: before.source === 'ours' || !before.installed,
|
|
370
|
+
version: after.version,
|
|
371
|
+
installedAt: Date.now(),
|
|
372
|
+
method: before.installed ? 'existing' : 'auto',
|
|
373
|
+
};
|
|
374
|
+
step.state = 'ok';
|
|
375
|
+
step.message = r.message;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (step.kind === 'install-engine' && step.engine === 'bili') {
|
|
379
|
+
const before = await biliStatus();
|
|
380
|
+
const r = await installBili();
|
|
381
|
+
if (!r.ok)
|
|
382
|
+
throw new Error(r.message);
|
|
383
|
+
state.engines.bili = { installedByUs: !before.installed, installedAt: Date.now(), method: 'npm' };
|
|
384
|
+
step.state = 'ok';
|
|
385
|
+
step.message = r.message;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (step.kind === 'configure-host' && step.hostId) {
|
|
389
|
+
if (!originalHosts.has(step.hostId)) {
|
|
390
|
+
const prev = state.hosts[step.hostId];
|
|
391
|
+
originalHosts.set(step.hostId, prev ? JSON.parse(JSON.stringify(prev)) : undefined);
|
|
392
|
+
}
|
|
393
|
+
if (!hostFiles.has(step.hostId)) {
|
|
394
|
+
hostFiles.set(step.hostId, await snapshotHostFiles(step.hostId, tx));
|
|
395
|
+
}
|
|
396
|
+
const recipe = HOST_RECIPES.find((r) => r.id === step.hostId);
|
|
397
|
+
if (!recipe)
|
|
398
|
+
throw new Error(`找不到宿主配方 ${step.hostId}`);
|
|
399
|
+
if (step.engine === 'rtk' && recipe.rtkAgent) {
|
|
400
|
+
const r = await configureRtkAgent(recipe.rtkAgent);
|
|
401
|
+
if (!r.ok)
|
|
402
|
+
throw new Error(r.message);
|
|
403
|
+
successes.set(step.hostId, { ...(successes.get(step.hostId) ?? {}), rtk: true });
|
|
404
|
+
state.hosts[step.hostId] = {
|
|
405
|
+
...(state.hosts[step.hostId] ?? {
|
|
406
|
+
id: step.hostId,
|
|
407
|
+
configuredAt: Date.now(),
|
|
408
|
+
configPaths: [],
|
|
409
|
+
}),
|
|
410
|
+
rtkAgent: recipe.rtkAgent,
|
|
411
|
+
rtkConfiguredByUs: true,
|
|
412
|
+
configPaths: recipe.configPaths ?? [],
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
else if (step.engine === 'bili' && recipe.bili?.client) {
|
|
416
|
+
const r = await biliPluginInstall(recipe.bili.client);
|
|
417
|
+
if (!r.ok)
|
|
418
|
+
throw new Error(r.message);
|
|
419
|
+
successes.set(step.hostId, { ...(successes.get(step.hostId) ?? {}), bili: true });
|
|
420
|
+
state.hosts[step.hostId] = {
|
|
421
|
+
...(state.hosts[step.hostId] ?? {
|
|
422
|
+
id: step.hostId,
|
|
423
|
+
configuredAt: Date.now(),
|
|
424
|
+
configPaths: [],
|
|
425
|
+
}),
|
|
426
|
+
biliClient: recipe.bili.client,
|
|
427
|
+
biliMode: recipe.bili.mode,
|
|
428
|
+
biliConfiguredByUs: true,
|
|
429
|
+
configPaths: recipe.configPaths ?? [],
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
throw new Error(`宿主 ${step.hostId} 没有 ${step.engine} 的接入配方`);
|
|
434
|
+
}
|
|
435
|
+
step.state = 'ok';
|
|
436
|
+
step.message = `已接入 ${recipe.name}`;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
step.state = 'ok';
|
|
440
|
+
step.message = '无需操作';
|
|
441
|
+
}
|
|
442
|
+
catch (e) {
|
|
443
|
+
step.state = 'failed';
|
|
444
|
+
step.message = e instanceof Error ? e.message : String(e);
|
|
445
|
+
if (step.kind === 'install-engine') {
|
|
446
|
+
engineFailure = true;
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
449
|
+
const files = step.hostId ? hostFiles.get(step.hostId) : undefined;
|
|
450
|
+
if (step.hostId) {
|
|
451
|
+
const prev = originalHosts.get(step.hostId);
|
|
452
|
+
if (prev)
|
|
453
|
+
state.hosts[step.hostId] = prev;
|
|
454
|
+
else
|
|
455
|
+
delete state.hosts[step.hostId];
|
|
456
|
+
}
|
|
457
|
+
if (files?.length) {
|
|
458
|
+
captureAfterHashesFor(files);
|
|
459
|
+
const r = rollbackTransaction({ ...tx, files });
|
|
460
|
+
step.message += r.conflicts.length ? `;有 ${r.conflicts.length} 个文件被用户改动,已跳过覆盖` : ';已回滚该宿主配置';
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (engineFailure) {
|
|
465
|
+
captureAfterHashes(tx);
|
|
466
|
+
rollbackTransaction(tx);
|
|
467
|
+
scanAndPersist(state);
|
|
468
|
+
return {
|
|
469
|
+
ok: false,
|
|
470
|
+
planId: plan.id,
|
|
471
|
+
message: '引擎安装失败,整份计划已停止;未完成的宿主没有写入。',
|
|
472
|
+
steps: plan.steps,
|
|
473
|
+
scan: await scanOptimizer(),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
captureAfterHashes(tx);
|
|
477
|
+
state.transactions = [...(state.transactions ?? []), tx].slice(-20);
|
|
478
|
+
const finalRtk = await rtkStatus();
|
|
479
|
+
state.engines.rtk = {
|
|
480
|
+
...(state.engines.rtk ?? {}),
|
|
481
|
+
installedByUs: finalRtk.source === 'ours',
|
|
482
|
+
version: finalRtk.version || state.engines.rtk?.version,
|
|
483
|
+
installedAt: state.engines.rtk?.installedAt,
|
|
484
|
+
method: state.engines.rtk?.method,
|
|
485
|
+
};
|
|
486
|
+
state.engines.bili = state.engines.bili ?? { installedByUs: false };
|
|
487
|
+
saveOptimizerState(state);
|
|
488
|
+
const failed = plan.steps.filter((s) => s.state === 'failed');
|
|
489
|
+
const ok = plan.steps.filter((s) => s.state === 'ok');
|
|
490
|
+
if (failed.length === 0 && ok.length > 0) {
|
|
491
|
+
for (const h of successes.keys()) {
|
|
492
|
+
const rec = state.hosts[h];
|
|
493
|
+
if (rec)
|
|
494
|
+
rec.configuredAt = Date.now();
|
|
495
|
+
}
|
|
496
|
+
saveOptimizerState(state);
|
|
497
|
+
}
|
|
498
|
+
return {
|
|
499
|
+
ok: failed.length === 0 && ok.length > 0,
|
|
500
|
+
planId: plan.id,
|
|
501
|
+
message: failed.length > 0
|
|
502
|
+
? `${failed.length} 个步骤失败,已按宿主回滚;${ok.length} 个步骤成功。`
|
|
503
|
+
: ok.length > 0
|
|
504
|
+
? `已接入 ${new Set(ok.map((s) => s.hostId).filter(Boolean)).size} 个宿主;重启对应应用后生效。`
|
|
505
|
+
: '没有可执行的自动步骤。',
|
|
506
|
+
steps: plan.steps,
|
|
507
|
+
scan: await scanOptimizer(),
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
function scanAndPersist(state) {
|
|
511
|
+
state.lastScanAt = Date.now();
|
|
512
|
+
saveOptimizerState(state);
|
|
513
|
+
}
|
|
514
|
+
export async function rollbackOptimizer() {
|
|
515
|
+
const state = loadOptimizerState();
|
|
516
|
+
const steps = [];
|
|
517
|
+
for (const rec of Object.values(state.hosts)) {
|
|
518
|
+
if (rec.biliConfiguredByUs && rec.biliClient && rec.biliMode === 'plugin') {
|
|
519
|
+
const r = await biliPluginRemove(rec.biliClient);
|
|
520
|
+
steps.push({
|
|
521
|
+
id: stepId(['rollback', 'bili', rec.id]),
|
|
522
|
+
engine: 'bili',
|
|
523
|
+
hostId: rec.id,
|
|
524
|
+
kind: 'configure-host',
|
|
525
|
+
title: `移除 ${rec.id} 的 bili 插件`,
|
|
526
|
+
detail: r.message,
|
|
527
|
+
risk: 'medium',
|
|
528
|
+
state: r.ok ? 'ok' : 'failed',
|
|
529
|
+
message: r.message,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
if (rec.rtkConfiguredByUs && rec.rtkAgent) {
|
|
533
|
+
const r = await unconfigureRtkAgent(rec.rtkAgent);
|
|
534
|
+
steps.push({
|
|
535
|
+
id: stepId(['rollback', 'rtk', rec.id]),
|
|
536
|
+
engine: 'rtk',
|
|
537
|
+
hostId: rec.id,
|
|
538
|
+
kind: 'configure-host',
|
|
539
|
+
title: `移除 ${rec.id} 的 RTK hook`,
|
|
540
|
+
detail: r.message,
|
|
541
|
+
risk: 'low',
|
|
542
|
+
state: r.ok ? 'ok' : 'failed',
|
|
543
|
+
message: r.message,
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
for (const tx of [...(state.transactions ?? [])].reverse()) {
|
|
548
|
+
const r = rollbackTransaction(tx);
|
|
549
|
+
steps.push({
|
|
550
|
+
id: stepId(['rollback', 'files', tx.id]),
|
|
551
|
+
kind: 'verify',
|
|
552
|
+
title: `恢复配置快照 ${tx.id}`,
|
|
553
|
+
detail: r.conflicts.length
|
|
554
|
+
? `${r.restored.length} 个文件已恢复,${r.conflicts.length} 个因用户改动跳过`
|
|
555
|
+
: `${r.restored.length} 个文件已恢复`,
|
|
556
|
+
risk: 'low',
|
|
557
|
+
state: r.errors.length ? 'failed' : 'ok',
|
|
558
|
+
message: [...r.conflicts.map((p) => `冲突:${p}`), ...r.errors].slice(0, 6).join(' / '),
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
state.hosts = {};
|
|
562
|
+
state.transactions = [];
|
|
563
|
+
saveOptimizerState(state);
|
|
564
|
+
const failed = steps.filter((s) => s.state === 'failed');
|
|
565
|
+
return {
|
|
566
|
+
ok: failed.length === 0,
|
|
567
|
+
message: failed.length ? `回滚完成,但有 ${failed.length} 个步骤失败,请查看详情。` : '已恢复接入前的配置。',
|
|
568
|
+
steps,
|
|
569
|
+
scan: await scanOptimizer(),
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
/** 供服务端 job 使用:从当前扫描重新生成计划,避免前端提交过期计划。 */
|
|
573
|
+
export async function applyOptimizerSelection(profile, hostIds) {
|
|
574
|
+
const scan = await scanOptimizer();
|
|
575
|
+
const plan = buildOptimizerPlan(scan, profile, hostIds);
|
|
576
|
+
return applyOptimizerPlan(plan);
|
|
577
|
+
}
|
|
578
|
+
export function jobFromApply(id, plan) {
|
|
579
|
+
return {
|
|
580
|
+
id,
|
|
581
|
+
kind: 'apply',
|
|
582
|
+
status: 'running',
|
|
583
|
+
startedAt: Date.now(),
|
|
584
|
+
message: '正在执行接入计划…',
|
|
585
|
+
plan,
|
|
586
|
+
steps: plan.steps,
|
|
587
|
+
};
|
|
588
|
+
}
|