dsh-free-search 0.9.40 → 0.9.41

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
@@ -48,7 +48,7 @@
48
48
 
49
49
  - **统一引擎回退** —— 任何引擎失败(付费/免费,缺 key/401/限流/网络)自动轮流尝试下一个引擎:首选引擎 → 其他引擎(exa/tavily/keenable/firecrawl/parallel/you 无 key 也会尝试,因为它们自带 keyless 免费额度)→ 剩余免费引擎,搜索永不直接失败;结果顶部注明实际生效的引擎(如 `Note: perplexity unavailable or failed, using exa.`);失败按类别处理:额度/鉴权失败 → 本会话冷却该引擎,反爬 → 短退避,超时/5xx/限流 → 同引擎重试一次,解析失败/0 结果 → 不冷却(详见下文「失败分类与引擎冷却」)。
50
50
  - **多 key 轮换** —— 任何 key 字段(或对应环境变量)都可以用逗号 / 分号 / 换行分隔多把 key;平时按请求轮流使用(round-robin,避免单 key 撞 QPS/RPM 风控),遇到 401/402/429(鉴权失败、额度耗尽、限流)先轮换同一引擎的下一把,再走引擎回退;`multi` 模式同样生效(#96)。
51
- - **按 key 冷却与诊断** —— 429 与额度错误按 key 分别冷却,同一引擎的其他 key 不受牵连;冷却状态写入磁盘,重启后仍在;失败信息和日志里的 key 一律打码;设置页底部的「诊断」按钮列出每个引擎当前为什么不可用、冷却还剩多久,以及本次进程内的调用次数、成功/空/失败和平均耗时;同一引擎并发超过 2 会排队(HTML SERP 为 1),避免免费引擎被同时打爆。
51
+ - **按 key 冷却与诊断** —— 429 与额度错误按 key 分别冷却,同一引擎的其他 key 不受牵连;冷却状态写入磁盘,重启后仍在;失败信息和日志里的 key 一律打码;设置页底部的「诊断」按钮列出每个引擎当前为什么不可用、冷却还剩多久,以及本次进程内的调用次数、成功/空/失败和平均耗时;同一引擎并发超过 2 会排队(HTML SERP 为 1),避免免费引擎被同时打爆;诊断还会标注当前 web search/fetch provider,被其他插件接管时给出互斥警告。
52
52
  - **自带更新** —— 卡片底部显示当前版本和「检查更新」;npm 安装的版本可一键升级到 latest,本地 link 开发模式改为跳转 npm 页面并提示 `git pull`。
53
53
  - **引擎测试** —— `free_search_test` 工具让 agent 一键测试所有引擎;设置页也有「测试引擎」按钮(直测当前引擎,不走回退链,付费引擎无 key 会明确报错)。
54
54
  - **截断安全** —— 标题和摘要按码点截断,搜索结果、工具输出和 `web_fetch` 正文在离开插件前统一清除孤立代理;含 emoji 的结果不会再让会话历史出现无法序列化的字符(#108)。
@@ -58,7 +58,8 @@
58
58
 
59
59
  #### Multi 与语言池
60
60
 
61
- - **Multi 模式** —— 可把搜索引擎设为 `Multi Search`:`web_search` 按查询语言并发**对应语言池的全部**已启用引擎(不再是前 3 个;中文/英文池可在设置页编辑,每池最低 2 个引擎)、按 URL 合并去重(同站判定用 **eTLD+1**)、跨源命中的结果优先;设置页有 **Fast / Balanced / Deep** 三档强度,也可手填并发上限与目标成功源数;整轮检索共享 **30 秒总预算**,到点返回已有结果;合并结果的条数上限可在设置页调整(对应 `multiMaxResults`,默认 20,最大 100,单次 `maxResults` 只能要得更少)。代价是成倍消耗额度;multi 失败会自动退回单引擎回退链。
61
+ - **Multi 模式** —— 可把搜索引擎设为 `Multi Search`:`web_search` 按查询语言并发**对应语言池的全部**已启用引擎(不再是前 3 个;中文/英文池可在设置页编辑,每池最低 2 个引擎)、按 URL 合并去重(同站判定用 **eTLD+1**)、跨源命中的结果优先;设置页有 **Fast / Balanced / Deep** 三档强度,也可手填并发上限与目标成功源数;整轮检索共享 **30 秒总预算**,到点返回已有结果;合并结果的条数上限可在设置页调整(对应 `multiMaxResults`,默认 20,最大 100,单次 `maxResults` 只能要得更少)。合并结果会用 MinHash 去掉近重复来源。代价是成倍消耗额度;multi 失败会自动退回单引擎回退链。
62
+ - **按意图路由** —— Auto 在未自定义回退顺序时,按查询领域(金融 / 学术 / 代码 / 新闻 / 购物)重排当前语言池;只调整已有引擎的先后,不新增引擎、不改回退集合。
62
63
 
63
64
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-performance.png" alt="性能:缓存与 Multi 档位" width="100%" />
64
65
  <sub>▲ 性能:结果缓存时长与 Multi 的 Fast / Balanced / Deep 档位</sub>
@@ -84,7 +85,7 @@
84
85
  - **平台搜索(platform_search)** —— 搜 GitHub / V2EX / B站 / Reddit / Hacker News / Stack Overflow / 维基百科 / npm / YouTube / Vimeo / 掘金 / 豆瓣 / Qiita(公开 API 或免 key 抓取,零依赖);X (Twitter) 经本地 Grok Build CLI(需 SuperGrok / X Premium 登录)。
85
86
  - **垂直领域直查(domain_search)** —— 41 个免 key 垂直源直查:包/版本(PyPI、crates、GitHub releases、endoflife…)、学术(arXiv、Crossref、OpenAlex、Semantic Scholar、PubMed、dblp、Zenodo…)、安全(NVD、OSV、CISA KEV)、金融(SEC EDGAR、IMF、World Bank、CFETS、Yahoo Finance、CoinGecko…)、法律(US Federal Register、US CourtListener、openlegaldata、UK legislation)、新闻(Google News、GDELT)等。
86
87
  - **视频搜索(video_search)** —— 跨站找视频:Bing Videos + DuckDuckGo Videos(免 key,失败互相回退),返回视频链接、标题与来源/时长等元信息。
87
- - **一次调用完成研究(research)** —— 多引擎并发搜索 → 候选重排 → 分层抓取正文 → 段落选窗 → 带出处的 Markdown 证据包;模型组件(重排/嵌入/决策模型)全部可选,缺失或失败时静默回退规则路径。
88
+ - **一次调用完成研究(research)** —— 多引擎并发搜索 → 候选重排 → 分层抓取正文 → 段落选窗 → 带出处的 Markdown 证据包;模型组件(重排/嵌入/决策模型)全部可选,缺失或失败时静默回退规则路径;输出附带证据质量闸门(high / medium / low 与结论上限),证据不足时明确提示先核验再下结论。
88
89
  - **检索正文缓存(cache_search)** —— 全文检索 `research` 抓过的正文(`node:sqlite` 持久缓存,存储 7 天;`node:sqlite` 不可用时自动降级为 no-op,免 flag 需 ≥ 22.13,22.5–22.12 需 `--experimental-sqlite`)。
89
90
  - **干净集成** —— 实现官方 `WebSearchProvider` seam 接口,与官方插件共存。
90
91
  - **时间过滤** —— `advanced_search` 工具支持 `timeRange`:固定档、自定义相对值、绝对日期三种形式(详见下方逻辑说明)。
@@ -585,7 +586,7 @@ Search engine test:
585
586
 
586
587
  #### 离线自检断言(tools/)
587
588
 
588
- 仓库自带 **51 个**零依赖断言脚本(合计 **805 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
589
+ 仓库自带 **55 个**零依赖断言脚本(合计 **827 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
589
590
 
590
591
  | 脚本 | 覆盖 | 运行(项数) |
591
592
  |---|---|---|
@@ -598,6 +599,9 @@ Search engine test:
598
599
  | `assert-maintenance.mjs` | 维护面:CI 在 Node 20/22/24 跑全部断言并过打包闸门、发布脚本会 bump / 校验 / 打 tag / 可发布、恢复官方 provider 的桥接与设置页按钮 | `node tools/assert-maintenance.mjs`(4) |
599
600
  | `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 36 个引擎且免费/按次标记正确、index 不引用引擎私有名 | `node tools/assert-engine-modules.mjs`(6) |
600
601
  | `assert-bing-relevance.mjs` | Bing 相关性(#112):单字中文 token 被剔除、无关替代 SERP 被拒、真正相关的结果通过、只命中通用引擎名的整批被拒、单一 token 覆盖一半时放行、单字/纯数字查询的显式行为 | `node tools/assert-bing-relevance.mjs`(6) |
602
+ | `assert-quality.mjs` | 研究证据闸门:8 源 / 3 域 / 3 正文 / 2 日期为 high,3 源 / 2 域 / 1 正文为 medium,单源与失败注记为 low,空包为 low,research 的 schema/输出/brief 接线 | `node tools/assert-quality.mjs`(6) |
603
+ | `assert-dedupe.mjs` | 近重复去重:MinHash 同文本同签名、同 URL 去重、跨站转载去重、不同文章保留且顺序不变、阈值可调、provider 与 multi 两条路径接线 | `node tools/assert-dedupe.mjs`(6) |
604
+ | `assert-intent-routing.mjs` | 意图路由:五类领域与 general 分类、偏好重排稳定、Auto 头部按领域、自定义回退顺序不被重排、时间过滤仍生效、接线 | `node tools/assert-intent-routing.mjs`(6) |
601
605
  | `assert-result-ranking.mjs` | 合并排序:**eTLD+1 同域判定** / 域名轮转 / `seenIn` 降为末位 / 时效仅带时间过滤时生效 | `node tools/assert-result-ranking.mjs`(31) |
602
606
  | `assert-url-norm.mjs` | URL 规范化:只剔已审计的 tracking 参数,保留可能区分资源的参数 | `node tools/assert-url-norm.mjs`(72) |
603
607
  | `assert-prompt-contract.mjs` | 系统提示词契约:**检索≠抓取**、不可信边界、模型内置搜索只在显式选中时运行 | `node tools/assert-prompt-contract.mjs`(9) |
@@ -705,7 +709,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
705
709
 
706
710
  - **Unified Engine Fallback** — Any engine failure (paid or free, missing key, 401, rate limit, network error) automatically tries the next engine: the configured engine first, then other engines (exa/tavily/keenable/firecrawl/parallel/you are tried even without a key because they have built-in keyless quota), then the remaining free engines (Bing/AnySearch etc.) — with a note attached to the results naming the engine that actually served them (e.g. `Note: perplexity unavailable or failed, using exa.`). Failures are classified: quota/auth failures cool the engine down for the session, anti-bot walls back off briefly, timeout/5xx/rate-limit failures retry the same engine once, and parse errors / 0 results are reported without cooling it down. Search never fails outright.
707
711
  - **Multi-key rotation** — Any key field (or its env var) accepts several keys separated by commas, semicolons or newlines. Keys are used round-robin per request, and on 401/402/429 the same engine retries with the next key before the engine-level fallback runs. This also applies inside `multi` mode (#96).
708
- - **Per-key cooldowns and diagnostics** — a 429 or quota error cools the key that hit it, not every other key of the same engine; the state is written to disk and survives a restart; keys are masked in failure text and logs; the Diagnose button at the bottom of the settings page lists why each engine is currently unavailable, how long its cooldown has left, and the in-process call count, success/empty/failure split and average latency; concurrent calls to one engine queue beyond 2 (1 for HTML SERP), so a free engine is not hammered in the same second.
712
+ - **Per-key cooldowns and diagnostics** — a 429 or quota error cools the key that hit it, not every other key of the same engine; the state is written to disk and survives a restart; keys are masked in failure text and logs; the Diagnose button at the bottom of the settings page lists why each engine is currently unavailable, how long its cooldown has left, and the in-process call count, success/empty/failure split and average latency; concurrent calls to one engine queue beyond 2 (1 for HTML SERP), so a free engine is not hammered in the same second; the doctor also reports the active web search/fetch provider and warns when another plugin owns it (providers are mutually exclusive).
709
713
  - **Built-in updater** — the card footer shows the version and a Check update button; npm installs upgrade to latest in one click, while a local link install links to the npm page and points at git pull instead.
710
714
  - **Engine Testing** — `free_search_test` for the agent to check all engines in one call; the settings UI also has a "Test engine" button that tests the selected engine directly (no fallback chain; paid engines without a key report an explicit error).
711
715
  - **Truncation safety** — titles and snippets are cut by code point, and search results, tool output and web_fetch bodies are stripped of lone surrogates before leaving the plugin; an emoji can no longer make history unserializable (#108).
@@ -715,7 +719,8 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
715
719
 
716
720
  #### Multi and language pools
717
721
 
718
- - **Multi mode** — pick `Multi Search` as the engine: web_search queries **every enabled engine of the query's language pool** concurrently (no longer top 3; zh/en pools editable in the settings UI, minimum 2 engines each), merges/deduplicates URLs (same-site detection via **eTLD+1**) and prioritizes cross-source hits; the settings UI offers **Fast / Balanced / Deep** presets or your own cap and target numbers; the whole run shares one **30-second budget** and returns whatever it already has when time is up; the final unique-result ceiling is configurable in Settings (`multiMaxResults`, default 20, max 100, while a per-call `maxResults` can only ask for fewer). This costs more quota; a failed multi run automatically falls back to the single-engine chain.
722
+ - **Multi mode** — pick `Multi Search` as the engine: web_search queries **every enabled engine of the query's language pool** concurrently (no longer top 3; zh/en pools editable in the settings UI, minimum 2 engines each), merges/deduplicates URLs (same-site detection via **eTLD+1**) and prioritizes cross-source hits; the settings UI offers **Fast / Balanced / Deep** presets or your own cap and target numbers; the whole run shares one **30-second budget** and returns whatever it already has when time is up; the final unique-result ceiling is configurable in Settings (`multiMaxResults`, default 20, max 100, while a per-call `maxResults` can only ask for fewer). Merged results are de-duplicated with MinHash. This costs more quota; a failed multi run automatically falls back to the single-engine chain.
723
+ - **Intent routing** — when no custom fallback order is set, Auto reorders the current language pool by query domain (finance / academic / code / news / shopping); it only changes the order of engines already selected, never adds engines or changes the fallback set.
719
724
 
720
725
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-performance.png" alt="Performance: cache and Multi presets" width="100%" />
721
726
  <sub>▲ Performance: result cache TTL and the Fast / Balanced / Deep Multi presets</sub>
@@ -741,7 +746,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
741
746
  - **Platform Search (`platform_search`)** — Search GitHub / V2EX / Bilibili / Reddit / Hacker News / Stack Overflow / Wikipedia / npm / YouTube / Vimeo / Juejin / Douban / Qiita (public APIs or keyless scraping, zero extra dependencies); X (Twitter) goes through the local Grok Build CLI (SuperGrok / X Premium sign-in).
742
747
  - **Vertical Lookups (`domain_search`)** — Direct lookup in 41 keyless vertical sources: packages/versions (PyPI, crates, GitHub releases, endoflife…), academia (arXiv, Crossref, OpenAlex, Semantic Scholar, PubMed, dblp, Zenodo…), security (NVD, OSV, CISA KEV), finance (SEC EDGAR, IMF, World Bank, CFETS, Yahoo Finance, CoinGecko…), law (US Federal Register, US CourtListener, openlegaldata, UK legislation), news (Google News, GDELT) and more.
743
748
  - **Video Search (`video_search`)** — Find videos across the web via Bing Videos + DuckDuckGo Videos (keyless, mutual fallback), returning video links with titles and publisher/duration metadata.
744
- - **One-Call Research (`research`)** — Concurrent multi-engine search → candidate rerank → tiered body fetch → window selection → an evidence pack with provenance as Markdown; every model component (rerank / embedding / decision model) is optional and silently falls back to the rule path when missing or failing.
749
+ - **One-Call Research (`research`)** — Concurrent multi-engine search → candidate rerank → tiered body fetch → window selection → an evidence pack with provenance as Markdown; every model component (rerank / embedding / decision model) is optional and silently falls back to the rule path when missing or failing; the output carries an evidence quality gate (high / medium / low with a conclusion cap) and says so when the evidence is too thin.
745
750
  - **Search Fetched Bodies (`cache_search`)** — Full-text search over the bodies `research` already fetched (`node:sqlite` persistent cache, 7-day retention; degrades to a no-op whenever `node:sqlite` is unavailable — unflagged from 22.13, while 22.5–22.12 needs `--experimental-sqlite`).
746
751
  - **Clean Integration** — Implements the official `WebSearchProvider` seam interface, coexisting seamlessly with official plugins.
747
752
  - **Time Filtering** — The `advanced_search` tool supports `timeRange`: fixed tiers, custom relative values, or an absolute date (details below).
@@ -1244,7 +1249,7 @@ Restart `dsh web` after switching to apply changes.
1244
1249
 
1245
1250
  #### Offline self-check assertions (`tools/`)
1246
1251
 
1247
- **Fifty-one** zero-dependency assertion scripts ship with the repo (**805 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1252
+ **Fifty-five** zero-dependency assertion scripts ship with the repo (**827 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1248
1253
 
1249
1254
  | Script | Covers | Run (count) |
1250
1255
  |---|---|---|
@@ -1257,6 +1262,9 @@ Restart `dsh web` after switching to apply changes.
1257
1262
  | `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) |
1258
1263
  | `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 36 engines with the right free/explicit flags, and index never reads an engine-private name | `node tools/assert-engine-modules.mjs` (6) |
1259
1264
  | `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) |
1265
+ | `assert-quality.mjs` | Research evidence gate: 8 sources / 3 domains / 3 bodies / 2 dates is high, 3 / 2 / 1 is medium, a single source or a degraded note is low, an empty package is low, and research wires the gate into schema, output and brief | `node tools/assert-quality.mjs` (6) |
1266
+ | `assert-dedupe.mjs` | Near-duplicate removal: identical text shares a MinHash signature, exact URLs and cross-site copies are dropped, different articles survive in order, the threshold is configurable, and both the provider and multi paths run it | `node tools/assert-dedupe.mjs` (6) |
1267
+ | `assert-intent-routing.mjs` | Intent routing: the five domains plus general, stable preference reordering, Auto head follows the domain, a custom fallback order is never reordered, time filtering still applies, and the wiring | `node tools/assert-intent-routing.mjs` (6) |
1260
1268
  | `assert-result-ranking.mjs` | merged ranking: **eTLD+1 same-site detection** / domain round-robin / `seenIn` demoted / freshness only under a time filter | `node tools/assert-result-ranking.mjs` (31) |
1261
1269
  | `assert-url-norm.mjs` | URL normalization: strips only audited tracking params, keeps params that may identify different resources | `node tools/assert-url-norm.mjs` (72) |
1262
1270
  | `assert-prompt-contract.mjs` | system-prompt contract: **search ≠ fetch**, untrusted-data boundary, model engines only when explicitly selected | `node tools/assert-prompt-contract.mjs` (9) |
package/lib/client.js CHANGED
@@ -650,7 +650,7 @@ window.__ModuleLoader__.load({
650
650
  "cache_search",
651
651
  "domain_search",
652
652
  ];
653
- const PLUGIN_VERSION = "0.9.40";
653
+ const PLUGIN_VERSION = "0.9.41";
654
654
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
655
655
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
656
656
  const NAV_ITEMS = [
package/lib/dedupe.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Near-duplicate removal for merged search results. Syndicated copies usually
3
+ * differ in URL and a few characters, so exact-URL dedupe misses them; a small
4
+ * MinHash signature over title+snippet catches them without model calls.
5
+ */
6
+
7
+ const SEEDS = Array.from({ length: 16 }, (_, i) => (i + 1) * 0x9e3779b1);
8
+
9
+ function hash32(text, seed) {
10
+ let hash = (2166136261 ^ seed) >>> 0;
11
+ for (let i = 0; i < text.length; i += 1) {
12
+ hash ^= text.charCodeAt(i);
13
+ hash = Math.imul(hash, 16777619);
14
+ }
15
+ return hash >>> 0;
16
+ }
17
+
18
+ function normalize(text) {
19
+ return String(text ?? "")
20
+ .toLowerCase()
21
+ .replace(/https?:\/\/\S+/g, " ")
22
+ .replace(/[\s\p{P}\p{S}]+/gu, "");
23
+ }
24
+
25
+ function shingles(text) {
26
+ const value = normalize(text);
27
+ if (value.length === 0) return [];
28
+ const size = value.length >= 6 ? 3 : Math.max(1, value.length);
29
+ const out = [];
30
+ for (let i = 0; i + size <= value.length; i += 1) out.push(value.slice(i, i + size));
31
+ return [...new Set(out)];
32
+ }
33
+
34
+ export function minHash(text, size = SEEDS.length) {
35
+ const parts = shingles(text);
36
+ if (parts.length === 0) return Array.from({ length: size }, () => 0);
37
+ return SEEDS.slice(0, size).map((seed) => {
38
+ let min = 0xffffffff;
39
+ for (const part of parts) {
40
+ const value = hash32(part, seed);
41
+ if (value < min) min = value;
42
+ }
43
+ return min;
44
+ });
45
+ }
46
+
47
+ export function similarity(a, b) {
48
+ if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
49
+ let same = 0;
50
+ for (let i = 0; i < a.length; i += 1) if (a[i] === b[i]) same += 1;
51
+ return same / a.length;
52
+ }
53
+
54
+ /**
55
+ * Keep the first source of a near-duplicate group. Order is preserved; exact
56
+ * URL duplicates are also removed. Threshold 0.8 works for syndicated copies
57
+ * while leaving different articles with the same topic separate.
58
+ */
59
+ export function dedupeNearDuplicates(sources, { threshold = 0.8, textOf = (source) => `${source?.title ?? ""} ${source?.snippet ?? ""}` } = {}) {
60
+ const list = Array.isArray(sources) ? sources : [];
61
+ const kept = [];
62
+ const signatures = [];
63
+ const exactUrls = new Set();
64
+ for (const source of list) {
65
+ const url = String(source?.url ?? "");
66
+ if (url && exactUrls.has(url)) continue;
67
+ const signature = minHash(textOf(source));
68
+ if (signatures.some((existing) => similarity(existing, signature) >= threshold)) continue;
69
+ if (url) exactUrls.add(url);
70
+ kept.push(source);
71
+ signatures.push(signature);
72
+ }
73
+ return kept;
74
+ }
package/lib/doctor.js CHANGED
@@ -24,6 +24,8 @@ export function buildDoctorReport({
24
24
  dshHome = "",
25
25
  provider = "",
26
26
  effectiveProvider = "",
27
+ searchProvider = "",
28
+ fetchProvider = "",
27
29
  promptLanguage = "en",
28
30
  promptChars = 0,
29
31
  promptInjected = true,
@@ -38,6 +40,19 @@ export function buildDoctorReport({
38
40
  lines.push(
39
41
  `preferred: ${provider || "auto"}${provider ? "" : ` (resolves to ${effectiveProvider || "?"})`} · prompt ${promptLanguage}, ${promptChars} chars${promptInjected ? "" : ", not injected"}`
40
42
  );
43
+ lines.push(`providers: search=${searchProvider || "auto"} · fetch=${fetchProvider || "auto"}`);
44
+ const warnings = [];
45
+ if (searchProvider && searchProvider !== "ddg" && searchProvider !== "deepseek-official") {
46
+ warnings.push(`search is served by "${searchProvider}", not this plugin; search providers are mutually exclusive (the last takeover wins)`);
47
+ }
48
+ if (fetchProvider && fetchProvider !== "fs-quality-fetch" && fetchProvider !== "http") {
49
+ warnings.push(`fetch is served by "${fetchProvider}", not this plugin; fetch providers are mutually exclusive`);
50
+ }
51
+ if (warnings.length > 0) {
52
+ lines.push("");
53
+ lines.push("warnings:");
54
+ for (const warning of warnings) lines.push(` - ${warning}`);
55
+ }
41
56
  const enabledTools = toolsKnown.filter((id) => !tools.disabled.includes(id));
42
57
  lines.push(`tools: ${enabledTools.length}/${toolsKnown.length} on${enabledTools.length ? ` (${enabledTools.join(", ")})` : ""}`);
43
58
  lines.push("");
package/lib/index.js CHANGED
@@ -41,6 +41,8 @@ import { searchSerply } from "./engines/serply.js";
41
41
  import { searchOutcrawl } from "./engines/outcrawl.js";
42
42
  import { searchGoogle } from "./engines/google.js";
43
43
  import { createEngineRuntime, ENGINE_CONCURRENCY_LIMIT, SERP_CONCURRENCY_LIMIT } from "./engine_runtime.js";
44
+ import { classifyIntent, preferForIntent } from "./intent.js";
45
+ import { dedupeNearDuplicates } from "./dedupe.js";
44
46
  import { searchYoucom, resolveYoucomApiKey } from "./engines/you.js";
45
47
  import { searchTinyfish } from "./engines/tinyfish.js";
46
48
  import { searchJina } from "./engines/jina.js";
@@ -409,14 +411,15 @@ function routeEngines(query, { timeRange, disabledEngines = [], fallbackOrder =
409
411
  ? enabled.filter((engine) => routeHead.includes(engine))
410
412
  : routeHead.filter((engine) => enabledSet.has(engine));
411
413
 
414
+ const routerHead = hasCustomOrder ? head : preferForIntent(head, classifyIntent(query));
412
415
  let ordered;
413
416
  if (timeRange) {
414
- const timeHead = head.filter((engine) => TIME_ENGINES.includes(engine));
415
- const timeOthers = enabled.filter((engine) => TIME_ENGINES.includes(engine) && !head.includes(engine));
416
- const nonTimeHead = head.filter((engine) => !TIME_ENGINES.includes(engine));
417
+ const timeHead = routerHead.filter((engine) => TIME_ENGINES.includes(engine));
418
+ const timeOthers = enabled.filter((engine) => TIME_ENGINES.includes(engine) && !routerHead.includes(engine));
419
+ const nonTimeHead = routerHead.filter((engine) => !TIME_ENGINES.includes(engine));
417
420
  ordered = [...timeHead, ...timeOthers, ...nonTimeHead];
418
421
  } else {
419
- ordered = [...head];
422
+ ordered = [...routerHead];
420
423
  }
421
424
 
422
425
  // 白名单是显式意图:被它单独允许的按次计费引擎也可以进入 auto 的兜底位置。
@@ -2141,12 +2144,21 @@ function apply(ctx, config) {
2141
2144
  });
2142
2145
  }
2143
2146
  const injected = composeInjectedPrompt(cfg);
2147
+ const webProvider = (key) => {
2148
+ try {
2149
+ return String(providerSelection(ctx.web, key).current ?? "");
2150
+ } catch {
2151
+ return "";
2152
+ }
2153
+ };
2144
2154
  return buildDoctorReport({
2145
2155
  version: PACKAGE_VERSION,
2146
2156
  nodeVersion: process.versions.node,
2147
2157
  dshHome: dshHomeDir(),
2148
2158
  provider: cfg.provider,
2149
2159
  effectiveProvider: cfg.provider || autoDefaultProvider,
2160
+ searchProvider: webProvider("searchProvider"),
2161
+ fetchProvider: webProvider("fetchProvider"),
2150
2162
  promptLanguage: promptLanguageOf({ promptLanguage: cfg.promptLanguage }),
2151
2163
  promptChars: injected.length,
2152
2164
  promptInjected: Boolean(injected),
@@ -2472,7 +2484,9 @@ function apply(ctx, config) {
2472
2484
  // 轮换时机:首次失败后 keyRings 已经填充,此时再判断有几把 key。
2473
2485
  for (let attempt = 0; attempt < 10; attempt++) {
2474
2486
  try {
2475
- return sanitizeSearchResult(await provider.searchOnce(request, signal));
2487
+ const safe = sanitizeSearchResult(await provider.searchOnce(request, signal));
2488
+ if (Array.isArray(safe.sources)) safe.sources = dedupeNearDuplicates(safe.sources);
2489
+ return safe;
2476
2490
  } catch (error) {
2477
2491
  const keys = maxKeyRingLength();
2478
2492
  if (keys <= 1 || attempt >= keys - 1 || !isKeyRotationCandidate(error)) throw error;
@@ -3419,7 +3433,7 @@ function apply(ctx, config) {
3419
3433
  provider: "multi_search",
3420
3434
  // #108: the multi tool bypasses provider.search, so sanitize here as well
3421
3435
  content: stripLoneSurrogates(`Note: ${notes.join("; ")}`),
3422
- sources: sanitizeSources(finalSources),
3436
+ sources: dedupeNearDuplicates(sanitizeSources(finalSources)),
3423
3437
  truncated: false,
3424
3438
  };
3425
3439
  };
@@ -3925,8 +3939,6 @@ function apply(ctx, config) {
3925
3939
  },
3926
3940
  maxResults: {
3927
3941
  type: "number",
3928
- minimum: 1,
3929
- maximum: MULTI_RESULTS_MAX,
3930
3942
  description: toolParam(lang, "multi_search", "maxResults", {
3931
3943
  limit: normalizeMultiMaxResults(current().multiMaxResults),
3932
3944
  }),
package/lib/intent.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Lightweight, deterministic query intent routing. It does not replace the
3
+ * language pools or Auto; it only reorders the engines already selected for
4
+ * the query so the head matches the domain (finance, academic, code, news,
5
+ * shopping). Unknown/general queries keep the existing order.
6
+ */
7
+
8
+ const RULES = [
9
+ {
10
+ domain: "finance",
11
+ pattern:
12
+ /股票|基金|财报|利率|汇率|贷款|债券|通胀|通胀率|市值|IPO|加密货币|比特币|stock|equity|fund|earnings|inflation|interest rate|forex|lpr|crypto|bitcoin|nasdaq|nyse/i,
13
+ },
14
+ {
15
+ domain: "academic",
16
+ pattern:
17
+ /论文|文献|学术|引用|期刊|会议|研究综述|arxiv|doi|citation|paper|study|pubmed|scholar|journal|conference|preprint/i,
18
+ },
19
+ {
20
+ domain: "code",
21
+ pattern:
22
+ /代码|报错|编译|函数|接口|依赖|仓库|github|gitlab|npm|pypi|python|javascript|typescript|rust|golang|java|docker|kubernetes|stack trace|exception|regex|api error/i,
23
+ },
24
+ {
25
+ domain: "news",
26
+ pattern:
27
+ /新闻|最新|今天|昨天|本周|本月|今年|发布|突发|breaking|today|latest|this week|this month|announced|launch/i,
28
+ },
29
+ {
30
+ domain: "shopping",
31
+ pattern:
32
+ /价格|购买|优惠|折扣|测评|推荐|哪款|性价比|price|buy|discount|deal|review|best|cheap/i,
33
+ },
34
+ ];
35
+
36
+ export const INTENT_PREFERENCES = {
37
+ finance: ["baidu", "bing", "anysearch", "exa", "tavily", "ddg"],
38
+ academic: ["exa", "tavily", "parallel", "bing", "anysearch", "ddg"],
39
+ code: ["bing", "ddg", "exa", "tavily", "degoog", "anysearch"],
40
+ news: ["bing", "baidu", "anysearch", "exa", "ddg"],
41
+ shopping: ["baidu", "bing", "anysearch", "ddg", "exa"],
42
+ };
43
+
44
+ export function classifyIntent(query) {
45
+ const text = String(query ?? "");
46
+ for (const rule of RULES) {
47
+ if (rule.pattern.test(text)) return { domain: rule.domain, matched: true };
48
+ }
49
+ return { domain: "general", matched: false };
50
+ }
51
+
52
+ /** Stable reorder of an existing engine list by the domain preference. */
53
+ export function preferForIntent(engines, intent) {
54
+ const preference = INTENT_PREFERENCES[intent?.domain] ?? [];
55
+ if (preference.length === 0 || engines.length === 0) return [...engines];
56
+ const rank = new Map(preference.map((id, index) => [id, index]));
57
+ return engines
58
+ .map((id, index) => ({ id, index }))
59
+ .sort((a, b) => (rank.get(a.id) ?? 999) - (rank.get(b.id) ?? 999) || a.index - b.index)
60
+ .map((entry) => entry.id);
61
+ }
package/lib/quality.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Evidence quality gate for the research tool. The goal is not to score
3
+ * relevance again; it is to tell the model how much the returned package can
4
+ * support a conclusion, and to cap the wording when the evidence is thin.
5
+ *
6
+ * high: at least 8 sources across 3 domains, 3 fetched documents, 2 dated sources
7
+ * medium: at least 3 sources, 2 domains, 1 fetched document
8
+ * low: anything less, or a failed/partial run recorded in notes
9
+ */
10
+ function hostOf(url) {
11
+ try {
12
+ return new URL(String(url)).hostname.replace(/^www\./i, "").toLowerCase();
13
+ } catch {
14
+ return "";
15
+ }
16
+ }
17
+
18
+ export function assessEvidenceQuality({ sources = [], documents = [], notes = [] } = {}) {
19
+ const list = Array.isArray(sources) ? sources : [];
20
+ const docs = Array.isArray(documents) ? documents : [];
21
+ const noteList = Array.isArray(notes) ? notes : [];
22
+ const domains = new Set(list.map((source) => hostOf(source?.url)).filter(Boolean)).size;
23
+ const dated = list.filter((source) => typeof source?.publishedAt === "string" && source.publishedAt.length > 0).length;
24
+ const fetched = docs.length;
25
+
26
+ const degraded = noteList.some((note) =>
27
+ /search failed|budget_exhausted|budget exhausted|all fetches failed|notEvaluated|deadline_hit/i.test(String(note))
28
+ );
29
+
30
+ let level = "low";
31
+ if (list.length >= 8 && domains >= 3 && fetched >= 3 && dated >= 2) level = "high";
32
+ else if (list.length >= 3 && domains >= 2 && fetched >= 1) level = "medium";
33
+ if (degraded) level = "low";
34
+
35
+ const note =
36
+ level === "high"
37
+ ? "enough independent sources and fetched bodies for a confident answer"
38
+ : level === "medium"
39
+ ? "thin evidence: verify the key claims against the listed sources before concluding"
40
+ : "insufficient evidence: do not state conclusions as fact; fetch more sources or report the gap";
41
+
42
+ return { level, cap: level, sources: list.length, domains, dated, fetched, note };
43
+ }
package/lib/research.js CHANGED
@@ -9,6 +9,7 @@ import { rerank, embed, cosineMatrix, decide, judgeQueryIntent } from "./rerank.
9
9
  import { promptLanguageOf, toolDescription, toolParam, localizedEffect } from "./prompt_i18n.js";
10
10
  import { httpsJson, htmlToText, callExa, callFirecrawl, callCrawl4ai } from "./fetch_upstream.js";
11
11
  import { isDomainBlocked } from "./domain_filter.js";
12
+ import { assessEvidenceQuality } from "./quality.js";
12
13
 
13
14
  // 模型组件的受控替身(测试/评审用;抓取层的替身在 fetch_upstream.js 的 CONTROLLED_STUBS)
14
15
  export const CONTROLLED_STUBS = { rerank: null, embed: null, decide: null, judgeQueryIntent: null };
@@ -838,6 +839,19 @@ export function registerResearchTool(ctx, { provider, resolveApiKey, wrapUntrust
838
839
  sources: { type: "array", items: { type: "object", additionalProperties: false, properties: RESEARCH_SOURCE_FIELDS } },
839
840
  documents: { type: "array", items: { type: "object", additionalProperties: false, properties: DOC_FIELDS } },
840
841
  notes: { type: "array", items: { type: "string" } },
842
+ quality: {
843
+ type: "object",
844
+ additionalProperties: false,
845
+ properties: {
846
+ level: { type: "string" },
847
+ cap: { type: "string" },
848
+ sources: { type: "number" },
849
+ domains: { type: "number" },
850
+ dated: { type: "number" },
851
+ fetched: { type: "number" },
852
+ note: { type: "string" },
853
+ },
854
+ },
841
855
  },
842
856
  },
843
857
  render(_args, value) {
@@ -862,9 +876,15 @@ export function registerResearchTool(ctx, { provider, resolveApiKey, wrapUntrust
862
876
  return `### ${d.title || d.url}${mark}\n[${d.url}]\n_${meta}_\n\n${d.content}`;
863
877
  });
864
878
  const notes = value.notes.length ? `\n## Notes\n${value.notes.map((n) => `- ${n}`).join("\n")}` : "";
879
+ const q = value.quality;
880
+ const quality = q
881
+ ? `_evidence: ${q.level} · ${q.sources} sources · ${q.domains} domains · ${q.dated} dated · ${q.fetched} fetched — ${q.note}_\n`
882
+ : "";
865
883
  const brief =
866
884
  `# Research: ${value.question}\n` +
867
- `_engines: ${value.engines} · sources: ${value.sources.length} · documents: ${value.documents.length} · ~${value.estimatedTokens} tokens_\n\n` +
885
+ `_engines: ${value.engines} · sources: ${value.sources.length} · documents: ${value.documents.length} · ~${value.estimatedTokens} tokens_\n` +
886
+ quality +
887
+ `\n` +
868
888
  `## Sources\n${src.join("\n") || "No results found."}\n\n` +
869
889
  `## Documents\n${docs.join("\n\n") || "(no documents fetched — snippets above are all we have)"}` +
870
890
  notes;
@@ -1344,6 +1364,7 @@ export function registerResearchTool(ctx, { provider, resolveApiKey, wrapUntrust
1344
1364
  out.estimatedTokens = estimateTokens(
1345
1365
  out.sources.map((s) => s.title + s.snippet).join("") + out.documents.map((d) => d.content).join("")
1346
1366
  );
1367
+ out.quality = assessEvidenceQuality(out);
1347
1368
  return out;
1348
1369
  } finally {
1349
1370
  clearTimeout(deadlineTimer);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.40",
3
+ "version": "0.9.41",
4
4
  "description": "Free web search for DeepSeek Harness: 27 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao 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.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",