@240xu/dsh-websearch 2.8.5 → 2.8.7
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 +2 -2
- package/lib/backends/ddg.js +3 -2
- package/lib/backends/exa.js +2 -1
- package/lib/backends/parallel.js +2 -1
- package/lib/backends/searxng.js +162 -59
- package/lib/config.js +205 -0
- package/lib/index.js +10 -202
- package/lib/provider.js +47 -18
- package/lib/util/describe-error.js +58 -0
- package/lib/util/egress-fetch.js +93 -19
- package/lib/util/failure-label.js +40 -0
- package/lib/util/mcp-client.js +7 -3
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -143,7 +143,7 @@ pnpm install
|
|
|
143
143
|
|
|
144
144
|
### 4. per-backend 超时上限(P2)
|
|
145
145
|
|
|
146
|
-
- `ddg`
|
|
146
|
+
- `ddg` 专属超时上限 8s、`searxng` 5s(`min(上限, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。ddg 由 5s 上调至 8s:实测可用的慢抓取需 ~7.7s(route6 审计),5s 会把「即将返回」误判为超时。实测见 docs/real-call-2.8.0.md。
|
|
147
147
|
|
|
148
148
|
## v2.7.3 兼容修复 | What's new in v2.7.3
|
|
149
149
|
|
|
@@ -247,7 +247,7 @@ v2.7.0 缓存/熔断/历史三项的依据与刻意取舍(含查证过的反
|
|
|
247
247
|
2. **缓存失效(TTL-only vs 事件驱动)**:Cloudflare「Retention vs Freshness (TTL)」https://developers.cloudflare.com/cache/concepts/retention-vs-freshness/ 与「Revalidation」https://developers.cloudflare.com/cache/concepts/revalidation/ 。搜索结果没有可靠的原站变更信号可订阅(网页索引持续变化),事件驱动失效无锚点;TTL-only + 把 TTL 做成设置项(默认 900s)+ key 纳入后端组合,是"可接受的最终一致性"。取舍:900s 内索引更新不可见——对搜索场景可接受,且用户可调低。
|
|
248
248
|
3. **原子写(tmp + renameSync)**:POSIX 上 rename(2) 原子替换(Node 文档:newPath 已存在时覆盖);Windows 上 libuv 将 fs.rename 映射为 MoveFileExW(MOVEFILE_REPLACE_EXISTING)(libuv#283 https://github.com/joyent/libuv/issues/283 ,LWN 讨论 https://lwn.net/Articles/682988/ 指出 MS 文档不承诺该调用的原子性)。**结论:POSIX 双端原子;Windows 实践上等价但官方文档不背书**——因此本插件在写入端额外做了兜底:读端永远校验 JSON 完整性、坏条目按 miss 处理并删除,即使 Windows 上出现半写状态也不会返回坏数据。
|
|
249
249
|
4b. **查全查多(v2.8.0)**:Tavily Search API(`search_depth: advanced` 2 credits、`max_results` 0-20、`include_answer`、topic=news 时间加权)https://docs.tavily.com/api-reference/endpoint/search ;Exa Search API(type 分类检索、category 枚举、livecrawl;注意 2026 版 coding-agent 指南声明 neural 为 legacy 术语、且告诫勿臆造 category 值——本插件只注入 OpenAPI 枚举内的高置信值)https://exa.ai/docs/reference/search-api-guide-for-coding-agents 与 https://github.com/exa-labs/openapi-spec/blob/master/exa-openapi-spec.yaml ;SearXNG Search API(`categories` 逗号多类目、`language`)https://docs.searxng.org/dev/search_api.html ;Brave Search API(`freshness`、`result_filter`,本轮仅调研未接线)https://api-dashboard.search.brave.com/app/documentation 。多查询融合:RRF 出自 Cormack et al. 2009,RAG-Fusion 实现 https://github.com/Raudaschl/rag-fusion ;HyDE https://arxiv.org/abs/2212.10496 ;**门控依据** arXiv:2404.01037(盲目多查询劣化)——因此 multiQuery 默认关、启发式从严、原查询全权重参与。
|
|
250
|
-
4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA
|
|
250
|
+
4c. **per-backend 超时**:不可达主机的 TCP 连接失败不受应用层超时保护,只能靠 abort 计时器兜底;ddg(HTML 抓取)与 SearXNG(公共实例无 SLA)是拖尾主力。上限取「P50 成功延迟的一个数量级」并留余量:SearXNG 5s(实测成功 ~1.3s),ddg 8s(route6 实测成功可达 ~7.7s)。
|
|
251
251
|
4d. **搜索历史隐私**:Article 29 Working Party 意见书 WP148 https://ec.europa.eu/justice/article-29/documentation/opinion-recommendation/files/2008/wp148_en.pdf 认定查询日志(query + 时间 + 来源标识)属个人数据;EFF 六条自保建议 https://w2.eff.org/Privacy/search/searchtips.pdf 的第一条是"别在搜索词里放 PII"——说明 query 天然可能携带 PII(人名、账号、地址)。本插件的取舍:历史只存 {query, time, resultCount, backendsOk/Total}(无 IP、无 cookie、无结果 URL)、环形 50 条自动滚动即短保留、本机存储不出网、提供 historyEnabled 开关与 POST clear 端点。**未做 query 脱敏**:脱敏会破坏"查看最近搜了什么"的核心用途,且本机单用户场景下该数据本就在 DSH 会话日志里存在;若未来历史跨设备同步,脱敏/加密是上线前置条件。
|
|
252
252
|
|
|
253
253
|
## License | 许可
|
package/lib/backends/ddg.js
CHANGED
|
@@ -9,6 +9,7 @@ import { searchAborted, isAbortError, throwIfSearchAborted } from "../util/abort
|
|
|
9
9
|
import { applyDdgFilters, normalizeFilters } from "../util/filters.js";
|
|
10
10
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
11
11
|
import { egressFetch } from "../util/egress-fetch.js";
|
|
12
|
+
import { describeError } from "../util/describe-error.js";
|
|
12
13
|
|
|
13
14
|
export const DDG_ENDPOINT = "https://html.duckduckgo.com/html/";
|
|
14
15
|
|
|
@@ -55,9 +56,9 @@ export const ddgBackend = {
|
|
|
55
56
|
text = await res.text();
|
|
56
57
|
} catch (err) {
|
|
57
58
|
if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
|
|
58
|
-
hooks.recordOutcome?.({ status: "error", message:
|
|
59
|
+
hooks.recordOutcome?.({ status: "error", message: describeError(err) });
|
|
59
60
|
throw new WebError(
|
|
60
|
-
`ddg search failed: ${
|
|
61
|
+
`ddg search failed: ${describeError(err)}`,
|
|
61
62
|
"WEB_PROVIDER_ERROR",
|
|
62
63
|
{ cause: err },
|
|
63
64
|
);
|
package/lib/backends/exa.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { mcpCall } from "../util/mcp-client.js";
|
|
11
11
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
12
|
+
import { describeError } from "../util/describe-error.js";
|
|
12
13
|
|
|
13
14
|
const EXA_ENDPOINT = "https://mcp.exa.ai/mcp";
|
|
14
15
|
const EXA_TOOL = "web_search_exa";
|
|
@@ -63,7 +64,7 @@ export const exaBackend = {
|
|
|
63
64
|
} catch (err) {
|
|
64
65
|
if (err instanceof WebError) throw err;
|
|
65
66
|
throw new WebError(
|
|
66
|
-
`exa search failed: ${
|
|
67
|
+
`exa search failed: ${describeError(err)}`,
|
|
67
68
|
"WEB_PROVIDER_ERROR",
|
|
68
69
|
{ cause: err },
|
|
69
70
|
);
|
package/lib/backends/parallel.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
17
|
import { mcpCall } from "../util/mcp-client.js";
|
|
18
18
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
19
|
+
import { describeError } from "../util/describe-error.js";
|
|
19
20
|
|
|
20
21
|
const PARALLEL_ENDPOINT = "https://search.parallel.ai/mcp";
|
|
21
22
|
const PARALLEL_TOOL = "web_search";
|
|
@@ -51,7 +52,7 @@ export const parallelBackend = {
|
|
|
51
52
|
} catch (err) {
|
|
52
53
|
if (err instanceof WebError) throw err;
|
|
53
54
|
throw new WebError(
|
|
54
|
-
`parallel search failed: ${
|
|
55
|
+
`parallel search failed: ${describeError(err)}`,
|
|
55
56
|
"WEB_PROVIDER_ERROR",
|
|
56
57
|
{ cause: err },
|
|
57
58
|
);
|
package/lib/backends/searxng.js
CHANGED
|
@@ -4,15 +4,43 @@
|
|
|
4
4
|
* Auth: None (public instances) or API key for private instances
|
|
5
5
|
* Free tier: Unlimited (public instances)
|
|
6
6
|
* Default instance: https://searx.be
|
|
7
|
+
*
|
|
8
|
+
* Health is SEMANTIC (route3/route6): HTTP 200 alone means nothing — public
|
|
9
|
+
* instances answer non-browser clients with anti-bot interstitials (searx.be
|
|
10
|
+
* served an 11 KB "Verifying your browser…" page with status 200). A response
|
|
11
|
+
* only counts as healthy when it parses as JSON AND carries a results[]
|
|
12
|
+
* array (validation); an empty results[] is a legitimate empty search.
|
|
7
13
|
*/
|
|
8
14
|
|
|
9
15
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
10
16
|
import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
|
|
11
17
|
import { applySearxngFilters, normalizeFilters, safeSearchParams } from "../util/filters.js";
|
|
12
18
|
import { egressFetch } from "../util/egress-fetch.js";
|
|
19
|
+
import { describeError } from "../util/describe-error.js";
|
|
13
20
|
|
|
14
21
|
const DEFAULT_SEARXNG_URL = "https://searx.be";
|
|
15
22
|
|
|
23
|
+
// Markers of anti-bot / interstitial pages seen across public instances
|
|
24
|
+
// (route3 matrix: Anubis "Making sure you're not a bot!", Substation
|
|
25
|
+
// "Security check", cookie challenges, searx.be's own "Verifying your
|
|
26
|
+
// browser…"). Used only to CLASSIFY a non-JSON 200 for telemetry/health —
|
|
27
|
+
// there is deliberately no evasion logic here (no JS, no cookie forging).
|
|
28
|
+
const ANTI_BOT_RE = /(verifying your browser|making sure you.?re not a bot|checking you are not a bot|anubis|antibot|security check|just a moment|enable javascript|captcha|browser verification)/i;
|
|
29
|
+
|
|
30
|
+
// Multi-instance failover (opt-in via searxngBaseURLs; route3 §5.4 draft).
|
|
31
|
+
// Public-instance 429/anti-bot windows run 5-8+ minutes, so a failed instance
|
|
32
|
+
// is rotated out (not retried every search); a success clears its cooldown.
|
|
33
|
+
// Fail-open: when every candidate is cooling down we still try them all —
|
|
34
|
+
// rotation must never make search worse than the single-instance status quo.
|
|
35
|
+
const INSTANCE_COOLDOWN_MS = 10 * 60_000;
|
|
36
|
+
const INSTANCE_ATTEMPT_TIMEOUT_MS = 4500;
|
|
37
|
+
const instanceCooldowns = new Map(); // baseURL -> cooledUntil (epoch ms)
|
|
38
|
+
|
|
39
|
+
/** Test hook: clear per-instance cooldowns between cases. */
|
|
40
|
+
export function resetInstanceCooldowns() {
|
|
41
|
+
instanceCooldowns.clear();
|
|
42
|
+
}
|
|
43
|
+
|
|
16
44
|
/** @type {import("../provider.js").Backend} */
|
|
17
45
|
export const searxngBackend = {
|
|
18
46
|
id: "searxng",
|
|
@@ -26,76 +54,151 @@ export const searxngBackend = {
|
|
|
26
54
|
async search(request, signal, options, hooks) {
|
|
27
55
|
throwIfSearchAborted(signal);
|
|
28
56
|
const backendOpts = options ?? {};
|
|
29
|
-
|
|
30
57
|
const baseURL = backendOpts.baseURL ?? DEFAULT_SEARXNG_URL;
|
|
31
58
|
const apiKey = await backendOpts.resolveApiKey?.(); // Optional for private instances
|
|
32
|
-
|
|
33
|
-
const url = new URL(baseURL);
|
|
34
|
-
url.pathname = url.pathname.replace(/\/+$/,"") + "/search";
|
|
35
|
-
url.searchParams.set("q", request.query);
|
|
36
|
-
url.searchParams.set("format", "json");
|
|
37
|
-
// deepCoverage widens the category sweep (docs.searxng.org Search API:
|
|
38
|
-
// categories is a comma-separated list) — breadth over one category.
|
|
39
|
-
url.searchParams.set("categories", request.deepCoverage === true ? "general,news,it" : "general");
|
|
40
|
-
// Language: settings/request filter wins, else historical "en" default.
|
|
41
|
-
const filters = normalizeFilters(request.filters);
|
|
42
|
-
url.searchParams.set("language", filters.lang ?? "en");
|
|
43
|
-
applySearxngFilters(url, filters); // time_range (+ language override)
|
|
44
|
-
// Safe-search defaults ON (preserves the previous hardcoded behavior).
|
|
45
|
-
url.searchParams.set("safesearch", safeSearchParams("searxng", backendOpts.safeSearch ?? true) ?? "1");
|
|
46
|
-
url.searchParams.set("pageno", "1");
|
|
47
|
-
|
|
48
|
-
const headers = {
|
|
49
|
-
"Accept": "application/json",
|
|
50
|
-
"User-Agent": "dsh-websearch/2.3",
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
if (apiKey) {
|
|
54
|
-
headers["Authorization"] = "Bearer " + apiKey;
|
|
55
|
-
}
|
|
56
59
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
60
|
+
const candidates = [];
|
|
61
|
+
for (const candidate of [baseURL, ...(Array.isArray(backendOpts.baseURLs) ? backendOpts.baseURLs : [])]) {
|
|
62
|
+
const trimmed = typeof candidate === "string" ? candidate.trim() : "";
|
|
63
|
+
if (trimmed !== "" && !candidates.includes(trimmed)) candidates.push(trimmed);
|
|
64
|
+
}
|
|
62
65
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
headers,
|
|
68
|
-
redirect: "error",
|
|
69
|
-
|
|
70
|
-
signal,
|
|
71
|
-
});
|
|
72
|
-
} catch (error) {
|
|
73
|
-
if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
|
|
74
|
-
throw new WebError("SearXNG request failed: " + error +
|
|
75
|
-
" (instance unreachable? point searxngBaseURL at another public instance)", "WEB_PROVIDER_ERROR", { cause: error });
|
|
66
|
+
// Single instance (the default): legacy path, unchanged semantics.
|
|
67
|
+
if (candidates.length === 1) {
|
|
68
|
+
const sources = await queryInstance(candidates[0], request, signal, backendOpts, apiKey, hooks);
|
|
69
|
+
return { sources };
|
|
76
70
|
}
|
|
77
71
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
72
|
+
// Multi-instance: sequential attempts (etiquette: never fan out against
|
|
73
|
+
// volunteer instances), per-instance soft timeout, cooldown on failure.
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
const fresh = candidates.filter((u) => (instanceCooldowns.get(u) ?? 0) <= now);
|
|
76
|
+
const order = fresh.length > 0 ? fresh : candidates; // all cooled -> fail-open
|
|
77
|
+
let lastErr = null;
|
|
78
|
+
for (const candidate of order) {
|
|
79
|
+
throwIfSearchAborted(signal);
|
|
80
|
+
const attemptController = new AbortController();
|
|
81
|
+
const attemptSignal = signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal;
|
|
82
|
+
const timer = setTimeout(() => attemptController.abort(), INSTANCE_ATTEMPT_TIMEOUT_MS);
|
|
83
|
+
try {
|
|
84
|
+
const sources = await queryInstance(candidate, request, attemptSignal, backendOpts, apiKey, hooks);
|
|
85
|
+
instanceCooldowns.delete(candidate);
|
|
86
|
+
return { sources };
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (signal?.aborted === true) throw searchAborted(signal, error);
|
|
89
|
+
instanceCooldowns.set(candidate, Date.now() + INSTANCE_COOLDOWN_MS);
|
|
90
|
+
if (attemptController.signal.aborted && !(signal && signal.aborted)) {
|
|
91
|
+
lastErr = new WebError(
|
|
92
|
+
`SearXNG instance attempt timed out after ${INSTANCE_ATTEMPT_TIMEOUT_MS}ms (${candidate})`,
|
|
93
|
+
"WEB_PROVIDER_ERROR",
|
|
94
|
+
{ cause: error instanceof Error ? error : undefined },
|
|
95
|
+
);
|
|
96
|
+
} else if (error instanceof WebError && error.code !== "WEB_ABORTED") {
|
|
97
|
+
lastErr = error;
|
|
98
|
+
} else {
|
|
99
|
+
lastErr = new WebError(
|
|
100
|
+
"SearXNG instance failed (" + candidate + "): " + describeError(error),
|
|
101
|
+
"WEB_PROVIDER_ERROR",
|
|
102
|
+
{ cause: error instanceof Error ? error : undefined },
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
} finally {
|
|
106
|
+
clearTimeout(timer);
|
|
83
107
|
}
|
|
84
|
-
throw new WebError("SearXNG API error (HTTP " + response.status + "): " + text, "WEB_PROVIDER_ERROR");
|
|
85
108
|
}
|
|
109
|
+
throw lastErr ?? new WebError("SearXNG: no instance available (all cooling down)", "WEB_PROVIDER_ERROR");
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* One request against one instance. Throws WebError on any failure; abort
|
|
115
|
+
* semantics are the caller's contract (signal passed through verbatim).
|
|
116
|
+
* @returns {Promise<Array>} sources
|
|
117
|
+
*/
|
|
118
|
+
async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hooks) {
|
|
119
|
+
const url = new URL(baseURL);
|
|
120
|
+
url.pathname = url.pathname.replace(/\/+$/,"") + "/search";
|
|
121
|
+
url.searchParams.set("q", request.query);
|
|
122
|
+
url.searchParams.set("format", "json");
|
|
123
|
+
// deepCoverage widens the category sweep (docs.searxng.org Search API:
|
|
124
|
+
// categories is a comma-separated list) — breadth over one category.
|
|
125
|
+
url.searchParams.set("categories", request.deepCoverage === true ? "general,news,it" : "general");
|
|
126
|
+
// Language: settings/request filter wins, else historical "en" default.
|
|
127
|
+
const filters = normalizeFilters(request.filters);
|
|
128
|
+
url.searchParams.set("language", filters.lang ?? "en");
|
|
129
|
+
applySearxngFilters(url, filters); // time_range (+ language override)
|
|
130
|
+
// Safe-search defaults ON (preserves the previous hardcoded behavior).
|
|
131
|
+
url.searchParams.set("safesearch", safeSearchParams("searxng", backendOpts.safeSearch ?? true) ?? "1");
|
|
132
|
+
url.searchParams.set("pageno", "1");
|
|
133
|
+
|
|
134
|
+
const headers = {
|
|
135
|
+
"Accept": "application/json",
|
|
136
|
+
"User-Agent": "dsh-websearch/2.3",
|
|
137
|
+
};
|
|
138
|
+
if (apiKey) {
|
|
139
|
+
headers["Authorization"] = "Bearer " + apiKey;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
hooks?.recordRequest?.({
|
|
143
|
+
endpoint: baseURL,
|
|
144
|
+
toolName: "searxng_search",
|
|
145
|
+
body: { q: request.query },
|
|
146
|
+
});
|
|
86
147
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
148
|
+
let response;
|
|
149
|
+
try {
|
|
150
|
+
response = await egressFetch(url, {
|
|
151
|
+
method: "GET",
|
|
152
|
+
headers,
|
|
153
|
+
redirect: "error",
|
|
154
|
+
signal,
|
|
155
|
+
});
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
|
|
158
|
+
throw new WebError("SearXNG request failed: " + describeError(error) +
|
|
159
|
+
" (instance unreachable? point searxngBaseURL at another public instance)", "WEB_PROVIDER_ERROR", { cause: error });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (!response.ok) {
|
|
163
|
+
const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
|
|
164
|
+
hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
|
|
165
|
+
if (response.status === 429 || response.status >= 500) {
|
|
166
|
+
throw new WebError("SearXNG API error (HTTP " + response.status + "): " + text + " (instance struggling? point searxngBaseURL at another public instance)", "WEB_PROVIDER_ERROR");
|
|
92
167
|
}
|
|
168
|
+
throw new WebError("SearXNG API error (HTTP " + response.status + "): " + text, "WEB_PROVIDER_ERROR");
|
|
169
|
+
}
|
|
93
170
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
171
|
+
// 200 does not mean JSON (route3: searx.be 200 + HTML anti-bot page). Read
|
|
172
|
+
// the body once and classify the parse failure so the failure reads as
|
|
173
|
+
// "instance degraded", not like a plugin bug.
|
|
174
|
+
const bodyText = await response.text();
|
|
175
|
+
// Optional chain: fetch shims/mocks may omit headers; a real Response never does.
|
|
176
|
+
const contentType = String(response.headers?.get?.("content-type") ?? "");
|
|
177
|
+
let data;
|
|
178
|
+
try {
|
|
179
|
+
data = JSON.parse(bodyText);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
const antiBot = /text\/html/i.test(contentType) || ANTI_BOT_RE.test(bodyText.slice(0, 4096));
|
|
182
|
+
const message = antiBot
|
|
183
|
+
? "SearXNG instance degraded: returned an anti-bot challenge page (HTTP 200, non-JSON)"
|
|
184
|
+
: "SearXNG: invalid JSON response (content-type: " + (contentType || "unknown") + ")";
|
|
185
|
+
hooks?.recordOutcome?.({ status: "error", message });
|
|
186
|
+
throw new WebError(message, "WEB_PROVIDER_ERROR", { cause: error });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Semantic health gate: a SearXNG API response always carries a results[]
|
|
190
|
+
// array; JSON without one (walls/proxies wrapping errors in 200s) is a
|
|
191
|
+
// protocol violation, not an empty search.
|
|
192
|
+
if (!Array.isArray(data?.results)) {
|
|
193
|
+
const message = "SearXNG: JSON response lacks a results[] array (not a SearXNG API response?)";
|
|
194
|
+
hooks?.recordOutcome?.({ status: "error", message });
|
|
195
|
+
throw new WebError(message, "WEB_PROVIDER_ERROR");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const sources = parseSearxngResult(data, request.maxResults ?? 8);
|
|
199
|
+
hooks?.recordOutcome?.({ status: "success", count: sources.length });
|
|
200
|
+
return sources;
|
|
201
|
+
}
|
|
99
202
|
|
|
100
203
|
/**
|
|
101
204
|
* Parse SearXNG API response.
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { BREAKER_DEFAULTS } from "./breaker.js";
|
|
3
|
+
|
|
4
|
+
/** Environment-variable names each key-gated backend reads. */
|
|
5
|
+
const DEFAULT_KEY_ENV = {
|
|
6
|
+
deepseek: "DEEPSEEK_API_KEY",
|
|
7
|
+
anthropic: "ANTHROPIC_API_KEY",
|
|
8
|
+
openai: "OPENAI_API_KEY",
|
|
9
|
+
brave: "BRAVE_API_KEY",
|
|
10
|
+
tavily: "TAVILY_API_KEY",
|
|
11
|
+
serper: "SERPER_API_KEY",
|
|
12
|
+
mojeek: "MOJEEK_API_KEY",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Default base URLs. */
|
|
16
|
+
const DEFAULT_BASE_URLS = {
|
|
17
|
+
exa: "https://mcp.exa.ai/mcp",
|
|
18
|
+
parallel: "https://search.parallel.ai/mcp",
|
|
19
|
+
ddg: "https://html.duckduckgo.com/html/",
|
|
20
|
+
searxng: "https://searx.be",
|
|
21
|
+
brave: "https://api.search.brave.com/res/v1/web/search",
|
|
22
|
+
tavily: "https://api.tavily.com/search",
|
|
23
|
+
serper: "https://google.serper.dev/search",
|
|
24
|
+
mojeek: "https://api.mojeek.com/v1/search",
|
|
25
|
+
deepseek: "https://api.deepseek.com/anthropic/v1",
|
|
26
|
+
anthropic: "https://api.anthropic.com/v1",
|
|
27
|
+
openai: "https://api.openai.com/v1",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Default models for model-carrying backends. */
|
|
31
|
+
const DEFAULT_MODELS = {
|
|
32
|
+
deepseek: "deepseek-v4-flash",
|
|
33
|
+
anthropic: "claude-sonnet-4-6",
|
|
34
|
+
openai: "gpt-4o",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* GUI-friendly labels for each backend (shown in the Settings panel).
|
|
39
|
+
*/
|
|
40
|
+
const DEFAULT_LABELS = {
|
|
41
|
+
exa: "Exa (MCP, 免费无 Key)",
|
|
42
|
+
parallel: "Parallel (MCP, 免费无 Key)",
|
|
43
|
+
ddg: "DuckDuckGo (HTML 抓取, 兜底)",
|
|
44
|
+
searxng: "SearXNG (元搜索, 免费无 Key)",
|
|
45
|
+
brave: "Brave Search (独立索引, 2000/月免费)",
|
|
46
|
+
tavily: "Tavily (AI 专用, 含答案摘要)",
|
|
47
|
+
serper: "Serper.dev (Google 抓取, 2500/月免费)",
|
|
48
|
+
mojeek: "Mojeek (独立索引, 1000/天免费)",
|
|
49
|
+
deepseek: "DeepSeek (原生 web_search, 需 Key)",
|
|
50
|
+
anthropic: "Anthropic (Claude 原生 web_search, 需 Key)",
|
|
51
|
+
openai: "OpenAI (Responses API web_search, 需 Key)",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Settings schema — flat, GUI-friendly. Every object property is optional by
|
|
56
|
+
* default in schemastery; defaults are supplied via .default(). API keys are
|
|
57
|
+
* credential-refs (env-var names), which the Settings UI renders as a
|
|
58
|
+
* credential selector / secret field.
|
|
59
|
+
*/
|
|
60
|
+
export const Config = z.object({
|
|
61
|
+
// Global
|
|
62
|
+
numResults: z.number().step(1).min(1).max(50).default(8)
|
|
63
|
+
.description("每次搜索返回的最大结果数"),
|
|
64
|
+
concurrency: z.number().step(1).min(1).max(10).default(6)
|
|
65
|
+
.description("同时并发的后端数量"),
|
|
66
|
+
backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(30000)
|
|
67
|
+
.description("单后端最大等待时间(毫秒)"),
|
|
68
|
+
|
|
69
|
+
// v2.1 result shaping
|
|
70
|
+
recency: z.union(["any", "day", "week", "month", "year"]).default("any")
|
|
71
|
+
.description("时间范围过滤(映射到各后端原生参数;any=不过滤)"),
|
|
72
|
+
language: z.string().default("")
|
|
73
|
+
.description("搜索语言(如 en、zh-CN;留空用各后端默认)"),
|
|
74
|
+
safeSearch: z.boolean().default(true)
|
|
75
|
+
.description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
|
|
76
|
+
dedupStrategy: z.union(["url", "url+title"]).default("url")
|
|
77
|
+
.description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
|
|
78
|
+
rerank: z.boolean().default(false)
|
|
79
|
+
.description("按查询词相关性重排序(确定性、并列时保持后端优先级)"),
|
|
80
|
+
resultTelemetry: z.boolean().default(true)
|
|
81
|
+
.description("在搜索结果尾部附一行后端健康遥测(状态+耗时),模型可据此自诊断"),
|
|
82
|
+
|
|
83
|
+
// v2.7.0 disk cache / circuit breaker / search history
|
|
84
|
+
// W1 (fe-ui review): labels speak user language with a group prefix
|
|
85
|
+
// (【缓存】/【熔断】/【历史】) instead of camelCase keys; units are
|
|
86
|
+
// spelled out (秒 / 毫秒) and grouping follows the field order below.
|
|
87
|
+
cacheEnabled: z.boolean().default(true)
|
|
88
|
+
.description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
|
|
89
|
+
cacheTtl: z.number().step(30).min(30).max(86400).default(900)
|
|
90
|
+
.description("缓存有效期【缓存】(单位:秒):默认 900 秒;不想用缓存请直接关闭上一项"),
|
|
91
|
+
breakerEnabled: z.boolean().default(true)
|
|
92
|
+
.description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
|
|
93
|
+
breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
|
|
94
|
+
.description("熔断阈值【熔断】:连续失败多少次后触发(默认 3 次)"),
|
|
95
|
+
breakerCooldownMs: z.number().step(1000).min(0).max(3600000).default(BREAKER_DEFAULTS.cooldownMs)
|
|
96
|
+
.description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;设为 0 表示关闭冷却(熔断仅计数)"),
|
|
97
|
+
historyEnabled: z.boolean().default(true)
|
|
98
|
+
.description("记录搜索历史【历史】:只追加,最多 50 条;可在设置 → 搜索 中查看与清空"),
|
|
99
|
+
|
|
100
|
+
// v2.8.0 查全查多
|
|
101
|
+
multiQueryEnabled: z.boolean().default(false)
|
|
102
|
+
.description("多查询融合【查全】:复杂查询(长度>60 或含 vs/and/比较/对比/和)自动派生 2-3 个子查询,各扇出后用 RRF(k=60) 融合;默认关"),
|
|
103
|
+
deepCoverage: z.boolean().default(false)
|
|
104
|
+
.description("深度覆盖【查全】:每后端请求条数上调 50% 再全局去重截断,牺牲带宽换覆盖面;Tavily 自动切 advanced 深度,SearXNG 扩展多类目;默认关"),
|
|
105
|
+
|
|
106
|
+
// Enable toggles (one per backend)
|
|
107
|
+
enableExa: z.boolean().default(true).description(DEFAULT_LABELS.exa),
|
|
108
|
+
enableParallel: z.boolean().default(true).description(DEFAULT_LABELS.parallel),
|
|
109
|
+
enableDdg: z.boolean().default(true).description(DEFAULT_LABELS.ddg),
|
|
110
|
+
enableSearxng: z.boolean().default(true).description(DEFAULT_LABELS.searxng),
|
|
111
|
+
enableBrave: z.boolean().default(false).description(DEFAULT_LABELS.brave),
|
|
112
|
+
enableTavily: z.boolean().default(false).description(DEFAULT_LABELS.tavily),
|
|
113
|
+
enableSerper: z.boolean().default(false).description(DEFAULT_LABELS.serper),
|
|
114
|
+
enableMojeek: z.boolean().default(false).description(DEFAULT_LABELS.mojeek),
|
|
115
|
+
enableDeepseek: z.boolean().default(false).description(DEFAULT_LABELS.deepseek),
|
|
116
|
+
enableAnthropic: z.boolean().default(false).description(DEFAULT_LABELS.anthropic),
|
|
117
|
+
enableOpenai: z.boolean().default(false).description(DEFAULT_LABELS.openai),
|
|
118
|
+
|
|
119
|
+
// Credential refs (env-var names; secrets live in the credentials service)
|
|
120
|
+
braveApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.brave)
|
|
121
|
+
.description("Brave API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
122
|
+
tavilyApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.tavily)
|
|
123
|
+
.description("Tavily API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
124
|
+
serperApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.serper)
|
|
125
|
+
.description("Serper API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
126
|
+
mojeekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.mojeek)
|
|
127
|
+
.description("Mojeek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
128
|
+
deepseekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.deepseek)
|
|
129
|
+
.description("Deepseek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
130
|
+
anthropicApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.anthropic)
|
|
131
|
+
.description("Anthropic API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
132
|
+
openaiApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.openai)
|
|
133
|
+
.description("Openai API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
134
|
+
searxngApiKeyEnv: z.string().role("credential-ref").default("SEARXNG_API_KEY")
|
|
135
|
+
.description("SearXNG 私有实例的 API Key 凭证引用(公共实例留空)"),
|
|
136
|
+
|
|
137
|
+
// Base URLs (defaults from built-in registry)
|
|
138
|
+
braveBaseURL: z.string().default(DEFAULT_BASE_URLS.brave)
|
|
139
|
+
.description("Brave API 端点(默认官方;自托管/代理实例改此项)"),
|
|
140
|
+
tavilyBaseURL: z.string().default(DEFAULT_BASE_URLS.tavily)
|
|
141
|
+
.description("Tavily API 端点(默认官方;自托管/代理实例改此项)"),
|
|
142
|
+
serperBaseURL: z.string().default(DEFAULT_BASE_URLS.serper)
|
|
143
|
+
.description("Serper.dev API 端点(默认官方;自托管/代理实例改此项)"),
|
|
144
|
+
mojeekBaseURL: z.string().default(DEFAULT_BASE_URLS.mojeek)
|
|
145
|
+
.description("Mojeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
146
|
+
searxngBaseURL: z.string().default(DEFAULT_BASE_URLS.searxng)
|
|
147
|
+
.description("SearXNG API 端点(默认官方;自托管/代理实例改此项)"),
|
|
148
|
+
searxngBaseURLs: z.array(z.string()).default([])
|
|
149
|
+
.description("SearXNG 备用实例列表(可选;主实例失败时按序尝试,失败实例冷却 10 分钟)"),
|
|
150
|
+
deepseekBaseURL: z.string().default(DEFAULT_BASE_URLS.deepseek)
|
|
151
|
+
.description("DeepSeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
152
|
+
anthropicBaseURL: z.string().default(DEFAULT_BASE_URLS.anthropic)
|
|
153
|
+
.description("Anthropic API 端点(默认官方;自托管/代理实例改此项)"),
|
|
154
|
+
openaiBaseURL: z.string().default(DEFAULT_BASE_URLS.openai)
|
|
155
|
+
.description("OpenAI API 端点(默认官方;自托管/代理实例改此项)"),
|
|
156
|
+
|
|
157
|
+
// Models
|
|
158
|
+
deepseekModel: z.string().default(DEFAULT_MODELS.deepseek)
|
|
159
|
+
.description("DeepSeek 后端使用的模型名"),
|
|
160
|
+
anthropicModel: z.string().default(DEFAULT_MODELS.anthropic)
|
|
161
|
+
.description("Anthropic 后端使用的模型名"),
|
|
162
|
+
openaiModel: z.string().default(DEFAULT_MODELS.openai)
|
|
163
|
+
.description("OpenAI 后端使用的模型名"),
|
|
164
|
+
tavilySearchDepth: z.union(["basic", "advanced"]).default("basic")
|
|
165
|
+
.description("Tavily 搜索深度"),
|
|
166
|
+
|
|
167
|
+
// Legacy compatibility: explicit enabled-backend list overrides toggles
|
|
168
|
+
enabledBackends: z.array(z.string())
|
|
169
|
+
.description("显式启用后端列表(优先于上方开关;留空则用开关)"),
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// 0.2.0 SettingsForms adapter (cross-settings-forms.md ruling): the 0.2.0
|
|
173
|
+
// settings service auto-generates its form from entry.fiber.runtime.Config —
|
|
174
|
+
// but volatileForm (RT dsh-settings lib/index.js:122-138) keeps ONLY fields
|
|
175
|
+
// with meta.volatile; a Config without any yields an empty form. Marking the
|
|
176
|
+
// top object makes the whole Config the form. Direct meta assignment (not
|
|
177
|
+
// .volatile(), which returns a NEW schema and throws on re-wrap) is
|
|
178
|
+
// equivalent and idempotent on both the 0.1.5 and 0.2.0 schemastery lines.
|
|
179
|
+
Config.meta = { ...Config.meta, volatile: true };
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Per-field user-language labels (fe-ui W1 remainder): the settings renderer
|
|
183
|
+
* falls back to camelCase keys when no label is present, so attach one to
|
|
184
|
+
* each v2.7 descriptor (meta.label, plus a plain .label for renderers that
|
|
185
|
+
* read the top level). Units live in the label tail (秒 / 毫秒). Whether the
|
|
186
|
+
* host actually renders them is visual-check V5; the schema layer now
|
|
187
|
+
* provides the field regardless.
|
|
188
|
+
*/
|
|
189
|
+
const FIELD_LABELS = {
|
|
190
|
+
cacheEnabled: "启用搜索结果缓存",
|
|
191
|
+
cacheTtl: "缓存有效期(秒)",
|
|
192
|
+
breakerEnabled: "后端熔断器",
|
|
193
|
+
breakerThreshold: "熔断阈值(连续失败次数)",
|
|
194
|
+
breakerCooldownMs: "熔断冷却时长(毫秒)",
|
|
195
|
+
historyEnabled: "记录搜索历史",
|
|
196
|
+
};
|
|
197
|
+
for (const [key, label] of Object.entries(FIELD_LABELS)) {
|
|
198
|
+
const sch = Config.dict?.[key];
|
|
199
|
+
if (sch) {
|
|
200
|
+
sch.meta = { ...sch.meta, label };
|
|
201
|
+
sch.label = label;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export { DEFAULT_KEY_ENV, DEFAULT_BASE_URLS, DEFAULT_MODELS, DEFAULT_LABELS };
|
package/lib/index.js
CHANGED
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @module dsh-websearch
|
|
10
10
|
*/
|
|
11
|
-
import z from "@deepseek-ai/schemastery";
|
|
12
11
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
13
12
|
// NOTE (2026-09-12, dsh 0.1.5 compat): installSettingsSection +
|
|
14
13
|
// settingsNamespace were removed from @deepseek-ai/dsh-settings in the 0.1.5
|
|
@@ -42,6 +41,9 @@ import { BREAKER_DEFAULTS } from "./breaker.js";
|
|
|
42
41
|
import os from "node:os";
|
|
43
42
|
import path from "node:path";
|
|
44
43
|
|
|
44
|
+
import { Config, DEFAULT_KEY_ENV, DEFAULT_BASE_URLS, DEFAULT_MODELS, DEFAULT_LABELS } from "./config.js";
|
|
45
|
+
export { Config };
|
|
46
|
+
|
|
45
47
|
/** Cordis plugin name used by loader diagnostics. */
|
|
46
48
|
export const name = "unified-search";
|
|
47
49
|
/** The web seam this provider registers into. */
|
|
@@ -68,210 +70,11 @@ const BACKENDS = {
|
|
|
68
70
|
/** All backend ids in registry order. */
|
|
69
71
|
const ALL_BACKENDS = Object.keys(BACKENDS);
|
|
70
72
|
|
|
71
|
-
/** Backends enabled by default (keyless only). */
|
|
72
|
-
const DEFAULT_ENABLED = ["exa", "parallel", "ddg", "searxng"];
|
|
73
|
-
|
|
74
|
-
/** Environment-variable names each key-gated backend reads. */
|
|
75
|
-
const DEFAULT_KEY_ENV = {
|
|
76
|
-
deepseek: "DEEPSEEK_API_KEY",
|
|
77
|
-
anthropic: "ANTHROPIC_API_KEY",
|
|
78
|
-
openai: "OPENAI_API_KEY",
|
|
79
|
-
brave: "BRAVE_API_KEY",
|
|
80
|
-
tavily: "TAVILY_API_KEY",
|
|
81
|
-
serper: "SERPER_API_KEY",
|
|
82
|
-
mojeek: "MOJEEK_API_KEY",
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
/** Default base URLs. */
|
|
86
|
-
const DEFAULT_BASE_URLS = {
|
|
87
|
-
exa: "https://mcp.exa.ai/mcp",
|
|
88
|
-
parallel: "https://search.parallel.ai/mcp",
|
|
89
|
-
ddg: "https://html.duckduckgo.com/html/",
|
|
90
|
-
searxng: "https://searx.be",
|
|
91
|
-
brave: "https://api.search.brave.com/res/v1/web/search",
|
|
92
|
-
tavily: "https://api.tavily.com/search",
|
|
93
|
-
serper: "https://google.serper.dev/search",
|
|
94
|
-
mojeek: "https://api.mojeek.com/v1/search",
|
|
95
|
-
deepseek: "https://api.deepseek.com/anthropic/v1",
|
|
96
|
-
anthropic: "https://api.anthropic.com/v1",
|
|
97
|
-
openai: "https://api.openai.com/v1",
|
|
98
|
-
};
|
|
99
|
-
|
|
100
73
|
/** Env var that overrides the default backend sweep order / enabled set. */
|
|
101
74
|
const ENABLED_ENV = "DSH_UNIFIED_SEARCH_BACKENDS";
|
|
102
75
|
|
|
103
|
-
/**
|
|
104
|
-
const
|
|
105
|
-
deepseek: "deepseek-v4-flash",
|
|
106
|
-
anthropic: "claude-sonnet-4-6",
|
|
107
|
-
openai: "gpt-4o",
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* GUI-friendly labels for each backend (shown in the Settings panel).
|
|
112
|
-
*/
|
|
113
|
-
const DEFAULT_LABELS = {
|
|
114
|
-
exa: "Exa (MCP, 免费无 Key)",
|
|
115
|
-
parallel: "Parallel (MCP, 免费无 Key)",
|
|
116
|
-
ddg: "DuckDuckGo (HTML 抓取, 兜底)",
|
|
117
|
-
searxng: "SearXNG (元搜索, 免费无 Key)",
|
|
118
|
-
brave: "Brave Search (独立索引, 2000/月免费)",
|
|
119
|
-
tavily: "Tavily (AI 专用, 含答案摘要)",
|
|
120
|
-
serper: "Serper.dev (Google 抓取, 2500/月免费)",
|
|
121
|
-
mojeek: "Mojeek (独立索引, 1000/天免费)",
|
|
122
|
-
deepseek: "DeepSeek (原生 web_search, 需 Key)",
|
|
123
|
-
anthropic: "Anthropic (Claude 原生 web_search, 需 Key)",
|
|
124
|
-
openai: "OpenAI (Responses API web_search, 需 Key)",
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Settings schema — flat, GUI-friendly. Every object property is optional by
|
|
129
|
-
* default in schemastery; defaults are supplied via .default(). API keys are
|
|
130
|
-
* credential-refs (env-var names), which the Settings UI renders as a
|
|
131
|
-
* credential selector / secret field.
|
|
132
|
-
*/
|
|
133
|
-
export const Config = z.object({
|
|
134
|
-
// Global
|
|
135
|
-
numResults: z.number().step(1).min(1).max(50).default(8)
|
|
136
|
-
.description("每次搜索返回的最大结果数"),
|
|
137
|
-
concurrency: z.number().step(1).min(1).max(10).default(6)
|
|
138
|
-
.description("同时并发的后端数量"),
|
|
139
|
-
backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(30000)
|
|
140
|
-
.description("单后端最大等待时间(毫秒)"),
|
|
141
|
-
|
|
142
|
-
// v2.1 result shaping
|
|
143
|
-
recency: z.union(["any", "day", "week", "month", "year"]).default("any")
|
|
144
|
-
.description("时间范围过滤(映射到各后端原生参数;any=不过滤)"),
|
|
145
|
-
language: z.string().default("")
|
|
146
|
-
.description("搜索语言(如 en、zh-CN;留空用各后端默认)"),
|
|
147
|
-
safeSearch: z.boolean().default(true)
|
|
148
|
-
.description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
|
|
149
|
-
dedupStrategy: z.union(["url", "url+title"]).default("url")
|
|
150
|
-
.description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
|
|
151
|
-
rerank: z.boolean().default(false)
|
|
152
|
-
.description("按查询词相关性重排序(确定性、并列时保持后端优先级)"),
|
|
153
|
-
resultTelemetry: z.boolean().default(true)
|
|
154
|
-
.description("在搜索结果尾部附一行后端健康遥测(状态+耗时),模型可据此自诊断"),
|
|
155
|
-
|
|
156
|
-
// v2.7.0 disk cache / circuit breaker / search history
|
|
157
|
-
// W1 (fe-ui review): labels speak user language with a group prefix
|
|
158
|
-
// (【缓存】/【熔断】/【历史】) instead of camelCase keys; units are
|
|
159
|
-
// spelled out (秒 / 毫秒) and grouping follows the field order below.
|
|
160
|
-
cacheEnabled: z.boolean().default(true)
|
|
161
|
-
.description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
|
|
162
|
-
cacheTtl: z.number().step(30).min(30).max(86400).default(900)
|
|
163
|
-
.description("缓存有效期【缓存】(单位:秒):默认 900 秒;不想用缓存请直接关闭上一项"),
|
|
164
|
-
breakerEnabled: z.boolean().default(true)
|
|
165
|
-
.description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
|
|
166
|
-
breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
|
|
167
|
-
.description("熔断阈值【熔断】:连续失败多少次后触发(默认 3 次)"),
|
|
168
|
-
breakerCooldownMs: z.number().step(1000).min(0).max(3600000).default(BREAKER_DEFAULTS.cooldownMs)
|
|
169
|
-
.description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;设为 0 表示关闭冷却(熔断仅计数)"),
|
|
170
|
-
historyEnabled: z.boolean().default(true)
|
|
171
|
-
.description("记录搜索历史【历史】:只追加,最多 50 条;可在设置 → 搜索 中查看与清空"),
|
|
172
|
-
|
|
173
|
-
// v2.8.0 查全查多
|
|
174
|
-
multiQueryEnabled: z.boolean().default(false)
|
|
175
|
-
.description("多查询融合【查全】:复杂查询(长度>60 或含 vs/and/比较/对比/和)自动派生 2-3 个子查询,各扇出后用 RRF(k=60) 融合;默认关"),
|
|
176
|
-
deepCoverage: z.boolean().default(false)
|
|
177
|
-
.description("深度覆盖【查全】:每后端请求条数上调 50% 再全局去重截断,牺牲带宽换覆盖面;Tavily 自动切 advanced 深度,SearXNG 扩展多类目;默认关"),
|
|
178
|
-
|
|
179
|
-
// Enable toggles (one per backend)
|
|
180
|
-
enableExa: z.boolean().default(true).description(DEFAULT_LABELS.exa),
|
|
181
|
-
enableParallel: z.boolean().default(true).description(DEFAULT_LABELS.parallel),
|
|
182
|
-
enableDdg: z.boolean().default(true).description(DEFAULT_LABELS.ddg),
|
|
183
|
-
enableSearxng: z.boolean().default(true).description(DEFAULT_LABELS.searxng),
|
|
184
|
-
enableBrave: z.boolean().default(false).description(DEFAULT_LABELS.brave),
|
|
185
|
-
enableTavily: z.boolean().default(false).description(DEFAULT_LABELS.tavily),
|
|
186
|
-
enableSerper: z.boolean().default(false).description(DEFAULT_LABELS.serper),
|
|
187
|
-
enableMojeek: z.boolean().default(false).description(DEFAULT_LABELS.mojeek),
|
|
188
|
-
enableDeepseek: z.boolean().default(false).description(DEFAULT_LABELS.deepseek),
|
|
189
|
-
enableAnthropic: z.boolean().default(false).description(DEFAULT_LABELS.anthropic),
|
|
190
|
-
enableOpenai: z.boolean().default(false).description(DEFAULT_LABELS.openai),
|
|
191
|
-
|
|
192
|
-
// Credential refs (env-var names; secrets live in the credentials service)
|
|
193
|
-
braveApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.brave)
|
|
194
|
-
.description("Brave API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
195
|
-
tavilyApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.tavily)
|
|
196
|
-
.description("Tavily API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
197
|
-
serperApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.serper)
|
|
198
|
-
.description("Serper API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
199
|
-
mojeekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.mojeek)
|
|
200
|
-
.description("Mojeek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
201
|
-
deepseekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.deepseek)
|
|
202
|
-
.description("Deepseek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
203
|
-
anthropicApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.anthropic)
|
|
204
|
-
.description("Anthropic API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
205
|
-
openaiApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.openai)
|
|
206
|
-
.description("Openai API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
207
|
-
searxngApiKeyEnv: z.string().role("credential-ref").default("SEARXNG_API_KEY")
|
|
208
|
-
.description("SearXNG 私有实例的 API Key 凭证引用(公共实例留空)"),
|
|
209
|
-
|
|
210
|
-
// Base URLs (defaults from built-in registry)
|
|
211
|
-
braveBaseURL: z.string().default(DEFAULT_BASE_URLS.brave)
|
|
212
|
-
.description("Brave API 端点(默认官方;自托管/代理实例改此项)"),
|
|
213
|
-
tavilyBaseURL: z.string().default(DEFAULT_BASE_URLS.tavily)
|
|
214
|
-
.description("Tavily API 端点(默认官方;自托管/代理实例改此项)"),
|
|
215
|
-
serperBaseURL: z.string().default(DEFAULT_BASE_URLS.serper)
|
|
216
|
-
.description("Serper.dev API 端点(默认官方;自托管/代理实例改此项)"),
|
|
217
|
-
mojeekBaseURL: z.string().default(DEFAULT_BASE_URLS.mojeek)
|
|
218
|
-
.description("Mojeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
219
|
-
searxngBaseURL: z.string().default(DEFAULT_BASE_URLS.searxng)
|
|
220
|
-
.description("SearXNG API 端点(默认官方;自托管/代理实例改此项)"),
|
|
221
|
-
deepseekBaseURL: z.string().default(DEFAULT_BASE_URLS.deepseek)
|
|
222
|
-
.description("DeepSeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
223
|
-
anthropicBaseURL: z.string().default(DEFAULT_BASE_URLS.anthropic)
|
|
224
|
-
.description("Anthropic API 端点(默认官方;自托管/代理实例改此项)"),
|
|
225
|
-
openaiBaseURL: z.string().default(DEFAULT_BASE_URLS.openai)
|
|
226
|
-
.description("OpenAI API 端点(默认官方;自托管/代理实例改此项)"),
|
|
227
|
-
|
|
228
|
-
// Models
|
|
229
|
-
deepseekModel: z.string().default(DEFAULT_MODELS.deepseek)
|
|
230
|
-
.description("DeepSeek 后端使用的模型名"),
|
|
231
|
-
anthropicModel: z.string().default(DEFAULT_MODELS.anthropic)
|
|
232
|
-
.description("Anthropic 后端使用的模型名"),
|
|
233
|
-
openaiModel: z.string().default(DEFAULT_MODELS.openai)
|
|
234
|
-
.description("OpenAI 后端使用的模型名"),
|
|
235
|
-
tavilySearchDepth: z.union(["basic", "advanced"]).default("basic")
|
|
236
|
-
.description("Tavily 搜索深度"),
|
|
237
|
-
|
|
238
|
-
// Legacy compatibility: explicit enabled-backend list overrides toggles
|
|
239
|
-
enabledBackends: z.array(z.string())
|
|
240
|
-
.description("显式启用后端列表(优先于上方开关;留空则用开关)"),
|
|
241
|
-
});
|
|
242
|
-
|
|
243
|
-
// 0.2.0 SettingsForms adapter (cross-settings-forms.md ruling): the 0.2.0
|
|
244
|
-
// settings service auto-generates its form from entry.fiber.runtime.Config —
|
|
245
|
-
// but volatileForm (RT dsh-settings lib/index.js:122-138) keeps ONLY fields
|
|
246
|
-
// with meta.volatile; a Config without any yields an empty form. Marking the
|
|
247
|
-
// top object makes the whole Config the form. Direct meta assignment (not
|
|
248
|
-
// .volatile(), which returns a NEW schema and throws on re-wrap) is
|
|
249
|
-
// equivalent and idempotent on both the 0.1.5 and 0.2.0 schemastery lines.
|
|
250
|
-
Config.meta = { ...Config.meta, volatile: true };
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Per-field user-language labels (fe-ui W1 remainder): the settings renderer
|
|
254
|
-
* falls back to camelCase keys when no label is present, so attach one to
|
|
255
|
-
* each v2.7 descriptor (meta.label, plus a plain .label for renderers that
|
|
256
|
-
* read the top level). Units live in the label tail (秒 / 毫秒). Whether the
|
|
257
|
-
* host actually renders them is visual-check V5; the schema layer now
|
|
258
|
-
* provides the field regardless.
|
|
259
|
-
*/
|
|
260
|
-
const FIELD_LABELS = {
|
|
261
|
-
cacheEnabled: "启用搜索结果缓存",
|
|
262
|
-
cacheTtl: "缓存有效期(秒)",
|
|
263
|
-
breakerEnabled: "后端熔断器",
|
|
264
|
-
breakerThreshold: "熔断阈值(连续失败次数)",
|
|
265
|
-
breakerCooldownMs: "熔断冷却时长(毫秒)",
|
|
266
|
-
historyEnabled: "记录搜索历史",
|
|
267
|
-
};
|
|
268
|
-
for (const [key, label] of Object.entries(FIELD_LABELS)) {
|
|
269
|
-
const sch = Config.dict?.[key];
|
|
270
|
-
if (sch) {
|
|
271
|
-
sch.meta = { ...sch.meta, label };
|
|
272
|
-
sch.label = label;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
76
|
+
/** Backends enabled by default (keyless only). */
|
|
77
|
+
const DEFAULT_ENABLED = ["exa", "parallel", "ddg", "searxng"];
|
|
275
78
|
|
|
276
79
|
/**
|
|
277
80
|
* Project one resolved settings section into the options snapshot the provider
|
|
@@ -328,6 +131,11 @@ export function resolveOptions(ctx, config) {
|
|
|
328
131
|
baseURL: config?.[`${id}BaseURL`] ?? DEFAULT_BASE_URLS[id],
|
|
329
132
|
model: config?.[`${id}Model`] ?? DEFAULT_MODELS[id],
|
|
330
133
|
...(id === "tavily" ? { searchDepth: config?.tavilySearchDepth ?? "basic" } : {}),
|
|
134
|
+
...(id === "searxng" ? {
|
|
135
|
+
baseURLs: Array.isArray(config?.searxngBaseURLs)
|
|
136
|
+
? config.searxngBaseURLs.filter((u) => typeof u === "string" && u.trim() !== "")
|
|
137
|
+
: [],
|
|
138
|
+
} : {}),
|
|
331
139
|
safeSearch: config?.safeSearch !== false,
|
|
332
140
|
label: DEFAULT_LABELS[id] ?? id,
|
|
333
141
|
requiresKey: DEFAULT_KEY_ENV[id] !== undefined,
|
package/lib/provider.js
CHANGED
|
@@ -27,6 +27,7 @@ import { cacheKeyFor } from "./cache.js";
|
|
|
27
27
|
import { foldBreaker, isCooled, cooledAnnotation } from "./breaker.js";
|
|
28
28
|
import { rrfFuse } from "./rrf.js";
|
|
29
29
|
import { isComplexQuery, deriveSubQueries } from "./multiquery.js";
|
|
30
|
+
import { failureLabel } from "./util/failure-label.js";
|
|
30
31
|
|
|
31
32
|
const PROVIDER_ID = "unified";
|
|
32
33
|
|
|
@@ -35,8 +36,13 @@ const PROVIDER_ID = "unified";
|
|
|
35
36
|
// default lets one dead backend stall the whole fan-out tail. The effective
|
|
36
37
|
// timeout is min(override, backendTimeoutMs), so an operator's shorter global
|
|
37
38
|
// timeout always wins.
|
|
39
|
+
// ddg raised 5s -> 8s in v2.8.6 (route6): a live getting-through DDG fetch
|
|
40
|
+
// through the TLS forwarder measured 7.7s, so the 5s ceiling killed slow-but-
|
|
41
|
+
// working scrapes ("ddg: timed out after 5000ms" while the page was one
|
|
42
|
+
// second away). searxng stays at 5s — searx.be answers in ~1.3s when up, and
|
|
43
|
+
// failover cooldowns make a fast fail cheaper than a long wait.
|
|
38
44
|
const BACKEND_TIMEOUT_OVERRIDES_MS = {
|
|
39
|
-
ddg:
|
|
45
|
+
ddg: 8000,
|
|
40
46
|
searxng: 5000,
|
|
41
47
|
};
|
|
42
48
|
|
|
@@ -46,6 +52,11 @@ export function effectiveBackendTimeoutMs(id, backendTimeoutMs) {
|
|
|
46
52
|
return Number.isFinite(override) ? Math.min(override, backendTimeoutMs) : backendTimeoutMs;
|
|
47
53
|
}
|
|
48
54
|
|
|
55
|
+
// All-fail error composition: how many per-backend reasons to inline before
|
|
56
|
+
// collapsing the rest into a "+N more" marker (route6: the old code silently
|
|
57
|
+
// dropped reasons 5+ and never mentioned cooled-skipped backends).
|
|
58
|
+
const MAX_FAILURE_DETAILS = 4;
|
|
59
|
+
|
|
49
60
|
// Module-level per-backend health telemetry (id -> entry), updated on every
|
|
50
61
|
// backend completion during a real search. Purely passive: nothing writes here
|
|
51
62
|
// outside search(), so the read-only /api/unified-search/health route can
|
|
@@ -334,22 +345,25 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
334
345
|
return value;
|
|
335
346
|
},
|
|
336
347
|
(err) => {
|
|
337
|
-
|
|
348
|
+
// Timeout classification happens BEFORE telemetry/health are
|
|
349
|
+
// recorded (route6 P6): backends surface an internal timeout
|
|
350
|
+
// as their own abort-flavored error ("unified search aborted",
|
|
351
|
+
// raw AbortError, …), so the old code recorded that text in
|
|
352
|
+
// the telemetry line and health payload even though the final
|
|
353
|
+
// thrown error said "timed out after Nms" — the two disagreed
|
|
354
|
+
// and "(unified search aborted)" read as if the USER cancelled.
|
|
355
|
+
const timedOut = controller.signal.aborted && !(signal && signal.aborted);
|
|
356
|
+
const reason = timedOut
|
|
357
|
+
? `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
|
|
358
|
+
: String(err instanceof Error ? err.message : err);
|
|
359
|
+
const msg = reason.slice(0, 80);
|
|
338
360
|
telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
|
|
339
361
|
recordBackendHealth(id, { ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg }, breakerCfg);
|
|
340
|
-
throw
|
|
362
|
+
throw timedOut
|
|
363
|
+
? new WebError(reason, "WEB_PROVIDER_ERROR", { cause: err instanceof Error ? err : undefined })
|
|
364
|
+
: err;
|
|
341
365
|
},
|
|
342
366
|
)
|
|
343
|
-
.catch((err) => {
|
|
344
|
-
if (controller.signal.aborted && !(signal && signal.aborted)) {
|
|
345
|
-
throw new WebError(
|
|
346
|
-
`backend "${id}" timed out after ${effectiveTimeoutMs}ms`,
|
|
347
|
-
"WEB_PROVIDER_ERROR",
|
|
348
|
-
{ cause: err instanceof Error ? err : undefined },
|
|
349
|
-
);
|
|
350
|
-
}
|
|
351
|
-
throw err;
|
|
352
|
-
})
|
|
353
367
|
.finally(() => clearTimeout(timeoutId));
|
|
354
368
|
};
|
|
355
369
|
|
|
@@ -435,9 +449,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
435
449
|
}
|
|
436
450
|
// Multi-query fans every variant through every backend; cap the line
|
|
437
451
|
// so the telemetry note cannot dwarf the results themselves.
|
|
452
|
+
// Failure notes translate known classes into short user-facing
|
|
453
|
+
// labels (route6 P2); the raw text remains the fallback, and a
|
|
454
|
+
// backend that just crossed the breaker threshold is annotated as
|
|
455
|
+
// cooled on this same line.
|
|
438
456
|
const parts = allTelemetry
|
|
439
457
|
.slice(0, 12)
|
|
440
|
-
.map((t) =>
|
|
458
|
+
.map((t) => {
|
|
459
|
+
if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
|
|
460
|
+
const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
|
|
461
|
+
const cooledNow = cooledAnnotation(latestBackendHealth.get(t.id), Date.now());
|
|
462
|
+
return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "") + (cooledNow ? " " + cooledNow : "");
|
|
463
|
+
})
|
|
441
464
|
.concat(cooledParts);
|
|
442
465
|
if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
|
|
443
466
|
const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
|
|
@@ -475,19 +498,25 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
475
498
|
};
|
|
476
499
|
}
|
|
477
500
|
|
|
478
|
-
// All
|
|
501
|
+
// All attempted backends failed - synthesize one meaningful error that
|
|
479
502
|
// names each backend's own reason so the caller (model or user) can act.
|
|
480
|
-
|
|
503
|
+
// Reasons beyond MAX_FAILURE_DETAILS collapse into "+N more"; backends
|
|
504
|
+
// that never ran (breaker cooldown) are named explicitly — without the
|
|
505
|
+
// note "(N)" reads as "N enabled" when it means "N attempted" (route6).
|
|
506
|
+
const detail = allFailures.slice(0, MAX_FAILURE_DETAILS)
|
|
481
507
|
.map((f) => f.id + ": " + String(f.err instanceof Error ? f.err.message : f.err).slice(0, 120))
|
|
482
|
-
.join("; ");
|
|
508
|
+
.join("; ") + (allFailures.length > MAX_FAILURE_DETAILS ? `; +${allFailures.length - MAX_FAILURE_DETAILS} more` : "");
|
|
483
509
|
const allKeyMissing =
|
|
484
510
|
allFailures.length > 0 &&
|
|
485
511
|
allFailures.every((f) => f.err instanceof WebError && (f.err.code === "WEB_PROVIDER_UNAVAILABLE" || f.err.code === "WEB_PROVIDER_CREDENTIAL_MISSING"));
|
|
486
512
|
const hint = allKeyMissing
|
|
487
513
|
? " (every enabled backend is missing its API key - add keys in Settings > Web Search, or enable a keyless backend)"
|
|
488
514
|
: "";
|
|
515
|
+
const cooledNote = cooled.size > 0
|
|
516
|
+
? " (cooled-skipped: " + [...cooled].map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, Date.now()) || "⏸cooled")).join(", ") + ")"
|
|
517
|
+
: "";
|
|
489
518
|
throw new WebError(
|
|
490
|
-
`unified search: all enabled backends failed (${allFailures.length}) - ${detail}` + hint,
|
|
519
|
+
`unified search: all enabled backends failed (${allFailures.length}) - ${detail}` + cooledNote + hint,
|
|
491
520
|
"WEB_PROVIDER_ERROR",
|
|
492
521
|
{ cause: hardError ?? undefined },
|
|
493
522
|
);
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// util/describe-error.js — cause-chain-aware one-line error description.
|
|
2
|
+
//
|
|
3
|
+
// Native fetch (undici, including the EnvHttpProxyAgent / ProxyAgent paths a
|
|
4
|
+
// harness may install as its global dispatcher) reports the actionable
|
|
5
|
+
// failure — getaddrinfo ENOTFOUND, ECONNREFUSED, proxy CONNECT failure, TLS
|
|
6
|
+
// error, timeout — on `error.cause`, while String(error) yields a bare
|
|
7
|
+
// "TypeError: fetch failed". Failure wrappers that interpolate the bare form
|
|
8
|
+
// leave the model/user unable to tell "DNS dead" from "proxy rejected" from
|
|
9
|
+
// "sidecar stalled". This helper walks the cause chain (bounded depth and
|
|
10
|
+
// length) and joins it into one line so the detail survives into mcp-client
|
|
11
|
+
// wraps, backend wraps, the provider's all-fail enumeration, the telemetry
|
|
12
|
+
// line and the health payload.
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_DEPTH = 3;
|
|
15
|
+
const DEFAULT_MAX_LEN = 220;
|
|
16
|
+
|
|
17
|
+
/** One-line description of `error`, following up to maxDepth causes. */
|
|
18
|
+
export function describeError(error, options = {}) {
|
|
19
|
+
const maxDepth = Number.isFinite(options.maxDepth) ? Math.max(0, options.maxDepth) : DEFAULT_MAX_DEPTH;
|
|
20
|
+
const maxLen = Number.isFinite(options.maxLen) ? Math.max(40, options.maxLen) : DEFAULT_MAX_LEN;
|
|
21
|
+
const parts = [];
|
|
22
|
+
let current = error;
|
|
23
|
+
for (let depth = 0; current !== undefined && current !== null && depth <= maxDepth; depth++) {
|
|
24
|
+
const text = oneLiner(current);
|
|
25
|
+
if (text !== "" && parts[parts.length - 1] !== text) parts.push(text);
|
|
26
|
+
// undici sometimes aggregates several socket errors under one cause;
|
|
27
|
+
// surface up to two of them instead of a useless "AggregateError: []".
|
|
28
|
+
if (current instanceof AggregateError && Array.isArray(current.errors) && current.errors.length > 0) {
|
|
29
|
+
for (const sub of current.errors.slice(0, 2)) {
|
|
30
|
+
const subText = oneLiner(sub);
|
|
31
|
+
if (subText !== "" && !parts.includes(subText)) parts.push(subText);
|
|
32
|
+
}
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
current = current?.cause;
|
|
36
|
+
}
|
|
37
|
+
if (parts.length === 0) return "";
|
|
38
|
+
let out = parts[0];
|
|
39
|
+
if (parts.length > 1) out += " (cause: " + parts.slice(1).join(" <- ") + ")";
|
|
40
|
+
return out.length > maxLen ? out.slice(0, maxLen - 1) + "…" : out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function oneLiner(value) {
|
|
44
|
+
let text;
|
|
45
|
+
if (value instanceof Error) {
|
|
46
|
+
const name = value.name && value.name !== "Error" ? value.name + ": " : "";
|
|
47
|
+
const message = String(value.message ?? "");
|
|
48
|
+
// Keep the errno-style code when the message does not already carry it
|
|
49
|
+
// (e.g. code ENOTFOUND with message "fetch failed"). Only E*/UND_ERR_*
|
|
50
|
+
// codes qualify — host error codes like "WEB_PROVIDER_ERROR" are
|
|
51
|
+
// transport metadata, not message text.
|
|
52
|
+
const codeOk = typeof value.code === "string" && /^(E[A-Z_]+|UND_ERR_[A-Z_]+)$/.test(value.code) && !message.includes(value.code);
|
|
53
|
+
text = name + (codeOk ? value.code + " " : "") + message;
|
|
54
|
+
} else {
|
|
55
|
+
text = String(value);
|
|
56
|
+
}
|
|
57
|
+
return text.replace(/\s+/g, " ").trim();
|
|
58
|
+
}
|
package/lib/util/egress-fetch.js
CHANGED
|
@@ -141,31 +141,36 @@ async function tunneledFetch(url, init, proxy, depth) {
|
|
|
141
141
|
/**
|
|
142
142
|
* Relay through the TLS-egress sidecar: POST /fwd with an
|
|
143
143
|
* x-sidecar-spec base64 JSON header; the sidecar performs the upstream
|
|
144
|
-
* request with its own (Chromium) TLS stack and
|
|
145
|
-
* status/headers/body
|
|
144
|
+
* request with its own (Chromium) TLS stack and returns the upstream
|
|
145
|
+
* status/headers/body verbatim. Upstream dial failures surface as
|
|
146
146
|
* 502 + x-sidecar-error, which we rethrow as fetch-style TypeError.
|
|
147
|
+
*
|
|
148
|
+
* proxy-exempt: this hop must own its transport (node:http(s)) by design —
|
|
149
|
+
* hosts install a global dispatcher (e.g. an HTTP_PROXY-wired
|
|
150
|
+
* EnvHttpProxyAgent); routing this hop through it would send the sidecar
|
|
151
|
+
* request into the very proxy chain the sidecar fronts, and with the
|
|
152
|
+
* sidecar host missing from NO_PROXY it dies there (observed as
|
|
153
|
+
* "dial HK -> sidecar ... EOF" in the proxy log). The proxy decision for
|
|
154
|
+
* the *upstream* request rides in the sidecar spec
|
|
155
|
+
* (DSH_EGRESS_FORWARDER_PROXY), not in this hop.
|
|
156
|
+
*
|
|
157
|
+
* A forwarder-level ceiling bounds the hop even when the sidecar accepts
|
|
158
|
+
* connections but stops responding (half-dead process): the effective
|
|
159
|
+
* limit is min(caller signal, DSH_EGRESS_FORWARDER_TIMEOUT_MS ?? 20s).
|
|
147
160
|
*/
|
|
148
161
|
async function forwarderFetch(url, init, forwarder) {
|
|
149
162
|
const method = String(init.method ?? "GET").toUpperCase();
|
|
150
163
|
const headers = normalizeHeaders(init.headers);
|
|
151
164
|
const body = normalizeBody(init.body);
|
|
152
|
-
const
|
|
165
|
+
const timeoutMs = forwarderTimeoutMs();
|
|
166
|
+
const callerSignal = init.signal;
|
|
167
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
168
|
+
const signal = callerSignal !== undefined ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
|
|
169
|
+
const spec = { url, method, headers, timeout_ms: timeoutMs };
|
|
153
170
|
if (forwarder.proxy !== undefined) spec.proxy = forwarder.proxy;
|
|
154
171
|
if (init.redirect !== undefined) spec.redirect = init.redirect;
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
response = await fetch(forwarder.endpoint, {
|
|
158
|
-
method: "POST",
|
|
159
|
-
headers: {
|
|
160
|
-
"content-type": "application/octet-stream",
|
|
161
|
-
"x-sidecar-spec": Buffer.from(JSON.stringify(spec)).toString("base64"),
|
|
162
|
-
},
|
|
163
|
-
...(body !== undefined ? { body } : {}),
|
|
164
|
-
...(init.signal !== undefined ? { signal: init.signal } : {}),
|
|
165
|
-
});
|
|
166
|
-
} catch (error) {
|
|
167
|
-
throw new TypeError(`fetch failed: forwarder unreachable (${sanitize(error)})`, { cause: error });
|
|
168
|
-
}
|
|
172
|
+
throwIfAborted(signal);
|
|
173
|
+
const response = await forwarderExchange(forwarder.endpoint, spec, body, signal, callerSignal, timeoutSignal, timeoutMs);
|
|
169
174
|
const marker = response.headers.get("x-sidecar-error");
|
|
170
175
|
if (response.status === 502 && marker !== null) {
|
|
171
176
|
let detail = "";
|
|
@@ -175,6 +180,64 @@ async function forwarderFetch(url, init, forwarder) {
|
|
|
175
180
|
return response;
|
|
176
181
|
}
|
|
177
182
|
|
|
183
|
+
const DEFAULT_FORWARDER_TIMEOUT_MS = 20_000;
|
|
184
|
+
|
|
185
|
+
/** Forwarder-hop ceiling; DSH_EGRESS_FORWARDER_TIMEOUT_MS overrides (tests/rescue). */
|
|
186
|
+
export function forwarderTimeoutMs() {
|
|
187
|
+
const n = Number(process.env.DSH_EGRESS_FORWARDER_TIMEOUT_MS);
|
|
188
|
+
return Number.isFinite(n) && n > 0 ? n : DEFAULT_FORWARDER_TIMEOUT_MS;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* The sidecar exchange over node:http(s). Failure mapping priority:
|
|
193
|
+
* 1. caller signal aborted -> the caller's own abort reason;
|
|
194
|
+
* 2. forwarder timeout fired -> "did not respond ... (sidecar stalled?)";
|
|
195
|
+
* 3. otherwise -> "unreachable (<cause chain>)".
|
|
196
|
+
*/
|
|
197
|
+
function forwarderExchange(endpoint, spec, body, signal, callerSignal, timeoutSignal, timeoutMs) {
|
|
198
|
+
const target = new URL(endpoint);
|
|
199
|
+
const secure = target.protocol === "https:";
|
|
200
|
+
const transport = secure ? https : http;
|
|
201
|
+
const headers = {
|
|
202
|
+
"content-type": "application/octet-stream",
|
|
203
|
+
"x-sidecar-spec": Buffer.from(JSON.stringify(spec)).toString("base64"),
|
|
204
|
+
};
|
|
205
|
+
if (body !== undefined) headers["content-length"] = String(body.length);
|
|
206
|
+
return new Promise((resolve, reject) => {
|
|
207
|
+
let settled = false;
|
|
208
|
+
const fail = (error) => {
|
|
209
|
+
if (settled) return;
|
|
210
|
+
settled = true;
|
|
211
|
+
if (callerSignal?.aborted === true) {
|
|
212
|
+
reject(abortReason(callerSignal));
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (timeoutSignal.aborted === true) {
|
|
216
|
+
reject(new TypeError(`fetch failed: forwarder did not respond within ${timeoutMs}ms (sidecar stalled?)`, { cause: error }));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
reject(new TypeError(`fetch failed: forwarder unreachable (${sanitize(error)})`, { cause: error }));
|
|
220
|
+
};
|
|
221
|
+
const request = transport.request({
|
|
222
|
+
host: target.hostname,
|
|
223
|
+
port: target.port !== "" ? Number(target.port) : secure ? 443 : 80,
|
|
224
|
+
method: "POST",
|
|
225
|
+
path: target.pathname + target.search,
|
|
226
|
+
headers,
|
|
227
|
+
signal,
|
|
228
|
+
});
|
|
229
|
+
request.on("error", fail);
|
|
230
|
+
request.on("response", (res) => {
|
|
231
|
+
collect(res).then((response) => {
|
|
232
|
+
if (settled) return;
|
|
233
|
+
settled = true;
|
|
234
|
+
resolve(response);
|
|
235
|
+
}, fail);
|
|
236
|
+
});
|
|
237
|
+
request.end(body);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
178
241
|
/* ------------------------------------------------------------------ */
|
|
179
242
|
/* transports */
|
|
180
243
|
/* ------------------------------------------------------------------ */
|
|
@@ -389,9 +452,20 @@ function abortReason(signal) {
|
|
|
389
452
|
return signal?.reason !== undefined ? signal.reason : new DOMException("This operation was aborted", "AbortError");
|
|
390
453
|
}
|
|
391
454
|
|
|
455
|
+
// One-line description including the cause chain: undici hides the real
|
|
456
|
+
// failure (proxy CONNECT rejection / ECONNREFUSED / ENOTFOUND / TLS / proxy
|
|
457
|
+
// 502) behind a bare "fetch failed"; message-only sanitizing would drop it.
|
|
392
458
|
function sanitize(error) {
|
|
393
|
-
const
|
|
394
|
-
|
|
459
|
+
const parts = [];
|
|
460
|
+
let current = error;
|
|
461
|
+
for (let depth = 0; current !== undefined && current !== null && depth < 3; depth++) {
|
|
462
|
+
const raw = current instanceof Error && current.message ? String(current.message) : String(current);
|
|
463
|
+
const text = raw.replace(/\s+/g, " ").trim();
|
|
464
|
+
if (text !== "" && parts[parts.length - 1] !== text) parts.push(text);
|
|
465
|
+
current = current?.cause;
|
|
466
|
+
}
|
|
467
|
+
const out = parts.length === 0 ? String(error) : parts.join(" <- ");
|
|
468
|
+
return out.slice(0, 200);
|
|
395
469
|
}
|
|
396
470
|
|
|
397
471
|
async function drain(response) {
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// util/failure-label.js — short user-facing classification of a backend
|
|
2
|
+
// failure for the telemetry line ("[websearch backends] ... searxng ✗...").
|
|
3
|
+
//
|
|
4
|
+
// The raw reason stays the machine-facing truth (all-fail error, health
|
|
5
|
+
// payload); the telemetry line is what the model/user reads next to results,
|
|
6
|
+
// where "SearXNG: invalid JSON response" reads like a plugin bug while it
|
|
7
|
+
// actually means "the instance served an anti-bot page" (route3/route6).
|
|
8
|
+
// Pure and zero-dep: returns undefined when no confident class matches, so
|
|
9
|
+
// the caller keeps the raw text as fallback.
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {string} id backend id (searxng gets a dedicated phrasing)
|
|
13
|
+
* @param {string} raw failure message (already truncated by the caller)
|
|
14
|
+
* @returns {string|undefined} short label, or undefined to keep the raw text
|
|
15
|
+
*/
|
|
16
|
+
export function failureLabel(id, raw) {
|
|
17
|
+
const m = String(raw ?? "");
|
|
18
|
+
if (m === "") return undefined;
|
|
19
|
+
if (/(invalid JSON|anti-bot|not a bot|antibot|captcha|challenge page|verifying your browser)/i.test(m)) {
|
|
20
|
+
return id === "searxng"
|
|
21
|
+
? "instance degraded (anti-bot/non-JSON page)"
|
|
22
|
+
: "non-JSON response (bot wall?)";
|
|
23
|
+
}
|
|
24
|
+
if (/timed out after \d+ms/.test(m)) return "timeout (network slow/blocked)";
|
|
25
|
+
// Proxy/forwarder-path failures get their own class: the route5 incident
|
|
26
|
+
// (harness EnvHttpProxyAgent hijacking the sidecar request) surfaced as a
|
|
27
|
+
// generic "fetch failed", pointing the reader at DNS/TLS when the actual
|
|
28
|
+
// fault was the proxy/egress hop.
|
|
29
|
+
if (/(proxy|tunnel|forwarder|CONNECT)/i.test(m)) return "proxy/forwarder path failed";
|
|
30
|
+
if (/(fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EPIPE|socket hang up)/i.test(m)) {
|
|
31
|
+
return "network unreachable (DNS/TCP/TLS)";
|
|
32
|
+
}
|
|
33
|
+
if (/HTTP 429|Too Many Requests|rate.?limit/i.test(m)) return "rate-limited (HTTP 429)";
|
|
34
|
+
const s5 = /HTTP (5\d\d)/.exec(m);
|
|
35
|
+
if (s5) return "server error (HTTP " + s5[1] + ")";
|
|
36
|
+
const s4 = /HTTP (40[13]|\b403\b)/.exec(m);
|
|
37
|
+
if (s4) return "blocked (HTTP " + s4[1] + ")";
|
|
38
|
+
if (/lacks a results\[\] array|not a SearXNG API/.test(m)) return "unexpected API shape";
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
package/lib/util/mcp-client.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
9
9
|
import { egressFetch } from "./egress-fetch.js";
|
|
10
|
+
import { describeError } from "./describe-error.js";
|
|
10
11
|
|
|
11
12
|
const UA = "dsh-websearch/2.3";
|
|
12
13
|
const PROTOCOL_VERSION = "2025-06-18";
|
|
@@ -55,7 +56,10 @@ async function ensureSession(url, signal) {
|
|
|
55
56
|
});
|
|
56
57
|
} catch (error) {
|
|
57
58
|
if (signal?.aborted) throw error;
|
|
58
|
-
|
|
59
|
+
// describeError (not `${error}`): undici puts the actionable failure —
|
|
60
|
+
// proxy rejection / ENOTFOUND / TLS / timeout — on error.cause; the bare
|
|
61
|
+
// form would only say "TypeError: fetch failed" (route6 audit).
|
|
62
|
+
throw new WebError(`MCP initialize failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
if (!initResponse.ok) {
|
|
@@ -177,7 +181,7 @@ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
|
|
|
177
181
|
});
|
|
178
182
|
} catch (error) {
|
|
179
183
|
if (signal?.aborted) throw error;
|
|
180
|
-
throw new WebError(`MCP tools/call failed: ${error}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
184
|
+
throw new WebError(`MCP tools/call failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
181
185
|
}
|
|
182
186
|
|
|
183
187
|
// On 401/403/404 with a sessionful server, invalidate and retry once.
|
|
@@ -202,7 +206,7 @@ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
|
|
|
202
206
|
});
|
|
203
207
|
} catch (error) {
|
|
204
208
|
if (signal?.aborted) throw error;
|
|
205
|
-
throw new WebError(`MCP tools/call retry failed: ${error}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
209
|
+
throw new WebError(`MCP tools/call retry failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
206
210
|
}
|
|
207
211
|
}
|
|
208
212
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@240xu/dsh-websearch",
|
|
3
|
-
"version": "2.8.
|
|
3
|
+
"version": "2.8.7",
|
|
4
4
|
"description": "Unified web search provider for DeepSeek Harness (ctx.web): 11 backends — Exa + Parallel + DDG + SearXNG (keyless), DeepSeek + Anthropic + OpenAI + Brave + Tavily + Serper + Mojeek (key-gated via Settings credentials). Registers provider id \"unified\" for zero-config web_search. 统一网页搜索聚合:11 后端并发扇出、去重合并,零依赖。See CHANGELOG.md for version history.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"default": "./lib/index.js"
|
|
10
10
|
},
|
|
11
11
|
"./package.json": "./package.json",
|
|
12
|
-
"./client": "./lib/client.js"
|
|
12
|
+
"./client": "./lib/client.js",
|
|
13
|
+
"./config": "./lib/config.js"
|
|
13
14
|
},
|
|
14
15
|
"files": [
|
|
15
16
|
"lib",
|