heartcode 0.1.27 → 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/CHANGELOG.md +123 -0
- package/README.md +84 -30
- package/SKILL.md +37 -11
- package/bin/heartcode.js +252 -56
- package/package.json +1 -1
- package/prompts/agent.md +131 -22
- package/src/agent.js +498 -77
- package/src/background.js +105 -0
- package/src/client.js +14 -3
- package/src/config.js +1 -1
- package/src/guided.js +7 -2
- package/src/headless.js +10 -4
- package/src/memory.js +6 -2
- package/src/research.js +142 -0
- package/src/sessions.js +4 -1
- package/src/settings.html +331 -76
- package/src/settings.js +73 -0
- package/src/telegram.js +81 -0
- package/src/tools.js +163 -53
- package/src/ui.js +235 -34
- package/src/web.js +150 -40
package/src/web.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// web_fetch and web_search: a page as text, and search results, with no API key.
|
|
2
|
-
// Search asks
|
|
3
|
-
// instances (the list from searx.space), Mwmbl,
|
|
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
|
+
import { keywords } from './memory.js'
|
|
9
10
|
// ponytail: scraping, no API; add a keyed backend (Brave, Tavily) if DuckDuckGo blocks for good.
|
|
10
11
|
|
|
11
12
|
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36'
|
|
@@ -42,6 +43,7 @@ export function htmlToText(html, base) {
|
|
|
42
43
|
} catch {}
|
|
43
44
|
return /^https?:/.test(url) && text !== url ? `[${text}](${url})` : text
|
|
44
45
|
})
|
|
46
|
+
.replace(/<table\b[^>]*>([\s\S]*?)<\/table>/gi, (m, inner) => tableToMarkdown(inner) ?? m)
|
|
45
47
|
.replace(/<li\b[^>]*>/gi, '\n- ')
|
|
46
48
|
.replace(/<(br|hr)\b[^>]*>/gi, '\n')
|
|
47
49
|
.replace(/<\/(p|div|section|tr|table|ul|ol|blockquote|dd|dt)>/gi, '\n')
|
|
@@ -58,26 +60,95 @@ export function htmlToText(html, base) {
|
|
|
58
60
|
return title && !text.startsWith(`# ${title}`) ? `# ${title}\n\n${text}` : text
|
|
59
61
|
}
|
|
60
62
|
|
|
61
|
-
|
|
63
|
+
// An HTML table's rows as a Markdown table (header row first); null when it isn't a real one (a
|
|
64
|
+
// layout table of one column), which is then left to the plain conversion.
|
|
65
|
+
function tableToMarkdown(inner) {
|
|
66
|
+
const cell = (h) => decode(h.replace(/<br\b[^>]*>/gi, ' ').replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').replace(/\|/g, '\\|').trim()
|
|
67
|
+
const rows = [...inner.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)].map((r) => [...r[1].matchAll(/<t[hd]\b[^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => cell(c[1]))).filter((r) => r.length)
|
|
68
|
+
const cols = Math.max(0, ...rows.map((r) => r.length))
|
|
69
|
+
if (cols < 2 || rows.length < 2) return null
|
|
70
|
+
const line = (r) => `| ${[...r, ...Array(cols - r.length).fill('')].join(' | ')} |`
|
|
71
|
+
return `\n\n${line(rows[0])}\n|${' --- |'.repeat(cols)}\n${rows.slice(1).map(line).join('\n')}\n\n`
|
|
72
|
+
}
|
|
62
73
|
|
|
63
|
-
//
|
|
64
|
-
|
|
74
|
+
const MAX = 10_000 // what one web_fetch result shows (agent.js keeps about that much of one)
|
|
75
|
+
|
|
76
|
+
// A page, fetched and turned into Markdown: { url (after redirects), title, text, status, ok } or { error }.
|
|
77
|
+
export async function fetchPage(url, { signal } = {}) {
|
|
65
78
|
let u
|
|
66
79
|
try {
|
|
67
80
|
u = new URL(/^\w+:\/\//.test(url) ? url : `https://${url}`)
|
|
68
81
|
} catch {
|
|
69
|
-
return
|
|
82
|
+
return { error: `"${url}" is not a URL` }
|
|
70
83
|
}
|
|
71
|
-
if (!/^https?:$/.test(u.protocol)) return
|
|
84
|
+
if (!/^https?:$/.test(u.protocol)) return { error: 'only http and https URLs can be fetched' }
|
|
72
85
|
const res = await fetch(u, { headers: HEADERS, redirect: 'follow', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000) })
|
|
73
86
|
const type = res.headers.get('content-type') ?? ''
|
|
74
|
-
if (!/text|json|xml|javascript|markdown/.test(type) && type) return
|
|
87
|
+
if (!/text|json|xml|javascript|markdown/.test(type) && type) return { error: `${u.href} is ${type.split(';')[0]}, not text (${res.status})` }
|
|
75
88
|
const body = await res.text()
|
|
76
|
-
const
|
|
89
|
+
const html = /html/.test(type) || /^\s*<(!doctype|html)/i.test(body)
|
|
90
|
+
const text = html ? htmlToText(body, res.url) : body
|
|
91
|
+
const title = html ? decode(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(body)?.[1]?.trim() ?? '') : ''
|
|
92
|
+
return { url: res.url || u.href, asked: u.href, title, text, status: res.status, ok: res.ok }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// A page's text, from `start` (characters), for the model (no file to point at).
|
|
96
|
+
export async function webFetch(url, { start = 0, signal } = {}) {
|
|
97
|
+
const p = await fetchPage(url, { signal })
|
|
98
|
+
if (p.error) return `error: ${p.error}`
|
|
77
99
|
const from = Math.max(0, Number(start) || 0)
|
|
78
|
-
const part = text.slice(from, from + MAX)
|
|
79
|
-
const more = from + MAX < text.length ? `\n\n… (${text.length} characters in all; call web_fetch with start: ${from + MAX} for more)` : ''
|
|
80
|
-
return `${
|
|
100
|
+
const part = p.text.slice(from, from + MAX)
|
|
101
|
+
const more = from + MAX < p.text.length ? `\n\n… (${p.text.length} characters in all; call web_fetch with start: ${from + MAX} for more)` : ''
|
|
102
|
+
return `${p.ok ? '' : `error: HTTP ${p.status}\n`}${p.url !== p.asked ? `(redirected to ${p.url})\n` : ''}${part || '(empty page)'}${more}`
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// What the model is shown of a page that is saved whole in `file` (its text starting at line
|
|
106
|
+
// `bodyLine` there). A short page: all of it. A long one: its outline (each heading with its line in
|
|
107
|
+
// the file) and the sections that match what the model is looking for (else the page's start), as
|
|
108
|
+
// much as fits — the rest is a read_file of those lines away, not lost.
|
|
109
|
+
export function pageView(text, { lookFor = '', file = '', bodyLine = 1, max = MAX } = {}) {
|
|
110
|
+
const lines = String(text).split('\n')
|
|
111
|
+
if (text.length <= max) return `${text || '(empty page)'}${file ? `\n\n(This page is saved in ${file}.)` : ''}`
|
|
112
|
+
// sections: from one heading to the next (the part before the first heading is one too)
|
|
113
|
+
const sections = []
|
|
114
|
+
let fence = false
|
|
115
|
+
for (const [i, l] of lines.entries()) {
|
|
116
|
+
if (/^\s*```/.test(l)) fence = !fence
|
|
117
|
+
if ((!fence && /^#{1,6}\s/.test(l)) || i === 0) sections.push({ start: i, heading: /^#{1,6}\s/.test(l) ? l.trim() : '' })
|
|
118
|
+
}
|
|
119
|
+
for (const [k, sec] of sections.entries()) sec.end = (sections[k + 1]?.start ?? lines.length) - 1
|
|
120
|
+
const at = (i) => i + bodyLine // a line of the text → its line in the saved file
|
|
121
|
+
let outline = sections.filter((x) => x.heading).map((x) => `${' '.repeat(Math.max(0, x.heading.match(/^#+/)[0].length - 1))}- ${x.heading.replace(/^#+\s*/, '')} (line ${at(x.start)})`).join('\n')
|
|
122
|
+
if (outline.length > 3000) outline = `${outline.slice(0, 3000).replace(/\n[^\n]*$/, '')}\n- … (more headings: search the file for them)`
|
|
123
|
+
const words = new Set(keywords(lookFor))
|
|
124
|
+
const scored = sections.map((x, k) => {
|
|
125
|
+
const body = lines.slice(x.start, x.end + 1).join('\n')
|
|
126
|
+
const hw = new Set(keywords(x.heading))
|
|
127
|
+
let score = 0
|
|
128
|
+
for (const w of new Set(keywords(body))) if (words.has(w)) score += hw.has(w) ? 3 : 1
|
|
129
|
+
return { ...x, k, body, score }
|
|
130
|
+
})
|
|
131
|
+
const room = max - outline.length - 400
|
|
132
|
+
const pick = []
|
|
133
|
+
let used = 0
|
|
134
|
+
const order = words.size && scored.some((x) => x.score > 0) ? [...scored].filter((x) => x.score > 0).sort((a, b) => b.score - a.score) : scored
|
|
135
|
+
for (const x of order) {
|
|
136
|
+
const piece = x.body.length > room - used ? x.body.slice(0, Math.max(0, room - used)) : x.body
|
|
137
|
+
if (piece.length < 200 && pick.length) break
|
|
138
|
+
pick.push({ ...x, piece })
|
|
139
|
+
used += piece.length
|
|
140
|
+
if (used >= room) break
|
|
141
|
+
}
|
|
142
|
+
pick.sort((a, b) => a.k - b.k)
|
|
143
|
+
const shown = pick.map((x) => `[lines ${at(x.start)}–${at(x.start + x.piece.split('\n').length - 1)}]\n${x.piece}`).join('\n\n…\n\n')
|
|
144
|
+
const what = words.size && order !== scored ? `The parts that match "${lookFor}"` : 'The start of the page'
|
|
145
|
+
return [
|
|
146
|
+
`This page is long (${lines.length} lines, ${text.length} characters).${file ? ` All of it is saved in ${file}: read_file it with start_line/end_line for any part (the line numbers below are that file's), or search in it.` : ''}`,
|
|
147
|
+
outline && `Outline:\n${outline}`,
|
|
148
|
+
`${what}:\n\n${shown}`,
|
|
149
|
+
]
|
|
150
|
+
.filter(Boolean)
|
|
151
|
+
.join('\n\n')
|
|
81
152
|
}
|
|
82
153
|
|
|
83
154
|
const strip = (s) => decode(String(s).replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim()
|
|
@@ -241,58 +312,96 @@ async function github(query, signal) {
|
|
|
241
312
|
return ((await res.json()).items ?? []).map((r) => ({ title: `${r.full_name} (GitHub, ${r.stargazers_count}★)`, url: r.html_url, snippet: r.description ?? '' }))
|
|
242
313
|
}
|
|
243
314
|
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
|
|
247
|
-
|
|
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
|
|
248
351
|
const SIDE = new Set(['stackoverflow', 'npm', 'github']) // for coding questions: a few each, when they match
|
|
249
|
-
const GENERAL = new Set(['searx', 'duckduckgo']) // the broadest: waited for a while even when the fast ones have answered
|
|
250
352
|
|
|
251
|
-
// Results as text: title, URL, where they came from and snippet, numbered. The engines are asked
|
|
252
|
-
//
|
|
253
|
-
//
|
|
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.
|
|
254
356
|
let unreachableUntil = 0 // search couldn't be reached: said at once for a while, without waiting again
|
|
255
357
|
let unreachableWhy = ''
|
|
256
|
-
export async function webSearch(query, { signal, limit = 10, engines = ENGINES } = {}) {
|
|
358
|
+
export async function webSearch(query, { signal, limit = 10, engines = ENGINES, order } = {}) {
|
|
257
359
|
const q = String(query ?? '').trim()
|
|
258
360
|
if (!q) return 'error: no query given'
|
|
259
|
-
if (Date.now() < unreachableUntil && engines === ENGINES) return unreachableWhy
|
|
361
|
+
if (Date.now() < unreachableUntil && engines === ENGINES && !order) return unreachableWhy
|
|
260
362
|
const words = [...new Set(q.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}.+#-]{2,}/gu) ?? [])]
|
|
261
363
|
const failed = []
|
|
262
364
|
const merged = new Map()
|
|
263
365
|
const stop = new AbortController()
|
|
264
366
|
const each = AbortSignal.any([signal, stop.signal, AbortSignal.timeout(25_000)].filter(Boolean))
|
|
265
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]))
|
|
266
371
|
await new Promise((resolve) => {
|
|
267
|
-
|
|
268
|
-
let
|
|
269
|
-
let
|
|
270
|
-
let
|
|
271
|
-
|
|
272
|
-
const
|
|
273
|
-
|
|
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
|
|
274
383
|
engines[name](q, each)
|
|
275
384
|
.then((hits) => {
|
|
276
385
|
hits = hits.filter((h) => h.url && h.title)
|
|
277
386
|
if (SIDE.has(name)) hits = hits.slice(0, 3)
|
|
278
387
|
if (!hits.length) return failed.push(`${name}: no results`)
|
|
279
|
-
answered++
|
|
280
|
-
if (GENERAL.has(name)) general++
|
|
281
388
|
for (const h of hits) {
|
|
282
389
|
const key = h.url.replace(/^https?:\/\/(www\.)?/, '').replace(/[/#?]+$/, '')
|
|
283
390
|
const had = merged.get(key)
|
|
284
391
|
if (!had) merged.set(key, { hit: h, score: relevance(words, h), from: [name] })
|
|
285
392
|
else if (!had.from.includes(name)) had.from.push(name)
|
|
286
393
|
}
|
|
287
|
-
// enough: the slower ones get a little more (a general engine, the best results, up to 12 s)
|
|
288
|
-
if (answered >= 2 && good() >= limit) {
|
|
289
|
-
clearTimeout(grace)
|
|
290
|
-
grace = setTimeout(done, general ? 2000 : 12_000)
|
|
291
|
-
}
|
|
292
394
|
})
|
|
293
395
|
.catch((e) => failed.push(`${name}: ${e.name === 'AbortError' || /aborted/.test(e.message) ? (signal?.aborted ? 'stopped' : 'too slow') : e.message}`))
|
|
294
|
-
.finally(() =>
|
|
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
|
+
})
|
|
295
403
|
}
|
|
404
|
+
launch()
|
|
296
405
|
})
|
|
297
406
|
stop.abort() // the slow ones: not waited for
|
|
298
407
|
if (signal?.aborted) throw Object.assign(new Error('stopped'), { name: 'AbortError' })
|
|
@@ -302,7 +411,8 @@ export async function webSearch(query, { signal, limit = 10, engines = ENGINES }
|
|
|
302
411
|
const textOf = (h) => `${h.title} ${h.snippet} ${h.url}`.toLowerCase()
|
|
303
412
|
const weight = Object.fromEntries(words.map((w) => [w, Math.log(1 + all.length / (1 + all.filter((x) => textOf(x.hit).includes(w)).length))]))
|
|
304
413
|
const total = words.reduce((t, w) => t + weight[w], 0) || 1
|
|
305
|
-
|
|
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)
|
|
306
416
|
if (ranked.length) {
|
|
307
417
|
unreachableUntil = 0
|
|
308
418
|
return ranked
|