heartcode 0.1.54 → 0.1.56
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 +51 -0
- package/bin/heartcode.js +86 -33
- package/package.json +1 -1
- package/prompts/agent.md +8 -5
- package/prompts/guided.md +1 -1
- package/src/acp.js +9 -4
- package/src/agent.js +122 -32
- package/src/client.js +7 -6
- package/src/guided.js +65 -15
- package/src/headless.js +3 -1
- package/src/lsp.js +10 -0
- package/src/tabs.js +6 -2
- package/src/tools.js +158 -40
- package/src/ui.js +331 -88
package/src/ui.js
CHANGED
|
@@ -78,6 +78,9 @@ export const THEMES = {
|
|
|
78
78
|
}
|
|
79
79
|
export const c = { bold: sgr(1, 22), italic: sgr(3, 23) }
|
|
80
80
|
export let background = '' // the theme's background, as an escape sequence ('' = the terminal's)
|
|
81
|
+
let foreground = '' // and its text color, with it: the terminal's own may not show on it (light on a dark terminal)
|
|
82
|
+
// A row painted in the theme's background (and text color, where a style ends its own)
|
|
83
|
+
const paintBg = (t) => t.replace(/\x1b\[(0|39|49)?m/g, (m, n) => m + (n === '39' ? foreground : n === '49' ? background : background + foreground))
|
|
81
84
|
// Each palette color's opening sequence, to recolor what's already on screen (UI.recolor).
|
|
82
85
|
export const themeCodes = () => Object.fromEntries(Object.keys(THEMES.dark).filter((k) => k !== 'background').map((k) => [k, c[k]('\0').split('\0')[0]]))
|
|
83
86
|
export function setTheme(name = 'dark') {
|
|
@@ -93,6 +96,7 @@ export function setTheme(name = 'dark') {
|
|
|
93
96
|
const [bgHex, bgBasic] = t.background ?? [null]
|
|
94
97
|
delete t.background
|
|
95
98
|
background = color && bgHex ? bg(bgHex, bgBasic)('\0').split('\0')[0] : ''
|
|
99
|
+
foreground = background && t.text[0] ? fg(t.text[0], t.text[1])('\0').split('\0')[0] : ''
|
|
96
100
|
for (const [k, [hex, basic]] of Object.entries(t)) {
|
|
97
101
|
if (!hex) c[k] = k === 'select' ? sgr(7, 27) : basic === 1 ? sgr(1, 22) : basic === 2 ? sgr(2, 22) : (s) => String(s)
|
|
98
102
|
else c[k] = (k === 'select' ? bg : fg)(hex, basic)
|
|
@@ -306,6 +310,8 @@ function sgrState(state = {}, text) {
|
|
|
306
310
|
}
|
|
307
311
|
const sgrPrefix = (st = {}) => [st.fg, st.bg, st.bold, st.italic].filter(Boolean).map((x) => `\x1b[${x}m`).join('')
|
|
308
312
|
|
|
313
|
+
const plainOf = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
|
|
314
|
+
|
|
309
315
|
// Cuts a colored line to `cols` cells.
|
|
310
316
|
function fit(line, cols) {
|
|
311
317
|
return wrapAnsi(line, cols)[0]
|
|
@@ -356,13 +362,14 @@ export function wrapAnsi(line, cols) {
|
|
|
356
362
|
return rows
|
|
357
363
|
}
|
|
358
364
|
|
|
359
|
-
// wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut)
|
|
360
|
-
|
|
365
|
+
// wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut);
|
|
366
|
+
// hang: the rows after the first indented by that many cells
|
|
367
|
+
export function wrapWords(line, cols, hang = 0) {
|
|
361
368
|
const width = (x) => x.replace(/\x1b\[[0-9;]*m/g, '').length
|
|
362
369
|
const rows = []
|
|
363
370
|
let row = ''
|
|
364
371
|
for (const word of line.split(/(?<= )/)) {
|
|
365
|
-
if (width(row.trim()) && width(row + word.trimEnd()) > cols) {
|
|
372
|
+
if (width(row.trim()) && width(row + word.trimEnd()) > (rows.length ? cols - hang : cols)) {
|
|
366
373
|
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
|
|
367
374
|
rows.push(row.trimEnd() + (style ? '\x1b[0m' : ''))
|
|
368
375
|
row = style
|
|
@@ -370,7 +377,33 @@ export function wrapWords(line, cols) {
|
|
|
370
377
|
row += word
|
|
371
378
|
}
|
|
372
379
|
rows.push(row)
|
|
373
|
-
|
|
380
|
+
const pad = ' '.repeat(hang)
|
|
381
|
+
return rows.flatMap((r, i) => {
|
|
382
|
+
const [head, ...more] = wrapAnsi(r, i ? cols - hang : cols)
|
|
383
|
+
return [i ? pad + head : head, ...(more.length ? wrapAnsi(more.join(''), cols - hang).map((x) => pad + x) : [])]
|
|
384
|
+
})
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// wrapWords with a hanging indent: wrapped rows go under the text, not back to column 0 (after a
|
|
388
|
+
// marker like "! ", "● ", "⎿ ", or a two-column line's description column)
|
|
389
|
+
export function wrapHang(line, cols) {
|
|
390
|
+
const plain = line.replace(/\x1b\[[0-9;]*m/g, '')
|
|
391
|
+
if (width(plain) <= cols) return [line]
|
|
392
|
+
const m = /^\s*(?:[^\w\s]{1,2}|\d{1,3}[.)]) (?=\S)/.exec(plain) ?? /^\s*\S.*?\S {2,}(?=\S)/.exec(plain) ?? /^\s*/.exec(plain)
|
|
393
|
+
const hang = width(m[0])
|
|
394
|
+
return wrapWords(line, cols, hang < cols * 0.6 ? hang : 0)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// "a · b · c" on as many rows as it needs, broken between its parts (never inside one)
|
|
398
|
+
export function wrapParts(line, cols, sep = ' · ') {
|
|
399
|
+
const vis = (x) => width(x.replace(/\x1b\[[0-9;]*m/g, ''))
|
|
400
|
+
return line.split(sep).reduce((rows, k) => (rows.length && vis(rows.at(-1) + sep + k) <= cols ? (rows[rows.length - 1] += sep + k) : rows.push(k), rows), [])
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// 4000 → "4s", 75000 → "1m 15s", 2h 3m: a clock that fits on a busy line
|
|
404
|
+
const short = (ms) => {
|
|
405
|
+
const s = Math.max(0, Math.floor(ms / 1000))
|
|
406
|
+
return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor(s / 60) % 60}m`
|
|
374
407
|
}
|
|
375
408
|
|
|
376
409
|
// Streams text as an indented, word-wrapped block: "<marker>first line\n next line".
|
|
@@ -401,7 +434,7 @@ export class Block {
|
|
|
401
434
|
out += '\n'.repeat(Math.min(this.newlines, 2)) + this.indent
|
|
402
435
|
this.col = this.indent.length
|
|
403
436
|
this.newlines = 0
|
|
404
|
-
} else if (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12)) {
|
|
437
|
+
} else if (!this.nowrap && (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12))) {
|
|
405
438
|
out += '\n' + this.indent + this.hang
|
|
406
439
|
this.col = this.indent.length + this.hang.length
|
|
407
440
|
if (ch === ' ') continue
|
|
@@ -417,9 +450,10 @@ export class Block {
|
|
|
417
450
|
}
|
|
418
451
|
}
|
|
419
452
|
|
|
420
|
-
// The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks
|
|
421
|
-
// **bold**, *italic* and `code`. Into a
|
|
422
|
-
// or a "*" could still be a marker.
|
|
453
|
+
// The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks (with a gutter),
|
|
454
|
+
// tables (in columns: held back until the table ends), rules, **bold**, *italic* and `code`. Into a
|
|
455
|
+
// Block (which wraps); held back only while a line's start or a "*" could still be a marker. Links
|
|
456
|
+
// stay as written.
|
|
423
457
|
export class Markdown {
|
|
424
458
|
constructor(block, base = (x) => x) {
|
|
425
459
|
Object.assign(this, { block, base, buf: '', sol: true, fence: false, bold: false, ital: false, code: false, line: null, prev: ' ' })
|
|
@@ -455,7 +489,11 @@ export class Markdown {
|
|
|
455
489
|
this.fence = !this.fence
|
|
456
490
|
return nl < 0 ? s.length : nl + 1 // the fence line itself isn't shown
|
|
457
491
|
}
|
|
458
|
-
if (this.fence)
|
|
492
|
+
if (this.fence) {
|
|
493
|
+
b.hang = ' '
|
|
494
|
+
this.#out('│ ', c.ghost) // code, set apart from the prose
|
|
495
|
+
return 0
|
|
496
|
+
}
|
|
459
497
|
if (whole && /^\s*([-*_])(\s*\1){2,}\s*$/.test(head)) {
|
|
460
498
|
this.#out('─'.repeat(Math.min(40, b.width - b.indent.length)), c.ghost)
|
|
461
499
|
return head.length
|
|
@@ -478,21 +516,72 @@ export class Markdown {
|
|
|
478
516
|
if ((m = /^\s*>\s?/.exec(head))) {
|
|
479
517
|
b.hang = ' '
|
|
480
518
|
this.line = (x) => c.faint(c.italic(x))
|
|
481
|
-
this.#out('
|
|
519
|
+
this.#out('▎ ', c.accent) // a quote: not the code gutter's │
|
|
482
520
|
return m[0].length
|
|
483
521
|
}
|
|
484
522
|
return 0
|
|
485
523
|
}
|
|
524
|
+
// A table ("| a | b |" rows, "|---|" under the head): once it has ended (false: not yet), drawn
|
|
525
|
+
// in columns fitted to the width, the head bold, a rule under it. Returns how much of s it took.
|
|
526
|
+
#table(s, final) {
|
|
527
|
+
const lines = []
|
|
528
|
+
let at = 0
|
|
529
|
+
for (;;) {
|
|
530
|
+
const nl = s.indexOf('\n', at)
|
|
531
|
+
if (nl < 0) {
|
|
532
|
+
const rest = s.slice(at)
|
|
533
|
+
if (/^[ \t]*[^ \t|]/.test(rest)) break // the next line isn't a row: the table is over
|
|
534
|
+
if (!final) return false // a row still coming, or the table may go on
|
|
535
|
+
if (rest.trim()) lines.push(rest), (at = s.length)
|
|
536
|
+
break
|
|
537
|
+
}
|
|
538
|
+
const line = s.slice(at, nl)
|
|
539
|
+
if (!/^[ \t]*\|/.test(line)) break
|
|
540
|
+
lines.push(line)
|
|
541
|
+
at = nl + 1
|
|
542
|
+
}
|
|
543
|
+
const sep = (l) => /^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/.test(l)
|
|
544
|
+
const b = this.block
|
|
545
|
+
if (!lines.some(sep)) {
|
|
546
|
+
for (const l of lines) this.#out(l + '\n', this.base) // not a table after all: as written
|
|
547
|
+
return at
|
|
548
|
+
}
|
|
549
|
+
const strip = (t) => t.replace(/\*\*|__|`/g, '').trim()
|
|
550
|
+
const rows = lines.filter((l) => !sep(l)).map((l) => l.trim().replace(/^\||\|$/g, '').split('|').map(strip))
|
|
551
|
+
const n = Math.max(...rows.map((r) => r.length))
|
|
552
|
+
const wide = [...Array(n)].map((_, k) => Math.max(1, ...rows.map((r) => width(r[k] ?? ''))))
|
|
553
|
+
const room = b.width - b.indent.length - 3 * (n - 1)
|
|
554
|
+
while (wide.reduce((x, y) => x + y, 0) > room && Math.max(...wide) > 3) wide[wide.indexOf(Math.max(...wide))]-- // too wide: the widest columns give way
|
|
555
|
+
const cell = (t, w) => (width(t) > w ? `${sliceCols(t, 0, w - 1)}…` : t + ' '.repeat(w - width(t)))
|
|
556
|
+
b.nowrap = true
|
|
557
|
+
rows.forEach((r, i) => {
|
|
558
|
+
wide.forEach((w, k) => {
|
|
559
|
+
if (k) this.#out(' │ ', c.ghost)
|
|
560
|
+
const t = k === n - 1 ? cell(r[k] ?? '', w).trimEnd() : cell(r[k] ?? '', w)
|
|
561
|
+
this.#out(t || ' ', i ? this.base : (x) => c.bold(c.bright(x)))
|
|
562
|
+
})
|
|
563
|
+
this.#out('\n')
|
|
564
|
+
if (!i) this.#out(wide.map((w) => '─'.repeat(w)).join('─┼─') + '\n', c.ghost)
|
|
565
|
+
})
|
|
566
|
+
b.nowrap = false
|
|
567
|
+
return at
|
|
568
|
+
}
|
|
486
569
|
#run(final) {
|
|
487
570
|
let s = this.buf
|
|
488
571
|
let text = ''
|
|
489
572
|
const flush = () => (this.#out(text), (text = ''))
|
|
490
573
|
let i = 0
|
|
491
574
|
while (i < s.length) {
|
|
575
|
+
if (this.sol && !this.fence && /^[ \t]*\|/.test(s.slice(i, i + 40))) {
|
|
576
|
+
const n = this.#table(s.slice(i), final)
|
|
577
|
+
if (n === false) break
|
|
578
|
+
i += n
|
|
579
|
+
continue
|
|
580
|
+
}
|
|
492
581
|
if (this.sol) {
|
|
493
582
|
const n = this.#lineStart(s.slice(i), final)
|
|
494
583
|
if (n === false) break
|
|
495
|
-
this.sol =
|
|
584
|
+
this.sol = n > 0 && s[i + n - 1] === '\n' // a fence line, taken whole: the next line starts next
|
|
496
585
|
i += n
|
|
497
586
|
continue
|
|
498
587
|
}
|
|
@@ -688,6 +777,8 @@ export class UI {
|
|
|
688
777
|
this.asking = false
|
|
689
778
|
this.frame = 0
|
|
690
779
|
this.dialog = null // a box over the screen (the background commands' logs)
|
|
780
|
+
this.waitingFor = null // () → the model a request waits on (the app's), for "waiting for <model>"
|
|
781
|
+
this.helpers = new Map() // helpers at work (agent.js): label → what it's doing now, shown under the spinner
|
|
691
782
|
}
|
|
692
783
|
|
|
693
784
|
// A dialog: a box in the middle, 70% of the screen each way, the conversation going on around it;
|
|
@@ -704,8 +795,9 @@ export class UI {
|
|
|
704
795
|
this.render()
|
|
705
796
|
}
|
|
706
797
|
// Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
|
|
707
|
-
// and the wheel scroll it, Esc closes it
|
|
708
|
-
|
|
798
|
+
// and the wheel scroll it, Esc closes it (and toggle: a key's action, as the key that opened it).
|
|
799
|
+
// Without the full screen: printed.
|
|
800
|
+
showText(title, text, toggle) {
|
|
709
801
|
if (!this.full) return this.print(text)
|
|
710
802
|
const all = String(text).split('\n')
|
|
711
803
|
let top = 0
|
|
@@ -713,26 +805,27 @@ export class UI {
|
|
|
713
805
|
let total = 0
|
|
714
806
|
this.setDialog({
|
|
715
807
|
title,
|
|
808
|
+
toggle,
|
|
716
809
|
key: (key) => {
|
|
717
810
|
const by = { up: key.wheel ? -3 : -1, down: key.wheel ? 3 : 1, pageup: -page, pagedown: page, home: -1e9, end: 1e9 }[key.name]
|
|
718
811
|
if (by) top = Math.max(0, Math.min(top + by, total - page))
|
|
719
812
|
},
|
|
720
813
|
draw: (w, h) => {
|
|
721
|
-
const rows = all.flatMap((l) =>
|
|
814
|
+
const rows = all.flatMap((l) => wrapHang(l, w)) // a two-column line's description wraps under itself
|
|
722
815
|
total = rows.length
|
|
723
|
-
|
|
816
|
+
const foot = (p) => wrapParts(`${total > p ? `${top + 1}–${Math.min(total, top + p)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''}Esc close`, w)
|
|
817
|
+
page = h - 1 - foot(h - 2).length
|
|
724
818
|
top = Math.max(0, Math.min(top, total - page))
|
|
725
|
-
|
|
726
|
-
const where = total > page ? `${top + 1}–${Math.min(total, top + page)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''
|
|
727
|
-
return [...shown, '', c.faint(`${where}Esc close`)]
|
|
819
|
+
return [...rows.slice(top, top + page), '', ...foot(page).map((r) => c.faint(r))]
|
|
728
820
|
},
|
|
729
821
|
})
|
|
730
822
|
}
|
|
731
823
|
|
|
732
|
-
// where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border)
|
|
824
|
+
// where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border); 70% of the
|
|
825
|
+
// screen, 90% of a small one (a narrow one: long names on fewer rows)
|
|
733
826
|
#dialogBox(cols, rows) {
|
|
734
|
-
const w = Math.max(30, Math.floor(cols * 0.7))
|
|
735
|
-
const h = Math.max(8, Math.floor(rows * 0.7))
|
|
827
|
+
const w = Math.max(30, Math.floor(cols * (cols < 100 ? 0.9 : 0.7)))
|
|
828
|
+
const h = Math.max(8, Math.floor(rows * (rows < 40 ? 0.9 : 0.7)))
|
|
736
829
|
return { x: Math.floor((cols - w) / 2) + 1, y: Math.floor((rows - h) / 2) + 1, w: Math.min(w, cols) - 2, h: Math.min(h, rows) - 2 }
|
|
737
830
|
}
|
|
738
831
|
// d: { title, lines(w, h) → lines (at most h), fill?: always 70% tall too (a log), cursor?(w) →
|
|
@@ -751,14 +844,14 @@ export class UI {
|
|
|
751
844
|
const x = Math.floor((cols - W - 2) / 2) + 1
|
|
752
845
|
const y = Math.floor((rows - h - 2 * PY - 2) / 2) + 1
|
|
753
846
|
this.dialogAt = { x, y, W, H: h + 2 * PY, cx: x + 1 + PX, cy: y + 1 + PY } // for the mouse (screen cells, from 1)
|
|
754
|
-
const paint = (t) => (background ? `${background}${t
|
|
847
|
+
const paint = (t) => (background ? `${background}${foreground}${paintBg(t)}\x1b[0m` : `${t}\x1b[0m`)
|
|
755
848
|
const pad = (t, n) => {
|
|
756
849
|
const cut = fit(t, n)
|
|
757
850
|
return cut + ' '.repeat(Math.max(0, n - width(cut.replace(/\x1b\[[0-9;]*m/g, ''))))
|
|
758
851
|
}
|
|
759
852
|
const title = name ? ` ${width(name) > W - 6 ? `${fit(name, W - 7)}…` : name} ` : '' // too long: cut (a question shows all of it inside)
|
|
760
853
|
const row = (i, t) => `\x1b[${y + i};${x}H${paint(t)}`
|
|
761
|
-
let out = row(0, c.brand('╭─') + c.bold(title) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
|
|
854
|
+
let out = row(0, c.brand('╭─') + c.bright(c.bold(title)) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
|
|
762
855
|
const blank = c.brand('│') + ' '.repeat(W) + c.brand('│')
|
|
763
856
|
for (let i = 0; i < PY; i++) out += row(1 + i, blank)
|
|
764
857
|
for (let i = 0; i < h; i++) out += row(1 + PY + i, c.brand('│') + ' '.repeat(PX) + pad(lines[i] ?? '', w) + ' '.repeat(PX) + c.brand('│'))
|
|
@@ -771,11 +864,17 @@ export class UI {
|
|
|
771
864
|
return [out, cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l']
|
|
772
865
|
}
|
|
773
866
|
|
|
867
|
+
// A pick shown as cards: one to choose from a few, in no groups (no filter to type into)
|
|
868
|
+
#cards(pick) {
|
|
869
|
+
return Boolean(pick && !pick.multi && pick.items.length <= 6 && !pick.items.some((x) => x.group))
|
|
870
|
+
}
|
|
871
|
+
|
|
774
872
|
// The question being asked, as a dialog: its title; what's typed (the filter, or the answer) with the
|
|
775
873
|
// cursor; a picker's choices. A short list (a few, one to choose) is shown as cards: the name, its
|
|
776
874
|
// description under it. A permission (confirm) shows what just happened (the change or command it
|
|
777
875
|
// asks about) above the choices. A picker's body (pick's option): a few lines saying what's going on.
|
|
778
|
-
|
|
876
|
+
// Too little room: the keys and the countdown stay; the text, the choices, what it's about give way.
|
|
877
|
+
#question(cols, rows) {
|
|
779
878
|
const rl = this.rl
|
|
780
879
|
const m = this.menu
|
|
781
880
|
const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
|
|
@@ -789,55 +888,125 @@ export class UI {
|
|
|
789
888
|
const padTo = (t, n) => t + ' '.repeat(Math.max(0, n - width(plain(t))))
|
|
790
889
|
const pick = m.pick
|
|
791
890
|
const choices = pick ? m.items.filter((x) => !x.header) : []
|
|
792
|
-
const cards = pick
|
|
891
|
+
const cards = this.#cards(pick)
|
|
892
|
+
const own = pick?.items.some((x) => x.own) // typing goes into "Something else", not a filter
|
|
893
|
+
const typingOwn = m.items[m.sel]?.item?.own && m.items[m.sel].item.text // ←/→ move in what's typed; Tab goes on
|
|
793
894
|
const body = pick?.body ? String(pick.body).split('\n') : []
|
|
794
|
-
const hint = (pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ?
|
|
895
|
+
const hint = (pick?.nav ? (typingOwn ? 'Tab questions · ' : '←→ questions · ') : '') + (pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? `↑↓ move · Space tick · Alt+A/N all/none · Enter take · Esc cancel · ${own ? 'type your own' : 'type to filter'}` : `↑↓ move · Enter choose · Esc cancel${own ? ' · type your own' : cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel')
|
|
896
|
+
const timer = this.autoLine() // on its own line, so it's seen (and not cut off with the keys)
|
|
897
|
+
const long = width(title) > this.#dialogBox(cols, rows).w - 6 // too long for the border: inside instead, said once
|
|
898
|
+
// at most n rows; the rest said to be there
|
|
899
|
+
const clip = (lines, n) => (lines.length <= n ? lines : [...lines.slice(0, Math.max(0, n - 1)), c.faint(`↓ ${lines.length - n + 1} more lines`)])
|
|
900
|
+
// text on at most n rows of w, the last ending in "…" when there's more
|
|
901
|
+
const rowsOf = (t, w, n) => {
|
|
902
|
+
const r = wrapWords(t, w)
|
|
903
|
+
return r.length <= n ? r : [...r.slice(0, n - 1), `${fit(r[n - 1], w - 1)}…`]
|
|
904
|
+
}
|
|
795
905
|
let at = 0
|
|
796
|
-
const long = (w) => width(title) > w // too long for the border: all of it inside too
|
|
797
906
|
return {
|
|
798
|
-
title: title.length > 200 ?
|
|
799
|
-
cursor: (w) => (pick?.fixed || (cards && pick) ? null : { row: at, col: field(w).col }),
|
|
907
|
+
title: long || title.length > 200 ? '' : title,
|
|
908
|
+
cursor: (w) => (pick?.fixed || (cards && pick) || own ? null : { row: at, col: field(w).col }),
|
|
800
909
|
lines: (w, h) => {
|
|
801
|
-
const
|
|
802
|
-
const
|
|
803
|
-
const
|
|
910
|
+
const rule = c.ghost('─'.repeat(w))
|
|
911
|
+
const head = long ? [...wrapWords(c.bright(c.bold(title.slice(0, 1000))), w), ''] : []
|
|
912
|
+
const text = body.flatMap((l) => wrapHang(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
|
|
913
|
+
const intro = [...(pick?.tabs ? [...wrapAnsi(c.text(pick.tabs), w), ''] : []), ...head, ...text, ...(text.length ? [''] : [])]
|
|
914
|
+
const keys = wrapParts(hint, w).map((r) => c.faint(r))
|
|
804
915
|
if (!pick) {
|
|
805
|
-
const
|
|
806
|
-
const
|
|
916
|
+
const shown = clip(intro, h - 2 - keys.length)
|
|
917
|
+
const recent = this.askAbout ? this.#recent(w, Math.min(8, h - shown.length - 4 - keys.length), title) : []
|
|
918
|
+
const top = [...recent, ...(recent.length ? [rule, ''] : []), ...shown]
|
|
807
919
|
at = top.length
|
|
808
|
-
return [...top, field(w).text, '',
|
|
920
|
+
return [...top, field(w).text, '', ...keys]
|
|
809
921
|
}
|
|
922
|
+
const filter = pick.fixed || cards || own ? [] : [field(w).text, rule]
|
|
923
|
+
const tail = ['', ...(timer ? wrapParts(timer, w).map((r) => c.warn(r)) : []), ...keys]
|
|
924
|
+
// the cards: each its rows (a long name on two, a description on up to three), a gap between
|
|
925
|
+
const blocks = !cards
|
|
926
|
+
? []
|
|
927
|
+
: choices.map((x, i) => {
|
|
928
|
+
const on = m.items[m.sel] === x
|
|
929
|
+
const name = rowsOf(x.item.label, w - 2, 2).map((r, k) => (k ? ' ' : on ? `${c.brand('❯')} ` : ' ') + (on ? c.bright(c.bold(r)) : c.text(r)))
|
|
930
|
+
const desc = x.item.desc ? rowsOf(String(x.item.desc), w - 2, 3).map((r) => ` ${on ? c.muted(r) : c.faint(r)}`) : []
|
|
931
|
+
const rows = [...name, ...desc].map((r) => (on ? c.select(padTo(r, w)) : r))
|
|
932
|
+
return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows
|
|
933
|
+
})
|
|
934
|
+
const want = cards ? blocks.flat().length : Math.max(1, m.items.length)
|
|
935
|
+
const least = Math.min(want, cards ? Math.max(...blocks.map((b) => b.length)) + 2 : 3) // the choices give way first, down to this
|
|
936
|
+
const top0 = clip(intro, Math.max(3, h - tail.length - filter.length - least))
|
|
937
|
+
const room = Math.max(1, h - tail.length - filter.length - top0.length)
|
|
810
938
|
let list
|
|
811
|
-
if (
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
939
|
+
if (!choices.length) list = [c.faint(`nothing matches "${rl.line}"`)]
|
|
940
|
+
else if (!cards) list = this.#menuLines(w, Math.max(1, Math.min(room - (m.items.length > room ? 1 : 0), m.items.length))).slice(1)
|
|
941
|
+
else if (blocks.flat().length <= room) list = blocks.flat()
|
|
942
|
+
else {
|
|
943
|
+
// not all of them fit: the chosen one and those around it, with how many more above and below
|
|
944
|
+
let [a, b] = [Math.max(0, choices.findIndex((x) => m.items[m.sel] === x)), 0]
|
|
945
|
+
b = a + 1
|
|
946
|
+
const size = (a, b) => blocks.slice(a, b).flat().length + (a > 0) + (b < blocks.length)
|
|
947
|
+
for (;;) {
|
|
948
|
+
if (b < blocks.length && size(a, b + 1) <= room) b++
|
|
949
|
+
else if (a > 0 && size(a - 1, b) <= room) a--
|
|
950
|
+
else break
|
|
951
|
+
}
|
|
952
|
+
const up = a ? [c.faint(`↑ ${a} more`)] : []
|
|
953
|
+
const down = b < blocks.length ? [c.faint(`↓ ${blocks.length - b} more`)] : []
|
|
954
|
+
list = [...up, ...blocks.slice(a, b).flat().slice(0, Math.max(1, room - up.length - down.length)), ...down]
|
|
821
955
|
}
|
|
822
|
-
const
|
|
823
|
-
const
|
|
824
|
-
if (!cards) list = m.items.length ? this.#menuLines(w, Math.max(1, Math.min(room - (m.items.length > room ? 1 : 0), m.items.length))).slice(1) : [c.faint(`nothing matches "${rl.line}"`)]
|
|
825
|
-
const recent = this.askAbout ? this.#recent(w, Math.min(8, room - list.length - 1)) : []
|
|
826
|
-
const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
|
|
956
|
+
const recent = this.askAbout ? this.#recent(w, Math.min(8, h - tail.length - filter.length - top0.length - list.length - 2), title) : []
|
|
957
|
+
const top = [...recent, ...(recent.length ? [rule, ''] : []), ...top0]
|
|
827
958
|
at = top.length
|
|
828
|
-
return [...top, ...filter, ...list,
|
|
959
|
+
return [...top, ...filter, ...list, ...tail]
|
|
829
960
|
},
|
|
830
961
|
}
|
|
831
962
|
}
|
|
832
963
|
|
|
833
|
-
// The
|
|
834
|
-
|
|
964
|
+
// The plan (todo list) while it works, kept in sight under the spinner: how much is done, what's
|
|
965
|
+
// being done, what's left. Long ones: the finished folded into a count, the open ones up to 8.
|
|
966
|
+
#todoLines(cols) {
|
|
967
|
+
const todos = this.todos?.() ?? []
|
|
968
|
+
const open = todos.filter((t) => t.status !== 'completed')
|
|
969
|
+
if (!open.length) return []
|
|
970
|
+
const done = todos.length - open.length
|
|
971
|
+
const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑') }
|
|
972
|
+
const line = (t) => fit(` ${mark[t.status]} ${t.status === 'in_progress' ? c.info(c.bold(t.content)) : t.status === 'completed' ? c.faint(t.content) : c.muted(t.content)}`, cols)
|
|
973
|
+
const shown = todos.length <= 8 ? todos : open.slice(0, 7)
|
|
974
|
+
return [
|
|
975
|
+
fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
|
|
976
|
+
...(todos.length > 8 && done ? [fit(` ${c.faint(`☑ ${done} done`)}`, cols)] : []),
|
|
977
|
+
...shown.map(line),
|
|
978
|
+
...(open.length > shown.filter((t) => t.status !== 'completed').length ? [fit(` ${c.faint(`… ${open.length - 7} more`)}`, cols)] : []),
|
|
979
|
+
]
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// The last lines of this task's output, at most n rows of w (what a question in the middle of the work
|
|
983
|
+
// is about): whole lines, from the start of a block (not mid-sentence), without what the question
|
|
984
|
+
// itself says (about: its text, e.g. the command it asks to run).
|
|
985
|
+
#recent(w, n, about = '') {
|
|
835
986
|
if (n <= 0) return []
|
|
836
|
-
const
|
|
987
|
+
const flat = (t) => t.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s+/g, ' ').trim().toLowerCase()
|
|
988
|
+
const said = flat(about)
|
|
837
989
|
const from = Math.max(0, (this.inputMark ?? 0) + 1) // this task's: from after your message
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
990
|
+
const got = [] // [{ i, rows }]
|
|
991
|
+
let used = 0
|
|
992
|
+
let cut = false
|
|
993
|
+
for (let i = this.log.length - 1; i >= from; i--) {
|
|
994
|
+
const t = flat(this.log[i]).replace(/^[^\w\s]{1,2} /, '')
|
|
995
|
+
if (t.length >= 8 && said.includes(t)) continue // already in the question
|
|
996
|
+
const rows = wrapHang(this.log[i], w)
|
|
997
|
+
if (used + rows.length > n) {
|
|
998
|
+
cut = true
|
|
999
|
+
break
|
|
1000
|
+
}
|
|
1001
|
+
got.unshift({ i, rows })
|
|
1002
|
+
used += rows.length
|
|
1003
|
+
}
|
|
1004
|
+
// cut short: from the first line that starts a block (after a blank line, or not indented)
|
|
1005
|
+
const start = cut ? got.findIndex((g) => !flat(this.log[g.i - 1] ?? '') || /^\S/.test(plainOf(this.log[g.i]))) : 0
|
|
1006
|
+
const out = got.slice(Math.max(0, start)).flatMap((g) => g.rows)
|
|
1007
|
+
while (out.length && !plainOf(out[0]).trim()) out.shift()
|
|
1008
|
+
while (out.length && !plainOf(out.at(-1)).trim()) out.pop()
|
|
1009
|
+
return out
|
|
841
1010
|
}
|
|
842
1011
|
|
|
843
1012
|
// One model reply: thinking (dim, its own block) kept apart from the answer.
|
|
@@ -862,10 +1031,11 @@ export class UI {
|
|
|
862
1031
|
return {
|
|
863
1032
|
think: (t) => {
|
|
864
1033
|
if (!t || text) return
|
|
1034
|
+
this.tokenAt = Date.now() // it answers: no longer "waiting for" it
|
|
865
1035
|
thought += t
|
|
866
1036
|
if (!this.showThinking && !think) {
|
|
867
1037
|
this.thinkTail = thought.slice(-4000) // its last two lines, live (render)
|
|
868
|
-
return this.spinner(
|
|
1038
|
+
return this.spinner('thinking') // the time: in the line under it (and "thought for" after)
|
|
869
1039
|
}
|
|
870
1040
|
if (!think) {
|
|
871
1041
|
this.thinkTail = ''
|
|
@@ -880,7 +1050,9 @@ export class UI {
|
|
|
880
1050
|
},
|
|
881
1051
|
text: (t) => {
|
|
882
1052
|
if (!t) return
|
|
1053
|
+
this.tokenAt = Date.now()
|
|
883
1054
|
if (!text) {
|
|
1055
|
+
if (this.label === 'thinking') this.label = 'answering'
|
|
884
1056
|
think?.end()
|
|
885
1057
|
this.gap()
|
|
886
1058
|
summary()
|
|
@@ -936,7 +1108,7 @@ export class UI {
|
|
|
936
1108
|
// mouse: HeartCode takes the mouse (the wheel scrolls the conversation, dragging copies); off,
|
|
937
1109
|
// the terminal keeps it, so text is selected and copied the terminal's own way (over SSH too).
|
|
938
1110
|
fullscreen({ mouse = false } = {}) {
|
|
939
|
-
if (this.full || !(this.input.isTTY && this.out.isTTY)) return
|
|
1111
|
+
if (this.full || !(this.input.isTTY && this.out.isTTY) || process.env.TERM === 'dumb') return
|
|
940
1112
|
this.full = true
|
|
941
1113
|
this.mouseOn = mouse ? MOUSE_ON : ''
|
|
942
1114
|
// alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
|
|
@@ -1156,7 +1328,7 @@ export class UI {
|
|
|
1156
1328
|
const out = []
|
|
1157
1329
|
this.log.forEach((line, i) => {
|
|
1158
1330
|
const w = this.wrapped[i]
|
|
1159
|
-
if (!w || w.src !== line) this.wrapped[i] = { src: line, rows:
|
|
1331
|
+
if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapHang(line, cols) } // at spaces, wrapped rows under the text
|
|
1160
1332
|
out.push(...this.wrapped[i].rows)
|
|
1161
1333
|
})
|
|
1162
1334
|
return out
|
|
@@ -1184,23 +1356,33 @@ export class UI {
|
|
|
1184
1356
|
const below = [hiddenBelow ? note(hiddenBelow, '↓') : rule, ...(statusText ? statusText.split('\n').map((l) => fit(' ' + l, cols)) : [])]
|
|
1185
1357
|
const bottom = []
|
|
1186
1358
|
if (this.timer && !this.asking) {
|
|
1187
|
-
// the spinner on its own line
|
|
1359
|
+
// the spinner on its own line, one status: the model not answering yet (since this request went),
|
|
1360
|
+
// else what's being done; the time in all (and Esc) on the next, on more lines when it doesn't fit
|
|
1188
1361
|
const request = this.requestSince?.()
|
|
1189
|
-
const
|
|
1362
|
+
const label = this.#label()
|
|
1363
|
+
const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined
|
|
1364
|
+
const status = waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'} ${short(Date.now() - request)}` : label
|
|
1365
|
+
const timer = this.busySince ? [this.beforeRetry !== undefined && 'no answer yet', `${short(this.worked())} in all`, 'Esc to stop', this.thinkTail && 'Alt+O shows all thinking'].filter(Boolean).join(' · ') : ''
|
|
1190
1366
|
if (this.thinkTail) {
|
|
1191
1367
|
// the thinking's last two lines (long ones wrapped), dim, changing as it comes
|
|
1192
1368
|
const w = Math.max(20, cols - 6)
|
|
1193
1369
|
const lines = this.thinkTail.split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap((l) => l.match(new RegExp(`.{1,${w}}(\\s|$)|.{${w}}`, 'g')) ?? [l]).map((l) => l.trim()).filter(Boolean)
|
|
1194
1370
|
for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
|
|
1195
1371
|
}
|
|
1196
|
-
bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(
|
|
1197
|
-
if (timer) bottom.push(fit(` ${c.faint(
|
|
1372
|
+
bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
|
|
1373
|
+
if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
|
|
1374
|
+
// helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
|
|
1375
|
+
const helpers = [...this.helpers]
|
|
1376
|
+
for (const [name, what] of helpers.slice(0, helpers.length > 6 ? 5 : 6)) bottom.push(fit(` ${c.faint('◦')} ${c.muted(name)}${what ? c.faint(` · ${what}`) : ''}`, cols))
|
|
1377
|
+
if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
|
|
1378
|
+
bottom.push(...this.#todoLines(cols))
|
|
1198
1379
|
}
|
|
1199
1380
|
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`))
|
|
1200
1381
|
if (this.ahead.length) {
|
|
1201
1382
|
const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
|
|
1202
1383
|
const sep = c.ghost(' · ')
|
|
1203
|
-
|
|
1384
|
+
const queued = `${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[key('Alt+S', 'send first now'), key('Alt+A', 'send all now'), key('Alt+M', 'change when done')].join(sep)}`
|
|
1385
|
+
bottom.push(...wrapParts(queued, cols - 2, sep).map((r) => fit(` ${r}`, cols))) // on more lines, not cut
|
|
1204
1386
|
for (const [i, l] of this.ahead.slice(0, 5).entries()) bottom.push(fit(` ${c.accent(`${i + 1}.`)} ${c.muted(l.replace(/\s+/g, ' '))}`, cols))
|
|
1205
1387
|
if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
|
|
1206
1388
|
}
|
|
@@ -1223,7 +1405,7 @@ export class UI {
|
|
|
1223
1405
|
for (let i = Math.max(0, s.row - top); i <= Math.min(view.length - 1, e.row - top); i++) view[i] = highlight(view[i], top + i === s.row ? s.col : 0, top + i === e.row ? e.col + 1 : Infinity)
|
|
1224
1406
|
}
|
|
1225
1407
|
// a theme with a background: every row painted with it (a style ending its own background goes back to it)
|
|
1226
|
-
let row = background ? (line) => `${background}${line
|
|
1408
|
+
let row = background ? (line) => `${background}${foreground}${paintBg(line)}\x1b[K\x1b[0m` : (line) => `${line}\x1b[0m\x1b[K`
|
|
1227
1409
|
let s = '\x1b[?25l'
|
|
1228
1410
|
// a dialog open: everything behind it dimmed
|
|
1229
1411
|
if (this.dialog || asked) {
|
|
@@ -1260,7 +1442,7 @@ export class UI {
|
|
|
1260
1442
|
let cursor
|
|
1261
1443
|
if (this.dialog || asked) {
|
|
1262
1444
|
this.regions = new Map()
|
|
1263
|
-
const [box, cur] = this.#drawDialog(cols, rows, this.dialog ? { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) } : this.#question())
|
|
1445
|
+
const [box, cur] = this.#drawDialog(cols, rows, this.dialog ? { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) } : this.#question(cols, rows))
|
|
1264
1446
|
s += box
|
|
1265
1447
|
cursor = cur // a question: its cursor in the box; else hidden
|
|
1266
1448
|
} else {
|
|
@@ -1328,7 +1510,8 @@ export class UI {
|
|
|
1328
1510
|
// and not in a menu or a mid-task yes/no question, where Space types a space as usual)
|
|
1329
1511
|
if (key.name === 'space' && !this.rl.line && !this.menu.pick && !(this.asking && !this.histOn) && this.voiceReady()) return this.#action('voice', write)
|
|
1330
1512
|
if (!this.asking && !(key.ctrl && key.name === 'c')) return this.#typeAhead(s, key, write)
|
|
1331
|
-
|
|
1513
|
+
// Shift+Tab: the mode at the prompt only; never while a question is open (between questions: the one before)
|
|
1514
|
+
if (key.name === 'tab' && key.shift && !this.menu.pick?.nav) return this.histOn ? this.cyclePermission() : undefined
|
|
1332
1515
|
// A new line instead of sending: Shift/Ctrl/Alt/Cmd+Enter (arrive as "\n" or ESC+Enter),
|
|
1333
1516
|
// Ctrl+J, "\" right before Enter, and line breaks inside a paste.
|
|
1334
1517
|
if (key.name === 'paste-start' || key.name === 'paste-end') {
|
|
@@ -1361,6 +1544,7 @@ export class UI {
|
|
|
1361
1544
|
const twice = key.sequence === '\x1b\x1b' || Date.now() - (this.lastEscape ?? 0) < 800 // a lone Esc also comes with meta set
|
|
1362
1545
|
this.lastEscape = twice ? 0 : Date.now()
|
|
1363
1546
|
if (twice) {
|
|
1547
|
+
this.remember(rl.line) // wiped, not lost: ↑ brings it back
|
|
1364
1548
|
this.clearInput()
|
|
1365
1549
|
return this.refreshMenu()
|
|
1366
1550
|
}
|
|
@@ -1378,6 +1562,25 @@ export class UI {
|
|
|
1378
1562
|
return
|
|
1379
1563
|
}
|
|
1380
1564
|
if (m.pick) {
|
|
1565
|
+
// an answer of their own (ask_user's "Something else"): what's typed goes into it, right there
|
|
1566
|
+
const own = m.pick.items.find((x) => x.own)
|
|
1567
|
+
const onOwn = own && it?.item === own
|
|
1568
|
+
const typing = own && !key.ctrl && !key.meta && ((key.name === 'backspace' && onOwn) || (/^[^\x00-\x1f\x7f]+$/.test(s ?? '') && !(key.name === 'space' && m.pick.multi && !onOwn)))
|
|
1569
|
+
if (typing) {
|
|
1570
|
+
own.hint ??= own.text ? 'type your own answer' : own.desc // what it says before anything's typed
|
|
1571
|
+
own.text = key.name === 'backspace' ? (own.text ?? '').slice(0, -1) : (own.text ?? '') + s
|
|
1572
|
+
own.desc = own.text ? `› ${own.text}▏` : own.hint
|
|
1573
|
+
if (m.pick.multi) own.checked = Boolean(own.text)
|
|
1574
|
+
m.sel = m.items.findIndex((x) => x.item === own)
|
|
1575
|
+
return this.refreshMenu()
|
|
1576
|
+
}
|
|
1577
|
+
if (onOwn && own.text && (key.name === 'left' || key.name === 'right')) return // typing: not to another question (Tab still goes)
|
|
1578
|
+
if (onOwn && key.name === 'return' && !own.text?.trim() && !m.pick.multi) return // nothing typed yet: type it here
|
|
1579
|
+
// between questions (ask_user with several): what's ticked stays ticked
|
|
1580
|
+
if (m.pick.nav && !rl.line && (key.name === 'left' || key.name === 'right' || key.name === 'tab')) {
|
|
1581
|
+
m.pick.chosen = { nav: key.name === 'left' || (key.name === 'tab' && key.shift) ? -1 : 1 }
|
|
1582
|
+
return write('\r', { name: 'return' })
|
|
1583
|
+
}
|
|
1381
1584
|
if (key.name === 'up' || key.name === 'down') return this.#move(key.name === 'up' ? -1 : 1)
|
|
1382
1585
|
if (key.name === 'tab') return
|
|
1383
1586
|
if (m.pick.multi && key.name === 'space' && it && !it.item.only) {
|
|
@@ -1392,6 +1595,7 @@ export class UI {
|
|
|
1392
1595
|
return write('\r', { name: 'return' })
|
|
1393
1596
|
}
|
|
1394
1597
|
if (key.name === 'return') return // nothing matches the filter
|
|
1598
|
+
if (!own && this.#cards(m.pick)) return // cards have no filter: typing into one nobody sees would hide them all
|
|
1395
1599
|
write(s, key)
|
|
1396
1600
|
return this.refreshMenu()
|
|
1397
1601
|
}
|
|
@@ -1451,7 +1655,7 @@ export class UI {
|
|
|
1451
1655
|
if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
|
|
1452
1656
|
return this.escStop()
|
|
1453
1657
|
}
|
|
1454
|
-
if (key.name === 'tab' && key.shift) return this.
|
|
1658
|
+
if (key.name === 'tab' && key.shift) return this.cyclePermission()
|
|
1455
1659
|
if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
|
|
1456
1660
|
if (it && (key.name === 'up' || key.name === 'down')) {
|
|
1457
1661
|
m.sel = (m.sel + (key.name === 'up' ? m.items.length - 1 : 1)) % m.items.length
|
|
@@ -1513,7 +1717,7 @@ export class UI {
|
|
|
1513
1717
|
case 'stop':
|
|
1514
1718
|
return this.asking ? undefined : this.onEscape?.()
|
|
1515
1719
|
case 'cycle_permissions':
|
|
1516
|
-
return this.
|
|
1720
|
+
return this.asking && !this.histOn ? undefined : this.cyclePermission() // not while a question is open
|
|
1517
1721
|
case 'newline':
|
|
1518
1722
|
rl.line = rl.line.slice(0, rl.cursor) + '\n' + rl.line.slice(rl.cursor)
|
|
1519
1723
|
rl.cursor++
|
|
@@ -1734,7 +1938,9 @@ export class UI {
|
|
|
1734
1938
|
const w = Math.min(Math.max(0, ...shown.filter((x) => !x.header).map((x) => x.value.length)), 48)
|
|
1735
1939
|
const lines = shown.map((x, i) => {
|
|
1736
1940
|
if (x.header) return c.accent(c.bold(x.value.slice(0, width)))
|
|
1737
|
-
const
|
|
1941
|
+
const full = `${x.value.padEnd(w)} ${x.desc ?? ''}`.trimEnd()
|
|
1942
|
+
const room = width - 2 - pad.length
|
|
1943
|
+
const plain = full.length > room ? `${full.slice(0, room - 1)}…` : full // cut: said so
|
|
1738
1944
|
const name = plain.slice(0, w)
|
|
1739
1945
|
if (first + i !== m.sel) return `${pad} ${c.text(name)}${c.faint(plain.slice(w))}`
|
|
1740
1946
|
const row = `${c.brand('❯')} ${c.bright(c.bold(name))}${c.muted(plain.slice(w))}`
|
|
@@ -1824,13 +2030,14 @@ export class UI {
|
|
|
1824
2030
|
|
|
1825
2031
|
// history: this prompt's messages go into ↑/↓ history (only the main prompt, never answers like keys).
|
|
1826
2032
|
// One question on screen at a time: a command run beside a task (onNow) and the task can both ask.
|
|
2033
|
+
// A question also waits for voice being recorded to end (its words go where they were going).
|
|
1827
2034
|
async #free() {
|
|
1828
|
-
while (this.full && this.asking) await new Promise((r) => this.freed.push(r))
|
|
2035
|
+
while ((this.full && this.asking) || this.recording) await new Promise((r) => (this.recording ? setTimeout(r, 200) : this.freed.push(r)))
|
|
1829
2036
|
}
|
|
1830
2037
|
|
|
1831
2038
|
ask(prompt, { initial = '', suggest = false, history = false } = {}) {
|
|
1832
2039
|
if (this.dialog && !history) this.setDialog(null) // a question (a permission, a picker) needs you: the dialog makes way
|
|
1833
|
-
if (this.full && this.asking) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
|
|
2040
|
+
if (this.full && (this.asking || (this.recording && !history))) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
|
|
1834
2041
|
if (history && this.kept) [initial, this.kept] = [initial || this.kept, ''] // typed before a submit()
|
|
1835
2042
|
this.stopSpin()
|
|
1836
2043
|
const rl = this.#rl()
|
|
@@ -1849,6 +2056,8 @@ export class UI {
|
|
|
1849
2056
|
}
|
|
1850
2057
|
// a question in the middle of work: what's being typed for later waits until it's answered
|
|
1851
2058
|
const draft = !history && rl.line ? [rl.line, (rl.line = ''), (rl.cursor = 0)][0] : ''
|
|
2059
|
+
// piped input: its lines are messages, not answers; nobody's there to answer
|
|
2060
|
+
if (!history && !rl.terminal) return this.write(prompt + c.dim('(no answer: the input is not a terminal)') + '\n'), Promise.resolve(null)
|
|
1852
2061
|
if (this.queue.length) {
|
|
1853
2062
|
const l = this.queue.shift()
|
|
1854
2063
|
log('input', `${prompt.trim()} ${/api key/i.test(prompt) && l ? `${l.slice(0, 4)}…(${l.length} chars)` : l}`) // never log keys
|
|
@@ -1889,11 +2098,12 @@ export class UI {
|
|
|
1889
2098
|
const pick = this.menu.pick
|
|
1890
2099
|
const echo = prompt.replace(/^ /, '') // the input's margin isn't part of the conversation
|
|
1891
2100
|
this.inputMark = this.log.length - 1 // where this message starts, for /rewind
|
|
1892
|
-
const
|
|
2101
|
+
const said = (x) => (x.own && x.text?.trim() ? x.text.trim() : x.label) // their own answer: what they typed
|
|
2102
|
+
const picked = Array.isArray(pick?.chosen) ? pick.chosen.map(said).join(', ') : pick?.chosen && said(pick.chosen)
|
|
1893
2103
|
if (pick?.quiet) this.render()
|
|
1894
|
-
else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: the recommended one`) : '') + '\n')
|
|
2104
|
+
else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: ${pick.auto.fired === 'theirs' ? 'yours' : 'the recommended one'}`) : '') + '\n')
|
|
1895
2105
|
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)
|
|
1896
|
-
else if (l
|
|
2106
|
+
else if (l?.trim()) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
|
|
1897
2107
|
else this.render()
|
|
1898
2108
|
}
|
|
1899
2109
|
if (draft) [rl.line, rl.cursor] = [draft, draft.length]
|
|
@@ -1915,17 +2125,20 @@ export class UI {
|
|
|
1915
2125
|
// quiet: the question and answer aren't left in the conversation (a question before it starts).
|
|
1916
2126
|
// fixed: a dialog: no typing to filter, no other keys meanwhile.
|
|
1917
2127
|
// auto: { item, secs }: nobody answers for secs seconds (each key starts the wait again) → item is chosen.
|
|
1918
|
-
|
|
2128
|
+
// tabs: a row of tabs above it (several questions); nav: ←/→ (Tab, Shift+Tab) close it with { nav: -1 | 1 }.
|
|
2129
|
+
async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '', auto = null, tabs = '', nav = false } = {}) {
|
|
1919
2130
|
if (!this.full) {
|
|
1920
2131
|
items.forEach((it, i) => this.print(` ${i + 1}. ${it.group ? `${it.group} · ` : ''}${it.label}${it.desc ? ' ' + c.dim(it.desc) : ''}`))
|
|
1921
2132
|
const a = await this.ask(`${title} ${c.dim(multi ? '(numbers, like 1,3)' : '(number)')}: `)
|
|
2133
|
+
this.autoPicked = a === null && Boolean(auto) && !this.rl.terminal && 'nobody' // piped input: nobody's there to answer, so the recommended one (Esc stays no answer)
|
|
2134
|
+
if (this.autoPicked) return multi ? [auto.item] : auto.item
|
|
1922
2135
|
if (!multi) return items[Number(a) - 1] ?? null
|
|
1923
2136
|
const chosen = String(a ?? '').split(/[\s,]+/).map((n) => items[Number(n) - 1]).filter(Boolean)
|
|
1924
2137
|
return chosen.length ? chosen : null
|
|
1925
2138
|
}
|
|
1926
2139
|
await this.#free()
|
|
1927
2140
|
if (multi) for (const it of items) if (!it.only) it.checked ??= false
|
|
1928
|
-
this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, auto: auto && { ...auto } }
|
|
2141
|
+
this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, tabs, nav, auto: auto && { ...auto } }
|
|
1929
2142
|
this.autoPicked = false // chosen for the user (nobody answered in time), for the caller to say so
|
|
1930
2143
|
if (auto) {
|
|
1931
2144
|
this.#armAuto()
|
|
@@ -1949,8 +2162,11 @@ export class UI {
|
|
|
1949
2162
|
a.timer = setTimeout(() => {
|
|
1950
2163
|
const pick = this.menu.pick
|
|
1951
2164
|
if (pick?.auto !== a) return
|
|
1952
|
-
|
|
1953
|
-
|
|
2165
|
+
if (this.out.hidden) return this.#armAuto() // a tab in the background: you haven't seen it yet
|
|
2166
|
+
const ticked = pick.items.filter((x) => x.checked)
|
|
2167
|
+
const typed = pick.items.find((x) => x.own && x.text?.trim()) // their own answer, typed but not sent
|
|
2168
|
+
a.fired = this.autoPicked = (pick.multi ? ticked.length : typed) ? 'theirs' : true
|
|
2169
|
+
pick.chosen = pick.multi ? (ticked.length ? ticked : [a.item]) : (typed ?? a.item)
|
|
1954
2170
|
this.rl.line = ''
|
|
1955
2171
|
this.rl.cursor = 0
|
|
1956
2172
|
this.ttyWrite('\r', { name: 'return' })
|
|
@@ -1958,19 +2174,41 @@ export class UI {
|
|
|
1958
2174
|
this.render()
|
|
1959
2175
|
}
|
|
1960
2176
|
|
|
2177
|
+
// A tab comes on screen: its question's wait starts now.
|
|
2178
|
+
resumeAuto() {
|
|
2179
|
+
if (this.menu.pick?.auto) this.#armAuto()
|
|
2180
|
+
}
|
|
2181
|
+
|
|
1961
2182
|
autoHint() {
|
|
1962
2183
|
const a = this.menu.pick?.auto
|
|
1963
2184
|
return a ? ` · recommended in ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s` : ''
|
|
1964
2185
|
}
|
|
1965
2186
|
|
|
2187
|
+
// A pick that chooses by itself (auto): how long until it does, and what it will do then.
|
|
2188
|
+
autoLine() {
|
|
2189
|
+
const pick = this.menu.pick
|
|
2190
|
+
const a = pick?.auto
|
|
2191
|
+
if (!a) return ''
|
|
2192
|
+
const theirs = pick.items.some((x) => x.checked || (x.own && x.text?.trim())) // ticked or typed: that's what goes
|
|
2193
|
+
return `◷ ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s · then ${theirs ? 'yours is sent' : (a.say ?? 'the recommended answer is chosen')} · a key restarts it`
|
|
2194
|
+
}
|
|
2195
|
+
|
|
1966
2196
|
setPermission(mode) {
|
|
1967
2197
|
log('permissions', mode)
|
|
1968
2198
|
if (mode === 'plan' && this.permission !== 'plan') this.beforePlan = this.permission // what plan mode asks like, and goes back to
|
|
2199
|
+
this.leftPlan = null
|
|
1969
2200
|
this.permission = mode
|
|
1970
2201
|
this.onPermission?.(mode)
|
|
1971
2202
|
this.render()
|
|
1972
2203
|
}
|
|
1973
2204
|
|
|
2205
|
+
// Shift+Tab: the next mode; plan goes back to the mode before it, and the next press goes on after plan.
|
|
2206
|
+
cyclePermission() {
|
|
2207
|
+
if (this.permission === 'plan' && this.beforePlan && this.beforePlan !== 'plan') return this.setPermission(this.beforePlan), (this.leftPlan = this.beforePlan)
|
|
2208
|
+
const at = this.leftPlan === this.permission ? 'plan' : this.permission
|
|
2209
|
+
this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === at) + 1) % PERMISSIONS.length][0])
|
|
2210
|
+
}
|
|
2211
|
+
|
|
1974
2212
|
// kind: 'edit', 'command' or 'read'. true = yes, false = no, string = "no, and here is why"
|
|
1975
2213
|
// kind 'read' (web search and fetch): asked like a command, but never in plan mode, which is for
|
|
1976
2214
|
// looking around. Otherwise plan mode asks as the mode before it did (only reading tools get here).
|
|
@@ -1987,6 +2225,7 @@ export class UI {
|
|
|
1987
2225
|
}
|
|
1988
2226
|
}
|
|
1989
2227
|
const a = await this.ask(`${c.yellow('?')} ${question} ${c.dim('[Y/n or type feedback]')} `)
|
|
2228
|
+
if (a === null && !this.rl.terminal) return `Not allowed: HeartCode's input is not a terminal, so nobody can approve this. Don't retry it; say in your reply what you would have done.`
|
|
1990
2229
|
if (a === null) return false
|
|
1991
2230
|
const t = a.trim()
|
|
1992
2231
|
if (/^(y|yes)?$/i.test(t)) return true
|
|
@@ -1998,12 +2237,13 @@ export class UI {
|
|
|
1998
2237
|
{ label: 'Yes', value: true },
|
|
1999
2238
|
{ label: "Yes, and don't ask again", value: 'all' },
|
|
2000
2239
|
{ label: 'No', value: false },
|
|
2001
|
-
{ label: 'No, and tell the model what to do instead', value: 'why' },
|
|
2240
|
+
{ label: 'No, and tell the model what to do instead', desc: 'type it here', value: 'why', own: true }, // typed in its row, as ask_user's "Something else"
|
|
2002
2241
|
]
|
|
2003
|
-
const
|
|
2004
|
-
|
|
2242
|
+
const got = await this.pick(`${c.yellow('?')} ${question}`, opts)
|
|
2243
|
+
const a = got?.value ?? false
|
|
2244
|
+
if (a === 'all') this.permission === 'plan' ? (this.beforePlan = 'all') : this.setPermission('all') // plan mode stays: it goes on to 'all' afterwards
|
|
2005
2245
|
if (a !== 'why') return Boolean(a)
|
|
2006
|
-
return
|
|
2246
|
+
return got.text?.trim() || false
|
|
2007
2247
|
}
|
|
2008
2248
|
|
|
2009
2249
|
write(s) {
|
|
@@ -2041,7 +2281,7 @@ export class UI {
|
|
|
2041
2281
|
Object.assign(this, { tail: m.tail, sgr: m.sgr })
|
|
2042
2282
|
const lines = text ? text.split('\n') : []
|
|
2043
2283
|
if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
|
|
2044
|
-
else if (lines.length) this.showText(title, text)
|
|
2284
|
+
else if (lines.length) this.showText(title === '/toggle_thinking' ? 'Thinking' : title, text, title) // its key (Alt+O) closes it again
|
|
2045
2285
|
else this.render()
|
|
2046
2286
|
}
|
|
2047
2287
|
// A blank line before a new block, unless there already is one.
|
|
@@ -2066,6 +2306,7 @@ export class UI {
|
|
|
2066
2306
|
|
|
2067
2307
|
spinner(label) {
|
|
2068
2308
|
this.label = label
|
|
2309
|
+
if (this.requestSince?.()) this.tokenAt = Date.now() // changed during a request: something came (a tool call being written)
|
|
2069
2310
|
if (!this.out.isTTY || this.timer) return
|
|
2070
2311
|
let i = 0
|
|
2071
2312
|
const tick = () => {
|
|
@@ -2091,10 +2332,12 @@ export class UI {
|
|
|
2091
2332
|
}
|
|
2092
2333
|
this.beforeRetry ??= typeof this.label === 'function' ? 'thinking' : this.label || 'thinking'
|
|
2093
2334
|
const until = Date.now() + ms
|
|
2094
|
-
|
|
2335
|
+
// why first, short: "cannot reach http://127.0.0.1:47329/v1/chat/completions (ECONNREFUSED)" → "can't reach 127.0.0.1:47329"
|
|
2336
|
+
let why = shortError(err).replace(/^cannot reach (\S+)(?: \([^)]*\))?/, (m, u) => `can't reach ${URL.canParse(u) ? new URL(u).host : u}`)
|
|
2337
|
+
if (why.length > 50) why = `${why.slice(0, 49)}…`
|
|
2095
2338
|
const left = () => Math.max(0, Math.ceil((until - Date.now()) / 1000)) * 1000
|
|
2096
|
-
if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${
|
|
2097
|
-
this.spinner(() => `${c.yellow('⚠')} retrying in ${
|
|
2339
|
+
if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${short(left())} (all failed once)` : ''} (try ${attempt})`)
|
|
2340
|
+
this.spinner(() => `${c.yellow('⚠')} ${why} · retrying in ${short(left())} (try ${attempt})`)
|
|
2098
2341
|
}
|
|
2099
2342
|
|
|
2100
2343
|
stopSpin() {
|