bambu-printer-mcp 1.1.93 → 1.1.94

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.
@@ -16,8 +16,11 @@ import { randomUUID } from "node:crypto";
16
16
  import fs from "node:fs/promises";
17
17
  import path from "node:path";
18
18
  import JSZip from "jszip";
19
+ import { SaxesParser } from "saxes";
19
20
  import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
20
21
  import { MACHINE_LIMITS, normalizeModel } from "../safety/limits.js";
22
+ import { readSafe3mfArchive } from "../safety/archive.js";
23
+ import { listModelPlates } from "./model-plates.js";
21
24
  import { COUNTERPART_CONTRACT } from "./schemas.js";
22
25
 
23
26
  const MAX_PARTS = 64;
@@ -28,6 +31,8 @@ const PART_KEYS = new Set(["stl_path", "name", "filament"]);
28
31
 
29
32
  export class Make3mfError extends Error {}
30
33
 
34
+ const isFilament = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_FILAMENT;
35
+
31
36
  type Mesh = { vertices: Float32Array; indices: Uint32Array; triangles: number; min: number[]; max: number[] };
32
37
  type Part = { name: string; stlPath: string; filament: number; mesh: Mesh };
33
38
  export type Make3mfResult = {
@@ -89,47 +94,87 @@ async function readMesh(filePath: string, label: string): Promise<Mesh> {
89
94
  /** Shortest decimal that reads back as the same float32. */
90
95
  const coordinate = (value: number) => String(Number(value.toPrecision(9)));
91
96
 
92
- /** The model XML as buffers, so a large mesh never becomes one giant string. */
93
- function modelXml(parts: Part[], transform: number[]): Buffer {
97
+ /** One object of a project: an assembly of parts, placed on a plate (1-based). */
98
+ type Assembly = { name: string; plate: number; parts: Part[] };
99
+
100
+ /** Buffered XML, so a large mesh never becomes one giant string. */
101
+ function bufferWriter() {
94
102
  const chunks: Buffer[] = [];
95
103
  let pending: string[] = [];
96
- const write = (line: string) => {
97
- pending.push(line);
98
- if (pending.length >= 20_000) { chunks.push(Buffer.from(pending.join(""))); pending = []; }
104
+ return {
105
+ write(line: string) {
106
+ pending.push(line);
107
+ if (pending.length >= 20_000) { chunks.push(Buffer.from(pending.join(""))); pending = []; }
108
+ },
109
+ done(): Buffer { chunks.push(Buffer.from(pending.join(""))); pending = []; return Buffer.concat(chunks); },
99
110
  };
111
+ }
112
+
113
+ /** A mesh's <mesh> element. */
114
+ function writeMesh(write: (line: string) => void, mesh: Mesh) {
115
+ const { vertices, indices } = mesh;
116
+ write(` <mesh>\n <vertices>\n`);
117
+ for (let i = 0; i < vertices.length; i += 3) write(` <vertex x="${coordinate(vertices[i])}" y="${coordinate(vertices[i + 1])}" z="${coordinate(vertices[i + 2])}"/>\n`);
118
+ write(` </vertices>\n <triangles>\n`);
119
+ for (let i = 0; i < indices.length; i += 3) write(` <triangle v1="${indices[i]}" v2="${indices[i + 1]}" v3="${indices[i + 2]}"/>\n`);
120
+ write(` </triangles>\n </mesh>\n`);
121
+ }
122
+
123
+ /** The model XML: every part's mesh object (ids 1..P), then one assembly object per object, one build item each. */
124
+ function modelXml(objects: Assembly[], transforms: number[][], application: string): Buffer {
125
+ const { write, done } = bufferWriter();
100
126
  write(`<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021">\n`);
101
- write(` <metadata name="Application">bambu-printer-mcp counterpart_make_3mf</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`);
127
+ write(` <metadata name="Application">${application}</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`);
128
+ const parts = objects.flatMap(object => object.parts);
102
129
  parts.forEach((part, index) => {
103
- write(` <object id="${index + 1}" type="model">\n <mesh>\n <vertices>\n`);
104
- const { vertices, indices } = part.mesh;
105
- for (let i = 0; i < vertices.length; i += 3) write(` <vertex x="${coordinate(vertices[i])}" y="${coordinate(vertices[i + 1])}" z="${coordinate(vertices[i + 2])}"/>\n`);
106
- write(` </vertices>\n <triangles>\n`);
107
- for (let i = 0; i < indices.length; i += 3) write(` <triangle v1="${indices[i]}" v2="${indices[i + 1]}" v3="${indices[i + 2]}"/>\n`);
108
- write(` </triangles>\n </mesh>\n </object>\n`);
130
+ write(` <object id="${index + 1}" type="model">\n`);
131
+ writeMesh(write, part.mesh);
132
+ write(` </object>\n`);
109
133
  });
110
- const assembly = parts.length + 1;
111
- write(` <object id="${assembly}" type="model">\n <components>\n`);
112
- parts.forEach((_, index) => write(` <component objectid="${index + 1}"/>\n`));
113
- write(` </components>\n </object>\n </resources>\n <build>\n`);
114
- write(` <item objectid="${assembly}" transform="1 0 0 0 1 0 0 0 1 ${transform.map(coordinate).join(" ")}"/>\n </build>\n</model>\n`);
115
- chunks.push(Buffer.from(pending.join("")));
116
- return Buffer.concat(chunks);
117
- }
118
-
119
- function modelSettingsXml(parts: Part[], name: string): string {
120
- const assembly = parts.length + 1;
121
- const partBlocks = parts.map((part, index) => ` <part id="${index + 1}" subtype="normal_part">
134
+ let first = 1;
135
+ objects.forEach((object, index) => {
136
+ write(` <object id="${parts.length + 1 + index}" type="model">\n <components>\n`);
137
+ object.parts.forEach((_, at) => write(` <component objectid="${first + at}"/>\n`));
138
+ first += object.parts.length;
139
+ write(` </components>\n </object>\n`);
140
+ });
141
+ write(` </resources>\n <build>\n`);
142
+ objects.forEach((_, index) => write(` <item objectid="${parts.length + 1 + index}" transform="1 0 0 0 1 0 0 0 1 ${transforms[index].map(coordinate).join(" ")}"/>\n`));
143
+ write(` </build>\n</model>\n`);
144
+ return done();
145
+ }
146
+
147
+ function modelSettingsXml(objects: Assembly[], plates: number): string {
148
+ const partCount = objects.reduce((sum, object) => sum + object.parts.length, 0);
149
+ let first = 1;
150
+ const blocks = objects.map((object, index) => {
151
+ const partBlocks = object.parts.map((part, at) => ` <part id="${first + at}" subtype="normal_part">
122
152
  <metadata key="name" value="${xmlAttribute(part.name)}"/>
123
153
  <metadata key="extruder" value="${part.filament}"/>
124
154
  </part>`).join("\n");
125
- return `<?xml version="1.0" encoding="UTF-8"?>
126
- <config>
127
- <object id="${assembly}">
128
- <metadata key="name" value="${xmlAttribute(name)}"/>
129
- <metadata key="extruder" value="${parts[0].filament}"/>
155
+ first += object.parts.length;
156
+ return ` <object id="${partCount + 1 + index}">
157
+ <metadata key="name" value="${xmlAttribute(object.name)}"/>
158
+ <metadata key="extruder" value="${object.parts[0].filament}"/>
130
159
  ${partBlocks}
131
160
  </object>
132
- </config>
161
+ `;
162
+ }).join("");
163
+ // Plates only when the project uses more than one, so a one-plate file stays as counterpart_make_3mf always wrote it.
164
+ const plateBlocks = plates <= 1 ? "" : Array.from({ length: plates }, (_, i) => ` <plate>
165
+ <metadata key="plater_id" value="${i + 1}"/>
166
+ <metadata key="plater_name" value=""/>
167
+ <metadata key="locked" value="false"/>
168
+ ${objects.flatMap((object, index) => object.plate !== i + 1 ? [] : [` <model_instance>
169
+ <metadata key="object_id" value="${partCount + 1 + index}"/>
170
+ <metadata key="instance_id" value="0"/>
171
+ <metadata key="identify_id" value="${partCount + 1 + index}"/>
172
+ </model_instance>
173
+ `]).join("")} </plate>
174
+ `).join("");
175
+ return `<?xml version="1.0" encoding="UTF-8"?>
176
+ <config>
177
+ ${blocks}${plateBlocks}</config>
133
178
  `;
134
179
  }
135
180
 
@@ -146,17 +191,43 @@ const RELATIONSHIPS = `<?xml version="1.0" encoding="UTF-8"?>
146
191
  </Relationships>
147
192
  `;
148
193
 
149
- /** Where the assembly's footprint centre goes: the configured model's bed centre, else a 256 mm bed's. */
150
- function plateCentre(): [number, number] {
194
+
195
+ /** The configured model's bed (width, depth), else a 256 mm bed. */
196
+ function bedSize(): [number, number] {
151
197
  const model = normalizeModel(process.env.BAMBU_PRINTER_MODEL || process.env.BAMBU_MODEL);
152
198
  const volume = model ? MACHINE_LIMITS[model]?.volume : undefined;
153
- return volume ? [volume[0] / 2, volume[1] / 2] : [128, 128];
199
+ return volume ? [volume[0], volume[1]] : [256, 256];
154
200
  }
155
201
 
156
- export async function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult> {
157
- if (Object.keys(args).some(key => key !== "parts" && key !== "out_path")) fail("counterpart_make_3mf accepts only parts and out_path.");
158
- if (!Array.isArray(args.parts) || args.parts.length === 0 || args.parts.length > MAX_PARTS) fail(`parts must list 1 to ${MAX_PARTS} STL parts.`);
159
- const requested = path.resolve(nonEmptyText(args.out_path, "out_path"));
202
+ /**
203
+ * Where plate N (1-based) starts in the build frame, as Bambu Studio lays plates out (PartPlateList::compute_origin
204
+ * and compute_colum_count): about sqrt(count) columns, each plate a bed plus a fifth from the next, rows toward -Y.
205
+ */
206
+ function plateOrigin(plate: number, plates: number, [width, depth]: [number, number]): [number, number] {
207
+ const root = Math.sqrt(plates), rounded = Math.round(root);
208
+ const columns = root > rounded ? rounded + 1 : rounded;
209
+ const index = plate - 1;
210
+ return [(index % columns) * width * 1.2, -Math.floor(index / columns) * depth * 1.2];
211
+ }
212
+
213
+ /** One shared translation per plate: its objects keep their relative positions, centred on the plate, lowest point on the bed. */
214
+ function plateTransforms(objects: Assembly[]): number[][] {
215
+ const bed = bedSize();
216
+ const plates = Math.max(...objects.map(object => object.plate));
217
+ const shift = new Map<number, number[]>();
218
+ for (const plate of new Set(objects.map(object => object.plate))) {
219
+ const parts = objects.filter(object => object.plate === plate).flatMap(object => object.parts);
220
+ const min = [0, 1, 2].map(axis => Math.min(...parts.map(part => part.mesh.min[axis])));
221
+ const max = [0, 1, 2].map(axis => Math.max(...parts.map(part => part.mesh.max[axis])));
222
+ const [x, y] = plateOrigin(plate, plates, bed);
223
+ shift.set(plate, [x + bed[0] / 2 - (min[0] + max[0]) / 2, y + bed[1] / 2 - (min[1] + max[1]) / 2, -min[2]]);
224
+ }
225
+ return objects.map(object => shift.get(object.plate)!);
226
+ }
227
+
228
+ /** A new path, refusing one that exists; its parent directory must exist. */
229
+ async function newOutPath(value: unknown): Promise<string> {
230
+ const requested = path.resolve(nonEmptyText(value, "out_path"));
160
231
  if (path.extname(requested).toLowerCase() !== ".3mf") fail("out_path must name a new .3mf file.");
161
232
  const directory = await fs.realpath(path.dirname(requested)).catch(() => fail("out_path parent directory must already exist."));
162
233
  const outPath = path.join(directory, path.basename(requested));
@@ -165,6 +236,34 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
165
236
  return undefined;
166
237
  });
167
238
  if (existing) fail("out_path already exists; choose a new file. Existing files are never overwritten.");
239
+ return outPath;
240
+ }
241
+
242
+ /** Publish bytes at a new path without replacing anything that appeared there since it was checked. */
243
+ async function publish(outPath: string, bytes: Buffer): Promise<void> {
244
+ const staged = path.join(path.dirname(outPath), `.counterpart-${randomUUID()}.3mf`);
245
+ try {
246
+ await fs.writeFile(staged, bytes, { flag: "wx" });
247
+ // link() publishes without replacing a file created since the check above.
248
+ await fs.link(staged, outPath).catch(() => fail("Cannot write out_path; it may already exist or be unwritable."));
249
+ } finally {
250
+ await fs.rm(staged, { force: true }).catch(() => {});
251
+ }
252
+ }
253
+
254
+ async function writeAssemblies(objects: Assembly[], outPath: string, application: string): Promise<void> {
255
+ const zip = new JSZip();
256
+ zip.file("[Content_Types].xml", CONTENT_TYPES);
257
+ zip.file("_rels/.rels", RELATIONSHIPS);
258
+ zip.file("3D/3dmodel.model", modelXml(objects, plateTransforms(objects), application));
259
+ zip.file("Metadata/model_settings.config", modelSettingsXml(objects, Math.max(...objects.map(object => object.plate))));
260
+ await publish(outPath, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } }));
261
+ }
262
+
263
+ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult> {
264
+ if (Object.keys(args).some(key => key !== "parts" && key !== "out_path")) fail("counterpart_make_3mf accepts only parts and out_path.");
265
+ if (!Array.isArray(args.parts) || args.parts.length === 0 || args.parts.length > MAX_PARTS) fail(`parts must list 1 to ${MAX_PARTS} STL parts.`);
266
+ const outPath = await newOutPath(args.out_path);
168
267
 
169
268
  const parts: Part[] = [];
170
269
  let triangles = 0;
@@ -177,35 +276,13 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
177
276
  const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
178
277
  if (path.extname(stlPath).toLowerCase() !== ".stl") fail(`${label}.stl_path must name an STL file.`);
179
278
  const filament = entry.filament ?? index + 1;
180
- if (typeof filament !== "number" || !Number.isInteger(filament) || filament < 1 || filament > MAX_FILAMENT) {
181
- fail(`${label}.filament must be an integer from 1 to ${MAX_FILAMENT}.`);
182
- }
279
+ if (!isFilament(filament)) fail(`${label}.filament must be an integer from 1 to ${MAX_FILAMENT}.`);
183
280
  const mesh = await readMesh(await fs.realpath(stlPath).catch(() => fail(`${label}.stl_path does not exist.`)), `${label}.stl_path`);
184
281
  triangles += mesh.triangles;
185
282
  if (triangles > MAX_TOTAL_TRIANGLES) fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
186
283
  parts.push({ name, stlPath, filament, mesh });
187
284
  }
188
-
189
- // One shared translation: footprint centred on the plate, lowest point on the bed.
190
- const min = [0, 1, 2].map(axis => Math.min(...parts.map(part => part.mesh.min[axis])));
191
- const max = [0, 1, 2].map(axis => Math.max(...parts.map(part => part.mesh.max[axis])));
192
- const [centreX, centreY] = plateCentre();
193
- const transform = [centreX - (min[0] + max[0]) / 2, centreY - (min[1] + max[1]) / 2, -min[2]];
194
-
195
- const zip = new JSZip();
196
- zip.file("[Content_Types].xml", CONTENT_TYPES);
197
- zip.file("_rels/.rels", RELATIONSHIPS);
198
- zip.file("3D/3dmodel.model", modelXml(parts, transform));
199
- zip.file("Metadata/model_settings.config", modelSettingsXml(parts, path.basename(outPath, path.extname(outPath))));
200
- const bytes = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } });
201
- const staged = path.join(directory, `.counterpart-${randomUUID()}.3mf`);
202
- try {
203
- await fs.writeFile(staged, bytes, { flag: "wx" });
204
- // link() publishes without replacing a file created since the check above.
205
- await fs.link(staged, outPath).catch(() => fail("Cannot write out_path; it may already exist or be unwritable."));
206
- } finally {
207
- await fs.rm(staged, { force: true }).catch(() => {});
208
- }
285
+ await writeAssemblies([{ name: path.basename(outPath, path.extname(outPath)), plate: 1, parts }], outPath, "bambu-printer-mcp counterpart_make_3mf");
209
286
  return {
210
287
  contract: COUNTERPART_CONTRACT,
211
288
  path: outPath,
@@ -214,3 +291,311 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
214
291
  parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
215
292
  };
216
293
  }
294
+
295
+ // --- cad_run 3MF projects (project_3mf in a design script) --------------------------------------------------------
296
+
297
+ const MAX_PLATES = 64;
298
+ const MAX_EDIT_SETTINGS_BYTES = 8 * 1024 * 1024;
299
+ const MAX_EDIT_MODEL_BYTES = 64 * 1024 * 1024;
300
+ const MAX_EDIT_TOTAL_BYTES = 128 * 1024 * 1024;
301
+ const IDENTITY_COMPONENT = "1 0 0 0 1 0 0 0 1 0 0 0";
302
+ const IDENTITY_MATRIX = "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1";
303
+ type ProjectEdit =
304
+ | { op: "add_part"; object_id: number; name: string; filament: number; stl: number }
305
+ | { op: "replace_part"; object_id: number; part_id: number; path: string; stl: number }
306
+ | { op: "set_part"; object_id: number; part_id: number; name?: string; filament?: number };
307
+
308
+ const isId = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
309
+ const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
310
+
311
+ /** One element by tag and id in XML text: its start offset, end offset and full text. */
312
+ function elementById(xml: string, tag: string, id: number): { start: number; end: number; text: string } | undefined {
313
+ const pattern = new RegExp(`<((?:\\w+:)?${tag})\\b[^>]*\\bid="${id}"[^>]*?(?:/>|>[\\s\\S]*?</\\1>)`, "g");
314
+ const match = pattern.exec(xml);
315
+ return match ? { start: match.index, end: match.index + match[0].length, text: match[0] } : undefined;
316
+ }
317
+
318
+ /**
319
+ * Whether XML text is a 3MF model document: well-formed, a <model> root and one <resources> directly under it, closed
320
+ * once in the text, so a splice at its close lands inside the model's resources and nowhere else.
321
+ */
322
+ function isModelDocument(xml: string): boolean {
323
+ if ((xml.match(/<\/(?:\w+:)?resources\s*>/g) ?? []).length !== 1) return false;
324
+ // A self-closing <resources/> has no close tag of its own, so the one "</resources>" the text holds (in a comment, say)
325
+ // is not the element's: the splice would land there. Refused.
326
+ let depth = 0, root = "", resources = 0, selfClosed = false;
327
+ try {
328
+ const parser = new SaxesParser({ xmlns: false });
329
+ parser.on("error", error => { throw error; });
330
+ parser.on("opentag", tag => {
331
+ const local = tag.name.replace(/^\w+:/, "");
332
+ if (depth === 0) root = local;
333
+ else if (depth === 1 && local === "resources") { resources += 1; if (tag.isSelfClosing) selfClosed = true; }
334
+ depth += 1;
335
+ });
336
+ parser.on("closetag", () => { depth -= 1; });
337
+ parser.write(xml).close();
338
+ } catch { return false; }
339
+ return root === "model" && resources === 1 && !selfClosed;
340
+ }
341
+
342
+ /** The prefix a document binds to the 3MF production extension, if any. */
343
+ const productionPrefix = (xml: string) => /\bxmlns:(\w+)="http:\/\/schemas\.microsoft\.com\/3dmanufacturing\/production\/2015\/06"/.exec(xml)?.[1];
344
+
345
+ /** A mesh as <mesh> text, for splicing into an existing model part. */
346
+ function meshText(mesh: Mesh): string {
347
+ const { write, done } = bufferWriter();
348
+ writeMesh(write, mesh);
349
+ return done().toString("utf8");
350
+ }
351
+
352
+ function setMetadata(block: string, key: string, value: string): string {
353
+ const entry = `<metadata key="${key}" value="${xmlAttribute(value)}"/>`;
354
+ const existing = new RegExp(`<metadata\\s+key="${escapeRegExp(key)}"\\s+value="[^"]*"\\s*/>`);
355
+ if (existing.test(block)) return block.replace(existing, entry);
356
+ // A self-closing <part …/> opens up, so the metadata lands inside the part and not on its object.
357
+ const empty = /^<((?:\w+:)?part)\b([^>]*?)\s*\/>$/.exec(block);
358
+ if (empty) return `<${empty[1]}${empty[2]}>\n ${entry}\n </${empty[1]}>`;
359
+ return block.replace(/(<(?:\w+:)?part\b[^>]*>)/, `$1\n ${entry}`);
360
+ }
361
+
362
+ /**
363
+ * Write the 3MF a cad_run design script returned as project_3mf() (src/cad/project3mf.py): `manifest` is the
364
+ * sandbox's <name>.project.json, `partsDir` its STL parts, `inputs` the run's input snapshots by alias. A new project
365
+ * is written as counterpart_make_3mf writes one, an object per assembly on its plate. An edit copies the base 3MF and
366
+ * changes only what the script changed, so its print settings, painting, plates and other parts stay as they were.
367
+ */
368
+ export async function writeCadProject3mf(manifest: unknown, partsDir: string, inputs: Record<string, string>, outPath: string)
369
+ : Promise<{ base: string | null; changed: string[] }> {
370
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) fail("The design's 3MF project manifest is malformed.");
371
+ const project = manifest as Record<string, unknown>;
372
+ if (project.version !== 1) fail("The design's 3MF project manifest has an unknown version.");
373
+ let triangles = 0;
374
+ const stlIndexes = new Set<number>();
375
+ const partMesh = async (index: unknown, label: string): Promise<Mesh> => {
376
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= MAX_PARTS || stlIndexes.has(index)) fail(`${label} names no part file.`);
377
+ stlIndexes.add(index);
378
+ const mesh = await readMesh(path.join(partsDir, `${index}.stl`), label);
379
+ if ((triangles += mesh.triangles) > MAX_TOTAL_TRIANGLES) fail(`The project's new parts have more than ${MAX_TOTAL_TRIANGLES} triangles; decimate them first.`);
380
+ return mesh;
381
+ };
382
+ const text = (value: unknown, label: string) => nonEmptyText(value, label).trim().slice(0, 200);
383
+
384
+ if (project.base === null || project.base === undefined) {
385
+ if (!Array.isArray(project.objects) || !project.objects.length || project.objects.length > MAX_PARTS) fail("A new 3MF project needs 1 to 64 objects.");
386
+ const objects: Assembly[] = [];
387
+ for (const [index, value] of project.objects.entries()) {
388
+ const entry = value as Record<string, unknown>;
389
+ const plate = entry?.plate;
390
+ if (typeof plate !== "number" || !Number.isInteger(plate) || plate < 1 || plate > MAX_PLATES) fail(`objects[${index}].plate must be from 1 to ${MAX_PLATES}.`);
391
+ if (!Array.isArray(entry.parts) || !entry.parts.length) fail(`objects[${index}] has no parts.`);
392
+ const parts: Part[] = [];
393
+ for (const [at, part] of (entry.parts as Record<string, unknown>[]).entries()) {
394
+ if (!isFilament(part?.filament)) fail(`objects[${index}].parts[${at}].filament must be from 1 to ${MAX_FILAMENT}.`);
395
+ parts.push({ name: text(part.name, "part name"), stlPath: "", filament: part.filament, mesh: await partMesh(part.stl, `objects[${index}].parts[${at}]`) });
396
+ }
397
+ objects.push({ name: text(entry.name, "object name"), plate, parts });
398
+ }
399
+ await writeAssemblies(objects, outPath, "bambu-printer-mcp cad_run");
400
+ return { base: null, changed: objects.flatMap(object => object.parts.map(part => `${object.name}: ${part.name} (filament ${part.filament}, plate ${object.plate})`)) };
401
+ }
402
+
403
+ const alias = project.base;
404
+ if (typeof alias !== "string" || !Object.prototype.hasOwnProperty.call(inputs, alias)) fail("The 3MF project's base is not one of this run's inputs.");
405
+ const { zip } = await readSafe3mfArchive(inputs[alias]);
406
+ if (Object.keys(zip.files).some(name => /^Metadata\/plate_\d+\.gcode$/.test(name))) fail("The base 3MF holds G-code: edit the project file, not a sliced .gcode.3mf.");
407
+ // The base's files the edit rewrites become strings in this process: each is capped as list_3mf_plates caps what it
408
+ // reads (settings 8 MiB, a model part 64 MiB), and all of them together at 128 MiB.
409
+ const files = new Map<string, string>();
410
+ let textBytes = 0;
411
+ const read = async (name: string) => {
412
+ if (!files.has(name)) {
413
+ const file = zip.file(name);
414
+ if (!file) fail(`The base 3MF has no ${name}.`);
415
+ const bytes = await file.async("nodebuffer");
416
+ const cap = name.toLowerCase().endsWith(".model") ? MAX_EDIT_MODEL_BYTES : MAX_EDIT_SETTINGS_BYTES;
417
+ if (bytes.length > cap || (textBytes += bytes.length) > MAX_EDIT_TOTAL_BYTES)
418
+ fail(`The base 3MF's ${name} is too large to edit (settings up to ${MAX_EDIT_SETTINGS_BYTES / 1024 / 1024} MiB, a model part up to ${MAX_EDIT_MODEL_BYTES / 1024 / 1024} MiB, ${MAX_EDIT_TOTAL_BYTES / 1024 / 1024} MiB in all).`);
419
+ files.set(name, bytes.toString("utf8"));
420
+ }
421
+ return files.get(name)!;
422
+ };
423
+ const ROOT = "3D/3dmodel.model", SETTINGS = "Metadata/model_settings.config";
424
+ // A component's path comes from the untrusted base: only a model part may take a mesh.
425
+ const checkedModels = new Set<string>();
426
+ const readModel = async (name: string) => {
427
+ const model = await read(name);
428
+ if (!checkedModels.has(name)) {
429
+ if ((name !== ROOT && !name.toLowerCase().endsWith(".model")) || !isModelDocument(model)) fail(`The base 3MF's ${name} is not a 3MF model part; a part's mesh can only go into one.`);
430
+ checkedModels.add(name);
431
+ }
432
+ return model;
433
+ };
434
+ await readModel(ROOT);
435
+ await read(SETTINGS);
436
+ if (!Array.isArray(project.edits) || !project.edits.length || project.edits.length > 256) fail("A 3MF edit needs 1 to 256 edits.");
437
+ // A part can only print in a filament the project declares (none declared: the slicer's own list decides).
438
+ const declared = (await listModelPlates(inputs[alias], { paintLimits: { meshBytes: 0, totalBytes: 0 } })).project_filaments.length;
439
+ const declaredFilament = (value: unknown, label: string) => {
440
+ if (!isFilament(value)) fail(`${label} must be from 1 to ${MAX_FILAMENT}.`);
441
+ if (declared && value > declared) fail(`${label} ${value} is not one of the ${declared} filaments the base 3MF declares.`);
442
+ return value;
443
+ };
444
+ const changed: string[] = [];
445
+ // A component's or build item's reference, resolved: the model file it names (no path: the file it is written in;
446
+ // with or without one leading "/") and the object id there.
447
+ const reference = (attributes: string, file: string) => ({
448
+ id: Number(/\bobjectid="(\d+)"/.exec(attributes)?.[1]),
449
+ path: ((/\b(?:\w+:)?path="([^"]*)"/.exec(attributes)?.[1]) ?? "").replace(/^\//, "") || file,
450
+ });
451
+ const COMPONENT = /<(?:\w+:)?component\b([^>]*)\/?>/g;
452
+ // A root object's components: the file each part's mesh lives in and its id there.
453
+ const componentsOf = (objectId: number) => {
454
+ const object = elementById(files.get(ROOT)!, "object", objectId);
455
+ if (!object) fail(`The base 3MF has no object ${objectId}.`);
456
+ return [...object.text.matchAll(COMPONENT)].map(match => reference(match[1], ROOT));
457
+ };
458
+ const settingsObject = (objectId: number) => {
459
+ const block = elementById(files.get(SETTINGS)!, "object", objectId);
460
+ if (!block) fail(`The base 3MF's model_settings.config does not describe object ${objectId}.`);
461
+ return block;
462
+ };
463
+ // The components that assemblies inside the other model files hold, resolved once: an edit never changes them (it
464
+ // adds mesh objects to those files and re-points only root components). A file without the word "component" is
465
+ // skipped without becoming a string.
466
+ let partReferences: { id: number; path: string }[] | undefined;
467
+ const modelPartReferences = async () => {
468
+ if (!partReferences) {
469
+ partReferences = [];
470
+ for (const [name, entry] of Object.entries(zip.files)) {
471
+ if (entry.dir || name === ROOT || !name.toLowerCase().endsWith(".model")) continue;
472
+ let xml = files.get(name);
473
+ if (xml === undefined) {
474
+ const bytes = await entry.async("nodebuffer");
475
+ if (!bytes.includes("component")) continue;
476
+ if (bytes.length > MAX_EDIT_MODEL_BYTES) fail(`The base 3MF's ${name} is too large to edit (a model part up to ${MAX_EDIT_MODEL_BYTES / 1024 / 1024} MiB).`);
477
+ xml = bytes.toString("utf8");
478
+ }
479
+ for (const match of xml.matchAll(COMPONENT)) partReferences.push(reference(match[1], name));
480
+ }
481
+ }
482
+ return partReferences;
483
+ };
484
+ // Every use of mesh resource `id` in model file `target`: the root model's components and build items (a build item
485
+ // may place another file's object through p:path), and the components of assemblies in any model part.
486
+ const usesOf = async (target: string, id: number) => {
487
+ const root = [...files.get(ROOT)!.matchAll(/<(?:\w+:)?(?:component|item)\b([^>]*)\/?>/g)].map(match => reference(match[1], ROOT));
488
+ return [...root, ...await modelPartReferences()].filter(entry => entry.id === id && entry.path === target).length;
489
+ };
490
+ // A part given its own copy of a shared mesh: (object, model file, original part id) -> the copy's id, so a later edit
491
+ // of the same part finds it.
492
+ const copies = new Map<string, number>();
493
+ const partKey = (objectId: number, file: string, partId: number) => `${objectId}\n${file}\n${partId}`;
494
+ const currentId = (objectId: number, file: string, partId: number) => copies.get(partKey(objectId, file, partId)) ?? partId;
495
+ for (const [index, value] of project.edits.entries()) {
496
+ const edit = value as ProjectEdit;
497
+ if (!edit || typeof edit !== "object" || !isId(edit.object_id)) fail(`edits[${index}] is malformed.`);
498
+ if (edit.op === "add_part") {
499
+ declaredFilament(edit.filament, `edits[${index}].filament`);
500
+ const name = text(edit.name, "part name");
501
+ const components = componentsOf(edit.object_id);
502
+ if (!components.length) fail(`Object ${edit.object_id} is a single mesh without parts; a part can only join an object made of parts.`);
503
+ const target = components[0].path;
504
+ const model = await readModel(target);
505
+ const ids = [...model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"/g)].map(match => Number(match[1]));
506
+ const id = Math.max(0, ...ids, ...components.map(component => component.id)) + 1;
507
+ const filePrefix = productionPrefix(model);
508
+ const objectXml = ` <object id="${id}"${filePrefix ? ` ${filePrefix}:UUID="${randomUUID()}"` : ""} type="model">\n${meshText(await partMesh(edit.stl, `edits[${index}]`))} </object>\n `;
509
+ // A mesh kept in the root model goes before the object that uses it: the 3MF core forbids forward references.
510
+ const at = target === ROOT ? elementById(model, "object", edit.object_id)!.start : model.lastIndexOf("</resources>");
511
+ if (at < 0) fail(`${target} has no resources.`);
512
+ files.set(target, model.slice(0, at) + objectXml + model.slice(at));
513
+ const root = files.get(ROOT)!;
514
+ const object = elementById(root, "object", edit.object_id)!;
515
+ const rootPrefix = productionPrefix(root);
516
+ if (target !== ROOT && !rootPrefix) fail("The base 3MF keeps parts in other model files without declaring the production extension.");
517
+ const component = `<component${target !== ROOT ? ` ${rootPrefix}:path="/${xmlAttribute(target)}"` : ""} objectid="${id}"${rootPrefix ? ` ${rootPrefix}:UUID="${randomUUID()}"` : ""} transform="${IDENTITY_COMPONENT}"/>`;
518
+ const close = object.text.search(/<\/(?:\w+:)?components>/);
519
+ files.set(ROOT, root.slice(0, object.start) + object.text.slice(0, close) + component + object.text.slice(close) + root.slice(object.end));
520
+ const settings = files.get(SETTINGS)!;
521
+ const block = settingsObject(edit.object_id);
522
+ const part = ` <part id="${id}" subtype="normal_part">\n <metadata key="name" value="${xmlAttribute(name)}"/>\n <metadata key="matrix" value="${IDENTITY_MATRIX}"/>\n <metadata key="extruder" value="${edit.filament}"/>\n </part>\n `;
523
+ const end = block.text.lastIndexOf("</object>");
524
+ files.set(SETTINGS, settings.slice(0, block.start) + block.text.slice(0, end) + part + block.text.slice(end) + settings.slice(block.end));
525
+ changed.push(`added ${name} to object ${edit.object_id} (filament ${edit.filament})`);
526
+ } else if (edit.op === "replace_part" || edit.op === "set_part") {
527
+ if (!isId(edit.part_id)) fail(`edits[${index}].part_id is malformed.`);
528
+ // A part is its (objectid, model file): two model files may reuse an object id.
529
+ const component = componentsOf(edit.object_id).find(entry => entry.id === currentId(edit.object_id, entry.path, edit.part_id)
530
+ && (edit.op !== "replace_part" || `/${entry.path}` === edit.path));
531
+ if (!component) fail(`Object ${edit.object_id} has no part ${edit.part_id}${edit.op === "replace_part" ? ` in ${String(edit.path).slice(0, 200)}` : ""}.`);
532
+ if (edit.op === "replace_part") {
533
+ let model = await readModel(component.path);
534
+ const mesh = elementById(model, "object", component.id);
535
+ if (!mesh || !/<(?:\w+:)?mesh\b/.test(mesh.text)) fail(`Part ${edit.part_id} of object ${edit.object_id} has no mesh to replace.`);
536
+ const fresh = meshText(await partMesh(edit.stl, `edits[${index}]`)).trim();
537
+ const next = mesh.text.replace(/<((?:\w+:)?mesh)\b[\s\S]*<\/\1>/, () => fresh);
538
+ // The edited object's own uses of the mesh (an object may place one mesh twice) all take the replacement.
539
+ const own = componentsOf(edit.object_id).filter(entry => entry.id === component.id && entry.path === component.path).length;
540
+ const others = await usesOf(component.path, component.id) - own;
541
+ if (others <= 0) {
542
+ files.set(component.path, model.slice(0, mesh.start) + next + model.slice(mesh.end));
543
+ changed.push(`replaced part ${edit.part_id} of object ${edit.object_id} (its painting, if any, went with the old mesh)`);
544
+ continue;
545
+ }
546
+ // Other objects use this mesh too: the edited object gets its own copy under a new id, and every other use
547
+ // keeps the original bytes. The copy follows the original, so it still precedes the objects that use it.
548
+ // Its id is new in its model file and among the root objects, so no settings entry can mistake it for another.
549
+ const ids = [model, files.get(ROOT)!].flatMap(xml => [...xml.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"/g)].map(match => Number(match[1])));
550
+ const id = Math.max(0, ...ids, ...componentsOf(edit.object_id).map(entry => entry.id)) + 1;
551
+ const copy = next.replace(/^<[^>]*>/, open => open
552
+ .replace(/\bid="\d+"/, `id="${id}"`)
553
+ .replace(/\b((?:\w+:)?UUID)="[^"]*"/g, (_, attribute) => `${attribute}="${randomUUID()}"`));
554
+ model = model.slice(0, mesh.end) + "\n " + copy + model.slice(mesh.end);
555
+ files.set(component.path, model);
556
+ // Point the edited object's components at the copy.
557
+ const root = files.get(ROOT)!;
558
+ const object = elementById(root, "object", edit.object_id)!;
559
+ const objectText = object.text.replace(COMPONENT, (tag, attributes: string) => {
560
+ const target = reference(attributes, ROOT);
561
+ if (target.path !== component.path || target.id !== component.id) return tag;
562
+ return tag.replace(/\bobjectid="\d+"/, `objectid="${id}"`);
563
+ });
564
+ files.set(ROOT, root.slice(0, object.start) + objectText + root.slice(object.end));
565
+ // Its part settings (name, filament) move to the copy's id; other objects' settings stay as they were.
566
+ const settings = files.get(SETTINGS)!;
567
+ const block = elementById(settings, "object", edit.object_id);
568
+ const part = block && elementById(block.text, "part", component.id);
569
+ if (block && part) {
570
+ const renamed = part.text.replace(/^(<(?:\w+:)?part\b[^>]*?\bid=")\d+"/, `$1${id}"`);
571
+ const updated = block.text.slice(0, part.start) + renamed + block.text.slice(part.end);
572
+ files.set(SETTINGS, settings.slice(0, block.start) + updated + settings.slice(block.end));
573
+ }
574
+ copies.set(partKey(edit.object_id, component.path, edit.part_id), id);
575
+ changed.push(`replaced part ${edit.part_id} of object ${edit.object_id} with its own copy, now part ${id}: ${others} other use${others === 1 ? "" : "s"} of the shared mesh keep the original (its painting, if any, went with the old mesh)`);
576
+ } else {
577
+ const settings = files.get(SETTINGS)!;
578
+ const block = settingsObject(edit.object_id);
579
+ const part = elementById(block.text, "part", component.id);
580
+ if (!part) fail(`model_settings.config has no part ${edit.part_id} in object ${edit.object_id}.`);
581
+ let next = part.text;
582
+ if (edit.name !== undefined) next = setMetadata(next, "name", text(edit.name, "part name"));
583
+ if (edit.filament !== undefined) {
584
+ declaredFilament(edit.filament, `edits[${index}].filament`);
585
+ next = setMetadata(next, "extruder", String(edit.filament));
586
+ }
587
+ const updated = block.text.slice(0, part.start) + next + block.text.slice(part.end);
588
+ files.set(SETTINGS, settings.slice(0, block.start) + updated + settings.slice(block.end));
589
+ changed.push(`set part ${edit.part_id} of object ${edit.object_id}:${edit.name !== undefined ? ` name ${edit.name}` : ""}${edit.filament !== undefined ? ` filament ${edit.filament}` : ""}`);
590
+ }
591
+ } else fail(`edits[${index}].op is unknown.`);
592
+ }
593
+ // A fresh archive with the base's files in their order: JSZip would otherwise add directory entries the base never had.
594
+ const output = new JSZip();
595
+ for (const [name, entry] of Object.entries(zip.files)) {
596
+ if (entry.dir) continue;
597
+ output.file(name, files.get(name) ?? await entry.async("nodebuffer"), { createFolders: false });
598
+ }
599
+ await publish(outPath, await output.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } }));
600
+ return { base: alias, changed };
601
+ }
@@ -8,7 +8,7 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
- import { PAINT_LIMITS, plateFilaments, type PaintLimits, type PlateFilament, type PlateLayout } from "./plate-filaments.js";
11
+ import { PAINT_LIMITS, plateFilaments, type PaintLimits, type PlateFilament, type PlateLayout, type PlatePart } from "./plate-filaments.js";
12
12
 
13
13
  export interface ModelPlate {
14
14
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
@@ -34,6 +34,13 @@ export interface ModelPlate {
34
34
  * so every declared filament is listed rather than risk leaving out one that prints. A client offers them all.
35
35
  */
36
36
  filaments_complete: boolean;
37
+ /**
38
+ * The root 3D/3dmodel.model build items on this plate, 0-based in build order (counterpart/1): the copies a client
39
+ * places to draw this plate from the open 3MF standard alone. Empty for a sliced-only file without a model.
40
+ */
41
+ build_items: number[];
42
+ /** Each model part of this plate's objects once, with the filament it prints in (counterpart/1; see PlatePart). */
43
+ parts: PlatePart[];
37
44
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
38
45
  thumbnail_png_base64?: string;
39
46
  }
@@ -108,7 +115,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
108
115
  const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
109
116
  return objectId ? [{ objectId, instanceId }] : [];
110
117
  }) });
111
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true,
118
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true, build_items: [], parts: [],
112
119
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
113
120
  }
114
121
  for (const name of Object.keys(zip.files)) {
@@ -116,7 +123,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
116
123
  if (!match) continue;
117
124
  const number = Number(match[1]);
118
125
  if (!valid(number)) continue;
119
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true };
126
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] };
120
127
  const layout = layouts.get(number) ?? { number, objectIds: [] };
121
128
  layouts.set(number, layout);
122
129
  if (match[2] === "gcode") plate.sliced = true;
@@ -134,9 +141,9 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
134
141
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
135
142
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
136
143
  if (!result.plates.length) {
137
- result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true });
144
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] });
138
145
  // Without plates every object is on the one plate.
139
- layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
146
+ layouts.set(1, { number: 1, allItems: true, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
140
147
  }
141
148
  const geometry = has("item") && (has("mesh") || has("component"));
142
149
  if (!geometry) {
@@ -153,6 +160,11 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
153
160
  for (const plate of result.plates) {
154
161
  plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
155
162
  plate.filaments_complete = !filaments.incomplete.has(plate.index + 1);
163
+ // A sliced-only file has no model to draw from.
164
+ if (geometry) {
165
+ plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
166
+ plate.parts = filaments.parts.get(plate.index + 1) ?? [];
167
+ }
156
168
  }
157
169
  result.project_filaments = filaments.project;
158
170
  if (options.thumbnails) for (const plate of result.plates) {