bambu-printer-mcp 1.1.71 → 1.1.72

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.
@@ -11,8 +11,10 @@ import { EventEmitter } from 'events';
11
11
  import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
13
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
14
+ import { listModelPlates } from '../counterpart/model-plates.js';
14
15
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
15
16
  import { plainSlicerError, UNKNOWN_SLICER_ERROR } from '../slicer/slicer-messages.js';
17
+ import { bambuCliExitCode } from '../slicer/cli-exit-codes.js';
16
18
  import { applyProcessOverrides } from '../slicer/process-overrides.js';
17
19
  import { profileJsonFiles } from '../slicer/profile-files.js';
18
20
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
@@ -25,11 +27,13 @@ const BAMBU_PROFILE_ROOTS = [
25
27
  '/Applications/BambuStudio.app/Contents/Resources/profiles/BBL',
26
28
  '/Applications/OrcaSlicer.app/Contents/Resources/profiles/BBL',
27
29
  ];
30
+ // curr_bed_type's enum keys (Bambu Studio 02.08.02.61 libslic3r/PrintConfig.cpp:437-445).
28
31
  const BAMBU_CLI_BED_TYPES = {
29
32
  textured_plate: 'Textured PEI Plate',
30
33
  cool_plate: 'Cool Plate',
31
34
  engineering_plate: 'Engineering Plate',
32
35
  hot_plate: 'High Temp Plate',
36
+ supertack_plate: 'Supertack Plate',
33
37
  };
34
38
  export const SLICER_TYPES = [
35
39
  'bambustudio',
@@ -171,29 +175,6 @@ function describeSlicerFailure(error, stdout, stderr, cli) {
171
175
  const output = stderr.trim() ? "" : stdout.trim().split("\n").slice(-20).join("\n");
172
176
  return `Slicer failed: the slicer ${status}${reason ? ` (${reason})` : ""}. ${error.message.trim()}${output ? `\nSlicer output: ${output}` : ""}`;
173
177
  }
174
- // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
175
- // exits with the low byte of the code; result.json names the error.
176
- const BAMBU_CLI_ERRORS = {
177
- [-2]: "invalid parameters to the slicer",
178
- [-3]: "input files not found",
179
- [-5]: "preset file cannot be parsed",
180
- [-6]: "model file cannot be parsed",
181
- [-9]: "copying objects failed",
182
- [-17]: "printer is not compatible with the process preset",
183
- [-21]: "auto-arranging objects failed",
184
- [-22]: "auto-orienting objects failed",
185
- [-50]: "a plate is empty or has no object fully inside it; arrange the model or place it on the plate",
186
- [-51]: "incorrect slicing parameters",
187
- [-52]: "objects extend over the bed boundary",
188
- [-60]: "no printable objects remain after skipping",
189
- [-61]: "filaments are not compatible with the plate type",
190
- [-62]: "the filaments' temperatures differ too much",
191
- [-63]: "objects collide in print-by-object mode",
192
- [-64]: "objects collide",
193
- [-100]: "slicing the model failed",
194
- [-101]: "G-code conflicts after slicing",
195
- [-102]: "G-code in an unprintable area",
196
- };
197
178
  function bambuCliFailureReason(exitCode, cli) {
198
179
  const result = readCliResult(cli);
199
180
  if (typeof result?.error_string === "string" && result.error_string.trim()) {
@@ -201,8 +182,8 @@ function bambuCliFailureReason(exitCode, cli) {
201
182
  }
202
183
  if (typeof exitCode !== "number")
203
184
  return undefined;
204
- const code = Object.keys(BAMBU_CLI_ERRORS).map(Number).find(value => (value & 0xff) === exitCode);
205
- return code === undefined ? undefined : `${BAMBU_CLI_ERRORS[code]} [${code}]`;
185
+ const known = bambuCliExitCode(exitCode);
186
+ return known ? `${known.sentence} [${known.code}]` : undefined;
206
187
  }
207
188
  export class STLManipulator extends EventEmitter {
208
189
  constructor(tempDir = path.join(process.cwd(), 'temp')) {
@@ -623,9 +604,6 @@ export class STLManipulator extends EventEmitter {
623
604
  if (!bedType)
624
605
  return undefined;
625
606
  const normalized = bedType.trim().toLowerCase();
626
- if (normalized === 'supertack_plate') {
627
- throw new Error('BambuStudio CLI SuperTack bed type is not verified; use a pre-sliced 3MF or choose textured_plate, cool_plate, engineering_plate, or hot_plate.');
628
- }
629
607
  return BAMBU_CLI_BED_TYPES[normalized] || bedType;
630
608
  }
631
609
  /**
@@ -1381,37 +1359,41 @@ export class STLManipulator extends EventEmitter {
1381
1359
  const once = (options) => this.sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, options);
1382
1360
  const layers = bambuOptions?.pauseAtLayers?.length ? bambuOptions.pauseAtLayers : undefined;
1383
1361
  const cli = slicerType === 'bambustudio' || slicerType === 'orcaslicer' || slicerType === 'orcaslicer-bambulab';
1384
- const plate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : 1;
1385
- // The CLI drops a project's own pauses and colour changes; carry them over.
1386
- const project = cli && /\.3mf$/i.test(stlFilePath) ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1387
- if (!layers && !project?.gcodes.length)
1362
+ // Without new pauses the CLI keeps the project's own pauses and colour changes itself: it loads a
1363
+ // Bambu 3MF's Metadata/custom_gcode_per_layer.xml with the project (Bambu Studio 02.08.02.61
1364
+ // BambuStudio.cpp:1882, bbs_3mf.cpp:2051), so nothing is passed.
1365
+ if (!layers)
1388
1366
  return once(bambuOptions);
1389
- if (layers && !cli) {
1367
+ if (!cli) {
1390
1368
  throw new Error(`Pausing at a layer needs the Bambu Studio or OrcaSlicer CLI, not ${slicerType}.`);
1391
1369
  }
1370
+ const chosenPlate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : undefined;
1371
+ const plate = chosenPlate ?? 1;
1372
+ const threeMf = /\.3mf$/i.test(stlFilePath);
1373
+ // --load-custom-gcodes replaces the whole per-plate map and holds one plate (--slice N, or plate 1 for
1374
+ // --slice 0: BambuStudio.cpp:2224-2233, 4005-4008), so slicing every plate would drop plates 2..n's own.
1375
+ if (threeMf && chosenPlate === undefined && (await listModelPlates(stlFilePath)).plate_count > 1) {
1376
+ throw new Error('Pausing at a layer works on one plate at a time. Choose the plate with slice_plate.');
1377
+ }
1378
+ // The map replaces the project's own entries for this plate, so they are merged in.
1379
+ const project = threeMf ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1392
1380
  const customGcodesFile = path.join(this.tempDir, `custom-gcodes-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
1393
1381
  try {
1394
- let tops = [];
1395
- if (layers) {
1396
- // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1397
- if (progressCallback)
1398
- progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1399
- const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1400
- const gcode = await readPlateGcode(plain.path, plate);
1401
- if (!gcode)
1402
- throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1403
- tops = layerTops(gcode);
1404
- }
1405
- const info = layers ? customGcodesWithPauses(tops, layers, project) : project;
1406
- await fs.promises.writeFile(customGcodesFile, JSON.stringify(info));
1382
+ // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1383
+ if (progressCallback)
1384
+ progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1385
+ const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1386
+ const plainGcode = await readPlateGcode(plain.path, plate);
1387
+ if (!plainGcode)
1388
+ throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1389
+ const tops = layerTops(plainGcode);
1390
+ await fs.promises.writeFile(customGcodesFile, JSON.stringify(customGcodesWithPauses(tops, layers, project)));
1407
1391
  const result = await once({ ...bambuOptions, customGcodesFile });
1408
- if (layers) {
1409
- const gcode = await readPlateGcode(result.path, plate);
1410
- const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1411
- const missing = layers.filter(layer => !placed.includes(layer));
1412
- if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1413
- throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1414
- }
1392
+ const gcode = await readPlateGcode(result.path, plate);
1393
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1394
+ const missing = layers.filter(layer => !placed.includes(layer));
1395
+ if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1396
+ throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1415
1397
  }
1416
1398
  return result;
1417
1399
  }
package/dist/types.d.ts CHANGED
@@ -81,12 +81,18 @@ export interface ThreeMFAmsRequirements {
81
81
  filaments: ThreeMFFilamentRequirement[];
82
82
  }
83
83
  export interface ThreeMFPlateObject {
84
+ /** The instance's identify_id: the id the printer's skip_objects command takes. */
84
85
  id: number;
85
86
  name: string;
87
+ /** Already skipped in this file (slice_info's skipped="true"). */
88
+ skipped: boolean;
89
+ /** First-layer area and box from plate_N.json, only when the name is unique on the plate. */
86
90
  area: number | null;
87
91
  bbox: unknown;
88
92
  }
89
93
  export interface ThreeMFPlateObjects {
90
94
  plateIndex: number;
95
+ /** The plate was sliced with object labels, which the printer needs to skip objects. */
96
+ labelObjectEnabled: boolean;
91
97
  objects: ThreeMFPlateObject[];
92
98
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.71",
3
+ "version": "1.1.72",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
package/src/3mf_parser.ts CHANGED
@@ -499,73 +499,67 @@ export async function analyze3MFAmsRequirements(
499
499
  };
500
500
  }
501
501
 
502
+ /**
503
+ * The objects of one sliced plate that the printer can skip, as Bambu Studio lists them in its skip dialog
504
+ * (02.08.02.61 slic3r/GUI/PartSkipDialog.cpp:734-741, SkipPartCanvas.cpp:690-730): one entry per instance
505
+ * from Metadata/slice_info.config's plate whose `index` matches (written per instance at bbs_3mf.cpp:8718-8750),
506
+ * with its identify_id. plate_N.json's bbox_objects are not paired by position: their `id` is an internal
507
+ * object id the printer doesn't know (BambuStudio.cpp:7374-7382), and copies share a name. The wipe tower
508
+ * is never a slice_info object.
509
+ */
502
510
  export async function analyze3MFPlateObjects(
503
511
  filePath: string,
504
512
  plateIndex: number = 0
505
513
  ): Promise<ThreeMFPlateObjects> {
506
514
  const data = await fs.readFile(filePath);
507
515
  const zip = await JSZip.loadAsync(data);
508
- const plateName = `Metadata/plate_${plateIndex + 1}.json`;
509
- const plateFile = zip.file(plateName);
510
-
511
- if (!plateFile) {
512
- throw new Error(`3MF is missing ${plateName}; cannot list plate objects.`);
513
- }
514
-
515
- const plateJson = JSON.parse(await plateFile.async('string'));
516
- const bboxObjects = Array.isArray(plateJson?.bbox_objects) ? plateJson.bbox_objects : [];
517
- const sliceInfoObjects: Array<{ id: number; name: string | null }> = [];
516
+ const plateNumber = plateIndex + 1;
518
517
  const sliceInfo = zip.file('Metadata/slice_info.config');
518
+ if (!sliceInfo) {
519
+ throw new Error('This 3MF has no Metadata/slice_info.config, so it was not sliced by Bambu Studio or OrcaSlicer and has no skip-object ids. Slice it first.');
520
+ }
521
+ const parsed = await parseStringPromise(await sliceInfo.async('string'), { explicitArray: true });
522
+ const plates: any[] = parsed?.config?.plate ?? [];
523
+ const selected = plates.find(plate => (plate?.metadata ?? [])
524
+ .some((item: any) => item?.$?.key === 'index' && Number(item?.$?.value) === plateNumber));
525
+ if (!selected) {
526
+ throw new Error(`Plate ${plateNumber} was not sliced in this 3MF, so it has no skip-object ids.`);
527
+ }
528
+ const labelObjectEnabled = (selected.metadata ?? [])
529
+ .some((item: any) => item?.$?.key === 'label_object_enabled' && item?.$?.value === 'true');
530
+ const instances = (selected.object ?? []).flatMap((object: any) => {
531
+ const id = Number(object?.$?.identify_id);
532
+ if (!Number.isSafeInteger(id) || id <= 0) return [];
533
+ return [{ id, name: typeof object.$.name === 'string' ? object.$.name : `object_${id}`, skipped: object.$.skipped === 'true' }];
534
+ });
519
535
 
520
- if (sliceInfo) {
536
+ // First-layer area and box, attached by name only where one instance and one box carry it.
537
+ const boxes = new Map<string, any[]>();
538
+ const plateFile = zip.file(`Metadata/plate_${plateNumber}.json`);
539
+ if (plateFile) {
521
540
  try {
522
- const parsed = await parseStringPromise(await sliceInfo.async('string'), {
523
- explicitArray: false,
524
- mergeAttrs: true,
525
- });
526
- const plateNodes = parsed?.config?.plate
527
- ? Array.isArray(parsed.config.plate) ? parsed.config.plate : [parsed.config.plate]
528
- : [];
529
- const plateNumber = plateIndex + 1;
530
- const selectedPlate =
531
- plateNodes.find((plate: any) => {
532
- const metadata = Array.isArray(plate?.metadata)
533
- ? plate.metadata
534
- : plate?.metadata
535
- ? [plate.metadata]
536
- : [];
537
- return metadata.some((item: any) => item?.key === 'index' && Number(item?.value) === plateNumber);
538
- }) || plateNodes[plateIndex] || plateNodes[0];
539
- const objectNodes = selectedPlate?.object
540
- ? Array.isArray(selectedPlate.object) ? selectedPlate.object : [selectedPlate.object]
541
- : [];
542
- for (const object of objectNodes) {
543
- const id = Number.parseInt(String(object?.identify_id ?? ''), 10);
544
- if (!Number.isInteger(id)) continue;
545
- sliceInfoObjects.push({
546
- id,
547
- name: typeof object?.name === 'string' ? object.name : null,
548
- });
541
+ const plateJson = JSON.parse(await plateFile.async('string'));
542
+ for (const box of Array.isArray(plateJson?.bbox_objects) ? plateJson.bbox_objects : []) {
543
+ if (typeof box?.name !== 'string' || box.name === 'wipe_tower') continue;
544
+ boxes.set(box.name, [...(boxes.get(box.name) ?? []), box]);
549
545
  }
550
546
  } catch {
551
- // Fall back to bbox IDs for older or malformed 3MFs.
547
+ // The ids above still stand without the boxes.
552
548
  }
553
549
  }
550
+ const nameCount = new Map<string, number>();
551
+ for (const instance of instances) nameCount.set(instance.name, (nameCount.get(instance.name) ?? 0) + 1);
554
552
 
555
553
  return {
556
554
  plateIndex,
557
- objects: bboxObjects
558
- .map((object: any, index: number) => {
559
- const sliceObject = sliceInfoObjects[index];
560
- const id = sliceObject?.id ?? Number(object?.id);
561
- if (!Number.isInteger(id)) return null;
562
- return {
563
- id,
564
- name: sliceObject?.name || (typeof object?.name === 'string' ? object.name : `object_${id}`),
565
- area: Number.isFinite(Number(object?.area)) ? Number(object.area) : null,
566
- bbox: object?.bbox ?? null,
567
- };
568
- })
569
- .filter((object: unknown): object is NonNullable<typeof object> => object !== null),
555
+ labelObjectEnabled,
556
+ objects: instances.map((instance: { id: number; name: string; skipped: boolean }) => {
557
+ const box = nameCount.get(instance.name) === 1 && boxes.get(instance.name)?.length === 1 ? boxes.get(instance.name)![0] : undefined;
558
+ return {
559
+ ...instance,
560
+ area: box && Number.isFinite(Number(box.area)) ? Number(box.area) : null,
561
+ bbox: box?.bbox ?? null,
562
+ };
563
+ }),
570
564
  };
571
565
  }
@@ -75,7 +75,9 @@ export function bridgeAmsMapping2Entry(value: number, dualNozzle = false): { ams
75
75
  if (value < 0) return { ams_id: 255, slot_id: 255 };
76
76
  if (value === 255) return dualNozzle ? { ams_id: 255, slot_id: 0 } : { ams_id: 255, slot_id: 255 };
77
77
  if (value === 254) return { ams_id: 254, slot_id: dualNozzle ? 0 : 254 };
78
- if (value >= 128) return { ams_id: 128, slot_id: value - 128 };
78
+ // An AMS-HT has one slot; its absolute tray index is its own unit id (Bambu Studio 02.08.02.61
79
+ // DevFilaSystem.cpp:367-368), sent as that unit's ams_id with slot 0 (SelectMachine.cpp:1489-1497).
80
+ if (value >= 128) return { ams_id: value, slot_id: 0 };
79
81
  return { ams_id: Math.floor(value / 4), slot_id: value % 4 };
80
82
  }
81
83
 
@@ -14,6 +14,12 @@ export interface ModelPlate {
14
14
  index: number;
15
15
  name: string;
16
16
  objects: string[];
17
+ /**
18
+ * Each object copy on the plate with its identify_id, from model_settings.config's <model_instance> entries
19
+ * (Bambu Studio 02.08.02.61 bbs_3mf.cpp:8448-8482). These are the ids slice_stl's skip_objects takes: the
20
+ * CLI matches them against each instance's loaded id (BambuStudio.cpp:1785-1789, 6530-6545).
21
+ */
22
+ instances: { identify_id: number; name: string }[];
17
23
  /** The file already holds this plate's G-code. */
18
24
  sliced: boolean;
19
25
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
@@ -31,6 +37,7 @@ export interface ModelPlates {
31
37
  const MAX_METADATA_BYTES = 8 * 1024 * 1024;
32
38
  const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
33
39
  const MAX_PLATES = 1000;
40
+ const MAX_INSTANCES_PER_PLATE = 1000;
34
41
 
35
42
  const words = (value: string) => value
36
43
  .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
@@ -71,7 +78,13 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
71
78
  const number = Number(id[1]);
72
79
  if (!valid(number)) continue;
73
80
  const name = /<metadata\s+key="plater_name"\s+value="([^"]*)"/.exec(match[1]);
74
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false,
81
+ const instances = [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
82
+ const object = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
83
+ const identify = Number(/<metadata\s+key="identify_id"\s+value="(\d+)"/.exec(instance[1])?.[1]);
84
+ return object !== undefined && Number.isSafeInteger(identify) && identify > 0
85
+ ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
86
+ }).slice(0, MAX_INSTANCES_PER_PLATE);
87
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances,
75
88
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
76
89
  }
77
90
  for (const name of Object.keys(zip.files)) {
@@ -79,7 +92,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
79
92
  if (!match) continue;
80
93
  const number = Number(match[1]);
81
94
  if (!valid(number)) continue;
82
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], sliced: false };
95
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false };
83
96
  if (match[2] === "gcode") plate.sliced = true;
84
97
  else {
85
98
  try {
@@ -92,7 +105,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
92
105
  }
93
106
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
94
107
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
95
- if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], sliced: false });
108
+ if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false });
96
109
  const geometry = has("item") && (has("mesh") || has("component"));
97
110
  if (!geometry) {
98
111
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
package/src/index.ts CHANGED
@@ -266,7 +266,7 @@ function resolveNozzleVolumeType(value: unknown): "Standard" | "High Flow" | und
266
266
  }
267
267
  return NOZZLE_VOLUME_TYPES[normalized as keyof typeof NOZZLE_VOLUME_TYPES];
268
268
  }
269
- const VALID_BAMBUSTUDIO_CLI_BED_TYPES = ["textured_plate", "cool_plate", "engineering_plate", "hot_plate"] as const;
269
+ const VALID_BAMBUSTUDIO_CLI_BED_TYPES = ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"] as const;
270
270
 
271
271
  // Map model IDs to BambuStudio --load-machine preset names
272
272
  const BAMBU_MODEL_PRESETS: Record<string, (nozzle: string) => string> = {
@@ -809,7 +809,7 @@ function resolveBambuStudioCliBedType(argsBedType: string | undefined): string {
809
809
  const bedType = resolveBedType(argsBedType);
810
810
  if (!(VALID_BAMBUSTUDIO_CLI_BED_TYPES as readonly string[]).includes(bedType)) {
811
811
  throw new Error(
812
- `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(", ")}`
812
+ `BambuStudio CLI bed_type "${bedType}" is not one of: ${VALID_BAMBUSTUDIO_CLI_BED_TYPES.join(", ")}`
813
813
  );
814
814
  }
815
815
  return bedType;
@@ -1630,12 +1630,6 @@ class BambuPrinterMCPServer {
1630
1630
  }
1631
1631
  assertUniformCliNozzles(args);
1632
1632
 
1633
- if (bedType === "supertack_plate") {
1634
- throw new Error(
1635
- '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.'
1636
- );
1637
- }
1638
-
1639
1633
  console.error(`3MF has no gcode - auto-slicing with ${slicerType} for ${printModel}`);
1640
1634
  const autoSliceOptions: BambuSliceOptions = {
1641
1635
  ...(slicerType === "orca-slicer-api" ? {} : {
@@ -2227,11 +2221,6 @@ class BambuPrinterMCPServer {
2227
2221
  }
2228
2222
 
2229
2223
  const printPreset = BAMBU_MODEL_PRESETS[printModel]?.(printNozzle);
2230
- if (bedType === "supertack_plate") {
2231
- throw new Error(
2232
- '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.'
2233
- );
2234
- }
2235
2224
  const autoSliceOptions: BambuSliceOptions = {
2236
2225
  ...(slicerType === "orca-slicer-api" ? {} : {
2237
2226
  uptodate: true, ensureOnBed: true, minSave: true, skipModifiedGcodes: true,
@@ -2579,7 +2568,7 @@ class BambuPrinterMCPServer {
2579
2568
  },
2580
2569
  {
2581
2570
  name: "list_3mf_plates",
2582
- 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.",
2571
+ 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) 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.",
2583
2572
  inputSchema: {
2584
2573
  type: "object",
2585
2574
  properties: {
@@ -2591,7 +2580,7 @@ class BambuPrinterMCPServer {
2591
2580
  },
2592
2581
  {
2593
2582
  name: "list_3mf_plate_objects",
2594
- description: "List object IDs from a sliced 3MF plate. Use these IDs with skip_objects during a running print.",
2583
+ 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.",
2595
2584
  inputSchema: {
2596
2585
  type: "object",
2597
2586
  properties: {
@@ -2742,7 +2731,7 @@ class BambuPrinterMCPServer {
2742
2731
  bed_type: {
2743
2732
  type: "string",
2744
2733
  enum: ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"],
2745
- 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."
2734
+ description: "Bed plate type for slicing (default: textured_plate)."
2746
2735
  },
2747
2736
  nozzle_type: {
2748
2737
  type: "string",
@@ -2803,7 +2792,7 @@ class BambuPrinterMCPServer {
2803
2792
  bed_type: {
2804
2793
  type: "string",
2805
2794
  enum: ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"],
2806
- 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."
2795
+ description: "Bed plate type for slicing (default: textured_plate)."
2807
2796
  },
2808
2797
  nozzle_type: {
2809
2798
  type: "string",
@@ -2822,7 +2811,7 @@ class BambuPrinterMCPServer {
2822
2811
  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." },
2823
2812
  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." },
2824
2813
  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." },
2825
- 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." },
2814
+ 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." },
2826
2815
  load_filaments: { type: "string", description: "Override filament profiles. Semicolon-separated paths to filament JSON configs, e.g. 'pla_basic.json;petg_cf.json'." },
2827
2816
  filament_profile: { type: "string", description: "Compatibility alias for load_filaments. Semicolon-separated Orca/Bambu filament profile JSON paths." },
2828
2817
  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." },
@@ -3280,7 +3269,7 @@ class BambuPrinterMCPServer {
3280
3269
  properties: {
3281
3270
  object_ids: {
3282
3271
  type: "array",
3283
- description: "Object IDs to skip. Use list_3mf_plate_objects on the sliced 3MF to find IDs.",
3272
+ description: "identify_id values of the object copies to skip. Use list_3mf_plate_objects on the sliced 3MF to find them.",
3284
3273
  items: { type: "number" }
3285
3274
  },
3286
3275
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
@@ -4740,11 +4729,6 @@ class BambuPrinterMCPServer {
4740
4729
  }
4741
4730
  if (!hasGcode) {
4742
4731
  assertUniformCliNozzles(args as Record<string, any>);
4743
- if (printBedType === "supertack_plate") {
4744
- throw new Error(
4745
- '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.'
4746
- );
4747
- }
4748
4732
  console.error(`3MF has no gcode — auto-slicing with ${slicerType} for ${printModel}`);
4749
4733
  const autoSliceOptions: BambuSliceOptions = {
4750
4734
  ...(slicerType === "orca-slicer-api" ? { slicePlate: plateIndex + 1 } : {
@@ -4753,7 +4737,8 @@ class BambuPrinterMCPServer {
4753
4737
  bedType: printBedType,
4754
4738
  nozzleType: resolveNozzleType(args?.nozzle_type),
4755
4739
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
4756
- ...(pauseLayers ? { pauseAtLayers: pauseLayers } : {}),
4740
+ // A pause belongs to the plate being printed; the CLI carries custom G-code for one plate only.
4741
+ ...(pauseLayers ? { pauseAtLayers: pauseLayers, slicePlate: plateIndex + 1 } : {}),
4757
4742
  };
4758
4743
  if (!explicitSlicerProfile) {
4759
4744
  try {
@@ -30,13 +30,26 @@ function list(value: unknown): string[] {
30
30
  if (typeof value === 'string') return value.split(/[;,]/).map(s=>s.trim().replace(/^"|"$/g,''));
31
31
  return [];
32
32
  }
33
+ /**
34
+ * Every name a Bambu plate goes by, to the plate_N.json bed_type token Bambu Studio writes for it
35
+ * (02.08.02.61 PrintConfig.hpp:437-456 bed_type_to_gcode_string). project_settings and the G-code header
36
+ * carry curr_bed_type's enum key instead (PrintConfig.cpp:437-445); the GUI labels (:1307-1311) and this
37
+ * server's own bed_type values name the same plates. Other names (another slicer's plates) stay as written,
38
+ * so two copies of the same name still agree.
39
+ */
40
+ const BED_NAMES: Record<string, string[]> = {
41
+ cool_plate: ['cool plate'],
42
+ eng_plate: ['engineering plate'],
43
+ hot_plate: ['high temp plate', 'smooth pei plate', 'smooth pei plate / high temp plate', 'high temperature plate'],
44
+ textured_plate: ['textured pei plate'],
45
+ supertack_plate: ['supertack plate', 'bambu cool plate supertack', 'cool plate supertack'],
46
+ };
47
+ const BED_TOKENS = new Map(Object.entries(BED_NAMES).flatMap(([token, names]) =>
48
+ [token, ...names].map(name => [name.replace(/[_-]/g,' '), token] as const)));
33
49
  function normalizeBed(value: unknown): string | undefined {
34
50
  if (typeof value !== 'string' || !value.trim()) return undefined;
35
51
  const text = value.trim().toLowerCase().replace(/[_-]/g,' ').replace(/\s+/g,' ');
36
- if (['textured pei plate','textured plate'].includes(text)) return 'textured pei plate';
37
- if (['supertack plate','cool plate supertack'].includes(text)) return 'cool plate supertack';
38
- if (['smooth pei plate','high temp plate','high temperature plate','hot plate'].includes(text)) return 'smooth pei plate';
39
- return text;
52
+ return BED_TOKENS.get(text) ?? text;
40
53
  }
41
54
  function metadataValues(metadata: Metadata[], keys: string[]): unknown[] {
42
55
  return metadata.flatMap(data=>keys.filter(key=>data[key] !== undefined).map(key=>data[key]));
@@ -374,8 +374,9 @@ function externalTray(raw: Record<string,any>, trayIndex: number, model: string)
374
374
  return object(raw.vt_tray) ? raw.vt_tray : undefined;
375
375
  }
376
376
  function mappedTray(raw: Record<string,any>, index: number): Record<string,any> {
377
- const unit = index >= 128 ? 128 : Math.floor(index / 4);
378
- const slot = index >= 128 ? index - 128 : index % 4;
377
+ // An AMS-HT tray index is the unit's own id, with its single slot 0 (Bambu Studio DevFilaSystem.cpp:367-368).
378
+ const unit = index >= 128 ? index : Math.floor(index / 4);
379
+ const slot = index >= 128 ? 0 : index % 4;
379
380
  const units = raw.ams?.ams;
380
381
  const ams = Array.isArray(units) ? units.find((value:any) => Number(value?.id) === unit) : undefined;
381
382
  const tray = Array.isArray(ams?.tray) ? ams.tray.find((value:any) => Number(value?.id) === slot) : 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: Record<number, { name: string; sentence: string }> = {
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
+
62
+ /** The table's entry for a process exit status (the code's low byte) or a full negative code. */
63
+ export function bambuCliExitCode(exitCode: unknown): { code: number; name: string; sentence: string } | undefined {
64
+ if (typeof exitCode !== "number" || !Number.isInteger(exitCode) || exitCode === 0) 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
+ }
@@ -7,11 +7,13 @@ import JSZip from "jszip";
7
7
  * (M400 U1 on Bambu printers) before the chosen layer, so the printer pauses
8
8
  * by itself there and waits for Resume; no remote command is involved.
9
9
  *
10
- * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). It
11
- * does not apply the pauses a project 3MF already carries in
12
- * Metadata/custom_gcode_per_print_z.xml, so those are read here and passed the
13
- * same way. A pause's print_z must be the exact top of its layer: a height
14
- * between layers lands on the layer below.
10
+ * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). A
11
+ * project 3MF keeps its own pauses and colour changes in
12
+ * Metadata/custom_gcode_per_layer.xml (Bambu Studio 02.08.02.61 bbs_3mf.cpp:184,
13
+ * written at :8943-8990), which the CLI loads with the project. The JSON
14
+ * replaces that whole map (BambuStudio.cpp:4005-4008), so the plate's own
15
+ * entries are read here and merged in. A pause's print_z must be the exact top
16
+ * of its layer: a height between layers lands on the layer below.
15
17
  */
16
18
 
17
19
  /** CustomGCode::Type, in the order bbs_3mf.cpp writes it as an integer. */
@@ -61,7 +63,7 @@ export async function readProjectCustomGcodes(threeMfPath: string, plate = 1): P
61
63
  } catch {
62
64
  return undefined;
63
65
  }
64
- const file = zip.file(/^Metadata\/custom_gcode_per_print_z\.xml$/i)[0];
66
+ const file = zip.file(/^Metadata\/custom_gcode_per_layer\.xml$/i)[0];
65
67
  if (!file) return undefined;
66
68
  const xml = await file.async("string");
67
69
  for (const block of xml.match(/<plate>[\s\S]*?<\/plate>/g) ?? []) {