@240xu/dsh-websearch 2.8.8 → 2.9.0

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())——后者先执行
@@ -131,7 +155,7 @@ export function createLimiter(concurrency) {
131
155
  * compromised or poisoned backends never reach model/GUI consumers.
132
156
  */
133
157
  function collectFanoutResults(results, eligible, signal) {
134
- const collected = [];
158
+ const perBackend = [];
135
159
  let mergedContent;
136
160
  let hardAborted = false;
137
161
  let hardError = null;
@@ -145,11 +169,15 @@ function collectFanoutResults(results, eligible, signal) {
145
169
  if (mergedContent === undefined && typeof settled.value?.content === "string" && settled.value.content.length > 0) {
146
170
  mergedContent = settled.value.content;
147
171
  }
148
- for (const src of settled.value?.sources ?? []) {
149
- if (src && typeof src.url === "string" && /^https?:\/\//i.test(src.url)) collected.push(src);
172
+ const list = Array.isArray(settled.value?.sources) ? settled.value.sources : [];
173
+ const safe = [];
174
+ for (const src of list) {
175
+ if (src && typeof src.url === "string" && /^https?:\/\//i.test(src.url)) safe.push(src);
150
176
  }
177
+ perBackend.push(safe);
151
178
  } else {
152
179
  const err = settled.reason;
180
+ perBackend.push([]);
153
181
  if (err instanceof WebError && err.code === "WEB_ABORTED") {
154
182
  // Per-backend abort -> soft unless the caller signal fired.
155
183
  if (signal?.aborted === true) hardAborted = true;
@@ -160,6 +188,16 @@ function collectFanoutResults(results, eligible, signal) {
160
188
  }
161
189
  }
162
190
  }
191
+ // Rank-major round-robin: every backend's #1 precedes any backend's #2.
192
+ // Concatenating whole lists let the first two backends fill the cap and
193
+ // starve the rest; this mirrors dsh-tool-web's mergeSearchResults.
194
+ const collected = [];
195
+ const longest = perBackend.reduce((n, list) => Math.max(n, list.length), 0);
196
+ for (let rank = 0; rank < longest; rank += 1) {
197
+ for (const list of perBackend) {
198
+ if (list[rank] !== undefined) collected.push(list[rank]);
199
+ }
200
+ }
163
201
  return { collected, mergedContent, hardAborted, hardError, failures };
164
202
  }
165
203
 
@@ -202,22 +240,44 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
202
240
  ...(opts.filters ?? {}),
203
241
  ...(request?.filters ?? {}),
204
242
  });
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
- );
243
+ // The host sends its deployment cap as request.maxResults; the card's
244
+ // numResults is the user's requested count. Neither alone is right:
245
+ // cap wins when smaller (never exceed the deployment limit), the user
246
+ // value wins when smaller (settings must actually take effect).
247
+ const hostCap = Number(request?.maxResults);
248
+ const userMax = opts.numResults === undefined || opts.numResults === null
249
+ ? Number.POSITIVE_INFINITY
250
+ : Number(opts.numResults);
251
+ // `official` leaves the count to the consumer (the tool always sends
252
+ // maxResults); every other tier keeps the user's explicit count as an
253
+ // upper bound, but never exceeds the host cap.
254
+ const finiteCaps = [hostCap, userMax].filter((n) => Number.isFinite(n) && n > 0);
255
+ const boundedMax = finiteCaps.length > 0 ? Math.max(1, Math.min(...finiteCaps)) : 10;
256
+ let effReq = { ...request, maxResults: boundedMax };
257
+ // `official` passes the model's exact query: the official consumer owns
258
+ // query construction, and provider-level rewriting can change a quoted
259
+ // phrase or a product name. `balanced`/`thorough` strip only
260
+ // conversational prefixes (see prompting.js).
261
+ if (opts.queryShaping !== false) {
262
+ effReq.query = shapeQuery(effReq.query);
263
+ // 2.8.2(P2):整形后为空("搜索"/"search" 等寒暄独词被剥光)→ 早拒。
264
+ // 不拒会:①空串扇出全部后端 ②不同原始查询共享 "" 缓存键(别名污染)
265
+ // ③落入 all-backends-failed(0) 的误导错误。
266
+ if (!effReq.query) {
267
+ throw new WebError(
268
+ "unified search: empty query after shaping (the request contained only fillers like \"search\")",
269
+ "WEB_PROVIDER_ERROR",
270
+ );
271
+ }
272
+ } else if (typeof effReq.query !== "string" || effReq.query.trim() === "") {
273
+ throw new WebError("unified search: empty query", "WEB_PROVIDER_ERROR");
218
274
  }
219
275
  if (Object.keys(filters).length > 0) effReq = { ...effReq, filters };
220
276
  const maxResults = effReq.maxResults;
277
+ // `truncated` means the SEAM dropped sources to honour request.maxResults
278
+ // (dsh-web/src/types.ts); a provider-side cut to the user's numResults is
279
+ // a preference, not seam truncation.
280
+ const seamBound = Number.isFinite(hostCap) && hostCap > 0 ? hostCap : Number.POSITIVE_INFINITY;
221
281
  const concurrency = opts.concurrency ?? 6;
222
282
  const backendTimeoutMs = opts.backendTimeoutMs ?? 30000;
223
283
 
@@ -226,11 +286,20 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
226
286
  const coverage = opts.deepCoverage === true;
227
287
  // Per-backend widening: fetch more per backend, dedupe down afterwards.
228
288
  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];
289
+ const multiGate = opts.multiQueryEnabled === true && isComplexQuery(effReq.query);
290
+ const derived = multiGate ? deriveSubQueries(effReq.query) : [effReq.query];
291
+ // A gate-true query can still derive zero useful variants ("C vs Rust"
292
+ // drops the one-character "C"). Treat that as single-query instead of
293
+ // flipping cacheMode and paying for a duplicate cache entry.
294
+ const useMulti = derived.length > 1;
295
+ const variants = useMulti ? derived : [effReq.query];
296
+ // Result-presentation language also keys the cache: two raw queries can
297
+ // shape to the same string ("请搜索 cats" / "cats") while the header
298
+ // language follows the raw request.
299
+ const queryLanguage = /[\u4e00-\u9fff]/.test(String(request?.query ?? "")) ? "zh" : "en";
231
300
  // Cache-key mode marker: different coverage/multiQuery settings must not
232
301
  // serve each other's cached results.
233
- const cacheMode = (multi ? "multi" : "single") + (coverage ? "+coverage" : "");
302
+ const cacheMode = (useMulti ? "multi" : "single") + (coverage ? "+coverage" : "");
234
303
 
235
304
  // v2.7.0 disk cache: keyed on (shaped query + filters + maxResults +
236
305
  // backends + mode). A hit short-circuits the fan-out entirely; sources
@@ -239,7 +308,30 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
239
308
  const cacheEnabled = opts.cacheEnabled === true && cache;
240
309
  let cacheKey = null;
241
310
  if (cacheEnabled) {
242
- cacheKey = cacheKeyFor({ query: effReq.query, filters, maxResults, backends: opts.enabledBackends, mode: cacheMode });
311
+ // Result-affecting options belong in the key; otherwise a settings
312
+ // change is masked by a hit within the cache TTL.
313
+ const resultOptions = {};
314
+ for (const [k, v] of Object.entries(opts)) {
315
+ if (typeof v === "function") continue;
316
+ if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping)$/.test(k)
317
+ || /BaseURL$|^.*Model$|^.*ApiKeyEnv$|^enable[A-Z]/.test(k)) resultOptions[k] = v;
318
+ }
319
+ // resolveOptions() keeps per-backend settings under opts.backends[id],
320
+ // not as top-level opts keys. Flatten the result-affecting ones with
321
+ // an id prefix so editing a backend's baseURL/model/searchDepth does
322
+ // not get masked by a cache hit within the TTL (65 号 N2).
323
+ for (const id of opts.enabledBackends ?? []) {
324
+ const be = opts.backends?.[id];
325
+ if (!be || typeof be !== "object") continue;
326
+ // Every per-backend option that changes results must appear here, or
327
+ // a cache hit inside the TTL masks the edit. baseURLs (plural) is the
328
+ // SearXNG failover list; leaving it out made instance changes inert.
329
+ for (const k of ["baseURL", "baseURLs", "model", "searchDepth", "safeSearch", "apiKeyEnv"]) {
330
+ if (be[k] !== undefined) resultOptions[`${id}.${k}`] = be[k];
331
+ }
332
+ }
333
+ resultOptions.queryLanguage = queryLanguage;
334
+ cacheKey = cacheKeyFor({ query: effReq.query, filters, maxResults, backends: opts.enabledBackends, mode: cacheMode, resultOptions });
243
335
  const hit = cache.get(cacheKey);
244
336
  if (hit && Array.isArray(hit.value?.sources) && hit.value.sources.length > 0) {
245
337
  // Defense in depth: the fresh path drops non-http(s) schemes before
@@ -252,15 +344,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
252
344
  cacheKey = null;
253
345
  } else {
254
346
  let hitContent = typeof hit.value.content === "string" ? hit.value.content : undefined;
255
- const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
256
- 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
- });
347
+ // `official` promises no provider-added text (the consumer owns
348
+ // presentation), so the diagnostic cache note is gated with the
349
+ // header rather than appended unconditionally.
350
+ if (opts.resultHeader !== false) {
351
+ const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
352
+ hitContent = hitContent === undefined ? cacheNote : hitContent + "\n\n" + cacheNote;
353
+ }
354
+ // Replay the fan-out's own counters instead of fabricating 1/1: a
355
+ // cache hit for a four-backend search used to report one backend.
356
+ const hitOk = Number.isInteger(hit.value.backendsOk) ? hit.value.backendsOk : 1;
357
+ const hitTotal = Number.isInteger(hit.value.backendsTotal) ? hit.value.backendsTotal : 1;
358
+ recordHistory(history, request?.query, hit.value.sources.length, hitOk, hitTotal);
264
359
  return {
265
360
  sources: safeSources,
266
361
  ...(hitContent !== undefined ? { content: hitContent } : {}),
@@ -290,20 +385,62 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
290
385
  candidates.push({ id, backend: be, beOpts });
291
386
  }
292
387
  const cooled = new Map();
388
+ const rateLimitedCooled = new Map();
293
389
  let eligible = candidates;
294
390
  if (breakerCfg) {
295
391
  const active = candidates.filter((c) => {
296
- if (isCooled(latestBackendHealth.get(c.id), nowMs)) {
297
- cooled.set(c.id, latestBackendHealth.get(c.id));
392
+ const entry = latestBackendHealth.get(c.id);
393
+ if (isCooled(entry, nowMs)) {
394
+ cooled.set(c.id, entry);
395
+ if (entry?.rateLimited === true) rateLimitedCooled.set(c.id, entry);
298
396
  return false;
299
397
  }
300
398
  return true;
301
399
  });
302
- if (active.length > 0) eligible = active;
303
- else cooled.clear(); // all cooled -> fail-open
400
+ // A rate-limited/quota backend must never be re-hit while its cooldown
401
+ // is open, even in a mixed outage. Only the non-quota cooled backends
402
+ // keep the historical fail-open behaviour; when nothing usable remains
403
+ // and at least one cooldown is quota-driven, fail fast with a retry hint.
404
+ // A backend in a non-quota cooldown stays out of the fan-out while any
405
+ // healthy backend remains: retrying it every search made the breaker
406
+ // inert (three failures in a row never actually stopped the calls).
407
+ // Only when EVERYTHING is cooling do we fail open — refusing to search
408
+ // at all is worse than re-hitting a backend that might have recovered.
409
+ const cooledReusable = [...cooled.entries()]
410
+ .filter(([, e]) => e?.rateLimited !== true)
411
+ .map(([id]) => candidates.find((c) => c.id === id))
412
+ .filter(Boolean);
413
+ const failOpen = active.length > 0 ? active : cooledReusable;
414
+ if (failOpen.length > 0) eligible = failOpen;
415
+ else if (rateLimitedCooled.size > 0) {
416
+ const until = Math.max(...[...rateLimitedCooled.values()].map((e) => e?.cooledUntil ?? 0));
417
+ const waitS = Math.max(0, Math.ceil((until - nowMs) / 1000));
418
+ // Distinguish a real quota/rate-limit cooldown from a keyless
419
+ // permission refusal: retrying the latter after N seconds cannot
420
+ // succeed without configuring a key.
421
+ const keyless = [...rateLimitedCooled.values()].some((e) => e?.keylessRejected === true);
422
+ recordHistory(history, request?.query, 0, 0, candidates.length);
423
+ if (keyless) {
424
+ throw new WebError(
425
+ "unified search: all backends need an API key (keyless access is unavailable); add a key or enable another backend",
426
+ "WEB_PROVIDER_ERROR",
427
+ );
428
+ }
429
+ recordHistory(history, request?.query, 0, 0, candidates.length);
430
+ throw new WebError(
431
+ `unified search: all backends are rate-limited; retry after ~${waitS}s`,
432
+ "WEB_PROVIDER_ERROR",
433
+ );
434
+ } else {
435
+ // Pure non-quota outage: keep fail-open so a breaker can never make
436
+ // search worse than no breaker.
437
+ eligible = candidates;
438
+ cooled.clear();
439
+ }
304
440
  }
305
441
 
306
442
  if (eligible.length === 0) {
443
+ recordHistory(history, request?.query, 0, 0, candidates.length);
307
444
  throw new WebError(
308
445
  "unified search: no enabled backend is available (configure a backend or set an API key)",
309
446
  "WEB_PROVIDER_UNAVAILABLE",
@@ -313,8 +450,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
313
450
  // Run ONE query variant through the full fan-out: breaker-aware backend
314
451
  // execution under the per-variant limiter, then PHASE 1 collect. The
315
452
  // internal abort/timeout semantics are unchanged from v2.7.
316
- const fanoutVariant = async (variantReq) => {
453
+ const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY) => {
317
454
  const telemetry = [];
455
+ // Health is folded once per backend per SEARCH, after every variant
456
+ // finished: recording per variant let one multi-query search trip the
457
+ // 3-failure breaker (and inflate history counters) by itself.
458
+ const health = [];
318
459
  const limit = createLimiter(concurrency);
319
460
  const runBackend = ({ id, backend, beOpts, hooks }) => {
320
461
  const startedAtMs = Date.now();
@@ -322,29 +463,61 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
322
463
  // Enforce http(s); plain http only for private hosts (self-hosted SearXNG).
323
464
  // Reject embedded credentials. Failure is a per-backend soft error.
324
465
  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");
466
+ const invalid = invalidBaseURL(beOpts.baseURL);
467
+ if (invalid !== undefined) {
468
+ throw new WebError(`backend "${id}" has an invalid baseURL: ${invalid}`, "WEB_PROVIDER_ERROR");
331
469
  }
332
470
  }
333
471
  const controller = new AbortController();
334
472
  const mergedSignal = signal
335
473
  ? AbortSignal.any([signal, controller.signal])
336
474
  : controller.signal;
337
- const effectiveTimeoutMs = effectiveBackendTimeoutMs(id, backendTimeoutMs);
475
+ const effectiveTimeoutMs = Math.max(1, Math.min(effectiveBackendTimeoutMs(id, backendTimeoutMs), variantBudgetMs));
338
476
  const timeoutId = setTimeout(() => controller.abort(), effectiveTimeoutMs);
339
- return backend
340
- .search(variantReq, mergedSignal, beOpts, hooks)
477
+ // A backend that ignores its signal (blackholed TCP, stuck proxy)
478
+ // must not hold the whole fan-out past its budget. Race the call
479
+ // against a guard that rejects on caller abort or timer abort; the
480
+ // loser keeps running in the background, as before.
481
+ let guardCleanup = () => {};
482
+ const guard = new Promise((_, reject) => {
483
+ if (signal?.aborted === true) {
484
+ reject(searchAborted(signal));
485
+ return;
486
+ }
487
+ const onCaller = () => reject(searchAborted(signal));
488
+ const onTimeout = () => reject(new DOMException("backend timed out", "AbortError"));
489
+ signal?.addEventListener("abort", onCaller, { once: true });
490
+ controller.signal.addEventListener("abort", onTimeout, { once: true });
491
+ guardCleanup = () => {
492
+ signal?.removeEventListener("abort", onCaller);
493
+ controller.signal.removeEventListener("abort", onTimeout);
494
+ };
495
+ });
496
+ return Promise.race([
497
+ // SearXNG's multi-instance split needs the effective budget to
498
+ // divide it across candidates; without it the backend saw an
499
+ // undefined budget and every instance got its own 4.5s.
500
+ backend.search(variantReq, mergedSignal, { ...beOpts, backendTimeoutMs: effectiveTimeoutMs }, hooks),
501
+ guard,
502
+ ])
341
503
  .then(
342
504
  (value) => {
343
- 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);
505
+ // A backend that resolves without a sources[] array is a
506
+ // contract violation, not a successful zero-hit search; route
507
+ // it through the failure path so telemetry/health agree.
508
+ if (value === null || typeof value !== "object" || !Array.isArray(value.sources)) {
509
+ throw new WebError(`backend "${id}" returned no sources[]`, "WEB_PROVIDER_ERROR");
510
+ }
511
+ telemetry.push({ id, ok: true, ms: Date.now() - startedAtMs, count: value.sources.length });
512
+ health.push({ id, ok: true, at: Date.now(), ms: Date.now() - startedAtMs, count: value?.sources?.length ?? 0 });
345
513
  return value;
346
514
  },
347
515
  (err) => {
516
+ // A caller cancellation is not a backend outage: recording it
517
+ // as a failure would let the stop button trip the breaker and
518
+ // paint /health red. The outer throwIfSearchAborted(signal)
519
+ // still propagates the cancellation to the caller.
520
+ if (signal?.aborted === true) throw err;
348
521
  // Timeout classification happens BEFORE telemetry/health are
349
522
  // recorded (route6 P6): backends surface an internal timeout
350
523
  // as their own abort-flavored error ("unified search aborted",
@@ -356,15 +529,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
356
529
  const reason = timedOut
357
530
  ? `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
358
531
  : String(err instanceof Error ? err.message : err);
359
- const msg = reason.slice(0, 80);
532
+ const msg = sanitizeError(reason, 80);
360
533
  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);
534
+ health.push({
535
+ id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
536
+ rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
537
+ });
362
538
  throw timedOut
363
539
  ? new WebError(reason, "WEB_PROVIDER_ERROR", { cause: err instanceof Error ? err : undefined })
364
540
  : err;
365
541
  },
366
542
  )
367
- .finally(() => clearTimeout(timeoutId));
543
+ .finally(() => { clearTimeout(timeoutId); guardCleanup(); });
368
544
  };
369
545
 
370
546
  const results = await Promise.allSettled(
@@ -378,7 +554,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
378
554
  );
379
555
  throwIfSearchAborted(signal);
380
556
  const fold = collectFanoutResults(results, eligible, signal);
381
- return { ...fold, telemetry };
557
+ return { ...fold, telemetry, health };
382
558
  };
383
559
 
384
560
  // Fan out per variant (sequential — the limiter already parallelizes
@@ -386,15 +562,38 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
386
562
  const perVariant = [];
387
563
  const allTelemetry = [];
388
564
  const allFailures = [];
565
+ // One search-wide budget: sequential variants must not multiply the
566
+ // per-backend timeout into N × 30s (which also exceeds the host's 30s
567
+ // tool deadline). Later variants get only the time still left.
568
+ const searchBudgetMs = Math.max(1, Number(opts.backendTimeoutMs) || 30000);
569
+ const searchDeadline = Date.now() + searchBudgetMs;
389
570
  let hardError = null;
571
+ // Final outcome per backend across every variant. Success wins; otherwise
572
+ // keep the latest failure and the most severe quota classification.
573
+ const searchHealth = new Map();
390
574
  for (const variantQuery of variants) {
575
+ const remaining = searchDeadline - Date.now();
576
+ if (remaining <= 0) break;
391
577
  const variantReq = {
392
578
  ...effReq,
393
579
  query: variantQuery,
394
580
  maxResults: backendMaxResults,
395
581
  ...(coverage ? { deepCoverage: true } : {}),
396
582
  };
397
- const fold = await fanoutVariant(variantReq);
583
+ const fold = await fanoutVariant(variantReq, remaining);
584
+ for (const outcome of fold.health) {
585
+ const prev = searchHealth.get(outcome.id);
586
+ if (prev === undefined || outcome.ok === true) {
587
+ searchHealth.set(outcome.id, { ...outcome });
588
+ } else if (prev.ok !== true) {
589
+ searchHealth.set(outcome.id, {
590
+ ...outcome,
591
+ rateLimited: prev.rateLimited === true || outcome.rateLimited === true,
592
+ keylessRejected: prev.keylessRejected === true || outcome.keylessRejected === true,
593
+ retryAfterMs: Math.max(prev.retryAfterMs ?? 0, outcome.retryAfterMs ?? 0) || undefined,
594
+ });
595
+ }
596
+ }
398
597
  allTelemetry.push(...fold.telemetry);
399
598
  allFailures.push(...fold.failures);
400
599
  if (fold.hardError !== null && hardError === null) hardError = fold.hardError;
@@ -409,43 +608,80 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
409
608
  perVariant.push({ query: variantQuery, ordered, mergedContent: fold.mergedContent });
410
609
  }
411
610
 
611
+ // Fold the breaker once per backend per search. `null` (breaker off) is
612
+ // honoured by recordBackendHealth and never publishes a cooldown.
613
+ for (const [id, outcome] of searchHealth) {
614
+ recordBackendHealth(
615
+ id,
616
+ { ok: outcome.ok, at: outcome.at, ms: outcome.ms, count: outcome.count, error: outcome.error },
617
+ breakerCfg,
618
+ {
619
+ rateLimited: outcome.rateLimited === true,
620
+ keylessRejected: outcome.keylessRejected === true,
621
+ retryAfterMs: outcome.retryAfterMs,
622
+ },
623
+ );
624
+ }
625
+
626
+ // Counted once: every history record below needs it, and the fan-out is
627
+ // finished by this point so the array no longer grows. History counts
628
+ // unique backends, not attempts: multi-query fans one backend out once
629
+ // per variant, which used to report `backendsTotal` as variants × backends.
630
+ const okCount = allTelemetry.filter((t) => t.ok).length;
631
+ const historyOk = new Set(allTelemetry.filter((t) => t.ok).map((t) => t.id)).size;
632
+ const historyTotal = new Set(allTelemetry.map((t) => t.id)).size;
633
+
412
634
  // PHASE 4 fuse: multi-query mode fuses the per-variant ranked lists with
413
635
  // RRF (k=60); single-query mode keeps the historical behavior (the one
414
636
  // 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] ?? []);
637
+ // The original query keeps full weight and derived variants contribute
638
+ // at half weight: presence in several narrow variants must not outrank a
639
+ // page that answers the user's actual query (RRF is rank-only, so a
640
+ // homepage repeated across sub-queries otherwise wins).
641
+ const orderedVariants = perVariant.filter((v) => v.ordered.length > 0);
642
+ const ordered = useMulti
643
+ ? rrfFuse(orderedVariants.map((v) => v.ordered), {
644
+ weights: orderedVariants.map((v) => (v.query === effReq.query ? 2 : 1)),
645
+ }).fused
646
+ : (orderedVariants[0]?.ordered ?? []);
419
647
 
420
648
  // If we got ANY sources, return them even if some backends failed.
421
649
  if (ordered.length > 0) {
422
650
  const sources = ordered.slice(0, maxResults);
423
651
  // 结果呈现头(Anthropic web-search / OpenAI grounding 官方指引):
424
652
  // 置于结果块最前,要求逐条引用来源 URL、优先官方/一手与较新来源;
425
- // 语言按查询文本自动选择(含 CJK 用中文头)。可用
426
- // opts.resultHeader === false 关闭。
653
+ // The result header is always prepended; the language follows the
654
+ // query text (CJK selects the Chinese header).
427
655
  let outContent = perVariant.find((v) => v.mergedContent !== undefined)?.mergedContent;
428
656
  if (opts.resultHeader !== false && (sources.length > 0 || outContent !== undefined)) {
429
- const header = resultHeader(typeof request?.query === "string" && /[\u4e00-\u9fff]/.test(request.query) ? "zh" : "en");
657
+ const header = resultHeader(queryLanguage);
430
658
  outContent = outContent === undefined ? header : header + "\n\n" + outContent;
431
659
  }
432
660
  // Store the pre-telemetry core (sources + headered content) so a cache
433
661
  // hit reproduces the exact sources and the model-facing header.
434
662
  if (cacheKey && cache) {
435
- cache.set(cacheKey, { sources, content: outContent, truncated: ordered.length > maxResults });
663
+ cache.set(cacheKey, {
664
+ sources, content: outContent,
665
+ truncated: ordered.length > seamBound,
666
+ backendsOk: historyOk, backendsTotal: historyTotal,
667
+ });
436
668
  }
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
- });
669
+ recordHistory(history, request?.query, sources.length, historyOk, historyTotal);
444
670
  if (opts.resultTelemetry !== false && (allTelemetry.length > 0 || cooled.size > 0)) {
671
+ // Only backends that actually never ran get a cooldown note here.
672
+ // fail-open puts non-quota cooled backends back into the fan-out, so
673
+ // their failures already appear above; annotating them again would
674
+ // print the same backend twice on one line.
675
+ const ranIds = new Set(allTelemetry.map((t) => t.id));
445
676
  const cooledParts = [];
446
677
  for (const [cid, centry] of cooled) {
447
- const ann = cooledAnnotation(centry, Date.now()) || "⏸cooled";
448
- cooledParts.push(cid + " " + ann);
678
+ if (ranIds.has(cid)) continue;
679
+ // The note is anchored to fan-out time (the instant the cooldown
680
+ // decision was made). If the window expires while a slow search is
681
+ // still running, say so instead of claiming the backend is cooling.
682
+ const ann = cooledAnnotation(centry, nowMs);
683
+ if (ann) cooledParts.push(cid + " " + ann
684
+ + (isCooled(centry, Date.now()) ? "" : " (expired during search)"));
449
685
  }
450
686
  // Multi-query fans every variant through every backend; cap the line
451
687
  // so the telemetry note cannot dwarf the results themselves.
@@ -469,7 +705,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
469
705
  return {
470
706
  sources,
471
707
  ...(outContent !== undefined ? { content: outContent } : {}),
472
- truncated: ordered.length > maxResults,
708
+ truncated: ordered.length > seamBound,
473
709
  };
474
710
  }
475
711
 
@@ -477,20 +713,31 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
477
713
  // 过滤后为空)时,原实现无条件落入下面的 throw,模型端拿到
478
714
  // `all enabled backends failed (0) - `(detail 空、计数自相矛盾),且丢弃已
479
715
  // 拿到的 mergedContent(如 Tavily 直答)。成功即空 → 正常返回空结果。
480
- if (allFailures.length === 0) {
716
+ // `allFailures.length === 0` is not the only success shape: with three
717
+ // enabled backends, one may fail while two succeed and return zero hits
718
+ // (filtered-out/obscure query). The old guard then threw "all enabled
719
+ // backends failed (1)" although two thirds of the fan-out succeeded.
720
+ // A success is a success even when the merged list is empty.
721
+ if (allFailures.length === 0 || okCount > 0) {
481
722
  let emptyContent = perVariant.find((v) => v.mergedContent !== undefined)?.mergedContent;
482
723
  if (opts.resultHeader !== false && emptyContent !== undefined) {
483
724
  const header = resultHeader(typeof request?.query === "string" && /[\u4e00-\u9fff]/.test(request.query) ? "zh" : "en");
484
725
  emptyContent = header + "\n\n" + emptyContent;
485
726
  }
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 });
727
+ if (opts.resultTelemetry !== false && allFailures.length > 0) {
728
+ const parts = allTelemetry.slice(0, 12).map((t) => {
729
+ if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
730
+ const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
731
+ return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "");
732
+ });
733
+ if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
734
+ const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
735
+ emptyContent = emptyContent === undefined ? line : emptyContent + "\n\n" + line;
736
+ }
737
+ recordHistory(history, request?.query, 0, historyOk, historyTotal);
738
+ // An empty result is never served from the cache (the read path
739
+ // requires a non-empty sources array), so writing it only pays for a
740
+ // full eviction scan and can push real entries out.
494
741
  return {
495
742
  sources: [],
496
743
  ...(emptyContent !== undefined ? { content: emptyContent } : {}),
@@ -500,25 +747,45 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
500
747
 
501
748
  // All attempted backends failed - synthesize one meaningful error that
502
749
  // names each backend's own reason so the caller (model or user) can act.
750
+ // A total outage must be visible in history: otherwise the newest entry
751
+ // still shows the last success while health already records failures,
752
+ // making failure-rate/availability statistics silently omit outages.
503
753
  // Reasons beyond MAX_FAILURE_DETAILS collapse into "+N more"; backends
504
754
  // that never ran (breaker cooldown) are named explicitly — without the
505
- // note "(N)" reads as "N enabled" when it means "N attempted" (route6).
506
- 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))
508
- .join("; ") + (allFailures.length > MAX_FAILURE_DETAILS ? `; +${allFailures.length - MAX_FAILURE_DETAILS} more` : "");
755
+ // note "(N)" reads as "N enabled" when it means "N attempted".
756
+ // allFailures holds one entry per attempt (multi-query fans out once per
757
+ // variant); fold to one entry per backend before counting/reporting.
758
+ const uniqueFailures = [...new Map(allFailures.map((f) => [f.id, f])).values()];
759
+ const detail = uniqueFailures.slice(0, MAX_FAILURE_DETAILS)
760
+ .map((f) => f.id + ": " + sanitizeError(f.err instanceof Error ? f.err.message : f.err, 120))
761
+ .join("; ") + (uniqueFailures.length > MAX_FAILURE_DETAILS ? `; +${uniqueFailures.length - MAX_FAILURE_DETAILS} more` : "");
509
762
  const allKeyMissing =
510
- allFailures.length > 0 &&
511
- allFailures.every((f) => f.err instanceof WebError && (f.err.code === "WEB_PROVIDER_UNAVAILABLE" || f.err.code === "WEB_PROVIDER_CREDENTIAL_MISSING"));
763
+ uniqueFailures.length > 0 &&
764
+ uniqueFailures.every((f) => f.err instanceof WebError && f.err.code === "WEB_PROVIDER_CREDENTIAL_MISSING");
512
765
  const hint = allKeyMissing
513
766
  ? " (every enabled backend is missing its API key - add keys in Settings > Web Search, or enable a keyless backend)"
514
767
  : "";
515
- const cooledNote = cooled.size > 0
516
- ? " (cooled-skipped: " + [...cooled].map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, Date.now()) || "⏸cooled")).join(", ") + ")"
768
+ // A total outage must be visible in history: otherwise the newest entry
769
+ // still shows the last success while health already records failures,
770
+ // making failure-rate/availability statistics silently omit outages.
771
+ recordHistory(history, request?.query, 0, historyOk, historyTotal);
772
+ // Anchor the note to the fan-out instant: recomputing at render time would
773
+ // claim "expired" for a backend that was genuinely cooling when skipped.
774
+ // fail-open re-runs non-quota cooled backends, so only those that were
775
+ // genuinely skipped belong in this note; naming a backend that just ran
776
+ // reads as "skipped" and "failed" in the same sentence.
777
+ const skippedOnly = [...cooled].filter(([cid]) => !allTelemetry.some((t) => t.id === cid));
778
+ const cooledNote = skippedOnly.length > 0
779
+ ? " (cooled-skipped: " + skippedOnly.map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, nowMs) || "⏸cooled")).join(", ") + ")"
517
780
  : "";
518
781
  throw new WebError(
519
- `unified search: all enabled backends failed (${allFailures.length}) - ${detail}` + cooledNote + hint,
782
+ `unified search: all attempted backends failed (${uniqueFailures.length} of ${candidates.length} enabled) - ${detail}` + cooledNote + hint,
520
783
  "WEB_PROVIDER_ERROR",
521
- { cause: hardError ?? undefined },
784
+ {
785
+ // The cause message can embed an upstream body that echoes a key;
786
+ // redact it just like the top-level detail.
787
+ cause: hardError instanceof Error ? new Error(sanitizeError(hardError.message, 160)) : undefined,
788
+ },
522
789
  );
523
790
  },
524
791
  };