@casualjim/pi-pretty 0.7.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.
@@ -0,0 +1,119 @@
1
+ /* pi-pretty: ls tool -- directory listing with styled output. */
2
+
3
+ import type { AgentToolResult, ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
+ import { BG_ERROR, FG_DIM, RST, resolveBaseBackground, TOOL_RESULT_INDENT } from "../config.js";
5
+ import { shortPath } from "../helpers.js";
6
+ import {
7
+ fillToolBackground,
8
+ fillToolBody,
9
+ rememberToolTitle,
10
+ renderToolError,
11
+ renderToolMetrics,
12
+ renderTree,
13
+ setCollapsedToolTitle,
14
+ } from "../render.js";
15
+ import { resolveTextCtor } from "../tui-text.js";
16
+ import type { LsDetails, RenderCtxLike, SdkToolDef, TextContent, ThemeLike } from "../types.js";
17
+ import { wrapExecuteWithMetrics } from "./metrics.js";
18
+
19
+ type Result = AgentToolResult<Record<string, unknown>>;
20
+
21
+ export function registerLsTool(
22
+ pi: ExtensionAPI,
23
+ cwd: string,
24
+ _fffService: unknown,
25
+ sdkTool: SdkToolDef,
26
+ TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
27
+ ): void {
28
+ const home = process.env.HOME ?? "";
29
+ const TC = resolveTextCtor(TextComp);
30
+
31
+ // SAFETY: the object below matches the host ToolDefinition contract at runtime
32
+ // (name/parameters schema plus execute/renderCall/renderResult), but its loose
33
+ // internal shape cannot be named as the host's generic type here. pi validates
34
+ // the schema and invokes the callbacks with host types.
35
+ pi.registerTool({
36
+ name: "ls",
37
+ label: "List",
38
+ description: sdkTool.description ?? "List directory contents",
39
+ parameters: sdkTool.parameters,
40
+ promptSnippet: sdkTool.promptSnippet,
41
+ renderShell: "self",
42
+
43
+ execute: wrapExecuteWithMetrics(async (tid, params, sig, _upd, ctx: ExtensionContext) => {
44
+ const result = (await sdkTool.execute(tid, params, sig, undefined, ctx)) as Result;
45
+ const tc = getText(result);
46
+ result.details = {
47
+ _type: "lsResult",
48
+ text: tc,
49
+ path: String((params as any).path ?? ""),
50
+ entryCount: tc ? tc.trim().split("\n").filter(Boolean).length : 0,
51
+ } as LsDetails;
52
+ return result;
53
+ }),
54
+
55
+ renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
56
+ resolveBaseBackground(theme);
57
+ const text = ctx.lastComponent ?? new TC("", 0, 0);
58
+ const rawPath = args.path;
59
+ const path =
60
+ rawPath === null || rawPath === undefined || String(rawPath).length === 0
61
+ ? ""
62
+ : shortPath(cwd, home, String(rawPath));
63
+ const limit = args.limit;
64
+ let out = theme.fg("toolTitle", theme.bold("ls"));
65
+ if (path) out += ` ${theme.fg("accent", path)}`;
66
+ if (limit !== undefined && limit !== null) out += theme.fg("toolOutput", ` (limit ${limit})`);
67
+ const renderTitle = (suffix = ""): string =>
68
+ fillToolBackground(`\n${TOOL_RESULT_INDENT}${out}${suffix}\n`, ctx.isError ? BG_ERROR : undefined);
69
+ rememberToolTitle(ctx, text, renderTitle);
70
+ text.setText(renderTitle());
71
+ return text;
72
+ },
73
+
74
+ renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
75
+ resolveBaseBackground(theme);
76
+
77
+ const text = ctx.lastComponent ?? new TC("", 0, 0);
78
+ if (ctx.isError) {
79
+ text.setText(renderToolError(getText(result) || "Error", theme));
80
+ return text;
81
+ }
82
+ const d = result.details as LsDetails | undefined;
83
+ if (d?._type === "lsResult" && d.text) {
84
+ if (!ctx.expanded) {
85
+ const summary = `${FG_DIM}${d.entryCount} entries — ctrl+o to expand${RST}${renderToolMetrics(result)}`;
86
+ if (setCollapsedToolTitle(ctx, text, ` ${summary}`)) return text;
87
+ text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${summary}`));
88
+ return text;
89
+ }
90
+ const rendered = renderTree(d.text, d.path)
91
+ .split("\n")
92
+ .map((l) => `${TOOL_RESULT_INDENT}${l}`)
93
+ .join("\n");
94
+ text.setText(
95
+ fillToolBody(
96
+ `${TOOL_RESULT_INDENT}${FG_DIM}${d.entryCount} entries${RST}${renderToolMetrics(result)}\n${rendered}`,
97
+ ),
98
+ );
99
+ return text;
100
+ }
101
+ const fc = result.content?.[0];
102
+ text.setText(
103
+ fillToolBody(
104
+ `${TOOL_RESULT_INDENT}${theme.fg("dim", fc && "text" in fc ? String(fc.text).slice(0, 120) : "done")}`,
105
+ ),
106
+ );
107
+ return text;
108
+ },
109
+ } as unknown as ToolDefinition<any, any, any>);
110
+ }
111
+
112
+ function getText(result: Result): string {
113
+ return (
114
+ ((result.content ?? []) as TextContent[])
115
+ .filter((c) => c.type === "text")
116
+ .map((c) => c.text)
117
+ .join("\n") ?? ""
118
+ );
119
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * pi-pretty: tool metrics wrapper — elapsed time + output size.
3
+ *
4
+ * Wraps execute functions to record performance metadata in result.details.
5
+ */
6
+
7
+ import type { AgentToolResult, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import { CHARS_KEY, ELAPSED_KEY } from "../helpers.js";
9
+
10
+ type ExecuteFn = (
11
+ tid: string,
12
+ params: any,
13
+ sig: AbortSignal | undefined,
14
+ _upd: unknown,
15
+ ctx: ExtensionContext,
16
+ ) => Promise<AgentToolResult<Record<string, unknown>>>;
17
+
18
+ export interface RejectedExecutionMetrics {
19
+ elapsedMs: number;
20
+ chars: number;
21
+ }
22
+
23
+ export type RejectedExecutionHandler = (toolCallId: string, metrics: RejectedExecutionMetrics) => void;
24
+
25
+ export function wrapExecuteWithMetrics(execute: ExecuteFn, onRejected?: RejectedExecutionHandler): ExecuteFn {
26
+ return async (tid, params, sig, upd, ctx) => {
27
+ const start = performance.now();
28
+ try {
29
+ const result = await execute(tid, params, sig, upd, ctx);
30
+ const elapsedMs = performance.now() - start;
31
+ const details = (result.details ?? {}) as Record<string, unknown>;
32
+ details[ELAPSED_KEY] = elapsedMs;
33
+ details[CHARS_KEY] = getOutputCharCount(result);
34
+ (result as { details: Record<string, unknown> }).details = details;
35
+ return result;
36
+ } catch (error) {
37
+ onRejected?.(tid, {
38
+ elapsedMs: performance.now() - start,
39
+ chars: getErrorCharCount(error),
40
+ });
41
+ throw error;
42
+ }
43
+ };
44
+ }
45
+
46
+ function getErrorCharCount(error: unknown): number {
47
+ const text = error instanceof Error ? error.message : String(error);
48
+ return text.replace(/\r/g, "").length;
49
+ }
50
+
51
+ function getOutputCharCount(result: AgentToolResult<unknown>): number {
52
+ const content = result.content;
53
+ if (!Array.isArray(content)) return 0;
54
+ let length = 0;
55
+ for (const block of content) {
56
+ if (block.type !== "text") continue;
57
+ length += String(block.text ?? "").replace(/\r/g, "").length;
58
+ }
59
+ return length;
60
+ }
@@ -0,0 +1,319 @@
1
+ /* pi-pretty: read tool -- file reading with syntax highlighting and inline image support. */
2
+
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import type { AgentToolResult, ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import { getReadmePath } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ BG_BASE,
8
+ BG_ERROR,
9
+ FG_DIM,
10
+ FG_LNUM,
11
+ FG_RULE,
12
+ RST,
13
+ resolveBaseBackground,
14
+ TOOL_RESULT_INDENT,
15
+ termWidth,
16
+ } from "../config.js";
17
+ import { normalizeLineEndings, shortPath } from "../helpers.js";
18
+ import { fillToolBackground, fillToolBody, renderFileContent, renderToolError } from "../render.js";
19
+ import { resolveTextCtor } from "../tui-text.js";
20
+ import type { ReadDetails, RenderCtxLike, SdkToolDef, TextContent, ThemeLike } from "../types.js";
21
+ import { wrapExecuteWithMetrics } from "./metrics.js";
22
+
23
+ type Result = AgentToolResult<Record<string, unknown>>;
24
+
25
+ function getPiDocsLabel(filePath: string, cwd: string): string | undefined {
26
+ const packageRoot = dirname(getReadmePath());
27
+ const relativePath = relative(resolve(packageRoot), resolve(cwd, filePath));
28
+ if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
29
+ return undefined;
30
+ }
31
+
32
+ const label = relativePath.split(sep).join("/");
33
+ return label === "README.md" || label.startsWith("docs/") || label.startsWith("examples/") ? label : undefined;
34
+ }
35
+
36
+ function getSkillName(filePath: string, content: string): string | undefined {
37
+ if (basename(filePath) !== "SKILL.md") return undefined;
38
+
39
+ const lines = content.split("\n");
40
+ if (lines[0]?.trim() === "---") {
41
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
42
+ for (const line of lines.slice(1, end < 0 ? 1 : end)) {
43
+ const match = /^name\s*:\s*(.+?)\s*$/.exec(line);
44
+ if (!match) continue;
45
+ const value = match[1].trim();
46
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
47
+ return value.slice(1, -1).trim() || basename(dirname(filePath));
48
+ }
49
+ return value || basename(dirname(filePath));
50
+ }
51
+ }
52
+
53
+ return basename(dirname(filePath));
54
+ }
55
+
56
+ function renderSkillHeader(skillName: string, expanded: boolean, theme: ThemeLike): string {
57
+ const label = theme.fg("accent", "[skill]");
58
+ const name = theme.fg("toolTitle", skillName);
59
+ const hint = theme.fg("dim", `ctrl+o to ${expanded ? "collapse" : "expand"}`);
60
+ return `${label} ${name} ${hint}`;
61
+ }
62
+
63
+ export function registerReadTool(
64
+ pi: ExtensionAPI,
65
+ cwd: string,
66
+ _fffService: unknown,
67
+ sdkTool: SdkToolDef,
68
+ TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
69
+ renderContent: typeof renderFileContent = renderFileContent,
70
+ ): void {
71
+ const TC = resolveTextCtor(TextComp);
72
+ const home = process.env.HOME ?? "";
73
+
74
+ // SAFETY: the object below matches the host ToolDefinition contract at runtime
75
+ // (name/parameters schema plus execute/renderCall/renderResult), but its loose
76
+ // internal shape cannot be named as the host's generic type here. pi validates
77
+ // the schema and invokes the callbacks with host types.
78
+ pi.registerTool({
79
+ name: "read",
80
+ label: "Read",
81
+ description: sdkTool.description ?? "Read file contents",
82
+ parameters: sdkTool.parameters,
83
+ promptSnippet: sdkTool.promptSnippet,
84
+ promptGuidelines: sdkTool.promptGuidelines,
85
+ constrainedSampling: sdkTool.constrainedSampling,
86
+ renderShell: "self",
87
+
88
+ execute: wrapExecuteWithMetrics(async (tid, params, sig, _upd, ctx: ExtensionContext) => {
89
+ const p = params as any;
90
+ const result = (await sdkTool.execute(tid, p, sig, undefined, ctx)) as Result;
91
+
92
+ const imageBlock = (result.content as any[])?.find((c: any) => c.type === "image");
93
+ if (imageBlock) {
94
+ result.details = {
95
+ _type: "readImage",
96
+ filePath: String(p.path ?? ""),
97
+ } as ReadDetails;
98
+ return result;
99
+ }
100
+
101
+ const tc = normalizeLineEndings(getText(result));
102
+ result.details = {
103
+ _type: "readFile",
104
+ filePath: String(p.path ?? ""),
105
+ content: tc,
106
+ offset: typeof p.offset === "number" ? p.offset : 0,
107
+ lineCount: tc ? tc.split("\n").length : 0,
108
+ } as ReadDetails;
109
+ return result;
110
+ }),
111
+
112
+ renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
113
+ resolveBaseBackground(theme);
114
+
115
+ const text = ctx.lastComponent ?? new TC("", 0, 0);
116
+ if (!ctx.isError) {
117
+ text.setText("");
118
+ return text;
119
+ }
120
+
121
+ const path = String(args.path ?? "");
122
+ const label = theme.fg("error", theme.bold("→ read"));
123
+ text.setText(fillToolBackground(`\n${TOOL_RESULT_INDENT}${label} ${theme.fg("toolTitle", path)}\n`, BG_ERROR));
124
+ return text;
125
+ },
126
+
127
+ renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
128
+ resolveBaseBackground(theme);
129
+
130
+ const renderToken = nextReadRenderToken(ctx);
131
+ const text = ctx.lastComponent ?? new TC("", 0, 0);
132
+
133
+ if (ctx.isError) {
134
+ text.setText(renderToolError(getText(result) || "Error", theme));
135
+ return text;
136
+ }
137
+
138
+ const d = result.details as ReadDetails | undefined;
139
+
140
+ // Image content is preserved for ToolExecution's host-generic image pass.
141
+ // Keep the SDK's text note visible as a fallback when host images are hidden
142
+ // or unsupported by the terminal.
143
+ if (d?._type === "readImage") {
144
+ const note = getText(result);
145
+ // Keep fallback text visually separated from the preceding tool row.
146
+ text.setText(note ? fillToolBody(`\n${note}`, BG_BASE) : "");
147
+ return text;
148
+ }
149
+
150
+ // File content — line-numbered display
151
+ if (d?._type === "readFile" && d.content) {
152
+ const tw = termWidth();
153
+ const lines = d.content.split("\n");
154
+ const total = lines.length;
155
+ const filePath = String(d.filePath ?? "");
156
+ const skillName = getSkillName(filePath, d.content);
157
+ const p2 = shortPath(cwd, home, filePath);
158
+ const off2 = typeof d.offset === "number" ? `:${d.offset}` : "";
159
+ if (!ctx.expanded) {
160
+ if (skillName) {
161
+ const header = renderSkillHeader(skillName, false, theme);
162
+ text.setText(fillToolBody(`\n${TOOL_RESULT_INDENT}${header}\n`, BG_BASE));
163
+ return text;
164
+ }
165
+ const docsLabel = getPiDocsLabel(filePath, cwd);
166
+ const title = docsLabel
167
+ ? `${theme.fg("toolTitle", theme.bold("→ read docs"))} ${theme.fg("toolTitle", docsLabel)}`
168
+ : `${theme.fg("toolTitle", theme.bold("→ read"))} ${theme.fg("toolTitle", p2)}`;
169
+ text.setText(
170
+ fillToolBody(
171
+ `\n${TOOL_RESULT_INDENT}${title}${theme.fg("dim", off2)} ${FG_DIM}${total} lines — ctrl+o to expand${RST}`,
172
+ BG_BASE,
173
+ ),
174
+ );
175
+ return text;
176
+ }
177
+ const maxShow = lines.length;
178
+ const show = lines.slice(0, maxShow);
179
+ const offset = d.offset || 0;
180
+ const nw = Math.max(3, String(offset + total).length);
181
+ const gw = nw + 3;
182
+ const cw = Math.max(1, tw - gw);
183
+
184
+ const header = skillName
185
+ ? renderSkillHeader(skillName, true, theme)
186
+ : `${theme.fg("toolTitle", theme.bold("→ read"))} ${theme.fg("toolTitle", p2)}${theme.fg("dim", off2)}`;
187
+ const highlightRequest: ReadHighlightRequest = {
188
+ content: d.content,
189
+ filePath: d.filePath,
190
+ offset,
191
+ maxLines: maxShow,
192
+ width: cw,
193
+ };
194
+ const cachedHighlight = getCachedReadHighlight(ctx, highlightRequest);
195
+ if (cachedHighlight !== undefined) {
196
+ const highlighted = buildHighlightedRead(cachedHighlight, header, skillName, offset, nw, tw);
197
+ text.setText(fillToolBody(highlighted, BG_BASE));
198
+ return text;
199
+ }
200
+
201
+ const out: string[] = ["", `${TOOL_RESULT_INDENT}${header}`, ""];
202
+ out.push(`${TOOL_RESULT_INDENT}${FG_RULE}${"─".repeat(tw - 1)}${RST}`);
203
+ for (let i = 0; i < show.length; i++) {
204
+ const ln = offset + i + 1;
205
+ const code = show[i] ?? "";
206
+ const display = code.length > cw ? `${code.slice(0, Math.max(0, cw - 1))}${FG_DIM}›${RST}` : code;
207
+ const lineNo = String(ln);
208
+ out.push(
209
+ `${TOOL_RESULT_INDENT}${FG_LNUM}${" ".repeat(Math.max(0, nw - lineNo.length))}${lineNo}${RST} ${FG_RULE}│${RST} ${display}${RST}`,
210
+ );
211
+ }
212
+ if (total > maxShow) {
213
+ out.push(`${TOOL_RESULT_INDENT}${FG_DIM}… ${total - maxShow} more lines (${total} total)${RST}`);
214
+ }
215
+ const rendered = out.join("\n");
216
+ text.setText(fillToolBody(rendered, BG_BASE));
217
+
218
+ // Async syntax highlighting via Shiki. The component is reused across
219
+ // expansion changes, so stale work must not restore an older view.
220
+ renderContent(d.content, d.filePath, offset, maxShow, cw)
221
+ .then((hl) => {
222
+ if (!isCurrentReadRender(ctx, renderToken)) return;
223
+ setCachedReadHighlight(ctx, highlightRequest, hl);
224
+ const highlighted = buildHighlightedRead(hl, header, skillName, offset, nw, tw);
225
+ text.setText(fillToolBody(highlighted, BG_BASE));
226
+ ctx.invalidate?.();
227
+ })
228
+ .catch(() => {});
229
+
230
+ return text;
231
+ }
232
+
233
+ const fc = result.content?.[0];
234
+ text.setText(
235
+ fillToolBody(
236
+ `${TOOL_RESULT_INDENT}${theme.fg("dim", fc && "text" in fc ? String(fc.text).slice(0, 120) : "done")}`,
237
+ BG_BASE,
238
+ ),
239
+ );
240
+ return text;
241
+ },
242
+ } as unknown as ToolDefinition<any, any, any>);
243
+ }
244
+
245
+ const READ_RENDER_TOKEN = "__piPrettyReadRenderToken";
246
+ const READ_HIGHLIGHT_CACHE = "__piPrettyReadHighlightCache";
247
+
248
+ type ReadHighlightRequest = {
249
+ content: string;
250
+ filePath: string;
251
+ offset: number;
252
+ maxLines: number;
253
+ width: number;
254
+ };
255
+
256
+ type ReadHighlightCache = ReadHighlightRequest & {
257
+ highlighted: string;
258
+ };
259
+
260
+ function nextReadRenderToken(ctx: RenderCtxLike): number {
261
+ const state = ctx.state;
262
+ const token = typeof state[READ_RENDER_TOKEN] === "number" ? state[READ_RENDER_TOKEN] + 1 : 1;
263
+ state[READ_RENDER_TOKEN] = token;
264
+ return token;
265
+ }
266
+
267
+ function isCurrentReadRender(ctx: RenderCtxLike, token: number): boolean {
268
+ return ctx.state[READ_RENDER_TOKEN] === token;
269
+ }
270
+
271
+ function getCachedReadHighlight(ctx: RenderCtxLike, request: ReadHighlightRequest): string | undefined {
272
+ const cache = ctx.state[READ_HIGHLIGHT_CACHE] as ReadHighlightCache | undefined;
273
+ if (!cache) return undefined;
274
+ if (
275
+ cache.content !== request.content ||
276
+ cache.filePath !== request.filePath ||
277
+ cache.offset !== request.offset ||
278
+ cache.maxLines !== request.maxLines ||
279
+ cache.width !== request.width
280
+ ) {
281
+ return undefined;
282
+ }
283
+ return cache.highlighted;
284
+ }
285
+
286
+ function setCachedReadHighlight(ctx: RenderCtxLike, request: ReadHighlightRequest, highlighted: string): void {
287
+ ctx.state[READ_HIGHLIGHT_CACHE] = {
288
+ ...request,
289
+ highlighted,
290
+ } satisfies ReadHighlightCache;
291
+ }
292
+
293
+ function buildHighlightedRead(
294
+ highlighted: string,
295
+ header: string,
296
+ skillName: string | undefined,
297
+ offset: number,
298
+ nw: number,
299
+ tw: number,
300
+ ): string {
301
+ const padded = highlighted
302
+ .split("\n")
303
+ .map((line, index) => {
304
+ const lineNo = String(offset + index + 1);
305
+ return `${TOOL_RESULT_INDENT}${FG_LNUM}${" ".repeat(Math.max(0, nw - lineNo.length))}${lineNo}${RST} ${FG_RULE}│${RST} ${line}${RST}`;
306
+ })
307
+ .join("\n");
308
+ const divider = skillName ? `${TOOL_RESULT_INDENT}${FG_RULE}${"─".repeat(Math.max(1, tw - 1))}${RST}\n` : "";
309
+ return `\n${TOOL_RESULT_INDENT}${header}\n\n${divider}${padded}`;
310
+ }
311
+
312
+ function getText(result: Result): string {
313
+ return (
314
+ ((result.content ?? []) as TextContent[])
315
+ .filter((c) => c.type === "text")
316
+ .map((c) => c.text)
317
+ .join("\n") ?? ""
318
+ );
319
+ }
@@ -0,0 +1,17 @@
1
+ import { Text } from "@earendil-works/pi-tui";
2
+
3
+ type TextCtor = new (
4
+ text?: string,
5
+ paddingX?: number,
6
+ paddingY?: number,
7
+ ) => {
8
+ setText(value: string): void;
9
+ };
10
+
11
+ export function getTextCtor(): TextCtor {
12
+ return Text;
13
+ }
14
+
15
+ export function resolveTextCtor(TextComp?: TextCtor): TextCtor {
16
+ return TextComp ?? Text;
17
+ }