Skip to content

Instantly share code, notes, and snippets.

@samfoy
Created April 19, 2026 18:22
Show Gist options
  • Select an option

  • Save samfoy/aaae144970dcf1f85019d2d80537e114 to your computer and use it in GitHub Desktop.

Select an option

Save samfoy/aaae144970dcf1f85019d2d80537e114 to your computer and use it in GitHub Desktop.
pi extension: compact Claude Code-style tool result display (read/bash/edit/write/grep/find/ls show one-line summaries instead of full output)
/**
* pi-compact-tools — Compact tool result display
*
* Overrides built-in tool rendering to show a condensed "Claude Code style" view:
* - read: shows path + line count instead of full file contents
* - bash: shows command + exit code/line count instead of full output
* - edit: shows path + edit count
* - write: shows path + byte count
* - grep: shows pattern + match count
* - find: shows pattern + result count
* - ls: shows path + entry count
*
* Full output still goes to the LLM — only the TUI display is compacted.
* Press the expand key (default: e) on any tool to see the full built-in rendering.
*/
import type { ExtensionAPI, Theme } from "@mariozechner/pi-coding-agent";
import {
createReadTool,
createBashTool,
createEditTool,
createWriteTool,
createGrepTool,
createFindTool,
createLsTool,
keyHint,
} from "@mariozechner/pi-coding-agent";
import { Text } from "@mariozechner/pi-tui";
import { basename } from "node:path";
// ── Helpers ──────────────────────────────────────────────────────────────
function textContent(result: any): string {
const first = result?.content?.[0];
return first?.type === "text" ? first.text : "";
}
function lineCount(text: string): number {
if (!text) return 0;
return text.split("\n").length;
}
function shortPath(path: string): string {
// Show last 2 segments for readability
const parts = path.replace(/^\//, "").split("/");
if (parts.length <= 2) return path;
return "…/" + parts.slice(-2).join("/");
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes}B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
// ── Extension ────────────────────────────────────────────────────────────
export default function (pi: ExtensionAPI) {
// We need cwd for creating tools — get it from session_start
let cwd = process.cwd();
pi.on("session_start", async (_event, ctx) => {
cwd = ctx.cwd;
});
// ── read ──────────────────────────────────────────────────────────────
const readBuiltin = createReadTool(cwd);
pi.registerTool({
name: "read",
label: "Read",
description: readBuiltin.description,
parameters: readBuiltin.parameters,
prepareArguments: readBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return readBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
const path = (args.path ?? "").replace(/^@/, "");
let s = theme.fg("toolTitle", theme.bold("Read "));
s += theme.fg("accent", shortPath(path));
if (args.offset || args.limit) {
const parts: string[] = [];
if (args.offset) parts.push(`offset:${args.offset}`);
if (args.limit) parts.push(`limit:${args.limit}`);
s += theme.fg("dim", ` (${parts.join(", ")})`);
}
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, context) {
if (isPartial) {
return new Text(theme.fg("dim", "Reading…"), 0, 0);
}
const text = textContent(result);
const isError = text.startsWith("Error") || text.startsWith("Access denied");
const path = (context.args?.path ?? "").replace(/^@/, "");
if (isError) {
return new Text(theme.fg("error", "✗ ") + theme.fg("muted", text.split("\n")[0]), 0, 0);
}
// Check if it was an image
const hasImage = result.content?.some((c: any) => c.type === "image");
if (hasImage) {
return new Text(
theme.fg("success", "✔ ") + theme.fg("muted", `${basename(path)} (image)`),
0,
0,
);
}
const lines = lineCount(text);
const bytes = Buffer.byteLength(text, "utf-8");
const truncated = result.details?.truncation?.truncated;
let s = theme.fg("success", "✔ ");
s += theme.fg("muted", `${lines} lines`);
s += theme.fg("dim", ` (${formatBytes(bytes)})`);
if (truncated) {
s += theme.fg("warning", " [truncated]");
}
if (!expanded) {
s += theme.fg("dim", ` ${keyHint("app.tools.expand", "to expand")}`);
}
if (expanded) {
// Show first ~20 lines as preview
const preview = text.split("\n").slice(0, 30).join("\n");
s += "\n" + theme.fg("dim", preview);
if (lines > 30) {
s += "\n" + theme.fg("dim", `… ${lines - 30} more lines`);
}
}
return new Text(s, 0, 0);
},
});
// ── bash ─────────────────────────────────────────────────────────────
const bashBuiltin = createBashTool(cwd);
pi.registerTool({
name: "bash",
label: "Bash",
description: bashBuiltin.description,
parameters: bashBuiltin.parameters,
executionMode: "sequential",
prepareArguments: bashBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return bashBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
const cmd = args.command ?? "";
// Show first line of command, truncated
const firstLine = cmd.split("\n")[0];
const display = firstLine.length > 80 ? firstLine.slice(0, 77) + "…" : firstLine;
const multiline = cmd.includes("\n");
let s = theme.fg("toolTitle", theme.bold("Bash "));
s += theme.fg("muted", display);
if (multiline) {
s += theme.fg("dim", ` (+${cmd.split("\n").length - 1} lines)`);
}
if (args.timeout) {
s += theme.fg("dim", ` timeout:${args.timeout}s`);
}
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, _context) {
if (isPartial) {
const partial = textContent(result);
const partialLines = partial ? lineCount(partial) : 0;
return new Text(
theme.fg("dim", `Running… ${partialLines > 0 ? `(${partialLines} lines so far)` : ""}`),
0,
0,
);
}
const text = textContent(result);
const lines = lineCount(text);
const truncated = result.details?.truncation?.truncated;
// Detect exit code from the output pattern
const exitMatch = text.match(/^Exit code: (\d+)/m) || text.match(/exit code[:\s]+(\d+)/i);
const exitCode = exitMatch ? parseInt(exitMatch[1], 10) : undefined;
const isError = exitCode !== undefined && exitCode !== 0;
let s: string;
if (isError) {
s = theme.fg("error", `✗ exit ${exitCode}`);
} else if (exitCode === 0) {
s = theme.fg("success", "✔ ");
} else {
s = theme.fg("success", "✔ ");
}
s += theme.fg("muted", `${lines} lines`);
const bytes = Buffer.byteLength(text, "utf-8");
s += theme.fg("dim", ` (${formatBytes(bytes)})`);
if (truncated) {
s += theme.fg("warning", " [truncated]");
}
if (!expanded) {
s += theme.fg("dim", ` ${keyHint("app.tools.expand", "to expand")}`);
}
if (expanded) {
const preview = text.split("\n").slice(0, 30).join("\n");
s += "\n" + theme.fg("dim", preview);
if (lines > 30) {
s += "\n" + theme.fg("dim", `… ${lines - 30} more lines`);
}
}
return new Text(s, 0, 0);
},
});
// ── edit ──────────────────────────────────────────────────────────────
const editBuiltin = createEditTool(cwd);
pi.registerTool({
name: "edit",
label: "Edit",
description: editBuiltin.description,
parameters: editBuiltin.parameters,
prepareArguments: editBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return editBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
const path = (args.path ?? "").replace(/^@/, "");
const editCount = args.edits?.length ?? 0;
let s = theme.fg("toolTitle", theme.bold("Edit "));
s += theme.fg("accent", shortPath(path));
s += theme.fg("dim", ` (${editCount} edit${editCount !== 1 ? "s" : ""})`);
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, context) {
if (isPartial) {
return new Text(theme.fg("dim", "Editing…"), 0, 0);
}
const text = textContent(result);
const isError = text.toLowerCase().includes("error") || text.toLowerCase().includes("failed");
if (isError) {
return new Text(theme.fg("error", "✗ ") + theme.fg("muted", text.split("\n")[0]), 0, 0);
}
let s = theme.fg("success", "✔ ") + theme.fg("muted", text.split("\n")[0]);
if (expanded) {
const rest = text.split("\n").slice(1).join("\n");
if (rest.trim()) {
s += "\n" + theme.fg("dim", rest);
}
}
return new Text(s, 0, 0);
},
});
// ── write ─────────────────────────────────────────────────────────────
const writeBuiltin = createWriteTool(cwd);
pi.registerTool({
name: "write",
label: "Write",
description: writeBuiltin.description,
parameters: writeBuiltin.parameters,
prepareArguments: writeBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return writeBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
const path = (args.path ?? "").replace(/^@/, "");
const bytes = Buffer.byteLength(args.content ?? "", "utf-8");
let s = theme.fg("toolTitle", theme.bold("Write "));
s += theme.fg("accent", shortPath(path));
s += theme.fg("dim", ` (${formatBytes(bytes)})`);
t.setText(s);
return t;
},
renderResult(result, { expanded }, theme, _context) {
const text = textContent(result);
const isError = text.toLowerCase().includes("error");
if (isError) {
return new Text(theme.fg("error", "✗ ") + theme.fg("muted", text), 0, 0);
}
let s = theme.fg("success", "✔ ") + theme.fg("muted", text.split("\n")[0]);
if (expanded) {
const rest = text.split("\n").slice(1).join("\n");
if (rest.trim()) {
s += "\n" + theme.fg("dim", rest);
}
}
return new Text(s, 0, 0);
},
});
// ── grep ──────────────────────────────────────────────────────────────
const grepBuiltin = createGrepTool(cwd);
pi.registerTool({
name: "grep",
label: "Grep",
description: grepBuiltin.description,
parameters: grepBuiltin.parameters,
prepareArguments: grepBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return grepBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
let s = theme.fg("toolTitle", theme.bold("Grep "));
s += theme.fg("accent", `"${args.pattern}"`);
if (args.path) s += theme.fg("dim", ` in ${shortPath(args.path)}`);
if (args.glob) s += theme.fg("dim", ` glob:${args.glob}`);
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, _context) {
if (isPartial) {
return new Text(theme.fg("dim", "Searching…"), 0, 0);
}
const text = textContent(result);
const lines = lineCount(text);
const noResults = text.includes("No matches found") || text.trim() === "";
const truncated = result.details?.truncation?.truncated;
if (noResults) {
return new Text(theme.fg("dim", "No matches"), 0, 0);
}
// Count match files from ripgrep output
const fileMatches = new Set(
text.split("\n").filter((l: string) => l.match(/^[^:]+:\d+:/)).map((l: string) => l.split(":")[0]),
);
let s = theme.fg("success", "✔ ");
s += theme.fg("muted", `${lines} lines`);
if (fileMatches.size > 0) {
s += theme.fg("dim", ` across ${fileMatches.size} file${fileMatches.size !== 1 ? "s" : ""}`);
}
if (truncated) {
s += theme.fg("warning", " [truncated]");
}
if (!expanded) {
s += theme.fg("dim", ` ${keyHint("app.tools.expand", "to expand")}`);
}
if (expanded) {
const preview = text.split("\n").slice(0, 30).join("\n");
s += "\n" + theme.fg("dim", preview);
if (lines > 30) {
s += "\n" + theme.fg("dim", `… ${lines - 30} more lines`);
}
}
return new Text(s, 0, 0);
},
});
// ── find ──────────────────────────────────────────────────────────────
const findBuiltin = createFindTool(cwd);
pi.registerTool({
name: "find",
label: "Find",
description: findBuiltin.description,
parameters: findBuiltin.parameters,
prepareArguments: findBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return findBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
let s = theme.fg("toolTitle", theme.bold("Find "));
s += theme.fg("accent", `"${args.pattern}"`);
if (args.path) s += theme.fg("dim", ` in ${shortPath(args.path)}`);
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, _context) {
if (isPartial) {
return new Text(theme.fg("dim", "Searching…"), 0, 0);
}
const text = textContent(result);
const noResults = text.includes("No files found") || text.trim() === "";
if (noResults) {
return new Text(theme.fg("dim", "No files found"), 0, 0);
}
const files = text.split("\n").filter((l: string) => l.trim());
const truncated = result.details?.truncation?.truncated;
let s = theme.fg("success", "✔ ");
s += theme.fg("muted", `${files.length} file${files.length !== 1 ? "s" : ""}`);
if (truncated) {
s += theme.fg("warning", " [truncated]");
}
if (!expanded) {
s += theme.fg("dim", ` ${keyHint("app.tools.expand", "to expand")}`);
}
if (expanded) {
// Show tree-like listing
for (let i = 0; i < Math.min(files.length, 30); i++) {
const isLast = i === Math.min(files.length, 30) - 1 && files.length <= 30;
const prefix = isLast ? "└─" : "├─";
s += "\n" + theme.fg("dim", ` ${prefix} `) + theme.fg("muted", files[i]);
}
if (files.length > 30) {
s += "\n" + theme.fg("dim", ` … ${files.length - 30} more`);
}
}
return new Text(s, 0, 0);
},
});
// ── ls ────────────────────────────────────────────────────────────────
const lsBuiltin = createLsTool(cwd);
pi.registerTool({
name: "ls",
label: "Ls",
description: lsBuiltin.description,
parameters: lsBuiltin.parameters,
prepareArguments: lsBuiltin.prepareArguments,
async execute(toolCallId, params, signal, onUpdate, _ctx) {
return lsBuiltin.execute(toolCallId, params, signal, onUpdate);
},
renderCall(args, theme, context) {
const t = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
let s = theme.fg("toolTitle", theme.bold("Ls "));
s += theme.fg("accent", shortPath(args.path ?? "."));
t.setText(s);
return t;
},
renderResult(result, { expanded, isPartial }, theme, _context) {
if (isPartial) {
return new Text(theme.fg("dim", "Listing…"), 0, 0);
}
const text = textContent(result);
const entries = text.split("\n").filter((l: string) => l.trim());
const truncated = result.details?.truncation?.truncated;
let s = theme.fg("success", "✔ ");
s += theme.fg("muted", `${entries.length} entr${entries.length !== 1 ? "ies" : "y"}`);
if (truncated) {
s += theme.fg("warning", " [truncated]");
}
if (!expanded) {
s += theme.fg("dim", ` ${keyHint("app.tools.expand", "to expand")}`);
}
if (expanded) {
for (let i = 0; i < Math.min(entries.length, 30); i++) {
const isLast = i === Math.min(entries.length, 30) - 1 && entries.length <= 30;
const prefix = isLast ? "└─" : "├─";
s += "\n" + theme.fg("dim", ` ${prefix} `) + theme.fg("muted", entries[i]);
}
if (entries.length > 30) {
s += "\n" + theme.fg("dim", ` … ${entries.length - 30} more`);
}
}
return new Text(s, 0, 0);
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment