multiedit.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import z from "zod"
  2. import { Tool } from "./tool"
  3. import { EditTool } from "./edit"
  4. import DESCRIPTION from "./multiedit.txt"
  5. import path from "path"
  6. import { Instance } from "../project/instance"
  7. export const MultiEditTool = Tool.define("multiedit", {
  8. description: DESCRIPTION,
  9. parameters: z.object({
  10. filePath: z.string().describe("The absolute path to the file to modify"),
  11. edits: z
  12. .array(
  13. z.object({
  14. filePath: z.string().describe("The absolute path to the file to modify"),
  15. oldString: z.string().describe("The text to replace"),
  16. newString: z.string().describe("The text to replace it with (must be different from oldString)"),
  17. replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
  18. }),
  19. )
  20. .describe("Array of edit operations to perform sequentially on the file"),
  21. }),
  22. async execute(params, ctx) {
  23. const tool = await EditTool.init()
  24. const results = []
  25. for (const [, edit] of params.edits.entries()) {
  26. const result = await tool.execute(
  27. {
  28. filePath: params.filePath,
  29. oldString: edit.oldString,
  30. newString: edit.newString,
  31. replaceAll: edit.replaceAll,
  32. },
  33. ctx,
  34. )
  35. results.push(result)
  36. }
  37. return {
  38. title: path.relative(Instance.worktree, params.filePath),
  39. metadata: {
  40. results: results.map((r) => r.metadata),
  41. },
  42. output: results.at(-1)!.output,
  43. }
  44. },
  45. })