bambu-printer-mcp 1.1.51 → 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 +202 -45
  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 +3 -0
  35. package/dist/stl/stl-manipulator.js +50 -4
  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 +195 -49
  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 +58 -5
@@ -1,7 +1,12 @@
1
+ import {CameraStreams, type FrameOptions} 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, type ControlReply } 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";
@@ -22,7 +27,6 @@ import {
22
27
  PushAllCommand,
23
28
  UpdateFanCommand,
24
29
  UpdateLightCommand,
25
- UpdateStateCommand,
26
30
  } from "bambu-node";
27
31
 
28
32
  /**
@@ -70,12 +74,46 @@ function publishStudioJson(client: BambuClient, message: Record<string, any>, qo
70
74
 
71
75
  /**
72
76
  * Bambu Studio's stop, MachineObject::command_task_abort (DeviceManager.cpp:1418-1426):
73
- * {"print":{"command":"stop","param":"","sequence_id":"<n>"}} at QoS 1. bambu-node's
74
- * UpdateStateCommand sends no param, at QoS 0.
77
+ * {"print":{"command":"stop","param":"","sequence_id":"<n>"}} at QoS 1 (bambu-node's
78
+ * UpdateStateCommand sends no param, at QoS 0). Pause and Resume go the same way (studioControl).
75
79
  */
76
80
  const studioStopCommand = {
77
81
  invoke: (client: BambuClient) => publishStudioJson(client, { print: { command: "stop", param: "", sequence_id: String(Date.now()) } }, 1),
78
82
  };
83
+ /**
84
+ * Pause, Resume or Stop exactly as Bambu Studio sends them (MachineObject::command_task_*), with this server's own
85
+ * 32-bit sequence id, so the printer's answer to this one control can be told apart from any other report.
86
+ */
87
+ function studioControl(command: "stop" | "pause" | "resume") {
88
+ const sequenceId = String(20_000 + (Date.now() % 1_000_000));
89
+ return { command, sequenceId, invoke: (client: BambuClient) => publishStudioJson(client, { print: { command, param: "", sequence_id: sequenceId } }, 1) };
90
+ }
91
+
92
+ /** How long a control on the direct local network waits for the printer's answer (BAMBU_CONTROL_REPLY_MS, 0-30000). */
93
+ function controlReplyMs(): number {
94
+ const configured = Number(process.env.BAMBU_CONTROL_REPLY_MS);
95
+ return Number.isFinite(configured) && configured >= 0 ? Math.min(configured, 30_000) : 5_000;
96
+ }
97
+
98
+ /**
99
+ * The printer's answer to one control on its report topic (the client re-emits every message as rawMessage).
100
+ * Started before the publish so a fast answer is not missed; undefined when none arrives in time.
101
+ */
102
+ function watchControlReply(client: BambuClient, command: string, sequenceId: string, ms: number): Promise<ControlReply | undefined> {
103
+ const emitter = client as any;
104
+ if (ms <= 0 || typeof emitter?.on !== "function" || typeof emitter?.off !== "function") return Promise.resolve(undefined);
105
+ return new Promise(resolve => {
106
+ let timer: ReturnType<typeof setTimeout> | undefined;
107
+ const onMessage = (_topic: string, payload: Buffer | string) => {
108
+ const reply = controlReply(String(payload), command, sequenceId);
109
+ if (reply) finish(reply);
110
+ };
111
+ const finish = (reply: ControlReply | undefined) => { clearTimeout(timer); emitter.off("rawMessage", onMessage); resolve(reply); };
112
+ timer = setTimeout(() => finish(undefined), ms);
113
+ emitter.on("rawMessage", onMessage);
114
+ });
115
+ }
116
+
79
117
  /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
80
118
  const STALE_REPORT_MS = 300_000;
81
119
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
@@ -579,6 +617,86 @@ type CheckedJob = CheckedFile & {
579
617
  uploadedHere: boolean;
580
618
  };
581
619
 
620
+ /**
621
+ * Where each printer's resume record is kept so a restart of this server (a deploy, a crash, a reboot) during a
622
+ * pause can still resume the job it started: BAMBU_RESUME_STATE_DIR, else bambu-printer-mcp/resume in the
623
+ * config home. Resume runs every check on a reloaded record: a fresh paused report naming this exact job, the
624
+ * re-read bytes or its unique name, and a person for an unverified file.
625
+ */
626
+ export function defaultResumeStateDir(env: NodeJS.ProcessEnv = process.env): string {
627
+ if (env.BAMBU_RESUME_STATE_DIR) return env.BAMBU_RESUME_STATE_DIR;
628
+ const configHome = env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), ".config");
629
+ return path.join(configHome, "bambu-printer-mcp", "resume");
630
+ }
631
+
632
+ function isCheckedJob(value: any): value is CheckedJob {
633
+ return Boolean(value) && typeof value === "object" && /^[a-f0-9]{64}$/.test(value.sha256 ?? "") &&
634
+ typeof value.remotePath === "string" && value.remotePath !== "" && typeof value.model === "string" &&
635
+ Boolean(value.requirements) && typeof value.requirements === "object" && Array.isArray(value.materials) &&
636
+ typeof value.seenRunning === "boolean" && typeof value.uploadedHere === "boolean" &&
637
+ [value.maxNozzleTemperature, value.maxBedTemperature, value.maxChamberTemperature].every(Number.isFinite);
638
+ }
639
+
640
+ /**
641
+ * The resume record of each printer (keyed host and serial). With a folder, every change is written to that
642
+ * printer's own file (private, replaced atomically) and the file is read the first time the printer is asked
643
+ * about, so a new server process knows the job the previous one started. Without one it lives in memory only.
644
+ */
645
+ class ResumeRecords {
646
+ private readonly jobs = new Map<string, CheckedJob>();
647
+ private readonly read = new Set<string>();
648
+ constructor(private readonly dir?: string) {}
649
+
650
+ get(key: string): CheckedJob | undefined {
651
+ if (!this.read.has(key)) {
652
+ this.read.add(key);
653
+ const saved = this.dir ? this.readFile(key) : undefined;
654
+ if (saved) this.jobs.set(key, saved);
655
+ }
656
+ return this.jobs.get(key);
657
+ }
658
+
659
+ set(key: string, job: CheckedJob): void {
660
+ this.read.add(key);
661
+ this.jobs.set(key, job);
662
+ this.save(key);
663
+ }
664
+
665
+ delete(key: string): boolean {
666
+ this.read.add(key);
667
+ const had = this.jobs.delete(key);
668
+ this.save(key);
669
+ return had;
670
+ }
671
+
672
+ /** Write this printer's record as it is now (or remove its file). A failed write never stops a print or a control. */
673
+ save(key: string): void {
674
+ if (!this.dir) return;
675
+ const file = this.file(key);
676
+ const job = this.jobs.get(key);
677
+ try {
678
+ if (!job) { rmSync(file, { force: true }); return; }
679
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });
680
+ const temporary = `${file}.${process.pid}.tmp`;
681
+ writeFileSync(temporary, JSON.stringify({ version: 1, key, job }), { mode: 0o600 });
682
+ renameSync(temporary, file);
683
+ } catch (error) {
684
+ console.error(`Could not save the resume record for ${key.replace("\n", " ")}: ${(error as Error).message}. Resume still works until this server restarts.`);
685
+ }
686
+ }
687
+
688
+ private file(key: string): string {
689
+ return path.join(this.dir!, `${createHash("sha256").update(key).digest("hex").slice(0, 32)}.json`);
690
+ }
691
+
692
+ private readFile(key: string): CheckedJob | undefined {
693
+ try {
694
+ const saved = JSON.parse(readFileSync(this.file(key), "utf8"));
695
+ return saved?.version === 1 && saved.key === key && isCheckedJob(saved.job) ? saved.job : undefined;
696
+ } catch { return undefined; }
697
+ }
698
+ }
699
+
582
700
  const ACTIVE_JOB_STATES = new Set(["PREPARE", "SLICING", "RUNNING", "PAUSE"]);
583
701
  /** Reports after which a started job can no longer be resumed. */
584
702
  const ENDED_JOB_STATES = new Set(["FINISH", "FAILED", "IDLE"]);
@@ -629,67 +747,41 @@ function reportedJobName(raw: Record<string, any>): string | undefined {
629
747
 
630
748
  export type PrintPreflight = { finishedJob?: string; serial: string; model: string; notices: string[] };
631
749
 
632
- /**
633
- * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
634
- * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
635
- */
636
- export function cameraFrameParser(onFrame: (jpeg: Buffer) => void, onError: (error: Error) => void): (chunk: Buffer) => void {
637
- let buffered = Buffer.alloc(0);
638
- let failed = false;
639
- return chunk => {
640
- if (failed) return;
641
- buffered = Buffer.concat([buffered, chunk]);
642
- while (buffered.length >= 16) {
643
- const payloadSize = buffered.readUInt32LE(0);
644
- if (payloadSize <= 0 || payloadSize > 5_000_000) {
645
- failed = true;
646
- onError(new Error(`camera_snapshot: unreasonable payload size ${payloadSize} from header; auth likely failed.`));
647
- return;
648
- }
649
- if (buffered.length < 16 + payloadSize) return;
650
- const jpeg = buffered.subarray(16, 16 + payloadSize);
651
- buffered = buffered.subarray(16 + payloadSize);
652
- if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
653
- failed = true;
654
- onError(new Error(`camera_snapshot: payload does not start with JPEG SOI (FF D8); got ${jpeg[0].toString(16)} ${jpeg[1].toString(16)}.`));
655
- return;
656
- }
657
- onFrame(Buffer.from(jpeg));
658
- }
659
- };
660
- }
750
+ export {cameraFrameParser} from "./camera-wire.js";
661
751
 
662
752
  export class BambuImplementation {
663
753
  private printerStore: BambuClientStore;
754
+ readonly cameraStreams = new CameraStreams();
664
755
  /**
665
756
  * The job each printer may resume, keyed host and serial. Cancel, a report
666
757
  * that it ended after it was seen running, or another job seen in its place
667
758
  * retires it, so a later job that reuses the name is never resumed.
668
759
  */
669
- private checkedJobs = new Map<string, CheckedJob>();
760
+ private readonly checkedJobs: ResumeRecords;
670
761
  /** In-flight counterpart_print_progress reads, one per printer. */
671
762
  private progressReads = new Map<string, Promise<ProgressReport | null>>();
672
763
  private clearedErrors = new Map<string, string[]>();
673
764
 
674
- constructor(private readonly confirm?: (message: string) => Promise<boolean>) {
765
+ constructor(private readonly confirm?: (message: string) => Promise<boolean>, options: { resumeStateDir?: string } = {}) {
766
+ this.checkedJobs = new ResumeRecords(options.resumeStateDir);
675
767
  this.printerStore = new BambuClientStore((host, serial, report) => this.observeReport(host, serial, report));
676
768
  }
677
769
 
678
770
  /**
679
- * Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
680
- * ordinary prompts; a physical check, or a prompt with requiredBecause (why
681
- * this one cannot be skipped), always asks.
771
+ * Ask a person through MCP elicitation, only for a physical check or a prompt with
772
+ * requiredBecause (why a person must accept it). Ordinary print, heating and resume
773
+ * starts do not ask: the client's own button is the yes, and the printer runs its
774
+ * own checks.
682
775
  */
683
776
  async confirmHardwareAction(message: string, physicalCheck = false, requiredBecause?: string): Promise<void> {
684
- if (!physicalCheck && requiredBecause === undefined && process.env.BAMBU_REQUIRE_CONFIRMATION === "0") return;
777
+ if (!physicalCheck && requiredBecause === undefined) return;
685
778
  if (!this.confirm) {
686
779
  throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent." + (requiredBecause ? ` ${requiredBecause}` : ""));
687
780
  }
688
781
  if (!(await this.confirm(message))) {
689
782
  throw new Error("Hardware safety confirmation was declined or cancelled in the MCP client. No command was sent. " + (physicalCheck
690
783
  ? "This confirmation covers a physical check at the printer and always needs a person to accept it."
691
- : requiredBecause ?? ("Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
692
- "A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts.")));
784
+ : requiredBecause ?? "Some clients decline prompts automatically, for example in a non-interactive permission mode."));
693
785
  }
694
786
  }
695
787
 
@@ -732,7 +824,7 @@ export class BambuImplementation {
732
824
  throw new Error("Printer job changed during preflight. Review the current printer status and retry.");
733
825
  }
734
826
  // An X2D raises its hidden camera notice about 15 seconds after boot, so it
735
- // can appear after the human confirmed. Never pass a notice nobody was told about.
827
+ // can appear after the preflight. Never pass a notice the preflight did not name.
736
828
  const unnamed = hiddenHmsNotices(status?.raw, preflight.serial, preflight.model).filter(notice => !preflight.notices.includes(notice));
737
829
  if (unnamed.length) {
738
830
  throw new Error(`Printer reported ${unnamed.join(", ")} after the print confirmation. ` +
@@ -766,7 +858,7 @@ export class BambuImplementation {
766
858
  if (!checked || !raw || typeof raw.gcode_state !== "string") return;
767
859
  const state = raw.gcode_state.toUpperCase();
768
860
  if (ACTIVE_JOB_STATES.has(state) && reportsJob(raw, checked.remotePath)) {
769
- checked.seenRunning = true;
861
+ if (!checked.seenRunning) { checked.seenRunning = true; this.checkedJobs.save(key); }
770
862
  return;
771
863
  }
772
864
  if (checked.seenRunning && (ENDED_JOB_STATES.has(state) || (ACTIVE_JOB_STATES.has(state) && reportedJobNames(raw).length > 0))) {
@@ -1285,13 +1377,20 @@ export class BambuImplementation {
1285
1377
  const ackMs = stopAckMs();
1286
1378
  const deadline = new AbortController();
1287
1379
  const timer = setTimeout(() => deadline.abort(Object.assign(new Error("stop not acknowledged"), { name: "TimeoutError" })), ackMs);
1288
- try { await this.invokeEmergencyCommand(printer!, studioStopCommand, deadline.signal); }
1380
+ const stop = studioControl("stop");
1381
+ const answered = watchControlReply(printer!, stop.command, stop.sequenceId, controlReplyMs());
1382
+ try { await this.invokeEmergencyCommand(printer!, stop, deadline.signal); }
1289
1383
  catch (error) {
1290
1384
  if ((error as Error)?.name === "TimeoutError") throw new Error(`The printer did not acknowledge the stop within ${ackMs / 1000} s; its MQTT client was closed so the stop cannot be sent late. Check the printer.`);
1291
1385
  throw error;
1292
1386
  } finally { clearTimeout(timer); }
1293
1387
  this.checkedJobs.delete(`${host}\n${serial}`);
1294
- 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." };
1388
+ // A printer that is not in LAN Only + Developer Mode answers an unsigned Stop with a refusal.
1389
+ const reply = await answered;
1390
+ if (reply && !reply.accepted) throw new Error(refusedControlMessage("stop", "the local network", reply.errCode, true));
1391
+ return { status: "success", confirmed: Boolean(reply), message: reply
1392
+ ? "The printer accepted Stop."
1393
+ : "Stop sent and acknowledged by the printer (MQTT QoS 1), as Bambu Studio sends it. Check get_printer_status to confirm the job stopped." };
1295
1394
  } catch (error) {
1296
1395
  throw new Error(`Failed to cancel print: ${(error as Error).message}`);
1297
1396
  }
@@ -1348,8 +1447,12 @@ export class BambuImplementation {
1348
1447
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
1349
1448
  try {
1350
1449
  if (dispatch) return await dispatch();
1351
- else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "pause" }));
1352
- return { status: "success", message: "Pause command sent successfully." };
1450
+ const pause = studioControl("pause");
1451
+ const answered = watchControlReply(printer!, pause.command, pause.sequenceId, controlReplyMs());
1452
+ await invokeWithoutAck(printer!, pause);
1453
+ const reply = await answered;
1454
+ if (reply && !reply.accepted) throw new Error(refusedControlMessage("pause", "the local network", reply.errCode, true));
1455
+ return { status: "success", confirmed: Boolean(reply), message: reply ? "The printer accepted Pause." : "Pause command sent successfully." };
1353
1456
  } catch (error) {
1354
1457
  throw new Error(`Failed to pause print: ${(error as Error).message}`);
1355
1458
  }
@@ -1358,8 +1461,8 @@ export class BambuImplementation {
1358
1461
  /**
1359
1462
  * Resume reheats and moves the printer, so it is gated like a print start:
1360
1463
  * only the job this server inspected and started, while a fresh report shows
1361
- * it paused, with its bytes re-read over FTPS and compared, and after human
1362
- * confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
1464
+ * it paused, with its bytes re-read over FTPS and compared. Only a file that
1465
+ * could not be re-read asks a person. The record must still
1363
1466
  * be current at every check, including the native helper's last one.
1364
1467
  */
1365
1468
  async resumeJob(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any> {
@@ -1399,16 +1502,23 @@ export class BambuImplementation {
1399
1502
  `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)`}. ` +
1400
1503
  "Confirm the nozzle path is clear and the filament is still loaded.",
1401
1504
  false,
1402
- // The opt-out covers resumes whose bytes were checked; an unverified file always needs a person.
1403
- 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."
1505
+ // A resume whose bytes were checked does not ask; an unverified file always needs a person.
1506
+ bytesVerified ? undefined : "The printer's copy of this file could not be re-read, so this resume always needs a person to accept it."
1404
1507
  );
1405
1508
  // The job may have been resumed, stopped or replaced at the printer while the prompt was open.
1406
1509
  await pausedJob();
1407
1510
  const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
1408
1511
  assertActive();
1409
- if (dispatch) await dispatch(assertActive, pausedJob);
1410
- else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "resume" }));
1411
- return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1512
+ if (dispatch) {
1513
+ await dispatch(assertActive, pausedJob);
1514
+ return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1515
+ }
1516
+ const resume = studioControl("resume");
1517
+ const answered = watchControlReply(printer!, resume.command, resume.sequenceId, controlReplyMs());
1518
+ await invokeWithoutAck(printer!, resume);
1519
+ const reply = await answered;
1520
+ if (reply && !reply.accepted) throw new Error(refusedControlMessage("resume", "the local network", reply.errCode, true));
1521
+ return { status: "success", confirmed: Boolean(reply), message: reply ? `The printer accepted Resume for ${jobName}.` : `Resume command sent for ${jobName}.`, jobName, bytesVerified };
1412
1522
  });
1413
1523
  }
1414
1524
 
@@ -2024,6 +2134,27 @@ export class BambuImplementation {
2024
2134
  *
2025
2135
  * Read-only; no confirm gate. Default 8s timeout for cold-start latency.
2026
2136
  */
2137
+ cameraStreamStart(host: string, serial: string, token: string, options: {bambuModel?: string; fps?: number; idleTimeoutMs?: number; ffmpegPath?: string} = {}) {
2138
+ const fps = cameraNumber(options.fps, 1, 0.2, 2, "fps");
2139
+ const idleTimeoutMs = cameraNumber(options.idleTimeoutMs, 30000, 5000, 120000, "idle_timeout_ms", true);
2140
+ const model = normalizeModel(options.bambuModel) ?? "";
2141
+ const tcp = TCP_CAMERA_MODELS.has(model);
2142
+ if (!tcp && !RTSP_CAMERA_MODELS.has(model)) throw new Error("camera_stream_start requires a supported bambu_model or BAMBU_MODEL");
2143
+ const {stream, status} = this.cameraStreams.start(JSON.stringify([host, serial]), {transport: tcp ? "tcp-6000" : "rtsps-322", fps, idleTimeoutMs,
2144
+ skipFirstFrame: tcp, open: handlers => tcp ? openTcpCameraSource(host, token, handlers) : openRtspCameraSource(host, token, fps, handlers, options.ffmpegPath)});
2145
+ return {status, transport: stream.transport, fps: stream.fps, startedAt: stream.startedAt};
2146
+ }
2147
+ async cameraStreamFrame(host: string, serial: string, options: FrameOptions = {}) {
2148
+ const sinceSeq = cameraNumber(options.sinceSeq, 0, 0, Number.MAX_SAFE_INTEGER, "since_seq", true);
2149
+ const waitMs = cameraNumber(options.waitMs, 0, 0, 10000, "wait_ms", true);
2150
+ const minChange = cameraNumber(options.minChange, 0.02, 0, 1, "min_change");
2151
+ const maxWidth = options.maxWidth === undefined ? undefined : cameraNumber(options.maxWidth, 300, 1, 4096, "max_width", true);
2152
+ const maxBytes = options.maxBytes === undefined ? undefined : cameraNumber(options.maxBytes, 42000, 4096, 5000000, "max_bytes", true);
2153
+ if (options.changedOnly !== undefined && typeof options.changedOnly !== "boolean") throw new Error("changed_only must be a boolean");
2154
+ return this.cameraStreams.get(JSON.stringify([host, serial]))?.frame({...options, sinceSeq, waitMs, minChange, maxWidth, maxBytes}) ?? {status: "stopped", seq: 0};
2155
+ }
2156
+ cameraStreamStop(host: string, serial: string) { this.cameraStreams.stop(JSON.stringify([host, serial])); return {status: "stopped"}; }
2157
+
2027
2158
  async cameraSnapshot(
2028
2159
  host: string,
2029
2160
  _serial: string,
@@ -2058,6 +2189,14 @@ export class BambuImplementation {
2058
2189
  transport?: "tcp-6000" | "rtsps-322";
2059
2190
  }> {
2060
2191
  const timeoutMs = options.timeoutMs ?? 8_000;
2192
+ const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
2193
+ if (stream && !stream.stopped) {
2194
+ const jpeg = await stream.latest(Math.min(timeoutMs, 10_000));
2195
+ if (!jpeg) throw new Error("The active camera stream has not produced a live frame");
2196
+ if (options.savePath) await (await import("node:fs/promises")).writeFile(options.savePath, jpeg);
2197
+ return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport,
2198
+ ...(options.savePath ? {savedTo: options.savePath} : {})};
2199
+ }
2061
2200
  const model = (options.bambuModel ?? "").toLowerCase();
2062
2201
  const RTSP_MODELS = RTSP_CAMERA_MODELS;
2063
2202
 
@@ -2219,12 +2358,7 @@ export class BambuImplementation {
2219
2358
  ): Promise<Buffer> {
2220
2359
  const tls = await import("node:tls");
2221
2360
 
2222
- const auth = Buffer.alloc(80, 0);
2223
- auth.writeUInt32LE(0x40, 0); // payload size
2224
- auth.writeUInt32LE(0x3000, 4); // type
2225
- // flags=0, reserved=0 are already zero from Buffer.alloc.
2226
- auth.write("bblp", 16, 4, "ascii");
2227
- auth.write(token, 48, Math.min(32, Buffer.byteLength(token, "ascii")), "ascii");
2361
+ const auth = cameraAuth(token);
2228
2362
 
2229
2363
  return new Promise((resolve, reject) => {
2230
2364
  let settled = false;
@@ -0,0 +1,53 @@
1
+ import tls from "node:tls";
2
+ import {spawn} from "node:child_process";
3
+ import {cameraAuth, cameraFrameParser} from "./camera-wire.js";
4
+ import type {OpenCameraSource} from "./camera-stream.js";
5
+
6
+ type Handlers = Parameters<OpenCameraSource>[0];
7
+
8
+ /** Reuses the snapshot protocol/parser; the socket lives until its stream closes it. */
9
+ export function openTcpCameraSource(host: string, token: string, handlers: Handlers, port = 6000): ReturnType<OpenCameraSource> {
10
+ let closed = false;
11
+ const socket = tls.connect({host, port, rejectUnauthorized: false}, () => socket.write(cameraAuth(token)));
12
+ const fail = (error: Error) => { if (!closed) handlers.onError(error); };
13
+ socket.setTimeout(15_000, () => fail(new Error("Camera stream timed out")));
14
+ socket.on("data", cameraFrameParser(bytes => { if (!closed) handlers.onFrame(bytes); }, fail));
15
+ socket.on("error", fail);
16
+ socket.on("close", () => { if (!closed) handlers.onEnd(); });
17
+ return {close() { closed = true; socket.destroy(); }};
18
+ }
19
+
20
+ /** ffmpeg's MJPEG output has no per-frame process or temporary file. */
21
+ export function mjpegParser(onFrame: (bytes: Buffer) => void, onError: (error: Error) => void): (chunk: Buffer) => void {
22
+ let buffer = Buffer.alloc(0), failed = false;
23
+ return chunk => {
24
+ if (failed) return;
25
+ buffer = Buffer.concat([buffer, chunk]);
26
+ for (;;) {
27
+ const start = buffer.indexOf(Buffer.from([0xff, 0xd8]));
28
+ if (start < 0) { buffer = buffer.subarray(Math.max(0, buffer.length - 1)); return; }
29
+ if (start) buffer = buffer.subarray(start);
30
+ const end = buffer.indexOf(Buffer.from([0xff, 0xd9]), 2);
31
+ if (end >= 0) { onFrame(Buffer.from(buffer.subarray(0, end + 2))); buffer = buffer.subarray(end + 2); continue; }
32
+ if (buffer.length > 5_000_000) { failed = true; onError(new Error("Camera JPEG too large")); }
33
+ return;
34
+ }
35
+ };
36
+ }
37
+
38
+ export function openRtspCameraSource(host: string, token: string, fps: number, handlers: Handlers, ffmpegPath = "ffmpeg"): ReturnType<OpenCameraSource> {
39
+ const url = `rtsps://bblp:${encodeURIComponent(token)}@${host}:322/streaming/live/1`;
40
+ const child = spawn(ffmpegPath, ["-tls_verify", "0", "-rtsp_transport", "tcp", "-i", url,
41
+ "-an", "-vf", `fps=${fps}`, "-c:v", "mjpeg", "-q:v", "5", "-f", "image2pipe", "-loglevel", "error", "pipe:1"], {stdio: ["ignore", "pipe", "pipe"]});
42
+ let closed = false, denied = false;
43
+ let timer: ReturnType<typeof setTimeout>;
44
+ const fail = (error: Error) => { if (!closed) handlers.onError(error); };
45
+ const arm = () => { clearTimeout(timer); timer = setTimeout(() => fail(new Error("RTSP camera stream timed out")), 15_000); timer.unref(); };
46
+ arm();
47
+ child.stdout.on("data", mjpegParser(bytes => { arm(); if (!closed) handlers.onFrame(bytes); }, fail));
48
+ // Drain stderr but never expose the credential-bearing URL in ffmpeg diagnostics.
49
+ child.stderr.on("data", bytes => { if (/401|403|Unauthorized|Forbidden/i.test(String(bytes))) denied = true; });
50
+ child.once("error", () => fail(new Error("RTSP camera process could not start")));
51
+ child.once("exit", () => { clearTimeout(timer); if (!closed) denied ? fail(new Error("RTSP camera authentication failed")) : handlers.onEnd(); });
52
+ return {close() { closed = true; clearTimeout(timer); child.kill("SIGKILL"); }};
53
+ }
@@ -0,0 +1,165 @@
1
+ /** One camera source per printer; bounded frames and native thumbnail processing. */
2
+ import sharp from "sharp";
3
+ sharp.cache({ memory: 8, files: 0, items: 32 });
4
+
5
+ export type CameraTransport = "tcp-6000" | "rtsps-322";
6
+ export type CameraSource = { close(): void };
7
+ export type OpenCameraSource = (handlers: { onFrame(bytes: Buffer): void; onError(error: Error): void; onEnd(): void }) => CameraSource;
8
+ export type FrameOptions = { sinceSeq?: number; waitMs?: number; maxWidth?: number; maxBytes?: number; changedOnly?: boolean; minChange?: number; signal?: AbortSignal };
9
+ export type StreamFrameResult = { status: "frame" | "unchanged" | "stopped" | "unavailable"; seq: number; capturedAt?: string; width?: number; height?: number; format?: "image/jpeg"; base64?: string; change?: number; reason?: "auth" | "unreachable" | "no-camera" };
10
+ type Frame = { seq: number; bytes: Buffer; thumb: Buffer; at: number; width: number; height: number; scaled: Map<string, Promise<{data: Buffer; info: {width: number; height: number}}>> };
11
+ export type StreamOptions = { transport: CameraTransport; fps: number; idleTimeoutMs: number; open: OpenCameraSource; skipFirstFrame: boolean };
12
+
13
+ export function thumbnailChange(a: Uint8Array, b: Uint8Array): number {
14
+ let total = 0;
15
+ for (let i = 0; i < a.length; i++) total += Math.abs(a[i] - b[i]);
16
+ return total / (a.length * 255);
17
+ }
18
+
19
+ export class CameraStream {
20
+ readonly startedAt = new Date().toISOString();
21
+ readonly transport: CameraTransport;
22
+ readonly fps: number;
23
+ #source?: CameraSource;
24
+ #timer?: ReturnType<typeof setTimeout>;
25
+ #generation = 0;
26
+ #processing = false;
27
+ #lastAccepted = -Infinity;
28
+ #latest?: Frame;
29
+ // Keep thumbnails of frames actually delivered, not every camera frame. A quiet view may keep
30
+ // comparing with its first frame for hours; a rolling JPEG history would repeatedly resend it.
31
+ #references = new Map<number, Buffer>();
32
+ #waiters = new Set<() => void>();
33
+ #stopped = false;
34
+ #reconnected = false;
35
+ #reason?: StreamFrameResult["reason"];
36
+ #seq = 0;
37
+ constructor(private options: StreamOptions, private nextSeq: () => number, private now: () => number = Date.now) {
38
+ this.transport = options.transport; this.fps = options.fps;
39
+ }
40
+ get stopped(): boolean { return this.#stopped; }
41
+ start(): void { this.touch(); this.#connect(); }
42
+ touch(idleTimeoutMs?: number): void {
43
+ if (this.#stopped) return;
44
+ if (idleTimeoutMs !== undefined) this.options.idleTimeoutMs = idleTimeoutMs;
45
+ clearTimeout(this.#timer);
46
+ this.#timer = setTimeout(() => this.stop(), this.options.idleTimeoutMs);
47
+ this.#timer.unref();
48
+ }
49
+ stop(): void {
50
+ if (this.#stopped) return;
51
+ this.#stopped = true; this.#generation++;
52
+ clearTimeout(this.#timer);
53
+ this.#source?.close(); this.#source = undefined;
54
+ this.#latest = undefined; this.#references.clear(); this.#wake();
55
+ }
56
+ #wake(): void { for (const wake of [...this.#waiters]) wake(); }
57
+ #connect(): void {
58
+ const generation = ++this.#generation;
59
+ let buffered: Buffer | undefined, live = !this.options.skipFirstFrame;
60
+ const current = () => !this.#stopped && generation === this.#generation;
61
+ try {
62
+ const source = this.options.open({
63
+ onFrame: bytes => {
64
+ if (!current()) return;
65
+ // P1/A1 replay their stale buffered frame, sometimes more than once.
66
+ if (!live) { if (!buffered) { buffered = bytes; return; } if (bytes.equals(buffered)) return; buffered = undefined; live = true; }
67
+ if (this.#processing || this.now() - this.#lastAccepted < 1000 / this.fps) return;
68
+ this.#lastAccepted = this.now(); this.#processing = true;
69
+ void this.#accept(bytes, generation).catch(() => { if (current()) this.#lost("unreachable"); })
70
+ .finally(() => { this.#processing = false; });
71
+ },
72
+ onError: error => { if (current()) this.#lost(/auth|payload size|401|403/i.test(error.message) ? "auth" : "unreachable"); },
73
+ onEnd: () => { if (current()) this.#lost("unreachable"); },
74
+ });
75
+ // A transport may fail synchronously. Never keep its abandoned source after reconnect/stop.
76
+ if (current()) this.#source = source; else source.close();
77
+ } catch { if (current()) this.#lost("unreachable"); }
78
+ }
79
+ #lost(reason: NonNullable<StreamFrameResult["reason"]>): void {
80
+ this.#generation++;
81
+ this.#source?.close(); this.#source = undefined;
82
+ if (!this.#reconnected && reason !== "auth") { this.#reconnected = true; this.#connect(); return; }
83
+ this.#reason = reason; this.stop();
84
+ }
85
+ async #accept(bytes: Buffer, generation: number): Promise<void> {
86
+ if (bytes.length > 5_000_000) throw Error("Camera JPEG too large");
87
+ const decoder = sharp(bytes, {limitInputPixels: 8_000_000});
88
+ const metadata = await decoder.metadata();
89
+ const thumb = await decoder.resize(32, 18, {fit: "fill"}).greyscale().raw().toBuffer();
90
+ if (this.#stopped || generation !== this.#generation) return;
91
+ this.#latest = {seq: this.#seq = this.nextSeq(), bytes, thumb, at: this.now(), width: metadata.width!, height: metadata.height!, scaled: new Map()};
92
+ this.#wake();
93
+ }
94
+ async frame(options: FrameOptions = {}): Promise<StreamFrameResult> {
95
+ const since = options.sinceSeq ?? 0, deadline = Date.now() + (options.waitMs ?? 0);
96
+ this.touch();
97
+ for (;;) {
98
+ options.signal?.throwIfAborted();
99
+ if (this.#reason) return {status: "unavailable", seq: this.#seq, reason: this.#reason};
100
+ if (this.#stopped) return {status: "stopped", seq: this.#seq};
101
+ const latest = this.#latest;
102
+ if (latest && latest.seq > since) {
103
+ const reference = this.#references.get(since);
104
+ const change = reference ? thumbnailChange(latest.thumb, reference) : 1;
105
+ if (options.changedOnly === false || change >= (options.minChange ?? 0.02)) return this.#result(latest, change, options.maxWidth, options.maxBytes);
106
+ }
107
+ const left = deadline - Date.now();
108
+ if (left <= 0) return {status: "unchanged", seq: since, ...(latest ? {capturedAt: new Date(latest.at).toISOString()} : {})};
109
+ await new Promise<void>(resolve => {
110
+ const done = () => { clearTimeout(timer); this.#waiters.delete(done); options.signal?.removeEventListener("abort", done); resolve(); };
111
+ const timer = setTimeout(done, left);
112
+ this.#waiters.add(done); options.signal?.addEventListener("abort", done, {once: true});
113
+ });
114
+ }
115
+ }
116
+ async latest(waitMs: number): Promise<Buffer | undefined> {
117
+ const result = await this.frame({waitMs, changedOnly: false});
118
+ return result.status === "frame" ? Buffer.from(result.base64!, "base64") : undefined;
119
+ }
120
+ async #encoded(frame: Frame, width: number, maxBytes?: number): Promise<{data: Buffer; info: {width: number; height: number}}> {
121
+ // Start near the byte target instead of always encoding a full-size frame that will be
122
+ // discarded. Source JPEG density is a cheap conservative estimate, not a size guarantee.
123
+ if (maxBytes && frame.bytes.length > maxBytes) width = Math.min(width, Math.max(1, Math.floor(frame.width * Math.sqrt(maxBytes / frame.bytes.length) * 0.8)));
124
+ // At most four native encodes. The final 1-pixel fallback guarantees a bounded result
125
+ // even for pathological entropy; quality stays 70 and aspect ratio is preserved.
126
+ for (let attempt = 0; attempt < 4; attempt++) {
127
+ const encoded = await sharp(frame.bytes, {limitInputPixels: 8_000_000}).resize({width, withoutEnlargement: true}).jpeg({quality: 70}).toBuffer({resolveWithObject: true});
128
+ if (!maxBytes || encoded.data.length <= maxBytes) return encoded;
129
+ width = attempt === 2 ? 1 : Math.max(1, Math.floor(width * Math.min(0.8, Math.sqrt(maxBytes / encoded.data.length) * 0.9)));
130
+ }
131
+ throw new Error("Camera frame could not fit max_bytes");
132
+ }
133
+ async #result(frame: Frame, change: number, maxWidth?: number, maxBytes?: number): Promise<StreamFrameResult> {
134
+ let bytes = frame.bytes, width = frame.width, height = frame.height;
135
+ if ((maxWidth && width > maxWidth) || (maxBytes && bytes.length > maxBytes)) {
136
+ const key = `${maxWidth ?? width}:${maxBytes ?? 0}`;
137
+ let scaled = frame.scaled.get(key);
138
+ if (!scaled) {
139
+ scaled = this.#encoded(frame, Math.min(width, maxWidth ?? width), maxBytes);
140
+ if (frame.scaled.size < 4) frame.scaled.set(key, scaled);
141
+ }
142
+ const resized = await scaled; bytes = resized.data; width = resized.info.width; height = resized.info.height;
143
+ }
144
+ if (this.#stopped) return this.#reason ? {status: "unavailable", seq: this.#seq, reason: this.#reason} : {status: "stopped", seq: this.#seq};
145
+ this.#references.set(frame.seq, frame.thumb);
146
+ if (this.#references.size > 256) this.#references.delete(this.#references.keys().next().value!);
147
+ return {status: "frame", seq: frame.seq, capturedAt: new Date(frame.at).toISOString(), width, height, format: "image/jpeg", base64: bytes.toString("base64"), change};
148
+ }
149
+ }
150
+
151
+ export class CameraStreams {
152
+ #streams = new Map<string, CameraStream>();
153
+ #sequence = 0;
154
+ constructor(private now: () => number = Date.now) {}
155
+ get(key: string): CameraStream | undefined { return this.#streams.get(key); }
156
+ start(key: string, options: StreamOptions): {stream: CameraStream; status: "started" | "running"} {
157
+ const existing = this.get(key);
158
+ if (existing && !existing.stopped) { existing.touch(options.idleTimeoutMs); return {stream: existing, status: "running"}; }
159
+ const stream = new CameraStream(options, () => ++this.#sequence, this.now);
160
+ this.#streams.set(key, stream); stream.start();
161
+ return {stream, status: "started"};
162
+ }
163
+ stop(key: string): void { this.get(key)?.stop(); }
164
+ stopAll(): void { for (const stream of this.#streams.values()) stream.stop(); this.#streams.clear(); }
165
+ }
@@ -0,0 +1,29 @@
1
+ /** Additive stream tools; discovery is the capability check for older clients. */
2
+ const routing = {
3
+ host: {type: "string", description: "Printer LAN host or IP; defaults to the configured Bambu host."},
4
+ bambu_serial: {type: "string", description: "Printer serial number; defaults to the configured serial and identifies its shared stream."},
5
+ bambu_token: {type: "string", description: "Printer LAN access code; defaults to the configured access code."},
6
+ };
7
+ const frameSchema = {
8
+ type: "object" as const, properties: {
9
+ status: {type: "string", enum: ["frame", "unchanged", "stopped", "unavailable"]}, seq: {type: "integer", minimum: 0},
10
+ capturedAt: {type: "string"}, width: {type: "integer"}, height: {type: "integer"},
11
+ format: {type: "string", const: "image/jpeg"}, base64: {type: "string"}, change: {type: "number"},
12
+ reason: {type: "string", enum: ["no-camera", "auth", "unreachable"]},
13
+ }, required: ["status", "seq"],
14
+ };
15
+ export const CAMERA_STREAM_TOOLS = [
16
+ {name: "camera_stream_start", description: "Start or renew one persistent camera connection for this printer. Call only while watched; it closes automatically after idle_timeout_ms without a viewer request. camera_snapshot then reuses its latest frame. No printer motion or print commands.",
17
+ inputSchema: {type: "object" as const, properties: {...routing, bambu_model: {type: "string", description: "Bambu model used to select the camera transport; defaults to BAMBU_MODEL."}, fps: {type: "number", minimum: 0.2, maximum: 2, default: 1, description: "Maximum processed frames per second. The first viewer sets the rate until the stream closes."}, idle_timeout_ms: {type: "integer", minimum: 5000, maximum: 120000, default: 30000, description: "Close the shared connection after this many milliseconds without a viewer request."}}, additionalProperties: false},
18
+ outputSchema: {type: "object" as const, properties: {status: {type: "string", enum: ["started", "running"]}, transport: {type: "string", enum: ["tcp-6000", "rtsps-322"]}, fps: {type: "number"}, startedAt: {type: "string"}}, required: ["status", "transport", "fps", "startedAt"]}},
19
+ {name: "camera_frame", description: "Read the shared camera stream, optionally waiting up to 10 seconds. Returns JPEG only when newer than since_seq and visibly changed (32×18 grayscale difference). Retain the last delivered frame's seq on unchanged. max_width resizes JPEG to the viewer. Does not start a stopped stream.",
20
+ inputSchema: {type: "object" as const, properties: {...routing, since_seq: {type: "integer", minimum: 0, default: 0, description: "Sequence of the last delivered JPEG; retain it when a result is unchanged."}, wait_ms: {type: "integer", minimum: 0, maximum: 10000, default: 0, description: "Maximum time to await a newer changed frame; zero returns immediately."}, max_width: {type: "integer", minimum: 1, maximum: 4096, description: "Optional maximum JPEG width in pixels, preserving aspect ratio and never enlarging."}, max_bytes: {type: "integer", minimum: 4096, maximum: 5000000, description: "Optional maximum encoded JPEG bytes. Downscales further at quality 70 when needed; base64 adds about one third plus protocol overhead. Use 42000 for a two-second 30 KB/s viewer budget."}, changed_only: {type: "boolean", default: true, description: "Return JPEG only when its thumbnail differs enough from the last delivered frame."}, min_change: {type: "number", minimum: 0, maximum: 1, default: 0.02, description: "Minimum mean absolute grayscale thumbnail difference, normalized from zero to one."}}, additionalProperties: false}, outputSchema: frameSchema},
21
+ {name: "camera_stream_stop", description: "Close this printer's camera connection and free its cached frames. Other printers keep their own streams. Active viewers may restart it; normally let the idle timeout close a shared stream.",
22
+ inputSchema: {type: "object" as const, properties: routing, additionalProperties: false}, outputSchema: {type: "object" as const, properties: {status: {type: "string", const: "stopped"}}, required: ["status"]}},
23
+ ];
24
+
25
+ export function cameraNumber(value: unknown, fallback: number, min: number, max: number, name: string, integer = false): number {
26
+ const n = value === undefined ? fallback : value;
27
+ if (typeof n !== "number" || !Number.isFinite(n) || n < min || n > max || (integer && !Number.isSafeInteger(n))) throw new Error(`${name} must be ${integer ? "an integer" : "a number"} from ${min} to ${max}`);
28
+ return n;
29
+ }