bambu-printer-mcp 1.1.45 → 1.1.47

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.
package/README.md CHANGED
@@ -206,7 +206,7 @@ The optional FULU **BambuNetwork bridge** exposes `bambu_network_bridge_status`,
206
206
  - Set print speed mode (`silent`/`standard`/`sport`/`ludicrous`), clear HMS/print errors, trigger AMS RFID re-read, and control H2/P2 airduct mode (`cooling`/`heating`) via MQTT
207
207
  - **Start/stop AMS filament drying** (`set_ams_drying`) on heated AMS units (AMS Pro / AMS-HT). Sends `print.ams_control` MQTT command.
208
208
  - Set nozzle and bed temperature via G-code dispatch over MQTT
209
- - Confirm print starts and positive manual heating through a human preflight prompt. Finished-bed clearance and hardware-error clearing require explicit human acknowledgment; see [hardware safety and headless configuration](https://github.com/DMontgomery40/bambu-printer-mcp/blob/main/docs/SLICING.md).
209
+ - Confirm print starts and positive manual heating through a human preflight prompt. Hardware-error clearing requires explicit human acknowledgment; see [hardware safety and headless configuration](https://github.com/DMontgomery40/bambu-printer-mcp/blob/main/docs/SLICING.md).
210
210
  - Set fan speed (part, auxiliary, chamber) and chamber light mode (on/off/flashing) via MQTT
211
211
  - Read HMS (Health Management System) diagnostics as an MCP resource at `printer://{host}/hms` — read-only error summary from the printer, with automatic settle retry
212
212
  - Start G-code files already stored on the printer
package/dist/index.js CHANGED
@@ -946,7 +946,7 @@ class BambuPrinterMCPServer {
946
946
  throw new Error(`No hardware confirmation within ${describeDuration(this.confirmationTimeoutMs)}; nothing was sent to the printer. Retry when someone can check the printer, or raise BAMBU_CONFIRMATION_TIMEOUT_MS.`);
947
947
  }
948
948
  if (isElicitationUnsupported(error)) {
949
- throw new Error("Human hardware confirmation requires an MCP client with elicitation support. For deliberately headless operation, BAMBU_REQUIRE_CONFIRMATION=0 disables ordinary print/heat prompts; finished-bed clearance and hardware-error confirmation still require elicitation.");
949
+ throw new Error("Human hardware confirmation requires an MCP client with elicitation support. For deliberately headless operation, BAMBU_REQUIRE_CONFIRMATION=0 disables ordinary print/heat prompts; hardware-error confirmation still requires elicitation.");
950
950
  }
951
951
  throw new Error(`Human hardware confirmation failed: ${error?.message ?? error}. Nothing was sent to the printer.`);
952
952
  }
@@ -1229,10 +1229,10 @@ class BambuPrinterMCPServer {
1229
1229
  const requirements = { ...inspection, amsMapping: mapping, useAMS };
1230
1230
  const initialStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1231
1231
  validatePrinterState(initialStatus, requirements);
1232
- const bedClearance = await this.bambu.confirmPrintPreflight(devId, initialStatus, inspection);
1232
+ const preflight = await this.bambu.confirmPrintPreflight(devId, initialStatus, inspection);
1233
1233
  const confirmedStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1234
1234
  validatePrinterState(confirmedStatus, requirements);
1235
- this.bambu.assertBedClearance(confirmedStatus, bedClearance);
1235
+ this.bambu.assertPrintPreflight(confirmedStatus, preflight);
1236
1236
  const amsMapping = stringifyBridgeJson(mapping?.map(value => bridgeAmsMappingValue(value, isDualNozzleModel(printModel))));
1237
1237
  const remoteFileName = uniquePrintName(threeMFPath);
1238
1238
  const checkedName = remoteFileName.replace(/(?:\.gcode)?\.3mf$/i, "");
@@ -1310,7 +1310,7 @@ class BambuPrinterMCPServer {
1310
1310
  assertActive();
1311
1311
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1312
1312
  validatePrinterState(dispatchStatus, requirements);
1313
- this.bambu.assertBedClearance(dispatchStatus, bedClearance);
1313
+ this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1314
1314
  if (externalStorage && externalStorageState(dispatchStatus.raw) !== "normal") {
1315
1315
  throw new Error("The printer's SD card or USB stick is no longer ready. Check it and start the print again.");
1316
1316
  }
@@ -1328,7 +1328,7 @@ class BambuPrinterMCPServer {
1328
1328
  assertActive();
1329
1329
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1330
1330
  validatePrinterState(dispatchStatus, requirements);
1331
- this.bambu.assertBedClearance(dispatchStatus, bedClearance);
1331
+ this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1332
1332
  },
1333
1333
  assertDispatchAllowed: method => { if (method === bridgeMethod)
1334
1334
  assertActive(); },
@@ -26,7 +26,6 @@ interface BambuPrintOptionsInternal {
26
26
  amsSlots?: number[];
27
27
  md5?: string;
28
28
  }
29
- /** What the human confirmed in confirmPrintPreflight, checked again before dispatch. */
30
29
  export type PrintPreflight = {
31
30
  finishedJob?: string;
32
31
  serial: string;
@@ -47,13 +46,12 @@ export declare class BambuImplementation {
47
46
  confirmHardwareAction(message: string, physicalCheck?: boolean): Promise<void>;
48
47
  private finishedJobIdentity;
49
48
  /**
50
- * The human print confirmation. Its result goes to assertBedClearance at
51
- * every later state check of the same print, which stops the print if the
52
- * situation the human confirmed has changed.
49
+ * Record the current job and notices during preflight so a changed printer state
50
+ * is detected before dispatch.
53
51
  */
54
52
  confirmPrintPreflight(serial: string, status: any, inspection: Awaited<ReturnType<typeof inspectPrintFile>>): Promise<PrintPreflight>;
55
53
  /** Stop a print whose confirmed situation changed: a newly finished job, or a hidden HMS notice the preflight did not name. */
56
- assertBedClearance(status: any, preflight: PrintPreflight): void;
54
+ assertPrintPreflight(status: any, preflight: PrintPreflight): void;
57
55
  private getPrinter;
58
56
  /** Internal handoff from a successful inspected transport; never exposed as an MCP tool. */
59
57
  recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements): void;
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
2
+ import { isFinishedP1SJob, isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
3
3
  import fs from "node:fs/promises";
4
4
  import { readFileSync, existsSync } from "node:fs";
5
5
  import path from "node:path";
@@ -386,6 +386,10 @@ class BambuClientStore {
386
386
  this.initialReportResolvers.clear();
387
387
  }
388
388
  }
389
+ /** The preflight state, checked again before dispatch. */
390
+ function printJobIdentity(raw) {
391
+ return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
392
+ }
389
393
  /**
390
394
  * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
391
395
  * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
@@ -439,14 +443,13 @@ export class BambuImplementation {
439
443
  }
440
444
  finishedJobIdentity(status) {
441
445
  const raw = status.raw;
442
- return raw.gcode_state === "FINISH" || isCancelledX2DJob(raw, String(status.model ?? ""))
443
- ? JSON.stringify([raw.gcode_state, raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id])
446
+ return raw.gcode_state === "FINISH" || (isCancelledX2DJob(raw, String(status.model ?? "")) || isFinishedP1SJob(raw, String(status.model ?? "")))
447
+ ? printJobIdentity(raw)
444
448
  : undefined;
445
449
  }
446
450
  /**
447
- * The human print confirmation. Its result goes to assertBedClearance at
448
- * every later state check of the same print, which stops the print if the
449
- * situation the human confirmed has changed.
451
+ * Record the current job and notices during preflight so a changed printer state
452
+ * is detected before dispatch.
450
453
  */
451
454
  async confirmPrintPreflight(serial, status, inspection) {
452
455
  const finishedJob = this.finishedJobIdentity(status);
@@ -455,22 +458,21 @@ export class BambuImplementation {
455
458
  const unchipped = unchippedNozzles(status?.raw);
456
459
  await this.confirmHardwareAction(`Start a checked print on ${inspection.model.toUpperCase()} (${serial})? Nozzles: ${inspection.nozzleDiameters.join(", ")} mm. ` +
457
460
  `Materials: ${inspection.materials.join(", ")}. Peak targets: nozzle ${inspection.maxNozzleTemperature}°C, bed ${inspection.maxBedTemperature}°C, chamber ${inspection.maxChamberTemperature}°C. ` +
458
- `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels and that the build plate is clear.` +
459
- (finishedJob !== undefined ? (status.raw.gcode_state === "FAILED"
460
- ? " 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."
461
- : " The printer reports FINISH: remove the previous part and debris before confirming.") : "") +
461
+ `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels.` +
462
+ (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." : "") +
462
463
  (cleared ? ` Previously cleared hardware codes: ${cleared.map(describeHmsKey).join(", ")}. Confirm their physical causes have been resolved.` : "") +
463
464
  (notices.length ? ` The printer also reports ${notices.join(", ")}, which Bambu lists for this model without text and never shows as a fault; ` +
464
465
  `${notices.length === 1 ? "it does" : "they do"} not block printing.` : "") +
465
466
  (unchipped.length ? ` Printer ${unchipped.length === 1 ? `nozzle ${unchipped[0]} reports` : `nozzles ${unchipped.join(" and ")} report`} no identity chip, ` +
466
- `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);
467
+ `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);
467
468
  return { finishedJob, serial, model: inspection.model, notices };
468
469
  }
469
470
  /** Stop a print whose confirmed situation changed: a newly finished job, or a hidden HMS notice the preflight did not name. */
470
- assertBedClearance(status, preflight) {
471
+ assertPrintPreflight(status, preflight) {
471
472
  const current = this.finishedJobIdentity(status);
472
- if (current !== undefined && current !== preflight.finishedJob) {
473
- throw new Error("Printer reports a newly finished job. Confirm that its part and debris have been removed before retrying the print.");
473
+ if ((preflight.finishedJob !== undefined && printJobIdentity(status.raw) !== preflight.finishedJob)
474
+ || (current !== undefined && preflight.finishedJob === undefined)) {
475
+ throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
474
476
  }
475
477
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
476
478
  // can appear after the human confirmed. Never pass a notice nobody was told about.
@@ -755,13 +757,13 @@ export class BambuImplementation {
755
757
  requirements = this.validateLoadedGcodeState(initialStatus, inspection);
756
758
  else
757
759
  validatePrinterState(initialStatus, requirements);
758
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
760
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
759
761
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
760
762
  if (legacyContainer)
761
763
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
762
764
  else
763
765
  validatePrinterState(confirmedStatus, requirements);
764
- this.assertBedClearance(confirmedStatus, bedClearance);
766
+ this.assertPrintPreflight(confirmedStatus, preflight);
765
767
  assertActive();
766
768
  await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
767
769
  // Uploads can be long. Recheck current state before the command is dispatched.
@@ -770,7 +772,7 @@ export class BambuImplementation {
770
772
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
771
773
  else
772
774
  validatePrinterState(dispatchStatus, requirements);
773
- this.assertBedClearance(dispatchStatus, bedClearance);
775
+ this.assertPrintPreflight(dispatchStatus, preflight);
774
776
  const printer = await this.getPrinter(host, serial, token);
775
777
  assertActive();
776
778
  if (legacyContainer) {
@@ -1339,16 +1341,16 @@ export class BambuImplementation {
1339
1341
  throw new Error("Raw G-code with AMS selection requires a .3mf project export with verified physical slot mappings.");
1340
1342
  const initialStatus = await this.getSafetyStatus(host, serial, token);
1341
1343
  let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
1342
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1344
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1343
1345
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
1344
1346
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
1345
- this.assertBedClearance(confirmedStatus, bedClearance);
1347
+ this.assertPrintPreflight(confirmedStatus, preflight);
1346
1348
  assertActive();
1347
1349
  const remotePath = path.posix.join(path.posix.dirname(filename), uniquePrintName(filename));
1348
1350
  await this.ftpUpload(host, token, filePath, `/${remotePath}`);
1349
1351
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
1350
1352
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
1351
- this.assertBedClearance(dispatchStatus, bedClearance);
1353
+ this.assertPrintPreflight(dispatchStatus, preflight);
1352
1354
  const printer = await this.getPrinter(host, serial, token);
1353
1355
  assertActive();
1354
1356
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
@@ -46,9 +46,13 @@ export interface ValidatedPrinterState {
46
46
  * calls 0300400C "The task was canceled."
47
47
  * Only this observed terminal condition qualifies, never an arbitrary failure.
48
48
  * Callers still validate HMS, identity, hardware and material configuration,
49
- * and print dispatch must obtain job-bound physical bed-clearance confirmation.
49
+ * and print dispatch rechecks the identity of the observed job.
50
50
  */
51
51
  export declare function isCancelledX2DJob(raw: Record<string, any>, model: string): boolean;
52
+ /** Bambu Studio 2.8.2.61 marks FAILED as finished. Limit P1S recovery to
53
+ * a named prior job explicitly reporting idle, no print error and no HMS.
54
+ * Dispatch rechecks the observed job identity. */
55
+ export declare function isFinishedP1SJob(raw: Record<string, any>, model: string): boolean;
52
56
  /** Nozzles whose reported diameter and type are configured settings rather than chip readings. */
53
57
  export declare function unchippedNozzles(raw: unknown): number[];
54
58
  /** The one key format for a reported entry, shared by the gate and clear_hms_errors. */
@@ -123,13 +123,21 @@ function finiteNumber(value) {
123
123
  * calls 0300400C "The task was canceled."
124
124
  * Only this observed terminal condition qualifies, never an arbitrary failure.
125
125
  * Callers still validate HMS, identity, hardware and material configuration,
126
- * and print dispatch must obtain job-bound physical bed-clearance confirmation.
126
+ * and print dispatch rechecks the identity of the observed job.
127
127
  */
128
128
  export function isCancelledX2DJob(raw, model) {
129
129
  return normalizeModel(model) === "x2d" && raw.gcode_state === "FAILED" &&
130
130
  finiteNumber(raw.print_error) === 0 && finiteNumber(raw.fail_reason) === 0x0300400c &&
131
131
  [raw.gcode_file, raw.subtask_name].some(value => typeof value === "string" && value.trim().length > 0);
132
132
  }
133
+ /** Bambu Studio 2.8.2.61 marks FAILED as finished. Limit P1S recovery to
134
+ * a named prior job explicitly reporting idle, no print error and no HMS.
135
+ * Dispatch rechecks the observed job identity. */
136
+ export function isFinishedP1SJob(raw, model) {
137
+ return normalizeModel(model) === "p1s" && raw.gcode_state === "FAILED" && raw.print_type === "idle" &&
138
+ finiteNumber(raw.print_error) === 0 && Array.isArray(raw.hms) && raw.hms.length === 0 &&
139
+ [raw.gcode_file, raw.subtask_name].some(value => typeof value === "string" && value.trim().length > 0);
140
+ }
133
141
  const token = (value) => typeof value === "string" ? value.trim().toLowerCase().replace(/[\s_-]/g, "") : "";
134
142
  function nozzleTypeAndFlow(value) {
135
143
  const text = String(value ?? "");
@@ -310,10 +318,10 @@ function logHiddenNotices(raw, serial, model) {
310
318
  }
311
319
  function validateErrors(raw, requireIdle, serial, model) {
312
320
  const state = typeof raw.gcode_state === "string" ? raw.gcode_state.toUpperCase() : "UNKNOWN";
313
- const cancelled = isCancelledX2DJob(raw, model);
314
- if (requireIdle && !["IDLE", "FINISH"].includes(state) && !cancelled)
321
+ const terminal = isCancelledX2DJob(raw, model) || isFinishedP1SJob(raw, model);
322
+ if (requireIdle && !["IDLE", "FINISH"].includes(state) && !terminal)
315
323
  throw new Error(`Printer state ${state} is not safely idle.`);
316
- if (!requireIdle && !["IDLE", "FINISH", "RUNNING", "PAUSE"].includes(state) && !cancelled)
324
+ if (!requireIdle && !["IDLE", "FINISH", "RUNNING", "PAUSE"].includes(state) && !terminal)
317
325
  throw new Error(`Printer state ${state} is unknown or failed.`);
318
326
  if (finiteNumber(raw.print_error) !== 0)
319
327
  throw new Error("Printer reports a print error or did not report its error state.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.45",
3
+ "version": "1.1.47",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
package/src/index.ts CHANGED
@@ -1243,7 +1243,7 @@ class BambuPrinterMCPServer {
1243
1243
  throw new Error(`No hardware confirmation within ${describeDuration(this.confirmationTimeoutMs)}; nothing was sent to the printer. Retry when someone can check the printer, or raise BAMBU_CONFIRMATION_TIMEOUT_MS.`);
1244
1244
  }
1245
1245
  if (isElicitationUnsupported(error)) {
1246
- throw new Error("Human hardware confirmation requires an MCP client with elicitation support. For deliberately headless operation, BAMBU_REQUIRE_CONFIRMATION=0 disables ordinary print/heat prompts; finished-bed clearance and hardware-error confirmation still require elicitation.");
1246
+ throw new Error("Human hardware confirmation requires an MCP client with elicitation support. For deliberately headless operation, BAMBU_REQUIRE_CONFIRMATION=0 disables ordinary print/heat prompts; hardware-error confirmation still requires elicitation.");
1247
1247
  }
1248
1248
  throw new Error(`Human hardware confirmation failed: ${error?.message ?? error}. Nothing was sent to the printer.`);
1249
1249
  }
@@ -1642,10 +1642,10 @@ class BambuPrinterMCPServer {
1642
1642
  const requirements = { ...inspection, amsMapping: mapping, useAMS };
1643
1643
  const initialStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1644
1644
  validatePrinterState(initialStatus, requirements);
1645
- const bedClearance = await this.bambu.confirmPrintPreflight(devId, initialStatus, inspection);
1645
+ const preflight = await this.bambu.confirmPrintPreflight(devId, initialStatus, inspection);
1646
1646
  const confirmedStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1647
1647
  validatePrinterState(confirmedStatus, requirements);
1648
- this.bambu.assertBedClearance(confirmedStatus, bedClearance);
1648
+ this.bambu.assertPrintPreflight(confirmedStatus, preflight);
1649
1649
  const amsMapping = stringifyBridgeJson(mapping?.map(value => bridgeAmsMappingValue(value, isDualNozzleModel(printModel))));
1650
1650
  const remoteFileName = uniquePrintName(threeMFPath);
1651
1651
  const checkedName = remoteFileName.replace(/(?:\.gcode)?\.3mf$/i, "");
@@ -1724,7 +1724,7 @@ class BambuPrinterMCPServer {
1724
1724
  assertActive();
1725
1725
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1726
1726
  validatePrinterState(dispatchStatus, requirements);
1727
- this.bambu.assertBedClearance(dispatchStatus, bedClearance);
1727
+ this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1728
1728
  if (externalStorage && externalStorageState(dispatchStatus.raw) !== "normal") {
1729
1729
  throw new Error("The printer's SD card or USB stick is no longer ready. Check it and start the print again.");
1730
1730
  }
@@ -1741,7 +1741,7 @@ class BambuPrinterMCPServer {
1741
1741
  assertActive();
1742
1742
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1743
1743
  validatePrinterState(dispatchStatus, requirements);
1744
- this.bambu.assertBedClearance(dispatchStatus, bedClearance);
1744
+ this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1745
1745
  },
1746
1746
  assertDispatchAllowed: method => { if (method === bridgeMethod) assertActive(); },
1747
1747
  onDispatched: method => { if (method === bridgeMethod) retainForDispatchedUpload(); },
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
2
+ import { isFinishedP1SJob, isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
3
3
  import fs from "node:fs/promises";
4
4
  import { readFileSync, existsSync } from "node:fs";
5
5
  import path from "node:path";
@@ -471,7 +471,11 @@ class BambuClientStore {
471
471
  }
472
472
  }
473
473
 
474
- /** What the human confirmed in confirmPrintPreflight, checked again before dispatch. */
474
+ /** The preflight state, checked again before dispatch. */
475
+ function printJobIdentity(raw: Record<string, any>): string {
476
+ return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
477
+ }
478
+
475
479
  export type PrintPreflight = { finishedJob?: string; serial: string; model: string; notices: string[] };
476
480
 
477
481
  /**
@@ -528,15 +532,14 @@ export class BambuImplementation {
528
532
 
529
533
  private finishedJobIdentity(status: any): string | undefined {
530
534
  const raw = status.raw;
531
- return raw.gcode_state === "FINISH" || isCancelledX2DJob(raw, String(status.model ?? ""))
532
- ? JSON.stringify([raw.gcode_state, raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id])
535
+ return raw.gcode_state === "FINISH" || (isCancelledX2DJob(raw, String(status.model ?? "")) || isFinishedP1SJob(raw, String(status.model ?? "")))
536
+ ? printJobIdentity(raw)
533
537
  : undefined;
534
538
  }
535
539
 
536
540
  /**
537
- * The human print confirmation. Its result goes to assertBedClearance at
538
- * every later state check of the same print, which stops the print if the
539
- * situation the human confirmed has changed.
541
+ * Record the current job and notices during preflight so a changed printer state
542
+ * is detected before dispatch.
540
543
  */
541
544
  async confirmPrintPreflight(serial: string, status: any, inspection: Awaited<ReturnType<typeof inspectPrintFile>>): Promise<PrintPreflight> {
542
545
  const finishedJob = this.finishedJobIdentity(status);
@@ -546,25 +549,24 @@ export class BambuImplementation {
546
549
  await this.confirmHardwareAction(
547
550
  `Start a checked print on ${inspection.model.toUpperCase()} (${serial})? Nozzles: ${inspection.nozzleDiameters.join(", ")} mm. ` +
548
551
  `Materials: ${inspection.materials.join(", ")}. Peak targets: nozzle ${inspection.maxNozzleTemperature}°C, bed ${inspection.maxBedTemperature}°C, chamber ${inspection.maxChamberTemperature}°C. ` +
549
- `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels and that the build plate is clear.` +
550
- (finishedJob !== undefined ? (status.raw.gcode_state === "FAILED"
551
- ? " 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."
552
- : " The printer reports FINISH: remove the previous part and debris before confirming.") : "") +
552
+ `File SHA-256: ${inspection.sha256}. Confirm the physical spool labels.` +
553
+ (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." : "") +
553
554
  (cleared ? ` Previously cleared hardware codes: ${cleared.map(describeHmsKey).join(", ")}. Confirm their physical causes have been resolved.` : "") +
554
555
  (notices.length ? ` The printer also reports ${notices.join(", ")}, which Bambu lists for this model without text and never shows as a fault; ` +
555
556
  `${notices.length === 1 ? "it does" : "they do"} not block printing.` : "") +
556
557
  (unchipped.length ? ` Printer ${unchipped.length === 1 ? `nozzle ${unchipped[0]} reports` : `nozzles ${unchipped.join(" and ")} report`} no identity chip, ` +
557
558
  `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"}.` : ""),
558
- finishedJob !== undefined || !!cleared
559
+ !!cleared
559
560
  );
560
561
  return { finishedJob, serial, model: inspection.model, notices };
561
562
  }
562
563
 
563
564
  /** Stop a print whose confirmed situation changed: a newly finished job, or a hidden HMS notice the preflight did not name. */
564
- assertBedClearance(status: any, preflight: PrintPreflight): void {
565
+ assertPrintPreflight(status: any, preflight: PrintPreflight): void {
565
566
  const current = this.finishedJobIdentity(status);
566
- if (current !== undefined && current !== preflight.finishedJob) {
567
- throw new Error("Printer reports a newly finished job. Confirm that its part and debris have been removed before retrying the print.");
567
+ if ((preflight.finishedJob !== undefined && printJobIdentity(status.raw) !== preflight.finishedJob)
568
+ || (current !== undefined && preflight.finishedJob === undefined)) {
569
+ throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
568
570
  }
569
571
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
570
572
  // can appear after the human confirmed. Never pass a notice nobody was told about.
@@ -895,18 +897,18 @@ export class BambuImplementation {
895
897
  const initialStatus = await this.getSafetyStatus(host, serial, token);
896
898
  if (legacyContainer) requirements = this.validateLoadedGcodeState(initialStatus, inspection);
897
899
  else validatePrinterState(initialStatus, requirements);
898
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
900
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
899
901
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
900
902
  if (legacyContainer) requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
901
903
  else validatePrinterState(confirmedStatus, requirements);
902
- this.assertBedClearance(confirmedStatus, bedClearance);
904
+ this.assertPrintPreflight(confirmedStatus, preflight);
903
905
  assertActive();
904
906
  await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
905
907
  // Uploads can be long. Recheck current state before the command is dispatched.
906
908
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
907
909
  if (legacyContainer) requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
908
910
  else validatePrinterState(dispatchStatus, requirements);
909
- this.assertBedClearance(dispatchStatus, bedClearance);
911
+ this.assertPrintPreflight(dispatchStatus, preflight);
910
912
  const printer = await this.getPrinter(host, serial, token);
911
913
  assertActive();
912
914
  if (legacyContainer) {
@@ -1536,16 +1538,16 @@ export class BambuImplementation {
1536
1538
  if (inspection.selectsAms) throw new Error("Raw G-code with AMS selection requires a .3mf project export with verified physical slot mappings.");
1537
1539
  const initialStatus = await this.getSafetyStatus(host, serial, token);
1538
1540
  let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
1539
- const bedClearance = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1541
+ const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
1540
1542
  const confirmedStatus = await this.getSafetyStatus(host, serial, token);
1541
1543
  requirements = this.validateLoadedGcodeState(confirmedStatus, inspection);
1542
- this.assertBedClearance(confirmedStatus, bedClearance);
1544
+ this.assertPrintPreflight(confirmedStatus, preflight);
1543
1545
  assertActive();
1544
1546
  const remotePath = path.posix.join(path.posix.dirname(filename), uniquePrintName(filename));
1545
1547
  await this.ftpUpload(host, token, filePath, `/${remotePath}`);
1546
1548
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
1547
1549
  requirements = this.validateLoadedGcodeState(dispatchStatus, inspection);
1548
- this.assertBedClearance(dispatchStatus, bedClearance);
1550
+ this.assertPrintPreflight(dispatchStatus, preflight);
1549
1551
  const printer = await this.getPrinter(host, serial, token);
1550
1552
  assertActive();
1551
1553
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
@@ -134,13 +134,21 @@ function finiteNumber(value: unknown): number | undefined {
134
134
  * calls 0300400C "The task was canceled."
135
135
  * Only this observed terminal condition qualifies, never an arbitrary failure.
136
136
  * Callers still validate HMS, identity, hardware and material configuration,
137
- * and print dispatch must obtain job-bound physical bed-clearance confirmation.
137
+ * and print dispatch rechecks the identity of the observed job.
138
138
  */
139
139
  export function isCancelledX2DJob(raw: Record<string, any>, model: string): boolean {
140
140
  return normalizeModel(model) === "x2d" && raw.gcode_state === "FAILED" &&
141
141
  finiteNumber(raw.print_error) === 0 && finiteNumber(raw.fail_reason) === 0x0300400c &&
142
142
  [raw.gcode_file, raw.subtask_name].some(value => typeof value === "string" && value.trim().length > 0);
143
143
  }
144
+ /** Bambu Studio 2.8.2.61 marks FAILED as finished. Limit P1S recovery to
145
+ * a named prior job explicitly reporting idle, no print error and no HMS.
146
+ * Dispatch rechecks the observed job identity. */
147
+ export function isFinishedP1SJob(raw: Record<string, any>, model: string): boolean {
148
+ return normalizeModel(model) === "p1s" && raw.gcode_state === "FAILED" && raw.print_type === "idle" &&
149
+ finiteNumber(raw.print_error) === 0 && Array.isArray(raw.hms) && raw.hms.length === 0 &&
150
+ [raw.gcode_file, raw.subtask_name].some(value => typeof value === "string" && value.trim().length > 0);
151
+ }
144
152
  const token = (value: unknown) => typeof value === "string" ? value.trim().toLowerCase().replace(/[\s_-]/g, "") : "";
145
153
  function nozzleTypeAndFlow(value: unknown): {type?: string; flow?: string} {
146
154
  const text = String(value ?? "");
@@ -319,9 +327,9 @@ function logHiddenNotices(raw: Record<string, any>, serial: string, model: strin
319
327
 
320
328
  function validateErrors(raw: Record<string,any>, requireIdle: boolean, serial: string, model: string) {
321
329
  const state = typeof raw.gcode_state === "string" ? raw.gcode_state.toUpperCase() : "UNKNOWN";
322
- const cancelled = isCancelledX2DJob(raw, model);
323
- if (requireIdle && !["IDLE","FINISH"].includes(state) && !cancelled) throw new Error(`Printer state ${state} is not safely idle.`);
324
- if (!requireIdle && !["IDLE","FINISH","RUNNING","PAUSE"].includes(state) && !cancelled) throw new Error(`Printer state ${state} is unknown or failed.`);
330
+ const terminal = isCancelledX2DJob(raw, model) || isFinishedP1SJob(raw, model);
331
+ if (requireIdle && !["IDLE","FINISH"].includes(state) && !terminal) throw new Error(`Printer state ${state} is not safely idle.`);
332
+ if (!requireIdle && !["IDLE","FINISH","RUNNING","PAUSE"].includes(state) && !terminal) throw new Error(`Printer state ${state} is unknown or failed.`);
325
333
  if (finiteNumber(raw.print_error) !== 0) throw new Error("Printer reports a print error or did not report its error state.");
326
334
  if (!Array.isArray(raw.hms)) throw new Error("Printer HMS error state is missing or malformed.");
327
335
  for (const reported of raw.hms) {