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.
- package/README.md +40 -1
- package/dist/cad/contracts.d.ts +424 -0
- package/dist/cad/contracts.js +288 -0
- package/dist/cad/process.d.ts +32 -0
- package/dist/cad/process.js +151 -0
- package/dist/cad/refusal.d.ts +15 -0
- package/dist/cad/refusal.js +30 -0
- package/dist/cad/serial.d.ts +6 -0
- package/dist/cad/serial.js +114 -0
- package/dist/cad/storage.d.ts +34 -0
- package/dist/cad/storage.js +201 -0
- package/dist/cad-engine.d.ts +43 -0
- package/dist/cad-engine.js +546 -0
- package/dist/counterpart/info.js +2 -0
- package/dist/counterpart/remote.js +7 -0
- package/dist/counterpart/schemas.d.ts +33 -0
- package/dist/counterpart/schemas.js +1 -0
- package/dist/counterpart/setup.d.ts +10 -0
- package/dist/counterpart/setup.js +6 -2
- package/dist/design-guidance.js +2 -6
- package/dist/index.js +45 -4
- package/dist/tool-annotations.js +4 -0
- package/package.json +1 -1
- package/src/cad/contracts.ts +317 -0
- package/src/cad/geometry.py +157 -0
- package/src/cad/process.ts +216 -0
- package/src/cad/refusal.ts +34 -0
- package/src/cad/requirements.in +9 -0
- package/src/cad/requirements.lock +69 -0
- package/src/cad/serial.ts +126 -0
- package/src/cad/storage.ts +232 -0
- package/src/cad/worker.py +161 -0
- package/src/cad-engine.ts +794 -0
- package/src/counterpart/info.ts +2 -0
- package/src/counterpart/remote.ts +6 -0
- package/src/counterpart/schemas.ts +2 -0
- package/src/counterpart/setup.ts +12 -2
- package/src/design-guidance.ts +2 -0
- package/src/index.ts +40 -4
- package/src/tool-annotations.ts +4 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Independent geometry checks, six orthographic views and triangle-exact surface separation."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import math
|
|
4
|
+
import numpy as np
|
|
5
|
+
import trimesh
|
|
6
|
+
import manifold3d as mf
|
|
7
|
+
from PIL import Image, ImageDraw
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def mesh(file):
|
|
11
|
+
m = trimesh.load(file, force='mesh', file_type='stl')
|
|
12
|
+
m.merge_vertices()
|
|
13
|
+
if not len(m.faces) or len(m.faces) > 250000 or not np.isfinite(m.vertices).all():
|
|
14
|
+
raise ValueError('Mesh must have finite vertices and 1..250000 triangles.')
|
|
15
|
+
return m
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def manifold(m):
|
|
19
|
+
return mf.Manifold(mf.Mesh(np.asarray(m.vertices, dtype=np.float32), np.asarray(m.faces, dtype=np.uint32)))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def inspect(request):
|
|
23
|
+
from build123d import import_step
|
|
24
|
+
base = Path(request['output']) / request['name']
|
|
25
|
+
m = mesh(str(base) + '.stl')
|
|
26
|
+
step = import_step(str(base) + '.step') if request.get('mode', 'solid') == 'solid' else None
|
|
27
|
+
mm = manifold(m)
|
|
28
|
+
bounds = m.bounds.tolist()
|
|
29
|
+
sb = step.bounding_box() if step is not None else None
|
|
30
|
+
step_bounds = [list(sb.min), list(sb.max)] if sb is not None else None
|
|
31
|
+
checks = {'watertight': bool(m.is_watertight), 'winding_consistent': bool(m.is_winding_consistent), 'positive_volume': bool(m.is_volume),
|
|
32
|
+
'manifold': mm.status() == mf.Error.NoError, 'step_valid': bool(step.is_valid) if step is not None else None,
|
|
33
|
+
'stl_step_bounds_agree': bool(np.max(np.abs(m.bounds - np.array(step_bounds))) <= 0.2) if step_bounds is not None else None}
|
|
34
|
+
return {'valid': all(v for v in checks.values() if v is not None), 'units': 'mm', 'bounds_mm': bounds,
|
|
35
|
+
'size_mm': m.extents.tolist(), 'volume_mm3': float(m.volume) if m.is_volume else None,
|
|
36
|
+
'step_volume_mm3': float(step.volume) if step is not None else None, 'solid_count': len(step.solids()) if step is not None else len(m.split(only_watertight=True)),
|
|
37
|
+
'mesh_components': len(m.split(only_watertight=False)), 'checks': checks,
|
|
38
|
+
'renders': render(m, base.parent / (base.name + '.renders'))}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def render(m, folder):
|
|
42
|
+
folder.mkdir(exist_ok=True)
|
|
43
|
+
tri, centres, normals = m.triangles, m.triangles.mean(axis=1), m.face_normals
|
|
44
|
+
# Keep only boundaries, creases and view silhouettes, not every STL triangle.
|
|
45
|
+
# Each stroke is painted with its triangle so nearer surfaces hide rear edges.
|
|
46
|
+
edges = np.sort(m.faces[:, [[0, 1], [1, 2], [2, 0]]].reshape(-1, 2), axis=1)
|
|
47
|
+
_, inverse, counts = np.unique(edges, axis=0, return_inverse=True, return_counts=True)
|
|
48
|
+
ordered = np.argsort(inverse, kind='stable')
|
|
49
|
+
starts = np.cumsum(counts) - counts
|
|
50
|
+
paired = np.flatnonzero(counts == 2)
|
|
51
|
+
a, b = ordered[starts[paired]] // 3, ordered[starts[paired] + 1] // 3
|
|
52
|
+
feature = counts != 2
|
|
53
|
+
feature[paired] = np.einsum('ij,ij->i', normals[a], normals[b]) < math.cos(math.radians(35))
|
|
54
|
+
views = [('front', 0, 2, 1, 1), ('back', 0, 2, 1, -1), ('left', 1, 2, 0, -1),
|
|
55
|
+
('right', 1, 2, 0, 1), ('top', 0, 1, 2, 1), ('bottom', 0, 1, 2, -1)]
|
|
56
|
+
images, paths = [], {}
|
|
57
|
+
for name, u, v, depth, sign in views:
|
|
58
|
+
im = Image.new('RGB', (800, 800), '#f5f5f2')
|
|
59
|
+
draw = ImageDraw.Draw(im)
|
|
60
|
+
xy = tri[:, :, [u, v]].copy()
|
|
61
|
+
xy[:, :, 0] *= sign * (-1 if depth == 1 else 1)
|
|
62
|
+
lo, hi = xy.min(axis=(0, 1)), xy.max(axis=(0, 1))
|
|
63
|
+
extent = max(hi - lo)
|
|
64
|
+
if extent <= 0: raise ValueError('Empty mesh extent')
|
|
65
|
+
xy = (xy - (lo + hi) / 2) * (680 / extent) + 400
|
|
66
|
+
xy[:, :, 1] = 800 - xy[:, :, 1]
|
|
67
|
+
light = np.zeros(3); light[depth] = sign * .85; light[v] = .45; light[u] = -.3 * sign * (-1 if depth == 1 else 1)
|
|
68
|
+
light /= np.linalg.norm(light)
|
|
69
|
+
shades = .4 + .6 * np.clip(normals @ light, 0, 1)
|
|
70
|
+
# Parallel interior walls otherwise get exactly the same flat lighting as
|
|
71
|
+
# the near wall, concealing openings that look onto the back of a cavity.
|
|
72
|
+
depths = tri[:, :, depth] * sign
|
|
73
|
+
span = float(np.ptp(depths))
|
|
74
|
+
near = (centres[:, depth] * sign - depths.min()) / span if span > 0 else np.ones(len(tri))
|
|
75
|
+
shades *= .76 + .24 * near
|
|
76
|
+
outlines = feature.copy()
|
|
77
|
+
facing = normals[:, depth] * sign > 1e-8
|
|
78
|
+
outlines[paired] |= facing[a] != facing[b]
|
|
79
|
+
outlines = outlines[inverse].reshape(-1, 3)
|
|
80
|
+
for i in np.argsort(centres[:, depth] * sign, kind='stable'):
|
|
81
|
+
draw.polygon([tuple(a) for a in xy[i]], fill=tuple(int(k * shades[i]) for k in (79, 166, 186)))
|
|
82
|
+
for j in np.flatnonzero(outlines[i]):
|
|
83
|
+
draw.line([tuple(xy[i, j]), tuple(xy[i, (j + 1) % 3])], fill=(27, 62, 70), width=2)
|
|
84
|
+
draw.text((24, 22), name + ' | ' + ', '.join(f'{x:.2f}' for x in m.extents) + ' mm', fill='black')
|
|
85
|
+
file = folder / (name + '.png'); im.save(file); paths[name] = str(file); images.append(im)
|
|
86
|
+
sheet = Image.new('RGB', (1600, 2400), 'white')
|
|
87
|
+
for i, im in enumerate(images): sheet.paste(im, ((i % 2) * 800, (i // 2) * 800))
|
|
88
|
+
sheet.save(folder / 'contact.png'); paths['contact'] = str(folder / 'contact.png')
|
|
89
|
+
return paths
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def triangle_distance(a, b):
|
|
93
|
+
"""Distance for one A triangle against N B triangles: vertex/face and all 9 edge pairs."""
|
|
94
|
+
n = len(b)
|
|
95
|
+
distances = []
|
|
96
|
+
for i in range(3):
|
|
97
|
+
q = trimesh.triangles.closest_point(b, np.repeat(a[i][None, :], n, axis=0))
|
|
98
|
+
distances.append(np.linalg.norm(q - a[i], axis=1))
|
|
99
|
+
q = trimesh.triangles.closest_point(np.repeat(a[None, :, :], n, axis=0), b[:, i, :])
|
|
100
|
+
distances.append(np.linalg.norm(q - b[:, i, :], axis=1))
|
|
101
|
+
for i in range(3):
|
|
102
|
+
u = a[(i + 1) % 3] - a[i]
|
|
103
|
+
for j in range(3):
|
|
104
|
+
v = b[:, (j + 1) % 3] - b[:, j]
|
|
105
|
+
w = a[i] - b[:, j]
|
|
106
|
+
aa = np.dot(u, u); bb = v @ u; cc = np.einsum('ij,ij->i', v, v)
|
|
107
|
+
dd = w @ u; ee = np.einsum('ij,ij->i', v, w)
|
|
108
|
+
denom = aa * cc - bb * bb
|
|
109
|
+
s = np.clip(np.divide(bb * ee - cc * dd, denom, out=np.zeros(n), where=denom > 1e-20), 0, 1)
|
|
110
|
+
t = np.clip((bb * s + ee) / np.maximum(cc, 1e-30), 0, 1)
|
|
111
|
+
s = np.clip((bb * t - dd) / max(aa, 1e-30), 0, 1)
|
|
112
|
+
distances.append(np.linalg.norm(w + s[:, None] * u - t[:, None] * v, axis=1))
|
|
113
|
+
return float(np.min(distances))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def minimum_gap(a, b):
|
|
117
|
+
# AABB pruning is complete: every candidate closer than the current upper bound has intersecting expanded boxes.
|
|
118
|
+
if len(a.faces) > len(b.faces): a, b = b, a
|
|
119
|
+
_, d, _ = trimesh.proximity.closest_point(b, a.vertices[:32])
|
|
120
|
+
best = float(d.min())
|
|
121
|
+
if best <= 1e-8: return 0.0
|
|
122
|
+
tree = b.triangles_tree
|
|
123
|
+
pairs = 0
|
|
124
|
+
for tri in a.triangles:
|
|
125
|
+
lo, hi = tri.min(0) - best, tri.max(0) + best
|
|
126
|
+
indices = list(tree.intersection(np.r_[lo, hi]))
|
|
127
|
+
pairs += len(indices)
|
|
128
|
+
if pairs > 10000000: raise ValueError('Fit distance exceeds the 10-million triangle-pair budget; simplify the meshes.')
|
|
129
|
+
if indices: best = min(best, triangle_distance(tri, b.triangles[indices]))
|
|
130
|
+
if best <= 1e-8: return 0.0
|
|
131
|
+
return best
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def fit(request):
|
|
135
|
+
a, b = mesh(request['model']), mesh(request['reference'])
|
|
136
|
+
transform = request.get('transform', {})
|
|
137
|
+
if not isinstance(transform, dict) or set(transform) - {'translation_mm', 'rotation_deg'}:
|
|
138
|
+
raise ValueError('transform supports only explicit rigid translation_mm and rotation_deg; scaling is never implicit.')
|
|
139
|
+
translation = np.asarray(transform.get('translation_mm', [0, 0, 0]), dtype=float)
|
|
140
|
+
rotation = np.asarray(transform.get('rotation_deg', [0, 0, 0]), dtype=float)
|
|
141
|
+
if translation.shape != (3,) or rotation.shape != (3,) or not np.isfinite(np.r_[translation, rotation]).all():
|
|
142
|
+
raise ValueError('Transform requires finite three-number vectors.')
|
|
143
|
+
matrix = trimesh.transformations.euler_matrix(*np.radians(rotation), axes='sxyz'); matrix[:3, 3] = translation
|
|
144
|
+
b.apply_transform(matrix)
|
|
145
|
+
ma, mb = manifold(a), manifold(b)
|
|
146
|
+
if not a.is_volume or not b.is_volume or ma.status() != mf.Error.NoError or mb.status() != mf.Error.NoError:
|
|
147
|
+
raise ValueError('Fit checks require positively wound watertight manifold STL meshes; repair open scans explicitly before checking.')
|
|
148
|
+
overlap = ma ^ mb
|
|
149
|
+
if overlap.status() != mf.Error.NoError: raise ValueError('Mesh interference Boolean failed.')
|
|
150
|
+
volume = float(overlap.volume())
|
|
151
|
+
gap = 0.0 if volume > 1e-8 else minimum_gap(a, b)
|
|
152
|
+
clearance = request.get('clearance_mm', 0)
|
|
153
|
+
return {'units': 'mm', 'interference_volume_mm3': volume, 'minimum_gap_mm': gap,
|
|
154
|
+
'clearance_mm': clearance, 'clear': volume <= 1e-8 and gap + 1e-8 >= clearance,
|
|
155
|
+
'transform': {'translation_mm': translation.tolist(), 'rotation_deg': rotation.tolist()},
|
|
156
|
+
'method': 'Manifold3D float32 interference; float64 triangle surface distance (vertex/face and edge/edge)',
|
|
157
|
+
'reference_rescaled': False}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export interface CadProcessOptions {
|
|
6
|
+
env: NodeJS.ProcessEnv;
|
|
7
|
+
cwd?: string;
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
export interface CadSystem {
|
|
12
|
+
platform: NodeJS.Platform;
|
|
13
|
+
run(
|
|
14
|
+
file: string,
|
|
15
|
+
args: string[],
|
|
16
|
+
options: CadProcessOptions,
|
|
17
|
+
): Promise<{ stdout: string; stderr?: string }>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** No shell, no inherited printer/provider environment, bounded output, and kill the entire dispatched group. */
|
|
21
|
+
export function runCadProcess(
|
|
22
|
+
file: string,
|
|
23
|
+
args: string[],
|
|
24
|
+
options: CadProcessOptions,
|
|
25
|
+
): Promise<{ stdout: string; stderr: string }> {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
options.signal?.throwIfAborted();
|
|
28
|
+
const child = spawn(file, args, {
|
|
29
|
+
env: options.env,
|
|
30
|
+
cwd: options.cwd,
|
|
31
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
32
|
+
detached: process.platform !== "win32",
|
|
33
|
+
});
|
|
34
|
+
let stdout = "",
|
|
35
|
+
stderr = "",
|
|
36
|
+
failure: Error | undefined;
|
|
37
|
+
const kill = () => {
|
|
38
|
+
try {
|
|
39
|
+
if (child.pid)
|
|
40
|
+
process.kill(
|
|
41
|
+
process.platform === "win32" ? child.pid : -child.pid,
|
|
42
|
+
"SIGKILL",
|
|
43
|
+
);
|
|
44
|
+
} catch {
|
|
45
|
+
/* already exited */
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const stop = (error: Error) => {
|
|
49
|
+
failure ??= error;
|
|
50
|
+
kill();
|
|
51
|
+
};
|
|
52
|
+
const timer = setTimeout(
|
|
53
|
+
() =>
|
|
54
|
+
stop(
|
|
55
|
+
new Error(
|
|
56
|
+
`CAD process timed out after ${options.timeoutMs} ms; execution was stopped, not replayed.`,
|
|
57
|
+
),
|
|
58
|
+
),
|
|
59
|
+
options.timeoutMs,
|
|
60
|
+
);
|
|
61
|
+
const abort = () =>
|
|
62
|
+
stop(
|
|
63
|
+
new Error(
|
|
64
|
+
"CAD operation cancelled; execution was stopped, not replayed.",
|
|
65
|
+
),
|
|
66
|
+
);
|
|
67
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
68
|
+
child.stdout.on("data", (b) => {
|
|
69
|
+
stdout += b.toString();
|
|
70
|
+
if (Buffer.byteLength(stdout) > 2 * 1024 * 1024)
|
|
71
|
+
stop(new Error("CAD process exceeded its output limit."));
|
|
72
|
+
});
|
|
73
|
+
child.stderr.on("data", (b) => {
|
|
74
|
+
stderr += b.toString();
|
|
75
|
+
if (Buffer.byteLength(stderr) > 2 * 1024 * 1024)
|
|
76
|
+
stop(new Error("CAD diagnostics exceeded their output limit."));
|
|
77
|
+
});
|
|
78
|
+
child.once("error", (e) => {
|
|
79
|
+
failure = e;
|
|
80
|
+
});
|
|
81
|
+
child.once("close", (code) => {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
options.signal?.removeEventListener("abort", abort);
|
|
84
|
+
kill();
|
|
85
|
+
if (failure) reject(failure);
|
|
86
|
+
else if (code !== 0)
|
|
87
|
+
reject(
|
|
88
|
+
new Error(
|
|
89
|
+
`CAD process failed (${code}): ${(stderr || stdout).slice(-6000)}`,
|
|
90
|
+
),
|
|
91
|
+
);
|
|
92
|
+
else resolve({ stdout, stderr });
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
export const defaultCadSystem: CadSystem = {
|
|
97
|
+
platform: process.platform,
|
|
98
|
+
run: runCadProcess,
|
|
99
|
+
};
|
|
100
|
+
export interface CadSandboxRoots {
|
|
101
|
+
data: string;
|
|
102
|
+
job: string;
|
|
103
|
+
assets: string;
|
|
104
|
+
python: string;
|
|
105
|
+
readonly: string[];
|
|
106
|
+
inputs?: string[];
|
|
107
|
+
}
|
|
108
|
+
const sb = (s: string) => JSON.stringify(s);
|
|
109
|
+
|
|
110
|
+
/** Linux uses an empty mount tree and fresh user/PID/network namespaces. A missing/blocked bwrap is fatal. */
|
|
111
|
+
export async function cadSandbox(
|
|
112
|
+
platform: NodeJS.Platform,
|
|
113
|
+
r: CadSandboxRoots,
|
|
114
|
+
): Promise<{ command: string; args: string[] }> {
|
|
115
|
+
if (platform === "darwin") {
|
|
116
|
+
// Runtime system files remain readable, but personal data, IPC, network and process spawning do not.
|
|
117
|
+
const variants = (p: string) => [
|
|
118
|
+
p,
|
|
119
|
+
...(/^\/(?:Users|private|Volumes)(?:\/|$)/.test(p)
|
|
120
|
+
? ["/System/Volumes/Data" + p]
|
|
121
|
+
: []),
|
|
122
|
+
];
|
|
123
|
+
const systemReads = [
|
|
124
|
+
"/System/Library",
|
|
125
|
+
"/System/Cryptexes",
|
|
126
|
+
"/System/Volumes/Preboot",
|
|
127
|
+
"/private/preboot",
|
|
128
|
+
"/Library/Fonts",
|
|
129
|
+
"/usr/lib",
|
|
130
|
+
"/usr/share",
|
|
131
|
+
"/usr/bin",
|
|
132
|
+
"/bin",
|
|
133
|
+
"/sbin",
|
|
134
|
+
"/dev",
|
|
135
|
+
"/private/etc/localtime",
|
|
136
|
+
"/etc/localtime",
|
|
137
|
+
];
|
|
138
|
+
const readable = [
|
|
139
|
+
...systemReads,
|
|
140
|
+
path.join(r.data, "runtime"),
|
|
141
|
+
path.join(r.data, "python"),
|
|
142
|
+
r.assets,
|
|
143
|
+
r.job,
|
|
144
|
+
...(r.inputs ?? []),
|
|
145
|
+
].flatMap(variants);
|
|
146
|
+
const profile = `(version 1)(allow default)
|
|
147
|
+
(deny process-info*)(allow process-info* (target self))
|
|
148
|
+
(deny sysctl-read)
|
|
149
|
+
(allow sysctl-read (sysctl-name-prefix "hw.") (sysctl-name-prefix "machdep.cpu.")
|
|
150
|
+
(sysctl-name-prefix "kern.os") (sysctl-name "kern.ostype") (sysctl-name "kern.hostname") (sysctl-name "kern.domainname")
|
|
151
|
+
(sysctl-name "kern.version") (sysctl-name "kern.maxfiles") (sysctl-name "kern.maxfilesperproc"))
|
|
152
|
+
(deny file-link)(deny network*)(deny appleevent-send)(deny mach-lookup)(deny signal)(deny process-fork)
|
|
153
|
+
(deny process-exec)(allow process-exec (literal ${sb(await fs.realpath(r.python).catch(() => r.python))}))
|
|
154
|
+
(deny file-read*)
|
|
155
|
+
(allow file-read-metadata)(deny file-write*)
|
|
156
|
+
(allow file-read* (literal "/") (literal "/System") (literal "/System/Volumes") (literal "/System/Volumes/Data") (literal "/private"))
|
|
157
|
+
(allow file-read* ${readable.map((p) => `(subpath ${sb(p)})`).join(" ")})
|
|
158
|
+
(allow file-write* ${variants(r.job)
|
|
159
|
+
.map((p) => `(subpath ${sb(p)})`)
|
|
160
|
+
.join(" ")} (literal "/dev/null"))
|
|
161
|
+
${r.readonly
|
|
162
|
+
.flatMap(variants)
|
|
163
|
+
.map((p) => `(deny file-write* (subpath ${sb(p)}))`)
|
|
164
|
+
.join("\n")}`;
|
|
165
|
+
return { command: "/usr/bin/sandbox-exec", args: ["-p", profile] };
|
|
166
|
+
}
|
|
167
|
+
if (platform === "linux") {
|
|
168
|
+
const args = [
|
|
169
|
+
"--unshare-all",
|
|
170
|
+
"--die-with-parent",
|
|
171
|
+
"--new-session",
|
|
172
|
+
"--cap-drop",
|
|
173
|
+
"ALL",
|
|
174
|
+
"--proc",
|
|
175
|
+
"/proc",
|
|
176
|
+
"--dev",
|
|
177
|
+
"/dev",
|
|
178
|
+
"--tmpfs",
|
|
179
|
+
"/tmp",
|
|
180
|
+
];
|
|
181
|
+
for (const dir of ["/usr", "/bin", "/lib", "/lib64", "/sbin"])
|
|
182
|
+
if (
|
|
183
|
+
await fs.stat(dir).then(
|
|
184
|
+
() => true,
|
|
185
|
+
() => false,
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
args.push("--ro-bind", dir, dir);
|
|
189
|
+
for (const file of ["/etc/ld.so.cache", "/etc/localtime", "/etc/fonts"]) {
|
|
190
|
+
if (
|
|
191
|
+
await fs.stat(file).then(
|
|
192
|
+
() => true,
|
|
193
|
+
() => false,
|
|
194
|
+
)
|
|
195
|
+
)
|
|
196
|
+
args.push("--ro-bind", file, file);
|
|
197
|
+
}
|
|
198
|
+
for (const dir of [
|
|
199
|
+
path.join(r.data, "runtime"),
|
|
200
|
+
path.join(r.data, "python"),
|
|
201
|
+
r.assets,
|
|
202
|
+
...(r.inputs ?? []),
|
|
203
|
+
])
|
|
204
|
+
args.push("--ro-bind", dir, dir);
|
|
205
|
+
args.push("--bind", r.job, r.job);
|
|
206
|
+
for (const file of r.readonly.filter(
|
|
207
|
+
(file) => !(r.inputs ?? []).includes(file),
|
|
208
|
+
))
|
|
209
|
+
args.push("--ro-bind", file, file);
|
|
210
|
+
args.push("--chdir", r.job);
|
|
211
|
+
return { command: "bwrap", args };
|
|
212
|
+
}
|
|
213
|
+
throw new Error(
|
|
214
|
+
`CAD confinement is unavailable on ${platform}; no unconfined execution is permitted.`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Stable CAD refusals use the same structuredContent shape as printer refusals. */
|
|
2
|
+
export const CAD_REFUSAL_CODES = [
|
|
3
|
+
"cad-uv-missing",
|
|
4
|
+
"cad-data-volume-refused",
|
|
5
|
+
"cad-setup-busy",
|
|
6
|
+
"cad-operation-busy",
|
|
7
|
+
"cad-queue-timeout",
|
|
8
|
+
"cad-not-ready",
|
|
9
|
+
"cad-confinement-unavailable",
|
|
10
|
+
"cad-disabled",
|
|
11
|
+
"cad-failed",
|
|
12
|
+
] as const;
|
|
13
|
+
export type CadRefusalCode = (typeof CAD_REFUSAL_CODES)[number];
|
|
14
|
+
export class CadRefusal extends Error {
|
|
15
|
+
constructor(
|
|
16
|
+
readonly code: CadRefusalCode,
|
|
17
|
+
message: string,
|
|
18
|
+
) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "CadRefusal";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function cadFailure(error: unknown, tool: string) {
|
|
24
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
25
|
+
return {
|
|
26
|
+
status: "error" as const,
|
|
27
|
+
code: error instanceof CadRefusal ? error.code : "cad-failed",
|
|
28
|
+
message,
|
|
29
|
+
tool,
|
|
30
|
+
retryable: false,
|
|
31
|
+
suggestion:
|
|
32
|
+
"Resolve the reported CAD condition before making another request. Interrupted work is never replayed automatically.",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
anytree==2.13.0
|
|
2
|
+
asttokens==3.0.2
|
|
3
|
+
bd-materials==0.2.5
|
|
4
|
+
build123d==0.13.0
|
|
5
|
+
cadquery-ocp-novtk==8.0.1.1.0
|
|
6
|
+
cadquery-ocp-proxy==8.0.1.1.0
|
|
7
|
+
certifi==2026.10.23
|
|
8
|
+
charset-normalizer==3.5.2
|
|
9
|
+
cloudpickle==3.1.2
|
|
10
|
+
colorama==0.4.6 ; sys_platform == 'win32'
|
|
11
|
+
dataclasses-json==0.6.7
|
|
12
|
+
deprecated==3.0.1
|
|
13
|
+
executing==2.3.0
|
|
14
|
+
ezdxf==1.4.5
|
|
15
|
+
fonttools==4.68.0
|
|
16
|
+
idna==3.20
|
|
17
|
+
imageio==2.38.1
|
|
18
|
+
ipython==9.18.1
|
|
19
|
+
ipython-pygments-lexers==1.1.1
|
|
20
|
+
jedi==0.20.1
|
|
21
|
+
joblib==1.6.0
|
|
22
|
+
lazy-loader==0.6
|
|
23
|
+
lib3mf==2.5.0 ; platform_machine != 'aarch64' or sys_platform != 'linux'
|
|
24
|
+
manifold3d==3.5.4
|
|
25
|
+
marshmallow==3.26.2
|
|
26
|
+
matplotlib-inline==0.2.2
|
|
27
|
+
mpmath==1.3.0
|
|
28
|
+
mypy-extensions==1.2.0
|
|
29
|
+
narwhals==2.28.0
|
|
30
|
+
networkx==3.7
|
|
31
|
+
numpy==2.5.4
|
|
32
|
+
ocp-gordon==0.3.1
|
|
33
|
+
ocpsvg==0.7.0
|
|
34
|
+
packaging==26.3
|
|
35
|
+
parso==0.8.7
|
|
36
|
+
pexpect==4.9.0 ; sys_platform != 'emscripten' and sys_platform != 'win32'
|
|
37
|
+
pillow==13.0.0
|
|
38
|
+
platformdirs==4.14.5
|
|
39
|
+
prompt-toolkit==3.0.53
|
|
40
|
+
psutil==7.2.2 ; sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'emscripten'
|
|
41
|
+
ptyprocess==0.7.0 ; sys_platform != 'emscripten' and sys_platform != 'win32'
|
|
42
|
+
pure-eval==0.2.4
|
|
43
|
+
py-lib3mf==2.5.0 ; platform_machine == 'aarch64' and sys_platform == 'linux'
|
|
44
|
+
pygltflib==1.16.5
|
|
45
|
+
pygments==2.21.0
|
|
46
|
+
pyparsing==3.3.3
|
|
47
|
+
requests==2.34.2
|
|
48
|
+
rtree==1.4.1
|
|
49
|
+
scikit-image==0.26.0
|
|
50
|
+
scikit-learn==1.9.1
|
|
51
|
+
scipy==1.18.1
|
|
52
|
+
shapely==2.1.2
|
|
53
|
+
stack-data==0.6.3
|
|
54
|
+
svgelements==1.9.6
|
|
55
|
+
svgpathtools==1.8.0
|
|
56
|
+
svgwrite==1.4.3
|
|
57
|
+
sympy==1.14.0
|
|
58
|
+
threadpoolctl==3.8.0
|
|
59
|
+
threejs-materials==1.2.5
|
|
60
|
+
tifffile==2026.11.8
|
|
61
|
+
traitlets==5.16.1
|
|
62
|
+
trianglesolver==1.2
|
|
63
|
+
trimesh==5.2.0
|
|
64
|
+
typing-extensions==4.16.0
|
|
65
|
+
typing-inspect==0.9.0
|
|
66
|
+
urllib3==2.8.0
|
|
67
|
+
wcwidth==0.9.4
|
|
68
|
+
webcolors==24.8.0
|
|
69
|
+
wrapt==2.5.2
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { CadRefusal } from "./refusal.js";
|
|
7
|
+
|
|
8
|
+
function dead(pid: unknown): boolean {
|
|
9
|
+
if (!Number.isInteger(pid) || Number(pid) < 1) return false;
|
|
10
|
+
try {
|
|
11
|
+
process.kill(Number(pid), 0);
|
|
12
|
+
return false;
|
|
13
|
+
} catch (e) {
|
|
14
|
+
return (e as NodeJS.ErrnoException).code === "ESRCH";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** One dispatched operation per environment; runs queue across processes and never replay. */
|
|
18
|
+
export async function withCadLock<T>(
|
|
19
|
+
data: string,
|
|
20
|
+
options: {
|
|
21
|
+
operation: "setup" | "run" | "fit";
|
|
22
|
+
deadline?: number;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
},
|
|
25
|
+
work: (waitedMs: number) => Promise<T>,
|
|
26
|
+
): Promise<T> {
|
|
27
|
+
await fs.mkdir(data, { recursive: true, mode: 0o700 });
|
|
28
|
+
const lock = path.join(data, "operation.lock"),
|
|
29
|
+
queue = path.join(data, "queue");
|
|
30
|
+
const start = performance.now();
|
|
31
|
+
let ticket: string | undefined, temporary: string | undefined;
|
|
32
|
+
const queued = options.operation === "run";
|
|
33
|
+
if (queued) {
|
|
34
|
+
await fs.mkdir(queue, { recursive: true, mode: 0o700 });
|
|
35
|
+
const name = `${String(Date.now()).padStart(13, "0")}-${process.hrtime.bigint().toString().padStart(20, "0")}-${randomUUID()}.json`;
|
|
36
|
+
ticket = path.join(queue, name);
|
|
37
|
+
temporary = path.join(queue, `.new-${randomUUID()}`);
|
|
38
|
+
await fs.writeFile(temporary, JSON.stringify({ pid: process.pid }), {
|
|
39
|
+
flag: "wx",
|
|
40
|
+
mode: 0o600,
|
|
41
|
+
});
|
|
42
|
+
await fs.rename(temporary, ticket);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
for (;;) {
|
|
46
|
+
options.signal?.throwIfAborted();
|
|
47
|
+
if (queued && performance.now() >= options.deadline!)
|
|
48
|
+
throw new CadRefusal(
|
|
49
|
+
"cad-queue-timeout",
|
|
50
|
+
"The CAD run's timeout expired while waiting for another operation. This run was not dispatched.",
|
|
51
|
+
);
|
|
52
|
+
const names = (
|
|
53
|
+
await fs.readdir(queue).catch((e) => {
|
|
54
|
+
if (e.code === "ENOENT") return [] as string[];
|
|
55
|
+
throw e;
|
|
56
|
+
})
|
|
57
|
+
)
|
|
58
|
+
.filter((n) => /^\d+-\d+-[a-f0-9-]+\.json$/.test(n))
|
|
59
|
+
.sort();
|
|
60
|
+
const live: string[] = [];
|
|
61
|
+
for (const name of names) {
|
|
62
|
+
const file = path.join(queue, name);
|
|
63
|
+
try {
|
|
64
|
+
const previous = JSON.parse(await fs.readFile(file, "utf8"));
|
|
65
|
+
if (dead(previous.pid)) {
|
|
66
|
+
await fs.unlink(file).catch(() => {});
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
} catch (e) {
|
|
70
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
71
|
+
}
|
|
72
|
+
live.push(name);
|
|
73
|
+
}
|
|
74
|
+
const turn = queued
|
|
75
|
+
? live[0] === path.basename(ticket!)
|
|
76
|
+
: live.length === 0;
|
|
77
|
+
let handle;
|
|
78
|
+
if (turn) {
|
|
79
|
+
try {
|
|
80
|
+
handle = await fs.open(lock, "wx", 0o600);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
|
83
|
+
try {
|
|
84
|
+
const previous = JSON.parse(await fs.readFile(lock, "utf8"));
|
|
85
|
+
if (dead(previous.pid)) {
|
|
86
|
+
await fs.unlink(lock).catch(() => {});
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
/* A partially written live lock stays locked. */
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (handle) {
|
|
95
|
+
try {
|
|
96
|
+
await handle.writeFile(
|
|
97
|
+
JSON.stringify({ pid: process.pid, operation: options.operation }),
|
|
98
|
+
);
|
|
99
|
+
if (ticket) {
|
|
100
|
+
await fs.unlink(ticket);
|
|
101
|
+
ticket = undefined;
|
|
102
|
+
}
|
|
103
|
+
return await work(Math.round(performance.now() - start));
|
|
104
|
+
} finally {
|
|
105
|
+
await handle.close();
|
|
106
|
+
await fs.unlink(lock).catch(() => {});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (!queued)
|
|
110
|
+
throw new CadRefusal(
|
|
111
|
+
options.operation === "setup"
|
|
112
|
+
? "cad-setup-busy"
|
|
113
|
+
: "cad-operation-busy",
|
|
114
|
+
"Another CAD operation is already running or queued. Wait for it to finish; this request was not dispatched.",
|
|
115
|
+
);
|
|
116
|
+
await delay(
|
|
117
|
+
Math.min(50, Math.max(1, options.deadline! - performance.now())),
|
|
118
|
+
undefined,
|
|
119
|
+
{ signal: options.signal },
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
if (ticket) await fs.unlink(ticket).catch(() => {});
|
|
124
|
+
if (temporary) await fs.unlink(temporary).catch(() => {});
|
|
125
|
+
}
|
|
126
|
+
}
|