@hncode/hncode 0.8.1 → 0.8.3

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.
Files changed (52) hide show
  1. package/README.md +18 -0
  2. package/README_CN.md +14 -0
  3. package/bin/hncode +54 -8
  4. package/package.json +1 -1
  5. package/src/agent-task.js +356 -337
  6. package/src/agent.js +1465 -1405
  7. package/src/animate.js +56 -0
  8. package/src/colors.js +615 -593
  9. package/src/config.js +50 -7
  10. package/src/context-bar.js +280 -278
  11. package/src/doctor.js +4 -3
  12. package/src/file-tree.js +4 -3
  13. package/src/highlight.js +20 -6
  14. package/src/i18n.js +1432 -389
  15. package/src/image-row.js +11 -2
  16. package/src/index.js +218 -6
  17. package/src/keybindings.js +2 -1
  18. package/src/llm.js +146 -21
  19. package/src/log-file.js +112 -0
  20. package/src/markdown.js +646 -567
  21. package/src/mcp-server.js +409 -0
  22. package/src/mcp.js +279 -29
  23. package/src/memory-profile.js +19 -16
  24. package/src/migrate-index.js +175 -0
  25. package/src/migrate.js +392 -0
  26. package/src/panels.js +9 -7
  27. package/src/plan.js +7 -5
  28. package/src/plugin.js +37 -21
  29. package/src/registry-browser.js +17 -15
  30. package/src/rows-plan-bg.js +3 -2
  31. package/src/rows-status.js +20 -6
  32. package/src/rows-tool-result.js +242 -208
  33. package/src/screen-paint.js +153 -128
  34. package/src/session-recover.js +317 -0
  35. package/src/session.js +203 -13
  36. package/src/settings-schema.js +9 -0
  37. package/src/swarm-progress.js +6 -2
  38. package/src/tasks-browser.js +37 -36
  39. package/src/team-panel.js +12 -11
  40. package/src/term.js +57 -21
  41. package/src/text.js +254 -149
  42. package/src/tool-line.js +7 -2
  43. package/src/tool-result.js +400 -327
  44. package/src/tools/agent.js +7 -2
  45. package/src/tools/ask-user-question.js +1 -2
  46. package/src/tools/bash.js +446 -434
  47. package/src/tools/edit.js +653 -665
  48. package/src/tools/goal.js +130 -93
  49. package/src/tools/read.js +141 -133
  50. package/src/tools/tasks.js +214 -214
  51. package/src/tools/utils.js +143 -104
  52. package/src/tui.js +20887 -19942
package/src/markdown.js CHANGED
@@ -1,567 +1,646 @@
1
- // Markdown → ANSI rows.
2
- //
3
- // One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
4
- // hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
5
- //
6
- // The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
7
- // lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
8
- // same rows as a whole-document render, which is the property the cache depends on.
9
-
10
- import { C } from './colors.js';
11
- import { renderLatex } from './latex.js';
12
- import { measureTex, encodeTexImage, TEX_MAX_ROWS } from './tex/index.js';
13
- import { render as renderMermaid, sourceBox as mermaidSourceBox, toAnsi as mermaidAnsi } from './mermaid/index.js';
14
- import { encodeImageRow } from './image-row.js';
15
- import { terminalCaps } from './term-caps.js';
16
- import { col, visualCol, wrapWords } from './text.js';
17
-
18
- /**
19
- * Version of the markdown renderer, part of the incremental cache key.
20
- *
21
- * That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer itself now produces
22
- * different rows for the same input. A session that cached a block before a fence type learned to draw kept showing
23
- * the old output, so the change looked like it had not shipped. Bump this whenever what `renderMdText` produces for
24
- * the same input changes.
25
- */
26
- export const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
27
-
28
- /**
29
- * Render a growing markdown text, re-rendering only the last block.
30
- *
31
- * @param {object} msg carries `_mdCache` between calls
32
- * @param {string} text
33
- * @param {number} width
34
- * @param {string} fg body colour
35
- * @param {string} codeFg inline-code colour
36
- * @returns {{headRows: string[], tailRows: string[], headCut: number}}
37
- */
38
- export function renderMdIncremental(msg, text, width, fg, codeFg) {
39
- const src = text.replace(/\r\n/g, '\n');
40
- let c = msg._mdCache;
41
- // Layout identity: same width/colours and the same text. Comparing the text (not just its length) is required — a
42
- // same-length replacement must re-render.
43
- if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
44
- return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
45
- }
46
- if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
47
- c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
48
- }
49
-
50
- const parts = splitBlocks(src);
51
- // A block is final once a LATER block exists; the last one is still growing.
52
- const headCount = Math.max(0, parts.length - 1);
53
- // THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text, width and
54
- // colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`, but it leaves `c`
55
- // untouched (its width and colours still match), and this reuse test then finds the block texts identical and hands
56
- // back the old rows.
57
- const canReuse = c.v === MD_RENDER_VERSION
58
- && Array.isArray(c.blocks)
59
- && Array.isArray(c.blockTexts)
60
- && c.blockTexts.length >= headCount
61
- && parts.length >= headCount
62
- && c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
63
-
64
- const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
65
- const headRows = [];
66
- for (const b of blocks) for (const r of b) headRows.push(r);
67
- const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
68
- const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
69
-
70
- msg._mdCache = {
71
- v: MD_RENDER_VERSION,
72
- text: src, width, fg, codeFg,
73
- blocks, blockTexts: parts.slice(0, headCount),
74
- headRows, tailRows, headCut,
75
- };
76
- return { headRows, tailRows, headCut };
77
- }
78
-
79
- /**
80
- * Split at blank lines OUTSIDE a fence.
81
- *
82
- * The blank line(s) begin the NEXT block, so every block renders the same whether or not later blocks exist — that is
83
- * the property the incremental cache depends on.
84
- */
85
- export function splitBlocks(src) {
86
- if (src === '') return [''];
87
- const lines = src.split('\n');
88
- const out = [];
89
- let cur = [];
90
- let fence = false;
91
- for (const ln of lines) {
92
- const isFence = /^\s*(```+|~~~+)/.test(ln);
93
- const blank = ln.trim() === '';
94
- if (blank && !fence) {
95
- if (cur.length) { out.push(cur); cur = []; }
96
- cur.push(ln);
97
- continue;
98
- }
99
- if (isFence) fence = !fence;
100
- cur.push(ln);
101
- }
102
- if (cur.length) out.push(cur);
103
- return out.map((b) => b.join('\n'));
104
- }
105
-
106
- /** Render a whole markdown document to painted rows. */
107
- export function renderMdText(text, width, fg, codeFg) {
108
- const src = String(text).replace(/\r\n/g, '\n');
109
- const para = src.split('\n');
110
- const out = [];
111
- let i = 0;
112
- const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
113
- const splitCells = (l) => {
114
- const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
115
- return s.split('|').map((c) => c.trim());
116
- };
117
-
118
- while (i < para.length) {
119
- const line = para[i];
120
- const t = line.replace(/\s+$/, '');
121
- // DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
122
- //
123
- // A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`. It is laid out
124
- // here as the formula it describes — stacked fractions, limits above a sum — and its source is what remains when
125
- // the subset cannot express it, exactly as a math fence behaves. The opener has to start the line and the closer
126
- // has to end one, so `cost is $$x$$ total` stays prose and is handled as inline math by the line renderer below.
127
- const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
128
- if (mathOpen) {
129
- const open = mathOpen[1];
130
- const close = open === '$$' ? '$$' : '\\]';
131
- const after = t.slice(mathOpen.index + mathOpen[0].length);
132
- let body = null;
133
- let used = 0;
134
- let closed = true;
135
- // One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
136
- const oneLine = after.indexOf(close);
137
- if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
138
- body = after.slice(0, oneLine);
139
- used = 1;
140
- } else if (after.trim() === '') {
141
- // Multi-line form: everything up to the line that ends with the closer.
142
- const collected = [];
143
- let k = i + 1;
144
- let found = false;
145
- while (k < para.length) {
146
- const cl = para[k].replace(/\s+$/, '');
147
- if (cl.trimEnd().endsWith(close)) {
148
- collected.push(cl.slice(0, cl.lastIndexOf(close)));
149
- k++;
150
- found = true;
151
- break;
152
- }
153
- collected.push(para[k]);
154
- k++;
155
- }
156
- body = collected.join('\n');
157
- used = k - i;
158
- // Still streaming: no closer yet, so the body is prose plus half a formula.
159
- closed = found;
160
- }
161
- if (body !== null && closed) {
162
- i += used;
163
- // Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
164
- const rows = mathBlockRows(body, width, true);
165
- if (rows) {
166
- out.push(...rows);
167
- } else {
168
- // Unsupported: show the TeX so the reader still gets the formula's meaning.
169
- for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
170
- }
171
- continue;
172
- }
173
- }
174
- // Fenced code block. Rendered with a rule ABOVE (labelled with the language) and a matching full-width rule BELOW,
175
- // so the block is visibly delimited.
176
- const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
177
- if (fm) {
178
- const lang = fm[2] || '';
179
- i++;
180
- const buf = [];
181
- const fenceChar = fm[1][0];
182
- const fenceLen = fm[1].length;
183
- const isCloser = (s) => {
184
- const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
185
- return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
186
- };
187
- while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
188
- // Whether the closing fence was actually reached: an open fence means the text is still streaming.
189
- const fenceClosed = i < para.length;
190
- i++; // closing fence (no-op when the fence is still open)
191
- const rule = (s) => col(s, C.gray);
192
- // MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula it
193
- // describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather than as
194
- // flattened Unicode.
195
- //
196
- // Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the picture
197
- // cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset cannot express
198
- // the TeX at all.
199
- if (/^(latex|tex|math)$/i.test(lang)) {
200
- const tex = buf.join('\n').trim();
201
- const rendered = mathBlockRows(tex, width, fenceClosed);
202
- if (rendered) {
203
- out.push(...rendered);
204
- continue;
205
- }
206
- // Falls through to the plain code block: the source is all we have.
207
- }
208
- if (/^mermaid$/i.test(lang)) {
209
- const diagramSrc = buf.join('\n');
210
- let art = null;
211
- try { art = renderMermaid(diagramSrc); } catch { art = null; }
212
- // Wider than the panel: the frame is the honest answer, since truncating art would cut a box in half rather
213
- // than say the diagram does not fit.
214
- if (art && art.width <= width) {
215
- // `toAnsi` keeps the role of every span, so the frame stays dim and the connectors cyan instead of the
216
- // whole diagram arriving as plain white text.
217
- const coloured = mermaidAnsi(art);
218
- for (const l of coloured) out.push(l);
219
- continue;
220
- }
221
- try {
222
- for (const l of mermaidSourceBox(diagramSrc, width).plain) out.push(col(l, C.white));
223
- continue;
224
- } catch { /* fall through to the plain code block */ }
225
- }
226
- // Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
227
- if (lang) {
228
- const head = `\u2500 ${lang} `;
229
- out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
230
- } else {
231
- out.push(rule('─'.repeat(Math.max(1, width))));
232
- }
233
- // Fenced code block CONTENT is plain body text — the default terminal colour, not the theme's cyan. The cyan is
234
- // reserved for UI chrome and the language label; a large code block in cyan reads as "everything is the theme
235
- // colour".
236
- for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
237
- // Closing rule, matching the opening one.
238
- out.push(rule('─'.repeat(Math.max(1, width))));
239
- continue;
240
- }
241
- // Table: a header line followed by a separator line
242
- if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
243
- const header = splitCells(t);
244
- const sep = splitCells(para[i + 1]);
245
- const body = [];
246
- i += 2;
247
- while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
248
- renderTable(out, header, body, sep.length, width, fg);
249
- continue;
250
- }
251
- // Fall through to single-line renderer
252
- const rows = markdownLineToRows(t, width, fg, codeFg, false);
253
- out.push(...rows);
254
- i++;
255
- }
256
- return out;
257
- }
258
-
259
- /** Render a Markdown table as aligned columns. Header bolded, rows readable. */
260
- export function renderTable(out, header, body, colCount, width, fg) {
261
- const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
262
- const B = C.border;
263
- const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
264
- // Per-column natural width (visual columns), reserving 2 padding each side.
265
- const natural = Array.from({ length: cols }, (_, c) => {
266
- let m = 0;
267
- const consider = (v) => { m = Math.max(m, visualCol(v)); };
268
- consider(val(header, c));
269
- for (const r of body) consider(val(r, c));
270
- return m;
271
- });
272
- // Cap total table width to the available width (minus borders).
273
- const availInner = Math.max(cols, width - (cols + 1));
274
- const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
275
- let widths;
276
- if (totalNatural <= availInner) {
277
- widths = natural;
278
- } else {
279
- // Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
280
- // unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
281
- const MIN_COL = 4;
282
- const over = totalNatural - availInner;
283
- const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
284
- widths = natural.map((n) => {
285
- const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
286
- return Math.max(Math.min(MIN_COL, n), n - shrink);
287
- });
288
- }
289
- // WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which pushed
290
- // every border after it to the right and broke the table's alignment for the rest of the row. The row now grows
291
- // taller: each cell is wrapped to its column, and every line is padded to the same width.
292
- const wrapCell = (text, w) => {
293
- if (!text) return [''];
294
- return wrapWords(text, Math.max(1, w));
295
- };
296
- // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
297
- // asterisks and backticks verbatim, which is not what the author wrote.
298
- const styled = (text, w, bold) => {
299
- const plain = wrapCell(text, w);
300
- const paint = bold ? C.white + C.bold : C.gray;
301
- return plain.map((lineText) => {
302
- // Render the markdown FIRST, then pad the RESULT.
303
- //
304
- // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
305
- // characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
306
- // the column short by two and every border after it moved left.
307
- const md = inlineMarkdown(lineText, C.gray, bold ? C.white : C.gray);
308
- const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
309
- const pad = Math.max(0, w - printed);
310
- return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
311
- });
312
- };
313
- const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
314
- // One logical row, as several physical lines when any cell wraps.
315
- const oneRow = (cells, bold) => {
316
- const rendered = [];
317
- for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
318
- const height = Math.max(1, ...rendered.map((r) => r.length));
319
- for (let lineIdx = 0; lineIdx < height; lineIdx++) {
320
- const parts = rendered.map((r, c) => (r[lineIdx] !== undefined
321
- ? r[lineIdx]
322
- : col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
323
- out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
324
- }
325
- };
326
- out.push(rule('╭', '┬', '╮'));
327
- oneRow(header, true);
328
- out.push(rule('├', '┼', '┤'));
329
- for (const r of body) oneRow(r, false);
330
- out.push(rule('╰', '┴', '╯'));
331
- }
332
-
333
- /** One line of markdown to rows: headings, rules, quotes, lists, then inline styles. */
334
- export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
335
- const out = [];
336
- const t = line.replace(/\s+$/, '');
337
-
338
- // Headings: `# Title`
339
- let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
340
- if (m && !isContinuation) {
341
- const hashCount = m[2].length;
342
- // h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
343
- const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
344
- for (const w of wrapWords(m[3], width)) {
345
- out.push(col(w, size));
346
- }
347
- return out;
348
- }
349
- // Thematic break
350
- if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
351
- out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
352
- return out;
353
- }
354
- // Blockquote
355
- //
356
- // THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct block
357
- // in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own voice.
358
- // Colouring both the same made a quote indistinguishable from an indented paragraph.
359
- if (/^\s*>\s?/.test(t)) {
360
- const content = t.replace(/^\s*>\s?/, '');
361
- for (const w of wrapWords(content, Math.max(1, width - 2))) {
362
- out.push(col('▍ ', C.cyan) + col(w, C.comment));
363
- }
364
- return out;
365
- }
366
- // Unordered/ordered list — bold the bullet, keep content plain. Also handles task checkboxes.
367
- {
368
- const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
369
- if (task && !isContinuation) {
370
- const checked = task[3] !== ' ';
371
- const box = checked ? col('✓', C.green) : col('○', C.gray);
372
- const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
373
- for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
374
- out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
375
- }
376
- return out;
377
- }
378
- const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
379
- if (li && !isContinuation) {
380
- const isOrdered = /^\d/.test(li[2]);
381
- const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
382
- const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
383
- let first = true;
384
- for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
385
- out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
386
- first = false;
387
- }
388
- return out;
389
- }
390
- }
391
- // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
392
- if (/[*`\[$]|\\\(/.test(t)) {
393
- for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
394
- return out;
395
- }
396
- // Plain - apply default foreground color
397
- for (const w of wrapWords(t, width)) out.push(col(w, fg));
398
- return out;
399
- }
400
-
401
- /**
402
- * Whether the terminal can receive a formula as a picture.
403
- *
404
- * Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported (XTWINOPS 16).
405
- * Without the cell size the picture would be measured in guessed cells, which is what put a formula on the wrong rows
406
- * before — so a missing cell size falls back to text rather than guess.
407
- */
408
- export function mathImageCapable() {
409
- const caps = terminalCaps();
410
- if (!caps) return null;
411
- // KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far better: the
412
- // pixels are uploaded once and every later frame is a placement, while a Sixel has to be retransmitted and moves the
413
- // cursor when it is drawn.
414
- const protocol = caps.kittyGraphics
415
- ? 'kitty'
416
- : (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
417
- if (!protocol) return null;
418
- const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
419
- return cell ? { protocol, cell } : null;
420
- }
421
-
422
- /** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
423
- export const MATH_INK = { r: 220, g: 220, b: 220 };
424
-
425
- /**
426
- * The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
427
- *
428
- * A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and the image
429
- * is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and matches the
430
- * fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
431
- */
432
- export function mathCellHeight() {
433
- const caps = terminalCaps();
434
- const cell = caps && caps.cell;
435
- return cell && cell.h > 0 ? cell.h : 20;
436
- }
437
-
438
- /**
439
- * Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it cannot,
440
- * and nothing when the TeX is outside the subset (the caller then shows the source).
441
- *
442
- * @param {string} tex TeX without delimiters.
443
- * @param {number} width Columns available.
444
- * @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a picture of
445
- * half a formula is worse than the TeX of half a formula.
446
- * @returns {string[]|null}
447
- */
448
- export function mathBlockRows(tex, width, closed) {
449
- const src = stripMathDelimiters(tex);
450
- if (!src) return null;
451
- // A picture sits where the text form does: one column of indent, and no wider than the panel.
452
- const room = Math.max(8, width - 2);
453
- if (closed) {
454
- const placed = placeTex(src, room);
455
- if (placed) return placed;
456
- }
457
- const rendered = renderLatex(src, { display: true });
458
- if (rendered === undefined) return null;
459
- return rendered
460
- .split('\n')
461
- .map((l) => col(l.slice(0, width), C.white));
462
- }
463
-
464
- /**
465
- * Remove the delimiters a formula may still be wrapped in.
466
- *
467
- * A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the delimiters too
468
- * — a model writes the fence around `$$…$$` often enough that it is the common case, not the odd one. Typesetting the
469
- * delimiters along with the formula draws them as glyphs inside the picture.
470
- *
471
- * Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and stripping it
472
- * would change the formula. The loop runs because a doubled wrapper leaves one pair behind after the first pass.
473
- */
474
- export function stripMathDelimiters(tex) {
475
- let s = String(tex || '').trim();
476
- for (;;) {
477
- const before = s;
478
- if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
479
- s = s.slice(2, -2).trim();
480
- } else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
481
- s = s.slice(2, -2).trim();
482
- } else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
483
- s = s.slice(2, -2).trim();
484
- }
485
- if (s === before) return s;
486
- }
487
- }
488
-
489
- /**
490
- * Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
491
- *
492
- * The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the rows below it
493
- * are blank, and the frame writer turns them into a cursor move and a graphics sequence. Every reason to decline is a
494
- * reason the caller already has a text fallback for, so this never throws.
495
- */
496
- export function placeTex(tex, room) {
497
- const capable = mathImageCapable();
498
- if (!capable) return null;
499
- try {
500
- // Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for and then
501
- // thrown away.
502
- const measured = measureTex(tex, { cell: capable.cell });
503
- if (!measured || measured.columns > room || measured.rows > TEX_MAX_ROWS) return null;
504
- const image = encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
505
- if (!image) return null;
506
- // THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from its first
507
- // VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only land on a six-pixel
508
- // band boundary, which leaves up to a quarter of a cell of the formula above the window and makes it slide as the
509
- // view scrolls. The frame writer reads this back and re-renders with `skipTop` when a picture needs cropping.
510
- const rows = [encodeImageRow(image.sequence, image.rows, image.columns, tex)];
511
- for (let r = 1; r < image.rows; r++) rows.push('');
512
- return rows;
513
- } catch {
514
- // A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
515
- return null;
516
- }
517
- }
518
-
519
- /**
520
- * Whether a `$...$` body is a formula rather than prose.
521
- *
522
- * Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that starts or
523
- * ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX command and no operator
524
- * in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
525
- */
526
- export function looksLikeInlineMath(body) {
527
- if (/^\s/.test(body) || /\s$/.test(body)) return false;
528
- if (body.startsWith('{') || body.includes('`')) return false;
529
- if (/^\d+([.,]\d+)?$/.test(body)) return false;
530
- if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
531
- return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
532
- }
533
-
534
- /**
535
- * Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~, [text](url).
536
- *
537
- * Order matters so inner tokens are handled safely. `base` is the surrounding foreground colour; every inline style
538
- * re-asserts it after its own reset, otherwise the bare `\e[0m` would cancel the base colour for the REST of the line
539
- * — plain text after a **bold** run used to lose its colour and fall back to the terminal default.
540
- */
541
- export function inlineMarkdown(s, codeFg, base) {
542
- const fb = base || '';
543
- let r = s;
544
- // Inline code first so it is not mangled by * [] ~.
545
- r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
546
- // INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so `*` and `_`
547
- // inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
548
- r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
549
- const tex = dollar !== undefined ? dollar : paren;
550
- // A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
551
- if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
552
- const out = renderLatex(tex, { display: false });
553
- // Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
554
- if (out === undefined || out.includes('\n')) return m;
555
- return out;
556
- });
557
- // Bold
558
- r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
559
- // Strikethrough
560
- r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
561
- // Italic
562
- r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
563
- // Links: [text](url) -> text (cyan); autolink bare http(s) urls
564
- r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
565
- r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
566
- return r;
567
- }
1
+ // Markdown → ANSI rows.
2
+ //
3
+ // One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
4
+ // hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
5
+ //
6
+ // The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
7
+ // lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
8
+ // same rows as a whole-document render, which is the property the cache depends on.
9
+
10
+ import { C } from './colors.js';
11
+ import { renderLatex } from './latex.js';
12
+ // THE TYPESETTER IS LOADED WHEN A PICTURE IS ACTUALLY NEEDED.
13
+ //
14
+ // `measureTex` / `encodeTexImage` pull in the whole TeX layout, metrics and raster pipeline: 21ms of module evaluation,
15
+ // which every session paid before the first frame — for a feature that (a) most replies do not use and (b) is skipped
16
+ // entirely when the terminal cannot show a bitmap. `placeTex` returns early in that case, so the common path never
17
+ // needs these at all.
18
+ //
19
+ // ESM has no synchronous require, so the first formula draws as its Unicode layout and the bitmap appears from the next
20
+ // frame. Asking for a picture twice to get it once is better than every startup paying for it.
21
+ let texMod = null;
22
+ let texLoading = null;
23
+ function loadTex() {
24
+ if (texMod) return texMod;
25
+ if (!texLoading) {
26
+ texLoading = import('./tex/index.js')
27
+ .then((m) => { texMod = m; return m; })
28
+ .catch(() => { texLoading = null; return null; });
29
+ }
30
+ return null;
31
+ }
32
+ import { encodeImageRow } from './image-row.js';
33
+ import { terminalCaps } from './term-caps.js';
34
+ import { col, visualCol, wrapWords, wrapStyled } from './text.js';
35
+
36
+ /**
37
+ * Mermaid is loaded on first use, not at import.
38
+ *
39
+ * It costs ~54ms of module evaluation — the largest single item behind `latex` and `tui` — and it is only needed to draw
40
+ * a ```mermaid fence, which most sessions never contain. On a weak machine that is a visible slice of the blank screen
41
+ * before the first frame, paid for a feature the session may not use at all.
42
+ *
43
+ * `require`-style sync loading is not available in ESM, so the first mermaid block renders as its SOURCE and kicks off
44
+ * the load; the next frame draws the diagram. A diagram appearing one frame late is not something a reader notices,
45
+ * and it is strictly better than every session paying for it up front.
46
+ */
47
+ let mermaidMod = null;
48
+ let mermaidLoading = null;
49
+
50
+ // The repaint hook. The renderer is PURE — it draws and returns — so it cannot ask for a
51
+ // frame itself, and without asking the diagram never appears: the first frame draws the
52
+ // source, the module finishes loading a moment later, and nothing repaints, so the source
53
+ // stays on screen for the rest of the session.
54
+ //
55
+ // The TUI registers its own repaint here at startup. A caller that does not care (a test,
56
+ // a headless render) simply never sees the diagram and keeps the source, which is the
57
+ // honest fallback.
58
+ let mermaidReady = null;
59
+
60
+ /** Ask to be repainted when the mermaid module finishes loading. */
61
+ export function onMermaidReady(fn) {
62
+ mermaidReady = typeof fn === 'function' ? fn : null;
63
+ }
64
+
65
+ function loadMermaid() {
66
+ if (mermaidMod) return mermaidMod;
67
+ if (!mermaidLoading) {
68
+ mermaidLoading = import('./mermaid/index.js')
69
+ .then((m) => {
70
+ mermaidMod = m;
71
+ // The diagram is drawable now. Repaint, or the source stays on screen forever.
72
+ if (mermaidReady) { try { mermaidReady(); } catch { /* a repaint is not worth failing for */ } }
73
+ return m;
74
+ })
75
+ .catch(() => { mermaidLoading = null; return null; });
76
+ }
77
+ return null; // not ready yet; the caller falls back to the source this frame
78
+ }
79
+
80
+ /**
81
+ * Version of the markdown renderer, part of the incremental cache key.
82
+ *
83
+ * That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer itself now produces
84
+ * different rows for the same input. A session that cached a block before a fence type learned to draw kept showing
85
+ * the old output, so the change looked like it had not shipped. Bump this whenever what `renderMdText` produces for
86
+ * the same input changes.
87
+ */
88
+ export const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
89
+
90
+ /**
91
+ * Render a growing markdown text, re-rendering only the last block.
92
+ *
93
+ * @param {object} msg carries `_mdCache` between calls
94
+ * @param {string} text
95
+ * @param {number} width
96
+ * @param {string} fg body colour
97
+ * @param {string} codeFg inline-code colour
98
+ * @returns {{headRows: string[], tailRows: string[], headCut: number}}
99
+ */
100
+ export function renderMdIncremental(msg, text, width, fg, codeFg) {
101
+ const src = text.replace(/\r\n/g, '\n');
102
+ let c = msg._mdCache;
103
+ // Layout identity: same width/colours and the same text. Comparing the text (not just its length) is required — a
104
+ // same-length replacement must re-render.
105
+ if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
106
+ return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
107
+ }
108
+ if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
109
+ c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
110
+ }
111
+
112
+ const parts = splitBlocks(src);
113
+ // A block is final once a LATER block exists; the last one is still growing.
114
+ const headCount = Math.max(0, parts.length - 1);
115
+ // THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text, width and
116
+ // colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`, but it leaves `c`
117
+ // untouched (its width and colours still match), and this reuse test then finds the block texts identical and hands
118
+ // back the old rows.
119
+ const canReuse = c.v === MD_RENDER_VERSION
120
+ && Array.isArray(c.blocks)
121
+ && Array.isArray(c.blockTexts)
122
+ && c.blockTexts.length >= headCount
123
+ && parts.length >= headCount
124
+ && c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
125
+
126
+ const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
127
+ const headRows = [];
128
+ for (const b of blocks) for (const r of b) headRows.push(r);
129
+ const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
130
+ const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
131
+
132
+ msg._mdCache = {
133
+ v: MD_RENDER_VERSION,
134
+ text: src, width, fg, codeFg,
135
+ blocks, blockTexts: parts.slice(0, headCount),
136
+ headRows, tailRows, headCut,
137
+ };
138
+ return { headRows, tailRows, headCut };
139
+ }
140
+
141
+ /**
142
+ * Split at blank lines OUTSIDE a fence.
143
+ *
144
+ * The blank line(s) begin the NEXT block, so every block renders the same whether or not later blocks exist — that is
145
+ * the property the incremental cache depends on.
146
+ */
147
+ export function splitBlocks(src) {
148
+ if (src === '') return [''];
149
+ const lines = src.split('\n');
150
+ const out = [];
151
+ let cur = [];
152
+ let fence = false;
153
+ for (const ln of lines) {
154
+ const isFence = /^\s*(```+|~~~+)/.test(ln);
155
+ const blank = ln.trim() === '';
156
+ if (blank && !fence) {
157
+ if (cur.length) { out.push(cur); cur = []; }
158
+ cur.push(ln);
159
+ continue;
160
+ }
161
+ if (isFence) fence = !fence;
162
+ cur.push(ln);
163
+ }
164
+ if (cur.length) out.push(cur);
165
+ return out.map((b) => b.join('\n'));
166
+ }
167
+
168
+ /** Render a whole markdown document to painted rows. */
169
+ export function renderMdText(text, width, fg, codeFg) {
170
+ const src = String(text).replace(/\r\n/g, '\n');
171
+ const para = src.split('\n');
172
+ const out = [];
173
+ let i = 0;
174
+ const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
175
+ const splitCells = (l) => {
176
+ const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
177
+ return s.split('|').map((c) => c.trim());
178
+ };
179
+
180
+ while (i < para.length) {
181
+ const line = para[i];
182
+ const t = line.replace(/\s+$/, '');
183
+ // DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
184
+ //
185
+ // A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`. It is laid out
186
+ // here as the formula it describes — stacked fractions, limits above a sum — and its source is what remains when
187
+ // the subset cannot express it, exactly as a math fence behaves. The opener has to start the line and the closer
188
+ // has to end one, so `cost is $$x$$ total` stays prose and is handled as inline math by the line renderer below.
189
+ const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
190
+ if (mathOpen) {
191
+ const open = mathOpen[1];
192
+ const close = open === '$$' ? '$$' : '\\]';
193
+ const after = t.slice(mathOpen.index + mathOpen[0].length);
194
+ let body = null;
195
+ let used = 0;
196
+ let closed = true;
197
+ // One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
198
+ const oneLine = after.indexOf(close);
199
+ if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
200
+ body = after.slice(0, oneLine);
201
+ used = 1;
202
+ } else if (after.trim() === '') {
203
+ // Multi-line form: everything up to the line that ends with the closer.
204
+ const collected = [];
205
+ let k = i + 1;
206
+ let found = false;
207
+ while (k < para.length) {
208
+ const cl = para[k].replace(/\s+$/, '');
209
+ if (cl.trimEnd().endsWith(close)) {
210
+ collected.push(cl.slice(0, cl.lastIndexOf(close)));
211
+ k++;
212
+ found = true;
213
+ break;
214
+ }
215
+ collected.push(para[k]);
216
+ k++;
217
+ }
218
+ body = collected.join('\n');
219
+ used = k - i;
220
+ // Still streaming: no closer yet, so the body is prose plus half a formula.
221
+ closed = found;
222
+ }
223
+ if (body !== null && closed) {
224
+ i += used;
225
+ // Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
226
+ const rows = mathBlockRows(body, width, true);
227
+ if (rows) {
228
+ out.push(...rows);
229
+ } else {
230
+ // Unsupported: show the TeX so the reader still gets the formula's meaning.
231
+ for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
232
+ }
233
+ continue;
234
+ }
235
+ }
236
+ // Fenced code block. Rendered with a rule ABOVE (labelled with the language) and a matching full-width rule BELOW,
237
+ // so the block is visibly delimited.
238
+ const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
239
+ if (fm) {
240
+ const lang = fm[2] || '';
241
+ i++;
242
+ const buf = [];
243
+ const fenceChar = fm[1][0];
244
+ const fenceLen = fm[1].length;
245
+ const isCloser = (s) => {
246
+ const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
247
+ return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
248
+ };
249
+ while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
250
+ // Whether the closing fence was actually reached: an open fence means the text is still streaming.
251
+ const fenceClosed = i < para.length;
252
+ i++; // closing fence (no-op when the fence is still open)
253
+ const rule = (s) => col(s, C.gray);
254
+ // MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula it
255
+ // describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather than as
256
+ // flattened Unicode.
257
+ //
258
+ // Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the picture
259
+ // cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset cannot express
260
+ // the TeX at all.
261
+ if (/^(latex|tex|math)$/i.test(lang)) {
262
+ const tex = buf.join('\n').trim();
263
+ const rendered = mathBlockRows(tex, width, fenceClosed);
264
+ if (rendered) {
265
+ out.push(...rendered);
266
+ continue;
267
+ }
268
+ // Falls through to the plain code block: the source is all we have.
269
+ }
270
+ if (/^mermaid$/i.test(lang)) {
271
+ const diagramSrc = buf.join('\n');
272
+ // The module is fetched on the first mermaid block and draws from the NEXT frame; until then the source box is
273
+ // what the reader sees, which is the same fallback used when a diagram does not fit.
274
+ const mm = loadMermaid();
275
+ if (mm) {
276
+ let art = null;
277
+ try { art = mm.render(diagramSrc); } catch { art = null; }
278
+ // Wider than the panel: the frame is the honest answer, since truncating art would cut a box in half rather
279
+ // than say the diagram does not fit.
280
+ if (art && art.width <= width) {
281
+ // `toAnsi` keeps the role of every span, so the frame stays dim and the connectors cyan instead of the
282
+ // whole diagram arriving as plain white text.
283
+ const coloured = mm.toAnsi(art);
284
+ for (const l of coloured) out.push(l);
285
+ continue;
286
+ }
287
+ }
288
+ try {
289
+ if (mm) {
290
+ for (const l of mm.sourceBox(diagramSrc, width).plain) out.push(col(l, C.white));
291
+ continue;
292
+ }
293
+ } catch { /* fall through to the plain code block */ }
294
+ }
295
+ // Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
296
+ if (lang) {
297
+ const head = `\u2500 ${lang} `;
298
+ out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
299
+ } else {
300
+ out.push(rule('─'.repeat(Math.max(1, width))));
301
+ }
302
+ // Fenced code block CONTENT is plain body text — the default terminal colour, not the theme's cyan. The cyan is
303
+ // reserved for UI chrome and the language label; a large code block in cyan reads as "everything is the theme
304
+ // colour".
305
+ for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
306
+ // Closing rule, matching the opening one.
307
+ out.push(rule('─'.repeat(Math.max(1, width))));
308
+ continue;
309
+ }
310
+ // Table: a header line followed by a separator line
311
+ if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
312
+ const header = splitCells(t);
313
+ const sep = splitCells(para[i + 1]);
314
+ const body = [];
315
+ i += 2;
316
+ while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
317
+ renderTable(out, header, body, sep.length, width, fg);
318
+ continue;
319
+ }
320
+ // Fall through to single-line renderer
321
+ const rows = markdownLineToRows(t, width, fg, codeFg, false);
322
+ out.push(...rows);
323
+ i++;
324
+ }
325
+ return out;
326
+ }
327
+
328
+ /** Render a Markdown table as aligned columns. Header bolded, rows readable. */
329
+ export function renderTable(out, header, body, colCount, width, fg) {
330
+ const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
331
+ const B = C.border;
332
+ const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
333
+ // Per-column natural width (visual columns), reserving 2 padding each side.
334
+ const natural = Array.from({ length: cols }, (_, c) => {
335
+ let m = 0;
336
+ const consider = (v) => { m = Math.max(m, visualCol(v)); };
337
+ consider(val(header, c));
338
+ for (const r of body) consider(val(r, c));
339
+ return m;
340
+ });
341
+ // Cap total table width to the available width (minus borders).
342
+ const availInner = Math.max(cols, width - (cols + 1));
343
+ const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
344
+ let widths;
345
+ if (totalNatural <= availInner) {
346
+ widths = natural;
347
+ } else {
348
+ // Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
349
+ // unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
350
+ const MIN_COL = 4;
351
+ const over = totalNatural - availInner;
352
+ const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
353
+ widths = natural.map((n) => {
354
+ const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
355
+ return Math.max(Math.min(MIN_COL, n), n - shrink);
356
+ });
357
+ }
358
+ // WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which pushed
359
+ // every border after it to the right and broke the table's alignment for the rest of the row. The row now grows
360
+ // taller: each cell is wrapped to its column, and every line is padded to the same width.
361
+ const wrapCell = (text, w) => {
362
+ if (!text) return [''];
363
+ return wrapWords(text, Math.max(1, w));
364
+ };
365
+ // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
366
+ // asterisks and backticks verbatim, which is not what the author wrote.
367
+ //
368
+ // RENDER FIRST, WRAP SECOND, for the same reason as the prose renderer: a `**bold**` that
369
+ // straddled a line break matched no pattern and the asterisks were printed as they were
370
+ // written. The wrap is on the RENDERED text, so it measures what the terminal shows.
371
+ const styled = (text, w, bold) => {
372
+ const paint = bold ? C.white + C.bold : C.gray;
373
+ const md = inlineMarkdown(String(text == null ? '' : text), C.gray, bold ? C.white : C.gray);
374
+ return wrapStyled(md, Math.max(1, w)).map((lineText) => {
375
+ // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
376
+ // characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
377
+ // the column short by two and every border after it moved left.
378
+ const printed = visualCol(lineText);
379
+ const pad = Math.max(0, w - printed);
380
+ return col(' ', paint) + col(lineText, paint) + col(' '.repeat(pad) + ' ', paint);
381
+ });
382
+ };
383
+ const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
384
+ // One logical row, as several physical lines when any cell wraps.
385
+ const oneRow = (cells, bold) => {
386
+ const rendered = [];
387
+ for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
388
+ const height = Math.max(1, ...rendered.map((r) => r.length));
389
+ for (let lineIdx = 0; lineIdx < height; lineIdx++) {
390
+ const parts = rendered.map((r, c) => (r[lineIdx] !== undefined
391
+ ? r[lineIdx]
392
+ : col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
393
+ out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
394
+ }
395
+ };
396
+ out.push(rule('╭', '┬', '╮'));
397
+ oneRow(header, true);
398
+ out.push(rule('├', '┼', '┤'));
399
+ for (const r of body) oneRow(r, false);
400
+ out.push(rule('╰', '┴', '╯'));
401
+ }
402
+
403
+ /** One line of markdown to rows: headings, rules, quotes, lists, then inline styles. */
404
+ export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
405
+ const out = [];
406
+ const t = line.replace(/\s+$/, '');
407
+
408
+ // Headings: `# Title`
409
+ let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
410
+ if (m && !isContinuation) {
411
+ const hashCount = m[2].length;
412
+ // h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
413
+ const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
414
+ for (const w of wrapWords(m[3], width)) {
415
+ out.push(col(w, size));
416
+ }
417
+ return out;
418
+ }
419
+ // Thematic break
420
+ if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
421
+ out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
422
+ return out;
423
+ }
424
+ // Blockquote
425
+ //
426
+ // THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct block
427
+ // in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own voice.
428
+ // Colouring both the same made a quote indistinguishable from an indented paragraph.
429
+ if (/^\s*>\s?/.test(t)) {
430
+ const content = t.replace(/^\s*>\s?/, '');
431
+ for (const w of wrapWords(content, Math.max(1, width - 2))) {
432
+ out.push(col('▍ ', C.cyan) + col(w, C.comment));
433
+ }
434
+ return out;
435
+ }
436
+ // Unordered/ordered list — bold the bullet, keep content plain. Also handles task checkboxes.
437
+ {
438
+ const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
439
+ if (task && !isContinuation) {
440
+ const checked = task[3] !== ' ';
441
+ const box = checked ? col('✓', C.green) : col('○', C.gray);
442
+ const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
443
+ for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
444
+ out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
445
+ }
446
+ return out;
447
+ }
448
+ const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
449
+ if (li && !isContinuation) {
450
+ const isOrdered = /^\d/.test(li[2]);
451
+ const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
452
+ const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
453
+ let first = true;
454
+ for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
455
+ out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
456
+ first = false;
457
+ }
458
+ return out;
459
+ }
460
+ }
461
+ // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
462
+ //
463
+ // RENDER FIRST, WRAP SECOND. Wrapping the source broke every marker that straddled a line
464
+ // break: a `**bold**` split across two lines matched no pattern, so the asterisks were
465
+ // printed verbatim — a literal `**` in the middle of a sentence. Rendering first turns the
466
+ // markers into colour, and the wrap then measures what the terminal will show.
467
+ if (/[*`\[$]|\\\(/.test(t)) {
468
+ for (const w of wrapStyled(inlineMarkdown(t, codeFg, fg), width)) out.push(col(w, fg));
469
+ return out;
470
+ }
471
+ // Plain - apply default foreground color
472
+ for (const w of wrapWords(t, width)) out.push(col(w, fg));
473
+ return out;
474
+ }
475
+
476
+ /**
477
+ * Whether the terminal can receive a formula as a picture.
478
+ *
479
+ * Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported (XTWINOPS 16).
480
+ * Without the cell size the picture would be measured in guessed cells, which is what put a formula on the wrong rows
481
+ * before — so a missing cell size falls back to text rather than guess.
482
+ */
483
+ export function mathImageCapable() {
484
+ const caps = terminalCaps();
485
+ if (!caps) return null;
486
+ // KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far better: the
487
+ // pixels are uploaded once and every later frame is a placement, while a Sixel has to be retransmitted and moves the
488
+ // cursor when it is drawn.
489
+ const protocol = caps.kittyGraphics
490
+ ? 'kitty'
491
+ : (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
492
+ if (!protocol) return null;
493
+ const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
494
+ return cell ? { protocol, cell } : null;
495
+ }
496
+
497
+ /** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
498
+ export const MATH_INK = { r: 220, g: 220, b: 220 };
499
+
500
+ /**
501
+ * The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
502
+ *
503
+ * A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and the image
504
+ * is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and matches the
505
+ * fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
506
+ */
507
+ export function mathCellHeight() {
508
+ const caps = terminalCaps();
509
+ const cell = caps && caps.cell;
510
+ return cell && cell.h > 0 ? cell.h : 20;
511
+ }
512
+
513
+ /**
514
+ * Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it cannot,
515
+ * and nothing when the TeX is outside the subset (the caller then shows the source).
516
+ *
517
+ * @param {string} tex TeX without delimiters.
518
+ * @param {number} width Columns available.
519
+ * @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a picture of
520
+ * half a formula is worse than the TeX of half a formula.
521
+ * @returns {string[]|null}
522
+ */
523
+ export function mathBlockRows(tex, width, closed) {
524
+ const src = stripMathDelimiters(tex);
525
+ if (!src) return null;
526
+ // A picture sits where the text form does: one column of indent, and no wider than the panel.
527
+ const room = Math.max(8, width - 2);
528
+ if (closed) {
529
+ const placed = placeTex(src, room);
530
+ if (placed) return placed;
531
+ }
532
+ const rendered = renderLatex(src, { display: true });
533
+ if (rendered === undefined) return null;
534
+ return rendered
535
+ .split('\n')
536
+ .map((l) => col(l.slice(0, width), C.white));
537
+ }
538
+
539
+ /**
540
+ * Remove the delimiters a formula may still be wrapped in.
541
+ *
542
+ * A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the delimiters too
543
+ * — a model writes the fence around `$$…$$` often enough that it is the common case, not the odd one. Typesetting the
544
+ * delimiters along with the formula draws them as glyphs inside the picture.
545
+ *
546
+ * Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and stripping it
547
+ * would change the formula. The loop runs because a doubled wrapper leaves one pair behind after the first pass.
548
+ */
549
+ export function stripMathDelimiters(tex) {
550
+ let s = String(tex || '').trim();
551
+ for (;;) {
552
+ const before = s;
553
+ if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
554
+ s = s.slice(2, -2).trim();
555
+ } else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
556
+ s = s.slice(2, -2).trim();
557
+ } else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
558
+ s = s.slice(2, -2).trim();
559
+ }
560
+ if (s === before) return s;
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
566
+ *
567
+ * The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the rows below it
568
+ * are blank, and the frame writer turns them into a cursor move and a graphics sequence. Every reason to decline is a
569
+ * reason the caller already has a text fallback for, so this never throws.
570
+ */
571
+ export function placeTex(tex, room) {
572
+ const capable = mathImageCapable();
573
+ if (!capable) return null;
574
+ // Loaded on first use — see loadTex. Until it lands the caller draws the Unicode layout, which is the same fallback
575
+ // used when a formula cannot be placed as a picture.
576
+ const T = loadTex();
577
+ if (!T) return null;
578
+ try {
579
+ // Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for and then
580
+ // thrown away.
581
+ const measured = T.measureTex(tex, { cell: capable.cell });
582
+ if (!measured || measured.columns > room || measured.rows > T.TEX_MAX_ROWS) return null;
583
+ const image = T.encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
584
+ if (!image) return null;
585
+ // THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from its first
586
+ // VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only land on a six-pixel
587
+ // band boundary, which leaves up to a quarter of a cell of the formula above the window and makes it slide as the
588
+ // view scrolls. The frame writer reads this back and re-renders with `skipTop` when a picture needs cropping.
589
+ const rows = [encodeImageRow(image.sequence, image.rows, image.columns, tex)];
590
+ for (let r = 1; r < image.rows; r++) rows.push('');
591
+ return rows;
592
+ } catch {
593
+ // A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
594
+ return null;
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Whether a `$...$` body is a formula rather than prose.
600
+ *
601
+ * Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that starts or
602
+ * ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX command and no operator
603
+ * in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
604
+ */
605
+ export function looksLikeInlineMath(body) {
606
+ if (/^\s/.test(body) || /\s$/.test(body)) return false;
607
+ if (body.startsWith('{') || body.includes('`')) return false;
608
+ if (/^\d+([.,]\d+)?$/.test(body)) return false;
609
+ if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
610
+ return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
611
+ }
612
+
613
+ /**
614
+ * Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~, [text](url).
615
+ *
616
+ * Order matters so inner tokens are handled safely. `base` is the surrounding foreground colour; every inline style
617
+ * re-asserts it after its own reset, otherwise the bare `\e[0m` would cancel the base colour for the REST of the line
618
+ * — plain text after a **bold** run used to lose its colour and fall back to the terminal default.
619
+ */
620
+ export function inlineMarkdown(s, codeFg, base) {
621
+ const fb = base || '';
622
+ let r = s;
623
+ // Inline code first so it is not mangled by * [] ~.
624
+ r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
625
+ // INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so `*` and `_`
626
+ // inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
627
+ r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
628
+ const tex = dollar !== undefined ? dollar : paren;
629
+ // A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
630
+ if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
631
+ const out = renderLatex(tex, { display: false });
632
+ // Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
633
+ if (out === undefined || out.includes('\n')) return m;
634
+ return out;
635
+ });
636
+ // Bold
637
+ r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
638
+ // Strikethrough
639
+ r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
640
+ // Italic
641
+ r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
642
+ // Links: [text](url) -> text (cyan); autolink bare http(s) urls
643
+ r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
644
+ r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
645
+ return r;
646
+ }