@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
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { C } from './colors.js';
7
7
  import { col, visualCol, wrapWords } from './text.js';
8
+ import { uiText } from './i18n.js';
8
9
  import { fmtTokens } from './format.js';
9
10
  import { SPIN_PLACEHOLDER } from './animate.js';
10
11
 
@@ -32,15 +33,28 @@ export function compactionRows(msg, width, expanded, spin) {
32
33
  const detail = (msg.tokensBefore != null && msg.tokensAfter != null)
33
34
  ? col(` (${fmtTokens(msg.tokensBefore)} → ${fmtTokens(msg.tokensAfter)} tokens)`, C.gray) : '';
34
35
  const hint = (msg.text || '').trim()
35
- ? col(` (Ctrl-O to ${expanded ? 'hide' : 'show'} compaction summary)`, C.gray) : '';
36
- head = bullet + col('Compaction complete', C.green + C.bold) + detail + hint;
36
+ ? col(uiText(` (Ctrl-O to ${expanded ? 'hide' : 'show'} compaction summary)`), C.gray) : '';
37
+ head = bullet + col(uiText('Compaction complete'), C.green + C.bold) + detail + hint;
37
38
  } else if (canceled) {
38
- head = bullet + col('Compaction cancelled', C.yellow + C.bold)
39
+ head = bullet + col(uiText('Compaction cancelled'), C.yellow + C.bold)
39
40
  + (msg.reason ? col(' (' + msg.reason + ')', C.gray) : '');
40
41
  } else {
41
- head = bullet + col('Compacting context…', C.cyan + C.bold);
42
+ head = bullet + col(uiText('Compacting context…'), C.cyan + C.bold);
42
43
  }
43
44
  const out = [{ text: head, ind: '', raw: true }];
45
+ // WHERE THE EARLIER CONVERSATION WENT.
46
+ //
47
+ // Compaction drops the oldest messages from the model's history AND the oldest rows from the displayed transcript, so
48
+ // a long conversation visibly loses its top. The row above only reported token counts, which reads as "something was
49
+ // deleted". This says what actually happened: the history was summarised, it is still in the session file, and
50
+ // `/recap` reads it back.
51
+ if (done) {
52
+ const trimmed = Number(msg.trimmed) || 0;
53
+ const note = trimmed > 0
54
+ ? uiText(`${trimmed} earlier message${trimmed === 1 ? '' : 's'} left the screen — summarised above, still in the session file (/recap to read it back)`)
55
+ : uiText('the full conversation is still in the session file (/recap to read it back)');
56
+ out.push({ text: INDENT + col(note, C.gray), ind: INDENT, raw: true });
57
+ }
44
58
  if (msg.instruction) {
45
59
  out.push({ text: INDENT + col(String(msg.instruction), C.gray), ind: INDENT, raw: true });
46
60
  }
@@ -90,14 +104,14 @@ export function thinkingRows(msg, width, expanded) {
90
104
  // The spinner frame is NOT baked in here: a glyph that changes every tick would invalidate this row's cache and
91
105
  // re-wrap the whole reasoning block each time, which is what made long thinking look laggy. The caller substitutes
92
106
  // the live frame outside the cache instead.
93
- out.push({ text: SPIN_PLACEHOLDER + ' thinking…', ind: '', color: C.gray });
107
+ out.push({ text: SPIN_PLACEHOLDER + uiText(' thinking…'), ind: '', color: C.gray });
94
108
  const vis = contentLines.length > PREVIEW ? contentLines.slice(-PREVIEW) : contentLines;
95
109
  for (const l of vis) out.push({ text: it(l), ind: INDENT, color: C.gray });
96
110
  } else {
97
111
  const shown = contentLines.slice(0, PREVIEW);
98
112
  shown.forEach((l, i) => out.push({ text: it(l), ind: i === 0 ? '● ' : INDENT, color: C.gray }));
99
113
  if (contentLines.length > PREVIEW) {
100
- out.push({ text: `… (${contentLines.length - PREVIEW} more lines, ctrl+o to expand)`, ind: INDENT, color: C.gray });
114
+ out.push({ text: uiText(`… (${contentLines.length - PREVIEW} more lines, ctrl+o to expand)`), ind: INDENT, color: C.gray });
101
115
  }
102
116
  }
103
117
  return out;
@@ -1,208 +1,242 @@
1
- // A tool result row: the `↳` block under the tool line.
2
- //
3
- // The shape is the same for every tool, and the parts differ:
4
- //
5
- // ● Used Edit (a.js) +1 -1 <- the tool line, counts only
6
- // ↳ 179 - old line <- ONE `↳` on the FIRST body row
7
- // 179 + new line
8
- // Edited a.js: replaced 1 occurrence(s). <- receipt LAST
9
- //
10
- // An Edit's DIFF is the body and carries the marker, with the receipt moved to the bottom; every other tool's output
11
- // IS the body and carries the marker on its first line.
12
-
13
- import { C } from './colors.js';
14
- import { col, expandTabs, fitAnsi, sanitizeText, visualCol, wrapWords } from './text.js';
15
- import { langForPath } from './highlight.js';
16
- import { paintCode } from './diff.js';
17
-
18
- export function toolResultRows(msg, width, expanded) {
19
- // The marker sits in the SAME COLUMN as the tool bullet `●` (columns 0-1), so `↳ ` starts at column 0 and the output
20
- // text is indented to the tool text column. ONE `↳` per result, however many lines it has.
21
- const pre = '↳ ';
22
- const cont = ' ';
23
- const bodyW = Math.max(1, width - visualCol(cont));
24
- // Strip escapes BEFORE splitting: a file or a command can emit raw cursor codes, and letting them through made the
25
- // terminal OBEY them — recolouring the transcript, resetting styles mid-row, clearing the screen over the composer.
26
- const rawLines = sanitizeText(msg.text).replace(/\r\n/g, '\n').split('\n');
27
- // A TAB counts as ZERO columns in our width maths but advances to the next tab stop in a real terminal. A row
28
- // containing one was therefore padded short and the terminal kept the old frame's glyphs in the gap — the "residue"
29
- // under tool output. Read rows are the exception: their first tab is the line-number separator and is handled in the
30
- // Read branch below, where the CONTENT half is expanded too.
31
- if (!msg.readPath) for (let k = 0; k < rawLines.length; k++) rawLines[k] = expandTabs(rawLines[k]);
32
- // Trim blank lines at BOTH ends: commands typically emit a trailing newline, and some tools emit a leading one. A
33
- // stray blank line would render as a lone "↳ " with no content.
34
- while (rawLines.length && rawLines[0].trim() === '') rawLines.shift();
35
- while (rawLines.length && rawLines[rawLines.length - 1].trim() === '') rawLines.pop();
36
- const MAX_RESULT_LINES = expanded ? Infinity : 12;
37
- // The exit-code line is bookkeeping for the AGENT and is NEVER shown to the user — success or failure. A failure is
38
- // already legible from the RED result text below. `[error: …]` is kept: it carries the message, not just a code.
39
- const visible = rawLines.filter((ln) => !/^\[exit code:/.test(ln.trim()));
40
- const failed = msg.failed === true;
41
- // A silent Bash keeps the ONE empty output row it had while running. Only Bash has this area: an empty Read/Grep
42
- // result must not grow a phantom line merely because the command itself printed nothing.
43
- const shown = visible.length ? visible.slice(0, MAX_RESULT_LINES) : (msg.toolName === 'Bash' ? [''] : []);
44
-
45
- const diffRows = [];
46
- const receiptRows = [];
47
- const hasDiff = Array.isArray(msg.diff); // empty array => receipt-only (Write)
48
-
49
- if (hasDiff) {
50
- // Same collapse rule as elsewhere: a short preview by default, everything once Ctrl+O expands. 16 rows (not 12)
51
- // because a change renders as a PAIR: `- old` then `+ new`.
52
- const MAX = expanded ? Infinity : 16;
53
- // Show the unified diff WITH context rows (ctx = dim) so a change is not two orphaned blocks; `gap` rows mark where
54
- // unchanged lines were elided.
55
- const total = msg.diff.length;
56
- const wNo = Math.max(1, ...msg.diff.map((d) => String(d.no || 0).length));
57
- // THE COMMENT STATE TRAVELS BETWEEN THE ROWS of one diff, so a block comment that opens on a context row and closes
58
- // on a changed one stays grey across both.
59
- let inComment = false;
60
- let emitted = 0;
61
- for (const d of msg.diff) {
62
- if (emitted >= MAX) break;
63
- if (d.type === 'gap') {
64
- diffRows.push({ text: col(' ⋮', C.gray), ind: cont, raw: true });
65
- emitted++;
66
- continue;
67
- }
68
- const no = String(d.no || 0).padStart(wNo);
69
- const mark = d.type === 'add' ? '+' : d.type === 'del' ? '-' : ' ';
70
- // TABS ARE EXPANDED FIRST: `visualCol` counts one as zero columns, so an indented row measured short and its
71
- // background stopped before the right edge — the strip of page colour seen on Go diffs.
72
- const text = expandTabs(sanitizeText(d.text));
73
-
74
- // The sign, line number and content share the line's addition/deletion background; syntax highlighting changes
75
- // only the foreground. The wash runs to the right edge so adjacent changed rows read as one block.
76
- const isAdd = d.type === 'add';
77
- const isDel = d.type === 'del';
78
- const lineBg = isAdd ? C.diffAddBg : isDel ? C.diffDelBg : '';
79
- const fg = isAdd ? C.diffAddFg : isDel ? C.diffDelFg : C.white;
80
- const lead = col(`${no} ${mark} `, lineBg ? fg + lineBg : fg);
81
-
82
- if (!lineBg) {
83
- // CONTEXT LINES ARE CODE TOO. They are most of a diff and the part a reader scans to place the change, so they
84
- // get the same highlighter, on the CODE SURFACE rather than the raw page — a changed block sits on one recessed
85
- // field. The +/- rows around it keep their green/red wash.
86
- const ctxPainted = paintCode(text, d.lang, '', inComment);
87
- inComment = ctxPainted.inComment;
88
- const ctxRow = (lead + ctxPainted.text).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
89
- diffRows.push({ text: C.codeBg + fitAnsi(ctxRow, bodyW) + C.bgReset, ind: cont, raw: true });
90
- emitted++;
91
- continue;
92
- }
93
-
94
- // Keep only the line-level wash and syntax foreground. Positional word pairing can highlight the wrong token when
95
- // lines are reordered or punctuation changes, so no word tint is applied.
96
- const painted = paintCode(text, d.lang, lineBg, inComment);
97
- inComment = painted.inComment;
98
- const used = visualCol(`${no} ${mark} `) + visualCol(painted.text);
99
- const pad = ' '.repeat(Math.max(0, bodyW - used));
100
- // The padding is INSIDE the wash, so it must not end with a bare reset: `col()` closes with ESC[0m, which would
101
- // drop the background on the last column and leave a strip of page colour at the right edge.
102
- diffRows.push({ text: lead + painted.text + lineBg + pad + '\x1b[39m', ind: cont, raw: true });
103
- emitted++;
104
- }
105
- if (total > emitted) {
106
- diffRows.push({
107
- text: col(`… (${total - emitted} more lines, ctrl+o to expand)`, C.gray),
108
- ind: cont, raw: true,
109
- });
110
- }
111
- if (total === 0) diffRows.push({ text: col('(no changes)', C.gray), ind: cont, raw: true });
112
- // The receipt: one line per source line of the tool's own message.
113
- for (const ln of shown) {
114
- const color = failed ? C.red : C.gray;
115
- for (const t of (ln === '' ? [''] : wrapWords(ln, bodyW))) {
116
- receiptRows.push({ text: t, ind: cont, color });
117
- }
118
- }
119
- } else {
120
- // No diff: the tool's own output is the body.
121
- //
122
- // A READ RESULT IS SOURCE CODE, so its numbered lines are syntax-coloured — the file's own language, carried on the
123
- // message by the tool_result handler, which is the last place that still knows the path. The header and any error
124
- // keep the plain grey: those are the tool's own words, not the file's.
125
- const readLang = msg.readPath ? langForPath(msg.readPath) : null;
126
- // THE GUTTER IS ONE WIDTH FOR THE WHOLE BLOCK. The tool sends `N<TAB>text`, and the tab is what used to place the
127
- // code — so `1` and `10` started their text at different columns once the tab was expanded. Padding the NUMBER to
128
- // the widest one in this block keeps the digits left-aligned and the code aligned under itself.
129
- const numW = shown.reduce((w, ln) => {
130
- const m = /^(\d+)\t/.exec(ln);
131
- return m ? Math.max(w, m[1].length) : w;
132
- }, 0);
133
- let inComment = false;
134
- shown.forEach((ln, idx) => {
135
- const isErr = /^\[error:/.test(ln.trim());
136
- // A failed run is red throughout so it cannot be skimmed past.
137
- const color = isErr ? C.red : (failed ? C.red : C.gray);
138
- // `N<TAB>text` is the Read tool's own line format; only those rows are file content.
139
- const numbered = readLang && !isErr ? /^(\d+)\t([\s\S]*)$/.exec(ln) : null;
140
- if (numbered) {
141
- // A READ CAN START INSIDE A BLOCK COMMENT. The `/**` may sit above the first visible row, so no cross-row state
142
- // can tell the highlighter the first row is a comment — it coloured `of`, `switch`, `from` in a JSDoc paragraph
143
- // as keywords. A row that is plainly part of a block comment (` * …`, an opening `/**`, or the closing `*/`) is
144
- // painted as a comment on its own merits; the opener also seeds the rows that follow.
145
- const content = expandTabs(numbered[2]);
146
- const isBlockCommentRow = /^\s*(?:\/\*|\*|\*\/|\*\*)/.test(content);
147
- const painted = paintCode(content, readLang, '', inComment || isBlockCommentRow);
148
- if (/\/\*/.test(content) && !/\*\//.test(content)) inComment = true;
149
- else if (/\*\//.test(content)) inComment = false;
150
- // The separator is a SPACE: the number is padded to the block's widest, so every row's code starts in the same
151
- // column.
152
- const text = `${col(numbered[1].padStart(numW), C.white)} ${painted.text}`;
153
- // A Read row is TRUNCATED, not wrapped. Wrapping folded an overlong line onto a second row without a line
154
- // number, and that second row was exactly what a differential painter could not reconcile with the previous
155
- // frame: the leftover glyphs stayed under it as residue. One source line is one display row.
156
- //
157
- // The background has to survive the row's own resets: every syntax token closes with `ESC[0m`, and the padding
158
- // `fitAnsi` adds sits AFTER the last one. Re-asserting after each reset — the same trick `paintCode` uses for a
159
- // diff wash — keeps the surface on the padding too, so the block reads solid.
160
- const surfaced = text.replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
161
- diffRows.push({ text: C.codeBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 ? pre : cont, raw: true });
162
- return;
163
- }
164
- const wrapped = ln === '' ? [''] : wrapWords(ln, bodyW);
165
- // BASH OUTPUT SITS ON THE TERMINAL SURFACE, like text inside a real terminal emulator: the darkest recess on
166
- // screen. Other tools keep the plain page background, so a command's output reads as "a terminal ran this" rather
167
- // than as an ordinary result.
168
- const termSurface = msg.toolName === 'Bash' || msg.toolName === 'Shell';
169
- wrapped.forEach((t, i) => {
170
- if (termSurface) {
171
- const surfaced = t.replace(/\x1b\[0m/g, `\x1b[0m${C.termBg}`);
172
- diffRows.push({ text: C.termBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 && i === 0 ? pre : cont, raw: true });
173
- } else {
174
- diffRows.push({ text: t, ind: idx === 0 && i === 0 ? pre : cont, color });
175
- }
176
- });
177
- });
178
- if (visible.length > MAX_RESULT_LINES) {
179
- // The hint says HOW to see the rest: "… N more lines" alone gave the user no way to know Ctrl+O would reveal it.
180
- // Only reachable while COLLAPSED: expanded, `MAX_RESULT_LINES` is Infinity.
181
- diffRows.push({
182
- text: `… ${visible.length - MAX_RESULT_LINES} more lines, ctrl+o to expand`,
183
- ind: cont,
184
- color: failed ? C.red : C.gray,
185
- });
186
- }
187
- }
188
-
189
- const out = [];
190
- for (const r of diffRows) out.push(r);
191
- for (const r of receiptRows) out.push(r);
192
- // Put the `↳` on the FIRST rendered row (diff or output) — never on the receipt, which sits last.
193
- if (out.length && out[0].ind === cont && Array.isArray(msg.diff) && msg.diff.length > 0) {
194
- out[0] = { ...out[0], ind: pre };
195
- }
196
- // The TOOL ROW may already have drawn this result's body — a Write streams the file's content up there — in which
197
- // case the receipt below is the whole result and must NOT open a second `↳` block:
198
- // ● Used Write (a.txt) 1.3KB
199
- // ↳ 1 <content> <- the body, marked on the tool row
200
- // ↳ File written: a.txt (1372 bytes) <- the stray second `↳`, now plain
201
- // One body, one marker. `bodyOnToolRow` is set by the tool_result handler, the only place that knows whether the tool
202
- // row had content to show.
203
- if (msg.bodyOnToolRow && out.length && out[0].ind === pre) {
204
- out[0] = { ...out[0], ind: cont };
205
- }
206
- // Nothing to show (empty output) -> render no row at all rather than a dangling "↳ ".
207
- return out;
208
- }
1
+ // A tool result row: the `↳` block under the tool line.
2
+ //
3
+ // The shape is the same for every tool, and the parts differ:
4
+ //
5
+ // ● Used Edit (a.js) +1 -1 <- the tool line, counts only
6
+ // ↳ 179 - old line <- ONE `↳` on the FIRST body row
7
+ // 179 + new line
8
+ // Edited a.js: replaced 1 occurrence(s). <- receipt LAST
9
+ //
10
+ // An Edit's DIFF is the body and carries the marker, with the receipt moved to the bottom; every other tool's output
11
+ // IS the body and carries the marker on its first line.
12
+
13
+ import { C } from './colors.js';
14
+ import { col, expandTabs, fitAnsi, sanitizeText, visualCol, wrapWords } from './text.js';
15
+ import { uiText } from './i18n.js';
16
+ import { langForPath } from './highlight.js';
17
+ import { paintCode } from './diff.js';
18
+
19
+ export function toolResultRows(msg, width, expanded) {
20
+ // The marker sits in the SAME COLUMN as the tool bullet `●` (columns 0-1), so `↳ ` starts at column 0 and the output
21
+ // text is indented to the tool text column. ONE `↳` per result, however many lines it has.
22
+ //
23
+ // The marker carries the STRUCTURAL colour, not the body's. A `↳` is a piece of chrome —
24
+ // it says "what follows belongs to the line above" — and it was inheriting the result's
25
+ // grey, which on a dark page made it a smudge in the margin rather than a marker. The
26
+ // plain text is kept for the comparisons below and for the width maths; the coloured one
27
+ // is what is drawn.
28
+ const PRE = '↳ ';
29
+ const pre = C.marker + '↳ ' + C.reset;
30
+ const cont = ' ';
31
+ const bodyW = Math.max(1, width - visualCol(cont));
32
+ // Strip escapes BEFORE splitting: a file or a command can emit raw cursor codes, and letting them through made the
33
+ // terminal OBEY them — recolouring the transcript, resetting styles mid-row, clearing the screen over the composer.
34
+ const rawLines = sanitizeText(msg.text).replace(/\r\n/g, '\n').split('\n');
35
+ // A TAB counts as ZERO columns in our width maths but advances to the next tab stop in a real terminal. A row
36
+ // containing one was therefore padded short and the terminal kept the old frame's glyphs in the gap — the "residue"
37
+ // under tool output. Read rows are the exception: their first tab is the line-number separator and is handled in the
38
+ // Read branch below, where the CONTENT half is expanded too.
39
+ if (!msg.readPath) for (let k = 0; k < rawLines.length; k++) rawLines[k] = expandTabs(rawLines[k]);
40
+ // Trim blank lines at BOTH ends: commands typically emit a trailing newline, and some tools emit a leading one. A
41
+ // stray blank line would render as a lone "↳ " with no content.
42
+ while (rawLines.length && rawLines[0].trim() === '') rawLines.shift();
43
+ while (rawLines.length && rawLines[rawLines.length - 1].trim() === '') rawLines.pop();
44
+ // COLLAPSED IS A GLANCE; EXPANDED IS A READ, NOT A DUMP.
45
+ //
46
+ // Expanded used to be `Infinity`, so Ctrl+O on a command that printed 3000 lines put all 3000 into the transcript: the
47
+ // conversation above it scrolled away, the scrollbar became meaningless, and every frame afterwards paid to lay out
48
+ // rows nobody would read. The cap here is what a person can actually scan; past that the output belongs in a file,
49
+ // which is what the hint says.
50
+ const MAX_RESULT_LINES = expanded ? 400 : 12;
51
+ // The exit-code line is bookkeeping for the AGENT and is NEVER shown to the user — success or failure. A failure is
52
+ // already legible from the RED result text below. `[error: …]` is kept: it carries the message, not just a code.
53
+ const visible = rawLines.filter((ln) => !/^\[exit code:/.test(ln.trim()));
54
+ const failed = msg.failed === true;
55
+ // A silent Bash keeps the ONE empty output row it had while running. Only Bash has this area: an empty Read/Grep
56
+ // result must not grow a phantom line merely because the command itself printed nothing.
57
+ const shown = visible.length ? visible.slice(0, MAX_RESULT_LINES) : (msg.toolName === 'Bash' ? [''] : []);
58
+
59
+ const diffRows = [];
60
+ const receiptRows = [];
61
+ const hasDiff = Array.isArray(msg.diff); // empty array => receipt-only (Write)
62
+
63
+ if (hasDiff) {
64
+ // Same collapse rule as elsewhere: a short preview by default, everything once Ctrl+O expands. 16 rows (not 12)
65
+ // because a change renders as a PAIR: `- old` then `+ new`.
66
+ const MAX = expanded ? 400 : 16;
67
+ // Show the unified diff WITH context rows (ctx = dim) so a change is not two orphaned blocks; `gap` rows mark where
68
+ // unchanged lines were elided.
69
+ const total = msg.diff.length;
70
+ const wNo = Math.max(1, ...msg.diff.map((d) => String(d.no || 0).length));
71
+ // THE COMMENT STATE TRAVELS BETWEEN THE ROWS of one diff, so a block comment that opens on a context row and closes
72
+ // on a changed one stays grey across both.
73
+ let inComment = false;
74
+ let emitted = 0;
75
+ for (const d of msg.diff) {
76
+ if (emitted >= MAX) break;
77
+ if (d.type === 'gap') {
78
+ diffRows.push({ text: col(' ⋮', C.gray), ind: cont, raw: true });
79
+ emitted++;
80
+ continue;
81
+ }
82
+ const no = String(d.no || 0).padStart(wNo);
83
+ const mark = d.type === 'add' ? '+' : d.type === 'del' ? '-' : ' ';
84
+ // TABS ARE EXPANDED FIRST: `visualCol` counts one as zero columns, so an indented row measured short and its
85
+ // background stopped before the right edge — the strip of page colour seen on Go diffs.
86
+ const text = expandTabs(sanitizeText(d.text));
87
+
88
+ // The sign, line number and content share the line's addition/deletion background; syntax highlighting changes
89
+ // only the foreground. The wash runs to the right edge so adjacent changed rows read as one block.
90
+ const isAdd = d.type === 'add';
91
+ const isDel = d.type === 'del';
92
+ const lineBg = isAdd ? C.diffAddBg : isDel ? C.diffDelBg : '';
93
+ const fg = isAdd ? C.diffAddFg : isDel ? C.diffDelFg : C.white;
94
+ const lead = col(`${no} ${mark} `, lineBg ? fg + lineBg : fg);
95
+
96
+ if (!lineBg) {
97
+ // CONTEXT LINES ARE CODE TOO. They are most of a diff and the part a reader scans to place the change, so they
98
+ // get the same highlighter, on the CODE SURFACE rather than the raw page — a changed block sits on one recessed
99
+ // field. The +/- rows around it keep their green/red wash.
100
+ const ctxPainted = paintCode(text, d.lang, '', inComment);
101
+ inComment = ctxPainted.inComment;
102
+ const ctxRow = (lead + ctxPainted.text).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
103
+ diffRows.push({ text: C.codeBg + fitAnsi(ctxRow, bodyW) + C.bgReset, ind: cont, raw: true });
104
+ emitted++;
105
+ continue;
106
+ }
107
+
108
+ // Keep only the line-level wash and syntax foreground. Positional word pairing can highlight the wrong token when
109
+ // lines are reordered or punctuation changes, so no word tint is applied.
110
+ const painted = paintCode(text, d.lang, lineBg, inComment);
111
+ inComment = painted.inComment;
112
+ const used = visualCol(`${no} ${mark} `) + visualCol(painted.text);
113
+ const pad = ' '.repeat(Math.max(0, bodyW - used));
114
+ // The padding is INSIDE the wash, so it must not end with a bare reset: `col()` closes with ESC[0m, which would
115
+ // drop the background on the last column and leave a strip of page colour at the right edge.
116
+ diffRows.push({ text: lead + painted.text + lineBg + pad + '\x1b[39m', ind: cont, raw: true });
117
+ emitted++;
118
+ }
119
+ if (total > emitted) {
120
+ diffRows.push({
121
+ // A DEAD-END Ctrl+O IS WORSE THAN NO HINT. Collapsed it expands; already expanded there is nothing left to
122
+ // reveal, so the line says how much was withheld instead of inviting a key that would do nothing.
123
+ text: col(expanded
124
+ ? uiText(`… (${total - emitted} more lines not shown; press ctrl+e for the whole thing)`)
125
+ : uiText(`… (${total - emitted} more lines, ctrl+o to expand)`), C.gray),
126
+ ind: cont, raw: true,
127
+ });
128
+ }
129
+ if (total === 0) diffRows.push({ text: col('(no changes)', C.gray), ind: cont, raw: true });
130
+ // The receipt: one line per source line of the tool's own message.
131
+ for (const ln of shown) {
132
+ const color = failed ? C.red : C.gray;
133
+ for (const t of (ln === '' ? [''] : wrapWords(ln, bodyW))) {
134
+ receiptRows.push({ text: t, ind: cont, color });
135
+ }
136
+ }
137
+ } else {
138
+ // No diff: the tool's own output is the body.
139
+ //
140
+ // A READ RESULT IS SOURCE CODE, so its numbered lines are syntax-coloured — the file's own language, carried on the
141
+ // message by the tool_result handler, which is the last place that still knows the path. The header and any error
142
+ // keep the plain grey: those are the tool's own words, not the file's.
143
+ const readLang = msg.readPath ? langForPath(msg.readPath) : null;
144
+ // THE GUTTER IS ONE WIDTH FOR THE WHOLE BLOCK. The tool sends `N<TAB>text`, and the tab is what used to place the
145
+ // code — so `1` and `10` started their text at different columns once the tab was expanded. Padding the NUMBER to
146
+ // the widest one in this block keeps the digits left-aligned and the code aligned under itself.
147
+ const numW = shown.reduce((w, ln) => {
148
+ const m = /^(\d+)\t/.exec(ln);
149
+ return m ? Math.max(w, m[1].length) : w;
150
+ }, 0);
151
+ let inComment = false;
152
+ shown.forEach((ln, idx) => {
153
+ const isErr = /^\[error:/.test(ln.trim());
154
+ // A failed run is red throughout so it cannot be skimmed past.
155
+ const color = isErr ? C.red : (failed ? C.red : C.gray);
156
+ // `N<TAB>text` is the Read tool's own line format; only those rows are file content.
157
+ const numbered = readLang && !isErr ? /^(\d+)\t([\s\S]*)$/.exec(ln) : null;
158
+ if (numbered) {
159
+ // A READ CAN START INSIDE A BLOCK COMMENT. The `/**` may sit above the first visible row, so no cross-row state
160
+ // can tell the highlighter the first row is a comment — it coloured `of`, `switch`, `from` in a JSDoc paragraph
161
+ // as keywords. A row that is plainly part of a block comment (` * …`, an opening `/**`, or the closing `*/`) is
162
+ // painted as a comment on its own merits; the opener also seeds the rows that follow.
163
+ const content = expandTabs(numbered[2]);
164
+ const isBlockCommentRow = /^\s*(?:\/\*|\*|\*\/|\*\*)/.test(content);
165
+ const painted = paintCode(content, readLang, '', inComment || isBlockCommentRow);
166
+ if (/\/\*/.test(content) && !/\*\//.test(content)) inComment = true;
167
+ else if (/\*\//.test(content)) inComment = false;
168
+ // The separator is a SPACE: the number is padded to the block's widest, so every row's code starts in the same
169
+ // column.
170
+ const text = `${col(numbered[1].padStart(numW), C.white)} ${painted.text}`;
171
+ // A Read row is TRUNCATED, not wrapped. Wrapping folded an overlong line onto a second row without a line
172
+ // number, and that second row was exactly what a differential painter could not reconcile with the previous
173
+ // frame: the leftover glyphs stayed under it as residue. One source line is one display row.
174
+ //
175
+ // The background has to survive the row's own resets: every syntax token closes with `ESC[0m`, and the padding
176
+ // `fitAnsi` adds sits AFTER the last one. Re-asserting after each reset — the same trick `paintCode` uses for a
177
+ // diff wash — keeps the surface on the padding too, so the block reads solid.
178
+ const surfaced = text.replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
179
+ diffRows.push({ text: C.codeBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 ? pre : cont, raw: true });
180
+ return;
181
+ }
182
+ const wrapped = ln === '' ? [''] : wrapWords(ln, bodyW);
183
+ // BASH OUTPUT SITS ON THE TERMINAL SURFACE, like text inside a real terminal emulator: the darkest recess on
184
+ // screen. Other tools keep the plain page background, so a command's output reads as "a terminal ran this" rather
185
+ // than as an ordinary result.
186
+ const termSurface = msg.toolName === 'Bash' || msg.toolName === 'Shell';
187
+ wrapped.forEach((t, i) => {
188
+ if (termSurface) {
189
+ const surfaced = t.replace(/\x1b\[0m/g, `\x1b[0m${C.termBg}${color}`);
190
+ // A FOREGROUND IS NOT OPTIONAL HERE.
191
+ //
192
+ // This set only the background, so the text fell back to the terminal's own default colour. Against the very
193
+ // dark `termBg` that is readable on a light default and invisible on a dark one — which is exactly what a
194
+ // dark-background terminal showed: a solid dark block with no words in it.
195
+ //
196
+ // The `\x1b[0m` inside the row closes EVERYTHING, background included, so both have to be re-asserted after
197
+ // each one: the wash and the colour.
198
+ diffRows.push({ text: C.termBg + color + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 && i === 0 ? pre : cont, raw: true });
199
+ } else {
200
+ diffRows.push({ text: t, ind: idx === 0 && i === 0 ? pre : cont, color });
201
+ }
202
+ });
203
+ });
204
+ if (visible.length > MAX_RESULT_LINES) {
205
+ // THE HINT SAYS HOW TO SEE THE REST, and what "the rest" is depends on where we are.
206
+ //
207
+ // Collapsed: Ctrl+O expands — that is the whole point of the line.
208
+ // Already expanded: there is no more to reveal here, so inviting another Ctrl+O would be a dead end. Say how much
209
+ // was withheld and where it does live, which is the tool result the model was given (and, when the result was
210
+ // spilled, the file it was written to).
211
+ const rest = visible.length - MAX_RESULT_LINES;
212
+ const text = expanded
213
+ ? uiText(`… ${rest} more line${rest === 1 ? '' : 's'} not shown; ctrl+o collapses, ctrl+e shows all of it`)
214
+ : uiText(`… ${rest} more lines, ctrl+o to expand`);
215
+ diffRows.push({
216
+ text,
217
+ ind: cont,
218
+ color: failed ? C.red : C.gray,
219
+ });
220
+ }
221
+ }
222
+
223
+ const out = [];
224
+ for (const r of diffRows) out.push(r);
225
+ for (const r of receiptRows) out.push(r);
226
+ // Put the `↳` on the FIRST rendered row (diff or output) — never on the receipt, which sits last.
227
+ if (out.length && out[0].ind === cont && Array.isArray(msg.diff) && msg.diff.length > 0) {
228
+ out[0] = { ...out[0], ind: pre };
229
+ }
230
+ // The TOOL ROW may already have drawn this result's body — a Write streams the file's content up there — in which
231
+ // case the receipt below is the whole result and must NOT open a second `↳` block:
232
+ // ● Used Write (a.txt) 1.3KB
233
+ // ↳ 1 <content> <- the body, marked on the tool row
234
+ // ↳ File written: a.txt (1372 bytes) <- the stray second `↳`, now plain
235
+ // One body, one marker. `bodyOnToolRow` is set by the tool_result handler, the only place that knows whether the tool
236
+ // row had content to show.
237
+ if (msg.bodyOnToolRow && out.length && out[0].ind === pre) {
238
+ out[0] = { ...out[0], ind: cont };
239
+ }
240
+ // Nothing to show (empty output) -> render no row at all rather than a dangling "↳ ".
241
+ return out;
242
+ }