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
@@ -1,3 +1,6 @@
1
+ import {snapshotFrame} from "../counterpart/fresh-frame.js";
2
+ import {FlightRecords,flightKey,type PrintGeometry} from "../counterpart/flight-record.js";
3
+ import {geometryFromGcode,geometryFromFile} from "../counterpart/print-geometry.js";
1
4
  import { PrinterRefusal, markPrintCommandSent } from "../refusal.js";
2
5
  import {CameraStreams, type FrameOptions} from "./camera-stream.js";
3
6
  import {openTcpCameraSource, openRtspCameraSource} from "./camera-sources.js";
@@ -598,6 +601,7 @@ export type ProgressReport = { raw: Record<string, any>; receivedAt: number };
598
601
  /** The inspected bytes and limits of a started job, for the resume prompt and byte check. */
599
602
  export type CheckedFile = {
600
603
  sha256: string;
604
+ expected?: PrintGeometry;
601
605
  /** A project's printed plate: its number and the SHA-256 of its Metadata/plate_<index>.gcode. */
602
606
  plate?: { index: number; sha256: string };
603
607
  model: string;
@@ -716,13 +720,21 @@ function reportsJob(raw: Record<string, any>, remotePath: string): boolean {
716
720
  export async function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile> {
717
721
  const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
718
722
  let plate: CheckedFile["plate"];
723
+ let expected: PrintGeometry | undefined;
719
724
  const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
720
725
  if (plateNumber && /\.3mf$/i.test(filePath)) {
721
726
  const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath!);
722
- if (entry) plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
727
+ if (entry) {
728
+ const bytes = await entry.async("nodebuffer");
729
+ plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(bytes).digest("hex") };
730
+ if (bytes.length <= 64 * 1024 * 1024) expected = geometryFromGcode(bytes.toString("utf8"));
731
+ }
732
+ } else if (!/\.3mf$/i.test(filePath)) {
733
+ expected = await geometryFromFile(filePath);
723
734
  }
735
+
724
736
  return {
725
- sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
737
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), ...(expected ? { expected } : {}), model: inspection.model,
726
738
  maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
727
739
  materials: [...new Set(used.length ? used : inspection.materials)],
728
740
  };
@@ -753,6 +765,7 @@ export type PrintPreflight = { finishedJob?: string; serial: string; model: stri
753
765
  export {cameraFrameParser} from "./camera-wire.js";
754
766
 
755
767
  export class BambuImplementation {
768
+ readonly flightRecords = new FlightRecords();
756
769
  private printerStore: BambuClientStore;
757
770
  readonly cameraStreams = new CameraStreams();
758
771
  /**
@@ -846,16 +859,26 @@ export class BambuImplementation {
846
859
  * verified: a resume then re-reads it if it can and otherwise matches the
847
860
  * unique name, as KAN-216 does for firmware that cannot download a file.
848
861
  */
862
+ /** At the existing send-authorization boundary: record evidence even if the reply/helper is lost. */
863
+ recordFlightDispatch(host:string,serial:string,remotePath:string,requirements:PrinterStateRequirements,file:CheckedFile):void {
864
+ this.flightRecords.begin(flightKey(host,serial),{sha256:file.sha256,jobName:remotePath,mapping:requirements.amsMapping,materials:file.materials,plate:file.plate,expected:file.expected});
865
+ }
866
+
849
867
  recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements, file: CheckedFile, uploadedHere = true): void {
850
868
  if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? "")) throw new Error("A started job needs the SHA-256 of its inspected bytes.");
851
869
  this.checkedJobs.set(`${host}\n${serial}`, {
852
870
  ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
853
871
  });
872
+ if(!this.flightRecords.accept(flightKey(host,serial),remotePath)){
873
+ this.recordFlightDispatch(host,serial,remotePath,requirements,file);
874
+ this.flightRecords.accept(flightKey(host,serial),remotePath);
875
+ }
854
876
  this.clearedErrors.delete(serial);
855
877
  }
856
878
 
857
879
  /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
858
880
  observeReport(host: string, serial: string, raw: Record<string, any> | undefined): void {
881
+ if (raw) this.flightRecords.observe(flightKey(host, serial), raw);
859
882
  const key = `${host}\n${serial}`;
860
883
  const checked = this.checkedJobs.get(key);
861
884
  if (!checked || !raw || typeof raw.gcode_state !== "string") return;
@@ -1273,6 +1296,7 @@ export class BambuImplementation {
1273
1296
  assertActive();
1274
1297
  if (legacyContainer) {
1275
1298
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1299
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1276
1300
  markPrintCommandSent();
1277
1301
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath })); } catch (error) { watcher.dispose(); throw error; }
1278
1302
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
@@ -1355,6 +1379,7 @@ export class BambuImplementation {
1355
1379
  }
1356
1380
 
1357
1381
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1382
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1358
1383
  markPrintCommandSent();
1359
1384
  try { await printer.publish(projectFileCmd); } catch (error) { watcher.dispose(); throw error; }
1360
1385
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
@@ -2016,6 +2041,7 @@ export class BambuImplementation {
2016
2041
  const printer = await this.getPrinter(host, serial, token);
2017
2042
  assertActive();
2018
2043
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
2044
+ this.recordFlightDispatch(host,serial,remotePath,requirements,resumeFile);
2019
2045
  markPrintCommandSent();
2020
2046
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath })); } catch (error) { watcher.dispose(); throw error; }
2021
2047
  this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
@@ -2174,6 +2200,7 @@ export class BambuImplementation {
2174
2200
  token: string,
2175
2201
  options: {
2176
2202
  savePath?: string;
2203
+ capturedAfter?: string;
2177
2204
  timeoutMs?: number;
2178
2205
  bambuModel?: string;
2179
2206
  /**
@@ -2196,6 +2223,7 @@ export class BambuImplementation {
2196
2223
  sizeBytes: number;
2197
2224
  base64: string;
2198
2225
  savedTo?: string;
2226
+ capturedAt?: string;
2199
2227
  width?: number;
2200
2228
  height?: number;
2201
2229
  note?: string;
@@ -2204,10 +2232,11 @@ export class BambuImplementation {
2204
2232
  const timeoutMs = options.timeoutMs ?? 8_000;
2205
2233
  const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
2206
2234
  if (stream && !stream.stopped) {
2207
- const jpeg = await stream.latest(Math.min(timeoutMs, 10_000));
2208
- if (!jpeg) throw new Error("The active camera stream has not produced a live frame");
2235
+ const frame = await snapshotFrame(stream,timeoutMs,options.capturedAfter);
2236
+ if (frame.status!=="frame"||!frame.base64) throw new Error("The active camera stream has not produced a live frame");
2237
+ const jpeg=Buffer.from(frame.base64,"base64");
2209
2238
  if (options.savePath) await (await import("node:fs/promises")).writeFile(options.savePath, jpeg);
2210
- return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport,
2239
+ return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport, capturedAt:frame.capturedAt,
2211
2240
  ...(options.savePath ? {savedTo: options.savePath} : {})};
2212
2241
  }
2213
2242
  const model = (options.bambuModel ?? "").toLowerCase();
@@ -153,7 +153,7 @@ function parameterWords(text: string): Map<string, number> {
153
153
  }
154
154
 
155
155
  /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
156
- function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
156
+ export function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
157
157
  if (i !== undefined || j !== undefined) return [x + (i ?? 0), y + (j ?? 0)];
158
158
  if (r === undefined || r === 0 || (tx === x && ty === y)) return undefined;
159
159
  const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);
@@ -0,0 +1,52 @@
1
+ /** XML output boundary for 3MF metadata; no printer calls or geometry/G-code changes. */
2
+ import fs from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { SaxesParser } from "saxes";
5
+ import { readSafe3mfArchive } from "../safety/archive.js";
6
+
7
+ /** Encode text for a quoted XML attribute, preserving whitespace through XML parsing. */
8
+ export function xmlAttribute(value: string): string {
9
+ const entities: Record<string,string> = {"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\t":"&#9;","\n":"&#10;","\r":"&#13;"};
10
+ return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replace(/[&"'<>\t\r\n]/g, char=>entities[char]);
11
+ }
12
+ const parses = (xml:string) => {
13
+ try {
14
+ let root:string|undefined;
15
+ const parser=new SaxesParser();
16
+ parser.on("error",error=>{throw error;});
17
+ parser.on("opentag",node=>{root ??= node.name;});
18
+ parser.write(xml).close();
19
+ return root === "config";
20
+ } catch { return false; }
21
+ };
22
+
23
+ /** Studio 02.08.02.61 bbs_3mf.cpp writes object opt_serialize values without XML escaping.
24
+ * Only repair its single-line key/value metadata form. Unexpected malformed XML fails closed. */
25
+ export async function escapedModelSettings(xml:string):Promise<string> {
26
+ if (Buffer.byteLength(xml)>16*1024*1024) throw Error("3MF model settings exceed the 16 MiB XML limit.");
27
+ if (await parses(xml)) return xml;
28
+ const lines=xml.split(/(?<=\n)/);
29
+ for(let i=0;i<lines.length;i++) {
30
+ const match=/^([ \t]*<metadata\s+key="[\w.:-]+"\s+value=")(.*)("\s*\/>[ \t]*\r?\n?)$/.exec(lines[i]);
31
+ if (!match || await parses('<config>'+lines[i]+'</config>')) continue;
32
+ lines[i]=match[1]+xmlAttribute(match[2])+match[3];
33
+ }
34
+ const repaired=lines.join('');
35
+ if (!await parses(repaired)) throw Error("Slicer produced malformed Metadata/model_settings.config; no safe attribute repair is available.");
36
+ return repaired;
37
+ }
38
+
39
+ /** Normalize only a newly produced/restored slice, before caching or handing it to the client. */
40
+ export async function normalize3mfMetadata(filePath:string):Promise<void> {
41
+ const {zip}=await readSafe3mfArchive(filePath);
42
+ const entry=zip.file('Metadata/model_settings.config');
43
+ if(!entry) return;
44
+ const original=await entry.async('string'), repaired=await escapedModelSettings(original);
45
+ if (repaired===original) return;
46
+ zip.file(entry.name,repaired);
47
+ const staged=filePath+'.'+randomUUID()+'.xml-tmp';
48
+ try {
49
+ await fs.writeFile(staged,await zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'}),{flag:'wx',mode:0o600});
50
+ await fs.rename(staged,filePath);
51
+ } finally { await fs.rm(staged,{force:true}).catch(()=>{}); }
52
+ }
@@ -1,3 +1,4 @@
1
+ import { normalize3mfMetadata } from "../slicer/3mf-xml.js";
1
2
  import { customGcodesWithPauses, layerTops, machinePauseGcode, pausedLayers, readPlateGcode, readProjectCustomGcodes } from "../slicer/layer-pauses.js";
2
3
  import * as THREE from 'three';
3
4
  import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
@@ -2134,12 +2135,14 @@ export class STLManipulator extends EventEmitter {
2134
2135
  if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
2135
2136
  throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
2136
2137
  }
2137
- if (cacheKey && !restored && fs.existsSync(outputFilePath)) await keepSlice(cacheKey, cacheRun!);
2138
2138
 
2139
2139
  if (!fs.existsSync(outputFilePath)) {
2140
2140
  throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
2141
2141
  }
2142
2142
 
2143
+ if (/\.3mf$/i.test(outputFilePath)) await normalize3mfMetadata(outputFilePath);
2144
+ if (cacheKey && !restored) await keepSlice(cacheKey, cacheRun!);
2145
+
2143
2146
  if (progressCallback) progressCallback(100, "Slicing completed successfully");
2144
2147
 
2145
2148
  this.emit('operationComplete', {
@@ -38,12 +38,16 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
38
38
  cad_setup: hints(false, true, true, true),
39
39
  cad_run: hints(false, false, false, false),
40
40
  cad_check_fit: READ_LOCAL,
41
+ cad_examples: READ_LOCAL,
42
+ design_guidance: READ_LOCAL,
41
43
  // Printer and cloud reads
42
44
  get_printer_status: READ_OUTSIDE,
43
45
  get_printer_filaments: READ_OUTSIDE,
44
46
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
45
47
  list_printer_files: READ_OUTSIDE,
46
48
  counterpart_print_progress: READ_OUTSIDE,
49
+ counterpart_print_record: READ_LOCAL,
50
+ counterpart_print_assess: hints(false,false,true,false),
47
51
  counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
48
52
  counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
49
53
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.