@vincemakes/kiso-tui 0.1.39 → 0.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,884 +1,4 @@
1
- /**
2
- * TUI v6 (ADR-0046) — the components: EVERY screen line's renderer.
3
- *
4
- * Each component turns one piece of state into display lines (SGR
5
- * included, raw — the compositor writes them verbatim). The folding
6
- * lives HERE: every line a component returns must fit the terminal
7
- * width — the compositor's crash-on-violation invariant backs it up
8
- * (a component that forgets to fold CRASHES with a diagnostic, never
9
- * silently truncates — pi tui-main-screen.ts:447-473).
10
- *
11
- * The fold is SGR-AWARE: a line whose bold/dim span would straddle a
12
- * fold boundary closes the span at the break and reopens it on the
13
- * next row — the #16b contract (no literal "[2m" fragments) survives
14
- * folding. displayWidth/charWidth (editor.ts) are the width primitives
15
- * (untouched); render.ts supplies the original text (palette, escape,
16
- * tint, fold wording).
17
- */
18
- import { displayWidth } from "./editor.js";
19
- import { bannerLines, escapeTerminal, foldThinking, foldResult, colorInlineCode, renderTerminalGap, renderToolSummary, toolTarget, kUnit, palette, } from "./render.js";
20
- /** The spinner glyphs, cycled by the compositor's on-demand tick. */
21
- export const SPINNER = ["▖", "▘", "▝", "▗"];
22
- /**
23
- * The fold — split a display-width line into ≤W rows, preserving SGR
24
- * spans across the break: a span open at the break closes (reset) at
25
- * the row's end and reopens on the next row. The rows are what the
26
- * terminal's own soft-wrap would have produced — except the compositor
27
- * folds FIRST, so the terminal never reflows a component's line (the
28
- * #17 merge class cannot reach committed content).
29
- */
30
- export function foldLine(line, W) {
31
- if (W < 1)
32
- return [line];
33
- // collect the plain text + the SGR segments so the walk can track
34
- // the open span state
35
- const out = [];
36
- let current = "";
37
- let width = 0;
38
- let open = []; // the SGR sequences seen since the last reset
39
- for (let i = 0; i < line.length;) {
40
- if (line[i] === "\n") {
41
- // a real line break — the row ends here (the same close/reopen
42
- // as a fold boundary, so a span never leaks across the break)
43
- const close = open.length > 0 ? "\x1b[0m" : "";
44
- out.push(current + close);
45
- current = open.join("");
46
- width = 0;
47
- i += 1;
48
- continue;
49
- }
50
- if (line[i] === "\x1b") {
51
- const m = /^\x1b\[[0-9;]*m/.exec(line.slice(i));
52
- if (m !== null) {
53
- if (m[0] === "\x1b[0m")
54
- open = [];
55
- else
56
- open.push(m[0]);
57
- current += m[0];
58
- i += m[0].length;
59
- continue;
60
- }
61
- // a non-SGR CSI (the raw cell's own content, escaped at
62
- // composition) — copy verbatim, zero width
63
- const csi = /^\x1b\[[0-9;?]*[A-Za-z]/.exec(line.slice(i));
64
- if (csi !== null) {
65
- current += csi[0];
66
- i += csi[0].length;
67
- continue;
68
- }
69
- current += line[i];
70
- i += 1;
71
- continue;
72
- }
73
- const cw = displayWidth(line[i]);
74
- if (width + cw > W && width > 0) {
75
- // the fold — close the open spans, push, reopen on the next row
76
- const close = open.length > 0 ? "\x1b[0m" : "";
77
- out.push(current + close);
78
- current = open.join("");
79
- width = 0;
80
- continue;
81
- }
82
- current += line[i];
83
- width += cw;
84
- i += 1;
85
- }
86
- if (current !== "" || out.length === 0)
87
- out.push(current);
88
- return out;
89
- }
90
- /** The visible width of a rendered line (SGR stripped — the invariant
91
- * the compositor enforces on every emitted line). */
92
- export function visibleWidth(line) {
93
- let w = 0;
94
- for (let i = 0; i < line.length;) {
95
- if (line[i] === "\x1b") {
96
- const m = /^\x1b\[[0-9;?]*[A-Za-z]/.exec(line.slice(i));
97
- if (m !== null) {
98
- i += m[0].length;
99
- continue;
100
- }
101
- i += 1;
102
- continue;
103
- }
104
- w += displayWidth(line[i]);
105
- i += 1;
106
- }
107
- return w;
108
- }
109
- /** The W11 spacing formula — "a row gets one blank line above it when
110
- * the row is itself a block, or when the previous sibling was taller
111
- * than one row". One-row siblings pack tight; anything multi-row
112
- * breathes on both sides. The FIRST cell never gets the blank (it sits
113
- * at the body's top — the banner would otherwise start one row down).
114
- * `prev` is the previous sibling's OWN rows (raw — a cell's own blank
115
- * must never count toward its height). The blank is a JOIN artifact:
116
- * the cell's own render stays blank-free, so per-cell accounting
117
- * (heights, the fold cache) never sees a fake row. */
118
- export function bodySpacing(prev, rows) {
119
- if (rows.length === 0 || prev === null || prev.length === 0)
120
- return rows;
121
- if (rows.length > 1 || prev.length > 1)
122
- return ["", ...rows];
123
- return rows;
124
- }
125
- /** The container — vertical concatenation with the W11 formula. No
126
- * component decides its own spacing: every blank in the body is the
127
- * container's. */
128
- export class Container {
129
- children;
130
- constructor(children) {
131
- this.children = children;
132
- }
133
- render(width, ctx) {
134
- const out = [];
135
- let prev = null;
136
- for (const c of this.children) {
137
- const rows = c.render(width, ctx);
138
- out.push(...bodySpacing(prev, rows));
139
- prev = rows;
140
- }
141
- return out;
142
- }
143
- }
144
- const TOOL_SUMMARY_MAX = 60; // the tool line's parameter summary, chars
145
- /** The component for one cell — the mapping table lives here so the
146
- * compositor stays a pure writer. */
147
- export function cellComponent(cell) {
148
- switch (cell.kind) {
149
- case "user":
150
- return new UserMessage(cell);
151
- case "thinking":
152
- return new ThinkingFold(cell);
153
- case "tool":
154
- return new ToolExecution(cell);
155
- case "text":
156
- return new AssistantMessage(cell);
157
- case "notice":
158
- return new ErrorLine(cell);
159
- case "banner":
160
- return new Banner(cell);
161
- case "raw":
162
- return new RawBlock(cell);
163
- case "terminal":
164
- return new TerminalBlock(cell);
165
- case "checklist":
166
- return new Checklist(cell);
167
- }
168
- }
169
- /**
170
- * The user message — the W16 inset chip ALONE (the 2026-08-09 ruling:
171
- * the ▍ rail and the indent are retired — the rail's stated pipe
172
- * fallback was theoretical redundancy: the CLI's pipe path is the
173
- * line-mode "you>" form and never renders UserMessage). The chip folds
174
- * the text at W−2 (the side pads), then pads EVERY row to the longest
175
- * row's DISPLAY width + one space each side, flush left: the block is
176
- * only as wide as what was said (never the full-width band — a short
177
- * message like /think would paint a bar across the terminal). The
178
- * padding is by cells (charWidth is the width authority), so a CJK row
179
- * pads by width, never by chars, and the chip never overruns its fold.
180
- * SGR 7 closed with SGR 27 — never SGR 0, the chip composes with a
181
- * surrounding span — and NEVER dim: reverse video inverts the CURRENT
182
- * colours, so dimmed text would invert into a dimmed block with no
183
- * contrast.
184
- */
185
- class UserMessage {
186
- cell;
187
- constructor(cell) {
188
- this.cell = cell;
189
- }
190
- render(W, _ctx) {
191
- const p = palette();
192
- const chipW = Math.max(1, W - 2);
193
- const rows = [];
194
- for (const para of this.cell.text.split("\n")) {
195
- const folded = foldLine(escapeTerminal(para), chipW);
196
- const inner = Math.max(...folded.map((r) => displayWidth(r)));
197
- for (const row of folded) {
198
- const pad = inner - displayWidth(row);
199
- rows.push(`${p.rv} ${row}${" ".repeat(pad)} ${p.rvEnd}`);
200
- }
201
- }
202
- return rows;
203
- }
204
- }
205
- /** The thinking fold — one dim line, width-capped so the /think suffix
206
- * rides the fold's own row (the #17 fix's slice, componentized). The
207
- * slice is DISPLAY-WIDTH-based (the char-based slice overflowed with
208
- * CJK — 2 cells per char — and tripped invariant ① on a real
209
- * Chinese session). W2: the leading ⋯ is the thinking gutter — the
210
- * midline mark (the state), never the text ellipsis (the truncation). */
211
- class ThinkingFold {
212
- cell;
213
- constructor(cell) {
214
- this.cell = cell;
215
- }
216
- render(W, _ctx) {
217
- const block = this.cell.text;
218
- const trimmed = escapeTerminal(block.trim());
219
- // the SHORT branch is width-aware TOO: the ≤100 short-circuit was
220
- // W-blind — a short block at a narrow width returned the line
221
- // UNFOLDED and tripped invariant ① (the crash class still live on
222
- // npm for short /think blocks after a resize).
223
- if (trimmed.length <= 100)
224
- return [`${palette().dim}⋯${widthCut(trimmed, Math.max(1, W - 1))}${palette().reset}`];
225
- const suffix = ` (${block.length} chars · /think)`;
226
- const slice = Math.max(1, W - 1 - suffix.length);
227
- return [`${palette().dim}⋯${widthCut(trimmed, slice)}${suffix}${palette().reset}`];
228
- }
229
- }
230
- /** Fold a line's CONTENT at W−2 and prefix EVERY row with the gutter
231
- * (W2: a wrapped tool row keeps its state mark — the left edge alone
232
- * distinguishes the states at --plain; the UserMessage rail precedent,
233
- * v5 #16f). The gutter carries its own SGR (e.g. the bold ✓). */
234
- function gutterFold(gutter, line, W) {
235
- const textW = Math.max(1, W - 2);
236
- return foldLine(line, textW).map((r) => `${gutter}${r}`);
237
- }
238
- /** Lines without the phantom empty line after a trailing newline. */
239
- function countLines(text) {
240
- if (text === "")
241
- return 0;
242
- const parts = text.split("\n");
243
- return parts[parts.length - 1] === "" ? parts.length - 1 : parts.length;
244
- }
245
- /** W4: the settled-row metadata — the human summary in parentheses. The
246
- * separation NEVER relies on dim: a pipe drops the SGR, and the shapes
247
- * below read at full strength with the palette off. read → the line
248
- * count ("912 lines"; "200 of 3412 lines" when the tool cut it — the
249
- * note names the remainder; ≥1000 k-formats, "2.4k lines"); write/edit
250
- * → the ± diff stats (the approval diff's counts — an auto-allowed
251
- * write never computed one, so the input's own counts fall back, then
252
- * the result's line count); shell → the exit code (parsed from the
253
- * failure text — the tool names it — 0 on success); a non-shell error
254
- * → the error text's first line; anything else → the result's line
255
- * count. */
256
- function settledMeta(c) {
257
- if (c.isError) {
258
- // a shell EXECUTION failure names its code first ("exit 1: …") —
259
- // that IS the metadata, and the body shows the full text. A
260
- // shell without the code (a denial, a precondition) is not an
261
- // exit failure: the first line stays the metadata, exactly like
262
- // any other error.
263
- if (c.name === "shell" && /^exit \d+/.test(c.resultText))
264
- return `exit ${/^exit (\d+)/.exec(c.resultText)[1]}`;
265
- return c.resultText.split("\n")[0].slice(0, 60);
266
- }
267
- if (c.name === "read_file") {
268
- const noteAt = c.resultText.lastIndexOf("\n… ");
269
- const shown = countLines(noteAt >= 0 ? c.resultText.slice(0, noteAt) : c.resultText);
270
- const more = noteAt >= 0 ? /(\d+) more lines?/.exec(c.resultText.slice(noteAt)) : null;
271
- const k = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n));
272
- if (more !== null) {
273
- const total = shown + Number(more[1]);
274
- return `${shown} of ${total} line${total === 1 ? "" : "s"}`;
275
- }
276
- return `${k(shown)} line${shown === 1 ? "" : "s"}`;
277
- }
278
- if (c.name === "write_file" || c.name === "edit_file") {
279
- if (c.added + c.removed > 0)
280
- return `+${c.added} -${c.removed}`;
281
- // no approval diff (an auto-allowed write): the input summary may
282
- // be sliced at TOOL_SUMMARY_MAX — best-effort, then the last resort
283
- let parsed = null;
284
- try {
285
- parsed = JSON.parse(c.input);
286
- }
287
- catch {
288
- parsed = null;
289
- }
290
- if (c.name === "write_file" && parsed !== null && typeof parsed.content === "string") {
291
- return `+${countLines(parsed.content)}`;
292
- }
293
- if (c.name === "edit_file" && parsed !== null && typeof parsed.search === "string" && typeof parsed.replace === "string") {
294
- const added = countLines(parsed.replace);
295
- const removed = countLines(parsed.search);
296
- if (added + removed > 0)
297
- return `+${added} -${removed}`;
298
- }
299
- }
300
- if (c.name === "shell")
301
- return "exit 0";
302
- const n = countLines(c.resultText);
303
- return `${n} line${n === 1 ? "" : "s"}`;
304
- }
305
- /** The tool execution line + the bounded block — every state is its
306
- * own render; the lines fold (the summary gives way first). W7 (the
307
- * flow contract): the block's BODY (the rows below the header) is
308
- * capped in SCREEN rows AFTER the fold, at the current width — the
309
- * renderer-cut row (`└ +N … · ctrl+r`) sits INSIDE the cap (a
310
- * truncated block is cap−1 output rows + the cut row); the TOOL-cut
311
- * row (`└ capped by …` — the tool's OWN truncation note, W10) is a
312
- * DIFFERENT fact, never counted in the output cap. W3: the verb is
313
- * stripped of its "_file" suffix and padded to 5 columns — the target
314
- * paths line up (the pipe path strips the same suffix, render.ts —
315
- * both paths print the same verb; a verb ≥ 5 columns is not padded).
316
- * The block's cut note keeps the RAW name (it names the tool the
317
- * model should call again). W4: the settled row's parentheses hold
318
- * the human metadata (settledMeta) — the input summary lived in the
319
- * running row; the OUTCOME is what the settled row says. */
320
- class ToolExecution {
321
- cell;
322
- constructor(cell) {
323
- this.cell = cell;
324
- }
325
- render(W, ctx) {
326
- const p = palette();
327
- const c = this.cell;
328
- const verb = escapeTerminal(c.name.replace("_file", ""));
329
- const verbCol = verb.length < 5 ? `${verb}${" ".repeat(5 - verb.length)}` : verb;
330
- const summary = escapeTerminal(c.input);
331
- if (c.rolled !== null) {
332
- // W13 — the rolled-up group's ONE row + the target children:
333
- // the work order's claimed shape, verbatim — the verbCol's
334
- // 5-char pad reproduces the "read 5 files" double space, the
335
- // children are the first 3 basename targets, the overflow row
336
- // carries the ctrl+r affordance (its "└ … ctrl+r" joins the
337
- // W15 expand history — the head's commit captures it).
338
- const r = c.rolled;
339
- const noun = ROLLUP_NOUN[c.name] ?? "calls";
340
- const out = gutterFold(`${p.bold}✓${p.reset} `, `${verbCol} ${r.count} ${noun} (${kUnit(r.lines)} lines, ${r.elapsed}s)`, W);
341
- const shown = r.targets.slice(0, 3);
342
- if (shown.length > 0)
343
- out.push(` ${p.dim}${CUT_ROW}${escapeTerminal(shown.join(" · "))}${p.reset}`);
344
- if (r.targets.length > 3)
345
- out.push(` ${p.dim}${CUT_ROW}+${r.targets.length - 3} more — ctrl+r expands${p.reset}`);
346
- return out;
347
- }
348
- if (c.state === "done") {
349
- // W19: the pinned deny — the claimed shape verbatim: the FULL
350
- // call name (the denial names the call), the target, the reason
351
- // in the W4 parentheses idiom, no timing (the call never ran).
352
- // The same ✗ family as any failure; the [result ✗] body still
353
- // rides below (never hide information).
354
- if (c.reason !== null) {
355
- let input = {};
356
- try {
357
- input = JSON.parse(c.inputFull);
358
- }
359
- catch {
360
- // the full JSON is always parseable (stringified at
361
- // toolStart) — the empty fallback never fires
362
- }
363
- const target = toolTarget(c.name, input);
364
- const out = gutterFold(`${p.red}✗${p.reset} `, `${p.red}${escapeTerminal(`${c.name} ${target}`)} (${escapeTerminal(c.reason)})${p.reset}`, W);
365
- out.push(...toolBlockBody(c, W));
366
- return out;
367
- }
368
- const elapsed = c.startedAt !== null && c.doneAt !== null ? ((c.doneAt - c.startedAt) / 1000).toFixed(1) : "?";
369
- const meta = escapeTerminal(settledMeta(c));
370
- const out = c.isError
371
- ? gutterFold(`${p.red}✗${p.reset} `, `${p.red}${verbCol} (${meta}, ${elapsed}s)${p.reset}`, W)
372
- : gutterFold(`${p.bold}✓${p.reset} `, `${verbCol} (${meta}, ${elapsed}s)`, W);
373
- out.push(...toolBlockBody(c, W));
374
- return out;
375
- }
376
- if (c.state === "approval") {
377
- // W2: the ⏸ is the GUTTER (the left edge), never the line's tail
378
- const out = gutterFold(`${p.bold}⏸${p.reset} `, `${verbCol} ${summary}`, W);
379
- out.push(...toolBlockBody(c, W));
380
- return out;
381
- }
382
- if (c.state === "running") {
383
- // W2: the spinner IS the gutter (the left edge); the elapsed
384
- // rides the summary's tail
385
- const elapsed = c.startedAt !== null ? Math.max(1, Math.round((ctx.now - c.startedAt) / 1000)) : 1;
386
- const out = gutterFold(`${p.bold}${SPINNER[ctx.spinnerI % SPINNER.length]}${p.reset} `, `${verbCol} ${summary} ${elapsed}s`, W);
387
- out.push(...toolBlockBody(c, W));
388
- return out;
389
- }
390
- // W2: ◦ replaces → for QUEUED — · is the separator inside every
391
- // metadata group; a queued marker that is also the separator
392
- // glyph reads as noise
393
- return gutterFold(`${p.dim}◦${p.reset} `, `${verbCol} ${summary}`, W);
394
- }
395
- }
396
- /** W13 — the rollup opt-in table: which tools collapse, and the count
397
- * NOUN (read_file calls → "5 files", list_dir → "5 dirs", search_text
398
- * → "5 matches"). Only these tools opt in — a shell burst is never
399
- * rolled up (its rows carry meaning). The folded-turn line (W14) reuses
400
- * the plurals for its other-tool terms ("2 dirs", "1 match"). */
401
- export const ROLLUP_NOUN = {
402
- read_file: "files",
403
- list_dir: "dirs",
404
- search_text: "matches",
405
- };
406
- /** The count term with the singular/plural forms — "no reads", "1 read",
407
- * "5 reads". The noun's singular drops the plural suffix ("dirs" → "dir",
408
- * "matches" → "match"). */
409
- function countTerm(n, singular, plural) {
410
- if (n === 0)
411
- return `no ${plural}`;
412
- if (n === 1)
413
- return `1 ${singular}`;
414
- return `${n} ${plural}`;
415
- }
416
- /** W14 — the folded-turn line: a whole QUIET turn (no text), once it is
417
- * scrollback, becomes ONE line — the work order's claimed shape
418
- * (`▞ thought 19s · 5 reads · no edits`), the counts accumulated at
419
- * toolStart: read_file → "reads", edit_file → "edits", the other tools
420
- * as first-call-order terms (the ROLLUP_NOUN plurals when the tool opts
421
- * in, the verb + "s" otherwise). */
422
- export function turnFold(t) {
423
- const p = palette();
424
- const parts = [`thought ${t.thoughtSeconds}s`, countTerm(t.reads, "read", "reads"), countTerm(t.edits, "edit", "edits")];
425
- for (const [name, n] of t.others) {
426
- const noun = ROLLUP_NOUN[name];
427
- if (noun !== undefined) {
428
- parts.push(countTerm(n, noun.endsWith("es") ? noun.slice(0, -2) : noun.slice(0, -1), noun));
429
- }
430
- else {
431
- const verb = name.replace("_file", "");
432
- parts.push(countTerm(n, verb, `${verb}s`));
433
- }
434
- }
435
- return [`${p.bold}▞${p.reset} ${parts.join(" · ")}`];
436
- }
437
- // ---- the bounded-block flow contract (W7, W8, W10) ----
438
- /** The caps — screen rows counted AFTER the fold, at the current width
439
- * (the W7 table). The renderer-cut row is inside the cap. */
440
- const CAP_SHELL_SETTLED = 5; // the shell output tail, settled
441
- const CAP_LIVE_WINDOW = 3; // the running tool's FIXED window (W8)
442
- const CAP_DIFF = 12; // the approval diff: head + the named middle + tail
443
- const CAP_ERROR = 3; // the error text head
444
- /** The block body rows' prefixes (W2's gutter table): │ a bounded
445
- * block's body, └ the block's last row — what was cut, where the rest
446
- * is — at the LEFT EDGE (the gutter column: the left edge alone
447
- * distinguishes the states at --plain). Structural (constraint 1). */
448
- const BODY_ROW = "│ ";
449
- const CUT_ROW = "└ ";
450
- const blockMemo = new WeakMap();
451
- /** The block's body rows below the header (memoized, W9). */
452
- function toolBlockBody(c, W) {
453
- const memo = blockMemo.get(c);
454
- const state = `${c.state}:${c.isError}:${c.name}:${c.expanded ? "x" : ""}`;
455
- const content = c.state === "approval" ? (c.diff ?? null) : c.resultText;
456
- if (memo !== undefined && memo.width === W && memo.state === state && memo.content === content)
457
- return memo.rows;
458
- const p = palette();
459
- const rows = c.expanded
460
- ? // W15: the toggle's full form — the WHOLE body, no cap, no
461
- // cut note (nothing is cut; the width fold still holds — the
462
- // height may change while live, the user asked for it). The
463
- // delegate has no body — its rows are unchanged.
464
- c.state === "approval"
465
- ? diffBody(c.diff, W, true)
466
- : c.name === "delegate"
467
- ? c.state === "running"
468
- ? delegateRunning(c, W)
469
- : delegateSettled(c, W)
470
- : blockRows(c.resultText, W)
471
- : c.state === "done"
472
- ? c.isError
473
- ? errorBody(c, W)
474
- : c.name === "delegate"
475
- ? delegateSettled(c, W)
476
- : c.name.startsWith("shell")
477
- ? shellTail(c.resultText, W)
478
- : []
479
- : c.state === "running"
480
- ? c.name === "delegate"
481
- ? delegateRunning(c, W)
482
- : liveWindow(c.resultText, W)
483
- : c.state === "approval"
484
- ? diffBody(c.diff, W)
485
- : [];
486
- const note = c.expanded ? null : toolCutNote(c.name, c.resultText);
487
- if (note !== null)
488
- rows.push(...foldLine(`${p.dim}${CUT_ROW}${note}${p.reset}`, W));
489
- blockMemo.set(c, { width: W, state, content, rows });
490
- return rows;
491
- }
492
- /** Fold result text into dim body rows (the BODY_ROW prefix): escape,
493
- * split, fold each line at W−prefix; trailing empty rows (the result's
494
- * final newline) drop. */
495
- function blockRows(text, W) {
496
- const p = palette();
497
- const textW = Math.max(1, W - visibleWidth(BODY_ROW));
498
- const rows = [];
499
- for (const raw of escapeTerminal(text).split("\n")) {
500
- for (const row of foldLine(raw, textW))
501
- rows.push(`${p.dim}${BODY_ROW}${row}${p.reset}`);
502
- }
503
- while (rows.length > 0 && visibleWidth(rows[rows.length - 1]) === visibleWidth(BODY_ROW))
504
- rows.pop();
505
- return rows;
506
- }
507
- /** The shell output tail, settled: the LAST rows, capped at 5 — the
508
- * renderer cut at the block's bottom ("earlier rows" — the conclusion
509
- * is at the end, pi's truncateToVisualLines direction). */
510
- function shellTail(text, W) {
511
- const p = palette();
512
- const rows = blockRows(text, W);
513
- if (rows.length <= CAP_SHELL_SETTLED)
514
- return rows;
515
- const kept = CAP_SHELL_SETTLED - 1;
516
- const cut = foldLine(`${p.dim}${CUT_ROW}+${rows.length - kept} earlier rows · ctrl+r${p.reset}`, W);
517
- return [...rows.slice(rows.length - kept), ...cut];
518
- }
519
- /** The error text head: the FIRST rows, capped at 3 — the answer is at
520
- * the start (opencode's collapseToolOutput direction). The header row
521
- * already summarizes the first line, so the body starts at line 2. */
522
- function errorBody(c, W) {
523
- const p = palette();
524
- // W4: a shell EXECUTION failure's line 0 ("exit 1: …") no longer
525
- // rides the header — the parsed code does — so the body keeps the
526
- // FULL text. Any other error keeps the pre-W4 split: line 0 is the
527
- // header's metadata, the body shows the rest.
528
- // W19: a DENIED call's header meta is the PARSED reason (from the
529
- // denied tag), decoupled from the result text — the body keeps the
530
- // FULL content including the "[Permission denied] " prefix (never
531
- // hide information — the folded body rides the pinned row).
532
- const skipFirst = c.name === "shell" && /^exit \d+/.test(c.resultText) ? 0 : c.reason !== null && c.reason !== undefined ? 0 : 1;
533
- const rows = blockRows(c.resultText.split("\n").slice(skipFirst).join("\n"), W);
534
- if (rows.length <= CAP_ERROR)
535
- return rows;
536
- const cut = foldLine(`${p.dim}${CUT_ROW}+${rows.length - (CAP_ERROR - 1)} more · ctrl+r${p.reset}`, W);
537
- return [...rows.slice(0, CAP_ERROR - 1), ...cut];
538
- }
539
- /** The running tool's FIXED-height window (W8): exactly 3 rows from
540
- * the FIRST frame — blank-padded before output arrives, the renderer
541
- * cut inside the window. The height changes exactly once, at settle —
542
- * a cell that grows mid-list would shift every row after it on every
543
- * delta (the parallel-tools jitter). */
544
- function liveWindow(text, W) {
545
- const p = palette();
546
- if (text === "") {
547
- return [`${p.dim}${BODY_ROW}${p.reset}`, `${p.dim}${BODY_ROW}${p.reset}`, `${p.dim}${CUT_ROW}waiting for output${p.reset}`];
548
- }
549
- const rows = blockRows(text, W);
550
- if (rows.length <= CAP_LIVE_WINDOW) {
551
- while (rows.length < CAP_LIVE_WINDOW)
552
- rows.push(`${p.dim}${BODY_ROW}${p.reset}`);
553
- return rows;
554
- }
555
- const cut = foldLine(`${p.dim}${CUT_ROW}+${rows.length - (CAP_LIVE_WINDOW - 1)} earlier rows · ctrl+r${p.reset}`, W);
556
- return [...rows.slice(rows.length - (CAP_LIVE_WINDOW - 1)), ...cut];
557
- }
558
- /** W12: the delegate's child sessions collapse to the tool row plus ONE
559
- * line — the height NEVER changes (running → settled replaces the row
560
- * in place). The running row derives from the INPUT: the parent has no
561
- * live channel to a running child (ToolContext carries only
562
- * signal/sessionId; execute returns ONE result), so the roles are the
563
- * honest current data — the spec's "<child's current tool>" has no
564
- * event source. The settled row parses the extension's summary marker
565
- * (the blob's first line) — its absence falls back to no body (an old
566
- * extension's output still renders). The one-line shape is shared with
567
- * W18's status row (the work order: "implement them with one helper"). */
568
- function delegateRunning(c, W) {
569
- const p = palette();
570
- const n = c.childRoles.length;
571
- const text = n === 0 ? "children running…" : `${n === 1 ? "1 child" : `${n} children`} · ${c.childRoles.join(" · ")}`;
572
- return [oneLineRow(p, text, W)];
573
- }
574
- function delegateSettled(c, W) {
575
- const p = palette();
576
- const m = /^summary: (.+)$/m.exec(c.resultText);
577
- if (m === null)
578
- return [];
579
- return [oneLineRow(p, `${m[1]} · /last for the report`, W)];
580
- }
581
- /** ONE row at the left gutter, truncated to fit the width — never a
582
- * fold (a fold would wrap into TWO rows and break the one-line height
583
- * contract). */
584
- function oneLineRow(p, text, W) {
585
- const esc = escapeTerminal(text);
586
- if (visibleWidth(`${p.dim}${CUT_ROW}${esc}${p.reset}`) <= W)
587
- return `${p.dim}${CUT_ROW}${esc}${p.reset}`;
588
- const w = Math.max(1, W - visibleWidth(`${p.dim}${CUT_ROW}${p.reset}`));
589
- return `${p.dim}${CUT_ROW}${esc.slice(0, w - 1)}…${p.reset}`;
590
- }
591
- /** The approval mini-diff (W7): capped at 12 folded rows — the head +
592
- * the named middle (the renderer cut — what was cut, how to expand) +
593
- * the tail. The rows are folded at the current width BEFORE the cap —
594
- * the R1 measured bug: truncateDiff capped at 40 ENTRIES while the
595
- * fold turned them into 73 SCREEN rows at W≤80 (a 44-row terminal's
596
- * content cap is H−4 = 40 — the approval force-committed a third of
597
- * the screen into scrollback inside one frame).
598
- * W17: the cap is a ROW budget at every width — the └ cut is ONE line
599
- * (a folded cut pushed the total past 12 at narrow widths), and below
600
- * a floor of 3 SOURCE lines visible the head/tail pair is noise (each
601
- * fragment a sliver of a long line): drop to the head only — the head
602
- * takes the whole budget — and the └ row carries the rest. */
603
- function diffBody(diff, W, expanded = false) {
604
- const p = palette();
605
- if (diff === null)
606
- return [];
607
- const rows = [];
608
- // W17: each line's fold START row (the running total) — the pair
609
- // floor reads it for the head/tail SOURCE-line counts below.
610
- const starts = [0];
611
- for (const d of diff) {
612
- const body = d.kind === "-"
613
- ? `${p.red}- ${escapeTerminal(d.text)}${p.reset}`
614
- : d.kind === "+"
615
- ? `${p.green}+ ${escapeTerminal(d.text)}${p.reset}`
616
- : `${p.dim} ${escapeTerminal(d.text)}${p.reset}`;
617
- // W2: the diff body is a bounded block's body — the │ gutter
618
- // (dim), never the old bold ▎ rail (the table lists no ▎); the
619
- // +/- marks and their colors ride the content
620
- rows.push(...gutterFold(`${p.dim}│${p.reset} `, body, W));
621
- starts.push(rows.length);
622
- }
623
- if (expanded || rows.length <= CAP_DIFF)
624
- return rows;
625
- const head = Math.floor((CAP_DIFF - 1) / 2);
626
- const tail = CAP_DIFF - 1 - head;
627
- // W17: the └ cut is ONE row at every width — the count leads, the
628
- // expand affordances are cuttable (the same one-line shape as W12's
629
- // delegate row and W18's status row).
630
- const cut = (n) => oneLineRow(p, `+${n} rows · ctrl+r to expand · /last for the full diff`, W);
631
- // W17: the floor — the head window shows the lines whose fold starts
632
- // before `head` rows; the tail window the lines whose fold ENDS after
633
- // `rows.length - tail` (starts[i+1] is line i's end). When the pair
634
- // shows fewer than 3 SOURCE lines together, it is noise at this width
635
- // (each fragment a sliver of a long line): drop to the head only —
636
- // the head takes the whole budget, the └ row carries the rest.
637
- if (starts.filter((s) => s < head).length + starts.slice(1).filter((s) => s > rows.length - tail).length < 3)
638
- return [...rows.slice(0, CAP_DIFF - 1), cut(rows.length - (CAP_DIFF - 1))];
639
- return [...rows.slice(0, head), cut(rows.length - head - tail), ...rows.slice(rows.length - tail)];
640
- }
641
- /** The TOOL's OWN truncation note (W10) — a different fact from the
642
- * renderer's cut: the tools truncate and append a continuation note
643
- * (packages/tools-node/src/index.ts — read_file's "call again with
644
- * offset=N", the output cap, list_dir's entry cap). The note reaches
645
- * the MODEL and never the human — this row surfaces it. Detected in
646
- * the result's TAIL (the note is appended at the end); returns null
647
- * when the tool did not truncate. */
648
- function toolCutNote(name, resultText) {
649
- const tail = resultText.slice(-300);
650
- const m = /offset=(\d+)/.exec(tail);
651
- if (m !== null)
652
- return `capped by ${escapeTerminal(name)} · offset=${m[1]} for the rest`;
653
- if (/…\[truncated\]/.test(tail) || /… \+?\d+ more (?:lines|entries)/.test(tail))
654
- return `capped by ${escapeTerminal(name)} · /last for the rest`;
655
- return null;
656
- }
657
- /** The assistant body text — wrapped at W, the inline-code tint per
658
- * row (the #16e rule: a span never matches across rows). */
659
- class AssistantMessage {
660
- cell;
661
- constructor(cell) {
662
- this.cell = cell;
663
- }
664
- render(W, _ctx) {
665
- const text = escapeTerminal(this.cell.text);
666
- const wrapped = foldLine(text, W);
667
- return wrapped.length > 0 ? wrapped.map((l) => colorInlineCode(l)) : [""];
668
- }
669
- }
670
- /** The ⚠ / notice lines — the error surface. */
671
- class ErrorLine {
672
- cell;
673
- constructor(cell) {
674
- this.cell = cell;
675
- }
676
- render(W, _ctx) {
677
- return foldLine(escapeTerminal(this.cell.text), W);
678
- }
679
- }
680
- /** The CLI's pre-rendered blocks (the banner, the recap, slash-command
681
- * output) — the SGR applied at composition (render.ts), folded here
682
- * verbatim: the #16b contract (no re-escaping) holds, and the fold is
683
- * SGR-aware so the accent spans survive a break. */
684
- class RawBlock {
685
- cell;
686
- constructor(cell) {
687
- this.cell = cell;
688
- }
689
- render(W, _ctx) {
690
- return this.cell.lines.flatMap((l) => foldLine(l, W));
691
- }
692
- }
693
- /** The terminal label + the status line. W11: the rhythm gap blank is
694
- * gone — the container's formula breathes below a multi-row cell (the
695
- * terminal is always multi-row when labelled), never the component. */
696
- class TerminalBlock {
697
- cell;
698
- constructor(cell) {
699
- this.cell = cell;
700
- }
701
- render(W, _ctx) {
702
- return [...foldLine(this.cell.label, W), ...foldLine(this.cell.line, W)];
703
- }
704
- }
705
- /** The startup banner — a LIVE cell: every render re-derives the tier
706
- * from the CURRENT width AND height (bannerLines), so a resize re-tiers
707
- * the art instead of re-folding frozen rows (the W1 tier table: below
708
- * 40 cols the logo never paints). W11: no trailing blank — the
709
- * container's formula breathes below the (always multi-row) banner. */
710
- class Banner {
711
- cell;
712
- constructor(cell) {
713
- this.cell = cell;
714
- }
715
- render(W, ctx) {
716
- const p = palette();
717
- const rows = bannerLines(W, ctx.height, this.cell.version, this.cell.extensionsText, this.cell.resume, ctx.now);
718
- return rows.map((r) => `${p.dim}${r}${p.reset}`);
719
- }
720
- }
721
- /** W20 — the task block's fixed-window height: the whole live block
722
- * (header + rows) in POST-FOLD screen rows at EVERY width: the header,
723
- * the active row, up to 2 pending, the overflow-pending fold, the
724
- * done-collapse. Every live row CUTS at W (never folds) — the block's
725
- * height is its row count. */
726
- export const CAP_TASK_LIVE = 6;
727
- /** W20 — the live block's fixed-window row cut: an SGR-aware ONE-ROW
728
- * truncation (foldLine wraps; a wrapped row would break the height
729
- * cap — every live row is exactly one screen row at every width).
730
- * A line that fits (≤ W) passes through whole; an overflow cuts the
731
- * content at W−1 — the ellipsis's slot — and the ellipsis rides AFTER
732
- * the reset (post-reset — the PTY needles' convention). The cut row
733
- * never exceeds W (invariant ①). */
734
- function cutLine(line, W) {
735
- if (visibleWidth(line) <= W)
736
- return line;
737
- let out = "";
738
- let width = 0;
739
- for (let i = 0; i < line.length;) {
740
- if (line[i] === "\x1b") {
741
- const m = /^\x1b\[[0-9;]*m/.exec(line.slice(i)) ?? line[i];
742
- out += m;
743
- i += m.length;
744
- continue;
745
- }
746
- const cw = displayWidth(line[i]);
747
- if (width + cw > W - 1)
748
- break; // reserve the ellipsis's column
749
- out += line[i];
750
- width += cw;
751
- i += 1;
752
- }
753
- return `${out}\x1b[0m…`;
754
- }
755
- /** W20 — the settled block's duration, the `2h 14m` form (the task
756
- * narrative's long-horizon idiom): minutes+seconds under an hour,
757
- * hours+minutes past it. */
758
- export function formatDuration(totalSeconds) {
759
- const s = Math.max(0, Math.round(totalSeconds));
760
- if (s < 60)
761
- return `${s}s`;
762
- const m = Math.floor(s / 60);
763
- return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m`;
764
- }
765
- /**
766
- * W20 — the task checklist as STATE: ONE live block that redraws in
767
- * place (the current turn's in-place updates), settling at the turn's
768
- * end as ONE recap block. LIVE (done:false): the fixed "task" prefix +
769
- * the compositor-derived counts (the model tail rides AFTER — never
770
- * model-controlled), the active item first with ▸ (the menu's "the
771
- * current one"), pending next (≤2), the done items COLLAPSED behind the
772
- * W10 cut family `└ +N done · ctrl+r`, overflow pending behind
773
- * `└ +N more · ctrl+r` — every row cut at W so the cap holds at every
774
- * width. ctrl+r (W15) toggles the full list in place (expanded). SETTLED
775
- * (done:true): the recap idiom `task done · N items · <duration>` + the
776
- * FULL final item list in the checklist's existing shape (▖/□/▣ —
777
- * indented two, the glyph leads, no │ gutter).
778
- */
779
- class Checklist {
780
- cell;
781
- constructor(cell) {
782
- this.cell = cell;
783
- }
784
- render(W, _ctx) {
785
- const p = palette();
786
- const { items, done, expanded, durationSeconds } = this.cell;
787
- const active = items.filter((i) => i.status === "active");
788
- const pending = items.filter((i) => i.status === "pending");
789
- const doneCount = items.length - active.length - pending.length;
790
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
791
- const tail = this.cell.header === "" ? "" : ` · ${this.cell.header}`;
792
- const fixed = done
793
- ? `task done · ${plural(items.length, "item")} · ${formatDuration(durationSeconds)}`
794
- : `task · ${plural(items.length, "item")} · ${active.length} active · ${doneCount} done`;
795
- const header = `${p.bold}▞${p.reset} ${escapeTerminal(fixed + tail)}`;
796
- // the FULL-list forms: SETTLED — the durable record (the fold is
797
- // fine — committed content wraps naturally) — and the LIVE ctrl+r
798
- // toggle (the header CUTS — the block stays one window high; the
799
- // expanded rows show the ▣ the collapse hid). The live flag picks
800
- // the glyphs: the settled list keeps the durable ▖, the expanded
801
- // live list the ▸.
802
- const glyph = (status, live) => {
803
- const g = status === "pending" ? "□" : status === "active" ? (live ? "▸" : "▖") : "▣";
804
- return g === "▸" ? `${p.bold}▸${p.reset}` : g;
805
- };
806
- if (done || expanded) {
807
- const rows = done ? foldLine(header, W) : [cutLine(header, W)];
808
- for (const item of items)
809
- rows.push(...foldLine(` ${glyph(item.status, !done)} ${escapeTerminal(item.text)}`, W));
810
- return rows;
811
- }
812
- // LIVE — the fixed window: the header + the item rows CUT at W
813
- // (one screen row each — the block's height is its row count,
814
- // CAP_TASK_LIVE, at every width). The cut is the momentary view;
815
- // the settle (and the ctrl+r toggle) show everything.
816
- const itemRows = [];
817
- if (active.length > 0)
818
- itemRows.push(` ${p.bold}▸${p.reset} ${escapeTerminal(active[0].text)}`);
819
- for (const item of pending.slice(0, 2))
820
- itemRows.push(` □ ${escapeTerminal(item.text)}`);
821
- const more = pending.length - 2;
822
- if (more > 0)
823
- itemRows.push(` ${p.dim}└ +${more} more · ctrl+r${p.reset}`);
824
- if (doneCount > 0)
825
- itemRows.push(` ${p.dim}└ +${doneCount} done · ctrl+r${p.reset}`);
826
- return [cutLine(header, W), ...itemRows.map((r) => cutLine(r, W))];
827
- }
828
- }
829
- // ---- the chrome components (the status container, the slot, the footer) ----
830
- /** The status container's row: the status text (+ the tail) with the
831
- * right-aligned "/ commands · ↑ history" hint in the idle state —
832
- * the hint CUT FIRST when the width is short (the #16g rule); when
833
- * the STATUS ITSELF cannot fit, it cuts with a "…" — the last resort,
834
- * enforced by invariant ① (the old code let the status soft-wrap). */
835
- export function statusLine(status, tail, question, W, hint) {
836
- const p = palette();
837
- const text = `${status}${tail === "" ? "" : ` · ${tail}`}`;
838
- if (question)
839
- return `${p.dim}${widthCut(text, W)}${p.reset}`;
840
- // W18: the hint is a parameter — the compacting row right-aligns its
841
- // "esc to cancel" (the same one-line-bounded shape as W12's delegate
842
- // row; the #16g rule still cuts the HINT first, then the status with
843
- // a "…" — never a fold).
844
- const hintText = hint ?? " / commands · ↑ history";
845
- const statusW = visibleWidth(text);
846
- if (statusW > W) {
847
- return `${p.dim}${widthCut(text, W - 1)}…${p.reset}`;
848
- }
849
- const hintW = visibleWidth(hintText);
850
- if (statusW + hintW > W)
851
- return `${p.dim}${text}${p.reset}`;
852
- return `${p.dim}${text}${" ".repeat(Math.max(0, W - statusW - hintW))}${hintText}${p.reset}`;
853
- }
854
- /** The display-width prefix of a plain (SGR-free) text. */
855
- function widthCut(text, max) {
856
- let w = 0;
857
- let i = 0;
858
- for (; i < text.length; i += 1) {
859
- const cw = displayWidth(text[i]);
860
- if (w + cw > max)
861
- break;
862
- w += cw;
863
- }
864
- return text.slice(0, i);
865
- }
866
- /** W6 — the box: the chrome's top rail. The two ╌ dotted rows become
867
- * a rounded box (the box already says "input lives here"); the rails
868
- * stay dim, the width is still the full W (the box is a rail with
869
- * corners — the menu/gap rows above and the status below are
870
- * untouched). */
871
- export function boxTop(W) {
872
- return `\x1b[2m╭${"─".repeat(Math.max(0, W - 2))}╮\x1b[0m`;
873
- }
874
- /** W6 — the box: the chrome's bottom rail. */
875
- export function boxBottom(W) {
876
- return `\x1b[2m╰${"─".repeat(Math.max(0, W - 2))}╯\x1b[0m`;
877
- }
878
- /** The terminal label + rhythm gap (the pipe path's v2c bytes — the
879
- * exact render the passthrough needs). */
880
- export function terminalPipe(label, statusLineText) {
881
- return label + renderTerminalGap(statusLineText);
882
- }
883
- /** The pipe-path pieces the passthrough reuses (byte-identical). */
884
- export { foldThinking, foldResult, renderToolSummary, TOOL_SUMMARY_MAX };
1
+ /** The components cell renderer moved to tui-cells (ADR-0043
2
+ * Amendment 4) — this module is the re-export shim: the compositor's
3
+ * and index.ts's imports (./components.js) stay verbatim. */
4
+ export * from "@vincemakes/kiso-tui-cells/components";