@fffangchenghao/dsh-web-search 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.1
4
+
5
+ ### Changed
6
+ - **The core-word retry now runs only when the first answer is unusable.**
7
+ `transport` checks the original rows against the relevance gate before
8
+ spending a second request. Queries whose `cn.bing` answer already has a
9
+ relevant row (`pip 安装 requests 库`, `React useEffect 用法`,
10
+ `PostgreSQL 逻辑复制 配置`) keep their original latency; the dictionary-page
11
+ failures (`东数西算 八个国家枢纽节点 定位`, `如何配置 postgres 逻辑复制`) still
12
+ retry and recover. Live comparison for the three working queries: rows and
13
+ expected-domain hits unchanged, p50 latency back to the pre-variant value
14
+ (React 2.8 s → 0.6 s in the sample).
15
+ - **Regression evidence for 0.19.0/0.19.1.** Replaying the 20-query corpus
16
+ against the 0.15.0 result shows delta 0 on P@8, R@8, MRR@8, zero-hit and every
17
+ category/language slice; the five-query long corpus is unchanged at
18
+ `0.4500 / 1.0000 / 0.7667`. Only 3 of the 20 baseline queries trigger a
19
+ variant at all (`zh-postgres-logical`, `zh-pip-requests`,
20
+ `zh-react-useeffect`), and after the guard none of them does.
21
+
22
+ ## 0.19.0
23
+
24
+ ### Added
25
+ - **Core-word retry for whole-phrase engines.** `cn.bing` and 360 Search match a
26
+ long Chinese query as one phrase and fall back to dictionary pages for its
27
+ first character when the phrase is unknown. `src/variants.ts` derives at most
28
+ one alternate query — the technical segments of a mixed query
29
+ (`如何配置 postgres 逻辑复制` → `postgres 逻辑复制`), or the first content
30
+ segment of a pure CJK query (`东数西算 八个国家枢纽节点 定位` → `东数西算`) —
31
+ and the transport asks it once, merging the rows after the original list.
32
+ Measured on the policy query, `cn.bing` went from zero usable rows to the NDRC
33
+ article, the gov.cn implementation opinion, and the ncsti overview; the fused
34
+ list is now eight relevant rows.
35
+ - **A five-query long-Chinese diagnostic corpus.** `bench/queries-long.json`
36
+ covers a policy question, a mixed PostgreSQL question, and Python / Kubernetes
37
+ / React release-doc questions; fixtures live in `bench/fixtures-long/`.
38
+ `scripts/bench.mjs` grew `--queries` and `--fixtures` to record and evaluate it
39
+ without touching the 20-query baseline. Result: P@8 `0.4500`, R@8 `1.0000`,
40
+ MRR@8 `0.7667`, zero hits 0.
41
+
42
+ ### Changed
43
+ - Two extra test files (`variants`, `variant-fetch`) and 5 tests; 498 cases
44
+ total (497 pass, one environment skip).
45
+
3
46
  ## 0.18.0
4
47
 
5
48
  ### Fixed
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  <p align="center">
11
11
  <a href="https://www.npmjs.com/package/@fffangchenghao/dsh-web-search"><img src="https://img.shields.io/npm/v/@fffangchenghao/dsh-web-search.svg" alt="npm version"></a>
12
- <img src="https://img.shields.io/badge/tests-492%20passing-brightgreen" alt="tests">
12
+ <img src="https://img.shields.io/badge/tests-498%20passing-brightgreen" alt="tests">
13
13
  <img src="https://img.shields.io/badge/engines-8%2C%20zero%20API%20key-brightgreen" alt="engines">
14
14
  <img src="https://img.shields.io/badge/node-%3E%3D22.18-blue" alt="node">
15
15
  <img src="https://img.shields.io/badge/dsh-%3E%3D0.2.1--rc.2%20%3C0.3.0-blueviolet" alt="dsh">
@@ -21,7 +21,7 @@
21
21
  - **No API key, eight engines.** AnySearch, CN Bing, DuckDuckGo HTML, www Bing, DuckDuckGo Lite and 360 Search are scraped directly; Exa joins the primary tier through its keyless MCP endpoint, and Firecrawl's search API is the measured fallback. The plugin works out of the box.
22
22
  - **The ranking is measured, not asserted.** Cross-engine reciprocal-rank fusion with authority and freshness boosts, a 20-query offline benchmark, and an 81-configuration parameter sweep — the only search plugin here that publishes both its metric and its confidence intervals. See [How the ranking works](docs/rrf-ranking.md).
23
23
  - **Fetching admits failure.** Binary documents and empty 200 responses are rejected by name (`SEARCH_UNSUPPORTED`, `SEARCH_EMPTY`) instead of being returned as noise; the direct → tunnel → render → extract ladder shares one 25 s budget and stops when there is no time left. The budget is per request — there is a regression test for exactly that.
24
- - **493 tests across 32 files**, a committed `lib/`, declared `engines.dsh` / `engines.node`, and a [SECURITY.md](SECURITY.md) that lists every process, host and file the plugin touches.
24
+ - **499 tests across 34 files**, a committed `lib/`, declared `engines.dsh` / `engines.node`, and a [SECURITY.md](SECURITY.md) that lists every process, host and file the plugin touches.
25
25
  - **Bilingual documentation.** This README and [中文说明](README.zh-CN.md) are maintained side by side.
26
26
 
27
27
  ![Ranking baseline and parameter sweep](https://raw.githubusercontent.com/fangchenghao/dsh-web-search/main/docs/images/bench.png)
@@ -37,7 +37,7 @@ The web-search corner of the DSH plugin ecosystem is crowded, and most rivals ar
37
37
  | Key-free engines | 8 | ~30 | 7 channels (+X) | 1 official API |
38
38
  | Dedicated vertical sources | 34 (8 on by default) | 41 | — | — |
39
39
  | Model-facing tools | 6 | ~10 | 3 | 5 |
40
- | Test suite | 32 files / 493 cases | none | 29 files | 6 files |
40
+ | Test suite | 34 files / 499 cases | none | 29 files | 6 files |
41
41
  | Ranking benchmark | 20 queries + 81-config sweep | — | — | — |
42
42
  | Store status | source contract satisfied, awaiting review | unlisted | no entry | blocked (review-required) |
43
43
 
@@ -242,7 +242,7 @@ Each line is the plain version first, the technical note second. The technical n
242
242
 
243
243
  5. **Chinese and English are handled separately, and Chinese rows must talk about the question.**
244
244
  English queries lead with global sources, Chinese queries with Chinese sources, so "how to …" is not answered with a dictionary page for the word `how`. A scraped Chinese engine can still fall back to single-character dictionary and company pages for a long query; those rows are dropped before fusion unless they share at least two words with the question, and `.gov.cn` / `.edu.cn` official pages get the authority boost.
245
- *Technical: `lead = cn` when the query contains CJK characters, `lead = global` for plain ASCII; the other region only appends when the leading one comes up short. `src/relevance.ts` splits a CJK query into character bigrams (an ASCII word counts double), requires two weight units of overlap with title, snippet or URL, and returns English queries untouched. Measured on `东数西算 八个国家枢纽节点 定位`, `cn.bing` answered with ten dictionary/company rows; the gate now reports `cn.bing: no relevant results` and the fused list keeps the NDRC/百科/news rows.*
245
+ *Technical: `lead = cn` when the query contains CJK characters, `lead = global` for plain ASCII; the other region only appends when the leading one comes up short. `src/relevance.ts` splits a CJK query into character bigrams (an ASCII word counts double), requires two weight units of overlap with title, snippet or URL, and returns English queries untouched. A whole-phrase engine that misses a long query is asked once more with its core words (`src/variants.ts`) — but only when its first answer contains no row that survives the relevance gate, so a working short query pays neither the request nor the latency: `东数西算 八个国家枢纽节点 定位` also asks `东数西算`, `如何配置 postgres 逻辑复制` also asks `postgres 逻辑复制`. Measured on the first query, `cn.bing` answered with ten dictionary/company rows before this; it now contributes the NDRC and gov.cn articles, and the fused list has eight relevant rows.*
246
246
 
247
247
  6. **You choose speed or completeness.**
248
248
  `auto` waits up to 6 s for English and 3.5 s for Chinese; `fast` takes whoever answers first; `all` waits for everyone, up to 10 s.
@@ -306,7 +306,7 @@ Each line is the plain version first, the technical note second. The technical n
306
306
 
307
307
  21. **Search quality has a repeatable benchmark.**
308
308
  Ranking changes are no longer judged by feel: a fixed set of 20 queries produces the same scores every time.
309
- *Technical: `bench/` holds 20 queries (10 Chinese, 10 English), five in each of docs / release / package / news, each annotated with 1–3 expected domains. `node scripts/bench.mjs` replays recorded fixtures offline, never touches the network, and prints precision@8, recall@8, MRR@8 plus each engine's contribution; `--record` re-records live (1.5 s between queries) to refresh the fixtures; `--json` gives machine-readable output for version comparisons, and past results live in `bench/results/`. Baseline for 0.15.0 (tier-aware replay, so the recorded fallback engines only count when production would run them): P@8 `0.4375`, R@8 `0.7917`, MRR@8 `0.8071`; Chinese `0.4000 / 0.8167 / 0.7976`, English `0.4750 / 0.7667 / 0.8167`. The controlled experiments and known gaps are in the appendix.*
309
+ *Technical: `bench/` holds 20 queries (10 Chinese, 10 English), five in each of docs / release / package / news, each annotated with 1–3 expected domains. `node scripts/bench.mjs` replays recorded fixtures offline, never touches the network, and prints precision@8, recall@8, MRR@8 plus each engine's contribution; `--record` re-records live (1.5 s between queries) to refresh the fixtures; `--json` gives machine-readable output for version comparisons, and past results live in `bench/results/`. Baseline for 0.15.0 (tier-aware replay, so the recorded fallback engines only count when production would run them): P@8 `0.4375`, R@8 `0.7917`, MRR@8 `0.8071`; Chinese `0.4000 / 0.8167 / 0.7976`, English `0.4750 / 0.7667 / 0.8167`. A separate five-query long-Chinese diagnostic (`bench/queries-long.json`, recorded with `--queries ... --fixtures ...`) scores `0.4500 / 1.0000 / 0.7667`, with every query hitting an expected domain; it is kept separate so the 20-query baseline stays comparable. The controlled experiments and known gaps are in the appendix.*
310
310
 
311
311
  22. **Research, in one call.**
312
312
  For "what do the official docs and two other sources actually say about X", `research` runs up to three searches, opens the leading pages through the same fetch ladder, and returns one evidence pack in which every excerpt sits under its URL. A page that will not load is reported by URL and reason instead of aborting the pack.
package/README.zh-CN.md CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  <p align="center">
11
11
  <a href="https://www.npmjs.com/package/@fffangchenghao/dsh-web-search"><img src="https://img.shields.io/npm/v/@fffangchenghao/dsh-web-search.svg" alt="npm 版本"></a>
12
- <img src="https://img.shields.io/badge/tests-492%20passing-brightgreen" alt="测试">
12
+ <img src="https://img.shields.io/badge/tests-498%20passing-brightgreen" alt="测试">
13
13
  <img src="https://img.shields.io/badge/engines-8%2C%20zero%20API%20key-brightgreen" alt="引擎">
14
14
  <img src="https://img.shields.io/badge/node-%3E%3D22.18-blue" alt="node">
15
15
  <img src="https://img.shields.io/badge/dsh-%3E%3D0.2.1--rc.2%20%3C0.3.0-blueviolet" alt="dsh">
@@ -21,7 +21,7 @@
21
21
  - **不要 API key,八个引擎。** AnySearch、必应中国、DuckDuckGo HTML、必应国际、DuckDuckGo Lite、360 搜索直接抓取;Exa 走它的免密钥 MCP 通道加入主引擎,Firecrawl 的搜索 API 作为实测后的兜底。装好就能用。
22
22
  - **排序是量出来的,不是写出来的。** 跨引擎 RRF 融合,叠加权威度与时效加权;20 条离线基准 + 81 组参数扫描,是这类插件里唯一同时公开指标和置信区间的。方法见 [排序是怎么做的](docs/rrf-ranking.md)。
23
23
  - **抓取会承认失败。** 二进制文档和「200 但正文为空」会被明确拒绝(`SEARCH_UNSUPPORTED`、`SEARCH_EMPTY`),而不是当噪音返回;direct → tunnel → render → extract 四级阶梯共享 25 秒预算,预算不足就不再起新的一级。预算是「每次请求」而不是「插件启动时」,这点有回归测试守着。
24
- - **32 个测试文件、493 个用例**,`lib/` 产物入库,声明了 `engines.dsh` / `engines.node`,[SECURITY.md](SECURITY.md) 逐项列出插件会碰的进程、主机和文件。
24
+ - **34 个测试文件、499 个用例**,`lib/` 产物入库,声明了 `engines.dsh` / `engines.node`,[SECURITY.md](SECURITY.md) 逐项列出插件会碰的进程、主机和文件。
25
25
  - **双语文档。** 本文件和 [English README](README.md) 同步维护。
26
26
 
27
27
  ![排序基线参数扫描](https://raw.githubusercontent.com/fangchenghao/dsh-web-search/main/docs/images/bench.png)
@@ -37,7 +37,7 @@ DSH 插件生态里的「联网搜索」这一块已经很挤,大多数竞品
37
37
  | 免 key 引擎 | 8 | ~30 | 7 条通道(含 X) | 1 个官方 API |
38
38
  | 专门数据源 | 34(默认开 8 个)| 41 | — | — |
39
39
  | 面向模型的工具 | 6 | ~10 | 3 | 5 |
40
- | 测试 | 32 文件 / 493 用例 | 无 | 29 文件 | 6 文件 |
40
+ | 测试 | 34 文件 / 499 用例 | 无 | 29 文件 | 6 文件 |
41
41
  | 排序基准 | 20 查询 + 81 组扫描 | — | — | — |
42
42
  | 商店状态 | 源码契约已满足,待复核 | unlisted | 无条目 | blocked(review-required) |
43
43
 
@@ -242,7 +242,7 @@ Harness 里有个叫 `web` 的**服务**,它自己不会搜索,只负责「
242
242
 
243
243
  5. **中英文分开处理,而且中文结果必须真的在讲这个问题。**
244
244
  英文问题先看国外来源,中文问题先看中文来源,避免「how to …」被某个中文引擎按单词 `how` 匹配成词典页。中文长查询仍可能被引擎退化成单字词典页、公司页;这些行在融合前会被丢掉,除非标题/摘要/URL 与问题至少重合两个词;`.gov.cn` / `.edu.cn` 官方页面另有权威度加权。
245
- *技术补充:查询含 CJK 字符时 `lead = cn`,纯 ASCII 时 `lead = global`;非主导区只在主导区凑不够条数时才追加。`src/relevance.ts` 把中文查询切成二字 bigram(ASCII 单词权重翻倍),要求与标题、摘要或 URL 至少两个权重单位的重合;英文查询原样放行。用「东数西算 八个国家枢纽节点 定位」实测:`cn.bing` 返回十条词典/公司页,现在会报 `cn.bing: no relevant results`,融合结果保留发改委/百科/新闻页。*
245
+ *技术补充:查询含 CJK 字符时 `lead = cn`,纯 ASCII 时 `lead = global`;非主导区只在主导区凑不够条数时才追加。`src/relevance.ts` 把中文查询切成二字 bigram(ASCII 单词权重翻倍),要求与标题、摘要或 URL 至少两个权重单位的重合;英文查询原样放行。对整串匹配型引擎还会用核心词补问一次(`src/variants.ts`),但只在原答案没有任何一条能通过相关性门槛时才补问——短查询正常工作时不付这次请求和延迟:「东数西算 八个国家枢纽节点 定位」会补问「东数西算」,「如何配置 postgres 逻辑复制」会补问「postgres 逻辑复制」。实测第一条查询:`cn.bing` 原来返回十条词典/公司页,现在能贡献发改委和 gov.cn 文章,融合结果八条全部相关。*
246
246
 
247
247
  6. **快慢可以选。**
248
248
  默认 `auto`:英文最多等 6 秒、中文最多等 3.5 秒;`fast` 谁先回就用谁;`all` 等所有引擎,最多 10 秒。
@@ -306,7 +306,7 @@ Harness 里有个叫 `web` 的**服务**,它自己不会搜索,只负责「
306
306
 
307
307
  21. **搜索质量有了可重复的基准。**
308
308
  改排序不再靠感觉:仓库里有一组固定的 20 条查询,每次改完都能跑出同一套分数。
309
- *技术补充:`bench/` 下 20 条查询(中文 10、英文 10),四类各 5 条(文档 / 版本发布 / 包与库 / 新闻),每条标注 1–3 个期望域名。`node scripts/bench.mjs` 离线读夹具重放,不联网,输出 precision@8、recall@8、MRR@8 与每个引擎的贡献;`--record` 联网重新录制(每条限速 1.5 秒),用于更新夹具;`--json` 输出机器可读结果,便于版本间对比,历史结果存在 `bench/results/`。当前基线(0.15.0,按 tier 回放):P@8 `0.4375`、R@8 `0.7917`、MRR@8 `0.8071`;中文 `0.4000 / 0.8167 / 0.7976`,英文 `0.4750 / 0.7667 / 0.8167`。对照实验和已知短板见附录。*
309
+ *技术补充:`bench/` 下 20 条查询(中文 10、英文 10),四类各 5 条(文档 / 版本发布 / 包与库 / 新闻),每条标注 1–3 个期望域名。`node scripts/bench.mjs` 离线读夹具重放,不联网,输出 precision@8、recall@8、MRR@8 与每个引擎的贡献;`--record` 联网重新录制(每条限速 1.5 秒),用于更新夹具;`--json` 输出机器可读结果,便于版本间对比,历史结果存在 `bench/results/`。当前基线(0.15.0,按 tier 回放):P@8 `0.4375`、R@8 `0.7917`、MRR@8 `0.8071`;中文 `0.4000 / 0.8167 / 0.7976`,英文 `0.4750 / 0.7667 / 0.8167`。另有五条中文长查询的独立诊断集(`bench/queries-long.json`,用 `--queries ... --fixtures ...` 录制):`0.4500 / 1.0000 / 0.7667`,五条都命中期望域名;它与 20 条基线分开保存,避免改变基线的可比性。对照实验和已知短板见附录。*
310
310
 
311
311
  22. **一次调用完成小调研。**
312
312
  问「官方文档和另外两个来源到底怎么说」时,`research` 先跑最多三条查询,再用与 `web_fetch` 相同的抓取阶梯打开靠前的页面,最后返回一份证据包:每段摘录下面就是它的 URL。打不开的页面按 URL 和原因列出,不会让整份证据包失败。
package/client.js CHANGED
@@ -47,7 +47,7 @@
47
47
  var ENTRY = 'web-search-bing';
48
48
  var PACKAGE_NAME = 'dsh-web-search-bing';
49
49
  /** Keep in step with package.json; compared with the npm registry. */
50
- var VERSION = '0.18.0';
50
+ var VERSION = '0.19.1';
51
51
  /** Snapshot used while no configuration service is reachable. */
52
52
  var EMPTY_STATE = { status: 'unavailable', value: undefined, base: undefined, user: undefined, revision: undefined, writable: false };
53
53
 
@@ -149,6 +149,35 @@ reported as `no relevant results` and the fallback tier can run) and the ranker
149
149
  (so offline replay applies the same rule). On the 20-query bench it changes no
150
150
  metric: the recorded fixtures do not contain that failure mode.
151
151
 
152
+
153
+ ## Long-query diagnostic
154
+
155
+ The 20-query corpus has two- or three-token queries and does not exercise the
156
+ whole-phrase failure mode. `bench/queries-long.json` adds five long Chinese
157
+ queries (policy, PostgreSQL, Python, Kubernetes, React) and is recorded into
158
+ `bench/fixtures-long/` separately:
159
+
160
+ ```
161
+ node scripts/bench.mjs --record --queries bench/queries-long.json --fixtures bench/fixtures-long
162
+ node scripts/bench.mjs --queries bench/queries-long.json --fixtures bench/fixtures-long
163
+ ```
164
+
165
+ Result on 0.19.0: P@8 `0.4500`, R@8 `1.0000`, MRR@8 `0.7667`, zero-hit 0, every
166
+ query hitting at least one expected domain. `cn.bing` contributes 25 of the 40
167
+ fused rows after the variant retry, against zero usable rows before it for the
168
+ policy query. The corpus is deliberately separate so the 20-query baseline in
169
+ `bench/queries.json` stays comparable.
170
+
171
+ ## Retry cost guard
172
+
173
+ The core-word retry is not free: it is one more request to the same engine.
174
+ `src/transport.ts` therefore checks the first answer with the same relevance
175
+ gate before retrying. Only an answer with zero surviving rows triggers the
176
+ variant; `pip 安装 requests 库` and `React useEffect 用法` keep their original
177
+ latency (measured live: 2.7 s → 3.5 s and 1.5 s → 2.8 s without the guard,
178
+ 1.5 s and 0.6 s with it), while the dictionary-page failures still retry and
179
+ recover. The 20-query replay compare is delta 0 on P@8, R@8 and MRR@8.
180
+
152
181
  ## Known limits
153
182
 
154
183
  - **Relative Chinese time words.** A query like "上周发布的那版" carries its time
package/lib/engines.js CHANGED
@@ -4,6 +4,7 @@ import { resolveProxy } from "./proxy.js";
4
4
  import { parseAnySearch, parseBing, parseDdgHtml, parseDdgLite, parseExaMcp, parseFirecrawl, parseSo } from "./parsers.js";
5
5
  import { mergeRegions } from "./rank.js";
6
6
  import { filterRelevant } from "./relevance.js";
7
+ import { cjkQueryVariants } from "./variants.js";
7
8
  import { cacheKey } from "./cache.js";
8
9
  import { searchHost } from "./transport.js";
9
10
  import { keyFailureKind, keyPoolFor } from "./keys.js";
@@ -112,6 +113,7 @@ export const HOSTS = [
112
113
  // No `filters` parameter: see the measurement note before `HOSTS`.
113
114
  build: (query) => `https://cn.bing.com/search?q=${encodeURIComponent(query)}`,
114
115
  parse: parseBing,
116
+ variants: cjkQueryVariants,
115
117
  },
116
118
  {
117
119
  id: 'so',
@@ -121,6 +123,7 @@ export const HOSTS = [
121
123
  region: 'cn',
122
124
  build: (query) => `https://www.so.com/s?q=${encodeURIComponent(query)}`,
123
125
  parse: parseSo,
126
+ variants: cjkQueryVariants,
124
127
  },
125
128
  {
126
129
  id: 'ddg-lite',
@@ -18,21 +18,4 @@ export type AttemptOutcome = {
18
18
  ok: false;
19
19
  error: SearchError;
20
20
  };
21
- /**
22
- * Ask one engine, going direct first unless it is marked `viaProxy`.
23
- *
24
- * A domestic engine goes direct first, because that is both faster and the path
25
- * its site expects; only if that fails is it retried through the tunnel, so a
26
- * network that blocks it directly still works. An engine marked `viaProxy` is
27
- * tunnelled from the start.
28
- *
29
- * @param host - the engine.
30
- * @param query - the user query.
31
- * @param signal - cancellation.
32
- * @param timeoutMs - per-attempt deadline.
33
- * @param proxy - tunnel URL, or `undefined` when none is available.
34
- * @param timeRange - active publication window, forwarded to engines that can
35
- * push it into their query (currently DuckDuckGo's `df`).
36
- * @returns the outcome of the route that got furthest; cancellation is rethrown.
37
- */
38
21
  export declare function searchHost(host: HostSpec, query: string, signal: AbortSignal | undefined, timeoutMs?: number, proxy?: string, timeRange?: TimeRange): Promise<AttemptOutcome>;
package/lib/transport.js CHANGED
@@ -2,6 +2,7 @@ import { SearchError, parseRetryAfter } from "./errors.js";
2
2
  import { proxyGet } from "./proxy.js";
3
3
  import { echoesQuery } from "./parsers.js";
4
4
  import { gateFor } from "./semaphore.js";
5
+ import { isRelevant, queryProfile } from "./relevance.js";
5
6
  /** Markers of an interstitial anti-bot page, narrow enough not to hit prose. */
6
7
  const BOT_WALL_MARKERS = ['qcaptcha', '访问异常', 'unusual traffic', 'verify you are human', '安全验证'];
7
8
  /**
@@ -147,8 +148,16 @@ async function attempt(host, url, signal, timeoutMs, proxy, query) {
147
148
  * push it into their query (currently DuckDuckGo's `df`).
148
149
  * @returns the outcome of the route that got furthest; cancellation is rethrown.
149
150
  */
150
- export async function searchHost(host, query, signal, timeoutMs = 15000, proxy, timeRange) {
151
+ /** Ask one engine one query, with the direct-then-tunnel retry. */
152
+ async function attemptWithRoute(host, query, signal, timeoutMs, route, proxy, timeRange) {
151
153
  const url = host.build(query, timeRange);
154
+ const first = await attempt(host, url, signal, timeoutMs, route, query);
155
+ if (first.ok || route !== undefined || proxy === undefined || signal?.aborted === true)
156
+ return first;
157
+ const retry = await attempt(host, url, signal, timeoutMs, proxy, query);
158
+ return retry.ok ? retry : first;
159
+ }
160
+ export async function searchHost(host, query, signal, timeoutMs = 15000, proxy, timeRange) {
152
161
  const route = host.viaProxy === true ? proxy : undefined;
153
162
  // A gate holds the permit for the whole engine attempt, including the
154
163
  // direct-then-tunnel retry, so a burst of concurrent searches cannot stack
@@ -157,11 +166,34 @@ export async function searchHost(host, query, signal, timeoutMs = 15000, proxy,
157
166
  ? undefined
158
167
  : await gateFor(host.id, host.maxConcurrent).acquire(signal);
159
168
  try {
160
- const first = await attempt(host, url, signal, timeoutMs, route, query);
161
- if (first.ok || route !== undefined || proxy === undefined || signal?.aborted === true)
162
- return first;
163
- const retry = await attempt(host, url, signal, timeoutMs, proxy, query);
164
- return retry.ok ? retry : first;
169
+ const result = await attemptWithRoute(host, query, signal, timeoutMs, route, proxy, timeRange);
170
+ const variants = host.variants?.(query) ?? [];
171
+ if (variants.length === 0 || signal?.aborted === true)
172
+ return result;
173
+ // Only pay for the extra request when the engine's first answer is unusable.
174
+ // A working short query (`pip 安装 requests 库`, `React useEffect 用法`) has
175
+ // relevant rows already, and asking again doubled its latency for nothing.
176
+ const profile = queryProfile(query);
177
+ if (result.ok && result.sources.some((source) => isRelevant(source, profile)))
178
+ return result;
179
+ const merged = result.ok ? [...result.sources] : [];
180
+ const seen = new Set(merged.map((source) => source.url));
181
+ for (const variant of variants) {
182
+ // `signal?.aborted === true` above narrowed the false branch to
183
+ // `aborted: false`, so test truthiness here instead of the literal.
184
+ if (signal?.aborted)
185
+ break;
186
+ const extra = await attemptWithRoute(host, variant, signal, timeoutMs, route, proxy, timeRange);
187
+ if (!extra.ok)
188
+ continue;
189
+ for (const source of extra.sources) {
190
+ if (seen.has(source.url))
191
+ continue;
192
+ seen.add(source.url);
193
+ merged.push(source);
194
+ }
195
+ }
196
+ return merged.length > 0 ? { ok: true, sources: merged } : result;
165
197
  }
166
198
  finally {
167
199
  release?.();
package/lib/types.d.ts CHANGED
@@ -54,6 +54,15 @@ export interface HostSpec {
54
54
  skipEcho?: boolean;
55
55
  /** Confirm the payload really belongs to the query (scraped pages only). */
56
56
  echoesQuery?: (payload: string, query: string) => boolean;
57
+ /**
58
+ * Alternate spellings to ask when the engine matches whole phrases.
59
+ *
60
+ * `cn.bing` answers a long Chinese query with a dictionary page for its first
61
+ * character; asking once more with the core words is the only way to get the
62
+ * rows it has. The transport merges the variant's rows after the original's,
63
+ * so ranking still sees the engine's own order first.
64
+ */
65
+ variants?: (query: string) => string[];
57
66
  /** Absolute request URL for a query. `timeRange` may be pushed down when the engine supports it. */
58
67
  build: (query: string, timeRange?: TimeRange) => string;
59
68
  /** Request body for a JSON POST. */
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Query variants for engines that match a whole phrase.
3
+ *
4
+ * `cn.bing` treats a long Chinese query as one phrase: when the phrase is not
5
+ * in its index it falls back to a dictionary page for the first character.
6
+ * `东数西算 枢纽节点` answers correctly, `东数西算 八个国家枢纽节点 定位`
7
+ * answers with ten entries for `东`, and `postgres 逻辑复制` answers with the
8
+ * PostgreSQL manual while `如何配置 postgres 逻辑复制` answers with the
9
+ * dictionary entry for `如何`. Re-asking once with the core words turns those
10
+ * failures back into relevant rows, at the cost of one extra request that the
11
+ * tier's soft deadline bounds.
12
+ *
13
+ * The rule is deliberately small and explainable:
14
+ *
15
+ * - a mixed query (CJK plus ASCII) drops question/action/intent segments and
16
+ * keeps the technical ones (`如何配置 postgres 逻辑复制` → `postgres 逻辑复制`);
17
+ * - a pure CJK query keeps its first content segment, which is where the entity
18
+ * usually sits (`东数西算 八个国家枢纽节点 定位` → `东数西算`);
19
+ * - everything else gets no variant, so an ordinary two-word query pays nothing.
20
+ *
21
+ * @module @fangchenghao/dsh-web-search/variants
22
+ */
23
+ /**
24
+ * Build at most one alternate query for a whole-phrase engine.
25
+ * @param query - the user's original query.
26
+ * @returns a single variant, or an empty array when none is likely useful.
27
+ */
28
+ export declare function cjkQueryVariants(query: string): string[];
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Query variants for engines that match a whole phrase.
3
+ *
4
+ * `cn.bing` treats a long Chinese query as one phrase: when the phrase is not
5
+ * in its index it falls back to a dictionary page for the first character.
6
+ * `东数西算 枢纽节点` answers correctly, `东数西算 八个国家枢纽节点 定位`
7
+ * answers with ten entries for `东`, and `postgres 逻辑复制` answers with the
8
+ * PostgreSQL manual while `如何配置 postgres 逻辑复制` answers with the
9
+ * dictionary entry for `如何`. Re-asking once with the core words turns those
10
+ * failures back into relevant rows, at the cost of one extra request that the
11
+ * tier's soft deadline bounds.
12
+ *
13
+ * The rule is deliberately small and explainable:
14
+ *
15
+ * - a mixed query (CJK plus ASCII) drops question/action/intent segments and
16
+ * keeps the technical ones (`如何配置 postgres 逻辑复制` → `postgres 逻辑复制`);
17
+ * - a pure CJK query keeps its first content segment, which is where the entity
18
+ * usually sits (`东数西算 八个国家枢纽节点 定位` → `东数西算`);
19
+ * - everything else gets no variant, so an ordinary two-word query pays nothing.
20
+ *
21
+ * @module @fangchenghao/dsh-web-search/variants
22
+ */
23
+ /** Segments that ask rather than name. */
24
+ const QUESTION_PREFIX = /^(如何|怎么|怎样|为什么|为何|哪些|什么|多少|请问|帮我|帮忙|查一下|介绍一下|介绍|解释一下|解释|说明一下|说明|有没有|是否|想知道|求)/u;
25
+ /** Whole segments that add intent rather than retrieval signal. */
26
+ const INTENT_SEGMENTS = new Set([
27
+ '定位', '介绍', '含义', '意思', '意义', '区别', '对比', '比较', '方法',
28
+ '教程', '步骤', '指南', '攻略', '用法', '示例', '例子', '作用', '原理',
29
+ '配置', '安装', '使用', '设置', '部署', '怎么用', '如何用', '有哪些',
30
+ ]);
31
+ /** Characters that make a segment CJK. */
32
+ const CJK = /[\u3400-\u9fff\uf900-\ufaff]/u;
33
+ /** Split a query into the labels a user separated with spaces. */
34
+ function segmentsOf(query) {
35
+ return query.trim().split(/\s+/u).filter((segment) => segment.length > 0);
36
+ }
37
+ /** Strip a leading question word and report whether anything usable is left. */
38
+ function contentOf(segment) {
39
+ const stripped = segment.replace(QUESTION_PREFIX, '').trim();
40
+ if (stripped.length < 2)
41
+ return undefined;
42
+ if (INTENT_SEGMENTS.has(stripped))
43
+ return undefined;
44
+ return stripped;
45
+ }
46
+ /** Whether a whole segment only carries intent. */
47
+ function isIntent(segment) {
48
+ return INTENT_SEGMENTS.has(segment) || QUESTION_PREFIX.test(segment);
49
+ }
50
+ /**
51
+ * Build at most one alternate query for a whole-phrase engine.
52
+ * @param query - the user's original query.
53
+ * @returns a single variant, or an empty array when none is likely useful.
54
+ */
55
+ export function cjkQueryVariants(query) {
56
+ if (!CJK.test(query))
57
+ return [];
58
+ const segments = segmentsOf(query);
59
+ if (segments.length < 2)
60
+ return [];
61
+ const ascii = segments.some((segment) => /^[a-z0-9][a-z0-9.+#_-]*$/iu.test(segment));
62
+ const variant = ascii
63
+ ? segments
64
+ .filter((segment) => !isIntent(segment))
65
+ .map((segment) => contentOf(segment) ?? '')
66
+ .filter((segment) => segment.length > 0)
67
+ .join(' ')
68
+ : (contentOf(segments[0] ?? '') ?? '');
69
+ if (variant.length === 0)
70
+ return [];
71
+ if (variant.toLowerCase() === query.trim().replace(/\s+/gu, ' ').toLowerCase())
72
+ return [];
73
+ return [variant];
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fffangchenghao/dsh-web-search",
3
- "version": "0.18.0",
3
+ "version": "0.19.1",
4
4
  "description": "DSH bundle: a key-free web search provider. Leads with the anonymous AnySearch API and falls back to public result pages (DuckDuckGo, Bing, 360), merged by reciprocal-rank fusion with a bilingual region policy, an engine cooldown and a TTL cache.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",