@240xu/dsh-websearch 2.8.7 → 2.8.9

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,13 +3,13 @@
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
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.
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
 
@@ -28,9 +28,25 @@ DSH([DeepSeek Harness](https://github.com/deepseek-ai/dsh))原生插件:
28
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 同机制 |
29
29
  | `anthropic` | `ANTHROPIC_API_KEY` | `https://api.anthropic.com/v1/messages` | Anthropic Messages + `web_search_20250305`, model `claude-sonnet-4-6` | Claude Code 同机制 |
30
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 | 默认关,计量型 |
31
33
 
32
34
  > 可用性说明:available() 只做本地配置检查(不联网探测可达性);密钥在每次搜索时按操作解析,缺失时该后端以明确错误码软失败(不阻塞其他后端)。全部缺 Key 时错误会指向设置页。
33
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
+
34
50
  ### SearXNG 实例 | Public instances
35
51
 
36
52
  SearXNG 默认指向 `https://searx.be`;公共实例可用性随网络环境波动,失败时错误信息会提示换源。
@@ -82,7 +98,8 @@ pnpm install
82
98
 
83
99
  | 字段 | 默认 | 说明 |
84
100
  |---|---|---|
85
- | `numResults` | 8 | 每次搜索返回结果数(1-50) |
101
+ | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
+ | `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
86
103
  | `concurrency` | 6 | 并发后端数(1-10) |
87
104
  | `backendTimeoutMs` | 30000 | 单后端超时毫秒 |
88
105
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
@@ -93,10 +110,20 @@ pnpm install
93
110
 
94
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 中。
95
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
+
96
123
  **结果健康遥测(默认开)**:每次搜索的 `content` 尾部附一行 `[websearch backends] exa ✓5ms/3 · ddg ✗30000ms`,
97
- 模型可据此自诊断并建议用户调整设置;设置面板「结果策略」可关闭(`resultTelemetry`)。
124
+ 模型可据此自诊断并建议用户调整设置;设置面板「结果策略」可关闭(`resultTelemetry`),`official` 档始终关闭。
98
125
 
99
- **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 后端)
100
127
 
101
128
  **API Key 授权**(credential-ref,填环境变量名,实际 key 存于 credentials 服务或环境变量):
102
129
 
@@ -113,7 +140,7 @@ pnpm install
113
140
 
114
141
  **Base URL / Model**:每个 key-gated 后端都有对应 `${id}BaseURL`;DeepSeek/Anthropic/OpenAI 另有 `${id}Model`;Tavily 有 `tavilySearchDepth`(basic/advanced)。
115
142
 
116
- 环境变量兜底:未在 credentials 配置时回退读同名环境变量;`DSH_UNIFIED_SEARCH_BACKENDS` 可逗号分隔强制指定启用集合。
143
+ 环境变量兜底:未在 credentials 配置时回退读同名环境变量。`DSH_UNIFIED_SEARCH_BACKENDS` 可逗号分隔指定启用集合,但优先级低于 `enabledBackends` 与 `enableXxx` 开关;由于四个免 Key 后端开关默认均为 `true`,该环境变量仅在所有开关被显式关闭时生效(Known Limitation)。
117
144
 
118
145
  ## v2.8.1 SettingsForms 适配 | What's new in v2.8.1
119
146
 
@@ -128,7 +155,7 @@ pnpm install
128
155
  ### 1. multiQuery 多查询 RRF 融合(`multiQueryEnabled`,默认关)
129
156
 
130
157
  - 门控启发式(刻意从严):查询长度 > 60 字符,或含 `vs / and / 比较 / 对比 / 和` 分隔词,才触发;简单查询单扇出,行为与旧版完全一致(arXiv:2404.01037:盲目多查询会劣化)。
131
- - 触发后派生 ≤3 个子查询(原查询永远参与融合且保持全权重),各自走完整 11 后端扇出,再用 RRF(k=60)融合:出现在多个子查询结果里的条目被提升,单列表独占条目按位次衰减;URL 去重、首见元数据保留。
158
+ - 触发后派生 ≤3 个子查询(原查询永远参与融合且保持全权重),各自走完整 13 后端扇出,再用 RRF(k=60)融合:出现在多个子查询结果里的条目被提升,单列表独占条目按位次衰减;URL 去重、首见元数据保留。
132
159
  - 遥测行合并各变体并截断至 12 条,避免淹没结果。
133
160
 
134
161
  ### 2. deepCoverage 深度覆盖(`deepCoverage`,默认关)
@@ -143,7 +170,7 @@ pnpm install
143
170
 
144
171
  ### 4. per-backend 超时上限(P2)
145
172
 
146
- - `ddg` 专属超时上限 8s、`searxng` 5s(`min(上限, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。ddg 由 5s 上调至 8s:实测可用的慢抓取需 ~7.7s(route6 审计),5s 会把「即将返回」误判为超时。实测见 docs/real-call-2.8.0.md。
173
+ - `ddg` / `searxng` 专属超时上限 5s(`min(5s, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
147
174
 
148
175
  ## v2.7.3 兼容修复 | What's new in v2.7.3
149
176
 
@@ -201,7 +228,7 @@ pnpm install
201
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.
202
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.
203
230
  - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 30s) caps each backend.
204
- - **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.
205
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).
206
233
 
207
234
  ## Architecture | 架构
@@ -213,7 +240,7 @@ lib/
213
240
  util/
214
241
  abort.js # isAbortError / searchAborted / throwIfSearchAborted / maybeAbortError
215
242
  mcp-client.js # streamable-http MCP client (initialize + tools/call + session cache)
216
- log.js # recordBackendRequest / recordBackendOutcome → session event log
243
+ log.js # recordBackendRequest / recordBackendOutcome → host logger (never session events)
217
244
  backends/
218
245
  exa.js # Exa (web_search_exa) via mcp-client
219
246
  parallel.js # Parallel (web_search) via mcp-client
@@ -237,7 +264,23 @@ tests/
237
264
  node --test tests/
238
265
  ```
239
266
 
240
- v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)。
267
+ 当前 211/211 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 # 211/211
281
+ ```
282
+
283
+ v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
241
284
 
242
285
  ## 权威依据与取舍 | Authoritative sources & design trade-offs
243
286
 
@@ -247,7 +290,7 @@ v2.7.0 缓存/熔断/历史三项的依据与刻意取舍(含查证过的反
247
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 内索引更新不可见——对搜索场景可接受,且用户可调低。
248
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 上出现半写状态也不会返回坏数据。
249
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 默认关、启发式从严、原查询全权重参与。
250
- 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)是拖尾主力,5s 上限取「P50 成功延迟的一个数量级」。
251
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 会话日志里存在;若未来历史跨设备同步,脱敏/加密是上线前置条件。
252
295
 
253
296
  ## License | 许可
@@ -17,7 +17,9 @@
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
24
  /** Attribution header; bumped with the package version. */
23
25
  const UA = "dsh-websearch/2.3";
@@ -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
 
@@ -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;
@@ -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(
@@ -0,0 +1,127 @@
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
+ limit: 8,
47
+ };
48
+ // resolveOptions() supplies an async resolveApiKey(); a literal apiKey is
49
+ // accepted for stubs (same split as anthropic-like.js). Resolution failure
50
+ // degrades to the keyless tier.
51
+ let apiKey = typeof options?.apiKey === "string" ? options.apiKey : "";
52
+ if (!apiKey && typeof options?.resolveApiKey === "function") {
53
+ try { apiKey = (await options.resolveApiKey()) ?? ""; } catch { apiKey = ""; }
54
+ }
55
+ const extraHeaders = apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
56
+ // Use the configured baseURL so the sidecar/proxy path and the provider
57
+ // trust gate apply; fall back to the official endpoint when unset.
58
+ const endpoint = typeof options?.baseURL === "string" && options.baseURL.length > 0
59
+ ? options.baseURL : FIRECRAWL_ENDPOINT;
60
+
61
+ // Keys must never appear in recorded request metadata.
62
+ hooks.recordRequest?.({
63
+ endpoint,
64
+ toolName: FIRECRAWL_TOOL,
65
+ body: args,
66
+ headers: {},
67
+ });
68
+
69
+ let result;
70
+ try {
71
+ result = await mcpCall(
72
+ endpoint,
73
+ FIRECRAWL_TOOL,
74
+ args,
75
+ extraHeaders,
76
+ signal,
77
+ // The hosted Firecrawl MCP endpoint is stateless; the official
78
+ // provider sends a single tools/call.
79
+ { skipInitialize: true },
80
+ );
81
+ } catch (err) {
82
+ if (err instanceof WebError) throw err;
83
+ throw new WebError(
84
+ `firecrawl search failed: ${String(err?.message ?? err)}`,
85
+ "WEB_PROVIDER_ERROR",
86
+ { cause: err },
87
+ );
88
+ }
89
+
90
+ if (result?.isError === true) {
91
+ const message = String(result.content?.[0]?.text ?? "unknown");
92
+ hooks.recordOutcome?.({ status: "error", message });
93
+ throw new WebError(`firecrawl returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
94
+ }
95
+
96
+ const sources = parseFirecrawlResult(result, request.maxResults ?? 8);
97
+ hooks.recordOutcome?.({ status: "ok", count: sources.length });
98
+ return { sources, content: undefined, truncated: false };
99
+ },
100
+ };
101
+
102
+ /** Parse the JSON string embedded in content[0].text into DSH sources. */
103
+ export function parseFirecrawlResult(result, maxResults) {
104
+ const text = result?.content?.[0]?.text;
105
+ if (typeof text !== "string" || text.length === 0) return [];
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(text);
109
+ } catch {
110
+ return [];
111
+ }
112
+ if (parsed?.success === false || !Array.isArray(parsed?.data?.web)) return [];
113
+ const sources = [];
114
+ for (const item of parsed.data.web) {
115
+ if (typeof item?.url !== "string" || item.url.length === 0) continue;
116
+ const source = { url: item.url };
117
+ if (typeof item.title === "string" && item.title.length > 0) source.title = item.title;
118
+ if (typeof item.description === "string" && item.description.length > 0) {
119
+ source.snippet = item.description;
120
+ }
121
+ sources.push(source);
122
+ if (sources.length >= maxResults) break;
123
+ }
124
+ return sources;
125
+ }
126
+
127
+ 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
 
@@ -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
  );
@@ -48,7 +48,8 @@ export const parallelBackend = {
48
48
 
49
49
  let result;
50
50
  try {
51
- result = await mcpCall(PARALLEL_ENDPOINT, PARALLEL_TOOL, args, {}, signal);
51
+ // The official provider sends a bare tools/call with no session handshake.
52
+ result = await mcpCall(PARALLEL_ENDPOINT, PARALLEL_TOOL, args, {}, signal, { skipInitialize: true });
52
53
  } catch (err) {
53
54
  if (err instanceof WebError) throw err;
54
55
  throw new WebError(
@@ -59,32 +60,13 @@ export const parallelBackend = {
59
60
  }
60
61
 
61
62
  if (result?.isError === true) {
62
-
63
-
64
63
  const message = String(result.content?.[0]?.text ?? "unknown");
65
-
66
-
67
64
  hooks.recordOutcome?.({ status: "error", message });
68
-
69
-
70
65
  throw new WebError(`parallel returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
71
-
72
-
73
66
  }
74
67
 
75
-
76
68
  const sources = parseParallelResult(result, request.maxResults ?? 8);
77
-
78
-
79
69
  hooks.recordOutcome?.({ status: "ok", count: sources.length });
80
-
81
- if (result?.isError === true) {
82
- throw new WebError(
83
- `parallel returned an MCP error: ${String(result.content?.[0]?.text ?? "unknown")}`,
84
- "WEB_PROVIDER_ERROR",
85
- );
86
- }
87
-
88
70
  return { sources, content: undefined, truncated: false };
89
71
  },
90
72
  };