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/src/counterpart/info.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {CAD_CAPABILITY,cadEnabled} from "../cad/contracts.js";
|
|
1
2
|
/** counterpart_printer_info for Bambu printers (PRD §8.4). Pure: no printer traffic. */
|
|
2
3
|
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "../printers/camera-models.js";
|
|
3
4
|
import { normalizeModel } from "../safety/limits.js";
|
|
@@ -33,6 +34,7 @@ export function bambuPrinterInfo(options: { server: { name: string; version: str
|
|
|
33
34
|
host: options.host,
|
|
34
35
|
},
|
|
35
36
|
capabilities: {
|
|
37
|
+
...(cadEnabled()?{cad:CAD_CAPABILITY}:{}),
|
|
36
38
|
progress: true,
|
|
37
39
|
layers: true,
|
|
38
40
|
// camera_snapshot needs the model to choose its transport.
|
|
@@ -41,6 +41,10 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
|
|
|
41
41
|
blender_mcp_status: "read",
|
|
42
42
|
counterpart_printer_info: "read",
|
|
43
43
|
counterpart_print_progress: "read",
|
|
44
|
+
cad_status: "read",
|
|
45
|
+
cad_setup: "read",
|
|
46
|
+
cad_run: "design",
|
|
47
|
+
cad_check_fit: "design",
|
|
44
48
|
fusion_mcp_status: "read",
|
|
45
49
|
blender_mcp_setup: "read", // checks only; update raises it
|
|
46
50
|
fusion_mcp_setup: "read", // checks only; install raises it
|
|
@@ -97,6 +101,7 @@ const RAISED_BY: Readonly<Record<string, Record<string, RemoteScope>>> = {
|
|
|
97
101
|
fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
|
|
98
102
|
blender_mcp_status: { connect: "design" }, // connects to Blender
|
|
99
103
|
blender_mcp_setup: { update: "raw" }, // replaces the add-on in the person's Blender
|
|
104
|
+
cad_setup: { install: "raw" },
|
|
100
105
|
fusion_mcp_setup: { install: "raw" }, // installs into the person's Fusion, a login item and this server's .env
|
|
101
106
|
};
|
|
102
107
|
|
|
@@ -119,6 +124,7 @@ const FILE_ARGUMENTS: ReadonlySet<string> = new Set(["filament_profile", "slicer
|
|
|
119
124
|
const isPath = (key: string) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
|
|
120
125
|
|
|
121
126
|
function kindOf(tool: string, key: string, depth: number): ArgumentKind | undefined {
|
|
127
|
+
if (tool === "cad_check_fit" && depth === 0 && ["model", "reference"].includes(key)) return "path";
|
|
122
128
|
// counterpart_print_route's own `route` is the connection the caller chooses.
|
|
123
129
|
if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key)) return "config";
|
|
124
130
|
if (depth === 0 && TOP_LEVEL_CONFIG.has(key)) return "config-top";
|
|
@@ -28,6 +28,7 @@ export type PrinterInfo = {
|
|
|
28
28
|
server: { name: string; version: string };
|
|
29
29
|
printer: { kind: typeof PRINTER_KINDS[number]; model?: string; serial?: string; host: string; name?: string };
|
|
30
30
|
capabilities: {
|
|
31
|
+
cad?: {contract: string; status: string; setup: string; run: string; checkFit: string; prompt: string};
|
|
31
32
|
progress: boolean; layers: boolean;
|
|
32
33
|
camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
|
|
33
34
|
cameraStream?: boolean;
|
|
@@ -67,6 +68,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
|
|
|
67
68
|
capabilities: {
|
|
68
69
|
type: "object",
|
|
69
70
|
properties: {
|
|
71
|
+
cad: {type: "object", properties: {contract: {type: "string", const: "cad/1"}, status: {type: "string"}, setup: {type: "string"}, run: {type: "string"}, checkFit: {type: "string"}, prompt: {type: "string"}}, required: ["contract", "status", "setup", "run", "checkFit", "prompt"]},
|
|
70
72
|
progress: { type: "boolean" },
|
|
71
73
|
layers: { type: "boolean" },
|
|
72
74
|
camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
|
package/src/design-guidance.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CAD_DESIGN_PROMPT } from "./cad/contracts.js";
|
|
1
2
|
/**
|
|
2
3
|
* Manufacturing guidance for agents that design printable models: David Montgomery's FDM design
|
|
3
4
|
* prompt pack (3 November 2026), verbatim. Served as MCP prompts and a resource; the other printer
|
|
@@ -175,6 +176,7 @@ export const FDM_CAPABILITY_RESOURCE = { uri: FDM_CAPABILITY_URI, name: "FDM bri
|
|
|
175
176
|
description: "Planning bands and evidence for bridges and overhangs, for when one is consequential and there is no sufficiently specific measured capability available" };
|
|
176
177
|
|
|
177
178
|
export const DESIGN_PROMPTS: DesignPrompt[] = [
|
|
179
|
+
CAD_DESIGN_PROMPT,
|
|
178
180
|
{ name: "fdm_design", title: "Design for FDM printing", text: FDM_CORE,
|
|
179
181
|
description: "Persistent instructions for every design or model-editing task: plan how the object prints as part of the design, using the actual printer, filaments and slice." },
|
|
180
182
|
{ name: "fdm_multicolor", title: "Multicolour and support materials", text: FDM_MULTICOLOR,
|
package/src/index.ts
CHANGED
|
@@ -57,6 +57,9 @@ import {
|
|
|
57
57
|
type BambuNativeUpdateCallback,
|
|
58
58
|
} from "./bambu-native.js";
|
|
59
59
|
import { importFileViaBambuConnect } from "./bambu-connect.js";
|
|
60
|
+
import { CadEngine } from "./cad-engine.js";
|
|
61
|
+
import { CadRefusal } from "./cad/refusal.js";
|
|
62
|
+
import { CAD_TOOLS, cadEnabled } from "./cad/contracts.js";
|
|
60
63
|
import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
|
|
61
64
|
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";
|
|
62
65
|
import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake, type BlenderAddonHandshake } from "./design-app-setup.js";
|
|
@@ -88,6 +91,7 @@ import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } fro
|
|
|
88
91
|
|
|
89
92
|
dotenv.config();
|
|
90
93
|
|
|
94
|
+
const CAD_ENABLED = cadEnabled();
|
|
91
95
|
const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
|
|
92
96
|
const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
|
|
93
97
|
const DEFAULT_BAMBU_TOKEN =
|
|
@@ -151,6 +155,7 @@ const SERVER_INFO = {
|
|
|
151
155
|
};
|
|
152
156
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
153
157
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
158
|
+
"cad_status", "cad_setup", "cad_run", "cad_check_fit",
|
|
154
159
|
"counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
|
|
155
160
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
156
161
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
@@ -1386,6 +1391,7 @@ class BambuPrinterMCPServer {
|
|
|
1386
1391
|
private server: Server;
|
|
1387
1392
|
private bambu: BambuImplementation;
|
|
1388
1393
|
private bambuNetwork: BambuNetworkBridge;
|
|
1394
|
+
private readonly cad = new CadEngine({outputRoots:[TEMP_DIR,...(process.env.CAD_OUTPUT_DIRS?.split(path.delimiter).filter(Boolean)??[])]});
|
|
1389
1395
|
private readonly blender = new BlenderMcpBridge();
|
|
1390
1396
|
private readonly fusion = new FusionMcpBridge();
|
|
1391
1397
|
// Downloads and installer output are staged in this server's own temporary folder.
|
|
@@ -1407,7 +1413,7 @@ class BambuPrinterMCPServer {
|
|
|
1407
1413
|
resources: {},
|
|
1408
1414
|
tools: {}
|
|
1409
1415
|
},
|
|
1410
|
-
instructions: SERVER_INSTRUCTIONS
|
|
1416
|
+
instructions: SERVER_INSTRUCTIONS + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
|
|
1411
1417
|
}
|
|
1412
1418
|
);
|
|
1413
1419
|
|
|
@@ -2380,7 +2386,7 @@ class BambuPrinterMCPServer {
|
|
|
2380
2386
|
/** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
|
|
2381
2387
|
setupPromptHandlers() {
|
|
2382
2388
|
this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
2383
|
-
prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
|
|
2389
|
+
prompts: [...DESIGN_PROMPTS.filter(p => CAD_ENABLED || p.name !== "cad_design"), FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
|
|
2384
2390
|
}));
|
|
2385
2391
|
this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
2386
2392
|
if (request.params.name === FDM_SLICING_PROMPT.name) {
|
|
@@ -2391,7 +2397,7 @@ class BambuPrinterMCPServer {
|
|
|
2391
2397
|
messages: [{ role: "user" as const, content: { type: "text" as const, text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
|
|
2392
2398
|
};
|
|
2393
2399
|
}
|
|
2394
|
-
const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
|
|
2400
|
+
const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name && (CAD_ENABLED || item.name !== "cad_design"));
|
|
2395
2401
|
if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
|
|
2396
2402
|
return {
|
|
2397
2403
|
description: prompt.description,
|
|
@@ -3468,6 +3474,7 @@ class BambuPrinterMCPServer {
|
|
|
3468
3474
|
required: ["stl_path"]
|
|
3469
3475
|
}
|
|
3470
3476
|
},
|
|
3477
|
+
...(CAD_ENABLED ? CAD_TOOLS : []),
|
|
3471
3478
|
{
|
|
3472
3479
|
name: "blender_mcp_status",
|
|
3473
3480
|
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.",
|
|
@@ -3750,6 +3757,10 @@ class BambuPrinterMCPServer {
|
|
|
3750
3757
|
.catch(() => {});
|
|
3751
3758
|
});
|
|
3752
3759
|
|
|
3760
|
+
if (!CAD_ENABLED && name.startsWith("cad_")) {
|
|
3761
|
+
const failure = await this.cad.failure(new CadRefusal("cad-disabled", "Code-CAD is disabled by CAD_ENABLED=0."), name);
|
|
3762
|
+
return {isError: true, content: [{type: "text", text: failure.message}], structuredContent: failure};
|
|
3763
|
+
}
|
|
3753
3764
|
const host = String(args?.host || DEFAULT_HOST);
|
|
3754
3765
|
const bambuSerial = String(args?.bambu_serial || DEFAULT_BAMBU_SERIAL);
|
|
3755
3766
|
const bambuToken = String(args?.bambu_token || DEFAULT_BAMBU_TOKEN);
|
|
@@ -5095,6 +5106,27 @@ class BambuPrinterMCPServer {
|
|
|
5095
5106
|
result = await makeCounterpart3mf(args ?? {});
|
|
5096
5107
|
break;
|
|
5097
5108
|
|
|
5109
|
+
case "cad_status":
|
|
5110
|
+
if (args && Object.keys(args).length) throw new Error("cad_status takes no arguments.");
|
|
5111
|
+
result = await this.cad.status(); break;
|
|
5112
|
+
case "cad_setup":
|
|
5113
|
+
case "cad_run":
|
|
5114
|
+
case "cad_check_fit": {
|
|
5115
|
+
const started = Date.now();
|
|
5116
|
+
let sequence = 0;
|
|
5117
|
+
const heartbeat = progressToken === undefined ? undefined : setInterval(() => {
|
|
5118
|
+
progressNotifications = progressNotifications.then(() => extra.sendNotification({method: "notifications/progress", params: {
|
|
5119
|
+
progressToken, progress: ++sequence, message: `${name}: working for ${Math.round((Date.now()-started)/1000)} seconds`,
|
|
5120
|
+
}})).catch(() => {});
|
|
5121
|
+
}, 5000);
|
|
5122
|
+
try {
|
|
5123
|
+
result = name === "cad_setup" ? await this.cad.setup(args ?? {}, extra.signal)
|
|
5124
|
+
: name === "cad_run" ? await this.cad.run(args ?? {}, extra.signal)
|
|
5125
|
+
: await this.cad.checkFit(args ?? {}, extra.signal);
|
|
5126
|
+
} finally { if (heartbeat) clearInterval(heartbeat); }
|
|
5127
|
+
break;
|
|
5128
|
+
}
|
|
5129
|
+
|
|
5098
5130
|
case "blender_mcp_setup":
|
|
5099
5131
|
if (args?.update !== undefined && typeof args.update !== "boolean") throw new Error("update must be a boolean.");
|
|
5100
5132
|
result = args?.update === true ? await this.blenderSetup.update(extra.signal) : await this.blenderSetup.check();
|
|
@@ -5145,6 +5177,10 @@ class BambuPrinterMCPServer {
|
|
|
5145
5177
|
return { content: [{ type: "text", text }] };
|
|
5146
5178
|
|
|
5147
5179
|
} catch (error) {
|
|
5180
|
+
if (name.startsWith("cad_")) {
|
|
5181
|
+
const failure = await this.cad.failure(error, name);
|
|
5182
|
+
return {isError: true, content: [{type: "text" as const, text: failure.message}], structuredContent: failure};
|
|
5183
|
+
}
|
|
5148
5184
|
const message = error instanceof Error ? error.message : String(error);
|
|
5149
5185
|
// Refusals and printer rejections repeat unchanged; say what to fix instead of "try again".
|
|
5150
5186
|
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/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)) {
|
package/src/tool-annotations.ts
CHANGED
|
@@ -34,6 +34,10 @@ const START_PRINT = hints(false, false, false, true);
|
|
|
34
34
|
const SLICE_AND_PRINT = hints(false, true, false, true);
|
|
35
35
|
|
|
36
36
|
export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
|
|
37
|
+
cad_status: READ_LOCAL,
|
|
38
|
+
cad_setup: hints(false, true, true, true),
|
|
39
|
+
cad_run: hints(false, false, false, false),
|
|
40
|
+
cad_check_fit: READ_LOCAL,
|
|
37
41
|
// Printer and cloud reads
|
|
38
42
|
get_printer_status: READ_OUTSIDE,
|
|
39
43
|
get_printer_filaments: READ_OUTSIDE,
|