@harrarz/pi-declutter-tool-calls 0.0.0-stage → 0.1.0

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
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # Pi Declutter Tool Calls
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
+ One row per tool call. Expand for the details.
4
+
5
+ This Pi 1.5+ extension supplies display-only renderers for Read, Write, Edit, Bash, Grep, Find, Ls, `fffind` and `ffgrep`. Other tools keep their renderers. It does not replace tool execution or change the results received by the model.
6
+
7
+ ```sh
8
+ pi install npm:@harrarz/pi-declutter-tool-calls
9
+ ```
10
+
11
+ Migrating from the unscoped npm package? Remove it with `pi remove npm:pi-declutter-tool-calls` before installing the scoped package. Existing Git installs use the same repository and need no change.
12
+
13
+ Click a completed tool row to expand or collapse it. Regular Pi handles clicks and wheel scrolling through the Pi transcript without switching to fullscreen. Visible tool headers can be toggled while scrolling through the transcript; this is not native shell scrollback. Fullscreen uses Pi's own mouse handling. Pi's standard **Toggle tool output** binding (default `Ctrl+O`) toggles tool output globally. The active theme supplies row backgrounds; status text, line counts and errors are readable without color.
14
+
15
+ - **Edit:** changed lines appear in aligned Before/After panes with negative/positive backgrounds. Long lines wrap within their panes.
16
+ - **Bash:** simple pipelines get compact previews; shell constructs that cannot be split confidently keep their command preview. Heredocs such as `python3 - <<'PY'` collapse to an inline-script label. Expand to see captured output and command, including the script body. Pi's own capture limits still apply.
17
+ - **Read, Write, Grep, Find, Ls:** expand for text output and arguments. Image display is managed by Pi.
18
+
19
+ Development: `npm ci && npm run check` (Node 22.19+). Tests use Pi's tool execution component, including per-row mouse expansion.
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@harrarz/pi-declutter-tool-calls",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "One row per tool call. Expand for the details.",
6
+ "keywords": [
7
+ "pi-package"
8
+ ],
9
+ "pi": {
10
+ "extensions": [
11
+ "./src/index.ts"
12
+ ]
13
+ },
14
+ "devDependencies": {
15
+ "@earendil-works/pi-coding-agent": "^1.5.2",
16
+ "@earendil-works/pi-tui": "^1.5.2",
17
+ "@types/node": "^26.6.4",
18
+ "typescript": "^7.0.2"
19
+ },
20
+ "scripts": {
21
+ "check": "tsc --noEmit && node --test test/*.test.ts"
22
+ },
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
25
+ "@earendil-works/pi-tui": ">=1.5.0"
26
+ },
27
+ "files": [
28
+ "src"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/harrarz/pi-declutter-tool-calls.git"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,81 @@
1
+ import type { ExtensionAPI, ToolRenderers } from '@earendil-works/pi-coding-agent';
2
+ import { mixColors, Text } from '@earendil-works/pi-tui';
3
+ import { basename, dirname, relative, isAbsolute } from 'node:path';
4
+ import { compactSpacing } from './spacing.ts';
5
+ import { registerRegularInput } from './regular.ts';
6
+ import { bashPreview, clean, diffRows, header, inline } from './layout.ts';
7
+
8
+ const searches = new Set(['grep', 'find', 'ffgrep', 'fffind']);
9
+ const supported = new Set(['read', 'edit', 'write', 'bash', 'ls', ...searches]);
10
+ const empty = { render: () => [], invalidate() {} };
11
+ const str = (v: unknown) => typeof v === 'string' ? v : '';
12
+
13
+ export function renderer(name: string): ToolRenderers {
14
+ const label = name[0].toUpperCase() + name.slice(1);
15
+ return {
16
+ renderShell: 'self',
17
+ renderCall(args, theme, ctx) {
18
+ const a = (args ?? {}) as Record<string, unknown>;
19
+ const path = inline(str(a.path));
20
+ const preview = name === 'bash' ? bashPreview(str(a.command)) : undefined;
21
+ ctx.state.declutterRow = true;
22
+ const local = isAbsolute(path) && ctx.cwd ? relative(ctx.cwd, path) || '.' : path;
23
+ const folder = searches.has(name) || name === 'ls' ? local || '.' : name === 'bash' ? '' : dirname(local || '.');
24
+ const directory = folder && !folder.endsWith('/') ? `${folder}/` : folder;
25
+ let title = preview?.title ?? (name === 'ls' ? 'list' : basename(local));
26
+ if (name === 'read' && typeof a.offset === 'number') title += `:${a.offset}${typeof a.limit === 'number' ? `–${a.offset + a.limit - 1}` : ''}`;
27
+ if (searches.has(name)) title = inline(str(a.pattern)) || '*';
28
+ const tool = `${ctx.expanded ? '▾' : '▸'} ${label}`;
29
+ return { invalidate() {}, render(width) {
30
+ // Pi constructs the call and result components before laying out either.
31
+ const summary = ctx.state.declutterSummary as { text: string; timeout: boolean } | undefined;
32
+ const right = ctx.isPartial ? (ctx.executionStarted ? 'running' : 'preparing') : summary?.text ?? 'done';
33
+ const time = !ctx.isPartial && ctx.durationMs != null ? `${Math.round(ctx.durationMs)}ms` : '';
34
+ const line = header(tool, title, directory, right, time, width);
35
+ if (ctx.isError && summary?.timeout) return [theme.style(line, { bg: mixColors(theme.colors.toolPendingBg, theme.colors.warning, 0.25) })];
36
+ return [theme.bg(ctx.isError ? 'toolErrorBg' : ctx.isPartial ? 'toolPendingBg' : 'toolSuccessBg', line)];
37
+ } };
38
+ },
39
+ renderResult(result, { expanded }, theme, ctx) {
40
+ const args = (ctx.args ?? {}) as Record<string, unknown>;
41
+ const output = clean(result.content.map(c => c.type === 'text' ? c.text : '').filter(Boolean).join('\n'));
42
+ const diff = name === 'edit' ? clean(str(result.details?.diff)) : '';
43
+ const lines = output.trimEnd().split('\n');
44
+ const last = lines.at(-1) ?? '';
45
+ const timeout = name === 'bash' && ctx.isError && /^Command timed out after /.test(last);
46
+ let summary: string;
47
+ if (ctx.isError) {
48
+ const code = /^Command exited with code (\d+)$/.exec(last);
49
+ summary = timeout ? last.replace(/^Command /, '') : code ? `exit ${code[1]} ${lines.slice(0,-1).reverse().find(s => s.trim()) ?? ''}` : `error: ${last}`;
50
+ } else if (diff) {
51
+ summary = `+${(diff.match(/^\+/gm) ?? []).length} −${(diff.match(/^-/gm) ?? []).length}`;
52
+ } else if (result.content.some(c => c.type === 'image')) summary = 'image';
53
+ else if (name === 'write') summary = 'written';
54
+ else summary = output.trim() ? `${lines.length} ${lines.length === 1 ? 'line' : 'lines'}` : 'no output';
55
+ if (result.details?.truncation?.truncated) summary += ' · truncated';
56
+ ctx.state.declutterSummary = { text: inline(summary), timeout };
57
+ if (!expanded) return empty;
58
+ if (diff && !ctx.isError) return { render: width => diffRows(diff, width, theme), invalidate() {} };
59
+ const blocks: string[] = [];
60
+ if (output) blocks.push(`${theme.fg('dim', 'Output')}\n${output}`);
61
+ if (name === 'bash') {
62
+ const cmd = clean(str(args.command));
63
+ const stages = bashPreview(cmd).stages;
64
+ if (stages.length) blocks.push(`${theme.fg('dim', 'Pipeline')}\n${stages.map((s,i) => (i ? '| ' : '') + s).join('\n')}`);
65
+ blocks.push(`${theme.fg('dim', 'Command' + (typeof args.timeout === 'number' ? ` · timeout ${args.timeout}s` : ''))}\n${cmd}`);
66
+ } else blocks.push(`${theme.fg('dim', 'Arguments')}\n${clean(JSON.stringify(args, null, 2))}`);
67
+ return new Text(blocks.join('\n\n'), 0, 0);
68
+ },
69
+ };
70
+ }
71
+
72
+ export default function declutterToolCalls(pi: ExtensionAPI) {
73
+ let restore: (() => void) | undefined;
74
+ pi.on('session_start', (_, ctx) => { if (ctx.mode === 'tui') restore ??= compactSpacing(); });
75
+ pi.on('session_shutdown', () => { restore?.(); restore = undefined; });
76
+ pi.registerMarkdownTransformer((text, {messageType, availableWidth}) =>
77
+ messageType === 'assistant' && text.trim() && availableWidth > 0
78
+ ? `\x1b[38;2;255;255;255m${'━'.repeat(Math.min(24, availableWidth))}\x1b[39m\n\n${text}` : text);
79
+ registerRegularInput(pi);
80
+ pi.registerToolRenderer((name, next) => supported.has(name) ? renderer(name) : next());
81
+ }
package/src/layout.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+
4
+ export const clean = (s: string) => stripTerminalSequences(s.replace(/\r\n/g, '\n')).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, '').replace(/\t/g, ' ');
5
+ export const inline = (s: string) => clean(s).replace(/\s+/g, ' ').trim();
6
+ const fit = (s: string, w: number) => w > 0 ? truncateToWidth(s, w) : '';
7
+ export function pad(s: string, w: number) {
8
+ const text = fit(s, w);
9
+ return text + ' '.repeat(Math.max(0, w - visibleWidth(text)));
10
+ }
11
+ export function header(tool: string, subject: string, directory: string, result: string, time: string, w: number) {
12
+ if (w < 52) return pad(`${tool} ${subject} ${directory} ${result} ${time}`, w);
13
+ const dir = Math.floor(w * .20), status = Math.floor(w * .24);
14
+ return [pad(tool, 8), pad(subject, w - dir - status - 24), pad(directory, dir), pad(result, status), pad(time, 12)].join(' ');
15
+ }
16
+
17
+ /** Recognize simple pipelines only. Never evaluate shell text; complex syntax stays verbatim. */
18
+ export function bashPreview(command: string) {
19
+ const script = command.match(/^\s*([\w./-]+)(?:[ \t]+-)?[ \t]*<<-?[ \t]*['"]?(\w+)['"]?[ \t]*\n/);
20
+ if (script) return { title: `${script[1]} · inline script`, stages: [] };
21
+ const fallback = { title: inline(command.split('\n')[0]) + (command.includes('\n') ? ' …' : ''), stages: [] as string[] };
22
+ const stages: string[] = [];
23
+ let quote = '', start = 0;
24
+ for (let i = 0; i < command.length; i++) {
25
+ const c = command[i];
26
+ if (c === '\\' && quote !== "'") { i++; continue; }
27
+ if (quote) { if (c === quote) quote = ''; continue; }
28
+ if (c === '"' || c === "'") { quote = c; continue; }
29
+ if (';&()<>`#$\n'.includes(c) || command.startsWith('||', i)) return fallback;
30
+ if (c === '|') { stages.push(command.slice(start, i).trim()); start = i + 1; }
31
+ }
32
+ stages.push(command.slice(start).trim());
33
+ if (quote || stages.length < 2 || stages.some(s => !s)) return fallback;
34
+ return { title: [inline(stages[0]), ...stages.slice(1).map(s => inline(s).split(' ')[0])].join(' | '), stages };
35
+ }
36
+
37
+ // Pi's EditToolDetails.diff uses a sign, padded line number, space, and source.
38
+ export function diffRows(diff: string, width: number, theme: Theme): string[] {
39
+ if (width < 3) return diff.split('\n').map(s => fit(s, width));
40
+ const l = Math.floor((width - 1) / 2), r = width - 1 - l;
41
+ const rows = [pad('Before', l) + '│' + pad('After', r)];
42
+ let minus: string[] = [], plus: string[] = [], delta = 0;
43
+ function pair(a: string, b: string, change = false) {
44
+ const left = wrapTextWithAnsi(a, l), right = wrapTextWithAnsi(b, r);
45
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
46
+ const x = pad(left[i] ?? '', l), y = pad(right[i] ?? '', r);
47
+ rows.push((change && a && left[i] !== undefined ? theme.bg('toolErrorBg', x) : x) + '│' + (change && b && right[i] !== undefined ? theme.bg('toolSuccessBg', y) : y));
48
+ }
49
+ }
50
+ function flush() {
51
+ for (let i = 0; i < Math.max(minus.length, plus.length); i++) pair(minus[i] ?? '', plus[i] ?? '', true);
52
+ delta += plus.length - minus.length; minus = []; plus = [];
53
+ }
54
+ for (const line of diff.split('\n')) {
55
+ const m = /^([+ -]) *(\d+) (.*)$/.exec(line);
56
+ if (m?.[1] === '-') minus.push(`${m[2]} − ${m[3]}`);
57
+ else if (m?.[1] === '+') plus.push(`${m[2]} + ${m[3]}`);
58
+ else { flush(); if (m) pair(`${m[2]} ${m[3]}`, `${Number(m[2]) + delta} ${m[3]}`); else pair(line, line); }
59
+ }
60
+ flush(); return rows;
61
+ }
package/src/regular.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import type { OverlayHandle, TUI } from '@earendil-works/pi-tui';
3
+ import { clean } from './layout.ts';
4
+
5
+ type Main = TUI & { captureRenderState(): { previousLines: string[]; previousWidth: number; previousHeight: number; previousViewportTop: number; hardwareCursorRow: number } };
6
+ const header = /^\s*[▸▾] (?:Bash|Read|Edit|Write|Grep|Find|Ls|Fffind|Ffgrep)\s+/;
7
+ export function registerRegularInput(pi: ExtensionAPI) {
8
+ pi.on('session_start', (_, ctx) => {
9
+ if (ctx.mode !== 'tui') return;
10
+ ctx.ui.setWidget('declutter-regular-input', tui => {
11
+ if (tui.mode !== 'regular' || typeof (tui as Main).captureRenderState !== 'function') return { render: () => [], invalidate() {} };
12
+ const main = tui as Main;
13
+ let history: string[] = [], top = 0, bottom = 0, pane: OverlayHandle | undefined;
14
+ let press = '', anchor: number | undefined;
15
+ const close = () => { pane?.hide(); pane = undefined; history = []; };
16
+ const off = ctx.ui.onTerminalInput(data => {
17
+ const report = /^\x1b\[(\d+);\d+R$/.exec(data);
18
+ if (report) { anchor = main.captureRenderState().hardwareCursorRow - (Number(report[1])-1); return { consume: true }; }
19
+ const m = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
20
+ if (!m) { if (pane) close(); return; }
21
+ if (!pane && tui.hasOverlay()) return;
22
+ const button = Number(m[1]), x = Number(m[2])-1, y = Number(m[3])-1;
23
+ if ((button === 64 || button === 65) && m[4] === 'M') {
24
+ press = '';
25
+ if (!pane && button === 64) {
26
+ const s = main.captureRenderState();
27
+ bottom = s.previousViewportTop;
28
+ if (!bottom) return { consume: true };
29
+ history = s.previousLines; top = bottom;
30
+ pane = main.showOverlay({ invalidate() {}, render: () => history.slice(top, top + main.terminal.rows) },
31
+ { width:'100%', maxHeight:'100%', row:0, col:0, nonCapturing:true });
32
+ }
33
+ if (pane) {
34
+ top = Math.max(0, Math.min(bottom, top + (button === 64 ? -3 : 3)));
35
+ if (top === bottom) close();
36
+ main.requestRender();
37
+ }
38
+ } else if (button === 0 && m[4] === 'M') press = `${x}:${y}`;
39
+ else if (button === 0 && m[4] === 'm') {
40
+ if (press === `${x}:${y}`) {
41
+ const s = main.captureRenderState();
42
+ const line = y + (pane ? top : s.previousViewportTop || (s.previousLines.length < main.terminal.rows ? anchor ?? 0 : 0));
43
+ const displayed = clean((pane ? history : s.previousLines)[line] ?? '');
44
+ const current = pane ? main.render(s.previousWidth) : s.previousLines;
45
+ if (header.test(displayed) && clean(current[line] ?? '') === displayed) {
46
+ const result = main.handleMouse?.({ type:'click',button:'left',x,y:line,screenX:x,screenY:y,width:s.previousWidth,height:current.length,shift:false,alt:false,ctrl:false });
47
+ if (result?.handled) {
48
+ if (pane) {
49
+ history = main.render(s.previousWidth);
50
+ bottom = Math.max(0, history.length - main.terminal.rows);
51
+ if (top >= bottom) close();
52
+ }
53
+ main.requestRender();
54
+ }
55
+ }
56
+ }
57
+ press = '';
58
+ }
59
+ return { consume:true };
60
+ });
61
+ main.terminal.write('\x1b[?1000h\x1b[?1006h');
62
+ const timer = setTimeout(() => main.terminal.write('\x1b[6n'), 200);
63
+ return { render: () => [], invalidate() {}, dispose() { clearTimeout(timer); off(); close(); main.terminal.write('\x1b[?1006l\x1b[?1000l'); } };
64
+ });
65
+ });
66
+ }
package/src/spacing.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { ToolExecutionComponent } from '@earendil-works/pi-coding-agent';
2
+ import { Container, type Component } from '@earendil-works/pi-tui';
3
+ import { header } from './layout.ts';
4
+
5
+ // Pi 1.5 gives every tool its own leading spacer. Reuse the first spacer as
6
+ // the shared heading and omit subsequent ones. Keep Pi's hit-test heights
7
+ // in sync with what was actually painted; other transcript content is untouched.
8
+ export function compactSpacing() {
9
+ const original = Container.prototype.render, mouse = ToolExecutionComponent.prototype.handleMouse;
10
+ const tight = new WeakSet<Component>();
11
+ const render: typeof original = function(this: Container, width) {
12
+ const lines = original.call(this, width);
13
+ if (!this.children.some(c => c instanceof ToolExecutionComponent)) return lines;
14
+ const layout = (this as unknown as {mouseLayout?: {children: {component: Component; height: number}[]}}).mouseLayout;
15
+ if (!layout) return lines;
16
+ const out: string[] = [];
17
+ let offset = 0, inTable = false;
18
+ for (const cell of layout.children) {
19
+ const part = lines.slice(offset, offset + cell.height); offset += cell.height;
20
+ const tool = cell.component;
21
+ if (tool instanceof ToolExecutionComponent && (tool as unknown as {rendererState?: {declutterRow?: boolean}}).rendererState?.declutterRow && part[0] === '' && part.length > 1) {
22
+ if (inTable) { tight.add(tool); cell.height--; }
23
+ else { tight.delete(tool); out.push(header(' Tool','Command or file','Directory','Result','Time',width)); }
24
+ out.push(...part.slice(1)); inTable = true;
25
+ } else {
26
+ tight.delete(tool); out.push(...part);
27
+ if (part.length) inTable = false;
28
+ }
29
+ }
30
+ return out;
31
+ };
32
+ const handleMouse: typeof mouse = function(this: ToolExecutionComponent, event) {
33
+ return mouse.call(this, tight.has(this) ? {...event, y:event.y+1, height:event.height+1} : event);
34
+ };
35
+ Container.prototype.render = render; ToolExecutionComponent.prototype.handleMouse = handleMouse;
36
+ return () => { if (Container.prototype.render === render) Container.prototype.render = original; if (ToolExecutionComponent.prototype.handleMouse === handleMouse) ToolExecutionComponent.prototype.handleMouse = mouse; };
37
+ }