Elffuss BraidHub

kikocis/continue public

7668a8715766 · 2.5 KiBRawPermalink
1import { ToolImpl } from ".";
2import { ContextItem } from "../..";
3import { formatGrepSearchResults } from "../../util/grepSearch";
4
5const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
6const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
7
8function splitGrepResultsByFile(content: string): ContextItem[] {
9 const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
10
11 if (matches.length === 0) {
12 return [];
13 }
14
15 const contextItems: ContextItem[] = [];
16
17 for (let i = 0; i < matches.length; i++) {
18 const match = matches[i];
19 const filepath = match[1];
20 const startIndex = match.index!;
21 const endIndex =
22 i < matches.length - 1 ? matches[i + 1].index! : content.length;
23
24 // Extract grepped content for this file
25 const fileContent = content
26 .substring(startIndex, endIndex)
27 .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path
28 .trim();
29
30 if (fileContent) {
31 contextItems.push({
32 name: `Search results in ${filepath}`,
33 description: `Grep search results from ${filepath}`,
34 content: fileContent,
35 uri: { type: "file", value: filepath },
36 });
37 }
38 }
39
40 return contextItems;
41}
42
43export const grepSearchImpl: ToolImpl = async (args, extras) => {
44 const results = await extras.ide.getSearchResults(
45 args.query,
46 DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
47 );
48 const { formatted, numResults, truncated } = formatGrepSearchResults(
49 results,
50 DEFAULT_GREP_SEARCH_CHAR_LIMIT,
51 );
52 const truncationReasons: string[] = [];
53 if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
54 truncationReasons.push(
55 `the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`,
56 );
57 }
58 if (truncated) {
59 truncationReasons.push(
60 `the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`,
61 );
62 }
63
64 let contextItems: ContextItem[] = [];
65
66 const splitByFile: boolean = args.splitByFile || false;
67 if (splitByFile) {
68 contextItems = splitGrepResultsByFile(formatted);
69 } else {
70 contextItems = [
71 {
72 name: "Search results",
73 description: "Results from grep search",
74 content: formatted,
75 },
76 ];
77 }
78
79 if (truncationReasons.length > 0) {
80 contextItems.push({
81 name: "Search truncation warning",
82 description: "Informs the model that search results were truncated",
83 content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
84 });
85 }
86 return contextItems;
87};