bambu-printer-mcp 1.1.83 → 1.1.84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/refusal.d.ts +11 -4
- package/dist/refusal.js +14 -4
- package/dist/slicer/slicer-launch.d.ts +34 -0
- package/dist/slicer/slicer-launch.js +145 -0
- package/dist/stl/stl-manipulator.js +55 -33
- package/package.json +1 -1
- package/src/refusal.ts +15 -4
- package/src/slicer/slicer-launch.ts +149 -0
- package/src/stl/stl-manipulator.ts +17 -4
package/README.md
CHANGED
|
@@ -1186,6 +1186,8 @@ Slice an STL or 3MF file using an external slicer and return the path to the out
|
|
|
1186
1186
|
|
|
1187
1187
|
`slicer_path` and `slicer_profile` fall back to the `SLICER_PATH` and `SLICER_PROFILE` environment variables when omitted. Per-call `slicer_path` overrides require `MCP_ALLOW_EXECUTABLE_ARG=1`.
|
|
1188
1188
|
|
|
1189
|
+
**A slicer that waits on a window:** on macOS each Bambu Studio, OrcaSlicer or FULU slice runs with an empty home folder of its own (`CFFIXED_USER_HOME` under `TEMP_DIR`), so macOS's "reopen windows?" question after a slicer crash can't stop it. On macOS, a Bambu-compatible slicer that still uses no CPU and writes nothing for `SLICER_STALL_SECONDS` (default 20, 0 turns it off) is stopped, and the error's `structuredContent.code` is `slicer-waiting-on-dialog`. Nothing is sent to the printer. Open the slicer once, answer what it shows, quit it and slice again.
|
|
1190
|
+
|
|
1189
1191
|
You can provide either `template_3mf_path` or `template_name` when you want to slice from a saved template. `template_name` resolves through the local template registry directory configured for the server.
|
|
1190
1192
|
|
|
1191
1193
|
For printing on a Bambu printer, the recommended workflow is: export a sliced 3MF from your selected Bambu-compatible slicer, then pass that output path to `print_3mf`.
|
package/dist/refusal.d.ts
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A
|
|
3
|
-
* Counterpart
|
|
4
|
-
*
|
|
2
|
+
* A refusal with a stable code, returned as structuredContent.code on the tool's error, so clients such as
|
|
3
|
+
* Counterpart act on the code instead of matching the message (whose words, HMS numbers, firmware and slicer
|
|
4
|
+
* details change). None of them starts a print. Whether a print command was sent is dispatch truth: clients
|
|
5
|
+
* read structuredContent.printOutcome for it, never these codes or the message.
|
|
5
6
|
*
|
|
6
7
|
* - printer-command-rejected: the printer refused the print command itself (for Bambu, HMS 0500-0500-0001-0007,
|
|
7
8
|
* MQTT command verification); the file was uploaded and the command sent, but nothing is printing.
|
|
8
9
|
* - printer-not-ready: the printer isn't in a state that can start a print (busy, paused, failed, unknown).
|
|
9
10
|
* - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
|
|
11
|
+
* - slicer-waiting-on-dialog: the slicer stopped working (no CPU, no output) as it does while a window waits for an
|
|
12
|
+
* answer, and was stopped; nothing was sliced or sent. Not the slicer's verdict on the model: no slicer_report.
|
|
10
13
|
*/
|
|
11
|
-
export declare const REFUSAL_CODES: readonly ["printer-command-rejected", "printer-not-ready", "printer-upload-failed"];
|
|
14
|
+
export declare const REFUSAL_CODES: readonly ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog"];
|
|
12
15
|
export type RefusalCode = (typeof REFUSAL_CODES)[number];
|
|
13
16
|
export declare class PrinterRefusal extends Error {
|
|
14
17
|
readonly code: RefusalCode;
|
|
15
18
|
constructor(code: RefusalCode, message: string);
|
|
16
19
|
}
|
|
20
|
+
/** A slicer stopped because it waited on a dialog (src/slicer/slicer-launch.ts); carries slicer-waiting-on-dialog. */
|
|
21
|
+
export declare class SlicerStalled extends PrinterRefusal {
|
|
22
|
+
constructor(message: string);
|
|
23
|
+
}
|
|
17
24
|
/** counterpart/1 dispatch-tool errors describe dispatch truth independently of firmware-specific codes. */
|
|
18
25
|
export type PrintOutcome = "not-sent" | "unknown" | "rejected";
|
|
19
26
|
export declare function withPrintDispatch<T>(run: () => T): T;
|
package/dist/refusal.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
/**
|
|
3
|
-
* A
|
|
4
|
-
* Counterpart
|
|
5
|
-
*
|
|
3
|
+
* A refusal with a stable code, returned as structuredContent.code on the tool's error, so clients such as
|
|
4
|
+
* Counterpart act on the code instead of matching the message (whose words, HMS numbers, firmware and slicer
|
|
5
|
+
* details change). None of them starts a print. Whether a print command was sent is dispatch truth: clients
|
|
6
|
+
* read structuredContent.printOutcome for it, never these codes or the message.
|
|
6
7
|
*
|
|
7
8
|
* - printer-command-rejected: the printer refused the print command itself (for Bambu, HMS 0500-0500-0001-0007,
|
|
8
9
|
* MQTT command verification); the file was uploaded and the command sent, but nothing is printing.
|
|
9
10
|
* - printer-not-ready: the printer isn't in a state that can start a print (busy, paused, failed, unknown).
|
|
10
11
|
* - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
|
|
12
|
+
* - slicer-waiting-on-dialog: the slicer stopped working (no CPU, no output) as it does while a window waits for an
|
|
13
|
+
* answer, and was stopped; nothing was sliced or sent. Not the slicer's verdict on the model: no slicer_report.
|
|
11
14
|
*/
|
|
12
|
-
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed"];
|
|
15
|
+
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog"];
|
|
13
16
|
export class PrinterRefusal extends Error {
|
|
14
17
|
constructor(code, message) {
|
|
15
18
|
super(message);
|
|
@@ -17,6 +20,13 @@ export class PrinterRefusal extends Error {
|
|
|
17
20
|
this.name = "PrinterRefusal";
|
|
18
21
|
}
|
|
19
22
|
}
|
|
23
|
+
/** A slicer stopped because it waited on a dialog (src/slicer/slicer-launch.ts); carries slicer-waiting-on-dialog. */
|
|
24
|
+
export class SlicerStalled extends PrinterRefusal {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super("slicer-waiting-on-dialog", message);
|
|
27
|
+
this.name = "SlicerStalled";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
20
30
|
const printDispatch = new AsyncLocalStorage();
|
|
21
31
|
export function withPrintDispatch(run) {
|
|
22
32
|
return printDispatch.run({ attempted: false }, run);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
import { SlicerStalled } from "../refusal.js";
|
|
3
|
+
export interface SlicerLaunch {
|
|
4
|
+
/** The environment for the slicer process (undefined: inherit this server's). */
|
|
5
|
+
env?: NodeJS.ProcessEnv;
|
|
6
|
+
/** Seconds without CPU or output after which the slice is stopped and reported (watchForStall); 0: never. */
|
|
7
|
+
stallSeconds: number;
|
|
8
|
+
/** Removes this launch's home folder. */
|
|
9
|
+
cleanup(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The launch for one slice. On macOS a Bambu-compatible CLI gets its own empty home folder (always: an inherited
|
|
13
|
+
* CFFIXED_USER_HOME is replaced, since a home that held a stalled slice may hold the history that stalled it), and
|
|
14
|
+
* is watched for stalls. A new folder each slice, not one kept in the data folder, so no crash history can build up
|
|
15
|
+
* in it. Elsewhere nothing changes: no AppKit, and a slicer there may run behind a wrapper (AppImage, Flatpak) whose
|
|
16
|
+
* own CPU says nothing about the slicer's.
|
|
17
|
+
*/
|
|
18
|
+
export declare function prepareSlicerLaunch(slicerType: string, tempDir: string, platform?: NodeJS.Platform): Promise<SlicerLaunch>;
|
|
19
|
+
/**
|
|
20
|
+
* Seconds a slicer may use no CPU and write nothing before it is treated as waiting on a dialog
|
|
21
|
+
* (SLICER_STALL_SECONDS, 1-3600; 0 turns the check off). A slice is never idle that long: it computes or writes.
|
|
22
|
+
*/
|
|
23
|
+
export declare function slicerStallSeconds(raw?: string | undefined): number;
|
|
24
|
+
/** "[[dd-]hh:]mm:ss[.cc]" from ps -o time= (macOS: m:ss.cc; Linux: [dd-]hh:mm:ss), in seconds. */
|
|
25
|
+
export declare function parseCpuTime(text: string): number | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Calls onStall once when the child has used no CPU and written nothing to stdout or stderr for `seconds`, counted
|
|
28
|
+
* in consecutive polls (so a Mac that sleeps meanwhile doesn't count the sleep). It starts counting only after the
|
|
29
|
+
* child has shown it is running (output or CPU), and does nothing where CPU time can't be read. Returns a stop
|
|
30
|
+
* function; it also stops when the child exits.
|
|
31
|
+
*/
|
|
32
|
+
export declare function watchForStall(child: ChildProcess, seconds: number, onStall: () => void): () => void;
|
|
33
|
+
/** The failure for a slicer stopped by watchForStall. */
|
|
34
|
+
export declare function stalledSlicerError(slicerType: string, seconds: number): SlicerStalled;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { SlicerStalled } from "../refusal.js";
|
|
5
|
+
/**
|
|
6
|
+
* How a Bambu-compatible slicer CLI is launched so that it can't block on per-user AppKit launch state, and how a
|
|
7
|
+
* slicer that blocks anyway is noticed.
|
|
8
|
+
*
|
|
9
|
+
* Bambu Studio's command line opens a hidden GLFW window to draw plate thumbnails for --export-3mf (Bambu Studio
|
|
10
|
+
* 02.08.02.61 src/BambuStudio.cpp:6231-6259; OrcaSlicer and FULU's OrcaSlicer-bambulab inherit that code). The
|
|
11
|
+
* window starts NSApplication, and AppKit's window restoration then reads the person's crash history from
|
|
12
|
+
* ~/Library/Application Support/CrashReporter/<executable>_<hardware UUID>.plist. When that history says the app
|
|
13
|
+
* crashed while restoring windows, AppKit raises its modal "reopen windows?" alert, and the slicer waits on it at 0%
|
|
14
|
+
* CPU forever. Stopping it never answers the alert, so the next slice waits again.
|
|
15
|
+
*
|
|
16
|
+
* The CLI reads nothing else from the home folder: it takes its profiles from its own bundle (resources_dir(),
|
|
17
|
+
* BambuStudio.cpp:8325-8328) or from the files this server passes, its temporary files from TMPDIR
|
|
18
|
+
* (BambuStudio.cpp:1558-1559), and it sets no data directory unless --datadir is given (BambuStudio.cpp:8363-8367).
|
|
19
|
+
* So each slice gets a fresh, empty home of its own through CFFIXED_USER_HOME, under this server's TEMP_DIR, which
|
|
20
|
+
* AppKit honours for that history. Its preferences still come from the person's own (cfprefsd ignores
|
|
21
|
+
* CFFIXED_USER_HOME) and HOME is unchanged, so nothing else the slicer or this server reads moves.
|
|
22
|
+
*/
|
|
23
|
+
/** Slicer types launched from a local Bambu-compatible CLI binary. */
|
|
24
|
+
const BAMBU_CLI_TYPES = new Set(["bambustudio", "orcaslicer", "orcaslicer-bambulab"]);
|
|
25
|
+
/**
|
|
26
|
+
* The launch for one slice. On macOS a Bambu-compatible CLI gets its own empty home folder (always: an inherited
|
|
27
|
+
* CFFIXED_USER_HOME is replaced, since a home that held a stalled slice may hold the history that stalled it), and
|
|
28
|
+
* is watched for stalls. A new folder each slice, not one kept in the data folder, so no crash history can build up
|
|
29
|
+
* in it. Elsewhere nothing changes: no AppKit, and a slicer there may run behind a wrapper (AppImage, Flatpak) whose
|
|
30
|
+
* own CPU says nothing about the slicer's.
|
|
31
|
+
*/
|
|
32
|
+
export async function prepareSlicerLaunch(slicerType, tempDir, platform = process.platform) {
|
|
33
|
+
if (!BAMBU_CLI_TYPES.has(slicerType) || platform !== "darwin")
|
|
34
|
+
return { stallSeconds: 0, cleanup: async () => { } };
|
|
35
|
+
await fs.promises.mkdir(tempDir, { recursive: true });
|
|
36
|
+
const home = await fs.promises.mkdtemp(path.join(tempDir, "slicer-home-"));
|
|
37
|
+
return {
|
|
38
|
+
env: { ...process.env, CFFIXED_USER_HOME: home },
|
|
39
|
+
stallSeconds: slicerStallSeconds(),
|
|
40
|
+
cleanup: () => fs.promises.rm(home, { recursive: true, force: true }).catch(() => undefined),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const DEFAULT_STALL_SECONDS = 20;
|
|
44
|
+
/**
|
|
45
|
+
* Seconds a slicer may use no CPU and write nothing before it is treated as waiting on a dialog
|
|
46
|
+
* (SLICER_STALL_SECONDS, 1-3600; 0 turns the check off). A slice is never idle that long: it computes or writes.
|
|
47
|
+
*/
|
|
48
|
+
export function slicerStallSeconds(raw = process.env.SLICER_STALL_SECONDS) {
|
|
49
|
+
const text = raw?.trim();
|
|
50
|
+
if (!text)
|
|
51
|
+
return DEFAULT_STALL_SECONDS;
|
|
52
|
+
const value = Number(text);
|
|
53
|
+
return Number.isFinite(value) && value >= 0 && value <= 3600 ? value : DEFAULT_STALL_SECONDS;
|
|
54
|
+
}
|
|
55
|
+
/** "[[dd-]hh:]mm:ss[.cc]" from ps -o time= (macOS: m:ss.cc; Linux: [dd-]hh:mm:ss), in seconds. */
|
|
56
|
+
export function parseCpuTime(text) {
|
|
57
|
+
const match = /^\s*(?:(\d+)-)?((?:\d+:){0,2}\d+(?:\.\d+)?)\s*$/.exec(text);
|
|
58
|
+
if (!match)
|
|
59
|
+
return undefined;
|
|
60
|
+
const seconds = match[2].split(":").reduce((total, part) => total * 60 + Number(part), 0);
|
|
61
|
+
return (match[1] ? Number(match[1]) * 86400 : 0) + seconds;
|
|
62
|
+
}
|
|
63
|
+
/** The process's CPU time so far, in seconds, or undefined when it can't be read (Windows, an exited process). */
|
|
64
|
+
async function cpuSeconds(pid) {
|
|
65
|
+
if (process.platform === "win32")
|
|
66
|
+
return undefined;
|
|
67
|
+
if (process.platform === "linux") {
|
|
68
|
+
try {
|
|
69
|
+
// utime and stime, fields 14 and 15, after the parenthesised command name (which may hold spaces).
|
|
70
|
+
const stat = await fs.promises.readFile(`/proc/${pid}/stat`, "utf8");
|
|
71
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
72
|
+
return (Number(fields[11]) + Number(fields[12])) / 100;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return new Promise(resolve => {
|
|
79
|
+
execFile("/bin/ps", ["-o", "time=", "-p", String(pid)], { timeout: 5000 }, (error, stdout) => {
|
|
80
|
+
resolve(error ? undefined : parseCpuTime(stdout));
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** CPU seconds under which a poll counts as idle: a slicing CLI uses far more, a blocked one none. */
|
|
85
|
+
const IDLE_CPU_SECONDS = 0.05;
|
|
86
|
+
/**
|
|
87
|
+
* Calls onStall once when the child has used no CPU and written nothing to stdout or stderr for `seconds`, counted
|
|
88
|
+
* in consecutive polls (so a Mac that sleeps meanwhile doesn't count the sleep). It starts counting only after the
|
|
89
|
+
* child has shown it is running (output or CPU), and does nothing where CPU time can't be read. Returns a stop
|
|
90
|
+
* function; it also stops when the child exits.
|
|
91
|
+
*/
|
|
92
|
+
export function watchForStall(child, seconds, onStall) {
|
|
93
|
+
if (!seconds || child.pid === undefined || process.platform === "win32")
|
|
94
|
+
return () => { };
|
|
95
|
+
const pid = child.pid;
|
|
96
|
+
const pollMs = Math.min(2000, (seconds * 1000) / 4);
|
|
97
|
+
const pollsNeeded = Math.ceil((seconds * 1000) / pollMs);
|
|
98
|
+
let output = false, started = false, idlePolls = 0, lastCpu, stopped = false, polling = false;
|
|
99
|
+
const sawOutput = () => { output = true; };
|
|
100
|
+
child.stdout?.on("data", sawOutput);
|
|
101
|
+
child.stderr?.on("data", sawOutput);
|
|
102
|
+
const timer = setInterval(async () => {
|
|
103
|
+
if (polling || stopped)
|
|
104
|
+
return;
|
|
105
|
+
polling = true;
|
|
106
|
+
try {
|
|
107
|
+
const cpu = await cpuSeconds(pid);
|
|
108
|
+
if (stopped || cpu === undefined)
|
|
109
|
+
return;
|
|
110
|
+
const busy = output || lastCpu === undefined || cpu - lastCpu >= IDLE_CPU_SECONDS;
|
|
111
|
+
if (output || cpu >= IDLE_CPU_SECONDS)
|
|
112
|
+
started = true;
|
|
113
|
+
output = false;
|
|
114
|
+
lastCpu = cpu;
|
|
115
|
+
idlePolls = busy || !started ? 0 : idlePolls + 1;
|
|
116
|
+
// A slicer that exited meanwhile finished; its exit, not a stall, is reported.
|
|
117
|
+
if (idlePolls >= pollsNeeded && child.exitCode === null && child.signalCode === null) {
|
|
118
|
+
stop();
|
|
119
|
+
onStall();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
polling = false;
|
|
124
|
+
}
|
|
125
|
+
}, pollMs);
|
|
126
|
+
const stop = () => {
|
|
127
|
+
if (stopped)
|
|
128
|
+
return;
|
|
129
|
+
stopped = true;
|
|
130
|
+
clearInterval(timer);
|
|
131
|
+
child.stdout?.off("data", sawOutput);
|
|
132
|
+
child.stderr?.off("data", sawOutput);
|
|
133
|
+
};
|
|
134
|
+
child.once("exit", stop);
|
|
135
|
+
child.once("error", stop);
|
|
136
|
+
return stop;
|
|
137
|
+
}
|
|
138
|
+
const SLICER_NAMES = { bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer" };
|
|
139
|
+
/** The failure for a slicer stopped by watchForStall. */
|
|
140
|
+
export function stalledSlicerError(slicerType, seconds) {
|
|
141
|
+
const name = SLICER_NAMES[slicerType] ?? "The slicer";
|
|
142
|
+
return new SlicerStalled(`${name} stopped slicing: it used no processor time and wrote nothing for ${seconds} seconds, which is what it does ` +
|
|
143
|
+
`while it waits on a window nobody can answer, such as a question it asks after a crash. It was stopped, and nothing ` +
|
|
144
|
+
`was sent to the printer. Open ${name} once, answer any question it shows, quit it, then slice again.`);
|
|
145
|
+
}
|
|
@@ -19,6 +19,7 @@ import { applyProcessOverrides } from '../slicer/process-overrides.js';
|
|
|
19
19
|
import { profileJsonFiles } from '../slicer/profile-files.js';
|
|
20
20
|
import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
|
|
21
21
|
import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
|
|
22
|
+
import { prepareSlicerLaunch, stalledSlicerError, watchForStall } from '../slicer/slicer-launch.js';
|
|
22
23
|
/** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
|
|
23
24
|
const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
24
25
|
const readFileAsync = promisify(fs.readFile);
|
|
@@ -1660,43 +1661,64 @@ export class STLManipulator extends EventEmitter {
|
|
|
1660
1661
|
if (progressCallback)
|
|
1661
1662
|
progressCallback(20, `Executing slicer: ${slicerPath} ${args.join(' ')}`);
|
|
1662
1663
|
console.error(`Executing: ${slicerPath} ${args.join(' ')}`);
|
|
1664
|
+
// A Bambu-compatible CLI runs in a home folder of its own (macOS), and one that waits on a dialog is stopped
|
|
1665
|
+
// and reported instead of waiting forever (src/slicer/slicer-launch.ts).
|
|
1666
|
+
const launch = await prepareSlicerLaunch(slicerType, this.tempDir);
|
|
1667
|
+
const stallSeconds = launch.stallSeconds;
|
|
1668
|
+
let stalled = false;
|
|
1663
1669
|
// Execute the slicer
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
|
|
1670
|
-
reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
|
|
1671
|
-
}
|
|
1672
|
-
else {
|
|
1673
|
-
console.error(`Slicer Stdout: ${stdout}`);
|
|
1674
|
-
if (stderr) {
|
|
1675
|
-
console.warn(`Slicer Stderr: ${stderr}`); // Log stderr even on success
|
|
1670
|
+
try {
|
|
1671
|
+
await new Promise((resolve, reject) => {
|
|
1672
|
+
const process = execFile(slicerPath, args, launch.env ? { env: launch.env } : {}, (error, stdout, stderr) => {
|
|
1673
|
+
if (stalled && error) {
|
|
1674
|
+
reject(stalledSlicerError(slicerType, stallSeconds));
|
|
1676
1675
|
}
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
// process.stderr?.on('data', (data) => { console.error(`Slicer stderr: ${data}`); });
|
|
1683
|
-
// Check for cancellation periodically
|
|
1684
|
-
const checkCancel = setInterval(() => {
|
|
1685
|
-
if (!this.activeOperations.get(operationId)) {
|
|
1686
|
-
clearInterval(checkCancel);
|
|
1687
|
-
try {
|
|
1688
|
-
process.kill(); // Attempt to kill the slicer process
|
|
1689
|
-
reject(new Error("Slicing operation cancelled"));
|
|
1676
|
+
else if (error) {
|
|
1677
|
+
console.error(`Slicer Error: ${error.message}`);
|
|
1678
|
+
console.error(`Slicer Stderr: ${stderr}`);
|
|
1679
|
+
const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
|
|
1680
|
+
reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
|
|
1690
1681
|
}
|
|
1691
|
-
|
|
1692
|
-
console.error(
|
|
1693
|
-
|
|
1682
|
+
else {
|
|
1683
|
+
console.error(`Slicer Stdout: ${stdout}`);
|
|
1684
|
+
if (stderr) {
|
|
1685
|
+
console.warn(`Slicer Stderr: ${stderr}`); // Log stderr even on success
|
|
1686
|
+
}
|
|
1687
|
+
resolve();
|
|
1694
1688
|
}
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1689
|
+
});
|
|
1690
|
+
// Optional: Add listeners for stdout/stderr for real-time progress if slicer provides it
|
|
1691
|
+
// process.stdout?.on('data', (data) => { console.error(`Slicer stdout: ${data}`); });
|
|
1692
|
+
// process.stderr?.on('data', (data) => { console.error(`Slicer stderr: ${data}`); });
|
|
1693
|
+
// Check for cancellation periodically
|
|
1694
|
+
const checkCancel = setInterval(() => {
|
|
1695
|
+
if (!this.activeOperations.get(operationId)) {
|
|
1696
|
+
clearInterval(checkCancel);
|
|
1697
|
+
try {
|
|
1698
|
+
process.kill(); // Attempt to kill the slicer process
|
|
1699
|
+
reject(new Error("Slicing operation cancelled"));
|
|
1700
|
+
}
|
|
1701
|
+
catch (killError) {
|
|
1702
|
+
console.error("Error attempting to kill slicer process:", killError);
|
|
1703
|
+
reject(new Error("Slicing operation cancelled, but failed to kill process."));
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
}, 500);
|
|
1707
|
+
process.on('exit', () => clearInterval(checkCancel));
|
|
1708
|
+
process.on('error', () => clearInterval(checkCancel)); // Ensure interval cleared on process error too
|
|
1709
|
+
watchForStall(process, stallSeconds, () => {
|
|
1710
|
+
stalled = true;
|
|
1711
|
+
console.error(`${slicerType} used no CPU and wrote nothing for ${stallSeconds} s; stopping it as waiting on a dialog.`);
|
|
1712
|
+
try {
|
|
1713
|
+
process.kill('SIGKILL');
|
|
1714
|
+
}
|
|
1715
|
+
catch { /* its exit is reported through the callback */ }
|
|
1716
|
+
});
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
finally {
|
|
1720
|
+
await launch.cleanup();
|
|
1721
|
+
}
|
|
1700
1722
|
}
|
|
1701
1723
|
if (!this.activeOperations.get(operationId)) {
|
|
1702
1724
|
// This check might be redundant if the promise rejected on kill, but good safety
|
package/package.json
CHANGED
package/src/refusal.ts
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* A
|
|
5
|
-
* Counterpart
|
|
6
|
-
*
|
|
4
|
+
* A refusal with a stable code, returned as structuredContent.code on the tool's error, so clients such as
|
|
5
|
+
* Counterpart act on the code instead of matching the message (whose words, HMS numbers, firmware and slicer
|
|
6
|
+
* details change). None of them starts a print. Whether a print command was sent is dispatch truth: clients
|
|
7
|
+
* read structuredContent.printOutcome for it, never these codes or the message.
|
|
7
8
|
*
|
|
8
9
|
* - printer-command-rejected: the printer refused the print command itself (for Bambu, HMS 0500-0500-0001-0007,
|
|
9
10
|
* MQTT command verification); the file was uploaded and the command sent, but nothing is printing.
|
|
10
11
|
* - printer-not-ready: the printer isn't in a state that can start a print (busy, paused, failed, unknown).
|
|
11
12
|
* - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
|
|
13
|
+
* - slicer-waiting-on-dialog: the slicer stopped working (no CPU, no output) as it does while a window waits for an
|
|
14
|
+
* answer, and was stopped; nothing was sliced or sent. Not the slicer's verdict on the model: no slicer_report.
|
|
12
15
|
*/
|
|
13
|
-
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed"] as const;
|
|
16
|
+
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog"] as const;
|
|
14
17
|
export type RefusalCode = (typeof REFUSAL_CODES)[number];
|
|
15
18
|
|
|
16
19
|
export class PrinterRefusal extends Error {
|
|
@@ -20,6 +23,14 @@ export class PrinterRefusal extends Error {
|
|
|
20
23
|
}
|
|
21
24
|
}
|
|
22
25
|
|
|
26
|
+
/** A slicer stopped because it waited on a dialog (src/slicer/slicer-launch.ts); carries slicer-waiting-on-dialog. */
|
|
27
|
+
export class SlicerStalled extends PrinterRefusal {
|
|
28
|
+
constructor(message: string) {
|
|
29
|
+
super("slicer-waiting-on-dialog", message);
|
|
30
|
+
this.name = "SlicerStalled";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
23
34
|
/** counterpart/1 dispatch-tool errors describe dispatch truth independently of firmware-specific codes. */
|
|
24
35
|
export type PrintOutcome = "not-sent" | "unknown" | "rejected";
|
|
25
36
|
const printDispatch = new AsyncLocalStorage<{ attempted: boolean }>();
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { execFile, type ChildProcess } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { SlicerStalled } from "../refusal.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* How a Bambu-compatible slicer CLI is launched so that it can't block on per-user AppKit launch state, and how a
|
|
8
|
+
* slicer that blocks anyway is noticed.
|
|
9
|
+
*
|
|
10
|
+
* Bambu Studio's command line opens a hidden GLFW window to draw plate thumbnails for --export-3mf (Bambu Studio
|
|
11
|
+
* 02.08.02.61 src/BambuStudio.cpp:6231-6259; OrcaSlicer and FULU's OrcaSlicer-bambulab inherit that code). The
|
|
12
|
+
* window starts NSApplication, and AppKit's window restoration then reads the person's crash history from
|
|
13
|
+
* ~/Library/Application Support/CrashReporter/<executable>_<hardware UUID>.plist. When that history says the app
|
|
14
|
+
* crashed while restoring windows, AppKit raises its modal "reopen windows?" alert, and the slicer waits on it at 0%
|
|
15
|
+
* CPU forever. Stopping it never answers the alert, so the next slice waits again.
|
|
16
|
+
*
|
|
17
|
+
* The CLI reads nothing else from the home folder: it takes its profiles from its own bundle (resources_dir(),
|
|
18
|
+
* BambuStudio.cpp:8325-8328) or from the files this server passes, its temporary files from TMPDIR
|
|
19
|
+
* (BambuStudio.cpp:1558-1559), and it sets no data directory unless --datadir is given (BambuStudio.cpp:8363-8367).
|
|
20
|
+
* So each slice gets a fresh, empty home of its own through CFFIXED_USER_HOME, under this server's TEMP_DIR, which
|
|
21
|
+
* AppKit honours for that history. Its preferences still come from the person's own (cfprefsd ignores
|
|
22
|
+
* CFFIXED_USER_HOME) and HOME is unchanged, so nothing else the slicer or this server reads moves.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Slicer types launched from a local Bambu-compatible CLI binary. */
|
|
26
|
+
const BAMBU_CLI_TYPES = new Set(["bambustudio", "orcaslicer", "orcaslicer-bambulab"]);
|
|
27
|
+
|
|
28
|
+
export interface SlicerLaunch {
|
|
29
|
+
/** The environment for the slicer process (undefined: inherit this server's). */
|
|
30
|
+
env?: NodeJS.ProcessEnv;
|
|
31
|
+
/** Seconds without CPU or output after which the slice is stopped and reported (watchForStall); 0: never. */
|
|
32
|
+
stallSeconds: number;
|
|
33
|
+
/** Removes this launch's home folder. */
|
|
34
|
+
cleanup(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The launch for one slice. On macOS a Bambu-compatible CLI gets its own empty home folder (always: an inherited
|
|
39
|
+
* CFFIXED_USER_HOME is replaced, since a home that held a stalled slice may hold the history that stalled it), and
|
|
40
|
+
* is watched for stalls. A new folder each slice, not one kept in the data folder, so no crash history can build up
|
|
41
|
+
* in it. Elsewhere nothing changes: no AppKit, and a slicer there may run behind a wrapper (AppImage, Flatpak) whose
|
|
42
|
+
* own CPU says nothing about the slicer's.
|
|
43
|
+
*/
|
|
44
|
+
export async function prepareSlicerLaunch(slicerType: string, tempDir: string, platform: NodeJS.Platform = process.platform): Promise<SlicerLaunch> {
|
|
45
|
+
if (!BAMBU_CLI_TYPES.has(slicerType) || platform !== "darwin") return { stallSeconds: 0, cleanup: async () => {} };
|
|
46
|
+
await fs.promises.mkdir(tempDir, { recursive: true });
|
|
47
|
+
const home = await fs.promises.mkdtemp(path.join(tempDir, "slicer-home-"));
|
|
48
|
+
return {
|
|
49
|
+
env: { ...process.env, CFFIXED_USER_HOME: home },
|
|
50
|
+
stallSeconds: slicerStallSeconds(),
|
|
51
|
+
cleanup: () => fs.promises.rm(home, { recursive: true, force: true }).catch(() => undefined),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const DEFAULT_STALL_SECONDS = 20;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Seconds a slicer may use no CPU and write nothing before it is treated as waiting on a dialog
|
|
59
|
+
* (SLICER_STALL_SECONDS, 1-3600; 0 turns the check off). A slice is never idle that long: it computes or writes.
|
|
60
|
+
*/
|
|
61
|
+
export function slicerStallSeconds(raw = process.env.SLICER_STALL_SECONDS): number {
|
|
62
|
+
const text = raw?.trim();
|
|
63
|
+
if (!text) return DEFAULT_STALL_SECONDS;
|
|
64
|
+
const value = Number(text);
|
|
65
|
+
return Number.isFinite(value) && value >= 0 && value <= 3600 ? value : DEFAULT_STALL_SECONDS;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** "[[dd-]hh:]mm:ss[.cc]" from ps -o time= (macOS: m:ss.cc; Linux: [dd-]hh:mm:ss), in seconds. */
|
|
69
|
+
export function parseCpuTime(text: string): number | undefined {
|
|
70
|
+
const match = /^\s*(?:(\d+)-)?((?:\d+:){0,2}\d+(?:\.\d+)?)\s*$/.exec(text);
|
|
71
|
+
if (!match) return undefined;
|
|
72
|
+
const seconds = match[2].split(":").reduce((total, part) => total * 60 + Number(part), 0);
|
|
73
|
+
return (match[1] ? Number(match[1]) * 86400 : 0) + seconds;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The process's CPU time so far, in seconds, or undefined when it can't be read (Windows, an exited process). */
|
|
77
|
+
async function cpuSeconds(pid: number): Promise<number | undefined> {
|
|
78
|
+
if (process.platform === "win32") return undefined;
|
|
79
|
+
if (process.platform === "linux") {
|
|
80
|
+
try {
|
|
81
|
+
// utime and stime, fields 14 and 15, after the parenthesised command name (which may hold spaces).
|
|
82
|
+
const stat = await fs.promises.readFile(`/proc/${pid}/stat`, "utf8");
|
|
83
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
84
|
+
return (Number(fields[11]) + Number(fields[12])) / 100;
|
|
85
|
+
} catch { return undefined; }
|
|
86
|
+
}
|
|
87
|
+
return new Promise(resolve => {
|
|
88
|
+
execFile("/bin/ps", ["-o", "time=", "-p", String(pid)], { timeout: 5_000 }, (error, stdout) => {
|
|
89
|
+
resolve(error ? undefined : parseCpuTime(stdout));
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** CPU seconds under which a poll counts as idle: a slicing CLI uses far more, a blocked one none. */
|
|
95
|
+
const IDLE_CPU_SECONDS = 0.05;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Calls onStall once when the child has used no CPU and written nothing to stdout or stderr for `seconds`, counted
|
|
99
|
+
* in consecutive polls (so a Mac that sleeps meanwhile doesn't count the sleep). It starts counting only after the
|
|
100
|
+
* child has shown it is running (output or CPU), and does nothing where CPU time can't be read. Returns a stop
|
|
101
|
+
* function; it also stops when the child exits.
|
|
102
|
+
*/
|
|
103
|
+
export function watchForStall(child: ChildProcess, seconds: number, onStall: () => void): () => void {
|
|
104
|
+
if (!seconds || child.pid === undefined || process.platform === "win32") return () => {};
|
|
105
|
+
const pid = child.pid;
|
|
106
|
+
const pollMs = Math.min(2_000, (seconds * 1000) / 4);
|
|
107
|
+
const pollsNeeded = Math.ceil((seconds * 1000) / pollMs);
|
|
108
|
+
let output = false, started = false, idlePolls = 0, lastCpu: number | undefined, stopped = false, polling = false;
|
|
109
|
+
const sawOutput = () => { output = true; };
|
|
110
|
+
child.stdout?.on("data", sawOutput);
|
|
111
|
+
child.stderr?.on("data", sawOutput);
|
|
112
|
+
const timer = setInterval(async () => {
|
|
113
|
+
if (polling || stopped) return;
|
|
114
|
+
polling = true;
|
|
115
|
+
try {
|
|
116
|
+
const cpu = await cpuSeconds(pid);
|
|
117
|
+
if (stopped || cpu === undefined) return;
|
|
118
|
+
const busy = output || lastCpu === undefined || cpu - lastCpu >= IDLE_CPU_SECONDS;
|
|
119
|
+
if (output || cpu >= IDLE_CPU_SECONDS) started = true;
|
|
120
|
+
output = false;
|
|
121
|
+
lastCpu = cpu;
|
|
122
|
+
idlePolls = busy || !started ? 0 : idlePolls + 1;
|
|
123
|
+
// A slicer that exited meanwhile finished; its exit, not a stall, is reported.
|
|
124
|
+
if (idlePolls >= pollsNeeded && child.exitCode === null && child.signalCode === null) { stop(); onStall(); }
|
|
125
|
+
} finally { polling = false; }
|
|
126
|
+
}, pollMs);
|
|
127
|
+
const stop = () => {
|
|
128
|
+
if (stopped) return;
|
|
129
|
+
stopped = true;
|
|
130
|
+
clearInterval(timer);
|
|
131
|
+
child.stdout?.off("data", sawOutput);
|
|
132
|
+
child.stderr?.off("data", sawOutput);
|
|
133
|
+
};
|
|
134
|
+
child.once("exit", stop);
|
|
135
|
+
child.once("error", stop);
|
|
136
|
+
return stop;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const SLICER_NAMES: Record<string, string> = { bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer" };
|
|
140
|
+
|
|
141
|
+
/** The failure for a slicer stopped by watchForStall. */
|
|
142
|
+
export function stalledSlicerError(slicerType: string, seconds: number): SlicerStalled {
|
|
143
|
+
const name = SLICER_NAMES[slicerType] ?? "The slicer";
|
|
144
|
+
return new SlicerStalled(
|
|
145
|
+
`${name} stopped slicing: it used no processor time and wrote nothing for ${seconds} seconds, which is what it does ` +
|
|
146
|
+
`while it waits on a window nobody can answer, such as a question it asks after a crash. It was stopped, and nothing ` +
|
|
147
|
+
`was sent to the printer. Open ${name} once, answer any question it shows, quit it, then slice again.`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
@@ -19,6 +19,7 @@ import { applyProcessOverrides, type ProcessOverrides } from '../slicer/process-
|
|
|
19
19
|
import { profileJsonFiles } from '../slicer/profile-files.js';
|
|
20
20
|
import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
|
|
21
21
|
import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
|
|
22
|
+
import { prepareSlicerLaunch, stalledSlicerError, watchForStall } from '../slicer/slicer-launch.js';
|
|
22
23
|
|
|
23
24
|
/** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
|
|
24
25
|
const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
@@ -2067,10 +2068,17 @@ export class STLManipulator extends EventEmitter {
|
|
|
2067
2068
|
if (progressCallback) progressCallback(20, `Executing slicer: ${slicerPath} ${args.join(' ')}`);
|
|
2068
2069
|
console.error(`Executing: ${slicerPath} ${args.join(' ')}`);
|
|
2069
2070
|
|
|
2071
|
+
// A Bambu-compatible CLI runs in a home folder of its own (macOS), and one that waits on a dialog is stopped
|
|
2072
|
+
// and reported instead of waiting forever (src/slicer/slicer-launch.ts).
|
|
2073
|
+
const launch = await prepareSlicerLaunch(slicerType, this.tempDir);
|
|
2074
|
+
const stallSeconds = launch.stallSeconds;
|
|
2075
|
+
let stalled = false;
|
|
2070
2076
|
// Execute the slicer
|
|
2071
|
-
await new Promise<void>((resolve, reject) => {
|
|
2072
|
-
const process = execFile(slicerPath, args, (error, stdout, stderr) => {
|
|
2073
|
-
if (error) {
|
|
2077
|
+
try { await new Promise<void>((resolve, reject) => {
|
|
2078
|
+
const process = execFile(slicerPath, args, launch.env ? { env: launch.env } : {}, (error, stdout, stderr) => {
|
|
2079
|
+
if (stalled && error) {
|
|
2080
|
+
reject(stalledSlicerError(slicerType, stallSeconds));
|
|
2081
|
+
} else if (error) {
|
|
2074
2082
|
console.error(`Slicer Error: ${error.message}`);
|
|
2075
2083
|
console.error(`Slicer Stderr: ${stderr}`);
|
|
2076
2084
|
const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
|
|
@@ -2104,8 +2112,13 @@ export class STLManipulator extends EventEmitter {
|
|
|
2104
2112
|
|
|
2105
2113
|
process.on('exit', () => clearInterval(checkCancel));
|
|
2106
2114
|
process.on('error', () => clearInterval(checkCancel)); // Ensure interval cleared on process error too
|
|
2115
|
+
watchForStall(process, stallSeconds, () => {
|
|
2116
|
+
stalled = true;
|
|
2117
|
+
console.error(`${slicerType} used no CPU and wrote nothing for ${stallSeconds} s; stopping it as waiting on a dialog.`);
|
|
2118
|
+
try { process.kill('SIGKILL'); } catch { /* its exit is reported through the callback */ }
|
|
2119
|
+
});
|
|
2107
2120
|
|
|
2108
|
-
});
|
|
2121
|
+
}); } finally { await launch.cleanup(); }
|
|
2109
2122
|
}
|
|
2110
2123
|
|
|
2111
2124
|
if (!this.activeOperations.get(operationId)) {
|