@240xu/dsh-websearch 2.8.8 → 2.8.9

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/lib/provider.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // Per-backend timeout: each backend call wrapped with opts.backendTimeoutMs (default 30s).
16
16
 
17
17
  import { WebError } from "@deepseek-ai/dsh-web";
18
- import { maybeAbortError, searchAborted, throwIfSearchAborted, isAbortedWebError } from "./util/abort.js";
18
+ import { searchAborted, throwIfSearchAborted } from "./util/abort.js";
19
19
  import {
20
20
  recordBackendRequest,
21
21
  recordBackendOutcome,
@@ -25,9 +25,12 @@ import { normalizeFilters } from "./util/filters.js";
25
25
  import { shapeQuery, resultHeader, TELEMETRY_TAG } from "./prompting.js";
26
26
  import { cacheKeyFor } from "./cache.js";
27
27
  import { foldBreaker, isCooled, cooledAnnotation } from "./breaker.js";
28
+ import { rateLimited, retryAfterMsFrom, keylessRejected } from "./util/failure-label.js";
28
29
  import { rrfFuse } from "./rrf.js";
29
30
  import { isComplexQuery, deriveSubQueries } from "./multiquery.js";
30
31
  import { failureLabel } from "./util/failure-label.js";
32
+ import { invalidBaseURL } from "./util/base-url.js";
33
+ import { sanitizeError } from "./util/redact.js";
31
34
 
32
35
  const PROVIDER_ID = "unified";
33
36
 
@@ -36,14 +39,13 @@ const PROVIDER_ID = "unified";
36
39
  // default lets one dead backend stall the whole fan-out tail. The effective
37
40
  // timeout is min(override, backendTimeoutMs), so an operator's shorter global
38
41
  // timeout always wins.
39
- // ddg raised 5s -> 8s in v2.8.6 (route6): a live getting-through DDG fetch
40
- // through the TLS forwarder measured 7.7s, so the 5s ceiling killed slow-but-
41
- // working scrapes ("ddg: timed out after 5000ms" while the page was one
42
- // second away). searxng stays at 5s — searx.be answers in ~1.3s when up, and
43
- // failover cooldowns make a fast fail cheaper than a long wait.
42
+ // ddg raised 5s -> 8s in v2.8.6 (route6): a live DDG fetch through the TLS
43
+ // forwarder measured 7.7s, so a 5s ceiling killed slow-but-working scrapes.
44
+ // searxng also gets 8s here: the public instances we use are slower than
45
+ // searx.be, and a hard 5s cap killed them mid-fetch in our probes.
44
46
  const BACKEND_TIMEOUT_OVERRIDES_MS = {
45
47
  ddg: 8000,
46
- searxng: 5000,
48
+ searxng: 8000,
47
49
  };
48
50
 
49
51
  /** Effective per-backend timeout = min(override ?? ∞, global). Exported for tests. */
@@ -70,14 +72,32 @@ export function getLatestBackendHealth() {
70
72
  return latestBackendHealth;
71
73
  }
72
74
 
73
- function recordBackendHealth(id, entry, breakerCfg) {
75
+ /** Append one entry to the search history with the shape every caller needs.
76
+ * Four call sites (cache hit, results, empty-but-successful, total failure)
77
+ * differ only in `resultCount` and the per-backend counters. */
78
+ function recordHistory(history, query, resultCount, backendsOk, backendsTotal) {
79
+ history?.record({ query, time: Date.now(), resultCount, backendsOk, backendsTotal });
80
+ }
81
+
82
+ function recordBackendHealth(id, entry, breakerCfg, opts = {}) {
74
83
  const prev = latestBackendHealth.get(id);
75
- const breaker = foldBreaker(prev, entry.ok === true, entry.at, breakerCfg ?? undefined);
84
+ // `null` means the operator disabled the breaker. Still count consecutive
85
+ // failures for diagnostics, but never publish a cooldown the provider does
86
+ // not honour (health/history used to show `cooled: true` while the backend
87
+ // kept being called).
88
+ const breaker = breakerCfg === null
89
+ ? { failCount: entry.ok === true ? 0 : (Number(prev?.failCount) || 0) + 1, cooledUntil: 0 }
90
+ : foldBreaker(prev, entry.ok === true, entry.at, breakerCfg, opts);
76
91
  latestBackendHealth.set(id, {
77
92
  ...entry,
78
93
  lastOkAt: entry.ok === true ? entry.at : (prev && prev.lastOkAt) || null,
79
94
  failCount: breaker.failCount,
80
95
  cooledUntil: breaker.cooledUntil,
96
+ // Persist the classification so a later full-cooldown decision can
97
+ // distinguish quota failures from ordinary outages and from a keyless
98
+ // permission refusal (which cannot be fixed by retrying after a wait).
99
+ rateLimited: opts.rateLimited === true,
100
+ keylessRejected: opts.keylessRejected === true,
81
101
  });
82
102
  }
83
103
 
@@ -95,6 +115,10 @@ export function getBackendBreaker(id) {
95
115
  */
96
116
  // 2.8.2: exported for P1 regression tests (limiter sync-throw deadlock)
97
117
  export function createLimiter(concurrency) {
118
+ // A zero/negative limit would leave every queued backend unresolved with
119
+ // no timeout to rescue it. Config and the GUI validate [1,10], but the
120
+ // limiter also receives values from hand-written profiles and embedders.
121
+ const maxRunning = Math.max(1, Math.floor(Number(concurrency) || 1));
98
122
  const queue = [];
99
123
  let running = 0;
100
124
 
@@ -104,7 +128,7 @@ export function createLimiter(concurrency) {
104
128
  process();
105
129
 
106
130
  function process() {
107
- while (running < concurrency && queue.length > 0) {
131
+ while (running < maxRunning && queue.length > 0) {
108
132
  const { fn, resolve, reject } = queue.shift();
109
133
  running++;
110
134
  // 2.8.2(P1):必须 .then(fn) 而非 Promise.resolve(fn())——后者先执行
@@ -202,19 +226,37 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
202
226
  ...(opts.filters ?? {}),
203
227
  ...(request?.filters ?? {}),
204
228
  });
205
- let effReq = { ...request, maxResults: Math.max(1, Number(request?.maxResults) || opts.numResults || 8) };
206
- // 系统性查询整形(Tavily/Exa best practices):扇出前对口语化查询做
207
- // 确定性归一 —— 剥离寒暄前缀、压缩空白、截断到 1500 字符;
208
- // 专名/版本号/日期原样保留,不改写语义。
209
- effReq.query = shapeQuery(effReq.query);
210
- // 2.8.2(P2):整形后为空("搜索"/"search" 等寒暄独词被剥光)→ 早拒。
211
- // 不拒会:①空串扇出全部后端 ②不同原始查询共享 "" 缓存键(别名污染)
212
- // ③落入 all-backends-failed(0) 的误导错误。
213
- if (!effReq.query) {
214
- throw new WebError(
215
- "unified search: empty query after shaping (the request contained only fillers like \"search\")",
216
- "WEB_PROVIDER_ERROR",
217
- );
229
+ // The host sends its deployment cap as request.maxResults; the card's
230
+ // numResults is the user's requested count. Neither alone is right:
231
+ // cap wins when smaller (never exceed the deployment limit), the user
232
+ // value wins when smaller (settings must actually take effect).
233
+ const hostCap = Number(request?.maxResults);
234
+ const userMax = opts.numResults === undefined || opts.numResults === null
235
+ ? Number.POSITIVE_INFINITY
236
+ : Number(opts.numResults);
237
+ // `official` leaves the count to the consumer (the tool always sends
238
+ // maxResults); every other tier keeps the user's explicit count as an
239
+ // upper bound, but never exceeds the host cap.
240
+ const finiteCaps = [hostCap, userMax].filter((n) => Number.isFinite(n) && n > 0);
241
+ const boundedMax = finiteCaps.length > 0 ? Math.max(1, Math.min(...finiteCaps)) : 10;
242
+ let effReq = { ...request, maxResults: boundedMax };
243
+ // `official` passes the model's exact query: the official consumer owns
244
+ // query construction, and provider-level rewriting can change a quoted
245
+ // phrase or a product name. `balanced`/`thorough` strip only
246
+ // conversational prefixes (see prompting.js).
247
+ if (opts.queryShaping !== false) {
248
+ effReq.query = shapeQuery(effReq.query);
249
+ // 2.8.2(P2):整形后为空("搜索"/"search" 等寒暄独词被剥光)→ 早拒。
250
+ // 不拒会:①空串扇出全部后端 ②不同原始查询共享 "" 缓存键(别名污染)
251
+ // ③落入 all-backends-failed(0) 的误导错误。
252
+ if (!effReq.query) {
253
+ throw new WebError(
254
+ "unified search: empty query after shaping (the request contained only fillers like \"search\")",
255
+ "WEB_PROVIDER_ERROR",
256
+ );
257
+ }
258
+ } else if (typeof effReq.query !== "string" || effReq.query.trim() === "") {
259
+ throw new WebError("unified search: empty query", "WEB_PROVIDER_ERROR");
218
260
  }
219
261
  if (Object.keys(filters).length > 0) effReq = { ...effReq, filters };
220
262
  const maxResults = effReq.maxResults;
@@ -226,11 +268,20 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
226
268
  const coverage = opts.deepCoverage === true;
227
269
  // Per-backend widening: fetch more per backend, dedupe down afterwards.
228
270
  const backendMaxResults = coverage ? Math.ceil(maxResults * 1.5) : maxResults;
229
- const multi = opts.multiQueryEnabled === true && isComplexQuery(effReq.query);
230
- const variants = multi ? deriveSubQueries(effReq.query) : [effReq.query];
271
+ const multiGate = opts.multiQueryEnabled === true && isComplexQuery(effReq.query);
272
+ const derived = multiGate ? deriveSubQueries(effReq.query) : [effReq.query];
273
+ // A gate-true query can still derive zero useful variants ("C vs Rust"
274
+ // drops the one-character "C"). Treat that as single-query instead of
275
+ // flipping cacheMode and paying for a duplicate cache entry.
276
+ const useMulti = derived.length > 1;
277
+ const variants = useMulti ? derived : [effReq.query];
278
+ // Result-presentation language also keys the cache: two raw queries can
279
+ // shape to the same string ("请搜索 cats" / "cats") while the header
280
+ // language follows the raw request.
281
+ const queryLanguage = /[\u4e00-\u9fff]/.test(String(request?.query ?? "")) ? "zh" : "en";
231
282
  // Cache-key mode marker: different coverage/multiQuery settings must not
232
283
  // serve each other's cached results.
233
- const cacheMode = (multi ? "multi" : "single") + (coverage ? "+coverage" : "");
284
+ const cacheMode = (useMulti ? "multi" : "single") + (coverage ? "+coverage" : "");
234
285
 
235
286
  // v2.7.0 disk cache: keyed on (shaped query + filters + maxResults +
236
287
  // backends + mode). A hit short-circuits the fan-out entirely; sources
@@ -239,7 +290,30 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
239
290
  const cacheEnabled = opts.cacheEnabled === true && cache;
240
291
  let cacheKey = null;
241
292
  if (cacheEnabled) {
242
- cacheKey = cacheKeyFor({ query: effReq.query, filters, maxResults, backends: opts.enabledBackends, mode: cacheMode });
293
+ // Result-affecting options belong in the key; otherwise a settings
294
+ // change is masked by a hit within the cache TTL.
295
+ const resultOptions = {};
296
+ for (const [k, v] of Object.entries(opts)) {
297
+ if (typeof v === "function") continue;
298
+ if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping)$/.test(k)
299
+ || /BaseURL$|^.*Model$|^.*ApiKeyEnv$|^enable[A-Z]/.test(k)) resultOptions[k] = v;
300
+ }
301
+ // resolveOptions() keeps per-backend settings under opts.backends[id],
302
+ // not as top-level opts keys. Flatten the result-affecting ones with
303
+ // an id prefix so editing a backend's baseURL/model/searchDepth does
304
+ // not get masked by a cache hit within the TTL (65 号 N2).
305
+ for (const id of opts.enabledBackends ?? []) {
306
+ const be = opts.backends?.[id];
307
+ if (!be || typeof be !== "object") continue;
308
+ // Every per-backend option that changes results must appear here, or
309
+ // a cache hit inside the TTL masks the edit. baseURLs (plural) is the
310
+ // SearXNG failover list; leaving it out made instance changes inert.
311
+ for (const k of ["baseURL", "baseURLs", "model", "searchDepth", "safeSearch", "apiKeyEnv"]) {
312
+ if (be[k] !== undefined) resultOptions[`${id}.${k}`] = be[k];
313
+ }
314
+ }
315
+ resultOptions.queryLanguage = queryLanguage;
316
+ cacheKey = cacheKeyFor({ query: effReq.query, filters, maxResults, backends: opts.enabledBackends, mode: cacheMode, resultOptions });
243
317
  const hit = cache.get(cacheKey);
244
318
  if (hit && Array.isArray(hit.value?.sources) && hit.value.sources.length > 0) {
245
319
  // Defense in depth: the fresh path drops non-http(s) schemes before
@@ -254,13 +328,10 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
254
328
  let hitContent = typeof hit.value.content === "string" ? hit.value.content : undefined;
255
329
  const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
256
330
  hitContent = hitContent === undefined ? cacheNote : hitContent + "\n\n" + cacheNote;
257
- history?.record({
258
- query: request?.query,
259
- time: Date.now(),
260
- resultCount: hit.value.sources.length,
261
- backendsOk: 0,
262
- backendsTotal: 0,
263
- });
331
+ // A cache hit is served from a prior successful fan-out; a zero
332
+ // counter made it indistinguishable from a total outage.
333
+ const hitCount = hit.value.sources.length > 0 ? 1 : 0;
334
+ recordHistory(history, request?.query, hit.value.sources.length, hitCount, hitCount);
264
335
  return {
265
336
  sources: safeSources,
266
337
  ...(hitContent !== undefined ? { content: hitContent } : {}),
@@ -290,17 +361,56 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
290
361
  candidates.push({ id, backend: be, beOpts });
291
362
  }
292
363
  const cooled = new Map();
364
+ const rateLimitedCooled = new Map();
293
365
  let eligible = candidates;
294
366
  if (breakerCfg) {
295
367
  const active = candidates.filter((c) => {
296
- if (isCooled(latestBackendHealth.get(c.id), nowMs)) {
297
- cooled.set(c.id, latestBackendHealth.get(c.id));
368
+ const entry = latestBackendHealth.get(c.id);
369
+ if (isCooled(entry, nowMs)) {
370
+ cooled.set(c.id, entry);
371
+ if (entry?.rateLimited === true) rateLimitedCooled.set(c.id, entry);
298
372
  return false;
299
373
  }
300
374
  return true;
301
375
  });
302
- if (active.length > 0) eligible = active;
303
- else cooled.clear(); // all cooled -> fail-open
376
+ // A rate-limited/quota backend must never be re-hit while its cooldown
377
+ // is open, even in a mixed outage. Only the non-quota cooled backends
378
+ // keep the historical fail-open behaviour; when nothing usable remains
379
+ // and at least one cooldown is quota-driven, fail fast with a retry hint.
380
+ // A backend in a non-quota cooldown stays out of the fan-out while any
381
+ // healthy backend remains: retrying it every search made the breaker
382
+ // inert (three failures in a row never actually stopped the calls).
383
+ // Only when EVERYTHING is cooling do we fail open — refusing to search
384
+ // at all is worse than re-hitting a backend that might have recovered.
385
+ const cooledReusable = [...cooled.entries()]
386
+ .filter(([, e]) => e?.rateLimited !== true)
387
+ .map(([id]) => candidates.find((c) => c.id === id))
388
+ .filter(Boolean);
389
+ const failOpen = active.length > 0 ? active : cooledReusable;
390
+ if (failOpen.length > 0) eligible = failOpen;
391
+ else if (rateLimitedCooled.size > 0) {
392
+ const until = Math.max(...[...rateLimitedCooled.values()].map((e) => e?.cooledUntil ?? 0));
393
+ const waitS = Math.max(0, Math.ceil((until - nowMs) / 1000));
394
+ // Distinguish a real quota/rate-limit cooldown from a keyless
395
+ // permission refusal: retrying the latter after N seconds cannot
396
+ // succeed without configuring a key.
397
+ const keyless = [...rateLimitedCooled.values()].some((e) => e?.keylessRejected === true);
398
+ if (keyless) {
399
+ throw new WebError(
400
+ "unified search: all backends need an API key (keyless access is unavailable); add a key or enable another backend",
401
+ "WEB_PROVIDER_ERROR",
402
+ );
403
+ }
404
+ throw new WebError(
405
+ `unified search: all backends are rate-limited; retry after ~${waitS}s`,
406
+ "WEB_PROVIDER_ERROR",
407
+ );
408
+ } else {
409
+ // Pure non-quota outage: keep fail-open so a breaker can never make
410
+ // search worse than no breaker.
411
+ eligible = candidates;
412
+ cooled.clear();
413
+ }
304
414
  }
305
415
 
306
416
  if (eligible.length === 0) {
@@ -315,6 +425,10 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
315
425
  // internal abort/timeout semantics are unchanged from v2.7.
316
426
  const fanoutVariant = async (variantReq) => {
317
427
  const telemetry = [];
428
+ // Health is folded once per backend per SEARCH, after every variant
429
+ // finished: recording per variant let one multi-query search trip the
430
+ // 3-failure breaker (and inflate history counters) by itself.
431
+ const health = [];
318
432
  const limit = createLimiter(concurrency);
319
433
  const runBackend = ({ id, backend, beOpts, hooks }) => {
320
434
  const startedAtMs = Date.now();
@@ -322,12 +436,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
322
436
  // Enforce http(s); plain http only for private hosts (self-hosted SearXNG).
323
437
  // Reject embedded credentials. Failure is a per-backend soft error.
324
438
  if (beOpts.baseURL !== undefined) {
325
- let bu = null;
326
- try { bu = new URL(beOpts.baseURL); } catch { bu = null; }
327
- const privHost = bu ? /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){3}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){3})$/.test(bu.hostname) : false;
328
- const schemeOk = bu && (bu.protocol === "https:" || (bu.protocol === "http:" && privHost));
329
- if (!schemeOk || bu.username || bu.password) {
330
- throw new WebError(`backend "${id}" has an invalid baseURL: https required (plain http only for private hosts), credentials-in-URL rejected`, "WEB_PROVIDER_ERROR");
439
+ const invalid = invalidBaseURL(beOpts.baseURL);
440
+ if (invalid !== undefined) {
441
+ throw new WebError(`backend "${id}" has an invalid baseURL: ${invalid}`, "WEB_PROVIDER_ERROR");
331
442
  }
332
443
  }
333
444
  const controller = new AbortController();
@@ -337,14 +448,22 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
337
448
  const effectiveTimeoutMs = effectiveBackendTimeoutMs(id, backendTimeoutMs);
338
449
  const timeoutId = setTimeout(() => controller.abort(), effectiveTimeoutMs);
339
450
  return backend
340
- .search(variantReq, mergedSignal, beOpts, hooks)
451
+ // SearXNG's multi-instance split needs the effective budget to
452
+ // divide it across candidates; without it the backend saw an
453
+ // undefined budget and every instance got its own 4.5s.
454
+ .search(variantReq, mergedSignal, { ...beOpts, backendTimeoutMs: effectiveTimeoutMs }, hooks)
341
455
  .then(
342
456
  (value) => {
343
457
  telemetry.push({ id, ok: true, ms: Date.now() - startedAtMs, count: value?.sources?.length ?? 0 });
344
- recordBackendHealth(id, { ok: true, at: Date.now(), ms: Date.now() - startedAtMs, count: value?.sources?.length ?? 0 }, breakerCfg);
458
+ health.push({ id, ok: true, at: Date.now(), ms: Date.now() - startedAtMs, count: value?.sources?.length ?? 0 });
345
459
  return value;
346
460
  },
347
461
  (err) => {
462
+ // A caller cancellation is not a backend outage: recording it
463
+ // as a failure would let the stop button trip the breaker and
464
+ // paint /health red. The outer throwIfSearchAborted(signal)
465
+ // still propagates the cancellation to the caller.
466
+ if (signal?.aborted === true) throw err;
348
467
  // Timeout classification happens BEFORE telemetry/health are
349
468
  // recorded (route6 P6): backends surface an internal timeout
350
469
  // as their own abort-flavored error ("unified search aborted",
@@ -356,9 +475,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
356
475
  const reason = timedOut
357
476
  ? `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
358
477
  : String(err instanceof Error ? err.message : err);
359
- const msg = reason.slice(0, 80);
478
+ const msg = sanitizeError(reason, 80);
360
479
  telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
361
- recordBackendHealth(id, { ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg }, breakerCfg);
480
+ health.push({
481
+ id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
482
+ rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
483
+ });
362
484
  throw timedOut
363
485
  ? new WebError(reason, "WEB_PROVIDER_ERROR", { cause: err instanceof Error ? err : undefined })
364
486
  : err;
@@ -378,7 +500,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
378
500
  );
379
501
  throwIfSearchAborted(signal);
380
502
  const fold = collectFanoutResults(results, eligible, signal);
381
- return { ...fold, telemetry };
503
+ return { ...fold, telemetry, health };
382
504
  };
383
505
 
384
506
  // Fan out per variant (sequential — the limiter already parallelizes
@@ -387,6 +509,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
387
509
  const allTelemetry = [];
388
510
  const allFailures = [];
389
511
  let hardError = null;
512
+ // Final outcome per backend across every variant. Success wins; otherwise
513
+ // keep the latest failure and the most severe quota classification.
514
+ const searchHealth = new Map();
390
515
  for (const variantQuery of variants) {
391
516
  const variantReq = {
392
517
  ...effReq,
@@ -395,6 +520,19 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
395
520
  ...(coverage ? { deepCoverage: true } : {}),
396
521
  };
397
522
  const fold = await fanoutVariant(variantReq);
523
+ for (const outcome of fold.health) {
524
+ const prev = searchHealth.get(outcome.id);
525
+ if (prev === undefined || outcome.ok === true) {
526
+ searchHealth.set(outcome.id, { ...outcome });
527
+ } else if (prev.ok !== true) {
528
+ searchHealth.set(outcome.id, {
529
+ ...outcome,
530
+ rateLimited: prev.rateLimited === true || outcome.rateLimited === true,
531
+ keylessRejected: prev.keylessRejected === true || outcome.keylessRejected === true,
532
+ retryAfterMs: Math.max(prev.retryAfterMs ?? 0, outcome.retryAfterMs ?? 0) || undefined,
533
+ });
534
+ }
535
+ }
398
536
  allTelemetry.push(...fold.telemetry);
399
537
  allFailures.push(...fold.failures);
400
538
  if (fold.hardError !== null && hardError === null) hardError = fold.hardError;
@@ -409,24 +547,53 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
409
547
  perVariant.push({ query: variantQuery, ordered, mergedContent: fold.mergedContent });
410
548
  }
411
549
 
550
+ // Fold the breaker once per backend per search. `null` (breaker off) is
551
+ // honoured by recordBackendHealth and never publishes a cooldown.
552
+ for (const [id, outcome] of searchHealth) {
553
+ recordBackendHealth(
554
+ id,
555
+ { ok: outcome.ok, at: outcome.at, ms: outcome.ms, count: outcome.count, error: outcome.error },
556
+ breakerCfg,
557
+ {
558
+ rateLimited: outcome.rateLimited === true,
559
+ keylessRejected: outcome.keylessRejected === true,
560
+ retryAfterMs: outcome.retryAfterMs,
561
+ },
562
+ );
563
+ }
564
+
565
+ // Counted once: every history record below needs it, and the fan-out is
566
+ // finished by this point so the array no longer grows. History counts
567
+ // unique backends, not attempts: multi-query fans one backend out once
568
+ // per variant, which used to report `backendsTotal` as variants × backends.
569
+ const okCount = allTelemetry.filter((t) => t.ok).length;
570
+ const historyOk = new Set(allTelemetry.filter((t) => t.ok).map((t) => t.id)).size;
571
+ const historyTotal = new Set(allTelemetry.map((t) => t.id)).size;
572
+
412
573
  // PHASE 4 fuse: multi-query mode fuses the per-variant ranked lists with
413
574
  // RRF (k=60); single-query mode keeps the historical behavior (the one
414
575
  // list, unchanged ordering).
415
- const orderedLists = perVariant.filter((v) => v.ordered.length > 0).map((v) => v.ordered);
416
- const ordered = multi
417
- ? rrfFuse(orderedLists).fused
418
- : (orderedLists[0] ?? []);
576
+ // The original query keeps full weight and derived variants contribute
577
+ // at half weight: presence in several narrow variants must not outrank a
578
+ // page that answers the user's actual query (RRF is rank-only, so a
579
+ // homepage repeated across sub-queries otherwise wins).
580
+ const orderedVariants = perVariant.filter((v) => v.ordered.length > 0);
581
+ const ordered = useMulti
582
+ ? rrfFuse(orderedVariants.map((v) => v.ordered), {
583
+ weights: orderedVariants.map((v) => (v.query === effReq.query ? 2 : 1)),
584
+ }).fused
585
+ : (orderedVariants[0]?.ordered ?? []);
419
586
 
420
587
  // If we got ANY sources, return them even if some backends failed.
421
588
  if (ordered.length > 0) {
422
589
  const sources = ordered.slice(0, maxResults);
423
590
  // 结果呈现头(Anthropic web-search / OpenAI grounding 官方指引):
424
591
  // 置于结果块最前,要求逐条引用来源 URL、优先官方/一手与较新来源;
425
- // 语言按查询文本自动选择(含 CJK 用中文头)。可用
426
- // opts.resultHeader === false 关闭。
592
+ // The result header is always prepended; the language follows the
593
+ // query text (CJK selects the Chinese header).
427
594
  let outContent = perVariant.find((v) => v.mergedContent !== undefined)?.mergedContent;
428
595
  if (opts.resultHeader !== false && (sources.length > 0 || outContent !== undefined)) {
429
- const header = resultHeader(typeof request?.query === "string" && /[\u4e00-\u9fff]/.test(request.query) ? "zh" : "en");
596
+ const header = resultHeader(queryLanguage);
430
597
  outContent = outContent === undefined ? header : header + "\n\n" + outContent;
431
598
  }
432
599
  // Store the pre-telemetry core (sources + headered content) so a cache
@@ -434,18 +601,22 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
434
601
  if (cacheKey && cache) {
435
602
  cache.set(cacheKey, { sources, content: outContent, truncated: ordered.length > maxResults });
436
603
  }
437
- history?.record({
438
- query: request?.query,
439
- time: Date.now(),
440
- resultCount: sources.length,
441
- backendsOk: allTelemetry.filter((t) => t.ok).length,
442
- backendsTotal: allTelemetry.length,
443
- });
604
+ recordHistory(history, request?.query, sources.length, historyOk, historyTotal);
444
605
  if (opts.resultTelemetry !== false && (allTelemetry.length > 0 || cooled.size > 0)) {
606
+ // Only backends that actually never ran get a cooldown note here.
607
+ // fail-open puts non-quota cooled backends back into the fan-out, so
608
+ // their failures already appear above; annotating them again would
609
+ // print the same backend twice on one line.
610
+ const ranIds = new Set(allTelemetry.map((t) => t.id));
445
611
  const cooledParts = [];
446
612
  for (const [cid, centry] of cooled) {
447
- const ann = cooledAnnotation(centry, Date.now()) || "⏸cooled";
448
- cooledParts.push(cid + " " + ann);
613
+ if (ranIds.has(cid)) continue;
614
+ // The note is anchored to fan-out time (the instant the cooldown
615
+ // decision was made). If the window expires while a slow search is
616
+ // still running, say so instead of claiming the backend is cooling.
617
+ const ann = cooledAnnotation(centry, nowMs);
618
+ if (ann) cooledParts.push(cid + " " + ann
619
+ + (isCooled(centry, Date.now()) ? "" : " (expired during search)"));
449
620
  }
450
621
  // Multi-query fans every variant through every backend; cap the line
451
622
  // so the telemetry note cannot dwarf the results themselves.
@@ -477,20 +648,31 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
477
648
  // 过滤后为空)时,原实现无条件落入下面的 throw,模型端拿到
478
649
  // `all enabled backends failed (0) - `(detail 空、计数自相矛盾),且丢弃已
479
650
  // 拿到的 mergedContent(如 Tavily 直答)。成功即空 → 正常返回空结果。
480
- if (allFailures.length === 0) {
651
+ // `allFailures.length === 0` is not the only success shape: with three
652
+ // enabled backends, one may fail while two succeed and return zero hits
653
+ // (filtered-out/obscure query). The old guard then threw "all enabled
654
+ // backends failed (1)" although two thirds of the fan-out succeeded.
655
+ // A success is a success even when the merged list is empty.
656
+ if (allFailures.length === 0 || okCount > 0) {
481
657
  let emptyContent = perVariant.find((v) => v.mergedContent !== undefined)?.mergedContent;
482
658
  if (opts.resultHeader !== false && emptyContent !== undefined) {
483
659
  const header = resultHeader(typeof request?.query === "string" && /[\u4e00-\u9fff]/.test(request.query) ? "zh" : "en");
484
660
  emptyContent = header + "\n\n" + emptyContent;
485
661
  }
486
- history?.record({
487
- query: request?.query,
488
- time: Date.now(),
489
- resultCount: 0,
490
- backendsOk: allTelemetry.filter((t) => t.ok).length,
491
- backendsTotal: allTelemetry.length,
492
- });
493
- if (cacheKey && cache) cache.set(cacheKey, { sources: [], content: emptyContent, truncated: false });
662
+ if (opts.resultTelemetry !== false && allFailures.length > 0) {
663
+ const parts = allTelemetry.slice(0, 12).map((t) => {
664
+ if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
665
+ const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
666
+ return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "");
667
+ });
668
+ if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
669
+ const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
670
+ emptyContent = emptyContent === undefined ? line : emptyContent + "\n\n" + line;
671
+ }
672
+ recordHistory(history, request?.query, 0, historyOk, historyTotal);
673
+ // An empty result is never served from the cache (the read path
674
+ // requires a non-empty sources array), so writing it only pays for a
675
+ // full eviction scan and can push real entries out.
494
676
  return {
495
677
  sources: [],
496
678
  ...(emptyContent !== undefined ? { content: emptyContent } : {}),
@@ -500,11 +682,14 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
500
682
 
501
683
  // All attempted backends failed - synthesize one meaningful error that
502
684
  // names each backend's own reason so the caller (model or user) can act.
685
+ // A total outage must be visible in history: otherwise the newest entry
686
+ // still shows the last success while health already records failures,
687
+ // making failure-rate/availability statistics silently omit outages.
503
688
  // Reasons beyond MAX_FAILURE_DETAILS collapse into "+N more"; backends
504
689
  // that never ran (breaker cooldown) are named explicitly — without the
505
- // note "(N)" reads as "N enabled" when it means "N attempted" (route6).
690
+ // note "(N)" reads as "N enabled" when it means "N attempted".
506
691
  const detail = allFailures.slice(0, MAX_FAILURE_DETAILS)
507
- .map((f) => f.id + ": " + String(f.err instanceof Error ? f.err.message : f.err).slice(0, 120))
692
+ .map((f) => f.id + ": " + sanitizeError(f.err instanceof Error ? f.err.message : f.err, 120))
508
693
  .join("; ") + (allFailures.length > MAX_FAILURE_DETAILS ? `; +${allFailures.length - MAX_FAILURE_DETAILS} more` : "");
509
694
  const allKeyMissing =
510
695
  allFailures.length > 0 &&
@@ -512,8 +697,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
512
697
  const hint = allKeyMissing
513
698
  ? " (every enabled backend is missing its API key - add keys in Settings > Web Search, or enable a keyless backend)"
514
699
  : "";
515
- const cooledNote = cooled.size > 0
516
- ? " (cooled-skipped: " + [...cooled].map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, Date.now()) || "⏸cooled")).join(", ") + ")"
700
+ // A total outage must be visible in history: otherwise the newest entry
701
+ // still shows the last success while health already records failures,
702
+ // making failure-rate/availability statistics silently omit outages.
703
+ recordHistory(history, request?.query, 0, historyOk, historyTotal);
704
+ // Anchor the note to the fan-out instant: recomputing at render time would
705
+ // claim "expired" for a backend that was genuinely cooling when skipped.
706
+ // fail-open re-runs non-quota cooled backends, so only those that were
707
+ // genuinely skipped belong in this note; naming a backend that just ran
708
+ // reads as "skipped" and "failed" in the same sentence.
709
+ const skippedOnly = [...cooled].filter(([cid]) => !allTelemetry.some((t) => t.id === cid));
710
+ const cooledNote = skippedOnly.length > 0
711
+ ? " (cooled-skipped: " + skippedOnly.map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, nowMs) || "⏸cooled")).join(", ") + ")"
517
712
  : "";
518
713
  throw new WebError(
519
714
  `unified search: all enabled backends failed (${allFailures.length}) - ${detail}` + cooledNote + hint,
package/lib/rrf.js CHANGED
@@ -24,24 +24,29 @@ function itemKey(item) {
24
24
  * Fuse ranked lists of search sources with Reciprocal Rank Fusion.
25
25
  *
26
26
  * @param {Array<Array<object>>} lists each list is already ranked best-first
27
- * @param {{k?: number}} [opts] k constant (default 60)
27
+ * @param {{k?: number, weights?: number[]}} [opts] k constant (default 60);
28
+ * optional per-list weights (the original query can outweigh derived variants)
28
29
  * @returns {{ fused: object[], scores: Map<string, number> }}
29
30
  * fused: sources sorted by accumulated RRF score desc (ties keep first
30
31
  * appearance order); sources without a usable key are dropped.
31
32
  */
32
- export function rrfFuse(lists, { k = RRF_K } = {}) {
33
+ export function rrfFuse(lists, { k = RRF_K, weights } = {}) {
33
34
  const kk = Number(k) > 0 ? Number(k) : RRF_K;
34
35
  const scores = new Map(); // key -> accumulated score
35
36
  const firstSeen = new Map(); // key -> source object (first metadata wins)
36
37
  const order = []; // keys in first-appearance order (stable ties)
37
38
 
38
- for (const list of Array.isArray(lists) ? lists : []) {
39
+ const allLists = Array.isArray(lists) ? lists : [];
40
+ for (let index = 0; index < allLists.length; index++) {
41
+ const list = allLists[index];
39
42
  if (!Array.isArray(list)) continue;
43
+ const weight = Number(weights?.[index]);
44
+ const w = Number.isFinite(weight) && weight > 0 ? weight : 1;
40
45
  for (let rank = 0; rank < list.length; rank++) {
41
46
  const item = list[rank];
42
47
  const key = itemKey(item);
43
48
  if (!key) continue;
44
- scores.set(key, (scores.get(key) ?? 0) + 1 / (kk + rank));
49
+ scores.set(key, (scores.get(key) ?? 0) + w / (kk + rank));
45
50
  if (!firstSeen.has(key)) {
46
51
  firstSeen.set(key, item);
47
52
  order.push(key);