bambu-printer-mcp 1.1.90 → 1.1.92

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 (86) hide show
  1. package/CONTRIBUTORS.md +2 -0
  2. package/README.md +48 -3
  3. package/dist/bambu-native.js +1 -1
  4. package/dist/cad/contracts.js +16 -7
  5. package/dist/cad/examples.d.ts +2 -1
  6. package/dist/cad/examples.js +13 -10
  7. package/dist/cad/serial.d.ts +1 -1
  8. package/dist/cad/serial.js +4 -6
  9. package/dist/cad-engine.js +17 -12
  10. package/dist/counterpart/flight-record.d.ts +155 -0
  11. package/dist/counterpart/flight-record.js +831 -0
  12. package/dist/counterpart/flight-tools.d.ts +213 -0
  13. package/dist/counterpart/flight-tools.js +232 -0
  14. package/dist/counterpart/fresh-frame.d.ts +16 -0
  15. package/dist/counterpart/fresh-frame.js +26 -0
  16. package/dist/counterpart/make-3mf.js +1 -4
  17. package/dist/counterpart/physical-evidence.d.ts +70 -0
  18. package/dist/counterpart/physical-evidence.js +103 -0
  19. package/dist/counterpart/print-geometry.d.ts +13 -0
  20. package/dist/counterpart/print-geometry.js +181 -0
  21. package/dist/counterpart/remote.js +2 -0
  22. package/dist/counterpart/schemas.d.ts +32 -0
  23. package/dist/counterpart/schemas.js +2 -0
  24. package/dist/counterpart/visual-evidence.d.ts +38 -0
  25. package/dist/counterpart/visual-evidence.js +155 -0
  26. package/dist/index.js +63 -24
  27. package/dist/printers/bambu.d.ts +15 -2
  28. package/dist/printers/bambu.js +64 -12
  29. package/dist/safety/limits.d.ts +6 -0
  30. package/dist/safety/limits.js +8 -0
  31. package/dist/safety/print-file.js +2 -2
  32. package/dist/safety/print-preview.d.ts +2 -0
  33. package/dist/safety/print-preview.js +1 -1
  34. package/dist/safety/printer-state.d.ts +4 -0
  35. package/dist/safety/printer-state.js +14 -1
  36. package/dist/slicer/3mf-xml.d.ts +7 -0
  37. package/dist/slicer/3mf-xml.js +61 -0
  38. package/dist/stl/stl-manipulator.js +5 -2
  39. package/dist/studio-print-options.d.ts +9 -0
  40. package/dist/studio-print-options.js +34 -2
  41. package/dist/tool-annotations.js +2 -0
  42. package/package.json +2 -1
  43. package/src/bambu-native.ts +1 -1
  44. package/src/cad/contracts.ts +17 -7
  45. package/src/cad/examples/bag_clip.py +1 -0
  46. package/src/cad/examples/bistable_clicker.py +1 -0
  47. package/src/cad/examples/broom_grip.py +61 -0
  48. package/src/cad/examples/cable_clip.py +1 -0
  49. package/src/cad/examples/chainmail.py +1 -0
  50. package/src/cad/examples/desk_clamp_hook.py +91 -0
  51. package/src/cad/examples/desk_edge_cable_holder.py +55 -0
  52. package/src/cad/examples/drawer_divider.py +56 -0
  53. package/src/cad/examples/hinged_box.py +1 -0
  54. package/src/cad/examples/knurled_knob.py +1 -0
  55. package/src/cad/examples/loft_handle.py +1 -0
  56. package/src/cad/examples/organizer_tray.py +41 -0
  57. package/src/cad/examples/phone_stand.py +1 -0
  58. package/src/cad/examples/plant_pot.py +53 -0
  59. package/src/cad/examples/shelf_bracket.py +53 -0
  60. package/src/cad/examples/swept_hook.py +1 -0
  61. package/src/cad/examples/threaded_jar.py +1 -0
  62. package/src/cad/examples/trigger_capo.py +1 -0
  63. package/src/cad/examples/wall_hook.py +1 -0
  64. package/src/cad/examples.ts +13 -10
  65. package/src/cad/geometry.py +6 -0
  66. package/src/cad/serial.ts +4 -6
  67. package/src/cad-engine.ts +9 -3
  68. package/src/counterpart/flight-record.ts +984 -0
  69. package/src/counterpart/flight-tools.ts +282 -0
  70. package/src/counterpart/fresh-frame.ts +45 -0
  71. package/src/counterpart/make-3mf.ts +1 -5
  72. package/src/counterpart/physical-evidence.ts +185 -0
  73. package/src/counterpart/print-geometry.ts +192 -0
  74. package/src/counterpart/remote.ts +2 -0
  75. package/src/counterpart/schemas.ts +3 -0
  76. package/src/counterpart/visual-evidence.ts +212 -0
  77. package/src/index.ts +61 -21
  78. package/src/printers/bambu.ts +64 -10
  79. package/src/safety/limits.ts +8 -0
  80. package/src/safety/print-file.ts +2 -2
  81. package/src/safety/print-preview.ts +1 -1
  82. package/src/safety/printer-state.ts +13 -1
  83. package/src/slicer/3mf-xml.ts +52 -0
  84. package/src/stl/stl-manipulator.ts +4 -1
  85. package/src/studio-print-options.ts +33 -2
  86. package/src/tool-annotations.ts +2 -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";
@@ -17,7 +20,7 @@ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, d
17
20
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements, type PrinterStateRequirements } from "../safety/printer-state.js";
18
21
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
19
22
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
20
- import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
23
+ import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
21
24
  import { Client as FTPClient } from "basic-ftp";
22
25
  import { uploadBytes } from "./ftp-upload.js";
23
26
  import * as mqtt from "mqtt";
@@ -154,6 +157,19 @@ const MODEL_ID_TO_NAME: Record<string, string> = {
154
157
 
155
158
  const H2_MODEL_NAMES = new Set(["h2", "h2c", "h2d", "h2dpro", "h2d pro", "h2s", "x2d"]);
156
159
 
160
+ /**
161
+ * X1C firmware 01.12.00.00 was seen refusing every FTPS STOR with
162
+ * "553 Could not create file." (card ready and writable, Developer Mode on)
163
+ * while Bambu Studio's networking plug-in still printed. Name that route.
164
+ */
165
+ export function ftpsRefusalHint(error: unknown, model: string | undefined): string {
166
+ const message = error instanceof Error ? error.message : String(error);
167
+ if (normalizeModel(model) !== "x1c" || ((error as { code?: unknown })?.code !== 553 && !/^553\b/.test(message))) return "";
168
+ return ' X1C firmware 01.12.00.00 has been seen refusing every direct FTPS upload this way. ' +
169
+ 'Retry with connection_mode: "bambu_native", which uploads through Bambu Studio\'s networking plug-in ' +
170
+ '(on macOS, first run npm run build:native in the package directory; on Linux, bambu-printer-mcp-native-setup).';
171
+ }
172
+
157
173
  export function assertDirectPrintSupported(model: string | undefined, serial?: string): void {
158
174
  if (model?.trim().toLowerCase() === "x2d" || serial?.trim().toUpperCase().startsWith("20P")) {
159
175
  throw new Error(
@@ -598,6 +614,7 @@ export type ProgressReport = { raw: Record<string, any>; receivedAt: number };
598
614
  /** The inspected bytes and limits of a started job, for the resume prompt and byte check. */
599
615
  export type CheckedFile = {
600
616
  sha256: string;
617
+ expected?: PrintGeometry;
601
618
  /** A project's printed plate: its number and the SHA-256 of its Metadata/plate_<index>.gcode. */
602
619
  plate?: { index: number; sha256: string };
603
620
  model: string;
@@ -716,13 +733,21 @@ function reportsJob(raw: Record<string, any>, remotePath: string): boolean {
716
733
  export async function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile> {
717
734
  const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
718
735
  let plate: CheckedFile["plate"];
736
+ let expected: PrintGeometry | undefined;
719
737
  const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
720
738
  if (plateNumber && /\.3mf$/i.test(filePath)) {
721
739
  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") };
740
+ if (entry) {
741
+ const bytes = await entry.async("nodebuffer");
742
+ plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(bytes).digest("hex") };
743
+ if (bytes.length <= 64 * 1024 * 1024) expected = geometryFromGcode(bytes.toString("utf8"));
744
+ }
745
+ } else if (!/\.3mf$/i.test(filePath)) {
746
+ expected = await geometryFromFile(filePath);
723
747
  }
748
+
724
749
  return {
725
- sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
750
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), ...(expected ? { expected } : {}), model: inspection.model,
726
751
  maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
727
752
  materials: [...new Set(used.length ? used : inspection.materials)],
728
753
  };
@@ -753,6 +778,7 @@ export type PrintPreflight = { finishedJob?: string; serial: string; model: stri
753
778
  export {cameraFrameParser} from "./camera-wire.js";
754
779
 
755
780
  export class BambuImplementation {
781
+ readonly flightRecords = new FlightRecords();
756
782
  private printerStore: BambuClientStore;
757
783
  readonly cameraStreams = new CameraStreams();
758
784
  /**
@@ -846,16 +872,26 @@ export class BambuImplementation {
846
872
  * verified: a resume then re-reads it if it can and otherwise matches the
847
873
  * unique name, as KAN-216 does for firmware that cannot download a file.
848
874
  */
875
+ /** At the existing send-authorization boundary: record evidence even if the reply/helper is lost. */
876
+ recordFlightDispatch(host:string,serial:string,remotePath:string,requirements:PrinterStateRequirements,file:CheckedFile):void {
877
+ this.flightRecords.begin(flightKey(host,serial),{sha256:file.sha256,jobName:remotePath,mapping:requirements.amsMapping,materials:file.materials,plate:file.plate,expected:file.expected});
878
+ }
879
+
849
880
  recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements, file: CheckedFile, uploadedHere = true): void {
850
881
  if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? "")) throw new Error("A started job needs the SHA-256 of its inspected bytes.");
851
882
  this.checkedJobs.set(`${host}\n${serial}`, {
852
883
  ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
853
884
  });
885
+ if(!this.flightRecords.accept(flightKey(host,serial),remotePath)){
886
+ this.recordFlightDispatch(host,serial,remotePath,requirements,file);
887
+ this.flightRecords.accept(flightKey(host,serial),remotePath);
888
+ }
854
889
  this.clearedErrors.delete(serial);
855
890
  }
856
891
 
857
892
  /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
858
893
  observeReport(host: string, serial: string, raw: Record<string, any> | undefined): void {
894
+ if (raw) this.flightRecords.observe(flightKey(host, serial), raw);
859
895
  const key = `${host}\n${serial}`;
860
896
  const checked = this.checkedJobs.get(key);
861
897
  if (!checked || !raw || typeof raw.gcode_state !== "string") return;
@@ -1119,12 +1155,13 @@ export class BambuImplementation {
1119
1155
  });
1120
1156
  const resumeFile = await checkedFile(inspection, options.filePath);
1121
1157
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1122
- const studio = resolveStudioPrintOptions(model, {
1158
+ const caller: CallerPrintOptions = {
1123
1159
  bedLeveling: options.bedLeveling, flowCalibration: options.flowCalibration,
1124
1160
  vibrationCalibration: options.vibrationCalibration, layerInspect: options.layerInspect,
1125
1161
  autoBedLeveling: options.autoBedLeveling, autoFlowCali: options.autoFlowCali,
1126
1162
  autoOffsetCali: options.autoOffsetCali, extruderCaliManualMode: options.extruderCaliManualMode,
1127
- } satisfies CallerPrintOptions, { usedNozzles: usedNozzleCount(inspection) });
1163
+ };
1164
+ const studio = resolveStudioPrintOptions(model, caller, { usedNozzles: usedNozzleCount(inspection) });
1128
1165
  const projectMetadata = await this.resolveProjectFileMetadata(
1129
1166
  options.filePath,
1130
1167
  options.plateIndex,
@@ -1262,7 +1299,7 @@ export class BambuImplementation {
1262
1299
  await this.ftpUpload(host, token, options.filePath, remoteUploadPath, options.onUploadProgress);
1263
1300
  } catch (error) {
1264
1301
  // Nothing has been sent to the printer but (part of) a file, so the print certainly did not start.
1265
- throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started.`);
1302
+ throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started.${ftpsRefusalHint(error, model)}`);
1266
1303
  }
1267
1304
  // Uploads can be long. Recheck current state before the command is dispatched.
1268
1305
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
@@ -1273,12 +1310,14 @@ export class BambuImplementation {
1273
1310
  assertActive();
1274
1311
  if (legacyContainer) {
1275
1312
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1313
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1276
1314
  markPrintCommandSent();
1277
1315
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath })); } catch (error) { watcher.dispose(); throw error; }
1278
1316
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
1279
1317
  const dispatch = await watcher.settled();
1280
1318
  return {
1281
1319
  status: "success", dispatch, remoteProjectPath,
1320
+ calibration: directPrintOptionReport(caller, studio, {}),
1282
1321
  message: dispatch === "started"
1283
1322
  ? `The printer accepted and started the checked gcode.3mf print: ${options.projectName}`
1284
1323
  : `Uploaded the checked gcode.3mf and sent the print command for ${options.projectName}; the printer has not reported starting yet. ` +
@@ -1354,7 +1393,9 @@ export class BambuImplementation {
1354
1393
  };
1355
1394
  }
1356
1395
 
1396
+ const calibration = directPrintOptionReport(caller, studio, projectFileCmd.print);
1357
1397
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1398
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1358
1399
  markPrintCommandSent();
1359
1400
  try { await printer.publish(projectFileCmd); } catch (error) { watcher.dispose(); throw error; }
1360
1401
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
@@ -1363,6 +1404,7 @@ export class BambuImplementation {
1363
1404
 
1364
1405
  return {
1365
1406
  status: "success",
1407
+ calibration,
1366
1408
  dispatch,
1367
1409
  message: dispatch === "started"
1368
1410
  ? `The printer accepted and started the checked 3MF print: ${options.projectName}`
@@ -1982,7 +2024,15 @@ export class BambuImplementation {
1982
2024
  assertActive();
1983
2025
  const destination = path.posix.join(path.posix.dirname(remotePath), uniquePrintName(remotePath));
1984
2026
  if (upload) await upload(snapshot, destination, assertActive);
1985
- else await this.ftpUpload(host, token, snapshot, `/${destination}`);
2027
+ else {
2028
+ try {
2029
+ await this.ftpUpload(host, token, snapshot, `/${destination}`);
2030
+ } catch (error) {
2031
+ const hint = ftpsRefusalHint(error, model);
2032
+ if (hint && error instanceof Error) error.message += hint;
2033
+ throw error;
2034
+ }
2035
+ }
1986
2036
  return { status: "success", uploaded: true, remotePath: destination, printRequested: false, inspected: printable };
1987
2037
  }));
1988
2038
  }
@@ -2016,6 +2066,7 @@ export class BambuImplementation {
2016
2066
  const printer = await this.getPrinter(host, serial, token);
2017
2067
  assertActive();
2018
2068
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
2069
+ this.recordFlightDispatch(host,serial,remotePath,requirements,resumeFile);
2019
2070
  markPrintCommandSent();
2020
2071
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath })); } catch (error) { watcher.dispose(); throw error; }
2021
2072
  this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
@@ -2174,6 +2225,7 @@ export class BambuImplementation {
2174
2225
  token: string,
2175
2226
  options: {
2176
2227
  savePath?: string;
2228
+ capturedAfter?: string;
2177
2229
  timeoutMs?: number;
2178
2230
  bambuModel?: string;
2179
2231
  /**
@@ -2196,6 +2248,7 @@ export class BambuImplementation {
2196
2248
  sizeBytes: number;
2197
2249
  base64: string;
2198
2250
  savedTo?: string;
2251
+ capturedAt?: string;
2199
2252
  width?: number;
2200
2253
  height?: number;
2201
2254
  note?: string;
@@ -2204,10 +2257,11 @@ export class BambuImplementation {
2204
2257
  const timeoutMs = options.timeoutMs ?? 8_000;
2205
2258
  const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
2206
2259
  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");
2260
+ const frame = await snapshotFrame(stream,timeoutMs,options.capturedAfter);
2261
+ if (frame.status!=="frame"||!frame.base64) throw new Error("The active camera stream has not produced a live frame");
2262
+ const jpeg=Buffer.from(frame.base64,"base64");
2209
2263
  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,
2264
+ return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport, capturedAt:frame.capturedAt,
2211
2265
  ...(options.savePath ? {savedTo: options.savePath} : {})};
2212
2266
  }
2213
2267
  const model = (options.bambuModel ?? "").toLowerCase();
@@ -40,6 +40,14 @@ export function isDualNozzleModel(model: unknown): boolean {
40
40
  const normalized = normalizeModel(model);
41
41
  return normalized !== undefined && DUAL_NOZZLE_MODELS.has(normalized);
42
42
  }
43
+ /** File models a printer accepts besides its own, keyed by the printer's observed model.
44
+ * A P1P with the enclosure upgrade kit still reports itself as a P1P, while its jobs are sliced with the P1S
45
+ * preset. Bambu Studio sends those jobs: resources/printers/C11.json (P1P) lists C12 (P1S) in compatible_machine.
46
+ * The two models have identical MACHINE_LIMITS, and the file is still checked against the printer's own limits. */
47
+ export const ACCEPTED_FILE_MODELS: Readonly<Record<string, ReadonlySet<string>>> = {p1p: new Set(['p1s'])};
48
+ export function fileModelFitsPrinter(fileModel: string, printerModel: string): boolean {
49
+ return fileModel === printerModel || ACCEPTED_FILE_MODELS[printerModel]?.has(fileModel) === true;
50
+ }
43
51
  export function normalizeModel(value: unknown): string | undefined {
44
52
  if (typeof value !== 'string') return undefined;
45
53
  let model = value.trim().toLowerCase().replace(/^bambu\s*(?:lab\s*)?/, '').replace(/[\s_-]/g, '');
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readBoundedPrintFile, loadSafe3mfArchive } from './archive.js';
3
3
  import { projectFilaments, type ProjectFilament } from "../ams-mapping.js";
4
- import { MACHINE_LIMITS, isDualNozzleModel, normalizeMaterial, normalizeModel, validateStartupPurgeTemperature, validateTemperature } from './limits.js';
4
+ import { MACHINE_LIMITS, fileModelFitsPrinter, isDualNozzleModel, normalizeMaterial, normalizeModel, validateStartupPurgeTemperature, validateTemperature } from './limits.js';
5
5
 
6
6
  export interface PrintFileInspection {
7
7
  model: string;
@@ -240,7 +240,7 @@ export async function inspectPrintFile(filePath: string, options: {model:string;
240
240
  const metadata:Metadata[]=[project,...headers];
241
241
  validateFffJob([...metadata,plate]);
242
242
  const declaredModel=consistent(metadataValues(metadata,['printer_model']),normalizeModel,'printer model');
243
- if(declaredModel!==model) return fail(`file model ${declaredModel} contradicts requested model ${model}`);
243
+ if(!fileModelFitsPrinter(declaredModel,model)) return fail(`file model ${declaredModel} contradicts requested model ${model}`);
244
244
  const nozzleDiameters=consistent(metadataValues(metadata,['nozzle_diameter']),value=>{
245
245
  const values=list(value);return values.length && values.every(v=>NUMBER.test(v) && [0.2,0.4,0.6,0.8].includes(Number(v)))?values.map(Number):undefined;
246
246
  },'nozzle diameter');
@@ -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);
@@ -366,13 +366,16 @@ function trayRange(value: unknown, label: string): number | undefined {
366
366
  /** Dual-nozzle printers report one virtual external slot per nozzle, numbered as Bambu
367
367
  * Studio does (VIRTUAL_TRAY_MAIN_ID 255 = right/main nozzle, VIRTUAL_TRAY_DEPUTY_ID 254 =
368
368
  * left/deputy nozzle), so the requested tray selects its slot. Single-nozzle printers keep
369
- * requiring exactly one slot 254 report, then the legacy vt_tray field. */
369
+ * requiring exactly one external slot report, then the legacy vt_tray field. */
370
370
  function externalTray(raw: Record<string,any>, trayIndex: number, model: string): Record<string,any> | undefined {
371
371
  const slots = raw.vir_slot;
372
372
  const dualNozzle = isDualNozzleModel(model);
373
373
  if (Array.isArray(slots)) {
374
374
  const selected = slots.filter((slot:any) => Number(slot?.id) === trayIndex);
375
375
  if (selected.length === 1 && (dualNozzle || slots.length === 1)) return selected[0];
376
+ // X1C firmware 01.12 reports its single external slot as id 255 (ams_id 255, slot 0) while
377
+ // tray_now is 254. One external slot on a single-nozzle printer is unambiguous.
378
+ if (!dualNozzle && slots.length === 1 && [254,255].includes(Number(slots[0]?.id)) && [254,255].includes(trayIndex)) return slots[0];
376
379
  if (dualNozzle && selected.length === 0 && slots.length > 0) throw new Error(`External spool ${trayIndex} is not in the fresh per-nozzle report; cannot verify the selected material.`);
377
380
  if (slots.length > 0) throw new Error("External spool report is ambiguous for this nozzle; cannot verify the selected material.");
378
381
  }
@@ -526,3 +529,12 @@ export function externalStorageState(raw: unknown): ExternalStorageState {
526
529
  }
527
530
  return state;
528
531
  }
532
+
533
+ /** Studio DeviceManager.cpp at 926a7192574b: fun2 bit 0 advertises eMMC printing.
534
+ * Use only a fresh raw report at the caller. Reject malformed flags rather than
535
+ * stripping arbitrary characters as Studio's general-purpose parser does. */
536
+ export function internalPrintingSupported(raw: unknown): boolean {
537
+ if (!object(raw) || typeof raw.fun2 !== "string") return false;
538
+ const flags = raw.fun2.trim().replace(/^0x/i, "");
539
+ return /^[0-9a-f]+$/i.test(flags) && (parseInt(flags.slice(-1), 16) & 1) === 1;
540
+ }
@@ -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', {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The print options Bambu Studio's Send dialog sends, resolved the way it
3
- * resolves them, so every print route sends what Bambu's own Print button
4
- * would. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
3
+ * resolves them, for the vendor SDK. Direct routes report which options their verified
4
+ * wire format can carry; this does not establish SDK packet equivalence. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
5
5
  * the hidden-HMS and stage tables are pinned to:
6
6
  *
7
7
  * - SelectMachine.cpp:3344-3356 `set_print_config(bed_type,
@@ -199,3 +199,34 @@ export function usedNozzleCount(inspection: { usedFilamentPositions: number[]; f
199
199
  const nozzles = inspection.usedFilamentPositions.map(position => inspection.filamentNozzleIndices?.[position]).filter((value): value is number => Number.isInteger(value));
200
200
  return nozzles.length === inspection.usedFilamentPositions.length && nozzles.length ? new Set(nozzles).size : undefined;
201
201
  }
202
+
203
+ /** Report only verified direct-wire fields. A task boolean is not an SDK mode.
204
+ * null means this route does not transmit that option, not off/auto/unknown hardware state. */
205
+ export function directPrintOptionReport(caller: CallerPrintOptions, resolved: StudioPrintOptions, packet: Record<string, unknown>) {
206
+ const fields = {
207
+ bedLeveling: ["task_bed_leveling", "bed_leveling"],
208
+ flowCalibration: ["task_flow_cali", "flow_cali"],
209
+ vibrationCalibration: ["task_vibration_cali", "vibration_cali"],
210
+ layerInspect: ["task_layer_inspect", "layer_inspect"],
211
+ autoBedLeveling: ["auto_bed_leveling", "auto_bed_leveling"],
212
+ autoFlowCali: ["auto_flow_cali", "auto_flow_cali"],
213
+ autoOffsetCali: ["auto_offset_cali", "nozzle_offset_cali"],
214
+ extruderCaliManualMode: ["extruder_cali_manual_mode", "extrude_cali_manual_mode"],
215
+ } as const;
216
+ const requested: CallerPrintOptions = {};
217
+ const transmitted: Record<string, boolean | number | null> = {};
218
+ const unsupported: string[] = [];
219
+ for (const key of Object.keys(fields) as Array<keyof CallerPrintOptions>) {
220
+ const [sdk, wire] = fields[key];
221
+ if (caller[key] !== undefined) Object.assign(requested, { [key]: caller[key] });
222
+ const value = packet[wire];
223
+ transmitted[sdk] = typeof value === "boolean" || typeof value === "number" ? value : null;
224
+ if (caller[key] !== undefined && transmitted[sdk] === null) unsupported.push(key);
225
+ }
226
+ const omitted = Object.keys(transmitted).filter(key => transmitted[key] === null);
227
+ const warning = omitted.length
228
+ ? `Direct print options not transmitted: ${omitted.join(", ")}. Task booleans are not equivalent to Studio integer modes.` +
229
+ (unsupported.length ? ` Requested overrides unsupported by this route: ${unsupported.join(", ")}. Use a vendor bridge/native route that supports these options if required.` : "")
230
+ : undefined;
231
+ return { requested, resolved, transmitted, unsupported, ...(warning ? { warning } : {}) };
232
+ }
@@ -46,6 +46,8 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
46
46
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
47
47
  list_printer_files: READ_OUTSIDE,
48
48
  counterpart_print_progress: READ_OUTSIDE,
49
+ counterpart_print_record: READ_LOCAL,
50
+ counterpart_print_assess: hints(false,false,true,false),
49
51
  counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
50
52
  counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
51
53
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.