@240xu/dsh-websearch 2.9.1 → 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,14 +92,16 @@ pnpm install
92
92
  > 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
93
93
 
94
94
 
95
- 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数;缓存、熔断、历史、多查询、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
 
99
99
  | 字段 | 默认 | 说明 |
100
100
  |---|---|---|
101
101
  | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
- | `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
102
+ | `numResults` | 10 | 每次搜索返回结果数(1-100;Exa 上限 100,official 档沿用宿主工具的条数上限) |
103
+ | `includeDomains` | 空 | 仅约束 OpenAI/Anthropic 原生后端(最多 20;其余后端不支持,合并结果仍可能来自其他域名) |
104
+ | `excludeDomains` | 空 | 排除这些域名(最多 20;Anthropic 仅发 allow,OpenAI 两个列表同时发送) |
103
105
  | `concurrency` | 6 | 并发后端数(1-10) |
104
106
  | `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
105
107
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
@@ -170,6 +172,7 @@ pnpm install
170
172
 
171
173
  ### 4. per-backend 超时上限(P2)
172
174
 
175
+ - SearXNG 仅在 `thorough`/`deepCoverage` 且未开启内部多查询时翻第 2 页(单实例;第 2 页 429/5xx 会回退到第 1 页并冷却 60 秒);多实例 failover 始终只取第 1 页。
173
176
  - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
174
177
 
175
178
  ## v2.7.3 兼容修复 | What's new in v2.7.3
@@ -203,7 +206,9 @@ pnpm install
203
206
  - 相同 **(整形后查询 + filters + maxResults + 启用后端集合)** 在 TTL 内直接命中缓存,不打任何后端;`sources` 与首次搜索完全一致。
204
207
  - 命中时 `content` 追加一行 `[websearch cache] cache hit, age Ns`。
205
208
  - 存储位置:`$DSH_HOME/cache/websearch/results/`,单条目一个 JSON 文件,tmp+rename 原子写,超出上限按最旧淘汰;任何 fs 错误都被吞掉,缓存坏了绝不影响搜索。
206
- - 设置:`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`)。
207
212
 
208
213
  ### 2. 后端熔断器(默认开,保守阈值)
209
214
 
@@ -264,7 +269,7 @@ tests/
264
269
  node --test tests/
265
270
  ```
266
271
 
267
- 当前 218/218 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` 单独跑)。
268
273
 
269
274
  ### Test-only dependencies
270
275
 
@@ -277,7 +282,7 @@ live service before running the suite:
277
282
  ```bash
278
283
  bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
279
284
  find node_modules/@deepseek-ai -xtype l # expect no output
280
- node --test tests/*.test.js # 218/218
285
+ node --test tests/*.test.js # 225/225
281
286
  ```
282
287
 
283
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,6 +86,15 @@ export function createAnthropicLikeBackend(spec) {
86
86
  const maxUses = options.maxUses ?? 5;
87
87
  const endpoint = `${baseURL.replace(/\/$/, "")}/messages`;
88
88
 
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
+ : {};
89
98
  const body = {
90
99
  model,
91
100
  max_tokens: maxTokens,
@@ -100,7 +109,7 @@ export function createAnthropicLikeBackend(spec) {
100
109
  ],
101
110
  },
102
111
  ],
103
- tools: [{ type: toolName, name: "web_search", max_uses: maxUses }],
112
+ tools: [{ type: toolName, name: "web_search", max_uses: maxUses, ...domainArgs }],
104
113
  };
105
114
 
106
115
  hooks.recordRequest?.({
@@ -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) {
@@ -41,7 +41,7 @@ export const exaBackend = {
41
41
  async search(request, signal, options, hooks = {}) {
42
42
  const args = {
43
43
  query: request.query,
44
- numResults: request.maxResults ?? 8,
44
+ numResults: Math.max(1, Math.min(Number(request.maxResults) || 10, 100)),
45
45
  };
46
46
  // v2.8.0: category inference — deepCoverage-gated like tavily (searchDepth
47
47
  // advanced) and searxng (category sweep): 2.8.1 审计发现此处漏了门控,
@@ -78,7 +78,7 @@ export const exaBackend = {
78
78
  throw new WebError(`exa returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
79
79
  }
80
80
 
81
- const sources = parseExaResult(result, request.maxResults ?? 8);
81
+ const sources = parseExaResult(result, Math.max(1, Math.min(Number(request.maxResults) || 10, 100)));
82
82
  hooks.recordOutcome?.({ status: "ok", count: sources.length });
83
83
 
84
84
  return { sources, content: undefined, truncated: false };
@@ -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,17 @@ export const openaiBackend = {
53
53
  const model = options.model || "gpt-4o";
54
54
  const endpoint = `${baseURL}/responses`;
55
55
 
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
+ : {};
56
61
  const body = {
57
62
  model,
58
- tools: [{ type: "web_search" }],
63
+ tools: [{
64
+ type: "web_search",
65
+ ...(Object.keys(domainFilters).length > 0 ? { filters: domainFilters } : {}),
66
+ }],
59
67
  input: request.query,
60
68
  };
61
69
 
@@ -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/cache.js CHANGED
@@ -30,13 +30,13 @@ export const CACHE_DEFAULTS = {
30
30
  /**
31
31
  * Compute the deterministic cache key for a search.
32
32
  * The key covers the shaped query, filters, the effective maxResults, the
33
- * enabledBackends set (sorted), the cache mode, and every non-function result
34
- * option: switching the backend mix or editing a result-affecting setting
35
- * must never serve a stale result within the TTL (arch-review P1-1).
33
+ * enabledBackends selection **in fan-out order**, the cache mode, and every
34
+ * non-function result option: switching the mix or reordering it can change
35
+ * which duplicate's title/snippet wins, so both must miss (arch-review P1-1).
36
36
  * Pure function; exported for tests and host reuse.
37
37
  */
38
38
  export function cacheKeyFor({ query, filters, maxResults, backends, mode, resultOptions }) {
39
- const backendSet = Array.isArray(backends) ? [...backends].sort().join(",") : "";
39
+ const backendSet = Array.isArray(backends) ? backends.join(",") : "";
40
40
  let shaped = {};
41
41
  if (resultOptions && typeof resultOptions === "object") {
42
42
  const keys = Object.keys(resultOptions).filter((k) =>
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
@@ -680,12 +675,14 @@ window.__ModuleLoader__.load({
680
675
  // Mirror the server schema bounds client-side so bad input is
681
676
  // caught in the UI instead of a failed Host round-trip.
682
677
  const BOUNDS = {
683
- numResults: [1, 50],
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";
@@ -161,8 +174,8 @@ export const Config = z.object({
161
174
  // Global
162
175
  intervention: z.union(["official", "balanced", "thorough"]).default("balanced")
163
176
  .description("搜索介入程度【策略】:official=只做官方 provider 该做的(原样查询、不加结果头/遥测、沿用工具的条数上限);balanced=确定性去噪 + 去重/遥测(默认);thorough=额外启用相关性重排与深度覆盖(内部多查询仍是独立开关,默认关)"),
164
- numResults: z.number().step(1).min(1).max(50).default(10)
165
- .description("每次搜索返回的最大结果数(official 档沿用宿主工具的条数上限)"),
177
+ numResults: z.number().step(1).min(1).max(100).default(10)
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)
@@ -175,6 +188,10 @@ export const Config = z.object({
175
188
  .description("搜索语言(如 en、zh-CN;留空用各后端默认)"),
176
189
  safeSearch: z.boolean().default(true)
177
190
  .description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
191
+ includeDomains: z.string().default("")
192
+ .description("只约束 OpenAI/Anthropic 原生后端的允许域名(逗号/空格分隔,最多 20 个);其余后端不支持,合并结果仍可能来自其他域名"),
193
+ excludeDomains: z.string().default("")
194
+ .description("排除这些域名(逗号/空格分隔,最多 20 个);Anthropic 仅发 allowed(include 优先),OpenAI 两个列表同时发送由服务端裁决"),
178
195
  dedupStrategy: z.union(["url", "url+title"]).default("url")
179
196
  .description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
180
197
  rerank: z.boolean().default(false)
@@ -197,7 +214,7 @@ export const Config = z.object({
197
214
  breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
198
215
  .description("熔断阈值【熔断】:连续失败多少次后触发(默认 3 次)"),
199
216
  breakerCooldownMs: z.number().step(1000).min(0).max(3600000).default(BREAKER_DEFAULTS.cooldownMs)
200
- .description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;设为 0 表示关闭冷却(熔断仅计数)"),
217
+ .description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;0 关闭按阈值的冷却,带 Retry-After 的 429 仍按该窗口冷却"),
201
218
  historyEnabled: z.boolean().default(true)
202
219
  .description("记录搜索历史【历史】:只追加,最多 50 条;可在设置 → 搜索 中查看与清空"),
203
220
 
@@ -327,6 +344,31 @@ for (const [key, label] of Object.entries(FIELD_LABELS)) {
327
344
  * serves its NEXT search with. Key resolution: credentialRef -> credentials
328
345
  * service -> env.
329
346
  */
347
+ /** Normalize a comma/space-domain setting into lowercase bare hostnames. */
348
+ function normalizeDomainList(raw) {
349
+ if (typeof raw !== "string" || raw.trim() === "") return [];
350
+ const out = [];
351
+ for (const piece of raw.split(/[,,、;;\s]+/)) {
352
+ const item = piece.trim().toLowerCase();
353
+ if (item === "") continue;
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);
358
+ try {
359
+ const u = new URL(item.includes("://") ? item : "https://" + host);
360
+ host = u.hostname;
361
+ } catch { /* keep the raw token and validate below */ }
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;
366
+ if (!out.includes(host)) out.push(host);
367
+ if (out.length >= 20) break;
368
+ }
369
+ return out;
370
+ }
371
+
330
372
  export function resolveOptions(ctx, config) {
331
373
  // 1. Determine enabled backends: explicit list > toggles > env > defaults.
332
374
  // The four keyless toggles default to true, so the env fallback is reachable
@@ -361,6 +403,14 @@ export function resolveOptions(ctx, config) {
361
403
  enabledBackends = [...new Set(enabledBackends)];
362
404
 
363
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;
364
414
  const backends = {};
365
415
  for (const id of ALL_BACKENDS) {
366
416
  const keyEnvName = config?.[`${id}ApiKeyEnv`] ?? DEFAULT_KEY_ENV[id];
@@ -377,15 +427,35 @@ export function resolveOptions(ctx, config) {
377
427
  : [],
378
428
  } : {}),
379
429
  safeSearch: config?.safeSearch !== false,
430
+ includeDomains,
431
+ excludeDomains,
380
432
  label: DEFAULT_LABELS[id] ?? id,
381
433
  requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
382
434
  optionalKey: OPTIONAL_KEY_IDS.has(id),
383
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
+ })(),
384
443
  resolveApiKey: async () => {
385
- const credentials = ctx.get("credentials");
386
- if (credentials !== undefined) return (await credentials.resolve(ref))?.value;
387
- const ambient = launchEnvironmentOf(ctx).get(ref);
388
- 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
+ }
389
459
  },
390
460
  };
391
461
  }
@@ -432,6 +502,9 @@ export function resolveOptions(ctx, config) {
432
502
  // invisibly.
433
503
  multiQueryEnabled: !official && config?.multiQueryEnabled === true,
434
504
  deepCoverage: thorough || (!official && config?.deepCoverage === true),
505
+ includeDomains,
506
+ excludeDomains,
507
+ domainFilterError,
435
508
  filters: {
436
509
  recency: typeof config?.recency === "string" && config.recency !== "any" ? config.recency : undefined,
437
510
  lang: language.length > 0 ? language : undefined,
@@ -460,6 +533,14 @@ export function resolveStoreDir(env = process.env, fallbackHome = os.homedir())
460
533
  * model names / credential references in the DSH Settings panel.
461
534
  */
462
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
+ }
463
544
  let current = () => config;
464
545
  /** 0.2.x SettingsForms instance, captured for the browser settings bridge. */
465
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) {
@@ -654,7 +675,29 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
654
675
  // finished by this point so the array no longer grows. History counts
655
676
  // unique backends, not attempts: multi-query fans one backend out once
656
677
  // per variant, which used to report `backendsTotal` as variants × backends.
657
- const okCount = allTelemetry.filter((t) => t.ok).length;
678
+ // One display segment per backend, not per variant: a multi-query
679
+ // search otherwise repeats the same backend N times and can hide a
680
+ // backend beyond the 12-slot cap while health/history show it once.
681
+ const foldedTelemetry = [];
682
+ const telemetryById = new Map();
683
+ for (const t of allTelemetry) {
684
+ const prev = telemetryById.get(t.id);
685
+ if (prev === undefined) {
686
+ const copy = { ...t };
687
+ telemetryById.set(t.id, copy);
688
+ foldedTelemetry.push(copy);
689
+ continue;
690
+ }
691
+ if (t.ok === true) {
692
+ prev.ok = true;
693
+ prev.count = Math.max(prev.count ?? 0, t.count ?? 0);
694
+ prev.error = undefined;
695
+ } else if (prev.ok !== true) {
696
+ prev.error = t.error;
697
+ }
698
+ prev.ms = Math.max(prev.ms ?? 0, t.ms ?? 0);
699
+ }
700
+ const okCount = foldedTelemetry.filter((t) => t.ok).length;
658
701
  const historyOk = new Set(allTelemetry.filter((t) => t.ok).map((t) => t.id)).size;
659
702
  const historyTotal = new Set(allTelemetry.map((t) => t.id)).size;
660
703
 
@@ -716,7 +759,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
716
759
  // labels (route6 P2); the raw text remains the fallback, and a
717
760
  // backend that just crossed the breaker threshold is annotated as
718
761
  // cooled on this same line.
719
- const parts = allTelemetry
762
+ const parts = foldedTelemetry
720
763
  .slice(0, 12)
721
764
  .map((t) => {
722
765
  if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
@@ -725,7 +768,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
725
768
  return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "") + (cooledNow ? " " + cooledNow : "");
726
769
  })
727
770
  .concat(cooledParts);
728
- if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
771
+ if (foldedTelemetry.length > 12) parts.push(`… +${foldedTelemetry.length - 12}`);
729
772
  const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
730
773
  outContent = outContent === undefined ? line : outContent + "\n\n" + line;
731
774
  }
@@ -752,12 +795,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
752
795
  emptyContent = header + "\n\n" + emptyContent;
753
796
  }
754
797
  if (opts.resultTelemetry !== false && allFailures.length > 0) {
755
- const parts = allTelemetry.slice(0, 12).map((t) => {
798
+ const parts = foldedTelemetry.slice(0, 12).map((t) => {
756
799
  if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
757
800
  const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
758
801
  return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "");
759
802
  });
760
- if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
803
+ if (foldedTelemetry.length > 12) parts.push(`… +${foldedTelemetry.length - 12}`);
761
804
  const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
762
805
  emptyContent = emptyContent === undefined ? line : emptyContent + "\n\n" + line;
763
806
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-websearch",
3
- "version": "2.9.1",
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",