diff --git a/core/tools/implementations/codebaseTool.ts b/core/tools/implementations/codebaseTool.ts index 9ea0ecdc7..4af0579bf 100644 --- a/core/tools/implementations/codebaseTool.ts +++ b/core/tools/implementations/codebaseTool.ts @@ -1,16 +1,15 @@ import { ToolImpl } from "."; import { RangeInFile } from "../.."; import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval"; +import { getStringArg } from "../parseArgs"; export const codebaseToolImpl: ToolImpl = async (args, extras) => { - if (!args?.query || args.query.trim() === "") { - throw new Error("`query` parameter is required and cannot be empty."); - } + const query = getStringArg(args, "query"); try { const contextExtras = { config: extras.config, - fullInput: args.query, + fullInput: query, embeddingsProvider: extras.config.selectedModelByRole.embed, reranker: extras.config.selectedModelByRole.rerank, llm: extras.llm, @@ -33,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => { { name: "No Results", description: "Codebase search", - content: `No relevant code found for query: "${args.query}". This could mean: + content: `No relevant code found for query: "${query}". This could mean: - The codebase hasn't been indexed yet - No code matches the search criteria - Embeddings provider is not configured diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index d1849025e..0677e7dcd 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -2,28 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; +import { getStringArg } from "../parseArgs"; export const createNewFileImpl: ToolImpl = async (args, extras) => { - if (!args?.filepath) { - throw new Error("`filepath` argument is required and cannot be empty."); - } - if (args?.contents === undefined) { - throw new Error( - "`contents` argument is required to create a new file (can be empty).", - ); - } + const filepath = getStringArg(args, "filepath"); + const contents = getStringArg(args, "contents", true); + const resolvedFileUri = await inferResolvedUriFromRelativePath( - args.filepath, + filepath, extras.ide, ); if (resolvedFileUri) { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { throw new Error( - `File ${args.filepath} already exists. Use the edit tool to edit this file`, + `File ${filepath} already exists. Use the edit tool to edit this file`, ); } - await extras.ide.writeFile(resolvedFileUri, args.contents); + await extras.ide.writeFile(resolvedFileUri, contents); await extras.ide.openFile(resolvedFileUri); await extras.ide.saveFile(resolvedFileUri); if (extras.codeBaseIndexer) { diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 2e7a646aa..8e8ebcf90 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml"; import { ToolImpl } from "."; import { RuleWithSource } from "../.."; import { createRuleFilePath } from "../../config/markdown/utils"; +import { + getBooleanArg, + getOptionalStringArg, + getStringArg, +} from "../parseArgs"; export type CreateRuleBlockArgs = Pick< Required, @@ -9,16 +14,21 @@ export type CreateRuleBlockArgs = Pick< > & Pick; -export const createRuleBlockImpl: ToolImpl = async ( - { name, rule, ...otherArgs }: CreateRuleBlockArgs, - extras, -) => { - if (!name || !rule) { - throw new Error( - "`name` and `rule` arguments are required to create a rule.", - ); - } - const fileContent = createRuleMarkdown(name, rule, otherArgs); +export const createRuleBlockImpl: ToolImpl = async (args, extras) => { + const name = getStringArg(args, "name"); + const rule = getStringArg(args, "rule"); + + const description = getOptionalStringArg(args, "description"); + const regex = getOptionalStringArg(args, "regex"); + const globs = getOptionalStringArg(args, "globs"); + const alwaysApply = getBooleanArg(args, "alwaysApply", false); + + const fileContent = createRuleMarkdown(name, rule, { + alwaysApply, + description, + globs, + regex, + }); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); const ruleFilePath = createRuleFilePath(localContinueDir, name); @@ -29,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async ( return [ { name: "New Rule Block", - description: otherArgs.description || "", + description: description || "", uri: { type: "file", value: ruleFilePath, diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts index 802be2e7c..95b5b216b 100644 --- a/core/tools/implementations/fetchUrlContent.ts +++ b/core/tools/implementations/fetchUrlContent.ts @@ -1,14 +1,13 @@ import { ToolImpl } from "."; import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +import { getStringArg } from "../parseArgs"; const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { - if (!args?.url) { - throw new Error("`url` argument is required and cannot be empty"); - } + const url = getStringArg(args, "url"); - const contextItems = await getUrlContextItems(args.url, extras.fetch); + const contextItems = await getUrlContextItems(url, extras.fetch); // Track truncated content const truncatedUrls: string[] = []; @@ -16,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { // Check and truncate each context item const processedItems = contextItems.map((item) => { if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) { - truncatedUrls.push(args.url); + truncatedUrls.push(url); return { ...item, content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT), diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts index 03a061b57..04a105556 100644 --- a/core/tools/implementations/globSearch.ts +++ b/core/tools/implementations/globSearch.ts @@ -1,16 +1,13 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; +import { getStringArg } from "../parseArgs"; const MAX_AGENT_GLOB_RESULTS = 100; export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { - if (!args?.pattern) { - throw new Error( - "`pattern` argument is required for a glob search, and cannot be empty", - ); - } + const pattern = getStringArg(args, "pattern"); const results = await extras.ide.getFileResults( - args.pattern, + pattern, MAX_AGENT_GLOB_RESULTS, ); const contextItems: ContextItem[] = [ diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index d9dd3df20..b75c21891 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,6 +1,7 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; import { formatGrepSearchResults } from "../../util/grepSearch"; +import { getStringArg } from "../parseArgs"; const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now @@ -41,14 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] { } export const grepSearchImpl: ToolImpl = async (args, extras) => { - if (!args?.query) { - throw new Error( - "`query` argument is required for a grep search, and cannot be empty", - ); - } + const query = getStringArg(args, "query"); const results = await extras.ide.getSearchResults( - args.query, + query, DEFAULT_GREP_SEARCH_RESULTS_LIMIT, ); const { formatted, numResults, truncated } = formatGrepSearchResults( @@ -69,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { let contextItems: ContextItem[] = []; - const splitByFile: boolean = args.splitByFile || false; + const splitByFile: boolean = args?.splitByFile || false; if (splitByFile) { contextItems = splitGrepResultsByFile(formatted); } else { diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index 89e9ccbdc..a026d0f47 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -2,34 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getUriPathBasename } from "../../util/uri"; import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; export const readFileImpl: ToolImpl = async (args, extras) => { - if (!args?.filepath) { - throw new Error( - "`filepath` argument is required to read a file, and cannot be empty", - ); - } + const filepath = getStringArg(args, "filepath"); - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - extras.ide, - ); + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); if (!firstUriMatch) { - throw new Error(`Could not find file ${args.filepath}`); + throw new Error(`Could not find file ${filepath}`); } const content = await extras.ide.readFile(firstUriMatch); await throwIfFileExceedsHalfOfContext( - args.filepath, + filepath, content, extras.config.selectedModelByRole.chat, ); return [ { - name: getUriPathBasename(args.filepath), - description: args.filepath, + name: getUriPathBasename(firstUriMatch), + description: filepath, content, uri: { type: "file", diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index f61d6328c..61467e429 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -1,19 +1,14 @@ import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; export const requestRuleImpl: ToolImpl = async (args, extras) => { - if (!args?.name) { - throw new Error( - "`name` argument is required to request a rule, and cannot be empty", - ); - } + const name = getStringArg(args, "name"); // Find the rule by name in the config - const rule = extras.config.rules.find((r) => r.name === args.name); + const rule = extras.config.rules.find((r) => r.name === name); if (!rule || !rule.ruleFile) { - throw new Error( - `Rule with name "${args.name}" not found or has no file path`, - ); + throw new Error(`Rule with name "${name}" not found or has no file path`); } return [ diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index b57a9572d..201d76358 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -24,6 +24,7 @@ import { isProcessBackgrounded, removeBackgroundedProcess, } from "../../util/processTerminalBackgroundStates"; +import { getBooleanArg, getStringArg } from "../parseArgs"; const asyncExec = util.promisify(childProcess.exec); @@ -50,14 +51,11 @@ const ENABLED_FOR_REMOTES = [ ]; export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { - if (!args?.command) { - throw new Error( - "`command` argument is required to run a terminal command, and cannot be empty", - ); - } - + const command = getStringArg(args, "command"); // Default to waiting for completion if not specified - const waitForCompletion = args.waitForCompletion !== false; + const waitForCompletion = + getBooleanArg(args, "waitForCompletion", false) ?? true; + const ideInfo = await extras.ide.getIdeInfo(); const toolCallId = extras.toolCallId || ""; @@ -90,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } // Use spawn with color environment - const childProc = childProcess.spawn(args.command, { + const childProc = childProcess.spawn(command, { cwd, shell: true, env: getColorEnv(), // Add enhanced environment for colors @@ -235,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // Standard execution, waiting for completion try { // Use color environment for exec as well - const output = await asyncExec(args.command, { + const output = await asyncExec(command, { cwd, env: getColorEnv(), }); @@ -264,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // but don't attach any listeners other than error try { // Use spawn with color environment - const childProc = childProcess.spawn(args.command, { + const childProc = childProcess.spawn(command, { cwd, shell: true, env: getColorEnv(), // Add color environment @@ -315,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // For remote environments, just run the command // Note: waitForCompletion is not supported in remote environments yet - await extras.ide.runCommand(args.command); + await extras.ide.runCommand(command); return [ { name: "Terminal", diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts index 4a5d277c3..3d331ebfd 100644 --- a/core/tools/implementations/searchWeb.ts +++ b/core/tools/implementations/searchWeb.ts @@ -1,16 +1,13 @@ import { ToolImpl } from "."; import { fetchSearchResults } from "../../context/providers/WebContextProvider"; +import { getStringArg } from "../parseArgs"; const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; export const searchWebImpl: ToolImpl = async (args, extras) => { - if (!args?.query) { - throw new Error( - "`query` argument is required to search the web, and cannot be empty", - ); - } + const query = getStringArg(args, "query"); - const webResults = await fetchSearchResults(args.query, 5, extras.fetch); + const webResults = await fetchSearchResults(query, 5, extras.fetch); // Track truncated results const truncatedResults: string[] = []; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index bbda7143f..b7897aae8 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -2,14 +2,10 @@ import generateRepoMap from "../../util/generateRepoMap"; import { resolveRelativePathInDir } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { - if (!args?.directory_path) { - throw new Error( - "`directory_path` argument is required to view a map of a subdirectory, and cannot be empty", - ); - } - const { directory_path } = args; + const directory_path = getStringArg(args, "directory_path"); const uri = await resolveRelativePathInDir(directory_path, extras.ide); diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 8ee794eb5..1e7709ddc 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -12,3 +12,52 @@ export function safeParseToolCallArgs( return {}; } } + +export function getStringArg( + args: any, + argName: string, + allowEmpty = false, +): string { + if (!args || !(argName in args) || typeof args[argName] !== "string") { + throw new Error( + `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`, + ); + } + if (!allowEmpty && !args[argName].trim()) { + throw new Error(`Argument ${argName} must not be empty`); + } + return args[argName]; +} + +export function getOptionalStringArg( + args: any, + argName: string, + allowEmpty = false, +) { + if (typeof args?.[argName] === "undefined") { + return undefined; + } + return getStringArg(args, argName, allowEmpty); +} + +export function getBooleanArg(args: any, argName: string, required = false) { + if (!args || !(argName in args)) { + if (required) { + throw new Error(`Argument \`${argName}\` is required (type boolean)`); + } else { + return undefined; + } + } + if (typeof args[argName] === "string") { + if (args[argName].toLowerCase() === "false") { + return false; + } + if (args[argName].toLowerCase() === "true") { + return true; + } + } + if (typeof args[argName] !== "boolean") { + throw new Error(`Argument \`${argName}\` must be a boolean true or false`); + } + return args[argName]; +} diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts new file mode 100644 index 000000000..b501191f0 --- /dev/null +++ b/core/tools/parseArgs.vitest.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from "vitest"; +import { ToolCallDelta } from ".."; +import { + getBooleanArg, + getOptionalStringArg, + getStringArg, + safeParseToolCallArgs, +} from "./parseArgs"; + +describe("safeParseToolCallArgs", () => { + it("should parse valid JSON arguments", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: '{"name": "test", "value": 123}', + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({ name: "test", value: 123 }); + }); + + it("should parse valid JSON arguments with whitespace", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: ' {"name": "test", "value": 123} ', + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({ name: "test", value: 123 }); + }); + + it("should return empty object for invalid JSON", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: '{"name": "test", value: 123', // Invalid JSON + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); + + it("should return empty object when arguments is empty", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: "", + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); + + it("should return empty object when arguments is null or undefined", () => { + const toolCall1: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: null as any, + }, + }; + + const toolCall2: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: undefined, + }, + }; + + expect(safeParseToolCallArgs(toolCall1)).toEqual({}); + expect(safeParseToolCallArgs(toolCall2)).toEqual({}); + }); + + it("should handle case when function is undefined", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: undefined, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); +}); + +describe("getStringArg", () => { + it("should return string argument when valid", () => { + const args = { name: "test" }; + const result = getStringArg(args, "name"); + expect(result).toBe("test"); + }); + + it("should throw error when argument is missing", () => { + const args = { otherArg: "test" }; + expect(() => getStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is not a string", () => { + const args = { name: 123 }; + expect(() => getStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is empty and empty not allowed", () => { + const args = { name: "" }; + expect(() => getStringArg(args, "name")).toThrowError( + "Argument name must not be empty", + ); + + const argsWithSpace = { name: " " }; + expect(() => getStringArg(argsWithSpace, "name")).toThrowError( + "Argument name must not be empty", + ); + }); + + it("should accept empty string when allowEmpty is true", () => { + const args = { name: "" }; + const result = getStringArg(args, "name", true); + expect(result).toBe(""); + + const argsWithSpace = { name: " " }; + const resultWithSpace = getStringArg(argsWithSpace, "name", true); + expect(resultWithSpace).toBe(" "); + }); + + it("should handle null or undefined args", () => { + expect(() => getStringArg(null, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + expect(() => getStringArg(undefined, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); +}); + +describe("getOptionalStringArg", () => { + it("should return undefined when argument is not provided", () => { + const args = { otherArg: "test" }; + const result = getOptionalStringArg(args, "name"); + expect(result).toBeUndefined(); + }); + + it("should return string argument when valid", () => { + const args = { name: "test" }; + const result = getOptionalStringArg(args, "name"); + expect(result).toBe("test"); + }); + + it("should throw error when argument is not a string", () => { + const args = { name: 123 }; + expect(() => getOptionalStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is empty and empty not allowed", () => { + const args = { name: "" }; + expect(() => getOptionalStringArg(args, "name")).toThrowError( + "Argument name must not be empty", + ); + }); + + it("should accept empty string when allowEmpty is true", () => { + const args = { name: "" }; + const result = getOptionalStringArg(args, "name", true); + expect(result).toBe(""); + }); + + it("should handle null or undefined args", () => { + expect(getOptionalStringArg(null, "name")).toBeUndefined(); + expect(getOptionalStringArg(undefined, "name")).toBeUndefined(); + }); +}); + +describe("getBooleanArg", () => { + it("should return boolean argument when valid", () => { + const argsTrue = { flag: true }; + const argsFalse = { flag: false }; + + expect(getBooleanArg(argsTrue, "flag")).toBe(true); + expect(getBooleanArg(argsFalse, "flag")).toBe(false); + }); + + it("should return undefined when argument is not provided and not required", () => { + const args = { otherArg: true }; + const result = getBooleanArg(args, "flag"); + expect(result).toBeUndefined(); + }); + + it("should throw error when argument is not provided and required", () => { + const args = { otherArg: true }; + expect(() => getBooleanArg(args, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + }); + + it('should handle string "true" and "false" values', () => { + const argsStringTrue = { flag: "true" }; + const argsStringFalse = { flag: "false" }; + const argsStringTrueUppercase = { flag: "TRUE" }; + const argsStringFalseUppercase = { flag: "FALSE" }; + + expect(getBooleanArg(argsStringTrue, "flag")).toBe(true); + expect(getBooleanArg(argsStringFalse, "flag")).toBe(false); + expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true); + expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false); + }); + + it("should throw error when argument is not a boolean or valid boolean string", () => { + const argsNumber = { flag: 1 }; + const argsInvalidString = { flag: "yes" }; + const argsObject = { flag: {} }; + + expect(() => getBooleanArg(argsNumber, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + expect(() => getBooleanArg(argsObject, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + }); + + it("should handle null or undefined args", () => { + expect(getBooleanArg(null, "flag")).toBeUndefined(); + expect(getBooleanArg(undefined, "flag")).toBeUndefined(); + + expect(() => getBooleanArg(null, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + expect(() => getBooleanArg(undefined, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + }); +});