bambu-printer-mcp 1.1.82 → 1.1.83
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 +39 -0
- package/dist/cad/contracts.d.ts +424 -0
- package/dist/cad/contracts.js +288 -0
- package/dist/cad/process.d.ts +32 -0
- package/dist/cad/process.js +151 -0
- package/dist/cad/refusal.d.ts +15 -0
- package/dist/cad/refusal.js +30 -0
- package/dist/cad/serial.d.ts +6 -0
- package/dist/cad/serial.js +114 -0
- package/dist/cad/storage.d.ts +34 -0
- package/dist/cad/storage.js +201 -0
- package/dist/cad-engine.d.ts +43 -0
- package/dist/cad-engine.js +546 -0
- package/dist/counterpart/info.js +2 -0
- package/dist/counterpart/remote.js +7 -0
- package/dist/counterpart/schemas.d.ts +33 -0
- package/dist/counterpart/schemas.js +1 -0
- package/dist/design-guidance.js +2 -6
- package/dist/index.js +44 -3
- package/dist/tool-annotations.js +4 -0
- package/package.json +1 -1
- package/src/cad/contracts.ts +317 -0
- package/src/cad/geometry.py +157 -0
- package/src/cad/process.ts +216 -0
- package/src/cad/refusal.ts +34 -0
- package/src/cad/requirements.in +9 -0
- package/src/cad/requirements.lock +69 -0
- package/src/cad/serial.ts +126 -0
- package/src/cad/storage.ts +232 -0
- package/src/cad/worker.py +161 -0
- package/src/cad-engine.ts +794 -0
- package/src/counterpart/info.ts +2 -0
- package/src/counterpart/remote.ts +6 -0
- package/src/counterpart/schemas.ts +2 -0
- package/src/design-guidance.ts +2 -0
- package/src/index.ts +39 -3
- package/src/tool-annotations.ts +4 -0
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
import { performance } from "node:perf_hooks";
|
|
8
|
+
import { CadRefusal, cadFailure } from "./cad/refusal.js";
|
|
9
|
+
import { withCadLock } from "./cad/serial.js";
|
|
10
|
+
import {
|
|
11
|
+
measureEnvironment,
|
|
12
|
+
snapshotInputs,
|
|
13
|
+
storageInfo,
|
|
14
|
+
type CadStorage,
|
|
15
|
+
} from "./cad/storage.js";
|
|
16
|
+
import { cadSandbox, defaultCadSystem, type CadSystem } from "./cad/process.js";
|
|
17
|
+
|
|
18
|
+
const ASSETS = fileURLToPath(new URL("../src/cad/", import.meta.url));
|
|
19
|
+
const BUILD123D = "0.13.0";
|
|
20
|
+
const PACKAGE_NAME = createRequire(import.meta.url)("../package.json")
|
|
21
|
+
.name as string;
|
|
22
|
+
export type CadArguments = Record<string, unknown>;
|
|
23
|
+
export interface CadOptions {
|
|
24
|
+
dataDir?: string;
|
|
25
|
+
outputRoots: string[];
|
|
26
|
+
system?: CadSystem;
|
|
27
|
+
}
|
|
28
|
+
export interface CadStatus {
|
|
29
|
+
configured: boolean;
|
|
30
|
+
ready: boolean;
|
|
31
|
+
python: string | null;
|
|
32
|
+
build123d: string;
|
|
33
|
+
platform: string;
|
|
34
|
+
storage: CadStorage;
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
export class CadEngine {
|
|
38
|
+
private readonly system: CadSystem;
|
|
39
|
+
readonly dataDir: string;
|
|
40
|
+
constructor(private readonly options: CadOptions) {
|
|
41
|
+
this.system = options.system ?? defaultCadSystem;
|
|
42
|
+
this.dataDir = path.resolve(
|
|
43
|
+
options.dataDir ??
|
|
44
|
+
process.env.CAD_DATA_DIR ??
|
|
45
|
+
path.join(
|
|
46
|
+
process.platform === "darwin"
|
|
47
|
+
? path.join(os.homedir(), "Library", "Application Support")
|
|
48
|
+
: (process.env.XDG_DATA_HOME ??
|
|
49
|
+
path.join(os.homedir(), ".local", "share")),
|
|
50
|
+
PACKAGE_NAME,
|
|
51
|
+
"cad",
|
|
52
|
+
),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
async status(): Promise<CadStatus> {
|
|
56
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
57
|
+
const configured = await fs.stat(python).then(
|
|
58
|
+
(s) => s.isFile(),
|
|
59
|
+
() => false,
|
|
60
|
+
);
|
|
61
|
+
let ready = false;
|
|
62
|
+
let sizeMarker:
|
|
63
|
+
{ installed_bytes?: unknown; measured_at?: unknown } | undefined;
|
|
64
|
+
try {
|
|
65
|
+
const marker = JSON.parse(
|
|
66
|
+
await fs.readFile(path.join(this.dataDir, "ready.json"), "utf8"),
|
|
67
|
+
);
|
|
68
|
+
sizeMarker = marker.storage;
|
|
69
|
+
ready =
|
|
70
|
+
configured &&
|
|
71
|
+
marker.build123d === BUILD123D &&
|
|
72
|
+
marker.platform === this.system.platform &&
|
|
73
|
+
marker.fingerprint === (await this.fingerprint()) &&
|
|
74
|
+
marker.dataDevice === (await fs.stat(this.dataDir)).dev;
|
|
75
|
+
} catch {
|
|
76
|
+
/* setup not verified */
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
configured,
|
|
80
|
+
ready,
|
|
81
|
+
python: configured ? python : null,
|
|
82
|
+
build123d: BUILD123D,
|
|
83
|
+
platform: this.system.platform,
|
|
84
|
+
storage: storageInfo(
|
|
85
|
+
sizeMarker,
|
|
86
|
+
configured ||
|
|
87
|
+
(
|
|
88
|
+
await Promise.all(
|
|
89
|
+
["runtime", "python", "cache"].map((name) =>
|
|
90
|
+
fs.stat(path.join(this.dataDir, name)).then(
|
|
91
|
+
() => true,
|
|
92
|
+
() => false,
|
|
93
|
+
),
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
).some(Boolean),
|
|
97
|
+
),
|
|
98
|
+
...(!ready
|
|
99
|
+
? {
|
|
100
|
+
error:
|
|
101
|
+
"Run cad_setup with install: true to install and verify the confined CAD runtime.",
|
|
102
|
+
}
|
|
103
|
+
: {}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
async failure(error: unknown, tool: string) {
|
|
107
|
+
const storage = await this.status().then(
|
|
108
|
+
(status) => status.storage,
|
|
109
|
+
() => storageInfo(undefined, true),
|
|
110
|
+
);
|
|
111
|
+
return { ...cadFailure(error, tool), storage };
|
|
112
|
+
}
|
|
113
|
+
private async allowedDirectory(value: unknown): Promise<string> {
|
|
114
|
+
if (typeof value !== "string" || !value)
|
|
115
|
+
throw new Error(
|
|
116
|
+
"output_dir must be an existing allowed output directory.",
|
|
117
|
+
);
|
|
118
|
+
const dir = await fs.realpath(path.resolve(value)).catch(() => {
|
|
119
|
+
throw new Error(
|
|
120
|
+
"output_dir must be an existing allowed output directory.",
|
|
121
|
+
);
|
|
122
|
+
});
|
|
123
|
+
for (const root of this.options.outputRoots) {
|
|
124
|
+
const real = await fs.realpath(path.resolve(root)).catch(() => undefined);
|
|
125
|
+
if (
|
|
126
|
+
real &&
|
|
127
|
+
(dir === real || dir.startsWith(real + path.sep)) &&
|
|
128
|
+
(await fs.stat(dir)).isDirectory()
|
|
129
|
+
)
|
|
130
|
+
return dir;
|
|
131
|
+
}
|
|
132
|
+
throw new Error(
|
|
133
|
+
"output_dir is outside the allowed output directories (TEMP_DIR or trusted CAD_OUTPUT_DIRS).",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
private environment(home: string): NodeJS.ProcessEnv {
|
|
137
|
+
return {
|
|
138
|
+
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
139
|
+
HOME: home,
|
|
140
|
+
TMPDIR: path.join(home, "tmp"),
|
|
141
|
+
TMP: path.join(home, "tmp"),
|
|
142
|
+
TEMP: path.join(home, "tmp"),
|
|
143
|
+
LANG: "en_US.UTF-8",
|
|
144
|
+
PYTHONDONTWRITEBYTECODE: "1",
|
|
145
|
+
MPLCONFIGDIR: path.join(home, "tmp", "mpl"),
|
|
146
|
+
OPENBLAS_NUM_THREADS: "1",
|
|
147
|
+
OMP_NUM_THREADS: "1",
|
|
148
|
+
VECLIB_MAXIMUM_THREADS: "1",
|
|
149
|
+
UV_CACHE_DIR: path.join(this.dataDir, "cache"),
|
|
150
|
+
UV_PYTHON_INSTALL_DIR: path.join(this.dataDir, "python"),
|
|
151
|
+
UV_NO_CONFIG: "1",
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
private async exclusive<T>(
|
|
155
|
+
work: (waitedMs: number) => Promise<T>,
|
|
156
|
+
operation: "setup" | "run" | "fit" = "fit",
|
|
157
|
+
signal?: AbortSignal,
|
|
158
|
+
deadline?: number,
|
|
159
|
+
): Promise<T> {
|
|
160
|
+
return withCadLock(this.dataDir, { operation, signal, deadline }, work);
|
|
161
|
+
}
|
|
162
|
+
private async confined(
|
|
163
|
+
mode: string,
|
|
164
|
+
request: string,
|
|
165
|
+
job: string,
|
|
166
|
+
readonly: string[],
|
|
167
|
+
timeoutMs: number,
|
|
168
|
+
signal?: AbortSignal,
|
|
169
|
+
inputDirectories: string[] = [],
|
|
170
|
+
): Promise<{ stdout: string; stderr?: string }> {
|
|
171
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
172
|
+
const sandbox = await cadSandbox(this.system.platform, {
|
|
173
|
+
data: this.dataDir,
|
|
174
|
+
job,
|
|
175
|
+
assets: ASSETS,
|
|
176
|
+
python,
|
|
177
|
+
readonly,
|
|
178
|
+
inputs: inputDirectories,
|
|
179
|
+
});
|
|
180
|
+
await fs.mkdir(path.join(job, "tmp"), { recursive: true, mode: 0o700 });
|
|
181
|
+
return this.system.run(
|
|
182
|
+
sandbox.command,
|
|
183
|
+
[
|
|
184
|
+
...sandbox.args,
|
|
185
|
+
python,
|
|
186
|
+
"-I",
|
|
187
|
+
"-B",
|
|
188
|
+
path.join(ASSETS, "worker.py"),
|
|
189
|
+
mode,
|
|
190
|
+
request,
|
|
191
|
+
],
|
|
192
|
+
{
|
|
193
|
+
env: this.environment(job),
|
|
194
|
+
cwd: job,
|
|
195
|
+
timeoutMs,
|
|
196
|
+
signal,
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
async setup(
|
|
201
|
+
args: CadArguments,
|
|
202
|
+
signal?: AbortSignal,
|
|
203
|
+
): Promise<Record<string, unknown>> {
|
|
204
|
+
only(args, ["install"]);
|
|
205
|
+
if (args.install !== undefined && typeof args.install !== "boolean")
|
|
206
|
+
throw new Error("install must be a boolean.");
|
|
207
|
+
if (args.install !== true)
|
|
208
|
+
return {
|
|
209
|
+
supported: ["darwin", "linux"].includes(this.system.platform),
|
|
210
|
+
...(await this.status()),
|
|
211
|
+
};
|
|
212
|
+
if (!["darwin", "linux"].includes(this.system.platform))
|
|
213
|
+
throw new CadRefusal(
|
|
214
|
+
"cad-confinement-unavailable",
|
|
215
|
+
`CAD confinement is unavailable on ${this.system.platform}.`,
|
|
216
|
+
);
|
|
217
|
+
return this.exclusive(
|
|
218
|
+
async () => {
|
|
219
|
+
signal?.throwIfAborted();
|
|
220
|
+
const env = this.environment(this.dataDir);
|
|
221
|
+
await this.requireSupportedStorage(env, signal);
|
|
222
|
+
await fs.mkdir(env.TMPDIR!, { recursive: true });
|
|
223
|
+
await fs.unlink(path.join(this.dataDir, "ready.json")).catch(() => {});
|
|
224
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
225
|
+
const opts = { env, cwd: this.dataDir, signal, timeoutMs: 600_000 };
|
|
226
|
+
try {
|
|
227
|
+
if (
|
|
228
|
+
!(await fs.stat(python).then(
|
|
229
|
+
(s) => s.isFile(),
|
|
230
|
+
() => false,
|
|
231
|
+
))
|
|
232
|
+
)
|
|
233
|
+
await this.system.run(
|
|
234
|
+
"uv",
|
|
235
|
+
[
|
|
236
|
+
"venv",
|
|
237
|
+
"--managed-python",
|
|
238
|
+
"--python",
|
|
239
|
+
"3.12",
|
|
240
|
+
"--no-config",
|
|
241
|
+
path.join(this.dataDir, "runtime"),
|
|
242
|
+
],
|
|
243
|
+
opts,
|
|
244
|
+
);
|
|
245
|
+
await this.system.run(
|
|
246
|
+
"uv",
|
|
247
|
+
[
|
|
248
|
+
"pip",
|
|
249
|
+
"sync",
|
|
250
|
+
"--python",
|
|
251
|
+
python,
|
|
252
|
+
"--only-binary",
|
|
253
|
+
":all:",
|
|
254
|
+
"--no-config",
|
|
255
|
+
path.join(ASSETS, "requirements.lock"),
|
|
256
|
+
],
|
|
257
|
+
opts,
|
|
258
|
+
);
|
|
259
|
+
} catch (e) {
|
|
260
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT")
|
|
261
|
+
throw new CadRefusal(
|
|
262
|
+
"cad-uv-missing",
|
|
263
|
+
"uv is not available on the MCP's PATH. Install uv, then run cad_setup again; no model was run.",
|
|
264
|
+
);
|
|
265
|
+
throw e;
|
|
266
|
+
}
|
|
267
|
+
await this.system.run(
|
|
268
|
+
python,
|
|
269
|
+
["-I", "-B", path.join(ASSETS, "worker.py"), "imports"],
|
|
270
|
+
{ ...opts, timeoutMs: 120_000 },
|
|
271
|
+
);
|
|
272
|
+
const job = await fs.mkdtemp(path.join(this.dataDir, "verify-"));
|
|
273
|
+
const request = path.join(job, "request.json");
|
|
274
|
+
await fs.writeFile(
|
|
275
|
+
request,
|
|
276
|
+
JSON.stringify({ output: job, home: os.homedir() }),
|
|
277
|
+
{ mode: 0o600 },
|
|
278
|
+
);
|
|
279
|
+
const result = JSON.parse(
|
|
280
|
+
(
|
|
281
|
+
await this.confined(
|
|
282
|
+
"smoke",
|
|
283
|
+
request,
|
|
284
|
+
job,
|
|
285
|
+
[request],
|
|
286
|
+
180_000,
|
|
287
|
+
signal,
|
|
288
|
+
)
|
|
289
|
+
).stdout,
|
|
290
|
+
);
|
|
291
|
+
if (
|
|
292
|
+
result.build123d !== BUILD123D ||
|
|
293
|
+
!result.watertight ||
|
|
294
|
+
!result.manifold ||
|
|
295
|
+
!result.step_valid ||
|
|
296
|
+
result.solid_count !== 1
|
|
297
|
+
)
|
|
298
|
+
throw new Error("CAD setup's confined STL/STEP round trip failed.");
|
|
299
|
+
const storage = {
|
|
300
|
+
installed_bytes: await measureEnvironment(this.dataDir),
|
|
301
|
+
measured_at: new Date().toISOString(),
|
|
302
|
+
};
|
|
303
|
+
await fs.writeFile(
|
|
304
|
+
path.join(this.dataDir, "ready.json"),
|
|
305
|
+
JSON.stringify({
|
|
306
|
+
build123d: BUILD123D,
|
|
307
|
+
platform: this.system.platform,
|
|
308
|
+
verifiedAt: new Date().toISOString(),
|
|
309
|
+
fingerprint: await this.fingerprint(),
|
|
310
|
+
dataDevice: (await fs.stat(this.dataDir)).dev,
|
|
311
|
+
storage,
|
|
312
|
+
}),
|
|
313
|
+
{ mode: 0o600 },
|
|
314
|
+
);
|
|
315
|
+
return {
|
|
316
|
+
supported: true,
|
|
317
|
+
...(await this.status()),
|
|
318
|
+
installed: true,
|
|
319
|
+
message:
|
|
320
|
+
"CAD is ready; confined import, build, STL and STEP round trip passed. No native files were re-signed.",
|
|
321
|
+
};
|
|
322
|
+
},
|
|
323
|
+
"setup",
|
|
324
|
+
signal,
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
private async fingerprint(): Promise<string> {
|
|
328
|
+
const hash = createHash("sha256");
|
|
329
|
+
for (const file of [
|
|
330
|
+
"requirements.lock",
|
|
331
|
+
"worker.py",
|
|
332
|
+
"geometry.py",
|
|
333
|
+
"process.ts",
|
|
334
|
+
"storage.ts",
|
|
335
|
+
"serial.ts",
|
|
336
|
+
"refusal.ts",
|
|
337
|
+
"contracts.ts",
|
|
338
|
+
])
|
|
339
|
+
hash.update(await fs.readFile(path.join(ASSETS, file)));
|
|
340
|
+
hash.update(
|
|
341
|
+
await fs.readFile(new URL("../src/cad-engine.ts", import.meta.url)),
|
|
342
|
+
);
|
|
343
|
+
for (const file of [
|
|
344
|
+
"process.js",
|
|
345
|
+
"storage.js",
|
|
346
|
+
"serial.js",
|
|
347
|
+
"refusal.js",
|
|
348
|
+
"contracts.js",
|
|
349
|
+
])
|
|
350
|
+
hash.update(await fs.readFile(new URL(`./cad/${file}`, import.meta.url)));
|
|
351
|
+
hash.update(await fs.readFile(new URL("./cad-engine.js", import.meta.url)));
|
|
352
|
+
return hash.digest("hex");
|
|
353
|
+
}
|
|
354
|
+
private async requireSupportedStorage(
|
|
355
|
+
env: NodeJS.ProcessEnv,
|
|
356
|
+
signal?: AbortSignal,
|
|
357
|
+
): Promise<void> {
|
|
358
|
+
if (this.system.platform !== "darwin") return;
|
|
359
|
+
const error = () =>
|
|
360
|
+
new CadRefusal(
|
|
361
|
+
"cad-data-volume-refused",
|
|
362
|
+
"Code-CAD on macOS requires an internal disk with file ownership enabled. External and network data volumes are unsupported after measured native-import stalls. Set CAD_DATA_DIR to an internal folder and rerun cad_setup; nothing was installed by this attempt.",
|
|
363
|
+
);
|
|
364
|
+
try {
|
|
365
|
+
const opts = { env, cwd: this.dataDir, timeoutMs: 10_000, signal };
|
|
366
|
+
const df = await this.system.run("/bin/df", ["-P", this.dataDir], opts);
|
|
367
|
+
const device = df.stdout
|
|
368
|
+
.trim()
|
|
369
|
+
.split(/\r?\n/)
|
|
370
|
+
.at(-1)
|
|
371
|
+
?.trim()
|
|
372
|
+
.split(/\s+/)[0];
|
|
373
|
+
if (!device || !/^\/dev\/disk\d+(?:s\d+)*$/.test(device)) throw error();
|
|
374
|
+
const info = await this.system.run(
|
|
375
|
+
"/usr/sbin/diskutil",
|
|
376
|
+
["info", "-plist", device],
|
|
377
|
+
opts,
|
|
378
|
+
);
|
|
379
|
+
if (
|
|
380
|
+
!/<key>Internal<\/key>\s*<true\s*\/>/.test(info.stdout) ||
|
|
381
|
+
!/<key>GlobalPermissionsEnabled<\/key>\s*<true\s*\/>/.test(info.stdout)
|
|
382
|
+
)
|
|
383
|
+
throw error();
|
|
384
|
+
} catch (e) {
|
|
385
|
+
if (signal?.aborted) throw e;
|
|
386
|
+
throw error();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
private async inputFile(value: unknown, extension: string): Promise<string> {
|
|
390
|
+
if (
|
|
391
|
+
typeof value !== "string" ||
|
|
392
|
+
path.extname(value).toLowerCase() !== extension
|
|
393
|
+
)
|
|
394
|
+
throw new Error(`Expected an allowed ${extension} file.`);
|
|
395
|
+
const file = await fs.realpath(path.resolve(value));
|
|
396
|
+
await this.allowedDirectory(path.dirname(file));
|
|
397
|
+
const st = await fs.stat(file);
|
|
398
|
+
if (!st.isFile() || st.size > 64 * 1024 * 1024)
|
|
399
|
+
throw new Error(
|
|
400
|
+
"CAD input must be a regular file no larger than 64 MiB.",
|
|
401
|
+
);
|
|
402
|
+
return file;
|
|
403
|
+
}
|
|
404
|
+
async run(
|
|
405
|
+
args: CadArguments,
|
|
406
|
+
signal?: AbortSignal,
|
|
407
|
+
): Promise<Record<string, unknown>> {
|
|
408
|
+
const started = performance.now();
|
|
409
|
+
only(args, [
|
|
410
|
+
"script",
|
|
411
|
+
"script_path",
|
|
412
|
+
"parameters",
|
|
413
|
+
"output_dir",
|
|
414
|
+
"name",
|
|
415
|
+
"timeout_ms",
|
|
416
|
+
"inputs",
|
|
417
|
+
"mode",
|
|
418
|
+
"final",
|
|
419
|
+
]);
|
|
420
|
+
const root = await this.allowedDirectory(args.output_dir);
|
|
421
|
+
const name = plainName(args.name);
|
|
422
|
+
const timeout = milliseconds(args.timeout_ms),
|
|
423
|
+
deadline = started + timeout;
|
|
424
|
+
if (args.final !== undefined && typeof args.final !== "boolean")
|
|
425
|
+
throw new Error("final must be a boolean.");
|
|
426
|
+
if (root.split(path.sep).includes(".cad-inputs"))
|
|
427
|
+
throw new Error(
|
|
428
|
+
"output_dir cannot be inside the reserved CAD input cache.",
|
|
429
|
+
);
|
|
430
|
+
const remaining = () => {
|
|
431
|
+
const value = Math.floor(deadline - performance.now());
|
|
432
|
+
if (value <= 0) throw new Error("CAD run timed out.");
|
|
433
|
+
return value;
|
|
434
|
+
};
|
|
435
|
+
if ((args.script === undefined) === (args.script_path === undefined))
|
|
436
|
+
throw new Error("Supply exactly one of script or script_path.");
|
|
437
|
+
const source =
|
|
438
|
+
args.script === undefined
|
|
439
|
+
? await fs.readFile(
|
|
440
|
+
await this.inputFile(args.script_path, ".py"),
|
|
441
|
+
"utf8",
|
|
442
|
+
)
|
|
443
|
+
: args.script;
|
|
444
|
+
if (
|
|
445
|
+
typeof source !== "string" ||
|
|
446
|
+
!source.trim() ||
|
|
447
|
+
Buffer.byteLength(source) > 256 * 1024
|
|
448
|
+
)
|
|
449
|
+
throw new Error(
|
|
450
|
+
"script must be nonempty Python text no larger than 256 KiB.",
|
|
451
|
+
);
|
|
452
|
+
const overrides = args.parameters ?? {};
|
|
453
|
+
if (!overrides || typeof overrides !== "object" || Array.isArray(overrides))
|
|
454
|
+
throw new Error("parameters must be a JSON object.");
|
|
455
|
+
const mode = args.mode ?? "solid";
|
|
456
|
+
if (mode !== "solid" && mode !== "mesh")
|
|
457
|
+
throw new Error("mode must be solid or mesh.");
|
|
458
|
+
let requestedInputs: unknown;
|
|
459
|
+
if (args.inputs !== undefined) {
|
|
460
|
+
if (!Array.isArray(args.inputs) || args.inputs.length > 16)
|
|
461
|
+
throw new Error(
|
|
462
|
+
"inputs must be an array of at most 16 {name, path} files.",
|
|
463
|
+
);
|
|
464
|
+
const named: Record<string, string> = Object.create(null);
|
|
465
|
+
for (const item of args.inputs) {
|
|
466
|
+
if (
|
|
467
|
+
!item ||
|
|
468
|
+
typeof item !== "object" ||
|
|
469
|
+
Array.isArray(item) ||
|
|
470
|
+
Object.keys(item).some((k) => k !== "name" && k !== "path") ||
|
|
471
|
+
typeof item.name !== "string" ||
|
|
472
|
+
typeof item.path !== "string" ||
|
|
473
|
+
Object.prototype.hasOwnProperty.call(named, item.name)
|
|
474
|
+
)
|
|
475
|
+
throw new Error(
|
|
476
|
+
"Each input needs a unique name and an allowed path.",
|
|
477
|
+
);
|
|
478
|
+
named[item.name] = item.path;
|
|
479
|
+
}
|
|
480
|
+
requestedInputs = named;
|
|
481
|
+
}
|
|
482
|
+
if (requestedInputs === undefined && typeof args.script_path === "string") {
|
|
483
|
+
const file = args.script_path.replace(/\.py$/i, ".inputs.json");
|
|
484
|
+
try {
|
|
485
|
+
requestedInputs = JSON.parse(
|
|
486
|
+
await fs.readFile(await this.inputFile(file, ".json"), "utf8"),
|
|
487
|
+
);
|
|
488
|
+
} catch (e) {
|
|
489
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
const inputs: Record<string, string> = {};
|
|
493
|
+
if (requestedInputs !== undefined) {
|
|
494
|
+
if (
|
|
495
|
+
!requestedInputs ||
|
|
496
|
+
typeof requestedInputs !== "object" ||
|
|
497
|
+
Array.isArray(requestedInputs) ||
|
|
498
|
+
Object.keys(requestedInputs).length > 16
|
|
499
|
+
)
|
|
500
|
+
throw new Error("inputs must name at most 16 local files.");
|
|
501
|
+
for (const [alias, value] of Object.entries(requestedInputs)) {
|
|
502
|
+
if (
|
|
503
|
+
!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(alias) ||
|
|
504
|
+
typeof value !== "string"
|
|
505
|
+
)
|
|
506
|
+
throw new Error(
|
|
507
|
+
"Each input needs a plain alias and an allowed file path.",
|
|
508
|
+
);
|
|
509
|
+
const ext = path.extname(value).toLowerCase();
|
|
510
|
+
inputs[alias] = await this.inputFile(value, ext);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
return this.exclusive(
|
|
514
|
+
async (queueWaitMs) => {
|
|
515
|
+
const status = await this.status();
|
|
516
|
+
if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
|
|
517
|
+
const job = await fs.mkdtemp(path.join(root, `cad-${name}-`));
|
|
518
|
+
await fs.chmod(job, 0o700);
|
|
519
|
+
const script = path.join(job, `${name}.py`),
|
|
520
|
+
parameters = path.join(job, `${name}.parameters.json`),
|
|
521
|
+
request = path.join(job, ".cad-request.json");
|
|
522
|
+
const resultManifest = path.join(job, "cad-result.json");
|
|
523
|
+
const lineage = createHash("sha256").update(source).digest("hex");
|
|
524
|
+
await fs.writeFile(script, source, { mode: 0o600 });
|
|
525
|
+
let previous: unknown = {};
|
|
526
|
+
if (args.script_path !== undefined) {
|
|
527
|
+
try {
|
|
528
|
+
previous = JSON.parse(
|
|
529
|
+
await fs.readFile(
|
|
530
|
+
await this.inputFile(
|
|
531
|
+
String(args.script_path).replace(
|
|
532
|
+
/\.py$/i,
|
|
533
|
+
".parameters.json",
|
|
534
|
+
),
|
|
535
|
+
".json",
|
|
536
|
+
),
|
|
537
|
+
"utf8",
|
|
538
|
+
),
|
|
539
|
+
);
|
|
540
|
+
} catch (e) {
|
|
541
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
await fs.writeFile(
|
|
545
|
+
parameters,
|
|
546
|
+
JSON.stringify({ ...(previous as object), ...overrides }),
|
|
547
|
+
{ mode: 0o600 },
|
|
548
|
+
);
|
|
549
|
+
await atomicJson(resultManifest, {
|
|
550
|
+
status: "pending",
|
|
551
|
+
final: args.final === true,
|
|
552
|
+
lineage_id: lineage,
|
|
553
|
+
});
|
|
554
|
+
try {
|
|
555
|
+
remaining();
|
|
556
|
+
signal?.throwIfAborted();
|
|
557
|
+
const snapshot = await snapshotInputs(root, inputs, signal, {
|
|
558
|
+
directory: path.join(this.dataDir, "input-index"),
|
|
559
|
+
authorize: (directory) => this.allowedDirectory(directory),
|
|
560
|
+
});
|
|
561
|
+
const snapshots = snapshot.inputs,
|
|
562
|
+
manifest = path.join(job, `${name}.inputs.json`);
|
|
563
|
+
await fs.writeFile(manifest, JSON.stringify(snapshots, null, 2), {
|
|
564
|
+
mode: 0o600,
|
|
565
|
+
});
|
|
566
|
+
const base = {
|
|
567
|
+
output: job,
|
|
568
|
+
name,
|
|
569
|
+
script,
|
|
570
|
+
parameters,
|
|
571
|
+
mode,
|
|
572
|
+
inputs: snapshots,
|
|
573
|
+
};
|
|
574
|
+
await fs.writeFile(request, JSON.stringify(base), { mode: 0o600 });
|
|
575
|
+
const protectedFiles = [
|
|
576
|
+
script,
|
|
577
|
+
parameters,
|
|
578
|
+
request,
|
|
579
|
+
manifest,
|
|
580
|
+
resultManifest,
|
|
581
|
+
...(snapshot.directory ? [snapshot.directory] : []),
|
|
582
|
+
];
|
|
583
|
+
const readableInputs = snapshot.directory ? [snapshot.directory] : [];
|
|
584
|
+
const effective = JSON.parse(
|
|
585
|
+
(
|
|
586
|
+
await this.system.run(
|
|
587
|
+
status.python!,
|
|
588
|
+
[
|
|
589
|
+
"-I",
|
|
590
|
+
"-B",
|
|
591
|
+
path.join(ASSETS, "worker.py"),
|
|
592
|
+
"parameters",
|
|
593
|
+
request,
|
|
594
|
+
],
|
|
595
|
+
{
|
|
596
|
+
env: this.environment(job),
|
|
597
|
+
cwd: job,
|
|
598
|
+
timeoutMs: Math.min(10_000, remaining()),
|
|
599
|
+
signal,
|
|
600
|
+
},
|
|
601
|
+
)
|
|
602
|
+
).stdout,
|
|
603
|
+
);
|
|
604
|
+
await fs.writeFile(parameters, JSON.stringify(effective, null, 2), {
|
|
605
|
+
mode: 0o600,
|
|
606
|
+
});
|
|
607
|
+
const t = performance.now();
|
|
608
|
+
const built = await this.confined(
|
|
609
|
+
"build",
|
|
610
|
+
request,
|
|
611
|
+
job,
|
|
612
|
+
protectedFiles,
|
|
613
|
+
remaining(),
|
|
614
|
+
signal,
|
|
615
|
+
readableInputs,
|
|
616
|
+
);
|
|
617
|
+
await fs.writeFile(
|
|
618
|
+
path.join(job, "build.log"),
|
|
619
|
+
(built.stdout + "\n" + (built.stderr ?? "")).slice(-200_000),
|
|
620
|
+
{ mode: 0o600, flag: "wx" },
|
|
621
|
+
);
|
|
622
|
+
for (const ext of mode === "solid" ? ["stl", "step"] : ["stl"]) {
|
|
623
|
+
const st = await fs.lstat(path.join(job, `${name}.${ext}`));
|
|
624
|
+
if (!st.isFile() || st.size === 0 || st.size > 64 * 1024 * 1024)
|
|
625
|
+
throw new Error(
|
|
626
|
+
`CAD ${ext} export is missing, unsafe or too large.`,
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
const checked = JSON.parse(
|
|
630
|
+
(
|
|
631
|
+
await this.confined(
|
|
632
|
+
"inspect",
|
|
633
|
+
request,
|
|
634
|
+
job,
|
|
635
|
+
protectedFiles,
|
|
636
|
+
remaining(),
|
|
637
|
+
signal,
|
|
638
|
+
readableInputs,
|
|
639
|
+
)
|
|
640
|
+
).stdout,
|
|
641
|
+
);
|
|
642
|
+
const result = {
|
|
643
|
+
...checked,
|
|
644
|
+
status: "completed",
|
|
645
|
+
final: args.final === true,
|
|
646
|
+
completed_at: new Date().toISOString(),
|
|
647
|
+
lineage_id: lineage,
|
|
648
|
+
result_manifest: resultManifest,
|
|
649
|
+
script,
|
|
650
|
+
parameters,
|
|
651
|
+
inputs: snapshots,
|
|
652
|
+
input_manifest: manifest,
|
|
653
|
+
input_hashes: snapshot.hashes,
|
|
654
|
+
snapshot_bytes_added: snapshot.added,
|
|
655
|
+
snapshot_bytes_reused: snapshot.reused,
|
|
656
|
+
queue_wait_ms: queueWaitMs,
|
|
657
|
+
stl: path.join(job, `${name}.stl`),
|
|
658
|
+
step: mode === "solid" ? path.join(job, `${name}.step`) : null,
|
|
659
|
+
...(mode === "mesh"
|
|
660
|
+
? {
|
|
661
|
+
step_unavailable:
|
|
662
|
+
"Mesh mode has no parametric B-rep; STEP export is unavailable.",
|
|
663
|
+
}
|
|
664
|
+
: {}),
|
|
665
|
+
seconds: (performance.now() - t) / 1000,
|
|
666
|
+
};
|
|
667
|
+
await atomicJson(resultManifest, result);
|
|
668
|
+
return result;
|
|
669
|
+
} catch (e) {
|
|
670
|
+
await atomicJson(resultManifest, {
|
|
671
|
+
status: "failed",
|
|
672
|
+
final: false,
|
|
673
|
+
final_requested: args.final === true,
|
|
674
|
+
lineage_id: lineage,
|
|
675
|
+
message: e instanceof Error ? e.message : String(e),
|
|
676
|
+
script,
|
|
677
|
+
parameters,
|
|
678
|
+
}).catch(() => {});
|
|
679
|
+
const message = `${e instanceof Error ? e.message : String(e)} Checkpoint retained: ${script} and ${parameters}.`;
|
|
680
|
+
if (e instanceof CadRefusal) throw new CadRefusal(e.code, message);
|
|
681
|
+
throw new Error(message);
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
"run",
|
|
685
|
+
signal,
|
|
686
|
+
deadline,
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
async checkFit(
|
|
690
|
+
args: CadArguments,
|
|
691
|
+
signal?: AbortSignal,
|
|
692
|
+
): Promise<Record<string, unknown>> {
|
|
693
|
+
only(args, [
|
|
694
|
+
"model",
|
|
695
|
+
"reference",
|
|
696
|
+
"transform",
|
|
697
|
+
"clearance_mm",
|
|
698
|
+
"timeout_ms",
|
|
699
|
+
]);
|
|
700
|
+
const model = await this.inputFile(args.model, ".stl"),
|
|
701
|
+
reference = await this.inputFile(args.reference, ".stl");
|
|
702
|
+
const clearance = args.clearance_mm ?? 0;
|
|
703
|
+
if (
|
|
704
|
+
typeof clearance !== "number" ||
|
|
705
|
+
!Number.isFinite(clearance) ||
|
|
706
|
+
clearance < 0 ||
|
|
707
|
+
clearance > 100
|
|
708
|
+
)
|
|
709
|
+
throw new Error("clearance_mm must be finite, between 0 and 100.");
|
|
710
|
+
return this.exclusive(
|
|
711
|
+
async () => {
|
|
712
|
+
const status = await this.status();
|
|
713
|
+
if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
|
|
714
|
+
const job = await fs.mkdtemp(path.join(this.dataDir, "fit-"));
|
|
715
|
+
try {
|
|
716
|
+
await fs.copyFile(model, path.join(job, "model.stl"));
|
|
717
|
+
await fs.copyFile(reference, path.join(job, "reference.stl"));
|
|
718
|
+
const request = path.join(job, "request.json");
|
|
719
|
+
await fs.writeFile(
|
|
720
|
+
request,
|
|
721
|
+
JSON.stringify({
|
|
722
|
+
model: path.join(job, "model.stl"),
|
|
723
|
+
reference: path.join(job, "reference.stl"),
|
|
724
|
+
transform: args.transform ?? {},
|
|
725
|
+
clearance_mm: clearance,
|
|
726
|
+
}),
|
|
727
|
+
);
|
|
728
|
+
return JSON.parse(
|
|
729
|
+
(
|
|
730
|
+
await this.confined(
|
|
731
|
+
"fit",
|
|
732
|
+
request,
|
|
733
|
+
job,
|
|
734
|
+
[
|
|
735
|
+
request,
|
|
736
|
+
path.join(job, "model.stl"),
|
|
737
|
+
path.join(job, "reference.stl"),
|
|
738
|
+
],
|
|
739
|
+
milliseconds(args.timeout_ms),
|
|
740
|
+
signal,
|
|
741
|
+
)
|
|
742
|
+
).stdout,
|
|
743
|
+
);
|
|
744
|
+
} finally {
|
|
745
|
+
await fs.rm(job, { recursive: true, force: true });
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
"fit",
|
|
749
|
+
signal,
|
|
750
|
+
);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
function only(args: CadArguments, keys: string[]): void {
|
|
754
|
+
if (Object.keys(args).some((k) => !keys.includes(k)))
|
|
755
|
+
throw new Error(`CAD accepts only ${keys.join(", ")}.`);
|
|
756
|
+
}
|
|
757
|
+
function plainName(name: unknown): string {
|
|
758
|
+
if (
|
|
759
|
+
typeof name !== "string" ||
|
|
760
|
+
!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(name) ||
|
|
761
|
+
name.includes("..")
|
|
762
|
+
)
|
|
763
|
+
throw new Error(
|
|
764
|
+
"name must be a plain filename stem (up to 64 characters).",
|
|
765
|
+
);
|
|
766
|
+
return name;
|
|
767
|
+
}
|
|
768
|
+
function milliseconds(value: unknown): number {
|
|
769
|
+
if (value === undefined) return 120_000;
|
|
770
|
+
if (
|
|
771
|
+
typeof value !== "number" ||
|
|
772
|
+
!Number.isInteger(value) ||
|
|
773
|
+
value < 100 ||
|
|
774
|
+
value > 900_000
|
|
775
|
+
)
|
|
776
|
+
throw new Error("timeout_ms must be an integer from 100 to 900000.");
|
|
777
|
+
return value;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
async function atomicJson(file: string, value: unknown): Promise<void> {
|
|
781
|
+
const temporary = path.join(
|
|
782
|
+
path.dirname(file),
|
|
783
|
+
`.cad-result-${randomUUID()}.tmp`,
|
|
784
|
+
);
|
|
785
|
+
try {
|
|
786
|
+
await fs.writeFile(temporary, JSON.stringify(value, null, 2), {
|
|
787
|
+
flag: "wx",
|
|
788
|
+
mode: 0o600,
|
|
789
|
+
});
|
|
790
|
+
await fs.rename(temporary, file);
|
|
791
|
+
} finally {
|
|
792
|
+
await fs.unlink(temporary).catch(() => {});
|
|
793
|
+
}
|
|
794
|
+
}
|