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