@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.
@@ -0,0 +1 @@
1
+ export { t as discoverServe, n as ensureServeRunning, r as findRunningServe, i as readServeRuntimeFile } from "./serveEnsure-BTj9IifL.js";
@@ -0,0 +1,632 @@
1
+ import { C as loadConfigFile, _ as currentConfigPath, i as buildCooldownController, m as allowsPrivateNetwork, r as spawnHidden, t as runSearch } from "./search-DeT416xs.js";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import * as fs from "node:fs";
6
+ import * as http from "node:http";
7
+ import { fileURLToPath } from "node:url";
8
+ // src/serveIdentity.ts
9
+ /** 候选端口的起点。选这一段是为了避开常见服务端口,且远离临时端口区。 */
10
+ var PORT_BASE = 42e3;
11
+ /** 目录指纹的长度(十六进制字符)。8 位 = 32 位空间,碰撞概率可忽略。 */
12
+ var FINGERPRINT_CHARS = 8;
13
+ /**
14
+ * 算出一个状态目录的指纹。
15
+ *
16
+ * 用 `realpathSync` 而不是 `path.resolve`:Windows 上 `C:\Users\Administrator`
17
+ * 与 `C:\Users\ADMINI~1`(8.3 短名)是**同一个目录**,junction 与它指向的
18
+ * 目标也是同一个。用 resolve 会给出两组不同的指纹,于是同一份状态被认成
19
+ * 两个身份——服务绑在一组候选上、客户端去探另一组,症状与「服务没起来」
20
+ * 一模一样。
21
+ *
22
+ * 目录还没建出来时 realpath 会抛 ENOENT:那时退回 resolve,因为那种情况下
23
+ * 没有「另一个写法」可言。大小写仍要统一(`C:\Users` 与 `c:\users` 在
24
+ * Windows 上相等)。
25
+ */
26
+ function fingerprintOf(stateDir) {
27
+ const resolved = realpathOrSelf(stateDir);
28
+ return createHash("sha256").update(resolved.toLowerCase()).digest("hex").slice(0, FINGERPRINT_CHARS);
29
+ }
30
+ /** realpath 拿不到(目录不存在、权限不足)时退回 resolve。 */
31
+ function realpathOrSelf(stateDir) {
32
+ try {
33
+ return fs.realpathSync(stateDir);
34
+ } catch {
35
+ return path.resolve(stateDir);
36
+ }
37
+ }
38
+ /**
39
+ * 从指纹推出一组候选端口,按优先级从高到低。
40
+ *
41
+ * 确定性:同一个指纹永远给出同一组。跨进程、跨宿主、跨重启都一样。
42
+ *
43
+ * 端口范围由算式自身保证:`42000 + (seed % 2000)` 最大 43999,加 7 得
44
+ * 44006,远低于 65535。所以这里不需要越界过滤——早先有一个 `<= 65535`
45
+ * 的守卫,它永远不触发,却让函数**可能返回少于 PORT_SPAN 个元素**,与
46
+ * 「候选恒为 8 个」的契约和测试断言互相矛盾。
47
+ */
48
+ function candidatePorts(fingerprint) {
49
+ const base = PORT_BASE + Number.parseInt(fingerprint, 16) % 2e3;
50
+ const ports = [];
51
+ for (let i = 0; i < 8; i += 1) ports.push(base + i);
52
+ return ports;
53
+ }
54
+ /** 状态目录:与其他模块的 `.searchfuse` 保持同一份约定。 */
55
+ function stateDirOf(home) {
56
+ return path.join(home, ".searchfuse");
57
+ }
58
+ /** 从一个 home 目录推出服务身份。 */
59
+ function identityOf(home) {
60
+ const fingerprint = fingerprintOf(stateDirOf(home));
61
+ return {
62
+ fingerprint,
63
+ ports: candidatePorts(fingerprint)
64
+ };
65
+ }
66
+ // src/serve.ts
67
+ /** token 文件位置。与配置分离:配置会被复制备份,秘密不该跟着走。 */
68
+ function serveTokenPath() {
69
+ return path.join(os.homedir(), ".searchfuse", "serve-token");
70
+ }
71
+ /** 运行时文件:谁在跑、端口、指纹、token。客户端优先读它;它不在时按候选探测。 */
72
+ function runtimePath() {
73
+ return path.join(os.homedir(), ".searchfuse", "runtime.json");
74
+ }
75
+ /** 读 token;没有就生成一个并写盘(POSIX 上用 0600)。 */
76
+ function ensureServeToken() {
77
+ const file = serveTokenPath();
78
+ try {
79
+ const existing = fs.readFileSync(file, "utf-8").trim();
80
+ if (existing !== "") return existing;
81
+ } catch {}
82
+ const token = randomToken();
83
+ fs.mkdirSync(path.dirname(file), {
84
+ recursive: true,
85
+ mode: 448
86
+ });
87
+ fs.writeFileSync(file, `${token}\n`, { mode: 384 });
88
+ try {
89
+ fs.chmodSync(file, 384);
90
+ } catch {}
91
+ return token;
92
+ }
93
+ /** 32 字节随机 token 的十六进制形式。 */
94
+ function randomToken() {
95
+ const bytes = /* @__PURE__ */ new Uint8Array(32);
96
+ crypto.getRandomValues(bytes);
97
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
98
+ }
99
+ /**
100
+ * 把一次聚合结果翻译成 SearXNG 的形状。
101
+ *
102
+ * 三条规则:
103
+ * - `title` / `url` / `content` 直对,缺 `url` 的条目丢弃(omp 需要它)
104
+ * - `engine` 填作答的引擎名,不是 `searxng`——它本来就是别的东西
105
+ * - **`unresponsive_engines` 必须带上**:omp 靠它在结果为空时保真上游原因,
106
+ * 缺了它只会退化成一句泛化错误
107
+ */
108
+ function toSearxngShape(raw, query) {
109
+ const root = typeof raw === "object" && raw !== null ? raw : {};
110
+ const results = Array.isArray(root.results) ? root.results : [];
111
+ const entry = typeof results[0] === "object" && results[0] !== null ? results[0] : {};
112
+ const items = Array.isArray(entry.items) ? entry.items : [];
113
+ const mapped = [];
114
+ for (const item of items) {
115
+ if (typeof item !== "object" || item === null) continue;
116
+ const record = item;
117
+ const url = typeof record.url === "string" ? record.url : void 0;
118
+ if (!url) continue;
119
+ const title = typeof record.title === "string" ? record.title : url;
120
+ const content = typeof record.snippet === "string" ? record.snippet : typeof record.summary === "string" ? record.summary : "";
121
+ mapped.push({
122
+ title,
123
+ url,
124
+ content,
125
+ engine: typeof entry.engine === "string" ? entry.engine : "searchfuse"
126
+ });
127
+ }
128
+ const failures = [];
129
+ const attempts = Array.isArray(entry.attempts) ? entry.attempts : [];
130
+ for (const attempt of attempts) {
131
+ if (typeof attempt !== "object" || attempt === null) continue;
132
+ const record = attempt;
133
+ if (typeof record.error !== "string") continue;
134
+ failures.push([typeof record.engine === "string" ? record.engine : "unknown", record.error]);
135
+ }
136
+ if (failures.length === 0) {
137
+ const uncertainty = Array.isArray(entry.uncertainty) ? entry.uncertainty : [];
138
+ for (const line of uncertainty) {
139
+ if (typeof line !== "string" || line === "") continue;
140
+ const colon = line.indexOf(":");
141
+ if (colon > 0 && colon < 40) failures.push([line.slice(0, colon).trim(), line.slice(colon + 1).trim()]);
142
+ else failures.push(["searchfuse", line]);
143
+ }
144
+ }
145
+ const answer = typeof entry.summary === "string" && entry.summary !== "" ? [entry.summary] : [];
146
+ return {
147
+ query,
148
+ number_of_results: mapped.length,
149
+ results: mapped,
150
+ answers: answer,
151
+ unresponsive_engines: failures
152
+ };
153
+ }
154
+ /** `config.engines` 里启用中的引擎名,供 `/config` 的壳使用。 */
155
+ function enabledEngines() {
156
+ const engines = loadConfigFile(currentConfigPath()).engines ?? {};
157
+ return Object.entries(engines).filter(([, settings]) => settings.enabled !== false).map(([name]) => ({ name }));
158
+ }
159
+ /** 常量的响应头。`no-store`:这是搜索,不该被任何中间层缓存。 */
160
+ var JSON_HEADERS = {
161
+ "content-type": "application/json; charset=utf-8",
162
+ "cache-control": "no-store"
163
+ };
164
+ /** 从请求里取 bearer token,大小写不敏感。 */
165
+ function bearerOf(header) {
166
+ if (header === void 0) return void 0;
167
+ return /^Bearer\s+(.+)$/i.exec(header.trim())?.[1];
168
+ }
169
+ /**
170
+ /**
171
+ * 起服务。按候选端口顺序找第一个能绑的,全部被占才报错。
172
+ *
173
+ * 为什么是确定性候选而不是让内核随机分配:端口随机时 runtime.json 会成为
174
+ * 唯一线索,而它会在服务被 kill 时消失(close 跑不到)。候选来自目录指纹,
175
+ * 同一份 `.searchfuse` 永远得到同一组,客户端不必依赖文件也能找到服务。
176
+ *
177
+ * 为什么不漂移到任意空闲端口:8 个候选都被占说明同机上真有 8 个实例,
178
+ * 那时报错比再挑一个用户不知道的端口更有用——后者会让诊断无处下手。
179
+ */
180
+ function startServe(options) {
181
+ const search = options.search ?? runSearch;
182
+ const fingerprint = options.fingerprint ?? identityOf(os.homedir()).fingerprint;
183
+ const version = "0.1.2";
184
+ let hits = 0;
185
+ let inFlight = 0;
186
+ let idleTimer;
187
+ /** 实际绑定的端口。listen 回调里才有值,`/healthz` 要把它报出去。 */
188
+ let boundPortForHealth = options.port;
189
+ const server = http.createServer((req, res) => {
190
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${options.port}`);
191
+ if (url.pathname === "/healthz") {
192
+ res.writeHead(200, {
193
+ "content-type": "text/plain; charset=utf-8",
194
+ "cache-control": "no-store"
195
+ });
196
+ res.end("OK");
197
+ return;
198
+ }
199
+ if (url.pathname === "/identity") {
200
+ res.writeHead(200, {
201
+ "content-type": "application/json; charset=utf-8",
202
+ "cache-control": "no-store"
203
+ });
204
+ res.end(JSON.stringify({
205
+ port: boundPortForHealth,
206
+ pid: process.pid,
207
+ fingerprint,
208
+ version
209
+ }));
210
+ return;
211
+ }
212
+ if (bearerOf(req.headers.authorization) !== options.token) {
213
+ res.writeHead(401, JSON_HEADERS);
214
+ res.end(JSON.stringify({ error: "unauthorized" }));
215
+ return;
216
+ }
217
+ if (url.pathname === "/__stats") {
218
+ res.writeHead(200, JSON_HEADERS);
219
+ res.end(JSON.stringify({ localHits: hits }));
220
+ return;
221
+ }
222
+ if (url.pathname === "/config") {
223
+ res.writeHead(200, JSON_HEADERS);
224
+ res.end(JSON.stringify({ engines: enabledEngines() }));
225
+ return;
226
+ }
227
+ if (url.pathname === "/v1/search" || url.pathname === "/v1/read-page") {
228
+ inFlight += 1;
229
+ scheduleIdleExit();
230
+ const config = loadConfigFile(currentConfigPath());
231
+ const isReadPage = url.pathname === "/v1/read-page";
232
+ const query = url.searchParams.get("q") ?? "";
233
+ const targetUrl = url.searchParams.get("url") ?? "";
234
+ if (isReadPage && targetUrl === "") {
235
+ inFlight -= 1;
236
+ res.writeHead(400, JSON_HEADERS);
237
+ res.end(JSON.stringify({ error: "missing url" }));
238
+ return;
239
+ }
240
+ if (!isReadPage && query === "") {
241
+ inFlight -= 1;
242
+ res.writeHead(400, JSON_HEADERS);
243
+ res.end(JSON.stringify({ error: "missing q" }));
244
+ return;
245
+ }
246
+ const options = isReadPage ? {
247
+ url: targetUrl,
248
+ allowPrivateNetwork: allowsPrivateNetwork(config),
249
+ config,
250
+ cooldown: buildCooldownController(config)
251
+ } : {
252
+ query,
253
+ sources: url.searchParams.get("source") ?? "web",
254
+ maxResults: Number(url.searchParams.get("max") ?? "") || void 0,
255
+ timeoutMs: Number(url.searchParams.get("timeout") ?? "") || void 0,
256
+ deadlineMs: Number(url.searchParams.get("deadline") ?? "") || void 0,
257
+ allowPrivateNetwork: allowsPrivateNetwork(config),
258
+ config,
259
+ cooldown: buildCooldownController(config)
260
+ };
261
+ search(options).then((result) => {
262
+ if (result.results.some((entry) => entry.status !== "unavailable")) hits += 1;
263
+ res.writeHead(200, JSON_HEADERS);
264
+ res.end(JSON.stringify(result));
265
+ }).catch((error) => {
266
+ const message = error instanceof Error ? error.message : String(error);
267
+ res.writeHead(500, JSON_HEADERS);
268
+ res.end(JSON.stringify({ error: message }));
269
+ }).finally(() => {
270
+ inFlight -= 1;
271
+ scheduleIdleExit();
272
+ });
273
+ return;
274
+ }
275
+ if (url.pathname === "/search") {
276
+ const query = url.searchParams.get("q") ?? "";
277
+ inFlight += 1;
278
+ scheduleIdleExit();
279
+ const config = loadConfigFile(currentConfigPath());
280
+ search({
281
+ query,
282
+ sources: "web",
283
+ allowPrivateNetwork: allowsPrivateNetwork(config),
284
+ config,
285
+ cooldown: buildCooldownController(config)
286
+ }).then((result) => {
287
+ const payload = toSearxngShape(result, query);
288
+ if (payload.results.length > 0) hits += 1;
289
+ res.writeHead(200, JSON_HEADERS);
290
+ res.end(JSON.stringify(payload));
291
+ }).catch((error) => {
292
+ const message = error instanceof Error ? error.message : String(error);
293
+ res.writeHead(500, JSON_HEADERS);
294
+ res.end(JSON.stringify({
295
+ error: message,
296
+ results: [],
297
+ answers: [],
298
+ unresponsive_engines: []
299
+ }));
300
+ }).finally(() => {
301
+ inFlight -= 1;
302
+ scheduleIdleExit();
303
+ });
304
+ return;
305
+ }
306
+ res.writeHead(404, JSON_HEADERS);
307
+ res.end(JSON.stringify({ error: "not found" }));
308
+ });
309
+ /** 空闲退出:**只统计空闲**,在途请求期间绝不退出。 */
310
+ function scheduleIdleExit() {
311
+ if (options.idleExitSeconds <= 0) return;
312
+ clearTimeout(idleTimer);
313
+ if (inFlight > 0) return;
314
+ idleTimer = setTimeout(() => {
315
+ if (inFlight > 0) return;
316
+ close();
317
+ }, options.idleExitSeconds * 1e3 + 2e3);
318
+ idleTimer.unref();
319
+ }
320
+ async function close() {
321
+ clearTimeout(idleTimer);
322
+ try {
323
+ const raw = fs.readFileSync(runtimePath(), "utf-8");
324
+ const parsed = JSON.parse(raw);
325
+ if (typeof parsed.pid === "number" && parsed.pid === process.pid) fs.rmSync(runtimePath(), { force: true });
326
+ } catch {}
327
+ const closed = Promise.withResolvers();
328
+ server.close(() => closed.resolve());
329
+ await closed.promise;
330
+ }
331
+ const ready = Promise.withResolvers();
332
+ /**
333
+ * 依次尝试候选端口的监听器。
334
+ *
335
+ * 候选来自目录指纹,同一份 `.searchfuse` 永远得到同一组,所以「谁先来谁
336
+ * 占住前面的」。全部被占才报错——那时说明同机上真有 8 个实例,比让内核
337
+ * 随机分配一个用户不知道的端口要好:后两者会让 runtime.json 成为唯一线索。
338
+ */
339
+ const portQueue = options.candidatePorts !== void 0 && options.candidatePorts.length > 0 ? [...options.candidatePorts] : [options.port];
340
+ /** 已经尝试过的端口,用来在报错时把「试过哪些」完整说出来。 */
341
+ const triedPorts = [];
342
+ const tryListenNext = () => {
343
+ const port = portQueue.shift();
344
+ if (port === void 0) {
345
+ ready.reject(/* @__PURE__ */ new Error(`No candidate port was usable (tried ${triedPorts.join(", ")}). Stop another searchfuse instance, or set serve.port to a free number.`));
346
+ return;
347
+ }
348
+ triedPorts.push(port);
349
+ server.listen(port, "127.0.0.1");
350
+ };
351
+ server.on("error", (error) => {
352
+ const portLevel = error.code === "EADDRINUSE" || error.code === "EACCES";
353
+ if (portLevel && portQueue.length > 0) {
354
+ tryListenNext();
355
+ return;
356
+ }
357
+ if (portLevel) {
358
+ ready.reject(/* @__PURE__ */ new Error(`Port ${options.port} could not be bound (${error.code}). Leave serve.port at 0 so searchfuse can pick a deterministic candidate derived from your ~/.searchfuse directory.`));
359
+ return;
360
+ }
361
+ ready.reject(error);
362
+ });
363
+ server.once("listening", () => {
364
+ const address = server.address();
365
+ const boundPort = typeof address === "object" && address !== null ? address.port : options.port;
366
+ boundPortForHealth = boundPort;
367
+ try {
368
+ fs.mkdirSync(path.dirname(runtimePath()), {
369
+ recursive: true,
370
+ mode: 448
371
+ });
372
+ fs.writeFileSync(runtimePath(), `${JSON.stringify({
373
+ port: boundPort,
374
+ pid: process.pid,
375
+ fingerprint,
376
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
377
+ version,
378
+ token: options.token
379
+ }, null, 2)}\n`);
380
+ } catch {}
381
+ scheduleIdleExit();
382
+ ready.resolve({
383
+ server,
384
+ port: boundPort,
385
+ localHits: () => hits,
386
+ close
387
+ });
388
+ });
389
+ tryListenNext();
390
+ return ready.promise;
391
+ }
392
+ // src/serveEnsure.ts
393
+ var DEFAULT_TIMEOUT_MS = 2e4;
394
+ /** 探 /healthz 的上限。服务是本机回环,超过就算不通。 */
395
+ var HEALTH_TIMEOUT_MS = 2e3;
396
+ /** spawn 之后轮询就绪状态的间隔。 */
397
+ var POLL_INTERVAL_MS = 500;
398
+ /** 睡一会儿。轮询用,为这点事引入依赖不值得。 */
399
+ function sleep(ms) {
400
+ return new Promise((resolve) => setTimeout(resolve, ms));
401
+ }
402
+ /** 把 spawn 失败整理成一行可读的原因。 */
403
+ function describeSpawnFailure(error) {
404
+ return `serve --ensure failed to start: ${error instanceof Error ? error.message : String(error)}`;
405
+ }
406
+ /**
407
+ * 读 `~/.searchfuse/runtime.json`。
408
+ *
409
+ * 文件可能被 `serve --ensure` 写入、被 `serve` 的 close() 删除,也可能
410
+ * 上一次进程被杀后残留成「指向死端口」。所以形状检查必须严格:
411
+ * 端口不是数字就直接当没有,宁可多拉起一次,也不要拿一个坏端口去连。
412
+ */
413
+ function readServeRuntimeFile(file = runtimePath()) {
414
+ try {
415
+ const raw = fs.readFileSync(file, "utf-8");
416
+ const parsed = JSON.parse(raw);
417
+ if (typeof parsed.port !== "number" || !Number.isInteger(parsed.port)) return void 0;
418
+ if (typeof parsed.token !== "string" || parsed.token === "") return void 0;
419
+ return {
420
+ port: parsed.port,
421
+ token: parsed.token
422
+ };
423
+ } catch {
424
+ return;
425
+ }
426
+ }
427
+ /**
428
+ * 探一次 /healthz。返回是否 200。
429
+ */
430
+ function healthOnce(port) {
431
+ return new Promise((resolve) => {
432
+ const req = http.request({
433
+ host: "127.0.0.1",
434
+ port,
435
+ path: "/healthz",
436
+ method: "GET",
437
+ timeout: HEALTH_TIMEOUT_MS,
438
+ headers: { Connection: "close" }
439
+ }, (res) => {
440
+ res.resume();
441
+ resolve(res.statusCode === 200);
442
+ });
443
+ req.on("error", () => resolve(false));
444
+ req.on("timeout", () => {
445
+ req.destroy();
446
+ resolve(false);
447
+ });
448
+ req.end();
449
+ });
450
+ }
451
+ /**
452
+ * 读一次 `/identity`,拿到那个服务自称的指纹。
453
+ *
454
+ * 为什么不复用 `/healthz`:四个现存消费者都只看 `/healthz` 的状态码,
455
+ * 把它的 body 换成 JSON 是无谓的破坏。身份校验放在独立端点上。
456
+ */
457
+ function identityOnce(port) {
458
+ return new Promise((resolve) => {
459
+ const req = http.request({
460
+ host: "127.0.0.1",
461
+ port,
462
+ path: "/identity",
463
+ method: "GET",
464
+ timeout: HEALTH_TIMEOUT_MS,
465
+ headers: { Connection: "close" }
466
+ }, (res) => {
467
+ if (res.statusCode !== 200) {
468
+ res.resume();
469
+ resolve(void 0);
470
+ return;
471
+ }
472
+ let body = "";
473
+ res.on("data", (chunk) => {
474
+ body += chunk;
475
+ });
476
+ res.on("end", () => {
477
+ try {
478
+ const parsed = JSON.parse(body);
479
+ resolve(typeof parsed.fingerprint === "string" ? parsed.fingerprint : void 0);
480
+ } catch {
481
+ resolve(void 0);
482
+ }
483
+ });
484
+ });
485
+ req.on("error", () => resolve(void 0));
486
+ req.on("timeout", () => {
487
+ req.destroy();
488
+ resolve(void 0);
489
+ });
490
+ req.end();
491
+ });
492
+ }
493
+ /**
494
+ * 按目录推导出的候选端口逐个探测,找出真正属于这份 `.searchfuse` 的服务。
495
+ *
496
+ * 这是「runtime.json 不再是唯一凭证」的落地:文件消失(服务被 kill 时来不及
497
+ * 清理)、或指向了一个死端口,都能靠这条路径找回真正的服务。
498
+ *
499
+ * **必须校验指纹**。只看 `/healthz` 200 会把「恰好占着候选端口的别的程序」
500
+ * 认成自己的服务,然后把搜索请求连同 token 发给它。
501
+ *
502
+ * 返回的 token 可能缺失(`serve-token` 文件还没写或读不了):那种情况下
503
+ * 端口仍然是对的,调用方可以只用端口做唤醒/健康检查;要发鉴权请求时再读一次。
504
+ */
505
+ async function discoverServe(fingerprint, ports) {
506
+ for (const port of ports) {
507
+ if (await identityOnce(port) !== fingerprint) continue;
508
+ const runtime = readServeRuntimeFile();
509
+ if (runtime !== void 0 && runtime.port === port) return runtime;
510
+ return {
511
+ port,
512
+ token: readServeTokenFile()
513
+ };
514
+ }
515
+ }
516
+ /** 读 token 文件。服务端与客户端共用同一份,所以这里只需读。 */
517
+ function readServeTokenFile(file = serveTokenPath()) {
518
+ try {
519
+ const token = fs.readFileSync(file, "utf-8").trim();
520
+ return token === "" ? void 0 : token;
521
+ } catch {
522
+ return;
523
+ }
524
+ }
525
+ /**
526
+ * 判断服务是否已经在跑,返回它的端口。
527
+ *
528
+ * `serve --ensure` 与插件侧共用这一个判据。顺序是:
529
+ *
530
+ * 1. `runtime.json` 里记的端口健康就直接认。
531
+ * 2. 否则按目录指纹推导的候选端口逐个探 `/identity`,指纹匹配的才算。
532
+ *
533
+ * **第 2 步是「同目录 = 同服务」在服务生命周期侧成立的关键。** 早先 CLI 的
534
+ * `--ensure` 只信文件:文件一消失(服务被 kill 时 close 跑不到)就判「没在
535
+ * 跑」,于是在下一个候选端口上起第二个实例。实测复现过 A 活 42800、删文件、
536
+ * B 起在 42801、两个都在听——此后客户端按候选探到 A、dsh 按文件连 B,同一台
537
+ * 机器两个聚合器轮流接管搜索。
538
+ *
539
+ * 判据必须是指纹匹配而不是只看 `/healthz` 200:否则恰好占着候选端口的别的
540
+ * 程序会被当成「已有服务」,于是拒绝启动——那比多起一个更糟。
541
+ */
542
+ async function findRunningServe(file = runtimePath()) {
543
+ const fromFile = readServeRuntimeFile(file);
544
+ if (fromFile !== void 0 && await healthOnce(fromFile.port)) return fromFile.port;
545
+ const identity = identityOf(os.homedir());
546
+ const discovered = await discoverServe(identity.fingerprint, identity.ports);
547
+ if (discovered === void 0) return void 0;
548
+ return await healthOnce(discovered.port) ? discovered.port : void 0;
549
+ }
550
+ /**
551
+ * 确保本地服务在跑。已在跑就什么都不做。
552
+ *
553
+ * 顺序是「先探文件、再探 /healthz、最后才 spawn」:文件在但服务已死是最阴的
554
+ * 状态(服务不能用、文件却指向它),直接 spawn 会撞上仍被占用的端口。
555
+ *
556
+ * 拉起复用 `serve --ensure` 而不是自己起服务:它已经处理了「端口 0 由内核
557
+ * 分配」「已在跑就 exit 0」两个边界。在插件里重写一遍必然漂移。
558
+ *
559
+ * 就绪的判据是 `/healthz` 通过,不是子进程退出码。`serve --ensure` 只在
560
+ * 「已经在跑」时以 0 退出;真正需要起服务时它会把服务拉起来并**常驻**,
561
+ * 永远等不到 close 事件。等退出码会一路等到超时,然后用 child.kill() 杀掉
562
+ * 刚刚起来的那个服务——这正是本设计要避免的事。所以 spawn 之后就把子进程
563
+ * 交出去(detached + unref),改为轮询健康检查。
564
+ */
565
+ async function ensureServeRunning(options = {}) {
566
+ const file = runtimePath();
567
+ const existing = readServeRuntimeFile(file);
568
+ if (existing !== void 0 && await healthOnce(existing.port)) return {
569
+ started: false,
570
+ port: existing.port
571
+ };
572
+ const identity = identityOf(os.homedir());
573
+ const discovered = await discoverServe(identity.fingerprint, identity.ports);
574
+ if (discovered !== void 0 && await healthOnce(discovered.port)) return {
575
+ started: false,
576
+ port: discovered.port
577
+ };
578
+ const cliPath = options.cliPath ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist", "main.js");
579
+ const nodeBinary = options.nodeBinary ?? "node";
580
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
581
+ let spawnError;
582
+ let exitedEarly;
583
+ try {
584
+ const child = spawnHidden(nodeBinary, [
585
+ cliPath,
586
+ "serve",
587
+ "--ensure"
588
+ ], {
589
+ stdio: "ignore",
590
+ detached: true
591
+ });
592
+ child.unref();
593
+ child.on("error", (error) => {
594
+ spawnError = error;
595
+ });
596
+ child.on("close", (code) => {
597
+ exitedEarly = code === null ? void 0 : code;
598
+ });
599
+ } catch (error) {
600
+ return {
601
+ started: false,
602
+ reason: describeSpawnFailure(error)
603
+ };
604
+ }
605
+ const deadline = Date.now() + timeoutMs;
606
+ for (;;) {
607
+ if (spawnError !== void 0) return {
608
+ started: false,
609
+ reason: describeSpawnFailure(spawnError)
610
+ };
611
+ if (exitedEarly !== void 0 && exitedEarly !== 0) return {
612
+ started: false,
613
+ reason: `serve --ensure exited ${exitedEarly}`
614
+ };
615
+ const runtime = readServeRuntimeFile(file);
616
+ if (runtime !== void 0) {
617
+ if (await healthOnce(runtime.port)) return {
618
+ started: true,
619
+ port: runtime.port
620
+ };
621
+ } else if (exitedEarly === 0) return {
622
+ started: false,
623
+ reason: "runtime.json not written"
624
+ };
625
+ if (Date.now() >= deadline) return {
626
+ started: false,
627
+ reason: `serve did not become healthy within ${timeoutMs} ms`
628
+ };
629
+ await sleep(POLL_INTERVAL_MS);
630
+ }
631
+ }
632
+ export { ensureServeToken as a, identityOf as c, readServeRuntimeFile as i, ensureServeRunning as n, runtimePath as o, findRunningServe as r, startServe as s, discoverServe as t };