bambu-printer-mcp 1.1.48 → 1.1.50

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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The print options Bambu Studio's Send dialog sends, resolved the way it
3
+ * resolves them, so every print route sends what Bambu's own Print button
4
+ * would. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
5
+ * the hidden-HMS and stage tables are pinned to:
6
+ *
7
+ * - SelectMachine.cpp:3344-3356 `set_print_config(bed_type,
8
+ * bed_leveling == "on", flow_cali == "on", false, timelapse, true,
9
+ * ext_change_assist, bed_leveling.getValueInt(), flow_cali.getValueInt(),
10
+ * nozzle_offset_cali.getValueInt(), pa_value_switch ? 0 : 1)`. Vibration
11
+ * calibration is always false and layer inspection always true; the
12
+ * parameter order is PrintJob.hpp:98-116.
13
+ * - SelectMachine.cpp:7318-7329 `getValueInt`: off 0, on 1, auto 2.
14
+ * - SelectMachine.cpp:1117-1123 `update_select_layout`: update_option_opts
15
+ * (which choices each option offers on this printer) runs before
16
+ * load_option_vals.
17
+ * - SelectMachine.cpp:2993-3027 `load_option_vals`: the value saved in
18
+ * BambuStudio.conf under the printer type, if the option offers it; else
19
+ * "auto" if offered; else "on". Dual-nozzle printers then set nozzle offset
20
+ * calibration to "auto" for a two-nozzle job and, without a filament
21
+ * switcher, "off" for a one-nozzle job.
22
+ * - SelectMachine.cpp:2586-2615 `update_option_opts`: bed leveling offers
23
+ * auto/on/off when the printer's support_bed_leveling is 2 and on/off when it
24
+ * is 1; with 0 it is hidden and keeps the auto/on/off it was built with
25
+ * (SelectMachine.cpp:676-691), as does flow calibration when the printer has
26
+ * no PA calibration. DeviceManager.cpp:1100/4441 give P-series printers
27
+ * (series_p1p: P1P, P1S) no PA calibration, so their flow calibration is
28
+ * hidden and resolves to "auto". Nozzle offset calibration always offers auto.
29
+ * - SelectMachine.cpp:705-707: the PA value switch starts on and is not saved,
30
+ * so extruder_cali_manual_mode is 0.
31
+ *
32
+ * Approximations, outside the P1P/P1S: flow calibration on other printers is
33
+ * shown when the printer's push status reports PA calibration (assumed here),
34
+ * and offers auto when support_auto_flow_calibration is true and the mapped
35
+ * filaments allow it (can_support_pa_auto_cali, assumed true). A filament
36
+ * switcher on a dual-nozzle printer is assumed absent.
37
+ */
38
+ import fs from "node:fs";
39
+ import os from "node:os";
40
+ import path from "node:path";
41
+ const AUTO_ON_OFF = ["auto", "on", "off"];
42
+ const ON_OFF = ["on", "off"];
43
+ /**
44
+ * Studio's printer types (resources/printers/<type>.json at the pinned commit:
45
+ * model_id/printer_type, printer_series, support_bed_leveling,
46
+ * support_auto_flow_calibration), keyed by this server's model names.
47
+ */
48
+ const STUDIO_PRINTERS = {
49
+ p1p: { types: ["C11"], pSeries: true, bedLeveling: 1, autoFlow: false, dualNozzle: false },
50
+ p1s: { types: ["C12"], pSeries: true, bedLeveling: 1, autoFlow: false, dualNozzle: false },
51
+ x1c: { types: ["3DPrinter-X1-Carbon"], pSeries: false, bedLeveling: 1, autoFlow: false, dualNozzle: false },
52
+ x1: { types: ["3DPrinter-X1"], pSeries: false, bedLeveling: 1, autoFlow: false, dualNozzle: false },
53
+ x1e: { types: ["C13"], pSeries: false, bedLeveling: 1, autoFlow: false, dualNozzle: false },
54
+ a1mini: { types: ["N1"], pSeries: false, bedLeveling: 1, autoFlow: false, dualNozzle: false },
55
+ a1: { types: ["N2S"], pSeries: false, bedLeveling: 1, autoFlow: false, dualNozzle: false },
56
+ p2s: { types: ["N7"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: false },
57
+ x2d: { types: ["N6"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: true },
58
+ h2s: { types: ["O1S"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: false },
59
+ h2d: { types: ["O1D"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: true },
60
+ h2dpro: { types: ["O1E"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: true },
61
+ h2c: { types: ["O1C", "O1C2"], pSeries: false, bedLeveling: 2, autoFlow: true, dualNozzle: true },
62
+ };
63
+ /** Where Studio keeps BambuStudio.conf; BAMBU_STUDIO_CONFIG overrides it (empty: none). */
64
+ export function studioConfigPath() {
65
+ const override = process.env.BAMBU_STUDIO_CONFIG;
66
+ if (override !== undefined)
67
+ return override.trim() || undefined;
68
+ if (process.platform === "darwin")
69
+ return path.join(os.homedir(), "Library", "Application Support", "BambuStudio", "BambuStudio.conf");
70
+ if (process.platform === "win32")
71
+ return process.env.APPDATA ? path.join(process.env.APPDATA, "BambuStudio", "BambuStudio.conf") : undefined;
72
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "BambuStudio", "BambuStudio.conf");
73
+ }
74
+ /**
75
+ * The Send dialog options Studio saved for a printer type, and nothing else:
76
+ * BambuStudio.conf also holds access codes, so only that one section is kept,
77
+ * and a parse failure is reported without any of the file's text.
78
+ */
79
+ export function readStudioSavedOptions(printerTypes, configPath) {
80
+ if (!configPath)
81
+ return undefined;
82
+ let text;
83
+ try {
84
+ const stat = fs.statSync(configPath);
85
+ if (!stat.isFile() || stat.size > 16 * 1024 * 1024)
86
+ return undefined;
87
+ text = fs.readFileSync(configPath, "utf8");
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ let config;
93
+ // Studio appends "# MD5 checksum <hex>" after the JSON.
94
+ try {
95
+ config = JSON.parse(text.split("\n").filter(line => !line.trimStart().startsWith("#")).join("\n"));
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ if (!config || typeof config !== "object")
101
+ return undefined;
102
+ for (const type of printerTypes) {
103
+ const section = config[type];
104
+ if (!section || typeof section !== "object" || Array.isArray(section))
105
+ continue;
106
+ const saved = {};
107
+ for (const key of ["bed_leveling", "flow_cali", "nozzle_offset_cali", "timelapse"]) {
108
+ const value = section[key];
109
+ if (typeof value === "string")
110
+ saved[key] = value;
111
+ }
112
+ return saved;
113
+ }
114
+ return undefined;
115
+ }
116
+ function fromInt(value, label) {
117
+ if (value === 0)
118
+ return "off";
119
+ if (value === 1)
120
+ return "on";
121
+ if (value === 2)
122
+ return "auto";
123
+ throw new Error(`${label} must be 0 (off), 1 (on) or 2 (auto).`);
124
+ }
125
+ const toInt = (value) => value === "off" ? 0 : value === "on" ? 1 : 2;
126
+ /** load_option_vals for one option: saved if offered, else auto if offered, else on. */
127
+ function loaded(saved, offers) {
128
+ if (saved !== undefined && offers.includes(saved))
129
+ return { value: saved, source: "studio-config" };
130
+ return { value: offers.includes("auto") ? "auto" : "on", source: "studio-default" };
131
+ }
132
+ /**
133
+ * What Studio's Send dialog would send for this model, with the caller's
134
+ * explicit choices taking precedence. usedNozzles is the number of nozzles the
135
+ * job uses, for dual-nozzle printers.
136
+ */
137
+ export function resolveStudioPrintOptions(model, caller = {}, options = {}) {
138
+ const printer = STUDIO_PRINTERS[model];
139
+ const saved = printer ? readStudioSavedOptions(printer.types, "configPath" in options ? options.configPath : studioConfigPath()) ?? {} : {};
140
+ const printerType = printer?.types[0];
141
+ const bedOffers = !printer || printer.bedLeveling !== 1 ? AUTO_ON_OFF : ON_OFF;
142
+ const flowOffers = !printer || printer.pSeries || printer.autoFlow ? AUTO_ON_OFF : ON_OFF;
143
+ const bed = loaded(saved.bed_leveling, bedOffers);
144
+ const flow = loaded(saved.flow_cali, flowOffers);
145
+ let offset = loaded(saved.nozzle_offset_cali, AUTO_ON_OFF);
146
+ if (printer?.dualNozzle && options.usedNozzles !== undefined) {
147
+ if (options.usedNozzles >= 2)
148
+ offset = { value: "auto", source: "studio-default" };
149
+ else if (options.usedNozzles === 1)
150
+ offset = { value: "off", source: "studio-default" };
151
+ }
152
+ const choose = (current, auto, flag, label) => auto !== undefined ? { value: fromInt(auto, label), source: "caller" }
153
+ : flag !== undefined ? { value: flag ? "on" : "off", source: "caller" }
154
+ : current;
155
+ const bedLeveling = choose(bed, caller.autoBedLeveling, caller.bedLeveling, "auto_bed_leveling");
156
+ const flowCali = choose(flow, caller.autoFlowCali, caller.flowCalibration, "auto_flow_cali");
157
+ const nozzleOffset = choose(offset, caller.autoOffsetCali, undefined, "auto_offset_cali");
158
+ const manualMode = caller.extruderCaliManualMode ?? 0;
159
+ if (!Number.isInteger(manualMode) || manualMode < -1 || manualMode > 1)
160
+ throw new Error("extruder_cali_manual_mode must be -1, 0 or 1.");
161
+ return {
162
+ ...(printerType ? { printerType } : {}),
163
+ values: { bed_leveling: bedLeveling.value, flow_cali: flowCali.value, nozzle_offset_cali: nozzleOffset.value },
164
+ sources: { bed_leveling: bedLeveling.source, flow_cali: flowCali.source, nozzle_offset_cali: nozzleOffset.source },
165
+ task_bed_leveling: bedLeveling.value === "on",
166
+ task_flow_cali: flowCali.value === "on",
167
+ task_vibration_cali: caller.vibrationCalibration ?? false,
168
+ task_layer_inspect: caller.layerInspect ?? true,
169
+ auto_bed_leveling: toInt(bedLeveling.value),
170
+ auto_flow_cali: toInt(flowCali.value),
171
+ auto_offset_cali: toInt(nozzleOffset.value),
172
+ extruder_cali_manual_mode: manualMode,
173
+ };
174
+ }
175
+ /** The number of nozzles a job's used filaments print from, when the inspection knows. */
176
+ export function usedNozzleCount(inspection) {
177
+ const nozzles = inspection.usedFilamentPositions.map(position => inspection.filamentNozzleIndices?.[position]).filter((value) => Number.isInteger(value));
178
+ return nozzles.length === inspection.usedFilamentPositions.length && nozzles.length ? new Set(nozzles).size : undefined;
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.48",
3
+ "version": "1.1.50",
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": {
@@ -13,7 +13,7 @@
13
13
  "start:stdio": "MCP_TRANSPORT=stdio node dist/index.js",
14
14
  "start:http": "MCP_TRANSPORT=streamable-http node dist/index.js",
15
15
  "build": "tsc",
16
- "test": "npm run build && node --test tests/*.test.mjs tests/**/*.test.mjs",
16
+ "test": "npm run build && node --test --import ./tests/support/isolate-studio-config.mjs tests/*.test.mjs tests/**/*.test.mjs",
17
17
  "package:mcpb": "npm run build && node scripts/package-mcpb.mjs",
18
18
  "version": "node scripts/sync-manifest-version.mjs",
19
19
  "postinstall": "node scripts/install-patches.mjs",
@@ -25,6 +25,11 @@ export type BambuNativePrintOptions = {
25
25
  flowCalibration?: boolean;
26
26
  vibrationCalibration?: boolean;
27
27
  layerInspect?: boolean;
28
+ /** Bambu Studio's PrintParams auto_* values (0 off, 1 on, 2 auto) and extruder_cali_manual_mode. */
29
+ autoBedLeveling?: number;
30
+ autoFlowCali?: number;
31
+ autoOffsetCali?: number;
32
+ extruderCaliManualMode?: number;
28
33
  timelapse?: boolean;
29
34
  /** true: the SD card or USB stick; false: internal storage (eMMC); unset: BAMBU_NATIVE_TRY_EMMC_PRINT or internal. Reported as the requested storage. */
30
35
  externalStorage?: boolean;
@@ -863,8 +868,13 @@ export async function printWithBambuNative(
863
868
  BAMBU_NATIVE_NOZZLES_INFO: options.nozzlesInfo || "",
864
869
  BAMBU_NATIVE_BED_LEVELING: boolEnv(options.bedLeveling, true),
865
870
  BAMBU_NATIVE_FLOW_CALIBRATION: boolEnv(options.flowCalibration, true),
866
- BAMBU_NATIVE_VIBRATION_CALIBRATION: boolEnv(options.vibrationCalibration, true),
867
- BAMBU_NATIVE_LAYER_INSPECT: boolEnv(options.layerInspect, false),
871
+ // Bambu Studio's Send dialog hard-codes these (SelectMachine.cpp:3344-3356).
872
+ BAMBU_NATIVE_VIBRATION_CALIBRATION: boolEnv(options.vibrationCalibration, false),
873
+ BAMBU_NATIVE_LAYER_INSPECT: boolEnv(options.layerInspect, true),
874
+ ...(options.autoBedLeveling === undefined ? {} : { BAMBU_NATIVE_AUTO_BED_LEVELING: String(options.autoBedLeveling) }),
875
+ ...(options.autoFlowCali === undefined ? {} : { BAMBU_NATIVE_AUTO_FLOW_CALI: String(options.autoFlowCali) }),
876
+ ...(options.autoOffsetCali === undefined ? {} : { BAMBU_NATIVE_AUTO_OFFSET_CALI: String(options.autoOffsetCali) }),
877
+ ...(options.extruderCaliManualMode === undefined ? {} : { BAMBU_NATIVE_EXTRUDER_CALI_MANUAL_MODE: String(options.extruderCaliManualMode) }),
868
878
  BAMBU_NATIVE_TIMELAPSE: boolEnv(options.timelapse, false),
869
879
  ...(options.externalStorage === undefined ? {} : { BAMBU_NATIVE_TRY_EMMC_PRINT: String(!options.externalStorage) }),
870
880
  },
@@ -922,8 +932,13 @@ export async function uploadWithBambuNative(
922
932
  BAMBU_NATIVE_NOZZLES_INFO: options.nozzlesInfo || "",
923
933
  BAMBU_NATIVE_BED_LEVELING: boolEnv(options.bedLeveling, true),
924
934
  BAMBU_NATIVE_FLOW_CALIBRATION: boolEnv(options.flowCalibration, true),
925
- BAMBU_NATIVE_VIBRATION_CALIBRATION: boolEnv(options.vibrationCalibration, true),
926
- BAMBU_NATIVE_LAYER_INSPECT: boolEnv(options.layerInspect, false),
935
+ // Bambu Studio's Send dialog hard-codes these (SelectMachine.cpp:3344-3356).
936
+ BAMBU_NATIVE_VIBRATION_CALIBRATION: boolEnv(options.vibrationCalibration, false),
937
+ BAMBU_NATIVE_LAYER_INSPECT: boolEnv(options.layerInspect, true),
938
+ ...(options.autoBedLeveling === undefined ? {} : { BAMBU_NATIVE_AUTO_BED_LEVELING: String(options.autoBedLeveling) }),
939
+ ...(options.autoFlowCali === undefined ? {} : { BAMBU_NATIVE_AUTO_FLOW_CALI: String(options.autoFlowCali) }),
940
+ ...(options.autoOffsetCali === undefined ? {} : { BAMBU_NATIVE_AUTO_OFFSET_CALI: String(options.autoOffsetCali) }),
941
+ ...(options.extruderCaliManualMode === undefined ? {} : { BAMBU_NATIVE_EXTRUDER_CALI_MANUAL_MODE: String(options.extruderCaliManualMode) }),
927
942
  BAMBU_NATIVE_TIMELAPSE: boolEnv(options.timelapse, false),
928
943
  },
929
944
  300_000,
@@ -6,6 +6,7 @@
6
6
  import path from "node:path";
7
7
  import { BAMBU_STAGES } from "../printers/bambu-stages.js";
8
8
  import { HMS_MESSAGES, HMS_MESSAGES_SOURCE, PRINT_ERROR_MESSAGES, type HmsText } from "../safety/hms-messages.js";
9
+ import { studioDownloadedText } from "../studio-hms-text.js";
9
10
  import { isDualNozzleModel, normalizeModel } from "../safety/limits.js";
10
11
  import { finiteNumber, hmsCode, isHiddenNotice } from "../safety/printer-state.js";
11
12
  import { COUNTERPART_CONTRACT, type PrintProgress, type PrintState, type Problem, type ProblemSeverity, type Temperature } from "./schemas.js";
@@ -77,7 +78,7 @@ export function bambuProblems(raw: Record<string, any>, serial: string, model: s
77
78
  // 0300400C only records a cancel; it is the state, not a problem.
78
79
  if (error !== undefined && Number.isInteger(error) && error > 0 && error <= 0xffffffff && error !== TASK_CANCELLED) {
79
80
  const code = error.toString(16).padStart(8, "0").toUpperCase();
80
- add({ code, severity: "error", message: tableText(PRINT_ERROR_MESSAGES, code, serial) ?? undocumented(code) });
81
+ add({ code, severity: "error", message: tableText(PRINT_ERROR_MESSAGES, code, serial) ?? studioDownloadedText("error", code, serial) ?? undocumented(code) });
81
82
  }
82
83
  for (const reported of Array.isArray(raw.hms) ? raw.hms : []) {
83
84
  const entry = hmsCode(reported);
@@ -93,7 +94,8 @@ export function bambuProblems(raw: Record<string, any>, serial: string, model: s
93
94
  add({
94
95
  code,
95
96
  severity: HMS_SEVERITIES[entry.severity] ?? "error",
96
- message: tableText(HMS_MESSAGES, entry.hex, serial) ?? undocumented(code),
97
+ // The pinned tag bundles no P1, X1 or A1 table; the user's own Studio download may have the text.
98
+ message: tableText(HMS_MESSAGES, entry.hex, serial) ?? studioDownloadedText("hms", entry.hex, serial) ?? undocumented(code),
97
99
  url: hmsUrl(entry.hex),
98
100
  });
99
101
  }
@@ -72,9 +72,11 @@ export const defaultFusionSystem: FusionSystem = {
72
72
  /**
73
73
  * An open port is not enough: Blender's MCP add-on defaults to
74
74
  * localhost:9876, the add-in's own default. The add-in speaks newline-delimited JSON
75
- * (addon/server/socket_server.py) and answers {"type":"ping"} with
76
- * {"status":"success","result":{"pong":true}} without touching Fusion's API;
77
- * Blender's add-on answers an unknown command with an error.
75
+ * (addon/server/socket_server.py) and answers {"type":"ping"} without touching
76
+ * Fusion's API: on its fast path (event_bridge.py) with
77
+ * {"status":"success","result":{"ok":true,"status":"pong"}}, and through its
78
+ * command handler with {"pong":true}. Blender's add-on answers an unknown command
79
+ * with an error.
78
80
  */
79
81
  addinAnswers: (host, port, timeoutMs) => new Promise(resolve => {
80
82
  const socket = net.connect({ host, port });
@@ -96,7 +98,7 @@ export const defaultFusionSystem: FusionSystem = {
96
98
  const newline = buffer.indexOf("\n");
97
99
  try {
98
100
  const reply = JSON.parse(newline >= 0 ? buffer.slice(0, newline) : buffer);
99
- done(reply?.status === "success" && reply?.result?.pong === true);
101
+ done(reply?.status === "success" && (reply?.result?.status === "pong" || reply?.result?.pong === true));
100
102
  } catch {
101
103
  if (newline >= 0) done(false);
102
104
  }
package/src/index.ts CHANGED
@@ -45,6 +45,7 @@ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, h
45
45
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, parse3MF } from './3mf_parser.js';
46
46
  import type { ThreeMFAmsRequirements } from "./types.js";
47
47
  import { BambuImplementation, assertDirectPrintSupported, checkedFile } from "./printers/bambu.js";
48
+ import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "./studio-print-options.js";
48
49
  import { inspectPrintFile } from "./safety/print-file.js";
49
50
  import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
50
51
  import { isDualNozzleModel } from "./safety/limits.js";
@@ -158,6 +159,28 @@ function assertUniformCliNozzles(args: Record<string, any>): void {
158
159
  }
159
160
 
160
161
  const VALID_BAMBU_MODELS = ["p1s", "p1p", "p2s", "x1c", "x1e", "a1", "a1mini", "h2d", "h2dpro", "h2s", "h2c", "x2d"] as const;
162
+
163
+ /** The Send dialog options a caller set explicitly; the rest resolve as Bambu Studio does (studio-print-options.ts). */
164
+ function callerPrintOptions(args: Record<string, any> | undefined): CallerPrintOptions {
165
+ const flag = (value: unknown) => value === undefined ? undefined : Boolean(value);
166
+ const int = (value: unknown, label: string) => {
167
+ if (value === undefined) return undefined;
168
+ const number = Number(value);
169
+ if (!Number.isInteger(number)) throw new Error(`${label} must be an integer.`);
170
+ return number;
171
+ };
172
+ const options: CallerPrintOptions = {
173
+ bedLeveling: flag(args?.bed_leveling),
174
+ flowCalibration: flag(args?.flow_calibration),
175
+ vibrationCalibration: flag(args?.vibration_calibration),
176
+ layerInspect: flag(args?.layer_inspect),
177
+ autoBedLeveling: int(args?.auto_bed_leveling, "auto_bed_leveling"),
178
+ autoFlowCali: int(args?.auto_flow_cali, "auto_flow_cali"),
179
+ autoOffsetCali: int(args?.auto_offset_cali, "auto_offset_cali"),
180
+ extruderCaliManualMode: int(args?.extruder_cali_manual_mode, "extruder_cali_manual_mode"),
181
+ };
182
+ return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined)) as CallerPrintOptions;
183
+ }
161
184
  type BambuModel = typeof VALID_BAMBU_MODELS[number];
162
185
  // X2D uses the same project_file/ams_mapping2 family of LAN print fields as
163
186
  // the dual-nozzle H2 path. Keep it in this gate so pre-sliced multi-filament
@@ -1646,6 +1669,8 @@ class BambuPrinterMCPServer {
1646
1669
  return withPrinterOperation(devIp, devId, assertActive => withPrintSnapshot(threeMFPath, async (snapshot, retainForDispatchedUpload) => {
1647
1670
  const inspection = await inspectPrintFile(snapshot, { model: printModel, nozzleDiameters: printNozzles, plateIndex, bedType: printBedType });
1648
1671
  const resumeFile = await checkedFile(inspection, snapshot);
1672
+ // The options Bambu Studio's Send dialog would send; explicit ones win.
1673
+ const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1649
1674
  let mapping = finalAmsMapping?.slice();
1650
1675
  if (finalAmsSlots) {
1651
1676
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length) throw new Error("ams_slots must supply exactly one physical tray per used filament.");
@@ -1709,18 +1734,18 @@ class BambuPrinterMCPServer {
1709
1734
  use_ssl_for_mqtt: args?.use_ssl_for_mqtt !== undefined ? Boolean(args.use_ssl_for_mqtt) : true,
1710
1735
  username: String(args?.username || "bblp"),
1711
1736
  password,
1712
- task_bed_leveling: args?.bed_leveling !== undefined ? Boolean(args.bed_leveling) : true,
1713
- task_flow_cali: args?.flow_calibration !== undefined ? Boolean(args.flow_calibration) : true,
1714
- task_vibration_cali: args?.vibration_calibration !== undefined ? Boolean(args.vibration_calibration) : true,
1715
- task_layer_inspect: args?.layer_inspect !== undefined ? Boolean(args.layer_inspect) : false,
1737
+ task_bed_leveling: studio.task_bed_leveling,
1738
+ task_flow_cali: studio.task_flow_cali,
1739
+ task_vibration_cali: studio.task_vibration_cali,
1740
+ task_layer_inspect: studio.task_layer_inspect,
1716
1741
  task_record_timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : false,
1717
1742
  task_use_ams: useAMS,
1718
1743
  task_bed_type: printBedType,
1719
1744
  extra_options: stringifyBridgeJson(args?.extra_options) || "",
1720
- auto_bed_leveling: args?.auto_bed_leveling !== undefined ? Number(args.auto_bed_leveling) : 0,
1721
- auto_flow_cali: args?.auto_flow_cali !== undefined ? Number(args.auto_flow_cali) : 0,
1722
- auto_offset_cali: args?.auto_offset_cali !== undefined ? Number(args.auto_offset_cali) : 0,
1723
- extruder_cali_manual_mode: args?.extruder_cali_manual_mode !== undefined ? Number(args.extruder_cali_manual_mode) : -1,
1745
+ auto_bed_leveling: studio.auto_bed_leveling,
1746
+ auto_flow_cali: studio.auto_flow_cali,
1747
+ auto_offset_cali: studio.auto_offset_cali,
1748
+ extruder_cali_manual_mode: studio.extruder_cali_manual_mode,
1724
1749
  task_ext_change_assist: args?.external_change_assist !== undefined ? Boolean(args.external_change_assist) : false,
1725
1750
  try_emmc_print: args?.try_emmc_print !== undefined ? Boolean(args.try_emmc_print) : false,
1726
1751
  };
@@ -1743,6 +1768,10 @@ class BambuPrinterMCPServer {
1743
1768
  flowCalibration: params.task_flow_cali as boolean,
1744
1769
  vibrationCalibration: params.task_vibration_cali as boolean,
1745
1770
  layerInspect: params.task_layer_inspect as boolean,
1771
+ autoBedLeveling: studio.auto_bed_leveling,
1772
+ autoFlowCali: studio.auto_flow_cali,
1773
+ autoOffsetCali: studio.auto_offset_cali,
1774
+ extruderCaliManualMode: studio.extruder_cali_manual_mode,
1746
1775
  timelapse: params.task_record_timelapse as boolean,
1747
1776
  externalStorage,
1748
1777
  }, native.onUpdate, { signal: native.signal, assertActive, beforeDispatch: async () => {
@@ -2680,10 +2709,10 @@ class BambuPrinterMCPServer {
2680
2709
  ams_mapping_info: { type: "string", description: "Raw JSON string for FULU PrintParams ams_mapping_info, matching OrcaSlicer-bambulab's detailed AMS mapping field." },
2681
2710
  nozzle_mapping: { type: "string", description: "Raw JSON string for FULU PrintParams nozzle_mapping." },
2682
2711
  nozzles_info: { type: "string", description: "Raw JSON string for FULU PrintParams nozzles_info." },
2683
- bed_leveling: { type: "boolean", description: "Enable auto bed leveling in FULU PrintParams (default: true)." },
2684
- flow_calibration: { type: "boolean", description: "Enable flow calibration in FULU PrintParams (default: true)." },
2685
- vibration_calibration: { type: "boolean", description: "Enable vibration calibration in FULU PrintParams (default: true)." },
2686
- layer_inspect: { type: "boolean", description: "Enable first-layer inspection where supported (default: false for BambuNetwork bridge)." },
2712
+ bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
2713
+ flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
2714
+ vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
2715
+ layer_inspect: { type: "boolean", description: "First-layer inspection where supported (default true, as Bambu Studio sends)." },
2687
2716
  timelapse: { type: "boolean", description: "Enable timelapse recording in FULU PrintParams (default: false)." },
2688
2717
  use_ssl_for_ftp: { type: "boolean", description: "Whether FULU local print should use SSL for FTP (default: true)." },
2689
2718
  use_ssl_for_mqtt: { type: "boolean", description: "Whether FULU local print should use SSL for MQTT (default: true)." },
@@ -3115,9 +3144,9 @@ class BambuPrinterMCPServer {
3115
3144
  type: "boolean",
3116
3145
  description: "When true, match the sliced 3MF's tray_info_idx requirements against live AMS inventory and use the resulting ams_slots. Ignored when ams_mapping or ams_slots is provided."
3117
3146
  },
3118
- bed_leveling: { type: "boolean", description: "Enable auto bed leveling (default: true)" },
3119
- flow_calibration: { type: "boolean", description: "Enable flow calibration (default: true)" },
3120
- vibration_calibration: { type: "boolean", description: "Enable vibration calibration (default: true)" },
3147
+ bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
3148
+ flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
3149
+ vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
3121
3150
  timelapse: { type: "boolean", description: "Enable timelapse recording (default: false)" },
3122
3151
  slicer_profile: { type: "string", description: "Path to the slicer profile/config file for auto-slicing (optional)." },
3123
3152
  template_3mf_path: { type: "string", description: "Optional template 3MF whose embedded Bambu slicer settings should be reused when auto-slicing this print job." },
@@ -3151,9 +3180,9 @@ class BambuPrinterMCPServer {
3151
3180
  enum: ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"],
3152
3181
  description: "Bed plate type currently installed (default: textured_plate)"
3153
3182
  },
3154
- bed_leveling: { type: "boolean", description: "Enable auto bed leveling (default: true)" },
3155
- flow_calibration: { type: "boolean", description: "Enable flow calibration (default: true)" },
3156
- vibration_calibration: { type: "boolean", description: "Enable vibration calibration (default: true)" },
3183
+ bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
3184
+ flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
3185
+ vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
3157
3186
  timelapse: { type: "boolean", description: "Enable timelapse recording (default: false)" },
3158
3187
  slicer_profile: { type: "string", description: "Path to the slicer profile/config file for auto-slicing (optional)." },
3159
3188
  nozzle_diameter: { type: "string", description: "Nozzle diameter in mm for auto-slicing (default: 0.4)" }
@@ -4459,10 +4488,7 @@ class BambuPrinterMCPServer {
4459
4488
  amsMapping: finalAmsMapping,
4460
4489
  amsSlots: finalAmsSlots,
4461
4490
  bedType: printBedType,
4462
- bedLeveling: args?.bed_leveling !== undefined ? Boolean(args.bed_leveling) : undefined,
4463
- flowCalibration: args?.flow_calibration !== undefined ? Boolean(args.flow_calibration) : undefined,
4464
- vibrationCalibration: args?.vibration_calibration !== undefined ? Boolean(args.vibration_calibration) : undefined,
4465
- layerInspect: args?.layer_inspect !== undefined ? Boolean(args.layer_inspect) : undefined,
4491
+ ...callerPrintOptions(args),
4466
4492
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : undefined,
4467
4493
  });
4468
4494
  // Report what the printer did, not merely that a command was published.
@@ -4527,9 +4553,7 @@ class BambuPrinterMCPServer {
4527
4553
  useAMS: true,
4528
4554
  amsSlots: collarAnalysis.amsSlots,
4529
4555
  bedType: printBedType,
4530
- bedLeveling: args?.bed_leveling !== undefined ? Boolean(args.bed_leveling) : true,
4531
- flowCalibration: args?.flow_calibration !== undefined ? Boolean(args.flow_calibration) : true,
4532
- vibrationCalibration: args?.vibration_calibration !== undefined ? Boolean(args.vibration_calibration) : true,
4556
+ ...callerPrintOptions(args),
4533
4557
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : false,
4534
4558
  });
4535
4559
 
@@ -12,6 +12,7 @@ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, d
12
12
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements, type PrinterStateRequirements } from "../safety/printer-state.js";
13
13
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
14
14
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
15
+ import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
15
16
  import { Client as FTPClient } from "basic-ftp";
16
17
  import * as mqtt from "mqtt";
17
18
  import {
@@ -46,6 +47,35 @@ function loadClientCreds(): { cert: Buffer; key: Buffer } | null {
46
47
  const CLIENT_CREDS = loadClientCreds();
47
48
 
48
49
  const COMMAND_SETTLE_MS = 300;
50
+ /** How long a stop waits for the printer's MQTT PUBACK before its client is closed (BAMBU_STOP_ACK_MS for tests). */
51
+ const stopAckMs = () => { const value = Number(process.env.BAMBU_STOP_ACK_MS); return Number.isInteger(value) && value > 0 ? value : 10_000; };
52
+
53
+ /**
54
+ * Publish JSON exactly as Bambu Studio's MachineObject::publish_json does
55
+ * (DeviceManager.cpp:2462): the given message on device/<serial>/request at the
56
+ * given QoS. With QoS 1 it resolves on the printer's PUBACK. bambu-node's own
57
+ * publish has no QoS (MQTT.js defaults to 0).
58
+ */
59
+ function publishStudioJson(client: BambuClient, message: Record<string, any>, qos: 0 | 1): Promise<void> {
60
+ const mqttClient = (client as any).mqttClient;
61
+ const serial = (client as any).config?.serialNumber;
62
+ if (!mqttClient || typeof mqttClient.publish !== "function" || typeof serial !== "string") return client.publish(message);
63
+ return new Promise((resolve, reject) => {
64
+ mqttClient.publish(`device/${serial}/request`, JSON.stringify(message), { qos }, (error?: Error) => {
65
+ if (error) reject(new Error(`Error publishing to device/${serial}/request: ${error.message}`));
66
+ else resolve();
67
+ });
68
+ });
69
+ }
70
+
71
+ /**
72
+ * 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.
75
+ */
76
+ const studioStopCommand = {
77
+ invoke: (client: BambuClient) => publishStudioJson(client, { print: { command: "stop", param: "", sequence_id: String(Date.now()) } }, 1),
78
+ };
49
79
  /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
50
80
  const STALE_REPORT_MS = 300_000;
51
81
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
@@ -114,6 +144,11 @@ interface BambuPrintOptionsInternal {
114
144
  flowCalibration?: boolean;
115
145
  vibrationCalibration?: boolean;
116
146
  layerInspect?: boolean;
147
+ /** Explicit Studio option values (0 off, 1 on, 2 auto); see studio-print-options.ts. */
148
+ autoBedLeveling?: number;
149
+ autoFlowCali?: number;
150
+ autoOffsetCali?: number;
151
+ extruderCaliManualMode?: number;
117
152
  timelapse?: boolean;
118
153
  amsMapping?: number[];
119
154
  /**
@@ -988,6 +1023,13 @@ export class BambuImplementation {
988
1023
  model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
989
1024
  });
990
1025
  const resumeFile = await checkedFile(inspection, options.filePath);
1026
+ // The options Bambu Studio's Send dialog would send; explicit ones win.
1027
+ const studio = resolveStudioPrintOptions(model, {
1028
+ bedLeveling: options.bedLeveling, flowCalibration: options.flowCalibration,
1029
+ vibrationCalibration: options.vibrationCalibration, layerInspect: options.layerInspect,
1030
+ autoBedLeveling: options.autoBedLeveling, autoFlowCali: options.autoFlowCali,
1031
+ autoOffsetCali: options.autoOffsetCali, extruderCaliManualMode: options.extruderCaliManualMode,
1032
+ } satisfies CallerPrintOptions, { usedNozzles: usedNozzleCount(inspection) });
991
1033
  const projectMetadata = await this.resolveProjectFileMetadata(
992
1034
  options.filePath,
993
1035
  options.plateIndex,
@@ -1160,16 +1202,21 @@ export class BambuImplementation {
1160
1202
  md5,
1161
1203
  bed_type: options.bedType || "auto",
1162
1204
  timelapse: b(options.timelapse),
1163
- bed_leveling: b(options.bedLeveling ?? true),
1164
- auto_bed_leveling: 1,
1165
- flow_cali: b(options.flowCalibration ?? false),
1166
- vibration_cali: b(options.vibrationCalibration ?? true),
1167
- layer_inspect: b(options.layerInspect ?? false),
1205
+ bed_leveling: b(studio.task_bed_leveling),
1206
+ auto_bed_leveling: studio.auto_bed_leveling,
1207
+ // No verified project_file field requests automatic flow calibration
1208
+ // (Studio's PrintParams auto_flow_cali reaches the printer through the
1209
+ // plug-in, whose MQTT form is not public), so "auto" sends 0 as before,
1210
+ // and extrude_cali_flag keeps its existing 0. The bridge and native
1211
+ // routes carry auto_flow_cali.
1212
+ flow_cali: b(studio.task_flow_cali),
1213
+ vibration_cali: b(studio.task_vibration_cali),
1214
+ layer_inspect: b(studio.task_layer_inspect),
1168
1215
  use_ams: options.useAMS !== false,
1169
1216
  cfg: "0",
1170
1217
  extrude_cali_flag: 0,
1171
- extrude_cali_manual_mode: 0,
1172
- nozzle_offset_cali: 2,
1218
+ extrude_cali_manual_mode: studio.extruder_cali_manual_mode,
1219
+ nozzle_offset_cali: studio.auto_offset_cali,
1173
1220
  subtask_name: subtaskName,
1174
1221
  profile_id: "0",
1175
1222
  project_id: submissionId,
@@ -1187,10 +1234,10 @@ export class BambuImplementation {
1187
1234
  url: projectUrl,
1188
1235
  subtask_name: subtaskName,
1189
1236
  md5,
1190
- flow_cali: options.flowCalibration ?? true,
1191
- layer_inspect: options.layerInspect ?? true,
1192
- vibration_cali: options.vibrationCalibration ?? true,
1193
- bed_leveling: options.bedLeveling ?? true,
1237
+ flow_cali: studio.task_flow_cali,
1238
+ layer_inspect: studio.task_layer_inspect,
1239
+ vibration_cali: studio.task_vibration_cali,
1240
+ bed_leveling: studio.task_bed_leveling,
1194
1241
  bed_type: options.bedType || "textured_plate",
1195
1242
  timelapse: options.timelapse ?? false,
1196
1243
  use_ams: options.useAMS !== false,
@@ -1234,9 +1281,17 @@ export class BambuImplementation {
1234
1281
 
1235
1282
  try {
1236
1283
  if (dispatch) return await dispatch();
1237
- else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "stop" }));
1284
+ // A stop with no PUBACK must not stay queued in MQTT.js and reach a later job.
1285
+ const ackMs = stopAckMs();
1286
+ const deadline = new AbortController();
1287
+ const timer = setTimeout(() => deadline.abort(Object.assign(new Error("stop not acknowledged"), { name: "TimeoutError" })), ackMs);
1288
+ try { await this.invokeEmergencyCommand(printer!, studioStopCommand, deadline.signal); }
1289
+ catch (error) {
1290
+ 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
+ throw error;
1292
+ } finally { clearTimeout(timer); }
1238
1293
  this.checkedJobs.delete(`${host}\n${serial}`);
1239
- return { status: "success", message: "Cancel command sent successfully." };
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." };
1240
1295
  } catch (error) {
1241
1296
  throw new Error(`Failed to cancel print: ${(error as Error).message}`);
1242
1297
  }
@@ -1275,8 +1330,8 @@ export class BambuImplementation {
1275
1330
  signal?.throwIfAborted();
1276
1331
  const printer = await this.getPrinter(host, serial, token);
1277
1332
  signal?.throwIfAborted();
1278
- await this.invokeEmergencyCommand(printer, new UpdateStateCommand({ state: "stop" }), signal);
1279
- return { status: "success", message: "Cancel command sent over MQTT." };
1333
+ await this.invokeEmergencyCommand(printer, studioStopCommand, signal);
1334
+ return { status: "success", message: "Stop sent over MQTT and acknowledged by the printer (QoS 1)." };
1280
1335
  }
1281
1336
 
1282
1337
  /** Raw MQTT heater-off; switching off needs no material or model declaration. */
@@ -1404,7 +1459,7 @@ export class BambuImplementation {
1404
1459
  ]);
1405
1460
  const confirmedJob = jobIdentity(initialStatus.raw);
1406
1461
  const jobName = initialStatus.raw.subtask_name || initialStatus.raw.gcode_file;
1407
- await this.confirmHardwareAction(`Clear reported hardware errors on ${serial}: ${codes.map(describeHmsKey).join(", ")}?${jobName ? ` Current job: ${String(jobName)}.` : ""} Inspect the printer and resolve the physical cause first. Confirm only after removing obstructions and correcting the fault.`, true);
1462
+ await this.confirmHardwareAction(`Clear reported hardware errors on ${serial}: ${codes.map(describeHmsKey).join(", ")}?${jobName ? ` Current job: ${String(jobName)}.` : ""} Inspect the printer and resolve the physical cause first. Confirm only after correcting the fault.`, true);
1408
1463
  const beforeDispatch = async () => {
1409
1464
  assertActive();
1410
1465
  const currentStatus = await this.getSafetyStatus(host, serial, token);