bambu-printer-mcp 1.1.81 → 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,232 @@
1
+ import fs from "node:fs/promises";
2
+ import { createReadStream } from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+
6
+ // Budget estimates for the shipped pins, including managed Python and retained uv cache.
7
+ export const CAD_SIZE_ESTIMATE = {
8
+ expected_download_bytes: 350 * 1024 ** 2,
9
+ expected_installed_bytes: 1536 * 1024 ** 2,
10
+ };
11
+ export interface CadStorage {
12
+ expected_download_bytes: number;
13
+ expected_installed_bytes: number;
14
+ installed_bytes: number | null;
15
+ measurement: "allocated-last-setup";
16
+ measured_at?: string;
17
+ }
18
+ export function storageInfo(
19
+ marker: { installed_bytes?: unknown; measured_at?: unknown } | undefined,
20
+ exists: boolean,
21
+ ): CadStorage {
22
+ return {
23
+ ...CAD_SIZE_ESTIMATE,
24
+ installed_bytes:
25
+ typeof marker?.installed_bytes === "number" &&
26
+ Number.isFinite(marker.installed_bytes) &&
27
+ marker.installed_bytes >= 0
28
+ ? marker.installed_bytes
29
+ : exists
30
+ ? null
31
+ : 0,
32
+ measurement: "allocated-last-setup",
33
+ ...(typeof marker?.measured_at === "string"
34
+ ? { measured_at: marker.measured_at }
35
+ : {}),
36
+ };
37
+ }
38
+ /** Allocated filesystem bytes, like du; no symlink traversal or double-counted hardlinks. */
39
+ export async function measureEnvironment(data: string): Promise<number> {
40
+ const seen = new Set<string>();
41
+ let bytes = 0;
42
+ async function walk(file: string): Promise<void> {
43
+ const stat = await fs.lstat(file).catch((e) => {
44
+ if (e.code === "ENOENT") return null;
45
+ throw e;
46
+ });
47
+ if (!stat) return;
48
+ const key = `${stat.dev}:${stat.ino}`;
49
+ if (seen.has(key)) return;
50
+ seen.add(key);
51
+ bytes += stat.blocks * 512;
52
+ if (stat.isDirectory())
53
+ for (const name of await fs.readdir(file))
54
+ await walk(path.join(file, name));
55
+ }
56
+ for (const name of ["runtime", "python", "cache"])
57
+ await walk(path.join(data, name));
58
+ return bytes;
59
+ }
60
+ async function digest(
61
+ file: string,
62
+ signal?: AbortSignal,
63
+ ): Promise<{ hash: string; bytes: number }> {
64
+ const hash = createHash("sha256");
65
+ let bytes = 0;
66
+ signal?.throwIfAborted();
67
+ const stream = createReadStream(file);
68
+ const abort = () => {
69
+ const error = new Error("CAD input snapshot cancelled.");
70
+ error.name = "AbortError";
71
+ stream.destroy(error);
72
+ };
73
+ signal?.addEventListener("abort", abort, { once: true });
74
+ try {
75
+ for await (const chunk of stream) {
76
+ signal?.throwIfAborted();
77
+ bytes += chunk.length;
78
+ if (bytes > 64 * 1024 ** 2) throw new Error("CAD input exceeds 64 MiB.");
79
+ hash.update(chunk);
80
+ }
81
+ return { hash: hash.digest("hex"), bytes };
82
+ } finally {
83
+ signal?.removeEventListener("abort", abort);
84
+ stream.destroy();
85
+ }
86
+ }
87
+ /** Each immutable bundle contains exactly the declared files, retaining linked asset basenames. */
88
+ export async function snapshotInputs(
89
+ root: string,
90
+ files: Record<string, string>,
91
+ signal?: AbortSignal,
92
+ index?: {
93
+ directory: string;
94
+ authorize: (directory: string) => Promise<string>;
95
+ },
96
+ ) {
97
+ const entries: {
98
+ alias: string;
99
+ file: string;
100
+ name: string;
101
+ hash: string;
102
+ bytes: number;
103
+ }[] = [];
104
+ let bytes = 0;
105
+ const names = new Set<string>();
106
+ for (const [alias, file] of Object.entries(files)) {
107
+ const name = path.basename(file);
108
+ if (names.has(name.toLowerCase()))
109
+ throw new Error(
110
+ "CAD input files must have distinct original filenames so linked mesh/texture assets remain unambiguous.",
111
+ );
112
+ names.add(name.toLowerCase());
113
+ const content = await digest(file, signal);
114
+ bytes += content.bytes;
115
+ if (bytes > 256 * 1024 ** 2)
116
+ throw new Error("CAD inputs exceed their 256 MiB total limit.");
117
+ entries.push({ alias, file, name, ...content });
118
+ }
119
+ const inputs: Record<string, string> = {},
120
+ hashes: Record<string, string> = {};
121
+ if (!entries.length)
122
+ return { inputs, hashes, directory: null, added: 0, reused: 0 };
123
+ const identity = entries
124
+ .map(({ name, hash, bytes }) => ({ name, hash, bytes }))
125
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
126
+ const id = createHash("sha256")
127
+ .update(JSON.stringify(identity))
128
+ .digest("hex");
129
+ const cache = path.join(root, ".cad-inputs"),
130
+ directory = path.join(cache, id);
131
+ async function verify(directory: string): Promise<void> {
132
+ if (!(await fs.lstat(directory)).isDirectory())
133
+ throw new Error("CAD input bundle must be a directory, not a link.");
134
+ const found = await fs.readdir(directory);
135
+ if (
136
+ found.length !== entries.length ||
137
+ found.some((n) => !entries.some((e) => e.name === n))
138
+ )
139
+ throw new Error("CAD input bundle contains undeclared files.");
140
+ for (const entry of entries) {
141
+ const file = path.join(directory, entry.name);
142
+ if (!(await fs.lstat(file)).isFile())
143
+ throw new Error("CAD cached input is not a regular file.");
144
+ const actual = await digest(file, signal);
145
+ if (actual.hash !== entry.hash || actual.bytes !== entry.bytes)
146
+ throw new Error("CAD input cache failed its content hash check.");
147
+ }
148
+ }
149
+ const candidates = new Set(
150
+ Object.values(files).map((file) => path.dirname(file)),
151
+ );
152
+ if (index) {
153
+ try {
154
+ const known = JSON.parse(
155
+ await fs.readFile(path.join(index.directory, id + ".json"), "utf8"),
156
+ );
157
+ if (typeof known.directory === "string") candidates.add(known.directory);
158
+ } catch {
159
+ /* An absent/stale index is rebuilt from declared content. */
160
+ }
161
+ }
162
+ for (const candidate of candidates) {
163
+ if (
164
+ path.basename(candidate) !== id ||
165
+ path.basename(path.dirname(candidate)) !== ".cad-inputs"
166
+ )
167
+ continue;
168
+ try {
169
+ if (index) await index.authorize(candidate);
170
+ await verify(candidate);
171
+ for (const entry of entries) {
172
+ inputs[entry.alias] = path.join(candidate, entry.name);
173
+ hashes[entry.alias] = entry.hash;
174
+ }
175
+ return { inputs, hashes, directory: candidate, added: 0, reused: bytes };
176
+ } catch {
177
+ /* Do not expose a stale, out-of-policy or incomplete bundle. */
178
+ }
179
+ }
180
+ await fs.mkdir(cache, { recursive: true, mode: 0o700 });
181
+ if ((await fs.lstat(cache)).isSymbolicLink())
182
+ throw new Error("CAD input cache must not be a symlink.");
183
+ let added = 0;
184
+ try {
185
+ await verify(directory);
186
+ } catch (e) {
187
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
188
+ const stage = await fs.mkdtemp(path.join(cache, ".stage-"));
189
+ try {
190
+ for (const entry of entries) {
191
+ const file = path.join(stage, entry.name);
192
+ await fs.copyFile(entry.file, file);
193
+ const copied = await digest(file, signal);
194
+ if (copied.hash !== entry.hash || copied.bytes !== entry.bytes)
195
+ throw new Error(
196
+ "CAD input changed while snapshotting; no run was dispatched.",
197
+ );
198
+ await fs.chmod(file, 0o444);
199
+ }
200
+ try {
201
+ await fs.rename(stage, directory);
202
+ added = bytes;
203
+ } catch (e) {
204
+ if (
205
+ !["EEXIST", "ENOTEMPTY"].includes((e as NodeJS.ErrnoException).code!)
206
+ )
207
+ throw e;
208
+ await verify(directory);
209
+ }
210
+ } finally {
211
+ await fs.rm(stage, { recursive: true, force: true });
212
+ }
213
+ }
214
+ if (index) {
215
+ await fs.mkdir(index.directory, { recursive: true, mode: 0o700 });
216
+ const temporary = path.join(index.directory, ".new-" + randomUUID());
217
+ try {
218
+ await fs.writeFile(temporary, JSON.stringify({ directory }), {
219
+ flag: "wx",
220
+ mode: 0o600,
221
+ });
222
+ await fs.rename(temporary, path.join(index.directory, id + ".json"));
223
+ } finally {
224
+ await fs.unlink(temporary).catch(() => {});
225
+ }
226
+ }
227
+ for (const entry of entries) {
228
+ inputs[entry.alias] = path.join(directory, entry.name);
229
+ hashes[entry.alias] = entry.hash;
230
+ }
231
+ return { inputs, hashes, directory, added, reused: bytes - added };
232
+ }
@@ -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()