okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8667a3dbf
main
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 ) => { 40if ( key [ 0 ] === '#' ) { 41const code = key [ 1 ]. toLowerCase () === 'x' ?parseInt ( key . slice ( 2 ), 16 ) :parseInt ( key . slice ( 1 ), 10 ); 42return Number . isFinite ( code ) && code > 0 && code < 0x110000 ?String . fromCodePoint ( code ) :whole ; 43} 44return 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 ) { 50let value = decode ( href ). trim (); 51if ( value . startsWith ( '//' )) value = `https: ${ value } ` ; 52try { 53const url = new URL ( value , 'https://duckduckgo.com/' ); 54const target = url . searchParams . get ( 'uddg' ); 55if ( target ) return new URL ( target ). href ; 56if ( url . hostname . endsWith ( 'duckduckgo.com' )) return null ; // an internal link, an ad or a "more results" link 57return / ^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 ) { 63const out = []; 64const links = [ ...String ( html ). matchAll ( / <a\b [ ^ > ] * class=" [ ^ " ] * \bresult__a\b [ ^ " ] * " [ ^ > ] * > / gi )]; 65for ( let i = 0 ; i < links . length ; i ++ ) { 66const open = links [ i ]; 67const start = open . index + open [ 0 ]. length ; 68const next = links [ i + 1 ]?. index ?? html . length ; 69const chunk = html . slice ( start , next ); 70const close = chunk . indexOf ( '</a>' ); 71if ( close < 0 ) continue ; 72const href = / href=" ([ ^ " ] * ) " / i . exec ( open [ 0 ])?.[ 1 ]; 73const url = href ?realUrl ( href ) :null ; 74const title = plain ( chunk . slice ( 0 , close )); 75if ( ! 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). 77const block = html . lastIndexOf ( '<div class="result' , open . index ); 78if ( block >= 0 && / result--ad | result__ad / . test ( html . slice ( block , html . indexOf ( '>' , block ) + 1 ))) continue ; 79const snippetMatch = / < (?: a | td | div ) \b [ ^ > ] * class=" [ ^ " ] * \bresult__snippet\b [ ^ " ] * " [ ^ > ] * > ([ \s\S ] * ? ) <\/ (?: a | td | div ) > / i . exec ( chunk ); 80const snippet = snippetMatch ?plain ( snippetMatch [ 1 ]) :'' ; 81out . push ({ url, title, ...( snippet ?{ snippet} :{}) }); 82} 83return 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 ) { 88const out = []; 89const links = [ ...String ( html ). matchAll ( / <a\b [ ^ > ] * class= [ '" ][ ^ '" ] * \bresult-link\b [ ^ '" ] * [ '" ][ ^ > ] * > / gi )]; 90for ( let i = 0 ; i < links . length ; i ++ ) { 91const open = links [ i ]; 92const start = open . index + open [ 0 ]. length ; 93const next = links [ i + 1 ]?. index ?? html . length ; 94const chunk = html . slice ( start , next ); 95const close = chunk . indexOf ( '</a>' ); 96if ( close < 0 ) continue ; 97const href = / href= [ '" ]([ ^ '" ] * )[ '" ] / i . exec ( open [ 0 ])?.[ 1 ]; 98const url = href ?realUrl ( href ) :null ; 99const title = plain ( chunk . slice ( 0 , close )); 100if ( ! url || ! title ) continue ; 101const snippetMatch = / <td\b [ ^ > ] * class= [ '" ][ ^ '" ] * \bresult-snippet\b [ ^ '" ] * [ '" ][ ^ > ] * > ([ \s\S ] * ? ) <\/td> / i . exec ( chunk ); 102const snippet = snippetMatch ?plain ( snippetMatch [ 1 ]) :'' ; 103out . push ({ url, title, ...( snippet ?{ snippet} :{}) }); 104} 105return dedupe ( out ); 106} 107 108function dedupe ( rows ) { 109const seen = new Set (); 110return 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 ) { 115if ( status === 202 || status === 403 || status === 418 || status === 429 ) return true ; 116return / 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 { 122constructor ( 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 { 133constructor ({ now, sleep, random, gap= GAP_MS , jitter= JITTER_MS , perMinute= PER_MINUTE }) { 134Object . assign ( this , { now, sleep, random, gap, jitter, perMinute}); 135this . starts = []; this . last = 0 ; this . chain = Promise . resolve (); 136} 137turn ( signal ) { 138const run = this . chain . then ( async () => { 139const spacing = this . gap + Math . floor ( this . random () * this . jitter ); 140for (;;) { 141if ( signal ?. aborted ) throw new SearchUnavailable ( 'The search was cancelled.' , 'WEB_ABORTED' ); 142const t = this . now (); 143while ( this . starts . length && t - this . starts [ 0 ] > 60_000 ) this . starts . shift (); 144const wait = this . last ?Math . max ( spacing - ( t - this . last ), this . starts . length >= this . perMinute ?60_000 - ( t - this . starts [ 0 ]) :0 ) :0 ; 145if ( wait <= 0 ) break ; 146if ( wait > 30_000 ) throw new SearchUnavailable ( LIMITED_SENTENCE , 'WEB_RATE_LIMITED' ); 147await this . sleep ( wait ); 148} 149this . last = this . now (); 150this . starts . push ( this . last ); 151}); 152this . chain = run . catch (() => {}); 153return run ; 154} 155} 156 157const REFUSED = Symbol ( 'refused' ); 158const retryAfterMs = res => { 159const v = Number ( res ?. headers ?. get ?.( 'retry-after' )); 160return 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 } = {}) { 169const cache = new Map (); 170 171/** A source: its pacing, and what to do after it refuses. */ 172const source = ( id , name ) => ({ id, name, pacer :new Pacer ({ now, sleep, random}), blockedUntil :0 , strikes :0 , refusals :0 }); 173const ddg = source ( 'duckduckgo' , 'DuckDuckGo' ); 174const bing = source ( 'bing' , 'Bing' ); 175const refuse = ( s , res ) => { 176s . strikes += 1 ; s . refusals += 1 ; 177s . blockedUntil = now () + Math . max ( retryAfterMs ( res ), Math . min ( COOLDOWN_MS * 2 ** ( s . strikes - 1 ), COOLDOWN_MAX_MS )); 178}; 179const accepted = s => { s . strikes = 0 ; s . blockedUntil = 0 ; }; 180 181const 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 187async function get ( url , init , signal ) { 188const timeout = AbortSignal . timeout ( 15_000 ); 189const res = await fetchImpl ( url , { redirect :'follow' , ...init , signal :signal ?AbortSignal . any ([ signal , timeout ]) :timeout }); 190return { 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. */ 194async function ask ( s , makeRequest , signal ) { 195let failure ; 196for ( let attempt = 0 ; attempt < 2 ; attempt ++ ) { 197await s . pacer . turn ( signal ); 198try { 199const page = await get ( ...makeRequest (), signal ); 200if ( ! serverError ( page . status )) return page ; 201failure = new Error ( `HTTP ${ page . status } ` ); 202} catch ( error ) { 203if ( signal ?. aborted ) throw new SearchUnavailable ( 'The search was cancelled.' , 'WEB_ABORTED' , { cause :error }); 204failure = error ; 205} 206if ( attempt === 0 ) await sleep ( RETRY_PAUSE_MS + Math . floor ( random () * 1000 )); 207} 208return { failure}; 209} 210 211async function searchDuckDuckGo ( query , signal ) { 212const form = new URLSearchParams ({ q :query , b :'' , kl :'wt-wt' , df :'' }). toString (); 213const post = ( url , origin ) => () => [ url , { method :'POST' , headers :headers ( origin , { 'content-type' :'application/x-www-form-urlencoded' }), body :form }]; 214let reachedOnce = false ; 215for ( const [ url , origin , parse ] of [[ HTML_URL , 'https://html.duckduckgo.com' , parseHtmlResults ], [ LITE_URL , 'https://lite.duckduckgo.com' , parseLiteResults ]]) { 216const page = await ask ( ddg , post ( url , origin ), signal ); 217if ( page . failure ) return { failure :page . failure }; 218reachedOnce = true ; 219// A refusal on the first page is a refusal for the whole address: the lite page would only add one more strike. 220if ( looksBlocked ( page . status , page . html )) { refuse ( ddg , page . res ); return { refused :true }; } 221const sources = parse ( page . html ); 222if ( sources . length ) { accepted ( ddg ); return { sources}; } 223} 224if ( reachedOnce ) accepted ( ddg ); 225return { sources :[] }; 226} 227 228async function searchBing ( query , signal ) { 229const url = ` ${ BING_URL } ? ${ new URLSearchParams ({ q : query , setlang : 'en' })} ` ; 230const page = await ask ( bing , () => [ url , { method :'GET' , headers :headers ( null ) }], signal ); 231if ( page . failure ) return { failure :page . failure }; 232if ( bingLooksBlocked ( page . status , page . html )) { refuse ( bing , page . res ); return { refused :true }; } 233accepted ( bing ); 234return { sources :parseBingResults ( page . html ) }; 235} 236 237return { 238id :DDG_PROVIDER_ID , 239available :() => typeof fetchImpl === 'function' , 240/** What happened so far, for tests and for the status line in the app's log. */ 241status :() => ({ 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 }), 242async search ( request , signal ) { 243const query = String ( request . query ?? '' ). trim (). slice ( 0 , 400 ); 244if ( ! query ) throw new SearchUnavailable ( 'Type what to search for.' , 'WEB_PROVIDER_ERROR' ); 245const key = queryKey ( query ); 246const want = request . maxResults ?? 10 ; 247const hit = cache . get ( key ); 248if ( hit && now () - hit . at < CACHE_MS ) return { sources :hit . sources . slice ( 0 , want ), truncated :false }; 249let limited = false , unreachable = false ; 250for ( const [ s , run ] of [[ ddg , searchDuckDuckGo ], [ bing , searchBing ]]) { 251if ( s . blockedUntil > now ()) { limited = true ; continue ; } // asked again too soon: that only extends a block 252const result = await run ( query , signal ); 253if ( result . refused ) { limited = true ; continue ; } 254if ( result . failure ) { unreachable = true ; continue ; } 255if ( ! result . sources . length ) return { sources :[], truncated :false }; // a real search with no results is an answer, not an error 256cache . set ( key , { at :now (), sources :result . sources }); 257if ( cache . size > CACHE_SIZE ) cache . delete ( cache . keys (). next (). value ); 258return { sources :result . sources . slice ( 0 , want ), truncated :false }; 259} 260if ( limited ) throw new SearchUnavailable ( BLOCKED_MESSAGE , 'WEB_RATE_LIMITED' ); 261throw new SearchUnavailable ( unreachable ?UNREACHABLE_MESSAGE :BLOCKED_MESSAGE , unreachable ?'WEB_PROVIDER_ERROR' :'WEB_RATE_LIMITED' ); 262}, 263}; 264}