@240xu/dsh-websearch 2.8.4 → 2.8.6
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 +9 -7
- package/lib/backends/exa.js +2 -1
- package/lib/backends/parallel.js +2 -1
- package/lib/backends/searxng.js +162 -59
- package/lib/index.js +7 -0
- package/lib/provider.js +47 -18
- package/lib/util/describe-error.js +58 -0
- package/lib/util/egress-fetch.js +142 -3
- package/lib/util/failure-label.js +40 -0
- package/lib/util/mcp-client.js +7 -3
- package/package.json +1 -1
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
|
|
|
@@ -30,20 +31,21 @@ export const ddgBackend = {
|
|
|
30
31
|
throwIfSearchAborted(signal);
|
|
31
32
|
const params = new URLSearchParams({ q: request.query, b: Math.random().toString().slice(2) });
|
|
32
33
|
applyDdgFilters(params, normalizeFilters(request.filters));
|
|
33
|
-
const
|
|
34
|
+
const target = `${DDG_ENDPOINT}?${params.toString()}`;
|
|
34
35
|
hooks.recordRequest?.({ endpoint: DDG_ENDPOINT, toolName: "html", body: { q: request.query }, headers: {} });
|
|
35
36
|
|
|
36
37
|
let text;
|
|
37
38
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
// GET form: DDG's html endpoint still serves the same results page, and
|
|
40
|
+
// unlike the POST form it is not rejected by the endpoint's bot wall
|
|
41
|
+
// for non-browser clients (POST is JA3 + method double-gated).
|
|
42
|
+
const res = await egressFetch(target, {
|
|
43
|
+
method: "GET",
|
|
40
44
|
redirect: "error",
|
|
41
45
|
headers: {
|
|
42
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
43
46
|
"Accept": "text/html",
|
|
44
47
|
"User-Agent": "dsh-websearch/2.3",
|
|
45
48
|
},
|
|
46
|
-
body,
|
|
47
49
|
...(signal !== undefined ? { signal } : {}),
|
|
48
50
|
});
|
|
49
51
|
if (!res.ok) {
|
|
@@ -54,9 +56,9 @@ export const ddgBackend = {
|
|
|
54
56
|
text = await res.text();
|
|
55
57
|
} catch (err) {
|
|
56
58
|
if (signal?.aborted === true || isAbortError(err)) throw searchAborted(signal, err);
|
|
57
|
-
hooks.recordOutcome?.({ status: "error", message:
|
|
59
|
+
hooks.recordOutcome?.({ status: "error", message: describeError(err) });
|
|
58
60
|
throw new WebError(
|
|
59
|
-
`ddg search failed: ${
|
|
61
|
+
`ddg search failed: ${describeError(err)}`,
|
|
60
62
|
"WEB_PROVIDER_ERROR",
|
|
61
63
|
{ cause: err },
|
|
62
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/index.js
CHANGED
|
@@ -218,6 +218,8 @@ export const Config = z.object({
|
|
|
218
218
|
.description("Mojeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
219
219
|
searxngBaseURL: z.string().default(DEFAULT_BASE_URLS.searxng)
|
|
220
220
|
.description("SearXNG API 端点(默认官方;自托管/代理实例改此项)"),
|
|
221
|
+
searxngBaseURLs: z.array(z.string()).default([])
|
|
222
|
+
.description("SearXNG 备用实例列表(可选;主实例失败时按序尝试,失败实例冷却 10 分钟)"),
|
|
221
223
|
deepseekBaseURL: z.string().default(DEFAULT_BASE_URLS.deepseek)
|
|
222
224
|
.description("DeepSeek API 端点(默认官方;自托管/代理实例改此项)"),
|
|
223
225
|
anthropicBaseURL: z.string().default(DEFAULT_BASE_URLS.anthropic)
|
|
@@ -328,6 +330,11 @@ export function resolveOptions(ctx, config) {
|
|
|
328
330
|
baseURL: config?.[`${id}BaseURL`] ?? DEFAULT_BASE_URLS[id],
|
|
329
331
|
model: config?.[`${id}Model`] ?? DEFAULT_MODELS[id],
|
|
330
332
|
...(id === "tavily" ? { searchDepth: config?.tavilySearchDepth ?? "basic" } : {}),
|
|
333
|
+
...(id === "searxng" ? {
|
|
334
|
+
baseURLs: Array.isArray(config?.searxngBaseURLs)
|
|
335
|
+
? config.searxngBaseURLs.filter((u) => typeof u === "string" && u.trim() !== "")
|
|
336
|
+
: [],
|
|
337
|
+
} : {}),
|
|
331
338
|
safeSearch: config?.safeSearch !== false,
|
|
332
339
|
label: DEFAULT_LABELS[id] ?? id,
|
|
333
340
|
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
|
@@ -10,6 +10,14 @@
|
|
|
10
10
|
//
|
|
11
11
|
// When no matching proxy env is set, or the target host sits in NO_PROXY, it
|
|
12
12
|
// defers to the native fetch, so behavior everywhere else is unchanged.
|
|
13
|
+
//
|
|
14
|
+
// Optional TLS-egress forwarder: when DSH_EGRESS_FORWARDER is set (a local
|
|
15
|
+
// sidecar exposing a POST /fwd API backed by a Chromium TLS stack), requests
|
|
16
|
+
// are relayed through it with the upstream proxy carried in the sidecar spec
|
|
17
|
+
// (DSH_EGRESS_FORWARDER_PROXY, defaulting to HTTPS_PROXY). This exists because
|
|
18
|
+
// some upstreams (Exa, DuckDuckGo) gate on the client TLS fingerprint (JA3)
|
|
19
|
+
// rather than on the exit IP; the Node TLS fingerprint is rejected where a
|
|
20
|
+
// real browser's is accepted. Unset the env and behavior is byte-identical.
|
|
13
21
|
|
|
14
22
|
import http from "node:http";
|
|
15
23
|
import https from "node:https";
|
|
@@ -17,13 +25,33 @@ import https from "node:https";
|
|
|
17
25
|
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
|
|
18
26
|
const MAX_REDIRECTS = 5;
|
|
19
27
|
|
|
20
|
-
/** fetch-compatible entry:
|
|
28
|
+
/** fetch-compatible entry: forwarder first, then HTTPS_PROXY/HTTP_PROXY tunnel. */
|
|
21
29
|
export function egressFetch(url, init = {}) {
|
|
30
|
+
const forwarder = forwarderFor(url);
|
|
31
|
+
if (forwarder !== undefined) return forwarderFetch(String(url), init, forwarder);
|
|
22
32
|
const proxy = proxyFor(url);
|
|
23
33
|
if (proxy === undefined) return fetch(url, init);
|
|
24
34
|
return tunneledFetch(String(url), init, proxy, 0);
|
|
25
35
|
}
|
|
26
36
|
|
|
37
|
+
/** Resolve the TLS-egress forwarder for a request target (NO_PROXY aware). */
|
|
38
|
+
function forwarderFor(url) {
|
|
39
|
+
let target;
|
|
40
|
+
try {
|
|
41
|
+
target = new URL(String(url));
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
if (target.protocol !== "https:" && target.protocol !== "http:") return undefined;
|
|
46
|
+
const env = process.env;
|
|
47
|
+
const endpoint = env.DSH_EGRESS_FORWARDER;
|
|
48
|
+
if (endpoint === undefined || endpoint === "") return undefined;
|
|
49
|
+
if (inNoProxy(target, env.NO_PROXY || env.no_proxy)) return undefined;
|
|
50
|
+
const proxy = env.DSH_EGRESS_FORWARDER_PROXY
|
|
51
|
+
|| env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy || "";
|
|
52
|
+
return { endpoint, proxy: proxy === "" ? undefined : proxy };
|
|
53
|
+
}
|
|
54
|
+
|
|
27
55
|
/** Resolve the proxy URL for a request target (NO_PROXY aware). */
|
|
28
56
|
function proxyFor(url) {
|
|
29
57
|
let target;
|
|
@@ -110,6 +138,106 @@ async function tunneledFetch(url, init, proxy, depth) {
|
|
|
110
138
|
return response;
|
|
111
139
|
}
|
|
112
140
|
|
|
141
|
+
/**
|
|
142
|
+
* Relay through the TLS-egress sidecar: POST /fwd with an
|
|
143
|
+
* x-sidecar-spec base64 JSON header; the sidecar performs the upstream
|
|
144
|
+
* request with its own (Chromium) TLS stack and returns the upstream
|
|
145
|
+
* status/headers/body verbatim. Upstream dial failures surface as
|
|
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).
|
|
160
|
+
*/
|
|
161
|
+
async function forwarderFetch(url, init, forwarder) {
|
|
162
|
+
const method = String(init.method ?? "GET").toUpperCase();
|
|
163
|
+
const headers = normalizeHeaders(init.headers);
|
|
164
|
+
const body = normalizeBody(init.body);
|
|
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 };
|
|
170
|
+
if (forwarder.proxy !== undefined) spec.proxy = forwarder.proxy;
|
|
171
|
+
if (init.redirect !== undefined) spec.redirect = init.redirect;
|
|
172
|
+
throwIfAborted(signal);
|
|
173
|
+
const response = await forwarderExchange(forwarder.endpoint, spec, body, signal, callerSignal, timeoutSignal, timeoutMs);
|
|
174
|
+
const marker = response.headers.get("x-sidecar-error");
|
|
175
|
+
if (response.status === 502 && marker !== null) {
|
|
176
|
+
let detail = "";
|
|
177
|
+
try { detail = (await response.text()).slice(0, 200); } catch {}
|
|
178
|
+
throw new TypeError(`fetch failed: forwarder ${marker}${detail !== "" ? ` (${detail})` : ""}`);
|
|
179
|
+
}
|
|
180
|
+
return response;
|
|
181
|
+
}
|
|
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
|
+
|
|
113
241
|
/* ------------------------------------------------------------------ */
|
|
114
242
|
/* transports */
|
|
115
243
|
/* ------------------------------------------------------------------ */
|
|
@@ -324,9 +452,20 @@ function abortReason(signal) {
|
|
|
324
452
|
return signal?.reason !== undefined ? signal.reason : new DOMException("This operation was aborted", "AbortError");
|
|
325
453
|
}
|
|
326
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.
|
|
327
458
|
function sanitize(error) {
|
|
328
|
-
const
|
|
329
|
-
|
|
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);
|
|
330
469
|
}
|
|
331
470
|
|
|
332
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.6",
|
|
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",
|