@240xu/dsh-websearch 2.8.8 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,28 +3,16 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@240xu/dsh-websearch.svg)](https://www.npmjs.com/package/@240xu/dsh-websearch)
4
4
  [![license](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
5
5
 
6
- > Aggregated web search provider for [DeepSeek Harness](https://github.com/deepseek-ai/dsh) — one plugin id `unified` that fans out to eleven backends concurrently, merges + URL-dedups results, and stays usable even when some backends go down.
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
 
12
- DSH([DeepSeek Harness](https://github.com/deepseek-ai/dsh))原生插件:向 `ctx.web` 注册**唯一**的聚合搜索 provider `unified`,内置十一后端并发 fan-out,合并 + URL 去重后返回——即使部分后端宕机仍可用。
12
+ DSH([DeepSeek Harness](https://github.com/deepseek-ai/dsh))原生插件:向 `ctx.web` 注册**唯一**的聚合搜索 provider `unified`,内置十三后端并发 fan-out,合并 + URL 去重后返回——即使部分后端宕机仍可用。
13
13
 
14
14
  纯 Cordis 直插:只注册一个 provider,所以 `dsh-web` 的选择规则永远不会触发 `WEB_PROVIDER_AMBIGUOUS`。**零配置即可搜索**——Exa + Parallel + DuckDuckGo + SearXNG 四者皆无 key、开箱即用;DeepSeek / Anthropic / OpenAI / Brave / Tavily / Serper / Mojeek 在提供 API key 后自动激活。
15
15
 
16
-
17
- ## 10 秒速查
18
-
19
- ```sh
20
- dsh plugin --profile web add @240xu/dsh-websearch
21
- # 重启 dsh web 后,在 设置 → Web Search 选择 unified
22
- ```
23
-
24
- - 不想逐个装:`dsh plugin --profile web add @240xu/dsh-plugin-hub`(会带入本插件)
25
- - 卸载:`dsh plugin --profile web remove @240xu/dsh-websearch`
26
- - 零 Key 可用:Exa / Parallel / DuckDuckGo / SearXNG;其余后端配 Key 后自动启用
27
-
28
16
  ## Backends | 后端
29
17
 
30
18
  | id | key | endpoint | how it returns | notes |
@@ -40,9 +28,25 @@ dsh plugin --profile web add @240xu/dsh-websearch
40
28
  | `deepseek` | `DEEPSEEK_API_KEY` | `https://api.deepseek.com/anthropic/v1/messages` | Anthropic Messages API + native `web_search_20250305` server tool, model `deepseek-v4-flash` | 与 dav web-search-deepseek 同机制 |
41
29
  | `anthropic` | `ANTHROPIC_API_KEY` | `https://api.anthropic.com/v1/messages` | Anthropic Messages + `web_search_20250305`, model `claude-sonnet-4-6` | Claude Code 同机制 |
42
30
  | `openai` | `OPENAI_API_KEY` | `https://api.openai.com/v1/responses` | Responses API native `web_search` tool, parse `url_citation` annotations | Codex 同机制 |
31
+ | `firecrawl` | none/optional | `https://mcp.firecrawl.dev/v2/mcp` | streamable-http MCP, hosted keyless tier (metered), optional key raises limits | 默认关,计量型 |
32
+ | `tinyfish` | none/optional | `https://agent.tinyfish.ai/mcp` | streamable-http MCP, keyless 30/min · 50/day, optional key raises limits | 默认关,计量型 |
43
33
 
44
34
  > 可用性说明:available() 只做本地配置检查(不联网探测可达性);密钥在每次搜索时按操作解析,缺失时该后端以明确错误码软失败(不阻塞其他后端)。全部缺 Key 时错误会指向设置页。
45
35
 
36
+ ### Adding a backend | 新增后端
37
+
38
+ Non-2xx responses must be thrown through `webErrorFromResponse()` from
39
+ `lib/util/web-error.js`. It attaches four fields after constructing the
40
+ `WebError` — `status`, `retryAfter`, `rateLimited`, `quota` — and picks the
41
+ `code` from `RATE_LIMIT` / `QUOTA` / `WEB_PROVIDER_ERROR`. A keyless permission
42
+ refusal arrives as an MCP `isError` result rather than a non-2xx response, so
43
+ `keylessRejected` is derived by `failure-label.js` from that exact text, not
44
+ attached here. Downstream routing (`failure-label.js`,
45
+ the breaker, 3b) reads those fields, never the message text. Do not hand-write
46
+ `new WebError(..., "WEB_PROVIDER_ERROR")` for an HTTP failure — that drops the
47
+ status and makes a 429 look like an ordinary outage. A source-level test pins
48
+ every `webErrorFromResponse` call site.
49
+
46
50
  ### SearXNG 实例 | Public instances
47
51
 
48
52
  SearXNG 默认指向 `https://searx.be`;公共实例可用性随网络环境波动,失败时错误信息会提示换源。
@@ -88,13 +92,14 @@ pnpm install
88
92
  > 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
89
93
 
90
94
 
91
- 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),全部字段扁平化、开箱可编辑:
95
+ 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 23 个开关/参数;缓存、熔断、历史、多查询、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 profile patch 配置:
92
96
 
93
97
  **全局**
94
98
 
95
99
  | 字段 | 默认 | 说明 |
96
100
  |---|---|---|
97
- | `numResults` | 8 | 每次搜索返回结果数(1-50) |
101
+ | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
+ | `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
98
103
  | `concurrency` | 6 | 并发后端数(1-10) |
99
104
  | `backendTimeoutMs` | 30000 | 单后端超时毫秒 |
100
105
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
@@ -105,10 +110,20 @@ pnpm install
105
110
 
106
111
  **v2.1 结果策略**:设置面板新增「结果策略」分区。时间/语言过滤按各后端能力自动映射——Brave `freshness/country/search_lang`、Tavily `time_range`、Serper `tbs/hl/gl`(Google 日期语法)、SearXNG `time_range/language`、DDG `df`;不支持的后端自动忽略对应维度。内部超时以真实原因失败(backend "<id>" timed out after Nms),不再被静默降级为取消;Mojeek 的 API Key 改走 Authorization 头,不再出现在 URL 中。
107
112
 
113
+ **搜索介入程度(`intervention`,默认 `balanced`)**:控制插件在官方 `web_search` 契约之外做多少事。
114
+
115
+ | 档位 | 查询 | 多查询 | 深覆盖 | 重排 | 结果头/遥测 | 条数 |
116
+ |---|---|---|---|---|---|---|
117
+ | `official` | 原样(不改写) | 关 | 关 | 关 | 关 | 沿用宿主 `maxResults` |
118
+ | `balanced` | 只剥明确的口语前缀 | 独立开关,默认关 | 独立开关,默认关 | 独立开关,默认关 | 开 | `min(宿主, numResults)` |
119
+ | `thorough` | 同 balanced | 独立开关,默认关 | **开** | **开** | 开 | `min(宿主, numResults)` |
120
+
121
+ 依据:DSH 0.2.2-rc.5 的 `web_search` 由**模型**写 1–10 条 query,`dsh-tool-web` 负责并发/轮转合并/结果格式,`content` 是 provider 答案而非指令(`dsh-tool-web/src/search.ts:265-329`、`dsh-web/src/types.ts:26-63`)。官方 DeepSeek provider 原样转发 query、不写 `content`(`dsh-web-search-deepseek/src/provider.ts:243-252`)。因此 `official` 档只做 provider 该做的扇出/去重;内部多查询保持独立开关,避免在模型不知情时把一次调用放大成 3×N。
122
+
108
123
  **结果健康遥测(默认开)**:每次搜索的 `content` 尾部附一行 `[websearch backends] exa ✓5ms/3 · ddg ✗30000ms`,
109
- 模型可据此自诊断并建议用户调整设置;设置面板「结果策略」可关闭(`resultTelemetry`)。
124
+ 模型可据此自诊断并建议用户调整设置;设置面板「结果策略」可关闭(`resultTelemetry`),`official` 档始终关闭。
110
125
 
111
- **11 个后端开关**:`enableExa` / `enableParallel` / `enableDdg` / `enableSearxng`(默认开);`enableBrave` / `enableTavily` / `enableSerper` / `enableMojeek` / `enableDeepseek` / `enableAnthropic` / `enableOpenai`(默认关)
126
+ **13 个后端开关**:`enableExa` / `enableParallel` / `enableDdg` / `enableSearxng`(默认开);`enableBrave` / `enableTavily` / `enableSerper` / `enableMojeek` / `enableDeepseek` / `enableAnthropic` / `enableOpenai` / `enableFirecrawl` / `enableTinyfish`(默认关,后两者为计量型免 Key 后端)
112
127
 
113
128
  **API Key 授权**(credential-ref,填环境变量名,实际 key 存于 credentials 服务或环境变量):
114
129
 
@@ -125,7 +140,7 @@ pnpm install
125
140
 
126
141
  **Base URL / Model**:每个 key-gated 后端都有对应 `${id}BaseURL`;DeepSeek/Anthropic/OpenAI 另有 `${id}Model`;Tavily 有 `tavilySearchDepth`(basic/advanced)。
127
142
 
128
- 环境变量兜底:未在 credentials 配置时回退读同名环境变量;`DSH_UNIFIED_SEARCH_BACKENDS` 可逗号分隔强制指定启用集合。
143
+ 环境变量兜底:未在 credentials 配置时回退读同名环境变量。`DSH_UNIFIED_SEARCH_BACKENDS` 可逗号分隔指定启用集合,但优先级低于 `enabledBackends` 与 `enableXxx` 开关;由于四个免 Key 后端开关默认均为 `true`,该环境变量仅在所有开关被显式关闭时生效(Known Limitation)。
129
144
 
130
145
  ## v2.8.1 SettingsForms 适配 | What's new in v2.8.1
131
146
 
@@ -140,7 +155,7 @@ pnpm install
140
155
  ### 1. multiQuery 多查询 RRF 融合(`multiQueryEnabled`,默认关)
141
156
 
142
157
  - 门控启发式(刻意从严):查询长度 > 60 字符,或含 `vs / and / 比较 / 对比 / 和` 分隔词,才触发;简单查询单扇出,行为与旧版完全一致(arXiv:2404.01037:盲目多查询会劣化)。
143
- - 触发后派生 ≤3 个子查询(原查询永远参与融合且保持全权重),各自走完整 11 后端扇出,再用 RRF(k=60)融合:出现在多个子查询结果里的条目被提升,单列表独占条目按位次衰减;URL 去重、首见元数据保留。
158
+ - 触发后派生 ≤3 个子查询(原查询永远参与融合且保持全权重),各自走完整 13 后端扇出,再用 RRF(k=60)融合:出现在多个子查询结果里的条目被提升,单列表独占条目按位次衰减;URL 去重、首见元数据保留。
144
159
  - 遥测行合并各变体并截断至 12 条,避免淹没结果。
145
160
 
146
161
  ### 2. deepCoverage 深度覆盖(`deepCoverage`,默认关)
@@ -155,7 +170,7 @@ pnpm install
155
170
 
156
171
  ### 4. per-backend 超时上限(P2)
157
172
 
158
- - `ddg` 专属超时上限 8s、`searxng` 5s(`min(上限, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。ddg 由 5s 上调至 8s:实测可用的慢抓取需 ~7.7s(route6 审计),5s 会把「即将返回」误判为超时。实测见 docs/real-call-2.8.0.md。
173
+ - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
159
174
 
160
175
  ## v2.7.3 兼容修复 | What's new in v2.7.3
161
176
 
@@ -206,14 +221,14 @@ pnpm install
206
221
 
207
222
  ## Design | 设计
208
223
 
209
- - **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.
210
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`.
211
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.
212
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.
213
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.
214
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.
215
230
  - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 30s) caps each backend.
216
- - **Streamable-http MCP, custom handshake**: `lib/util/mcp-client.js` implements `initialize → notifications/initialized → tools/call` with `Mcp-Session-Id` header caching against Exa and Parallel — no dependency on the full MCP SDK.
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.
217
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).
218
233
 
219
234
  ## Architecture | 架构
@@ -225,7 +240,7 @@ lib/
225
240
  util/
226
241
  abort.js # isAbortError / searchAborted / throwIfSearchAborted / maybeAbortError
227
242
  mcp-client.js # streamable-http MCP client (initialize + tools/call + session cache)
228
- log.js # recordBackendRequest / recordBackendOutcome → session event log
243
+ log.js # recordBackendRequest / recordBackendOutcome → host logger (never session events)
229
244
  backends/
230
245
  exa.js # Exa (web_search_exa) via mcp-client
231
246
  parallel.js # Parallel (web_search) via mcp-client
@@ -249,7 +264,23 @@ tests/
249
264
  node --test tests/
250
265
  ```
251
266
 
252
- v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)。
267
+ 当前 213/213 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
268
+
269
+ ### Test-only dependencies
270
+
271
+ The six `@deepseek-ai/*` packages under `node_modules/` are test-only symlinks
272
+ into the running Harness checkout. They are not shipped and are gitignored. A
273
+ runtime switch moves the checkout and leaves absolute links dangling, which
274
+ makes `node --test` fail with `ERR_MODULE_NOT_FOUND`. Rebuild them from the
275
+ live service before running the suite:
276
+
277
+ ```bash
278
+ bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
279
+ find node_modules/@deepseek-ai -xtype l # expect no output
280
+ node --test tests/*.test.js # 213/213
281
+ ```
282
+
283
+ v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
253
284
 
254
285
  ## 权威依据与取舍 | Authoritative sources & design trade-offs
255
286
 
@@ -259,7 +290,7 @@ v2.7.0 缓存/熔断/历史三项的依据与刻意取舍(含查证过的反
259
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 内索引更新不可见——对搜索场景可接受,且用户可调低。
260
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 上出现半写状态也不会返回坏数据。
261
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 默认关、启发式从严、原查询全权重参与。
262
- 4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA)是拖尾主力。上限取「P50 成功延迟的一个数量级」并留余量:SearXNG 5s(实测成功 ~1.3s),ddg 8s(route6 实测成功可达 ~7.7s)。
293
+ 4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA)是拖尾主力,8s 上限取「P50 成功延迟的一个数量级」。
263
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 会话日志里存在;若未来历史跨设备同步,脱敏/加密是上线前置条件。
264
295
 
265
296
  ## License | 许可
@@ -286,4 +317,4 @@ MIT © 2026 240xu
286
317
  ZH 寒暄表补裸「搜索」(原 `搜索一下?` 要求带“一”漏掉裸词)。
287
318
  - **[P2] CJK 分隔符词内保护**:和/比较/对比 须**任一侧**有空白/标点边界才切——
288
319
  词内裸和(柔和光线/和平精英)不再切断实体;单侧空格的真分隔("sftp 和面板")照切。
289
- - 回归测试 ×4(零结果/limiter 死锁/exa 门控/CJK 保护/空查询拒),91/91。
320
+ - 回归测试 ×4(零结果/limiter 死锁/exa 门控/CJK 保护/空查询拒),91/91。
@@ -17,9 +17,11 @@
17
17
 
18
18
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
19
19
  import { WebError } from "@deepseek-ai/dsh-web";
20
+ import { webErrorFromResponse } from "../util/web-error.js";
20
21
  import { egressFetch } from "../util/egress-fetch.js";
22
+ import { describeError } from "../util/describe-error.js";
21
23
 
22
- /** Attribution header; bumped with the package version. */
24
+ /** Attribution header token; stable across releases, not derived from package.json. */
23
25
  const UA = "dsh-websearch/2.3";
24
26
 
25
27
  /**
@@ -128,16 +130,18 @@ export function createAnthropicLikeBackend(spec) {
128
130
  });
129
131
  } catch (err) {
130
132
  if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
131
- hooks.recordOutcome?.({ status: "error", message: String(err?.message ?? err) });
133
+ hooks.recordOutcome?.({ status: "error", message: describeError(err) });
132
134
  throw new WebError(
133
- `${id} search request failed: ${String(err?.message ?? err)}`,
135
+ `${id} search request failed: ${describeError(err)}`,
134
136
  "WEB_PROVIDER_ERROR",
135
137
  { cause: err },
136
138
  );
137
139
  }
138
140
 
139
141
  if (!response.ok) {
140
- let message = `${id} API error (HTTP ${response.status})`;
142
+ // Same as openai: the label and status live in webErrorFromResponse,
143
+ // so this carries the upstream detail only.
144
+ let message = "";
141
145
  try {
142
146
  const parsed = await response.json();
143
147
  const detail =
@@ -148,8 +152,8 @@ export function createAnthropicLikeBackend(spec) {
148
152
  } catch (err) {
149
153
  if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
150
154
  }
151
- hooks.recordOutcome?.({ status: "error", message });
152
- throw new WebError(message, "WEB_PROVIDER_ERROR");
155
+ hooks.recordOutcome?.({ status: "error", message: message === "" ? `HTTP ${response.status}` : message });
156
+ throw webErrorFromResponse(response, message, id);
153
157
  }
154
158
 
155
159
  try {
@@ -162,9 +166,9 @@ export function createAnthropicLikeBackend(spec) {
162
166
  hooks.recordOutcome?.({ status: "error", message: err.message });
163
167
  throw err;
164
168
  }
165
- hooks.recordOutcome?.({ status: "error", message: String(err?.message ?? err) });
169
+ hooks.recordOutcome?.({ status: "error", message: describeError(err) });
166
170
  throw new WebError(
167
- `${id} returned an unprocessable response body: ${String(err?.message ?? err)}`,
171
+ `${id} returned an unprocessable response body: ${describeError(err)}`,
168
172
  "WEB_PROVIDER_ERROR",
169
173
  { cause: err },
170
174
  );
@@ -6,9 +6,11 @@
6
6
  */
7
7
 
8
8
  import { WebError } from "@deepseek-ai/dsh-web";
9
+ import { webErrorFromResponse } from "../util/web-error.js";
9
10
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
10
11
  import { applyBraveFilters, normalizeFilters, safeSearchParams } from "../util/filters.js";
11
12
  import { egressFetch } from "../util/egress-fetch.js";
13
+ import { describeError } from "../util/describe-error.js";
12
14
 
13
15
  const BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search";
14
16
 
@@ -27,7 +29,7 @@ export const braveBackend = {
27
29
 
28
30
  const apiKey = await backendOpts.resolveApiKey?.();
29
31
  if (!apiKey) {
30
- 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");
31
33
  }
32
34
 
33
35
  const baseURL = backendOpts.baseURL ?? BRAVE_ENDPOINT;
@@ -60,13 +62,13 @@ export const braveBackend = {
60
62
  });
61
63
  } catch (error) {
62
64
  if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
63
- throw new WebError(`Brave Search request failed: ${error}`, "WEB_PROVIDER_ERROR", { cause: error });
65
+ throw new WebError(`Brave Search request failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
64
66
  }
65
67
 
66
68
  if (!response.ok) {
67
69
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
68
70
  hooks?.recordOutcome?.({ status: "error", message: `HTTP ${response.status}: ${text}` });
69
- throw new WebError(`Brave Search API error (HTTP ${response.status}): ${text}`, "WEB_PROVIDER_ERROR");
71
+ throw webErrorFromResponse(response, text, "Brave");
70
72
  }
71
73
 
72
74
  let data;
@@ -98,7 +100,9 @@ export function parseBraveResult(data, maxResults) {
98
100
  url: item.url,
99
101
  ...(item.title ? { title: item.title } : {}),
100
102
  ...(item.description ? { snippet: item.description } : {}),
101
- ...(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 } : {}),
102
106
  });
103
107
  }
104
108
  return sources;
@@ -8,6 +8,7 @@
8
8
  import { searchAborted, isAbortError, throwIfSearchAborted } from "../util/abort.js";
9
9
  import { applyDdgFilters, normalizeFilters } from "../util/filters.js";
10
10
  import { WebError } from "@deepseek-ai/dsh-web";
11
+ import { webErrorFromResponse } from "../util/web-error.js";
11
12
  import { egressFetch } from "../util/egress-fetch.js";
12
13
  import { describeError } from "../util/describe-error.js";
13
14
 
@@ -51,12 +52,16 @@ export const ddgBackend = {
51
52
  if (!res.ok) {
52
53
  let detail = "";
53
54
  try { detail = (await res.text()).slice(0, 200); } catch {}
54
- throw new WebError(`ddg HTTP ${res.status}${detail ? ": " + detail : ""}`, "WEB_PROVIDER_ERROR");
55
+ throw webErrorFromResponse(res, detail, "ddg");
55
56
  }
56
57
  text = await res.text();
57
58
  } catch (err) {
58
59
  if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
59
60
  hooks.recordOutcome?.({ status: "error", message: describeError(err) });
61
+ // webErrorFromResponse() already produced a structured WebError with
62
+ // status/code/rateLimited; re-wrapping it would drop those fields and
63
+ // force the breaker back onto message-text classification.
64
+ if (err instanceof WebError) throw err;
60
65
  throw new WebError(
61
66
  `ddg search failed: ${describeError(err)}`,
62
67
  "WEB_PROVIDER_ERROR",
@@ -85,22 +90,33 @@ export const ddgBackend = {
85
90
  */
86
91
  export function parseDdgHtml(html, maxResults) {
87
92
  if (!html) return [];
88
- // Result anchors: <a ... class="result__a" ... href="<url>">Title</a>
89
- const anchorRe = /<a\b[^>]*\bclass="[^"]*result__a[^"]*"[^>]*\bhref="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi;
90
- const sources = [];
93
+ // Collect every result anchor first. The attributes are matched
94
+ // independently of order: DDG has emitted href before class, and the old
95
+ // combined regex then returned zero results.
96
+ const anchors = [];
97
+ const anchorRe = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
91
98
  let m;
92
99
  while ((m = anchorRe.exec(html)) !== null) {
93
- const rawHref = m[1];
94
- const url = decodeDdgUddg(rawHref);
100
+ const attrs = m[1];
101
+ if (!/\bclass="[^"]*result__a[^"]*"/i.test(attrs)) continue;
102
+ const href = /\bhref="([^"]*)"/i.exec(attrs);
103
+ if (href === null) continue;
104
+ anchors.push({ href: href[1], title: m[2], start: m.index, end: m.index + m[0].length });
105
+ }
106
+ const sources = [];
107
+ for (const [index, anchor] of anchors.entries()) {
108
+ const url = decodeDdgUddg(anchor.href);
95
109
  if (!url) continue;
96
110
 
97
111
  // Title text: strip nested tags inside the anchor.
98
- const title = stripTags(m[2]).trim();
112
+ const title = stripTags(anchor.title).trim();
99
113
 
100
- // Snippet: search forward from this anchor for the nearest result__snippet.
101
- const after = html.slice(m.index + m[0].length);
102
- const snipRe = /<a\b[^>]*\bclass="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/a>/i;
103
- const snipM = snipRe.exec(after);
114
+ // Snippet: search only inside this result block, ending at the next
115
+ // result anchor. Scanning to the end of the document let a result with no
116
+ // snippet inherit the next result's snippet.
117
+ const blockEnd = index + 1 < anchors.length ? anchors[index + 1].start : html.length;
118
+ const block = html.slice(anchor.end, blockEnd);
119
+ const snipM = /<a\b[^>]*\bclass="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/a>/i.exec(block);
104
120
  const snippet = snipM ? stripTags(snipM[1]).trim() : undefined;
105
121
 
106
122
  const source = { url };
@@ -60,7 +60,9 @@ export const exaBackend = {
60
60
 
61
61
  let result;
62
62
  try {
63
- result = await mcpCall(EXA_ENDPOINT, EXA_TOOL, args, {}, signal);
63
+ // The public Exa MCP endpoint is stateless; the official provider sends
64
+ // a single tools/call with no initialize round-trip.
65
+ result = await mcpCall(EXA_ENDPOINT, EXA_TOOL, args, {}, signal, { skipInitialize: true });
64
66
  } catch (err) {
65
67
  if (err instanceof WebError) throw err;
66
68
  throw new WebError(
@@ -115,7 +117,8 @@ function joinHighlights(block) {
115
117
  const tail = block.slice(m.index + m[0].length);
116
118
  const bullets = [...tail.matchAll(/^\s+-\s+(.+)$/gm)].map((b) => b[1].trim());
117
119
  if (bullets.length === 0) return undefined;
118
- return bullets.join(" … ");
120
+ // Bound what reaches the model: highlights are excerpts, not full text.
121
+ return bullets.join(" … ").slice(0, 400);
119
122
  }
120
123
 
121
124
  export default exaBackend;
@@ -0,0 +1,129 @@
1
+ // firecrawl.js — Firecrawl search backend (streamable-http MCP, v2).
2
+ //
3
+ // Requests the official Firecrawl MCP endpoint through the shared MCP client.
4
+ // The hosted keyless tier is rate limited; an optional API key raises its
5
+ // limits. Results are normalised to { url, title?, snippet? }.
6
+
7
+ // https://github.com/anomalyco/opencode/blob/v2.2.5/packages/core/src/plugin/websearch/firecrawl.ts
8
+ // https://docs.firecrawl.dev/mcp-server/keyless.md
9
+ //
10
+ // Endpoint: https://mcp.firecrawl.dev/v2/mcp
11
+ // - keyless hosted tier: no credential, exposes firecrawl_search /
12
+ // firecrawl_scrape / firecrawl_parse only, rate limited per IP (official
13
+ // docs, HTTP 200). The exact daily numbers are not published.
14
+ // - with FIRECRAWL_API_KEY: Authorization: Bearer <key>, higher limits.
15
+ // The v2.2.5 OpenCode client does NOT send an explicit keyless header; the
16
+ // server implicitly provides the tier when no Authorization header is set.
17
+ //
18
+ // Response envelope: content[0].text is a JSON string of
19
+ // { success: boolean, data: { web: [{ url, title?, description? }] } }
20
+ // which we normalise to the DSH source shape { url, title?, snippet? }.
21
+ //
22
+ // Registration is intentionally opt-in (DEFAULT_ENABLED does not contain this
23
+ // id) because the keyless tier is metered and its exact ceiling is unknown.
24
+
25
+ import { mcpCall } from "../util/mcp-client.js";
26
+ import { WebError } from "@deepseek-ai/dsh-web";
27
+
28
+ const FIRECRAWL_ENDPOINT = "https://mcp.firecrawl.dev/v2/mcp";
29
+ const FIRECRAWL_TOOL = "firecrawl_search";
30
+
31
+ export const firecrawlBackend = {
32
+ id: "firecrawl",
33
+ requiresCredential: false,
34
+
35
+ available() {
36
+ // Hosted keyless tier works without a key; a key only raises limits.
37
+ return true;
38
+ },
39
+
40
+ async search(request, signal, options, hooks = {}) {
41
+ // The official provider requests a fixed page of 8; a larger maxResults
42
+ // is applied locally by parseFirecrawlResult, not sent upstream where it
43
+ // would consume more of the hosted keyless quota.
44
+ const args = {
45
+ query: request.query,
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)),
49
+ };
50
+ // resolveOptions() supplies an async resolveApiKey(); a literal apiKey is
51
+ // accepted for stubs (same split as anthropic-like.js). Resolution failure
52
+ // degrades to the keyless tier.
53
+ let apiKey = typeof options?.apiKey === "string" ? options.apiKey : "";
54
+ if (!apiKey && typeof options?.resolveApiKey === "function") {
55
+ try { apiKey = (await options.resolveApiKey()) ?? ""; } catch { apiKey = ""; }
56
+ }
57
+ const extraHeaders = apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
58
+ // Use the configured baseURL so the sidecar/proxy path and the provider
59
+ // trust gate apply; fall back to the official endpoint when unset.
60
+ const endpoint = typeof options?.baseURL === "string" && options.baseURL.length > 0
61
+ ? options.baseURL : FIRECRAWL_ENDPOINT;
62
+
63
+ // Keys must never appear in recorded request metadata.
64
+ hooks.recordRequest?.({
65
+ endpoint,
66
+ toolName: FIRECRAWL_TOOL,
67
+ body: args,
68
+ headers: {},
69
+ });
70
+
71
+ let result;
72
+ try {
73
+ result = await mcpCall(
74
+ endpoint,
75
+ FIRECRAWL_TOOL,
76
+ args,
77
+ extraHeaders,
78
+ signal,
79
+ // The hosted Firecrawl MCP endpoint is stateless; the official
80
+ // provider sends a single tools/call.
81
+ { skipInitialize: true },
82
+ );
83
+ } catch (err) {
84
+ if (err instanceof WebError) throw err;
85
+ throw new WebError(
86
+ `firecrawl search failed: ${String(err?.message ?? err)}`,
87
+ "WEB_PROVIDER_ERROR",
88
+ { cause: err },
89
+ );
90
+ }
91
+
92
+ if (result?.isError === true) {
93
+ const message = String(result.content?.[0]?.text ?? "unknown");
94
+ hooks.recordOutcome?.({ status: "error", message });
95
+ throw new WebError(`firecrawl returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
96
+ }
97
+
98
+ const sources = parseFirecrawlResult(result, request.maxResults ?? 8);
99
+ hooks.recordOutcome?.({ status: "ok", count: sources.length });
100
+ return { sources, content: undefined, truncated: false };
101
+ },
102
+ };
103
+
104
+ /** Parse the JSON string embedded in content[0].text into DSH sources. */
105
+ export function parseFirecrawlResult(result, maxResults) {
106
+ const text = result?.content?.[0]?.text;
107
+ if (typeof text !== "string" || text.length === 0) return [];
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(text);
111
+ } catch {
112
+ return [];
113
+ }
114
+ if (parsed?.success === false || !Array.isArray(parsed?.data?.web)) return [];
115
+ const sources = [];
116
+ for (const item of parsed.data.web) {
117
+ if (typeof item?.url !== "string" || item.url.length === 0) continue;
118
+ const source = { url: item.url };
119
+ if (typeof item.title === "string" && item.title.length > 0) source.title = item.title;
120
+ if (typeof item.description === "string" && item.description.length > 0) {
121
+ source.snippet = item.description.slice(0, 400);
122
+ }
123
+ sources.push(source);
124
+ if (sources.length >= maxResults) break;
125
+ }
126
+ return sources;
127
+ }
128
+
129
+ export default firecrawlBackend;
@@ -6,8 +6,10 @@
6
6
  */
7
7
 
8
8
  import { WebError } from "@deepseek-ai/dsh-web";
9
+ import { webErrorFromResponse } from "../util/web-error.js";
9
10
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
10
11
  import { egressFetch } from "../util/egress-fetch.js";
12
+ import { describeError } from "../util/describe-error.js";
11
13
 
12
14
  const MOJEEK_ENDPOINT = "https://api.mojeek.com/v1/search";
13
15
 
@@ -26,7 +28,7 @@ export const mojeekBackend = {
26
28
 
27
29
  const apiKey = await backendOpts.resolveApiKey?.();
28
30
  if (!apiKey) {
29
- throw new WebError("Mojeek: API key not configured", "WEB_PROVIDER_UNAVAILABLE");
31
+ throw new WebError("Mojeek: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
30
32
  }
31
33
 
32
34
  const baseURL = backendOpts.baseURL ?? MOJEEK_ENDPOINT;
@@ -62,13 +64,13 @@ export const mojeekBackend = {
62
64
  });
63
65
  } catch (error) {
64
66
  if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
65
- throw new WebError("Mojeek request failed: " + error, "WEB_PROVIDER_ERROR", { cause: error });
67
+ throw new WebError("Mojeek request failed: " + describeError(error), "WEB_PROVIDER_ERROR", { cause: error });
66
68
  }
67
69
 
68
70
  if (!response.ok) {
69
71
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
70
72
  hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
71
- throw new WebError("Mojeek API error (HTTP " + response.status + "): " + text, "WEB_PROVIDER_ERROR");
73
+ throw webErrorFromResponse(response, text, "Mojeek");
72
74
  }
73
75
 
74
76
  let data;
@@ -12,7 +12,9 @@
12
12
 
13
13
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
14
14
  import { WebError } from "@deepseek-ai/dsh-web";
15
+ import { webErrorFromResponse } from "../util/web-error.js";
15
16
  import { egressFetch } from "../util/egress-fetch.js";
17
+ import { describeError } from "../util/describe-error.js";
16
18
 
17
19
  const UA = "dsh-websearch/2.3";
18
20
 
@@ -82,16 +84,19 @@ export const openaiBackend = {
82
84
  });
83
85
  } catch (err) {
84
86
  if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
85
- hooks.recordOutcome?.({ status: "error", message: String(err?.message ?? err) });
87
+ hooks.recordOutcome?.({ status: "error", message: describeError(err) });
86
88
  throw new WebError(
87
- `openai search request failed: ${String(err?.message ?? err)}`,
89
+ `openai search request failed: ${describeError(err)}`,
88
90
  "WEB_PROVIDER_ERROR",
89
91
  { cause: err },
90
92
  );
91
93
  }
92
94
 
93
95
  if (!response.ok) {
94
- let message = `openai API error (HTTP ${response.status})`;
96
+ // webErrorFromResponse already prefixes "<Label> API error (HTTP <n>):",
97
+ // so this is only the upstream detail. Defaulting it to the same sentence
98
+ // would print the status line twice.
99
+ let message = "";
95
100
  try {
96
101
  const parsed = await response.json();
97
102
  const detail =
@@ -102,8 +107,8 @@ export const openaiBackend = {
102
107
  } catch (err) {
103
108
  if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
104
109
  }
105
- hooks.recordOutcome?.({ status: "error", message });
106
- throw new WebError(message, "WEB_PROVIDER_ERROR");
110
+ hooks.recordOutcome?.({ status: "error", message: message === "" ? `HTTP ${response.status}` : message });
111
+ throw webErrorFromResponse(response, message, "OpenAI");
107
112
  }
108
113
 
109
114
  try {
@@ -117,9 +122,9 @@ export const openaiBackend = {
117
122
  hooks.recordOutcome?.({ status: "error", message: err.message });
118
123
  throw err;
119
124
  }
120
- hooks.recordOutcome?.({ status: "error", message: String(err?.message ?? err) });
125
+ hooks.recordOutcome?.({ status: "error", message: describeError(err) });
121
126
  throw new WebError(
122
- `openai returned an unprocessable response body: ${String(err?.message ?? err)}`,
127
+ `openai returned an unprocessable response body: ${describeError(err)}`,
123
128
  "WEB_PROVIDER_ERROR",
124
129
  { cause: err },
125
130
  );