heartcode 0.1.25 → 0.1.30

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
@@ -6,6 +6,7 @@
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
8
  import { HOME, 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
- const MAX = 10_000 // a part and its note fit in a tool result (agent.js keeps 12,000 characters of one)
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
- // A page's text, from `start` (characters), for the model.
64
- export async function webFetch(url, { start = 0, signal } = {}) {
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 `error: "${url}" is not a URL`
82
+ return { error: `"${url}" is not a URL` }
70
83
  }
71
- if (!/^https?:$/.test(u.protocol)) return 'error: only http and https URLs can be fetched'
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 `error: ${u.href} is ${type.split(';')[0]}, not text (${res.status})`
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 text = /html/.test(type) || /^\s*<(!doctype|html)/i.test(body) ? htmlToText(body, res.url) : body
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 `${res.ok ? '' : `error: HTTP ${res.status}\n`}${res.url !== u.href ? `(redirected to ${res.url})\n` : ''}${part || '(empty page)'}${more}`
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()