@240xu/dsh-websearch 2.8.9 → 2.9.1

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
@@ -5,7 +5,7 @@
5
5
 
6
6
  > Aggregated web search provider for [DeepSeek Harness](https://github.com/deepseek-ai/dsh) — one plugin id `unified` that fans out to thirteen backends concurrently, merges + URL-dedups results, and stays usable even when some backends go down.
7
7
 
8
- A pure-Cordis drop-in: registers ONE provider at `ctx.web` so the `dsh-web` selection rule never fires `WEB_PROVIDER_AMBIGUOUS`. Zero-config search out of the box (Exa + Parallel + DuckDuckGo + SearXNG are keyless); API-key backends (DeepSeek / Anthropic / OpenAI / Brave / Tavily / Serper / Mojeek) auto-activate once their key is supplied via the credentials service or env.
8
+ A pure-Cordis drop-in: registers one provider id at `ctx.web`; with `searchProvider: unified` pinned (see Install), the `dsh-web` selection rule never has to choose between it and the host's DeepSeek search providers. Zero-config search out of the box (Exa + Parallel + DuckDuckGo + SearXNG are keyless); API-key backends (DeepSeek / Anthropic / OpenAI / Brave / Tavily / Serper / Mojeek) auto-activate once their key is supplied via the credentials service or env.
9
9
 
10
10
  ---
11
11
 
@@ -92,7 +92,7 @@ pnpm install
92
92
  > 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
93
93
 
94
94
 
95
- 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),全部字段扁平化、开箱可编辑:
95
+ 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数;缓存、熔断、历史、多查询、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 profile patch 配置:
96
96
 
97
97
  **全局**
98
98
 
@@ -101,7 +101,7 @@ pnpm install
101
101
  | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
102
  | `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
103
103
  | `concurrency` | 6 | 并发后端数(1-10) |
104
- | `backendTimeoutMs` | 30000 | 单后端超时毫秒 |
104
+ | `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
105
105
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
106
106
  | `language` | 空 | 搜索语言,如 en、zh-CN(SearXNG/Brave/Serper 支持) |
107
107
  | `safeSearch` | true | 安全搜索开关(SearXNG/Brave 支持) |
@@ -170,7 +170,7 @@ pnpm install
170
170
 
171
171
  ### 4. per-backend 超时上限(P2)
172
172
 
173
- - `ddg` / `searxng` 专属超时上限 5s(`min(5s, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
173
+ - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
174
174
 
175
175
  ## v2.7.3 兼容修复 | What's new in v2.7.3
176
176
 
@@ -221,13 +221,13 @@ pnpm install
221
221
 
222
222
  ## Design | 设计
223
223
 
224
- - **One provider, no ambiguity**: a single `registeredSearchProvider({id:"unified"})` — the `dsh-web` seam's selection rule picks it unambiguously, and `search()` caps `maxResults` itself.
224
+ - **One provider pin, no ambiguity**: `registeredSearchProvider({id:"unified"})` plus `searchProvider: unified` (Install) means the seam never chooses between this provider and the host's DeepSeek search providers; `search()` caps `maxResults` itself.
225
225
  - **`Promise.allSettled` fan-out**: every enabled + available backend fires concurrently; a single backend failure is demoted to a soft `null` so the rest still contribute — only when ALL fail does the provider throw `WEB_PROVIDER_ERROR`.
226
226
  - **Per-backend abort demotion**: a single backend aborting becomes soft-null; the provider only rethrows `WEB_ABORTED` when the caller's own `AbortSignal` fires.
227
227
  - **Dedup strategies**: `url` keeps the historical URL-key merge with cross-backend field fill-in; `url+title` additionally collapses same-story syndicated mirrors (title Jaccard >= 0.9, CJK-aware tokenizer) while still enriching the kept entry.
228
228
  - **Deterministic rerank (optional)**: query-term overlap scoring (title x3 / snippet x2 / URL x1); stable ties preserve fan-out priority — same input always yields the same order.
229
229
  - **Honest timeouts**: each backend runs under an internal abort controller merged into the caller signal; when only the internal timer fires, the failure is reclassified as WEB_PROVIDER_ERROR ("backend <id> timed out") instead of being masked as a user cancellation.
230
- - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 30s) caps each backend.
230
+ - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 24s) caps each backend.
231
231
  - **Streamable-http MCP, custom handshake**: `lib/util/mcp-client.js` implements `initialize → notifications/initialized → tools/call` with `Mcp-Session-Id` header caching and `MCP-Protocol-Version` after initialization, against Exa, Parallel, Firecrawl and TinyFish — no dependency on the full MCP SDK.
232
232
  - **Host-logger diagnostics**: each backend routes request/outcome through lib/util/log.js to the host logger (ctx.logger), best-effort and never thrown - deliberately NOT session events: the session event vocabulary is a closed set third-party plugins must not extend (an unknown envelope type makes the whole session log unreadable).
233
233
 
@@ -264,7 +264,7 @@ tests/
264
264
  node --test tests/
265
265
  ```
266
266
 
267
- 当前 211/211 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
267
+ 当前 218/218 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
268
268
 
269
269
  ### Test-only dependencies
270
270
 
@@ -277,7 +277,7 @@ live service before running the suite:
277
277
  ```bash
278
278
  bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
279
279
  find node_modules/@deepseek-ai -xtype l # expect no output
280
- node --test tests/*.test.js # 211/211
280
+ node --test tests/*.test.js # 218/218
281
281
  ```
282
282
 
283
283
  v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
@@ -290,7 +290,7 @@ v2.7.0 缓存/熔断/历史三项的依据与刻意取舍(含查证过的反
290
290
  2. **缓存失效(TTL-only vs 事件驱动)**:Cloudflare「Retention vs Freshness (TTL)」https://developers.cloudflare.com/cache/concepts/retention-vs-freshness/ 与「Revalidation」https://developers.cloudflare.com/cache/concepts/revalidation/ 。搜索结果没有可靠的原站变更信号可订阅(网页索引持续变化),事件驱动失效无锚点;TTL-only + 把 TTL 做成设置项(默认 900s)+ key 纳入后端组合,是"可接受的最终一致性"。取舍:900s 内索引更新不可见——对搜索场景可接受,且用户可调低。
291
291
  3. **原子写(tmp + renameSync)**:POSIX 上 rename(2) 原子替换(Node 文档:newPath 已存在时覆盖);Windows 上 libuv 将 fs.rename 映射为 MoveFileExW(MOVEFILE_REPLACE_EXISTING)(libuv#283 https://github.com/joyent/libuv/issues/283 ,LWN 讨论 https://lwn.net/Articles/682988/ 指出 MS 文档不承诺该调用的原子性)。**结论:POSIX 双端原子;Windows 实践上等价但官方文档不背书**——因此本插件在写入端额外做了兜底:读端永远校验 JSON 完整性、坏条目按 miss 处理并删除,即使 Windows 上出现半写状态也不会返回坏数据。
292
292
  4b. **查全查多(v2.8.0)**:Tavily Search API(`search_depth: advanced` 2 credits、`max_results` 0-20、`include_answer`、topic=news 时间加权)https://docs.tavily.com/api-reference/endpoint/search ;Exa Search API(type 分类检索、category 枚举、livecrawl;注意 2026 版 coding-agent 指南声明 neural 为 legacy 术语、且告诫勿臆造 category 值——本插件只注入 OpenAPI 枚举内的高置信值)https://exa.ai/docs/reference/search-api-guide-for-coding-agents 与 https://github.com/exa-labs/openapi-spec/blob/master/exa-openapi-spec.yaml ;SearXNG Search API(`categories` 逗号多类目、`language`)https://docs.searxng.org/dev/search_api.html ;Brave Search API(`freshness`、`result_filter`,本轮仅调研未接线)https://api-dashboard.search.brave.com/app/documentation 。多查询融合:RRF 出自 Cormack et al. 2009,RAG-Fusion 实现 https://github.com/Raudaschl/rag-fusion ;HyDE https://arxiv.org/abs/2212.10496 ;**门控依据** arXiv:2404.01037(盲目多查询劣化)——因此 multiQuery 默认关、启发式从严、原查询全权重参与。
293
- 4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA)是拖尾主力,5s 上限取「P50 成功延迟的一个数量级」。
293
+ 4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA)是拖尾主力,8s 上限取「P50 成功延迟的一个数量级」。
294
294
  4d. **搜索历史隐私**:Article 29 Working Party 意见书 WP148 https://ec.europa.eu/justice/article-29/documentation/opinion-recommendation/files/2008/wp148_en.pdf 认定查询日志(query + 时间 + 来源标识)属个人数据;EFF 六条自保建议 https://w2.eff.org/Privacy/search/searchtips.pdf 的第一条是"别在搜索词里放 PII"——说明 query 天然可能携带 PII(人名、账号、地址)。本插件的取舍:历史只存 {query, time, resultCount, backendsOk/Total}(无 IP、无 cookie、无结果 URL)、环形 50 条自动滚动即短保留、本机存储不出网、提供 historyEnabled 开关与 POST clear 端点。**未做 query 脱敏**:脱敏会破坏"查看最近搜了什么"的核心用途,且本机单用户场景下该数据本就在 DSH 会话日志里存在;若未来历史跨设备同步,脱敏/加密是上线前置条件。
295
295
 
296
296
  ## License | 许可
@@ -21,7 +21,7 @@ import { webErrorFromResponse } from "../util/web-error.js";
21
21
  import { egressFetch } from "../util/egress-fetch.js";
22
22
  import { describeError } from "../util/describe-error.js";
23
23
 
24
- /** Attribution header; bumped with the package version. */
24
+ /** Attribution header token; stable across releases, not derived from package.json. */
25
25
  const UA = "dsh-websearch/2.3";
26
26
 
27
27
  /**
@@ -29,7 +29,7 @@ export const braveBackend = {
29
29
 
30
30
  const apiKey = await backendOpts.resolveApiKey?.();
31
31
  if (!apiKey) {
32
- throw new WebError("Brave Search: API key not configured", "WEB_PROVIDER_UNAVAILABLE");
32
+ throw new WebError("Brave Search: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
33
33
  }
34
34
 
35
35
  const baseURL = backendOpts.baseURL ?? BRAVE_ENDPOINT;
@@ -100,7 +100,9 @@ export function parseBraveResult(data, maxResults) {
100
100
  url: item.url,
101
101
  ...(item.title ? { title: item.title } : {}),
102
102
  ...(item.description ? { snippet: item.description } : {}),
103
- ...(item.age ? { publishedAt: item.age } : {}),
103
+ // Brave's `age` is human text ("3 days ago") unless it is an ISO date; the
104
+ // seam declares publishedAt ISO-8601, so only pass a date-shaped value.
105
+ ...(typeof item.age === "string" && /^\d{4}-\d{2}-\d{2}/.test(item.age) ? { publishedAt: item.age } : {}),
104
106
  });
105
107
  }
106
108
  return sources;
@@ -117,7 +117,8 @@ function joinHighlights(block) {
117
117
  const tail = block.slice(m.index + m[0].length);
118
118
  const bullets = [...tail.matchAll(/^\s+-\s+(.+)$/gm)].map((b) => b[1].trim());
119
119
  if (bullets.length === 0) return undefined;
120
- return bullets.join(" … ");
120
+ // Bound what reaches the model: highlights are excerpts, not full text.
121
+ return bullets.join(" … ").slice(0, 400);
121
122
  }
122
123
 
123
124
  export default exaBackend;
@@ -43,7 +43,9 @@ export const firecrawlBackend = {
43
43
  // would consume more of the hosted keyless quota.
44
44
  const args = {
45
45
  query: request.query,
46
- limit: 8,
46
+ // v2 limit defaults to 10 and accepts up to 100; the old fixed 8
47
+ // silently under-delivered a 10-result request.
48
+ limit: Math.max(1, Math.min(Number(request.maxResults) || 10, 100)),
47
49
  };
48
50
  // resolveOptions() supplies an async resolveApiKey(); a literal apiKey is
49
51
  // accepted for stubs (same split as anthropic-like.js). Resolution failure
@@ -116,7 +118,7 @@ export function parseFirecrawlResult(result, maxResults) {
116
118
  const source = { url: item.url };
117
119
  if (typeof item.title === "string" && item.title.length > 0) source.title = item.title;
118
120
  if (typeof item.description === "string" && item.description.length > 0) {
119
- source.snippet = item.description;
121
+ source.snippet = item.description.slice(0, 400);
120
122
  }
121
123
  sources.push(source);
122
124
  if (sources.length >= maxResults) break;
@@ -28,7 +28,7 @@ export const mojeekBackend = {
28
28
 
29
29
  const apiKey = await backendOpts.resolveApiKey?.();
30
30
  if (!apiKey) {
31
- throw new WebError("Mojeek: API key not configured", "WEB_PROVIDER_UNAVAILABLE");
31
+ throw new WebError("Mojeek: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
32
32
  }
33
33
 
34
34
  const baseURL = backendOpts.baseURL ?? MOJEEK_ENDPOINT;
@@ -89,7 +89,7 @@ export const searxngBackend = {
89
89
  // Retry-After and drives the breaker's quota cooldown. Taking whichever
90
90
  // instance failed LAST would discard it whenever a later instance failed
91
91
  // on plain network grounds.
92
- const severity = (err) => (err?.code === "RATE_LIMIT" || err?.code === "QUOTA_EXCEEDED" || err?.rateLimited === true ? 2 : 1);
92
+ const severity = (err) => (err?.code === "RATE_LIMIT" || err?.code === "QUOTA" || err?.rateLimited === true ? 2 : 1);
93
93
  // Each instance attempt must fit inside what is left of the backend budget:
94
94
  // three public instances at 4.5s each would otherwise need 13.5s while the
95
95
  // provider abandons the backend at 8s, and the per-instance detail is lost
@@ -29,7 +29,7 @@ export const serperBackend = {
29
29
 
30
30
  const apiKey = await backendOpts.resolveApiKey?.();
31
31
  if (!apiKey) {
32
- throw new WebError("Serper: API key not configured", "WEB_PROVIDER_UNAVAILABLE");
32
+ throw new WebError("Serper: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
33
33
  }
34
34
 
35
35
  const baseURL = backendOpts.baseURL ?? SERPER_ENDPOINT;
@@ -114,7 +114,9 @@ export function parseSerperResult(data, maxResults) {
114
114
  url: item.link,
115
115
  ...(item.title ? { title: item.title } : {}),
116
116
  ...(item.snippet ? { snippet: item.snippet.slice(0, 500) } : {}),
117
- ...(item.date ? { publishedAt: item.date } : {}),
117
+ // `date` is often relative ("2 days ago"); only ISO-shaped values are
118
+ // valid for the seam's ISO-8601 publishedAt.
119
+ ...(typeof item.date === "string" && /^\d{4}-\d{2}-\d{2}/.test(item.date) ? { publishedAt: item.date } : {}),
118
120
  });
119
121
  }
120
122
 
@@ -29,7 +29,7 @@ export const tavilyBackend = {
29
29
 
30
30
  const apiKey = await backendOpts.resolveApiKey?.();
31
31
  if (!apiKey) {
32
- throw new WebError("Tavily: API key not configured", "WEB_PROVIDER_UNAVAILABLE");
32
+ throw new WebError("Tavily: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
33
33
  }
34
34
 
35
35
  const baseURL = backendOpts.baseURL ?? TAVILY_ENDPOINT;
package/lib/cache.js CHANGED
@@ -29,11 +29,10 @@ export const CACHE_DEFAULTS = {
29
29
 
30
30
  /**
31
31
  * Compute the deterministic cache key for a search.
32
- * Includes the enabledBackends selection set (sorted): switching the backend
33
- * mix must never serve a stale result produced by a different combination
34
- * (arch-review P1-1). Also includes the options that change the merged
35
- * result (safeSearch, rerank, dedupStrategy, per-backend base URLs and
36
- * models) so editing a setting is not masked by a hit within the TTL.
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).
37
36
  * Pure function; exported for tests and host reuse.
38
37
  */
39
38
  export function cacheKeyFor({ query, filters, maxResults, backends, mode, resultOptions }) {
@@ -72,12 +71,18 @@ function ageSeconds(record, nowMs) {
72
71
  export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntries = CACHE_DEFAULTS.maxEntries }) {
73
72
  // ttlMs may be a number or () => number (settings can change at runtime).
74
73
  const ttlOf = typeof ttlMs === "function" ? ttlMs : () => Number(ttlMs) || 0;
74
+ // ttl 0 means "do not store": no read, no write, no diagnostic note.
75
+ const noStore = () => {
76
+ try { return Math.max(0, Number(ttlOf()) || 0) === 0; } catch { return false; }
77
+ };
75
78
  const cap = Math.max(1, Math.floor(Number(maxEntries) || CACHE_DEFAULTS.maxEntries));
76
79
 
77
80
  const fileFor = (key) => path.join(dir, `${key}.json`);
78
81
 
79
82
  function ensureDir() {
80
- mkdirSync(dir, { recursive: true });
83
+ // Query text and results are user data; keep them owner-only.
84
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
85
+ try { chmodSync(dir, 0o700); } catch { /* existing dir owned by another mode */ }
81
86
  }
82
87
 
83
88
  /**
@@ -87,8 +92,14 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
87
92
  */
88
93
  function atomicWrite(file, data) {
89
94
  const tmp = `${file}.${process.pid}.tmp`;
90
- writeFileSync(tmp, data, "utf8");
91
- renameSync(tmp, file);
95
+ try {
96
+ writeFileSync(tmp, data, { encoding: "utf8", mode: 0o600 });
97
+ renameSync(tmp, file);
98
+ } catch (err) {
99
+ // A failed rename must not leave an orphan tmp counted outside the cap.
100
+ try { unlinkSync(tmp); } catch { /* already gone */ }
101
+ throw err;
102
+ }
92
103
  }
93
104
 
94
105
  /** List current entries as [{key, file, mtime}] sorted oldest first. */
@@ -121,7 +132,21 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
121
132
  // an over-cap write pays the stat() of every entry. Trimming to a low-water
122
133
  // mark (10%, at least one) keeps that scan amortized over ~cap/10 writes
123
134
  // instead of running synchronously on every single write.
135
+ /** Remove crash-orphaned tmp files; the cap only counts `.json`. */
136
+ function sweepTmp(maxAgeMs = 3600_000) {
137
+ if (!existsSync(dir)) return;
138
+ const now = Date.now();
139
+ for (const name of readdirSync(dir)) {
140
+ if (!name.includes(".tmp")) continue;
141
+ const file = path.join(dir, name);
142
+ try {
143
+ if (now - statSync(file).mtimeMs >= maxAgeMs) unlinkSync(file);
144
+ } catch { /* raced */ }
145
+ }
146
+ }
147
+
124
148
  function evict() {
149
+ sweepTmp();
125
150
  if (countEntries() <= cap) return;
126
151
  const entries = listEntries();
127
152
  const lowWater = Math.max(1, cap - Math.max(1, Math.ceil(cap * 0.1)));
@@ -137,25 +162,32 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
137
162
  * @returns {{ value: object, age: number } | null} age in seconds; null on miss/expiry
138
163
  */
139
164
  get(key, nowMs = Date.now()) {
165
+ if (noStore()) return null;
166
+ const file = fileFor(key);
167
+ let record;
140
168
  try {
141
- const file = fileFor(key);
142
169
  if (!existsSync(file)) return null;
143
- const record = JSON.parse(readFileSync(file, "utf8"));
144
- if (!record || typeof record !== "object" || !record.value) return null;
145
- const age = ageSeconds(record, nowMs);
146
- const ttl = Math.max(0, Number(ttlOf()) || 0);
147
- if (age * 1000 > ttl) {
148
- try { unlinkSync(file); } catch { /* raced */ }
149
- return null;
150
- }
151
- return { value: record.value, age };
170
+ record = JSON.parse(readFileSync(file, "utf8"));
152
171
  } catch {
172
+ // Corrupt/unreadable entry: drop it. A transient TTL error below must
173
+ // NOT delete a valid entry, so it is outside this catch.
174
+ try { unlinkSync(file); } catch { /* raced */ }
175
+ return null;
176
+ }
177
+ if (!record || typeof record !== "object" || !record.value) {
178
+ try { unlinkSync(file); } catch { /* raced */ }
153
179
  return null;
154
180
  }
181
+ let ttl;
182
+ try { ttl = Math.max(0, Number(ttlOf()) || 0); } catch { return null; }
183
+ const age = ageSeconds(record, nowMs);
184
+ if (age * 1000 > ttl) return null;
185
+ return { value: record.value, age };
155
186
  },
156
187
 
157
188
  /** Store a result (best-effort; fs errors are swallowed). */
158
189
  set(key, value, nowMs = Date.now()) {
190
+ if (noStore()) return;
159
191
  try {
160
192
  ensureDir();
161
193
  atomicWrite(fileFor(key), JSON.stringify({ key, time: nowMs, value }));
@@ -168,6 +200,7 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
168
200
  /** Drop every cached entry (best-effort). */
169
201
  clear() {
170
202
  try {
203
+ sweepTmp(0);
171
204
  for (const e of listEntries()) {
172
205
  try { unlinkSync(e.file); } catch { /* raced */ }
173
206
  }