@giladbarnea/pi-pretty-bash 1.0.4 → 1.0.5

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 (3) hide show
  1. package/README.md +12 -12
  2. package/index.ts +184 -86
  3. package/package.json +8 -4
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ---
2
- last_updated: 2026-10-25T20-28
2
+ last_updated: 2026-11-02T20-46
3
3
  ---
4
4
 
5
5
  <div align="center">
@@ -13,33 +13,33 @@ last_updated: 2026-10-25T20-28
13
13
  [![license](https://img.shields.io/github/license/giladbarnea/pi-pretty-bash)](LICENSE)
14
14
  [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
15
15
 
16
- `pi-pretty-bash` adds theme-aware syntax colors to Bash tool calls and JSON output in Pi's TUI.
16
+ `pi-pretty-bash` gives Bash commands and results a compact boxed display with theme-aware syntax colors.
17
17
 
18
18
  </div>
19
19
 
20
- <p align="center">
21
- <img src="screenshots/1.png" alt="A syntax-highlighted Bash tool call in Pi" width="760">
22
- </p>
23
-
24
20
  ## Install
25
21
 
26
22
  ```sh
27
23
  pi install npm:@giladbarnea/pi-pretty-bash
28
24
  ```
29
25
 
30
- Start a new Pi session, or run `/reload` in the current session. Every later Bash tool call is highlighted automatically.
26
+ Alternatively, install from Git with `pi install git:github.com/giladbarnea/pi-pretty-bash`, or use `pi install /path/to/pi-pretty-bash` for development. Enable only one copy, then start a new Pi session or run `/reload`.
27
+
28
+ ## Rich Bash layout without replacing the Bash tool
29
+
30
+ Short commands get syntax colors in the header. Multiline commands get numbered boxes, and long commands wrap without losing their end. Result boxes show status, elapsed time and line counts. Collapsed results show ten visual tail rows; expansion shows the complete returned text.
31
31
 
32
- ## Bash commands and JSON output get syntax colors
32
+ The Bash palette preserves the former personal `bash-rich-highlight` choices, including function colors for built-ins. It uses `cli-highlight` with Pi theme colors, not the former HTML parser or hardcoded installation paths.
33
33
 
34
- The extension registers Bash renderers through Pi's `registerToolRenderer()` API without replacing Bash parameters or execution. It highlights the visible command with Pi's Bash colors.
34
+ Complete valid JSON up to 200 KiB gets Pi's JSON colors without reformatting. Larger JSON, partial output and unrecognized formats stay plain. Rendering never cuts or changes the result sent to the model. Failure captions use Pi's error flag, not text that merely resembles an exit-status message.
35
35
 
36
- After a command finishes, valid JSON up to 200 KiB gets Pi's JSON colors without reformatting. Larger output keeps Pi's native rendering without cutting its content. All other output keeps Pi's built-in rendering.
36
+ Source-provided terminal formatting and control characters are removed before display. The renderer then applies its own colors; tool results and programmatic data remain unchanged.
37
37
 
38
- Pi still owns command execution, streaming output, timing, truncation, expansion, and error display.
38
+ The extension uses `registerToolRenderer()` without replacing Bash parameters or execution. Timers stop when calls finish, the agent run ends or the session shuts down.
39
39
 
40
40
  ## Compatibility
41
41
 
42
- `pi-pretty-bash` targets Pi `1.4.*`. Other extensions can own the Bash tool and add parameters without changing this rendering.
42
+ `pi-pretty-bash` supports Pi `1.4.*` and `1.5.*`. Other extensions can own the Bash tool and add parameters without changing this rendering. If another extension also draws Bash, load pretty-bash first to select this display. Broader terminal-layout extensions may still style the surrounding tool block.
43
43
 
44
44
  ## License
45
45
 
package/index.ts CHANGED
@@ -1,120 +1,218 @@
1
+ import { stripVTControlCharacters } from "node:util";
1
2
  import {
2
- createBashToolDefinition,
3
3
  highlightCode,
4
+ keyHint,
4
5
  truncateToVisualLines,
5
6
  type BashToolDetails,
6
7
  type ExtensionAPI,
8
+ type Theme,
7
9
  type ToolRenderers,
8
10
  } from "@earendil-works/pi-coding-agent";
11
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
12
+ import { highlight } from "cli-highlight";
9
13
 
10
- const BASH_PREVIEW_LINES = 5;
11
14
  const JSON_HIGHLIGHT_MAX_BYTES = 200 * 1024;
15
+ const OUTPUT_PREVIEW_ROWS = 10;
16
+ const RESET = "\x1b[0m";
17
+
18
+ type BashArguments = { command?: string; timeout?: number };
19
+ type Result = Parameters<NonNullable<ToolRenderers["renderResult"]>>[0];
20
+ type RenderState = { startedAt?: number; endedAt?: number; timer?: ReturnType<typeof setInterval> };
21
+ type Context = Omit<Parameters<NonNullable<ToolRenderers["renderCall"]>>[2], "state"> & { state: RenderState };
22
+ type ParsedOutput = { body: string; status: string };
23
+
24
+ class BashDisplay implements Component {
25
+ private width?: number;
26
+ private lines?: string[];
27
+ private draw: (width: number) => string[];
28
+
29
+ constructor(draw: (width: number) => string[]) {
30
+ this.draw = draw;
31
+ }
32
+
33
+ invalidate(): void {
34
+ this.lines = undefined;
35
+ }
36
+
37
+ render(width: number): string[] {
38
+ if (this.lines && this.width === width) return this.lines;
39
+ this.width = width;
40
+ this.lines = this.draw(Math.max(1, width - 1)).map(line => truncateToWidth(line, width));
41
+ return this.lines;
42
+ }
43
+ }
44
+
45
+ /** Apply the old Bash token palette without its hand-written HTML parser.
46
+ * @example bashColors('echo "$HOME"', theme) // Built-ins use syntaxFunction; variables use syntaxVariable.
47
+ */
48
+ function bashColors(command: string, theme: Theme): string {
49
+ const colors = {
50
+ attr: "syntaxVariable", built_in: "syntaxFunction", comment: "syntaxComment",
51
+ function: "syntaxFunction", keyword: "syntaxKeyword", literal: "syntaxNumber",
52
+ meta: "muted", number: "syntaxNumber", operator: "syntaxOperator",
53
+ params: "syntaxVariable", property: "syntaxVariable", punctuation: "syntaxPunctuation",
54
+ string: "syntaxString", subst: "syntaxOperator", symbol: "syntaxVariable",
55
+ title: "syntaxFunction", type: "syntaxType", variable: "syntaxVariable",
56
+ } as const;
57
+ const formatters = Object.fromEntries(Object.entries(colors).map(([scope, token]) => [scope, (text: string) => theme.fg(token, text)]));
58
+ return highlight(command, { language: "bash", ignoreIllegals: true, theme: { ...formatters, default: (text: string) => text } });
59
+ }
12
60
 
13
- interface RenderComponent {
14
- render(width: number): string[];
61
+ /** Name the command after environment assignments and common launch prefixes.
62
+ * @example commandName('MODE=test env bash script.sh') // "bash"
63
+ */
64
+ function commandName(command: string): string {
65
+ return command.trim().split(/\s+/).find(word => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) && !["command", "env", "nohup", "sudo", "time"].includes(word)) ?? "Bash";
15
66
  }
16
67
 
17
- interface ComponentContainer extends RenderComponent {
18
- children: RenderComponent[];
68
+ /** Describe multiline commands, pipelines, heredocs and timeouts.
69
+ * @example commandFacts('cat file | sort', undefined) // ["1 pipe"]
70
+ */
71
+ function commandFacts(command: string, timeout: number | undefined): string[] {
72
+ const lines = command.split("\n").length;
73
+ const pipes = command.match(/(?<!\|)\|(?!\|)/g)?.length ?? 0;
74
+ return [
75
+ ...(lines > 1 ? [`${lines} lines`] : []),
76
+ ...(pipes > 0 ? [`${pipes} pipe${pipes === 1 ? "" : "s"}`] : []),
77
+ ...(/(^|[^<])<<-?/.test(command) ? ["heredoc"] : []),
78
+ ...(typeof timeout === "number" ? [`timeout ${timeout}s`] : []),
79
+ ];
80
+ }
81
+
82
+ /** Draw a Bash input or output box at the available width.
83
+ * @example box(["hello"], 12, theme) // A three-row box containing hello.
84
+ */
85
+ function box(rows: string[], width: number, theme: Theme, caption = ""): string[] {
86
+ const border = (text: string) => theme.fg("borderMuted", text);
87
+ const innerWidth = Math.max(1, width - 4);
88
+ const title = truncateToWidth(caption, Math.max(1, width - 6));
89
+ const top = title
90
+ ? `${border("┌─")} ${title} ${border("─".repeat(Math.max(1, width - 5 - visibleWidth(title))) + "┐")}`
91
+ : border(`┌${"─".repeat(Math.max(1, width - 2))}┐`);
92
+ return [
93
+ top,
94
+ ...rows.map(row => `${border("│")} ${row}${" ".repeat(Math.max(0, innerWidth - visibleWidth(row)))}${RESET} ${border("│")}`),
95
+ border(`└${"─".repeat(Math.max(1, width - 2))}┘`),
96
+ ];
19
97
  }
20
98
 
21
- function hasChildren(component: RenderComponent): component is ComponentContainer {
22
- return "children" in component && Array.isArray(component.children);
99
+ /** Keep the complete command, using a numbered box only for multiline input.
100
+ * @example commandRows({command: "echo hi"}, theme, false).render(80) // A syntax-colored Bash header.
101
+ */
102
+ function commandRows(args: BashArguments, theme: Theme, pending: boolean): Component {
103
+ const command = displayText(args.command ?? "");
104
+ const sourceLines = command.split("\n");
105
+ const highlighted = bashColors(command, theme).split("\n");
106
+ const firstLine = sourceLines[0].trim() || "…";
107
+ const firstLineColored = bashColors(firstLine, theme);
108
+ const prefix = `${theme.fg(pending ? "warning" : "accent", "● ")}${theme.bold("Bash ")}`;
109
+ const facts = commandFacts(command, args.timeout);
110
+ const suffix = facts.length ? theme.fg("dim", ` · ${facts.join(" · ")}`) : "";
111
+ const candidates = [
112
+ `${prefix}${firstLineColored}${suffix}`,
113
+ `${prefix}${firstLineColored}`,
114
+ `${prefix}${theme.fg("accent", commandName(command))}${suffix}`,
115
+ `${prefix}${theme.fg("accent", commandName(command))}`,
116
+ prefix.trimEnd(),
117
+ ];
118
+ return new BashDisplay(width => {
119
+ const header = candidates.find(candidate => visibleWidth(candidate) <= width) ?? candidates[4];
120
+ if (sourceLines.length === 1 && visibleWidth(candidates[0]) <= width) return [header];
121
+ const numberWidth = sourceLines.length > 1 ? Math.max(2, String(sourceLines.length).length) : 0;
122
+ const codeWidth = Math.max(1, width - 4 - (numberWidth ? numberWidth + 1 : 0));
123
+ const rows = highlighted.flatMap((line, index) => wrapTextWithAnsi(line || " ", codeWidth).map((segment, segmentIndex) => {
124
+ const number = segmentIndex === 0 ? theme.fg("muted", String(index + 1).padStart(numberWidth)) : " ".repeat(numberWidth);
125
+ return numberWidth ? `${number} ${segment}` : segment;
126
+ }));
127
+ return [header, ...box(rows, width, theme)];
128
+ });
129
+ }
130
+
131
+ /** Remove untrusted terminal instructions before applying renderer-owned styling.
132
+ * @example displayText('\x1b[31mhello\x1b[0m\x07') // "hello"
133
+ */
134
+ function displayText(text: string): string {
135
+ return stripVTControlCharacters(text).replace(/\r\n|\r/g, "\n").replace(/\t/g, " ").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
23
136
  }
24
137
 
25
- /**
138
+ /** Interpret Pi's error footer only when Pi marks the call as failed.
139
+ * @example parseOutput("Command exited with code 99", false, false) // {body: "Command exited with code 99", status: "✓"}
140
+ */
141
+ function parseOutput(output: string, isError: boolean, partial: boolean): ParsedOutput {
142
+ const body = displayText(output).trimEnd();
143
+ if (partial) return { body, status: "running" };
144
+ if (!isError) return { body, status: "✓" };
145
+ const match = /(?:^|\n)(Command exited with code (\d+)|Command aborted|Command timed out after (\d+) seconds)\s*$/.exec(body);
146
+ if (!match) return { body, status: "✗ failed" };
147
+ const status = match[2] ? `✗ exit ${match[2]}` : match[3] ? `✗ timeout ${match[3]}s` : "✗ aborted";
148
+ return { body: body.slice(0, match.index).trimEnd(), status };
149
+ }
150
+
151
+ /** Recognize complete JSON within the highlighting budget, without reformatting it.
26
152
  * @example isJson('{"enabled":true}') // true
27
153
  */
28
154
  function isJson(output: string): boolean {
155
+ if (output.length > JSON_HIGHLIGHT_MAX_BYTES || Buffer.byteLength(output, "utf8") > JSON_HIGHLIGHT_MAX_BYTES) return false;
29
156
  try {
30
- const parsed: unknown = JSON.parse(output);
31
- return JSON.stringify(parsed) !== undefined;
157
+ JSON.parse(output);
158
+ return true;
32
159
  } catch {
33
160
  return false;
34
161
  }
35
162
  }
36
163
 
37
164
  export default function prettyBash(pi: ExtensionAPI): void {
38
- const bashTool = createBashToolDefinition(process.cwd()) as ToolRenderers;
39
- const renderBashCall = bashTool.renderCall;
40
- const renderBashResult = bashTool.renderResult;
41
-
42
- if (!renderBashCall) {
43
- throw new Error("Pi's Bash tool has no call renderer");
44
- }
45
- if (!renderBashResult) {
46
- throw new Error("Pi's Bash tool has no result renderer");
47
- }
165
+ const active = new Set<RenderState>();
166
+ const finish = (state: RenderState): void => {
167
+ if (state.timer) clearInterval(state.timer);
168
+ state.timer = undefined;
169
+ state.endedAt ??= Date.now();
170
+ active.delete(state);
171
+ };
172
+ const stopTimers = (): void => { for (const state of active) finish(state); };
173
+ pi.on("agent_end", stopTimers);
174
+ pi.on("session_shutdown", stopTimers);
48
175
 
49
176
  const renderers: ToolRenderers = {
50
- renderCall(arguments_, theme, context) {
51
- const component = renderBashCall(arguments_, theme, context);
52
- if (!("setText" in component) || typeof component.setText !== "function") {
53
- throw new Error("Pi's Bash call renderer no longer returns mutable text");
177
+ renderShell: "self",
178
+ renderCall(args: unknown, theme: Theme, context: Context) {
179
+ const { state } = context;
180
+ if (context.executionStarted && context.isPartial && state.startedAt === undefined && state.endedAt === undefined) {
181
+ state.startedAt = Date.now();
182
+ state.timer = setInterval(context.invalidate, 1000);
183
+ state.timer.unref?.();
184
+ active.add(state);
54
185
  }
55
-
56
- const callArguments = arguments_ as Record<string, unknown>;
57
- const command = typeof callArguments.command === "string" ? callArguments.command : "";
58
- const renderedCommand = command
59
- ? highlightCode(command, "bash").join("\n")
60
- : theme.fg("toolOutput", "...");
61
- const timeout =
62
- typeof callArguments.timeout === "number"
63
- ? theme.fg("muted", ` (timeout ${callArguments.timeout}s)`)
64
- : "";
65
-
66
- component.setText(`${theme.fg("toolTitle", theme.bold("$"))} ${renderedCommand}${timeout}`);
67
- return component;
186
+ if (!context.isPartial) finish(state);
187
+ return commandRows((args ?? {}) as BashArguments, theme, context.executionStarted && context.isPartial && state.endedAt === undefined);
68
188
  },
69
-
70
- renderResult(result, options, theme, context) {
71
- const component = renderBashResult(result, options, theme, context);
72
- const output = result.content
73
- .map((content) => (content.type === "text" ? content.text : ""))
74
- .join("\n");
189
+ renderResult(result: Result, options, theme: Theme, context: Context) {
190
+ const output = result.content.filter(part => part.type === "text").map(part => part.text).join("\n");
75
191
  const details = result.details as BashToolDetails | undefined;
76
- const shouldHighlight =
77
- !options.isPartial &&
78
- !details?.truncation?.truncated &&
79
- output.length <= JSON_HIGHLIGHT_MAX_BYTES &&
80
- Buffer.byteLength(output, "utf8") <= JSON_HIGHLIGHT_MAX_BYTES &&
81
- isJson(output);
82
-
83
- if (!shouldHighlight) {
84
- return component;
85
- }
86
- // Pi renders expanded output as one component, and collapsed output as a spacer followed by its preview.
87
- const outputIndex = options.expanded ? 0 : 1;
88
- if (!hasChildren(component) || !component.children[outputIndex]) {
89
- throw new Error("Pi's Bash result renderer no longer exposes its output component");
90
- }
91
-
92
- const outputComponent = component.children[outputIndex];
93
- const renderOutput = outputComponent.render.bind(outputComponent);
94
- const highlightedOutput = highlightCode(output.trim(), "json").join("\n");
95
- const maxVisualLines = options.expanded ? Number.POSITIVE_INFINITY : BASH_PREVIEW_LINES;
96
-
97
- outputComponent.render = (width) => {
98
- const originalLines = renderOutput(width);
99
- const highlightedLines = truncateToVisualLines(
100
- highlightedOutput,
101
- maxVisualLines,
102
- width,
103
- ).visualLines;
104
- const preservedLineCount = originalLines.length - highlightedLines.length;
105
-
106
- if (preservedLineCount < 0) {
107
- throw new Error("Pi's Bash result layout changed while highlighting JSON output");
108
- }
109
-
110
- return [...originalLines.slice(0, preservedLineCount), ...highlightedLines];
111
- };
112
-
113
- return component;
192
+ const parsed = parseOutput(output, context.isError, options.isPartial);
193
+ if (details?.truncation?.truncated) parsed.body = parsed.body.replace(/\n*\[Showing [^\]]*\]\s*$/, "");
194
+ if (!options.isPartial) finish(context.state);
195
+ const duration = context.durationMs ?? (context.state.startedAt === undefined ? undefined : (context.state.endedAt ?? Date.now()) - context.state.startedAt);
196
+ const truncation = details?.truncation;
197
+ const count = parsed.body ? parsed.body.split("\n").length : 0;
198
+ const countLabel = truncation?.truncated ? `${truncation.outputLines}/${truncation.totalLines} lines` : `${count} line${count === 1 ? "" : "s"}`;
199
+ const caption = [
200
+ theme.fg(options.isPartial ? "warning" : context.isError ? "error" : "success", parsed.status),
201
+ ...(duration === undefined ? [] : [theme.fg("muted", `${(duration / 1000).toFixed(1)}s`)]),
202
+ ...(count ? [theme.fg("muted", countLabel)] : []),
203
+ ...(truncation?.truncated ? [theme.fg("warning", "truncated")] : []),
204
+ ].join(theme.fg("dim", " · "));
205
+ const highlighted = !options.isPartial && !truncation?.truncated && output.length <= JSON_HIGHLIGHT_MAX_BYTES && Buffer.byteLength(output, "utf8") <= JSON_HIGHLIGHT_MAX_BYTES && isJson(parsed.body);
206
+ const styled = highlighted ? highlightCode(parsed.body, "json").join("\n") : parsed.body.split("\n").map(line => theme.fg("toolOutput", line)).join("\n");
207
+ return new BashDisplay(width => {
208
+ if (!parsed.body.trim()) return ["", `${caption}${theme.fg("dim", " · ")}${theme.fg("muted", options.isPartial ? "waiting for output" : "no output")}`];
209
+ const innerWidth = Math.max(1, width - 4);
210
+ const { skippedCount, visualLines } = truncateToVisualLines(styled, options.expanded ? Infinity : OUTPUT_PREVIEW_ROWS, innerWidth);
211
+ const hint = skippedCount ? wrapTextWithAnsi(`${theme.fg("muted", `… ${skippedCount} earlier lines · `)}${keyHint("app.tools.expand", "to expand")}`, innerWidth) : [];
212
+ const outputPath = details?.fullOutputPath ? wrapTextWithAnsi(theme.fg("muted", `Full output: ${displayText(details.fullOutputPath)}`), width) : [];
213
+ return ["", ...box([...hint, ...visualLines], width, theme, caption), ...outputPath];
214
+ });
114
215
  },
115
216
  };
116
-
117
- pi.registerToolRenderer((toolName, next) =>
118
- toolName === "bash" ? { ...next(), ...renderers } : next(),
119
- );
217
+ pi.registerToolRenderer((name, next) => name === "bash" ? renderers : next());
120
218
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-pretty-bash",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "type": "module",
5
- "description": "Syntax-highlight Bash tool calls and JSON output in Pi's TUI.",
5
+ "description": "Rich Bash command and result displays with syntax-colored commands and JSON output.",
6
6
  "keywords": [
7
7
  "pi-package",
8
8
  "pi",
@@ -28,7 +28,8 @@
28
28
  "screenshots/1.png"
29
29
  ],
30
30
  "peerDependencies": {
31
- "@earendil-works/pi-coding-agent": "1.4.*"
31
+ "@earendil-works/pi-coding-agent": "1.4.* || 1.5.*",
32
+ "@earendil-works/pi-tui": "*"
32
33
  },
33
34
  "publishConfig": {
34
35
  "access": "public"
@@ -39,9 +40,12 @@
39
40
  ]
40
41
  },
41
42
  "devDependencies": {
42
- "@earendil-works/pi-coding-agent": "1.4.*"
43
+ "@earendil-works/pi-coding-agent": "1.5.*"
43
44
  },
44
45
  "scripts": {
45
46
  "test": "node --test test/*.test.mjs"
47
+ },
48
+ "dependencies": {
49
+ "cli-highlight": "2.1.11"
46
50
  }
47
51
  }