bambu-printer-mcp 1.1.67 → 1.1.69
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/bambu-network-bridge.d.ts +51 -1
- package/dist/bambu-network-bridge.js +230 -20
- package/dist/counterpart/model-plates.d.ts +20 -0
- package/dist/counterpart/model-plates.js +106 -0
- package/dist/counterpart/remote.js +1 -0
- package/dist/counterpart/setup.d.ts +2 -2
- package/dist/counterpart/sliced-file.d.ts +7 -2
- package/dist/counterpart/sliced-file.js +8 -2
- package/dist/design-guidance.d.ts +14 -0
- package/dist/design-guidance.js +27 -1
- package/dist/index.js +45 -9
- package/dist/safety/artifact.d.ts +5 -2
- package/dist/safety/artifact.js +6 -3
- package/dist/safety/print-file.js +6 -1
- package/dist/slicer/slicer-messages.d.ts +4 -0
- package/dist/slicer/slicer-messages.js +62 -0
- package/dist/stl/stl-manipulator.d.ts +4 -0
- package/dist/stl/stl-manipulator.js +8 -1
- package/dist/tool-annotations.js +1 -0
- package/package.json +1 -1
- package/src/bambu-network-bridge.ts +227 -24
- package/src/counterpart/model-plates.ts +111 -0
- package/src/counterpart/remote.ts +1 -0
- package/src/counterpart/sliced-file.ts +14 -5
- package/src/design-guidance.ts +30 -1
- package/src/index.ts +43 -9
- package/src/safety/artifact.ts +6 -3
- package/src/safety/print-file.ts +6 -1
- package/src/slicer/slicer-messages.ts +64 -0
- package/src/stl/stl-manipulator.ts +12 -1
- package/src/tool-annotations.ts +1 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
1
|
+
import { execFile, spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import os from "node:os";
|
|
@@ -153,7 +153,8 @@ export type BambuNetworkBridgeStatus = {
|
|
|
153
153
|
* which the host must already be able to read.
|
|
154
154
|
*/
|
|
155
155
|
export function bambuNetworkCertDir(configDir: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
156
|
-
|
|
156
|
+
// Absolute, as every folder given to the host is: a containerized host runs from /plugins, not this server's folder.
|
|
157
|
+
return path.resolve(trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert"));
|
|
157
158
|
}
|
|
158
159
|
|
|
159
160
|
export function prepareBambuNetworkCertDir(configDir: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
@@ -177,6 +178,179 @@ function shellQuote(value: string): string {
|
|
|
177
178
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
178
179
|
}
|
|
179
180
|
|
|
181
|
+
/**
|
|
182
|
+
* FULU's Linux host run in a Docker image (BAMBU_NETWORK_BRIDGE_IMAGE), for a Mac or any machine without the
|
|
183
|
+
* x86-64 Linux runtime installed natively. The image holds FULU's host runtime in /fulu (pjarczak_bambu_linux_host
|
|
184
|
+
* and ca-certificates.crt) and the networking plug-in in /plugins (libbambu_networking.so, libBambuSource.so).
|
|
185
|
+
*/
|
|
186
|
+
export type BridgeContainer = {
|
|
187
|
+
image: string;
|
|
188
|
+
docker: string;
|
|
189
|
+
dockerHost?: string;
|
|
190
|
+
/** A Colima profile started (never stopped or restarted) when Docker doesn't answer. */
|
|
191
|
+
colima?: { executable: string; profile: string; home?: string };
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
export function bridgeContainer(env: NodeJS.ProcessEnv = process.env): BridgeContainer | undefined {
|
|
195
|
+
const image = trimEnv(env.BAMBU_NETWORK_BRIDGE_IMAGE);
|
|
196
|
+
if (!image) return undefined;
|
|
197
|
+
const dockerHost = trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER_HOST);
|
|
198
|
+
const profile = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE);
|
|
199
|
+
const home = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_HOME);
|
|
200
|
+
// A Colima profile started with --activate=false leaves Docker's default context alone, so without an explicit
|
|
201
|
+
// host the server talks to that profile's own socket.
|
|
202
|
+
const colimaHome = home || path.join(os.homedir(), ".colima");
|
|
203
|
+
const host = dockerHost || (profile ? `unix://${path.join(colimaHome, profile, "docker.sock")}` : undefined);
|
|
204
|
+
return {
|
|
205
|
+
image,
|
|
206
|
+
docker: trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER) || "docker",
|
|
207
|
+
...(host ? { dockerHost: host } : {}),
|
|
208
|
+
...(profile ? { colima: { executable: trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA) || "colima", profile, ...(home ? { home } : {}) } } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** `--host <socket>` for every docker call, when a host is set. */
|
|
213
|
+
function dockerHostArgs(container: BridgeContainer): string[] {
|
|
214
|
+
return container.dockerHost ? ["--host", container.dockerHost] : [];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The image's fixed layout: FULU's runtime and the networking plug-in, with the CA bundle cloud calls need. */
|
|
218
|
+
const CONTAINER_ENV = [
|
|
219
|
+
"LD_LIBRARY_PATH=/plugins:/fulu",
|
|
220
|
+
"SSL_CERT_FILE=/fulu/ca-certificates.crt",
|
|
221
|
+
"CURL_CA_BUNDLE=/fulu/ca-certificates.crt",
|
|
222
|
+
"SSL_CERT_DIR=/etc/ssl/certs",
|
|
223
|
+
"PJARCZAK_BAMBU_PLUGIN_DIR=/plugins",
|
|
224
|
+
"PJARCZAK_BAMBU_NETWORK_SO=/plugins/libbambu_networking.so",
|
|
225
|
+
"PJARCZAK_BAMBU_SOURCE_SO=/plugins/libBambuSource.so",
|
|
226
|
+
];
|
|
227
|
+
/** Set by the server for the host (country, expected network version): passed into the container from its env. */
|
|
228
|
+
const CONTAINER_PASSED_ENV = ["PJARCZAK_BAMBU_COUNTRY_CODE", "PJARCZAK_EXPECTED_BAMBU_NETWORK_VERSION"];
|
|
229
|
+
|
|
230
|
+
/** The explicit host command, when one is set: it wins over the Docker image. */
|
|
231
|
+
function explicitBridgeCommand(env: NodeJS.ProcessEnv = process.env): string | undefined {
|
|
232
|
+
return trimEnv(env.BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.PJARCZAK_BAMBU_BRIDGE_COMMAND);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function configuredBridgeConfigDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
236
|
+
return path.resolve(trimEnv(env.BAMBU_NETWORK_CONFIG_DIR) || trimEnv(env.PJARCZAK_BAMBU_PROBE_LOG_DIR) || defaultBambuNetworkConfigDir());
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Where a print's checked snapshot is written when the host runs in the Docker image: inside the agent's config
|
|
241
|
+
* folder, which the container mounts. The system temporary folder is no good there: Colima shares the home
|
|
242
|
+
* folder but not /tmp or /var/folders, so the host would see an empty folder. Undefined without the image.
|
|
243
|
+
*/
|
|
244
|
+
export function bridgeSnapshotRoot(env: NodeJS.ProcessEnv = process.env): string | undefined {
|
|
245
|
+
if (explicitBridgeCommand(env) || !bridgeContainer(env)) return undefined;
|
|
246
|
+
const root = path.join(configuredBridgeConfigDir(env), "print-snapshots");
|
|
247
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
248
|
+
clearStaleSnapshots(root);
|
|
249
|
+
return root;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const STALE_SNAPSHOT_MS = 24 * 60 * 60 * 1000;
|
|
253
|
+
const clearedSnapshotRoots = new Set<string>();
|
|
254
|
+
/**
|
|
255
|
+
* A snapshot kept for an upload still running is removed when the server exits; one a killed server left stays
|
|
256
|
+
* here, where no system cleanup reaches it. Once per server, snapshots older than a day are removed.
|
|
257
|
+
*/
|
|
258
|
+
function clearStaleSnapshots(root: string, now = Date.now()): void {
|
|
259
|
+
if (clearedSnapshotRoots.has(root)) return;
|
|
260
|
+
clearedSnapshotRoots.add(root);
|
|
261
|
+
for (const name of fs.readdirSync(root)) {
|
|
262
|
+
if (!name.startsWith("bambu-print-")) continue;
|
|
263
|
+
const dir = path.join(root, name);
|
|
264
|
+
try { if (now - fs.statSync(dir).mtimeMs > STALE_SNAPSHOT_MS) fs.rmSync(dir, { recursive: true, force: true }); } catch { /* gone already */ }
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The folders the host must see at the same absolute paths: the agent's config folder (the plug-in writes its
|
|
270
|
+
* logs and session there; a host given a log_dir it can't open aborts, FULU #54), the folder print snapshots are
|
|
271
|
+
* written to, and the certificate folder.
|
|
272
|
+
*/
|
|
273
|
+
export function bridgeContainerMounts(configDir: string, env: NodeJS.ProcessEnv = process.env): string[] {
|
|
274
|
+
fs.mkdirSync(configDir, { recursive: true });
|
|
275
|
+
const folders = [path.resolve(configDir)];
|
|
276
|
+
const snapshots = bridgeSnapshotRoot(env);
|
|
277
|
+
if (snapshots) folders.push(path.resolve(snapshots));
|
|
278
|
+
const certDir = trimEnv(env.BAMBU_NETWORK_CERT_DIR);
|
|
279
|
+
if (certDir) {
|
|
280
|
+
// Made here, so Docker doesn't create it (as root, inside the VM) for the mount.
|
|
281
|
+
fs.mkdirSync(certDir, { recursive: true });
|
|
282
|
+
folders.push(path.resolve(certDir));
|
|
283
|
+
}
|
|
284
|
+
const unique = [...new Set(folders)].filter((dir, _i, all) => !all.some(other => other !== dir && dir.startsWith(other + path.sep)));
|
|
285
|
+
// The host is given these paths as written, so each is mounted there; the VM reads the folder it really is
|
|
286
|
+
// (a symlinked folder's link target need not be shared with the VM).
|
|
287
|
+
return unique.map(dir => {
|
|
288
|
+
let real = dir;
|
|
289
|
+
try { real = fs.realpathSync(dir); } catch { /* created later by the host */ }
|
|
290
|
+
if (dir.includes(":") || real.includes(":")) throw new Error(`The FULU container can't mount ${dir}: Docker volume paths can't contain ':'. Move that folder.`);
|
|
291
|
+
return `${real}:${dir}`;
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* docker run for the host: stdin/stdout are the bridge's framed protocol; the host is piped through cat (FULU #50).
|
|
297
|
+
* `--init` puts an init process first, so the SIGTERM docker forwards on stop reaches the host: a shell as the
|
|
298
|
+
* container's first process ignores it, and the container kept running after the server stopped. `name` lets stop
|
|
299
|
+
* remove the container even when the docker client was killed.
|
|
300
|
+
*/
|
|
301
|
+
export function bridgeContainerArgs(container: BridgeContainer, mounts: string[], name?: string): string[] {
|
|
302
|
+
return [
|
|
303
|
+
...dockerHostArgs(container),
|
|
304
|
+
"run", "--rm", "-i", "--init", ...(name ? ["--name", name] : []),
|
|
305
|
+
"--platform", "linux/amd64", "--network", "host", "--log-driver=none", "--workdir", "/plugins",
|
|
306
|
+
...mounts.flatMap(mount => ["-v", `${mount}:rw`]),
|
|
307
|
+
...CONTAINER_ENV.flatMap(value => ["-e", value]),
|
|
308
|
+
...CONTAINER_PASSED_ENV.flatMap(name => ["-e", name]),
|
|
309
|
+
container.image,
|
|
310
|
+
"/bin/sh", "-c", "/fulu/pjarczak_bambu_linux_host | cat",
|
|
311
|
+
];
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const runQuietly = (file: string, args: string[], options: { env?: NodeJS.ProcessEnv; timeout: number }) =>
|
|
315
|
+
new Promise<void>((resolve, reject) => {
|
|
316
|
+
execFile(file, args, { env: options.env ?? process.env, timeout: options.timeout, maxBuffer: 1024 * 1024 }, (error, _stdout, stderr) => {
|
|
317
|
+
if (error) reject(Object.assign(error, { stderr: String(stderr ?? "") }));
|
|
318
|
+
else resolve();
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Docker must answer before the host starts. When it doesn't and a Colima profile is configured, that profile is
|
|
324
|
+
* started without changing Docker's global context; a running profile is never stopped or restarted.
|
|
325
|
+
*/
|
|
326
|
+
export async function ensureBridgeContainerRuntime(container: BridgeContainer, timeouts = { infoMs: 20_000, startMs: 600_000 }): Promise<void> {
|
|
327
|
+
const info = () => runQuietly(container.docker, [...dockerHostArgs(container), "info"], { timeout: timeouts.infoMs });
|
|
328
|
+
try { await info(); return; } catch (error) {
|
|
329
|
+
if (!container.colima) {
|
|
330
|
+
throw new Error(`Docker didn't answer (${container.docker}${container.dockerHost ? ` --host ${container.dockerHost}` : ""} info), so the FULU container can't start. Start Docker, or set BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const { executable, profile, home } = container.colima!;
|
|
334
|
+
try {
|
|
335
|
+
await runQuietly(executable, ["start", "--profile", profile, "--activate=false"], { env: { ...process.env, ...(home ? { COLIMA_HOME: home } : {}) }, timeout: timeouts.startMs });
|
|
336
|
+
} catch (error) {
|
|
337
|
+
const detail = String((error as { stderr?: string }).stderr ?? "").trim().split("\n").slice(-3).join(" ");
|
|
338
|
+
throw new Error(`Colima profile ${profile} didn't start for the FULU container${detail ? `: ${detail}` : "."}`);
|
|
339
|
+
}
|
|
340
|
+
try { await info(); } catch {
|
|
341
|
+
throw new Error(`Colima profile ${profile} started, but Docker still doesn't answer at ${container.dockerHost ?? "its default host"}.`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Stops the bridge's own named container (SIGTERM to the host through --init, two seconds to exit), then removes
|
|
347
|
+
* it. A container that is already gone is fine.
|
|
348
|
+
*/
|
|
349
|
+
async function removeBridgeContainer(container: BridgeContainer, name: string): Promise<void> {
|
|
350
|
+
await runQuietly(container.docker, [...dockerHostArgs(container), "stop", "--time", "2", name], { timeout: 20_000 }).catch(() => undefined);
|
|
351
|
+
await runQuietly(container.docker, [...dockerHostArgs(container), "rm", "-f", name], { timeout: 20_000 }).catch(() => undefined);
|
|
352
|
+
}
|
|
353
|
+
|
|
180
354
|
function trimEnv(value: string | undefined): string | undefined {
|
|
181
355
|
const trimmed = value?.trim();
|
|
182
356
|
return trimmed ? trimmed : undefined;
|
|
@@ -350,6 +524,9 @@ function assertBridgeOk(value: unknown, method: string): void {
|
|
|
350
524
|
export class BambuNetworkBridge {
|
|
351
525
|
private child?: ChildProcessWithoutNullStreams;
|
|
352
526
|
private commandLine?: string;
|
|
527
|
+
/** This bridge's own container, when the host runs in the Docker image: unique, so two servers never remove each other's. */
|
|
528
|
+
private readonly containerName = `bambu-fulu-host-${process.pid}-${randomUUID().slice(0, 8)}`;
|
|
529
|
+
private runningContainer?: BridgeContainer;
|
|
353
530
|
private stdoutBuffer = Buffer.alloc(0);
|
|
354
531
|
private pending = new Map<number, PendingRequest>();
|
|
355
532
|
private nextRequestId = 1;
|
|
@@ -367,23 +544,18 @@ export class BambuNetworkBridge {
|
|
|
367
544
|
*/
|
|
368
545
|
private localSessionTail: Promise<void> = Promise.resolve();
|
|
369
546
|
|
|
370
|
-
resolveBridgeCommand(override?: string): string {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
);
|
|
547
|
+
resolveBridgeCommand(override?: string, configDir?: string): string {
|
|
548
|
+
const explicit = trimEnv(override) || explicitBridgeCommand();
|
|
549
|
+
if (explicit) return explicit;
|
|
550
|
+
const container = bridgeContainer();
|
|
551
|
+
if (!container) return "";
|
|
552
|
+
const mounts = bridgeContainerMounts(this.resolveConfigDir(configDir));
|
|
553
|
+
return [container.docker, ...bridgeContainerArgs(container, mounts, this.containerName)].map(shellQuote).join(" ");
|
|
378
554
|
}
|
|
379
555
|
|
|
380
556
|
resolveConfigDir(override?: string): string {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
trimEnv(process.env.BAMBU_NETWORK_CONFIG_DIR) ||
|
|
384
|
-
trimEnv(process.env.PJARCZAK_BAMBU_PROBE_LOG_DIR) ||
|
|
385
|
-
defaultBambuNetworkConfigDir()
|
|
386
|
-
);
|
|
557
|
+
const dir = trimEnv(override);
|
|
558
|
+
return dir ? path.resolve(dir) : configuredBridgeConfigDir();
|
|
387
559
|
}
|
|
388
560
|
|
|
389
561
|
resolveCountryCode(override?: string): string {
|
|
@@ -396,7 +568,7 @@ export class BambuNetworkBridge {
|
|
|
396
568
|
}
|
|
397
569
|
|
|
398
570
|
getStatus(options: BambuNetworkBridgeOptions = {}): BambuNetworkBridgeStatus {
|
|
399
|
-
const command = this.resolveBridgeCommand(options.bridgeCommand);
|
|
571
|
+
const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
|
|
400
572
|
const configDir = this.resolveConfigDir(options.configDir);
|
|
401
573
|
const countryCode = this.resolveCountryCode(options.countryCode);
|
|
402
574
|
|
|
@@ -427,7 +599,7 @@ export class BambuNetworkBridge {
|
|
|
427
599
|
runtime,
|
|
428
600
|
note: command
|
|
429
601
|
? undefined
|
|
430
|
-
: "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command.",
|
|
602
|
+
: "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command, or BAMBU_NETWORK_BRIDGE_IMAGE to a Docker image holding FULU's Linux host.",
|
|
431
603
|
};
|
|
432
604
|
}
|
|
433
605
|
|
|
@@ -436,7 +608,7 @@ export class BambuNetworkBridge {
|
|
|
436
608
|
throw new Error("BambuNetwork bridge method is required.");
|
|
437
609
|
}
|
|
438
610
|
|
|
439
|
-
await this.ensureStarted(options.bridgeCommand);
|
|
611
|
+
await this.ensureStarted(options.bridgeCommand, options.configDir);
|
|
440
612
|
await options.beforeDispatch?.(method);
|
|
441
613
|
|
|
442
614
|
const id = this.nextRequestId++;
|
|
@@ -481,7 +653,7 @@ export class BambuNetworkBridge {
|
|
|
481
653
|
agent: number;
|
|
482
654
|
handshake: unknown;
|
|
483
655
|
}> {
|
|
484
|
-
const command = this.resolveBridgeCommand(options.bridgeCommand);
|
|
656
|
+
const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
|
|
485
657
|
const configDir = this.resolveConfigDir(options.configDir);
|
|
486
658
|
const countryCode = this.resolveCountryCode(options.countryCode);
|
|
487
659
|
const userInfo = trimEnv(options.userInfo) || trimEnv(process.env.BAMBU_NETWORK_USER_INFO) || "";
|
|
@@ -939,6 +1111,8 @@ export class BambuNetworkBridge {
|
|
|
939
1111
|
|
|
940
1112
|
async stop(): Promise<void> {
|
|
941
1113
|
const child = this.child;
|
|
1114
|
+
const running = this.runningContainer;
|
|
1115
|
+
this.runningContainer = undefined;
|
|
942
1116
|
this.child = undefined;
|
|
943
1117
|
this.commandLine = undefined;
|
|
944
1118
|
this.agentId = undefined;
|
|
@@ -952,15 +1126,26 @@ export class BambuNetworkBridge {
|
|
|
952
1126
|
this.pending.delete(id);
|
|
953
1127
|
}
|
|
954
1128
|
|
|
1129
|
+
// The container goes first: a shell that keeps the docker client as its own child holds the pipes open until
|
|
1130
|
+
// the client exits, so waiting for the shell before removing the container could wait for ever.
|
|
1131
|
+
if (running) await removeBridgeContainer(running, this.containerName);
|
|
955
1132
|
if (child && child.exitCode === null) {
|
|
956
1133
|
await new Promise<void>((resolve) => {
|
|
1134
|
+
let settleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
957
1135
|
const forceTimer = setTimeout(() => {
|
|
958
1136
|
if (child.exitCode === null) {
|
|
959
1137
|
child.kill("SIGKILL");
|
|
960
1138
|
}
|
|
1139
|
+
// A descendant can still hold the pipes after the shell is killed: stop waiting for it, and let go of
|
|
1140
|
+
// those pipes so nothing it writes reaches a bridge started after this one.
|
|
1141
|
+
settleTimer = setTimeout(() => {
|
|
1142
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
|
|
1143
|
+
resolve();
|
|
1144
|
+
}, 2000);
|
|
961
1145
|
}, 2000);
|
|
962
1146
|
child.once("close", () => {
|
|
963
1147
|
clearTimeout(forceTimer);
|
|
1148
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
964
1149
|
resolve();
|
|
965
1150
|
});
|
|
966
1151
|
child.kill("SIGTERM");
|
|
@@ -968,12 +1153,22 @@ export class BambuNetworkBridge {
|
|
|
968
1153
|
}
|
|
969
1154
|
}
|
|
970
1155
|
|
|
971
|
-
|
|
972
|
-
|
|
1156
|
+
/** A start in progress: concurrent callers wait for it, so a cold Docker host is started (and named) once. */
|
|
1157
|
+
private starting?: Promise<void>;
|
|
1158
|
+
|
|
1159
|
+
private async ensureStarted(commandOverride?: string, configDir?: string): Promise<void> {
|
|
1160
|
+
while (this.starting) await this.starting.catch(() => undefined);
|
|
1161
|
+
const start = this.startBridge(commandOverride, configDir);
|
|
1162
|
+
this.starting = start;
|
|
1163
|
+
try { await start; } finally { if (this.starting === start) this.starting = undefined; }
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
private async startBridge(commandOverride?: string, configDir?: string): Promise<void> {
|
|
1167
|
+
const command = this.resolveBridgeCommand(commandOverride, configDir);
|
|
973
1168
|
if (!command) {
|
|
974
1169
|
throw new Error(
|
|
975
|
-
"BAMBU_NETWORK_BRIDGE_COMMAND is required for FULU BambuNetwork support. " +
|
|
976
|
-
"Point
|
|
1170
|
+
"BAMBU_NETWORK_BRIDGE_COMMAND or BAMBU_NETWORK_BRIDGE_IMAGE is required for FULU BambuNetwork support. " +
|
|
1171
|
+
"Point the command at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper, or name a Docker image holding FULU's Linux host."
|
|
977
1172
|
);
|
|
978
1173
|
}
|
|
979
1174
|
|
|
@@ -985,6 +1180,14 @@ export class BambuNetworkBridge {
|
|
|
985
1180
|
await this.stop();
|
|
986
1181
|
}
|
|
987
1182
|
|
|
1183
|
+
const container = trimEnv(commandOverride) || explicitBridgeCommand() ? undefined : bridgeContainer();
|
|
1184
|
+
if (container) {
|
|
1185
|
+
await ensureBridgeContainerRuntime(container);
|
|
1186
|
+
// The docker client can exit (a dropped socket) while its container keeps running under this bridge's name.
|
|
1187
|
+
await removeBridgeContainer(container, this.containerName);
|
|
1188
|
+
this.runningContainer = container;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
988
1191
|
const shell = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
|
|
989
1192
|
const shellArgs = process.platform === "win32"
|
|
990
1193
|
? ["/d", "/s", "/c", command]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* list_3mf_plates: a Bambu Studio / OrcaSlicer project's plates as its designer laid them out, before slicing
|
|
3
|
+
* (Counterpart PRD §5.5 "Plates of an imported 3MF", §8.0 item 9). Bambu Studio shows a downloaded kit as its
|
|
4
|
+
* plates straight away; clients show the same from here instead of parsing the project files themselves.
|
|
5
|
+
*
|
|
6
|
+
* Plates come from Metadata/model_settings.config (`<plate>` with `plater_id`, `plater_name` and the objects it
|
|
7
|
+
* holds) and, for a sliced file, from Metadata/plate_N.json and plate_N.gcode. A plain 3MF with no plate metadata
|
|
8
|
+
* is one plate. Only bounded metadata is read; nothing is extracted or run.
|
|
9
|
+
*/
|
|
10
|
+
import { readSafe3mfArchive } from "../safety/archive.js";
|
|
11
|
+
|
|
12
|
+
export interface ModelPlate {
|
|
13
|
+
/** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
|
|
14
|
+
index: number;
|
|
15
|
+
name: string;
|
|
16
|
+
objects: string[];
|
|
17
|
+
/** The file already holds this plate's G-code. */
|
|
18
|
+
sliced: boolean;
|
|
19
|
+
/** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
|
|
20
|
+
thumbnail_png_base64?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ModelPlates {
|
|
23
|
+
plate_count: number;
|
|
24
|
+
plates: ModelPlate[];
|
|
25
|
+
title?: string;
|
|
26
|
+
designer?: string;
|
|
27
|
+
licence?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** For the settings and plate files; the model file can be large and is only scanned. */
|
|
31
|
+
const MAX_METADATA_BYTES = 8 * 1024 * 1024;
|
|
32
|
+
const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
|
|
33
|
+
const MAX_PLATES = 1000;
|
|
34
|
+
|
|
35
|
+
const words = (value: string) => value
|
|
36
|
+
.replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&": "&", "<": "<", ">": ">", """: "\"", "'": "'" }[entity]!))
|
|
37
|
+
.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
|
|
38
|
+
|
|
39
|
+
export async function listModelPlates(filePath: string, options: { thumbnails?: boolean } = {}): Promise<ModelPlates> {
|
|
40
|
+
const { zip } = await readSafe3mfArchive(filePath);
|
|
41
|
+
const text = async (name: string) => {
|
|
42
|
+
const file = zip.file(name);
|
|
43
|
+
if (!file) return "";
|
|
44
|
+
const bytes = await file.async("nodebuffer");
|
|
45
|
+
if (bytes.length > MAX_METADATA_BYTES) throw new Error(`${name} is too large to read.`);
|
|
46
|
+
return bytes.toString("utf8");
|
|
47
|
+
};
|
|
48
|
+
// The model file can hold the whole mesh (a plain 3MF): scanned as bytes, never made one string.
|
|
49
|
+
const modelBytes = await zip.file("3D/3dmodel.model")?.async("nodebuffer");
|
|
50
|
+
const head = modelBytes?.subarray(0, 1024 * 1024).toString("utf8") ?? "";
|
|
51
|
+
if (!/<(?:\w+:)?model\b/.test(head)) throw new Error("That file is not a 3MF model.");
|
|
52
|
+
// An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
|
|
53
|
+
const has = (tag: string) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
|
|
54
|
+
const result: ModelPlates = { plate_count: 0, plates: [] };
|
|
55
|
+
const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
|
|
56
|
+
if (metadata.get("Title")) result.title = metadata.get("Title");
|
|
57
|
+
if (metadata.get("Designer")) result.designer = metadata.get("Designer");
|
|
58
|
+
if (metadata.get("License")) result.licence = metadata.get("License");
|
|
59
|
+
|
|
60
|
+
const settings = await text("Metadata/model_settings.config");
|
|
61
|
+
const objects = new Map([...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
|
|
62
|
+
const name = /<metadata\s+key="name"\s+value="([^"]*)"/.exec(match[2]);
|
|
63
|
+
return [match[1], words(name?.[1] ?? "")];
|
|
64
|
+
}));
|
|
65
|
+
const plates = new Map<number, ModelPlate>();
|
|
66
|
+
// A plate number out of range is skipped, as a slicer would not show it.
|
|
67
|
+
const valid = (number: number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
|
|
68
|
+
for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
|
|
69
|
+
const id = /<metadata\s+key="plater_id"\s+value="(\d+)"/.exec(match[1]);
|
|
70
|
+
if (!id) continue;
|
|
71
|
+
const number = Number(id[1]);
|
|
72
|
+
if (!valid(number)) continue;
|
|
73
|
+
const name = /<metadata\s+key="plater_name"\s+value="([^"]*)"/.exec(match[1]);
|
|
74
|
+
plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false,
|
|
75
|
+
objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
|
|
76
|
+
}
|
|
77
|
+
for (const name of Object.keys(zip.files)) {
|
|
78
|
+
const match = /^Metadata\/plate_([1-9]\d*)\.(json|gcode)$/.exec(name);
|
|
79
|
+
if (!match) continue;
|
|
80
|
+
const number = Number(match[1]);
|
|
81
|
+
if (!valid(number)) continue;
|
|
82
|
+
const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], sliced: false };
|
|
83
|
+
if (match[2] === "gcode") plate.sliced = true;
|
|
84
|
+
else {
|
|
85
|
+
try {
|
|
86
|
+
const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[] };
|
|
87
|
+
if (Array.isArray(value.bbox_objects)) plate.objects = value.bbox_objects
|
|
88
|
+
.flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
|
|
89
|
+
} catch { /* the plate keeps the objects model_settings lists */ }
|
|
90
|
+
}
|
|
91
|
+
plates.set(number, plate);
|
|
92
|
+
}
|
|
93
|
+
result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
|
|
94
|
+
// A standard single-build 3MF has no Bambu plate metadata: it is one plate.
|
|
95
|
+
if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], sliced: false });
|
|
96
|
+
const geometry = has("item") && (has("mesh") || has("component"));
|
|
97
|
+
if (!geometry) {
|
|
98
|
+
// A sliced-only file (previews and G-code, no model): only its sliced plates can print.
|
|
99
|
+
result.plates = result.plates.filter(plate => plate.sliced);
|
|
100
|
+
if (!result.plates.length) throw new Error("This 3MF has previews and settings but no model or printable plate.");
|
|
101
|
+
}
|
|
102
|
+
if (options.thumbnails) for (const plate of result.plates) {
|
|
103
|
+
const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
|
|
104
|
+
if (!file) continue;
|
|
105
|
+
const bytes = await file.async("nodebuffer");
|
|
106
|
+
if (bytes.length <= MAX_THUMBNAIL_BYTES && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
|
|
107
|
+
plate.thumbnail_png_base64 = bytes.toString("base64");
|
|
108
|
+
}
|
|
109
|
+
result.plate_count = result.plates.length;
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
@@ -31,6 +31,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
|
|
|
31
31
|
get_printer_filaments: "read",
|
|
32
32
|
resolve_3mf_ams_slots: "read",
|
|
33
33
|
list_3mf_plate_objects: "read",
|
|
34
|
+
list_3mf_plates: "read",
|
|
34
35
|
get_stl_info: "read",
|
|
35
36
|
list_templates: "read",
|
|
36
37
|
list_printer_files: "read",
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
|
|
3
|
+
import { plainSlicerError, UNKNOWN_SLICER_ERROR } from "../slicer/slicer-messages.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* What a client shows about a sliced file, read here so it never parses slicer formats itself (Counterpart PRD
|
|
@@ -92,13 +93,21 @@ async function readFacts(filePath: string, plateIndex: number): Promise<SlicedFi
|
|
|
92
93
|
}
|
|
93
94
|
|
|
94
95
|
/**
|
|
95
|
-
* Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed,
|
|
96
|
-
* (
|
|
96
|
+
* Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, what a person is
|
|
97
|
+
* told (`message`: a plain sentence for a refusal, src/slicer/slicer-messages.ts; the plates' warnings for a slice
|
|
98
|
+
* that worked), the slicer's own words for the log (`slicer_message`: the error and every plate's warning,
|
|
99
|
+
* verbatim), and how many plates it sliced.
|
|
97
100
|
*/
|
|
98
|
-
export interface SlicerReport { failed: boolean; message?: string; plate_count?: number }
|
|
101
|
+
export interface SlicerReport { failed: boolean; message?: string; slicer_message?: string; plate_count?: number }
|
|
99
102
|
|
|
100
103
|
const clean = (text: string) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
|
|
101
104
|
|
|
105
|
+
/** A refusal's report: the plain sentence, and the slicer's words kept beside it. */
|
|
106
|
+
export function refusalReport(words: string): SlicerReport {
|
|
107
|
+
const raw = clean(words).slice(0, 2000);
|
|
108
|
+
return { failed: true, message: plainSlicerError(raw) ?? UNKNOWN_SLICER_ERROR, ...(raw ? { slicer_message: raw } : {}) };
|
|
109
|
+
}
|
|
110
|
+
|
|
102
111
|
export function slicerReport(result: unknown): SlicerReport | undefined {
|
|
103
112
|
if (!result || typeof result !== "object" || Array.isArray(result)) return undefined;
|
|
104
113
|
const value = result as { return_code?: unknown; error_string?: unknown; sliced_plates?: unknown };
|
|
@@ -110,6 +119,6 @@ export function slicerReport(result: unknown): SlicerReport | undefined {
|
|
|
110
119
|
const failed = value.return_code !== 0;
|
|
111
120
|
const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
|
|
112
121
|
const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
|
|
113
|
-
if (failed) return
|
|
114
|
-
return { failed, ...(words ? { message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
|
|
122
|
+
if (failed) return refusalReport(words || `return code ${String(value.return_code)}`);
|
|
123
|
+
return { failed, ...(words ? { message: words, slicer_message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
|
|
115
124
|
}
|
package/src/design-guidance.ts
CHANGED
|
@@ -185,4 +185,33 @@ export const DESIGN_PROMPTS: DesignPrompt[] = [
|
|
|
185
185
|
description: "A separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation: keep, revise, or validate one specific uncertainty." },
|
|
186
186
|
];
|
|
187
187
|
|
|
188
|
-
|
|
188
|
+
const SLICER_NAMES: Record<string, string> = {
|
|
189
|
+
bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "FULU OrcaSlicer-bambulab",
|
|
190
|
+
"orca-slicer-api": "the remote OrcaSlicer service (orca-slicer-api)", prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* How this server's configured slicer orients, makes supports and checks a slice: the slicer-specific half of a
|
|
195
|
+
* design pass's print plan (the fdm_slicing prompt). `capabilities` is what slice_stl applies on that backend, as
|
|
196
|
+
* counterpart_printer_info reports it.
|
|
197
|
+
*/
|
|
198
|
+
export function slicingGuidance(slicerType: string, capabilities: { supports: boolean; orient: boolean }): string {
|
|
199
|
+
const slicer = SLICER_NAMES[slicerType] ?? slicerType;
|
|
200
|
+
const lines = [
|
|
201
|
+
`How this printer MCP slices. Its slicer is ${slicer}.`,
|
|
202
|
+
"- When they could change a decision, read the printer's loaded filaments with get_printer_filaments and its slicing settings with get_slice_settings.",
|
|
203
|
+
"- To check a consequential choice, slice a checkpoint with slice_stl and read its structured slicer_result (return code, error and each plate's warning), not only the file path. A checkpoint is only a check: the print slices the exported model again.",
|
|
204
|
+
capabilities.orient
|
|
205
|
+
? `- Orientation: slice_stl with orient true lets ${slicer}'s own auto-orient choose how an STL sits on the bed. It keeps overhang area low; it does not check cantilevers. To see what it chooses, slice the checkpoint with orient true. When a print is oriented this way, don't promise a particular orientation on the bed: the slicer chooses it.`
|
|
206
|
+
: `- Orientation: ${slicer} doesn't auto-orient here. An STL prints in the orientation it's exported in.`,
|
|
207
|
+
capabilities.supports
|
|
208
|
+
? "- Supports: set enable_support on every slice_stl call. With enable_support true it generates supports in the style support_type names (tree(auto) or normal(auto)); with false it generates none; left out, the process preset's own setting applies. Slice the checkpoint with enable_support set the way the print will be sliced. A print gets the supports it was sliced with: print the sliced file itself, or slice the print with slice_stl and the same enable_support and support_type. print_3mf's own slicing of a file that isn't sliced yet takes no support settings; it uses the process profile's."
|
|
209
|
+
: `- Supports: ${slicer} takes no support settings from slice_stl here: whether it generates supports is its configured profile's own setting. Slice a checkpoint to see what that profile does before modeling any support yourself.`,
|
|
210
|
+
];
|
|
211
|
+
return lines.join("\n");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export const FDM_SLICING_PROMPT = { name: "fdm_slicing", title: "How this MCP slices",
|
|
215
|
+
description: "Add to every design or model-editing task: how this server's slicer orients a model and generates supports, and how to check a choice with a checkpoint slice." };
|
|
216
|
+
|
|
217
|
+
export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt and the fdm_slicing prompt. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split or joint could help, and fdm_after_slice as a separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation. Read " + FDM_CAPABILITY_URI + " when a bridge or overhang is consequential and there is no sufficiently specific measured capability available.";
|