| 1 | import * as fs from "fs"; |
| 2 | |
| 3 | import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; |
| 4 | |
| 5 | import { formatToolArgument } from "./formatters.js"; |
| 6 | import { Tool } from "./types.js"; |
| 7 | |
| 8 | // Track files that have been read in the current session |
| 9 | export const readFilesSet = new Set<string>(); |
| 10 | export function markFileAsRead(filePath: string) { |
| 11 | readFilesSet.add(filePath); |
| 12 | } |
| 13 | |
| 14 | export const readFileTool: Tool = { |
| 15 | name: "Read", |
| 16 | displayName: "Read", |
| 17 | description: "Read the contents of a file at the specified path", |
| 18 | parameters: { |
| 19 | type: "object", |
| 20 | required: ["filepath"], |
| 21 | properties: { |
| 22 | filepath: { |
| 23 | type: "string", |
| 24 | description: "The path to the file to read", |
| 25 | }, |
| 26 | }, |
| 27 | }, |
| 28 | readonly: true, |
| 29 | isBuiltIn: true, |
| 30 | preprocess: async (args) => { |
| 31 | let { filepath } = args; |
| 32 | if (filepath.startsWith("./")) { |
| 33 | filepath = filepath.slice(2); |
| 34 | } |
| 35 | throwIfFileIsSecurityConcern(filepath); |
| 36 | return { |
| 37 | args, |
| 38 | preview: [ |
| 39 | { |
| 40 | type: "text", |
| 41 | content: `Will read ${formatToolArgument(filepath)}`, |
| 42 | }, |
| 43 | ], |
| 44 | }; |
| 45 | }, |
| 46 | run: async (args: { filepath: string }): Promise<string> => { |
| 47 | try { |
| 48 | let { filepath } = args; |
| 49 | if (filepath.startsWith("./")) { |
| 50 | filepath = filepath.slice(2); |
| 51 | } |
| 52 | |
| 53 | if (!fs.existsSync(filepath)) { |
| 54 | return `Error: File does not exist: ${filepath}`; |
| 55 | } |
| 56 | const realPath = fs.realpathSync(filepath); |
| 57 | const content = fs.readFileSync(realPath, "utf-8"); |
| 58 | // Mark this file as read for the edit tool |
| 59 | markFileAsRead(realPath); |
| 60 | |
| 61 | const lines = content.split("\n"); |
| 62 | if (lines.length > 5000) { |
| 63 | const truncatedContent = lines.slice(0, 5000).join("\n"); |
| 64 | return `Content of ${filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`; |
| 65 | } |
| 66 | |
| 67 | return `Content of ${filepath}:\n${content}`; |
| 68 | } catch (error) { |
| 69 | return `Error reading file: ${ |
| 70 | error instanceof Error ? error.message : String(error) |
| 71 | }`; |
| 72 | } |
| 73 | }, |
| 74 | }; |