@oh-my-pi/pi-coding-agent 13.11.0 → 13.11.1

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,385 @@
1
+ import type { Component } from "@oh-my-pi/pi-tui";
2
+ import { Text } from "@oh-my-pi/pi-tui";
3
+ import { callExaTool, findApiKey as findExaKey, formatSearchResults, isSearchResponse } from "../../exa/mcp-client";
4
+ import type { CustomToolResult, RenderResultOptions } from "../../extensibility/custom-tools/types";
5
+ import type { Theme } from "../../modes/theme/theme";
6
+ import {
7
+ formatCount,
8
+ formatExpandHint,
9
+ formatMoreItems,
10
+ formatStatusIcon,
11
+ replaceTabs,
12
+ truncateToWidth,
13
+ } from "../../tools/render-utils";
14
+ import { decodeHtmlEntities } from "../scrapers/types";
15
+ import type { CodeSearchProviderId } from "./types";
16
+
17
+ export interface CodeSearchToolParams {
18
+ query: string;
19
+ code_context?: string;
20
+ }
21
+
22
+ export interface CodeSearchSource {
23
+ title: string;
24
+ url: string;
25
+ repository: string;
26
+ path: string;
27
+ branch: string;
28
+ snippet?: string;
29
+ totalMatches?: string;
30
+ }
31
+
32
+ export interface CodeSearchResponse {
33
+ provider: CodeSearchProviderId;
34
+ query: string;
35
+ totalResults?: number;
36
+ sources: CodeSearchSource[];
37
+ }
38
+
39
+ export interface CodeSearchRenderDetails {
40
+ response?: CodeSearchResponse;
41
+ error?: string;
42
+ provider: CodeSearchProviderId;
43
+ }
44
+
45
+ interface GrepApiHit {
46
+ repo: string;
47
+ branch: string;
48
+ path: string;
49
+ contentSnippet?: string;
50
+ totalMatches?: string;
51
+ }
52
+
53
+ interface GrepApiResponse {
54
+ totalResults?: number;
55
+ hits: GrepApiHit[];
56
+ }
57
+
58
+ let preferredCodeSearchProvider: CodeSearchProviderId = "grep";
59
+
60
+ export function setPreferredCodeSearchProvider(provider: CodeSearchProviderId): void {
61
+ preferredCodeSearchProvider = provider;
62
+ }
63
+
64
+ function stringifyExaCodeResponse(payload: unknown): string {
65
+ if (typeof payload === "string") return payload;
66
+ if (typeof payload === "number" || typeof payload === "boolean") return String(payload);
67
+ if (payload === null || payload === undefined) return "";
68
+ const serialized = JSON.stringify(payload, null, 2);
69
+ return typeof serialized === "string" ? serialized : "";
70
+ }
71
+
72
+ function normalizeExaCodeSearchResponse(
73
+ params: CodeSearchToolParams,
74
+ payload: unknown,
75
+ formattedSearchResponse?: string,
76
+ ): CodeSearchResponse {
77
+ const snippet = formattedSearchResponse ?? stringifyExaCodeResponse(payload);
78
+ return {
79
+ provider: "exa",
80
+ query: params.query,
81
+ sources: [
82
+ {
83
+ title: params.query,
84
+ url: "https://exa.ai/",
85
+ repository: "exa",
86
+ path: "code-search",
87
+ branch: "public-mcp",
88
+ snippet: snippet.length > 0 ? snippet : undefined,
89
+ },
90
+ ],
91
+ };
92
+ }
93
+
94
+ function getStringProperty(value: object, key: string): string | undefined {
95
+ const candidate = Reflect.get(value, key);
96
+ return typeof candidate === "string" ? candidate : undefined;
97
+ }
98
+
99
+ function getNumberProperty(value: object, key: string): number | undefined {
100
+ const candidate = Reflect.get(value, key);
101
+ return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined;
102
+ }
103
+
104
+ function getObjectProperty(value: object, key: string): object | undefined {
105
+ const candidate = Reflect.get(value, key);
106
+ return typeof candidate === "object" && candidate !== null ? candidate : undefined;
107
+ }
108
+
109
+ function getArrayProperty(value: object, key: string): unknown[] | undefined {
110
+ const candidate = Reflect.get(value, key);
111
+ return Array.isArray(candidate) ? candidate : undefined;
112
+ }
113
+
114
+ function stripHtmlTags(value: string): string {
115
+ return value
116
+ .replace(/<br\s*\/?>/gi, "")
117
+ .replace(/<\/?mark>/gi, "")
118
+ .replace(/<span[^>]*>/gi, "")
119
+ .replace(/<\/span>/gi, "")
120
+ .replace(/<[^>]+>/g, "");
121
+ }
122
+
123
+ function formatGrepSnippet(snippetHtml: string | undefined): string | undefined {
124
+ if (!snippetHtml) return undefined;
125
+
126
+ const rowPattern = /<tr[^>]*data-line="(\d+)"[^>]*>[\s\S]*?<pre>([\s\S]*?)<\/pre>[\s\S]*?<\/tr>/gi;
127
+ const lines: string[] = [];
128
+
129
+ for (const match of snippetHtml.matchAll(rowPattern)) {
130
+ const lineNumber = match[1];
131
+ const rawCode = match[2] ?? "";
132
+ const text = decodeHtmlEntities(stripHtmlTags(rawCode)).trimEnd();
133
+ if (text.length === 0) continue;
134
+ lines.push(`${lineNumber}: ${text}`);
135
+ }
136
+
137
+ if (lines.length > 0) {
138
+ return lines.join("\n");
139
+ }
140
+
141
+ const plainText = decodeHtmlEntities(stripHtmlTags(snippetHtml)).replace(/\s+\n/g, "\n").trim();
142
+ return plainText.length > 0 ? plainText : undefined;
143
+ }
144
+
145
+ function parseGrepApiResponse(payload: unknown): GrepApiResponse | null {
146
+ if (typeof payload !== "object" || payload === null) return null;
147
+
148
+ const hitsObject = getObjectProperty(payload, "hits");
149
+ if (!hitsObject) return null;
150
+
151
+ const hitValues = getArrayProperty(hitsObject, "hits") ?? [];
152
+ const hits: GrepApiHit[] = [];
153
+ for (const item of hitValues) {
154
+ if (typeof item !== "object" || item === null) continue;
155
+ const repo = getStringProperty(item, "repo");
156
+ const branch = getStringProperty(item, "branch");
157
+ const path = getStringProperty(item, "path");
158
+ if (!repo || !branch || !path) continue;
159
+
160
+ const content = getObjectProperty(item, "content");
161
+ hits.push({
162
+ repo,
163
+ branch,
164
+ path,
165
+ contentSnippet: content ? getStringProperty(content, "snippet") : undefined,
166
+ totalMatches: getStringProperty(item, "total_matches"),
167
+ });
168
+ }
169
+ if (hitValues.length > 0 && hits.length === 0) return null;
170
+
171
+ return {
172
+ totalResults: getNumberProperty(hitsObject, "total"),
173
+ hits,
174
+ };
175
+ }
176
+
177
+ function buildGrepQuery(params: CodeSearchToolParams): string {
178
+ return params.query.trim();
179
+ }
180
+
181
+ function tokenizeCodeContext(codeContext: string | undefined): string[] {
182
+ if (!codeContext) return [];
183
+ return codeContext
184
+ .toLowerCase()
185
+ .split(/[^a-z0-9_./:-]+/i)
186
+ .filter(token => token.length >= 2);
187
+ }
188
+
189
+ function scoreGrepHit(hit: GrepApiHit, contextTokens: string[]): number {
190
+ if (contextTokens.length === 0) return 0;
191
+ const snippet = formatGrepSnippet(hit.contentSnippet)?.toLowerCase() ?? "";
192
+ const repo = hit.repo.toLowerCase();
193
+ const path = hit.path.toLowerCase();
194
+
195
+ let score = 0;
196
+ for (const token of contextTokens) {
197
+ if (repo.includes(token)) score += 4;
198
+ if (path.includes(token)) score += 3;
199
+ if (snippet.includes(token)) score += 2;
200
+ }
201
+
202
+ return score;
203
+ }
204
+
205
+ export async function searchCodeWithGrep(params: CodeSearchToolParams): Promise<CodeSearchResponse> {
206
+ const query = buildGrepQuery(params);
207
+ const url = new URL("https://grep.app/api/search");
208
+ url.searchParams.set("q", query);
209
+
210
+ const response = await fetch(url, {
211
+ headers: {
212
+ Accept: "application/json",
213
+ Referer: `https://grep.app/search?q=${encodeURIComponent(query)}`,
214
+ },
215
+ });
216
+
217
+ if (!response.ok) {
218
+ const message = await response.text();
219
+ throw new Error(`grep.app API error (${response.status}): ${message}`);
220
+ }
221
+
222
+ const payload: unknown = await response.json();
223
+ const parsed = parseGrepApiResponse(payload);
224
+ if (!parsed) {
225
+ throw new Error("grep.app returned an unexpected response shape.");
226
+ }
227
+
228
+ const contextTokens = tokenizeCodeContext(params.code_context);
229
+ const rankedHits = [...parsed.hits].sort(
230
+ (left, right) => scoreGrepHit(right, contextTokens) - scoreGrepHit(left, contextTokens),
231
+ );
232
+
233
+ return {
234
+ provider: "grep",
235
+ query,
236
+ totalResults: parsed.totalResults,
237
+ sources: rankedHits.map(hit => ({
238
+ title: `${hit.repo}/${hit.path}`,
239
+ url: `https://github.com/${hit.repo}/blob/${hit.branch}/${hit.path}`,
240
+ repository: hit.repo,
241
+ path: hit.path,
242
+ branch: hit.branch,
243
+ snippet: formatGrepSnippet(hit.contentSnippet),
244
+ totalMatches: hit.totalMatches,
245
+ })),
246
+ };
247
+ }
248
+
249
+ async function searchCodeWithExa(params: CodeSearchToolParams): Promise<CodeSearchResponse> {
250
+ const exaParams = params.code_context
251
+ ? { query: params.query, code_context: params.code_context }
252
+ : { query: params.query };
253
+ const response = await callExaTool("get_code_context_exa", exaParams, findExaKey());
254
+ if (isSearchResponse(response)) {
255
+ return normalizeExaCodeSearchResponse(params, response, formatSearchResults(response));
256
+ }
257
+
258
+ return normalizeExaCodeSearchResponse(params, response);
259
+ }
260
+
261
+ export function formatCodeSearchForLlm(response: CodeSearchResponse): string {
262
+ const parts: string[] = [];
263
+ const summaryParts: string[] = [response.provider];
264
+ if (response.totalResults !== undefined) {
265
+ summaryParts.push(`${response.totalResults.toLocaleString()} total matches`);
266
+ }
267
+ parts.push(`Code search via ${summaryParts.join(" · ")}`);
268
+
269
+ if (response.sources.length === 0) {
270
+ parts.push("No results found.");
271
+ return parts.join("\n");
272
+ }
273
+
274
+ for (const [index, source] of response.sources.entries()) {
275
+ const metadata: string[] = [source.repository, source.path];
276
+ if (source.totalMatches) metadata.push(`${source.totalMatches} matches`);
277
+ parts.push(`[${index + 1}] ${metadata.join(" · ")}`);
278
+ parts.push(` ${source.url}`);
279
+ if (source.snippet) {
280
+ for (const line of source.snippet.split("\n").slice(0, 8)) {
281
+ parts.push(` ${line}`);
282
+ }
283
+ }
284
+ }
285
+
286
+ return parts.join("\n");
287
+ }
288
+
289
+ export async function executeCodeSearch(
290
+ params: CodeSearchToolParams,
291
+ ): Promise<CustomToolResult<CodeSearchRenderDetails>> {
292
+ try {
293
+ const response =
294
+ preferredCodeSearchProvider === "grep" ? await searchCodeWithGrep(params) : await searchCodeWithExa(params);
295
+
296
+ return {
297
+ content: [{ type: "text", text: formatCodeSearchForLlm(response) }],
298
+ details: { provider: response.provider, response },
299
+ };
300
+ } catch (error) {
301
+ const message = error instanceof Error ? error.message : String(error);
302
+ return {
303
+ content: [{ type: "text", text: `Error: ${message}` }],
304
+ details: { provider: preferredCodeSearchProvider, error: message },
305
+ };
306
+ }
307
+ }
308
+
309
+ export function renderCodeSearchCall(
310
+ args: CodeSearchToolParams,
311
+ _options: RenderResultOptions,
312
+ theme: Theme,
313
+ ): Component {
314
+ let text = `${theme.fg("toolTitle", "Code Search")} ${theme.fg("accent", truncateToWidth(args.query, 80))}`;
315
+ text += ` ${theme.fg("muted", `provider:${preferredCodeSearchProvider}`)}`;
316
+ if (args.code_context) {
317
+ text += ` ${theme.fg("dim", truncateToWidth(args.code_context, 40))}`;
318
+ }
319
+ return new Text(text, 0, 0);
320
+ }
321
+
322
+ export function renderCodeSearchResult(
323
+ result: { content: Array<{ type: string; text?: string }>; details?: CodeSearchRenderDetails },
324
+ options: RenderResultOptions,
325
+ uiTheme: Theme,
326
+ ): Component {
327
+ const details = result.details;
328
+ if (details?.error) {
329
+ return new Text(
330
+ `${formatStatusIcon("error", uiTheme)} ${uiTheme.fg("error", `Error: ${replaceTabs(details.error)}`)}`,
331
+ 0,
332
+ 0,
333
+ );
334
+ }
335
+
336
+ const response = details?.response;
337
+ if (!response) {
338
+ return new Text(`${formatStatusIcon("warning", uiTheme)} ${uiTheme.fg("muted", "No code search results")}`, 0, 0);
339
+ }
340
+
341
+ const resultCount = response.sources.length;
342
+ const meta: string[] = [formatCount("result", resultCount), `provider:${response.provider}`];
343
+ if (response.totalResults !== undefined) {
344
+ meta.push(`${response.totalResults.toLocaleString()} total`);
345
+ }
346
+ const expandHint = formatExpandHint(uiTheme, options.expanded, resultCount > 1);
347
+ let text = `${formatStatusIcon(resultCount > 0 ? "success" : "warning", uiTheme)} ${uiTheme.fg("dim", meta.join(uiTheme.sep.dot))}${expandHint}`;
348
+
349
+ if (resultCount === 0) {
350
+ text += `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg("muted", "No results")}`;
351
+ return new Text(text, 0, 0);
352
+ }
353
+
354
+ const visibleSources = options.expanded ? response.sources : response.sources.slice(0, 1);
355
+ for (const [index, source] of visibleSources.entries()) {
356
+ const isLast = index === visibleSources.length - 1;
357
+ const branch = isLast ? uiTheme.tree.last : uiTheme.tree.branch;
358
+ const cont = isLast ? " " : uiTheme.tree.vertical;
359
+ text += `\n ${uiTheme.fg("dim", branch)} ${uiTheme.fg("accent", truncateToWidth(replaceTabs(source.title), 100))}`;
360
+ text += `\n ${uiTheme.fg("dim", cont)} ${uiTheme.fg("dim", uiTheme.tree.hook)} ${uiTheme.fg("mdLinkUrl", source.url)}`;
361
+
362
+ if (source.totalMatches) {
363
+ text += `\n ${uiTheme.fg("dim", cont)} ${uiTheme.fg("dim", uiTheme.tree.hook)} ${uiTheme.fg("muted", `Matches: ${source.totalMatches}`)}`;
364
+ }
365
+
366
+ if (source.snippet) {
367
+ const snippetLines = source.snippet.split("\n").slice(0, options.expanded ? 6 : 3);
368
+ for (const line of snippetLines) {
369
+ text += `\n ${uiTheme.fg("dim", cont)} ${uiTheme.fg("dim", uiTheme.tree.hook)} ${uiTheme.fg(
370
+ "toolOutput",
371
+ truncateToWidth(replaceTabs(line), 100),
372
+ )}`;
373
+ }
374
+ }
375
+ }
376
+
377
+ if (!options.expanded && response.sources.length > visibleSources.length) {
378
+ text += `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg(
379
+ "muted",
380
+ formatMoreItems(response.sources.length - visibleSources.length, "result"),
381
+ )}`;
382
+ }
383
+
384
+ return new Text(text, 0, 0);
385
+ }