bambu-printer-mcp 1.1.82 → 1.1.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
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 = process.env) {
4
+ return !["0", "false", "off"].includes(env.CAD_ENABLED?.trim().toLowerCase() ?? "");
5
+ }
6
+ export const CAD_CAPABILITY = {
7
+ contract: "cad/1",
8
+ status: "cad_status",
9
+ setup: "cad_setup",
10
+ run: "cad_run",
11
+ checkFit: "cad_check_fit",
12
+ prompt: "cad_design",
13
+ };
14
+ const storage = {
15
+ type: "object",
16
+ properties: {
17
+ expected_download_bytes: { type: "integer" },
18
+ expected_installed_bytes: { type: "integer" },
19
+ installed_bytes: { type: ["integer", "null"] },
20
+ measurement: { type: "string", const: "allocated-last-setup" },
21
+ measured_at: { type: "string" },
22
+ },
23
+ required: [
24
+ "expected_download_bytes",
25
+ "expected_installed_bytes",
26
+ "installed_bytes",
27
+ "measurement",
28
+ ],
29
+ };
30
+ const status = {
31
+ storage,
32
+ configured: { type: "boolean" },
33
+ ready: { type: "boolean" },
34
+ python: { type: ["string", "null"] },
35
+ build123d: { type: "string" },
36
+ platform: { type: "string" },
37
+ error: { type: "string" },
38
+ };
39
+ const failure = {
40
+ type: "object",
41
+ properties: {
42
+ status: { type: "string", const: "error" },
43
+ code: { type: "string", enum: [...CAD_REFUSAL_CODES] },
44
+ message: { type: "string" },
45
+ tool: { type: "string" },
46
+ retryable: { type: "boolean" },
47
+ suggestion: { type: "string" },
48
+ storage,
49
+ },
50
+ required: ["status", "code", "message", "tool", "retryable", "suggestion"],
51
+ };
52
+ const output = (properties, required) => ({
53
+ type: "object",
54
+ anyOf: [{ type: "object", properties, required }, failure],
55
+ });
56
+ const timeout = {
57
+ type: "integer",
58
+ minimum: 100,
59
+ maximum: 900000,
60
+ description: "Total queue wait, preparation, execution and inspection deadline. Default 120000 ms; cancellation kills the dispatched process group.",
61
+ };
62
+ export const CAD_TOOLS = [
63
+ {
64
+ name: "cad_status",
65
+ description: "Read the optional code-CAD runtime's last verified readiness and pinned version, without starting Python or installing anything.",
66
+ inputSchema: {
67
+ type: "object",
68
+ properties: {},
69
+ additionalProperties: false,
70
+ },
71
+ outputSchema: output(status, [
72
+ "configured",
73
+ "ready",
74
+ "python",
75
+ "build123d",
76
+ "platform",
77
+ "storage",
78
+ ]),
79
+ },
80
+ {
81
+ name: "cad_setup",
82
+ description: "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.",
83
+ inputSchema: {
84
+ type: "object",
85
+ properties: {
86
+ install: {
87
+ type: "boolean",
88
+ default: false,
89
+ description: "Install and verify the pinned optional runtime; false only checks it.",
90
+ },
91
+ },
92
+ additionalProperties: false,
93
+ },
94
+ outputSchema: output({
95
+ ...status,
96
+ supported: { type: "boolean" },
97
+ installed: { type: "boolean" },
98
+ message: { type: "string" },
99
+ }, ["supported", "configured", "ready", "storage"]),
100
+ },
101
+ {
102
+ name: "cad_run",
103
+ 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 renders and a contact sheet; valid geometry is not a physical-fit or motion proof.",
104
+ inputSchema: {
105
+ type: "object",
106
+ properties: {
107
+ inputs: {
108
+ type: "array",
109
+ maxItems: 16,
110
+ items: {
111
+ type: "object",
112
+ properties: { name: { type: "string" }, path: { type: "string" } },
113
+ required: ["name", "path"],
114
+ additionalProperties: false,
115
+ },
116
+ description: "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.",
117
+ },
118
+ mode: {
119
+ type: "string",
120
+ enum: ["solid", "mesh"],
121
+ default: "solid",
122
+ description: "solid returns build123d B-rep with STL/STEP; mesh returns trimesh.Trimesh with STL and an explicit unavailable STEP.",
123
+ },
124
+ script: {
125
+ type: "string",
126
+ maxLength: 262144,
127
+ description: "Python source declaring literal named P parameters and build() returning a Shape.",
128
+ },
129
+ script_path: {
130
+ type: "string",
131
+ description: "Allowed saved .py checkpoint to rebuild or edit instead of resending script.",
132
+ },
133
+ parameters: {
134
+ type: "object",
135
+ additionalProperties: true,
136
+ description: "Overrides for names already declared in P; saved values are retained.",
137
+ },
138
+ output_dir: {
139
+ type: "string",
140
+ description: "Existing allowed directory; a unique immutable run subfolder is created beneath it.",
141
+ },
142
+ name: {
143
+ type: "string",
144
+ maxLength: 64,
145
+ description: "Plain file stem for STL, STEP, Python and parameter artifacts.",
146
+ },
147
+ final: {
148
+ type: "boolean",
149
+ default: false,
150
+ description: "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.",
151
+ },
152
+ timeout_ms: timeout,
153
+ },
154
+ required: ["output_dir", "name"],
155
+ additionalProperties: false,
156
+ },
157
+ outputSchema: output({
158
+ status: { type: "string", const: "completed" },
159
+ final: { type: "boolean" },
160
+ completed_at: { type: "string" },
161
+ lineage_id: { type: "string" },
162
+ result_manifest: { type: "string" },
163
+ queue_wait_ms: { type: "integer" },
164
+ snapshot_bytes_added: { type: "integer" },
165
+ snapshot_bytes_reused: { type: "integer" },
166
+ input_hashes: {
167
+ type: "object",
168
+ additionalProperties: { type: "string" },
169
+ },
170
+ valid: { type: "boolean" },
171
+ units: { const: "mm", type: "string" },
172
+ script: { type: "string" },
173
+ parameters: { type: "string" },
174
+ stl: { type: "string" },
175
+ step: { type: ["string", "null"] },
176
+ step_unavailable: { type: "string" },
177
+ inputs: { type: "object", additionalProperties: { type: "string" } },
178
+ input_manifest: { type: "string" },
179
+ bounds_mm: {
180
+ type: "array",
181
+ items: { type: "array", items: { type: "number" } },
182
+ },
183
+ size_mm: { type: "array", items: { type: "number" } },
184
+ volume_mm3: { type: ["number", "null"] },
185
+ step_volume_mm3: { type: ["number", "null"] },
186
+ solid_count: { type: "integer" },
187
+ mesh_components: { type: "integer" },
188
+ checks: {
189
+ type: "object",
190
+ additionalProperties: { type: ["boolean", "null"] },
191
+ },
192
+ renders: { type: "object", additionalProperties: { type: "string" } },
193
+ seconds: { type: "number" },
194
+ }, [
195
+ "valid",
196
+ "status",
197
+ "final",
198
+ "completed_at",
199
+ "lineage_id",
200
+ "result_manifest",
201
+ "queue_wait_ms",
202
+ "snapshot_bytes_added",
203
+ "snapshot_bytes_reused",
204
+ "script",
205
+ "parameters",
206
+ "stl",
207
+ "step",
208
+ "bounds_mm",
209
+ "solid_count",
210
+ "checks",
211
+ "renders",
212
+ ]),
213
+ },
214
+ {
215
+ name: "cad_check_fit",
216
+ 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.",
217
+ inputSchema: {
218
+ type: "object",
219
+ properties: {
220
+ model: {
221
+ type: "string",
222
+ description: "Allowed watertight manifold model STL in millimetres.",
223
+ },
224
+ reference: {
225
+ type: "string",
226
+ description: "Allowed reference/scan STL in millimetres; never rescaled implicitly.",
227
+ },
228
+ transform: {
229
+ type: "object",
230
+ description: "Rigid transform applied only to reference: XYZ rotation about origin, then translation.",
231
+ properties: {
232
+ translation_mm: {
233
+ type: "array",
234
+ items: { type: "number" },
235
+ minItems: 3,
236
+ maxItems: 3,
237
+ },
238
+ rotation_deg: {
239
+ type: "array",
240
+ items: { type: "number" },
241
+ minItems: 3,
242
+ maxItems: 3,
243
+ },
244
+ },
245
+ additionalProperties: false,
246
+ },
247
+ clearance_mm: {
248
+ type: "number",
249
+ minimum: 0,
250
+ maximum: 100,
251
+ description: "Required global minimum surface gap; intentional support contact has zero gap.",
252
+ },
253
+ timeout_ms: timeout,
254
+ },
255
+ required: ["model", "reference"],
256
+ additionalProperties: false,
257
+ },
258
+ outputSchema: output({
259
+ units: { type: "string", const: "mm" },
260
+ interference_volume_mm3: { type: "number" },
261
+ minimum_gap_mm: { type: "number" },
262
+ clearance_mm: { type: "number" },
263
+ clear: { type: "boolean" },
264
+ transform: { type: "object" },
265
+ method: { type: "string" },
266
+ reference_rescaled: { type: "boolean", const: false },
267
+ }, [
268
+ "interference_volume_mm3",
269
+ "minimum_gap_mm",
270
+ "clear",
271
+ "transform",
272
+ "reference_rescaled",
273
+ ]),
274
+ },
275
+ ];
276
+ export const CAD_DESIGN_PROMPT = {
277
+ name: "cad_design",
278
+ title: "Parametric code-CAD design",
279
+ description: "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
280
+ 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.
281
+ 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.
282
+ 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.
283
+ 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.
284
+ 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.
285
+ 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.
286
+ 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.
287
+ 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.`,
288
+ };
@@ -0,0 +1,32 @@
1
+ export interface CadProcessOptions {
2
+ env: NodeJS.ProcessEnv;
3
+ cwd?: string;
4
+ timeoutMs: number;
5
+ signal?: AbortSignal;
6
+ }
7
+ export interface CadSystem {
8
+ platform: NodeJS.Platform;
9
+ run(file: string, args: string[], options: CadProcessOptions): Promise<{
10
+ stdout: string;
11
+ stderr?: string;
12
+ }>;
13
+ }
14
+ /** No shell, no inherited printer/provider environment, bounded output, and kill the entire dispatched group. */
15
+ export declare function runCadProcess(file: string, args: string[], options: CadProcessOptions): Promise<{
16
+ stdout: string;
17
+ stderr: string;
18
+ }>;
19
+ export declare const defaultCadSystem: CadSystem;
20
+ export interface CadSandboxRoots {
21
+ data: string;
22
+ job: string;
23
+ assets: string;
24
+ python: string;
25
+ readonly: string[];
26
+ inputs?: string[];
27
+ }
28
+ /** Linux uses an empty mount tree and fresh user/PID/network namespaces. A missing/blocked bwrap is fatal. */
29
+ export declare function cadSandbox(platform: NodeJS.Platform, r: CadSandboxRoots): Promise<{
30
+ command: string;
31
+ args: string[];
32
+ }>;
@@ -0,0 +1,151 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ /** No shell, no inherited printer/provider environment, bounded output, and kill the entire dispatched group. */
5
+ export function runCadProcess(file, args, options) {
6
+ return new Promise((resolve, reject) => {
7
+ options.signal?.throwIfAborted();
8
+ const child = spawn(file, args, {
9
+ env: options.env,
10
+ cwd: options.cwd,
11
+ stdio: ["ignore", "pipe", "pipe"],
12
+ detached: process.platform !== "win32",
13
+ });
14
+ let stdout = "", stderr = "", failure;
15
+ const kill = () => {
16
+ try {
17
+ if (child.pid)
18
+ process.kill(process.platform === "win32" ? child.pid : -child.pid, "SIGKILL");
19
+ }
20
+ catch {
21
+ /* already exited */
22
+ }
23
+ };
24
+ const stop = (error) => {
25
+ failure ?? (failure = error);
26
+ kill();
27
+ };
28
+ const timer = setTimeout(() => stop(new Error(`CAD process timed out after ${options.timeoutMs} ms; execution was stopped, not replayed.`)), options.timeoutMs);
29
+ const abort = () => stop(new Error("CAD operation cancelled; execution was stopped, not replayed."));
30
+ options.signal?.addEventListener("abort", abort, { once: true });
31
+ child.stdout.on("data", (b) => {
32
+ stdout += b.toString();
33
+ if (Buffer.byteLength(stdout) > 2 * 1024 * 1024)
34
+ stop(new Error("CAD process exceeded its output limit."));
35
+ });
36
+ child.stderr.on("data", (b) => {
37
+ stderr += b.toString();
38
+ if (Buffer.byteLength(stderr) > 2 * 1024 * 1024)
39
+ stop(new Error("CAD diagnostics exceeded their output limit."));
40
+ });
41
+ child.once("error", (e) => {
42
+ failure = e;
43
+ });
44
+ child.once("close", (code) => {
45
+ clearTimeout(timer);
46
+ options.signal?.removeEventListener("abort", abort);
47
+ kill();
48
+ if (failure)
49
+ reject(failure);
50
+ else if (code !== 0)
51
+ reject(new Error(`CAD process failed (${code}): ${(stderr || stdout).slice(-6000)}`));
52
+ else
53
+ resolve({ stdout, stderr });
54
+ });
55
+ });
56
+ }
57
+ export const defaultCadSystem = {
58
+ platform: process.platform,
59
+ run: runCadProcess,
60
+ };
61
+ const sb = (s) => JSON.stringify(s);
62
+ /** Linux uses an empty mount tree and fresh user/PID/network namespaces. A missing/blocked bwrap is fatal. */
63
+ export async function cadSandbox(platform, r) {
64
+ if (platform === "darwin") {
65
+ // Runtime system files remain readable, but personal data, IPC, network and process spawning do not.
66
+ const variants = (p) => [
67
+ p,
68
+ ...(/^\/(?:Users|private|Volumes)(?:\/|$)/.test(p)
69
+ ? ["/System/Volumes/Data" + p]
70
+ : []),
71
+ ];
72
+ const systemReads = [
73
+ "/System/Library",
74
+ "/System/Cryptexes",
75
+ "/System/Volumes/Preboot",
76
+ "/private/preboot",
77
+ "/Library/Fonts",
78
+ "/usr/lib",
79
+ "/usr/share",
80
+ "/usr/bin",
81
+ "/bin",
82
+ "/sbin",
83
+ "/dev",
84
+ "/private/etc/localtime",
85
+ "/etc/localtime",
86
+ ];
87
+ const readable = [
88
+ ...systemReads,
89
+ path.join(r.data, "runtime"),
90
+ path.join(r.data, "python"),
91
+ r.assets,
92
+ r.job,
93
+ ...(r.inputs ?? []),
94
+ ].flatMap(variants);
95
+ const profile = `(version 1)(allow default)
96
+ (deny process-info*)(allow process-info* (target self))
97
+ (deny sysctl-read)
98
+ (allow sysctl-read (sysctl-name-prefix "hw.") (sysctl-name-prefix "machdep.cpu.")
99
+ (sysctl-name-prefix "kern.os") (sysctl-name "kern.ostype") (sysctl-name "kern.hostname") (sysctl-name "kern.domainname")
100
+ (sysctl-name "kern.version") (sysctl-name "kern.maxfiles") (sysctl-name "kern.maxfilesperproc"))
101
+ (deny file-link)(deny network*)(deny appleevent-send)(deny mach-lookup)(deny signal)(deny process-fork)
102
+ (deny process-exec)(allow process-exec (literal ${sb(await fs.realpath(r.python).catch(() => r.python))}))
103
+ (deny file-read*)
104
+ (allow file-read-metadata)(deny file-write*)
105
+ (allow file-read* (literal "/") (literal "/System") (literal "/System/Volumes") (literal "/System/Volumes/Data") (literal "/private"))
106
+ (allow file-read* ${readable.map((p) => `(subpath ${sb(p)})`).join(" ")})
107
+ (allow file-write* ${variants(r.job)
108
+ .map((p) => `(subpath ${sb(p)})`)
109
+ .join(" ")} (literal "/dev/null"))
110
+ ${r.readonly
111
+ .flatMap(variants)
112
+ .map((p) => `(deny file-write* (subpath ${sb(p)}))`)
113
+ .join("\n")}`;
114
+ return { command: "/usr/bin/sandbox-exec", args: ["-p", profile] };
115
+ }
116
+ if (platform === "linux") {
117
+ const args = [
118
+ "--unshare-all",
119
+ "--die-with-parent",
120
+ "--new-session",
121
+ "--cap-drop",
122
+ "ALL",
123
+ "--proc",
124
+ "/proc",
125
+ "--dev",
126
+ "/dev",
127
+ "--tmpfs",
128
+ "/tmp",
129
+ ];
130
+ for (const dir of ["/usr", "/bin", "/lib", "/lib64", "/sbin"])
131
+ if (await fs.stat(dir).then(() => true, () => false))
132
+ args.push("--ro-bind", dir, dir);
133
+ for (const file of ["/etc/ld.so.cache", "/etc/localtime", "/etc/fonts"]) {
134
+ if (await fs.stat(file).then(() => true, () => false))
135
+ args.push("--ro-bind", file, file);
136
+ }
137
+ for (const dir of [
138
+ path.join(r.data, "runtime"),
139
+ path.join(r.data, "python"),
140
+ r.assets,
141
+ ...(r.inputs ?? []),
142
+ ])
143
+ args.push("--ro-bind", dir, dir);
144
+ args.push("--bind", r.job, r.job);
145
+ for (const file of r.readonly.filter((file) => !(r.inputs ?? []).includes(file)))
146
+ args.push("--ro-bind", file, file);
147
+ args.push("--chdir", r.job);
148
+ return { command: "bwrap", args };
149
+ }
150
+ throw new Error(`CAD confinement is unavailable on ${platform}; no unconfined execution is permitted.`);
151
+ }
@@ -0,0 +1,15 @@
1
+ /** Stable CAD refusals use the same structuredContent shape as printer refusals. */
2
+ export declare const CAD_REFUSAL_CODES: readonly ["cad-uv-missing", "cad-data-volume-refused", "cad-setup-busy", "cad-operation-busy", "cad-queue-timeout", "cad-not-ready", "cad-confinement-unavailable", "cad-disabled", "cad-failed"];
3
+ export type CadRefusalCode = (typeof CAD_REFUSAL_CODES)[number];
4
+ export declare class CadRefusal extends Error {
5
+ readonly code: CadRefusalCode;
6
+ constructor(code: CadRefusalCode, message: string);
7
+ }
8
+ export declare function cadFailure(error: unknown, tool: string): {
9
+ status: "error";
10
+ code: "cad-uv-missing" | "cad-data-volume-refused" | "cad-setup-busy" | "cad-operation-busy" | "cad-queue-timeout" | "cad-not-ready" | "cad-confinement-unavailable" | "cad-disabled" | "cad-failed";
11
+ message: string;
12
+ tool: string;
13
+ retryable: boolean;
14
+ suggestion: string;
15
+ };
@@ -0,0 +1,30 @@
1
+ /** Stable CAD refusals use the same structuredContent shape as printer refusals. */
2
+ export const CAD_REFUSAL_CODES = [
3
+ "cad-uv-missing",
4
+ "cad-data-volume-refused",
5
+ "cad-setup-busy",
6
+ "cad-operation-busy",
7
+ "cad-queue-timeout",
8
+ "cad-not-ready",
9
+ "cad-confinement-unavailable",
10
+ "cad-disabled",
11
+ "cad-failed",
12
+ ];
13
+ export class CadRefusal extends Error {
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = "CadRefusal";
18
+ }
19
+ }
20
+ export function cadFailure(error, tool) {
21
+ const message = error instanceof Error ? error.message : String(error);
22
+ return {
23
+ status: "error",
24
+ code: error instanceof CadRefusal ? error.code : "cad-failed",
25
+ message,
26
+ tool,
27
+ retryable: false,
28
+ suggestion: "Resolve the reported CAD condition before making another request. Interrupted work is never replayed automatically.",
29
+ };
30
+ }
@@ -0,0 +1,6 @@
1
+ /** One dispatched operation per environment; runs queue across processes and never replay. */
2
+ export declare function withCadLock<T>(data: string, options: {
3
+ operation: "setup" | "run" | "fit";
4
+ deadline?: number;
5
+ signal?: AbortSignal;
6
+ }, work: (waitedMs: number) => Promise<T>): Promise<T>;
@@ -0,0 +1,114 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { performance } from "node:perf_hooks";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { CadRefusal } from "./refusal.js";
7
+ function dead(pid) {
8
+ if (!Number.isInteger(pid) || Number(pid) < 1)
9
+ return false;
10
+ try {
11
+ process.kill(Number(pid), 0);
12
+ return false;
13
+ }
14
+ catch (e) {
15
+ return e.code === "ESRCH";
16
+ }
17
+ }
18
+ /** One dispatched operation per environment; runs queue across processes and never replay. */
19
+ export async function withCadLock(data, options, work) {
20
+ await fs.mkdir(data, { recursive: true, mode: 0o700 });
21
+ const lock = path.join(data, "operation.lock"), queue = path.join(data, "queue");
22
+ const start = performance.now();
23
+ let ticket, temporary;
24
+ const queued = options.operation === "run";
25
+ if (queued) {
26
+ await fs.mkdir(queue, { recursive: true, mode: 0o700 });
27
+ const name = `${String(Date.now()).padStart(13, "0")}-${process.hrtime.bigint().toString().padStart(20, "0")}-${randomUUID()}.json`;
28
+ ticket = path.join(queue, name);
29
+ temporary = path.join(queue, `.new-${randomUUID()}`);
30
+ await fs.writeFile(temporary, JSON.stringify({ pid: process.pid }), {
31
+ flag: "wx",
32
+ mode: 0o600,
33
+ });
34
+ await fs.rename(temporary, ticket);
35
+ }
36
+ try {
37
+ for (;;) {
38
+ options.signal?.throwIfAborted();
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.");
41
+ const names = (await fs.readdir(queue).catch((e) => {
42
+ if (e.code === "ENOENT")
43
+ return [];
44
+ throw e;
45
+ }))
46
+ .filter((n) => /^\d+-\d+-[a-f0-9-]+\.json$/.test(n))
47
+ .sort();
48
+ const live = [];
49
+ for (const name of names) {
50
+ const file = path.join(queue, name);
51
+ try {
52
+ const previous = JSON.parse(await fs.readFile(file, "utf8"));
53
+ if (dead(previous.pid)) {
54
+ await fs.unlink(file).catch(() => { });
55
+ continue;
56
+ }
57
+ }
58
+ catch (e) {
59
+ if (e.code === "ENOENT")
60
+ continue;
61
+ }
62
+ live.push(name);
63
+ }
64
+ const turn = queued
65
+ ? live[0] === path.basename(ticket)
66
+ : live.length === 0;
67
+ let handle;
68
+ if (turn) {
69
+ try {
70
+ handle = await fs.open(lock, "wx", 0o600);
71
+ }
72
+ catch (e) {
73
+ if (e.code !== "EEXIST")
74
+ throw e;
75
+ try {
76
+ const previous = JSON.parse(await fs.readFile(lock, "utf8"));
77
+ if (dead(previous.pid)) {
78
+ await fs.unlink(lock).catch(() => { });
79
+ continue;
80
+ }
81
+ }
82
+ catch {
83
+ /* A partially written live lock stays locked. */
84
+ }
85
+ }
86
+ }
87
+ if (handle) {
88
+ try {
89
+ await handle.writeFile(JSON.stringify({ pid: process.pid, operation: options.operation }));
90
+ if (ticket) {
91
+ await fs.unlink(ticket);
92
+ ticket = undefined;
93
+ }
94
+ return await work(Math.round(performance.now() - start));
95
+ }
96
+ finally {
97
+ await handle.close();
98
+ await fs.unlink(lock).catch(() => { });
99
+ }
100
+ }
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.");
105
+ await delay(Math.min(50, Math.max(1, options.deadline - performance.now())), undefined, { signal: options.signal });
106
+ }
107
+ }
108
+ finally {
109
+ if (ticket)
110
+ await fs.unlink(ticket).catch(() => { });
111
+ if (temporary)
112
+ await fs.unlink(temporary).catch(() => { });
113
+ }
114
+ }