@mwillbanks/ast-mcp 0.1.3 → 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 +59 -20
- package/dist/ast-mcp.js +232 -130
- package/dist/ast-mcp.js.map +107 -27
- package/package.json +2 -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 +70 -95
- 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 +579 -242
- 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 +48 -29
- 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 +9 -8
- 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
|
@@ -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
|
}
|
package/src/runtime/paths.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import { lstat, realpath } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { currentConfig } from "../config";
|
|
3
4
|
|
|
4
|
-
function configuredRoots(): string[] {
|
|
5
|
-
return (
|
|
6
|
-
process.env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean) ?? [
|
|
7
|
-
process.cwd(),
|
|
8
|
-
]
|
|
9
|
-
).map((item) => path.resolve(item));
|
|
5
|
+
async function configuredRoots(): Promise<string[]> {
|
|
6
|
+
return (await currentConfig()).workspace.roots;
|
|
10
7
|
}
|
|
11
8
|
function within(root: string, target: string): boolean {
|
|
12
9
|
const relative = path.relative(root, target);
|
|
@@ -17,16 +14,23 @@ function within(root: string, target: string): boolean {
|
|
|
17
14
|
}
|
|
18
15
|
|
|
19
16
|
async function allowedRoots(): Promise<string[]> {
|
|
20
|
-
const
|
|
17
|
+
const config = await currentConfig();
|
|
21
18
|
const roots = await Promise.all(
|
|
22
|
-
configuredRoots().map(async (root) =>
|
|
19
|
+
(await configuredRoots()).map(async (root) =>
|
|
20
|
+
realpath(root).catch(() => root),
|
|
21
|
+
),
|
|
22
|
+
);
|
|
23
|
+
const trustedRoots = await Promise.all(
|
|
24
|
+
config.trustedRoots.map(async (root) => realpath(root).catch(() => root)),
|
|
23
25
|
);
|
|
24
26
|
if (
|
|
25
|
-
|
|
26
|
-
roots.some(
|
|
27
|
+
!config.safety.allowExternalRoots &&
|
|
28
|
+
roots.some(
|
|
29
|
+
(root) => !trustedRoots.some((trustedRoot) => within(trustedRoot, root)),
|
|
30
|
+
)
|
|
27
31
|
)
|
|
28
32
|
throw new Error(
|
|
29
|
-
"
|
|
33
|
+
"Configured workspace roots contain a root outside the trusted project boundary; set safety.allow_external_roots=true or AST_MCP_ALLOW_EXTERNAL_ROOTS=1 to opt in",
|
|
30
34
|
);
|
|
31
35
|
return roots;
|
|
32
36
|
}
|
|
@@ -43,6 +47,7 @@ export async function rootForPath(filePath: string): Promise<string> {
|
|
|
43
47
|
return root;
|
|
44
48
|
}
|
|
45
49
|
export async function resolveWritablePath(filePath: string): Promise<string> {
|
|
50
|
+
const config = await currentConfig();
|
|
46
51
|
const roots = await allowedRoots();
|
|
47
52
|
const absolute = path.isAbsolute(filePath)
|
|
48
53
|
? filePath
|
|
@@ -63,11 +68,20 @@ export async function resolveWritablePath(filePath: string): Promise<string> {
|
|
|
63
68
|
}
|
|
64
69
|
const resolved = path.join(existing, ...missing, path.basename(absolute));
|
|
65
70
|
if (!roots.some((root) => within(root, resolved)))
|
|
66
|
-
throw new Error(
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Path is outside AST_MCP_ROOTS/configured workspace roots: ${filePath}`,
|
|
73
|
+
);
|
|
74
|
+
const metadata = await lstat(resolved).catch(() => undefined);
|
|
75
|
+
if (!metadata?.isSymbolicLink()) return resolved;
|
|
76
|
+
if (!config.safety.followSymlinks)
|
|
77
|
+
throw new Error(`Symbolic-link targets are not permitted: ${filePath}`);
|
|
78
|
+
const target = await realpath(resolved);
|
|
79
|
+
if (!roots.some((root) => within(root, target)))
|
|
80
|
+
throw new Error(
|
|
81
|
+
`Symbolic-link target is outside configured workspace roots: ${filePath}`,
|
|
82
|
+
);
|
|
83
|
+
return target;
|
|
70
84
|
}
|
|
71
|
-
export function rootsForDisplay(): string[] {
|
|
85
|
+
export async function rootsForDisplay(): Promise<string[]> {
|
|
72
86
|
return configuredRoots();
|
|
73
87
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { currentConfig } from "../config";
|
|
2
|
+
|
|
3
|
+
export async function requireExpectedHash(
|
|
4
|
+
expectedSha256: string | undefined,
|
|
5
|
+
operation: string,
|
|
6
|
+
): Promise<void> {
|
|
7
|
+
if (!expectedSha256 && (await currentConfig()).safety.requireHash)
|
|
8
|
+
throw new Error(
|
|
9
|
+
`${operation} requires expectedSha256 while safety.require_hash is enabled`,
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function verifyExpectedHash(
|
|
14
|
+
expectedSha256: string | undefined,
|
|
15
|
+
actualSha256: string,
|
|
16
|
+
): void {
|
|
17
|
+
if (expectedSha256 && expectedSha256 !== actualSha256)
|
|
18
|
+
throw new Error(
|
|
19
|
+
`Stale file context: expected ${expectedSha256}, found ${actualSha256}`,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
@@ -3,21 +3,31 @@ export function runCommandInput(
|
|
|
3
3
|
command: string,
|
|
4
4
|
args: string[],
|
|
5
5
|
input: string,
|
|
6
|
+
options: { cwd?: string; timeoutMs?: number } = {},
|
|
6
7
|
): Promise<{ stdout: string; stderr: string }> {
|
|
8
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
7
9
|
return new Promise((resolve, reject) => {
|
|
8
10
|
const child = execFile(
|
|
9
11
|
command,
|
|
10
12
|
args,
|
|
11
|
-
{
|
|
13
|
+
{
|
|
14
|
+
cwd: options.cwd,
|
|
15
|
+
encoding: "utf8",
|
|
16
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
17
|
+
timeout: timeoutMs,
|
|
18
|
+
},
|
|
12
19
|
(error, stdout, stderr) => {
|
|
13
|
-
if (error)
|
|
20
|
+
if (error) {
|
|
21
|
+
const detail = (stderr || stdout || error.message).trim();
|
|
14
22
|
reject(
|
|
15
23
|
new Error(
|
|
16
|
-
|
|
24
|
+
error.killed
|
|
25
|
+
? `${command} timed out after ${timeoutMs}ms${detail ? `: ${detail}` : ""}`
|
|
26
|
+
: `${command} failed: ${detail}`,
|
|
17
27
|
{ cause: error },
|
|
18
28
|
),
|
|
19
29
|
);
|
|
20
|
-
else resolve({ stderr, stdout });
|
|
30
|
+
} else resolve({ stderr, stdout });
|
|
21
31
|
},
|
|
22
32
|
);
|
|
23
33
|
child.stdin?.end(input);
|