@oh-my-pi/pi-coding-agent 13.11.0 → 13.12.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/package.json +7 -7
  3. package/src/capability/rule.ts +4 -0
  4. package/src/cli/commands/init-xdg.ts +27 -0
  5. package/src/cli/config-cli.ts +8 -3
  6. package/src/cli/shell-cli.ts +1 -1
  7. package/src/commands/config.ts +1 -1
  8. package/src/config/model-registry.ts +160 -26
  9. package/src/config/model-resolver.ts +84 -21
  10. package/src/config/settings-schema.ts +812 -647
  11. package/src/discovery/helpers.ts +11 -2
  12. package/src/exa/index.ts +1 -11
  13. package/src/exa/search.ts +1 -122
  14. package/src/exec/bash-executor.ts +62 -25
  15. package/src/extensibility/custom-tools/types.ts +2 -3
  16. package/src/extensibility/extensions/types.ts +2 -0
  17. package/src/extensibility/hooks/types.ts +2 -0
  18. package/src/index.ts +6 -6
  19. package/src/internal-urls/docs-index.generated.ts +3 -3
  20. package/src/lsp/config.ts +1 -0
  21. package/src/lsp/defaults.json +3 -3
  22. package/src/memories/index.ts +20 -7
  23. package/src/memories/storage.ts +46 -32
  24. package/src/modes/components/agent-dashboard.ts +23 -35
  25. package/src/modes/components/assistant-message.ts +25 -2
  26. package/src/modes/components/btw-panel.ts +104 -0
  27. package/src/modes/components/settings-defs.ts +5 -1
  28. package/src/modes/components/settings-selector.ts +6 -6
  29. package/src/modes/controllers/btw-controller.ts +193 -0
  30. package/src/modes/controllers/command-controller.ts +3 -1
  31. package/src/modes/controllers/event-controller.ts +4 -0
  32. package/src/modes/controllers/extension-ui-controller.ts +6 -0
  33. package/src/modes/controllers/input-controller.ts +10 -1
  34. package/src/modes/controllers/selector-controller.ts +18 -17
  35. package/src/modes/interactive-mode.ts +22 -0
  36. package/src/modes/prompt-action-autocomplete.ts +17 -3
  37. package/src/modes/rpc/rpc-client.ts +30 -19
  38. package/src/modes/theme/theme.ts +28 -36
  39. package/src/modes/types.ts +4 -0
  40. package/src/modes/utils/ui-helpers.ts +3 -0
  41. package/src/patch/hashline.ts +120 -16
  42. package/src/prompts/system/btw-user.md +8 -0
  43. package/src/prompts/system/custom-system-prompt.md +1 -1
  44. package/src/prompts/system/system-prompt.md +1 -0
  45. package/src/prompts/tools/code-search.md +45 -0
  46. package/src/prompts/tools/hashline.md +3 -0
  47. package/src/prompts/tools/read.md +2 -2
  48. package/src/sdk.ts +36 -40
  49. package/src/session/agent-session.ts +65 -37
  50. package/src/session/blob-store.ts +32 -0
  51. package/src/session/compaction/compaction.ts +27 -6
  52. package/src/session/history-storage.ts +2 -2
  53. package/src/session/session-manager.ts +116 -44
  54. package/src/session/streaming-output.ts +17 -54
  55. package/src/slash-commands/builtin-registry.ts +11 -0
  56. package/src/system-prompt.ts +4 -17
  57. package/src/task/agents.ts +1 -1
  58. package/src/task/executor.ts +1 -1
  59. package/src/task/index.ts +9 -8
  60. package/src/tools/browser.ts +11 -0
  61. package/src/tools/exit-plan-mode.ts +6 -0
  62. package/src/tools/fetch.ts +1 -1
  63. package/src/tools/output-meta.ts +104 -9
  64. package/src/tools/read.ts +13 -26
  65. package/src/utils/title-generator.ts +70 -92
  66. package/src/utils/tools-manager.ts +1 -1
  67. package/src/web/scrapers/index.ts +7 -7
  68. package/src/web/scrapers/utils.ts +1 -0
  69. package/src/web/search/code-search.ts +385 -0
  70. package/src/web/search/index.ts +25 -280
  71. package/src/web/search/provider.ts +1 -1
  72. package/src/web/search/types.ts +28 -0
  73. package/src/exa/company.ts +0 -26
  74. package/src/exa/linkedin.ts +0 -26
@@ -9,7 +9,6 @@ import type { ModelRegistry } from "../config/model-registry";
9
9
  import { resolveModelRoleValue } from "../config/model-resolver";
10
10
  import { renderPromptTemplate } from "../config/prompt-templates";
11
11
  import type { Settings } from "../config/settings";
12
- import MODEL_PRIO from "../priority.json" with { type: "json" };
13
12
  import titleSystemPrompt from "../prompts/system/title-system.md" with { type: "text" };
14
13
  import { toReasoningEffort } from "../thinking";
15
14
 
@@ -17,45 +16,28 @@ const TITLE_SYSTEM_PROMPT = renderPromptTemplate(titleSystemPrompt);
17
16
 
18
17
  const MAX_INPUT_CHARS = 2000;
19
18
 
20
- function getTitleModelCandidates(
19
+ function getTitleModel(
21
20
  registry: ModelRegistry,
22
21
  settings: Settings,
23
- ): Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }> {
22
+ currentModel?: Model<Api>,
23
+ ): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {
24
24
  const availableModels = registry.getAvailable();
25
- if (availableModels.length === 0) return [];
26
-
27
- const candidates: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }> = [];
28
- const addCandidate = (model?: Model<Api>, thinkingLevel?: ThinkingLevel): void => {
29
- if (!model) return;
30
- const exists = candidates.some(
31
- candidate => candidate.model.provider === model.provider && candidate.model.id === model.id,
32
- );
33
- if (!exists) {
34
- candidates.push({ model, thinkingLevel });
35
- }
36
- };
25
+ if (availableModels.length === 0) return undefined;
37
26
 
38
27
  const matchPreferences = { usageOrder: settings.getStorage()?.getModelUsageOrder() };
39
28
  const configuredSmol = resolveModelRoleValue(settings.getModelRole("smol"), availableModels, {
40
29
  settings,
41
30
  matchPreferences,
42
31
  });
43
- addCandidate(configuredSmol.model, configuredSmol.thinkingLevel);
44
-
45
- for (const pattern of MODEL_PRIO.smol) {
46
- const needle = pattern.toLowerCase();
47
- const exactMatch = availableModels.find(model => model.id.toLowerCase() === needle);
48
- addCandidate(exactMatch);
49
-
50
- const fuzzyMatch = availableModels.find(model => model.id.toLowerCase().includes(needle));
51
- addCandidate(fuzzyMatch);
32
+ if (configuredSmol.model) {
33
+ return { model: configuredSmol.model, thinkingLevel: configuredSmol.thinkingLevel };
52
34
  }
53
35
 
54
- for (const model of availableModels) {
55
- addCandidate(model);
36
+ if (currentModel) {
37
+ return { model: currentModel };
56
38
  }
57
39
 
58
- return candidates;
40
+ return undefined;
59
41
  }
60
42
 
61
43
  /**
@@ -71,10 +53,11 @@ export async function generateSessionTitle(
71
53
  registry: ModelRegistry,
72
54
  settings: Settings,
73
55
  sessionId?: string,
56
+ currentModel?: Model<Api>,
74
57
  ): Promise<string | null> {
75
- const candidates = getTitleModelCandidates(registry, settings);
76
- if (candidates.length === 0) {
77
- logger.debug("title-generator: no smol model found");
58
+ const candidate = getTitleModel(registry, settings, currentModel);
59
+ if (!candidate) {
60
+ logger.debug("title-generator: no title model found");
78
61
  return null;
79
62
  }
80
63
 
@@ -85,78 +68,73 @@ export async function generateSessionTitle(
85
68
  ${truncatedMessage}
86
69
  </user-message>`;
87
70
 
88
- for (const candidate of candidates) {
89
- const apiKey = await registry.getApiKey(candidate.model, sessionId);
90
- if (!apiKey) {
91
- logger.debug("title-generator: no API key for model", {
92
- provider: candidate.model.provider,
93
- id: candidate.model.id,
94
- });
95
- continue;
96
- }
97
-
98
- const request = {
99
- model: `${candidate.model.provider}/${candidate.model.id}`,
100
- systemPrompt: TITLE_SYSTEM_PROMPT,
101
- userMessage,
102
- maxTokens: 30,
103
- };
104
- logger.debug("title-generator: request", request);
105
-
106
- try {
107
- const response = await completeSimple(
108
- candidate.model,
109
- {
110
- systemPrompt: request.systemPrompt,
111
- messages: [{ role: "user", content: request.userMessage, timestamp: Date.now() }],
112
- },
113
- {
114
- apiKey,
115
- maxTokens: 30,
116
- reasoning: toReasoningEffort(candidate.thinkingLevel),
117
- },
118
- );
119
-
120
- if (response.stopReason === "error") {
121
- logger.debug("title-generator: response error", {
122
- model: request.model,
123
- stopReason: response.stopReason,
124
- errorMessage: response.errorMessage,
125
- });
126
- continue;
127
- }
71
+ const apiKey = await registry.getApiKey(candidate.model, sessionId);
72
+ if (!apiKey) {
73
+ logger.debug("title-generator: no API key for smol model", {
74
+ provider: candidate.model.provider,
75
+ id: candidate.model.id,
76
+ });
77
+ return null;
78
+ }
128
79
 
129
- // Extract title from response text content
130
- let title = "";
131
- for (const content of response.content) {
132
- if (content.type === "text") {
133
- title += content.text;
134
- }
135
- }
136
- title = title.trim();
80
+ const request = {
81
+ model: `${candidate.model.provider}/${candidate.model.id}`,
82
+ systemPrompt: TITLE_SYSTEM_PROMPT,
83
+ userMessage,
84
+ maxTokens: 30,
85
+ };
86
+ logger.debug("title-generator: request", request);
87
+
88
+ try {
89
+ const response = await completeSimple(
90
+ candidate.model,
91
+ {
92
+ systemPrompt: request.systemPrompt,
93
+ messages: [{ role: "user", content: request.userMessage, timestamp: Date.now() }],
94
+ },
95
+ {
96
+ apiKey,
97
+ maxTokens: 30,
98
+ reasoning: toReasoningEffort(candidate.thinkingLevel),
99
+ },
100
+ );
137
101
 
138
- logger.debug("title-generator: response", {
102
+ if (response.stopReason === "error") {
103
+ logger.debug("title-generator: response error", {
139
104
  model: request.model,
140
- title,
141
- usage: response.usage,
142
105
  stopReason: response.stopReason,
106
+ errorMessage: response.errorMessage,
143
107
  });
108
+ return null;
109
+ }
144
110
 
145
- if (!title) {
146
- continue;
111
+ let title = "";
112
+ for (const content of response.content) {
113
+ if (content.type === "text") {
114
+ title += content.text;
147
115
  }
116
+ }
117
+ title = title.trim();
148
118
 
149
- // Clean up: remove quotes, trailing punctuation
150
- return title.replace(/^["']|["']$/g, "").replace(/[.!?]$/, "");
151
- } catch (err) {
152
- logger.debug("title-generator: error", {
153
- model: request.model,
154
- error: err instanceof Error ? err.message : String(err),
155
- });
119
+ logger.debug("title-generator: response", {
120
+ model: request.model,
121
+ title,
122
+ usage: response.usage,
123
+ stopReason: response.stopReason,
124
+ });
125
+
126
+ if (!title) {
127
+ return null;
156
128
  }
157
- }
158
129
 
159
- return null;
130
+ return title.replace(/^["']|["']$/g, "").replace(/[.!?]$/, "");
131
+ } catch (err) {
132
+ logger.debug("title-generator: error", {
133
+ model: request.model,
134
+ error: err instanceof Error ? err.message : String(err),
135
+ });
136
+ return null;
137
+ }
160
138
  }
161
139
 
162
140
  /**
@@ -4,7 +4,7 @@ import * as path from "node:path";
4
4
  import { APP_NAME, getToolsDir, logger, ptree, TempDir } from "@oh-my-pi/pi-utils";
5
5
 
6
6
  const TOOLS_DIR = getToolsDir();
7
- const TOOL_DOWNLOAD_TIMEOUT_MS = 15000;
7
+ const TOOL_DOWNLOAD_TIMEOUT_MS = 120_000;
8
8
  const TOOL_METADATA_TIMEOUT_MS = 5000;
9
9
 
10
10
  interface ToolConfig {
@@ -85,17 +85,16 @@ export type { RenderResult, SpecialHandler } from "./types";
85
85
  export {
86
86
  fetchGitHubApi,
87
87
  handleArtifactHub,
88
- handleDocsRs,
89
88
  handleArxiv,
90
89
  handleAur,
91
90
  handleBiorxiv,
92
91
  handleBluesky,
93
92
  handleBrew,
94
93
  handleCheatSh,
95
- handleCisaKev,
96
94
  handleChocolatey,
97
- handleClojars,
98
95
  handleChooseALicense,
96
+ handleCisaKev,
97
+ handleClojars,
99
98
  handleCoinGecko,
100
99
  handleCratesIo,
101
100
  handleCrossref,
@@ -103,9 +102,10 @@ export {
103
102
  handleDiscogs,
104
103
  handleDiscourse,
105
104
  handleDockerHub,
105
+ handleDocsRs,
106
106
  handleFdroid,
107
- handleFlathub,
108
107
  handleFirefoxAddons,
108
+ handleFlathub,
109
109
  handleGitHub,
110
110
  handleGitHubGist,
111
111
  handleGitLab,
@@ -129,8 +129,8 @@ export {
129
129
  handleOllama,
130
130
  handleOpenCorporates,
131
131
  handleOpenLibrary,
132
- handleOrcid,
133
132
  handleOpenVsx,
133
+ handleOrcid,
134
134
  handleOsv,
135
135
  handlePackagist,
136
136
  handlePubDev,
@@ -142,13 +142,13 @@ export {
142
142
  handleRepology,
143
143
  handleRfc,
144
144
  handleRubyGems,
145
- handleSecEdgar,
146
145
  handleSearchcode,
146
+ handleSecEdgar,
147
147
  handleSemanticScholar,
148
148
  handleSnapcraft,
149
149
  handleSourcegraph,
150
- handleSpotify,
151
150
  handleSpdx,
151
+ handleSpotify,
152
152
  handleStackOverflow,
153
153
  handleTerraform,
154
154
  handleTldr,
@@ -1,4 +1,5 @@
1
1
  import { isRecord, ptree, TempDir } from "@oh-my-pi/pi-utils";
2
+
2
3
  export { isRecord };
3
4
 
4
5
  import { ToolAbortError } from "../../tools/tool-errors";
@@ -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
+ }