| 21 | "Apply a patch to modify multiple files. Supports adding, updating, and deleting files with context-aware changes.", |
| 22 | parameters: PatchParams, |
| 23 | async execute(params, ctx) { |
| 24 | if (!params.patchText) { |
| 25 | throw new Error("patchText is required") |
| 26 | } |
| 27 | |
| 28 | // Parse the patch to get hunks |
| 29 | let hunks: Patch.Hunk[] |
| 30 | try { |
| 31 | const parseResult = Patch.parsePatch(params.patchText) |
| 32 | hunks = parseResult.hunks |
| 33 | } catch (error) { |
| 34 | throw new Error(`Failed to parse patch: ${error}`) |
| 35 | } |
| 36 | |
| 37 | if (hunks.length === 0) { |
| 38 | throw new Error("No file changes found in patch") |
| 39 | } |
| 40 | |
| 41 | // Validate file paths and check permissions |
| 42 | const agent = await Agent.get(ctx.agent) |
| 43 | const fileChanges: Array<{ |
| 44 | filePath: string |
| 45 | oldContent: string |
| 46 | newContent: string |
| 47 | type: "add" | "update" | "delete" | "move" |
| 48 | movePath?: string |
| 49 | }> = [] |
| 50 | |
| 51 | let totalDiff = "" |
| 52 | |
| 53 | for (const hunk of hunks) { |
| 54 | const filePath = path.resolve(Instance.directory, hunk.path) |
| 55 | |
| 56 | if (!Filesystem.contains(Instance.directory, filePath)) { |
| 57 | const parentDir = path.dirname(filePath) |
| 58 | if (!(await Permission.isBypassEnabled())) { |
| 59 | if (agent.permission.external_directory === "ask") { |
| 60 | await Permission.ask({ |
| 61 | type: "external_directory", |
| 62 | pattern: [parentDir, path.join(parentDir, "*")], |
| 63 | sessionID: ctx.sessionID, |
| 64 | messageID: ctx.messageID, |
| 65 | callID: ctx.callID, |
| 66 | title: `Patch file outside working directory: ${filePath}`, |
| 67 | metadata: { |
| 68 | filepath: filePath, |
| 69 | parentDir, |
| 70 | }, |
| 71 | }) |
| 72 | } else if (agent.permission.external_directory === "deny") { |
| 73 | throw new Permission.RejectedError( |
| 74 | ctx.sessionID, |
| 75 | "external_directory", |
| 76 | ctx.callID, |
| 77 | { |
| 78 | filepath: filePath, |
| 79 | parentDir, |
| 80 | }, |