64875
Mc
mini-coder / files
mini-coder / src / tools / edit.ts
1.8 KB
1import { existsSync, readFileSync, writeFileSync } from "node:fs"; 2import { Type, type Static } from "@earendil-works/pi-ai"; 3import { createTwoFilesPatch } from "diff"; 4import type { ToolResult } from "./common.ts"; 5 6export const EDIT_PARAMS = Type.Object( 7 { 8 path: Type.String({ description: "File path" }), 9 oldText: Type.String({ description: "Exact text to replace; empty to create a file" }), 10 newText: Type.String({ description: "Replacement text" }), 11 }, 12 { additionalProperties: false }, 13); 14export type EditArgs = Static<typeof EDIT_PARAMS>; 15 16export function edit(args: EditArgs, signal: AbortSignal): ToolResult { 17 const { path, oldText, newText } = args; 18 const exists = existsSync(path); 19 20 if (oldText === "") { 21 if (exists) return { text: `edit failed: ${path} already exists`, isError: true }; 22 if (signal.aborted) return { text: "edit cancelled", isError: true }; 23 writeFileSync(path, newText); 24 return { text: `created ${path}\n${unified(path, "", newText)}`, isError: false }; 25 } 26 27 if (!exists) return { text: `edit failed: ${path} does not exist`, isError: true }; 28 const before = readFileSync(path, "utf8"); 29 const count = before.split(oldText).length - 1; 30 if (count === 0) return { text: `edit failed: oldText not found in ${path}`, isError: true }; 31 if (count > 1) return { text: `edit failed: oldText matches ${count} times in ${path}`, isError: true }; 32 33 const after = before.replace(oldText, newText); 34 if (signal.aborted) return { text: "edit cancelled", isError: true }; 35 writeFileSync(path, after); 36 return { text: `edited ${path}\n${unified(path, before, after)}`, isError: false }; 37} 38 39function unified(path: string, before: string, after: string): string { 40 return createTwoFilesPatch(path, path, before, after, "", "", { context: 3 }); 41}