bambu-printer-mcp 1.1.90 → 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 (42) hide show
  1. package/README.md +43 -0
  2. package/dist/counterpart/flight-record.d.ts +155 -0
  3. package/dist/counterpart/flight-record.js +831 -0
  4. package/dist/counterpart/flight-tools.d.ts +213 -0
  5. package/dist/counterpart/flight-tools.js +232 -0
  6. package/dist/counterpart/fresh-frame.d.ts +16 -0
  7. package/dist/counterpart/fresh-frame.js +26 -0
  8. package/dist/counterpart/make-3mf.js +1 -4
  9. package/dist/counterpart/physical-evidence.d.ts +70 -0
  10. package/dist/counterpart/physical-evidence.js +103 -0
  11. package/dist/counterpart/print-geometry.d.ts +13 -0
  12. package/dist/counterpart/print-geometry.js +181 -0
  13. package/dist/counterpart/remote.js +2 -0
  14. package/dist/counterpart/schemas.d.ts +32 -0
  15. package/dist/counterpart/schemas.js +2 -0
  16. package/dist/counterpart/visual-evidence.d.ts +38 -0
  17. package/dist/counterpart/visual-evidence.js +155 -0
  18. package/dist/index.js +24 -1
  19. package/dist/printers/bambu.d.ts +9 -2
  20. package/dist/printers/bambu.js +32 -6
  21. package/dist/safety/print-preview.d.ts +2 -0
  22. package/dist/safety/print-preview.js +1 -1
  23. package/dist/slicer/3mf-xml.d.ts +7 -0
  24. package/dist/slicer/3mf-xml.js +61 -0
  25. package/dist/stl/stl-manipulator.js +5 -2
  26. package/dist/tool-annotations.js +2 -0
  27. package/package.json +2 -1
  28. package/src/counterpart/flight-record.ts +984 -0
  29. package/src/counterpart/flight-tools.ts +282 -0
  30. package/src/counterpart/fresh-frame.ts +45 -0
  31. package/src/counterpart/make-3mf.ts +1 -5
  32. package/src/counterpart/physical-evidence.ts +185 -0
  33. package/src/counterpart/print-geometry.ts +192 -0
  34. package/src/counterpart/remote.ts +2 -0
  35. package/src/counterpart/schemas.ts +3 -0
  36. package/src/counterpart/visual-evidence.ts +212 -0
  37. package/src/index.ts +25 -2
  38. package/src/printers/bambu.ts +34 -5
  39. package/src/safety/print-preview.ts +1 -1
  40. package/src/slicer/3mf-xml.ts +52 -0
  41. package/src/stl/stl-manipulator.ts +4 -1
  42. package/src/tool-annotations.ts +2 -0
@@ -1,3 +1,6 @@
1
+ import { snapshotFrame } from "../counterpart/fresh-frame.js";
2
+ import { FlightRecords, flightKey } 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 } from "./camera-stream.js";
3
6
  import { openTcpCameraSource, openRtspCameraSource } from "./camera-sources.js";
@@ -597,14 +600,22 @@ function reportsJob(raw, remotePath) {
597
600
  export async function checkedFile(inspection, filePath) {
598
601
  const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
599
602
  let plate;
603
+ let expected;
600
604
  const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
601
605
  if (plateNumber && /\.3mf$/i.test(filePath)) {
602
606
  const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath);
603
- if (entry)
604
- plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
607
+ if (entry) {
608
+ const bytes = await entry.async("nodebuffer");
609
+ plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(bytes).digest("hex") };
610
+ if (bytes.length <= 64 * 1024 * 1024)
611
+ expected = geometryFromGcode(bytes.toString("utf8"));
612
+ }
613
+ }
614
+ else if (!/\.3mf$/i.test(filePath)) {
615
+ expected = await geometryFromFile(filePath);
605
616
  }
606
617
  return {
607
- sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
618
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), ...(expected ? { expected } : {}), model: inspection.model,
608
619
  maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
609
620
  materials: [...new Set(used.length ? used : inspection.materials)],
610
621
  };
@@ -632,6 +643,7 @@ export { cameraFrameParser } from "./camera-wire.js";
632
643
  export class BambuImplementation {
633
644
  constructor(confirm, options = {}) {
634
645
  this.confirm = confirm;
646
+ this.flightRecords = new FlightRecords();
635
647
  this.cameraStreams = new CameraStreams();
636
648
  /** In-flight counterpart_print_progress reads, one per printer. */
637
649
  this.progressReads = new Map();
@@ -708,16 +720,26 @@ export class BambuImplementation {
708
720
  * verified: a resume then re-reads it if it can and otherwise matches the
709
721
  * unique name, as KAN-216 does for firmware that cannot download a file.
710
722
  */
723
+ /** At the existing send-authorization boundary: record evidence even if the reply/helper is lost. */
724
+ recordFlightDispatch(host, serial, remotePath, requirements, file) {
725
+ this.flightRecords.begin(flightKey(host, serial), { sha256: file.sha256, jobName: remotePath, mapping: requirements.amsMapping, materials: file.materials, plate: file.plate, expected: file.expected });
726
+ }
711
727
  recordCheckedJob(host, serial, remotePath, requirements, file, uploadedHere = true) {
712
728
  if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? ""))
713
729
  throw new Error("A started job needs the SHA-256 of its inspected bytes.");
714
730
  this.checkedJobs.set(`${host}\n${serial}`, {
715
731
  ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
716
732
  });
733
+ if (!this.flightRecords.accept(flightKey(host, serial), remotePath)) {
734
+ this.recordFlightDispatch(host, serial, remotePath, requirements, file);
735
+ this.flightRecords.accept(flightKey(host, serial), remotePath);
736
+ }
717
737
  this.clearedErrors.delete(serial);
718
738
  }
719
739
  /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
720
740
  observeReport(host, serial, raw) {
741
+ if (raw)
742
+ this.flightRecords.observe(flightKey(host, serial), raw);
721
743
  const key = `${host}\n${serial}`;
722
744
  const checked = this.checkedJobs.get(key);
723
745
  if (!checked || !raw || typeof raw.gcode_state !== "string")
@@ -1106,6 +1128,7 @@ export class BambuImplementation {
1106
1128
  assertActive();
1107
1129
  if (legacyContainer) {
1108
1130
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1131
+ this.recordFlightDispatch(host, serial, remoteProjectPath, requirements, resumeFile);
1109
1132
  markPrintCommandSent();
1110
1133
  try {
1111
1134
  await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath }));
@@ -1193,6 +1216,7 @@ export class BambuImplementation {
1193
1216
  };
1194
1217
  }
1195
1218
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1219
+ this.recordFlightDispatch(host, serial, remoteProjectPath, requirements, resumeFile);
1196
1220
  markPrintCommandSent();
1197
1221
  try {
1198
1222
  await printer.publish(projectFileCmd);
@@ -1799,6 +1823,7 @@ export class BambuImplementation {
1799
1823
  const printer = await this.getPrinter(host, serial, token);
1800
1824
  assertActive();
1801
1825
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1826
+ this.recordFlightDispatch(host, serial, remotePath, requirements, resumeFile);
1802
1827
  markPrintCommandSent();
1803
1828
  try {
1804
1829
  await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath }));
@@ -1990,12 +2015,13 @@ export class BambuImplementation {
1990
2015
  const timeoutMs = options.timeoutMs ?? 8000;
1991
2016
  const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
1992
2017
  if (stream && !stream.stopped) {
1993
- const jpeg = await stream.latest(Math.min(timeoutMs, 10000));
1994
- if (!jpeg)
2018
+ const frame = await snapshotFrame(stream, timeoutMs, options.capturedAfter);
2019
+ if (frame.status !== "frame" || !frame.base64)
1995
2020
  throw new Error("The active camera stream has not produced a live frame");
2021
+ const jpeg = Buffer.from(frame.base64, "base64");
1996
2022
  if (options.savePath)
1997
2023
  await (await import("node:fs/promises")).writeFile(options.savePath, jpeg);
1998
- return { status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport,
2024
+ return { status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport, capturedAt: frame.capturedAt,
1999
2025
  ...(options.savePath ? { savedTo: options.savePath } : {}) };
2000
2026
  }
2001
2027
  const model = (options.bambuModel ?? "").toLowerCase();
@@ -31,6 +31,8 @@ export declare function extrusionSegments(gcode: string): {
31
31
  segments: Segment[];
32
32
  layers: number;
33
33
  };
34
+ /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
35
+ export declare function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined;
34
36
  /** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
35
37
  export declare function renderPrintPreview(gcode: string, colours?: unknown[]): PrintPreview | undefined;
36
38
  /** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
@@ -198,7 +198,7 @@ function parameterWords(text) {
198
198
  return words;
199
199
  }
200
200
  /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
201
- function arcCentre(x, y, tx, ty, clockwise, i, j, r) {
201
+ export function arcCentre(x, y, tx, ty, clockwise, i, j, r) {
202
202
  if (i !== undefined || j !== undefined)
203
203
  return [x + (i ?? 0), y + (j ?? 0)];
204
204
  if (r === undefined || r === 0 || (tx === x && ty === y))
@@ -0,0 +1,7 @@
1
+ /** Encode text for a quoted XML attribute, preserving whitespace through XML parsing. */
2
+ export declare function xmlAttribute(value: string): string;
3
+ /** Studio 02.08.02.61 bbs_3mf.cpp writes object opt_serialize values without XML escaping.
4
+ * Only repair its single-line key/value metadata form. Unexpected malformed XML fails closed. */
5
+ export declare function escapedModelSettings(xml: string): Promise<string>;
6
+ /** Normalize only a newly produced/restored slice, before caching or handing it to the client. */
7
+ export declare function normalize3mfMetadata(filePath: string): Promise<void>;
@@ -0,0 +1,61 @@
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
+ /** Encode text for a quoted XML attribute, preserving whitespace through XML parsing. */
7
+ export function xmlAttribute(value) {
8
+ const entities = { "&": "&amp;", '"': "&quot;", "'": "&apos;", "<": "&lt;", ">": "&gt;", "\t": "&#9;", "\n": "&#10;", "\r": "&#13;" };
9
+ return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replace(/[&"'<>\t\r\n]/g, char => entities[char]);
10
+ }
11
+ const parses = (xml) => {
12
+ try {
13
+ let root;
14
+ const parser = new SaxesParser();
15
+ parser.on("error", error => { throw error; });
16
+ parser.on("opentag", node => { root ?? (root = node.name); });
17
+ parser.write(xml).close();
18
+ return root === "config";
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ /** Studio 02.08.02.61 bbs_3mf.cpp writes object opt_serialize values without XML escaping.
25
+ * Only repair its single-line key/value metadata form. Unexpected malformed XML fails closed. */
26
+ export async function escapedModelSettings(xml) {
27
+ if (Buffer.byteLength(xml) > 16 * 1024 * 1024)
28
+ throw Error("3MF model settings exceed the 16 MiB XML limit.");
29
+ if (await parses(xml))
30
+ return xml;
31
+ const lines = xml.split(/(?<=\n)/);
32
+ for (let i = 0; i < lines.length; i++) {
33
+ const match = /^([ \t]*<metadata\s+key="[\w.:-]+"\s+value=")(.*)("\s*\/>[ \t]*\r?\n?)$/.exec(lines[i]);
34
+ if (!match || await parses('<config>' + lines[i] + '</config>'))
35
+ continue;
36
+ lines[i] = match[1] + xmlAttribute(match[2]) + match[3];
37
+ }
38
+ const repaired = lines.join('');
39
+ if (!await parses(repaired))
40
+ throw Error("Slicer produced malformed Metadata/model_settings.config; no safe attribute repair is available.");
41
+ return repaired;
42
+ }
43
+ /** Normalize only a newly produced/restored slice, before caching or handing it to the client. */
44
+ export async function normalize3mfMetadata(filePath) {
45
+ const { zip } = await readSafe3mfArchive(filePath);
46
+ const entry = zip.file('Metadata/model_settings.config');
47
+ if (!entry)
48
+ return;
49
+ const original = await entry.async('string'), repaired = await escapedModelSettings(original);
50
+ if (repaired === original)
51
+ return;
52
+ zip.file(entry.name, repaired);
53
+ const staged = filePath + '.' + randomUUID() + '.xml-tmp';
54
+ try {
55
+ await fs.writeFile(staged, await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }), { flag: 'wx', mode: 0o600 });
56
+ await fs.rename(staged, filePath);
57
+ }
58
+ finally {
59
+ await fs.rm(staged, { force: true }).catch(() => { });
60
+ }
61
+ }
@@ -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';
@@ -1732,11 +1733,13 @@ export class STLManipulator extends EventEmitter {
1732
1733
  if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1733
1734
  throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1734
1735
  }
1735
- if (cacheKey && !restored && fs.existsSync(outputFilePath))
1736
- await keepSlice(cacheKey, cacheRun);
1737
1736
  if (!fs.existsSync(outputFilePath)) {
1738
1737
  throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1739
1738
  }
1739
+ if (/\.3mf$/i.test(outputFilePath))
1740
+ await normalize3mfMetadata(outputFilePath);
1741
+ if (cacheKey && !restored)
1742
+ await keepSlice(cacheKey, cacheRun);
1740
1743
  if (progressCallback)
1741
1744
  progressCallback(100, "Slicing completed successfully");
1742
1745
  this.emit('operationComplete', {
@@ -24,6 +24,8 @@ export const TOOL_ANNOTATIONS = {
24
24
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
25
25
  list_printer_files: READ_OUTSIDE,
26
26
  counterpart_print_progress: READ_OUTSIDE,
27
+ counterpart_print_record: READ_LOCAL,
28
+ counterpart_print_assess: hints(false, false, true, false),
27
29
  counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
28
30
  counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
29
31
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.90",
3
+ "version": "1.1.91",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -55,6 +55,7 @@
55
55
  "jszip": "^3.10.2",
56
56
  "mqtt": "^5.16.1",
57
57
  "patch-package": "8.0.1",
58
+ "saxes": "^6.0.0",
58
59
  "sharp": "0.35.5",
59
60
  "three": "^0.173.0",
60
61
  "xml2js": "^0.6.2"