heartcode 0.1.37 → 0.1.41
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/.claude/scheduled_tasks.lock +1 -0
- package/CHANGELOG.md +99 -0
- package/README.md +27 -12
- package/SKILL.md +22 -7
- package/bin/heart.js +8 -21
- package/bin/heartcode.js +90 -62
- package/package.json +1 -1
- package/prompts/README.md +0 -1
- package/prompts/agent.md +114 -120
- package/src/agent.js +71 -261
- package/src/background.js +39 -12
- package/src/capabilities.js +2 -2
- package/src/client.js +41 -6
- package/src/config.js +1 -1
- package/src/fit.js +65 -0
- package/src/guided.js +12 -21
- package/src/importer.js +50 -12
- package/src/log.js +69 -18
- package/src/parquet.js +209 -0
- package/src/probe.js +20 -310
- package/src/prompts.js +1 -1
- package/src/rankings.js +122 -0
- package/src/settings.html +230 -115
- package/src/settings.js +59 -22
- package/src/skills.js +7 -3
- package/src/tools.js +189 -50
- package/src/ui.js +55 -10
- package/src/update.js +59 -0
- package/prompts/probe.md +0 -67
package/src/tools.js
CHANGED
|
@@ -17,7 +17,7 @@ import { runHooks } from './hooks.js'
|
|
|
17
17
|
import { parsePatch, applyChunks } from './patch.js'
|
|
18
18
|
import { formatFile } from './format.js'
|
|
19
19
|
import { diagnose, lspTool, findCommand } from './lsp.js'
|
|
20
|
-
import { startJob, newOutput, listJobs, getJob, stopJob, jobLine } from './background.js'
|
|
20
|
+
import { startJob, waitFor, newOutput, listJobs, getJob, stopJob, removeJob, keepLeftovers, jobLine } from './background.js'
|
|
21
21
|
|
|
22
22
|
const IGNORE = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.DS_Store'])
|
|
23
23
|
|
|
@@ -44,12 +44,27 @@ export function saveOutput(chatId, name, data, ext = 'txt') {
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
// Folders (and files) outside the project that the user's messages name ("look at ~/code/other
|
|
48
|
+
// first"): read_file, list_files and search read there, and commands there aren't called a wrong
|
|
49
|
+
// turn. Nothing outside the project is written.
|
|
50
|
+
const namedOutside = new Set()
|
|
51
|
+
const expandHome = (p) => p.replace(/^~(?=[\\/]|$)/, os.homedir())
|
|
52
|
+
export function noteNamedPaths(text) {
|
|
53
|
+
for (const m of String(text ?? '').matchAll(/(?:^|[\s"'`(<])((?:~|\/|[A-Za-z]:[\\/])[^\s"'`)>]+)/g)) {
|
|
54
|
+
const abs = path.resolve(expandHome(m[1].replace(/[.,;:!?]+$/, '')))
|
|
55
|
+
if (abs !== path.parse(abs).root && abs !== os.homedir() && fs.existsSync(abs)) namedOutside.add(abs)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const readableOutside = (abs) => [...namedOutside].some((d) => abs === d || abs.startsWith(d + path.sep))
|
|
59
|
+
|
|
60
|
+
// read: a path the user named outside the project is fine too (for reading only)
|
|
61
|
+
export function resolveIn(root, p, read = false) {
|
|
62
|
+
const clean = expandHome(String(p ?? '').trim().replace(/^["'`]+|["'`]+$/g, ''))
|
|
49
63
|
if (!clean) throw new Error('no path given')
|
|
50
64
|
const bare = root.replace(/^[\\/]+/, '') // the project's own path, its leading "/" left out by a sloppy copy
|
|
51
65
|
let abs = clean === bare || clean.startsWith(bare + '/') ? path.join(root, clean.slice(bare.length)) : path.resolve(root, clean)
|
|
52
66
|
if (isSavedOutput(abs)) return abs // a saved tool output
|
|
67
|
+
if (read && readableOutside(abs) && !(abs === root || abs.startsWith(root + path.sep))) return abs
|
|
53
68
|
// "num.js:" or "num.js," from a sloppy model: the file without the stray mark, if that one exists
|
|
54
69
|
const trimmed = path.resolve(root, clean.replace(/[:;,.]+$/, ''))
|
|
55
70
|
if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
|
|
@@ -120,7 +135,7 @@ export function listFiles(root, limit = 2000) {
|
|
|
120
135
|
// One folder's entries (the project root: ''), all of them: folders end in "/", what .gitignore
|
|
121
136
|
// leaves out says "(ignored)". Names only. At most `limit`.
|
|
122
137
|
export function folderView(root, rel = '', limit = 200) {
|
|
123
|
-
const abs = resolveIn(root, rel || '.')
|
|
138
|
+
const abs = resolveIn(root, rel || '.', true)
|
|
124
139
|
let entries
|
|
125
140
|
try {
|
|
126
141
|
entries = fs.readdirSync(abs, { withFileTypes: true })
|
|
@@ -148,7 +163,7 @@ const isBinary = (buf) => buf.subarray(0, 8000).includes(0)
|
|
|
148
163
|
export const numberLines = (lines, from = 1) => lines.map((l, i) => `${from + i}| ${l}`).join('\n')
|
|
149
164
|
|
|
150
165
|
export function readFileTool(root, p, start, end, maxLines = 400) {
|
|
151
|
-
const abs = resolveIn(root, p)
|
|
166
|
+
const abs = resolveIn(root, p, true)
|
|
152
167
|
const rel = path.relative(root, abs)
|
|
153
168
|
if (!fs.existsSync(abs)) {
|
|
154
169
|
const base = path.basename(abs)
|
|
@@ -186,7 +201,7 @@ export function imageUrl(abs, shown = abs) {
|
|
|
186
201
|
// are); for one that can't, where to send it.
|
|
187
202
|
const IMAGE = /\.(png|jpe?g|gif|webp)$/i
|
|
188
203
|
function readImage(s, p) {
|
|
189
|
-
const abs = resolveIn(s.root, p)
|
|
204
|
+
const abs = resolveIn(s.root, p, true)
|
|
190
205
|
const rel = path.relative(s.root, abs) || p
|
|
191
206
|
if (!fs.existsSync(abs)) return readFileTool(s.root, p)
|
|
192
207
|
if (s.strat?.vision) {
|
|
@@ -208,15 +223,16 @@ export function searchFiles(root, query, sub = '', limit = 50) {
|
|
|
208
223
|
} catch {
|
|
209
224
|
re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
|
|
210
225
|
}
|
|
211
|
-
const abs = sub ? resolveIn(root, sub) : ''
|
|
226
|
+
const abs = sub ? resolveIn(root, sub, true) : ''
|
|
227
|
+
const away = abs && abs !== root && !abs.startsWith(root + path.sep) && !isSavedOutput(abs) // a folder the user named outside the project
|
|
212
228
|
let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
|
|
213
229
|
try {
|
|
214
230
|
single = Boolean(abs) && fs.statSync(abs).isFile()
|
|
215
231
|
} catch {}
|
|
216
232
|
const saved = isSavedOutput(abs) || single
|
|
217
|
-
const prefix = sub && !saved ? path.relative(root, abs) : ''
|
|
233
|
+
const prefix = sub && !saved && !away ? path.relative(root, abs) : ''
|
|
218
234
|
const hits = []
|
|
219
|
-
for (const f of saved ? [abs] : listFiles(root)) {
|
|
235
|
+
for (const f of saved ? [abs] : away ? listFiles(abs).map((f) => path.join(abs, f)) : listFiles(root)) {
|
|
220
236
|
if (prefix && f !== prefix && !f.startsWith(prefix + '/')) continue
|
|
221
237
|
let buf
|
|
222
238
|
try {
|
|
@@ -334,7 +350,6 @@ export async function proposeWrite(s, rel, old, next) {
|
|
|
334
350
|
else {
|
|
335
351
|
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
336
352
|
fs.writeFileSync(abs, next)
|
|
337
|
-
if (/\.(html?|css)$/i.test(rel)) (s.uiTouched ??= new Set()).add(rel) // looked at in a browser when the model says it's done (agent.js)
|
|
338
353
|
}
|
|
339
354
|
const add = ops.filter(([t]) => t === '+').length
|
|
340
355
|
const del = ops.filter(([t]) => t === '-').length
|
|
@@ -397,7 +412,9 @@ export function searchesOutside(cmd, root) {
|
|
|
397
412
|
})
|
|
398
413
|
}
|
|
399
414
|
|
|
400
|
-
|
|
415
|
+
// Waited on for `wait` seconds (the model's choice): finished by then, its exit code and output;
|
|
416
|
+
// still running, it carries on in the background, and the model checks on it when it likes.
|
|
417
|
+
export async function runConfirmed(s, cmd, signal, background = false, wait) {
|
|
401
418
|
s.ui.step(background ? 'run in background' : 'run', cmd)
|
|
402
419
|
if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
|
|
403
420
|
s.ui.result('not run: plan mode')
|
|
@@ -410,26 +427,33 @@ export async function runConfirmed(s, cmd, signal, background = false) {
|
|
|
410
427
|
}
|
|
411
428
|
const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
|
|
412
429
|
if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
|
|
413
|
-
|
|
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
|
-
}
|
|
430
|
+
const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
|
|
418
431
|
const before = snapshot(s)
|
|
419
432
|
s.ui.spinner(`running ${cmd}`)
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
log('command', `${cmd} → exit ${code} in ${Date.now() - t0}ms\n${tail(output, 8000)}`)
|
|
433
|
+
const job = startJob(s.root, cmd)
|
|
434
|
+
await waitFor(job, secs * 1000, signal)
|
|
423
435
|
s.ui.stopSpin()
|
|
424
|
-
|
|
436
|
+
if (!job.exited) {
|
|
437
|
+
if (signal?.aborted && !background) {
|
|
438
|
+
removeJob(job) // Esc stops what it was waiting on
|
|
439
|
+
s.ui.result('stopped')
|
|
440
|
+
return `Stopped by the user (Esc) after ${Math.round((Date.now() - job.started) / 1000)}s.`
|
|
441
|
+
}
|
|
442
|
+
s.ui.result(`still running: #${job.id} in the background`)
|
|
443
|
+
return prompt('agent/background-started', { id: job.id, secs, output: newOutput(job).trim() || '(nothing yet)', file: job.file })
|
|
444
|
+
}
|
|
445
|
+
const output = newOutput(job, 4000)
|
|
446
|
+
const left = keepLeftovers(job) // `server &`: kept running, as a background command
|
|
447
|
+
if (!left) removeJob(job) // done: not one of the background list
|
|
448
|
+
log('command', `${cmd} → exit ${job.code} in ${job.ended - job.started}ms\n${output}`)
|
|
449
|
+
s.ui.result(`exit ${job.code}`)
|
|
425
450
|
const changed = changesSince(s, before)
|
|
426
|
-
|
|
427
|
-
return `exit code ${code}\n${tail(output, 4000) || '(no output)'}${changed ? `\nFiles this command changed: ${changed}` : ''}${why}`
|
|
451
|
+
return `exit code ${left ? 0 : job.code}\n${output.trim() || '(no output)'}${changed ? `\nFiles this command changed: ${changed}` : ''}${left ? `\n${prompt('agent/left-running', { id: job.id })}` : ''}`
|
|
428
452
|
}
|
|
429
453
|
|
|
430
|
-
// The background tool: what a command
|
|
431
|
-
// the list of them, or stop one.
|
|
432
|
-
function backgroundTool(s, a) {
|
|
454
|
+
// The background tool: what a command still running printed since the last look (after waiting
|
|
455
|
+
// up to `wait` seconds for it to finish, if asked), the list of them, or stop one.
|
|
456
|
+
async function backgroundTool(s, a, signal) {
|
|
433
457
|
const mine = listJobs(s.root)
|
|
434
458
|
if (a.action === 'list') return mine.length ? mine.map(jobLine).join('\n') : 'No background commands.'
|
|
435
459
|
const job = getJob(a.id ?? mine.at(-1)?.id)
|
|
@@ -439,6 +463,12 @@ function backgroundTool(s, a) {
|
|
|
439
463
|
s.ui.result(was ? `stopped #${job.id}` : `#${job.id} had already exited`)
|
|
440
464
|
return was ? `Stopped #${job.id} (${job.command}).` : `#${job.id} had already exited with ${job.code}.`
|
|
441
465
|
}
|
|
466
|
+
if (Number(a.wait) > 0) {
|
|
467
|
+
s.ui.spinner(`waiting on #${job.id} ${clip(job.command, 60)}`)
|
|
468
|
+
await waitFor(job, Number(a.wait) * 1000, signal)
|
|
469
|
+
s.ui.stopSpin()
|
|
470
|
+
}
|
|
471
|
+
if (job.exited) job.told = true // told here: not again as a background-ended note
|
|
442
472
|
const out = newOutput(job)
|
|
443
473
|
return `${jobLine(job)}\n${out.trim() ? `New output since the last look:\n${out}` : '(no new output since the last look)'}`
|
|
444
474
|
}
|
|
@@ -519,12 +549,12 @@ export const TOOL_DEFS = [
|
|
|
519
549
|
// One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
|
|
520
550
|
{ 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']) },
|
|
521
551
|
{ name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
|
|
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']) },
|
|
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']) },
|
|
552
|
+
{ name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
|
|
553
|
+
{ name: 'background', description: prompt('agent/tool-background'), parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
|
|
554
|
+
{ name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
|
|
525
555
|
{ name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
|
|
526
556
|
{ name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
|
|
527
|
-
{ name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' } }, ['question']) },
|
|
557
|
+
{ name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question']) },
|
|
528
558
|
]
|
|
529
559
|
|
|
530
560
|
// Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
|
|
@@ -535,7 +565,7 @@ const READ_ONLY = /^(cd|ls|cat|head|tail|wc|grep|egrep|rg|find|fd|tree|pwd|file|
|
|
|
535
565
|
// path wrong, then lost in what it finds there): told where the project is.
|
|
536
566
|
function outsideNote(root, cmd) {
|
|
537
567
|
const dirs = [...cmd.matchAll(/(?:^|&&|;|\|\|)\s*cd\s+("[^"]+"|'[^']+'|\S+)/g)].map((m) => m[1].replace(/^["']|["']$/g, '').replace(/^~(?=\/|$)/, os.homedir()))
|
|
538
|
-
const out = dirs.map((d) => path.resolve(root, d)).find((d) => d !== root && !d.startsWith(root + path.sep))
|
|
568
|
+
const out = dirs.map((d) => path.resolve(root, d)).find((d) => d !== root && !d.startsWith(root + path.sep) && !readableOutside(d))
|
|
539
569
|
return out ? `\n\n${prompt('agent/outside-project', { dir: out, root })}` : ''
|
|
540
570
|
}
|
|
541
571
|
|
|
@@ -551,27 +581,23 @@ export function readOnlyCommand(cmd) {
|
|
|
551
581
|
// they're needed: "describe" shows them, and a call whose arguments don't fit its schema gets the
|
|
552
582
|
// schema back with what's wrong (nothing is sent to the server). Sets s.mcpDirect
|
|
553
583
|
// (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)
|
|
555
|
-
//
|
|
584
|
+
// conversation's, or a model used to Claude Code's names) and s.mcpCatalog (with what each server
|
|
585
|
+
// says about using it: given with its first result, howTo).
|
|
556
586
|
export async function loadMcpTools(s, signal) {
|
|
557
|
-
if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map()
|
|
587
|
+
if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map() })
|
|
558
588
|
const catalog = await s.mcp.catalog(signal)
|
|
559
589
|
const direct = new Map()
|
|
560
|
-
const
|
|
561
|
-
for (const [server, { tools, instructions }] of catalog) {
|
|
590
|
+
for (const [server, { tools }] of catalog) {
|
|
562
591
|
for (const t of tools) {
|
|
563
592
|
let n = mcpName(server, t.name)
|
|
564
593
|
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
|
|
565
594
|
direct.set(n, { server, tool: t.name, def: t })
|
|
566
595
|
}
|
|
567
|
-
if (instructions) notes.push(`### ${server}\n${instructions}`)
|
|
568
596
|
}
|
|
569
|
-
return Object.assign(s, { mcpDirect: direct,
|
|
597
|
+
return Object.assign(s, { mcpDirect: direct, mcpCatalog: catalog })
|
|
570
598
|
}
|
|
571
599
|
// Tool names may only have letters, digits, _ and - (64 at most).
|
|
572
600
|
export const mcpName = (server, tool) => `mcp__${server}__${tool}`.replace(/[^\w-]/g, '_').slice(0, 64)
|
|
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)
|
|
575
601
|
|
|
576
602
|
// The MCP servers (one tool for all of their tools), the memory and the skill loader; each only when
|
|
577
603
|
// there's something to offer.
|
|
@@ -583,7 +609,7 @@ export function extraTools(s) {
|
|
|
583
609
|
const cfg = s.mcp.get(n)?.cfg ?? {}
|
|
584
610
|
const tools = s.mcpCatalog?.get(n)?.tools
|
|
585
611
|
const head = `${n}${cfg.description ? ` — ${cfg.description}` : ''}`
|
|
586
|
-
return tools ? `${head}
|
|
612
|
+
return tools ? `${head}: ${tools.map((t) => t.name).join(', ')}` : `${head} (its tools aren't known yet: tool "list" shows them)`
|
|
587
613
|
}
|
|
588
614
|
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']) })
|
|
589
615
|
}
|
|
@@ -594,7 +620,7 @@ export function extraTools(s) {
|
|
|
594
620
|
parameters: obj({ action: { type: 'string', enum: ['write', 'read', 'search', 'delete'] }, name: str, description: str, type: str, tags: str, scope: { type: 'string', enum: ['project', 'global'] }, content: str, query: str }, ['action']),
|
|
595
621
|
})
|
|
596
622
|
}
|
|
597
|
-
const forModel = [...(s.skills?.values() ?? [])].filter((k) => k.use
|
|
623
|
+
const forModel = [...(s.skills?.values() ?? [])].filter((k) => k.use === 'model' || k.use === 'both') // "use: me" skills cost nothing here; "always" ones are in the system prompt
|
|
598
624
|
if (forModel.length) {
|
|
599
625
|
const skills = forModel.map((k) => `${k.name}: ${k.description}`).join('\n')
|
|
600
626
|
out.push({ name: 'skill', description: prompt('agent/tool-skill', { skills }), parameters: obj({ name: str }, ['name']) })
|
|
@@ -611,7 +637,7 @@ export function extraTools(s) {
|
|
|
611
637
|
// todo: the model's checklist for this message, shown to the user each time it changes.
|
|
612
638
|
// Lenient: the list as JSON text, plain strings for items, "done" for completed.
|
|
613
639
|
const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
|
|
614
|
-
function todoTool(s, args) {
|
|
640
|
+
async function todoTool(s, args, signal, id) {
|
|
615
641
|
let list = args.todos ?? args.items ?? args
|
|
616
642
|
if (typeof list === 'string') {
|
|
617
643
|
try {
|
|
@@ -622,16 +648,57 @@ function todoTool(s, args) {
|
|
|
622
648
|
}
|
|
623
649
|
if (!Array.isArray(list)) return 'error: todos must be a list of {content, status}'
|
|
624
650
|
const todos = list
|
|
625
|
-
.map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending') }))
|
|
651
|
+
.map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending'), ...(t?.model && { model: String(t.model) }), ...((t?.parallel === true || t?.parallel === 'true') && { parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
|
|
626
652
|
.filter((t) => t.content.trim())
|
|
627
653
|
.map((t) => ({ ...t, status: /done|complete/i.test(t.status) ? 'completed' : /progress|doing|active/i.test(t.status) ? 'in_progress' : 'pending' }))
|
|
628
654
|
s.chat.todos = todos
|
|
629
655
|
s.todoTouched = true
|
|
630
656
|
const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
|
|
631
657
|
s.ui.print(todos.map((t) => ` ${paint[t.status](`${MARK[t.status]} ${t.content}`)}`).join('\n') || c.faint(' (todo list cleared)'))
|
|
658
|
+
const parts = await runParts(s, todos, signal, id)
|
|
632
659
|
const done = todos.filter((t) => t.status === 'completed').length
|
|
633
660
|
const next = todos.find((t) => t.status !== 'completed')
|
|
634
|
-
|
|
661
|
+
// a plan of several parts with none given to another model or run side by side: asked once a message
|
|
662
|
+
const open = todos.filter((t) => t.status === 'pending')
|
|
663
|
+
const askSplit = !parts && !s.isSub && !s.splitAsked && open.length >= 3 && !todos.some((t) => t.parallel || t.model) && s.subagent && s.team?.().length && s.ui.permission !== 'plan'
|
|
664
|
+
if (askSplit) s.splitAsked = true
|
|
665
|
+
return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${askSplit ? `\n\n${prompt('agent/split-check')}` : ''}`
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// The plan's parts marked parallel (or given to another model): each started at once as a helper
|
|
669
|
+
// on its model, all at the same time, each changing only the files its part owns; marked done when
|
|
670
|
+
// it reports back. What they did, for the model to put together and check. '' when none.
|
|
671
|
+
async function runParts(s, todos, signal, id) {
|
|
672
|
+
const parts = todos.filter((t) => t.status === 'pending' && (t.parallel || t.model))
|
|
673
|
+
if (!parts.length || s.isSub || !s.subagent || s.ui.permission === 'plan') return ''
|
|
674
|
+
// a model that isn't one of yours (a name made up, the product's own name): the part runs on this one
|
|
675
|
+
const yours = [{ provider: s.client?.provider, model: s.client?.model }, ...(s.team?.() ?? [])]
|
|
676
|
+
const known = (m) => yours.some((y) => `${y.provider} ${y.model}` === m || y.model === m || m.endsWith(` ${y.model}`))
|
|
677
|
+
const unknown = [...new Set(parts.filter((t) => t.model && !known(t.model)).map((t) => t.model))]
|
|
678
|
+
for (const t of parts) if (t.model && !known(t.model)) delete t.model
|
|
679
|
+
for (const t of parts) t.status = 'in_progress'
|
|
680
|
+
log('parts', parts.map((t) => `${t.content}${t.model ? ` (${t.model})` : ''}${t.files ? ` [${t.files.join(', ')}]` : ''}`))
|
|
681
|
+
s.ui.step('parts', `${parts.length} part${parts.length > 1 ? 's' : ''} at once: ${parts.map((t) => `${clip(t.content, 40)}${t.model ? ` (${t.model})` : ''}`).join(' · ')}`)
|
|
682
|
+
const plan = todos.map((t) => `- ${t.content}`).join('\n')
|
|
683
|
+
const choices = (s.chat?.choices ?? []).join('; ')
|
|
684
|
+
const reports = await Promise.all(
|
|
685
|
+
parts.map(async (t) => {
|
|
686
|
+
const brief = prompt('agent/part', { task: s.task ?? '', plan, part: t.content, files: (t.files ?? []).join(', '), choices })
|
|
687
|
+
let out
|
|
688
|
+
try {
|
|
689
|
+
out = await s.subagent({ prompt: brief, model: t.model, description: clip(t.content, 40), ownFiles: t.files }, signal, id)
|
|
690
|
+
} catch (e) {
|
|
691
|
+
if (e.name === 'AbortError' || signal?.aborted) throw e
|
|
692
|
+
out = `error: ${e.message}`
|
|
693
|
+
}
|
|
694
|
+
t.status = failed(out) ? 'pending' : 'completed'
|
|
695
|
+
return `## ${t.content}${t.model ? ` (${t.model})` : ''}: ${failed(out) ? 'not done' : 'done'}\n${clip(out, 3000)}`
|
|
696
|
+
}),
|
|
697
|
+
)
|
|
698
|
+
s.chat.todos = todos
|
|
699
|
+
const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
|
|
700
|
+
s.ui.print(todos.map((t) => ` ${paint[t.status](`${MARK[t.status]} ${t.content}`)}`).join('\n'))
|
|
701
|
+
return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
|
|
635
702
|
}
|
|
636
703
|
|
|
637
704
|
// ask_user: a question for the user mid-task, with choices (and their own answer) or free text.
|
|
@@ -656,6 +723,13 @@ async function askUser(s, args) {
|
|
|
656
723
|
answer = [...got.filter((x) => !x.own).map((x) => x.label), own?.trim()].filter(Boolean).join(', ')
|
|
657
724
|
} else answer = (await s.ui.ask(`${c.yellow('?')} ${c.bold(question)} `))?.trim()
|
|
658
725
|
log('ask', question, answer)
|
|
726
|
+
// how the user wants the work done: kept with the conversation (a "continue" later still knows), the
|
|
727
|
+
// first such question of a new message starts them afresh; steers the checks and reviews
|
|
728
|
+
if (args.emphasis && answer && s.chat) {
|
|
729
|
+
if (!s.choicesFresh) s.chat.choices = []
|
|
730
|
+
s.choicesFresh = true
|
|
731
|
+
s.chat.choices.push(`${question} → ${answer}`)
|
|
732
|
+
}
|
|
659
733
|
return answer ? `The user answered: ${answer}` : prompt('agent/ask-no-answer')
|
|
660
734
|
}
|
|
661
735
|
|
|
@@ -740,7 +814,19 @@ function memoryTool(s, args) {
|
|
|
740
814
|
// Lenient about slips in names: "chrome-devtools:", "evaluate_script'", no server when there's one.
|
|
741
815
|
const bare = (v) => String(v ?? '').trim().replace(/^["'`]+|["'`:;,.]+$/g, '')
|
|
742
816
|
|
|
817
|
+
// A server's own words on using it (its MCP "instructions"): with its first result in this
|
|
818
|
+
// conversation, not in every request's system prompt.
|
|
819
|
+
function howTo(s, server, out) {
|
|
820
|
+
const said = s.mcpCatalog?.get(server)?.instructions
|
|
821
|
+
if (!said || typeof out !== 'string' || (s.mcpTold ??= new Set()).has(server)) return out
|
|
822
|
+
s.mcpTold.add(server)
|
|
823
|
+
return `${out}\n\n${prompt('agent/mcp-instructions', { server, instructions: said })}`
|
|
824
|
+
}
|
|
825
|
+
|
|
743
826
|
async function mcpTool(s, args, signal) {
|
|
827
|
+
return howTo(s, bare(args?.server) || (s.mcp?.names.length === 1 ? s.mcp.names[0] : ''), await mcpCall(s, args, signal))
|
|
828
|
+
}
|
|
829
|
+
async function mcpCall(s, args, signal) {
|
|
744
830
|
const names = s.mcp?.names ?? []
|
|
745
831
|
// everything written into "server": 'chrome-devtools" tool="navigate_page" arguments={...}'
|
|
746
832
|
const crammed = /^\s*"?([\w.-]+)"?\s+tool\s*[=:]\s*"?([\w.-]+)"?(?:\s+arguments\s*[=:]\s*(\{[\s\S]*\}))?/.exec(String(args.server ?? ''))
|
|
@@ -804,6 +890,39 @@ export function argProblems(schema, a) {
|
|
|
804
890
|
return out
|
|
805
891
|
}
|
|
806
892
|
|
|
893
|
+
// A call's arguments mended where the tool's schema says what was meant, so it isn't sent back over
|
|
894
|
+
// a slip any model makes: a name in the wrong case (msgId → msgid), an unknown name when exactly one
|
|
895
|
+
// required one is missing (expression → function), one value where a list is wanted, a number or
|
|
896
|
+
// true/false written as text, a required one left out that an earlier call to this server gave (or
|
|
897
|
+
// its result marked "[selected]": the page a browser has open). Returns { a, fixed } (what changed).
|
|
898
|
+
export function repairArgs(schema, a, known = {}) {
|
|
899
|
+
const props = schema?.properties ?? {}
|
|
900
|
+
if (!a || typeof a !== 'object' || Array.isArray(a) || !schema?.properties) return { a, fixed: [] }
|
|
901
|
+
a = { ...a }
|
|
902
|
+
const fixed = []
|
|
903
|
+
const rename = (k, to) => ((a[to] = a[k]), delete a[k], fixed.push(`"${k}" → "${to}"`))
|
|
904
|
+
for (const k of Object.keys(a)) {
|
|
905
|
+
const to = !props[k] && Object.keys(props).find((p) => p.toLowerCase() === k.toLowerCase())
|
|
906
|
+
if (to && a[to] === undefined) rename(k, to)
|
|
907
|
+
}
|
|
908
|
+
for (const k of (schema.required ?? []).filter((k) => a[k] === undefined && known[k] !== undefined)) {
|
|
909
|
+
a[k] = known[k]
|
|
910
|
+
fixed.push(`"${k}": ${JSON.stringify(known[k])} (from the last call)`)
|
|
911
|
+
}
|
|
912
|
+
const unknown = Object.keys(a).filter((k) => !props[k])
|
|
913
|
+
const missing = (schema.required ?? []).filter((k) => a[k] === undefined)
|
|
914
|
+
const fits = (k, v) => { const ty = [props[k]?.type ?? []].flat(); return !ty.length || ty.includes(Array.isArray(v) ? 'array' : typeof v) || ty.includes('array') || (Number.isInteger(v) && ty.includes('integer')) }
|
|
915
|
+
if (unknown.length === 1 && missing.length === 1 && fits(missing[0], a[unknown[0]])) rename(unknown[0], missing[0])
|
|
916
|
+
for (const [k, v] of Object.entries(a)) {
|
|
917
|
+
const types = [props[k]?.type ?? []].flat()
|
|
918
|
+
if (!types.length || v === undefined || v === null) continue
|
|
919
|
+
if (types.includes('array') && !Array.isArray(v)) (a[k] = [v]), fixed.push(`"${k}" made a list`)
|
|
920
|
+
else if ((types.includes('number') || types.includes('integer')) && typeof v === 'string' && v.trim() !== '' && !Number.isNaN(Number(v)) && !types.includes('string')) (a[k] = Number(v)), fixed.push(`"${k}" made a number`)
|
|
921
|
+
else if (types.includes('boolean') && (v === 'true' || v === 'false') && !types.includes('string')) (a[k] = v === 'true'), fixed.push(`"${k}" made ${v}`)
|
|
922
|
+
}
|
|
923
|
+
return { a, fixed }
|
|
924
|
+
}
|
|
925
|
+
|
|
807
926
|
// One tool's description and arguments, for the model (describe, or a call that didn't fit).
|
|
808
927
|
const describeTool = (t) => `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}`
|
|
809
928
|
|
|
@@ -819,7 +938,11 @@ async function callMcp(s, server, tool, a, signal) {
|
|
|
819
938
|
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
939
|
}
|
|
821
940
|
}
|
|
822
|
-
//
|
|
941
|
+
// slips mended first (said in the result, so it's done right next time); what still doesn't fit:
|
|
942
|
+
// the schema comes back with what's wrong, and nothing is sent
|
|
943
|
+
const known = (server.lastArgs ??= {}) // values earlier calls to this server gave (helpers share it)
|
|
944
|
+
const mended = def?.inputSchema ? repairArgs(def.inputSchema, a, known) : { a, fixed: [] }
|
|
945
|
+
a = mended.a
|
|
823
946
|
const problems = def?.inputSchema ? argProblems(def.inputSchema, a) : []
|
|
824
947
|
if (problems.length) return `error: ${server.name} · ${tool} wasn't called — ${problems.join('; ')}.\n${describeTool(def)}\nCall it again with arguments that fit.`
|
|
825
948
|
// a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
|
|
@@ -839,6 +962,9 @@ async function callMcp(s, server, tool, a, signal) {
|
|
|
839
962
|
}
|
|
840
963
|
const parts = r.content ?? []
|
|
841
964
|
const text = parts.filter((p) => p.type === 'text').map((p) => p.text).join('\n')
|
|
965
|
+
for (const [k, v] of Object.entries(a)) if (v !== null && typeof v !== 'object') known[k] = v
|
|
966
|
+
const selected = /(\d+):[^\n]*\[selected\]/.exec(text)?.[1] // a browser's open page, after new_page/select_page
|
|
967
|
+
if (selected) known.pageId = Number(selected)
|
|
842
968
|
// Its images: the ones it returned, and image files it made while it ran (a path in its text to a
|
|
843
969
|
// file written during the call: "Saved screenshot to /…/shot.webp"; an old one it only mentions
|
|
844
970
|
// isn't one). Each is a file too, so a model that can't see them can have one that can look.
|
|
@@ -868,7 +994,8 @@ async function callMcp(s, server, tool, a, signal) {
|
|
|
868
994
|
note = `\n(${s.pendingImages.length - shown} image(s): shown to you in the next message${left.length ? `; not shown: ${left.join('; ')}` : ''})`
|
|
869
995
|
} else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/images-unseen', { files: files.join('\n') })}`
|
|
870
996
|
else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
|
|
871
|
-
|
|
997
|
+
const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
|
|
998
|
+
return `${r.isError ? 'error: ' : ''}${text || '(no text)'}${note}${mendNote}`
|
|
872
999
|
}
|
|
873
1000
|
|
|
874
1001
|
// tool "search": the tools of every server (or one) whose name or description has the query's
|
|
@@ -1101,6 +1228,8 @@ async function toolRun(name, args, s, signal, id) {
|
|
|
1101
1228
|
const hookName = name === 'mcp' && args?.server && args?.tool ? mcpName(String(args.server), String(args.tool)) : name
|
|
1102
1229
|
const pre = await runHooks(s, 'PreToolUse', { tool_name: hookName, tool_input: args }, signal)
|
|
1103
1230
|
if (pre.block) return prompt('agent/hook-blocked-tool', { reason: pre.block })
|
|
1231
|
+
const notMine = s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
|
|
1232
|
+
if (notMine) return prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') })
|
|
1104
1233
|
let out = await tool(name, args, s, signal, id)
|
|
1105
1234
|
const post = await runHooks(s, 'PostToolUse', { tool_name: hookName, tool_input: args, tool_response: out }, signal)
|
|
1106
1235
|
if (post.block) out += `\n\n${prompt('agent/hook-after-tool', { reason: post.block })}`
|
|
@@ -1108,6 +1237,16 @@ async function toolRun(name, args, s, signal, id) {
|
|
|
1108
1237
|
return out
|
|
1109
1238
|
}
|
|
1110
1239
|
|
|
1240
|
+
// The files a change would touch (edit_file's edits, write_file's path, a patch's files), for a part
|
|
1241
|
+
// of the plan that owns only some.
|
|
1242
|
+
function partPaths(name, args) {
|
|
1243
|
+
const a = normalize(args ?? {})
|
|
1244
|
+
if (name === 'edit_file') return [a.path, ...[a.edits ?? []].flat().map((e) => e?.path)].filter(Boolean).map(String)
|
|
1245
|
+
if (name === 'write_file' || name === 'append_file') return [a.path].filter(Boolean).map(String)
|
|
1246
|
+
if (name === 'apply_patch') return [...String(a.input ?? a.patch ?? '').matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim())
|
|
1247
|
+
return []
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1111
1250
|
// Argument names other tools use (Claude Code's file_path, old_string, new_string, …): models
|
|
1112
1251
|
// trained on them send them here too.
|
|
1113
1252
|
const ALIASES = { file_path: 'path', filePath: 'path', file: 'path', old_string: 'search', old_str: 'search', oldText: 'search', new_string: 'replace', new_str: 'replace', newText: 'replace', cmd: 'command', startLine: 'start_line', lineStart: 'start_line', start: 'start_line', endLine: 'end_line', lineEnd: 'end_line', end: 'end_line' }
|
|
@@ -1182,9 +1321,9 @@ async function tool(name, args, s, signal, id) {
|
|
|
1182
1321
|
}
|
|
1183
1322
|
case 'run_command':
|
|
1184
1323
|
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
|
|
1185
|
-
return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true')) + outsideNote(root, String(args.command ?? ''))
|
|
1324
|
+
return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true', args.wait)) + outsideNote(root, String(args.command ?? ''))
|
|
1186
1325
|
case 'background':
|
|
1187
|
-
return backgroundTool(s, args)
|
|
1326
|
+
return await backgroundTool(s, args, signal)
|
|
1188
1327
|
case 'apply_patch':
|
|
1189
1328
|
return await applyPatch(s, args.input ?? args.patch ?? args.command ?? '')
|
|
1190
1329
|
case 'mcp':
|
|
@@ -1192,7 +1331,7 @@ async function tool(name, args, s, signal, id) {
|
|
|
1192
1331
|
case 'memory':
|
|
1193
1332
|
return memoryTool(s, args)
|
|
1194
1333
|
case 'todo':
|
|
1195
|
-
return todoTool(s, args)
|
|
1334
|
+
return await todoTool(s, args, signal, id)
|
|
1196
1335
|
case 'web_search':
|
|
1197
1336
|
case 'web_fetch':
|
|
1198
1337
|
return await webTool(s, name, args, signal)
|
|
@@ -1206,7 +1345,7 @@ async function tool(name, args, s, signal, id) {
|
|
|
1206
1345
|
}
|
|
1207
1346
|
default: {
|
|
1208
1347
|
const m = mcpTarget(s, name)
|
|
1209
|
-
if (m) return await callMcp(s, m.server, m.tool, args, signal)
|
|
1348
|
+
if (m) return howTo(s, m.server.name, await callMcp(s, m.server, m.tool, args, signal))
|
|
1210
1349
|
return (await s.director?.tool(name, args, s, signal)) ?? `error: there is no tool named ${name}`
|
|
1211
1350
|
}
|
|
1212
1351
|
}
|
package/src/ui.js
CHANGED
|
@@ -105,7 +105,7 @@ setTheme()
|
|
|
105
105
|
|
|
106
106
|
// keybindings.json: { "ctrl+o": "cycle_permissions", "ctrl+g": "/toggle_thinking", "shift+tab": "none" }.
|
|
107
107
|
// Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
|
|
108
|
-
// scroll_line_up, scroll_line_down (3 lines), voice, new_tab,
|
|
108
|
+
// scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, new_tab,
|
|
109
109
|
// close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
|
|
110
110
|
// built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
|
|
111
111
|
const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
|
|
@@ -117,8 +117,9 @@ export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ct
|
|
|
117
117
|
// Alt+A all of them (as one message); Alt+M switches what goes when an answer is done (all or the
|
|
118
118
|
// next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
|
|
119
119
|
// Alt+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as
|
|
120
|
-
// PgUp/PgDn and the mouse wheel do)
|
|
121
|
-
|
|
120
|
+
// PgUp/PgDn and the mouse wheel do), Alt+Shift+↑↓ (or Ctrl+Home/End) to its top and bottom.
|
|
121
|
+
// keybindings.json can move any of them.
|
|
122
|
+
export const DEFAULT_KEYS = { 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'ctrl+home': 'scroll_top', 'ctrl+end': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', 'ctrl+pagedown': 'next_tab', 'ctrl+pageup': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
|
|
122
123
|
export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
|
|
123
124
|
let raw = {}
|
|
124
125
|
try {
|
|
@@ -352,6 +353,23 @@ export function wrapAnsi(line, cols) {
|
|
|
352
353
|
return rows
|
|
353
354
|
}
|
|
354
355
|
|
|
356
|
+
// wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut)
|
|
357
|
+
export function wrapWords(line, cols) {
|
|
358
|
+
const width = (x) => x.replace(/\x1b\[[0-9;]*m/g, '').length
|
|
359
|
+
const rows = []
|
|
360
|
+
let row = ''
|
|
361
|
+
for (const word of line.split(/(?<= )/)) {
|
|
362
|
+
if (width(row.trim()) && width(row + word.trimEnd()) > cols) {
|
|
363
|
+
const style = (row.match(/\x1b\[[0-9;]*m/g) ?? []).reduce((st, e) => (e === '\x1b[0m' ? '' : st + e), '') // colors still on: carried to the next row
|
|
364
|
+
rows.push(row.trimEnd() + (style ? '\x1b[0m' : ''))
|
|
365
|
+
row = style
|
|
366
|
+
}
|
|
367
|
+
row += word
|
|
368
|
+
}
|
|
369
|
+
rows.push(row)
|
|
370
|
+
return rows.flatMap((r) => wrapAnsi(r, cols))
|
|
371
|
+
}
|
|
372
|
+
|
|
355
373
|
// Streams text as an indented, word-wrapped block: "<marker>first line\n next line".
|
|
356
374
|
// Leading/trailing blank lines are dropped; runs of blank lines collapse to one.
|
|
357
375
|
export class Block {
|
|
@@ -695,7 +713,7 @@ export class UI {
|
|
|
695
713
|
if (by) top = Math.max(0, Math.min(top + by, total - page))
|
|
696
714
|
},
|
|
697
715
|
draw: (w, h) => {
|
|
698
|
-
const rows = all.flatMap((l) =>
|
|
716
|
+
const rows = all.flatMap((l) => wrapWords(l, w))
|
|
699
717
|
total = rows.length
|
|
700
718
|
page = h - 2
|
|
701
719
|
top = Math.max(0, Math.min(top, total - page))
|
|
@@ -888,12 +906,15 @@ export class UI {
|
|
|
888
906
|
|
|
889
907
|
// Full-screen mode: the alternate screen, the conversation on top, the input pinned to the
|
|
890
908
|
// bottom row, the spinner and the suggestion menu just above the input. PgUp/PgDn scroll.
|
|
891
|
-
|
|
909
|
+
// mouse: HeartCode takes the mouse (the wheel scrolls the conversation, dragging copies); off,
|
|
910
|
+
// the terminal keeps it, so text is selected and copied the terminal's own way (over SSH too).
|
|
911
|
+
fullscreen({ mouse = false } = {}) {
|
|
892
912
|
if (this.full || !(this.input.isTTY && this.out.isTTY)) return
|
|
893
913
|
this.full = true
|
|
914
|
+
this.mouseOn = mouse ? MOUSE_ON : ''
|
|
894
915
|
// alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
|
|
895
|
-
// · mouse reports (SGR)
|
|
896
|
-
this.out.write('\x1b[?1049h\x1b[H\x1b[2J\x1b[>1u\x1b[?2004h' +
|
|
916
|
+
// · mouse reports (SGR), when HeartCode takes the mouse
|
|
917
|
+
this.out.write('\x1b[?1049h\x1b[H\x1b[2J\x1b[>1u\x1b[?2004h' + this.mouseOn)
|
|
897
918
|
this.out.on('resize', () => this.render())
|
|
898
919
|
this.#rl()
|
|
899
920
|
process.on('exit', () => this.leaveFullscreen())
|
|
@@ -911,7 +932,7 @@ export class UI {
|
|
|
911
932
|
this.input.setRawMode?.(true)
|
|
912
933
|
this.rl?.resume()
|
|
913
934
|
if (wasFull) {
|
|
914
|
-
this.out.write('\x1b[?1049h\x1b[>1u\x1b[?2004h' +
|
|
935
|
+
this.out.write('\x1b[?1049h\x1b[>1u\x1b[?2004h' + this.mouseOn)
|
|
915
936
|
this.render()
|
|
916
937
|
}
|
|
917
938
|
}
|
|
@@ -1036,7 +1057,7 @@ export class UI {
|
|
|
1036
1057
|
// The conversation scrolls (rows up, negative: down); the tabs, the input and the status bar stay.
|
|
1037
1058
|
scrollBy(n) {
|
|
1038
1059
|
if (!this.full || this.out.hidden) return
|
|
1039
|
-
this.scroll = Math.max(0, this.scroll + n)
|
|
1060
|
+
this.scroll = Math.max(0, this.scroll + n) // Infinity: the top (render keeps it in range)
|
|
1040
1061
|
this.render()
|
|
1041
1062
|
}
|
|
1042
1063
|
page() {
|
|
@@ -1124,7 +1145,7 @@ export class UI {
|
|
|
1124
1145
|
bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(this.#label())}`, cols))
|
|
1125
1146
|
if (timer) bottom.push(fit(` ${c.faint(timer)}`, cols))
|
|
1126
1147
|
}
|
|
1127
|
-
if (this.scroll) bottom.push(c.dim(` ↓ ${this.scroll
|
|
1148
|
+
if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here while you read · Alt+Shift+↓ to the bottom`))
|
|
1128
1149
|
if (this.ahead.length) {
|
|
1129
1150
|
const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
|
|
1130
1151
|
const sep = c.ghost(' · ')
|
|
@@ -1139,6 +1160,9 @@ export class UI {
|
|
|
1139
1160
|
const inputTop = rows - below.length - inputRows + 1 // first row of the input
|
|
1140
1161
|
const avail = Math.max(0, inputTop - 1 - bottom.length - head.length)
|
|
1141
1162
|
const all = this.#rows(cols)
|
|
1163
|
+
// scrolled up: what you're reading stays put while new lines come in below (back at the bottom: it follows again)
|
|
1164
|
+
if (this.scroll && this.rowsWere && this.rowsCols === cols && all.length > this.rowsWere) this.scroll += all.length - this.rowsWere
|
|
1165
|
+
;[this.rowsWere, this.rowsCols] = [all.length, cols]
|
|
1142
1166
|
this.scroll = Math.min(this.scroll, Math.max(0, all.length - avail))
|
|
1143
1167
|
const top = Math.max(0, all.length - avail - this.scroll)
|
|
1144
1168
|
const view = all.slice(top, top + avail)
|
|
@@ -1452,6 +1476,9 @@ export class UI {
|
|
|
1452
1476
|
case 'scroll_line_up':
|
|
1453
1477
|
case 'scroll_line_down':
|
|
1454
1478
|
return this.scrollBy(what === 'scroll_line_up' ? 3 : -3)
|
|
1479
|
+
case 'scroll_top':
|
|
1480
|
+
case 'scroll_bottom':
|
|
1481
|
+
return this.scrollBy(what === 'scroll_top' ? Infinity : -Infinity)
|
|
1455
1482
|
}
|
|
1456
1483
|
if (!this.asking) {
|
|
1457
1484
|
this.ahead.push(what)
|
|
@@ -1801,6 +1828,7 @@ export class UI {
|
|
|
1801
1828
|
const picked = Array.isArray(pick?.chosen) ? pick.chosen.map((x) => x.label).join(', ') : pick?.chosen?.label
|
|
1802
1829
|
if (pick?.quiet) this.render()
|
|
1803
1830
|
else if (pick) this.write(echo + (picked ?? c.dim('cancelled')) + '\n')
|
|
1831
|
+
else if (l !== null && history && this.isCommand(l.trim()) && !/^\s*\/skill:/.test(l)) this.notice(/^\S+/.exec(l.trim())[0], 3000, '›') // a command isn't part of the conversation: its name for a moment (not its arguments: maybe a key)
|
|
1804
1832
|
else if (l !== null) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
|
|
1805
1833
|
else this.render()
|
|
1806
1834
|
}
|
|
@@ -1903,6 +1931,23 @@ export class UI {
|
|
|
1903
1931
|
})
|
|
1904
1932
|
}
|
|
1905
1933
|
}
|
|
1934
|
+
// A /command's output is taken back out of the conversation once it's done (nothing of a command
|
|
1935
|
+
// stays): one line shown as a notice for a moment, more in a box (Esc closes). Not when the command
|
|
1936
|
+
// put another conversation on the screen (/resume, /clear_chat…): that's what it's for.
|
|
1937
|
+
mark() {
|
|
1938
|
+
return { log: this.log, at: this.log.length - 1, base: this.log.at(-1), tail: this.tail, sgr: this.sgr }
|
|
1939
|
+
}
|
|
1940
|
+
unmark(m, title) {
|
|
1941
|
+
if (this.log !== m.log || this.log.length <= m.at || !this.log[m.at].startsWith(m.base)) return this.render()
|
|
1942
|
+
const text = [this.log[m.at].slice(m.base.length), ...this.log.slice(m.at + 1)].join('\n').replace(/^(\s*\n)+|\s+$/g, '')
|
|
1943
|
+
this.log.length = m.at + 1
|
|
1944
|
+
this.log[m.at] = m.base
|
|
1945
|
+
Object.assign(this, { tail: m.tail, sgr: m.sgr })
|
|
1946
|
+
const lines = text ? text.split('\n') : []
|
|
1947
|
+
if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
|
|
1948
|
+
else if (lines.length) this.showText(title, text)
|
|
1949
|
+
else this.render()
|
|
1950
|
+
}
|
|
1906
1951
|
// A blank line before a new block, unless there already is one.
|
|
1907
1952
|
gap() {
|
|
1908
1953
|
if (this.tail && this.tail !== '\n\n') this.write(this.tail.endsWith('\n') ? '\n' : '\n\n')
|