bambu-printer-mcp 1.1.90 → 1.1.92

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.
Files changed (86) hide show
  1. package/CONTRIBUTORS.md +2 -0
  2. package/README.md +48 -3
  3. package/dist/bambu-native.js +1 -1
  4. package/dist/cad/contracts.js +16 -7
  5. package/dist/cad/examples.d.ts +2 -1
  6. package/dist/cad/examples.js +13 -10
  7. package/dist/cad/serial.d.ts +1 -1
  8. package/dist/cad/serial.js +4 -6
  9. package/dist/cad-engine.js +17 -12
  10. package/dist/counterpart/flight-record.d.ts +155 -0
  11. package/dist/counterpart/flight-record.js +831 -0
  12. package/dist/counterpart/flight-tools.d.ts +213 -0
  13. package/dist/counterpart/flight-tools.js +232 -0
  14. package/dist/counterpart/fresh-frame.d.ts +16 -0
  15. package/dist/counterpart/fresh-frame.js +26 -0
  16. package/dist/counterpart/make-3mf.js +1 -4
  17. package/dist/counterpart/physical-evidence.d.ts +70 -0
  18. package/dist/counterpart/physical-evidence.js +103 -0
  19. package/dist/counterpart/print-geometry.d.ts +13 -0
  20. package/dist/counterpart/print-geometry.js +181 -0
  21. package/dist/counterpart/remote.js +2 -0
  22. package/dist/counterpart/schemas.d.ts +32 -0
  23. package/dist/counterpart/schemas.js +2 -0
  24. package/dist/counterpart/visual-evidence.d.ts +38 -0
  25. package/dist/counterpart/visual-evidence.js +155 -0
  26. package/dist/index.js +63 -24
  27. package/dist/printers/bambu.d.ts +15 -2
  28. package/dist/printers/bambu.js +64 -12
  29. package/dist/safety/limits.d.ts +6 -0
  30. package/dist/safety/limits.js +8 -0
  31. package/dist/safety/print-file.js +2 -2
  32. package/dist/safety/print-preview.d.ts +2 -0
  33. package/dist/safety/print-preview.js +1 -1
  34. package/dist/safety/printer-state.d.ts +4 -0
  35. package/dist/safety/printer-state.js +14 -1
  36. package/dist/slicer/3mf-xml.d.ts +7 -0
  37. package/dist/slicer/3mf-xml.js +61 -0
  38. package/dist/stl/stl-manipulator.js +5 -2
  39. package/dist/studio-print-options.d.ts +9 -0
  40. package/dist/studio-print-options.js +34 -2
  41. package/dist/tool-annotations.js +2 -0
  42. package/package.json +2 -1
  43. package/src/bambu-native.ts +1 -1
  44. package/src/cad/contracts.ts +17 -7
  45. package/src/cad/examples/bag_clip.py +1 -0
  46. package/src/cad/examples/bistable_clicker.py +1 -0
  47. package/src/cad/examples/broom_grip.py +61 -0
  48. package/src/cad/examples/cable_clip.py +1 -0
  49. package/src/cad/examples/chainmail.py +1 -0
  50. package/src/cad/examples/desk_clamp_hook.py +91 -0
  51. package/src/cad/examples/desk_edge_cable_holder.py +55 -0
  52. package/src/cad/examples/drawer_divider.py +56 -0
  53. package/src/cad/examples/hinged_box.py +1 -0
  54. package/src/cad/examples/knurled_knob.py +1 -0
  55. package/src/cad/examples/loft_handle.py +1 -0
  56. package/src/cad/examples/organizer_tray.py +41 -0
  57. package/src/cad/examples/phone_stand.py +1 -0
  58. package/src/cad/examples/plant_pot.py +53 -0
  59. package/src/cad/examples/shelf_bracket.py +53 -0
  60. package/src/cad/examples/swept_hook.py +1 -0
  61. package/src/cad/examples/threaded_jar.py +1 -0
  62. package/src/cad/examples/trigger_capo.py +1 -0
  63. package/src/cad/examples/wall_hook.py +1 -0
  64. package/src/cad/examples.ts +13 -10
  65. package/src/cad/geometry.py +6 -0
  66. package/src/cad/serial.ts +4 -6
  67. package/src/cad-engine.ts +9 -3
  68. package/src/counterpart/flight-record.ts +984 -0
  69. package/src/counterpart/flight-tools.ts +282 -0
  70. package/src/counterpart/fresh-frame.ts +45 -0
  71. package/src/counterpart/make-3mf.ts +1 -5
  72. package/src/counterpart/physical-evidence.ts +185 -0
  73. package/src/counterpart/print-geometry.ts +192 -0
  74. package/src/counterpart/remote.ts +2 -0
  75. package/src/counterpart/schemas.ts +3 -0
  76. package/src/counterpart/visual-evidence.ts +212 -0
  77. package/src/index.ts +61 -21
  78. package/src/printers/bambu.ts +64 -10
  79. package/src/safety/limits.ts +8 -0
  80. package/src/safety/print-file.ts +2 -2
  81. package/src/safety/print-preview.ts +1 -1
  82. package/src/safety/printer-state.ts +13 -1
  83. package/src/slicer/3mf-xml.ts +52 -0
  84. package/src/stl/stl-manipulator.ts +4 -1
  85. package/src/studio-print-options.ts +33 -2
  86. package/src/tool-annotations.ts +2 -0
package/CONTRIBUTORS.md CHANGED
@@ -6,6 +6,8 @@ Thank you to everyone who builds, tests, reports problems, and shares real print
6
6
 
7
7
  | Contributor | Contribution |
8
8
  | --- | --- |
9
+ | [ianhyzy](https://github.com/ianhyzy) | Contributes the one-way P1S-file/P1P-printer compatibility change in [#140](https://github.com/DMontgomery40/bambu-printer-mcp/pull/140), with P1P enclosure-kit hardware, firmware and Bambu Studio inspection evidence. Integration adds mocked route and live-identity regressions; those tests do not establish a physical MCP print. |
10
+ | [geooff](https://github.com/geooff) | Contributes X1C firmware 01.12 external-slot normalization and the opt-in native print/upload route in [#128](https://github.com/DMontgomery40/bambu-printer-mcp/pull/128), with one reported physical macOS X1C print to an SD card using an AMS 2 Pro slot. Linux, other X1C firmware and X1E hardware remain unverified. Integration adds fresh storage-capability and mocked dispatch/resume regressions; these do not independently verify physical printing. |
9
11
  | [Rowan McMahon (RowanMcMahon)](https://github.com/RowanMcMahon) | Reports A1 firmware 01.08.01.00 retaining `FAILED` after a stopped job and contributes the narrow terminal-state fix and regression tests in [#133](https://github.com/DMontgomery40/bambu-printer-mcp/pull/133). Supplies fresh MQTT evidence and reports a subsequent job reaching `FINISH`; this is contributor-reported status, not inspected physical-part verification. |
10
12
  | [billh-hub](https://github.com/billh-hub) | Reports and isolates three official H2C time-lapse and filament-change command rejections in [#84](https://github.com/DMontgomery40/bambu-printer-mcp/issues/84), supplies emitted commands and multi-colour reproduction evidence, and distinguishes the unknown cooling parameter for source-backed investigation. The correction preserves independent safety checks; no maintainer physical printing is claimed. |
11
13
  | [Steve Pritchard (sjpritchard)](https://github.com/sjpritchard) | Reports and diagnoses H2C per-variant first-layer temperature rejection in [#81](https://github.com/DMontgomery40/bambu-printer-mcp/issues/81), supplies the exact official preset metadata and reproduction, and identifies the upstream variant-mapping contract. Verification uses synthetic slicing and offline regressions, not physical printing. |
package/README.md CHANGED
@@ -643,6 +643,49 @@ Two transports are wired in, picked by `bambu_model`:
643
643
 
644
644
  Returns `{ status, format: "image/jpeg", sizeBytes, base64, savedTo?, transport }`. `transport` is `"tcp-6000"` or `"rtsps-322"` so callers can tell which path produced the frame. Pass `save_path` to also write the bytes to disk; otherwise only the base64 payload is returned.
645
645
 
646
+ #### counterpart_print_record
647
+
648
+ Use `list_jobs: true` to discover the retained job IDs before selecting an older `job_id`. Latest-job reads discover newer dispatches made by another MCP process. The process that authorized dispatch owns report writes while it is alive; after it exits, a restarted observer can take over from the saved record. Concurrent passive MCP sessions read the same disk evidence without overwriting the active recorder. Camera bytes appear once, in `structuredContent`, when `include_frames: true`.
649
+
650
+ Read the flight record of a job this server dispatched, without contacting the printer. Firmware `finished` means the printer finished its commands; it does not verify the physical object.
651
+
652
+ ```json
653
+ {"job_id":"optional saved record UUID", "include_frames":false}
654
+ ```
655
+
656
+ Omit `job_id` for the latest job on the configured printer; ordinary printer target overrides select another saved printer. The result has `contract: "counterpart/1"`, `status: "recorded" | "unavailable"`, an optional version-1 `record`, and separate `physical` evidence. Bambu records allowlisted native report fields; other adapters retain their existing normalized observations, without inventing fields their firmware/adapter does not expose. A record is established at the existing send-authorization boundary, so a lost transport/helper reply still leaves the exact hash/mapping with `dispatch.outcome: "unconfirmed"`. A successful transport reply marks it `accepted`; a matching active firmware report marks it `observed-active`. These outcomes do not verify physical success or authorize a retry. The record retains the inspected artifact SHA-256, selected plate/hash, filament mapping/materials, timestamped allowlisted state/error/stage/AMS/temperature changes, latest state, truncation count and camera metadata. Printer names, hosts, serials, credentials, arbitrary report text and URLs are excluded; the target and dispatched job identity are hashed. Raw unknown fields remain unknown; AMS `remain: -1` is not empty. After an active report has been seen, firmware terminal reports freeze the job record so later cooling does not evict its failure evidence. Returned task/subtask execution IDs are hashed. A changed execution ID or an observed ended-to-active reprint invalidates current-progress evidence durably (a bounded one-byte marker), including same-filename reprints; explicit archived reads keep the original evidence. History before this feature or outside retained/connected observations is unavailable, not reconstructed by contacting the printer.
657
+
658
+ Storage is private (directory 0700, files 0600), survives MCP restart, and is capped at ten jobs, 1 MiB/2048 report changes per job, a 64 KiB visual-observation sidecar, and 32 JPEGs of at most 512 KiB each. At most four images are returned per request. Older changes/jobs are removed; `droppedReports`, `droppedFrames` and `skippedCheckpoints` disclose gaps. `COUNTERPART_RECORD_DIR` is a trusted server environment override, never a tool-selected filesystem path. Storage failure warns on stderr and marks a record volatile; diagnostics never authorize printing, resume or another mutation.
659
+
660
+ While the client monitors `counterpart_print_progress`, existing reports trigger bounded asynchronous preparation-frame candidates (up to three stage changes), a first-layer frame, a completed-first-layer follow-up when layer 2 is observed, then a snapshot at crossed ten-layer milestones and height fractions (5%, 30%, 60%, 90%). The 32-frame ring preserves baseline/first-layer evidence and the latest recorded empty-footprint anomaly. There is no additional status polling or autonomous watcher. Without a monitoring client, known layer geometry, a matching active job and a usable existing camera source, no physical verdict is inferred. Skipped heights are not backfilled. Each frame binds its ID, actual report layer/time, expected sliced Z, capture receipt/acquisition time and image SHA-256. Image acquisition must be at or after its associated report boundary; an active stream waits for a newer frame when its cached frame predates that boundary. Old cached frames, a layer/state change during acquisition, and bounded camera failures are marked unavailable. A stable reported layer is not a hardware-synchronized shutter. `include_frames:true` reads saved JPEG base64 from disk; it does not open a camera. Expected geometry is the selected 3MF plate's or inspected standalone G-code snapshot's sliced layer Z and extrusion-path XY bounds, including swept extrema for G2/G3 XY arcs, not a calibrated camera silhouette or measured flow. Oversize/unsupported G-code or missing layer reports leave geometry/correspondence unknown.
661
+
662
+ `physical.status` is `unknown`, `consistent`, `suspect_no_growth` or `suspect_no_extrusion`, independently of firmware state. Without a usable client visual observation or calibrated height measurements it remains **unknown**, including after FINISH. When `physical.assessment` is present, the client worker should fetch its `frameId` and any useful `referenceFrameIds` with `counterpart_print_record` using `frame_format:"images"` and optional `frame_ids` (at most four). This returns normal MCP image content exactly once, indexed by `imageContentIndex` in frame metadata. Image format defaults to compact `view:"evidence"`; `omittedReports`/`omittedGeometryLayers` disclose omitted journal detail. `view:"record"` retains the full forensic record. The request includes the selected sliced footprint bounds, layer/height and explicit visibility/deposition criteria.
663
+
664
+ The client vision worker then calls **`counterpart_print_assess`** with:
665
+
666
+ ```json
667
+ {"job_id":"saved job UUID","artifact_sha256":"saved dispatch hash","frame_id":"saved frame UUID","image_sha256":"saved JPEG hash","visibility":"clear","footprint_visible":true,"deposition":"absent","attempted":true}
668
+ ```
669
+
670
+ The hashes/IDs must match the saved job and image. `visibility` is `clear|dark|occluded|out_of_view|unknown`; `deposition` is `absent|present|unknown`. Set `attempted` only when the frame follows attempted object deposition, and `footprint_visible` only when sufficient expected deposition area can be judged. Optional `reference_frame_id`, `reference_visibility` and `reference_empty` provide empty-bed context. **A clearly visible empty footprint after attempted printing is sufficient for `suspect_no_extrusion`; no reference is required.** A lowered, dark or occluded reference is not proof and does not suppress a clear direct observation. Dark/occluded/unlocatable current evidence stays unknown. Merely visible material does not verify height, coverage or final success.
671
+
672
+ This tool writes only bounded local visual observations (idempotently) and has no printer/camera I/O, model call or control. Observations live separately from the single-writer telemetry journal, so a worker process cannot overwrite live reports. Their result survives MCP restart and firmware FINISH. A `suspect_no_extrusion` warning stays active for the job through later unknown/dark/occluded observations and FINISH; only a later clear `present` observation with a visible footprint at a higher layer may supersede it (without proving final success). It is the first structured progress problem, with the observed layer (`physical.observedLayer`) and separate wording after firmware completion. A first-layer `unknown` observation still permits a new assessment at the crossed ten-layer checkpoint (10, 20, …), subject to fresh reports, available geometry and camera visibility. Image interpretation is the **client worker's** responsibility: the MCP does not contain an image classifier or pretend pixel change proves extrusion. Clients must consume pending assessments and should never announce a first layer is down from a counter alone. Installing these backend tools alone does not add that worker loop to an older client.
673
+
674
+ A worker may also fetch the images/geometry and pass up to four calibrated height measurements to this read tool:
675
+
676
+ ```json
677
+ {"measurements":[
678
+ {"frameId":"saved frame UUID", "visible":true, "observedHeightMm":24, "uncertaintyMm":0.5, "method":"calibrated-height"},
679
+ {"frameId":"another saved frame UUID", "visible":true, "observedHeightMm":24, "uncertaintyMm":0.5, "method":"calibrated-height"}
680
+ ]}
681
+ ```
682
+
683
+ The MCP validates the saved frame identities/times and evaluates these **client-supplied** measurements; it runs no vision model. Two visible, sufficiently separated expected heights can support consistency, or an unchanged short observed height can support `suspect_no_growth`. Occluded, out-of-view, uncalibrated, uncertain, stale or contradictory evidence stays unknown. `consistent` concerns height in those frames only; it does not verify final shape, strength or print success. The assessment returns frame IDs and explicit limitations and is computed without altering the record. There is no automatic stop, pause, resume, model call or printer-setting change.
684
+
685
+ Sensor limits: Bambu Studio v02.08.02.61 declares [P1S lidar calibration unavailable](https://github.com/bambulab/BambuStudio/blob/v02.08.02.61/resources/printers/C12.json#L37), [X1 Carbon lidar calibration available](https://github.com/bambulab/BambuStudio/blob/v02.08.02.61/resources/printers/BL-P001.json#L42), and [H2D calibration/wrapping capabilities](https://github.com/bambulab/BambuStudio/blob/v02.08.02.61/resources/printers/O1D.json#L51). These are capability/configuration facts, not deposited-height measurements. Studio parses [xcam detection options and live support bits](https://github.com/bambulab/BambuStudio/blob/v02.08.02.61/src/slic3r/GUI/DeviceCore/DevPrintOptions.cpp#L37) and [AMS air-print capability with firmware exceptions](https://github.com/bambulab/BambuStudio/blob/v02.08.02.61/src/slic3r/GUI/DeviceManager.cpp#L1112). This feature records reported evidence; it never enables a detector or assumes a capability from a model name.
686
+
687
+ Validation is offline replay and mocked transports only. No real-printer physical-success claim is made.
688
+
646
689
  #### camera_stream_start, camera_frame, camera_stream_stop
647
690
 
648
691
  Development capability; discover these tools before using them with an installed server. Start one shared camera connection while a viewer is open, then request changed frames. The connection closes after 30 seconds without a viewer request. Snapshots reuse its latest frame. A1/P1 use the existing TLS protocol; X1/H2/P2S use one ffmpeg process for the stream lifetime.
@@ -984,6 +1027,8 @@ The npm package and desktop bundle include `native/bambu-native-print.cpp`, `scr
984
1027
 
985
1028
  For X2D, `print_3mf` defaults to `connection_mode: "bambu_native"`; legacy `lan_mqtt_ftps` requests are redirected to it. Supply `ams_slots`, a complete project-level `ams_mapping`, or `auto_match_ams: true`. A job that uses only one external spool requires explicit `use_ams: false`; a job mixing AMS trays with the external spools maps them as `254` (left/deputy nozzle) and `255` (right/main nozzle). Raw `ams_mapping2` and nozzle/extra-option overrides are rejected before dispatch; the server derives both AMS representations from the checked structured mapping. Model/nozzle/material inspection and fresh printer-state checks apply before the helper receives a private snapshot. The native helper requests fresh shared printer-state authorization immediately before each print submission, including a certificate retry, and before checked heating, resume, or error-clearing commands; custom helpers must support this handshake. Stop and heater-off remain available without preflight. Native upload-only requests use the same all-plate inspection as FTPS uploads. They accept `project_name`, `preset_name`, `bed_type`, and an existing `plate_index`; AMS, nozzle, and calibration print options are rejected. Use `print_3mf` for checked print settings.
986
1029
 
1030
+ X1C can opt in to the same route with `connection_mode: "bambu_native"` on `print_3mf` or `upload_file`; its default stays `lan_mqtt_ftps` and nothing is redirected. Use it when the printer refuses direct FTPS uploads: an X1C on firmware 01.12.00.00 (LAN Only and Developer Mode on, a ready writable SD card) answered every FTPS `STOR` with `553 Could not create file.` while Bambu Studio printed normally, and an X1C `print_3mf` or `upload_file` that fails with 553 now names this route. The same inspection, AMS mapping and fresh printer-state checks apply. Native X1C printing requires a freshly reported ready SD card or USB stick unless fresh status advertises internal-printing support (`fun2` bit 0, as Bambu Studio reads it). Explicit or environment eMMC requests without that capability are refused, and storage readiness/capability is rechecked before dispatch. That X1C completed a native print on macOS (AMS slot, SD card storage); Linux and other X1C firmware are untested, and X1E is not enabled. Native controls (`x2d_native_control`, native heating and error clearing) remain X2D-only: an X1C job is stopped, paused and resumed over direct MQTT, even when the request names `bambu_native`.
1031
+
987
1032
  The helper waits for connection/certificate exchange and retries only the initial `-4030` send once. Rebuild the helper after upgrading to receive the teardown fix. A successful dispatch receipt ends the helper before plug-in cleanup can turn an accepted job into an error. If an older/custom helper crashes after dispatch, the server reports uncertainty: check the printer state and job name before retrying, because resending can duplicate a print. Previous hardware testing reached `RUNNING` on X2D; this revision is validated with mocked transport regressions and clean installs, not a new physical print. `bambu_connect` is an optional macOS handoff for user review in Bambu Connect and does not start a print. Native task, heater, and error controls retain the common safety checks; raw controls cannot bypass them. Request cancellation, stop, and heater-off interrupt pending native helpers; the server waits for process exit before releasing a checked file. A command already sent to the printer cannot be recalled by cancelling the request, so verify printer state before retrying.
988
1033
 
989
1034
  #### X2D native transport (Linux)
@@ -1274,7 +1319,7 @@ Check only by default. `{"install":true}` installs a pinned isolated environment
1274
1319
 
1275
1320
  #### cad_run
1276
1321
 
1277
- Read the `cad_design` prompt first. Supply `script` or a saved `script_path`, `output_dir`, and `name`. Scripts declare literal `P = {...}` parameters and a `build()` function returning a build123d shape. One later call with `script_path` and `parameters` changes a dimension and rebuilds. Each run creates a new subfolder and preserves its source/parameter checkpoint, even on failure. The result contains STL/STEP paths, measured geometry, validity checks, six orthographic views, a perspective view and a contact sheet with the perspective view large beside the six.
1322
+ Read the `cad_design` prompt first. Supply `script` or a saved `script_path`, `output_dir`, and `name`. Scripts declare literal `P = {...}` parameters and a `build()` function returning a build123d shape. One later call with `script_path` and `parameters` changes a dimension and rebuilds. Each run creates a new subfolder and preserves its source/parameter checkpoint, even on failure. The result contains STL/STEP paths, measured geometry, validity checks, six orthographic views, a perspective view and a contact sheet with the perspective view large beside the six; `next` says to read the perspective view before the next change, and `printed` carries whatever the script wrote with `print()` (up to 4000 characters), so a design can report a number it computed.
1278
1323
 
1279
1324
  Explicit `inputs: [{"name": "scan", "path": "/allowed/scan.stl"}]` snapshots the files a script may read as `INPUTS["scan"]`. For a mesh-only edit, use `mode: "mesh"` and return `trimesh.Trimesh`: it exports and validates STL plus renders, with `step: null` and a clear reason. For captured meshes, the injected `load_scan` helper takes explicit source units and an up-axis, converts coordinates to millimetres/Z-up, and grounds the mesh without fitting its size. Cleanup choices and labels belong to the caller’s rules; the MCP supplies execution, mesh libraries, checks and renders.
1280
1325
 
@@ -1286,11 +1331,11 @@ Unchanged declared inputs reuse immutable content-hash bundles, with `snapshot_b
1286
1331
 
1287
1332
  #### cad_examples
1288
1333
 
1289
- The code engine's cookbook: twelve worked build123d designs from simple to complex (cable clip, wall hook, knurled knob, phone stand, swept headphone hook, lofted tool handle, threaded jar, bag clip, hinged box, bistable clicker, chainmail, trigger capo), each modelled on the best bought version of the thing, with its concept, the published sizes it used and its script. Without arguments it lists them with the pattern each shows; with `name` it returns one record and script. The `cad_design` prompt names every example in one line, so a design worker reads the one that works like its request and adapts the pattern. Read-only; needs no CAD runtime. The scripts are in `src/cad/examples/`.
1334
+ The code engine's cookbook: nineteen worked build123d designs from simple to complex (cable clip, wall hook, drawer divider, organiser tray, plant pot, knurled knob, phone stand, swept headphone hook, lofted tool handle, shelf bracket, broom grip, desk-edge cable holder, threaded jar, desk-clamp headphone hook, bag clip, hinged box, bistable clicker, chainmail, trigger capo), each modelled on the best bought version of the thing, with what it is for, its concept, the published sizes it used and its script. Without arguments it lists them by purpose (`use_for`) with the pattern each shows; with `name` it returns one record and script. The `cad_design` prompt names every example by its purpose in one line, so a design worker chooses the one made for the nearest request before it chooses a mechanism. Read-only; needs no CAD runtime. The scripts are in `src/cad/examples/`.
1290
1335
 
1291
1336
  #### cad_check_fit
1292
1337
 
1293
- Check a model and reference STL with an explicit rigid transform. Returns interference volume and minimum surface gap, without quietly scaling a scan. Open/nonmanifold meshes are refused. A gap of zero includes intentional floor contact, so choose clearance checks to match the interface you actually want to measure.
1338
+ Check a model and reference STL with an explicit rigid transform. Returns interference volume and minimum surface gap, without quietly scaling a scan. Open/nonmanifold meshes are refused. A gap of zero includes intentional floor contact, so choose clearance checks to match the interface you actually want to measure. Like `cad_run`, a check waits for the engine's execution slot up to its `timeout_ms` and returns `queue_wait_ms`, so several can be sent at once.
1294
1339
 
1295
1340
  See [CAD setup, confinement, script contract and removal](docs/CAD.md) for configuration, examples and limits.
1296
1341
 
@@ -131,7 +131,7 @@ function isRegularFile(file) {
131
131
  */
132
132
  function resolveNativeInstall() {
133
133
  if (!isBambuNativePlatform()) {
134
- throw new Error("Bambu native X2D transport requires macOS or x86-64 Linux and Bambu's networking plug-in.");
134
+ throw new Error("Bambu native transport requires macOS or x86-64 Linux and Bambu's networking plug-in.");
135
135
  }
136
136
  const helper = resolveNativeHelper();
137
137
  if (process.platform !== "linux")
@@ -103,7 +103,7 @@ export const CAD_TOOLS = [
103
103
  },
104
104
  {
105
105
  name: "cad_run",
106
- description: "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 orthographic renders, a perspective view and a contact sheet, the closest approach between every pair of solids (bodies), problems, and what was checked and not checked; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
106
+ description: "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 orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, and printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
107
107
  inputSchema: {
108
108
  type: "object",
109
109
  properties: {
@@ -204,6 +204,11 @@ export const CAD_TOOLS = [
204
204
  checked: { type: "array", items: { type: "string" } },
205
205
  not_checked: { type: "array", items: { type: "string" } },
206
206
  renders: { type: "object", additionalProperties: { type: "string" } },
207
+ next: { type: "string", description: "What to do before the next change: look at the perspective render." },
208
+ printed: {
209
+ type: "string",
210
+ description: "The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
211
+ },
207
212
  seconds: { type: "number" },
208
213
  }, [
209
214
  "valid",
@@ -227,7 +232,7 @@ export const CAD_TOOLS = [
227
232
  },
228
233
  {
229
234
  name: "cad_examples",
230
- description: "The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them (name, title, the pattern each shows, the product it is modelled on). With name, returns that example's record and full script to adapt. Read-only; starts no process.",
235
+ description: "The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them by purpose (name, title, use_for: the requests it suits, the pattern it shows, the product it is modelled on): choose by use_for before choosing a mechanism. With name, returns that example's record and full script to adapt. Read-only; starts no process.",
231
236
  inputSchema: {
232
237
  type: "object",
233
238
  properties: {
@@ -246,15 +251,17 @@ export const CAD_TOOLS = [
246
251
  properties: {
247
252
  name: { type: "string" },
248
253
  title: { type: "string" },
254
+ use_for: { type: "string" },
249
255
  pattern: { type: "string" },
250
256
  modelled_on: { type: "string" },
251
257
  },
252
- required: ["name", "title", "pattern"],
258
+ required: ["name", "title", "use_for", "pattern"],
253
259
  },
254
260
  },
255
261
  usage: { type: "string" },
256
262
  name: { type: "string" },
257
263
  title: { type: "string" },
264
+ use_for: { type: "string" },
258
265
  pattern: { type: "string" },
259
266
  modelled_on: { type: "string" },
260
267
  published_sizes: { type: "string" },
@@ -265,7 +272,7 @@ export const CAD_TOOLS = [
265
272
  },
266
273
  {
267
274
  name: "cad_check_fit",
268
- description: "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.",
275
+ description: "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. Like cad_run, a call waits for the environment's exclusive execution slot up to its timeout_ms and reports queue_wait_ms, so several checks may be sent at once. Fails rather than guessing for open meshes or excessive triangle workload.",
269
276
  inputSchema: {
270
277
  type: "object",
271
278
  properties: {
@@ -309,6 +316,7 @@ export const CAD_TOOLS = [
309
316
  },
310
317
  outputSchema: output({
311
318
  units: { type: "string", const: "mm" },
319
+ queue_wait_ms: { type: "integer" },
312
320
  interference_volume_mm3: { type: "number" },
313
321
  minimum_gap_mm: { type: "number" },
314
322
  clearance_mm: { type: "number" },
@@ -330,9 +338,10 @@ export const CAD_DESIGN_PROMPT = {
330
338
  title: "Parametric code-CAD design",
331
339
  description: "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
332
340
  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.
333
- Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept in a few lines: the bought product you are following, its mechanism, the load path, the print orientation and why. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
334
- Worked examples: cad_examples lists this engine's cookbook (each modelled on a bought product, with its concept, published sizes and script) and returns one script by name. When the request works like one of these, read that example first and adapt its pattern, never its sizes:
341
+ A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
342
+ The cookbook, by what each example is for:
335
343
  ${cadExampleLines()}
344
+ Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
336
345
  What the cookbook taught about this engine: return several bodies as Compound([a, b]); bodies that touch or overlap come back invalid, so leave a real gap (0.2 mm or more) or union them, and check that solid_count equals the bodies you intend (for a print-in-place mechanism that count is the first evidence nothing fused). fillet() often fails on the edges of an outline unioned from many curves, where chamfer() usually succeeds: fillet or chamfer simple bodies before the booleans that complicate them, and when a chamfer fails too, apply it to the plain body and union the details on afterwards. Do not round a sketch by growing and shrinking it with offset(): the solid looks right and its STEP comes back with no solids (the step_solids check fails). A whole Sphere() exports open at its poles: trim them (Sphere(r) & Box(2 * r, 2 * r, 2 * r - 0.1)). One fillet of the same radius over every edge of a box can export open: fillet in two passes with different radii. A model with moving parts takes a pose parameter: the assembled pose to judge it, the print plate to make it.
337
346
  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. When a design has separate bodies (print-in-place parts, a captive wheel, links of a fabric), return Compound(children=[...]) with a label on each body: cad_run then checks that each labelled body is exactly one solid, so a piece cut off one body cannot hide behind two bodies fused into one. Near pairs of solids are screened and, where the screen cannot clear them, measured exactly against P["print_in_place_clearance_mm"] when you declare it, else 0.3 mm. If the bodies are shown assembled rather than printed in place (a shaft in its hole at a fit clearance), set P["print_in_place"] = False: only touching or overlap is then a problem. Export in print orientation with the plate at Z = 0: a solid below it, or above it with nothing under it that reaches it, is a problem. 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 the same renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
338
347
  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.
@@ -341,7 +350,7 @@ Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y")
341
350
  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.
342
351
  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.
343
352
  Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
344
- The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. Judge the form from the perspective view first: would a person recognise the product and want it? Then 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.
353
+ The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. 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.
345
354
  Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
346
355
  Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
347
356
  };
@@ -1,4 +1,5 @@
1
1
  declare const FIELDS: {
2
+ readonly "Use for": "use_for";
2
3
  readonly Pattern: "pattern";
3
4
  readonly "Modelled on": "modelled_on";
4
5
  readonly "Published sizes used": "published_sizes";
@@ -15,7 +16,7 @@ export type CadExample = {
15
16
  export declare const CAD_EXAMPLE_ORDER: string[];
16
17
  /** Every example on disk, in cookbook order (unlisted files last, by name). Empty when the folder is missing. */
17
18
  export declare function cadExamples(): CadExample[];
18
- /** One line per example for the cad_design prompt: "name: what it is; the pattern it shows". */
19
+ /** One line per example for the cad_design prompt: "name: what it is for". */
19
20
  export declare function cadExampleLines(): string;
20
21
  /** cad_examples: without a name, the list; with one, that example's record and script. */
21
22
  export declare function cadExamplesTool(args: Record<string, unknown>): Record<string, unknown>;
@@ -4,14 +4,16 @@ import { fileURLToPath } from "node:url";
4
4
  /**
5
5
  * The code engine's cookbook: worked build123d designs, each modelled on the best bought version of the thing, kept as
6
6
  * plain scripts in src/cad/examples/. A design worker reaches them only through this MCP: the cad_design prompt names
7
- * each pattern in one line, and the read-only cad_examples tool returns one script on request, so the prompt pays a
8
- * line per example instead of a script per example.
7
+ * each one by what it is for in one line, and the read-only cad_examples tool lists them and returns one script on
8
+ * request, so the prompt pays a line per example instead of a script per example.
9
9
  *
10
- * A script's header (its docstring) is the record: title on the first line, then "Pattern:", "Modelled on:",
11
- * "Published sizes used:", "Concept:" and "What makes this good:".
10
+ * A script's header (its docstring) is the record: title on the first line, then "Use for:" (the requests it suits,
11
+ * so a worker chooses by purpose before mechanism), "Pattern:", "Modelled on:", "Published sizes used:", "Concept:"
12
+ * and "What makes this good:".
12
13
  */
13
14
  const DIR = fileURLToPath(new URL("../../src/cad/examples/", import.meta.url));
14
15
  const FIELDS = {
16
+ "Use for": "use_for",
15
17
  "Pattern": "pattern",
16
18
  "Modelled on": "modelled_on",
17
19
  "Published sizes used": "published_sizes",
@@ -20,8 +22,9 @@ const FIELDS = {
20
22
  };
21
23
  /** Simplest first: the order the list and the prompt present them in. */
22
24
  export const CAD_EXAMPLE_ORDER = [
23
- "cable_clip", "wall_hook", "knurled_knob", "phone_stand", "swept_hook", "loft_handle", "threaded_jar",
24
- "bag_clip", "hinged_box", "bistable_clicker", "chainmail", "trigger_capo",
25
+ "cable_clip", "wall_hook", "drawer_divider", "organizer_tray", "plant_pot", "knurled_knob", "phone_stand",
26
+ "swept_hook", "loft_handle", "shelf_bracket", "broom_grip", "desk_edge_cable_holder", "threaded_jar",
27
+ "desk_clamp_hook", "bag_clip", "hinged_box", "bistable_clicker", "chainmail", "trigger_capo",
25
28
  ];
26
29
  function parse(name, script) {
27
30
  const header = /^\s*"""([\s\S]*?)"""/.exec(script)?.[1] ?? "";
@@ -57,9 +60,9 @@ export function cadExamples() {
57
60
  .sort((a, b) => rank(a.name) - rank(b.name) || a.name.localeCompare(b.name));
58
61
  return cache;
59
62
  }
60
- /** One line per example for the cad_design prompt: "name: what it is; the pattern it shows". */
63
+ /** One line per example for the cad_design prompt: "name: what it is for". */
61
64
  export function cadExampleLines() {
62
- return cadExamples().map((e) => `${e.name}: ${e.title}; ${e.pattern}`).join("\n");
65
+ return cadExamples().map((e) => `${e.name}: ${e.use_for}`).join("\n");
63
66
  }
64
67
  /** cad_examples: without a name, the list; with one, that example's record and script. */
65
68
  export function cadExamplesTool(args) {
@@ -69,8 +72,8 @@ export function cadExamplesTool(args) {
69
72
  const all = cadExamples();
70
73
  if (args.name === undefined)
71
74
  return {
72
- examples: all.map(({ name, title, pattern, modelled_on }) => ({ name, title, pattern, modelled_on })),
73
- usage: "Call cad_examples with one name to read its concept and script. Adapt the pattern to the request and to the product the person means; do not paste an example's sizes onto a different object.",
75
+ examples: all.map(({ name, title, use_for, pattern, modelled_on }) => ({ name, title, use_for, pattern, modelled_on })),
76
+ usage: "Choose by use_for: the example made for the nearest request, before you choose a mechanism. Call cad_examples with that name to read its concept and script. Adapt the form and pattern to the request and to the product the person means; do not paste an example's sizes onto a different object.",
74
77
  };
75
78
  if (typeof args.name !== "string")
76
79
  throw new Error("name must be a string.");
@@ -1,4 +1,4 @@
1
- /** One dispatched operation per environment; runs queue across processes and never replay. */
1
+ /** One dispatched operation per environment; runs and fit checks queue across processes and never replay. */
2
2
  export declare function withCadLock<T>(data: string, options: {
3
3
  operation: "setup" | "run" | "fit";
4
4
  deadline?: number;
@@ -15,13 +15,13 @@ function dead(pid) {
15
15
  return e.code === "ESRCH";
16
16
  }
17
17
  }
18
- /** One dispatched operation per environment; runs queue across processes and never replay. */
18
+ /** One dispatched operation per environment; runs and fit checks queue across processes and never replay. */
19
19
  export async function withCadLock(data, options, work) {
20
20
  await fs.mkdir(data, { recursive: true, mode: 0o700 });
21
21
  const lock = path.join(data, "operation.lock"), queue = path.join(data, "queue");
22
22
  const start = performance.now();
23
23
  let ticket, temporary;
24
- const queued = options.operation === "run";
24
+ const queued = options.operation !== "setup";
25
25
  if (queued) {
26
26
  await fs.mkdir(queue, { recursive: true, mode: 0o700 });
27
27
  const name = `${String(Date.now()).padStart(13, "0")}-${process.hrtime.bigint().toString().padStart(20, "0")}-${randomUUID()}.json`;
@@ -37,7 +37,7 @@ export async function withCadLock(data, options, work) {
37
37
  for (;;) {
38
38
  options.signal?.throwIfAborted();
39
39
  if (queued && performance.now() >= options.deadline)
40
- throw new CadRefusal("cad-queue-timeout", "The CAD run's timeout expired while waiting for another operation. This run was not dispatched.");
40
+ throw new CadRefusal("cad-queue-timeout", `The CAD ${options.operation === "fit" ? "fit check" : "run"}'s timeout expired while waiting for another operation. It was not dispatched.`);
41
41
  const names = (await fs.readdir(queue).catch((e) => {
42
42
  if (e.code === "ENOENT")
43
43
  return [];
@@ -99,9 +99,7 @@ export async function withCadLock(data, options, work) {
99
99
  }
100
100
  }
101
101
  if (!queued)
102
- throw new CadRefusal(options.operation === "setup"
103
- ? "cad-setup-busy"
104
- : "cad-operation-busy", "Another CAD operation is already running or queued. Wait for it to finish; this request was not dispatched.");
102
+ throw new CadRefusal("cad-setup-busy", "Another CAD operation is already running or queued. Wait for it to finish; this request was not dispatched.");
105
103
  await delay(Math.min(50, Math.max(1, options.deadline - performance.now())), undefined, { signal: options.signal });
106
104
  }
107
105
  }
@@ -587,8 +587,13 @@ export class CadEngine {
587
587
  throw new Error(`CAD ${ext} export is missing, unsafe or too large.`);
588
588
  }
589
589
  const checked = JSON.parse((await this.confined("inspect", request, job, protectedFiles, remaining(), signal, readableInputs)).stdout);
590
+ const printed = built.stdout.trim();
590
591
  const result = {
591
592
  ...checked,
593
+ // Beside the image paths, where the next step is decided.
594
+ 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.",
595
+ // The script's own print() output: its words, not a measurement by this engine.
596
+ ...(printed ? { printed: printed.length > 4000 ? printed.slice(0, 4000) + "\n[cut at 4000 characters; build.log has the rest]" : printed } : {}),
592
597
  status: "completed",
593
598
  final: args.final === true,
594
599
  completed_at: new Date().toISOString(),
@@ -649,7 +654,7 @@ export class CadEngine {
649
654
  // One deadline for the whole call: the automatic re-check and the fit share timeout_ms.
650
655
  const deadline = performance.now() + milliseconds(args.timeout_ms);
651
656
  const before = await this.ensureReady(signal, deadline);
652
- return this.exclusive(async () => {
657
+ return this.exclusive(async (queueWaitMs) => {
653
658
  const status = await this.status();
654
659
  if (!status.ready)
655
660
  throw new CadRefusal("cad-not-ready", before.error ?? status.error);
@@ -664,21 +669,21 @@ export class CadEngine {
664
669
  transform: args.transform ?? {},
665
670
  clearance_mm: clearance,
666
671
  }));
667
- return JSON.parse((await this.confined("fit", request, job, [
668
- request,
669
- path.join(job, "model.stl"),
670
- path.join(job, "reference.stl"),
671
- ], (() => {
672
- const left = Math.floor(deadline - performance.now());
673
- if (left <= 0)
674
- throw new Error("CAD fit timed out.");
675
- return left;
676
- })(), signal)).stdout);
672
+ return { queue_wait_ms: queueWaitMs, ...JSON.parse((await this.confined("fit", request, job, [
673
+ request,
674
+ path.join(job, "model.stl"),
675
+ path.join(job, "reference.stl"),
676
+ ], (() => {
677
+ const left = Math.floor(deadline - performance.now());
678
+ if (left <= 0)
679
+ throw new Error("CAD fit timed out.");
680
+ return left;
681
+ })(), signal)).stdout) };
677
682
  }
678
683
  finally {
679
684
  await fs.rm(job, { recursive: true, force: true });
680
685
  }
681
- }, "fit", signal);
686
+ }, "fit", signal, deadline);
682
687
  }
683
688
  }
684
689
  function only(args, keys) {
@@ -0,0 +1,155 @@
1
+ import { type VisualSubmission, type VisualObservation } from "./visual-evidence.js";
2
+ import type { PrintGeometry } from "./print-geometry.js";
3
+ import { type EvidenceFrame, type HeightMeasurement } from "./physical-evidence.js";
4
+ export type { PrintGeometry, HeightMeasurement };
5
+ export declare const flightKey: (host: string, serial: string) => string;
6
+ /** An allowlist, not a recursive dump/redactor. Unknown fields and arbitrary strings never reach disk. */
7
+ export declare function flightSnapshot(raw: Record<string, any>): Record<string, unknown>;
8
+ export interface FlightDispatch {
9
+ sha256: string;
10
+ jobName: string;
11
+ mapping?: number[];
12
+ materials?: string[];
13
+ plate?: {
14
+ index: number;
15
+ sha256: string;
16
+ };
17
+ expected?: PrintGeometry;
18
+ }
19
+ interface StoredDispatch extends Omit<FlightDispatch, "jobName" | "expected"> {
20
+ jobHash: string;
21
+ outcome: "unconfirmed" | "accepted" | "observed-active";
22
+ acceptedAt?: string;
23
+ }
24
+ export interface FlightRecord {
25
+ version: 1;
26
+ seenActive: boolean;
27
+ owner?: {
28
+ pid: number;
29
+ token: string;
30
+ };
31
+ endedAt?: string;
32
+ execution?: Record<string, string>;
33
+ executionSuperseded?: boolean;
34
+ id: string;
35
+ printerKey: string;
36
+ dispatchedAt: string;
37
+ dispatch: StoredDispatch;
38
+ expected?: PrintGeometry;
39
+ reports: Array<{
40
+ seq: number;
41
+ at: string;
42
+ changes: Record<string, unknown>;
43
+ }>;
44
+ latest: Record<string, unknown>;
45
+ droppedReports: number;
46
+ nextSeq: number;
47
+ frames: EvidenceFrame[];
48
+ skippedCheckpoints: number[];
49
+ droppedFrames: number;
50
+ sampledCheckpoints?: number[];
51
+ visualObservations?: VisualObservation[];
52
+ omittedReports?: number;
53
+ omittedGeometryLayers?: number;
54
+ storage: "durable" | "volatile";
55
+ }
56
+ export interface ReadRecordOptions {
57
+ evidenceOnly?: boolean;
58
+ frameIds?: string[];
59
+ listJobs?: boolean;
60
+ jobId?: string;
61
+ includeFrames?: boolean;
62
+ measurements?: HeightMeasurement[];
63
+ }
64
+ export declare class FlightRecords {
65
+ private readonly dir;
66
+ private readonly now;
67
+ private readonly maxEvents;
68
+ private readonly maxJobs;
69
+ private readonly maxBytes;
70
+ private readonly maxCaptureMs;
71
+ private readonly cache;
72
+ private readonly pending;
73
+ private readonly recentReports;
74
+ private readonly superseded;
75
+ private warned;
76
+ private readonly ownerToken;
77
+ constructor(options?: {
78
+ dir?: string;
79
+ now?: () => number;
80
+ maxEvents?: number;
81
+ maxJobs?: number;
82
+ maxBytes?: number;
83
+ maxCaptureMs?: number;
84
+ });
85
+ begin(key: string, input: FlightDispatch): string;
86
+ accept(key: string, jobName: string): boolean;
87
+ observe(key: string, raw: Record<string, any>, at?: number): void;
88
+ /** Progress may expose saved evidence only for the job in this returned report. */
89
+ physicalForReport(key: string, raw: Record<string, any> | null | undefined): import("./physical-evidence.js").PhysicalEvidence;
90
+ read(key: string, options?: ReadRecordOptions): {
91
+ physical: import("./physical-evidence.js").PhysicalEvidence;
92
+ jobs?: {
93
+ id: string;
94
+ dispatchedAt: string;
95
+ sha256: string;
96
+ outcome: "accepted" | "unconfirmed" | "observed-active";
97
+ }[] | undefined;
98
+ contract: "counterpart/1";
99
+ status: "unavailable";
100
+ } | {
101
+ record: FlightRecord;
102
+ physical: import("./physical-evidence.js").PhysicalEvidence;
103
+ jobs?: {
104
+ id: string;
105
+ dispatchedAt: string;
106
+ sha256: string;
107
+ outcome: "accepted" | "unconfirmed" | "observed-active";
108
+ }[] | undefined;
109
+ contract: "counterpart/1";
110
+ status: "recorded";
111
+ };
112
+ /** Persist only the client's frame-bound visual observation, without printer I/O or journal ownership changes. */
113
+ submitVisual(key: string, input: VisualSubmission): {
114
+ physical: import("./physical-evidence.js").PhysicalEvidence;
115
+ jobs?: {
116
+ id: string;
117
+ dispatchedAt: string;
118
+ sha256: string;
119
+ outcome: "accepted" | "unconfirmed" | "observed-active";
120
+ }[] | undefined;
121
+ contract: "counterpart/1";
122
+ status: "unavailable";
123
+ } | {
124
+ record: FlightRecord;
125
+ physical: import("./physical-evidence.js").PhysicalEvidence;
126
+ jobs?: {
127
+ id: string;
128
+ dispatchedAt: string;
129
+ sha256: string;
130
+ outcome: "accepted" | "unconfirmed" | "observed-active";
131
+ }[] | undefined;
132
+ contract: "counterpart/1";
133
+ status: "recorded";
134
+ };
135
+ private visualFile;
136
+ private visuals;
137
+ private trimFrames;
138
+ /** Called only after existing reports/reads, never on a timer; a sample cannot block the print. */
139
+ sample(key: string, capture: (capturedAfter: string) => Promise<{
140
+ base64?: string;
141
+ capturedAt?: string;
142
+ }>): Promise<void>;
143
+ /** One process writes a dispatched job; fresh observations can take over after its process exits. */
144
+ private canWrite;
145
+ private jobSummaries;
146
+ private isSuperseded;
147
+ /** Monotonic one-byte sidecar: another observer cannot overwrite the live owner's journal. */
148
+ private invalidateExecution;
149
+ private file;
150
+ private frameFile;
151
+ private files;
152
+ private get;
153
+ private save;
154
+ private prune;
155
+ }