| 1 | import * as fs from "fs"; |
| 2 | import * as path from "path"; |
| 3 | |
| 4 | import { formatToolArgument } from "./formatters.js"; |
| 5 | import { Tool } from "./types.js"; |
| 6 | |
| 7 | // List files in a directory |
| 8 | export const listFilesTool: Tool = { |
| 9 | name: "List", |
| 10 | displayName: "List", |
| 11 | description: "List files in a directory", |
| 12 | parameters: { |
| 13 | type: "object", |
| 14 | required: ["dirpath"], |
| 15 | properties: { |
| 16 | dirpath: { |
| 17 | type: "string", |
| 18 | description: "The path to the directory to list", |
| 19 | }, |
| 20 | }, |
| 21 | }, |
| 22 | readonly: true, |
| 23 | isBuiltIn: true, |
| 24 | preprocess: async (args) => { |
| 25 | return { |
| 26 | args, |
| 27 | preview: [ |
| 28 | { |
| 29 | type: "text", |
| 30 | content: args.dirpath |
| 31 | ? `Will list files in: ${formatToolArgument(args.dirpath)}` |
| 32 | : "Will list files in current directory", |
| 33 | }, |
| 34 | ], |
| 35 | }; |
| 36 | }, |
| 37 | run: async (args: { dirpath: string }): Promise<string> => { |
| 38 | try { |
| 39 | if (!fs.existsSync(args.dirpath)) { |
| 40 | return `Error: Directory does not exist: ${args.dirpath}`; |
| 41 | } |
| 42 | |
| 43 | if (!fs.statSync(args.dirpath).isDirectory()) { |
| 44 | return `Error: Path is not a directory: ${args.dirpath}`; |
| 45 | } |
| 46 | |
| 47 | const files = fs.readdirSync(args.dirpath); |
| 48 | const fileDetails = files.map((file) => { |
| 49 | const fullPath = path.join(args.dirpath, file); |
| 50 | const stats = fs.statSync(fullPath); |
| 51 | const type = stats.isDirectory() ? "directory" : "file"; |
| 52 | const size = stats.isFile() ? `${stats.size} bytes` : ""; |
| 53 | return `${file} (${type}${size ? `, ${size}` : ""})`; |
| 54 | }); |
| 55 | |
| 56 | return `Files in ${args.dirpath}:\n${fileDetails.join("\n")}`; |
| 57 | } catch (error) { |
| 58 | return `Error listing files: ${ |
| 59 | error instanceof Error ? error.message : String(error) |
| 60 | }`; |
| 61 | } |
| 62 | }, |
| 63 | }; |