pi-polish 0.1.3 → 0.1.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.
package/README.md CHANGED
@@ -13,16 +13,16 @@ pi install npm:pi-polish
13
13
 
14
14
  ## Features
15
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.
16
+ - Shell commands, file reads, searches and MCP tool calls 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` or `Called 2 MCP tools`). `ctrl+o` shows the full output.
17
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.
18
+ - Reads, searches, shell commands and MCP calls show a pulsing dot in your theme's accent color while they run, then turn into a quiet grey row once done, with a red dot if one failed. Edits and writes keep a green dot with their diff.
19
+ - An orange status line shows what Pi is doing, how long it has been at it and how many tokens it has written. When Pi finishes, a dim line says how long it worked and when it was done.
20
20
  - `❯` marks your messages and `●` marks Pi's replies.
21
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
22
 
23
23
  ## Compatibility
24
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.
25
+ pi-polish only changes how Pi's built-in tools and MCP 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.4.
26
26
 
27
27
  ## License
28
28
 
@@ -1,5 +1,6 @@
1
1
  import { AssistantMessageComponent, CustomEditor, type ExtensionAPI, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
- import { Markdown, MouseRegion, Spacer, Text } from "@earendil-works/pi-tui";
2
+ import { Markdown, MouseRegion, Spacer, Text, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import { shortCommand } from "./command.ts";
3
4
 
4
5
  const PROMPT = "❯";
5
6
  const REPLY = "●";
@@ -93,7 +94,7 @@ export default function (pi: ExtensionAPI) {
93
94
  const path = String(args?.path ?? "").split("/").pop();
94
95
  switch (name) {
95
96
  case "bash":
96
- return `Running ${String(args?.command ?? "").split("\n")[0].slice(0, 60)}`;
97
+ return `Running ${shortCommand(String(args?.command ?? ""), process.cwd()).slice(0, 60)}`;
97
98
  case "read":
98
99
  return `Reading ${path}`;
99
100
  case "edit":
@@ -107,8 +108,10 @@ export default function (pi: ExtensionAPI) {
107
108
  return "Starting a background job";
108
109
  case "questionnaire":
109
110
  return "Waiting for your answer";
111
+ case "tool_search":
112
+ return "Searching tools";
110
113
  default:
111
- return `Running ${name}`;
114
+ return name.startsWith("mcp__") ? `Calling ${name.split("__")[1]}/${name.split("__").slice(2).join("__")}` : `Running ${name}`;
112
115
  }
113
116
  };
114
117
  pi.on("session_start", async (_event, ctx) => {
@@ -116,6 +119,7 @@ export default function (pi: ExtensionAPI) {
116
119
  });
117
120
  pi.on("agent_start", async (_event, ctx) => {
118
121
  if (!ctx.hasUI) return;
122
+ showTurn(undefined);
119
123
  started = Date.now();
120
124
  tokens = 0;
121
125
  streamed = 0;
@@ -147,7 +151,31 @@ export default function (pi: ExtensionAPI) {
147
151
  pi.on("agent_end", async (_event, ctx) => {
148
152
  clearInterval(timer);
149
153
  timer = undefined;
150
- if (ctx.hasUI) ctx.ui.setWorkingMessage();
154
+ if (!ctx.hasUI) return;
155
+ ctx.ui.setWorkingMessage();
156
+ // How long the turn took and when it ended, until the next one starts
157
+ const secs = Math.round((Date.now() - started) / 1000);
158
+ const took = secs < 60 ? `${secs}s` : `${Math.floor(secs / 60)}m ${secs % 60}s`;
159
+ const done = new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
160
+ showTurn(`✻ Worked for ${took} · done ${done}`);
161
+ });
162
+ // A jump in the session tree leaves the turn behind, so its summary goes too
163
+ pi.on("session_tree", async () => showTurn(undefined));
164
+ // Set once and updated in place: setting a widget again moves it below the ones other extensions added since,
165
+ // while the turn line belongs at the top, where the working line was
166
+ let turnLine: string | undefined;
167
+ let redrawTurn = () => {};
168
+ const showTurn = (line: string | undefined) => {
169
+ turnLine = line;
170
+ redrawTurn();
171
+ };
172
+ pi.on("session_start", async (_event, ctx) => {
173
+ if (!ctx.hasUI) return;
174
+ turnLine = undefined;
175
+ ctx.ui.setWidget("pi-polish-turn", (tui, theme) => {
176
+ redrawTurn = () => tui.requestRender();
177
+ return { invalidate() {}, render: (width: number) => (turnLine ? [truncateToWidth(theme.fg("dim", turnLine), width)] : []) };
178
+ });
151
179
  });
152
180
  pi.on("session_shutdown", async () => clearInterval(timer));
153
181
 
@@ -0,0 +1,22 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { basename, isAbsolute, resolve } from "node:path";
3
+
4
+ // Real paths, so a cd through a symlink such as /tmp still counts as cwd
5
+ const real = (path: string) => {
6
+ try {
7
+ return realpathSync(path);
8
+ } catch {
9
+ return path;
10
+ }
11
+ };
12
+
13
+ /** A shell command's first line, without leading cds into cwd; another folder shows as its last part when the path is absolute. */
14
+ export function shortCommand(command: string, cwd: string): string {
15
+ const rest = command.trim().replace(/^(?:cd\s+(?:"[^"]*"|'[^']*'|\S+)[ \t]*(?:&&|;|\n)\s*)+/, (prefix) => {
16
+ const [, quoted, separator] = [...prefix.matchAll(/cd\s+("[^"]*"|'[^']*'|\S+)[ \t]*(&&|;|\n)/g)].at(-1)!;
17
+ const dir = quoted.replace(/^["']|["']$/g, "");
18
+ if (real(resolve(cwd, dir)) === real(resolve(cwd))) return "";
19
+ return `cd ${isAbsolute(dir) ? `…/${basename(dir)}` : quoted}${separator === ";" ? ";" : " &&"} `;
20
+ });
21
+ return rest.split("\n")[0];
22
+ }
@@ -7,7 +7,8 @@ import {
7
7
  type ExtensionAPI,
8
8
  type ToolRenderers,
9
9
  } from "@earendil-works/pi-coding-agent";
10
- import { type Component, Container, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
10
+ import { type Component, Container, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
11
+ import { shortCommand } from "./command.ts";
11
12
  import bash from "@shikijs/langs/shellscript";
12
13
  import css from "@shikijs/langs/css";
13
14
  import c from "@shikijs/langs/c";
@@ -56,13 +57,17 @@ const DIFF_PREVIEW_LINES = 16;
56
57
  const BG_RESET = "\x1b[49m";
57
58
  const FG_RESET = "\x1b[39m";
58
59
 
59
- type Kind = "bash" | "read" | "search" | "list";
60
- const KIND_OF: Record<string, Kind> = { bash: "bash", read: "read", grep: "search", find: "search", ls: "list" };
60
+ type Kind = "bash" | "read" | "search" | "list" | "tools" | "mcp";
61
+ const KIND_OF: Record<string, Kind> = { bash: "bash", read: "read", grep: "search", find: "search", ls: "list", tool_search: "tools" };
62
+ // Pi names MCP tools mcp__<server>__<tool>
63
+ const kindOf = (toolName: string): Kind | undefined => KIND_OF[toolName] ?? (toolName.startsWith("mcp__") ? "mcp" : undefined);
61
64
  const VERBS: Record<Kind, [done: string, running: string, one: string, many: string]> = {
62
65
  bash: ["Ran", "Running", "shell command", "shell commands"],
63
66
  read: ["Read", "Reading", "file", "files"],
64
67
  search: ["Searched", "Searching", "pattern", "patterns"],
65
68
  list: ["Listed", "Listing", "directory", "directories"],
69
+ tools: ["Ran", "Running", "tool search", "tool searches"],
70
+ mcp: ["Called", "Calling", "MCP tool", "MCP tools"],
66
71
  };
67
72
 
68
73
  interface Member {
@@ -98,15 +103,23 @@ function shortPath(path: unknown, cwd: string): string {
98
103
  function label(toolName: string, args: any, cwd: string): string {
99
104
  switch (toolName) {
100
105
  case "bash":
101
- return `$ ${String(args?.command ?? "").split("\n")[0]}`;
106
+ return `$ ${shortCommand(String(args?.command ?? ""), cwd)}`;
102
107
  case "read":
103
108
  return `Read ${shortPath(args?.path, cwd)}`;
104
109
  case "grep":
105
110
  return `Search "${args?.pattern ?? ""}"${args?.path ? ` in ${shortPath(args.path, cwd)}` : ""}`;
106
111
  case "find":
107
112
  return `Find "${args?.pattern ?? ""}"${args?.path ? ` in ${shortPath(args.path, cwd)}` : ""}`;
108
- default:
113
+ case "tool_search":
114
+ return `Search tools "${args?.query ?? ""}"`;
115
+ case "ls":
109
116
  return `List ${args?.path ? shortPath(args.path, cwd) : "."}`;
117
+ default: {
118
+ // server/tool like pi's own MCP rows, with the first text argument, which is usually the query
119
+ const [, server, ...tool] = toolName.split("__");
120
+ const first = Object.values(args ?? {}).find((v) => typeof v === "string") as string | undefined;
121
+ return `${server}/${tool.join("__")}${first ? ` "${first.split("\n")[0]}"` : ""}`;
122
+ }
110
123
  }
111
124
  }
112
125
 
@@ -412,6 +425,14 @@ function empty() {
412
425
  return new Container();
413
426
  }
414
427
 
428
+ /** Lines cut to the screen width instead of wrapping; the first line keeps its failure note in view. */
429
+ function oneLine(lines: string[], suffix = ""): Component {
430
+ return {
431
+ invalidate() {},
432
+ render: (width: number) => lines.map((line, i) => (i === 0 ? truncateToWidth(line, Math.max(10, width - visibleWidth(suffix))) + suffix : truncateToWidth(line, width))),
433
+ };
434
+ }
435
+
415
436
  export default function (pi: ExtensionAPI) {
416
437
  const cwd = process.cwd();
417
438
  const groupOf = new Map<string, Group>();
@@ -427,7 +448,7 @@ export default function (pi: ExtensionAPI) {
427
448
 
428
449
  const tick = (group: Group) => {
429
450
  const running = group.members.some((m) => !m.done);
430
- if (running && !group.timer) group.timer = setInterval(() => rowInvalidate.get(group.members[0].id)?.(), 1000);
451
+ if (running && !group.timer) group.timer = setInterval(() => rowInvalidate.get(group.members[0].id)?.(), 500);
431
452
  if (!running && group.timer) {
432
453
  clearInterval(group.timer);
433
454
  group.timer = undefined;
@@ -437,7 +458,7 @@ export default function (pi: ExtensionAPI) {
437
458
 
438
459
  const assign = (id: string, toolName: string, args: unknown, done = false, error = false): Group => {
439
460
  current ??= { members: [], started: Date.now() };
440
- current.members.push({ id, kind: KIND_OF[toolName], label: label(toolName, args, cwd), done, error });
461
+ current.members.push({ id, kind: kindOf(toolName)!, label: label(toolName, args, cwd), done, error });
441
462
  groupOf.set(id, current);
442
463
  return current;
443
464
  };
@@ -452,7 +473,10 @@ export default function (pi: ExtensionAPI) {
452
473
  // Rebuild groups for history so resumed sessions collapse the same way
453
474
  pi.on("session_start", async (_event, ctx) => {
454
475
  reset();
455
- for (const entry of ctx.sessionManager.getBranch()) {
476
+ const branch = ctx.sessionManager.getBranch();
477
+ // Tool results come after their calls, so collect the failures first
478
+ const failed = new Set(branch.flatMap((e: any) => (e.type === "message" && e.message.role === "toolResult" && e.message.isError ? [e.message.toolCallId] : [])));
479
+ for (const entry of branch) {
456
480
  if (entry.type !== "message") continue;
457
481
  const msg = entry.message as any;
458
482
  if (msg.role === "user") current = undefined;
@@ -460,7 +484,7 @@ export default function (pi: ExtensionAPI) {
460
484
  for (const part of msg.content ?? []) {
461
485
  if (part.type === "text" && part.text.trim()) current = undefined;
462
486
  if (part.type !== "toolCall") continue;
463
- if (KIND_OF[part.name]) assign(part.id, part.name, part.arguments, true);
487
+ if (kindOf(part.name)) assign(part.id, part.name, part.arguments, true, failed.has(part.id));
464
488
  else current = undefined;
465
489
  }
466
490
  }
@@ -492,7 +516,7 @@ export default function (pi: ExtensionAPI) {
492
516
  if (msg.role === "assistant" && (msg.content ?? []).some((c: any) => c.type === "text" && c.text.trim())) current = undefined;
493
517
  });
494
518
  pi.on("tool_execution_start", async (event) => {
495
- if (!KIND_OF[event.toolName]) {
519
+ if (!kindOf(event.toolName)) {
496
520
  current = undefined;
497
521
  return;
498
522
  }
@@ -526,31 +550,44 @@ export default function (pi: ExtensionAPI) {
526
550
  if (running) {
527
551
  const secs = Math.round((Date.now() - group.started) / 1000);
528
552
  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);
553
+ // The dot pulses every half second while the group runs, like a cursor blink
554
+ const pulse = Math.floor(Date.now() / 500) % 2 ? "dim" : "accent";
555
+ const head = theme.fg(pulse, `${MARK} `) + theme.fg("toolTitle", `${summary(group, true)}…`) + theme.fg("dim", ` · ${secs}s`) + failNote;
556
+ return oneLine([head, theme.fg("dim", ` └ ${active.label}`)]);
531
557
  }
532
- const hint = theme.fg("dim", ` (${keyHint("app.tools.expand", "expand")})`);
533
- const mark = theme.fg(failed ? "error" : "success", `${MARK} `);
558
+ // Finished rows go quiet, like Claude Code's: dim text, with a red ● only when something failed
559
+ const mark = failed ? theme.fg("error", `${MARK} `) : " ";
534
560
  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);
561
+ return oneLine([mark + theme.fg("dim", text)], failNote);
536
562
  };
537
563
 
538
564
  // The ● carries the status, like Claude Code: dim while arguments stream, accent while running, green or red when done.
539
565
  // 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} `);
566
+ const status = (context: { isPartial?: boolean; isError?: boolean; executionStarted?: boolean }) => {
567
+ if (context.isError) return "error";
568
+ if (context.executionStarted && context.isPartial) return "accent";
569
+ if (!context.executionStarted && live) return "dim";
570
+ return "success";
545
571
  };
572
+ const dot = (theme: any, context: any) => theme.fg(status(context), `${MARK} `);
546
573
 
547
574
  const groupedTool = (toolName: string): ToolRenderers => ({
548
575
  renderShell: "self",
549
576
  renderCall(args: any, theme, context) {
550
577
  const grouped = renderGrouped(context.toolCallId, theme, context);
551
578
  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);
579
+ // Expanded, a shell command shows in full, with its cd and every line; collapsed rows keep the short label
580
+ const command = context.expanded && toolName === "bash" ? String(args?.command ?? "").trim().split("\n") : undefined;
581
+ const text = command ? `$ ${command.slice(0, 60).join("\n")}${command.length > 60 ? `\n... ${command.length - 60} more lines` : ""}` : truncateToWidth(label(toolName, args, cwd), 400);
582
+ // Finished rows are dim without a dot; running and failed ones keep it
583
+ const done = status(context) === "success";
584
+ const mark = done ? " " : dot(theme, context);
585
+ // Wrapped lines continue under the text, past the dot, instead of at the left edge
586
+ return {
587
+ invalidate() {},
588
+ render: (width: number) =>
589
+ wrapTextWithAnsi(text, Math.max(10, width - 2)).map((line, i) => (i === 0 ? mark : " ") + theme.fg(done ? "dim" : "toolTitle", line)),
590
+ };
554
591
  },
555
592
  renderResult(result, { expanded }, theme) {
556
593
  if (!expanded) return empty();
@@ -599,7 +636,19 @@ export default function (pi: ExtensionAPI) {
599
636
  }),
600
637
  };
601
638
  // 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());
639
+ pi.registerToolRenderer((toolName, next) => {
640
+ if (renderers[toolName] || !kindOf(toolName)) return renderers[toolName] ?? next();
641
+ const own = groupedTool(toolName);
642
+ if (kindOf(toolName) !== "mcp") return own;
643
+ // Expanded MCP results keep pi's own view, which shows images and limits long one-line JSON. It gets
644
+ // no lastComponent, since that may be the empty component drawn while the row was collapsed.
645
+ const pis = next()?.renderResult;
646
+ return {
647
+ ...own,
648
+ renderResult: (result, options, theme, context) =>
649
+ options.expanded && pis ? pis(result, options, theme, { ...context, lastComponent: undefined }) : own.renderResult!(result, options, theme, context),
650
+ };
651
+ });
603
652
 
604
653
  // pi only lists a tool's guidelines while the tool is on
605
654
  pi.on("before_agent_start", async (event) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-polish",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "license": "MIT",
5
5
  "author": "Thomas van Dongen",
6
6
  "type": "module",