@aeondave/pi-theme-1337 0.0.0-stage → 0.5.1

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 (55) hide show
  1. package/CHANGELOG.md +253 -0
  2. package/LICENSE +21 -0
  3. package/README.md +159 -2
  4. package/assets/banner.png +0 -0
  5. package/assets/palettes.gif +0 -0
  6. package/docs/architecture.md +167 -0
  7. package/docs/configuration.md +87 -0
  8. package/docs/palette-design.md +51 -0
  9. package/docs/theme-motion.md +88 -0
  10. package/package.json +68 -4
  11. package/src/avatar.ts +174 -0
  12. package/src/background.ts +82 -0
  13. package/src/config.ts +357 -0
  14. package/src/diff-spans.ts +77 -0
  15. package/src/editor.ts +443 -0
  16. package/src/format.ts +464 -0
  17. package/src/frame.ts +380 -0
  18. package/src/index.ts +1195 -0
  19. package/src/quota.ts +581 -0
  20. package/src/redraw-guard.ts +79 -0
  21. package/src/run-summary.ts +623 -0
  22. package/src/spinner.ts +72 -0
  23. package/src/terminal-title.ts +67 -0
  24. package/src/tool-activity.ts +216 -0
  25. package/src/tool-adapter.ts +491 -0
  26. package/src/tool-groups.ts +192 -0
  27. package/src/tool-lexicon.ts +200 -0
  28. package/src/tool-view.ts +788 -0
  29. package/src/width.ts +246 -0
  30. package/themes/1337-amber.json +94 -0
  31. package/themes/1337-amber.pi1337 +3 -0
  32. package/themes/1337-cosmos.json +94 -0
  33. package/themes/1337-cosmos.pi1337 +3 -0
  34. package/themes/1337-cyber.json +94 -0
  35. package/themes/1337-cyber.pi1337 +3 -0
  36. package/themes/1337-cyberpunk-2077-edgerunner.json +94 -0
  37. package/themes/1337-cyberpunk-2077-edgerunner.pi1337 +7 -0
  38. package/themes/1337-cyberpunk-2077.json +94 -0
  39. package/themes/1337-cyberpunk-2077.pi1337 +7 -0
  40. package/themes/1337-fallout.json +94 -0
  41. package/themes/1337-fallout.pi1337 +4 -0
  42. package/themes/1337-ice.json +94 -0
  43. package/themes/1337-ice.pi1337 +3 -0
  44. package/themes/1337-magma.json +94 -0
  45. package/themes/1337-magma.pi1337 +1 -0
  46. package/themes/1337-neon.json +94 -0
  47. package/themes/1337-neon.pi1337 +3 -0
  48. package/themes/1337-poison.json +94 -0
  49. package/themes/1337-poison.pi1337 +3 -0
  50. package/themes/1337-skynet-dark.json +94 -0
  51. package/themes/1337-skynet-dark.pi1337 +4 -0
  52. package/themes/1337-skynet.json +94 -0
  53. package/themes/1337-skynet.pi1337 +4 -0
  54. package/themes/1337.json +95 -0
  55. package/themes/1337.pi1337 +3 -0
@@ -0,0 +1,788 @@
1
+ /** Pure, standalone transcript views. Execution and image rendering remain the host's. */
2
+ import type { Theme, ThemeBg, ThemeColor, ToolRenderers } from "@earendil-works/pi-coding-agent";
3
+ import type { Component } from "@earendil-works/pi-tui";
4
+ import {
5
+ codePointAtIndex,
6
+ formatDuration,
7
+ isLineSeparator,
8
+ isLoneSurrogate,
9
+ isUnsafeCodePoint,
10
+ plural,
11
+ recordOf,
12
+ sanitizeInlineText,
13
+ skipTerminalSequence,
14
+ textOf,
15
+ } from "./format.ts";
16
+ import { changedSpans, type DiffSpan } from "./diff-spans.ts";
17
+ import { toolWords } from "./tool-lexicon.ts";
18
+ import { clipTextRows, stripAnsi, truncateToWidth, visibleWidth } from "./width.ts";
19
+
20
+ export type CallContext = Parameters<NonNullable<ToolRenderers["renderCall"]>>[2];
21
+ type ToolResult = Parameters<NonNullable<ToolRenderers["renderResult"]>>[0];
22
+ type Row = {
23
+ text: string;
24
+ color: ThemeColor;
25
+ background?: ThemeBg;
26
+ dot?: ThemeColor;
27
+ wrap?: boolean;
28
+ /**
29
+ * Plain sanitized text painted `dim` right after a non-wrapping row's text, so
30
+ * metadata recedes behind the title. Rungs, widest first: the first that fits
31
+ * whole beside the title is shown, and none is ever clipped.
32
+ */
33
+ meta?: readonly string[];
34
+ /**
35
+ * Fuller spellings of a non-wrapping row, widest first, each shown only whole
36
+ * (with the first meta rung that still fits beside it); `text` is the fallback.
37
+ */
38
+ texts?: readonly string[];
39
+ /** A non-wrapping row whose END matters: when it does not fit it is cut from the left. */
40
+ tail?: boolean;
41
+ incomplete?: boolean;
42
+ emphasis?: DiffSpan[];
43
+ highlight?: (text: string, offset: number, theme: Theme) => string | undefined;
44
+ /**
45
+ * Already painted spellings of a non-wrapping, multi-colored row, widest
46
+ * first: the first that fits is shown untouched (repainting would break its
47
+ * inner colors). Only the last is truncated, and only when none fits. A
48
+ * last rung of "" always fits and emits no line at all: whole or absent.
49
+ */
50
+ painted?: readonly string[];
51
+ };
52
+ export type ViewRow = Row;
53
+ const PREVIEW_ROWS = 16;
54
+ const PREVIEW_CHARS = 8192;
55
+ const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: "grapheme" });
56
+
57
+ // Bound the input as well as the output: an unterminated control string must not
58
+ // make a one-row header scan megabytes of otherwise invisible payload.
59
+ const label = (value: unknown): string => sanitizeInlineText(textOf(value).slice(0, PREVIEW_CHARS));
60
+
61
+ /** A tool's path argument as its row prints it: sanitized, forward slashes, relative to `cwd` when inside it. */
62
+ export function pathLabel(value: unknown, cwd: string): string {
63
+ const path = label(value).replaceAll("\\", "/");
64
+ const root = label(cwd).replaceAll("\\", "/").replace(/\/+$/, "");
65
+ const windows = /^[a-z]:\//i.test(root) || root.startsWith("//");
66
+ const compare = (s: string) => windows ? s.toLowerCase() : s;
67
+ if (path && root && compare(path) === compare(root)) return ".";
68
+ if (root && compare(path).startsWith(`${compare(root)}/`)) return path.slice(root.length + 1);
69
+ return path || ".";
70
+ }
71
+
72
+ /**
73
+ * Spell every unsafe code point (and LS/PS, and an unpaired surrogate) as visible
74
+ * `\uXXXX` text: arguments are shown for inspection, so a hidden control is named,
75
+ * not dropped. Copies verbatim runs; expanded arguments may be megabytes.
76
+ */
77
+ export function safeExpandedText(text: string): string {
78
+ let out = "";
79
+ let run = 0;
80
+ for (let i = 0; i < text.length;) {
81
+ const cp = codePointAtIndex(text, i);
82
+ const size = cp > 0xffff ? 2 : 1;
83
+ if (cp !== 0x0a && (isUnsafeCodePoint(cp) || isLineSeparator(cp) || isLoneSurrogate(cp))) {
84
+ out += text.slice(run, i) + `\\u${cp.toString(16).padStart(4, "0")}`;
85
+ run = i + size;
86
+ }
87
+ i += size;
88
+ }
89
+ return out + text.slice(run);
90
+ }
91
+
92
+ /**
93
+ * Arguments are model output: a BigInt or a cycle makes JSON.stringify throw,
94
+ * and this runs inside render. Same placeholder as the adapter's fallback row.
95
+ */
96
+ function expandedArguments(args: Record<string, unknown>): string {
97
+ let json: string;
98
+ try { json = JSON.stringify(args, null, 2) ?? ""; } catch { json = "[unavailable arguments]"; }
99
+ return safeExpandedText(json);
100
+ }
101
+
102
+ function heading(name: string, args: Record<string, unknown>, cwd: string): string {
103
+ const verb = toolWords(name)?.title;
104
+ if (!verb) return label(name) || "Tool";
105
+ switch (name) {
106
+ case "bash": return `${verb} ${commandTitle(args.command)}`;
107
+ case "grep": case "find": return `${verb} “${label(args.pattern)}” in ${pathLabel(args.path, cwd)}`;
108
+ case "read": return `${verb} ${pathLabel(args.path, cwd)}${label(readRange(args.offset, args.limit))}`;
109
+ default: return `${verb} ${pathLabel(args.path, cwd)}`;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * A script's first line, not its lines folded into one: "set -e for f in …"
115
+ * reads as another command. " …" says more lines follow (the expanded row
116
+ * prints them). Only a bounded head is inspected; a head that ends past the
117
+ * first line is itself more of the script.
118
+ */
119
+ function commandTitle(value: unknown): string {
120
+ const command = textOf(value);
121
+ const head = command.slice(0, PREVIEW_CHARS);
122
+ let first = "";
123
+ for (const { start, end } of lineSpans(head)) {
124
+ const line = label(head.slice(start, end));
125
+ if (!line) continue;
126
+ if (first) return `${first} …`;
127
+ if (end === head.length && command.length > head.length) return line; // the first line runs past the head
128
+ first = line;
129
+ if (end < head.length && command.length > head.length) return `${first} …`;
130
+ }
131
+ return first;
132
+ }
133
+
134
+ /** The host shell's own ceiling (`MAX_TIMEOUT_MS` in its bash tool): a longer timeout is refused, never run. */
135
+ const MAX_TIMEOUT_MS = 2_147_483_647;
136
+
137
+ /**
138
+ * Stock Pi's ` (timeout 30s)` for a command that is still running, as one meta
139
+ * rung. The argument is the model's, so only what the host's shell would run
140
+ * is shown — a finite, positive number of seconds within its ceiling — and it
141
+ * is spelled here, to the millisecond the host schedules: digits and a
142
+ * decimal point, never the raw value. "" for anything else.
143
+ */
144
+ function timeoutRung(value: unknown): string {
145
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value * 1000 > MAX_TIMEOUT_MS) return "";
146
+ const seconds = Math.round(value * 1000) / 1000;
147
+ return seconds > 0 ? ` (timeout ${seconds}s)` : "";
148
+ }
149
+
150
+ /** Stock Pi's read range (`formatReadLineRange`), mirrored: `:110-131`, `:110`, or "" when malformed. */
151
+ function readRange(offset: unknown, limit: unknown): string {
152
+ if (offset == null && limit == null) return "";
153
+ const start = offset == null ? 1 : lineNumber(offset);
154
+ if (start === undefined) return "";
155
+ if (limit == null) return `:${start}`;
156
+ const count = lineNumber(limit);
157
+ if (count === undefined) return "";
158
+ const end = start + count - 1;
159
+ return `:${start}${end ? `-${end}` : ""}`;
160
+ }
161
+
162
+ function lineNumber(value: unknown): number | undefined {
163
+ if (typeof value === "string" && value.trim() !== "") value = Number(value);
164
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
165
+ }
166
+
167
+ /** The role of the status dot every row of this package leads with. */
168
+ export function statusRole(context: CallContext): ThemeColor {
169
+ if (context.isError) return "error";
170
+ if (!context.isPartial) return "success"; // includes resumed results without timing
171
+ return context.executionStarted ? "accent" : "dim";
172
+ }
173
+
174
+ /** The role of the `└` a result hangs under: the color this package's own result rows take. */
175
+ export function resultRole(context: CallContext): ThemeColor {
176
+ return context.isError ? "error" : context.isPartial ? "accent" : "toolOutput";
177
+ }
178
+
179
+ /** Side padding of a row `width` columns wide: padding yields before content, even with pathological settings. */
180
+ function sidePad(width: number, outputPad: unknown): number {
181
+ const requested = typeof outputPad === "number" && Number.isFinite(outputPad) ? Math.max(0, Math.floor(outputPad)) : 0;
182
+ return Math.min(requested, Math.max(0, Math.floor((width - 2) / 2)));
183
+ }
184
+
185
+ /** Columns a flat row's lead takes: "● ", "└ ", or the two spaces that align the lines under them. */
186
+ const LEAD = 2;
187
+
188
+ /** The width a third-party renderer gets inside the flat shell: the row minus its side padding and the lead. */
189
+ export function flatInnerWidth(width: number, outputPad: unknown): number {
190
+ return Math.max(1, width - 2 * sidePad(width, outputPad) - LEAD);
191
+ }
192
+
193
+ /** Where one slot's lines sit in a flat row: `skipped` leading blank lines were dropped, `count` are shown of `total`. */
194
+ export interface FlatSpan { skipped: number; count: number; total: number }
195
+ export interface FlatRow {
196
+ lines: string[];
197
+ /** Columns before the renderer's own cells, and how many it was given: mouse events map through these. */
198
+ left: number;
199
+ inner: number;
200
+ call: FlatSpan;
201
+ result: FlatSpan;
202
+ }
203
+
204
+ const isBlankLine = (line: string): boolean => line === "" || stripAnsi(line).trim() === "";
205
+
206
+ /**
207
+ * A third-party renderer's own lines in this package's flat shell: the call
208
+ * after one status dot, the result under a `└` connector, later lines aligned
209
+ * under the first. The lines are never rewritten or wrapped — one wider than
210
+ * the room it was rendered for is clipped — and only the blank rows a slot
211
+ * opens or closes with are dropped: they are its padding, not its content. A
212
+ * result with no call line above it takes the dot, unless it is rendered on
213
+ * its own (`resultOnly`, the HTML exporter's result slot).
214
+ * `call` and `result` must hold only strings and no image-protocol line: the caller keeps such rows out.
215
+ */
216
+ export function flatRow(call: readonly string[], result: readonly string[], width: number, outputPad: unknown,
217
+ dot: string, connector: string, resultOnly = false): FlatRow {
218
+ const pad = sidePad(width, outputPad);
219
+ const inner = Math.max(1, width - 2 * pad - LEAD);
220
+ const indent = " ".repeat(pad);
221
+ const rest = `${indent} `;
222
+ const lines: string[] = [];
223
+ const place = (source: readonly string[], lead: string): FlatSpan => {
224
+ let start = 0;
225
+ let end = source.length;
226
+ while (start < end && isBlankLine(source[start]!)) start++;
227
+ while (end > start && isBlankLine(source[end - 1]!)) end--;
228
+ for (let i = start; i < end; i++) {
229
+ const line = source[i]!;
230
+ // Measuring a styled line is the host ruler's fast path, truncating one is not: only a line that is too wide pays for it.
231
+ lines.push((i === start ? `${indent}${lead} ` : rest) + (visibleWidth(line) <= inner ? line : truncateToWidth(line, inner, "")));
232
+ }
233
+ return { skipped: start, count: end - start, total: source.length };
234
+ };
235
+ const callSpan = place(call, dot);
236
+ const resultSpan = place(result, callSpan.count || resultOnly ? connector : dot);
237
+ // A row narrower than the lead itself: clip, never let a line reach past the terminal edge.
238
+ return { lines: pad + LEAD + inner > width ? clipTextRows(lines, width) : lines, left: pad + LEAD, inner, call: callSpan, result: resultSpan };
239
+ }
240
+
241
+ /** Preserve printable output, spaces and line breaks; never replay terminal controls. */
242
+ export function safeOutput(text: string): string {
243
+ let out = "";
244
+ let run = 0; // start of the pending verbatim run: plain output is copied in slices, not per char
245
+ let i = 0;
246
+ while (i < text.length) {
247
+ const next = skipTerminalSequence(text, i);
248
+ if (next !== i) {
249
+ out += text.slice(run, i);
250
+ i = run = next;
251
+ continue;
252
+ }
253
+ const cp = codePointAtIndex(text, i);
254
+ const size = cp > 0xffff ? 2 : 1;
255
+ let replacement: string;
256
+ if (cp === 0x0a) {
257
+ i += size;
258
+ continue;
259
+ }
260
+ if (isLineSeparator(cp)) replacement = "\n";
261
+ else if (cp === 0x09) replacement = " ";
262
+ else if (isLoneSurrogate(cp)) replacement = "\ufffd"; // measured 0 columns, painted as 1
263
+ else if (isUnsafeCodePoint(cp)) replacement = "";
264
+ else {
265
+ i += size;
266
+ continue;
267
+ }
268
+ out += text.slice(run, i) + replacement;
269
+ i = run = i + size;
270
+ }
271
+ return out + text.slice(run);
272
+ }
273
+
274
+ /** Index spans avoid splitting a large file into an array just to preview its head. */
275
+ function* lineSpans(text: string): Generator<{ start: number; end: number }> {
276
+ let start = 0;
277
+ while (start < text.length) {
278
+ const newline = text.indexOf("\n", start);
279
+ const end = newline === -1 ? text.length : newline;
280
+ yield { start, end };
281
+ start = end + 1;
282
+ }
283
+ }
284
+
285
+ function* textBlocks(result: ToolResult): Generator<string> {
286
+ for (const block of result.content) if (block.type === "text") yield block.text;
287
+ }
288
+
289
+ function* fullText(text: string, color: ThemeColor = "toolOutput"): Generator<Row> {
290
+ // Expanded output has no line or character cap. Empty/trailing rows are intentional.
291
+ if (!text) return;
292
+ const safe = safeOutput(text);
293
+ for (const { start, end } of lineSpans(safe)) yield { text: safe.slice(start, end), color, wrap: true };
294
+ if (!safe || safe.endsWith("\n")) yield { text: "", color, wrap: true };
295
+ }
296
+
297
+ function resultRows(result: ToolResult, expanded: boolean, partial: boolean, error: boolean, hint: string, headerOnly: boolean): Row[] {
298
+ const color = error ? "error" : partial ? "accent" : "toolOutput";
299
+ const images = result.content.reduce((count, block) => count + Number(block.type === "image"), 0);
300
+ const attachments = images ? `${plural(images, "image attachment")} (display handled by host)` : "";
301
+ const emptyText = error ? "Failed (no diagnostic text)" : partial ? "Running…" : "";
302
+ const fallback: Row = { text: `└ ${[emptyText, attachments].filter(Boolean).join(" · ") || "No text output"}`, color };
303
+ if (expanded) {
304
+ const rows: Row[] = [];
305
+ for (const text of textBlocks(result)) for (const row of fullText(text, color)) rows.push(row);
306
+ return rows.length && (!images || rows.some(row => row.text.trim())) ? rows : [fallback];
307
+ }
308
+ if (headerOnly && !partial && !error) return images ? [fallback] : [];
309
+ if (partial || error) return tailRows(result, error ? 3 : 2, color, hint, fallback);
310
+ // Inspect only a bounded prefix, even when one text block contains a huge line.
311
+ let prefix = "";
312
+ let omitted = false;
313
+ for (const text of textBlocks(result)) {
314
+ const room = PREVIEW_CHARS - prefix.length;
315
+ if (room <= 0) { omitted = true; break; }
316
+ if (prefix) prefix += "\n";
317
+ prefix += text.slice(0, room);
318
+ if (text.length > room) { omitted = true; break; }
319
+ }
320
+ const safe = safeOutput(prefix);
321
+ // `npm run` opens with a blank line: it must not spend a preview row. Only whole
322
+ // blank lines go, so the first line keeps its indentation.
323
+ const lines = safe.replace(/^(?:[^\S\n]*\n)+/, "").split("\n");
324
+ const limit = 2;
325
+ // A trailing newline is not more output: only printable later lines count.
326
+ omitted ||= lines.slice(limit).some(line => line.trim());
327
+ const rows: Row[] = lines.slice(0, limit).map((text, i) => ({ text: `${i === 0 ? "└ " : " "}${text}`, color }));
328
+ if (!safe.trim()) rows.splice(0, rows.length, fallback);
329
+ if (omitted) rows.push({ text: ` … more output (${hint})`, color: "dim" });
330
+ return rows;
331
+ }
332
+
333
+ /**
334
+ * Running and failed calls preview their END: the newest progress line, the
335
+ * exception and the exit status are what say how it is going. Only a bounded
336
+ * suffix is inspected (never the whole output, never split whole), and the
337
+ * omitted earlier output is announced above the tail, where it was.
338
+ */
339
+ function tailRows(result: ToolResult, limit: number, color: ThemeColor, hint: string, fallback: Row): Row[] {
340
+ let window = "";
341
+ let cut = false;
342
+ for (let i = result.content.length - 1; i >= 0; i--) {
343
+ const block = result.content[i]!;
344
+ if (block.type !== "text" || !block.text) continue;
345
+ const room = PREVIEW_CHARS - window.length;
346
+ if (room <= 0) { cut = true; break; }
347
+ const piece = block.text.length > room ? block.text.slice(block.text.length - room) : block.text;
348
+ window = window ? `${piece}\n${window}` : piece;
349
+ if (block.text.length > room) { cut = true; break; }
350
+ }
351
+ let lines = nonBlankLines(window);
352
+ let endOfHugeLine = false;
353
+ if (cut) {
354
+ // The window may open inside an escape sequence or halfway through a line:
355
+ // start at its first line boundary (a carriage return is one too), unless
356
+ // nothing printable follows it.
357
+ const boundary = window.search(/[\n\r]/);
358
+ const whole = boundary === -1 ? [] : nonBlankLines(window.slice(boundary + 1));
359
+ if (whole.length) lines = whole;
360
+ else {
361
+ // One huge line: its end is what is new. The window may open with the rest
362
+ // of a control string whose introducer was cut off, or half a surrogate pair.
363
+ const first = window.charCodeAt(0);
364
+ lines = nonBlankLines(dropCutControlString(first >= 0xdc00 && first <= 0xdfff ? window.slice(1) : window));
365
+ endOfHugeLine = true;
366
+ }
367
+ }
368
+ const omitted = cut || lines.length > limit;
369
+ const tail = lines.slice(-limit);
370
+ if (!tail.length) return omitted ? [{ text: `└ … earlier output (${hint})`, color: "dim" }] : [fallback];
371
+ if (!omitted) return tail.map((text, i) => ({ text: `${i === 0 ? "└ " : " "}${text}`, color }));
372
+ return [{ text: `└ … earlier output (${hint})`, color: "dim" },
373
+ ...tail.map(text => ({ text: ` ${text}`, color, tail: endOfHugeLine }))];
374
+ }
375
+
376
+ /**
377
+ * Printable, non-blank lines as a terminal would leave them: a carriage return
378
+ * rewrites its line, so a progress meter shows its newest value, not its first.
379
+ */
380
+ function nonBlankLines(window: string): string[] {
381
+ const rewritten = window.split("\n").map(line => {
382
+ const settled = line.replace(/\r+$/, "");
383
+ return settled.slice(settled.lastIndexOf("\r") + 1);
384
+ }).join("\n");
385
+ return safeOutput(rewritten).split("\n").filter(line => line.trim());
386
+ }
387
+
388
+ /** Drop the remains of an OSC/DCS/APC payload when its terminator comes before any introducer. */
389
+ function dropCutControlString(window: string): string {
390
+ const introducer = window.search(/[\x1b\x90\x98\x9b\x9d-\x9f]/);
391
+ if (introducer !== -1 && window.charCodeAt(introducer) === 0x1b && window.charCodeAt(introducer + 1) === 0x5c) {
392
+ return window.slice(introducer + 2); // ESC \ with nothing opened before it
393
+ }
394
+ const terminator = window.search(/[\x07\x9c]/);
395
+ return terminator !== -1 && (introducer === -1 || terminator < introducer) ? window.slice(terminator + 1) : window;
396
+ }
397
+
398
+ /** Characters of a tail row inspected when it is cut from the left: more than any terminal is wide. */
399
+ const TAIL_SCAN = 1024;
400
+
401
+ /** Keep the end of a row that does not fit: its indent, "…", then the last graphemes that do. */
402
+ function truncateStart(text: string, room: number): string {
403
+ if (visibleWidth(text) <= room) return text;
404
+ const indent = /^[ └]*/.exec(text)![0];
405
+ const budget = room - visibleWidth(indent) - 1;
406
+ if (budget <= 0) return truncateToWidth(text, room, "…");
407
+ const scanned = text.length > TAIL_SCAN;
408
+ const graphemes = Array.from(GRAPHEMES.segment(scanned ? text.slice(-TAIL_SCAN) : text.slice(indent.length)), item => item.segment);
409
+ let kept = "";
410
+ let used = 0;
411
+ // When the scan window was sliced, its first grapheme may be half of one: never take it.
412
+ for (let i = graphemes.length - 1; i >= (scanned ? 1 : 0); i--) {
413
+ const size = visibleWidth(graphemes[i]!);
414
+ if (used + size > budget) break;
415
+ kept = graphemes[i] + kept;
416
+ used += size;
417
+ }
418
+ return `${indent}…${kept}`;
419
+ }
420
+
421
+ function diffRow(text: string, wrap: boolean): Row {
422
+ const sign = /^ {2,}\d+ ([+\- ]) /.exec(text)?.[1];
423
+ return {
424
+ text, wrap,
425
+ color: sign === "+" ? "toolDiffAdded" : sign === "-" ? "toolDiffRemoved" : "toolDiffContext",
426
+ background: sign === "+" ? "toolSuccessBg" : sign === "-" ? "toolErrorBg" : undefined,
427
+ };
428
+ }
429
+
430
+ /** Old/new line numbers use different coordinate spaces after insertions/deletions. */
431
+ function emphasizeReplacements(rows: Row[], complete: boolean): void {
432
+ let removed: Array<{ row: Row; offset: number }> = [];
433
+ let added: Array<{ row: Row; offset: number }> = [];
434
+ const flush = () => {
435
+ // Uneven groups lack an unambiguous positional pairing. Keep full-line color.
436
+ if (removed.length === added.length) for (let i = 0; i < removed.length; i++) {
437
+ const before = removed[i]!;
438
+ const after = added[i]!;
439
+ if (before.row.incomplete || after.row.incomplete) continue;
440
+ const spans = changedSpans(before.row.text.slice(before.offset), after.row.text.slice(after.offset));
441
+ before.row.emphasis = spans.before.map(span => ({ start: span.start + before.offset, end: span.end + before.offset }));
442
+ after.row.emphasis = spans.after.map(span => ({ start: span.start + after.offset, end: span.end + after.offset }));
443
+ }
444
+ removed = [];
445
+ added = [];
446
+ };
447
+ for (const row of rows) {
448
+ const match = /^ {2,}\d+ ([+-]) /.exec(row.text);
449
+ if (!match) { flush(); continue; }
450
+ if (match[1] === "-" && added.length) flush();
451
+ (match[1] === "-" ? removed : added).push({ row, offset: match[0].length });
452
+ }
453
+ if (complete) flush(); // The preview may end halfway through a larger change group.
454
+ }
455
+
456
+ function fileRows(name: string, args: Record<string, unknown>, result: ToolResult, expanded: boolean, hint: string, highlightCode?: (code: string, path: string) => string[]): Row[] | undefined {
457
+ const source = name === "edit" ? recordOf(result.details).diff : args.content;
458
+ if (typeof source !== "string" || (name === "edit" && !source)) return undefined;
459
+ let count = 0;
460
+ let added = 0;
461
+ let removed = 0;
462
+ const rows: Row[] = [];
463
+ let lineNumberWidth = 1;
464
+ for (const { start, end } of lineSpans(source)) {
465
+ count++;
466
+ if (name !== "edit") continue;
467
+ const match = /^([+\- ])\s*(\d+)\s/.exec(source.slice(start, Math.min(end, start + 64)));
468
+ if (match) lineNumberWidth = Math.max(lineNumberWidth, match[2].length);
469
+ }
470
+ // write numbers its own lines 1..count: the widest number is the last one.
471
+ if (name !== "edit") lineNumberWidth = String(count).length;
472
+ count = 0;
473
+ for (const { start, end } of lineSpans(source)) {
474
+ count++;
475
+ const raw = source.slice(start, Math.min(end, start + 64));
476
+ const parsed = name === "edit" ? /^([+\- ])\s*(\d+)\s/.exec(raw) : undefined;
477
+ if (parsed?.[1] === "+") added++;
478
+ if (parsed?.[1] === "-") removed++;
479
+ if (!expanded && rows.length >= PREVIEW_ROWS) continue;
480
+ const cap = expanded ? end : Math.min(end, start + PREVIEW_CHARS);
481
+ const content = safeOutput(source.slice(start, cap)).replaceAll("\n", " ") + (cap < end ? "…" : "");
482
+ if (name === "edit") {
483
+ const line = /^([+\- ])\s*(\d+)\s(.*)$/s.exec(content);
484
+ if (line) {
485
+ const [, sign, number, body] = line;
486
+ const gutter = ` ${number.padStart(lineNumberWidth)} ${sign} `;
487
+ if (sign === " " && highlightCode) {
488
+ const bodyOffset = gutter.length;
489
+ rows.push({
490
+ text: gutter + body, color: "toolDiffContext", wrap: expanded,
491
+ highlight(text, offset, theme) {
492
+ try {
493
+ const code = offset === 0 ? text.slice(bodyOffset) : text;
494
+ const highlighted = highlightCode(code, label(args.path))[0];
495
+ if (highlighted === undefined || !/\x1b\[[0-?]*[ -/]*[@-~]/.test(highlighted) || visibleWidth(highlighted) !== visibleWidth(code)) return undefined;
496
+ const gutter = offset === 0 ? theme.fg("toolDiffContext", text.slice(0, bodyOffset)) : "";
497
+ return gutter + highlighted;
498
+ } catch { return undefined; }
499
+ },
500
+ });
501
+ } else rows.push({ ...diffRow(`${gutter}${body}`, expanded), incomplete: cap < end });
502
+ } else rows.push(diffRow(content, expanded));
503
+ } else rows.push({ text: ` ${String(count).padStart(lineNumberWidth)} + ${content}`, color: "toolDiffAdded", background: "toolSuccessBg", wrap: expanded });
504
+ }
505
+ if (name === "edit") emphasizeReplacements(rows, count === rows.length);
506
+ const summary = name === "write" ? `Wrote ${plural(count, "line")}` : `Added ${plural(added, "line")}, removed ${plural(removed, "line")}`;
507
+ const remainder = count - rows.length;
508
+ rows.unshift({ text: `└ ${summary}`, color: "dim" });
509
+ if (remainder > 0) rows.push({ text: ` … ${remainder} more lines (${hint})`, color: "dim" });
510
+ if (expanded) for (const text of textBlocks(result)) for (const row of fullText(text)) rows.push(row);
511
+ return rows;
512
+ }
513
+
514
+ /** Wrap sanitized text using only the host-installed ruler, preserving grapheme boundaries. */
515
+ function* wrap(text: string, room: number): Generator<{ text: string; offset: number }> {
516
+ let current = "";
517
+ let offset = 0;
518
+ let used = 0;
519
+ for (const item of GRAPHEMES.segment(text)) {
520
+ const size = visibleWidth(item.segment);
521
+ if (used + size > room && current) {
522
+ yield { text: current, offset };
523
+ current = "";
524
+ offset = item.index;
525
+ used = 0;
526
+ }
527
+ if (size > room) {
528
+ // A one-cell viewport cannot draw a wide grapheme. A visible Unicode
529
+ // spelling retains its identity rather than silently discarding it.
530
+ const escaped = Array.from(item.segment, char => `\\u{${codePointAtIndex(char, 0).toString(16)}}`).join("");
531
+ for (let i = 0; i < escaped.length; i += room) yield { text: escaped.slice(i, i + room), offset: item.index };
532
+ offset = item.index + item.segment.length;
533
+ continue;
534
+ }
535
+ current += item.segment;
536
+ used += size;
537
+ }
538
+ if (current || !text) yield { text: current, offset };
539
+ }
540
+
541
+ function paint(row: Row, text: string, offset: number, room: number, theme: Theme): string {
542
+ let decorated = text;
543
+ if (row.emphasis?.length) {
544
+ const sourceLength = !row.wrap && text !== row.text && text.endsWith("…") ? text.length - 1 : text.length;
545
+ let cursor = 0;
546
+ decorated = "";
547
+ for (const span of row.emphasis) {
548
+ const start = Math.max(0, span.start - offset);
549
+ const end = Math.min(sourceLength, span.end - offset);
550
+ if (end <= start) continue;
551
+ decorated += text.slice(cursor, start) + theme.bold(text.slice(start, end));
552
+ cursor = end;
553
+ }
554
+ decorated += text.slice(cursor);
555
+ }
556
+ decorated = row.dot && text.startsWith("●")
557
+ ? theme.fg(row.dot, "●") + theme.fg(row.color, text.slice(1))
558
+ : theme.fg(row.color, decorated);
559
+ if (row.background) decorated = theme.bg(row.background, decorated + " ".repeat(Math.max(0, room - visibleWidth(text))));
560
+ return decorated;
561
+ }
562
+
563
+ /** Paint a non-wrapping row's `text` whole, with the widest meta rung that fits beside it; undefined when it does not fit. */
564
+ function whole(row: Row, text: string, room: number, theme: Theme, alone: boolean): string | undefined {
565
+ const textWidth = visibleWidth(text);
566
+ const meta = row.meta?.find(rung => rung && textWidth + visibleWidth(rung) <= room);
567
+ if (meta) return paint(row, text, 0, room - visibleWidth(meta), theme) + theme.fg("dim", meta);
568
+ return alone && textWidth <= room ? paint(row, text, 0, room, theme) : undefined;
569
+ }
570
+
571
+ /**
572
+ * `key` names what the rows were built from beyond the view's own inputs (a
573
+ * header's outcome arrives with the result): when it changes, rows rebuild.
574
+ */
575
+ export function view(theme: Theme, context: { readonly outputPad?: number }, build: () => Row[], key?: () => unknown): Component {
576
+ let rows: Row[] | undefined;
577
+ let builtFor: unknown;
578
+ let rendered: { width: number; pad: number; lines: string[] } | undefined;
579
+ return {
580
+ invalidate() { rows = undefined; rendered = undefined; },
581
+ render(width) {
582
+ width = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
583
+ if (!width) return [];
584
+ if (key && rows && key() !== builtFor) { rows = undefined; rendered = undefined; }
585
+ const pad = sidePad(width, context.outputPad);
586
+ if (rendered?.width === width && rendered.pad === pad) return rendered.lines;
587
+ const room = width - 2 * pad;
588
+ const indent = " ".repeat(pad);
589
+ const output: string[] = [];
590
+ if (!rows) {
591
+ builtFor = key?.();
592
+ rows = build();
593
+ }
594
+ for (const row of rows) {
595
+ if (row.painted?.length) {
596
+ const fit = row.painted.find(rung => visibleWidth(rung) <= room);
597
+ // An empty rung is the row's way of being absent at this width: no line, not a blank one.
598
+ if (fit !== "") output.push(indent + (fit ?? truncateToWidth(row.painted[row.painted.length - 1]!, room, "…")));
599
+ continue;
600
+ }
601
+ if (!row.wrap && (row.meta || row.texts)) {
602
+ let line: string | undefined;
603
+ for (const text of row.texts ?? []) if ((line = whole(row, text, room, theme, true)) !== undefined) break;
604
+ line ??= whole(row, row.text, room, theme, false);
605
+ if (line !== undefined) {
606
+ output.push(indent + line);
607
+ continue;
608
+ }
609
+ // Never a clipped "(expan…": no rung fits, so the title alone truncates.
610
+ }
611
+ const chunks = row.wrap ? wrap(row.text, room)
612
+ : [{ text: row.tail ? truncateStart(row.text, room) : truncateToWidth(row.text, room, "…"), offset: 0 }];
613
+ for (const chunk of chunks) {
614
+ const highlighted = row.highlight?.(chunk.text, chunk.offset, theme);
615
+ output.push(indent + (highlighted !== undefined && visibleWidth(highlighted) <= room
616
+ ? highlighted : paint(row, chunk.text, chunk.offset, room, theme)));
617
+ }
618
+ }
619
+ rendered = { width, pad, lines: output };
620
+ return output;
621
+ },
622
+ };
623
+ }
624
+
625
+ /** Renderers contain presentation only; callers decide whether a tool should use them. */
626
+ export interface ToolViewDependencies {
627
+ highlightCode?: (code: string, path: string) => string[];
628
+ }
629
+
630
+ /**
631
+ * The row-local record a result leaves for its header. Both renderers of one
632
+ * row get the same `context.state`, in either call order; keyed by the host's
633
+ * content array (stable across re-renders of one result) so a result is
634
+ * counted once, not on every expand toggle or frame.
635
+ */
636
+ const OUTCOME = Symbol("pi1337-outcome");
637
+ type OutcomeRecord = { content: ToolResult["content"]; details: unknown; text: string };
638
+ type RowState = { [OUTCOME]?: OutcomeRecord };
639
+
640
+ function recordOutcome(state: RowState, toolName: string, args: Record<string, unknown>, result: ToolResult, settled: boolean): void {
641
+ const last = state[OUTCOME];
642
+ if (!settled) { state[OUTCOME] = undefined; return; }
643
+ if (last?.content === result.content && last.details === result.details) return;
644
+ state[OUTCOME] = { content: result.content, details: result.details, text: outcomeOf(toolName, args, result) };
645
+ }
646
+
647
+ const count = (n: number, one: string, many: string, more = false) => more ? `${n}+ ${many}` : plural(n, one, many);
648
+ const limitOf = (value: unknown): number | undefined =>
649
+ typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
650
+
651
+ /**
652
+ * What a settled, successful quiet call found — "6 matches", "no results",
653
+ * "12 entries", "40 lines" — from the host tool's own result contract: zero
654
+ * results are its exact sentinel text, a limit is `details.*LimitReached`
655
+ * (so "100+"), a byte cap is `details.truncation.totalLines`. Otherwise rows
656
+ * are counted once, up to the notice the host appends after a blank line.
657
+ * "" whenever the result does not say reliably (grep with context lines mixes
658
+ * match and context rows; another tool's text shape; images).
659
+ */
660
+ function outcomeOf(toolName: string, args: Record<string, unknown>, result: ToolResult): string {
661
+ if (result.content.length !== 1 || result.content[0]!.type !== "text") return "";
662
+ const text = result.content[0]!.text;
663
+ const details = recordOf(result.details);
664
+ const truncation = recordOf(details.truncation);
665
+ const total = truncation.truncated === true && typeof truncation.totalLines === "number" && Number.isInteger(truncation.totalLines) && truncation.totalLines > 0
666
+ ? truncation.totalLines : undefined;
667
+ // Rows end where the host's notice block starts; a notice is appended only with details.
668
+ const rows = () => countLines(text, Object.keys(details).length > 0);
669
+ switch (toolName) {
670
+ case "grep": {
671
+ const limit = limitOf(details.matchLimitReached);
672
+ if (limit) return count(limit, "match", "matches", true);
673
+ if (text === "No matches found") return "no matches";
674
+ if (args.context != null && !(Number(args.context) <= 0)) return "";
675
+ return count(total ?? rows(), "match", "matches");
676
+ }
677
+ case "find": {
678
+ const limit = limitOf(details.resultLimitReached);
679
+ // The host's find lists directories too and calls its rows "results".
680
+ if (limit) return count(limit, "result", "results", true);
681
+ if (text === "No files found matching pattern") return "no results";
682
+ return count(total ?? rows(), "result", "results");
683
+ }
684
+ case "ls": {
685
+ const limit = limitOf(details.entryLimitReached);
686
+ if (limit) return count(limit, "entry", "entries", true);
687
+ if (text === "(empty directory)") return "empty";
688
+ return count(total ?? rows(), "entry", "entries");
689
+ }
690
+ case "bash": {
691
+ if (total) return count(total, "line", "lines");
692
+ if (text === "(no output)" || !text) return "";
693
+ const lines = countLines(text, false);
694
+ return lines ? count(lines, "line", "lines") : "";
695
+ }
696
+ default: return "";
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Lines as the host counts them (a trailing newline ends a line, it does not
702
+ * start one), optionally stopping at the first blank line. One indexOf pass.
703
+ */
704
+ export function countLines(text: string, untilBlank = false): number {
705
+ let lines = 0;
706
+ let start = 0;
707
+ while (start < text.length) {
708
+ const newline = text.indexOf("\n", start);
709
+ if (untilBlank && newline === start) break;
710
+ lines++;
711
+ if (newline === -1) break;
712
+ start = newline + 1;
713
+ }
714
+ return lines;
715
+ }
716
+
717
+ export function createToolView(toolName: string, expandHint: () => string, dependencies: ToolViewDependencies = {}): ToolRenderers {
718
+ const quiet = toolWords(toolName)?.quiet === true;
719
+ return {
720
+ renderShell: "self",
721
+ renderCall(args, theme, context) {
722
+ const state = context.state as RowState;
723
+ const outcomeKey = () => state[OUTCOME];
724
+ return view(theme, context, () => {
725
+ // Sub-second timings are noise next to the title; settled slow calls earn one.
726
+ const duration = !context.isPartial && typeof context.durationMs === "number" && Number.isFinite(context.durationMs) && context.durationMs >= 1000
727
+ ? ` · ${formatDuration(context.durationMs)}` : "";
728
+ const settled = !context.expanded && !context.isPartial && !context.isError && quiet;
729
+ const hint = settled ? ` (${label(expandHint()) || "expand"})` : "";
730
+ // Derived from tool text, so it is sanitized like any other foreign label.
731
+ const found = settled ? label(state[OUTCOME]?.text) : "";
732
+ const outcome = found ? ` · ${found}` : "";
733
+ // The hint is boilerplate every quiet row carries; a slow call's time is
734
+ // not, and what the call found matters most of all.
735
+ const meta = outcome ? [outcome + duration + hint, outcome + duration, outcome] : [duration + hint, duration];
736
+ // A running command names the timeout the model chose, as stock Pi does. It is
737
+ // the first rung to go, and gone with the final result: by then it either
738
+ // held or the error says so.
739
+ const timeout = toolName === "bash" && context.isPartial ? timeoutRung(recordOf(args).timeout) : "";
740
+ const rows: Row[] = [{ text: `● ${heading(toolName, recordOf(args), context.cwd)}`, color: "toolTitle", dot: statusRole(context),
741
+ meta: timeout ? [timeout + meta[0]!, ...meta] : meta }];
742
+ if (context.expanded) {
743
+ const allArgs = recordOf(args);
744
+ if (toolName === "bash") {
745
+ for (const row of fullText(safeExpandedText(textOf(allArgs.command)))) rows.push(row);
746
+ const { command: _command, ...otherArgs } = allArgs;
747
+ if (Object.keys(otherArgs).length) for (const row of fullText(expandedArguments(otherArgs), "toolOutput")) rows.push(row);
748
+ } else {
749
+ for (const row of fullText(expandedArguments(allArgs), "toolOutput")) rows.push(row);
750
+ }
751
+ }
752
+ return rows;
753
+ }, outcomeKey);
754
+ },
755
+ renderResult(result, options, theme, context) {
756
+ if (quiet) recordOutcome(context.state as RowState, toolName, recordOf(context.args), result,
757
+ !options.isPartial && !context.isPartial && !context.isError);
758
+ return view(theme, context, () => {
759
+ const hint = label(expandHint()) || "expand";
760
+ const partial = options.isPartial || context.isPartial;
761
+ if (!partial && !context.isError && (toolName === "edit" || toolName === "write")) {
762
+ const rows = fileRows(toolName, recordOf(context.args), result, options.expanded, hint, dependencies.highlightCode);
763
+ if (rows) return rows;
764
+ }
765
+ return resultRows(result, options.expanded, partial, context.isError, hint,
766
+ toolWords(toolName)?.quiet === true);
767
+ });
768
+ },
769
+ };
770
+ }
771
+
772
+ /**
773
+ * One folded run's row: "● Read width.ts, frame.ts · searched 2 patterns (ctrl+o to expand)"
774
+ * when that row fits whole (its hint only if that fits too), else the counted
775
+ * "● Read 2 files, searched 2 patterns (…)". Built on the same rows as every
776
+ * tool header, so it shares their indent, sanitizing, single-line truncation
777
+ * and width cache.
778
+ */
779
+ export function createRunSummaryView(sentence: string, theme: Theme, context: CallContext, expandHint: () => string, detailed = ""): Component {
780
+ return view(theme, context, () => {
781
+ const names = label(detailed);
782
+ const counted = label(sentence);
783
+ return [{
784
+ text: `● ${counted}`, color: "toolTitle", dot: "success", meta: [` (${label(expandHint()) || "expand"})`],
785
+ texts: names && names !== counted ? [`● ${names}`] : undefined,
786
+ }];
787
+ });
788
+ }