@240xu/dsh-websearch 2.8.8 → 2.9.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.
@@ -1,12 +1,69 @@
1
- // util/failure-label.js — short user-facing classification of a backend
2
- // failure for the telemetry line ("[websearch backends] ... searxng ✗...").
3
- //
4
- // The raw reason stays the machine-facing truth (all-fail error, health
5
- // payload); the telemetry line is what the model/user reads next to results,
6
- // where "SearXNG: invalid JSON response" reads like a plugin bug while it
7
- // actually means "the instance served an anti-bot page" (route3/route6).
8
- // Pure and zero-dep: returns undefined when no confident class matches, so
9
- // the caller keeps the raw text as fallback.
1
+ // failure-label.js — classify quota/rate-limit failures. Route on the stable
2
+ // `code` / `status` / `rateLimited` fields first (HarnessError JSDoc:
3
+ // "route on this, never by parsing message"). The message regex is a legacy
4
+ // fallback for errors built before webErrorFromResponse() landed.
5
+
6
+ import { RATE_LIMIT_CODE, QUOTA_CODE } from "./web-error.js";
7
+
8
+ /** True when the error indicates a keyless permission refusal (needs a key,
9
+ * not a retry). The Firecrawl hosted MCP returns this as an isError result. */
10
+ export function keylessRejected(err) {
11
+ if (err?.keylessRejected === true) return true;
12
+ const s = String(err?.message ?? err);
13
+ return /Anonymous keyless access is unavailable|keyless access is unavailable/i.test(s);
14
+ }
15
+
16
+ /** True when the error is a rate limit or exhausted quota. */
17
+ export function rateLimited(err) {
18
+ if (err?.code === RATE_LIMIT_CODE || err?.code === QUOTA_CODE) return true;
19
+ if (err?.rateLimited === true || err?.quota === true) return true;
20
+ if (Number(err?.status) === 429) return true;
21
+ if (typeof err?.providerCode === "string"
22
+ && /^(rate_limit_error|quota_exceeded|insufficient_quota)$/.test(err.providerCode)) return true;
23
+ // Legacy fallback for pre-helper errors. Bare "quota" and generic
24
+ // "anonymous" are deliberately excluded: they produced false positives on
25
+ // HTTP 200/402/503 bodies. Only Firecrawl's exact keyless MCP isError text
26
+ // is matched; it never passes through webErrorFromResponse().
27
+ const s = String(err?.message ?? err);
28
+ return /HTTP 429|429\b|rate.?limit/i.test(s)
29
+ || /额度/i.test(s)
30
+ || /Anonymous keyless access is unavailable/i.test(s);
31
+ }
32
+
33
+ // Cap a server-supplied cooldown so a bogus or hostile Retry-After cannot
34
+ // disable a backend for years. Anything beyond a day is treated as unknown.
35
+ const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;
36
+
37
+ /**
38
+ * Best-effort Retry-After extraction, in milliseconds. webErrorFromResponse()
39
+ * stores the raw header on err.retryAfter.
40
+ *
41
+ * Returns `undefined` when the response carried no usable header — including
42
+ * an unparsable value, a past http-date, or a value beyond the one-day cap.
43
+ * The breaker then falls back to the configured `breakerCooldownMs`, so
44
+ * `0 = count only` keeps working for header-less 429s instead of silently
45
+ * becoming 60 seconds.
46
+ *
47
+ * @returns {number|undefined} explicit cooldown in milliseconds, if any
48
+ */
49
+ export function retryAfterMsFrom(err) {
50
+ const v = err?.retryAfter
51
+ ?? err?.cause?.response?.headers?.get?.("retry-after")
52
+ ?? err?.cause?.retryAfter;
53
+ if (v == null || String(v).trim() === "") return undefined;
54
+ const secs = Number(v);
55
+ if (Number.isFinite(secs)) {
56
+ if (secs < 0) return undefined;
57
+ const ms = secs * 1000;
58
+ return ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
59
+ }
60
+ const date = Date.parse(v);
61
+ if (!Number.isFinite(date)) return undefined;
62
+ // An http-date in the past (clock skew, already-expired window) must not
63
+ // become a zero-length cooldown; treat it as unknown.
64
+ const ms = date - Date.now();
65
+ return ms > 0 && ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
66
+ }
10
67
 
11
68
  /**
12
69
  * @param {string} id backend id (searxng gets a dedicated phrasing)
@@ -25,9 +82,13 @@ export function failureLabel(id, raw) {
25
82
  // Proxy/forwarder-path failures get their own class: the route5 incident
26
83
  // (harness EnvHttpProxyAgent hijacking the sidecar request) surfaced as a
27
84
  // generic "fetch failed", pointing the reader at DNS/TLS when the actual
28
- // fault was the proxy/egress hop.
29
- if (/(proxy|tunnel|forwarder|CONNECT)/i.test(m)) return "proxy/forwarder path failed";
30
- if (/(fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EPIPE|socket hang up)/i.test(m)) {
85
+ // fault was the proxy/egress hop. Match explicit proxy markers first: a bare
86
+ // /CONNECT/i also matched "connect ECONNREFUSED", mislabelling ordinary
87
+ // network failures as proxy failures.
88
+ if (/proxy\s+(response|connect|tunnel)|HTTP Tunneling|CONNECT tunnel|forwarder|sidecar/i.test(m)) {
89
+ return "proxy/forwarder path failed";
90
+ }
91
+ if (/(fetch failed|connection refused|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT|ECONNRESET|EPIPE|socket hang up|certificate|TLS)/i.test(m)) {
31
92
  return "network unreachable (DNS/TCP/TLS)";
32
93
  }
33
94
  if (/HTTP 429|Too Many Requests|rate.?limit/i.test(m)) return "rate-limited (HTTP 429)";
package/lib/util/log.js CHANGED
@@ -18,14 +18,16 @@
18
18
  * search.
19
19
  */
20
20
 
21
+ import { redact } from "./redact.js";
22
+
21
23
  /** One-line summary safe for the host log. */
22
24
  function summarize(request) {
23
25
  try {
24
26
  const body = request && request.body ? JSON.stringify(request.body) : "";
25
27
  const trimmed = body.length > 200 ? body.slice(0, 200) + "..." : body;
26
- return String((request && request.endpoint) || "") +
28
+ return redact(String((request && request.endpoint) || "") +
27
29
  (request && request.toolName ? " tool=" + request.toolName : "") +
28
- (trimmed ? " body=" + trimmed : "");
30
+ (trimmed ? " body=" + trimmed : ""));
29
31
  } catch {
30
32
  return String(request && request.endpoint);
31
33
  }
@@ -56,7 +58,7 @@ export function recordBackendOutcome(ctx, backendId, outcome) {
56
58
  const logger = ctx && ctx.logger;
57
59
  if (!logger) return;
58
60
  const status = outcome && typeof outcome.status === "string" ? outcome.status : "";
59
- const line = "[websearch:" + backendId + "] outcome " + JSON.stringify(outcome ?? {}).slice(0, 500);
61
+ const line = redact("[websearch:" + backendId + "] outcome " + JSON.stringify(outcome ?? {}).slice(0, 500));
60
62
  if (status === "error" && typeof logger.warn === "function") logger.warn(line);
61
63
  else if (typeof logger.debug === "function") logger.debug(line);
62
64
  } catch {
@@ -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;
@@ -49,6 +53,21 @@ const TITLE_DUP_THRESHOLD = 0.9;
49
53
  *
50
54
  * The input array is not mutated; returns a fresh array.
51
55
  */
56
+ /** Canonical dedupe key: ignore fragments and common tracking params. */
57
+ function canonicalUrlKey(raw) {
58
+ try {
59
+ const u = new URL(raw);
60
+ u.hash = "";
61
+ u.hostname = u.hostname.toLowerCase();
62
+ for (const name of [...u.searchParams.keys()]) {
63
+ if (/^utm_/i.test(name) || /^(fbclid|gclid|mc_cid|mc_eid)$/i.test(name)) u.searchParams.delete(name);
64
+ }
65
+ return u.toString().replace(/\/$/, "").toLowerCase();
66
+ } catch {
67
+ return raw.toLowerCase();
68
+ }
69
+ }
70
+
52
71
  export function dedupeSources(sources, strategy) {
53
72
  const out = [];
54
73
  const byUrl = new Map(); // urlKey -> kept source
@@ -56,7 +75,7 @@ export function dedupeSources(sources, strategy) {
56
75
 
57
76
  for (const s of sources ?? []) {
58
77
  if (!s || typeof s.url !== "string" || s.url.length === 0) continue;
59
- const key = s.url.toLowerCase();
78
+ const key = canonicalUrlKey(s.url);
60
79
  const existing = byUrl.get(key);
61
80
  if (existing) {
62
81
  if (!existing.title && s.title) existing.title = s.title;
@@ -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.8",
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.9.0",
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": {