@240xu/dsh-websearch 2.10.0 → 2.11.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` 等其余字段通过 profile patch 配置:
95
+ 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数(共 60 个配置字段);缓存、熔断、历史、多查询、域名过滤、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 Config 表单 / profile patch 配置:
96
96
 
97
97
  **全局**
98
98
 
@@ -100,8 +100,8 @@ pnpm install
100
100
  |---|---|---|
101
101
  | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
102
  | `numResults` | 10 | 每次搜索返回结果数(1-100;Exa 上限 100,official 档沿用宿主工具的条数上限) |
103
- | `includeDomains` | 空 | 仅允许这些域名(逗号/空格分隔,最多 20;OpenAI/Anthropic 原生后端生效) |
104
- | `excludeDomains` | 空 | 排除这些域名(最多 20;同时设置时原生后端优先 allow) |
103
+ | `includeDomains` | 空 | 仅约束 OpenAI/Anthropic 原生后端(最多 20;其余后端不支持,合并结果仍可能来自其他域名) |
104
+ | `excludeDomains` | 空 | 排除这些域名(最多 20;Anthropic 仅发 allow,OpenAI 两个列表同时发送) |
105
105
  | `concurrency` | 6 | 并发后端数(1-10) |
106
106
  | `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
107
107
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
@@ -172,6 +172,7 @@ pnpm install
172
172
 
173
173
  ### 4. per-backend 超时上限(P2)
174
174
 
175
+ - SearXNG 仅在 `thorough`/`deepCoverage` 且未开启内部多查询时翻第 2 页(单实例;第 2 页 429/5xx 会回退到第 1 页并冷却 60 秒);多实例 failover 始终只取第 1 页。
175
176
  - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
176
177
 
177
178
  ## v2.7.3 兼容修复 | What's new in v2.7.3
@@ -205,7 +206,9 @@ pnpm install
205
206
  - 相同 **(整形后查询 + filters + maxResults + 启用后端集合)** 在 TTL 内直接命中缓存,不打任何后端;`sources` 与首次搜索完全一致。
206
207
  - 命中时 `content` 追加一行 `[websearch cache] cache hit, age Ns`。
207
208
  - 存储位置:`$DSH_HOME/cache/websearch/results/`,单条目一个 JSON 文件,tmp+rename 原子写,超出上限按最旧淘汰;任何 fs 错误都被吞掉,缓存坏了绝不影响搜索。
208
- - 设置:`cacheEnabled`(默认 true)、`cacheTtl`(秒,默认 900)。
209
+ - 设置:`cacheEnabled`(默认 true)、`cacheTtl`(秒,默认 900;**0 = no-store**,不读也不写)。
210
+ - 上限 200 条,超出按 mtime 最旧淘汰;缓存目录 0700、文件 0600(查询与结果属于用户数据)。
211
+ - 清理:`rm -rf $DSH_HOME/cache/websearch/results`(`DSH_HOME` 通常为 `~/.dsh`)。
209
212
 
210
213
  ### 2. 后端熔断器(默认开,保守阈值)
211
214
 
@@ -266,7 +269,7 @@ tests/
266
269
  node --test tests/
267
270
  ```
268
271
 
269
- 当前 220/220 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
272
+ 当前 225/225 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
270
273
 
271
274
  ### Test-only dependencies
272
275
 
@@ -279,7 +282,7 @@ live service before running the suite:
279
282
  ```bash
280
283
  bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
281
284
  find node_modules/@deepseek-ai -xtype l # expect no output
282
- node --test tests/*.test.js # 220/220
285
+ node --test tests/*.test.js # 225/225
283
286
  ```
284
287
 
285
288
  v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
@@ -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;
61
+ return okKey && urlOk && options?.credentialPresent !== false;
62
62
  },
63
63
 
64
64
  /**
@@ -86,11 +86,15 @@ export function createAnthropicLikeBackend(spec) {
86
86
  const maxUses = options.maxUses ?? 5;
87
87
  const endpoint = `${baseURL.replace(/\/$/, "")}/messages`;
88
88
 
89
- const domainArgs = Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
90
- ? { allowed_domains: options.includeDomains }
91
- : Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
92
- ? { blocked_domains: options.excludeDomains }
93
- : {};
89
+ // Only the Anthropic route has a probed domain-filter contract; the
90
+ // DeepSeek-compatible route shares this factory but has not been probed.
91
+ const domainArgs = id !== "anthropic"
92
+ ? {}
93
+ : Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
94
+ ? { allowed_domains: options.includeDomains }
95
+ : Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
96
+ ? { blocked_domains: options.excludeDomains }
97
+ : {};
94
98
  const body = {
95
99
  model,
96
100
  max_tokens: maxTokens,
@@ -20,7 +20,7 @@ export const braveBackend = {
20
20
  requiresCredential: true,
21
21
 
22
22
  available(options) {
23
- return typeof options?.resolveApiKey === "function";
23
+ return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
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";
22
+ return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
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;
32
+ return okKey && urlOk && options?.credentialPresent !== false;
33
33
  },
34
34
 
35
35
  /**
@@ -53,9 +53,11 @@ export const openaiBackend = {
53
53
  const model = options.model || "gpt-4o";
54
54
  const endpoint = `${baseURL}/responses`;
55
55
 
56
- const domainFilters = {};
57
- if (Array.isArray(options?.includeDomains) && options.includeDomains.length > 0) domainFilters.allowed_domains = options.includeDomains;
58
- if (Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0) domainFilters.blocked_domains = options.excludeDomains;
56
+ const domainFilters = Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
57
+ ? { allowed_domains: options.includeDomains }
58
+ : Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
59
+ ? { blocked_domains: options.excludeDomains }
60
+ : {};
59
61
  const body = {
60
62
  model,
61
63
  tools: [{
@@ -37,10 +37,12 @@ const ANTI_BOT_RE = /(verifying your browser|making sure you.?re not a bot|check
37
37
  const INSTANCE_COOLDOWN_MS = 10 * 60_000;
38
38
  const INSTANCE_ATTEMPT_TIMEOUT_MS = 4500;
39
39
  const instanceCooldowns = new Map(); // baseURL -> cooledUntil (epoch ms)
40
+ const pageCooldowns = new Map(); // baseURL -> no-pagination-until (epoch ms)
40
41
 
41
42
  /** Test hook: clear per-instance cooldowns between cases. */
42
43
  export function resetInstanceCooldowns() {
43
44
  instanceCooldowns.clear();
45
+ pageCooldowns.clear();
44
46
  }
45
47
 
46
48
  /** @type {import("../provider.js").Backend} */
@@ -106,7 +108,7 @@ export const searxngBackend = {
106
108
  const attemptSignal = signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal;
107
109
  const timer = setTimeout(() => attemptController.abort(), attemptMs);
108
110
  try {
109
- const sources = await queryInstance(candidate, request, attemptSignal, backendOpts, apiKey, hooks);
111
+ const sources = await queryInstance(candidate, { ...request, pageLimit: 1 }, attemptSignal, backendOpts, apiKey, hooks);
110
112
  instanceCooldowns.delete(candidate);
111
113
  return { sources };
112
114
  } catch (error) {
@@ -139,26 +141,73 @@ export const searxngBackend = {
139
141
  };
140
142
 
141
143
  /**
142
- * One request against one instance. Throws WebError on any failure; abort
143
- * semantics are the caller's contract (signal passed through verbatim).
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
146
+ * fails, the already-collected page-1 sources are returned. The outer
147
+ * per-instance timer/signal covers every page, so pagination cannot outlive
148
+ * the backend budget.
144
149
  * @returns {Promise<Array>} sources
145
150
  */
146
151
  async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hooks) {
147
- const url = new URL(baseURL);
148
- url.pathname = url.pathname.replace(/\/+$/,"") + "/search";
149
- url.searchParams.set("q", request.query);
150
- url.searchParams.set("format", "json");
152
+ const base = new URL(baseURL);
153
+ base.pathname = base.pathname.replace(/\/+$/,"") + "/search";
154
+ base.searchParams.set("q", request.query);
155
+ base.searchParams.set("format", "json");
151
156
  // deepCoverage widens the category sweep (docs.searxng.org Search API:
152
157
  // categories is a comma-separated list) — breadth over one category.
153
- url.searchParams.set("categories", request.deepCoverage === true ? "general,news,it" : "general");
158
+ base.searchParams.set("categories", request.deepCoverage === true ? "general,news,it" : "general");
154
159
  // Language: settings/request filter wins, else historical "en" default.
155
160
  const filters = normalizeFilters(request.filters);
156
- url.searchParams.set("language", filters.lang ?? "en");
157
- applySearxngFilters(url, filters); // time_range (+ language override)
161
+ base.searchParams.set("language", filters.lang ?? "en");
162
+ applySearxngFilters(base, filters); // time_range (+ language override)
158
163
  // Safe-search defaults ON (preserves the previous hardcoded behavior).
159
- url.searchParams.set("safesearch", safeSearchParams("searxng", backendOpts.safeSearch ?? true) ?? "1");
160
- url.searchParams.set("pageno", "1");
164
+ base.searchParams.set("safesearch", safeSearchParams("searxng", backendOpts.safeSearch ?? true) ?? "1");
161
165
 
166
+ const max = Math.max(1, Number(request.maxResults) || 8);
167
+ // A page-2 429/5xx must not be repeated on every search: keep the first
168
+ // page, skip extra pages for a minute.
169
+ const pages = (pageCooldowns.get(baseURL) ?? 0) > Date.now()
170
+ ? 1
171
+ : Math.min(2, Math.max(1, Number(request.pageLimit) || 1));
172
+ const out = [];
173
+ const seen = new Set();
174
+ for (let page = 1; page <= pages; page += 1) {
175
+ const pageUrl = new URL(base);
176
+ pageUrl.searchParams.set("pageno", String(page));
177
+ let pageSources;
178
+ try {
179
+ pageSources = await queryInstancePage(
180
+ baseURL, request, signal, backendOpts, apiKey, hooks, pageUrl, max - out.length,
181
+ );
182
+ } catch (error) {
183
+ // A failed page after a successful page 1 degrades coverage, not the
184
+ // whole result; the caller still gets the sources already found.
185
+ if (out.length > 0) {
186
+ if (page > 1 && (error?.code === "RATE_LIMIT" || error?.code === "QUOTA")) {
187
+ pageCooldowns.set(baseURL, Date.now() + 60_000);
188
+ }
189
+ break;
190
+ }
191
+ throw error;
192
+ }
193
+ for (const src of pageSources) {
194
+ if (src && typeof src.url === "string" && !seen.has(src.url)) {
195
+ seen.add(src.url);
196
+ out.push(src);
197
+ }
198
+ }
199
+ if (page === 1) pageCooldowns.delete(baseURL);
200
+ if (pageSources.length === 0 || out.length >= max) break;
201
+ }
202
+ return out.slice(0, max);
203
+ }
204
+
205
+ /**
206
+ * One page against one instance. Throws WebError on any failure; abort
207
+ * semantics are the caller's contract (signal passed through verbatim).
208
+ * @returns {Promise<Array>} sources
209
+ */
210
+ async function queryInstancePage(baseURL, request, signal, backendOpts, apiKey, hooks, url, remainingMax) {
162
211
  const headers = {
163
212
  "Accept": "application/json",
164
213
  "User-Agent": "dsh-websearch/2.3",
@@ -223,7 +272,7 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
223
272
  throw new WebError(message, "WEB_PROVIDER_ERROR");
224
273
  }
225
274
 
226
- const sources = parseSearxngResult(data, request.maxResults ?? 8);
275
+ const sources = parseSearxngResult(data, remainingMax);
227
276
  hooks?.recordOutcome?.({ status: "success", count: sources.length });
228
277
  return sources;
229
278
  }
@@ -20,7 +20,7 @@ export const serperBackend = {
20
20
  requiresCredential: true,
21
21
 
22
22
  available(options) {
23
- return typeof options?.resolveApiKey === "function";
23
+ return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
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";
23
+ return typeof options?.resolveApiKey === "function" && options?.credentialPresent !== false;
24
24
  },
25
25
 
26
26
  async search(request, signal, options, hooks) {
package/lib/client.js CHANGED
@@ -7,11 +7,6 @@ window.__ModuleLoader__.load({
7
7
  let react_jsx_runtime = require("react/jsx-runtime");
8
8
  let react = require("react");
9
9
 
10
- /** Localized display label for a backend id (falls back to the id). */
11
- function backendLabel(t, id) {
12
- return t("backend" + id.charAt(0).toUpperCase() + id.slice(1));
13
- }
14
-
15
10
  const NS = "websearch.settings";
16
11
  const PLUGIN_NS = "unified-search";
17
12
 
@@ -36,7 +31,7 @@ window.__ModuleLoader__.load({
36
31
  { id: "firecrawl", keyEnv: "FIRECRAWL_API_KEY", optionalKey: true, metered: true, label: "Firecrawl (免 Key · 有额度 · 默认关)" },
37
32
  { id: "tinyfish", keyEnv: "TINYFISH_API_KEY", optionalKey: true, metered: true, label: "TinyFish (免 Key · 30/分·50/日 · 默认关)" },
38
33
  ];
39
- const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs"];
34
+ const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs", "cacheTtl"];
40
35
  /** Enum-valued settings (validated client-side, saved as strings). */
41
36
  const SELECT_FIELDS = {
42
37
  intervention: ["official", "balanced", "thorough"],
@@ -44,7 +39,7 @@ window.__ModuleLoader__.load({
44
39
  dedupStrategy: ["url", "url+title"],
45
40
  };
46
41
  /** Boolean settings staged as "true"/"false" strings by the selects. */
47
- const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry", "resultHeader"];
42
+ const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry", "resultHeader", "cacheEnabled"];
48
43
  // split metered, opt-in backends out of the
49
44
  // "keyless / ready to use" group. They work without a key but are rate
50
45
  // limited and default OFF, so a separate section with an explicit hint
@@ -683,9 +678,11 @@ window.__ModuleLoader__.load({
683
678
  numResults: [1, 100],
684
679
  concurrency: [1, 10],
685
680
  backendTimeoutMs: [1000, 120000],
681
+ cacheTtl: [0, 86400],
686
682
  };
683
+ const STEP = { numResults: 1, concurrency: 1, backendTimeoutMs: 1000, cacheTtl: 30 };
687
684
  const [lo, hi] = BOUNDS[field] ?? [-Infinity, Infinity];
688
- if (!Number.isInteger(num) || num < lo || num > hi) { this.failed = true; this.failedFields.add(field); continue; }
685
+ if (!Number.isInteger(num) || num < lo || num > hi || num % (STEP[field] ?? 1) !== 0) { this.failed = true; this.failedFields.add(field); continue; }
689
686
  fieldOps.push({ op: "set", path: [field], value: num }); fieldOpNames.push(field);
690
687
  } else {
691
688
  fieldOps.push({ op: "set", path: [field], value: staged.text }); fieldOpNames.push(field);
@@ -735,6 +732,10 @@ window.__ModuleLoader__.load({
735
732
  && this.staged.size === 0 && this.stagedKeys.size === 0) this.savedAt = Date.now();
736
733
  } catch (err) {
737
734
  this.failed = true;
735
+ // A server-side schema 400 names the field; attribute it so
736
+ // the card can mark the offending control.
737
+ const named = /(?:invalid value for|unknown settings field) "([^"]+)"/.exec(String(err));
738
+ if (named !== null) this.failedFields.add(named[1]);
738
739
  this.conflict = String(err).includes("SETTINGS_CONFLICT");
739
740
  // Without a reload the stale expectedRevision makes every
740
741
  // subsequent Save fail the same way. Staged edits survive, so
package/lib/index.js CHANGED
@@ -20,6 +20,19 @@ 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
  // Import all backends
24
37
  import { exaBackend } from "./backends/exa.js";
25
38
  import { parallelBackend } from "./backends/parallel.js";
@@ -162,7 +175,7 @@ export const Config = z.object({
162
175
  intervention: z.union(["official", "balanced", "thorough"]).default("balanced")
163
176
  .description("搜索介入程度【策略】:official=只做官方 provider 该做的(原样查询、不加结果头/遥测、沿用工具的条数上限);balanced=确定性去噪 + 去重/遥测(默认);thorough=额外启用相关性重排与深度覆盖(内部多查询仍是独立开关,默认关)"),
164
177
  numResults: z.number().step(1).min(1).max(100).default(10)
165
- .description("每次搜索返回的最大结果数(official 档沿用宿主工具的条数上限)"),
178
+ .description("每次搜索返回的最大结果数(1-100;Exa/Firecrawl 可达 100,Brave/Tavily/Serper/Mojeek 每次最多 20;official 沿用宿主上限)"),
166
179
  concurrency: z.number().step(1).min(1).max(10).default(6)
167
180
  .description("同时并发的后端数量"),
168
181
  backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(24000)
@@ -176,9 +189,9 @@ export const Config = z.object({
176
189
  safeSearch: z.boolean().default(true)
177
190
  .description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
178
191
  includeDomains: z.string().default("")
179
- .description("只允许这些域名(逗号/空格分隔,最多 20 个;OpenAI/Anthropic 原生后端生效)"),
192
+ .description("只约束 OpenAI/Anthropic 原生后端的允许域名(逗号/空格分隔,最多 20 个);其余后端不支持,合并结果仍可能来自其他域名"),
180
193
  excludeDomains: z.string().default("")
181
- .description("排除这些域名(逗号/空格分隔,最多 20 个;与 includeDomains 同时设置时原生后端优先 include)"),
194
+ .description("排除这些域名(逗号/空格分隔,最多 20 个);Anthropic 仅发 allowed(include 优先),OpenAI 两个列表同时发送由服务端裁决"),
182
195
  dedupStrategy: z.union(["url", "url+title"]).default("url")
183
196
  .description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
184
197
  rerank: z.boolean().default(false)
@@ -335,16 +348,21 @@ for (const [key, label] of Object.entries(FIELD_LABELS)) {
335
348
  function normalizeDomainList(raw) {
336
349
  if (typeof raw !== "string" || raw.trim() === "") return [];
337
350
  const out = [];
338
- for (const piece of raw.split(/[,\s]+/)) {
351
+ for (const piece of raw.split(/[,,、;;\s]+/)) {
339
352
  const item = piece.trim().toLowerCase();
340
353
  if (item === "") continue;
341
354
  let host = item;
355
+ // A leading wildcard is the natural way to say "this domain and its
356
+ // subdomains"; both providers' filters already match subdomains.
357
+ if (host.startsWith("*.")) host = host.slice(2);
342
358
  try {
343
- const u = new URL(item.includes("://") ? item : "https://" + item);
359
+ const u = new URL(item.includes("://") ? item : "https://" + host);
344
360
  host = u.hostname;
345
361
  } catch { /* keep the raw token and validate below */ }
346
- host = host.replace(/^\[|\]$/g, "");
347
- if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host)) continue;
362
+ host = host.replace(/^\[|\]$/g, "").replace(/\.$/, "");
363
+ // Hostname only: at least one dot, no empty labels, no bare IPv4/IPv6
364
+ // 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;
348
366
  if (!out.includes(host)) out.push(host);
349
367
  if (out.length >= 20) break;
350
368
  }
@@ -385,6 +403,14 @@ export function resolveOptions(ctx, config) {
385
403
  enabledBackends = [...new Set(enabledBackends)];
386
404
 
387
405
  // 2. Resolve each backend option
406
+ const includeDomains = normalizeDomainList(config?.includeDomains);
407
+ const excludeDomains = normalizeDomainList(config?.excludeDomains);
408
+ // A non-empty setting that normalizes to nothing must not silently disable
409
+ // the restriction; the provider turns this into a clear search error.
410
+ const domainFilterError = (
411
+ (typeof config?.includeDomains === "string" && config.includeDomains.trim() !== "" && includeDomains.length === 0)
412
+ || (typeof config?.excludeDomains === "string" && config.excludeDomains.trim() !== "" && excludeDomains.length === 0)
413
+ ) ? "domain filter contains no valid hostname" : undefined;
388
414
  const backends = {};
389
415
  for (const id of ALL_BACKENDS) {
390
416
  const keyEnvName = config?.[`${id}ApiKeyEnv`] ?? DEFAULT_KEY_ENV[id];
@@ -401,17 +427,35 @@ export function resolveOptions(ctx, config) {
401
427
  : [],
402
428
  } : {}),
403
429
  safeSearch: config?.safeSearch !== false,
404
- includeDomains: normalizeDomainList(config?.includeDomains),
405
- excludeDomains: normalizeDomainList(config?.excludeDomains),
430
+ includeDomains,
431
+ excludeDomains,
406
432
  label: DEFAULT_LABELS[id] ?? id,
407
433
  requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
408
434
  optionalKey: OPTIONAL_KEY_IDS.has(id),
409
435
  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
+ })(),
410
443
  resolveApiKey: async () => {
411
- const credentials = ctx.get("credentials");
412
- if (credentials !== undefined) return (await credentials.resolve(ref))?.value;
413
- const ambient = launchEnvironmentOf(ctx).get(ref);
414
- return ambient !== undefined && ambient.value.length > 0 ? ambient.value : undefined;
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
+ }
415
459
  },
416
460
  };
417
461
  }
@@ -458,8 +502,9 @@ export function resolveOptions(ctx, config) {
458
502
  // invisibly.
459
503
  multiQueryEnabled: !official && config?.multiQueryEnabled === true,
460
504
  deepCoverage: thorough || (!official && config?.deepCoverage === true),
461
- includeDomains: normalizeDomainList(config?.includeDomains),
462
- excludeDomains: normalizeDomainList(config?.excludeDomains),
505
+ includeDomains,
506
+ excludeDomains,
507
+ domainFilterError,
463
508
  filters: {
464
509
  recency: typeof config?.recency === "string" && config.recency !== "any" ? config.recency : undefined,
465
510
  lang: language.length > 0 ? language : undefined,
@@ -488,6 +533,14 @@ export function resolveStoreDir(env = process.env, fallbackHome = os.homedir())
488
533
  * model names / credential references in the DSH Settings panel.
489
534
  */
490
535
  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
+ }
491
544
  let current = () => config;
492
545
  /** 0.2.x SettingsForms instance, captured for the browser settings bridge. */
493
546
  let settingsForms;
package/lib/provider.js CHANGED
@@ -236,6 +236,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
236
236
  async search(request, signal) {
237
237
  throwIfSearchAborted(signal);
238
238
  const opts = resolveOptions();
239
+ if (opts.domainFilterError !== undefined) {
240
+ throw new WebError("unified search: " + opts.domainFilterError, "WEB_PROVIDER_ERROR");
241
+ }
239
242
  const filters = normalizeFilters({
240
243
  ...(opts.filters ?? {}),
241
244
  ...(request?.filters ?? {}),
@@ -313,7 +316,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
313
316
  const resultOptions = {};
314
317
  for (const [k, v] of Object.entries(opts)) {
315
318
  if (typeof v === "function") continue;
316
- if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping)$/.test(k)
319
+ if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping|includeDomains|excludeDomains)$/.test(k)
317
320
  || /BaseURL$|^.*Model$|^.*ApiKeyEnv$|^enable[A-Z]/.test(k)) resultOptions[k] = v;
318
321
  }
319
322
  // resolveOptions() keeps per-backend settings under opts.backends[id],
@@ -323,6 +326,10 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
323
326
  for (const id of opts.enabledBackends ?? []) {
324
327
  const be = opts.backends?.[id];
325
328
  if (!be || typeof be !== "object") continue;
329
+ // Domain filters live in backend options as well; keying the
330
+ // top-level lists alone would miss a per-backend edit.
331
+ if (Array.isArray(be.includeDomains)) resultOptions[`${id}.includeDomains`] = be.includeDomains;
332
+ if (Array.isArray(be.excludeDomains)) resultOptions[`${id}.excludeDomains`] = be.excludeDomains;
326
333
  // Every per-backend option that changes results must appear here, or
327
334
  // a cache hit inside the TTL masks the edit. baseURLs (plural) is the
328
335
  // SearXNG failover list; leaving it out made instance changes inert.
@@ -348,8 +355,8 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
348
355
  } else {
349
356
  let hitContent = typeof hit.value.content === "string" ? hit.value.content : undefined;
350
357
  // `official` promises no provider-added text (the consumer owns
351
- // presentation), so the diagnostic cache note is gated with the
352
- // header rather than appended unconditionally.
358
+ // presentation), so the diagnostic cache note follows `resultTelemetry`
359
+ // rather than being appended unconditionally.
353
360
  if (opts.resultTelemetry !== false) {
354
361
  const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
355
362
  hitContent = hitContent === undefined ? cacheNote : hitContent + "\n\n" + cacheNote;
@@ -476,9 +483,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
476
483
  : controller.signal;
477
484
  const remainingNow = Number.isFinite(deadline) ? deadline - Date.now() : Number.POSITIVE_INFINITY;
478
485
  if (remainingNow <= 0) {
479
- return Promise.reject(new WebError(`backend "${id}" not started: search budget exhausted`, "WEB_PROVIDER_ERROR"));
486
+ const msg = "search budget exhausted (not started)";
487
+ telemetry.push({ id, ok: false, skipped: true, ms: 0, error: msg });
488
+ return Promise.reject(new WebError(`backend "${id}" ${msg}`, "WEB_PROVIDER_ERROR"));
480
489
  }
481
- const effectiveTimeoutMs = Math.max(1, Math.min(effectiveBackendTimeoutMs(id, backendTimeoutMs), variantBudgetMs, remainingNow));
490
+ const configuredTimeoutMs = effectiveBackendTimeoutMs(id, backendTimeoutMs);
491
+ const effectiveTimeoutMs = Math.max(1, Math.min(configuredTimeoutMs, variantBudgetMs, remainingNow));
492
+ // A call cut below its configured timeout by the shared budget is
493
+ // not an outage: do not fold it into the breaker/health.
494
+ // Startup jitter can shave a millisecond off the configured timeout; only
495
+ // a material cut is budget starvation.
496
+ const budgetClipped = effectiveTimeoutMs < configuredTimeoutMs
497
+ && remainingNow < configuredTimeoutMs - 10;
482
498
  const timeoutId = setTimeout(() => controller.abort(), effectiveTimeoutMs);
483
499
  // A backend that ignores its signal (blackholed TCP, stuck proxy)
484
500
  // must not hold the whole fan-out past its budget. Race the call
@@ -540,14 +556,16 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
540
556
  // and "(unified search aborted)" read as if the USER cancelled.
541
557
  const timedOut = controller.signal.aborted && !(signal && signal.aborted);
542
558
  const reason = timedOut
543
- ? `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
559
+ ? budgetClipped
560
+ ? `backend "${id}" search budget exhausted after ${effectiveTimeoutMs}ms`
561
+ : `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
544
562
  : String(err instanceof Error ? err.message : err);
545
563
  const msg = sanitizeError(reason, 80);
546
564
  telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
547
565
  // A missing API key is a configuration state, not an outage:
548
566
  // folding it would cool the breaker and paint /health red for
549
567
  // a backend the operator can fix in Settings.
550
- if (!(err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING")) {
568
+ if (!budgetClipped && !(err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING")) {
551
569
  health.push({
552
570
  id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
553
571
  rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
@@ -581,7 +599,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
581
599
  const allTelemetry = [];
582
600
  const allFailures = [];
583
601
  // One search-wide budget: sequential variants must not multiply the
584
- // per-backend timeout into N × 30s (which also exceeds the host's 30s
602
+ // per-backend timeout into N × 24s (which also exceeds the host's 30s
585
603
  // tool deadline). Later variants get only the time still left.
586
604
  const searchBudgetMs = Math.max(1, Number(opts.backendTimeoutMs) || 24000);
587
605
  const searchDeadline = Date.now() + searchBudgetMs;
@@ -606,6 +624,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
606
624
  query: variantQuery,
607
625
  maxResults: backendMaxResults,
608
626
  ...(coverage ? { deepCoverage: true } : {}),
627
+ // SearXNG paging is opt-in and never combines with internal
628
+ // multi-query (each variant already costs one request).
629
+ pageLimit: coverage && !useMulti ? 2 : 1,
609
630
  };
610
631
  const fold = await fanoutVariant(variantReq, share, searchDeadline);
611
632
  for (const outcome of fold.health) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-websearch",
3
- "version": "2.10.0",
3
+ "version": "2.11.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",