bambu-printer-mcp 1.1.82 → 1.1.84
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 +41 -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/refusal.d.ts +11 -4
- package/dist/refusal.js +14 -4
- package/dist/slicer/slicer-launch.d.ts +34 -0
- package/dist/slicer/slicer-launch.js +145 -0
- package/dist/stl/stl-manipulator.js +55 -33
- 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/refusal.ts +15 -4
- package/src/slicer/slicer-launch.ts +149 -0
- package/src/stl/stl-manipulator.ts +17 -4
- package/src/tool-annotations.ts +4 -0
|
@@ -0,0 +1,546 @@
|
|
|
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 { measureEnvironment, snapshotInputs, storageInfo, } from "./cad/storage.js";
|
|
11
|
+
import { cadSandbox, defaultCadSystem } from "./cad/process.js";
|
|
12
|
+
const ASSETS = fileURLToPath(new URL("../src/cad/", import.meta.url));
|
|
13
|
+
const BUILD123D = "0.13.0";
|
|
14
|
+
const PACKAGE_NAME = createRequire(import.meta.url)("../package.json")
|
|
15
|
+
.name;
|
|
16
|
+
export class CadEngine {
|
|
17
|
+
constructor(options) {
|
|
18
|
+
this.options = options;
|
|
19
|
+
this.system = options.system ?? defaultCadSystem;
|
|
20
|
+
this.dataDir = path.resolve(options.dataDir ??
|
|
21
|
+
process.env.CAD_DATA_DIR ??
|
|
22
|
+
path.join(process.platform === "darwin"
|
|
23
|
+
? path.join(os.homedir(), "Library", "Application Support")
|
|
24
|
+
: (process.env.XDG_DATA_HOME ??
|
|
25
|
+
path.join(os.homedir(), ".local", "share")), PACKAGE_NAME, "cad"));
|
|
26
|
+
}
|
|
27
|
+
async status() {
|
|
28
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
29
|
+
const configured = await fs.stat(python).then((s) => s.isFile(), () => false);
|
|
30
|
+
let ready = false;
|
|
31
|
+
let sizeMarker;
|
|
32
|
+
try {
|
|
33
|
+
const marker = JSON.parse(await fs.readFile(path.join(this.dataDir, "ready.json"), "utf8"));
|
|
34
|
+
sizeMarker = marker.storage;
|
|
35
|
+
ready =
|
|
36
|
+
configured &&
|
|
37
|
+
marker.build123d === BUILD123D &&
|
|
38
|
+
marker.platform === this.system.platform &&
|
|
39
|
+
marker.fingerprint === (await this.fingerprint()) &&
|
|
40
|
+
marker.dataDevice === (await fs.stat(this.dataDir)).dev;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
/* setup not verified */
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
configured,
|
|
47
|
+
ready,
|
|
48
|
+
python: configured ? python : null,
|
|
49
|
+
build123d: BUILD123D,
|
|
50
|
+
platform: this.system.platform,
|
|
51
|
+
storage: storageInfo(sizeMarker, configured ||
|
|
52
|
+
(await Promise.all(["runtime", "python", "cache"].map((name) => fs.stat(path.join(this.dataDir, name)).then(() => true, () => false)))).some(Boolean)),
|
|
53
|
+
...(!ready
|
|
54
|
+
? {
|
|
55
|
+
error: "Run cad_setup with install: true to install and verify the confined CAD runtime.",
|
|
56
|
+
}
|
|
57
|
+
: {}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async failure(error, tool) {
|
|
61
|
+
const storage = await this.status().then((status) => status.storage, () => storageInfo(undefined, true));
|
|
62
|
+
return { ...cadFailure(error, tool), storage };
|
|
63
|
+
}
|
|
64
|
+
async allowedDirectory(value) {
|
|
65
|
+
if (typeof value !== "string" || !value)
|
|
66
|
+
throw new Error("output_dir must be an existing allowed output directory.");
|
|
67
|
+
const dir = await fs.realpath(path.resolve(value)).catch(() => {
|
|
68
|
+
throw new Error("output_dir must be an existing allowed output directory.");
|
|
69
|
+
});
|
|
70
|
+
for (const root of this.options.outputRoots) {
|
|
71
|
+
const real = await fs.realpath(path.resolve(root)).catch(() => undefined);
|
|
72
|
+
if (real &&
|
|
73
|
+
(dir === real || dir.startsWith(real + path.sep)) &&
|
|
74
|
+
(await fs.stat(dir)).isDirectory())
|
|
75
|
+
return dir;
|
|
76
|
+
}
|
|
77
|
+
throw new Error("output_dir is outside the allowed output directories (TEMP_DIR or trusted CAD_OUTPUT_DIRS).");
|
|
78
|
+
}
|
|
79
|
+
environment(home) {
|
|
80
|
+
return {
|
|
81
|
+
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
82
|
+
HOME: home,
|
|
83
|
+
TMPDIR: path.join(home, "tmp"),
|
|
84
|
+
TMP: path.join(home, "tmp"),
|
|
85
|
+
TEMP: path.join(home, "tmp"),
|
|
86
|
+
LANG: "en_US.UTF-8",
|
|
87
|
+
PYTHONDONTWRITEBYTECODE: "1",
|
|
88
|
+
MPLCONFIGDIR: path.join(home, "tmp", "mpl"),
|
|
89
|
+
OPENBLAS_NUM_THREADS: "1",
|
|
90
|
+
OMP_NUM_THREADS: "1",
|
|
91
|
+
VECLIB_MAXIMUM_THREADS: "1",
|
|
92
|
+
UV_CACHE_DIR: path.join(this.dataDir, "cache"),
|
|
93
|
+
UV_PYTHON_INSTALL_DIR: path.join(this.dataDir, "python"),
|
|
94
|
+
UV_NO_CONFIG: "1",
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async exclusive(work, operation = "fit", signal, deadline) {
|
|
98
|
+
return withCadLock(this.dataDir, { operation, signal, deadline }, work);
|
|
99
|
+
}
|
|
100
|
+
async confined(mode, request, job, readonly, timeoutMs, signal, inputDirectories = []) {
|
|
101
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
102
|
+
const sandbox = await cadSandbox(this.system.platform, {
|
|
103
|
+
data: this.dataDir,
|
|
104
|
+
job,
|
|
105
|
+
assets: ASSETS,
|
|
106
|
+
python,
|
|
107
|
+
readonly,
|
|
108
|
+
inputs: inputDirectories,
|
|
109
|
+
});
|
|
110
|
+
await fs.mkdir(path.join(job, "tmp"), { recursive: true, mode: 0o700 });
|
|
111
|
+
return this.system.run(sandbox.command, [
|
|
112
|
+
...sandbox.args,
|
|
113
|
+
python,
|
|
114
|
+
"-I",
|
|
115
|
+
"-B",
|
|
116
|
+
path.join(ASSETS, "worker.py"),
|
|
117
|
+
mode,
|
|
118
|
+
request,
|
|
119
|
+
], {
|
|
120
|
+
env: this.environment(job),
|
|
121
|
+
cwd: job,
|
|
122
|
+
timeoutMs,
|
|
123
|
+
signal,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
async setup(args, signal) {
|
|
127
|
+
only(args, ["install"]);
|
|
128
|
+
if (args.install !== undefined && typeof args.install !== "boolean")
|
|
129
|
+
throw new Error("install must be a boolean.");
|
|
130
|
+
if (args.install !== true)
|
|
131
|
+
return {
|
|
132
|
+
supported: ["darwin", "linux"].includes(this.system.platform),
|
|
133
|
+
...(await this.status()),
|
|
134
|
+
};
|
|
135
|
+
if (!["darwin", "linux"].includes(this.system.platform))
|
|
136
|
+
throw new CadRefusal("cad-confinement-unavailable", `CAD confinement is unavailable on ${this.system.platform}.`);
|
|
137
|
+
return this.exclusive(async () => {
|
|
138
|
+
signal?.throwIfAborted();
|
|
139
|
+
const env = this.environment(this.dataDir);
|
|
140
|
+
await this.requireSupportedStorage(env, signal);
|
|
141
|
+
await fs.mkdir(env.TMPDIR, { recursive: true });
|
|
142
|
+
await fs.unlink(path.join(this.dataDir, "ready.json")).catch(() => { });
|
|
143
|
+
const python = path.join(this.dataDir, "runtime", "bin", "python");
|
|
144
|
+
const opts = { env, cwd: this.dataDir, signal, timeoutMs: 600000 };
|
|
145
|
+
try {
|
|
146
|
+
if (!(await fs.stat(python).then((s) => s.isFile(), () => false)))
|
|
147
|
+
await this.system.run("uv", [
|
|
148
|
+
"venv",
|
|
149
|
+
"--managed-python",
|
|
150
|
+
"--python",
|
|
151
|
+
"3.12",
|
|
152
|
+
"--no-config",
|
|
153
|
+
path.join(this.dataDir, "runtime"),
|
|
154
|
+
], opts);
|
|
155
|
+
await this.system.run("uv", [
|
|
156
|
+
"pip",
|
|
157
|
+
"sync",
|
|
158
|
+
"--python",
|
|
159
|
+
python,
|
|
160
|
+
"--only-binary",
|
|
161
|
+
":all:",
|
|
162
|
+
"--no-config",
|
|
163
|
+
path.join(ASSETS, "requirements.lock"),
|
|
164
|
+
], opts);
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
if (e.code === "ENOENT")
|
|
168
|
+
throw new CadRefusal("cad-uv-missing", "uv is not available on the MCP's PATH. Install uv, then run cad_setup again; no model was run.");
|
|
169
|
+
throw e;
|
|
170
|
+
}
|
|
171
|
+
await this.system.run(python, ["-I", "-B", path.join(ASSETS, "worker.py"), "imports"], { ...opts, timeoutMs: 120000 });
|
|
172
|
+
const job = await fs.mkdtemp(path.join(this.dataDir, "verify-"));
|
|
173
|
+
const request = path.join(job, "request.json");
|
|
174
|
+
await fs.writeFile(request, JSON.stringify({ output: job, home: os.homedir() }), { mode: 0o600 });
|
|
175
|
+
const result = JSON.parse((await this.confined("smoke", request, job, [request], 180000, signal)).stdout);
|
|
176
|
+
if (result.build123d !== BUILD123D ||
|
|
177
|
+
!result.watertight ||
|
|
178
|
+
!result.manifold ||
|
|
179
|
+
!result.step_valid ||
|
|
180
|
+
result.solid_count !== 1)
|
|
181
|
+
throw new Error("CAD setup's confined STL/STEP round trip failed.");
|
|
182
|
+
const storage = {
|
|
183
|
+
installed_bytes: await measureEnvironment(this.dataDir),
|
|
184
|
+
measured_at: new Date().toISOString(),
|
|
185
|
+
};
|
|
186
|
+
await fs.writeFile(path.join(this.dataDir, "ready.json"), JSON.stringify({
|
|
187
|
+
build123d: BUILD123D,
|
|
188
|
+
platform: this.system.platform,
|
|
189
|
+
verifiedAt: new Date().toISOString(),
|
|
190
|
+
fingerprint: await this.fingerprint(),
|
|
191
|
+
dataDevice: (await fs.stat(this.dataDir)).dev,
|
|
192
|
+
storage,
|
|
193
|
+
}), { mode: 0o600 });
|
|
194
|
+
return {
|
|
195
|
+
supported: true,
|
|
196
|
+
...(await this.status()),
|
|
197
|
+
installed: true,
|
|
198
|
+
message: "CAD is ready; confined import, build, STL and STEP round trip passed. No native files were re-signed.",
|
|
199
|
+
};
|
|
200
|
+
}, "setup", signal);
|
|
201
|
+
}
|
|
202
|
+
async fingerprint() {
|
|
203
|
+
const hash = createHash("sha256");
|
|
204
|
+
for (const file of [
|
|
205
|
+
"requirements.lock",
|
|
206
|
+
"worker.py",
|
|
207
|
+
"geometry.py",
|
|
208
|
+
"process.ts",
|
|
209
|
+
"storage.ts",
|
|
210
|
+
"serial.ts",
|
|
211
|
+
"refusal.ts",
|
|
212
|
+
"contracts.ts",
|
|
213
|
+
])
|
|
214
|
+
hash.update(await fs.readFile(path.join(ASSETS, file)));
|
|
215
|
+
hash.update(await fs.readFile(new URL("../src/cad-engine.ts", import.meta.url)));
|
|
216
|
+
for (const file of [
|
|
217
|
+
"process.js",
|
|
218
|
+
"storage.js",
|
|
219
|
+
"serial.js",
|
|
220
|
+
"refusal.js",
|
|
221
|
+
"contracts.js",
|
|
222
|
+
])
|
|
223
|
+
hash.update(await fs.readFile(new URL(`./cad/${file}`, import.meta.url)));
|
|
224
|
+
hash.update(await fs.readFile(new URL("./cad-engine.js", import.meta.url)));
|
|
225
|
+
return hash.digest("hex");
|
|
226
|
+
}
|
|
227
|
+
async requireSupportedStorage(env, signal) {
|
|
228
|
+
if (this.system.platform !== "darwin")
|
|
229
|
+
return;
|
|
230
|
+
const error = () => new CadRefusal("cad-data-volume-refused", "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.");
|
|
231
|
+
try {
|
|
232
|
+
const opts = { env, cwd: this.dataDir, timeoutMs: 10000, signal };
|
|
233
|
+
const df = await this.system.run("/bin/df", ["-P", this.dataDir], opts);
|
|
234
|
+
const device = df.stdout
|
|
235
|
+
.trim()
|
|
236
|
+
.split(/\r?\n/)
|
|
237
|
+
.at(-1)
|
|
238
|
+
?.trim()
|
|
239
|
+
.split(/\s+/)[0];
|
|
240
|
+
if (!device || !/^\/dev\/disk\d+(?:s\d+)*$/.test(device))
|
|
241
|
+
throw error();
|
|
242
|
+
const info = await this.system.run("/usr/sbin/diskutil", ["info", "-plist", device], opts);
|
|
243
|
+
if (!/<key>Internal<\/key>\s*<true\s*\/>/.test(info.stdout) ||
|
|
244
|
+
!/<key>GlobalPermissionsEnabled<\/key>\s*<true\s*\/>/.test(info.stdout))
|
|
245
|
+
throw error();
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
if (signal?.aborted)
|
|
249
|
+
throw e;
|
|
250
|
+
throw error();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async inputFile(value, extension) {
|
|
254
|
+
if (typeof value !== "string" ||
|
|
255
|
+
path.extname(value).toLowerCase() !== extension)
|
|
256
|
+
throw new Error(`Expected an allowed ${extension} file.`);
|
|
257
|
+
const file = await fs.realpath(path.resolve(value));
|
|
258
|
+
await this.allowedDirectory(path.dirname(file));
|
|
259
|
+
const st = await fs.stat(file);
|
|
260
|
+
if (!st.isFile() || st.size > 64 * 1024 * 1024)
|
|
261
|
+
throw new Error("CAD input must be a regular file no larger than 64 MiB.");
|
|
262
|
+
return file;
|
|
263
|
+
}
|
|
264
|
+
async run(args, signal) {
|
|
265
|
+
const started = performance.now();
|
|
266
|
+
only(args, [
|
|
267
|
+
"script",
|
|
268
|
+
"script_path",
|
|
269
|
+
"parameters",
|
|
270
|
+
"output_dir",
|
|
271
|
+
"name",
|
|
272
|
+
"timeout_ms",
|
|
273
|
+
"inputs",
|
|
274
|
+
"mode",
|
|
275
|
+
"final",
|
|
276
|
+
]);
|
|
277
|
+
const root = await this.allowedDirectory(args.output_dir);
|
|
278
|
+
const name = plainName(args.name);
|
|
279
|
+
const timeout = milliseconds(args.timeout_ms), deadline = started + timeout;
|
|
280
|
+
if (args.final !== undefined && typeof args.final !== "boolean")
|
|
281
|
+
throw new Error("final must be a boolean.");
|
|
282
|
+
if (root.split(path.sep).includes(".cad-inputs"))
|
|
283
|
+
throw new Error("output_dir cannot be inside the reserved CAD input cache.");
|
|
284
|
+
const remaining = () => {
|
|
285
|
+
const value = Math.floor(deadline - performance.now());
|
|
286
|
+
if (value <= 0)
|
|
287
|
+
throw new Error("CAD run timed out.");
|
|
288
|
+
return value;
|
|
289
|
+
};
|
|
290
|
+
if ((args.script === undefined) === (args.script_path === undefined))
|
|
291
|
+
throw new Error("Supply exactly one of script or script_path.");
|
|
292
|
+
const source = args.script === undefined
|
|
293
|
+
? await fs.readFile(await this.inputFile(args.script_path, ".py"), "utf8")
|
|
294
|
+
: args.script;
|
|
295
|
+
if (typeof source !== "string" ||
|
|
296
|
+
!source.trim() ||
|
|
297
|
+
Buffer.byteLength(source) > 256 * 1024)
|
|
298
|
+
throw new Error("script must be nonempty Python text no larger than 256 KiB.");
|
|
299
|
+
const overrides = args.parameters ?? {};
|
|
300
|
+
if (!overrides || typeof overrides !== "object" || Array.isArray(overrides))
|
|
301
|
+
throw new Error("parameters must be a JSON object.");
|
|
302
|
+
const mode = args.mode ?? "solid";
|
|
303
|
+
if (mode !== "solid" && mode !== "mesh")
|
|
304
|
+
throw new Error("mode must be solid or mesh.");
|
|
305
|
+
let requestedInputs;
|
|
306
|
+
if (args.inputs !== undefined) {
|
|
307
|
+
if (!Array.isArray(args.inputs) || args.inputs.length > 16)
|
|
308
|
+
throw new Error("inputs must be an array of at most 16 {name, path} files.");
|
|
309
|
+
const named = Object.create(null);
|
|
310
|
+
for (const item of args.inputs) {
|
|
311
|
+
if (!item ||
|
|
312
|
+
typeof item !== "object" ||
|
|
313
|
+
Array.isArray(item) ||
|
|
314
|
+
Object.keys(item).some((k) => k !== "name" && k !== "path") ||
|
|
315
|
+
typeof item.name !== "string" ||
|
|
316
|
+
typeof item.path !== "string" ||
|
|
317
|
+
Object.prototype.hasOwnProperty.call(named, item.name))
|
|
318
|
+
throw new Error("Each input needs a unique name and an allowed path.");
|
|
319
|
+
named[item.name] = item.path;
|
|
320
|
+
}
|
|
321
|
+
requestedInputs = named;
|
|
322
|
+
}
|
|
323
|
+
if (requestedInputs === undefined && typeof args.script_path === "string") {
|
|
324
|
+
const file = args.script_path.replace(/\.py$/i, ".inputs.json");
|
|
325
|
+
try {
|
|
326
|
+
requestedInputs = JSON.parse(await fs.readFile(await this.inputFile(file, ".json"), "utf8"));
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
if (e.code !== "ENOENT")
|
|
330
|
+
throw e;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const inputs = {};
|
|
334
|
+
if (requestedInputs !== undefined) {
|
|
335
|
+
if (!requestedInputs ||
|
|
336
|
+
typeof requestedInputs !== "object" ||
|
|
337
|
+
Array.isArray(requestedInputs) ||
|
|
338
|
+
Object.keys(requestedInputs).length > 16)
|
|
339
|
+
throw new Error("inputs must name at most 16 local files.");
|
|
340
|
+
for (const [alias, value] of Object.entries(requestedInputs)) {
|
|
341
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(alias) ||
|
|
342
|
+
typeof value !== "string")
|
|
343
|
+
throw new Error("Each input needs a plain alias and an allowed file path.");
|
|
344
|
+
const ext = path.extname(value).toLowerCase();
|
|
345
|
+
inputs[alias] = await this.inputFile(value, ext);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return this.exclusive(async (queueWaitMs) => {
|
|
349
|
+
const status = await this.status();
|
|
350
|
+
if (!status.ready)
|
|
351
|
+
throw new CadRefusal("cad-not-ready", status.error);
|
|
352
|
+
const job = await fs.mkdtemp(path.join(root, `cad-${name}-`));
|
|
353
|
+
await fs.chmod(job, 0o700);
|
|
354
|
+
const script = path.join(job, `${name}.py`), parameters = path.join(job, `${name}.parameters.json`), request = path.join(job, ".cad-request.json");
|
|
355
|
+
const resultManifest = path.join(job, "cad-result.json");
|
|
356
|
+
const lineage = createHash("sha256").update(source).digest("hex");
|
|
357
|
+
await fs.writeFile(script, source, { mode: 0o600 });
|
|
358
|
+
let previous = {};
|
|
359
|
+
if (args.script_path !== undefined) {
|
|
360
|
+
try {
|
|
361
|
+
previous = JSON.parse(await fs.readFile(await this.inputFile(String(args.script_path).replace(/\.py$/i, ".parameters.json"), ".json"), "utf8"));
|
|
362
|
+
}
|
|
363
|
+
catch (e) {
|
|
364
|
+
if (e.code !== "ENOENT")
|
|
365
|
+
throw e;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
await fs.writeFile(parameters, JSON.stringify({ ...previous, ...overrides }), { mode: 0o600 });
|
|
369
|
+
await atomicJson(resultManifest, {
|
|
370
|
+
status: "pending",
|
|
371
|
+
final: args.final === true,
|
|
372
|
+
lineage_id: lineage,
|
|
373
|
+
});
|
|
374
|
+
try {
|
|
375
|
+
remaining();
|
|
376
|
+
signal?.throwIfAborted();
|
|
377
|
+
const snapshot = await snapshotInputs(root, inputs, signal, {
|
|
378
|
+
directory: path.join(this.dataDir, "input-index"),
|
|
379
|
+
authorize: (directory) => this.allowedDirectory(directory),
|
|
380
|
+
});
|
|
381
|
+
const snapshots = snapshot.inputs, manifest = path.join(job, `${name}.inputs.json`);
|
|
382
|
+
await fs.writeFile(manifest, JSON.stringify(snapshots, null, 2), {
|
|
383
|
+
mode: 0o600,
|
|
384
|
+
});
|
|
385
|
+
const base = {
|
|
386
|
+
output: job,
|
|
387
|
+
name,
|
|
388
|
+
script,
|
|
389
|
+
parameters,
|
|
390
|
+
mode,
|
|
391
|
+
inputs: snapshots,
|
|
392
|
+
};
|
|
393
|
+
await fs.writeFile(request, JSON.stringify(base), { mode: 0o600 });
|
|
394
|
+
const protectedFiles = [
|
|
395
|
+
script,
|
|
396
|
+
parameters,
|
|
397
|
+
request,
|
|
398
|
+
manifest,
|
|
399
|
+
resultManifest,
|
|
400
|
+
...(snapshot.directory ? [snapshot.directory] : []),
|
|
401
|
+
];
|
|
402
|
+
const readableInputs = snapshot.directory ? [snapshot.directory] : [];
|
|
403
|
+
const effective = JSON.parse((await this.system.run(status.python, [
|
|
404
|
+
"-I",
|
|
405
|
+
"-B",
|
|
406
|
+
path.join(ASSETS, "worker.py"),
|
|
407
|
+
"parameters",
|
|
408
|
+
request,
|
|
409
|
+
], {
|
|
410
|
+
env: this.environment(job),
|
|
411
|
+
cwd: job,
|
|
412
|
+
timeoutMs: Math.min(10000, remaining()),
|
|
413
|
+
signal,
|
|
414
|
+
})).stdout);
|
|
415
|
+
await fs.writeFile(parameters, JSON.stringify(effective, null, 2), {
|
|
416
|
+
mode: 0o600,
|
|
417
|
+
});
|
|
418
|
+
const t = performance.now();
|
|
419
|
+
const built = await this.confined("build", request, job, protectedFiles, remaining(), signal, readableInputs);
|
|
420
|
+
await fs.writeFile(path.join(job, "build.log"), (built.stdout + "\n" + (built.stderr ?? "")).slice(-200000), { mode: 0o600, flag: "wx" });
|
|
421
|
+
for (const ext of mode === "solid" ? ["stl", "step"] : ["stl"]) {
|
|
422
|
+
const st = await fs.lstat(path.join(job, `${name}.${ext}`));
|
|
423
|
+
if (!st.isFile() || st.size === 0 || st.size > 64 * 1024 * 1024)
|
|
424
|
+
throw new Error(`CAD ${ext} export is missing, unsafe or too large.`);
|
|
425
|
+
}
|
|
426
|
+
const checked = JSON.parse((await this.confined("inspect", request, job, protectedFiles, remaining(), signal, readableInputs)).stdout);
|
|
427
|
+
const result = {
|
|
428
|
+
...checked,
|
|
429
|
+
status: "completed",
|
|
430
|
+
final: args.final === true,
|
|
431
|
+
completed_at: new Date().toISOString(),
|
|
432
|
+
lineage_id: lineage,
|
|
433
|
+
result_manifest: resultManifest,
|
|
434
|
+
script,
|
|
435
|
+
parameters,
|
|
436
|
+
inputs: snapshots,
|
|
437
|
+
input_manifest: manifest,
|
|
438
|
+
input_hashes: snapshot.hashes,
|
|
439
|
+
snapshot_bytes_added: snapshot.added,
|
|
440
|
+
snapshot_bytes_reused: snapshot.reused,
|
|
441
|
+
queue_wait_ms: queueWaitMs,
|
|
442
|
+
stl: path.join(job, `${name}.stl`),
|
|
443
|
+
step: mode === "solid" ? path.join(job, `${name}.step`) : null,
|
|
444
|
+
...(mode === "mesh"
|
|
445
|
+
? {
|
|
446
|
+
step_unavailable: "Mesh mode has no parametric B-rep; STEP export is unavailable.",
|
|
447
|
+
}
|
|
448
|
+
: {}),
|
|
449
|
+
seconds: (performance.now() - t) / 1000,
|
|
450
|
+
};
|
|
451
|
+
await atomicJson(resultManifest, result);
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
catch (e) {
|
|
455
|
+
await atomicJson(resultManifest, {
|
|
456
|
+
status: "failed",
|
|
457
|
+
final: false,
|
|
458
|
+
final_requested: args.final === true,
|
|
459
|
+
lineage_id: lineage,
|
|
460
|
+
message: e instanceof Error ? e.message : String(e),
|
|
461
|
+
script,
|
|
462
|
+
parameters,
|
|
463
|
+
}).catch(() => { });
|
|
464
|
+
const message = `${e instanceof Error ? e.message : String(e)} Checkpoint retained: ${script} and ${parameters}.`;
|
|
465
|
+
if (e instanceof CadRefusal)
|
|
466
|
+
throw new CadRefusal(e.code, message);
|
|
467
|
+
throw new Error(message);
|
|
468
|
+
}
|
|
469
|
+
}, "run", signal, deadline);
|
|
470
|
+
}
|
|
471
|
+
async checkFit(args, signal) {
|
|
472
|
+
only(args, [
|
|
473
|
+
"model",
|
|
474
|
+
"reference",
|
|
475
|
+
"transform",
|
|
476
|
+
"clearance_mm",
|
|
477
|
+
"timeout_ms",
|
|
478
|
+
]);
|
|
479
|
+
const model = await this.inputFile(args.model, ".stl"), reference = await this.inputFile(args.reference, ".stl");
|
|
480
|
+
const clearance = args.clearance_mm ?? 0;
|
|
481
|
+
if (typeof clearance !== "number" ||
|
|
482
|
+
!Number.isFinite(clearance) ||
|
|
483
|
+
clearance < 0 ||
|
|
484
|
+
clearance > 100)
|
|
485
|
+
throw new Error("clearance_mm must be finite, between 0 and 100.");
|
|
486
|
+
return this.exclusive(async () => {
|
|
487
|
+
const status = await this.status();
|
|
488
|
+
if (!status.ready)
|
|
489
|
+
throw new CadRefusal("cad-not-ready", status.error);
|
|
490
|
+
const job = await fs.mkdtemp(path.join(this.dataDir, "fit-"));
|
|
491
|
+
try {
|
|
492
|
+
await fs.copyFile(model, path.join(job, "model.stl"));
|
|
493
|
+
await fs.copyFile(reference, path.join(job, "reference.stl"));
|
|
494
|
+
const request = path.join(job, "request.json");
|
|
495
|
+
await fs.writeFile(request, JSON.stringify({
|
|
496
|
+
model: path.join(job, "model.stl"),
|
|
497
|
+
reference: path.join(job, "reference.stl"),
|
|
498
|
+
transform: args.transform ?? {},
|
|
499
|
+
clearance_mm: clearance,
|
|
500
|
+
}));
|
|
501
|
+
return JSON.parse((await this.confined("fit", request, job, [
|
|
502
|
+
request,
|
|
503
|
+
path.join(job, "model.stl"),
|
|
504
|
+
path.join(job, "reference.stl"),
|
|
505
|
+
], milliseconds(args.timeout_ms), signal)).stdout);
|
|
506
|
+
}
|
|
507
|
+
finally {
|
|
508
|
+
await fs.rm(job, { recursive: true, force: true });
|
|
509
|
+
}
|
|
510
|
+
}, "fit", signal);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
function only(args, keys) {
|
|
514
|
+
if (Object.keys(args).some((k) => !keys.includes(k)))
|
|
515
|
+
throw new Error(`CAD accepts only ${keys.join(", ")}.`);
|
|
516
|
+
}
|
|
517
|
+
function plainName(name) {
|
|
518
|
+
if (typeof name !== "string" ||
|
|
519
|
+
!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(name) ||
|
|
520
|
+
name.includes(".."))
|
|
521
|
+
throw new Error("name must be a plain filename stem (up to 64 characters).");
|
|
522
|
+
return name;
|
|
523
|
+
}
|
|
524
|
+
function milliseconds(value) {
|
|
525
|
+
if (value === undefined)
|
|
526
|
+
return 120000;
|
|
527
|
+
if (typeof value !== "number" ||
|
|
528
|
+
!Number.isInteger(value) ||
|
|
529
|
+
value < 100 ||
|
|
530
|
+
value > 900000)
|
|
531
|
+
throw new Error("timeout_ms must be an integer from 100 to 900000.");
|
|
532
|
+
return value;
|
|
533
|
+
}
|
|
534
|
+
async function atomicJson(file, value) {
|
|
535
|
+
const temporary = path.join(path.dirname(file), `.cad-result-${randomUUID()}.tmp`);
|
|
536
|
+
try {
|
|
537
|
+
await fs.writeFile(temporary, JSON.stringify(value, null, 2), {
|
|
538
|
+
flag: "wx",
|
|
539
|
+
mode: 0o600,
|
|
540
|
+
});
|
|
541
|
+
await fs.rename(temporary, file);
|
|
542
|
+
}
|
|
543
|
+
finally {
|
|
544
|
+
await fs.unlink(temporary).catch(() => { });
|
|
545
|
+
}
|
|
546
|
+
}
|
package/dist/counterpart/info.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CAD_CAPABILITY, cadEnabled } from "../cad/contracts.js";
|
|
1
2
|
/** counterpart_printer_info for Bambu printers (PRD §8.4). Pure: no printer traffic. */
|
|
2
3
|
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "../printers/camera-models.js";
|
|
3
4
|
import { normalizeModel } from "../safety/limits.js";
|
|
@@ -31,6 +32,7 @@ export function bambuPrinterInfo(options) {
|
|
|
31
32
|
host: options.host,
|
|
32
33
|
},
|
|
33
34
|
capabilities: {
|
|
35
|
+
...(cadEnabled() ? { cad: CAD_CAPABILITY } : {}),
|
|
34
36
|
progress: true,
|
|
35
37
|
layers: true,
|
|
36
38
|
// camera_snapshot needs the model to choose its transport.
|
|
@@ -18,6 +18,10 @@ export const REMOTE_SCOPES = {
|
|
|
18
18
|
blender_mcp_status: "read",
|
|
19
19
|
counterpart_printer_info: "read",
|
|
20
20
|
counterpart_print_progress: "read",
|
|
21
|
+
cad_status: "read",
|
|
22
|
+
cad_setup: "read",
|
|
23
|
+
cad_run: "design",
|
|
24
|
+
cad_check_fit: "design",
|
|
21
25
|
fusion_mcp_status: "read",
|
|
22
26
|
blender_mcp_setup: "read", // checks only; update raises it
|
|
23
27
|
fusion_mcp_setup: "read", // checks only; install raises it
|
|
@@ -73,6 +77,7 @@ const RAISED_BY = {
|
|
|
73
77
|
fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
|
|
74
78
|
blender_mcp_status: { connect: "design" }, // connects to Blender
|
|
75
79
|
blender_mcp_setup: { update: "raw" }, // replaces the add-on in the person's Blender
|
|
80
|
+
cad_setup: { install: "raw" },
|
|
76
81
|
fusion_mcp_setup: { install: "raw" }, // installs into the person's Fusion, a login item and this server's .env
|
|
77
82
|
};
|
|
78
83
|
/**
|
|
@@ -92,6 +97,8 @@ const TOP_LEVEL_CONFIG = new Set(["type"]);
|
|
|
92
97
|
const FILE_ARGUMENTS = new Set(["filament_profile", "slicer_profile", "load_filaments", "source_f3d"]);
|
|
93
98
|
const isPath = (key) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
|
|
94
99
|
function kindOf(tool, key, depth) {
|
|
100
|
+
if (tool === "cad_check_fit" && depth === 0 && ["model", "reference"].includes(key))
|
|
101
|
+
return "path";
|
|
95
102
|
// counterpart_print_route's own `route` is the connection the caller chooses.
|
|
96
103
|
if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key))
|
|
97
104
|
return "config";
|
|
@@ -60,6 +60,14 @@ export type PrinterInfo = {
|
|
|
60
60
|
name?: string;
|
|
61
61
|
};
|
|
62
62
|
capabilities: {
|
|
63
|
+
cad?: {
|
|
64
|
+
contract: string;
|
|
65
|
+
status: string;
|
|
66
|
+
setup: string;
|
|
67
|
+
run: string;
|
|
68
|
+
checkFit: string;
|
|
69
|
+
prompt: string;
|
|
70
|
+
};
|
|
63
71
|
progress: boolean;
|
|
64
72
|
layers: boolean;
|
|
65
73
|
camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
|
|
@@ -122,6 +130,31 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
|
|
|
122
130
|
capabilities: {
|
|
123
131
|
type: string;
|
|
124
132
|
properties: {
|
|
133
|
+
cad: {
|
|
134
|
+
type: string;
|
|
135
|
+
properties: {
|
|
136
|
+
contract: {
|
|
137
|
+
type: string;
|
|
138
|
+
const: string;
|
|
139
|
+
};
|
|
140
|
+
status: {
|
|
141
|
+
type: string;
|
|
142
|
+
};
|
|
143
|
+
setup: {
|
|
144
|
+
type: string;
|
|
145
|
+
};
|
|
146
|
+
run: {
|
|
147
|
+
type: string;
|
|
148
|
+
};
|
|
149
|
+
checkFit: {
|
|
150
|
+
type: string;
|
|
151
|
+
};
|
|
152
|
+
prompt: {
|
|
153
|
+
type: string;
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
required: string[];
|
|
157
|
+
};
|
|
125
158
|
progress: {
|
|
126
159
|
type: string;
|
|
127
160
|
};
|
|
@@ -36,6 +36,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
|
|
|
36
36
|
capabilities: {
|
|
37
37
|
type: "object",
|
|
38
38
|
properties: {
|
|
39
|
+
cad: { type: "object", properties: { contract: { type: "string", const: "cad/1" }, status: { type: "string" }, setup: { type: "string" }, run: { type: "string" }, checkFit: { type: "string" }, prompt: { type: "string" } }, required: ["contract", "status", "setup", "run", "checkFit", "prompt"] },
|
|
39
40
|
progress: { type: "boolean" },
|
|
40
41
|
layers: { type: "boolean" },
|
|
41
42
|
camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
|
package/dist/design-guidance.js
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Manufacturing guidance for agents that design printable models: David Montgomery's FDM design
|
|
3
|
-
* prompt pack (3 November 2026), verbatim. Served as MCP prompts and a resource; the other printer
|
|
4
|
-
* MCP (bambu-printer-mcp / mcp-3D-printer-server) serves the same text. Clients choose when to
|
|
5
|
-
* attach each piece.
|
|
6
|
-
*/
|
|
1
|
+
import { CAD_DESIGN_PROMPT } from "./cad/contracts.js";
|
|
7
2
|
export const FDM_CORE = `Design the finished object the user wants, with the manufacturing plan as part of the design. Preserve its function, fit, and visual identity. Use your design ability freely to make that outcome practical through geometry, orientation, materials, color placement, supports, and assembly.
|
|
8
3
|
|
|
9
4
|
Use the actual printer and material context: nozzle arrangement and filament routing, build volume, nozzle and line widths, layer profile, cooling, available filaments, and relevant successful prints or calibration. Missing information is unknown, not a capability the printer automatically has. Use reasonable, labeled assumptions for reversible choices; ask only when an unknown materially changes the result.
|
|
@@ -165,6 +160,7 @@ export const FDM_CAPABILITY_URI = "guidance://fdm/capability-guidance";
|
|
|
165
160
|
export const FDM_CAPABILITY_RESOURCE = { uri: FDM_CAPABILITY_URI, name: "FDM bridge and overhang guidance", mimeType: "text/markdown",
|
|
166
161
|
description: "Planning bands and evidence for bridges and overhangs, for when one is consequential and there is no sufficiently specific measured capability available" };
|
|
167
162
|
export const DESIGN_PROMPTS = [
|
|
163
|
+
CAD_DESIGN_PROMPT,
|
|
168
164
|
{ name: "fdm_design", title: "Design for FDM printing", text: FDM_CORE,
|
|
169
165
|
description: "Persistent instructions for every design or model-editing task: plan how the object prints as part of the design, using the actual printer, filaments and slice." },
|
|
170
166
|
{ name: "fdm_multicolor", title: "Multicolour and support materials", text: FDM_MULTICOLOR,
|