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.
package/dist/index.js CHANGED
@@ -27,6 +27,9 @@ import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } fr
27
27
  import { BambuNetworkBridge, bridgeSnapshotRoot, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
28
28
  import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
29
29
  import { importFileViaBambuConnect } from "./bambu-connect.js";
30
+ import { CadEngine } from "./cad-engine.js";
31
+ import { CadRefusal } from "./cad/refusal.js";
32
+ import { CAD_TOOLS, cadEnabled } from "./cad/contracts.js";
30
33
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
31
34
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
32
35
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake } from "./design-app-setup.js";
@@ -55,6 +58,7 @@ import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome }
55
58
  import { uploadProgressReporter } from "./upload-progress.js";
56
59
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
57
60
  dotenv.config();
61
+ const CAD_ENABLED = cadEnabled();
58
62
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
59
63
  const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
60
64
  const DEFAULT_BAMBU_TOKEN = process.env.BAMBU_PRINTER_ACCESS_TOKEN || process.env.BAMBU_TOKEN || "";
@@ -115,6 +119,7 @@ const SERVER_INFO = {
115
119
  };
116
120
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
117
121
  const OUTPUT_SCHEMA_TOOLS = new Set([
122
+ "cad_status", "cad_setup", "cad_run", "cad_check_fit",
118
123
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
119
124
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
120
125
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
@@ -1109,6 +1114,7 @@ if (!fs.existsSync(TEMP_DIR)) {
1109
1114
  }
1110
1115
  class BambuPrinterMCPServer {
1111
1116
  constructor() {
1117
+ this.cad = new CadEngine({ outputRoots: [TEMP_DIR, ...(process.env.CAD_OUTPUT_DIRS?.split(path.delimiter).filter(Boolean) ?? [])] });
1112
1118
  this.blender = new BlenderMcpBridge();
1113
1119
  this.fusion = new FusionMcpBridge();
1114
1120
  // Downloads and installer output are staged in this server's own temporary folder.
@@ -1123,7 +1129,7 @@ class BambuPrinterMCPServer {
1123
1129
  resources: {},
1124
1130
  tools: {}
1125
1131
  },
1126
- instructions: SERVER_INSTRUCTIONS
1132
+ instructions: SERVER_INSTRUCTIONS + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
1127
1133
  });
1128
1134
  this.bambu = new BambuImplementation(async (message) => {
1129
1135
  try {
@@ -1874,7 +1880,7 @@ class BambuPrinterMCPServer {
1874
1880
  /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
1875
1881
  setupPromptHandlers() {
1876
1882
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
1877
- prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
1883
+ prompts: [...DESIGN_PROMPTS.filter(p => CAD_ENABLED || p.name !== "cad_design"), FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
1878
1884
  }));
1879
1885
  this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1880
1886
  if (request.params.name === FDM_SLICING_PROMPT.name) {
@@ -1885,7 +1891,7 @@ class BambuPrinterMCPServer {
1885
1891
  messages: [{ role: "user", content: { type: "text", text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
1886
1892
  };
1887
1893
  }
1888
- const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
1894
+ const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name && (CAD_ENABLED || item.name !== "cad_design"));
1889
1895
  if (!prompt)
1890
1896
  throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
1891
1897
  return {
@@ -2959,6 +2965,7 @@ class BambuPrinterMCPServer {
2959
2965
  required: ["stl_path"]
2960
2966
  }
2961
2967
  },
2968
+ ...(CAD_ENABLED ? CAD_TOOLS : []),
2962
2969
  {
2963
2970
  name: "blender_mcp_status",
2964
2971
  description: "Inspect Blender MCP configuration or connect and discover the remote server's tools and schemas. Connecting does not edit the scene; use get_scene_info through blender_mcp_call to check the Blender addon.",
@@ -3234,6 +3241,10 @@ class BambuPrinterMCPServer {
3234
3241
  .then(() => extra.sendNotification({ method: "notifications/progress", params: { progressToken, ...params } }))
3235
3242
  .catch(() => { });
3236
3243
  });
3244
+ if (!CAD_ENABLED && name.startsWith("cad_")) {
3245
+ const failure = await this.cad.failure(new CadRefusal("cad-disabled", "Code-CAD is disabled by CAD_ENABLED=0."), name);
3246
+ return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
3247
+ }
3237
3248
  const host = String(args?.host || DEFAULT_HOST);
3238
3249
  const bambuSerial = String(args?.bambu_serial || DEFAULT_BAMBU_SERIAL);
3239
3250
  const bambuToken = String(args?.bambu_token || DEFAULT_BAMBU_TOKEN);
@@ -4369,6 +4380,32 @@ class BambuPrinterMCPServer {
4369
4380
  case "counterpart_make_3mf":
4370
4381
  result = await makeCounterpart3mf(args ?? {});
4371
4382
  break;
4383
+ case "cad_status":
4384
+ if (args && Object.keys(args).length)
4385
+ throw new Error("cad_status takes no arguments.");
4386
+ result = await this.cad.status();
4387
+ break;
4388
+ case "cad_setup":
4389
+ case "cad_run":
4390
+ case "cad_check_fit": {
4391
+ const started = Date.now();
4392
+ let sequence = 0;
4393
+ const heartbeat = progressToken === undefined ? undefined : setInterval(() => {
4394
+ progressNotifications = progressNotifications.then(() => extra.sendNotification({ method: "notifications/progress", params: {
4395
+ progressToken, progress: ++sequence, message: `${name}: working for ${Math.round((Date.now() - started) / 1000)} seconds`,
4396
+ } })).catch(() => { });
4397
+ }, 5000);
4398
+ try {
4399
+ result = name === "cad_setup" ? await this.cad.setup(args ?? {}, extra.signal)
4400
+ : name === "cad_run" ? await this.cad.run(args ?? {}, extra.signal)
4401
+ : await this.cad.checkFit(args ?? {}, extra.signal);
4402
+ }
4403
+ finally {
4404
+ if (heartbeat)
4405
+ clearInterval(heartbeat);
4406
+ }
4407
+ break;
4408
+ }
4372
4409
  case "blender_mcp_setup":
4373
4410
  if (args?.update !== undefined && typeof args.update !== "boolean")
4374
4411
  throw new Error("update must be a boolean.");
@@ -4412,6 +4449,10 @@ class BambuPrinterMCPServer {
4412
4449
  return { content: [{ type: "text", text }] };
4413
4450
  }
4414
4451
  catch (error) {
4452
+ if (name.startsWith("cad_")) {
4453
+ const failure = await this.cad.failure(error, name);
4454
+ return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
4455
+ }
4415
4456
  const message = error instanceof Error ? error.message : String(error);
4416
4457
  // Refusals and printer rejections repeat unchanged; say what to fix instead of "try again".
4417
4458
  const refused = /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
@@ -12,6 +12,10 @@ const START_PRINT = hints(false, false, false, true);
12
12
  /** Starts a print, auto-slicing an unsliced project first, which replaces an earlier slice output of that name. */
13
13
  const SLICE_AND_PRINT = hints(false, true, false, true);
14
14
  export const TOOL_ANNOTATIONS = {
15
+ cad_status: READ_LOCAL,
16
+ cad_setup: hints(false, true, true, true),
17
+ cad_run: hints(false, false, false, false),
18
+ cad_check_fit: READ_LOCAL,
15
19
  // Printer and cloud reads
16
20
  get_printer_status: READ_OUTSIDE,
17
21
  get_printer_filaments: READ_OUTSIDE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.82",
3
+ "version": "1.1.83",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -0,0 +1,317 @@
1
+ import { CAD_REFUSAL_CODES } from "./refusal.js";
2
+ /** cad/1 is an optional engine owned by the printer MCP. Readiness comes from cad_status, not the capability. */
3
+ export function cadEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
4
+ return !["0", "false", "off"].includes(
5
+ env.CAD_ENABLED?.trim().toLowerCase() ?? "",
6
+ );
7
+ }
8
+ export const CAD_CAPABILITY = {
9
+ contract: "cad/1",
10
+ status: "cad_status",
11
+ setup: "cad_setup",
12
+ run: "cad_run",
13
+ checkFit: "cad_check_fit",
14
+ prompt: "cad_design",
15
+ } as const;
16
+ const storage = {
17
+ type: "object",
18
+ properties: {
19
+ expected_download_bytes: { type: "integer" },
20
+ expected_installed_bytes: { type: "integer" },
21
+ installed_bytes: { type: ["integer", "null"] },
22
+ measurement: { type: "string", const: "allocated-last-setup" },
23
+ measured_at: { type: "string" },
24
+ },
25
+ required: [
26
+ "expected_download_bytes",
27
+ "expected_installed_bytes",
28
+ "installed_bytes",
29
+ "measurement",
30
+ ],
31
+ };
32
+ const status = {
33
+ storage,
34
+ configured: { type: "boolean" },
35
+ ready: { type: "boolean" },
36
+ python: { type: ["string", "null"] },
37
+ build123d: { type: "string" },
38
+ platform: { type: "string" },
39
+ error: { type: "string" },
40
+ };
41
+ const failure = {
42
+ type: "object",
43
+ properties: {
44
+ status: { type: "string", const: "error" },
45
+ code: { type: "string", enum: [...CAD_REFUSAL_CODES] },
46
+ message: { type: "string" },
47
+ tool: { type: "string" },
48
+ retryable: { type: "boolean" },
49
+ suggestion: { type: "string" },
50
+ storage,
51
+ },
52
+ required: ["status", "code", "message", "tool", "retryable", "suggestion"],
53
+ };
54
+ const output = (properties: Record<string, unknown>, required: string[]) => ({
55
+ type: "object" as const,
56
+ anyOf: [{ type: "object", properties, required }, failure],
57
+ });
58
+ const timeout = {
59
+ type: "integer",
60
+ minimum: 100,
61
+ maximum: 900000,
62
+ description:
63
+ "Total queue wait, preparation, execution and inspection deadline. Default 120000 ms; cancellation kills the dispatched process group.",
64
+ };
65
+ export const CAD_TOOLS = [
66
+ {
67
+ name: "cad_status",
68
+ description:
69
+ "Read the optional code-CAD runtime's last verified readiness and pinned version, without starting Python or installing anything.",
70
+ inputSchema: {
71
+ type: "object" as const,
72
+ properties: {},
73
+ additionalProperties: false,
74
+ },
75
+ outputSchema: output(status, [
76
+ "configured",
77
+ "ready",
78
+ "python",
79
+ "build123d",
80
+ "platform",
81
+ "storage",
82
+ ]),
83
+ },
84
+ {
85
+ name: "cad_setup",
86
+ description:
87
+ "Check the optional confined build123d runtime. With install: true, use uv to install pinned Python/packages in this MCP's data directory and prove a confined build plus STL/STEP round trip. On macOS, the data directory must be on an internal disk with file ownership enabled; external/network volumes are refused before installation. Native signatures are never modified. Never starts Blender, Fusion or a printer.",
88
+ inputSchema: {
89
+ type: "object" as const,
90
+ properties: {
91
+ install: {
92
+ type: "boolean",
93
+ default: false,
94
+ description:
95
+ "Install and verify the pinned optional runtime; false only checks it.",
96
+ },
97
+ },
98
+ additionalProperties: false,
99
+ },
100
+ outputSchema: output(
101
+ {
102
+ ...status,
103
+ supported: { type: "boolean" },
104
+ installed: { type: "boolean" },
105
+ message: { type: "string" },
106
+ },
107
+ ["supported", "configured", "ready", "storage"],
108
+ ),
109
+ },
110
+ {
111
+ name: "cad_run",
112
+ description:
113
+ "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six renders and a contact sheet; valid geometry is not a physical-fit or motion proof.",
114
+ inputSchema: {
115
+ type: "object" as const,
116
+ properties: {
117
+ inputs: {
118
+ type: "array",
119
+ maxItems: 16,
120
+ items: {
121
+ type: "object",
122
+ properties: { name: { type: "string" }, path: { type: "string" } },
123
+ required: ["name", "path"],
124
+ additionalProperties: false,
125
+ },
126
+ description:
127
+ "Explicit named files [{name, path}]. Content-addressed immutable input bundles are reused; snapshot_bytes_added/reused report storage. Only the selected declared bundle is exposed to build() as INPUTS[name]; nested path is declared for remote path policy.",
128
+ },
129
+ mode: {
130
+ type: "string",
131
+ enum: ["solid", "mesh"],
132
+ default: "solid",
133
+ description:
134
+ "solid returns build123d B-rep with STL/STEP; mesh returns trimesh.Trimesh with STL and an explicit unavailable STEP.",
135
+ },
136
+ script: {
137
+ type: "string",
138
+ maxLength: 262144,
139
+ description:
140
+ "Python source declaring literal named P parameters and build() returning a Shape.",
141
+ },
142
+ script_path: {
143
+ type: "string",
144
+ description:
145
+ "Allowed saved .py checkpoint to rebuild or edit instead of resending script.",
146
+ },
147
+ parameters: {
148
+ type: "object",
149
+ additionalProperties: true,
150
+ description:
151
+ "Overrides for names already declared in P; saved values are retained.",
152
+ },
153
+ output_dir: {
154
+ type: "string",
155
+ description:
156
+ "Existing allowed directory; a unique immutable run subfolder is created beneath it.",
157
+ },
158
+ name: {
159
+ type: "string",
160
+ maxLength: 64,
161
+ description:
162
+ "Plain file stem for STL, STEP, Python and parameter artifacts.",
163
+ },
164
+ final: {
165
+ type: "boolean",
166
+ default: false,
167
+ description:
168
+ "Mark the selected result. The protected cad-result.json records this flag and all returned validation; select completed final records after restart and still inspect valid/checks.",
169
+ },
170
+ timeout_ms: timeout,
171
+ },
172
+ required: ["output_dir", "name"],
173
+ additionalProperties: false,
174
+ },
175
+ outputSchema: output(
176
+ {
177
+ status: { type: "string", const: "completed" },
178
+ final: { type: "boolean" },
179
+ completed_at: { type: "string" },
180
+ lineage_id: { type: "string" },
181
+ result_manifest: { type: "string" },
182
+ queue_wait_ms: { type: "integer" },
183
+ snapshot_bytes_added: { type: "integer" },
184
+ snapshot_bytes_reused: { type: "integer" },
185
+ input_hashes: {
186
+ type: "object",
187
+ additionalProperties: { type: "string" },
188
+ },
189
+ valid: { type: "boolean" },
190
+ units: { const: "mm", type: "string" },
191
+ script: { type: "string" },
192
+ parameters: { type: "string" },
193
+ stl: { type: "string" },
194
+ step: { type: ["string", "null"] },
195
+ step_unavailable: { type: "string" },
196
+ inputs: { type: "object", additionalProperties: { type: "string" } },
197
+ input_manifest: { type: "string" },
198
+ bounds_mm: {
199
+ type: "array",
200
+ items: { type: "array", items: { type: "number" } },
201
+ },
202
+ size_mm: { type: "array", items: { type: "number" } },
203
+ volume_mm3: { type: ["number", "null"] },
204
+ step_volume_mm3: { type: ["number", "null"] },
205
+ solid_count: { type: "integer" },
206
+ mesh_components: { type: "integer" },
207
+ checks: {
208
+ type: "object",
209
+ additionalProperties: { type: ["boolean", "null"] },
210
+ },
211
+ renders: { type: "object", additionalProperties: { type: "string" } },
212
+ seconds: { type: "number" },
213
+ },
214
+ [
215
+ "valid",
216
+ "status",
217
+ "final",
218
+ "completed_at",
219
+ "lineage_id",
220
+ "result_manifest",
221
+ "queue_wait_ms",
222
+ "snapshot_bytes_added",
223
+ "snapshot_bytes_reused",
224
+ "script",
225
+ "parameters",
226
+ "stl",
227
+ "step",
228
+ "bounds_mm",
229
+ "solid_count",
230
+ "checks",
231
+ "renders",
232
+ ],
233
+ ),
234
+ },
235
+ {
236
+ name: "cad_check_fit",
237
+ description:
238
+ "Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Fails rather than guessing for open meshes or excessive triangle workload.",
239
+ inputSchema: {
240
+ type: "object" as const,
241
+ properties: {
242
+ model: {
243
+ type: "string",
244
+ description: "Allowed watertight manifold model STL in millimetres.",
245
+ },
246
+ reference: {
247
+ type: "string",
248
+ description:
249
+ "Allowed reference/scan STL in millimetres; never rescaled implicitly.",
250
+ },
251
+ transform: {
252
+ type: "object",
253
+ description:
254
+ "Rigid transform applied only to reference: XYZ rotation about origin, then translation.",
255
+ properties: {
256
+ translation_mm: {
257
+ type: "array",
258
+ items: { type: "number" },
259
+ minItems: 3,
260
+ maxItems: 3,
261
+ },
262
+ rotation_deg: {
263
+ type: "array",
264
+ items: { type: "number" },
265
+ minItems: 3,
266
+ maxItems: 3,
267
+ },
268
+ },
269
+ additionalProperties: false,
270
+ },
271
+ clearance_mm: {
272
+ type: "number",
273
+ minimum: 0,
274
+ maximum: 100,
275
+ description:
276
+ "Required global minimum surface gap; intentional support contact has zero gap.",
277
+ },
278
+ timeout_ms: timeout,
279
+ },
280
+ required: ["model", "reference"],
281
+ additionalProperties: false,
282
+ },
283
+ outputSchema: output(
284
+ {
285
+ units: { type: "string", const: "mm" },
286
+ interference_volume_mm3: { type: "number" },
287
+ minimum_gap_mm: { type: "number" },
288
+ clearance_mm: { type: "number" },
289
+ clear: { type: "boolean" },
290
+ transform: { type: "object" },
291
+ method: { type: "string" },
292
+ reference_rescaled: { type: "boolean", const: false },
293
+ },
294
+ [
295
+ "interference_volume_mm3",
296
+ "minimum_gap_mm",
297
+ "clear",
298
+ "transform",
299
+ "reference_rescaled",
300
+ ],
301
+ ),
302
+ },
303
+ ];
304
+ export const CAD_DESIGN_PROMPT = {
305
+ name: "cad_design",
306
+ title: "Parametric code-CAD design",
307
+ description:
308
+ "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
309
+ text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
310
+ Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus six renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
311
+ Call cad_run with script, output_dir and a plain name. It saves <name>.py and <name>.parameters.json before running, then exports <name>.stl and <name>.step in a fresh subfolder. For an edit, one cad_run with script_path pointing to the earlier .py, parameters containing just the changed dimension, output_dir and name regenerates it without resending the script. Existing parameter values are retained; unknown names and type changes are refused. A killed run can be retried from its checkpoint in a new workspace; mutations are never replayed automatically.
312
+ Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"|"-x"|"y"|"-y"|"z"|"-z", ground=True) is provided to build(). Name must be a declared input. Declare source units and the object's usage-up axis explicitly: the helper converts metres to millimetres, applies a rigid up-axis rotation and translates the lowest Z to zero; it never guesses scale or fits to calipers. Geometry/texture references must be declared inputs too; snapshots preserve distinct original filenames. Exports must be millimetres, Z up, in the orientation the object is used.
313
+ Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y") from build() in mode: "mesh" to export an unchanged, prepared reference STL for cad_check_fit. Declare every linked OBJ/MTL/texture asset. If you crop, simplify, fill, or otherwise alter this reference, report exactly what you excluded/changed and that the fit check proves only that reduced reference in the stated pose. A fit check against a scan is information; it must never resize or override an interface specified by measured dimensions. Keep those measured interfaces and report the discrepancy.
314
+ Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
315
+ Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
316
+ The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, six orthographic renders (front, back, left, right, top, bottom) and contact sheet. Inspect all six; revise visible defects. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence. Apply fdm_design and fdm_slicing too; never invoke a printer as part of constructing CAD.`,
317
+ };
@@ -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}