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 } 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,14 +421,60 @@ 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
  }
388
429
  }
389
- /** What the human confirmed in confirmPrintPreflight, checked again before dispatch. */
430
+ /** The preflight state, checked again before dispatch. */
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) {
@@ -448,9 +545,8 @@ export class BambuImplementation {
448
545
  : undefined;
449
546
  }
450
547
  /**
451
- * The human print confirmation. Its result goes to assertBedClearance at
452
- * every later state check of the same print, which stops the print if the
453
- * situation the human confirmed has changed.
548
+ * Record the current job and notices during preflight so a changed printer state
549
+ * is detected before dispatch.
454
550
  */
455
551
  async confirmPrintPreflight(serial, status, inspection) {
456
552
  const finishedJob = this.finishedJobIdentity(status);
@@ -459,25 +555,21 @@ export class BambuImplementation {
459
555
  const unchipped = unchippedNozzles(status?.raw);
460
556
  await this.confirmHardwareAction(`Start a checked print on ${inspection.model.toUpperCase()} (${serial})? Nozzles: ${inspection.nozzleDiameters.join(", ")} mm. ` +
461
557
  `Materials: ${inspection.materials.join(", ")}. Peak targets: nozzle ${inspection.maxNozzleTemperature}°C, bed ${inspection.maxBedTemperature}°C, chamber ${inspection.maxChamberTemperature}°C. ` +
462
- `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels and that the build plate is clear.` +
463
- (finishedJob !== undefined ? (status.raw.gcode_state === "FAILED"
464
- ? (isFinishedP1SJob(status.raw, inspection.model)
465
- ? " 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."
466
- : " 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.")
467
- : " The printer reports FINISH: remove the previous part and debris before confirming.") : "") +
558
+ `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels.` +
559
+ (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." : "") +
468
560
  (cleared ? ` Previously cleared hardware codes: ${cleared.map(describeHmsKey).join(", ")}. Confirm their physical causes have been resolved.` : "") +
469
561
  (notices.length ? ` The printer also reports ${notices.join(", ")}, which Bambu lists for this model without text and never shows as a fault; ` +
470
562
  `${notices.length === 1 ? "it does" : "they do"} not block printing.` : "") +
471
563
  (unchipped.length ? ` Printer ${unchipped.length === 1 ? `nozzle ${unchipped[0]} reports` : `nozzles ${unchipped.join(" and ")} report`} no identity chip, ` +
472
- `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"}.` : ""), finishedJob !== undefined || !!cleared);
564
+ `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"}.` : ""), !!cleared);
473
565
  return { finishedJob, serial, model: inspection.model, notices };
474
566
  }
475
567
  /** Stop a print whose confirmed situation changed: a newly finished job, or a hidden HMS notice the preflight did not name. */
476
- assertBedClearance(status, preflight) {
568
+ assertPrintPreflight(status, preflight) {
477
569
  const current = this.finishedJobIdentity(status);
478
570
  if ((preflight.finishedJob !== undefined && printJobIdentity(status.raw) !== preflight.finishedJob)
479
571
  || (current !== undefined && preflight.finishedJob === undefined)) {
480
- throw new Error("Printer reports a newly finished job. Confirm that its part and debris have been removed before retrying the print.");
572
+ throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
481
573
  }
482
574
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
483
575
  // can appear after the human confirmed. Never pass a notice nobody was told about.
@@ -490,11 +582,36 @@ export class BambuImplementation {
490
582
  async getPrinter(host, serial, token) {
491
583
  return this.printerStore.getPrinter(host, serial, token);
492
584
  }
493
- /** Internal handoff from a successful inspected transport; never exposed as an MCP tool. */
494
- recordCheckedJob(host, serial, remotePath, requirements) {
495
- 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
+ });
496
598
  this.clearedErrors.delete(serial);
497
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
+ }
498
615
  validateLoadedGcodeState(status, inspection) {
499
616
  const usedMaterials = inspection.usedFilamentPositions.map(position => inspection.materials[position]);
500
617
  if (new Set(usedMaterials).size !== 1)
@@ -570,6 +687,75 @@ export class BambuImplementation {
570
687
  async getSafetyStatus(host, serial, token) {
571
688
  return readFreshPrinterStatus(await this.getPrinter(host, serial, token), serial);
572
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
+ }
573
759
  async getStatus(host, serial, token) {
574
760
  try {
575
761
  const printer = await this.getPrinter(host, serial, token);
@@ -657,6 +843,7 @@ export class BambuImplementation {
657
843
  const inspection = await inspectPrintFile(options.filePath, {
658
844
  model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
659
845
  });
846
+ const resumeFile = await checkedFile(inspection, options.filePath);
660
847
  const projectMetadata = await this.resolveProjectFileMetadata(options.filePath, options.plateIndex, inspection.plateInternalPath);
661
848
  // Send project_file command via bambu-node MQTT (bypasses bambu-js
662
849
  // hardcoded use_ams=true and missing ams_mapping support)
@@ -762,13 +949,13 @@ export class BambuImplementation {
762
949
  requirements = this.validateLoadedGcodeState(initialStatus, inspection);
763
950
  else
764
951
  validatePrinterState(initialStatus, requirements);
765
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
952
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
766
953
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
767
954
  if (legacyContainer)
768
955
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
769
956
  else
770
957
  validatePrinterState(confirmedStatus, requirements);
771
- this.assertBedClearance(confirmedStatus, bedClearance);
958
+ this.assertPrintPreflight(confirmedStatus, preflight);
772
959
  assertActive();
773
960
  await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
774
961
  // Uploads can be long. Recheck current state before the command is dispatched.
@@ -777,7 +964,7 @@ export class BambuImplementation {
777
964
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
778
965
  else
779
966
  validatePrinterState(dispatchStatus, requirements);
780
- this.assertBedClearance(dispatchStatus, bedClearance);
967
+ this.assertPrintPreflight(dispatchStatus, preflight);
781
968
  const printer = await this.getPrinter(host, serial, token);
782
969
  assertActive();
783
970
  if (legacyContainer) {
@@ -789,7 +976,7 @@ export class BambuImplementation {
789
976
  watcher.dispose();
790
977
  throw error;
791
978
  }
792
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
979
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
793
980
  const dispatch = await watcher.settled();
794
981
  return {
795
982
  status: "success", dispatch, remoteProjectPath,
@@ -801,8 +988,13 @@ export class BambuImplementation {
801
988
  }
802
989
  const b = (v) => (v ? 1 : 0);
803
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;
804
995
  if (usesH2ProjectFile) {
805
996
  const submissionId = String(Date.now() & 0x7fffffff);
997
+ taskId = submissionId;
806
998
  projectFileCmd = {
807
999
  print: {
808
1000
  sequence_id: "0",
@@ -823,7 +1015,7 @@ export class BambuImplementation {
823
1015
  extrude_cali_flag: 0,
824
1016
  extrude_cali_manual_mode: 0,
825
1017
  nozzle_offset_cali: 2,
826
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1018
+ subtask_name: subtaskName,
827
1019
  profile_id: "0",
828
1020
  project_id: submissionId,
829
1021
  subtask_id: submissionId,
@@ -839,7 +1031,7 @@ export class BambuImplementation {
839
1031
  command: "project_file",
840
1032
  param: projectMetadata.plateInternalPath,
841
1033
  url: projectUrl,
842
- subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
1034
+ subtask_name: subtaskName,
843
1035
  md5,
844
1036
  flow_cali: options.flowCalibration ?? true,
845
1037
  layer_inspect: options.layerInspect ?? true,
@@ -865,7 +1057,7 @@ export class BambuImplementation {
865
1057
  watcher.dispose();
866
1058
  throw error;
867
1059
  }
868
- this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
1060
+ this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
869
1061
  await new Promise((resolve) => setTimeout(resolve, 300));
870
1062
  const dispatch = await watcher.settled();
871
1063
  return {
@@ -880,6 +1072,8 @@ export class BambuImplementation {
880
1072
  platePath: projectMetadata.plateInternalPath,
881
1073
  md5,
882
1074
  amsMapping,
1075
+ subtaskName,
1076
+ ...(taskId !== undefined ? { taskId } : {}),
883
1077
  };
884
1078
  }
885
1079
  async cancelJob(host, serial, token, dispatch) {
@@ -955,33 +1149,103 @@ export class BambuImplementation {
955
1149
  throw new Error(`Failed to pause print: ${error.message}`);
956
1150
  }
957
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
+ */
958
1159
  async resumeJob(host, serial, token, dispatch) {
959
1160
  return withPrinterOperation(host, serial, async (assertActive) => {
960
- const checked = this.checkedJobs.get(`${host}\n${serial}`);
1161
+ const key = `${host}\n${serial}`;
1162
+ const checked = this.checkedJobs.get(key);
961
1163
  if (!checked)
962
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.");
963
- const beforeDispatch = async () => {
1165
+ let jobName = path.posix.basename(checked.remotePath);
1166
+ const pausedJob = async () => {
964
1167
  assertActive();
965
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
+ }
966
1173
  validatePrinterState(status, { ...checked.requirements, requireIdle: false });
967
1174
  if (status.raw.gcode_state !== "PAUSE")
968
1175
  throw new Error("Resume requires a freshly reported paused job.");
969
- const stem = (value) => path.posix.basename(value).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
970
- const names = [status.raw.gcode_file, status.raw.subtask_name].filter(value => typeof value === "string");
971
- if (!names.some(value => stem(value) === stem(checked.remotePath)))
1176
+ if (!reportsJob(status.raw, checked.remotePath))
972
1177
  throw new Error("Paused job identity does not match this server's inspected artifact.");
1178
+ jobName = reportedJobName(status.raw) ?? jobName;
973
1179
  assertActive();
974
1180
  };
975
- 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();
976
1202
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
977
1203
  assertActive();
978
1204
  if (dispatch)
979
- await dispatch(assertActive, beforeDispatch);
1205
+ await dispatch(assertActive, pausedJob);
980
1206
  else
981
1207
  await invokeWithoutAck(printer, new UpdateStateCommand({ state: "resume" }));
982
- return { status: "success", message: "Resume command sent successfully." };
1208
+ return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
983
1209
  });
984
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
+ }
985
1249
  async clearHmsErrors(host, serial, token, dispatch) {
986
1250
  return withPrinterOperation(host, serial, async (assertActive) => {
987
1251
  const codesFor = (status) => {
@@ -1344,18 +1608,19 @@ export class BambuImplementation {
1344
1608
  const inspection = await inspectPrintFile(filePath, { model });
1345
1609
  if (inspection.selectsAms)
1346
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);
1347
1612
  const initialStatus = await this.getSafetyStatus(host, serial, token);
1348
1613
  let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
1349
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1614
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1350
1615
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
1351
1616
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
1352
- this.assertBedClearance(confirmedStatus, bedClearance);
1617
+ this.assertPrintPreflight(confirmedStatus, preflight);
1353
1618
  assertActive();
1354
1619
  const remotePath = path.posix.join(path.posix.dirname(filename), uniquePrintName(filename));
1355
1620
  await this.ftpUpload(host, token, filePath, `/${remotePath}`);
1356
1621
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
1357
1622
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
1358
- this.assertBedClearance(dispatchStatus, bedClearance);
1623
+ this.assertPrintPreflight(dispatchStatus, preflight);
1359
1624
  const printer = await this.getPrinter(host, serial, token);
1360
1625
  assertActive();
1361
1626
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
@@ -1366,10 +1631,12 @@ export class BambuImplementation {
1366
1631
  watcher.dispose();
1367
1632
  throw error;
1368
1633
  }
1369
- this.recordCheckedJob(host, serial, remotePath, requirements);
1634
+ this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
1370
1635
  const dispatch = await watcher.settled();
1371
1636
  return {
1372
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),
1373
1640
  message: dispatch === "started"
1374
1641
  ? `The printer accepted and started ${remotePath}.`
1375
1642
  : `Sent the print command for ${remotePath}; the printer has not reported starting yet. Check get_printer_status before assuming it is printing.`,
@@ -1524,19 +1791,7 @@ export class BambuImplementation {
1524
1791
  async cameraSnapshot(host, _serial, token, options = {}) {
1525
1792
  const timeoutMs = options.timeoutMs ?? 8000;
1526
1793
  const model = (options.bambuModel ?? "").toLowerCase();
1527
- // P1/A1 series still use the proprietary TCP-on-6000 framed JPEG path
1528
- // (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
1529
- const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
1530
- // X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
1531
- // OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
1532
- // integration's models.py shows the printer reports its own
1533
- // `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
1534
- // A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
1535
- // confirmed by local H2 camera transport probes).
1536
- const RTSP_MODELS = new Set([
1537
- "x1", "x1c", "x1carbon", "x1e", "p2s",
1538
- "h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
1539
- ]);
1794
+ const RTSP_MODELS = RTSP_CAMERA_MODELS;
1540
1795
  if (!model) {
1541
1796
  throw new Error("camera_snapshot requires bambu_model or BAMBU_MODEL so it can choose the correct Bambu camera protocol.");
1542
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
+ ]);