feat: ✨ Add range and head tools for file operations
This commit is contained in:
parent
6e2e18787c
commit
820822196b
14 changed files with 725 additions and 1 deletions
|
|
@ -1,5 +1,7 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "read_file",
|
||||
ReadFileRange = "read_file_range",
|
||||
ReadFileHead = "read_file_head",
|
||||
EditExistingFile = "edit_existing_file",
|
||||
SearchAndReplaceInFile = "search_and_replace_in_file",
|
||||
SingleFindAndReplace = "single_find_and_replace",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ import { grepSearchImpl } from "./implementations/grepSearch";
|
|||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
import { readFileHeadImpl } from "./implementations/readFileHead";
|
||||
import { readFileRangeImpl } from "./implementations/readFileRange";
|
||||
import { requestRuleImpl } from "./implementations/requestRule";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
|
|
@ -145,6 +147,10 @@ export async function callBuiltInTool(
|
|||
switch (functionName) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
case BuiltInToolNames.ReadFileRange:
|
||||
return await readFileRangeImpl(args, extras);
|
||||
case BuiltInToolNames.ReadFileHead:
|
||||
return await readFileHeadImpl(args, extras);
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ export { lsTool } from "./ls";
|
|||
export { multiEditTool } from "./multiEdit";
|
||||
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
|
||||
export { readFileTool } from "./readFile";
|
||||
export { readFileHeadTool } from "./readFileHead";
|
||||
export { readFileRangeTool } from "./readFileRange";
|
||||
export { requestRuleTool } from "./requestRule";
|
||||
export { runTerminalCommandTool } from "./runTerminalCommand";
|
||||
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
|
||||
|
|
@ -17,3 +19,4 @@ export { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
|||
export { viewDiffTool } from "./viewDiff";
|
||||
export { viewRepoMapTool } from "./viewRepoMap";
|
||||
export { viewSubdirectoryTool } from "./viewSubdirectory";
|
||||
|
||||
|
|
|
|||
42
core/tools/definitions/readFileHead.ts
Normal file
42
core/tools/definitions/readFileHead.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readFileHeadTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read File Head",
|
||||
wouldLikeTo: "read the first {{{ lines }}} lines of {{{ filepath }}}",
|
||||
isCurrently: "reading the first {{{ lines }}} lines of {{{ filepath }}}",
|
||||
hasAlready: "viewed the first {{{ lines }}} lines of {{{ filepath }}}",
|
||||
readonly: true,
|
||||
isInstant: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadFileHead,
|
||||
description:
|
||||
"Use this tool to read the first N lines from the beginning of a file. Similar to the Unix 'head' command.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "lines"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
|
||||
},
|
||||
lines: {
|
||||
type: "number",
|
||||
description:
|
||||
"The number of lines to read from the beginning of the file (must be positive)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To read the first N lines of a file, use the ${BuiltInToolNames.ReadFileHead} tool. For example, to read the first 20 lines of a file:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/the_file.txt"],
|
||||
["lines", "20"],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
};
|
||||
48
core/tools/definitions/readFileRange.ts
Normal file
48
core/tools/definitions/readFileRange.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readFileRangeTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read File Range",
|
||||
wouldLikeTo: "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
isCurrently: "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
hasAlready: "viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
readonly: true,
|
||||
isInstant: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadFileRange,
|
||||
description:
|
||||
"Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "startLine", "endLine"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
|
||||
},
|
||||
startLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line",
|
||||
},
|
||||
endLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/the_file.txt"],
|
||||
["startLine", 10],
|
||||
["endLine", 20],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
};
|
||||
113
core/tools/implementations/readFileHead.integration.vitest.ts
Normal file
113
core/tools/implementations/readFileHead.integration.vitest.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { expect, test, vi } from "vitest";
|
||||
import { ToolExtras } from "../..";
|
||||
import { readFileHeadImpl } from "./readFileHead";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../../util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../util/uri", () => ({
|
||||
getUriPathBasename: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./readFileLimit", () => ({
|
||||
throwIfFileExceedsHalfOfContext: vi.fn(),
|
||||
}));
|
||||
|
||||
test("readFileHeadImpl reads first N lines correctly", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
const expectedContent = "line1\nline2\nline3";
|
||||
const mockIde = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue(expectedContent),
|
||||
};
|
||||
|
||||
const mockExtras = {
|
||||
ide: mockIde,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result = await readFileHeadImpl(
|
||||
{
|
||||
filepath: "src/test.py",
|
||||
lines: 3,
|
||||
},
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
name: "test.txt",
|
||||
description: "src/test.py (first 3 lines)",
|
||||
content: expectedContent,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "file:///test.txt",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify readRangeInFile was called with correct 0-based range
|
||||
expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 0, character: 0 }, // First line (0-based)
|
||||
end: { line: 2, character: Number.MAX_SAFE_INTEGER }, // 3rd line (0-based)
|
||||
});
|
||||
});
|
||||
|
||||
test("readFileHeadImpl validates lines parameter", async () => {
|
||||
const mockExtras = {
|
||||
ide: { readRangeInFile: vi.fn() },
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
// Test lines < 1
|
||||
await expect(
|
||||
readFileHeadImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
lines: 0,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("lines must be 1 or greater");
|
||||
|
||||
await expect(
|
||||
readFileHeadImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
lines: -5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("lines must be 1 or greater");
|
||||
});
|
||||
|
||||
|
||||
|
||||
test("readFileHead handles file not found errors", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue(undefined);
|
||||
|
||||
const mockExtras = {
|
||||
ide: { readFile: vi.fn(), readRangeInFile: vi.fn() },
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
// Test readFileHead with non-existent file
|
||||
await expect(
|
||||
readFileHeadImpl(
|
||||
{
|
||||
filepath: "nonexistent.txt",
|
||||
lines: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow('File "nonexistent.txt" does not exist');
|
||||
});
|
||||
53
core/tools/implementations/readFileHead.ts
Normal file
53
core/tools/implementations/readFileHead.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getNumberArg, getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileHeadImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const lines = getNumberArg(args, "lines");
|
||||
|
||||
if (lines < 1) {
|
||||
throw new Error("lines must be 1 or greater");
|
||||
}
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(
|
||||
`File "${filepath}" does not exist. You might want to check the path and try again.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Use the IDE's readRangeInFile method to read first N lines
|
||||
// Lines 1 to N (converted to 0-based: 0 to N-1)
|
||||
const content = await extras.ide.readRangeInFile(firstUriMatch, {
|
||||
start: {
|
||||
line: 0, // First line (0-based)
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: lines - 1, // Nth line (0-based)
|
||||
character: Number.MAX_SAFE_INTEGER, // Read to end of line
|
||||
},
|
||||
});
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: `${filepath} (first ${lines} lines)`,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: firstUriMatch,
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
33
core/tools/implementations/readFileHead.vitest.ts
Normal file
33
core/tools/implementations/readFileHead.vitest.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { test, expect, vi } from "vitest";
|
||||
import { getNumberArg } from "../parseArgs";
|
||||
|
||||
test("readFileHead validates input arguments", () => {
|
||||
// Test valid positive numbers
|
||||
expect(() => getNumberArg({ lines: 1 }, "lines")).not.toThrow();
|
||||
expect(() => getNumberArg({ lines: 10 }, "lines")).not.toThrow();
|
||||
expect(() => getNumberArg({ lines: "5" }, "lines")).not.toThrow();
|
||||
|
||||
// Test missing arguments
|
||||
expect(() => getNumberArg({}, "lines")).toThrow(
|
||||
"Argument `lines` is required (type number)"
|
||||
);
|
||||
|
||||
// Test invalid arguments
|
||||
expect(() => getNumberArg({ lines: "not-a-number" }, "lines")).toThrow(
|
||||
"Argument `lines` must be a valid number"
|
||||
);
|
||||
expect(() => getNumberArg({ lines: true }, "lines")).toThrow(
|
||||
"Argument `lines` must be a valid number"
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileHead handles line number conversion correctly", () => {
|
||||
// Test that parsing works for various inputs
|
||||
expect(getNumberArg({ lines: 1 }, "lines")).toBe(1);
|
||||
expect(getNumberArg({ lines: "10" }, "lines")).toBe(10);
|
||||
expect(getNumberArg({ lines: 5.7 }, "lines")).toBe(5); // Should floor
|
||||
expect(getNumberArg({ lines: "3.9" }, "lines")).toBe(3); // Should floor
|
||||
|
||||
// Test that negative numbers are parsed (validation happens in implementation)
|
||||
expect(getNumberArg({ lines: -5 }, "lines")).toBe(-5);
|
||||
});
|
||||
198
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
198
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import { expect, test, vi } from "vitest";
|
||||
import { ToolExtras } from "../..";
|
||||
import { readFileRangeImpl } from "./readFileRange";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../../util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../util/uri", () => ({
|
||||
getUriPathBasename: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./readFileLimit", () => ({
|
||||
throwIfFileExceedsHalfOfContext: vi.fn(),
|
||||
}));
|
||||
|
||||
test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
// Mock the utility functions
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
// Test case 1: Start line beyond end of file
|
||||
const mockIdeOutOfBounds = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string
|
||||
};
|
||||
|
||||
const mockExtras1 = {
|
||||
ide: mockIdeOutOfBounds,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result1 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 100, // Beyond end of file
|
||||
endLine: 105,
|
||||
},
|
||||
mockExtras1,
|
||||
);
|
||||
|
||||
expect(result1).toHaveLength(1);
|
||||
expect(result1[0].content).toBe("");
|
||||
expect(result1[0].description).toBe("test.txt (lines 100-105)");
|
||||
|
||||
// Test case 2: End line beyond end of file
|
||||
const mockIdePartialRange = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content
|
||||
};
|
||||
|
||||
const mockExtras2 = {
|
||||
ide: mockIdePartialRange,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result2 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 5,
|
||||
endLine: 100, // Beyond end of file
|
||||
},
|
||||
mockExtras2,
|
||||
);
|
||||
|
||||
expect(result2).toHaveLength(1);
|
||||
expect(result2[0].content).toBe("line5\nline6");
|
||||
expect(result2[0].description).toBe("test.txt (lines 5-100)");
|
||||
|
||||
// Verify that IDE methods were called with correct 0-based ranges
|
||||
expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 99, character: 0 }, // 100 - 1
|
||||
end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1
|
||||
});
|
||||
|
||||
expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 4, character: 0 }, // 5 - 1
|
||||
end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1
|
||||
});
|
||||
});
|
||||
|
||||
test("readFileRangeImpl validates line number constraints", async () => {
|
||||
const mockExtras = {
|
||||
ide: { readRangeInFile: vi.fn(), readFile: vi.fn() },
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
// Test startLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 0,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("startLine must be 1 or greater");
|
||||
|
||||
// Test negative startLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: -1,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: 0,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("endLine must be 1 or greater");
|
||||
|
||||
// Test negative endLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: -1,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < startLine
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 10,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("endLine (5) must be greater than or equal to startLine (10)");
|
||||
});
|
||||
|
||||
test("readFileRangeImpl handles normal ranges correctly", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
const mockIde = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"),
|
||||
};
|
||||
|
||||
const mockExtras = {
|
||||
ide: mockIde,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "src/test.py",
|
||||
startLine: 2,
|
||||
endLine: 4,
|
||||
},
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
name: "test.txt",
|
||||
description: "src/test.py (lines 2-4)",
|
||||
content: "line2\nline3\nline4",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "file:///test.txt",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify correct 0-based conversion
|
||||
expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 1, character: 0 }, // 2 - 1
|
||||
end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
62
core/tools/implementations/readFileRange.ts
Normal file
62
core/tools/implementations/readFileRange.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getNumberArg, getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileRangeImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const startLine = getNumberArg(args, "startLine");
|
||||
const endLine = getNumberArg(args, "endLine");
|
||||
|
||||
// Validate that line numbers are positive integers
|
||||
if (startLine < 1) {
|
||||
throw new Error("startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.");
|
||||
}
|
||||
if (endLine < 1) {
|
||||
throw new Error("endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.");
|
||||
}
|
||||
if (endLine < startLine) {
|
||||
throw new Error(`endLine (${endLine}) must be greater than or equal to startLine (${startLine})`);
|
||||
}
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(
|
||||
`File "${filepath}" does not exist. You might want to check the path and try again.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally)
|
||||
const content = await extras.ide.readRangeInFile(firstUriMatch, {
|
||||
start: {
|
||||
line: startLine - 1, // Convert from 1-based to 0-based
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: endLine - 1, // Convert from 1-based to 0-based
|
||||
character: Number.MAX_SAFE_INTEGER, // Read to end of line
|
||||
},
|
||||
});
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`;
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: rangeDescription,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: firstUriMatch,
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { getNumberArg } from "../parseArgs";
|
||||
|
||||
test("readFileRange should validate positive line number arguments", () => {
|
||||
// Test positive startLine validation
|
||||
expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow();
|
||||
|
||||
// Test positive endLine validation
|
||||
expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow();
|
||||
|
||||
// Test missing arguments
|
||||
expect(() => getNumberArg({}, "startLine")).toThrow(
|
||||
"Argument `startLine` is required (type number)"
|
||||
);
|
||||
expect(() => getNumberArg({}, "endLine")).toThrow(
|
||||
"Argument `endLine` is required (type number)"
|
||||
);
|
||||
|
||||
// Test invalid arguments
|
||||
expect(() => getNumberArg({ startLine: "not-a-number" }, "startLine")).toThrow(
|
||||
"Argument `startLine` must be a valid number"
|
||||
);
|
||||
expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow(
|
||||
"Argument `endLine` must be a valid number"
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRange should handle line number conversion", () => {
|
||||
// Test that our parsing function converts correctly
|
||||
expect(getNumberArg({ line: 1 }, "line")).toBe(1);
|
||||
expect(getNumberArg({ line: "5" }, "line")).toBe(5);
|
||||
expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor
|
||||
expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor
|
||||
});
|
||||
|
||||
test("readFileRange parses negative numbers (validation happens in implementation)", () => {
|
||||
// The parseArgs function should parse negative numbers correctly
|
||||
// but the implementation will reject them with helpful error messages
|
||||
expect(getNumberArg({ line: -1 }, "line")).toBe(-1);
|
||||
expect(getNumberArg({ line: -10 }, "line")).toBe(-10);
|
||||
expect(getNumberArg({ line: "-5" }, "line")).toBe(-5);
|
||||
});
|
||||
|
||||
test("readFileRange handles out-of-bounds ranges gracefully", () => {
|
||||
// IDE implementations handle out-of-bounds gracefully:
|
||||
// - VS Code: Uses array.slice() which handles out-of-bounds gracefully
|
||||
// - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds
|
||||
// Both return empty content or available content without throwing errors
|
||||
|
||||
expect(() => {
|
||||
const startLine = getNumberArg({ startLine: 1000 }, "startLine");
|
||||
const endLine = getNumberArg({ endLine: 2000 }, "endLine");
|
||||
expect(startLine).toBe(1000);
|
||||
expect(endLine).toBe(2000);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
|
@ -4,6 +4,8 @@ import * as toolDefinitions from "./definitions";
|
|||
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
|
||||
export const getBaseToolDefinitions = () => [
|
||||
toolDefinitions.readFileTool,
|
||||
toolDefinitions.readFileRangeTool,
|
||||
toolDefinitions.readFileHeadTool,
|
||||
toolDefinitions.createNewFileTool,
|
||||
toolDefinitions.runTerminalCommandTool,
|
||||
toolDefinitions.globSearchTool,
|
||||
|
|
|
|||
|
|
@ -40,6 +40,24 @@ export function getOptionalStringArg(
|
|||
return getStringArg(args, argName, allowEmpty);
|
||||
}
|
||||
|
||||
export function getNumberArg(args: any, argName: string): number {
|
||||
if (!args || !(argName in args)) {
|
||||
throw new Error(`Argument \`${argName}\` is required (type number)`);
|
||||
}
|
||||
const value = args[argName];
|
||||
if (typeof value === "string") {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
if (typeof value !== "number" || isNaN(value)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return Math.floor(value); // Ensure integer for line numbers (supports negative numbers)
|
||||
}
|
||||
|
||||
export function getBooleanArg(args: any, argName: string, required = false) {
|
||||
if (!args || !(argName in args)) {
|
||||
if (required) {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ import { describe, expect, it } from "vitest";
|
|||
import { ToolCallDelta } from "..";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getNumberArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
safeParseToolCallArgs,
|
||||
safeParseToolCallArgs
|
||||
} from "./parseArgs";
|
||||
|
||||
describe("safeParseToolCallArgs", () => {
|
||||
|
|
@ -246,3 +247,86 @@ describe("getBooleanArg", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getNumberArg", () => {
|
||||
it("should return number argument when valid", () => {
|
||||
const args = { count: 42 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse string numbers", () => {
|
||||
const args = { count: "42" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should floor decimal numbers", () => {
|
||||
const args = { count: 42.7 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse and floor string decimal numbers", () => {
|
||||
const args = { count: "42.7" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: 42 };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a number", () => {
|
||||
const argsString = { count: "not-a-number" };
|
||||
const argsBoolean = { count: true };
|
||||
const argsObject = { count: {} };
|
||||
|
||||
expect(() => getNumberArg(argsString, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsBoolean, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsObject, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is NaN", () => {
|
||||
const args = { count: NaN };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle negative numbers", () => {
|
||||
const args = { count: -5 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-5);
|
||||
});
|
||||
|
||||
it("should handle negative string numbers", () => {
|
||||
const args = { count: "-10" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-10);
|
||||
});
|
||||
|
||||
it("should handle zero", () => {
|
||||
const args = { count: 0 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(0);
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getNumberArg(null, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
expect(() => getNumberArg(undefined, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue