1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
|
import { z } from "zod";
import * as path from "path";
import * as fs from "fs/promises";
import { Tool } from "./tool";
import { FileTimes } from "./util/file-times";
const DESCRIPTION = `Applies a patch to multiple files in one operation. This tool is useful for making coordinated changes across multiple files.
The patch text must follow this format:
*** Begin Patch
*** Update File: /path/to/file
@@ Context line (unique within the file)
Line to keep
-Line to remove
+Line to add
Line to keep
*** Add File: /path/to/new/file
+Content of the new file
+More content
*** Delete File: /path/to/file/to/delete
*** End Patch
Before using this tool:
1. Use the FileRead tool to understand the files' contents and context
2. Verify all file paths are correct (use the LS tool)
CRITICAL REQUIREMENTS FOR USING THIS TOOL:
1. UNIQUENESS: Context lines MUST uniquely identify the specific sections you want to change
2. PRECISION: All whitespace, indentation, and surrounding code must match exactly
3. VALIDATION: Ensure edits result in idiomatic, correct code
4. PATHS: Always use absolute file paths (starting with /)
The tool will apply all changes in a single atomic operation.`;
const PatchParams = z.object({
patchText: z
.string()
.describe("The full patch text that describes all changes to be made"),
});
interface PatchResponseMetadata {
changed: string[];
additions: number;
removals: number;
}
interface Change {
type: "add" | "update" | "delete";
old_content?: string;
new_content?: string;
}
interface Commit {
changes: Record<string, Change>;
}
interface PatchOperation {
type: "update" | "add" | "delete";
filePath: string;
hunks?: PatchHunk[];
content?: string;
}
interface PatchHunk {
contextLine: string;
changes: PatchChange[];
}
interface PatchChange {
type: "keep" | "remove" | "add";
content: string;
}
function identifyFilesNeeded(patchText: string): string[] {
const files: string[] = [];
const lines = patchText.split("\n");
for (const line of lines) {
if (
line.startsWith("*** Update File:") ||
line.startsWith("*** Delete File:")
) {
const filePath = line.split(":", 2)[1]?.trim();
if (filePath) files.push(filePath);
}
}
return files;
}
function identifyFilesAdded(patchText: string): string[] {
const files: string[] = [];
const lines = patchText.split("\n");
for (const line of lines) {
if (line.startsWith("*** Add File:")) {
const filePath = line.split(":", 2)[1]?.trim();
if (filePath) files.push(filePath);
}
}
return files;
}
function textToPatch(
patchText: string,
_currentFiles: Record<string, string>,
): [PatchOperation[], number] {
const operations: PatchOperation[] = [];
const lines = patchText.split("\n");
let i = 0;
let fuzz = 0;
while (i < lines.length) {
const line = lines[i];
if (line.startsWith("*** Update File:")) {
const filePath = line.split(":", 2)[1]?.trim();
if (!filePath) {
i++;
continue;
}
const hunks: PatchHunk[] = [];
i++;
while (i < lines.length && !lines[i].startsWith("***")) {
if (lines[i].startsWith("@@")) {
const contextLine = lines[i].substring(2).trim();
const changes: PatchChange[] = [];
i++;
while (
i < lines.length &&
!lines[i].startsWith("@@") &&
!lines[i].startsWith("***")
) {
const changeLine = lines[i];
if (changeLine.startsWith(" ")) {
changes.push({ type: "keep", content: changeLine.substring(1) });
} else if (changeLine.startsWith("-")) {
changes.push({
type: "remove",
content: changeLine.substring(1),
});
} else if (changeLine.startsWith("+")) {
changes.push({ type: "add", content: changeLine.substring(1) });
}
i++;
}
hunks.push({ contextLine, changes });
} else {
i++;
}
}
operations.push({ type: "update", filePath, hunks });
} else if (line.startsWith("*** Add File:")) {
const filePath = line.split(":", 2)[1]?.trim();
if (!filePath) {
i++;
continue;
}
let content = "";
i++;
while (i < lines.length && !lines[i].startsWith("***")) {
if (lines[i].startsWith("+")) {
content += lines[i].substring(1) + "\n";
}
i++;
}
operations.push({ type: "add", filePath, content: content.slice(0, -1) });
} else if (line.startsWith("*** Delete File:")) {
const filePath = line.split(":", 2)[1]?.trim();
if (filePath) {
operations.push({ type: "delete", filePath });
}
i++;
} else {
i++;
}
}
return [operations, fuzz];
}
function patchToCommit(
operations: PatchOperation[],
currentFiles: Record<string, string>,
): Commit {
const changes: Record<string, Change> = {};
for (const op of operations) {
if (op.type === "delete") {
changes[op.filePath] = {
type: "delete",
old_content: currentFiles[op.filePath] || "",
};
} else if (op.type === "add") {
changes[op.filePath] = {
type: "add",
new_content: op.content || "",
};
} else if (op.type === "update" && op.hunks) {
const originalContent = currentFiles[op.filePath] || "";
const lines = originalContent.split("\n");
for (const hunk of op.hunks) {
const contextIndex = lines.findIndex((line) =>
line.includes(hunk.contextLine),
);
if (contextIndex === -1) {
throw new Error(`Context line not found: ${hunk.contextLine}`);
}
let currentIndex = contextIndex;
for (const change of hunk.changes) {
if (change.type === "keep") {
currentIndex++;
} else if (change.type === "remove") {
lines.splice(currentIndex, 1);
} else if (change.type === "add") {
lines.splice(currentIndex, 0, change.content);
currentIndex++;
}
}
}
changes[op.filePath] = {
type: "update",
old_content: originalContent,
new_content: lines.join("\n"),
};
}
}
return { changes };
}
function generateDiff(
oldContent: string,
newContent: string,
filePath: string,
): [string, number, number] {
// Mock implementation - would need actual diff generation
const lines1 = oldContent.split("\n");
const lines2 = newContent.split("\n");
const additions = Math.max(0, lines2.length - lines1.length);
const removals = Math.max(0, lines1.length - lines2.length);
return [`--- ${filePath}\n+++ ${filePath}\n`, additions, removals];
}
async function applyCommit(
commit: Commit,
writeFile: (path: string, content: string) => Promise<void>,
deleteFile: (path: string) => Promise<void>,
): Promise<void> {
for (const [filePath, change] of Object.entries(commit.changes)) {
if (change.type === "delete") {
await deleteFile(filePath);
} else if (change.new_content !== undefined) {
await writeFile(filePath, change.new_content);
}
}
}
export const patch = Tool.define({
name: "patch",
description: DESCRIPTION,
parameters: PatchParams,
execute: async (params) => {
if (!params.patchText) {
throw new Error("patchText is required");
}
// Identify all files needed for the patch and verify they've been read
const filesToRead = identifyFilesNeeded(params.patchText);
for (const filePath of filesToRead) {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
if (!FileTimes.get(absPath)) {
throw new Error(
`you must read the file ${filePath} before patching it. Use the FileRead tool first`,
);
}
try {
const stats = await fs.stat(absPath);
if (stats.isDirectory()) {
throw new Error(`path is a directory, not a file: ${absPath}`);
}
const lastRead = FileTimes.get(absPath);
if (lastRead && stats.mtime > lastRead) {
throw new Error(
`file ${absPath} has been modified since it was last read (mod time: ${stats.mtime.toISOString()}, last read: ${lastRead.toISOString()})`,
);
}
} catch (error: any) {
if (error.code === "ENOENT") {
throw new Error(`file not found: ${absPath}`);
}
throw new Error(`failed to access file: ${error.message}`);
}
}
// Check for new files to ensure they don't already exist
const filesToAdd = identifyFilesAdded(params.patchText);
for (const filePath of filesToAdd) {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
try {
await fs.stat(absPath);
throw new Error(`file already exists and cannot be added: ${absPath}`);
} catch (error: any) {
if (error.code !== "ENOENT") {
throw new Error(`failed to check file: ${error.message}`);
}
}
}
// Load all required files
const currentFiles: Record<string, string> = {};
for (const filePath of filesToRead) {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
try {
const content = await fs.readFile(absPath, "utf-8");
currentFiles[filePath] = content;
} catch (error: any) {
throw new Error(`failed to read file ${absPath}: ${error.message}`);
}
}
// Process the patch
const [patch, fuzz] = textToPatch(params.patchText, currentFiles);
if (fuzz > 3) {
throw new Error(
`patch contains fuzzy matches (fuzz level: ${fuzz}). Please make your context lines more precise`,
);
}
// Convert patch to commit
const commit = patchToCommit(patch, currentFiles);
// Apply the changes to the filesystem
await applyCommit(
commit,
async (filePath: string, content: string) => {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
// Create parent directories if needed
const dir = path.dirname(absPath);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(absPath, content, "utf-8");
},
async (filePath: string) => {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
await fs.unlink(absPath);
},
);
// Calculate statistics
const changedFiles: string[] = [];
let totalAdditions = 0;
let totalRemovals = 0;
for (const [filePath, change] of Object.entries(commit.changes)) {
let absPath = filePath;
if (!path.isAbsolute(absPath)) {
absPath = path.resolve(process.cwd(), absPath);
}
changedFiles.push(absPath);
const oldContent = change.old_content || "";
const newContent = change.new_content || "";
// Calculate diff statistics
const [, additions, removals] = generateDiff(
oldContent,
newContent,
filePath,
);
totalAdditions += additions;
totalRemovals += removals;
// Record file operations
FileTimes.write(absPath);
FileTimes.read(absPath);
}
const result = `Patch applied successfully. ${changedFiles.length} files changed, ${totalAdditions} additions, ${totalRemovals} removals`;
const output = result;
return {
metadata: {
changed: changedFiles,
additions: totalAdditions,
removals: totalRemovals,
} satisfies PatchResponseMetadata,
output,
};
},
});
|