|
| 1 | +import fsOperation from "fileSystem"; |
| 2 | +import { StructuredTool } from "@langchain/core/tools"; |
| 3 | +import { addedFolder } from "lib/openFolder"; |
| 4 | +import { z } from "zod"; |
| 5 | + |
| 6 | +/** |
| 7 | + * Tool for creating a new file or editing an existing file in Acode |
| 8 | + */ |
| 9 | +class EditFileTool extends StructuredTool { |
| 10 | + name = "editFile"; |
| 11 | + description = |
| 12 | + "This is a tool for creating a new file or editing an existing file. For moving or renaming files, you should generally use the `terminal` tool with the 'mv' command instead."; |
| 13 | + schema = z.object({ |
| 14 | + path: z |
| 15 | + .string() |
| 16 | + .describe( |
| 17 | + "The relative path of the file to edit or create. This path should never be absolute, and the first component of the path should always be a root directory in a project (opened in sidebar). For example, if root directories are 'directory1' and 'directory2', to edit 'file.txt' in 'directory1', use 'directory1/file.txt'. To edit 'file.txt' in 'directory2', use 'directory2/file.txt'.", |
| 18 | + ), |
| 19 | + mode: z |
| 20 | + .enum(["edit", "create", "overwrite"]) |
| 21 | + .describe( |
| 22 | + "The mode of operation on the file. Possible values: 'edit' - Make granular edits to an existing file (requires oldString and newString), 'create' - Create a new file if it doesn't exist, 'overwrite' - Replace the entire contents of an existing file. When a file already exists, prefer editing it as opposed to recreating it from scratch.", |
| 23 | + ), |
| 24 | + content: z |
| 25 | + .string() |
| 26 | + .optional() |
| 27 | + .describe( |
| 28 | + "The content to write to the file. Required for 'create' and 'overwrite' modes.", |
| 29 | + ), |
| 30 | + oldString: z |
| 31 | + .string() |
| 32 | + .optional() |
| 33 | + .describe( |
| 34 | + "The text to replace (required for 'edit' mode). Must match exactly including whitespace. Can be empty string to insert text at the beginning of newString location.", |
| 35 | + ), |
| 36 | + newString: z |
| 37 | + .string() |
| 38 | + .optional() |
| 39 | + .describe( |
| 40 | + "The replacement text (required for 'edit' mode). Can be empty string to delete the oldString.", |
| 41 | + ), |
| 42 | + replaceAll: z |
| 43 | + .boolean() |
| 44 | + .optional() |
| 45 | + .describe( |
| 46 | + "If true, replace all occurrences of oldString. If false (default), replace only the first occurrence.", |
| 47 | + ), |
| 48 | + }); |
| 49 | + |
| 50 | + /** |
| 51 | + * Check if a URI is a SAF URI |
| 52 | + */ |
| 53 | + isSafUri(uri) { |
| 54 | + return uri.startsWith("content://") && uri.includes("/tree/"); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Check if SAF URI already has the :: separator (complete format) |
| 59 | + */ |
| 60 | + isCompleteSafUri(uri) { |
| 61 | + return this.isSafUri(uri) && uri.includes("::"); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Construct SAF URI for file access |
| 66 | + */ |
| 67 | + constructSafFileUri(baseUri, filePath) { |
| 68 | + // For incomplete SAF URIs (without ::), construct the full format |
| 69 | + // baseUri::primary:fullFilePath |
| 70 | + return `${baseUri}::primary:${filePath}`; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Check if file exists |
| 75 | + */ |
| 76 | + async fileExists(fileUrl) { |
| 77 | + try { |
| 78 | + const stat = await fsOperation(fileUrl).stat(); |
| 79 | + return stat.isFile; |
| 80 | + } catch (error) { |
| 81 | + return false; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + async _call({ |
| 86 | + path, |
| 87 | + mode, |
| 88 | + content, |
| 89 | + oldString, |
| 90 | + newString, |
| 91 | + replaceAll = false, |
| 92 | + }) { |
| 93 | + try { |
| 94 | + // Validate inputs based on mode |
| 95 | + if (mode === "edit") { |
| 96 | + if (oldString === undefined || newString === undefined) { |
| 97 | + return `Error: 'edit' mode requires both 'oldString' and 'newString' parameters.`; |
| 98 | + } |
| 99 | + } else if (mode === "create" || mode === "overwrite") { |
| 100 | + if (content === undefined) { |
| 101 | + return `Error: '${mode}' mode requires 'content' parameter.`; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + // Split the path to get project name and file path |
| 106 | + const pathParts = path.split("/"); |
| 107 | + const projectName = pathParts[0]; |
| 108 | + const filePath = pathParts.slice(1).join("/"); |
| 109 | + |
| 110 | + // Find the project in addedFolder array |
| 111 | + const project = addedFolder.find( |
| 112 | + (folder) => folder.title === projectName, |
| 113 | + ); |
| 114 | + if (!project) { |
| 115 | + return `Error: Project '${projectName}' not found in opened projects`; |
| 116 | + } |
| 117 | + |
| 118 | + let fileUrl; |
| 119 | + |
| 120 | + // Check if this is a SAF URI |
| 121 | + if (this.isSafUri(project.url)) { |
| 122 | + if (this.isCompleteSafUri(project.url)) { |
| 123 | + // SAF URI already has :: separator, just append the file path normally |
| 124 | + // Handle both cases: with trailing slash or without |
| 125 | + const baseUrl = project.url.endsWith("/") |
| 126 | + ? project.url |
| 127 | + : project.url + "/"; |
| 128 | + fileUrl = baseUrl + filePath; |
| 129 | + } else { |
| 130 | + // SAF URI without :: separator, use the special format |
| 131 | + fileUrl = this.constructSafFileUri(project.url, path); |
| 132 | + } |
| 133 | + } else { |
| 134 | + // For regular file URIs, use the normal path concatenation |
| 135 | + fileUrl = project.url + "/" + filePath; |
| 136 | + } |
| 137 | + |
| 138 | + // Check if file exists |
| 139 | + const exists = await this.fileExists(fileUrl); |
| 140 | + |
| 141 | + // Handle different modes |
| 142 | + switch (mode) { |
| 143 | + case "create": |
| 144 | + if (exists) { |
| 145 | + return `Error: File '${path}' already exists. Use 'edit' or 'overwrite' mode instead.`; |
| 146 | + } |
| 147 | + // For creating files, we need to use createFile method |
| 148 | + // Extract directory URL and filename |
| 149 | + const fileName = filePath.split("/").pop(); |
| 150 | + const dirPath = pathParts.slice(1, -1).join("/"); |
| 151 | + |
| 152 | + let dirUrl; |
| 153 | + if (this.isSafUri(project.url)) { |
| 154 | + if (this.isCompleteSafUri(project.url)) { |
| 155 | + const baseUrl = project.url.endsWith("/") |
| 156 | + ? project.url |
| 157 | + : project.url + "/"; |
| 158 | + dirUrl = dirPath ? baseUrl + dirPath : project.url; |
| 159 | + } else { |
| 160 | + dirUrl = dirPath |
| 161 | + ? this.constructSafFileUri( |
| 162 | + project.url, |
| 163 | + projectName + "/" + dirPath, |
| 164 | + ) |
| 165 | + : project.url; |
| 166 | + } |
| 167 | + } else { |
| 168 | + dirUrl = dirPath ? project.url + "/" + dirPath : project.url; |
| 169 | + } |
| 170 | + |
| 171 | + await fsOperation(dirUrl).createFile(fileName, content); |
| 172 | + return `File '${path}' has been successfully created.`; |
| 173 | + |
| 174 | + case "overwrite": |
| 175 | + if (!exists) { |
| 176 | + return `Error: File '${path}' does not exist. Use 'create' mode instead.`; |
| 177 | + } |
| 178 | + await fsOperation(fileUrl).writeFile(content); |
| 179 | + return `File '${path}' has been successfully overwritten.`; |
| 180 | + |
| 181 | + case "edit": |
| 182 | + if (!exists) { |
| 183 | + return `Error: File '${path}' does not exist. Use 'create' mode instead.`; |
| 184 | + } |
| 185 | + |
| 186 | + // Read current content |
| 187 | + const currentContent = await fsOperation(fileUrl).readFile("utf8"); |
| 188 | + |
| 189 | + // Handle empty oldString (insertion at beginning of file) |
| 190 | + if (oldString === "") { |
| 191 | + const updatedContent = newString + currentContent; |
| 192 | + await fsOperation(fileUrl).writeFile(updatedContent); |
| 193 | + return `File '${path}' has been successfully edited. Inserted text at beginning of file.`; |
| 194 | + } |
| 195 | + |
| 196 | + // Check if oldString exists in the file |
| 197 | + if (!currentContent.includes(oldString)) { |
| 198 | + // Provide more helpful error message |
| 199 | + const lines = currentContent.split("\n"); |
| 200 | + const preview = |
| 201 | + lines.length > 5 |
| 202 | + ? `First 5 lines:\n${lines |
| 203 | + .slice(0, 5) |
| 204 | + .map((line, i) => `${i + 1}: ${line}`) |
| 205 | + .join("\n")}` |
| 206 | + : `File content:\n${lines.map((line, i) => `${i + 1}: ${line}`).join("\n")}`; |
| 207 | + return `Error: The text to replace was not found in '${path}'.\n\nSearching for:\n${JSON.stringify(oldString)}\n\n${preview}`; |
| 208 | + } |
| 209 | + |
| 210 | + // Count occurrences for reporting |
| 211 | + const occurrenceCount = ( |
| 212 | + currentContent.match( |
| 213 | + new RegExp(oldString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), |
| 214 | + ) || [] |
| 215 | + ).length; |
| 216 | + |
| 217 | + // Perform the replacement |
| 218 | + let updatedContent; |
| 219 | + if (replaceAll) { |
| 220 | + // Replace all occurrences using replaceAll method |
| 221 | + updatedContent = currentContent.replaceAll(oldString, newString); |
| 222 | + } else { |
| 223 | + // Replace only first occurrence |
| 224 | + updatedContent = currentContent.replace(oldString, newString); |
| 225 | + } |
| 226 | + |
| 227 | + // Check if replacement actually changed the content |
| 228 | + if (updatedContent === currentContent) { |
| 229 | + return `Warning: No changes were made to '${path}'. The 'oldString' and 'newString' are identical.`; |
| 230 | + } |
| 231 | + |
| 232 | + // Write the updated content |
| 233 | + await fsOperation(fileUrl).writeFile(updatedContent); |
| 234 | + |
| 235 | + const replacedCount = replaceAll ? occurrenceCount : 1; |
| 236 | + const message = replaceAll |
| 237 | + ? `File '${path}' has been successfully edited. Replaced ${replacedCount} occurrence(s) of the text.` |
| 238 | + : `File '${path}' has been successfully edited. Replaced first occurrence of the text (${occurrenceCount} total found).`; |
| 239 | + |
| 240 | + return message; |
| 241 | + |
| 242 | + default: |
| 243 | + return `Error: Invalid mode '${mode}'. Use 'create', 'edit', or 'overwrite'.`; |
| 244 | + } |
| 245 | + } catch (error) { |
| 246 | + return `Error processing file: ${error.message}`; |
| 247 | + } |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +export const editFile = new EditFileTool(); |
0 commit comments