okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s32808667a3dbf

main
14.5 KiB264 linesraw
1/**
2 * Web search with no account and no key: DuckDuckGo's own web-page search results, with Bing's plain result page as the second source.
3 *
4 * The Harness has three search backends and all of them need a paid service key. This is the fourth: it asks DuckDuckGo's plain
5 * HTML search page the way a browser does and reads the result list out of the page. It is the default for the agent's
6 * `web_search` tool; the person can switch to a keyed service in Settings -> Tools.
7 *
8 * Being polite is part of the design, because DuckDuckGo refuses a program that asks too fast (2026-10-18, a Linux box: two searches in
9 * 1.2 s were answered, the third got HTTP 202 "anomaly" and every DuckDuckGo page then refused for minutes):
10 *   - an ordinary browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*; nothing hidden);
11 *   - one request at a time per source, 2.5 to 4 s apart (random, so it does not look like a clock), at most 8 a minute;
12 *   - the same question is answered from a session cache (30 minutes), so a model that repeats itself costs nothing;
13 *   - when a source refuses (HTTP 202/403/429 or a challenge page) it is left alone for a cooldown that doubles every time it refuses
14 *     again (1, 2, 4 ... up to 10 minutes; a Retry-After header is honoured) instead of being asked again, which only extends a block;
15 *   - a refused DuckDuckGo page is not followed by the lite page (same refusal, one more strike): the next source is tried instead;
16 *   - a timeout or a server error gets one retry after a short pause, then the next source;
17 *   - when every source refuses the answer is one plain sentence that also tells the model not to retry (see LIMITED_MESSAGE).
18 * Results come from DuckDuckGo or Bing; they are not ranked or filtered here.
19 *
20 * Nothing in this file touches the Harness, so it can be tested alone. `strata-search.mjs` is the plugin that registers it.
21 */
22import { BING_URL, bingLooksBlocked, parseBingResults } from './web-search-bing.mjs';
23
24export const DDG_PROVIDER_ID = 'strata-duckduckgo';
25
26const HTML_URL = 'https://html.duckduckgo.com/html/';
27const LITE_URL = 'https://lite.duckduckgo.com/lite/';
28const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
29const CACHE_MS = 30 * 60 * 1000;
30const CACHE_SIZE = 120;
31const GAP_MS = 2500;
32const JITTER_MS = 1500;
33const PER_MINUTE = 8;
34const COOLDOWN_MS = 60_000;
35const COOLDOWN_MAX_MS = 10 * 60_000;
36const RETRY_PAUSE_MS = 1500;
37
38const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/' };
39const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => {
40  if (key[0] === '#') {
41    const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : parseInt(key.slice(1), 10);
42    return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : whole;
43  }
44  return ENTITIES[key.toLowerCase()] ?? whole;
45});
46const plain = html => decode(String(html).replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim();
47
48/** DuckDuckGo wraps every result link in its own redirect; the real address is in `uddg`. */
49export function realUrl(href) {
50  let value = decode(href).trim();
51  if (value.startsWith('//')) value = `https:${value}`;
52  try {
53    const url = new URL(value, 'https://duckduckgo.com/');
54    const target = url.searchParams.get('uddg');
55    if (target) return new URL(target).href;
56    if (url.hostname.endsWith('duckduckgo.com')) return null;      // an internal link, an ad or a "more results" link
57    return /^https?:$/.test(url.protocol) ? url.href : null;
58  } catch { return null; }
59}
60
61/** The result list of the HTML page. Tolerant: a result needs a link and a title; the snippet is optional. */
62export function parseHtmlResults(html) {
63  const out = [];
64  const links = [...String(html).matchAll(/<a\b[^>]*class="[^"]*\bresult__a\b[^"]*"[^>]*>/gi)];
65  for (let i = 0; i < links.length; i++) {
66    const open = links[i];
67    const start = open.index + open[0].length;
68    const next = links[i + 1]?.index ?? html.length;
69    const chunk = html.slice(start, next);
70    const close = chunk.indexOf('</a>');
71    if (close < 0) continue;
72    const href = /href="([^"]*)"/i.exec(open[0])?.[1];
73    const url = href ? realUrl(href) : null;
74    const title = plain(chunk.slice(0, close));
75    if (!url || !title) continue;
76    // An ad is a result block whose own opening tag says so (the block that holds this link, not the one before it).
77    const block = html.lastIndexOf('<div class="result', open.index);
78    if (block >= 0 && /result--ad|result__ad/.test(html.slice(block, html.indexOf('>', block) + 1))) continue;
79    const snippetMatch = /<(?:a|td|div)\b[^>]*class="[^"]*\bresult__snippet\b[^"]*"[^>]*>([\s\S]*?)<\/(?:a|td|div)>/i.exec(chunk);
80    const snippet = snippetMatch ? plain(snippetMatch[1]) : '';
81    out.push({ url, title, ...(snippet ? { snippet } : {}) });
82  }
83  return dedupe(out);
84}
85
86/** The result list of the lite page (a table), used when the HTML page gives nothing. */
87export function parseLiteResults(html) {
88  const out = [];
89  const links = [...String(html).matchAll(/<a\b[^>]*class=['"][^'"]*\bresult-link\b[^'"]*['"][^>]*>/gi)];
90  for (let i = 0; i < links.length; i++) {
91    const open = links[i];
92    const start = open.index + open[0].length;
93    const next = links[i + 1]?.index ?? html.length;
94    const chunk = html.slice(start, next);
95    const close = chunk.indexOf('</a>');
96    if (close < 0) continue;
97    const href = /href=['"]([^'"]*)['"]/i.exec(open[0])?.[1];
98    const url = href ? realUrl(href) : null;
99    const title = plain(chunk.slice(0, close));
100    if (!url || !title) continue;
101    const snippetMatch = /<td\b[^>]*class=['"][^'"]*\bresult-snippet\b[^'"]*['"][^>]*>([\s\S]*?)<\/td>/i.exec(chunk);
102    const snippet = snippetMatch ? plain(snippetMatch[1]) : '';
103    out.push({ url, title, ...(snippet ? { snippet } : {}) });
104  }
105  return dedupe(out);
106}
107
108function dedupe(rows) {
109  const seen = new Set();
110  return rows.filter(r => !seen.has(r.url) && seen.add(r.url));
111}
112
113/** DuckDuckGo asks a program to prove it is a person by serving a challenge page instead of results. */
114export function looksBlocked(status, html) {
115  if (status === 202 || status === 403 || status === 418 || status === 429) return true;
116  return /anomaly-modal|anomaly\.js|unusual traffic|are you a (?:robot|human)|captcha|challenge-form/i.test(String(html).slice(0, 60000))
117    && !/class="[^"]*\bresult__a\b/.test(html);
118}
119
120
121export class SearchUnavailable extends Error {
122  constructor(message, code = 'WEB_PROVIDER_ERROR', options) { super(message, options); this.name = 'WebError'; this.code = code; }
123}
124
125/** The one plain sentence for the person. The words "Settings → Tools → Web search" are where the key goes in the app. */
126export const LIMITED_SENTENCE = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search.';
127/** What the tool answers: the sentence, then what the model should do (it must not keep searching). */
128export const BLOCKED_MESSAGE = `${LIMITED_SENTENCE} Do not retry this search: go on with what you know and tell the person, in one plain sentence, that web search was limited.`;
129export const UNREACHABLE_MESSAGE = 'The search could not reach the internet. Check the connection and try again. Do not retry this search now: go on with what you know and say that search was unavailable.';
130
131/** One request at a time, spaced out with a little randomness, and at most PER_MINUTE a minute. */
132class Pacer {
133  constructor({ now, sleep, random, gap = GAP_MS, jitter = JITTER_MS, perMinute = PER_MINUTE }) {
134    Object.assign(this, { now, sleep, random, gap, jitter, perMinute });
135    this.starts = []; this.last = 0; this.chain = Promise.resolve();
136  }
137  turn(signal) {
138    const run = this.chain.then(async () => {
139      const spacing = this.gap + Math.floor(this.random() * this.jitter);
140      for (;;) {
141        if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED');
142        const t = this.now();
143        while (this.starts.length && t - this.starts[0] > 60_000) this.starts.shift();
144        const wait = this.last ? Math.max(spacing - (t - this.last), this.starts.length >= this.perMinute ? 60_000 - (t - this.starts[0]) : 0) : 0;
145        if (wait <= 0) break;
146        if (wait > 30_000) throw new SearchUnavailable(LIMITED_SENTENCE, 'WEB_RATE_LIMITED');
147        await this.sleep(wait);
148      }
149      this.last = this.now();
150      this.starts.push(this.last);
151    });
152    this.chain = run.catch(() => {});
153    return run;
154  }
155}
156
157const REFUSED = Symbol('refused');
158const retryAfterMs = res => {
159  const v = Number(res?.headers?.get?.('retry-after'));
160  return Number.isFinite(v) && v > 0 ? Math.min(v * 1000, COOLDOWN_MAX_MS) : 0;
161};
162const serverError = status => status >= 500 && status < 600;
163const queryKey = query => query.toLowerCase().replace(/\s+/g, ' ').trim();
164
165/**
166 * @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise<void>, random?: () => number}} [deps]
167 */
168export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), random = Math.random } = {}) {
169  const cache = new Map();
170
171  /** A source: its pacing, and what to do after it refuses. */
172  const source = (id, name) => ({ id, name, pacer: new Pacer({ now, sleep, random }), blockedUntil: 0, strikes: 0, refusals: 0 });
173  const ddg = source('duckduckgo', 'DuckDuckGo');
174  const bing = source('bing', 'Bing');
175  const refuse = (s, res) => {
176    s.strikes += 1; s.refusals += 1;
177    s.blockedUntil = now() + Math.max(retryAfterMs(res), Math.min(COOLDOWN_MS * 2 ** (s.strikes - 1), COOLDOWN_MAX_MS));
178  };
179  const accepted = s => { s.strikes = 0; s.blockedUntil = 0; };
180
181  const headers = (origin, extra = {}) => ({
182    'user-agent': USER_AGENT, accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.9',
183    'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1',
184    ...(origin ? { referer: `${origin}/`, origin } : {}), ...extra,
185  });
186
187  async function get(url, init, signal) {
188    const timeout = AbortSignal.timeout(15_000);
189    const res = await fetchImpl(url, { redirect: 'follow', ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
190    return { res, status: res.status, html: await res.text() };
191  }
192
193  /** One page request with one retry after a pause for a timeout, a network error or a server error. Throws SearchUnavailable only for cancel. */
194  async function ask(s, makeRequest, signal) {
195    let failure;
196    for (let attempt = 0; attempt < 2; attempt++) {
197      await s.pacer.turn(signal);
198      try {
199        const page = await get(...makeRequest(), signal);
200        if (!serverError(page.status)) return page;
201        failure = new Error(`HTTP ${page.status}`);
202      } catch (error) {
203        if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
204        failure = error;
205      }
206      if (attempt === 0) await sleep(RETRY_PAUSE_MS + Math.floor(random() * 1000));
207    }
208    return { failure };
209  }
210
211  async function searchDuckDuckGo(query, signal) {
212    const form = new URLSearchParams({ q: query, b: '', kl: 'wt-wt', df: '' }).toString();
213    const post = (url, origin) => () => [url, { method: 'POST', headers: headers(origin, { 'content-type': 'application/x-www-form-urlencoded' }), body: form }];
214    let reachedOnce = false;
215    for (const [url, origin, parse] of [[HTML_URL, 'https://html.duckduckgo.com', parseHtmlResults], [LITE_URL, 'https://lite.duckduckgo.com', parseLiteResults]]) {
216      const page = await ask(ddg, post(url, origin), signal);
217      if (page.failure) return { failure: page.failure };
218      reachedOnce = true;
219      // A refusal on the first page is a refusal for the whole address: the lite page would only add one more strike.
220      if (looksBlocked(page.status, page.html)) { refuse(ddg, page.res); return { refused: true }; }
221      const sources = parse(page.html);
222      if (sources.length) { accepted(ddg); return { sources }; }
223    }
224    if (reachedOnce) accepted(ddg);
225    return { sources: [] };
226  }
227
228  async function searchBing(query, signal) {
229    const url = `${BING_URL}?${new URLSearchParams({ q: query, setlang: 'en' })}`;
230    const page = await ask(bing, () => [url, { method: 'GET', headers: headers(null) }], signal);
231    if (page.failure) return { failure: page.failure };
232    if (bingLooksBlocked(page.status, page.html)) { refuse(bing, page.res); return { refused: true }; }
233    accepted(bing);
234    return { sources: parseBingResults(page.html) };
235  }
236
237  return {
238    id: DDG_PROVIDER_ID,
239    available: () => typeof fetchImpl === 'function',
240    /** What happened so far, for tests and for the status line in the app's log. */
241    status: () => ({ duckduckgo: { strikes: ddg.strikes, refusals: ddg.refusals, blockedForMs: Math.max(0, ddg.blockedUntil - now()) }, bing: { strikes: bing.strikes, refusals: bing.refusals, blockedForMs: Math.max(0, bing.blockedUntil - now()) }, cached: cache.size }),
242    async search(request, signal) {
243      const query = String(request.query ?? '').trim().slice(0, 400);
244      if (!query) throw new SearchUnavailable('Type what to search for.', 'WEB_PROVIDER_ERROR');
245      const key = queryKey(query);
246      const want = request.maxResults ?? 10;
247      const hit = cache.get(key);
248      if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, want), truncated: false };
249      let limited = false, unreachable = false;
250      for (const [s, run] of [[ddg, searchDuckDuckGo], [bing, searchBing]]) {
251        if (s.blockedUntil > now()) { limited = true; continue; }    // asked again too soon: that only extends a block
252        const result = await run(query, signal);
253        if (result.refused) { limited = true; continue; }
254        if (result.failure) { unreachable = true; continue; }
255        if (!result.sources.length) return { sources: [], truncated: false };      // a real search with no results is an answer, not an error
256        cache.set(key, { at: now(), sources: result.sources });
257        if (cache.size > CACHE_SIZE) cache.delete(cache.keys().next().value);
258        return { sources: result.sources.slice(0, want), truncated: false };
259      }
260      if (limited) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED');
261      throw new SearchUnavailable(unreachable ? UNREACHABLE_MESSAGE : BLOCKED_MESSAGE, unreachable ? 'WEB_PROVIDER_ERROR' : 'WEB_RATE_LIMITED');
262    },
263  };
264}