dsh-free-search 0.9.54 → 0.9.55

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
@@ -34,7 +34,7 @@
34
34
  #### 引擎与切换
35
35
 
36
36
  - **零成本** —— 多个免费引擎,无需 key、无需注册
37
- - **41 个引擎可选**:DuckDuckGo(html/lite)、Bing、SearXNG(元搜索,支持自定义实例)、AnySearch、Exa、Tavily、Keenable、Firecrawl、Parallel、Brave(`brave`,官方 Search API,需 `BRAVE_API_KEY`)、智谱(`zhipu`,官方 Web Search API,需 `ZHIPU_API_KEY`)、Perplexity、SerpBase、Serply、Outcrawl、Google 自定义搜索(`google`,需 API key + CSE ID)、秘塔搜索(`metaso`,官方 API,按点数计费)、Yandex 搜索(`yandex`,官方 API,按请求计费,需 folder ID)、腾讯元宝搜索(`yuanbao`,API key 网关,有活动免费额度)、DeepSeek 官方、DeepSeek 原生搜索 API、You.com、百度千帆、Kimi、阿里云百炼、火山联网搜索(豆包搜索)、知乎全网/站内(`zhihu_global`/`zhihu_site`,经知乎开放平台 MCP)、Antigravity CLI 搜索(`agy`,需本机安装)、OpenAI / Gemini / Claude 模型内置搜索。默认自动回退链覆盖其中 30 个;5 个 HTML SERP 引擎默认不参与,OpenAI / Gemini / Claude 三个模型引擎、Metaso、Yandex 和 Yuanbao 都只在显式点名时运行。
37
+ - **42 个引擎可选**:DuckDuckGo(html/lite)、Bing、SearXNG(元搜索,支持自定义实例)、AnySearch、Exa、Tavily、Keenable、Firecrawl、Parallel、Brave(`brave`,官方 Search API,需 `BRAVE_API_KEY`)、智谱(`zhipu`,官方 Web Search API,需 `ZHIPU_API_KEY`)、Perplexity、SerpBase、Serply、Outcrawl、SpecStream(`specstream`,官方 Search API,需 `SPECSTREAM_API_KEY`)、Google 自定义搜索(`google`,需 API key + CSE ID)、秘塔搜索(`metaso`,官方 API,按点数计费)、Yandex 搜索(`yandex`,官方 API,按请求计费,需 folder ID)、腾讯元宝搜索(`yuanbao`,API key 网关,有活动免费额度)、DeepSeek 官方、DeepSeek 原生搜索 API、You.com、百度千帆、Kimi、阿里云百炼、火山联网搜索(豆包搜索)、知乎全网/站内(`zhihu_global`/`zhihu_site`,经知乎开放平台 MCP)、Antigravity CLI 搜索(`agy`,需本机安装)、OpenAI / Gemini / Claude 模型内置搜索。默认自动回退链覆盖其中 30 个;5 个 HTML SERP 引擎默认不参与,OpenAI / Gemini / Claude 三个模型引擎、Metaso、Yandex、Yuanbao 和 SpecStream 都只在显式点名时运行。
38
38
  - **5 个 HTML 搜索页引擎(默认关闭)** —— 把传统搜索页并入同一套引擎 / 回退 / 冷却 / 设置体系:`baidu-html`(百度网页)、`so360`、`sogou`、`wechat`(微信文章)、`toutiao`。免 key、免额度,代价是抓页面:验证码/反爬按 `bot-wall` 归类并让整个家族冷却 10 分钟(整段出口 IP 都会被打标),结果也没有 API 摘要。它们默认不进 auto / 回退链 / 语言池,只在显式 `engine=` 或加入语言池时运行。
39
39
  - **引擎白名单** —— 设置页「只使用勾选的引擎」开启后,只有勾选的引擎可用,升级新增的引擎默认不启用;配置里对应 `allowedEngines`(非空时等价于把其余引擎全部禁用)。
40
40
  - **全局引擎开关与回退优先级** —— 设置页可勾选/取消引擎(取消后全局生效:普通搜索 / Auto / `advanced_search` / `multi_search` / 引擎测试都不再用它),并可用 ↑↓ 调整全局回退顺序(一键恢复默认)。
@@ -97,6 +97,7 @@
97
97
  - **网页设置页** —— 引擎切换 + API key 配置(UI 中 key 脱敏显示「已配置」)+ 中英文切换;入口在左侧「插件」页的组件行配置(`plugins.row.config`,DSH 0.2.1-rc.2+)。远程访问(VPS / 反向代理 / 自定义域名)下也能用:桥接接口沿用宿主的 Host 围栏,`--trusted-host` 与 `--public-url` 声明的地址会放行(#84)。
98
98
  - **侧栏入口可关闭** —— 默认在左侧栏显示「免费搜索」;设置页关闭后写入配置并持久化,重启仍隐藏;隐藏时可用 `/free-search` 命令或插件页打开。
99
99
  - **斜杠命令可关闭** —— 默认注册 `/free-search-engine` 和 `/free-search`;设置页关闭 `slashCommands` 后两个命令都不再注册,设置仍在插件页,提示词也改为让模型参考插件设置。适合只想给 agent 用搜索工具的场景。
100
+ - **优先使用免 key 档(可选)** —— 默认配了 key 的引擎一律用 key。设置页打开 `keylessFirst` 后,Exa / Tavily / Keenable / Firecrawl / Parallel / AnySearch / You.com 先走免 key 档,只有它限流、额度用尽、要求鉴权或网络失败时才改用 key(同一次请求内重试一次);免 key 档失败后会休息一段时间(上限 45 分钟),期间直接用 key。适合 key 按量计费、想把它留作后备的场景。
100
101
 
101
102
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-apikeys.png" alt="全局回退优先级与每引擎 API key" width="100%" />
102
103
  <sub>▲ 全局回退优先级:每行一个引擎,右侧填该引擎的 API key(已配置会脱敏显示)</sub>
@@ -156,6 +157,7 @@
156
157
  | `metaso` | 秘塔搜索 | 付费(点数) | 否 | 需 `METASO_API_KEY`(metaso.cn/api);官方 AI 搜索 API,按点数计费(约 0.03 元/次,新用户有体验额度);支持网页 / 文库 / 学术三种 `scope`,返回摘要和来源;不在默认回退顺序里,配 key 后显式选用 |
157
158
  | `yandex` | Yandex 搜索 | 付费 | 否 | 需 `YANDEX_API_KEY` 和 `yandexFolderId`(AI Studio,按请求计费,需 billing account);官方 Search API,`searchType` 支持 RU/TR/COM/KK/BE/UZ,响应为 Base64 XML;支持 day / 2 weeks / month 时间过滤;显式专用 |
158
159
  | `yuanbao` | 腾讯元宝搜索 | 付费(有活动免费额度) | 否 | 需 `TENCENTCLOUD_WSA_APIKEY`(console.cloud.tencent.com/wsapi);API key 网关,支持自然 / 权威 / 混合模式、站点限定、时间范围;活动页可领每日免费额度(限时);显式专用 |
160
+ | `specstream` | SpecStream | 付费 | 否 | 需 `SPECSTREAM_API_KEY`(specstream.ai);网页搜索结果(标题/链接/摘要/发布日期),单次最多 10 条;显式专用(不在默认回退链、Auto 路由或语言池里) |
159
161
  | `deepseek-official` | DeepSeek 官方 | 付费 | 否 | 需 `DEEPSEEK_API_KEY`;走 Anthropic 兼容的 `web_search` 服务端工具,每次搜索是一整个模型轮次(慢、耗 token) |
160
162
  | `deepseek-tools` | DeepSeek 原生搜索 API | 付费 | 否 | 需 `DEEPSEEK_API_KEY`(与上一档共用);直接 `POST /v1/tools/search`,无模型参与,返回结构化 `results[]`(`title`/`url`/`summary`/`date`),同 query 实测 ~0.3s vs 上一档 ~5-6s;端点可通过 `deepseekToolsBaseUrl` 改成自定义网关(完整 URL 或 base;走 `/v1/search` 的网关请填完整 URL),key 可用 `deepseekToolsApiKey` 单独覆盖 |
161
163
  | `baidu` | 百度千帆 AI 搜索 | 额度 | 否 | 需 `BAIDU_API_KEY`(千帆 AI 搜索:web_search 每日赠 50 次,额度用尽/403 时自动回退到 chat/completions,另有 100 次/天免费额度;超额按量后付费);中文全网,支持时间过滤 |
@@ -189,6 +191,7 @@
189
191
  - SerpBase:<https://serpbase.dev>
190
192
  - Serply:<https://serply.io>(API 文档:<https://serply.io/docs>)
191
193
  - Outcrawl:<https://outcrawl.ai>(API 文档:<https://outcrawl.ai/docs>)
194
+ - SpecStream:<https://specstream.ai/signup?src=dsh-free-search>(API 文档:<https://specstream.ai/agents.md>;`?src=dsh-free-search` 仅用于来源归因统计,不含任何返佣或推广分成)
192
195
  - DeepSeek:<https://platform.deepseek.com/api_keys>
193
196
  - 豆包搜索(火山联网搜索):<https://console.volcengine.com/search-infinity/web-search>
194
197
  - You.com:<https://you.com/platform/api-keys>
@@ -202,7 +205,7 @@
202
205
  | ① 无限免 key | `ddg` / `ddg-lite` / `bing` / `searxng` / `anysearch` | — |
203
206
  | ② 匿名额度(不配 key 也能跑) | `exa` / `tavily` / `keenable` / `firecrawl` / `parallel` / `you`(每天 100 次) | 配 key 提额 |
204
207
  | ③ 免费额度(需 key) | `zhihu_global` / `zhihu_site`(每日 5,000 次试用)、`doubao`(每月 500 次)、`baidu`(每日 50 次)、`aliyun`(新用户 200 次包)、`brave`(每月 $5 额度 ≈ 1,000 次) | 按量后付费 |
205
- | ④ 付费升级(需 key 才有产出) | `serpbase`(注册送 100 次)/ `serply`(30 天 2,500 次)/ `outcrawl`(每月 1,000 credits)/ `perplexity` / `deepseek-official` / `deepseek-tools` / `kimi` | 按量 / 按次 |
208
+ | ④ 付费升级(需 key 才有产出) | `serpbase`(注册送 100 次)/ `serply`(30 天 2,500 次)/ `outcrawl`(每月 1,000 credits)/ `specstream`(显式专用)/ `perplexity` / `deepseek-official` / `deepseek-tools` / `kimi` | 按量 / 按次 |
206
209
  | ⑤ 按次计费(模型内置,显式-only) | `openai` / `gemini` / `claude` | 按 token + 每次搜索 |
207
210
 
208
211
  选默认池的经验:**① 打底 + ③ 打主力**;② 可以进但要知道它在烧匿名额度;④ 只在你确实需要该源时显式选用;⑤ 永不入池。完整的逐引擎额度事实与默认池提案见 [docs/engine-quota-tiers.md](./docs/engine-quota-tiers.md)。
@@ -288,7 +291,7 @@ DSH 0.2.1 设置 → 网页搜索 → **DeepSeek 搜索 API** 开关会和本插
288
291
  配置页提供:
289
292
 
290
293
  - **Search engine**:下拉框切换引擎,保存即生效
291
- - **API keys**:为 Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / SerpBase / Serply / Outcrawl / Google CSE / Metaso / Yandex / Yuanbao / You.com 填写 key(密码框,保存后只显示"已配置";Exa / Tavily / Keenable / Firecrawl / Parallel / You.com 不填也可免 key 使用)
294
+ - **API keys**:为 Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / SerpBase / Serply / Outcrawl / SpecStream / Google CSE / Metaso / Yandex / Yuanbao / You.com 填写 key(密码框,保存后只显示"已配置";Exa / Tavily / Keenable / Firecrawl / Parallel / You.com 不填也可免 key 使用)
292
295
  - **推荐**:付费引擎 key 建议写入 harness 凭据中心 `~/.dsh/.credentials.yaml`(如 `DEEPSEEK_API_KEY: sk-...`,与官方 LLM provider 一致,一处管理所有 key)。插件读取优先级:凭据中心 > 设置页 > 环境变量,设置页填的 key 仅作为遗留兼容。
293
296
  - **Test engine**:直测当前引擎可用性(不走回退链,付费引擎无 key 会明确报错)
294
297
  - **Use Bing default**:把当前搜索引擎切回稳定的免费 Bing;`Discard` 只撤销尚未保存的编辑
@@ -433,6 +436,7 @@ perplexityApiKey: ...
433
436
  serpbaseApiKey: ... # 或通过设置页填写
434
437
  serplyApiKey: ... # 或通过设置页填写
435
438
  outcrawlApiKey: ... # 或通过设置页填写
439
+ specstreamApiKey: ... # 或通过设置页填写
436
440
  googleCseApiKey: ... # Google Custom Search API key
437
441
  googleCseId: "..." # Programmable Search Engine 的 cx
438
442
  metasoApiKey: ... # Metaso API key (metaso.cn/api)
@@ -539,7 +543,7 @@ Search engine test:
539
543
  npx -y -p dsh-free-search dsh-free-search-mcp
540
544
  ```
541
545
 
542
- 第一版只暴露 `web_search`(Bing / DuckDuckGo,免 key)和 `web_fetch`(直连 / 浏览器 / Exa / Firecrawl);不暴露付费引擎、`research`、`multi_search`,也不监听端口。Claude Desktop 配置示例:
546
+ `web_search` 默认只自动调用免 key 的 Bing / DuckDuckGo;在参数或 `MCP_SEARCH_ENGINE` 里显式点名 `google` / `baidu` / `brave` / `metaso` / `yandex` / `yuanbao` / `deepseek-tools` / `zhipu` 时才会使用付费引擎。支持 `time_range`(day/week/month/year)。`web_fetch` 仍走直连 / 浏览器 / Exa / Firecrawl。不暴露 `research`、`multi_search`,也不监听端口。Claude Desktop 配置示例:
543
547
 
544
548
  ```json
545
549
  {
@@ -553,7 +557,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
553
557
  }
554
558
  ```
555
559
 
556
- 环境变量:`MCP_SEARCH_ENGINE`(auto / bing / ddg / ddg-lite)、`MCP_MAX_RESULTS`、`MCP_SAFE_SEARCH`、`MCP_LANG`、`MCP_BING_MARKET`、`MCP_BROWSER_FETCH`、`MCP_ALLOW_FAKE_IP_CIDRS`;抓取层可用 `EXA_API_KEY` / `FIRECRAWL_API_KEY`。
560
+ 环境变量:`MCP_SEARCH_ENGINE`(默认 auto,也可指定任意引擎 id)、`MCP_MAX_RESULTS`、`MCP_SAFE_SEARCH`、`MCP_LANG`、`MCP_BING_MARKET`、`MCP_BROWSER_FETCH`、`MCP_ALLOW_FAKE_IP_CIDRS`。付费引擎按需读取:`GOOGLE_CSE_API_KEY` + `GOOGLE_CSE_ID`、`BAIDU_API_KEY`、`BRAVE_API_KEY`、`METASO_API_KEY` / `MCP_METASO_SCOPE`、`YANDEX_API_KEY` + `YANDEX_FOLDER_ID`、`TENCENTCLOUD_WSA_APIKEY` / `MCP_YUANBAO_MODE` / `MCP_YUANBAO_SITE`、`DEEPSEEK_TOOLS_API_KEY` 或 `DEEPSEEK_API_KEY`、`ZHIPU_API_KEY` / `MCP_ZHIPU_SEARCH_ENGINE`;抓取层可用 `EXA_API_KEY` / `FIRECRAWL_API_KEY`。
557
561
 
558
562
  #### 平台搜索(platform_search)
559
563
 
@@ -627,21 +631,22 @@ npx -y -p dsh-free-search dsh-free-search-mcp
627
631
 
628
632
  #### 离线自检断言(tools/)
629
633
 
630
- 仓库自带 **69 个**零依赖断言脚本(合计 **983 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
634
+ 仓库自带 **70 个**零依赖断言脚本(合计 **1032 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
631
635
 
632
636
  | 脚本 | 覆盖 | 运行(项数) |
633
637
  |---|---|---|
634
638
  | `assert-auto-default.mjs` | 自动默认引擎:`provider` 留空时的地区判定(CN → bing、其它 → parallel)、探测失败回落 bing、`DSH_FREE_SEARCH_DEFAULT` 覆盖、提示词跟随、`effectiveProvider` 下发 | `node tools/assert-auto-default.mjs`(7) |
635
639
  | `assert-serp-engines.mjs` | HTML 搜索页家族:注册表不变式、时间过滤声明、默认不进 auto 与回退链、显式入池才生效、四个解析器的内联 fixture、反爬识别与文本清洗 | `node tools/assert-serp-engines.mjs`(32) |
636
- | `assert-engines.mjs` | 引擎清单 / 免费引擎口径 / 语言分池路由 / 池配置字段 / 知乎 URL 剥 utm / `deepseek-tools` 接线与 snippetCap 放宽 | `node tools/assert-engines.mjs`(41) |
640
+ | `assert-engines.mjs` | 引擎清单 / 免费引擎口径 / 语言分池路由 / 池配置字段 / 知乎 URL 剥 utm / `deepseek-tools` 接线与 snippetCap 放宽 / `outcrawl` 与 `specstream` 显式专用注册点 | `node tools/assert-engines.mjs`(89) |
637
641
  | `assert-blocked-domains.mjs` | 域名黑名单:解析、匹配、收口,且前后端清洗同口径 | `node tools/assert-blocked-domains.mjs`(69) |
638
642
  | `assert-multi-policy.mjs` | multi 执行策略:并发上限是天花板 / 目标成功源非硬下限 / 凭据资格在上限之前分流 / **Fast·Balanced·Deep 档位** | `node tools/assert-multi-policy.mjs`(146) |
639
643
  | `assert-multi-limit.mjs` | multi 结果上限(#109):默认 20 / 硬上限 100 / 配置归一化、单次 maxResults 受上限约束、工具参数与本段提示词写明生效上限、设置页字段与保存 | `node tools/assert-multi-limit.mjs`(6) |
640
644
  | `assert-maintenance.mjs` | 维护面:CI 在 Node 20/22/24 跑全部断言并过打包闸门、发布脚本会 bump / 校验 / 打 tag / 可发布、恢复官方 provider 的桥接与设置页按钮 | `node tools/assert-maintenance.mjs`(4) |
641
- | `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 41 个引擎且免费/按次标记正确、index 不引用引擎私有名 | `node tools/assert-engine-modules.mjs`(6) |
645
+ | `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 42 个引擎且免费/按次标记正确、index 不引用引擎私有名 | `node tools/assert-engine-modules.mjs`(6) |
642
646
  | `assert-brave.mjs` | Brave Search:catalog/凭据/设置接线、请求头与 count/freshness、错误分类、HTML 清洗、ISO 日期归一化、15s 超时 | `node tools/assert-brave.mjs`(54) |
643
647
  | `assert-sidebar-entry.mjs` | 侧栏入口(#129):`sidebarEntry` 默认开、设置页读写、条件注册/注销、`/free-search` 命令打开面板 | `node tools/assert-sidebar-entry.mjs`(4) |
644
648
  | `assert-slash-commands.mjs` | 斜杠命令开关:`slashCommands` 默认开、设置页读写、两个命令按配置注册/注销、关闭后提示词不再提 `/free-search-engine` | `node tools/assert-slash-commands.mjs`(4) |
649
+ | `assert-keyless-first.mjs` | 免 key 优先:`keylessFirst` 默认关、开启后先走免 key 档,限流/鉴权/网络失败改用 key 并休息、其他失败不动用 key、无 key 行为不变,覆盖 Tavily、Exa 与 multi 模式 | `node tools/assert-keyless-first.mjs`(13) |
645
650
  | `assert-zhipu.mjs` | 智谱搜索:catalog/回退链、请求头与 engine/count/recency、Sogou 步进、响应映射、错误分类、无 key | `node tools/assert-zhipu.mjs`(6) |
646
651
  | `assert-deepseek-snippets.mjs` | deepseek-tools 摘要:默认 600、0 不截断、总预算上限、短条目保留 | `node tools/assert-deepseek-snippets.mjs`(4) |
647
652
  | `assert-bing-relevance.mjs` | Bing 相关性(#112):单字中文 token 被剔除、无关替代 SERP 被拒、真正相关的结果通过、只命中通用引擎名的整批被拒、单一 token 覆盖一半时放行、单字/纯数字查询的显式行为 | `node tools/assert-bing-relevance.mjs`(6) |
@@ -656,8 +661,8 @@ npx -y -p dsh-free-search dsh-free-search-mcp
656
661
  | `assert-research-call-wrappers.mjs` | research 四个 `call*` 包装层的替身/底层透传(#75 回归) | `node tools/assert-research-call-wrappers.mjs`(23) |
657
662
  | `assert-fetch-chain.mjs` | `fs-quality-fetch` 四层链序、任一层命中即停、exa 失败静默降级 firecrawl、全层失败聚合报错 | `node tools/assert-fetch-chain.mjs`(8) |
658
663
  | `assert-fetch-ssrf.mjs` | 抓取 SSRF 防护:公网/私网/保留地址判定、DNS 解析到私网拒绝、localhost 与 IP 字面量拒绝、非 HTTPS 与带凭据 URL 拒绝、fake-ip 网段默认拒绝且仅按配置放行、IPv6 ULA 显式放行、放行后仍拒绝回环/IPv4 私网/链路本地、provider 接线与设置项 | `node tools/assert-fetch-ssrf.mjs`(8) |
659
- | `assert-mcp.mjs` | MCP stdio 面:initialize 协议协商、tools/list 的 JSON Schema、tools/call 文本结果、工具错误与 JSON-RPC 错误区分、必填参数校验、bin/files 打包 | `node tools/assert-mcp.mjs`(6) |
660
- | `assert-mcp.mjs` | MCP stdio surface: initialize negotiation, tools/list JSON Schema, tools/call text results, tool errors vs JSON-RPC errors, required arguments, bin/files packaging | `node tools/assert-mcp.mjs` (6) |
664
+ | `assert-mcp.mjs` | MCP stdio 面:initialize 协议协商、tools/list 的 JSON Schema、tools/call 文本结果、工具错误与 JSON-RPC 错误区分、必填参数校验、显式付费引擎与新 provider、bin/files 打包 | `node tools/assert-mcp.mjs`(9) |
665
+ | `assert-mcp.mjs` | MCP stdio surface: initialize negotiation, tools/list JSON Schema, tools/call text results, tool errors vs JSON-RPC errors, required arguments, explicit keyed engines and new providers, bin/files packaging | `node tools/assert-mcp.mjs` (9) |
661
666
  | `assert-baidu.mjs` | 百度千帆:key 必填、web_search 首请求、403 或 results.code 额度错误回退 chat/completions(stream:false)、401 不回退、双端失败合并报错 | `node tools/assert-baidu.mjs`(6) |
662
667
  | `assert-deepseek-endpoint.mjs` | DeepSeek 搜索端点:默认地址、base/完整 URL 归一、自定义 endpoint 收 Bearer/key/query、配置与设置页接线 | `node tools/assert-deepseek-endpoint.mjs`(4) |
663
668
  | `assert-yuanbao.mjs` |key 必填、Bearer 网关/Query/Mode/Site/FromTime、自然与 VR 页面解析、日期归一、错误分类、注册与显式专用 | `node tools/assert-yuanbao.mjs`(6) |
@@ -751,7 +756,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
751
756
  #### Engines and switching
752
757
 
753
758
  - **Zero Cost** — Multiple free engines with no API key or registration required
754
- - **41 engines available** — DuckDuckGo (HTML / Lite), Bing, AnySearch AI, SearXNG (meta-search with custom instances), Exa, Tavily, Keenable, Firecrawl, Parallel, Brave (`brave`, official Search API, needs `BRAVE_API_KEY`), Zhipu (`zhipu`, official Web Search API, needs `ZHIPU_API_KEY`), Perplexity, SerpBase, Serply, Outcrawl, Google Programmable Search (`google`, needs an API key plus a CSE ID), Metaso (秘塔搜索, official API, billed per call), Yandex Search (official API, billed per request, folder ID required), Tencent Yuanbao Search (API-key gateway with a limited free-quota activity), DeepSeek Official, DeepSeek Native Search API, You.com, Baidu Qianfan, Kimi, Aliyun Bailian, Volcano Doubao, Zhihu web-wide/site search (`zhihu_global`/`zhihu_site`, via the Zhihu open-platform MCP), Antigravity CLI search (`agy`, requires the local CLI), and the model-based OpenAI / Gemini / Claude searches. The default auto-fallback chain covers 30 of them; the 5 HTML SERP engines stay out by default and the per-call billed OpenAI / Gemini / Claude engines, Metaso, Yandex and Yuanbao run only when explicitly named.
759
+ - **42 engines available** — DuckDuckGo (HTML / Lite), Bing, AnySearch AI, SearXNG (meta-search with custom instances), Exa, Tavily, Keenable, Firecrawl, Parallel, Brave (`brave`, official Search API, needs `BRAVE_API_KEY`), Zhipu (`zhipu`, official Web Search API, needs `ZHIPU_API_KEY`), Perplexity, SerpBase, Serply, Outcrawl, SpecStream (`specstream`, official Search API, needs `SPECSTREAM_API_KEY`), Google Programmable Search (`google`, needs an API key plus a CSE ID), Metaso (秘塔搜索, official API, billed per call), Yandex Search (official API, billed per request, folder ID required), Tencent Yuanbao Search (API-key gateway with a limited free-quota activity), DeepSeek Official, DeepSeek Native Search API, You.com, Baidu Qianfan, Kimi, Aliyun Bailian, Volcano Doubao, Zhihu web-wide/site search (`zhihu_global`/`zhihu_site`, via the Zhihu open-platform MCP), Antigravity CLI search (`agy`, requires the local CLI), and the model-based OpenAI / Gemini / Claude searches. The default auto-fallback chain covers 30 of them; the 5 HTML SERP engines stay out by default and the per-call billed OpenAI / Gemini / Claude engines, Metaso, Yandex, Yuanbao and SpecStream run only when explicitly named.
755
760
  - **5 HTML SERP engines (off by default)** — Traditional result pages join the same engine / fallback / cooldown / settings machinery: `baidu-html` (Baidu web), `so360`, `sogou`, `wechat` (WeChat articles) and `toutiao`. No key, no quota — the trade-off is scraping: captcha/anti-bot pages are classified as `bot-wall` and cool the whole family down for 10 minutes (the egress IP gets flagged as a whole), and results carry no API snippets. They never join auto routing, the fallback chain or the language pools; they only run when named via `engine=` or added to a pool.
756
761
  - **Engine whitelist** — turn on Use only the checked engines and only those engines stay usable; engines added by later versions stay off. It maps to `allowedEngines` in the config (a non-empty list is equivalent to disabling every other engine).
757
762
  - **Global engine enable/disable & fallback priority** — uncheck engines you never want (applies everywhere: web_search fallback, Auto routing, advanced_search, multi_search, engine tests) and reorder the global fallback chain with ↑↓ (one-click reset).
@@ -814,6 +819,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
814
819
  - **Web Settings UI** — Engine switching, API key configuration (keys masked as "configured" in the UI), and a Chinese/English toggle; the entry is the component-row config (`plugins.row.config`) on the sidebar Plugins page (DSH 0.2.1-rc.2+). Remote access (VPS, reverse proxy, custom domain) works too: the bridge reuses the host's own Host fence, so addresses declared with `--trusted-host` or `--public-url` are accepted (#84).
815
820
  - **Optional sidebar entry** — the left-sidebar row is shown by default; turning it off persists in the plugin config and survives restarts. The panel remains reachable through `/free-search` or the plugin page.
816
821
  - **Optional slash commands** — `/free-search-engine` and `/free-search` are registered by default; turning `slashCommands` off in settings unregisters both, settings stay on the plugin page, and the prompt points the model at the plugin settings instead. Useful when you only want the search tools for the agent.
822
+ - **Keyless tier first (optional)** — by default an engine with a key always uses it. With `keylessFirst` on in settings, Exa / Tavily / Keenable / Firecrawl / Parallel / AnySearch / You.com try their keyless tier first and switch to the key only when that tier is rate limited, out of quota, asks for auth or fails to connect (retried once within the same request). A failed keyless tier rests for a while (at most 45 minutes), and searches go straight to the key meanwhile. Useful when the key is pay-as-you-go and should be the backup.
817
823
 
818
824
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-apikeys.png" alt="Global fallback priority and per-engine API keys" width="100%" />
819
825
  <sub>▲ Global fallback priority: one engine per row, its API key on the right (configured keys are masked)</sub>
@@ -874,6 +880,7 @@ If this plugin has been helpful, a ⭐ on [GitHub](https://github.com/DDDMUC/dsh
874
880
  | `metaso` | Metaso (秘塔搜索) | Paid (credits) | No | Requires `METASO_API_KEY` (metaso.cn/api); official AI search API billed per call (about ¥0.03/query, trial credits for new accounts); supports webpage / document / scholar scopes and returns summaries with sources; not in the default fallback order, use it explicitly after configuring a key |
875
881
  | `yandex` | Yandex Search | Paid | No | Requires `YANDEX_API_KEY` and `yandexFolderId` (AI Studio; billed per request to a billing account); official Search API with RU/TR/COM/KK/BE/UZ search types and Base64 XML responses; supports day / 2 weeks / month time filters; explicit-only |
876
882
  | `yuanbao` | Tencent Yuanbao Search | Paid (limited free-quota activity) | No | Requires `TENCENTCLOUD_WSA_APIKEY` (console.cloud.tencent.com/wsapi); API-key gateway with natural / authoritative / hybrid modes, site restriction and time ranges; the activity page offers a limited daily free quota; explicit-only |
883
+ | `specstream` | SpecStream | Paid | No | Requires `SPECSTREAM_API_KEY` (specstream.ai); web results with title, URL, snippet and publish date, up to 10 per search; explicit-only (never enters the default fallback chain, Auto routing, or language pools) |
877
884
  | `deepseek-official` | DeepSeek Official | Paid | No | Requires `DEEPSEEK_API_KEY`; uses the Anthropic-compatible `web_search` server tool, so every search is a full model turn (slow, token-billed) |
878
885
  | `deepseek-tools` | DeepSeek Native Search API | Paid | No | Requires `DEEPSEEK_API_KEY` (shared with the row above); calls `POST /v1/tools/search` directly, no model involved, returns structured `results[]` (`title`/`url`/`summary`/`date`) — measured ~0.3s vs ~5-6s for the row above; the endpoint is configurable via `deepseekToolsBaseUrl` (full URL or base; use the full URL for a gateway exposing `/v1/search`) and the key can be overridden with `deepseekToolsApiKey` for custom gateways |
879
886
  | `baidu` | Baidu Qianfan AI Search | Quota | No | Requires `BAIDU_API_KEY` (Qianfan AI Search: 50 free web_search calls/day; when that quota is exhausted or returns 403 it falls back to chat/completions, which has a separate 100/day free quota; pay-as-you-go beyond); Chinese web-wide, supports time filtering |
@@ -907,6 +914,7 @@ If this plugin has been helpful, a ⭐ on [GitHub](https://github.com/DDDMUC/dsh
907
914
  - SerpBase: <https://serpbase.dev>
908
915
  - Serply: <https://serply.io> (API docs: <https://serply.io/docs>)
909
916
  - Outcrawl: <https://outcrawl.ai> (API docs: <https://outcrawl.ai/docs>)
917
+ - SpecStream: <https://specstream.ai/signup?src=dsh-free-search> (API docs: <https://specstream.ai/agents.md>; `?src=dsh-free-search` is a source-attribution parameter only, with no referral or affiliate payment)
910
918
  - DeepSeek: <https://platform.deepseek.com/api_keys>
911
919
  - Doubao / Volcano Web Search: <https://console.volcengine.com/search-infinity/web-search>
912
920
  - You.com: <https://you.com/platform/api-keys>
@@ -921,7 +929,7 @@ The free/paid binary is not what decides **who belongs in a default pool** — t
921
929
  | ① Unlimited, no key | `ddg` / `ddg-lite` / `bing` / `searxng` / `anysearch` | — |
922
930
  | ② Anonymous quota (runs without a key) | `exa` / `tavily` / `keenable` / `firecrawl` / `parallel` / `you` (100/day) | key raises the quota |
923
931
  | ③ Free quota (key required) | `zhihu_global` / `zhihu_site` (5,000/day trial), `doubao` (500/month), `baidu` (50/day), `aliyun` (200-call starter pack), `brave` ($5/month credit ≈ 1,000 queries) | pay-as-you-go |
924
- | ④ Paid upgrade (needs a key to return anything) | `serpbase` (100 free on signup) / `serply` (2,500 for 30 days) / `outcrawl` (1,000 credits a month) / `perplexity` / `deepseek-official` / `deepseek-tools` / `kimi` | per call / per query |
932
+ | ④ Paid upgrade (needs a key to return anything) | `serpbase` (100 free on signup) / `serply` (2,500 for 30 days) / `outcrawl` (1,000 credits a month) / `specstream` (explicit-only) / `perplexity` / `deepseek-official` / `deepseek-tools` / `kimi` | per call / per query |
925
933
  | ⑤ Per-call billing (model built-in, explicit-only) | `openai` / `gemini` / `claude` | per token + per search |
926
934
 
927
935
  Rule of thumb for a default pool: **① as the floor + ③ as the workhorse**; ② is allowed but remember it burns anonymous quota; ④ only when you actually want that source; ⑤ never enters a pool. Per-engine facts and a default-pool proposal live in [docs/engine-quota-tiers.md](./docs/engine-quota-tiers.md).
@@ -1007,7 +1015,7 @@ After installation, open the config page (DSH 0.2.1-rc.2+):
1007
1015
  The config page provides:
1008
1016
 
1009
1017
  - **Search engine**: Select an engine from the dropdown; changes take effect immediately upon saving.
1010
- - **API keys**: Enter keys for Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / Google CSE / Metaso / Yandex / Yuanbao / You.com (password fields; displayed as "configured" once saved; Exa / Tavily / Keenable / Firecrawl / Parallel / You.com work without a key too).
1018
+ - **API keys**: Enter keys for Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / Google CSE / Metaso / Yandex / Yuanbao / SpecStream / You.com (password fields; displayed as "configured" once saved; Exa / Tavily / Keenable / Firecrawl / Parallel / You.com work without a key too).
1011
1019
  - **Recommended**: store paid-engine keys in the harness credential center `~/.dsh/.credentials.yaml` (e.g. `DEEPSEEK_API_KEY: sk-...`, same as the official LLM providers — one place for all keys). Resolution order: credentials center > settings page > environment variable; the settings-page fields remain for backward compatibility.
1012
1020
  - **Test engine**: Tests the selected engine directly (no fallback chain; paid engines without a key report an explicit error).
1013
1021
  - **Use Bing default**: stage a switch back to the stable free Bing engine; `Discard` only cancels unsaved edits
@@ -1152,6 +1160,7 @@ perplexityApiKey: ...
1152
1160
  serpbaseApiKey: ... # Or configure via the web settings UI
1153
1161
  serplyApiKey: ... # Or configure via the web settings UI
1154
1162
  outcrawlApiKey: ... # Or configure via the web settings UI
1163
+ specstreamApiKey: ... # Or configure via the web settings UI
1155
1164
  googleCseApiKey: ... # Google Custom Search API key
1156
1165
  googleCseId: "..." # Programmable Search Engine cx
1157
1166
  metasoApiKey: ... # Metaso API key (metaso.cn/api)
@@ -1258,7 +1267,7 @@ The repo also ships a standalone stdio MCP server for Claude Desktop, Cursor, Co
1258
1267
  npx -y -p dsh-free-search dsh-free-search-mcp
1259
1268
  ```
1260
1269
 
1261
- The first version exposes `web_search` (Bing / DuckDuckGo, no key) and `web_fetch` (direct / browser / Exa / Firecrawl). It does not expose paid engines, `research` or `multi_search`, and it does not listen on a port. Claude Desktop example:
1270
+ `web_search` auto-runs only the keyless Bing / DuckDuckGo engines; a keyed engine (`google` / `baidu` / `brave` / `metaso` / `yandex` / `yuanbao` / `deepseek-tools` / `zhipu`) runs only when named in the argument or `MCP_SEARCH_ENGINE`. It supports `time_range` (day/week/month/year). `web_fetch` still uses direct / browser / Exa / Firecrawl. It does not expose `research` or `multi_search`, and it does not listen on a port. Claude Desktop example:
1262
1271
 
1263
1272
  ```json
1264
1273
  {
@@ -1272,7 +1281,7 @@ The first version exposes `web_search` (Bing / DuckDuckGo, no key) and `web_fetc
1272
1281
  }
1273
1282
  ```
1274
1283
 
1275
- Environment: `MCP_SEARCH_ENGINE` (auto / bing / ddg / ddg-lite), `MCP_MAX_RESULTS`, `MCP_SAFE_SEARCH`, `MCP_LANG`, `MCP_BING_MARKET`, `MCP_BROWSER_FETCH`, `MCP_ALLOW_FAKE_IP_CIDRS`; the fetch tiers can use `EXA_API_KEY` / `FIRECRAWL_API_KEY`.
1284
+ Environment: `MCP_SEARCH_ENGINE` (auto by default, or any explicit engine id), `MCP_MAX_RESULTS`, `MCP_SAFE_SEARCH`, `MCP_LANG`, `MCP_BING_MARKET`, `MCP_BROWSER_FETCH`, `MCP_ALLOW_FAKE_IP_CIDRS`. Keyed engines read their own env: `GOOGLE_CSE_API_KEY` + `GOOGLE_CSE_ID`, `BAIDU_API_KEY`, `BRAVE_API_KEY`, `METASO_API_KEY` / `MCP_METASO_SCOPE`, `YANDEX_API_KEY` + `YANDEX_FOLDER_ID`, `TENCENTCLOUD_WSA_APIKEY` / `MCP_YUANBAO_MODE` / `MCP_YUANBAO_SITE`, `DEEPSEEK_TOOLS_API_KEY` or `DEEPSEEK_API_KEY`, `ZHIPU_API_KEY` / `MCP_ZHIPU_SEARCH_ENGINE`; the fetch tiers can use `EXA_API_KEY` / `FIRECRAWL_API_KEY`.
1276
1285
 
1277
1286
  #### Platform Search (`platform_search`)
1278
1287
 
@@ -1346,21 +1355,22 @@ Restart `dsh web` after switching to apply changes.
1346
1355
 
1347
1356
  #### Offline self-check assertions (`tools/`)
1348
1357
 
1349
- **Sixty-nine** zero-dependency assertion scripts ship with the repo (**983 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1358
+ **Seventy** zero-dependency assertion scripts ship with the repo (**1032 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1350
1359
 
1351
1360
  | Script | Covers | Run (count) |
1352
1361
  |---|---|---|
1353
1362
  | `assert-auto-default.mjs` | Automatic default engine: the region decision when `provider` is empty (CN to bing, anything else to parallel), falling back to bing on a failed probe, the `DSH_FREE_SEARCH_DEFAULT` override, the prompt following it, and `effectiveProvider` reaching the panel | `node tools/assert-auto-default.mjs` (7) |
1354
1363
  | `assert-serp-engines.mjs` | HTML SERP family: registry invariants, time-filter declarations, staying out of auto routing and the fallback chain, only joining when named in a pool, inline fixtures for the four parsers, anti-bot detection and text cleanup | `node tools/assert-serp-engines.mjs` (32) |
1355
- | `assert-engines.mjs` | engine registry / free-engine rule / language-pool routing / pool config fields / Zhihu URL utm stripping / `deepseek-tools` wiring and snippetCap widening | `node tools/assert-engines.mjs` (41) |
1364
+ | `assert-engines.mjs` | engine registry / free-engine rule / language-pool routing / pool config fields / Zhihu URL utm stripping / `deepseek-tools` wiring and snippetCap widening / `outcrawl` and explicit-only `specstream` registration | `node tools/assert-engines.mjs` (89) |
1356
1365
  | `assert-blocked-domains.mjs` | domain blocklist: parsing, matching, choke points, and byte-identical front/back-end sanitizing | `node tools/assert-blocked-domains.mjs` (69) |
1357
1366
  | `assert-multi-policy.mjs` | multi execution policy: ceiling semantics / target-is-not-a-hard-minimum / credential eligibility before the ceiling / **Fast·Balanced·Deep presets** | `node tools/assert-multi-policy.mjs` (146) |
1358
1367
  | `assert-multi-limit.mjs` | Multi result ceiling (#109): default 20 / hard max 100 / config normalisation, per-call maxResults clamped to the ceiling, tool copy and prompt state name the effective limit, settings field and save path | `node tools/assert-multi-limit.mjs` (6) |
1359
1368
  | `assert-maintenance.mjs` | Maintenance surface: CI runs every assertion on Node 20/22/24 plus the packaging gate, the release script bumps / verifies / tags / can publish, and the restore-official-provider bridge and settings button are wired | `node tools/assert-maintenance.mjs` (4) |
1360
- | `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, the catalog covers 41 engines with the right free/explicit flags, and index never reads an engine-private name | `node tools/assert-engine-modules.mjs` (6) |
1369
+ | `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, the catalog covers 42 engines with the right free/explicit flags, and index never reads an engine-private name | `node tools/assert-engine-modules.mjs` (6) |
1361
1370
  | `assert-brave.mjs` | Brave Search: catalog / credential / settings wiring, request headers and count/freshness, error classification, HTML stripping, ISO date normalization, and the 15s budget | `node tools/assert-brave.mjs` (54) |
1362
1371
  | `assert-sidebar-entry.mjs` | Sidebar entry (#129): `sidebarEntry` defaults on, settings load/save it, registration can be disposed/recreated, and `/free-search` opens the panel | `node tools/assert-sidebar-entry.mjs` (4) |
1363
1372
  | `assert-slash-commands.mjs` | Slash-command switch: `slashCommands` defaults on, settings load/save it, both commands register/unregister from config, and the prompt stops naming `/free-search-engine` when off | `node tools/assert-slash-commands.mjs` (4) |
1373
+ | `assert-keyless-first.mjs` | Keyless tier first: `keylessFirst` defaults off; when on, the keyless tier runs first and a rate limit, auth demand or network failure falls back to the key (which then rests the keyless tier), other failures leave the key alone, and no-key behaviour is unchanged; covers Tavily, Exa and multi mode | `node tools/assert-keyless-first.mjs` (13) |
1364
1374
  | `assert-zhipu.mjs` | Zhipu Web Search: catalog/fallback wiring, auth and request engine/count/recency, Sogou count steps, response mapping, error classes, missing key | `node tools/assert-zhipu.mjs` (6) |
1365
1375
  | `assert-deepseek-snippets.mjs` | deepseek-tools snippets: default 600, 0 disables the cap, total budget ceiling, and short results survive | `node tools/assert-deepseek-snippets.mjs` (4) |
1366
1376
  | `assert-bing-relevance.mjs` | Bing relevance (#112): single-character CJK tokens removed, an unrelated substituted SERP rejected, genuinely relevant results accepted, a batch matching only a generic engine name rejected, one distinctive token covering half the query accepted, and explicit single-character/numeric behaviour | `node tools/assert-bing-relevance.mjs` (6) |
package/lib/client.js CHANGED
@@ -356,12 +356,14 @@ window.__ModuleLoader__.load({
356
356
  keyStorage: "Key 存储位置",
357
357
  keyStorageCred: "凭据中心(推荐)",
358
358
  keyStorageSettings: "设置页(兼容)",
359
- keyStorageCredHint: (c) => `保存后写入 ~/.dsh/.credentials.yaml(最高优先级)。当前已配置:${["anysearch", "exa", "tavily", "keenable", "firecrawl", "parallel", "brave", "zhipu", "perplexity", "serpbase", "serply", "outcrawl", "deepseek", "youcom", "baidu", "kimi", "aliyun", "doubao", "openai", "gemini", "claude"].filter((k) => c[k]).map((k) => k.toUpperCase()).join(", ") || "无"}`,
359
+ keyStorageCredHint: (c) => `保存后写入 ~/.dsh/.credentials.yaml(最高优先级)。当前已配置:${["anysearch", "exa", "tavily", "keenable", "firecrawl", "parallel", "brave", "zhipu", "perplexity", "serpbase", "serply", "outcrawl", "specstream", "deepseek", "youcom", "baidu", "kimi", "aliyun", "doubao", "openai", "gemini", "claude"].filter((k) => c[k]).map((k) => k.toUpperCase()).join(", ") || "无"}`,
360
360
  keyStorageSettingsHint: "保存后写入当前 profile 的插件条目 config(cordis.patch.yml,优先级低于凭据中心)。",
361
361
  sidebarEntryLabel: "在左侧栏显示入口",
362
362
  sidebarEntryHint: "关闭后不再注册侧栏入口,仍可用 /free-search 命令或插件页打开;该设置会持久化,重启后仍生效。",
363
363
  slashCommandsLabel: "注册聊天框斜杠命令",
364
364
  slashCommandsHint: "关闭后不再注册 /free-search-engine 和 /free-search,设置仍在插件页;该设置会持久化,重启后仍生效。",
365
+ keylessFirstLabel: "优先使用免 key 档",
366
+ keylessFirstHint: "默认关闭:配了 key 的引擎一律用 key。开启后,Exa、Tavily、Keenable、Firecrawl、Parallel、AnySearch、You.com 先走免 key 档,限流、额度用尽、鉴权或网络失败时才改用 key,省 key 的额度。",
365
367
  engineEnable: "全局启用的搜索引擎",
366
368
  engineEnableHint: "取消勾选后,该引擎会从普通 web_search 回退链、Auto 智能路由、advanced_search、multi_search 和引擎测试中全局排除。至少保留一个引擎。",
367
369
  allowlistMode: "只使用勾选的引擎",
@@ -573,12 +575,14 @@ window.__ModuleLoader__.load({
573
575
  keyStorage: "Key storage",
574
576
  keyStorageCred: "Credential center (recommended)",
575
577
  keyStorageSettings: "Settings page (legacy)",
576
- keyStorageCredHint: (c) => `Saved to ~/.dsh/.credentials.yaml (highest priority). Currently configured: ${["anysearch", "exa", "tavily", "keenable", "firecrawl", "parallel", "brave", "zhipu", "perplexity", "serpbase", "serply", "outcrawl", "deepseek", "youcom", "baidu", "kimi", "aliyun", "doubao", "openai", "gemini", "claude"].filter((k) => c[k]).map((k) => k.toUpperCase()).join(", ") || "none"}`,
578
+ keyStorageCredHint: (c) => `Saved to ~/.dsh/.credentials.yaml (highest priority). Currently configured: ${["anysearch", "exa", "tavily", "keenable", "firecrawl", "parallel", "brave", "zhipu", "perplexity", "serpbase", "serply", "outcrawl", "specstream", "deepseek", "youcom", "baidu", "kimi", "aliyun", "doubao", "openai", "gemini", "claude"].filter((k) => c[k]).map((k) => k.toUpperCase()).join(", ") || "none"}`,
577
579
  keyStorageSettingsHint: "Saved to the active profile plugin entry config (cordis.patch.yml; lower priority than the credential center).",
578
580
  sidebarEntryLabel: "Show entry in the left sidebar",
579
581
  sidebarEntryHint: "When off, the sidebar entry is not registered; use /free-search or the plugin page instead. This setting persists across restarts.",
580
582
  slashCommandsLabel: "Register chat slash commands",
581
583
  slashCommandsHint: "When off, /free-search-engine and /free-search are not registered; settings stay on the plugin page. This setting persists across restarts.",
584
+ keylessFirstLabel: "Use keyless tiers first",
585
+ keylessFirstHint: "Off by default: an engine with a key always uses it. When on, Exa, Tavily, Keenable, Firecrawl, Parallel, AnySearch and You.com try their keyless tier first and switch to the key only when it is rate limited, out of quota, needs auth or fails to connect, which saves the key's quota.",
582
586
  engineEnable: "Globally enabled search engines",
583
587
  engineEnableHint: "Unchecked engines are excluded globally from web_search fallback, Auto routing, advanced_search, multi_search, and engine tests. At least one engine must remain enabled.",
584
588
  allowlistMode: "Use only the checked engines",
@@ -765,7 +769,7 @@ window.__ModuleLoader__.load({
765
769
  "cache_search",
766
770
  "domain_search",
767
771
  ];
768
- const PLUGIN_VERSION = "0.9.54";
772
+ const PLUGIN_VERSION = "0.9.55";
769
773
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
770
774
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
771
775
  const NAV_ITEMS = [
@@ -819,6 +823,7 @@ window.__ModuleLoader__.load({
819
823
  { id: "metaso", label: "Metaso · 秘塔搜索", badge: "API KEY", link: "https://metaso.cn/api" },
820
824
  { id: "yandex", label: "Yandex · 搜索 API", badge: "API KEY", link: "https://aistudio.yandex.cloud" },
821
825
  { id: "yuanbao", label: "腾讯元宝 · 搜索", badge: "API KEY", link: "https://console.cloud.tencent.com/wsapi" },
826
+ { id: "specstream", label: "SpecStream", badge: "API KEY", link: "https://specstream.ai/signup?src=dsh-free-search" },
822
827
  { id: "deepseek-official", label: "DeepSeek Official", badge: "API KEY", link: "https://platform.deepseek.com/api_keys" },
823
828
  { id: "deepseek-tools", label: "DeepSeek Tools API", badge: "API KEY", link: "https://api-docs.deepseek.com/zh-cn/guides/search" },
824
829
  { id: "you", label: "You.com", badge: "FREE", link: "https://you.com/platform/api-keys" },
@@ -842,11 +847,11 @@ window.__ModuleLoader__.load({
842
847
  ];
843
848
  const ENGINE_IDS = ENGINES.filter((engine) => engine.id !== "auto" && engine.id !== "multi").map((engine) => engine.id);
844
849
  // 与 lib/index.js 的 EXPLICIT_ONLY_ENGINES 同源:按次计费、只在显式选中时运行,因此不提供入池候选。
845
- const EXPLICIT_ONLY_ENGINES = ["openai", "gemini", "claude", "metaso", "yandex", "yuanbao"];
850
+ const EXPLICIT_ONLY_ENGINES = ["openai", "gemini", "claude", "metaso", "yandex", "yuanbao", "specstream"];
846
851
  // 与 lib/serp_engines.js 的 SERP_ENGINE_IDS 同源:HTML 抓取型引擎,默认不进自动回退链。
847
852
  const SERP_ENGINE_IDS = ["baidu-html", "so360", "sogou", "wechat", "toutiao"];
848
853
  const MODEL_ENGINES = ENGINES.filter(
849
- (engine) => EXPLICIT_ONLY_ENGINES.includes(engine.id) && !["metaso", "yandex", "yuanbao"].includes(engine.id)
854
+ (engine) => EXPLICIT_ONLY_ENGINES.includes(engine.id) && !["metaso", "yandex", "yuanbao", "specstream"].includes(engine.id)
850
855
  );
851
856
  const DEFAULT_FALLBACK_ORDER = ["exa", "tavily", "keenable", "firecrawl", "parallel", "brave", "zhipu", "perplexity", "serpbase", "serply", "outcrawl", "agy", "deepseek-tools", "deepseek-official", "you", "baidu", "kimi", "aliyun", "doubao", "tinyfish", "jina", "bing", "anysearch", "ddg", "ddg-lite", "searxng", "degoog", "zhihu_global", "zhihu_site"];
852
857
  const normalizeFallbackOrder = (value) => {
@@ -1084,6 +1089,7 @@ window.__ModuleLoader__.load({
1084
1089
  const [provider, setProvider] = react.useState("bing");
1085
1090
  const [sidebarEntry, setSidebarEntry] = react.useState(true);
1086
1091
  const [slashCommands, setSlashCommands] = react.useState(true);
1092
+ const [keylessFirst, setKeylessFirst] = react.useState(false);
1087
1093
  const [effectiveDefault, setEffectiveDefault] = react.useState("bing");
1088
1094
  const [disabledEngines, setDisabledEngines] = react.useState([]);
1089
1095
  const [allowedEngines, setAllowedEngines] = react.useState([]);
@@ -1125,6 +1131,7 @@ window.__ModuleLoader__.load({
1125
1131
  const [yuanbaoKey, setYuanbaoKey] = react.useState("");
1126
1132
  const [yuanbaoMode, setYuanbaoMode] = react.useState("0");
1127
1133
  const [yuanbaoSite, setYuanbaoSite] = react.useState("");
1134
+ const [specstreamKey, setSpecstreamKey] = react.useState("");
1128
1135
  const [deepseekToolsKey, setDeepseekToolsKey] = react.useState("");
1129
1136
  const [deepseekToolsUrl, setDeepseekToolsUrl] = react.useState("");
1130
1137
  const [snippetMaxChars, setSnippetMaxChars] = react.useState("600");
@@ -1219,6 +1226,7 @@ window.__ModuleLoader__.load({
1219
1226
  metaso: [metasoKey, setMetasoKey],
1220
1227
  yandex: [yandexKey, setYandexKey],
1221
1228
  yuanbao: [yuanbaoKey, setYuanbaoKey],
1229
+ specstream: [specstreamKey, setSpecstreamKey],
1222
1230
  you: [youcomKey, setYoucomKey],
1223
1231
  baidu: [baiduKey, setBaiduKey],
1224
1232
  kimi: [kimiKey, setKimiKey],
@@ -1418,6 +1426,7 @@ window.__ModuleLoader__.load({
1418
1426
  sidebarEntryController?.(v.sidebarEntry !== false);
1419
1427
  setSlashCommands(v.slashCommands !== false);
1420
1428
  slashCommandsController?.(v.slashCommands !== false);
1429
+ setKeylessFirst(v.keylessFirst === true);
1421
1430
  setDisabledEngines(
1422
1431
  Array.isArray(v.disabledEngines)
1423
1432
  ? [...new Set(v.disabledEngines.filter((id) => ENGINES.some((engine) => engine.id === id && id !== "auto" && id !== "multi")))]
@@ -1473,6 +1482,7 @@ window.__ModuleLoader__.load({
1473
1482
  setYuanbaoKey(v.yuanbaoApiKey ?? "");
1474
1483
  setYuanbaoMode(v.yuanbaoMode === 1 || v.yuanbaoMode === 2 ? String(v.yuanbaoMode) : "0");
1475
1484
  setYuanbaoSite(v.yuanbaoSite ?? "");
1485
+ setSpecstreamKey(v.specstreamApiKey ?? "");
1476
1486
  setDeepseekToolsKey(v.deepseekToolsApiKey ?? "");
1477
1487
  setDeepseekToolsUrl(v.deepseekToolsBaseUrl ?? "");
1478
1488
  setSnippetMaxChars(String(v.snippetMaxChars ?? 600));
@@ -1531,6 +1541,7 @@ window.__ModuleLoader__.load({
1531
1541
  if (path === "metasoApiKey") configured.metaso = true;
1532
1542
  if (path === "yandexApiKey") configured.yandex = true;
1533
1543
  if (path === "yuanbaoApiKey") configured.yuanbao = true;
1544
+ if (path === "specstreamApiKey") configured.specstream = true;
1534
1545
  if (path === "deepseekToolsApiKey") configured.deepseek = true;
1535
1546
  }
1536
1547
  }
@@ -1543,7 +1554,7 @@ window.__ModuleLoader__.load({
1543
1554
  const cred = await bridgeCredentialsStatus();
1544
1555
  if (cred.ok) {
1545
1556
  const cc = {};
1546
- const map = { anysearchApiKey: "anysearch", exaApiKey: "exa", tavilyApiKey: "tavily", keenableApiKey: "keenable", firecrawlApiKey: "firecrawl", parallelApiKey: "parallel", braveApiKey: "brave", zhipuApiKey: "zhipu", perplexityApiKey: "perplexity", deepseekApiKey: "deepseek", serpbaseApiKey: "serpbase", serplyApiKey: "serply", outcrawlApiKey: "outcrawl", youcomApiKey: "youcom", degoogApiKey: "degoog", googleCseApiKey: "google", metasoApiKey: "metaso", yandexApiKey: "yandex", yuanbaoApiKey: "yuanbao", deepseekToolsApiKey: "deepseek", baiduApiKey: "baidu", kimiApiKey: "kimi", aliyunApiKey: "aliyun", doubaoApiKey: "doubao", openaiApiKey: "openai", geminiApiKey: "gemini", claudeApiKey: "claude", zhihuApiKey: "zhihu", tinyfishApiKey: "tinyfish", jinaApiKey: "jina", searxngBearerToken: "searxng" };
1557
+ const map = { anysearchApiKey: "anysearch", exaApiKey: "exa", tavilyApiKey: "tavily", keenableApiKey: "keenable", firecrawlApiKey: "firecrawl", parallelApiKey: "parallel", braveApiKey: "brave", zhipuApiKey: "zhipu", perplexityApiKey: "perplexity", deepseekApiKey: "deepseek", serpbaseApiKey: "serpbase", serplyApiKey: "serply", outcrawlApiKey: "outcrawl", specstreamApiKey: "specstream", youcomApiKey: "youcom", degoogApiKey: "degoog", googleCseApiKey: "google", metasoApiKey: "metaso", yandexApiKey: "yandex", yuanbaoApiKey: "yuanbao", deepseekToolsApiKey: "deepseek", baiduApiKey: "baidu", kimiApiKey: "kimi", aliyunApiKey: "aliyun", doubaoApiKey: "doubao", openaiApiKey: "openai", geminiApiKey: "gemini", claudeApiKey: "claude", zhihuApiKey: "zhihu", tinyfishApiKey: "tinyfish", jinaApiKey: "jina", searxngBearerToken: "searxng" };
1547
1558
  for (const [k, v] of Object.entries(cred.value.configured ?? {})) {
1548
1559
  if (map[k]) cc[map[k]] = v;
1549
1560
  }
@@ -1598,6 +1609,7 @@ window.__ModuleLoader__.load({
1598
1609
  ["metasoApiKey", metasoKey],
1599
1610
  ["yandexApiKey", yandexKey],
1600
1611
  ["yuanbaoApiKey", yuanbaoKey],
1612
+ ["specstreamApiKey", specstreamKey],
1601
1613
  ["youcomApiKey", youcomKey],
1602
1614
  ["baiduApiKey", baiduKey],
1603
1615
  ["kimiApiKey", kimiKey],
@@ -1626,6 +1638,7 @@ window.__ModuleLoader__.load({
1626
1638
  const ops = [{ op: "set", path: ["provider"], value: provider }];
1627
1639
  ops.push({ op: "set", path: ["sidebarEntry"], value: sidebarEntry !== false });
1628
1640
  ops.push({ op: "set", path: ["slashCommands"], value: slashCommands !== false });
1641
+ ops.push({ op: "set", path: ["keylessFirst"], value: keylessFirst === true });
1629
1642
  ops.push({ op: "set", path: ["disabledEngines"], value: disabledEngines });
1630
1643
  ops.push({ op: "set", path: ["allowedEngines"], value: allowedEngines });
1631
1644
  ops.push({ op: "set", path: ["fallbackOrder"], value: normalizeFallbackOrder(fallbackOrder) });
@@ -2359,6 +2372,36 @@ window.__ModuleLoader__.load({
2359
2372
  }),
2360
2373
  ],
2361
2374
  }),
2375
+ react_jsx_runtime.jsx("div", {
2376
+ className: "dshfs-field",
2377
+ children: [
2378
+ react_jsx_runtime.jsx("div", {
2379
+ className: "dshfs-label",
2380
+ children: t.keylessFirstLabel,
2381
+ }),
2382
+ react_jsx_runtime.jsx("label", {
2383
+ className: "dshfs-platform",
2384
+ children: [
2385
+ react_jsx_runtime.jsx("input", {
2386
+ type: "checkbox",
2387
+ checked: keylessFirst,
2388
+ disabled: !ready || saving,
2389
+ onChange: (e) => {
2390
+ setKeylessFirst(e.target.checked);
2391
+ setDirty(true);
2392
+ setFailed(false);
2393
+ setSaveError("");
2394
+ },
2395
+ }),
2396
+ t.keylessFirstLabel,
2397
+ ],
2398
+ }),
2399
+ react_jsx_runtime.jsx("p", {
2400
+ className: "dshfs-hint",
2401
+ children: t.keylessFirstHint,
2402
+ }),
2403
+ ],
2404
+ }),
2362
2405
  react_jsx_runtime.jsx("div", {
2363
2406
  className: "dshfs-field",
2364
2407
  id: "dshfs-anchor-engines",
@@ -2563,7 +2606,7 @@ react_jsx_runtime.jsx("div", {
2563
2606
  }),
2564
2607
  react_jsx_runtime.jsx("div", {
2565
2608
  className: "dshfs-priorityList",
2566
- children: ["metaso", "yandex", "yuanbao"].map((engineId) => {
2609
+ children: ["metaso", "yandex", "yuanbao", "specstream"].map((engineId) => {
2567
2610
  const engine = ENGINES.find((item) => item.id === engineId);
2568
2611
  if (!engine) return null;
2569
2612
  return react_jsx_runtime.jsx("div", {
@@ -29,6 +29,7 @@ const BASE_ENGINES = [
29
29
  { id: "metaso", free: false, time: false, explicitOnly: true },
30
30
  { id: "yandex", free: false, time: false, explicitOnly: true },
31
31
  { id: "yuanbao", free: false, time: true, explicitOnly: true },
32
+ { id: "specstream", free: false, time: false, explicitOnly: true },
32
33
  { id: "deepseek-official", free: false, time: false },
33
34
  { id: "deepseek-tools", free: false, time: true },
34
35
  { id: "you", free: false, time: false },
@@ -0,0 +1,81 @@
1
+ // SpecStream Search API.
2
+ // GET https://api.specstream.ai/v1/web-search?q=...&num=... with a Bearer key;
3
+ // billed per search, so this engine is keyed and stays explicit-only (never in the default fallback chain).
4
+ import { uniqueSources } from "./shared.js";
5
+
6
+ const SPECSTREAM_URL = "https://api.specstream.ai/v1/web-search";
7
+ // Up to 10 results is one search at the base price; more results cost more.
8
+ const MAX_RESULTS = 10;
9
+
10
+ function specstreamErrorMessage(status, detail) {
11
+ let upstream = "";
12
+ try {
13
+ upstream = JSON.parse(detail)?.error?.message ?? "";
14
+ } catch {}
15
+ const suffix = upstream ? `: ${String(upstream).slice(0, 200)}` : "";
16
+ if (status === 401) {
17
+ return "SpecStream API key is invalid (HTTP 401); update it on the Free Search page";
18
+ }
19
+ if (status === 402) return `SpecStream account has insufficient balance (HTTP 402)${suffix}`;
20
+ if (status === 403) return `SpecStream API key may not run this search (HTTP 403)${suffix}`;
21
+ return `SpecStream API error (HTTP ${status})${suffix}`;
22
+ }
23
+
24
+ function publishedDate(value) {
25
+ const text = String(value ?? "").trim();
26
+ return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : "";
27
+ }
28
+
29
+ export async function searchSpecStream(query, maxResults, apiKey, signal) {
30
+ if (!apiKey) throw new Error("SpecStream search requires SPECSTREAM_API_KEY");
31
+ const limit = Math.min(Math.max(Number(maxResults) || 10, 1), MAX_RESULTS);
32
+ const url = `${SPECSTREAM_URL}?${new URLSearchParams({ q: query, num: String(limit) })}`;
33
+
34
+ let response;
35
+ try {
36
+ response = await fetch(url, {
37
+ method: "GET",
38
+ redirect: "error",
39
+ headers: {
40
+ authorization: `Bearer ${apiKey}`,
41
+ accept: "application/json",
42
+ "user-agent": "deepseek-harness/free-search",
43
+ },
44
+ signal: AbortSignal.any([...(signal !== undefined ? [signal] : []), AbortSignal.timeout(30000)]),
45
+ });
46
+ } catch (error) {
47
+ if (signal?.aborted) throw error;
48
+ if (error?.name === "TimeoutError") throw new Error("SpecStream request timed out");
49
+ throw new Error(`SpecStream request failed: ${error?.message ?? String(error)}`);
50
+ }
51
+
52
+ if (!response.ok) {
53
+ const detail = await response.text().catch(() => "");
54
+ throw new Error(specstreamErrorMessage(response.status, detail));
55
+ }
56
+
57
+ let data;
58
+ try {
59
+ data = await response.json();
60
+ } catch {
61
+ throw new Error("SpecStream returned an invalid JSON response");
62
+ }
63
+
64
+ const items = Array.isArray(data?.data?.sources) ? data.data.sources : [];
65
+ const sources = items
66
+ .map((item) => {
67
+ const link = String(item?.url ?? "").trim();
68
+ if (!link) return null;
69
+ const snippet = String(item?.snippet ?? "").trim();
70
+ const date = publishedDate(item?.published);
71
+ return {
72
+ url: link,
73
+ ...(item?.title ? { title: String(item.title) } : {}),
74
+ ...(snippet ? { snippet } : {}),
75
+ ...(date ? { publishedAt: date } : {}),
76
+ };
77
+ })
78
+ .filter(Boolean);
79
+
80
+ return { sources: uniqueSources(sources, limit), truncated: false };
81
+ }
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@ import { SettingsConflictError } from "@deepseek-ai/dsh-settings";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import fs from "node:fs";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
5
6
  import os from "node:os";
6
7
  import path from "node:path";
7
8
  import { exec, execFile } from "node:child_process";
@@ -16,7 +17,7 @@ import { selectEngines, planTopUp, resolveMinSources, describeTarget, credential
16
17
  import { promptLanguageOf, systemCopy, toolDescription, toolParam, localizedEffect, effectivePromptText, normalizePromptPages, PROMPT_SEGMENTS } from "./prompt_i18n.js";
17
18
  import { SERP_FAMILY, searchSerpEngine } from "./serp_engines.js";
18
19
  import { ALL_ENGINES, FREE_ENGINES, TIME_ENGINES, EXPLICIT_ONLY_ENGINES, DEFAULT_FALLBACK_ORDER } from "./engine_meta.js";
19
- import { createCooldownStore, cooldownDelayFor, isRegionLocked, keyCooldownId, SESSION, SHORT_COOLDOWN_MS } from "./cooldown.js";
20
+ import { createCooldownStore, cooldownDelayFor, isRegionLocked, keyCooldownId, DEFAULT_QUOTA_COOLDOWN_MS, SESSION, SHORT_COOLDOWN_MS } from "./cooldown.js";
20
21
  import { stripLoneSurrogates, truncateText, sanitizeSource, sanitizeSources, sanitizeSearchResult, sanitizeError } from "./safe_text.js";
21
22
  import { rememberSecret, redactSecrets, environmentSecrets } from "./redact.js";
22
23
  import { buildDoctorReport } from "./doctor.js";
@@ -45,6 +46,7 @@ import { searchGoogle } from "./engines/google.js";
45
46
  import { searchMetaso } from "./engines/metaso.js";
46
47
  import { searchYandex } from "./engines/yandex.js";
47
48
  import { searchYuanbao } from "./engines/yuanbao.js";
49
+ import { searchSpecStream } from "./engines/specstream.js";
48
50
  import { createEngineRuntime, ENGINE_CONCURRENCY_LIMIT, SERP_CONCURRENCY_LIMIT } from "./engine_runtime.js";
49
51
  import { classifyIntent, preferForIntent } from "./intent.js";
50
52
  import { dedupeNearDuplicates } from "./dedupe.js";
@@ -1371,6 +1373,22 @@ function toView(descriptor) {
1371
1373
  */
1372
1374
  export function bridgeAuthRejection(request, connection) {
1373
1375
  if (connection === undefined || connection === null) return 503;
1376
+ // Newer DSH exposes admit(); older DSH exposes requestRejection.
1377
+ const admit = connection.admit;
1378
+ if (typeof admit === "function") {
1379
+ try {
1380
+ const admission = admit.call(connection, request);
1381
+ if (admission && typeof admission === "object" && "rejection" in admission) {
1382
+ return admission.rejection;
1383
+ }
1384
+ if (admission && typeof admission === "object" && "peer" in admission) {
1385
+ return undefined;
1386
+ }
1387
+ return 503;
1388
+ } catch {
1389
+ return 503;
1390
+ }
1391
+ }
1374
1392
  const reject = connection.requestRejection;
1375
1393
  if (typeof reject !== "function") return 503;
1376
1394
  try {
@@ -1627,7 +1645,10 @@ function makeBridgeRoutes(settings, search, testEngine, getCredentials, getConfi
1627
1645
  const guard = (req, res) => {
1628
1646
  const rejection = bridgeAuthRejection(req, connection());
1629
1647
  if (rejection !== undefined) {
1630
- writeJson(res, rejection, { error: "host authentication required" });
1648
+ const error = rejection === 401 || rejection === 403
1649
+ ? "host authentication required"
1650
+ : "bridge admission unavailable";
1651
+ writeJson(res, rejection, { error });
1631
1652
  return false;
1632
1653
  }
1633
1654
  if (!isBridgeRequestAllowed(req)) {
@@ -1844,6 +1865,7 @@ const KEY_REF_MAP = {
1844
1865
  metasoApiKey: "METASO_API_KEY",
1845
1866
  yandexApiKey: "YANDEX_API_KEY",
1846
1867
  yuanbaoApiKey: "TENCENTCLOUD_WSA_APIKEY",
1868
+ specstreamApiKey: "SPECSTREAM_API_KEY",
1847
1869
  deepseekApiKey: "DEEPSEEK_API_KEY",
1848
1870
  deepseekToolsApiKey: "DEEPSEEK_TOOLS_API_KEY",
1849
1871
  // 设置页写入的凭据槽位保持旧名,已保存的 key 不受影响;读取时 YDC_API_KEY 优先(见 resolveYoucomApiKey)
@@ -1871,6 +1893,8 @@ const Config = z.object({
1871
1893
  sidebarEntry: z.boolean().default(true).volatile(),
1872
1894
  // 关闭后不注册 /free-search-engine 与 /free-search;设置仍在插件页。
1873
1895
  slashCommands: z.boolean().default(true).volatile(),
1896
+ // 默认 false:配了 key 的引擎一律用 key。开启后先走免 key 档,免 key 档限流/额度/鉴权/网络失败时才改用 key,省 key 的额度。
1897
+ keylessFirst: z.boolean().default(false).volatile(),
1874
1898
  disabledEngines: z.array(z.string()).default([]).volatile(),
1875
1899
  // #106:白名单。非空时只有这些引擎可用(等于把其余引擎全部禁用),默认空 = 不限制。
1876
1900
  allowedEngines: z.array(z.string()).default([]).volatile(),
@@ -1943,6 +1967,7 @@ const Config = z.object({
1943
1967
  serpbaseApiKey: z.string().role("secret").volatile(),
1944
1968
  serplyApiKey: z.string().role("secret").volatile(),
1945
1969
  outcrawlApiKey: z.string().role("secret").volatile(),
1970
+ specstreamApiKey: z.string().role("secret").volatile(),
1946
1971
  googleCseApiKey: z.string().role("secret").volatile(),
1947
1972
  deepseekApiKey: z.string().role("secret").volatile(),
1948
1973
  deepseekToolsApiKey: z.string().role("secret").volatile(),
@@ -2013,6 +2038,7 @@ const LEGACY_MIGRATABLE_KEYS = [
2013
2038
  "serpbaseApiKey",
2014
2039
  "serplyApiKey",
2015
2040
  "outcrawlApiKey",
2041
+ "specstreamApiKey",
2016
2042
  "deepseekApiKey",
2017
2043
  "snippetMaxChars",
2018
2044
  "snippetBudgetChars",
@@ -2311,7 +2337,15 @@ function apply(ctx, config) {
2311
2337
  for (const ring of keyRings.values()) max = Math.max(max, ring.keys.length);
2312
2338
  return max;
2313
2339
  };
2340
+ // keylessFirst: while an engine runs its keyless tier, key lookups come back empty so
2341
+ // the engine's own "key ? keyed API : keyless endpoint" branch takes the keyless side.
2342
+ const keylessTier = new AsyncLocalStorage();
2314
2343
  const resolveApiKey = async (envName, settingsKey, peek = false) => {
2344
+ if (keylessTier.getStore() === true) {
2345
+ const ring = keyRings.get(envName);
2346
+ if (ring) ring.lastUsed = undefined;
2347
+ return "";
2348
+ }
2315
2349
  let raw = "";
2316
2350
  const credentials = getCredentials();
2317
2351
  if (credentials) {
@@ -2384,8 +2418,8 @@ function apply(ctx, config) {
2384
2418
  };
2385
2419
  const resolveClaudeKey = () => resolveApiKey("ANTHROPIC_API_KEY", "claudeApiKey");
2386
2420
  // You.com:标准名 YDC_API_KEY,旧名 YOUCOM_API_KEY 作为别名继续生效(不配 key 走免 key 档)
2387
- const resolveYoucomKey = () =>
2388
- resolveYoucomApiKey({
2421
+ const resolveYoucomKey = async () =>
2422
+ keylessTier.getStore() === true ? "" : resolveYoucomApiKey({
2389
2423
  resolveCredential: async (ref) => {
2390
2424
  const credentials = getCredentials();
2391
2425
  if (!credentials) return "";
@@ -2526,6 +2560,8 @@ function apply(ctx, config) {
2526
2560
  site: cfg.yuanbaoSite,
2527
2561
  }, timeRange, signal);
2528
2562
  },
2563
+ specstream: async ({ query, maxResults, signal }) =>
2564
+ searchSpecStream(query, maxResults, await requireEngineKey("SPECSTREAM_API_KEY", "specstreamApiKey", "SpecStream", " (get one at https://specstream.ai/signup?src=dsh-free-search)"), signal),
2529
2565
  you: async ({ query, maxResults, signal }) =>
2530
2566
  searchYoucom(query, maxResults, await resolveYoucomKey(), signal),
2531
2567
  tinyfish: async ({ query, maxResults, timeRange, signal }) =>
@@ -2584,6 +2620,43 @@ function apply(ctx, config) {
2584
2620
  searchSerpEngine(id, query, { maxResults, timeRange, signal });
2585
2621
  }
2586
2622
 
2623
+ // keylessFirst: engines that have both a keyless tier and a keyed tier. Probes say
2624
+ // whether a key is configured (peek only, no ring position is consumed).
2625
+ const keyedTierProbes = {
2626
+ exa: () => resolveApiKey("EXA_API_KEY", "exaApiKey", true),
2627
+ tavily: () => resolveApiKey("TAVILY_API_KEY", "tavilyApiKey", true),
2628
+ keenable: () => resolveApiKey("KEENABLE_API_KEY", "keenableApiKey", true),
2629
+ firecrawl: () => resolveApiKey("FIRECRAWL_API_KEY", "firecrawlApiKey", true),
2630
+ parallel: () => resolveApiKey("PARALLEL_API_KEY", "parallelApiKey", true),
2631
+ anysearch: () => resolveApiKey("ANYSEARCH_API_KEY", "anysearchApiKey", true),
2632
+ you: () => resolveYoucomKey(),
2633
+ };
2634
+ const KEYLESS_RETRY_WITH_KEY = new Set(["quota", "auth", "bot-wall", "transient"]);
2635
+ const keylessRestUntil = new Map();
2636
+ // Run the keyless tier first when a key is configured and keylessFirst is on; if that
2637
+ // tier is out of quota, rate limited, needs auth or is unreachable, run again with the key.
2638
+ // A failed keyless tier rests for a while so the next searches go straight to the key.
2639
+ const withKeylessFirst = async (engine, run) => {
2640
+ const probe = keyedTierProbes[engine];
2641
+ if (!probe || current().keylessFirst !== true) return run();
2642
+ if ((keylessRestUntil.get(engine) ?? 0) > Date.now() || !(await probe())) return run();
2643
+ try {
2644
+ return await keylessTier.run(true, run);
2645
+ } catch (error) {
2646
+ const failure = classifyFailure(error);
2647
+ const keylessBlocked = engine === "firecrawl" && isFirecrawlKeylessBlocked();
2648
+ if (!keylessBlocked && !KEYLESS_RETRY_WITH_KEY.has(failure.class)) throw error;
2649
+ const rest = Math.min(cooldownDelayFor(failure.class, failure.message) ?? SHORT_COOLDOWN_MS, DEFAULT_QUOTA_COOLDOWN_MS);
2650
+ keylessRestUntil.set(engine, Date.now() + rest);
2651
+ logger.warn(`free-search: ${engine} keyless tier failed [${failure.class}] (${redactSecrets(failure.message, environmentSecrets())}), retrying with the configured key`);
2652
+ return run();
2653
+ }
2654
+ };
2655
+ for (const id of Object.keys(keyedTierProbes)) {
2656
+ const keyFirstRunner = engineRunners[id];
2657
+ engineRunners[id] = (args) => withKeylessFirst(id, () => keyFirstRunner(args));
2658
+ }
2659
+
2587
2660
  const provider = {
2588
2661
  id: "ddg",
2589
2662
  available() {
@@ -3231,6 +3304,11 @@ function apply(ctx, config) {
3231
3304
  if (!key) return { ok: false, error: "TENCENTCLOUD_WSA_APIKEY not configured" };
3232
3305
  return await searchYuanbao(q, n, key, { mode: cfg.yuanbaoMode, site: cfg.yuanbaoSite }, tr);
3233
3306
  }
3307
+ case "specstream": {
3308
+ const key = await resolveApiKey("SPECSTREAM_API_KEY", "specstreamApiKey");
3309
+ if (!key) return { ok: false, error: "SPECSTREAM_API_KEY not configured" };
3310
+ return await searchSpecStream(q, n, key);
3311
+ }
3234
3312
  case "agy": {
3235
3313
  if (!agyAvailable()) return { ok: false, error: "Antigravity CLI not installed (install Antigravity or set AGY_BIN)" };
3236
3314
  return await searchAgy(q, n, {});
@@ -3312,7 +3390,7 @@ function apply(ctx, config) {
3312
3390
  for (let i = 0; ; i += 1) {
3313
3391
  const startedAt = Date.now();
3314
3392
  try {
3315
- const result = await engineRuntime.run(engine, engineConcurrency(engine), () => attempt());
3393
+ const result = await engineRuntime.run(engine, engineConcurrency(engine), () => withKeylessFirst(engine, attempt));
3316
3394
  engineRuntime.record(engine, { ms: Date.now() - startedAt, sources: result.sources?.length ?? 0 });
3317
3395
  return result;
3318
3396
  } catch (error) {
@@ -4321,6 +4399,7 @@ export {
4321
4399
  searchSerpbase,
4322
4400
  searchSerply,
4323
4401
  searchOutcrawl,
4402
+ searchSpecStream,
4324
4403
  searchGoogle,
4325
4404
  searchTinyfish,
4326
4405
  searchJina,
@@ -0,0 +1,144 @@
1
+ // Headless engine dispatch for the MCP server. Free engines stay keyless;
2
+ // keyed engines read credentials from the MCP process environment and are only
3
+ // used when the caller names them (auto never spends paid quota).
4
+ import { searchBing } from "./engines/bing.js";
5
+ import { searchDdgHtml } from "./engines/ddg.js";
6
+ import { searchDdgLite } from "./engines/ddg-lite.js";
7
+ import { searchGoogle } from "./engines/google.js";
8
+ import { searchBaidu } from "./engines/baidu.js";
9
+ import { searchBrave } from "./engines/brave.js";
10
+ import { searchMetaso } from "./engines/metaso.js";
11
+ import { searchZhipu } from "./engines/zhipu.js";
12
+ import { searchYandex } from "./engines/yandex.js";
13
+ import { searchYuanbao } from "./engines/yuanbao.js";
14
+ import { searchDeepSeekTools } from "./engines/deepseek-tools.js";
15
+ import { parseTimeRange } from "./engines/shared.js";
16
+
17
+ export const MCP_ENGINE_IDS = [
18
+ "auto",
19
+ "bing",
20
+ "ddg",
21
+ "ddg-lite",
22
+ "google",
23
+ "baidu",
24
+ "brave",
25
+ "metaso",
26
+ "yandex",
27
+ "yuanbao",
28
+ "deepseek-tools",
29
+ "zhipu",
30
+ ];
31
+
32
+ export const MCP_FREE_ENGINES = ["bing", "ddg", "ddg-lite"];
33
+ export const MCP_KEYED_ENGINES = ["google", "baidu", "brave", "metaso", "yandex", "yuanbao", "deepseek-tools", "zhipu"];
34
+
35
+ function env(name, fallback = "") {
36
+ return String(process.env[name] ?? fallback).trim();
37
+ }
38
+
39
+ function requireEnv(name, label) {
40
+ const value = env(name);
41
+ if (!value) throw new Error(`${label} requires ${name}`);
42
+ return value;
43
+ }
44
+
45
+ function timeRangeOf(args) {
46
+ return parseTimeRange(args?.time_range);
47
+ }
48
+
49
+ export async function runMcpEngine(id, query, options = {}) {
50
+ const engine = String(id ?? "").trim().toLowerCase() || "auto";
51
+ if (!MCP_ENGINE_IDS.includes(engine)) throw new Error(`unknown engine "${engine}"`);
52
+ const maxResults = Math.min(Math.max(Number(options.maxResults) || 8, 1), 20);
53
+ const safeSearch = String(options.safeSearch ?? env("MCP_SAFE_SEARCH", "off")).trim().toLowerCase();
54
+ const lang = env("MCP_LANG", "zh");
55
+ const timeRange = timeRangeOf(options);
56
+ const signal = options.signal;
57
+
58
+ if (engine === "auto") {
59
+ const errors = [];
60
+ for (const candidate of MCP_FREE_ENGINES) {
61
+ try {
62
+ const result = await runMcpEngine(candidate, query, options);
63
+ if (result.sources.length > 0) return result;
64
+ errors.push(`${candidate}: no results`);
65
+ } catch (error) {
66
+ errors.push(`${candidate}: ${error?.message ?? String(error)}`);
67
+ }
68
+ }
69
+ throw new Error(`all free engines failed (${errors.join("; ")})`);
70
+ }
71
+
72
+ switch (engine) {
73
+ case "bing":
74
+ return {
75
+ engine,
76
+ ...(await searchBing(query, maxResults, {
77
+ lang,
78
+ safeSearch,
79
+ ...(env("MCP_BING_MARKET") ? { bingMarket: env("MCP_BING_MARKET") } : {}),
80
+ }, signal)),
81
+ };
82
+ case "ddg":
83
+ return { engine, ...(await searchDdgHtml(query, maxResults, { safeSearch, timeRange }, signal)) };
84
+ case "ddg-lite":
85
+ return { engine, ...(await searchDdgLite(query, maxResults, { safeSearch, timeRange }, signal)) };
86
+ case "google": {
87
+ const key = requireEnv("GOOGLE_CSE_API_KEY", "Google");
88
+ const cx = requireEnv("GOOGLE_CSE_ID", "Google");
89
+ return {
90
+ engine,
91
+ ...(await searchGoogle(query, maxResults, key, cx, timeRange, { lang, safeSearch }, signal)),
92
+ };
93
+ }
94
+ case "baidu":
95
+ return { engine, ...(await searchBaidu(query, maxResults, requireEnv("BAIDU_API_KEY", "Baidu"), timeRange, signal)) };
96
+ case "brave":
97
+ return { engine, ...(await searchBrave(query, maxResults, requireEnv("BRAVE_API_KEY", "Brave"), timeRange, signal)) };
98
+ case "metaso": {
99
+ const key = requireEnv("METASO_API_KEY", "Metaso");
100
+ return {
101
+ engine,
102
+ ...(await searchMetaso(query, maxResults, key, env("MCP_METASO_SCOPE", "webpage"), timeRange, signal)),
103
+ };
104
+ }
105
+ case "yandex": {
106
+ const key = requireEnv("YANDEX_API_KEY", "Yandex");
107
+ const folderId = requireEnv("YANDEX_FOLDER_ID", "Yandex");
108
+ return {
109
+ engine,
110
+ ...(await searchYandex(query, maxResults, key, folderId, {
111
+ searchType: env("MCP_YANDEX_SEARCH_TYPE", "auto"),
112
+ lang,
113
+ safeSearch,
114
+ }, timeRange, signal)),
115
+ };
116
+ }
117
+ case "yuanbao": {
118
+ const key = requireEnv("TENCENTCLOUD_WSA_APIKEY", "Yuanbao");
119
+ return {
120
+ engine,
121
+ ...(await searchYuanbao(query, maxResults, key, {
122
+ mode: env("MCP_YUANBAO_MODE", "0"),
123
+ site: env("MCP_YUANBAO_SITE"),
124
+ }, timeRange, signal)),
125
+ };
126
+ }
127
+ case "deepseek-tools": {
128
+ const key = env("DEEPSEEK_TOOLS_API_KEY") || requireEnv("DEEPSEEK_API_KEY", "DeepSeek");
129
+ return {
130
+ engine,
131
+ ...(await searchDeepSeekTools(query, maxResults, key, timeRange, signal, env("MCP_DEEPSEEK_TOOLS_URL"))),
132
+ };
133
+ }
134
+ case "zhipu": {
135
+ const key = requireEnv("ZHIPU_API_KEY", "Zhipu");
136
+ return {
137
+ engine,
138
+ ...(await searchZhipu(query, maxResults, key, timeRange, signal, env("MCP_ZHIPU_SEARCH_ENGINE", "search_std"))),
139
+ };
140
+ }
141
+ default:
142
+ throw new Error(`unknown engine "${engine}"`);
143
+ }
144
+ }
package/lib/mcp_server.js CHANGED
@@ -1,14 +1,11 @@
1
1
  // Headless MCP surface for dsh-free-search: stdio JSON-RPC, no DSH runtime.
2
- // First version exposes web_search (free keyless engines) and web_fetch.
2
+ // Exposes web_search (free engines plus explicitly named keyed engines) and web_fetch.
3
3
  import fs from "node:fs";
4
- import { searchBing } from "./engines/bing.js";
5
- import { searchDdgHtml } from "./engines/ddg.js";
6
- import { searchDdgLite } from "./engines/ddg-lite.js";
7
4
  import { createFetchProvider } from "./fetch_provider.js";
5
+ import { runMcpEngine, MCP_ENGINE_IDS } from "./mcp_engines.js";
8
6
 
9
7
  const SERVER_NAME = "dsh-free-search";
10
8
  const PROTOCOL_VERSIONS = ["2024-11-05", "2025-03-26", "2025-06-18"];
11
- const ENGINE_IDS = ["auto", "bing", "ddg", "ddg-lite"];
12
9
  const SAFE_SEARCH = ["off", "moderate", "strict"];
13
10
 
14
11
  const TOOLS = [
@@ -21,8 +18,9 @@ const TOOLS = [
21
18
  properties: {
22
19
  query: { type: "string", description: "Search query." },
23
20
  max_results: { type: "integer", minimum: 1, maximum: 20, description: "Number of results, default 8." },
24
- engine: { type: "string", enum: ENGINE_IDS, description: "Engine id; auto tries Bing then DuckDuckGo." },
21
+ engine: { type: "string", enum: MCP_ENGINE_IDS, description: "Engine id; auto tries Bing then DuckDuckGo. Keyed engines are explicit." },
25
22
  safe_search: { type: "string", enum: SAFE_SEARCH, description: "Safe-search level." },
23
+ time_range: { type: "string", enum: ["day", "week", "month", "year"], description: "Optional freshness filter." },
26
24
  },
27
25
  required: ["query"],
28
26
  additionalProperties: false,
@@ -84,36 +82,10 @@ export async function searchWeb(args = {}) {
84
82
  if (!query) throw new Error("query is required");
85
83
  const maxResults = Math.min(Math.max(Number(args.max_results) || numberEnv("MCP_MAX_RESULTS", 8, 1, 20), 1), 20);
86
84
  const requested = String(args.engine ?? env("MCP_SEARCH_ENGINE", "auto")).trim().toLowerCase();
87
- if (!ENGINE_IDS.includes(requested)) throw new Error(`unknown engine "${requested}"`);
85
+ if (!MCP_ENGINE_IDS.includes(requested)) throw new Error(`unknown engine "${requested}"`);
88
86
  const safeSearch = String(args.safe_search ?? env("MCP_SAFE_SEARCH", "off")).trim().toLowerCase();
89
87
  if (!SAFE_SEARCH.includes(safeSearch)) throw new Error(`invalid safe_search "${safeSearch}"`);
90
- const lang = env("MCP_LANG", "zh");
91
- const order = requested === "auto" ? ["bing", "ddg", "ddg-lite"] : [requested];
92
- const errors = [];
93
-
94
- for (const engine of order) {
95
- try {
96
- let result;
97
- if (engine === "bing") {
98
- result = await searchBing(query, maxResults, {
99
- lang,
100
- safeSearch,
101
- ...(env("MCP_BING_MARKET") ? { bingMarket: env("MCP_BING_MARKET") } : {}),
102
- });
103
- } else if (engine === "ddg") {
104
- result = await searchDdgHtml(query, maxResults, { safeSearch });
105
- } else {
106
- result = await searchDdgLite(query, maxResults, { safeSearch });
107
- }
108
- const sources = Array.isArray(result?.sources) ? result.sources : [];
109
- if (sources.length > 0) return { engine, sources: sources.slice(0, maxResults) };
110
- errors.push(`${engine}: no results`);
111
- } catch (error) {
112
- errors.push(`${engine}: ${error?.message ?? String(error)}`);
113
- }
114
- }
115
-
116
- throw new Error(`all engines failed (${errors.join("; ")})`);
88
+ return runMcpEngine(requested, query, { maxResults, safeSearch, time_range: args.time_range });
117
89
  }
118
90
 
119
91
  let fetchProvider = null;
@@ -229,6 +229,7 @@ export const REQUIRED_CREDENTIALS = {
229
229
  metaso: [{ env: "METASO_API_KEY", settings: "metasoApiKey" }],
230
230
  yandex: [{ env: "YANDEX_API_KEY", settings: "yandexApiKey" }],
231
231
  yuanbao: [{ env: "TENCENTCLOUD_WSA_APIKEY", settings: "yuanbaoApiKey" }],
232
+ specstream: [{ env: "SPECSTREAM_API_KEY", settings: "specstreamApiKey" }],
232
233
  tinyfish: [{ env: "TINYFISH_API_KEY", settings: "tinyfishApiKey" }],
233
234
  jina: [{ env: "JINA_API_KEY", settings: "jinaApiKey" }],
234
235
  baidu: [{ env: "BAIDU_API_KEY", settings: "baiduApiKey" }],
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.54",
4
- "description": "Free web search for DeepSeek Harness: 41 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/Brave/Zhipu/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao/Google CSE/Metaso/Yandex/Yuanbao with key; OpenAI/Gemini/Claude model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + editable zh/en language pools + multi mode (parallel full language-pool merge) + multi_search cross-source tool + failure-aware fallback (quota/auth cooldown, transient retry, fallbackOn) + time filtering + platform search + domain blocklist (blockedDomains) + web_fetch, with web settings UI, plus a standalone stdio MCP server.",
3
+ "version": "0.9.55",
4
+ "description": "Free web search for DeepSeek Harness: 42 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/Brave/Zhipu/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao/Google CSE/Metaso/Yandex/Yuanbao/SpecStream with key; OpenAI/Gemini/Claude model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + editable zh/en language pools + multi mode (parallel full language-pool merge) + multi_search cross-source tool + failure-aware fallback (quota/auth cooldown, transient retry, fallbackOn) + time filtering + platform search + domain blocklist (blockedDomains) + web_fetch, with web settings UI, plus a standalone stdio MCP server.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -34,6 +34,7 @@
34
34
  "serpbase",
35
35
  "serply",
36
36
  "outcrawl",
37
+ "specstream",
37
38
  "search",
38
39
  "free",
39
40
  "brave",