Merge pull request #7161 from chezsmithy/feat-range-and-head-tools

feat: ✨ Add experimental range tool for file operations
This commit is contained in:
Dallin Romney 2025-09-03 11:30:33 -07:00 • committed by GitHub
commit 3eff9ffaba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 494 additions and 0 deletions

View file

@ -1,5 +1,6 @@
export enum BuiltInToolNames {
ReadFile = "read_file",
ReadFileRange = "read_file_range",
EditExistingFile = "edit_existing_file",
SingleFindAndReplace = "single_find_and_replace",
MultiEdit = "multi_edit",

View file

@ -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 { readFileRangeImpl } from "./implementations/readFileRange";
import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
@ -145,6 +147,8 @@ export async function callBuiltInTool(
switch (functionName) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
case BuiltInToolNames.ReadFileRange:
return await readFileRangeImpl(args, extras);
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.GrepSearch:

View file

@ -9,6 +9,8 @@ export { lsTool } from "./ls";
export { multiEditTool } from "./multiEdit";
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
export { readFileTool } from "./readFile";
export { readFileRangeTool } from "./readFileRange";
export { requestRuleTool } from "./requestRule";
export { runTerminalCommandTool } from "./runTerminalCommand";
export { searchWebTool } from "./searchWeb";

View file

@ -0,0 +1,51 @@
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",
};

View file

@ -0,0 +1,204 @@
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
});
});

View file

@ -0,0 +1,68 @@
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,
},
},
];
};

View 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();
});

View file

@ -4,6 +4,7 @@ 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.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
@ -33,6 +34,7 @@ export const getConfigDependentToolDefinitions = (
toolDefinitions.viewRepoMapTool,
toolDefinitions.viewSubdirectoryTool,
toolDefinitions.codebaseTool,
toolDefinitions.readFileRangeTool,
);
}

View file

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

View file

@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { ToolCallDelta } from "..";
import {
getBooleanArg,
getNumberArg,
getOptionalStringArg,
getStringArg,
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)",
);
});
});