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,338 @@
1
+ /**
2
+ * The project filaments each plate of a Bambu Studio / OrcaSlicer 3MF prints with, worked out the way Bambu Studio
3
+ * does it (v02.08.02.61), so a client asks the person to choose spools only for the filaments that plate uses.
4
+ *
5
+ * - A sliced plate: Studio's own record, Metadata/plate_N.json `filament_ids` (0-based), written from the slice.
6
+ * - An unsliced plate: PartPlate::get_extruders_under_cli (src/slic3r/GUI/PartPlate.cpp:1298-1420) over the objects
7
+ * with an instance on the plate (model_settings.config <model_instance>; an instance with printable="0" in the
8
+ * 3dmodel.model build is skipped, PartPlate.cpp:1321):
9
+ * - each volume's ModelVolume::get_extruders (src/libslic3r/Model.cpp:3357-3412): negative parts, support blockers
10
+ * and enforcers print nothing; the volume's painted states (mmu_segmentation, `paint_color`); the volume's own
11
+ * extruder (ModelVolume::extruder_id, Model.cpp:3295-3306: the part's, else the object's, else 1) unless paint
12
+ * covers every facet of a model part; and the volume's wall/solid/sparse infill filaments, else the object's;
13
+ * - the object's layer-range extruders (Metadata/layer_config_ranges.xml, by 1-based model object index);
14
+ * - the object's feature filaments when separate_filaments_for_features is on;
15
+ * - the support and support-interface filaments when the object (or the project) prints support or a raft;
16
+ * - the plate's tool changes (Metadata/custom_gcode_per_layer.xml, CustomGCode::ToolChange = 2,
17
+ * PartPlate.cpp:1263-1274).
18
+ * Painting is decoded as FacetsAnnotation::set_triangle_from_string (Model.cpp:4631-4650) and
19
+ * TriangleSelector::deserialize (src/libslic3r/TriangleSelector.cpp:2111-2139) read it; this is a reimplementation
20
+ * from that documented behaviour, not Studio's code.
21
+ *
22
+ * Only bounded metadata and mesh text are read; nothing is extracted or run.
23
+ */
24
+ import type JSZip from "jszip";
25
+
26
+ export interface PlateFilament {
27
+ /** 1-based project filament number: slice_stl's load_filaments/filament_colours position, print_3mf's ams_mapping index + 1. */
28
+ index: number;
29
+ /** As the project declares it (project_settings.config filament_colour), #RRGGBB. */
30
+ colour?: string;
31
+ /** project_settings.config filament_type. */
32
+ material?: string;
33
+ /** project_settings.config filament_ids (Bambu's filament id, e.g. GFA00). */
34
+ filament_id?: string;
35
+ /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
36
+ name?: string;
37
+ }
38
+
39
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
40
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
41
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
42
+ const MAX_FILAMENT = 64;
43
+
44
+ const words = (value: string) => value
45
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
46
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
47
+
48
+ type Settings = Map<string, string>;
49
+ interface Part { id: string; subtype: string; name: string; settings: Settings }
50
+ interface ObjectEntry { id: string; name: string; settings: Settings; parts: Part[] }
51
+
52
+ const metadataOf = (block: string): Settings => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
53
+
54
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
55
+ export function readModelObjects(settings: string): ObjectEntry[] {
56
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
57
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
58
+ const own = metadataOf(part[2]);
59
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
60
+ });
61
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
62
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
63
+ });
64
+ }
65
+
66
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
67
+ function intOf(value: unknown): number | undefined {
68
+ const first = Array.isArray(value) ? value[0] : value;
69
+ if (typeof first === "number" && Number.isInteger(first)) return first;
70
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first)) return undefined;
71
+ return Number(first);
72
+ }
73
+ function boolOf(value: unknown): boolean | undefined {
74
+ const first = Array.isArray(value) ? value[0] : value;
75
+ if (typeof first === "boolean") return first;
76
+ if (typeof first !== "string") return undefined;
77
+ if (/^(?:1|true)$/i.test(first.trim())) return true;
78
+ if (/^(?:0|false)$/i.test(first.trim())) return false;
79
+ return undefined;
80
+ }
81
+
82
+ /**
83
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
84
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
85
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
86
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
87
+ */
88
+ export function paintedStates(paint: string): number[] {
89
+ const nibbles: number[] = [];
90
+ for (let i = paint.length - 1; i >= 0; i--) {
91
+ const digit = Number.parseInt(paint[i], 16);
92
+ if (Number.isNaN(digit)) return [];
93
+ nibbles.push(digit);
94
+ }
95
+ const states: number[] = [];
96
+ let at = 0, pending = 1;
97
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
98
+ while (pending > 0) {
99
+ const code = next();
100
+ if (code === undefined) break;
101
+ pending -= 1;
102
+ const sides = code & 0b11;
103
+ if (sides) { pending += sides + 1; continue; }
104
+ if ((code & 0b1100) === 0b1100) {
105
+ let more = 0, value = next();
106
+ while (value === 0b1111) { more += 1; value = next(); }
107
+ if (value === undefined) break;
108
+ states.push(value + 15 * more + 3);
109
+ } else states.push(code >> 2);
110
+ }
111
+ return states;
112
+ }
113
+
114
+ /** What a mesh's painting says: the painted filament states, and whether any facet keeps the volume's own filament. */
115
+ interface MeshPaint { states: Set<number>; ownFilament: boolean }
116
+
117
+ /**
118
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
119
+ */
120
+ async function readPainting(zip: JSZip, paths: Set<string>): Promise<Map<string, MeshPaint>> {
121
+ const result = new Map<string, MeshPaint>();
122
+ let total = 0;
123
+ for (const path of paths) {
124
+ const file = zip.file(path);
125
+ if (!file) continue;
126
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
127
+ const size = (file as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize;
128
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL)) continue;
129
+ const bytes = await file.async("nodebuffer");
130
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL) continue;
131
+ if (!bytes.includes("paint_color=\"")) continue;
132
+ const text = bytes.toString("utf8");
133
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
134
+ const paint: MeshPaint = { states: new Set(), ownFilament: false };
135
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
136
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
137
+ if (!value) { paint.ownFilament = true; continue; }
138
+ for (const state of paintedStates(value)) {
139
+ if (state === 0) paint.ownFilament = true;
140
+ else paint.states.add(state);
141
+ }
142
+ }
143
+ result.set(`${path}#${object[1]}`, paint);
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+
149
+ interface ProjectFilaments { colours: string[]; materials: string[]; ids: string[]; config: Record<string, unknown> }
150
+
151
+ function projectFilaments(config: Record<string, unknown>): ProjectFilaments {
152
+ const list = (key: string): string[] => Array.isArray(config[key]) ? (config[key] as unknown[]).map(String) : [];
153
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
154
+ }
155
+
156
+ function describe(index: number, project: ProjectFilaments, name?: string): PlateFilament {
157
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
158
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
159
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
160
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
161
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
162
+ }
163
+
164
+ export interface PlateLayout {
165
+ /** 1-based plate number. */
166
+ number: number;
167
+ /** model_settings.config object ids with an instance on this plate, in plate order. */
168
+ objectIds: string[];
169
+ /** Each copy on the plate: its object and that object's instance_id (model_settings.config <model_instance>). */
170
+ instances?: { objectId: string; instanceId: number }[];
171
+ /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
172
+ slicedFilamentIds?: number[];
173
+ }
174
+
175
+ /**
176
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
177
+ * 3D/3dmodel.model text.
178
+ */
179
+ export async function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[]): Promise<{ plates: Map<number, PlateFilament[]>; project: PlateFilament[] }> {
180
+ const text = async (name: string) => {
181
+ const file = zip.file(name);
182
+ if (!file) return "";
183
+ const bytes = await file.async("nodebuffer");
184
+ if (bytes.length > MAX_TEXT_BYTES) throw new Error(`${name} is too large to read.`);
185
+ return bytes.toString("utf8");
186
+ };
187
+ let config: Record<string, unknown> = {};
188
+ try {
189
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}") as unknown;
190
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
191
+ } catch { /* a project without readable settings declares no filaments */ }
192
+ const project = projectFilaments(config);
193
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
194
+ const valid = (index: number | undefined): index is number => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
195
+
196
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
197
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
198
+ const components = new Map<string, Map<string, string>>();
199
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
200
+ const parts = new Map<string, string>();
201
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
202
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
203
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
204
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
205
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
206
+ if (id) parts.set(id, path || "3D/3dmodel.model");
207
+ }
208
+ if (parts.size) components.set(object[1], parts);
209
+ }
210
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
211
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
212
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
213
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
214
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
215
+ // isn't printable (PartPlate.cpp:1311-1322).
216
+ const printableItems = new Map<string, boolean[]>();
217
+ for (const item of buildItems) {
218
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
219
+ if (id) printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
220
+ }
221
+ const printableCopy = (objectId: string, instanceId?: number) => {
222
+ const flags = printableItems.get(objectId);
223
+ if (!flags) return true;
224
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
225
+ };
226
+
227
+
228
+ const rangeExtruders = new Map<string, number[]>();
229
+ const ranges = await text("Metadata/layer_config_ranges.xml");
230
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
231
+ const objectId = order[Number(object[1]) - 1];
232
+ if (!objectId) continue;
233
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
234
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
235
+ 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));
236
+ }
237
+ const toolChanges = new Map<number, number[]>();
238
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
239
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
240
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
241
+ if (!Number.isInteger(id)) continue;
242
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
243
+ .filter(layer => /\btype="2"/.test(layer[1]))
244
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
245
+ }
246
+
247
+ // Painting only matters for parts on a plate that is not sliced yet.
248
+ const paintPaths = new Set<string>();
249
+ for (const plate of plates) if (!plate.slicedFilamentIds) for (const objectId of plate.objectIds)
250
+ for (const path of components.get(objectId)?.values() ?? []) paintPaths.add(path);
251
+ const painting = await readPainting(zip, paintPaths);
252
+
253
+ const global = (key: string) => intOf(config[key]) ?? 0;
254
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"] as const;
255
+ const result = new Map<number, PlateFilament[]>();
256
+ for (const plate of plates) {
257
+ const used = new Map<number, string | undefined>();
258
+ const add = (index: number | undefined, name?: string) => {
259
+ if (!valid(index)) return;
260
+ if (!used.has(index) || (!used.get(index) && name)) used.set(index, name || undefined);
261
+ };
262
+ // An object counts once on a plate when any of its copies there prints.
263
+ const printing = plate.instances?.length
264
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
265
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
266
+ for (const objectId of printing) {
267
+ const object = objects.get(objectId);
268
+ if (!object) continue;
269
+ const objectInt = (key: string) => intOf(object.settings.get(key));
270
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() as Settings }];
271
+ for (const part of parts) {
272
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype)) continue;
273
+ const partInt = (key: string) => intOf(part.settings.get(key));
274
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
275
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
276
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
277
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
278
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
279
+ const label = part.name || object.name;
280
+ const path = components.get(objectId)?.get(part.id);
281
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
282
+ for (const state of paint?.states ?? []) if (part.subtype === "normal_part") add(state, label);
283
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
284
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
285
+ if (extruderSet) add(ownExtruder, label);
286
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
287
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
288
+ else for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1, label);
289
+ }
290
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
291
+ const own = partInt(key);
292
+ if (own !== undefined) { if (own > 0) add(own, label); }
293
+ else if ((objectInt(key) ?? 0) > 0) add(objectInt(key), label);
294
+ }
295
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
296
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
297
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
298
+ }
299
+ for (const extruder of rangeExtruders.get(objectId) ?? []) add(extruder, object.name);
300
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
301
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
302
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
303
+ const setting = (key: string) => object.settings.has(key) ? object.settings.get(key) : config[key];
304
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
305
+ if (support) {
306
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
307
+ add(intOf(setting("support_interface_filament")) || undefined);
308
+ add(intOf(setting("support_filament")) || undefined);
309
+ }
310
+ }
311
+ for (const extruder of toolChanges.get(plate.number) ?? []) add(extruder);
312
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
313
+ // else filament 1 (ModelVolume::extruder_id's default).
314
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
315
+ for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1);
316
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
317
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
318
+ const mixed = Array.isArray(config.filament_is_mixed) ? (config.filament_is_mixed as unknown[]).map(value => boolOf(value) === true) : [];
319
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? (config.filament_mixed_components as unknown[]).map(String) : [];
320
+ if (mixed.some(Boolean)) for (const [index, name] of [...used]) {
321
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length) continue;
322
+ used.delete(index);
323
+ for (const part of mixedComponents[index - 1].split(",")) {
324
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
325
+ if (component >= 1) add(component, name);
326
+ }
327
+ }
328
+ if (plate.slicedFilamentIds) {
329
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
330
+ const names = new Map(used);
331
+ used.clear();
332
+ for (const id of plate.slicedFilamentIds) add(id + 1, names.get(id + 1));
333
+ }
334
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
335
+ }
336
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
337
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
338
+ }
package/src/index.ts CHANGED
@@ -60,7 +60,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
60
60
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
61
61
  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";
62
62
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake, type BlenderAddonHandshake } from "./design-app-setup.js";
63
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
63
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
64
64
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
65
65
  import type { ThreeMFAmsRequirements } from "./types.js";
66
66
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
@@ -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" ? {} : {
@@ -1835,7 +1829,8 @@ class BambuPrinterMCPServer {
1835
1829
  const resumeFile = await checkedFile(inspection, snapshot);
1836
1830
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1837
1831
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1838
- let mapping = finalAmsMapping?.slice();
1832
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1833
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1839
1834
  if (finalAmsSlots) {
1840
1835
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length) throw new Error("ams_slots must supply exactly one physical tray per used filament.");
1841
1836
  mapping = Array(inspection.materials.length).fill(-1);
@@ -2227,11 +2222,6 @@ class BambuPrinterMCPServer {
2227
2222
  }
2228
2223
 
2229
2224
  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
2225
  const autoSliceOptions: BambuSliceOptions = {
2236
2226
  ...(slicerType === "orca-slicer-api" ? {} : {
2237
2227
  uptodate: true, ensureOnBed: true, minSave: true, skipModifiedGcodes: true,
@@ -2579,7 +2569,7 @@ class BambuPrinterMCPServer {
2579
2569
  },
2580
2570
  {
2581
2571
  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.",
2572
+ 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.",
2583
2573
  inputSchema: {
2584
2574
  type: "object",
2585
2575
  properties: {
@@ -2591,7 +2581,7 @@ class BambuPrinterMCPServer {
2591
2581
  },
2592
2582
  {
2593
2583
  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.",
2584
+ 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
2585
  inputSchema: {
2596
2586
  type: "object",
2597
2587
  properties: {
@@ -2742,7 +2732,7 @@ class BambuPrinterMCPServer {
2742
2732
  bed_type: {
2743
2733
  type: "string",
2744
2734
  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."
2735
+ description: "Bed plate type for slicing (default: textured_plate)."
2746
2736
  },
2747
2737
  nozzle_type: {
2748
2738
  type: "string",
@@ -2803,7 +2793,7 @@ class BambuPrinterMCPServer {
2803
2793
  bed_type: {
2804
2794
  type: "string",
2805
2795
  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."
2796
+ description: "Bed plate type for slicing (default: textured_plate)."
2807
2797
  },
2808
2798
  nozzle_type: {
2809
2799
  type: "string",
@@ -2822,7 +2812,7 @@ class BambuPrinterMCPServer {
2822
2812
  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
2813
  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
2814
  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." },
2815
+ 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
2816
  load_filaments: { type: "string", description: "Override filament profiles. Semicolon-separated paths to filament JSON configs, e.g. 'pla_basic.json;petg_cf.json'." },
2827
2817
  filament_profile: { type: "string", description: "Compatibility alias for load_filaments. Semicolon-separated Orca/Bambu filament profile JSON paths." },
2828
2818
  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 +3270,7 @@ class BambuPrinterMCPServer {
3280
3270
  properties: {
3281
3271
  object_ids: {
3282
3272
  type: "array",
3283
- description: "Object IDs to skip. Use list_3mf_plate_objects on the sliced 3MF to find IDs.",
3273
+ description: "identify_id values of the object copies to skip. Use list_3mf_plate_objects on the sliced 3MF to find them.",
3284
3274
  items: { type: "number" }
3285
3275
  },
3286
3276
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
@@ -3384,7 +3374,7 @@ class BambuPrinterMCPServer {
3384
3374
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
3385
3375
  ams_mapping: {
3386
3376
  type: "array",
3387
- 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.",
3377
+ 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.",
3388
3378
  items: { type: "number" }
3389
3379
  },
3390
3380
  ams_slots: {
@@ -4740,11 +4730,6 @@ class BambuPrinterMCPServer {
4740
4730
  }
4741
4731
  if (!hasGcode) {
4742
4732
  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
4733
  console.error(`3MF has no gcode — auto-slicing with ${slicerType} for ${printModel}`);
4749
4734
  const autoSliceOptions: BambuSliceOptions = {
4750
4735
  ...(slicerType === "orca-slicer-api" ? { slicePlate: plateIndex + 1 } : {
@@ -4753,7 +4738,8 @@ class BambuPrinterMCPServer {
4753
4738
  bedType: printBedType,
4754
4739
  nozzleType: resolveNozzleType(args?.nozzle_type),
4755
4740
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
4756
- ...(pauseLayers ? { pauseAtLayers: pauseLayers } : {}),
4741
+ // A pause belongs to the plate being printed; the CLI carries custom G-code for one plate only.
4742
+ ...(pauseLayers ? { pauseAtLayers: pauseLayers, slicePlate: plateIndex + 1 } : {}),
4757
4743
  };
4758
4744
  if (!explicitSlicerProfile) {
4759
4745
  try {
@@ -14,7 +14,7 @@ import { Readable } from "node:stream";
14
14
  import { readSafe3mfArchive } from "../safety/archive.js";
15
15
  import { inspectPrintFile, type PrintFileInspection } 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, type PrinterStateRequirements } 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";
@@ -1175,7 +1175,9 @@ export class BambuImplementation {
1175
1175
  let baseMapping: number[];
1176
1176
  if (options.amsMapping && options.amsMapping.length > 0) {
1177
1177
  for (const v of options.amsMapping) validateTrayValue(v, "ams_mapping");
1178
- baseMapping = options.amsMapping.slice();
1178
+ // Bambu Studio sends a tray only for the filaments the plate prints and -1 for every other project filament
1179
+ // (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500): so does this route.
1180
+ baseMapping = studioAmsMapping(options.amsMapping, inspection.usedFilamentPositions);
1179
1181
  } else if (options.amsSlots && options.amsSlots.length > 0) {
1180
1182
  for (const v of options.amsSlots) validateTrayValue(v, "amsSlots");
1181
1183
  const positions = projectMetadata.usedFilamentPositions;
@@ -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
+ }