@j0hanz/filesystem-mcp 2.2.0 → 2.4.0
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.
- package/README.md +38 -32
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +21 -40
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +24 -46
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts +5 -17
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +32 -40
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/config.d.ts +2 -0
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js.map +1 -1
- package/dist/core/cursor.d.ts +1 -12
- package/dist/core/cursor.d.ts.map +1 -1
- package/dist/core/cursor.js +2 -12
- package/dist/core/cursor.js.map +1 -1
- package/dist/core/errors.d.ts +6 -11
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +62 -117
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-uri.d.ts +7 -3
- package/dist/core/file-uri.d.ts.map +1 -1
- package/dist/core/file-uri.js +8 -4
- package/dist/core/file-uri.js.map +1 -1
- package/dist/core/fmt.d.ts +0 -11
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +1 -19
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/fs.d.ts +34 -4
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +151 -12
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +1 -2
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +12 -28
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +19 -29
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +58 -73
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/observability.d.ts +9 -0
- package/dist/core/observability.d.ts.map +1 -1
- package/dist/core/observability.js +13 -2
- package/dist/core/observability.js.map +1 -1
- package/dist/core/path-completer.d.ts +6 -9
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +28 -55
- package/dist/core/path-completer.js.map +1 -1
- package/dist/core/path-discovery.d.ts.map +1 -1
- package/dist/core/path-discovery.js +3 -4
- package/dist/core/path-discovery.js.map +1 -1
- package/dist/core/path-utils.d.ts +28 -0
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +57 -2
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +3 -8
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +8 -9
- package/dist/core/path.js.map +1 -1
- package/dist/core/read.d.ts +3 -22
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +46 -96
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts +8 -9
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +11 -14
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts +6 -1
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +21 -23
- package/dist/core/search.js.map +1 -1
- package/dist/core/sensitive.d.ts +4 -2
- package/dist/core/sensitive.d.ts.map +1 -1
- package/dist/core/sensitive.js +262 -45
- package/dist/core/sensitive.js.map +1 -1
- package/dist/core/store.d.ts +41 -16
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +147 -82
- package/dist/core/store.js.map +1 -1
- package/dist/core/util.d.ts +3 -2
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +5 -6
- package/dist/core/util.js.map +1 -1
- package/dist/core/watcher-registry.d.ts +1 -1
- package/dist/core/watcher-registry.d.ts.map +1 -1
- package/dist/core/watcher-registry.js +9 -5
- package/dist/core/watcher-registry.js.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/instructions.js +2 -2
- package/dist/instructions.js.map +1 -1
- package/dist/prompts.js +1 -1
- package/dist/prompts.js.map +1 -1
- package/dist/resources.d.ts +11 -19
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +51 -62
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts +4 -5
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +15 -11
- package/dist/server.js.map +1 -1
- package/dist/tools/batch.d.ts +2 -2
- package/dist/tools/batch.js +3 -3
- package/dist/tools/batch.js.map +1 -1
- package/dist/tools/create.d.ts +1 -1
- package/dist/tools/create.d.ts.map +1 -1
- package/dist/tools/create.js +168 -17
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +15 -9
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +48 -94
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts +1 -1
- package/dist/tools/delete.d.ts.map +1 -1
- package/dist/tools/delete.js +23 -23
- package/dist/tools/delete.js.map +1 -1
- package/dist/tools/diff.d.ts +1 -1
- package/dist/tools/diff.d.ts.map +1 -1
- package/dist/tools/diff.js +7 -37
- package/dist/tools/diff.js.map +1 -1
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +101 -92
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/find-files.d.ts +1 -1
- package/dist/tools/find-files.d.ts.map +1 -1
- package/dist/tools/find-files.js +18 -37
- package/dist/tools/find-files.js.map +1 -1
- package/dist/tools/index.d.ts +10 -10
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +14 -13
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/list-roots.d.ts +1 -1
- package/dist/tools/list-roots.js +3 -3
- package/dist/tools/list-roots.js.map +1 -1
- package/dist/tools/list.d.ts +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +23 -29
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +31 -45
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/patch.d.ts +1 -1
- package/dist/tools/patch.js +7 -7
- package/dist/tools/patch.js.map +1 -1
- package/dist/tools/progress.d.ts +17 -28
- package/dist/tools/progress.d.ts.map +1 -1
- package/dist/tools/progress.js +42 -94
- package/dist/tools/progress.js.map +1 -1
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +10 -12
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts +1 -1
- package/dist/tools/replace-text.d.ts.map +1 -1
- package/dist/tools/replace-text.js +32 -49
- package/dist/tools/replace-text.js.map +1 -1
- package/dist/tools/search-text.d.ts +1 -1
- package/dist/tools/search-text.d.ts.map +1 -1
- package/dist/tools/search-text.js +82 -45
- package/dist/tools/search-text.js.map +1 -1
- package/dist/tools/stat.d.ts +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +9 -29
- package/dist/tools/stat.js.map +1 -1
- package/dist/transport/http-policy.js +4 -4
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts +2 -2
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +21 -18
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/shared.d.ts +2 -2
- package/dist/transport/shared.js +2 -2
- package/dist/transport/shared.js.map +1 -1
- package/dist/transport/stdio.d.ts +4 -3
- package/dist/transport/stdio.d.ts.map +1 -1
- package/dist/transport/stdio.js +7 -6
- package/dist/transport/stdio.js.map +1 -1
- package/dist/transport.d.ts +2 -2
- package/dist/transport.js +2 -2
- package/dist/transport.js.map +1 -1
- package/package.json +6 -13
- package/dist/core/page-store.d.ts +0 -41
- package/dist/core/page-store.d.ts.map +0 -1
- package/dist/core/page-store.js +0 -74
- package/dist/core/page-store.js.map +0 -1
- package/dist/core/primitives.d.ts +0 -34
- package/dist/core/primitives.d.ts.map +0 -1
- package/dist/core/primitives.js +0 -63
- package/dist/core/primitives.js.map +0 -1
package/dist/tools/edit.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { basename } from 'node:path';
|
|
2
2
|
import * as z from 'zod/v4';
|
|
3
|
-
import { computeDiffStats, unifiedPatch } from
|
|
4
|
-
import { ErrorCode, FsError } from
|
|
5
|
-
import { buildWrittenFileMeta } from
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { defineTool } from './define.js';
|
|
3
|
+
import { computeDiffStats, unifiedPatch } from "../core/diff.js";
|
|
4
|
+
import { ErrorCode, FsError } from "../core/errors.js";
|
|
5
|
+
import { buildWrittenFileMeta } from "../core/file-uri.js";
|
|
6
|
+
import { defaultFalseBoolean, FileKind, isBlank, IsoDateTime, NonNegInt, OperationSummarySchema, PerFileErrorSchema, RequiredPath, singleOrBatchAccessPaths, } from "../core/schema.js";
|
|
7
|
+
import { compileRegex, execMatches, freeRegex } from "../core/search.js";
|
|
8
|
+
import { isTotalFailure, runOverPaths } from "./batch.js";
|
|
9
|
+
import { defineTool } from "./define.js";
|
|
11
10
|
const EditSpecSchema = z
|
|
12
11
|
.strictObject({
|
|
13
12
|
oldText: z
|
|
@@ -16,7 +15,7 @@ const EditSpecSchema = z
|
|
|
16
15
|
.refine((val) => !isBlank(val), {
|
|
17
16
|
message: 'oldText cannot be empty or whitespace-only',
|
|
18
17
|
})
|
|
19
|
-
.describe('Exact literal text to locate in the file.
|
|
18
|
+
.describe('Exact literal text to locate in the file; it must match exactly once. Include 3-5 lines of context so it does — an oldText found in several places fails with their line numbers.')
|
|
20
19
|
.meta({ examples: ['const x = 1;', 'function oldName('] }),
|
|
21
20
|
newText: z
|
|
22
21
|
.string()
|
|
@@ -107,10 +106,6 @@ const PerFileResultSchema = z.strictObject({
|
|
|
107
106
|
.array(z.string())
|
|
108
107
|
.optional()
|
|
109
108
|
.describe('oldText values that did not match any content in the file'),
|
|
110
|
-
lineRange: z
|
|
111
|
-
.tuple([PositiveInt, PositiveInt])
|
|
112
|
-
.optional()
|
|
113
|
-
.describe('Line range [firstLine, lastLine] covering all applied edits'),
|
|
114
109
|
});
|
|
115
110
|
const EditPerPathSchema = z.strictObject({
|
|
116
111
|
path: z.string().describe('Requested file path'),
|
|
@@ -123,84 +118,109 @@ const EditFileOutputSchema = z.strictObject({
|
|
|
123
118
|
.describe('Per-path edit results ordered to match the input paths'),
|
|
124
119
|
summary: OperationSummarySchema,
|
|
125
120
|
});
|
|
126
|
-
|
|
121
|
+
const MAX_REPORTED_MATCH_LINES = 5;
|
|
122
|
+
/**
|
|
123
|
+
* Where `oldText` matches. `count` is non-overlapping occurrences, except that a
|
|
124
|
+
* lone match with a second one overlapping it counts two (`abab` in `ababab`),
|
|
125
|
+
* since either is a span the caller could have meant — the count is exact only
|
|
126
|
+
* when it answers "once or not". Only the count and the first few starts are
|
|
127
|
+
* kept: a short oldText in a large file can match millions of times.
|
|
128
|
+
*/
|
|
129
|
+
function findEditMatches(content, oldText, ignoreWhitespace) {
|
|
130
|
+
const found = { first: undefined, count: 0, starts: [] };
|
|
131
|
+
const add = (startIndex, length) => {
|
|
132
|
+
found.first ??= { startIndex, length };
|
|
133
|
+
found.count += 1;
|
|
134
|
+
if (found.starts.length < MAX_REPORTED_MATCH_LINES)
|
|
135
|
+
found.starts.push(startIndex);
|
|
136
|
+
};
|
|
127
137
|
if (ignoreWhitespace) {
|
|
128
138
|
// Make whitespace flexible (tolerate indentation/spacing differences)
|
|
129
139
|
// without letting it cross line boundaries: a whitespace run that contains
|
|
130
140
|
// a newline keeps at least one newline, so a single-line oldText cannot
|
|
131
141
|
// match across a newline and a multi-line oldText cannot collapse onto one
|
|
132
142
|
// line. Horizontal whitespace stays mandatory between word characters so
|
|
133
|
-
// adjacent identifiers are not merged.
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
143
|
+
// adjacent identifiers are not merged. Built token by token: `split` on
|
|
144
|
+
// whitespace puts text at even indices and whitespace runs at odd ones.
|
|
145
|
+
const tokens = oldText.split(/(\s+)/u);
|
|
146
|
+
let pattern = '';
|
|
147
|
+
for (const [i, token] of tokens.entries()) {
|
|
148
|
+
if (i % 2 === 0) {
|
|
149
|
+
pattern += RegExp.escape(token);
|
|
150
|
+
}
|
|
151
|
+
else if (token.includes('\n')) {
|
|
152
|
+
pattern += '[^\\S\\n]*\\n+[^\\S\\n]*';
|
|
153
|
+
}
|
|
154
|
+
else if (/\w$/.test(tokens[i - 1] ?? '') && /^\w/.test(tokens[i + 1] ?? '')) {
|
|
155
|
+
pattern += '[^\\S\\n]+';
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
pattern += '[^\\S\\n]*';
|
|
159
|
+
}
|
|
160
|
+
}
|
|
138
161
|
const regex = compileRegex(pattern, { caseSensitive: true });
|
|
139
162
|
try {
|
|
140
163
|
// execMatches resets lastIndex and reports UTF-16 offsets; the raw RE2
|
|
141
164
|
// index counts code points and would splice off-by-one per emoji.
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
165
|
+
const scan = (from) => {
|
|
166
|
+
for (const match of execMatches(regex, from === 0 ? content : content.slice(from))) {
|
|
167
|
+
// A zero-length match names an empty span, which cannot be replaced.
|
|
168
|
+
if (match.text.length > 0)
|
|
169
|
+
add(from + match.start, match.text.length);
|
|
170
|
+
if (from > 0)
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
149
173
|
};
|
|
174
|
+
scan(0);
|
|
175
|
+
// execMatches resumes past each match, so a second match overlapping the
|
|
176
|
+
// first is never reported; look once more from just past its first
|
|
177
|
+
// non-whitespace character. Starting inside the leading whitespace would
|
|
178
|
+
// re-find the same occurrence, since the pattern's leading run is `*`. The
|
|
179
|
+
// pattern carries no anchors, so matching a suffix finds the same spans.
|
|
180
|
+
if (found.count === 1 && found.first) {
|
|
181
|
+
const { startIndex, length } = found.first;
|
|
182
|
+
const lead = content.slice(startIndex, startIndex + length).search(/\S/u);
|
|
183
|
+
scan(afterCodePoint(content, startIndex + lead));
|
|
184
|
+
}
|
|
150
185
|
}
|
|
151
186
|
finally {
|
|
152
187
|
// The compiled pattern owns wasm memory re2-wasm never reclaims on its
|
|
153
|
-
// own; its lifetime is this one
|
|
188
|
+
// own; its lifetime is this one search.
|
|
154
189
|
freeRegex(regex);
|
|
155
190
|
}
|
|
191
|
+
return found;
|
|
156
192
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
193
|
+
// Non-overlapping, so the scan stays linear on repetitive content; the one
|
|
194
|
+
// overlap that matters — a second match inside the only one — is checked after.
|
|
195
|
+
for (let i = content.indexOf(oldText); i !== -1; i = content.indexOf(oldText, i + oldText.length)) {
|
|
196
|
+
add(i, oldText.length);
|
|
160
197
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
198
|
+
if (found.count === 1 && found.first) {
|
|
199
|
+
const overlap = content.indexOf(oldText, afterCodePoint(content, found.first.startIndex));
|
|
200
|
+
if (overlap !== -1)
|
|
201
|
+
add(overlap, oldText.length);
|
|
202
|
+
}
|
|
203
|
+
return found;
|
|
204
|
+
}
|
|
205
|
+
/** The UTF-16 offset just past the code point at `index`, so a surrogate pair is never split. */
|
|
206
|
+
function afterCodePoint(content, index) {
|
|
207
|
+
return index + ((content.codePointAt(index) ?? 0) > 0xffff ? 2 : 1);
|
|
208
|
+
}
|
|
209
|
+
function ambiguousEditError(content, found, editIndex, shifted) {
|
|
210
|
+
const lines = [
|
|
211
|
+
...new Set(found.starts.map((start) => content.slice(0, start).split('\n').length)),
|
|
212
|
+
];
|
|
213
|
+
const label = lines.length === 1 ? 'line' : 'lines';
|
|
214
|
+
const more = found.count > found.starts.length ? ', ...' : '';
|
|
215
|
+
// Offsets come from the content as earlier edits in this call left it, which
|
|
216
|
+
// is not the file the caller read once one of them has applied.
|
|
217
|
+
const where = shifted ? ' after earlier edits' : '';
|
|
218
|
+
return new FsError(ErrorCode.INVALID_INPUT, `edits[${String(editIndex)}]: oldText matches ${String(found.count)} places${where} ` +
|
|
219
|
+
`(${label} ${lines.join(', ')}${more}). Add surrounding lines so it matches once.`);
|
|
165
220
|
}
|
|
166
221
|
function replaceEditMatch(content, match, newText) {
|
|
167
222
|
return (content.slice(0, match.startIndex) + newText + content.slice(match.startIndex + match.length));
|
|
168
223
|
}
|
|
169
|
-
/**
|
|
170
|
-
* Compute the 1-indexed line range of changed lines in `modified` relative to
|
|
171
|
-
* `original`, using a common-prefix/suffix line scan. This is a conservative
|
|
172
|
-
* bound (it widens to cover independent changes between matching bookends), but
|
|
173
|
-
* it is computed against the FINAL content so it is not skewed by earlier edits
|
|
174
|
-
* inserting or removing lines — which the per-edit merge could not account for.
|
|
175
|
-
*/
|
|
176
|
-
function computeChangedLineRange(original, modified) {
|
|
177
|
-
const origLines = original.split('\n');
|
|
178
|
-
const modLines = modified.split('\n');
|
|
179
|
-
const minLen = Math.min(origLines.length, modLines.length);
|
|
180
|
-
let firstChanged = -1;
|
|
181
|
-
for (let i = 0; i < minLen; i++) {
|
|
182
|
-
if (origLines[i] !== modLines[i]) {
|
|
183
|
-
firstChanged = i;
|
|
184
|
-
break;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
if (firstChanged === -1 && origLines.length === modLines.length)
|
|
188
|
-
return undefined;
|
|
189
|
-
if (firstChanged === -1)
|
|
190
|
-
firstChanged = minLen; // pure append/trim at the tail
|
|
191
|
-
let lastChangedMod = modLines.length - 1;
|
|
192
|
-
let lastChangedOrig = origLines.length - 1;
|
|
193
|
-
while (lastChangedMod > firstChanged &&
|
|
194
|
-
lastChangedOrig >= 0 &&
|
|
195
|
-
modLines[lastChangedMod] === origLines[lastChangedOrig]) {
|
|
196
|
-
lastChangedMod--;
|
|
197
|
-
lastChangedOrig--;
|
|
198
|
-
}
|
|
199
|
-
// When the modified content is a strict prefix of the original (a tail trim on
|
|
200
|
-
// a file with no final newline), the loop above never runs and lastChangedMod
|
|
201
|
-
// lands one below firstChanged. Clamp so the range is never inverted.
|
|
202
|
-
return [firstChanged + 1, Math.max(firstChanged, lastChangedMod) + 1];
|
|
203
|
-
}
|
|
204
224
|
function buildEditFileValue(validPath, meta, modified, result) {
|
|
205
225
|
return {
|
|
206
226
|
path: validPath,
|
|
@@ -216,20 +236,6 @@ function buildEditFileValue(validPath, meta, modified, result) {
|
|
|
216
236
|
: {}),
|
|
217
237
|
...(result.unmatchedEdits.length > 0 ? { unmatchedEdits: result.unmatchedEdits } : {}),
|
|
218
238
|
...(result.diff ? { diff: result.diff } : {}),
|
|
219
|
-
...(result.lineRange ? { lineRange: result.lineRange } : {}),
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
function finalizeEditResult(originalContent, updatedContent, appliedEdits, unmatchedEdits, lineRange) {
|
|
223
|
-
const { linesAdded, linesRemoved } = appliedEdits > 0
|
|
224
|
-
? computeDiffStats(originalContent, updatedContent)
|
|
225
|
-
: { linesAdded: 0, linesRemoved: 0 };
|
|
226
|
-
return {
|
|
227
|
-
content: updatedContent,
|
|
228
|
-
appliedEdits,
|
|
229
|
-
unmatchedEdits,
|
|
230
|
-
linesAdded,
|
|
231
|
-
linesRemoved,
|
|
232
|
-
...(lineRange ? { lineRange } : {}),
|
|
233
239
|
};
|
|
234
240
|
}
|
|
235
241
|
function buildEditFileMetadata(content, validPath, appliedEdits, resourceStore) {
|
|
@@ -247,19 +253,21 @@ function applyEdits(content, edits, ignoreWhitespace) {
|
|
|
247
253
|
let newContent = content;
|
|
248
254
|
let appliedEdits = 0;
|
|
249
255
|
const unmatchedEdits = [];
|
|
250
|
-
for (const edit of edits) {
|
|
251
|
-
const
|
|
252
|
-
|
|
256
|
+
for (const [index, edit] of edits.entries()) {
|
|
257
|
+
const found = findEditMatches(newContent, edit.oldText, ignoreWhitespace);
|
|
258
|
+
// A second match is an error rather than a pick: splicing the first would
|
|
259
|
+
// edit a block the caller may not have meant and still report success.
|
|
260
|
+
if (found.count > 1)
|
|
261
|
+
throw ambiguousEditError(newContent, found, index, appliedEdits > 0);
|
|
262
|
+
if (!found.first) {
|
|
253
263
|
unmatchedEdits.push(edit.oldText);
|
|
254
264
|
continue;
|
|
255
265
|
}
|
|
256
|
-
newContent = replaceEditMatch(newContent,
|
|
266
|
+
newContent = replaceEditMatch(newContent, found.first, edit.newText);
|
|
257
267
|
appliedEdits += 1;
|
|
258
268
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
const lineRange = appliedEdits > 0 ? computeChangedLineRange(content, newContent) : undefined;
|
|
262
|
-
return finalizeEditResult(content, newContent, appliedEdits, unmatchedEdits, lineRange);
|
|
269
|
+
const { linesAdded, linesRemoved } = appliedEdits > 0 ? computeDiffStats(content, newContent) : { linesAdded: 0, linesRemoved: 0 };
|
|
270
|
+
return { content: newContent, appliedEdits, unmatchedEdits, linesAdded, linesRemoved };
|
|
263
271
|
}
|
|
264
272
|
async function handleEditFile(filePath, edits, options, ctx) {
|
|
265
273
|
const { validPath, content } = await ctx.fs.readEditableText(filePath, {
|
|
@@ -332,7 +340,8 @@ export const EDIT = defineTool({
|
|
|
332
340
|
title: 'Edit Files',
|
|
333
341
|
description: 'Apply sequential literal string replacements to one or more files (max 5 files per call). ' +
|
|
334
342
|
'Modes: single-file { path, edits } or per-file { files: [{ path, edits }] }. ' +
|
|
335
|
-
'oldText must match file content exactly; include 3-5 lines of surrounding context
|
|
343
|
+
'oldText must match file content exactly and only once; include 3-5 lines of surrounding context, ' +
|
|
344
|
+
'or the edit fails listing the lines it matched. ' +
|
|
336
345
|
'Set dryRun=true to preview diffs without writing. ' +
|
|
337
346
|
'For glob-based bulk regex replacement across many files, use replace_text instead.',
|
|
338
347
|
input: EditFileInputSchema,
|
package/dist/tools/edit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[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,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YAC9B,IAAI,OAAO,IAAI,CAAC,EAAE,CAAC;gBACjB,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;gBACtD,SAAS;YACX,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;YAC3D,IAAI,CAAC,CAAC,KAAK,CAAC,YAAY;gBAAE,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACrE,CAAC;QAED,MAAM,WAAW,GAAG,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAEnE,OAAO;YACL,UAAU,EAAE;gBACV,OAAO,EAAE,cAAc;gBACvB,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB;YACD,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC;YACtC,GAAG,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAClE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { computeDiffStats, unifiedPatch } from '../core/diff.js';\nimport { ErrorCode, FsError } from '../core/errors.js';\nimport { buildWrittenFileMeta, type WrittenFileMeta } from '../core/file-uri.js';\nimport { escapeRegexLiteral } from '../core/primitives.js';\nimport {\n defaultFalseBoolean,\n FileKind,\n isBlank,\n IsoDateTime,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n PositiveInt,\n RequiredPath,\n singleOrBatchAccessPaths,\n} from '../core/schema.js';\nimport { compileRegex, execMatches, freeRegex } from '../core/search.js';\nimport type { ResourceStore } from '../core/store.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport { defineTool, type ToolCtx } from './define.js';\n\nconst EditSpecSchema = z\n .strictObject({\n oldText: z\n .string()\n .min(1, 'oldText required')\n .refine((val) => !isBlank(val), {\n message: 'oldText cannot be empty or whitespace-only',\n })\n .describe(\n 'Exact literal text to locate in the file. Must include 3-5 lines of context to ensure uniqueness and avoid matching the wrong block.',\n )\n .meta({ examples: ['const x = 1;', 'function oldName('] }),\n newText: z\n .string()\n .describe('Replacement text. Use an empty string to delete the matched oldText.')\n .meta({ examples: ['const x = 2;', 'function newName(', ''] }),\n })\n // The one document in this server where a `$ref` pays: this subschema is used\n // at both `edits` and `files[].edits`, so an `id` hoists it into `$defs` once\n // instead of inlining ~1.3 kB twice. Shared schemas used once per document\n // deliberately carry no `id` — there a `$ref` costs more than it saves.\n .meta({ id: 'EditSpec' });\n\nconst MAX_MULTI_FILES = 5;\nconst MAX_EDITS_PER_FILE = 100;\n\nconst EditFileInputSchema = z\n .strictObject({\n path: RequiredPath.optional().describe('Single file path; mutually exclusive with files'),\n edits: z\n .array(EditSpecSchema)\n .min(1)\n .max(MAX_EDITS_PER_FILE)\n .optional()\n .describe('Replacements applied to path; not allowed when using files'),\n files: z\n .array(\n z.strictObject({\n path: RequiredPath,\n edits: z\n .array(EditSpecSchema)\n .min(1)\n .max(MAX_EDITS_PER_FILE)\n .describe('Replacements to apply to this specific file'),\n }),\n )\n .min(1)\n .max(MAX_MULTI_FILES)\n .optional()\n .describe('Per-file entries (batch mode)'),\n dryRun: defaultFalseBoolean(\n 'Preview diffs without writing to disk (default: false = apply edits)',\n ),\n ignoreWhitespace: defaultFalseBoolean(\n 'Ignore leading/trailing whitespace differences when matching oldText',\n ),\n })\n .superRefine((value, ctx) => {\n const hasPath = value.path !== undefined;\n const hasFiles = value.files !== undefined;\n if (hasPath === hasFiles) {\n ctx.addIssue({\n code: 'custom',\n path: ['path'],\n message: \"Provide exactly one of 'path' or 'files'\",\n input: value,\n });\n }\n if (hasPath && value.edits === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['edits'],\n message: \"'edits' required when using 'path'\",\n input: value,\n });\n }\n if (hasFiles && value.edits !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['edits'],\n message: \"'edits' not allowed with 'files'; each file carries its own edits\",\n input: value,\n });\n }\n })\n // Mirror the superRefine on the wire: exactly one input mode, and single-file\n // mode carries its own `edits`. Without `edits` in the first branch, `{ path }`\n // alone validated against the published schema and was then rejected at\n // runtime — the model had no way to see that coming.\n .meta({ oneOf: [{ required: ['path', 'edits'] }, { required: ['files'] }] });\n\nconst PerFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the edited file'),\n size: NonNegInt.describe('File size in bytes after edits'),\n lineCount: NonNegInt.describe('Number of lines in the file after edits'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI pointing to the updated file content; omitted when no edit matched (appliedEdits is 0) and the file was left untouched',\n ),\n modified: IsoDateTime.describe('Last modification timestamp after edits (ISO 8601 UTC)'),\n appliedEdits: NonNegInt.describe('Number of edits successfully applied'),\n linesAdded: NonNegInt.optional().describe('Net lines added by all applied edits'),\n linesRemoved: NonNegInt.optional().describe('Net lines removed by all applied edits'),\n diff: z.string().optional().describe('Unified diff of all changes (present only in dryRun mode)'),\n unmatchedEdits: z\n .array(z.string())\n .optional()\n .describe('oldText values that did not match any content in the file'),\n lineRange: z\n .tuple([PositiveInt, PositiveInt])\n .optional()\n .describe('Line range [firstLine, lastLine] covering all applied edits'),\n});\n\nconst EditPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: PerFileResultSchema.optional().describe('Edit result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst EditFileOutputSchema = z.strictObject({\n results: z\n .array(EditPerPathSchema)\n .describe('Per-path edit results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype EditFileValue = z.infer<typeof PerFileResultSchema>;\n\ninterface TextRange {\n startIndex: number;\n length: number;\n}\n\ninterface EditResult {\n content: string;\n appliedEdits: number;\n unmatchedEdits: string[];\n linesAdded: number;\n linesRemoved: number;\n diff?: string;\n lineRange?: [number, number];\n}\n\nfunction findEditMatch(\n content: string,\n oldText: string,\n ignoreWhitespace: boolean,\n): TextRange | undefined {\n if (ignoreWhitespace) {\n // Make whitespace flexible (tolerate indentation/spacing differences)\n // without letting it cross line boundaries: a whitespace run that contains\n // a newline keeps at least one newline, so a single-line oldText cannot\n // match across a newline and a multi-line oldText cannot collapse onto one\n // line. Horizontal whitespace stays mandatory between word characters so\n // adjacent identifiers are not merged.\n const pattern = escapeRegexLiteral(oldText)\n .replace(/[^\\S\\n]*\\n\\s*/g, '[^\\\\S\\\\n]*\\\\n+[^\\\\S\\\\n]*')\n .replace(/(\\w)[^\\S\\n]+(\\w)/g, '$1[^\\\\S\\\\n]+$2')\n .replace(/[^\\S\\n]+/g, '[^\\\\S\\\\n]*');\n const regex = compileRegex(pattern, { caseSensitive: true });\n try {\n // execMatches resets lastIndex and reports UTF-16 offsets; the raw RE2\n // index counts code points and would splice off-by-one per emoji.\n const { value: match } = execMatches(regex, content).next();\n // A zero-length match names an empty span, which cannot be replaced.\n if (match === undefined || match.text.length === 0) return undefined;\n\n return {\n startIndex: match.start,\n length: match.text.length,\n };\n } finally {\n // The compiled pattern owns wasm memory re2-wasm never reclaims on its\n // own; its lifetime is this one match.\n freeRegex(regex);\n }\n }\n\n const index = content.indexOf(oldText);\n if (index === -1) {\n return undefined;\n }\n\n return {\n startIndex: index,\n length: oldText.length,\n };\n}\n\nfunction replaceEditMatch(content: string, match: TextRange, newText: string): string {\n return (\n content.slice(0, match.startIndex) + newText + content.slice(match.startIndex + match.length)\n );\n}\n\n/**\n * Compute the 1-indexed line range of changed lines in `modified` relative to\n * `original`, using a common-prefix/suffix line scan. This is a conservative\n * bound (it widens to cover independent changes between matching bookends), but\n * it is computed against the FINAL content so it is not skewed by earlier edits\n * inserting or removing lines — which the per-edit merge could not account for.\n */\nfunction computeChangedLineRange(original: string, modified: string): [number, number] | undefined {\n const origLines = original.split('\\n');\n const modLines = modified.split('\\n');\n const minLen = Math.min(origLines.length, modLines.length);\n\n let firstChanged = -1;\n for (let i = 0; i < minLen; i++) {\n if (origLines[i] !== modLines[i]) {\n firstChanged = i;\n break;\n }\n }\n if (firstChanged === -1 && origLines.length === modLines.length) return undefined;\n if (firstChanged === -1) firstChanged = minLen; // pure append/trim at the tail\n\n let lastChangedMod = modLines.length - 1;\n let lastChangedOrig = origLines.length - 1;\n while (\n lastChangedMod > firstChanged &&\n lastChangedOrig >= 0 &&\n modLines[lastChangedMod] === origLines[lastChangedOrig]\n ) {\n lastChangedMod--;\n lastChangedOrig--;\n }\n\n // When the modified content is a strict prefix of the original (a tail trim on\n // a file with no final newline), the loop above never runs and lastChangedMod\n // lands one below firstChanged. Clamp so the range is never inverted.\n return [firstChanged + 1, Math.max(firstChanged, lastChangedMod) + 1];\n}\n\nfunction buildEditFileValue(\n validPath: string,\n meta: EditFileMetadata,\n modified: string,\n result: EditResult,\n): EditFileValue {\n return {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n ...(meta.resourceUri !== undefined ? { resourceUri: meta.resourceUri } : {}),\n modified,\n appliedEdits: result.appliedEdits,\n ...(result.appliedEdits > 0\n ? { linesAdded: result.linesAdded, linesRemoved: result.linesRemoved }\n : {}),\n ...(result.unmatchedEdits.length > 0 ? { unmatchedEdits: result.unmatchedEdits } : {}),\n ...(result.diff ? { diff: result.diff } : {}),\n ...(result.lineRange ? { lineRange: result.lineRange } : {}),\n };\n}\n\nfunction finalizeEditResult(\n originalContent: string,\n updatedContent: string,\n appliedEdits: number,\n unmatchedEdits: string[],\n lineRange: EditResult['lineRange'],\n): EditResult {\n const { linesAdded, linesRemoved } =\n appliedEdits > 0\n ? computeDiffStats(originalContent, updatedContent)\n : { linesAdded: 0, linesRemoved: 0 };\n\n return {\n content: updatedContent,\n appliedEdits,\n unmatchedEdits,\n linesAdded,\n linesRemoved,\n ...(lineRange ? { lineRange } : {}),\n };\n}\n\n/** {@link WrittenFileMeta}, with `resourceUri` widened: an edit that matched\n * nothing has no updated content to point at. */\ntype EditFileMetadata = Omit<WrittenFileMeta, 'resourceUri'> & {\n resourceUri: string | undefined;\n};\n\nfunction buildEditFileMetadata(\n content: string,\n validPath: string,\n appliedEdits: number,\n resourceStore: ResourceStore | undefined,\n): EditFileMetadata {\n const meta = buildWrittenFileMeta(validPath, content, resourceStore);\n // Omitted rather than empty-stringed when nothing matched: `\"\"` satisfied the\n // schema's `string` and then failed every resources/read a client tried it on.\n const written = appliedEdits > 0;\n return {\n ...meta,\n resourceUri: written ? meta.resourceUri : undefined,\n resourceLink: written ? meta.resourceLink : undefined,\n };\n}\n\nfunction applyEdits(\n content: string,\n edits: z.infer<typeof EditSpecSchema>[],\n ignoreWhitespace: boolean,\n): EditResult {\n let newContent = content;\n let appliedEdits = 0;\n const unmatchedEdits: string[] = [];\n\n for (const edit of edits) {\n const match = findEditMatch(newContent, edit.oldText, ignoreWhitespace);\n\n if (!match) {\n unmatchedEdits.push(edit.oldText);\n continue;\n }\n\n newContent = replaceEditMatch(newContent, match, edit.newText);\n appliedEdits += 1;\n }\n\n // Compute the line range against the final content so earlier edits whose\n // lines were shifted by later edits are still covered.\n const lineRange = appliedEdits > 0 ? computeChangedLineRange(content, newContent) : undefined;\n\n return finalizeEditResult(content, newContent, appliedEdits, unmatchedEdits, lineRange);\n}\n\ninterface EditFileOptions {\n dryRun: boolean;\n ignoreWhitespace: boolean;\n}\n\nasync function handleEditFile(\n filePath: string,\n edits: z.infer<typeof EditSpecSchema>[],\n options: EditFileOptions,\n ctx: ToolCtx,\n): Promise<{ file: EditFileValue; resourceLink?: ContentBlock }> {\n const { validPath, content } = await ctx.fs.readEditableText(filePath, {\n signal: ctx.signal,\n });\n const editResult = applyEdits(content, edits, options.ignoreWhitespace);\n\n if (options.dryRun) {\n if (editResult.appliedEdits > 0) {\n editResult.diff = unifiedPatch(basename(validPath), content, editResult.content);\n }\n\n // Nothing was written, so there is no updated content to point a\n // resourceUri or a resource_link at — the file on disk is still the one the\n // caller already has. Same rule the appliedEdits-is-0 case follows: no\n // write, no link.\n const meta = buildEditFileMetadata(editResult.content, validPath, 0, ctx.resourceStore);\n return {\n file: buildEditFileValue(validPath, meta, new Date().toISOString(), editResult),\n ...(meta.resourceLink ? { resourceLink: meta.resourceLink } : {}),\n };\n }\n\n if (editResult.unmatchedEdits.length > 0) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${editResult.unmatchedEdits.length} edit(s) failed to match. Verify oldText matches exact file content.`,\n filePath,\n );\n }\n\n if (editResult.appliedEdits > 0) {\n await ctx.fs.writeFile(filePath, editResult.content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n ctx.log?.(\n 'info',\n `edit: ${filePath} (${editResult.appliedEdits} edits, +${editResult.linesAdded}/-${editResult.linesRemoved})`,\n 'edit',\n );\n }\n\n // `modified` is read from a post-write stat and is advisory: under a concurrent\n // writer it may reflect that writer's mtime while `size`/content below come from\n // this edit's atomic write. The file content itself is always consistent.\n const { stats: fileStats } = await ctx.fs.stat(filePath, { signal: ctx.signal });\n const meta = buildEditFileMetadata(\n editResult.content,\n validPath,\n editResult.appliedEdits,\n ctx.resourceStore,\n );\n return {\n file: buildEditFileValue(validPath, meta, fileStats.mtime.toISOString(), editResult),\n ...(meta.resourceLink ? { resourceLink: meta.resourceLink } : {}),\n };\n}\n\nfunction formatEditSummary(\n results: readonly z.infer<typeof EditPerPathSchema>[],\n dryRun: boolean,\n): string {\n const tag = dryRun ? ' [dry run]' : '';\n // Single-file failure: say why here rather than making the caller read\n // structuredContent for the one message that can apply.\n const [only] = results;\n if (results.length === 1 && only?.error) {\n return `edit: ${only.path} FAILED — ${only.error.message}${tag}`;\n }\n const tokens = results.map((r) => {\n if (r.error) return `${basename(r.path)} FAILED`;\n const v = r.value;\n if (!v) return `${basename(r.path)} (no result)`;\n if (v.unmatchedEdits && v.unmatchedEdits.length > 0) return `${basename(v.path)} NO MATCH`;\n const added = v.linesAdded ?? 0;\n const removed = v.linesRemoved ?? 0;\n if (added === 0 && removed === 0) return `${basename(v.path)} (no change)`;\n return `${basename(v.path)} +${String(added)} -${String(removed)}`;\n });\n\n const failed = results.filter((r) => r.error !== undefined).length;\n const ok = results.length - failed;\n const ratio = failed > 0 ? ` (${String(ok)}/${String(results.length)} ok)` : '';\n return `edit: ${tokens.join(' · ')}${ratio}${tag}`;\n}\n\nexport const EDIT = defineTool({\n name: 'edit',\n title: 'Edit Files',\n description:\n 'Apply sequential literal string replacements to one or more files (max 5 files per call). ' +\n 'Modes: single-file { path, edits } or per-file { files: [{ path, edits }] }. ' +\n 'oldText must match file content exactly; include 3-5 lines of surrounding context to ensure uniqueness. ' +\n 'Set dryRun=true to preview diffs without writing. ' +\n 'For glob-based bulk regex replacement across many files, use replace_text instead.',\n input: EditFileInputSchema,\n output: EditFileOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => {\n const dryLabel = args.dryRun ? ' [dry run]' : '';\n let subject: string;\n if (args.path !== undefined) {\n subject = basename(args.path);\n } else if (args.files !== undefined) {\n subject = `${args.files.length} files`;\n } else {\n subject = 'files';\n }\n return { label: `Edit${dryLabel}`, subject };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n const sharedEdits = args.edits ?? [];\n const batchInput = args.path !== undefined ? { path: args.path } : { files: args.files ?? [] };\n\n const options: EditFileOptions = {\n dryRun: args.dryRun,\n ignoreWhitespace: args.ignoreWhitespace,\n };\n\n const batch = await runOverPaths<\n { edits: z.infer<typeof EditSpecSchema>[] },\n { file: EditFileValue; resourceLink?: ContentBlock }\n >(\n batchInput,\n ctx,\n ({ path, override }) => handleEditFile(path, override?.edits ?? sharedEdits, options, ctx),\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const perPathResults: z.infer<typeof EditPerPathSchema>[] = [];\n const resourceLinks: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n perPathResults.push({ path: r.path, error: r.error });\n continue;\n }\n perPathResults.push({ path: r.path, value: r.value.file });\n if (r.value.resourceLink) resourceLinks.push(r.value.resourceLink);\n }\n\n const summaryText = formatEditSummary(perPathResults, args.dryRun);\n\n return {\n structured: {\n results: perPathResults,\n summary: batch.summary,\n },\n text: summaryText,\n isError: isTotalFailure(batch.summary),\n ...(resourceLinks.length > 0 ? { resources: resourceLinks } : {}),\n };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAwB,MAAM,qBAAqB,CAAC;AACjF,OAAO,EACL,mBAAmB,EACnB,QAAQ,EACR,OAAO,EACP,WAAW,EACX,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,YAAY,EACZ,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAA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AC;YAC3D,IAAI,CAAC,CAAC,KAAK,CAAC,YAAY;gBAAE,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACrE,CAAC;QAED,MAAM,WAAW,GAAG,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAEnE,OAAO;YACL,UAAU,EAAE;gBACV,OAAO,EAAE,cAAc;gBACvB,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB;YACD,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC;YACtC,GAAG,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAClE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { computeDiffStats, unifiedPatch } from '../core/diff.ts';\nimport { ErrorCode, FsError } from '../core/errors.ts';\nimport { buildWrittenFileMeta, type WrittenFileMeta } from '../core/file-uri.ts';\nimport {\n defaultFalseBoolean,\n FileKind,\n isBlank,\n IsoDateTime,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n RequiredPath,\n singleOrBatchAccessPaths,\n} from '../core/schema.ts';\nimport { compileRegex, execMatches, freeRegex } from '../core/search.ts';\nimport type { ResourceStore } from '../core/store.ts';\nimport { isTotalFailure, runOverPaths } from './batch.ts';\nimport { defineTool, type ToolCtx } from './define.ts';\n\nconst EditSpecSchema = z\n .strictObject({\n oldText: z\n .string()\n .min(1, 'oldText required')\n .refine((val) => !isBlank(val), {\n message: 'oldText cannot be empty or whitespace-only',\n })\n .describe(\n 'Exact literal text to locate in the file; it must match exactly once. Include 3-5 lines of context so it does — an oldText found in several places fails with their line numbers.',\n )\n .meta({ examples: ['const x = 1;', 'function oldName('] }),\n newText: z\n .string()\n .describe('Replacement text. Use an empty string to delete the matched oldText.')\n .meta({ examples: ['const x = 2;', 'function newName(', ''] }),\n })\n // The one document in this server where a `$ref` pays: this subschema is used\n // at both `edits` and `files[].edits`, so an `id` hoists it into `$defs` once\n // instead of inlining ~1.3 kB twice. Shared schemas used once per document\n // deliberately carry no `id` — there a `$ref` costs more than it saves.\n .meta({ id: 'EditSpec' });\n\nconst MAX_MULTI_FILES = 5;\nconst MAX_EDITS_PER_FILE = 100;\n\nconst EditFileInputSchema = z\n .strictObject({\n path: RequiredPath.optional().describe('Single file path; mutually exclusive with files'),\n edits: z\n .array(EditSpecSchema)\n .min(1)\n .max(MAX_EDITS_PER_FILE)\n .optional()\n .describe('Replacements applied to path; not allowed when using files'),\n files: z\n .array(\n z.strictObject({\n path: RequiredPath,\n edits: z\n .array(EditSpecSchema)\n .min(1)\n .max(MAX_EDITS_PER_FILE)\n .describe('Replacements to apply to this specific file'),\n }),\n )\n .min(1)\n .max(MAX_MULTI_FILES)\n .optional()\n .describe('Per-file entries (batch mode)'),\n dryRun: defaultFalseBoolean(\n 'Preview diffs without writing to disk (default: false = apply edits)',\n ),\n ignoreWhitespace: defaultFalseBoolean(\n 'Ignore leading/trailing whitespace differences when matching oldText',\n ),\n })\n .superRefine((value, ctx) => {\n const hasPath = value.path !== undefined;\n const hasFiles = value.files !== undefined;\n if (hasPath === hasFiles) {\n ctx.addIssue({\n code: 'custom',\n path: ['path'],\n message: \"Provide exactly one of 'path' or 'files'\",\n input: value,\n });\n }\n if (hasPath && value.edits === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['edits'],\n message: \"'edits' required when using 'path'\",\n input: value,\n });\n }\n if (hasFiles && value.edits !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['edits'],\n message: \"'edits' not allowed with 'files'; each file carries its own edits\",\n input: value,\n });\n }\n })\n // Mirror the superRefine on the wire: exactly one input mode, and single-file\n // mode carries its own `edits`. Without `edits` in the first branch, `{ path }`\n // alone validated against the published schema and was then rejected at\n // runtime — the model had no way to see that coming.\n .meta({ oneOf: [{ required: ['path', 'edits'] }, { required: ['files'] }] });\n\nconst PerFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the edited file'),\n size: NonNegInt.describe('File size in bytes after edits'),\n lineCount: NonNegInt.describe('Number of lines in the file after edits'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI pointing to the updated file content; omitted when no edit matched (appliedEdits is 0) and the file was left untouched',\n ),\n modified: IsoDateTime.describe('Last modification timestamp after edits (ISO 8601 UTC)'),\n appliedEdits: NonNegInt.describe('Number of edits successfully applied'),\n linesAdded: NonNegInt.optional().describe('Net lines added by all applied edits'),\n linesRemoved: NonNegInt.optional().describe('Net lines removed by all applied edits'),\n diff: z.string().optional().describe('Unified diff of all changes (present only in dryRun mode)'),\n unmatchedEdits: z\n .array(z.string())\n .optional()\n .describe('oldText values that did not match any content in the file'),\n});\n\nconst EditPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: PerFileResultSchema.optional().describe('Edit result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst EditFileOutputSchema = z.strictObject({\n results: z\n .array(EditPerPathSchema)\n .describe('Per-path edit results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype EditFileValue = z.infer<typeof PerFileResultSchema>;\n\ninterface TextRange {\n startIndex: number;\n length: number;\n}\n\ninterface EditResult {\n content: string;\n appliedEdits: number;\n unmatchedEdits: string[];\n linesAdded: number;\n linesRemoved: number;\n diff?: string;\n}\n\nconst MAX_REPORTED_MATCH_LINES = 5;\n\ninterface EditMatches {\n /** The first match; undefined when oldText matches nothing. */\n first: TextRange | undefined;\n count: number;\n /** UTF-16 start offsets of the first {@link MAX_REPORTED_MATCH_LINES} matches. */\n starts: number[];\n}\n\n/**\n * Where `oldText` matches. `count` is non-overlapping occurrences, except that a\n * lone match with a second one overlapping it counts two (`abab` in `ababab`),\n * since either is a span the caller could have meant — the count is exact only\n * when it answers \"once or not\". Only the count and the first few starts are\n * kept: a short oldText in a large file can match millions of times.\n */\nfunction findEditMatches(content: string, oldText: string, ignoreWhitespace: boolean): EditMatches {\n const found: EditMatches = { first: undefined, count: 0, starts: [] };\n const add = (startIndex: number, length: number): void => {\n found.first ??= { startIndex, length };\n found.count += 1;\n if (found.starts.length < MAX_REPORTED_MATCH_LINES) found.starts.push(startIndex);\n };\n\n if (ignoreWhitespace) {\n // Make whitespace flexible (tolerate indentation/spacing differences)\n // without letting it cross line boundaries: a whitespace run that contains\n // a newline keeps at least one newline, so a single-line oldText cannot\n // match across a newline and a multi-line oldText cannot collapse onto one\n // line. Horizontal whitespace stays mandatory between word characters so\n // adjacent identifiers are not merged. Built token by token: `split` on\n // whitespace puts text at even indices and whitespace runs at odd ones.\n const tokens = oldText.split(/(\\s+)/u);\n let pattern = '';\n for (const [i, token] of tokens.entries()) {\n if (i % 2 === 0) {\n pattern += RegExp.escape(token);\n } else if (token.includes('\\n')) {\n pattern += '[^\\\\S\\\\n]*\\\\n+[^\\\\S\\\\n]*';\n } else if (/\\w$/.test(tokens[i - 1] ?? '') && /^\\w/.test(tokens[i + 1] ?? '')) {\n pattern += '[^\\\\S\\\\n]+';\n } else {\n pattern += '[^\\\\S\\\\n]*';\n }\n }\n const regex = compileRegex(pattern, { caseSensitive: true });\n try {\n // execMatches resets lastIndex and reports UTF-16 offsets; the raw RE2\n // index counts code points and would splice off-by-one per emoji.\n const scan = (from: number): void => {\n for (const match of execMatches(regex, from === 0 ? content : content.slice(from))) {\n // A zero-length match names an empty span, which cannot be replaced.\n if (match.text.length > 0) add(from + match.start, match.text.length);\n if (from > 0) return;\n }\n };\n scan(0);\n // execMatches resumes past each match, so a second match overlapping the\n // first is never reported; look once more from just past its first\n // non-whitespace character. Starting inside the leading whitespace would\n // re-find the same occurrence, since the pattern's leading run is `*`. The\n // pattern carries no anchors, so matching a suffix finds the same spans.\n if (found.count === 1 && found.first) {\n const { startIndex, length } = found.first;\n const lead = content.slice(startIndex, startIndex + length).search(/\\S/u);\n scan(afterCodePoint(content, startIndex + lead));\n }\n } finally {\n // The compiled pattern owns wasm memory re2-wasm never reclaims on its\n // own; its lifetime is this one search.\n freeRegex(regex);\n }\n return found;\n }\n\n // Non-overlapping, so the scan stays linear on repetitive content; the one\n // overlap that matters — a second match inside the only one — is checked after.\n for (\n let i = content.indexOf(oldText);\n i !== -1;\n i = content.indexOf(oldText, i + oldText.length)\n ) {\n add(i, oldText.length);\n }\n if (found.count === 1 && found.first) {\n const overlap = content.indexOf(oldText, afterCodePoint(content, found.first.startIndex));\n if (overlap !== -1) add(overlap, oldText.length);\n }\n return found;\n}\n\n/** The UTF-16 offset just past the code point at `index`, so a surrogate pair is never split. */\nfunction afterCodePoint(content: string, index: number): number {\n return index + ((content.codePointAt(index) ?? 0) > 0xffff ? 2 : 1);\n}\n\nfunction ambiguousEditError(\n content: string,\n found: EditMatches,\n editIndex: number,\n shifted: boolean,\n): FsError {\n const lines = [\n ...new Set(found.starts.map((start) => content.slice(0, start).split('\\n').length)),\n ];\n const label = lines.length === 1 ? 'line' : 'lines';\n const more = found.count > found.starts.length ? ', ...' : '';\n // Offsets come from the content as earlier edits in this call left it, which\n // is not the file the caller read once one of them has applied.\n const where = shifted ? ' after earlier edits' : '';\n return new FsError(\n ErrorCode.INVALID_INPUT,\n `edits[${String(editIndex)}]: oldText matches ${String(found.count)} places${where} ` +\n `(${label} ${lines.join(', ')}${more}). Add surrounding lines so it matches once.`,\n );\n}\n\nfunction replaceEditMatch(content: string, match: TextRange, newText: string): string {\n return (\n content.slice(0, match.startIndex) + newText + content.slice(match.startIndex + match.length)\n );\n}\n\nfunction buildEditFileValue(\n validPath: string,\n meta: WrittenFileMeta,\n modified: string,\n result: EditResult,\n): EditFileValue {\n return {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n ...(meta.resourceUri !== undefined ? { resourceUri: meta.resourceUri } : {}),\n modified,\n appliedEdits: result.appliedEdits,\n ...(result.appliedEdits > 0\n ? { linesAdded: result.linesAdded, linesRemoved: result.linesRemoved }\n : {}),\n ...(result.unmatchedEdits.length > 0 ? { unmatchedEdits: result.unmatchedEdits } : {}),\n ...(result.diff ? { diff: result.diff } : {}),\n };\n}\n\nfunction buildEditFileMetadata(\n content: string,\n validPath: string,\n appliedEdits: number,\n resourceStore: ResourceStore | undefined,\n): WrittenFileMeta {\n const meta = buildWrittenFileMeta(validPath, content, resourceStore);\n // Omitted rather than empty-stringed when nothing matched: `\"\"` satisfied the\n // schema's `string` and then failed every resources/read a client tried it on.\n const written = appliedEdits > 0;\n return {\n ...meta,\n resourceUri: written ? meta.resourceUri : undefined,\n resourceLink: written ? meta.resourceLink : undefined,\n };\n}\n\nfunction applyEdits(\n content: string,\n edits: z.infer<typeof EditSpecSchema>[],\n ignoreWhitespace: boolean,\n): EditResult {\n let newContent = content;\n let appliedEdits = 0;\n const unmatchedEdits: string[] = [];\n\n for (const [index, edit] of edits.entries()) {\n const found = findEditMatches(newContent, edit.oldText, ignoreWhitespace);\n\n // A second match is an error rather than a pick: splicing the first would\n // edit a block the caller may not have meant and still report success.\n if (found.count > 1) throw ambiguousEditError(newContent, found, index, appliedEdits > 0);\n\n if (!found.first) {\n unmatchedEdits.push(edit.oldText);\n continue;\n }\n\n newContent = replaceEditMatch(newContent, found.first, edit.newText);\n appliedEdits += 1;\n }\n\n const { linesAdded, linesRemoved } =\n appliedEdits > 0 ? computeDiffStats(content, newContent) : { linesAdded: 0, linesRemoved: 0 };\n return { content: newContent, appliedEdits, unmatchedEdits, linesAdded, linesRemoved };\n}\n\ninterface EditFileOptions {\n dryRun: boolean;\n ignoreWhitespace: boolean;\n}\n\nasync function handleEditFile(\n filePath: string,\n edits: z.infer<typeof EditSpecSchema>[],\n options: EditFileOptions,\n ctx: ToolCtx,\n): Promise<{ file: EditFileValue; resourceLink?: ContentBlock }> {\n const { validPath, content } = await ctx.fs.readEditableText(filePath, {\n signal: ctx.signal,\n });\n const editResult = applyEdits(content, edits, options.ignoreWhitespace);\n\n if (options.dryRun) {\n if (editResult.appliedEdits > 0) {\n editResult.diff = unifiedPatch(basename(validPath), content, editResult.content);\n }\n\n // Nothing was written, so there is no updated content to point a\n // resourceUri or a resource_link at — the file on disk is still the one the\n // caller already has. Same rule the appliedEdits-is-0 case follows: no\n // write, no link.\n const meta = buildEditFileMetadata(editResult.content, validPath, 0, ctx.resourceStore);\n return {\n file: buildEditFileValue(validPath, meta, new Date().toISOString(), editResult),\n ...(meta.resourceLink ? { resourceLink: meta.resourceLink } : {}),\n };\n }\n\n if (editResult.unmatchedEdits.length > 0) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${editResult.unmatchedEdits.length} edit(s) failed to match. Verify oldText matches exact file content.`,\n filePath,\n );\n }\n\n if (editResult.appliedEdits > 0) {\n await ctx.fs.writeFile(filePath, editResult.content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n ctx.log?.(\n 'info',\n `edit: ${filePath} (${editResult.appliedEdits} edits, +${editResult.linesAdded}/-${editResult.linesRemoved})`,\n 'edit',\n );\n }\n\n // `modified` is read from a post-write stat and is advisory: under a concurrent\n // writer it may reflect that writer's mtime while `size`/content below come from\n // this edit's atomic write. The file content itself is always consistent.\n const { stats: fileStats } = await ctx.fs.stat(filePath, { signal: ctx.signal });\n const meta = buildEditFileMetadata(\n editResult.content,\n validPath,\n editResult.appliedEdits,\n ctx.resourceStore,\n );\n return {\n file: buildEditFileValue(validPath, meta, fileStats.mtime.toISOString(), editResult),\n ...(meta.resourceLink ? { resourceLink: meta.resourceLink } : {}),\n };\n}\n\nfunction formatEditSummary(\n results: readonly z.infer<typeof EditPerPathSchema>[],\n dryRun: boolean,\n): string {\n const tag = dryRun ? ' [dry run]' : '';\n // Single-file failure: say why here rather than making the caller read\n // structuredContent for the one message that can apply.\n const [only] = results;\n if (results.length === 1 && only?.error) {\n return `edit: ${only.path} FAILED — ${only.error.message}${tag}`;\n }\n const tokens = results.map((r) => {\n if (r.error) return `${basename(r.path)} FAILED`;\n const v = r.value;\n if (!v) return `${basename(r.path)} (no result)`;\n if (v.unmatchedEdits && v.unmatchedEdits.length > 0) return `${basename(v.path)} NO MATCH`;\n const added = v.linesAdded ?? 0;\n const removed = v.linesRemoved ?? 0;\n if (added === 0 && removed === 0) return `${basename(v.path)} (no change)`;\n return `${basename(v.path)} +${String(added)} -${String(removed)}`;\n });\n\n const failed = results.filter((r) => r.error !== undefined).length;\n const ok = results.length - failed;\n const ratio = failed > 0 ? ` (${String(ok)}/${String(results.length)} ok)` : '';\n return `edit: ${tokens.join(' · ')}${ratio}${tag}`;\n}\n\nexport const EDIT = defineTool({\n name: 'edit',\n title: 'Edit Files',\n description:\n 'Apply sequential literal string replacements to one or more files (max 5 files per call). ' +\n 'Modes: single-file { path, edits } or per-file { files: [{ path, edits }] }. ' +\n 'oldText must match file content exactly and only once; include 3-5 lines of surrounding context, ' +\n 'or the edit fails listing the lines it matched. ' +\n 'Set dryRun=true to preview diffs without writing. ' +\n 'For glob-based bulk regex replacement across many files, use replace_text instead.',\n input: EditFileInputSchema,\n output: EditFileOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => {\n const dryLabel = args.dryRun ? ' [dry run]' : '';\n let subject: string;\n if (args.path !== undefined) {\n subject = basename(args.path);\n } else if (args.files !== undefined) {\n subject = `${args.files.length} files`;\n } else {\n subject = 'files';\n }\n return { label: `Edit${dryLabel}`, subject };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n const sharedEdits = args.edits ?? [];\n const batchInput = args.path !== undefined ? { path: args.path } : { files: args.files ?? [] };\n\n const options: EditFileOptions = {\n dryRun: args.dryRun,\n ignoreWhitespace: args.ignoreWhitespace,\n };\n\n const batch = await runOverPaths<\n { edits: z.infer<typeof EditSpecSchema>[] },\n { file: EditFileValue; resourceLink?: ContentBlock }\n >(\n batchInput,\n ctx,\n ({ path, override }) => handleEditFile(path, override?.edits ?? sharedEdits, options, ctx),\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const perPathResults: z.infer<typeof EditPerPathSchema>[] = [];\n const resourceLinks: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n perPathResults.push({ path: r.path, error: r.error });\n continue;\n }\n perPathResults.push({ path: r.path, value: r.value.file });\n if (r.value.resourceLink) resourceLinks.push(r.value.resourceLink);\n }\n\n const summaryText = formatEditSummary(perPathResults, args.dryRun);\n\n return {\n structured: {\n results: perPathResults,\n summary: batch.summary,\n },\n text: summaryText,\n isError: isTotalFailure(batch.summary),\n ...(resourceLinks.length > 0 ? { resources: resourceLinks } : {}),\n };\n },\n});\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const FIND_FILES: import("./define.
|
|
1
|
+
export declare const FIND_FILES: import("./define.ts").DefinedTool;
|
|
2
2
|
//# sourceMappingURL=find-files.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find-files.d.ts","sourceRoot":"","sources":["../../src/tools/find-files.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"find-files.d.ts","sourceRoot":"","sources":["../../src/tools/find-files.ts"],"names":[],"mappings":"AAkKA,eAAO,MAAM,UAAU,mCA+CrB,CAAC"}
|
package/dist/tools/find-files.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import * as z from 'zod/v4';
|
|
2
|
-
import { SearchStoppedReasonSchema } from
|
|
3
|
-
import {
|
|
4
|
-
import { ErrorCode } from
|
|
5
|
-
import { formatCount, pageTrailer, truncateProgressPattern } from
|
|
6
|
-
import { toPosixRelative } from
|
|
7
|
-
import { CursorSchema,
|
|
8
|
-
import { searchFiles } from
|
|
9
|
-
import { putJsonResource } from
|
|
10
|
-
import { DEFAULT_SEARCH_RESULTS, DEFAULT_SEARCH_TIMEOUT_MS, MAX_SEARCH_RESULTS, } from
|
|
11
|
-
import { defineTool } from
|
|
2
|
+
import { SearchStoppedReasonSchema } from "../core/concurrency.js";
|
|
3
|
+
import { paginate } from "../core/cursor.js";
|
|
4
|
+
import { ErrorCode } from "../core/errors.js";
|
|
5
|
+
import { formatCount, pageTrailer, truncateProgressPattern } from "../core/fmt.js";
|
|
6
|
+
import { toPosixRelative } from "../core/path.js";
|
|
7
|
+
import { CursorSchema, IncludeHidden, IncludeIgnored, MaxDepth, NextCursorSchema, NonNegInt, OptionalPath, SafeGlobPattern, } from "../core/schema.js";
|
|
8
|
+
import { searchFiles } from "../core/search.js";
|
|
9
|
+
import { putJsonResource } from "../core/store.js";
|
|
10
|
+
import { DEFAULT_SEARCH_RESULTS, DEFAULT_SEARCH_TIMEOUT_MS, MAX_SEARCH_RESULTS, } from "../core/util.js";
|
|
11
|
+
import { defineTool } from "./define.js";
|
|
12
12
|
// ---------------------------------------------------------------------------
|
|
13
13
|
const SearchFilesInputSchema = z.strictObject({
|
|
14
14
|
path: OptionalPath.describe('Base directory to search under (default: first allowed root)'),
|
|
@@ -20,14 +20,14 @@ const SearchFilesInputSchema = z.strictObject({
|
|
|
20
20
|
.optional()
|
|
21
21
|
.default(DEFAULT_SEARCH_RESULTS)
|
|
22
22
|
.describe('Maximum number of matching files to return per page'),
|
|
23
|
-
includeIgnored:
|
|
24
|
-
includeHidden:
|
|
23
|
+
includeIgnored: IncludeIgnored,
|
|
24
|
+
includeHidden: IncludeHidden,
|
|
25
25
|
sortBy: z
|
|
26
26
|
.enum(['name', 'path'])
|
|
27
27
|
.optional()
|
|
28
28
|
.default('path')
|
|
29
29
|
.describe('Sort order: path = full path (default), name = basename only'),
|
|
30
|
-
maxDepth:
|
|
30
|
+
maxDepth: MaxDepth,
|
|
31
31
|
cursor: CursorSchema,
|
|
32
32
|
});
|
|
33
33
|
const SearchFilesOutputSchema = z.strictObject({
|
|
@@ -47,20 +47,11 @@ const SearchFilesOutputSchema = z.strictObject({
|
|
|
47
47
|
.describe('URI to the full results JSON in the resource store; first page only, whenever the response is incomplete — more pages follow, or the result cap cut the search'),
|
|
48
48
|
nextCursor: NextCursorSchema,
|
|
49
49
|
});
|
|
50
|
-
function buildRelativeResults(basePath, displayResults) {
|
|
51
|
-
const relativeResults = [];
|
|
52
|
-
for (const entry of displayResults) {
|
|
53
|
-
relativeResults.push({
|
|
54
|
-
path: toPosixRelative(basePath, entry.path),
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
return relativeResults;
|
|
58
|
-
}
|
|
59
50
|
function searchFilesOutput(results, metadata, nextCursor, resourceUri) {
|
|
60
51
|
return {
|
|
61
52
|
root: metadata.root,
|
|
62
53
|
results: [...results],
|
|
63
|
-
totalMatches: metadata.
|
|
54
|
+
totalMatches: metadata.matched,
|
|
64
55
|
filesScanned: metadata.filesScanned,
|
|
65
56
|
...(metadata.skippedInaccessible ? { skippedInaccessible: metadata.skippedInaccessible } : {}),
|
|
66
57
|
...(metadata.stoppedReason !== undefined ? { stoppedReason: metadata.stoppedReason } : {}),
|
|
@@ -70,7 +61,7 @@ function searchFilesOutput(results, metadata, nextCursor, resourceUri) {
|
|
|
70
61
|
}
|
|
71
62
|
async function handleSearchFiles(args, ctx) {
|
|
72
63
|
const requestedBasePath = ctx.fs.pathGuard.resolvePathOrRoot(args.path);
|
|
73
|
-
const queryKey =
|
|
64
|
+
const queryKey = JSON.stringify({
|
|
74
65
|
method: 'find_files',
|
|
75
66
|
path: requestedBasePath,
|
|
76
67
|
pattern: args.pattern,
|
|
@@ -97,18 +88,8 @@ async function handleSearchFiles(args, ctx) {
|
|
|
97
88
|
};
|
|
98
89
|
const result = await searchFiles(basePath, args.pattern, searchOptions, ctx.fs.pathGuard);
|
|
99
90
|
return {
|
|
100
|
-
items:
|
|
101
|
-
metadata: {
|
|
102
|
-
root: result.basePath,
|
|
103
|
-
totalMatches: result.summary.matched,
|
|
104
|
-
filesScanned: result.summary.filesScanned,
|
|
105
|
-
...(result.summary.skippedInaccessible
|
|
106
|
-
? { skippedInaccessible: result.summary.skippedInaccessible }
|
|
107
|
-
: {}),
|
|
108
|
-
...(result.summary.stoppedReason !== undefined
|
|
109
|
-
? { stoppedReason: result.summary.stoppedReason }
|
|
110
|
-
: {}),
|
|
111
|
-
},
|
|
91
|
+
items: result.results.map((r) => ({ path: toPosixRelative(result.basePath, r.path) })),
|
|
92
|
+
metadata: { root: result.basePath, ...result.summary },
|
|
112
93
|
truncated: result.summary.truncated,
|
|
113
94
|
};
|
|
114
95
|
},
|
|
@@ -119,7 +100,7 @@ async function handleSearchFiles(args, ctx) {
|
|
|
119
100
|
return {
|
|
120
101
|
structured: searchFilesOutput(paged.page, paged.metadata, paged.nextCursor, paged.resource?.entry.uri),
|
|
121
102
|
offset: paged.offset,
|
|
122
|
-
total: paged.metadata.
|
|
103
|
+
total: paged.metadata.matched,
|
|
123
104
|
...(paged.resource ? { link: paged.resource.link } : {}),
|
|
124
105
|
};
|
|
125
106
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find-files.js","sourceRoot":"","sources":["../../src/tools/find-files.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB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E,CAAC;IACrD,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QACvB,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC/E,MAAM,IAAI,GACR,UAAU,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;YAC3B,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YAClD,CAAC,CAAC,sBAAsB,IAAI,CAAC,OAAO,GAAG,CAAC;QAC5C,MAAM,IAAI,GACR,IAAI;YACJ,WAAW,CAAC;gBACV,MAAM;gBACN,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC,MAAM;gBAChC,KAAK;gBACL,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,YAAY;gBAClB,UAAU,EAAE,UAAU,CAAC,UAAU;gBACjC,aAAa,EAAE,UAAU,CAAC,aAAa;aACxC,CAAC,CAAC;QACL,IAAI,IAAI,EAAE,CAAC;YACT,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;IAC9B,CAAC;CACF,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { SearchStoppedReasonSchema } from '../core/concurrency.js';\nimport { pageQueryKey, paginate } from '../core/cursor.js';\nimport { ErrorCode } from '../core/errors.js';\nimport { formatCount, pageTrailer, truncateProgressPattern } from '../core/fmt.js';\nimport { toPosixRelative } from '../core/path.js';\nimport {\n CursorSchema,\n includeHiddenField,\n includeIgnoredField,\n maxDepthField,\n NextCursorSchema,\n NonNegInt,\n OptionalPath,\n SafeGlobPattern,\n} from '../core/schema.js';\nimport { searchFiles } from '../core/search.js';\nimport type { JsonResourceResult } from '../core/store.js';\nimport { putJsonResource } from '../core/store.js';\nimport {\n DEFAULT_SEARCH_RESULTS,\n DEFAULT_SEARCH_TIMEOUT_MS,\n MAX_SEARCH_RESULTS,\n} from '../core/util.js';\nimport { defineTool, type ToolCtx } from './define.js';\n\n// ---------------------------------------------------------------------------\n\nconst SearchFilesInputSchema = z.strictObject({\n path: OptionalPath.describe('Base directory to search under (default: first allowed root)'),\n pattern: SafeGlobPattern.describe('Glob pattern to match file paths (e.g. **/*.ts, src/**/*.js)'),\n maxResults: z\n .uint32()\n .min(1)\n .max(MAX_SEARCH_RESULTS)\n .optional()\n .default(DEFAULT_SEARCH_RESULTS)\n .describe('Maximum number of matching files to return per page'),\n includeIgnored: includeIgnoredField(),\n includeHidden: includeHiddenField(),\n sortBy: z\n .enum(['name', 'path'])\n .optional()\n .default('path')\n .describe('Sort order: path = full path (default), name = basename only'),\n maxDepth: maxDepthField(),\n cursor: CursorSchema,\n});\n\nconst SearchFilesOutputSchema = z.strictObject({\n root: z.string().describe('Resolved base directory used as the search root'),\n results: z\n .array(\n z.strictObject({\n path: z.string().describe('File path relative to the search root'),\n }),\n )\n .describe('Matched files ordered by sortBy'),\n totalMatches: NonNegInt.optional().describe('Total number of matching files found'),\n filesScanned: NonNegInt.optional().describe('Total number of files examined during the search'),\n skippedInaccessible: NonNegInt.optional().describe(\n 'Files skipped due to permission or access errors',\n ),\n stoppedReason: SearchStoppedReasonSchema.describe(\n 'Why the search ended early: maxResults = result cap reached, timeout = time limit hit or the request was cancelled. Absent when the scan ran to completion.',\n ),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to the full results JSON in the resource store; first page only, whenever the response is incomplete — more pages follow, or the result cap cut the search',\n ),\n nextCursor: NextCursorSchema,\n});\n\nfunction buildRelativeResults(\n basePath: string,\n displayResults: readonly { path: string }[],\n): NonNullable<z.infer<typeof SearchFilesOutputSchema>['results']> {\n const relativeResults: NonNullable<z.infer<typeof SearchFilesOutputSchema>['results']> = [];\n for (const entry of displayResults) {\n relativeResults.push({\n path: toPosixRelative(basePath, entry.path),\n });\n }\n return relativeResults;\n}\n\ntype SearchFileResult = NonNullable<z.infer<typeof SearchFilesOutputSchema>['results']>[number];\n\ninterface SearchFilesPageMetadata {\n readonly root: string;\n readonly totalMatches: number;\n readonly filesScanned: number;\n readonly skippedInaccessible?: number;\n readonly stoppedReason?: z.infer<typeof SearchFilesOutputSchema>['stoppedReason'];\n}\n\nfunction searchFilesOutput(\n results: readonly SearchFileResult[],\n metadata: SearchFilesPageMetadata,\n nextCursor: string | undefined,\n resourceUri: string | undefined,\n): z.infer<typeof SearchFilesOutputSchema> {\n return {\n root: metadata.root,\n results: [...results],\n totalMatches: metadata.totalMatches,\n filesScanned: metadata.filesScanned,\n ...(metadata.skippedInaccessible ? { skippedInaccessible: metadata.skippedInaccessible } : {}),\n ...(metadata.stoppedReason !== undefined ? { stoppedReason: metadata.stoppedReason } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n ...(nextCursor !== undefined ? { nextCursor } : {}),\n };\n}\n\nasync function handleSearchFiles(\n args: z.infer<typeof SearchFilesInputSchema>,\n ctx: ToolCtx,\n): Promise<{\n structured: z.infer<typeof SearchFilesOutputSchema>;\n offset: number;\n total: number;\n link?: ReturnType<typeof putJsonResource>['link'];\n}> {\n const requestedBasePath = ctx.fs.pathGuard.resolvePathOrRoot(args.path);\n const queryKey = pageQueryKey({\n method: 'find_files',\n path: requestedBasePath,\n pattern: args.pattern,\n includeIgnored: args.includeIgnored,\n includeHidden: args.includeHidden,\n sortBy: args.sortBy,\n maxDepth: args.maxDepth,\n });\n const { resourceStore } = ctx;\n\n const paged = await paginate<SearchFileResult, SearchFilesPageMetadata, JsonResourceResult>({\n store: ctx.pageStore,\n queryKey,\n cursor: args.cursor,\n pageSize: args.maxResults,\n produce: async () => {\n const basePath = await ctx.fs.pathGuard.validateExistingDirectory(requestedBasePath);\n const searchOptions: Parameters<typeof searchFiles>[2] = {\n maxResults: MAX_SEARCH_RESULTS,\n includeHidden: args.includeHidden,\n sortBy: args.sortBy,\n skipIgnored: !args.includeIgnored,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n signal: ctx.signal,\n };\n const result = await searchFiles(basePath, args.pattern, searchOptions, ctx.fs.pathGuard);\n return {\n items: buildRelativeResults(result.basePath, result.results),\n metadata: {\n root: result.basePath,\n totalMatches: result.summary.matched,\n filesScanned: result.summary.filesScanned,\n ...(result.summary.skippedInaccessible\n ? { skippedInaccessible: result.summary.skippedInaccessible }\n : {}),\n ...(result.summary.stoppedReason !== undefined\n ? { stoppedReason: result.summary.stoppedReason }\n : {}),\n },\n truncated: result.summary.truncated,\n };\n },\n externalize: resourceStore\n ? (results) => putJsonResource(resourceStore, `${args.pattern} files`, results)\n : undefined,\n });\n\n return {\n structured: searchFilesOutput(\n paged.page,\n paged.metadata,\n paged.nextCursor,\n paged.resource?.entry.uri,\n ),\n offset: paged.offset,\n total: paged.metadata.totalMatches,\n ...(paged.resource ? { link: paged.resource.link } : {}),\n };\n}\n\nexport const FIND_FILES = defineTool({\n name: 'find_files',\n title: 'Find Files',\n description:\n 'Find files matching a glob pattern. Returns matched paths with optional metadata. ' +\n 'Pagination cursors reference a query-bound snapshot that expires after 60 seconds. ' +\n 'For content search use search_text; for bulk regex replacements use replace_text with the same glob.',\n input: SearchFilesInputSchema,\n output: SearchFilesOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.UNKNOWN,\n progress: (args) => ({\n label: 'Find',\n subject: truncateProgressPattern(args.pattern),\n }),\n progressDone: (_args, result) => ({\n detail: formatCount(result.totalMatches ?? 0, 'match', 'matches'),\n }),\n accessPaths: (args) => (args.path ? [args.path] : []),\n run: async (args, ctx) => {\n const { structured, offset, total, link } = await handleSearchFiles(args, ctx);\n const body =\n structured.results.length > 0\n ? structured.results.map((r) => r.path).join('\\n')\n : `No files matching '${args.pattern}'`;\n const text =\n body +\n pageTrailer({\n offset,\n shown: structured.results.length,\n total,\n noun: 'files',\n tool: 'find_files',\n nextCursor: structured.nextCursor,\n stoppedReason: structured.stoppedReason,\n });\n if (link) {\n return { structured, text, resources: [link] };\n }\n return { structured, text };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"find-files.js","sourceRoot":"","sources":["../../src/tools/find-files.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,cAAc,EACd,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACT,YAAY,EACZ,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAgB,MAAM,aAAa,CAAC;AAEvD,8EAA8E;AAE9E,MAAM,sBAAsB,GAAG,CAAC,CAAC,YAAY,CAAC;IAC5C,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,8DAA8D,CAAC;IAC3F,OAAO,EAAE,eAAe,CAAC,QAAQ,CAAC,8DAA8D,CAAC;IACjG,UAAU,EA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CAAC;IACF,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACrD,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QACvB,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC/E,MAAM,IAAI,GACR,UAAU,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;YAC3B,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YAClD,CAAC,CAAC,sBAAsB,IAAI,CAAC,OAAO,GAAG,CAAC;QAC5C,MAAM,IAAI,GACR,IAAI;YACJ,WAAW,CAAC;gBACV,MAAM;gBACN,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC,MAAM;gBAChC,KAAK;gBACL,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,YAAY;gBAClB,UAAU,EAAE,UAAU,CAAC,UAAU;gBACjC,aAAa,EAAE,UAAU,CAAC,aAAa;aACxC,CAAC,CAAC;QACL,IAAI,IAAI,EAAE,CAAC;YACT,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;IAC9B,CAAC;CACF,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { SearchStoppedReasonSchema } from '../core/concurrency.ts';\nimport { paginate } from '../core/cursor.ts';\nimport { ErrorCode } from '../core/errors.ts';\nimport { formatCount, pageTrailer, truncateProgressPattern } from '../core/fmt.ts';\nimport { toPosixRelative } from '../core/path.ts';\nimport {\n CursorSchema,\n IncludeHidden,\n IncludeIgnored,\n MaxDepth,\n NextCursorSchema,\n NonNegInt,\n OptionalPath,\n SafeGlobPattern,\n} from '../core/schema.ts';\nimport { searchFiles } from '../core/search.ts';\nimport type { JsonResourceResult } from '../core/store.ts';\nimport { putJsonResource } from '../core/store.ts';\nimport {\n DEFAULT_SEARCH_RESULTS,\n DEFAULT_SEARCH_TIMEOUT_MS,\n MAX_SEARCH_RESULTS,\n} from '../core/util.ts';\nimport { defineTool, type ToolCtx } from './define.ts';\n\n// ---------------------------------------------------------------------------\n\nconst SearchFilesInputSchema = z.strictObject({\n path: OptionalPath.describe('Base directory to search under (default: first allowed root)'),\n pattern: SafeGlobPattern.describe('Glob pattern to match file paths (e.g. **/*.ts, src/**/*.js)'),\n maxResults: z\n .uint32()\n .min(1)\n .max(MAX_SEARCH_RESULTS)\n .optional()\n .default(DEFAULT_SEARCH_RESULTS)\n .describe('Maximum number of matching files to return per page'),\n includeIgnored: IncludeIgnored,\n includeHidden: IncludeHidden,\n sortBy: z\n .enum(['name', 'path'])\n .optional()\n .default('path')\n .describe('Sort order: path = full path (default), name = basename only'),\n maxDepth: MaxDepth,\n cursor: CursorSchema,\n});\n\nconst SearchFilesOutputSchema = z.strictObject({\n root: z.string().describe('Resolved base directory used as the search root'),\n results: z\n .array(\n z.strictObject({\n path: z.string().describe('File path relative to the search root'),\n }),\n )\n .describe('Matched files ordered by sortBy'),\n totalMatches: NonNegInt.optional().describe('Total number of matching files found'),\n filesScanned: NonNegInt.optional().describe('Total number of files examined during the search'),\n skippedInaccessible: NonNegInt.optional().describe(\n 'Files skipped due to permission or access errors',\n ),\n stoppedReason: SearchStoppedReasonSchema.describe(\n 'Why the search ended early: maxResults = result cap reached, timeout = time limit hit or the request was cancelled. Absent when the scan ran to completion.',\n ),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to the full results JSON in the resource store; first page only, whenever the response is incomplete — more pages follow, or the result cap cut the search',\n ),\n nextCursor: NextCursorSchema,\n});\n\ntype SearchFileResult = z.infer<typeof SearchFilesOutputSchema>['results'][number];\n\n/** The engine's own summary plus its root is the page metadata; nothing is copied out of it. */\ntype SearchFilesPageMetadata = Awaited<ReturnType<typeof searchFiles>>['summary'] & {\n readonly root: string;\n};\n\nfunction searchFilesOutput(\n results: readonly SearchFileResult[],\n metadata: SearchFilesPageMetadata,\n nextCursor: string | undefined,\n resourceUri: string | undefined,\n): z.infer<typeof SearchFilesOutputSchema> {\n return {\n root: metadata.root,\n results: [...results],\n totalMatches: metadata.matched,\n filesScanned: metadata.filesScanned,\n ...(metadata.skippedInaccessible ? { skippedInaccessible: metadata.skippedInaccessible } : {}),\n ...(metadata.stoppedReason !== undefined ? { stoppedReason: metadata.stoppedReason } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n ...(nextCursor !== undefined ? { nextCursor } : {}),\n };\n}\n\nasync function handleSearchFiles(\n args: z.infer<typeof SearchFilesInputSchema>,\n ctx: ToolCtx,\n): Promise<{\n structured: z.infer<typeof SearchFilesOutputSchema>;\n offset: number;\n total: number;\n link?: ReturnType<typeof putJsonResource>['link'];\n}> {\n const requestedBasePath = ctx.fs.pathGuard.resolvePathOrRoot(args.path);\n const queryKey = JSON.stringify({\n method: 'find_files',\n path: requestedBasePath,\n pattern: args.pattern,\n includeIgnored: args.includeIgnored,\n includeHidden: args.includeHidden,\n sortBy: args.sortBy,\n maxDepth: args.maxDepth,\n });\n const { resourceStore } = ctx;\n\n const paged = await paginate<SearchFileResult, SearchFilesPageMetadata, JsonResourceResult>({\n store: ctx.pageStore,\n queryKey,\n cursor: args.cursor,\n pageSize: args.maxResults,\n produce: async () => {\n const basePath = await ctx.fs.pathGuard.validateExistingDirectory(requestedBasePath);\n const searchOptions: Parameters<typeof searchFiles>[2] = {\n maxResults: MAX_SEARCH_RESULTS,\n includeHidden: args.includeHidden,\n sortBy: args.sortBy,\n skipIgnored: !args.includeIgnored,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n signal: ctx.signal,\n };\n const result = await searchFiles(basePath, args.pattern, searchOptions, ctx.fs.pathGuard);\n return {\n items: result.results.map((r) => ({ path: toPosixRelative(result.basePath, r.path) })),\n metadata: { root: result.basePath, ...result.summary },\n truncated: result.summary.truncated,\n };\n },\n externalize: resourceStore\n ? (results) => putJsonResource(resourceStore, `${args.pattern} files`, results)\n : undefined,\n });\n\n return {\n structured: searchFilesOutput(\n paged.page,\n paged.metadata,\n paged.nextCursor,\n paged.resource?.entry.uri,\n ),\n offset: paged.offset,\n total: paged.metadata.matched,\n ...(paged.resource ? { link: paged.resource.link } : {}),\n };\n}\n\nexport const FIND_FILES = defineTool({\n name: 'find_files',\n title: 'Find Files',\n description:\n 'Find files matching a glob pattern. Returns matched paths with optional metadata. ' +\n 'Pagination cursors reference a query-bound snapshot that expires after 60 seconds. ' +\n 'For content search use search_text; for bulk regex replacements use replace_text with the same glob.',\n input: SearchFilesInputSchema,\n output: SearchFilesOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.UNKNOWN,\n progress: (args) => ({\n label: 'Find',\n subject: truncateProgressPattern(args.pattern),\n }),\n progressDone: (_args, result) => ({\n detail: formatCount(result.totalMatches ?? 0, 'match', 'matches'),\n }),\n accessPaths: (args) => (args.path ? [args.path] : []),\n run: async (args, ctx) => {\n const { structured, offset, total, link } = await handleSearchFiles(args, ctx);\n const body =\n structured.results.length > 0\n ? structured.results.map((r) => r.path).join('\\n')\n : `No files matching '${args.pattern}'`;\n const text =\n body +\n pageTrailer({\n offset,\n shown: structured.results.length,\n total,\n noun: 'files',\n tool: 'find_files',\n nextCursor: structured.nextCursor,\n stoppedReason: structured.stoppedReason,\n });\n if (link) {\n return { structured, text, resources: [link] };\n }\n return { structured, text };\n },\n});\n"]}
|