| 1 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 2 | import { v4 as uuid } from "uuid"; |
| 3 | import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; |
| 4 | import { ClientToolImpl } from "./callClientTool"; |
| 5 | export const editToolImpl: ClientToolImpl = async ( |
| 6 | args, |
| 7 | toolCallId, |
| 8 | extras, |
| 9 | ) => { |
| 10 | if (!args.filepath || !args.changes) { |
| 11 | throw new Error( |
| 12 | "`filepath` and `changes` arguments are required to edit an existing file.", |
| 13 | ); |
| 14 | } |
| 15 | let filepath = args.filepath; |
| 16 | if (filepath.startsWith("./")) { |
| 17 | filepath = filepath.slice(2); |
| 18 | } |
| 19 | |
| 20 | const openFiles = await extras.ideMessenger.ide.getOpenFiles(); |
| 21 | let firstUriMatch = await resolveRelativePathInDir( |
| 22 | filepath, |
| 23 | extras.ideMessenger.ide, |
| 24 | ); |
| 25 | |
| 26 | if (!firstUriMatch) { |
| 27 | for (const uri of openFiles) { |
| 28 | if (uri.endsWith(filepath)) { |
| 29 | firstUriMatch = uri; |
| 30 | break; |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | if (!firstUriMatch) { |
| 36 | throw new Error(`${filepath} does not exist`); |
| 37 | } |
| 38 | const streamId = uuid(); |
| 39 | void extras.dispatch( |
| 40 | applyForEditTool({ |
| 41 | streamId, |
| 42 | text: args.changes, |
| 43 | toolCallId, |
| 44 | filepath: firstUriMatch, |
| 45 | }), |
| 46 | ); |
| 47 | |
| 48 | return { |
| 49 | respondImmediately: true, |
| 50 | output: [ |
| 51 | { |
| 52 | name: "File edited successfully", |
| 53 | content: `Successfully initiated edit for ${firstUriMatch}`, |
| 54 | description: "File edit operation started", |
| 55 | }, |
| 56 | ], |
| 57 | }; |
| 58 | }; |