-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.ts
More file actions
919 lines (841 loc) · 31.9 KB
/
Copy pathlib.ts
File metadata and controls
919 lines (841 loc) · 31.9 KB
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { randomBytes } from "crypto";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { diffLines, createTwoFilesPatch } from "diff";
import { minimatch } from "minimatch";
import {
ERROR_CODES,
SUPPORTED_ENCODINGS,
FUZZY_MATCH_THRESHOLD,
type SupportedEncoding,
} from "./constants.js";
import {
normalizePath,
expandHome,
isPathWithinDirectory,
} from "./path-utils.js";
// --- Operation Limits ---
export const DEFAULT_READ_TIMEOUT_MS = 30_000; // 30s timeout for read operations
export const DEFAULT_MAX_DIR_ENTRIES = 10_000; // max entries for recursive directory listing
export const DIR_ENTRY_WARNING_THRESHOLD = 1_000; // warn at this count
export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new CodedError(
`Operation timed out after ${timeoutMs}ms: ${label}`,
ERROR_CODES.FILESYSTEM_ERROR
));
}, timeoutMs);
promise.then(
(val) => { clearTimeout(timer); resolve(val); },
(err) => { clearTimeout(timer); reject(err); }
);
});
}
// --- Custom Error Class ---
export class CodedError extends Error {
readonly code: string;
readonly editsApplied?: number;
constructor(message: string, code: string, options?: { editsApplied?: number }) {
super(message);
this.name = "CodedError";
this.code = code;
if (options?.editsApplied !== undefined) {
this.editsApplied = options.editsApplied;
}
}
}
// --- Type Guard: error with .code property (Node.js system errors, CodedError, etc.) ---
export function hasErrorCode(value: unknown): value is { code: string; message?: string } {
return (
typeof value === "object" &&
value !== null &&
"code" in value &&
typeof (value as Record<string, unknown>).code === "string"
);
}
// --- Allowed Directories State ---
export type AllowedRootKind = "directory" | "file";
export interface AllowedRoot {
path: string;
kind: AllowedRootKind;
}
let allowedDirectories: string[] = [];
let allowedRoots: AllowedRoot[] = [];
const activeAtomicTempPaths = new Set<string>();
export function getAllowedDirectories(): string[] {
return [...allowedDirectories];
}
export function getAllowedRoots(): AllowedRoot[] {
return allowedRoots.map((root) => ({ ...root }));
}
export function setAllowedDirectories(dirs: string[]): void {
allowedRoots = dirs.map((dir) => ({ path: dir, kind: "directory" }));
allowedDirectories = allowedRoots.map((root) => root.path);
}
export function setAllowedRoots(roots: AllowedRoot[]): void {
allowedRoots = roots.map((root) => ({ ...root }));
allowedDirectories = allowedRoots.map((root) => root.path);
}
export function trackTempFileForCleanup(tempPath: string): () => void {
activeAtomicTempPaths.add(tempPath);
return () => {
activeAtomicTempPaths.delete(tempPath);
};
}
export async function cleanupActiveTempFiles(): Promise<string[]> {
const tempPaths = [...activeAtomicTempPaths];
const removed: string[] = [];
await Promise.all(tempPaths.map(async (tempPath) => {
try {
await fs.unlink(tempPath);
removed.push(tempPath);
} catch (error: unknown) {
if (!hasErrorCode(error) || error.code !== "ENOENT") {
// Cleanup is best effort: never mask the original shutdown/failure path.
}
} finally {
activeAtomicTempPaths.delete(tempPath);
}
}));
return removed;
}
function getAllowedDirectoryRoots(): AllowedRoot[] {
return allowedRoots.filter((root) => root.kind === "directory");
}
// --- Relative Path Resolution ---
export function resolveRelativePathAgainstAllowedDirectories(relativePath: string): string {
const directoryRoots = getAllowedDirectoryRoots();
if (directoryRoots.length === 0) {
return path.resolve(process.cwd(), relativePath);
}
for (const allowedRoot of directoryRoots) {
const candidate = path.resolve(allowedRoot.path, relativePath);
const normalizedCandidate = normalizePath(candidate);
if (isPathWithinDirectory(normalizedCandidate, allowedRoot.path, { caseSensitive: true })) {
return candidate;
}
}
return path.resolve(directoryRoots[0].path, relativePath);
}
function normalizedRootPath(root: AllowedRoot): string {
return normalizePath(root.path);
}
function isResolvedPathAllowed(normalizedResolvedPath: string): boolean {
return allowedRoots.some((root) => {
const rootPath = normalizedRootPath(root);
if (root.kind === "file") return normalizedResolvedPath === rootPath;
return isPathWithinDirectory(normalizedResolvedPath, rootPath, { caseSensitive: true });
});
}
function isResolvedPathWithinAllowedDirectory(normalizedResolvedPath: string): boolean {
return getAllowedDirectoryRoots().some((root) =>
isPathWithinDirectory(normalizedResolvedPath, normalizedRootPath(root), { caseSensitive: true })
);
}
function isStringPathWithinAllowedDirectory(normalizedPath: string): boolean {
return getAllowedDirectoryRoots().some((root) =>
isPathWithinDirectory(normalizedPath, normalizedRootPath(root), { caseSensitive: true })
);
}
function isBlockedSystemPath(candidatePath: string): boolean {
if (process.platform === "win32") return false;
const normalized = normalizePath(path.resolve(candidatePath));
const blockedPrefixes = ["/dev", "/proc", "/sys"];
return blockedPrefixes.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`));
}
async function findExistingAncestor(startPath: string): Promise<string | null> {
let current = startPath;
while (true) {
try {
return await fs.realpath(current);
} catch (error: unknown) {
const errCode = hasErrorCode(error) ? error.code : undefined;
if (errCode !== "ENOENT") throw error;
const parent = path.dirname(current);
if (parent === current) return null;
current = parent;
}
}
}
// --- Security Validation ---
export async function validatePath(requestedPath: string): Promise<string> {
// Reject null bytes -- path injection vector
if (requestedPath.includes("\x00")) {
throw new CodedError("Invalid path: path contains null bytes", ERROR_CODES.INVALID_ARGS);
}
// Reject double-encoded path traversal (%252e%252e -> %2e%2e -> ..)
if (/%25/i.test(requestedPath)) {
throw new CodedError("Invalid path: double-encoded characters detected", ERROR_CODES.INVALID_ARGS);
}
// Reject UNC paths on non-Windows platforms (\\server\share)
if (process.platform !== "win32" && /^\\\\/.test(requestedPath)) {
throw new CodedError("Invalid path: UNC paths are not supported on this platform", ERROR_CODES.INVALID_ARGS);
}
// Reject Windows-style backslash separators on Unix (potential bypass)
if (process.platform !== "win32" && /\\/.test(requestedPath)) {
throw new CodedError("Invalid path: backslash path separators are not allowed on this platform", ERROR_CODES.INVALID_ARGS);
}
const expandedPath = expandHome(requestedPath);
const absolute = path.isAbsolute(expandedPath)
? path.resolve(expandedPath)
: resolveRelativePathAgainstAllowedDirectories(expandedPath);
if (isBlockedSystemPath(absolute)) {
throw new CodedError("Invalid path: access to device/system files is not allowed", ERROR_CODES.ACCESS_DENIED);
}
try {
const realPath = await fs.realpath(absolute);
if (isBlockedSystemPath(realPath)) {
throw new CodedError("Invalid path: access to device/system files is not allowed", ERROR_CODES.ACCESS_DENIED);
}
const normalizedReal = normalizePath(realPath);
if (!isResolvedPathAllowed(normalizedReal)) {
throw new CodedError(
"Access denied - symlink target outside allowed roots",
ERROR_CODES.ACCESS_DENIED
);
}
return realPath;
} catch (error: unknown) {
// Rethrow our own CodedError errors immediately (e.g. ACCESS_DENIED from symlink check)
if (error instanceof CodedError) {
throw error;
}
const errCode = hasErrorCode(error) ? error.code : undefined;
const errMessage = error instanceof Error ? error.message : String(error);
if (errCode === "ENOENT") {
// Path doesn't exist, check parent
const parentDir = path.dirname(absolute);
try {
const realParentPath = await fs.realpath(parentDir);
const normalizedParent = normalizePath(realParentPath);
if (!isResolvedPathWithinAllowedDirectory(normalizedParent)) {
throw new CodedError(
"Access denied - parent directory outside allowed roots",
ERROR_CODES.ACCESS_DENIED
);
}
return absolute;
} catch (parentError: unknown) {
// If parent resolved but is outside allowed dirs, rethrow immediately
if (parentError instanceof CodedError) {
throw parentError;
}
const parentErrCode = hasErrorCode(parentError) ? parentError.code : undefined;
// Parent doesn't exist — check string path for create_parents support
if (parentErrCode === "ENOENT") {
const existingAncestor = await findExistingAncestor(parentDir);
const normalizedAncestor = existingAncestor ? normalizePath(existingAncestor) : null;
if (normalizedAncestor && isResolvedPathWithinAllowedDirectory(normalizedAncestor)) {
return absolute;
}
if (!isStringPathWithinAllowedDirectory(normalizePath(absolute))) {
throw new CodedError(
`Access denied - path outside allowed roots: ${absolute} is not within [${allowedDirectories.join(", ")}]`,
ERROR_CODES.ACCESS_DENIED
);
}
throw new CodedError(
`Parent directory does not exist: ${parentDir}. Use 'list_allowed_directories' to verify accessible paths.`,
ERROR_CODES.PATH_NOT_FOUND
);
}
// Other error (permissions, etc.) — throw immediately
throw new CodedError(
`Parent directory is inaccessible: ${parentDir}`,
ERROR_CODES.PERMISSION_DENIED
);
}
}
// Other error (not ENOENT) during initial realpath
if (errCode === "EACCES" || errCode === "EPERM") {
throw new CodedError(
`Permission denied accessing path: ${absolute}`,
ERROR_CODES.PERMISSION_DENIED
);
}
throw new CodedError(
`Filesystem error validating path ${absolute}: ${errMessage}`,
ERROR_CODES.FILESYSTEM_ERROR
);
}
}
// --- Encoding Helpers ---
export function validateEncoding(encoding: string): SupportedEncoding {
const normalized = encoding.toLowerCase() as SupportedEncoding;
if (!SUPPORTED_ENCODINGS.includes(normalized)) {
throw new CodedError(
`Unsupported encoding '${encoding}'. Supported encodings: ${SUPPORTED_ENCODINGS.join(", ")}`,
ERROR_CODES.INVALID_ENCODING
);
}
return normalized;
}
export interface BOMResult {
content: string;
bomDetected: string | null;
}
export function detectAndStripBOM(buffer: Buffer): BOMResult {
// UTF-8 BOM: EF BB BF
if (buffer.length >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
return { content: buffer.subarray(3).toString("utf-8"), bomDetected: "UTF-8" };
}
// UTF-16 BE BOM: FE FF
if (buffer.length >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
const contentBytes = buffer.subarray(2);
const swapped = Buffer.allocUnsafe(contentBytes.length);
for (let i = 0; i < contentBytes.length; i += 2) {
swapped[i] = contentBytes[i + 1] ?? 0;
swapped[i + 1] = contentBytes[i];
}
return { content: swapped.toString("utf16le"), bomDetected: "UTF-16 BE" };
}
// UTF-16 LE BOM: FF FE
if (buffer.length >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
return { content: buffer.subarray(2).toString("utf16le"), bomDetected: "UTF-16 LE" };
}
return { content: buffer.toString("utf-8"), bomDetected: null };
}
export function hasBinaryContent(content: string): boolean {
return content.includes("\x00");
}
// --- File Stats ---
export interface FileInfo {
size: number;
created: Date;
modified: Date;
accessed: Date;
isDirectory: boolean;
isFile: boolean;
permissions: string;
}
export async function getFileStats(filePath: string): Promise<FileInfo> {
const stats = await fs.stat(filePath);
return {
size: stats.size,
created: stats.birthtime,
modified: stats.mtime,
accessed: stats.atime,
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
permissions: process.platform === "win32" ? "N/A (Windows)" : stats.mode.toString(8).slice(-3),
};
}
// --- Search Files ---
export interface SearchFilesOptions {
search_mode?: "substring" | "regex" | "glob";
case_sensitive?: boolean;
max_results?: number;
match_path?: boolean;
}
export interface SearchFilesResult {
matches: string[];
totalMatches: number;
truncated: boolean;
entriesVisited: number;
entryLimitReached: boolean;
}
export async function searchFiles(
rootPath: string,
pattern: string,
excludePatterns: string[] = [],
options: SearchFilesOptions = {}
): Promise<SearchFilesResult> {
const {
search_mode = "substring",
max_results = 1000,
match_path = false,
} = options;
// Default case sensitivity: false for substring, true for regex/glob
const caseSensitive = options.case_sensitive ?? (search_mode !== "substring");
const results: string[] = [];
let totalMatches = 0;
let limitReached = false;
let entriesVisited = 0;
let entryLimitReached = false;
async function search(currentPath: string) {
if (limitReached || entryLimitReached) return;
let entries;
try {
entries = await fs.readdir(currentPath, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (limitReached || entryLimitReached) return;
entriesVisited++;
if (entriesVisited >= DEFAULT_MAX_DIR_ENTRIES) {
entryLimitReached = true;
return;
}
const fullPath = path.join(currentPath, entry.name);
try {
const relativePath = path.relative(rootPath, fullPath);
const shouldExclude = excludePatterns.some((excludePattern) =>
minimatch(relativePath, excludePattern, { dot: true, matchBase: true })
);
if (shouldExclude) continue;
const matchTarget = match_path ? relativePath : entry.name;
let isMatch = false;
switch (search_mode) {
case "regex":
try {
const flags = caseSensitive ? "" : "i";
const regex = new RegExp(pattern, flags);
isMatch = regex.test(matchTarget);
} catch (e: unknown) {
const errMsg = e instanceof Error ? e.message : String(e);
throw new CodedError(`Invalid regex pattern "${pattern}": ${errMsg}`, ERROR_CODES.INVALID_ARGS);
}
break;
case "glob":
isMatch = minimatch(matchTarget, pattern, { dot: true, nocase: !caseSensitive });
break;
case "substring":
default:
isMatch = caseSensitive
? matchTarget.includes(pattern)
: matchTarget.toLowerCase().includes(pattern.toLowerCase());
break;
}
if (isMatch) {
totalMatches++;
if (results.length < max_results) {
results.push(fullPath);
} else {
limitReached = true;
return;
}
}
if (entry.isDirectory()) {
await search(fullPath);
}
} catch (entryError: unknown) {
if (entryError instanceof CodedError && entryError.code === ERROR_CODES.INVALID_ARGS) throw entryError;
continue;
}
}
}
await search(rootPath);
return {
matches: results,
totalMatches,
truncated: totalMatches > results.length,
entriesVisited,
entryLimitReached,
};
}
// --- File Editing Utilities ---
export function normalizeLineEndings(text: string): string {
return text.replace(/\r\n/g, "\n");
}
export function createUnifiedDiff(
originalContent: string,
newContent: string,
filepath: string = "file"
): string {
const normalizedOriginal = normalizeLineEndings(originalContent);
const normalizedNew = normalizeLineEndings(newContent);
return createTwoFilesPatch(
filepath,
filepath,
normalizedOriginal,
normalizedNew,
"original",
"modified"
);
}
// Helper for fuzzy matching in edit_file
export function calculateSimilarity(
oldLines: string[],
potentialMatchLines: string[]
): number {
if (oldLines.length === 0) return potentialMatchLines.length === 0 ? 1 : 0;
const trimmedOld = oldLines.map((l) => l.trim());
const trimmedPotential = potentialMatchLines.map((l) => l.trim());
// Use diffLines to compare trimmed content
const diffResult = diffLines(
trimmedOld.join("\n"),
trimmedPotential.join("\n"),
{ newlineIsToken: true }
);
let commonLines = 0;
diffResult.forEach((part) => {
if (!part.added && !part.removed) {
commonLines += part.count || 0;
}
});
// Similarity is the ratio of common lines to the original number of lines
return commonLines / oldLines.length;
}
export interface FileEdit {
oldText?: string;
newText: string;
start_line?: number;
end_line?: number;
insert_at_line?: number;
}
export interface ApplyFileEditsOptions {
showLineNumbersOnError?: boolean;
}
function splitReplacementLines(text: string): string[] {
return normalizeLineEndings(text).split("\n");
}
function formatNumberedSnippet(lines: string[], startLine = 1, maxLines = 40): string {
return lines
.slice(0, maxLines)
.map((line, index) => `${startLine + index} | ${line}`)
.join("\n");
}
export async function applyFileEdits(
filePath: string,
edits: FileEdit[],
encoding: SupportedEncoding = "utf-8",
dryRun = false,
options: ApplyFileEditsOptions = {}
): Promise<string> {
if (edits.length === 0) {
return createUnifiedDiff("", "", filePath);
}
const contentBuffer = await fs.readFile(filePath);
let content: string;
try {
content = normalizeLineEndings(contentBuffer.toString(encoding));
} catch (encError: unknown) {
const encMsg = encError instanceof Error ? encError.message : String(encError);
throw new CodedError(
`Encoding error reading ${filePath} with encoding '${encoding}': ${encMsg}`,
ERROR_CODES.ENCODING_ERROR
);
}
let modifiedContent = content;
const totalLineCount = content.split("\n").length;
for (let editIndex = 0; editIndex < edits.length; editIndex++) {
const edit = edits[editIndex];
const editNum = editIndex + 1;
const normalizedNew = normalizeLineEndings(edit.newText);
const contentLines = modifiedContent.split("\n");
if (edit.insert_at_line !== undefined) {
if (edit.insert_at_line > contentLines.length + 1) {
throw new CodedError(
`Edit ${editNum} of ${edits.length}: insert_at_line (${edit.insert_at_line}) is greater than the allowed insertion line (${contentLines.length + 1}).`,
ERROR_CODES.INVALID_ARGS,
{ editsApplied: editIndex }
);
}
contentLines.splice(edit.insert_at_line - 1, 0, ...splitReplacementLines(edit.newText));
modifiedContent = contentLines.join("\n");
continue;
}
if (edit.start_line !== undefined || edit.end_line !== undefined) {
if (edit.start_line === undefined || edit.end_line === undefined) {
throw new CodedError(
`Edit ${editNum} of ${edits.length}: start_line and end_line must be provided together for line-range edits.`,
ERROR_CODES.INVALID_ARGS,
{ editsApplied: editIndex }
);
}
if (edit.start_line > edit.end_line) {
throw new CodedError(
`Edit ${editNum} of ${edits.length}: start_line (${edit.start_line}) cannot be greater than end_line (${edit.end_line}).`,
ERROR_CODES.INVALID_ARGS,
{ editsApplied: editIndex }
);
}
if (edit.end_line > contentLines.length) {
throw new CodedError(
`Edit ${editNum} of ${edits.length}: end_line (${edit.end_line}) is greater than the file line count (${contentLines.length}).`,
ERROR_CODES.INVALID_ARGS,
{ editsApplied: editIndex }
);
}
contentLines.splice(edit.start_line - 1, edit.end_line - edit.start_line + 1, ...splitReplacementLines(edit.newText));
modifiedContent = contentLines.join("\n");
continue;
}
if (edit.oldText === undefined) {
throw new CodedError(
`Edit ${editNum} of ${edits.length}: provide oldText, start_line/end_line, or insert_at_line.`,
ERROR_CODES.INVALID_ARGS,
{ editsApplied: editIndex }
);
}
const normalizedOld = normalizeLineEndings(edit.oldText);
let matchFound = false;
// 1. Try exact match
if (modifiedContent.includes(normalizedOld)) {
modifiedContent = modifiedContent.replace(normalizedOld, normalizedNew);
continue;
}
// 2. Try whitespace-trimmed line match
const oldLines = normalizedOld.split("\n");
const textEditContentLines = modifiedContent.split("\n");
for (let i = 0; i <= textEditContentLines.length - oldLines.length; i++) {
const potentialMatchLines = textEditContentLines.slice(i, i + oldLines.length);
const isTrimmedMatch = oldLines.every((oldLine, j) => {
return oldLine.trim() === potentialMatchLines[j].trim();
});
if (isTrimmedMatch) {
// Preserve original indentation: detect indent of first matched line,
// then apply relative indentation to replacement lines
const originalIndent = textEditContentLines[i].match(/^\s*/)?.[0] || "";
const newLines = normalizedNew.split("\n").map((line, j) => {
if (j === 0) return originalIndent + line.trimStart();
// For subsequent lines, preserve relative indentation
const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || "";
const newIndent = line.match(/^\s*/)?.[0] || "";
if (oldIndent && newIndent) {
const relativeIndent = newIndent.length - oldIndent.length;
return originalIndent + " ".repeat(Math.max(0, relativeIndent)) + line.trimStart();
}
return line;
});
textEditContentLines.splice(i, oldLines.length, ...newLines);
modifiedContent = textEditContentLines.join("\n");
matchFound = true;
break;
}
}
if (matchFound) {
continue;
}
// 3. If still no match, try fuzzy search
let bestMatch = { score: 0, index: -1 };
let ambiguousMatchCount = 0;
const AMBIGUITY_TOLERANCE = 0.05; // matches within 5% of best are "ambiguous"
for (let i = 0; i <= textEditContentLines.length - oldLines.length; i++) {
const potentialMatchLines = textEditContentLines.slice(i, i + oldLines.length);
const score = calculateSimilarity(oldLines, potentialMatchLines);
if (score > bestMatch.score) {
bestMatch = { score, index: i };
ambiguousMatchCount = 1;
} else if (score >= bestMatch.score - AMBIGUITY_TOLERANCE && score >= FUZZY_MATCH_THRESHOLD) {
ambiguousMatchCount++;
}
}
// 4. Handle fuzzy search outcome
if (bestMatch.score >= FUZZY_MATCH_THRESHOLD) {
const contextLines = 3;
const startContext = Math.max(0, bestMatch.index - contextLines);
const endContext = Math.min(
textEditContentLines.length,
bestMatch.index + oldLines.length + contextLines
);
const snippet = textEditContentLines
.slice(startContext, endContext)
.map((line, idx) => `${startContext + idx + 1} | ${line}`)
.join("\n");
const matchedLines = textEditContentLines.slice(bestMatch.index, bestMatch.index + oldLines.length);
let firstDivergence = "";
for (let d = 0; d < oldLines.length; d++) {
if (oldLines[d].trim() !== matchedLines[d]?.trim()) {
firstDivergence = `\nFirst difference at line ${bestMatch.index + d + 1}:\n Expected: ${JSON.stringify(oldLines[d].trim())}\n Found: ${JSON.stringify((matchedLines[d] || "").trim())}`;
break;
}
}
const ambiguityWarning = ambiguousMatchCount > 1
? `\n\nWarning: ${ambiguousMatchCount} locations matched with similar scores. The best match is shown above.`
: "";
const feedbackMessage = `Edit ${editNum} of ${edits.length}: text not found exactly or with trimmed whitespace. Found a potential fuzzy match with ${Math.round(
bestMatch.score * 100
)}% similarity starting at line ${
bestMatch.index + 1
}:${firstDivergence}\n\`\`\`\n${snippet}\n\`\`\`${ambiguityWarning}`;
throw new CodedError(feedbackMessage, ERROR_CODES.EDIT_MATCH_UNCERTAIN, { editsApplied: editIndex });
} else {
const numberedContext = options.showLineNumbersOnError
? `\n\nFile excerpt:\n\`\`\`\n${formatNumberedSnippet(textEditContentLines)}\n\`\`\``
: "";
throw new CodedError(
`Edit ${editNum} of ${edits.length}: could not find a match (file has ${totalLineCount} lines). Verify the file content with 'read_file' before retrying.\nSearched for:\n${edit.oldText}${numberedContext}`,
ERROR_CODES.EDIT_MATCH_NOT_FOUND,
{ editsApplied: editIndex }
);
}
}
// If all edits succeeded without throwing:
const diff = createUnifiedDiff(content, modifiedContent, filePath);
let numBackticks = 3;
while (diff.includes("`".repeat(numBackticks))) numBackticks++;
const formattedDiff = `${"`".repeat(numBackticks)}diff\n${diff}${"`".repeat(
numBackticks
)}\n\n`;
if (!dryRun) {
await overwriteFileWithinRootPolicy(filePath, modifiedContent, encoding);
}
return formattedDiff;
}
export async function overwriteFileWithinRootPolicy(
filePath: string,
content: string,
encoding: SupportedEncoding = "utf-8"
): Promise<void> {
const parentDir = normalizePath(path.dirname(filePath));
if (isResolvedPathWithinAllowedDirectory(parentDir)) {
await atomicWriteFile(filePath, content, encoding);
return;
}
await fs.writeFile(filePath, content, { encoding, flag: "w" });
}
// --- Atomic Write Helper ---
export async function atomicWriteFile(
filePath: string,
content: string,
encoding: SupportedEncoding = "utf-8"
): Promise<void> {
const tempPath = `${filePath}.${randomBytes(6).toString("hex")}.tmp`;
const untrackTempPath = trackTempFileForCleanup(tempPath);
try {
await fs.writeFile(tempPath, content, { encoding });
// On Windows, rename can fail with EPERM if the target is locked by another
// process (e.g., antivirus scanners, editor file watchers). Retry with delay.
const maxRetries = process.platform === "win32" ? 3 : 0;
let lastError: unknown;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
await fs.rename(tempPath, filePath);
untrackTempPath();
return;
} catch (renameError: unknown) {
lastError = renameError;
const isRetryable =
process.platform === "win32" &&
hasErrorCode(renameError) &&
(renameError.code === "EPERM" || renameError.code === "EBUSY") &&
attempt < maxRetries;
if (isRetryable) {
await new Promise((resolve) => setTimeout(resolve, 100 * (attempt + 1)));
} else {
throw renameError;
}
}
}
throw lastError;
} catch (error) {
try {
await fs.unlink(tempPath);
} catch {
// Ignore cleanup errors
} finally {
untrackTempPath();
}
throw error;
}
}
// --- Helper: Format file size ---
export function formatSize(bytes: number): string {
const units = ["B", "KB", "MB", "GB", "TB"];
if (!isFinite(bytes) || bytes <= 0) return "0 B";
const i = Math.floor(Math.log(bytes) / Math.log(1024));
if (i < 0 || i === 0) return `${bytes} ${units[0]}`;
const unitIndex = Math.min(i, units.length - 1);
return `${(bytes / Math.pow(1024, unitIndex)).toFixed(2)} ${units[unitIndex]}`;
}
// --- Helper: Memory-efficient tail (last N lines) ---
export async function tailFile(filePath: string, numLines: number, encoding: BufferEncoding = "utf-8"): Promise<string> {
if (numLines <= 0) return "";
const CHUNK_SIZE = 1024;
const stats = await fs.stat(filePath);
if (stats.size === 0) return "";
const fileHandle = await fs.open(filePath, "r");
try {
const lines: string[] = [];
let position = stats.size;
const chunk = Buffer.alloc(CHUNK_SIZE);
let linesFound = 0;
let remainingText = "";
while (position > 0 && linesFound < numLines) {
const size = Math.min(CHUNK_SIZE, position);
position -= size;
const { bytesRead } = await fileHandle.read({ buffer: chunk, offset: 0, length: size, position });
if (!bytesRead) break;
const readData = chunk.subarray(0, bytesRead).toString(encoding);
const chunkText = readData + remainingText;
const chunkLines = normalizeLineEndings(chunkText).split("\n");
if (position > 0) {
remainingText = chunkLines[0];
chunkLines.shift();
}
for (let i = chunkLines.length - 1; i >= 0 && linesFound < numLines; i--) {
lines.unshift(chunkLines[i]);
linesFound++;
}
}
return lines.join("\n");
} finally {
await fileHandle.close();
}
}
// --- Helper: Memory-efficient head (first N lines) ---
export async function headFile(filePath: string, numLines: number, encoding: BufferEncoding = "utf-8"): Promise<string> {
if (numLines <= 0) return "";
const fileHandle = await fs.open(filePath, "r");
try {
const lines: string[] = [];
let buffer = "";
let bytesRead = 0;
const chunk = Buffer.alloc(1024);
while (lines.length < numLines) {
const result = await fileHandle.read({ buffer: chunk, offset: 0, length: chunk.length, position: bytesRead });
if (result.bytesRead === 0) break;
bytesRead += result.bytesRead;
buffer += chunk.subarray(0, result.bytesRead).toString(encoding);
const newLineIndex = buffer.lastIndexOf("\n");
if (newLineIndex !== -1) {
const completeLines = buffer.slice(0, newLineIndex).split("\n");
buffer = buffer.slice(newLineIndex + 1);
for (const line of completeLines) {
lines.push(line);
if (lines.length >= numLines) break;
}
}
}
if (buffer.length > 0 && lines.length < numLines) {
lines.push(buffer);
}
return lines.join("\n");
} finally {
await fileHandle.close();
}
}
// --- Helper: Stream file as base64 ---
export async function readFileAsBase64Stream(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
const stream = fsSync.createReadStream(filePath);
const chunks: Buffer[] = [];
stream.on("data", (chunk: string | Buffer) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
stream.on("end", () => resolve(Buffer.concat(chunks).toString("base64")));
stream.on("error", (err) => reject(err));
});
}
// --- Centralized Error Handler ---
export function mapErrorCode(error: unknown): string {
if (hasErrorCode(error)) {
if (Object.values(ERROR_CODES).includes(error.code)) return error.code;
if (error.code === "ENOENT") return ERROR_CODES.PATH_NOT_FOUND;
if (error.code === "EACCES" || error.code === "EPERM") return ERROR_CODES.PERMISSION_DENIED;
if (error.code === "EEXIST" || error.code === "ENOTEMPTY") return ERROR_CODES.DESTINATION_EXISTS;
}
return ERROR_CODES.FILESYSTEM_ERROR;
}
export function withErrorHandling<T extends Record<string, unknown>>(
toolName: string,
handler: (args: T) => Promise<CallToolResult>
): (args: T) => Promise<CallToolResult> {
return async (args: T): Promise<CallToolResult> => {
try {
return await handler(args);
} catch (error: unknown) {
const mappedCode = mapErrorCode(error);
const message = error instanceof Error ? error.message : String(error);
console.error(`Error executing tool ${toolName}: [${mappedCode}] ${message}`);
return {
content: [{ type: "text" as const, text: `Error: ${message}` }],
isError: true,
result: { errorCode: mappedCode },
};
}
};
}