bambu-printer-mcp 1.1.89 → 1.1.91

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.
Files changed (70) hide show
  1. package/README.md +49 -1
  2. package/dist/cad/contracts.d.ts +84 -0
  3. package/dist/cad/contracts.js +50 -5
  4. package/dist/cad/examples.d.ts +22 -0
  5. package/dist/cad/examples.js +81 -0
  6. package/dist/cad/process.js +3 -0
  7. package/dist/cad-engine.d.ts +25 -0
  8. package/dist/cad-engine.js +197 -27
  9. package/dist/counterpart/flight-record.d.ts +155 -0
  10. package/dist/counterpart/flight-record.js +831 -0
  11. package/dist/counterpart/flight-tools.d.ts +213 -0
  12. package/dist/counterpart/flight-tools.js +232 -0
  13. package/dist/counterpart/fresh-frame.d.ts +16 -0
  14. package/dist/counterpart/fresh-frame.js +26 -0
  15. package/dist/counterpart/make-3mf.js +1 -4
  16. package/dist/counterpart/physical-evidence.d.ts +70 -0
  17. package/dist/counterpart/physical-evidence.js +103 -0
  18. package/dist/counterpart/print-geometry.d.ts +13 -0
  19. package/dist/counterpart/print-geometry.js +181 -0
  20. package/dist/counterpart/remote.js +4 -0
  21. package/dist/counterpart/schemas.d.ts +32 -0
  22. package/dist/counterpart/schemas.js +2 -0
  23. package/dist/counterpart/visual-evidence.d.ts +38 -0
  24. package/dist/counterpart/visual-evidence.js +155 -0
  25. package/dist/design-guidance.d.ts +22 -1
  26. package/dist/design-guidance.js +35 -2
  27. package/dist/index.js +35 -3
  28. package/dist/printers/bambu.d.ts +9 -2
  29. package/dist/printers/bambu.js +32 -6
  30. package/dist/safety/print-preview.d.ts +2 -0
  31. package/dist/safety/print-preview.js +1 -1
  32. package/dist/slicer/3mf-xml.d.ts +7 -0
  33. package/dist/slicer/3mf-xml.js +61 -0
  34. package/dist/stl/stl-manipulator.js +5 -2
  35. package/dist/tool-annotations.js +4 -0
  36. package/package.json +2 -1
  37. package/src/cad/contracts.ts +54 -5
  38. package/src/cad/examples/bag_clip.py +86 -0
  39. package/src/cad/examples/bistable_clicker.py +81 -0
  40. package/src/cad/examples/cable_clip.py +55 -0
  41. package/src/cad/examples/chainmail.py +45 -0
  42. package/src/cad/examples/hinged_box.py +101 -0
  43. package/src/cad/examples/knurled_knob.py +50 -0
  44. package/src/cad/examples/loft_handle.py +52 -0
  45. package/src/cad/examples/phone_stand.py +92 -0
  46. package/src/cad/examples/swept_hook.py +69 -0
  47. package/src/cad/examples/threaded_jar.py +62 -0
  48. package/src/cad/examples/trigger_capo.py +95 -0
  49. package/src/cad/examples/wall_hook.py +65 -0
  50. package/src/cad/examples.ts +77 -0
  51. package/src/cad/geometry.py +122 -4
  52. package/src/cad/process.ts +3 -0
  53. package/src/cad/worker.py +4 -0
  54. package/src/cad-engine.ts +221 -52
  55. package/src/counterpart/flight-record.ts +984 -0
  56. package/src/counterpart/flight-tools.ts +282 -0
  57. package/src/counterpart/fresh-frame.ts +45 -0
  58. package/src/counterpart/make-3mf.ts +1 -5
  59. package/src/counterpart/physical-evidence.ts +185 -0
  60. package/src/counterpart/print-geometry.ts +192 -0
  61. package/src/counterpart/remote.ts +4 -0
  62. package/src/counterpart/schemas.ts +3 -0
  63. package/src/counterpart/visual-evidence.ts +212 -0
  64. package/src/design-guidance.ts +35 -2
  65. package/src/index.ts +38 -4
  66. package/src/printers/bambu.ts +34 -5
  67. package/src/safety/print-preview.ts +1 -1
  68. package/src/slicer/3mf-xml.ts +52 -0
  69. package/src/stl/stl-manipulator.ts +4 -1
  70. package/src/tool-annotations.ts +4 -0
package/src/cad-engine.ts CHANGED
@@ -33,10 +33,18 @@ export interface CadStatus {
33
33
  platform: string;
34
34
  storage: CadStorage;
35
35
  error?: string;
36
+ /** Set when this call re-verified a runtime that only the engine's own sources had changed under. */
37
+ reverified?: string;
36
38
  }
37
39
  export class CadEngine {
38
40
  private readonly system: CadSystem;
39
41
  readonly dataDir: string;
42
+ private reverifyFailure?: { fingerprint: string; error: string };
43
+ /** How long a re-check waits for another CAD operation to let go of the engine (Counterpart reads status with 30 s). */
44
+ busyWaitMs = 25_000;
45
+ /** Within this window a freed engine is re-checked here; later this call only waits for the other call's result, so
46
+ * a wait plus a ~17 s re-check cannot overrun the status deadline. */
47
+ busyRetryMs = 5_000;
40
48
  constructor(private readonly options: CadOptions) {
41
49
  this.system = options.system ?? defaultCadSystem;
42
50
  this.dataDir = path.resolve(
@@ -207,7 +215,7 @@ export class CadEngine {
207
215
  if (args.install !== true)
208
216
  return {
209
217
  supported: ["darwin", "linux"].includes(this.system.platform),
210
- ...(await this.status()),
218
+ ...(await this.ensureReady(signal)),
211
219
  };
212
220
  if (!["darwin", "linux"].includes(this.system.platform))
213
221
  throw new CadRefusal(
@@ -264,54 +272,8 @@ export class CadEngine {
264
272
  );
265
273
  throw e;
266
274
  }
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
- );
275
+ this.reverifyFailure = undefined;
276
+ await this.verify(opts, signal);
315
277
  return {
316
278
  supported: true,
317
279
  ...(await this.status()),
@@ -324,6 +286,203 @@ export class CadEngine {
324
286
  signal,
325
287
  );
326
288
  }
289
+ /**
290
+ * The proof setup ends with: the runtime's imports, then the confined build, STL and STEP round trip, then the ready
291
+ * marker with the engine fingerprint and the runtime identity it proved. Shared by cad_setup and the automatic
292
+ * re-verification after an update that changed only the engine's sources.
293
+ */
294
+ private async verify(
295
+ opts: { env: NodeJS.ProcessEnv; cwd: string; signal?: AbortSignal; timeoutMs: number },
296
+ signal?: AbortSignal,
297
+ measured?: unknown,
298
+ ): Promise<void> {
299
+ // Setup proves the fresh install's imports outside confinement first; a re-check of an unchanged runtime relies on
300
+ // the confined round trip, which imports the same libraries.
301
+ if (measured === undefined) {
302
+ const python = path.join(this.dataDir, "runtime", "bin", "python");
303
+ await this.system.run(
304
+ python,
305
+ ["-I", "-B", path.join(ASSETS, "worker.py"), "imports"],
306
+ { ...opts, timeoutMs: 120_000 },
307
+ );
308
+ }
309
+ const job = await fs.mkdtemp(path.join(this.dataDir, "verify-"));
310
+ const request = path.join(job, "request.json");
311
+ await fs.writeFile(
312
+ request,
313
+ JSON.stringify({ output: job, home: os.homedir() }),
314
+ { mode: 0o600 },
315
+ );
316
+ const result = JSON.parse(
317
+ (
318
+ await this.confined(
319
+ "smoke",
320
+ request,
321
+ job,
322
+ [request],
323
+ 180_000,
324
+ signal,
325
+ )
326
+ ).stdout,
327
+ );
328
+ if (
329
+ result.build123d !== BUILD123D ||
330
+ !result.watertight ||
331
+ !result.manifold ||
332
+ !result.step_valid ||
333
+ result.solid_count !== 1
334
+ )
335
+ throw new Error("CAD setup's confined STL/STEP round trip failed.");
336
+ // A re-check of an unchanged runtime keeps the size setup measured instead of walking 1.4 GB again.
337
+ const storage = measured ?? {
338
+ installed_bytes: await measureEnvironment(this.dataDir),
339
+ measured_at: new Date().toISOString(),
340
+ };
341
+ await fs.writeFile(
342
+ path.join(this.dataDir, "ready.json"),
343
+ JSON.stringify({
344
+ build123d: BUILD123D,
345
+ platform: this.system.platform,
346
+ verifiedAt: new Date().toISOString(),
347
+ fingerprint: await this.fingerprint(),
348
+ runtime: await this.runtimeIdentity(),
349
+ dataDevice: (await fs.stat(this.dataDir)).dev,
350
+ storage,
351
+ }),
352
+ { mode: 0o600 },
353
+ );
354
+ }
355
+ /**
356
+ * Re-verifies without installing when only the engine's own sources changed since the last proof (#609): the
357
+ * marker matches this platform, build123d and data device, its engine fingerprint differs, and the installed
358
+ * runtime still matches requirements.lock exactly with the same interpreter. Anything else, including a changed
359
+ * lock, still needs cad_setup with install: true. A failed re-verification is reported, not retried, until the
360
+ * engine changes again or setup runs.
361
+ */
362
+ async ensureReady(signal?: AbortSignal, deadline?: number): Promise<CadStatus> {
363
+ const status = await this.status();
364
+ if (status.ready || !status.configured) return status;
365
+ const fingerprint = await this.fingerprint();
366
+ if (!(await this.onlyEngineChanged(fingerprint))) return status;
367
+ if (this.reverifyFailure?.fingerprint === fingerprint)
368
+ return { ...status, error: this.reverifyFailure.error };
369
+ const started = performance.now();
370
+ // A cad_run or cad_check_fit passes its own deadline: the re-check, its waiting included, stays inside timeout_ms.
371
+ const outOfTime = {
372
+ ...status,
373
+ error:
374
+ "The automatic re-check after this MCP's update did not finish within this call's timeout_ms; the next call runs it again.",
375
+ };
376
+ if (deadline !== undefined && deadline - started < 1) return outOfTime;
377
+ const limit = deadline === undefined ? undefined : AbortSignal.timeout(Math.ceil(deadline - started));
378
+ const bounded = limit ? (signal ? AbortSignal.any([signal, limit]) : limit) : signal;
379
+ const recheck = () =>
380
+ this.exclusive(
381
+ async () => {
382
+ if ((await this.status()).ready) return;
383
+ const env = this.environment(this.dataDir);
384
+ await fs.mkdir(env.TMPDIR!, { recursive: true });
385
+ const previous = await fs
386
+ .readFile(path.join(this.dataDir, "ready.json"), "utf8")
387
+ .then((text) => JSON.parse(text).storage, () => undefined);
388
+ await this.verify({ env, cwd: this.dataDir, signal: bounded, timeoutMs: 600_000 }, bounded, previous ?? null);
389
+ },
390
+ "setup",
391
+ bounded,
392
+ );
393
+ try {
394
+ // Another call may hold the engine, usually this same re-check from another process (Counterpart reading
395
+ // cad_status while the design worker's first cad_run starts): wait for it and try again, never call it a failure.
396
+ const waited = performance.now();
397
+ for (let attempt = true, until = Math.min(waited + this.busyWaitMs, deadline ?? Infinity); ; ) {
398
+ try {
399
+ if (attempt) {
400
+ await recheck();
401
+ break;
402
+ }
403
+ throw new CadRefusal("cad-setup-busy", "waiting for the other CAD operation's result");
404
+ } catch (e) {
405
+ if (!(e instanceof CadRefusal && e.code === "cad-setup-busy")) throw e;
406
+ signal?.throwIfAborted();
407
+ if (limit?.aborted) return outOfTime;
408
+ if ((await this.status()).ready) break;
409
+ attempt = performance.now() - waited < this.busyRetryMs;
410
+ if (performance.now() >= until)
411
+ return {
412
+ ...(await this.status()),
413
+ error:
414
+ "Another CAD operation is running; this MCP re-checks its unchanged runtime by itself when that finishes. Ask again shortly.",
415
+ };
416
+ await new Promise((resolve) => setTimeout(resolve, 500));
417
+ }
418
+ }
419
+ } catch (e) {
420
+ signal?.throwIfAborted();
421
+ if (limit?.aborted) return outOfTime; // ran out of this call's time: not a failed re-check, never cached
422
+ const reason = e instanceof Error ? e.message : String(e);
423
+ this.reverifyFailure = {
424
+ fingerprint,
425
+ error: `The automatic re-check after this MCP's update failed (${reason.slice(0, 300)}). Run cad_setup with install: true.`,
426
+ };
427
+ return { ...(await this.status()), error: this.reverifyFailure.error };
428
+ }
429
+ const after = await this.status();
430
+ return after.ready
431
+ ? {
432
+ ...after,
433
+ reverified: `Re-checked automatically after an update to the engine (${Math.round((performance.now() - started) / 1000)} s): the installed runtime was unchanged; confined import, build, STL and STEP round trip passed.`,
434
+ }
435
+ : after;
436
+ }
437
+ private async onlyEngineChanged(fingerprint: string): Promise<boolean> {
438
+ try {
439
+ const marker = JSON.parse(await fs.readFile(path.join(this.dataDir, "ready.json"), "utf8"));
440
+ if (
441
+ marker.build123d !== BUILD123D ||
442
+ marker.platform !== this.system.platform ||
443
+ marker.dataDevice !== (await fs.stat(this.dataDir)).dev ||
444
+ typeof marker.fingerprint !== "string" ||
445
+ marker.fingerprint === fingerprint
446
+ )
447
+ return false;
448
+ const runtime = await this.runtimeIdentity();
449
+ if (!runtime.matchesLock) return false;
450
+ // Markers from engines without the runtime record (bambu-printer-mcp 1.1.89, mcp-3D-printer-server 1.2.71 and
451
+ // earlier) qualify by the exact package match; the re-run proof decides the rest.
452
+ if (marker.runtime && (marker.runtime.interpreter !== runtime.interpreter || marker.runtime.lock_sha256 !== runtime.lock_sha256))
453
+ return false;
454
+ return true;
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+ /** The interpreter the venv runs and whether its installed distributions are exactly requirements.lock's pins. */
460
+ private async runtimeIdentity(): Promise<{ interpreter: string; lock_sha256: string; matchesLock: boolean }> {
461
+ const lock = await fs.readFile(path.join(ASSETS, "requirements.lock"), "utf8");
462
+ const runtime = path.join(this.dataDir, "runtime");
463
+ const cfg = await fs.readFile(path.join(runtime, "pyvenv.cfg"), "utf8").catch(() => "");
464
+ const field = (name: string) => cfg.match(new RegExp(`^${name}\\s*=\\s*(.+)$`, "m"))?.[1]?.trim() ?? "";
465
+ const interpreter = `${field("version_info") || field("version")} ${await fs.realpath(path.join(runtime, "bin", "python")).catch(() => "")}`;
466
+ const norm = (name: string) => name.toLowerCase().replace(/[-_.]+/g, "-");
467
+ const installed = new Map<string, string>();
468
+ const lib = path.join(runtime, "lib");
469
+ for (const dir of await fs.readdir(lib).catch(() => [] as string[])) {
470
+ if (!/^python3\.\d+$/.test(dir)) continue;
471
+ for (const entry of await fs.readdir(path.join(lib, dir, "site-packages")).catch(() => [] as string[])) {
472
+ const m = entry.match(/^(.+)-([^-]+)\.dist-info$/);
473
+ if (m) installed.set(norm(m[1]), m[2]);
474
+ }
475
+ }
476
+ let matchesLock = installed.size > 0;
477
+ for (const line of lock.split("\n")) {
478
+ const m = line.match(/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;]+)\s*(;.*)?$/);
479
+ if (!m) continue;
480
+ const have = installed.get(norm(m[1]));
481
+ // A pin behind an environment marker may not apply here: absent is fine, a different version is not.
482
+ if (have === undefined ? !m[3] : have !== m[2]) matchesLock = false;
483
+ }
484
+ return { interpreter, lock_sha256: createHash("sha256").update(lock).digest("hex"), matchesLock };
485
+ }
327
486
  private async fingerprint(): Promise<string> {
328
487
  const hash = createHash("sha256");
329
488
  for (const file of [
@@ -511,10 +670,13 @@ export class CadEngine {
511
670
  inputs[alias] = await this.inputFile(value, ext);
512
671
  }
513
672
  }
673
+ // Re-check before queueing, inside this run's deadline; a not-ready refusal still comes from inside the queue,
674
+ // after any queue timeout.
675
+ const before = await this.ensureReady(signal, deadline);
514
676
  return this.exclusive(
515
677
  async (queueWaitMs) => {
516
678
  const status = await this.status();
517
- if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
679
+ if (!status.ready) throw new CadRefusal("cad-not-ready", before.error ?? status.error!);
518
680
  const job = await fs.mkdtemp(path.join(root, `cad-${name}-`));
519
681
  await fs.chmod(job, 0o700);
520
682
  const script = path.join(job, `${name}.py`),
@@ -708,10 +870,13 @@ export class CadEngine {
708
870
  clearance > 100
709
871
  )
710
872
  throw new Error("clearance_mm must be finite, between 0 and 100.");
873
+ // One deadline for the whole call: the automatic re-check and the fit share timeout_ms.
874
+ const deadline = performance.now() + milliseconds(args.timeout_ms);
875
+ const before = await this.ensureReady(signal, deadline);
711
876
  return this.exclusive(
712
877
  async () => {
713
878
  const status = await this.status();
714
- if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
879
+ if (!status.ready) throw new CadRefusal("cad-not-ready", before.error ?? status.error!);
715
880
  const job = await fs.mkdtemp(path.join(this.dataDir, "fit-"));
716
881
  try {
717
882
  await fs.copyFile(model, path.join(job, "model.stl"));
@@ -737,7 +902,11 @@ export class CadEngine {
737
902
  path.join(job, "model.stl"),
738
903
  path.join(job, "reference.stl"),
739
904
  ],
740
- milliseconds(args.timeout_ms),
905
+ (() => {
906
+ const left = Math.floor(deadline - performance.now());
907
+ if (left <= 0) throw new Error("CAD fit timed out.");
908
+ return left;
909
+ })(),
741
910
  signal,
742
911
  )
743
912
  ).stdout,