feat: more thorough tool arg checking utils with tests

This commit is contained in:
Dallin Romney 2025-07-21 15:31:52 +02:00
parent ae29787bd2
commit 1ee5c54151
13 changed files with 365 additions and 90 deletions

View file

@ -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

View file

@ -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) {

View file

@ -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<RuleWithSource>,
@ -9,16 +14,21 @@ export type CreateRuleBlockArgs = Pick<
> &
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
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,

View file

@ -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),

View file

@ -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[] = [

View file

@ -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 {

View file

@ -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",

View file

@ -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 [

View file

@ -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",

View file

@ -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[] = [];

View file

@ -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);

View file

@ -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];
}

View file

@ -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)",
);
});
});