bambu-printer-mcp 1.1.50 → 1.1.52

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 (54) hide show
  1. package/README.md +33 -8
  2. package/dist/ams-mapping.d.ts +19 -0
  3. package/dist/ams-mapping.js +49 -0
  4. package/dist/bambu-network-bridge.d.ts +86 -9
  5. package/dist/bambu-network-bridge.js +284 -4
  6. package/dist/control-reply.d.ts +21 -0
  7. package/dist/control-reply.js +44 -0
  8. package/dist/counterpart/info.js +1 -0
  9. package/dist/counterpart/route.d.ts +37 -0
  10. package/dist/counterpart/route.js +78 -0
  11. package/dist/counterpart/schemas.d.ts +4 -0
  12. package/dist/counterpart/schemas.js +1 -0
  13. package/dist/design-guidance.d.ts +26 -0
  14. package/dist/design-guidance.js +177 -0
  15. package/dist/fusion-mcp-bridge.d.ts +8 -4
  16. package/dist/fusion-mcp-bridge.js +36 -10
  17. package/dist/index.js +219 -54
  18. package/dist/printers/bambu.d.ts +38 -13
  19. package/dist/printers/bambu.js +204 -69
  20. package/dist/printers/camera-sources.d.ts +8 -0
  21. package/dist/printers/camera-sources.js +66 -0
  22. package/dist/printers/camera-stream.d.ts +65 -0
  23. package/dist/printers/camera-stream.js +227 -0
  24. package/dist/printers/camera-tools.d.ts +192 -0
  25. package/dist/printers/camera-tools.js +29 -0
  26. package/dist/printers/camera-wire.d.ts +7 -0
  27. package/dist/printers/camera-wire.js +40 -0
  28. package/dist/safety/print-file.d.ts +3 -0
  29. package/dist/safety/print-file.js +11 -2
  30. package/dist/safety/printer-state.d.ts +7 -0
  31. package/dist/safety/printer-state.js +11 -1
  32. package/dist/slicer/layer-pauses.d.ts +47 -0
  33. package/dist/slicer/layer-pauses.js +130 -0
  34. package/dist/stl/stl-manipulator.d.ts +40 -1
  35. package/dist/stl/stl-manipulator.js +253 -83
  36. package/package.json +2 -1
  37. package/src/ams-mapping.ts +52 -0
  38. package/src/bambu-network-bridge.ts +311 -8
  39. package/src/control-reply.ts +41 -0
  40. package/src/counterpart/info.ts +1 -0
  41. package/src/counterpart/route.ts +91 -0
  42. package/src/counterpart/schemas.ts +2 -0
  43. package/src/design-guidance.ts +188 -0
  44. package/src/fusion-mcp-bridge.ts +30 -10
  45. package/src/index.ts +213 -57
  46. package/src/printers/bambu.ts +194 -60
  47. package/src/printers/camera-sources.ts +53 -0
  48. package/src/printers/camera-stream.ts +165 -0
  49. package/src/printers/camera-tools.ts +29 -0
  50. package/src/printers/camera-wire.ts +39 -0
  51. package/src/safety/print-file.ts +12 -2
  52. package/src/safety/printer-state.ts +11 -1
  53. package/src/slicer/layer-pauses.ts +143 -0
  54. package/src/stl/stl-manipulator.ts +298 -93
@@ -1,3 +1,4 @@
1
+ import { CameraStreams, type FrameOptions } from "./camera-stream.js";
1
2
  import { inspectPrintFile, type PrintFileInspection } from "../safety/print-file.js";
2
3
  import { type PrinterStateRequirements } from "../safety/printer-state.js";
3
4
  export declare function assertDirectPrintSupported(model: string | undefined, serial?: string): void;
@@ -50,6 +51,13 @@ export type CheckedFile = {
50
51
  maxChamberTemperature: number;
51
52
  materials: string[];
52
53
  };
54
+ /**
55
+ * Where each printer's resume record is kept so a restart of this server (a deploy, a crash, a reboot) during a
56
+ * pause can still resume the job it started: BAMBU_RESUME_STATE_DIR, else bambu-printer-mcp/resume in the
57
+ * config home. Resume runs every check on a reloaded record: a fresh paused report naming this exact job, the
58
+ * re-read bytes or its unique name, and a person for an unverified file.
59
+ */
60
+ export declare function defaultResumeStateDir(env?: NodeJS.ProcessEnv): string;
53
61
  /** What a resume needs to know about a started file (filePath, the inspected snapshot): its bytes, printed plate, limits and used materials. */
54
62
  export declare function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile>;
55
63
  export type PrintPreflight = {
@@ -58,28 +66,28 @@ export type PrintPreflight = {
58
66
  model: string;
59
67
  notices: string[];
60
68
  };
61
- /**
62
- * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
63
- * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
64
- */
65
- export declare function cameraFrameParser(onFrame: (jpeg: Buffer) => void, onError: (error: Error) => void): (chunk: Buffer) => void;
69
+ export { cameraFrameParser } from "./camera-wire.js";
66
70
  export declare class BambuImplementation {
67
71
  private readonly confirm?;
68
72
  private printerStore;
73
+ readonly cameraStreams: CameraStreams;
69
74
  /**
70
75
  * The job each printer may resume, keyed host and serial. Cancel, a report
71
76
  * that it ended after it was seen running, or another job seen in its place
72
77
  * retires it, so a later job that reuses the name is never resumed.
73
78
  */
74
- private checkedJobs;
79
+ private readonly checkedJobs;
75
80
  /** In-flight counterpart_print_progress reads, one per printer. */
76
81
  private progressReads;
77
82
  private clearedErrors;
78
- constructor(confirm?: ((message: string) => Promise<boolean>) | undefined);
83
+ constructor(confirm?: ((message: string) => Promise<boolean>) | undefined, options?: {
84
+ resumeStateDir?: string;
85
+ });
79
86
  /**
80
- * Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
81
- * ordinary prompts; a physical check, or a prompt with requiredBecause (why
82
- * this one cannot be skipped), always asks.
87
+ * Ask a person through MCP elicitation, only for a physical check or a prompt with
88
+ * requiredBecause (why a person must accept it). Ordinary print, heating and resume
89
+ * starts do not ask: the client's own button is the yes, and the printer runs its
90
+ * own checks.
83
91
  */
84
92
  confirmHardwareAction(message: string, physicalCheck?: boolean, requiredBecause?: string): Promise<void>;
85
93
  private finishedJobIdentity;
@@ -132,8 +140,8 @@ export declare class BambuImplementation {
132
140
  /**
133
141
  * Resume reheats and moves the printer, so it is gated like a print start:
134
142
  * only the job this server inspected and started, while a fresh report shows
135
- * it paused, with its bytes re-read over FTPS and compared, and after human
136
- * confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
143
+ * it paused, with its bytes re-read over FTPS and compared. Only a file that
144
+ * could not be re-read asks a person. The record must still
137
145
  * be current at every check, including the native helper's last one.
138
146
  */
139
147
  resumeJob(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any>;
@@ -246,6 +254,24 @@ export declare class BambuImplementation {
246
254
  *
247
255
  * Read-only; no confirm gate. Default 8s timeout for cold-start latency.
248
256
  */
257
+ cameraStreamStart(host: string, serial: string, token: string, options?: {
258
+ bambuModel?: string;
259
+ fps?: number;
260
+ idleTimeoutMs?: number;
261
+ ffmpegPath?: string;
262
+ }): {
263
+ status: "started" | "running";
264
+ transport: import("./camera-stream.js").CameraTransport;
265
+ fps: number;
266
+ startedAt: string;
267
+ };
268
+ cameraStreamFrame(host: string, serial: string, options?: FrameOptions): Promise<import("./camera-stream.js").StreamFrameResult | {
269
+ status: string;
270
+ seq: number;
271
+ }>;
272
+ cameraStreamStop(host: string, serial: string): {
273
+ status: string;
274
+ };
249
275
  cameraSnapshot(host: string, _serial: string, token: string, options?: {
250
276
  savePath?: string;
251
277
  timeoutMs?: number;
@@ -336,4 +362,3 @@ export declare class BambuImplementation {
336
362
  private waitForTlsSession;
337
363
  disconnectAll(): Promise<void>;
338
364
  }
339
- export {};
@@ -1,7 +1,12 @@
1
+ import { CameraStreams } from "./camera-stream.js";
2
+ import { openTcpCameraSource, openRtspCameraSource } from "./camera-sources.js";
3
+ import { cameraNumber } from "./camera-tools.js";
4
+ import { cameraFrameParser, cameraAuth } from "./camera-wire.js";
1
5
  import { createHash } from "node:crypto";
6
+ import { controlReply, refusedControlMessage } from "../control-reply.js";
2
7
  import { isFinishedP1SJob, isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
3
8
  import fs from "node:fs/promises";
4
- import { createReadStream, readFileSync, existsSync } from "node:fs";
9
+ import { createReadStream, readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync } from "node:fs";
5
10
  import path from "node:path";
6
11
  import os from "node:os";
7
12
  import { Readable } from "node:stream";
@@ -15,7 +20,7 @@ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
15
20
  import { resolveStudioPrintOptions, usedNozzleCount } from "../studio-print-options.js";
16
21
  import { Client as FTPClient } from "basic-ftp";
17
22
  import * as mqtt from "mqtt";
18
- import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, UpdateStateCommand, } from "bambu-node";
23
+ import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, } from "bambu-node";
19
24
  /**
20
25
  * Post-Jan-2025 H2D firmware requires mTLS with a Bambu-issued client cert.
21
26
  * Loads cert+key once from:
@@ -62,12 +67,45 @@ function publishStudioJson(client, message, qos) {
62
67
  }
63
68
  /**
64
69
  * Bambu Studio's stop, MachineObject::command_task_abort (DeviceManager.cpp:1418-1426):
65
- * {"print":{"command":"stop","param":"","sequence_id":"<n>"}} at QoS 1. bambu-node's
66
- * UpdateStateCommand sends no param, at QoS 0.
70
+ * {"print":{"command":"stop","param":"","sequence_id":"<n>"}} at QoS 1 (bambu-node's
71
+ * UpdateStateCommand sends no param, at QoS 0). Pause and Resume go the same way (studioControl).
67
72
  */
68
73
  const studioStopCommand = {
69
74
  invoke: (client) => publishStudioJson(client, { print: { command: "stop", param: "", sequence_id: String(Date.now()) } }, 1),
70
75
  };
76
+ /**
77
+ * Pause, Resume or Stop exactly as Bambu Studio sends them (MachineObject::command_task_*), with this server's own
78
+ * 32-bit sequence id, so the printer's answer to this one control can be told apart from any other report.
79
+ */
80
+ function studioControl(command) {
81
+ const sequenceId = String(20000 + (Date.now() % 1000000));
82
+ return { command, sequenceId, invoke: (client) => publishStudioJson(client, { print: { command, param: "", sequence_id: sequenceId } }, 1) };
83
+ }
84
+ /** How long a control on the direct local network waits for the printer's answer (BAMBU_CONTROL_REPLY_MS, 0-30000). */
85
+ function controlReplyMs() {
86
+ const configured = Number(process.env.BAMBU_CONTROL_REPLY_MS);
87
+ return Number.isFinite(configured) && configured >= 0 ? Math.min(configured, 30000) : 5000;
88
+ }
89
+ /**
90
+ * The printer's answer to one control on its report topic (the client re-emits every message as rawMessage).
91
+ * Started before the publish so a fast answer is not missed; undefined when none arrives in time.
92
+ */
93
+ function watchControlReply(client, command, sequenceId, ms) {
94
+ const emitter = client;
95
+ if (ms <= 0 || typeof emitter?.on !== "function" || typeof emitter?.off !== "function")
96
+ return Promise.resolve(undefined);
97
+ return new Promise(resolve => {
98
+ let timer;
99
+ const onMessage = (_topic, payload) => {
100
+ const reply = controlReply(String(payload), command, sequenceId);
101
+ if (reply)
102
+ finish(reply);
103
+ };
104
+ const finish = (reply) => { clearTimeout(timer); emitter.off("rawMessage", onMessage); resolve(reply); };
105
+ timer = setTimeout(() => finish(undefined), ms);
106
+ emitter.on("rawMessage", onMessage);
107
+ });
108
+ }
71
109
  /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
72
110
  const STALE_REPORT_MS = 300000;
73
111
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
@@ -462,6 +500,89 @@ class BambuClientStore {
462
500
  function printJobIdentity(raw) {
463
501
  return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
464
502
  }
503
+ /**
504
+ * Where each printer's resume record is kept so a restart of this server (a deploy, a crash, a reboot) during a
505
+ * pause can still resume the job it started: BAMBU_RESUME_STATE_DIR, else bambu-printer-mcp/resume in the
506
+ * config home. Resume runs every check on a reloaded record: a fresh paused report naming this exact job, the
507
+ * re-read bytes or its unique name, and a person for an unverified file.
508
+ */
509
+ export function defaultResumeStateDir(env = process.env) {
510
+ if (env.BAMBU_RESUME_STATE_DIR)
511
+ return env.BAMBU_RESUME_STATE_DIR;
512
+ const configHome = env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), ".config");
513
+ return path.join(configHome, "bambu-printer-mcp", "resume");
514
+ }
515
+ function isCheckedJob(value) {
516
+ return Boolean(value) && typeof value === "object" && /^[a-f0-9]{64}$/.test(value.sha256 ?? "") &&
517
+ typeof value.remotePath === "string" && value.remotePath !== "" && typeof value.model === "string" &&
518
+ Boolean(value.requirements) && typeof value.requirements === "object" && Array.isArray(value.materials) &&
519
+ typeof value.seenRunning === "boolean" && typeof value.uploadedHere === "boolean" &&
520
+ [value.maxNozzleTemperature, value.maxBedTemperature, value.maxChamberTemperature].every(Number.isFinite);
521
+ }
522
+ /**
523
+ * The resume record of each printer (keyed host and serial). With a folder, every change is written to that
524
+ * printer's own file (private, replaced atomically) and the file is read the first time the printer is asked
525
+ * about, so a new server process knows the job the previous one started. Without one it lives in memory only.
526
+ */
527
+ class ResumeRecords {
528
+ constructor(dir) {
529
+ this.dir = dir;
530
+ this.jobs = new Map();
531
+ this.read = new Set();
532
+ }
533
+ get(key) {
534
+ if (!this.read.has(key)) {
535
+ this.read.add(key);
536
+ const saved = this.dir ? this.readFile(key) : undefined;
537
+ if (saved)
538
+ this.jobs.set(key, saved);
539
+ }
540
+ return this.jobs.get(key);
541
+ }
542
+ set(key, job) {
543
+ this.read.add(key);
544
+ this.jobs.set(key, job);
545
+ this.save(key);
546
+ }
547
+ delete(key) {
548
+ this.read.add(key);
549
+ const had = this.jobs.delete(key);
550
+ this.save(key);
551
+ return had;
552
+ }
553
+ /** Write this printer's record as it is now (or remove its file). A failed write never stops a print or a control. */
554
+ save(key) {
555
+ if (!this.dir)
556
+ return;
557
+ const file = this.file(key);
558
+ const job = this.jobs.get(key);
559
+ try {
560
+ if (!job) {
561
+ rmSync(file, { force: true });
562
+ return;
563
+ }
564
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });
565
+ const temporary = `${file}.${process.pid}.tmp`;
566
+ writeFileSync(temporary, JSON.stringify({ version: 1, key, job }), { mode: 0o600 });
567
+ renameSync(temporary, file);
568
+ }
569
+ catch (error) {
570
+ console.error(`Could not save the resume record for ${key.replace("\n", " ")}: ${error.message}. Resume still works until this server restarts.`);
571
+ }
572
+ }
573
+ file(key) {
574
+ return path.join(this.dir, `${createHash("sha256").update(key).digest("hex").slice(0, 32)}.json`);
575
+ }
576
+ readFile(key) {
577
+ try {
578
+ const saved = JSON.parse(readFileSync(this.file(key), "utf8"));
579
+ return saved?.version === 1 && saved.key === key && isCheckedJob(saved.job) ? saved.job : undefined;
580
+ }
581
+ catch {
582
+ return undefined;
583
+ }
584
+ }
585
+ }
465
586
  const ACTIVE_JOB_STATES = new Set(["PREPARE", "SLICING", "RUNNING", "PAUSE"]);
466
587
  /** Reports after which a started job can no longer be resumed. */
467
588
  const ENDED_JOB_STATES = new Set(["FINISH", "FAILED", "IDLE"]);
@@ -506,58 +627,25 @@ function reportedJobName(raw) {
506
627
  return subtask;
507
628
  return typeof raw.gcode_file === "string" ? path.posix.basename(raw.gcode_file.replace(/\\/g, "/").replace(/^\d+:/, "")) || undefined : undefined;
508
629
  }
509
- /**
510
- * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
511
- * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
512
- */
513
- export function cameraFrameParser(onFrame, onError) {
514
- let buffered = Buffer.alloc(0);
515
- let failed = false;
516
- return chunk => {
517
- if (failed)
518
- return;
519
- buffered = Buffer.concat([buffered, chunk]);
520
- while (buffered.length >= 16) {
521
- const payloadSize = buffered.readUInt32LE(0);
522
- if (payloadSize <= 0 || payloadSize > 5000000) {
523
- failed = true;
524
- onError(new Error(`camera_snapshot: unreasonable payload size ${payloadSize} from header; auth likely failed.`));
525
- return;
526
- }
527
- if (buffered.length < 16 + payloadSize)
528
- return;
529
- const jpeg = buffered.subarray(16, 16 + payloadSize);
530
- buffered = buffered.subarray(16 + payloadSize);
531
- if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
532
- failed = true;
533
- onError(new Error(`camera_snapshot: payload does not start with JPEG SOI (FF D8); got ${jpeg[0].toString(16)} ${jpeg[1].toString(16)}.`));
534
- return;
535
- }
536
- onFrame(Buffer.from(jpeg));
537
- }
538
- };
539
- }
630
+ export { cameraFrameParser } from "./camera-wire.js";
540
631
  export class BambuImplementation {
541
- constructor(confirm) {
632
+ constructor(confirm, options = {}) {
542
633
  this.confirm = confirm;
543
- /**
544
- * The job each printer may resume, keyed host and serial. Cancel, a report
545
- * that it ended after it was seen running, or another job seen in its place
546
- * retires it, so a later job that reuses the name is never resumed.
547
- */
548
- this.checkedJobs = new Map();
634
+ this.cameraStreams = new CameraStreams();
549
635
  /** In-flight counterpart_print_progress reads, one per printer. */
550
636
  this.progressReads = new Map();
551
637
  this.clearedErrors = new Map();
638
+ this.checkedJobs = new ResumeRecords(options.resumeStateDir);
552
639
  this.printerStore = new BambuClientStore((host, serial, report) => this.observeReport(host, serial, report));
553
640
  }
554
641
  /**
555
- * Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
556
- * ordinary prompts; a physical check, or a prompt with requiredBecause (why
557
- * this one cannot be skipped), always asks.
642
+ * Ask a person through MCP elicitation, only for a physical check or a prompt with
643
+ * requiredBecause (why a person must accept it). Ordinary print, heating and resume
644
+ * starts do not ask: the client's own button is the yes, and the printer runs its
645
+ * own checks.
558
646
  */
559
647
  async confirmHardwareAction(message, physicalCheck = false, requiredBecause) {
560
- if (!physicalCheck && requiredBecause === undefined && process.env.BAMBU_REQUIRE_CONFIRMATION === "0")
648
+ if (!physicalCheck && requiredBecause === undefined)
561
649
  return;
562
650
  if (!this.confirm) {
563
651
  throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent." + (requiredBecause ? ` ${requiredBecause}` : ""));
@@ -565,8 +653,7 @@ export class BambuImplementation {
565
653
  if (!(await this.confirm(message))) {
566
654
  throw new Error("Hardware safety confirmation was declined or cancelled in the MCP client. No command was sent. " + (physicalCheck
567
655
  ? "This confirmation covers a physical check at the printer and always needs a person to accept it."
568
- : requiredBecause ?? ("Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
569
- "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."));
570
657
  }
571
658
  }
572
659
  finishedJobIdentity(status) {
@@ -603,7 +690,7 @@ export class BambuImplementation {
603
690
  throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
604
691
  }
605
692
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
606
- // can appear after the human confirmed. Never pass a notice nobody was told about.
693
+ // can appear after the preflight. Never pass a notice the preflight did not name.
607
694
  const unnamed = hiddenHmsNotices(status?.raw, preflight.serial, preflight.model).filter(notice => !preflight.notices.includes(notice));
608
695
  if (unnamed.length) {
609
696
  throw new Error(`Printer reported ${unnamed.join(", ")} after the print confirmation. ` +
@@ -636,7 +723,10 @@ export class BambuImplementation {
636
723
  return;
637
724
  const state = raw.gcode_state.toUpperCase();
638
725
  if (ACTIVE_JOB_STATES.has(state) && reportsJob(raw, checked.remotePath)) {
639
- checked.seenRunning = true;
726
+ if (!checked.seenRunning) {
727
+ checked.seenRunning = true;
728
+ this.checkedJobs.save(key);
729
+ }
640
730
  return;
641
731
  }
642
732
  if (checked.seenRunning && (ENDED_JOB_STATES.has(state) || (ACTIVE_JOB_STATES.has(state) && reportedJobNames(raw).length > 0))) {
@@ -1130,8 +1220,10 @@ export class BambuImplementation {
1130
1220
  const ackMs = stopAckMs();
1131
1221
  const deadline = new AbortController();
1132
1222
  const timer = setTimeout(() => deadline.abort(Object.assign(new Error("stop not acknowledged"), { name: "TimeoutError" })), ackMs);
1223
+ const stop = studioControl("stop");
1224
+ const answered = watchControlReply(printer, stop.command, stop.sequenceId, controlReplyMs());
1133
1225
  try {
1134
- await this.invokeEmergencyCommand(printer, studioStopCommand, deadline.signal);
1226
+ await this.invokeEmergencyCommand(printer, stop, deadline.signal);
1135
1227
  }
1136
1228
  catch (error) {
1137
1229
  if (error?.name === "TimeoutError")
@@ -1142,7 +1234,13 @@ export class BambuImplementation {
1142
1234
  clearTimeout(timer);
1143
1235
  }
1144
1236
  this.checkedJobs.delete(`${host}\n${serial}`);
1145
- return { status: "success", message: "Stop sent and acknowledged by the printer (MQTT QoS 1), as Bambu Studio sends it. Check get_printer_status to confirm the job stopped." };
1237
+ // A printer that is not in LAN Only + Developer Mode answers an unsigned Stop with a refusal.
1238
+ const reply = await answered;
1239
+ if (reply && !reply.accepted)
1240
+ throw new Error(refusedControlMessage("stop", "the local network", reply.errCode, true));
1241
+ return { status: "success", confirmed: Boolean(reply), message: reply
1242
+ ? "The printer accepted Stop."
1243
+ : "Stop sent and acknowledged by the printer (MQTT QoS 1), as Bambu Studio sends it. Check get_printer_status to confirm the job stopped." };
1146
1244
  }
1147
1245
  catch (error) {
1148
1246
  throw new Error(`Failed to cancel print: ${error.message}`);
@@ -1197,9 +1295,13 @@ export class BambuImplementation {
1197
1295
  try {
1198
1296
  if (dispatch)
1199
1297
  return await dispatch();
1200
- else
1201
- await invokeWithoutAck(printer, new UpdateStateCommand({ state: "pause" }));
1202
- return { status: "success", message: "Pause command sent successfully." };
1298
+ const pause = studioControl("pause");
1299
+ const answered = watchControlReply(printer, pause.command, pause.sequenceId, controlReplyMs());
1300
+ await invokeWithoutAck(printer, pause);
1301
+ const reply = await answered;
1302
+ if (reply && !reply.accepted)
1303
+ throw new Error(refusedControlMessage("pause", "the local network", reply.errCode, true));
1304
+ return { status: "success", confirmed: Boolean(reply), message: reply ? "The printer accepted Pause." : "Pause command sent successfully." };
1203
1305
  }
1204
1306
  catch (error) {
1205
1307
  throw new Error(`Failed to pause print: ${error.message}`);
@@ -1208,8 +1310,8 @@ export class BambuImplementation {
1208
1310
  /**
1209
1311
  * Resume reheats and moves the printer, so it is gated like a print start:
1210
1312
  * only the job this server inspected and started, while a fresh report shows
1211
- * it paused, with its bytes re-read over FTPS and compared, and after human
1212
- * confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
1313
+ * it paused, with its bytes re-read over FTPS and compared. Only a file that
1314
+ * could not be re-read asks a person. The record must still
1213
1315
  * be current at every check, including the native helper's last one.
1214
1316
  */
1215
1317
  async resumeJob(host, serial, token, dispatch) {
@@ -1251,17 +1353,23 @@ export class BambuImplementation {
1251
1353
  `bed ${checked.maxBedTemperature}°C, chamber ${checked.maxChamberTemperature}°C) and moves. Materials: ${checked.materials.length ? checked.materials.join(", ") : "none declared"}. ` +
1252
1354
  `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)`}. ` +
1253
1355
  "Confirm the nozzle path is clear and the filament is still loaded.", false,
1254
- // The opt-out covers resumes whose bytes were checked; an unverified file always needs a person.
1255
- 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.");
1356
+ // A resume whose bytes were checked does not ask; an unverified file always needs a person.
1357
+ bytesVerified ? undefined : "The printer's copy of this file could not be re-read, so this resume always needs a person to accept it.");
1256
1358
  // The job may have been resumed, stopped or replaced at the printer while the prompt was open.
1257
1359
  await pausedJob();
1258
1360
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
1259
1361
  assertActive();
1260
- if (dispatch)
1362
+ if (dispatch) {
1261
1363
  await dispatch(assertActive, pausedJob);
1262
- else
1263
- await invokeWithoutAck(printer, new UpdateStateCommand({ state: "resume" }));
1264
- return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1364
+ return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1365
+ }
1366
+ const resume = studioControl("resume");
1367
+ const answered = watchControlReply(printer, resume.command, resume.sequenceId, controlReplyMs());
1368
+ await invokeWithoutAck(printer, resume);
1369
+ const reply = await answered;
1370
+ if (reply && !reply.accepted)
1371
+ throw new Error(refusedControlMessage("resume", "the local network", reply.errCode, true));
1372
+ return { status: "success", confirmed: Boolean(reply), message: reply ? `The printer accepted Resume for ${jobName}.` : `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1265
1373
  });
1266
1374
  }
1267
1375
  /**
@@ -1844,8 +1952,40 @@ export class BambuImplementation {
1844
1952
  *
1845
1953
  * Read-only; no confirm gate. Default 8s timeout for cold-start latency.
1846
1954
  */
1955
+ cameraStreamStart(host, serial, token, options = {}) {
1956
+ const fps = cameraNumber(options.fps, 1, 0.2, 2, "fps");
1957
+ const idleTimeoutMs = cameraNumber(options.idleTimeoutMs, 30000, 5000, 120000, "idle_timeout_ms", true);
1958
+ const model = normalizeModel(options.bambuModel) ?? "";
1959
+ const tcp = TCP_CAMERA_MODELS.has(model);
1960
+ if (!tcp && !RTSP_CAMERA_MODELS.has(model))
1961
+ throw new Error("camera_stream_start requires a supported bambu_model or BAMBU_MODEL");
1962
+ const { stream, status } = this.cameraStreams.start(JSON.stringify([host, serial]), { transport: tcp ? "tcp-6000" : "rtsps-322", fps, idleTimeoutMs,
1963
+ skipFirstFrame: tcp, open: handlers => tcp ? openTcpCameraSource(host, token, handlers) : openRtspCameraSource(host, token, fps, handlers, options.ffmpegPath) });
1964
+ return { status, transport: stream.transport, fps: stream.fps, startedAt: stream.startedAt };
1965
+ }
1966
+ async cameraStreamFrame(host, serial, options = {}) {
1967
+ const sinceSeq = cameraNumber(options.sinceSeq, 0, 0, Number.MAX_SAFE_INTEGER, "since_seq", true);
1968
+ const waitMs = cameraNumber(options.waitMs, 0, 0, 10000, "wait_ms", true);
1969
+ const minChange = cameraNumber(options.minChange, 0.02, 0, 1, "min_change");
1970
+ const maxWidth = options.maxWidth === undefined ? undefined : cameraNumber(options.maxWidth, 300, 1, 4096, "max_width", true);
1971
+ const maxBytes = options.maxBytes === undefined ? undefined : cameraNumber(options.maxBytes, 42000, 4096, 5000000, "max_bytes", true);
1972
+ if (options.changedOnly !== undefined && typeof options.changedOnly !== "boolean")
1973
+ throw new Error("changed_only must be a boolean");
1974
+ return this.cameraStreams.get(JSON.stringify([host, serial]))?.frame({ ...options, sinceSeq, waitMs, minChange, maxWidth, maxBytes }) ?? { status: "stopped", seq: 0 };
1975
+ }
1976
+ cameraStreamStop(host, serial) { this.cameraStreams.stop(JSON.stringify([host, serial])); return { status: "stopped" }; }
1847
1977
  async cameraSnapshot(host, _serial, token, options = {}) {
1848
1978
  const timeoutMs = options.timeoutMs ?? 8000;
1979
+ const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
1980
+ if (stream && !stream.stopped) {
1981
+ const jpeg = await stream.latest(Math.min(timeoutMs, 10000));
1982
+ if (!jpeg)
1983
+ throw new Error("The active camera stream has not produced a live frame");
1984
+ if (options.savePath)
1985
+ await (await import("node:fs/promises")).writeFile(options.savePath, jpeg);
1986
+ return { status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport,
1987
+ ...(options.savePath ? { savedTo: options.savePath } : {}) };
1988
+ }
1849
1989
  const model = (options.bambuModel ?? "").toLowerCase();
1850
1990
  const RTSP_MODELS = RTSP_CAMERA_MODELS;
1851
1991
  if (!model) {
@@ -1984,12 +2124,7 @@ export class BambuImplementation {
1984
2124
  */
1985
2125
  async fetchTcpCameraFrame(host, token, timeoutMs, port = 6000) {
1986
2126
  const tls = await import("node:tls");
1987
- const auth = Buffer.alloc(80, 0);
1988
- auth.writeUInt32LE(0x40, 0); // payload size
1989
- auth.writeUInt32LE(0x3000, 4); // type
1990
- // flags=0, reserved=0 are already zero from Buffer.alloc.
1991
- auth.write("bblp", 16, 4, "ascii");
1992
- auth.write(token, 48, Math.min(32, Buffer.byteLength(token, "ascii")), "ascii");
2127
+ const auth = cameraAuth(token);
1993
2128
  return new Promise((resolve, reject) => {
1994
2129
  let settled = false;
1995
2130
  let frames = 0;
@@ -0,0 +1,8 @@
1
+ import type { OpenCameraSource } from "./camera-stream.js";
2
+ type Handlers = Parameters<OpenCameraSource>[0];
3
+ /** Reuses the snapshot protocol/parser; the socket lives until its stream closes it. */
4
+ export declare function openTcpCameraSource(host: string, token: string, handlers: Handlers, port?: number): ReturnType<OpenCameraSource>;
5
+ /** ffmpeg's MJPEG output has no per-frame process or temporary file. */
6
+ export declare function mjpegParser(onFrame: (bytes: Buffer) => void, onError: (error: Error) => void): (chunk: Buffer) => void;
7
+ export declare function openRtspCameraSource(host: string, token: string, fps: number, handlers: Handlers, ffmpegPath?: string): ReturnType<OpenCameraSource>;
8
+ export {};
@@ -0,0 +1,66 @@
1
+ import tls from "node:tls";
2
+ import { spawn } from "node:child_process";
3
+ import { cameraAuth, cameraFrameParser } from "./camera-wire.js";
4
+ /** Reuses the snapshot protocol/parser; the socket lives until its stream closes it. */
5
+ export function openTcpCameraSource(host, token, handlers, port = 6000) {
6
+ let closed = false;
7
+ const socket = tls.connect({ host, port, rejectUnauthorized: false }, () => socket.write(cameraAuth(token)));
8
+ const fail = (error) => { if (!closed)
9
+ handlers.onError(error); };
10
+ socket.setTimeout(15000, () => fail(new Error("Camera stream timed out")));
11
+ socket.on("data", cameraFrameParser(bytes => { if (!closed)
12
+ handlers.onFrame(bytes); }, fail));
13
+ socket.on("error", fail);
14
+ socket.on("close", () => { if (!closed)
15
+ handlers.onEnd(); });
16
+ return { close() { closed = true; socket.destroy(); } };
17
+ }
18
+ /** ffmpeg's MJPEG output has no per-frame process or temporary file. */
19
+ export function mjpegParser(onFrame, onError) {
20
+ let buffer = Buffer.alloc(0), failed = false;
21
+ return chunk => {
22
+ if (failed)
23
+ return;
24
+ buffer = Buffer.concat([buffer, chunk]);
25
+ for (;;) {
26
+ const start = buffer.indexOf(Buffer.from([0xff, 0xd8]));
27
+ if (start < 0) {
28
+ buffer = buffer.subarray(Math.max(0, buffer.length - 1));
29
+ return;
30
+ }
31
+ if (start)
32
+ buffer = buffer.subarray(start);
33
+ const end = buffer.indexOf(Buffer.from([0xff, 0xd9]), 2);
34
+ if (end >= 0) {
35
+ onFrame(Buffer.from(buffer.subarray(0, end + 2)));
36
+ buffer = buffer.subarray(end + 2);
37
+ continue;
38
+ }
39
+ if (buffer.length > 5000000) {
40
+ failed = true;
41
+ onError(new Error("Camera JPEG too large"));
42
+ }
43
+ return;
44
+ }
45
+ };
46
+ }
47
+ export function openRtspCameraSource(host, token, fps, handlers, ffmpegPath = "ffmpeg") {
48
+ const url = `rtsps://bblp:${encodeURIComponent(token)}@${host}:322/streaming/live/1`;
49
+ const child = spawn(ffmpegPath, ["-tls_verify", "0", "-rtsp_transport", "tcp", "-i", url,
50
+ "-an", "-vf", `fps=${fps}`, "-c:v", "mjpeg", "-q:v", "5", "-f", "image2pipe", "-loglevel", "error", "pipe:1"], { stdio: ["ignore", "pipe", "pipe"] });
51
+ let closed = false, denied = false;
52
+ let timer;
53
+ const fail = (error) => { if (!closed)
54
+ handlers.onError(error); };
55
+ const arm = () => { clearTimeout(timer); timer = setTimeout(() => fail(new Error("RTSP camera stream timed out")), 15000); timer.unref(); };
56
+ arm();
57
+ child.stdout.on("data", mjpegParser(bytes => { arm(); if (!closed)
58
+ handlers.onFrame(bytes); }, fail));
59
+ // Drain stderr but never expose the credential-bearing URL in ffmpeg diagnostics.
60
+ child.stderr.on("data", bytes => { if (/401|403|Unauthorized|Forbidden/i.test(String(bytes)))
61
+ denied = true; });
62
+ child.once("error", () => fail(new Error("RTSP camera process could not start")));
63
+ child.once("exit", () => { clearTimeout(timer); if (!closed)
64
+ denied ? fail(new Error("RTSP camera authentication failed")) : handlers.onEnd(); });
65
+ return { close() { closed = true; clearTimeout(timer); child.kill("SIGKILL"); } };
66
+ }
@@ -0,0 +1,65 @@
1
+ export type CameraTransport = "tcp-6000" | "rtsps-322";
2
+ export type CameraSource = {
3
+ close(): void;
4
+ };
5
+ export type OpenCameraSource = (handlers: {
6
+ onFrame(bytes: Buffer): void;
7
+ onError(error: Error): void;
8
+ onEnd(): void;
9
+ }) => CameraSource;
10
+ export type FrameOptions = {
11
+ sinceSeq?: number;
12
+ waitMs?: number;
13
+ maxWidth?: number;
14
+ maxBytes?: number;
15
+ changedOnly?: boolean;
16
+ minChange?: number;
17
+ signal?: AbortSignal;
18
+ };
19
+ export type StreamFrameResult = {
20
+ status: "frame" | "unchanged" | "stopped" | "unavailable";
21
+ seq: number;
22
+ capturedAt?: string;
23
+ width?: number;
24
+ height?: number;
25
+ format?: "image/jpeg";
26
+ base64?: string;
27
+ change?: number;
28
+ reason?: "auth" | "unreachable" | "no-camera";
29
+ };
30
+ export type StreamOptions = {
31
+ transport: CameraTransport;
32
+ fps: number;
33
+ idleTimeoutMs: number;
34
+ open: OpenCameraSource;
35
+ skipFirstFrame: boolean;
36
+ };
37
+ export declare function thumbnailChange(a: Uint8Array, b: Uint8Array): number;
38
+ export declare class CameraStream {
39
+ #private;
40
+ private options;
41
+ private nextSeq;
42
+ private now;
43
+ readonly startedAt: string;
44
+ readonly transport: CameraTransport;
45
+ readonly fps: number;
46
+ constructor(options: StreamOptions, nextSeq: () => number, now?: () => number);
47
+ get stopped(): boolean;
48
+ start(): void;
49
+ touch(idleTimeoutMs?: number): void;
50
+ stop(): void;
51
+ frame(options?: FrameOptions): Promise<StreamFrameResult>;
52
+ latest(waitMs: number): Promise<Buffer | undefined>;
53
+ }
54
+ export declare class CameraStreams {
55
+ #private;
56
+ private now;
57
+ constructor(now?: () => number);
58
+ get(key: string): CameraStream | undefined;
59
+ start(key: string, options: StreamOptions): {
60
+ stream: CameraStream;
61
+ status: "started" | "running";
62
+ };
63
+ stop(key: string): void;
64
+ stopAll(): void;
65
+ }