bambu-printer-mcp 1.1.46 → 1.1.48

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 +197 -17
  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 +79 -8
  18. package/dist/printers/bambu.js +311 -56
  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 +20 -2
  24. package/dist/safety/printer-state.js +5 -5
  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 +204 -17
  38. package/src/printers/bambu-stages.ts +90 -0
  39. package/src/printers/bambu.ts +329 -56
  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 +6 -6
  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, type PrinterStateRequirements } 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 {
@@ -45,6 +46,8 @@ function loadClientCreds(): { cert: Buffer; key: Buffer } | null {
45
46
  const CLIENT_CREDS = loadClientCreds();
46
47
 
47
48
  const COMMAND_SETTLE_MS = 300;
49
+ /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
50
+ const STALE_REPORT_MS = 300_000;
48
51
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
49
52
  const COMMAND_VERIFICATION_HMS = { attr: 0x05000500, code: 0x00010007 };
50
53
  const COMMAND_REJECTED_MESSAGE =
@@ -289,9 +292,16 @@ function ftpsSecureOptions(host: string): Record<string, unknown> {
289
292
  }
290
293
 
291
294
  class BambuClientStore {
295
+ /** Sees every merged report, so a resume record notices a job ending even when nobody polls. */
296
+ constructor(private readonly onReport?: (host: string, serial: string, report: Record<string, any>) => void) {}
297
+
292
298
  private printers: Map<string, BambuClient> = new Map();
293
299
  private initialConnectionPromises: Map<string, Promise<void>> = new Map();
294
300
  private reportSnapshots: Map<string, Record<string, any>> = new Map();
301
+ /** When the last MQTT report for each printer arrived (ms since epoch). */
302
+ private reportTimes: Map<string, number> = new Map();
303
+ /** When PushAll was last sent for a stale cache, so a quiet printer is not asked repeatedly. */
304
+ private refreshTimes: Map<string, number> = new Map();
295
305
  private initialReportPromises: Map<string, Promise<void>> = new Map();
296
306
  private initialReportResolvers: Map<string, () => void> = new Map();
297
307
 
@@ -325,17 +335,43 @@ class BambuClientStore {
325
335
 
326
336
  const previous = this.reportSnapshots.get(key) || {};
327
337
  this.reportSnapshots.set(key, { ...previous, ...update });
338
+ this.reportTimes.set(key, Date.now());
328
339
  this.resolveInitialReport(key);
329
340
  }
330
341
 
342
+ private reportObserved(host: string, serial: string, key: string): void {
343
+ const report = this.reportSnapshots.get(key);
344
+ if (!report || !this.onReport) return;
345
+ try { this.onReport(host, serial, report); } catch { /* an observer never breaks report handling */ }
346
+ }
347
+
331
348
  private clearPrinterState(key: string): void {
332
349
  this.printers.delete(key);
333
350
  this.initialConnectionPromises.delete(key);
334
351
  this.reportSnapshots.delete(key);
352
+ this.reportTimes.delete(key);
353
+ this.refreshTimes.delete(key);
335
354
  this.initialReportPromises.delete(key);
336
355
  this.initialReportResolvers.delete(key);
337
356
  }
338
357
 
358
+ /** The merged report of a connected printer and when it last arrived; none before the first report. */
359
+ getCachedReportWithTime(host: string, serial: string, token: string): { raw: Record<string, any>; receivedAt: number } | null {
360
+ const key = getPrinterKey(host, serial, token);
361
+ const raw = this.reportSnapshots.get(key);
362
+ const receivedAt = this.reportTimes.get(key);
363
+ return raw && receivedAt !== undefined && this.printers.has(key) ? { raw, receivedAt } : null;
364
+ }
365
+
366
+ /** Records a stale-cache refresh; false when one was sent within minIntervalMs. */
367
+ claimRefresh(host: string, serial: string, token: string, minIntervalMs: number): boolean {
368
+ const key = getPrinterKey(host, serial, token);
369
+ const last = this.refreshTimes.get(key);
370
+ if (last !== undefined && Date.now() - last < minIntervalMs) return false;
371
+ this.refreshTimes.set(key, Date.now());
372
+ return true;
373
+ }
374
+
339
375
  getCachedReport(host: string, serial: string, token: string): Record<string, any> | null {
340
376
  return this.reportSnapshots.get(getPrinterKey(host, serial, token)) || null;
341
377
  }
@@ -406,6 +442,7 @@ class BambuClientStore {
406
442
  const printMessage = parsed?.print;
407
443
  if (printMessage && typeof printMessage === "object") {
408
444
  this.updateReportSnapshot(key, printMessage);
445
+ this.reportObserved(host, serial, key);
409
446
  }
410
447
  } catch {
411
448
  // Ignore unrelated payloads.
@@ -414,6 +451,7 @@ class BambuClientStore {
414
451
 
415
452
  printer.on("printer:dataUpdate", (data) => {
416
453
  this.updateReportSnapshot(key, data);
454
+ this.reportObserved(host, serial, key);
417
455
  });
418
456
 
419
457
  printer.on("client:connect", () => {
@@ -466,16 +504,94 @@ class BambuClientStore {
466
504
  this.printers.clear();
467
505
  this.initialConnectionPromises.clear();
468
506
  this.reportSnapshots.clear();
507
+ this.reportTimes.clear();
508
+ this.refreshTimes.clear();
469
509
  this.initialReportPromises.clear();
470
510
  this.initialReportResolvers.clear();
471
511
  }
472
512
  }
473
513
 
474
- /** What the human confirmed in confirmPrintPreflight, checked again before dispatch. */
514
+ /** The preflight state, checked again before dispatch. */
475
515
  function printJobIdentity(raw: Record<string, any>): string {
476
516
  return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
477
517
  }
478
518
 
519
+ /** A merged MQTT report and when it last arrived (ms since epoch). */
520
+ export type ProgressReport = { raw: Record<string, any>; receivedAt: number };
521
+
522
+ /** The inspected bytes and limits of a started job, for the resume prompt and byte check. */
523
+ export type CheckedFile = {
524
+ sha256: string;
525
+ /** A project's printed plate: its number and the SHA-256 of its Metadata/plate_<index>.gcode. */
526
+ plate?: { index: number; sha256: string };
527
+ model: string;
528
+ maxNozzleTemperature: number;
529
+ maxBedTemperature: number;
530
+ maxChamberTemperature: number;
531
+ materials: string[];
532
+ };
533
+
534
+ /**
535
+ * The last job this server inspected and started on a printer. seenRunning: a
536
+ * report showed it preparing, printing or paused, so a later ended report, or
537
+ * another job in its place, is about it rather than about the job before it.
538
+ */
539
+ type CheckedJob = CheckedFile & {
540
+ remotePath: string;
541
+ requirements: PrinterStateRequirements;
542
+ seenRunning: boolean;
543
+ /** This server uploaded the bytes to remotePath over FTPS, so a failed re-read refuses the resume. */
544
+ uploadedHere: boolean;
545
+ };
546
+
547
+ const ACTIVE_JOB_STATES = new Set(["PREPARE", "SLICING", "RUNNING", "PAUSE"]);
548
+ /** Reports after which a started job can no longer be resumed. */
549
+ const ENDED_JOB_STATES = new Set(["FINISH", "FAILED", "IDLE"]);
550
+
551
+ const jobStem = (value: string) => path.posix.basename(value.replace(/\\/g, "/")).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
552
+ const reportedJobNames = (raw: Record<string, any>): string[] =>
553
+ [raw.gcode_file, raw.subtask_name].filter((value): value is string => typeof value === "string" && value.trim() !== "");
554
+ /** Whether a report names the job stored at remotePath (subtask_name for projects, gcode_file for raw G-code). */
555
+ function reportsJob(raw: Record<string, any>, remotePath: string): boolean {
556
+ return reportedJobNames(raw).some(value => jobStem(value) === jobStem(remotePath));
557
+ }
558
+
559
+ /** What a resume needs to know about a started file (filePath, the inspected snapshot): its bytes, printed plate, limits and used materials. */
560
+ export async function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile> {
561
+ const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
562
+ let plate: CheckedFile["plate"];
563
+ const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
564
+ if (plateNumber && /\.3mf$/i.test(filePath)) {
565
+ const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath!);
566
+ if (entry) plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
567
+ }
568
+ return {
569
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
570
+ maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
571
+ materials: [...new Set(used.length ? used : inspection.materials)],
572
+ };
573
+ }
574
+
575
+ /**
576
+ * Where a printer keeps the plate G-code it extracted from a project to print
577
+ * it. A P1S removes the uploaded 3MF once it starts and keeps
578
+ * cache/<name>_plate_<n>.gcode, byte-identical to the 3MF's
579
+ * Metadata/plate_<n>.gcode (checked on a P1S for project_file and legacy
580
+ * .gcode.3mf jobs).
581
+ */
582
+ function extractedPlatePath(remotePath: string, index: number): string {
583
+ const directory = path.posix.dirname(remotePath);
584
+ const stem = path.posix.basename(remotePath).replace(/(?:\.gcode)?\.3mf$/i, "");
585
+ return `${directory === "." ? "" : `${directory}/`}${stem}_plate_${index}.gcode`;
586
+ }
587
+
588
+ /** The name counterpart_print_progress reports for the job: subtask_name, else the G-code file's basename. */
589
+ function reportedJobName(raw: Record<string, any>): string | undefined {
590
+ const subtask = typeof raw.subtask_name === "string" ? raw.subtask_name.trim() : "";
591
+ if (subtask) return subtask;
592
+ return typeof raw.gcode_file === "string" ? path.posix.basename(raw.gcode_file.replace(/\\/g, "/").replace(/^\d+:/, "")) || undefined : undefined;
593
+ }
594
+
479
595
  export type PrintPreflight = { finishedJob?: string; serial: string; model: string; notices: string[] };
480
596
 
481
597
  /**
@@ -510,23 +626,35 @@ export function cameraFrameParser(onFrame: (jpeg: Buffer) => void, onError: (err
510
626
 
511
627
  export class BambuImplementation {
512
628
  private printerStore: BambuClientStore;
513
- private checkedJobs = new Map<string, { remotePath: string; requirements: PrinterStateRequirements }>();
629
+ /**
630
+ * The job each printer may resume, keyed host and serial. Cancel, a report
631
+ * that it ended after it was seen running, or another job seen in its place
632
+ * retires it, so a later job that reuses the name is never resumed.
633
+ */
634
+ private checkedJobs = new Map<string, CheckedJob>();
635
+ /** In-flight counterpart_print_progress reads, one per printer. */
636
+ private progressReads = new Map<string, Promise<ProgressReport | null>>();
514
637
  private clearedErrors = new Map<string, string[]>();
515
638
 
516
639
  constructor(private readonly confirm?: (message: string) => Promise<boolean>) {
517
- this.printerStore = new BambuClientStore();
640
+ this.printerStore = new BambuClientStore((host, serial, report) => this.observeReport(host, serial, report));
518
641
  }
519
642
 
520
- async confirmHardwareAction(message: string, physicalCheck = false): Promise<void> {
521
- if (!physicalCheck && process.env.BAMBU_REQUIRE_CONFIRMATION === "0") return;
643
+ /**
644
+ * Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
645
+ * ordinary prompts; a physical check, or a prompt with requiredBecause (why
646
+ * this one cannot be skipped), always asks.
647
+ */
648
+ async confirmHardwareAction(message: string, physicalCheck = false, requiredBecause?: string): Promise<void> {
649
+ if (!physicalCheck && requiredBecause === undefined && process.env.BAMBU_REQUIRE_CONFIRMATION === "0") return;
522
650
  if (!this.confirm) {
523
- throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent.");
651
+ throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent." + (requiredBecause ? ` ${requiredBecause}` : ""));
524
652
  }
525
653
  if (!(await this.confirm(message))) {
526
654
  throw new Error("Hardware safety confirmation was declined or cancelled in the MCP client. No command was sent. " + (physicalCheck
527
655
  ? "This confirmation covers a physical check at the printer and always needs a person to accept it."
528
- : "Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
529
- "A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts."));
656
+ : requiredBecause ?? ("Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
657
+ "A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts.")));
530
658
  }
531
659
  }
532
660
 
@@ -538,9 +666,8 @@ export class BambuImplementation {
538
666
  }
539
667
 
540
668
  /**
541
- * The human print confirmation. Its result goes to assertBedClearance at
542
- * every later state check of the same print, which stops the print if the
543
- * situation the human confirmed has changed.
669
+ * Record the current job and notices during preflight so a changed printer state
670
+ * is detected before dispatch.
544
671
  */
545
672
  async confirmPrintPreflight(serial: string, status: any, inspection: Awaited<ReturnType<typeof inspectPrintFile>>): Promise<PrintPreflight> {
546
673
  const finishedJob = this.finishedJobIdentity(status);
@@ -550,28 +677,24 @@ export class BambuImplementation {
550
677
  await this.confirmHardwareAction(
551
678
  `Start a checked print on ${inspection.model.toUpperCase()} (${serial})? Nozzles: ${inspection.nozzleDiameters.join(", ")} mm. ` +
552
679
  `Materials: ${inspection.materials.join(", ")}. Peak targets: nozzle ${inspection.maxNozzleTemperature}°C, bed ${inspection.maxBedTemperature}°C, chamber ${inspection.maxChamberTemperature}°C. ` +
553
- `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels and that the build plate is clear.` +
554
- (finishedJob !== undefined ? (status.raw.gcode_state === "FAILED"
555
- ? (isFinishedP1SJob(status.raw, inspection.model)
556
- ? " The previous P1S job ended in FAILED and the printer now reports idle with no print or HMS errors. Remove the previous part and every detached part, support and strand from the plate and nozzle before confirming. No error-reset command is sent."
557
- : " The previous X2D task was canceled (0300400C): remove every detached part, support and strand from the plate and nozzle before confirming. FAILED is the previous job's terminal state; no error-reset command is sent.")
558
- : " The printer reports FINISH: remove the previous part and debris before confirming.") : "") +
680
+ `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels.` +
681
+ (status.raw.gcode_state === "FAILED" && finishedJob !== undefined ? " The previous job reports FAILED; the current printer report meets the checked idle and error requirements. No error-reset command is sent." : "") +
559
682
  (cleared ? ` Previously cleared hardware codes: ${cleared.map(describeHmsKey).join(", ")}. Confirm their physical causes have been resolved.` : "") +
560
683
  (notices.length ? ` The printer also reports ${notices.join(", ")}, which Bambu lists for this model without text and never shows as a fault; ` +
561
684
  `${notices.length === 1 ? "it does" : "they do"} not block printing.` : "") +
562
685
  (unchipped.length ? ` Printer ${unchipped.length === 1 ? `nozzle ${unchipped[0]} reports` : `nozzles ${unchipped.join(" and ")} report`} no identity chip, ` +
563
686
  `so ${unchipped.length === 1 ? "its" : "their"} diameter and type are the printer's configured settings; confirm they match the installed ${unchipped.length === 1 ? "hotend" : "hotends"}.` : ""),
564
- finishedJob !== undefined || !!cleared
687
+ !!cleared
565
688
  );
566
689
  return { finishedJob, serial, model: inspection.model, notices };
567
690
  }
568
691
 
569
692
  /** Stop a print whose confirmed situation changed: a newly finished job, or a hidden HMS notice the preflight did not name. */
570
- assertBedClearance(status: any, preflight: PrintPreflight): void {
693
+ assertPrintPreflight(status: any, preflight: PrintPreflight): void {
571
694
  const current = this.finishedJobIdentity(status);
572
695
  if ((preflight.finishedJob !== undefined && printJobIdentity(status.raw) !== preflight.finishedJob)
573
696
  || (current !== undefined && preflight.finishedJob === undefined)) {
574
- throw new Error("Printer reports a newly finished job. Confirm that its part and debris have been removed before retrying the print.");
697
+ throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
575
698
  }
576
699
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
577
700
  // can appear after the human confirmed. Never pass a notice nobody was told about.
@@ -586,12 +709,36 @@ export class BambuImplementation {
586
709
  return this.printerStore.getPrinter(host, serial, token);
587
710
  }
588
711
 
589
- /** Internal handoff from a successful inspected transport; never exposed as an MCP tool. */
590
- recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements): void {
591
- this.checkedJobs.set(`${host}\n${serial}`, { remotePath, requirements: structuredClone(requirements) });
712
+ /**
713
+ * Internal handoff from a successful inspected transport; never exposed as
714
+ * an MCP tool. uploadedHere is false for the plug-in routes, where Bambu's
715
+ * plug-in or cloud put the file on the printer at a path this server has not
716
+ * verified: a resume then re-reads it if it can and otherwise matches the
717
+ * unique name, as KAN-216 does for firmware that cannot download a file.
718
+ */
719
+ recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements, file: CheckedFile, uploadedHere = true): void {
720
+ if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? "")) throw new Error("A started job needs the SHA-256 of its inspected bytes.");
721
+ this.checkedJobs.set(`${host}\n${serial}`, {
722
+ ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
723
+ });
592
724
  this.clearedErrors.delete(serial);
593
725
  }
594
726
 
727
+ /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
728
+ observeReport(host: string, serial: string, raw: Record<string, any> | undefined): void {
729
+ const key = `${host}\n${serial}`;
730
+ const checked = this.checkedJobs.get(key);
731
+ if (!checked || !raw || typeof raw.gcode_state !== "string") return;
732
+ const state = raw.gcode_state.toUpperCase();
733
+ if (ACTIVE_JOB_STATES.has(state) && reportsJob(raw, checked.remotePath)) {
734
+ checked.seenRunning = true;
735
+ return;
736
+ }
737
+ if (checked.seenRunning && (ENDED_JOB_STATES.has(state) || (ACTIVE_JOB_STATES.has(state) && reportedJobNames(raw).length > 0))) {
738
+ this.checkedJobs.delete(key);
739
+ }
740
+ }
741
+
595
742
  private validateLoadedGcodeState(status: any, inspection: Awaited<ReturnType<typeof inspectPrintFile>>): PrinterStateRequirements {
596
743
  const usedMaterials = inspection.usedFilamentPositions.map(position => inspection.materials[position]);
597
744
  if (new Set(usedMaterials).size !== 1) throw new Error("gcode_file printing cannot verify physical changes between different materials. Use a mapped .3mf project.");
@@ -675,6 +822,69 @@ export class BambuImplementation {
675
822
  return readFreshPrinterStatus(await this.getPrinter(host, serial, token), serial);
676
823
  }
677
824
 
825
+ /**
826
+ * The merged MQTT report for counterpart_print_progress and when it arrived.
827
+ * On a held session it comes from the cache with no printer traffic. PushAll
828
+ * is sent only to fill a cold cache, or at most once per STALE_REPORT_MS when
829
+ * the printer has been quiet for longer than that (P1-series firmware lags
830
+ * when asked often). The whole read, connection and publish included, is
831
+ * bounded by timeoutMs: the MQTT connect to an unreachable printer keeps
832
+ * retrying, so it must not hold the call. Then the result is null, or a stale
833
+ * report that could not be refreshed in time. Display data only; safety
834
+ * checks use getSafetyStatus.
835
+ */
836
+ async readProgressReport(host: string, serial: string, token: string, timeoutMs = 8_000): Promise<ProgressReport | null> {
837
+ const cached = this.printerStore.getCachedReportWithTime(host, serial, token);
838
+ const warm = cached !== null && typeof cached.raw.gcode_state === "string";
839
+ if (warm && (Date.now() - cached.receivedAt <= STALE_REPORT_MS || !this.printerStore.claimRefresh(host, serial, token, STALE_REPORT_MS))) return cached;
840
+ // One first read or refresh per printer at a time. Callers that gave up share
841
+ // it, so a printer that comes back gets one PushAll, not one per expired poll.
842
+ const key = getPrinterKey(host, serial, token);
843
+ let read = this.progressReads.get(key);
844
+ if (!read) {
845
+ const started = warm ? this.refreshProgressReport(host, serial, token, cached) : this.firstProgressReport(host, serial, token);
846
+ read = started.finally(() => { if (this.progressReads.get(key) === read) this.progressReads.delete(key); });
847
+ read.catch(() => {});
848
+ this.progressReads.set(key, read);
849
+ }
850
+ const latest = () => warm ? this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached : null;
851
+ let timer: NodeJS.Timeout | undefined;
852
+ const expired = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
853
+ try {
854
+ return (await Promise.race([read, expired])) ?? latest();
855
+ } catch {
856
+ return latest();
857
+ } finally {
858
+ clearTimeout(timer);
859
+ }
860
+ }
861
+
862
+ private async firstProgressReport(host: string, serial: string, token: string): Promise<ProgressReport | null> {
863
+ const printer = await this.getPrinter(host, serial, token);
864
+ // The printer may already have pushed its full status while connecting.
865
+ if (typeof this.printerStore.getCachedReportWithTime(host, serial, token)?.raw.gcode_state !== "string") {
866
+ try { await invokeWithoutAck(printer, new PushAllCommand()); } catch { /* the printer pushes on its own too */ }
867
+ }
868
+ await this.printerStore.waitForInitialReport(host, serial, token, 4_000);
869
+ // A connected printer whose report still lacks gcode_state is busy, not offline.
870
+ return this.printerStore.getCachedReportWithTime(host, serial, token);
871
+ }
872
+
873
+ private async refreshProgressReport(host: string, serial: string, token: string, cached: ProgressReport): Promise<ProgressReport> {
874
+ try {
875
+ await invokeWithoutAck(await this.getPrinter(host, serial, token), new PushAllCommand());
876
+ const deadline = Date.now() + 2_000;
877
+ while (Date.now() < deadline) {
878
+ const latest = this.printerStore.getCachedReportWithTime(host, serial, token);
879
+ if (latest && latest.receivedAt > cached.receivedAt) return latest;
880
+ await sleep(50);
881
+ }
882
+ } catch {
883
+ // A failed refresh leaves the cached report, which still carries its own time.
884
+ }
885
+ return this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached;
886
+ }
887
+
678
888
  async getStatus(host: string, serial: string, token: string): Promise<any> {
679
889
  try {
680
890
  const printer = await this.getPrinter(host, serial, token);
@@ -777,6 +987,7 @@ export class BambuImplementation {
777
987
  const inspection = await inspectPrintFile(options.filePath, {
778
988
  model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
779
989
  });
990
+ const resumeFile = await checkedFile(inspection, options.filePath);
780
991
  const projectMetadata = await this.resolveProjectFileMetadata(
781
992
  options.filePath,
782
993
  options.plateIndex,
@@ -902,24 +1113,24 @@ export class BambuImplementation {
902
1113
  const initialStatus = await this.getSafetyStatus(host, serial, token);
903
1114
  if (legacyContainer) requirements = this.validateLoadedGcodeState(initialStatus, inspection);
904
1115
  else validatePrinterState(initialStatus, requirements);
905
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1116
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
906
1117
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
907
1118
  if (legacyContainer) requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
908
1119
  else validatePrinterState(confirmedStatus, requirements);
909
- this.assertBedClearance(confirmedStatus, bedClearance);
1120
+ this.assertPrintPreflight(confirmedStatus, preflight);
910
1121
  assertActive();
911
1122
  await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
912
1123
  // Uploads can be long. Recheck current state before the command is dispatched.
913
1124
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
914
1125
  if (legacyContainer) requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
915
1126
  else validatePrinterState(dispatchStatus, requirements);
916
- this.assertBedClearance(dispatchStatus, bedClearance);
1127
+ this.assertPrintPreflight(dispatchStatus, preflight);
917
1128
  const printer = await this.getPrinter(host, serial, token);
918
1129
  assertActive();
919
1130
  if (legacyContainer) {
920
1131
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
921
1132
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath })); } catch (error) { watcher.dispose(); throw error; }
922
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
1133
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
923
1134
  const dispatch = await watcher.settled();
924
1135
  return {
925
1136
  status: "success", dispatch, remoteProjectPath,
@@ -932,8 +1143,13 @@ export class BambuImplementation {
932
1143
 
933
1144
  const b = (v: any) => (v ? 1 : 0);
934
1145
  let projectFileCmd: Record<string, any>;
1146
+ // The printer reports these back as subtask_name/task_id, so the result
1147
+ // returns exactly what was sent. Only the H2-style route sends a real task id.
1148
+ const subtaskName = remoteFileName.replace(/\.3mf$/i, "");
1149
+ let taskId: string | undefined;
935
1150
  if (usesH2ProjectFile) {
936
1151
  const submissionId = String(Date.now() & 0x7fffffff);
1152
+ taskId = submissionId;
937
1153
  projectFileCmd = {
938
1154
  print: {
939
1155
  sequence_id: "0",
@@ -954,7 +1170,7 @@ export class BambuImplementation {
954
1170
  extrude_cali_flag: 0,
955
1171
  extrude_cali_manual_mode: 0,
956
1172
  nozzle_offset_cali: 2,
957
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1173
+ subtask_name: subtaskName,
958
1174
  profile_id: "0",
959
1175
  project_id: submissionId,
960
1176
  subtask_id: submissionId,
@@ -969,7 +1185,7 @@ export class BambuImplementation {
969
1185
  command: "project_file",
970
1186
  param: projectMetadata.plateInternalPath,
971
1187
  url: projectUrl,
972
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1188
+ subtask_name: subtaskName,
973
1189
  md5,
974
1190
  flow_cali: options.flowCalibration ?? true,
975
1191
  layer_inspect: options.layerInspect ?? true,
@@ -990,7 +1206,7 @@ export class BambuImplementation {
990
1206
 
991
1207
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
992
1208
  try { await printer.publish(projectFileCmd); } catch (error) { watcher.dispose(); throw error; }
993
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
1209
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
994
1210
  await new Promise((resolve) => setTimeout(resolve, 300));
995
1211
  const dispatch = await watcher.settled();
996
1212
 
@@ -1006,6 +1222,8 @@ export class BambuImplementation {
1006
1222
  platePath: projectMetadata.plateInternalPath,
1007
1223
  md5,
1008
1224
  amsMapping,
1225
+ subtaskName,
1226
+ ...(taskId !== undefined ? { taskId } : {}),
1009
1227
  };
1010
1228
  }
1011
1229
 
@@ -1082,29 +1300,93 @@ export class BambuImplementation {
1082
1300
  }
1083
1301
  }
1084
1302
 
1303
+ /**
1304
+ * Resume reheats and moves the printer, so it is gated like a print start:
1305
+ * only the job this server inspected and started, while a fresh report shows
1306
+ * it paused, with its bytes re-read over FTPS and compared, and after human
1307
+ * confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
1308
+ * be current at every check, including the native helper's last one.
1309
+ */
1085
1310
  async resumeJob(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any> {
1086
1311
  return withPrinterOperation(host, serial, async assertActive => {
1087
- const checked = this.checkedJobs.get(`${host}\n${serial}`);
1312
+ const key = `${host}\n${serial}`;
1313
+ const checked = this.checkedJobs.get(key);
1088
1314
  if (!checked) throw new Error("Resume requires a job inspected and started by this server instance. Verify other jobs on the printer before resuming them there.");
1089
- const beforeDispatch = async () => {
1315
+ let jobName = path.posix.basename(checked.remotePath);
1316
+ const pausedJob = async () => {
1090
1317
  assertActive();
1091
1318
  const status = await this.getSafetyStatus(host, serial, token);
1319
+ this.observeReport(host, serial, status.raw);
1320
+ if (this.checkedJobs.get(key) !== checked) {
1321
+ 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.`);
1322
+ }
1092
1323
  validatePrinterState(status, { ...checked.requirements, requireIdle: false });
1093
1324
  if (status.raw.gcode_state !== "PAUSE") throw new Error("Resume requires a freshly reported paused job.");
1094
- const stem = (value: string) => path.posix.basename(value).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
1095
- const names = [status.raw.gcode_file, status.raw.subtask_name].filter(value => typeof value === "string");
1096
- if (!names.some(value => stem(value) === stem(checked.remotePath))) throw new Error("Paused job identity does not match this server's inspected artifact.");
1325
+ if (!reportsJob(status.raw, checked.remotePath)) throw new Error("Paused job identity does not match this server's inspected artifact.");
1326
+ jobName = reportedJobName(status.raw) ?? jobName;
1097
1327
  assertActive();
1098
1328
  };
1099
- await beforeDispatch();
1329
+ await pausedJob();
1330
+ const reread = await this.rereadJob(host, token, checked);
1331
+ if ("changed" in reread) {
1332
+ if (this.checkedJobs.get(key) === checked) this.checkedJobs.delete(key);
1333
+ 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.`);
1334
+ }
1335
+ const unread = "unread" in reread ? reread.unread : undefined;
1336
+ if (unread !== undefined && checked.uploadedHere) {
1337
+ 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.`);
1338
+ }
1339
+ const bytesVerified = "verified" in reread;
1340
+ assertActive();
1341
+ await this.confirmHardwareAction(
1342
+ `Resume ${jobName} on ${checked.model.toUpperCase()} (${serial})? It reheats to its targets (peak nozzle ${checked.maxNozzleTemperature}°C, ` +
1343
+ `bed ${checked.maxBedTemperature}°C, chamber ${checked.maxChamberTemperature}°C) and moves. Materials: ${checked.materials.length ? checked.materials.join(", ") : "none declared"}. ` +
1344
+ `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)`}. ` +
1345
+ "Confirm the nozzle path is clear and the filament is still loaded.",
1346
+ false,
1347
+ // The opt-out covers resumes whose bytes were checked; an unverified file always needs a person.
1348
+ 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."
1349
+ );
1350
+ // The job may have been resumed, stopped or replaced at the printer while the prompt was open.
1351
+ await pausedJob();
1100
1352
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
1101
1353
  assertActive();
1102
- if (dispatch) await dispatch(assertActive, beforeDispatch);
1354
+ if (dispatch) await dispatch(assertActive, pausedJob);
1103
1355
  else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "resume" }));
1104
- return { status: "success", message: "Resume command sent successfully." };
1356
+ return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1105
1357
  });
1106
1358
  }
1107
1359
 
1360
+ /**
1361
+ * Re-read a started job's bytes over FTPS: the uploaded file, else the plate
1362
+ * G-code the printer extracted from the project to print it. The first file
1363
+ * that can be read decides; a mismatch is reported as changed.
1364
+ */
1365
+ private async rereadJob(host: string, token: string, checked: CheckedJob): Promise<{ verified: string } | { changed: string } | { unread: string }> {
1366
+ const candidates = [{ remote: checked.remotePath, sha256: checked.sha256 }];
1367
+ if (checked.plate) candidates.push({ remote: extractedPlatePath(checked.remotePath, checked.plate.index), sha256: checked.plate.sha256 });
1368
+ const failures: string[] = [];
1369
+ for (const candidate of candidates) {
1370
+ let sha256: string;
1371
+ try { sha256 = await this.remoteSha256(host, token, candidate.remote); }
1372
+ catch (error) { failures.push(`${candidate.remote}: ${(error as Error).message}`); continue; }
1373
+ return sha256 === candidate.sha256 ? { verified: candidate.remote } : { changed: candidate.remote };
1374
+ }
1375
+ return { unread: failures.join("; ") };
1376
+ }
1377
+
1378
+ /** SHA-256 of a printer file, streamed from an FTPS download into a private directory. */
1379
+ private async remoteSha256(host: string, token: string, remotePath: string): Promise<string> {
1380
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-resume-check-"));
1381
+ try {
1382
+ const localPath = path.join(directory, "job");
1383
+ await this.ftpDownload(host, token, remotePath, localPath);
1384
+ const hash = createHash("sha256");
1385
+ for await (const chunk of createReadStream(localPath)) hash.update(chunk as Buffer);
1386
+ return hash.digest("hex");
1387
+ } finally { await fs.rm(directory, { recursive: true, force: true }); }
1388
+ }
1389
+
1108
1390
  async clearHmsErrors(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any> {
1109
1391
  return withPrinterOperation(host, serial, async assertActive => {
1110
1392
  const codesFor = (status: any): string[] => {
@@ -1541,26 +1823,29 @@ export class BambuImplementation {
1541
1823
  if (!model) throw new Error("A supported bambuModel is required before printing.");
1542
1824
  const inspection = await inspectPrintFile(filePath, { model });
1543
1825
  if (inspection.selectsAms) throw new Error("Raw G-code with AMS selection requires a .3mf project export with verified physical slot mappings.");
1826
+ const resumeFile = await checkedFile(inspection, filePath);
1544
1827
  const initialStatus = await this.getSafetyStatus(host, serial, token);
1545
1828
  let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
1546
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1829
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1547
1830
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
1548
1831
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
1549
- this.assertBedClearance(confirmedStatus, bedClearance);
1832
+ this.assertPrintPreflight(confirmedStatus, preflight);
1550
1833
  assertActive();
1551
1834
  const remotePath = path.posix.join(path.posix.dirname(filename), uniquePrintName(filename));
1552
1835
  await this.ftpUpload(host, token, filePath, `/${remotePath}`);
1553
1836
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
1554
1837
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
1555
- this.assertBedClearance(dispatchStatus, bedClearance);
1838
+ this.assertPrintPreflight(dispatchStatus, preflight);
1556
1839
  const printer = await this.getPrinter(host, serial, token);
1557
1840
  assertActive();
1558
1841
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1559
1842
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath })); } catch (error) { watcher.dispose(); throw error; }
1560
- this.recordCheckedJob(host, serial, remotePath, requirements);
1843
+ this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
1561
1844
  const dispatch = await watcher.settled();
1562
1845
  return {
1563
1846
  status: "success", uploaded: true, printRequested: true, dispatch, remotePath,
1847
+ // counterpart_print_progress reports this as job.name (the printer reports no subtask_name for raw G-code).
1848
+ jobName: path.posix.basename(remotePath),
1564
1849
  message: dispatch === "started"
1565
1850
  ? `The printer accepted and started ${remotePath}.`
1566
1851
  : `Sent the print command for ${remotePath}; the printer has not reported starting yet. Check get_printer_status before assuming it is printing.`,
@@ -1719,19 +2004,7 @@ export class BambuImplementation {
1719
2004
  }> {
1720
2005
  const timeoutMs = options.timeoutMs ?? 8_000;
1721
2006
  const model = (options.bambuModel ?? "").toLowerCase();
1722
- // P1/A1 series still use the proprietary TCP-on-6000 framed JPEG path
1723
- // (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
1724
- const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
1725
- // X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
1726
- // OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
1727
- // integration's models.py shows the printer reports its own
1728
- // `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
1729
- // A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
1730
- // confirmed by local H2 camera transport probes).
1731
- const RTSP_MODELS = new Set([
1732
- "x1", "x1c", "x1carbon", "x1e", "p2s",
1733
- "h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
1734
- ]);
2007
+ const RTSP_MODELS = RTSP_CAMERA_MODELS;
1735
2008
 
1736
2009
  if (!model) {
1737
2010
  throw new Error(