@@ -2,20 +2,23 @@ import { existsSync, mkdirSync } from "node:fs";
22 import { dirname, join, relative } from "node:path";
33 import { z } from "zod";
44 import type { ToolDef } from "../llm-api/types.ts";
5+import { findLineByHash } from "./hashline.ts";
56
67 const EditInput = z.object({
78 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
8- oldString: z
9+ startAnchor: z.string().optional().describe('Start anchor, e.g. "11:a3"'),
10+ endAnchor: z
911 .string()
10- .describe(
11- "Exact string to find and replace. Must match exactly including whitespace and indentation. " +
12- "Must be unique in the file. To create a new file, pass an empty string.",
13- ),
14- newString: z
12+ .optional()
13+ .describe('End anchor (inclusive), e.g. "33:0e"'),
14+ newContent: z
1515 .string()
16- .describe(
17- "String to replace oldString with. Pass empty string to delete oldString.",
18- ),
16+ .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"),
1922 cwd: z
2023 .string()
2124 .optional()
@@ -32,14 +35,15 @@ export interface EditOutput {
3235 created: boolean;
3336 }
3437
38+const HASH_NOT_FOUND_ERROR =
39+ "Hash not found. Re-read the file to get current anchors.";
40+
3541 export const editTool: ToolDef<EditInput, EditOutput> = {
3642 name: "edit",
3743 description:
38- "Edit a file by replacing an exact string with a new string. " +
39- "The oldString must match exactly (including whitespace). " +
40- "To create a new file, pass oldString as empty string. " +
41- "To delete text, pass newString as empty string. " +
42- "Prefer small, focused edits over replacing large blocks.",
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.",
4347 schema: EditInput,
4448 execute: async (input) => {
4549 const cwd = input.cwd ?? process.cwd();
@@ -51,21 +55,30 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
5155 let created = false;
5256
5357 // ── Creating a new file ──────────────────────────────────────────────────
54- if (input.oldString === "") {
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+
5568 const dir = dirname(filePath);
5669 if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
5770
5871 const existing = await Bun.file(filePath).exists();
5972 if (existing) {
6073 throw new Error(
61- `File "${relPath}" already exists. Provide oldString to edit an existing file.`,
74+ `File "${relPath}" already exists. Provide startAnchor to edit an existing file.`,
6275 );
6376 }
6477
65- await Bun.write(filePath, input.newString);
78+ await Bun.write(filePath, input.newContent);
6679 created = true;
6780
68- const diff = generateDiff(relPath, "", input.newString);
81+ const diff = generateDiff(relPath, "", input.newContent);
6982 return { path: relPath, success: true, diff, created };
7083 }
7184
@@ -74,27 +87,67 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
7487 const exists = await file.exists();
7588 if (!exists) {
7689 throw new Error(
77- `File not found: "${relPath}". To create a new file, pass oldString as empty string.`,
90+ `File not found: "${relPath}". To create a new file, omit startAnchor.`,
7891 );
7992 }
8093
81- const original = await file.text();
82-
83- // Check uniqueness
84- const firstIdx = original.indexOf(input.oldString);
85- if (firstIdx === -1) {
94+ const start = parseAnchor(input.startAnchor, "startAnchor");
95+ const end = input.endAnchor
96+ ? parseAnchor(input.endAnchor, "endAnchor")
97+ : null;
98+ if (end && end.line < start.line) {
8699 throw new Error(
87- `oldString not found in "${relPath}". Make sure it matches exactly including whitespace and indentation.`,
100+ "endAnchor line number must be >= startAnchor line number.",
88101 );
89102 }
90- const secondIdx = original.indexOf(input.oldString, firstIdx + 1);
91- if (secondIdx !== -1) {
92- throw new Error(
93- `oldString matches multiple locations in "${relPath}". Provide more surrounding context to make it unique.`,
94- );
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+ }
109+
110+ const original = await file.text();
111+ const lines = original.split("\n");
112+
113+ const startLine = findLineByHash(lines, start.hash, start.line);
114+ if (!startLine) throw new Error(HASH_NOT_FOUND_ERROR);
115+
116+ let endLine = startLine;
117+ if (end) {
118+ const resolvedEnd = findLineByHash(lines, end.hash, end.line);
119+ if (!resolvedEnd) throw new Error(HASH_NOT_FOUND_ERROR);
120+ endLine = resolvedEnd;
121+ }
122+ if (endLine < startLine) {
123+ throw new Error("endAnchor resolves before startAnchor.");
95124 }
96125
97- const updated = original.replace(input.oldString, input.newString);
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+ }
149+
150+ const updated = updatedLines.join("\n");
98151 await Bun.write(filePath, updated);
99152
100153 const diff = generateDiff(relPath, original, updated);
@@ -102,6 +155,30 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
102155 },
103156 };
104157
158+interface ParsedAnchor {
159+ line: number;
160+ hash: string;
161+}
162+
163+function parseAnchor(value: string, name: string): ParsedAnchor {
164+ const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
165+ if (!match) {
166+ throw new Error(`Invalid ${name}. Expected "line:hh".`);
167+ }
168+
169+ const line = Number(match[1]);
170+ if (!Number.isInteger(line) || line < 1) {
171+ throw new Error(`Invalid ${name} line number.`);
172+ }
173+
174+ const hash = match[2];
175+ if (!hash) {
176+ throw new Error(`Invalid ${name}. Expected "line:hh".`);
177+ }
178+
179+ return { line, hash: hash.toLowerCase() };
180+}
181+
105182 // ─── Simple unified diff generator ───────────────────────────────────────────
106183
107184 function generateDiff(filePath: string, before: string, after: string): string {