bambu-printer-mcp 1.1.71 → 1.1.73

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,325 @@
1
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
2
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
3
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
4
+ const MAX_FILAMENT = 64;
5
+ const words = (value) => value
6
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]))
7
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
8
+ const metadataOf = (block) => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
9
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
10
+ export function readModelObjects(settings) {
11
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
12
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
13
+ const own = metadataOf(part[2]);
14
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
15
+ });
16
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
17
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
18
+ });
19
+ }
20
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
21
+ function intOf(value) {
22
+ const first = Array.isArray(value) ? value[0] : value;
23
+ if (typeof first === "number" && Number.isInteger(first))
24
+ return first;
25
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first))
26
+ return undefined;
27
+ return Number(first);
28
+ }
29
+ function boolOf(value) {
30
+ const first = Array.isArray(value) ? value[0] : value;
31
+ if (typeof first === "boolean")
32
+ return first;
33
+ if (typeof first !== "string")
34
+ return undefined;
35
+ if (/^(?:1|true)$/i.test(first.trim()))
36
+ return true;
37
+ if (/^(?:0|false)$/i.test(first.trim()))
38
+ return false;
39
+ return undefined;
40
+ }
41
+ /**
42
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
43
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
44
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
45
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
46
+ */
47
+ export function paintedStates(paint) {
48
+ const nibbles = [];
49
+ for (let i = paint.length - 1; i >= 0; i--) {
50
+ const digit = Number.parseInt(paint[i], 16);
51
+ if (Number.isNaN(digit))
52
+ return [];
53
+ nibbles.push(digit);
54
+ }
55
+ const states = [];
56
+ let at = 0, pending = 1;
57
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
58
+ while (pending > 0) {
59
+ const code = next();
60
+ if (code === undefined)
61
+ break;
62
+ pending -= 1;
63
+ const sides = code & 0b11;
64
+ if (sides) {
65
+ pending += sides + 1;
66
+ continue;
67
+ }
68
+ if ((code & 0b1100) === 0b1100) {
69
+ let more = 0, value = next();
70
+ while (value === 0b1111) {
71
+ more += 1;
72
+ value = next();
73
+ }
74
+ if (value === undefined)
75
+ break;
76
+ states.push(value + 15 * more + 3);
77
+ }
78
+ else
79
+ states.push(code >> 2);
80
+ }
81
+ return states;
82
+ }
83
+ /**
84
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
85
+ */
86
+ async function readPainting(zip, paths) {
87
+ const result = new Map();
88
+ let total = 0;
89
+ for (const path of paths) {
90
+ const file = zip.file(path);
91
+ if (!file)
92
+ continue;
93
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
94
+ const size = file._data?.uncompressedSize;
95
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL))
96
+ continue;
97
+ const bytes = await file.async("nodebuffer");
98
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL)
99
+ continue;
100
+ if (!bytes.includes("paint_color=\""))
101
+ continue;
102
+ const text = bytes.toString("utf8");
103
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
104
+ const paint = { states: new Set(), ownFilament: false };
105
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
106
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
107
+ if (!value) {
108
+ paint.ownFilament = true;
109
+ continue;
110
+ }
111
+ for (const state of paintedStates(value)) {
112
+ if (state === 0)
113
+ paint.ownFilament = true;
114
+ else
115
+ paint.states.add(state);
116
+ }
117
+ }
118
+ result.set(`${path}#${object[1]}`, paint);
119
+ }
120
+ }
121
+ return result;
122
+ }
123
+ function projectFilaments(config) {
124
+ const list = (key) => Array.isArray(config[key]) ? config[key].map(String) : [];
125
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
126
+ }
127
+ function describe(index, project, name) {
128
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
129
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
130
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
131
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
132
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
133
+ }
134
+ /**
135
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
136
+ * 3D/3dmodel.model text.
137
+ */
138
+ export async function plateFilaments(zip, settings, model, plates) {
139
+ const text = async (name) => {
140
+ const file = zip.file(name);
141
+ if (!file)
142
+ return "";
143
+ const bytes = await file.async("nodebuffer");
144
+ if (bytes.length > MAX_TEXT_BYTES)
145
+ throw new Error(`${name} is too large to read.`);
146
+ return bytes.toString("utf8");
147
+ };
148
+ let config = {};
149
+ try {
150
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}");
151
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
152
+ config = parsed;
153
+ }
154
+ catch { /* a project without readable settings declares no filaments */ }
155
+ const project = projectFilaments(config);
156
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
157
+ const valid = (index) => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
158
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
159
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
160
+ const components = new Map();
161
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
162
+ const parts = new Map();
163
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
164
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
165
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
166
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
167
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
168
+ if (id)
169
+ parts.set(id, path || "3D/3dmodel.model");
170
+ }
171
+ if (parts.size)
172
+ components.set(object[1], parts);
173
+ }
174
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
175
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
176
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
177
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
178
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
179
+ // isn't printable (PartPlate.cpp:1311-1322).
180
+ const printableItems = new Map();
181
+ for (const item of buildItems) {
182
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
183
+ if (id)
184
+ printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
185
+ }
186
+ const printableCopy = (objectId, instanceId) => {
187
+ const flags = printableItems.get(objectId);
188
+ if (!flags)
189
+ return true;
190
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
191
+ };
192
+ const rangeExtruders = new Map();
193
+ const ranges = await text("Metadata/layer_config_ranges.xml");
194
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
195
+ const objectId = order[Number(object[1]) - 1];
196
+ if (!objectId)
197
+ continue;
198
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
199
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
200
+ rangeExtruders.set(objectId, [...object[2].matchAll(/<option\s+opt_key="(?:extruder|wall_filament|sparse_infill_filament|solid_infill_filament)"\s*>\s*(\d+)\s*<\/option>/g)].map(match => Number(match[1])).filter(id => id > 0));
201
+ }
202
+ const toolChanges = new Map();
203
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
204
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
205
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
206
+ if (!Number.isInteger(id))
207
+ continue;
208
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
209
+ .filter(layer => /\btype="2"/.test(layer[1]))
210
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
211
+ }
212
+ // Painting only matters for parts on a plate that is not sliced yet.
213
+ const paintPaths = new Set();
214
+ for (const plate of plates)
215
+ if (!plate.slicedFilamentIds)
216
+ for (const objectId of plate.objectIds)
217
+ for (const path of components.get(objectId)?.values() ?? [])
218
+ paintPaths.add(path);
219
+ const painting = await readPainting(zip, paintPaths);
220
+ const global = (key) => intOf(config[key]) ?? 0;
221
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"];
222
+ const result = new Map();
223
+ for (const plate of plates) {
224
+ const used = new Map();
225
+ const add = (index, name) => {
226
+ if (!valid(index))
227
+ return;
228
+ if (!used.has(index) || (!used.get(index) && name))
229
+ used.set(index, name || undefined);
230
+ };
231
+ // An object counts once on a plate when any of its copies there prints.
232
+ const printing = plate.instances?.length
233
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
234
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
235
+ for (const objectId of printing) {
236
+ const object = objects.get(objectId);
237
+ if (!object)
238
+ continue;
239
+ const objectInt = (key) => intOf(object.settings.get(key));
240
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() }];
241
+ for (const part of parts) {
242
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype))
243
+ continue;
244
+ const partInt = (key) => intOf(part.settings.get(key));
245
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
246
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
247
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
248
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
249
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
250
+ const label = part.name || object.name;
251
+ const path = components.get(objectId)?.get(part.id);
252
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
253
+ for (const state of paint?.states ?? [])
254
+ if (part.subtype === "normal_part")
255
+ add(state, label);
256
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
257
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
258
+ if (extruderSet)
259
+ add(ownExtruder, label);
260
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
261
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
262
+ else
263
+ for (const key of FEATURES)
264
+ add(global(key) > 0 ? global(key) : 1, label);
265
+ }
266
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
267
+ const own = partInt(key);
268
+ if (own !== undefined) {
269
+ if (own > 0)
270
+ add(own, label);
271
+ }
272
+ else if ((objectInt(key) ?? 0) > 0)
273
+ add(objectInt(key), label);
274
+ }
275
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
276
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
277
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
278
+ }
279
+ for (const extruder of rangeExtruders.get(objectId) ?? [])
280
+ add(extruder, object.name);
281
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
282
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
283
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
284
+ const setting = (key) => object.settings.has(key) ? object.settings.get(key) : config[key];
285
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
286
+ if (support) {
287
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
288
+ add(intOf(setting("support_interface_filament")) || undefined);
289
+ add(intOf(setting("support_filament")) || undefined);
290
+ }
291
+ }
292
+ for (const extruder of toolChanges.get(plate.number) ?? [])
293
+ add(extruder);
294
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
295
+ // else filament 1 (ModelVolume::extruder_id's default).
296
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
297
+ for (const key of FEATURES)
298
+ add(global(key) > 0 ? global(key) : 1);
299
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
300
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
301
+ const mixed = Array.isArray(config.filament_is_mixed) ? config.filament_is_mixed.map(value => boolOf(value) === true) : [];
302
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? config.filament_mixed_components.map(String) : [];
303
+ if (mixed.some(Boolean))
304
+ for (const [index, name] of [...used]) {
305
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length)
306
+ continue;
307
+ used.delete(index);
308
+ for (const part of mixedComponents[index - 1].split(",")) {
309
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
310
+ if (component >= 1)
311
+ add(component, name);
312
+ }
313
+ }
314
+ if (plate.slicedFilamentIds) {
315
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
316
+ const names = new Map(used);
317
+ used.clear();
318
+ for (const id of plate.slicedFilamentIds)
319
+ add(id + 1, names.get(id + 1));
320
+ }
321
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
322
+ }
323
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
324
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
325
+ }
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
30
30
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
31
31
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
32
32
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake } from "./design-app-setup.js";
33
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
33
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
34
34
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
35
35
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
36
36
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
@@ -225,7 +225,7 @@ function resolveNozzleVolumeType(value) {
225
225
  }
226
226
  return NOZZLE_VOLUME_TYPES[normalized];
227
227
  }
228
- const VALID_BAMBUSTUDIO_CLI_BED_TYPES = ["textured_plate", "cool_plate", "engineering_plate", "hot_plate"];
228
+ const VALID_BAMBUSTUDIO_CLI_BED_TYPES = ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"];
229
229
  // Map model IDs to BambuStudio --load-machine preset names
230
230
  const BAMBU_MODEL_PRESETS = {
231
231
  p1s: (n) => `Bambu Lab P1S ${n} nozzle`,
@@ -653,7 +653,7 @@ function resolveBedType(argsBedType) {
653
653
  function resolveBambuStudioCliBedType(argsBedType) {
654
654
  const bedType = resolveBedType(argsBedType);
655
655
  if (!VALID_BAMBUSTUDIO_CLI_BED_TYPES.includes(bedType)) {
656
- throw new Error(`BambuStudio CLI bed_type "${bedType}" is not verified. Use a pre-sliced 3MF for SuperTack, or choose one of: ${VALID_BAMBUSTUDIO_CLI_BED_TYPES.join(", ")}`);
656
+ throw new Error(`BambuStudio CLI bed_type "${bedType}" is not one of: ${VALID_BAMBUSTUDIO_CLI_BED_TYPES.join(", ")}`);
657
657
  }
658
658
  return bedType;
659
659
  }
@@ -1292,9 +1292,6 @@ class BambuPrinterMCPServer {
1292
1292
  return { threeMFPath, autoSliced: false };
1293
1293
  }
1294
1294
  assertUniformCliNozzles(args);
1295
- if (bedType === "supertack_plate") {
1296
- throw new Error('BambuStudio CLI SuperTack bed type is not verified; use a pre-sliced 3MF for SuperTack or choose textured_plate, cool_plate, engineering_plate, or hot_plate.');
1297
- }
1298
1295
  console.error(`3MF has no gcode - auto-slicing with ${slicerType} for ${printModel}`);
1299
1296
  const autoSliceOptions = {
1300
1297
  ...(slicerType === "orca-slicer-api" ? {} : {
@@ -1432,7 +1429,8 @@ class BambuPrinterMCPServer {
1432
1429
  const resumeFile = await checkedFile(inspection, snapshot);
1433
1430
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1434
1431
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1435
- let mapping = finalAmsMapping?.slice();
1432
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1433
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1436
1434
  if (finalAmsSlots) {
1437
1435
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length)
1438
1436
  throw new Error("ams_slots must supply exactly one physical tray per used filament.");
@@ -1771,9 +1769,6 @@ class BambuPrinterMCPServer {
1771
1769
  throw new Error(`Failed to inspect collar charm 3MF before slicing: ${error.message}`);
1772
1770
  }
1773
1771
  const printPreset = BAMBU_MODEL_PRESETS[printModel]?.(printNozzle);
1774
- if (bedType === "supertack_plate") {
1775
- throw new Error('BambuStudio CLI SuperTack bed type is not verified; use a pre-sliced 3MF for SuperTack or choose textured_plate, cool_plate, engineering_plate, or hot_plate.');
1776
- }
1777
1772
  const autoSliceOptions = {
1778
1773
  ...(slicerType === "orca-slicer-api" ? {} : {
1779
1774
  uptodate: true, ensureOnBed: true, minSave: true, skipModifiedGcodes: true,
@@ -2063,7 +2058,7 @@ class BambuPrinterMCPServer {
2063
2058
  },
2064
2059
  {
2065
2060
  name: "list_3mf_plates",
2066
- description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2061
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2067
2062
  inputSchema: {
2068
2063
  type: "object",
2069
2064
  properties: {
@@ -2075,7 +2070,7 @@ class BambuPrinterMCPServer {
2075
2070
  },
2076
2071
  {
2077
2072
  name: "list_3mf_plate_objects",
2078
- description: "List object IDs from a sliced 3MF plate. Use these IDs with skip_objects during a running print.",
2073
+ description: "List the objects of a sliced 3MF plate that the printer can skip, one per copy, as Bambu Studio's skip dialog lists them: identify_id (id), name, whether it is already skipped, and labelObjectEnabled (the plate was sliced with object labels, which skipping needs). Use these ids with skip_objects during a running print.",
2079
2074
  inputSchema: {
2080
2075
  type: "object",
2081
2076
  properties: {
@@ -2226,7 +2221,7 @@ class BambuPrinterMCPServer {
2226
2221
  bed_type: {
2227
2222
  type: "string",
2228
2223
  enum: ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"],
2229
- description: "Bed plate type for slicing (default: textured_plate). SuperTack is accepted only for pre-sliced print jobs until the BambuStudio CLI identifier is verified."
2224
+ description: "Bed plate type for slicing (default: textured_plate)."
2230
2225
  },
2231
2226
  nozzle_type: {
2232
2227
  type: "string",
@@ -2287,7 +2282,7 @@ class BambuPrinterMCPServer {
2287
2282
  bed_type: {
2288
2283
  type: "string",
2289
2284
  enum: ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"],
2290
- description: "Bed plate type for slicing (default: textured_plate). SuperTack is accepted only for pre-sliced print jobs until the BambuStudio CLI identifier is verified."
2285
+ description: "Bed plate type for slicing (default: textured_plate)."
2291
2286
  },
2292
2287
  nozzle_type: {
2293
2288
  type: "string",
@@ -2306,7 +2301,7 @@ class BambuPrinterMCPServer {
2306
2301
  arrange: { type: "boolean", description: "Auto-arrange all objects on the build plate with optimal spacing; STL input is arranged by default. Set false only to keep a 3MF's existing layout: an STL that is not already on the plate then fails to slice." },
2307
2302
  ensure_on_bed: { type: "boolean", description: "Detect models floating above the bed and lower them onto the build surface. Safety net for imported models with incorrect Z origins." },
2308
2303
  clone_objects: { type: "string", description: "Clone the loaded model: total copies as a single integer, e.g. '3'. The Bambu-style CLIs count copies per input file and this tool loads one file, so a comma-separated list is rejected by the slicer." },
2309
- skip_objects: { type: "string", description: "Skip specific objects during slicing by index. Comma-separated, e.g. '3,5,10'. Useful for multi-object 3MFs where you only want to print some parts." },
2304
+ skip_objects: { type: "string", description: "Skip these object copies when slicing, by identify_id, comma-separated (e.g. '78,92'). The ids are the instances list_3mf_plates gives for each plate; they are not positions. Useful for multi-object 3MFs where you only want to print some parts." },
2310
2305
  load_filaments: { type: "string", description: "Override filament profiles. Semicolon-separated paths to filament JSON configs, e.g. 'pla_basic.json;petg_cf.json'." },
2311
2306
  filament_profile: { type: "string", description: "Compatibility alias for load_filaments. Semicolon-separated Orca/Bambu filament profile JSON paths." },
2312
2307
  load_filament_ids: { type: "string", description: "Map filaments to objects/parts. Comma-separated IDs matching load_filaments order, e.g. '1,2,3,1' assigns filament 1 to objects 0 and 3." },
@@ -2764,7 +2759,7 @@ class BambuPrinterMCPServer {
2764
2759
  properties: {
2765
2760
  object_ids: {
2766
2761
  type: "array",
2767
- description: "Object IDs to skip. Use list_3mf_plate_objects on the sliced 3MF to find IDs.",
2762
+ description: "identify_id values of the object copies to skip. Use list_3mf_plate_objects on the sliced 3MF to find them.",
2768
2763
  items: { type: "number" }
2769
2764
  },
2770
2765
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
@@ -2868,7 +2863,7 @@ class BambuPrinterMCPServer {
2868
2863
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
2869
2864
  ams_mapping: {
2870
2865
  type: "array",
2871
- description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
2866
+ description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray. Positions the selected plate does not print are sent as -1, as Bambu Studio sends them, whatever is passed there (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
2872
2867
  items: { type: "number" }
2873
2868
  },
2874
2869
  ams_slots: {
@@ -4089,9 +4084,6 @@ class BambuPrinterMCPServer {
4089
4084
  }
4090
4085
  if (!hasGcode) {
4091
4086
  assertUniformCliNozzles(args);
4092
- if (printBedType === "supertack_plate") {
4093
- throw new Error('BambuStudio CLI SuperTack bed type is not verified; use a pre-sliced 3MF for SuperTack or choose textured_plate, cool_plate, engineering_plate, or hot_plate.');
4094
- }
4095
4087
  console.error(`3MF has no gcode — auto-slicing with ${slicerType} for ${printModel}`);
4096
4088
  const autoSliceOptions = {
4097
4089
  ...(slicerType === "orca-slicer-api" ? { slicePlate: plateIndex + 1 } : {
@@ -4100,7 +4092,8 @@ class BambuPrinterMCPServer {
4100
4092
  bedType: printBedType,
4101
4093
  nozzleType: resolveNozzleType(args?.nozzle_type),
4102
4094
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
4103
- ...(pauseLayers ? { pauseAtLayers: pauseLayers } : {}),
4095
+ // A pause belongs to the plate being printed; the CLI carries custom G-code for one plate only.
4096
+ ...(pauseLayers ? { pauseAtLayers: pauseLayers, slicePlate: plateIndex + 1 } : {}),
4104
4097
  };
4105
4098
  if (!explicitSlicerProfile) {
4106
4099
  try {
@@ -14,7 +14,7 @@ import { Readable } from "node:stream";
14
14
  import { readSafe3mfArchive } from "../safety/archive.js";
15
15
  import { inspectPrintFile } from "../safety/print-file.js";
16
16
  import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safety/limits.js";
17
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
17
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange, studioAmsMapping } from "../ams-mapping.js";
18
18
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements } from "../safety/printer-state.js";
19
19
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
20
20
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
@@ -1016,7 +1016,9 @@ export class BambuImplementation {
1016
1016
  if (options.amsMapping && options.amsMapping.length > 0) {
1017
1017
  for (const v of options.amsMapping)
1018
1018
  validateTrayValue(v, "ams_mapping");
1019
- baseMapping = options.amsMapping.slice();
1019
+ // Bambu Studio sends a tray only for the filaments the plate prints and -1 for every other project filament
1020
+ // (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500): so does this route.
1021
+ baseMapping = studioAmsMapping(options.amsMapping, inspection.usedFilamentPositions);
1020
1022
  }
1021
1023
  else if (options.amsSlots && options.amsSlots.length > 0) {
1022
1024
  for (const v of options.amsSlots)
@@ -11,17 +11,26 @@ function list(value) {
11
11
  return value.split(/[;,]/).map(s => s.trim().replace(/^"|"$/g, ''));
12
12
  return [];
13
13
  }
14
+ /**
15
+ * Every name a Bambu plate goes by, to the plate_N.json bed_type token Bambu Studio writes for it
16
+ * (02.08.02.61 PrintConfig.hpp:437-456 bed_type_to_gcode_string). project_settings and the G-code header
17
+ * carry curr_bed_type's enum key instead (PrintConfig.cpp:437-445); the GUI labels (:1307-1311) and this
18
+ * server's own bed_type values name the same plates. Other names (another slicer's plates) stay as written,
19
+ * so two copies of the same name still agree.
20
+ */
21
+ const BED_NAMES = {
22
+ cool_plate: ['cool plate'],
23
+ eng_plate: ['engineering plate'],
24
+ hot_plate: ['high temp plate', 'smooth pei plate', 'smooth pei plate / high temp plate', 'high temperature plate'],
25
+ textured_plate: ['textured pei plate'],
26
+ supertack_plate: ['supertack plate', 'bambu cool plate supertack', 'cool plate supertack'],
27
+ };
28
+ const BED_TOKENS = new Map(Object.entries(BED_NAMES).flatMap(([token, names]) => [token, ...names].map(name => [name.replace(/[_-]/g, ' '), token])));
14
29
  function normalizeBed(value) {
15
30
  if (typeof value !== 'string' || !value.trim())
16
31
  return undefined;
17
32
  const text = value.trim().toLowerCase().replace(/[_-]/g, ' ').replace(/\s+/g, ' ');
18
- if (['textured pei plate', 'textured plate'].includes(text))
19
- return 'textured pei plate';
20
- if (['supertack plate', 'cool plate supertack'].includes(text))
21
- return 'cool plate supertack';
22
- if (['smooth pei plate', 'high temp plate', 'high temperature plate', 'hot plate'].includes(text))
23
- return 'smooth pei plate';
24
- return text;
33
+ return BED_TOKENS.get(text) ?? text;
25
34
  }
26
35
  function metadataValues(metadata, keys) {
27
36
  return metadata.flatMap(data => keys.filter(key => data[key] !== undefined).map(key => data[key]));
@@ -376,8 +376,9 @@ function externalTray(raw, trayIndex, model) {
376
376
  return object(raw.vt_tray) ? raw.vt_tray : undefined;
377
377
  }
378
378
  function mappedTray(raw, index) {
379
- const unit = index >= 128 ? 128 : Math.floor(index / 4);
380
- const slot = index >= 128 ? index - 128 : index % 4;
379
+ // An AMS-HT tray index is the unit's own id, with its single slot 0 (Bambu Studio DevFilaSystem.cpp:367-368).
380
+ const unit = index >= 128 ? index : Math.floor(index / 4);
381
+ const slot = index >= 128 ? 0 : index % 4;
381
382
  const units = raw.ams?.ams;
382
383
  const ams = Array.isArray(units) ? units.find((value) => Number(value?.id) === unit) : undefined;
383
384
  const tray = Array.isArray(ams?.tray) ? ams.tray.find((value) => Number(value?.id) === slot) : undefined;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Every error code the Bambu Studio CLI can exit with, from libslic3r/Utils.hpp:21-75 of Bambu Studio
3
+ * 02.08.02.61 (OrcaSlicer's CLI shares them). The names and numbers are Studio's; the sentences are ours.
4
+ * The process exits with the code's low byte (-50 exits as 206). The CLI's own result.json, when present and
5
+ * fresh, is still the better reason; this table is for when it is missing or stale.
6
+ *
7
+ * tests/slicer/cli-exit-codes.test.mjs checks the names and numbers against Utils.hpp's list.
8
+ */
9
+ export declare const BAMBU_CLI_EXIT_CODES: Record<number, {
10
+ name: string;
11
+ sentence: string;
12
+ }>;
13
+ /** The table's entry for a process exit status (the code's low byte) or a full negative code. */
14
+ export declare function bambuCliExitCode(exitCode: unknown): {
15
+ code: number;
16
+ name: string;
17
+ sentence: string;
18
+ } | undefined;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Every error code the Bambu Studio CLI can exit with, from libslic3r/Utils.hpp:21-75 of Bambu Studio
3
+ * 02.08.02.61 (OrcaSlicer's CLI shares them). The names and numbers are Studio's; the sentences are ours.
4
+ * The process exits with the code's low byte (-50 exits as 206). The CLI's own result.json, when present and
5
+ * fresh, is still the better reason; this table is for when it is missing or stale.
6
+ *
7
+ * tests/slicer/cli-exit-codes.test.mjs checks the names and numbers against Utils.hpp's list.
8
+ */
9
+ export const BAMBU_CLI_EXIT_CODES = {
10
+ [-1]: { name: "CLI_ENVIRONMENT_ERROR", sentence: "the slicer could not set up its working environment" },
11
+ [-2]: { name: "CLI_INVALID_PARAMS", sentence: "the slicer was given options it does not accept" },
12
+ [-3]: { name: "CLI_FILE_NOTFOUND", sentence: "an input file was not found" },
13
+ [-4]: { name: "CLI_FILELIST_INVALID_ORDER", sentence: "the input files were in the wrong order (a 3MF has to come first)" },
14
+ [-5]: { name: "CLI_CONFIG_FILE_ERROR", sentence: "a settings file could not be read" },
15
+ [-6]: { name: "CLI_DATA_FILE_ERROR", sentence: "the model file could not be read" },
16
+ [-7]: { name: "CLI_INVALID_PRINTER_TECH", sentence: "the printer settings are not for a filament (FDM) printer" },
17
+ [-8]: { name: "CLI_UNSUPPORTED_OPERATION", sentence: "the slicer does not support that operation" },
18
+ [-9]: { name: "CLI_COPY_OBJECTS_ERROR", sentence: "making copies of the objects failed" },
19
+ [-10]: { name: "CLI_SCALE_TO_FIT_ERROR", sentence: "scaling the model to fit the bed failed" },
20
+ [-11]: { name: "CLI_EXPORT_STL_ERROR", sentence: "writing the STL file failed" },
21
+ [-12]: { name: "CLI_EXPORT_OBJ_ERROR", sentence: "writing the OBJ file failed" },
22
+ [-13]: { name: "CLI_EXPORT_3MF_ERROR", sentence: "writing the 3MF file failed" },
23
+ [-14]: { name: "CLI_OUT_OF_MEMORY", sentence: "the slicer ran out of memory" },
24
+ [-15]: { name: "CLI_3MF_NOT_SUPPORT_MACHINE_CHANGE", sentence: "this 3MF can't be moved to the chosen printer" },
25
+ [-16]: { name: "CLI_3MF_NEW_MACHINE_NOT_SUPPORTED", sentence: "the chosen printer can't be used with this 3MF" },
26
+ [-17]: { name: "CLI_PROCESS_NOT_COMPATIBLE", sentence: "the process settings don't fit the chosen printer" },
27
+ [-18]: { name: "CLI_INVALID_VALUES_IN_3MF", sentence: "the 3MF holds settings values the slicer rejects" },
28
+ [-19]: { name: "CLI_POSTPROCESS_NOT_SUPPORTED", sentence: "the settings use post-processing scripts, which the slicer CLI doesn't run" },
29
+ [-20]: { name: "CLI_PRINTABLE_SIZE_REDUCED", sentence: "the chosen printer's bed is smaller than the one the settings were made for" },
30
+ [-21]: { name: "CLI_OBJECT_ARRANGE_FAILED", sentence: "arranging the objects on the plate failed" },
31
+ [-22]: { name: "CLI_OBJECT_ORIENT_FAILED", sentence: "turning the objects to print well failed" },
32
+ [-23]: { name: "CLI_MODIFIED_PARAMS_TO_PRINTER", sentence: "the printer settings change its bed area, height or excluded area, which isn't allowed" },
33
+ [-24]: { name: "CLI_FILE_VERSION_NOT_SUPPORTED", sentence: "the 3MF was saved by a slicer version this one can't read (often a beta)" },
34
+ [-25]: { name: "CLI_3MF_FEATURE_NOT_SUPPORTED", sentence: "the 3MF uses an experimental feature this slicer doesn't support yet" },
35
+ [-50]: { name: "CLI_NO_SUITABLE_OBJECTS", sentence: "a plate is empty or has no object fully inside it; arrange the model or place it on the plate" },
36
+ [-51]: { name: "CLI_VALIDATE_ERROR", sentence: "the slicing settings failed the slicer's own checks" },
37
+ [-52]: { name: "CLI_OBJECTS_PARTLY_INSIDE", sentence: "objects extend over the bed boundary" },
38
+ [-53]: { name: "CLI_EXPORT_CACHE_DIRECTORY_CREATE_FAILED", sentence: "the slicer couldn't create its cache folder" },
39
+ [-54]: { name: "CLI_EXPORT_CACHE_WRITE_FAILED", sentence: "the slicer couldn't write its cache" },
40
+ [-55]: { name: "CLI_IMPORT_CACHE_NOT_FOUND", sentence: "the slicer's cache wasn't found" },
41
+ [-56]: { name: "CLI_IMPORT_CACHE_DATA_CAN_NOT_USE", sentence: "the slicer's cache couldn't be read" },
42
+ [-57]: { name: "CLI_IMPORT_CACHE_LOAD_FAILED", sentence: "loading the slicer's cache failed" },
43
+ [-58]: { name: "CLI_SLICING_TIME_EXCEEDS_LIMIT", sentence: "slicing a plate took longer than the time limit; simplify the model or use a taller layer height" },
44
+ [-59]: { name: "CLI_TRIANGLE_COUNT_EXCEEDS_LIMIT", sentence: "a plate has more triangles than the limit; simplify the model" },
45
+ [-60]: { name: "CLI_NO_SUITABLE_OBJECTS_AFTER_SKIP", sentence: "no printable objects remain after skipping" },
46
+ [-61]: { name: "CLI_FILAMENT_NOT_MATCH_BED_TYPE", sentence: "a filament can't be printed on the chosen plate type" },
47
+ [-62]: { name: "CLI_FILAMENTS_DIFFERENT_TEMP", sentence: "the filaments' temperatures differ too much" },
48
+ [-63]: { name: "CLI_OBJECT_COLLISION_IN_SEQ_PRINT", sentence: "objects collide in print-by-object mode" },
49
+ [-64]: { name: "CLI_OBJECT_COLLISION_IN_LAYER_PRINT", sentence: "objects collide" },
50
+ [-65]: { name: "CLI_SPIRAL_MODE_INVALID_PARAMS", sentence: "some settings can't be used in spiral vase mode" },
51
+ [-66]: { name: "CLI_FILAMENT_CAN_NOT_MAP", sentence: "some filaments can't be assigned to the printer's nozzles" },
52
+ [-67]: { name: "CLI_ONLY_ONE_TPU_SUPPORTED", sentence: "only one TPU filament can be used in a print" },
53
+ [-68]: { name: "CLI_FILAMENTS_NOT_SUPPORTED_BY_EXTRUDER", sentence: "a filament can't be printed by the nozzle it is assigned to" },
54
+ [-100]: { name: "CLI_SLICING_ERROR", sentence: "slicing the model failed" },
55
+ [-101]: { name: "CLI_GCODE_PATH_CONFLICTS", sentence: "the print paths of two objects overlap; move them apart, or move the wipe tower away from the models" },
56
+ [-102]: { name: "CLI_GCODE_PATH_IN_UNPRINTABLE_AREA", sentence: "the print reaches an area one of the printer's nozzles can't print" },
57
+ [-103]: { name: "CLI_FILAMENT_UNPRINTABLE_ON_FIRST_LAYER", sentence: "a filament can't be printed on the first layer of this plate type" },
58
+ [-104]: { name: "CLI_GCODE_PATH_OUTSIDE", sentence: "the print goes outside the printable area, usually through a support, brim, skirt or the wipe tower" },
59
+ [-105]: { name: "CLI_GCODE_IN_WRAPPING_DETECT_AREA", sentence: "the print goes into the bed area the printer keeps clear for its clumping (wrapping) check" },
60
+ };
61
+ /** The table's entry for a process exit status (the code's low byte) or a full negative code. */
62
+ export function bambuCliExitCode(exitCode) {
63
+ if (typeof exitCode !== "number" || !Number.isInteger(exitCode) || exitCode === 0)
64
+ return undefined;
65
+ const code = Object.keys(BAMBU_CLI_EXIT_CODES).map(Number)
66
+ .find(value => value === exitCode || (value & 0xff) === exitCode);
67
+ return code === undefined ? undefined : { code, ...BAMBU_CLI_EXIT_CODES[code] };
68
+ }