|
| 1 | +import * as path from "path" |
| 2 | +import * as fs from "fs/promises" |
| 3 | +import { Cline } from "../Cline" |
| 4 | +import { ClineSayTool } from "../../shared/ExtensionMessage" |
| 5 | +import { ToolUse } from "../assistant-message" |
| 6 | +import { formatResponse } from "../prompts/responses" |
| 7 | +import { AskApproval, HandleError, PushToolResult, RemoveClosingTag } from "./types" |
| 8 | +import { getReadablePath } from "../../utils/path" |
| 9 | +import { fileExistsAtPath } from "../../utils/fs" |
| 10 | +import { insertGroups } from "../diff/insert-groups" |
| 11 | +import delay from "delay" |
| 12 | +import { DiffViewProvider } from "../../integrations/editor/DiffViewProvider" |
| 13 | + |
| 14 | +/** |
| 15 | + * Implements the insert_content tool. |
| 16 | + * |
| 17 | + * @param cline - The instance of Cline that is executing this tool. |
| 18 | + * @param block - The block of assistant message content that specifies the |
| 19 | + * parameters for this tool. |
| 20 | + * @param askApproval - A function that asks the user for approval to show a |
| 21 | + * message. |
| 22 | + * @param handleError - A function that handles an error that occurred while |
| 23 | + * executing this tool. |
| 24 | + * @param pushToolResult - A function that pushes the result of this tool to the |
| 25 | + * conversation. |
| 26 | + * @param removeClosingTag - A function that removes a closing tag from a string. |
| 27 | + */ |
| 28 | +export async function insertContentTool( |
| 29 | + cline: Cline, |
| 30 | + block: ToolUse, |
| 31 | + askApproval: AskApproval, |
| 32 | + handleError: HandleError, |
| 33 | + pushToolResult: PushToolResult, |
| 34 | + removeClosingTag: RemoveClosingTag, |
| 35 | + diffViewProvider: DiffViewProvider, |
| 36 | + didEditFileEmitter: (b: boolean) => void, //ensure this is passed by ref |
| 37 | +) { |
| 38 | + const relPath: string | undefined = block.params.path |
| 39 | + const operations: string | undefined = block.params.operations |
| 40 | + |
| 41 | + const sharedMessageProps: ClineSayTool = { |
| 42 | + tool: "appliedDiff", |
| 43 | + path: getReadablePath(cline.cwd, removeClosingTag("path", relPath)), |
| 44 | + } |
| 45 | + |
| 46 | + try { |
| 47 | + if (block.partial) { |
| 48 | + const partialMessage = JSON.stringify(sharedMessageProps) |
| 49 | + await cline.ask("tool", partialMessage, block.partial).catch(() => {}) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + // Validate required parameters |
| 54 | + if (!relPath) { |
| 55 | + cline.consecutiveMistakeCount++ |
| 56 | + pushToolResult(await cline.sayAndCreateMissingParamError("insert_content", "path")) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + if (!operations) { |
| 61 | + cline.consecutiveMistakeCount++ |
| 62 | + pushToolResult(await cline.sayAndCreateMissingParamError("insert_content", "operations")) |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + const absolutePath = path.resolve(cline.cwd, relPath) |
| 67 | + const fileExists = await fileExistsAtPath(absolutePath) |
| 68 | + |
| 69 | + if (!fileExists) { |
| 70 | + cline.consecutiveMistakeCount++ |
| 71 | + const formattedError = `File does not exist at path: ${absolutePath}\n\n<error_details>\nThe specified file could not be found. Please verify the file path and try again.\n</error_details>` |
| 72 | + await cline.say("error", formattedError) |
| 73 | + pushToolResult(formattedError) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + let parsedOperations: Array<{ |
| 78 | + start_line: number |
| 79 | + content: string |
| 80 | + }> |
| 81 | + |
| 82 | + try { |
| 83 | + parsedOperations = JSON.parse(operations) |
| 84 | + if (!Array.isArray(parsedOperations)) { |
| 85 | + throw new Error("Operations must be an array") |
| 86 | + } |
| 87 | + } catch (error) { |
| 88 | + cline.consecutiveMistakeCount++ |
| 89 | + await cline.say("error", `Failed to parse operations JSON: ${error.message}`) |
| 90 | + pushToolResult(formatResponse.toolError("Invalid operations JSON format")) |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + cline.consecutiveMistakeCount = 0 |
| 95 | + |
| 96 | + // Read the file |
| 97 | + const fileContent = await fs.readFile(absolutePath, "utf8") |
| 98 | + diffViewProvider.editType = "modify" |
| 99 | + diffViewProvider.originalContent = fileContent |
| 100 | + const lines = fileContent.split("\n") |
| 101 | + |
| 102 | + const updatedContent = insertGroups( |
| 103 | + lines, |
| 104 | + parsedOperations.map((elem) => { |
| 105 | + return { |
| 106 | + index: elem.start_line - 1, |
| 107 | + elements: elem.content.split("\n"), |
| 108 | + } |
| 109 | + }), |
| 110 | + ).join("\n") |
| 111 | + |
| 112 | + // Show changes in diff view |
| 113 | + if (!diffViewProvider.isEditing) { |
| 114 | + await cline.ask("tool", JSON.stringify(sharedMessageProps), true).catch(() => {}) |
| 115 | + // First open with original content |
| 116 | + await diffViewProvider.open(relPath) |
| 117 | + await diffViewProvider.update(fileContent, false) |
| 118 | + diffViewProvider.scrollToFirstDiff() |
| 119 | + await delay(200) |
| 120 | + } |
| 121 | + |
| 122 | + const diff = formatResponse.createPrettyPatch(relPath, fileContent, updatedContent) |
| 123 | + |
| 124 | + if (!diff) { |
| 125 | + pushToolResult(`No changes needed for '${relPath}'`) |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + await diffViewProvider.update(updatedContent, true) |
| 130 | + |
| 131 | + const completeMessage = JSON.stringify({ |
| 132 | + ...sharedMessageProps, |
| 133 | + diff, |
| 134 | + } satisfies ClineSayTool) |
| 135 | + |
| 136 | + const didApprove = await askApproval("tool", completeMessage) |
| 137 | + |
| 138 | + if (!didApprove) { |
| 139 | + await diffViewProvider.revertChanges() |
| 140 | + pushToolResult("Changes were rejected by the user.") |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + const { newProblemsMessage, userEdits, finalContent } = await diffViewProvider.saveChanges() |
| 145 | + didEditFileEmitter(true) |
| 146 | + |
| 147 | + if (!userEdits) { |
| 148 | + pushToolResult(`The content was successfully inserted in ${relPath.toPosix()}.${newProblemsMessage}`) |
| 149 | + await diffViewProvider.reset() |
| 150 | + return |
| 151 | + } |
| 152 | + |
| 153 | + const userFeedbackDiff = JSON.stringify({ |
| 154 | + tool: "appliedDiff", |
| 155 | + path: getReadablePath(cline.cwd, relPath), |
| 156 | + diff: userEdits, |
| 157 | + } satisfies ClineSayTool) |
| 158 | + |
| 159 | + console.debug("[DEBUG] User made edits, sending feedback diff:", userFeedbackDiff) |
| 160 | + await cline.say("user_feedback_diff", userFeedbackDiff) |
| 161 | + pushToolResult( |
| 162 | + `The user made the following updates to your content:\n\n${userEdits}\n\n` + |
| 163 | + `The updated content, which includes both your original modifications and the user's edits, has been successfully saved to ${relPath.toPosix()}. Here is the full, updated content of the file:\n\n` + |
| 164 | + `<final_file_content path="${relPath.toPosix()}">\n${finalContent}\n</final_file_content>\n\n` + |
| 165 | + `Please note:\n` + |
| 166 | + `1. You do not need to re-write the file with these changes, as they have already been applied.\n` + |
| 167 | + `2. Proceed with the task using this updated file content as the new baseline.\n` + |
| 168 | + `3. If the user's edits have addressed part of the task or changed the requirements, adjust your approach accordingly.` + |
| 169 | + `${newProblemsMessage}`, |
| 170 | + ) |
| 171 | + await diffViewProvider.reset() |
| 172 | + } catch (error) { |
| 173 | + await handleError("insert content", error) |
| 174 | + await diffViewProvider.reset() |
| 175 | + } |
| 176 | +} |
0 commit comments