@giladbarnea/pi-pretty-bash 1.0.3 → 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 +15 -11
  2. package/index.ts +191 -83
  3. package/package.json +8 -4
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ ---
2
+ last_updated: 2026-11-02T20-46
3
+ ---
4
+
1
5
  <div align="center">
2
6
 
3
7
  # pi-pretty-bash
@@ -9,33 +13,33 @@
9
13
  [![license](https://img.shields.io/github/license/giladbarnea/pi-pretty-bash)](LICENSE)
10
14
  [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
11
15
 
12
- `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.
13
17
 
14
18
  </div>
15
19
 
16
- <p align="center">
17
- <img src="screenshots/1.png" alt="A syntax-highlighted Bash tool call in Pi" width="760">
18
- </p>
19
-
20
20
  ## Install
21
21
 
22
22
  ```sh
23
23
  pi install npm:@giladbarnea/pi-pretty-bash
24
24
  ```
25
25
 
26
- 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.
27
31
 
28
- ## 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.
29
33
 
30
- The extension starts from Pi's complete built-in Bash definition. 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.
31
35
 
32
- After a command finishes, the extension checks its complete output with `JSON.parse()`. Valid JSON gets Pi's JSON colors without reformatting. 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.
33
37
 
34
- 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.
35
39
 
36
40
  ## Compatibility
37
41
 
38
- `pi-pretty-bash` requires Pi `0.99.2` or newer.
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.
39
43
 
40
44
  ## License
41
45
 
package/index.ts CHANGED
@@ -1,110 +1,218 @@
1
+ import { stripVTControlCharacters } from "node:util";
1
2
  import {
2
- createBashToolDefinition,
3
3
  highlightCode,
4
+ keyHint,
4
5
  truncateToVisualLines,
6
+ type BashToolDetails,
5
7
  type ExtensionAPI,
8
+ type Theme,
9
+ type ToolRenderers,
6
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";
13
+
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
+ }
7
60
 
8
- const BASH_PREVIEW_LINES = 5;
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";
66
+ }
67
+
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
+ }
9
81
 
10
- interface RenderComponent {
11
- render(width: number): string[];
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
+ ];
97
+ }
98
+
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
+ });
12
129
  }
13
130
 
14
- interface ComponentContainer extends RenderComponent {
15
- children: RenderComponent[];
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, "");
16
136
  }
17
137
 
18
- function hasChildren(component: RenderComponent): component is ComponentContainer {
19
- return "children" in component && Array.isArray(component.children);
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 };
20
149
  }
21
150
 
22
- /**
151
+ /** Recognize complete JSON within the highlighting budget, without reformatting it.
23
152
  * @example isJson('{"enabled":true}') // true
24
153
  */
25
154
  function isJson(output: string): boolean {
155
+ if (output.length > JSON_HIGHLIGHT_MAX_BYTES || Buffer.byteLength(output, "utf8") > JSON_HIGHLIGHT_MAX_BYTES) return false;
26
156
  try {
27
- const parsed: unknown = JSON.parse(output);
28
- return JSON.stringify(parsed) !== undefined;
157
+ JSON.parse(output);
158
+ return true;
29
159
  } catch {
30
160
  return false;
31
161
  }
32
162
  }
33
163
 
34
164
  export default function prettyBash(pi: ExtensionAPI): void {
35
- const bashTool = createBashToolDefinition(process.cwd());
36
- const renderBashCall = bashTool.renderCall;
37
- const renderBashResult = bashTool.renderResult;
38
-
39
- if (!renderBashCall) {
40
- throw new Error("Pi's Bash tool has no call renderer");
41
- }
42
- if (!renderBashResult) {
43
- throw new Error("Pi's Bash tool has no result renderer");
44
- }
45
-
46
- pi.registerTool({
47
- ...bashTool,
48
-
49
- renderCall(arguments_, theme, context) {
50
- const component = renderBashCall(arguments_, theme, context);
51
- if (!("setText" in component) || typeof component.setText !== "function") {
52
- throw new Error("Pi's Bash call renderer no longer returns mutable text");
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);
175
+
176
+ const renderers: ToolRenderers = {
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);
53
185
  }
54
-
55
- const command = typeof arguments_.command === "string" ? arguments_.command : "";
56
- const renderedCommand = command
57
- ? highlightCode(command, "bash").join("\n")
58
- : theme.fg("toolOutput", "...");
59
- const timeout =
60
- typeof arguments_.timeout === "number"
61
- ? theme.fg("muted", ` (timeout ${arguments_.timeout}s)`)
62
- : "";
63
-
64
- component.setText(`${theme.fg("toolTitle", theme.bold("$"))} ${renderedCommand}${timeout}`);
65
- return component;
186
+ if (!context.isPartial) finish(state);
187
+ return commandRows((args ?? {}) as BashArguments, theme, context.executionStarted && context.isPartial && state.endedAt === undefined);
66
188
  },
67
-
68
- renderResult(result, options, theme, context) {
69
- const component = renderBashResult(result, options, theme, context);
70
- const output = result.content
71
- .map((content) => (content.type === "text" ? content.text : ""))
72
- .join("\n")
73
- .trim();
74
- const shouldHighlight =
75
- !options.isPartial && !result.details?.truncation?.truncated && isJson(output);
76
-
77
- if (!shouldHighlight) {
78
- return component;
79
- }
80
- // Pi renders expanded output as one component, and collapsed output as a spacer followed by its preview.
81
- const outputIndex = options.expanded ? 0 : 1;
82
- if (!hasChildren(component) || !component.children[outputIndex]) {
83
- throw new Error("Pi's Bash result renderer no longer exposes its output component");
84
- }
85
-
86
- const outputComponent = component.children[outputIndex];
87
- const renderOutput = outputComponent.render.bind(outputComponent);
88
- const highlightedOutput = highlightCode(output, "json").join("\n");
89
- const maxVisualLines = options.expanded ? Number.POSITIVE_INFINITY : BASH_PREVIEW_LINES;
90
-
91
- outputComponent.render = (width) => {
92
- const originalLines = renderOutput(width);
93
- const highlightedLines = truncateToVisualLines(
94
- highlightedOutput,
95
- maxVisualLines,
96
- width,
97
- ).visualLines;
98
- const preservedLineCount = originalLines.length - highlightedLines.length;
99
-
100
- if (preservedLineCount < 0) {
101
- throw new Error("Pi's Bash result layout changed while highlighting JSON output");
102
- }
103
-
104
- return [...originalLines.slice(0, preservedLineCount), ...highlightedLines];
105
- };
106
-
107
- return component;
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");
191
+ const details = result.details as BashToolDetails | undefined;
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
+ });
108
215
  },
109
- });
216
+ };
217
+ pi.registerToolRenderer((name, next) => name === "bash" ? renderers : next());
110
218
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-pretty-bash",
3
- "version": "1.0.3",
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": ">=0.99.2"
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.1.0"
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
  }