@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.
- package/LICENSE +21 -0
- package/README.md +48 -0
- package/package.json +71 -0
- package/src/autocomplete.ts +91 -0
- package/src/config.ts +468 -0
- package/src/fff-helpers.ts +86 -0
- package/src/fff.ts +340 -0
- package/src/find-glob.ts +21 -0
- package/src/helpers.ts +75 -0
- package/src/index.ts +556 -0
- package/src/notices.ts +3 -0
- package/src/prompt-editor.ts +104 -0
- package/src/render.ts +488 -0
- package/src/session-color.ts +172 -0
- package/src/tools/bash.d.ts +21 -0
- package/src/tools/bash.ts +163 -0
- package/src/tools/find.ts +231 -0
- package/src/tools/grep.ts +187 -0
- package/src/tools/labels.ts +3 -0
- package/src/tools/ls.ts +119 -0
- package/src/tools/metrics.ts +60 -0
- package/src/tools/read.ts +319 -0
- package/src/tui-text.ts +17 -0
- package/src/types.ts +202 -0
- package/src/working-indicator.ts +912 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/* pi-pretty: bash renderers — display-only.
|
|
2
|
+
*
|
|
3
|
+
* pi-heimdall owns the `bash` tool (sandboxed execute) and attaches these
|
|
4
|
+
* renderers, so output keeps pi-pretty styling. pi-pretty itself never
|
|
5
|
+
* registers, substitutes, or executes the bash tool. */
|
|
6
|
+
|
|
7
|
+
import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { resolveBaseBackground, TOOL_RESULT_INDENT, termWidth } from "../config.js";
|
|
9
|
+
import { compactErrorLines, inferBashExitCode, stripBashExitStatusLine } from "../helpers.js";
|
|
10
|
+
import {
|
|
11
|
+
fillToolBackground,
|
|
12
|
+
fillToolBody,
|
|
13
|
+
rememberToolTitle,
|
|
14
|
+
renderToolDuration,
|
|
15
|
+
renderToolError,
|
|
16
|
+
setCollapsedToolTitle,
|
|
17
|
+
} from "../render.js";
|
|
18
|
+
import { resolveTextCtor } from "../tui-text.js";
|
|
19
|
+
import type { BashDetails, ComponentLike, RenderCtxLike, ThemeLike, TextContent } from "../types.js";
|
|
20
|
+
|
|
21
|
+
type Result = AgentToolResult<Record<string, unknown>>;
|
|
22
|
+
const BASH_RESULT_RENDER_KEY = "__piPrettyBashResultRender";
|
|
23
|
+
export interface BashRenderers {
|
|
24
|
+
renderShell: "self";
|
|
25
|
+
/** Returns the host Text component; loosely typed so the tool owner can attach it to its ToolDefinition. */
|
|
26
|
+
renderCall: (args: any, theme: ThemeLike, ctx: RenderCtxLike) => unknown;
|
|
27
|
+
renderResult: (result: Result, opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) => unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createBashRenderers(
|
|
31
|
+
TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
|
|
32
|
+
): BashRenderers {
|
|
33
|
+
const TC = resolveTextCtor(TextComp);
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
renderShell: "self",
|
|
37
|
+
|
|
38
|
+
renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
39
|
+
resolveBaseBackground(theme);
|
|
40
|
+
const text = (ctx.lastComponent ?? new TC("", 0, 0)) as ComponentLike;
|
|
41
|
+
const t = typeof args.timeout === "number" ? ` ${theme.fg("muted", `(timeout ${args.timeout}s)`)}` : "";
|
|
42
|
+
const tw = termWidth() || 80;
|
|
43
|
+
const rawCmd = String(args.command ?? "");
|
|
44
|
+
const headerBudget = ctx.expanded ? tw : Math.max(8, tw - 20);
|
|
45
|
+
const cmd =
|
|
46
|
+
rawCmd.length === 0
|
|
47
|
+
? theme.fg("toolOutput", "...")
|
|
48
|
+
: !ctx.expanded && rawCmd.length > headerBudget
|
|
49
|
+
? `${rawCmd.slice(0, Math.max(1, headerBudget))}…`
|
|
50
|
+
: rawCmd;
|
|
51
|
+
const commandLabel = theme.fg(ctx.isError ? "error" : "toolTitle", theme.bold(`$ ${cmd}`));
|
|
52
|
+
const renderTitle = (suffix = ""): string =>
|
|
53
|
+
fillToolBackground(
|
|
54
|
+
`\n${TOOL_RESULT_INDENT}${commandLabel}${t}${suffix}\n`,
|
|
55
|
+
undefined,
|
|
56
|
+
ctx.expanded ? undefined : tw,
|
|
57
|
+
);
|
|
58
|
+
rememberToolTitle(ctx, text, renderTitle);
|
|
59
|
+
text.setText(renderTitle());
|
|
60
|
+
return text;
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
64
|
+
resolveBaseBackground(theme);
|
|
65
|
+
|
|
66
|
+
const text = (ctx.lastComponent ?? new TC("", 0, 0)) as ComponentLike;
|
|
67
|
+
restoreBashResultRender(ctx, text);
|
|
68
|
+
const displayResult = result;
|
|
69
|
+
|
|
70
|
+
const details = displayResult.details;
|
|
71
|
+
const tc = getText(displayResult);
|
|
72
|
+
const d: BashDetails | undefined =
|
|
73
|
+
(details as BashDetails)?._type === "bashResult"
|
|
74
|
+
? (details as BashDetails)
|
|
75
|
+
: tc || ctx.isError
|
|
76
|
+
? {
|
|
77
|
+
_type: "bashResult",
|
|
78
|
+
text: tc || "Error",
|
|
79
|
+
exitCode: inferBashExitCode(tc, ctx.isError ? 1 : 0),
|
|
80
|
+
command: "",
|
|
81
|
+
}
|
|
82
|
+
: undefined;
|
|
83
|
+
|
|
84
|
+
if (d?._type === "bashResult") {
|
|
85
|
+
const isErr = ctx.isError || (d.exitCode !== null && d.exitCode !== 0);
|
|
86
|
+
const cleaned = stripBashExitStatusLine(d.text);
|
|
87
|
+
const output = isErr ? compactErrorLines(cleaned).join("\n") : cleaned;
|
|
88
|
+
const lineCount = output.split("\n").length;
|
|
89
|
+
const info = [
|
|
90
|
+
`${lineCount} lines`,
|
|
91
|
+
renderToolDuration(displayResult),
|
|
92
|
+
!ctx.expanded ? "ctrl+o to expand" : "",
|
|
93
|
+
]
|
|
94
|
+
.filter(Boolean)
|
|
95
|
+
.map((part) => theme.fg("dim", part))
|
|
96
|
+
.join(theme.fg("dim", " · "));
|
|
97
|
+
const header = `${TOOL_RESULT_INDENT}${info}`;
|
|
98
|
+
const rw = termWidth();
|
|
99
|
+
|
|
100
|
+
if (setCollapsedToolTitle(ctx, text, ` ${info}`)) return text;
|
|
101
|
+
|
|
102
|
+
const renderFn = (w: number) => {
|
|
103
|
+
if (!ctx.expanded) return fillToolBody(header, undefined, w);
|
|
104
|
+
if (!output.trim()) return fillToolBody(header, undefined, w);
|
|
105
|
+
const show = output.split("\n");
|
|
106
|
+
const out = [header, "", ...show.map((line: string) => `${TOOL_RESULT_INDENT}${line}`)];
|
|
107
|
+
return fillToolBody(out.join("\n"), undefined, w);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
text.setText(renderFn(rw));
|
|
111
|
+
const baseRender =
|
|
112
|
+
typeof (text as ComponentLike).render === "function" ? (text as ComponentLike).render.bind(text) : null;
|
|
113
|
+
if (baseRender) {
|
|
114
|
+
ctx.state[BASH_RESULT_RENDER_KEY] = baseRender;
|
|
115
|
+
let key: string | undefined;
|
|
116
|
+
// SAFETY: same host Text component contract as restoreBashResultRender;
|
|
117
|
+
// we memoize renders behind the component's own render(width) hook.
|
|
118
|
+
(text as unknown as Record<string, unknown>).render = (w: number) => {
|
|
119
|
+
const width = Math.max(1, Math.floor(w || termWidth()));
|
|
120
|
+
const k = `bash:${ctx.expanded ? "1" : "0"}:${width}:${d.exitCode ?? "killed"}:${output.length}:${renderToolDuration(displayResult)}`;
|
|
121
|
+
if (key !== k) {
|
|
122
|
+
text.setText(renderFn(width));
|
|
123
|
+
key = k;
|
|
124
|
+
}
|
|
125
|
+
return baseRender(width);
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return text;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (ctx.isError) {
|
|
132
|
+
text.setText(renderToolError(tc || "Error", theme));
|
|
133
|
+
return text;
|
|
134
|
+
}
|
|
135
|
+
const fc = displayResult.content?.[0];
|
|
136
|
+
text.setText(
|
|
137
|
+
fillToolBody(
|
|
138
|
+
`${TOOL_RESULT_INDENT}${theme.fg("dim", fc && "text" in fc ? String(fc.text).slice(0, 120) : "done")}`,
|
|
139
|
+
),
|
|
140
|
+
);
|
|
141
|
+
return text;
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function restoreBashResultRender(ctx: RenderCtxLike, text: ComponentLike): void {
|
|
147
|
+
const state = ctx.state;
|
|
148
|
+
const original = state[BASH_RESULT_RENDER_KEY] as ((width: number) => string[]) | undefined;
|
|
149
|
+
if (!original) return;
|
|
150
|
+
// SAFETY: text is the host Text component created in renderResult; the host TUI
|
|
151
|
+
// contract guarantees render(width): string[] even though ComponentLike omits it.
|
|
152
|
+
(text as unknown as { render: (width: number) => string[] }).render = original;
|
|
153
|
+
delete state[BASH_RESULT_RENDER_KEY];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function getText(result: Result): string {
|
|
157
|
+
return (
|
|
158
|
+
((result.content ?? []) as TextContent[])
|
|
159
|
+
.filter((c) => c.type === "text")
|
|
160
|
+
.map((c) => c.text)
|
|
161
|
+
.join("\n") ?? ""
|
|
162
|
+
);
|
|
163
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/* pi-pretty: find tool -- FFF-backed file search with SDK (fd) fallback. */
|
|
2
|
+
|
|
3
|
+
import { isAbsolute, relative } from "node:path";
|
|
4
|
+
import type { AgentToolResult, ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { BG_ERROR, FG_DIM, RST, resolveBaseBackground, TOOL_RESULT_INDENT } from "../config.js";
|
|
6
|
+
import { isLikelyGlobPattern, normalizeFindGlobPattern } from "../find-glob.js";
|
|
7
|
+
import { shortPath } from "../helpers.js";
|
|
8
|
+
import { NOTICE_PARTIAL_FILE_INDEX } from "../notices.js";
|
|
9
|
+
import {
|
|
10
|
+
fillToolBackground,
|
|
11
|
+
fillToolBody,
|
|
12
|
+
rememberToolTitle,
|
|
13
|
+
renderFindResults,
|
|
14
|
+
renderToolDuration,
|
|
15
|
+
renderToolError,
|
|
16
|
+
setCollapsedToolTitle,
|
|
17
|
+
} from "../render.js";
|
|
18
|
+
import { resolveTextCtor } from "../tui-text.js";
|
|
19
|
+
import type { FffServiceWithCursor, FindDetails, RenderCtxLike, SdkToolDef, TextContent, ThemeLike } from "../types.js";
|
|
20
|
+
import { wrapExecuteWithMetrics } from "./metrics.js";
|
|
21
|
+
|
|
22
|
+
type Result = AgentToolResult<Record<string, unknown>>;
|
|
23
|
+
|
|
24
|
+
function getText(result: Result): string {
|
|
25
|
+
return (result.content ?? [])
|
|
26
|
+
.filter((c) => c.type === "text")
|
|
27
|
+
.map((c) => (c as TextContent).text ?? "")
|
|
28
|
+
.join("\n");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function buildGlobPattern(pattern: string, path: string | undefined, basePath: string | null): string {
|
|
32
|
+
const raw = pattern.startsWith("/") ? pattern.slice(1) : pattern;
|
|
33
|
+
const normalized = normalizeFindGlobPattern(raw);
|
|
34
|
+
let cleanPath = path ?? "";
|
|
35
|
+
if (cleanPath && isAbsolute(cleanPath) && basePath) {
|
|
36
|
+
cleanPath = relative(basePath, cleanPath) || "";
|
|
37
|
+
}
|
|
38
|
+
cleanPath = cleanPath.replace(/\/$/, "");
|
|
39
|
+
if (cleanPath) {
|
|
40
|
+
if (normalized.startsWith("**/")) {
|
|
41
|
+
return `${cleanPath}/${normalized}`;
|
|
42
|
+
}
|
|
43
|
+
if (normalized.includes("/")) {
|
|
44
|
+
return `${cleanPath}/${normalized}`;
|
|
45
|
+
}
|
|
46
|
+
return `${cleanPath}/**/${normalized}`;
|
|
47
|
+
}
|
|
48
|
+
return normalized.startsWith("**/") || normalized.includes("/") ? normalized : `**/${normalized}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function normalizeSdkFindOutput(text: string): { text: string; matchCount: number; notices: string[] } {
|
|
52
|
+
const trimmed = text.trim();
|
|
53
|
+
if (!trimmed || trimmed === "No files found matching pattern") {
|
|
54
|
+
return { text: "", matchCount: 0, notices: [] };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const noticeMatch = /\n\n\[([^\r\n]*)\]\s*$/.exec(text);
|
|
58
|
+
const body = noticeMatch ? text.slice(0, noticeMatch.index) : text;
|
|
59
|
+
const notices = noticeMatch ? noticeMatch[1].split(". ").filter(Boolean) : [];
|
|
60
|
+
const matchCount = body.trim() ? body.trim().split("\n").filter(Boolean).length : 0;
|
|
61
|
+
return { text: body, matchCount, notices };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function sdkFindAsFindResult(
|
|
65
|
+
sdkTool: SdkToolDef,
|
|
66
|
+
tid: string,
|
|
67
|
+
params: Record<string, unknown>,
|
|
68
|
+
sig: AbortSignal | undefined,
|
|
69
|
+
ctx: ExtensionContext,
|
|
70
|
+
pattern: string,
|
|
71
|
+
extraNotices: string[],
|
|
72
|
+
): Promise<Result> {
|
|
73
|
+
const result = (await sdkTool.execute(tid, params, sig, undefined, ctx)) as Result;
|
|
74
|
+
const parsed = normalizeSdkFindOutput(getText(result));
|
|
75
|
+
const prev = (result.details as FindDetails | undefined)?.notices ?? [];
|
|
76
|
+
const notices = [...parsed.notices, ...(Array.isArray(prev) ? prev : []), ...extraNotices];
|
|
77
|
+
result.details = {
|
|
78
|
+
_type: "findResult",
|
|
79
|
+
text: parsed.text,
|
|
80
|
+
pattern,
|
|
81
|
+
matchCount: parsed.matchCount,
|
|
82
|
+
notices,
|
|
83
|
+
};
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function registerFindTool(
|
|
88
|
+
pi: ExtensionAPI,
|
|
89
|
+
cwd: string,
|
|
90
|
+
fffService: FffServiceWithCursor | null | undefined,
|
|
91
|
+
sdkTool: SdkToolDef,
|
|
92
|
+
TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
|
|
93
|
+
): void {
|
|
94
|
+
const TC = resolveTextCtor(TextComp);
|
|
95
|
+
const home = process.env.HOME ?? "";
|
|
96
|
+
|
|
97
|
+
// SAFETY: the object below matches the host ToolDefinition contract at runtime
|
|
98
|
+
// (name/parameters schema plus execute/renderCall/renderResult), but its loose
|
|
99
|
+
// internal shape cannot be named as the host's generic type here. pi validates
|
|
100
|
+
// the schema and invokes the callbacks with host types.
|
|
101
|
+
pi.registerTool({
|
|
102
|
+
name: "find",
|
|
103
|
+
label: "Find",
|
|
104
|
+
description: sdkTool.description ?? "Find files matching a glob pattern",
|
|
105
|
+
parameters: sdkTool.parameters,
|
|
106
|
+
renderShell: "self",
|
|
107
|
+
|
|
108
|
+
execute: wrapExecuteWithMetrics(async (tid, params, sig, _upd, ctx: ExtensionContext) => {
|
|
109
|
+
const pattern = String(params.pattern ?? "");
|
|
110
|
+
const path = params.path ? String(params.path) : undefined;
|
|
111
|
+
const limit = params.limit;
|
|
112
|
+
const fff = fffService?.isAvailable ? fffService.getFinder() : null;
|
|
113
|
+
|
|
114
|
+
if (fff) {
|
|
115
|
+
try {
|
|
116
|
+
const effectiveLimit = Math.max(1, typeof limit === "number" ? limit : 100);
|
|
117
|
+
const basePathResult = fff.getBasePath();
|
|
118
|
+
const basePath = basePathResult.ok ? basePathResult.value : null;
|
|
119
|
+
const globPattern = buildGlobPattern(pattern, path, basePath);
|
|
120
|
+
const searchResult = fff.glob(globPattern, {
|
|
121
|
+
pageSize: effectiveLimit,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
if (searchResult.ok) {
|
|
125
|
+
const items = searchResult.value.items.slice(0, effectiveLimit);
|
|
126
|
+
const notices: string[] = [];
|
|
127
|
+
if (fffService?.partialIndex) notices.push(NOTICE_PARTIAL_FILE_INDEX);
|
|
128
|
+
if (items.length >= effectiveLimit) notices.push(`${effectiveLimit} limit reached`);
|
|
129
|
+
if (searchResult.value.totalMatched > items.length) {
|
|
130
|
+
notices.push(`${searchResult.value.totalMatched} total matches`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (items.length === 0 && isLikelyGlobPattern(pattern)) {
|
|
134
|
+
return sdkFindAsFindResult(sdkTool, tid, params, sig, ctx, pattern, [
|
|
135
|
+
"FFF glob returned no matches; results from SDK find (fd).",
|
|
136
|
+
...notices,
|
|
137
|
+
]);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (items.length > 0) notices.push("Search engine: FFF glob.");
|
|
141
|
+
else if (notices.length === 0) notices.push("Search engine: FFF glob (no matches).");
|
|
142
|
+
|
|
143
|
+
const paths = items.map((i) => i.relativePath).join("\n");
|
|
144
|
+
return {
|
|
145
|
+
content: [{ type: "text" as const, text: paths }],
|
|
146
|
+
details: {
|
|
147
|
+
_type: "findResult",
|
|
148
|
+
text: paths,
|
|
149
|
+
pattern,
|
|
150
|
+
matchCount: items.length,
|
|
151
|
+
notices,
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
} catch {
|
|
156
|
+
/* fall through to SDK */
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return sdkFindAsFindResult(sdkTool, tid, params, sig, ctx, pattern, [
|
|
161
|
+
fff ? "FFF find unavailable; results from SDK find (fd)." : "Search engine: SDK find (fd).",
|
|
162
|
+
]);
|
|
163
|
+
}),
|
|
164
|
+
|
|
165
|
+
renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
166
|
+
resolveBaseBackground(theme);
|
|
167
|
+
const a = args as { pattern?: unknown; path?: unknown; limit?: unknown };
|
|
168
|
+
const text = (ctx as RenderCtxLike).lastComponent ?? new TC("", 0, 0);
|
|
169
|
+
const pattern = a.pattern == null ? "" : String(a.pattern);
|
|
170
|
+
const pathArg = a.path == null ? "<missing>" : shortPath(cwd, home, String(a.path));
|
|
171
|
+
const limit = a.limit;
|
|
172
|
+
const findLabel = theme.fg(ctx.isError ? "error" : "toolTitle", theme.bold("✱ find"));
|
|
173
|
+
const patternPart = pattern ? theme.fg("toolTitle", pattern) : "";
|
|
174
|
+
const inPart = theme.fg("dim", " in ");
|
|
175
|
+
const pathPart = theme.fg("toolOutput", pathArg);
|
|
176
|
+
const limitPart = limit !== undefined && limit !== null ? theme.fg("dim", ` limit ${limit}`) : "";
|
|
177
|
+
const out = `${findLabel} ${patternPart}${inPart}${pathPart}${limitPart}`;
|
|
178
|
+
const renderTitle = (suffix = ""): string =>
|
|
179
|
+
fillToolBackground(`\n${TOOL_RESULT_INDENT}${out}${suffix}\n`, ctx.isError ? BG_ERROR : undefined);
|
|
180
|
+
rememberToolTitle(ctx, text, renderTitle);
|
|
181
|
+
text.setText(renderTitle());
|
|
182
|
+
return text;
|
|
183
|
+
},
|
|
184
|
+
|
|
185
|
+
renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
186
|
+
resolveBaseBackground(theme);
|
|
187
|
+
const r = result;
|
|
188
|
+
const text = (ctx as RenderCtxLike).lastComponent ?? new TC("", 0, 0);
|
|
189
|
+
if (ctx.isError) {
|
|
190
|
+
text.setText(renderToolError(getText(r) || "Error", theme));
|
|
191
|
+
return text;
|
|
192
|
+
}
|
|
193
|
+
const d = r.details as FindDetails | undefined;
|
|
194
|
+
if (d?._type === "findResult") {
|
|
195
|
+
if (!d.text.trim()) {
|
|
196
|
+
const notice = d.notices?.length ? ` ${theme.fg("warning", `[${d.notices.join(". ")}]`)}` : "";
|
|
197
|
+
if (setCollapsedToolTitle(ctx, text, ` ${FG_DIM}0 files${RST}${notice}`)) return text;
|
|
198
|
+
const noticeStr = d.notices?.length
|
|
199
|
+
? `\n${TOOL_RESULT_INDENT}${theme.fg("warning", `[${d.notices.join(". ")}]`)}`
|
|
200
|
+
: "";
|
|
201
|
+
text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${theme.fg("dim", "0 files")}${noticeStr}`));
|
|
202
|
+
return text;
|
|
203
|
+
}
|
|
204
|
+
if (!ctx.expanded) {
|
|
205
|
+
const duration = renderToolDuration(r);
|
|
206
|
+
const summary = `${FG_DIM}${d.matchCount} files — ctrl+o to expand${RST}${duration ? `${FG_DIM}· ${duration}${RST}` : ""}`;
|
|
207
|
+
if (setCollapsedToolTitle(ctx, text, ` ${summary}`)) return text;
|
|
208
|
+
text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${summary}`));
|
|
209
|
+
return text;
|
|
210
|
+
}
|
|
211
|
+
const rendered = renderFindResults(d.text, theme)
|
|
212
|
+
.split("\n")
|
|
213
|
+
.map((l) => `${TOOL_RESULT_INDENT}${l}`)
|
|
214
|
+
.join("\n");
|
|
215
|
+
const noticeStr = d.notices?.length
|
|
216
|
+
? `\n${TOOL_RESULT_INDENT}${theme.fg("warning", `[${d.notices.join(". ")}]`)}`
|
|
217
|
+
: "";
|
|
218
|
+
const duration = renderToolDuration(r);
|
|
219
|
+
text.setText(
|
|
220
|
+
fillToolBody(
|
|
221
|
+
`${TOOL_RESULT_INDENT}${theme.fg("dim", `${d.matchCount} files`)}${duration ? `${FG_DIM}· ${duration}${RST}` : ""}\n${rendered}${noticeStr}`,
|
|
222
|
+
),
|
|
223
|
+
);
|
|
224
|
+
return text;
|
|
225
|
+
}
|
|
226
|
+
const fc = r.content?.[0] as TextContent | undefined;
|
|
227
|
+
text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${theme.fg("dim", fc?.text?.slice(0, 120) ?? "0 files")}`));
|
|
228
|
+
return text;
|
|
229
|
+
},
|
|
230
|
+
} as unknown as ToolDefinition);
|
|
231
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/* pi-pretty: grep tool -- FFF-backed text search with SDK fallback. */
|
|
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 { fffFormatGrepText } from "../fff-helpers.js";
|
|
6
|
+
import { normalizeLineEndings, shortPath } from "../helpers.js";
|
|
7
|
+
import { NOTICE_PARTIAL_FILE_INDEX } from "../notices.js";
|
|
8
|
+
import {
|
|
9
|
+
fillToolBackground,
|
|
10
|
+
fillToolBody,
|
|
11
|
+
rememberToolTitle,
|
|
12
|
+
renderToolError,
|
|
13
|
+
setCollapsedToolTitle,
|
|
14
|
+
} from "../render.js";
|
|
15
|
+
import { resolveTextCtor } from "../tui-text.js";
|
|
16
|
+
import type { FffServiceWithCursor, GrepDetails, RenderCtxLike, SdkToolDef, TextContent, ThemeLike } from "../types.js";
|
|
17
|
+
import { wrapExecuteWithMetrics } from "./metrics.js";
|
|
18
|
+
|
|
19
|
+
const invalidArg = "<missing>";
|
|
20
|
+
|
|
21
|
+
type Result = AgentToolResult<Record<string, unknown>>;
|
|
22
|
+
|
|
23
|
+
export function registerGrepTool(
|
|
24
|
+
pi: ExtensionAPI,
|
|
25
|
+
cwd: string,
|
|
26
|
+
fffService: FffServiceWithCursor | null | undefined,
|
|
27
|
+
sdkTool: SdkToolDef,
|
|
28
|
+
TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
|
|
29
|
+
): void {
|
|
30
|
+
const T = resolveTextCtor(TextComp);
|
|
31
|
+
const home = process.env.HOME ?? "";
|
|
32
|
+
|
|
33
|
+
// SAFETY: the object below matches the host ToolDefinition contract at runtime
|
|
34
|
+
// (name/parameters schema plus execute/renderCall/renderResult), but its loose
|
|
35
|
+
// internal shape cannot be named as the host's generic type here. pi validates
|
|
36
|
+
// the schema and invokes the callbacks with host types.
|
|
37
|
+
pi.registerTool({
|
|
38
|
+
name: "grep",
|
|
39
|
+
label: "Grep",
|
|
40
|
+
description: sdkTool.description ?? "Search file contents by pattern",
|
|
41
|
+
parameters: sdkTool.parameters,
|
|
42
|
+
renderShell: "self",
|
|
43
|
+
|
|
44
|
+
execute: wrapExecuteWithMetrics(async (tid, params, sig, _upd, ctx: ExtensionContext) => {
|
|
45
|
+
const p = params as any;
|
|
46
|
+
const pattern = String(p.pattern ?? "");
|
|
47
|
+
const path = p.path ? String(p.path) : undefined;
|
|
48
|
+
const glob = p.glob ? String(p.glob) : undefined;
|
|
49
|
+
const context = typeof p.context === "number" ? p.context : 0;
|
|
50
|
+
const limit = typeof p.limit === "number" ? p.limit : 200;
|
|
51
|
+
const literal = p.literal === true;
|
|
52
|
+
|
|
53
|
+
// FFF exposes smart-case, not the SDK's explicit ignoreCase mode.
|
|
54
|
+
// Fall back when callers request case-insensitive matching so the SDK
|
|
55
|
+
// remains the semantic source of truth for that option.
|
|
56
|
+
if (fffService?.isAvailable && !path && !glob && p.ignoreCase !== true) {
|
|
57
|
+
try {
|
|
58
|
+
const fff = fffService.getFinder();
|
|
59
|
+
if (!fff) throw new Error("FFF finder not available");
|
|
60
|
+
const effectiveLimit = Math.max(1, limit);
|
|
61
|
+
const grepResult = fff.grep(pattern, {
|
|
62
|
+
pageSize: effectiveLimit,
|
|
63
|
+
mode: literal ? "plain" : "regex",
|
|
64
|
+
smartCase: false,
|
|
65
|
+
beforeContext: context,
|
|
66
|
+
afterContext: context,
|
|
67
|
+
});
|
|
68
|
+
if (grepResult.ok) {
|
|
69
|
+
const grep = grepResult.value;
|
|
70
|
+
const items = grep.items.slice(0, effectiveLimit);
|
|
71
|
+
const cursorStore = fffService.getCursorStore();
|
|
72
|
+
const notices: string[] = [];
|
|
73
|
+
if (fffService.partialIndex) notices.push(NOTICE_PARTIAL_FILE_INDEX);
|
|
74
|
+
if (items.length >= effectiveLimit) notices.push(`${effectiveLimit} limit reached`);
|
|
75
|
+
if (grep.regexFallbackError) notices.push(`Regex failed: ${grep.regexFallbackError}, used literal match`);
|
|
76
|
+
if (grep.nextCursor) {
|
|
77
|
+
const cursorId = cursorStore.store(grep.nextCursor);
|
|
78
|
+
notices.push(`More results available: cursor="${cursorId}"`);
|
|
79
|
+
}
|
|
80
|
+
const text = appendNotices(fffFormatGrepText(items, effectiveLimit), notices);
|
|
81
|
+
return {
|
|
82
|
+
content: [{ type: "text" as const, text }],
|
|
83
|
+
details: {
|
|
84
|
+
_type: "grepResult",
|
|
85
|
+
text: items.length > 0 ? text : "",
|
|
86
|
+
pattern,
|
|
87
|
+
matchCount: items.length,
|
|
88
|
+
} as GrepDetails,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
/* fall through */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const result = (await sdkTool.execute(tid, p, sig, undefined, ctx)) as Result;
|
|
97
|
+
for (const c of (result.content ?? []) as any[]) {
|
|
98
|
+
if (c.type === "text") c.text = normalizeLineEndings(c.text);
|
|
99
|
+
}
|
|
100
|
+
const tc =
|
|
101
|
+
((result.content ?? []) as TextContent[])
|
|
102
|
+
.filter((c) => c.type === "text")
|
|
103
|
+
.map((c) => c.text)
|
|
104
|
+
.join("\n") ?? "";
|
|
105
|
+
const normalizedText = tc.trim() === "No matches found" ? "" : tc;
|
|
106
|
+
result.details = {
|
|
107
|
+
_type: "grepResult",
|
|
108
|
+
text: normalizedText,
|
|
109
|
+
pattern,
|
|
110
|
+
matchCount: normalizedText ? normalizedText.trim().split("\n").filter(Boolean).length : 0,
|
|
111
|
+
} as GrepDetails;
|
|
112
|
+
return result;
|
|
113
|
+
}),
|
|
114
|
+
|
|
115
|
+
renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
116
|
+
resolveBaseBackground(theme);
|
|
117
|
+
const text = ctx.lastComponent ?? new T("", 0, 0);
|
|
118
|
+
const pattern = args.pattern === null || args.pattern === undefined ? invalidArg : String(args.pattern);
|
|
119
|
+
const path = args.path === null || args.path === undefined ? invalidArg : shortPath(cwd, home, String(args.path));
|
|
120
|
+
const glob = args.glob;
|
|
121
|
+
const limit = args.limit;
|
|
122
|
+
const literal = args.literal === true;
|
|
123
|
+
const caseInsensitive = args.caseInsensitive === true || args.ignoreCase === true;
|
|
124
|
+
let out = `${theme.fg(ctx.isError ? "error" : "toolTitle", theme.bold("✱ grep"))} ${theme.fg("toolTitle", `/${pattern || ""}/`)}${theme.fg("toolOutput", ` in ${path}`)}`;
|
|
125
|
+
if (glob) out += theme.fg("dim", ` (${String(glob)})`);
|
|
126
|
+
if (limit !== undefined && limit !== null) out += theme.fg("dim", ` limit ${limit}`);
|
|
127
|
+
if (literal) out += theme.fg("dim", ` (literal)`);
|
|
128
|
+
if (caseInsensitive) out += theme.fg("dim", ` (case-insensitive)`);
|
|
129
|
+
const renderTitle = (suffix = ""): string =>
|
|
130
|
+
fillToolBackground(`\n${TOOL_RESULT_INDENT}${out}${suffix}\n`, ctx.isError ? BG_ERROR : undefined);
|
|
131
|
+
rememberToolTitle(ctx, text, renderTitle);
|
|
132
|
+
text.setText(renderTitle());
|
|
133
|
+
return text;
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
|
|
137
|
+
resolveBaseBackground(theme);
|
|
138
|
+
const text = ctx.lastComponent ?? new T("", 0, 0);
|
|
139
|
+
if (ctx.isError) {
|
|
140
|
+
text.setText(
|
|
141
|
+
renderToolError(
|
|
142
|
+
((result.content ?? []) as TextContent[])
|
|
143
|
+
.filter((c) => c.type === "text")
|
|
144
|
+
.map((c) => c.text)
|
|
145
|
+
.join("\n") || "Error",
|
|
146
|
+
theme,
|
|
147
|
+
),
|
|
148
|
+
);
|
|
149
|
+
return text;
|
|
150
|
+
}
|
|
151
|
+
const d = result.details as GrepDetails | undefined;
|
|
152
|
+
if (d?._type === "grepResult" && d.text) {
|
|
153
|
+
const lines = d.text.split("\n");
|
|
154
|
+
if (!ctx.expanded) {
|
|
155
|
+
const summary = `${FG_DIM}${lines.length} lines — ctrl+o to expand${RST}`;
|
|
156
|
+
if (setCollapsedToolTitle(ctx, text, ` ${summary}`)) return text;
|
|
157
|
+
text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${summary}`, ctx.isError ? BG_ERROR : undefined));
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
const maxShow = lines.length;
|
|
161
|
+
const show = lines.slice(0, maxShow);
|
|
162
|
+
const remaining = lines.length - maxShow;
|
|
163
|
+
const out: string[] = [];
|
|
164
|
+
for (const line of show) {
|
|
165
|
+
if (!line) continue;
|
|
166
|
+
out.push(theme.fg("toolOutput", line));
|
|
167
|
+
}
|
|
168
|
+
if (remaining > 0) {
|
|
169
|
+
out.push(theme.fg("muted", `… (${remaining} more ${remaining === 1 ? "line" : "lines"}, to expand)`));
|
|
170
|
+
}
|
|
171
|
+
const body = out.map((l) => `${TOOL_RESULT_INDENT}${l}`).join("\n");
|
|
172
|
+
text.setText(fillToolBody(body, ctx.isError ? BG_ERROR : undefined));
|
|
173
|
+
return text;
|
|
174
|
+
}
|
|
175
|
+
const fc = result.content?.[0];
|
|
176
|
+
const fallback = fc && "text" in fc ? String(fc.text).slice(0, 120) : "no matches";
|
|
177
|
+
text.setText(
|
|
178
|
+
fillToolBody(`${TOOL_RESULT_INDENT}${theme.fg("dim", fallback)}`, ctx.isError ? BG_ERROR : undefined),
|
|
179
|
+
);
|
|
180
|
+
return text;
|
|
181
|
+
},
|
|
182
|
+
} as unknown as ToolDefinition<any, any, any>);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function appendNotices(text: string, notices: string[]): string {
|
|
186
|
+
return notices.length ? `${text}\n\n[${notices.join(". ")}]` : text;
|
|
187
|
+
}
|