bambu-printer-mcp 1.1.91 → 1.1.93

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 (69) hide show
  1. package/CONTRIBUTORS.md +2 -0
  2. package/README.md +8 -4
  3. package/dist/bambu-native.js +1 -1
  4. package/dist/cad/contracts.js +16 -7
  5. package/dist/cad/examples.d.ts +2 -1
  6. package/dist/cad/examples.js +13 -10
  7. package/dist/cad/serial.d.ts +1 -1
  8. package/dist/cad/serial.js +4 -6
  9. package/dist/cad-engine.js +17 -12
  10. package/dist/counterpart/info.d.ts +2 -0
  11. package/dist/counterpart/info.js +6 -1
  12. package/dist/counterpart/remote.js +1 -0
  13. package/dist/counterpart/schemas.d.ts +5 -0
  14. package/dist/counterpart/schemas.js +1 -0
  15. package/dist/counterpart/self-check.d.ts +79 -0
  16. package/dist/counterpart/self-check.js +163 -0
  17. package/dist/index.js +50 -24
  18. package/dist/printers/bambu.d.ts +6 -0
  19. package/dist/printers/bambu.js +59 -25
  20. package/dist/printers/report-merge.d.ts +12 -0
  21. package/dist/printers/report-merge.js +46 -0
  22. package/dist/safety/limits.d.ts +6 -0
  23. package/dist/safety/limits.js +8 -0
  24. package/dist/safety/print-file.js +2 -2
  25. package/dist/safety/printer-state.d.ts +4 -0
  26. package/dist/safety/printer-state.js +14 -1
  27. package/dist/stl/stl-manipulator.js +79 -20
  28. package/dist/studio-print-options.d.ts +9 -0
  29. package/dist/studio-print-options.js +34 -2
  30. package/dist/tool-annotations.js +1 -0
  31. package/package.json +6 -1
  32. package/src/bambu-native.ts +1 -1
  33. package/src/cad/contracts.ts +17 -7
  34. package/src/cad/examples/bag_clip.py +1 -0
  35. package/src/cad/examples/bistable_clicker.py +1 -0
  36. package/src/cad/examples/broom_grip.py +61 -0
  37. package/src/cad/examples/cable_clip.py +1 -0
  38. package/src/cad/examples/chainmail.py +1 -0
  39. package/src/cad/examples/desk_clamp_hook.py +91 -0
  40. package/src/cad/examples/desk_edge_cable_holder.py +55 -0
  41. package/src/cad/examples/drawer_divider.py +56 -0
  42. package/src/cad/examples/hinged_box.py +1 -0
  43. package/src/cad/examples/knurled_knob.py +1 -0
  44. package/src/cad/examples/loft_handle.py +1 -0
  45. package/src/cad/examples/organizer_tray.py +41 -0
  46. package/src/cad/examples/phone_stand.py +1 -0
  47. package/src/cad/examples/plant_pot.py +53 -0
  48. package/src/cad/examples/shelf_bracket.py +53 -0
  49. package/src/cad/examples/swept_hook.py +1 -0
  50. package/src/cad/examples/threaded_jar.py +1 -0
  51. package/src/cad/examples/trigger_capo.py +1 -0
  52. package/src/cad/examples/wall_hook.py +1 -0
  53. package/src/cad/examples.ts +13 -10
  54. package/src/cad/geometry.py +6 -0
  55. package/src/cad/serial.ts +4 -6
  56. package/src/cad-engine.ts +9 -3
  57. package/src/counterpart/info.ts +7 -1
  58. package/src/counterpart/remote.ts +1 -0
  59. package/src/counterpart/schemas.ts +3 -1
  60. package/src/counterpart/self-check.ts +164 -0
  61. package/src/index.ts +48 -20
  62. package/src/printers/bambu.ts +57 -24
  63. package/src/printers/report-merge.ts +48 -0
  64. package/src/safety/limits.ts +8 -0
  65. package/src/safety/print-file.ts +2 -2
  66. package/src/safety/printer-state.ts +13 -1
  67. package/src/stl/stl-manipulator.ts +75 -14
  68. package/src/studio-print-options.ts +33 -2
  69. package/src/tool-annotations.ts +1 -0
@@ -366,13 +366,16 @@ function trayRange(value: unknown, label: string): number | undefined {
366
366
  /** Dual-nozzle printers report one virtual external slot per nozzle, numbered as Bambu
367
367
  * Studio does (VIRTUAL_TRAY_MAIN_ID 255 = right/main nozzle, VIRTUAL_TRAY_DEPUTY_ID 254 =
368
368
  * left/deputy nozzle), so the requested tray selects its slot. Single-nozzle printers keep
369
- * requiring exactly one slot 254 report, then the legacy vt_tray field. */
369
+ * requiring exactly one external slot report, then the legacy vt_tray field. */
370
370
  function externalTray(raw: Record<string,any>, trayIndex: number, model: string): Record<string,any> | undefined {
371
371
  const slots = raw.vir_slot;
372
372
  const dualNozzle = isDualNozzleModel(model);
373
373
  if (Array.isArray(slots)) {
374
374
  const selected = slots.filter((slot:any) => Number(slot?.id) === trayIndex);
375
375
  if (selected.length === 1 && (dualNozzle || slots.length === 1)) return selected[0];
376
+ // X1C firmware 01.12 reports its single external slot as id 255 (ams_id 255, slot 0) while
377
+ // tray_now is 254. One external slot on a single-nozzle printer is unambiguous.
378
+ if (!dualNozzle && slots.length === 1 && [254,255].includes(Number(slots[0]?.id)) && [254,255].includes(trayIndex)) return slots[0];
376
379
  if (dualNozzle && selected.length === 0 && slots.length > 0) throw new Error(`External spool ${trayIndex} is not in the fresh per-nozzle report; cannot verify the selected material.`);
377
380
  if (slots.length > 0) throw new Error("External spool report is ambiguous for this nozzle; cannot verify the selected material.");
378
381
  }
@@ -526,3 +529,12 @@ export function externalStorageState(raw: unknown): ExternalStorageState {
526
529
  }
527
530
  return state;
528
531
  }
532
+
533
+ /** Studio DeviceManager.cpp at 926a7192574b: fun2 bit 0 advertises eMMC printing.
534
+ * Use only a fresh raw report at the caller. Reject malformed flags rather than
535
+ * stripping arbitrary characters as Studio's general-purpose parser does. */
536
+ export function internalPrintingSupported(raw: unknown): boolean {
537
+ if (!object(raw) || typeof raw.fun2 !== "string") return false;
538
+ const flags = raw.fun2.trim().replace(/^0x/i, "");
539
+ return /^[0-9a-f]+$/i.test(flags) && (parseInt(flags.slice(-1), 16) & 1) === 1;
540
+ }
@@ -10,7 +10,7 @@ import path from 'path';
10
10
  import { promisify } from 'util';
11
11
  import { EventEmitter } from 'events';
12
12
  import * as crypto from 'crypto';
13
- import { execFile } from 'child_process';
13
+ import { spawn, type ChildProcess } from 'child_process';
14
14
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
15
15
  import { listModelPlates } from '../counterpart/model-plates.js';
16
16
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
@@ -283,6 +283,33 @@ function slicerResultText(result: SlicerResult): string {
283
283
  ].filter((text): text is string => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
284
284
  }
285
285
 
286
+ /** What execFile hands its callback when the slicer fails: its message carries the command and stderr. */
287
+ type SlicerExit = Error & { code?: number | string | null; signal?: NodeJS.Signals | null; killed?: boolean; cmd?: string };
288
+ /** The output kept from each stream, as execFile's default maxBuffer; the rest is dropped, not failed. */
289
+ const SLICER_OUTPUT_LIMIT = 1024 * 1024;
290
+
291
+ /**
292
+ * execFile for the slicer, with detached passed through (execFile drops it): on POSIX the slicer then leads its own
293
+ * process group, so a cancel can stop the helpers it starts too. The callback gets what execFile's would.
294
+ */
295
+ function execSlicer(file: string, args: string[], env: NodeJS.ProcessEnv | undefined, detached: boolean,
296
+ callback: (error: SlicerExit | null, stdout: string, stderr: string) => void): ChildProcess {
297
+ // stdin is ignored, as execFile ends it: no slicer reads it.
298
+ const child = spawn(file, args, { ...(env ? { env } : {}), detached, stdio: ["ignore", "pipe", "pipe"] });
299
+ let stdout = "", stderr = "", settled = false;
300
+ const keep = (text: string, chunk: Buffer) => text.length >= SLICER_OUTPUT_LIMIT ? text : (text + chunk.toString("utf8")).slice(0, SLICER_OUTPUT_LIMIT);
301
+ child.stdout?.on("data", (chunk: Buffer) => { stdout = keep(stdout, chunk); });
302
+ child.stderr?.on("data", (chunk: Buffer) => { stderr = keep(stderr, chunk); });
303
+ const finish = (error: SlicerExit | null) => { if (!settled) { settled = true; callback(error, stdout, stderr); } };
304
+ child.on("error", error => finish(Object.assign(error, { cmd: [file, ...args].join(" ") })));
305
+ child.on("close", (code, signal) => {
306
+ if (code === 0 && !signal) return finish(null);
307
+ const cmd = [file, ...args].join(" ");
308
+ finish(Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, signal, killed: child.killed, cmd }));
309
+ });
310
+ return child;
311
+ }
312
+
286
313
  function describeSlicerFailure(
287
314
  error: { message: string; code?: unknown; signal?: unknown },
288
315
  stdout: string,
@@ -2074,10 +2101,17 @@ export class STLManipulator extends EventEmitter {
2074
2101
  const launch = await prepareSlicerLaunch(slicerType, this.tempDir);
2075
2102
  const stallSeconds = launch.stallSeconds;
2076
2103
  let stalled = false;
2104
+ let cancelled = false;
2077
2105
  // Execute the slicer
2078
2106
  try { await new Promise<void>((resolve, reject) => {
2079
- const process = execFile(slicerPath, args, launch.env ? { env: launch.env } : {}, (error, stdout, stderr) => {
2080
- if (stalled && error) {
2107
+ // POSIX: the slicer leads its own process group, so stopping it also stops the helpers it starts.
2108
+ const group = globalThis.process.platform !== 'win32';
2109
+ const process = execSlicer(slicerPath, args, launch.env, group, (error, stdout, stderr) => {
2110
+ if (cancelled) {
2111
+ // Settled once the slicer and every process sharing its output have gone, so its folder is removed after
2112
+ // nothing can write to it.
2113
+ reject(new Error("Slicing operation cancelled"));
2114
+ } else if (stalled && error) {
2081
2115
  reject(stalledSlicerError(slicerType, stallSeconds));
2082
2116
  } else if (error) {
2083
2117
  console.error(`Slicer Error: ${error.message}`);
@@ -2097,26 +2131,49 @@ export class STLManipulator extends EventEmitter {
2097
2131
  // process.stdout?.on('data', (data) => { console.error(`Slicer stdout: ${data}`); });
2098
2132
  // process.stderr?.on('data', (data) => { console.error(`Slicer stderr: ${data}`); });
2099
2133
 
2100
- // Check for cancellation periodically
2134
+ // Stops the slicer and, on POSIX, its whole process group (a group already gone is not an error).
2135
+ const stop = (signal: NodeJS.Signals) => {
2136
+ try {
2137
+ if (group && process.pid !== undefined) globalThis.process.kill(-process.pid, signal);
2138
+ else process.kill(signal);
2139
+ } catch (killError) {
2140
+ if ((killError as NodeJS.ErrnoException).code !== 'ESRCH') console.error(`Could not send ${signal} to the slicer:`, killError);
2141
+ }
2142
+ };
2143
+ // Check for cancellation periodically: the slicer is stopped, and the call settles when it has gone.
2144
+ let forceKill: NodeJS.Timeout | undefined;
2145
+ let abandon: NodeJS.Timeout | undefined;
2101
2146
  const checkCancel = setInterval(() => {
2102
2147
  if (!this.activeOperations.get(operationId)) {
2103
2148
  clearInterval(checkCancel);
2104
- try {
2105
- process.kill(); // Attempt to kill the slicer process
2149
+ cancelled = true;
2150
+ stop('SIGTERM');
2151
+ // A slicer or helper that ignores SIGTERM is killed outright rather than waited on. A helper outside the
2152
+ // group (daemonized, or any helper on Windows) can still hold the output pipes, so 'close' never comes:
2153
+ // a second later the pipes are let go and the cancel settles.
2154
+ forceKill = setTimeout(() => {
2155
+ stop('SIGKILL');
2156
+ abandon = setTimeout(() => {
2157
+ process.stdout?.destroy();
2158
+ process.stderr?.destroy();
2106
2159
  reject(new Error("Slicing operation cancelled"));
2107
- } catch (killError) {
2108
- console.error("Error attempting to kill slicer process:", killError);
2109
- reject(new Error("Slicing operation cancelled, but failed to kill process."));
2110
- }
2160
+ }, 1000);
2161
+ }, 5000);
2111
2162
  }
2112
2163
  }, 500);
2113
2164
 
2114
- process.on('exit', () => clearInterval(checkCancel));
2115
- process.on('error', () => clearInterval(checkCancel)); // Ensure interval cleared on process error too
2165
+ process.on('exit', () => {
2166
+ // Exit can precede a client cancel while a helper retains output pipes; polling runs until close.
2167
+ // A helper that outlived the slicer still holds its output; finish it so the call can settle.
2168
+ if (cancelled && group) stop('SIGKILL');
2169
+ });
2170
+ // The deadline runs until every process sharing the slicer's output has let go, not only the slicer.
2171
+ process.on('close', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
2172
+ process.on('error', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
2116
2173
  watchForStall(process, stallSeconds, () => {
2117
2174
  stalled = true;
2118
2175
  console.error(`${slicerType} used no CPU and wrote nothing for ${stallSeconds} s; stopping it as waiting on a dialog.`);
2119
- try { process.kill('SIGKILL'); } catch { /* its exit is reported through the callback */ }
2176
+ stop('SIGKILL');
2120
2177
  });
2121
2178
 
2122
2179
  }); } finally { await launch.cleanup(); }
@@ -2156,7 +2213,11 @@ export class STLManipulator extends EventEmitter {
2156
2213
  } catch (error) {
2157
2214
  console.error(`Slicing failed for ${stlFilePath}:`, error);
2158
2215
  // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
2159
- if (sliceDir) await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
2216
+ if (sliceDir) {
2217
+ await fs.promises.rm(sliceDir, { recursive: true, force: true }).then(
2218
+ () => console.error(`Removed the folder of the failed or cancelled slice: ${sliceDir}`),
2219
+ removeError => console.error(`Could not remove the folder of the failed or cancelled slice ${sliceDir}:`, removeError));
2220
+ }
2160
2221
  this.emit('operationError', {
2161
2222
  operationId,
2162
2223
  type: 'slice',
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The print options Bambu Studio's Send dialog sends, resolved the way it
3
- * resolves them, so every print route sends what Bambu's own Print button
4
- * would. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
3
+ * resolves them, for the vendor SDK. Direct routes report which options their verified
4
+ * wire format can carry; this does not establish SDK packet equivalence. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
5
5
  * the hidden-HMS and stage tables are pinned to:
6
6
  *
7
7
  * - SelectMachine.cpp:3344-3356 `set_print_config(bed_type,
@@ -199,3 +199,34 @@ export function usedNozzleCount(inspection: { usedFilamentPositions: number[]; f
199
199
  const nozzles = inspection.usedFilamentPositions.map(position => inspection.filamentNozzleIndices?.[position]).filter((value): value is number => Number.isInteger(value));
200
200
  return nozzles.length === inspection.usedFilamentPositions.length && nozzles.length ? new Set(nozzles).size : undefined;
201
201
  }
202
+
203
+ /** Report only verified direct-wire fields. A task boolean is not an SDK mode.
204
+ * null means this route does not transmit that option, not off/auto/unknown hardware state. */
205
+ export function directPrintOptionReport(caller: CallerPrintOptions, resolved: StudioPrintOptions, packet: Record<string, unknown>) {
206
+ const fields = {
207
+ bedLeveling: ["task_bed_leveling", "bed_leveling"],
208
+ flowCalibration: ["task_flow_cali", "flow_cali"],
209
+ vibrationCalibration: ["task_vibration_cali", "vibration_cali"],
210
+ layerInspect: ["task_layer_inspect", "layer_inspect"],
211
+ autoBedLeveling: ["auto_bed_leveling", "auto_bed_leveling"],
212
+ autoFlowCali: ["auto_flow_cali", "auto_flow_cali"],
213
+ autoOffsetCali: ["auto_offset_cali", "nozzle_offset_cali"],
214
+ extruderCaliManualMode: ["extruder_cali_manual_mode", "extrude_cali_manual_mode"],
215
+ } as const;
216
+ const requested: CallerPrintOptions = {};
217
+ const transmitted: Record<string, boolean | number | null> = {};
218
+ const unsupported: string[] = [];
219
+ for (const key of Object.keys(fields) as Array<keyof CallerPrintOptions>) {
220
+ const [sdk, wire] = fields[key];
221
+ if (caller[key] !== undefined) Object.assign(requested, { [key]: caller[key] });
222
+ const value = packet[wire];
223
+ transmitted[sdk] = typeof value === "boolean" || typeof value === "number" ? value : null;
224
+ if (caller[key] !== undefined && transmitted[sdk] === null) unsupported.push(key);
225
+ }
226
+ const omitted = Object.keys(transmitted).filter(key => transmitted[key] === null);
227
+ const warning = omitted.length
228
+ ? `Direct print options not transmitted: ${omitted.join(", ")}. Task booleans are not equivalent to Studio integer modes.` +
229
+ (unsupported.length ? ` Requested overrides unsupported by this route: ${unsupported.join(", ")}. Use a vendor bridge/native route that supports these options if required.` : "")
230
+ : undefined;
231
+ return { requested, resolved, transmitted, unsupported, ...(warning ? { warning } : {}) };
232
+ }
@@ -67,6 +67,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
67
67
  list_templates: READ_LOCAL,
68
68
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
69
69
  counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
70
+ counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
70
71
  counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
71
72
 
72
73
  // Local outputs in the server's temporary directory