heartcode 0.1.27 → 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/CHANGELOG.md +78 -0
- package/README.md +73 -29
- package/SKILL.md +31 -11
- package/bin/heartcode.js +20 -2
- package/package.json +1 -1
- package/prompts/agent.md +110 -20
- package/src/agent.js +426 -70
- package/src/client.js +14 -3
- package/src/config.js +1 -1
- package/src/guided.js +7 -2
- package/src/headless.js +8 -3
- package/src/memory.js +6 -2
- package/src/research.js +142 -0
- package/src/sessions.js +4 -1
- package/src/settings.html +212 -57
- package/src/settings.js +38 -0
- package/src/telegram.js +81 -0
- package/src/tools.js +133 -48
- package/src/ui.js +2 -1
- package/src/web.js +81 -10
package/src/tools.js
CHANGED
|
@@ -2,16 +2,17 @@ import fs from 'node:fs'
|
|
|
2
2
|
import { createHash } from 'node:crypto'
|
|
3
3
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
4
4
|
import { log } from './log.js'
|
|
5
|
-
import { slug, fullSlug } from './memory.js'
|
|
5
|
+
import { slug, fullSlug, keywords } from './memory.js'
|
|
6
6
|
import { fillArgs } from './skills.js'
|
|
7
7
|
import { prompt } from './prompts.js'
|
|
8
8
|
import path from 'node:path'
|
|
9
9
|
import os from 'node:os'
|
|
10
10
|
import { spawn, execFileSync } from 'node:child_process'
|
|
11
11
|
import { applyEdit, closest, trimBlank } from './edit.js'
|
|
12
|
-
import { readJson } from './config.js'
|
|
12
|
+
import { readJson, HOME } from './config.js'
|
|
13
13
|
import { c, diffLines, renderDiff } from './ui.js'
|
|
14
|
-
import { webFetch, webSearch } from './web.js'
|
|
14
|
+
import { webFetch, webSearch, fetchPage, pageView } from './web.js'
|
|
15
|
+
import { savePage, saveSearch, findResearch } from './research.js'
|
|
15
16
|
import { runHooks } from './hooks.js'
|
|
16
17
|
import { parsePatch, applyChunks } from './patch.js'
|
|
17
18
|
import { formatFile } from './format.js'
|
|
@@ -24,13 +25,16 @@ export const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s)
|
|
|
24
25
|
|
|
25
26
|
// Tool output too long for the conversation is saved here (one folder per chat), where read_file
|
|
26
27
|
// and search can read it although it's outside the project.
|
|
27
|
-
export const OUTPUTS = path.join(
|
|
28
|
+
export const OUTPUTS = path.join(HOME, 'outputs') // kept with the chat: a resumed one's pointers still open
|
|
29
|
+
const LEGACY_OUTPUTS = path.join(os.tmpdir(), 'heartcode-outputs') // where older HeartCode kept them
|
|
30
|
+
export const isSavedOutput = (abs) => [OUTPUTS, LEGACY_OUTPUTS].some((d) => String(abs).startsWith(d + path.sep))
|
|
28
31
|
// data: text, or an image's bytes (ext: png…)
|
|
32
|
+
let saved = 0
|
|
29
33
|
export function saveOutput(chatId, name, data, ext = 'txt') {
|
|
30
34
|
try {
|
|
31
35
|
const dir = path.join(OUTPUTS, String(chatId ?? 'chat'))
|
|
32
36
|
fs.mkdirSync(dir, { recursive: true })
|
|
33
|
-
const file = path.join(dir, `${Date.now().toString(36)}-${String(name).replace(/[^\w-]/g, '_').slice(0, 60)}.${ext}`)
|
|
37
|
+
const file = path.join(dir, `${Date.now().toString(36)}-${(++saved).toString(36)}-${String(name).replace(/[^\w-]/g, '_').slice(0, 60)}.${ext}`) // several in one millisecond: each its own file
|
|
34
38
|
fs.writeFileSync(file, data)
|
|
35
39
|
return file
|
|
36
40
|
} catch (e) {
|
|
@@ -44,7 +48,7 @@ export function resolveIn(root, p) {
|
|
|
44
48
|
if (!clean) throw new Error('no path given')
|
|
45
49
|
const bare = root.replace(/^[\\/]+/, '') // the project's own path, its leading "/" left out by a sloppy copy
|
|
46
50
|
let abs = clean === bare || clean.startsWith(bare + '/') ? path.join(root, clean.slice(bare.length)) : path.resolve(root, clean)
|
|
47
|
-
if (abs
|
|
51
|
+
if (isSavedOutput(abs)) return abs // a saved tool output
|
|
48
52
|
// "num.js:" or "num.js," from a sloppy model: the file without the stray mark, if that one exists
|
|
49
53
|
const trimmed = path.resolve(root, clean.replace(/[:;,.]+$/, ''))
|
|
50
54
|
if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
|
|
@@ -204,7 +208,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
|
|
|
204
208
|
re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
|
|
205
209
|
}
|
|
206
210
|
const abs = sub ? resolveIn(root, sub) : ''
|
|
207
|
-
|
|
211
|
+
let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
|
|
212
|
+
try {
|
|
213
|
+
single = Boolean(abs) && fs.statSync(abs).isFile()
|
|
214
|
+
} catch {}
|
|
215
|
+
const saved = isSavedOutput(abs) || single
|
|
208
216
|
const prefix = sub && !saved ? path.relative(root, abs) : ''
|
|
209
217
|
const hits = []
|
|
210
218
|
for (const f of saved ? [abs] : listFiles(root)) {
|
|
@@ -449,6 +457,7 @@ function changesSince(s, before) {
|
|
|
449
457
|
const notes = []
|
|
450
458
|
for (const rel of new Set([...before.keys(), ...after.keys()])) {
|
|
451
459
|
if (before.get(rel) === after.get(rel)) continue
|
|
460
|
+
if (/^\.heartcode[\\/]/.test(rel)) continue // HeartCode's own (research, memory, models) written meanwhile — a page fetched while the command ran — not the command's
|
|
452
461
|
if (!(before.complete && after.complete) && (!before.has(rel) || !after.has(rel))) continue // a list cut at its limit: in one, not the other, says nothing
|
|
453
462
|
const old = was.get(rel)
|
|
454
463
|
const next = after.has(rel) ? s.fileCache.get(rel)?.text : undefined
|
|
@@ -490,8 +499,8 @@ export const TOOL_DEFS = [
|
|
|
490
499
|
{ name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
|
|
491
500
|
{ name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str }, ['command']) },
|
|
492
501
|
{ name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] } }, ['content', 'status']) } }, ['todos']) },
|
|
493
|
-
{ name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str }, ['query']) },
|
|
494
|
-
{ name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, start: int }, ['url']) },
|
|
502
|
+
{ name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
|
|
503
|
+
{ name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
|
|
495
504
|
{ name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' } }, ['question']) },
|
|
496
505
|
]
|
|
497
506
|
|
|
@@ -513,21 +522,20 @@ export function readOnlyCommand(cmd) {
|
|
|
513
522
|
return c.split(/\s*(?:&&|\|\||;|\|)\s*/).every((part) => READ_ONLY.test(part))
|
|
514
523
|
}
|
|
515
524
|
|
|
516
|
-
// MCP servers' tools as the model sees them:
|
|
517
|
-
//
|
|
518
|
-
//
|
|
519
|
-
//
|
|
520
|
-
//
|
|
521
|
-
|
|
525
|
+
// MCP servers' tools as the model sees them: one tool, mcp, whose description lists every server's
|
|
526
|
+
// tools by name with one line on what each does — not each tool's whole schema in every request
|
|
527
|
+
// (two browser servers' schemas alone were ~14k tokens a request). A tool's arguments come when
|
|
528
|
+
// they're needed: "describe" shows them, and a call whose arguments don't fit its schema gets the
|
|
529
|
+
// schema back with what's wrong (nothing is sent to the server). Sets s.mcpDirect
|
|
530
|
+
// (mcp__server__tool → { server, tool, def }: only to understand a call by that name — an older
|
|
531
|
+
// conversation's, or a model used to Claude Code's names), s.mcpCatalog and s.mcpInstructions (what
|
|
532
|
+
// the servers say about using them).
|
|
522
533
|
export async function loadMcpTools(s, signal) {
|
|
523
|
-
if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(),
|
|
534
|
+
if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(), mcpInstructions: '' })
|
|
524
535
|
const catalog = await s.mcp.catalog(signal)
|
|
525
|
-
// the servers with the fewest tools first, while they fit
|
|
526
|
-
const known = [...catalog].sort((a, b) => a[1].tools.length - b[1].tools.length)
|
|
527
536
|
const direct = new Map()
|
|
528
537
|
const notes = []
|
|
529
|
-
for (const [server, { tools, instructions }] of
|
|
530
|
-
if (direct.size + tools.length > MAX_MCP_TOOLS) continue
|
|
538
|
+
for (const [server, { tools, instructions }] of catalog) {
|
|
531
539
|
for (const t of tools) {
|
|
532
540
|
let n = mcpName(server, t.name)
|
|
533
541
|
if (direct.has(n)) n = `${n.slice(0, 57)}_${createHash('sha256').update(`${server}/${t.name}`).digest('hex').slice(0, 6)}` // cut to the same 64 characters as another
|
|
@@ -535,33 +543,26 @@ export async function loadMcpTools(s, signal) {
|
|
|
535
543
|
}
|
|
536
544
|
if (instructions) notes.push(`### ${server}\n${instructions}`)
|
|
537
545
|
}
|
|
538
|
-
|
|
539
|
-
return Object.assign(s, { mcpDirect: direct, mcpMeta: s.mcp.names.filter((n) => !shown.has(n)), mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
|
|
546
|
+
return Object.assign(s, { mcpDirect: direct, mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
|
|
540
547
|
}
|
|
541
548
|
// Tool names may only have letters, digits, _ and - (64 at most).
|
|
542
549
|
export const mcpName = (server, tool) => `mcp__${server}__${tool}`.replace(/[^\w-]/g, '_').slice(0, 64)
|
|
543
|
-
// A
|
|
544
|
-
|
|
545
|
-
if (Array.isArray(x)) return x.map(cleanSchema)
|
|
546
|
-
if (!x || typeof x !== 'object') return x
|
|
547
|
-
return Object.fromEntries(Object.entries(x).filter(([k]) => k !== '$schema').map(([k, v]) => [k, cleanSchema(v)]))
|
|
548
|
-
}
|
|
549
|
-
function mcpDefs(s) {
|
|
550
|
-
return [...(s.mcpDirect?.entries() ?? [])].map(([name, { server, tool, def }]) => {
|
|
551
|
-
const schema = cleanSchema(def.inputSchema ?? {})
|
|
552
|
-
return { name, description: clip(String(def.description ?? `${tool} (${server})`).trim(), 2000), parameters: { ...schema, type: 'object', properties: schema.properties ?? {} } }
|
|
553
|
-
})
|
|
554
|
-
}
|
|
550
|
+
// A tool's description cut to its first sentence (what it does), for the list.
|
|
551
|
+
const firstLine = (d) => String(d ?? '').trim().split(/\n|(?<=\.)\s/)[0].slice(0, 140)
|
|
555
552
|
|
|
556
|
-
// The MCP servers
|
|
557
|
-
// something to offer.
|
|
553
|
+
// The MCP servers (one tool for all of their tools), the memory and the skill loader; each only when
|
|
554
|
+
// there's something to offer.
|
|
558
555
|
export function extraTools(s) {
|
|
559
|
-
const out =
|
|
560
|
-
const
|
|
561
|
-
if (
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
556
|
+
const out = []
|
|
557
|
+
const servers = s.mcp?.names ?? []
|
|
558
|
+
if (servers.length) {
|
|
559
|
+
const list = (n) => {
|
|
560
|
+
const cfg = s.mcp.get(n)?.cfg ?? {}
|
|
561
|
+
const tools = s.mcpCatalog?.get(n)?.tools
|
|
562
|
+
const head = `${n}${cfg.description ? ` — ${cfg.description}` : ''}`
|
|
563
|
+
return tools ? `${head}\n${tools.map((t) => ` - ${t.name}: ${firstLine(t.description)}`).join('\n')}` : `${head} (its tools aren't known yet: tool "list" shows them)`
|
|
564
|
+
}
|
|
565
|
+
out.push({ name: 'mcp', description: prompt('agent/tool-mcp', { servers: servers.map(list).join('\n') }), parameters: obj({ server: str, tool: str, arguments: { type: 'object' } }, ['server', 'tool']) })
|
|
565
566
|
}
|
|
566
567
|
if (s.memory) {
|
|
567
568
|
out.push({
|
|
@@ -640,9 +641,40 @@ async function webTool(s, name, args, signal) {
|
|
|
640
641
|
if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
|
|
641
642
|
const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
|
|
642
643
|
if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
|
|
643
|
-
|
|
644
|
-
|
|
644
|
+
// what this message's research is for: the page's look_for, else the last search, else the task
|
|
645
|
+
const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
|
|
646
|
+
if (name === 'web_search') {
|
|
647
|
+
s.lastQuery = what
|
|
648
|
+
// already read for this project: offered first (the model decides: use it, or search fresh)
|
|
649
|
+
const saved = !args.fresh && s.root && !s.noResearch ? findResearch(s.root, what, 5).filter((r) => r.kind !== 'search') : []
|
|
650
|
+
if (saved.length) {
|
|
651
|
+
log('research', `"${what}": ${saved.length} saved page(s) offered first`)
|
|
652
|
+
return prompt('agent/research-saved', { query: what, pages: saved.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}${r.used_for ? `; used for: ${r.used_for}` : ''}) → ${r.file}`).join('\n') })
|
|
653
|
+
}
|
|
654
|
+
s.ui.spinner(`searching: ${clip(what, 60)}`)
|
|
655
|
+
const out = await webSearch(what, { signal })
|
|
656
|
+
if (s.root && !s.noResearch && !/^(error:|no results)/.test(out)) {
|
|
657
|
+
const { file } = saveSearch(s.root, what, out)
|
|
658
|
+
s.research?.push({ kind: 'search', file, title: `Search: ${what}` })
|
|
659
|
+
}
|
|
660
|
+
return out
|
|
661
|
+
}
|
|
662
|
+
s.ui.spinner(`fetching ${clip(what, 60)}`)
|
|
663
|
+
if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal }) // nothing kept (--no-memory)
|
|
664
|
+
const page = await fetchPage(what, { signal })
|
|
665
|
+
if (page.error) return `error: ${page.error}`
|
|
666
|
+
const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
|
|
667
|
+
if (!page.ok || !page.text.trim()) return `${head}${page.text.slice(0, MAX_PAGE) || '(empty page)'}` // an error page isn't worth keeping
|
|
668
|
+
const { file, bodyLine } = savePage(s.root, { url: page.url, title: page.title, text: page.text, query: purpose })
|
|
669
|
+
s.research?.push({ kind: 'page', file, url: page.url, title: page.title || page.url })
|
|
670
|
+
const id = runningCall.getStore()
|
|
671
|
+
if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
|
|
672
|
+
log('research', `saved ${page.url} → ${file}`)
|
|
673
|
+
// "start": the part from there on, as before (an older conversation's way of reading on)
|
|
674
|
+
if (Number(args.start) > 0) return `${head}${await webFetch(page.url, { start: args.start, signal })}\n\n(All of this page is saved in ${file}.)`
|
|
675
|
+
return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
|
|
645
676
|
}
|
|
677
|
+
const MAX_PAGE = 10_000
|
|
646
678
|
|
|
647
679
|
function memoryTool(s, args) {
|
|
648
680
|
const m = s.memory
|
|
@@ -653,8 +685,16 @@ function memoryTool(s, args) {
|
|
|
653
685
|
if (!args.content && !args.description) return 'error: write needs at least content or a description'
|
|
654
686
|
if (!String(args.name ?? '').trim() && !String(args.description ?? '').trim()) return 'error: write needs a "name" (or a description to name it by). Nothing was saved.'
|
|
655
687
|
if (String(args.name ?? '').trim() && fullSlug(args.name).length > 60) return 'error: the name is too long (60 characters at most, as a file name). Nothing was saved.'
|
|
688
|
+
const isNew = !m.read(args.name || args.description)
|
|
656
689
|
const n = m.write(args)
|
|
657
|
-
|
|
690
|
+
// a new note that says much the same as one there already: said, so they're merged, not piled up
|
|
691
|
+
const words = new Set(keywords(`${n} ${args.description ?? ''}`))
|
|
692
|
+
const overlap = (x) => {
|
|
693
|
+
const theirs = new Set(keywords(`${x.name} ${x.description}`))
|
|
694
|
+
return [...theirs].filter((w) => words.has(w)).length / Math.max(1, Math.min(theirs.size, words.size))
|
|
695
|
+
}
|
|
696
|
+
const similar = isNew && words.size >= 3 ? m.list().filter((x) => x.name !== n && overlap(x) >= 0.6).slice(0, 3) : []
|
|
697
|
+
return `Saved [[${n}]]${m.read(n)?.scope === 'global' ? ' (global)' : ''}.${similar.length ? ` Similar notes exist: ${similar.map((x) => `[[${x.name}]] — ${x.description}`).join('; ')}. If one says the same thing, merge them: write the merged note under one name and delete the other.` : ''}`
|
|
658
698
|
}
|
|
659
699
|
case 'read': {
|
|
660
700
|
if (!name.trim()) return 'error: read needs the note\'s "name" (search finds notes by words).'
|
|
@@ -704,16 +744,61 @@ async function mcpTool(s, args, signal) {
|
|
|
704
744
|
s.ui.spinner(`starting ${server.name}`)
|
|
705
745
|
const tools = await server.listTools(signal)
|
|
706
746
|
if (tool === 'list') return tools.map((t) => `${t.name}: ${String(t.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 160)}`).join('\n')
|
|
707
|
-
const t = tools.find((x) => x.name === a.name)
|
|
708
|
-
return t ?
|
|
747
|
+
const t = tools.find((x) => x.name === (a.name ?? a.tool))
|
|
748
|
+
return t ? describeTool(t) : `error: ${server.name} has no tool "${a.name ?? a.tool}"; tool "list" shows its tools`
|
|
709
749
|
}
|
|
710
750
|
return callMcp(s, server, tool, a, signal)
|
|
711
751
|
}
|
|
712
752
|
|
|
753
|
+
// What's wrong with a call's arguments for a tool's JSON schema (the common part of it: required,
|
|
754
|
+
// unknown names, types, enums), or [] when they fit. Unknown names get the closest real one.
|
|
755
|
+
export function argProblems(schema, a) {
|
|
756
|
+
const props = schema?.properties ?? {}
|
|
757
|
+
const out = []
|
|
758
|
+
if (!a || typeof a !== 'object' || Array.isArray(a)) return ['"arguments" must be an object']
|
|
759
|
+
for (const k of schema?.required ?? []) if (a[k] === undefined) out.push(`"${k}" is required`)
|
|
760
|
+
const near = (k) => {
|
|
761
|
+
const d = (x, y) => {
|
|
762
|
+
const m = Array.from({ length: x.length + 1 }, (_, i) => [i, ...Array(y.length).fill(0)])
|
|
763
|
+
for (let j = 1; j <= y.length; j++) m[0][j] = j
|
|
764
|
+
for (let i = 1; i <= x.length; i++) for (let j = 1; j <= y.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1))
|
|
765
|
+
return m[x.length][y.length]
|
|
766
|
+
}
|
|
767
|
+
const best = Object.keys(props).map((p) => [p, d(k.toLowerCase(), p.toLowerCase())]).sort((x, y) => x[1] - y[1])[0]
|
|
768
|
+
return best && best[1] <= Math.max(2, Math.floor(best[0].length / 3)) ? ` (did you mean "${best[0]}"?)` : ''
|
|
769
|
+
}
|
|
770
|
+
const typeOk = (t, v) => ({ string: typeof v === 'string', number: typeof v === 'number', integer: Number.isInteger(v), boolean: typeof v === 'boolean', array: Array.isArray(v), object: v !== null && typeof v === 'object' && !Array.isArray(v), null: v === null })[t] ?? true
|
|
771
|
+
for (const [k, v] of Object.entries(a)) {
|
|
772
|
+
const p = props[k]
|
|
773
|
+
if (!p) {
|
|
774
|
+
if (schema?.properties && schema.additionalProperties !== true) out.push(`"${k}" is not one of its arguments${near(k)}`)
|
|
775
|
+
continue
|
|
776
|
+
}
|
|
777
|
+
const types = [p.type ?? []].flat()
|
|
778
|
+
if (types.length && !types.some((t) => typeOk(t, v))) out.push(`"${k}" must be ${types.join(' or ')}, not ${Array.isArray(v) ? 'an array' : v === null ? 'null' : typeof v}`)
|
|
779
|
+
if (p.enum && !p.enum.includes(v)) out.push(`"${k}" must be one of ${p.enum.map((x) => JSON.stringify(x)).join(', ')}`)
|
|
780
|
+
}
|
|
781
|
+
return out
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// One tool's description and arguments, for the model (describe, or a call that didn't fit).
|
|
785
|
+
const describeTool = (t) => `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}`
|
|
786
|
+
|
|
713
787
|
// One MCP tool call. Asked about like a command, unless the server marks the tool read-only.
|
|
714
788
|
async function callMcp(s, server, tool, a, signal) {
|
|
715
789
|
if (!allowed(s, mcpName(server.name, tool))) return `error: the tool ${mcpName(server.name, tool)} is not allowed here`
|
|
716
|
-
|
|
790
|
+
let def = (server.tools ?? s.mcpCatalog?.get(server.name)?.tools)?.find((t) => t.name === tool)
|
|
791
|
+
if (!def) {
|
|
792
|
+
const tools = await server.listTools(signal).catch(() => null)
|
|
793
|
+
def = tools?.find((t) => t.name === tool)
|
|
794
|
+
if (tools && !def) {
|
|
795
|
+
const close = tools.filter((t) => t.name.includes(tool) || tool.includes(t.name)).map((t) => t.name)
|
|
796
|
+
return `error: ${server.name} has no tool "${tool}".${close.length ? ` Did you mean ${close.join(' or ')}?` : ''} Its tools: ${tools.map((t) => t.name).join(', ')}`
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
// arguments that don't fit: the schema comes back with what's wrong, and nothing is sent
|
|
800
|
+
const problems = def?.inputSchema ? argProblems(def.inputSchema, a) : []
|
|
801
|
+
if (problems.length) return `error: ${server.name} · ${tool} wasn't called — ${problems.join('; ')}.\n${describeTool(def)}\nCall it again with arguments that fit.`
|
|
717
802
|
// a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
|
|
718
803
|
// declines what it would ask, so a browser's snapshot must not be); any other like a command
|
|
719
804
|
if (!def?.annotations?.readOnlyHint) {
|
package/src/ui.js
CHANGED
|
@@ -9,7 +9,7 @@ import { log } from './log.js'
|
|
|
9
9
|
import { HOME } from './config.js'
|
|
10
10
|
import { listen, transcribePcm, voiceProblem } from './voice.js'
|
|
11
11
|
|
|
12
|
-
const color = (process.stdout.isTTY || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR
|
|
12
|
+
export const color = (process.stdout.isTTY || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR
|
|
13
13
|
// 24-bit where the terminal says so, else the nearest of 256 (Terminal.app, xterm-256color), else 16.
|
|
14
14
|
const depth = !color ? 0 : /truecolor|24bit/i.test(process.env.COLORTERM ?? '') ? 3 : /256/.test(process.env.TERM ?? '') || process.env.TERM_PROGRAM === 'Apple_Terminal' ? 2 : 1
|
|
15
15
|
const to256 = ([r, g, b]) => {
|
|
@@ -1457,6 +1457,7 @@ export class UI {
|
|
|
1457
1457
|
return Promise.resolve(l)
|
|
1458
1458
|
}
|
|
1459
1459
|
if (this.closed) return Promise.resolve(null)
|
|
1460
|
+
if (this.busySince && !history) this.onWaiting?.(prompt) // asked mid-task: you may be away (Telegram)
|
|
1460
1461
|
this.menu.on = Boolean(suggest && (this.suggest || this.menu.pick) && this.full)
|
|
1461
1462
|
this.histOn = history
|
|
1462
1463
|
this.histAt = -1
|
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
|
-
|
|
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()
|