bambu-printer-mcp 1.1.92 → 1.1.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/counterpart/info.d.ts +2 -0
- package/dist/counterpart/info.js +6 -1
- package/dist/counterpart/remote.js +1 -0
- package/dist/counterpart/schemas.d.ts +5 -0
- package/dist/counterpart/schemas.js +1 -0
- package/dist/counterpart/self-check.d.ts +79 -0
- package/dist/counterpart/self-check.js +163 -0
- package/dist/index.js +11 -1
- package/dist/printers/bambu.js +27 -19
- package/dist/printers/report-merge.d.ts +12 -0
- package/dist/printers/report-merge.js +46 -0
- package/dist/stl/stl-manipulator.js +79 -20
- package/dist/tool-annotations.js +1 -0
- package/package.json +6 -1
- package/src/counterpart/info.ts +7 -1
- package/src/counterpart/remote.ts +1 -0
- package/src/counterpart/schemas.ts +3 -1
- package/src/counterpart/self-check.ts +164 -0
- package/src/index.ts +12 -1
- package/src/printers/bambu.ts +27 -19
- package/src/printers/report-merge.ts +48 -0
- package/src/stl/stl-manipulator.ts +75 -14
- package/src/tool-annotations.ts +1 -0
package/README.md
CHANGED
|
@@ -1133,7 +1133,9 @@ If the project does not match those assumptions, the tool fails fast with a stru
|
|
|
1133
1133
|
|
|
1134
1134
|
[Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. Other tools return an error's details in `structuredContent` (`status`, `retryable`, `suggestion`, `message`). When the printer refuses a print, the error also carries a stable `code`: `printer-command-rejected`, `printer-not-ready`, or `printer-upload-failed` when the file didn't reach the printer and no print command was sent, so a client can act on the code rather than the wording. A `print_3mf` call made with a progress token reports its LAN upload as MCP progress: `progress` is bytes sent, `total` the file's bytes, and `_meta["counterpart/stage"]` is `"upload"`, at most once per whole percent. `counterpart_printer_info` reports `capabilities.slicing` (`supports`, `copies`, `orient`), so a client can offer those choices without knowing the slicer. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
|
|
1135
1135
|
|
|
1136
|
-
- **`counterpart_printer_info`** returns `{contract, server: {name, version}, printer: {kind: "bambu", model, serial, host}, capabilities}`. `capabilities` lists progress, layers, the camera transport (`bambu-tcp` for A1/P1, `rtsp` for X1, P2S, H2 and X2D, `none` without a model), `cameraStream: true` for supported camera models, `filaments: "ams"`, pause, resume, cancel, `print3mf` and `gcode` (false on X2D). It sends nothing to the printer and never returns the access code.
|
|
1136
|
+
- **`counterpart_printer_info`** returns `{contract, server: {name, version}, printer: {kind: "bambu", model, displayName, serial, host}, capabilities}`. `displayName` is the model with its maker ("Bambu Lab P1S"), to show as given; it and `model` are absent when the model is unknown. `capabilities` lists progress, layers, the camera transport (`bambu-tcp` for A1/P1, `rtsp` for X1, P2S, H2 and X2D, `none` without a model), `cameraStream: true` for supported camera models, `filaments: "ams"`, pause, resume, cancel, `print3mf` and `gcode` (false on X2D). It sends nothing to the printer and never returns the access code.
|
|
1137
|
+
- **`counterpart_self_check`** returns `{contract, server: {name, version}, ok, checks: [{name, ok, version?, message?}]}`: one check that the running server is its installed package's version, one per runtime dependency in `package.json` (it resolves from this install and loads, and the installed version meets an exact pin, `^` or `~` range), and `bambu-node patch`: every hunk of the bundled patch is in the installed bambu-node (a read-only reverse dry run, as postinstall checks), and it reads an H2D version report in memory as only the patched module can. Run it after an update; `ok` is false when any check fails. It sends nothing to the printer.
|
|
1138
|
+
- **`package.json` `counterpart`**: `{contract: "counterpart/1", notes, autoUpdate}`, readable with `npm view bambu-printer-mcp counterpart` before a client downloads a version. `notes` is one sentence about that release; `autoUpdate: false` asks clients not to install it automatically.
|
|
1137
1139
|
- **`counterpart_print_route`** reads or changes how prints and Stop/Pause/Resume reach the printer: `{route, mode, type, choices, savedTo}`, where `route` is `lan` (the local network, in the configured `BAMBU_DEFAULT_CONNECTION_MODE`) or `cloud` (Bambu Cloud through the [FULU bridge](docs/FULU.md)). Pass `route` to change it; the next print and control use it at once, and it is written to the `.env` in the server's working directory when one exists (`savedTo`, otherwise `null`). It is not part of the shared contract: it has no `outputSchema`, and mcp-3D-printer-server has no Bambu Cloud route.
|
|
1138
1140
|
- **`counterpart_print_progress`** returns `{contract, observedAt, state, job?, temps?, activeFilament?, problems}` from the printer's MQTT reports, which this server keeps while it is connected. A held session is answered from that cache without any printer traffic, and `observedAt` is when the printer sent the report. The server asks the printer for a full report only to fill an empty cache, and at most once every five minutes after the printer has been quiet that long. A printer that sends no report within 8 seconds is `offline`.
|
|
1139
1141
|
- `state`: `IDLE` is `idle`, `PREPARE`/`SLICING` `preparing`, `RUNNING` `printing`, `PAUSE` `paused`, `FINISH` `finished` and `FAILED` `failed`. A `FAILED` job with `0300400C` ("The task was canceled.") in `print_error`, or in X2D's `fail_reason`, is `cancelled`. Any other or missing `gcode_state` on a connected printer is `busy`.
|
|
@@ -10,6 +10,8 @@ export declare function bambuSliceCapabilities(slicerType: string | undefined):
|
|
|
10
10
|
copies: boolean;
|
|
11
11
|
orient: boolean;
|
|
12
12
|
};
|
|
13
|
+
/** The maker's own name for this model ("Bambu Lab P1S"), so a client shows it as given and composes nothing. */
|
|
14
|
+
export declare const BAMBU_MAKER = "Bambu Lab";
|
|
13
15
|
export declare function bambuPrinterInfo(options: {
|
|
14
16
|
server: {
|
|
15
17
|
name: string;
|
package/dist/counterpart/info.js
CHANGED
|
@@ -19,15 +19,20 @@ export function bambuSliceCapabilities(slicerType) {
|
|
|
19
19
|
return { supports: true, copies: false, orient: true };
|
|
20
20
|
return { supports: false, copies: false, orient: false };
|
|
21
21
|
}
|
|
22
|
+
/** The maker's own name for this model ("Bambu Lab P1S"), so a client shows it as given and composes nothing. */
|
|
23
|
+
export const BAMBU_MAKER = "Bambu Lab";
|
|
22
24
|
export function bambuPrinterInfo(options) {
|
|
23
25
|
const model = normalizeModel(options.model);
|
|
26
|
+
const named = model ? DISPLAY_NAMES.get(model) : undefined;
|
|
24
27
|
const serial = options.serial?.trim();
|
|
25
28
|
return {
|
|
26
29
|
contract: COUNTERPART_CONTRACT,
|
|
27
30
|
server: options.server,
|
|
28
31
|
printer: {
|
|
29
32
|
kind: "bambu",
|
|
30
|
-
...(model ? { model:
|
|
33
|
+
...(model ? { model: named ?? model.toUpperCase() } : {}),
|
|
34
|
+
// Only a name Bambu gives the model; nothing is composed from another value.
|
|
35
|
+
...(named ? { displayName: `${BAMBU_MAKER} ${named}` } : {}),
|
|
31
36
|
...(serial ? { serial } : {}),
|
|
32
37
|
host: options.host,
|
|
33
38
|
},
|
|
@@ -17,6 +17,7 @@ export const REMOTE_SCOPES = {
|
|
|
17
17
|
inspect_print_file: "read",
|
|
18
18
|
blender_mcp_status: "read",
|
|
19
19
|
counterpart_printer_info: "read",
|
|
20
|
+
counterpart_self_check: "read",
|
|
20
21
|
counterpart_print_progress: "read",
|
|
21
22
|
counterpart_print_record: "read",
|
|
22
23
|
counterpart_print_assess: "control", // local evidence mutation, never a printer command
|
|
@@ -54,9 +54,11 @@ export type PrinterInfo = {
|
|
|
54
54
|
name: string;
|
|
55
55
|
version: string;
|
|
56
56
|
};
|
|
57
|
+
/** displayName: the model with its maker ("Bambu Lab P1S"), shown as given; absent when the model is unknown. */
|
|
57
58
|
printer: {
|
|
58
59
|
kind: typeof PRINTER_KINDS[number];
|
|
59
60
|
model?: string;
|
|
61
|
+
displayName?: string;
|
|
60
62
|
serial?: string;
|
|
61
63
|
host: string;
|
|
62
64
|
name?: string;
|
|
@@ -117,6 +119,9 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
|
|
|
117
119
|
model: {
|
|
118
120
|
type: string;
|
|
119
121
|
};
|
|
122
|
+
displayName: {
|
|
123
|
+
type: string;
|
|
124
|
+
};
|
|
120
125
|
serial: {
|
|
121
126
|
type: string;
|
|
122
127
|
};
|
|
@@ -28,6 +28,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
|
|
|
28
28
|
properties: {
|
|
29
29
|
kind: { type: "string", enum: [...PRINTER_KINDS] },
|
|
30
30
|
model: { type: "string" },
|
|
31
|
+
displayName: { type: "string" },
|
|
31
32
|
serial: { type: "string" },
|
|
32
33
|
host: { type: "string" },
|
|
33
34
|
name: { type: "string" },
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
2
|
+
/** optional: an optional dependency, whose failure does not make ok false (mcp-3D-printer-server has one; this server none). */
|
|
3
|
+
export type SelfCheck = {
|
|
4
|
+
name: string;
|
|
5
|
+
ok: boolean;
|
|
6
|
+
optional?: boolean;
|
|
7
|
+
version?: string;
|
|
8
|
+
message?: string;
|
|
9
|
+
};
|
|
10
|
+
export type SelfCheckResult = {
|
|
11
|
+
contract: typeof COUNTERPART_CONTRACT;
|
|
12
|
+
server: {
|
|
13
|
+
name: string;
|
|
14
|
+
version: string;
|
|
15
|
+
};
|
|
16
|
+
ok: boolean;
|
|
17
|
+
checks: SelfCheck[];
|
|
18
|
+
};
|
|
19
|
+
export declare const SELF_CHECK_OUTPUT_SCHEMA: {
|
|
20
|
+
type: "object";
|
|
21
|
+
properties: {
|
|
22
|
+
contract: {
|
|
23
|
+
type: string;
|
|
24
|
+
const: string;
|
|
25
|
+
};
|
|
26
|
+
server: {
|
|
27
|
+
type: string;
|
|
28
|
+
properties: {
|
|
29
|
+
name: {
|
|
30
|
+
type: string;
|
|
31
|
+
};
|
|
32
|
+
version: {
|
|
33
|
+
type: string;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
required: string[];
|
|
37
|
+
};
|
|
38
|
+
ok: {
|
|
39
|
+
type: string;
|
|
40
|
+
description: string;
|
|
41
|
+
};
|
|
42
|
+
checks: {
|
|
43
|
+
type: string;
|
|
44
|
+
items: {
|
|
45
|
+
type: string;
|
|
46
|
+
properties: {
|
|
47
|
+
name: {
|
|
48
|
+
type: string;
|
|
49
|
+
};
|
|
50
|
+
ok: {
|
|
51
|
+
type: string;
|
|
52
|
+
};
|
|
53
|
+
optional: {
|
|
54
|
+
type: string;
|
|
55
|
+
};
|
|
56
|
+
version: {
|
|
57
|
+
type: string;
|
|
58
|
+
};
|
|
59
|
+
message: {
|
|
60
|
+
type: string;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
required: string[];
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
required: string[];
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Whether version meets declared, for the forms package.json uses: x.y.z exactly, ^x.y.z (the leftmost non-zero
|
|
71
|
+
* part stays) or ~x.y.z (the minor stays). Other forms are not judged (undefined).
|
|
72
|
+
*/
|
|
73
|
+
export declare function meetsDeclared(version: string, declared: string): boolean | undefined;
|
|
74
|
+
/** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
|
|
75
|
+
export declare function versionProblem(name: string, version: string | undefined, declared: string): string | undefined;
|
|
76
|
+
export declare function selfCheck(server: {
|
|
77
|
+
name: string;
|
|
78
|
+
version: string;
|
|
79
|
+
}): Promise<SelfCheckResult>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_self_check (counterpart/1): whether this install's own runtime dependencies and the bundled bambu-node
|
|
3
|
+
* patch loaded, so a client that updated the server can tell a broken install from a working one. Local only: it
|
|
4
|
+
* loads modules from this server's own install and sends nothing to a printer.
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
11
|
+
export const SELF_CHECK_OUTPUT_SCHEMA = {
|
|
12
|
+
type: "object",
|
|
13
|
+
properties: {
|
|
14
|
+
contract: { type: "string", const: COUNTERPART_CONTRACT },
|
|
15
|
+
server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
|
|
16
|
+
ok: { type: "boolean", description: "Every check passed, optional dependencies aside." },
|
|
17
|
+
checks: {
|
|
18
|
+
type: "array",
|
|
19
|
+
items: {
|
|
20
|
+
type: "object",
|
|
21
|
+
properties: { name: { type: "string" }, ok: { type: "boolean" }, optional: { type: "boolean" }, version: { type: "string" }, message: { type: "string" } },
|
|
22
|
+
required: ["name", "ok"],
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
required: ["contract", "server", "ok", "checks"],
|
|
27
|
+
};
|
|
28
|
+
const PACKAGE_JSON = new URL("../../package.json", import.meta.url);
|
|
29
|
+
/** The module each dependency is loaded through, where its package root is not importable on its own. */
|
|
30
|
+
const ENTRIES = {
|
|
31
|
+
"@modelcontextprotocol/sdk": "@modelcontextprotocol/sdk/server/index.js",
|
|
32
|
+
// Only its patch parser runs, at install (scripts/install-patches.mjs); its root is the CLI.
|
|
33
|
+
"patch-package": "patch-package/dist/patch/parse.js",
|
|
34
|
+
};
|
|
35
|
+
/** The version in the package.json of name that contains file, from this install. */
|
|
36
|
+
function installedVersion(file, name) {
|
|
37
|
+
for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) {
|
|
38
|
+
const manifest = path.join(dir, "package.json");
|
|
39
|
+
if (!fs.existsSync(manifest))
|
|
40
|
+
continue;
|
|
41
|
+
try {
|
|
42
|
+
const parsed = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
43
|
+
if (parsed?.name === name)
|
|
44
|
+
return typeof parsed.version === "string" ? parsed.version : undefined;
|
|
45
|
+
}
|
|
46
|
+
catch { /* a malformed manifest is not this package's */ }
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
/** The file specifier resolves to from this module (import.meta.resolve needs Node.js 18.19 or 20.6; older ones require). */
|
|
51
|
+
function resolveFromHere(specifier) {
|
|
52
|
+
return typeof import.meta.resolve === "function"
|
|
53
|
+
? fileURLToPath(import.meta.resolve(specifier))
|
|
54
|
+
: createRequire(import.meta.url).resolve(specifier);
|
|
55
|
+
}
|
|
56
|
+
const message = (error) => error instanceof Error ? error.message : String(error);
|
|
57
|
+
/**
|
|
58
|
+
* Whether version meets declared, for the forms package.json uses: x.y.z exactly, ^x.y.z (the leftmost non-zero
|
|
59
|
+
* part stays) or ~x.y.z (the minor stays). Other forms are not judged (undefined).
|
|
60
|
+
*/
|
|
61
|
+
export function meetsDeclared(version, declared) {
|
|
62
|
+
const want = /^([~^]?)(\d+)\.(\d+)\.(\d+)$/.exec(declared.trim());
|
|
63
|
+
const have = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version);
|
|
64
|
+
if (!want || !have)
|
|
65
|
+
return undefined;
|
|
66
|
+
// A prerelease (3.22.21-beta.1) meets none of these forms.
|
|
67
|
+
if (have[4])
|
|
68
|
+
return false;
|
|
69
|
+
const [w0, w1, w2] = want.slice(2).map(Number), [h0, h1, h2] = have.slice(1, 4).map(Number);
|
|
70
|
+
const order = h0 - w0 || h1 - w1 || h2 - w2;
|
|
71
|
+
if (want[1] === "")
|
|
72
|
+
return order === 0;
|
|
73
|
+
if (order < 0)
|
|
74
|
+
return false;
|
|
75
|
+
if (want[1] === "~")
|
|
76
|
+
return h0 === w0 && h1 === w1;
|
|
77
|
+
return w0 > 0 ? h0 === w0 : w1 > 0 ? h0 === 0 && h1 === w1 : h0 === 0 && h1 === 0 && h2 === w2;
|
|
78
|
+
}
|
|
79
|
+
/** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
|
|
80
|
+
export function versionProblem(name, version, declared) {
|
|
81
|
+
const meets = meetsDeclared(version ?? "", declared);
|
|
82
|
+
if (meets === true)
|
|
83
|
+
return undefined;
|
|
84
|
+
if (meets === undefined && version !== undefined)
|
|
85
|
+
return `This check cannot judge ${name}'s declared version "${declared}"; ${version} is installed.`;
|
|
86
|
+
return `This server needs ${name} ${declared}; ${version ?? "an unknown version"} is installed.`;
|
|
87
|
+
}
|
|
88
|
+
/** One dependency: it resolves from this install, loads, and its installed version meets package.json's. */
|
|
89
|
+
async function dependencyCheck(name, declared) {
|
|
90
|
+
const specifier = ENTRIES[name] ?? name;
|
|
91
|
+
try {
|
|
92
|
+
const file = resolveFromHere(specifier);
|
|
93
|
+
const version = installedVersion(file, name);
|
|
94
|
+
await import(specifier);
|
|
95
|
+
const problem = versionProblem(name, version, declared);
|
|
96
|
+
if (problem)
|
|
97
|
+
return { name, ok: false, ...(version ? { version } : {}), message: problem };
|
|
98
|
+
return { name, ok: true, ...(version ? { version } : {}) };
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
return { name, ok: false, message: `${name} did not load: ${message(error)}` };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Every hunk of the bundled patch is in the installed bambu-node: a read-only reverse dry run, as postinstall checks. */
|
|
105
|
+
function patchApplied(version) {
|
|
106
|
+
const require = createRequire(import.meta.url);
|
|
107
|
+
const root = fs.realpathSync(path.dirname(require.resolve("bambu-node/package.json")));
|
|
108
|
+
const { parsePatchFile } = require("patch-package/dist/patch/parse.js");
|
|
109
|
+
const { executeEffects } = require("patch-package/dist/patch/apply.js");
|
|
110
|
+
const { reversePatch } = require("patch-package/dist/patch/reverse.js");
|
|
111
|
+
const patch = fs.readFileSync(new URL(`../../patches/bambu-node+${version}.patch`, import.meta.url), "utf8");
|
|
112
|
+
const effects = parsePatchFile(patch).map((effect) => {
|
|
113
|
+
if (effect.type !== "patch" || !effect.path.startsWith("node_modules/bambu-node/"))
|
|
114
|
+
throw new Error("the bundled patch has an unexpected target");
|
|
115
|
+
return { ...effect, path: effect.path.slice("node_modules/bambu-node/".length) };
|
|
116
|
+
});
|
|
117
|
+
try {
|
|
118
|
+
executeEffects(reversePatch(effects), { cwd: root, dryRun: true, bestEffort: false });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
throw new Error(`the installed bambu-node ${version} is missing part of this server's patch`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The bundled patch (patches/bambu-node+<version>.patch) is in the installed bambu-node, and the loaded module
|
|
126
|
+
* behaves patched: it adds the H2-series and later printers to model detection, so an unpatched bambu-node throws
|
|
127
|
+
* "Printer model not supported!" on an H2D's version report. The report is read in memory, without a connection.
|
|
128
|
+
*/
|
|
129
|
+
async function bambuNodePatchCheck(version) {
|
|
130
|
+
const name = "bambu-node patch";
|
|
131
|
+
try {
|
|
132
|
+
if (!version)
|
|
133
|
+
throw new Error("package.json names no bambu-node version");
|
|
134
|
+
patchApplied(version);
|
|
135
|
+
const { BambuClient } = await import("bambu-node");
|
|
136
|
+
const serial = "094SELFCHECK";
|
|
137
|
+
const client = new BambuClient({ host: "127.0.0.1", serialNumber: serial, accessToken: "self-check" });
|
|
138
|
+
await client.onMessage(JSON.stringify({ info: { command: "get_version", module: [{ name: "ota", sn: serial }] } }), `device/${serial}/report`);
|
|
139
|
+
const model = client.data?.model;
|
|
140
|
+
return model === "H2D" ? { name, ok: true } : { name, ok: false, message: `bambu-node read an H2D as ${String(model)}; reinstall this server so its patch is applied.` };
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
return { name, ok: false, message: `bambu-node is not patched: ${message(error)}. Reinstall this server so its patch is applied.` };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
export async function selfCheck(server) {
|
|
147
|
+
let dependencies = {};
|
|
148
|
+
const checks = [];
|
|
149
|
+
try {
|
|
150
|
+
const manifest = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8"));
|
|
151
|
+
dependencies = manifest.dependencies ?? {};
|
|
152
|
+
if (manifest.version !== server.version)
|
|
153
|
+
checks.push({ name: "package", ok: false, version: String(manifest.version), message: `The running server is ${server.version}, but its install is ${manifest.version}; restart it.` });
|
|
154
|
+
else
|
|
155
|
+
checks.push({ name: "package", ok: true, version: server.version });
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
checks.push({ name: "package", ok: false, message: `Could not read this server's package.json: ${message(error)}` });
|
|
159
|
+
}
|
|
160
|
+
checks.push(...await Promise.all(Object.entries(dependencies).map(([name, declared]) => dependencyCheck(name, declared))));
|
|
161
|
+
checks.push(await bambuNodePatchCheck(dependencies["bambu-node"]));
|
|
162
|
+
return { contract: COUNTERPART_CONTRACT, server, ok: checks.every(check => check.ok || check.optional), checks };
|
|
163
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -57,6 +57,7 @@ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_C
|
|
|
57
57
|
import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
|
|
58
58
|
import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
|
|
59
59
|
import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
|
|
60
|
+
import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
|
|
60
61
|
import { parseProcessOverrides } from "./slicer/process-overrides.js";
|
|
61
62
|
import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
|
|
62
63
|
import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
|
|
@@ -125,7 +126,7 @@ const SERVER_INFO = {
|
|
|
125
126
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
126
127
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
127
128
|
"cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
|
|
128
|
-
"counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
|
|
129
|
+
"counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
|
|
129
130
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
130
131
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
131
132
|
"camera_stream_start", "camera_frame", "camera_stream_stop",
|
|
@@ -3058,6 +3059,12 @@ class BambuPrinterMCPServer {
|
|
|
3058
3059
|
},
|
|
3059
3060
|
outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
|
|
3060
3061
|
},
|
|
3062
|
+
{
|
|
3063
|
+
name: "counterpart_self_check",
|
|
3064
|
+
description: "Counterpart contract (counterpart/1): whether this install's own runtime dependencies and its bundled bambu-node patch loaded, each with its installed version. Run it after an update; ok is false when a check failed, with a message saying which. Sends nothing to the printer.",
|
|
3065
|
+
inputSchema: { type: "object", properties: {} },
|
|
3066
|
+
outputSchema: SELF_CHECK_OUTPUT_SCHEMA
|
|
3067
|
+
},
|
|
3061
3068
|
{
|
|
3062
3069
|
name: "counterpart_discover_printers",
|
|
3063
3070
|
description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
|
|
@@ -4375,6 +4382,9 @@ class BambuPrinterMCPServer {
|
|
|
4375
4382
|
sliced: args?.sliced === true, names: colourNames() });
|
|
4376
4383
|
break;
|
|
4377
4384
|
}
|
|
4385
|
+
case "counterpart_self_check":
|
|
4386
|
+
result = await selfCheck(SERVER_INFO);
|
|
4387
|
+
break;
|
|
4378
4388
|
case "counterpart_printer_info":
|
|
4379
4389
|
result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
|
|
4380
4390
|
break;
|
package/dist/printers/bambu.js
CHANGED
|
@@ -23,6 +23,7 @@ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
|
|
|
23
23
|
import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount } from "../studio-print-options.js";
|
|
24
24
|
import { Client as FTPClient } from "basic-ftp";
|
|
25
25
|
import { uploadBytes } from "./ftp-upload.js";
|
|
26
|
+
import { mergeBambuReport } from "./report-merge.js";
|
|
26
27
|
import * as mqtt from "mqtt";
|
|
27
28
|
import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, } from "bambu-node";
|
|
28
29
|
/**
|
|
@@ -355,11 +356,34 @@ class BambuClientStore {
|
|
|
355
356
|
if (!update || Object.keys(update).length === 0) {
|
|
356
357
|
return;
|
|
357
358
|
}
|
|
358
|
-
|
|
359
|
-
this.reportSnapshots.set(key, { ...previous, ...update });
|
|
359
|
+
this.reportSnapshots.set(key, mergeBambuReport(this.reportSnapshots.get(key), update));
|
|
360
360
|
this.reportTimes.set(key, Date.now());
|
|
361
361
|
this.resolveInitialReport(key);
|
|
362
362
|
}
|
|
363
|
+
/** Merges the printer's reports into its snapshot as they arrive (tests feed a client without a connection). */
|
|
364
|
+
watchReports(printer, host, serial, key) {
|
|
365
|
+
printer.on("rawMessage", (_topic, payload) => {
|
|
366
|
+
try {
|
|
367
|
+
const parsed = JSON.parse(payload.toString());
|
|
368
|
+
const printMessage = parsed?.print;
|
|
369
|
+
if (printMessage && typeof printMessage === "object") {
|
|
370
|
+
this.updateReportSnapshot(key, printMessage);
|
|
371
|
+
this.reportObserved(host, serial, key);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
// Ignore unrelated payloads.
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
// bambu-node passes its whole merged report and then what changed. Only the change is merged here, so a field the
|
|
379
|
+
// printer has not sent again (the previous job's layer) is not copied back over this merge's own reset.
|
|
380
|
+
printer.on("printer:dataUpdate", (_data, changed) => {
|
|
381
|
+
if (!changed || typeof changed !== "object")
|
|
382
|
+
return;
|
|
383
|
+
this.updateReportSnapshot(key, changed);
|
|
384
|
+
this.reportObserved(host, serial, key);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
363
387
|
reportObserved(host, serial, key) {
|
|
364
388
|
const report = this.reportSnapshots.get(key);
|
|
365
389
|
if (!report || !this.onReport)
|
|
@@ -447,23 +471,7 @@ class BambuClientStore {
|
|
|
447
471
|
accessToken: token,
|
|
448
472
|
});
|
|
449
473
|
this.ensureInitialReportPromise(key);
|
|
450
|
-
|
|
451
|
-
try {
|
|
452
|
-
const parsed = JSON.parse(payload.toString());
|
|
453
|
-
const printMessage = parsed?.print;
|
|
454
|
-
if (printMessage && typeof printMessage === "object") {
|
|
455
|
-
this.updateReportSnapshot(key, printMessage);
|
|
456
|
-
this.reportObserved(host, serial, key);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
catch {
|
|
460
|
-
// Ignore unrelated payloads.
|
|
461
|
-
}
|
|
462
|
-
});
|
|
463
|
-
printer.on("printer:dataUpdate", (data) => {
|
|
464
|
-
this.updateReportSnapshot(key, data);
|
|
465
|
-
this.reportObserved(host, serial, key);
|
|
466
|
-
});
|
|
474
|
+
this.watchReports(printer, host, serial, key);
|
|
467
475
|
printer.on("client:connect", () => {
|
|
468
476
|
this.printers.set(key, printer);
|
|
469
477
|
this.initialConnectionPromises.delete(key);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merging Bambu MQTT reports. P1/A1 printers push only what changed, so a merged report keeps every field until the
|
|
3
|
+
* printer sends it again. A new job's first pushes can carry its name and layer count before its layer number, and the
|
|
4
|
+
* previous job's last layer then read against the new total ("315/150"). Until the new job reports its own progress,
|
|
5
|
+
* its report has none.
|
|
6
|
+
*/
|
|
7
|
+
/** True when update describes a different job than the report merged before it. */
|
|
8
|
+
export declare function startsNewJob(previous: Record<string, any> | undefined, update: Record<string, any>): boolean;
|
|
9
|
+
/** The previous job's progress fields to leave out when update starts a new job without reporting them. */
|
|
10
|
+
export declare function newJobResets(previous: Record<string, any> | undefined, update: Record<string, any>): string[];
|
|
11
|
+
/** previous merged with update, without the previous job's progress when update starts a new one (newJobResets). */
|
|
12
|
+
export declare function mergeBambuReport(previous: Record<string, any> | undefined, update: Record<string, any>): Record<string, any>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merging Bambu MQTT reports. P1/A1 printers push only what changed, so a merged report keeps every field until the
|
|
3
|
+
* printer sends it again. A new job's first pushes can carry its name and layer count before its layer number, and the
|
|
4
|
+
* previous job's last layer then read against the new total ("315/150"). Until the new job reports its own progress,
|
|
5
|
+
* its report has none.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Fields that name the job a report describes. The layer count is not one: a running job's count can be revised, and a
|
|
9
|
+
* different job differs in its name, file or task id.
|
|
10
|
+
*/
|
|
11
|
+
const JOB_FIELDS = ["subtask_name", "gcode_file", "task_id"];
|
|
12
|
+
/** A new job prepares (PREPARE, SLICING) after any end; RUNNING straight after FAILED is that job resuming. */
|
|
13
|
+
const PREPARING = new Set(["PREPARE", "SLICING"]);
|
|
14
|
+
const DONE = new Set(["FINISH", "IDLE"]);
|
|
15
|
+
/** The previous job's progress, left out of a new job's report until the printer reports the new job's own. */
|
|
16
|
+
const JOB_PROGRESS = ["layer_num", "mc_percent", "mc_remaining_time"];
|
|
17
|
+
/** A job field's value, or undefined for a placeholder: empty, or 0 (LAN prints report task_id "0"). */
|
|
18
|
+
function named(value) {
|
|
19
|
+
const text = value === undefined || value === null ? "" : String(value).trim();
|
|
20
|
+
return text === "" || text === "0" ? undefined : text;
|
|
21
|
+
}
|
|
22
|
+
/** True when update describes a different job than the report merged before it. */
|
|
23
|
+
export function startsNewJob(previous, update) {
|
|
24
|
+
if (!previous)
|
|
25
|
+
return false;
|
|
26
|
+
for (const field of JOB_FIELDS) {
|
|
27
|
+
const before = named(previous[field]), after = named(update[field]);
|
|
28
|
+
if (before !== undefined && after !== undefined && before !== after)
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
const before = String(previous.gcode_state), after = String(update.gcode_state);
|
|
32
|
+
return (DONE.has(before) || before === "FAILED") && PREPARING.has(after) || DONE.has(before) && after === "RUNNING";
|
|
33
|
+
}
|
|
34
|
+
/** The previous job's progress fields to leave out when update starts a new job without reporting them. */
|
|
35
|
+
export function newJobResets(previous, update) {
|
|
36
|
+
if (!startsNewJob(previous, update))
|
|
37
|
+
return [];
|
|
38
|
+
return JOB_PROGRESS.filter(field => update[field] === undefined && previous?.[field] !== undefined);
|
|
39
|
+
}
|
|
40
|
+
/** previous merged with update, without the previous job's progress when update starts a new one (newJobResets). */
|
|
41
|
+
export function mergeBambuReport(previous, update) {
|
|
42
|
+
const merged = { ...previous, ...update };
|
|
43
|
+
for (const field of newJobResets(previous, update))
|
|
44
|
+
delete merged[field];
|
|
45
|
+
return merged;
|
|
46
|
+
}
|
|
@@ -10,7 +10,7 @@ import path from 'path';
|
|
|
10
10
|
import { promisify } from 'util';
|
|
11
11
|
import { EventEmitter } from 'events';
|
|
12
12
|
import * as crypto from 'crypto';
|
|
13
|
-
import {
|
|
13
|
+
import { spawn } from 'child_process';
|
|
14
14
|
import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
|
|
15
15
|
import { listModelPlates } from '../counterpart/model-plates.js';
|
|
16
16
|
import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
|
|
@@ -169,6 +169,32 @@ function slicerResultText(result) {
|
|
|
169
169
|
...plates.map(plate => plate && typeof plate === "object" ? plate.warning_message : undefined),
|
|
170
170
|
].filter((text) => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
|
|
171
171
|
}
|
|
172
|
+
/** The output kept from each stream, as execFile's default maxBuffer; the rest is dropped, not failed. */
|
|
173
|
+
const SLICER_OUTPUT_LIMIT = 1024 * 1024;
|
|
174
|
+
/**
|
|
175
|
+
* execFile for the slicer, with detached passed through (execFile drops it): on POSIX the slicer then leads its own
|
|
176
|
+
* process group, so a cancel can stop the helpers it starts too. The callback gets what execFile's would.
|
|
177
|
+
*/
|
|
178
|
+
function execSlicer(file, args, env, detached, callback) {
|
|
179
|
+
// stdin is ignored, as execFile ends it: no slicer reads it.
|
|
180
|
+
const child = spawn(file, args, { ...(env ? { env } : {}), detached, stdio: ["ignore", "pipe", "pipe"] });
|
|
181
|
+
let stdout = "", stderr = "", settled = false;
|
|
182
|
+
const keep = (text, chunk) => text.length >= SLICER_OUTPUT_LIMIT ? text : (text + chunk.toString("utf8")).slice(0, SLICER_OUTPUT_LIMIT);
|
|
183
|
+
child.stdout?.on("data", (chunk) => { stdout = keep(stdout, chunk); });
|
|
184
|
+
child.stderr?.on("data", (chunk) => { stderr = keep(stderr, chunk); });
|
|
185
|
+
const finish = (error) => { if (!settled) {
|
|
186
|
+
settled = true;
|
|
187
|
+
callback(error, stdout, stderr);
|
|
188
|
+
} };
|
|
189
|
+
child.on("error", error => finish(Object.assign(error, { cmd: [file, ...args].join(" ") })));
|
|
190
|
+
child.on("close", (code, signal) => {
|
|
191
|
+
if (code === 0 && !signal)
|
|
192
|
+
return finish(null);
|
|
193
|
+
const cmd = [file, ...args].join(" ");
|
|
194
|
+
finish(Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, signal, killed: child.killed, cmd }));
|
|
195
|
+
});
|
|
196
|
+
return child;
|
|
197
|
+
}
|
|
172
198
|
function describeSlicerFailure(error, stdout, stderr, cli) {
|
|
173
199
|
const status = typeof error.signal === "string" && error.signal
|
|
174
200
|
? `crashed with ${error.signal}`
|
|
@@ -1667,11 +1693,19 @@ export class STLManipulator extends EventEmitter {
|
|
|
1667
1693
|
const launch = await prepareSlicerLaunch(slicerType, this.tempDir);
|
|
1668
1694
|
const stallSeconds = launch.stallSeconds;
|
|
1669
1695
|
let stalled = false;
|
|
1696
|
+
let cancelled = false;
|
|
1670
1697
|
// Execute the slicer
|
|
1671
1698
|
try {
|
|
1672
1699
|
await new Promise((resolve, reject) => {
|
|
1673
|
-
|
|
1674
|
-
|
|
1700
|
+
// POSIX: the slicer leads its own process group, so stopping it also stops the helpers it starts.
|
|
1701
|
+
const group = globalThis.process.platform !== 'win32';
|
|
1702
|
+
const process = execSlicer(slicerPath, args, launch.env, group, (error, stdout, stderr) => {
|
|
1703
|
+
if (cancelled) {
|
|
1704
|
+
// Settled once the slicer and every process sharing its output have gone, so its folder is removed after
|
|
1705
|
+
// nothing can write to it.
|
|
1706
|
+
reject(new Error("Slicing operation cancelled"));
|
|
1707
|
+
}
|
|
1708
|
+
else if (stalled && error) {
|
|
1675
1709
|
reject(stalledSlicerError(slicerType, stallSeconds));
|
|
1676
1710
|
}
|
|
1677
1711
|
else if (error) {
|
|
@@ -1691,29 +1725,53 @@ export class STLManipulator extends EventEmitter {
|
|
|
1691
1725
|
// Optional: Add listeners for stdout/stderr for real-time progress if slicer provides it
|
|
1692
1726
|
// process.stdout?.on('data', (data) => { console.error(`Slicer stdout: ${data}`); });
|
|
1693
1727
|
// process.stderr?.on('data', (data) => { console.error(`Slicer stderr: ${data}`); });
|
|
1694
|
-
//
|
|
1728
|
+
// Stops the slicer and, on POSIX, its whole process group (a group already gone is not an error).
|
|
1729
|
+
const stop = (signal) => {
|
|
1730
|
+
try {
|
|
1731
|
+
if (group && process.pid !== undefined)
|
|
1732
|
+
globalThis.process.kill(-process.pid, signal);
|
|
1733
|
+
else
|
|
1734
|
+
process.kill(signal);
|
|
1735
|
+
}
|
|
1736
|
+
catch (killError) {
|
|
1737
|
+
if (killError.code !== 'ESRCH')
|
|
1738
|
+
console.error(`Could not send ${signal} to the slicer:`, killError);
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1741
|
+
// Check for cancellation periodically: the slicer is stopped, and the call settles when it has gone.
|
|
1742
|
+
let forceKill;
|
|
1743
|
+
let abandon;
|
|
1695
1744
|
const checkCancel = setInterval(() => {
|
|
1696
1745
|
if (!this.activeOperations.get(operationId)) {
|
|
1697
1746
|
clearInterval(checkCancel);
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1747
|
+
cancelled = true;
|
|
1748
|
+
stop('SIGTERM');
|
|
1749
|
+
// A slicer or helper that ignores SIGTERM is killed outright rather than waited on. A helper outside the
|
|
1750
|
+
// group (daemonized, or any helper on Windows) can still hold the output pipes, so 'close' never comes:
|
|
1751
|
+
// a second later the pipes are let go and the cancel settles.
|
|
1752
|
+
forceKill = setTimeout(() => {
|
|
1753
|
+
stop('SIGKILL');
|
|
1754
|
+
abandon = setTimeout(() => {
|
|
1755
|
+
process.stdout?.destroy();
|
|
1756
|
+
process.stderr?.destroy();
|
|
1757
|
+
reject(new Error("Slicing operation cancelled"));
|
|
1758
|
+
}, 1000);
|
|
1759
|
+
}, 5000);
|
|
1706
1760
|
}
|
|
1707
1761
|
}, 500);
|
|
1708
|
-
process.on('exit', () =>
|
|
1709
|
-
|
|
1762
|
+
process.on('exit', () => {
|
|
1763
|
+
// Exit can precede a client cancel while a helper retains output pipes; polling runs until close.
|
|
1764
|
+
// A helper that outlived the slicer still holds its output; finish it so the call can settle.
|
|
1765
|
+
if (cancelled && group)
|
|
1766
|
+
stop('SIGKILL');
|
|
1767
|
+
});
|
|
1768
|
+
// The deadline runs until every process sharing the slicer's output has let go, not only the slicer.
|
|
1769
|
+
process.on('close', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
|
|
1770
|
+
process.on('error', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
|
|
1710
1771
|
watchForStall(process, stallSeconds, () => {
|
|
1711
1772
|
stalled = true;
|
|
1712
1773
|
console.error(`${slicerType} used no CPU and wrote nothing for ${stallSeconds} s; stopping it as waiting on a dialog.`);
|
|
1713
|
-
|
|
1714
|
-
process.kill('SIGKILL');
|
|
1715
|
-
}
|
|
1716
|
-
catch { /* its exit is reported through the callback */ }
|
|
1774
|
+
stop('SIGKILL');
|
|
1717
1775
|
});
|
|
1718
1776
|
});
|
|
1719
1777
|
}
|
|
@@ -1753,8 +1811,9 @@ export class STLManipulator extends EventEmitter {
|
|
|
1753
1811
|
catch (error) {
|
|
1754
1812
|
console.error(`Slicing failed for ${stlFilePath}:`, error);
|
|
1755
1813
|
// Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
|
|
1756
|
-
if (sliceDir)
|
|
1757
|
-
await fs.promises.rm(sliceDir, { recursive: true, force: true }).
|
|
1814
|
+
if (sliceDir) {
|
|
1815
|
+
await fs.promises.rm(sliceDir, { recursive: true, force: true }).then(() => console.error(`Removed the folder of the failed or cancelled slice: ${sliceDir}`), removeError => console.error(`Could not remove the folder of the failed or cancelled slice ${sliceDir}:`, removeError));
|
|
1816
|
+
}
|
|
1758
1817
|
this.emit('operationError', {
|
|
1759
1818
|
operationId,
|
|
1760
1819
|
type: 'slice',
|
package/dist/tool-annotations.js
CHANGED
|
@@ -44,6 +44,7 @@ export const TOOL_ANNOTATIONS = {
|
|
|
44
44
|
list_templates: READ_LOCAL,
|
|
45
45
|
get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
|
|
46
46
|
counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
|
|
47
|
+
counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
|
|
47
48
|
counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
|
|
48
49
|
// Local outputs in the server's temporary directory
|
|
49
50
|
extend_stl_base: LOCAL_OUTPUT,
|
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bambu-printer-mcp",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.93",
|
|
4
4
|
"description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
|
|
5
|
+
"counterpart": {
|
|
6
|
+
"contract": "counterpart/1",
|
|
7
|
+
"notes": "Adds installation self-checks and printer names with their makers, and clears stale progress until the new job reports its own.",
|
|
8
|
+
"autoUpdate": true
|
|
9
|
+
},
|
|
5
10
|
"main": "dist/index.js",
|
|
6
11
|
"repository": {
|
|
7
12
|
"type": "git",
|
package/src/counterpart/info.ts
CHANGED
|
@@ -21,15 +21,21 @@ export function bambuSliceCapabilities(slicerType: string | undefined): { suppor
|
|
|
21
21
|
return { supports: false, copies: false, orient: false };
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/** The maker's own name for this model ("Bambu Lab P1S"), so a client shows it as given and composes nothing. */
|
|
25
|
+
export const BAMBU_MAKER = "Bambu Lab";
|
|
26
|
+
|
|
24
27
|
export function bambuPrinterInfo(options: { server: { name: string; version: string }; host: string; serial?: string; model?: string; slicerType?: string }): PrinterInfo {
|
|
25
28
|
const model = normalizeModel(options.model);
|
|
29
|
+
const named = model ? DISPLAY_NAMES.get(model) : undefined;
|
|
26
30
|
const serial = options.serial?.trim();
|
|
27
31
|
return {
|
|
28
32
|
contract: COUNTERPART_CONTRACT,
|
|
29
33
|
server: options.server,
|
|
30
34
|
printer: {
|
|
31
35
|
kind: "bambu",
|
|
32
|
-
...(model ? { model:
|
|
36
|
+
...(model ? { model: named ?? model.toUpperCase() } : {}),
|
|
37
|
+
// Only a name Bambu gives the model; nothing is composed from another value.
|
|
38
|
+
...(named ? { displayName: `${BAMBU_MAKER} ${named}` } : {}),
|
|
33
39
|
...(serial ? { serial } : {}),
|
|
34
40
|
host: options.host,
|
|
35
41
|
},
|
|
@@ -40,6 +40,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
|
|
|
40
40
|
inspect_print_file: "read",
|
|
41
41
|
blender_mcp_status: "read",
|
|
42
42
|
counterpart_printer_info: "read",
|
|
43
|
+
counterpart_self_check: "read",
|
|
43
44
|
counterpart_print_progress: "read",
|
|
44
45
|
counterpart_print_record: "read",
|
|
45
46
|
counterpart_print_assess: "control", // local evidence mutation, never a printer command
|
|
@@ -28,7 +28,8 @@ export type PrintProgress = {
|
|
|
28
28
|
export type PrinterInfo = {
|
|
29
29
|
contract: typeof COUNTERPART_CONTRACT;
|
|
30
30
|
server: { name: string; version: string };
|
|
31
|
-
|
|
31
|
+
/** displayName: the model with its maker ("Bambu Lab P1S"), shown as given; absent when the model is unknown. */
|
|
32
|
+
printer: { kind: typeof PRINTER_KINDS[number]; model?: string; displayName?: string; serial?: string; host: string; name?: string };
|
|
32
33
|
capabilities: {
|
|
33
34
|
cad?: {contract: string; status: string; setup: string; run: string; checkFit: string; prompt: string};
|
|
34
35
|
progress: boolean; layers: boolean;
|
|
@@ -61,6 +62,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
|
|
|
61
62
|
properties: {
|
|
62
63
|
kind: { type: "string", enum: [...PRINTER_KINDS] },
|
|
63
64
|
model: { type: "string" },
|
|
65
|
+
displayName: { type: "string" },
|
|
64
66
|
serial: { type: "string" },
|
|
65
67
|
host: { type: "string" },
|
|
66
68
|
name: { type: "string" },
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_self_check (counterpart/1): whether this install's own runtime dependencies and the bundled bambu-node
|
|
3
|
+
* patch loaded, so a client that updated the server can tell a broken install from a working one. Local only: it
|
|
4
|
+
* loads modules from this server's own install and sends nothing to a printer.
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
11
|
+
|
|
12
|
+
/** optional: an optional dependency, whose failure does not make ok false (mcp-3D-printer-server has one; this server none). */
|
|
13
|
+
export type SelfCheck = { name: string; ok: boolean; optional?: boolean; version?: string; message?: string };
|
|
14
|
+
export type SelfCheckResult = {
|
|
15
|
+
contract: typeof COUNTERPART_CONTRACT;
|
|
16
|
+
server: { name: string; version: string };
|
|
17
|
+
ok: boolean;
|
|
18
|
+
checks: SelfCheck[];
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const SELF_CHECK_OUTPUT_SCHEMA = {
|
|
22
|
+
type: "object" as const,
|
|
23
|
+
properties: {
|
|
24
|
+
contract: { type: "string", const: COUNTERPART_CONTRACT },
|
|
25
|
+
server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
|
|
26
|
+
ok: { type: "boolean", description: "Every check passed, optional dependencies aside." },
|
|
27
|
+
checks: {
|
|
28
|
+
type: "array",
|
|
29
|
+
items: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: { name: { type: "string" }, ok: { type: "boolean" }, optional: { type: "boolean" }, version: { type: "string" }, message: { type: "string" } },
|
|
32
|
+
required: ["name", "ok"],
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
required: ["contract", "server", "ok", "checks"],
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const PACKAGE_JSON = new URL("../../package.json", import.meta.url);
|
|
40
|
+
/** The module each dependency is loaded through, where its package root is not importable on its own. */
|
|
41
|
+
const ENTRIES: Record<string, string> = {
|
|
42
|
+
"@modelcontextprotocol/sdk": "@modelcontextprotocol/sdk/server/index.js",
|
|
43
|
+
// Only its patch parser runs, at install (scripts/install-patches.mjs); its root is the CLI.
|
|
44
|
+
"patch-package": "patch-package/dist/patch/parse.js",
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** The version in the package.json of name that contains file, from this install. */
|
|
48
|
+
function installedVersion(file: string, name: string): string | undefined {
|
|
49
|
+
for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) {
|
|
50
|
+
const manifest = path.join(dir, "package.json");
|
|
51
|
+
if (!fs.existsSync(manifest)) continue;
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
54
|
+
if (parsed?.name === name) return typeof parsed.version === "string" ? parsed.version : undefined;
|
|
55
|
+
} catch { /* a malformed manifest is not this package's */ }
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The file specifier resolves to from this module (import.meta.resolve needs Node.js 18.19 or 20.6; older ones require). */
|
|
61
|
+
function resolveFromHere(specifier: string): string {
|
|
62
|
+
return typeof import.meta.resolve === "function"
|
|
63
|
+
? fileURLToPath(import.meta.resolve(specifier))
|
|
64
|
+
: createRequire(import.meta.url).resolve(specifier);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const message = (error: unknown) => error instanceof Error ? error.message : String(error);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Whether version meets declared, for the forms package.json uses: x.y.z exactly, ^x.y.z (the leftmost non-zero
|
|
71
|
+
* part stays) or ~x.y.z (the minor stays). Other forms are not judged (undefined).
|
|
72
|
+
*/
|
|
73
|
+
export function meetsDeclared(version: string, declared: string): boolean | undefined {
|
|
74
|
+
const want = /^([~^]?)(\d+)\.(\d+)\.(\d+)$/.exec(declared.trim());
|
|
75
|
+
const have = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version);
|
|
76
|
+
if (!want || !have) return undefined;
|
|
77
|
+
// A prerelease (3.22.21-beta.1) meets none of these forms.
|
|
78
|
+
if (have[4]) return false;
|
|
79
|
+
const [w0, w1, w2] = want.slice(2).map(Number), [h0, h1, h2] = have.slice(1, 4).map(Number);
|
|
80
|
+
const order = h0 - w0 || h1 - w1 || h2 - w2;
|
|
81
|
+
if (want[1] === "") return order === 0;
|
|
82
|
+
if (order < 0) return false;
|
|
83
|
+
if (want[1] === "~") return h0 === w0 && h1 === w1;
|
|
84
|
+
return w0 > 0 ? h0 === w0 : w1 > 0 ? h0 === 0 && h1 === w1 : h0 === 0 && h1 === 0 && h2 === w2;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
|
|
88
|
+
export function versionProblem(name: string, version: string | undefined, declared: string): string | undefined {
|
|
89
|
+
const meets = meetsDeclared(version ?? "", declared);
|
|
90
|
+
if (meets === true) return undefined;
|
|
91
|
+
if (meets === undefined && version !== undefined) return `This check cannot judge ${name}'s declared version "${declared}"; ${version} is installed.`;
|
|
92
|
+
return `This server needs ${name} ${declared}; ${version ?? "an unknown version"} is installed.`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** One dependency: it resolves from this install, loads, and its installed version meets package.json's. */
|
|
96
|
+
async function dependencyCheck(name: string, declared: string): Promise<SelfCheck> {
|
|
97
|
+
const specifier = ENTRIES[name] ?? name;
|
|
98
|
+
try {
|
|
99
|
+
const file = resolveFromHere(specifier);
|
|
100
|
+
const version = installedVersion(file, name);
|
|
101
|
+
await import(specifier);
|
|
102
|
+
const problem = versionProblem(name, version, declared);
|
|
103
|
+
if (problem) return { name, ok: false, ...(version ? { version } : {}), message: problem };
|
|
104
|
+
return { name, ok: true, ...(version ? { version } : {}) };
|
|
105
|
+
} catch (error) {
|
|
106
|
+
return { name, ok: false, message: `${name} did not load: ${message(error)}` };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Every hunk of the bundled patch is in the installed bambu-node: a read-only reverse dry run, as postinstall checks. */
|
|
111
|
+
function patchApplied(version: string): void {
|
|
112
|
+
const require = createRequire(import.meta.url);
|
|
113
|
+
const root = fs.realpathSync(path.dirname(require.resolve("bambu-node/package.json")));
|
|
114
|
+
const { parsePatchFile } = require("patch-package/dist/patch/parse.js");
|
|
115
|
+
const { executeEffects } = require("patch-package/dist/patch/apply.js");
|
|
116
|
+
const { reversePatch } = require("patch-package/dist/patch/reverse.js");
|
|
117
|
+
const patch = fs.readFileSync(new URL(`../../patches/bambu-node+${version}.patch`, import.meta.url), "utf8");
|
|
118
|
+
const effects = parsePatchFile(patch).map((effect: { type: string; path: string }) => {
|
|
119
|
+
if (effect.type !== "patch" || !effect.path.startsWith("node_modules/bambu-node/")) throw new Error("the bundled patch has an unexpected target");
|
|
120
|
+
return { ...effect, path: effect.path.slice("node_modules/bambu-node/".length) };
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
123
|
+
executeEffects(reversePatch(effects), { cwd: root, dryRun: true, bestEffort: false });
|
|
124
|
+
} catch {
|
|
125
|
+
throw new Error(`the installed bambu-node ${version} is missing part of this server's patch`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The bundled patch (patches/bambu-node+<version>.patch) is in the installed bambu-node, and the loaded module
|
|
131
|
+
* behaves patched: it adds the H2-series and later printers to model detection, so an unpatched bambu-node throws
|
|
132
|
+
* "Printer model not supported!" on an H2D's version report. The report is read in memory, without a connection.
|
|
133
|
+
*/
|
|
134
|
+
async function bambuNodePatchCheck(version: string | undefined): Promise<SelfCheck> {
|
|
135
|
+
const name = "bambu-node patch";
|
|
136
|
+
try {
|
|
137
|
+
if (!version) throw new Error("package.json names no bambu-node version");
|
|
138
|
+
patchApplied(version);
|
|
139
|
+
const { BambuClient } = await import("bambu-node");
|
|
140
|
+
const serial = "094SELFCHECK";
|
|
141
|
+
const client = new BambuClient({ host: "127.0.0.1", serialNumber: serial, accessToken: "self-check" });
|
|
142
|
+
await (client as any).onMessage(JSON.stringify({ info: { command: "get_version", module: [{ name: "ota", sn: serial }] } }), `device/${serial}/report`);
|
|
143
|
+
const model = (client as any).data?.model;
|
|
144
|
+
return model === "H2D" ? { name, ok: true } : { name, ok: false, message: `bambu-node read an H2D as ${String(model)}; reinstall this server so its patch is applied.` };
|
|
145
|
+
} catch (error) {
|
|
146
|
+
return { name, ok: false, message: `bambu-node is not patched: ${message(error)}. Reinstall this server so its patch is applied.` };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function selfCheck(server: { name: string; version: string }): Promise<SelfCheckResult> {
|
|
151
|
+
let dependencies: Record<string, string> = {};
|
|
152
|
+
const checks: SelfCheck[] = [];
|
|
153
|
+
try {
|
|
154
|
+
const manifest = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8"));
|
|
155
|
+
dependencies = manifest.dependencies ?? {};
|
|
156
|
+
if (manifest.version !== server.version) checks.push({ name: "package", ok: false, version: String(manifest.version), message: `The running server is ${server.version}, but its install is ${manifest.version}; restart it.` });
|
|
157
|
+
else checks.push({ name: "package", ok: true, version: server.version });
|
|
158
|
+
} catch (error) {
|
|
159
|
+
checks.push({ name: "package", ok: false, message: `Could not read this server's package.json: ${message(error)}` });
|
|
160
|
+
}
|
|
161
|
+
checks.push(...await Promise.all(Object.entries(dependencies).map(([name, declared]) => dependencyCheck(name, declared))));
|
|
162
|
+
checks.push(await bambuNodePatchCheck(dependencies["bambu-node"]));
|
|
163
|
+
return { contract: COUNTERPART_CONTRACT, server, ok: checks.every(check => check.ok || check.optional), checks };
|
|
164
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -88,6 +88,7 @@ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_C
|
|
|
88
88
|
import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
|
|
89
89
|
import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
|
|
90
90
|
import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
|
|
91
|
+
import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
|
|
91
92
|
import { parseProcessOverrides } from "./slicer/process-overrides.js";
|
|
92
93
|
import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
|
|
93
94
|
import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
|
|
@@ -161,7 +162,7 @@ const SERVER_INFO = {
|
|
|
161
162
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
162
163
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
163
164
|
"cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
|
|
164
|
-
"counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
|
|
165
|
+
"counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
|
|
165
166
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
166
167
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
167
168
|
"camera_stream_start", "camera_frame", "camera_stream_stop",
|
|
@@ -3567,6 +3568,12 @@ class BambuPrinterMCPServer {
|
|
|
3567
3568
|
},
|
|
3568
3569
|
outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
|
|
3569
3570
|
},
|
|
3571
|
+
{
|
|
3572
|
+
name: "counterpart_self_check",
|
|
3573
|
+
description: "Counterpart contract (counterpart/1): whether this install's own runtime dependencies and its bundled bambu-node patch loaded, each with its installed version. Run it after an update; ok is false when a check failed, with a message saying which. Sends nothing to the printer.",
|
|
3574
|
+
inputSchema: { type: "object", properties: {} },
|
|
3575
|
+
outputSchema: SELF_CHECK_OUTPUT_SCHEMA
|
|
3576
|
+
},
|
|
3570
3577
|
{
|
|
3571
3578
|
name: "counterpart_discover_printers",
|
|
3572
3579
|
description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
|
|
@@ -5098,6 +5105,10 @@ class BambuPrinterMCPServer {
|
|
|
5098
5105
|
break;
|
|
5099
5106
|
}
|
|
5100
5107
|
|
|
5108
|
+
case "counterpart_self_check":
|
|
5109
|
+
result = await selfCheck(SERVER_INFO);
|
|
5110
|
+
break;
|
|
5111
|
+
|
|
5101
5112
|
case "counterpart_printer_info":
|
|
5102
5113
|
result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
|
|
5103
5114
|
break;
|
package/src/printers/bambu.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
|
|
|
23
23
|
import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
|
|
24
24
|
import { Client as FTPClient } from "basic-ftp";
|
|
25
25
|
import { uploadBytes } from "./ftp-upload.js";
|
|
26
|
+
import { mergeBambuReport } from "./report-merge.js";
|
|
26
27
|
import * as mqtt from "mqtt";
|
|
27
28
|
import {
|
|
28
29
|
BambuClient,
|
|
@@ -425,12 +426,35 @@ class BambuClientStore {
|
|
|
425
426
|
return;
|
|
426
427
|
}
|
|
427
428
|
|
|
428
|
-
|
|
429
|
-
this.reportSnapshots.set(key, { ...previous, ...update });
|
|
429
|
+
this.reportSnapshots.set(key, mergeBambuReport(this.reportSnapshots.get(key), update));
|
|
430
430
|
this.reportTimes.set(key, Date.now());
|
|
431
431
|
this.resolveInitialReport(key);
|
|
432
432
|
}
|
|
433
433
|
|
|
434
|
+
/** Merges the printer's reports into its snapshot as they arrive (tests feed a client without a connection). */
|
|
435
|
+
private watchReports(printer: BambuClient, host: string, serial: string, key: string): void {
|
|
436
|
+
printer.on("rawMessage", (_topic, payload) => {
|
|
437
|
+
try {
|
|
438
|
+
const parsed = JSON.parse(payload.toString());
|
|
439
|
+
const printMessage = parsed?.print;
|
|
440
|
+
if (printMessage && typeof printMessage === "object") {
|
|
441
|
+
this.updateReportSnapshot(key, printMessage);
|
|
442
|
+
this.reportObserved(host, serial, key);
|
|
443
|
+
}
|
|
444
|
+
} catch {
|
|
445
|
+
// Ignore unrelated payloads.
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
// bambu-node passes its whole merged report and then what changed. Only the change is merged here, so a field the
|
|
450
|
+
// printer has not sent again (the previous job's layer) is not copied back over this merge's own reset.
|
|
451
|
+
printer.on("printer:dataUpdate", (_data, changed) => {
|
|
452
|
+
if (!changed || typeof changed !== "object") return;
|
|
453
|
+
this.updateReportSnapshot(key, changed);
|
|
454
|
+
this.reportObserved(host, serial, key);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
434
458
|
private reportObserved(host: string, serial: string, key: string): void {
|
|
435
459
|
const report = this.reportSnapshots.get(key);
|
|
436
460
|
if (!report || !this.onReport) return;
|
|
@@ -528,23 +552,7 @@ class BambuClientStore {
|
|
|
528
552
|
});
|
|
529
553
|
this.ensureInitialReportPromise(key);
|
|
530
554
|
|
|
531
|
-
|
|
532
|
-
try {
|
|
533
|
-
const parsed = JSON.parse(payload.toString());
|
|
534
|
-
const printMessage = parsed?.print;
|
|
535
|
-
if (printMessage && typeof printMessage === "object") {
|
|
536
|
-
this.updateReportSnapshot(key, printMessage);
|
|
537
|
-
this.reportObserved(host, serial, key);
|
|
538
|
-
}
|
|
539
|
-
} catch {
|
|
540
|
-
// Ignore unrelated payloads.
|
|
541
|
-
}
|
|
542
|
-
});
|
|
543
|
-
|
|
544
|
-
printer.on("printer:dataUpdate", (data) => {
|
|
545
|
-
this.updateReportSnapshot(key, data);
|
|
546
|
-
this.reportObserved(host, serial, key);
|
|
547
|
-
});
|
|
555
|
+
this.watchReports(printer, host, serial, key);
|
|
548
556
|
|
|
549
557
|
printer.on("client:connect", () => {
|
|
550
558
|
this.printers.set(key, printer);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merging Bambu MQTT reports. P1/A1 printers push only what changed, so a merged report keeps every field until the
|
|
3
|
+
* printer sends it again. A new job's first pushes can carry its name and layer count before its layer number, and the
|
|
4
|
+
* previous job's last layer then read against the new total ("315/150"). Until the new job reports its own progress,
|
|
5
|
+
* its report has none.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Fields that name the job a report describes. The layer count is not one: a running job's count can be revised, and a
|
|
10
|
+
* different job differs in its name, file or task id.
|
|
11
|
+
*/
|
|
12
|
+
const JOB_FIELDS = ["subtask_name", "gcode_file", "task_id"] as const;
|
|
13
|
+
/** A new job prepares (PREPARE, SLICING) after any end; RUNNING straight after FAILED is that job resuming. */
|
|
14
|
+
const PREPARING = new Set(["PREPARE", "SLICING"]);
|
|
15
|
+
const DONE = new Set(["FINISH", "IDLE"]);
|
|
16
|
+
|
|
17
|
+
/** The previous job's progress, left out of a new job's report until the printer reports the new job's own. */
|
|
18
|
+
const JOB_PROGRESS = ["layer_num", "mc_percent", "mc_remaining_time"] as const;
|
|
19
|
+
|
|
20
|
+
/** A job field's value, or undefined for a placeholder: empty, or 0 (LAN prints report task_id "0"). */
|
|
21
|
+
function named(value: unknown): string | undefined {
|
|
22
|
+
const text = value === undefined || value === null ? "" : String(value).trim();
|
|
23
|
+
return text === "" || text === "0" ? undefined : text;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** True when update describes a different job than the report merged before it. */
|
|
27
|
+
export function startsNewJob(previous: Record<string, any> | undefined, update: Record<string, any>): boolean {
|
|
28
|
+
if (!previous) return false;
|
|
29
|
+
for (const field of JOB_FIELDS) {
|
|
30
|
+
const before = named(previous[field]), after = named(update[field]);
|
|
31
|
+
if (before !== undefined && after !== undefined && before !== after) return true;
|
|
32
|
+
}
|
|
33
|
+
const before = String(previous.gcode_state), after = String(update.gcode_state);
|
|
34
|
+
return (DONE.has(before) || before === "FAILED") && PREPARING.has(after) || DONE.has(before) && after === "RUNNING";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The previous job's progress fields to leave out when update starts a new job without reporting them. */
|
|
38
|
+
export function newJobResets(previous: Record<string, any> | undefined, update: Record<string, any>): string[] {
|
|
39
|
+
if (!startsNewJob(previous, update)) return [];
|
|
40
|
+
return JOB_PROGRESS.filter(field => update[field] === undefined && previous?.[field] !== undefined);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** previous merged with update, without the previous job's progress when update starts a new one (newJobResets). */
|
|
44
|
+
export function mergeBambuReport(previous: Record<string, any> | undefined, update: Record<string, any>): Record<string, any> {
|
|
45
|
+
const merged: Record<string, any> = { ...previous, ...update };
|
|
46
|
+
for (const field of newJobResets(previous, update)) delete merged[field];
|
|
47
|
+
return merged;
|
|
48
|
+
}
|
|
@@ -10,7 +10,7 @@ import path from 'path';
|
|
|
10
10
|
import { promisify } from 'util';
|
|
11
11
|
import { EventEmitter } from 'events';
|
|
12
12
|
import * as crypto from 'crypto';
|
|
13
|
-
import {
|
|
13
|
+
import { spawn, type ChildProcess } from 'child_process';
|
|
14
14
|
import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
|
|
15
15
|
import { listModelPlates } from '../counterpart/model-plates.js';
|
|
16
16
|
import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
|
|
@@ -283,6 +283,33 @@ function slicerResultText(result: SlicerResult): string {
|
|
|
283
283
|
].filter((text): text is string => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
/** What execFile hands its callback when the slicer fails: its message carries the command and stderr. */
|
|
287
|
+
type SlicerExit = Error & { code?: number | string | null; signal?: NodeJS.Signals | null; killed?: boolean; cmd?: string };
|
|
288
|
+
/** The output kept from each stream, as execFile's default maxBuffer; the rest is dropped, not failed. */
|
|
289
|
+
const SLICER_OUTPUT_LIMIT = 1024 * 1024;
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* execFile for the slicer, with detached passed through (execFile drops it): on POSIX the slicer then leads its own
|
|
293
|
+
* process group, so a cancel can stop the helpers it starts too. The callback gets what execFile's would.
|
|
294
|
+
*/
|
|
295
|
+
function execSlicer(file: string, args: string[], env: NodeJS.ProcessEnv | undefined, detached: boolean,
|
|
296
|
+
callback: (error: SlicerExit | null, stdout: string, stderr: string) => void): ChildProcess {
|
|
297
|
+
// stdin is ignored, as execFile ends it: no slicer reads it.
|
|
298
|
+
const child = spawn(file, args, { ...(env ? { env } : {}), detached, stdio: ["ignore", "pipe", "pipe"] });
|
|
299
|
+
let stdout = "", stderr = "", settled = false;
|
|
300
|
+
const keep = (text: string, chunk: Buffer) => text.length >= SLICER_OUTPUT_LIMIT ? text : (text + chunk.toString("utf8")).slice(0, SLICER_OUTPUT_LIMIT);
|
|
301
|
+
child.stdout?.on("data", (chunk: Buffer) => { stdout = keep(stdout, chunk); });
|
|
302
|
+
child.stderr?.on("data", (chunk: Buffer) => { stderr = keep(stderr, chunk); });
|
|
303
|
+
const finish = (error: SlicerExit | null) => { if (!settled) { settled = true; callback(error, stdout, stderr); } };
|
|
304
|
+
child.on("error", error => finish(Object.assign(error, { cmd: [file, ...args].join(" ") })));
|
|
305
|
+
child.on("close", (code, signal) => {
|
|
306
|
+
if (code === 0 && !signal) return finish(null);
|
|
307
|
+
const cmd = [file, ...args].join(" ");
|
|
308
|
+
finish(Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, signal, killed: child.killed, cmd }));
|
|
309
|
+
});
|
|
310
|
+
return child;
|
|
311
|
+
}
|
|
312
|
+
|
|
286
313
|
function describeSlicerFailure(
|
|
287
314
|
error: { message: string; code?: unknown; signal?: unknown },
|
|
288
315
|
stdout: string,
|
|
@@ -2074,10 +2101,17 @@ export class STLManipulator extends EventEmitter {
|
|
|
2074
2101
|
const launch = await prepareSlicerLaunch(slicerType, this.tempDir);
|
|
2075
2102
|
const stallSeconds = launch.stallSeconds;
|
|
2076
2103
|
let stalled = false;
|
|
2104
|
+
let cancelled = false;
|
|
2077
2105
|
// Execute the slicer
|
|
2078
2106
|
try { await new Promise<void>((resolve, reject) => {
|
|
2079
|
-
|
|
2080
|
-
|
|
2107
|
+
// POSIX: the slicer leads its own process group, so stopping it also stops the helpers it starts.
|
|
2108
|
+
const group = globalThis.process.platform !== 'win32';
|
|
2109
|
+
const process = execSlicer(slicerPath, args, launch.env, group, (error, stdout, stderr) => {
|
|
2110
|
+
if (cancelled) {
|
|
2111
|
+
// Settled once the slicer and every process sharing its output have gone, so its folder is removed after
|
|
2112
|
+
// nothing can write to it.
|
|
2113
|
+
reject(new Error("Slicing operation cancelled"));
|
|
2114
|
+
} else if (stalled && error) {
|
|
2081
2115
|
reject(stalledSlicerError(slicerType, stallSeconds));
|
|
2082
2116
|
} else if (error) {
|
|
2083
2117
|
console.error(`Slicer Error: ${error.message}`);
|
|
@@ -2097,26 +2131,49 @@ export class STLManipulator extends EventEmitter {
|
|
|
2097
2131
|
// process.stdout?.on('data', (data) => { console.error(`Slicer stdout: ${data}`); });
|
|
2098
2132
|
// process.stderr?.on('data', (data) => { console.error(`Slicer stderr: ${data}`); });
|
|
2099
2133
|
|
|
2100
|
-
//
|
|
2134
|
+
// Stops the slicer and, on POSIX, its whole process group (a group already gone is not an error).
|
|
2135
|
+
const stop = (signal: NodeJS.Signals) => {
|
|
2136
|
+
try {
|
|
2137
|
+
if (group && process.pid !== undefined) globalThis.process.kill(-process.pid, signal);
|
|
2138
|
+
else process.kill(signal);
|
|
2139
|
+
} catch (killError) {
|
|
2140
|
+
if ((killError as NodeJS.ErrnoException).code !== 'ESRCH') console.error(`Could not send ${signal} to the slicer:`, killError);
|
|
2141
|
+
}
|
|
2142
|
+
};
|
|
2143
|
+
// Check for cancellation periodically: the slicer is stopped, and the call settles when it has gone.
|
|
2144
|
+
let forceKill: NodeJS.Timeout | undefined;
|
|
2145
|
+
let abandon: NodeJS.Timeout | undefined;
|
|
2101
2146
|
const checkCancel = setInterval(() => {
|
|
2102
2147
|
if (!this.activeOperations.get(operationId)) {
|
|
2103
2148
|
clearInterval(checkCancel);
|
|
2104
|
-
|
|
2105
|
-
|
|
2149
|
+
cancelled = true;
|
|
2150
|
+
stop('SIGTERM');
|
|
2151
|
+
// A slicer or helper that ignores SIGTERM is killed outright rather than waited on. A helper outside the
|
|
2152
|
+
// group (daemonized, or any helper on Windows) can still hold the output pipes, so 'close' never comes:
|
|
2153
|
+
// a second later the pipes are let go and the cancel settles.
|
|
2154
|
+
forceKill = setTimeout(() => {
|
|
2155
|
+
stop('SIGKILL');
|
|
2156
|
+
abandon = setTimeout(() => {
|
|
2157
|
+
process.stdout?.destroy();
|
|
2158
|
+
process.stderr?.destroy();
|
|
2106
2159
|
reject(new Error("Slicing operation cancelled"));
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
reject(new Error("Slicing operation cancelled, but failed to kill process."));
|
|
2110
|
-
}
|
|
2160
|
+
}, 1000);
|
|
2161
|
+
}, 5000);
|
|
2111
2162
|
}
|
|
2112
2163
|
}, 500);
|
|
2113
2164
|
|
|
2114
|
-
process.on('exit', () =>
|
|
2115
|
-
|
|
2165
|
+
process.on('exit', () => {
|
|
2166
|
+
// Exit can precede a client cancel while a helper retains output pipes; polling runs until close.
|
|
2167
|
+
// A helper that outlived the slicer still holds its output; finish it so the call can settle.
|
|
2168
|
+
if (cancelled && group) stop('SIGKILL');
|
|
2169
|
+
});
|
|
2170
|
+
// The deadline runs until every process sharing the slicer's output has let go, not only the slicer.
|
|
2171
|
+
process.on('close', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
|
|
2172
|
+
process.on('error', () => { clearInterval(checkCancel); clearTimeout(forceKill); clearTimeout(abandon); });
|
|
2116
2173
|
watchForStall(process, stallSeconds, () => {
|
|
2117
2174
|
stalled = true;
|
|
2118
2175
|
console.error(`${slicerType} used no CPU and wrote nothing for ${stallSeconds} s; stopping it as waiting on a dialog.`);
|
|
2119
|
-
|
|
2176
|
+
stop('SIGKILL');
|
|
2120
2177
|
});
|
|
2121
2178
|
|
|
2122
2179
|
}); } finally { await launch.cleanup(); }
|
|
@@ -2156,7 +2213,11 @@ export class STLManipulator extends EventEmitter {
|
|
|
2156
2213
|
} catch (error) {
|
|
2157
2214
|
console.error(`Slicing failed for ${stlFilePath}:`, error);
|
|
2158
2215
|
// Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
|
|
2159
|
-
if (sliceDir)
|
|
2216
|
+
if (sliceDir) {
|
|
2217
|
+
await fs.promises.rm(sliceDir, { recursive: true, force: true }).then(
|
|
2218
|
+
() => console.error(`Removed the folder of the failed or cancelled slice: ${sliceDir}`),
|
|
2219
|
+
removeError => console.error(`Could not remove the folder of the failed or cancelled slice ${sliceDir}:`, removeError));
|
|
2220
|
+
}
|
|
2160
2221
|
this.emit('operationError', {
|
|
2161
2222
|
operationId,
|
|
2162
2223
|
type: 'slice',
|
package/src/tool-annotations.ts
CHANGED
|
@@ -67,6 +67,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
|
|
|
67
67
|
list_templates: READ_LOCAL,
|
|
68
68
|
get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
|
|
69
69
|
counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
|
|
70
|
+
counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
|
|
70
71
|
counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
|
|
71
72
|
|
|
72
73
|
// Local outputs in the server's temporary directory
|