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/src/settings.js CHANGED
@@ -19,6 +19,8 @@ import { THEMES, PERMISSIONS } from './ui.js'
19
19
  import { loadSkills, frontMatter } from './skills.js'
20
20
  import { installSkill, findImports } from './importer.js'
21
21
  import { capabilities } from './capabilities.js'
22
+ import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
23
+ import { searchSettings, testSearxng, ENGINE_NAMES } from './web.js'
22
24
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs } from './log.js'
23
25
 
24
26
  const PAGE = new URL('./settings.html', import.meta.url)
@@ -39,6 +41,7 @@ const STATUS_ITEMS = [
39
41
  { id: 'cost', label: 'Cost', sample: '$0.14' },
40
42
  { id: 'autocompact', label: 'Auto-compact off', sample: 'auto-compact off' },
41
43
  { id: 'worktree', label: 'Git worktree', sample: '⎇ feature' },
44
+ { id: 'background', label: 'Background commands', sample: '⚙ 2 running' },
42
45
  { id: 'permissions', label: 'Permissions', sample: '⏵⏵ all allowed' },
43
46
  ]
44
47
  const STATUS_IDS = new Set(STATUS_ITEMS.map((i) => i.id))
@@ -361,6 +364,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
361
364
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
362
365
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
363
366
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
367
+ // Telegram notifications: never the token itself, only a hint of it
368
+ telegram: (({ token, bot, chatName, chatId, on, events } = {}) => ({ hint: tokenHint(token), bot: bot ?? null, chatName: chatName ?? null, connected: Boolean(token && chatId), on: on !== false, events: Object.fromEntries(Object.keys(EVENTS).map((k) => [k, events?.[k] !== false])), names: EVENTS }))(cfg.telegram),
369
+ search: { ...(({ searxng, order, off }) => ({ searxng, order, off }))(searchSettings()), names: ENGINE_NAMES }, // web search: your SearXNG, the engines' order and switches
364
370
  capabilities: capabilities(cfg), // features that need outside tools, and whether they're here
365
371
  choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS },
366
372
  files: FILES.map(([name, about, json, example]) => ({ name, about, json, example, text: fs.existsSync(path.join(HOME, name)) ? fs.readFileSync(path.join(HOME, name), 'utf8') : '' })),
@@ -651,6 +657,73 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
651
657
  },
652
658
  // The status bar's layout from the visual editor: false (off), null (back to default), or a list
653
659
  // of lines ({ left:[item ids], right:[item ids] }). Unknown item ids are dropped; empty = off.
660
+ // Telegram: a bot token checked (or the saved one, to look again for the chat once you pressed
661
+ // Start in the bot); the newest chat that wrote to the bot is the one notifications go to, and
662
+ // it gets a first message saying so.
663
+ 'POST /api/telegram/connect': async ({ token }) => {
664
+ const tk = String(token ?? '').trim() || cfg.telegram?.token
665
+ if (!tk) throw new Error('paste the token @BotFather gave you')
666
+ if (!/^\d+:[\w-]{20,}$/.test(tk)) throw new Error("that doesn't look like a bot token (it's like 123456789:AAH…, from @BotFather)")
667
+ const r = await connect(tk)
668
+ const chat = r.chats[0]
669
+ const was = cfg.telegram?.token === tk ? cfg.telegram : {}
670
+ cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
671
+ save('setting:telegram')
672
+ if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. You'll get a message here when a task finishes, fails, or waits for you.")
673
+ return { ...state(), found: chat?.name ?? null }
674
+ },
675
+ 'POST /api/telegram/test': async () => {
676
+ if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
677
+ await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications reach you.')
678
+ return state()
679
+ },
680
+ 'POST /api/telegram/set': ({ on, event, value }) => {
681
+ if (!cfg.telegram) throw new Error('connect Telegram first')
682
+ if (typeof on === 'boolean') cfg.telegram.on = on
683
+ if (event !== undefined) {
684
+ if (!EVENTS[event] || typeof value !== 'boolean') throw new Error(`event: ${Object.keys(EVENTS).join(', ')}, on or off`)
685
+ cfg.telegram.events = { ...cfg.telegram.events, [event]: value }
686
+ }
687
+ save('setting:telegram')
688
+ return state()
689
+ },
690
+ 'POST /api/telegram/remove': () => {
691
+ cfg.telegram = undefined
692
+ save('setting:telegram')
693
+ return state()
694
+ },
695
+ // Web search: your own SearXNG's address ('' removes it), the engines' order, the ones switched off.
696
+ 'POST /api/search': ({ searxng, order, off }) => {
697
+ const now = searchSettings()
698
+ const next = { searxng: now.searxng || undefined, order: now.order, off: now.off }
699
+ if (searxng !== undefined) {
700
+ let u = String(searxng ?? '').trim()
701
+ if (u && !/^https?:\/\//i.test(u)) u = `https://${u}`
702
+ if (u) {
703
+ try {
704
+ if (!new URL(u).hostname) throw new Error()
705
+ } catch {
706
+ throw new Error(`"${searxng}" is not an address`)
707
+ }
708
+ }
709
+ next.searxng = u ? u.replace(/\/?$/, '/') : undefined
710
+ }
711
+ const names = Object.keys(ENGINE_NAMES)
712
+ if (Array.isArray(order)) next.order = [...order.filter((n) => names.includes(n)), ...names.filter((n) => !order.includes(n))]
713
+ if (Array.isArray(off)) next.off = off.filter((n) => names.includes(n))
714
+ cfg.search = next
715
+ save('setting:search')
716
+ return state()
717
+ },
718
+ 'POST /api/search/test': async ({ searxng }) => {
719
+ const u = String(searxng ?? '').trim() || searchSettings().searxng
720
+ if (!u) throw new Error('type your SearXNG address first')
721
+ const n = await testSearxng(/^https?:\/\//i.test(u) ? u : `https://${u}`).catch((e) => {
722
+ throw new Error(`${u} didn't answer a search: ${e.cause?.code || e.message}`)
723
+ })
724
+ if (!n) throw new Error(`${u} answered, with no results (is it a SearXNG? are its engines on?)`)
725
+ return { results: n }
726
+ },
654
727
  'POST /api/statusbar': ({ statusBar }) => {
655
728
  const clean = (a) => (Array.isArray(a) ? a.filter((x) => STATUS_IDS.has(x)) : [])
656
729
  if (statusBar === false) cfg.statusBar = false
@@ -0,0 +1,81 @@
1
+ // Telegram notifications: HeartCode messages you through your own bot when a task finishes, fails
2
+ // or waits for you (a question, a permission). Telegram's Bot API (https://core.telegram.org/bots/api):
3
+ // getMe checks the token, getUpdates finds your chat once you've pressed Start in the bot,
4
+ // sendMessage sends (plain text, 4096 characters at most). Set up on the settings page
5
+ // (cfg.telegram: { token, chatId, chatName, bot, on, events }). The token is never logged or shown whole.
6
+ import { log } from './log.js'
7
+ import { saveConfig } from './config.js'
8
+
9
+ const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the env: a stand-in server, for tests
10
+ export const EVENTS = {
11
+ done: 'A task finished',
12
+ failed: 'A task failed',
13
+ waiting: 'HeartCode is waiting for you (a question or a permission)',
14
+ }
15
+
16
+ async function call(token, method, body = {}, timeout = 15_000) {
17
+ let res
18
+ try {
19
+ res = await fetch(`${API}/bot${token}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeout) })
20
+ } catch (e) {
21
+ throw new Error(`can't reach Telegram (${e.cause?.code || e.name})`) // not e.message: the URL has the token in it
22
+ }
23
+ const j = await res.json().catch(() => ({ ok: false, description: `HTTP ${res.status}` }))
24
+ if (!j.ok) throw Object.assign(new Error(j.error_code === 401 || j.error_code === 404 ? 'Telegram refused the bot token (check it in @BotFather)' : j.description || `HTTP ${res.status}`), { code: j.error_code, retryAfter: j.parameters?.retry_after })
25
+ return j.result
26
+ }
27
+
28
+ // The token shown to people: its bot's number and the last 4 characters.
29
+ export const tokenHint = (token) => (token ? `${String(token).split(':')[0]}:…${String(token).slice(-4)}` : '')
30
+
31
+ // A token checked, and the chats that have written to the bot (newest first): { bot, chats: [{ id, name }] }.
32
+ // None yet: the user hasn't pressed Start in the bot (or wrote to it more than a day ago).
33
+ export async function connect(token) {
34
+ const me = await call(token, 'getMe')
35
+ const updates = await call(token, 'getUpdates', { limit: 100, allowed_updates: ['message'] }).catch((e) => {
36
+ if (e.code === 409) throw new Error('this bot is set up with a webhook, so its messages can\'t be read here: use a bot of its own for HeartCode')
37
+ throw e
38
+ })
39
+ const chats = new Map()
40
+ for (const u of [...updates].reverse()) {
41
+ const chat = u.message?.chat
42
+ if (!chat || chats.has(chat.id)) continue
43
+ chats.set(chat.id, { id: chat.id, name: chat.title || [chat.first_name, chat.last_name].filter(Boolean).join(' ') || (chat.username ? `@${chat.username}` : String(chat.id)) })
44
+ }
45
+ return { bot: me.username, chats: [...chats.values()] }
46
+ }
47
+
48
+ export const tgReady = (t) => Boolean(t?.token && t?.chatId && t.on !== false)
49
+
50
+ // One message; a rate limit is waited out once (Telegram says how long).
51
+ export async function sendTelegram(t, text, { silent = false } = {}) {
52
+ const body = { chat_id: t.chatId, text: String(text).slice(0, 4096), disable_notification: silent, link_preview_options: { is_disabled: true } }
53
+ try {
54
+ return await call(t.token, 'sendMessage', body)
55
+ } catch (e) {
56
+ if (!e.retryAfter) throw e
57
+ await new Promise((r) => setTimeout(r, Math.min(e.retryAfter, 60) * 1000))
58
+ return await call(t.token, 'sendMessage', body)
59
+ }
60
+ }
61
+
62
+ // An event, if Telegram is set up and that event is on. Never waits on it, never throws: a
63
+ // notification that can't be sent is logged, the work goes on.
64
+ // A token saved before Start was pressed in the bot has no chat yet: it's looked up then (and kept).
65
+ export function notify(cfg, event, text) {
66
+ const t = cfg?.telegram
67
+ if (!t?.token || t.on === false || t.events?.[event] === false) return
68
+ const chat = t.chatId ? Promise.resolve(t) : findChat(cfg)
69
+ chat.then((ready) => ready && sendTelegram(ready, text)).catch((e) => log('telegram', `${event}: couldn't send (${e.message})`))
70
+ }
71
+ async function findChat(cfg) {
72
+ const { chats } = await connect(cfg.telegram.token)
73
+ if (!chats.length) {
74
+ log('telegram', "no chat yet: press Start in the bot (Telegram), then HeartCode finds it")
75
+ return null
76
+ }
77
+ Object.assign(cfg.telegram, { chatId: chats[0].id, chatName: chats[0].name })
78
+ saveConfig(cfg)
79
+ log('telegram', `found the chat: ${chats[0].name}`)
80
+ return cfg.telegram
81
+ }
package/src/tools.js CHANGED
@@ -2,20 +2,22 @@ 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'
18
19
  import { diagnose, lspTool, findCommand } from './lsp.js'
20
+ import { startJob, newOutput, listJobs, getJob, stopJob, jobLine } from './background.js'
19
21
 
20
22
  const IGNORE = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.DS_Store'])
21
23
 
@@ -24,13 +26,16 @@ export const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s)
24
26
 
25
27
  // Tool output too long for the conversation is saved here (one folder per chat), where read_file
26
28
  // and search can read it although it's outside the project.
27
- export const OUTPUTS = path.join(os.tmpdir(), 'heartcode-outputs')
29
+ export const OUTPUTS = path.join(HOME, 'outputs') // kept with the chat: a resumed one's pointers still open
30
+ const LEGACY_OUTPUTS = path.join(os.tmpdir(), 'heartcode-outputs') // where older HeartCode kept them
31
+ export const isSavedOutput = (abs) => [OUTPUTS, LEGACY_OUTPUTS].some((d) => String(abs).startsWith(d + path.sep))
28
32
  // data: text, or an image's bytes (ext: png…)
33
+ let saved = 0
29
34
  export function saveOutput(chatId, name, data, ext = 'txt') {
30
35
  try {
31
36
  const dir = path.join(OUTPUTS, String(chatId ?? 'chat'))
32
37
  fs.mkdirSync(dir, { recursive: true })
33
- const file = path.join(dir, `${Date.now().toString(36)}-${String(name).replace(/[^\w-]/g, '_').slice(0, 60)}.${ext}`)
38
+ 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
39
  fs.writeFileSync(file, data)
35
40
  return file
36
41
  } catch (e) {
@@ -44,7 +49,7 @@ export function resolveIn(root, p) {
44
49
  if (!clean) throw new Error('no path given')
45
50
  const bare = root.replace(/^[\\/]+/, '') // the project's own path, its leading "/" left out by a sloppy copy
46
51
  let abs = clean === bare || clean.startsWith(bare + '/') ? path.join(root, clean.slice(bare.length)) : path.resolve(root, clean)
47
- if (abs.startsWith(OUTPUTS + path.sep)) return abs // a saved tool output
52
+ if (isSavedOutput(abs)) return abs // a saved tool output
48
53
  // "num.js:" or "num.js," from a sloppy model: the file without the stray mark, if that one exists
49
54
  const trimmed = path.resolve(root, clean.replace(/[:;,.]+$/, ''))
50
55
  if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
@@ -204,7 +209,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
204
209
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
205
210
  }
206
211
  const abs = sub ? resolveIn(root, sub) : ''
207
- const saved = abs.startsWith(OUTPUTS + path.sep) // a tool output saved outside the project
212
+ let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
213
+ try {
214
+ single = Boolean(abs) && fs.statSync(abs).isFile()
215
+ } catch {}
216
+ const saved = isSavedOutput(abs) || single
208
217
  const prefix = sub && !saved ? path.relative(root, abs) : ''
209
218
  const hits = []
210
219
  for (const f of saved ? [abs] : listFiles(root)) {
@@ -263,7 +272,7 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
263
272
  clearTimeout(timer)
264
273
  signal?.removeEventListener('abort', stop)
265
274
  if (kill(0) && code !== 'interrupted' && code !== 'timeout') {
266
- note += '\n(Processes this command left running in the background were stopped: run_command cannot keep a server running.)'
275
+ note += '\n(Processes this command left running in the background were stopped. To keep a server or watcher running, run it with background: true.)'
267
276
  }
268
277
  kill('SIGTERM')
269
278
  setTimeout(() => kill('SIGKILL'), 2000).unref()
@@ -388,8 +397,8 @@ export function searchesOutside(cmd, root) {
388
397
  })
389
398
  }
390
399
 
391
- export async function runConfirmed(s, cmd, signal) {
392
- s.ui.step('run', cmd)
400
+ export async function runConfirmed(s, cmd, signal, background = false) {
401
+ s.ui.step(background ? 'run in background' : 'run', cmd)
393
402
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
394
403
  s.ui.result('not run: plan mode')
395
404
  return prompt('agent/plan-refused-command')
@@ -401,6 +410,11 @@ export async function runConfirmed(s, cmd, signal) {
401
410
  }
402
411
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
403
412
  if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
413
+ if (background) {
414
+ const { job, output } = await startJob(s.root, cmd)
415
+ s.ui.result(job.exited ? `exited with ${job.code}` : `running in the background as #${job.id}`)
416
+ return prompt('agent/background-started', { id: job.id, running: !job.exited, code: job.code, output: output.trim() || '(nothing yet)', file: job.file })
417
+ }
404
418
  const before = snapshot(s)
405
419
  s.ui.spinner(`running ${cmd}`)
406
420
  const t0 = Date.now()
@@ -413,6 +427,22 @@ export async function runConfirmed(s, cmd, signal) {
413
427
  return `exit code ${code}\n${tail(output, 4000) || '(no output)'}${changed ? `\nFiles this command changed: ${changed}` : ''}${why}`
414
428
  }
415
429
 
430
+ // The background tool: what a command started with background: true printed since the last look,
431
+ // the list of them, or stop one.
432
+ function backgroundTool(s, a) {
433
+ const mine = listJobs(s.root)
434
+ if (a.action === 'list') return mine.length ? mine.map(jobLine).join('\n') : 'No background commands.'
435
+ const job = getJob(a.id ?? mine.at(-1)?.id)
436
+ if (!job || job.root !== s.root) return `error: no background command #${a.id}. ${mine.length ? `They are: ${mine.map((j) => `#${j.id} ${j.command}`).join(', ')}` : 'None are running.'}`
437
+ if (a.action === 'stop') {
438
+ const was = stopJob(job)
439
+ s.ui.result(was ? `stopped #${job.id}` : `#${job.id} had already exited`)
440
+ return was ? `Stopped #${job.id} (${job.command}).` : `#${job.id} had already exited with ${job.code}.`
441
+ }
442
+ const out = newOutput(job)
443
+ return `${jobLine(job)}\n${out.trim() ? `New output since the last look:\n${out}` : '(no new output since the last look)'}`
444
+ }
445
+
416
446
  // Files a shell command changes are tracked like HeartCode's own edits: shown as diffs, kept for
417
447
  // /rewind, and told to the model. Text files up to 256 KB, read only when they changed since the
418
448
  // last look (the contents are cached per session).
@@ -449,6 +479,7 @@ function changesSince(s, before) {
449
479
  const notes = []
450
480
  for (const rel of new Set([...before.keys(), ...after.keys()])) {
451
481
  if (before.get(rel) === after.get(rel)) continue
482
+ 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
483
  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
484
  const old = was.get(rel)
454
485
  const next = after.has(rel) ? s.fileCache.get(rel)?.text : undefined
@@ -488,10 +519,11 @@ export const TOOL_DEFS = [
488
519
  // One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
489
520
  { name: 'edit_file', description: prompt('agent/tool-edit_file'), parameters: obj({ path: str, search: str, replace: str, start_line: int, end_line: int }, ['path', 'replace']) },
490
521
  { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
491
- { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str }, ['command']) },
522
+ { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str, background: { type: 'boolean' } }, ['command']) },
523
+ { name: 'background', description: prompt('agent/tool-background'), parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int }, ['action']) },
492
524
  { 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']) },
525
+ { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
526
+ { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
495
527
  { name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' } }, ['question']) },
496
528
  ]
497
529
 
@@ -513,21 +545,20 @@ export function readOnlyCommand(cmd) {
513
545
  return c.split(/\s*(?:&&|\|\||;|\|)\s*/).every((part) => READ_ONLY.test(part))
514
546
  }
515
547
 
516
- // MCP servers' tools as the model sees them: each its own tool, mcp__server__tool (Claude Code's
517
- // names), with its description and arguments, the way the model would see them in Claude Code.
518
- // Servers whose tools aren't known yet (still starting, failed), or too many tools at once, go
519
- // through the one mcp tool instead. Sets s.mcpDirect (name → { server, tool, def }), s.mcpMeta
520
- // (servers behind the mcp tool) and s.mcpInstructions (what the servers say about using them).
521
- export const MAX_MCP_TOOLS = 100
548
+ // MCP servers' tools as the model sees them: one tool, mcp, whose description lists every server's
549
+ // tools by name with one line on what each does — not each tool's whole schema in every request
550
+ // (two browser servers' schemas alone were ~14k tokens a request). A tool's arguments come when
551
+ // they're needed: "describe" shows them, and a call whose arguments don't fit its schema gets the
552
+ // schema back with what's wrong (nothing is sent to the server). Sets s.mcpDirect
553
+ // (mcp__server__tool → { server, tool, def }: only to understand a call by that name — an older
554
+ // conversation's, or a model used to Claude Code's names), s.mcpCatalog and s.mcpInstructions (what
555
+ // the servers say about using them).
522
556
  export async function loadMcpTools(s, signal) {
523
- if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(), mcpMeta: [], mcpInstructions: '' })
557
+ if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(), mcpInstructions: '' })
524
558
  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
559
  const direct = new Map()
528
560
  const notes = []
529
- for (const [server, { tools, instructions }] of known) {
530
- if (direct.size + tools.length > MAX_MCP_TOOLS) continue
561
+ for (const [server, { tools, instructions }] of catalog) {
531
562
  for (const t of tools) {
532
563
  let n = mcpName(server, t.name)
533
564
  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 +566,26 @@ export async function loadMcpTools(s, signal) {
535
566
  }
536
567
  if (instructions) notes.push(`### ${server}\n${instructions}`)
537
568
  }
538
- const shown = new Set([...direct.values()].map((d) => d.server))
539
- return Object.assign(s, { mcpDirect: direct, mcpMeta: s.mcp.names.filter((n) => !shown.has(n)), mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
569
+ return Object.assign(s, { mcpDirect: direct, mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
540
570
  }
541
571
  // Tool names may only have letters, digits, _ and - (64 at most).
542
572
  export const mcpName = (server, tool) => `mcp__${server}__${tool}`.replace(/[^\w-]/g, '_').slice(0, 64)
543
- // A schema as providers take it: an object, without the keys some refuse ($schema).
544
- function cleanSchema(x) {
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
- }
573
+ // A tool's description cut to its first sentence (what it does), for the list.
574
+ const firstLine = (d) => String(d ?? '').trim().split(/\n|(?<=\.)\s/)[0].slice(0, 140)
555
575
 
556
- // The MCP servers' tools, the one tool for the rest, and the skill loader; each only when there's
557
- // something to offer.
576
+ // The MCP servers (one tool for all of their tools), the memory and the skill loader; each only when
577
+ // there's something to offer.
558
578
  export function extraTools(s) {
559
- const out = mcpDefs(s)
560
- const meta = s.mcpMeta ?? s.mcp?.names ?? []
561
- if (meta.length) {
562
- // no description: the names of its tools, when known, say what it's for
563
- const about = (n) => s.mcp.get(n).cfg.description || (s.mcpCatalog?.get(n) ? `tools: ${clip(s.mcpCatalog.get(n).tools.map((t) => t.name).join(', '), 300)}` : 'no description')
564
- out.push({ name: 'mcp', description: prompt('agent/tool-mcp', { servers: meta.map((n) => `${n}: ${about(n)}`).join('\n') }), parameters: obj({ server: str, tool: str, arguments: { type: 'object' } }, ['server', 'tool']) })
579
+ const out = []
580
+ const servers = s.mcp?.names ?? []
581
+ if (servers.length) {
582
+ const list = (n) => {
583
+ const cfg = s.mcp.get(n)?.cfg ?? {}
584
+ const tools = s.mcpCatalog?.get(n)?.tools
585
+ const head = `${n}${cfg.description ? ` — ${cfg.description}` : ''}`
586
+ 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)`
587
+ }
588
+ 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
589
  }
566
590
  if (s.memory) {
567
591
  out.push({
@@ -640,9 +664,40 @@ async function webTool(s, name, args, signal) {
640
664
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
641
665
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
642
666
  if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
643
- s.ui.spinner(name === 'web_search' ? `searching: ${clip(what, 60)}` : `fetching ${clip(what, 60)}`)
644
- return name === 'web_search' ? await webSearch(what, { signal }) : await webFetch(what, { start: args.start, signal })
667
+ // what this message's research is for: the page's look_for, else the last search, else the task
668
+ const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
669
+ if (name === 'web_search') {
670
+ s.lastQuery = what
671
+ // already read for this project: offered first (the model decides: use it, or search fresh)
672
+ const saved = !args.fresh && s.root && !s.noResearch ? findResearch(s.root, what, 5).filter((r) => r.kind !== 'search') : []
673
+ if (saved.length) {
674
+ log('research', `"${what}": ${saved.length} saved page(s) offered first`)
675
+ 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') })
676
+ }
677
+ s.ui.spinner(`searching: ${clip(what, 60)}`)
678
+ const out = await webSearch(what, { signal })
679
+ if (s.root && !s.noResearch && !/^(error:|no results)/.test(out)) {
680
+ const { file } = saveSearch(s.root, what, out)
681
+ s.research?.push({ kind: 'search', file, title: `Search: ${what}` })
682
+ }
683
+ return out
684
+ }
685
+ s.ui.spinner(`fetching ${clip(what, 60)}`)
686
+ if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal }) // nothing kept (--no-memory)
687
+ const page = await fetchPage(what, { signal })
688
+ if (page.error) return `error: ${page.error}`
689
+ const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
690
+ if (!page.ok || !page.text.trim()) return `${head}${page.text.slice(0, MAX_PAGE) || '(empty page)'}` // an error page isn't worth keeping
691
+ const { file, bodyLine } = savePage(s.root, { url: page.url, title: page.title, text: page.text, query: purpose })
692
+ s.research?.push({ kind: 'page', file, url: page.url, title: page.title || page.url })
693
+ const id = runningCall.getStore()
694
+ if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
695
+ log('research', `saved ${page.url} → ${file}`)
696
+ // "start": the part from there on, as before (an older conversation's way of reading on)
697
+ 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}.)`
698
+ return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
645
699
  }
700
+ const MAX_PAGE = 10_000
646
701
 
647
702
  function memoryTool(s, args) {
648
703
  const m = s.memory
@@ -653,8 +708,16 @@ function memoryTool(s, args) {
653
708
  if (!args.content && !args.description) return 'error: write needs at least content or a description'
654
709
  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
710
  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.'
711
+ const isNew = !m.read(args.name || args.description)
656
712
  const n = m.write(args)
657
- return `Saved [[${n}]]${m.read(n)?.scope === 'global' ? ' (global)' : ''}.`
713
+ // a new note that says much the same as one there already: said, so they're merged, not piled up
714
+ const words = new Set(keywords(`${n} ${args.description ?? ''}`))
715
+ const overlap = (x) => {
716
+ const theirs = new Set(keywords(`${x.name} ${x.description}`))
717
+ return [...theirs].filter((w) => words.has(w)).length / Math.max(1, Math.min(theirs.size, words.size))
718
+ }
719
+ const similar = isNew && words.size >= 3 ? m.list().filter((x) => x.name !== n && overlap(x) >= 0.6).slice(0, 3) : []
720
+ 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
721
  }
659
722
  case 'read': {
660
723
  if (!name.trim()) return 'error: read needs the note\'s "name" (search finds notes by words).'
@@ -704,16 +767,61 @@ async function mcpTool(s, args, signal) {
704
767
  s.ui.spinner(`starting ${server.name}`)
705
768
  const tools = await server.listTools(signal)
706
769
  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 ? `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}` : `error: ${server.name} has no tool "${a.name}"; tool "list" shows its tools`
770
+ const t = tools.find((x) => x.name === (a.name ?? a.tool))
771
+ return t ? describeTool(t) : `error: ${server.name} has no tool "${a.name ?? a.tool}"; tool "list" shows its tools`
709
772
  }
710
773
  return callMcp(s, server, tool, a, signal)
711
774
  }
712
775
 
776
+ // What's wrong with a call's arguments for a tool's JSON schema (the common part of it: required,
777
+ // unknown names, types, enums), or [] when they fit. Unknown names get the closest real one.
778
+ export function argProblems(schema, a) {
779
+ const props = schema?.properties ?? {}
780
+ const out = []
781
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return ['"arguments" must be an object']
782
+ for (const k of schema?.required ?? []) if (a[k] === undefined) out.push(`"${k}" is required`)
783
+ const near = (k) => {
784
+ const d = (x, y) => {
785
+ const m = Array.from({ length: x.length + 1 }, (_, i) => [i, ...Array(y.length).fill(0)])
786
+ for (let j = 1; j <= y.length; j++) m[0][j] = j
787
+ 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))
788
+ return m[x.length][y.length]
789
+ }
790
+ const best = Object.keys(props).map((p) => [p, d(k.toLowerCase(), p.toLowerCase())]).sort((x, y) => x[1] - y[1])[0]
791
+ return best && best[1] <= Math.max(2, Math.floor(best[0].length / 3)) ? ` (did you mean "${best[0]}"?)` : ''
792
+ }
793
+ 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
794
+ for (const [k, v] of Object.entries(a)) {
795
+ const p = props[k]
796
+ if (!p) {
797
+ if (schema?.properties && schema.additionalProperties !== true) out.push(`"${k}" is not one of its arguments${near(k)}`)
798
+ continue
799
+ }
800
+ const types = [p.type ?? []].flat()
801
+ 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}`)
802
+ if (p.enum && !p.enum.includes(v)) out.push(`"${k}" must be one of ${p.enum.map((x) => JSON.stringify(x)).join(', ')}`)
803
+ }
804
+ return out
805
+ }
806
+
807
+ // One tool's description and arguments, for the model (describe, or a call that didn't fit).
808
+ const describeTool = (t) => `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}`
809
+
713
810
  // One MCP tool call. Asked about like a command, unless the server marks the tool read-only.
714
811
  async function callMcp(s, server, tool, a, signal) {
715
812
  if (!allowed(s, mcpName(server.name, tool))) return `error: the tool ${mcpName(server.name, tool)} is not allowed here`
716
- const def = (server.tools ?? s.mcpCatalog?.get(server.name)?.tools)?.find((t) => t.name === tool)
813
+ let def = (server.tools ?? s.mcpCatalog?.get(server.name)?.tools)?.find((t) => t.name === tool)
814
+ if (!def) {
815
+ const tools = await server.listTools(signal).catch(() => null)
816
+ def = tools?.find((t) => t.name === tool)
817
+ if (tools && !def) {
818
+ const close = tools.filter((t) => t.name.includes(tool) || tool.includes(t.name)).map((t) => t.name)
819
+ return `error: ${server.name} has no tool "${tool}".${close.length ? ` Did you mean ${close.join(' or ')}?` : ''} Its tools: ${tools.map((t) => t.name).join(', ')}`
820
+ }
821
+ }
822
+ // arguments that don't fit: the schema comes back with what's wrong, and nothing is sent
823
+ const problems = def?.inputSchema ? argProblems(def.inputSchema, a) : []
824
+ if (problems.length) return `error: ${server.name} · ${tool} wasn't called — ${problems.join('; ')}.\n${describeTool(def)}\nCall it again with arguments that fit.`
717
825
  // a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
718
826
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
719
827
  if (!def?.annotations?.readOnlyHint) {
@@ -1074,7 +1182,9 @@ async function tool(name, args, s, signal, id) {
1074
1182
  }
1075
1183
  case 'run_command':
1076
1184
  if (/^\s*apply_patch\b[\s\S]*\*\*\* Begin Patch/.test(String(args.command ?? ''))) return await applyPatch(s, args.command) // apply_patch <<'EOF' … as Codex runs it
1077
- return (await runConfirmed(s, String(args.command ?? ''), signal)) + outsideNote(root, String(args.command ?? ''))
1185
+ return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true')) + outsideNote(root, String(args.command ?? ''))
1186
+ case 'background':
1187
+ return backgroundTool(s, args)
1078
1188
  case 'apply_patch':
1079
1189
  return await applyPatch(s, args.input ?? args.patch ?? args.command ?? '')
1080
1190
  case 'mcp':