@xynogen/pix-pretty 2.1.0 → 3.0.0

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.
package/src/utils.ts CHANGED
@@ -1,48 +1,9 @@
1
1
  import { isAbsolute, relative, resolve } from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
- import {
4
- type Color,
5
- type Component,
6
- getCapabilities,
7
- hyperlink,
8
- MouseRegion,
9
- mixColors,
10
- Text,
11
- truncateToWidth,
12
- visibleWidth,
13
- } from "@earendil-works/pi-tui";
14
-
15
- import {
16
- ANSI_CAPTURE_RE,
17
- BG_BASE,
18
- BG_ERROR,
19
- BOLD,
20
- BOLD_OFF,
21
- FG_LNUM,
22
- FG_RULE,
23
- hasAnsi,
24
- RST,
25
- } from "./ansi.ts";
3
+ import { getCapabilities, hyperlink, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+ import { ANSI_CAPTURE_RE, BG_BASE, FG_LNUM, RST } from "./ansi.ts";
26
5
  import { MAX_PREVIEW_LINES } from "./config.ts";
27
- import { icon } from "./icon-catalog.ts";
28
- import { fadeLine, fadePaint, fadeRowsOf, fadeText } from "./text.ts";
29
- import type {
30
- FgTheme,
31
- TextComponentCtor,
32
- TextComponentLike,
33
- ToolContent,
34
- ToolImageContent,
35
- ToolResultLike,
36
- ToolTextContent,
37
- } from "./types.ts";
38
-
39
- export function renderToolError(error: string, theme: FgTheme): string {
40
- return fillToolBackground(theme.fg("error", error), BG_ERROR);
41
- }
42
-
43
- export function normalizeLineEndings(text: string): string {
44
- return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
45
- }
6
+ import type { TextComponentCtor, TextComponentLike } from "./types.ts";
46
7
 
47
8
  function preserveToolBackground(ansi: string, bg: string): string {
48
9
  return ansi.replace(ANSI_CAPTURE_RE, (seq, params: string) => {
@@ -52,7 +13,7 @@ function preserveToolBackground(ansi: string, bg: string): string {
52
13
  }
53
14
 
54
15
  export function fillToolBackground(text: string, bg = BG_BASE, width?: number): string {
55
- const resolvedWidth = width ?? termW();
16
+ const resolvedWidth = width ?? terminalWidth();
56
17
  return text
57
18
  .split("\n")
58
19
  .map((line) => {
@@ -86,22 +47,6 @@ type ViewportComponent = {
86
47
  invalidate(): void;
87
48
  };
88
49
 
89
- type ResultComponent = ViewportComponent & {
90
- handleInput?(data: string): void;
91
- wantsKeyRelease?: boolean;
92
- };
93
-
94
- type FramableComponent = Partial<ResultComponent> & Partial<TextComponentLike>;
95
- type ResultFrameTheme = StatusRuleTheme;
96
-
97
- const RESULT_FRAME = Symbol("pix.resultFrame");
98
- type FramedResultComponent = ResultComponent & {
99
- [RESULT_FRAME]: {
100
- component: FramableComponent;
101
- update(theme: ResultFrameTheme, isError: boolean, section: boolean): void;
102
- };
103
- };
104
-
105
50
  // ponytail: 4 widths cover drag/split/fullscreen toggles. The ceiling is memory
106
51
  // (4 × card size). Raise MAX_WIDTHS if the profile `resize` column shows misses.
107
52
  const MAX_WIDTHS = 4;
@@ -186,10 +131,6 @@ class ViewportText implements TextComponentLike, ViewportComponent {
186
131
  }
187
132
  }
188
133
 
189
- export function pluralize(count: number, noun: string, plural?: string): string {
190
- return `${count} ${count === 1 ? noun : (plural ?? `${noun}s`)}`;
191
- }
192
-
193
134
  export interface FormatJsonOptions {
194
135
  /** Hard char ceiling for the whole block; a longer block is clipped with an ellipsis. */
195
136
  maxChars?: number;
@@ -261,312 +202,6 @@ export function formatJson(value: unknown, options: FormatJsonOptions = {}): str
261
202
  return out;
262
203
  }
263
204
 
264
- export type CollapsedToolStatus = "success" | "error" | "warning";
265
-
266
- /**
267
- * Status glyphs for collapsed tool rows. `⚠` (warning) is East-Asian *wide*
268
- * (2 cells) while `✓`/`✗` are 1 cell — render them through `padIcon` so every
269
- * marker occupies the same fixed column and rows stay vertically aligned.
270
- * (`⚡` is reserved for strength / model-score badges, not warnings.)
271
- */
272
- export const COLLAPSED_TOOL_GLYPH: Record<CollapsedToolStatus, string> = {
273
- get success() {
274
- return icon("status.ok");
275
- },
276
- get warning() {
277
- return icon("status.warn");
278
- },
279
- get error() {
280
- return icon("status.error");
281
- },
282
- };
283
-
284
- /**
285
- * Normalize a marker glyph to a fixed display width so mixed 1-cell and 2-cell
286
- * (East-Asian wide / emoji) icons align in a column and the following text
287
- * always starts at the same offset. Measures actual terminal cells via pi-tui's
288
- * `visibleWidth` (ANSI-aware), then right-pads with spaces. A glyph already
289
- * at/over `width` is returned unchanged (never truncated — clipping a marker is
290
- * worse than a 1-cell overflow).
291
- *
292
- * The default width (2) makes every marker occupy exactly two cells, so with a
293
- * single separator space the following text always starts at the same column:
294
- *
295
- * `${padIcon("✓")} bash` // "✓ bash" (1 cell + 1 pad + separator)
296
- * `${padIcon("⚠")} bash` // "⚠ bash" (2 cells + separator — same column)
297
- */
298
- export function padIcon(glyph: string, width = 2): string {
299
- const pad = width - visibleWidth(glyph);
300
- return pad > 0 ? glyph + " ".repeat(pad) : glyph;
301
- }
302
-
303
- /** Fixed icon/name columns align the divider across compact activity widgets. */
304
- export function widgetTitle(
305
- theme: { fg: (role: "toolTitle" | "muted", text: string) => string },
306
- glyph: string,
307
- name: string,
308
- ): string {
309
- return theme.fg("toolTitle", `${padIcon(glyph, 3)} ${name.padEnd(8)}`) + theme.fg("muted", " │ ");
310
- }
311
-
312
- /**
313
- * Join non-empty parts with a middot separator: `dotJoin(["a", "", "b"])` → `"a · b"`.
314
- * Empty/nullish parts are dropped so callers can pass conditional pieces inline.
315
- * Pass `paint` (e.g. `(s) => theme.fg("dim", s)`) to tint the separator to theme.
316
- */
317
- export function dotJoin(
318
- parts: Array<string | false | null | undefined>,
319
- paint?: RulePaint,
320
- ): string {
321
- const sep = paint ? paint(" · ") : " · ";
322
- return parts.filter((p): p is string => Boolean(p)).join(sep);
323
- }
324
-
325
- type CollapsedToolTheme = {
326
- fg: (
327
- key: "success" | "error" | "warning" | "toolTitle" | "muted" | "dim",
328
- text: string,
329
- ) => string;
330
- bold: (text: string) => string;
331
- colors?: {
332
- dim: Parameters<typeof mixColors>[0];
333
- customMessageBg: Parameters<typeof mixColors>[1];
334
- };
335
- style?: (text: string, style: { fg: ReturnType<typeof mixColors> }) => string;
336
- };
337
-
338
- /** Keep identity/stats fixed; only the trailing activity consumes spare columns. */
339
- export function widgetActivityRow(
340
- theme: Pick<CollapsedToolTheme, "fg" | "colors" | "style">,
341
- prefix: string,
342
- activity: string,
343
- width: number,
344
- stats = "",
345
- ): string {
346
- const paint = fadePaint(theme);
347
- if (stats) {
348
- const room = width - visibleWidth(stats) - 2;
349
- if (room < visibleWidth(prefix)) return fadeLine(`${prefix} ${stats}`, width, paint);
350
- const body = widgetActivityRow(theme, prefix, activity, room);
351
- return body + " ".repeat(width - visibleWidth(body) - visibleWidth(stats)) + stats;
352
- }
353
- const separator = theme.fg("muted", " · ");
354
- const room = width - visibleWidth(prefix) - 3;
355
- if (!activity || room < 1) return fadeLine(prefix, width, paint);
356
- return prefix + separator + fadeText(activity, room, paint);
357
- }
358
-
359
- /** Use the host lifecycle fields so every call has the same status marker. */
360
- export function renderTitle(
361
- theme: {
362
- fg: (role: "muted" | "warning" | "error" | "success" | "toolTitle", text: string) => string;
363
- bold?: (text: string) => string;
364
- },
365
- tool: string,
366
- context: { executionStarted?: boolean; isPartial?: boolean; isError?: boolean } = {},
367
- action?: string,
368
- ): string {
369
- const complete = context.isPartial === false;
370
- const role = complete
371
- ? context.isError
372
- ? "error"
373
- : "success"
374
- : context.executionStarted
375
- ? "warning"
376
- : "muted";
377
- const marker = complete
378
- ? context.isError
379
- ? "status.error"
380
- : "status.ok"
381
- : context.executionStarted
382
- ? "status.running"
383
- : "status.pending";
384
- const label = action ? `${tool} · ${action}` : tool;
385
- return `${theme.fg(role, padIcon(icon(marker)))} ${theme.fg("toolTitle", theme.bold?.(label) ?? label)}`;
386
- }
387
-
388
- /** Build a plain call renderer; command and rich previews keep their own body. */
389
- export function renderCall<TArgs = Record<string, unknown>>(
390
- tool: string,
391
- target: (args: TArgs) => string,
392
- action?: (args: TArgs) => string | undefined,
393
- ) {
394
- return (
395
- args: TArgs,
396
- theme: Parameters<typeof renderTitle>[0] & { fg: (role: "dim", text: string) => string },
397
- context: Parameters<typeof renderTitle>[2] & {
398
- lastComponent?: Component;
399
- state: Record<string, unknown>;
400
- expanded: boolean;
401
- },
402
- ): Component => {
403
- const previous = context.lastComponent && unframeToolResult(context.lastComponent);
404
- const text =
405
- previous && "setText" in previous && typeof previous.setText === "function"
406
- ? (previous as Component & { setText(value: string): void })
407
- : new Text("", 0, 0);
408
- if (hideCollapsedToolCall(context.state, context.expanded, (value) => text.setText(value)))
409
- return text;
410
- const value = target(args);
411
- text.setText(
412
- `${renderTitle(theme, tool, context, action?.(args))}${value ? ` ${theme.fg("dim", value)}` : ""}`,
413
- );
414
- return text;
415
- };
416
- }
417
-
418
- /** Format the shared one-row content without assuming a render shell. */
419
- export function renderRow(
420
- theme: CollapsedToolTheme,
421
- tool: string,
422
- target: string,
423
- meta = "",
424
- status: CollapsedToolStatus = "success",
425
- width?: number,
426
- ): string {
427
- const marker = padIcon(
428
- icon(status === "success" ? "status.ok" : status === "error" ? "status.error" : "status.warn"),
429
- );
430
- const title = `${theme.fg(status, marker)} ${theme.fg("toolTitle", theme.bold(tool))}`;
431
- const metadata = meta ? ` ${theme.fg("muted", "·")} ${theme.fg("muted", meta)}` : "";
432
- if (width === undefined)
433
- return `${title}${target ? ` ${theme.fg("dim", target)}` : ""}${metadata}`;
434
- const room = width - visibleWidth(title) - visibleWidth(metadata) - 1;
435
- const fitted = target && room > 0 ? fadeText(target, room, fadePaint(theme)) : "";
436
- return truncateToWidth(`${title}${fitted ? ` ${fitted}` : ""}${metadata}`, width, "…");
437
- }
438
-
439
- /** Render shared one-row content for tools using the self-rendered shell. */
440
- export function renderCollapsed(
441
- theme: CollapsedToolTheme,
442
- tool: string,
443
- target: string,
444
- meta = "",
445
- status: CollapsedToolStatus = "success",
446
- width?: number,
447
- ): string {
448
- return fillToolBackground(
449
- renderRow(theme, tool, target, meta, status, width ?? termW()),
450
- BG_BASE,
451
- width,
452
- );
453
- }
454
-
455
- /** Hide renderCall after its paired result has auto-collapsed. */
456
- export function hideCollapsedToolCall(
457
- state: { collapsed?: boolean },
458
- expanded: boolean,
459
- setText: (text: string) => void,
460
- ): boolean {
461
- if (!state.collapsed || expanded) return false;
462
- setText("");
463
- return true;
464
- }
465
-
466
- export type DimPreviewOptions = {
467
- maxLines?: number;
468
- /** Header line shown above the body. NON-FRAMED mode only — in framed mode
469
- * the header is intentionally dropped (the collapsed row already carries the
470
- * count, so a floating header above the frame is redundant). */
471
- header?: string;
472
- /** Pattern whose matches are highlighted (bold, themed) inside dim lines.
473
- * A string is matched literally (case-insensitive); a RegExp is used as-is
474
- * (callers pass the compiled search pattern so regex greps highlight too). */
475
- highlight?: string | RegExp;
476
- /** Wrap the body in a top/bottom rule frame (overflow below), like bash/ls/mcp. */
477
- frame?: boolean;
478
- /** Tint the frame rules (green ok, red error) — same status color as bash/ls. */
479
- paint?: RulePaint;
480
- /** Renderer context: the overflow row shows the user's expand key. */
481
- ctx?: ExpandHintCtx;
482
- };
483
-
484
- /** Compile a highlight pattern into a global RegExp, or null when it can't
485
- * match anything. Strings match literally (case-insensitive); a RegExp is
486
- * re-flagged global so every occurrence on a line lights up. */
487
- function toHighlightRegex(pattern: string | RegExp): RegExp | null {
488
- if (typeof pattern !== "string") {
489
- const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
490
- try {
491
- return new RegExp(pattern.source, flags);
492
- } catch {
493
- return null;
494
- }
495
- }
496
- if (!pattern) return null;
497
- // Literal string → escape regex metacharacters, case-insensitive.
498
- const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
499
- try {
500
- return new RegExp(escaped, "gi");
501
- } catch {
502
- return null;
503
- }
504
- }
505
-
506
- function dimLineWithHighlight(line: string, theme: FgTheme, pattern?: string | RegExp): string {
507
- if (!pattern) return theme.fg("dim", line);
508
- // A line that already carries ANSI (e.g. a source that emitted its own color)
509
- // can't be safely index-sliced — a match could land inside an escape and
510
- // corrupt it. Skip highlighting and dim the whole line instead.
511
- if (hasAnsi(line)) return theme.fg("dim", line);
512
- const re = pattern ? toHighlightRegex(pattern) : null;
513
- if (!re) return theme.fg("dim", line);
514
-
515
- // Themed bold hit: theme.fg carries its own reset, so re-open BOLD after it
516
- // and close with the bold-off code (\x1b[22m) to avoid leaking bold onward.
517
- const hit = (s: string) => `${BOLD}${theme.fg("success", s)}${BOLD_OFF}`;
518
- const parts: string[] = [];
519
- let start = 0;
520
- for (let m = re.exec(line); m !== null; m = re.exec(line)) {
521
- const idx = m.index;
522
- const text = m[0];
523
- if (text.length === 0) {
524
- re.lastIndex++; // zero-width match (e.g. /a*/) — advance to avoid a loop
525
- continue;
526
- }
527
- if (idx > start) parts.push(theme.fg("dim", line.slice(start, idx)));
528
- parts.push(hit(text));
529
- start = idx + text.length;
530
- }
531
- if (start < line.length) parts.push(theme.fg("dim", line.slice(start)));
532
- return parts.length > 0 ? parts.join("") : theme.fg("dim", line);
533
- }
534
-
535
- export function renderDimPreview(
536
- text: string,
537
- theme: FgTheme,
538
- opts: DimPreviewOptions = {},
539
- ): string {
540
- const maxLines = opts.maxLines ?? MAX_PREVIEW_LINES;
541
- const highlight = opts.highlight;
542
- const output = normalizeLineEndings(text).trim() || "done";
543
- const lines = output.split("\n");
544
- // Highlight only the preview rows (+1 so the fade still knows it was cut), then fade the
545
- // last of them instead of a hard cut.
546
- const body = fadeRowsOf(
547
- lines
548
- .slice(0, maxLines + 1)
549
- .map((line) => bodyLine(line, theme, (l) => dimLineWithHighlight(l, theme, highlight))),
550
- theme,
551
- maxLines,
552
- );
553
- const header = opts.header ? `${BODY_PAD}${theme.fg("dim", opts.header)}` : undefined;
554
- const overflow =
555
- lines.length > maxLines ? moreLines(lines.length - maxLines, theme, opts.ctx) : undefined;
556
-
557
- if (opts.frame) {
558
- // One shape regardless of line count: a single framed box, no floating
559
- // header (the collapsed row carries the count). Rules follow status color.
560
- const out = ruleFrame(body, overflow ? [overflow] : [], undefined, opts.paint);
561
- return fillToolBackground(out.join("\n"));
562
- }
563
-
564
- const preview = body;
565
- if (header) preview.unshift(header);
566
- if (overflow) preview.push(overflow);
567
- return fillToolBackground(preview.join("\n"));
568
- }
569
-
570
205
  let _cachedTermW: number | undefined;
571
206
  let _termWResizeBound = false;
572
207
 
@@ -574,7 +209,7 @@ function _bindTermWResize(): void {
574
209
  if (_termWResizeBound) return;
575
210
  _termWResizeBound = true;
576
211
  // Persistent listeners: every SIGWINCH invalidates the cache so the next
577
- // termW() re-reads. `.once` only caught the first resize, leaving width
212
+ // terminalWidth() re-reads. `.once` only caught the first resize, leaving width
578
213
  // stale on subsequent resizes.
579
214
  const invalidate = () => {
580
215
  _cachedTermW = undefined;
@@ -586,7 +221,7 @@ function _bindTermWResize(): void {
586
221
  /** Read terminal width — checks all available sources in priority order.
587
222
  * Falls back to querying the controlling tty via fd 1/2/stdin ioctl.
588
223
  * Result is cached and invalidated on SIGWINCH / stdout resize. */
589
- export function termW(): number {
224
+ export function terminalWidth(): number {
590
225
  _bindTermWResize();
591
226
  if (_cachedTermW !== undefined) return _cachedTermW;
592
227
 
@@ -651,379 +286,7 @@ export function linkedShortPath(cwd: string, home: string, p: string): string {
651
286
  return hyperlink(text, pathToFileURL(resolve(cwd, p)).href);
652
287
  }
653
288
 
654
- /** Paints a rule line. Callers pass `(s) => theme.fg(status, s)` so the frame
655
- * tint follows the active theme (success/error/warning). Default = neutral FG_RULE. */
656
- export type RulePaint = (glyphs: string) => string;
657
-
658
- /** Render a full-width solid rule. */
659
- export function rule(w: number, paint?: RulePaint): string {
660
- const glyphs = "─".repeat(w);
661
- return paint ? paint(glyphs) : `${FG_RULE}${glyphs}${RST}`;
662
- }
663
-
664
- /** Theme slice for {@link fadeRulePaint}. Without `colors`/`style` the rule stays flat. */
665
- export type StatusRuleTheme = {
666
- fg: (key: "success" | "error", text: string) => string;
667
- colors?: Readonly<Record<string, Color | undefined>>;
668
- style?: (text: string, style: { fg: Color }) => string;
669
- };
670
-
671
- /**
672
- * Status-colored rule paint that fades in on the left and out on the right: the last
673
- * `fadeColumns` cells at each end mix toward the tool background. Themes without color
674
- * data get the plain `theme.fg(role, …)` rule.
675
- */
676
- export function fadeRulePaint(
677
- theme: StatusRuleTheme,
678
- role: "success" | "error",
679
- fadeColumns = 8,
680
- ): RulePaint {
681
- return (glyphs) => {
682
- const cells = [...glyphs];
683
- const edge = Math.min(fadeColumns, Math.floor(cells.length / 2));
684
- const fg = theme.colors?.[role];
685
- const bg = theme.colors?.[role === "error" ? "toolErrorBg" : "toolSuccessBg"];
686
- if (!fg || !bg || !theme.style || edge < 1) return theme.fg(role, glyphs);
687
- // Cell i from the edge (0 = outermost) is faintest at the edge, full color past `edge`.
688
- // Call as a method: Pi's Theme.style reads `this`.
689
- const cell = (ch: string, i: number) =>
690
- theme.style?.(ch, { fg: mixColors(fg, bg, 1 - (i + 1) / (edge + 1)) }) ?? ch;
691
- const left = cells.slice(0, edge).map(cell).join("");
692
- const right = cells
693
- .slice(-edge)
694
- .map((ch, i) => cell(ch, edge - 1 - i))
695
- .join("");
696
- return left + theme.fg(role, cells.slice(edge, -edge).join("")) + right;
697
- };
698
- }
699
-
700
- /** Narrow theme for helpers that paint only `muted`. Pi's Theme and FgTheme both fit. */
701
- type MutedTheme = { fg: (key: "muted", text: string) => string };
702
-
703
- /** Matches an `=== label ===` separator line (a common shell/echo idiom). */
704
- const SECTION_RE = /^\s*={2,}\s*(.+?)\s*={2,}\s*$/;
705
-
706
- /** Fixed dash count before a left-aligned section label. */
707
- const SECTION_RULE_LEAD = 4;
708
-
709
- /**
710
- * If `line` is an `=== label ===` separator, render it as a left-aligned
711
- * section divider (`──── label ───────────`); otherwise return null. Callers
712
- * fall back to their normal per-line rendering on null. Fills the full `width`
713
- * so the divider aligns with the surrounding tool frame. Label and rule both
714
- * use the muted role — theme-driven, ANSI-safe.
715
- */
716
- export function sectionRule(line: string, theme: MutedTheme, width: number): string | null {
717
- const m = SECTION_RE.exec(line);
718
- if (!m || hasAnsi(line)) return null;
719
- const label = ` ${m[1]} `;
720
- const trail = width - SECTION_RULE_LEAD - visibleWidth(label);
721
- // Label fits → lead rule + trailing fill. Too long to fill → don't force a
722
- // full-width rule; wrap it snugly with 2 dashes each side (`── long text ──`).
723
- const [lead, tail] = trail >= 2 ? [SECTION_RULE_LEAD, trail] : [2, 2];
724
- return theme.fg("muted", `${"─".repeat(lead)}${label}${"─".repeat(tail)}`);
725
- }
726
-
727
- /**
728
- * Make a custom message/entry card toggle on left click, like Pi's tool results.
729
- * Pi gives custom renderers no click handling, so a renderer returns
730
- * `clickToggle(expanded, (open) => card(open))`: a left click rebuilds the card
731
- * with the flipped state. A host Ctrl+O rebuild resets it to the host `expanded`.
732
- * Other mouse events are left unhandled (drag selects text, wheel scrolls).
733
- */
734
- export function clickToggle(
735
- expanded: boolean,
736
- build: (expanded: boolean) => Component,
737
- ): MouseRegion {
738
- let open = expanded;
739
- let view = build(open);
740
- return new MouseRegion(
741
- { render: (width) => view.render(width), invalidate: () => view.invalidate() },
742
- (event) => {
743
- if (event.type !== "click" || event.button !== "left") return undefined;
744
- open = !open;
745
- view = build(open);
746
- return { handled: true };
747
- },
748
- );
749
- }
750
-
751
- /**
752
- * Body indent: one tab. pi-tui renders `\t` as 3 cells, the title column after
753
- * the 2-cell status icon + space.
754
- */
755
- export const BODY_PAD = "\t";
756
-
757
- /**
758
- * One tool-result body line, aligned under the tool title. An `=== label ===` line
759
- * becomes a full-width section rule. Other lines go through `paint`.
760
- */
761
- export function bodyLine(
762
- line: string,
763
- theme: MutedTheme,
764
- paint: (line: string) => string = (s) => s,
765
- ): string {
766
- // ponytail: 3 = pi-tui tab width. Use visibleWidth if BODY_PAD stops being one tab.
767
- return `${BODY_PAD}${sectionRule(line, theme, termW() - 3) ?? paint(line)}`;
768
- }
769
-
770
- /** Renderer context slice that knows the user's expand key (Pi's `ToolRenderContext`). */
771
- export type ExpandHintCtx = {
772
- keyHint?: (keybinding: "app.tools.expand", description: string) => string;
773
- /** Expanded view: renderers that take this context show every row, no hint. */
774
- expanded?: boolean;
775
- };
776
-
777
- /**
778
- * `(ctrl+o to expand)` with the user's configured key, styled like Pi's own hint.
779
- * Without a host `keyHint` (tests, old hosts), the key falls back to `ctrl+o`.
780
- */
781
- export function expandHint(theme: MutedTheme, ctx?: ExpandHintCtx): string {
782
- const hint =
783
- ctx?.keyHint?.("app.tools.expand", "to expand") ?? theme.fg("muted", "ctrl+o to expand");
784
- return `${theme.fg("muted", "(")}${hint}${theme.fg("muted", ")")}`;
785
- }
786
-
787
- /**
788
- * Muted `… N more lines (ctrl+o to expand)` footer for a truncated tool-result body.
789
- * Pass the renderer context so the hint shows the user's own expand key.
790
- */
791
- export function moreLines(count: number, theme: MutedTheme, ctx?: ExpandHintCtx): string {
792
- return `${BODY_PAD}${theme.fg("muted", `… ${pluralize(count, "more line")} `)}${expandHint(theme, ctx)}`;
793
- }
794
-
795
- /** Decorate completed tool output with status-colored default chrome. */
796
- export function frameToolResult<T extends FramableComponent & { setText(value: string): void }>(
797
- component: T,
798
- theme: ResultFrameTheme,
799
- isError: boolean,
800
- ): ResultComponent & { setText(value: string): void; getText?: () => string };
801
- export function frameToolResult(
802
- component: FramableComponent,
803
- theme: ResultFrameTheme,
804
- isError: boolean,
805
- ): ResultComponent;
806
- export function frameToolResult(
807
- component: FramableComponent,
808
- theme: ResultFrameTheme,
809
- isError: boolean,
810
- ): ResultComponent {
811
- return decorateToolResult(component, theme, isError, false);
812
- }
813
-
814
- /** Decorate explicit expanded/detail sections with solid top and bottom rules. */
815
- export function frameToolSection(
816
- component: FramableComponent,
817
- theme: ResultFrameTheme,
818
- isError: boolean,
819
- ): ResultComponent {
820
- return decorateToolResult(component, theme, isError, true);
821
- }
822
-
823
- function decorateToolResult(
824
- component: FramableComponent,
825
- theme: ResultFrameTheme,
826
- isError: boolean,
827
- section: boolean,
828
- ): ResultComponent & Partial<TextComponentLike> {
829
- const existing = component as Partial<FramedResultComponent>;
830
- if (existing[RESULT_FRAME]) {
831
- existing[RESULT_FRAME].update(theme, isError, section);
832
- return component as ResultComponent;
833
- }
834
- let frameTheme = theme;
835
- let failed = isError;
836
- let solid = section;
837
- const framed: FramedResultComponent & Partial<TextComponentLike> = {
838
- [RESULT_FRAME]: {
839
- component,
840
- update(nextTheme, nextError, nextSection) {
841
- frameTheme = nextTheme;
842
- failed = nextError;
843
- solid = nextSection;
844
- },
845
- },
846
- wantsKeyRelease: component.wantsKeyRelease,
847
- render(width) {
848
- const paint = fadeRulePaint(frameTheme, failed ? "error" : "success");
849
- const lines = component.render?.(width) ?? [];
850
- return solid ? sectionFrame(lines, [], width, paint) : ruleFrame(lines, [], width, paint);
851
- },
852
- invalidate() {
853
- component.invalidate?.();
854
- },
855
- handleInput: component.handleInput ? (data) => component.handleInput?.(data) : undefined,
856
- };
857
- if (component.setText) framed.setText = (value) => component.setText?.(value);
858
- if (component.getText) framed.getText = () => component.getText?.() ?? "";
859
- return framed;
860
- }
861
-
862
- /** Remove the result frame while preserving its underlying renderer component. */
863
- export function unframeToolResult<T extends FramableComponent>(component: T): T {
864
- const framed = component as Partial<FramedResultComponent>;
865
- return (framed[RESULT_FRAME]?.component ?? component) as T;
866
- }
867
-
868
- function isTextComponent(component: Component): component is TextComponentLike {
869
- return typeof (component as Partial<TextComponentLike>).setText === "function";
870
- }
871
-
872
- /** The prior render's text component (unframed) when it has one, else a fresh one. */
873
- export function reuseText(
874
- last: Component | undefined,
875
- TextComponent: TextComponentCtor = Text,
876
- ): TextComponentLike {
877
- const prior = last && unframeToolResult(last);
878
- return prior && isTextComponent(prior) ? prior : new TextComponent("", 0, 0);
879
- }
880
-
881
- /**
882
- * Default completed-tool chrome: unchanged body, full-width solid close, then
883
- * footer lines. Existing callers inherit this distro-wide presentation.
884
- */
885
- export function ruleFrame(
886
- bodyLines: string[],
887
- footerLines: string[] = [],
888
- width?: number,
889
- paint?: RulePaint,
890
- ): string[] {
891
- return [...bodyLines, rule(width ?? termW(), paint), ...footerLines];
892
- }
893
-
894
- /**
895
- * Command-output body: the first MAX_PREVIEW_LINES rows (all when expanded) with a
896
- * fading tail and an "… N more" footer. Completed output closes with a status rule;
897
- * partial output stays unframed. Returns the rows; the caller fills the background.
898
- */
899
- export function outputBodyRows(
900
- lines: string[],
901
- theme: StatusRuleTheme & MutedTheme & Parameters<typeof fadeRowsOf>[1],
902
- ctx: ExpandHintCtx,
903
- status: "success" | "error",
904
- partial: boolean,
905
- ): string[] {
906
- const maxShow = ctx.expanded ? lines.length : MAX_PREVIEW_LINES;
907
- const footer = lines.length > maxShow ? [moreLines(lines.length - maxShow, theme, ctx)] : [];
908
- // Fade the last preview rows instead of a hard cut before the "… N more" row.
909
- const body = fadeRowsOf(
910
- lines.slice(0, maxShow + 1).map((line) => bodyLine(line, theme)),
911
- theme,
912
- maxShow,
913
- );
914
- return partial
915
- ? [...body, ...footer]
916
- : ruleFrame(body, footer, termW(), fadeRulePaint(theme, status));
917
- }
918
-
919
- /** Explicit solid top/bottom frame for sections that need stronger separation. */
920
- export function sectionFrame(
921
- bodyLines: string[],
922
- footerLines: string[] = [],
923
- width?: number,
924
- paint?: RulePaint,
925
- ): string[] {
926
- const r = rule(width ?? termW(), paint);
927
- return [r, ...bodyLines, r, ...footerLines];
928
- }
929
-
930
- export function lnum(n: number, w: number): string {
289
+ export function lineNumber(n: number, w: number): string {
931
290
  const v = String(n);
932
291
  return `${FG_LNUM}${" ".repeat(Math.max(0, w - v.length))}${v}${RST}`;
933
292
  }
934
-
935
- // ---------------------------------------------------------------------------
936
- // Human-readable file size
937
- // ---------------------------------------------------------------------------
938
-
939
- export function humanSize(bytes: number): string {
940
- if (bytes < 1024) return `${bytes} B`;
941
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
942
- if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
943
- return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
944
- }
945
-
946
- // ---------------------------------------------------------------------------
947
- // File-type icons — Nerd Font glyphs (Seti-UI + Devicons, stable in NF v3+)
948
- //
949
- // Requires a Nerd Font installed (e.g., JetBrainsMono Nerd Font, FiraCode NF).
950
- // Fallback: set PRETTY_ICONS=none to disable icons.
951
- // ---------------------------------------------------------------------------
952
-
953
- export function isTextContent(content: ToolContent): content is ToolTextContent {
954
- return content.type === "text";
955
- }
956
-
957
- export function isImageContent(content: ToolContent): content is ToolImageContent {
958
- return content.type === "image";
959
- }
960
-
961
- export function getTextContent(result: ToolResultLike): string {
962
- return (
963
- result.content
964
- ?.filter(isTextContent)
965
- .map((content) => content.text || "")
966
- .join("\n") ?? ""
967
- );
968
- }
969
-
970
- /** Add renderer metadata without discarding execution metadata from the upstream tool. */
971
- export function setResultDetails<T>(result: ToolResultLike, details: T): void {
972
- const upstream =
973
- result.details && typeof result.details === "object"
974
- ? (result.details as Record<string, unknown>)
975
- : undefined;
976
- result.details = upstream ? { ...upstream, ...details } : details;
977
- }
978
-
979
- export function makeTextResult<TDetails>(
980
- text: string,
981
- details: TDetails,
982
- ): ToolResultLike<TDetails> {
983
- return {
984
- content: [{ type: "text", text }],
985
- details,
986
- };
987
- }
988
-
989
- /** Details of an action tool (download, proc): an outcome plus model-facing lines or an error. */
990
- export interface ActionResultDetails {
991
- action: string;
992
- ok: boolean;
993
- lines: string[];
994
- error?: string;
995
- }
996
-
997
- /** Tool result for an action: the error, else the lines, else `<action> ok`. */
998
- export function makeActionResult<TDetails extends ActionResultDetails>(details: TDetails) {
999
- return {
1000
- content: [
1001
- {
1002
- type: "text" as const,
1003
- text: details.error ?? (details.lines.join("\n") || `${details.action} ok`),
1004
- },
1005
- ],
1006
- details,
1007
- isError: !details.ok,
1008
- };
1009
- }
1010
-
1011
- export function appendNotices(text: string, notices: string[]): string {
1012
- return notices.length ? `${text}\n\n[${notices.join(". ")}]` : text;
1013
- }
1014
-
1015
- export function countRipgrepMatches(text: string): number {
1016
- return text
1017
- .trim()
1018
- .split("\n")
1019
- .filter((line) => /^.+?[:-]\d+[:-]/.test(line)).length;
1020
- }
1021
-
1022
- export function getErrorMessage(error: unknown): string {
1023
- return error instanceof Error ? error.message : String(error);
1024
- }
1025
-
1026
- export function trimToUndefined(value: string | undefined): string | undefined {
1027
- const trimmed = value?.trim();
1028
- return trimmed ? trimmed : undefined;
1029
- }