1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
|
/**
* sl0p Tool Boxes
*
* Reframes the built-in tool rows (bash, read, edit, write, grep, find, ls)
* in the same rounded-border "sl0peration" style used by the last-prompt
* topbar widget — a labelled top border, │ side rails, and a rounded bottom.
*
* It does NOT reimplement tool behavior or output: it grabs each built-in
* tool *definition* (execute + native renderCall/renderResult, so syntax
* highlighting, diffs, truncation warnings etc. are preserved) and wraps the
* lines those native renderers produce inside the frame.
*
* Border/state palette (matches last-prompt.ts):
* pending -> warning (◉)
* success -> dim (✓)
* error -> error (✗)
*
* Note: overriding built-in tools makes interactive mode print a one-time
* "overriding built-in tool" warning per tool. That is expected.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import {
createBashToolDefinition,
createReadToolDefinition,
createEditToolDefinition,
createWriteToolDefinition,
createGrepToolDefinition,
createFindToolDefinition,
createLsToolDefinition,
keyHint,
} from "@earendil-works/pi-coding-agent";
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
// Minimal structural types so we don't fight the full generics.
type Theme = any;
type Component = { render(width: number): string[]; invalidate?: () => void };
type ToolDef = {
name: string;
label?: string;
description: string;
parameters: any;
promptSnippet?: string;
execute: (...a: any[]) => any;
renderCall?: (args: any, theme: Theme, context: any) => Component;
renderResult?: (result: any, options: any, theme: Theme, context: any) => Component;
};
const H = "─";
const V = "│";
const TL = "╭";
const TR = "╮";
const BL = "╰";
const BR = "╯";
type Status = "pending" | "ok" | "error";
type Paint = (s: string) => string;
function borderColorFor(status: Status): string {
return status === "error" ? "error" : status === "pending" ? "warning" : "dim";
}
// ── Pulsing border for in-progress tools ────────────────────────────────────
// Only tools that are ACTUALLY EXECUTING IN THIS SESSION animate. "Active" is
// driven strictly by live tool_execution_start/end events keyed by toolCallId —
// NOT by render-time status. This is critical: on session restore (`pi -c`)
// every finished tool row re-renders, and if we inferred "pending" from the
// default status we'd mark them all active and start a 10fps invalidate storm
// that never settles (the startup-flicker lockup). Restored rows fire no
// tool_execution_start, so they never pulse. A single module-level timer
// re-paints active rows at 10fps and stops the instant none are active.
// Anti-flicker: only the horizontal top/bottom borders pulse; side rails stay a
// static color so streaming output never triggers a full-box repaint.
const PULSE: Array<[number, number, number]> = [
[0xff, 0x8a, 0x1e], // amber
[0xff, 0x2e, 0x88], // hot pink
[0xb0, 0x5c, 0xff], // violet
[0x2e, 0xd6, 0xff], // cyan
];
const PULSE_PERIOD = 40; // frames per full palette trip (~4s at 10fps)
const FRAME_MS = 100;
function lerp(a: number, b: number, t: number): number {
return Math.round(a + (b - a) * t);
}
function pulseRGB(phase: number): [number, number, number] {
const n = PULSE.length;
const x = ((((phase % 1) + 1) % 1) * n);
const i = Math.floor(x) % n;
const j = (i + 1) % n;
const t = x - Math.floor(x);
const a = PULSE[i];
const b = PULSE[j];
return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)];
}
function fgRGB(rgb: [number, number, number], s: string): string {
return `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${s}\x1b[39m`;
}
let tick = 0;
let animTimer: ReturnType<typeof setInterval> | undefined;
const activeIds = new Set<string>(); // toolCallIds executing in THIS session
const rowsById = new Map<string, FrameState>(); // toolCallId -> row state (for the timer)
function pulsePaint(): Paint {
const rgb = pulseRGB((tick % PULSE_PERIOD) / PULSE_PERIOD);
return (s: string) => fgRGB(rgb, s);
}
function solidPaint(theme: Theme, color: string): Paint {
return (s: string) => theme.fg(color, s);
}
function ensureAnim(): void {
if (animTimer) return;
animTimer = setInterval(() => {
tick++;
if (activeIds.size === 0) {
clearInterval(animTimer);
animTimer = undefined;
return;
}
for (const id of activeIds) rowsById.get(id)?.ctxInvalidate?.();
}, FRAME_MS);
}
function markActive(id: string | undefined): void {
if (!id) return;
activeIds.add(id);
ensureAnim();
}
function clearActive(id: string | undefined): void {
if (id) activeIds.delete(id);
}
function stopAllAnim(): void {
activeIds.clear();
if (animTimer) {
clearInterval(animTimer);
animTimer = undefined;
}
}
function statusIcon(status: Status, theme: Theme): string {
if (status === "error") return theme.fg("error", "✗");
if (status === "pending") return theme.fg("warning", "◉");
return theme.fg("success", "✓");
}
// Collapse $HOME to ~ for tidier header paths.
function prettyPath(p: string): string {
const home = process.env.HOME;
return home && p.startsWith(home) ? "~" + p.slice(home.length) : p;
}
function stripAnsi(s: string): string {
// eslint-disable-next-line no-control-regex
return s.replace(/\x1b\[[0-9;]*m/g, "");
}
// ── Diff line backgrounds (edit tool) ───────────────────────────────────────
const DIFF_ADDED_BG = "#123521"; // dark green fill behind added lines
const DIFF_REMOVED_BG = "#3a1620"; // dark red fill behind removed lines
function hexBg(hex: string, s: string): string {
const h = hex.replace("#", "");
const r = parseInt(h.slice(0, 2), 16);
const g = parseInt(h.slice(2, 4), 16);
const b = parseInt(h.slice(4, 6), 16);
return `\x1b[48;2;${r};${g};${b}m${s}\x1b[49m`;
}
// Remove any background SGR codes so our diff background is the only one and
// isn't overridden by the native edit component's per-line Box background.
function stripBg(s: string): string {
return s
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[48;2;\d+;\d+;\d+m/g, "")
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[48;5;\d+m/g, "")
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[(?:4[0-7]|10[0-7]|49)m/g, "");
}
// Fill added/removed diff rows with a background across the full inner width.
// Detects the leading +/- marker (ignoring +++/--- headers) on the stripped
// text; context/other lines are left untouched.
function applyDiffBackgrounds(lines: string[], bodyInner: number): string[] {
return lines.map((line) => {
// Drop the native per-line background so ours actually shows.
const stripped = stripBg(line);
// The native edit component indents diff rows (Box padding), so look at the
// first non-space char for the +/- marker (ignoring +++/--- headers).
const t = stripAnsi(stripped).replace(/^\s+/, "");
let bg: string | undefined;
if (t[0] === "+" && t[1] !== "+") bg = DIFF_ADDED_BG;
else if (t[0] === "-" && t[1] !== "-") bg = DIFF_REMOVED_BG;
if (!bg) return stripped; // context/other rows: native tint removed, no fill
let s = stripped;
if (visibleWidth(s) > bodyInner) s = truncateToWidth(s, bodyInner, "…");
const pad = Math.max(0, bodyInner - visibleWidth(s));
return hexBg(bg, s + " ".repeat(pad));
});
}
// When we hoist the path into the header, drop the native call's redundant
// leading "<tool> <path>" line (and any following blank spacer) while keeping
// the rest of its body (e.g. edit renders its diff in renderCall).
function stripRedundantCallLines(lines: string[], name: string): string[] {
let i = 0;
while (i < lines.length) {
const t = stripAnsi(lines[i]).trim();
if (t === "" || t === name || t.startsWith(name + " ")) {
i++;
continue;
}
break;
}
return lines.slice(i);
}
// Per-tool header summary: the key argument hoisted into the top border so we
// can drop the redundant native call line (e.g. "edit <path>").
const HEADER_SUMMARY: Record<string, (args: any) => string | undefined> = {
edit: (a) => (a?.path ? prettyPath(a.path) : undefined),
read: (a) => (a?.path ? prettyPath(a.path) : undefined),
write: (a) => (a?.path ? prettyPath(a.path) : undefined),
ls: (a) => (a?.path ? prettyPath(a.path) : undefined),
};
const READ_PREVIEW_LINES = 10;
// Per-tool result-body override. Returning undefined falls back to the native
// renderResult. Read hides its content unless expanded, so we synthesize a
// short inline preview of the chunk it read (native full output on expand).
const RESULT_PREVIEW: Record<
string,
(result: any, options: any, theme: Theme) => string[] | undefined
> = {
read: (result, options, theme) => {
if (options?.expanded) return undefined; // expanded -> use native full output
const block = Array.isArray(result?.content)
? result.content.find((b: any) => b?.type === "text")
: undefined;
const text = typeof block?.text === "string" ? block.text : "";
if (!text.trim()) return undefined;
const all = text.split("\n");
while (all.length && all[all.length - 1].trim() === "") all.pop();
const shown = all.slice(0, READ_PREVIEW_LINES).map((l: string) => theme.fg("toolOutput", l));
const more = all.length - READ_PREVIEW_LINES;
if (more > 0) {
shown.push(theme.fg("muted", `… ${more} more lines (`) + keyHint("app.tools.expand", "to expand") + theme.fg("muted", ")"));
}
return shown;
},
};
// Top border: ╭─ ✓ bash ───────────────╮ (label carries its own colors)
function frameTop(width: number, label: string, paint: Paint): string {
const innerWidth = Math.max(0, width - 2);
const leftLen = innerWidth > 2 ? 1 : 0;
let content = ` ${label} `;
// Keep at least one trailing dash; truncate an over-long header so it never
// overflows the box width.
const maxContent = Math.max(0, innerWidth - leftLen - 1);
if (visibleWidth(content) > maxContent) content = truncateToWidth(content, maxContent, "…");
const rightLen = Math.max(0, innerWidth - leftLen - visibleWidth(content));
return (
paint(TL) +
paint(H.repeat(leftLen)) +
content +
paint(H.repeat(rightLen)) +
paint(TR)
);
}
function frameBottom(width: number, paint: Paint): string {
const innerWidth = Math.max(0, width - 2);
return paint(BL + H.repeat(innerWidth) + BR);
}
// Wrap already-rendered inner lines with │ … │ rails and padding.
function frameBody(lines: string[], width: number, paint: Paint): string[] {
const v = paint(V);
const innerWidth = Math.max(0, width - 4); // 2 rails + 2 padding spaces
return lines.map((raw) => {
let line = raw;
if (visibleWidth(line) > innerWidth) line = truncateToWidth(line, innerWidth, "…");
const pad = Math.max(0, innerWidth - visibleWidth(line));
return `${v} ${line}${" ".repeat(pad)} ${v}`;
});
}
type FrameState = {
inner: Record<string, unknown>; // private state bag handed to the native renderer
callInner?: Component;
resultInner?: Component;
status: Status;
resultActive: boolean; // true once the result slot starts rendering (it then owns the bottom border)
ctxInvalidate?: () => void; // row rerender trigger (updateDisplay + requestRender)
toolCallId?: string; // used to match live tool_execution_start/end events
// Inner-line caches persisted on the row state so they survive the
// updateDisplay() rebuilds our pulse timer triggers each tick. Keyed by width;
// reset when the underlying args/result change (or on invalidate/theme change).
callArgsRef?: any;
summaryText?: string;
callW: number;
callLines?: string[];
resultRef?: any;
resultExpanded?: boolean;
resultW: number;
resultLines?: string[];
};
function ensureState(context: any): FrameState {
if (!context.state.__slopFrame) {
context.state.__slopFrame = {
inner: {},
status: "pending" as Status,
resultActive: false,
callW: -1,
resultW: -1,
};
}
const st = context.state.__slopFrame as FrameState;
if (context.toolCallId) {
st.toolCallId = context.toolCallId;
rowsById.set(context.toolCallId, st);
}
return st;
}
// A row animates only if its tool is executing in THIS session (event-driven).
function isActiveRow(st: FrameState): boolean {
return !!st.toolCallId && activeIds.has(st.toolCallId);
}
// A context for the native renderer: its own state bag + its own lastComponent.
function childCtx(context: any, st: FrameState, slot: "call" | "result") {
return {
...context,
state: st.inner,
lastComponent: slot === "call" ? st.callInner : st.resultInner,
};
}
function registerFramedTool(pi: ExtensionAPI, def: ToolDef) {
const displayName = def.name;
const summarize = HEADER_SUMMARY[def.name];
pi.registerTool({
name: def.name,
label: def.label ?? def.name,
description: def.description,
parameters: def.parameters,
promptSnippet: def.promptSnippet,
renderShell: "self", // we draw our own frame + background
async execute(toolCallId, params, signal, onUpdate, ctx) {
return def.execute(toolCallId, params, signal, onUpdate, ctx);
},
renderCall(args, theme, context) {
const st = ensureState(context);
st.ctxInvalidate = context.invalidate;
// Rebuild the native call component only when the args actually change
// (not on every pulse-driven updateDisplay). edit draws its diff here; the
// redundant leading "<tool> <path>" line is stripped in the inner cache.
if (args !== st.callArgsRef) {
st.callInner = def.renderCall
? def.renderCall(args, theme, childCtx(context, st, "call"))
: undefined;
st.callArgsRef = args;
st.summaryText = summarize ? summarize(args) : undefined;
st.callW = -1;
}
// (Whether this row animates is decided by live tool_execution events, not
// here — see isActiveRow / the event handlers in the default export.)
// Inner-line cache lives on `st` (survives updateDisplay). Only the native
// render + diff regex are expensive; the frame is rebuilt cheaply so it can
// re-paint with the pulse color each tick without recomputing content.
const innerLines = (width: number): string[] => {
if (st.callW === width && st.callLines) return st.callLines;
let lines = st.callInner ? st.callInner.render(Math.max(1, width - 4)) : [];
if (st.summaryText) lines = stripRedundantCallLines(lines, displayName);
if (displayName === "edit") lines = applyDiffBackgrounds(lines, Math.max(1, width - 4));
st.callW = width;
st.callLines = lines;
return lines;
};
let cw = -1;
let cl: string[] = [];
return {
render(width: number): string[] {
const activeNow = isActiveRow(st);
const status: Status = activeNow ? "pending" : st.status;
const base =
statusIcon(status, theme) + " " + theme.fg("toolTitle", theme.bold(displayName));
const label = st.summaryText ? base + " " + theme.fg("accent", st.summaryText) : base;
const inner = innerLines(width);
// IMPORTANT (anti-flicker): the side rails + body use a STATIC status
// color; only the horizontal top/bottom borders pulse. Pulsing the
// rails recolors every body line each frame, which forces a full-box
// repaint while a tool streams output (edit/write) and reads as violent
// flicker. Keeping rails static means streaming only redraws the new
// content line, and the pulse only touches 1-2 border lines. (NOTES.md)
const build = (border: Paint, rail: Paint): string[] => {
const out = [frameTop(width, label, border), ...frameBody(inner, width, rail)];
// While the result slot hasn't started rendering yet (still-running
// tool), close the box here so the frame is never bottomless.
if (!st.resultActive) out.push(frameBottom(width, border));
return out;
};
const rail = solidPaint(theme, borderColorFor(status));
if (activeNow) {
cw = -1; // don't cache while animating; recompute solid once settled
return build(pulsePaint(), rail);
}
if (width === cw) return cl;
cl = build(rail, rail);
cw = width;
return cl;
},
invalidate() {
cw = -1;
st.callW = -1;
st.callArgsRef = undefined; // rebuild native on theme change
st.callInner?.invalidate?.();
},
};
},
renderResult(result, options, theme, context) {
const st = ensureState(context);
st.ctxInvalidate = context.invalidate;
st.status = context.isError ? "error" : options.isPartial ? "pending" : "ok";
st.resultActive = true; // the result slot now owns the bottom border
// NOTE: do NOT call context.invalidate() here. renderResult runs during
// rendering, so invalidating would schedule another render that calls
// renderResult again -> infinite render loop (hangs pi). The pulse timer
// drives invalidation from OUTSIDE the render pass instead.
// Rebuild the native result component only when result/expand changes.
if (result !== st.resultRef || options.expanded !== st.resultExpanded) {
st.resultInner = def.renderResult
? def.renderResult(result, options, theme, childCtx(context, st, "result"))
: {
render: () => {
const c = result?.content?.[0];
const text = c?.type === "text" ? String(c.text) : "";
return text.split("\n");
},
};
st.resultRef = result;
st.resultExpanded = options.expanded;
st.resultW = -1;
}
// (Animation is event-driven; see isActiveRow / default export handlers.)
const preview = RESULT_PREVIEW[displayName];
const innerLines = (width: number): string[] => {
if (st.resultW === width && st.resultLines) return st.resultLines;
let lines: string[] | undefined;
if (preview) lines = preview(result, options, theme);
if (lines === undefined) {
lines = st.resultInner ? st.resultInner.render(Math.max(1, width - 4)) : [];
}
// Completed edits render their diff in the result slot — give +/- rows a bg.
if (displayName === "edit") lines = applyDiffBackgrounds(lines, Math.max(1, width - 4));
st.resultW = width;
st.resultLines = lines;
return lines;
};
let cw = -1;
let cl: string[] = [];
return {
render(width: number): string[] {
const inner = innerLines(width);
const activeNow = isActiveRow(st);
// Anti-flicker: static rails/body, only the bottom border pulses.
const railColor = activeNow ? "warning" : borderColorFor(st.status);
const rail = solidPaint(theme, railColor);
const build = (border: Paint): string[] => [
...frameBody(inner, width, rail),
frameBottom(width, border),
];
if (activeNow) {
cw = -1;
return build(pulsePaint());
}
if (width === cw) return cl;
cl = build(rail);
cw = width;
return cl;
},
invalidate() {
cw = -1;
st.resultW = -1;
st.resultRef = undefined; // rebuild native on theme change
st.resultInner?.invalidate?.();
},
};
},
});
}
export default function (pi: ExtensionAPI) {
const cwd = process.cwd();
const defs: ToolDef[] = [
createBashToolDefinition(cwd) as unknown as ToolDef,
createReadToolDefinition(cwd) as unknown as ToolDef,
createEditToolDefinition(cwd) as unknown as ToolDef,
createWriteToolDefinition(cwd) as unknown as ToolDef,
createGrepToolDefinition(cwd) as unknown as ToolDef,
createFindToolDefinition(cwd) as unknown as ToolDef,
createLsToolDefinition(cwd) as unknown as ToolDef,
];
for (const def of defs) registerFramedTool(pi, def);
// Animation is driven ONLY by live execution events, so restored/finished rows
// (e.g. on `pi -c`) never animate. A row pulses from tool_execution_start until
// tool_execution_end; the refresh() nudges the row to repaint immediately.
const refresh = (id: string | undefined) => {
if (id) rowsById.get(id)?.ctxInvalidate?.();
};
pi.on("tool_execution_start", (event: any) => {
markActive(event.toolCallId);
refresh(event.toolCallId);
});
pi.on("tool_execution_end", (event: any) => {
clearActive(event.toolCallId);
refresh(event.toolCallId);
});
// Safety net: guarantee the timer stops even if an end event is missed
// (abort/error). agent_settled fires when the run is no longer producing tool
// output; session_shutdown on teardown.
pi.on("agent_settled", stopAllAnim);
pi.on("session_shutdown", stopAllAnim);
}
|