@j0hanz/filesystem-mcp 2.6.3 → 2.7.1
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 +28 -19
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +5 -2
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +22 -3
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts +0 -17
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +53 -47
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/config.d.ts +7 -0
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js +7 -0
- package/dist/core/config.js.map +1 -1
- package/dist/core/diff.d.ts +0 -4
- package/dist/core/diff.d.ts.map +1 -1
- package/dist/core/diff.js +1 -15
- package/dist/core/diff.js.map +1 -1
- package/dist/core/file-uri.d.ts +9 -9
- package/dist/core/file-uri.d.ts.map +1 -1
- package/dist/core/file-uri.js +16 -11
- package/dist/core/file-uri.js.map +1 -1
- package/dist/core/fs.d.ts +1 -1
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +65 -56
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +6 -0
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +80 -13
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +30 -13
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +35 -10
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/mime.d.ts +2 -4
- package/dist/core/mime.d.ts.map +1 -1
- package/dist/core/mime.js +3 -8
- package/dist/core/mime.js.map +1 -1
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +7 -4
- 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 +2 -2
- package/dist/core/path-discovery.js.map +1 -1
- package/dist/core/path-utils.d.ts +1 -3
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +0 -3
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +7 -0
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +69 -26
- package/dist/core/path.js.map +1 -1
- package/dist/core/read.d.ts +1 -0
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +4 -0
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts +0 -80
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +0 -89
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts +8 -1
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +191 -101
- package/dist/core/search.js.map +1 -1
- package/dist/core/store.d.ts +7 -11
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +19 -21
- package/dist/core/store.js.map +1 -1
- package/dist/core/util.d.ts +17 -0
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +19 -0
- package/dist/core/util.js.map +1 -1
- package/dist/instructions.js +1 -1
- package/dist/instructions.js.map +1 -1
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +5 -2
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +8 -1
- package/dist/server.js.map +1 -1
- package/dist/tools/batch.d.ts +3 -13
- package/dist/tools/batch.d.ts.map +1 -1
- package/dist/tools/batch.js +11 -27
- package/dist/tools/batch.js.map +1 -1
- package/dist/tools/create.d.ts.map +1 -1
- package/dist/tools/create.js +25 -46
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +20 -23
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +11 -27
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts.map +1 -1
- package/dist/tools/delete.js +10 -37
- package/dist/tools/delete.js.map +1 -1
- package/dist/tools/diff.d.ts.map +1 -1
- package/dist/tools/diff.js +2 -13
- package/dist/tools/diff.js.map +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +20 -53
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/find-files.d.ts.map +1 -1
- package/dist/tools/find-files.js +3 -28
- package/dist/tools/find-files.js.map +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/list-roots.d.ts.map +1 -1
- package/dist/tools/list-roots.js +1 -12
- package/dist/tools/list-roots.js.map +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +19 -53
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +54 -37
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/patch.d.ts.map +1 -1
- package/dist/tools/patch.js +4 -24
- package/dist/tools/patch.js.map +1 -1
- package/dist/tools/progress.d.ts +0 -2
- package/dist/tools/progress.d.ts.map +1 -1
- package/dist/tools/progress.js +20 -12
- package/dist/tools/progress.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +29 -116
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts.map +1 -1
- package/dist/tools/replace-text.js +20 -43
- package/dist/tools/replace-text.js.map +1 -1
- package/dist/tools/search-text.d.ts.map +1 -1
- package/dist/tools/search-text.js +24 -78
- package/dist/tools/search-text.js.map +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +5 -19
- package/dist/tools/stat.js.map +1 -1
- package/dist/transport/http-policy.d.ts.map +1 -1
- package/dist/transport/http-policy.js +1 -0
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +16 -27
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/shared.d.ts +3 -1
- package/dist/transport/shared.d.ts.map +1 -1
- package/dist/transport/shared.js +14 -1
- package/dist/transport/shared.js.map +1 -1
- package/dist/transport/stdio.d.ts.map +1 -1
- package/dist/transport/stdio.js +18 -3
- package/dist/transport/stdio.js.map +1 -1
- package/package.json +3 -3
package/dist/tools/move.js
CHANGED
|
@@ -1,44 +1,26 @@
|
|
|
1
1
|
import { isInputRequiredResult } from '@modelcontextprotocol/server';
|
|
2
|
-
import {
|
|
2
|
+
import { stat } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, relative, resolve } from 'node:path';
|
|
3
4
|
import * as z from 'zod/v4';
|
|
4
5
|
import { processInParallel } from "../core/concurrency.js";
|
|
5
6
|
import { ErrorCode, FsError, isFsError, isNodeError, Problem, rethrowIfAborted, } from "../core/errors.js";
|
|
6
7
|
import { joinRoster, pathLabel } from "../core/fmt.js";
|
|
7
8
|
import { destExists } from "../core/fs.js";
|
|
9
|
+
import { globEntries } from "../core/glob.js";
|
|
8
10
|
import { confirmKey, describeRefusal, pendingRoundTrip, readAcceptedChoice, } from "../core/input-required.js";
|
|
9
11
|
import { isPathInsideDirectory, isSamePath, normalizeCaseForComparison, respellCaseOnlyTarget, } from "../core/path-utils.js";
|
|
10
|
-
import { defaultFalseBoolean,
|
|
12
|
+
import { defaultFalseBoolean, RequiredPath } from "../core/schema.js";
|
|
11
13
|
import { PARALLEL_CONCURRENCY } from "../core/util.js";
|
|
12
14
|
import { defineTool } from "./define.js";
|
|
13
15
|
const MoveItemSchema = z.strictObject({
|
|
14
16
|
source: RequiredPath.describe('Path of the file or directory to move or copy'),
|
|
15
17
|
destination: RequiredPath.describe('Destination path'),
|
|
16
18
|
});
|
|
17
|
-
const MoveItemResultSchema = z.strictObject({
|
|
18
|
-
from: z.string().describe('Resolved absolute source path'),
|
|
19
|
-
to: z.string().describe('Resolved absolute destination path'),
|
|
20
|
-
});
|
|
21
19
|
const MoveInputSchema = z.strictObject({
|
|
22
20
|
moves: z.array(MoveItemSchema).min(1).max(100).describe('Operations to perform (max 100)'),
|
|
23
21
|
copy: defaultFalseBoolean('Copy instead of move; sources are left in place'),
|
|
24
22
|
overwrite: defaultFalseBoolean('Copy mode only: overwrite existing destinations without confirmation'),
|
|
25
23
|
});
|
|
26
|
-
const MoveFailureItemSchema = z.strictObject({
|
|
27
|
-
source: z.string().describe('Source path that could not be moved'),
|
|
28
|
-
destination: z.string().describe('Intended destination path for the failed move'),
|
|
29
|
-
error: PerFileErrorSchema,
|
|
30
|
-
});
|
|
31
|
-
const MoveOutputSchema = z.strictObject({
|
|
32
|
-
moves: z.array(MoveItemResultSchema).describe('Successfully completed operations'),
|
|
33
|
-
failures: z
|
|
34
|
-
.array(MoveFailureItemSchema)
|
|
35
|
-
.optional()
|
|
36
|
-
.describe('Operations that failed with per-item error details'),
|
|
37
|
-
skipped: z
|
|
38
|
-
.array(z.string())
|
|
39
|
-
.optional()
|
|
40
|
-
.describe('Destinations skipped because the user chose Skip'),
|
|
41
|
-
});
|
|
42
24
|
const VERB = { move: 'Move', copy: 'Copy' };
|
|
43
25
|
/**
|
|
44
26
|
* Phase 1 (no mutation): validate source and destination, reject self-targets
|
|
@@ -50,13 +32,16 @@ const VERB = { move: 'Move', copy: 'Copy' };
|
|
|
50
32
|
* `overwrite` is copy-only — move has no confirmation bypass — so a move always
|
|
51
33
|
* passes false.
|
|
52
34
|
*/
|
|
53
|
-
async function planTransfer(op, pair, fs, overwrite) {
|
|
35
|
+
async function planTransfer(op, pair, fs, overwrite, signal) {
|
|
54
36
|
let realSource;
|
|
55
37
|
let opSource;
|
|
56
38
|
let validDest;
|
|
57
39
|
try {
|
|
58
40
|
({ realSource, opSource } = await validateTransferSource(op, pair.source, fs));
|
|
59
41
|
validDest = await fs.pathGuard.validatePathForWrite(pair.destination);
|
|
42
|
+
if (!(op === 'move' && opSource !== realSource) && (await stat(realSource)).isDirectory()) {
|
|
43
|
+
await assertTreeHasNoProtectedEntries(op, realSource, pair.source, validDest, fs, signal);
|
|
44
|
+
}
|
|
60
45
|
}
|
|
61
46
|
catch (error) {
|
|
62
47
|
return { status: 'fail', failure: pairFailure(pair, error) };
|
|
@@ -108,7 +93,7 @@ async function executeTransfer(op, plan, ctx, pendingSorted) {
|
|
|
108
93
|
return { skipped: plan.pair.destination };
|
|
109
94
|
}
|
|
110
95
|
if (choice !== 'overwrite') {
|
|
111
|
-
throw new FsError(ErrorCode.CANCELLED, `${VERB[op]} cancelled: overwrite of "${plan.pair.destination}" was ${describeRefusal(ctx
|
|
96
|
+
throw new FsError(ErrorCode.CANCELLED, `${VERB[op]} cancelled: overwrite of "${plan.pair.destination}" was ${describeRefusal(ctx, key)}`, plan.pair.destination);
|
|
112
97
|
}
|
|
113
98
|
}
|
|
114
99
|
// TOCTOU check before any mutation: a destination that did not exist when
|
|
@@ -121,7 +106,7 @@ async function executeTransfer(op, plan, ctx, pendingSorted) {
|
|
|
121
106
|
await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });
|
|
122
107
|
if (op === 'move') {
|
|
123
108
|
await performRenameWithFallback(plan.opSource, plan.validDest, ctx.fs, plan.pair.source);
|
|
124
|
-
ctx.log
|
|
109
|
+
ctx.log('info', `move: ${plan.pair.source} -> ${plan.pair.destination}`, 'move');
|
|
125
110
|
}
|
|
126
111
|
else {
|
|
127
112
|
await ctx.fs.cp(plan.opSource, plan.validDest, {
|
|
@@ -147,7 +132,7 @@ function pairFailure(pair, error) {
|
|
|
147
132
|
* their `plan` and `execute` callbacks.
|
|
148
133
|
*/
|
|
149
134
|
async function runTransfers(items, ctx, op, overwrite) {
|
|
150
|
-
const { results: planned, errors: planErrors } = await processInParallel(items, (pair) => planTransfer(op, pair, ctx.fs, overwrite), PARALLEL_CONCURRENCY, ctx.signal);
|
|
135
|
+
const { results: planned, errors: planErrors } = await processInParallel(items, (pair) => planTransfer(op, pair, ctx.fs, overwrite, ctx.signal), PARALLEL_CONCURRENCY, ctx.signal);
|
|
151
136
|
// plan callbacks are fail-closed (they return { status: 'fail' }, never
|
|
152
137
|
// throw), so planErrors should always be empty. Surface the first rather
|
|
153
138
|
// than silently dropping the item if a future plan callback violates that.
|
|
@@ -186,12 +171,9 @@ async function runTransfers(items, ctx, op, overwrite) {
|
|
|
186
171
|
if (pendingSorted.length > 0) {
|
|
187
172
|
// Round 1 returns input_required; a retry whose verified state does not
|
|
188
173
|
// bind this overwrite set throws (R9) via `pendingRoundTrip`.
|
|
189
|
-
const round = await pendingRoundTrip({
|
|
174
|
+
const round = await pendingRoundTrip(ctx, {
|
|
190
175
|
op,
|
|
191
176
|
pending: pendingSorted,
|
|
192
|
-
requestState: ctx.requestState,
|
|
193
|
-
clientCapabilities: ctx.clientCapabilities,
|
|
194
|
-
serverCtx: ctx.serverCtx,
|
|
195
177
|
buildInputs: (dests) => dests.map((dest, i) => ({
|
|
196
178
|
key: confirmKey(i),
|
|
197
179
|
message: op === 'move'
|
|
@@ -207,7 +189,7 @@ async function runTransfers(items, ctx, op, overwrite) {
|
|
|
207
189
|
let completed = 0;
|
|
208
190
|
const tick = () => {
|
|
209
191
|
completed += 1;
|
|
210
|
-
ctx.onProgress
|
|
192
|
+
ctx.onProgress({ current: completed, total });
|
|
211
193
|
};
|
|
212
194
|
const { results: execResults, errors: execErrors } = await processInParallel(ready, async (readyPlan) => {
|
|
213
195
|
try {
|
|
@@ -268,6 +250,46 @@ async function validateTransferSource(op, source, fs) {
|
|
|
268
250
|
throw new FsError(ErrorCode.ACCESS_DENIED, `${VERB[op]} failed for ${source}`, source);
|
|
269
251
|
}
|
|
270
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* A directory transfer may proceed only when every entry keeps the same
|
|
255
|
+
* sensitive-file status before and after relocation. Path-based rules
|
|
256
|
+
* (`secrets/**`, `.aws/credentials`) follow the path, not the file, so refuse
|
|
257
|
+
* any entry that would leave or enter the protected set. Walk the tree once
|
|
258
|
+
* before any mutation and fail the pair closed if anything changes status.
|
|
259
|
+
* Name-based rules need no help — they match after the move too.
|
|
260
|
+
*/
|
|
261
|
+
async function assertTreeHasNoProtectedEntries(op, realSource, requestedSource, validDest, fs, signal) {
|
|
262
|
+
let protectedCount = 0;
|
|
263
|
+
const entries = globEntries({
|
|
264
|
+
cwd: realSource,
|
|
265
|
+
pattern: '**/*',
|
|
266
|
+
includeHidden: true,
|
|
267
|
+
skipIgnored: false,
|
|
268
|
+
onlyFiles: false,
|
|
269
|
+
...(signal ? { signal } : {}),
|
|
270
|
+
});
|
|
271
|
+
try {
|
|
272
|
+
for await (const entry of entries) {
|
|
273
|
+
signal?.throwIfAborted();
|
|
274
|
+
const entryRelativePath = relative(realSource, entry.path);
|
|
275
|
+
const requestedSourcePath = resolve(requestedSource, entryRelativePath);
|
|
276
|
+
const destinationPath = resolve(validDest, entryRelativePath);
|
|
277
|
+
const protectedBefore = fs.pathGuard.isSensitive(entry.path) || fs.pathGuard.isSensitive(requestedSourcePath);
|
|
278
|
+
const protectedAfter = fs.pathGuard.isSensitive(destinationPath);
|
|
279
|
+
if (protectedBefore !== protectedAfter) {
|
|
280
|
+
protectedCount++;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
rethrowIfAborted(error);
|
|
287
|
+
throw new FsError(ErrorCode.ACCESS_DENIED, `${VERB[op]} refused: the directory could not be fully inspected for protected entries`, requestedSource, error);
|
|
288
|
+
}
|
|
289
|
+
if (protectedCount > 0) {
|
|
290
|
+
throw new FsError(ErrorCode.ACCESS_DENIED, `${VERB[op]} refused: the directory contains protected entries matching the sensitive-file policy; move or copy individual files instead`, requestedSource);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
271
293
|
export async function performRenameWithFallback(validSource, validDest, fsOps, originalSource) {
|
|
272
294
|
try {
|
|
273
295
|
await fsOps.rename(validSource, validDest);
|
|
@@ -309,12 +331,7 @@ export const MOVE = defineTool({
|
|
|
309
331
|
description: 'Move, rename, or copy files and directories, like mv or cp -r. ' +
|
|
310
332
|
'Each destination is the full new path, not a folder to move into; missing parent directories are created.',
|
|
311
333
|
input: MoveInputSchema,
|
|
312
|
-
|
|
313
|
-
annotations: {
|
|
314
|
-
readOnlyHint: false,
|
|
315
|
-
destructiveHint: true,
|
|
316
|
-
openWorldHint: false,
|
|
317
|
-
},
|
|
334
|
+
readOnlyHint: false,
|
|
318
335
|
progress: (args) => {
|
|
319
336
|
const label = args.copy ? 'Copy' : 'Move';
|
|
320
337
|
if (args.moves.length === 1) {
|
package/dist/tools/move.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"move.js","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,WAAW,EACX,OAAO,EACP,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,qBAAqB,EACrB,UAAU,EACV,0BAA0B,EAC1B,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC1F,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,cAAc,GAAG,CAAC,CAAC,YAAY,CAAC;IACpC,MAAM,EAAE,YAAY,CA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E,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC5C,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC3C;YACD,IAAI,EAAE,YAAY,CAAC,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC;YAClD,2EAA2E;YAC3E,uEAAuE;YACvE,OAAO,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,CAAC;SACtE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename, dirname, resolve } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.ts';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.ts';\nimport { joinRoster, pathLabel } from '../core/fmt.ts';\nimport { destExists } from '../core/fs.ts';\nimport type { GuardedFileSystem } from '../core/fs.ts';\nimport {\n confirmKey,\n describeRefusal,\n pendingRoundTrip,\n readAcceptedChoice,\n} from '../core/input-required.ts';\nimport {\n isPathInsideDirectory,\n isSamePath,\n normalizeCaseForComparison,\n respellCaseOnlyTarget,\n} from '../core/path-utils.ts';\nimport { defaultFalseBoolean, PerFileErrorSchema, RequiredPath } from '../core/schema.ts';\nimport { PARALLEL_CONCURRENCY } from '../core/util.ts';\nimport type { ToolCtx } from './define.ts';\nimport { defineTool } from './define.ts';\n\nconst MoveItemSchema = z.strictObject({\n source: RequiredPath.describe('Path of the file or directory to move or copy'),\n destination: RequiredPath.describe('Destination path'),\n});\n\nconst MoveItemResultSchema = z.strictObject({\n from: z.string().describe('Resolved absolute source path'),\n to: z.string().describe('Resolved absolute destination path'),\n});\n\nconst MoveInputSchema = z.strictObject({\n moves: z.array(MoveItemSchema).min(1).max(100).describe('Operations to perform (max 100)'),\n copy: defaultFalseBoolean('Copy instead of move; sources are left in place'),\n overwrite: defaultFalseBoolean(\n 'Copy mode only: overwrite existing destinations without confirmation',\n ),\n});\n\nconst MoveFailureItemSchema = z.strictObject({\n source: z.string().describe('Source path that could not be moved'),\n destination: z.string().describe('Intended destination path for the failed move'),\n error: PerFileErrorSchema,\n});\n\ntype MoveFailureItem = z.infer<typeof MoveFailureItemSchema>;\n\nconst MoveOutputSchema = z.strictObject({\n moves: z.array(MoveItemResultSchema).describe('Successfully completed operations'),\n failures: z\n .array(MoveFailureItemSchema)\n .optional()\n .describe('Operations that failed with per-item error details'),\n skipped: z\n .array(z.string())\n .optional()\n .describe('Destinations skipped because the user chose Skip'),\n});\n\ntype MoveItemResult = z.infer<typeof MoveItemResultSchema>;\n\ntype PairOp = 'move' | 'copy';\n\nconst VERB: Readonly<Record<PairOp, string>> = { move: 'Move', copy: 'Copy' };\n\n/** A move or copy pre-checked up to the point a confirmation decision is needed. */\ninterface TransferPlan {\n pair: { source: string; destination: string };\n /**\n * The path the mutation runs on: the link itself for a move, the resolved\n * target for a copy. Every collision check uses the resolved source instead\n * — see {@link validateTransferSource}.\n */\n opSource: string;\n validDest: string;\n /**\n * A rename that only changes the destination's case. Move must perform it —\n * it is real work — so it is exempt from the destination-exists checks that\n * would otherwise read the source itself as an existing destination. Never\n * true for a copy, which treats a case-only target as a self-copy and skips.\n */\n isCaseOnlyRename: boolean;\n /** Whether the destination existed when planned (drives the TOCTOU guard). */\n destExistedOriginally: boolean;\n /** Destination exists and is not a self/case-only target → needs overwrite confirmation. */\n pending: boolean;\n}\n\n/**\n * Phase 1 (no mutation): validate source and destination, reject self-targets\n * and transfers into a subdirectory of the source, and stat the destination to\n * decide whether this pair needs an overwrite confirmation. No `mkdir` happens\n * here — the old flow created the destination's parent before asking, which\n * mutated the filesystem before a confirmation; that now waits for phase 2 (R14).\n *\n * `overwrite` is copy-only — move has no confirmation bypass — so a move always\n * passes false.\n */\nasync function planTransfer(\n op: PairOp,\n pair: { source: string; destination: string },\n fs: ToolCtx['fs'],\n overwrite: boolean,\n): Promise<TransferPlanResult> {\n let realSource: string;\n let opSource: string;\n let validDest: string;\n try {\n ({ realSource, opSource } = await validateTransferSource(op, pair.source, fs));\n validDest = await fs.pathGuard.validatePathForWrite(pair.destination);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(pair, error) };\n }\n\n // Comparisons run on the resolved source; only the fs call in phase 2 uses\n // opSource. validatePathForWrite resolves the destination through a symlink\n // too, so both sides of every check must be resolved to match.\n const resolvedSource = resolve(realSource);\n let resolvedDest = resolve(validDest);\n\n // validatePathForWrite realpaths an existing destination to its on-disk\n // spelling, so a case-only rename resolves to the source itself; re-spell\n // it with the requested basename before deciding self vs. rename.\n if (resolvedSource === resolvedDest) {\n validDest = respellCaseOnlyTarget(pair.destination, validDest);\n resolvedDest = resolve(validDest);\n }\n\n const isSelf = resolvedSource === resolvedDest;\n const isCaseOnlyRename = !isSelf && isSamePath(resolvedSource, resolvedDest);\n\n // A copy onto a case-only variant of its own source is the same file, so it\n // is a no-op; the same rename is real work for move and proceeds.\n if (isSelf || (isCaseOnlyRename && op === 'copy')) {\n return { status: 'noop' };\n }\n\n if (!isCaseOnlyRename && isPathInsideDirectory(resolvedSource, resolvedDest)) {\n return {\n status: 'fail',\n failure: pairFailure(\n pair,\n new FsError(\n ErrorCode.INVALID_INPUT,\n `Cannot ${op} a directory into its own subdirectory`,\n pair.source,\n ),\n ),\n };\n }\n\n const destExistedOriginally = !isCaseOnlyRename && (await destExists(fs, validDest, op));\n const pending = destExistedOriginally && !overwrite;\n\n return {\n status: 'plan',\n plan: { pair, opSource, validDest, isCaseOnlyRename, destExistedOriginally, pending },\n };\n}\n\n/**\n * Phase 2 (mutation): confirm an overwrite if needed, TOCTOU-check the\n * destination, create its parent, then rename (with cross-device fallback) or\n * copy. A declined/missing confirmation throws `CANCELLED`, collected as a\n * per-pair failure by the caller. A destination that appeared between plan and\n * mutation (created during the confirmation gap) also fails closed.\n */\nasync function executeTransfer(\n op: PairOp,\n plan: TransferPlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<TransferExecResult> {\n if (plan.pending) {\n const key = confirmKey(pendingSorted.indexOf(plan.validDest));\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `${VERB[op]} cancelled: overwrite of \"${plan.pair.destination}\" was ${describeRefusal(ctx.inputResponses, key)}`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if (\n !plan.isCaseOnlyRename &&\n !plan.destExistedOriginally &&\n (await destExists(ctx.fs, plan.validDest, op))\n ) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `${VERB[op]} cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n if (op === 'move') {\n await performRenameWithFallback(plan.opSource, plan.validDest, ctx.fs, plan.pair.source);\n ctx.log?.('info', `move: ${plan.pair.source} -> ${plan.pair.destination}`, 'move');\n } else {\n await ctx.fs.cp(plan.opSource, plan.validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n force: true,\n });\n }\n return { value: { from: plan.opSource, to: plan.validDest } };\n}\n\ntype TransferPlanResult =\n | { status: 'fail'; failure: MoveFailureItem }\n | { status: 'noop' }\n | { status: 'plan'; plan: TransferPlan };\n\n/** A discriminated union, so the fold below narrows without a generic cast. */\ntype TransferExecResult = { readonly skipped: string } | { readonly value: MoveItemResult };\n\nfunction pairFailure(\n pair: { source: string; destination: string },\n error: unknown,\n): MoveFailureItem {\n return {\n source: pair.source,\n destination: pair.destination,\n error: Problem.fromUnknown(error, ErrorCode.UNKNOWN, pair.source),\n };\n}\n\n/**\n * The source→destination sibling of `runOverPaths`: plan every pair, fail closed\n * on a duplicated destination, round-trip the overwrite confirmations as one\n * set, then execute what survived in parallel. `copy` and `move` differ only in\n * their `plan` and `execute` callbacks.\n */\nasync function runTransfers(\n items: readonly z.infer<typeof MoveItemSchema>[],\n ctx: ToolCtx,\n op: PairOp,\n overwrite: boolean,\n): Promise<\n | { results: MoveItemResult[]; skipped: string[]; failures: MoveFailureItem[] }\n | InputRequiredResult\n> {\n const { results: planned, errors: planErrors } = await processInParallel(\n items,\n (pair) => planTransfer(op, pair, ctx.fs, overwrite),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n // plan callbacks are fail-closed (they return { status: 'fail' }, never\n // throw), so planErrors should always be empty. Surface the first rather\n // than silently dropping the item if a future plan callback violates that.\n const firstPlanError = planErrors[0];\n if (firstPlanError) throw firstPlanError.error;\n\n const failures: MoveFailureItem[] = [];\n const candidates: TransferPlan[] = [];\n for (const { value } of planned) {\n if (value.status === 'fail') failures.push(value.failure);\n else if (value.status === 'plan') candidates.push(value.plan);\n // 'noop' (self-copy / self-move) is silently skipped.\n }\n\n // Two sources targeting the same destination in one batch would otherwise\n // collapse to a single shared overwrite confirmation and let the second\n // one silently clobber the first's freshly-written content. Fail closed:\n // only the first plan per destination proceeds; later ones targeting the\n // same destination are reported as a per-item failure.\n const seenDest = new Set<string>();\n const ready: TransferPlan[] = [];\n for (const candidate of candidates) {\n const destKey = normalizeCaseForComparison(candidate.validDest);\n if (seenDest.has(destKey)) {\n failures.push(\n pairFailure(\n candidate.pair,\n new FsError(\n ErrorCode.INVALID_INPUT,\n `${VERB[op]} cancelled: another entry in this batch already targets destination \"${candidate.pair.destination}\"`,\n candidate.pair.destination,\n ),\n ),\n );\n continue;\n }\n seenDest.add(destKey);\n ready.push(candidate);\n }\n\n const pendingSorted = ready\n .filter((p) => p.pending)\n .map((p) => p.validDest)\n .sort();\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required; a retry whose verified state does not\n // bind this overwrite set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip({\n op,\n pending: pendingSorted,\n requestState: ctx.requestState,\n clientCapabilities: ctx.clientCapabilities,\n serverCtx: ctx.serverCtx,\n buildInputs: (dests) =>\n dests.map((dest, i) => ({\n key: confirmKey(i),\n message:\n op === 'move'\n ? `\"${dest}\" already exists. Overwrite it?`\n : `Destination \"${dest}\" already exists. Overwrite it?`,\n choices: ['overwrite', 'skip'],\n })),\n });\n if (round !== undefined) return round;\n }\n\n const total = ready.length;\n let completed = 0;\n const tick = (): void => {\n completed += 1;\n ctx.onProgress?.({ current: completed, total });\n };\n const { results: execResults, errors: execErrors } = await processInParallel(\n ready,\n async (readyPlan) => {\n try {\n return await executeTransfer(op, readyPlan, ctx, pendingSorted);\n } finally {\n tick();\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n for (const { error, index } of execErrors) {\n rethrowIfAborted(error);\n const failed = ready[index];\n if (failed) failures.push(pairFailure(failed.pair, error));\n }\n\n const results: MoveItemResult[] = [];\n const skipped: string[] = [];\n for (const { value } of execResults) {\n if ('skipped' in value) skipped.push(value.skipped);\n else results.push(value.value);\n }\n\n return { results, skipped, failures };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[],\n): string {\n const failCount = failures.length;\n // Name each pair. \"move: 2 items\" left the caller to open structuredContent\n // to learn which two, and a partial failure was unreadable without it.\n // Skipped destinations are an outcome the user chose, not a failure — name\n // them, or an all-skipped call reads as \"copy: nothing\".\n const tokens = [\n ...results.map((r) => `${pathLabel(r.from)} → ${pathLabel(r.to)}`),\n ...skipped.map((dest) => `${pathLabel(dest)} SKIPPED`),\n ];\n const parts = [`${verb}: ${joinRoster(tokens) || 'nothing'}`];\n if (failCount > 0) parts.push(`${String(failCount)} failed`);\n return parts.join(' · ');\n}\n\ninterface TransferSource {\n /** Symlink resolved — the identity used for every same-target comparison. */\n realSource: string;\n /** The path the mutation runs on: symlink preserved for move, resolved for copy. */\n opSource: string;\n}\n\n/**\n * A move needs two views of its source. Renaming must operate on the link\n * itself, or moving a symlink would rename the file it points at and leave the\n * link dangling. Every collision check must instead compare the resolved\n * target, or a link moved onto itself (or onto its own target) reads as a real\n * move and renames the link over that target, destroying it. A copy reads\n * through the link, so both views are the resolved one.\n */\nasync function validateTransferSource(\n op: PairOp,\n source: string,\n fs: ToolCtx['fs'],\n): Promise<TransferSource> {\n try {\n const realSource = await fs.pathGuard.validateExistingPath(source);\n const opSource = op === 'move' ? await fs.pathGuard.validatePathForDelete(source) : realSource;\n return { realSource, opSource };\n } catch (error) {\n if (isFsError(error)) throw error;\n throw new FsError(ErrorCode.ACCESS_DENIED, `${VERB[op]} failed for ${source}`, source);\n }\n}\n\nexport async function performRenameWithFallback(\n validSource: string,\n validDest: string,\n fsOps: Pick<GuardedFileSystem, 'rename' | 'cp' | 'rm'>,\n originalSource: string,\n): Promise<void> {\n try {\n await fsOps.rename(validSource, validDest);\n } catch (error: unknown) {\n rethrowIfAborted(error);\n\n if (!isNodeError(error) || error.code !== 'EXDEV') {\n throw error;\n }\n\n // EXDEV: cross-device rename. Copy then remove, preserving symlinks and\n // timestamps so link semantics survive the move.\n let copied = false;\n try {\n await fsOps.cp(validSource, validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n });\n copied = true;\n await fsOps.rm(validSource, { recursive: true, force: true });\n } catch (copyOrRemoveError) {\n rethrowIfAborted(copyOrRemoveError);\n if (copied) {\n // cp succeeded but rm failed: the destination already holds a complete\n // copy and the source remains. Surface the rm error as the cause so the\n // caller can recover (clean up the duplicate) instead of a silent generic\n // failure that hides the partial completion.\n const baseProblem = Problem.fromUnknown(\n copyOrRemoveError,\n ErrorCode.UNKNOWN,\n originalSource,\n );\n throw new FsError(\n baseProblem.code,\n `Cross-device move of ${originalSource}: copy succeeded but source removal failed (destination holds a copy): ${baseProblem.message}`,\n originalSource,\n copyOrRemoveError,\n );\n }\n throw copyOrRemoveError;\n }\n }\n}\n\nexport const MOVE = defineTool({\n name: 'move',\n title: 'Move or Copy Files',\n description:\n 'Move, rename, or copy files and directories, like mv or cp -r. ' +\n 'Each destination is the full new path, not a folder to move into; missing parent directories are created.',\n input: MoveInputSchema,\n output: MoveOutputSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => {\n const label = args.copy ? 'Copy' : 'Move';\n if (args.moves.length === 1) {\n const move = args.moves[0];\n return {\n label,\n subject: `${basename(move?.source ?? '')} → ${basename(move?.destination ?? '')}`,\n };\n }\n return { label, subject: `${String(args.moves.length)} files` };\n },\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const op: PairOp = args.copy ? 'copy' : 'move';\n // `overwrite` is copy-only; move has no confirmation bypass.\n const outcome = await runTransfers(args.moves, ctx, op, args.copy && args.overwrite);\n // input_required is a return value, not a completed call: surface it\n // verbatim so the executor short-circuits before building a CallToolResult.\n if (isInputRequiredResult(outcome)) return outcome;\n const { results, skipped, failures } = outcome;\n return {\n structured: {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n },\n text: buildSummary(op, results, failures, skipped),\n // Every requested pair failed: no move, no copy, no user-chosen skip - the\n // call did nothing. A skip is work the caller asked for, so it counts.\n isError: failures.length > 0 && results.length + skipped.length === 0,\n };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"move.js","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAA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,qEAAqE;QACrE,4EAA4E;QAC5E,IAAI,qBAAqB,CAAC,OAAO,CAAC;YAAE,OAAO,OAAO,CAAC;QACnD,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;QAC/C,OAAO;YACL,UAAU,EAAE;gBACV,KAAK,EAAE,OAAO;gBACd,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC5C,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC3C;YACD,IAAI,EAAE,YAAY,CAAC,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC;YAClD,2EAA2E;YAC3E,uEAAuE;YACvE,OAAO,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,CAAC;SACtE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { stat } from 'node:fs/promises';\nimport { basename, dirname, relative, resolve } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.ts';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.ts';\nimport { joinRoster, pathLabel } from '../core/fmt.ts';\nimport { destExists } from '../core/fs.ts';\nimport type { GuardedFileSystem } from '../core/fs.ts';\nimport { globEntries } from '../core/glob.ts';\nimport {\n confirmKey,\n describeRefusal,\n pendingRoundTrip,\n readAcceptedChoice,\n} from '../core/input-required.ts';\nimport {\n isPathInsideDirectory,\n isSamePath,\n normalizeCaseForComparison,\n respellCaseOnlyTarget,\n} from '../core/path-utils.ts';\nimport { defaultFalseBoolean, RequiredPath } from '../core/schema.ts';\nimport { PARALLEL_CONCURRENCY } from '../core/util.ts';\nimport type { ToolCtx } from './define.ts';\nimport { defineTool } from './define.ts';\n\nconst MoveItemSchema = z.strictObject({\n source: RequiredPath.describe('Path of the file or directory to move or copy'),\n destination: RequiredPath.describe('Destination path'),\n});\n\ninterface MoveItemResult {\n from: string;\n to: string;\n}\n\nconst MoveInputSchema = z.strictObject({\n moves: z.array(MoveItemSchema).min(1).max(100).describe('Operations to perform (max 100)'),\n copy: defaultFalseBoolean('Copy instead of move; sources are left in place'),\n overwrite: defaultFalseBoolean(\n 'Copy mode only: overwrite existing destinations without confirmation',\n ),\n});\n\ninterface MoveFailureItem {\n source: string;\n destination: string;\n error: Problem;\n}\n\ninterface MoveOutput {\n moves: MoveItemResult[];\n failures?: MoveFailureItem[];\n skipped?: string[];\n}\n\ntype PairOp = 'move' | 'copy';\n\nconst VERB: Readonly<Record<PairOp, string>> = { move: 'Move', copy: 'Copy' };\n\n/** A move or copy pre-checked up to the point a confirmation decision is needed. */\ninterface TransferPlan {\n pair: { source: string; destination: string };\n /**\n * The path the mutation runs on: the link itself for a move, the resolved\n * target for a copy. Every collision check uses the resolved source instead\n * — see {@link validateTransferSource}.\n */\n opSource: string;\n validDest: string;\n /**\n * A rename that only changes the destination's case. Move must perform it —\n * it is real work — so it is exempt from the destination-exists checks that\n * would otherwise read the source itself as an existing destination. Never\n * true for a copy, which treats a case-only target as a self-copy and skips.\n */\n isCaseOnlyRename: boolean;\n /** Whether the destination existed when planned (drives the TOCTOU guard). */\n destExistedOriginally: boolean;\n /** Destination exists and is not a self/case-only target → needs overwrite confirmation. */\n pending: boolean;\n}\n\n/**\n * Phase 1 (no mutation): validate source and destination, reject self-targets\n * and transfers into a subdirectory of the source, and stat the destination to\n * decide whether this pair needs an overwrite confirmation. No `mkdir` happens\n * here — the old flow created the destination's parent before asking, which\n * mutated the filesystem before a confirmation; that now waits for phase 2 (R14).\n *\n * `overwrite` is copy-only — move has no confirmation bypass — so a move always\n * passes false.\n */\nasync function planTransfer(\n op: PairOp,\n pair: { source: string; destination: string },\n fs: ToolCtx['fs'],\n overwrite: boolean,\n signal: AbortSignal | undefined,\n): Promise<TransferPlanResult> {\n let realSource: string;\n let opSource: string;\n let validDest: string;\n try {\n ({ realSource, opSource } = await validateTransferSource(op, pair.source, fs));\n validDest = await fs.pathGuard.validatePathForWrite(pair.destination);\n if (!(op === 'move' && opSource !== realSource) && (await stat(realSource)).isDirectory()) {\n await assertTreeHasNoProtectedEntries(op, realSource, pair.source, validDest, fs, signal);\n }\n } catch (error) {\n return { status: 'fail', failure: pairFailure(pair, error) };\n }\n\n // Comparisons run on the resolved source; only the fs call in phase 2 uses\n // opSource. validatePathForWrite resolves the destination through a symlink\n // too, so both sides of every check must be resolved to match.\n const resolvedSource = resolve(realSource);\n let resolvedDest = resolve(validDest);\n\n // validatePathForWrite realpaths an existing destination to its on-disk\n // spelling, so a case-only rename resolves to the source itself; re-spell\n // it with the requested basename before deciding self vs. rename.\n if (resolvedSource === resolvedDest) {\n validDest = respellCaseOnlyTarget(pair.destination, validDest);\n resolvedDest = resolve(validDest);\n }\n\n const isSelf = resolvedSource === resolvedDest;\n const isCaseOnlyRename = !isSelf && isSamePath(resolvedSource, resolvedDest);\n\n // A copy onto a case-only variant of its own source is the same file, so it\n // is a no-op; the same rename is real work for move and proceeds.\n if (isSelf || (isCaseOnlyRename && op === 'copy')) {\n return { status: 'noop' };\n }\n\n if (!isCaseOnlyRename && isPathInsideDirectory(resolvedSource, resolvedDest)) {\n return {\n status: 'fail',\n failure: pairFailure(\n pair,\n new FsError(\n ErrorCode.INVALID_INPUT,\n `Cannot ${op} a directory into its own subdirectory`,\n pair.source,\n ),\n ),\n };\n }\n\n const destExistedOriginally = !isCaseOnlyRename && (await destExists(fs, validDest, op));\n const pending = destExistedOriginally && !overwrite;\n\n return {\n status: 'plan',\n plan: { pair, opSource, validDest, isCaseOnlyRename, destExistedOriginally, pending },\n };\n}\n\n/**\n * Phase 2 (mutation): confirm an overwrite if needed, TOCTOU-check the\n * destination, create its parent, then rename (with cross-device fallback) or\n * copy. A declined/missing confirmation throws `CANCELLED`, collected as a\n * per-pair failure by the caller. A destination that appeared between plan and\n * mutation (created during the confirmation gap) also fails closed.\n */\nasync function executeTransfer(\n op: PairOp,\n plan: TransferPlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses' | 'droppedInputResponseKeys' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<TransferExecResult> {\n if (plan.pending) {\n const key = confirmKey(pendingSorted.indexOf(plan.validDest));\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `${VERB[op]} cancelled: overwrite of \"${plan.pair.destination}\" was ${describeRefusal(ctx, key)}`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if (\n !plan.isCaseOnlyRename &&\n !plan.destExistedOriginally &&\n (await destExists(ctx.fs, plan.validDest, op))\n ) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `${VERB[op]} cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n if (op === 'move') {\n await performRenameWithFallback(plan.opSource, plan.validDest, ctx.fs, plan.pair.source);\n ctx.log('info', `move: ${plan.pair.source} -> ${plan.pair.destination}`, 'move');\n } else {\n await ctx.fs.cp(plan.opSource, plan.validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n force: true,\n });\n }\n return { value: { from: plan.opSource, to: plan.validDest } };\n}\n\ntype TransferPlanResult =\n | { status: 'fail'; failure: MoveFailureItem }\n | { status: 'noop' }\n | { status: 'plan'; plan: TransferPlan };\n\n/** A discriminated union, so the fold below narrows without a generic cast. */\ntype TransferExecResult = { readonly skipped: string } | { readonly value: MoveItemResult };\n\nfunction pairFailure(\n pair: { source: string; destination: string },\n error: unknown,\n): MoveFailureItem {\n return {\n source: pair.source,\n destination: pair.destination,\n error: Problem.fromUnknown(error, ErrorCode.UNKNOWN, pair.source),\n };\n}\n\n/**\n * The source→destination sibling of `runOverPaths`: plan every pair, fail closed\n * on a duplicated destination, round-trip the overwrite confirmations as one\n * set, then execute what survived in parallel. `copy` and `move` differ only in\n * their `plan` and `execute` callbacks.\n */\nasync function runTransfers(\n items: readonly z.infer<typeof MoveItemSchema>[],\n ctx: ToolCtx,\n op: PairOp,\n overwrite: boolean,\n): Promise<\n | { results: MoveItemResult[]; skipped: string[]; failures: MoveFailureItem[] }\n | InputRequiredResult\n> {\n const { results: planned, errors: planErrors } = await processInParallel(\n items,\n (pair) => planTransfer(op, pair, ctx.fs, overwrite, ctx.signal),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n // plan callbacks are fail-closed (they return { status: 'fail' }, never\n // throw), so planErrors should always be empty. Surface the first rather\n // than silently dropping the item if a future plan callback violates that.\n const firstPlanError = planErrors[0];\n if (firstPlanError) throw firstPlanError.error;\n\n const failures: MoveFailureItem[] = [];\n const candidates: TransferPlan[] = [];\n for (const { value } of planned) {\n if (value.status === 'fail') failures.push(value.failure);\n else if (value.status === 'plan') candidates.push(value.plan);\n // 'noop' (self-copy / self-move) is silently skipped.\n }\n\n // Two sources targeting the same destination in one batch would otherwise\n // collapse to a single shared overwrite confirmation and let the second\n // one silently clobber the first's freshly-written content. Fail closed:\n // only the first plan per destination proceeds; later ones targeting the\n // same destination are reported as a per-item failure.\n const seenDest = new Set<string>();\n const ready: TransferPlan[] = [];\n for (const candidate of candidates) {\n const destKey = normalizeCaseForComparison(candidate.validDest);\n if (seenDest.has(destKey)) {\n failures.push(\n pairFailure(\n candidate.pair,\n new FsError(\n ErrorCode.INVALID_INPUT,\n `${VERB[op]} cancelled: another entry in this batch already targets destination \"${candidate.pair.destination}\"`,\n candidate.pair.destination,\n ),\n ),\n );\n continue;\n }\n seenDest.add(destKey);\n ready.push(candidate);\n }\n\n const pendingSorted = ready\n .filter((p) => p.pending)\n .map((p) => p.validDest)\n .sort();\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required; a retry whose verified state does not\n // bind this overwrite set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip(ctx, {\n op,\n pending: pendingSorted,\n buildInputs: (dests) =>\n dests.map((dest, i) => ({\n key: confirmKey(i),\n message:\n op === 'move'\n ? `\"${dest}\" already exists. Overwrite it?`\n : `Destination \"${dest}\" already exists. Overwrite it?`,\n choices: ['overwrite', 'skip'],\n })),\n });\n if (round !== undefined) return round;\n }\n\n const total = ready.length;\n let completed = 0;\n const tick = (): void => {\n completed += 1;\n ctx.onProgress({ current: completed, total });\n };\n const { results: execResults, errors: execErrors } = await processInParallel(\n ready,\n async (readyPlan) => {\n try {\n return await executeTransfer(op, readyPlan, ctx, pendingSorted);\n } finally {\n tick();\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n for (const { error, index } of execErrors) {\n rethrowIfAborted(error);\n const failed = ready[index];\n if (failed) failures.push(pairFailure(failed.pair, error));\n }\n\n const results: MoveItemResult[] = [];\n const skipped: string[] = [];\n for (const { value } of execResults) {\n if ('skipped' in value) skipped.push(value.skipped);\n else results.push(value.value);\n }\n\n return { results, skipped, failures };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[],\n): string {\n const failCount = failures.length;\n // Name each pair. \"move: 2 items\" left the caller to open structuredContent\n // to learn which two, and a partial failure was unreadable without it.\n // Skipped destinations are an outcome the user chose, not a failure — name\n // them, or an all-skipped call reads as \"copy: nothing\".\n const tokens = [\n ...results.map((r) => `${pathLabel(r.from)} → ${pathLabel(r.to)}`),\n ...skipped.map((dest) => `${pathLabel(dest)} SKIPPED`),\n ];\n const parts = [`${verb}: ${joinRoster(tokens) || 'nothing'}`];\n if (failCount > 0) parts.push(`${String(failCount)} failed`);\n return parts.join(' · ');\n}\n\ninterface TransferSource {\n /** Symlink resolved — the identity used for every same-target comparison. */\n realSource: string;\n /** The path the mutation runs on: symlink preserved for move, resolved for copy. */\n opSource: string;\n}\n\n/**\n * A move needs two views of its source. Renaming must operate on the link\n * itself, or moving a symlink would rename the file it points at and leave the\n * link dangling. Every collision check must instead compare the resolved\n * target, or a link moved onto itself (or onto its own target) reads as a real\n * move and renames the link over that target, destroying it. A copy reads\n * through the link, so both views are the resolved one.\n */\nasync function validateTransferSource(\n op: PairOp,\n source: string,\n fs: ToolCtx['fs'],\n): Promise<TransferSource> {\n try {\n const realSource = await fs.pathGuard.validateExistingPath(source);\n const opSource = op === 'move' ? await fs.pathGuard.validatePathForDelete(source) : realSource;\n return { realSource, opSource };\n } catch (error) {\n if (isFsError(error)) throw error;\n throw new FsError(ErrorCode.ACCESS_DENIED, `${VERB[op]} failed for ${source}`, source);\n }\n}\n\n/**\n * A directory transfer may proceed only when every entry keeps the same\n * sensitive-file status before and after relocation. Path-based rules\n * (`secrets/**`, `.aws/credentials`) follow the path, not the file, so refuse\n * any entry that would leave or enter the protected set. Walk the tree once\n * before any mutation and fail the pair closed if anything changes status.\n * Name-based rules need no help — they match after the move too.\n */\nasync function assertTreeHasNoProtectedEntries(\n op: PairOp,\n realSource: string,\n requestedSource: string,\n validDest: string,\n fs: ToolCtx['fs'],\n signal: AbortSignal | undefined,\n): Promise<void> {\n let protectedCount = 0;\n const entries = globEntries({\n cwd: realSource,\n pattern: '**/*',\n includeHidden: true,\n skipIgnored: false,\n onlyFiles: false,\n ...(signal ? { signal } : {}),\n });\n try {\n for await (const entry of entries) {\n signal?.throwIfAborted();\n const entryRelativePath = relative(realSource, entry.path);\n const requestedSourcePath = resolve(requestedSource, entryRelativePath);\n const destinationPath = resolve(validDest, entryRelativePath);\n const protectedBefore =\n fs.pathGuard.isSensitive(entry.path) || fs.pathGuard.isSensitive(requestedSourcePath);\n const protectedAfter = fs.pathGuard.isSensitive(destinationPath);\n if (protectedBefore !== protectedAfter) {\n protectedCount++;\n break;\n }\n }\n } catch (error) {\n rethrowIfAborted(error);\n throw new FsError(\n ErrorCode.ACCESS_DENIED,\n `${VERB[op]} refused: the directory could not be fully inspected for protected entries`,\n requestedSource,\n error,\n );\n }\n if (protectedCount > 0) {\n throw new FsError(\n ErrorCode.ACCESS_DENIED,\n `${VERB[op]} refused: the directory contains protected entries matching the sensitive-file policy; move or copy individual files instead`,\n requestedSource,\n );\n }\n}\n\nexport async function performRenameWithFallback(\n validSource: string,\n validDest: string,\n fsOps: Pick<GuardedFileSystem, 'rename' | 'cp' | 'rm'>,\n originalSource: string,\n): Promise<void> {\n try {\n await fsOps.rename(validSource, validDest);\n } catch (error: unknown) {\n rethrowIfAborted(error);\n\n if (!isNodeError(error) || error.code !== 'EXDEV') {\n throw error;\n }\n\n // EXDEV: cross-device rename. Copy then remove, preserving symlinks and\n // timestamps so link semantics survive the move.\n let copied = false;\n try {\n await fsOps.cp(validSource, validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n });\n copied = true;\n await fsOps.rm(validSource, { recursive: true, force: true });\n } catch (copyOrRemoveError) {\n rethrowIfAborted(copyOrRemoveError);\n if (copied) {\n // cp succeeded but rm failed: the destination already holds a complete\n // copy and the source remains. Surface the rm error as the cause so the\n // caller can recover (clean up the duplicate) instead of a silent generic\n // failure that hides the partial completion.\n const baseProblem = Problem.fromUnknown(\n copyOrRemoveError,\n ErrorCode.UNKNOWN,\n originalSource,\n );\n throw new FsError(\n baseProblem.code,\n `Cross-device move of ${originalSource}: copy succeeded but source removal failed (destination holds a copy): ${baseProblem.message}`,\n originalSource,\n copyOrRemoveError,\n );\n }\n throw copyOrRemoveError;\n }\n }\n}\n\nexport const MOVE = defineTool<typeof MoveInputSchema, MoveOutput>({\n name: 'move',\n title: 'Move or Copy Files',\n description:\n 'Move, rename, or copy files and directories, like mv or cp -r. ' +\n 'Each destination is the full new path, not a folder to move into; missing parent directories are created.',\n input: MoveInputSchema,\n readOnlyHint: false,\n progress: (args) => {\n const label = args.copy ? 'Copy' : 'Move';\n if (args.moves.length === 1) {\n const move = args.moves[0];\n return {\n label,\n subject: `${basename(move?.source ?? '')} → ${basename(move?.destination ?? '')}`,\n };\n }\n return { label, subject: `${String(args.moves.length)} files` };\n },\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const op: PairOp = args.copy ? 'copy' : 'move';\n // `overwrite` is copy-only; move has no confirmation bypass.\n const outcome = await runTransfers(args.moves, ctx, op, args.copy && args.overwrite);\n // input_required is a return value, not a completed call: surface it\n // verbatim so the executor short-circuits before building a CallToolResult.\n if (isInputRequiredResult(outcome)) return outcome;\n const { results, skipped, failures } = outcome;\n return {\n structured: {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n },\n text: buildSummary(op, results, failures, skipped),\n // Every requested pair failed: no move, no copy, no user-chosen skip - the\n // call did nothing. A skip is work the caller asked for, so it counts.\n isError: failures.length > 0 && results.length + skipped.length === 0,\n };\n },\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patch.d.ts","sourceRoot":"","sources":["../../src/tools/patch.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"patch.d.ts","sourceRoot":"","sources":["../../src/tools/patch.ts"],"names":[],"mappings":"AA8CA,eAAO,MAAM,KAAK,mCAsHhB,CAAC"}
|
package/dist/tools/patch.js
CHANGED
|
@@ -4,7 +4,7 @@ import { applyPatch, parsePatch } from 'diff';
|
|
|
4
4
|
import { ErrorCode, FsError } from "../core/errors.js";
|
|
5
5
|
import { buildWrittenFileMeta } from "../core/file-uri.js";
|
|
6
6
|
import { countLines } from "../core/read.js";
|
|
7
|
-
import { defaultFalseBoolean,
|
|
7
|
+
import { defaultFalseBoolean, RequiredPath } from "../core/schema.js";
|
|
8
8
|
import { defineTool } from "./define.js";
|
|
9
9
|
const PatchInputSchema = z.strictObject({
|
|
10
10
|
path: RequiredPath.describe('File to apply the diff to'),
|
|
@@ -14,21 +14,6 @@ const PatchInputSchema = z.strictObject({
|
|
|
14
14
|
.describe('Single-file unified diff to apply (as produced by the diff tool or edit dry-run)'),
|
|
15
15
|
dryRun: defaultFalseBoolean('Preview the result without writing (default: false)'),
|
|
16
16
|
});
|
|
17
|
-
const PatchOutputSchema = z.strictObject({
|
|
18
|
-
path: z.string().describe('Resolved absolute path of the patched file'),
|
|
19
|
-
size: NonNegInt.describe('File size in bytes after patching'),
|
|
20
|
-
lineCount: NonNegInt.describe('Number of lines in the file after patching'),
|
|
21
|
-
mimeType: z.string().describe('Detected MIME type of the file'),
|
|
22
|
-
kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),
|
|
23
|
-
resourceUri: z
|
|
24
|
-
.string()
|
|
25
|
-
.optional()
|
|
26
|
-
.describe('Resource URI pointing to the patched file content; omitted on dryRun or when the resulting file exceeds the text-size cap, which the store would reject'),
|
|
27
|
-
modified: IsoDateTime.describe('Last modification timestamp after patching (ISO 8601 UTC)'),
|
|
28
|
-
linesAdded: NonNegInt.describe('Number of lines added by the patch'),
|
|
29
|
-
linesRemoved: NonNegInt.describe('Number of lines removed by the patch'),
|
|
30
|
-
diff: z.string().optional().describe('Unified diff preview (present only in dryRun mode)'),
|
|
31
|
-
});
|
|
32
17
|
// Hunk lines are the raw unified lines with their +/-/ leading prefix (no
|
|
33
18
|
// +++/--- file headers inside hunks), so the first char is a reliable marker.
|
|
34
19
|
function countAddedRemoved(parsedPatch) {
|
|
@@ -51,12 +36,7 @@ export const PATCH = defineTool({
|
|
|
51
36
|
'Nothing is written unless every hunk applies in file order with exactly matching context; ' +
|
|
52
37
|
'hunks are found by their context, so start line numbers may be off.',
|
|
53
38
|
input: PatchInputSchema,
|
|
54
|
-
|
|
55
|
-
annotations: {
|
|
56
|
-
readOnlyHint: false,
|
|
57
|
-
destructiveHint: true,
|
|
58
|
-
openWorldHint: false,
|
|
59
|
-
},
|
|
39
|
+
readOnlyHint: false,
|
|
60
40
|
progress: (args) => ({
|
|
61
41
|
label: args.dryRun ? 'Patch [dry run]' : 'Patch',
|
|
62
42
|
subject: basename(args.path),
|
|
@@ -115,7 +95,7 @@ export const PATCH = defineTool({
|
|
|
115
95
|
const summaryText = `patch: ${basename(args.path)} +${String(linesAdded)} -${String(linesRemoved)}`;
|
|
116
96
|
if (!args.dryRun) {
|
|
117
97
|
await ctx.fs.writeFile(args.path, patched, { signal: ctx.signal });
|
|
118
|
-
ctx.log
|
|
98
|
+
ctx.log('info', `patch: ${args.path} (+${linesAdded}/-${linesRemoved})`, 'patch');
|
|
119
99
|
}
|
|
120
100
|
// `modified` is read from a post-write stat and is advisory: under a concurrent
|
|
121
101
|
// writer it may reflect that writer's mtime while `size`/content come from this
|
|
@@ -126,8 +106,8 @@ export const PATCH = defineTool({
|
|
|
126
106
|
const meta = buildWrittenFileMeta({
|
|
127
107
|
validPath,
|
|
128
108
|
content: patched,
|
|
129
|
-
resourceStore: ctx.resourceStore,
|
|
130
109
|
dryRun: args.dryRun,
|
|
110
|
+
lastModified: fileStats.mtime.toISOString(),
|
|
131
111
|
});
|
|
132
112
|
return {
|
|
133
113
|
structured: {
|
package/dist/tools/patch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patch.js","sourceRoot":"","sources":["../../src/tools/patch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,oBAAoB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AW;YACzC,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/E,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\nimport { applyPatch, parsePatch } from 'diff';\n\nimport { ErrorCode, FsError } from '../core/errors.ts';\nimport { buildWrittenFileMeta } from '../core/file-uri.ts';\nimport { countLines } from '../core/read.ts';\nimport {\n defaultFalseBoolean,\n FileKind,\n IsoDateTime,\n NonNegInt,\n RequiredPath,\n} from '../core/schema.ts';\nimport { defineTool } from './define.ts';\n\nconst PatchInputSchema = z.strictObject({\n path: RequiredPath.describe('File to apply the diff to'),\n diff: z\n .string()\n .min(1)\n .describe('Single-file unified diff to apply (as produced by the diff tool or edit dry-run)'),\n dryRun: defaultFalseBoolean('Preview the result without writing (default: false)'),\n});\n\nconst PatchOutputSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the patched file'),\n size: NonNegInt.describe('File size in bytes after patching'),\n lineCount: NonNegInt.describe('Number of lines in the file after patching'),\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 patched file content; omitted on dryRun or when the resulting file exceeds the text-size cap, which the store would reject',\n ),\n modified: IsoDateTime.describe('Last modification timestamp after patching (ISO 8601 UTC)'),\n linesAdded: NonNegInt.describe('Number of lines added by the patch'),\n linesRemoved: NonNegInt.describe('Number of lines removed by the patch'),\n diff: z.string().optional().describe('Unified diff preview (present only in dryRun mode)'),\n});\n\n// Hunk lines are the raw unified lines with their +/-/ leading prefix (no\n// +++/--- file headers inside hunks), so the first char is a reliable marker.\nfunction countAddedRemoved(parsedPatch: ReturnType<typeof parsePatch>[number]): {\n linesAdded: number;\n linesRemoved: number;\n} {\n let linesAdded = 0;\n let linesRemoved = 0;\n for (const hunk of parsedPatch.hunks) {\n for (const line of hunk.lines) {\n if (line.startsWith('+')) linesAdded += 1;\n else if (line.startsWith('-')) linesRemoved += 1;\n }\n }\n return { linesAdded, linesRemoved };\n}\n\nexport const PATCH = defineTool({\n name: 'patch',\n title: 'Patch',\n description:\n 'Apply a single-file unified diff to one existing text file, like git apply. ' +\n 'Nothing is written unless every hunk applies in file order with exactly matching context; ' +\n 'hunks are found by their context, so start line numbers may be off.',\n input: PatchInputSchema,\n output: PatchOutputSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => ({\n label: args.dryRun ? 'Patch [dry run]' : 'Patch',\n subject: basename(args.path),\n }),\n accessPaths: (args) => [args.path],\n run: async (args, ctx) => {\n const { validPath, content, stats } = await ctx.fs.readEditableText(args.path, {\n signal: ctx.signal,\n tool: 'patch',\n });\n\n // patch is single-file only: a multi-file unified diff (parsePatch length > 1)\n // is rejected. Multi-file application needs per-file PathGuard-resolved loaders\n // and is deferred (out of scope).\n const parsed = parsePatch(args.diff);\n if (parsed.length !== 1) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `patch accepts a single-file unified diff; received ${parsed.length} file(s)`,\n args.path,\n );\n }\n const parsedPatch = parsed[0];\n if (!parsedPatch || parsedPatch.hunks.length === 0) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch accepts a single-file unified diff with at least one hunk; received an empty patch',\n args.path,\n );\n }\n // jsdiff tries each hunk at its header line before bounding the search by\n // the previous hunk, so a header pointing back into text an earlier hunk\n // already consumed applies there and emits that region twice. Start each\n // hunk no earlier than where the previous hunk's changes end; its trailing\n // context may still overlap, as jsdiff allows.\n let floor = 0;\n const hunks = parsedPatch.hunks.map((hunk) => {\n const oldStart = Math.max(hunk.oldStart, floor);\n let trailingContext = 0;\n for (const line of hunk.lines) {\n if (line === '' || line.startsWith(' ')) trailingContext++;\n else if (line.startsWith('+') || line.startsWith('-')) trailingContext = 0;\n }\n floor = oldStart + hunk.oldLines - trailingContext;\n return { ...hunk, oldStart };\n });\n // applyPatch returns false (strict) on hunk mismatch — not a falsy empty string,\n // so `=== false` distinguishes a no-op patch ('') from a failed one.\n const patched = applyPatch(content, { ...parsedPatch, hunks });\n if (patched === false) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch did not apply cleanly: hunk context does not match file content (hunks must be in file order)',\n args.path,\n );\n }\n\n const { linesAdded, linesRemoved } = countAddedRemoved(parsedPatch);\n // Backstop for placements the clamp cannot see, such as zero-context hunks\n // whose headers point past the end of the file: refuse rather than write.\n if (countLines(patched) !== countLines(content) + linesAdded - linesRemoved) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch would duplicate or drop lines: a hunk overlaps an earlier one or starts past the end of the file',\n args.path,\n );\n }\n // The patched file used to come back whole in the text block, so a one-line\n // hunk against a 5000-line file returned 5000 lines. Every other write tool\n // answers with a summary; the result is reachable via `resourceUri` or a\n // follow-up `read` when the caller actually wants the bytes.\n const summaryText = `patch: ${basename(args.path)} +${String(linesAdded)} -${String(linesRemoved)}`;\n\n if (!args.dryRun) {\n await ctx.fs.writeFile(args.path, patched, { signal: ctx.signal });\n ctx.log?.('info', `patch: ${args.path} (+${linesAdded}/-${linesRemoved})`, 'patch');\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 come from this\n // patch's atomic write. The file content itself is always consistent.\n const fileStats = args.dryRun\n ? stats\n : (await ctx.fs.stat(args.path, { signal: ctx.signal })).stats;\n const meta = buildWrittenFileMeta({\n validPath,\n content: patched,\n resourceStore: ctx.resourceStore,\n dryRun: args.dryRun,\n });\n return {\n structured: {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n modified: fileStats.mtime.toISOString(),\n linesAdded,\n linesRemoved,\n ...(meta.resourceUri !== undefined ? { resourceUri: meta.resourceUri } : {}),\n ...(args.dryRun ? { diff: args.diff } : {}),\n },\n // A dry run exists to be previewed, so it keeps returning the patched\n // text; only the write path summarizes, where the bytes are on disk.\n text: args.dryRun ? patched : summaryText,\n ...(meta.resourceLink !== undefined ? { resources: [meta.resourceLink] } : {}),\n };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"patch.js","sourceRoot":"","sources":["../../src/tools/patch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAwB,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,gBAAgB,GAAG,CAAC,CAAC,YAAY,CAAC;IACtC,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,2BAA2B,CAAC;IACxD,IAAI,EAAE,CAAC;SACJ,MAAM,EAAE;SACR,GAAG,CAAC,CAAC,CAAC;SACN,QAAQ,CAAC,kFAAkF,CAAC;IAC/F,MAAM,EAAE,mBAAmB,CAAC,qDAAqD,CAAC;CACnF,CAAC,CAAC;AAWH,0EAA0E;AAC1E,8EAA8E;AAC9E,SAAS,iBAAiB,CAAC,WAAkD;IAI3E,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QACrC,KAAK,MAAM,IAAI,IAAI,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AAE,CAAC,CAAC,CAAC,KAAK,CAAC;QACjE,MAAM,IAAI,GAAG,oBAAoB,CAAC;YAChC,SAAS;YACT,OAAO,EAAE,OAAO;YAChB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,YAAY,EAAE,SAAS,CAAC,KAAK,CAAC,WAAW,EAAE;SAC5C,CAAC,CAAC;QACH,OAAO;YACL,UAAU,EAAE;gBACV,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,SAAS,EAAE,IAAI,CAAC,SAAS;gBACzB,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,QAAQ,EAAE,SAAS,CAAC,KAAK,CAAC,WAAW,EAAE;gBACvC,UAAU;gBACV,YAAY;gBACZ,GAAG,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC5E,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC5C;YACD,sEAAsE;YACtE,qEAAqE;YACrE,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW;YACzC,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/E,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\nimport { applyPatch, parsePatch } from 'diff';\n\nimport { ErrorCode, FsError } from '../core/errors.ts';\nimport { buildWrittenFileMeta, type WrittenFileMeta } from '../core/file-uri.ts';\nimport { countLines } from '../core/read.ts';\nimport { defaultFalseBoolean, RequiredPath } from '../core/schema.ts';\nimport { defineTool } from './define.ts';\n\nconst PatchInputSchema = z.strictObject({\n path: RequiredPath.describe('File to apply the diff to'),\n diff: z\n .string()\n .min(1)\n .describe('Single-file unified diff to apply (as produced by the diff tool or edit dry-run)'),\n dryRun: defaultFalseBoolean('Preview the result without writing (default: false)'),\n});\n\ntype PatchOutput = Omit<WrittenFileMeta, 'resourceUri' | 'resourceLink'> & {\n path: string;\n resourceUri?: string;\n modified: string;\n linesAdded: number;\n linesRemoved: number;\n diff?: string;\n};\n\n// Hunk lines are the raw unified lines with their +/-/ leading prefix (no\n// +++/--- file headers inside hunks), so the first char is a reliable marker.\nfunction countAddedRemoved(parsedPatch: ReturnType<typeof parsePatch>[number]): {\n linesAdded: number;\n linesRemoved: number;\n} {\n let linesAdded = 0;\n let linesRemoved = 0;\n for (const hunk of parsedPatch.hunks) {\n for (const line of hunk.lines) {\n if (line.startsWith('+')) linesAdded += 1;\n else if (line.startsWith('-')) linesRemoved += 1;\n }\n }\n return { linesAdded, linesRemoved };\n}\n\nexport const PATCH = defineTool<typeof PatchInputSchema, PatchOutput>({\n name: 'patch',\n title: 'Patch',\n description:\n 'Apply a single-file unified diff to one existing text file, like git apply. ' +\n 'Nothing is written unless every hunk applies in file order with exactly matching context; ' +\n 'hunks are found by their context, so start line numbers may be off.',\n input: PatchInputSchema,\n readOnlyHint: false,\n progress: (args) => ({\n label: args.dryRun ? 'Patch [dry run]' : 'Patch',\n subject: basename(args.path),\n }),\n accessPaths: (args) => [args.path],\n run: async (args, ctx) => {\n const { validPath, content, stats } = await ctx.fs.readEditableText(args.path, {\n signal: ctx.signal,\n tool: 'patch',\n });\n\n // patch is single-file only: a multi-file unified diff (parsePatch length > 1)\n // is rejected. Multi-file application needs per-file PathGuard-resolved loaders\n // and is deferred (out of scope).\n const parsed = parsePatch(args.diff);\n if (parsed.length !== 1) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `patch accepts a single-file unified diff; received ${parsed.length} file(s)`,\n args.path,\n );\n }\n const parsedPatch = parsed[0];\n if (!parsedPatch || parsedPatch.hunks.length === 0) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch accepts a single-file unified diff with at least one hunk; received an empty patch',\n args.path,\n );\n }\n // jsdiff tries each hunk at its header line before bounding the search by\n // the previous hunk, so a header pointing back into text an earlier hunk\n // already consumed applies there and emits that region twice. Start each\n // hunk no earlier than where the previous hunk's changes end; its trailing\n // context may still overlap, as jsdiff allows.\n let floor = 0;\n const hunks = parsedPatch.hunks.map((hunk) => {\n const oldStart = Math.max(hunk.oldStart, floor);\n let trailingContext = 0;\n for (const line of hunk.lines) {\n if (line === '' || line.startsWith(' ')) trailingContext++;\n else if (line.startsWith('+') || line.startsWith('-')) trailingContext = 0;\n }\n floor = oldStart + hunk.oldLines - trailingContext;\n return { ...hunk, oldStart };\n });\n // applyPatch returns false (strict) on hunk mismatch — not a falsy empty string,\n // so `=== false` distinguishes a no-op patch ('') from a failed one.\n const patched = applyPatch(content, { ...parsedPatch, hunks });\n if (patched === false) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch did not apply cleanly: hunk context does not match file content (hunks must be in file order)',\n args.path,\n );\n }\n\n const { linesAdded, linesRemoved } = countAddedRemoved(parsedPatch);\n // Backstop for placements the clamp cannot see, such as zero-context hunks\n // whose headers point past the end of the file: refuse rather than write.\n if (countLines(patched) !== countLines(content) + linesAdded - linesRemoved) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n 'patch would duplicate or drop lines: a hunk overlaps an earlier one or starts past the end of the file',\n args.path,\n );\n }\n // The patched file used to come back whole in the text block, so a one-line\n // hunk against a 5000-line file returned 5000 lines. Every other write tool\n // answers with a summary; the result is reachable via `resourceUri` or a\n // follow-up `read` when the caller actually wants the bytes.\n const summaryText = `patch: ${basename(args.path)} +${String(linesAdded)} -${String(linesRemoved)}`;\n\n if (!args.dryRun) {\n await ctx.fs.writeFile(args.path, patched, { signal: ctx.signal });\n ctx.log('info', `patch: ${args.path} (+${linesAdded}/-${linesRemoved})`, 'patch');\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 come from this\n // patch's atomic write. The file content itself is always consistent.\n const fileStats = args.dryRun\n ? stats\n : (await ctx.fs.stat(args.path, { signal: ctx.signal })).stats;\n const meta = buildWrittenFileMeta({\n validPath,\n content: patched,\n dryRun: args.dryRun,\n lastModified: fileStats.mtime.toISOString(),\n });\n return {\n structured: {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n modified: fileStats.mtime.toISOString(),\n linesAdded,\n linesRemoved,\n ...(meta.resourceUri !== undefined ? { resourceUri: meta.resourceUri } : {}),\n ...(args.dryRun ? { diff: args.diff } : {}),\n },\n // A dry run exists to be previewed, so it keeps returning the patched\n // text; only the write path summarizes, where the bytes are on disk.\n text: args.dryRun ? patched : summaryText,\n ...(meta.resourceLink !== undefined ? { resources: [meta.resourceLink] } : {}),\n };\n },\n});\n"]}
|
package/dist/tools/progress.d.ts
CHANGED
|
@@ -9,8 +9,6 @@ interface ProgressSessionOptions {
|
|
|
9
9
|
label: string;
|
|
10
10
|
/** Absent when the client sent no `progressToken`; the session then only tracks state. */
|
|
11
11
|
sink?: ProgressSink;
|
|
12
|
-
/** Override the tick rate-limit window. Default: 50ms. */
|
|
13
|
-
rateLimitMs?: number;
|
|
14
12
|
}
|
|
15
13
|
/**
|
|
16
14
|
* One tool call's progress stream: a monotonic cursor, a tick rate limit, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"progress.d.ts","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,8BAA8B,CAAC;AAK7F,2FAA2F;AAC3F,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,MAAM,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED,UAAU,sBAAsB;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,0FAA0F;IAC1F,IAAI,CAAC,EAAE,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"progress.d.ts","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,8BAA8B,CAAC;AAK7F,2FAA2F;AAC3F,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,MAAM,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED,UAAU,sBAAsB;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,0FAA0F;IAC1F,IAAI,CAAC,EAAE,YAAY,CAAC;CACrB;AAKD;;;;;GAKG;AACH,qBAAa,eAAe;;gBAYd,IAAI,EAAE,sBAAsB;IAOxC,GAAG,CAAC,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IASvE,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAO/B,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAO5B,iFAAiF;IAC3E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAyD7B"}
|
package/dist/tools/progress.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { formatUnknownErrorMessage } from "../core/errors.js";
|
|
2
2
|
import { Logger } from "../core/observability.js";
|
|
3
|
-
|
|
3
|
+
/** Minimum gap between two tick frames on the wire. */
|
|
4
|
+
const RATE_LIMIT_MS = 50;
|
|
4
5
|
/**
|
|
5
6
|
* One tool call's progress stream: a monotonic cursor, a tick rate limit, and
|
|
6
7
|
* the wire guard the spec requires (`progress` strictly increases per token).
|
|
@@ -10,21 +11,18 @@ const DEFAULT_RATE_LIMIT_MS = 50;
|
|
|
10
11
|
export class ProgressSession {
|
|
11
12
|
#label;
|
|
12
13
|
#sink;
|
|
13
|
-
#rateLimitMs;
|
|
14
14
|
#startTime;
|
|
15
15
|
#pending = new Set();
|
|
16
16
|
#cursor = 0;
|
|
17
|
-
#lastSentMs
|
|
17
|
+
#lastSentMs;
|
|
18
18
|
#lastProgress = -1;
|
|
19
|
+
#started = false;
|
|
19
20
|
#done = false;
|
|
20
21
|
constructor(opts) {
|
|
21
22
|
this.#label = opts.label;
|
|
22
23
|
this.#sink = opts.sink;
|
|
23
|
-
this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;
|
|
24
24
|
this.#startTime = Date.now();
|
|
25
|
-
this.#lastSentMs = this.#startTime -
|
|
26
|
-
// Synthetic start tick: the wire sees 0 at session creation.
|
|
27
|
-
this.#emit('tick', 0, undefined, this.#label);
|
|
25
|
+
this.#lastSentMs = this.#startTime - RATE_LIMIT_MS;
|
|
28
26
|
}
|
|
29
27
|
set(input) {
|
|
30
28
|
if (this.#done)
|
|
@@ -32,18 +30,21 @@ export class ProgressSession {
|
|
|
32
30
|
// A repeated or backward tick would put a duplicate value on the wire — drop it.
|
|
33
31
|
if (input.current <= this.#cursor)
|
|
34
32
|
return;
|
|
33
|
+
this.#start();
|
|
35
34
|
this.#cursor = input.current;
|
|
36
35
|
this.#emit('tick', this.#cursor, input.total, input.message ?? this.#label);
|
|
37
36
|
}
|
|
38
37
|
complete(message) {
|
|
39
38
|
if (this.#done)
|
|
40
39
|
return;
|
|
40
|
+
this.#start();
|
|
41
41
|
this.#done = true;
|
|
42
42
|
this.#emit('complete', this.#cursor, undefined, message);
|
|
43
43
|
}
|
|
44
44
|
fail(message) {
|
|
45
45
|
if (this.#done)
|
|
46
46
|
return;
|
|
47
|
+
this.#start();
|
|
47
48
|
this.#done = true;
|
|
48
49
|
this.#emit('fail', this.#cursor, undefined, message ?? this.#label);
|
|
49
50
|
}
|
|
@@ -52,23 +53,30 @@ export class ProgressSession {
|
|
|
52
53
|
if (this.#pending.size > 0)
|
|
53
54
|
await Promise.allSettled([...this.#pending]);
|
|
54
55
|
}
|
|
56
|
+
#start() {
|
|
57
|
+
if (this.#started)
|
|
58
|
+
return;
|
|
59
|
+
this.#started = true;
|
|
60
|
+
// Input-only rounds must not restart the originating token's progress.
|
|
61
|
+
this.#emit('start', 0, undefined, this.#label);
|
|
62
|
+
}
|
|
55
63
|
#emit(kind, current, total, message) {
|
|
56
64
|
const now = Date.now();
|
|
57
65
|
if (kind === 'tick') {
|
|
58
|
-
// Widen the window after 5s of execution
|
|
59
|
-
|
|
60
|
-
const window = now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;
|
|
66
|
+
// Widen the window after 5s of execution.
|
|
67
|
+
const window = now - this.#startTime > 5000 ? 250 : RATE_LIMIT_MS;
|
|
61
68
|
if (now - this.#lastSentMs < window)
|
|
62
69
|
return;
|
|
63
70
|
}
|
|
64
|
-
|
|
71
|
+
if (kind !== 'start')
|
|
72
|
+
this.#lastSentMs = now;
|
|
65
73
|
if (!this.#sink)
|
|
66
74
|
return;
|
|
67
75
|
if (kind === 'complete') {
|
|
68
76
|
current = total ?? current;
|
|
69
77
|
total = current;
|
|
70
78
|
}
|
|
71
|
-
if (kind
|
|
79
|
+
if (kind === 'complete' || kind === 'fail') {
|
|
72
80
|
current = Math.max(current, this.#lastProgress + 1);
|
|
73
81
|
if (total !== undefined && total < current)
|
|
74
82
|
total = current;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"progress.js","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAEA,OAAO,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CAAC,KAAK,CAAC,EAAE,CAChF,CAAC;QACJ,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import type { Notification, ProgressNotificationParams } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.ts';\nimport { Logger } from '../core/observability.ts';\n\n/** Where progress frames go: the `notifications/progress` sink for one `progressToken`. */\nexport interface ProgressSink {\n toolName: string;\n token: string | number;\n notify: (n: Notification) => Promise<void>;\n}\n\ninterface ProgressSessionOptions {\n label: string;\n /** Absent when the client sent no `progressToken`; the session then only tracks state. */\n sink?: ProgressSink;\n}\n\n/** Minimum gap between two tick frames on the wire. */\nconst RATE_LIMIT_MS = 50;\n\n/**\n * One tool call's progress stream: a monotonic cursor, a tick rate limit, and\n * the wire guard the spec requires (`progress` strictly increases per token).\n * Terminal frames (`complete`, `fail`) always reach the wire — they carry the\n * outcome message — so they advance past the last value instead of dropping.\n */\nexport class ProgressSession {\n readonly #label: string;\n readonly #sink: ProgressSink | undefined;\n readonly #startTime: number;\n readonly #pending = new Set<Promise<void>>();\n\n #cursor = 0;\n #lastSentMs: number;\n #lastProgress = -1;\n #started = false;\n #done = false;\n\n constructor(opts: ProgressSessionOptions) {\n this.#label = opts.label;\n this.#sink = opts.sink;\n this.#startTime = Date.now();\n this.#lastSentMs = this.#startTime - RATE_LIMIT_MS;\n }\n\n set(input: { current: number; total?: number; message?: string }): void {\n if (this.#done) return;\n // A repeated or backward tick would put a duplicate value on the wire — drop it.\n if (input.current <= this.#cursor) return;\n this.#start();\n this.#cursor = input.current;\n this.#emit('tick', this.#cursor, input.total, input.message ?? this.#label);\n }\n\n complete(message: string): void {\n if (this.#done) return;\n this.#start();\n this.#done = true;\n this.#emit('complete', this.#cursor, undefined, message);\n }\n\n fail(message?: string): void {\n if (this.#done) return;\n this.#start();\n this.#done = true;\n this.#emit('fail', this.#cursor, undefined, message ?? this.#label);\n }\n\n /** Await every notification in flight; a failed send is logged, never thrown. */\n async flush(): Promise<void> {\n if (this.#pending.size > 0) await Promise.allSettled([...this.#pending]);\n }\n\n #start(): void {\n if (this.#started) return;\n this.#started = true;\n // Input-only rounds must not restart the originating token's progress.\n this.#emit('start', 0, undefined, this.#label);\n }\n\n #emit(\n kind: 'start' | 'tick' | 'complete' | 'fail',\n current: number,\n total: number | undefined,\n message: string,\n ): void {\n const now = Date.now();\n if (kind === 'tick') {\n // Widen the window after 5s of execution.\n const window = now - this.#startTime > 5000 ? 250 : RATE_LIMIT_MS;\n if (now - this.#lastSentMs < window) return;\n }\n if (kind !== 'start') this.#lastSentMs = now;\n if (!this.#sink) return;\n\n if (kind === 'complete') {\n current = total ?? current;\n total = current;\n }\n if (kind === 'complete' || kind === 'fail') {\n current = Math.max(current, this.#lastProgress + 1);\n if (total !== undefined && total < current) total = current;\n }\n // Spec: progress must increase on every notification for the same token.\n if (current <= this.#lastProgress) return;\n this.#lastProgress = current;\n\n const { toolName, token, notify } = this.#sink;\n const params: ProgressNotificationParams = {\n progressToken: token,\n progress: current,\n ...(total !== undefined ? { total } : {}),\n message,\n };\n const promise = notify({ method: 'notifications/progress', params })\n .catch((error: unknown) => {\n // A sink failure must never fail the tool call it is reporting on.\n Logger.warn(\n `${toolName}: progressNotification failed: ${formatUnknownErrorMessage(error)}`,\n );\n })\n .finally(() => {\n this.#pending.delete(promise);\n });\n this.#pending.add(promise);\n }\n}\n"]}
|
package/dist/tools/read.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAsUA,eAAO,MAAM,IAAI,mCAkHf,CAAC"}
|