localmcp-cli 0.0.1 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1122 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream, createWriteStream } from "node:fs";
3
+ import {
4
+ access,
5
+ appendFile,
6
+ cp,
7
+ mkdir,
8
+ open,
9
+ readdir,
10
+ readFile,
11
+ rename,
12
+ rm,
13
+ stat,
14
+ writeFile,
15
+ } from "node:fs/promises";
16
+ import path from "node:path";
17
+ import { Readable } from "node:stream";
18
+ import { pipeline } from "node:stream/promises";
19
+ import { CONTROL_SECURITY_SCHEMES, okResult, toolMeta } from "../core/protocol.js";
20
+ import { applyPatchOperations } from "./apply-patch.js";
21
+
22
+ const MAX_LINE_READ_FILE_BYTES = 16 * 1024 * 1024;
23
+ const MAX_STAT_HASH_BYTES = 50 * 1024 * 1024;
24
+ const MAX_TRANSFER_CHUNK_BYTES = 1048576;
25
+ const MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024;
26
+ const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
27
+ const MAX_SEARCH_FILE_BYTES = 2 * 1024 * 1024;
28
+ const DEFAULT_SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", "__pycache__"]);
29
+
30
+ function sha256Buffer(buf) {
31
+ return createHash("sha256").update(buf).digest("hex");
32
+ }
33
+
34
+ async function sha256File(filePath) {
35
+ return new Promise((resolve, reject) => {
36
+ const hash = createHash("sha256");
37
+ const stream = createReadStream(filePath);
38
+ stream.on("data", chunk => hash.update(chunk));
39
+ stream.on("error", reject);
40
+ stream.on("end", () => resolve(hash.digest("hex")));
41
+ });
42
+ }
43
+
44
+ async function pathExists(targetPath) {
45
+ try {
46
+ await access(targetPath);
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ function detectEol(text) {
54
+ return text.includes("\r\n") ? "\r\n" : "\n";
55
+ }
56
+
57
+ function normalizeToEol(text, eol) {
58
+ return String(text ?? "").replace(/\r\n/g, "\n").replace(/\n/g, eol);
59
+ }
60
+
61
+ function findAllOccurrences(haystack, needle) {
62
+ if (!needle) return [];
63
+ const positions = [];
64
+ let from = 0;
65
+ while (from <= haystack.length) {
66
+ const idx = haystack.indexOf(needle, from);
67
+ if (idx === -1) break;
68
+ positions.push(idx);
69
+ from = idx + needle.length;
70
+ }
71
+ return positions;
72
+ }
73
+
74
+ function offsetToLineNumber(text, offset) {
75
+ let line = 1;
76
+ for (let i = 0; i < offset && i < text.length; i += 1) {
77
+ if (text.charCodeAt(i) === 10) line += 1;
78
+ }
79
+ return line;
80
+ }
81
+
82
+ function buildCompactDiff(beforeText, afterText, displayPath, maxChars = 4000) {
83
+ const beforeLines = beforeText.replace(/\r\n/g, "\n").split("\n");
84
+ const afterLines = afterText.replace(/\r\n/g, "\n").split("\n");
85
+ let start = 0;
86
+ while (start < beforeLines.length && start < afterLines.length && beforeLines[start] === afterLines[start]) {
87
+ start += 1;
88
+ }
89
+ let endBefore = beforeLines.length - 1;
90
+ let endAfter = afterLines.length - 1;
91
+ while (endBefore >= start && endAfter >= start && beforeLines[endBefore] === afterLines[endAfter]) {
92
+ endBefore -= 1;
93
+ endAfter -= 1;
94
+ }
95
+ if (start > endBefore && start > endAfter) return "";
96
+
97
+ const ctxStart = Math.max(0, start - 2);
98
+ const ctxEndBefore = Math.min(beforeLines.length - 1, endBefore + 2);
99
+ const ctxEndAfter = Math.min(afterLines.length - 1, endAfter + 2);
100
+ const header = `--- ${displayPath}\n+++ ${displayPath}\n@@ -${ctxStart + 1},${ctxEndBefore - ctxStart + 1} +${ctxStart + 1},${ctxEndAfter - ctxStart + 1} @@`;
101
+ const body = [];
102
+ for (let i = ctxStart; i < start; i += 1) body.push(` ${beforeLines[i]}`);
103
+ for (let i = start; i <= endBefore; i += 1) body.push(`-${beforeLines[i]}`);
104
+ for (let i = start; i <= endAfter; i += 1) body.push(`+${afterLines[i]}`);
105
+ for (let i = endAfter + 1; i <= ctxEndAfter; i += 1) body.push(` ${afterLines[i]}`);
106
+ const full = `${header}\n${body.join("\n")}`;
107
+ return full.length <= maxChars ? full : `${full.slice(0, maxChars)}\n... [diff truncated]`;
108
+ }
109
+
110
+ function globToRegExp(pattern) {
111
+ let regex = "^";
112
+ for (let i = 0; i < pattern.length; i += 1) {
113
+ const ch = pattern[i];
114
+ if (ch === "*") {
115
+ if (pattern[i + 1] === "*") {
116
+ if (pattern[i + 2] === "/") {
117
+ regex += "(?:.*/)?";
118
+ i += 2;
119
+ } else {
120
+ regex += ".*";
121
+ i += 1;
122
+ }
123
+ } else {
124
+ regex += "[^/]*";
125
+ }
126
+ } else if (ch === "?") {
127
+ regex += "[^/]";
128
+ } else if ("\\^$+?.()|[]{}".includes(ch)) {
129
+ regex += `\\${ch}`;
130
+ } else {
131
+ regex += ch;
132
+ }
133
+ }
134
+ regex += "$";
135
+ return new RegExp(regex, "i");
136
+ }
137
+
138
+ function matchesFilePattern(relPath, fileName, rawPattern) {
139
+ if (!rawPattern) return true;
140
+ const pattern = rawPattern.replaceAll("\\", "/").trim();
141
+ if (!pattern) return true;
142
+ if (!/[*?]/.test(pattern)) {
143
+ const lower = pattern.toLowerCase();
144
+ return relPath.toLowerCase().includes(lower) || fileName.toLowerCase().includes(lower);
145
+ }
146
+ const re = globToRegExp(pattern);
147
+ return pattern.includes("/") ? re.test(relPath) : re.test(fileName) || re.test(relPath);
148
+ }
149
+
150
+ async function walkDirectory(dirPath, { maxDepth, includeHidden, maxEntries, assertPublicPath }) {
151
+ const entries = [];
152
+ let truncated = false;
153
+
154
+ async function visit(currentDir, depth) {
155
+ if (truncated) return;
156
+ const dirents = await readdir(currentDir, { withFileTypes: true });
157
+ dirents.sort((a, b) => a.name.localeCompare(b.name));
158
+ for (const dirent of dirents) {
159
+ if (!includeHidden && dirent.name.startsWith(".")) continue;
160
+ if (entries.length >= maxEntries) {
161
+ truncated = true;
162
+ return;
163
+ }
164
+ const fullPath = path.join(currentDir, dirent.name);
165
+ try { assertPublicPath(fullPath); } catch { continue; }
166
+ const relPath = path.relative(dirPath, fullPath).replaceAll("\\", "/");
167
+ const type = dirent.isDirectory() ? "directory" : dirent.isSymbolicLink() ? "symlink" : "file";
168
+ entries.push({ name: dirent.name, path: relPath, type });
169
+ if (dirent.isDirectory() && depth < maxDepth) {
170
+ await visit(fullPath, depth + 1);
171
+ }
172
+ }
173
+ }
174
+
175
+ await visit(dirPath, 1);
176
+ return { entries, truncated };
177
+ }
178
+
179
+ export function createFilesystemTools({ config, auth }) {
180
+ return [
181
+ {
182
+ name: "list_directory",
183
+ title: "List directory",
184
+ description: "List files and folders under LOCAL_CONTROL_ROOTS without reading contents or modifying files.",
185
+ inputSchema: {
186
+ type: "object",
187
+ properties: {
188
+ path: { type: "string", description: "Directory to list. Relative paths resolve from server cwd." },
189
+ depth: { type: "integer", minimum: 1, maximum: 3, description: "Recursive depth from 1 to 3." },
190
+ includeHidden: { type: "boolean", description: "Include dotfiles and dotfolders." },
191
+ },
192
+ additionalProperties: false,
193
+ },
194
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
195
+ _meta: toolMeta("Listing local directory", "Local directory listing ready"),
196
+ async handler(args, { authContext }) {
197
+ auth.requireReadAuth(authContext);
198
+ const dirPath = await config.resolveAllowedPath(args.path || ".", { mustExist: true, accessMode: "read" });
199
+ const depth = Math.min(Math.max(Number(args.depth ?? 1) || 1, 1), 3);
200
+ const includeHidden = Boolean(args.includeHidden);
201
+ const { entries, truncated } = await walkDirectory(dirPath, {
202
+ maxDepth: depth,
203
+ includeHidden,
204
+ assertPublicPath: config.assertPublicPath,
205
+ maxEntries: config.state.maxDirectoryEntries,
206
+ });
207
+ const payload = { root: dirPath, count: entries.length, truncated, entries };
208
+ return okResult(JSON.stringify(payload, null, 2), payload);
209
+ },
210
+ },
211
+ {
212
+ name: "read_file",
213
+ title: "Read file",
214
+ description:
215
+ "Read a UTF-8 or base64 file from LOCAL_CONTROL_ROOTS. Supports DSH/Codex 1-based line pagination (offset/limit or startLine/endLine/maxLines with line numbers) and byte-offset chunking (byteOffset/maxBytes).",
216
+ inputSchema: {
217
+ type: "object",
218
+ properties: {
219
+ path: { type: "string", minLength: 1 },
220
+ encoding: { type: "string", enum: ["utf8", "base64"] },
221
+ maxBytes: { type: "integer", minimum: 1, maximum: 1048576 },
222
+ offset: {
223
+ type: "integer",
224
+ minimum: 0,
225
+ description: "1-based start line in utf8 line mode (DSH/Codex style), or byte offset in base64 mode.",
226
+ },
227
+ limit: {
228
+ type: "integer",
229
+ minimum: 1,
230
+ maximum: 2000,
231
+ description: "Maximum lines to return in line mode (default 400, DSH/Codex style).",
232
+ },
233
+ byteOffset: {
234
+ type: "integer",
235
+ minimum: 0,
236
+ description: "Explicit byte offset for chunked reads in utf8 or base64 mode.",
237
+ },
238
+ startLine: { type: "integer", minimum: 1, description: "1-based inclusive start line (UTF-8 only)." },
239
+ endLine: { type: "integer", minimum: 1, description: "1-based inclusive end line (UTF-8 only)." },
240
+ maxLines: { type: "integer", minimum: 1, maximum: 2000, description: "Alias for limit in line mode." },
241
+ withLineNumbers: { type: "boolean", description: "Prefix returned UTF-8 lines with 1-based line numbers." },
242
+ },
243
+ required: ["path"],
244
+ additionalProperties: false,
245
+ },
246
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
247
+ _meta: toolMeta("Reading local file", "Local file read"),
248
+ async handler(args, { authContext }) {
249
+ auth.requireReadAuth(authContext);
250
+ if (!args.path || typeof args.path !== "string") {
251
+ throw new Error("path is required.");
252
+ }
253
+ const filePath = await config.resolveAllowedPath(args.path, { mustExist: true, accessMode: "read" });
254
+ const encoding = args.encoding === "base64" ? "base64" : "utf8";
255
+ const byteLimit = Math.min(
256
+ Math.max(Number(args.maxBytes ?? config.state.maxReadBytes) || config.state.maxReadBytes, 1),
257
+ config.state.maxReadBytes,
258
+ 1048576
259
+ );
260
+
261
+ const info = await stat(filePath);
262
+ if (!info.isFile()) {
263
+ throw new Error(`Target "${filePath}" is not a regular file.`);
264
+ }
265
+
266
+ const explicitLineArgs =
267
+ args.startLine !== undefined ||
268
+ args.endLine !== undefined ||
269
+ args.maxLines !== undefined ||
270
+ args.limit !== undefined ||
271
+ args.withLineNumbers !== undefined;
272
+
273
+ const dshLineOffset = encoding === "utf8" && args.byteOffset === undefined && args.offset !== undefined;
274
+ const lineMode = encoding === "utf8" && args.byteOffset === undefined && (explicitLineArgs || dshLineOffset);
275
+
276
+ if (lineMode) {
277
+ if (info.size > MAX_LINE_READ_FILE_BYTES) {
278
+ throw new Error(
279
+ `File size (${info.size} bytes) exceeds line-range read limit (${MAX_LINE_READ_FILE_BYTES} bytes). Use byteOffset or transfer_file read_chunk instead.`
280
+ );
281
+ }
282
+ const raw = await readFile(filePath, "utf8");
283
+ const normalized = raw.replace(/\r\n/g, "\n");
284
+ const allLines = normalized === "" ? [] : normalized.split("\n");
285
+ if (allLines.length > 0 && normalized.endsWith("\n")) allLines.pop();
286
+ const totalLines = allLines.length;
287
+
288
+ const startLine = Math.max(1, Number(args.startLine ?? args.offset ?? 1) || 1);
289
+ const requestedMaxLines = args.limit ?? args.maxLines;
290
+ const defaultLineCount = requestedMaxLines !== undefined ? Number(requestedMaxLines) : 400;
291
+ const defaultEnd =
292
+ args.endLine !== undefined
293
+ ? Number(args.endLine)
294
+ : startLine + defaultLineCount - 1;
295
+ const maxLineCap = Math.min(2000, Math.max(1, requestedMaxLines !== undefined ? Number(requestedMaxLines) : 2000));
296
+ const requestedEnd = Math.min(totalLines, Math.max(startLine - 1, defaultEnd));
297
+ const cappedEnd = Math.min(requestedEnd, startLine + maxLineCap - 1);
298
+
299
+ // Default to numbered lines when using DSH/Codex offset/limit pagination unless explicitly disabled.
300
+ const useLineNumbers =
301
+ args.withLineNumbers !== undefined
302
+ ? Boolean(args.withLineNumbers)
303
+ : args.offset !== undefined || args.limit !== undefined;
304
+
305
+ const selected = [];
306
+ let byteCount = 0;
307
+ let truncatedByBytes = false;
308
+ let actualEnd = startLine - 1;
309
+
310
+ for (let lineNum = startLine; lineNum <= cappedEnd; lineNum += 1) {
311
+ const lineText = allLines[lineNum - 1] ?? "";
312
+ const formatted = useLineNumbers ? `${lineNum}: ${lineText}` : lineText;
313
+ const additionBytes = Buffer.byteLength(selected.length > 0 ? `\n${formatted}` : formatted, "utf8");
314
+ if (byteCount + additionBytes > byteLimit && selected.length > 0) {
315
+ truncatedByBytes = true;
316
+ break;
317
+ }
318
+ selected.push(formatted);
319
+ byteCount += additionBytes;
320
+ actualEnd = lineNum;
321
+ }
322
+
323
+ const content = selected.join("\n");
324
+ const eof = actualEnd >= totalLines;
325
+ const truncated = truncatedByBytes || actualEnd < totalLines;
326
+ const payload = {
327
+ path: filePath,
328
+ encoding: "utf8",
329
+ size: info.size,
330
+ totalLines,
331
+ startLine: totalLines === 0 ? 0 : Math.min(startLine, totalLines),
332
+ endLine: totalLines === 0 ? 0 : Math.max(0, actualEnd),
333
+ linesRead: selected.length,
334
+ bytesRead: Buffer.byteLength(content, "utf8"),
335
+ eof,
336
+ truncated,
337
+ content,
338
+ };
339
+ return okResult(content, payload);
340
+ }
341
+
342
+ const byteOffset = Math.max(0, Number(args.byteOffset ?? args.offset ?? 0) || 0);
343
+ if (byteOffset >= info.size) {
344
+ const payload = {
345
+ path: filePath,
346
+ encoding,
347
+ size: info.size,
348
+ byteOffset,
349
+ bytesRead: 0,
350
+ nextOffset: info.size,
351
+ eof: true,
352
+ truncated: false,
353
+ content: "",
354
+ };
355
+ return okResult("", payload);
356
+ }
357
+
358
+ const readSize = Math.min(info.size - byteOffset, byteLimit);
359
+ const handle = await open(filePath, "r");
360
+ let buf;
361
+ try {
362
+ buf = Buffer.alloc(readSize);
363
+ const { bytesRead } = await handle.read(buf, 0, readSize, byteOffset);
364
+ buf = buf.subarray(0, bytesRead);
365
+ } finally {
366
+ await handle.close();
367
+ }
368
+ const content = buf.toString(encoding);
369
+ const nextOffset = byteOffset + buf.length;
370
+ const eof = nextOffset >= info.size;
371
+ const payload = {
372
+ path: filePath,
373
+ encoding,
374
+ size: info.size,
375
+ byteOffset,
376
+ bytesRead: buf.length,
377
+ nextOffset,
378
+ eof,
379
+ truncated: !eof,
380
+ content,
381
+ };
382
+ return okResult(content, payload);
383
+ },
384
+ },
385
+ {
386
+ name: "write_file",
387
+ title: "Write file",
388
+ description: "Create, overwrite, or append UTF-8 or base64 binary content to a file under LOCAL_CONTROL_ROOTS.",
389
+ inputSchema: {
390
+ type: "object",
391
+ properties: {
392
+ path: { type: "string", minLength: 1 },
393
+ content: { type: "string" },
394
+ encoding: { type: "string", enum: ["utf8", "base64"], description: "Content encoding (default utf8)." },
395
+ mode: { type: "string", enum: ["create", "overwrite", "append"] },
396
+ control_pin: { type: "string", description: "Optional fallback PIN when not authenticated by secret-key or OAuth." },
397
+ },
398
+ required: ["path", "content"],
399
+ additionalProperties: false,
400
+ },
401
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false, idempotentHint: false },
402
+ _meta: toolMeta("Writing local file", "Local file write finished", CONTROL_SECURITY_SCHEMES),
403
+ async handler(args, { authContext }) {
404
+ auth.requireCapability("ALLOW_WRITES", config.state.allowWrites, args.control_pin, authContext);
405
+ if (!args.path || typeof args.path !== "string") {
406
+ throw new Error("path is required.");
407
+ }
408
+ const mode = args.mode || "overwrite";
409
+ const encoding = args.encoding === "base64" ? "base64" : "utf8";
410
+ const filePath = await config.resolveAllowedPath(args.path, { mustExist: false });
411
+ await mkdir(path.dirname(filePath), { recursive: true });
412
+
413
+ const rawContent = String(args.content ?? "");
414
+ const buffer =
415
+ encoding === "base64"
416
+ ? Buffer.from(rawContent.replace(/\s+/g, ""), "base64")
417
+ : Buffer.from(rawContent, "utf8");
418
+
419
+ if (mode === "append") {
420
+ await appendFile(filePath, buffer);
421
+ } else {
422
+ await writeFile(filePath, buffer, { flag: mode === "create" ? "wx" : "w" });
423
+ }
424
+
425
+ const info = await stat(filePath);
426
+ const payload = {
427
+ path: filePath,
428
+ mode,
429
+ encoding,
430
+ bytesWritten: buffer.length,
431
+ totalSize: info.size,
432
+ sha256: sha256Buffer(buffer),
433
+ };
434
+ return okResult(JSON.stringify(payload, null, 2), payload);
435
+ },
436
+ },
437
+ {
438
+ name: "edit_file",
439
+ title: "Edit file (partial replace)",
440
+ description:
441
+ "Atomically apply exact search-and-replace edits (DSH/Codex old_string -> new_string) or 1-based line-range partial replacement to a UTF-8 file while preserving line endings.",
442
+ inputSchema: {
443
+ type: "object",
444
+ properties: {
445
+ path: { type: "string", minLength: 1 },
446
+ old_string: { type: "string", description: "Exact text to locate and replace." },
447
+ new_string: { type: "string", description: "Replacement text for old_string." },
448
+ replace_all: { type: "boolean", description: "Replace all occurrences of old_string." },
449
+ expected_replacements: { type: "integer", minimum: 1, description: "Expected number of matches (default 1 unless replace_all is true)." },
450
+ edits: {
451
+ type: "array",
452
+ minItems: 1,
453
+ maxItems: 50,
454
+ description: "Batch of sequential search-and-replace edits validated atomically.",
455
+ items: {
456
+ type: "object",
457
+ properties: {
458
+ old_string: { type: "string", minLength: 1 },
459
+ new_string: { type: "string" },
460
+ replace_all: { type: "boolean" },
461
+ expected_replacements: { type: "integer", minimum: 1 },
462
+ },
463
+ required: ["old_string", "new_string"],
464
+ additionalProperties: false,
465
+ },
466
+ },
467
+ startLine: { type: "integer", minimum: 1, description: "1-based inclusive start line for line-range replacement." },
468
+ endLine: { type: "integer", minimum: 0, description: "1-based inclusive end line (use endLine < startLine to insert before startLine)." },
469
+ content: { type: "string", description: "Replacement block for line-range replacement." },
470
+ dryRun: { type: "boolean", description: "Validate and return diff without writing to disk." },
471
+ control_pin: { type: "string", description: "Optional fallback PIN when not authenticated by secret-key or OAuth." },
472
+ },
473
+ required: ["path"],
474
+ additionalProperties: false,
475
+ },
476
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false, idempotentHint: false },
477
+ _meta: toolMeta("Editing local file", "Local file edit finished", CONTROL_SECURITY_SCHEMES),
478
+ async handler(args, { authContext }) {
479
+ auth.requireCapability("ALLOW_WRITES", config.state.allowWrites, args.control_pin, authContext);
480
+ const filePath = await config.resolveAllowedPath(args.path, { mustExist: true });
481
+ const info = await stat(filePath);
482
+ if (!info.isFile()) {
483
+ throw new Error(`Target "${filePath}" is not a regular file.`);
484
+ }
485
+ if (info.size > MAX_LINE_READ_FILE_BYTES) {
486
+ throw new Error(`File size (${info.size} bytes) exceeds edit_file limit (${MAX_LINE_READ_FILE_BYTES} bytes).`);
487
+ }
488
+
489
+ const original = await readFile(filePath, "utf8");
490
+ const eol = detectEol(original);
491
+ const totalLinesBefore = original === "" ? 0 : original.replace(/\r\n/g, "\n").split("\n").length;
492
+ let updated = original;
493
+ let totalReplacements = 0;
494
+ let editsApplied = 0;
495
+
496
+ if (args.startLine !== undefined) {
497
+ if (args.content === undefined) {
498
+ throw new Error("content is required when using startLine/endLine replacement.");
499
+ }
500
+ const normalized = original.replace(/\r\n/g, "\n");
501
+ const hadTrailingNewline = normalized.endsWith("\n");
502
+ const lines = normalized === "" ? [] : normalized.split("\n");
503
+ if (hadTrailingNewline) lines.pop();
504
+
505
+ const startLine = Number(args.startLine);
506
+ const endLine = args.endLine !== undefined ? Number(args.endLine) : startLine;
507
+ if (startLine < 1 || startLine > lines.length + 1) {
508
+ throw new Error(`startLine (${startLine}) is out of range (1..${lines.length + 1}).`);
509
+ }
510
+ if (endLine > lines.length) {
511
+ throw new Error(`endLine (${endLine}) exceeds total lines (${lines.length}).`);
512
+ }
513
+
514
+ const replacementRaw = String(args.content).replace(/\r\n/g, "\n");
515
+ const replacementLines = replacementRaw === "" ? [] : replacementRaw.split("\n");
516
+ if (replacementLines.length > 0 && replacementRaw.endsWith("\n")) {
517
+ replacementLines.pop();
518
+ }
519
+
520
+ const deleteCount = endLine >= startLine ? endLine - startLine + 1 : 0;
521
+ lines.splice(startLine - 1, deleteCount, ...replacementLines);
522
+ updated = lines.length === 0 ? "" : lines.join(eol) + (hadTrailingNewline ? eol : "");
523
+ totalReplacements = 1;
524
+ editsApplied = 1;
525
+ } else {
526
+ const editList = Array.isArray(args.edits)
527
+ ? args.edits
528
+ : args.old_string !== undefined
529
+ ? [
530
+ {
531
+ old_string: args.old_string,
532
+ new_string: args.new_string ?? "",
533
+ replace_all: Boolean(args.replace_all),
534
+ expected_replacements: args.expected_replacements,
535
+ },
536
+ ]
537
+ : [];
538
+
539
+ if (editList.length === 0) {
540
+ throw new Error("Provide old_string/new_string, edits[], or startLine/content.");
541
+ }
542
+
543
+ for (let i = 0; i < editList.length; i += 1) {
544
+ const item = editList[i];
545
+ if (!item.old_string) {
546
+ throw new Error(`Edit #${i + 1} has an empty old_string.`);
547
+ }
548
+ const needle = normalizeToEol(item.old_string, eol);
549
+ const replacement = normalizeToEol(item.new_string ?? "", eol);
550
+ const matches = findAllOccurrences(updated, needle);
551
+
552
+ if (matches.length === 0) {
553
+ throw new Error(`Edit #${i + 1}: old_string not found in "${filePath}".`);
554
+ }
555
+ if (item.expected_replacements !== undefined && matches.length !== item.expected_replacements) {
556
+ const linesList = matches.slice(0, 5).map(pos => offsetToLineNumber(updated, pos)).join(", ");
557
+ throw new Error(
558
+ `Edit #${i + 1}: expected ${item.expected_replacements} occurrence(s), found ${matches.length} (lines: ${linesList}).`
559
+ );
560
+ }
561
+ if (!item.replace_all && item.expected_replacements === undefined && matches.length > 1) {
562
+ const linesList = matches.slice(0, 5).map(pos => offsetToLineNumber(updated, pos)).join(", ");
563
+ throw new Error(
564
+ `Edit #${i + 1}: old_string matched ${matches.length} times (lines: ${linesList}). Provide more context or set replace_all: true.`
565
+ );
566
+ }
567
+
568
+ updated = item.replace_all || (item.expected_replacements && item.expected_replacements > 1)
569
+ ? updated.split(needle).join(replacement)
570
+ : updated.replace(needle, () => replacement);
571
+ totalReplacements += matches.length;
572
+ editsApplied += 1;
573
+ }
574
+ }
575
+
576
+ const dryRun = Boolean(args.dryRun);
577
+ if (!dryRun) {
578
+ await writeFile(filePath, updated, "utf8");
579
+ }
580
+ const totalLinesAfter = updated === "" ? 0 : updated.replace(/\r\n/g, "\n").split("\n").length;
581
+ const diff = buildCompactDiff(original, updated, filePath);
582
+ const payload = {
583
+ ok: true,
584
+ path: filePath,
585
+ dryRun,
586
+ editsApplied,
587
+ replacements: totalReplacements,
588
+ totalLinesBefore,
589
+ totalLinesAfter,
590
+ diff,
591
+ };
592
+ return okResult(diff || JSON.stringify(payload, null, 2), payload);
593
+ },
594
+ },
595
+ {
596
+ name: "apply_patch",
597
+ title: "Apply patch",
598
+ description:
599
+ "Atomically apply a multi-file Codex ('*** Begin Patch' / '*** End Patch') or standard unified diff patch inside LOCAL_CONTROL_ROOTS.",
600
+ inputSchema: {
601
+ type: "object",
602
+ properties: {
603
+ patch: { type: "string", minLength: 1, description: "Patch text in Codex Begin/End Patch or unified diff format." },
604
+ cwd: { type: "string", description: "Optional base directory for relative paths inside the patch." },
605
+ dryRun: { type: "boolean", description: "Validate patch against files without modifying disk." },
606
+ control_pin: { type: "string", description: "Optional fallback PIN when not authenticated by secret-key or OAuth." },
607
+ },
608
+ required: ["patch"],
609
+ additionalProperties: false,
610
+ },
611
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false, idempotentHint: false },
612
+ _meta: toolMeta("Applying structured patch", "Structured patch applied", CONTROL_SECURITY_SCHEMES),
613
+ async handler(args, { authContext }) {
614
+ auth.requireCapability("ALLOW_WRITES", config.state.allowWrites, args.control_pin, authContext);
615
+ const payload = await applyPatchOperations({
616
+ patch: args.patch,
617
+ cwd: args.cwd,
618
+ dryRun: Boolean(args.dryRun),
619
+ resolvePath: (candidate, opts) => config.resolveAllowedPath(candidate, opts),
620
+ });
621
+ return okResult(JSON.stringify(payload, null, 2), payload);
622
+ },
623
+ },
624
+ {
625
+ name: "transfer_file",
626
+ title: "Transfer and manage files",
627
+ description:
628
+ "Inspect metadata, transfer binary/large files via verified base64 chunks (read_chunk/write_chunk), copy/move/delete local files, download from an HTTP(S) URL, or upload a local file to an HTTP(S) URL.",
629
+ inputSchema: {
630
+ type: "object",
631
+ properties: {
632
+ action: {
633
+ type: "string",
634
+ enum: ["stat", "read_chunk", "write_chunk", "copy", "move", "delete", "download_url", "upload_url"],
635
+ description: "File transfer or management operation.",
636
+ },
637
+ path: { type: "string", minLength: 1, description: "Target path (or source path for copy/move/upload_url)." },
638
+ destination: { type: "string", minLength: 1, description: "Destination path for copy/move." },
639
+ offset: { type: "integer", minimum: 0, description: "Byte offset for read_chunk or write_chunk." },
640
+ length: { type: "integer", minimum: 1, maximum: MAX_TRANSFER_CHUNK_BYTES, description: "Chunk size in bytes for read_chunk (default 262144)." },
641
+ dataBase64: { type: "string", description: "Base64-encoded chunk payload for write_chunk." },
642
+ truncate: { type: "boolean", description: "Truncate/recreate target file before writing chunk (for first chunk of write_chunk)." },
643
+ eof: { type: "boolean", description: "Marks final chunk in write_chunk to compute and optionally verify full-file SHA-256." },
644
+ expectedChunkSha256: { type: "string", description: "Optional SHA-256 hex digest to verify the write_chunk payload." },
645
+ expectedFileSha256: { type: "string", description: "Optional SHA-256 hex digest to verify full file on eof or download_url." },
646
+ overwrite: { type: "boolean", description: "Allow overwriting existing destination for copy/move/download_url." },
647
+ recursive: { type: "boolean", description: "Allow recursive copy or directory deletion." },
648
+ url: { type: "string", minLength: 1, description: "HTTP(S) URL for download_url or upload_url." },
649
+ method: { type: "string", enum: ["PUT", "POST"], description: "HTTP method for upload_url (default PUT, or POST when multipartField is set)." },
650
+ multipartField: { type: "string", minLength: 1, description: "Form field name for multipart/form-data upload_url (e.g. 'file')." },
651
+ contentType: { type: "string", description: "Optional Content-Type for raw upload_url (default application/octet-stream)." },
652
+ headers: {
653
+ type: "object",
654
+ additionalProperties: { type: "string" },
655
+ description: "Optional HTTP request headers for download_url or upload_url.",
656
+ },
657
+ timeoutMs: { type: "integer", minimum: 1000, maximum: 120000, description: "Timeout for download_url or upload_url (default 30000)." },
658
+ control_pin: { type: "string", description: "Optional fallback PIN for write/mutate/upload actions." },
659
+ },
660
+ required: ["action", "path"],
661
+ additionalProperties: false,
662
+ },
663
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },
664
+ _meta: toolMeta("Running file transfer operation", "File transfer operation finished", CONTROL_SECURITY_SCHEMES),
665
+ async handler(args, { authContext }) {
666
+ const action = args.action;
667
+
668
+ if (action === "stat") {
669
+ auth.requireReadAuth(authContext);
670
+ const resolved = await config.resolveAllowedPath(args.path, { mustExist: false, accessMode: "read" });
671
+ if (!(await pathExists(resolved))) {
672
+ const payload = { ok: true, action, path: resolved, exists: false };
673
+ return okResult(JSON.stringify(payload, null, 2), payload);
674
+ }
675
+ const real = await config.resolveAllowedPath(args.path, { mustExist: true, accessMode: "read" });
676
+ const info = await stat(real);
677
+ const type = info.isDirectory() ? "directory" : info.isFile() ? "file" : "other";
678
+ const payload = {
679
+ ok: true,
680
+ action,
681
+ path: real,
682
+ exists: true,
683
+ type,
684
+ size: info.size,
685
+ mtimeMs: Math.round(info.mtimeMs),
686
+ mtimeIso: info.mtime.toISOString(),
687
+ ...(info.isFile() && info.size <= MAX_STAT_HASH_BYTES ? { sha256: await sha256File(real) } : {}),
688
+ };
689
+ return okResult(JSON.stringify(payload, null, 2), payload);
690
+ }
691
+
692
+ if (action === "read_chunk") {
693
+ auth.requireReadAuth(authContext);
694
+ const filePath = await config.resolveAllowedPath(args.path, { mustExist: true, accessMode: "read" });
695
+ const info = await stat(filePath);
696
+ if (!info.isFile()) {
697
+ throw new Error(`Target "${filePath}" is not a regular file.`);
698
+ }
699
+ const offset = Math.max(0, Number(args.offset ?? 0) || 0);
700
+ const length = Math.min(Math.max(Number(args.length ?? 262144) || 262144, 1), MAX_TRANSFER_CHUNK_BYTES);
701
+ if (offset >= info.size) {
702
+ const payload = {
703
+ ok: true,
704
+ action,
705
+ path: filePath,
706
+ offset,
707
+ bytesRead: 0,
708
+ nextOffset: info.size,
709
+ totalSize: info.size,
710
+ eof: true,
711
+ chunkSha256: sha256Buffer(Buffer.alloc(0)),
712
+ dataBase64: "",
713
+ };
714
+ return okResult(JSON.stringify(payload, null, 2), payload);
715
+ }
716
+
717
+ const readSize = Math.min(info.size - offset, length);
718
+ const handle = await open(filePath, "r");
719
+ let buf;
720
+ try {
721
+ buf = Buffer.alloc(readSize);
722
+ const { bytesRead } = await handle.read(buf, 0, readSize, offset);
723
+ buf = buf.subarray(0, bytesRead);
724
+ } finally {
725
+ await handle.close();
726
+ }
727
+ const nextOffset = offset + buf.length;
728
+ const payload = {
729
+ ok: true,
730
+ action,
731
+ path: filePath,
732
+ offset,
733
+ bytesRead: buf.length,
734
+ nextOffset,
735
+ totalSize: info.size,
736
+ eof: nextOffset >= info.size,
737
+ chunkSha256: sha256Buffer(buf),
738
+ dataBase64: buf.toString("base64"),
739
+ };
740
+ return okResult(JSON.stringify(payload, null, 2), payload);
741
+ }
742
+
743
+ // All remaining actions mutate the filesystem or transfer data externally.
744
+ auth.requireCapability("ALLOW_WRITES", config.state.allowWrites, args.control_pin, authContext);
745
+
746
+ if (action === "write_chunk") {
747
+ if (typeof args.dataBase64 !== "string") {
748
+ throw new Error("dataBase64 is required for write_chunk.");
749
+ }
750
+ const filePath = await config.resolveAllowedPath(args.path, { mustExist: false });
751
+ await mkdir(path.dirname(filePath), { recursive: true });
752
+ const buf = Buffer.from(args.dataBase64.replace(/\s+/g, ""), "base64");
753
+ const chunkSha256 = sha256Buffer(buf);
754
+ if (args.expectedChunkSha256 && chunkSha256 !== args.expectedChunkSha256.toLowerCase()) {
755
+ throw new Error(`Chunk SHA-256 mismatch: expected ${args.expectedChunkSha256}, got ${chunkSha256}.`);
756
+ }
757
+
758
+ const offset = Math.max(0, Number(args.offset ?? 0) || 0);
759
+ const truncate = Boolean(args.truncate);
760
+ const exists = await pathExists(filePath);
761
+ const handle = await open(filePath, truncate || !exists ? "w+" : "r+");
762
+ try {
763
+ if (buf.length > 0) {
764
+ await handle.write(buf, 0, buf.length, offset);
765
+ }
766
+ } finally {
767
+ await handle.close();
768
+ }
769
+
770
+ const info = await stat(filePath);
771
+ let fileSha256;
772
+ if (args.eof || args.expectedFileSha256) {
773
+ fileSha256 = await sha256File(filePath);
774
+ if (args.expectedFileSha256 && fileSha256 !== args.expectedFileSha256.toLowerCase()) {
775
+ throw new Error(`File SHA-256 mismatch: expected ${args.expectedFileSha256}, got ${fileSha256}.`);
776
+ }
777
+ }
778
+
779
+ const payload = {
780
+ ok: true,
781
+ action,
782
+ path: filePath,
783
+ offset,
784
+ bytesWritten: buf.length,
785
+ nextOffset: offset + buf.length,
786
+ totalSize: info.size,
787
+ chunkSha256,
788
+ ...(fileSha256 ? { fileSha256 } : {}),
789
+ eof: Boolean(args.eof),
790
+ };
791
+ return okResult(JSON.stringify(payload, null, 2), payload);
792
+ }
793
+
794
+ if (action === "copy" || action === "move") {
795
+ if (!args.destination) {
796
+ throw new Error(`destination is required for ${action}.`);
797
+ }
798
+ const srcPath = await config.resolveAllowedPath(args.path, { mustExist: true });
799
+ const destPath = await config.resolveAllowedPath(args.destination, { mustExist: false });
800
+ if (!args.overwrite && (await pathExists(destPath))) {
801
+ throw new Error(`Destination "${destPath}" already exists. Set overwrite: true to replace it.`);
802
+ }
803
+ await mkdir(path.dirname(destPath), { recursive: true });
804
+ const srcInfo = await stat(srcPath);
805
+
806
+ if (action === "copy") {
807
+ if (srcInfo.isDirectory() && !args.recursive) {
808
+ throw new Error(`Source "${srcPath}" is a directory. Set recursive: true to copy directories.`);
809
+ }
810
+ await cp(srcPath, destPath, { recursive: Boolean(args.recursive), force: Boolean(args.overwrite) });
811
+ } else {
812
+ if (args.overwrite && (await pathExists(destPath))) {
813
+ await rm(destPath, { recursive: true, force: true });
814
+ }
815
+ try {
816
+ await rename(srcPath, destPath);
817
+ } catch (error) {
818
+ if (error?.code !== "EXDEV") throw error;
819
+ await cp(srcPath, destPath, { recursive: true, force: true });
820
+ await rm(srcPath, { recursive: true, force: true });
821
+ }
822
+ }
823
+
824
+ const destInfo = await stat(destPath);
825
+ const payload = {
826
+ ok: true,
827
+ action,
828
+ source: srcPath,
829
+ destination: destPath,
830
+ type: destInfo.isDirectory() ? "directory" : "file",
831
+ size: destInfo.size,
832
+ };
833
+ return okResult(JSON.stringify(payload, null, 2), payload);
834
+ }
835
+
836
+ if (action === "delete") {
837
+ const targetPath = await config.resolveAllowedPath(args.path, { mustExist: true });
838
+ const info = await stat(targetPath);
839
+ if (info.isDirectory() && !args.recursive) {
840
+ throw new Error(`Target "${targetPath}" is a directory. Set recursive: true to delete it.`);
841
+ }
842
+ await rm(targetPath, { recursive: Boolean(args.recursive), force: false });
843
+ const payload = {
844
+ ok: true,
845
+ action,
846
+ path: targetPath,
847
+ deletedType: info.isDirectory() ? "directory" : "file",
848
+ };
849
+ return okResult(JSON.stringify(payload, null, 2), payload);
850
+ }
851
+
852
+ if (action === "download_url") {
853
+ if (!args.url) {
854
+ throw new Error("url is required for download_url.");
855
+ }
856
+ const parsedUrl = new URL(args.url);
857
+ if (!["http:", "https:"].includes(parsedUrl.protocol)) {
858
+ throw new Error(`Unsupported URL protocol "${parsedUrl.protocol}". Only http and https are allowed.`);
859
+ }
860
+ const destPath = await config.resolveAllowedPath(args.path, { mustExist: false });
861
+ if (!args.overwrite && (await pathExists(destPath))) {
862
+ throw new Error(`Destination "${destPath}" already exists. Set overwrite: true to replace it.`);
863
+ }
864
+ await mkdir(path.dirname(destPath), { recursive: true });
865
+
866
+ const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? 30000) || 30000, 1000), 120000);
867
+ const controller = new AbortController();
868
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
869
+ try {
870
+ const response = await fetch(parsedUrl, {
871
+ headers: args.headers || {},
872
+ redirect: "follow",
873
+ signal: controller.signal,
874
+ });
875
+ if (!response.ok) {
876
+ throw new Error(`Download failed with HTTP ${response.status} ${response.statusText}`);
877
+ }
878
+ if (!response.body) {
879
+ throw new Error("Response body is empty.");
880
+ }
881
+ const contentLength = Number(response.headers.get("content-length") || 0);
882
+ if (contentLength > MAX_DOWNLOAD_BYTES) {
883
+ throw new Error(`Remote file (${contentLength} bytes) exceeds download limit (${MAX_DOWNLOAD_BYTES} bytes).`);
884
+ }
885
+
886
+ const hash = createHash("sha256");
887
+ let totalBytes = 0;
888
+ const reader = Readable.fromWeb(response.body);
889
+ const ws = createWriteStream(destPath);
890
+ reader.on("data", chunk => {
891
+ totalBytes += chunk.length;
892
+ if (totalBytes > MAX_DOWNLOAD_BYTES) {
893
+ reader.destroy(new Error(`Download exceeded maximum allowed size (${MAX_DOWNLOAD_BYTES} bytes).`));
894
+ return;
895
+ }
896
+ hash.update(chunk);
897
+ });
898
+ await pipeline(reader, ws);
899
+
900
+ const fileSha256 = hash.digest("hex");
901
+ if (args.expectedFileSha256 && fileSha256 !== args.expectedFileSha256.toLowerCase()) {
902
+ await rm(destPath, { force: true });
903
+ throw new Error(`Downloaded file SHA-256 mismatch: expected ${args.expectedFileSha256}, got ${fileSha256}.`);
904
+ }
905
+
906
+ const payload = {
907
+ ok: true,
908
+ action,
909
+ url: response.url || args.url,
910
+ path: destPath,
911
+ status: response.status,
912
+ contentType: response.headers.get("content-type") || "",
913
+ bytesWritten: totalBytes,
914
+ sha256: fileSha256,
915
+ };
916
+ return okResult(JSON.stringify(payload, null, 2), payload);
917
+ } finally {
918
+ clearTimeout(timer);
919
+ }
920
+ }
921
+
922
+ if (action === "upload_url") {
923
+ if (!args.url) {
924
+ throw new Error("url is required for upload_url.");
925
+ }
926
+ const parsedUrl = new URL(args.url);
927
+ if (!["http:", "https:"].includes(parsedUrl.protocol)) {
928
+ throw new Error(`Unsupported URL protocol "${parsedUrl.protocol}". Only http and https are allowed.`);
929
+ }
930
+ const srcPath = await config.resolveAllowedPath(args.path, { mustExist: true });
931
+ const info = await stat(srcPath);
932
+ if (!info.isFile()) {
933
+ throw new Error(`Source "${srcPath}" is not a regular file.`);
934
+ }
935
+ if (info.size > MAX_UPLOAD_BYTES) {
936
+ throw new Error(`File size (${info.size} bytes) exceeds upload_url limit (${MAX_UPLOAD_BYTES} bytes).`);
937
+ }
938
+
939
+ const fileBuf = await readFile(srcPath);
940
+ const fileSha256 = sha256Buffer(fileBuf);
941
+ const method = args.method || (args.multipartField ? "POST" : "PUT");
942
+ const headers = { ...(args.headers || {}) };
943
+ let body;
944
+
945
+ if (args.multipartField) {
946
+ const form = new FormData();
947
+ const blob = new Blob([fileBuf], { type: args.contentType || "application/octet-stream" });
948
+ form.append(args.multipartField, blob, path.basename(srcPath));
949
+ body = form;
950
+ } else {
951
+ if (!Object.keys(headers).some(k => k.toLowerCase() === "content-type")) {
952
+ headers["content-type"] = args.contentType || "application/octet-stream";
953
+ }
954
+ body = fileBuf;
955
+ }
956
+
957
+ const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? 30000) || 30000, 1000), 120000);
958
+ const controller = new AbortController();
959
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
960
+ try {
961
+ const response = await fetch(parsedUrl, {
962
+ method,
963
+ headers,
964
+ body,
965
+ redirect: "follow",
966
+ signal: controller.signal,
967
+ });
968
+ const responseTextRaw = await response.text().catch(() => "");
969
+ if (!response.ok) {
970
+ throw new Error(`Upload failed with HTTP ${response.status} ${response.statusText}: ${responseTextRaw.slice(0, 300)}`);
971
+ }
972
+ const responseText = responseTextRaw.length > 2000 ? `${responseTextRaw.slice(0, 2000)}... [truncated]` : responseTextRaw;
973
+ const payload = {
974
+ ok: true,
975
+ action,
976
+ url: response.url || args.url,
977
+ method,
978
+ path: srcPath,
979
+ status: response.status,
980
+ bytesSent: fileBuf.length,
981
+ sha256: fileSha256,
982
+ responseText,
983
+ };
984
+ return okResult(JSON.stringify(payload, null, 2), payload);
985
+ } finally {
986
+ clearTimeout(timer);
987
+ }
988
+ }
989
+
990
+ throw new Error(`Unsupported transfer_file action: ${action}`);
991
+ },
992
+ },
993
+ {
994
+ name: "search_files",
995
+ title: "Search files and content",
996
+ description:
997
+ "Find files by glob/name pattern and/or search UTF-8 text or regex inside files under LOCAL_CONTROL_ROOTS.",
998
+ inputSchema: {
999
+ type: "object",
1000
+ properties: {
1001
+ path: { type: "string", description: "Root directory to search (defaults to server cwd)." },
1002
+ pattern: { type: "string", description: "Glob (e.g. '*.js', 'src/**/*.ts') or filename substring filter." },
1003
+ query: { type: "string", description: "Text or regex pattern to search inside file contents." },
1004
+ isRegex: { type: "boolean", description: "Treat query as a JavaScript regular expression." },
1005
+ caseSensitive: { type: "boolean", description: "Case-sensitive content matching (default false)." },
1006
+ includeHidden: { type: "boolean", description: "Include dotfiles, dotfolders, and node_modules." },
1007
+ maxResults: { type: "integer", minimum: 1, maximum: 200, description: "Max matches to return (default 50)." },
1008
+ },
1009
+ additionalProperties: false,
1010
+ },
1011
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
1012
+ _meta: toolMeta("Searching local files", "Local file search ready"),
1013
+ async handler(args, { authContext }) {
1014
+ auth.requireReadAuth(authContext);
1015
+ if (!args.pattern && !args.query) {
1016
+ throw new Error("Provide at least one of pattern or query.");
1017
+ }
1018
+ const rootDir = await config.resolveAllowedPath(args.path || ".", { mustExist: true, accessMode: "read" });
1019
+ const maxResults = Math.min(Math.max(Number(args.maxResults ?? 50) || 50, 1), 200);
1020
+ const includeHidden = Boolean(args.includeHidden);
1021
+ const caseSensitive = Boolean(args.caseSensitive);
1022
+ const hasQuery = Boolean(args.query);
1023
+
1024
+ let regex = null;
1025
+ if (hasQuery && args.isRegex) {
1026
+ regex = new RegExp(args.query, caseSensitive ? "" : "i");
1027
+ }
1028
+ const queryLower = hasQuery && !args.isRegex && !caseSensitive ? args.query.toLowerCase() : null;
1029
+
1030
+ const matches = [];
1031
+ let truncated = false;
1032
+ let filesScanned = 0;
1033
+
1034
+ async function visit(currentDir) {
1035
+ if (truncated) return;
1036
+ let dirents;
1037
+ try {
1038
+ dirents = await readdir(currentDir, { withFileTypes: true });
1039
+ } catch {
1040
+ return;
1041
+ }
1042
+ dirents.sort((a, b) => a.name.localeCompare(b.name));
1043
+
1044
+ for (const dirent of dirents) {
1045
+ if (truncated) return;
1046
+ if (!includeHidden && (dirent.name.startsWith(".") || DEFAULT_SKIP_DIRS.has(dirent.name))) {
1047
+ continue;
1048
+ }
1049
+ const fullPath = path.join(currentDir, dirent.name);
1050
+ try { config.assertPublicPath(fullPath); } catch { continue; }
1051
+ const relPath = path.relative(rootDir, fullPath).replaceAll("\\", "/");
1052
+
1053
+ if (dirent.isDirectory()) {
1054
+ await visit(fullPath);
1055
+ continue;
1056
+ }
1057
+ if (!dirent.isFile()) continue;
1058
+ if (!matchesFilePattern(relPath, dirent.name, args.pattern)) continue;
1059
+
1060
+ if (!hasQuery) {
1061
+ if (matches.length >= maxResults) {
1062
+ truncated = true;
1063
+ return;
1064
+ }
1065
+ matches.push({ path: relPath, fullPath });
1066
+ continue;
1067
+ }
1068
+
1069
+ let info;
1070
+ try {
1071
+ info = await stat(fullPath);
1072
+ } catch {
1073
+ continue;
1074
+ }
1075
+ if (info.size > MAX_SEARCH_FILE_BYTES) continue;
1076
+
1077
+ let buf;
1078
+ try {
1079
+ buf = await readFile(fullPath);
1080
+ } catch {
1081
+ continue;
1082
+ }
1083
+ if (buf.includes(0)) continue;
1084
+
1085
+ filesScanned += 1;
1086
+ const lines = buf.toString("utf8").replace(/\r\n/g, "\n").split("\n");
1087
+ for (let i = 0; i < lines.length; i += 1) {
1088
+ const line = lines[i];
1089
+ const hit = regex
1090
+ ? regex.test(line)
1091
+ : caseSensitive
1092
+ ? line.includes(args.query)
1093
+ : line.toLowerCase().includes(queryLower);
1094
+ if (hit) {
1095
+ if (matches.length >= maxResults) {
1096
+ truncated = true;
1097
+ return;
1098
+ }
1099
+ matches.push({
1100
+ path: relPath,
1101
+ line: i + 1,
1102
+ text: line.length > 300 ? `${line.slice(0, 300)}...` : line,
1103
+ });
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ await visit(rootDir);
1110
+ const payload = {
1111
+ root: rootDir,
1112
+ mode: hasQuery ? "content" : "files",
1113
+ filesScanned,
1114
+ count: matches.length,
1115
+ truncated,
1116
+ matches,
1117
+ };
1118
+ return okResult(JSON.stringify(payload, null, 2), payload);
1119
+ },
1120
+ },
1121
+ ];
1122
+ }