| 1 | import { resolveRelativePathInDir } from "../../util/ideUtils"; |
| 2 | import { getUriPathBasename } from "../../util/uri"; |
| 3 | |
| 4 | import { ToolImpl } from "."; |
| 5 | import { getNumberArg, getStringArg } from "../parseArgs"; |
| 6 | import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; |
| 7 | |
| 8 | export const readFileRangeImpl: ToolImpl = async (args, extras) => { |
| 9 | const filepath = getStringArg(args, "filepath"); |
| 10 | const startLine = getNumberArg(args, "startLine"); |
| 11 | const endLine = getNumberArg(args, "endLine"); |
| 12 | |
| 13 | // Validate that line numbers are positive integers |
| 14 | if (startLine < 1) { |
| 15 | throw new Error( |
| 16 | "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", |
| 17 | ); |
| 18 | } |
| 19 | if (endLine < 1) { |
| 20 | throw new Error( |
| 21 | "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", |
| 22 | ); |
| 23 | } |
| 24 | if (endLine < startLine) { |
| 25 | throw new Error( |
| 26 | `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, |
| 27 | ); |
| 28 | } |
| 29 | |
| 30 | const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); |
| 31 | if (!firstUriMatch) { |
| 32 | throw new Error( |
| 33 | `File "${filepath}" does not exist. You might want to check the path and try again.`, |
| 34 | ); |
| 35 | } |
| 36 | |
| 37 | // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) |
| 38 | const content = await extras.ide.readRangeInFile(firstUriMatch, { |
| 39 | start: { |
| 40 | line: startLine - 1, // Convert from 1-based to 0-based |
| 41 | character: 0, |
| 42 | }, |
| 43 | end: { |
| 44 | line: endLine - 1, // Convert from 1-based to 0-based |
| 45 | character: Number.MAX_SAFE_INTEGER, // Read to end of line |
| 46 | }, |
| 47 | }); |
| 48 | |
| 49 | await throwIfFileExceedsHalfOfContext( |
| 50 | filepath, |
| 51 | content, |
| 52 | extras.config.selectedModelByRole.chat, |
| 53 | ); |
| 54 | |
| 55 | const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; |
| 56 | |
| 57 | return [ |
| 58 | { |
| 59 | name: getUriPathBasename(firstUriMatch), |
| 60 | description: rangeDescription, |
| 61 | content, |
| 62 | uri: { |
| 63 | type: "file", |
| 64 | value: firstUriMatch, |
| 65 | }, |
| 66 | }, |
| 67 | ]; |
| 68 | }; |