| 21 | filePath: z.string().describe("The absolute path to the file to write (must be absolute, not relative)"), |
| 22 | }), |
| 23 | async execute(params, ctx) { |
| 24 | const agent = await Agent.get(ctx.agent) |
| 25 | |
| 26 | const filepath = path.isAbsolute(params.filePath) ? params.filePath : path.join(Instance.directory, params.filePath) |
| 27 | if (!Filesystem.contains(Instance.directory, filepath)) { |
| 28 | const parentDir = path.dirname(filepath) |
| 29 | if (!(await Permission.isBypassEnabled())) { |
| 30 | if (agent.permission.external_directory === "ask") { |
| 31 | await Permission.ask({ |
| 32 | type: "external_directory", |
| 33 | pattern: [parentDir, path.join(parentDir, "*")], |
| 34 | sessionID: ctx.sessionID, |
| 35 | messageID: ctx.messageID, |
| 36 | callID: ctx.callID, |
| 37 | title: `Write file outside working directory: ${filepath}`, |
| 38 | metadata: { |
| 39 | filepath, |
| 40 | parentDir, |
| 41 | }, |
| 42 | }) |
| 43 | } else if (agent.permission.external_directory === "deny") { |
| 44 | throw new Permission.RejectedError( |
| 45 | ctx.sessionID, |
| 46 | "external_directory", |
| 47 | ctx.callID, |
| 48 | { |
| 49 | filepath: filepath, |
| 50 | parentDir, |
| 51 | }, |
| 52 | `File ${filepath} is not in the current working directory`, |
| 53 | ) |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | const file = Bun.file(filepath) |
| 59 | const exists = await file.exists() |
| 60 | if (exists) await FileTime.assert(ctx.sessionID, filepath) |
| 61 | |
| 62 | if (agent.permission.edit === "ask") |
| 63 | await Permission.ask({ |
| 64 | type: "write", |
| 65 | sessionID: ctx.sessionID, |
| 66 | messageID: ctx.messageID, |
| 67 | callID: ctx.callID, |
| 68 | title: exists ? "Overwrite this file: " + filepath : "Create new file: " + filepath, |
| 69 | metadata: { |
| 70 | filePath: filepath, |
| 71 | content: params.content, |
| 72 | exists, |
| 73 | }, |
| 74 | }) |
| 75 | |
| 76 | await Bun.write(filepath, params.content) |
| 77 | await Bus.publish(File.Event.Edited, { |
| 78 | file: filepath, |
| 79 | }) |
| 80 | FileTime.read(ctx.sessionID, filepath) |