bambu-printer-mcp 1.1.82 → 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 +41 -0
- package/dist/cad/contracts.d.ts +424 -0
- package/dist/cad/contracts.js +288 -0
- package/dist/cad/process.d.ts +32 -0
- package/dist/cad/process.js +151 -0
- package/dist/cad/refusal.d.ts +15 -0
- package/dist/cad/refusal.js +30 -0
- package/dist/cad/serial.d.ts +6 -0
- package/dist/cad/serial.js +114 -0
- package/dist/cad/storage.d.ts +34 -0
- package/dist/cad/storage.js +201 -0
- package/dist/cad-engine.d.ts +43 -0
- package/dist/cad-engine.js +546 -0
- package/dist/counterpart/info.js +2 -0
- package/dist/counterpart/remote.js +7 -0
- package/dist/counterpart/schemas.d.ts +33 -0
- package/dist/counterpart/schemas.js +1 -0
- package/dist/design-guidance.js +2 -6
- package/dist/index.js +44 -3
- 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/dist/tool-annotations.js +4 -0
- package/package.json +1 -1
- package/src/cad/contracts.ts +317 -0
- package/src/cad/geometry.py +157 -0
- package/src/cad/process.ts +216 -0
- package/src/cad/refusal.ts +34 -0
- package/src/cad/requirements.in +9 -0
- package/src/cad/requirements.lock +69 -0
- package/src/cad/serial.ts +126 -0
- package/src/cad/storage.ts +232 -0
- package/src/cad/worker.py +161 -0
- package/src/cad-engine.ts +794 -0
- package/src/counterpart/info.ts +2 -0
- package/src/counterpart/remote.ts +6 -0
- package/src/counterpart/schemas.ts +2 -0
- package/src/design-guidance.ts +2 -0
- package/src/index.ts +39 -3
- package/src/refusal.ts +15 -4
- package/src/slicer/slicer-launch.ts +149 -0
- package/src/stl/stl-manipulator.ts +17 -4
- package/src/tool-annotations.ts +4 -0
package/dist/index.js
CHANGED
|
@@ -27,6 +27,9 @@ import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } fr
|
|
|
27
27
|
import { BambuNetworkBridge, bridgeSnapshotRoot, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
|
|
28
28
|
import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
|
|
29
29
|
import { importFileViaBambuConnect } from "./bambu-connect.js";
|
|
30
|
+
import { CadEngine } from "./cad-engine.js";
|
|
31
|
+
import { CadRefusal } from "./cad/refusal.js";
|
|
32
|
+
import { CAD_TOOLS, cadEnabled } from "./cad/contracts.js";
|
|
30
33
|
import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
|
|
31
34
|
import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
|
|
32
35
|
import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake } from "./design-app-setup.js";
|
|
@@ -55,6 +58,7 @@ import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome }
|
|
|
55
58
|
import { uploadProgressReporter } from "./upload-progress.js";
|
|
56
59
|
import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
|
|
57
60
|
dotenv.config();
|
|
61
|
+
const CAD_ENABLED = cadEnabled();
|
|
58
62
|
const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
|
|
59
63
|
const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
|
|
60
64
|
const DEFAULT_BAMBU_TOKEN = process.env.BAMBU_PRINTER_ACCESS_TOKEN || process.env.BAMBU_TOKEN || "";
|
|
@@ -115,6 +119,7 @@ const SERVER_INFO = {
|
|
|
115
119
|
};
|
|
116
120
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
117
121
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
122
|
+
"cad_status", "cad_setup", "cad_run", "cad_check_fit",
|
|
118
123
|
"counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
|
|
119
124
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
120
125
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
@@ -1109,6 +1114,7 @@ if (!fs.existsSync(TEMP_DIR)) {
|
|
|
1109
1114
|
}
|
|
1110
1115
|
class BambuPrinterMCPServer {
|
|
1111
1116
|
constructor() {
|
|
1117
|
+
this.cad = new CadEngine({ outputRoots: [TEMP_DIR, ...(process.env.CAD_OUTPUT_DIRS?.split(path.delimiter).filter(Boolean) ?? [])] });
|
|
1112
1118
|
this.blender = new BlenderMcpBridge();
|
|
1113
1119
|
this.fusion = new FusionMcpBridge();
|
|
1114
1120
|
// Downloads and installer output are staged in this server's own temporary folder.
|
|
@@ -1123,7 +1129,7 @@ class BambuPrinterMCPServer {
|
|
|
1123
1129
|
resources: {},
|
|
1124
1130
|
tools: {}
|
|
1125
1131
|
},
|
|
1126
|
-
instructions: SERVER_INSTRUCTIONS
|
|
1132
|
+
instructions: SERVER_INSTRUCTIONS + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
|
|
1127
1133
|
});
|
|
1128
1134
|
this.bambu = new BambuImplementation(async (message) => {
|
|
1129
1135
|
try {
|
|
@@ -1874,7 +1880,7 @@ class BambuPrinterMCPServer {
|
|
|
1874
1880
|
/** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
|
|
1875
1881
|
setupPromptHandlers() {
|
|
1876
1882
|
this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
1877
|
-
prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
|
|
1883
|
+
prompts: [...DESIGN_PROMPTS.filter(p => CAD_ENABLED || p.name !== "cad_design"), FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
|
|
1878
1884
|
}));
|
|
1879
1885
|
this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
1880
1886
|
if (request.params.name === FDM_SLICING_PROMPT.name) {
|
|
@@ -1885,7 +1891,7 @@ class BambuPrinterMCPServer {
|
|
|
1885
1891
|
messages: [{ role: "user", content: { type: "text", text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
|
|
1886
1892
|
};
|
|
1887
1893
|
}
|
|
1888
|
-
const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
|
|
1894
|
+
const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name && (CAD_ENABLED || item.name !== "cad_design"));
|
|
1889
1895
|
if (!prompt)
|
|
1890
1896
|
throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
|
|
1891
1897
|
return {
|
|
@@ -2959,6 +2965,7 @@ class BambuPrinterMCPServer {
|
|
|
2959
2965
|
required: ["stl_path"]
|
|
2960
2966
|
}
|
|
2961
2967
|
},
|
|
2968
|
+
...(CAD_ENABLED ? CAD_TOOLS : []),
|
|
2962
2969
|
{
|
|
2963
2970
|
name: "blender_mcp_status",
|
|
2964
2971
|
description: "Inspect Blender MCP configuration or connect and discover the remote server's tools and schemas. Connecting does not edit the scene; use get_scene_info through blender_mcp_call to check the Blender addon.",
|
|
@@ -3234,6 +3241,10 @@ class BambuPrinterMCPServer {
|
|
|
3234
3241
|
.then(() => extra.sendNotification({ method: "notifications/progress", params: { progressToken, ...params } }))
|
|
3235
3242
|
.catch(() => { });
|
|
3236
3243
|
});
|
|
3244
|
+
if (!CAD_ENABLED && name.startsWith("cad_")) {
|
|
3245
|
+
const failure = await this.cad.failure(new CadRefusal("cad-disabled", "Code-CAD is disabled by CAD_ENABLED=0."), name);
|
|
3246
|
+
return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
|
|
3247
|
+
}
|
|
3237
3248
|
const host = String(args?.host || DEFAULT_HOST);
|
|
3238
3249
|
const bambuSerial = String(args?.bambu_serial || DEFAULT_BAMBU_SERIAL);
|
|
3239
3250
|
const bambuToken = String(args?.bambu_token || DEFAULT_BAMBU_TOKEN);
|
|
@@ -4369,6 +4380,32 @@ class BambuPrinterMCPServer {
|
|
|
4369
4380
|
case "counterpart_make_3mf":
|
|
4370
4381
|
result = await makeCounterpart3mf(args ?? {});
|
|
4371
4382
|
break;
|
|
4383
|
+
case "cad_status":
|
|
4384
|
+
if (args && Object.keys(args).length)
|
|
4385
|
+
throw new Error("cad_status takes no arguments.");
|
|
4386
|
+
result = await this.cad.status();
|
|
4387
|
+
break;
|
|
4388
|
+
case "cad_setup":
|
|
4389
|
+
case "cad_run":
|
|
4390
|
+
case "cad_check_fit": {
|
|
4391
|
+
const started = Date.now();
|
|
4392
|
+
let sequence = 0;
|
|
4393
|
+
const heartbeat = progressToken === undefined ? undefined : setInterval(() => {
|
|
4394
|
+
progressNotifications = progressNotifications.then(() => extra.sendNotification({ method: "notifications/progress", params: {
|
|
4395
|
+
progressToken, progress: ++sequence, message: `${name}: working for ${Math.round((Date.now() - started) / 1000)} seconds`,
|
|
4396
|
+
} })).catch(() => { });
|
|
4397
|
+
}, 5000);
|
|
4398
|
+
try {
|
|
4399
|
+
result = name === "cad_setup" ? await this.cad.setup(args ?? {}, extra.signal)
|
|
4400
|
+
: name === "cad_run" ? await this.cad.run(args ?? {}, extra.signal)
|
|
4401
|
+
: await this.cad.checkFit(args ?? {}, extra.signal);
|
|
4402
|
+
}
|
|
4403
|
+
finally {
|
|
4404
|
+
if (heartbeat)
|
|
4405
|
+
clearInterval(heartbeat);
|
|
4406
|
+
}
|
|
4407
|
+
break;
|
|
4408
|
+
}
|
|
4372
4409
|
case "blender_mcp_setup":
|
|
4373
4410
|
if (args?.update !== undefined && typeof args.update !== "boolean")
|
|
4374
4411
|
throw new Error("update must be a boolean.");
|
|
@@ -4412,6 +4449,10 @@ class BambuPrinterMCPServer {
|
|
|
4412
4449
|
return { content: [{ type: "text", text }] };
|
|
4413
4450
|
}
|
|
4414
4451
|
catch (error) {
|
|
4452
|
+
if (name.startsWith("cad_")) {
|
|
4453
|
+
const failure = await this.cad.failure(error, name);
|
|
4454
|
+
return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
|
|
4455
|
+
}
|
|
4415
4456
|
const message = error instanceof Error ? error.message : String(error);
|
|
4416
4457
|
// Refusals and printer rejections repeat unchanged; say what to fix instead of "try again".
|
|
4417
4458
|
const refused = /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
|
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/dist/tool-annotations.js
CHANGED
|
@@ -12,6 +12,10 @@ const START_PRINT = hints(false, false, false, true);
|
|
|
12
12
|
/** Starts a print, auto-slicing an unsliced project first, which replaces an earlier slice output of that name. */
|
|
13
13
|
const SLICE_AND_PRINT = hints(false, true, false, true);
|
|
14
14
|
export const TOOL_ANNOTATIONS = {
|
|
15
|
+
cad_status: READ_LOCAL,
|
|
16
|
+
cad_setup: hints(false, true, true, true),
|
|
17
|
+
cad_run: hints(false, false, false, false),
|
|
18
|
+
cad_check_fit: READ_LOCAL,
|
|
15
19
|
// Printer and cloud reads
|
|
16
20
|
get_printer_status: READ_OUTSIDE,
|
|
17
21
|
get_printer_filaments: READ_OUTSIDE,
|