From 63552e3fd31d9c471969b5d74cfabf925215172c Mon Sep 17 00:00:00 2001 From: Ting-Wai To Date: Wed, 2 Jul 2025 22:47:57 -0700 Subject: [PATCH 1/4] @codebase use tool calling (under experimental flag) --- core/config/sharedConfig.ts | 5 + .../pipelines/BaseRetrievalPipeline.ts | 203 +++++++++++++++++- .../pipelines/NoRerankerRetrievalPipeline.ts | 22 +- .../pipelines/RerankerRetrievalPipeline.ts | 22 +- core/context/retrieval/retrieval.ts | 10 +- core/core.ts | 11 +- core/index.d.ts | 6 + core/tools/definitions/globSearch.ts | 2 +- gui/src/pages/config/UserSettingsForm.tsx | 12 ++ 9 files changed, 269 insertions(+), 24 deletions(-) diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 9fb8da4e5..5d7053cf8 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -22,6 +22,7 @@ export const sharedConfigSchema = z logEditingData: z.boolean(), optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), + codebaseToolCallingOnly: z.boolean(), // `ui` in `ContinueConfig` showSessionTabs: z.boolean(), @@ -187,6 +188,10 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.optInNextEditFeature = sharedConfig.optInNextEditFeature; } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { + configCopy.experimental.codebaseToolCallingOnly = + sharedConfig.codebaseToolCallingOnly; + } return configCopy; } diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index b8e196cff..de731de76 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,45 @@ // @ts-ignore import nlp from "wink-nlp-utils"; -import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { + BranchAndDir, + Chunk, + ContextItem, + ContinueConfig, + IDE, + ILLM, + Tool, + ToolExtras, +} from "../../../"; import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache"; import { chunkDocument } from "../../../indexing/chunk/chunk"; import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { BuiltInToolNames } from "../../../tools/builtIn"; +import { globSearchTool } from "../../../tools/definitions/globSearch"; +import { grepSearchTool } from "../../../tools/definitions/grepSearch"; +import { lsTool } from "../../../tools/definitions/lsTool"; +import { readFileTool } from "../../../tools/definitions/readFile"; +import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap"; +import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory"; +import { fileGlobSearchImpl } from "../../../tools/implementations/globSearch"; +import { grepSearchImpl } from "../../../tools/implementations/grepSearch"; +import { lsToolImpl } from "../../../tools/implementations/lsTool"; +import { readFileImpl } from "../../../tools/implementations/readFile"; +import { viewRepoMapImpl } from "../../../tools/implementations/viewRepoMap"; +import { viewSubdirectoryImpl } from "../../../tools/implementations/viewSubdirectory"; const DEFAULT_CHUNK_SIZE = 384; +const availableTools: Tool[] = [ + globSearchTool, + grepSearchTool, + lsTool, + readFileTool, + viewRepoMapTool, + viewSubdirectoryTool, +]; + export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; @@ -152,7 +183,175 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(args: RetrievalPipelineRunArguments): Promise { + run(_args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } + + protected async retrieveWithTools(input: string): Promise { + const toolSelectionPrompt = `Given the following user input: "${input}" + +Available tools: +${availableTools + .map((tool) => { + const requiredParams = tool.function.parameters?.required || []; + const properties = tool.function.parameters?.properties || {}; + const paramDescriptions = requiredParams + .map( + (param: any) => + `${param}: ${properties[param]?.description || "string"}`, + ) + .join(", "); + + return `- ${tool.function.name}: ${tool.function.description} + Required arguments: ${paramDescriptions || "none"}`; + }) + .join("\n")} + +Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else: +{ + "tools": [ + { + "name": "", + "args": { "": "" } + } + ] +}`; + + // Get LLM response for tool selection + const toolSelectionResponse = await this.options.llm.complete( + toolSelectionPrompt, + new AbortController().signal, + ); + + let toolCalls: { name: string; args: any }[] = []; + try { + const parsed = JSON.parse(toolSelectionResponse); + toolCalls = parsed.tools || []; + console.log("retrieveWithTools", toolCalls); + } catch (e) { + console.log("Failed to parse tool selection response", e); + return []; + } + + // Execute tools and collect results + const allContextItems: ContextItem[] = []; + + const toolExtras: ToolExtras = { + ide: this.options.ide, + llm: this.options.llm, + fetch: fetch, + tool: grepSearchTool, + config: this.options.config, + }; + + for (const toolCall of toolCalls) { + switch (toolCall.name) { + case BuiltInToolNames.FileGlobSearch: + toolExtras.tool = globSearchTool; + const globSearchContextItems = await fileGlobSearchImpl( + toolCall.args, + toolExtras, + ); + allContextItems.push(...globSearchContextItems); + break; + + case BuiltInToolNames.GrepSearch: + toolExtras.tool = grepSearchTool; + const grepContextItems = await grepSearchImpl( + toolCall.args, + toolExtras, + ); + allContextItems.push(...grepContextItems); + break; + + case BuiltInToolNames.LSTool: + toolExtras.tool = lsTool; + const lsContextItems = await lsToolImpl(toolCall.args, toolExtras); + allContextItems.push(...lsContextItems); + break; + + case BuiltInToolNames.ReadFile: + toolExtras.tool = readFileTool; + const readFileImplContextItems = await readFileImpl( + toolCall.args, + toolExtras, + ); + allContextItems.push(...readFileImplContextItems); + break; + + case BuiltInToolNames.ViewRepoMap: + toolExtras.tool = viewRepoMapTool; + const repoMapContextItems = await viewRepoMapImpl( + toolCall.args, + toolExtras, + ); + allContextItems.push(...repoMapContextItems); + break; + + case BuiltInToolNames.ViewSubdirectory: + toolExtras.tool = viewSubdirectoryTool; + const viewSubdirContextItems = await viewSubdirectoryImpl( + toolCall.args, + toolExtras, + ); + allContextItems.push(...viewSubdirContextItems); + break; + } + } + + const chunks: Chunk[] = []; + + // Transform ContextItem[] to Chunk[] + for (const contextItem of allContextItems) { + const content = contextItem.content; + const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; + + if (matches.length === 0) { + // single chunk content or no file path patterns found that need to be split + const filepath = + contextItem.uri?.value || contextItem.name || "unknown"; + const cleanedFilepath = filepath.replace(/^file:\/\/\//, ""); + + chunks.push({ + content: contextItem.content, + startLine: -1, + endLine: -1, + digest: `file:///${cleanedFilepath}`, + filepath: `file:///${cleanedFilepath}`, + index: 0, + }); + } else { + // Split grep search results by file paths and create separate chunks + for (let i = 0; i < matches.length; i++) { + const match = matches[i]; + const filepath = match[1]; + const startIndex = match.index!; + const endIndex = + i < matches.length - 1 ? matches[i + 1].index! : content.length; + + // Extract grepped content for this file + const fileContent = content + .substring(startIndex, endIndex) + .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path + .trim(); + + if (fileContent) { + // getUriDescription expects a full file path + const fullFilePath = `file:///${filepath}`; + chunks.push({ + content: fileContent, + startLine: -1, + endLine: -1, + digest: fullFilePath, + filepath: fullFilePath, + index: i, + }); + } + } + } + } + + console.log("retrieveWithTools chunks", chunks); + return chunks; + } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index ca88c479e..f98a48c41 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { console.error("Error retrieving repo map chunks:", error); } - retrievalResults.push( - ...recentlyEditedFilesChunks, - ...ftsChunks, - ...embeddingsChunks, - ...repoMapChunks, - ); + if (this.options.config.experimental?.codebaseToolCallingOnly) { + let toolBasedChunks: Chunk[] = []; + try { + toolBasedChunks = await this.retrieveWithTools(input); + } catch (error) { + console.error("Error retrieving tool based chunks:", error); + } + retrievalResults.push(...toolBasedChunks); + } else { + retrievalResults.push( + ...recentlyEditedFilesChunks, + ...ftsChunks, + ...embeddingsChunks, + ...repoMapChunks, + ); + } if (filterDirectory) { // Backup if the individual retrieval methods don't listen diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 6829e7d75..8a9d053fd 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { console.error("Error retrieving repo map chunks:", error); } - retrievalResults.push( - ...recentlyEditedFilesChunks, - ...ftsChunks, - ...embeddingsChunks, - ...repoMapChunks, - ); + if (config.experimental?.codebaseToolCallingOnly) { + let toolBasedChunks: Chunk[] = []; + try { + toolBasedChunks = await this.retrieveWithTools(input); + } catch (error) { + console.error("Error retrieving tool based chunks:", error); + } + retrievalResults.push(...toolBasedChunks); + } else { + retrievalResults.push( + ...recentlyEditedFilesChunks, + ...ftsChunks, + ...embeddingsChunks, + ...repoMapChunks, + ); + } if (filterDirectory) { // Backup if the individual retrieval methods don't listen diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 3b8e98427..1ada3a792 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -91,7 +91,7 @@ export async function retrieveContextItemsFromEmbeddings( return []; } - return [ + const result = [ { ...INSTRUCTIONS_BASE_ITEM, content: @@ -108,7 +108,11 @@ export async function retrieveContextItemsFromEmbeddings( } return { - name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`, + // Don't show line numbers for tool calls where startLine = -1 + name: + r.startLine === -1 + ? baseName + : `${baseName} (${r.startLine + 1}-${r.endLine + 1})`, description: last2Parts, content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``, uri: { @@ -118,4 +122,6 @@ export async function retrieveContextItemsFromEmbeddings( }; }), ]; + + return result; } diff --git a/core/core.ts b/core/core.ts index 613bd0807..030e04733 100644 --- a/core/core.ts +++ b/core/core.ts @@ -45,7 +45,6 @@ import { RangeInFile, ToolCall, type ContextItem, - type ContextItemId, type IDE, } from "."; @@ -1102,11 +1101,6 @@ export class Core { } try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; - void Telemetry.capture("context_provider_get_context_items", { name: provider.description.title, }); @@ -1133,7 +1127,10 @@ export class Core { return items.map((item) => ({ ...item, - id, + id: { + providerTitle: provider.description.title, + itemId: item.uri?.value ?? uuidv4(), + }, })); } catch (e) { let knownError = false; diff --git a/core/index.d.ts b/core/index.d.ts index 3cc31dbaf..33f90351a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1420,6 +1420,12 @@ export interface ExperimentalConfig { * If enabled, will enable next edit in place of autocomplete */ optInNextEditFeature?: boolean; + + /** + * If enabled, @codebase will only use tool calling + * instead of embeddings, FTS, recently edited files, etc. + */ + codebaseToolCallingOnly?: boolean; } export interface AnalyticsConfig { diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index b3cbcac5b..42e8afd2d 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -13,7 +13,7 @@ export const globSearchTool: Tool = { function: { name: BuiltInToolNames.FileGlobSearch, description: - "Search for files in the project. Output may be truncated; use targeted patterns", + "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns", parameters: { type: "object", required: ["pattern"], diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index eba44f2c8..04405f1be 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -95,6 +95,8 @@ export function UserSettingsForm() { config.experimental?.enableExperimentalTools ?? false; const optInNextEditFeature = config.experimental?.optInNextEditFeature ?? false; + const codebaseToolCallingOnly = + config.experimental?.codebaseToolCallingOnly ?? false; const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; const disableIndexing = config.disableIndexing ?? false; @@ -422,6 +424,16 @@ export function UserSettingsForm() { text="Enable experimental tools" /> + + handleUpdate({ + codebaseToolCallingOnly: !codebaseToolCallingOnly, + }) + } + text="@Codebase: use tool calling only" + /> + {hasContinueEmail && ( Date: Thu, 3 Jul 2025 10:56:50 -0700 Subject: [PATCH 2/4] cleanup --- core/context/retrieval/pipelines/BaseRetrievalPipeline.ts | 2 +- core/context/retrieval/retrieval.ts | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index de731de76..50f58c073 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -183,7 +183,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(_args: RetrievalPipelineRunArguments): Promise { + run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 1ada3a792..31dc8750b 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -91,7 +91,7 @@ export async function retrieveContextItemsFromEmbeddings( return []; } - const result = [ + return [ { ...INSTRUCTIONS_BASE_ITEM, content: @@ -122,6 +122,4 @@ export async function retrieveContextItemsFromEmbeddings( }; }), ]; - - return result; } From 7345ad2c7afac94ba33dde07698c4eeee8d1d5b1 Mon Sep 17 00:00:00 2001 From: Ting-Wai To Date: Thu, 3 Jul 2025 12:29:51 -0700 Subject: [PATCH 3/4] Address comments --- .../pipelines/BaseRetrievalPipeline.ts | 106 +++++------------- core/tools/callTool.ts | 8 +- 2 files changed, 38 insertions(+), 76 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 50f58c073..6a405a3e3 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -15,23 +15,17 @@ import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCa import { chunkDocument } from "../../../indexing/chunk/chunk"; import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; -import { BuiltInToolNames } from "../../../tools/builtIn"; +import { callBuiltInTool } from "../../../tools/callTool"; import { globSearchTool } from "../../../tools/definitions/globSearch"; import { grepSearchTool } from "../../../tools/definitions/grepSearch"; import { lsTool } from "../../../tools/definitions/lsTool"; import { readFileTool } from "../../../tools/definitions/readFile"; import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap"; import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory"; -import { fileGlobSearchImpl } from "../../../tools/implementations/globSearch"; -import { grepSearchImpl } from "../../../tools/implementations/grepSearch"; -import { lsToolImpl } from "../../../tools/implementations/lsTool"; -import { readFileImpl } from "../../../tools/implementations/readFile"; -import { viewRepoMapImpl } from "../../../tools/implementations/viewRepoMap"; -import { viewSubdirectoryImpl } from "../../../tools/implementations/viewSubdirectory"; const DEFAULT_CHUNK_SIZE = 384; -const availableTools: Tool[] = [ +const AVAILABLE_TOOLS: Tool[] = [ globSearchTool, grepSearchTool, lsTool, @@ -191,21 +185,18 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { const toolSelectionPrompt = `Given the following user input: "${input}" Available tools: -${availableTools - .map((tool) => { - const requiredParams = tool.function.parameters?.required || []; - const properties = tool.function.parameters?.properties || {}; - const paramDescriptions = requiredParams - .map( - (param: any) => - `${param}: ${properties[param]?.description || "string"}`, - ) - .join(", "); +${AVAILABLE_TOOLS.map((tool) => { + const requiredParams = tool.function.parameters?.required || []; + const properties = tool.function.parameters?.properties || {}; + const paramDescriptions = requiredParams + .map( + (param: any) => `${param}: ${properties[param]?.description || "string"}`, + ) + .join(", "); - return `- ${tool.function.name}: ${tool.function.description} + return `- ${tool.function.name}: ${tool.function.description} Required arguments: ${paramDescriptions || "none"}`; - }) - .join("\n")} +}).join("\n")} Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else: { @@ -218,14 +209,20 @@ Determine which tools should be used to answer this query. You should feel free }`; // Get LLM response for tool selection - const toolSelectionResponse = await this.options.llm.complete( - toolSelectionPrompt, + const toolSelectionResponse = await this.options.llm.chat( + [{ role: "user", content: toolSelectionPrompt }], new AbortController().signal, ); let toolCalls: { name: string; args: any }[] = []; try { - const parsed = JSON.parse(toolSelectionResponse); + const responseContent = + typeof toolSelectionResponse.content === "string" + ? toolSelectionResponse.content + : toolSelectionResponse.content + .map((part) => (part.type === "text" ? part.text : "")) + .join(""); + const parsed = JSON.parse(responseContent); toolCalls = parsed.tools || []; console.log("retrieveWithTools", toolCalls); } catch (e) { @@ -245,58 +242,17 @@ Determine which tools should be used to answer this query. You should feel free }; for (const toolCall of toolCalls) { - switch (toolCall.name) { - case BuiltInToolNames.FileGlobSearch: - toolExtras.tool = globSearchTool; - const globSearchContextItems = await fileGlobSearchImpl( - toolCall.args, - toolExtras, - ); - allContextItems.push(...globSearchContextItems); - break; + const tool = AVAILABLE_TOOLS.find( + (t) => t.function.name === toolCall.name, + )!; - case BuiltInToolNames.GrepSearch: - toolExtras.tool = grepSearchTool; - const grepContextItems = await grepSearchImpl( - toolCall.args, - toolExtras, - ); - allContextItems.push(...grepContextItems); - break; - - case BuiltInToolNames.LSTool: - toolExtras.tool = lsTool; - const lsContextItems = await lsToolImpl(toolCall.args, toolExtras); - allContextItems.push(...lsContextItems); - break; - - case BuiltInToolNames.ReadFile: - toolExtras.tool = readFileTool; - const readFileImplContextItems = await readFileImpl( - toolCall.args, - toolExtras, - ); - allContextItems.push(...readFileImplContextItems); - break; - - case BuiltInToolNames.ViewRepoMap: - toolExtras.tool = viewRepoMapTool; - const repoMapContextItems = await viewRepoMapImpl( - toolCall.args, - toolExtras, - ); - allContextItems.push(...repoMapContextItems); - break; - - case BuiltInToolNames.ViewSubdirectory: - toolExtras.tool = viewSubdirectoryTool; - const viewSubdirContextItems = await viewSubdirectoryImpl( - toolCall.args, - toolExtras, - ); - allContextItems.push(...viewSubdirContextItems); - break; - } + toolExtras.tool = tool; + const contextItems = await callBuiltInTool( + toolCall.name, + toolCall.args, + toolExtras, + ); + allContextItems.push(...contextItems); } const chunks: Chunk[] = []; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 0b81cbae5..ac4a09080 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -17,6 +17,8 @@ import { requestRuleImpl } from "./implementations/requestRule"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { viewRepoMapImpl } from "./implementations/viewRepoMap"; +import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; import { safeParseToolCallArgs } from "./parseArgs"; async function callHttpTool( @@ -136,7 +138,7 @@ async function callToolFromUri( } } -async function callBuiltInTool( +export async function callBuiltInTool( functionName: string, args: any, extras: ToolExtras, @@ -168,6 +170,10 @@ async function callBuiltInTool( return await requestRuleImpl(args, extras); case BuiltInToolNames.CodebaseTool: return await codebaseToolImpl(args, extras); + case BuiltInToolNames.ViewRepoMap: + return await viewRepoMapImpl(args, extras); + case BuiltInToolNames.ViewSubdirectory: + return await viewSubdirectoryImpl(args, extras); default: throw new Error(`Tool "${functionName}" not found`); } From a87d8f37aca547510494dd8f5350971d02666abe Mon Sep 17 00:00:00 2001 From: Ting-Wai To Date: Thu, 3 Jul 2025 13:03:02 -0700 Subject: [PATCH 4/4] Address comments, refactor splitGrepResultsByFile into grepSearch implementation --- .../pipelines/BaseRetrievalPipeline.ts | 66 ++++++------------- core/tools/implementations/grepSearch.ts | 57 ++++++++++++++-- 2 files changed, 69 insertions(+), 54 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 6a405a3e3..d13da2145 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -15,6 +15,7 @@ import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCa import { chunkDocument } from "../../../indexing/chunk/chunk"; import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { BuiltInToolNames } from "../../../tools/builtIn"; import { callBuiltInTool } from "../../../tools/callTool"; import { globSearchTool } from "../../../tools/definitions/globSearch"; import { grepSearchTool } from "../../../tools/definitions/grepSearch"; @@ -246,10 +247,15 @@ Determine which tools should be used to answer this query. You should feel free (t) => t.function.name === toolCall.name, )!; + const args = toolCall.args; + if (toolCall.name === BuiltInToolNames.GrepSearch) { + args.splitByFile = true; + } + toolExtras.tool = tool; const contextItems = await callBuiltInTool( toolCall.name, - toolCall.args, + args, toolExtras, ); allContextItems.push(...contextItems); @@ -258,53 +264,19 @@ Determine which tools should be used to answer this query. You should feel free const chunks: Chunk[] = []; // Transform ContextItem[] to Chunk[] - for (const contextItem of allContextItems) { - const content = contextItem.content; - const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; + for (let i = 0; i < allContextItems.length; i++) { + const contextItem = allContextItems[i]; + const filepath = contextItem.uri?.value || contextItem.name || "unknown"; + const cleanedFilepath = filepath.replace(/^file:\/\/\//, ""); - if (matches.length === 0) { - // single chunk content or no file path patterns found that need to be split - const filepath = - contextItem.uri?.value || contextItem.name || "unknown"; - const cleanedFilepath = filepath.replace(/^file:\/\/\//, ""); - - chunks.push({ - content: contextItem.content, - startLine: -1, - endLine: -1, - digest: `file:///${cleanedFilepath}`, - filepath: `file:///${cleanedFilepath}`, - index: 0, - }); - } else { - // Split grep search results by file paths and create separate chunks - for (let i = 0; i < matches.length; i++) { - const match = matches[i]; - const filepath = match[1]; - const startIndex = match.index!; - const endIndex = - i < matches.length - 1 ? matches[i + 1].index! : content.length; - - // Extract grepped content for this file - const fileContent = content - .substring(startIndex, endIndex) - .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path - .trim(); - - if (fileContent) { - // getUriDescription expects a full file path - const fullFilePath = `file:///${filepath}`; - chunks.push({ - content: fileContent, - startLine: -1, - endLine: -1, - digest: fullFilePath, - filepath: fullFilePath, - index: i, - }); - } - } - } + chunks.push({ + content: contextItem.content, + startLine: -1, + endLine: -1, + digest: `file:///${cleanedFilepath}`, + filepath: `file:///${cleanedFilepath}`, + index: i, + }); } console.log("retrieveWithTools chunks", chunks); diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index 149b68a75..b13839669 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -5,6 +5,41 @@ import { formatGrepSearchResults } from "../../util/grepSearch"; const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now +function splitGrepResultsByFile(content: string): ContextItem[] { + const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; + + if (matches.length === 0) { + return []; + } + + const contextItems: ContextItem[] = []; + + for (let i = 0; i < matches.length; i++) { + const match = matches[i]; + const filepath = match[1]; + const startIndex = match.index!; + const endIndex = + i < matches.length - 1 ? matches[i + 1].index! : content.length; + + // Extract grepped content for this file + const fileContent = content + .substring(startIndex, endIndex) + .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path + .trim(); + + if (fileContent) { + contextItems.push({ + name: `Search results in ${filepath}`, + description: `Grep search results from ${filepath}`, + content: fileContent, + uri: { type: "file", value: filepath }, + }); + } + } + + return contextItems; +} + export const grepSearchImpl: ToolImpl = async (args, extras) => { const results = await extras.ide.getSearchResults( args.query, @@ -26,13 +61,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ); } - const contextItems: ContextItem[] = [ - { - name: "Search results", - description: "Results from grep search", - content: formatted, - }, - ]; + let contextItems: ContextItem[] = []; + + const splitByFile: boolean = args.splitByFile || false; + if (splitByFile) { + contextItems = splitGrepResultsByFile(formatted); + } else { + contextItems = [ + { + name: "Search results", + description: "Results from grep search", + content: formatted, + }, + ]; + } + if (truncationReasons.length > 0) { contextItems.push({ name: "Search truncation warning",