@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.
@@ -13,10 +13,12 @@
13
13
  */
14
14
 
15
15
  import { WebError } from "@deepseek-ai/dsh-web";
16
+ import { webErrorFromResponse } from "../util/web-error.js";
16
17
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
17
18
  import { applySearxngFilters, normalizeFilters, safeSearchParams } from "../util/filters.js";
18
19
  import { egressFetch } from "../util/egress-fetch.js";
19
20
  import { describeError } from "../util/describe-error.js";
21
+ import { invalidBaseURL } from "../util/base-url.js";
20
22
 
21
23
  const DEFAULT_SEARXNG_URL = "https://searx.be";
22
24
 
@@ -62,6 +64,14 @@ export const searxngBackend = {
62
64
  const trimmed = typeof candidate === "string" ? candidate.trim() : "";
63
65
  if (trimmed !== "" && !candidates.includes(trimmed)) candidates.push(trimmed);
64
66
  }
67
+ // Every candidate receives the configured API key, so every candidate
68
+ // passes the same trust gate as baseURL. This is checked here (not only in
69
+ // the provider) because searxngBaseURLs was the unvalidated path and the
70
+ // backend is also usable directly by embedders.
71
+ const invalid = candidates.map((c) => invalidBaseURL(c)).find((reason) => reason !== undefined);
72
+ if (invalid !== undefined) {
73
+ throw new WebError("SearXNG: invalid instance URL (" + invalid + ")", "WEB_PROVIDER_ERROR");
74
+ }
65
75
 
66
76
  // Single instance (the default): legacy path, unchanged semantics.
67
77
  if (candidates.length === 1) {
@@ -75,11 +85,26 @@ export const searxngBackend = {
75
85
  const fresh = candidates.filter((u) => (instanceCooldowns.get(u) ?? 0) <= now);
76
86
  const order = fresh.length > 0 ? fresh : candidates; // all cooled -> fail-open
77
87
  let lastErr = null;
78
- for (const candidate of order) {
88
+ // A quota/rate-limit answer is the most actionable failure: it carries
89
+ // Retry-After and drives the breaker's quota cooldown. Taking whichever
90
+ // instance failed LAST would discard it whenever a later instance failed
91
+ // on plain network grounds.
92
+ const severity = (err) => (err?.code === "RATE_LIMIT" || err?.code === "QUOTA_EXCEEDED" || err?.rateLimited === true ? 2 : 1);
93
+ // Each instance attempt must fit inside what is left of the backend budget:
94
+ // three public instances at 4.5s each would otherwise need 13.5s while the
95
+ // provider abandons the backend at 8s, and the per-instance detail is lost
96
+ // to a generic "timed out after 8000ms".
97
+ const budgetMs = Number(backendOpts?.backendTimeoutMs);
98
+ const deadline = Number.isFinite(budgetMs) && budgetMs > 0 ? Date.now() + budgetMs : Infinity;
99
+ for (const [index, candidate] of order.entries()) {
79
100
  throwIfSearchAborted(signal);
101
+ const remaining = deadline - Date.now();
102
+ if (remaining <= 0) break;
103
+ const share = remaining / Math.max(1, order.length - index);
104
+ const attemptMs = Math.max(1000, Math.min(INSTANCE_ATTEMPT_TIMEOUT_MS, share));
80
105
  const attemptController = new AbortController();
81
106
  const attemptSignal = signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal;
82
- const timer = setTimeout(() => attemptController.abort(), INSTANCE_ATTEMPT_TIMEOUT_MS);
107
+ const timer = setTimeout(() => attemptController.abort(), attemptMs);
83
108
  try {
84
109
  const sources = await queryInstance(candidate, request, attemptSignal, backendOpts, apiKey, hooks);
85
110
  instanceCooldowns.delete(candidate);
@@ -88,23 +113,26 @@ export const searxngBackend = {
88
113
  if (signal?.aborted === true) throw searchAborted(signal, error);
89
114
  instanceCooldowns.set(candidate, Date.now() + INSTANCE_COOLDOWN_MS);
90
115
  if (attemptController.signal.aborted && !(signal && signal.aborted)) {
91
- lastErr = new WebError(
92
- `SearXNG instance attempt timed out after ${INSTANCE_ATTEMPT_TIMEOUT_MS}ms (${candidate})`,
116
+ const timedOutErr = new WebError(
117
+ `SearXNG instance attempt timed out after ${attemptMs}ms (${candidate})`,
93
118
  "WEB_PROVIDER_ERROR",
94
119
  { cause: error instanceof Error ? error : undefined },
95
120
  );
121
+ if (lastErr === null || severity(timedOutErr) > severity(lastErr)) lastErr = timedOutErr;
96
122
  } else if (error instanceof WebError && error.code !== "WEB_ABORTED") {
97
- lastErr = error;
123
+ if (lastErr === null || severity(error) > severity(lastErr)) lastErr = error;
98
124
  } else {
99
- lastErr = new WebError(
125
+ const netErr = new WebError(
100
126
  "SearXNG instance failed (" + candidate + "): " + describeError(error),
101
127
  "WEB_PROVIDER_ERROR",
102
128
  { cause: error instanceof Error ? error : undefined },
103
129
  );
130
+ if (lastErr === null || severity(netErr) > severity(lastErr)) lastErr = netErr;
104
131
  }
105
132
  } finally {
106
133
  clearTimeout(timer);
107
134
  }
135
+
108
136
  }
109
137
  throw lastErr ?? new WebError("SearXNG: no instance available (all cooling down)", "WEB_PROVIDER_ERROR");
110
138
  },
@@ -163,9 +191,9 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
163
191
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
164
192
  hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
165
193
  if (response.status === 429 || response.status >= 500) {
166
- throw new WebError("SearXNG API error (HTTP " + response.status + "): " + text + " (instance struggling? point searxngBaseURL at another public instance)", "WEB_PROVIDER_ERROR");
194
+ throw webErrorFromResponse(response, text + " (instance struggling? point searxngBaseURL at another public instance)", "SearXNG");
167
195
  }
168
- throw new WebError("SearXNG API error (HTTP " + response.status + "): " + text, "WEB_PROVIDER_ERROR");
196
+ throw webErrorFromResponse(response, text, "SearXNG");
169
197
  }
170
198
 
171
199
  // 200 does not mean JSON (route3: searx.be 200 + HTML anti-bot page). Read
@@ -6,9 +6,11 @@
6
6
  */
7
7
 
8
8
  import { WebError } from "@deepseek-ai/dsh-web";
9
+ import { webErrorFromResponse } from "../util/web-error.js";
9
10
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
10
11
  import { applySerperFilters, normalizeFilters } from "../util/filters.js";
11
12
  import { egressFetch } from "../util/egress-fetch.js";
13
+ import { describeError } from "../util/describe-error.js";
12
14
 
13
15
  const SERPER_ENDPOINT = "https://google.serper.dev/search";
14
16
 
@@ -62,13 +64,13 @@ export const serperBackend = {
62
64
  });
63
65
  } catch (error) {
64
66
  if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
65
- throw new WebError("Serper request failed: " + error, "WEB_PROVIDER_ERROR", { cause: error });
67
+ throw new WebError("Serper request failed: " + describeError(error), "WEB_PROVIDER_ERROR", { cause: error });
66
68
  }
67
69
 
68
70
  if (!response.ok) {
69
71
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
70
72
  hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
71
- throw new WebError("Serper API error (HTTP " + response.status + "): " + text, "WEB_PROVIDER_ERROR");
73
+ throw webErrorFromResponse(response, text, "Serper");
72
74
  }
73
75
 
74
76
  let data;
@@ -6,9 +6,11 @@
6
6
  */
7
7
 
8
8
  import { WebError } from "@deepseek-ai/dsh-web";
9
+ import { webErrorFromResponse } from "../util/web-error.js";
9
10
  import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
10
11
  import { applyTavilyFilters, normalizeFilters } from "../util/filters.js";
11
12
  import { egressFetch } from "../util/egress-fetch.js";
13
+ import { describeError } from "../util/describe-error.js";
12
14
 
13
15
  const TAVILY_ENDPOINT = "https://api.tavily.com/search";
14
16
 
@@ -71,13 +73,13 @@ export const tavilyBackend = {
71
73
  });
72
74
  } catch (error) {
73
75
  if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
74
- throw new WebError(`Tavily request failed: ${error}`, "WEB_PROVIDER_ERROR", { cause: error });
76
+ throw new WebError(`Tavily request failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
75
77
  }
76
78
 
77
79
  if (!response.ok) {
78
80
  const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
79
81
  hooks?.recordOutcome?.({ status: "error", message: `HTTP ${response.status}: ${text}` });
80
- throw new WebError(`Tavily API error (HTTP ${response.status}): ${text}`, "WEB_PROVIDER_ERROR");
82
+ throw webErrorFromResponse(response, text, "Tavily");
81
83
  }
82
84
 
83
85
  let data;
@@ -0,0 +1,124 @@
1
+ // tinyfish.js — TinyFish search backend (streamable-http MCP).
2
+ //
3
+ // Aligned with the OpenCode v2 websearch provider:
4
+ // https://github.com/anomalyco/opencode/blob/v2.2.5/packages/core/src/plugin/websearch/tinyfish.ts
5
+ // The hosted keyless tier needs no credential; an optional API key activates
6
+ // the session handshake and raises limits.
7
+ // Endpoint: https://agent.tinyfish.ai/mcp
8
+ // - keyless: header `X-TinyFish-Access-Mode: keyless`, NO initialize /
9
+ // Mcp-Session-Id handshake. TinyFish v2.2.5 source comment:
10
+ // "Keyed requests are rejected without the Mcp-Session-Id returned by
11
+ // initialize; keyless ones are not."
12
+ // - keyed: header `X-API-Key: <key>` plus the normal 3-step handshake
13
+ // (mcpCall default). Our mcpCall() gained `options.skipInitialize` to
14
+ // express exactly this split without regressing exa/parallel.
15
+ //
16
+ // Keyless limits observed via tools/list: 30 requests/min, 50 searches/UTC
17
+ // day (search only: web + news). The REST pricing page uses different numbers
18
+ // (TinySearch 30 req/min, 500/hour) — that is a different ingress, do not
19
+ // conflate the two. See 05-search-backends.md appendix A.3.
20
+ //
21
+ // Response envelope: content[0].text is a JSON string of
22
+ // { results: [{ url, title, snippet }] }.
23
+ //
24
+ // Registration is opt-in (DEFAULT_ENABLED does not contain this id).
25
+
26
+ import { mcpCall } from "../util/mcp-client.js";
27
+ import { WebError } from "@deepseek-ai/dsh-web";
28
+
29
+ const TINYFISH_ENDPOINT = "https://agent.tinyfish.ai/mcp";
30
+ const TINYFISH_TOOL = "search";
31
+
32
+ export const tinyfishBackend = {
33
+ id: "tinyfish",
34
+ requiresCredential: false,
35
+
36
+ available() {
37
+ // Keyless mode needs no credential.
38
+ return true;
39
+ },
40
+
41
+ async search(request, signal, options, hooks = {}) {
42
+ const args = { query: request.query };
43
+ // resolveOptions() supplies an async resolveApiKey() closure. A literal
44
+ // apiKey is accepted for stubs; a failed resolution degrades to keyless.
45
+ let apiKey = typeof options?.apiKey === "string" ? options.apiKey : "";
46
+ if (!apiKey && typeof options?.resolveApiKey === "function") {
47
+ try { apiKey = (await options.resolveApiKey()) ?? ""; } catch { apiKey = ""; }
48
+ }
49
+ const keyed = apiKey.length > 0;
50
+
51
+ const extraHeaders = keyed
52
+ ? { "X-API-Key": apiKey }
53
+ : { "X-TinyFish-Access-Mode": "keyless" };
54
+ // Use the configured baseURL so the provider trust gate and sidecar path apply.
55
+ const endpoint = typeof options?.baseURL === "string" && options.baseURL.length > 0
56
+ ? options.baseURL : TINYFISH_ENDPOINT;
57
+
58
+ // Never record the key itself.
59
+ hooks.recordRequest?.({
60
+ endpoint,
61
+ toolName: TINYFISH_TOOL,
62
+ body: args,
63
+ headers: {},
64
+ });
65
+
66
+ let result;
67
+ try {
68
+ result = await mcpCall(
69
+ endpoint,
70
+ TINYFISH_TOOL,
71
+ args,
72
+ extraHeaders,
73
+ signal,
74
+ // Keyless is stateless: skip initialize. Keyed uses the handshake
75
+ // once; the session cache is keyed by URL *and* X-API-Key, so a
76
+ // rotated credential cannot reuse the previous Mcp-Session-Id, and a
77
+ // server-side expiry still triggers the 401/403/404 retry.
78
+ { skipInitialize: !keyed },
79
+ );
80
+ } catch (err) {
81
+ if (err instanceof WebError) throw err;
82
+ throw new WebError(
83
+ `tinyfish search failed: ${String(err?.message ?? err)}`,
84
+ "WEB_PROVIDER_ERROR",
85
+ { cause: err },
86
+ );
87
+ }
88
+
89
+ if (result?.isError === true) {
90
+ const message = String(result.content?.[0]?.text ?? "unknown");
91
+ hooks.recordOutcome?.({ status: "error", message });
92
+ throw new WebError(`tinyfish returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
93
+ }
94
+
95
+ const sources = parseTinyfishResult(result, request.maxResults ?? 8);
96
+ hooks.recordOutcome?.({ status: "ok", count: sources.length });
97
+ return { sources, content: undefined, truncated: false };
98
+ },
99
+ };
100
+
101
+ /** Parse the JSON string embedded in content[0].text into DSH sources. */
102
+ export function parseTinyfishResult(result, maxResults) {
103
+ const text = result?.content?.[0]?.text;
104
+ if (typeof text !== "string" || text.length === 0) return [];
105
+ let parsed;
106
+ try {
107
+ parsed = JSON.parse(text);
108
+ } catch {
109
+ return [];
110
+ }
111
+ if (!Array.isArray(parsed?.results)) return [];
112
+ const sources = [];
113
+ for (const item of parsed.results) {
114
+ if (typeof item?.url !== "string" || item.url.length === 0) continue;
115
+ const source = { url: item.url };
116
+ if (typeof item.title === "string" && item.title.length > 0) source.title = item.title;
117
+ if (typeof item.snippet === "string" && item.snippet.length > 0) source.snippet = item.snippet;
118
+ sources.push(source);
119
+ if (sources.length >= maxResults) break;
120
+ }
121
+ return sources;
122
+ }
123
+
124
+ export default tinyfishBackend;
package/lib/breaker.js CHANGED
@@ -24,9 +24,11 @@ export const BREAKER_DEFAULTS = {
24
24
  * @param {boolean} ok did this call succeed?
25
25
  * @param {number} nowMs
26
26
  * @param {{threshold?: number, cooldownMs?: number}} cfg
27
+ * @param {{rateLimited?: boolean, retryAfterMs?: number}} [opts] - a quota
28
+ * failure cools the backend immediately instead of waiting for threshold.
27
29
  * @returns {{ failCount: number, cooledUntil: number }}
28
30
  */
29
- export function foldBreaker(prev, ok, nowMs, cfg = {}) {
31
+ export function foldBreaker(prev, ok, nowMs, cfg = {}, opts = {}) {
30
32
  const threshold = Math.max(1, Math.floor(Number(cfg.threshold) || BREAKER_DEFAULTS.threshold));
31
33
  // cooldownMs === 0 explicitly disables the cooldown window (cooledUntil = now
32
34
  // expires instantly). Only null/undefined falls back to the default — an
@@ -35,13 +37,32 @@ export function foldBreaker(prev, ok, nowMs, cfg = {}) {
35
37
  ? Math.max(0, Math.floor(Number(cfg.cooldownMs) || 0))
36
38
  : BREAKER_DEFAULTS.cooldownMs;
37
39
  if (ok) return { failCount: 0, cooledUntil: 0 };
38
- const failCount = (Number.isFinite(prev?.failCount) ? prev.failCount : 0) + 1;
40
+ // A cooldown window that has already expired starts a fresh failure streak;
41
+ // otherwise failCount grows monotonically across unrelated outages.
42
+ // cooledUntil === 0 means "never opened", so the streak still accumulates.
43
+ const hadOpenWindow = Number.isFinite(prev?.cooledUntil) && prev.cooledUntil > 0;
44
+ const expired = hadOpenWindow && prev.cooledUntil <= nowMs;
45
+ const baseCount = Number.isFinite(prev?.failCount) ? prev.failCount : 0;
46
+ const failCount = expired ? 1 : baseCount + 1;
47
+ const prevCooledUntil = expired ? 0 : (Number.isFinite(prev?.cooledUntil) ? prev.cooledUntil : 0);
48
+ // A rate-limit/quota response should not be retried twice more just to
49
+ // reach the failure threshold; cool immediately for the retry window.
50
+ if (opts.rateLimited === true) {
51
+ // A quota answer carries its own Retry-After; without one, fall back to
52
+ // the configured cooldown. A zero here means "count only", matching the
53
+ // threshold path above.
54
+ const retryAfterMs = Number.isFinite(opts.retryAfterMs) ? opts.retryAfterMs : cooldownMs;
55
+ return { failCount, cooledUntil: retryAfterMs > 0 ? nowMs + retryAfterMs : 0 };
56
+ }
39
57
  if (failCount >= threshold) {
40
- return { failCount, cooledUntil: nowMs + cooldownMs };
58
+ // cooldownMs === 0 means "count only, never cool": writing a window of
59
+ // zero length would immediately look expired and reset the streak, so the
60
+ // threshold could never be reached again.
61
+ return { failCount, cooledUntil: cooldownMs > 0 ? nowMs + cooldownMs : 0 };
41
62
  }
42
63
  // Keep an existing open window if the backend was already open (failure
43
64
  // while open extends nothing, but must not silently close it).
44
- return { failCount, cooledUntil: Number.isFinite(prev?.cooledUntil) ? prev.cooledUntil : 0 };
65
+ return { failCount, cooledUntil: prevCooledUntil };
45
66
  }
46
67
 
47
68
  /**
package/lib/cache.js CHANGED
@@ -31,16 +31,26 @@ export const CACHE_DEFAULTS = {
31
31
  * Compute the deterministic cache key for a search.
32
32
  * Includes the enabledBackends selection set (sorted): switching the backend
33
33
  * mix must never serve a stale result produced by a different combination
34
- * (arch-review P1-1). Pure function; exported for tests and host reuse.
34
+ * (arch-review P1-1). Also includes the options that change the merged
35
+ * result (safeSearch, rerank, dedupStrategy, per-backend base URLs and
36
+ * models) so editing a setting is not masked by a hit within the TTL.
37
+ * Pure function; exported for tests and host reuse.
35
38
  */
36
- export function cacheKeyFor({ query, filters, maxResults, backends, mode }) {
39
+ export function cacheKeyFor({ query, filters, maxResults, backends, mode, resultOptions }) {
37
40
  const backendSet = Array.isArray(backends) ? [...backends].sort().join(",") : "";
41
+ let shaped = {};
42
+ if (resultOptions && typeof resultOptions === "object") {
43
+ const keys = Object.keys(resultOptions).filter((k) =>
44
+ typeof resultOptions[k] !== "function" && !k.startsWith("resolve"));
45
+ for (const k of keys.sort()) shaped[k] = resultOptions[k] ?? null;
46
+ }
38
47
  const canonical = JSON.stringify({
39
48
  q: typeof query === "string" ? query : "",
40
49
  f: filters ?? {},
41
50
  n: Number(maxResults) || 0,
42
51
  b: backendSet,
43
52
  m: typeof mode === "string" ? mode : "",
53
+ o: shaped,
44
54
  });
45
55
  return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
46
56
  }
@@ -97,9 +107,26 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
97
107
  return out.sort((a, b) => a.mtime - b.mtime);
98
108
  }
99
109
 
110
+ /** Count entry names without stat()ing them (the common, under-cap path). */
111
+ function countEntries() {
112
+ if (!existsSync(dir)) return 0;
113
+ let n = 0;
114
+ for (const name of readdirSync(dir)) {
115
+ if (name.endsWith(".json") && !name.includes(".tmp")) n += 1;
116
+ }
117
+ return n;
118
+ }
119
+
120
+ // maxEntries is a hard bound. Checking it costs one readdir of names; only
121
+ // an over-cap write pays the stat() of every entry. Trimming to a low-water
122
+ // mark (10%, at least one) keeps that scan amortized over ~cap/10 writes
123
+ // instead of running synchronously on every single write.
100
124
  function evict() {
125
+ if (countEntries() <= cap) return;
101
126
  const entries = listEntries();
102
- for (let i = 0; i < entries.length - cap; i++) {
127
+ const lowWater = Math.max(1, cap - Math.max(1, Math.ceil(cap * 0.1)));
128
+ const remove = entries.length - lowWater;
129
+ for (let i = 0; i < remove; i++) {
103
130
  try { unlinkSync(entries[i].file); } catch { /* raced */ }
104
131
  }
105
132
  }