@wenaixi/searchfuse 0.1.0 → 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.
Files changed (38) hide show
  1. package/CHANGELOG.md +157 -1
  2. package/README.md +2 -10
  3. package/README.zh-CN.md +2 -10
  4. package/SECURITY.md +36 -2
  5. package/claude/.claude-plugin/plugin.json +1 -1
  6. package/claude/hooks/register.ts +90 -18
  7. package/dist/kernel.js +17 -6
  8. package/dist/main.js +64 -21
  9. package/dist/{search-BIW13Csk.js → search-DeT416xs.js} +123 -11
  10. package/dist/serve-ensure.js +1 -140
  11. package/dist/serveEnsure-BTj9IifL.js +632 -0
  12. package/dsh/index.js +137 -3
  13. package/omp/extension.ts +263 -29
  14. package/omp/host-types.d.ts +47 -0
  15. package/omp/tsconfig.json +13 -0
  16. package/package.json +3 -7
  17. package/skills/searchfuse/SKILL.md +4 -4
  18. package/skills/searchfuse/references/configure.md +4 -2
  19. package/skills/searchfuse/references/runtime.md +1 -1
  20. package/skills/searchfuse/scripts/run.ps1 +1 -1
  21. package/skills/searchfuse/scripts/run.sh +1 -1
  22. package/dist/serve-Bfqz-nCB.js +0 -279
  23. package/docs/commit.md +0 -77
  24. package/docs/dsh.md +0 -205
  25. package/docs/harness-setup.md +0 -78
  26. package/docs/parity-matrix.md +0 -61
  27. package/docs/searxng-setup.md +0 -117
  28. package/docs/security.md +0 -59
  29. package/docs/settings-redesign-decisions.md +0 -407
  30. package/docs/superpowers/plans/2026-11-24-serve-lifecycle.md +0 -880
  31. package/docs/superpowers/reports/2026-11-24-serve-lifecycle-ledger.md +0 -211
  32. package/docs/superpowers/specs/2026-11-20-searchfuse-dual-host-design.md +0 -172
  33. package/docs/superpowers/specs/2026-11-21-searchfuse-tri-host-design.md +0 -659
  34. package/docs/superpowers/specs/2026-11-21-tri-host-takeover-design.md +0 -363
  35. package/docs/superpowers/specs/2026-11-22-settings-card-refactor-design.md +0 -117
  36. package/docs/superpowers/specs/2026-11-24-serve-lifecycle-design.md +0 -155
  37. package/docs/testing.md +0 -92
  38. package/docs/troubleshooting.md +0 -258
package/dist/main.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { A as findEngine, C as loadConfigFile, D as ROLE_PREFERENCE, E as setConfigValue, F as commandOnPath, M as registerSearxngCleanup, N as grokAuthFile, O as allEngines, P as splitApiKeys, S as isPlainObject, T as renderEffectiveConfig, _ as currentConfigPath, a as clearAllCooldowns, b as exposeOf, c as loadCooldownState, d as ROLES, f as aggregateDeadlineMs, g as cooldownEnabled, h as chosenEngine, i as buildCooldownController, j as listEngines, k as enginesForRole, l as parseCooldownStateKey, m as allowsPrivateNetwork, n as waitForPendingKills, o as coolingEntry, p as aggregateMode, s as currentStatePath, t as runSearch, u as CONFIG_PATH, v as effectiveMcp, w as migrateLegacyDir, x as initConfigFile, y as engineSettings } from "./search-BIW13Csk.js";
2
+ import { A as findEngine, C as loadConfigFile, D as ROLE_PREFERENCE, E as setConfigValue, F as commandOnPath, M as registerSearxngCleanup, N as grokAuthFile, O as allEngines, P as splitApiKeys, S as isPlainObject, T as renderEffectiveConfig, _ as currentConfigPath, a as clearAllCooldowns, b as exposeOf, c as loadCooldownState, d as ROLES, f as aggregateDeadlineMs, g as cooldownEnabled, h as chosenEngine, i as buildCooldownController, j as listEngines, k as enginesForRole, l as parseCooldownStateKey, m as allowsPrivateNetwork, n as waitForPendingKills, o as coolingEntry, p as aggregateMode, s as currentStatePath, t as runSearch, u as CONFIG_PATH, v as effectiveMcp, w as migrateLegacyDir, x as initConfigFile, y as engineSettings } from "./search-DeT416xs.js";
3
3
  import { r as isServerNameValid, t as McpConnection } from "./protocol-ClnjMnGV.js";
4
- import { n as runtimePath, r as startServe, t as ensureServeToken } from "./serve-Bfqz-nCB.js";
4
+ import { a as ensureServeToken, c as identityOf, o as runtimePath, r as findRunningServe, s as startServe, t as discoverServe } from "./serveEnsure-BTj9IifL.js";
5
5
  import { Command } from "commander";
6
6
  import * as fs$1 from "fs";
7
7
  import * as os from "os";
@@ -585,15 +585,20 @@ function syncClaudeSettings(enabled, paths, file = claudeSettingsPath()) {
585
585
  const hosts = raw.searchfuseHosts;
586
586
  const existing = typeof hosts === "object" && hosts !== null && !Array.isArray(hosts) ? hosts : {};
587
587
  const claude = typeof existing.claudeCode === "object" && existing.claudeCode !== null ? existing.claudeCode : {};
588
- if (claude.enabled === enabled) return { changed: false };
588
+ const nextClaude = {
589
+ ...claude,
590
+ enabled,
591
+ runtimePath: paths.runtimePath,
592
+ kernelPath: paths.kernelPath,
593
+ ...paths.identity === void 0 ? {} : {
594
+ fingerprint: paths.identity.fingerprint,
595
+ ports: paths.identity.ports
596
+ }
597
+ };
598
+ if (claude.enabled === nextClaude.enabled && claude.runtimePath === nextClaude.runtimePath && claude.kernelPath === nextClaude.kernelPath && JSON.stringify(claude.fingerprint) === JSON.stringify(nextClaude.fingerprint) && JSON.stringify(claude.ports) === JSON.stringify(nextClaude.ports)) return { changed: false };
589
599
  raw.searchfuseHosts = {
590
600
  ...existing,
591
- claudeCode: {
592
- ...claude,
593
- enabled,
594
- runtimePath: paths.runtimePath,
595
- kernelPath: paths.kernelPath
596
- }
601
+ claudeCode: nextClaude
597
602
  };
598
603
  const next = `${JSON.stringify(raw, null, 2)}\n`;
599
604
  const decision = decideWrite(file, next);
@@ -983,6 +988,18 @@ if (process.env.MODSEARCH_NESTED) {
983
988
  }
984
989
  /** 一次已结束的运行,在真正收尾前最多等多久让被遗弃的工作收场。 */
985
990
  var EXIT_BACKSTOP_MS = 2e3;
991
+ /**
992
+ * 退出兜底计时器挂在 globalThis 上的键。
993
+ *
994
+ * 为什么不用普通模块变量:`main.ts` 一被 import 就会立即解析 argv(commander
995
+ * 的 `program.parse()` 在模块顶层),测试没法在配置好 argv 之前 import 它,
996
+ * 也就拿不到模块作用域里的句柄。挂在 globalThis 的符号上,测试用同一个
997
+ * `Symbol.for(...)` 直接取,不必 import 这个模块。
998
+ *
999
+ * 计时器本身 `.unref()` 过,不阻止进程退出;但它会在测试结束后才触发
1000
+ * `process.exit`,那时 spy 已恢复,Vitest 报「unexpected process.exit」。
1001
+ */
1002
+ var EXIT_BACKSTOP_KEY = Symbol.for("searchfuse.exitBackstop");
986
1003
  /** 写入并等到流确实收下,这样退出时不会把它截断。 */
987
1004
  function writeFully(stream, text) {
988
1005
  return new Promise((resolve, reject) => {
@@ -990,7 +1007,7 @@ function writeFully(stream, text) {
990
1007
  });
991
1008
  }
992
1009
  var program = new Command();
993
- program.name("searchfuse").description("Plug-in web search and page fetch for models without native web access: query or URL in, structured JSON evidence out").version("0.1.0");
1010
+ program.name("searchfuse").description("Plug-in web search and page fetch for models without native web access: query or URL in, structured JSON evidence out").version("0.1.2");
994
1011
  program.command("search", { isDefault: true }).description("Search the web or X, or fetch a page (default command)").option("-q, --query <text>", "Search query (or answer focus when combined with -u)").option("-u, --url <url>", "Fetch this web page instead of searching").option("-o, --output <path>", "Write result JSON to a file").option("-s, --source <list>", "Where to search: web, x, or web,x (default: web, or x when the query is about X)").option("-e, --engine <name>", `Engine for this run, overriding config (${listEngines().join(", ")})`).option("-m, --model <name>", "Engine model, where the engine has one").option("--prompt <text>", "Extra constraints for this run").option("--max-results <n>", "Maximum number of search results", "8").option("--timeout <ms>", "Engine timeout in milliseconds", "180000").option("--deadline <ms>", "Wall-clock budget for the whole run in milliseconds, across every engine tried (default: none)").option("--workdir <path>", "Working directory for engines that run a command").option("--allow-private-network", "Allow reserved address ranges for this run, for VPNs that map public hosts into them").action(async (options) => {
995
1012
  let exitCode = 0;
996
1013
  try {
@@ -1033,7 +1050,12 @@ program.command("search", { isDefault: true }).description("Search the web or X,
1033
1050
  }
1034
1051
  await waitForPendingKills();
1035
1052
  process.exitCode = exitCode;
1036
- setTimeout(() => process.exit(exitCode), EXIT_BACKSTOP_MS).unref();
1053
+ const store = globalThis;
1054
+ const previous = store[EXIT_BACKSTOP_KEY];
1055
+ if (previous !== void 0) clearTimeout(previous);
1056
+ const timer = setTimeout(() => process.exit(exitCode), EXIT_BACKSTOP_MS);
1057
+ timer.unref();
1058
+ store[EXIT_BACKSTOP_KEY] = timer;
1037
1059
  });
1038
1060
  program.command("doctor").description("Diagnose config and routing on this machine (no quota, no network)").option("--json", "Print the report as JSON").action((options) => {
1039
1061
  try {
@@ -1129,13 +1151,11 @@ program.command("serve").description("Run the local SearXNG-compatible service t
1129
1151
  }
1130
1152
  let releaseLockFn;
1131
1153
  if (options.ensure) {
1132
- const running = readRuntimeFile();
1133
- if (running !== void 0) try {
1134
- if ((await fetch(`http://127.0.0.1:${running.port}/healthz`, { signal: AbortSignal.timeout(2e3) })).ok) {
1135
- process.stdout.write(`Already running on 127.0.0.1:${running.port}.\n`);
1136
- process.exit(0);
1137
- }
1138
- } catch {}
1154
+ const runningPort = await findRunningServe();
1155
+ if (runningPort !== void 0) {
1156
+ process.stdout.write(`Already running on 127.0.0.1:${runningPort}.\n`);
1157
+ process.exit(0);
1158
+ }
1139
1159
  const lockFile = path.join(path.dirname(runtimePath()), "serve.ensure.lock");
1140
1160
  let holdsLock = false;
1141
1161
  /** 抢锁失败时如果是环境错误,记在这里,让下面直接报出来而不是空等。 */
@@ -1234,7 +1254,13 @@ program.command("serve").description("Run the local SearXNG-compatible service t
1234
1254
  } catch {}
1235
1255
  await new Promise((resolve) => setTimeout(resolve, 300));
1236
1256
  }
1237
- process.stderr.write("Error: another serve --ensure is starting up; gave up waiting.\n");
1257
+ let waitingOnPid = 0;
1258
+ try {
1259
+ waitingOnPid = Number(fs$1.readFileSync(lockFile, "utf-8").trim());
1260
+ } catch {}
1261
+ if (waitingOnPid > 0 && !isAlive(waitingOnPid)) process.stderr.write(`Error: the process that was starting the service (pid ${waitingOnPid}) exited without writing runtime.json. Check that its candidate ports are free (or set serve.port to a free number).
1262
+ `);
1263
+ else process.stderr.write("Error: another serve --ensure is starting up; gave up waiting.\n");
1238
1264
  process.exit(1);
1239
1265
  }
1240
1266
  const releaseLock = () => {
@@ -1250,13 +1276,29 @@ program.command("serve").description("Run the local SearXNG-compatible service t
1250
1276
  releaseLockFn = releaseLock;
1251
1277
  }
1252
1278
  const token = ensureServeToken();
1279
+ const identity = identityOf(os.homedir());
1280
+ const useCandidates = requested === 0;
1253
1281
  try {
1254
1282
  const handle = await startServe({
1255
1283
  port: requested,
1256
1284
  token,
1257
- idleExitSeconds: options.daemon ? 0 : config.serve?.idleExitSeconds ?? 0
1285
+ idleExitSeconds: options.daemon ? 0 : config.serve?.idleExitSeconds ?? 0,
1286
+ fingerprint: identity.fingerprint,
1287
+ ...useCandidates ? { candidatePorts: identity.ports } : {}
1258
1288
  });
1259
1289
  process.stdout.write(`Listening on http://127.0.0.1:${handle.port}\n`);
1290
+ if (useCandidates) {
1291
+ const earlier = identity.ports.slice(0, identity.ports.indexOf(handle.port));
1292
+ if (earlier.length > 0) {
1293
+ const winner = await discoverServe(identity.fingerprint, earlier);
1294
+ if (winner !== void 0) {
1295
+ process.stdout.write(`Port ${handle.port} yielded to the instance already running on 127.0.0.1:${winner.port}.\n`);
1296
+ await handle.close();
1297
+ releaseLockFn?.();
1298
+ process.exit(0);
1299
+ }
1300
+ }
1301
+ }
1260
1302
  releaseLockFn?.();
1261
1303
  } catch (error) {
1262
1304
  releaseLockFn?.();
@@ -1295,7 +1337,8 @@ hosts.command("sync").description("Write each host configuration from ~/.searchf
1295
1337
  const selfDir = path.dirname(fileURLToPath(import.meta.url));
1296
1338
  const result = syncClaudeSettings(claudeEnabled, {
1297
1339
  runtimePath: path.join(os.homedir(), ".searchfuse", "runtime.json"),
1298
- kernelPath: path.join(selfDir, "kernel.js")
1340
+ kernelPath: path.join(selfDir, "kernel.js"),
1341
+ identity: identityOf(os.homedir())
1299
1342
  });
1300
1343
  lines.push(`claudeCode: ${claudeEnabled ? "enabled" : "disabled"}` + (result.changed ? "" : " (no change)") + (result.backup ? ` [backup: ${path.basename(result.backup)}]` : ""));
1301
1344
  }
@@ -2663,8 +2663,11 @@ function setConfigValue(dottedKey, value, configPath = currentConfigPath()) {
2663
2663
  const parsed = coerceBoolean(value);
2664
2664
  if (parsed === void 0) throw new Error(`Invalid allowPrivateNetwork value: ${value}. Use true or false.`);
2665
2665
  config.allowPrivateNetwork = parsed;
2666
- } else if (parts.length === 2 && parts[0] === "hosts") {
2666
+ } else if (parts[0] === "hosts") {
2667
+ if (parts.length !== 2 && parts.length !== 3) throw new Error(`Unknown hosts setting: ${dottedKey}. Use hosts.<name> or hosts.<name>.enabled.`);
2667
2668
  const hostName = parts[1];
2669
+ const field = parts[2];
2670
+ if (field !== void 0 && field !== "enabled") throw new Error(`Unknown hosts setting: hosts.${hostName}.${field}. Use hosts.${hostName}.enabled.`);
2668
2671
  const knownHosts = [
2669
2672
  "dsh",
2670
2673
  "claudeCode",
@@ -2672,7 +2675,7 @@ function setConfigValue(dottedKey, value, configPath = currentConfigPath()) {
2672
2675
  ];
2673
2676
  if (!knownHosts.includes(hostName)) throw new Error(`Unknown host: ${hostName}. Known hosts: ${knownHosts.join(", ")}.`);
2674
2677
  const parsed = coerceBoolean(value);
2675
- if (parsed === void 0) throw new Error(`Invalid hosts.${hostName} value: ${value}. Use true or false.`);
2678
+ if (parsed === void 0) throw new Error(`Invalid hosts.${hostName}.enabled value: ${value}. Use true or false.`);
2676
2679
  config.hosts = {
2677
2680
  ...config.hosts,
2678
2681
  [hostName]: {
@@ -3065,24 +3068,56 @@ function parseResetDuration(message) {
3065
3068
  return (hours * 3600 + minutes * 60 + seconds) * 1e3;
3066
3069
  }
3067
3070
  /**
3071
+ * Parse an explicit retry-after value in seconds, or null.
3072
+ *
3073
+ * Firecrawl 的免注册额度耗尽时报 429,正文是 JSON:
3074
+ * `{"reason":"credits","retry_after_seconds":66233}`。这个秒数就是权威的恢复
3075
+ * 时间,比任何兜底 TTL 都准。同时也认 HTTP 标准的 `Retry-After` 头写进
3076
+ * message 的**秒数形态**。
3077
+ *
3078
+ * **不认 HTTP-date 形态**(`Retry-After: Wed, 21 Oct 2015 07:28:00 GMT`)。
3079
+ * 认不动时会返回 null 退回兜底 TTL,冷却偏短而不是偏长,是可以接受的降级。
3080
+ * 真正会写出 date 形态的上游,正文里通常另有 `Resets in ...` 或秒数字段。
3081
+ */
3082
+ function parseRetryAfterSeconds(message) {
3083
+ const match = /"retry_after_seconds"\s*:\s*(\d+)/i.exec(message);
3084
+ if (match) {
3085
+ const seconds = Number.parseInt(match[1] ?? "", 10);
3086
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : null;
3087
+ }
3088
+ const header = /\bretry-after:\s*(\d+)/i.exec(message);
3089
+ if (header) {
3090
+ const seconds = Number.parseInt(header[1] ?? "", 10);
3091
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : null;
3092
+ }
3093
+ return null;
3094
+ }
3095
+ /**
3068
3096
  * Decide whether an engine failure is the quota class worth remembering, and
3069
3097
  * when the engine should recover. A per-second rate limit is transient, not a
3070
3098
  * spent budget, so it returns null and never touches the store. A quota error
3071
3099
  * with a reset clause recovers precisely, one without recovers after the
3072
3100
  * default TTL. A region lock is not a quota but is just as lasting, so it is
3073
3101
  * held for a day.
3102
+ *
3103
+ * **429 不等于瞬时限流。** firecrawl 的免注册额度用完时也回 429,正文却明写
3104
+ * `"reason":"credits"` 与 `retry_after_seconds`——那是花光的预算,不是每秒
3105
+ * 一次的抖动。早先只看 `/429/` 就 `return null`,于是每跑一次搜索都白撞一次
3106
+ * 这堵墙,而 `retry_after_seconds` 这个权威恢复时间从来没人读。
3074
3107
  */
3075
3108
  function classifyQuota(error, now) {
3076
3109
  const message = error instanceof Error ? error.message : String(error);
3077
3110
  if (REGION_LOCKED.test(message)) return new Date(now.getTime() + MONTHLY_COOLDOWN_MS);
3078
3111
  const looksRateLimited = /rate.?limit|too many requests|\b429\b/i.test(message);
3079
3112
  const monthlyQuota = /\bhttp 43[23]\b/i.test(message);
3080
- const looksQuota = monthlyQuota || /quota|out of credit|insufficient (?:balance|credit)|credits? (?:exhausted|used up)|balance|Resets? in/i.test(message);
3113
+ const creditReason = /"reason"\s*:\s*"[^"]*(?:credits(?=["_]|$)|credit[_-](?:exhausted|depleted|used|limit|quota)|quota|(?:usage|daily|monthly|plan|billing)[_-]?limit(?:[_-](?:reached|exceeded))?)/i.test(message);
3114
+ const looksQuota = monthlyQuota || creditReason || /quota|out of credit|insufficient (?:balance|credit)|credits? (?:exhausted|used up)|balance|Resets? in/i.test(message);
3081
3115
  if (looksRateLimited && !looksQuota) return null;
3082
3116
  if (!looksQuota) return null;
3083
- const resetMs = parseResetDuration(message);
3117
+ const resetMs = parseRetryAfterSeconds(message) ?? parseResetDuration(message);
3084
3118
  const fallbackMs = monthlyQuota ? MONTHLY_COOLDOWN_MS : DEFAULT_COOLDOWN_MS;
3085
- return new Date(now.getTime() + (resetMs ?? fallbackMs));
3119
+ const until = new Date(now.getTime() + (resetMs ?? fallbackMs));
3120
+ return Number.isFinite(until.getTime()) ? until : null;
3086
3121
  }
3087
3122
  /**
3088
3123
  * Record a cooldown when the error is quota class. Mutates the in-memory state
@@ -3218,9 +3253,14 @@ async function fanout(targets, request, totalDeadlineMs, cancelSignal, options =
3218
3253
  }));
3219
3254
  const outputs = [];
3220
3255
  const failures = [];
3256
+ const outcomes = [];
3221
3257
  for (const { name, outcome } of settled) {
3222
3258
  if (outcome === "stopped") {
3223
3259
  failures.push(cancelledByCaller() ? `${name}: the run was cancelled before this source answered.` : `${name}: timed out after ${totalDeadlineMs} ms.`);
3260
+ outcomes.push({
3261
+ engine: name,
3262
+ ok: false
3263
+ });
3224
3264
  continue;
3225
3265
  }
3226
3266
  if (outcome.status === "fulfilled") {
@@ -3230,21 +3270,33 @@ async function fanout(targets, request, totalDeadlineMs, cancelSignal, options =
3230
3270
  engine: name,
3231
3271
  items
3232
3272
  });
3273
+ outcomes.push({
3274
+ engine: name,
3275
+ ok: true
3276
+ });
3233
3277
  continue;
3234
3278
  }
3235
3279
  const reason = outcome.reason;
3236
3280
  const text = reason instanceof Error ? reason.message : String(reason);
3237
3281
  failures.push(`${name}: ${text}`);
3282
+ outcomes.push({
3283
+ engine: name,
3284
+ ok: false,
3285
+ reason
3286
+ });
3238
3287
  }
3239
3288
  if (outputs.length === 0) {
3240
3289
  const lines = [...failures, ...skipped];
3241
3290
  const why = cancelledByCaller() ? "The run was cancelled." : "Every engine failed or was skipped, so nothing could be fused.";
3242
- throw new Error(`${why} ${lines.join(" | ")}`);
3291
+ const error = /* @__PURE__ */ new Error(`${why} ${lines.join(" | ")}`);
3292
+ error.outcomes = outcomes;
3293
+ throw error;
3243
3294
  }
3244
3295
  return {
3245
3296
  outputs,
3246
3297
  failures,
3247
- skipped
3298
+ skipped,
3299
+ outcomes
3248
3300
  };
3249
3301
  }
3250
3302
  // src/aggregate/canonicalUrl.ts
@@ -3804,9 +3856,21 @@ async function runFused(config, env, query, timeoutMs, options) {
3804
3856
  skipped.push(`${engine.name}: 处于冷却期,本次未参与(配额恢复后自动回归)`);
3805
3857
  continue;
3806
3858
  }
3859
+ let effective = settings;
3860
+ if (controller && keyCount > 1) {
3861
+ const keys = splitApiKeys(settings.apiKey);
3862
+ const healthy = keys.findIndex((_, index) => !coolingEntry(controller.state, engine.name, controller.now, index));
3863
+ if (healthy > 0) {
3864
+ const reordered = [keys[healthy], ...keys.filter((_, index) => index !== healthy)];
3865
+ effective = {
3866
+ ...settings,
3867
+ apiKey: reordered.join(",")
3868
+ };
3869
+ }
3870
+ }
3807
3871
  targets.push({
3808
3872
  engine,
3809
- settings
3873
+ settings: effective
3810
3874
  });
3811
3875
  }
3812
3876
  if (targets.length === 0) return;
@@ -3824,23 +3888,67 @@ async function runFused(config, env, query, timeoutMs, options) {
3824
3888
  try {
3825
3889
  fanoutResult = await fanout(targets, request, budgetMs, void 0, { skipped });
3826
3890
  } catch (error) {
3891
+ recordFusedCooldowns(controller, error);
3827
3892
  throw error;
3828
3893
  }
3829
- const { outputs, failures } = fanoutResult;
3894
+ const { outputs, failures, outcomes } = fanoutResult;
3830
3895
  return buildFusedResult({
3831
3896
  items: rrfFuse(outputs),
3832
3897
  engines: outputs.map((o) => o.engine),
3833
3898
  failures,
3834
3899
  skipped,
3900
+ cooldownNotes: recordFusedCooldowns(controller, void 0, outcomes) ?? [],
3835
3901
  durationSeconds: (Date.now() - startedAt) / 1e3,
3836
3902
  query
3837
3903
  });
3838
3904
  }
3839
3905
  /**
3906
+ * 把融合运行里每个引擎的结局落到冷却记录上,返回一行行给人看的提示。
3907
+ *
3908
+ * 超时与取消(`ok: false` 但没有 `reason`)不该记——它们是瞬时的,与配额
3909
+ * 无关;`classifyQuota` 自己也会再判一遍(限流不算配额)。
3910
+ *
3911
+ * 全灭时 `fanout` 抛错,调用方从带出来的 `outcomes` 里再取一次;这就是
3912
+ * `fallbackError` 参数的用途。
3913
+ */
3914
+ function recordFusedCooldowns(controller, fallbackError, outcomes) {
3915
+ if (!controller) return void 0;
3916
+ const source = outcomes ?? outcomesFromError(fallbackError);
3917
+ const notes = [];
3918
+ for (const outcome of source) {
3919
+ if (typeof outcome?.engine !== "string") continue;
3920
+ if (outcome.ok) {
3921
+ const stateKey = cooldownStateKey(outcome.engine);
3922
+ if (controller.state.engineCooldowns[stateKey] !== void 0) controller.clear(outcome.engine);
3923
+ continue;
3924
+ }
3925
+ if (outcome.reason === void 0) continue;
3926
+ try {
3927
+ const entry = controller.record(outcome.engine, outcome.reason);
3928
+ if (entry) notes.push(`The ${outcome.engine} engine hit a lasting limit (quota or region) and is now cooling until ${entry.until}.`);
3929
+ } catch (recordError) {
3930
+ const message = recordError instanceof Error ? recordError.message : String(recordError);
3931
+ notes.push(`Cooldown state for ${outcome.engine} could not be recorded (${message}).`);
3932
+ }
3933
+ }
3934
+ return notes;
3935
+ }
3936
+ /**
3937
+ * 从 `fanout` 抛出的错误上取回各引擎的结局。
3938
+ *
3939
+ * `fanout` 把 `outcomes` 挂在 error 上(见它的全灭分支),这样失败路径不必
3940
+ * 为了记冷却重跑一遍引擎。取不到就当没有——记冷却失败不该掩盖原错误。
3941
+ */
3942
+ function outcomesFromError(error) {
3943
+ if (typeof error !== "object" || error === null) return [];
3944
+ const outcomes = error.outcomes;
3945
+ return Array.isArray(outcomes) ? outcomes : [];
3946
+ }
3947
+ /**
3840
3948
  * 组装一次融合运行作答所用的条目。
3841
3949
  */
3842
3950
  function buildFusedResult(input) {
3843
- const { items, engines, failures, skipped, durationSeconds, query } = input;
3951
+ const { items, engines, failures, skipped, cooldownNotes, durationSeconds, query } = input;
3844
3952
  const multiSource = items.filter((item) => {
3845
3953
  const found = item.foundIn;
3846
3954
  return Array.isArray(found) && found.length > 1;
@@ -3853,7 +3961,11 @@ function buildFusedResult(input) {
3853
3961
  status: failures.length > 0 ? "degraded" : "ok",
3854
3962
  summary,
3855
3963
  items,
3856
- uncertainty: [...failures, ...skipped],
3964
+ uncertainty: [
3965
+ ...failures,
3966
+ ...skipped,
3967
+ ...cooldownNotes ?? []
3968
+ ],
3857
3969
  warnings: items.length === 0 ? ["No results were returned by any of the eligible engines."] : [],
3858
3970
  attempts: [],
3859
3971
  durationSeconds
@@ -1,140 +1 @@
1
- import { n as runtimePath } from "./serve-Bfqz-nCB.js";
2
- import { r as spawnHidden } from "./search-BIW13Csk.js";
3
- import * as path from "node:path";
4
- import * as fs from "node:fs";
5
- import * as http from "node:http";
6
- import { fileURLToPath } from "node:url";
7
- // src/serveEnsure.ts
8
- var DEFAULT_TIMEOUT_MS = 2e4;
9
- /** 探 /healthz 的上限。服务是本机回环,超过就算不通。 */
10
- var HEALTH_TIMEOUT_MS = 2e3;
11
- /** spawn 之后轮询就绪状态的间隔。 */
12
- var POLL_INTERVAL_MS = 500;
13
- /** 睡一会儿。轮询用,为这点事引入依赖不值得。 */
14
- function sleep(ms) {
15
- return new Promise((resolve) => setTimeout(resolve, ms));
16
- }
17
- /** 把 spawn 失败整理成一行可读的原因。 */
18
- function describeSpawnFailure(error) {
19
- return `serve --ensure failed to start: ${error instanceof Error ? error.message : String(error)}`;
20
- }
21
- /**
22
- * 读 `~/.searchfuse/runtime.json`。
23
- *
24
- * 文件可能被 `serve --ensure` 写入、被 `serve` 的 close() 删除,也可能
25
- * 上一次进程被杀后残留成「指向死端口」。所以形状检查必须严格:
26
- * 端口不是数字就直接当没有,宁可多拉起一次,也不要拿一个坏端口去连。
27
- */
28
- function readServeRuntimeFile(file = runtimePath()) {
29
- try {
30
- const raw = fs.readFileSync(file, "utf-8");
31
- const parsed = JSON.parse(raw);
32
- if (typeof parsed.port !== "number" || !Number.isInteger(parsed.port)) return void 0;
33
- if (typeof parsed.token !== "string" || parsed.token === "") return void 0;
34
- return {
35
- port: parsed.port,
36
- token: parsed.token
37
- };
38
- } catch {
39
- return;
40
- }
41
- }
42
- /** 探一次 /healthz。返回是否 200。 */
43
- function healthOnce(port) {
44
- return new Promise((resolve) => {
45
- const req = http.request({
46
- host: "127.0.0.1",
47
- port,
48
- path: "/healthz",
49
- method: "GET",
50
- timeout: HEALTH_TIMEOUT_MS,
51
- headers: { Connection: "close" }
52
- }, (res) => {
53
- res.resume();
54
- resolve(res.statusCode === 200);
55
- });
56
- req.on("error", () => resolve(false));
57
- req.on("timeout", () => {
58
- req.destroy();
59
- resolve(false);
60
- });
61
- req.end();
62
- });
63
- }
64
- /**
65
- * 确保本地服务在跑。已在跑就什么都不做。
66
- *
67
- * 顺序是「先探文件、再探 /healthz、最后才 spawn」:文件在但服务已死是最阴的
68
- * 状态(服务不能用、文件却指向它),直接 spawn 会撞上仍被占用的端口。
69
- *
70
- * 拉起复用 `serve --ensure` 而不是自己起服务:它已经处理了「端口 0 由内核
71
- * 分配」「已在跑就 exit 0」两个边界。在插件里重写一遍必然漂移。
72
- *
73
- * 就绪的判据是 `/healthz` 通过,不是子进程退出码。`serve --ensure` 只在
74
- * 「已经在跑」时以 0 退出;真正需要起服务时它会把服务拉起来并**常驻**,
75
- * 永远等不到 close 事件。等退出码会一路等到超时,然后用 child.kill() 杀掉
76
- * 刚刚起来的那个服务——这正是本设计要避免的事。所以 spawn 之后就把子进程
77
- * 交出去(detached + unref),改为轮询健康检查。
78
- */
79
- async function ensureServeRunning(options = {}) {
80
- const file = runtimePath();
81
- const existing = readServeRuntimeFile(file);
82
- if (existing !== void 0 && await healthOnce(existing.port)) return {
83
- started: false,
84
- port: existing.port
85
- };
86
- const cliPath = options.cliPath ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist", "main.js");
87
- const nodeBinary = options.nodeBinary ?? "node";
88
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
89
- let spawnError;
90
- let exitedEarly;
91
- try {
92
- const child = spawnHidden(nodeBinary, [
93
- cliPath,
94
- "serve",
95
- "--ensure"
96
- ], {
97
- stdio: "ignore",
98
- detached: true
99
- });
100
- child.unref();
101
- child.on("error", (error) => {
102
- spawnError = error;
103
- });
104
- child.on("close", (code) => {
105
- exitedEarly = code === null ? void 0 : code;
106
- });
107
- } catch (error) {
108
- return {
109
- started: false,
110
- reason: describeSpawnFailure(error)
111
- };
112
- }
113
- const deadline = Date.now() + timeoutMs;
114
- for (;;) {
115
- if (spawnError !== void 0) return {
116
- started: false,
117
- reason: describeSpawnFailure(spawnError)
118
- };
119
- if (exitedEarly !== void 0 && exitedEarly !== 0) return {
120
- started: false,
121
- reason: `serve --ensure exited ${exitedEarly}`
122
- };
123
- const runtime = readServeRuntimeFile(file);
124
- if (runtime !== void 0) {
125
- if (await healthOnce(runtime.port)) return {
126
- started: true,
127
- port: runtime.port
128
- };
129
- } else if (exitedEarly === 0) return {
130
- started: false,
131
- reason: "runtime.json not written"
132
- };
133
- if (Date.now() >= deadline) return {
134
- started: false,
135
- reason: `serve did not become healthy within ${timeoutMs} ms`
136
- };
137
- await sleep(POLL_INTERVAL_MS);
138
- }
139
- }
140
- export { ensureServeRunning, readServeRuntimeFile };
1
+ export { t as discoverServe, n as ensureServeRunning, r as findRunningServe, i as readServeRuntimeFile } from "./serveEnsure-BTj9IifL.js";