bambu-printer-mcp 1.1.47 → 1.1.49

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 (45) hide show
  1. package/README.md +117 -3
  2. package/dist/blender-mcp-bridge.d.ts +15 -0
  3. package/dist/blender-mcp-bridge.js +21 -3
  4. package/dist/counterpart/info.d.ts +10 -0
  5. package/dist/counterpart/info.js +34 -0
  6. package/dist/counterpart/make-3mf.d.ts +16 -0
  7. package/dist/counterpart/make-3mf.js +219 -0
  8. package/dist/counterpart/progress.d.ts +28 -0
  9. package/dist/counterpart/progress.js +254 -0
  10. package/dist/counterpart/schemas.d.ts +322 -0
  11. package/dist/counterpart/schemas.js +124 -0
  12. package/dist/fusion-mcp-bridge.d.ts +182 -0
  13. package/dist/fusion-mcp-bridge.js +557 -0
  14. package/dist/index.js +192 -12
  15. package/dist/printers/bambu-stages.d.ts +7 -0
  16. package/dist/printers/bambu-stages.js +89 -0
  17. package/dist/printers/bambu.d.ts +76 -4
  18. package/dist/printers/bambu.js +298 -38
  19. package/dist/printers/camera-models.d.ts +7 -0
  20. package/dist/printers/camera-models.js +18 -0
  21. package/dist/safety/hms-messages.d.ts +42 -0
  22. package/dist/safety/hms-messages.js +6194 -0
  23. package/dist/safety/printer-state.d.ts +18 -0
  24. package/dist/safety/printer-state.js +3 -3
  25. package/dist/slicer/process-overrides.d.ts +12 -0
  26. package/dist/slicer/process-overrides.js +33 -0
  27. package/dist/slicer/remote-slicer.js +2 -0
  28. package/dist/stl/stl-manipulator.d.ts +2 -0
  29. package/dist/stl/stl-manipulator.js +19 -0
  30. package/package.json +1 -1
  31. package/src/blender-mcp-bridge.ts +22 -3
  32. package/src/counterpart/info.ts +36 -0
  33. package/src/counterpart/make-3mf.ts +220 -0
  34. package/src/counterpart/progress.ts +254 -0
  35. package/src/counterpart/schemas.ts +154 -0
  36. package/src/fusion-mcp-bridge.ts +545 -0
  37. package/src/index.ts +199 -12
  38. package/src/printers/bambu-stages.ts +90 -0
  39. package/src/printers/bambu.ts +316 -38
  40. package/src/printers/camera-models.ts +18 -0
  41. package/src/safety/hms-messages.ts +6198 -0
  42. package/src/safety/printer-state.ts +4 -4
  43. package/src/slicer/process-overrides.ts +42 -0
  44. package/src/slicer/remote-slicer.ts +2 -0
  45. package/src/stl/stl-manipulator.ts +22 -0
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { isFinishedP1SJob, isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
3
3
  import fs from "node:fs/promises";
4
- import { readFileSync, existsSync } from "node:fs";
4
+ import { createReadStream, readFileSync, existsSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import os from "node:os";
7
7
  import { Readable } from "node:stream";
@@ -11,6 +11,7 @@ import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safet
11
11
  import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
12
12
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements } from "../safety/printer-state.js";
13
13
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
14
+ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
14
15
  import { Client as FTPClient } from "basic-ftp";
15
16
  import * as mqtt from "mqtt";
16
17
  import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, UpdateStateCommand, } from "bambu-node";
@@ -36,6 +37,8 @@ function loadClientCreds() {
36
37
  }
37
38
  const CLIENT_CREDS = loadClientCreds();
38
39
  const COMMAND_SETTLE_MS = 300;
40
+ /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
41
+ const STALE_REPORT_MS = 300000;
39
42
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
40
43
  const COMMAND_VERIFICATION_HMS = { attr: 0x05000500, code: 0x00010007 };
41
44
  const COMMAND_REJECTED_MESSAGE = "The printer rejected the print command (HMS 0500-0500-0001-0007, \"MQTT command verification failed\"). " +
@@ -230,10 +233,16 @@ function ftpsSecureOptions(host) {
230
233
  return opts;
231
234
  }
232
235
  class BambuClientStore {
233
- constructor() {
236
+ /** Sees every merged report, so a resume record notices a job ending even when nobody polls. */
237
+ constructor(onReport) {
238
+ this.onReport = onReport;
234
239
  this.printers = new Map();
235
240
  this.initialConnectionPromises = new Map();
236
241
  this.reportSnapshots = new Map();
242
+ /** When the last MQTT report for each printer arrived (ms since epoch). */
243
+ this.reportTimes = new Map();
244
+ /** When PushAll was last sent for a stale cache, so a quiet printer is not asked repeatedly. */
245
+ this.refreshTimes = new Map();
237
246
  this.initialReportPromises = new Map();
238
247
  this.initialReportResolvers = new Map();
239
248
  }
@@ -262,15 +271,43 @@ class BambuClientStore {
262
271
  }
263
272
  const previous = this.reportSnapshots.get(key) || {};
264
273
  this.reportSnapshots.set(key, { ...previous, ...update });
274
+ this.reportTimes.set(key, Date.now());
265
275
  this.resolveInitialReport(key);
266
276
  }
277
+ reportObserved(host, serial, key) {
278
+ const report = this.reportSnapshots.get(key);
279
+ if (!report || !this.onReport)
280
+ return;
281
+ try {
282
+ this.onReport(host, serial, report);
283
+ }
284
+ catch { /* an observer never breaks report handling */ }
285
+ }
267
286
  clearPrinterState(key) {
268
287
  this.printers.delete(key);
269
288
  this.initialConnectionPromises.delete(key);
270
289
  this.reportSnapshots.delete(key);
290
+ this.reportTimes.delete(key);
291
+ this.refreshTimes.delete(key);
271
292
  this.initialReportPromises.delete(key);
272
293
  this.initialReportResolvers.delete(key);
273
294
  }
295
+ /** The merged report of a connected printer and when it last arrived; none before the first report. */
296
+ getCachedReportWithTime(host, serial, token) {
297
+ const key = getPrinterKey(host, serial, token);
298
+ const raw = this.reportSnapshots.get(key);
299
+ const receivedAt = this.reportTimes.get(key);
300
+ return raw && receivedAt !== undefined && this.printers.has(key) ? { raw, receivedAt } : null;
301
+ }
302
+ /** Records a stale-cache refresh; false when one was sent within minIntervalMs. */
303
+ claimRefresh(host, serial, token, minIntervalMs) {
304
+ const key = getPrinterKey(host, serial, token);
305
+ const last = this.refreshTimes.get(key);
306
+ if (last !== undefined && Date.now() - last < minIntervalMs)
307
+ return false;
308
+ this.refreshTimes.set(key, Date.now());
309
+ return true;
310
+ }
274
311
  getCachedReport(host, serial, token) {
275
312
  return this.reportSnapshots.get(getPrinterKey(host, serial, token)) || null;
276
313
  }
@@ -330,6 +367,7 @@ class BambuClientStore {
330
367
  const printMessage = parsed?.print;
331
368
  if (printMessage && typeof printMessage === "object") {
332
369
  this.updateReportSnapshot(key, printMessage);
370
+ this.reportObserved(host, serial, key);
333
371
  }
334
372
  }
335
373
  catch {
@@ -338,6 +376,7 @@ class BambuClientStore {
338
376
  });
339
377
  printer.on("printer:dataUpdate", (data) => {
340
378
  this.updateReportSnapshot(key, data);
379
+ this.reportObserved(host, serial, key);
341
380
  });
342
381
  printer.on("client:connect", () => {
343
382
  this.printers.set(key, printer);
@@ -382,6 +421,8 @@ class BambuClientStore {
382
421
  this.printers.clear();
383
422
  this.initialConnectionPromises.clear();
384
423
  this.reportSnapshots.clear();
424
+ this.reportTimes.clear();
425
+ this.refreshTimes.clear();
385
426
  this.initialReportPromises.clear();
386
427
  this.initialReportResolvers.clear();
387
428
  }
@@ -390,6 +431,50 @@ class BambuClientStore {
390
431
  function printJobIdentity(raw) {
391
432
  return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
392
433
  }
434
+ const ACTIVE_JOB_STATES = new Set(["PREPARE", "SLICING", "RUNNING", "PAUSE"]);
435
+ /** Reports after which a started job can no longer be resumed. */
436
+ const ENDED_JOB_STATES = new Set(["FINISH", "FAILED", "IDLE"]);
437
+ const jobStem = (value) => path.posix.basename(value.replace(/\\/g, "/")).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
438
+ const reportedJobNames = (raw) => [raw.gcode_file, raw.subtask_name].filter((value) => typeof value === "string" && value.trim() !== "");
439
+ /** Whether a report names the job stored at remotePath (subtask_name for projects, gcode_file for raw G-code). */
440
+ function reportsJob(raw, remotePath) {
441
+ return reportedJobNames(raw).some(value => jobStem(value) === jobStem(remotePath));
442
+ }
443
+ /** What a resume needs to know about a started file (filePath, the inspected snapshot): its bytes, printed plate, limits and used materials. */
444
+ export async function checkedFile(inspection, filePath) {
445
+ const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
446
+ let plate;
447
+ const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
448
+ if (plateNumber && /\.3mf$/i.test(filePath)) {
449
+ const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath);
450
+ if (entry)
451
+ plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
452
+ }
453
+ return {
454
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
455
+ maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
456
+ materials: [...new Set(used.length ? used : inspection.materials)],
457
+ };
458
+ }
459
+ /**
460
+ * Where a printer keeps the plate G-code it extracted from a project to print
461
+ * it. A P1S removes the uploaded 3MF once it starts and keeps
462
+ * cache/<name>_plate_<n>.gcode, byte-identical to the 3MF's
463
+ * Metadata/plate_<n>.gcode (checked on a P1S for project_file and legacy
464
+ * .gcode.3mf jobs).
465
+ */
466
+ function extractedPlatePath(remotePath, index) {
467
+ const directory = path.posix.dirname(remotePath);
468
+ const stem = path.posix.basename(remotePath).replace(/(?:\.gcode)?\.3mf$/i, "");
469
+ return `${directory === "." ? "" : `${directory}/`}${stem}_plate_${index}.gcode`;
470
+ }
471
+ /** The name counterpart_print_progress reports for the job: subtask_name, else the G-code file's basename. */
472
+ function reportedJobName(raw) {
473
+ const subtask = typeof raw.subtask_name === "string" ? raw.subtask_name.trim() : "";
474
+ if (subtask)
475
+ return subtask;
476
+ return typeof raw.gcode_file === "string" ? path.posix.basename(raw.gcode_file.replace(/\\/g, "/").replace(/^\d+:/, "")) || undefined : undefined;
477
+ }
393
478
  /**
394
479
  * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
395
480
  * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
@@ -424,21 +509,33 @@ export function cameraFrameParser(onFrame, onError) {
424
509
  export class BambuImplementation {
425
510
  constructor(confirm) {
426
511
  this.confirm = confirm;
512
+ /**
513
+ * The job each printer may resume, keyed host and serial. Cancel, a report
514
+ * that it ended after it was seen running, or another job seen in its place
515
+ * retires it, so a later job that reuses the name is never resumed.
516
+ */
427
517
  this.checkedJobs = new Map();
518
+ /** In-flight counterpart_print_progress reads, one per printer. */
519
+ this.progressReads = new Map();
428
520
  this.clearedErrors = new Map();
429
- this.printerStore = new BambuClientStore();
521
+ this.printerStore = new BambuClientStore((host, serial, report) => this.observeReport(host, serial, report));
430
522
  }
431
- async confirmHardwareAction(message, physicalCheck = false) {
432
- if (!physicalCheck && process.env.BAMBU_REQUIRE_CONFIRMATION === "0")
523
+ /**
524
+ * Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
525
+ * ordinary prompts; a physical check, or a prompt with requiredBecause (why
526
+ * this one cannot be skipped), always asks.
527
+ */
528
+ async confirmHardwareAction(message, physicalCheck = false, requiredBecause) {
529
+ if (!physicalCheck && requiredBecause === undefined && process.env.BAMBU_REQUIRE_CONFIRMATION === "0")
433
530
  return;
434
531
  if (!this.confirm) {
435
- throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent.");
532
+ throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent." + (requiredBecause ? ` ${requiredBecause}` : ""));
436
533
  }
437
534
  if (!(await this.confirm(message))) {
438
535
  throw new Error("Hardware safety confirmation was declined or cancelled in the MCP client. No command was sent. " + (physicalCheck
439
536
  ? "This confirmation covers a physical check at the printer and always needs a person to accept it."
440
- : "Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
441
- "A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts."));
537
+ : requiredBecause ?? ("Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
538
+ "A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts.")));
442
539
  }
443
540
  }
444
541
  finishedJobIdentity(status) {
@@ -485,11 +582,36 @@ export class BambuImplementation {
485
582
  async getPrinter(host, serial, token) {
486
583
  return this.printerStore.getPrinter(host, serial, token);
487
584
  }
488
- /** Internal handoff from a successful inspected transport; never exposed as an MCP tool. */
489
- recordCheckedJob(host, serial, remotePath, requirements) {
490
- this.checkedJobs.set(`${host}\n${serial}`, { remotePath, requirements: structuredClone(requirements) });
585
+ /**
586
+ * Internal handoff from a successful inspected transport; never exposed as
587
+ * an MCP tool. uploadedHere is false for the plug-in routes, where Bambu's
588
+ * plug-in or cloud put the file on the printer at a path this server has not
589
+ * verified: a resume then re-reads it if it can and otherwise matches the
590
+ * unique name, as KAN-216 does for firmware that cannot download a file.
591
+ */
592
+ recordCheckedJob(host, serial, remotePath, requirements, file, uploadedHere = true) {
593
+ if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? ""))
594
+ throw new Error("A started job needs the SHA-256 of its inspected bytes.");
595
+ this.checkedJobs.set(`${host}\n${serial}`, {
596
+ ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
597
+ });
491
598
  this.clearedErrors.delete(serial);
492
599
  }
600
+ /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
601
+ observeReport(host, serial, raw) {
602
+ const key = `${host}\n${serial}`;
603
+ const checked = this.checkedJobs.get(key);
604
+ if (!checked || !raw || typeof raw.gcode_state !== "string")
605
+ return;
606
+ const state = raw.gcode_state.toUpperCase();
607
+ if (ACTIVE_JOB_STATES.has(state) && reportsJob(raw, checked.remotePath)) {
608
+ checked.seenRunning = true;
609
+ return;
610
+ }
611
+ if (checked.seenRunning && (ENDED_JOB_STATES.has(state) || (ACTIVE_JOB_STATES.has(state) && reportedJobNames(raw).length > 0))) {
612
+ this.checkedJobs.delete(key);
613
+ }
614
+ }
493
615
  validateLoadedGcodeState(status, inspection) {
494
616
  const usedMaterials = inspection.usedFilamentPositions.map(position => inspection.materials[position]);
495
617
  if (new Set(usedMaterials).size !== 1)
@@ -565,6 +687,75 @@ export class BambuImplementation {
565
687
  async getSafetyStatus(host, serial, token) {
566
688
  return readFreshPrinterStatus(await this.getPrinter(host, serial, token), serial);
567
689
  }
690
+ /**
691
+ * The merged MQTT report for counterpart_print_progress and when it arrived.
692
+ * On a held session it comes from the cache with no printer traffic. PushAll
693
+ * is sent only to fill a cold cache, or at most once per STALE_REPORT_MS when
694
+ * the printer has been quiet for longer than that (P1-series firmware lags
695
+ * when asked often). The whole read, connection and publish included, is
696
+ * bounded by timeoutMs: the MQTT connect to an unreachable printer keeps
697
+ * retrying, so it must not hold the call. Then the result is null, or a stale
698
+ * report that could not be refreshed in time. Display data only; safety
699
+ * checks use getSafetyStatus.
700
+ */
701
+ async readProgressReport(host, serial, token, timeoutMs = 8000) {
702
+ const cached = this.printerStore.getCachedReportWithTime(host, serial, token);
703
+ const warm = cached !== null && typeof cached.raw.gcode_state === "string";
704
+ if (warm && (Date.now() - cached.receivedAt <= STALE_REPORT_MS || !this.printerStore.claimRefresh(host, serial, token, STALE_REPORT_MS)))
705
+ return cached;
706
+ // One first read or refresh per printer at a time. Callers that gave up share
707
+ // it, so a printer that comes back gets one PushAll, not one per expired poll.
708
+ const key = getPrinterKey(host, serial, token);
709
+ let read = this.progressReads.get(key);
710
+ if (!read) {
711
+ const started = warm ? this.refreshProgressReport(host, serial, token, cached) : this.firstProgressReport(host, serial, token);
712
+ read = started.finally(() => { if (this.progressReads.get(key) === read)
713
+ this.progressReads.delete(key); });
714
+ read.catch(() => { });
715
+ this.progressReads.set(key, read);
716
+ }
717
+ const latest = () => warm ? this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached : null;
718
+ let timer;
719
+ const expired = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
720
+ try {
721
+ return (await Promise.race([read, expired])) ?? latest();
722
+ }
723
+ catch {
724
+ return latest();
725
+ }
726
+ finally {
727
+ clearTimeout(timer);
728
+ }
729
+ }
730
+ async firstProgressReport(host, serial, token) {
731
+ const printer = await this.getPrinter(host, serial, token);
732
+ // The printer may already have pushed its full status while connecting.
733
+ if (typeof this.printerStore.getCachedReportWithTime(host, serial, token)?.raw.gcode_state !== "string") {
734
+ try {
735
+ await invokeWithoutAck(printer, new PushAllCommand());
736
+ }
737
+ catch { /* the printer pushes on its own too */ }
738
+ }
739
+ await this.printerStore.waitForInitialReport(host, serial, token, 4000);
740
+ // A connected printer whose report still lacks gcode_state is busy, not offline.
741
+ return this.printerStore.getCachedReportWithTime(host, serial, token);
742
+ }
743
+ async refreshProgressReport(host, serial, token, cached) {
744
+ try {
745
+ await invokeWithoutAck(await this.getPrinter(host, serial, token), new PushAllCommand());
746
+ const deadline = Date.now() + 2000;
747
+ while (Date.now() < deadline) {
748
+ const latest = this.printerStore.getCachedReportWithTime(host, serial, token);
749
+ if (latest && latest.receivedAt > cached.receivedAt)
750
+ return latest;
751
+ await sleep(50);
752
+ }
753
+ }
754
+ catch {
755
+ // A failed refresh leaves the cached report, which still carries its own time.
756
+ }
757
+ return this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached;
758
+ }
568
759
  async getStatus(host, serial, token) {
569
760
  try {
570
761
  const printer = await this.getPrinter(host, serial, token);
@@ -652,6 +843,7 @@ export class BambuImplementation {
652
843
  const inspection = await inspectPrintFile(options.filePath, {
653
844
  model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
654
845
  });
846
+ const resumeFile = await checkedFile(inspection, options.filePath);
655
847
  const projectMetadata = await this.resolveProjectFileMetadata(options.filePath, options.plateIndex, inspection.plateInternalPath);
656
848
  // Send project_file command via bambu-node MQTT (bypasses bambu-js
657
849
  // hardcoded use_ams=true and missing ams_mapping support)
@@ -784,7 +976,7 @@ export class BambuImplementation {
784
976
  watcher.dispose();
785
977
  throw error;
786
978
  }
787
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
979
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
788
980
  const dispatch = await watcher.settled();
789
981
  return {
790
982
  status: "success", dispatch, remoteProjectPath,
@@ -796,8 +988,13 @@ export class BambuImplementation {
796
988
  }
797
989
  const b = (v) => (v ? 1 : 0);
798
990
  let projectFileCmd;
991
+ // The printer reports these back as subtask_name/task_id, so the result
992
+ // returns exactly what was sent. Only the H2-style route sends a real task id.
993
+ const subtaskName = remoteFileName.replace(/\.3mf$/i, "");
994
+ let taskId;
799
995
  if (usesH2ProjectFile) {
800
996
  const submissionId = String(Date.now() & 0x7fffffff);
997
+ taskId = submissionId;
801
998
  projectFileCmd = {
802
999
  print: {
803
1000
  sequence_id: "0",
@@ -818,7 +1015,7 @@ export class BambuImplementation {
818
1015
  extrude_cali_flag: 0,
819
1016
  extrude_cali_manual_mode: 0,
820
1017
  nozzle_offset_cali: 2,
821
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1018
+ subtask_name: subtaskName,
822
1019
  profile_id: "0",
823
1020
  project_id: submissionId,
824
1021
  subtask_id: submissionId,
@@ -834,7 +1031,7 @@ export class BambuImplementation {
834
1031
  command: "project_file",
835
1032
  param: projectMetadata.plateInternalPath,
836
1033
  url: projectUrl,
837
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1034
+ subtask_name: subtaskName,
838
1035
  md5,
839
1036
  flow_cali: options.flowCalibration ?? true,
840
1037
  layer_inspect: options.layerInspect ?? true,
@@ -860,7 +1057,7 @@ export class BambuImplementation {
860
1057
  watcher.dispose();
861
1058
  throw error;
862
1059
  }
863
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
1060
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
864
1061
  await new Promise((resolve) => setTimeout(resolve, 300));
865
1062
  const dispatch = await watcher.settled();
866
1063
  return {
@@ -875,6 +1072,8 @@ export class BambuImplementation {
875
1072
  platePath: projectMetadata.plateInternalPath,
876
1073
  md5,
877
1074
  amsMapping,
1075
+ subtaskName,
1076
+ ...(taskId !== undefined ? { taskId } : {}),
878
1077
  };
879
1078
  }
880
1079
  async cancelJob(host, serial, token, dispatch) {
@@ -950,33 +1149,103 @@ export class BambuImplementation {
950
1149
  throw new Error(`Failed to pause print: ${error.message}`);
951
1150
  }
952
1151
  }
1152
+ /**
1153
+ * Resume reheats and moves the printer, so it is gated like a print start:
1154
+ * only the job this server inspected and started, while a fresh report shows
1155
+ * it paused, with its bytes re-read over FTPS and compared, and after human
1156
+ * confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
1157
+ * be current at every check, including the native helper's last one.
1158
+ */
953
1159
  async resumeJob(host, serial, token, dispatch) {
954
1160
  return withPrinterOperation(host, serial, async (assertActive) => {
955
- const checked = this.checkedJobs.get(`${host}\n${serial}`);
1161
+ const key = `${host}\n${serial}`;
1162
+ const checked = this.checkedJobs.get(key);
956
1163
  if (!checked)
957
1164
  throw new Error("Resume requires a job inspected and started by this server instance. Verify other jobs on the printer before resuming them there.");
958
- const beforeDispatch = async () => {
1165
+ let jobName = path.posix.basename(checked.remotePath);
1166
+ const pausedJob = async () => {
959
1167
  assertActive();
960
1168
  const status = await this.getSafetyStatus(host, serial, token);
1169
+ this.observeReport(host, serial, status.raw);
1170
+ if (this.checkedJobs.get(key) !== checked) {
1171
+ throw new Error(`${jobName} is no longer the job this server started: it was cancelled, it ended, or another job took its place. Nothing was sent; check the printer and resume it there.`);
1172
+ }
961
1173
  validatePrinterState(status, { ...checked.requirements, requireIdle: false });
962
1174
  if (status.raw.gcode_state !== "PAUSE")
963
1175
  throw new Error("Resume requires a freshly reported paused job.");
964
- const stem = (value) => path.posix.basename(value).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
965
- const names = [status.raw.gcode_file, status.raw.subtask_name].filter(value => typeof value === "string");
966
- if (!names.some(value => stem(value) === stem(checked.remotePath)))
1176
+ if (!reportsJob(status.raw, checked.remotePath))
967
1177
  throw new Error("Paused job identity does not match this server's inspected artifact.");
1178
+ jobName = reportedJobName(status.raw) ?? jobName;
968
1179
  assertActive();
969
1180
  };
970
- await beforeDispatch();
1181
+ await pausedJob();
1182
+ const reread = await this.rereadJob(host, token, checked);
1183
+ if ("changed" in reread) {
1184
+ if (this.checkedJobs.get(key) === checked)
1185
+ this.checkedJobs.delete(key);
1186
+ throw new Error(`${jobName} on the printer is no longer the file this server inspected (SHA-256 of ${reread.changed} changed). Nothing was sent, and this job can no longer be resumed from here.`);
1187
+ }
1188
+ const unread = "unread" in reread ? reread.unread : undefined;
1189
+ if (unread !== undefined && checked.uploadedHere) {
1190
+ throw new Error(`Could not re-read ${jobName} from the printer over FTPS to confirm it is the inspected file (${unread}). Nothing was sent; resume it at the printer.`);
1191
+ }
1192
+ const bytesVerified = "verified" in reread;
1193
+ assertActive();
1194
+ await this.confirmHardwareAction(`Resume ${jobName} on ${checked.model.toUpperCase()} (${serial})? It reheats to its targets (peak nozzle ${checked.maxNozzleTemperature}°C, ` +
1195
+ `bed ${checked.maxBedTemperature}°C, chamber ${checked.maxChamberTemperature}°C) and moves. Materials: ${checked.materials.length ? checked.materials.join(", ") : "none declared"}. ` +
1196
+ `File SHA-256: ${checked.sha256}${"verified" in reread ? ` (re-read from the printer${reread.verified === checked.remotePath ? "" : ` as its extracted plate ${reread.verified}`})` : ` (Bambu's plug-in placed the file, and it could not be re-read over FTPS: ${unread}; matched by its unique name)`}. ` +
1197
+ "Confirm the nozzle path is clear and the filament is still loaded.", false,
1198
+ // The opt-out covers resumes whose bytes were checked; an unverified file always needs a person.
1199
+ bytesVerified ? undefined : "The printer's copy of this file could not be re-read, so this resume always needs a person to accept it, even with BAMBU_REQUIRE_CONFIRMATION=0.");
1200
+ // The job may have been resumed, stopped or replaced at the printer while the prompt was open.
1201
+ await pausedJob();
971
1202
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
972
1203
  assertActive();
973
1204
  if (dispatch)
974
- await dispatch(assertActive, beforeDispatch);
1205
+ await dispatch(assertActive, pausedJob);
975
1206
  else
976
1207
  await invokeWithoutAck(printer, new UpdateStateCommand({ state: "resume" }));
977
- return { status: "success", message: "Resume command sent successfully." };
1208
+ return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
978
1209
  });
979
1210
  }
1211
+ /**
1212
+ * Re-read a started job's bytes over FTPS: the uploaded file, else the plate
1213
+ * G-code the printer extracted from the project to print it. The first file
1214
+ * that can be read decides; a mismatch is reported as changed.
1215
+ */
1216
+ async rereadJob(host, token, checked) {
1217
+ const candidates = [{ remote: checked.remotePath, sha256: checked.sha256 }];
1218
+ if (checked.plate)
1219
+ candidates.push({ remote: extractedPlatePath(checked.remotePath, checked.plate.index), sha256: checked.plate.sha256 });
1220
+ const failures = [];
1221
+ for (const candidate of candidates) {
1222
+ let sha256;
1223
+ try {
1224
+ sha256 = await this.remoteSha256(host, token, candidate.remote);
1225
+ }
1226
+ catch (error) {
1227
+ failures.push(`${candidate.remote}: ${error.message}`);
1228
+ continue;
1229
+ }
1230
+ return sha256 === candidate.sha256 ? { verified: candidate.remote } : { changed: candidate.remote };
1231
+ }
1232
+ return { unread: failures.join("; ") };
1233
+ }
1234
+ /** SHA-256 of a printer file, streamed from an FTPS download into a private directory. */
1235
+ async remoteSha256(host, token, remotePath) {
1236
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-resume-check-"));
1237
+ try {
1238
+ const localPath = path.join(directory, "job");
1239
+ await this.ftpDownload(host, token, remotePath, localPath);
1240
+ const hash = createHash("sha256");
1241
+ for await (const chunk of createReadStream(localPath))
1242
+ hash.update(chunk);
1243
+ return hash.digest("hex");
1244
+ }
1245
+ finally {
1246
+ await fs.rm(directory, { recursive: true, force: true });
1247
+ }
1248
+ }
980
1249
  async clearHmsErrors(host, serial, token, dispatch) {
981
1250
  return withPrinterOperation(host, serial, async (assertActive) => {
982
1251
  const codesFor = (status) => {
@@ -995,7 +1264,7 @@ export class BambuImplementation {
995
1264
  ]);
996
1265
  const confirmedJob = jobIdentity(initialStatus.raw);
997
1266
  const jobName = initialStatus.raw.subtask_name || initialStatus.raw.gcode_file;
998
- await this.confirmHardwareAction(`Clear reported hardware errors on ${serial}: ${codes.map(describeHmsKey).join(", ")}?${jobName ? ` Current job: ${String(jobName)}.` : ""} Inspect the printer and resolve the physical cause first. Confirm only after removing obstructions and correcting the fault.`, true);
1267
+ await this.confirmHardwareAction(`Clear reported hardware errors on ${serial}: ${codes.map(describeHmsKey).join(", ")}?${jobName ? ` Current job: ${String(jobName)}.` : ""} Inspect the printer and resolve the physical cause first. Confirm only after correcting the fault.`, true);
999
1268
  const beforeDispatch = async () => {
1000
1269
  assertActive();
1001
1270
  const currentStatus = await this.getSafetyStatus(host, serial, token);
@@ -1339,6 +1608,7 @@ export class BambuImplementation {
1339
1608
  const inspection = await inspectPrintFile(filePath, { model });
1340
1609
  if (inspection.selectsAms)
1341
1610
  throw new Error("Raw G-code with AMS selection requires a .3mf project export with verified physical slot mappings.");
1611
+ const resumeFile = await checkedFile(inspection, filePath);
1342
1612
  const initialStatus = await this.getSafetyStatus(host, serial, token);
1343
1613
  let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
1344
1614
  const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
@@ -1361,10 +1631,12 @@ export class BambuImplementation {
1361
1631
  watcher.dispose();
1362
1632
  throw error;
1363
1633
  }
1364
- this.recordCheckedJob(host, serial, remotePath, requirements);
1634
+ this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
1365
1635
  const dispatch = await watcher.settled();
1366
1636
  return {
1367
1637
  status: "success", uploaded: true, printRequested: true, dispatch, remotePath,
1638
+ // counterpart_print_progress reports this as job.name (the printer reports no subtask_name for raw G-code).
1639
+ jobName: path.posix.basename(remotePath),
1368
1640
  message: dispatch === "started"
1369
1641
  ? `The printer accepted and started ${remotePath}.`
1370
1642
  : `Sent the print command for ${remotePath}; the printer has not reported starting yet. Check get_printer_status before assuming it is printing.`,
@@ -1519,19 +1791,7 @@ export class BambuImplementation {
1519
1791
  async cameraSnapshot(host, _serial, token, options = {}) {
1520
1792
  const timeoutMs = options.timeoutMs ?? 8000;
1521
1793
  const model = (options.bambuModel ?? "").toLowerCase();
1522
- // P1/A1 series still use the proprietary TCP-on-6000 framed JPEG path
1523
- // (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
1524
- const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
1525
- // X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
1526
- // OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
1527
- // integration's models.py shows the printer reports its own
1528
- // `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
1529
- // A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
1530
- // confirmed by local H2 camera transport probes).
1531
- const RTSP_MODELS = new Set([
1532
- "x1", "x1c", "x1carbon", "x1e", "p2s",
1533
- "h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
1534
- ]);
1794
+ const RTSP_MODELS = RTSP_CAMERA_MODELS;
1535
1795
  if (!model) {
1536
1796
  throw new Error("camera_snapshot requires bambu_model or BAMBU_MODEL so it can choose the correct Bambu camera protocol.");
1537
1797
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Which camera transport each model uses, keyed by the lowercased model name
3
+ * with spaces removed. camera_snapshot routes by these sets and
4
+ * counterpart_printer_info reports them, so the two always agree.
5
+ */
6
+ export declare const TCP_CAMERA_MODELS: ReadonlySet<string>;
7
+ export declare const RTSP_CAMERA_MODELS: ReadonlySet<string>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Which camera transport each model uses, keyed by the lowercased model name
3
+ * with spaces removed. camera_snapshot routes by these sets and
4
+ * counterpart_printer_info reports them, so the two always agree.
5
+ */
6
+ // P1/A1 series use the proprietary TCP-on-6000 framed JPEG path
7
+ // (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
8
+ export const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
9
+ // X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
10
+ // OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
11
+ // integration's models.py shows the printer reports its own
12
+ // `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
13
+ // A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
14
+ // confirmed by local H2 camera transport probes).
15
+ export const RTSP_CAMERA_MODELS = new Set([
16
+ "x1", "x1c", "x1carbon", "x1e", "p2s",
17
+ "h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
18
+ ]);
@@ -0,0 +1,42 @@
1
+ export declare const HMS_MESSAGES_SOURCE: {
2
+ readonly studioTag: "v02.08.02.61";
3
+ readonly studioCommit: "926a7192574bcb9b3a732e1ec59a46d79cb45466";
4
+ /** Per table: Bambu's device_hms and device_error versions, and the SHA-256 of the English file used. */
5
+ readonly tables: {
6
+ readonly "093": {
7
+ readonly hmsVersion: 202508191204;
8
+ readonly errorVersion: 202508192303;
9
+ readonly sha256: "7801fd6c355854b62ecb62ee32727b4e5dcca908841dbcfd5e5de45b3dfd1c25";
10
+ };
11
+ readonly "094": {
12
+ readonly hmsVersion: 202503231214;
13
+ readonly errorVersion: 202503231214;
14
+ readonly sha256: "047c15e2140738ec08258b74536e6cb996cddf0c586c5c39e2318e54125a9e76";
15
+ };
16
+ readonly "20P": {
17
+ readonly hmsVersion: 202511162200;
18
+ readonly errorVersion: 202511162200;
19
+ readonly sha256: "e4f067d027b9bcbb9bbf6cb90f41f11130cf4d83dffd3dee101db7826dc808c3";
20
+ };
21
+ readonly "22E": {
22
+ readonly hmsVersion: 202510142200;
23
+ readonly errorVersion: 202510142200;
24
+ readonly sha256: "87426021aea2bd4e8d721e46e1c86808fd7c6fc06f52baf6d952ead9e8d14d1e";
25
+ };
26
+ readonly "239": {
27
+ readonly hmsVersion: 202506171403;
28
+ readonly errorVersion: 202506171403;
29
+ readonly sha256: "c1d23d5302756d57df5cb9bc795d95fc54ef1db7565dca1f04b69a024886426a";
30
+ };
31
+ readonly "31B": {
32
+ readonly hmsVersion: 202511162200;
33
+ readonly errorVersion: 202511162200;
34
+ readonly sha256: "dcf63657bff5451f0715ea3c032efe482279bc8cbc28cb9b8ae51c7354826574";
35
+ };
36
+ };
37
+ };
38
+ export type HmsText = string | Readonly<Record<string, string>>;
39
+ /** device_hms: 16 hex digits, attr then code, as in Bambu's long error code. */
40
+ export declare const HMS_MESSAGES: Readonly<Record<string, HmsText>>;
41
+ /** device_error: the printer's print_error as 8 hex digits. */
42
+ export declare const PRINT_ERROR_MESSAGES: Readonly<Record<string, HmsText>>;