@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/CHANGELOG.md +287 -0
- package/LICENSE +21 -0
- package/README.md +161 -2
- package/README.zh-CN.md +162 -0
- package/SECURITY.md +54 -0
- package/claude/.claude-plugin/plugin.json +17 -0
- package/claude/SKILL.md +53 -0
- package/claude/hooks/hooks.json +3 -0
- package/claude/hooks/register.ts +624 -0
- package/cordis.patch.yml +16 -0
- package/dist/config-schema.js +40 -0
- package/dist/errorCause-BY0A0XKN.js +17 -0
- package/dist/kernel.js +73 -0
- package/dist/main.js +1414 -0
- package/dist/mcp-protocol.js +1 -0
- package/dist/mcp-registry.js +155 -0
- package/dist/protocol-ClnjMnGV.js +259 -0
- package/dist/proxy-DodOSGiI.js +50 -0
- package/dist/search-DeT416xs.js +4173 -0
- package/dist/serve-ensure.js +1 -0
- package/dist/serveEnsure-BTj9IifL.js +632 -0
- package/dsh/client.js +2917 -0
- package/dsh/fetch-schema.json +1 -0
- package/dsh/index.js +2774 -0
- package/dsh/search-schema.json +65 -0
- package/dsh/spawnHidden.d.ts +7 -0
- package/dsh/spawnHidden.js +8 -0
- package/omp/extension.ts +565 -0
- package/omp/host-types.d.ts +47 -0
- package/omp/tsconfig.json +13 -0
- package/package.json +91 -4
- package/skills/searchfuse/SKILL.md +139 -0
- package/skills/searchfuse/references/cli.md +78 -0
- package/skills/searchfuse/references/configure.md +407 -0
- package/skills/searchfuse/references/output-schema.md +182 -0
- package/skills/searchfuse/references/runtime.md +58 -0
- package/skills/searchfuse/scripts/run.ps1 +279 -0
- package/skills/searchfuse/scripts/run.sh +315 -0
package/dsh/index.js
ADDED
|
@@ -0,0 +1,2774 @@
|
|
|
1
|
+
// DeepSeek Harness (dsh) 插件:把 harness 的 web 能力接到本包自带的 modsearch
|
|
2
|
+
// CLI 上。dsh 本身已经有一个 web seam(`ctx.web`),它基于可插拔的 provider
|
|
3
|
+
// 提供原生 `web_search` 工具,所以搜索以 provider 的身份接入,而不是再立一个
|
|
4
|
+
// 竞争性的工具:模型继续用稳定的 `web_search` schema,UI 继续显示引用卡片,
|
|
5
|
+
// 后端则换成 modsearch 的免密钥引擎链。dsh 没有 seam 覆盖的两块语料,X 和
|
|
6
|
+
// 聚焦式页面阅读,各自注册为独立工具;与 modlens 的 `read_image` 同理,注册
|
|
7
|
+
// 出去的工具 schema 每次请求都会送到模型面前,不存在「触发与否靠运气」的
|
|
8
|
+
// 问题。引擎从本包内的 ../dist/main.js 拉起:不走 PATH 查找,不用 npx,插件
|
|
9
|
+
// 与它的引擎版本锁定在一起。
|
|
10
|
+
//
|
|
11
|
+
// 通过 cordis.patch.yml 的条目加载(见 package.json 的 `dsh.bundle` manifest):
|
|
12
|
+
// 一条条目挂载本插件,另一条把 `web` seam 的 `searchProvider` 指向它。引擎、
|
|
13
|
+
// 密钥和路由仍然保存在 ~/.searchfuse/config.json,与所有 harness 共用。
|
|
14
|
+
import { chmodSync, existsSync, statSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { request as httpRequest } from 'node:http';
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
18
|
+
import { dirname, join, resolve } from 'node:path';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
import { spawnHidden } from './spawnHidden.js';
|
|
21
|
+
// 完整 CLI 入口。doctor 需要子命令解析与 config 读取,所以用 dist/main.js。
|
|
22
|
+
// 注意搜索内核是另一个入口(dist/kernel.js,只认 --query / --url),两者
|
|
23
|
+
// 不能混用:把 kernel.js 拿去执行 `serve --ensure` 会报「不认识的命令」。
|
|
24
|
+
const DOCTOR_CLI_PATH = fileURLToPath(new URL('../dist/main.js', import.meta.url));
|
|
25
|
+
/** 拉起服务的上限。比 omp 与 Claude 侧的唤醒上限宽一些:这条路径带轮询。 */
|
|
26
|
+
const SERVE_ENSURE_TIMEOUT_MS = 20_000;
|
|
27
|
+
// 由仓库里的一个测试与 src/schema.ts 保持同步;插件文件无法导入 TS 源码,
|
|
28
|
+
// 且要保持完全零依赖(只用 node 内置模块)。
|
|
29
|
+
const SEARCH_OUTPUT_SCHEMA = JSON.parse(readFileSync(new URL('./search-schema.json', import.meta.url), 'utf8'));
|
|
30
|
+
const FETCH_OUTPUT_SCHEMA = JSON.parse(readFileSync(new URL('./fetch-schema.json', import.meta.url), 'utf8'));
|
|
31
|
+
// CLI 的 --timeout 是按引擎计算的,而一个引擎失败后会把一份全新的预算交给
|
|
32
|
+
// 下一个引擎,所以每条路径还会传 --deadline:整轮运行的墙钟时间上限。单个
|
|
33
|
+
// 引擎分到的时间远低于 deadline,好让故障转移的引擎仍有轮次可用;而 deadline
|
|
34
|
+
// 又低于 harness 的预算,于是整轮运行最终总是落在结果上,或落在 CLI 那句有
|
|
35
|
+
// 描述性的错误上,绝不会变成宿主那边一句光秃秃的 abort。
|
|
36
|
+
//
|
|
37
|
+
// 自有工具:每引擎最多 120 秒,整轮 180 秒,外加一个越过 deadline 的协作式
|
|
38
|
+
// 兜底。
|
|
39
|
+
const OWN_TOOL_ENGINE_TIMEOUT_MS = 120_000;
|
|
40
|
+
const OWN_TOOL_DEADLINE_MS = 180_000;
|
|
41
|
+
const OWN_TOOL_BACKSTOP_MS = OWN_TOOL_DEADLINE_MS + 20_000;
|
|
42
|
+
// HTTP 请求的墙钟上限。服务端自己有整轮 deadline(默认 180 秒),这里比它
|
|
43
|
+
// 多留一点余量,免得客户端先放弃、把一个仍在正常工作的轮次掐断。
|
|
44
|
+
const SEARCH_TIMEOUT_MS = 240_000;
|
|
45
|
+
// provider 路径运行在 tool-web 的预算之下(随包发布的搜索路由是 60 秒):
|
|
46
|
+
// 单个引擎给 40 秒,就能在 55 秒的一整轮里给一次快速回退留出余地。
|
|
47
|
+
/**
|
|
48
|
+
* 插件多久重新检查一次配置文件的 mtime。文件很小,stat 也很便宜;几秒钟
|
|
49
|
+
* 足够短,用户刚保存完一个服务器,下一轮就期望看到它的工具。
|
|
50
|
+
*
|
|
51
|
+
* MCP 工具与独立引擎工具共用这一个节奏:两处盯的是同一个文件,各起一套
|
|
52
|
+
* 定时器只会让两者在改动后出现短暂的看法不一致。
|
|
53
|
+
*/
|
|
54
|
+
const CONFIG_POLL_MS = 5_000;
|
|
55
|
+
/**
|
|
56
|
+
* 有 MCP 服务端没连上时,隔多久再试一次。
|
|
57
|
+
*
|
|
58
|
+
* 启动时的网络抖动很常见:一个包丢了、一个服务端恰好在重启。立刻重试只会
|
|
59
|
+
* 撞上同一个故障,而永远不重试则意味着那个服务端的工具一直缺席,直到用户
|
|
60
|
+
* 手动改配置。30 秒足够让一次抖动过去,也短到用户不会觉得它坏了。
|
|
61
|
+
*/
|
|
62
|
+
const MCP_RETRY_DELAY_MS = 30_000;
|
|
63
|
+
const PROVIDER_TIMEOUT_MS = 40_000;
|
|
64
|
+
const PROVIDER_DEADLINE_MS = 55_000;
|
|
65
|
+
/**
|
|
66
|
+
* 把 catch 抓到的未知值收窄成「有 message 的错误」。
|
|
67
|
+
*
|
|
68
|
+
* 严格模式下 catch 的绑定推断不出 `.message`(它被推成一个空对象类型),
|
|
69
|
+
* 而抛出来的东西什么形状都可能是:Error、字符串、带 code 的 Node 错误。
|
|
70
|
+
* 直接读 `.message` 在类型层面被拒绝,在运行层面则对字符串抛异常得出一片空白。
|
|
71
|
+
*/
|
|
72
|
+
function caughtMessage(error) {
|
|
73
|
+
if (error !== null && typeof error === 'object' && 'message' in error) {
|
|
74
|
+
const message = error.message;
|
|
75
|
+
if (typeof message === 'string')
|
|
76
|
+
return message;
|
|
77
|
+
}
|
|
78
|
+
return String(error);
|
|
79
|
+
}
|
|
80
|
+
/** 读取 catch 变量上的 `code`(Node 的 ENOENT 之类),没有就返回空串。 */
|
|
81
|
+
function caughtCode(error) {
|
|
82
|
+
if (error !== null && typeof error === 'object' && 'code' in error) {
|
|
83
|
+
const code = error.code;
|
|
84
|
+
if (typeof code === 'string')
|
|
85
|
+
return code;
|
|
86
|
+
}
|
|
87
|
+
return '';
|
|
88
|
+
}
|
|
89
|
+
export const name = 'modsearch';
|
|
90
|
+
export const inject = ['tools', 'web'];
|
|
91
|
+
/** 包根目录。本文件在 dsh/ 下,所以上一层就是包根。 */
|
|
92
|
+
const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
93
|
+
/** Claude Code mod 需要落地的文件,相对 `claude/` 源目录。 */
|
|
94
|
+
const CLAUDE_MOD_FILES = [
|
|
95
|
+
'SKILL.md',
|
|
96
|
+
join('.claude-plugin', 'plugin.json'),
|
|
97
|
+
join('hooks', 'hooks.json'),
|
|
98
|
+
join('hooks', 'register.ts'),
|
|
99
|
+
'tsconfig.json',
|
|
100
|
+
];
|
|
101
|
+
/** 读一个文件,读不到返回 undefined。 */
|
|
102
|
+
function slurp(file) {
|
|
103
|
+
try {
|
|
104
|
+
return readFileSync(file, 'utf-8');
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Claude Code mod 的接入状态。
|
|
112
|
+
*
|
|
113
|
+
* 目录里可能有用户自己加的东西,所以这里只按「应有文件清单」逐项比对,
|
|
114
|
+
* 不做整目录扫描:多出来的文件与我们无关,缺了或旧了才是我们要报的。
|
|
115
|
+
*
|
|
116
|
+
* 关闭时**不删目录**,所以这里读到的可能是「装好了但开关关着」——那是一份
|
|
117
|
+
* 完全合法的状态,由 `hosts.claudeCode.enabled` 表达,不是这里的事。
|
|
118
|
+
*/
|
|
119
|
+
function claudeHostStatus() {
|
|
120
|
+
const target = join(homedir(), '.claude', 'skills', 'searchfuse-mod');
|
|
121
|
+
const source = join(PACKAGE_ROOT, 'claude');
|
|
122
|
+
const missing = [];
|
|
123
|
+
const stale = [];
|
|
124
|
+
let present = 0;
|
|
125
|
+
for (const relative of CLAUDE_MOD_FILES) {
|
|
126
|
+
const current = slurp(join(target, relative));
|
|
127
|
+
if (current === undefined) {
|
|
128
|
+
missing.push(relative);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
present += 1;
|
|
132
|
+
const expected = slurp(join(source, relative));
|
|
133
|
+
if (expected !== undefined && current !== expected) {
|
|
134
|
+
stale.push(relative);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { installed: present > 0, stale, missing };
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* omp 扩展的接入状态。
|
|
141
|
+
*
|
|
142
|
+
* 「装了但旧了」是最容易骗人的一种:文件明明在,行为却还是旧的 ——
|
|
143
|
+
* 与 pnpm 把 `file:` 依赖复制成快照是同一类陷阱。所以内容比对单独报一栏。
|
|
144
|
+
*
|
|
145
|
+
* **比对前必须先把模板渲染一遍**,理由与 `src/hosts.ts` 的 `ompStatus`
|
|
146
|
+
* 完全相同:安装时占位符会被换成真实路径,拿模板原文比会让每一次正确的
|
|
147
|
+
* 安装都显示成陈旧。
|
|
148
|
+
*/
|
|
149
|
+
function ompHostStatus() {
|
|
150
|
+
const file = join(homedir(), '.omp', 'agent', 'extensions', 'searchfuse.ts');
|
|
151
|
+
const source = join(PACKAGE_ROOT, 'omp', 'extension.ts');
|
|
152
|
+
const current = slurp(file);
|
|
153
|
+
const missing = current === undefined ? ['searchfuse.ts'] : [];
|
|
154
|
+
const stale = [];
|
|
155
|
+
if (current !== undefined) {
|
|
156
|
+
const template = slurp(source);
|
|
157
|
+
if (template !== undefined) {
|
|
158
|
+
const kernelPath = join(PACKAGE_ROOT, 'dist', 'kernel.js');
|
|
159
|
+
const escaped = JSON.stringify(kernelPath).slice(1, -1);
|
|
160
|
+
const expected = template.replaceAll('__SEARCHFUSE_KERNEL_PATH__', escaped);
|
|
161
|
+
if (current !== expected)
|
|
162
|
+
stale.push('searchfuse.ts');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { installed: current !== undefined, stale, missing };
|
|
166
|
+
}
|
|
167
|
+
/** 各家宿主的接入状态,供卡片显示。 */
|
|
168
|
+
function hostStatuses(config) {
|
|
169
|
+
return {
|
|
170
|
+
claudeCode: claudeHostStatus(),
|
|
171
|
+
omp: ompHostStatus(),
|
|
172
|
+
// dsh 宿主本身不需要落地文件:它就是当前这个进程,接没接上由「这个
|
|
173
|
+
// 插件有没有被加载」自己说明,不必再查一遍磁盘。
|
|
174
|
+
enabled: {
|
|
175
|
+
claudeCode: config.hosts?.claudeCode?.enabled !== false,
|
|
176
|
+
omp: config.hosts?.omp?.enabled !== false,
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
export function apply(ctx, config = {}) {
|
|
181
|
+
if (config.searchProvider !== false) {
|
|
182
|
+
registerSearchProvider(ctx, config);
|
|
183
|
+
}
|
|
184
|
+
// 两条热重载入口。它们登记在下面唯一的那套监视器上:插件自己拥有
|
|
185
|
+
// ~/.searchfuse/config.json,宿主的 profile 重载信号永远不会为它触发,所以
|
|
186
|
+
// 只能自己定时看一看。
|
|
187
|
+
const reloaders = [];
|
|
188
|
+
// MCP 服务器,在 ~/.searchfuse/config.json 的 `mcp` 下配置。协议实现作为
|
|
189
|
+
// 独立的构建模块发布,因为本文件是手写的 JavaScript,无法导入 TypeScript
|
|
190
|
+
// 源码。
|
|
191
|
+
//
|
|
192
|
+
// 所有带状态的东西都活在这个闭包里,绝不放模块作用域:在没有文件变更时,
|
|
193
|
+
// 宿主会原地重载插件而不重新求值模块,于是模块级的 session 会活得比它自己
|
|
194
|
+
// 的 fiber 更久,还会被下一代实例共享。
|
|
195
|
+
if (config.mcp !== false) {
|
|
196
|
+
reloaders.push(registerMcpTools(ctx));
|
|
197
|
+
}
|
|
198
|
+
// 以裸 JSON-Schema 工具定义的形式注册(不导入任何 dsh 包:developer-preview
|
|
199
|
+
// 注册表接受这种定义,而 @deepseek-ai/dsh-tools 的树外解析目前还不可靠),
|
|
200
|
+
// 所以本插件在 execute 内部自己负责参数校验。
|
|
201
|
+
// 默认关闭:X 搜索需要有登录状态的 Grok,在没登录的机器上它只能给出降级
|
|
202
|
+
// 答案。注册一个干不了自己活的工具,代价是模型每次请求都要带一份 schema,
|
|
203
|
+
// 以及首次尝试时的一次失败调用。引擎本身仍保持注册,于是 `doctor` 依然能
|
|
204
|
+
// 报告 Grok 是否已登录,而用户可以在它登录的那一刻立刻把这个开关打开。
|
|
205
|
+
if (config.xSearch === true) {
|
|
206
|
+
registerXSearchTool(ctx);
|
|
207
|
+
}
|
|
208
|
+
if (config.readPage !== false) {
|
|
209
|
+
registerReadPageTool(ctx);
|
|
210
|
+
}
|
|
211
|
+
// 独立引擎工具,注册在 MCP 之前:内置名字正是 MCP 服务器不该碰的,而用户
|
|
212
|
+
// 自己命名的引擎工具就属于用户。
|
|
213
|
+
if (config.engineTools !== false) {
|
|
214
|
+
reloaders.push(registerEngineTools(ctx));
|
|
215
|
+
}
|
|
216
|
+
if (reloaders.length > 0) {
|
|
217
|
+
// 唯一的监视器。文件一改,两边都看一眼;各自的签名比对决定谁真的需要重建
|
|
218
|
+
// 自己的工具,所以改 `mcp` 不会惊动引擎工具,反之亦然。
|
|
219
|
+
watchModsearchConfigFile(ctx, () => {
|
|
220
|
+
for (const reload of reloaders) {
|
|
221
|
+
try {
|
|
222
|
+
reload();
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
console.error(`[searchfuse] config reload failed: ${caughtMessage(error)}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
// 设置卡片。dsh web 用户没有终端,所以 `modsearch config set` 在那里够不着,
|
|
231
|
+
// 引擎密钥也就没有入口。浏览器那一半(dsh/client.js)贡献的卡片连的是下面
|
|
232
|
+
// 这条设置路由,而不是某个 settings schema,因为这些值住在
|
|
233
|
+
// ~/.searchfuse/config.json,与 CLI 和其他所有 harness 共用。
|
|
234
|
+
//
|
|
235
|
+
// webServer 只在 web profile 下存在,而这个 cordis 没有「可选注入」的写法,
|
|
236
|
+
// 所以两半都搭在带作用域的 ctx.inject 调用上:闭包只在服务存在的地方运行,
|
|
237
|
+
// 服务不存在的地方它根本不运行。headless profile 则原样保留插件的工具和
|
|
238
|
+
// 搜索 provider。
|
|
239
|
+
if (config.settingsCard !== false && typeof ctx.inject === 'function') {
|
|
240
|
+
ctx.inject(['webServer'], (scope) => {
|
|
241
|
+
try {
|
|
242
|
+
registerConfigRoute(scope);
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
console.error(`[searchfuse] settings card route skipped: ${error}`);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
// 从 rc.7 到 0.1.6-alpha.1,设置页是按已服务的 settings 命名空间来分发插件
|
|
249
|
+
// 卡片的:只有当卡片的槽位键匹配上宿主应答过的命名空间,卡片才会被渲染。
|
|
250
|
+
// 这里注册的命名空间是个空的透传,因为它的全部职责就是让卡片可被分发。
|
|
251
|
+
// 值仍然留在上面那条路由背后的配置文件里。schema 按这个 seam 实际会对它
|
|
252
|
+
// 调用的东西做了鸭子类型:可调用,加上 toJSON,于是本插件不需要导入任何
|
|
253
|
+
// dsh 包就能描述「什么都没有」。
|
|
254
|
+
//
|
|
255
|
+
// 0.1.6-alpha.2 把卡片挪到了 Plugins 页,按包名索引;0.1.7 又移除了注册表:
|
|
256
|
+
// 它的 settings 服务只列出 `.volatile()` 的 Config 字段,而本插件一个都没
|
|
257
|
+
// 有。没有 register 的宿主在这里没什么可服务的,于是这个命名空间被静默
|
|
258
|
+
// 跳过。
|
|
259
|
+
ctx.inject(['settings'], (scope) => {
|
|
260
|
+
if (typeof scope.settings.register !== 'function') {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
const passThrough = (value) => ({
|
|
265
|
+
...(value ?? {}),
|
|
266
|
+
});
|
|
267
|
+
passThrough.toJSON = () => ({
|
|
268
|
+
uid: 0,
|
|
269
|
+
refs: { 0: { type: 'object', meta: { default: {} }, dict: {} } },
|
|
270
|
+
});
|
|
271
|
+
scope.settings.register('modsearch', passThrough, { base: {} });
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
console.error(`[searchfuse] settings namespace skipped: ${error}`);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* web seam 的搜索能力,由 modsearch 引擎链支撑(默认 Firecrawl 免密钥、无需
|
|
281
|
+
* 注册,agy 靠登录,Tavily 和 Exa 靠密钥,带冷却感知的故障转移)。`available()`
|
|
282
|
+
* 必须保持廉价且离线,而 CLI 加上它的路由始终随包发布,所以这里返回 true,
|
|
283
|
+
* 把真实的判定留给执行阶段:一次没有可用引擎的运行会带着逐引擎的尝试清单失败,
|
|
284
|
+
* 这比在这里悄悄返回 false 要好。
|
|
285
|
+
*/
|
|
286
|
+
/**
|
|
287
|
+
* 一次 `web_search` 调用的墙钟预算。
|
|
288
|
+
*
|
|
289
|
+
* 插件配置优先,因为不同部署可能给这个值定不同的大小。其次读配置文件的
|
|
290
|
+
* `aggregate.deadlineMs`——这样用户在文件里设一个数,命令行和面向模型的工具
|
|
291
|
+
* 就都用它,而不是出现两个互相打架的数。内置默认值是三者中最宽的:在 web
|
|
292
|
+
* seam 之下,调用方是一个正在等模型回答的人,比终端能容忍更长的等待。
|
|
293
|
+
*/
|
|
294
|
+
function providerBudgets(config) {
|
|
295
|
+
const fromPlugin = {
|
|
296
|
+
timeoutMs: typeof config?.providerTimeoutMs === 'number' && config.providerTimeoutMs > 0
|
|
297
|
+
? config.providerTimeoutMs
|
|
298
|
+
: undefined,
|
|
299
|
+
deadlineMs: typeof config?.providerDeadlineMs === 'number' && config.providerDeadlineMs > 0
|
|
300
|
+
? config.providerDeadlineMs
|
|
301
|
+
: undefined,
|
|
302
|
+
};
|
|
303
|
+
let fromFile;
|
|
304
|
+
try {
|
|
305
|
+
const parsed = readModsearchConfig();
|
|
306
|
+
const configured = isPlainObject(parsed.aggregate) ? parsed.aggregate.deadlineMs : undefined;
|
|
307
|
+
if (typeof configured === 'number' && Number.isFinite(configured) && configured > 0) {
|
|
308
|
+
fromFile = configured;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
// 配置文件读不出来,并不构成让一次搜索失败的理由;下面的默认值照样能用。
|
|
313
|
+
}
|
|
314
|
+
const deadlineMs = fromPlugin.deadlineMs ?? fromFile ?? PROVIDER_DEADLINE_MS;
|
|
315
|
+
// 单引擎预算必须给最慢的引擎在整轮预算里留出余地,所以它跟着 deadline 走,
|
|
316
|
+
// 而不是变成第二个需要手动同步的数字。
|
|
317
|
+
const timeoutMs = fromPlugin.timeoutMs ?? Math.min(PROVIDER_TIMEOUT_MS, deadlineMs);
|
|
318
|
+
return { timeoutMs, deadlineMs };
|
|
319
|
+
}
|
|
320
|
+
function registerSearchProvider(ctx, config) {
|
|
321
|
+
if (typeof ctx.web?.registerSearchProvider !== 'function') {
|
|
322
|
+
// developer-preview 阶段的一次接口迁移:降级成「只有工具」的插件,但要在
|
|
323
|
+
// harness 日志里说出来,而不是无声消失。
|
|
324
|
+
console.error('[searchfuse] web seam has no registerSearchProvider; search provider skipped');
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const { timeoutMs, deadlineMs } = providerBudgets(config);
|
|
328
|
+
ctx.web.registerSearchProvider({
|
|
329
|
+
id: 'modsearch',
|
|
330
|
+
available: () => true,
|
|
331
|
+
async search(request, signal) {
|
|
332
|
+
const args = [
|
|
333
|
+
'-q',
|
|
334
|
+
request.query,
|
|
335
|
+
'--source',
|
|
336
|
+
'web',
|
|
337
|
+
'--timeout',
|
|
338
|
+
String(timeoutMs),
|
|
339
|
+
'--deadline',
|
|
340
|
+
String(deadlineMs),
|
|
341
|
+
];
|
|
342
|
+
if (typeof request.maxResults === 'number') {
|
|
343
|
+
args.push('--max-results', String(request.maxResults));
|
|
344
|
+
}
|
|
345
|
+
const entry = await runCli(args, signal);
|
|
346
|
+
const lines = [entry.summary];
|
|
347
|
+
const uncertainty = Array.isArray(entry.uncertainty) ? entry.uncertainty : [];
|
|
348
|
+
if (uncertainty.length > 0) {
|
|
349
|
+
lines.push(`Uncertain: ${uncertainty.join('; ')}`);
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
content: lines.filter(Boolean).join('\n'),
|
|
353
|
+
sources: toSources(entry.items),
|
|
354
|
+
// CLI 本身已经执行了 --max-results;seam 这边无论如何都会再封一次顶。
|
|
355
|
+
truncated: false,
|
|
356
|
+
};
|
|
357
|
+
},
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* X(Twitter)搜索:web seam 完全没有概念的那块语料。当 Grok Build 已安装且
|
|
362
|
+
* 已登录时,CLI 把请求路由给它;否则由一个 web 引擎顶替,答案被标记为降级,
|
|
363
|
+
* 于是「二手证据」在权威值里是显式的,绝不静默。
|
|
364
|
+
*/
|
|
365
|
+
function registerXSearchTool(ctx) {
|
|
366
|
+
ctx.tools.register({
|
|
367
|
+
name: 'x_search',
|
|
368
|
+
description: 'Search X (Twitter) posts through the searchfuse bridge. Use for questions about posts, threads, accounts, or discussions on X: what someone posted, reactions to an event, sentiment in a community. Returns structured evidence with a summary, per-post items with URLs, and an uncertainty list. A degraded status means X itself was unreachable and a keyless web search answered second-hand. Run `npx @wenaixi/searchfuse doctor` to inspect the resolved engines.',
|
|
369
|
+
parameters: {
|
|
370
|
+
type: 'object',
|
|
371
|
+
properties: {
|
|
372
|
+
query: {
|
|
373
|
+
type: 'string',
|
|
374
|
+
description: 'What to look for on X (accounts, topics, time bounds in plain words)',
|
|
375
|
+
},
|
|
376
|
+
max_results: {
|
|
377
|
+
type: 'number',
|
|
378
|
+
description: 'Maximum number of result items (default 8)',
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
required: ['query'],
|
|
382
|
+
},
|
|
383
|
+
output: {
|
|
384
|
+
schema: SEARCH_OUTPUT_SCHEMA,
|
|
385
|
+
render: (_args, value) => [{ type: 'text', text: renderSearchEvidence(value) }],
|
|
386
|
+
// 给原生引用卡片用的持久投影;只从权威值派生,所以回放时无需重跑任何
|
|
387
|
+
// 东西。
|
|
388
|
+
presentationMeta: (_args, value) => ({ sources: toSources(value.items) }),
|
|
389
|
+
},
|
|
390
|
+
// CLI 自己会执行 deadline;这里只是协作式的兜底。
|
|
391
|
+
timeoutMs: OWN_TOOL_BACKSTOP_MS,
|
|
392
|
+
isConcurrencySafe: () => true,
|
|
393
|
+
presentCall: (args) => ({
|
|
394
|
+
card: 'generic',
|
|
395
|
+
title: 'x_search',
|
|
396
|
+
kind: 'search',
|
|
397
|
+
rawInput: args,
|
|
398
|
+
}),
|
|
399
|
+
presentResult: (_args, result) => {
|
|
400
|
+
if (result.isError || !result.meta || !Array.isArray(result.meta.sources)) {
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
return { card: 'web', kind: 'search', sources: result.meta.sources, truncated: false };
|
|
404
|
+
},
|
|
405
|
+
async execute(args, exec) {
|
|
406
|
+
if (typeof args?.query !== 'string' || args.query.trim() === '') {
|
|
407
|
+
throw new Error('x_search needs a non-empty string "query".');
|
|
408
|
+
}
|
|
409
|
+
const cliArgs = ['-q', args.query, '--source', 'x', ...ownToolBudget()];
|
|
410
|
+
if (typeof args.max_results === 'number' && args.max_results > 0) {
|
|
411
|
+
cliArgs.push('--max-results', String(Math.floor(args.max_results)));
|
|
412
|
+
}
|
|
413
|
+
const entry = await runCli(cliArgs, exec.signal);
|
|
414
|
+
// 权威值是证据加上它的来源信息;路由细节(尝试记录、耗时、引擎消耗)
|
|
415
|
+
// 留在运行层,不进权威值。
|
|
416
|
+
return {
|
|
417
|
+
status: entry.status,
|
|
418
|
+
source: entry.source,
|
|
419
|
+
summary: entry.summary,
|
|
420
|
+
items: Array.isArray(entry.items) ? entry.items : [],
|
|
421
|
+
uncertainty: Array.isArray(entry.uncertainty) ? entry.uncertainty : [],
|
|
422
|
+
};
|
|
423
|
+
},
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* 聚焦式页面阅读:抓一个 URL 并返回证据,可选地由一个问题焦点来塑形。故意做成
|
|
428
|
+
* 独立工具,而不是 web seam 的 fetch provider:seam 的 fetch 契约是安全的原始
|
|
429
|
+
* 抓取(真实状态码、未经消化的正文),并且按设计排除了阅读焦点;而这里是
|
|
430
|
+
* LLM 处理过的阅读,带摘要、抽取后的内容、外链、不确定性清单和运行层警告。
|
|
431
|
+
* CLI 默认拦截私网目标,本工具不提供任何绕过它的方式。dsh 默认也暴露它自己的
|
|
432
|
+
* 原始 web_fetch,所以描述里点明了二者的分工。
|
|
433
|
+
*/
|
|
434
|
+
function registerReadPageTool(ctx) {
|
|
435
|
+
ctx.tools.register({
|
|
436
|
+
name: 'read_page',
|
|
437
|
+
description: 'Read one web page through the searchfuse bridge and return digested evidence: a summary, the extracted content, outgoing links, uncertainty, and operational warnings such as cloud fetching. Use it over web_fetch when you want the page digested or focused on one question (pass "query"), or when the page is rendered by JavaScript and a plain fetch returns an empty shell. Use web_fetch, where available, when you need the raw page text or the HTTP status code. Private-network URLs are blocked. Page reading needs no engine setup. Run `npx @wenaixi/searchfuse doctor` to inspect the resolved route.',
|
|
438
|
+
parameters: {
|
|
439
|
+
type: 'object',
|
|
440
|
+
properties: {
|
|
441
|
+
url: {
|
|
442
|
+
type: 'string',
|
|
443
|
+
description: 'The http(s) URL to read',
|
|
444
|
+
},
|
|
445
|
+
query: {
|
|
446
|
+
type: 'string',
|
|
447
|
+
description: 'Optional question to focus the reading on (e.g. "what are the rate limits")',
|
|
448
|
+
},
|
|
449
|
+
},
|
|
450
|
+
required: ['url'],
|
|
451
|
+
},
|
|
452
|
+
output: {
|
|
453
|
+
schema: FETCH_OUTPUT_SCHEMA,
|
|
454
|
+
render: (_args, value) => [{ type: 'text', text: renderFetchEvidence(value) }],
|
|
455
|
+
},
|
|
456
|
+
timeoutMs: OWN_TOOL_BACKSTOP_MS,
|
|
457
|
+
isConcurrencySafe: () => true,
|
|
458
|
+
presentCall: (args) => ({
|
|
459
|
+
card: 'generic',
|
|
460
|
+
title: 'read_page',
|
|
461
|
+
kind: 'fetch',
|
|
462
|
+
rawInput: args,
|
|
463
|
+
}),
|
|
464
|
+
async execute(args, exec) {
|
|
465
|
+
if (typeof args?.url !== 'string' || !/^https?:\/\//i.test(args.url.trim())) {
|
|
466
|
+
throw new Error('read_page needs an http(s) "url".');
|
|
467
|
+
}
|
|
468
|
+
const cliArgs = ['-u', args.url, ...ownToolBudget()];
|
|
469
|
+
if (typeof args.query === 'string' && args.query.trim() !== '') {
|
|
470
|
+
cliArgs.push('-q', args.query);
|
|
471
|
+
}
|
|
472
|
+
const entry = await runCli(cliArgs, exec.signal);
|
|
473
|
+
return {
|
|
474
|
+
summary: entry.summary,
|
|
475
|
+
content: typeof entry.content === 'string' ? entry.content : '',
|
|
476
|
+
...(Array.isArray(entry.links) ? { links: entry.links } : {}),
|
|
477
|
+
uncertainty: Array.isArray(entry.uncertainty) ? entry.uncertainty : [],
|
|
478
|
+
warnings: Array.isArray(entry.warnings) ? entry.warnings : [],
|
|
479
|
+
};
|
|
480
|
+
},
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
/** 给插件自有工具用的 CLI 预算参数。 */
|
|
484
|
+
function ownToolBudget() {
|
|
485
|
+
return [
|
|
486
|
+
'--timeout',
|
|
487
|
+
String(OWN_TOOL_ENGINE_TIMEOUT_MS),
|
|
488
|
+
'--deadline',
|
|
489
|
+
String(OWN_TOOL_DEADLINE_MS),
|
|
490
|
+
];
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* 跑一次 CLI,从它的 envelope 里取出那一条 source 记录。当运行失败、或该
|
|
494
|
+
* source 返回 unavailable 时抛出异常并带上逐引擎的尝试轨迹,这样 harness 的
|
|
495
|
+
* 错误信息里说的就是实际试过什么。
|
|
496
|
+
*/
|
|
497
|
+
/**
|
|
498
|
+
* 被拉起的 CLI 所需的环境。Electron 会把桌面可执行文件暴露为 process.execPath,
|
|
499
|
+
* 它的子进程必须进入 Node 模式,否则 CLI 的路径和参数会被交回给应用本身。
|
|
500
|
+
*/
|
|
501
|
+
function childEnv() {
|
|
502
|
+
return process.versions.electron ? { ...process.env, ELECTRON_RUN_AS_NODE: '1' } : process.env;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* 探一次 `/healthz`。返回是否 200。
|
|
506
|
+
*
|
|
507
|
+
* 探针必须带 `Connection: close`:服务走 keep-alive,不主动断开就会一直
|
|
508
|
+
* 等到超时,把一个健康实例误判成不通。
|
|
509
|
+
*/
|
|
510
|
+
function healthOnce(port) {
|
|
511
|
+
return new Promise((resolve) => {
|
|
512
|
+
const req = httpRequest({
|
|
513
|
+
host: '127.0.0.1',
|
|
514
|
+
port,
|
|
515
|
+
path: '/healthz',
|
|
516
|
+
method: 'GET',
|
|
517
|
+
timeout: 2000,
|
|
518
|
+
headers: { Connection: 'close' },
|
|
519
|
+
}, (res) => {
|
|
520
|
+
res.resume();
|
|
521
|
+
resolve(res.statusCode === 200);
|
|
522
|
+
});
|
|
523
|
+
req.on('error', () => resolve(false));
|
|
524
|
+
req.on('timeout', () => {
|
|
525
|
+
req.destroy();
|
|
526
|
+
resolve(false);
|
|
527
|
+
});
|
|
528
|
+
req.end();
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* 服务身份推导。**必须与 `src/serveIdentity.ts` 逐字一致。**
|
|
533
|
+
*
|
|
534
|
+
* 为什么在这里抄一份而不 import:本文件属于 dsh 的独立构建(rootDir="dsh"),
|
|
535
|
+
* 产物要能脱离 `src/` 单独分发。三份拷贝(src / dsh / claude)任何一份漂移,
|
|
536
|
+
* 都会造成「服务绑一个端口、客户端去探另一个」的错配,且症状与「服务没起来」
|
|
537
|
+
* 一模一样。`src/serveIdentity.parity.test.ts` 锁住三者一致——那是唯一的
|
|
538
|
+
* 防漂移手段。
|
|
539
|
+
*/
|
|
540
|
+
const IDENTITY_PORT_BASE = 42000;
|
|
541
|
+
const IDENTITY_PORT_SPAN = 8;
|
|
542
|
+
/**
|
|
543
|
+
* 用 realpathSync 而不是 resolve:Windows 上 `C:\Users\Administrator` 与
|
|
544
|
+
* `C:\Users\ADMINI~1`(8.3 短名)是同一个目录,junction 与它的目标也是。
|
|
545
|
+
* 用 resolve 会给出两组指纹,同一份状态被认成两个身份。目录不存在时退回
|
|
546
|
+
* resolve——那种情况下没有「另一个写法」可言。
|
|
547
|
+
*/
|
|
548
|
+
function identityFingerprintOf(stateDir) {
|
|
549
|
+
let resolved;
|
|
550
|
+
try {
|
|
551
|
+
resolved = realpathSync(stateDir);
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
resolved = resolve(stateDir);
|
|
555
|
+
}
|
|
556
|
+
return createHash('sha256').update(resolved.toLowerCase()).digest('hex').slice(0, 8);
|
|
557
|
+
}
|
|
558
|
+
function identityCandidatePorts(fingerprint) {
|
|
559
|
+
const seed = Number.parseInt(fingerprint, 16);
|
|
560
|
+
const base = IDENTITY_PORT_BASE + (seed % 2_000);
|
|
561
|
+
const ports = [];
|
|
562
|
+
for (let i = 0; i < IDENTITY_PORT_SPAN; i += 1) {
|
|
563
|
+
ports.push(base + i);
|
|
564
|
+
}
|
|
565
|
+
return ports;
|
|
566
|
+
}
|
|
567
|
+
function identityOfHome(home) {
|
|
568
|
+
const fingerprint = identityFingerprintOf(join(home, '.searchfuse'));
|
|
569
|
+
return { fingerprint, ports: identityCandidatePorts(fingerprint) };
|
|
570
|
+
}
|
|
571
|
+
/** 读 `/identity`,拿到服务自称的指纹。 */
|
|
572
|
+
function identityOnce(port) {
|
|
573
|
+
return new Promise((resolve) => {
|
|
574
|
+
const req = httpRequest({ host: '127.0.0.1', port, path: '/identity', method: 'GET', timeout: 2000, headers: { Connection: 'close' } }, (res) => {
|
|
575
|
+
if (res.statusCode !== 200) {
|
|
576
|
+
res.resume();
|
|
577
|
+
resolve(undefined);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
let body = '';
|
|
581
|
+
res.on('data', (chunk) => {
|
|
582
|
+
body += chunk;
|
|
583
|
+
});
|
|
584
|
+
res.on('end', () => {
|
|
585
|
+
try {
|
|
586
|
+
const parsed = JSON.parse(body);
|
|
587
|
+
resolve(isPlainObject(parsed) && typeof parsed.fingerprint === 'string' ? parsed.fingerprint : undefined);
|
|
588
|
+
}
|
|
589
|
+
catch {
|
|
590
|
+
resolve(undefined);
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
});
|
|
594
|
+
req.on('error', () => resolve(undefined));
|
|
595
|
+
req.on('timeout', () => {
|
|
596
|
+
req.destroy();
|
|
597
|
+
resolve(undefined);
|
|
598
|
+
});
|
|
599
|
+
req.end();
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* 按候选端口找回属于这份 `.searchfuse` 的服务。
|
|
604
|
+
*
|
|
605
|
+
* runtime.json 会在服务被 kill 时消失(close 跑不到),所以它不能是唯一凭证。
|
|
606
|
+
* 必须校验指纹:只看 `/healthz` 200 会把恰好占着候选端口的别的程序认成自己的。
|
|
607
|
+
*
|
|
608
|
+
* 指纹一旦匹配就**停止探测**:那一份 `.searchfuse` 的服务就在这个端口,
|
|
609
|
+
* 后面的候选不可能再是它。token 读不到时直接返回 undefined(调用方回退
|
|
610
|
+
* 子进程),而不是继续白探剩下七个端口。
|
|
611
|
+
*/
|
|
612
|
+
async function discoverServeRuntime() {
|
|
613
|
+
const identity = identityOfHome(homedir());
|
|
614
|
+
for (const port of identity.ports) {
|
|
615
|
+
if ((await identityOnce(port)) !== identity.fingerprint)
|
|
616
|
+
continue;
|
|
617
|
+
// 与 src/serveEnsure.ts 的 discoverServe 同一顺序:文件里记的端口若与
|
|
618
|
+
// 探测到的一致,直接用它的 token(省一次读);否则读 token 文件。
|
|
619
|
+
const fromFile = readServeRuntime();
|
|
620
|
+
if (fromFile !== undefined && fromFile.port === port)
|
|
621
|
+
return fromFile;
|
|
622
|
+
const fileToken = readServeTokenFile();
|
|
623
|
+
return fileToken === undefined ? undefined : { port, token: fileToken };
|
|
624
|
+
}
|
|
625
|
+
return undefined;
|
|
626
|
+
}
|
|
627
|
+
/** 读 token 文件。服务端与客户端共用同一份。 */
|
|
628
|
+
function readServeTokenFile() {
|
|
629
|
+
try {
|
|
630
|
+
const token = readFileSync(join(homedir(), '.searchfuse', 'serve-token'), 'utf-8').trim();
|
|
631
|
+
return token === '' ? undefined : token;
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return undefined;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* 拉起本地服务:跑 `serve --ensure`。
|
|
639
|
+
*
|
|
640
|
+
* 就绪的判据是 `/healthz` 通过,不是子进程退出码。实测:`serve --ensure`
|
|
641
|
+
* 只在「已经在跑」时以 0 退出;真正需要起服务时它会把服务拉起来并**常驻**,
|
|
642
|
+
* 永远等不到 close。等退出码会一路等到超时,然后杀掉刚起来的那个服务。
|
|
643
|
+
* 所以 spawn 之后就把子进程交出去(detached + unref),改为轮询健康检查。
|
|
644
|
+
*
|
|
645
|
+
* CLI 路径从 `PACKAGE_ROOT` 推,不假设与源码树同构——插件在 pnpm 的快照里
|
|
646
|
+
* 运行时,`../dist/main.js` 指向的是快照内的副本,那正是要用的那份。
|
|
647
|
+
*
|
|
648
|
+
* `SEARCHFUSE_SERVE_CLI` 可以让测试注入一个假 CLI:路由的 handler 没有
|
|
649
|
+
* 参数可传,而真 CLI 会留下一个常驻服务,测试不能那么干。
|
|
650
|
+
*
|
|
651
|
+
* `MODSEARCH_DSH_CLI` 是给用户/测试覆盖「CLI 该从哪找」的老通道,优先级
|
|
652
|
+
* 高于默认路径。删掉 `cliPath()` 时差点把它一起砍掉——那是既有能力,
|
|
653
|
+
* 不是死代码(`src/dshPlugin.test.ts` 靠它注入一个缺失路径来验重装提示)。
|
|
654
|
+
*/
|
|
655
|
+
async function startServe(cliPath = process.env.SEARCHFUSE_SERVE_CLI ??
|
|
656
|
+
process.env.MODSEARCH_DSH_CLI ??
|
|
657
|
+
join(PACKAGE_ROOT, 'dist', 'main.js')) {
|
|
658
|
+
// 服务已经在跑:不 spawn,直接确认。这条与 `src/serveEnsure.ts` 的
|
|
659
|
+
// 第 1、2 步必须一致——否则服务在跑时点「拉起」会白起一个子进程。
|
|
660
|
+
// 这里要探健康(与 tryServe 的判据不同):拉起动作的「已在跑」必须以
|
|
661
|
+
// 真的能应答为准,文件写着端口但服务已死时必须重新拉起。
|
|
662
|
+
const already = readServeRuntime();
|
|
663
|
+
if (already !== undefined && (await healthOnce(already.port))) {
|
|
664
|
+
return { started: false, port: already.port };
|
|
665
|
+
}
|
|
666
|
+
// 文件不在时,靠目录指纹把还活着的服务认回来(同 tryServe 的第二级)。
|
|
667
|
+
const discovered = already === undefined ? await discoverServeRuntime() : undefined;
|
|
668
|
+
if (discovered !== undefined && (await healthOnce(discovered.port))) {
|
|
669
|
+
return { started: false, port: discovered.port };
|
|
670
|
+
}
|
|
671
|
+
// 只有 npm 包才带 dist/:从 GitHub 源码安装(DSH 的添加对话框接受仓库 URL)
|
|
672
|
+
// 没有构建产物,此时 Node 打印的那句光秃秃的 "Cannot find module" 没指出
|
|
673
|
+
// 任何出路。在这里提前给一句能照着做的指示,比让 spawn 失败更有用。
|
|
674
|
+
if (!existsSync(cliPath)) {
|
|
675
|
+
return {
|
|
676
|
+
started: false,
|
|
677
|
+
reason: `searchfuse's CLI build is missing (${cliPath}). This happens when the plugin was ` +
|
|
678
|
+
'installed from its GitHub repository, which ships source only. Remove the ' +
|
|
679
|
+
'plugin and add it again by package name: @wenaixi/searchfuse',
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
let spawnError;
|
|
683
|
+
let exitedEarly;
|
|
684
|
+
try {
|
|
685
|
+
const child = spawnHidden('node', [cliPath, 'serve', '--ensure'], {
|
|
686
|
+
stdio: 'ignore',
|
|
687
|
+
// 让服务脱离父进程的会话:dsh 宿主退出时不该把服务带走。
|
|
688
|
+
detached: true,
|
|
689
|
+
});
|
|
690
|
+
child.unref();
|
|
691
|
+
child.on('error', (error) => {
|
|
692
|
+
spawnError = error;
|
|
693
|
+
});
|
|
694
|
+
child.on('close', (code) => {
|
|
695
|
+
exitedEarly = code === null ? undefined : code;
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
// spawn 本身同步抛出的情况。
|
|
700
|
+
return { started: false, reason: caughtMessage(error) };
|
|
701
|
+
}
|
|
702
|
+
const deadline = Date.now() + SERVE_ENSURE_TIMEOUT_MS;
|
|
703
|
+
for (;;) {
|
|
704
|
+
if (spawnError !== undefined) {
|
|
705
|
+
return { started: false, reason: caughtMessage(spawnError) };
|
|
706
|
+
}
|
|
707
|
+
// 非 0 退出是明确的启动失败,立刻收手;退出 0 不作终局,让健康检查说了算。
|
|
708
|
+
if (exitedEarly !== undefined && exitedEarly !== 0) {
|
|
709
|
+
return { started: false, reason: `serve --ensure exited ${exitedEarly}` };
|
|
710
|
+
}
|
|
711
|
+
const probe = readServeRuntime();
|
|
712
|
+
if (probe !== undefined && (await healthOnce(probe.port))) {
|
|
713
|
+
return { started: true, port: probe.port };
|
|
714
|
+
}
|
|
715
|
+
if (Date.now() >= deadline) {
|
|
716
|
+
return { started: false, reason: `serve did not become healthy within ${SERVE_ENSURE_TIMEOUT_MS} ms` };
|
|
717
|
+
}
|
|
718
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* 本地服务在不在。
|
|
723
|
+
*
|
|
724
|
+
* 只报状态,不报诊断原文:卡片要的是一个答案。
|
|
725
|
+
*/
|
|
726
|
+
async function serveStatus() {
|
|
727
|
+
const existing = readServeRuntime();
|
|
728
|
+
if (existing === undefined)
|
|
729
|
+
return { running: false };
|
|
730
|
+
return (await healthOnce(existing.port))
|
|
731
|
+
? { running: true, port: existing.port }
|
|
732
|
+
: { running: false };
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* 读本地服务的运行时信息:`~/.searchfuse/runtime.json`。
|
|
736
|
+
*
|
|
737
|
+
* 返回 undefined 表示服务没起(文件不在、读不了、或不是我们要的形状)。
|
|
738
|
+
* 调用方据此回退到子进程。
|
|
739
|
+
*
|
|
740
|
+
* 端口必须是整数:`typeof === 'number'` 会放过 `3.5` 与 `NaN`,拿它们去连
|
|
741
|
+
* 只会得到一个模棱两可的连接错误。判据与 `src/serveEnsure.ts` 的同名逻辑
|
|
742
|
+
* 必须一致——两处得出两种答案的话,卡片与运行时就会互相撒谎。
|
|
743
|
+
*/
|
|
744
|
+
function readServeRuntime() {
|
|
745
|
+
const file = join(homedir(), '.searchfuse', 'runtime.json');
|
|
746
|
+
let raw;
|
|
747
|
+
try {
|
|
748
|
+
raw = readFileSync(file, 'utf8');
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
return undefined;
|
|
752
|
+
}
|
|
753
|
+
let parsed;
|
|
754
|
+
try {
|
|
755
|
+
parsed = JSON.parse(raw);
|
|
756
|
+
}
|
|
757
|
+
catch {
|
|
758
|
+
return undefined;
|
|
759
|
+
}
|
|
760
|
+
if (!isPlainObject(parsed))
|
|
761
|
+
return undefined;
|
|
762
|
+
if (typeof parsed.port !== 'number' || !Number.isInteger(parsed.port))
|
|
763
|
+
return undefined;
|
|
764
|
+
if (typeof parsed.token !== 'string' || parsed.token === '')
|
|
765
|
+
return undefined;
|
|
766
|
+
return { port: parsed.port, token: parsed.token };
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* 服务的两级定位:文件优先,候选探测兜底。
|
|
770
|
+
*
|
|
771
|
+
* 顺序有讲究:**文件里写的端口优先且不先探健康**。
|
|
772
|
+
*
|
|
773
|
+
* 早先这里是「先 healthOnce 再返回」。那样有个隐蔽的退化:服务活着但
|
|
774
|
+
* `/healthz` 恰好不通(或桩服务只实现业务端点时),会被判成「服务不存在」,
|
|
775
|
+
* 于是回退去 spawn kernel——本来该得到的错误正文(服务端逐引擎的尝试轨迹)
|
|
776
|
+
* 就此消失,用户看到的是「不可达」而不是真实原因。
|
|
777
|
+
*
|
|
778
|
+
* 所以判据是:文件存在且形状合法就认它,把「它到底通不通」交给真正的
|
|
779
|
+
* 请求去答。只有**文件不在**时才需要候选探测——那才是「服务被 kill、
|
|
780
|
+
* close 跑不到、文件消失」的场景。
|
|
781
|
+
*/
|
|
782
|
+
async function locateServeRuntime() {
|
|
783
|
+
const fromFile = readServeRuntime();
|
|
784
|
+
if (fromFile !== undefined)
|
|
785
|
+
return fromFile;
|
|
786
|
+
return discoverServeRuntime();
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* 取一次搜索结果:**服务优先,子进程兜底**。
|
|
790
|
+
*
|
|
791
|
+
* 为什么要两条:服务在跑时省掉一次 Node 启动(约 200ms);服务不在时
|
|
792
|
+
* 用户仍然能搜。只走一条就等于把可用性押在另一件事上。
|
|
793
|
+
*/
|
|
794
|
+
/**
|
|
795
|
+
* 把一份 CLI 风格的参数表翻译成服务端路由。
|
|
796
|
+
*
|
|
797
|
+
* 短式(`-q`/`-u`)与长式(`--query`/`--url`)都认:插件自有工具用的是短式,
|
|
798
|
+
* 而 provider seam 走的是长式;按位置下标取参数则会读到 flag 本身。
|
|
799
|
+
*/
|
|
800
|
+
function toServeRequest(args) {
|
|
801
|
+
const flag = (...names) => {
|
|
802
|
+
for (const name of names) {
|
|
803
|
+
const index = args.indexOf(name);
|
|
804
|
+
if (index !== -1)
|
|
805
|
+
return args[index + 1];
|
|
806
|
+
}
|
|
807
|
+
return undefined;
|
|
808
|
+
};
|
|
809
|
+
// 预算对搜索和读页都一样适用,所以先收好,两条路由各自带上。
|
|
810
|
+
const budgets = new URLSearchParams();
|
|
811
|
+
const timeout = flag('--timeout');
|
|
812
|
+
if (timeout !== undefined)
|
|
813
|
+
budgets.set('timeout', timeout);
|
|
814
|
+
const deadline = flag('--deadline');
|
|
815
|
+
if (deadline !== undefined)
|
|
816
|
+
budgets.set('deadline', deadline);
|
|
817
|
+
const withBudgets = (params) => {
|
|
818
|
+
for (const [key, value] of budgets)
|
|
819
|
+
params.set(key, value);
|
|
820
|
+
return params;
|
|
821
|
+
};
|
|
822
|
+
const url = flag('-u', '--url');
|
|
823
|
+
if (url !== undefined) {
|
|
824
|
+
return { endpoint: '/v1/read-page', params: withBudgets(new URLSearchParams({ url })) };
|
|
825
|
+
}
|
|
826
|
+
const query = flag('-q', '--query');
|
|
827
|
+
if (query === undefined)
|
|
828
|
+
return undefined;
|
|
829
|
+
const params = withBudgets(new URLSearchParams({ q: query, source: flag('--source') ?? 'web' }));
|
|
830
|
+
const max = flag('--max-results');
|
|
831
|
+
if (max !== undefined)
|
|
832
|
+
params.set('max', max);
|
|
833
|
+
return { endpoint: '/v1/search', params };
|
|
834
|
+
}
|
|
835
|
+
/** 调一次服务;拿到文本就返回,否则 undefined。 */
|
|
836
|
+
async function tryServe(args, signal) {
|
|
837
|
+
const runtime = await locateServeRuntime();
|
|
838
|
+
if (runtime === undefined)
|
|
839
|
+
return undefined;
|
|
840
|
+
const request = toServeRequest(args);
|
|
841
|
+
if (request === undefined)
|
|
842
|
+
return undefined;
|
|
843
|
+
// 一次聚合可能要几十秒,所以给足时间;但必须有上限,否则服务卡住时
|
|
844
|
+
// 这次工具调用会永久挂起,只能靠宿主信号兜底。
|
|
845
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
846
|
+
const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
|
|
847
|
+
try {
|
|
848
|
+
const url = `http://127.0.0.1:${runtime.port}${request.endpoint}?${request.params.toString()}`;
|
|
849
|
+
const response = await fetch(url, {
|
|
850
|
+
headers: { authorization: `Bearer ${runtime.token}`, accept: 'application/json' },
|
|
851
|
+
signal: combined,
|
|
852
|
+
});
|
|
853
|
+
const body = await response.text();
|
|
854
|
+
if (response.ok)
|
|
855
|
+
return body;
|
|
856
|
+
// 服务端 5xx 的正文里带着逐引擎的尝试轨迹(例如谁没登录、谁超时)。
|
|
857
|
+
// 把它原样抛出去,宿主的错误信息才说得出实际试过什么;若服务端回的是
|
|
858
|
+
// 空正文或非 JSON,就交给上层按「不可达」处理。
|
|
859
|
+
if (response.status >= 500 && body.trim() !== '') {
|
|
860
|
+
throw new Error(describeServeFailure(response.status, body));
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
catch (error) {
|
|
864
|
+
if (error instanceof Error && error.message.startsWith(SERVE_FAILURE_PREFIX)) {
|
|
865
|
+
throw error;
|
|
866
|
+
}
|
|
867
|
+
// 连接被拒或超时:交给上层决定下一步。
|
|
868
|
+
}
|
|
869
|
+
return undefined;
|
|
870
|
+
}
|
|
871
|
+
/** 一句前缀,用来把「服务端的业务错误」与「连不上」区分开。 */
|
|
872
|
+
const SERVE_FAILURE_PREFIX = 'searchfuse service error: ';
|
|
873
|
+
/** 把服务端的错误正文转成宿主可读的消息。 */
|
|
874
|
+
function describeServeFailure(status, body) {
|
|
875
|
+
let detail = body.trim();
|
|
876
|
+
try {
|
|
877
|
+
const parsed = JSON.parse(body);
|
|
878
|
+
if (isPlainObject(parsed) && typeof parsed.error === 'string') {
|
|
879
|
+
detail = parsed.error;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
catch {
|
|
883
|
+
// 不是 JSON:正文本身就是那句话。
|
|
884
|
+
}
|
|
885
|
+
return `${SERVE_FAILURE_PREFIX}${status} ${detail.slice(0, 600)}`;
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* 唤醒服务:把它拉起来并确认 healthy。
|
|
889
|
+
*
|
|
890
|
+
* **绝不能等 `serve --ensure` 的退出码。** 那是 2026-11-25 现场验证过的
|
|
891
|
+
* 事故根因:`serve --ensure` 在服务不在跑时会拉起服务并**常驻不退出**,
|
|
892
|
+
* 而 `run()` 会一直等到超时;超时中断的只是这个等待,**子进程没被杀**,
|
|
893
|
+
* 于是每失败一次就留下一个僵尸 node 进程。118 个僵尸、3719 MB 私有内存、
|
|
894
|
+
* 118 个监听端口,就是这么一个个攒出来的。
|
|
895
|
+
*
|
|
896
|
+
* 唯一的实现是 `startServe()`:spawn 出 detached + unref 的常驻子进程
|
|
897
|
+
* 就撒手,再用 `/healthz` 轮询到它就绪。这里只是给它一个不带 CLI 覆盖的
|
|
898
|
+
* 入口,供搜索路径调用。
|
|
899
|
+
*
|
|
900
|
+
* 返回是否**这次真的把它拉起来了**(供上层的重试判断)。
|
|
901
|
+
*/
|
|
902
|
+
async function wakeServe(signal) {
|
|
903
|
+
// **不能把 `cliPath()` 的结果传进去。** 它指向 `dist/kernel.js`(搜索内核,
|
|
904
|
+
// 只接受 `--query` / `--url`),而 `serve --ensure` 是 `dist/main.js` 的子命令。
|
|
905
|
+
// 2026-11-25 实测:把 kernel.js 当 CLI 传过去,等于执行
|
|
906
|
+
// `node dist/kernel.js serve --ensure`,kernel 不认识 `serve`,报错退出,
|
|
907
|
+
// 第三级兜底从来没真正起过服务。`startServe` 的默认参数就是 main.js,
|
|
908
|
+
// 所以这里不传任何 CLI 覆盖。
|
|
909
|
+
if (signal?.aborted === true)
|
|
910
|
+
return { woke: false };
|
|
911
|
+
try {
|
|
912
|
+
const outcome = await startServe();
|
|
913
|
+
if (outcome.port !== undefined)
|
|
914
|
+
return { woke: true };
|
|
915
|
+
// 没起来:把失败原因带上去,让上层能区分「构建缺失」(可行动的重装指示)
|
|
916
|
+
// 与「服务连不上」(去跑 doctor)。丢掉 reason 会把前者降级成后者。
|
|
917
|
+
return { woke: false, reason: outcome.reason };
|
|
918
|
+
}
|
|
919
|
+
catch (error) {
|
|
920
|
+
return { woke: false, reason: error instanceof Error ? error.message : String(error) };
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* 取一次搜索结果。**两级**:HTTP -> 唤醒并重试。
|
|
925
|
+
*
|
|
926
|
+
* 没有第三级「搜完就 spawn 一个一次性 kernel」。那条路会绕过服务,
|
|
927
|
+
* 也让三宿主本来共享的缓存与冷却状态失去意义;而且它是一个并行的
|
|
928
|
+
* 第二实现——同一个查询在这里有两套代码路径,出问题时很难判断
|
|
929
|
+
* 到底走的哪一套。服务起不来就如实报错,把故障暴露出来,而不是
|
|
930
|
+
* 悄悄退化成另一种行为。
|
|
931
|
+
*
|
|
932
|
+
* 唤醒本身要起一个进程(`serve --ensure`),这是服务的入口,不是
|
|
933
|
+
* 兜底的重复实现。
|
|
934
|
+
*/
|
|
935
|
+
async function fetchOrSpawn(args, signal) {
|
|
936
|
+
const first = await tryServe(args, signal);
|
|
937
|
+
if (first !== undefined)
|
|
938
|
+
return first;
|
|
939
|
+
const woke = await wakeServe(signal);
|
|
940
|
+
if (woke.woke) {
|
|
941
|
+
const second = await tryServe(args, signal);
|
|
942
|
+
if (second !== undefined)
|
|
943
|
+
return second;
|
|
944
|
+
}
|
|
945
|
+
// **构建缺失是可行动的,不能降级成一句「去跑 doctor」。**
|
|
946
|
+
// 从 GitHub 源码安装的插件没有 dist/,用户看到「服务连不上」会一头雾水;
|
|
947
|
+
// 「重装成包名」才是那条出路。这条 reason 由 startServe 在 spawn 之前给出。
|
|
948
|
+
if (woke.reason !== undefined && woke.reason.includes('build is missing')) {
|
|
949
|
+
throw new Error(woke.reason);
|
|
950
|
+
}
|
|
951
|
+
throw new Error('searchfuse service is not reachable and could not be started. ' +
|
|
952
|
+
'Run `npx @wenaixi/searchfuse serve --ensure` in a terminal to see why, ' +
|
|
953
|
+
'then `npx @wenaixi/searchfuse doctor` to check the engine setup.');
|
|
954
|
+
}
|
|
955
|
+
async function runCli(args, signal) {
|
|
956
|
+
const stdout = await fetchOrSpawn(args, signal);
|
|
957
|
+
let parsed;
|
|
958
|
+
try {
|
|
959
|
+
parsed = JSON.parse(stdout);
|
|
960
|
+
}
|
|
961
|
+
catch {
|
|
962
|
+
throw new Error(`modsearch produced no JSON: ${stdout.trim().slice(0, 300)}`);
|
|
963
|
+
}
|
|
964
|
+
const entry = Array.isArray(parsed.results) ? parsed.results[0] : undefined;
|
|
965
|
+
if (!entry || typeof entry.summary !== 'string') {
|
|
966
|
+
throw new Error('modsearch returned an envelope without a usable source entry');
|
|
967
|
+
}
|
|
968
|
+
if (entry.status === 'unavailable') {
|
|
969
|
+
const attempts = (Array.isArray(entry.attempts) ? entry.attempts : [])
|
|
970
|
+
.map((attempt) => `${attempt.engine}: ${attempt.error ?? 'skipped'}`)
|
|
971
|
+
.join('; ');
|
|
972
|
+
throw new Error(`modsearch could not reach the requested source${attempts ? ` (${attempts})` : ''}. ` +
|
|
973
|
+
'Run `npx @wenaixi/searchfuse doctor` in a terminal to check the engine setup.');
|
|
974
|
+
}
|
|
975
|
+
return entry;
|
|
976
|
+
}
|
|
977
|
+
/** 把 CLI 的结果条目映射成 seam 的可引用来源结构,顺手丢掉垃圾项。 */
|
|
978
|
+
function toSources(items) {
|
|
979
|
+
if (!Array.isArray(items)) {
|
|
980
|
+
return [];
|
|
981
|
+
}
|
|
982
|
+
return items
|
|
983
|
+
.filter((item) => item && typeof item.url === 'string' && item.url !== '')
|
|
984
|
+
.map((item) => ({
|
|
985
|
+
url: item.url,
|
|
986
|
+
...(typeof item.title === 'string' && item.title !== '' ? { title: item.title } : {}),
|
|
987
|
+
...(typeof item.snippet === 'string' && item.snippet !== '' ? { snippet: item.snippet } : {}),
|
|
988
|
+
...(typeof item.published_at === 'string' && item.published_at !== ''
|
|
989
|
+
? { publishedAt: item.published_at }
|
|
990
|
+
: {}),
|
|
991
|
+
}));
|
|
992
|
+
}
|
|
993
|
+
function renderSearchEvidence(value) {
|
|
994
|
+
const lines = [];
|
|
995
|
+
if (value.status === 'degraded') {
|
|
996
|
+
lines.push(`[X was unreachable; a ${value.source} search answered second-hand. Treat as indirect evidence.]`);
|
|
997
|
+
}
|
|
998
|
+
lines.push(value.summary);
|
|
999
|
+
const items = value.items ?? [];
|
|
1000
|
+
if (items.length > 0) {
|
|
1001
|
+
lines.push('', 'Results:');
|
|
1002
|
+
items.forEach((item, index) => {
|
|
1003
|
+
const dated = item.published_at ? ` (${item.published_at})` : '';
|
|
1004
|
+
lines.push(`${index + 1}. ${item.title}${dated} — ${item.url}`);
|
|
1005
|
+
if (item.snippet) {
|
|
1006
|
+
lines.push(` ${item.snippet}`);
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
const uncertainty = value.uncertainty ?? [];
|
|
1011
|
+
if (uncertainty.length > 0) {
|
|
1012
|
+
lines.push('', `Uncertain: ${uncertainty.join('; ')}`);
|
|
1013
|
+
}
|
|
1014
|
+
return lines.join('\n');
|
|
1015
|
+
}
|
|
1016
|
+
const RENDER_CONTENT_CAP = 20_000;
|
|
1017
|
+
const RENDER_LINK_CAP = 20;
|
|
1018
|
+
function renderFetchEvidence(value) {
|
|
1019
|
+
const lines = [value.summary];
|
|
1020
|
+
const content = value.content?.trim();
|
|
1021
|
+
if (content) {
|
|
1022
|
+
lines.push('', 'Content:', content.length > RENDER_CONTENT_CAP ? `${content.slice(0, RENDER_CONTENT_CAP)}…` : content);
|
|
1023
|
+
}
|
|
1024
|
+
const links = Array.isArray(value.links) ? value.links.slice(0, RENDER_LINK_CAP) : [];
|
|
1025
|
+
if (links.length > 0) {
|
|
1026
|
+
lines.push('', 'Links:');
|
|
1027
|
+
for (const link of links) {
|
|
1028
|
+
lines.push(`- ${link.text} — ${link.url}`);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
const uncertainty = value.uncertainty ?? [];
|
|
1032
|
+
if (uncertainty.length > 0) {
|
|
1033
|
+
lines.push('', `Uncertain: ${uncertainty.join('; ')}`);
|
|
1034
|
+
}
|
|
1035
|
+
const warnings = value.warnings ?? [];
|
|
1036
|
+
if (warnings.length > 0) {
|
|
1037
|
+
lines.push('', `Warnings: ${warnings.join('; ')}`);
|
|
1038
|
+
}
|
|
1039
|
+
return lines.join('\n');
|
|
1040
|
+
}
|
|
1041
|
+
// ---------------------------------------------------------------------------
|
|
1042
|
+
// 设置卡片,宿主这一半:它读写 ~/.searchfuse/config.json,也就是 CLI 编辑的
|
|
1043
|
+
// 同一个文件,所以在浏览器里设的密钥,就是其他每个 harness 用的密钥。浏览器
|
|
1044
|
+
// 永远收不到密钥本身,只会收到「有没有存过」。
|
|
1045
|
+
// ---------------------------------------------------------------------------
|
|
1046
|
+
/** 本插件自己注册的工具名。MCP 服务器不得占用其中之一:一次静默覆盖会把
|
|
1047
|
+
* 内置工具替换成第三方服务器随便起的名字。
|
|
1048
|
+
*/
|
|
1049
|
+
const BASE_TOOL_NAMES = ['x_search', 'read_page'];
|
|
1050
|
+
/** 配置提升为独立工具的每个引擎,按它们注册时的名字。每次新鲜读取,使保存的
|
|
1051
|
+
* 改动在下一次加载时生效。 */
|
|
1052
|
+
function engineToolNames() {
|
|
1053
|
+
try {
|
|
1054
|
+
const config = readModsearchConfig();
|
|
1055
|
+
const engines = (isPlainObject(config.engines) ? config.engines : {});
|
|
1056
|
+
return Object.entries(engines)
|
|
1057
|
+
.filter(([, rawSettings]) => {
|
|
1058
|
+
const settings = rawSettings;
|
|
1059
|
+
return (isPlainObject(settings) &&
|
|
1060
|
+
isPlainObject(settings.expose) &&
|
|
1061
|
+
settings.expose.tool === true &&
|
|
1062
|
+
// 与 registerEngineTools 遵循的规则相同:被关掉的引擎不是工具,所以
|
|
1063
|
+
// 它的名字可以被别人占用。
|
|
1064
|
+
coerceBoolean(settings.enabled) !== false);
|
|
1065
|
+
})
|
|
1066
|
+
.map(([rawName, settings]) => typeof settings.toolName === 'string' && settings.toolName.trim() !== ''
|
|
1067
|
+
? settings.toolName.trim()
|
|
1068
|
+
: `${canonicalEngine(rawName)}_search`);
|
|
1069
|
+
}
|
|
1070
|
+
catch {
|
|
1071
|
+
return [];
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
/** 卡片提供的引擎,顺序就是文档介绍它们的顺序。 */
|
|
1075
|
+
const CARD_ENGINES = [
|
|
1076
|
+
'antigravity-cli',
|
|
1077
|
+
'tavily',
|
|
1078
|
+
'exa',
|
|
1079
|
+
'firecrawl',
|
|
1080
|
+
'keenable',
|
|
1081
|
+
'anysearch',
|
|
1082
|
+
'youcom',
|
|
1083
|
+
'searxng',
|
|
1084
|
+
'grok-cli',
|
|
1085
|
+
'local',
|
|
1086
|
+
];
|
|
1087
|
+
/** 需要 API 密钥的引擎。 */
|
|
1088
|
+
const KEYED_ENGINES = ['tavily', 'exa', 'firecrawl', 'keenable', 'anysearch'];
|
|
1089
|
+
/**
|
|
1090
|
+
* 需要 `baseURL` 的引擎。SearXNG 在这里而不在需要密钥的那组:它需要一个
|
|
1091
|
+
* 对端主机来通信,但不需要凭证,这两种能力分开校验,所以一次卡片保存不会
|
|
1092
|
+
* 把 API 密钥写到跟它毫无关系的引擎上。
|
|
1093
|
+
*/
|
|
1094
|
+
const ENDPOINT_ENGINES = [...KEYED_ENGINES, 'searxng'];
|
|
1095
|
+
/**
|
|
1096
|
+
* 一次运行真的会读取其 `model` 设置的引擎。其余引擎不显示这个字段,而不是
|
|
1097
|
+
* 显示一个背后什么都没有的输入框:HTTP 引擎忽略它,而 grok-cli 跟随的
|
|
1098
|
+
* 是 Grok Build 当前登录的账号。
|
|
1099
|
+
*/
|
|
1100
|
+
const MODEL_ENGINES = ['antigravity-cli'];
|
|
1101
|
+
/**
|
|
1102
|
+
* 默认不激活的引擎,与 `src/config.ts` 的 `OFF_UNLESS_ENABLED` 是一份跨端
|
|
1103
|
+
* 副本:本文件是手写 JavaScript,不能 import TypeScript 源码。
|
|
1104
|
+
* `dshPlugin.test.ts` 有一条 lockstep 断言两边一致。
|
|
1105
|
+
*
|
|
1106
|
+
* 它们仍然出现在卡片上,用户可以逐个打开;而 `doctor` 照样报告它们是否存在,
|
|
1107
|
+
* 所以「装了吗」和「开着吗」是两个可以分开看的答案。
|
|
1108
|
+
*/
|
|
1109
|
+
const DEFAULT_OFF_ENGINES = ['antigravity-cli'];
|
|
1110
|
+
/**
|
|
1111
|
+
* 所有被接受的拼写,与 src/config.ts 里的 CANONICAL_ENGINE 对应。用别名保存
|
|
1112
|
+
* 的设置就是同一个引擎的设置,所以卡片必须在它们本来所在的地方读写。
|
|
1113
|
+
*/
|
|
1114
|
+
const ENGINE_ALIASES = {
|
|
1115
|
+
antigravity: 'antigravity-cli',
|
|
1116
|
+
agy: 'antigravity-cli',
|
|
1117
|
+
grok: 'grok-cli',
|
|
1118
|
+
http: 'local',
|
|
1119
|
+
direct: 'local',
|
|
1120
|
+
};
|
|
1121
|
+
/**
|
|
1122
|
+
* 按字段覆盖文件值的环境变量,与 src/config.ts 的 ENV_BINDINGS 对应。一张
|
|
1123
|
+
* 只读文件的卡片,对一个通过环境变量导出密钥的容器会显示空表单,并把一个
|
|
1124
|
+
* 正常工作的引擎报告成未配置。
|
|
1125
|
+
*/
|
|
1126
|
+
const ENGINE_ENV_BINDINGS = {
|
|
1127
|
+
tavily: { apiKey: 'TAVILY_API_KEY', baseURL: 'TAVILY_BASE_URL' },
|
|
1128
|
+
exa: { apiKey: 'EXA_API_KEY', baseURL: 'EXA_BASE_URL' },
|
|
1129
|
+
firecrawl: { apiKey: 'FIRECRAWL_API_KEY', baseURL: 'FIRECRAWL_BASE_URL' },
|
|
1130
|
+
keenable: { apiKey: 'KEENABLE_API_KEY', baseURL: 'KEENABLE_BASE_URL' },
|
|
1131
|
+
anysearch: { apiKey: 'ANYSEARCH_API_KEY', baseURL: 'ANYSEARCH_BASE_URL' },
|
|
1132
|
+
};
|
|
1133
|
+
/** 一个存储名所指的规范引擎;它什么都不指时返回 ''。 */
|
|
1134
|
+
function canonicalEngine(name) {
|
|
1135
|
+
if (typeof name !== 'string') {
|
|
1136
|
+
return '';
|
|
1137
|
+
}
|
|
1138
|
+
const trimmed = name.trim().toLowerCase();
|
|
1139
|
+
if (CARD_ENGINES.includes(trimmed)) {
|
|
1140
|
+
return trimmed;
|
|
1141
|
+
}
|
|
1142
|
+
// 只查自有属性:裸下标会走原型链,于是 "constructor" 会以一个函数的身份
|
|
1143
|
+
// 返回来,并被当成一个引擎。
|
|
1144
|
+
return Object.hasOwn(ENGINE_ALIASES, trimmed)
|
|
1145
|
+
? ENGINE_ALIASES[trimmed]
|
|
1146
|
+
: '';
|
|
1147
|
+
}
|
|
1148
|
+
/** 只认 JSON 对象:null、数组和原型上的成员都不算设置。 */
|
|
1149
|
+
function isPlainObject(value) {
|
|
1150
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
1151
|
+
}
|
|
1152
|
+
/** 对齐 CLI 对手改布尔值的处理方式,但不迁移文件。 */
|
|
1153
|
+
function coerceBoolean(value) {
|
|
1154
|
+
if (typeof value === 'boolean') {
|
|
1155
|
+
return value;
|
|
1156
|
+
}
|
|
1157
|
+
if (typeof value === 'string') {
|
|
1158
|
+
const normalized = value.trim().toLowerCase();
|
|
1159
|
+
if (normalized === 'true') {
|
|
1160
|
+
return true;
|
|
1161
|
+
}
|
|
1162
|
+
if (normalized === 'false') {
|
|
1163
|
+
return false;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return undefined;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* 这个引擎此刻是开着的吗?
|
|
1170
|
+
*
|
|
1171
|
+
* 与 `src/config.ts` 的 `engineSettings()` 里那段 OFF_UNLESS_ENABLED 判定
|
|
1172
|
+
* 对齐:未设置 `enabled` 时,名单里的引擎算关,其余算开;显式写下的值永远
|
|
1173
|
+
* 压过默认。宿主半边必须自己判一遍,因为它不能 import TypeScript 源码,而
|
|
1174
|
+
* 判错一次就是「卡片上打开的引擎其实从来没被用过」。
|
|
1175
|
+
*/
|
|
1176
|
+
function engineEnabled(name, settings = {}) {
|
|
1177
|
+
const explicit = coerceBoolean(settings.enabled);
|
|
1178
|
+
if (explicit !== undefined) {
|
|
1179
|
+
return explicit;
|
|
1180
|
+
}
|
|
1181
|
+
return !DEFAULT_OFF_ENGINES.includes(name);
|
|
1182
|
+
}
|
|
1183
|
+
/** 逗号分隔的 API 密钥值里是否至少含一个真实密钥。 */
|
|
1184
|
+
function hasApiKeys(value) {
|
|
1185
|
+
return (typeof value === 'string' &&
|
|
1186
|
+
value
|
|
1187
|
+
.split(',')
|
|
1188
|
+
.map((key) => key.trim())
|
|
1189
|
+
.some((key) => key !== ''));
|
|
1190
|
+
}
|
|
1191
|
+
/** ~/.searchfuse/config.json,每个 harness 共用的那一个文件。 */
|
|
1192
|
+
function modsearchConfigPath() {
|
|
1193
|
+
// 与 src/config.ts 的 DIR_NAME 保持一致。这里曾返回 `.modsearch`,
|
|
1194
|
+
// 于是冲突:CLI 读写 `.searchfuse`,卡片读写 `.modsearch`,同一段注释
|
|
1195
|
+
// 却写着 `.searchfuse`。两个路径各存一份配置,改一边另一边看不到。
|
|
1196
|
+
return join(homedir(), '.searchfuse', 'config.json');
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* 共享配置,原样读出。只有文件不存在才当作空:一个存在却解析不了的文件
|
|
1200
|
+
* 是某人的配置,一张把它当作空的卡片会在下次保存时覆盖掉它。
|
|
1201
|
+
*
|
|
1202
|
+
* 刻意不用 CLI 的 loadConfigFile:那个在读取时会迁移遗留结构,而一次保存
|
|
1203
|
+
* 并不是重写用户没要求处理的文件的时机。卡片不拥有的东西,它就不碰。
|
|
1204
|
+
*/
|
|
1205
|
+
function readModsearchConfig() {
|
|
1206
|
+
const file = modsearchConfigPath();
|
|
1207
|
+
let raw;
|
|
1208
|
+
try {
|
|
1209
|
+
raw = readFileSync(file, 'utf8');
|
|
1210
|
+
}
|
|
1211
|
+
catch (error) {
|
|
1212
|
+
if (caughtCode(error) === 'ENOENT') {
|
|
1213
|
+
return {};
|
|
1214
|
+
}
|
|
1215
|
+
throw new Error(`cannot read ${file}: ${caughtMessage(error)}`);
|
|
1216
|
+
}
|
|
1217
|
+
let parsed;
|
|
1218
|
+
try {
|
|
1219
|
+
parsed = JSON.parse(raw);
|
|
1220
|
+
}
|
|
1221
|
+
catch (error) {
|
|
1222
|
+
throw new Error(`${file} is not valid JSON: ${caughtMessage(error)}`);
|
|
1223
|
+
}
|
|
1224
|
+
if (!isPlainObject(parsed)) {
|
|
1225
|
+
throw new Error(`${file} does not hold a JSON object`);
|
|
1226
|
+
}
|
|
1227
|
+
return parsed;
|
|
1228
|
+
}
|
|
1229
|
+
/** 持有某个引擎设置的文件条目键:它自己的,加上别名。 */
|
|
1230
|
+
function fileKeysFor(engine, config) {
|
|
1231
|
+
const engines = isPlainObject(config.engines) ? config.engines : {};
|
|
1232
|
+
return Object.keys(engines).filter((key) => canonicalEngine(key) === engine);
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* 某个引擎的文件设置,别名条目按 CLI 的方式合并:按文件顺序,所以靠后的
|
|
1236
|
+
* 条目胜出,正是 migrateLegacyConfig 折叠它们的方式。
|
|
1237
|
+
*/
|
|
1238
|
+
function fileSettingsFor(engine, config) {
|
|
1239
|
+
const engines = (isPlainObject(config.engines) ? config.engines : {});
|
|
1240
|
+
let settings = {};
|
|
1241
|
+
for (const key of fileKeysFor(engine, config)) {
|
|
1242
|
+
if (isPlainObject(engines[key])) {
|
|
1243
|
+
settings = { ...settings, ...engines[key] };
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
return settings;
|
|
1247
|
+
}
|
|
1248
|
+
/** 某个引擎的环境设置,按字段,与 engineSettings 应用它们的方式一致。 */
|
|
1249
|
+
function envSettingsFor(engine, env = process.env) {
|
|
1250
|
+
const settings = {};
|
|
1251
|
+
const bindings = (Object.hasOwn(ENGINE_ENV_BINDINGS, engine)
|
|
1252
|
+
? ENGINE_ENV_BINDINGS[engine]
|
|
1253
|
+
: {});
|
|
1254
|
+
for (const [field, variable] of Object.entries(bindings)) {
|
|
1255
|
+
const raw = env[variable];
|
|
1256
|
+
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
1257
|
+
if (value !== '' && (field !== 'apiKey' || hasApiKeys(value))) {
|
|
1258
|
+
settings[field] = value;
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
return settings;
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* 卡片被允许知道的内容:每个引擎的端点和模型,外加是否存过密钥以及它来自
|
|
1265
|
+
* 哪里,且永远不包括密钥本身。读不到秘密的浏览器泄漏不了秘密,也写不回一个
|
|
1266
|
+
* 空白值把它盖掉。
|
|
1267
|
+
*
|
|
1268
|
+
* 是 async 的:`serve` 段要探一次 `/healthz`,那是网络动作。
|
|
1269
|
+
*/
|
|
1270
|
+
async function engineSummary(config = readModsearchConfig(), env = process.env) {
|
|
1271
|
+
const engines = {};
|
|
1272
|
+
for (const name of CARD_ENGINES) {
|
|
1273
|
+
const fromFile = fileSettingsFor(name, config);
|
|
1274
|
+
const fromEnv = envSettingsFor(name, env);
|
|
1275
|
+
const fileKey = hasApiKeys(fromFile.apiKey);
|
|
1276
|
+
const envKey = hasApiKeys(fromEnv.apiKey);
|
|
1277
|
+
engines[name] = {
|
|
1278
|
+
baseURL: fromEnv.baseURL ?? (typeof fromFile.baseURL === 'string' ? fromFile.baseURL : ''),
|
|
1279
|
+
model: typeof fromFile.model === 'string' ? fromFile.model : '',
|
|
1280
|
+
hasKey: envKey || fileKey,
|
|
1281
|
+
// 生效值:「文件里写没写」与「此刻开没开」是两回事,默认关闭的引擎
|
|
1282
|
+
// 在文件里往往一个字都没有。卡片要的是后者。
|
|
1283
|
+
enabled: engineEnabled(name, fromFile),
|
|
1284
|
+
// 标出「关闭来自默认而不是用户亲手关的」:卡片据此说明打开它需要先存
|
|
1285
|
+
// 一份显式设置。
|
|
1286
|
+
defaultOff: DEFAULT_OFF_ENGINES.includes(name) && coerceBoolean(fromFile.enabled) === undefined,
|
|
1287
|
+
// 曝光矩阵以及随之而来的两个字段。只报告引擎自己的值:代理为空意味着
|
|
1288
|
+
// 文件里没有,这就是卡片显示的内容。
|
|
1289
|
+
expose: isPlainObject(fromFile.expose) ? fromFile.expose : {},
|
|
1290
|
+
proxy: typeof fromFile.proxy === 'string' ? fromFile.proxy : '',
|
|
1291
|
+
toolName: typeof fromFile.toolName === 'string' ? fromFile.toolName : '',
|
|
1292
|
+
// 环境变量里的密钥在运行时压过文件里的密钥,所以一张报告文件密钥的
|
|
1293
|
+
// 卡片,会在一次看起来什么也没改的保存之后解释错误的原因。
|
|
1294
|
+
keySource: envKey ? 'env' : fileKey ? 'file' : null,
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
// MCP server:卡片要能单独给每一个配代理。默认集合(context7/grep)
|
|
1298
|
+
// 即使文件里没写也要列出来——用户正是要给它们配代理才需要这张表。
|
|
1299
|
+
const mcp = {};
|
|
1300
|
+
var configuredMcp = isPlainObject(config.mcp) ? config.mcp : {};
|
|
1301
|
+
var defaultMcp = {
|
|
1302
|
+
context7: { transport: 'streamable-http', url: 'https://mcp.context7.com/mcp' },
|
|
1303
|
+
grep: { transport: 'streamable-http', url: 'https://mcp.grep.app' },
|
|
1304
|
+
};
|
|
1305
|
+
var mcpNames = Object.keys(defaultMcp);
|
|
1306
|
+
for (var extra of Object.keys(configuredMcp)) {
|
|
1307
|
+
if (!mcpNames.includes(extra))
|
|
1308
|
+
mcpNames.push(extra);
|
|
1309
|
+
}
|
|
1310
|
+
for (var name of mcpNames) {
|
|
1311
|
+
var fromFile = isPlainObject(configuredMcp[name]) ? configuredMcp[name] : {};
|
|
1312
|
+
var fromDefault = defaultMcp[name] || {};
|
|
1313
|
+
var enabled = fromFile.enabled !== false;
|
|
1314
|
+
mcp[name] = {
|
|
1315
|
+
url: typeof fromFile.url === 'string' && fromFile.url !== '' ? fromFile.url : fromDefault.url || '',
|
|
1316
|
+
transport: typeof fromFile.transport === 'string' ? fromFile.transport : 'streamable-http',
|
|
1317
|
+
// 三态代理:'' = 跟随环境变量,'direct' = 直连,URL = 用该代理。
|
|
1318
|
+
// 空串与「没配」必须区分,所以文件里的 null 报成 'direct'。
|
|
1319
|
+
proxy: fromFile.proxy === null
|
|
1320
|
+
? 'direct'
|
|
1321
|
+
: typeof fromFile.proxy === 'string'
|
|
1322
|
+
? fromFile.proxy
|
|
1323
|
+
: '',
|
|
1324
|
+
enabled,
|
|
1325
|
+
// 文件里没写这一项:卡片要标「默认」,并知道保存时是新建还是改已有的。
|
|
1326
|
+
isDefault: Object.hasOwn(configuredMcp, name) === false,
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
return {
|
|
1330
|
+
// 三种状态分开:钉在某个引擎上、由它的某个别名钉住(按规范名报告),
|
|
1331
|
+
// 或者根本没有钉住,也就是由引擎链按可用性挑选。
|
|
1332
|
+
engine: canonicalEngine(config.engine),
|
|
1333
|
+
engines,
|
|
1334
|
+
keyed: KEYED_ENGINES,
|
|
1335
|
+
endpoints: ENDPOINT_ENGINES,
|
|
1336
|
+
models: MODEL_ENGINES,
|
|
1337
|
+
mcp,
|
|
1338
|
+
// 卡片要展示拖动排序与「聚合/退避」选择,所以两者都得下发。
|
|
1339
|
+
//
|
|
1340
|
+
// 顺序下发的是文件里写的那份**原始名单**,不是补齐后的完整顺序:卡片要
|
|
1341
|
+
// 区分「用户亲手排过的」与「从没排过的」,补全之后就看不出来了。卡片
|
|
1342
|
+
// 自己知道全部引擎是谁,补齐是它的事。
|
|
1343
|
+
engineOrder: Array.isArray(config.aggregate?.engineOrder)
|
|
1344
|
+
? config.aggregate.engineOrder.filter((name) => typeof name === 'string')
|
|
1345
|
+
: [],
|
|
1346
|
+
// 未写 mode 等于融合,与 src/config.ts 的 aggregateMode() 同一判据。
|
|
1347
|
+
aggregateMode: config.aggregate?.mode === 'chain' ? 'chain' : 'rrf',
|
|
1348
|
+
// 宿主接入状态:卡片要显示「omp / Claude Code 现在接上了没」,
|
|
1349
|
+
// 而这件事只能靠看文件回答,没有任何宿主提供查询接口。
|
|
1350
|
+
//
|
|
1351
|
+
// 与 `hosts.<name>.enabled` 分开报告是对的:开关是「想不想接」,
|
|
1352
|
+
// 状态是「实际接上了没」。两者不同步正是最需要被看见的故障——
|
|
1353
|
+
// 开关写着 true、文件却没装,或者反过来。
|
|
1354
|
+
hosts: hostStatuses(config),
|
|
1355
|
+
// 本地服务在不在。它决定 Claude Code 与 omp 的搜索走 HTTP 还是退回
|
|
1356
|
+
// spawn 子进程,而那条降级路径用户完全感知不到——只在日志里留一条
|
|
1357
|
+
// ENOENT。所以卡片必须把它报出来。
|
|
1358
|
+
serve: await serveStatus(),
|
|
1359
|
+
// SearXNG 的抓取配置。卡片要能逐引擎配代理,所以这里原样交出去,
|
|
1360
|
+
// 保存时由 applyCardSettings 校验并写回。
|
|
1361
|
+
//
|
|
1362
|
+
// `embedded` 必须与 src/config.ts 的 `engineSettings()` 用同一个判据
|
|
1363
|
+
// (`!== false`):文件里没写这个键就等于开启。曾经这里写的是
|
|
1364
|
+
// `=== true`,于是全新用户打开卡片看到「关闭」,而运行时内置实例
|
|
1365
|
+
// 明明可用 —— 一张撒谎的设置页比没有设置页更糟。
|
|
1366
|
+
searxng: {
|
|
1367
|
+
embedded: config.searxng?.embedded !== false,
|
|
1368
|
+
outgoing: isPlainObject(config.searxng?.outgoing) ? config.searxng.outgoing : {},
|
|
1369
|
+
networks: isPlainObject(config.searxng?.networks) ? config.searxng.networks : {},
|
|
1370
|
+
engines: isPlainObject(config.searxng?.engines) ? config.searxng.engines : {},
|
|
1371
|
+
},
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* 把一次卡片提交应用到共享文件。只有卡片的三个关注点能动:引擎偏好、被点名
|
|
1376
|
+
* 的那个引擎自己的密钥、端点和模型,以及自动参与。`bin`、
|
|
1377
|
+
* `allowPrivateNetwork`、`cooldown` 和 `keylessFetch` 只留给 CLI,其余每个
|
|
1378
|
+
* 键都原样抄过去。
|
|
1379
|
+
*
|
|
1380
|
+
* 缺失或空的 `apiKey` 不动已存的那一个:卡片从不收到密钥,所以它也绝不能被
|
|
1381
|
+
* 一个它自己显示出来的空白字段给清掉。
|
|
1382
|
+
*/
|
|
1383
|
+
function applyCardSettings(patch) {
|
|
1384
|
+
const config = readModsearchConfig();
|
|
1385
|
+
if (patch?.engine !== undefined) {
|
|
1386
|
+
const pin = typeof patch.engine === 'string' ? patch.engine.trim() : '';
|
|
1387
|
+
if (pin === '') {
|
|
1388
|
+
// 空串是 CLI 自己表示「自动」的拼法,不是一个缺失的值。
|
|
1389
|
+
config.engine = '';
|
|
1390
|
+
}
|
|
1391
|
+
else {
|
|
1392
|
+
const engine = canonicalEngine(pin);
|
|
1393
|
+
if (!CARD_ENGINES.includes(engine)) {
|
|
1394
|
+
throw new Error(`unknown engine: ${patch.engine}`);
|
|
1395
|
+
}
|
|
1396
|
+
config.engine = engine;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
// 拖动排序写回:整份名单替换,而不是逐项追加。
|
|
1400
|
+
//
|
|
1401
|
+
// 顺序就是它本来的样子,不能用 merge 语义:把 A 拖到 B 前面,本质上是
|
|
1402
|
+
// 「A 和 B 的相对位置变了」,而任何只增不减的合并都表达不了这一点。
|
|
1403
|
+
// 名单过长的部分被截掉,重复项去重,未知引擎名直接拒绝 —— 它只可能来自
|
|
1404
|
+
// 一个过期的卡片,而静默丢弃会让用户看着屏幕上的顺序与文件里的不符。
|
|
1405
|
+
if (patch?.engineOrder !== undefined) {
|
|
1406
|
+
if (!Array.isArray(patch.engineOrder)) {
|
|
1407
|
+
throw new Error('engineOrder must be an array of engine names');
|
|
1408
|
+
}
|
|
1409
|
+
const seen = new Set();
|
|
1410
|
+
const order = [];
|
|
1411
|
+
for (const raw of patch.engineOrder) {
|
|
1412
|
+
const engine = canonicalEngine(raw);
|
|
1413
|
+
if (!CARD_ENGINES.includes(engine)) {
|
|
1414
|
+
throw new Error(`unknown engine in engineOrder: ${String(raw)}`);
|
|
1415
|
+
}
|
|
1416
|
+
// 重复项保留第一次出现的位置,不报错:拖动实现里重复态是中间态,
|
|
1417
|
+
// 用户没有为此做错什么。
|
|
1418
|
+
if (seen.has(engine))
|
|
1419
|
+
continue;
|
|
1420
|
+
seen.add(engine);
|
|
1421
|
+
order.push(engine);
|
|
1422
|
+
}
|
|
1423
|
+
if (order.length === 0) {
|
|
1424
|
+
// 空名单等于「没排过」,删键而不是写一个空数组:后者在文件里看起来
|
|
1425
|
+
// 像一次刻意的设置,而它其实只是用户把卡片收了起来。
|
|
1426
|
+
if (config.aggregate !== undefined) {
|
|
1427
|
+
delete config.aggregate.engineOrder;
|
|
1428
|
+
if (Object.keys(config.aggregate).length === 0)
|
|
1429
|
+
delete config.aggregate;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
else {
|
|
1433
|
+
config.aggregate = Object.assign({}, config.aggregate, { engineOrder: order });
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
// 聚合与退避二选一。写 'chain' 或 'rrf' 都落成显式值;'rrf' 是默认,
|
|
1437
|
+
// 但删键与写键的读回结果相同,写显式值让文件自己说明当前行为。
|
|
1438
|
+
if (patch?.aggregateMode !== undefined) {
|
|
1439
|
+
const mode = patch.aggregateMode;
|
|
1440
|
+
if (mode !== 'rrf' && mode !== 'chain') {
|
|
1441
|
+
throw new Error(`aggregateMode must be "rrf" or "chain", got: ${String(mode)}`);
|
|
1442
|
+
}
|
|
1443
|
+
config.aggregate = Object.assign({}, config.aggregate, { mode });
|
|
1444
|
+
}
|
|
1445
|
+
// 宿主开关。卡片只能改自己属于的那两个宿主;dsh 由「插件有没有被加载」
|
|
1446
|
+
// 表达,不是这里的一个布尔值。
|
|
1447
|
+
//
|
|
1448
|
+
// 这里只写配置,不触发 hosts sync:卡片是浏览器的,它没有权限去装文件,
|
|
1449
|
+
// 也不该在用户点「保存」时顺手改另一个 harness 的目录。落地的动作仍然由
|
|
1450
|
+
// `searchfuse hosts sync` 负责,卡片上的「需要更新」提示指向它。
|
|
1451
|
+
if (patch?.hostEnabled !== undefined) {
|
|
1452
|
+
if (!isPlainObject(patch.hostEnabled)) {
|
|
1453
|
+
throw new Error('hostEnabled must be an object');
|
|
1454
|
+
}
|
|
1455
|
+
for (const [name, value] of Object.entries(patch.hostEnabled)) {
|
|
1456
|
+
if (name !== 'claudeCode' && name !== 'omp') {
|
|
1457
|
+
throw new Error(`unknown host: ${name}`);
|
|
1458
|
+
}
|
|
1459
|
+
if (typeof value !== 'boolean') {
|
|
1460
|
+
throw new Error(`hosts.${name}.enabled must be true or false`);
|
|
1461
|
+
}
|
|
1462
|
+
config.hosts = Object.assign({}, config.hosts, {
|
|
1463
|
+
[name]: Object.assign({}, config.hosts?.[name], { enabled: value }),
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
// 引擎字段一次编辑一个引擎,由 `target` 点名。缺失意味着这次保存没有碰任何
|
|
1468
|
+
// 引擎设置,这正是「只改钉住项」的保存的样子。
|
|
1469
|
+
if (patch?.target !== undefined) {
|
|
1470
|
+
const engine = canonicalEngine(patch.target);
|
|
1471
|
+
if (!CARD_ENGINES.includes(engine)) {
|
|
1472
|
+
throw new Error(`unknown engine: ${patch.target}`);
|
|
1473
|
+
}
|
|
1474
|
+
if (!KEYED_ENGINES.includes(engine) && patch.apiKey !== undefined) {
|
|
1475
|
+
throw new Error(`${engine} takes no API key`);
|
|
1476
|
+
}
|
|
1477
|
+
if (!ENDPOINT_ENGINES.includes(engine) && patch.baseURL !== undefined) {
|
|
1478
|
+
throw new Error(`${engine} takes no base URL`);
|
|
1479
|
+
}
|
|
1480
|
+
if (!MODEL_ENGINES.includes(engine) && patch.model !== undefined) {
|
|
1481
|
+
throw new Error(`${engine} takes no model setting`);
|
|
1482
|
+
}
|
|
1483
|
+
if (config.engines !== undefined && !isPlainObject(config.engines)) {
|
|
1484
|
+
throw new Error('the "engines" section of the config file is not an object');
|
|
1485
|
+
}
|
|
1486
|
+
// 写到读取时真正生效的位置:持有该引擎设置的最后一个条目,就是合并时
|
|
1487
|
+
// 胜出的那个,所以用别名保存的密钥是被更新,而不是被一份 CLI 永远读不到
|
|
1488
|
+
// 的第二份副本遮蔽。
|
|
1489
|
+
const holders = fileKeysFor(engine, config);
|
|
1490
|
+
const target = holders.length > 0 ? holders[holders.length - 1] : engine;
|
|
1491
|
+
config.engines = { ...config.engines };
|
|
1492
|
+
if (config.engines[target] !== undefined && !isPlainObject(config.engines[target])) {
|
|
1493
|
+
throw new Error(`the "engines.${target}" entry of the config file is not an object`);
|
|
1494
|
+
}
|
|
1495
|
+
const settings = { ...config.engines[target] };
|
|
1496
|
+
if (patch.baseURL !== undefined) {
|
|
1497
|
+
const baseURL = typeof patch.baseURL === 'string' ? patch.baseURL.trim() : '';
|
|
1498
|
+
if (baseURL === '') {
|
|
1499
|
+
// 空串取消这个覆盖,回到官方端点。
|
|
1500
|
+
delete settings.baseURL;
|
|
1501
|
+
}
|
|
1502
|
+
else if (!/^https?:\/\//i.test(baseURL)) {
|
|
1503
|
+
// CLI 应用的也是同一条规则,理由也一样:这个主机会收到该引擎的 API
|
|
1504
|
+
// 密钥。
|
|
1505
|
+
throw new Error(`invalid base URL: ${baseURL}. Use a full http(s) URL, e.g. https://api.example.com`);
|
|
1506
|
+
}
|
|
1507
|
+
else {
|
|
1508
|
+
settings.baseURL = baseURL;
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
if (patch.model !== undefined) {
|
|
1512
|
+
const model = typeof patch.model === 'string' ? patch.model.trim() : '';
|
|
1513
|
+
if (model === '') {
|
|
1514
|
+
delete settings.model;
|
|
1515
|
+
}
|
|
1516
|
+
else {
|
|
1517
|
+
settings.model = model;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
const apiKey = typeof patch.apiKey === 'string' ? patch.apiKey.trim() : '';
|
|
1521
|
+
if (apiKey !== '') {
|
|
1522
|
+
settings.apiKey = apiKey;
|
|
1523
|
+
}
|
|
1524
|
+
// 空白的代理字段是「别动它」,不是「清掉它」:对代理保存在文件里的引擎,
|
|
1525
|
+
// 卡片显示的是空字段,所以把空白当成删除,会抹掉用户从没看见过的值。要
|
|
1526
|
+
// 故意移除代理,用 CLI 的 `config set <engine>.proxy ""`。
|
|
1527
|
+
if (typeof patch.proxy === 'string' && patch.proxy.trim() !== '') {
|
|
1528
|
+
const proxy = patch.proxy.trim();
|
|
1529
|
+
if (!isValidProxyValue(proxy)) {
|
|
1530
|
+
throw new Error(`invalid proxy: ${proxy}. Use "direct", "none", or a full http(s) URL such as http://127.0.0.1:7890`);
|
|
1531
|
+
}
|
|
1532
|
+
settings.proxy = proxy;
|
|
1533
|
+
}
|
|
1534
|
+
// 曝光矩阵。缺失意味着这次保存没有碰它。
|
|
1535
|
+
if (isPlainObject(patch.expose)) {
|
|
1536
|
+
const aggregate = coerceBoolean(patch.expose.aggregate);
|
|
1537
|
+
const tool = coerceBoolean(patch.expose.tool);
|
|
1538
|
+
const next = {};
|
|
1539
|
+
if (aggregate !== undefined) {
|
|
1540
|
+
next.aggregate = aggregate;
|
|
1541
|
+
}
|
|
1542
|
+
if (tool !== undefined) {
|
|
1543
|
+
next.tool = tool;
|
|
1544
|
+
}
|
|
1545
|
+
if (Object.keys(next).length > 0) {
|
|
1546
|
+
settings.expose = { ...(isPlainObject(settings.expose) ? settings.expose : {}), ...next };
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
if (typeof patch.toolName === 'string' && patch.toolName.trim() !== '') {
|
|
1550
|
+
const name = patch.toolName.trim();
|
|
1551
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) {
|
|
1552
|
+
throw new Error(`invalid tool name: ${name}. Use 1-64 characters of A-Z, a-z, 0-9, _ or -`);
|
|
1553
|
+
}
|
|
1554
|
+
if (BASE_TOOL_NAMES.includes(name)) {
|
|
1555
|
+
throw new Error(`tool name "${name}" belongs to a built-in tool`);
|
|
1556
|
+
}
|
|
1557
|
+
settings.toolName = name;
|
|
1558
|
+
}
|
|
1559
|
+
config.engines[target] = settings;
|
|
1560
|
+
}
|
|
1561
|
+
// 自动路由授权。缺失意味着这次保存没有碰引擎链。`true` 移除覆盖项,因为
|
|
1562
|
+
// 启用是内置默认值。文件中只需要存在「退出」这一种状态。
|
|
1563
|
+
if (isPlainObject(patch?.enabled)) {
|
|
1564
|
+
if (config.engines !== undefined && !isPlainObject(config.engines)) {
|
|
1565
|
+
throw new Error('the "engines" section of the config file is not an object');
|
|
1566
|
+
}
|
|
1567
|
+
config.engines = { ...config.engines };
|
|
1568
|
+
for (const engine of CARD_ENGINES) {
|
|
1569
|
+
const enabled = patch.enabled[engine];
|
|
1570
|
+
if (typeof enabled !== 'boolean') {
|
|
1571
|
+
continue;
|
|
1572
|
+
}
|
|
1573
|
+
const holders = fileKeysFor(engine, config);
|
|
1574
|
+
if (enabled) {
|
|
1575
|
+
// 移除每一个别名上的覆盖。只删最后一个,可能暴露出更早的
|
|
1576
|
+
// `enabled: false`,而合并后的配置会把它读进去。
|
|
1577
|
+
for (const holder of holders) {
|
|
1578
|
+
if (!isPlainObject(config.engines[holder])) {
|
|
1579
|
+
throw new Error(`the "engines.${holder}" entry of the config file is not an object`);
|
|
1580
|
+
}
|
|
1581
|
+
const settings = { ...config.engines[holder] };
|
|
1582
|
+
delete settings.enabled;
|
|
1583
|
+
if (Object.keys(settings).length === 0) {
|
|
1584
|
+
delete config.engines[holder];
|
|
1585
|
+
}
|
|
1586
|
+
else {
|
|
1587
|
+
config.engines[holder] = settings;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
continue;
|
|
1591
|
+
}
|
|
1592
|
+
const target = holders.length > 0 ? holders[holders.length - 1] : engine;
|
|
1593
|
+
if (config.engines[target] !== undefined && !isPlainObject(config.engines[target])) {
|
|
1594
|
+
throw new Error(`the "engines.${target}" entry of the config file is not an object`);
|
|
1595
|
+
}
|
|
1596
|
+
config.engines[target] = { ...config.engines[target], enabled: false };
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
// MCP server 的编辑:一个 patch 只碰一个 server,由 `mcpTarget` 点名。
|
|
1600
|
+
// 与引擎一样,缺失意味着这次保存没碰 MCP。
|
|
1601
|
+
if (patch?.mcpTarget !== undefined) {
|
|
1602
|
+
var mcpName = typeof patch.mcpTarget === 'string' ? patch.mcpTarget.trim() : '';
|
|
1603
|
+
if (mcpName === '') {
|
|
1604
|
+
throw new Error('mcpTarget must be a non-empty server name');
|
|
1605
|
+
}
|
|
1606
|
+
// server 名会成为工具名的一部分,合法字符集与 MCP 配置层一致。
|
|
1607
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(mcpName)) {
|
|
1608
|
+
throw new Error(`invalid MCP server name: ${mcpName} (use A-Za-z0-9_- up to 32)`);
|
|
1609
|
+
}
|
|
1610
|
+
if (config.mcp !== undefined && !isPlainObject(config.mcp)) {
|
|
1611
|
+
throw new Error('the "mcp" section of the config file is not an object');
|
|
1612
|
+
}
|
|
1613
|
+
const existing = isPlainObject(config.mcp) && isPlainObject(config.mcp[mcpName]) ? config.mcp[mcpName] : {};
|
|
1614
|
+
var next = { ...existing };
|
|
1615
|
+
if (patch.mcpUrl !== undefined) {
|
|
1616
|
+
var url = typeof patch.mcpUrl === 'string' ? patch.mcpUrl.trim() : '';
|
|
1617
|
+
if (url !== '') {
|
|
1618
|
+
let parsed;
|
|
1619
|
+
try {
|
|
1620
|
+
parsed = new URL(url);
|
|
1621
|
+
}
|
|
1622
|
+
catch {
|
|
1623
|
+
throw new Error(`invalid MCP url: ${url}`);
|
|
1624
|
+
}
|
|
1625
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
1626
|
+
throw new Error(`invalid MCP url: ${url} (use http or https)`);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
if (url === '') {
|
|
1630
|
+
// 空串:如果这是默认项且原本没有文件条目,就不必写一个空 url。
|
|
1631
|
+
Reflect.deleteProperty(next, 'url');
|
|
1632
|
+
}
|
|
1633
|
+
else {
|
|
1634
|
+
next.url = url;
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
if (patch.mcpTransport !== undefined) {
|
|
1638
|
+
var transport = typeof patch.mcpTransport === 'string' ? patch.mcpTransport.trim() : '';
|
|
1639
|
+
if (transport !== '' && transport !== 'streamable-http') {
|
|
1640
|
+
throw new Error(`unsupported MCP transport: ${transport} (only streamable-http)`);
|
|
1641
|
+
}
|
|
1642
|
+
if (transport === '')
|
|
1643
|
+
Reflect.deleteProperty(next, 'transport');
|
|
1644
|
+
else
|
|
1645
|
+
next.transport = transport;
|
|
1646
|
+
}
|
|
1647
|
+
// 代理三态。这里是「文件里存什么」的决定点:
|
|
1648
|
+
// '' → 删掉 proxy(跟随环境变量)
|
|
1649
|
+
// 'direct' → 存 null(显式直连)
|
|
1650
|
+
// 其它 → 必须是合法 http(s) URL
|
|
1651
|
+
if (patch.mcpProxy !== undefined) {
|
|
1652
|
+
var rawProxy = typeof patch.mcpProxy === 'string' ? patch.mcpProxy.trim() : '';
|
|
1653
|
+
if (rawProxy === '') {
|
|
1654
|
+
Reflect.deleteProperty(next, 'proxy');
|
|
1655
|
+
}
|
|
1656
|
+
else if (rawProxy === 'direct' || rawProxy === 'none') {
|
|
1657
|
+
next.proxy = null;
|
|
1658
|
+
}
|
|
1659
|
+
else {
|
|
1660
|
+
let parsedProxy;
|
|
1661
|
+
try {
|
|
1662
|
+
parsedProxy = new URL(rawProxy);
|
|
1663
|
+
}
|
|
1664
|
+
catch {
|
|
1665
|
+
throw new Error(`invalid MCP proxy: ${rawProxy}`);
|
|
1666
|
+
}
|
|
1667
|
+
if (parsedProxy.protocol !== 'http:' && parsedProxy.protocol !== 'https:') {
|
|
1668
|
+
throw new Error(`invalid MCP proxy: ${rawProxy} (use http or https)`);
|
|
1669
|
+
}
|
|
1670
|
+
next.proxy = rawProxy;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
if (patch.mcpEnabled !== undefined) {
|
|
1674
|
+
next.enabled = patch.mcpEnabled !== false;
|
|
1675
|
+
}
|
|
1676
|
+
config.mcp = { ...(isPlainObject(config.mcp) ? config.mcp : {}), [mcpName]: next };
|
|
1677
|
+
}
|
|
1678
|
+
// SearXNG 抓取配置。三种编辑互斥,用各自的键点名:
|
|
1679
|
+
// searxngEmbedded —— 打开/关闭随包实例
|
|
1680
|
+
// searxngOutgoingProxies —— 整段 outgoing.proxies(SearXNG 内部的默认轮询)
|
|
1681
|
+
// searxngNetwork —— 一个命名网络的整段定义
|
|
1682
|
+
// searxngEngine —— 一个上游引擎的规则
|
|
1683
|
+
// 缺省意味着这次保存没碰它,与其余 patch 的语义一致。
|
|
1684
|
+
if (patch?.searxngEmbedded !== undefined) {
|
|
1685
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1686
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1687
|
+
}
|
|
1688
|
+
var searxngBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1689
|
+
// 两个布尔值都写显式值,不删键。
|
|
1690
|
+
//
|
|
1691
|
+
// src/config.ts 把「没有 embedded 键」读作开启,而旧实现遇到 `false`
|
|
1692
|
+
// 时删掉了这个键,于是「关闭」在写盘后等价于「开启」—— 按钮点得动、
|
|
1693
|
+
// 文件也变了、行为却没变。删键与写 false 只有在默认值相反时才有分,
|
|
1694
|
+
// 这里默认是开,所以 false 必须落成字面 false。
|
|
1695
|
+
if (patch.searxngEmbedded === true) {
|
|
1696
|
+
searxngBase.embedded = true;
|
|
1697
|
+
}
|
|
1698
|
+
else {
|
|
1699
|
+
searxngBase.embedded = false;
|
|
1700
|
+
}
|
|
1701
|
+
config.searxng = searxngBase;
|
|
1702
|
+
}
|
|
1703
|
+
// 外部实例地址与代理。空串表示清掉(回到官方端点 / 跟随环境)。
|
|
1704
|
+
// 它与 searxngEmbedded 共同表达「用哪一个实例」:地址非空则外部优先,
|
|
1705
|
+
// 否则看随包开关。
|
|
1706
|
+
if (patch?.searxngExternalURL !== undefined) {
|
|
1707
|
+
if (config.engines !== undefined && !isPlainObject(config.engines)) {
|
|
1708
|
+
throw new Error('the "engines" section of the config file is not an object');
|
|
1709
|
+
}
|
|
1710
|
+
config.engines = { ...(isPlainObject(config.engines) ? config.engines : {}) };
|
|
1711
|
+
var searxngEngineEntry = isPlainObject(config.engines.searxng) ? { ...config.engines.searxng } : {};
|
|
1712
|
+
var externalURL = typeof patch.searxngExternalURL === 'string'
|
|
1713
|
+
? patch.searxngExternalURL.trim()
|
|
1714
|
+
: '';
|
|
1715
|
+
if (externalURL === '') {
|
|
1716
|
+
delete searxngEngineEntry.baseURL;
|
|
1717
|
+
}
|
|
1718
|
+
else {
|
|
1719
|
+
if (!/^https?:\/\//i.test(externalURL)) {
|
|
1720
|
+
throw new Error(`invalid SearXNG base URL: ${externalURL}. Use a full http(s) URL`);
|
|
1721
|
+
}
|
|
1722
|
+
searxngEngineEntry.baseURL = externalURL;
|
|
1723
|
+
}
|
|
1724
|
+
if (patch.searxngExternalProxy !== undefined) {
|
|
1725
|
+
var externalProxy = typeof patch.searxngExternalProxy === 'string'
|
|
1726
|
+
? patch.searxngExternalProxy.trim()
|
|
1727
|
+
: '';
|
|
1728
|
+
if (externalProxy === '') {
|
|
1729
|
+
delete searxngEngineEntry.proxy;
|
|
1730
|
+
}
|
|
1731
|
+
else {
|
|
1732
|
+
if (!isValidProxyValue(externalProxy)) {
|
|
1733
|
+
throw new Error(`invalid SearXNG proxy: ${externalProxy}`);
|
|
1734
|
+
}
|
|
1735
|
+
searxngEngineEntry.proxy = externalProxy;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
config.engines.searxng = searxngEngineEntry;
|
|
1739
|
+
}
|
|
1740
|
+
// 批量上游引擎规则:{ <engineName>: { enabled?: bool, proxy?: string } }。
|
|
1741
|
+
//
|
|
1742
|
+
// 每条都先复制现有规则再逐字段覆盖,所以 UI 没暴露的 network /
|
|
1743
|
+
// using_tor_proxy 不会被一次保存擦掉。这也是「卡片不展示的字段必须
|
|
1744
|
+
// 原样保留」这条红线的落点。
|
|
1745
|
+
if (patch?.searxngRules !== undefined) {
|
|
1746
|
+
if (!isPlainObject(patch.searxngRules)) {
|
|
1747
|
+
throw new Error('searxngRules must be an object of engine rules');
|
|
1748
|
+
}
|
|
1749
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1750
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1751
|
+
}
|
|
1752
|
+
var rulesBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1753
|
+
var rulesEngines = isPlainObject(rulesBase.engines) ? { ...rulesBase.engines } : {};
|
|
1754
|
+
for (var [ruleKey, ruleValue] of Object.entries(patch.searxngRules)) {
|
|
1755
|
+
if (!isPlainObject(ruleValue)) {
|
|
1756
|
+
throw new Error(`searxngRules.${ruleKey} must be an object`);
|
|
1757
|
+
}
|
|
1758
|
+
var existing = isPlainObject(rulesEngines[ruleKey]) ? { ...rulesEngines[ruleKey] } : {};
|
|
1759
|
+
const rule = ruleValue;
|
|
1760
|
+
if (rule.enabled !== undefined) {
|
|
1761
|
+
if (rule.enabled === true) {
|
|
1762
|
+
// 「启用」是默认态,删掉 disabled 而不是写 false——与既有写法一致。
|
|
1763
|
+
delete existing.disabled;
|
|
1764
|
+
}
|
|
1765
|
+
else {
|
|
1766
|
+
existing.disabled = true;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
if (rule.proxy !== undefined) {
|
|
1770
|
+
var proxyLines = proxiesFromPatch(rule.proxy, `searxngRules.${ruleKey}.proxy`);
|
|
1771
|
+
if (Object.keys(proxyLines).length === 0) {
|
|
1772
|
+
delete existing.proxies;
|
|
1773
|
+
}
|
|
1774
|
+
else {
|
|
1775
|
+
existing.proxies = proxyLines;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
if (Object.keys(existing).length > 0) {
|
|
1779
|
+
rulesEngines[ruleKey] = existing;
|
|
1780
|
+
}
|
|
1781
|
+
else {
|
|
1782
|
+
delete rulesEngines[ruleKey];
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
if (Object.keys(rulesEngines).length === 0) {
|
|
1786
|
+
delete rulesBase.engines;
|
|
1787
|
+
}
|
|
1788
|
+
else {
|
|
1789
|
+
rulesBase.engines = rulesEngines;
|
|
1790
|
+
}
|
|
1791
|
+
config.searxng = rulesBase;
|
|
1792
|
+
}
|
|
1793
|
+
if (patch?.searxngOutgoingProxies !== undefined) {
|
|
1794
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1795
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1796
|
+
}
|
|
1797
|
+
var outgoingSection = parseProxiesPatch(patch.searxngOutgoingProxies, 'searxng.outgoing.protocols');
|
|
1798
|
+
var outgoingBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1799
|
+
if (Object.keys(outgoingSection).length === 0) {
|
|
1800
|
+
delete outgoingBase.outgoing;
|
|
1801
|
+
}
|
|
1802
|
+
else {
|
|
1803
|
+
outgoingBase.outgoing = outgoingSection;
|
|
1804
|
+
}
|
|
1805
|
+
config.searxng = outgoingBase;
|
|
1806
|
+
}
|
|
1807
|
+
if (patch?.searxngExtraProxyTimeout !== undefined) {
|
|
1808
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1809
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1810
|
+
}
|
|
1811
|
+
var extraBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1812
|
+
var rawExtra = patch.searxngExtraProxyTimeout;
|
|
1813
|
+
if (rawExtra === null || rawExtra === '') {
|
|
1814
|
+
delete extraBase.extra_proxy_timeout;
|
|
1815
|
+
}
|
|
1816
|
+
else {
|
|
1817
|
+
var extraSeconds = typeof rawExtra === 'number' ? rawExtra : Number(rawExtra);
|
|
1818
|
+
if (!Number.isFinite(extraSeconds) || extraSeconds <= 0) {
|
|
1819
|
+
throw new Error(`invalid searxng.extra_proxy_timeout: ${String(rawExtra)} (use a positive number of seconds)`);
|
|
1820
|
+
}
|
|
1821
|
+
extraBase.extra_proxy_timeout = extraSeconds;
|
|
1822
|
+
}
|
|
1823
|
+
config.searxng = extraBase;
|
|
1824
|
+
}
|
|
1825
|
+
if (patch?.searxngNetwork !== undefined) {
|
|
1826
|
+
var networkName = typeof patch.searxngNetwork === 'string' ? patch.searxngNetwork.trim() : '';
|
|
1827
|
+
if (networkName === '') {
|
|
1828
|
+
throw new Error('searxngNetwork must be a non-empty network name');
|
|
1829
|
+
}
|
|
1830
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(networkName)) {
|
|
1831
|
+
throw new Error(`invalid network name: ${networkName} (use A-Za-z0-9_- up to 64)`);
|
|
1832
|
+
}
|
|
1833
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1834
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1835
|
+
}
|
|
1836
|
+
var networkBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1837
|
+
var networks = isPlainObject(networkBase.networks) ? { ...networkBase.networks } : {};
|
|
1838
|
+
// null 表示删掉这条网络;删除一个被引擎引用的网络会在校验时暴露出来。
|
|
1839
|
+
if (patch.searxngNetworkProxies === null) {
|
|
1840
|
+
delete networks[networkName];
|
|
1841
|
+
}
|
|
1842
|
+
else if (patch.searxngNetworkProxies !== undefined) {
|
|
1843
|
+
var networkProxies = parseProxiesPatch(patch.searxngNetworkProxies, `searxng.networks.${networkName}.protocols`);
|
|
1844
|
+
var existingNetwork = isPlainObject(networks[networkName]) ? networks[networkName] : {};
|
|
1845
|
+
var nextNetwork = { ...existingNetwork };
|
|
1846
|
+
if (Object.keys(networkProxies).length === 0)
|
|
1847
|
+
delete nextNetwork.proxies;
|
|
1848
|
+
else
|
|
1849
|
+
nextNetwork.proxies = networkProxies;
|
|
1850
|
+
networks[networkName] = nextNetwork;
|
|
1851
|
+
}
|
|
1852
|
+
if (Object.keys(networks).length === 0)
|
|
1853
|
+
delete networkBase.networks;
|
|
1854
|
+
else
|
|
1855
|
+
networkBase.networks = networks;
|
|
1856
|
+
config.searxng = networkBase;
|
|
1857
|
+
}
|
|
1858
|
+
if (patch?.searxngEngine !== undefined) {
|
|
1859
|
+
var upstreamName = typeof patch.searxngEngine === 'string' ? patch.searxngEngine.trim() : '';
|
|
1860
|
+
if (upstreamName === '') {
|
|
1861
|
+
throw new Error('searxngEngine must be a non-empty engine name');
|
|
1862
|
+
}
|
|
1863
|
+
if (config.searxng !== undefined && !isPlainObject(config.searxng)) {
|
|
1864
|
+
throw new Error('the "searxng" section of the config file is not an object');
|
|
1865
|
+
}
|
|
1866
|
+
var engineBase = { ...(isPlainObject(config.searxng) ? config.searxng : {}) };
|
|
1867
|
+
var upstreamEngines = isPlainObject(engineBase.engines) ? { ...engineBase.engines } : {};
|
|
1868
|
+
if (patch.searxngEngineRemove === true) {
|
|
1869
|
+
delete upstreamEngines[upstreamName];
|
|
1870
|
+
}
|
|
1871
|
+
else {
|
|
1872
|
+
var existingRule = isPlainObject(upstreamEngines[upstreamName])
|
|
1873
|
+
? upstreamEngines[upstreamName]
|
|
1874
|
+
: {};
|
|
1875
|
+
var nextRule = { ...existingRule };
|
|
1876
|
+
if (patch.searxngEngineNetwork !== undefined) {
|
|
1877
|
+
var networkRef = typeof patch.searxngEngineNetwork === 'string'
|
|
1878
|
+
? patch.searxngEngineNetwork.trim()
|
|
1879
|
+
: '';
|
|
1880
|
+
if (networkRef === '')
|
|
1881
|
+
delete nextRule.network;
|
|
1882
|
+
else
|
|
1883
|
+
nextRule.network = networkRef;
|
|
1884
|
+
}
|
|
1885
|
+
if (patch.searxngEngineProxies !== undefined) {
|
|
1886
|
+
var ruleProxies = parseProxiesPatch(patch.searxngEngineProxies, `searxng.engines.${upstreamName}.protocols`);
|
|
1887
|
+
if (Object.keys(ruleProxies).length === 0)
|
|
1888
|
+
delete nextRule.proxies;
|
|
1889
|
+
else
|
|
1890
|
+
nextRule.proxies = ruleProxies;
|
|
1891
|
+
}
|
|
1892
|
+
if (patch.searxngEngineTor !== undefined) {
|
|
1893
|
+
if (patch.searxngEngineTor)
|
|
1894
|
+
nextRule.using_tor_proxy = true;
|
|
1895
|
+
else
|
|
1896
|
+
delete nextRule.using_tor_proxy;
|
|
1897
|
+
}
|
|
1898
|
+
if (patch.searxngEngineDisabled !== undefined) {
|
|
1899
|
+
if (patch.searxngEngineDisabled)
|
|
1900
|
+
nextRule.disabled = true;
|
|
1901
|
+
else
|
|
1902
|
+
delete nextRule.disabled;
|
|
1903
|
+
}
|
|
1904
|
+
upstreamEngines[upstreamName] = nextRule;
|
|
1905
|
+
}
|
|
1906
|
+
if (Object.keys(upstreamEngines).length === 0)
|
|
1907
|
+
delete engineBase.engines;
|
|
1908
|
+
else
|
|
1909
|
+
engineBase.engines = upstreamEngines;
|
|
1910
|
+
config.searxng = engineBase;
|
|
1911
|
+
}
|
|
1912
|
+
// 保存前把 searxng 段整体校验一遍:引擎引用一个不存在的网络,或者代理写错了
|
|
1913
|
+
// 协议,在实例启动时才报错会让「保存成功」变成一句谎话。
|
|
1914
|
+
const searxngError = validateSearxngSection(config.searxng);
|
|
1915
|
+
if (searxngError !== null) {
|
|
1916
|
+
throw new Error(searxngError);
|
|
1917
|
+
}
|
|
1918
|
+
writeConfigFile(config);
|
|
1919
|
+
}
|
|
1920
|
+
/**
|
|
1921
|
+
* 按 src/config.ts 写配置的方式写回:在同目录下新建一个 0600 权限的文件,再
|
|
1922
|
+
* 改名就位。writeFileSync 的 mode 只在它「创建」文件时生效,所以重写一个已存在
|
|
1923
|
+
* 的 0644 配置,会让新密钥以全局可读的权限落地,直到 chmod 才收紧。
|
|
1924
|
+
*/
|
|
1925
|
+
function writeConfigFile(config) {
|
|
1926
|
+
const file = modsearchConfigPath();
|
|
1927
|
+
// 这里的符号链接会穿透到它指向的任何地方去写,所以直接拒绝而不是跟随:
|
|
1928
|
+
// CLI 写的是真实文件,别的形态都是这张卡片不该默默接受的安排。
|
|
1929
|
+
try {
|
|
1930
|
+
if (lstatSync(file).isSymbolicLink()) {
|
|
1931
|
+
throw new Error(`${file} is a symlink; edit the file it points at instead`);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
catch (error) {
|
|
1935
|
+
if (caughtCode(error) !== 'ENOENT') {
|
|
1936
|
+
throw error;
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
const dir = dirname(file);
|
|
1940
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1941
|
+
const unique = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;
|
|
1942
|
+
const tmp = join(dir, `.config.${unique}.tmp`);
|
|
1943
|
+
writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
1944
|
+
try {
|
|
1945
|
+
renameSync(tmp, file);
|
|
1946
|
+
}
|
|
1947
|
+
catch (error) {
|
|
1948
|
+
try {
|
|
1949
|
+
unlinkSync(tmp);
|
|
1950
|
+
}
|
|
1951
|
+
catch {
|
|
1952
|
+
// 改名失败才是值得报告的那个错误
|
|
1953
|
+
}
|
|
1954
|
+
throw error;
|
|
1955
|
+
}
|
|
1956
|
+
try {
|
|
1957
|
+
chmodSync(file, 0o600);
|
|
1958
|
+
}
|
|
1959
|
+
catch {
|
|
1960
|
+
// 在没有 POSIX 权限位的平台上尽力而为
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* 卡片自动模式区背后那份只读的就绪清单:这台机器上哪些引擎已经配好了。
|
|
1965
|
+
* `doctor --json` 不需要网络也没有配额,就能回答这个问题,所以这条路由拉起
|
|
1966
|
+
* 本包自带的 CLI,并从它的 roles 里取出逐引擎的判定。结果短暂缓存,因为一次
|
|
1967
|
+
* 探测要付出启动一个进程的代价,而重新展开卡片不该再付一遍;缓存以 CLI 路径
|
|
1968
|
+
* 为键,所以不同的二进制就是不同的答案。
|
|
1969
|
+
*/
|
|
1970
|
+
const READINESS_TTL_MS = 60_000;
|
|
1971
|
+
const READINESS_TIMEOUT_MS = 20_000;
|
|
1972
|
+
/** 搜索角色优先:卡片讲的是搜索,而且这也是被配置的那个角色。 */
|
|
1973
|
+
const READINESS_ROLES = ['search', 'social', 'fetch'];
|
|
1974
|
+
let readinessCache = null;
|
|
1975
|
+
async function engineReadiness() {
|
|
1976
|
+
const cli = process.env.MODSEARCH_DSH_CLI || DOCTOR_CLI_PATH;
|
|
1977
|
+
if (readinessCache !== null && readinessCache.cli === cli) {
|
|
1978
|
+
if (Date.now() - readinessCache.at < READINESS_TTL_MS) {
|
|
1979
|
+
return readinessCache.value;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
try {
|
|
1983
|
+
// 有界且可中止:卡住的探测会把卡片的展开也卡住,而卡片没有这一区照样
|
|
1984
|
+
// 能活。
|
|
1985
|
+
const { stdout, code } = await run(process.execPath, [cli, 'doctor', '--json'], AbortSignal.timeout(READINESS_TIMEOUT_MS), childEnv());
|
|
1986
|
+
if (code !== 0) {
|
|
1987
|
+
return null;
|
|
1988
|
+
}
|
|
1989
|
+
const roles = JSON.parse(stdout)?.roles;
|
|
1990
|
+
if (!Array.isArray(roles)) {
|
|
1991
|
+
return null;
|
|
1992
|
+
}
|
|
1993
|
+
const found = new Map();
|
|
1994
|
+
const ordered = [...roles].sort((a, b) => READINESS_ROLES.indexOf(a?.role) - READINESS_ROLES.indexOf(b?.role));
|
|
1995
|
+
for (const role of ordered) {
|
|
1996
|
+
for (const candidate of Array.isArray(role?.candidates) ? role.candidates : []) {
|
|
1997
|
+
const engine = canonicalEngine(candidate?.engine);
|
|
1998
|
+
// 一个引擎只按它自己的角色判定一次:firecrawl 在 search 和 fetch 两个
|
|
1999
|
+
// 角色下服务、判定还不同,而卡片讲的是搜索。
|
|
2000
|
+
if (!CARD_ENGINES.includes(engine) || found.has(engine)) {
|
|
2001
|
+
continue;
|
|
2002
|
+
}
|
|
2003
|
+
found.set(engine, {
|
|
2004
|
+
engine,
|
|
2005
|
+
role: typeof role.role === 'string' ? role.role : '',
|
|
2006
|
+
ready: candidate.ready === true,
|
|
2007
|
+
reason: typeof candidate.reason === 'string' ? candidate.reason : '',
|
|
2008
|
+
keySource: candidate.keySource ?? null,
|
|
2009
|
+
});
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
const value = CARD_ENGINES.filter((name) => found.has(name)).map((name) => found.get(name));
|
|
2013
|
+
readinessCache = { cli, at: Date.now(), value };
|
|
2014
|
+
return value;
|
|
2015
|
+
}
|
|
2016
|
+
catch {
|
|
2017
|
+
return null;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
/**
|
|
2021
|
+
* GET /searchfuse/config:上面那份摘要。POST:一次卡片提交。部署层的鉴权必须
|
|
2022
|
+
* 覆盖这条路由。裸的 webServer 注册表不继承 dsh 的 Connection 鉴权,而本插件
|
|
2023
|
+
* 自己也不施加任何 Host、Origin 或 Fetch Metadata 策略。
|
|
2024
|
+
*
|
|
2025
|
+
* 注册表会返回一个 disposer,但不把它绑定到任何人的生命周期上,而服务器的
|
|
2026
|
+
* 寿命比本插件长:Plugins 页面会不重启地关掉再打开一个 bundle。用 effect 持有
|
|
2027
|
+
* 它,路由就随插件一起走。放任不管的话,它会继续为一个已经关闭的插件提供配置
|
|
2028
|
+
* 文件,还让下一次打开变成重复注册。
|
|
2029
|
+
*/
|
|
2030
|
+
/**
|
|
2031
|
+
* 与 CLI 应用于 `engines.<name>.proxy` 的三值规则相同。这里重复实现而不是
|
|
2032
|
+
* 导入,因为本文件是手写的 JavaScript,够不到 TypeScript 源码;覆盖引擎清单
|
|
2033
|
+
* 的那个同步测试,就是让它们保持一致的样板。
|
|
2034
|
+
*/
|
|
2035
|
+
/**
|
|
2036
|
+
* 校验整段 `searxng`,返回第一条错误或 null。
|
|
2037
|
+
*
|
|
2038
|
+
* 这是 src/providers/searxngSettings.ts 里 validateSearxngConfig 的宿主侧
|
|
2039
|
+
* 对应实现:插件文件不能 import TypeScript 源码,所以规则在这里复写一遍,
|
|
2040
|
+
* 由 src/dshPlugin.test.ts 的锁步测试保证两边的错误消息与判定一致。
|
|
2041
|
+
*/
|
|
2042
|
+
function validateSearxngSection(section) {
|
|
2043
|
+
if (!isPlainObject(section))
|
|
2044
|
+
return null;
|
|
2045
|
+
const outgoingError = validateProxiesShape(section.outgoing, 'searxng.outgoing');
|
|
2046
|
+
if (outgoingError !== null)
|
|
2047
|
+
return outgoingError;
|
|
2048
|
+
const networks = (isPlainObject(section.networks) ? section.networks : {});
|
|
2049
|
+
for (const [name, rawNetwork] of Object.entries(networks)) {
|
|
2050
|
+
if (name.trim() === '')
|
|
2051
|
+
return 'searxng.networks: a network name is empty';
|
|
2052
|
+
const network = rawNetwork;
|
|
2053
|
+
const error = validateProxiesShape(network?.proxies, `searxng.networks.${name}.proxies`);
|
|
2054
|
+
if (error !== null)
|
|
2055
|
+
return error;
|
|
2056
|
+
}
|
|
2057
|
+
// extra_proxy_timeout 属于 outgoing 整体:SearXNG 的 Network.__init__
|
|
2058
|
+
// 不接受这个名字,写在某条网络下会让实例启动直接失败。
|
|
2059
|
+
const extra = section.extra_proxy_timeout;
|
|
2060
|
+
if (extra !== undefined) {
|
|
2061
|
+
if (typeof extra !== 'number' || !Number.isFinite(extra) || extra <= 0) {
|
|
2062
|
+
return 'searxng.extra_proxy_timeout must be a positive number';
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
const upstream = (isPlainObject(section.engines) ? section.engines : {});
|
|
2066
|
+
for (const [name, rawRule] of Object.entries(upstream)) {
|
|
2067
|
+
if (name.trim() === '')
|
|
2068
|
+
return 'searxng.engines: an engine name is empty';
|
|
2069
|
+
const rule = rawRule;
|
|
2070
|
+
if (rule?.network !== undefined && !Object.hasOwn(networks, String(rule.network))) {
|
|
2071
|
+
const known = Object.keys(networks);
|
|
2072
|
+
return `searxng.engines.${name}.network "${String(rule.network)}" is not defined in searxng.networks (known: ${known.length > 0 ? known.join(', ') : 'none'})`;
|
|
2073
|
+
}
|
|
2074
|
+
const error = validateProxiesShape(rule?.proxies, `searxng.engines.${name}.proxies`);
|
|
2075
|
+
if (error !== null)
|
|
2076
|
+
return error;
|
|
2077
|
+
}
|
|
2078
|
+
return null;
|
|
2079
|
+
}
|
|
2080
|
+
/** 校验一个已经写进文件的 `proxies` 形状。 */
|
|
2081
|
+
function validateProxiesShape(proxies, where) {
|
|
2082
|
+
if (proxies === undefined)
|
|
2083
|
+
return null;
|
|
2084
|
+
if (!isPlainObject(proxies))
|
|
2085
|
+
return `${where}: must be an object of protocols`;
|
|
2086
|
+
for (const key of Object.keys(proxies)) {
|
|
2087
|
+
if (key !== 'http' && key !== 'https' && key !== 'all://') {
|
|
2088
|
+
return `${where}: unknown proxies key "${key}"; use http, https, or all://`;
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
for (const [key, raw] of Object.entries(proxies)) {
|
|
2092
|
+
if (raw === undefined)
|
|
2093
|
+
continue;
|
|
2094
|
+
const list = Array.isArray(raw) ? raw : [raw];
|
|
2095
|
+
for (const proxy of list) {
|
|
2096
|
+
if (typeof proxy !== 'string')
|
|
2097
|
+
return `${where}.${key}: proxy must be a string`;
|
|
2098
|
+
try {
|
|
2099
|
+
const parsed = new URL(proxy);
|
|
2100
|
+
if (!['http:', 'https:', 'socks5:', 'socks5h:'].includes(parsed.protocol)) {
|
|
2101
|
+
return `${where}.${key}: invalid proxy "${proxy}"`;
|
|
2102
|
+
}
|
|
2103
|
+
if (parsed.hostname === '')
|
|
2104
|
+
return `${where}.${key}: invalid proxy "${proxy}"`;
|
|
2105
|
+
}
|
|
2106
|
+
catch {
|
|
2107
|
+
return `${where}.${key}: invalid proxy "${proxy}"`;
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
return null;
|
|
2112
|
+
}
|
|
2113
|
+
/**
|
|
2114
|
+
* 把「一行一个代理」的文本转成 proxies 结构。
|
|
2115
|
+
*
|
|
2116
|
+
* 卡片用文本框承载逐引擎代理(一行一个),这里负责把它规范成
|
|
2117
|
+
* `{ 'all://': [...] }`。空文本 = 清掉该引擎的代理覆盖。
|
|
2118
|
+
*
|
|
2119
|
+
* 校验与 `parseProxiesPatch` 同源:协议只认 http(s)/socks5(h),
|
|
2120
|
+
* 缺 scheme 或主机都当场报错,而不是等实例启动时才炸。
|
|
2121
|
+
*/
|
|
2122
|
+
function proxiesFromPatch(text, where) {
|
|
2123
|
+
var raw = typeof text === 'string' ? text : '';
|
|
2124
|
+
var lines = raw
|
|
2125
|
+
.split(/\r?\n/)
|
|
2126
|
+
.map((line) => line.trim())
|
|
2127
|
+
.filter((line) => line !== '');
|
|
2128
|
+
if (lines.length === 0)
|
|
2129
|
+
return {};
|
|
2130
|
+
var parsed = [];
|
|
2131
|
+
for (var line of lines) {
|
|
2132
|
+
var url;
|
|
2133
|
+
try {
|
|
2134
|
+
url = new URL(line);
|
|
2135
|
+
}
|
|
2136
|
+
catch {
|
|
2137
|
+
throw new Error(`${where}: invalid proxy "${line}". Include a scheme, e.g. http://127.0.0.1:7890`);
|
|
2138
|
+
}
|
|
2139
|
+
if (!['http:', 'https:', 'socks5:', 'socks5h:'].includes(url.protocol)) {
|
|
2140
|
+
throw new Error(`${where}: unsupported scheme "${url.protocol.replace(':', '')}" in "${line}"`);
|
|
2141
|
+
}
|
|
2142
|
+
if (url.hostname === '') {
|
|
2143
|
+
throw new Error(`${where}: invalid proxy "${line}": missing host`);
|
|
2144
|
+
}
|
|
2145
|
+
parsed.push(line);
|
|
2146
|
+
}
|
|
2147
|
+
return { 'all://': parsed.length === 1 ? parsed[0] : parsed };
|
|
2148
|
+
}
|
|
2149
|
+
/**
|
|
2150
|
+
* 把卡片提交的一份 `{ http, https, all:// }` 规范成 SearXNG 认的代理表。
|
|
2151
|
+
*
|
|
2152
|
+
* 规则与 src/providers/searxngSettings.ts 的 validateProxies 完全一致:
|
|
2153
|
+
* 键只有三种,值可以是单个 URL 或 URL 数组,每个 URL 自带 http(s)/socks5(h)
|
|
2154
|
+
* 协议。两套规则必须同源,否则卡片能保存出一份实例读不进去的配置。
|
|
2155
|
+
*
|
|
2156
|
+
* `''` 或空对象表示「这一协议不要代理」;返回对象里不出现该键,渲染时也就
|
|
2157
|
+
* 不会写出去。
|
|
2158
|
+
*/
|
|
2159
|
+
function parseProxiesPatch(raw, where) {
|
|
2160
|
+
if (!isPlainObject(raw)) {
|
|
2161
|
+
throw new Error(`${where} must be an object like { "all://": "http://127.0.0.1:7890" }`);
|
|
2162
|
+
}
|
|
2163
|
+
const allowed = ['http', 'https', 'all://'];
|
|
2164
|
+
const result = {};
|
|
2165
|
+
for (const [rawKey, rawValue] of Object.entries(raw)) {
|
|
2166
|
+
if (rawValue === undefined || rawValue === null)
|
|
2167
|
+
continue;
|
|
2168
|
+
if (!allowed.includes(rawKey)) {
|
|
2169
|
+
throw new Error(`${where}: unknown protocols key "${rawKey}"; use http, https, or all://`);
|
|
2170
|
+
}
|
|
2171
|
+
// 数组表示同一协议下轮询使用;单个字符串是它的简写。
|
|
2172
|
+
const list = Array.isArray(rawValue) ? rawValue : [rawValue];
|
|
2173
|
+
const proxies = [];
|
|
2174
|
+
for (const entry of list) {
|
|
2175
|
+
if (typeof entry !== 'string') {
|
|
2176
|
+
throw new Error(`${where}.${rawKey}: proxy must be a string`);
|
|
2177
|
+
}
|
|
2178
|
+
const trimmed = entry.trim();
|
|
2179
|
+
if (trimmed === '')
|
|
2180
|
+
continue;
|
|
2181
|
+
let parsed;
|
|
2182
|
+
try {
|
|
2183
|
+
parsed = new URL(trimmed);
|
|
2184
|
+
}
|
|
2185
|
+
catch {
|
|
2186
|
+
throw new Error(`invalid proxy "${trimmed}": include a scheme, e.g. http://127.0.0.1:7890`);
|
|
2187
|
+
}
|
|
2188
|
+
if (!['http:', 'https:', 'socks5:', 'socks5h:'].includes(parsed.protocol)) {
|
|
2189
|
+
throw new Error(`invalid proxy "${trimmed}": unsupported scheme "${parsed.protocol.replace(':', '')}"; ` +
|
|
2190
|
+
'use http, https, socks5, or socks5h');
|
|
2191
|
+
}
|
|
2192
|
+
if (parsed.hostname === '') {
|
|
2193
|
+
throw new Error(`invalid proxy "${trimmed}": missing host`);
|
|
2194
|
+
}
|
|
2195
|
+
proxies.push(trimmed);
|
|
2196
|
+
}
|
|
2197
|
+
// 单值写成字符串,多值写成数组:与 SearXNG 的 settings.yml 写法一一对应,
|
|
2198
|
+
// 用户把卡片里看到的内容抄进文件时不用改形状。
|
|
2199
|
+
if (proxies.length === 1)
|
|
2200
|
+
result[rawKey] = proxies[0];
|
|
2201
|
+
else if (proxies.length > 1)
|
|
2202
|
+
result[rawKey] = proxies;
|
|
2203
|
+
}
|
|
2204
|
+
return result;
|
|
2205
|
+
}
|
|
2206
|
+
function isValidProxyValue(value) {
|
|
2207
|
+
if (value === 'direct' || value === 'none') {
|
|
2208
|
+
return true;
|
|
2209
|
+
}
|
|
2210
|
+
if (!/^https?:\/\//i.test(value)) {
|
|
2211
|
+
return false;
|
|
2212
|
+
}
|
|
2213
|
+
try {
|
|
2214
|
+
const parsed = new URL(value);
|
|
2215
|
+
return parsed.hostname !== '';
|
|
2216
|
+
}
|
|
2217
|
+
catch {
|
|
2218
|
+
return false;
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
/**
|
|
2222
|
+
* 盯着配置文件,发现改动就回调。
|
|
2223
|
+
*
|
|
2224
|
+
* 宿主的 profile 重载信号永远不会为这份文件触发——它是插件自己的,不在
|
|
2225
|
+
* profile 里。每隔几秒 stat 一次是最便宜的发现办法;文件很小,代价可以忽略。
|
|
2226
|
+
*
|
|
2227
|
+
* 定时器用 unref 放掉,免得它自己把进程撑住;拆除登记在 ctx 上,所以插件
|
|
2228
|
+
* 卸载时不会留下一个还在跑的定时器。回调抛出的东西由调用方自己接住:这个
|
|
2229
|
+
* 助手只负责发现改动,不替调用方决定失败该怎么办。
|
|
2230
|
+
*
|
|
2231
|
+
* @returns 停止监视的函数。正常路径用不到它——ctx 卸载时会自己停掉。
|
|
2232
|
+
*/
|
|
2233
|
+
function watchModsearchConfigFile(ctx, onChange) {
|
|
2234
|
+
const file = modsearchConfigPath();
|
|
2235
|
+
let lastMtime;
|
|
2236
|
+
try {
|
|
2237
|
+
lastMtime = statSync(file).mtimeMs;
|
|
2238
|
+
}
|
|
2239
|
+
catch {
|
|
2240
|
+
// 还没有配置文件:把它当成「什么都没有」,第一次创建就是一次改动。
|
|
2241
|
+
lastMtime = undefined;
|
|
2242
|
+
}
|
|
2243
|
+
const pollTimer = setInterval(() => {
|
|
2244
|
+
let mtime;
|
|
2245
|
+
try {
|
|
2246
|
+
mtime = statSync(file).mtimeMs;
|
|
2247
|
+
}
|
|
2248
|
+
catch {
|
|
2249
|
+
// 文件被删掉也是一次值得理会的改动。
|
|
2250
|
+
mtime = undefined;
|
|
2251
|
+
}
|
|
2252
|
+
if (mtime === lastMtime) {
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
lastMtime = mtime;
|
|
2256
|
+
onChange();
|
|
2257
|
+
}, CONFIG_POLL_MS);
|
|
2258
|
+
if (typeof pollTimer?.unref === 'function') {
|
|
2259
|
+
pollTimer.unref();
|
|
2260
|
+
}
|
|
2261
|
+
const stop = () => {
|
|
2262
|
+
clearInterval(pollTimer);
|
|
2263
|
+
};
|
|
2264
|
+
try {
|
|
2265
|
+
ctx.effect(() => () => stop(), 'modsearch: config watch');
|
|
2266
|
+
}
|
|
2267
|
+
catch {
|
|
2268
|
+
// 一个已经失效的 ctx 没有 fiber 可以挂拆除;定时器会活到进程结束,
|
|
2269
|
+
// 这正是宿主对一个从不卸载的插件的处理方式。
|
|
2270
|
+
}
|
|
2271
|
+
return stop;
|
|
2272
|
+
}
|
|
2273
|
+
/**
|
|
2274
|
+
* 绑定配置文件 `mcp` 下点名的 MCP 服务器。
|
|
2275
|
+
*
|
|
2276
|
+
* 两条性质要紧:
|
|
2277
|
+
*
|
|
2278
|
+
* - 一个服务器连不上,绝不能拖住插件。搜索是产品;MCP 是附加项。每次失败
|
|
2279
|
+
* 变一行日志,其余服务器照常注册。
|
|
2280
|
+
* - session 活得比本次调用更久(已注册的工具要用它们),所以它们的拆除登记
|
|
2281
|
+
* 在 fiber 上。卸载插件会关掉它们。
|
|
2282
|
+
*
|
|
2283
|
+
* 注册是异步的,而 `apply` 是同步的。工作启动后,等它落定工具才出现;在一台
|
|
2284
|
+
* 服务器慢或不可达的机器上,搜索立刻可用,而不是等一个来回之后才可用。
|
|
2285
|
+
*/
|
|
2286
|
+
function registerMcpTools(ctx) {
|
|
2287
|
+
let result;
|
|
2288
|
+
let disposed = false;
|
|
2289
|
+
let lastSignature = '';
|
|
2290
|
+
let inFlight = false;
|
|
2291
|
+
/** 失败后的自动重试定时器;null 表示没有排队的重试。 */
|
|
2292
|
+
let retryTimer = null;
|
|
2293
|
+
/** 配置里决定「哪些工具存在」的那一部分。 */
|
|
2294
|
+
const signatureOf = (servers) => {
|
|
2295
|
+
const shape = Object.entries(servers)
|
|
2296
|
+
.filter(([, server]) => isPlainObject(server))
|
|
2297
|
+
.map(([key, rawServer]) => {
|
|
2298
|
+
const server = rawServer;
|
|
2299
|
+
return [
|
|
2300
|
+
key,
|
|
2301
|
+
server.enabled !== false,
|
|
2302
|
+
Array.isArray(server.allowTools) ? [...server.allowTools].sort() : null,
|
|
2303
|
+
isPlainObject(server.toolNames) ? Object.entries(server.toolNames).sort() : null,
|
|
2304
|
+
typeof server.url === 'string' ? server.url : null,
|
|
2305
|
+
];
|
|
2306
|
+
})
|
|
2307
|
+
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
|
|
2308
|
+
return JSON.stringify(shape);
|
|
2309
|
+
};
|
|
2310
|
+
const settle = async () => {
|
|
2311
|
+
if (inFlight) {
|
|
2312
|
+
return;
|
|
2313
|
+
}
|
|
2314
|
+
inFlight = true;
|
|
2315
|
+
let config;
|
|
2316
|
+
try {
|
|
2317
|
+
config = readModsearchConfig();
|
|
2318
|
+
}
|
|
2319
|
+
catch (error) {
|
|
2320
|
+
console.error(`[searchfuse] mcp skipped: ${caughtMessage(error)}`);
|
|
2321
|
+
inFlight = false;
|
|
2322
|
+
return;
|
|
2323
|
+
}
|
|
2324
|
+
const servers = (isPlainObject(config.mcp) ? config.mcp : {});
|
|
2325
|
+
const enabled = Object.entries(servers).filter(([, rawServer]) => isPlainObject(rawServer) && rawServer.enabled !== false);
|
|
2326
|
+
const signature = signatureOf(servers);
|
|
2327
|
+
// 自上一趟以来没有任何变化:已注册的工具正是对这一份配置的应答,替换它们
|
|
2328
|
+
// 只会毫无理由地把活着的工具定义删掉再重建。
|
|
2329
|
+
if (signature === lastSignature && result !== undefined) {
|
|
2330
|
+
inFlight = false;
|
|
2331
|
+
return;
|
|
2332
|
+
}
|
|
2333
|
+
// 旧的一代先走。旧工具仍被占用时注册新工具,会在同名上冲突,让整趟注册
|
|
2334
|
+
// 失败。
|
|
2335
|
+
if (result !== undefined) {
|
|
2336
|
+
result.disposeTools();
|
|
2337
|
+
await result.closeAll().catch(() => undefined);
|
|
2338
|
+
result = undefined;
|
|
2339
|
+
}
|
|
2340
|
+
lastSignature = signature;
|
|
2341
|
+
if (enabled.length === 0) {
|
|
2342
|
+
inFlight = false;
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
// 注册表自己产出它要的东西;宿主接受裸 JSON-Schema 定义,所以本插件仍然
|
|
2346
|
+
// 不导入任何 @deepseek-ai 包。
|
|
2347
|
+
let mod;
|
|
2348
|
+
try {
|
|
2349
|
+
// 这是构建产物,随包发布而不在本仓库的编译范围里;它没有 .d.ts,
|
|
2350
|
+
// 官方文档也没有承诺导出形状,所以这里显式忽略缺失的声明。
|
|
2351
|
+
// @ts-expect-error -- 生成的 JS 模块没有类型声明
|
|
2352
|
+
mod = await import('../dist/mcp-registry.js');
|
|
2353
|
+
}
|
|
2354
|
+
catch (error) {
|
|
2355
|
+
console.error(`[searchfuse] mcp client unavailable: ${caughtMessage(error)}`);
|
|
2356
|
+
inFlight = false;
|
|
2357
|
+
return;
|
|
2358
|
+
}
|
|
2359
|
+
if (disposed) {
|
|
2360
|
+
inFlight = false;
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
try {
|
|
2364
|
+
const registered = await mod.registerMcpServers(ctx, {
|
|
2365
|
+
servers: Object.fromEntries(enabled),
|
|
2366
|
+
allowTools: collectMcpAllowLists(servers),
|
|
2367
|
+
toolNames: collectMcpToolNames(servers),
|
|
2368
|
+
// 既有内置工具,也有用户提升为工具的任何引擎:这些名字已经在屏幕上
|
|
2369
|
+
// 了,一个服务器悄悄占用其中一个,等于把一个能用的工具换成别人的。
|
|
2370
|
+
reservedNames: [...BASE_TOOL_NAMES, ...engineToolNames()],
|
|
2371
|
+
});
|
|
2372
|
+
result = registered;
|
|
2373
|
+
}
|
|
2374
|
+
catch (error) {
|
|
2375
|
+
console.error(`[searchfuse] mcp registration failed: ${caughtMessage(error)}`);
|
|
2376
|
+
inFlight = false;
|
|
2377
|
+
return;
|
|
2378
|
+
}
|
|
2379
|
+
inFlight = false;
|
|
2380
|
+
// 从这一行起,`result` 就是这一代注册的会话;上面的 try/catch 已保证失败
|
|
2381
|
+
// 路径提前返回,所以这里用一个局部常量把「可能未定义」收窄掉。
|
|
2382
|
+
const session = result;
|
|
2383
|
+
if (disposed) {
|
|
2384
|
+
// 插件在它进行中时消失了:它刚注册的工具已经随 fiber 一起拆除,但 session
|
|
2385
|
+
// 是这一次调用自己的责任。
|
|
2386
|
+
await session.closeAll().catch(() => undefined);
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
for (const report of session.reports) {
|
|
2390
|
+
if (report.error) {
|
|
2391
|
+
console.error(`[searchfuse] mcp ${report.serverKey}: ${report.error}`);
|
|
2392
|
+
}
|
|
2393
|
+
// 跳过只记一条信息,不进重试判定:宿主已有同名工具是稳定事实,
|
|
2394
|
+
// 每 30 秒重试一次同样的跳过没有任何意义。
|
|
2395
|
+
for (const note of report.skipped ?? []) {
|
|
2396
|
+
console.error(`[searchfuse] mcp ${report.serverKey}: tool ${note}; skipped`);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
// 有服务端没连上:安排一次稍后的重试。
|
|
2400
|
+
//
|
|
2401
|
+
// 启动那一刻的网络抖动不该让一个服务端的工具永久消失。签名机制挡的是
|
|
2402
|
+
// 「配置没变还重连」,但它也意味着失败之后不会自己再试——用户得改点什么
|
|
2403
|
+
// 才会触发下一轮。这里补上自动重试,并给一个足够长的间隔:立刻重试只会
|
|
2404
|
+
// 撞上同一个故障,而太长的等待又让恢复显得像卡住了。
|
|
2405
|
+
const failed = session.reports.filter((r) => r.error !== undefined);
|
|
2406
|
+
if (failed.length > 0 && !disposed && retryTimer === null) {
|
|
2407
|
+
retryTimer = setTimeout(() => {
|
|
2408
|
+
retryTimer = null;
|
|
2409
|
+
if (disposed) {
|
|
2410
|
+
return;
|
|
2411
|
+
}
|
|
2412
|
+
// 清掉签名,让 settle 认为「配置变了」而重新注册:失败的那些服务端
|
|
2413
|
+
// 要借此获得第二次机会,而已经连上的会因为同名冲突预先被 disposeTools
|
|
2414
|
+
// 拆掉再重建——代价是它们也要重新握手一次,但这是唯一能让两者同时
|
|
2415
|
+
// 成立的路径,且只在有失败时才发生。
|
|
2416
|
+
lastSignature = '';
|
|
2417
|
+
settle().catch((error) => {
|
|
2418
|
+
console.error(`[searchfuse] mcp retry failed: ${caughtMessage(error)}`);
|
|
2419
|
+
});
|
|
2420
|
+
}, MCP_RETRY_DELAY_MS);
|
|
2421
|
+
if (typeof retryTimer?.unref === 'function') {
|
|
2422
|
+
retryTimer.unref();
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
};
|
|
2426
|
+
try {
|
|
2427
|
+
ctx.effect(() => () => {
|
|
2428
|
+
disposed = true;
|
|
2429
|
+
if (retryTimer !== null) {
|
|
2430
|
+
clearTimeout(retryTimer);
|
|
2431
|
+
retryTimer = null;
|
|
2432
|
+
}
|
|
2433
|
+
result?.closeAll().catch(() => undefined);
|
|
2434
|
+
}, 'modsearch: mcp sessions');
|
|
2435
|
+
}
|
|
2436
|
+
catch {
|
|
2437
|
+
// 一个已经失效的 ctx 没有 fiber 可以把拆除挂上去;于是 session 会活到进程
|
|
2438
|
+
// 结束,这正是宿主对一个从不卸载的插件的处理方式。
|
|
2439
|
+
}
|
|
2440
|
+
// 配置文件是插件自己的,所以宿主的 profile 重载信号永远不会为它触发。监视器
|
|
2441
|
+
// 由 apply 统一建一套,这里只把重载入口交出去:MCP 与独立引擎工具读的是同一
|
|
2442
|
+
// 份文件,各起一套定时器只会让两边在改动后短暂地看法不一致。
|
|
2443
|
+
settle().catch((error) => {
|
|
2444
|
+
console.error(`[searchfuse] mcp setup failed: ${error?.message ?? error}`);
|
|
2445
|
+
});
|
|
2446
|
+
return settle;
|
|
2447
|
+
}
|
|
2448
|
+
/** 服务器请求隐藏的 `<serverKey>/<toolName>` 条目。 */
|
|
2449
|
+
function collectMcpAllowLists(servers) {
|
|
2450
|
+
const allow = {};
|
|
2451
|
+
for (const [key, rawServer] of Object.entries(servers)) {
|
|
2452
|
+
const server = rawServer;
|
|
2453
|
+
if (Array.isArray(server?.allowTools)) {
|
|
2454
|
+
allow[key] = server.allowTools.filter((name) => typeof name === 'string');
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
return allow;
|
|
2458
|
+
}
|
|
2459
|
+
/** `<serverKey>/<rawName>` 映射到调用方选定的工具名。 */
|
|
2460
|
+
function collectMcpToolNames(servers) {
|
|
2461
|
+
const names = {};
|
|
2462
|
+
for (const [key, rawServer] of Object.entries(servers)) {
|
|
2463
|
+
const server = rawServer;
|
|
2464
|
+
if (isPlainObject(server?.toolNames)) {
|
|
2465
|
+
for (const [raw, chosen] of Object.entries((server.toolNames ?? {}))) {
|
|
2466
|
+
if (typeof chosen === 'string' && chosen !== '') {
|
|
2467
|
+
names[`${key}/${raw}`] = chosen;
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
return names;
|
|
2473
|
+
}
|
|
2474
|
+
/**
|
|
2475
|
+
* 独立引擎工具。
|
|
2476
|
+
*
|
|
2477
|
+
* 标了 `expose.tool` 的引擎就变成模型能按名字调用的工具,无论它是否也加入
|
|
2478
|
+
* 融合答案。这是曝光矩阵的另一半:没有它,「只做独立工具」就配置出一个任何
|
|
2479
|
+
* 模型都够不着的引擎。
|
|
2480
|
+
*
|
|
2481
|
+
* 注册是同步的,而且直接读配置文件,所以配置问题会在加载时暴露,并点名是哪
|
|
2482
|
+
* 个文件,而不是变成一个莫名其妙什么都不做的工具。
|
|
2483
|
+
*/
|
|
2484
|
+
function registerEngineTools(ctx) {
|
|
2485
|
+
/** 上一轮注册的撤销句柄,以及那一轮对应的配置签名。 */
|
|
2486
|
+
const registered = [];
|
|
2487
|
+
let lastSignature;
|
|
2488
|
+
/**
|
|
2489
|
+
* 配置里决定「哪些引擎工具存在」的那一部分:名字、引擎、以及开关。
|
|
2490
|
+
*
|
|
2491
|
+
* 密钥、代理、baseURL 之类刻意不进签名:换一把密钥不该让工具在屏幕上消失
|
|
2492
|
+
* 又出现一次,而用户是看着那个列表点下去的。
|
|
2493
|
+
*/
|
|
2494
|
+
const signatureOf = (engines) => {
|
|
2495
|
+
// 遍历全部已知引擎而不是只遍历文件里那些条目:被默认关闭的引擎(在
|
|
2496
|
+
// OFF_UNLESS_ENABLED 里的那些)在配置里往往没有条目,只遍历文件会让
|
|
2497
|
+
// 签名看不出用户把它打开了——热重载于是不会重新注册它的工具。
|
|
2498
|
+
const shape = CARD_ENGINES.map((name) => {
|
|
2499
|
+
const settings = isPlainObject(engines[name]) ? engines[name] : {};
|
|
2500
|
+
const expose = isPlainObject(settings.expose) ? settings.expose : {};
|
|
2501
|
+
return [
|
|
2502
|
+
name,
|
|
2503
|
+
expose.tool === true,
|
|
2504
|
+
coerceBoolean(settings.enabled) !== false,
|
|
2505
|
+
typeof settings.toolName === 'string' ? settings.toolName.trim() : '',
|
|
2506
|
+
];
|
|
2507
|
+
});
|
|
2508
|
+
return JSON.stringify(shape);
|
|
2509
|
+
};
|
|
2510
|
+
const disposeAll = () => {
|
|
2511
|
+
for (const undo of registered) {
|
|
2512
|
+
try {
|
|
2513
|
+
undo();
|
|
2514
|
+
}
|
|
2515
|
+
catch {
|
|
2516
|
+
// 已经消失的工具不值得当成错误上报。
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
registered.length = 0;
|
|
2520
|
+
};
|
|
2521
|
+
const reload = () => {
|
|
2522
|
+
let config;
|
|
2523
|
+
try {
|
|
2524
|
+
config = readModsearchConfig();
|
|
2525
|
+
}
|
|
2526
|
+
catch (error) {
|
|
2527
|
+
// 配置文件坏了:保留现有工具,而不是先把它们撤掉再发现没东西可注册。
|
|
2528
|
+
// 一份写着半截 JSON 的文件不该让模型手里的工具突然消失。
|
|
2529
|
+
console.error(`[searchfuse] engine tools reload skipped: ${caughtMessage(error)}`);
|
|
2530
|
+
return;
|
|
2531
|
+
}
|
|
2532
|
+
const engines = isPlainObject(config.engines) ? config.engines : {};
|
|
2533
|
+
const signature = signatureOf(engines);
|
|
2534
|
+
if (signature === lastSignature) {
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
// 旧的一代先走:新工具与旧工具同名的场合,同时存在会让整趟注册失败。
|
|
2538
|
+
disposeAll();
|
|
2539
|
+
lastSignature = signature;
|
|
2540
|
+
const claimed = new Set(BASE_TOOL_NAMES);
|
|
2541
|
+
// 遍历全部已知引擎,而不是只遍历配置文件里那些条目。
|
|
2542
|
+
//
|
|
2543
|
+
// 用户可以在卡片上给一个默认关闭的引擎(arXiv、antigravity-cli)打开
|
|
2544
|
+
// 工具形态;那样一来配置里就有了它的条目。但反过来,一个从没被碰过的
|
|
2545
|
+
// 引擎在文件里没有条目,只遍历文件就永远看不到它——而「它此刻是不是
|
|
2546
|
+
// 开着」正是签名要比对的东西。
|
|
2547
|
+
//
|
|
2548
|
+
// 配置里可能用别名写同一个引擎(`exa` / `Exa`),`fileSettingsFor` 会按
|
|
2549
|
+
// 别名聚合,所以这里按键查也不会漏。
|
|
2550
|
+
for (const engine of CARD_ENGINES) {
|
|
2551
|
+
const rawSettings = fileSettingsFor(engine, config);
|
|
2552
|
+
const expose = isPlainObject(rawSettings.expose) ? rawSettings.expose : {};
|
|
2553
|
+
if (expose.tool !== true) {
|
|
2554
|
+
continue;
|
|
2555
|
+
}
|
|
2556
|
+
// `enabled: false` 是彻底的总开关,不只是「不参与融合」。用户关掉的引擎
|
|
2557
|
+
// 不能再以工具的身份出现:否则这个开关的含义就跟它说的不一样了。
|
|
2558
|
+
// 用 engineEnabled 而不是直接查 enabled:默认关闭的引擎从没在文件里
|
|
2559
|
+
// 写过 enabled,只查文件等于让它们绕过了这道闸。
|
|
2560
|
+
if (!engineEnabled(engine, rawSettings)) {
|
|
2561
|
+
continue;
|
|
2562
|
+
}
|
|
2563
|
+
const name = typeof rawSettings.toolName === 'string' && rawSettings.toolName.trim() !== ''
|
|
2564
|
+
? rawSettings.toolName.trim()
|
|
2565
|
+
: `${engine}_search`;
|
|
2566
|
+
if (claimed.has(name)) {
|
|
2567
|
+
console.error(`[searchfuse] engine tool skipped: "${name}" is already taken`);
|
|
2568
|
+
continue;
|
|
2569
|
+
}
|
|
2570
|
+
claimed.add(name);
|
|
2571
|
+
const undo = ctx.tools.register(engineToolDefinition({ name, engine, describe: engineDescription(engine) }));
|
|
2572
|
+
if (typeof undo === 'function') {
|
|
2573
|
+
registered.push(undo);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
};
|
|
2577
|
+
reload();
|
|
2578
|
+
return reload;
|
|
2579
|
+
}
|
|
2580
|
+
/** 把一个引擎做成独立工具:它自己的 source、它自己的引擎钉住项。 */
|
|
2581
|
+
function engineToolDefinition({ name, engine, describe }) {
|
|
2582
|
+
return {
|
|
2583
|
+
name,
|
|
2584
|
+
description: describe,
|
|
2585
|
+
parameters: {
|
|
2586
|
+
type: 'object',
|
|
2587
|
+
properties: {
|
|
2588
|
+
query: { type: 'string', description: 'What to search for' },
|
|
2589
|
+
max_results: {
|
|
2590
|
+
type: 'number',
|
|
2591
|
+
description: 'Maximum number of result items (default 8)',
|
|
2592
|
+
},
|
|
2593
|
+
},
|
|
2594
|
+
required: ['query'],
|
|
2595
|
+
},
|
|
2596
|
+
output: {
|
|
2597
|
+
schema: SEARCH_OUTPUT_SCHEMA,
|
|
2598
|
+
render: (_args, value) => [{ type: 'text', text: renderSearchEvidence(value) }],
|
|
2599
|
+
presentationMeta: (_args, value) => ({ sources: toSources(value.items) }),
|
|
2600
|
+
},
|
|
2601
|
+
timeoutMs: OWN_TOOL_BACKSTOP_MS,
|
|
2602
|
+
isConcurrencySafe: () => true,
|
|
2603
|
+
presentCall: (args) => ({
|
|
2604
|
+
card: 'generic',
|
|
2605
|
+
title: name,
|
|
2606
|
+
kind: 'search',
|
|
2607
|
+
rawInput: args,
|
|
2608
|
+
}),
|
|
2609
|
+
presentResult: (_args, result) => {
|
|
2610
|
+
if (result.isError || !result.meta || !Array.isArray(result.meta.sources)) {
|
|
2611
|
+
return undefined;
|
|
2612
|
+
}
|
|
2613
|
+
return { card: 'web', kind: 'search', sources: result.meta.sources, truncated: false };
|
|
2614
|
+
},
|
|
2615
|
+
async execute(args, exec) {
|
|
2616
|
+
if (typeof args?.query !== 'string' || args.query.trim() === '') {
|
|
2617
|
+
throw new Error(`${name} needs a non-empty string "query".`);
|
|
2618
|
+
}
|
|
2619
|
+
const cliArgs = [
|
|
2620
|
+
'-q',
|
|
2621
|
+
args.query,
|
|
2622
|
+
'--source',
|
|
2623
|
+
'web',
|
|
2624
|
+
'--engine',
|
|
2625
|
+
engine,
|
|
2626
|
+
...ownToolBudget(),
|
|
2627
|
+
];
|
|
2628
|
+
if (typeof args.max_results === 'number' && args.max_results > 0) {
|
|
2629
|
+
cliArgs.push('--max-results', String(Math.floor(args.max_results)));
|
|
2630
|
+
}
|
|
2631
|
+
const entry = await runCli(cliArgs, exec.signal);
|
|
2632
|
+
return {
|
|
2633
|
+
status: entry.status,
|
|
2634
|
+
source: entry.source,
|
|
2635
|
+
summary: entry.summary,
|
|
2636
|
+
items: Array.isArray(entry.items) ? entry.items : [],
|
|
2637
|
+
uncertainty: Array.isArray(entry.uncertainty) ? entry.uncertainty : [],
|
|
2638
|
+
};
|
|
2639
|
+
},
|
|
2640
|
+
};
|
|
2641
|
+
}
|
|
2642
|
+
/** 一个孤立的引擎工具向模型描述它自己的方式。 */
|
|
2643
|
+
function engineDescription(engine) {
|
|
2644
|
+
const base = `Search the web through the ${engine} engine alone, pinned to it with no fallback. Use it when you want exactly this engine's index rather than a fused answer. Returns structured evidence with a summary, per-item results, and an uncertainty list.`;
|
|
2645
|
+
// 浏览器那一半有它自己的免密钥清单;这一半没有理由仅仅为了加一句话就复制
|
|
2646
|
+
// 一份,而对一个有密钥的用户来说,那句话在哪种情况下都成立。
|
|
2647
|
+
return base;
|
|
2648
|
+
}
|
|
2649
|
+
function registerConfigRoute(ctx) {
|
|
2650
|
+
const route = {
|
|
2651
|
+
name: 'modsearch-config',
|
|
2652
|
+
kind: 'exact',
|
|
2653
|
+
path: '/searchfuse/config',
|
|
2654
|
+
handler: async (req, res) => {
|
|
2655
|
+
const send = (status, body) => {
|
|
2656
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
2657
|
+
res.end(JSON.stringify(body));
|
|
2658
|
+
};
|
|
2659
|
+
// 同源守卫。裸的 webServer 注册表不继承 dsh 的 Connection 鉴权,宿主侧
|
|
2660
|
+
// 也不施加任何 Host/Origin 策略,所以这条路由必须自己守:
|
|
2661
|
+
// - Host 必须指向本机回环,挡掉 DNS rebinding。
|
|
2662
|
+
// - Origin 若存在必须同源,挡掉跨站读取响应。
|
|
2663
|
+
// - POST 必须是 application/json:浏览器对非 JSON 的跨站 POST 可走
|
|
2664
|
+
// “简单请求”绕开 CORS 预检,强制 JSON 会让它在预检阶段就被拒。
|
|
2665
|
+
const sameOrigin = (value) => {
|
|
2666
|
+
if (typeof value !== 'string' || value === '')
|
|
2667
|
+
return true; // 非浏览器客户端没有 Origin
|
|
2668
|
+
try {
|
|
2669
|
+
const origin = new URL(value);
|
|
2670
|
+
return origin.hostname === '127.0.0.1'
|
|
2671
|
+
|| origin.hostname === 'localhost'
|
|
2672
|
+
|| origin.hostname === '[::1]';
|
|
2673
|
+
}
|
|
2674
|
+
catch {
|
|
2675
|
+
return false;
|
|
2676
|
+
}
|
|
2677
|
+
};
|
|
2678
|
+
const hostIsLoopback = (() => {
|
|
2679
|
+
const raw = req.headers?.host;
|
|
2680
|
+
if (typeof raw !== 'string' || raw === '')
|
|
2681
|
+
return true; // 无 Host 头:非浏览器直连
|
|
2682
|
+
const hostname = raw.startsWith('[') ? raw.slice(0, raw.indexOf(']') + 1) : raw.split(':')[0];
|
|
2683
|
+
return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]';
|
|
2684
|
+
})();
|
|
2685
|
+
if (!hostIsLoopback || !sameOrigin(req.headers?.origin)) {
|
|
2686
|
+
send(403, { error: 'request must come from the local host' });
|
|
2687
|
+
return;
|
|
2688
|
+
}
|
|
2689
|
+
if (req.method === 'GET') {
|
|
2690
|
+
try {
|
|
2691
|
+
const summary = (await engineSummary());
|
|
2692
|
+
if (new URL(req.url, 'http://localhost').searchParams.has('doctor')) {
|
|
2693
|
+
// 探测失败时为 null:卡片于是不显示就绪区,而不是凭空编出一份。
|
|
2694
|
+
summary.readiness = await engineReadiness();
|
|
2695
|
+
}
|
|
2696
|
+
send(200, summary);
|
|
2697
|
+
}
|
|
2698
|
+
catch (error) {
|
|
2699
|
+
send(409, { error: caughtMessage(error) });
|
|
2700
|
+
}
|
|
2701
|
+
return;
|
|
2702
|
+
}
|
|
2703
|
+
if (req.method !== 'POST') {
|
|
2704
|
+
res.writeHead(405).end();
|
|
2705
|
+
return;
|
|
2706
|
+
}
|
|
2707
|
+
// 必须是 application/json。跨站「简单请求」只能用
|
|
2708
|
+
// text/plain、application/x-www-form-urlencoded、multipart/form-data
|
|
2709
|
+
// 这三种 content-type,强制 JSON 就让它在 CORS 预检阶段被拒。
|
|
2710
|
+
const contentType = String(req.headers?.['content-type'] ?? '');
|
|
2711
|
+
if (!contentType.toLowerCase().includes('application/json')) {
|
|
2712
|
+
send(415, { error: 'content-type must be application/json' });
|
|
2713
|
+
return;
|
|
2714
|
+
}
|
|
2715
|
+
try {
|
|
2716
|
+
const chunks = [];
|
|
2717
|
+
let total = 0;
|
|
2718
|
+
for await (const chunk of req) {
|
|
2719
|
+
total += chunk.length;
|
|
2720
|
+
if (total > 64 * 1024) {
|
|
2721
|
+
send(413, { error: 'config payload too large' });
|
|
2722
|
+
req.destroy();
|
|
2723
|
+
return;
|
|
2724
|
+
}
|
|
2725
|
+
chunks.push(chunk);
|
|
2726
|
+
}
|
|
2727
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
2728
|
+
// 独立动作,不走 applyCardSettings:它会 spawn 子进程,而
|
|
2729
|
+
// applyCardSettings 的契约是「只写配置文件的那些段」。
|
|
2730
|
+
if (body?.action === 'ensureServe') {
|
|
2731
|
+
const outcome = await startServe();
|
|
2732
|
+
send(200, {
|
|
2733
|
+
ok: outcome.started || outcome.port !== undefined,
|
|
2734
|
+
...(outcome.port === undefined ? {} : { port: outcome.port }),
|
|
2735
|
+
...(outcome.reason === undefined ? {} : { message: outcome.reason }),
|
|
2736
|
+
});
|
|
2737
|
+
return;
|
|
2738
|
+
}
|
|
2739
|
+
applyCardSettings(body);
|
|
2740
|
+
// 缓存里的判定说的是这次保存刚刚重写之前的那个文件。继续用一分钟,
|
|
2741
|
+
// 会在设置它的密钥刚存进来之后,告诉卡片某个引擎仍未配置。
|
|
2742
|
+
readinessCache = null;
|
|
2743
|
+
send(200, await engineSummary());
|
|
2744
|
+
}
|
|
2745
|
+
catch (error) {
|
|
2746
|
+
send(400, { error: caughtMessage(error) });
|
|
2747
|
+
}
|
|
2748
|
+
},
|
|
2749
|
+
};
|
|
2750
|
+
ctx.effect(() => ctx.webServer.register(route), 'modsearch: settings route');
|
|
2751
|
+
}
|
|
2752
|
+
// 设置卡片的另一半,住在 socket 的这一侧,可以像 client.js 暴露 `__card` 那样
|
|
2753
|
+
// 从测试套件里够到。它读写真实的文件和真实的环境变量,所以它是针对这两者被
|
|
2754
|
+
// 测试的,而不是只通过 HTTP 路由测。
|
|
2755
|
+
export const __config = { engineSummary, applyCardSettings, modsearchConfigPath };
|
|
2756
|
+
function run(command, args, signal, env) {
|
|
2757
|
+
return new Promise((resolve, reject) => {
|
|
2758
|
+
const child = spawnHidden(command, args, {
|
|
2759
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
2760
|
+
signal,
|
|
2761
|
+
env,
|
|
2762
|
+
});
|
|
2763
|
+
let stdout = '';
|
|
2764
|
+
let stderr = '';
|
|
2765
|
+
child.stdout?.on('data', (chunk) => {
|
|
2766
|
+
stdout += chunk;
|
|
2767
|
+
});
|
|
2768
|
+
child.stderr?.on('data', (chunk) => {
|
|
2769
|
+
stderr += chunk;
|
|
2770
|
+
});
|
|
2771
|
+
child.on('error', reject);
|
|
2772
|
+
child.on('close', (code) => resolve({ stdout, stderr, code }));
|
|
2773
|
+
});
|
|
2774
|
+
}
|