pal-code 0.0.15 → 0.0.17

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 (33) hide show
  1. package/bin/pal-code.js +31 -15
  2. package/package.json +2 -2
  3. package/packages/cli/src/agent-panel.ts +1 -1
  4. package/packages/cli/src/commands.ts +1 -1
  5. package/packages/cli/src/components/assistant-body.ts +2 -2
  6. package/packages/cli/src/components/message-box.ts +1 -1
  7. package/packages/cli/src/components/permission-prompt.ts +3 -3
  8. package/packages/cli/src/components/render-history.ts +13 -12
  9. package/packages/cli/src/components/run-view.ts +109 -33
  10. package/packages/cli/src/components/sidebar.ts +73 -12
  11. package/packages/cli/src/components/status-line.ts +3 -3
  12. package/packages/cli/src/config.ts +1 -1
  13. package/packages/cli/src/index.ts +65 -27
  14. package/packages/cli/src/overlays/key-input.ts +2 -1
  15. package/packages/cli/src/overlays/model-picker.ts +2 -1
  16. package/packages/cli/src/overlays/session-picker.ts +3 -2
  17. package/packages/cli/src/state.ts +12 -0
  18. package/packages/cli/src/theme.ts +13 -1
  19. package/packages/cli/src/themes/github-dark.ts +14 -3
  20. package/packages/cli/src/themes/types.ts +26 -2
  21. package/packages/cli/src/themes/vanilla-pi.ts +23 -9
  22. package/packages/cli/src/tui/components/text.ts +102 -0
  23. package/packages/cli/src/tui/render/code-block.ts +325 -0
  24. package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
  25. package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
  26. package/packages/cli/src/tui/surface/index.ts +9 -0
  27. package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
  28. package/packages/cli/src/tui/theme-types.ts +59 -0
  29. package/packages/cli/src/tui/tty-width.ts +20 -0
  30. package/packages/cli/src/tui/types.ts +53 -0
  31. package/packages/cli/src/turn.ts +21 -11
  32. package/packages/cli/src/utils/permissions.ts +3 -3
  33. package/packages/cli/src/utils/code-block.ts +0 -200
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Fenced code blocks in the transcript: segmentation + boxed rendering.
3
+ *
4
+ * Both exports are pure and deterministic — same input bytes → same output
5
+ * bytes, no clock or randomness. Hover/success paint arrives as explicit
6
+ * `opts` parameters, never as ambient state, so the TUI can repaint
7
+ * differentially and the components can cache by width without desyncing
8
+ * the screen from the cache.
9
+ */
10
+
11
+ import {truncateToWidth} from '../tty-width.js';
12
+ import {paintPanel} from '../surface/paint-panel.js';
13
+
14
+ import {c, codebox} from '../../theme.js';
15
+ import {buildHeader, displayWidth, wrapText} from './format.js';
16
+ import {highlightCode, highlightDiff, inferDiffCodeLang} from './highlight.js';
17
+ import {diffLineTint, tintLine} from './highlight.js';
18
+
19
+ /** One piece of an assistant message: prose, or a fenced code block. */
20
+ export type CodeSegment =
21
+ | {readonly kind: 'text'; readonly text: string}
22
+ | {readonly kind: 'code'; readonly lang: string; readonly lines: readonly string[]};
23
+
24
+ /** Right-edge copy affordance drawn in rendered code-block headers. */
25
+ export const COPY_LABEL = '⧉ copy';
26
+
27
+ /** Header label once the copy succeeded — wider than COPY_LABEL, so the
28
+ * dash run and copy zone must recompute from it. */
29
+ export const SUCCESS_LABEL = '✓ copied';
30
+
31
+ /**
32
+ * Screen geometry of the header copy zone: the rightmost columns of the
33
+ * header row — the label plus the closing corner (`⧉ copy╮`). Returns null
34
+ * when disabled or when the box is too narrow for the label plus at least
35
+ * one dash. Measured with `displayWidth` (=== `visibleWidth`), so the
36
+ * renderer and the click hit-test always agree on the same columns even if
37
+ * the label's ambiguous-width glyph is measured differently than expected.
38
+ * `label` defaults to COPY_LABEL; pass SUCCESS_LABEL while the success
39
+ * chip is painted so the hit-test follows the reflowed zone.
40
+ */
41
+ export function copyZoneRect(
42
+ W: number,
43
+ tag: string,
44
+ enabled: boolean,
45
+ label = COPY_LABEL,
46
+ ): {startCol: number; width: number} | null {
47
+ const tagW = displayWidth(tag.trim());
48
+ const tagged = tag.trim() !== '' && tagW + 6 <= W;
49
+ const dashes = tagged ? W - tagW - 5 : W - 2;
50
+ const labelW = displayWidth(label);
51
+ if (!enabled || dashes - labelW < 1) return null;
52
+ return {startCol: W - labelW - 1, width: labelW + 1};
53
+ }
54
+
55
+ // Opening fence: up to 3 leading spaces, 3+ backticks, then an info string
56
+ // that must not itself contain backticks (CommonMark) — so a line like
57
+ // "```code```" mid-paragraph stays prose.
58
+ const OPEN_FENCE = /^ {0,3}(`{3,})([^`]*)$/;
59
+ // Closing fence: backticks and whitespace only, and never shorter than the opener.
60
+ const CLOSE_FENCE = /^ {0,3}(`{3,})[ \t]*$/;
61
+
62
+ function trimBlankEdges(lines: readonly string[]): readonly string[] {
63
+ let start = 0;
64
+ let end = lines.length;
65
+ while (start < end && (lines[start] ?? '').trim() === '') start++;
66
+ while (end > start && (lines[end - 1] ?? '').trim() === '') end--;
67
+ return lines.slice(start, end);
68
+ }
69
+
70
+ /**
71
+ * Split markdown into prose and fenced code segments.
72
+ *
73
+ * Handles the edge cases that show up in real model output: an unclosed
74
+ * fence at the end of the message (runs to end), no language tag, padded or
75
+ * mixed-case tags, fences that interrupt a paragraph, CRLF endings, and
76
+ * longer (````) fences whose content contains triple backticks.
77
+ */
78
+ export function parseCodeSegments(text: string): CodeSegment[] {
79
+ const segments: CodeSegment[] = [];
80
+ let textLines: string[] = [];
81
+ let fence: {ticks: number; lang: string; lines: string[]} | null = null;
82
+
83
+ const flushText = (): void => {
84
+ const kept = trimBlankEdges(textLines);
85
+ textLines = [];
86
+ if (kept.length > 0) segments.push({kind: 'text', text: kept.join('\n')});
87
+ };
88
+
89
+ for (const line of text.split(/\r\n|\r|\n/)) {
90
+ if (fence) {
91
+ const close = CLOSE_FENCE.exec(line);
92
+ if (close && (close[1] ?? '').length >= fence.ticks) {
93
+ segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
94
+ fence = null;
95
+ } else {
96
+ fence.lines.push(line);
97
+ }
98
+ continue;
99
+ }
100
+
101
+ const open = OPEN_FENCE.exec(line);
102
+ if (open) {
103
+ flushText();
104
+ const info = (open[2] ?? '').trim();
105
+ fence = {
106
+ ticks: (open[1] ?? '').length,
107
+ lang: info.split(/\s+/)[0] ?? '',
108
+ lines: [],
109
+ };
110
+ continue;
111
+ }
112
+ textLines.push(line);
113
+ }
114
+
115
+ if (fence) segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
116
+ flushText();
117
+ return segments;
118
+ }
119
+
120
+ /**
121
+ * Side-by-side rendering kicks in for diff/patch blocks once the box is
122
+ * wide enough for two readable code columns; narrower boxes keep the
123
+ * unified single-column layout.
124
+ */
125
+ const SIDE_BY_SIDE_MIN_WIDTH = 90;
126
+
127
+ /** One rendered diff row: a full-width header/hunk, or a left/right pair. */
128
+ export type DiffRow =
129
+ | {readonly kind: 'full'; readonly text: string}
130
+ | {readonly kind: 'split'; readonly left: string | null; readonly right: string | null};
131
+
132
+ /**
133
+ * Pair unified-diff lines into side-by-side rows.
134
+ *
135
+ * File headers (`---`/`+++`) and hunk markers (`@@`) span both columns;
136
+ * context lines mirror on both sides; `-` runs zip against the `+` run
137
+ * that follows them, short side blank-paired.
138
+ */
139
+ export function pairDiffRows(lines: readonly string[]): DiffRow[] {
140
+ const rows: DiffRow[] = [];
141
+ let removals: string[] = [];
142
+ let additions: string[] = [];
143
+ const flush = (): void => {
144
+ const n = Math.max(removals.length, additions.length);
145
+ for (let i = 0; i < n; i++) {
146
+ rows.push({kind: 'split', left: removals[i] ?? null, right: additions[i] ?? null});
147
+ }
148
+ removals = [];
149
+ additions = [];
150
+ };
151
+ for (const line of lines) {
152
+ if (line.startsWith('---') || line.startsWith('+++') || line.startsWith('@@')) {
153
+ flush();
154
+ rows.push({kind: 'full', text: line});
155
+ } else if (line.startsWith('-')) {
156
+ removals.push(line);
157
+ } else if (line.startsWith('+')) {
158
+ additions.push(line);
159
+ } else {
160
+ flush();
161
+ rows.push({kind: 'split', left: line, right: line});
162
+ }
163
+ }
164
+ flush();
165
+ return rows;
166
+ }
167
+
168
+ /**
169
+ * Render paired diff rows as two columns separated by a border wall.
170
+ * Cells never wrap — overlong lines hard-truncate so the columns stay
171
+ * aligned at EN width; each cell keeps its own line-role color.
172
+ */
173
+ function sideBySideBody(
174
+ rawLines: readonly string[],
175
+ W: number,
176
+ paint: (s: string) => string,
177
+ ): string[] {
178
+ // Walls + padding + middle separator consume 7 columns; the rest splits
179
+ // into left/right code columns (left takes the odd column, if any).
180
+ const leftW = Math.floor((W - 7) / 2);
181
+ const rightW = W - 7 - leftW;
182
+ const inner = W - 4;
183
+ // Code language guessed from the ---/+++ headers so added/removed code
184
+ // gets syntax colors, not just the +/- role color.
185
+ const codeLang = inferDiffCodeLang(rawLines);
186
+ const cell = (text: string | null, w: number, tint: string | null): string => {
187
+ const safe = truncateToWidth(text ?? '', w, '');
188
+ const padded = `${safe}${' '.repeat(Math.max(0, w - displayWidth(safe)))}`;
189
+ return tint ? tintLine(padded, tint) : padded;
190
+ };
191
+ const rows: string[] = [];
192
+ for (const row of pairDiffRows(rawLines)) {
193
+ if (row.kind === 'full') {
194
+ // Content spans the full inner width (walls + padding account for
195
+ // the rest) — one short and paintPanel pads AFTER the closing wall,
196
+ // drifting it a column left of the split rows' walls.
197
+ const safe = truncateToWidth(highlightDiff(row.text), inner, '');
198
+ const pad = Math.max(0, inner - displayWidth(safe));
199
+ rows.push(`${paint('│')} ${safe}${' '.repeat(pad)} ${paint('│')}`);
200
+ continue;
201
+ }
202
+ const left = cell(
203
+ row.left ? highlightDiff(row.left, codeLang) : '',
204
+ leftW,
205
+ row.left ? diffLineTint(row.left) : null,
206
+ );
207
+ const right = cell(
208
+ row.right ? highlightDiff(row.right, codeLang) : '',
209
+ rightW,
210
+ row.right ? diffLineTint(row.right) : null,
211
+ );
212
+ rows.push(`${paint('│')} ${left} ${paint('│')} ${right} ${paint('│')}`);
213
+ }
214
+ return rows;
215
+ }
216
+
217
+ /**
218
+ * Render one fenced code segment as a bordered, language-tagged box:
219
+ *
220
+ * ╭─ typescript ────────╮
221
+ * │ 1 const x = 1; │
222
+ * │ 2 console.log(x); │
223
+ * ╰─────────────────────╯
224
+ *
225
+ * The header tier carries the language tag and copy affordance; body rows
226
+ * get an optional line-number gutter (dimmer than the border, shown once
227
+ * the box is wide enough to keep a usable code column). Every row is drawn
228
+ * first, then passed through `paintPanel` so the surface fill re-opens after
229
+ * any embedded reset — same isolation guarantee as the sidebar panel. Code
230
+ * is syntax-highlighted via the existing `highlightCode` helper, then
231
+ * wrapped and hard-truncated to the box — no row ever exceeds `width`.
232
+ */
233
+ export function codeBlockBox(
234
+ code: string,
235
+ width: number,
236
+ lang = '',
237
+ opts?: {copy?: boolean; hover?: boolean; success?: boolean},
238
+ ): string {
239
+ // One clamp before anything is derived, so header/body/footer agree.
240
+ const W = Math.max(6, Math.floor(width));
241
+ const inner = W - 4; // columns between "│ " and " │"
242
+
243
+ const tag = lang.trim();
244
+ const hover = opts?.hover === true;
245
+ const success = opts?.success === true;
246
+ // Rows are painted WITHOUT the fill: `paint` switches only the foreground
247
+ // role, and `paintPanel` at the end opens the surface fill once per row
248
+ // and re-opens it after any embedded reset (highlightCode emits them).
249
+ // Reset after each border glyph so code text never inherits the border
250
+ // foreground (e.g. faint+cyan).
251
+ const paint = (s: string): string => `${codebox.borderFg}${s}${c.reset}`;
252
+
253
+ // Copy affordance: pin the label at the right edge of the header (zone
254
+ // includes the closing ╮) while the visible width stays exactly W.
255
+ // Chip precedence: success > hover > idle — success swaps both the
256
+ // label and the fg, and the zone reflows from the wider label.
257
+ const labelText = success ? SUCCESS_LABEL : COPY_LABEL;
258
+ const zone = copyZoneRect(W, tag, opts?.copy === true, labelText);
259
+ const tagW = displayWidth(tag);
260
+ const labelW = displayWidth(labelText);
261
+ const chipBg = hover && !success ? codebox.chipBgHover : codebox.chipBgIdle;
262
+ const chipFg = success ? codebox.successFg : hover ? codebox.chipFgHover : codebox.chipFgIdle;
263
+ const chip = `${chipBg}${chipFg}${labelText}`;
264
+
265
+ let header: string;
266
+ if (!zone) {
267
+ header = tag
268
+ ? buildHeader(W, tag, tagW, codebox.langFg, paint, '')
269
+ : paint(`╭${'─'.repeat(W - 2)}╮`);
270
+ } else if (tag !== '' && tagW + 6 <= W) {
271
+ const dashes = W - tagW - 5 - labelW;
272
+ header =
273
+ `${paint('╭─')} ${codebox.langFg}${tag}${c.reset} ${paint('─'.repeat(dashes))}` +
274
+ `${chip}${paint('╮')}`;
275
+ } else {
276
+ const dashes = W - 2 - labelW;
277
+ header = `${paint(`╭${'─'.repeat(dashes)}`)}${chip}${paint('╮')}`;
278
+ }
279
+
280
+ // Line-number gutter: a right-aligned number column in a dimmer shade of
281
+ // the border, shown for multi-line blocks once the code column keeps at
282
+ // least 8 columns. Wrapped continuation rows get a blank gutter so the
283
+ // code column stays aligned at EN width.
284
+ // Diff/patch blocks render side-by-side once wide enough; the unified
285
+ // single-column path below stays the narrow fallback.
286
+ const isDiff = tag === 'diff' || tag === 'patch';
287
+ if (isDiff && W >= SIDE_BY_SIDE_MIN_WIDTH) {
288
+ const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
289
+ return [header, ...sideBySideBody(code.split('\n'), W, paint), footer]
290
+ .map((line) => paintPanel(codebox.surfaceBg, line, W))
291
+ .join('\n');
292
+ }
293
+
294
+ const srcLines = highlightCode(code, tag || undefined);
295
+ const gutterW = String(srcLines.length).length;
296
+ const gutterOn = srcLines.length > 1 && inner - gutterW - 2 >= 8;
297
+ const available = inner - (gutterOn ? gutterW + 1 : 0); // columns for code + right pad
298
+ const textWidth = Math.max(1, available - 1); // reserve the last available column
299
+
300
+ const body: string[] = [];
301
+ // Raw lines run 1:1 with highlighted srcLines on the diff path (map, no
302
+ // expansion), so per-line role lookup stays aligned; other languages
303
+ // never consult rawLines.
304
+ const rawLines = code.split('\n');
305
+ for (let i = 0; i < srcLines.length; i++) {
306
+ const parts = wrapText(srcLines[i] ?? '', textWidth);
307
+ for (let j = 0; j < parts.length; j++) {
308
+ const safe = truncateToWidth((parts[j] ?? '').trimEnd(), textWidth, '');
309
+ const pad = Math.max(0, available - displayWidth(safe));
310
+ const gutter = gutterOn
311
+ ? j === 0
312
+ ? `${codebox.gutterFg}${String(i + 1).padStart(gutterW)}${c.reset}`
313
+ : ' '.repeat(gutterW)
314
+ : '';
315
+ const lead = gutterOn ? `${gutter} ` : '';
316
+ const content = `${lead}${safe}${c.reset}${' '.repeat(pad)}`;
317
+ const tint = isDiff ? diffLineTint(rawLines[i] ?? '') : null;
318
+ body.push(`${paint('│')} ${tint ? tintLine(content, tint) : content} ${paint('│')}`);
319
+ }
320
+ }
321
+
322
+ const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
323
+
324
+ return [header, ...body, footer].map((line) => paintPanel(codebox.surfaceBg, line, W)).join('\n');
325
+ }
@@ -1,7 +1,7 @@
1
- import {visibleWidth, wrapTextWithAnsi, truncateToWidth} from '../tui/tty-width.js';
1
+ import {visibleWidth, wrapTextWithAnsi, truncateToWidth} from '../tty-width.js';
2
2
 
3
- import {c, agentColors, agentLabels, surface} from '../theme.js';
4
- import type {AgentRole} from '../state.js';
3
+ import {c, agentColors, agentLabels, surface} from '../../theme.js';
4
+ import type {AgentRole} from '../../state.js';
5
5
 
6
6
  /**
7
7
  * Small text helpers shared by the renderers.
@@ -63,19 +63,19 @@ export function wrapText(text: string, maxWidth: number): string[] {
63
63
  }
64
64
 
65
65
  /**
66
- * Wrap a user message in a rounded Unicode box.
66
+ * Wrap a user message in a rounded Unicode box with a role icon column:
67
67
  *
68
- * The role tag sits in the top border (coloured by role, dimmed border); the
69
- * body carries only the message text. Every emitted row is exactly `width`
70
- * visible columns wide, so the box stays aligned at any terminal size:
68
+ * ╭─ [builder] ─── Mon 14:30 ─╮
69
+ * │ ▸ message text here │
70
+ * │ continued line │
71
+ * ╰───────────────────────────╯
71
72
  *
72
- * ╭─ [builder] ─────────╮
73
- * │ message text here │
74
- * │ continued line │
75
- * ╰─────────────────────╯
76
- *
77
- * Narrow terminals degrade cleanly: the tag is dropped once it no longer fits,
78
- * and `width` is clamped to a floor so the borders never collapse.
73
+ * Every body row carries a 2-column icon gutter (role-coloured `▸` on the
74
+ * first row, blanks on continuations) so text starts at one fixed column;
75
+ * the timestamp sits right-aligned in the header in `messageBox.dim`.
76
+ * Narrow terminals degrade cleanly: the icon column is dropped once the text
77
+ * would have fewer than 3 columns, then the timestamp, then the tag, and
78
+ * `width` is clamped to a floor so the borders never collapse.
79
79
  */
80
80
  export function userMessageBox(
81
81
  text: string,
@@ -85,8 +85,7 @@ export function userMessageBox(
85
85
  ): string {
86
86
  // One clamp before anything is derived, so header/body/footer agree.
87
87
  const W = Math.max(6, Math.floor(width));
88
- const inner = W - 4; // columns between "│ " and " │"
89
- const textWidth = Math.max(1, inner - 1); // reserve the last inner column
88
+ const inner = W - 4; // columns between the side walls
90
89
 
91
90
  const label = String(agentLabels[role] ?? role ?? '');
92
91
  const tagText = `[${label}]`;
@@ -99,17 +98,25 @@ export function userMessageBox(
99
98
 
100
99
  const header = buildHeader(W, tagText, tagWidth, roleColor, paint, timestamp);
101
100
 
102
- const body = wrapText(text, textWidth)
103
- .map((line) => {
104
- const safe = truncateToWidth(line.trimEnd(), textWidth, '');
105
- const pad = Math.max(0, inner - visibleWidth(safe));
106
- return `${paint('│')} ${safe}${c.reset}${' '.repeat(pad)} ${paint('│')}`;
107
- })
108
- .join('\n');
101
+ // Icon column: 2 columns (`▸ `), kept only when the code column still has
102
+ // room for readable text. Continuation rows pad it blank so every line's
103
+ // text starts at the same visible column.
104
+ const ICON_W = 2;
105
+ const iconOn = inner - ICON_W >= 4;
106
+ const available = inner - (iconOn ? ICON_W : 0); // text + right pad
107
+ const textWidth = Math.max(1, available - 1); // reserve the last available column
108
+
109
+ const rows: string[] = [];
110
+ wrapText(text, textWidth).forEach((line, i) => {
111
+ const safe = truncateToWidth(line.trimEnd(), textWidth, '');
112
+ const pad = Math.max(0, available - visibleWidth(safe));
113
+ const lead = iconOn ? (i === 0 ? `${roleColor}▸${c.reset} ` : ' ') : '';
114
+ rows.push(`${paint('│')} ${lead}${safe}${c.reset}${' '.repeat(pad)} ${paint('│')}`);
115
+ });
109
116
 
110
117
  const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
111
118
 
112
- return `${header}\n${body}\n${footer}`;
119
+ return `${header}\n${rows.join('\n')}\n${footer}`;
113
120
  }
114
121
 
115
122
  /**
@@ -2,10 +2,10 @@
2
2
  * Lightweight syntax highlighting for terminal code blocks.
3
3
  *
4
4
  * Zero dependencies — keyword + regex based. Covers the most common
5
- * languages well enough for agent output (TS, JS, Python, JSON, Shell, Go, Rust).
5
+ * languages well enough for agent output (TS, JS, Python, JSON, Shell, Go, Rust, diff).
6
6
  */
7
7
 
8
- import {c, syntax} from '../theme.js';
8
+ import {c, codebox, syntax} from '../../theme.js';
9
9
 
10
10
  // Per-language keyword sets
11
11
  const KEYWORDS: Record<string, Set<string> | null> = {
@@ -240,6 +240,13 @@ export function highlightCode(code: string, lang?: string): string[] {
240
240
  // JSON gets special treatment — highlight keys and string values differently
241
241
  if (lang === 'json') return lines.map((l) => highlightJson(l));
242
242
 
243
+ // Unified diffs: infer the code language from the ---/+++ file headers
244
+ // so added/removed lines get real syntax colors, not just role colors.
245
+ if (lang === 'diff' || lang === 'patch') {
246
+ const codeLang = inferDiffCodeLang(lines);
247
+ return lines.map((l) => highlightDiff(l, codeLang));
248
+ }
249
+
243
250
  return lines.map((line) => {
244
251
  if (keywords) {
245
252
  return highlightLine(line, keywords);
@@ -249,6 +256,91 @@ export function highlightCode(code: string, lang?: string): string[] {
249
256
  });
250
257
  }
251
258
 
259
+ /** File extension → highlight language for code inside diff blocks. */
260
+ const DIFF_LANG_BY_EXT: Record<string, string> = {
261
+ ts: 'typescript',
262
+ mts: 'typescript',
263
+ cts: 'typescript',
264
+ tsx: 'typescript',
265
+ js: 'javascript',
266
+ mjs: 'javascript',
267
+ cjs: 'javascript',
268
+ jsx: 'javascript',
269
+ py: 'python',
270
+ rs: 'rust',
271
+ sh: 'shell',
272
+ bash: 'shell',
273
+ zsh: 'shell',
274
+ go: 'go',
275
+ json: 'json',
276
+ };
277
+
278
+ /**
279
+ * Guess the code language of a unified diff from its ---/+++ file headers.
280
+ * Returns null when no header carries a recognized extension — callers then
281
+ * keep role-only colors instead of guessing wrong.
282
+ */
283
+ export function inferDiffCodeLang(lines: readonly string[]): string | null {
284
+ for (const line of lines) {
285
+ const m = /^(?:---|\+\+\+)\s+(?:[ab]\/)?(.+)$/.exec(line.trim());
286
+ if (!m) continue;
287
+ const path = m[1] ?? '';
288
+ const dot = path.lastIndexOf('.');
289
+ if (dot === -1) continue;
290
+ const lang = DIFF_LANG_BY_EXT[path.slice(dot + 1).toLowerCase()];
291
+ if (lang) return lang;
292
+ }
293
+ return null;
294
+ }
295
+
296
+ /**
297
+ * Highlight a unified diff line by role.
298
+ *
299
+ * +++ b/file / --- a/file file headers (bold)
300
+ * @@ -1,3 +1,4 @@ hunk headers (cyan)
301
+ * +added additions (green sign + syntax-colored code)
302
+ * -removed removals (red sign + syntax-colored code)
303
+ * context everything else (plain)
304
+ *
305
+ * The +/- sign carries the role color; the code after it is highlighted
306
+ * with `codeLang` when provided (inferred from the file headers) so
307
+ * keywords/strings/numbers read exactly like a normal code block.
308
+ */
309
+ export function highlightDiff(line: string, codeLang?: string | null): string {
310
+ if (line.startsWith('+++') || line.startsWith('---')) return `${c.bold}${line}${c.reset}`;
311
+ if (line.startsWith('@@')) return `${c.cyan}${line}${c.reset}`;
312
+ if ((line.startsWith('+') || line.startsWith('-')) && codeLang) {
313
+ const role = line.startsWith('+') ? c.green : c.red;
314
+ const rest = highlightCode(line.slice(1), codeLang)[0] ?? '';
315
+ return `${role}${line[0]}${c.reset}${rest}${c.reset}`;
316
+ }
317
+ if (line.startsWith('+')) return `${c.green}${line}${c.reset}`;
318
+ if (line.startsWith('-')) return `${c.red}${line}${c.reset}`;
319
+ return `${syntax.plain}${line}${c.reset}`;
320
+ }
321
+
322
+ /**
323
+ * Wash already-padded row content in a background tint edge-to-edge.
324
+ * Re-opens the tint after every embedded reset (same technique as
325
+ * paintPanel's fill) so syntax colors inside never punch holes in it.
326
+ * Split on the runtime reset value, never a literal escape.
327
+ */
328
+ export function tintLine(text: string, tint: string): string {
329
+ if (!tint) return text;
330
+ return `${tint}${text.split(c.reset).join(`${c.reset}${tint}`)}${c.reset}`;
331
+ }
332
+
333
+ /**
334
+ * Background wash for a raw diff line: deletions get the red tint,
335
+ * additions the green one, everything else none. Prefix-only, so it
336
+ * needs no headers and applies equally to unified and paired rows.
337
+ */
338
+ export function diffLineTint(line: string): string | null {
339
+ if (line.startsWith('+') && !line.startsWith('+++')) return codebox.diffAddBg;
340
+ if (line.startsWith('-') && !line.startsWith('---')) return codebox.diffDelBg;
341
+ return null;
342
+ }
343
+
252
344
  /**
253
345
  * Highlight a single line of code.
254
346
  *
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Surface painting — fills a background colour across a full terminal row.
3
+ *
4
+ * pi-tui-free. Adapts the fill behaviour pal's sidebar and code blocks rely on
5
+ * (paint a background across the entire panel width, not just the text) so the
6
+ * rendering layer can be published without pi-tui.
7
+ */
8
+
9
+ export {paintPanel} from './paint-panel.js';
@@ -7,7 +7,7 @@
7
7
  * are never truncated: painting only adds a background frame and padding.
8
8
  */
9
9
 
10
- import {visibleWidth} from './tty-width.js';
10
+ import {visibleWidth} from '../tty-width.js';
11
11
 
12
12
  export function paintPanel(bg: string, line: string, width: number): string {
13
13
  if (bg === '') return line;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * pi-tui-free theme contracts.
3
+ *
4
+ * Colour functions take a string and return it styled, so a theme is just a
5
+ * bag of `(text: string) => string` transforms. Declaring them here keeps the
6
+ * theme layer independent of whichever engine renders the text, while staying
7
+ * structurally compatible with pi-tui's own shapes.
8
+ *
9
+ * Adapted from @earendil-works/pi-tui's `dist/components/markdown.d.ts`,
10
+ * `editor.d.ts` and `select-list.d.ts` (MIT, © Mario Zechner,
11
+ * https://github.com/earendil-works/pi).
12
+ */
13
+
14
+ /** A styling transform: wraps `text` in the ANSI escapes for one role. */
15
+ export type StyleFn = (text: string) => string;
16
+
17
+ /** Colours for a filterable list (pickers, autocomplete). */
18
+ export interface SelectListTheme {
19
+ selectedPrefix: StyleFn;
20
+ selectedText: StyleFn;
21
+ description: StyleFn;
22
+ scrollInfo: StyleFn;
23
+ noMatch: StyleFn;
24
+ }
25
+
26
+ /** Colours for the prompt input line. */
27
+ export interface EditorTheme {
28
+ borderColor: StyleFn;
29
+ selectList: SelectListTheme;
30
+ }
31
+
32
+ /** Colours for rendered prose: headings, emphasis, quotes, code blocks. */
33
+ export interface MarkdownTheme {
34
+ heading: StyleFn;
35
+ link: StyleFn;
36
+ linkUrl: StyleFn;
37
+ code: StyleFn;
38
+ codeBlock: StyleFn;
39
+ codeBlockBorder: StyleFn;
40
+ quote: StyleFn;
41
+ quoteBorder: StyleFn;
42
+ hr: StyleFn;
43
+ listBullet: StyleFn;
44
+ bold: StyleFn;
45
+ italic: StyleFn;
46
+ strikethrough: StyleFn;
47
+ underline: StyleFn;
48
+ /** Syntax-highlight a fenced block, returning one styled line per row. */
49
+ highlightCode?: (code: string, lang?: string) => string[];
50
+ /** Prefix applied to each rendered code-block line (default: ` `). */
51
+ codeBlockIndent?: string;
52
+ }
53
+
54
+ /** One entry in a selectable list. */
55
+ export interface SelectItem {
56
+ value: string;
57
+ label: string;
58
+ description?: string;
59
+ }
@@ -971,3 +971,23 @@ export function truncateToWidth(
971
971
  }
972
972
  return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);
973
973
  }
974
+
975
+ /**
976
+ * Pad `line` out to `width` visible columns, then hand the whole row to `bgFn`.
977
+ *
978
+ * The padding is applied *before* painting so a background colour reaches the
979
+ * full row width instead of stopping at the last glyph — otherwise coloured
980
+ * surfaces show a ragged right edge against the terminal background.
981
+ *
982
+ * @param line - Row content, may contain ANSI escapes (they cost no width)
983
+ * @param width - Target width in visible columns
984
+ * @param bgFn - Paints the finished row, background included
985
+ */
986
+ export function applyBackgroundToLine(
987
+ line: string,
988
+ width: number,
989
+ bgFn: (text: string) => string,
990
+ ): string {
991
+ const paddingNeeded = Math.max(0, width - visibleWidth(line));
992
+ return bgFn(line + ' '.repeat(paddingNeeded));
993
+ }