bambu-printer-mcp 1.1.66 → 1.1.68

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.
@@ -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
- return trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert");
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
- return (
372
- trimEnv(override) ||
373
- trimEnv(process.env.BAMBU_NETWORK_BRIDGE_COMMAND) ||
374
- trimEnv(process.env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) ||
375
- trimEnv(process.env.PJARCZAK_BAMBU_BRIDGE_COMMAND) ||
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
- return (
382
- trimEnv(override) ||
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
- private async ensureStarted(commandOverride?: string): Promise<void> {
972
- const command = this.resolveBridgeCommand(commandOverride);
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 it at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper."
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]
@@ -41,6 +41,8 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
41
41
  counterpart_printer_info: "read",
42
42
  counterpart_print_progress: "read",
43
43
  fusion_mcp_status: "read",
44
+ blender_mcp_setup: "read", // checks only; update raises it
45
+ fusion_mcp_setup: "read", // checks only; install raises it
44
46
  // design
45
47
  slice_stl: "design",
46
48
  lay_flat: "design",
@@ -93,6 +95,8 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
93
95
  const RAISED_BY: Readonly<Record<string, Record<string, RemoteScope>>> = {
94
96
  fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
95
97
  blender_mcp_status: { connect: "design" }, // connects to Blender
98
+ blender_mcp_setup: { update: "raw" }, // replaces the add-on in the person's Blender
99
+ fusion_mcp_setup: { install: "raw" }, // installs into the person's Fusion, a login item and this server's .env
96
100
  };
97
101
 
98
102
  /**