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..d13da2145 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,40 @@ // @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 { 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"; const DEFAULT_CHUNK_SIZE = 384; +const AVAILABLE_TOOLS: Tool[] = [ + globSearchTool, + grepSearchTool, + lsTool, + readFileTool, + viewRepoMapTool, + viewSubdirectoryTool, +]; + export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; @@ -155,4 +181,105 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { 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: +${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} + 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.chat( + [{ role: "user", content: toolSelectionPrompt }], + new AbortController().signal, + ); + + let toolCalls: { name: string; args: any }[] = []; + try { + 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) { + 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) { + const tool = AVAILABLE_TOOLS.find( + (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, + args, + toolExtras, + ); + allContextItems.push(...contextItems); + } + + const chunks: Chunk[] = []; + + // Transform ContextItem[] to Chunk[] + 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:\/\/\//, ""); + + chunks.push({ + content: contextItem.content, + startLine: -1, + endLine: -1, + digest: `file:///${cleanedFilepath}`, + filepath: `file:///${cleanedFilepath}`, + 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..31dc8750b 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -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: { diff --git a/core/core.ts b/core/core.ts index 3749ede9e..5049484fe 100644 --- a/core/core.ts +++ b/core/core.ts @@ -45,7 +45,6 @@ import { RangeInFile, ToolCall, type ContextItem, - type ContextItemId, type IDE, } from "."; @@ -1101,11 +1100,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, }); @@ -1132,7 +1126,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 fdee1f262..c6dabcb02 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1422,6 +1422,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/callTool.ts b/core/tools/callTool.ts index c6e19b068..f24210511 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -16,6 +16,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( @@ -135,7 +137,7 @@ async function callToolFromUri( } } -async function callBuiltInTool( +export async function callBuiltInTool( functionName: string, args: any, extras: ToolExtras, @@ -167,6 +169,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`); } 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/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", 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 && (