bambu-printer-mcp 1.1.82 → 1.1.83

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,161 @@
1
+ """Trusted CAD entry points. User code runs only in build, inside the OS sandbox.
2
+ Inspection is a fresh process: user stdout, globals and check claims are never receipts.
3
+ """
4
+ import ast
5
+ import json
6
+ import math
7
+ import os
8
+ import resource
9
+ import sys
10
+ from pathlib import Path
11
+
12
+
13
+ def parameters(source, overrides):
14
+ tree = ast.parse(source)
15
+ declarations = [n for n in tree.body if isinstance(n, ast.Assign)
16
+ and any(isinstance(t, ast.Name) and t.id == 'P' for t in n.targets)]
17
+ if len(declarations) != 1:
18
+ raise ValueError('Declare exactly one top-level P = {...} dictionary of literal named parameters.')
19
+ node = declarations[0]
20
+ defaults = ast.literal_eval(node.value)
21
+ if not isinstance(defaults, dict) or not all(isinstance(k, str) and k and len(k) <= 80 for k in defaults):
22
+ raise ValueError('P must be a literal dictionary with named string keys.')
23
+ if not isinstance(overrides, dict) or set(overrides) - set(defaults):
24
+ raise ValueError('Unknown parameter override; only names declared in P may change.')
25
+ merged = {**defaults, **overrides}
26
+ encoded = json.dumps(merged, allow_nan=False)
27
+ if len(encoded) > 65536:
28
+ raise ValueError('Parameter values exceed 64 KiB.')
29
+ # Avoid surprising scalar/container type changes while allowing integer -> float dimensions.
30
+ for key, value in overrides.items():
31
+ original = defaults[key]
32
+ numeric = lambda x: isinstance(x, (int, float)) and not isinstance(x, bool)
33
+ if not (numeric(original) and numeric(value)) and type(original) is not type(value):
34
+ raise ValueError('Parameter type changed: ' + key)
35
+ return tree, node, merged
36
+
37
+
38
+ def scan_loader(inputs):
39
+ """Explicit coordinate preparation only; never infer units or scale to a requested fit."""
40
+ declared = dict(inputs)
41
+ def load_scan(name, *, source_units, up_axis, ground=True):
42
+ import numpy as np
43
+ import trimesh
44
+ if name not in declared: raise ValueError('load_scan requires a declared input name.')
45
+ if source_units not in ('m', 'mm'): raise ValueError('source_units must explicitly be m or mm.')
46
+ axes = {'x': [1,0,0], '-x': [-1,0,0], 'y': [0,1,0], '-y': [0,-1,0], 'z': [0,0,1], '-z': [0,0,-1]}
47
+ if up_axis not in axes: raise ValueError('up_axis must be x, -x, y, -y, z or -z: the object usage-up direction in the source frame.')
48
+ if not isinstance(ground, bool): raise ValueError('ground must be a boolean.')
49
+ m = trimesh.load(declared[name], force='mesh', process=False)
50
+ if not isinstance(m, trimesh.Trimesh) or not len(m.vertices) or not np.isfinite(m.vertices).all():
51
+ raise ValueError('Scan must contain a finite triangle mesh.')
52
+ factor = 1000.0 if source_units == 'm' else 1.0
53
+ # Smallest rotation; aligning an axis must not add an arbitrary yaw.
54
+ direction = np.asarray(axes[up_axis], dtype=float)
55
+ rotation_axis = np.cross(direction, [0,0,1])
56
+ angle = float(np.arccos(np.clip(direction[2], -1, 1)))
57
+ matrix = (np.eye(4) if angle == 0 else
58
+ trimesh.transformations.rotation_matrix(angle, rotation_axis if np.linalg.norm(rotation_axis) else [1,0,0]))
59
+ m.apply_scale(factor)
60
+ m.apply_transform(matrix)
61
+ lift = -float(m.bounds[0,2]) if ground else 0.0
62
+ m.apply_translation([0,0,lift])
63
+ m.merge_vertices()
64
+ m.units = 'mm'
65
+ m.metadata['cad_scan_frame'] = {'source_units':source_units,'units':'mm','source_up':up_axis,'up_axis':'z',
66
+ 'unit_factor':factor,'rotation':matrix.tolist(),'translation_z_mm':lift,'scale_to_fit':False}
67
+ return m
68
+ return load_scan
69
+
70
+
71
+ def limits():
72
+ caps = [(resource.RLIMIT_FSIZE, 128 * 1024**2), (resource.RLIMIT_CPU, 900),
73
+ (resource.RLIMIT_NOFILE, 128)]
74
+ if sys.platform != 'darwin': caps.append((resource.RLIMIT_AS, 8 * 1024**3))
75
+ for kind, requested in caps:
76
+ _, hard = resource.getrlimit(kind)
77
+ limit = requested if hard == resource.RLIM_INFINITY else min(requested, hard)
78
+ resource.setrlimit(kind, (limit, limit))
79
+
80
+
81
+ def main():
82
+ mode = sys.argv[1]
83
+ if mode == 'imports':
84
+ import build123d
85
+ import trimesh
86
+ import manifold3d
87
+ import numpy, scipy, skimage, shapely
88
+ from PIL import Image
89
+ print(json.dumps({'build123d': build123d.__version__}))
90
+ return
91
+ request = json.loads(Path(sys.argv[2]).read_text())
92
+ if mode == 'parameters':
93
+ _, _, merged = parameters(Path(request['script']).read_text(), json.loads(Path(request['parameters']).read_text()))
94
+ print(json.dumps(merged, allow_nan=False))
95
+ return
96
+ limits()
97
+ # -I omits both cwd and script directory; import only our package-owned helper.
98
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
99
+ if mode == 'build':
100
+ import build123d as cad
101
+ source = Path(request['script']).read_text()
102
+ tree, declaration, merged = parameters(source, json.loads(Path(request['parameters']).read_text()))
103
+ declaration.value = ast.Name(id='__cad_parameters__', ctx=ast.Load())
104
+ ast.fix_missing_locations(tree)
105
+ namespace = {'__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {}))}
106
+ exec(compile(tree, request['script'], 'exec'), namespace)
107
+ shape = namespace['build']()
108
+ out = Path(request['output']) / request['name']
109
+ if request.get('mode', 'solid') == 'mesh':
110
+ import trimesh
111
+ if not isinstance(shape, trimesh.Trimesh):
112
+ raise ValueError('Mesh-mode build() must return a trimesh.Trimesh.')
113
+ shape.export(str(out) + '.stl')
114
+ else:
115
+ if not isinstance(shape, cad.Shape) or not shape.is_valid or not shape.solids():
116
+ raise ValueError('build() must return a valid build123d Shape containing solids.')
117
+ cad.export_stl(shape, str(out) + '.stl', tolerance=0.01, angular_tolerance=0.1)
118
+ cad.export_step(shape, str(out) + '.step')
119
+ elif mode == 'inspect':
120
+ from geometry import inspect
121
+ print(json.dumps(inspect(request), allow_nan=False))
122
+ elif mode == 'fit':
123
+ from geometry import fit
124
+ print(json.dumps(fit(request), allow_nan=False))
125
+ elif mode == 'smoke':
126
+ import socket
127
+ import build123d as cad
128
+ from geometry import inspect
129
+ request['name'] = 'smoke'
130
+ out = Path(request['output'])
131
+ shape = cad.Box(10, 20, 30)
132
+ cad.export_stl(shape, str(out / 'smoke.stl'))
133
+ cad.export_step(shape, str(out / 'smoke.step'))
134
+ result = inspect(request)
135
+ # Prove this confinement actually rejects out-of-workspace writes and personal reads.
136
+ for target, operation in [(out.parent / 'cad-forbidden-write', 'write'),
137
+ (Path(request['home']) / '.ssh', 'read')]:
138
+ try:
139
+ if operation == 'write': target.write_text('forbidden')
140
+ else: os.listdir(target)
141
+ except (PermissionError, FileNotFoundError):
142
+ pass
143
+ else:
144
+ raise RuntimeError('CAD confinement did not reject ' + operation)
145
+ sock = socket.socket()
146
+ sock.settimeout(1)
147
+ try:
148
+ sock.connect(('192.0.2.1', 443))
149
+ except OSError:
150
+ pass
151
+ else:
152
+ raise RuntimeError('CAD confinement did not reject network access')
153
+ finally:
154
+ sock.close()
155
+ print(json.dumps({'build123d': cad.__version__, **result['checks'], 'solid_count': result['solid_count']}))
156
+ else:
157
+ raise ValueError('Unknown CAD operation')
158
+
159
+
160
+ if __name__ == '__main__':
161
+ main()