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.
@@ -0,0 +1,426 @@
1
+ """3MF project output for cad_run: project_3mf() inside build().
2
+
3
+ A design script returns a project_3mf() instead of a shape when the result is a multi-part, multi-colour 3MF:
4
+ either a new project (parts with names, filaments and plates) or an edit of a declared input 3MF (a designer's
5
+ project), which keeps everything it does not change: print settings, painting, plates and other parts.
6
+
7
+ This module runs inside the sandbox. It reads the input 3MF, tessellates the script's geometry and writes STL
8
+ parts plus a manifest into the job folder; the trusted MCP process writes the 3MF itself and checks it.
9
+ """
10
+ import json
11
+ import math
12
+ import re
13
+ import zipfile
14
+ import xml.etree.ElementTree as ET
15
+ from pathlib import Path
16
+
17
+ CORE = '{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}'
18
+ PRODUCTION = '{http://schemas.microsoft.com/3dmanufacturing/production/2015/06}'
19
+ ROOT_MODEL = '3D/3dmodel.model'
20
+ MAX_PARTS = 64
21
+ MAX_FILAMENT = 64
22
+ MAX_PLATES = 64
23
+ SKIPPED_SUBTYPES = ('negative_part', 'modifier_part', 'support_blocker', 'support_enforcer')
24
+
25
+
26
+ def _matrix(text):
27
+ """A 3MF transform (12 numbers, row vectors) as a 4x4 column-vector matrix."""
28
+ import numpy as np
29
+ m = np.eye(4)
30
+ if not text:
31
+ return m
32
+ values = [float(v) for v in text.split()]
33
+ if len(values) != 12 or not all(math.isfinite(v) for v in values):
34
+ raise ValueError('3MF transform must have 12 finite numbers.')
35
+ m[:3, :3] = np.array(values[:9]).reshape(3, 3).T
36
+ m[:3, 3] = values[9:]
37
+ return m
38
+
39
+
40
+ def _metadata(element):
41
+ return {m.get('key'): m.get('value', '') for m in element.findall('metadata') if m.get('key')}
42
+
43
+
44
+ def _int(value):
45
+ try:
46
+ number = int(str(value).strip())
47
+ except (TypeError, ValueError):
48
+ return 0
49
+ return number
50
+
51
+
52
+ class Part:
53
+ """A model part of a 3MF object: its mesh in the object's frame (component transform applied)."""
54
+
55
+ def __init__(self, object_id, part_id, path, name, filament, mesh, painted, local):
56
+ self.object_id = object_id
57
+ self.id = part_id
58
+ self.path = path
59
+ self.name = name
60
+ self.filament = filament
61
+ self.mesh = mesh
62
+ self.painted = painted
63
+ self._local = local # component transform: mesh coordinates -> object frame
64
+ self.plain = False # the object is this one mesh, without parts (a plain 3MF): it cannot be edited
65
+
66
+ def __repr__(self):
67
+ return f'Part(id={self.id}, name={self.name!r}, filament={self.filament}, painted={self.painted})'
68
+
69
+
70
+ class Object:
71
+ """A root object of the 3MF (what a build item places) with its parts."""
72
+
73
+ def __init__(self, object_id, name, plate, parts, placements):
74
+ self.id = object_id
75
+ self.name = name
76
+ self.plate = plate
77
+ self.parts = parts
78
+ self.placements = placements # build-item transforms: object frame -> plate (build) frame
79
+
80
+ def part(self, name_or_id):
81
+ for part in self.parts:
82
+ if str(part.id) == str(name_or_id) or part.name == name_or_id:
83
+ return part
84
+ raise ValueError(f'Object {self.name!r} has no part {name_or_id!r}.')
85
+
86
+ def __repr__(self):
87
+ return f'Object(id={self.id}, name={self.name!r}, plate={self.plate}, parts={self.parts!r})'
88
+
89
+
90
+ def _read(path):
91
+ """The input 3MF's objects with their parts as trimesh meshes in each object's frame."""
92
+ import numpy as np
93
+ import trimesh
94
+ with zipfile.ZipFile(path) as archive:
95
+ names = set(archive.namelist())
96
+ if ROOT_MODEL not in names:
97
+ raise ValueError('The input 3MF has no 3D/3dmodel.model.')
98
+ if any(re.fullmatch(r'Metadata/plate_\d+\.gcode', n) for n in names):
99
+ raise ValueError('The input 3MF holds G-code: edit the project file, not a sliced .gcode.3mf.')
100
+ # The input is a bounded snapshot (64 MiB): its model parts and settings are read once, here.
101
+ raw = {n: archive.read(n) for n in names if n.endswith('.model') or n in ('Metadata/model_settings.config', 'Metadata/project_settings.config')}
102
+ models = {}
103
+
104
+ def model(name):
105
+ name = name.lstrip('/')
106
+ if name not in models:
107
+ if name not in raw:
108
+ raise ValueError(f'The input 3MF names a missing model part {name}.')
109
+ models[name] = ET.fromstring(raw[name])
110
+ return models[name]
111
+
112
+ settings = ET.fromstring(raw['Metadata/model_settings.config']) if 'Metadata/model_settings.config' in raw else ET.Element('config')
113
+ root = model(ROOT_MODEL)
114
+ resources = {o.get('id'): o for o in root.iter(CORE + 'object')}
115
+ config = {o.get('id'): o for o in settings.findall('object')}
116
+ plate_of = {}
117
+ for plate in settings.findall('plate'):
118
+ number = _int(_metadata(plate).get('plater_id'))
119
+ for instance in plate.findall('model_instance'):
120
+ plate_of.setdefault(_metadata(instance).get('object_id'), number)
121
+ placements = {}
122
+ for item in root.iter(CORE + 'item'):
123
+ placements.setdefault(item.get('objectid'), []).append(_matrix(item.get('transform')))
124
+
125
+ def mesh_of(element):
126
+ mesh = element.find(CORE + 'mesh')
127
+ if mesh is None:
128
+ return None, False
129
+ vertices = np.array([[float(v.get(a)) for a in 'xyz'] for v in mesh.iter(CORE + 'vertex')], dtype=float).reshape(-1, 3)
130
+ triangles = list(mesh.iter(CORE + 'triangle'))
131
+ faces = np.array([[int(t.get(a)) for a in ('v1', 'v2', 'v3')] for t in triangles], dtype=np.int64).reshape(-1, 3)
132
+ painted = any(t.get('paint_color') for t in triangles)
133
+ return trimesh.Trimesh(vertices, faces, process=False), painted
134
+
135
+ objects = []
136
+ for object_id, items in placements.items():
137
+ element = resources.get(object_id)
138
+ if element is None:
139
+ continue
140
+ own = config.get(object_id)
141
+ meta = _metadata(own) if own is not None else {}
142
+ object_filament = _int(meta.get('extruder')) or 1
143
+ part_config = {p.get('id'): p for p in own.findall('part')} if own is not None else {}
144
+ parts = []
145
+ components = element.find(CORE + 'components')
146
+ if components is not None:
147
+ for component in components.findall(CORE + 'component'):
148
+ path = (component.get(PRODUCTION + 'path') or ROOT_MODEL).lstrip('/')
149
+ part_id = component.get('objectid')
150
+ part = part_config.get(part_id)
151
+ part_meta = _metadata(part) if part is not None else {}
152
+ if part is not None and part.get('subtype') == 'negative_part':
153
+ raise ValueError('CAD inspection of a 3MF project with negative volumes is not supported; '
154
+ 'the inspection mesh cannot yet apply their subtraction. Use a project with the cut baked into its mesh.')
155
+ if part is not None and part.get('subtype', 'normal_part') in SKIPPED_SUBTYPES:
156
+ continue
157
+ target = next((o for o in model(path).iter(CORE + 'object') if o.get('id') == part_id), None)
158
+ if target is None:
159
+ raise ValueError(f'Component {part_id} of object {object_id} is missing from {path}.')
160
+ mesh, painted = mesh_of(target)
161
+ if mesh is None:
162
+ raise ValueError('CAD inspection of nested or empty 3MF components is not supported; '
163
+ 'use a project whose object components directly contain meshes.')
164
+ local = _matrix(component.get('transform'))
165
+ mesh.apply_transform(local)
166
+ parts.append(Part(int(object_id), int(part_id), '/' + path, part_meta.get('name') or meta.get('name', ''),
167
+ _int(part_meta.get('extruder')) or object_filament, mesh, painted, local))
168
+ else:
169
+ mesh, painted = mesh_of(element)
170
+ if mesh is not None:
171
+ part = Part(int(object_id), int(object_id), '/' + ROOT_MODEL, meta.get('name', ''), object_filament, mesh, painted, np.eye(4))
172
+ part.plain = True
173
+ parts.append(part)
174
+ objects.append(Object(int(object_id), meta.get('name', ''), plate_of.get(object_id, 1), parts, items))
175
+ if not objects:
176
+ raise ValueError('The input 3MF has no object with a mesh.')
177
+ # The filaments the project declares: a part can only print in one of them.
178
+ declared = 0
179
+ try:
180
+ project = json.loads(raw.get('Metadata/project_settings.config', b'{}'))
181
+ declared = max(len(project.get(key) or []) for key in ('filament_colour', 'filament_type', 'filament_ids'))
182
+ except (ValueError, AttributeError, TypeError):
183
+ declared = 0
184
+ return objects, min(declared, MAX_FILAMENT)
185
+
186
+
187
+ def _geometry(value, label):
188
+ """A build123d Shape or a trimesh.Trimesh, as given."""
189
+ import trimesh
190
+ import build123d as cad
191
+ if isinstance(value, trimesh.Trimesh):
192
+ if not len(value.faces):
193
+ raise ValueError(label + ' is an empty mesh.')
194
+ return value
195
+ if isinstance(value, cad.Shape):
196
+ if not value.is_valid or not value.solids():
197
+ raise ValueError(label + ' must be a valid build123d Shape containing solids.')
198
+ return value
199
+ raise ValueError(label + ' must be a build123d Shape or a trimesh.Trimesh.')
200
+
201
+
202
+ def _filament(value, label):
203
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= MAX_FILAMENT:
204
+ raise ValueError(f'{label} must be an integer filament from 1 to {MAX_FILAMENT}.')
205
+ return value
206
+
207
+
208
+ def _name(value, label):
209
+ if not isinstance(value, str) or not value.strip() or '\0' in value or len(value) > 200:
210
+ raise ValueError(label + ' must be a non-empty name of at most 200 characters.')
211
+ return value.strip()
212
+
213
+
214
+ class Project3mf:
215
+ """What build() returns for a 3MF project. Made by project_3mf(base=None)."""
216
+
217
+ def __init__(self, base, base_path):
218
+ self.base = base
219
+ self.objects, self.filaments = _read(base_path) if base_path else ([], 0)
220
+ self._new = [] # new project: {object, plate, name, filament, geometry}
221
+ self._edits = [] # edit: operations on the base
222
+
223
+ def object(self, name_or_id):
224
+ """A base object by its root object id, or by its name when only one object has it."""
225
+ for obj in self.objects:
226
+ if str(obj.id) == str(name_or_id):
227
+ return obj
228
+ named = [obj for obj in self.objects if obj.name == name_or_id]
229
+ if len(named) > 1:
230
+ raise ValueError(f'{len(named)} objects are named {name_or_id!r} (ids ' + ', '.join(str(o.id) for o in named)
231
+ + '): pick one by id, or edit each copy.')
232
+ if named:
233
+ return named[0]
234
+ raise ValueError(f'The input 3MF has no object {name_or_id!r}; objects: ' + ', '.join(repr(o.name) for o in self.objects))
235
+
236
+ def _declared(self, filament, label):
237
+ filament = _filament(filament, label)
238
+ if self.base and self.filaments and filament > self.filaments:
239
+ raise ValueError(f'{label} {filament} is not one of the {self.filaments} filaments the input 3MF declares.')
240
+ return filament
241
+
242
+ def _count(self):
243
+ if len(self._new) + sum(1 for e in self._edits if 'geometry' in e) >= MAX_PARTS:
244
+ raise ValueError(f'A project takes at most {MAX_PARTS} new or replaced parts.')
245
+
246
+ def add_part(self, geometry, *, name, filament=None, object=None, plate=1):
247
+ """Add a part. Editing a 3MF: into the base object `object` (name or id), in that object's frame.
248
+ A new project: into the object named `object` (default: one object per part's name) on `plate`."""
249
+ self._count()
250
+ name = _name(name, 'name')
251
+ geometry = _geometry(geometry, f'Part {name!r}')
252
+ if self.base:
253
+ if object is None:
254
+ raise ValueError('Editing a 3MF, add_part needs object=: the base object (name or id) the part joins.')
255
+ target = self.object(object)
256
+ if any(part.plain for part in target.parts):
257
+ raise ValueError(f'Object {target.name!r} is one mesh without parts (a plain 3MF): only a Bambu Studio or OrcaSlicer project\'s objects take new parts.')
258
+ if plate != 1:
259
+ raise ValueError('Editing a 3MF, a new part sits on its object\'s plate; plate cannot be set.')
260
+ self._edits.append({'op': 'add_part', 'object_id': target.id, 'name': name,
261
+ 'filament': self._declared(filament if filament is not None else (target.parts[0].filament if target.parts else 1), 'filament'),
262
+ 'geometry': geometry})
263
+ else:
264
+ if isinstance(plate, bool) or not isinstance(plate, int) or not 1 <= plate <= MAX_PLATES:
265
+ raise ValueError(f'plate must be an integer from 1 to {MAX_PLATES}.')
266
+ self._new.append({'object': _name(object, 'object') if object is not None else name, 'plate': plate, 'name': name,
267
+ 'filament': _filament(filament if filament is not None else len(self._new) + 1, 'filament'),
268
+ 'geometry': geometry})
269
+ return self
270
+
271
+ def _base_part(self, part):
272
+ if not self.base:
273
+ raise ValueError('Only an edited 3MF has parts to change; add_part builds a new project.')
274
+ if not isinstance(part, Part):
275
+ raise ValueError('Pass a part from project.objects[...].parts (or project.object(...).part(...)).')
276
+ if part.plain:
277
+ raise ValueError(f'Part {part.name!r} is a plain 3MF object\'s only mesh, with no part settings to change: edit a Bambu Studio or OrcaSlicer project.')
278
+ return part
279
+
280
+ def replace_part(self, part, geometry):
281
+ """Replace a base part's mesh with new geometry in its object's frame. Its painting goes with the old mesh."""
282
+ part = self._base_part(part)
283
+ self._count()
284
+ self._edits.append({'op': 'replace_part', 'object_id': part.object_id, 'part_id': part.id, 'path': part.path,
285
+ 'geometry': _geometry(geometry, f'Replacement for {part.name!r}'), 'local': part._local})
286
+ return self
287
+
288
+ def set_part(self, part, *, name=None, filament=None):
289
+ """Rename a base part or change its filament (1-based). Painting on it is kept."""
290
+ part = self._base_part(part)
291
+ edit = {'op': 'set_part', 'object_id': part.object_id, 'part_id': part.id}
292
+ if name is not None:
293
+ edit['name'] = _name(name, 'name')
294
+ if filament is not None:
295
+ edit['filament'] = self._declared(filament, 'filament')
296
+ if len(edit) == 3:
297
+ raise ValueError('set_part needs name= or filament=.')
298
+ self._edits.append(edit)
299
+ return self
300
+
301
+
302
+ def project_factory(inputs):
303
+ declared = dict(inputs)
304
+
305
+ def project_3mf(base=None):
306
+ """A 3MF project for build() to return: new (base=None) or an edit of the declared input 3MF `base`."""
307
+ if base is None:
308
+ return Project3mf(None, None)
309
+ if base not in declared or not str(declared[base]).lower().endswith('.3mf'):
310
+ raise ValueError('project_3mf(base) needs the name of a declared .3mf input.')
311
+ return Project3mf(base, declared[base])
312
+ return project_3mf
313
+
314
+
315
+ def _fused(meshes):
316
+ """An object's parts as one body for the checks, as the STEP path fuses them: colour parts that touch or overlap
317
+ print as one piece, and their shared faces are not the object's surface. A part that is not a closed solid is kept
318
+ as it is, beside the others, so the checks still see the defect."""
319
+ import numpy as np
320
+ import trimesh
321
+ import manifold3d as mf
322
+ if len(meshes) < 2:
323
+ return meshes
324
+ solids, open_parts = [], []
325
+ for m in meshes:
326
+ part = m.copy()
327
+ part.merge_vertices()
328
+ solid = mf.Manifold(mf.Mesh(np.asarray(part.vertices, dtype=np.float32), np.asarray(part.faces, dtype=np.uint32))) if part.is_volume else None
329
+ if solid is None or solid.status() != mf.Error.NoError:
330
+ open_parts.append(m)
331
+ else:
332
+ solids.append(solid)
333
+ if len(solids) < 2:
334
+ return meshes
335
+ union = mf.Manifold.batch_boolean(solids, mf.OpType.Add)
336
+ body = union.to_mesh()
337
+ if union.status() != mf.Error.NoError or not len(body.tri_verts):
338
+ return meshes
339
+ return [trimesh.Trimesh(np.asarray(body.vert_properties, dtype=float)[:, :3], np.asarray(body.tri_verts, dtype=np.int64), process=False)] + open_parts
340
+
341
+
342
+ def export(project, out, mode):
343
+ """Write the project's parts as STL, a manifest the MCP writes the 3MF from, and one combined STL (plus STEP for a
344
+ new all-solid project) for the engine's usual checks and renders. The combined STL holds one fused body per object
345
+ placement, as the STEP holds one fused body per object."""
346
+ import numpy as np
347
+ import trimesh
348
+ import build123d as cad
349
+ if not project._new and not project._edits:
350
+ raise ValueError('The 3MF project is empty: add_part, replace_part or set_part first.')
351
+ if project.base and mode == 'solid':
352
+ raise ValueError('Editing a 3MF runs with mode: "mesh": the designer\'s parts are meshes, with no STEP.')
353
+ parts_dir = Path(str(out) + '.parts')
354
+ parts_dir.mkdir()
355
+ counter = [0]
356
+
357
+ def stl(geometry, transform=None):
358
+ index = counter[0]
359
+ counter[0] += 1
360
+ target = parts_dir / f'{index}.stl'
361
+ if isinstance(geometry, trimesh.Trimesh):
362
+ mesh = geometry.copy()
363
+ else:
364
+ cad.export_stl(geometry, str(target), tolerance=0.01, angular_tolerance=0.1)
365
+ mesh = trimesh.load(str(target), force='mesh')
366
+ if transform is not None:
367
+ mesh.apply_transform(transform)
368
+ mesh.export(str(target))
369
+ return index, mesh
370
+
371
+ manifest = {'version': 1, 'base': project.base}
372
+ combined = []
373
+ if project.base:
374
+ edits = []
375
+ replaced = {}
376
+ for edit in project._edits:
377
+ entry = {k: v for k, v in edit.items() if k not in ('geometry', 'local')}
378
+ if edit['op'] == 'add_part':
379
+ entry['stl'], mesh = stl(edit['geometry'])
380
+ replaced.setdefault((None, edit['object_id'], 'new'), []).append(mesh)
381
+ elif edit['op'] == 'replace_part':
382
+ # The replacement is drawn in the object's frame; the file keeps the part's component transform.
383
+ entry['stl'], mesh = stl(edit['geometry'], np.linalg.inv(edit['local']))
384
+ # A part is its (model file, object, part id): two model files may reuse an object id. The mesh is kept
385
+ # in its file's coordinates: an object that places it twice shows it under each component transform.
386
+ replaced[(edit['path'], edit['object_id'], edit['part_id'])] = mesh
387
+ edits.append(entry)
388
+ manifest['edits'] = edits
389
+ # The whole project as the build places it, with the edits, for the checks and renders.
390
+ for obj in project.objects:
391
+ meshes = []
392
+ for part in obj.parts:
393
+ fresh = replaced.get((part.path, obj.id, part.id))
394
+ meshes.append(part.mesh if fresh is None else fresh.copy().apply_transform(part._local))
395
+ meshes += replaced.get((None, obj.id, 'new'), [])
396
+ meshes = _fused(meshes)
397
+ for placement in obj.placements:
398
+ combined += [m.copy().apply_transform(placement) for m in meshes]
399
+ else:
400
+ objects, meshes = {}, {}
401
+ for part in project._new:
402
+ key = part['object']
403
+ if key in objects and objects[key]['plate'] != part['plate']:
404
+ raise ValueError(f'Object {key!r} has parts on two plates; one object sits on one plate.')
405
+ index, mesh = stl(part['geometry'])
406
+ objects.setdefault(key, {'name': key, 'plate': part['plate'], 'parts': []})['parts'].append(
407
+ {'stl': index, 'name': part['name'], 'filament': part['filament']})
408
+ meshes.setdefault(key, []).append(mesh)
409
+ for key in objects:
410
+ combined += _fused(meshes[key])
411
+ manifest['objects'] = list(objects.values())
412
+ shapes = [p['geometry'] for p in project._new]
413
+ if mode == 'solid':
414
+ if not all(isinstance(s, cad.Shape) for s in shapes):
415
+ raise ValueError('A project with mesh parts runs with mode: "mesh".')
416
+ # One body per object, its parts fused: the parts of a multi-colour object print as one piece, so the
417
+ # engine's body checks measure objects against each other, not an inlay against its own tile.
418
+ labelled = []
419
+ for key in objects:
420
+ members = [p['geometry'] for p in project._new if p['object'] == key]
421
+ body = members[0].fuse(*members[1:]) if len(members) > 1 else members[0].moved(cad.Location())
422
+ body.label = key
423
+ labelled.append(body)
424
+ cad.export_step(cad.Compound(children=labelled), str(out) + '.step')
425
+ trimesh.util.concatenate(combined).export(str(out) + '.stl')
426
+ Path(str(out) + '.project.json').write_text(json.dumps(manifest))
package/src/cad/worker.py CHANGED
@@ -104,12 +104,16 @@ def main():
104
104
  declaration.value = ast.Name(id='__cad_parameters__', ctx=ast.Load())
105
105
  ast.fix_missing_locations(tree)
106
106
  from scan_touchup import scan_touchup_factory
107
- namespace = {'__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {})),
107
+ from project3mf import Project3mf, export as export_project, project_factory
108
+ namespace = {'project_3mf': project_factory(request.get('inputs', {})), '__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {})),
108
109
  'scan_touchup': scan_touchup_factory(request.get('inputs', {}))}
109
110
  exec(compile(tree, request['script'], 'exec'), namespace)
110
111
  shape = namespace['build']()
111
112
  out = Path(request['output']) / request['name']
112
- if request.get('mode', 'solid') == 'mesh':
113
+ if isinstance(shape, Project3mf):
114
+ # A 3MF project: parts and a manifest for the MCP to write the 3MF from, plus the usual combined exports.
115
+ export_project(shape, out, request.get('mode', 'solid'))
116
+ elif request.get('mode', 'solid') == 'mesh':
113
117
  import trimesh
114
118
  if not isinstance(shape, trimesh.Trimesh):
115
119
  raise ValueError('Mesh-mode build() must return a trimesh.Trimesh.')
package/src/cad-engine.ts CHANGED
@@ -6,6 +6,8 @@ import { createHash, randomUUID } from "node:crypto";
6
6
  import { createRequire } from "node:module";
7
7
  import { performance } from "node:perf_hooks";
8
8
  import { CadRefusal, cadFailure } from "./cad/refusal.js";
9
+ import { writeCadProject3mf } from "./counterpart/make-3mf.js";
10
+ import { listModelPlates } from "./counterpart/model-plates.js";
9
11
  import { withCadLock } from "./cad/serial.js";
10
12
  import {
11
13
  measureEnvironment,
@@ -490,6 +492,7 @@ export class CadEngine {
490
492
  "worker.py",
491
493
  "geometry.py",
492
494
  "scan_touchup.py",
495
+ "project3mf.py",
493
496
  "process.ts",
494
497
  "storage.ts",
495
498
  "serial.ts",
@@ -803,8 +806,10 @@ export class CadEngine {
803
806
  ).stdout,
804
807
  );
805
808
  const printed = built.stdout.trim();
809
+ const project = await this.project3mf(job, name, snapshots);
806
810
  const result = {
807
811
  ...checked,
812
+ ...project,
808
813
  // Beside the image paths, where the next step is decided.
809
814
  next: "Read renders.perspective before the next cad_run or any other change: say what it shows is wrong against what you are making (the bought product you named, or the object in the photos), then fix that.",
810
815
  // The script's own print() output: its words, not a measurement by this engine.
@@ -854,6 +859,32 @@ export class CadEngine {
854
859
  deadline,
855
860
  );
856
861
  }
862
+ /**
863
+ * When build() returned project_3mf(), write <name>.3mf from the sandbox's manifest and part STLs (this trusted
864
+ * process writes it; the sandbox only meshed the parts) and read it back as list_3mf_plates does.
865
+ */
866
+ private async project3mf(job: string, name: string, inputs: Record<string, string>): Promise<Record<string, unknown>> {
867
+ const manifestPath = path.join(job, `${name}.project.json`);
868
+ const st = await fs.lstat(manifestPath).catch(() => undefined);
869
+ if (!st) return {};
870
+ if (!st.isFile() || st.size > 1024 * 1024) throw new Error("The design's 3MF project manifest is unsafe or too large.");
871
+ const partsDir = path.join(job, `${name}.parts`);
872
+ const dir = await fs.lstat(partsDir).catch(() => undefined);
873
+ if (!dir?.isDirectory()) throw new Error("The design's 3MF project parts are missing.");
874
+ const out = path.join(job, `${name}.3mf`);
875
+ const written = await writeCadProject3mf(JSON.parse(await fs.readFile(manifestPath, "utf8")), partsDir, inputs, out);
876
+ const listed = await listModelPlates(out);
877
+ return {
878
+ three_mf: out,
879
+ three_mf_project: {
880
+ base: written.base,
881
+ changes: written.changed,
882
+ plate_count: listed.plate_count,
883
+ plates: listed.plates.map(plate => ({ index: plate.index, name: plate.name, build_items: plate.build_items, parts: plate.parts, filaments: plate.filaments })),
884
+ project_filaments: listed.project_filaments,
885
+ },
886
+ };
887
+ }
857
888
  async checkFit(
858
889
  args: CadArguments,
859
890
  signal?: AbortSignal,