heartcode 0.1.30 → 0.1.32

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/src/web.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // web_fetch and web_search: a page as text, and search results, with no API key.
2
- // Search asks several engines at once and puts their results together (webSearch): public SearXNG
3
- // instances (the list from searx.space), Mwmbl, DuckDuckGo's HTML page, and for coding questions
4
- // Stack Overflow, npm and GitHub. Bing, Startpage, Mojeek, Google and Brave were tried too: blocked
2
+ // Search asks engines in your order (the settings page) and puts their results together (webSearch):
3
+ // your own SearXNG if you have one, public SearXNG instances (the list from searx.space), Mwmbl,
4
+ // DuckDuckGo's HTML page, and for coding questions Stack Overflow, npm and GitHub. Bing, Startpage, Mojeek, Google and Brave were tried too: blocked
5
5
  // (Brave refuses Node's connections), or junk results for scripts. When none can be reached, the
6
6
  // model is told "search is unreachable", so it stops searching instead of trying other words.
7
7
  import path from 'node:path'
8
- import { HOME, readJson, writeJson } from './config.js'
8
+ import { HOME, CONFIG_FILE, readJson, writeJson } from './config.js'
9
9
  import { keywords } from './memory.js'
10
10
  // ponytail: scraping, no API; add a keyed backend (Brave, Tavily) if DuckDuckGo blocks for good.
11
11
 
@@ -312,58 +312,96 @@ async function github(query, signal) {
312
312
  return ((await res.json()).items ?? []).map((r) => ({ title: `${r.full_name} (GitHub, ${r.stargazers_count}★)`, url: r.html_url, snippet: r.description ?? '' }))
313
313
  }
314
314
 
315
- // All asked at once; a search fails only when every one does. Public instances of the open-source
316
- // engines come and go (on 2026-10-31 most LibreY, Whoogle and 4get ones were down or blocked, so
317
- // they aren't here), and DuckDuckGo is blocked on some networks.
318
- export const ENGINES = { searx, mwmbl, duckduckgo, stackoverflow, npm, github }
315
+ // Your own SearXNG (cfg.search.searxng): its JSON API when it's switched on there, else its results
316
+ // page, as the public ones are asked.
317
+ async function mySearxng(query, signal, base = searchSettings().searxng) {
318
+ if (!base) throw new Error('no address set')
319
+ base = base.replace(/\/?$/, '/')
320
+ try {
321
+ const res = await fetch(`${base}search?format=json&q=${encodeURIComponent(query)}`, { headers: { ...HEADERS, accept: 'application/json' }, signal })
322
+ if (res.ok) return ((await res.json()).results ?? []).map((r) => ({ title: decode(String(r.title ?? '')), url: r.url, snippet: decode(String(r.content ?? '')) }))
323
+ } catch (e) {
324
+ if (signal?.aborted) throw e
325
+ }
326
+ return searxAt(base, query, signal)
327
+ }
328
+
329
+ // The settings page's Test button: does this address answer a search? → how many results.
330
+ export async function testSearxng(url) {
331
+ const hits = await mySearxng('open source search engine', AbortSignal.timeout(15_000), url)
332
+ return hits.filter((h) => h.url && h.title).length
333
+ }
334
+
335
+ // A search fails only when every engine does. Public instances of the open-source engines come and
336
+ // go (on 2026-10-31 most LibreY, Whoogle and 4get ones were down or blocked, so they aren't here),
337
+ // and DuckDuckGo is blocked on some networks.
338
+ export const ENGINES = { searxng: mySearxng, searx, duckduckgo, mwmbl, stackoverflow, npm, github }
339
+ export const ENGINE_NAMES = { searxng: 'Your SearXNG', searx: 'Public SearXNG instances', duckduckgo: 'DuckDuckGo', mwmbl: 'Mwmbl', stackoverflow: 'Stack Overflow', npm: 'npm', github: 'GitHub' }
340
+ // The settings page's order and switches (cfg.search: { searxng, order, off }), read at each search
341
+ // (a change applies at once, also in other HeartCodes). Engines missing from a saved order go after it.
342
+ export function searchSettings() {
343
+ const { searxng, order = [], off = [] } = readJson(CONFIG_FILE, {}).search ?? {}
344
+ const names = Object.keys(ENGINES)
345
+ const all = [...order.filter((n) => names.includes(n)), ...names.filter((n) => !order.includes(n))]
346
+ return { searxng: searxng || '', order: all, off, use: all.filter((n) => !off.includes(n) && (n !== 'searxng' || searxng)) }
347
+ }
348
+ // Asked in this order: the next one starts when the one before has answered without enough good
349
+ // results, failed, or taken 3 s; once there are enough, the rest aren't asked.
350
+ const STAGGER = 3000
319
351
  const SIDE = new Set(['stackoverflow', 'npm', 'github']) // for coding questions: a few each, when they match
320
- const GENERAL = new Set(['searx', 'duckduckgo']) // the broadest: waited for a while even when the fast ones have answered
321
352
 
322
- // Results as text: title, URL, where they came from and snippet, numbered. The engines are asked
323
- // together; once enough good results are in, the slower ones get 2 s more. Each result is scored on
324
- // its own (the query's words in it), one that several engines found ranks higher.
353
+ // Results as text: title, URL, where they came from and snippet, numbered. The engines are asked in
354
+ // your order (searchSettings, STAGGER). Each result is scored on its own (the query's words in it),
355
+ // one that several engines found ranks higher.
325
356
  let unreachableUntil = 0 // search couldn't be reached: said at once for a while, without waiting again
326
357
  let unreachableWhy = ''
327
- export async function webSearch(query, { signal, limit = 10, engines = ENGINES } = {}) {
358
+ export async function webSearch(query, { signal, limit = 10, engines = ENGINES, order } = {}) {
328
359
  const q = String(query ?? '').trim()
329
360
  if (!q) return 'error: no query given'
330
- if (Date.now() < unreachableUntil && engines === ENGINES) return unreachableWhy
361
+ if (Date.now() < unreachableUntil && engines === ENGINES && !order) return unreachableWhy
331
362
  const words = [...new Set(q.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}.+#-]{2,}/gu) ?? [])]
332
363
  const failed = []
333
364
  const merged = new Map()
334
365
  const stop = new AbortController()
335
366
  const each = AbortSignal.any([signal, stop.signal, AbortSignal.timeout(25_000)].filter(Boolean))
336
367
  const good = () => [...merged.values()].filter((x) => x.score >= 0.5).length
368
+ const names = order ?? (engines === ENGINES ? searchSettings().use : Object.keys(engines))
369
+ if (!names.length) return 'error: every search engine is switched off (settings page → General → Web search). web_fetch pages you know instead.'
370
+ const place = Object.fromEntries(names.map((n, i) => [n, i]))
337
371
  await new Promise((resolve) => {
338
- const names = Object.keys(engines)
339
- let left = names.length
340
- let answered = 0
341
- let general = 0
342
- let grace = null
343
- const done = () => (clearTimeout(grace), resolve())
344
- for (const name of names) {
372
+ let next = 0
373
+ let running = 0
374
+ let over = false
375
+ let stagger = null
376
+ const done = () => (over = true, clearTimeout(stagger), resolve())
377
+ const launch = () => {
378
+ clearTimeout(stagger)
379
+ if (over || next >= names.length) return
380
+ const name = names[next++]
381
+ running++
382
+ stagger = setTimeout(launch, STAGGER) // slow: the next one starts beside it
345
383
  engines[name](q, each)
346
384
  .then((hits) => {
347
385
  hits = hits.filter((h) => h.url && h.title)
348
386
  if (SIDE.has(name)) hits = hits.slice(0, 3)
349
387
  if (!hits.length) return failed.push(`${name}: no results`)
350
- answered++
351
- if (GENERAL.has(name)) general++
352
388
  for (const h of hits) {
353
389
  const key = h.url.replace(/^https?:\/\/(www\.)?/, '').replace(/[/#?]+$/, '')
354
390
  const had = merged.get(key)
355
391
  if (!had) merged.set(key, { hit: h, score: relevance(words, h), from: [name] })
356
392
  else if (!had.from.includes(name)) had.from.push(name)
357
393
  }
358
- // enough: the slower ones get a little more (a general engine, the best results, up to 12 s)
359
- if (answered >= 2 && good() >= limit) {
360
- clearTimeout(grace)
361
- grace = setTimeout(done, general ? 2000 : 12_000)
362
- }
363
394
  })
364
395
  .catch((e) => failed.push(`${name}: ${e.name === 'AbortError' || /aborted/.test(e.message) ? (signal?.aborted ? 'stopped' : 'too slow') : e.message}`))
365
- .finally(() => --left === 0 && done())
396
+ .finally(() => {
397
+ running--
398
+ if (over) return
399
+ if (good() >= limit) return done() // enough: the rest aren't asked
400
+ if (next < names.length) return launch() // not enough: the next one now
401
+ if (!running) done()
402
+ })
366
403
  }
404
+ launch()
367
405
  })
368
406
  stop.abort() // the slow ones: not waited for
369
407
  if (signal?.aborted) throw Object.assign(new Error('stopped'), { name: 'AbortError' })
@@ -373,7 +411,8 @@ export async function webSearch(query, { signal, limit = 10, engines = ENGINES }
373
411
  const textOf = (h) => `${h.title} ${h.snippet} ${h.url}`.toLowerCase()
374
412
  const weight = Object.fromEntries(words.map((w) => [w, Math.log(1 + all.length / (1 + all.filter((x) => textOf(x.hit).includes(w)).length))]))
375
413
  const total = words.reduce((t, w) => t + weight[w], 0) || 1
376
- const ranked = all.map((x) => ({ ...x, rank: words.reduce((t, w) => t + (textOf(x.hit).includes(w) ? weight[w] : 0), 0) / total + 0.15 * (x.from.length - 1) })).sort((a, b) => b.rank - a.rank)
414
+ // and a little by the engine's place in your order
415
+ const ranked = all.map((x) => ({ ...x, rank: words.reduce((t, w) => t + (textOf(x.hit).includes(w) ? weight[w] : 0), 0) / total + 0.15 * (x.from.length - 1) + 0.1 * (1 - Math.min(...x.from.map((n) => place[n] ?? names.length)) / names.length) })).sort((a, b) => b.rank - a.rank)
377
416
  if (ranked.length) {
378
417
  unreachableUntil = 0
379
418
  return ranked