@mwillbanks/ast-mcp 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -22
- package/dist/ast-mcp.js +301 -101
- package/dist/ast-mcp.js.map +107 -27
- package/package.json +3 -1
- package/src/ast-bro/capability.ts +3 -8
- package/src/ast-bro/client.ts +18 -2
- package/src/ast-bro/result.ts +5 -12
- package/src/cli.ts +112 -13
- package/src/config-cli.ts +54 -0
- package/src/config.ts +886 -0
- package/src/helpers/aider.ts +252 -0
- package/src/helpers/ast-bro.ts +64 -0
- package/src/helpers/config.ts +149 -0
- package/src/helpers/hook.ts +60 -0
- package/src/helpers/installer.ts +249 -0
- package/src/helpers/json.ts +19 -0
- package/src/helpers/mcp-schema.ts +31 -0
- package/src/helpers/process.ts +31 -0
- package/src/helpers/string.ts +97 -0
- package/src/hook.ts +135 -40
- package/src/http-entry.ts +1 -1
- package/src/http.ts +118 -103
- package/src/installer-transport.ts +190 -0
- package/src/installer.ts +596 -235
- package/src/mcp-cli.ts +104 -0
- package/src/patch/aider.ts +6 -199
- package/src/patch/engine.ts +271 -197
- package/src/runtime/dependencies.ts +161 -8
- package/src/runtime/file-delete.ts +13 -9
- package/src/runtime/file-read.ts +91 -57
- package/src/runtime/file-rename.ts +158 -0
- package/src/runtime/format.ts +57 -34
- package/src/runtime/paths.ts +30 -16
- package/src/runtime/policy.ts +21 -0
- package/src/runtime/process-input.ts +14 -4
- package/src/service.ts +219 -0
- package/src/shell-policy.ts +331 -0
- package/src/stdio.ts +47 -35
- package/src/tools/ast-bro.ts +12 -6
- package/src/tools/configured.ts +28 -0
- package/src/tools/files.ts +24 -27
- package/src/tools/index.ts +5 -3
- package/src/tools/lifecycle.ts +69 -55
- package/templates/skills/ast-mcp/SKILL.md +7 -6
- package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
- package/templates/skills/ast-mcp/evals/evals.json +1 -0
- package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
- package/templates/skills/ast-mcp/evals/score.ts +304 -267
- package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
- package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
- package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
- package/templates/skills/ast-mcp/evals/source.ts +164 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
- package/templates/skills/ast-mcp/references/installation.md +24 -11
- package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
- package/templates/skills/ast-mcp/scripts/check-install.ts +312 -110
|
@@ -1,20 +1,164 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { accessSync, constants, readFileSync } from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
5
|
+
import { currentConfig } from "../config";
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
const PACKAGE_ROOT = path.resolve(
|
|
6
8
|
import.meta.dir,
|
|
7
9
|
path.basename(import.meta.dir) === "dist" ? ".." : "../..",
|
|
8
10
|
);
|
|
9
11
|
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
|
|
14
|
+
interface BinaryResolutionOptions {
|
|
15
|
+
globalBinDirectories?: string[];
|
|
16
|
+
packageBinary?: string;
|
|
17
|
+
packageRoot?: string;
|
|
18
|
+
pathValue?: string;
|
|
19
|
+
platform?: NodeJS.Platform;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function executableNames(name: string, platform: NodeJS.Platform) {
|
|
23
|
+
if (platform !== "win32") return [name];
|
|
24
|
+
const extensions = (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
|
|
25
|
+
.split(";")
|
|
26
|
+
.filter(Boolean);
|
|
27
|
+
return [name, ...extensions.map((extension) => `${name}${extension}`)];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isExecutable(file: string, platform: NodeJS.Platform) {
|
|
31
|
+
try {
|
|
32
|
+
accessSync(
|
|
33
|
+
file,
|
|
34
|
+
platform === "win32" ? constants.F_OK : constants.F_OK | constants.X_OK,
|
|
35
|
+
);
|
|
36
|
+
return true;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function packageBinary(packageName: string, binaryName: string) {
|
|
43
|
+
try {
|
|
44
|
+
const manifestPath = require.resolve(`${packageName}/package.json`);
|
|
45
|
+
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
|
|
46
|
+
bin?: string | Record<string, string>;
|
|
47
|
+
};
|
|
48
|
+
const relative =
|
|
49
|
+
typeof manifest.bin === "string"
|
|
50
|
+
? manifest.bin
|
|
51
|
+
: manifest.bin?.[binaryName];
|
|
52
|
+
return relative
|
|
53
|
+
? path.resolve(path.dirname(manifestPath), relative)
|
|
54
|
+
: undefined;
|
|
55
|
+
} catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function commandOutput(command: string, args: string[]) {
|
|
61
|
+
try {
|
|
62
|
+
const result = Bun.spawnSync([command, ...args], {
|
|
63
|
+
stderr: "ignore",
|
|
64
|
+
stdout: "pipe",
|
|
65
|
+
});
|
|
66
|
+
return result.exitCode === 0 ? result.stdout.toString().trim() : "";
|
|
67
|
+
} catch {
|
|
68
|
+
return "";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function globalBinDirectories(binaryName: string, platform: NodeJS.Platform) {
|
|
73
|
+
const directories = new Set<string>();
|
|
74
|
+
const add = (value: string | undefined) => {
|
|
75
|
+
if (value) directories.add(path.resolve(value));
|
|
76
|
+
};
|
|
77
|
+
const yarnBinary = commandOutput("yarn", ["bin", binaryName]);
|
|
78
|
+
if (yarnBinary) add(path.dirname(yarnBinary));
|
|
79
|
+
add(process.env.BUN_INSTALL && path.join(process.env.BUN_INSTALL, "bin"));
|
|
80
|
+
add(process.env.PNPM_HOME);
|
|
81
|
+
add(
|
|
82
|
+
process.env.npm_config_prefix &&
|
|
83
|
+
(platform === "win32"
|
|
84
|
+
? process.env.npm_config_prefix
|
|
85
|
+
: path.join(process.env.npm_config_prefix, "bin")),
|
|
86
|
+
);
|
|
87
|
+
add(path.join(os.homedir(), ".bun/bin"));
|
|
88
|
+
add(path.join(os.homedir(), ".bun/install/global/node_modules/.bin"));
|
|
89
|
+
|
|
90
|
+
add(commandOutput("bun", ["pm", "bin", "-g"]));
|
|
91
|
+
add(commandOutput("pnpm", ["bin", "-g"]));
|
|
92
|
+
add(commandOutput("yarn", ["global", "bin"]));
|
|
93
|
+
const npmPrefix = commandOutput("npm", ["prefix", "-g"]);
|
|
94
|
+
add(
|
|
95
|
+
npmPrefix &&
|
|
96
|
+
(platform === "win32" ? npmPrefix : path.join(npmPrefix, "bin")),
|
|
97
|
+
);
|
|
98
|
+
return [...directories];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function executableCandidate(candidates: string[], platform: NodeJS.Platform) {
|
|
102
|
+
return candidates.find((candidate) => isExecutable(candidate, platform));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function ancestorBinaryCandidates(packageRoot: string, names: string[]) {
|
|
106
|
+
const candidates: string[] = [];
|
|
107
|
+
for (
|
|
108
|
+
let current = packageRoot;
|
|
109
|
+
path.dirname(current) !== current;
|
|
110
|
+
current = path.dirname(current)
|
|
111
|
+
) {
|
|
112
|
+
for (const name of names)
|
|
113
|
+
candidates.push(path.join(current, "node_modules/.bin", name));
|
|
114
|
+
}
|
|
115
|
+
return candidates;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function directoryBinaryCandidates(directories: string[], names: string[]) {
|
|
119
|
+
const candidates: string[] = [];
|
|
120
|
+
for (const directory of directories) {
|
|
121
|
+
if (!directory) continue;
|
|
122
|
+
for (const name of names) candidates.push(path.join(directory, name));
|
|
123
|
+
}
|
|
124
|
+
return candidates;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function resolveDependencyBinary(
|
|
128
|
+
binaryName: string,
|
|
129
|
+
packageName = binaryName,
|
|
130
|
+
options: BinaryResolutionOptions = {},
|
|
131
|
+
) {
|
|
132
|
+
const platform = options.platform ?? process.platform;
|
|
133
|
+
const packageRoot = options.packageRoot ?? PACKAGE_ROOT;
|
|
134
|
+
const names = executableNames(binaryName, platform);
|
|
135
|
+
const localCandidates = ancestorBinaryCandidates(packageRoot, names);
|
|
136
|
+
const directPackageBinary =
|
|
137
|
+
options.packageBinary ?? packageBinary(packageName, binaryName);
|
|
138
|
+
if (directPackageBinary) localCandidates.push(directPackageBinary);
|
|
139
|
+
const local = executableCandidate(localCandidates, platform);
|
|
140
|
+
if (local) return local;
|
|
141
|
+
const globalDirectories =
|
|
142
|
+
options.globalBinDirectories ?? globalBinDirectories(binaryName, platform);
|
|
143
|
+
const global = executableCandidate(
|
|
144
|
+
directoryBinaryCandidates(globalDirectories, names),
|
|
145
|
+
platform,
|
|
146
|
+
);
|
|
147
|
+
if (global) return global;
|
|
148
|
+
const pathDirectories = (options.pathValue ?? process.env.PATH ?? "").split(
|
|
149
|
+
path.delimiter,
|
|
150
|
+
);
|
|
151
|
+
return executableCandidate(
|
|
152
|
+
directoryBinaryCandidates(pathDirectories, names),
|
|
153
|
+
platform,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
14
156
|
|
|
15
157
|
export const AST_BRO_VERSION = "3.0.0";
|
|
16
158
|
export const AST_BRO_BINARY =
|
|
17
|
-
process.env.AST_BRO_BINARY ??
|
|
159
|
+
process.env.AST_BRO_BINARY ??
|
|
160
|
+
resolveDependencyBinary("ast-bro", "@ast-bro/cli") ??
|
|
161
|
+
"ast-bro";
|
|
18
162
|
|
|
19
163
|
export function assertAstBroAvailable(
|
|
20
164
|
binary = AST_BRO_BINARY,
|
|
@@ -51,4 +195,13 @@ export function assertAstBroAvailable(
|
|
|
51
195
|
|
|
52
196
|
export const DPRINT_BINARY =
|
|
53
197
|
process.env.DPRINT_BINARY ??
|
|
54
|
-
|
|
198
|
+
resolveDependencyBinary("dprint", "dprint") ??
|
|
199
|
+
"dprint";
|
|
200
|
+
|
|
201
|
+
export async function configuredAstBroBinary(): Promise<string> {
|
|
202
|
+
return (await currentConfig()).dependencies.astBroBinary ?? AST_BRO_BINARY;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function configuredDprintBinary(): Promise<string> {
|
|
206
|
+
return (await currentConfig()).dependencies.dprintBinary ?? DPRINT_BINARY;
|
|
207
|
+
}
|
|
@@ -4,12 +4,13 @@ import { astCapable } from "../ast-bro/capability";
|
|
|
4
4
|
import { callAstBro } from "../ast-bro/client";
|
|
5
5
|
import { parseAstBroJson } from "../ast-bro/result";
|
|
6
6
|
import { detectAstLanguage } from "../patch/languages";
|
|
7
|
-
import {
|
|
7
|
+
import { sha256File } from "./hash";
|
|
8
8
|
import { withFileLocks } from "./locks";
|
|
9
9
|
import { resolveWritablePath, rootForPath } from "./paths";
|
|
10
|
+
import { requireExpectedHash, verifyExpectedHash } from "./policy";
|
|
10
11
|
|
|
11
12
|
export interface FileDeleteRequest {
|
|
12
|
-
expectedSha256
|
|
13
|
+
expectedSha256?: string;
|
|
13
14
|
forceReferences?: boolean;
|
|
14
15
|
}
|
|
15
16
|
|
|
@@ -41,7 +42,13 @@ async function emptyParents(filePath: string, root: string) {
|
|
|
41
42
|
path.isAbsolute(relative)
|
|
42
43
|
)
|
|
43
44
|
break;
|
|
44
|
-
|
|
45
|
+
const contents = await readdir(directory).catch(
|
|
46
|
+
(error: NodeJS.ErrnoException) => {
|
|
47
|
+
if (error.code === "ENOENT") return undefined;
|
|
48
|
+
throw error;
|
|
49
|
+
},
|
|
50
|
+
);
|
|
51
|
+
if (contents?.length !== 0) break;
|
|
45
52
|
await rmdir(directory);
|
|
46
53
|
removedDirectories.push(directory);
|
|
47
54
|
directory = path.dirname(directory);
|
|
@@ -70,12 +77,9 @@ export async function deleteFilesSafely(requests: FileDeleteBatch) {
|
|
|
70
77
|
async () => {
|
|
71
78
|
const deleted: Record<string, unknown> = {};
|
|
72
79
|
for (const { filePath, request } of entries) {
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
throw new Error(
|
|
77
|
-
`Stale file context: expected ${request.expectedSha256}, found ${actual}`,
|
|
78
|
-
);
|
|
80
|
+
const actual = await sha256File(filePath);
|
|
81
|
+
await requireExpectedHash(request.expectedSha256, "file_delete");
|
|
82
|
+
verifyExpectedHash(request.expectedSha256, actual);
|
|
79
83
|
}
|
|
80
84
|
for (const { filePath, importers, request } of entries) {
|
|
81
85
|
await rm(filePath);
|
package/src/runtime/file-read.ts
CHANGED
|
@@ -35,9 +35,7 @@ async function mapConcurrently<Input, Output>(
|
|
|
35
35
|
return output;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
function
|
|
39
|
-
const [start, end] = request.lines ?? FILE_READ_DEFAULT_LINES;
|
|
40
|
-
const maxBytes = request.maxBytes ?? FILE_READ_MAX_BYTES;
|
|
38
|
+
function validateLineRange(start: number, end: number) {
|
|
41
39
|
if (!Number.isInteger(start) || start < 0)
|
|
42
40
|
throw new Error("file_read line start must be a non-negative integer");
|
|
43
41
|
if (!Number.isInteger(end) || end <= start)
|
|
@@ -46,6 +44,9 @@ function validateRequest(request: FileReadRequest) {
|
|
|
46
44
|
throw new Error(
|
|
47
45
|
`file_read line ranges are capped at ${FILE_READ_MAX_LINES} lines`,
|
|
48
46
|
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function validateMaxBytes(maxBytes: number) {
|
|
49
50
|
if (
|
|
50
51
|
!Number.isInteger(maxBytes) ||
|
|
51
52
|
maxBytes < 1 ||
|
|
@@ -54,76 +55,109 @@ function validateRequest(request: FileReadRequest) {
|
|
|
54
55
|
throw new Error(
|
|
55
56
|
`file_read maxBytes must be between 1 and ${FILE_READ_MAX_BYTES}`,
|
|
56
57
|
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function validateRequest(request: FileReadRequest) {
|
|
61
|
+
const [start, end] = request.lines ?? FILE_READ_DEFAULT_LINES;
|
|
62
|
+
const maxBytes = request.maxBytes ?? FILE_READ_MAX_BYTES;
|
|
63
|
+
validateLineRange(start, end);
|
|
64
|
+
validateMaxBytes(maxBytes);
|
|
57
65
|
return { lines: [start, end] as [number, number], maxBytes };
|
|
58
66
|
}
|
|
59
67
|
|
|
68
|
+
class LineRangeCollector {
|
|
69
|
+
private line = 0;
|
|
70
|
+
private moreInChunk = false;
|
|
71
|
+
private readonly selected: Buffer[] = [];
|
|
72
|
+
private selectedBytes = 0;
|
|
73
|
+
private truncated = false;
|
|
74
|
+
|
|
75
|
+
constructor(
|
|
76
|
+
private readonly lines: [number, number],
|
|
77
|
+
private readonly maxBytes: number,
|
|
78
|
+
) {}
|
|
79
|
+
|
|
80
|
+
consume(chunk: Buffer) {
|
|
81
|
+
let offset = 0;
|
|
82
|
+
while (offset < chunk.length) {
|
|
83
|
+
const newline = chunk.indexOf(10, offset);
|
|
84
|
+
const segmentEnd = newline < 0 ? chunk.length : newline + 1;
|
|
85
|
+
if (this.lineSelected() && this.append(chunk, offset, segmentEnd)) {
|
|
86
|
+
this.moreInChunk = true;
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
offset = segmentEnd;
|
|
90
|
+
if (newline < 0) return false;
|
|
91
|
+
this.line += 1;
|
|
92
|
+
if (this.line >= this.lines[1]) {
|
|
93
|
+
this.moreInChunk = offset < chunk.length;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
result(fileSize: number, bytesRead: number) {
|
|
101
|
+
const contentBuffer = Buffer.concat(this.selected, this.selectedBytes);
|
|
102
|
+
const returnedLineCount = bufferLineCount(contentBuffer);
|
|
103
|
+
return {
|
|
104
|
+
content: contentBuffer.toString("utf8"),
|
|
105
|
+
hasMore: this.truncated || this.moreInChunk || bytesRead < fileSize,
|
|
106
|
+
lines: {
|
|
107
|
+
requested: this.lines,
|
|
108
|
+
returned: [this.lines[0], this.lines[0] + returnedLineCount],
|
|
109
|
+
},
|
|
110
|
+
truncated: this.truncated,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private lineSelected() {
|
|
115
|
+
return this.line >= this.lines[0] && this.line < this.lines[1];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private append(chunk: Buffer, offset: number, segmentEnd: number) {
|
|
119
|
+
const remaining = this.maxBytes - this.selectedBytes;
|
|
120
|
+
const length = segmentEnd - offset;
|
|
121
|
+
if (length > remaining) {
|
|
122
|
+
if (remaining > 0) {
|
|
123
|
+
this.selected.push(chunk.subarray(offset, offset + remaining));
|
|
124
|
+
this.selectedBytes += remaining;
|
|
125
|
+
}
|
|
126
|
+
this.truncated = true;
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
if (length > 0) {
|
|
130
|
+
this.selected.push(chunk.subarray(offset, segmentEnd));
|
|
131
|
+
this.selectedBytes += length;
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function bufferLineCount(content: Buffer) {
|
|
138
|
+
let count = 0;
|
|
139
|
+
for (const byte of content) if (byte === 10) count += 1;
|
|
140
|
+
if (content.length > 0 && content.at(-1) !== 10) count += 1;
|
|
141
|
+
return count;
|
|
142
|
+
}
|
|
143
|
+
|
|
60
144
|
async function readLineRange(
|
|
61
145
|
filePath: string,
|
|
62
146
|
fileSize: number,
|
|
63
147
|
lines: [number, number],
|
|
64
148
|
maxBytes: number,
|
|
65
149
|
) {
|
|
66
|
-
const
|
|
67
|
-
const selected: Buffer[] = [];
|
|
68
|
-
let selectedBytes = 0;
|
|
69
|
-
let line = 0;
|
|
70
|
-
let moreInChunk = false;
|
|
71
|
-
let truncated = false;
|
|
150
|
+
const collector = new LineRangeCollector(lines, maxBytes);
|
|
72
151
|
const stream = createReadStream(filePath);
|
|
73
|
-
|
|
74
152
|
try {
|
|
75
|
-
|
|
153
|
+
for await (const raw of stream) {
|
|
76
154
|
const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
77
|
-
|
|
78
|
-
while (offset < chunk.length) {
|
|
79
|
-
const newline = chunk.indexOf(10, offset);
|
|
80
|
-
const segmentEnd = newline < 0 ? chunk.length : newline + 1;
|
|
81
|
-
if (line >= start && line < end) {
|
|
82
|
-
const remaining = maxBytes - selectedBytes;
|
|
83
|
-
const length = segmentEnd - offset;
|
|
84
|
-
if (length > remaining) {
|
|
85
|
-
if (remaining > 0) {
|
|
86
|
-
selected.push(chunk.subarray(offset, offset + remaining));
|
|
87
|
-
selectedBytes += remaining;
|
|
88
|
-
}
|
|
89
|
-
truncated = true;
|
|
90
|
-
moreInChunk = true;
|
|
91
|
-
break outer;
|
|
92
|
-
}
|
|
93
|
-
if (length > 0) {
|
|
94
|
-
selected.push(chunk.subarray(offset, segmentEnd));
|
|
95
|
-
selectedBytes += length;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
offset = segmentEnd;
|
|
99
|
-
if (newline >= 0) {
|
|
100
|
-
line += 1;
|
|
101
|
-
if (line >= end) {
|
|
102
|
-
moreInChunk = offset < chunk.length;
|
|
103
|
-
break outer;
|
|
104
|
-
}
|
|
105
|
-
} else break;
|
|
106
|
-
}
|
|
155
|
+
if (collector.consume(chunk)) break;
|
|
107
156
|
}
|
|
108
157
|
} finally {
|
|
109
158
|
stream.destroy();
|
|
110
159
|
}
|
|
111
|
-
|
|
112
|
-
const contentBuffer = Buffer.concat(selected, selectedBytes);
|
|
113
|
-
let returnedLineCount = 0;
|
|
114
|
-
for (const byte of contentBuffer) if (byte === 10) returnedLineCount += 1;
|
|
115
|
-
if (contentBuffer.length > 0 && contentBuffer.at(-1) !== 10)
|
|
116
|
-
returnedLineCount += 1;
|
|
117
|
-
|
|
118
|
-
return {
|
|
119
|
-
content: contentBuffer.toString("utf8"),
|
|
120
|
-
hasMore: truncated || moreInChunk || stream.bytesRead < fileSize,
|
|
121
|
-
lines: {
|
|
122
|
-
requested: lines,
|
|
123
|
-
returned: [start, start + returnedLineCount],
|
|
124
|
-
},
|
|
125
|
-
truncated,
|
|
126
|
-
};
|
|
160
|
+
return collector.result(fileSize, stream.bytesRead);
|
|
127
161
|
}
|
|
128
162
|
|
|
129
163
|
async function hashFileSafely(filePath: string) {
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { link, lstat, unlink } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { sha256File } from "./hash";
|
|
6
|
+
import { withFileLocks } from "./locks";
|
|
7
|
+
import { resolveWritablePath, rootForPath } from "./paths";
|
|
8
|
+
import { requireExpectedHash, verifyExpectedHash } from "./policy";
|
|
9
|
+
|
|
10
|
+
export interface FileRenameRequest {
|
|
11
|
+
destination: string;
|
|
12
|
+
expectedSha256?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type FileRenameBatch = Record<string, FileRenameRequest>;
|
|
16
|
+
|
|
17
|
+
type RenameEntry = {
|
|
18
|
+
destinationPath: string;
|
|
19
|
+
filePath: string;
|
|
20
|
+
request: FileRenameRequest;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
async function verifyLinkCapability(entries: RenameEntry[]) {
|
|
24
|
+
for (const entry of entries) {
|
|
25
|
+
const probe = join(
|
|
26
|
+
dirname(entry.destinationPath),
|
|
27
|
+
`.ast-mcp-rename-probe-${randomUUID()}`,
|
|
28
|
+
);
|
|
29
|
+
let linkError: unknown;
|
|
30
|
+
let created = false;
|
|
31
|
+
try {
|
|
32
|
+
await link(entry.filePath, probe);
|
|
33
|
+
created = true;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
linkError = error;
|
|
36
|
+
}
|
|
37
|
+
if (created) {
|
|
38
|
+
try {
|
|
39
|
+
await unlink(probe);
|
|
40
|
+
} catch (cleanupError) {
|
|
41
|
+
throw new AggregateError(
|
|
42
|
+
[cleanupError],
|
|
43
|
+
`file_rename probe cleanup failed; residual probe: ${probe}`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (linkError)
|
|
48
|
+
throw new Error(
|
|
49
|
+
`file_rename requires hard-link support between source and destination filesystems: ${String(linkError)}`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function moveFilesWithRollback(entries: RenameEntry[]) {
|
|
55
|
+
const files: Record<string, unknown> = {};
|
|
56
|
+
const moved: RenameEntry[] = [];
|
|
57
|
+
try {
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
await link(entry.filePath, entry.destinationPath);
|
|
60
|
+
try {
|
|
61
|
+
await unlink(entry.filePath);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
await unlink(entry.destinationPath).catch((cleanupError) => {
|
|
64
|
+
throw new AggregateError(
|
|
65
|
+
[error, cleanupError],
|
|
66
|
+
"file_rename failed while cleaning up the current destination",
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
moved.push(entry);
|
|
72
|
+
files[entry.filePath] = {
|
|
73
|
+
destinationPath: entry.destinationPath,
|
|
74
|
+
renamed: true,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
} catch (error) {
|
|
78
|
+
const rollbackErrors: unknown[] = [];
|
|
79
|
+
for (const entry of [...moved].reverse()) {
|
|
80
|
+
try {
|
|
81
|
+
await link(entry.destinationPath, entry.filePath);
|
|
82
|
+
await unlink(entry.destinationPath);
|
|
83
|
+
} catch (rollbackError) {
|
|
84
|
+
rollbackErrors.push(rollbackError);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (rollbackErrors.length > 0)
|
|
88
|
+
throw new AggregateError(
|
|
89
|
+
[error, ...rollbackErrors],
|
|
90
|
+
"file_rename failed and rollback was incomplete",
|
|
91
|
+
);
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
return files;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function renameFilesSafely(requests: FileRenameBatch) {
|
|
98
|
+
const requestedDestinations = Object.values(requests).map(
|
|
99
|
+
({ destination }) => destination,
|
|
100
|
+
);
|
|
101
|
+
if (new Set(requestedDestinations).size !== requestedDestinations.length)
|
|
102
|
+
throw new Error("file_rename destinations must be unique");
|
|
103
|
+
|
|
104
|
+
const entries = await Promise.all(
|
|
105
|
+
Object.entries(requests).map(async ([inputPath, request]) => {
|
|
106
|
+
const filePath = await resolveWritablePath(inputPath);
|
|
107
|
+
const destinationPath = await resolveWritablePath(request.destination);
|
|
108
|
+
const metadata = await lstat(filePath);
|
|
109
|
+
if (!metadata.isFile())
|
|
110
|
+
throw new Error(`file_rename accepts files only: ${inputPath}`);
|
|
111
|
+
if (filePath === destinationPath)
|
|
112
|
+
throw new Error(
|
|
113
|
+
`file_rename source and destination must differ: ${inputPath}`,
|
|
114
|
+
);
|
|
115
|
+
if (
|
|
116
|
+
(await rootForPath(filePath)) !== (await rootForPath(destinationPath))
|
|
117
|
+
)
|
|
118
|
+
throw new Error(
|
|
119
|
+
`file_rename source and destination must share a root: ${inputPath}`,
|
|
120
|
+
);
|
|
121
|
+
if (await lstat(destinationPath).catch(() => undefined))
|
|
122
|
+
throw new Error(
|
|
123
|
+
`file_rename destination already exists: ${request.destination}`,
|
|
124
|
+
);
|
|
125
|
+
return { destinationPath, filePath, request } satisfies RenameEntry;
|
|
126
|
+
}),
|
|
127
|
+
);
|
|
128
|
+
const sources = new Set<string>();
|
|
129
|
+
const destinations = new Set<string>();
|
|
130
|
+
for (const { destinationPath, filePath } of entries) {
|
|
131
|
+
if (sources.has(filePath))
|
|
132
|
+
throw new Error(`file_rename source appears more than once: ${filePath}`);
|
|
133
|
+
sources.add(filePath);
|
|
134
|
+
if (destinations.has(destinationPath))
|
|
135
|
+
throw new Error(
|
|
136
|
+
`file_rename destination appears more than once: ${destinationPath}`,
|
|
137
|
+
);
|
|
138
|
+
destinations.add(destinationPath);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
files: await withFileLocks(
|
|
143
|
+
entries.flatMap(({ destinationPath, filePath }) => [
|
|
144
|
+
filePath,
|
|
145
|
+
destinationPath,
|
|
146
|
+
]),
|
|
147
|
+
async () => {
|
|
148
|
+
await verifyLinkCapability(entries);
|
|
149
|
+
for (const { filePath, request } of entries) {
|
|
150
|
+
const actual = await sha256File(filePath);
|
|
151
|
+
await requireExpectedHash(request.expectedSha256, "file_rename");
|
|
152
|
+
verifyExpectedHash(request.expectedSha256, actual);
|
|
153
|
+
}
|
|
154
|
+
return moveFilesWithRollback(entries);
|
|
155
|
+
},
|
|
156
|
+
),
|
|
157
|
+
};
|
|
158
|
+
}
|
package/src/runtime/format.ts
CHANGED
|
@@ -1,30 +1,67 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
chmod,
|
|
4
|
-
lstat,
|
|
5
|
-
readFile,
|
|
6
|
-
rename,
|
|
7
|
-
unlink,
|
|
8
|
-
writeFile,
|
|
9
|
-
} from "node:fs/promises";
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
10
2
|
import path from "node:path";
|
|
3
|
+
import { currentConfig, type ResolvedConfig } from "../config";
|
|
4
|
+
import { replaceFileAtomically } from "./atomic";
|
|
5
|
+
import { configuredDprintBinary } from "./dependencies";
|
|
11
6
|
import { runCommandInput } from "./process-input";
|
|
12
7
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
);
|
|
16
|
-
|
|
17
|
-
|
|
8
|
+
const dprint = configuredDprintBinary;
|
|
9
|
+
function formatterPath(config: ResolvedConfig, filePath: string) {
|
|
10
|
+
const relative = path.relative(config.projectRoot, filePath);
|
|
11
|
+
return relative && !relative.startsWith("..") && !path.isAbsolute(relative)
|
|
12
|
+
? relative.split(path.sep).join("/")
|
|
13
|
+
: path.basename(filePath);
|
|
14
|
+
}
|
|
15
|
+
function matchesFormatter(
|
|
16
|
+
config: ResolvedConfig,
|
|
17
|
+
filePath: string,
|
|
18
|
+
formatter: ResolvedConfig["formatting"]["formatters"][number],
|
|
19
|
+
) {
|
|
20
|
+
const extension = path.extname(filePath).toLowerCase();
|
|
21
|
+
if (formatter.extensions.includes(extension)) return true;
|
|
22
|
+
const relative = formatterPath(config, filePath);
|
|
23
|
+
return formatter.globs.some((glob) => new Bun.Glob(glob).match(relative));
|
|
24
|
+
}
|
|
25
|
+
function formatterArgs(
|
|
26
|
+
config: ResolvedConfig,
|
|
27
|
+
filePath: string,
|
|
28
|
+
args: string[],
|
|
29
|
+
) {
|
|
30
|
+
return args.map((argument) =>
|
|
31
|
+
argument
|
|
32
|
+
.replaceAll("{file}", filePath)
|
|
33
|
+
.replaceAll("{project_root}", config.projectRoot),
|
|
34
|
+
);
|
|
35
|
+
}
|
|
18
36
|
|
|
19
37
|
export async function formatContent(
|
|
20
38
|
filePath: string,
|
|
21
39
|
content: string,
|
|
22
40
|
): Promise<string> {
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
41
|
+
const config = await currentConfig();
|
|
42
|
+
if (!config.formatting.enabled) return content;
|
|
43
|
+
const formatter = config.formatting.formatters.find((candidate) =>
|
|
44
|
+
matchesFormatter(config, filePath, candidate),
|
|
27
45
|
);
|
|
46
|
+
const result = formatter
|
|
47
|
+
? await runCommandInput(
|
|
48
|
+
formatter.command,
|
|
49
|
+
formatterArgs(config, filePath, formatter.args),
|
|
50
|
+
content,
|
|
51
|
+
{ cwd: config.projectRoot, timeoutMs: formatter.timeoutMs },
|
|
52
|
+
)
|
|
53
|
+
: await runCommandInput(
|
|
54
|
+
await dprint(),
|
|
55
|
+
[
|
|
56
|
+
"fmt",
|
|
57
|
+
"--config",
|
|
58
|
+
config.formatting.dprintConfig,
|
|
59
|
+
"--stdin",
|
|
60
|
+
formatterPath(config, filePath),
|
|
61
|
+
],
|
|
62
|
+
content,
|
|
63
|
+
{ cwd: config.projectRoot },
|
|
64
|
+
);
|
|
28
65
|
return result.stdout;
|
|
29
66
|
}
|
|
30
67
|
|
|
@@ -33,25 +70,11 @@ export async function assertFormattable(filePath: string): Promise<void> {
|
|
|
33
70
|
}
|
|
34
71
|
|
|
35
72
|
export async function formatFileAtomically(filePath: string): Promise<void> {
|
|
73
|
+
if (!(await currentConfig()).formatting.enabled) return;
|
|
36
74
|
const metadata = await lstat(filePath);
|
|
37
75
|
const formatted = await formatContent(
|
|
38
76
|
filePath,
|
|
39
77
|
await readFile(filePath, "utf8"),
|
|
40
78
|
);
|
|
41
|
-
|
|
42
|
-
const temporary = path.join(
|
|
43
|
-
path.dirname(filePath),
|
|
44
|
-
`${path.basename(filePath, extension)}.ast-mcp-format-${randomUUID()}${extension}`,
|
|
45
|
-
);
|
|
46
|
-
try {
|
|
47
|
-
await writeFile(temporary, formatted, {
|
|
48
|
-
encoding: "utf8",
|
|
49
|
-
flag: "wx",
|
|
50
|
-
mode: metadata.mode,
|
|
51
|
-
});
|
|
52
|
-
await chmod(temporary, metadata.mode);
|
|
53
|
-
await rename(temporary, filePath);
|
|
54
|
-
} finally {
|
|
55
|
-
await unlink(temporary).catch(() => undefined);
|
|
56
|
-
}
|
|
79
|
+
await replaceFileAtomically(filePath, formatted, metadata.mode);
|
|
57
80
|
}
|