bambu-printer-mcp 1.1.69 → 1.1.71

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 CHANGED
@@ -996,7 +996,7 @@ npx -y -p bambu-printer-mcp bambu-printer-mcp-native-setup
996
996
 
997
997
  Use the same package version as the server, for example `bambu-printer-mcp@1.2.3`; when the installation is missing or stale, the server's error names the exact command. The setup downloads the Linux plug-in that Bambu Studio itself installs, pinned to an exact version and SHA-256, and stores it with the certificates under `~/.config/bambu-printer-mcp/bambu-native` (`BAMBU_NATIVE_HOME` or `XDG_CONFIG_HOME` move it; set the same value for the server). The plug-in is not redistributed by this package, and Bambu Studio's own auto-updating copy is never used. The server finds the installation automatically and passes the plug-in and certificate paths to the helper. Rerun the setup with the server's package version after upgrading: the server refuses a helper built from another version. Only missing or changed files are downloaded again. The setup then loads the plug-in once, offline, so missing system libraries are reported during installation rather than on a stop command. `--verify` repeats these checks without network access. On Linux the server uses only this managed helper or `BAMBU_NATIVE_HELPER`; a package-local `npm run build:native` binary is not used.
998
998
 
999
- `--check-update` asks Bambu's plug-in service for the newest Linux plug-in and compares the `PrintParams` layout in the matching Bambu Studio header with the helper. It reports only: the setup never installs an unpinned plug-in, because a changed layout would send wrong print parameters. A pin is raised by a package release after the check passes and a hardware test.
999
+ `--check-update` asks Bambu's plug-in service for the newest Linux plug-in and compares the `PrintParams` layout in the matching Bambu Studio header with the helper. It reports only: the setup never installs an unpinned plug-in, because a changed layout would send wrong print parameters. A pin is raised by a package release after the check passes and the offered archive and required libraries are checksum-verified. Offline plug-in loading and physical X2D printing are separate validation steps, reported with each release.
1000
1000
 
1001
1001
  Once the helper, plug-in and certificates are installed, X2D printing, upload and controls use the same routing, safety checks and authorization handshake described for macOS above. On Linux, stop and heater-off go out over the native route and MQTT at the same time, so a stuck helper cannot delay them. MQTT is sent again once every older print or heating helper for that printer has exited and the immediate MQTT attempt has settled, so none can dispatch after it; either the native route or that later MQTT send succeeding counts, and the result lists all sends under `routes`. Each MQTT send gives up after 15 seconds (`BAMBU_EMERGENCY_MQTT_TIMEOUT_MS`), so an unreachable MQTT connection cannot hold back a stop the native route already sent. A connection completing after that deadline cannot dispatch its expired command; an already queued MQTT publish is discarded by force-closing and invalidating that client. A repeated stop or heater-off is harmless. macOS keeps its native-only route. On both systems a print goes to the printer's SD card or USB stick when the printer reports one ready, so it can be reprinted from the printer and archived by tools that read the card; otherwise it goes to internal storage (eMMC), as Bambu Studio's Print button always does. `BAMBU_NATIVE_TRY_EMMC_PRINT=1` (or `0`) forces the choice. The server accepts only the pinned plug-in checksums; `BAMBU_NATIVE_ALLOW_UNPINNED_PLUGIN=1` is a trusted override for testing another build at your own risk. Without a complete installation, Linux keeps its previous behavior: X2D status and slicing work, stop, pause and heater-off use MQTT, and native print requests name the setup command before contacting the printer. Bambu publishes the Linux plug-in for x86-64 only; other architectures keep the MQTT behavior.
1002
1002
 
@@ -73,12 +73,12 @@ export declare const BAMBU_NATIVE_CERTIFICATES: readonly ["slicer_base64.cer", "
73
73
  */
74
74
  export declare const BAMBU_NATIVE_PLUGIN_LIBRARIES: readonly ["libbambu_networking.so", "libBambuSource.so"];
75
75
  /**
76
- * The only Linux plug-in build whose PrintParams layout matches the helper
77
- * (Bambu Studio v02.08.02.61, network agent 02.08.02.54). The setup installs
76
+ * The pinned Linux plug-in build whose PrintParams layout matches the helper
77
+ * (Bambu Studio v02.09.01.70, network agent 02.09.01.54). The setup installs
78
78
  * exactly these files and the server refuses anything else.
79
79
  */
80
80
  export declare const BAMBU_NATIVE_PINNED_PLUGIN: Readonly<{
81
- version: "02.08.02.54";
81
+ version: "02.09.01.54";
82
82
  sha256: Readonly<Record<"libbambu_networking.so" | "libBambuSource.so", string>>;
83
83
  }>;
84
84
  /** Layout shared by the Linux setup script, the server and the helper's environment. */
@@ -39,14 +39,14 @@ export const BAMBU_NATIVE_CERTIFICATES = ["slicer_base64.cer", "printer.cer"];
39
39
  */
40
40
  export const BAMBU_NATIVE_PLUGIN_LIBRARIES = ["libbambu_networking.so", "libBambuSource.so"];
41
41
  /**
42
- * The only Linux plug-in build whose PrintParams layout matches the helper
43
- * (Bambu Studio v02.08.02.61, network agent 02.08.02.54). The setup installs
42
+ * The pinned Linux plug-in build whose PrintParams layout matches the helper
43
+ * (Bambu Studio v02.09.01.70, network agent 02.09.01.54). The setup installs
44
44
  * exactly these files and the server refuses anything else.
45
45
  */
46
46
  export const BAMBU_NATIVE_PINNED_PLUGIN = Object.freeze({
47
- version: "02.08.02.54",
47
+ version: "02.09.01.54",
48
48
  sha256: Object.freeze({
49
- "libbambu_networking.so": "bba49709c8dea14ba70251b43965646c0a5e2cde8fd133c64f764d425691bdf2",
49
+ "libbambu_networking.so": "a3d3fb6e6568cbf62a81c88248f4ddfee90ecaa47685d5156ada411271aa5ad3",
50
50
  "libBambuSource.so": "4e05f16fa02740fd12f0040b9efc3e70d43446c7a1a877c6a3926ef0758ca7db",
51
51
  }),
52
52
  });
package/dist/index.js CHANGED
@@ -4016,6 +4016,8 @@ class BambuPrinterMCPServer {
4016
4016
  console.warn("Could not resolve live printer filaments for slicing:", filamentError);
4017
4017
  }
4018
4018
  }
4019
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4020
+ sliceBambuOptions.signal = extra.signal;
4019
4021
  const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
4020
4022
  printerPreset, sliceBambuOptions);
4021
4023
  await progressNotifications;
@@ -630,7 +630,11 @@ async function writeTemp(tempDir, kind, leafName, data) {
630
630
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
631
631
  const filename = `flat-${kind}-${safe}-${hash}.json`;
632
632
  const out = path.join(tempDir, filename);
633
- await fs.writeFile(out, serialized, "utf8");
633
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
634
+ // rename it into place, so a reader never sees it truncated or half-written.
635
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
636
+ await fs.writeFile(partial, serialized, "utf8");
637
+ await fs.rename(partial, out);
634
638
  return out;
635
639
  }
636
640
  /* -------------------------------------------------------------------------- */
@@ -10,6 +10,8 @@ const SUPPORTED_OPTIONS = new Set([
10
10
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
11
11
  // Written into the uploaded process preset before the request, not sent as API options.
12
12
  'processOverrides',
13
+ // The request's cancellation, honoured through isCancelled; never sent.
14
+ 'signal',
13
15
  ]);
14
16
  function configuration() {
15
17
  let url;
@@ -28,6 +28,8 @@ export type SlicerType = typeof SLICER_TYPES[number];
28
28
  export declare function normalizeSlicerType(rawSlicerType: string): SlicerType;
29
29
  export declare function isBambuCompatibleSlicer(slicerType: SlicerType): boolean;
30
30
  export interface BambuSliceOptions {
31
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
32
+ signal?: AbortSignal;
31
33
  uptodate?: boolean;
32
34
  repetitions?: number;
33
35
  orient?: boolean;
@@ -82,6 +84,11 @@ export declare class STLManipulator extends EventEmitter {
82
84
  * Generate a unique operation ID
83
85
  */
84
86
  private generateOperationId;
87
+ /**
88
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
89
+ * its slice (callers print from it); older slice folders are removed as new slices start.
90
+ */
91
+ private newSliceFolder;
85
92
  private getAvailableProfileRoots;
86
93
  private findProfileFile;
87
94
  private buildFilamentIdIndex;
@@ -17,6 +17,8 @@ import { applyProcessOverrides } from '../slicer/process-overrides.js';
17
17
  import { profileJsonFiles } from '../slicer/profile-files.js';
18
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
19
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
20
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
21
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
20
22
  const readFileAsync = promisify(fs.readFile);
21
23
  const writeFileAsync = promisify(fs.writeFile);
22
24
  const BAMBU_PROFILE_ROOTS = [
@@ -219,6 +221,24 @@ export class STLManipulator extends EventEmitter {
219
221
  generateOperationId() {
220
222
  return crypto.randomUUID();
221
223
  }
224
+ /**
225
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
226
+ * its slice (callers print from it); older slice folders are removed as new slices start.
227
+ */
228
+ async newSliceFolder(operationId) {
229
+ const root = path.join(this.tempDir, 'slices');
230
+ await fs.promises.mkdir(root, { recursive: true });
231
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
232
+ for (const name of await fs.promises.readdir(root).catch(() => [])) {
233
+ const folder = path.join(root, name);
234
+ const info = await fs.promises.stat(folder).catch(() => undefined);
235
+ if (info?.isDirectory() && info.mtimeMs < cutoff)
236
+ await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
237
+ }
238
+ const folder = path.join(root, operationId);
239
+ await fs.promises.mkdir(folder);
240
+ return folder;
241
+ }
222
242
  getAvailableProfileRoots() {
223
243
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
224
244
  return [
@@ -307,7 +327,11 @@ export class STLManipulator extends EventEmitter {
307
327
  const serialized = JSON.stringify(value, null, 2);
308
328
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
309
329
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
310
- fs.writeFileSync(outPath, serialized);
330
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
331
+ // rename it into place, so a reader never sees it truncated or half-written.
332
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
333
+ fs.writeFileSync(partial, serialized);
334
+ fs.renameSync(partial, outPath);
311
335
  return outPath;
312
336
  }
313
337
  async resolveBambuLikeSettingsBundle(outputBase, slicerType, slicerProfile, printerPreset, bambuOptions, activeProfilesRoot, preserveOrcaExtrusionMode = false) {
@@ -1398,6 +1422,14 @@ export class STLManipulator extends EventEmitter {
1398
1422
  async sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1399
1423
  const operationId = this.generateOperationId();
1400
1424
  this.activeOperations.set(operationId, true);
1425
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1426
+ const signal = bambuOptions?.signal;
1427
+ const cancel = () => { if (this.activeOperations.has(operationId))
1428
+ this.activeOperations.set(operationId, false); };
1429
+ if (signal?.aborted) {
1430
+ this.activeOperations.delete(operationId);
1431
+ throw new Error("Slicing operation cancelled");
1432
+ }
1401
1433
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1402
1434
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
1403
1435
  }
@@ -1414,7 +1446,10 @@ export class STLManipulator extends EventEmitter {
1414
1446
  let cliResult;
1415
1447
  const orcaTemporaryDirectories = [];
1416
1448
  const temporaryFiles = [];
1449
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1450
+ let sliceDir;
1417
1451
  try {
1452
+ signal?.addEventListener('abort', cancel, { once: true });
1418
1453
  if (progressCallback)
1419
1454
  progressCallback(0, `Starting slicing with ${slicerType}...`);
1420
1455
  switch (slicerType) {
@@ -1463,7 +1498,13 @@ export class STLManipulator extends EventEmitter {
1463
1498
  throw new Error('Remote slicing process profile does not exist.');
1464
1499
  }
1465
1500
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1466
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1501
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1502
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1503
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1504
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1505
+ const bambuOutputPath = remote
1506
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1507
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1467
1508
  const outputDir = path.dirname(bambuOutputPath);
1468
1509
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1469
1510
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -1704,6 +1745,9 @@ export class STLManipulator extends EventEmitter {
1704
1745
  }
1705
1746
  catch (error) {
1706
1747
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1748
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
1749
+ if (sliceDir)
1750
+ await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
1707
1751
  this.emit('operationError', {
1708
1752
  operationId,
1709
1753
  type: 'slice',
@@ -1712,6 +1756,7 @@ export class STLManipulator extends EventEmitter {
1712
1756
  throw error;
1713
1757
  }
1714
1758
  finally {
1759
+ signal?.removeEventListener('abort', cancel);
1715
1760
  this.activeOperations.delete(operationId);
1716
1761
  for (const file of temporaryFiles) {
1717
1762
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.69",
3
+ "version": "1.1.71",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -21,15 +21,15 @@ const BUILD_SCRIPT = path.join(PACKAGE_ROOT, "scripts/build-bambu-native.sh");
21
21
  const DOWNLOAD_TIMEOUT_MS = 300_000;
22
22
  const MAX_DOWNLOAD_BYTES = 128 * 1024 * 1024;
23
23
 
24
- // Bambu Studio v02.08.02.61 declares network agent 02.08.02.54 with the same
24
+ // Bambu Studio v02.09.01.70 declares network agent 02.09.01.54 with the same
25
25
  // PrintParams layout as native/bambu-native-print.cpp. The server owns the
26
26
  // version and library checksums; this adds where to download them from.
27
27
  export const PINNED = Object.freeze({
28
- studioTag: "v02.08.02.61",
28
+ studioTag: "v02.09.01.70",
29
29
  plugin: Object.freeze({
30
30
  version: BAMBU_NATIVE_PINNED_PLUGIN.version,
31
- url: `https://public-cdn.bblmw.com/upgrade/studio/plugins/${BAMBU_NATIVE_PINNED_PLUGIN.version}/f1a94b8828/linux_${BAMBU_NATIVE_PINNED_PLUGIN.version}.zip`,
32
- sha256: "a7ea8ccec85ab5a7b8959a5697f7be957d58da82e67aad1cb0ad9b3cdf5baed6",
31
+ url: `https://public-cdn.bblmw.com/upgrade/studio/plugins/${BAMBU_NATIVE_PINNED_PLUGIN.version}/61dbe71463/linux_${BAMBU_NATIVE_PINNED_PLUGIN.version}.zip`,
32
+ sha256: "fffba3ebfd919dd5154ba613b6e3b3ab759a533b3f3c39841519030e7cc9b56a",
33
33
  // The networking plug-in opens the eMMC file tunnel through libBambuSource
34
34
  // in its own directory; without it uploads fail with -4.
35
35
  members: BAMBU_NATIVE_PINNED_PLUGIN.sha256,
@@ -117,14 +117,14 @@ export const BAMBU_NATIVE_CERTIFICATES = ["slicer_base64.cer", "printer.cer"] as
117
117
  export const BAMBU_NATIVE_PLUGIN_LIBRARIES = ["libbambu_networking.so", "libBambuSource.so"] as const;
118
118
 
119
119
  /**
120
- * The only Linux plug-in build whose PrintParams layout matches the helper
121
- * (Bambu Studio v02.08.02.61, network agent 02.08.02.54). The setup installs
120
+ * The pinned Linux plug-in build whose PrintParams layout matches the helper
121
+ * (Bambu Studio v02.09.01.70, network agent 02.09.01.54). The setup installs
122
122
  * exactly these files and the server refuses anything else.
123
123
  */
124
124
  export const BAMBU_NATIVE_PINNED_PLUGIN = Object.freeze({
125
- version: "02.08.02.54",
125
+ version: "02.09.01.54",
126
126
  sha256: Object.freeze({
127
- "libbambu_networking.so": "bba49709c8dea14ba70251b43965646c0a5e2cde8fd133c64f764d425691bdf2",
127
+ "libbambu_networking.so": "a3d3fb6e6568cbf62a81c88248f4ddfee90ecaa47685d5156ada411271aa5ad3",
128
128
  "libBambuSource.so": "4e05f16fa02740fd12f0040b9efc3e70d43446c7a1a877c6a3926ef0758ca7db",
129
129
  } as Record<(typeof BAMBU_NATIVE_PLUGIN_LIBRARIES)[number], string>),
130
130
  });
package/src/index.ts CHANGED
@@ -4644,6 +4644,8 @@ class BambuPrinterMCPServer {
4644
4644
  }
4645
4645
  }
4646
4646
 
4647
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4648
+ sliceBambuOptions.signal = extra.signal;
4647
4649
  const sliced = await this.stlManipulator.sliceSTLWithResult(
4648
4650
  String(args.stl_path), slicerType, slicerPath,
4649
4651
  activeSlicerProfile,
@@ -793,7 +793,11 @@ async function writeTemp(
793
793
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
794
794
  const filename = `flat-${kind}-${safe}-${hash}.json`;
795
795
  const out = path.join(tempDir, filename);
796
- await fs.writeFile(out, serialized, "utf8");
796
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
797
+ // rename it into place, so a reader never sees it truncated or half-written.
798
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
799
+ await fs.writeFile(partial, serialized, "utf8");
800
+ await fs.rename(partial, out);
797
801
  return out;
798
802
  }
799
803
 
@@ -12,6 +12,8 @@ const SUPPORTED_OPTIONS = new Set([
12
12
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
13
13
  // Written into the uploaded process preset before the request, not sent as API options.
14
14
  'processOverrides',
15
+ // The request's cancellation, honoured through isCancelled; never sent.
16
+ 'signal',
15
17
  ]);
16
18
 
17
19
  function configuration(): { base: string; headers: Record<string, string>; mode: string; timeout: number } {
@@ -18,6 +18,8 @@ import { profileJsonFiles } from '../slicer/profile-files.js';
18
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
19
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
20
20
 
21
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
22
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
21
23
  const readFileAsync = promisify(fs.readFile);
22
24
  const writeFileAsync = promisify(fs.writeFile);
23
25
  const BAMBU_PROFILE_ROOTS = [
@@ -164,6 +166,8 @@ function configuredBambuProfileDirs(): string[] {
164
166
 
165
167
  // Bambu-compatible slicer CLI flags exposed via the slice_stl tool
166
168
  export interface BambuSliceOptions {
169
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
170
+ signal?: AbortSignal;
167
171
  uptodate?: boolean; // --uptodate: update 3MF configs to latest presets
168
172
  repetitions?: number; // STL: --clone-objects N; 3MF: --repetitions N on the selected plate
169
173
  orient?: boolean; // --orient 1: auto-orient for printability
@@ -342,6 +346,24 @@ export class STLManipulator extends EventEmitter {
342
346
  return crypto.randomUUID();
343
347
  }
344
348
 
349
+ /**
350
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
351
+ * its slice (callers print from it); older slice folders are removed as new slices start.
352
+ */
353
+ private async newSliceFolder(operationId: string): Promise<string> {
354
+ const root = path.join(this.tempDir, 'slices');
355
+ await fs.promises.mkdir(root, { recursive: true });
356
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
357
+ for (const name of await fs.promises.readdir(root).catch(() => [] as string[])) {
358
+ const folder = path.join(root, name);
359
+ const info = await fs.promises.stat(folder).catch(() => undefined);
360
+ if (info?.isDirectory() && info.mtimeMs < cutoff) await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
361
+ }
362
+ const folder = path.join(root, operationId);
363
+ await fs.promises.mkdir(folder);
364
+ return folder;
365
+ }
366
+
345
367
  private getAvailableProfileRoots(): string[] {
346
368
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
347
369
  return [
@@ -456,7 +478,11 @@ export class STLManipulator extends EventEmitter {
456
478
  const serialized = JSON.stringify(value, null, 2);
457
479
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
458
480
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
459
- fs.writeFileSync(outPath, serialized);
481
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
482
+ // rename it into place, so a reader never sees it truncated or half-written.
483
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
484
+ fs.writeFileSync(partial, serialized);
485
+ fs.renameSync(partial, outPath);
460
486
  return outPath;
461
487
  }
462
488
 
@@ -1806,6 +1832,13 @@ export class STLManipulator extends EventEmitter {
1806
1832
  ): Promise<SliceOutput> {
1807
1833
  const operationId = this.generateOperationId();
1808
1834
  this.activeOperations.set(operationId, true);
1835
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1836
+ const signal = bambuOptions?.signal;
1837
+ const cancel = () => { if (this.activeOperations.has(operationId)) this.activeOperations.set(operationId, false); };
1838
+ if (signal?.aborted) {
1839
+ this.activeOperations.delete(operationId);
1840
+ throw new Error("Slicing operation cancelled");
1841
+ }
1809
1842
 
1810
1843
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1811
1844
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
@@ -1826,8 +1859,11 @@ export class STLManipulator extends EventEmitter {
1826
1859
  let cliResult: CliResultSource | undefined;
1827
1860
  const orcaTemporaryDirectories: string[] = [];
1828
1861
  const temporaryFiles: string[] = [];
1862
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1863
+ let sliceDir: string | undefined;
1829
1864
 
1830
1865
  try {
1866
+ signal?.addEventListener('abort', cancel, { once: true });
1831
1867
  if (progressCallback) progressCallback(0, `Starting slicing with ${slicerType}...`);
1832
1868
 
1833
1869
  switch (slicerType) {
@@ -1876,7 +1912,13 @@ export class STLManipulator extends EventEmitter {
1876
1912
  if (slicerProfile && !fs.existsSync(slicerProfile)) throw new Error('Remote slicing process profile does not exist.');
1877
1913
  }
1878
1914
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1879
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1915
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1916
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1917
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1918
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1919
+ const bambuOutputPath = remote
1920
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1921
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1880
1922
  const outputDir = path.dirname(bambuOutputPath);
1881
1923
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1882
1924
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -2118,6 +2160,8 @@ export class STLManipulator extends EventEmitter {
2118
2160
  return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
2119
2161
  } catch (error) {
2120
2162
  console.error(`Slicing failed for ${stlFilePath}:`, error);
2163
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
2164
+ if (sliceDir) await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
2121
2165
  this.emit('operationError', {
2122
2166
  operationId,
2123
2167
  type: 'slice',
@@ -2125,6 +2169,7 @@ export class STLManipulator extends EventEmitter {
2125
2169
  });
2126
2170
  throw error;
2127
2171
  } finally {
2172
+ signal?.removeEventListener('abort', cancel);
2128
2173
  this.activeOperations.delete(operationId);
2129
2174
  for (const file of temporaryFiles) {
2130
2175
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));