pi-polish 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thomas van Dongen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # pi-polish
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Makes [pi](https://pi.dev)'s output look like Claude Code's: tool calls fold into short summary lines, and edits show as colored diffs.
4
+
5
+ <picture>
6
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Pringled/pi-extensions/main/assets/images/pi-polish-dark.gif">
7
+ <img src="https://raw.githubusercontent.com/Pringled/pi-extensions/main/assets/images/pi-polish-light.gif" alt="pi-polish demo">
8
+ </picture>
9
+
10
+ ```bash
11
+ pi install npm:pi-polish
12
+ ```
13
+
14
+ ## Features
15
+
16
+ - Shell commands, file reads and searches in a row fold into one line that updates while they run (`Running 2 shell commands… · 5s`) and then sums them up (`Ran 3 shell commands, read 2 files`). `ctrl+o` shows the full output.
17
+ - Edits and new files show as diffs with syntax highlighting and the changed words marked, in colors that follow your pi theme, dark or light.
18
+ - A dot on each tool row shows its status: orange while running, green when done, red if it failed.
19
+ - An orange status line shows what pi is doing, how long it has been at it and how many tokens it has written.
20
+ - `❯` marks your messages and `●` marks pi's replies.
21
+ - A short instruction to the model to change files with pi's edit and write tools instead of shell commands like `sed -i`, so you see the changes as diffs.
22
+
23
+ ## Compatibility
24
+
25
+ pi-polish only changes how pi's built-in tools are drawn; the tools themselves run exactly as before. The chat styling (the markers and the status line) reaches into pi's internal UI, so a new pi release can break that part of the look until pi-polish is updated. Your sessions are never affected. Tested with pi 1.3.
26
+
27
+ ## License
28
+
29
+ MIT
@@ -0,0 +1,166 @@
1
+ import { AssistantMessageComponent, CustomEditor, type ExtensionAPI, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
+ import { Markdown } from "@earendil-works/pi-tui";
3
+
4
+ const PROMPT = "❯";
5
+ const REPLY = "●";
6
+ const ORANGE = "\x1b[38;2;217;119;87m";
7
+ const DIM = "\x1b[2m";
8
+ const RESET = "\x1b[0m";
9
+ const SPINNER = ["·", "✢", "✳", "✶", "✻", "✽", "✻", "✶", "✳", "✢"].map((f) => `${ORANGE}${f}${RESET}`);
10
+ const LEADING_ESCAPES = /^((?:\x1b\[[0-9;]*m|\x1b\][^\x07]*\x07)*) {2}/;
11
+ const OSC133_START = "\x1b]133;A\x07";
12
+ const OSC133_END = "\x1b]133;B\x07\x1b]133;C\x07";
13
+ const patched = Symbol.for("pi-polish.patched");
14
+
15
+ function markFirstLine(line: string, marker: string): string {
16
+ return line.replace(LEADING_ESCAPES, (_m, esc: string) => `${esc}${marker} `);
17
+ }
18
+
19
+ function patchOnce(proto: any, method: string, wrap: (original: (...args: any[]) => any) => (...args: any[]) => any) {
20
+ if (!proto || typeof proto[method] !== "function" || proto[method][patched]) return;
21
+ const replacement: any = wrap(proto[method]);
22
+ replacement[patched] = true;
23
+ proto[method] = replacement;
24
+ }
25
+
26
+ export default function (pi: ExtensionAPI) {
27
+ try {
28
+ // Drop hidden thinking blocks entirely instead of rendering a "Thinking..." line plus spacers
29
+ patchOnce(AssistantMessageComponent.prototype, "updateContent", (original) =>
30
+ function (this: any, message: any, ...rest: any[]) {
31
+ // Two columns of padding so reply text lines up behind the ● marker, like tool rows
32
+ this.outputPad = Math.max(this.outputPad ?? 1, 2);
33
+ if (!this.hideThinkingBlock) original.call(this, message, ...rest);
34
+ else {
35
+ original.call(this, { ...message, content: message.content.filter((c: any) => c.type !== "thinking") }, ...rest);
36
+ this.lastMessage = message;
37
+ }
38
+ // Text blocks are the Markdown children without a default style; thinking blocks carry one
39
+ for (const child of this.contentContainer?.children ?? []) {
40
+ if (!(child instanceof Markdown) || (child as any).defaultTextStyle !== undefined || (child as any)[patched]) continue;
41
+ const render = child.render.bind(child);
42
+ child.render = (width: number) => {
43
+ const lines: string[] = render(width);
44
+ const first = lines.findIndex((l) => l.replace(/\x1b\[[0-9;]*m/g, "").trim());
45
+ if (first >= 0) lines[first] = markFirstLine(lines[first], REPLY);
46
+ return lines;
47
+ };
48
+ (child as any)[patched] = true;
49
+ }
50
+ },
51
+ );
52
+
53
+ // Past prompts: one highlighted line with the ❯ marker instead of a padded three-line box
54
+ patchOnce(UserMessageComponent.prototype, "rebuild", (original) =>
55
+ function (this: any) {
56
+ this.outputPad = Math.max(this.outputPad ?? 1, 2);
57
+ return original.call(this);
58
+ },
59
+ );
60
+ patchOnce(UserMessageComponent.prototype, "render", (original) =>
61
+ function (this: any, width: number) {
62
+ const lines: string[] = original.call(this, width);
63
+ if (lines.length < 3) return lines;
64
+ const strip = (l: string) => l.replace(OSC133_START, "").replace(OSC133_END, "");
65
+ const body = lines.slice(1, -1).map(strip);
66
+ body[0] = OSC133_START + markFirstLine(body[0], `${DIM}${PROMPT}\x1b[22m`);
67
+ body[body.length - 1] = body[body.length - 1] + OSC133_END;
68
+ return body;
69
+ },
70
+ );
71
+ } catch (err) {
72
+ console.error(`[pi-polish] could not patch message components: ${(err as Error).message}`);
73
+ }
74
+
75
+ // Orange working line: what pi is doing now, elapsed time and output tokens for this run
76
+ let started = 0;
77
+ let tokens = 0;
78
+ let streamed = 0;
79
+ let phase = "Thinking";
80
+ let timer: NodeJS.Timeout | undefined;
81
+ const fmtTokens = (n: number) => (n < 1000 ? `${n}` : `${(n / 1000).toFixed(1)}k`);
82
+ const show = (ctx: any) => {
83
+ const secs = Math.round((Date.now() - started) / 1000);
84
+ const stats = `(${secs}s · ↓ ${fmtTokens(tokens + Math.round(streamed / 4))} tokens)`;
85
+ ctx.ui.setWorkingMessage(`${ORANGE}${phase}…${RESET} ${DIM}${stats}${RESET}`);
86
+ };
87
+ const toolPhase = (name: string, args: any) => {
88
+ const path = String(args?.path ?? "").split("/").pop();
89
+ switch (name) {
90
+ case "bash":
91
+ return `Running ${String(args?.command ?? "").split("\n")[0].slice(0, 60)}`;
92
+ case "read":
93
+ return `Reading ${path}`;
94
+ case "edit":
95
+ return `Editing ${path}`;
96
+ case "write":
97
+ return `Writing ${path}`;
98
+ case "grep":
99
+ case "find":
100
+ return `Searching for ${String(args?.pattern ?? "").slice(0, 40)}`;
101
+ case "bg_run":
102
+ return "Starting a background job";
103
+ case "questionnaire":
104
+ return "Waiting for your answer";
105
+ default:
106
+ return `Running ${name}`;
107
+ }
108
+ };
109
+ pi.on("session_start", async (_event, ctx) => {
110
+ if (ctx.hasUI) ctx.ui.setWorkingIndicator({ frames: SPINNER, intervalMs: 120 });
111
+ });
112
+ pi.on("agent_start", async (_event, ctx) => {
113
+ if (!ctx.hasUI) return;
114
+ started = Date.now();
115
+ tokens = 0;
116
+ streamed = 0;
117
+ phase = "Thinking";
118
+ show(ctx);
119
+ clearInterval(timer);
120
+ timer = setInterval(() => show(ctx), 1000);
121
+ });
122
+ pi.on("message_update", async (event, ctx) => {
123
+ if (!ctx.hasUI || event.message.role !== "assistant") return;
124
+ const parts = (event.message as any).content ?? [];
125
+ const last = parts[parts.length - 1];
126
+ phase = last?.type === "text" ? "Responding" : last?.type === "toolCall" ? "Preparing a tool call" : "Thinking";
127
+ streamed = parts.reduce((n: number, c: any) => n + (c.text?.length ?? c.thinking?.length ?? 0), 0);
128
+ });
129
+ pi.on("message_end", async (event) => {
130
+ if (event.message.role !== "assistant") return;
131
+ tokens += (event.message as any).usage?.output ?? 0;
132
+ streamed = 0;
133
+ });
134
+ pi.on("tool_execution_start", async (event, ctx) => {
135
+ if (!ctx.hasUI) return;
136
+ phase = toolPhase(event.toolName, event.args);
137
+ show(ctx);
138
+ });
139
+ pi.on("tool_execution_end", async () => {
140
+ phase = "Thinking";
141
+ });
142
+ pi.on("agent_end", async (_event, ctx) => {
143
+ clearInterval(timer);
144
+ timer = undefined;
145
+ if (ctx.hasUI) ctx.ui.setWorkingMessage();
146
+ });
147
+ pi.on("session_shutdown", async () => clearInterval(timer));
148
+
149
+ // ❯ before the input: two columns of editor padding, with the marker drawn into the first content line
150
+ pi.on("session_start", async (_event, ctx) => {
151
+ if (!ctx.hasUI) return;
152
+ const previous = ctx.ui.getEditorComponent();
153
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => {
154
+ const editor: any = previous?.(tui, theme, keybindings) ?? new CustomEditor(tui, theme, keybindings);
155
+ const render = editor.render.bind(editor);
156
+ editor.render = (width: number) => {
157
+ // Set on every render because pi may apply its own editor padding setting after creation
158
+ editor.paddingX = 2;
159
+ const lines: string[] = render(width);
160
+ if (lines.length > 1) lines[1] = markFirstLine(lines[1], PROMPT);
161
+ return lines;
162
+ };
163
+ return editor;
164
+ });
165
+ });
166
+ }
@@ -0,0 +1,609 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import {
4
+ getLanguageFromPath,
5
+ highlightCode,
6
+ keyHint,
7
+ type ExtensionAPI,
8
+ type ToolRenderers,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { type Component, Container, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
+ import bash from "@shikijs/langs/shellscript";
12
+ import css from "@shikijs/langs/css";
13
+ import c from "@shikijs/langs/c";
14
+ import diff from "@shikijs/langs/diff";
15
+ import docker from "@shikijs/langs/docker";
16
+ import go from "@shikijs/langs/go";
17
+ import html from "@shikijs/langs/html";
18
+ import ini from "@shikijs/langs/ini";
19
+ import java from "@shikijs/langs/java";
20
+ import javascript from "@shikijs/langs/javascript";
21
+ import json from "@shikijs/langs/json";
22
+ import jsonc from "@shikijs/langs/jsonc";
23
+ import jsx from "@shikijs/langs/jsx";
24
+ import lua from "@shikijs/langs/lua";
25
+ import make from "@shikijs/langs/make";
26
+ import markdown from "@shikijs/langs/markdown";
27
+ import python from "@shikijs/langs/python";
28
+ import rust from "@shikijs/langs/rust";
29
+ import sql from "@shikijs/langs/sql";
30
+ import toml from "@shikijs/langs/toml";
31
+ import tsx from "@shikijs/langs/tsx";
32
+ import typescript from "@shikijs/langs/typescript";
33
+ import xml from "@shikijs/langs/xml";
34
+ import yaml from "@shikijs/langs/yaml";
35
+ import darkPlus from "@shikijs/themes/dark-plus";
36
+ import lightPlus from "@shikijs/themes/light-plus";
37
+ import { diffWordsWithSpace } from "diff";
38
+ import { createHighlighterCoreSync, type HighlighterCore } from "shiki/core";
39
+ import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
40
+
41
+ const MARK = "●";
42
+
43
+ // Some models default to shell heredocs and sed even with pi's built-in guidance; these make the file tools the default
44
+ const FILE_TOOL_GUIDELINES: Record<string, string[]> = {
45
+ read: ["Use read to view file contents instead of cat, head, tail or sed -n in bash."],
46
+ edit: [
47
+ "Use edit to change existing files instead of bash: never modify files with sed -i, perl -pi, python or node scripts, or shell redirection.",
48
+ ],
49
+ write: [
50
+ "Use write to create new files or fully rewrite small ones instead of bash: never create files with cat <<EOF, echo or printf redirection, tee, or python scripts.",
51
+ "write creates missing parent directories itself, so call it directly instead of combining mkdir -p with a heredoc in bash.",
52
+ ],
53
+ };
54
+
55
+ const DIFF_PREVIEW_LINES = 16;
56
+ const BG_RESET = "\x1b[49m";
57
+ const FG_RESET = "\x1b[39m";
58
+
59
+ type Kind = "bash" | "read" | "search" | "list";
60
+ const KIND_OF: Record<string, Kind> = { bash: "bash", read: "read", grep: "search", find: "search", ls: "list" };
61
+ const VERBS: Record<Kind, [done: string, running: string, one: string, many: string]> = {
62
+ bash: ["Ran", "Running", "shell command", "shell commands"],
63
+ read: ["Read", "Reading", "file", "files"],
64
+ search: ["Searched", "Searching", "pattern", "patterns"],
65
+ list: ["Listed", "Listing", "directory", "directories"],
66
+ };
67
+
68
+ interface Member {
69
+ id: string;
70
+ kind: Kind;
71
+ label: string;
72
+ done: boolean;
73
+ error: boolean;
74
+ }
75
+
76
+ interface Group {
77
+ members: Member[];
78
+ started: number;
79
+ ended?: number;
80
+ timer?: NodeJS.Timeout;
81
+ }
82
+
83
+ type Result = { content: Array<{ type: string; text?: string }>; details?: unknown };
84
+
85
+ function resultText(result: Result): string {
86
+ return result.content
87
+ .filter((c) => c.type === "text")
88
+ .map((c) => c.text ?? "")
89
+ .join("\n");
90
+ }
91
+
92
+ function shortPath(path: unknown, cwd: string): string {
93
+ const p = String(path ?? "?");
94
+ const rel = relative(cwd, p);
95
+ return rel && !rel.startsWith("..") && !rel.startsWith("/") ? rel : p;
96
+ }
97
+
98
+ function label(toolName: string, args: any, cwd: string): string {
99
+ switch (toolName) {
100
+ case "bash":
101
+ return `$ ${String(args?.command ?? "").split("\n")[0]}`;
102
+ case "read":
103
+ return `Read ${shortPath(args?.path, cwd)}`;
104
+ case "grep":
105
+ return `Search "${args?.pattern ?? ""}"${args?.path ? ` in ${shortPath(args.path, cwd)}` : ""}`;
106
+ case "find":
107
+ return `Find "${args?.pattern ?? ""}"${args?.path ? ` in ${shortPath(args.path, cwd)}` : ""}`;
108
+ default:
109
+ return `List ${args?.path ? shortPath(args.path, cwd) : "."}`;
110
+ }
111
+ }
112
+
113
+ function summary(group: Group, running: boolean): string {
114
+ const counts = new Map<Kind, number>();
115
+ for (const m of group.members) counts.set(m.kind, (counts.get(m.kind) ?? 0) + 1);
116
+ const parts = [...counts].map(([kind, n]) => {
117
+ const [done, active, one, many] = VERBS[kind];
118
+ return `${(running ? active : done).toLowerCase()} ${n} ${n === 1 ? one : many}`;
119
+ });
120
+ const text = parts.join(", ");
121
+ return text.charAt(0).toUpperCase() + text.slice(1);
122
+ }
123
+
124
+ function expandedBody(theme: any, text: string, maxLines = 60): string {
125
+ const lines = text.split("\n");
126
+ const shown = lines.slice(0, maxLines).join("\n");
127
+ const extra = lines.length > maxLines ? `\n${theme.fg("dim", `... ${lines.length - maxLines} more lines`)}` : "";
128
+ return " " + theme.fg("toolOutput", shown).replace(/\n/g, "\n ") + extra;
129
+ }
130
+
131
+ // Shiki (TextMate grammars, as in VS Code) with Dark+ or Light+, matching Neovim's vscode.nvim.
132
+ // C++ is left out: its grammar takes ~0.5s to compile on first use and would freeze the screen; pi's highlighter covers it.
133
+ const SHIKI_LANGS = [bash, css, c, diff, docker, go, html, ini, java, javascript, json, jsonc, jsx, lua, make, markdown, python, rust, sql, toml, tsx, typescript, xml, yaml];
134
+ const EXT_TO_LANG: Record<string, string> = {
135
+ sh: "shellscript", bash: "shellscript", zsh: "shellscript", css: "css", c: "c", h: "c", diff: "diff", patch: "diff",
136
+ go: "go", html: "html", htm: "html", ini: "ini", cfg: "ini", conf: "ini", java: "java", js: "javascript",
137
+ mjs: "javascript", cjs: "javascript", json: "json", jsonc: "jsonc", jsx: "jsx", lua: "lua", mk: "make",
138
+ md: "markdown", py: "python", pyi: "python", rs: "rust", sql: "sql", toml: "toml", tsx: "tsx", ts: "typescript",
139
+ mts: "typescript", cts: "typescript", xml: "xml", yml: "yaml", yaml: "yaml",
140
+ };
141
+ const FILE_TO_LANG: Record<string, string> = { Dockerfile: "docker", Makefile: "make", makefile: "make" };
142
+ // Dark+ and Light+ leave Python calls and attributes uncolored because VS Code gets those from Pylance
143
+ const withPythonRules = (theme: any, name: string, call: string, attribute: string) => ({
144
+ ...theme,
145
+ name,
146
+ tokenColors: [
147
+ ...theme.tokenColors,
148
+ { scope: ["meta.function-call.generic"], settings: { foreground: call } },
149
+ { scope: ["meta.attribute"], settings: { foreground: attribute } },
150
+ ],
151
+ });
152
+ const SHIKI_THEMES = [withPythonRules(darkPlus, "dark-plus-pi", "#DCDCAA", "#9CDCFE"), withPythonRules(lightPlus, "light-plus-pi", "#795E26", "#001080")];
153
+ let shiki: HighlighterCore | undefined;
154
+
155
+ /** Slightly brighter and more saturated than stock Dark+, which reads as muddy on the terminal background. */
156
+ function brighten(hex: string): [number, number, number] {
157
+ // Plain code text is Dark+'s gray foreground; saturation can't lift a gray, so it maps straight to near-white
158
+ if (hex.toUpperCase().startsWith("#D4D4D4")) return [238, 238, 238];
159
+ const n = Number.parseInt(hex.slice(1, 7), 16);
160
+ let [r, g, b] = [(n >> 16) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
161
+ const max = Math.max(r, g, b);
162
+ const min = Math.min(r, g, b);
163
+ let h = 0;
164
+ let s = 0;
165
+ let l = (max + min) / 2;
166
+ if (max !== min) {
167
+ const d = max - min;
168
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
169
+ h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
170
+ h /= 6;
171
+ }
172
+ s = Math.min(1, s * 1.4);
173
+ // Lightening an already light color (function yellow, variable blue) washes it out to near-white, so only darker ones get it
174
+ if (l < 0.65) l = Math.min(0.72, l * 1.12);
175
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
176
+ const p = 2 * l - q;
177
+ const hue = (t: number) => {
178
+ const x = t < 0 ? t + 1 : t > 1 ? t - 1 : t;
179
+ return x < 1 / 6 ? p + (q - p) * 6 * x : x < 1 / 2 ? q : x < 2 / 3 ? p + (q - p) * (2 / 3 - x) * 6 : p;
180
+ };
181
+ [r, g, b] = s === 0 ? [l, l, l] : [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)];
182
+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
183
+ }
184
+
185
+ const rgb = (hex: string): [number, number, number] => {
186
+ const n = Number.parseInt(hex.slice(1, 7), 16);
187
+ return [n >> 16, (n >> 8) & 255, n & 255];
188
+ };
189
+
190
+ /** Colors for dark and light pi themes: Dark+ or Light+ code, and diff bands that suit the background. */
191
+ const PALETTES = {
192
+ dark: {
193
+ shikiTheme: "dark-plus-pi",
194
+ adjust: brighten,
195
+ defaultFg: "#D4D4D4",
196
+ typeFg: "#4EC9B0",
197
+ variableFg: "#9CDCFE",
198
+ addedBg: "\x1b[48;2;13;46;16m",
199
+ removedBg: "\x1b[48;2;63;12;16m",
200
+ // Brighter bands for the words that changed within a replaced line
201
+ addedWordBg: "\x1b[48;2;31;95;38m",
202
+ removedWordBg: "\x1b[48;2;122;30;36m",
203
+ // Line numbers and +/- signs tinted to match their band, like Claude Code, instead of dim gray
204
+ addedGutter: "\x1b[38;2;120;200;120m",
205
+ removedGutter: "\x1b[38;2;230;120;120m",
206
+ },
207
+ light: {
208
+ shikiTheme: "light-plus-pi",
209
+ adjust: rgb,
210
+ defaultFg: "#000000",
211
+ typeFg: "#267F99",
212
+ variableFg: "#001080",
213
+ addedBg: "\x1b[48;2;230;255;236m",
214
+ removedBg: "\x1b[48;2;255;235;233m",
215
+ addedWordBg: "\x1b[48;2;171;242;188m",
216
+ removedWordBg: "\x1b[48;2;255;206;203m",
217
+ addedGutter: "\x1b[38;2;26;127;55m",
218
+ removedGutter: "\x1b[38;2;207;34;46m",
219
+ },
220
+ };
221
+ type Palette = (typeof PALETTES)["dark"];
222
+
223
+ const paletteFor = (theme: any): Palette => (theme?.appearance === "light" ? PALETTES.light : PALETTES.dark);
224
+ const PY_BUILTIN_TYPES = new Set(["bool", "bytearray", "bytes", "complex", "dict", "float", "frozenset", "int", "list", "object", "set", "str", "tuple", "type"]);
225
+
226
+ /** Imported module names and aliases, from the snippet and the file on disk, so they can be colored as modules. */
227
+ function pythonModules(code: string, path: string): Set<string> {
228
+ let source = code;
229
+ try {
230
+ source += `\n${readFileSync(resolve(path), "utf8")}`;
231
+ } catch {}
232
+ const names = new Set<string>();
233
+ for (const m of source.matchAll(/^\s*import\s+([\w., ]+)/gm)) {
234
+ for (const item of m[1].split(",")) {
235
+ const [mod, alias] = item.trim().split(/\s+as\s+/);
236
+ if (mod) names.add(alias ?? mod.split(".")[0]);
237
+ }
238
+ }
239
+ for (const m of source.matchAll(/^\s*from\s+([\w.]+)\s+import/gm)) names.add(m[1].split(".")[0]);
240
+ return names;
241
+ }
242
+
243
+ /** Highlights code with Shiki when the file type is covered; undefined lets pi's own highlighter take over. */
244
+ function shikiLines(code: string, path: string, palette: Palette): string[] | undefined {
245
+ const name = path.split("/").pop() ?? "";
246
+ const lang = FILE_TO_LANG[name] ?? EXT_TO_LANG[name.split(".").pop()?.toLowerCase() ?? ""];
247
+ if (!lang) return undefined;
248
+ try {
249
+ shiki ??= createHighlighterCoreSync({ themes: SHIKI_THEMES, langs: SHIKI_LANGS, engine: createJavaScriptRegexEngine() });
250
+ const modules = lang === "python" ? pythonModules(code, path) : undefined;
251
+ const paint = (hex: string, text: string, italic = false) => {
252
+ const [r, g, b] = palette.adjust(hex);
253
+ return `\x1b[38;2;${r};${g};${b}m${italic ? "\x1b[3m" : ""}${text}${italic ? "\x1b[23m" : ""}\x1b[39m`;
254
+ };
255
+ const { defaultFg, typeFg, variableFg } = palette;
256
+ return shiki.codeToTokensBase(code, { lang, theme: palette.shikiTheme }).map((line) =>
257
+ line
258
+ .map((t) => {
259
+ const color = t.color ?? defaultFg;
260
+ // Python names the grammar leaves unscoped: color them like Neovim's tree-sitter + LSP does
261
+ if (modules && color.toUpperCase().startsWith(defaultFg)) {
262
+ return t.content.replace(/[A-Za-z_]\w*|[^A-Za-z_]+/g, (part) => {
263
+ if (!/^[A-Za-z_]/.test(part)) return paint(defaultFg, part);
264
+ if (modules.has(part) || PY_BUILTIN_TYPES.has(part)) return paint(typeFg, part);
265
+ return paint(variableFg, part);
266
+ });
267
+ }
268
+ return paint(color, t.content, Boolean((t.fontStyle ?? 0) & 1));
269
+ })
270
+ .join(""),
271
+ );
272
+ } catch {
273
+ return undefined;
274
+ }
275
+ }
276
+
277
+ type Span = [number, number];
278
+
279
+ /**
280
+ * The changed words of a replaced line, as column spans on each side (jsdiff word diff). Changes separated only by
281
+ * whitespace merge into one span. Undefined when the lines share too little for word highlighting to mean anything.
282
+ */
283
+ function changedSpans(before: string, after: string): [Span[], Span[]] | undefined {
284
+ const removed: Span[] = [];
285
+ const added: Span[] = [];
286
+ let [b, a, same] = [0, 0, 0];
287
+ const push = (spans: Span[], start: number, end: number) => {
288
+ const last = spans[spans.length - 1];
289
+ if (last && /^\s*$/.test((spans === removed ? before : after).slice(last[1], start))) last[1] = end;
290
+ else spans.push([start, end]);
291
+ };
292
+ for (const part of diffWordsWithSpace(before, after)) {
293
+ const n = part.value.length;
294
+ if (part.removed) push(removed, b, (b += n));
295
+ else if (part.added) push(added, a, (a += n));
296
+ else {
297
+ b += n;
298
+ a += n;
299
+ same += part.value.trim().length;
300
+ }
301
+ }
302
+ if (same < 0.3 * Math.max(before.trim().length, after.trim().length)) return undefined;
303
+ return [removed, added];
304
+ }
305
+
306
+ /** Puts a background on the given visible column spans of an ANSI-colored line, surviving color resets inside them. */
307
+ function withBackground(line: string, spans: Span[], on: string, off: string): string {
308
+ const marked = (col: number) => spans.some(([start, end]) => col >= start && col < end);
309
+ let out = "";
310
+ let col = 0;
311
+ let inside = false;
312
+ for (let i = 0; i < line.length; ) {
313
+ const esc = /^\x1b\[[0-9;]*m/.exec(line.slice(i));
314
+ if (esc) {
315
+ out += esc[0] + (inside && /^\x1b\[0?m$/.test(esc[0]) ? on : "");
316
+ i += esc[0].length;
317
+ continue;
318
+ }
319
+ const want = marked(col);
320
+ if (want !== inside) {
321
+ out += want ? on : off;
322
+ inside = want;
323
+ }
324
+ out += line[i++];
325
+ col++;
326
+ }
327
+ return inside ? out + off : out;
328
+ }
329
+
330
+ /**
331
+ * Renders pi's "+12 text" / "-12 text" / " 12 text" diff lines with syntax highlighting, added and
332
+ * removed lines as full-width colored bands.
333
+ */
334
+ class DiffView implements Component {
335
+ private highlighted: string[];
336
+ private palette: Palette;
337
+
338
+ constructor(
339
+ private lines: string[],
340
+ private theme: any,
341
+ private footer?: string,
342
+ path = "",
343
+ ) {
344
+ const palette = (this.palette = paletteFor(theme));
345
+ // Highlight all bodies as one snippet so multi-line strings and docstrings color correctly
346
+ const bodies = lines.map((line) => (/^[+\- ]\s*\d*\s(.*)$/.exec(line)?.[1] ?? line.slice(1)).replace(/\t/g, " "));
347
+ let highlighted: string[] = [];
348
+ try {
349
+ const code = bodies.join("\n");
350
+ const lang = getLanguageFromPath(path);
351
+ highlighted = shikiLines(code, path, palette) ?? (lang ? highlightCode(code, lang) : []);
352
+ } catch {
353
+ highlighted = [];
354
+ }
355
+ this.highlighted = highlighted.length === bodies.length ? highlighted : bodies.map((b) => theme.fg("toolTitle", b));
356
+
357
+ // Pair each run of removed lines with the added run right after it, line by line, and mark the changed words
358
+ for (let i = 0; i < lines.length; ) {
359
+ if (lines[i][0] !== "-") {
360
+ i++;
361
+ continue;
362
+ }
363
+ let removedEnd = i;
364
+ while (removedEnd < lines.length && lines[removedEnd][0] === "-") removedEnd++;
365
+ let addedEnd = removedEnd;
366
+ while (addedEnd < lines.length && lines[addedEnd][0] === "+") addedEnd++;
367
+ for (let k = 0; k < Math.min(removedEnd - i, addedEnd - removedEnd); k++) {
368
+ const [r, a] = [i + k, removedEnd + k];
369
+ const spans = changedSpans(bodies[r], bodies[a]);
370
+ if (!spans) continue;
371
+ this.highlighted[r] = withBackground(this.highlighted[r], spans[0], palette.removedWordBg, palette.removedBg);
372
+ this.highlighted[a] = withBackground(this.highlighted[a], spans[1], palette.addedWordBg, palette.addedBg);
373
+ }
374
+ i = addedEnd;
375
+ }
376
+ }
377
+
378
+ render(width: number): string[] {
379
+ const { addedBg, removedBg, addedGutter, removedGutter } = this.palette;
380
+ const out = this.lines.map((line, i) => {
381
+ const sign = line[0];
382
+ const num = /^[+\- ](\s*\d*)\s/.exec(line)?.[1] ?? "";
383
+ const gutterText = ` ${num} ${sign === " " ? " " : sign} `;
384
+ const gutter = sign === "+" ? addedGutter + gutterText + FG_RESET : sign === "-" ? removedGutter + gutterText + FG_RESET : this.theme.fg("dim", gutterText);
385
+ // Bands stop two columns short of the right edge, like Claude Code's
386
+ const inner = Math.max(10, width - 2);
387
+ const text = truncateToWidth(gutter + this.highlighted[i], inner);
388
+ if (sign === " ") return text;
389
+ const bg = sign === "+" ? addedBg : removedBg;
390
+ const pad = " ".repeat(Math.max(0, inner - visibleWidth(text)));
391
+ // Highlighter resets would end the band early, so restore the background after each one
392
+ return `${bg}${text.replace(/\x1b\[0?m/g, (m) => m + bg)}${pad}${BG_RESET}`;
393
+ });
394
+ if (this.footer) out.push(truncateToWidth(this.footer, width));
395
+ return out;
396
+ }
397
+
398
+ invalidate(): void {}
399
+ }
400
+
401
+ function lineCount(n: number): string {
402
+ return `${n} line${n === 1 ? "" : "s"}`;
403
+ }
404
+
405
+ function errorText(theme: any, text: string, expanded: boolean): Text {
406
+ const lines = text.trim().split("\n");
407
+ const body = expanded ? lines.join("\n ") : lines[0] + (lines.length > 1 ? theme.fg("dim", ` (${keyHint("app.tools.expand", "details")})`) : "");
408
+ return new Text(theme.fg("error", ` └ ${body}`), 0, 0);
409
+ }
410
+
411
+ function empty() {
412
+ return new Container();
413
+ }
414
+
415
+ export default function (pi: ExtensionAPI) {
416
+ const cwd = process.cwd();
417
+ const groupOf = new Map<string, Group>();
418
+ const rowInvalidate = new Map<string, () => void>();
419
+ let current: Group | undefined;
420
+ let live = false;
421
+ // False until session_start has grouped the history; pi draws old rows before that event
422
+ let ready = false;
423
+
424
+ const refresh = (group: Group) => {
425
+ for (const m of group.members) rowInvalidate.get(m.id)?.();
426
+ };
427
+
428
+ const tick = (group: Group) => {
429
+ const running = group.members.some((m) => !m.done);
430
+ if (running && !group.timer) group.timer = setInterval(() => rowInvalidate.get(group.members[0].id)?.(), 1000);
431
+ if (!running && group.timer) {
432
+ clearInterval(group.timer);
433
+ group.timer = undefined;
434
+ group.ended = Date.now();
435
+ }
436
+ };
437
+
438
+ const assign = (id: string, toolName: string, args: unknown, done = false, error = false): Group => {
439
+ current ??= { members: [], started: Date.now() };
440
+ current.members.push({ id, kind: KIND_OF[toolName], label: label(toolName, args, cwd), done, error });
441
+ groupOf.set(id, current);
442
+ return current;
443
+ };
444
+
445
+ const reset = () => {
446
+ for (const g of new Set(groupOf.values())) if (g.timer) clearInterval(g.timer);
447
+ groupOf.clear();
448
+ current = undefined;
449
+ ready = false;
450
+ };
451
+
452
+ // Rebuild groups for history so resumed sessions collapse the same way
453
+ pi.on("session_start", async (_event, ctx) => {
454
+ reset();
455
+ for (const entry of ctx.sessionManager.getBranch()) {
456
+ if (entry.type !== "message") continue;
457
+ const msg = entry.message as any;
458
+ if (msg.role === "user") current = undefined;
459
+ if (msg.role !== "assistant") continue;
460
+ for (const part of msg.content ?? []) {
461
+ if (part.type === "text" && part.text.trim()) current = undefined;
462
+ if (part.type !== "toolCall") continue;
463
+ if (KIND_OF[part.name]) assign(part.id, part.name, part.arguments, true);
464
+ else current = undefined;
465
+ }
466
+ }
467
+ current = undefined;
468
+ ready = true;
469
+ for (const invalidate of rowInvalidate.values()) invalidate();
470
+ // History rows were drawn before they were grouped; a full redraw clears their stale lines
471
+ if (ctx.hasUI) {
472
+ ctx.ui.setWidget("pi-polish-redraw", (tui) => {
473
+ setTimeout(() => {
474
+ ctx.ui.setWidget("pi-polish-redraw", undefined);
475
+ tui.requestRender(true);
476
+ }, 0);
477
+ return new Container();
478
+ });
479
+ }
480
+ });
481
+
482
+ pi.on("agent_start", async () => {
483
+ live = true;
484
+ current = undefined;
485
+ });
486
+ pi.on("agent_end", async () => {
487
+ live = false;
488
+ current = undefined;
489
+ });
490
+ pi.on("message_end", async (event) => {
491
+ const msg = event.message as any;
492
+ if (msg.role === "assistant" && (msg.content ?? []).some((c: any) => c.type === "text" && c.text.trim())) current = undefined;
493
+ });
494
+ pi.on("tool_execution_start", async (event) => {
495
+ if (!KIND_OF[event.toolName]) {
496
+ current = undefined;
497
+ return;
498
+ }
499
+ const group = assign(event.toolCallId, event.toolName, event.args);
500
+ tick(group);
501
+ refresh(group);
502
+ });
503
+ pi.on("tool_execution_end", async (event) => {
504
+ const group = groupOf.get(event.toolCallId);
505
+ const member = group?.members.find((m) => m.id === event.toolCallId);
506
+ if (!group || !member) return;
507
+ member.done = true;
508
+ member.error = event.isError;
509
+ tick(group);
510
+ refresh(group);
511
+ });
512
+ pi.on("session_shutdown", async () => reset());
513
+
514
+ /** Collapsed rendering for a grouped tool row; the group's first row draws the whole group. */
515
+ const renderGrouped = (toolCallId: string, theme: any, context: any): Component | undefined => {
516
+ rowInvalidate.set(toolCallId, context.invalidate);
517
+ if (context.expanded) return undefined;
518
+ const group = groupOf.get(toolCallId);
519
+ // Live rows wait for tool_execution_start to place them; history rows without a group render alone
520
+ if (!group) return live || !ready ? empty() : undefined;
521
+ if (group.members[0].id !== toolCallId) return empty();
522
+
523
+ const running = group.members.some((m) => !m.done);
524
+ const failed = group.members.filter((m) => m.error).length;
525
+ const failNote = failed ? theme.fg("error", ` · ${failed} failed`) : "";
526
+ if (running) {
527
+ const secs = Math.round((Date.now() - group.started) / 1000);
528
+ const active = [...group.members].reverse().find((m) => !m.done) ?? group.members[group.members.length - 1];
529
+ const head = theme.fg("accent", `${MARK} `) + theme.fg("toolTitle", `${summary(group, true)}…`) + theme.fg("dim", ` · ${secs}s`) + failNote;
530
+ return new Text(`${head}\n${theme.fg("dim", ` └ ${active.label}`)}`, 0, 0);
531
+ }
532
+ const hint = theme.fg("dim", ` (${keyHint("app.tools.expand", "expand")})`);
533
+ const mark = theme.fg(failed ? "error" : "success", `${MARK} `);
534
+ const text = group.members.length === 1 ? group.members[0].label : summary(group, false);
535
+ return new Text(mark + theme.fg("toolTitle", text) + failNote + hint, 0, 0);
536
+ };
537
+
538
+ // The ● carries the status, like Claude Code: dim while arguments stream, accent while running, green or red when done.
539
+ // History rows redrawn after /reload have no execution state, so they count as done.
540
+ const dot = (theme: any, context: { isPartial?: boolean; isError?: boolean; executionStarted?: boolean }) => {
541
+ if (context.isError) return theme.fg("error", `${MARK} `);
542
+ if (context.executionStarted && context.isPartial) return theme.fg("accent", `${MARK} `);
543
+ if (!context.executionStarted && live) return theme.fg("dim", `${MARK} `);
544
+ return theme.fg("success", `${MARK} `);
545
+ };
546
+
547
+ const groupedTool = (toolName: string): ToolRenderers => ({
548
+ renderShell: "self",
549
+ renderCall(args: any, theme, context) {
550
+ const grouped = renderGrouped(context.toolCallId, theme, context);
551
+ if (grouped) return grouped;
552
+ const text = truncateToWidth(label(toolName, args, cwd), 400);
553
+ return new Text(dot(theme, context) + theme.fg("toolTitle", text), 0, 0);
554
+ },
555
+ renderResult(result, { expanded }, theme) {
556
+ if (!expanded) return empty();
557
+ return new Text(expandedBody(theme, resultText(result as Result)), 0, 0);
558
+ },
559
+ });
560
+
561
+ /** An edit or write row: "Update path" or "Write path", then a stats line and a diff preview. */
562
+ const fileTool = (verb: string, diffOf: (result: any, args: any) => [stats: string, lines: string[]]): ToolRenderers => ({
563
+ renderShell: "self",
564
+ renderCall(args: any, theme, context) {
565
+ return new Text(dot(theme, context) + theme.fg("toolTitle", `${verb} ${shortPath(args?.path, cwd)}`), 0, 0);
566
+ },
567
+ renderResult(result, { expanded, isPartial }, theme, context) {
568
+ if (isPartial) return empty();
569
+ if (context.isError) return errorText(theme, resultText(result as Result), expanded);
570
+ const args = context.args as any;
571
+ const [stats, lines] = diffOf(result, args);
572
+ const shown = expanded ? lines : lines.slice(0, DIFF_PREVIEW_LINES);
573
+ const more = lines.length - shown.length;
574
+ const footer = more > 0 ? theme.fg("dim", ` … +${more} lines (${keyHint("app.tools.expand", "expand")})`) : undefined;
575
+ const box = new Container();
576
+ box.addChild(new Text(theme.fg("dim", ` └ ${stats}`), 0, 0));
577
+ box.addChild(new DiffView(shown, theme, footer, String(args?.path ?? "")));
578
+ return box;
579
+ },
580
+ });
581
+
582
+ const renderers: Record<string, ToolRenderers> = {
583
+ bash: groupedTool("bash"),
584
+ read: groupedTool("read"),
585
+ grep: groupedTool("grep"),
586
+ find: groupedTool("find"),
587
+ ls: groupedTool("ls"),
588
+ edit: fileTool("Update", (result) => {
589
+ const diff = String(result.details?.diff ?? "").split("\n").filter(Boolean);
590
+ const added = diff.filter((l) => l.startsWith("+")).length;
591
+ const removed = diff.filter((l) => l.startsWith("-")).length;
592
+ return [`Added ${lineCount(added)}, removed ${lineCount(removed)}`, diff];
593
+ }),
594
+ // A new file shows as added lines, previewed like an edit's diff
595
+ write: fileTool("Write", (_result, args) => {
596
+ const lines = String(args?.content ?? "").replace(/\n$/, "").split("\n");
597
+ const width = String(lines.length).length;
598
+ return [`Wrote ${lineCount(lines.length)}`, lines.map((line, i) => `+${String(i + 1).padStart(width)} ${line}`)];
599
+ }),
600
+ };
601
+ // Only the drawing changes: pi's own tools keep running, with their own schema and on/off state
602
+ pi.registerToolRenderer((toolName, next) => renderers[toolName] ?? next());
603
+
604
+ // pi only lists a tool's guidelines while the tool is on
605
+ pi.on("before_agent_start", async (event) => {
606
+ const guidelines = event.systemPromptOptions.toolGuidelines;
607
+ for (const [name, rules] of Object.entries(FILE_TOOL_GUIDELINES)) guidelines[name] = [...(guidelines[name] ?? []), ...rules];
608
+ });
609
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "pi-polish",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "author": "Thomas van Dongen",
6
+ "type": "module",
7
+ "homepage": "https://github.com/pringled/pi-extensions/tree/main/packages/pi-polish#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/pringled/pi-extensions/issues"
10
+ },
11
+ "files": [
12
+ "extensions",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "description": "Claude Code-style output for pi: tool calls fold into short summaries and edits show as colored diffs",
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi",
20
+ "pi-coding-agent",
21
+ "tui",
22
+ "diff",
23
+ "syntax-highlighting"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/pringled/pi-extensions.git",
28
+ "directory": "packages/pi-polish"
29
+ },
30
+ "pi": {
31
+ "extensions": [
32
+ "./extensions/tools.ts",
33
+ "./extensions/chrome.ts"
34
+ ],
35
+ "image": "https://raw.githubusercontent.com/Pringled/pi-extensions/main/assets/images/pi-polish-dark.gif"
36
+ },
37
+ "dependencies": {
38
+ "diff": "9.0.0",
39
+ "shiki": "4.5.0",
40
+ "@shikijs/langs": "4.5.0",
41
+ "@shikijs/themes": "4.5.0"
42
+ },
43
+ "peerDependencies": {
44
+ "@earendil-works/pi-coding-agent": "*",
45
+ "@earendil-works/pi-tui": "*"
46
+ }
47
+ }