@@ -1,24 +1,26 @@
1-import { existsSync, mkdirSync } from "node:fs";
2-import { dirname, join, relative } from "node:path";
1+import { join, relative } from "node:path";
32 import { z } from "zod";
43 import type { ToolDef } from "../llm-api/types.ts";
4+import { generateDiff } from "./diff.ts";
55 import { findLineByHash } from "./hashline.ts";
66
77 const EditInput = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- startAnchor: z.string().optional().describe('Start anchor, e.g. "11:a3"'),
9+ startAnchor: z
10+ .string()
11+ .describe('Start anchor from a prior read/grep, e.g. "11:a3"'),
1012 endAnchor: z
1113 .string()
1214 .optional()
13- .describe('End anchor (inclusive), e.g. "33:0e"'),
15+ .describe(
16+ 'End anchor (inclusive), e.g. "33:0e". Omit to target only the startAnchor line.',
17+ ),
1418 newContent: z
1519 .string()
1620 .optional()
17- .describe("Replacement text. Omit or pass empty string to delete a range."),
18- insertPosition: z
19- .enum(["before", "after"])
20- .optional()
21- .describe("Insert-only position relative to startAnchor"),
21+ .describe(
22+ "Replacement text. Omit or pass empty string to delete the range.",
23+ ),
2224 cwd: z
2325 .string()
2426 .optional()
@@ -29,10 +31,7 @@ type EditInput = z.infer<typeof EditInput>;
2931
3032 export interface EditOutput {
3133 path: string;
32- success: boolean;
33- /** Unified-style diff of the change */
3434 diff: string;
35- created: boolean;
3635 }
3736
3837 const HASH_NOT_FOUND_ERROR =
@@ -41,9 +40,11 @@ const HASH_NOT_FOUND_ERROR =
4140 export const editTool: ToolDef<EditInput, EditOutput> = {
4241 name: "edit",
4342 description:
44- "Edit a file using hashline anchors. Provide startAnchor (and optional endAnchor) " +
45- "to replace or delete a range. Use insertPosition with startAnchor to insert text. " +
46- "To create a new file, omit startAnchor and provide newContent.",
43+ "Replace or delete a range of lines in an existing file using hashline anchors. " +
44+ 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
45+ "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
46+ "Set newContent to the replacement text, or omit it to delete the range. " +
47+ "To create or overwrite a file use `write`. To insert without replacing any lines use `insert`.",
4748 schema: EditInput,
4849 execute: async (input) => {
4950 const cwd = input.cwd ?? process.cwd();
@@ -52,42 +53,11 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
5253 : join(cwd, input.path);
5354
5455 const relPath = relative(cwd, filePath);
55- let created = false;
56-
57- // โโ Creating a new file โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
58- if (!input.startAnchor) {
59- if (input.endAnchor || input.insertPosition) {
60- throw new Error(
61- "startAnchor is required for edits. Omit it only to create a new file.",
62- );
63- }
64- if (input.newContent === undefined) {
65- throw new Error("newContent is required to create a new file.");
66- }
67-
68- const dir = dirname(filePath);
69- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
70-
71- const existing = await Bun.file(filePath).exists();
72- if (existing) {
73- throw new Error(
74- `File "${relPath}" already exists. Provide startAnchor to edit an existing file.`,
75- );
76- }
77-
78- await Bun.write(filePath, input.newContent);
79- created = true;
80-
81- const diff = generateDiff(relPath, "", input.newContent);
82- return { path: relPath, success: true, diff, created };
83- }
8456
85- // โโ Editing an existing file โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
8657 const file = Bun.file(filePath);
87- const exists = await file.exists();
88- if (!exists) {
58+ if (!(await file.exists())) {
8959 throw new Error(
90- `File not found: "${relPath}". To create a new file, omit startAnchor.`,
60+ `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
9161 );
9262 }
9363
@@ -95,17 +65,12 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
9565 const end = input.endAnchor
9666 ? parseAnchor(input.endAnchor, "endAnchor")
9767 : null;
68+
9869 if (end && end.line < start.line) {
9970 throw new Error(
10071 "endAnchor line number must be >= startAnchor line number.",
10172 );
10273 }
103- if (input.insertPosition && input.endAnchor) {
104- throw new Error("insertPosition cannot be used with endAnchor.");
105- }
106- if (input.insertPosition && input.newContent === undefined) {
107- throw new Error("newContent is required for insert operations.");
108- }
10974
11075 const original = await file.text();
11176 const lines = original.split("\n");
@@ -123,35 +88,22 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
12388 throw new Error("endAnchor resolves before startAnchor.");
12489 }
12590
126- let updatedLines: string[];
127- if (input.insertPosition) {
128- const insertLines = (input.newContent ?? "").split("\n");
129- const insertAt =
130- input.insertPosition === "before" ? startLine - 1 : startLine;
131- updatedLines = [
132- ...lines.slice(0, insertAt),
133- ...insertLines,
134- ...lines.slice(insertAt),
135- ];
136- } else {
137- const replacement =
138- input.newContent === undefined || input.newContent === ""
139- ? []
140- : input.newContent.split("\n");
141- const startIdx = startLine - 1;
142- const endIdx = (end ? endLine : startLine) - 1;
143- updatedLines = [
144- ...lines.slice(0, startIdx),
145- ...replacement,
146- ...lines.slice(endIdx + 1),
147- ];
148- }
91+ const replacement =
92+ input.newContent === undefined || input.newContent === ""
93+ ? []
94+ : input.newContent.split("\n");
95+
96+ const updatedLines = [
97+ ...lines.slice(0, startLine - 1),
98+ ...replacement,
99+ ...lines.slice(endLine),
100+ ];
149101
150102 const updated = updatedLines.join("\n");
151103 await Bun.write(filePath, updated);
152104
153105 const diff = generateDiff(relPath, original, updated);
154- return { path: relPath, success: true, diff, created };
106+ return { path: relPath, diff };
155107 },
156108 };
157109
@@ -163,7 +115,9 @@ interface ParsedAnchor {
163115 function parseAnchor(value: string, name: string): ParsedAnchor {
164116 const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
165117 if (!match) {
166- throw new Error(`Invalid ${name}. Expected "line:hh".`);
118+ throw new Error(
119+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
120+ );
167121 }
168122
169123 const line = Number(match[1]);
@@ -173,74 +127,10 @@ function parseAnchor(value: string, name: string): ParsedAnchor {
173127
174128 const hash = match[2];
175129 if (!hash) {
176- throw new Error(`Invalid ${name}. Expected "line:hh".`);
130+ throw new Error(
131+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
132+ );
177133 }
178134
179135 return { line, hash: hash.toLowerCase() };
180136 }
181-
182-// โโโ Simple unified diff generator โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
183-
184-function generateDiff(filePath: string, before: string, after: string): string {
185- const beforeLines = before === "" ? [] : before.split("\n");
186- const afterLines = after === "" ? [] : after.split("\n");
187-
188- // Find changed regions using a simple LCS-based approach
189- // For our use case, we just show the hunks around the changed area
190- const diff = computeUnifiedDiff(beforeLines, afterLines);
191-
192- if (diff.length === 0) return "(no changes)";
193-
194- return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
195-}
196-
197-function computeUnifiedDiff(before: string[], after: string[]): string {
198- const CONTEXT = 3;
199-
200- // Simple O(n) approach: find the first and last differing line
201- let firstDiff = -1;
202- let lastDiffBefore = before.length;
203- let lastDiffAfter = after.length;
204-
205- for (let i = 0; i < Math.max(before.length, after.length); i++) {
206- if (before[i] !== after[i]) {
207- if (firstDiff === -1) firstDiff = i;
208- lastDiffBefore = i + 1;
209- lastDiffAfter = i + 1;
210- }
211- }
212-
213- if (firstDiff === -1) return "";
214-
215- const hunkStart = Math.max(0, firstDiff - CONTEXT);
216- const hunkEndBefore = Math.min(before.length, lastDiffBefore + CONTEXT);
217- const hunkEndAfter = Math.min(after.length, lastDiffAfter + CONTEXT);
218-
219- const lines: string[] = [];
220- lines.push(
221- `@@ -${hunkStart + 1},${hunkEndBefore - hunkStart} ` +
222- `+${hunkStart + 1},${hunkEndAfter - hunkStart} @@`,
223- );
224-
225- // Context before
226- for (let i = hunkStart; i < firstDiff; i++) {
227- lines.push(` ${before[i] ?? ""}`);
228- }
229-
230- // Removed lines
231- for (let i = firstDiff; i < lastDiffBefore && i < before.length; i++) {
232- lines.push(`-${before[i] ?? ""}`);
233- }
234-
235- // Added lines
236- for (let i = firstDiff; i < lastDiffAfter && i < after.length; i++) {
237- lines.push(`+${after[i] ?? ""}`);
238- }
239-
240- // Context after
241- for (let i = lastDiffBefore; i < hunkEndBefore && i < before.length; i++) {
242- lines.push(` ${before[i] ?? ""}`);
243- }
244-
245- return lines.join("\n");
246-}