@wenaixi/searchfuse 0.0.0-stage → 0.1.2

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/main.js ADDED
@@ -0,0 +1,1414 @@
1
+ #!/usr/bin/env node
2
+ import { A as findEngine, C as loadConfigFile, D as ROLE_PREFERENCE, E as setConfigValue, F as commandOnPath, M as registerSearxngCleanup, N as grokAuthFile, O as allEngines, P as splitApiKeys, S as isPlainObject, T as renderEffectiveConfig, _ as currentConfigPath, a as clearAllCooldowns, b as exposeOf, c as loadCooldownState, d as ROLES, f as aggregateDeadlineMs, g as cooldownEnabled, h as chosenEngine, i as buildCooldownController, j as listEngines, k as enginesForRole, l as parseCooldownStateKey, m as allowsPrivateNetwork, n as waitForPendingKills, o as coolingEntry, p as aggregateMode, s as currentStatePath, t as runSearch, u as CONFIG_PATH, v as effectiveMcp, w as migrateLegacyDir, x as initConfigFile, y as engineSettings } from "./search-DeT416xs.js";
3
+ import { r as isServerNameValid, t as McpConnection } from "./protocol-ClnjMnGV.js";
4
+ import { a as ensureServeToken, c as identityOf, o as runtimePath, r as findRunningServe, s as startServe, t as discoverServe } from "./serveEnsure-BTj9IifL.js";
5
+ import { Command } from "commander";
6
+ import * as fs$1 from "fs";
7
+ import * as os from "os";
8
+ import * as path from "path";
9
+ import { fileURLToPath } from "url";
10
+ import * as os$1 from "node:os";
11
+ import * as path$1 from "node:path";
12
+ import * as fs from "node:fs";
13
+ import * as readline from "readline";
14
+ // src/doctor.ts
15
+ /** 这个构建承诺的 Node 版本下限。与 package.json 的 engines 字段保持一致。 */
16
+ var MIN_NODE = "22.19.0";
17
+ var ROLE_JOB = {
18
+ search: "search the web",
19
+ fetch: "fetch a page",
20
+ social: "search X"
21
+ };
22
+ var INSTALL_AGY = "curl -fsSL https://antigravity.google/cli/install.sh | bash && agy";
23
+ var INSTALL_GROK = "curl -fsSL https://x.ai/cli/install.sh | bash && grok";
24
+ function configuredApiKeys(fromEnv, fromFile) {
25
+ const envKeys = splitApiKeys(fromEnv);
26
+ if (envKeys.length > 0) return {
27
+ count: envKeys.length,
28
+ source: "env"
29
+ };
30
+ const fileKeys = splitApiKeys(fromFile);
31
+ return {
32
+ count: fileKeys.length,
33
+ source: fileKeys.length > 0 ? "file" : null
34
+ };
35
+ }
36
+ function apiKeyPresentReason(count, source) {
37
+ return `API key present (${count} ${count === 1 ? "key" : "keys"}, from ${source})`;
38
+ }
39
+ /** 比较两个点分数字版本号。返回负数、零或正数。 */
40
+ function compareVersions(a, b) {
41
+ const pa = a.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
42
+ const pb = b.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
43
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
44
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
45
+ if (diff !== 0) return diff;
46
+ }
47
+ return 0;
48
+ }
49
+ /** 诊断单个引擎:它在本机能否使用,不能的话怎么修。 */
50
+ function diagnoseEngine(engine, config, env, role) {
51
+ const settings = engineSettings(engine.name, config, env);
52
+ const enabled = settings.enabled !== false;
53
+ if (engine.name === "antigravity-cli") {
54
+ const bin = settings.bin || "agy";
55
+ const ready = commandOnPath(bin, env);
56
+ return {
57
+ engine: engine.name,
58
+ enabled,
59
+ ready,
60
+ reason: ready ? `binary "${bin}" found and runnable` : `binary "${bin}" not found on PATH (sign-in also required, once)`,
61
+ ...ready ? {} : { fix: INSTALL_AGY }
62
+ };
63
+ }
64
+ if (engine.name === "tavily") {
65
+ const { count, source: keySource } = configuredApiKeys(env.TAVILY_API_KEY, config.engines?.tavily?.apiKey);
66
+ const ready = count > 0;
67
+ return {
68
+ engine: engine.name,
69
+ enabled,
70
+ ready,
71
+ keySource,
72
+ reason: keySource ? apiKeyPresentReason(count, keySource) : "no API key (not in TAVILY_API_KEY or the config file)",
73
+ ...ready ? {} : { fix: "searchfuse config set tavily.apiKey <key>" }
74
+ };
75
+ }
76
+ if (engine.name === "exa") {
77
+ const { count, source: keySource } = configuredApiKeys(env.EXA_API_KEY, config.engines?.exa?.apiKey);
78
+ const ready = count > 0;
79
+ return {
80
+ engine: engine.name,
81
+ enabled,
82
+ ready,
83
+ keySource,
84
+ reason: keySource ? apiKeyPresentReason(count, keySource) : "no API key (not in EXA_API_KEY or the config file)",
85
+ ...ready ? {} : { fix: "searchfuse config set exa.apiKey <key>" }
86
+ };
87
+ }
88
+ if (engine.name === "keenable") {
89
+ const { count, source: keySource } = configuredApiKeys(env.KEENABLE_API_KEY, config.engines?.keenable?.apiKey);
90
+ return {
91
+ engine: engine.name,
92
+ enabled,
93
+ ready: true,
94
+ keySource,
95
+ reason: keySource ? apiKeyPresentReason(count, keySource) : "keyless: works with no key and no signup (1,000 requests/hour, shared by everyone on this IP). Set a free key for 100,000 requests/month of your own."
96
+ };
97
+ }
98
+ if (engine.name === "youcom") return {
99
+ engine: engine.name,
100
+ enabled,
101
+ ready: true,
102
+ reason: "keyless: works with no key and no signup (100 searches/day, shared by everyone on this IP)."
103
+ };
104
+ if (engine.name === "firecrawl") {
105
+ const { count, source: keySource } = configuredApiKeys(env.FIRECRAWL_API_KEY, config.engines?.firecrawl?.apiKey);
106
+ const configuredEngine = chosenEngine(config);
107
+ const keylessFetch = settings.keylessFetch === void 0 || settings.keylessFetch === true || configuredEngine !== void 0 && findEngine(configuredEngine)?.name === "firecrawl";
108
+ if (role === "search") return {
109
+ engine: engine.name,
110
+ enabled,
111
+ ready: true,
112
+ keySource,
113
+ reason: keySource ? apiKeyPresentReason(count, keySource) : "keyless: works with no key and no signup (Firecrawl grants 1,000 free credits/month, metered per IP per day). Set a free key for your own quota."
114
+ };
115
+ const ready = Boolean(keySource || keylessFetch);
116
+ return {
117
+ engine: engine.name,
118
+ enabled,
119
+ ready,
120
+ keySource,
121
+ reason: keySource ? apiKeyPresentReason(count, keySource) : keylessFetch ? "keyless fetch (default): public pages are read by a cloud browser, no key or signup needed. Opt out with: searchfuse config set firecrawl.keylessFetch false" : "keyless fetch is switched off (firecrawl.keylessFetch false), so Firecrawl is excluded from automatic page fetch.",
122
+ ...ready ? {} : { fix: "searchfuse config set firecrawl.keylessFetch true" }
123
+ };
124
+ }
125
+ if (engine.name === "grok-cli") {
126
+ const bin = settings.bin || "grok";
127
+ const binPresent = commandOnPath(bin, env);
128
+ const authPath = grokAuthFile();
129
+ const authPresent = fs$1.existsSync(authPath);
130
+ const ready = binPresent && authPresent;
131
+ const parts = [];
132
+ parts.push(binPresent ? `binary "${bin}" found` : `binary "${bin}" not found on PATH`);
133
+ parts.push(authPresent ? `login file ${authPath} present` : `login file ${authPath} missing`);
134
+ return {
135
+ engine: engine.name,
136
+ enabled,
137
+ ready,
138
+ reason: parts.join("; "),
139
+ ...ready ? {} : { fix: INSTALL_GROK }
140
+ };
141
+ }
142
+ const ready = engine.isAvailable(settings, env, role);
143
+ return {
144
+ engine: engine.name,
145
+ enabled,
146
+ ready,
147
+ reason: ready ? "built in, needs nothing installed" : engine.requirement
148
+ };
149
+ }
150
+ /** 某角色的候选引擎,按解析顺序排列,并已去重。 */
151
+ function candidatesForRole(role, config) {
152
+ const names = [];
153
+ const configured = chosenEngine(config);
154
+ if (configured) {
155
+ const engine = findEngine(configured);
156
+ if (engine && engine.roles.includes(role)) names.push(engine.name);
157
+ }
158
+ for (const name of ROLE_PREFERENCE[role]) names.push(name);
159
+ for (const engine of enginesForRole(role)) if (!names.includes(engine.name)) names.push(engine.name);
160
+ const seen = /* @__PURE__ */ new Set();
161
+ const engines = [];
162
+ for (const name of names) {
163
+ const engine = findEngine(name);
164
+ if (engine && !seen.has(engine.name)) {
165
+ seen.add(engine.name);
166
+ engines.push(engine);
167
+ }
168
+ }
169
+ return engines;
170
+ }
171
+ /** 此刻正在冷却的引擎,以及开关本身是否打开。 */
172
+ function diagnoseCooldown(config, statePath, now) {
173
+ if (!cooldownEnabled(config)) return {
174
+ enabled: false,
175
+ statePath,
176
+ engines: []
177
+ };
178
+ const state = loadCooldownState(statePath);
179
+ const engines = [];
180
+ for (const stateKey of Object.keys(state.engineCooldowns)) {
181
+ const target = parseCooldownStateKey(stateKey);
182
+ const entry = coolingEntry(state, target.engine, now, target.keyIndex);
183
+ if (entry) engines.push({
184
+ engine: target.engine,
185
+ ...target.keyIndex === void 0 ? {} : { keyIndex: target.keyIndex },
186
+ until: entry.until,
187
+ remaining: formatRemaining(Date.parse(entry.until) - now.getTime()),
188
+ reason: entry.reason.split("\n")[0].slice(0, 120)
189
+ });
190
+ }
191
+ engines.sort((a, b) => a.engine.localeCompare(b.engine) || (a.keyIndex ?? -1) - (b.keyIndex ?? -1));
192
+ return {
193
+ enabled: true,
194
+ statePath,
195
+ engines
196
+ };
197
+ }
198
+ function formatRemaining(ms) {
199
+ if (ms <= 0) return "0m";
200
+ const totalMinutes = Math.round(ms / 6e4);
201
+ const hours = Math.floor(totalMinutes / 60);
202
+ const minutes = totalMinutes % 60;
203
+ return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
204
+ }
205
+ function runDoctor(options = {}) {
206
+ const env = options.env ?? process.env;
207
+ const nodeVersion = options.nodeVersion ?? process.versions.node;
208
+ const configPath = options.configPath ?? currentConfigPath();
209
+ const statePath = options.statePath ?? currentStatePath();
210
+ const now = options.now ?? /* @__PURE__ */ new Date();
211
+ let config = options.config ?? {};
212
+ let configProblem;
213
+ const exists = fs$1.existsSync(configPath);
214
+ let readable = !exists ? false : true;
215
+ let mode;
216
+ let permissionsOk = true;
217
+ if (options.config === void 0 && exists) {
218
+ try {
219
+ const bits = fs$1.statSync(configPath).mode & 511;
220
+ mode = bits.toString(8).padStart(3, "0");
221
+ permissionsOk = !(typeof process.getuid === "function") || (bits & 63) === 0;
222
+ } catch {}
223
+ try {
224
+ config = loadConfigFile(configPath);
225
+ } catch (error) {
226
+ readable = false;
227
+ configProblem = error instanceof Error ? error.message : String(error);
228
+ }
229
+ } else if (options.config === void 0) readable = false;
230
+ const ok = compareVersions(nodeVersion, MIN_NODE) >= 0;
231
+ const configuredName = chosenEngine(config);
232
+ let engineProblem;
233
+ if (configuredName && !findEngine(configuredName)) engineProblem = `"${configuredName}" is not a known engine, so search picks one automatically`;
234
+ const roles = ROLES.map((role) => {
235
+ const candidates = candidatesForRole(role, config).map((engine) => diagnoseEngine(engine, config, env, role));
236
+ const resolved = candidates.find((c) => c.enabled && c.ready)?.engine ?? null;
237
+ return {
238
+ role,
239
+ job: ROLE_JOB[role],
240
+ candidates,
241
+ resolved
242
+ };
243
+ });
244
+ const allowPrivate = allowsPrivateNetwork(config);
245
+ return {
246
+ node: {
247
+ version: nodeVersion,
248
+ minimum: MIN_NODE,
249
+ ok,
250
+ ...ok ? {} : { fix: `Upgrade Node to ${MIN_NODE} or newer.` }
251
+ },
252
+ engineChoice: {
253
+ value: configuredName ?? null,
254
+ source: configuredName ? "file" : "default",
255
+ ...engineProblem ? { problem: engineProblem } : {}
256
+ },
257
+ configFile: {
258
+ path: configPath,
259
+ exists,
260
+ ...mode ? { mode } : {},
261
+ permissionsOk,
262
+ ...permissionsOk ? {} : { note: `group/world can read this file. Run: chmod 600 ${configPath}` },
263
+ readable,
264
+ ...configProblem ? { problem: configProblem } : {}
265
+ },
266
+ allowPrivateNetwork: {
267
+ enabled: allowPrivate,
268
+ source: allowPrivate ? "file" : "default"
269
+ },
270
+ cooldown: diagnoseCooldown(config, statePath, now),
271
+ aggregate: diagnoseAggregate(config, env),
272
+ mcp: diagnoseMcp(config),
273
+ roles
274
+ };
275
+ }
276
+ /**
277
+ * 融合搜索会怎么跑。
278
+ *
279
+ * 每个搜索引擎都列出来,并说明它参与还是不参与——以及为什么。用户跑 doctor
280
+ * 想知道「为什么这个引擎没被用上」,只列参与者回答不了这个问题,而「没被用上」
281
+ * 在语义上有四种完全不同的成因:被关掉、只做独立工具、本机不可用、正在冷却。
282
+ * 这里能回答前三种;冷却属于运行时状态,由 cooldown 那一节负责。
283
+ */
284
+ function diagnoseAggregate(config, env) {
285
+ const participants = [];
286
+ for (const engine of allEngines()) {
287
+ if (!engine.roles.includes("search")) continue;
288
+ const settings = engineSettings(engine.name, config, env);
289
+ if (settings.enabled === false) {
290
+ participants.push({
291
+ engine: engine.name,
292
+ reason: "关闭(enabled: false)"
293
+ });
294
+ continue;
295
+ }
296
+ if (!exposeOf(settings).aggregate) {
297
+ participants.push({
298
+ engine: engine.name,
299
+ reason: "不参与融合(expose.aggregate: false)"
300
+ });
301
+ continue;
302
+ }
303
+ if (engine.execute === void 0) {
304
+ participants.push({
305
+ engine: engine.name,
306
+ reason: "进程内引擎之外(走链式路径)"
307
+ });
308
+ continue;
309
+ }
310
+ if (!engine.isAvailable(settings, env, "search")) {
311
+ participants.push({
312
+ engine: engine.name,
313
+ reason: "本机不可用(缺少密钥或命令)"
314
+ });
315
+ continue;
316
+ }
317
+ participants.push({
318
+ engine: engine.name,
319
+ reason: "参与融合"
320
+ });
321
+ }
322
+ return {
323
+ mode: aggregateMode(config),
324
+ deadlineMs: aggregateDeadlineMs(config),
325
+ participants
326
+ };
327
+ }
328
+ /**
329
+ * 配置文件里声明了哪些 MCP 服务端。
330
+ *
331
+ * 只说配置,不说连接结果:真实连接发生在宿主进程里,而 doctor 是另一个进程,
332
+ * 看不到那份 session。把两者混在一起会让一节「配置对不对」的诊断看起来像是在
333
+ * 回答「刚才连上没有」,而它做不到后者。键名契约在配置阶段就能判——它将成为
334
+ * 工具名的一部分,所以一个不合法的键等于一个永远注册不上的工具。
335
+ */
336
+ function diagnoseMcp(config) {
337
+ const servers = effectiveMcp(config);
338
+ const out = [];
339
+ for (const [key, raw] of Object.entries(servers)) {
340
+ if (!isPlainObject(raw)) {
341
+ out.push({
342
+ key,
343
+ url: null,
344
+ enabled: false,
345
+ problem: "条目不是一个对象"
346
+ });
347
+ continue;
348
+ }
349
+ const entry = {
350
+ key,
351
+ url: typeof raw.url === "string" ? raw.url : null,
352
+ enabled: raw.enabled !== false
353
+ };
354
+ if (!isServerNameValid(key)) entry.problem = "键名必须匹配 [A-Za-z0-9_-]{1,32}(它会成为工具名的一部分)";
355
+ else if (entry.url === null) entry.problem = "缺少 url";
356
+ out.push(entry);
357
+ }
358
+ return { servers: out };
359
+ }
360
+ /** 人类可读的报告。`--json` 则直接打印对象。 */
361
+ function formatDoctorReport(report) {
362
+ const lines = ["searchfuse doctor", ""];
363
+ lines.push("Node");
364
+ lines.push(` version: ${report.node.version}`);
365
+ lines.push(` minimum: ${report.node.minimum}`);
366
+ lines.push(` status: ${report.node.ok ? "OK" : "TOO OLD"}`);
367
+ if (report.node.fix) lines.push(` fix: ${report.node.fix}`);
368
+ lines.push("");
369
+ lines.push("Config");
370
+ const choice = report.engineChoice;
371
+ lines.push(` search engine: ${choice.value ? `${choice.value} (from config file)` : "(unset: automatic)"}`);
372
+ if (choice.problem) lines.push(` ! ${choice.problem}`);
373
+ const file = report.configFile;
374
+ if (!file.exists) lines.push(` file: ${file.path} (not present, running on defaults)`);
375
+ else if (file.problem) {
376
+ lines.push(` file: ${file.path} (unreadable)`);
377
+ lines.push(` ! ${file.problem}`);
378
+ } else {
379
+ lines.push(` file: ${file.path} (present, mode ${file.mode})`);
380
+ if (!file.permissionsOk && file.note) lines.push(` ! ${file.note}`);
381
+ }
382
+ lines.push(` allowPrivateNetwork: ${report.allowPrivateNetwork.enabled ? "on" : "off"} (${report.allowPrivateNetwork.source})`);
383
+ lines.push("");
384
+ lines.push("Cooldown");
385
+ if (!report.cooldown.enabled) lines.push(" switch: off (state not consulted)");
386
+ else if (report.cooldown.engines.length === 0) {
387
+ lines.push(" switch: on");
388
+ lines.push(" no engines are cooling right now");
389
+ } else {
390
+ lines.push(" switch: on");
391
+ for (const c of report.cooldown.engines) {
392
+ const label = c.keyIndex === void 0 ? c.engine : `${c.engine} key ${c.keyIndex + 1}`;
393
+ lines.push(` - ${label.padEnd(16)} cooling, ${c.remaining} left (until ${c.until})`);
394
+ if (c.reason) lines.push(` reason: ${c.reason}`);
395
+ }
396
+ }
397
+ lines.push("");
398
+ lines.push("Aggregate");
399
+ const agg = report.aggregate;
400
+ lines.push(` mode: ${agg.mode === "rrf" ? "rrf (concurrent fanout, fused)" : "chain (sequential fallback)"}`);
401
+ lines.push(` deadline: ${agg.deadlineMs} ms (whole run)`);
402
+ for (const p of agg.participants) {
403
+ const mark = p.reason === "参与融合" ? "FUSED " : "skip ";
404
+ lines.push(` - ${p.engine.padEnd(16)} ${mark} ${p.reason}`);
405
+ }
406
+ lines.push("");
407
+ lines.push("MCP");
408
+ if (report.mcp.servers.length === 0) lines.push(" no servers configured");
409
+ else {
410
+ for (const server of report.mcp.servers) {
411
+ const state = !server.enabled ? "off " : server.problem ? "INVALID" : "on ";
412
+ lines.push(` - ${server.key.padEnd(16)} ${state} ${server.url ?? "(no url)"}`);
413
+ if (server.problem) lines.push(` ! ${server.problem}`);
414
+ }
415
+ lines.push(" note: these are config facts only; live connection results appear in the plugin log");
416
+ }
417
+ lines.push("");
418
+ for (const role of report.roles) {
419
+ lines.push(`${role.role} (${role.job})`);
420
+ lines.push(` resolved: ${role.resolved ?? "(none available)"}`);
421
+ for (const c of role.candidates) {
422
+ const mark = !c.enabled ? "disabled" : c.ready ? "READY " : "not set";
423
+ lines.push(` - ${c.engine.padEnd(16)} ${mark} ${c.reason}`);
424
+ if (c.enabled && !c.ready && c.fix) lines.push(` fix: ${c.fix}`);
425
+ }
426
+ lines.push("");
427
+ }
428
+ return lines.join("\n").trimEnd();
429
+ }
430
+ // src/hosts.ts
431
+ /** omp 的配置文件位置。官方文档:用户级是 `~/.omp/agent/config.yml`。 */
432
+ function ompConfigPath() {
433
+ return path$1.join(os$1.homedir(), ".omp", "agent", "config.yml");
434
+ }
435
+ /** omp 的扩展目录。它从此处自动发现 `.ts` / `.js`。 */
436
+ function ompExtensionsDir() {
437
+ return path$1.join(os$1.homedir(), ".omp", "agent", "extensions");
438
+ }
439
+ /**
440
+ * 在 YAML 文本里把 `section.key` 设成某个标量值。
441
+ *
442
+ * 规则:
443
+ * - 段不存在 → 在文件末尾新增段
444
+ * - 段存在、键不存在 → 插到段内最后一个子键之后(保持缩进)
445
+ * - 段存在、键存在 → 原地替换那一行的值
446
+ * - 值为 `undefined` → 把那一行删掉(用于 disable)
447
+ *
448
+ * 只识别两空格缩进的子键,与 omp 自己的写法一致。这不是通用 YAML
449
+ * 处理器,只服务我们关心的那三个键。
450
+ */
451
+ function setYamlScalar(text, section, key, value) {
452
+ const lines = text.split(/\r?\n/);
453
+ const trailingEmpty = lines.length > 0 && lines[lines.length - 1] === "";
454
+ if (trailingEmpty) lines.pop();
455
+ const sectionStart = lines.findIndex((line) => new RegExp(`^${section}:\\s*$`).test(line));
456
+ const childPattern = /^\s{2}[^\s#][^:]*:/;
457
+ if (sectionStart === -1) {
458
+ if (value === void 0) return text;
459
+ lines.push(`${section}:`, ` ${key}: ${value}`);
460
+ return `${lines.join("\n")}${trailingEmpty ? "\n" : ""}`;
461
+ }
462
+ let sectionEnd = lines.length;
463
+ for (let i = sectionStart + 1; i < lines.length; i++) {
464
+ const line = lines[i];
465
+ if (line.length === 0 || line.startsWith("#") || /^\s/.test(line)) continue;
466
+ sectionEnd = i;
467
+ break;
468
+ }
469
+ const keyLine = lines.findIndex((line, index) => index > sectionStart && index < sectionEnd && new RegExp(`^\\s{2}${key}:`).test(line));
470
+ if (keyLine !== -1) {
471
+ if (value === void 0) lines.splice(keyLine, 1);
472
+ else lines[keyLine] = ` ${key}: ${value}`;
473
+ return `${lines.join("\n")}${trailingEmpty ? "\n" : ""}`;
474
+ }
475
+ if (value === void 0) return text;
476
+ let insertAt = sectionStart + 1;
477
+ for (let i = sectionStart + 1; i < sectionEnd; i++) if (childPattern.test(lines[i])) insertAt = i + 1;
478
+ lines.splice(insertAt, 0, ` ${key}: ${value}`);
479
+ return `${lines.join("\n")}${trailingEmpty ? "\n" : ""}`;
480
+ }
481
+ function decideWrite(file, next) {
482
+ let current;
483
+ try {
484
+ current = fs.readFileSync(file, "utf-8");
485
+ } catch {
486
+ current = void 0;
487
+ }
488
+ if (current === next) return { changed: false };
489
+ if (current !== void 0 && current !== "") {
490
+ const backup = `${file}.bak-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
491
+ fs.copyFileSync(file, backup);
492
+ return {
493
+ changed: true,
494
+ backup
495
+ };
496
+ }
497
+ return { changed: true };
498
+ }
499
+ /** 读 omp 配置;不存在时返回空串。 */
500
+ function readOmpConfig(file = ompConfigPath()) {
501
+ try {
502
+ return fs.readFileSync(file, "utf-8");
503
+ } catch {
504
+ return "";
505
+ }
506
+ }
507
+ /**
508
+ * 把 omp 接上或断开。
509
+ *
510
+ * 开启:写 `searxng.endpoint`、`searxng.token`、`modelRoles.web`,并清掉
511
+ * Basic 凭据(omp 里 Basic 优先于 Bearer,留着会让 token 被忽略)。
512
+ *
513
+ * 关闭:清掉 `searxng.endpoint`、`searxng.token`、Basic 凭据,并把
514
+ * `modelRoles.web` 写回 `web/public`——omp 没有任何运行时开关,不改写
515
+ * 就等于 `hosts.omp.enabled = false` 不起作用。
516
+ */
517
+ function syncOmp(wiring, file = ompConfigPath()) {
518
+ let text = readOmpConfig(file);
519
+ if (wiring === void 0) {
520
+ text = setYamlScalar(text, "searxng", "endpoint", void 0);
521
+ text = setYamlScalar(text, "searxng", "token", void 0);
522
+ text = setYamlScalar(text, "searxng", "basicUsername", void 0);
523
+ text = setYamlScalar(text, "searxng", "basicPassword", void 0);
524
+ text = setYamlScalar(text, "modelRoles", "web", "web/public");
525
+ } else {
526
+ text = setYamlScalar(text, "searxng", "endpoint", wiring.endpoint);
527
+ text = setYamlScalar(text, "searxng", "token", wiring.token);
528
+ text = setYamlScalar(text, "searxng", "basicUsername", void 0);
529
+ text = setYamlScalar(text, "searxng", "basicPassword", void 0);
530
+ text = setYamlScalar(text, "modelRoles", "web", wiring.webRole ?? "web/searxng");
531
+ }
532
+ const decision = decideWrite(file, text);
533
+ if (!decision.changed) return { changed: false };
534
+ fs.mkdirSync(path$1.dirname(file), { recursive: true });
535
+ fs.writeFileSync(file, text, "utf-8");
536
+ return decision.backup === void 0 ? { changed: true } : {
537
+ changed: true,
538
+ backup: decision.backup
539
+ };
540
+ }
541
+ /**
542
+ * 装 omp 扩展:把模板里的绝对路径替换掉,写到 omp 的扩展目录。
543
+ *
544
+ * 为什么是渲染而不是复制:扩展被复制到 `~/.omp/agent/extensions/` 之后,
545
+ * 它与本包的 `dist/` 已无相对关系,必须把绝对路径写进去才能拉起 kernel。
546
+ *
547
+ * `kernelPath` 用 kernel.js 而不是 serve.js:三家共享同一个聚合入口,
548
+ * 而 omp 侧靠扩展 spawn 它——不走 HTTP,于是随机端口不再是个问题。
549
+ */
550
+ function installOmpExtension(source, kernelPath) {
551
+ const escaped = JSON.stringify(kernelPath).slice(1, -1);
552
+ const rendered = source.replaceAll("__SEARCHFUSE_KERNEL_PATH__", escaped);
553
+ const dir = ompExtensionsDir();
554
+ fs.mkdirSync(dir, { recursive: true });
555
+ const target = path$1.join(dir, "searchfuse.ts");
556
+ fs.writeFileSync(target, rendered, "utf-8");
557
+ return target;
558
+ }
559
+ /**
560
+ * 卸载 omp 扩展:删掉 `hosts sync` 装进去的那一个文件。
561
+ *
562
+ * 为什么需要它:`hosts.omp.enabled = false` 若只写配置而不动扩展,omp
563
+ * 每次启动仍会加载扩展、仍会接管搜索——开关写着「关」,行为却是「开」。
564
+ * 只删我们自己的文件,别的扩展一个都不碰;返回是否真的删掉了。
565
+ */
566
+ function removeOmpExtension() {
567
+ const target = path$1.join(ompExtensionsDir(), "searchfuse.ts");
568
+ try {
569
+ fs.unlinkSync(target);
570
+ return true;
571
+ } catch {
572
+ return false;
573
+ }
574
+ }
575
+ function syncClaudeSettings(enabled, paths, file = claudeSettingsPath()) {
576
+ let raw = {};
577
+ let original = "";
578
+ try {
579
+ original = fs.readFileSync(file, "utf-8");
580
+ const parsed = JSON.parse(original);
581
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) raw = parsed;
582
+ } catch {
583
+ if (original !== "") throw new Error(`Cannot parse ${file}; refusing to overwrite it. Fix or delete the file first.`);
584
+ }
585
+ const hosts = raw.searchfuseHosts;
586
+ const existing = typeof hosts === "object" && hosts !== null && !Array.isArray(hosts) ? hosts : {};
587
+ const claude = typeof existing.claudeCode === "object" && existing.claudeCode !== null ? existing.claudeCode : {};
588
+ const nextClaude = {
589
+ ...claude,
590
+ enabled,
591
+ runtimePath: paths.runtimePath,
592
+ kernelPath: paths.kernelPath,
593
+ ...paths.identity === void 0 ? {} : {
594
+ fingerprint: paths.identity.fingerprint,
595
+ ports: paths.identity.ports
596
+ }
597
+ };
598
+ if (claude.enabled === nextClaude.enabled && claude.runtimePath === nextClaude.runtimePath && claude.kernelPath === nextClaude.kernelPath && JSON.stringify(claude.fingerprint) === JSON.stringify(nextClaude.fingerprint) && JSON.stringify(claude.ports) === JSON.stringify(nextClaude.ports)) return { changed: false };
599
+ raw.searchfuseHosts = {
600
+ ...existing,
601
+ claudeCode: nextClaude
602
+ };
603
+ const next = `${JSON.stringify(raw, null, 2)}\n`;
604
+ const decision = decideWrite(file, next);
605
+ if (!decision.changed) return { changed: false };
606
+ fs.mkdirSync(path$1.dirname(file), { recursive: true });
607
+ fs.writeFileSync(file, next, "utf-8");
608
+ return decision.backup === void 0 ? { changed: true } : {
609
+ changed: true,
610
+ backup: decision.backup
611
+ };
612
+ }
613
+ /** Claude Code 的用户级 settings。 */
614
+ function claudeSettingsPath() {
615
+ return path$1.join(os$1.homedir(), ".claude", "settings.json");
616
+ }
617
+ /**
618
+ * Claude Code mod 的用户级安装目录。
619
+ *
620
+ * `~/.claude/skills/<name>/` 会被当成 `@skills-dir` 插件自动加载,每个会话
621
+ * 生效,不需要 `--plugin-dir`。这是让「替换原生 WebSearch」常驻的唯一路径
622
+ * ——`--plugin-dir` 只活在带这个 flag 的那一次会话里。
623
+ */
624
+ function claudeSkillDir() {
625
+ return path$1.join(os$1.homedir(), ".claude", "skills", "searchfuse-mod");
626
+ }
627
+ /** mod 需要落地的文件,相对 `claude/` 源目录。顺序无关,只为打印好看。 */
628
+ var CLAUDE_MOD_FILES = [
629
+ "SKILL.md",
630
+ path$1.join(".claude-plugin", "plugin.json"),
631
+ path$1.join("hooks", "hooks.json"),
632
+ path$1.join("hooks", "register.ts"),
633
+ "tsconfig.json"
634
+ ];
635
+ /**
636
+ * 把仓库里的 `claude/` 同步到 `~/.claude/skills/searchfuse-mod/`。
637
+ *
638
+ * 为什么需要它:那份常驻安装是**副本**,不是软链。手工拷一次之后,仓库里
639
+ * `register.ts` 再改,技能目录那份不会跟着变——于是出现「代码已修、行为还是
640
+ * 旧的」,与 pnpm `file:` 依赖被复制成快照是同一类陷阱。让它由 `hosts sync`
641
+ * 管,改完源码跑一次就对齐。
642
+ *
643
+ * 写入粒度是**逐个文件**,不是整目录覆盖:技能目录里可能有用户自己加的
644
+ * 东西,整目录替换会把它们抹掉。内容相同的文件不重写,保持 mtime 不变。
645
+ *
646
+ * `enabled=false` 时**不删目录**,这与 omp 的处理不同,理由要看清:
647
+ * omp 没有任何运行时开关,留着扩展就仍在接管搜索,所以必须删;而 Claude
648
+ * 的 `register.ts` 每次 `tool.call` 都读 `searchfuseHosts.claudeCode.enabled`,
649
+ * 读到 false 就 `next(e)` 交回原生实现。删目录反而会让重新开启时静默失效
650
+ * (文件没了,开关写 true 也没人加载)。
651
+ */
652
+ function installClaudeSkill(sourceDir, targetDir = claudeSkillDir()) {
653
+ const installed = [];
654
+ for (const relative of CLAUDE_MOD_FILES) {
655
+ const from = path$1.join(sourceDir, relative);
656
+ const to = path$1.join(targetDir, relative);
657
+ let content;
658
+ try {
659
+ content = fs.readFileSync(from, "utf-8");
660
+ } catch {
661
+ continue;
662
+ }
663
+ let current;
664
+ try {
665
+ current = fs.readFileSync(to, "utf-8");
666
+ } catch {
667
+ current = void 0;
668
+ }
669
+ if (current === content) continue;
670
+ fs.mkdirSync(path$1.dirname(to), { recursive: true });
671
+ fs.writeFileSync(to, content, "utf-8");
672
+ installed.push(relative);
673
+ }
674
+ return {
675
+ changed: installed.length > 0,
676
+ installed
677
+ };
678
+ }
679
+ /** omp 的 MCP 配置文件。它从这里读,也兼容 `.mcp.json`。 */
680
+ function ompMcpPath() {
681
+ return path$1.join(os$1.homedir(), ".omp", "agent", "mcp.json");
682
+ }
683
+ /** 把 searchfuse 配置里的 `mcp` 段翻译成 omp 的 server 形状。 */
684
+ function toOmpServer(config) {
685
+ const transport = typeof config.transport === "string" ? config.transport : void 0;
686
+ const url = typeof config.url === "string" ? config.url : void 0;
687
+ if (transport === "stdio" && typeof config.command === "string") {
688
+ const args = Array.isArray(config.args) ? config.args.filter((arg) => typeof arg === "string") : [];
689
+ return args.length > 0 ? {
690
+ type: "stdio",
691
+ command: config.command,
692
+ args
693
+ } : {
694
+ type: "stdio",
695
+ command: config.command
696
+ };
697
+ }
698
+ if (url !== void 0 && (transport === "streamable-http" || transport === "http")) {
699
+ const headers = typeof config.headers === "object" && config.headers !== null && !Array.isArray(config.headers) ? config.headers : void 0;
700
+ return headers === void 0 ? {
701
+ type: "http",
702
+ url
703
+ } : {
704
+ type: "http",
705
+ url,
706
+ headers
707
+ };
708
+ }
709
+ if (url !== void 0 && transport === "sse") return {
710
+ type: "sse",
711
+ url
712
+ };
713
+ }
714
+ /** 读一个 JSON 文件;不存在或解析失败都返回 undefined(不当作空覆盖)。 */
715
+ function readJsonFile(file) {
716
+ try {
717
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
718
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
719
+ return;
720
+ } catch {
721
+ return;
722
+ }
723
+ }
724
+ /**
725
+ * 把 searchfuse 的 MCP 配置同步进 omp。
726
+ *
727
+ * **只补缺,不覆盖**:
728
+ * - omp 的 `mcp.json` 里已有的 server 一律不动(用户可能已经自己调过)
729
+ * - 只补 omp 里没有、而 searchfuse 配置里有的那些
730
+ * - `disabledServers` 原样保留
731
+ *
732
+ * 这样「已安装的话会自动处理」——用户装的不会被我们的默认值踩掉。
733
+ */
734
+ function syncOmpMcp(searchfuseConfig, file = ompMcpPath()) {
735
+ const existing = readJsonFile(file) ?? {};
736
+ const existingServers = typeof existing.mcpServers === "object" && existing.mcpServers !== null && !Array.isArray(existing.mcpServers) ? existing.mcpServers : {};
737
+ const sourceMcp = typeof searchfuseConfig.mcp === "object" && searchfuseConfig.mcp !== null && !Array.isArray(searchfuseConfig.mcp) ? searchfuseConfig.mcp : {};
738
+ const added = [];
739
+ const nextServers = { ...existingServers };
740
+ for (const [name, rawConfig] of Object.entries(sourceMcp)) {
741
+ if (Object.hasOwn(nextServers, name)) continue;
742
+ if (typeof rawConfig !== "object" || rawConfig === null || Array.isArray(rawConfig)) continue;
743
+ const server = toOmpServer(rawConfig);
744
+ if (server === void 0) continue;
745
+ nextServers[name] = server;
746
+ added.push(name);
747
+ }
748
+ if (added.length === 0) return {
749
+ added: [],
750
+ changed: false
751
+ };
752
+ const next = `${JSON.stringify({
753
+ ...existing,
754
+ mcpServers: nextServers
755
+ }, null, 2)}\n`;
756
+ const decision = decideWrite(file, next);
757
+ if (decision.changed) {
758
+ fs.mkdirSync(path$1.dirname(file), { recursive: true });
759
+ fs.writeFileSync(file, next, "utf-8");
760
+ }
761
+ return decision.backup === void 0 ? {
762
+ added,
763
+ changed: decision.changed
764
+ } : {
765
+ added,
766
+ changed: decision.changed,
767
+ backup: decision.backup
768
+ };
769
+ }
770
+ /**
771
+ * 报告 Claude Code 侧**已经装着**的 MCP server。
772
+ *
773
+ * 为什么不往里写:Claude Code 的 MCP 有自己的配置层级(`~/.claude.json`
774
+ * 的 `mcpServers`),用户可能已经装好并调过。插件的 `plugin.json` 里再声明
775
+ * 一遍同名 server 会造成「两个同名、谁生效」的歧义。所以这里只读不写,
776
+ * 由 `hosts sync` 打印出来告诉用户「这些已经在用」。
777
+ *
778
+ * omp 会自动从 `~/.claude.json` 导入(宿主源码 `claude-paths.ts` 确认),
779
+ * 所以 Claude 侧装了的,omp 那边也能拿到。
780
+ */
781
+ function reportClaudeMcp(claudeJsonPath = claudeUserConfigPath()) {
782
+ const raw = readJsonFile(claudeJsonPath);
783
+ if (raw === void 0) return [];
784
+ const servers = raw.mcpServers;
785
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) return [];
786
+ return Object.keys(servers);
787
+ }
788
+ /** Claude Code 的用户配置文件(MCP 与全局状态都在这里)。 */
789
+ function claudeUserConfigPath() {
790
+ return path$1.join(os$1.homedir(), ".claude.json");
791
+ }
792
+ // src/mcp/health.ts
793
+ /** 单次探测的握手超时。 */
794
+ var PROBE_TIMEOUT_MS = 3e3;
795
+ /** 探测结果的复用时长。5 分钟足够避免重复探测,又不至于让结果过时太久。 */
796
+ var CACHE_TTL_MS = 3e5;
797
+ /** 缓存文件的位置。与配置分离:它是可以随时删掉的缓存。 */
798
+ function mcpHealthPath() {
799
+ return path$1.join(os$1.homedir(), ".searchfuse", "mcp-health.json");
800
+ }
801
+ function readCache(file) {
802
+ try {
803
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
804
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
805
+ const out = {};
806
+ for (const [name, value] of Object.entries(parsed)) {
807
+ if (typeof value !== "object" || value === null) continue;
808
+ const record = value;
809
+ if (typeof record.ok !== "boolean" || typeof record.checkedAt !== "number") continue;
810
+ out[name] = {
811
+ ok: record.ok,
812
+ checkedAt: record.checkedAt,
813
+ fromCache: true,
814
+ ...typeof record.reason === "string" ? { reason: record.reason } : {}
815
+ };
816
+ }
817
+ return out;
818
+ } catch {
819
+ return {};
820
+ }
821
+ }
822
+ function writeCache(file, cache) {
823
+ try {
824
+ fs.mkdirSync(path$1.dirname(file), {
825
+ recursive: true,
826
+ mode: 448
827
+ });
828
+ const plain = {};
829
+ for (const [name, health] of Object.entries(cache)) plain[name] = health.ok ? {
830
+ ok: true,
831
+ checkedAt: health.checkedAt
832
+ } : {
833
+ ok: false,
834
+ checkedAt: health.checkedAt,
835
+ reason: health.reason
836
+ };
837
+ fs.writeFileSync(file, `${JSON.stringify(plain, null, 2)}\n`, { mode: 384 });
838
+ } catch {}
839
+ }
840
+ /**
841
+ * 探测一个 MCP server 能否完成握手。
842
+ *
843
+ * 判据是「能列出工具」——比只发一个 `initialize` 更严格,因为很多服务端
844
+ * 会接受 initialize 却在 `tools/list` 时才暴露真正的问题(鉴权过期、
845
+ * 上游不可达)。代价是多一次往返,值得。
846
+ */
847
+ async function probeMcpServer(config, now = Date.now()) {
848
+ const connection = new McpConnection({
849
+ ...config,
850
+ timeoutMs: PROBE_TIMEOUT_MS
851
+ });
852
+ try {
853
+ await connection.listTools();
854
+ return {
855
+ ok: true,
856
+ checkedAt: now,
857
+ fromCache: false
858
+ };
859
+ } catch (error) {
860
+ return {
861
+ ok: false,
862
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200),
863
+ checkedAt: now,
864
+ fromCache: false
865
+ };
866
+ } finally {
867
+ await connection.close();
868
+ }
869
+ }
870
+ /**
871
+ * 检查一组 server,能用缓存就用缓存。
872
+ *
873
+ * 返回每个 server 的健康结论;调用方据此决定注册哪些。**不可用的不会被
874
+ * 抛出**,只是被标出来——注册与不注册是调用方的决定。
875
+ */
876
+ async function checkMcpHealth(servers, options = {}) {
877
+ const file = options.cachePath ?? mcpHealthPath();
878
+ const maxAge = options.maxAgeMs ?? CACHE_TTL_MS;
879
+ const now = options.now ?? Date.now();
880
+ const cached = readCache(file);
881
+ const results = {};
882
+ let dirty = false;
883
+ const pending = [];
884
+ for (const [name, config] of Object.entries(servers)) {
885
+ const hit = cached[name];
886
+ if (hit !== void 0 && now - hit.checkedAt < maxAge) {
887
+ results[name] = hit;
888
+ continue;
889
+ }
890
+ pending.push([name, config]);
891
+ }
892
+ if (pending.length > 0) {
893
+ const settled = await Promise.all(pending.map(async ([name, config]) => {
894
+ return [name, await probeMcpServer(config, now)];
895
+ }));
896
+ for (const [name, health] of settled) {
897
+ results[name] = health;
898
+ cached[name] = health;
899
+ dirty = true;
900
+ }
901
+ }
902
+ if (dirty) writeCache(file, cached);
903
+ return results;
904
+ }
905
+ /** 从健康结论里挑出可用的那些。 */
906
+ function usableMcpNames(health) {
907
+ return Object.entries(health).filter(([, value]) => value.ok).map(([name]) => name);
908
+ }
909
+ // src/util/secretInput.ts
910
+ /**
911
+ * Read a secret without it touching argv. `searchfuse config set x.apiKey`
912
+ * with no value lands here: on a terminal it prompts with the echo muted, and
913
+ * on a pipe it reads the first line, so `pbpaste | searchfuse config set
914
+ * x.apiKey` works too. Either way the key stays out of shell history and out
915
+ * of the conversation with whatever agent is driving the terminal.
916
+ *
917
+ * The chat path cannot be blocked, only not led to: most users will paste a
918
+ * key wherever is most convenient, and the docs accept that. This is the
919
+ * clean path for the ones who care.
920
+ */
921
+ async function readSecret(promptText, stdin = process.stdin, stderr = process.stderr) {
922
+ if (!stdin.isTTY) {
923
+ stdin.setEncoding("utf8");
924
+ const MAX_CHARS = 65536;
925
+ let data = "";
926
+ for await (const chunk of stdin) {
927
+ data += chunk;
928
+ if (data.includes("\n")) break;
929
+ if (data.length > MAX_CHARS) throw new Error("stdin exceeded 64KB with no newline; that is not a key");
930
+ }
931
+ const value = data.split("\n")[0].trim();
932
+ if (value === "") throw new Error("no key arrived on stdin (pipe one line, or run on a terminal)");
933
+ return value;
934
+ }
935
+ const rl = readline.createInterface({
936
+ input: stdin,
937
+ output: stderr,
938
+ terminal: true
939
+ });
940
+ const muted = rl;
941
+ stderr.write(promptText);
942
+ muted._writeToOutput = () => {};
943
+ try {
944
+ const trimmed = (await new Promise((resolve, reject) => {
945
+ let settled = false;
946
+ const settle = (action) => {
947
+ if (!settled) {
948
+ settled = true;
949
+ action();
950
+ }
951
+ };
952
+ rl.question("", (answer) => settle(() => resolve(answer)));
953
+ rl.on("SIGINT", () => settle(() => reject(/* @__PURE__ */ new Error("cancelled, nothing was saved"))));
954
+ rl.on("close", () => settle(() => reject(/* @__PURE__ */ new Error("input ended before a key was entered"))));
955
+ })).trim();
956
+ if (trimmed === "") throw new Error("no key entered");
957
+ return trimmed;
958
+ } finally {
959
+ stderr.write("\n");
960
+ rl.close();
961
+ }
962
+ }
963
+ // src/util/isAlive.ts
964
+ /**
965
+ * 这个 pid 的进程还活着吗。
966
+ *
967
+ * `process.kill(pid, 0)` 不发送信号,只做存在性检查:进程在则静默返回,
968
+ * 不在则抛 ESRCH。跨进程锁用它回收「持锁进程已经死了」的陈旧锁。
969
+ *
970
+ * 独立成模块而不是留在 `main.ts`:`main.ts` 顶层有
971
+ * `await program.parseAsync(process.argv)`,任何导入它的测试都会把整个
972
+ * CLI 解析跑一遍。这个判据必须能被单元测试直接验,尤其是 EPERM 分支——
973
+ * 2026-11-25 反向验证时亲眼见过「测试抄了一份实现去测自己」的假绿。
974
+ */
975
+ function isAlive(pid) {
976
+ if (!Number.isInteger(pid) || pid <= 0) return false;
977
+ try {
978
+ process.kill(pid, 0);
979
+ return true;
980
+ } catch (error) {
981
+ return error.code === "EPERM";
982
+ }
983
+ }
984
+ // src/main.ts
985
+ if (process.env.MODSEARCH_NESTED) {
986
+ process.stderr.write("searchfuse refused to run: it was started from inside an engine that searchfuse itself spawned (recursion guard). An engine such as Grok Build tried to call searchfuse instead of using its own search tools.\n");
987
+ process.exit(1);
988
+ }
989
+ /** 一次已结束的运行,在真正收尾前最多等多久让被遗弃的工作收场。 */
990
+ var EXIT_BACKSTOP_MS = 2e3;
991
+ /**
992
+ * 退出兜底计时器挂在 globalThis 上的键。
993
+ *
994
+ * 为什么不用普通模块变量:`main.ts` 一被 import 就会立即解析 argv(commander
995
+ * 的 `program.parse()` 在模块顶层),测试没法在配置好 argv 之前 import 它,
996
+ * 也就拿不到模块作用域里的句柄。挂在 globalThis 的符号上,测试用同一个
997
+ * `Symbol.for(...)` 直接取,不必 import 这个模块。
998
+ *
999
+ * 计时器本身 `.unref()` 过,不阻止进程退出;但它会在测试结束后才触发
1000
+ * `process.exit`,那时 spy 已恢复,Vitest 报「unexpected process.exit」。
1001
+ */
1002
+ var EXIT_BACKSTOP_KEY = Symbol.for("searchfuse.exitBackstop");
1003
+ /** 写入并等到流确实收下,这样退出时不会把它截断。 */
1004
+ function writeFully(stream, text) {
1005
+ return new Promise((resolve, reject) => {
1006
+ stream.write(text, (error) => error ? reject(error) : resolve());
1007
+ });
1008
+ }
1009
+ var program = new Command();
1010
+ program.name("searchfuse").description("Plug-in web search and page fetch for models without native web access: query or URL in, structured JSON evidence out").version("0.1.2");
1011
+ program.command("search", { isDefault: true }).description("Search the web or X, or fetch a page (default command)").option("-q, --query <text>", "Search query (or answer focus when combined with -u)").option("-u, --url <url>", "Fetch this web page instead of searching").option("-o, --output <path>", "Write result JSON to a file").option("-s, --source <list>", "Where to search: web, x, or web,x (default: web, or x when the query is about X)").option("-e, --engine <name>", `Engine for this run, overriding config (${listEngines().join(", ")})`).option("-m, --model <name>", "Engine model, where the engine has one").option("--prompt <text>", "Extra constraints for this run").option("--max-results <n>", "Maximum number of search results", "8").option("--timeout <ms>", "Engine timeout in milliseconds", "180000").option("--deadline <ms>", "Wall-clock budget for the whole run in milliseconds, across every engine tried (default: none)").option("--workdir <path>", "Working directory for engines that run a command").option("--allow-private-network", "Allow reserved address ranges for this run, for VPNs that map public hosts into them").action(async (options) => {
1012
+ let exitCode = 0;
1013
+ try {
1014
+ const timeoutMs = Number.parseInt(options.timeout, 10);
1015
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid --timeout. Use a positive integer in milliseconds.");
1016
+ let deadlineMs;
1017
+ if (options.deadline !== void 0) {
1018
+ deadlineMs = Number.parseInt(options.deadline, 10);
1019
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) throw new Error("Invalid --deadline. Use a positive integer in milliseconds.");
1020
+ }
1021
+ const maxResults = Number.parseInt(options.maxResults, 10);
1022
+ if (!Number.isFinite(maxResults) || maxResults <= 0) throw new Error("Invalid --max-results. Use a positive integer.");
1023
+ const config = loadConfigFile();
1024
+ const result = await runSearch({
1025
+ query: options.query,
1026
+ url: options.url,
1027
+ engine: options.engine,
1028
+ sources: options.source,
1029
+ model: options.model,
1030
+ prompt: options.prompt,
1031
+ timeoutMs,
1032
+ deadlineMs,
1033
+ deadlineStartedAt: performance.timeOrigin,
1034
+ maxResults,
1035
+ workdir: options.workdir,
1036
+ allowPrivateNetwork: options.allowPrivateNetwork,
1037
+ config,
1038
+ cooldown: buildCooldownController(config)
1039
+ });
1040
+ const output = JSON.stringify(result, null, 2);
1041
+ if (options.output) {
1042
+ const outputPath = path.resolve(options.output);
1043
+ fs$1.mkdirSync(path.dirname(outputPath), { recursive: true });
1044
+ fs$1.writeFileSync(outputPath, output, "utf-8");
1045
+ }
1046
+ await writeFully(process.stdout, `${output}\n`);
1047
+ } catch (error) {
1048
+ await writeFully(process.stderr, [`Error: ${error instanceof Error ? error.message : String(error)}`, `Known engines: ${listEngines().join(", ")}`].join("\n") + "\n");
1049
+ exitCode = 1;
1050
+ }
1051
+ await waitForPendingKills();
1052
+ process.exitCode = exitCode;
1053
+ const store = globalThis;
1054
+ const previous = store[EXIT_BACKSTOP_KEY];
1055
+ if (previous !== void 0) clearTimeout(previous);
1056
+ const timer = setTimeout(() => process.exit(exitCode), EXIT_BACKSTOP_MS);
1057
+ timer.unref();
1058
+ store[EXIT_BACKSTOP_KEY] = timer;
1059
+ });
1060
+ program.command("doctor").description("Diagnose config and routing on this machine (no quota, no network)").option("--json", "Print the report as JSON").action((options) => {
1061
+ try {
1062
+ const report = runDoctor();
1063
+ if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
1064
+ else process.stdout.write(`${formatDoctorReport(report)}\n`);
1065
+ } catch (error) {
1066
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1067
+ process.exit(1);
1068
+ }
1069
+ });
1070
+ var config = program.command("config").description(`Manage ${CONFIG_PATH}. Optional: searchfuse runs without it.`);
1071
+ config.command("init").description(`Create a starter config at ${CONFIG_PATH}`).option("--force", "Overwrite an existing config file").action((options) => {
1072
+ try {
1073
+ initConfigFile(CONFIG_PATH, Boolean(options.force));
1074
+ process.stdout.write([
1075
+ `Created ${CONFIG_PATH}`,
1076
+ "Everything is optional. Things you can set:",
1077
+ " searchfuse config set engine <antigravity-cli|tavily|exa|firecrawl|keenable|youcom> which engine searches",
1078
+ " searchfuse config set <engine>.<apiKey|bin|model|baseURL|keylessFetch> <value> engine settings",
1079
+ " searchfuse config set cooldown <on|off> quota cooldown failover (default on)",
1080
+ " searchfuse config set allowPrivateNetwork <true|false> reach reserved/private ranges (default false)",
1081
+ "Search, page fetch, and X need no settings at all: keyless Firecrawl works out of the box.",
1082
+ ""
1083
+ ].join("\n"));
1084
+ } catch (error) {
1085
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1086
+ process.exit(1);
1087
+ }
1088
+ });
1089
+ config.command("set <key> [value]").description("Set a value, e.g. tavily.apiKey <key>, or search.engine tavily. Omit the value for an .apiKey to be prompted with the echo muted, so the key stays out of argv and shell history (a pipe works too: pbpaste | searchfuse config set tavily.apiKey)").action(async (key, value) => {
1090
+ try {
1091
+ if (value === void 0) {
1092
+ if (!key.endsWith(".apiKey")) throw new Error(`${key} needs a value: searchfuse config set ${key} <value>`);
1093
+ const parts = key.split(".").filter(Boolean);
1094
+ const engineName = parts[0] === "engines" ? parts[1] : parts[0];
1095
+ if (!engineName || !findEngine(engineName)) throw new Error(`Unknown engine: ${engineName ?? key}. Known engines: ${listEngines().join(", ")}.`);
1096
+ value = await readSecret(`Enter the value for ${key} (input hidden): `);
1097
+ }
1098
+ setConfigValue(key, value);
1099
+ process.stdout.write(`Saved ${key} to ${CONFIG_PATH}\n`);
1100
+ } catch (error) {
1101
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1102
+ process.exit(1);
1103
+ }
1104
+ });
1105
+ config.command("show").description("Print the effective config (file + env, source-tagged) with API keys masked").action(() => {
1106
+ try {
1107
+ process.stdout.write(`${renderEffectiveConfig(loadConfigFile(), process.env)}\n`);
1108
+ } catch (error) {
1109
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1110
+ process.exit(1);
1111
+ }
1112
+ });
1113
+ program.command("state").description("Manage the quota cooldown state at ~/.searchfuse/state.json").command("clear").description("Forget every engine cooldown, so all engines are tried at full priority again").action(() => {
1114
+ try {
1115
+ const statePath = currentStatePath();
1116
+ clearAllCooldowns(statePath);
1117
+ process.stdout.write(`Cleared cooldown state (${statePath}).\n`);
1118
+ } catch (error) {
1119
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1120
+ process.exit(1);
1121
+ }
1122
+ });
1123
+ /** 锁久到多久就认为持有者不正常(PID 复用兜底)。正常起服务只要几百毫秒。 */
1124
+ var STALE_LOCK_MS = 12e4;
1125
+ /**
1126
+ * 读 `~/.searchfuse/runtime.json`,只取端口。
1127
+ *
1128
+ * **判据必须与 `src/serveEnsure.ts` 的 `readServeRuntimeFile` 逐条一致**:
1129
+ * 同一个文件,两处若宽严不一,就会出现「一个判在跑、一个判没在跑」的
1130
+ * 错配——宽的那个 exit 0 不动手,严的那个去起新服务,结果是想用的服务
1131
+ * 根本没起来。2026-11-25 审查时发现这里原本只判 `typeof === 'number'`,
1132
+ * 缺整数校验与 token 校验,与 `serveEnsure.ts` 不一致。
1133
+ */
1134
+ function readRuntimeFile() {
1135
+ try {
1136
+ const raw = fs$1.readFileSync(path.join(os.homedir(), ".searchfuse", "runtime.json"), "utf8");
1137
+ const parsed = JSON.parse(raw);
1138
+ if (typeof parsed.port !== "number" || !Number.isInteger(parsed.port)) return void 0;
1139
+ if (typeof parsed.token !== "string" || parsed.token === "") return void 0;
1140
+ return { port: parsed.port };
1141
+ } catch {
1142
+ return;
1143
+ }
1144
+ }
1145
+ program.command("serve").description("Run the local SearXNG-compatible service that omp connects to").option("--ensure", "Start only if not already running; exit 0 if healthy").option("--daemon", "Run until killed (no idle exit)").option("--port <n>", "Port to listen on (default: config serve.port, or 0 for any free port)").action(async (options) => {
1146
+ const config = loadConfigFile();
1147
+ const requested = options.port !== void 0 ? Number(options.port) : config.serve?.port ?? 0;
1148
+ if (!Number.isInteger(requested) || requested < 0 || requested > 65535) {
1149
+ process.stderr.write(`Error: invalid port "${options.port ?? config.serve?.port}"\n`);
1150
+ process.exit(2);
1151
+ }
1152
+ let releaseLockFn;
1153
+ if (options.ensure) {
1154
+ const runningPort = await findRunningServe();
1155
+ if (runningPort !== void 0) {
1156
+ process.stdout.write(`Already running on 127.0.0.1:${runningPort}.\n`);
1157
+ process.exit(0);
1158
+ }
1159
+ const lockFile = path.join(path.dirname(runtimePath()), "serve.ensure.lock");
1160
+ let holdsLock = false;
1161
+ /** 抢锁失败时如果是环境错误,记在这里,让下面直接报出来而不是空等。 */
1162
+ let lastLockError;
1163
+ /**
1164
+ * 抢锁。**用 `linkSync`,不是 `openSync('wx')`。**
1165
+ *
1166
+ * 两者的差别只在回收路径上,但那个差别是致命的:
1167
+ * - `openSync('wx')` 依赖「锁文件不存在」才能成功。回收时要先删旧锁
1168
+ * 再建新锁,这**两步之间**任何进程都能建锁,于是并发回收时多个进程
1169
+ * 各自删一次、各自建一次,全都认为自己持锁。
1170
+ * - `linkSync(cand, lock)` 把「建锁」压成一次内核原子操作:只有当
1171
+ * `lock` 不存在时才成功,存在就抛 EEXIST。删完之后最先 link 的那个
1172
+ * 赢,其余全部 EEXIST。
1173
+ *
1174
+ * 2026-11-25 实测(8 进程真并发抢同一把陈旧锁):
1175
+ * `openSync('wx')` 版 8/8 全部报持锁;`linkSync` 版恰好 1 个成功、
1176
+ * 7 个 EEXIST。Windows 与 POSIX 都支持 link,Windows 上同样原子。
1177
+ */
1178
+ const tryTakeLock = () => {
1179
+ const candidate = `${lockFile}.cand.${process.pid}`;
1180
+ try {
1181
+ fs$1.writeFileSync(candidate, `${process.pid}\n`, { mode: 384 });
1182
+ } catch (writeError) {
1183
+ lastLockError = writeError;
1184
+ return "env-error";
1185
+ }
1186
+ try {
1187
+ fs$1.linkSync(candidate, lockFile);
1188
+ return true;
1189
+ } catch (linkError) {
1190
+ const code = linkError.code;
1191
+ if (code === "EEXIST" || code === "ENOENT" || code === "EISDIR" || code === "EPERM") try {
1192
+ if (fs$1.statSync(lockFile).isDirectory()) {
1193
+ fs$1.rmSync(lockFile, {
1194
+ recursive: true,
1195
+ force: true
1196
+ });
1197
+ return "retry";
1198
+ }
1199
+ } catch {}
1200
+ if (code === "EEXIST") return false;
1201
+ lastLockError = linkError;
1202
+ return "env-error";
1203
+ } finally {
1204
+ try {
1205
+ fs$1.unlinkSync(candidate);
1206
+ } catch {}
1207
+ }
1208
+ };
1209
+ try {
1210
+ fs$1.mkdirSync(path.dirname(lockFile), {
1211
+ recursive: true,
1212
+ mode: 448
1213
+ });
1214
+ } catch {}
1215
+ const take = tryTakeLock();
1216
+ if (take === "env-error") {
1217
+ process.stderr.write(`Error: cannot create ${lockFile} (${lastLockError?.code ?? lastLockError?.message}). Check that ~/.searchfuse is writable.
1218
+ `);
1219
+ process.exit(1);
1220
+ }
1221
+ holdsLock = take === true || take === "retry" && tryTakeLock() === true;
1222
+ if (!holdsLock) {
1223
+ let ownerPid = 0;
1224
+ try {
1225
+ ownerPid = Number(fs$1.readFileSync(lockFile, "utf-8").trim());
1226
+ } catch {}
1227
+ const ownerDead = ownerPid > 0 && !isAlive(ownerPid);
1228
+ let tooOld = false;
1229
+ try {
1230
+ tooOld = Date.now() - fs$1.statSync(lockFile).mtimeMs > STALE_LOCK_MS;
1231
+ } catch {}
1232
+ if (ownerDead || tooOld) {
1233
+ try {
1234
+ fs$1.unlinkSync(lockFile);
1235
+ } catch {}
1236
+ const retake = tryTakeLock();
1237
+ if (retake === "env-error") {
1238
+ process.stderr.write(`Error: cannot create ${lockFile} (${lastLockError?.code ?? lastLockError?.message}). Check that ~/.searchfuse is writable.
1239
+ `);
1240
+ process.exit(1);
1241
+ }
1242
+ holdsLock = retake === true || retake === "retry" && tryTakeLock() === true;
1243
+ }
1244
+ }
1245
+ if (!holdsLock) {
1246
+ const deadline = Date.now() + 2e4;
1247
+ while (Date.now() < deadline) {
1248
+ const ready = readRuntimeFile();
1249
+ if (ready !== void 0) try {
1250
+ if ((await fetch(`http://127.0.0.1:${ready.port}/healthz`, { signal: AbortSignal.timeout(2e3) })).ok) {
1251
+ process.stdout.write(`Already running on 127.0.0.1:${ready.port}.\n`);
1252
+ process.exit(0);
1253
+ }
1254
+ } catch {}
1255
+ await new Promise((resolve) => setTimeout(resolve, 300));
1256
+ }
1257
+ let waitingOnPid = 0;
1258
+ try {
1259
+ waitingOnPid = Number(fs$1.readFileSync(lockFile, "utf-8").trim());
1260
+ } catch {}
1261
+ if (waitingOnPid > 0 && !isAlive(waitingOnPid)) process.stderr.write(`Error: the process that was starting the service (pid ${waitingOnPid}) exited without writing runtime.json. Check that its candidate ports are free (or set serve.port to a free number).
1262
+ `);
1263
+ else process.stderr.write("Error: another serve --ensure is starting up; gave up waiting.\n");
1264
+ process.exit(1);
1265
+ }
1266
+ const releaseLock = () => {
1267
+ try {
1268
+ if (Number(fs$1.readFileSync(lockFile, "utf-8").trim()) === process.pid) fs$1.unlinkSync(lockFile);
1269
+ } catch {}
1270
+ };
1271
+ process.once("exit", releaseLock);
1272
+ for (const signalName of ["SIGINT", "SIGTERM"]) process.once(signalName, () => {
1273
+ releaseLock();
1274
+ process.exit(0);
1275
+ });
1276
+ releaseLockFn = releaseLock;
1277
+ }
1278
+ const token = ensureServeToken();
1279
+ const identity = identityOf(os.homedir());
1280
+ const useCandidates = requested === 0;
1281
+ try {
1282
+ const handle = await startServe({
1283
+ port: requested,
1284
+ token,
1285
+ idleExitSeconds: options.daemon ? 0 : config.serve?.idleExitSeconds ?? 0,
1286
+ fingerprint: identity.fingerprint,
1287
+ ...useCandidates ? { candidatePorts: identity.ports } : {}
1288
+ });
1289
+ process.stdout.write(`Listening on http://127.0.0.1:${handle.port}\n`);
1290
+ if (useCandidates) {
1291
+ const earlier = identity.ports.slice(0, identity.ports.indexOf(handle.port));
1292
+ if (earlier.length > 0) {
1293
+ const winner = await discoverServe(identity.fingerprint, earlier);
1294
+ if (winner !== void 0) {
1295
+ process.stdout.write(`Port ${handle.port} yielded to the instance already running on 127.0.0.1:${winner.port}.\n`);
1296
+ await handle.close();
1297
+ releaseLockFn?.();
1298
+ process.exit(0);
1299
+ }
1300
+ }
1301
+ }
1302
+ releaseLockFn?.();
1303
+ } catch (error) {
1304
+ releaseLockFn?.();
1305
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1306
+ process.exit(1);
1307
+ }
1308
+ });
1309
+ var hosts = program.command("hosts").description("Wire searchfuse into dsh / Claude Code / omp, or unwire it");
1310
+ hosts.command("sync").description("Write each host configuration from ~/.searchfuse/config.json").option("--dry-run", "Show what would change without writing").option("--skip-mcp-probe", "Register MCP servers without checking they are reachable").action(async (options) => {
1311
+ try {
1312
+ const config = loadConfigFile();
1313
+ const lines = [];
1314
+ const ompEnabled = config.hosts?.omp?.enabled !== false;
1315
+ if (options.dryRun) lines.push(`omp: ${ompEnabled ? "enable" : "disable"} (${ompConfigPath()})`);
1316
+ else {
1317
+ const result = syncOmp(void 0);
1318
+ lines.push(`omp: ${ompEnabled ? "enabled" : "disabled"} (HTTP wiring cleared)` + (result.changed ? "" : ", no change") + (result.backup ? ` [backup: ${path.basename(result.backup)}]` : ""));
1319
+ }
1320
+ if (options.dryRun) lines.push(ompEnabled ? "omp extension: would install (shadow builtin web_search)" : "omp extension: would remove (host disabled)");
1321
+ else if (!ompEnabled) {
1322
+ const removed = removeOmpExtension();
1323
+ lines.push(removed ? "omp extension: removed (host disabled)" : "omp extension: none to remove");
1324
+ } else {
1325
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
1326
+ const templatePath = path.join(selfDir, "..", "omp", "extension.ts");
1327
+ try {
1328
+ const installed = installOmpExtension(fs$1.readFileSync(templatePath, "utf-8"), path.join(selfDir, "kernel.js"));
1329
+ lines.push(`omp extension: installed (${path.basename(installed)})`);
1330
+ } catch (error) {
1331
+ lines.push(`omp extension: skipped (${error instanceof Error ? error.message : String(error)})`);
1332
+ }
1333
+ }
1334
+ const claudeEnabled = config.hosts?.claudeCode?.enabled !== false;
1335
+ if (options.dryRun) lines.push(`claudeCode: ${claudeEnabled ? "enable" : "disable"} (${claudeSettingsPath()})`);
1336
+ else {
1337
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
1338
+ const result = syncClaudeSettings(claudeEnabled, {
1339
+ runtimePath: path.join(os.homedir(), ".searchfuse", "runtime.json"),
1340
+ kernelPath: path.join(selfDir, "kernel.js"),
1341
+ identity: identityOf(os.homedir())
1342
+ });
1343
+ lines.push(`claudeCode: ${claudeEnabled ? "enabled" : "disabled"}` + (result.changed ? "" : " (no change)") + (result.backup ? ` [backup: ${path.basename(result.backup)}]` : ""));
1344
+ }
1345
+ {
1346
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
1347
+ const sourceDir = path.join(selfDir, "..", "claude");
1348
+ if (options.dryRun) lines.push(`claudeCode mod: would sync (${claudeSkillDir()})`);
1349
+ else {
1350
+ const synced = installClaudeSkill(sourceDir);
1351
+ lines.push(synced.changed ? `claudeCode mod: synced ${synced.installed.join(", ")}` : "claudeCode mod: already up to date");
1352
+ }
1353
+ }
1354
+ const mcpSet = effectiveMcp(config);
1355
+ const registeredNames = Object.keys(mcpSet);
1356
+ if (options.dryRun) lines.push(`mcp: would register ${registeredNames.join(", ") || "(none)"} (after reachability probe)`);
1357
+ else {
1358
+ let usable = registeredNames;
1359
+ if (!options.skipMcpProbe) {
1360
+ const health = await checkMcpHealth(Object.fromEntries(registeredNames.map((name) => [name, mcpSet[name]]).filter(([, entry]) => entry !== void 0).map(([name, entry]) => [name, {
1361
+ transport: "streamable-http",
1362
+ url: typeof entry.url === "string" ? entry.url : "",
1363
+ ...typeof entry.timeoutMs === "number" ? { timeoutMs: entry.timeoutMs } : {}
1364
+ }]).filter(([, entry]) => entry.url !== "")));
1365
+ usable = usableMcpNames(health);
1366
+ const dead = registeredNames.filter((name) => !usable.includes(name));
1367
+ if (dead.length > 0) for (const name of dead) {
1368
+ const reason = health[name]?.reason ?? "不可达";
1369
+ lines.push(`mcp: skipping ${name} (${reason})`);
1370
+ }
1371
+ }
1372
+ const mcp = syncOmpMcp({ mcp: Object.fromEntries(usable.map((name) => [name, mcpSet[name]])) });
1373
+ lines.push(mcp.added.length > 0 ? `mcp: added to omp: ${mcp.added.join(", ")}` + (mcp.backup ? ` [backup: ${path.basename(mcp.backup)}]` : "") : "mcp: omp already has all reachable servers (no change)");
1374
+ const claudeMcp = reportClaudeMcp();
1375
+ if (claudeMcp.length > 0) lines.push(`mcp: already installed in Claude Code: ${claudeMcp.join(", ")}`);
1376
+ }
1377
+ process.stdout.write(`${lines.join("\n")}\n`);
1378
+ } catch (error) {
1379
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1380
+ process.exit(1);
1381
+ }
1382
+ });
1383
+ var HOST_NAMES = [
1384
+ "dsh",
1385
+ "claudeCode",
1386
+ "omp"
1387
+ ];
1388
+ hosts.command("enable <host>").description(`Mark a host as enabled: ${HOST_NAMES.join(" | ")}`).action((name) => {
1389
+ try {
1390
+ if (!HOST_NAMES.includes(name)) throw new Error(`Unknown host "${name}". Known: ${HOST_NAMES.join(", ")}`);
1391
+ setConfigValue("hosts." + hostConfigKey(name), "true");
1392
+ process.stdout.write(`Enabled ${name}. Run \`searchfuse hosts sync\` to apply.\n`);
1393
+ } catch (error) {
1394
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1395
+ process.exit(1);
1396
+ }
1397
+ });
1398
+ hosts.command("disable <host>").description(`Mark a host as disabled: ${HOST_NAMES.join(" | ")}`).action((name) => {
1399
+ try {
1400
+ if (!HOST_NAMES.includes(name)) throw new Error(`Unknown host "${name}". Known: ${HOST_NAMES.join(", ")}`);
1401
+ setConfigValue("hosts." + hostConfigKey(name), "false");
1402
+ process.stdout.write(`Disabled ${name}. Run \`searchfuse hosts sync\` to apply.\n`);
1403
+ } catch (error) {
1404
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1405
+ process.exit(1);
1406
+ }
1407
+ });
1408
+ /** 配置里的键名与命令行名字可能不同(`claude-code` → `claudeCode`)。 */
1409
+ function hostConfigKey(name) {
1410
+ return name === "claude-code" ? "claudeCode" : name;
1411
+ }
1412
+ migrateLegacyDir();
1413
+ registerSearxngCleanup();
1414
+ await program.parseAsync(process.argv, { from: "node" });