@j0hanz/filesystem-mcp 2.1.7 → 2.1.8
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 +7 -7
- package/dist/cli.d.ts +1 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +29 -34
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts +4 -7
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +4 -12
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/cursor.d.ts.map +1 -1
- package/dist/core/cursor.js +8 -20
- package/dist/core/cursor.js.map +1 -1
- package/dist/core/fmt.d.ts +2 -1
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +8 -15
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/fs.d.ts +0 -14
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +1 -0
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +0 -3
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +5 -27
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +2 -2
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +4 -27
- package/dist/core/path-completer.js.map +1 -1
- package/dist/core/path-utils.d.ts +1 -1
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +2 -2
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +7 -9
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +24 -42
- package/dist/core/path.js.map +1 -1
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +6 -23
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +19 -74
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts +1 -7
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +6 -13
- package/dist/core/search.js.map +1 -1
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +6 -17
- package/dist/core/store.js.map +1 -1
- package/dist/index.js +15 -42
- package/dist/index.js.map +1 -1
- package/dist/prompts.d.ts.map +1 -1
- package/dist/prompts.js +17 -25
- package/dist/prompts.js.map +1 -1
- package/dist/resources.d.ts +4 -4
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +7 -17
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts +1 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -7
- package/dist/server.js.map +1 -1
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +35 -61
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete-file.d.ts.map +1 -1
- package/dist/tools/delete-file.js +30 -35
- package/dist/tools/delete-file.js.map +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +3 -7
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +2 -4
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/progress.d.ts +1 -1
- package/dist/tools/progress.d.ts.map +1 -1
- package/dist/tools/progress.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +36 -42
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-in-files.d.ts.map +1 -1
- package/dist/tools/replace-in-files.js +4 -18
- package/dist/tools/replace-in-files.js.map +1 -1
- package/dist/tools/search-content.d.ts.map +1 -1
- package/dist/tools/search-content.js +3 -25
- package/dist/tools/search-content.js.map +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +9 -37
- package/dist/tools/stat.js.map +1 -1
- package/dist/transport/http-policy.d.ts +18 -15
- package/dist/transport/http-policy.d.ts.map +1 -1
- package/dist/transport/http-policy.js +29 -39
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +29 -39
- package/dist/transport/http.js.map +1 -1
- package/package.json +4 -7
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,EAAE,WAAW,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC9F,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAClG,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,CAAC,QAAQ,CAAC,+CAA+C,CAAC;IAC9E,WAAW,EAAE,YAAY,CAAC,QAAQ,CAAC,kBAAkB,CAAC;CACvD,CAAC,CAAC;AAEH,MAAM,oBAAoB,GAAG,CAAC,CAAC,Y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MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IAClE,CAAC;IACD,gBAAgB,EAAE,SAAS,CAAC,OAAO;IACnC,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC;IAC3E,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QACvB,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC3C,qEAAqE;QACrE,4EAA4E;QAC5E,IAAI,qBAAqB,CAAC,MAAM,CAAC;YAAE,OAAO,MAAM,CAAC;QACjD,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QACrC,OAAO;YACL,UAAU,EAAE,MAAM;YAClB,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC;YAChF,2EAA2E;YAC3E,uEAAuE;YACvE,OAAO,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,CAAC;SAC3E,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.js';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport { destExists } from '../core/fs.js';\nimport type { GuardedFileSystem } from '../core/fs.js';\nimport { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';\nimport { IS_CASE_INSENSITIVE_FS, isPathInsideDirectory, isSamePath } from '../core/path-utils.js';\nimport { defaultFalseBoolean, PerFileErrorSchema, RequiredPath } from '../core/schema.js';\nimport { PARALLEL_CONCURRENCY } from '../core/util.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\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 const resolvedDest = resolve(validDest);\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 = `confirm_${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 declined or missing`,\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 = IS_CASE_INSENSITIVE_FS\n ? candidate.validDest.toLowerCase()\n : 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 buildInputs: (dests) =>\n dests.map((dest, i) =>\n choiceInput(\n `confirm_${i}`,\n op === 'move'\n ? `\"${dest}\" already exists. Overwrite it?`\n : `Destination \"${dest}\" already exists. Overwrite it?`,\n [\n { value: 'overwrite', title: 'Overwrite' },\n { value: 'skip', title: 'Skip' },\n ],\n ),\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\n/**\n * Two-phase move: pre-check every move (no mutation) to build the overwrite\n * pending set; if any move is pending and the round carries no verified\n * `requestState`, return `input_required` moving nothing (R14). On retry, R9\n * checks the state binds this move set, then each pending move proceeds only on\n * an accepted overwrite. Non-pending moves proceed alongside them.\n */\nasync function handleMove(\n args: z.infer<typeof MoveInputSchema>,\n ctx: ToolCtx,\n): Promise<z.infer<typeof MoveOutputSchema> | InputRequiredResult> {\n const op: PairOp = args.copy ? 'copy' : 'move';\n // `overwrite` is copy-only; move has no confirmation bypass.\n const overwrite = args.copy && args.overwrite;\n const outcome = await runTransfers(args.moves, ctx, op, overwrite);\n if (isInputRequiredResult(outcome)) return outcome;\n\n const { results, skipped, failures } = outcome;\n\n return {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[],\n): string {\n const successCount = results.length;\n const failCount = failures.length;\n if (failCount === 0 && skipped.length === 0 && successCount === 1) {\n const result = results[0];\n if (result) {\n return `${verb}: ${pathLabel(result.from)} → ${pathLabel(result.to)}`;\n }\n }\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\nasync 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 to explicit destination paths (max 100 operations per call). ' +\n 'Pass moves: [{ source, destination }] — there is no single-pair form. ' +\n 'Parent directories are created automatically. Set copy=true to copy instead of move (sources are kept). ' +\n 'An existing destination prompts the user to confirm the overwrite, so the call returns without moving ' +\n 'anything until that confirmation comes back; copy=true with overwrite=true skips the prompt, move has no ' +\n 'such bypass. Self-moves are silently skipped.',\n input: MoveInputSchema,\n output: MoveOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: 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 defaultErrorCode: ErrorCode.UNKNOWN,\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const output = await handleMove(args, ctx);\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(output)) return output;\n const failures = output.failures ?? [];\n const skipped = output.skipped ?? [];\n return {\n structured: output,\n text: buildSummary(args.copy ? 'copy' : 'move', output.moves, 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 && output.moves.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,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,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,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QACrC,OAAO;YACL,UAAU,EAAE,MAAM;YAClB,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC;YAChF,2EAA2E;YAC3E,uEAAuE;YACvE,OAAO,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,CAAC;SAC3E,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.js';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport { destExists } from '../core/fs.js';\nimport type { GuardedFileSystem } from '../core/fs.js';\nimport { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';\nimport {\n isPathInsideDirectory,\n isSamePath,\n normalizeCaseForComparison,\n} from '../core/path-utils.js';\nimport { defaultFalseBoolean, PerFileErrorSchema, RequiredPath } from '../core/schema.js';\nimport { PARALLEL_CONCURRENCY } from '../core/util.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\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 const resolvedDest = resolve(validDest);\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 = `confirm_${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 declined or missing`,\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 buildInputs: (dests) =>\n dests.map((dest, i) =>\n choiceInput(\n `confirm_${i}`,\n op === 'move'\n ? `\"${dest}\" already exists. Overwrite it?`\n : `Destination \"${dest}\" already exists. Overwrite it?`,\n [\n { value: 'overwrite', title: 'Overwrite' },\n { value: 'skip', title: 'Skip' },\n ],\n ),\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\n/**\n * Two-phase move: pre-check every move (no mutation) to build the overwrite\n * pending set; if any move is pending and the round carries no verified\n * `requestState`, return `input_required` moving nothing (R14). On retry, R9\n * checks the state binds this move set, then each pending move proceeds only on\n * an accepted overwrite. Non-pending moves proceed alongside them.\n */\nasync function handleMove(\n args: z.infer<typeof MoveInputSchema>,\n ctx: ToolCtx,\n): Promise<z.infer<typeof MoveOutputSchema> | InputRequiredResult> {\n const op: PairOp = args.copy ? 'copy' : 'move';\n // `overwrite` is copy-only; move has no confirmation bypass.\n const overwrite = args.copy && args.overwrite;\n const outcome = await runTransfers(args.moves, ctx, op, overwrite);\n if (isInputRequiredResult(outcome)) return outcome;\n\n const { results, skipped, failures } = outcome;\n\n return {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[],\n): string {\n const successCount = results.length;\n const failCount = failures.length;\n if (failCount === 0 && skipped.length === 0 && successCount === 1) {\n const result = results[0];\n if (result) {\n return `${verb}: ${pathLabel(result.from)} → ${pathLabel(result.to)}`;\n }\n }\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\nasync 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 to explicit destination paths (max 100 operations per call). ' +\n 'Pass moves: [{ source, destination }] — there is no single-pair form. ' +\n 'Parent directories are created automatically. Set copy=true to copy instead of move (sources are kept). ' +\n 'An existing destination prompts the user to confirm the overwrite, so the call returns without moving ' +\n 'anything until that confirmation comes back; copy=true with overwrite=true skips the prompt, move has no ' +\n 'such bypass. Self-moves are silently skipped.',\n input: MoveInputSchema,\n output: MoveOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: 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 defaultErrorCode: ErrorCode.UNKNOWN,\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const output = await handleMove(args, ctx);\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(output)) return output;\n const failures = output.failures ?? [];\n const skipped = output.skipped ?? [];\n return {\n structured: output,\n text: buildSummary(args.copy ? 'copy' : 'move', output.moves, 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 && output.moves.length + skipped.length === 0,\n };\n },\n});\n"]}
|
package/dist/tools/progress.d.ts
CHANGED
|
@@ -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;AAU7F,
|
|
1
|
+
{"version":3,"file":"progress.d.ts","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,8BAA8B,CAAC;AAU7F,KAAK,aAAa,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAClE;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACtE;IACE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,OAAO,CAAC;CAChB,CAAC;AAEN,UAAU,sBAAsB;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE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AG,OAAO;gBAAE,KAAK,GAAG,OAAO,CAAC;QAC9D,CAAC;QACD,yEAAyE;QACzE,IAAI,OAAO,IAAI,IAAI,CAAC,aAAa;YAAE,OAAO;QAC1C,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC;QAC7B,MAAM,kBAAkB,GAA+B;YACrD,aAAa,EAAE,IAAI,CAAC,KAAK;YACzB,QAAQ,EAAE,OAAO;YACjB,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACzC,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC;YAC1B,MAAM,EAAE,wBAAwB;YAChC,MAAM,EAAE,kBAAkB;SAC3B,CAAC;aACC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,mBAAmB,CAAC,IAAI,CAAC,QAAQ,EAAE,sBAAsB,EAAE,KAAK,CAAC,CAAC;QACpE,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;IAED,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YAC3B,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { Notification, ProgressNotificationParams } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport { Logger } from '../core/observability.js';\n\nfunction reportDetachedError(toolName: string, context: string, error: unknown): void {\n const message = formatUnknownErrorMessage(error);\n Logger.emit('warning', `${toolName}: ${context} failed: ${message}`);\n}\n\nexport type ProgressEvent =\n | { kind: 'tick'; current: number; total?: number; message: string }\n | { kind: 'complete'; current: number; total?: number; message: string }\n | {\n kind: 'fail';\n current: number;\n total?: number;\n message: string;\n error: unknown;\n };\n\ninterface ProgressSessionOptions {\n label: string;\n sink?: McpProgressSink;\n /** Override the rate limit window. Default: 50ms. */\n rateLimitMs?: number;\n}\n\nconst DEFAULT_RATE_LIMIT_MS = 50;\n\nexport class ProgressSession {\n readonly #label: string;\n readonly #sink: McpProgressSink | undefined;\n readonly #rateLimitMs: number;\n readonly #startTime: number;\n\n #cursor = 0;\n #lastSentMs = 0;\n #done = false;\n\n constructor(opts: ProgressSessionOptions) {\n this.#label = opts.label;\n this.#sink = opts.sink;\n this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;\n\n const now = Date.now();\n this.#startTime = now;\n this.#lastSentMs = now - this.#rateLimitMs;\n\n // Synthetic start tick — preserves today's \"fire 0 at session creation\" wire behavior.\n this.#dispatch({\n kind: 'tick',\n current: 0,\n message: this.#label,\n });\n }\n\n set(input: { current: number; total?: number; message?: string }): void {\n if (this.#done) return;\n // The spec requires `progress` to increase on every notification, and the\n // constructor already dispatched current: 0. A repeated or backward tick\n // would put a duplicate value on the wire — drop it.\n if (input.current <= this.#cursor) return;\n this.#cursor = input.current;\n this.#dispatch({\n kind: 'tick',\n current: this.#cursor,\n ...(input.total !== undefined ? { total: input.total } : {}),\n message: input.message ?? this.#label,\n });\n }\n\n complete(message: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'complete',\n current: this.#cursor,\n message,\n });\n }\n\n fail(error: unknown, message?: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'fail',\n current: this.#cursor,\n message: message ?? this.#label,\n error,\n });\n }\n\n #dispatch(event: ProgressEvent): void {\n if (this.#shouldRateLimit(event)) {\n return;\n }\n\n this.#lastSentMs = Date.now();\n\n if (!this.#sink) return;\n try {\n this.#sink.emit(event);\n } catch (err) {\n // A sink failure must never fail the tool call it is reporting on.\n Logger.warn('progress sink emit failed', { eventKind: event.kind, err });\n }\n }\n\n #shouldRateLimit(event: ProgressEvent): boolean {\n if (event.kind !== 'tick') {\n return false;\n }\n\n // Widen the window after 5s of execution; a rateLimitMs of 0 (tests) stays 0\n // only inside the first 5s, which every test run fits in.\n const now = Date.now();\n const effectiveRateLimit =\n now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;\n\n const elapsed = now - this.#lastSentMs;\n return elapsed < effectiveRateLimit;\n }\n}\n\nexport class McpProgressSink {\n private readonly toolName: string;\n private readonly token: string | number;\n private readonly notify: (n: Notification) => Promise<void>;\n readonly #pending = new Set<Promise<void>>();\n #lastProgress = -1;\n\n constructor(\n toolName: string,\n token: string | number,\n notify: (n: Notification) => Promise<void>,\n ) {\n this.toolName = toolName;\n this.token = token;\n this.notify = notify;\n }\n\n emit(event: ProgressEvent): void {\n let current = event.current;\n let total = event.total;\n if (event.kind === 'complete') {\n current = total ?? current;\n total = current;\n }\n if (event.kind !== 'tick') {\n // A terminal frame carries the outcome message, so it must reach the\n // wire. It repeats the cursor whenever the session has no `total` (there\n // is nothing higher to report), and the spec requires progress to\n // increase per token — so advance past the last value instead of dropping\n // the frame.\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 const notificationParams: ProgressNotificationParams = {\n progressToken: this.token,\n progress: current,\n ...(total !== undefined ? { total } : {}),\n message: event.message,\n };\n const promise = this.notify({\n method: 'notifications/progress',\n params: notificationParams,\n })\n .catch((error: unknown) => {\n reportDetachedError(this.toolName, 'progressNotification', error);\n })\n .finally(() => {\n this.#pending.delete(promise);\n });\n this.#pending.add(promise);\n }\n\n async flush(): Promise<void> {\n if (this.#pending.size > 0) {\n await Promise.allSettled([...this.#p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,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YAC3B,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { Notification, ProgressNotificationParams } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport { Logger } from '../core/observability.js';\n\nfunction reportDetachedError(toolName: string, context: string, error: unknown): void {\n const message = formatUnknownErrorMessage(error);\n Logger.emit('warning', `${toolName}: ${context} failed: ${message}`);\n}\n\ntype ProgressEvent =\n | { kind: 'tick'; current: number; total?: number; message: string }\n | { kind: 'complete'; current: number; total?: number; message: string }\n | {\n kind: 'fail';\n current: number;\n total?: number;\n message: string;\n error: unknown;\n };\n\ninterface ProgressSessionOptions {\n label: string;\n sink?: McpProgressSink;\n /** Override the rate limit window. Default: 50ms. */\n rateLimitMs?: number;\n}\n\nconst DEFAULT_RATE_LIMIT_MS = 50;\n\nexport class ProgressSession {\n readonly #label: string;\n readonly #sink: McpProgressSink | undefined;\n readonly #rateLimitMs: number;\n readonly #startTime: number;\n\n #cursor = 0;\n #lastSentMs = 0;\n #done = false;\n\n constructor(opts: ProgressSessionOptions) {\n this.#label = opts.label;\n this.#sink = opts.sink;\n this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;\n\n const now = Date.now();\n this.#startTime = now;\n this.#lastSentMs = now - this.#rateLimitMs;\n\n // Synthetic start tick — preserves today's \"fire 0 at session creation\" wire behavior.\n this.#dispatch({\n kind: 'tick',\n current: 0,\n message: this.#label,\n });\n }\n\n set(input: { current: number; total?: number; message?: string }): void {\n if (this.#done) return;\n // The spec requires `progress` to increase on every notification, and the\n // constructor already dispatched current: 0. A repeated or backward tick\n // would put a duplicate value on the wire — drop it.\n if (input.current <= this.#cursor) return;\n this.#cursor = input.current;\n this.#dispatch({\n kind: 'tick',\n current: this.#cursor,\n ...(input.total !== undefined ? { total: input.total } : {}),\n message: input.message ?? this.#label,\n });\n }\n\n complete(message: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'complete',\n current: this.#cursor,\n message,\n });\n }\n\n fail(error: unknown, message?: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'fail',\n current: this.#cursor,\n message: message ?? this.#label,\n error,\n });\n }\n\n #dispatch(event: ProgressEvent): void {\n if (this.#shouldRateLimit(event)) {\n return;\n }\n\n this.#lastSentMs = Date.now();\n\n if (!this.#sink) return;\n try {\n this.#sink.emit(event);\n } catch (err) {\n // A sink failure must never fail the tool call it is reporting on.\n Logger.warn('progress sink emit failed', { eventKind: event.kind, err });\n }\n }\n\n #shouldRateLimit(event: ProgressEvent): boolean {\n if (event.kind !== 'tick') {\n return false;\n }\n\n // Widen the window after 5s of execution; a rateLimitMs of 0 (tests) stays 0\n // only inside the first 5s, which every test run fits in.\n const now = Date.now();\n const effectiveRateLimit =\n now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;\n\n const elapsed = now - this.#lastSentMs;\n return elapsed < effectiveRateLimit;\n }\n}\n\nexport class McpProgressSink {\n private readonly toolName: string;\n private readonly token: string | number;\n private readonly notify: (n: Notification) => Promise<void>;\n readonly #pending = new Set<Promise<void>>();\n #lastProgress = -1;\n\n constructor(\n toolName: string,\n token: string | number,\n notify: (n: Notification) => Promise<void>,\n ) {\n this.toolName = toolName;\n this.token = token;\n this.notify = notify;\n }\n\n emit(event: ProgressEvent): void {\n let current = event.current;\n let total = event.total;\n if (event.kind === 'complete') {\n current = total ?? current;\n total = current;\n }\n if (event.kind !== 'tick') {\n // A terminal frame carries the outcome message, so it must reach the\n // wire. It repeats the cursor whenever the session has no `total` (there\n // is nothing higher to report), and the spec requires progress to\n // increase per token — so advance past the last value instead of dropping\n // the frame.\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 const notificationParams: ProgressNotificationParams = {\n progressToken: this.token,\n progress: current,\n ...(total !== undefined ? { total } : {}),\n message: event.message,\n };\n const promise = this.notify({\n method: 'notifications/progress',\n params: notificationParams,\n })\n .catch((error: unknown) => {\n reportDetachedError(this.toolName, 'progressNotification', error);\n })\n .finally(() => {\n this.#pending.delete(promise);\n });\n this.#pending.add(promise);\n }\n\n async flush(): Promise<void> {\n if (this.#pending.size > 0) {\n await Promise.allSettled([...this.#pending]);\n }\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":"AAkYA,eAAO,MAAM,SAAS,mCAgKpB,CAAC"}
|
package/dist/tools/read.js
CHANGED
|
@@ -103,7 +103,7 @@ function buildReadSpec(args, signal) {
|
|
|
103
103
|
}
|
|
104
104
|
// No `totalLines`: only `readFull` counts them and a full read never leaves
|
|
105
105
|
// more behind, so a continuation cannot know the total without a second pass.
|
|
106
|
-
function buildReadContinuation(result) {
|
|
106
|
+
function buildReadContinuation(result, requestedPath) {
|
|
107
107
|
if (!result.hasMoreLines)
|
|
108
108
|
return undefined;
|
|
109
109
|
const linesRead = result.linesRead ?? 0;
|
|
@@ -121,7 +121,7 @@ function buildReadContinuation(result) {
|
|
|
121
121
|
const nextEnd = nextStart + chunkSize - 1;
|
|
122
122
|
return {
|
|
123
123
|
tool: 'read',
|
|
124
|
-
args: { path:
|
|
124
|
+
args: { path: requestedPath, startLine: nextStart, endLine: nextEnd },
|
|
125
125
|
hint: `More lines remain from ${String(nextStart)}. Read next chunk with these args.`,
|
|
126
126
|
};
|
|
127
127
|
}
|
|
@@ -157,60 +157,58 @@ async function collectFileBudget(filePaths, maxTotalSize, maxSize, ctx) {
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
let total = 0;
|
|
160
|
-
const
|
|
160
|
+
const skippedResults = new Map();
|
|
161
|
+
const survivors = [];
|
|
162
|
+
let overflowed = false;
|
|
161
163
|
for (let i = 0; i < filePaths.length; i += 1) {
|
|
162
|
-
const
|
|
163
|
-
if (
|
|
164
|
+
const path = filePaths[i];
|
|
165
|
+
if (path === undefined)
|
|
164
166
|
continue;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
//
|
|
168
|
-
// through to survivors so its read surfaces the real error
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
167
|
+
const size = byIndex.get(i);
|
|
168
|
+
if (overflowed) {
|
|
169
|
+
// Only files that were actually stat'd get the TOO_LARGE result; a failed
|
|
170
|
+
// stat falls through to survivors so its read surfaces the real error —
|
|
171
|
+
// not a misleading TOO_LARGE.
|
|
172
|
+
if (size !== undefined) {
|
|
173
|
+
skippedResults.set(i, {
|
|
174
|
+
path,
|
|
175
|
+
error: {
|
|
176
|
+
code: ErrorCode.TOO_LARGE,
|
|
177
|
+
message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,
|
|
178
|
+
path,
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
survivors.push(path);
|
|
174
184
|
}
|
|
175
|
-
|
|
185
|
+
continue;
|
|
176
186
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return { skippedBudget, known };
|
|
180
|
-
}
|
|
181
|
-
function preFilterByBudget(pathList, budgetState) {
|
|
182
|
-
const skippedResults = new Map();
|
|
183
|
-
const survivors = [];
|
|
184
|
-
for (let i = 0; i < pathList.length; i += 1) {
|
|
185
|
-
const path = pathList[i];
|
|
186
|
-
if (path === undefined)
|
|
187
|
+
if (size === undefined) {
|
|
188
|
+
survivors.push(path);
|
|
187
189
|
continue;
|
|
188
|
-
|
|
190
|
+
}
|
|
191
|
+
if (total + size > maxTotalSize) {
|
|
192
|
+
overflowed = true;
|
|
189
193
|
skippedResults.set(i, {
|
|
190
194
|
path,
|
|
191
195
|
error: {
|
|
192
196
|
code: ErrorCode.TOO_LARGE,
|
|
193
|
-
message: `Skipped: combined estimated read would exceed maxTotalSize (${String(
|
|
197
|
+
message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,
|
|
194
198
|
path,
|
|
195
199
|
},
|
|
196
200
|
});
|
|
197
201
|
continue;
|
|
198
202
|
}
|
|
203
|
+
total += size;
|
|
199
204
|
survivors.push(path);
|
|
200
205
|
}
|
|
201
|
-
return { skippedResults, survivors };
|
|
206
|
+
return { skippedResults, survivors, known };
|
|
202
207
|
}
|
|
203
208
|
function buildPerPathReadValue(result, options) {
|
|
204
209
|
const mimeInfo = detectMimeFromContent(result.path, result.content);
|
|
205
210
|
const continuation = result.hasMoreLines && result.readMode !== 'tail'
|
|
206
|
-
? buildReadContinuation(
|
|
207
|
-
path: options.requestedPath,
|
|
208
|
-
hasMoreLines: true,
|
|
209
|
-
...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),
|
|
210
|
-
...(result.startLine !== undefined ? { startLine: result.startLine } : {}),
|
|
211
|
-
...(result.endLine !== undefined ? { endLine: result.endLine } : {}),
|
|
212
|
-
...(result.head !== undefined ? { head: result.head } : {}),
|
|
213
|
-
})
|
|
211
|
+
? buildReadContinuation(result, options.requestedPath)
|
|
214
212
|
: undefined;
|
|
215
213
|
const contentHash = options.includeHash
|
|
216
214
|
? createHash('sha256').update(result.content, 'utf-8').digest('hex')
|
|
@@ -339,12 +337,8 @@ export const READ_FILE = defineTool({
|
|
|
339
337
|
const maxTextFileSize = getMaxTextFileSize();
|
|
340
338
|
const budget = await collectFileBudget(pathList, defaultMaxTotalSize, maxTextFileSize, ctx);
|
|
341
339
|
known = budget.known;
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
maxTotalSize: defaultMaxTotalSize,
|
|
345
|
-
});
|
|
346
|
-
skippedResults = filtered.skippedResults;
|
|
347
|
-
survivors = filtered.survivors;
|
|
340
|
+
skippedResults = budget.skippedResults;
|
|
341
|
+
survivors = budget.survivors;
|
|
348
342
|
}
|
|
349
343
|
else {
|
|
350
344
|
pathList = [args.path ?? ''];
|
package/dist/tools/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,QAAQ,EACR,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,wBAAwB,EACxB,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,8BAA8B,EAC9B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1D,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AAC,OAAO,EAAE,CAAC;YACnD,CAAC,CAAC;iBACD,IAAI,CAAC,MAAM,CAAC,CAAC;QAEtB,yEAAyE;QACzE,oEAAoE;QACpE,2EAA2E;QAC3E,uEAAuE;QACvE,sEAAsE;QACtE,sCAAsC;QACtC,MAAM,iBAAiB,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;YAC/C,IAAI,OAAO,IAAI,MAAM;gBAAE,OAAO,MAAM,CAAC;YACrC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC;YAC5E,OAAO,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,UAAU,EAAE,EAAE,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE;YACnD,IAAI;YACJ,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC;YAChC,GAAG,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport { ErrorCode } from '../core/errors.js';\nimport { buildFileResourceLinkFor, buildFileResourceUri } from '../core/file-uri.js';\nimport { detectMimeFromContent, detectMimeType } from '../core/mime.js';\nimport type { ReadFileResult, ReadSpec } from '../core/read.js';\nimport { readFileWithStats } from '../core/read.js';\nimport {\n ContinuationSchema,\n defaultFalseBoolean,\n FileKind,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n PositiveInt,\n Sha256Hex,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n validateReadRange,\n} from '../core/schema.js';\nimport {\n DEFAULT_CONTINUATION_CHUNK_SIZE,\n DEFAULT_SEARCH_TIMEOUT_MS,\n getDefaultReadManyMaxTotalSize,\n getMaxTextFileSize,\n PARALLEL_CONCURRENCY,\n} from '../core/util.js';\nimport type { PerPathResult } from './batch.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst rangeField = (description: string) =>\n z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(description);\n\nconst readRangeFields = {\n head: rangeField('Return first N lines'),\n tail: rangeField('Return last N lines'),\n startLine: rangeField('Start line (1-indexed)'),\n endLine: rangeField('End line (1-indexed)'),\n};\n\nconst ReadFileInputSchema = singleOrBatchPathsInput({\n includeHash: defaultFalseBoolean('Include SHA-256 hash of the returned content in the response'),\n ...readRangeFields,\n})\n .superRefine((value, ctx) => {\n validateReadRange(\n {\n head: value.head,\n tail: value.tail,\n startLine: value.startLine,\n endLine: value.endLine,\n },\n ctx,\n );\n })\n // Mirror `validateReadRange` on the wire. Without this the four line params\n // published as four independent optional integers, so `{ path, head, tail }`\n // passed the advertised schema and was rejected only at call time.\n //\n // `oneOf` is restated because `.meta()` replaces the entry\n // `singleOrBatchPathsInput` set rather than merging into it — dropping it here\n // would silently un-publish the path/paths rule.\n .meta({\n // The line-param exclusivity that used to sit here as a five-branch\n // `not/anyOf` is one sentence in the description instead: validateReadRange\n // rejects every conflicting combination by name at runtime, so the wire copy\n // was paying for a second statement of a rule the model reads better in\n // prose.\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n dependentRequired: { endLine: ['startLine'] },\n });\n\n// File bytes are NOT here: text rides the text content block, image/audio ride\n// a media block. This schema is the metadata a caller cannot recover from\n// those blocks. `readOnePath` carries the bytes internally via\n// `PerPathReadValue` and `run` drops them before the structured half goes out.\nconst ReadPerPathValueSchema = z.strictObject({\n mimeType: z.string().optional().describe('Detected MIME type (e.g. text/typescript)'),\n kind: FileKind.optional().describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI for externalized content (present when file is stored in resource store)',\n ),\n continuation: ContinuationSchema.optional().describe(\n 'Next-read arguments; present when content was truncated due to size limits',\n ),\n totalLines: NonNegInt.optional().describe('Total line count in the full file'),\n linesRead: NonNegInt.optional().describe('Number of lines returned in this response'),\n hasMoreLines: z\n .boolean()\n .optional()\n .describe('True when additional lines remain beyond what was returned'),\n head: PositiveInt.optional().describe('Head lines requested'),\n tail: PositiveInt.optional().describe('Tail lines requested'),\n startLine: PositiveInt.optional().describe('Start line'),\n endLine: PositiveInt.optional().describe('End line'),\n contentHash: Sha256Hex.optional().describe(\n 'SHA-256 hex digest of the returned content (present when includeHash=true)',\n ),\n});\n\nconst ReadPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: ReadPerPathValueSchema.optional().describe('Read result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst ReadFileOutputSchema = z.strictObject({\n results: z.array(ReadPerPathSchema).describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype ReadFileInput = z.infer<typeof ReadFileInputSchema>;\n\nconst READ_TOOL_LABEL = 'Read';\n\nfunction buildReadSpec(args: ReadFileInput, signal?: AbortSignal): ReadSpec {\n const signalPart = signal ? { signal } : {};\n const { head, tail, startLine, endLine } = args;\n\n if (head !== undefined) return { kind: 'head', lines: head, ...signalPart };\n if (tail !== undefined) return { kind: 'tail', lines: tail, ...signalPart };\n if (startLine !== undefined || endLine !== undefined) {\n return {\n kind: 'range',\n start: startLine ?? 1,\n ...(endLine !== undefined ? { end: endLine } : {}),\n ...signalPart,\n };\n }\n return { kind: 'full', ...signalPart };\n}\n\n// No `totalLines`: only `readFull` counts them and a full read never leaves\n// more behind, so a continuation cannot know the total without a second pass.\nfunction buildReadContinuation(result: {\n path: string;\n hasMoreLines?: boolean;\n linesRead?: number;\n startLine?: number;\n endLine?: number;\n head?: number;\n}): z.infer<typeof ContinuationSchema> | undefined {\n if (!result.hasMoreLines) return undefined;\n const linesRead = result.linesRead ?? 0;\n const nextStart = (result.startLine ?? 1) + linesRead;\n let chunkSize: number;\n if (result.head !== undefined) {\n chunkSize = result.head;\n } else if (result.startLine !== undefined && result.endLine !== undefined) {\n chunkSize = result.endLine - result.startLine + 1;\n } else {\n chunkSize = DEFAULT_CONTINUATION_CHUNK_SIZE;\n }\n const nextEnd = nextStart + chunkSize - 1;\n return {\n tool: 'read',\n args: { path: result.path, startLine: nextStart, endLine: nextEnd },\n hint: `More lines remain from ${String(nextStart)}. Read next chunk with these args.`,\n };\n}\n\n/**\n * The published metadata plus the bytes this call read. `content` and\n * `mediaData` exist only between `readOnePath` and the content blocks `run`\n * builds from them — they are stripped before the structured half is returned,\n * which is why they are not in `ReadPerPathValueSchema`.\n */\ntype PerPathReadValue = z.infer<typeof ReadPerPathValueSchema> & {\n content?: string;\n mediaData?: string;\n};\n\ninterface BatchFileInfo {\n index: number;\n size: number;\n validPath: string;\n stats: Stats;\n}\n\nasync function collectFileBudget(\n filePaths: readonly string[],\n maxTotalSize: number,\n maxSize: number,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'log'>,\n): Promise<{\n skippedBudget: Set<number>;\n known: Map<string, { validPath: string; stats: Stats }>;\n}> {\n const indexed = filePaths.map((path, index) => ({ path, index }));\n const { results } = await processInParallel(\n indexed,\n async ({ path, index }): Promise<BatchFileInfo | undefined> => {\n try {\n const out = await ctx.fs.stat(path);\n return {\n index,\n size: Math.min(out.stats.size, maxSize),\n validPath: out.validPath,\n stats: out.stats,\n };\n } catch (err: unknown) {\n ctx.log?.('debug', `collectFileBudget: stat failed for \"${path}\": ${String(err)}`, 'read');\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const byIndex = new Map<number, number>();\n const known = new Map<string, { validPath: string; stats: Stats }>();\n for (const { value: item } of results) {\n if (!item) continue;\n byIndex.set(item.index, item.size);\n // Keyed by the ORIGINAL requested path string (not validPath) — that's\n // what readOnePath is called with downstream, and what filePaths[i]\n // holds.\n const requestedPath = filePaths[item.index];\n if (requestedPath !== undefined) {\n known.set(requestedPath, { validPath: item.validPath, stats: item.stats });\n }\n }\n\n let total = 0;\n const skippedBudget = new Set<number>();\n for (let i = 0; i < filePaths.length; i += 1) {\n const size = byIndex.get(i);\n if (size === undefined) continue;\n if (total + size > maxTotalSize) {\n // Only mark files that were actually stat'd as too large for the batch\n // budget. A file whose stat already failed (byIndex undefined) must fall\n // through to survivors so its read surfaces the real error (NOT_FILE /\n // permission) — not a misleading TOO_LARGE.\n for (let j = i; j < filePaths.length; j += 1) {\n if (byIndex.get(j) === undefined) continue;\n skippedBudget.add(j);\n }\n break;\n }\n total += size;\n }\n\n return { skippedBudget, known };\n}\n\nfunction preFilterByBudget(\n pathList: readonly string[],\n budgetState: { skippedBudget: Set<number>; maxTotalSize: number },\n): { skippedResults: Map<number, PerPathResult<PerPathReadValue>>; survivors: string[] } {\n const skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n const survivors: string[] = [];\n\n for (let i = 0; i < pathList.length; i += 1) {\n const path = pathList[i];\n if (path === undefined) continue;\n if (budgetState.skippedBudget.has(i)) {\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(\n budgetState.maxTotalSize,\n )} bytes)`,\n path,\n },\n });\n continue;\n }\n survivors.push(path);\n }\n\n return { skippedResults, survivors };\n}\n\nfunction buildPerPathReadValue(\n result: ReadFileResult,\n options: { includeHash?: boolean; hasResourceStore?: boolean; requestedPath: string },\n): PerPathReadValue {\n const mimeInfo = detectMimeFromContent(result.path, result.content);\n const continuation =\n result.hasMoreLines && result.readMode !== 'tail'\n ? buildReadContinuation({\n path: options.requestedPath,\n hasMoreLines: true,\n ...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),\n ...(result.startLine !== undefined ? { startLine: result.startLine } : {}),\n ...(result.endLine !== undefined ? { endLine: result.endLine } : {}),\n ...(result.head !== undefined ? { head: result.head } : {}),\n })\n : undefined;\n const contentHash = options.includeHash\n ? createHash('sha256').update(result.content, 'utf-8').digest('hex')\n : undefined;\n const resourceUri = options.hasResourceStore ? buildFileResourceUri(result.path) : undefined;\n\n return {\n content: result.content,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n ...(continuation ? { continuation } : {}),\n ...(result.totalLines !== undefined ? { totalLines: result.totalLines } : {}),\n ...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),\n ...(result.hasMoreLines ? { hasMoreLines: true } : {}),\n ...(result.head !== undefined ? { head: result.head } : {}),\n ...(result.tail !== undefined ? { tail: result.tail } : {}),\n ...(result.startLine !== undefined ? { startLine: result.startLine } : {}),\n ...(result.endLine !== undefined ? { endLine: result.endLine } : {}),\n ...(contentHash !== undefined ? { contentHash } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n };\n}\n\n/**\n * The two facts the model cannot act on without: that lines were dropped, and\n * the exact args to get the next chunk. Both used to live only in the structured\n * half, which no longer reaches the model. Each line is `//` prefixed and set\n * off by a blank line so it cannot be read as file bytes — do not drop either\n * guard.\n */\nfunction readTrailer(v: PerPathReadValue): string[] {\n const lines: string[] = [];\n if (v.continuation) {\n lines.push(\n `// truncated: ${v.continuation.hint} Continue: read ${JSON.stringify(v.continuation.args)}`,\n );\n } else if (v.hasMoreLines && v.linesRead !== undefined) {\n // A tail read gets no continuation — there are no args that read *backwards*\n // — so say what was shown rather than leaving the truncation silent.\n lines.push(`// truncated: showing last ${String(v.linesRead)} lines`);\n }\n if (v.contentHash !== undefined) lines.push(`// sha256: ${v.contentHash}`);\n return lines;\n}\n\nasync function readOnePath(\n filePath: string,\n args: ReadFileInput,\n ctx: ToolCtx,\n known?: { validPath: string; stats: Stats },\n): Promise<PerPathReadValue> {\n // Image/audio full read: return a media content block instead of throwing\n // INVALID_INPUT (\"Binary file detected.\"). Line-range reads are\n // text-oriented and stay rejected. `readRaw` enforces the same size cap as\n // the text path (getMaxTextFileSize), so a too-large image surfaces TOO_LARGE\n // rather than blowing memory. svg carries kind:'image' but is XML text —\n // readRaw.isBinary is false for it, so it falls through to the text path.\n const isRangeRead =\n args.head !== undefined ||\n args.tail !== undefined ||\n args.startLine !== undefined ||\n args.endLine !== undefined;\n if (!isRangeRead) {\n const mime = detectMimeType(filePath);\n if (mime.kind === 'image' || mime.kind === 'audio') {\n const raw = await ctx.fs.readRaw(filePath, { signal: ctx.signal });\n if (raw.isBinary) {\n return {\n content: `[binary ${mime.kind} content: ${String(raw.content.length)} bytes; returned as a ${mime.kind} content block]`,\n mimeType: raw.mimeType,\n kind: mime.kind,\n mediaData: raw.content.toString('base64'),\n };\n }\n }\n }\n\n const spec = buildReadSpec(args, ctx.signal);\n const result = known\n ? await readFileWithStats(filePath, known.validPath, known.stats, spec)\n : await ctx.fs.readFile(filePath, spec);\n\n return buildPerPathReadValue(result, {\n includeHash: args.includeHash,\n hasResourceStore: ctx.resourceStore !== undefined,\n // The continuation is args the caller pastes back, so it echoes the path\n // they wrote. `result.path` is the resolved absolute one — on Windows that\n // is a backslash-doubling JSON string that also spells out the server root.\n requestedPath: filePath,\n });\n}\n\nexport const READ_FILE = defineTool({\n name: 'read',\n title: 'Read File',\n description:\n 'Read one or more text files and return content. ' +\n 'Partial reads: head (first N lines), tail (last N lines), startLine/endLine (line range). ' +\n 'Batch mode: pass paths[] instead of path; line params are shared across all files. ' +\n 'head, tail, and startLine/endLine are mutually exclusive — use exactly one.',\n input: ReadFileInputSchema,\n output: ReadFileOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FILE,\n progress: (args) => {\n const isBatch = args.paths !== undefined;\n const name = isBatch ? `${String(args.paths?.length ?? 0)} files` : basename(args.path ?? '');\n if (isBatch) {\n return { label: READ_TOOL_LABEL, subject: name };\n }\n let scope: string | undefined;\n if (args.startLine !== undefined) {\n const end = args.endLine ?? '...';\n scope = `${args.startLine}-${String(end)}`;\n } else if (args.head !== undefined) {\n scope = `head ${args.head}`;\n } else if (args.tail !== undefined) {\n scope = `tail ${args.tail}`;\n }\n return { label: READ_TOOL_LABEL, subject: name, ...(scope ? { scope } : {}) };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n let pathList: string[];\n let skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n let survivors: string[];\n let known = new Map<string, { validPath: string; stats: Stats }>();\n\n if (args.paths !== undefined) {\n pathList = args.paths;\n const defaultMaxTotalSize = getDefaultReadManyMaxTotalSize();\n const maxTextFileSize = getMaxTextFileSize();\n const budget = await collectFileBudget(pathList, defaultMaxTotalSize, maxTextFileSize, ctx);\n known = budget.known;\n const filtered = preFilterByBudget(pathList, {\n skippedBudget: budget.skippedBudget,\n maxTotalSize: defaultMaxTotalSize,\n });\n skippedResults = filtered.skippedResults;\n survivors = filtered.survivors;\n } else {\n pathList = [args.path ?? ''];\n survivors = [...pathList];\n }\n\n const batchInput = { paths: survivors };\n\n // Every path can be budget-skipped (a single file over maxTotalSize does\n // it), and runOverPaths rejects an empty list. The per-path TOO_LARGE\n // results are already built — return those rather than failing the call.\n const batch =\n survivors.length === 0\n ? { results: [] as PerPathResult<PerPathReadValue>[] }\n : await runOverPaths<undefined, PerPathReadValue>(\n batchInput,\n ctx,\n ({ path }) => readOnePath(path, args, ctx, known.get(path)),\n { defaultErrorCode: ErrorCode.NOT_FILE },\n );\n\n const resultMap = new Map(batch.results.map((r) => [r.path, r]));\n const ordered: PerPathResult<PerPathReadValue>[] = pathList.map((path, idx) => {\n const skipped = skippedResults.get(idx);\n if (skipped) return skipped;\n const result = resultMap.get(path);\n return (\n result ?? {\n path,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown read failure' },\n }\n );\n });\n\n const failed = ordered.filter((r) => 'error' in r).length;\n const summary = {\n total: ordered.length,\n succeeded: ordered.length - failed,\n failed,\n };\n\n const resources: ContentBlock[] = [];\n for (const result of ordered) {\n if ('error' in result) continue;\n const v = result.value;\n // Image/audio full read: emit the media content block alongside the\n // structured value. The base64 lives in v.mediaData (set in readOnePath).\n if (v.mediaData && v.mimeType && (v.kind === 'image' || v.kind === 'audio')) {\n resources.push(\n v.kind === 'image'\n ? { type: 'image', data: v.mediaData, mimeType: v.mimeType }\n : { type: 'audio', data: v.mediaData, mimeType: v.mimeType },\n );\n continue;\n }\n if (!v.resourceUri || !v.content) continue;\n // `result.path` is the path as *requested*; `v.resourceUri` was built from\n // the *validated* one. Rebuilding from the request would emit a second URI\n // for the same file whenever the two differ in case — subscribe by one and\n // unsubscribe by the other and the watcher never goes away.\n resources.push(\n buildFileResourceLinkFor(\n v.resourceUri,\n basename(result.path),\n v.mimeType ?? 'application/octet-stream',\n Buffer.byteLength(v.content, 'utf8'),\n ),\n );\n }\n\n const [firstOrdered] = ordered;\n const body = (v: PerPathReadValue): string => {\n const content = v.content ?? 'read failed';\n const trailer = readTrailer(v);\n if (trailer.length === 0) return content;\n // Exactly one blank line between the bytes and the trailer, whether or not\n // the file ended in a newline.\n return `${content}${content.endsWith('\\n') ? '\\n' : '\\n\\n'}${trailer.join('\\n')}`;\n };\n const text =\n ordered.length === 1 && firstOrdered !== undefined\n ? 'error' in firstOrdered\n ? firstOrdered.error.message\n : body(firstOrdered.value)\n : ordered\n .map((r) => {\n const header = `// ${r.path}`;\n if ('value' in r) return `${header}\\n${body(r.value)}`;\n return `${header}\\n// Error: ${r.error.message}`;\n })\n .join('\\n\\n');\n\n // The bytes ship once. `text` above already carries every file's content\n // verbatim (and image/audio bytes ride the media content block), so\n // repeating them under `results[].value` doubled both the wire payload and\n // the model's token cost for every read. The structured half keeps the\n // metadata a client cannot recover from the text: paths, line counts,\n // hashes, continuations, resourceUri.\n const structuredResults = ordered.map((result) => {\n if ('error' in result) return result;\n const { content: _content, mediaData: _mediaData, ...value } = result.value;\n return { ...result, value };\n });\n\n return {\n structured: { results: structuredResults, summary },\n text,\n isError: isTotalFailure(summary),\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,QAAQ,EACR,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,wBAAwB,EACxB,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,8BAA8B,EAC9B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,UAAU,GAAG,CAAC,WAAmB,EAAE,EAAE,CACzC,CAAC;KACE,KAAK,EAAE;KACP,GAAG,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,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;gBACT,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;gBAC9B,IAAI,OAAO,IAAI,CAAC;oBAAE,OAAO,GAAG,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvD,OAAO,GAAG,MAAM,eAAe,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;YACnD,CAAC,CAAC;iBACD,IAAI,CAAC,MAAM,CAAC,CAAC;QAEtB,yEAAyE;QACzE,oEAAoE;QACpE,2EAA2E;QAC3E,uEAAuE;QACvE,sEAAsE;QACtE,sCAAsC;QACtC,MAAM,iBAAiB,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;YAC/C,IAAI,OAAO,IAAI,MAAM;gBAAE,OAAO,MAAM,CAAC;YACrC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC;YAC5E,OAAO,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,UAAU,EAAE,EAAE,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE;YACnD,IAAI;YACJ,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC;YAChC,GAAG,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport { ErrorCode } from '../core/errors.js';\nimport { buildFileResourceLinkFor, buildFileResourceUri } from '../core/file-uri.js';\nimport { detectMimeFromContent, detectMimeType } from '../core/mime.js';\nimport type { ReadFileResult, ReadSpec } from '../core/read.js';\nimport { readFileWithStats } from '../core/read.js';\nimport {\n ContinuationSchema,\n defaultFalseBoolean,\n FileKind,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n PositiveInt,\n Sha256Hex,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n validateReadRange,\n} from '../core/schema.js';\nimport {\n DEFAULT_CONTINUATION_CHUNK_SIZE,\n DEFAULT_SEARCH_TIMEOUT_MS,\n getDefaultReadManyMaxTotalSize,\n getMaxTextFileSize,\n PARALLEL_CONCURRENCY,\n} from '../core/util.js';\nimport type { PerPathResult } from './batch.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst rangeField = (description: string) =>\n z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(description);\n\nconst readRangeFields = {\n head: rangeField('Return first N lines'),\n tail: rangeField('Return last N lines'),\n startLine: rangeField('Start line (1-indexed)'),\n endLine: rangeField('End line (1-indexed)'),\n};\n\nconst ReadFileInputSchema = singleOrBatchPathsInput({\n includeHash: defaultFalseBoolean('Include SHA-256 hash of the returned content in the response'),\n ...readRangeFields,\n})\n .superRefine((value, ctx) => {\n validateReadRange(\n {\n head: value.head,\n tail: value.tail,\n startLine: value.startLine,\n endLine: value.endLine,\n },\n ctx,\n );\n })\n // Mirror `validateReadRange` on the wire. Without this the four line params\n // published as four independent optional integers, so `{ path, head, tail }`\n // passed the advertised schema and was rejected only at call time.\n //\n // `oneOf` is restated because `.meta()` replaces the entry\n // `singleOrBatchPathsInput` set rather than merging into it — dropping it here\n // would silently un-publish the path/paths rule.\n .meta({\n // The line-param exclusivity that used to sit here as a five-branch\n // `not/anyOf` is one sentence in the description instead: validateReadRange\n // rejects every conflicting combination by name at runtime, so the wire copy\n // was paying for a second statement of a rule the model reads better in\n // prose.\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n dependentRequired: { endLine: ['startLine'] },\n });\n\n// File bytes are NOT here: text rides the text content block, image/audio ride\n// a media block. This schema is the metadata a caller cannot recover from\n// those blocks. `readOnePath` carries the bytes internally via\n// `PerPathReadValue` and `run` drops them before the structured half goes out.\nconst ReadPerPathValueSchema = z.strictObject({\n mimeType: z.string().optional().describe('Detected MIME type (e.g. text/typescript)'),\n kind: FileKind.optional().describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI for externalized content (present when file is stored in resource store)',\n ),\n continuation: ContinuationSchema.optional().describe(\n 'Next-read arguments; present when content was truncated due to size limits',\n ),\n totalLines: NonNegInt.optional().describe('Total line count in the full file'),\n linesRead: NonNegInt.optional().describe('Number of lines returned in this response'),\n hasMoreLines: z\n .boolean()\n .optional()\n .describe('True when additional lines remain beyond what was returned'),\n head: PositiveInt.optional().describe('Head lines requested'),\n tail: PositiveInt.optional().describe('Tail lines requested'),\n startLine: PositiveInt.optional().describe('Start line'),\n endLine: PositiveInt.optional().describe('End line'),\n contentHash: Sha256Hex.optional().describe(\n 'SHA-256 hex digest of the returned content (present when includeHash=true)',\n ),\n});\n\nconst ReadPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: ReadPerPathValueSchema.optional().describe('Read result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst ReadFileOutputSchema = z.strictObject({\n results: z.array(ReadPerPathSchema).describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype ReadFileInput = z.infer<typeof ReadFileInputSchema>;\n\nconst READ_TOOL_LABEL = 'Read';\n\nfunction buildReadSpec(args: ReadFileInput, signal?: AbortSignal): ReadSpec {\n const signalPart = signal ? { signal } : {};\n const { head, tail, startLine, endLine } = args;\n\n if (head !== undefined) return { kind: 'head', lines: head, ...signalPart };\n if (tail !== undefined) return { kind: 'tail', lines: tail, ...signalPart };\n if (startLine !== undefined || endLine !== undefined) {\n return {\n kind: 'range',\n start: startLine ?? 1,\n ...(endLine !== undefined ? { end: endLine } : {}),\n ...signalPart,\n };\n }\n return { kind: 'full', ...signalPart };\n}\n\n// No `totalLines`: only `readFull` counts them and a full read never leaves\n// more behind, so a continuation cannot know the total without a second pass.\nfunction buildReadContinuation(\n result: ReadFileResult,\n requestedPath: string,\n): z.infer<typeof ContinuationSchema> | undefined {\n if (!result.hasMoreLines) return undefined;\n const linesRead = result.linesRead ?? 0;\n const nextStart = (result.startLine ?? 1) + linesRead;\n let chunkSize: number;\n if (result.head !== undefined) {\n chunkSize = result.head;\n } else if (result.startLine !== undefined && result.endLine !== undefined) {\n chunkSize = result.endLine - result.startLine + 1;\n } else {\n chunkSize = DEFAULT_CONTINUATION_CHUNK_SIZE;\n }\n const nextEnd = nextStart + chunkSize - 1;\n return {\n tool: 'read',\n args: { path: requestedPath, startLine: nextStart, endLine: nextEnd },\n hint: `More lines remain from ${String(nextStart)}. Read next chunk with these args.`,\n };\n}\n\n/**\n * The published metadata plus the bytes this call read. `content` and\n * `mediaData` exist only between `readOnePath` and the content blocks `run`\n * builds from them — they are stripped before the structured half is returned,\n * which is why they are not in `ReadPerPathValueSchema`.\n */\ntype PerPathReadValue = z.infer<typeof ReadPerPathValueSchema> & {\n content?: string;\n mediaData?: string;\n};\n\ninterface BatchFileInfo {\n index: number;\n size: number;\n validPath: string;\n stats: Stats;\n}\n\nasync function collectFileBudget(\n filePaths: readonly string[],\n maxTotalSize: number,\n maxSize: number,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'log'>,\n): Promise<{\n skippedResults: Map<number, PerPathResult<PerPathReadValue>>;\n survivors: string[];\n known: Map<string, { validPath: string; stats: Stats }>;\n}> {\n const indexed = filePaths.map((path, index) => ({ path, index }));\n const { results } = await processInParallel(\n indexed,\n async ({ path, index }): Promise<BatchFileInfo | undefined> => {\n try {\n const out = await ctx.fs.stat(path);\n return {\n index,\n size: Math.min(out.stats.size, maxSize),\n validPath: out.validPath,\n stats: out.stats,\n };\n } catch (err: unknown) {\n ctx.log?.('debug', `collectFileBudget: stat failed for \"${path}\": ${String(err)}`, 'read');\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const byIndex = new Map<number, number>();\n const known = new Map<string, { validPath: string; stats: Stats }>();\n for (const { value: item } of results) {\n if (!item) continue;\n byIndex.set(item.index, item.size);\n // Keyed by the ORIGINAL requested path string (not validPath) — that's\n // what readOnePath is called with downstream, and what filePaths[i]\n // holds.\n const requestedPath = filePaths[item.index];\n if (requestedPath !== undefined) {\n known.set(requestedPath, { validPath: item.validPath, stats: item.stats });\n }\n }\n\n let total = 0;\n const skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n const survivors: string[] = [];\n let overflowed = false;\n for (let i = 0; i < filePaths.length; i += 1) {\n const path = filePaths[i];\n if (path === undefined) continue;\n const size = byIndex.get(i);\n if (overflowed) {\n // Only files that were actually stat'd get the TOO_LARGE result; a failed\n // stat falls through to survivors so its read surfaces the real error —\n // not a misleading TOO_LARGE.\n if (size !== undefined) {\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n } else {\n survivors.push(path);\n }\n continue;\n }\n if (size === undefined) {\n survivors.push(path);\n continue;\n }\n if (total + size > maxTotalSize) {\n overflowed = true;\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n continue;\n }\n total += size;\n survivors.push(path);\n }\n\n return { skippedResults, survivors, known };\n}\n\nfunction buildPerPathReadValue(\n result: ReadFileResult,\n options: { includeHash?: boolean; hasResourceStore?: boolean; requestedPath: string },\n): PerPathReadValue {\n const mimeInfo = detectMimeFromContent(result.path, result.content);\n const continuation =\n result.hasMoreLines && result.readMode !== 'tail'\n ? buildReadContinuation(result, options.requestedPath)\n : undefined;\n const contentHash = options.includeHash\n ? createHash('sha256').update(result.content, 'utf-8').digest('hex')\n : undefined;\n const resourceUri = options.hasResourceStore ? buildFileResourceUri(result.path) : undefined;\n\n return {\n content: result.content,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n ...(continuation ? { continuation } : {}),\n ...(result.totalLines !== undefined ? { totalLines: result.totalLines } : {}),\n ...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),\n ...(result.hasMoreLines ? { hasMoreLines: true } : {}),\n ...(result.head !== undefined ? { head: result.head } : {}),\n ...(result.tail !== undefined ? { tail: result.tail } : {}),\n ...(result.startLine !== undefined ? { startLine: result.startLine } : {}),\n ...(result.endLine !== undefined ? { endLine: result.endLine } : {}),\n ...(contentHash !== undefined ? { contentHash } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n };\n}\n\n/**\n * The two facts the model cannot act on without: that lines were dropped, and\n * the exact args to get the next chunk. Both used to live only in the structured\n * half, which no longer reaches the model. Each line is `//` prefixed and set\n * off by a blank line so it cannot be read as file bytes — do not drop either\n * guard.\n */\nfunction readTrailer(v: PerPathReadValue): string[] {\n const lines: string[] = [];\n if (v.continuation) {\n lines.push(\n `// truncated: ${v.continuation.hint} Continue: read ${JSON.stringify(v.continuation.args)}`,\n );\n } else if (v.hasMoreLines && v.linesRead !== undefined) {\n // A tail read gets no continuation — there are no args that read *backwards*\n // — so say what was shown rather than leaving the truncation silent.\n lines.push(`// truncated: showing last ${String(v.linesRead)} lines`);\n }\n if (v.contentHash !== undefined) lines.push(`// sha256: ${v.contentHash}`);\n return lines;\n}\n\nasync function readOnePath(\n filePath: string,\n args: ReadFileInput,\n ctx: ToolCtx,\n known?: { validPath: string; stats: Stats },\n): Promise<PerPathReadValue> {\n // Image/audio full read: return a media content block instead of throwing\n // INVALID_INPUT (\"Binary file detected.\"). Line-range reads are\n // text-oriented and stay rejected. `readRaw` enforces the same size cap as\n // the text path (getMaxTextFileSize), so a too-large image surfaces TOO_LARGE\n // rather than blowing memory. svg carries kind:'image' but is XML text —\n // readRaw.isBinary is false for it, so it falls through to the text path.\n const isRangeRead =\n args.head !== undefined ||\n args.tail !== undefined ||\n args.startLine !== undefined ||\n args.endLine !== undefined;\n if (!isRangeRead) {\n const mime = detectMimeType(filePath);\n if (mime.kind === 'image' || mime.kind === 'audio') {\n const raw = await ctx.fs.readRaw(filePath, { signal: ctx.signal });\n if (raw.isBinary) {\n return {\n content: `[binary ${mime.kind} content: ${String(raw.content.length)} bytes; returned as a ${mime.kind} content block]`,\n mimeType: raw.mimeType,\n kind: mime.kind,\n mediaData: raw.content.toString('base64'),\n };\n }\n }\n }\n\n const spec = buildReadSpec(args, ctx.signal);\n const result = known\n ? await readFileWithStats(filePath, known.validPath, known.stats, spec)\n : await ctx.fs.readFile(filePath, spec);\n\n return buildPerPathReadValue(result, {\n includeHash: args.includeHash,\n hasResourceStore: ctx.resourceStore !== undefined,\n // The continuation is args the caller pastes back, so it echoes the path\n // they wrote. `result.path` is the resolved absolute one — on Windows that\n // is a backslash-doubling JSON string that also spells out the server root.\n requestedPath: filePath,\n });\n}\n\nexport const READ_FILE = defineTool({\n name: 'read',\n title: 'Read File',\n description:\n 'Read one or more text files and return content. ' +\n 'Partial reads: head (first N lines), tail (last N lines), startLine/endLine (line range). ' +\n 'Batch mode: pass paths[] instead of path; line params are shared across all files. ' +\n 'head, tail, and startLine/endLine are mutually exclusive — use exactly one.',\n input: ReadFileInputSchema,\n output: ReadFileOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FILE,\n progress: (args) => {\n const isBatch = args.paths !== undefined;\n const name = isBatch ? `${String(args.paths?.length ?? 0)} files` : basename(args.path ?? '');\n if (isBatch) {\n return { label: READ_TOOL_LABEL, subject: name };\n }\n let scope: string | undefined;\n if (args.startLine !== undefined) {\n const end = args.endLine ?? '...';\n scope = `${args.startLine}-${String(end)}`;\n } else if (args.head !== undefined) {\n scope = `head ${args.head}`;\n } else if (args.tail !== undefined) {\n scope = `tail ${args.tail}`;\n }\n return { label: READ_TOOL_LABEL, subject: name, ...(scope ? { scope } : {}) };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n let pathList: string[];\n let skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n let survivors: string[];\n let known = new Map<string, { validPath: string; stats: Stats }>();\n\n if (args.paths !== undefined) {\n pathList = args.paths;\n const defaultMaxTotalSize = getDefaultReadManyMaxTotalSize();\n const maxTextFileSize = getMaxTextFileSize();\n const budget = await collectFileBudget(pathList, defaultMaxTotalSize, maxTextFileSize, ctx);\n known = budget.known;\n skippedResults = budget.skippedResults;\n survivors = budget.survivors;\n } else {\n pathList = [args.path ?? ''];\n survivors = [...pathList];\n }\n\n const batchInput = { paths: survivors };\n\n // Every path can be budget-skipped (a single file over maxTotalSize does\n // it), and runOverPaths rejects an empty list. The per-path TOO_LARGE\n // results are already built — return those rather than failing the call.\n const batch =\n survivors.length === 0\n ? { results: [] as PerPathResult<PerPathReadValue>[] }\n : await runOverPaths<undefined, PerPathReadValue>(\n batchInput,\n ctx,\n ({ path }) => readOnePath(path, args, ctx, known.get(path)),\n { defaultErrorCode: ErrorCode.NOT_FILE },\n );\n\n const resultMap = new Map(batch.results.map((r) => [r.path, r]));\n const ordered: PerPathResult<PerPathReadValue>[] = pathList.map((path, idx) => {\n const skipped = skippedResults.get(idx);\n if (skipped) return skipped;\n const result = resultMap.get(path);\n return (\n result ?? {\n path,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown read failure' },\n }\n );\n });\n\n const failed = ordered.filter((r) => 'error' in r).length;\n const summary = {\n total: ordered.length,\n succeeded: ordered.length - failed,\n failed,\n };\n\n const resources: ContentBlock[] = [];\n for (const result of ordered) {\n if ('error' in result) continue;\n const v = result.value;\n // Image/audio full read: emit the media content block alongside the\n // structured value. The base64 lives in v.mediaData (set in readOnePath).\n if (v.mediaData && v.mimeType && (v.kind === 'image' || v.kind === 'audio')) {\n resources.push(\n v.kind === 'image'\n ? { type: 'image', data: v.mediaData, mimeType: v.mimeType }\n : { type: 'audio', data: v.mediaData, mimeType: v.mimeType },\n );\n continue;\n }\n if (!v.resourceUri || !v.content) continue;\n // `result.path` is the path as *requested*; `v.resourceUri` was built from\n // the *validated* one. Rebuilding from the request would emit a second URI\n // for the same file whenever the two differ in case — subscribe by one and\n // unsubscribe by the other and the watcher never goes away.\n resources.push(\n buildFileResourceLinkFor(\n v.resourceUri,\n basename(result.path),\n v.mimeType ?? 'application/octet-stream',\n Buffer.byteLength(v.content, 'utf8'),\n ),\n );\n }\n\n const [firstOrdered] = ordered;\n const body = (v: PerPathReadValue): string => {\n const content = v.content ?? 'read failed';\n const trailer = readTrailer(v);\n if (trailer.length === 0) return content;\n // Exactly one blank line between the bytes and the trailer, whether or not\n // the file ended in a newline.\n return `${content}${content.endsWith('\\n') ? '\\n' : '\\n\\n'}${trailer.join('\\n')}`;\n };\n const text =\n ordered.length === 1 && firstOrdered !== undefined\n ? 'error' in firstOrdered\n ? firstOrdered.error.message\n : body(firstOrdered.value)\n : ordered\n .map((r) => {\n const header = `// ${r.path}`;\n if ('value' in r) return `${header}\\n${body(r.value)}`;\n return `${header}\\n// Error: ${r.error.message}`;\n })\n .join('\\n\\n');\n\n // The bytes ship once. `text` above already carries every file's content\n // verbatim (and image/audio bytes ride the media content block), so\n // repeating them under `results[].value` doubled both the wire payload and\n // the model's token cost for every read. The structured half keeps the\n // metadata a client cannot recover from the text: paths, line counts,\n // hashes, continuations, resourceUri.\n const structuredResults = ordered.map((result) => {\n if ('error' in result) return result;\n const { content: _content, mediaData: _mediaData, ...value } = result.value;\n return { ...result, value };\n });\n\n return {\n structured: { results: structuredResults, summary },\n text,\n isError: isTotalFailure(summary),\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replace-in-files.d.ts","sourceRoot":"","sources":["../../src/tools/replace-in-files.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"replace-in-files.d.ts","sourceRoot":"","sources":["../../src/tools/replace-in-files.ts"],"names":[],"mappings":"AAylBA,eAAO,MAAM,kBAAkB,mCAyC7B,CAAC"}
|
|
@@ -251,17 +251,6 @@ function createCaseSensitiveLiteralMatcher(searchPattern) {
|
|
|
251
251
|
},
|
|
252
252
|
};
|
|
253
253
|
}
|
|
254
|
-
function buildReplacementPlan(content, replacement, matcher) {
|
|
255
|
-
const { content: updatedContent, matchCount } = matcher.replace(content, replacement);
|
|
256
|
-
if (matchCount === 0) {
|
|
257
|
-
return undefined;
|
|
258
|
-
}
|
|
259
|
-
return {
|
|
260
|
-
matchCount,
|
|
261
|
-
originalContent: content,
|
|
262
|
-
updatedContent,
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
254
|
async function processEntry(entryPath, ctx) {
|
|
266
255
|
const { options, signal, summary } = ctx;
|
|
267
256
|
const validPath = entryPath;
|
|
@@ -308,7 +297,9 @@ async function readReplacementPlan(validPath, ctx) {
|
|
|
308
297
|
const buffer = await readFileBufferWithLimit(fileHandle, maxFileSize, validPath, signal);
|
|
309
298
|
if (!matcher.testBuffer(buffer))
|
|
310
299
|
return undefined;
|
|
311
|
-
|
|
300
|
+
const originalContent = buffer.toString('utf-8');
|
|
301
|
+
const { content: updatedContent, matchCount } = matcher.replace(originalContent, replacement);
|
|
302
|
+
return matchCount === 0 ? undefined : { matchCount, originalContent, updatedContent };
|
|
312
303
|
}
|
|
313
304
|
catch (e_1) {
|
|
314
305
|
env_1.error = e_1;
|
|
@@ -414,13 +405,8 @@ async function handleSearchAndReplace(args, ctx) {
|
|
|
414
405
|
const effectivePattern = args.pattern ?? '**/*';
|
|
415
406
|
// An explicit single-file target bypasses baseNameMatch/exclude/hidden/
|
|
416
407
|
// gitignore filtering — it should always be processed as the one file named.
|
|
417
|
-
// The async generator matches globEntries' AsyncIterable contract; it needs
|
|
418
|
-
// no await (single yield), hence the disable.
|
|
419
408
|
const entries = singleFile
|
|
420
|
-
?
|
|
421
|
-
(async function* singleFileEntry() {
|
|
422
|
-
yield { path: singleFile };
|
|
423
|
-
})()
|
|
409
|
+
? [{ path: singleFile }]
|
|
424
410
|
: globEntries({
|
|
425
411
|
cwd: root,
|
|
426
412
|
pattern: effectivePattern,
|