@240xu/dsh-websearch 2.8.8 → 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.
- package/README.md +56 -25
- package/lib/backends/anthropic-like.js +11 -7
- package/lib/backends/brave.js +4 -2
- package/lib/backends/ddg.js +27 -11
- package/lib/backends/exa.js +3 -1
- package/lib/backends/firecrawl.js +127 -0
- package/lib/backends/mojeek.js +4 -2
- package/lib/backends/openai.js +12 -7
- package/lib/backends/parallel.js +2 -20
- package/lib/backends/searxng.js +36 -8
- package/lib/backends/serper.js +4 -2
- package/lib/backends/tavily.js +4 -2
- package/lib/backends/tinyfish.js +124 -0
- package/lib/breaker.js +25 -4
- package/lib/cache.js +30 -3
- package/lib/client.js +564 -182
- package/lib/health.js +20 -17
- package/lib/history.js +26 -36
- package/lib/index.js +157 -62
- package/lib/prompting.js +13 -3
- package/lib/provider.js +273 -78
- package/lib/rrf.js +9 -4
- package/lib/settings-api.js +44 -30
- package/lib/trust.js +6 -0
- package/lib/util/base-url.js +56 -0
- package/lib/util/egress-fetch.js +163 -12
- package/lib/util/failure-label.js +73 -12
- package/lib/util/log.js +5 -3
- package/lib/util/mcp-client.js +89 -40
- package/lib/util/namespace.js +28 -0
- package/lib/util/rank.js +6 -2
- package/lib/util/redact.js +49 -0
- package/lib/util/web-error.js +49 -0
- package/package.json +2 -2
package/lib/health.js
CHANGED
|
@@ -7,28 +7,18 @@
|
|
|
7
7
|
// provider's own telemetry truncation) and run through a defensive redaction
|
|
8
8
|
// pass for token-like fragments.
|
|
9
9
|
|
|
10
|
-
import { rejectionFor } from "./trust.js";
|
|
10
|
+
import { rejectionFor, rejectionBody } from "./trust.js";
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
import { sanitizeError as redactError } from "./util/redact.js";
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
const SECRET_PATTERNS = [
|
|
16
|
-
/sk-[A-Za-z0-9_-]{8,}/g,
|
|
17
|
-
/Bearer\s+[A-Za-z0-9._-]{8,}/gi,
|
|
18
|
-
/(api[_-]?key|token|secret|password)\s*[=:]\s*\S{6,}/gi,
|
|
19
|
-
];
|
|
14
|
+
const MAX_ERROR_CHARS = 120;
|
|
20
15
|
|
|
21
16
|
/**
|
|
22
17
|
* Truncate + redact an error string for safe display.
|
|
23
18
|
* Returns "" for falsy input; length bounded to 40-120 chars.
|
|
24
19
|
*/
|
|
25
20
|
export function sanitizeError(err) {
|
|
26
|
-
|
|
27
|
-
let s = String(err instanceof Error ? err.message : err);
|
|
28
|
-
for (const re of SECRET_PATTERNS) s = s.replace(re, "[redacted]");
|
|
29
|
-
s = s.replace(/\s+/g, " ").trim();
|
|
30
|
-
if (s.length > MAX_ERROR_CHARS) s = s.slice(0, MAX_ERROR_CHARS);
|
|
31
|
-
return s;
|
|
21
|
+
return redactError(err, MAX_ERROR_CHARS);
|
|
32
22
|
}
|
|
33
23
|
|
|
34
24
|
/**
|
|
@@ -60,6 +50,14 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
|
|
|
60
50
|
id,
|
|
61
51
|
enabled,
|
|
62
52
|
keyless,
|
|
53
|
+
optionalKey: beOpts.optionalKey === true,
|
|
54
|
+
metered: beOpts.metered === true,
|
|
55
|
+
// Observability: expose the breaker classification so callers can tell
|
|
56
|
+
// a quota cooldown from an ordinary outage or a missing key without
|
|
57
|
+
// parsing lastError. Additive fields; existing keys keep their meaning.
|
|
58
|
+
rateLimited: t?.rateLimited === true,
|
|
59
|
+
keylessRejected: t?.keylessRejected === true,
|
|
60
|
+
cooledUntilMs: Number.isFinite(t?.cooledUntil) && t.cooledUntil > 0 ? t.cooledUntil : null,
|
|
63
61
|
// reachable: true/false from the latest search telemetry; null = never probed.
|
|
64
62
|
reachable: t ? t.ok === true : null,
|
|
65
63
|
lastOk: t && typeof t.lastOkAt === "number" ? t.lastOkAt : null,
|
|
@@ -72,6 +70,10 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
|
|
|
72
70
|
ok: true,
|
|
73
71
|
enabled: enabledList.length,
|
|
74
72
|
keyless: enabledList.filter((b) => b.keyless).length,
|
|
73
|
+
// The deployment cap and the user's numResults combine as
|
|
74
|
+
// min(hostCap, userMax) in provider.search(); expose the user value here
|
|
75
|
+
// so an observer can explain why a search returned fewer results.
|
|
76
|
+
requestedMaxResults: Number.isFinite(opts.numResults) ? opts.numResults : null,
|
|
75
77
|
backends: list,
|
|
76
78
|
updatedAt: Date.now(),
|
|
77
79
|
};
|
|
@@ -82,8 +84,8 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
|
|
|
82
84
|
* GET only; never probes backends; response is JSON with no credentials.
|
|
83
85
|
*/
|
|
84
86
|
export function registerHealthRoute(ws, deps) {
|
|
85
|
-
if (!ws || typeof ws.register !== "function") return;
|
|
86
|
-
ws.register({
|
|
87
|
+
if (!ws || typeof ws.register !== "function") return [];
|
|
88
|
+
const disposer = ws.register({
|
|
87
89
|
kind: "exact",
|
|
88
90
|
path: "/api/unified-search/health",
|
|
89
91
|
handler: (req, res) => {
|
|
@@ -93,7 +95,7 @@ export function registerHealthRoute(ws, deps) {
|
|
|
93
95
|
};
|
|
94
96
|
const rejection = rejectionFor(req, typeof deps.getConnection === "function" ? deps.getConnection() : undefined);
|
|
95
97
|
if (rejection !== undefined) {
|
|
96
|
-
send(rejection,
|
|
98
|
+
send(rejection, rejectionBody(rejection));
|
|
97
99
|
return;
|
|
98
100
|
}
|
|
99
101
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
@@ -107,4 +109,5 @@ export function registerHealthRoute(ws, deps) {
|
|
|
107
109
|
}
|
|
108
110
|
},
|
|
109
111
|
});
|
|
112
|
+
return typeof disposer === "function" ? [disposer] : [];
|
|
110
113
|
}
|
package/lib/history.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
10
|
import path from "node:path";
|
|
11
|
-
import { rejectionFor } from "./trust.js";
|
|
11
|
+
import { rejectionFor, rejectionBody } from "./trust.js";
|
|
12
12
|
|
|
13
13
|
/** Ring-buffer cap (spec: 50). */
|
|
14
14
|
export const HISTORY_MAX_ENTRIES = 50;
|
|
@@ -82,40 +82,21 @@ export function createHistoryStore({ dir, maxEntries = HISTORY_MAX_ENTRIES }) {
|
|
|
82
82
|
return readAll().slice(0, cap).map(toPublicEntry);
|
|
83
83
|
},
|
|
84
84
|
|
|
85
|
-
/** Empty the history (
|
|
85
|
+
/** Empty the history. Serialised with record() so a pending append cannot
|
|
86
|
+
* resurrect an entry after the clear. */
|
|
86
87
|
clear() {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
88
|
+
writeChain = writeChain.then(() => {
|
|
89
|
+
try {
|
|
90
|
+
if (existsSync(file())) unlinkSync(file());
|
|
91
|
+
} catch {
|
|
92
|
+
// nothing to do
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return writeChain;
|
|
92
96
|
},
|
|
93
97
|
};
|
|
94
98
|
}
|
|
95
99
|
|
|
96
|
-
/**
|
|
97
|
-
* Minimal trust fence for plugin-registered routes (the host /api RPC fence
|
|
98
|
-
* does not cover webServer.register paths): require a loopback Host (blocks
|
|
99
|
-
* DNS rebinding) and a same-site browser context (sec-fetch-site same-origin
|
|
100
|
-
* / none, or an Origin whose host matches the request Host — blocks
|
|
101
|
-
* cross-site CSRF including text/plain preflight-less POSTs).
|
|
102
|
-
* Returns null when trusted, otherwise a short rejection reason.
|
|
103
|
-
*/
|
|
104
|
-
export function isTrustedApiRequest(req) {
|
|
105
|
-
const host = String(req?.headers?.host ?? "");
|
|
106
|
-
const hostOk = /^(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])(:\d+)?$/.test(host);
|
|
107
|
-
if (!hostOk) return "untrusted host";
|
|
108
|
-
const site = req?.headers?.["sec-fetch-site"];
|
|
109
|
-
if (site === "same-origin" || site === "none") return null;
|
|
110
|
-
const origin = req?.headers?.origin;
|
|
111
|
-
if (!origin) return site !== undefined ? "cross-site request" : null;
|
|
112
|
-
try {
|
|
113
|
-
return new URL(origin).host === host ? null : "cross-origin request";
|
|
114
|
-
} catch {
|
|
115
|
-
return "invalid origin";
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
100
|
/**
|
|
120
101
|
* Project the module-level backend health map into a small observability
|
|
121
102
|
* payload (v2.8.0 P2): per-backend last real success/failure, latency and
|
|
@@ -132,6 +113,9 @@ export function toBackendObservability(healthMap, nowMs = Date.now()) {
|
|
|
132
113
|
at: Number.isFinite(e?.at) ? e.at : null,
|
|
133
114
|
failCount: Number.isFinite(e?.failCount) ? e.failCount : 0,
|
|
134
115
|
cooled: Number.isFinite(e?.cooledUntil) && e.cooledUntil > nowMs,
|
|
116
|
+
cooledUntilMs: Number.isFinite(e?.cooledUntil) && e.cooledUntil > 0 ? e.cooledUntil : null,
|
|
117
|
+
rateLimited: e?.rateLimited === true,
|
|
118
|
+
keylessRejected: e?.keylessRejected === true,
|
|
135
119
|
});
|
|
136
120
|
}
|
|
137
121
|
}
|
|
@@ -148,7 +132,7 @@ export function toBackendObservability(healthMap, nowMs = Date.now()) {
|
|
|
148
132
|
* decision the kernel applies to its own /api routes).
|
|
149
133
|
*/
|
|
150
134
|
export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConnection }) {
|
|
151
|
-
if (!ws || typeof ws.register !== "function") return;
|
|
135
|
+
if (!ws || typeof ws.register !== "function") return [];
|
|
152
136
|
const send = (res, code, body) => {
|
|
153
137
|
res.writeHead(code, { "content-type": "application/json" });
|
|
154
138
|
res.end(JSON.stringify(body));
|
|
@@ -156,12 +140,12 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
|
|
|
156
140
|
const guarded = (handler) => (req, res) => {
|
|
157
141
|
const rejection = rejectionFor(req, typeof getConnection === "function" ? getConnection() : undefined);
|
|
158
142
|
if (rejection !== undefined) {
|
|
159
|
-
send(res, rejection,
|
|
143
|
+
send(res, rejection, rejectionBody(rejection));
|
|
160
144
|
return;
|
|
161
145
|
}
|
|
162
146
|
handler(req, res);
|
|
163
147
|
};
|
|
164
|
-
ws.register({
|
|
148
|
+
const disposerA = ws.register({
|
|
165
149
|
kind: "exact",
|
|
166
150
|
path: "/api/websearch/history",
|
|
167
151
|
handler: guarded((req, res) => {
|
|
@@ -177,7 +161,7 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
|
|
|
177
161
|
});
|
|
178
162
|
}),
|
|
179
163
|
});
|
|
180
|
-
ws.register({
|
|
164
|
+
const disposerB = ws.register({
|
|
181
165
|
kind: "exact",
|
|
182
166
|
path: "/api/websearch/history/clear",
|
|
183
167
|
handler: guarded((req, res) => {
|
|
@@ -186,8 +170,14 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
|
|
|
186
170
|
return;
|
|
187
171
|
}
|
|
188
172
|
const store = getStore();
|
|
189
|
-
|
|
190
|
-
|
|
173
|
+
// clear() is serialised behind the write chain, so the 200 must wait for
|
|
174
|
+
// it: otherwise the client's next GET can still see the old entries.
|
|
175
|
+
const cleared = store?.clear();
|
|
176
|
+
Promise.resolve(cleared).then(
|
|
177
|
+
() => send(res, 200, { ok: true, cleared: true }),
|
|
178
|
+
() => send(res, 500, { ok: false, error: "clear failed" }),
|
|
179
|
+
);
|
|
191
180
|
}),
|
|
192
181
|
});
|
|
182
|
+
return [disposerA, disposerB].filter((d) => typeof d === "function");
|
|
193
183
|
}
|
package/lib/index.js
CHANGED
|
@@ -18,6 +18,7 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
|
18
18
|
// plain string "unified-search". No import needed anymore.
|
|
19
19
|
import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
|
|
20
20
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
21
|
+
import { findPluginRow } from "./util/namespace.js";
|
|
21
22
|
|
|
22
23
|
// Import all backends
|
|
23
24
|
import { exaBackend } from "./backends/exa.js";
|
|
@@ -33,6 +34,9 @@ import { tavilyBackend } from "./backends/tavily.js";
|
|
|
33
34
|
import { serperBackend } from "./backends/serper.js";
|
|
34
35
|
import { searxngBackend } from "./backends/searxng.js";
|
|
35
36
|
import { mojeekBackend } from "./backends/mojeek.js";
|
|
37
|
+
// OpenCode v2 keyless MCP backends.
|
|
38
|
+
import { firecrawlBackend } from "./backends/firecrawl.js";
|
|
39
|
+
import { tinyfishBackend } from "./backends/tinyfish.js";
|
|
36
40
|
import { createUnifiedSearchProvider, getLatestBackendHealth } from "./provider.js";
|
|
37
41
|
import { registerHealthRoute } from "./health.js";
|
|
38
42
|
import { createSearchCache, CACHE_DEFAULTS } from "./cache.js";
|
|
@@ -63,12 +67,19 @@ const BACKENDS = {
|
|
|
63
67
|
deepseek: deepseekBackend,
|
|
64
68
|
anthropic: anthropicBackend,
|
|
65
69
|
openai: openaiBackend,
|
|
70
|
+
// Appended last so default fan-out order is unchanged.
|
|
71
|
+
// Both are opt-in (not in DEFAULT_ENABLED): their keyless tiers are metered
|
|
72
|
+
// and Firecrawl's exact daily ceiling is not published by the vendor.
|
|
73
|
+
firecrawl: firecrawlBackend,
|
|
74
|
+
tinyfish: tinyfishBackend,
|
|
66
75
|
};
|
|
67
76
|
|
|
68
77
|
/** All backend ids in registry order. */
|
|
69
78
|
const ALL_BACKENDS = Object.keys(BACKENDS);
|
|
70
79
|
|
|
71
80
|
/** Backends enabled by default (keyless only). */
|
|
81
|
+
// Firecrawl/TinyFish are intentionally absent here — enable them
|
|
82
|
+
// explicitly via the Settings toggles once their keyless quotas are reviewed.
|
|
72
83
|
const DEFAULT_ENABLED = ["exa", "parallel", "ddg", "searxng"];
|
|
73
84
|
|
|
74
85
|
/** Environment-variable names each key-gated backend reads. */
|
|
@@ -80,8 +91,16 @@ const DEFAULT_KEY_ENV = {
|
|
|
80
91
|
tavily: "TAVILY_API_KEY",
|
|
81
92
|
serper: "SERPER_API_KEY",
|
|
82
93
|
mojeek: "MOJEEK_API_KEY",
|
|
94
|
+
// Optional keys; keyless works without them.
|
|
95
|
+
firecrawl: "FIRECRAWL_API_KEY",
|
|
96
|
+
tinyfish: "TINYFISH_API_KEY",
|
|
83
97
|
};
|
|
84
98
|
|
|
99
|
+
/** Backends whose key only raises the hosted tier's limits, not a prerequisite. */
|
|
100
|
+
const OPTIONAL_KEY_IDS = new Set(["searxng", "firecrawl", "tinyfish"]);
|
|
101
|
+
/** Metered, opt-in backends surfaced separately in the card. */
|
|
102
|
+
const METERED_IDS = new Set(["firecrawl", "tinyfish"]);
|
|
103
|
+
|
|
85
104
|
/** Default base URLs. */
|
|
86
105
|
const DEFAULT_BASE_URLS = {
|
|
87
106
|
exa: "https://mcp.exa.ai/mcp",
|
|
@@ -95,6 +114,10 @@ const DEFAULT_BASE_URLS = {
|
|
|
95
114
|
deepseek: "https://api.deepseek.com/anthropic/v1",
|
|
96
115
|
anthropic: "https://api.anthropic.com/v1",
|
|
97
116
|
openai: "https://api.openai.com/v1",
|
|
117
|
+
// OpenCode v2 source endpoints; overridable via the
|
|
118
|
+
// matching *BaseURL settings so a TLS-fingerprint sidecar can be pointed at.
|
|
119
|
+
firecrawl: "https://mcp.firecrawl.dev/v2/mcp",
|
|
120
|
+
tinyfish: "https://agent.tinyfish.ai/mcp",
|
|
98
121
|
};
|
|
99
122
|
|
|
100
123
|
/** Env var that overrides the default backend sweep order / enabled set. */
|
|
@@ -122,6 +145,10 @@ const DEFAULT_LABELS = {
|
|
|
122
145
|
deepseek: "DeepSeek (原生 web_search, 需 Key)",
|
|
123
146
|
anthropic: "Anthropic (Claude 原生 web_search, 需 Key)",
|
|
124
147
|
openai: "OpenAI (Responses API web_search, 需 Key)",
|
|
148
|
+
// Labels surfaced in the Settings panel; the keyless tier is rate limited,
|
|
149
|
+
// which is why both toggles default to off.
|
|
150
|
+
firecrawl: "Firecrawl (MCP, keyless with quota, off by default)",
|
|
151
|
+
tinyfish: "TinyFish (MCP, keyless 30/min and 50/day, off by default)",
|
|
125
152
|
};
|
|
126
153
|
|
|
127
154
|
/**
|
|
@@ -132,8 +159,10 @@ const DEFAULT_LABELS = {
|
|
|
132
159
|
*/
|
|
133
160
|
export const Config = z.object({
|
|
134
161
|
// Global
|
|
135
|
-
|
|
136
|
-
.description("
|
|
162
|
+
intervention: z.union(["official", "balanced", "thorough"]).default("balanced")
|
|
163
|
+
.description("搜索介入程度【策略】:official=只做官方 provider 该做的(原样查询、不加结果头/遥测、沿用工具的条数上限);balanced=确定性去噪 + 去重/遥测(默认);thorough=额外启用相关性重排与深度覆盖(内部多查询仍是独立开关,默认关)"),
|
|
164
|
+
numResults: z.number().step(1).min(1).max(50).default(10)
|
|
165
|
+
.description("每次搜索返回的最大结果数(official 档沿用宿主工具的条数上限)"),
|
|
137
166
|
concurrency: z.number().step(1).min(1).max(10).default(6)
|
|
138
167
|
.description("同时并发的后端数量"),
|
|
139
168
|
backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(30000)
|
|
@@ -188,24 +217,33 @@ export const Config = z.object({
|
|
|
188
217
|
enableDeepseek: z.boolean().default(false).description(DEFAULT_LABELS.deepseek),
|
|
189
218
|
enableAnthropic: z.boolean().default(false).description(DEFAULT_LABELS.anthropic),
|
|
190
219
|
enableOpenai: z.boolean().default(false).description(DEFAULT_LABELS.openai),
|
|
220
|
+
// Opt-in by default; see DEFAULT_ENABLED comment.
|
|
221
|
+
enableFirecrawl: z.boolean().default(false).description(DEFAULT_LABELS.firecrawl),
|
|
222
|
+
enableTinyfish: z.boolean().default(false).description(DEFAULT_LABELS.tinyfish),
|
|
191
223
|
|
|
192
224
|
// Credential refs (env-var names; secrets live in the credentials service)
|
|
193
|
-
braveApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.brave)
|
|
225
|
+
braveApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.brave)
|
|
194
226
|
.description("Brave API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
195
|
-
tavilyApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.tavily)
|
|
227
|
+
tavilyApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.tavily)
|
|
196
228
|
.description("Tavily API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
197
|
-
serperApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.serper)
|
|
229
|
+
serperApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.serper)
|
|
198
230
|
.description("Serper API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
199
|
-
mojeekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.mojeek)
|
|
231
|
+
mojeekApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.mojeek)
|
|
200
232
|
.description("Mojeek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
201
|
-
deepseekApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.deepseek)
|
|
233
|
+
deepseekApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.deepseek)
|
|
202
234
|
.description("Deepseek API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
203
|
-
anthropicApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.anthropic)
|
|
235
|
+
anthropicApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.anthropic)
|
|
204
236
|
.description("Anthropic API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
205
|
-
openaiApiKeyEnv: z.string().role("credential-ref").default(DEFAULT_KEY_ENV.openai)
|
|
237
|
+
openaiApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.openai)
|
|
206
238
|
.description("Openai API Key 的凭证引用(填环境变量名,实际密钥存凭证库)"),
|
|
207
|
-
searxngApiKeyEnv: z.string().role("credential-ref").default("SEARXNG_API_KEY")
|
|
239
|
+
searxngApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default("SEARXNG_API_KEY")
|
|
208
240
|
.description("SearXNG 私有实例的 API Key 凭证引用(公共实例留空)"),
|
|
241
|
+
// Optional: both backends work keyless. Supplying a key only raises the
|
|
242
|
+
// hosted tier's limits (and for TinyFish activates the session handshake).
|
|
243
|
+
firecrawlApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.firecrawl)
|
|
244
|
+
.description("Firecrawl API key credential reference (optional; blank uses the hosted keyless tier)"),
|
|
245
|
+
tinyfishApiKeyEnv: z.string().role("credential-ref").pattern(/^[A-Za-z_][A-Za-z0-9_]*$/).min(1).default(DEFAULT_KEY_ENV.tinyfish)
|
|
246
|
+
.description("TinyFish API key credential reference (optional; blank uses keyless mode)"),
|
|
209
247
|
|
|
210
248
|
// Base URLs (defaults from built-in registry)
|
|
211
249
|
braveBaseURL: z.string().default(DEFAULT_BASE_URLS.brave)
|
|
@@ -226,6 +264,12 @@ export const Config = z.object({
|
|
|
226
264
|
.description("Anthropic API 端点(默认官方;自托管/代理实例改此项)"),
|
|
227
265
|
openaiBaseURL: z.string().default(DEFAULT_BASE_URLS.openai)
|
|
228
266
|
.description("OpenAI API 端点(默认官方;自托管/代理实例改此项)"),
|
|
267
|
+
// resolveOptions() derives `${id}BaseURL` for every id, so these two fields
|
|
268
|
+
// are required for the sidecar/proxy path.
|
|
269
|
+
firecrawlBaseURL: z.string().default(DEFAULT_BASE_URLS.firecrawl)
|
|
270
|
+
.description("Firecrawl MCP endpoint (official v2 by default; may point at a TLS sidecar)"),
|
|
271
|
+
tinyfishBaseURL: z.string().default(DEFAULT_BASE_URLS.tinyfish)
|
|
272
|
+
.description("TinyFish MCP endpoint (official by default; may point at a TLS sidecar)"),
|
|
229
273
|
|
|
230
274
|
// Models
|
|
231
275
|
deepseekModel: z.string().default(DEFAULT_MODELS.deepseek)
|
|
@@ -260,6 +304,7 @@ Config.meta = { ...Config.meta, volatile: true };
|
|
|
260
304
|
* provides the field regardless.
|
|
261
305
|
*/
|
|
262
306
|
const FIELD_LABELS = {
|
|
307
|
+
intervention: "搜索介入程度",
|
|
263
308
|
cacheEnabled: "启用搜索结果缓存",
|
|
264
309
|
cacheTtl: "缓存有效期(秒)",
|
|
265
310
|
breakerEnabled: "后端熔断器",
|
|
@@ -281,7 +326,9 @@ for (const [key, label] of Object.entries(FIELD_LABELS)) {
|
|
|
281
326
|
* service -> env.
|
|
282
327
|
*/
|
|
283
328
|
export function resolveOptions(ctx, config) {
|
|
284
|
-
// 1. Determine enabled backends: explicit list > toggles > env > defaults
|
|
329
|
+
// 1. Determine enabled backends: explicit list > toggles > env > defaults.
|
|
330
|
+
// The four keyless toggles default to true, so the env fallback is reachable
|
|
331
|
+
// only when all toggles are explicitly disabled; see README Known Limitation.
|
|
285
332
|
let enabledBackends = [];
|
|
286
333
|
|
|
287
334
|
if (config?.enabledBackends && config.enabledBackends.length > 0) {
|
|
@@ -289,20 +336,9 @@ export function resolveOptions(ctx, config) {
|
|
|
289
336
|
}
|
|
290
337
|
|
|
291
338
|
if (enabledBackends.length === 0) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
ddg: config?.enableDdg,
|
|
296
|
-
searxng: config?.enableSearxng,
|
|
297
|
-
brave: config?.enableBrave,
|
|
298
|
-
tavily: config?.enableTavily,
|
|
299
|
-
serper: config?.enableSerper,
|
|
300
|
-
mojeek: config?.enableMojeek,
|
|
301
|
-
deepseek: config?.enableDeepseek,
|
|
302
|
-
anthropic: config?.enableAnthropic,
|
|
303
|
-
openai: config?.enableOpenai,
|
|
304
|
-
};
|
|
305
|
-
enabledBackends = ALL_BACKENDS.filter((id) => toggleMap[id] === true);
|
|
339
|
+
// The Config schema names each backend's toggle `enable<Capitalized id>`;
|
|
340
|
+
// deriving the key keeps this in sync with BACKENDS automatically.
|
|
341
|
+
enabledBackends = ALL_BACKENDS.filter((id) => config?.[`enable${id.charAt(0).toUpperCase()}${id.slice(1)}`] === true);
|
|
306
342
|
}
|
|
307
343
|
|
|
308
344
|
if (enabledBackends.length === 0) {
|
|
@@ -337,7 +373,9 @@ export function resolveOptions(ctx, config) {
|
|
|
337
373
|
} : {}),
|
|
338
374
|
safeSearch: config?.safeSearch !== false,
|
|
339
375
|
label: DEFAULT_LABELS[id] ?? id,
|
|
340
|
-
requiresKey: DEFAULT_KEY_ENV[id] !== undefined,
|
|
376
|
+
requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
|
|
377
|
+
optionalKey: OPTIONAL_KEY_IDS.has(id),
|
|
378
|
+
metered: METERED_IDS.has(id),
|
|
341
379
|
resolveApiKey: async () => {
|
|
342
380
|
const credentials = ctx.get("credentials");
|
|
343
381
|
if (credentials !== undefined) return (await credentials.resolve(ref))?.value;
|
|
@@ -348,18 +386,33 @@ export function resolveOptions(ctx, config) {
|
|
|
348
386
|
}
|
|
349
387
|
|
|
350
388
|
const language = typeof config?.language === "string" ? config.language.trim() : "";
|
|
389
|
+
// Coarse intervention preset. `balanced` is the historical default and keeps
|
|
390
|
+
// every field independently configurable; `official` removes provider-level
|
|
391
|
+
// rewriting/presentation so the consumer (dsh-tool-web) owns them; `thorough`
|
|
392
|
+
// opts into the expensive stages. Explicit non-default flags still win under
|
|
393
|
+
// `balanced` only — the presets are authoritative by design.
|
|
394
|
+
const intervention = ["official", "balanced", "thorough"].includes(config?.intervention)
|
|
395
|
+
? config.intervention
|
|
396
|
+
: "balanced";
|
|
397
|
+
const official = intervention === "official";
|
|
398
|
+
const thorough = intervention === "thorough";
|
|
351
399
|
|
|
352
400
|
return {
|
|
353
401
|
enabledBackends,
|
|
354
|
-
|
|
402
|
+
intervention,
|
|
403
|
+
queryShaping: !official,
|
|
404
|
+
// official follows the consumer's maxResults bound; the other tiers keep
|
|
405
|
+
// the user's explicit count (and still never exceed the host cap).
|
|
406
|
+
numResults: official ? undefined : (config?.numResults ?? 10),
|
|
355
407
|
concurrency: config?.concurrency ?? 6,
|
|
356
408
|
backendTimeoutMs: config?.backendTimeoutMs ?? 30000,
|
|
357
409
|
// v2.1 shaping options consumed by the provider merge pipeline.
|
|
358
410
|
dedupStrategy: config?.dedupStrategy === "url+title" ? "url+title" : "url",
|
|
359
|
-
rerank: config?.rerank === true,
|
|
360
|
-
|
|
411
|
+
rerank: thorough || (!official && config?.rerank === true),
|
|
412
|
+
resultHeader: official ? false : config?.resultHeader !== false,
|
|
413
|
+
resultTelemetry: official ? false : config?.resultTelemetry !== false,
|
|
361
414
|
// v2.7.0 cache / breaker / history
|
|
362
|
-
cacheEnabled: config?.cacheEnabled
|
|
415
|
+
cacheEnabled: config?.cacheEnabled !== false,
|
|
363
416
|
cacheTtlS: Math.max(30, Math.floor(Number(config?.cacheTtl) || CACHE_DEFAULTS.ttlMs / 1000)),
|
|
364
417
|
breakerEnabled: config?.breakerEnabled !== false,
|
|
365
418
|
breakerThreshold: Math.max(1, Math.floor(Number(config?.breakerThreshold) || BREAKER_DEFAULTS.threshold)),
|
|
@@ -368,8 +421,12 @@ export function resolveOptions(ctx, config) {
|
|
|
368
421
|
: BREAKER_DEFAULTS.cooldownMs,
|
|
369
422
|
historyEnabled: config?.historyEnabled !== false,
|
|
370
423
|
// v2.8.0 coverage / multiQuery
|
|
371
|
-
|
|
372
|
-
|
|
424
|
+
// Internal multi-query stays an explicit opt-in in every tier: the
|
|
425
|
+
// official consumer already lets the model send 1-10 queries per call and
|
|
426
|
+
// merges them round-robin, so a "thorough" preset must not multiply calls
|
|
427
|
+
// invisibly.
|
|
428
|
+
multiQueryEnabled: !official && config?.multiQueryEnabled === true,
|
|
429
|
+
deepCoverage: thorough || (!official && config?.deepCoverage === true),
|
|
373
430
|
filters: {
|
|
374
431
|
recency: typeof config?.recency === "string" && config.recency !== "any" ? config.recency : undefined,
|
|
375
432
|
lang: language.length > 0 ? language : undefined,
|
|
@@ -414,11 +471,28 @@ export function apply(ctx, config) {
|
|
|
414
471
|
});
|
|
415
472
|
return;
|
|
416
473
|
}
|
|
417
|
-
// 0.2.x SettingsForms line: no installSection.
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
// config
|
|
421
|
-
|
|
474
|
+
// 0.2.x SettingsForms line: no installSection. The entry-level `config`
|
|
475
|
+
// passed to apply() carries only schema defaults on DSH 0.2.x; the live
|
|
476
|
+
// profile-patch / user values live in the settings service's effective
|
|
477
|
+
// config. Reading them per search is what makes the Settings card actually
|
|
478
|
+
// drive execution. Without this, saving a toggle writes to the settings
|
|
479
|
+
// service but `current()` keeps returning the stale initial config, so
|
|
480
|
+
// the save is a no-op. Mirrors the upstream settings-inert fix.
|
|
481
|
+
if (typeof settings?.describe === "function" && typeof settings?.mutate === "function") {
|
|
482
|
+
settingsForms = settings;
|
|
483
|
+
// Read the live settings-service values on every resolve so a save
|
|
484
|
+
// from the card drives the next search. Exact namespace ids take
|
|
485
|
+
// priority over the shape fallback; findPluginRow is shared with the
|
|
486
|
+
// HTTP bridge so both resolve the same row.
|
|
487
|
+
current = () => {
|
|
488
|
+
try {
|
|
489
|
+
const row = findPluginRow(settings.describe());
|
|
490
|
+
return (row && row.value) ?? config;
|
|
491
|
+
} catch {
|
|
492
|
+
return config;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
422
496
|
});
|
|
423
497
|
|
|
424
498
|
// v2.7.0 stores: disk cache + append-only search history, both under
|
|
@@ -440,10 +514,9 @@ export function apply(ctx, config) {
|
|
|
440
514
|
ctx,
|
|
441
515
|
resolveOptions: () => resolveOptions(ctx, current()),
|
|
442
516
|
backends: BACKENDS,
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
},
|
|
517
|
+
// The provider only reads and writes through get/set, both of which the
|
|
518
|
+
// store already exposes; wrapping them added nothing but indirection.
|
|
519
|
+
cache: searchCache,
|
|
447
520
|
history: {
|
|
448
521
|
record: (entry) => {
|
|
449
522
|
if (resolveOptions(ctx, current()).historyEnabled !== true) return;
|
|
@@ -467,26 +540,48 @@ export function apply(ctx, config) {
|
|
|
467
540
|
return undefined;
|
|
468
541
|
}
|
|
469
542
|
};
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
543
|
+
// Registrations are effects: WebServer.register() returns the disposer
|
|
544
|
+
// removing the route, so hand all of them to the injection fiber. Without
|
|
545
|
+
// this, a plugin reload leaves the old routes registered and the next
|
|
546
|
+
// load throws on duplicate (kind, path).
|
|
547
|
+
webCtx.effect(() => {
|
|
548
|
+
const disposers = [];
|
|
549
|
+
// Register incrementally: WebServer.register throws on a duplicate
|
|
550
|
+
// (kind, path). If one throws mid-way, roll back the routes already
|
|
551
|
+
// acquired, otherwise the effect exits without a disposer and those
|
|
552
|
+
// routes leak permanently (a later reload then conflicts with them).
|
|
553
|
+
const registers = [
|
|
554
|
+
() => registerHealthRoute(webCtx.webServer, {
|
|
555
|
+
resolveOptions: () => resolveOptions(ctx, current()),
|
|
556
|
+
backends: BACKENDS,
|
|
557
|
+
getBackendHealth: getLatestBackendHealth,
|
|
558
|
+
getConnection,
|
|
559
|
+
}),
|
|
560
|
+
// v2.7.0 search history: read-only GET + explicit clear POST.
|
|
561
|
+
// v2.8.0: GET also carries per-backend last-outcome observability.
|
|
562
|
+
() => registerHistoryRoutes(webCtx.webServer, {
|
|
563
|
+
getStore: () => historyStore,
|
|
564
|
+
getBackendHealth: getLatestBackendHealth,
|
|
565
|
+
getConnection,
|
|
566
|
+
}),
|
|
567
|
+
// Settings bridge for the browser card on 0.2.x builds (no legacy
|
|
568
|
+
// settingsScope service). Fenced by the host connection admission;
|
|
569
|
+
// writes land in the volatile config entry above.
|
|
570
|
+
() => registerSettingsRoutes(webCtx.webServer, {
|
|
571
|
+
getSettings: () => settingsForms,
|
|
572
|
+
getConfig: () => Config,
|
|
573
|
+
getConnection,
|
|
574
|
+
}),
|
|
575
|
+
];
|
|
576
|
+
try {
|
|
577
|
+
for (const register of registers) disposers.push(...register());
|
|
578
|
+
} catch (err) {
|
|
579
|
+
for (const dispose of disposers.reverse()) {
|
|
580
|
+
try { dispose(); } catch { /* best-effort rollback */ }
|
|
581
|
+
}
|
|
582
|
+
throw err;
|
|
583
|
+
}
|
|
584
|
+
return () => disposers.forEach((dispose) => dispose());
|
|
585
|
+
}, "unified-search: web routes");
|
|
491
586
|
});
|
|
492
587
|
}
|
package/lib/prompting.js
CHANGED
|
@@ -26,11 +26,20 @@
|
|
|
26
26
|
/** 查询硬上限(Tavily:agent 查询应简短聚焦;>1500 字符视为跑题长文)。 */
|
|
27
27
|
export const QUERY_MAX_CHARS = 1500;
|
|
28
28
|
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Conversational prefixes that are safe to strip. Bare verbs and question
|
|
31
|
+
* words are deliberately absent: "search", "find", "google", "what is" can be
|
|
32
|
+
* part of the subject ("searching algorithms", "findability testing", "google
|
|
33
|
+
* search api"), and `\b` alone is not enough because "find" is a word prefix
|
|
34
|
+
* of "findability". Quotes are search operators and are never stripped.
|
|
35
|
+
*/
|
|
30
36
|
const FILLER_PREFIX_RE =
|
|
31
|
-
/^(?:please|pls|kindly|could you(?: please)?|can you(?: please)?|help me(?: to)?|
|
|
37
|
+
/^(?:please|pls|kindly|could you(?: please)?|can you(?: please)?|would you(?: please)?|help me(?: to)?|i(?:'d| would)? like to know|tell me)\b[\s,,]*/i;
|
|
32
38
|
const FILLER_PREFIX_RE_ZH =
|
|
33
|
-
/^(
|
|
39
|
+
/^(?:请(?:帮我|帮忙)?(?:查一?下|查询|搜索一下|搜一下|找一下)|麻烦(?:帮我)?(?:查一?下|查询|搜索|搜一下|找一下)|帮我(?:查一?下|查询|搜索|搜一下|找一下|找)|帮忙(?:查一?下|查询|搜索|搜一下|找一下)|(?:查一?下|查询一下|搜索一下|搜一下|找一下)|我想知道|我想了解|请问)/;
|
|
40
|
+
|
|
41
|
+
/** A query that is only a request word ("search", "搜索") has no subject. */
|
|
42
|
+
const PURE_FILLER_RE = /^(?:search|please|pls|kindly|google|find|look up|查询|搜索|搜一下|查一下|请|麻烦|帮我查一下|请问)$/i;
|
|
34
43
|
|
|
35
44
|
/**
|
|
36
45
|
* 确定性查询整形:剥离口语前缀(循环多次以处理叠加寒暄)、压缩空白、
|
|
@@ -41,6 +50,7 @@ const FILLER_PREFIX_RE_ZH =
|
|
|
41
50
|
export function shapeQuery(query) {
|
|
42
51
|
if (typeof query !== "string") return "";
|
|
43
52
|
let q = query.replace(/\s+/g, " ").trim();
|
|
53
|
+
if (PURE_FILLER_RE.test(q)) return "";
|
|
44
54
|
// 中文寒暄与英文寒暄交替剥离,直到稳定。
|
|
45
55
|
for (let i = 0; i < 6; i++) {
|
|
46
56
|
const before = q;
|