@240xu/dsh-websearch 2.11.0 → 2.12.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/README.md CHANGED
@@ -92,7 +92,7 @@ pnpm install
92
92
  > 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
93
93
 
94
94
 
95
- 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数(共 60 个配置字段);缓存、熔断、历史、多查询、域名过滤、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 Config 表单 / profile patch 配置:
95
+ 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 26 个开关/参数(共 60 个配置字段);缓存、熔断、历史、多查询、域名过滤、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 Config 表单 / profile patch 配置:
96
96
 
97
97
  **全局**
98
98
 
@@ -58,7 +58,7 @@ export function createAnthropicLikeBackend(spec) {
58
58
  const okKey = (typeof options?.apiKey === "string" && options.apiKey.length > 0)
59
59
  || typeof options?.resolveApiKey === "function";
60
60
  const urlOk = typeof options?.baseURL === "string" && URL.canParse(options.baseURL);
61
- return okKey && urlOk && options?.credentialPresent !== false;
61
+ return okKey && urlOk;
62
62
  },
63
63
 
64
64
  /**
@@ -20,7 +20,7 @@ export const braveBackend = {
20
20
  requiresCredential: true,
21
21
 
22
22
  available(options) {
23
- return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
23
+ return typeof options?.resolveApiKey === "function";
24
24
  },
25
25
 
26
26
  async search(request, signal, options, hooks) {
@@ -19,7 +19,7 @@ export const mojeekBackend = {
19
19
  requiresCredential: true,
20
20
 
21
21
  available(options) {
22
- return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
22
+ return typeof options?.resolveApiKey === "function";
23
23
  },
24
24
 
25
25
  async search(request, signal, options, hooks) {
@@ -29,7 +29,7 @@ export const openaiBackend = {
29
29
  const okKey = (typeof options?.apiKey === "string" && options.apiKey.length > 0)
30
30
  || typeof options?.resolveApiKey === "function";
31
31
  const urlOk = typeof options?.baseURL === "string" && URL.canParse(options.baseURL);
32
- return okKey && urlOk && options?.credentialPresent !== false;
32
+ return okKey && urlOk;
33
33
  },
34
34
 
35
35
  /**
@@ -27,6 +27,9 @@ const SESSION_ID = "dsh-websearch-" + randomUUID().slice(0, 8);
27
27
  export const parallelBackend = {
28
28
  id: "parallel",
29
29
  requiresCredential: false,
30
+ // The provider may hand all derived facets to one call on the primary
31
+ // variant; later variants then skip this backend.
32
+ handlesAllVariants: true,
30
33
 
31
34
  available() {
32
35
  return true; // keyless endpoint
@@ -35,7 +38,8 @@ export const parallelBackend = {
35
38
  async search(request, signal, options, hooks = {}) {
36
39
  const args = {
37
40
  objective: request.query,
38
- search_queries: [request.query],
41
+ objective: request.searchPlan?.objective ?? request.query,
42
+ search_queries: request.searchPlan?.queries?.slice(0, 3) ?? [request.query],
39
43
  session_id: SESSION_ID,
40
44
  model_name: "dsh-websearch",
41
45
  };
@@ -141,8 +141,8 @@ export const searxngBackend = {
141
141
  };
142
142
 
143
143
  /**
144
- * Query one instance, paginating only when the request asks for breadth
145
- * (deepCoverage or maxResults > 10). Page 1 is authoritative: if a later page
144
+ * Query one instance, paginating only when the provider sets pageLimit > 1
145
+ * (deepCoverage without internal multi-query). Page 1 is authoritative: if a later page
146
146
  * fails, the already-collected page-1 sources are returned. The outer
147
147
  * per-instance timer/signal covers every page, so pagination cannot outlive
148
148
  * the backend budget.
@@ -180,12 +180,12 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
180
180
  baseURL, request, signal, backendOpts, apiKey, hooks, pageUrl, max - out.length,
181
181
  );
182
182
  } catch (error) {
183
+ if (signal?.aborted === true) throw searchAborted(signal, error);
183
184
  // A failed page after a successful page 1 degrades coverage, not the
184
- // whole result; the caller still gets the sources already found.
185
+ // whole result; the caller still gets the sources already found. Any
186
+ // page>1 failure pauses extra pages for a minute (a 5xx flaps too).
185
187
  if (out.length > 0) {
186
- if (page > 1 && (error?.code === "RATE_LIMIT" || error?.code === "QUOTA")) {
187
- pageCooldowns.set(baseURL, Date.now() + 60_000);
188
- }
188
+ if (page > 1) pageCooldowns.set(baseURL, Date.now() + 60_000);
189
189
  break;
190
190
  }
191
191
  throw error;
@@ -196,7 +196,7 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
196
196
  out.push(src);
197
197
  }
198
198
  }
199
- if (page === 1) pageCooldowns.delete(baseURL);
199
+ if (page > 1) pageCooldowns.delete(baseURL);
200
200
  if (pageSources.length === 0 || out.length >= max) break;
201
201
  }
202
202
  return out.slice(0, max);
@@ -20,7 +20,7 @@ export const serperBackend = {
20
20
  requiresCredential: true,
21
21
 
22
22
  available(options) {
23
- return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
23
+ return typeof options?.resolveApiKey === "function";
24
24
  },
25
25
 
26
26
  async search(request, signal, options, hooks) {
@@ -20,7 +20,7 @@ export const tavilyBackend = {
20
20
  requiresCredential: true,
21
21
 
22
22
  available(options) {
23
- return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
23
+ return typeof options?.resolveApiKey === "function";
24
24
  },
25
25
 
26
26
  async search(request, signal, options, hooks) {
package/lib/cache.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // cache.js — v2.7.0 disk cache for unified search results (zero dependencies).
2
2
  //
3
- // Cache key: sha256 over the canonical JSON of {query (already shaped),
4
- // filters, maxResults} — exactly the dimensions that change a search outcome.
3
+ // Cache key: sha256 over the canonical JSON of the shaped query, filters,
4
+ // effective maxResults, ordered backend set, cache mode and result options.
5
5
  // Entries live as one JSON file per key under <dir>, written atomically
6
6
  // (tmp file + rename) so a crash mid-write never leaves a corrupt cache.
7
7
  // Eviction: when the entry count exceeds maxEntries, the oldest-by-mtime
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { createHash } from "node:crypto";
12
12
  import {
13
+ chmodSync,
13
14
  existsSync,
14
15
  mkdirSync,
15
16
  readdirSync,
package/lib/client.js CHANGED
@@ -131,6 +131,8 @@ window.__ModuleLoader__.load({
131
131
  keyReadFailed: "密钥状态读取失败,请稍后重试",
132
132
  telemetryLabel: "结果健康遥测",
133
133
  resultHeaderLabel: "结果引用提示头",
134
+ cacheLabel: "结果缓存",
135
+ cacheTtlLabel: "缓存有效期(秒)",
134
136
  fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端(计量型仍保持关闭)",
135
137
  invalidFields: "以下字段未通过校验:",
136
138
  readOnlyScope: "当前配置只读(可能由宿主锁定)",
@@ -219,6 +221,8 @@ window.__ModuleLoader__.load({
219
221
  keyReadFailed: "could not read key status, please retry later",
220
222
  telemetryLabel: "Result health telemetry",
221
223
  resultHeaderLabel: "Citation header",
224
+ cacheLabel: "Result cache",
225
+ cacheTtlLabel: "Cache TTL (s)",
222
226
  fallbackHint: "All backends off: search falls back to the default keyless four (metered backends stay off).",
223
227
  invalidFields: "Fields failed validation:",
224
228
  readOnlyScope: "Configuration is read-only (locked by host?)",
@@ -980,6 +984,10 @@ window.__ModuleLoader__.load({
980
984
  react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("timeoutLabel") }) }),
981
985
  react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("timeoutLabel"), value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: (e) => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
982
986
  ] }),
987
+ react_jsx_runtime.jsxs("div", { children: [
988
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("cacheTtlLabel") }) }),
989
+ react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("cacheTtlLabel"), value: state.stagedText("cacheTtl") ?? String(state.value.cacheTtl ?? ""), onChange: (e) => card.edit("cacheTtl", e.target.value), inputMode: "numeric" }),
990
+ ] }),
983
991
  ] }),
984
992
  react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("shapingTitle") }),
985
993
  react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
@@ -1001,6 +1009,7 @@ window.__ModuleLoader__.load({
1001
1009
  react_jsx_runtime.jsx(SelectField, { label: t("safeSearchLabel"), value: selVal("safeSearch", "true"), options: boolOptions, onChange: (v) => card.edit("safeSearch", v) }),
1002
1010
  react_jsx_runtime.jsx(SelectField, { label: t("telemetryLabel"), value: selVal("resultTelemetry", "true"), options: boolOptions, onChange: (v) => card.edit("resultTelemetry", v) }),
1003
1011
  react_jsx_runtime.jsx(SelectField, { label: t("resultHeaderLabel"), value: selVal("resultHeader", "true"), options: boolOptions, onChange: (v) => card.edit("resultHeader", v) }),
1012
+ react_jsx_runtime.jsx(SelectField, { label: t("cacheLabel"), value: selVal("cacheEnabled", "true"), options: boolOptions, onChange: (v) => card.edit("cacheEnabled", v) }),
1004
1013
  ] }),
1005
1014
  ] });
1006
1015
  }
package/lib/health.js CHANGED
@@ -61,6 +61,7 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
61
61
  cooledUntilMs: Number.isFinite(t?.cooledUntil) && t.cooledUntil > nowMs ? t.cooledUntil : null,
62
62
  // reachable: true/false from the latest search telemetry; null = never probed.
63
63
  reachable: t ? t.ok === true : null,
64
+ credentialMissing: t?.credentialMissing === true,
64
65
  lastOk: t && typeof t.lastOkAt === "number" ? t.lastOkAt : null,
65
66
  lastError: t && t.ok !== true ? sanitizeError(t.error) || "unknown error" : null,
66
67
  };
package/lib/history.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // oldest entry beyond the cap is dropped. Exposure is strictly read-only via
7
7
  // GET /api/websearch/history; POST /api/websearch/history/clear empties it.
8
8
 
9
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import path from "node:path";
11
11
  import { rejectionFor, rejectionBody } from "./trust.js";
12
12
 
@@ -55,6 +55,7 @@ export function createHistoryStore({ dir, maxEntries = HISTORY_MAX_ENTRIES }) {
55
55
 
56
56
  function atomicWriteAll(list) {
57
57
  mkdirSync(dir, { recursive: true, mode: 0o700 });
58
+ try { chmodSync(dir, 0o700); } catch { /* existing dir owned by another mode */ }
58
59
  const f = file();
59
60
  const tmp = `${f}.${process.pid}.tmp`;
60
61
  writeFileSync(tmp, JSON.stringify(list, null, 2), { encoding: "utf8", mode: 0o600 });
package/lib/index.js CHANGED
@@ -20,18 +20,6 @@ import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
20
20
  import { WebError } from "@deepseek-ai/dsh-web";
21
21
  import { findPluginRow } from "./util/namespace.js";
22
22
 
23
- // Credential presence observed by the last resolveApiKey() call. The seam asks
24
- // available() before any search, so a cold/unknown ref must stay optimistic;
25
- // once a resolve returns empty (or a key), key-gated backends stop/start
26
- // advertising themselves without a restart.
27
- const keyPresence = new Map(); // ref -> { present, at }
28
- const PRESENCE_TTL_MS = 60_000;
29
-
30
- /** Test/support hook: forget observed key presence for one ref or all refs. */
31
- export function resetKeyPresence(ref) {
32
- if (ref === undefined) keyPresence.clear();
33
- else keyPresence.delete(ref);
34
- }
35
23
 
36
24
  // Import all backends
37
25
  import { exaBackend } from "./backends/exa.js";
@@ -208,7 +196,7 @@ export const Config = z.object({
208
196
  cacheEnabled: z.boolean().default(true)
209
197
  .description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
210
198
  cacheTtl: z.number().step(30).min(0).max(86400).default(900)
211
- .description("缓存有效期【缓存】(单位:秒):默认 900 秒;不想用缓存请直接关闭上一项"),
199
+ .description("缓存有效期【缓存】(单位:秒):默认 900;0 = 不缓存(no-store)"),
212
200
  breakerEnabled: z.boolean().default(true)
213
201
  .description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
214
202
  breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
@@ -359,10 +347,10 @@ function normalizeDomainList(raw) {
359
347
  const u = new URL(item.includes("://") ? item : "https://" + host);
360
348
  host = u.hostname;
361
349
  } catch { /* keep the raw token and validate below */ }
362
- host = host.replace(/^\[|\]$/g, "").replace(/\.$/, "");
350
+ host = host.replace(/^\[|\]$/g, "").replace(/^\*\./, "").replace(/\.$/, "");
363
351
  // Hostname only: at least one dot, no empty labels, no bare IPv4/IPv6
364
352
  // literals (OpenAI/Anthropic domain filters expect DNS names).
365
- if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host)) continue;
353
+ if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})$/.test(host)) continue;
366
354
  if (!out.includes(host)) out.push(host);
367
355
  if (out.length >= 20) break;
368
356
  }
@@ -407,7 +395,8 @@ export function resolveOptions(ctx, config) {
407
395
  const excludeDomains = normalizeDomainList(config?.excludeDomains);
408
396
  // A non-empty setting that normalizes to nothing must not silently disable
409
397
  // the restriction; the provider turns this into a clear search error.
410
- const domainFilterError = (
398
+ const domainConsumers = enabledBackends.some((id) => id === "openai" || id === "anthropic");
399
+ const domainFilterError = domainConsumers && (
411
400
  (typeof config?.includeDomains === "string" && config.includeDomains.trim() !== "" && includeDomains.length === 0)
412
401
  || (typeof config?.excludeDomains === "string" && config.excludeDomains.trim() !== "" && excludeDomains.length === 0)
413
402
  ) ? "domain filter contains no valid hostname" : undefined;
@@ -433,29 +422,11 @@ export function resolveOptions(ctx, config) {
433
422
  requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
434
423
  optionalKey: OPTIONAL_KEY_IDS.has(id),
435
424
  metered: METERED_IDS.has(id),
436
- credentialPresent: (() => {
437
- const seen = keyPresence.get(ref);
438
- if (seen === undefined) return undefined;
439
- // A stale "absent" hint may hide a key added without an event; fall
440
- // back to unknown so the next search can probe again.
441
- return !seen.present && Date.now() - seen.at > PRESENCE_TTL_MS ? undefined : seen.present;
442
- })(),
443
425
  resolveApiKey: async () => {
444
- try {
445
- let value;
446
- const credentials = ctx.get("credentials");
447
- if (credentials !== undefined) {
448
- value = (await credentials.resolve(ref))?.value;
449
- } else {
450
- const ambient = launchEnvironmentOf(ctx).get(ref);
451
- value = ambient !== undefined && ambient.value.length > 0 ? ambient.value : undefined;
452
- }
453
- keyPresence.set(ref, { present: typeof value === "string" && value.length > 0, at: Date.now() });
454
- return value;
455
- } catch (error) {
456
- keyPresence.delete(ref); // unknown, not absent
457
- throw error;
458
- }
426
+ const credentials = ctx.get("credentials");
427
+ if (credentials !== undefined) return (await credentials.resolve(ref))?.value;
428
+ const ambient = launchEnvironmentOf(ctx).get(ref);
429
+ return ambient !== undefined && ambient.value.length > 0 ? ambient.value : undefined;
459
430
  },
460
431
  };
461
432
  }
@@ -533,14 +504,6 @@ export function resolveStoreDir(env = process.env, fallbackHome = os.homedir())
533
504
  * model names / credential references in the DSH Settings panel.
534
505
  */
535
506
  export function apply(ctx, config) {
536
- for (const event of ["credentials/reference-updated", "credentials/updated"]) {
537
- try {
538
- ctx.on(event, (ref) => {
539
- if (typeof ref === "string") keyPresence.delete(ref);
540
- else keyPresence.clear();
541
- });
542
- } catch { /* this host does not forward the event */ }
543
- }
544
507
  let current = () => config;
545
508
  /** 0.2.x SettingsForms instance, captured for the browser settings bridge. */
546
509
  let settingsForms;
package/lib/provider.js CHANGED
@@ -85,9 +85,13 @@ function recordBackendHealth(id, entry, breakerCfg, opts = {}) {
85
85
  // failures for diagnostics, but never publish a cooldown the provider does
86
86
  // not honour (health/history used to show `cooled: true` while the backend
87
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);
88
+ const breaker = entry.credentialMissing === true
89
+ // A missing key is a configuration state, not an outage: keep the current
90
+ // breaker counters and only publish the diagnostic entry.
91
+ ? { failCount: Number(prev?.failCount) || 0, cooledUntil: Number(prev?.cooledUntil) || 0 }
92
+ : breakerCfg === null
93
+ ? { failCount: entry.ok === true ? 0 : (Number(prev?.failCount) || 0) + 1, cooledUntil: 0 }
94
+ : foldBreaker(prev, entry.ok === true, entry.at, breakerCfg, opts);
91
95
  latestBackendHealth.set(id, {
92
96
  ...entry,
93
97
  lastOkAt: entry.ok === true ? entry.at : (prev && prev.lastOkAt) || null,
@@ -98,6 +102,7 @@ function recordBackendHealth(id, entry, breakerCfg, opts = {}) {
98
102
  // permission refusal (which cannot be fixed by retrying after a wait).
99
103
  rateLimited: opts.rateLimited === true,
100
104
  keylessRejected: opts.keylessRejected === true,
105
+ credentialMissing: entry.credentialMissing === true,
101
106
  });
102
107
  }
103
108
 
@@ -450,8 +455,11 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
450
455
 
451
456
  if (eligible.length === 0) {
452
457
  recordHistory(history, request?.query, 0, 0, candidates.length);
458
+ const registered = (opts.enabledBackends ?? []).filter((id) => backends[id] !== undefined).length;
453
459
  throw new WebError(
454
- "unified search: none of the enabled backend ids is registered",
460
+ registered === 0
461
+ ? "unified search: none of the enabled backend ids is registered"
462
+ : "unified search: no enabled backend is available (missing API key or unsupported config)",
455
463
  "WEB_PROVIDER_UNAVAILABLE",
456
464
  );
457
465
  }
@@ -459,7 +467,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
459
467
  // Run ONE query variant through the full fan-out: breaker-aware backend
460
468
  // execution under the per-variant limiter, then PHASE 1 collect. The
461
469
  // internal abort/timeout semantics are unchanged from v2.7.
462
- const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY, deadline = Number.POSITIVE_INFINITY) => {
470
+ const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY, deadline = Number.POSITIVE_INFINITY, eligibleList = eligible) => {
463
471
  const telemetry = [];
464
472
  // Health is folded once per backend per SEARCH, after every variant
465
473
  // finished: recording per variant let one multi-query search trip the
@@ -555,6 +563,11 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
555
563
  // thrown error said "timed out after Nms" — the two disagreed
556
564
  // and "(unified search aborted)" read as if the USER cancelled.
557
565
  const timedOut = controller.signal.aborted && !(signal && signal.aborted);
566
+ // Only a timeout caused by the shared/variant budget is
567
+ // exempt from the breaker; a 429/500 on a clipped attempt is
568
+ // still a real backend failure.
569
+ const budgetClipped = timedOut
570
+ && (remainingNow < configuredTimeoutMs - 10 || variantBudgetMs < configuredTimeoutMs - 10);
558
571
  const reason = timedOut
559
572
  ? budgetClipped
560
573
  ? `backend "${id}" search budget exhausted after ${effectiveTimeoutMs}ms`
@@ -563,11 +576,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
563
576
  const msg = sanitizeError(reason, 80);
564
577
  telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
565
578
  // A missing API key is a configuration state, not an outage:
566
- // folding it would cool the breaker and paint /health red for
567
- // a backend the operator can fix in Settings.
568
- if (!budgetClipped && !(err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING")) {
579
+ // publish it for /health but keep it out of the breaker.
580
+ if (!budgetClipped) {
581
+ const credentialMissing = err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING";
569
582
  health.push({
570
583
  id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
584
+ ...(credentialMissing ? { credentialMissing: true } : {}),
571
585
  rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
572
586
  });
573
587
  }
@@ -580,7 +594,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
580
594
  };
581
595
 
582
596
  const results = await Promise.allSettled(
583
- eligible.map(({ id, backend, beOpts }) => {
597
+ eligibleList.map(({ id, backend, beOpts }) => {
584
598
  const hooks = {
585
599
  recordRequest: (req) => recordBackendRequest(ctx, id, req),
586
600
  recordOutcome: (out) => recordBackendOutcome(ctx, id, out),
@@ -589,7 +603,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
589
603
  }),
590
604
  );
591
605
  throwIfSearchAborted(signal);
592
- const fold = collectFanoutResults(results, eligible, signal);
606
+ const fold = collectFanoutResults(results, eligibleList, signal);
593
607
  return { ...fold, telemetry, health };
594
608
  };
595
609
 
@@ -619,16 +633,27 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
619
633
  // slow variant cannot starve the rest (the old code gave each variant
620
634
  // the full budget, and each backend inside it).
621
635
  const share = Math.max(1, Math.floor(remaining / Math.max(1, variants.length - variantIndex)));
636
+ // Parallel can merge the derived facets into one request; give it the
637
+ // plan on the primary variant and skip it for later variants. Other
638
+ // backends must not opt into handlesAllVariants (they cannot merge
639
+ // facets without changing semantics).
640
+ const searchPlan = useMulti && variantIndex === 0
641
+ ? { objective: effReq.query, queries: variants.slice(0, 3) }
642
+ : undefined;
643
+ const variantEligible = variantIndex === 0
644
+ ? eligible
645
+ : eligible.filter(({ backend }) => backend.handlesAllVariants !== true);
622
646
  const variantReq = {
623
647
  ...effReq,
624
648
  query: variantQuery,
625
649
  maxResults: backendMaxResults,
650
+ ...(searchPlan !== undefined ? { searchPlan } : {}),
626
651
  ...(coverage ? { deepCoverage: true } : {}),
627
652
  // SearXNG paging is opt-in and never combines with internal
628
653
  // multi-query (each variant already costs one request).
629
654
  pageLimit: coverage && !useMulti ? 2 : 1,
630
655
  };
631
- const fold = await fanoutVariant(variantReq, share, searchDeadline);
656
+ const fold = await fanoutVariant(variantReq, share, searchDeadline, variantEligible);
632
657
  for (const outcome of fold.health) {
633
658
  const prev = searchHealth.get(outcome.id);
634
659
  if (prev === undefined || outcome.ok === true) {
@@ -762,6 +787,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
762
787
  const parts = foldedTelemetry
763
788
  .slice(0, 12)
764
789
  .map((t) => {
790
+ if (t.skipped === true) return t.id + " ⏭budget";
765
791
  if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
766
792
  const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
767
793
  const cooledNow = cooledAnnotation(latestBackendHealth.get(t.id), Date.now());
@@ -826,6 +852,8 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
826
852
  // allFailures holds one entry per attempt (multi-query fans out once per
827
853
  // variant); fold to one entry per backend before counting/reporting.
828
854
  const uniqueFailures = [...new Map(allFailures.map((f) => [f.id, f])).values()];
855
+ const skippedIds = new Set(allTelemetry.filter((t) => t.skipped === true).map((t) => t.id));
856
+ const attemptedFailures = uniqueFailures.filter((f) => !skippedIds.has(f.id));
829
857
  const detail = uniqueFailures.slice(0, MAX_FAILURE_DETAILS)
830
858
  .map((f) => f.id + ": " + sanitizeError(f.err instanceof Error ? f.err.message : f.err, 120))
831
859
  .join("; ") + (uniqueFailures.length > MAX_FAILURE_DETAILS ? `; +${uniqueFailures.length - MAX_FAILURE_DETAILS} more` : "");
@@ -849,7 +877,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
849
877
  ? " (cooled-skipped: " + skippedOnly.map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, nowMs) || "⏸cooled")).join(", ") + ")"
850
878
  : "";
851
879
  throw new WebError(
852
- `unified search: all attempted backends failed (${uniqueFailures.length} of ${candidates.length} enabled) - ${detail}` + cooledNote + hint,
880
+ (skippedIds.size > 0
881
+ ? `unified search: all attempted backends failed (${attemptedFailures.length} of ${candidates.length} enabled; ${skippedIds.size} skipped for budget) - ${detail}`
882
+ : `unified search: all attempted backends failed (${uniqueFailures.length} of ${candidates.length} enabled) - ${detail}`) + cooledNote + hint,
853
883
  "WEB_PROVIDER_ERROR",
854
884
  {
855
885
  // The cause message can embed an upstream body that echoes a key;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-websearch",
3
- "version": "2.11.0",
3
+ "version": "2.12.0",
4
4
  "description": "Unified web search provider for DeepSeek Harness (ctx.web): 13 backends — Exa + Parallel + DDG + SearXNG (keyless), DeepSeek + Anthropic + OpenAI + Brave + Tavily + Serper + Mojeek (key-gated via Settings credentials), Firecrawl + TinyFish (metered keyless, opt-in). Registers provider id \"unified\" for zero-config web_search. 统一网页搜索聚合:13 后端并发扇出、去重合并。See CHANGELOG.md for version history.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",