bambu-printer-mcp 1.1.82 → 1.1.84

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 (45) hide show
  1. package/README.md +41 -0
  2. package/dist/cad/contracts.d.ts +424 -0
  3. package/dist/cad/contracts.js +288 -0
  4. package/dist/cad/process.d.ts +32 -0
  5. package/dist/cad/process.js +151 -0
  6. package/dist/cad/refusal.d.ts +15 -0
  7. package/dist/cad/refusal.js +30 -0
  8. package/dist/cad/serial.d.ts +6 -0
  9. package/dist/cad/serial.js +114 -0
  10. package/dist/cad/storage.d.ts +34 -0
  11. package/dist/cad/storage.js +201 -0
  12. package/dist/cad-engine.d.ts +43 -0
  13. package/dist/cad-engine.js +546 -0
  14. package/dist/counterpart/info.js +2 -0
  15. package/dist/counterpart/remote.js +7 -0
  16. package/dist/counterpart/schemas.d.ts +33 -0
  17. package/dist/counterpart/schemas.js +1 -0
  18. package/dist/design-guidance.js +2 -6
  19. package/dist/index.js +44 -3
  20. package/dist/refusal.d.ts +11 -4
  21. package/dist/refusal.js +14 -4
  22. package/dist/slicer/slicer-launch.d.ts +34 -0
  23. package/dist/slicer/slicer-launch.js +145 -0
  24. package/dist/stl/stl-manipulator.js +55 -33
  25. package/dist/tool-annotations.js +4 -0
  26. package/package.json +1 -1
  27. package/src/cad/contracts.ts +317 -0
  28. package/src/cad/geometry.py +157 -0
  29. package/src/cad/process.ts +216 -0
  30. package/src/cad/refusal.ts +34 -0
  31. package/src/cad/requirements.in +9 -0
  32. package/src/cad/requirements.lock +69 -0
  33. package/src/cad/serial.ts +126 -0
  34. package/src/cad/storage.ts +232 -0
  35. package/src/cad/worker.py +161 -0
  36. package/src/cad-engine.ts +794 -0
  37. package/src/counterpart/info.ts +2 -0
  38. package/src/counterpart/remote.ts +6 -0
  39. package/src/counterpart/schemas.ts +2 -0
  40. package/src/design-guidance.ts +2 -0
  41. package/src/index.ts +39 -3
  42. package/src/refusal.ts +15 -4
  43. package/src/slicer/slicer-launch.ts +149 -0
  44. package/src/stl/stl-manipulator.ts +17 -4
  45. package/src/tool-annotations.ts +4 -0
@@ -0,0 +1,216 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export interface CadProcessOptions {
6
+ env: NodeJS.ProcessEnv;
7
+ cwd?: string;
8
+ timeoutMs: number;
9
+ signal?: AbortSignal;
10
+ }
11
+ export interface CadSystem {
12
+ platform: NodeJS.Platform;
13
+ run(
14
+ file: string,
15
+ args: string[],
16
+ options: CadProcessOptions,
17
+ ): Promise<{ stdout: string; stderr?: string }>;
18
+ }
19
+
20
+ /** No shell, no inherited printer/provider environment, bounded output, and kill the entire dispatched group. */
21
+ export function runCadProcess(
22
+ file: string,
23
+ args: string[],
24
+ options: CadProcessOptions,
25
+ ): Promise<{ stdout: string; stderr: string }> {
26
+ return new Promise((resolve, reject) => {
27
+ options.signal?.throwIfAborted();
28
+ const child = spawn(file, args, {
29
+ env: options.env,
30
+ cwd: options.cwd,
31
+ stdio: ["ignore", "pipe", "pipe"],
32
+ detached: process.platform !== "win32",
33
+ });
34
+ let stdout = "",
35
+ stderr = "",
36
+ failure: Error | undefined;
37
+ const kill = () => {
38
+ try {
39
+ if (child.pid)
40
+ process.kill(
41
+ process.platform === "win32" ? child.pid : -child.pid,
42
+ "SIGKILL",
43
+ );
44
+ } catch {
45
+ /* already exited */
46
+ }
47
+ };
48
+ const stop = (error: Error) => {
49
+ failure ??= error;
50
+ kill();
51
+ };
52
+ const timer = setTimeout(
53
+ () =>
54
+ stop(
55
+ new Error(
56
+ `CAD process timed out after ${options.timeoutMs} ms; execution was stopped, not replayed.`,
57
+ ),
58
+ ),
59
+ options.timeoutMs,
60
+ );
61
+ const abort = () =>
62
+ stop(
63
+ new Error(
64
+ "CAD operation cancelled; execution was stopped, not replayed.",
65
+ ),
66
+ );
67
+ options.signal?.addEventListener("abort", abort, { once: true });
68
+ child.stdout.on("data", (b) => {
69
+ stdout += b.toString();
70
+ if (Buffer.byteLength(stdout) > 2 * 1024 * 1024)
71
+ stop(new Error("CAD process exceeded its output limit."));
72
+ });
73
+ child.stderr.on("data", (b) => {
74
+ stderr += b.toString();
75
+ if (Buffer.byteLength(stderr) > 2 * 1024 * 1024)
76
+ stop(new Error("CAD diagnostics exceeded their output limit."));
77
+ });
78
+ child.once("error", (e) => {
79
+ failure = e;
80
+ });
81
+ child.once("close", (code) => {
82
+ clearTimeout(timer);
83
+ options.signal?.removeEventListener("abort", abort);
84
+ kill();
85
+ if (failure) reject(failure);
86
+ else if (code !== 0)
87
+ reject(
88
+ new Error(
89
+ `CAD process failed (${code}): ${(stderr || stdout).slice(-6000)}`,
90
+ ),
91
+ );
92
+ else resolve({ stdout, stderr });
93
+ });
94
+ });
95
+ }
96
+ export const defaultCadSystem: CadSystem = {
97
+ platform: process.platform,
98
+ run: runCadProcess,
99
+ };
100
+ export interface CadSandboxRoots {
101
+ data: string;
102
+ job: string;
103
+ assets: string;
104
+ python: string;
105
+ readonly: string[];
106
+ inputs?: string[];
107
+ }
108
+ const sb = (s: string) => JSON.stringify(s);
109
+
110
+ /** Linux uses an empty mount tree and fresh user/PID/network namespaces. A missing/blocked bwrap is fatal. */
111
+ export async function cadSandbox(
112
+ platform: NodeJS.Platform,
113
+ r: CadSandboxRoots,
114
+ ): Promise<{ command: string; args: string[] }> {
115
+ if (platform === "darwin") {
116
+ // Runtime system files remain readable, but personal data, IPC, network and process spawning do not.
117
+ const variants = (p: string) => [
118
+ p,
119
+ ...(/^\/(?:Users|private|Volumes)(?:\/|$)/.test(p)
120
+ ? ["/System/Volumes/Data" + p]
121
+ : []),
122
+ ];
123
+ const systemReads = [
124
+ "/System/Library",
125
+ "/System/Cryptexes",
126
+ "/System/Volumes/Preboot",
127
+ "/private/preboot",
128
+ "/Library/Fonts",
129
+ "/usr/lib",
130
+ "/usr/share",
131
+ "/usr/bin",
132
+ "/bin",
133
+ "/sbin",
134
+ "/dev",
135
+ "/private/etc/localtime",
136
+ "/etc/localtime",
137
+ ];
138
+ const readable = [
139
+ ...systemReads,
140
+ path.join(r.data, "runtime"),
141
+ path.join(r.data, "python"),
142
+ r.assets,
143
+ r.job,
144
+ ...(r.inputs ?? []),
145
+ ].flatMap(variants);
146
+ const profile = `(version 1)(allow default)
147
+ (deny process-info*)(allow process-info* (target self))
148
+ (deny sysctl-read)
149
+ (allow sysctl-read (sysctl-name-prefix "hw.") (sysctl-name-prefix "machdep.cpu.")
150
+ (sysctl-name-prefix "kern.os") (sysctl-name "kern.ostype") (sysctl-name "kern.hostname") (sysctl-name "kern.domainname")
151
+ (sysctl-name "kern.version") (sysctl-name "kern.maxfiles") (sysctl-name "kern.maxfilesperproc"))
152
+ (deny file-link)(deny network*)(deny appleevent-send)(deny mach-lookup)(deny signal)(deny process-fork)
153
+ (deny process-exec)(allow process-exec (literal ${sb(await fs.realpath(r.python).catch(() => r.python))}))
154
+ (deny file-read*)
155
+ (allow file-read-metadata)(deny file-write*)
156
+ (allow file-read* (literal "/") (literal "/System") (literal "/System/Volumes") (literal "/System/Volumes/Data") (literal "/private"))
157
+ (allow file-read* ${readable.map((p) => `(subpath ${sb(p)})`).join(" ")})
158
+ (allow file-write* ${variants(r.job)
159
+ .map((p) => `(subpath ${sb(p)})`)
160
+ .join(" ")} (literal "/dev/null"))
161
+ ${r.readonly
162
+ .flatMap(variants)
163
+ .map((p) => `(deny file-write* (subpath ${sb(p)}))`)
164
+ .join("\n")}`;
165
+ return { command: "/usr/bin/sandbox-exec", args: ["-p", profile] };
166
+ }
167
+ if (platform === "linux") {
168
+ const args = [
169
+ "--unshare-all",
170
+ "--die-with-parent",
171
+ "--new-session",
172
+ "--cap-drop",
173
+ "ALL",
174
+ "--proc",
175
+ "/proc",
176
+ "--dev",
177
+ "/dev",
178
+ "--tmpfs",
179
+ "/tmp",
180
+ ];
181
+ for (const dir of ["/usr", "/bin", "/lib", "/lib64", "/sbin"])
182
+ if (
183
+ await fs.stat(dir).then(
184
+ () => true,
185
+ () => false,
186
+ )
187
+ )
188
+ args.push("--ro-bind", dir, dir);
189
+ for (const file of ["/etc/ld.so.cache", "/etc/localtime", "/etc/fonts"]) {
190
+ if (
191
+ await fs.stat(file).then(
192
+ () => true,
193
+ () => false,
194
+ )
195
+ )
196
+ args.push("--ro-bind", file, file);
197
+ }
198
+ for (const dir of [
199
+ path.join(r.data, "runtime"),
200
+ path.join(r.data, "python"),
201
+ r.assets,
202
+ ...(r.inputs ?? []),
203
+ ])
204
+ args.push("--ro-bind", dir, dir);
205
+ args.push("--bind", r.job, r.job);
206
+ for (const file of r.readonly.filter(
207
+ (file) => !(r.inputs ?? []).includes(file),
208
+ ))
209
+ args.push("--ro-bind", file, file);
210
+ args.push("--chdir", r.job);
211
+ return { command: "bwrap", args };
212
+ }
213
+ throw new Error(
214
+ `CAD confinement is unavailable on ${platform}; no unconfined execution is permitted.`,
215
+ );
216
+ }
@@ -0,0 +1,34 @@
1
+ /** Stable CAD refusals use the same structuredContent shape as printer refusals. */
2
+ export const CAD_REFUSAL_CODES = [
3
+ "cad-uv-missing",
4
+ "cad-data-volume-refused",
5
+ "cad-setup-busy",
6
+ "cad-operation-busy",
7
+ "cad-queue-timeout",
8
+ "cad-not-ready",
9
+ "cad-confinement-unavailable",
10
+ "cad-disabled",
11
+ "cad-failed",
12
+ ] as const;
13
+ export type CadRefusalCode = (typeof CAD_REFUSAL_CODES)[number];
14
+ export class CadRefusal extends Error {
15
+ constructor(
16
+ readonly code: CadRefusalCode,
17
+ message: string,
18
+ ) {
19
+ super(message);
20
+ this.name = "CadRefusal";
21
+ }
22
+ }
23
+ export function cadFailure(error: unknown, tool: string) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ return {
26
+ status: "error" as const,
27
+ code: error instanceof CadRefusal ? error.code : "cad-failed",
28
+ message,
29
+ tool,
30
+ retryable: false,
31
+ suggestion:
32
+ "Resolve the reported CAD condition before making another request. Interrupted work is never replayed automatically.",
33
+ };
34
+ }
@@ -0,0 +1,9 @@
1
+ build123d==0.13.0
2
+ numpy==2.5.4
3
+ scipy==1.18.1
4
+ trimesh==5.2.0
5
+ manifold3d==3.5.4
6
+ scikit-image==0.26.0
7
+ pillow==13.0.0
8
+ shapely==2.1.2
9
+ rtree==1.4.1
@@ -0,0 +1,69 @@
1
+ anytree==2.13.0
2
+ asttokens==3.0.2
3
+ bd-materials==0.2.5
4
+ build123d==0.13.0
5
+ cadquery-ocp-novtk==8.0.1.1.0
6
+ cadquery-ocp-proxy==8.0.1.1.0
7
+ certifi==2026.10.23
8
+ charset-normalizer==3.5.2
9
+ cloudpickle==3.1.2
10
+ colorama==0.4.6 ; sys_platform == 'win32'
11
+ dataclasses-json==0.6.7
12
+ deprecated==3.0.1
13
+ executing==2.3.0
14
+ ezdxf==1.4.5
15
+ fonttools==4.68.0
16
+ idna==3.20
17
+ imageio==2.38.1
18
+ ipython==9.18.1
19
+ ipython-pygments-lexers==1.1.1
20
+ jedi==0.20.1
21
+ joblib==1.6.0
22
+ lazy-loader==0.6
23
+ lib3mf==2.5.0 ; platform_machine != 'aarch64' or sys_platform != 'linux'
24
+ manifold3d==3.5.4
25
+ marshmallow==3.26.2
26
+ matplotlib-inline==0.2.2
27
+ mpmath==1.3.0
28
+ mypy-extensions==1.2.0
29
+ narwhals==2.28.0
30
+ networkx==3.7
31
+ numpy==2.5.4
32
+ ocp-gordon==0.3.1
33
+ ocpsvg==0.7.0
34
+ packaging==26.3
35
+ parso==0.8.7
36
+ pexpect==4.9.0 ; sys_platform != 'emscripten' and sys_platform != 'win32'
37
+ pillow==13.0.0
38
+ platformdirs==4.14.5
39
+ prompt-toolkit==3.0.53
40
+ psutil==7.2.2 ; sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'emscripten'
41
+ ptyprocess==0.7.0 ; sys_platform != 'emscripten' and sys_platform != 'win32'
42
+ pure-eval==0.2.4
43
+ py-lib3mf==2.5.0 ; platform_machine == 'aarch64' and sys_platform == 'linux'
44
+ pygltflib==1.16.5
45
+ pygments==2.21.0
46
+ pyparsing==3.3.3
47
+ requests==2.34.2
48
+ rtree==1.4.1
49
+ scikit-image==0.26.0
50
+ scikit-learn==1.9.1
51
+ scipy==1.18.1
52
+ shapely==2.1.2
53
+ stack-data==0.6.3
54
+ svgelements==1.9.6
55
+ svgpathtools==1.8.0
56
+ svgwrite==1.4.3
57
+ sympy==1.14.0
58
+ threadpoolctl==3.8.0
59
+ threejs-materials==1.2.5
60
+ tifffile==2026.11.8
61
+ traitlets==5.16.1
62
+ trianglesolver==1.2
63
+ trimesh==5.2.0
64
+ typing-extensions==4.16.0
65
+ typing-inspect==0.9.0
66
+ urllib3==2.8.0
67
+ wcwidth==0.9.4
68
+ webcolors==24.8.0
69
+ wrapt==2.5.2
@@ -0,0 +1,126 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { performance } from "node:perf_hooks";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { CadRefusal } from "./refusal.js";
7
+
8
+ function dead(pid: unknown): boolean {
9
+ if (!Number.isInteger(pid) || Number(pid) < 1) return false;
10
+ try {
11
+ process.kill(Number(pid), 0);
12
+ return false;
13
+ } catch (e) {
14
+ return (e as NodeJS.ErrnoException).code === "ESRCH";
15
+ }
16
+ }
17
+ /** One dispatched operation per environment; runs queue across processes and never replay. */
18
+ export async function withCadLock<T>(
19
+ data: string,
20
+ options: {
21
+ operation: "setup" | "run" | "fit";
22
+ deadline?: number;
23
+ signal?: AbortSignal;
24
+ },
25
+ work: (waitedMs: number) => Promise<T>,
26
+ ): Promise<T> {
27
+ await fs.mkdir(data, { recursive: true, mode: 0o700 });
28
+ const lock = path.join(data, "operation.lock"),
29
+ queue = path.join(data, "queue");
30
+ const start = performance.now();
31
+ let ticket: string | undefined, temporary: string | undefined;
32
+ const queued = options.operation === "run";
33
+ if (queued) {
34
+ await fs.mkdir(queue, { recursive: true, mode: 0o700 });
35
+ const name = `${String(Date.now()).padStart(13, "0")}-${process.hrtime.bigint().toString().padStart(20, "0")}-${randomUUID()}.json`;
36
+ ticket = path.join(queue, name);
37
+ temporary = path.join(queue, `.new-${randomUUID()}`);
38
+ await fs.writeFile(temporary, JSON.stringify({ pid: process.pid }), {
39
+ flag: "wx",
40
+ mode: 0o600,
41
+ });
42
+ await fs.rename(temporary, ticket);
43
+ }
44
+ try {
45
+ for (;;) {
46
+ options.signal?.throwIfAborted();
47
+ if (queued && performance.now() >= options.deadline!)
48
+ throw new CadRefusal(
49
+ "cad-queue-timeout",
50
+ "The CAD run's timeout expired while waiting for another operation. This run was not dispatched.",
51
+ );
52
+ const names = (
53
+ await fs.readdir(queue).catch((e) => {
54
+ if (e.code === "ENOENT") return [] as string[];
55
+ throw e;
56
+ })
57
+ )
58
+ .filter((n) => /^\d+-\d+-[a-f0-9-]+\.json$/.test(n))
59
+ .sort();
60
+ const live: string[] = [];
61
+ for (const name of names) {
62
+ const file = path.join(queue, name);
63
+ try {
64
+ const previous = JSON.parse(await fs.readFile(file, "utf8"));
65
+ if (dead(previous.pid)) {
66
+ await fs.unlink(file).catch(() => {});
67
+ continue;
68
+ }
69
+ } catch (e) {
70
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") continue;
71
+ }
72
+ live.push(name);
73
+ }
74
+ const turn = queued
75
+ ? live[0] === path.basename(ticket!)
76
+ : live.length === 0;
77
+ let handle;
78
+ if (turn) {
79
+ try {
80
+ handle = await fs.open(lock, "wx", 0o600);
81
+ } catch (e) {
82
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
83
+ try {
84
+ const previous = JSON.parse(await fs.readFile(lock, "utf8"));
85
+ if (dead(previous.pid)) {
86
+ await fs.unlink(lock).catch(() => {});
87
+ continue;
88
+ }
89
+ } catch {
90
+ /* A partially written live lock stays locked. */
91
+ }
92
+ }
93
+ }
94
+ if (handle) {
95
+ try {
96
+ await handle.writeFile(
97
+ JSON.stringify({ pid: process.pid, operation: options.operation }),
98
+ );
99
+ if (ticket) {
100
+ await fs.unlink(ticket);
101
+ ticket = undefined;
102
+ }
103
+ return await work(Math.round(performance.now() - start));
104
+ } finally {
105
+ await handle.close();
106
+ await fs.unlink(lock).catch(() => {});
107
+ }
108
+ }
109
+ if (!queued)
110
+ throw new CadRefusal(
111
+ options.operation === "setup"
112
+ ? "cad-setup-busy"
113
+ : "cad-operation-busy",
114
+ "Another CAD operation is already running or queued. Wait for it to finish; this request was not dispatched.",
115
+ );
116
+ await delay(
117
+ Math.min(50, Math.max(1, options.deadline! - performance.now())),
118
+ undefined,
119
+ { signal: options.signal },
120
+ );
121
+ }
122
+ } finally {
123
+ if (ticket) await fs.unlink(ticket).catch(() => {});
124
+ if (temporary) await fs.unlink(temporary).catch(() => {});
125
+ }
126
+ }
@@ -0,0 +1,232 @@
1
+ import fs from "node:fs/promises";
2
+ import { createReadStream } from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+
6
+ // Budget estimates for the shipped pins, including managed Python and retained uv cache.
7
+ export const CAD_SIZE_ESTIMATE = {
8
+ expected_download_bytes: 350 * 1024 ** 2,
9
+ expected_installed_bytes: 1536 * 1024 ** 2,
10
+ };
11
+ export interface CadStorage {
12
+ expected_download_bytes: number;
13
+ expected_installed_bytes: number;
14
+ installed_bytes: number | null;
15
+ measurement: "allocated-last-setup";
16
+ measured_at?: string;
17
+ }
18
+ export function storageInfo(
19
+ marker: { installed_bytes?: unknown; measured_at?: unknown } | undefined,
20
+ exists: boolean,
21
+ ): CadStorage {
22
+ return {
23
+ ...CAD_SIZE_ESTIMATE,
24
+ installed_bytes:
25
+ typeof marker?.installed_bytes === "number" &&
26
+ Number.isFinite(marker.installed_bytes) &&
27
+ marker.installed_bytes >= 0
28
+ ? marker.installed_bytes
29
+ : exists
30
+ ? null
31
+ : 0,
32
+ measurement: "allocated-last-setup",
33
+ ...(typeof marker?.measured_at === "string"
34
+ ? { measured_at: marker.measured_at }
35
+ : {}),
36
+ };
37
+ }
38
+ /** Allocated filesystem bytes, like du; no symlink traversal or double-counted hardlinks. */
39
+ export async function measureEnvironment(data: string): Promise<number> {
40
+ const seen = new Set<string>();
41
+ let bytes = 0;
42
+ async function walk(file: string): Promise<void> {
43
+ const stat = await fs.lstat(file).catch((e) => {
44
+ if (e.code === "ENOENT") return null;
45
+ throw e;
46
+ });
47
+ if (!stat) return;
48
+ const key = `${stat.dev}:${stat.ino}`;
49
+ if (seen.has(key)) return;
50
+ seen.add(key);
51
+ bytes += stat.blocks * 512;
52
+ if (stat.isDirectory())
53
+ for (const name of await fs.readdir(file))
54
+ await walk(path.join(file, name));
55
+ }
56
+ for (const name of ["runtime", "python", "cache"])
57
+ await walk(path.join(data, name));
58
+ return bytes;
59
+ }
60
+ async function digest(
61
+ file: string,
62
+ signal?: AbortSignal,
63
+ ): Promise<{ hash: string; bytes: number }> {
64
+ const hash = createHash("sha256");
65
+ let bytes = 0;
66
+ signal?.throwIfAborted();
67
+ const stream = createReadStream(file);
68
+ const abort = () => {
69
+ const error = new Error("CAD input snapshot cancelled.");
70
+ error.name = "AbortError";
71
+ stream.destroy(error);
72
+ };
73
+ signal?.addEventListener("abort", abort, { once: true });
74
+ try {
75
+ for await (const chunk of stream) {
76
+ signal?.throwIfAborted();
77
+ bytes += chunk.length;
78
+ if (bytes > 64 * 1024 ** 2) throw new Error("CAD input exceeds 64 MiB.");
79
+ hash.update(chunk);
80
+ }
81
+ return { hash: hash.digest("hex"), bytes };
82
+ } finally {
83
+ signal?.removeEventListener("abort", abort);
84
+ stream.destroy();
85
+ }
86
+ }
87
+ /** Each immutable bundle contains exactly the declared files, retaining linked asset basenames. */
88
+ export async function snapshotInputs(
89
+ root: string,
90
+ files: Record<string, string>,
91
+ signal?: AbortSignal,
92
+ index?: {
93
+ directory: string;
94
+ authorize: (directory: string) => Promise<string>;
95
+ },
96
+ ) {
97
+ const entries: {
98
+ alias: string;
99
+ file: string;
100
+ name: string;
101
+ hash: string;
102
+ bytes: number;
103
+ }[] = [];
104
+ let bytes = 0;
105
+ const names = new Set<string>();
106
+ for (const [alias, file] of Object.entries(files)) {
107
+ const name = path.basename(file);
108
+ if (names.has(name.toLowerCase()))
109
+ throw new Error(
110
+ "CAD input files must have distinct original filenames so linked mesh/texture assets remain unambiguous.",
111
+ );
112
+ names.add(name.toLowerCase());
113
+ const content = await digest(file, signal);
114
+ bytes += content.bytes;
115
+ if (bytes > 256 * 1024 ** 2)
116
+ throw new Error("CAD inputs exceed their 256 MiB total limit.");
117
+ entries.push({ alias, file, name, ...content });
118
+ }
119
+ const inputs: Record<string, string> = {},
120
+ hashes: Record<string, string> = {};
121
+ if (!entries.length)
122
+ return { inputs, hashes, directory: null, added: 0, reused: 0 };
123
+ const identity = entries
124
+ .map(({ name, hash, bytes }) => ({ name, hash, bytes }))
125
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
126
+ const id = createHash("sha256")
127
+ .update(JSON.stringify(identity))
128
+ .digest("hex");
129
+ const cache = path.join(root, ".cad-inputs"),
130
+ directory = path.join(cache, id);
131
+ async function verify(directory: string): Promise<void> {
132
+ if (!(await fs.lstat(directory)).isDirectory())
133
+ throw new Error("CAD input bundle must be a directory, not a link.");
134
+ const found = await fs.readdir(directory);
135
+ if (
136
+ found.length !== entries.length ||
137
+ found.some((n) => !entries.some((e) => e.name === n))
138
+ )
139
+ throw new Error("CAD input bundle contains undeclared files.");
140
+ for (const entry of entries) {
141
+ const file = path.join(directory, entry.name);
142
+ if (!(await fs.lstat(file)).isFile())
143
+ throw new Error("CAD cached input is not a regular file.");
144
+ const actual = await digest(file, signal);
145
+ if (actual.hash !== entry.hash || actual.bytes !== entry.bytes)
146
+ throw new Error("CAD input cache failed its content hash check.");
147
+ }
148
+ }
149
+ const candidates = new Set(
150
+ Object.values(files).map((file) => path.dirname(file)),
151
+ );
152
+ if (index) {
153
+ try {
154
+ const known = JSON.parse(
155
+ await fs.readFile(path.join(index.directory, id + ".json"), "utf8"),
156
+ );
157
+ if (typeof known.directory === "string") candidates.add(known.directory);
158
+ } catch {
159
+ /* An absent/stale index is rebuilt from declared content. */
160
+ }
161
+ }
162
+ for (const candidate of candidates) {
163
+ if (
164
+ path.basename(candidate) !== id ||
165
+ path.basename(path.dirname(candidate)) !== ".cad-inputs"
166
+ )
167
+ continue;
168
+ try {
169
+ if (index) await index.authorize(candidate);
170
+ await verify(candidate);
171
+ for (const entry of entries) {
172
+ inputs[entry.alias] = path.join(candidate, entry.name);
173
+ hashes[entry.alias] = entry.hash;
174
+ }
175
+ return { inputs, hashes, directory: candidate, added: 0, reused: bytes };
176
+ } catch {
177
+ /* Do not expose a stale, out-of-policy or incomplete bundle. */
178
+ }
179
+ }
180
+ await fs.mkdir(cache, { recursive: true, mode: 0o700 });
181
+ if ((await fs.lstat(cache)).isSymbolicLink())
182
+ throw new Error("CAD input cache must not be a symlink.");
183
+ let added = 0;
184
+ try {
185
+ await verify(directory);
186
+ } catch (e) {
187
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
188
+ const stage = await fs.mkdtemp(path.join(cache, ".stage-"));
189
+ try {
190
+ for (const entry of entries) {
191
+ const file = path.join(stage, entry.name);
192
+ await fs.copyFile(entry.file, file);
193
+ const copied = await digest(file, signal);
194
+ if (copied.hash !== entry.hash || copied.bytes !== entry.bytes)
195
+ throw new Error(
196
+ "CAD input changed while snapshotting; no run was dispatched.",
197
+ );
198
+ await fs.chmod(file, 0o444);
199
+ }
200
+ try {
201
+ await fs.rename(stage, directory);
202
+ added = bytes;
203
+ } catch (e) {
204
+ if (
205
+ !["EEXIST", "ENOTEMPTY"].includes((e as NodeJS.ErrnoException).code!)
206
+ )
207
+ throw e;
208
+ await verify(directory);
209
+ }
210
+ } finally {
211
+ await fs.rm(stage, { recursive: true, force: true });
212
+ }
213
+ }
214
+ if (index) {
215
+ await fs.mkdir(index.directory, { recursive: true, mode: 0o700 });
216
+ const temporary = path.join(index.directory, ".new-" + randomUUID());
217
+ try {
218
+ await fs.writeFile(temporary, JSON.stringify({ directory }), {
219
+ flag: "wx",
220
+ mode: 0o600,
221
+ });
222
+ await fs.rename(temporary, path.join(index.directory, id + ".json"));
223
+ } finally {
224
+ await fs.unlink(temporary).catch(() => {});
225
+ }
226
+ }
227
+ for (const entry of entries) {
228
+ inputs[entry.alias] = path.join(directory, entry.name);
229
+ hashes[entry.alias] = entry.hash;
230
+ }
231
+ return { inputs, hashes, directory, added, reused: bytes - added };
232
+ }