@240xu/dsh-websearch 2.10.0 → 2.12.0
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 +9 -6
- package/lib/backends/anthropic-like.js +9 -5
- package/lib/backends/openai.js +5 -3
- package/lib/backends/parallel.js +5 -1
- package/lib/backends/searxng.js +62 -13
- package/lib/cache.js +3 -2
- package/lib/client.js +18 -8
- package/lib/health.js +1 -0
- package/lib/history.js +2 -1
- package/lib/index.js +28 -12
- package/lib/provider.js +70 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -92,7 +92,7 @@ pnpm install
|
|
|
92
92
|
> 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
|
|
93
93
|
|
|
94
94
|
|
|
95
|
-
插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑
|
|
95
|
+
插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 26 个开关/参数(共 60 个配置字段);缓存、熔断、历史、多查询、域名过滤、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 Config 表单 / profile patch 配置:
|
|
96
96
|
|
|
97
97
|
**全局**
|
|
98
98
|
|
|
@@ -100,8 +100,8 @@ pnpm install
|
|
|
100
100
|
|---|---|---|
|
|
101
101
|
| `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
|
|
102
102
|
| `numResults` | 10 | 每次搜索返回结果数(1-100;Exa 上限 100,official 档沿用宿主工具的条数上限) |
|
|
103
|
-
| `includeDomains` | 空 |
|
|
104
|
-
| `excludeDomains` | 空 | 排除这些域名(最多 20
|
|
103
|
+
| `includeDomains` | 空 | 仅约束 OpenAI/Anthropic 原生后端(最多 20;其余后端不支持,合并结果仍可能来自其他域名) |
|
|
104
|
+
| `excludeDomains` | 空 | 排除这些域名(最多 20;Anthropic 仅发 allow,OpenAI 两个列表同时发送) |
|
|
105
105
|
| `concurrency` | 6 | 并发后端数(1-10) |
|
|
106
106
|
| `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
|
|
107
107
|
| `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
|
|
@@ -172,6 +172,7 @@ pnpm install
|
|
|
172
172
|
|
|
173
173
|
### 4. per-backend 超时上限(P2)
|
|
174
174
|
|
|
175
|
+
- SearXNG 仅在 `thorough`/`deepCoverage` 且未开启内部多查询时翻第 2 页(单实例;第 2 页 429/5xx 会回退到第 1 页并冷却 60 秒);多实例 failover 始终只取第 1 页。
|
|
175
176
|
- `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
|
|
176
177
|
|
|
177
178
|
## v2.7.3 兼容修复 | What's new in v2.7.3
|
|
@@ -205,7 +206,9 @@ pnpm install
|
|
|
205
206
|
- 相同 **(整形后查询 + filters + maxResults + 启用后端集合)** 在 TTL 内直接命中缓存,不打任何后端;`sources` 与首次搜索完全一致。
|
|
206
207
|
- 命中时 `content` 追加一行 `[websearch cache] cache hit, age Ns`。
|
|
207
208
|
- 存储位置:`$DSH_HOME/cache/websearch/results/`,单条目一个 JSON 文件,tmp+rename 原子写,超出上限按最旧淘汰;任何 fs 错误都被吞掉,缓存坏了绝不影响搜索。
|
|
208
|
-
- 设置:`cacheEnabled`(默认 true)、`cacheTtl`(秒,默认 900
|
|
209
|
+
- 设置:`cacheEnabled`(默认 true)、`cacheTtl`(秒,默认 900;**0 = no-store**,不读也不写)。
|
|
210
|
+
- 上限 200 条,超出按 mtime 最旧淘汰;缓存目录 0700、文件 0600(查询与结果属于用户数据)。
|
|
211
|
+
- 清理:`rm -rf $DSH_HOME/cache/websearch/results`(`DSH_HOME` 通常为 `~/.dsh`)。
|
|
209
212
|
|
|
210
213
|
### 2. 后端熔断器(默认开,保守阈值)
|
|
211
214
|
|
|
@@ -266,7 +269,7 @@ tests/
|
|
|
266
269
|
node --test tests/
|
|
267
270
|
```
|
|
268
271
|
|
|
269
|
-
当前
|
|
272
|
+
当前 225/225 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
|
|
270
273
|
|
|
271
274
|
### Test-only dependencies
|
|
272
275
|
|
|
@@ -279,7 +282,7 @@ live service before running the suite:
|
|
|
279
282
|
```bash
|
|
280
283
|
bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
|
|
281
284
|
find node_modules/@deepseek-ai -xtype l # expect no output
|
|
282
|
-
node --test tests/*.test.js #
|
|
285
|
+
node --test tests/*.test.js # 225/225
|
|
283
286
|
```
|
|
284
287
|
|
|
285
288
|
v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
|
|
@@ -86,11 +86,15 @@ export function createAnthropicLikeBackend(spec) {
|
|
|
86
86
|
const maxUses = options.maxUses ?? 5;
|
|
87
87
|
const endpoint = `${baseURL.replace(/\/$/, "")}/messages`;
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
89
|
+
// Only the Anthropic route has a probed domain-filter contract; the
|
|
90
|
+
// DeepSeek-compatible route shares this factory but has not been probed.
|
|
91
|
+
const domainArgs = id !== "anthropic"
|
|
92
|
+
? {}
|
|
93
|
+
: Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
|
|
94
|
+
? { allowed_domains: options.includeDomains }
|
|
95
|
+
: Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
|
|
96
|
+
? { blocked_domains: options.excludeDomains }
|
|
97
|
+
: {};
|
|
94
98
|
const body = {
|
|
95
99
|
model,
|
|
96
100
|
max_tokens: maxTokens,
|
package/lib/backends/openai.js
CHANGED
|
@@ -53,9 +53,11 @@ export const openaiBackend = {
|
|
|
53
53
|
const model = options.model || "gpt-4o";
|
|
54
54
|
const endpoint = `${baseURL}/responses`;
|
|
55
55
|
|
|
56
|
-
const domainFilters =
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
const domainFilters = Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
|
|
57
|
+
? { allowed_domains: options.includeDomains }
|
|
58
|
+
: Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
|
|
59
|
+
? { blocked_domains: options.excludeDomains }
|
|
60
|
+
: {};
|
|
59
61
|
const body = {
|
|
60
62
|
model,
|
|
61
63
|
tools: [{
|
package/lib/backends/parallel.js
CHANGED
|
@@ -27,6 +27,9 @@ const SESSION_ID = "dsh-websearch-" + randomUUID().slice(0, 8);
|
|
|
27
27
|
export const parallelBackend = {
|
|
28
28
|
id: "parallel",
|
|
29
29
|
requiresCredential: false,
|
|
30
|
+
// The provider may hand all derived facets to one call on the primary
|
|
31
|
+
// variant; later variants then skip this backend.
|
|
32
|
+
handlesAllVariants: true,
|
|
30
33
|
|
|
31
34
|
available() {
|
|
32
35
|
return true; // keyless endpoint
|
|
@@ -35,7 +38,8 @@ export const parallelBackend = {
|
|
|
35
38
|
async search(request, signal, options, hooks = {}) {
|
|
36
39
|
const args = {
|
|
37
40
|
objective: request.query,
|
|
38
|
-
|
|
41
|
+
objective: request.searchPlan?.objective ?? request.query,
|
|
42
|
+
search_queries: request.searchPlan?.queries?.slice(0, 3) ?? [request.query],
|
|
39
43
|
session_id: SESSION_ID,
|
|
40
44
|
model_name: "dsh-websearch",
|
|
41
45
|
};
|
package/lib/backends/searxng.js
CHANGED
|
@@ -37,10 +37,12 @@ const ANTI_BOT_RE = /(verifying your browser|making sure you.?re not a bot|check
|
|
|
37
37
|
const INSTANCE_COOLDOWN_MS = 10 * 60_000;
|
|
38
38
|
const INSTANCE_ATTEMPT_TIMEOUT_MS = 4500;
|
|
39
39
|
const instanceCooldowns = new Map(); // baseURL -> cooledUntil (epoch ms)
|
|
40
|
+
const pageCooldowns = new Map(); // baseURL -> no-pagination-until (epoch ms)
|
|
40
41
|
|
|
41
42
|
/** Test hook: clear per-instance cooldowns between cases. */
|
|
42
43
|
export function resetInstanceCooldowns() {
|
|
43
44
|
instanceCooldowns.clear();
|
|
45
|
+
pageCooldowns.clear();
|
|
44
46
|
}
|
|
45
47
|
|
|
46
48
|
/** @type {import("../provider.js").Backend} */
|
|
@@ -106,7 +108,7 @@ export const searxngBackend = {
|
|
|
106
108
|
const attemptSignal = signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal;
|
|
107
109
|
const timer = setTimeout(() => attemptController.abort(), attemptMs);
|
|
108
110
|
try {
|
|
109
|
-
const sources = await queryInstance(candidate, request, attemptSignal, backendOpts, apiKey, hooks);
|
|
111
|
+
const sources = await queryInstance(candidate, { ...request, pageLimit: 1 }, attemptSignal, backendOpts, apiKey, hooks);
|
|
110
112
|
instanceCooldowns.delete(candidate);
|
|
111
113
|
return { sources };
|
|
112
114
|
} catch (error) {
|
|
@@ -139,26 +141,73 @@ export const searxngBackend = {
|
|
|
139
141
|
};
|
|
140
142
|
|
|
141
143
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
+
* Query one instance, paginating only when the provider sets pageLimit > 1
|
|
145
|
+
* (deepCoverage without internal multi-query). Page 1 is authoritative: if a later page
|
|
146
|
+
* fails, the already-collected page-1 sources are returned. The outer
|
|
147
|
+
* per-instance timer/signal covers every page, so pagination cannot outlive
|
|
148
|
+
* the backend budget.
|
|
144
149
|
* @returns {Promise<Array>} sources
|
|
145
150
|
*/
|
|
146
151
|
async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hooks) {
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
152
|
+
const base = new URL(baseURL);
|
|
153
|
+
base.pathname = base.pathname.replace(/\/+$/,"") + "/search";
|
|
154
|
+
base.searchParams.set("q", request.query);
|
|
155
|
+
base.searchParams.set("format", "json");
|
|
151
156
|
// deepCoverage widens the category sweep (docs.searxng.org Search API:
|
|
152
157
|
// categories is a comma-separated list) — breadth over one category.
|
|
153
|
-
|
|
158
|
+
base.searchParams.set("categories", request.deepCoverage === true ? "general,news,it" : "general");
|
|
154
159
|
// Language: settings/request filter wins, else historical "en" default.
|
|
155
160
|
const filters = normalizeFilters(request.filters);
|
|
156
|
-
|
|
157
|
-
applySearxngFilters(
|
|
161
|
+
base.searchParams.set("language", filters.lang ?? "en");
|
|
162
|
+
applySearxngFilters(base, filters); // time_range (+ language override)
|
|
158
163
|
// Safe-search defaults ON (preserves the previous hardcoded behavior).
|
|
159
|
-
|
|
160
|
-
|
|
164
|
+
base.searchParams.set("safesearch", safeSearchParams("searxng", backendOpts.safeSearch ?? true) ?? "1");
|
|
165
|
+
|
|
166
|
+
const max = Math.max(1, Number(request.maxResults) || 8);
|
|
167
|
+
// A page-2 429/5xx must not be repeated on every search: keep the first
|
|
168
|
+
// page, skip extra pages for a minute.
|
|
169
|
+
const pages = (pageCooldowns.get(baseURL) ?? 0) > Date.now()
|
|
170
|
+
? 1
|
|
171
|
+
: Math.min(2, Math.max(1, Number(request.pageLimit) || 1));
|
|
172
|
+
const out = [];
|
|
173
|
+
const seen = new Set();
|
|
174
|
+
for (let page = 1; page <= pages; page += 1) {
|
|
175
|
+
const pageUrl = new URL(base);
|
|
176
|
+
pageUrl.searchParams.set("pageno", String(page));
|
|
177
|
+
let pageSources;
|
|
178
|
+
try {
|
|
179
|
+
pageSources = await queryInstancePage(
|
|
180
|
+
baseURL, request, signal, backendOpts, apiKey, hooks, pageUrl, max - out.length,
|
|
181
|
+
);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (signal?.aborted === true) throw searchAborted(signal, error);
|
|
184
|
+
// A failed page after a successful page 1 degrades coverage, not the
|
|
185
|
+
// whole result; the caller still gets the sources already found. Any
|
|
186
|
+
// page>1 failure pauses extra pages for a minute (a 5xx flaps too).
|
|
187
|
+
if (out.length > 0) {
|
|
188
|
+
if (page > 1) pageCooldowns.set(baseURL, Date.now() + 60_000);
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
for (const src of pageSources) {
|
|
194
|
+
if (src && typeof src.url === "string" && !seen.has(src.url)) {
|
|
195
|
+
seen.add(src.url);
|
|
196
|
+
out.push(src);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (page > 1) pageCooldowns.delete(baseURL);
|
|
200
|
+
if (pageSources.length === 0 || out.length >= max) break;
|
|
201
|
+
}
|
|
202
|
+
return out.slice(0, max);
|
|
203
|
+
}
|
|
161
204
|
|
|
205
|
+
/**
|
|
206
|
+
* One page against one instance. Throws WebError on any failure; abort
|
|
207
|
+
* semantics are the caller's contract (signal passed through verbatim).
|
|
208
|
+
* @returns {Promise<Array>} sources
|
|
209
|
+
*/
|
|
210
|
+
async function queryInstancePage(baseURL, request, signal, backendOpts, apiKey, hooks, url, remainingMax) {
|
|
162
211
|
const headers = {
|
|
163
212
|
"Accept": "application/json",
|
|
164
213
|
"User-Agent": "dsh-websearch/2.3",
|
|
@@ -223,7 +272,7 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
|
|
|
223
272
|
throw new WebError(message, "WEB_PROVIDER_ERROR");
|
|
224
273
|
}
|
|
225
274
|
|
|
226
|
-
const sources = parseSearxngResult(data,
|
|
275
|
+
const sources = parseSearxngResult(data, remainingMax);
|
|
227
276
|
hooks?.recordOutcome?.({ status: "success", count: sources.length });
|
|
228
277
|
return sources;
|
|
229
278
|
}
|
package/lib/cache.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// cache.js — v2.7.0 disk cache for unified search results (zero dependencies).
|
|
2
2
|
//
|
|
3
|
-
// Cache key: sha256 over the canonical JSON of
|
|
4
|
-
//
|
|
3
|
+
// Cache key: sha256 over the canonical JSON of the shaped query, filters,
|
|
4
|
+
// effective maxResults, ordered backend set, cache mode and result options.
|
|
5
5
|
// Entries live as one JSON file per key under <dir>, written atomically
|
|
6
6
|
// (tmp file + rename) so a crash mid-write never leaves a corrupt cache.
|
|
7
7
|
// Eviction: when the entry count exceeds maxEntries, the oldest-by-mtime
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { createHash } from "node:crypto";
|
|
12
12
|
import {
|
|
13
|
+
chmodSync,
|
|
13
14
|
existsSync,
|
|
14
15
|
mkdirSync,
|
|
15
16
|
readdirSync,
|
package/lib/client.js
CHANGED
|
@@ -7,11 +7,6 @@ window.__ModuleLoader__.load({
|
|
|
7
7
|
let react_jsx_runtime = require("react/jsx-runtime");
|
|
8
8
|
let react = require("react");
|
|
9
9
|
|
|
10
|
-
/** Localized display label for a backend id (falls back to the id). */
|
|
11
|
-
function backendLabel(t, id) {
|
|
12
|
-
return t("backend" + id.charAt(0).toUpperCase() + id.slice(1));
|
|
13
|
-
}
|
|
14
|
-
|
|
15
10
|
const NS = "websearch.settings";
|
|
16
11
|
const PLUGIN_NS = "unified-search";
|
|
17
12
|
|
|
@@ -36,7 +31,7 @@ window.__ModuleLoader__.load({
|
|
|
36
31
|
{ id: "firecrawl", keyEnv: "FIRECRAWL_API_KEY", optionalKey: true, metered: true, label: "Firecrawl (免 Key · 有额度 · 默认关)" },
|
|
37
32
|
{ id: "tinyfish", keyEnv: "TINYFISH_API_KEY", optionalKey: true, metered: true, label: "TinyFish (免 Key · 30/分·50/日 · 默认关)" },
|
|
38
33
|
];
|
|
39
|
-
const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs"];
|
|
34
|
+
const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs", "cacheTtl"];
|
|
40
35
|
/** Enum-valued settings (validated client-side, saved as strings). */
|
|
41
36
|
const SELECT_FIELDS = {
|
|
42
37
|
intervention: ["official", "balanced", "thorough"],
|
|
@@ -44,7 +39,7 @@ window.__ModuleLoader__.load({
|
|
|
44
39
|
dedupStrategy: ["url", "url+title"],
|
|
45
40
|
};
|
|
46
41
|
/** Boolean settings staged as "true"/"false" strings by the selects. */
|
|
47
|
-
const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry", "resultHeader"];
|
|
42
|
+
const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry", "resultHeader", "cacheEnabled"];
|
|
48
43
|
// split metered, opt-in backends out of the
|
|
49
44
|
// "keyless / ready to use" group. They work without a key but are rate
|
|
50
45
|
// limited and default OFF, so a separate section with an explicit hint
|
|
@@ -136,6 +131,8 @@ window.__ModuleLoader__.load({
|
|
|
136
131
|
keyReadFailed: "密钥状态读取失败,请稍后重试",
|
|
137
132
|
telemetryLabel: "结果健康遥测",
|
|
138
133
|
resultHeaderLabel: "结果引用提示头",
|
|
134
|
+
cacheLabel: "结果缓存",
|
|
135
|
+
cacheTtlLabel: "缓存有效期(秒)",
|
|
139
136
|
fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端(计量型仍保持关闭)",
|
|
140
137
|
invalidFields: "以下字段未通过校验:",
|
|
141
138
|
readOnlyScope: "当前配置只读(可能由宿主锁定)",
|
|
@@ -224,6 +221,8 @@ window.__ModuleLoader__.load({
|
|
|
224
221
|
keyReadFailed: "could not read key status, please retry later",
|
|
225
222
|
telemetryLabel: "Result health telemetry",
|
|
226
223
|
resultHeaderLabel: "Citation header",
|
|
224
|
+
cacheLabel: "Result cache",
|
|
225
|
+
cacheTtlLabel: "Cache TTL (s)",
|
|
227
226
|
fallbackHint: "All backends off: search falls back to the default keyless four (metered backends stay off).",
|
|
228
227
|
invalidFields: "Fields failed validation:",
|
|
229
228
|
readOnlyScope: "Configuration is read-only (locked by host?)",
|
|
@@ -683,9 +682,11 @@ window.__ModuleLoader__.load({
|
|
|
683
682
|
numResults: [1, 100],
|
|
684
683
|
concurrency: [1, 10],
|
|
685
684
|
backendTimeoutMs: [1000, 120000],
|
|
685
|
+
cacheTtl: [0, 86400],
|
|
686
686
|
};
|
|
687
|
+
const STEP = { numResults: 1, concurrency: 1, backendTimeoutMs: 1000, cacheTtl: 30 };
|
|
687
688
|
const [lo, hi] = BOUNDS[field] ?? [-Infinity, Infinity];
|
|
688
|
-
if (!Number.isInteger(num) || num < lo || num > hi) { this.failed = true; this.failedFields.add(field); continue; }
|
|
689
|
+
if (!Number.isInteger(num) || num < lo || num > hi || num % (STEP[field] ?? 1) !== 0) { this.failed = true; this.failedFields.add(field); continue; }
|
|
689
690
|
fieldOps.push({ op: "set", path: [field], value: num }); fieldOpNames.push(field);
|
|
690
691
|
} else {
|
|
691
692
|
fieldOps.push({ op: "set", path: [field], value: staged.text }); fieldOpNames.push(field);
|
|
@@ -735,6 +736,10 @@ window.__ModuleLoader__.load({
|
|
|
735
736
|
&& this.staged.size === 0 && this.stagedKeys.size === 0) this.savedAt = Date.now();
|
|
736
737
|
} catch (err) {
|
|
737
738
|
this.failed = true;
|
|
739
|
+
// A server-side schema 400 names the field; attribute it so
|
|
740
|
+
// the card can mark the offending control.
|
|
741
|
+
const named = /(?:invalid value for|unknown settings field) "([^"]+)"/.exec(String(err));
|
|
742
|
+
if (named !== null) this.failedFields.add(named[1]);
|
|
738
743
|
this.conflict = String(err).includes("SETTINGS_CONFLICT");
|
|
739
744
|
// Without a reload the stale expectedRevision makes every
|
|
740
745
|
// subsequent Save fail the same way. Staged edits survive, so
|
|
@@ -979,6 +984,10 @@ window.__ModuleLoader__.load({
|
|
|
979
984
|
react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("timeoutLabel") }) }),
|
|
980
985
|
react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("timeoutLabel"), value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: (e) => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
|
|
981
986
|
] }),
|
|
987
|
+
react_jsx_runtime.jsxs("div", { children: [
|
|
988
|
+
react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("cacheTtlLabel") }) }),
|
|
989
|
+
react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("cacheTtlLabel"), value: state.stagedText("cacheTtl") ?? String(state.value.cacheTtl ?? ""), onChange: (e) => card.edit("cacheTtl", e.target.value), inputMode: "numeric" }),
|
|
990
|
+
] }),
|
|
982
991
|
] }),
|
|
983
992
|
react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("shapingTitle") }),
|
|
984
993
|
react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
|
|
@@ -1000,6 +1009,7 @@ window.__ModuleLoader__.load({
|
|
|
1000
1009
|
react_jsx_runtime.jsx(SelectField, { label: t("safeSearchLabel"), value: selVal("safeSearch", "true"), options: boolOptions, onChange: (v) => card.edit("safeSearch", v) }),
|
|
1001
1010
|
react_jsx_runtime.jsx(SelectField, { label: t("telemetryLabel"), value: selVal("resultTelemetry", "true"), options: boolOptions, onChange: (v) => card.edit("resultTelemetry", v) }),
|
|
1002
1011
|
react_jsx_runtime.jsx(SelectField, { label: t("resultHeaderLabel"), value: selVal("resultHeader", "true"), options: boolOptions, onChange: (v) => card.edit("resultHeader", v) }),
|
|
1012
|
+
react_jsx_runtime.jsx(SelectField, { label: t("cacheLabel"), value: selVal("cacheEnabled", "true"), options: boolOptions, onChange: (v) => card.edit("cacheEnabled", v) }),
|
|
1003
1013
|
] }),
|
|
1004
1014
|
] });
|
|
1005
1015
|
}
|
package/lib/health.js
CHANGED
|
@@ -61,6 +61,7 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
|
|
|
61
61
|
cooledUntilMs: Number.isFinite(t?.cooledUntil) && t.cooledUntil > nowMs ? t.cooledUntil : null,
|
|
62
62
|
// reachable: true/false from the latest search telemetry; null = never probed.
|
|
63
63
|
reachable: t ? t.ok === true : null,
|
|
64
|
+
credentialMissing: t?.credentialMissing === true,
|
|
64
65
|
lastOk: t && typeof t.lastOkAt === "number" ? t.lastOkAt : null,
|
|
65
66
|
lastError: t && t.ok !== true ? sanitizeError(t.error) || "unknown error" : null,
|
|
66
67
|
};
|
package/lib/history.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// oldest entry beyond the cap is dropped. Exposure is strictly read-only via
|
|
7
7
|
// GET /api/websearch/history; POST /api/websearch/history/clear empties it.
|
|
8
8
|
|
|
9
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { rejectionFor, rejectionBody } from "./trust.js";
|
|
12
12
|
|
|
@@ -55,6 +55,7 @@ export function createHistoryStore({ dir, maxEntries = HISTORY_MAX_ENTRIES }) {
|
|
|
55
55
|
|
|
56
56
|
function atomicWriteAll(list) {
|
|
57
57
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
58
|
+
try { chmodSync(dir, 0o700); } catch { /* existing dir owned by another mode */ }
|
|
58
59
|
const f = file();
|
|
59
60
|
const tmp = `${f}.${process.pid}.tmp`;
|
|
60
61
|
writeFileSync(tmp, JSON.stringify(list, null, 2), { encoding: "utf8", mode: 0o600 });
|
package/lib/index.js
CHANGED
|
@@ -20,6 +20,7 @@ import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
|
|
|
20
20
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
21
21
|
import { findPluginRow } from "./util/namespace.js";
|
|
22
22
|
|
|
23
|
+
|
|
23
24
|
// Import all backends
|
|
24
25
|
import { exaBackend } from "./backends/exa.js";
|
|
25
26
|
import { parallelBackend } from "./backends/parallel.js";
|
|
@@ -162,7 +163,7 @@ export const Config = z.object({
|
|
|
162
163
|
intervention: z.union(["official", "balanced", "thorough"]).default("balanced")
|
|
163
164
|
.description("搜索介入程度【策略】:official=只做官方 provider 该做的(原样查询、不加结果头/遥测、沿用工具的条数上限);balanced=确定性去噪 + 去重/遥测(默认);thorough=额外启用相关性重排与深度覆盖(内部多查询仍是独立开关,默认关)"),
|
|
164
165
|
numResults: z.number().step(1).min(1).max(100).default(10)
|
|
165
|
-
.description("每次搜索返回的最大结果数(official
|
|
166
|
+
.description("每次搜索返回的最大结果数(1-100;Exa/Firecrawl 可达 100,Brave/Tavily/Serper/Mojeek 每次最多 20;official 沿用宿主上限)"),
|
|
166
167
|
concurrency: z.number().step(1).min(1).max(10).default(6)
|
|
167
168
|
.description("同时并发的后端数量"),
|
|
168
169
|
backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(24000)
|
|
@@ -176,9 +177,9 @@ export const Config = z.object({
|
|
|
176
177
|
safeSearch: z.boolean().default(true)
|
|
177
178
|
.description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
|
|
178
179
|
includeDomains: z.string().default("")
|
|
179
|
-
.description("
|
|
180
|
+
.description("只约束 OpenAI/Anthropic 原生后端的允许域名(逗号/空格分隔,最多 20 个);其余后端不支持,合并结果仍可能来自其他域名"),
|
|
180
181
|
excludeDomains: z.string().default("")
|
|
181
|
-
.description("排除这些域名(逗号/空格分隔,最多 20
|
|
182
|
+
.description("排除这些域名(逗号/空格分隔,最多 20 个);Anthropic 仅发 allowed(include 优先),OpenAI 两个列表同时发送由服务端裁决"),
|
|
182
183
|
dedupStrategy: z.union(["url", "url+title"]).default("url")
|
|
183
184
|
.description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
|
|
184
185
|
rerank: z.boolean().default(false)
|
|
@@ -195,7 +196,7 @@ export const Config = z.object({
|
|
|
195
196
|
cacheEnabled: z.boolean().default(true)
|
|
196
197
|
.description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
|
|
197
198
|
cacheTtl: z.number().step(30).min(0).max(86400).default(900)
|
|
198
|
-
.description("缓存有效期【缓存】(单位:秒):默认 900
|
|
199
|
+
.description("缓存有效期【缓存】(单位:秒):默认 900;0 = 不缓存(no-store)"),
|
|
199
200
|
breakerEnabled: z.boolean().default(true)
|
|
200
201
|
.description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
|
|
201
202
|
breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
|
|
@@ -335,16 +336,21 @@ for (const [key, label] of Object.entries(FIELD_LABELS)) {
|
|
|
335
336
|
function normalizeDomainList(raw) {
|
|
336
337
|
if (typeof raw !== "string" || raw.trim() === "") return [];
|
|
337
338
|
const out = [];
|
|
338
|
-
for (const piece of raw.split(/[
|
|
339
|
+
for (const piece of raw.split(/[,,、;;\s]+/)) {
|
|
339
340
|
const item = piece.trim().toLowerCase();
|
|
340
341
|
if (item === "") continue;
|
|
341
342
|
let host = item;
|
|
343
|
+
// A leading wildcard is the natural way to say "this domain and its
|
|
344
|
+
// subdomains"; both providers' filters already match subdomains.
|
|
345
|
+
if (host.startsWith("*.")) host = host.slice(2);
|
|
342
346
|
try {
|
|
343
|
-
const u = new URL(item.includes("://") ? item : "https://" +
|
|
347
|
+
const u = new URL(item.includes("://") ? item : "https://" + host);
|
|
344
348
|
host = u.hostname;
|
|
345
349
|
} catch { /* keep the raw token and validate below */ }
|
|
346
|
-
host = host.replace(/^\[|\]$/g, "");
|
|
347
|
-
|
|
350
|
+
host = host.replace(/^\[|\]$/g, "").replace(/^\*\./, "").replace(/\.$/, "");
|
|
351
|
+
// Hostname only: at least one dot, no empty labels, no bare IPv4/IPv6
|
|
352
|
+
// literals (OpenAI/Anthropic domain filters expect DNS names).
|
|
353
|
+
if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})$/.test(host)) continue;
|
|
348
354
|
if (!out.includes(host)) out.push(host);
|
|
349
355
|
if (out.length >= 20) break;
|
|
350
356
|
}
|
|
@@ -385,6 +391,15 @@ export function resolveOptions(ctx, config) {
|
|
|
385
391
|
enabledBackends = [...new Set(enabledBackends)];
|
|
386
392
|
|
|
387
393
|
// 2. Resolve each backend option
|
|
394
|
+
const includeDomains = normalizeDomainList(config?.includeDomains);
|
|
395
|
+
const excludeDomains = normalizeDomainList(config?.excludeDomains);
|
|
396
|
+
// A non-empty setting that normalizes to nothing must not silently disable
|
|
397
|
+
// the restriction; the provider turns this into a clear search error.
|
|
398
|
+
const domainConsumers = enabledBackends.some((id) => id === "openai" || id === "anthropic");
|
|
399
|
+
const domainFilterError = domainConsumers && (
|
|
400
|
+
(typeof config?.includeDomains === "string" && config.includeDomains.trim() !== "" && includeDomains.length === 0)
|
|
401
|
+
|| (typeof config?.excludeDomains === "string" && config.excludeDomains.trim() !== "" && excludeDomains.length === 0)
|
|
402
|
+
) ? "domain filter contains no valid hostname" : undefined;
|
|
388
403
|
const backends = {};
|
|
389
404
|
for (const id of ALL_BACKENDS) {
|
|
390
405
|
const keyEnvName = config?.[`${id}ApiKeyEnv`] ?? DEFAULT_KEY_ENV[id];
|
|
@@ -401,8 +416,8 @@ export function resolveOptions(ctx, config) {
|
|
|
401
416
|
: [],
|
|
402
417
|
} : {}),
|
|
403
418
|
safeSearch: config?.safeSearch !== false,
|
|
404
|
-
includeDomains
|
|
405
|
-
excludeDomains
|
|
419
|
+
includeDomains,
|
|
420
|
+
excludeDomains,
|
|
406
421
|
label: DEFAULT_LABELS[id] ?? id,
|
|
407
422
|
requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
|
|
408
423
|
optionalKey: OPTIONAL_KEY_IDS.has(id),
|
|
@@ -458,8 +473,9 @@ export function resolveOptions(ctx, config) {
|
|
|
458
473
|
// invisibly.
|
|
459
474
|
multiQueryEnabled: !official && config?.multiQueryEnabled === true,
|
|
460
475
|
deepCoverage: thorough || (!official && config?.deepCoverage === true),
|
|
461
|
-
includeDomains
|
|
462
|
-
excludeDomains
|
|
476
|
+
includeDomains,
|
|
477
|
+
excludeDomains,
|
|
478
|
+
domainFilterError,
|
|
463
479
|
filters: {
|
|
464
480
|
recency: typeof config?.recency === "string" && config.recency !== "any" ? config.recency : undefined,
|
|
465
481
|
lang: language.length > 0 ? language : undefined,
|
package/lib/provider.js
CHANGED
|
@@ -85,9 +85,13 @@ function recordBackendHealth(id, entry, breakerCfg, opts = {}) {
|
|
|
85
85
|
// failures for diagnostics, but never publish a cooldown the provider does
|
|
86
86
|
// not honour (health/history used to show `cooled: true` while the backend
|
|
87
87
|
// kept being called).
|
|
88
|
-
const breaker =
|
|
89
|
-
|
|
90
|
-
|
|
88
|
+
const breaker = entry.credentialMissing === true
|
|
89
|
+
// A missing key is a configuration state, not an outage: keep the current
|
|
90
|
+
// breaker counters and only publish the diagnostic entry.
|
|
91
|
+
? { failCount: Number(prev?.failCount) || 0, cooledUntil: Number(prev?.cooledUntil) || 0 }
|
|
92
|
+
: breakerCfg === null
|
|
93
|
+
? { failCount: entry.ok === true ? 0 : (Number(prev?.failCount) || 0) + 1, cooledUntil: 0 }
|
|
94
|
+
: foldBreaker(prev, entry.ok === true, entry.at, breakerCfg, opts);
|
|
91
95
|
latestBackendHealth.set(id, {
|
|
92
96
|
...entry,
|
|
93
97
|
lastOkAt: entry.ok === true ? entry.at : (prev && prev.lastOkAt) || null,
|
|
@@ -98,6 +102,7 @@ function recordBackendHealth(id, entry, breakerCfg, opts = {}) {
|
|
|
98
102
|
// permission refusal (which cannot be fixed by retrying after a wait).
|
|
99
103
|
rateLimited: opts.rateLimited === true,
|
|
100
104
|
keylessRejected: opts.keylessRejected === true,
|
|
105
|
+
credentialMissing: entry.credentialMissing === true,
|
|
101
106
|
});
|
|
102
107
|
}
|
|
103
108
|
|
|
@@ -236,6 +241,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
236
241
|
async search(request, signal) {
|
|
237
242
|
throwIfSearchAborted(signal);
|
|
238
243
|
const opts = resolveOptions();
|
|
244
|
+
if (opts.domainFilterError !== undefined) {
|
|
245
|
+
throw new WebError("unified search: " + opts.domainFilterError, "WEB_PROVIDER_ERROR");
|
|
246
|
+
}
|
|
239
247
|
const filters = normalizeFilters({
|
|
240
248
|
...(opts.filters ?? {}),
|
|
241
249
|
...(request?.filters ?? {}),
|
|
@@ -313,7 +321,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
313
321
|
const resultOptions = {};
|
|
314
322
|
for (const [k, v] of Object.entries(opts)) {
|
|
315
323
|
if (typeof v === "function") continue;
|
|
316
|
-
if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping)$/.test(k)
|
|
324
|
+
if (/^(safeSearch|rerank|dedupStrategy|language|recency|numResults|resultHeader|resultTelemetry|backendTimeoutMs|concurrency|multiQueryEnabled|deepCoverage|intervention|queryShaping|includeDomains|excludeDomains)$/.test(k)
|
|
317
325
|
|| /BaseURL$|^.*Model$|^.*ApiKeyEnv$|^enable[A-Z]/.test(k)) resultOptions[k] = v;
|
|
318
326
|
}
|
|
319
327
|
// resolveOptions() keeps per-backend settings under opts.backends[id],
|
|
@@ -323,6 +331,10 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
323
331
|
for (const id of opts.enabledBackends ?? []) {
|
|
324
332
|
const be = opts.backends?.[id];
|
|
325
333
|
if (!be || typeof be !== "object") continue;
|
|
334
|
+
// Domain filters live in backend options as well; keying the
|
|
335
|
+
// top-level lists alone would miss a per-backend edit.
|
|
336
|
+
if (Array.isArray(be.includeDomains)) resultOptions[`${id}.includeDomains`] = be.includeDomains;
|
|
337
|
+
if (Array.isArray(be.excludeDomains)) resultOptions[`${id}.excludeDomains`] = be.excludeDomains;
|
|
326
338
|
// Every per-backend option that changes results must appear here, or
|
|
327
339
|
// a cache hit inside the TTL masks the edit. baseURLs (plural) is the
|
|
328
340
|
// SearXNG failover list; leaving it out made instance changes inert.
|
|
@@ -348,8 +360,8 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
348
360
|
} else {
|
|
349
361
|
let hitContent = typeof hit.value.content === "string" ? hit.value.content : undefined;
|
|
350
362
|
// `official` promises no provider-added text (the consumer owns
|
|
351
|
-
// presentation), so the diagnostic cache note
|
|
352
|
-
//
|
|
363
|
+
// presentation), so the diagnostic cache note follows `resultTelemetry`
|
|
364
|
+
// rather than being appended unconditionally.
|
|
353
365
|
if (opts.resultTelemetry !== false) {
|
|
354
366
|
const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
|
|
355
367
|
hitContent = hitContent === undefined ? cacheNote : hitContent + "\n\n" + cacheNote;
|
|
@@ -443,8 +455,11 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
443
455
|
|
|
444
456
|
if (eligible.length === 0) {
|
|
445
457
|
recordHistory(history, request?.query, 0, 0, candidates.length);
|
|
458
|
+
const registered = (opts.enabledBackends ?? []).filter((id) => backends[id] !== undefined).length;
|
|
446
459
|
throw new WebError(
|
|
447
|
-
|
|
460
|
+
registered === 0
|
|
461
|
+
? "unified search: none of the enabled backend ids is registered"
|
|
462
|
+
: "unified search: no enabled backend is available (missing API key or unsupported config)",
|
|
448
463
|
"WEB_PROVIDER_UNAVAILABLE",
|
|
449
464
|
);
|
|
450
465
|
}
|
|
@@ -452,7 +467,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
452
467
|
// Run ONE query variant through the full fan-out: breaker-aware backend
|
|
453
468
|
// execution under the per-variant limiter, then PHASE 1 collect. The
|
|
454
469
|
// internal abort/timeout semantics are unchanged from v2.7.
|
|
455
|
-
const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY, deadline = Number.POSITIVE_INFINITY) => {
|
|
470
|
+
const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY, deadline = Number.POSITIVE_INFINITY, eligibleList = eligible) => {
|
|
456
471
|
const telemetry = [];
|
|
457
472
|
// Health is folded once per backend per SEARCH, after every variant
|
|
458
473
|
// finished: recording per variant let one multi-query search trip the
|
|
@@ -476,9 +491,18 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
476
491
|
: controller.signal;
|
|
477
492
|
const remainingNow = Number.isFinite(deadline) ? deadline - Date.now() : Number.POSITIVE_INFINITY;
|
|
478
493
|
if (remainingNow <= 0) {
|
|
479
|
-
|
|
494
|
+
const msg = "search budget exhausted (not started)";
|
|
495
|
+
telemetry.push({ id, ok: false, skipped: true, ms: 0, error: msg });
|
|
496
|
+
return Promise.reject(new WebError(`backend "${id}" ${msg}`, "WEB_PROVIDER_ERROR"));
|
|
480
497
|
}
|
|
481
|
-
const
|
|
498
|
+
const configuredTimeoutMs = effectiveBackendTimeoutMs(id, backendTimeoutMs);
|
|
499
|
+
const effectiveTimeoutMs = Math.max(1, Math.min(configuredTimeoutMs, variantBudgetMs, remainingNow));
|
|
500
|
+
// A call cut below its configured timeout by the shared budget is
|
|
501
|
+
// not an outage: do not fold it into the breaker/health.
|
|
502
|
+
// Startup jitter can shave a millisecond off the configured timeout; only
|
|
503
|
+
// a material cut is budget starvation.
|
|
504
|
+
const budgetClipped = effectiveTimeoutMs < configuredTimeoutMs
|
|
505
|
+
&& remainingNow < configuredTimeoutMs - 10;
|
|
482
506
|
const timeoutId = setTimeout(() => controller.abort(), effectiveTimeoutMs);
|
|
483
507
|
// A backend that ignores its signal (blackholed TCP, stuck proxy)
|
|
484
508
|
// must not hold the whole fan-out past its budget. Race the call
|
|
@@ -539,17 +563,25 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
539
563
|
// thrown error said "timed out after Nms" — the two disagreed
|
|
540
564
|
// and "(unified search aborted)" read as if the USER cancelled.
|
|
541
565
|
const timedOut = controller.signal.aborted && !(signal && signal.aborted);
|
|
566
|
+
// Only a timeout caused by the shared/variant budget is
|
|
567
|
+
// exempt from the breaker; a 429/500 on a clipped attempt is
|
|
568
|
+
// still a real backend failure.
|
|
569
|
+
const budgetClipped = timedOut
|
|
570
|
+
&& (remainingNow < configuredTimeoutMs - 10 || variantBudgetMs < configuredTimeoutMs - 10);
|
|
542
571
|
const reason = timedOut
|
|
543
|
-
?
|
|
572
|
+
? budgetClipped
|
|
573
|
+
? `backend "${id}" search budget exhausted after ${effectiveTimeoutMs}ms`
|
|
574
|
+
: `backend "${id}" timed out after ${effectiveTimeoutMs}ms`
|
|
544
575
|
: String(err instanceof Error ? err.message : err);
|
|
545
576
|
const msg = sanitizeError(reason, 80);
|
|
546
577
|
telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
|
|
547
578
|
// A missing API key is a configuration state, not an outage:
|
|
548
|
-
//
|
|
549
|
-
|
|
550
|
-
|
|
579
|
+
// publish it for /health but keep it out of the breaker.
|
|
580
|
+
if (!budgetClipped) {
|
|
581
|
+
const credentialMissing = err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING";
|
|
551
582
|
health.push({
|
|
552
583
|
id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
|
|
584
|
+
...(credentialMissing ? { credentialMissing: true } : {}),
|
|
553
585
|
rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
|
|
554
586
|
});
|
|
555
587
|
}
|
|
@@ -562,7 +594,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
562
594
|
};
|
|
563
595
|
|
|
564
596
|
const results = await Promise.allSettled(
|
|
565
|
-
|
|
597
|
+
eligibleList.map(({ id, backend, beOpts }) => {
|
|
566
598
|
const hooks = {
|
|
567
599
|
recordRequest: (req) => recordBackendRequest(ctx, id, req),
|
|
568
600
|
recordOutcome: (out) => recordBackendOutcome(ctx, id, out),
|
|
@@ -571,7 +603,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
571
603
|
}),
|
|
572
604
|
);
|
|
573
605
|
throwIfSearchAborted(signal);
|
|
574
|
-
const fold = collectFanoutResults(results,
|
|
606
|
+
const fold = collectFanoutResults(results, eligibleList, signal);
|
|
575
607
|
return { ...fold, telemetry, health };
|
|
576
608
|
};
|
|
577
609
|
|
|
@@ -581,7 +613,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
581
613
|
const allTelemetry = [];
|
|
582
614
|
const allFailures = [];
|
|
583
615
|
// One search-wide budget: sequential variants must not multiply the
|
|
584
|
-
// per-backend timeout into N ×
|
|
616
|
+
// per-backend timeout into N × 24s (which also exceeds the host's 30s
|
|
585
617
|
// tool deadline). Later variants get only the time still left.
|
|
586
618
|
const searchBudgetMs = Math.max(1, Number(opts.backendTimeoutMs) || 24000);
|
|
587
619
|
const searchDeadline = Date.now() + searchBudgetMs;
|
|
@@ -601,13 +633,27 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
601
633
|
// slow variant cannot starve the rest (the old code gave each variant
|
|
602
634
|
// the full budget, and each backend inside it).
|
|
603
635
|
const share = Math.max(1, Math.floor(remaining / Math.max(1, variants.length - variantIndex)));
|
|
636
|
+
// Parallel can merge the derived facets into one request; give it the
|
|
637
|
+
// plan on the primary variant and skip it for later variants. Other
|
|
638
|
+
// backends must not opt into handlesAllVariants (they cannot merge
|
|
639
|
+
// facets without changing semantics).
|
|
640
|
+
const searchPlan = useMulti && variantIndex === 0
|
|
641
|
+
? { objective: effReq.query, queries: variants.slice(0, 3) }
|
|
642
|
+
: undefined;
|
|
643
|
+
const variantEligible = variantIndex === 0
|
|
644
|
+
? eligible
|
|
645
|
+
: eligible.filter(({ backend }) => backend.handlesAllVariants !== true);
|
|
604
646
|
const variantReq = {
|
|
605
647
|
...effReq,
|
|
606
648
|
query: variantQuery,
|
|
607
649
|
maxResults: backendMaxResults,
|
|
650
|
+
...(searchPlan !== undefined ? { searchPlan } : {}),
|
|
608
651
|
...(coverage ? { deepCoverage: true } : {}),
|
|
652
|
+
// SearXNG paging is opt-in and never combines with internal
|
|
653
|
+
// multi-query (each variant already costs one request).
|
|
654
|
+
pageLimit: coverage && !useMulti ? 2 : 1,
|
|
609
655
|
};
|
|
610
|
-
const fold = await fanoutVariant(variantReq, share, searchDeadline);
|
|
656
|
+
const fold = await fanoutVariant(variantReq, share, searchDeadline, variantEligible);
|
|
611
657
|
for (const outcome of fold.health) {
|
|
612
658
|
const prev = searchHealth.get(outcome.id);
|
|
613
659
|
if (prev === undefined || outcome.ok === true) {
|
|
@@ -741,6 +787,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
741
787
|
const parts = foldedTelemetry
|
|
742
788
|
.slice(0, 12)
|
|
743
789
|
.map((t) => {
|
|
790
|
+
if (t.skipped === true) return t.id + " ⏭budget";
|
|
744
791
|
if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
|
|
745
792
|
const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
|
|
746
793
|
const cooledNow = cooledAnnotation(latestBackendHealth.get(t.id), Date.now());
|
|
@@ -805,6 +852,8 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
805
852
|
// allFailures holds one entry per attempt (multi-query fans out once per
|
|
806
853
|
// variant); fold to one entry per backend before counting/reporting.
|
|
807
854
|
const uniqueFailures = [...new Map(allFailures.map((f) => [f.id, f])).values()];
|
|
855
|
+
const skippedIds = new Set(allTelemetry.filter((t) => t.skipped === true).map((t) => t.id));
|
|
856
|
+
const attemptedFailures = uniqueFailures.filter((f) => !skippedIds.has(f.id));
|
|
808
857
|
const detail = uniqueFailures.slice(0, MAX_FAILURE_DETAILS)
|
|
809
858
|
.map((f) => f.id + ": " + sanitizeError(f.err instanceof Error ? f.err.message : f.err, 120))
|
|
810
859
|
.join("; ") + (uniqueFailures.length > MAX_FAILURE_DETAILS ? `; +${uniqueFailures.length - MAX_FAILURE_DETAILS} more` : "");
|
|
@@ -828,7 +877,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
828
877
|
? " (cooled-skipped: " + skippedOnly.map(([cid, centry]) => cid + " " + (cooledAnnotation(centry, nowMs) || "⏸cooled")).join(", ") + ")"
|
|
829
878
|
: "";
|
|
830
879
|
throw new WebError(
|
|
831
|
-
|
|
880
|
+
(skippedIds.size > 0
|
|
881
|
+
? `unified search: all attempted backends failed (${attemptedFailures.length} of ${candidates.length} enabled; ${skippedIds.size} skipped for budget) - ${detail}`
|
|
882
|
+
: `unified search: all attempted backends failed (${uniqueFailures.length} of ${candidates.length} enabled) - ${detail}`) + cooledNote + hint,
|
|
832
883
|
"WEB_PROVIDER_ERROR",
|
|
833
884
|
{
|
|
834
885
|
// The cause message can embed an upstream body that echoes a key;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@240xu/dsh-websearch",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.12.0",
|
|
4
4
|
"description": "Unified web search provider for DeepSeek Harness (ctx.web): 13 backends — Exa + Parallel + DDG + SearXNG (keyless), DeepSeek + Anthropic + OpenAI + Brave + Tavily + Serper + Mojeek (key-gated via Settings credentials), Firecrawl + TinyFish (metered keyless, opt-in). Registers provider id \"unified\" for zero-config web_search. 统一网页搜索聚合:13 后端并发扇出、去重合并。See CHANGELOG.md for version history.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|