@240xu/dsh-websearch 2.8.7 → 2.8.9

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.
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { WebError } from "@deepseek-ai/dsh-web";
9
+ import { webErrorFromResponse } from "./web-error.js";
9
10
  import { egressFetch } from "./egress-fetch.js";
10
11
  import { describeError } from "./describe-error.js";
11
12
 
@@ -13,19 +14,30 @@ const UA = "dsh-websearch/2.3";
13
14
  const PROTOCOL_VERSION = "2025-06-18";
14
15
  const SESSION_TTL_MS = 10 * 60 * 1000; // 10 minutes
15
16
 
16
- /** Per-URL session cache: { sessionId, initializedAt } */
17
+ /** Session cache keyed by URL + stable auth-header digest. A session bound to
18
+ * one credential must never be reused after the key rotates (65 号 N4). */
17
19
  const sessionCache = new Map();
20
+ function sessionCacheKey(url, extraHeaders) {
21
+ const auth = Object.entries(extraHeaders ?? {})
22
+ .filter(([k]) => /^(authorization|x-api-key|x-tinyfish-access-mode)$/i.test(k))
23
+ .sort(([a], [b]) => a.localeCompare(b))
24
+ .map(([k, v]) => `${k.toLowerCase()}:${String(v)}`)
25
+ .join("|");
26
+ return `${url}\0${auth}`;
27
+ }
18
28
 
19
29
  /**
20
30
  * Ensure MCP session is initialized for the given URL.
21
31
  * Performs the 3-step handshake if needed.
22
32
  * @returns {Promise<string>} sessionId
23
33
  */
24
- async function ensureSession(url, signal) {
34
+ async function ensureSession(url, signal, options = {}, extraHeaders = {}) {
25
35
  const now = Date.now();
26
- const cached = sessionCache.get(url);
27
-
28
- if (cached && (now - cached.initializedAt) < SESSION_TTL_MS) {
36
+ const key = sessionCacheKey(url, extraHeaders);
37
+ const cached = sessionCache.get(key);
38
+
39
+ // A rotated credential must not reuse a session bound to the old key.
40
+ if (!options.forceFreshSession && cached && (now - cached.initializedAt) < SESSION_TTL_MS) {
29
41
  return cached.sessionId;
30
42
  }
31
43
 
@@ -49,6 +61,7 @@ async function ensureSession(url, signal) {
49
61
  "Content-Type": "application/json",
50
62
  "Accept": "application/json, text/event-stream",
51
63
  "User-Agent": UA,
64
+ ...extraHeaders,
52
65
  },
53
66
  body: JSON.stringify(initBody),
54
67
  signal,
@@ -64,7 +77,7 @@ async function ensureSession(url, signal) {
64
77
 
65
78
  if (!initResponse.ok) {
66
79
  const text = await initResponse.text().catch(() => "").then((tx) => tx.slice(0, 300));
67
- throw new WebError(`MCP initialize HTTP ${initResponse.status}: ${text}`, "WEB_PROVIDER_ERROR");
80
+ throw webErrorFromResponse(initResponse, text, "MCP initialize");
68
81
  }
69
82
 
70
83
  // Extract Mcp-Session-Id from response headers. Stateless MCP servers may
@@ -84,8 +97,10 @@ async function ensureSession(url, signal) {
84
97
  method: "POST",
85
98
  headers: {
86
99
  "Content-Type": "application/json",
100
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
87
101
  ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
88
102
  "User-Agent": UA,
103
+ ...extraHeaders,
89
104
  },
90
105
  body: JSON.stringify(notifyBody),
91
106
  signal,
@@ -100,7 +115,7 @@ async function ensureSession(url, signal) {
100
115
  }
101
116
 
102
117
  // Cache the session
103
- sessionCache.set(url, { sessionId, initializedAt: now });
118
+ sessionCache.set(key, { sessionId, initializedAt: now });
104
119
  return sessionId;
105
120
  }
106
121
 
@@ -108,41 +123,62 @@ async function ensureSession(url, signal) {
108
123
  * Parse MCP response envelope - handles both SSE and plain JSON.
109
124
  * @returns {object} { id, result?, error? }
110
125
  */
111
- function parseEnvelope(text, expectedId) {
112
- // Try SSE format first: "event: message\ndata: {...}\n\n"
113
- if (text.includes("data:")) {
114
- // SSE spec: one JSON payload may span multiple data: lines - join them.
115
- const joined = text
116
- .trim()
117
- .split("\n")
118
- .filter((l) => l.startsWith("data:"))
119
- .map((l) => l.slice(5).trim())
120
- .join("");
121
- if (joined) {
122
- try {
123
- return JSON.parse(joined);
124
- } catch {}
126
+ export function parseEnvelope(text, expectedId) {
127
+ // Strip a UTF-8 BOM: some MCP servers prepend it to the first SSE line,
128
+ // which would otherwise make the leading `data:` invisible to the split.
129
+ const body = text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
130
+ // SSE: split into events on blank lines, parse each event's data lines, and
131
+ // pick the frame whose id matches the request and carries result/error.
132
+ // Joining all data lines across events produced "{...}{...}" and failed
133
+ // whenever a server pushed a notification before the actual response.
134
+ if (body.includes("data:")) {
135
+ for (const event of body.split(/\r?\n\r?\n/)) {
136
+ const joined = event
137
+ .split("\n")
138
+ .filter((l) => l.startsWith("data:"))
139
+ .map((l) => l.slice(5).trim())
140
+ .join("");
141
+ if (!joined) continue;
142
+ let frame;
143
+ try { frame = JSON.parse(joined); } catch { continue; }
144
+ const candidates = Array.isArray(frame) ? frame : [frame];
145
+ const match = candidates.find((r) => r && String(r.id) === String(expectedId)
146
+ && (r.result !== undefined || r.error !== undefined));
147
+ if (match) return match;
125
148
  }
126
149
  }
127
-
128
- // Try plain JSON (single line or JSON-RPC batch)
150
+
151
+ // Plain JSON (single line or JSON-RPC batch). An explicit id that differs
152
+ // from the request is a different response and must not be handed to this
153
+ // caller; a missing id is tolerated for JSON-RPC notification-style replies.
154
+ let parsed;
129
155
  try {
130
- const parsed = JSON.parse(text);
131
- if (Array.isArray(parsed)) {
132
- // Batch response - find matching id
133
- return parsed.find((r) => r.id === expectedId) ?? parsed[0];
156
+ parsed = JSON.parse(body);
157
+ } catch {
158
+ throw new WebError("MCP: failed to parse response envelope", "WEB_PROVIDER_ERROR");
159
+ }
160
+ if (Array.isArray(parsed)) {
161
+ const match = parsed.find((r) => String(r.id) === String(expectedId));
162
+ if (match) return match;
163
+ // A batch that only carries frames for other requests must not hand its
164
+ // first frame to this caller; the object path already rejects that case.
165
+ if (parsed.some((r) => r && r.id !== undefined && String(r.id) !== String(expectedId))) {
166
+ throw new WebError("MCP: response id does not match the request", "WEB_PROVIDER_ERROR");
134
167
  }
135
- return parsed;
136
- } catch {}
137
-
138
- throw new WebError("MCP: failed to parse response envelope", "WEB_PROVIDER_ERROR");
168
+ return parsed[0];
169
+ }
170
+ if (parsed && typeof parsed === "object" && parsed.id !== undefined
171
+ && String(parsed.id) !== String(expectedId)) {
172
+ throw new WebError("MCP: response id does not match the request", "WEB_PROVIDER_ERROR");
173
+ }
174
+ return parsed;
139
175
  }
140
176
 
141
177
  /**
142
178
  * Invalidate cached session for a URL (call on 401/403/404).
143
179
  */
144
- export function invalidateSession(url) {
145
- sessionCache.delete(url);
180
+ export function invalidateSession(url, extraHeaders) {
181
+ sessionCache.delete(sessionCacheKey(url, extraHeaders));
146
182
  }
147
183
 
148
184
  /**
@@ -152,14 +188,25 @@ export function invalidateSession(url) {
152
188
  * @param {object} args - Tool arguments
153
189
  * @param {object} extraHeaders - Additional headers
154
190
  * @param {AbortSignal} signal - Abort signal
191
+ * @param {{ skipInitialize?: boolean, forceFreshSession?: boolean }} [options] - Per-call transport options.
192
+ * `skipInitialize` sends a direct tools/call for stateless endpoints that
193
+ * do not need a session: TinyFish keyless, Exa, Parallel, Firecrawl (per
194
+ * the official websearch provider's single tools/call). `forceFreshSession`
195
+ * bypasses the URL-keyed session cache so a rotated credential cannot reuse
196
+ * a stale Mcp-Session-Id. Keyed calls use the handshake and a fresh session.
155
197
  * @returns {Promise<object>} Parsed result envelope
156
198
  */
157
- export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
158
- const sessionId = await ensureSession(url, signal);
199
+ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal, options = {}) {
200
+ // The session handshake is the default; stateless keyless servers accept a
201
+ // direct tools/call and skip it.
202
+ const sessionId = options.skipInitialize ? undefined : await ensureSession(url, signal, { forceFreshSession: options.forceFreshSession === true }, extraHeaders);
159
203
 
160
204
  const callBody = {
161
205
  jsonrpc: "2.0",
162
- id: 2, // increment from initialize(1)
206
+ // initialize uses id 1. Keep every tools/call away from it so a shared
207
+ // SSE stream cannot hand an initialize-shaped frame to a search caller.
208
+ // Sessionful and stateless calls also use distinct ids from each other.
209
+ id: options.skipInitialize ? 2 : 3,
163
210
  method: "tools/call",
164
211
  params: { name: toolName, arguments: args },
165
212
  };
@@ -171,6 +218,7 @@ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
171
218
  headers: {
172
219
  "Content-Type": "application/json",
173
220
  "Accept": "application/json, text/event-stream",
221
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
174
222
  ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
175
223
  "User-Agent": UA,
176
224
  ...extraHeaders,
@@ -187,15 +235,16 @@ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
187
235
  // On 401/403/404 with a sessionful server, invalidate and retry once.
188
236
  // Stateless servers (no session id) have no session to invalidate — fail loud.
189
237
  if (sessionId && (response.status === 401 || response.status === 403 || response.status === 404)) {
190
- invalidateSession(url);
191
- // Retry with fresh session
192
- const newSessionId = await ensureSession(url, signal);
238
+ invalidateSession(url, extraHeaders);
239
+ // Retry with fresh session, retaining the same credential headers.
240
+ const newSessionId = await ensureSession(url, signal, {}, extraHeaders);
193
241
  try {
194
242
  response = await egressFetch(url, {
195
243
  method: "POST",
196
244
  headers: {
197
245
  "Content-Type": "application/json",
198
246
  "Accept": "application/json, text/event-stream",
247
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
199
248
  ...(newSessionId ? { "Mcp-Session-Id": newSessionId } : {}),
200
249
  "User-Agent": UA,
201
250
  ...extraHeaders,
@@ -212,7 +261,7 @@ export async function mcpCall(url, toolName, args, extraHeaders = {}, signal) {
212
261
 
213
262
  if (!response.ok) {
214
263
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
215
- throw new WebError(`MCP tools/call HTTP ${response.status}: ${text}`, "WEB_PROVIDER_ERROR");
264
+ throw webErrorFromResponse(response, text, "MCP tools/call");
216
265
  }
217
266
 
218
267
  const text = await response.text();
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Locate this plugin's row in a settings `describe()` result.
3
+ *
4
+ * DSH 0.2.x keys namespaces by the profile entry id (`entry.options.id`),
5
+ * which for this plugin is `dsh-websearch`. Older hosts used the settings
6
+ * NAMESPACE `unified-search`. A host may expose several namespaces with
7
+ * generic field names such as `numResults`, so a shape-only match can select
8
+ * another plugin's row and make a write land in the wrong namespace.
9
+ * Prefer the exact ids; only fall back to the shape when neither id is
10
+ * present, and require at least two plugin-specific fields in that case.
11
+ *
12
+ * @param {unknown} rows - `settings.describe()` output.
13
+ * @returns {object|undefined} the matching row (with `.value`).
14
+ */
15
+ const PROFILE_ID = "dsh-websearch";
16
+ const LEGACY_ID = "unified-search";
17
+ const SHAPE_FIELDS = ["searxngBaseURL", "enableFirecrawl", "firecrawlBaseURL", "enableTinyfish", "tinyfishBaseURL"];
18
+
19
+ export function findPluginRow(rows) {
20
+ if (!Array.isArray(rows)) return undefined;
21
+ const candidates = rows.filter((row) => row !== null && typeof row === "object" && typeof row.ns === "string");
22
+ const byId = candidates.find((row) => row.ns === PROFILE_ID)
23
+ ?? candidates.find((row) => row.ns === LEGACY_ID);
24
+ if (byId) return byId;
25
+ return candidates.find((row) => row.value !== undefined && row.value !== null
26
+ && typeof row.value === "object"
27
+ && SHAPE_FIELDS.filter((key) => Object.hasOwn(row.value, key)).length >= 2);
28
+ }
package/lib/util/rank.js CHANGED
@@ -16,8 +16,12 @@ export function tokenize(text) {
16
16
  const tokens = new Set();
17
17
  if (typeof text !== "string" || text.length === 0) return tokens;
18
18
  const lower = text.toLowerCase();
19
- // ASCII word runs of length >= 2 ...
20
- for (const w of lower.match(/[a-z0-9]{2,}/g) ?? []) tokens.add(w);
19
+ // ASCII word runs of length >= 2, plus every digit run: single digits are
20
+ // version discriminators ("GPT-4" vs "GPT-5"), and dropping them made
21
+ // url+title dedupe merge different versions and made rerank blind to them.
22
+ for (const w of lower.match(/[a-z0-9]+/g) ?? []) {
23
+ if (w.length >= 2 || /^\d+$/.test(w)) tokens.add(w);
24
+ }
21
25
  // ... plus individual CJK chars (U+3400-U+9FFF common range covers CJK).
22
26
  for (const ch of lower.match(/[\u3400-\u9fff]/g) ?? []) tokens.add(ch);
23
27
  return tokens;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Credential redaction for text that leaves the plugin.
3
+ *
4
+ * Backends forward upstream error bodies, and providers sometimes echo the
5
+ * presented key back ("Incorrect API key provided: sk-live-…"). That text
6
+ * reaches the host log, the health/history payload, the telemetry line, and
7
+ * the model-visible failure message; none of those may carry a key.
8
+ *
9
+ * @module lib/util/redact
10
+ */
11
+
12
+ /** Token shapes we can recognise without knowing the issuing vendor. */
13
+ const SECRET_PATTERNS = [
14
+ /sk-[A-Za-z0-9_-]{8,}/g,
15
+ /tvly-[A-Za-z0-9_-]{8,}/g,
16
+ /BSA[A-Za-z0-9_-]{16,}/g,
17
+ /exa_[A-Za-z0-9_-]{8,}/g,
18
+ /ghp_[A-Za-z0-9]{16,}/g,
19
+ /github_pat_[A-Za-z0-9_]{16,}/g,
20
+ /npm_[A-Za-z0-9]{16,}/g,
21
+ /cfut_[A-Za-z0-9_-]{16,}/g,
22
+ /Bearer\s+[A-Za-z0-9._-]{8,}/gi,
23
+ /(api[_-]?key|token|secret|password)\s*[=:]\s*["']?[^\s"',]{6,}/gi,
24
+ ];
25
+
26
+ /**
27
+ * Replace token-like fragments with `[redacted]`.
28
+ *
29
+ * @param {unknown} value - text to sanitize; non-strings stringify first.
30
+ * @returns {string} redacted text.
31
+ */
32
+ export function redact(value) {
33
+ let text = value instanceof Error ? value.message : String(value ?? "");
34
+ for (const pattern of SECRET_PATTERNS) text = text.replace(pattern, "[redacted]");
35
+ return text;
36
+ }
37
+
38
+ /**
39
+ * Redact, collapse whitespace, and bound length for diagnostics/UI.
40
+ *
41
+ * @param {unknown} value - error or text to sanitize.
42
+ * @param {number} [maxChars] - maximum output length.
43
+ * @returns {string} safe, bounded text.
44
+ */
45
+ export function sanitizeError(value, maxChars = 120) {
46
+ if (value === null || value === undefined) return "";
47
+ const text = redact(value).replace(/\s+/g, " ").trim();
48
+ return text.length > maxChars ? text.slice(0, maxChars) : text;
49
+ }
@@ -0,0 +1,49 @@
1
+ // web-error.js — shared HTTP-failure constructor for the unified search
2
+ // provider. WebError (published dsh-web) extends HarnessError, whose
3
+ // constructor consumes only `cause`; extra fields must be assigned after
4
+ // construction. Keeping that in one place preserves `instanceof WebError`
5
+ // and the cause chain while giving the breaker machine-routable fields.
6
+
7
+ import { WebError } from "@deepseek-ai/dsh-web";
8
+
9
+ /** Canonical codes from dsh-llm/lib/types/error.js (RATE_LIMIT example, QUOTA_EXCEEDED_CODE). */
10
+ export const RATE_LIMIT_CODE = "RATE_LIMIT";
11
+ export const QUOTA_CODE = "QUOTA";
12
+
13
+ function headerValue(response, name) {
14
+ try { return response?.headers?.get?.(name) ?? undefined; } catch { return undefined; }
15
+ }
16
+
17
+ /**
18
+ * Build a WebError from a non-2xx Response. egressFetch already constructs a
19
+ * Response with status + full headers, so Retry-After is reachable here.
20
+ * @param {Response} response - the non-2xx response.
21
+ * @param {string} text - already-bounded upstream body.
22
+ * @param {string} label - backend name for the human-readable message.
23
+ * @param {{cause?: unknown}} [opts] - optional underlying error.
24
+ * @returns {WebError} error carrying status, retryAfter, rateLimited and code.
25
+ */
26
+ export function webErrorFromResponse(response, text, label, opts = {}) {
27
+ const status = Number(response?.status) || 0;
28
+ const retryAfter = headerValue(response, "retry-after");
29
+ const rateLimited = status === 429;
30
+ // 402 is an explicit payment/quota signal. 403 is ambiguous (invalid key,
31
+ // forbidden, or quota) so it must NOT be classified as quota here; treating
32
+ // every 403 as quota would cool a backend for a bad credential.
33
+ const quota = status === 402;
34
+ const code = rateLimited ? RATE_LIMIT_CODE
35
+ : quota ? QUOTA_CODE
36
+ : "WEB_PROVIDER_ERROR";
37
+ const message = `${label} API error (HTTP ${status}): ${String(text ?? "").slice(0, 140)}`;
38
+ const err = new WebError(
39
+ message,
40
+ code,
41
+ opts.cause === undefined ? undefined : { cause: opts.cause },
42
+ );
43
+ // HarnessError `super(message, options)` only accepts cause; attach the rest.
44
+ err.status = status;
45
+ err.retryAfter = retryAfter;
46
+ err.rateLimited = rateLimited;
47
+ err.quota = quota;
48
+ return err;
49
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@240xu/dsh-websearch",
3
- "version": "2.8.7",
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.",
3
+ "version": "2.8.9",
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",
7
7
  "exports": {
@@ -9,8 +9,7 @@
9
9
  "default": "./lib/index.js"
10
10
  },
11
11
  "./package.json": "./package.json",
12
- "./client": "./lib/client.js",
13
- "./config": "./lib/config.js"
12
+ "./client": "./lib/client.js"
14
13
  },
15
14
  "files": [
16
15
  "lib",
package/lib/config.js DELETED
@@ -1,205 +0,0 @@
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 };