bambu-printer-mcp 1.1.90 → 1.1.92

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.
Files changed (86) hide show
  1. package/CONTRIBUTORS.md +2 -0
  2. package/README.md +48 -3
  3. package/dist/bambu-native.js +1 -1
  4. package/dist/cad/contracts.js +16 -7
  5. package/dist/cad/examples.d.ts +2 -1
  6. package/dist/cad/examples.js +13 -10
  7. package/dist/cad/serial.d.ts +1 -1
  8. package/dist/cad/serial.js +4 -6
  9. package/dist/cad-engine.js +17 -12
  10. package/dist/counterpart/flight-record.d.ts +155 -0
  11. package/dist/counterpart/flight-record.js +831 -0
  12. package/dist/counterpart/flight-tools.d.ts +213 -0
  13. package/dist/counterpart/flight-tools.js +232 -0
  14. package/dist/counterpart/fresh-frame.d.ts +16 -0
  15. package/dist/counterpart/fresh-frame.js +26 -0
  16. package/dist/counterpart/make-3mf.js +1 -4
  17. package/dist/counterpart/physical-evidence.d.ts +70 -0
  18. package/dist/counterpart/physical-evidence.js +103 -0
  19. package/dist/counterpart/print-geometry.d.ts +13 -0
  20. package/dist/counterpart/print-geometry.js +181 -0
  21. package/dist/counterpart/remote.js +2 -0
  22. package/dist/counterpart/schemas.d.ts +32 -0
  23. package/dist/counterpart/schemas.js +2 -0
  24. package/dist/counterpart/visual-evidence.d.ts +38 -0
  25. package/dist/counterpart/visual-evidence.js +155 -0
  26. package/dist/index.js +63 -24
  27. package/dist/printers/bambu.d.ts +15 -2
  28. package/dist/printers/bambu.js +64 -12
  29. package/dist/safety/limits.d.ts +6 -0
  30. package/dist/safety/limits.js +8 -0
  31. package/dist/safety/print-file.js +2 -2
  32. package/dist/safety/print-preview.d.ts +2 -0
  33. package/dist/safety/print-preview.js +1 -1
  34. package/dist/safety/printer-state.d.ts +4 -0
  35. package/dist/safety/printer-state.js +14 -1
  36. package/dist/slicer/3mf-xml.d.ts +7 -0
  37. package/dist/slicer/3mf-xml.js +61 -0
  38. package/dist/stl/stl-manipulator.js +5 -2
  39. package/dist/studio-print-options.d.ts +9 -0
  40. package/dist/studio-print-options.js +34 -2
  41. package/dist/tool-annotations.js +2 -0
  42. package/package.json +2 -1
  43. package/src/bambu-native.ts +1 -1
  44. package/src/cad/contracts.ts +17 -7
  45. package/src/cad/examples/bag_clip.py +1 -0
  46. package/src/cad/examples/bistable_clicker.py +1 -0
  47. package/src/cad/examples/broom_grip.py +61 -0
  48. package/src/cad/examples/cable_clip.py +1 -0
  49. package/src/cad/examples/chainmail.py +1 -0
  50. package/src/cad/examples/desk_clamp_hook.py +91 -0
  51. package/src/cad/examples/desk_edge_cable_holder.py +55 -0
  52. package/src/cad/examples/drawer_divider.py +56 -0
  53. package/src/cad/examples/hinged_box.py +1 -0
  54. package/src/cad/examples/knurled_knob.py +1 -0
  55. package/src/cad/examples/loft_handle.py +1 -0
  56. package/src/cad/examples/organizer_tray.py +41 -0
  57. package/src/cad/examples/phone_stand.py +1 -0
  58. package/src/cad/examples/plant_pot.py +53 -0
  59. package/src/cad/examples/shelf_bracket.py +53 -0
  60. package/src/cad/examples/swept_hook.py +1 -0
  61. package/src/cad/examples/threaded_jar.py +1 -0
  62. package/src/cad/examples/trigger_capo.py +1 -0
  63. package/src/cad/examples/wall_hook.py +1 -0
  64. package/src/cad/examples.ts +13 -10
  65. package/src/cad/geometry.py +6 -0
  66. package/src/cad/serial.ts +4 -6
  67. package/src/cad-engine.ts +9 -3
  68. package/src/counterpart/flight-record.ts +984 -0
  69. package/src/counterpart/flight-tools.ts +282 -0
  70. package/src/counterpart/fresh-frame.ts +45 -0
  71. package/src/counterpart/make-3mf.ts +1 -5
  72. package/src/counterpart/physical-evidence.ts +185 -0
  73. package/src/counterpart/print-geometry.ts +192 -0
  74. package/src/counterpart/remote.ts +2 -0
  75. package/src/counterpart/schemas.ts +3 -0
  76. package/src/counterpart/visual-evidence.ts +212 -0
  77. package/src/index.ts +61 -21
  78. package/src/printers/bambu.ts +64 -10
  79. package/src/safety/limits.ts +8 -0
  80. package/src/safety/print-file.ts +2 -2
  81. package/src/safety/print-preview.ts +1 -1
  82. package/src/safety/printer-state.ts +13 -1
  83. package/src/slicer/3mf-xml.ts +52 -0
  84. package/src/stl/stl-manipulator.ts +4 -1
  85. package/src/studio-print-options.ts +33 -2
  86. package/src/tool-annotations.ts +2 -0
@@ -0,0 +1,192 @@
1
+ import { arcCentre } from "../safety/print-preview.js";
2
+
3
+ /** Expected geometry from the exact selected plate's sliced commands, never printer progress. */
4
+ export interface LayerGeometry {
5
+ layer: number;
6
+ zMm: number;
7
+ boundsMm?: [number, number, number, number];
8
+ }
9
+ export interface PrintGeometry {
10
+ heightMm?: number;
11
+ layers: LayerGeometry[];
12
+ }
13
+
14
+ export function geometryFromGcode(gcode: string): PrintGeometry {
15
+ const layers: LayerGeometry[] = [];
16
+ let z: number | undefined, layer: LayerGeometry | undefined;
17
+ let markerCount = 0,
18
+ currentIndex = 0,
19
+ previousMarkerZ: number | undefined;
20
+ let x = 0,
21
+ y = 0,
22
+ e = 0,
23
+ relative = false,
24
+ absoluteXY = true,
25
+ positionUnknown = false,
26
+ changingFilament = false,
27
+ feature = "",
28
+ executableEnded = false;
29
+ for (const line of gcode.split(/\r?\n/)) {
30
+ if (line === "; EXECUTABLE_BLOCK_END") executableEnded = true;
31
+ if (executableEnded) break;
32
+ const marker = /^;\s*(?:Z_HEIGHT:|Z:)\s*([\d.]+)/.exec(line);
33
+ if (marker) {
34
+ z = Number(marker[1]);
35
+ if (z !== previousMarkerZ) markerCount++;
36
+ previousMarkerZ = z;
37
+ currentIndex = markerCount;
38
+ layer = undefined;
39
+ if (!Number.isFinite(z) || z <= 0 || z > 10000) z = undefined;
40
+ }
41
+ const declared = /^;\s*layer num\/total_layer_count:\s*(\d+)\/\d+/.exec(
42
+ line,
43
+ );
44
+ if (declared) currentIndex = Number(declared[1]);
45
+ const featureMatch = /^;\s*(?:FEATURE|TYPE):\s*(.*)/i.exec(line);
46
+ if (featureMatch) feature = featureMatch[1].trim().toLowerCase();
47
+ const command = line
48
+ .split(";")[0]
49
+ .trim()
50
+ .toUpperCase()
51
+ .replace(/^N\d+\s*/, "")
52
+ .replace(/\*\d+\s*$/, "");
53
+ const parsed = /^([GMT])(\d+(?:\.\d+)?)/.exec(command);
54
+ if (!parsed) continue;
55
+ const word = parsed[1] + String(Number(parsed[2]));
56
+ const values: Record<string, number> = {};
57
+ for (const match of command
58
+ .slice(parsed[0].length)
59
+ .matchAll(/([A-Z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))/g)) {
60
+ if (values[match[1]] === undefined) values[match[1]] = Number(match[2]);
61
+ }
62
+ if (word === "G90") {
63
+ absoluteXY = true;
64
+ continue;
65
+ }
66
+ if (word === "G91") {
67
+ absoluteXY = false;
68
+ continue;
69
+ }
70
+ if (word === "M83") {
71
+ relative = true;
72
+ continue;
73
+ }
74
+ if (word === "M82") {
75
+ relative = false;
76
+ continue;
77
+ }
78
+ // Do not invent bed-coordinate footprints for unsupported unit/work-coordinate changes.
79
+ if (
80
+ word === "G20" ||
81
+ word === "G18" || word === "G19" || word === "G90.1" ||
82
+ word === "G53" ||
83
+ (word === "G92" && (values.X !== undefined || values.Y !== undefined))
84
+ )
85
+ return { layers: [] };
86
+ if (word === "G28") {
87
+ positionUnknown = true;
88
+ continue;
89
+ }
90
+ if (Object.values(values).some((v) => !Number.isFinite(v)))
91
+ return { layers: [] };
92
+ if (word === "G92") {
93
+ if (values.E !== undefined) e = values.E;
94
+ continue;
95
+ }
96
+ if (word === "M620" && values.S !== undefined) {
97
+ changingFilament = true;
98
+ continue;
99
+ }
100
+ if (word === "M621" && values.S !== undefined) {
101
+ changingFilament = false;
102
+ continue;
103
+ }
104
+ if (!["G0", "G1", "G2", "G3"].includes(word)) continue;
105
+ const nx =
106
+ values.X === undefined ? x : absoluteXY ? values.X : x + values.X;
107
+ const ny =
108
+ values.Y === undefined ? y : absoluteXY ? values.Y : y + values.Y;
109
+ const extrusion =
110
+ values.E === undefined ? 0 : relative ? values.E : values.E - e;
111
+ if (
112
+ z !== undefined &&
113
+ extrusion > 0 &&
114
+ word !== "G0" &&
115
+ !changingFilament &&
116
+ feature !== "custom" &&
117
+ (values.X !== undefined || values.Y !== undefined || word === "G2" || word === "G3")
118
+ ) {
119
+ if (positionUnknown) return { layers: [] };
120
+ const bounds = motionBounds(x, y, nx, ny, word, values);
121
+ if (!bounds) return { layers: [] };
122
+ if (!layer) {
123
+ // Repeated Z values do not create fictitious additional layers.
124
+ layer =
125
+ layers.at(-1)?.zMm === z
126
+ ? layers.at(-1)
127
+ : { layer: currentIndex, zMm: z };
128
+ if (layer && layers.at(-1) !== layer) layers.push(layer);
129
+ if (layers.length > 10000) return { layers: [] };
130
+ }
131
+ if (layer) {
132
+ const previous = layer.boundsMm;
133
+ layer.boundsMm = [
134
+ Math.min(previous?.[0] ?? bounds[0], bounds[0]),
135
+ Math.min(previous?.[1] ?? bounds[1], bounds[1]),
136
+ Math.max(previous?.[2] ?? bounds[2], bounds[2]),
137
+ Math.max(previous?.[3] ?? bounds[3], bounds[3]),
138
+ ];
139
+ }
140
+ }
141
+ if (absoluteXY && values.X !== undefined && values.Y !== undefined)
142
+ positionUnknown = false;
143
+ x = nx;
144
+ y = ny;
145
+ if (values.E !== undefined) e = relative ? e + values.E : values.E;
146
+ }
147
+ return {
148
+ ...(layers.length
149
+ ? { heightMm: Math.max(...layers.map((l) => l.zMm)) }
150
+ : {}),
151
+ layers,
152
+ };
153
+ }
154
+
155
+ /** Include the cardinal extrema actually swept by an XY arc, including I/J full circles. */
156
+ function motionBounds(x: number, y: number, nx: number, ny: number, word: string, values: Record<string, number>): [number, number, number, number] | undefined {
157
+ const bounds: [number, number, number, number] = [Math.min(x,nx),Math.min(y,ny),Math.max(x,nx),Math.max(y,ny)];
158
+ if (!bounds.every(Number.isFinite)) return;
159
+ if (word !== "G2" && word !== "G3") return bounds;
160
+ const clockwise = word === "G2";
161
+ const centre = arcCentre(x,y,nx,ny,clockwise,values.I,values.J,values.R);
162
+ if (!centre || !centre.every(Number.isFinite)) return;
163
+ const [cx,cy] = centre, radius = Math.hypot(x-cx,y-cy);
164
+ if (!Number.isFinite(radius) || radius <= 0 || Math.abs(Math.hypot(nx-cx,ny-cy)-radius) > Math.max(0.01,radius*0.001)) return;
165
+ const turn = 2*Math.PI;
166
+ const normal = (angle:number) => ((angle % turn)+turn)%turn;
167
+ const start = Math.atan2(y-cy,x-cx), end = Math.atan2(ny-cy,nx-cx);
168
+ const sweep = normal(clockwise ? start-end : end-start);
169
+ const full = x === nx && y === ny;
170
+ for (const angle of [0,Math.PI/2,Math.PI,3*Math.PI/2]) {
171
+ const distance = normal(clockwise ? start-angle : angle-start);
172
+ if (!full && distance > sweep+1e-10) continue;
173
+ const px = cx+radius*Math.cos(angle), py = cy+radius*Math.sin(angle);
174
+ bounds[0]=Math.min(bounds[0],px); bounds[1]=Math.min(bounds[1],py);
175
+ bounds[2]=Math.max(bounds[2],px); bounds[3]=Math.max(bounds[3],py);
176
+ }
177
+ return bounds;
178
+ }
179
+
180
+ /** Best-effort diagnostics only: an unreadable/oversize file cannot fail an already dispatched print. */
181
+ export async function geometryFromFile(
182
+ filePath: string,
183
+ ): Promise<PrintGeometry | undefined> {
184
+ try {
185
+ const fs = await import("node:fs/promises");
186
+ const stat = await fs.stat(filePath);
187
+ if (!stat.isFile() || stat.size > 64 * 1024 * 1024) return undefined;
188
+ return geometryFromGcode(await fs.readFile(filePath, "utf8"));
189
+ } catch {
190
+ return undefined;
191
+ }
192
+ }
@@ -41,6 +41,8 @@ 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
+ counterpart_print_record: "read",
45
+ counterpart_print_assess: "control", // local evidence mutation, never a printer command
44
46
  cad_status: "read",
45
47
  cad_examples: "read",
46
48
  design_guidance: "read",
@@ -1,3 +1,4 @@
1
+ import {PHYSICAL_EVIDENCE_SCHEMA,type PhysicalEvidence} from "./physical-evidence.js";
1
2
  /**
2
3
  * The Counterpart tool contract (counterpart/1): output schemas shared by the
3
4
  * tool list and the tests. mcp-3D-printer-server declares the same results.
@@ -15,6 +16,7 @@ export type ProblemSeverity = typeof PROBLEM_SEVERITIES[number];
15
16
  export type Problem = { code: string; severity: ProblemSeverity; message: string; url?: string };
16
17
  export type Temperature = { actual: number; target: number };
17
18
  export type PrintProgress = {
19
+ physical?: PhysicalEvidence;
18
20
  contract: typeof COUNTERPART_CONTRACT;
19
21
  observedAt: string;
20
22
  state: PrintState;
@@ -94,6 +96,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
94
96
  export const PRINT_PROGRESS_OUTPUT_SCHEMA = {
95
97
  type: "object" as const,
96
98
  properties: {
99
+ physical: PHYSICAL_EVIDENCE_SCHEMA,
97
100
  contract: { type: "string", const: COUNTERPART_CONTRACT },
98
101
  observedAt: { type: "string", description: "When the printer reported this (MQTT report time), ISO 8601." },
99
102
  state: { type: "string", enum: [...PRINT_STATES] },
@@ -0,0 +1,212 @@
1
+ /** Visual observations come from the client's worker; this module runs no image model or printer I/O. */
2
+ import { frameMatchesReport } from "./physical-evidence.js";
3
+ import type { EvidenceFrame, PhysicalEvidence } from "./physical-evidence.js";
4
+ import type { PrintGeometry } from "./print-geometry.js";
5
+
6
+ export const VISIBILITIES = [
7
+ "clear",
8
+ "dark",
9
+ "occluded",
10
+ "out_of_view",
11
+ "unknown",
12
+ ] as const;
13
+ export type Visibility = (typeof VISIBILITIES)[number];
14
+ export interface VisualSubmission {
15
+ jobId: string;
16
+ artifactSha256: string;
17
+ frameId: string;
18
+ imageSha256: string;
19
+ visibility: Visibility;
20
+ footprintVisible: boolean;
21
+ deposition: "absent" | "present" | "unknown";
22
+ attempted: boolean;
23
+ referenceFrameId?: string;
24
+ referenceVisibility?: Visibility;
25
+ referenceEmpty?: boolean;
26
+ }
27
+ export interface VisualObservation extends VisualSubmission {
28
+ at: string;
29
+ source: "client-vision";
30
+ }
31
+ const uuid = /^[a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}$/i,
32
+ sha = /^[a-f\d]{64}$/i;
33
+ export function validateVisualSubmission(
34
+ v: VisualSubmission,
35
+ ): VisualSubmission {
36
+ if (
37
+ !v ||
38
+ !uuid.test(v.jobId) ||
39
+ !uuid.test(v.frameId) ||
40
+ !sha.test(v.artifactSha256) ||
41
+ !sha.test(v.imageSha256) ||
42
+ !VISIBILITIES.includes(v.visibility) ||
43
+ typeof v.footprintVisible !== "boolean" ||
44
+ typeof v.attempted !== "boolean" ||
45
+ !["absent", "present", "unknown"].includes(v.deposition) ||
46
+ (v.referenceFrameId !== undefined &&
47
+ (!uuid.test(v.referenceFrameId) ||
48
+ !VISIBILITIES.includes(v.referenceVisibility!))) ||
49
+ (v.referenceEmpty !== undefined && typeof v.referenceEmpty !== "boolean")
50
+ )
51
+ throw Error("Invalid visual observation.");
52
+ return {
53
+ jobId: v.jobId,
54
+ artifactSha256: v.artifactSha256,
55
+ frameId: v.frameId,
56
+ imageSha256: v.imageSha256,
57
+ visibility: v.visibility,
58
+ footprintVisible: v.footprintVisible,
59
+ deposition: v.deposition,
60
+ attempted: v.attempted,
61
+ ...(v.referenceFrameId
62
+ ? {
63
+ referenceFrameId: v.referenceFrameId,
64
+ referenceVisibility: v.referenceVisibility,
65
+ referenceEmpty: v.referenceEmpty === true,
66
+ }
67
+ : {}),
68
+ };
69
+ }
70
+ function assessObservation(
71
+ frames: EvidenceFrame[],
72
+ observation: VisualObservation,
73
+ expected?: PrintGeometry,
74
+ ): PhysicalEvidence {
75
+ const limitations = [
76
+ "Firmware completion is separate from physical success.",
77
+ "Image interpretation is supplied by the client vision worker; the MCP runs no vision model.",
78
+ ];
79
+ const unknown = (reason: string): PhysicalEvidence => ({
80
+ status: "unknown",
81
+ evidence: [],
82
+ limitations: [...limitations, reason],
83
+ });
84
+ const frame = frames.find(
85
+ (f) =>
86
+ f.id === observation.frameId &&
87
+ f.status === "captured" &&
88
+ f.sha256 === observation.imageSha256 &&
89
+ f.role !== "baseline",
90
+ );
91
+ const footprint = expected?.layers.find(
92
+ (l) => l.layer === frame?.layer,
93
+ )?.boundsMm;
94
+ if (
95
+ !frame ||
96
+ !footprint ||
97
+ !footprint.every(Number.isFinite) ||
98
+ footprint[2] <= footprint[0] ||
99
+ footprint[3] <= footprint[1] ||
100
+ !frameMatchesReport(frame) ||
101
+ !observation.attempted
102
+ )
103
+ return unknown(
104
+ "Saved frame, expected deposition footprint or attempted-layer evidence is unavailable.",
105
+ );
106
+ if (
107
+ observation.visibility !== "clear" ||
108
+ !observation.footprintVisible ||
109
+ observation.deposition === "unknown"
110
+ )
111
+ return unknown(
112
+ "The expected footprint is dark, occluded, out of view, unlocatable or unassessed.",
113
+ );
114
+ if (observation.deposition === "present")
115
+ return {
116
+ ...unknown("The client reports visible material; height, coverage and final success remain unverified."),
117
+ observedLayer: frame.layer,
118
+ evidence: [frame.id],
119
+ };
120
+ const reference = frames.find(
121
+ (f) => f.id === observation.referenceFrameId && f.status === "captured",
122
+ );
123
+ const evidence = [frame.id];
124
+ if (
125
+ reference &&
126
+ observation.referenceVisibility === "clear" &&
127
+ observation.referenceEmpty === true
128
+ )
129
+ evidence.unshift(reference.id);
130
+ return {
131
+ status: "suspect_no_extrusion",
132
+ observedLayer: frame.layer,
133
+ evidence,
134
+ limitations: [
135
+ ...limitations,
136
+ "The client reports a clear expected footprint with no visible deposited material after deposition was attempted. Check the print; the cause is unverified.",
137
+ ...(evidence.length === 1
138
+ ? [
139
+ "No usable empty-bed reference was supplied; the clear empty-footprint observation is direct evidence.",
140
+ ]
141
+ : [
142
+ "The client compared the frame with the saved empty-bed reference.",
143
+ ]),
144
+ ],
145
+ };
146
+ }
147
+ /** Unknown checkpoints cannot erase clear empty-footprint evidence for this execution. */
148
+ export function assessVisual(
149
+ frames: EvidenceFrame[],
150
+ observations: VisualObservation[],
151
+ expected?: PrintGeometry,
152
+ ): PhysicalEvidence | undefined {
153
+ let latest: PhysicalEvidence | undefined;
154
+ let suspect: PhysicalEvidence | undefined;
155
+ let recovery: PhysicalEvidence | undefined;
156
+ const ordered = [...observations].sort((a,b) =>
157
+ (frames.find(f=>f.id===a.frameId)?.layer ?? 0) - (frames.find(f=>f.id===b.frameId)?.layer ?? 0));
158
+ for (const observation of ordered) {
159
+ latest = assessObservation(frames, observation, expected);
160
+ if (latest.status === "suspect_no_extrusion") { suspect = latest; recovery = undefined; }
161
+ else if (suspect && observation.deposition === "present" &&
162
+ latest.evidence.includes(observation.frameId) &&
163
+ (latest.observedLayer ?? 0) > (suspect.observedLayer ?? 0)) {
164
+ suspect = undefined;
165
+ latest.limitations.push("A later clear, visible-footprint present observation at a higher layer supersedes the earlier no-extrusion warning; final physical success remains unverified.");
166
+ recovery = latest;
167
+ }
168
+ }
169
+ if (!suspect) return recovery ?? latest;
170
+ return {...suspect,limitations:[...suspect.limitations,
171
+ "This job's no-extrusion warning stays active through unknown checkpoints and firmware completion. Only a later clear present observation with a visible footprint at a higher layer can supersede it."]};
172
+ }
173
+ export function assessmentRequest(
174
+ frames: EvidenceFrame[],
175
+ observations: VisualObservation[],
176
+ expected?: PrintGeometry,
177
+ ) {
178
+ const pending = frames.filter(
179
+ (f) =>
180
+ f.status === "captured" &&
181
+ frameMatchesReport(f) &&
182
+ f.role !== "baseline" &&
183
+ !observations.some((o) => o.frameId === f.id),
184
+ );
185
+ const frame = pending.find((f) => f.role === "first_layer") ?? pending.at(-1);
186
+ const footprint = expected?.layers.find(
187
+ (l) => l.layer === frame?.layer,
188
+ )?.boundsMm;
189
+ if (!frame || !footprint) return;
190
+ return {
191
+ required: true,
192
+ frameId: frame.id,
193
+ referenceFrameIds: frames
194
+ .filter((f) => f.role === "baseline" && f.status === "captured")
195
+ .map((f) => f.id),
196
+ layer: frame.layer,
197
+ expectedHeightMm: frame.expectedHeightMm,
198
+ expectedFootprintMm: footprint,
199
+ instruction:
200
+ "Fetch this frame (and any usable reference) with counterpart_print_record include_frames:true frame_format:images. Have the client vision worker locate the expected footprint. Record its observation with counterpart_print_assess. A clearly empty footprint after attempted printing is suspect_no_extrusion even without a usable reference. Dark/occluded/unlocatable is unknown. Never infer a first layer is down from counters.",
201
+ };
202
+ }
203
+
204
+ export function physicalProblems(physical: PhysicalEvidence, finished = false) {
205
+ if (physical.status !== "suspect_no_extrusion") return [];
206
+ const layer = Number.isInteger(physical.observedLayer) && physical.observedLayer! > 0
207
+ ? ` at layer ${physical.observedLayer}` : "";
208
+ const message = finished
209
+ ? `The printer reports finished, but the camera showed the part's area empty${layer}. Check the nozzle and filament path.`
210
+ : `Nothing seems to be coming out of the nozzle: the camera shows the part's area empty${layer}. The printer can still count layers without printing anything. Check the nozzle and filament path.`;
211
+ return [{code:"physical-no-extrusion",severity:"error" as const,message}];
212
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {physicalProblems} from "./counterpart/visual-evidence.js";
3
+ import {flightKey} from "./counterpart/flight-record.js";
4
+ import {FLIGHT_RECORD_PROPERTIES,FLIGHT_RECORD_DESCRIPTION,FLIGHT_RECORD_OUTPUT_SCHEMA,flightReadOptions,flightRecordResult,FLIGHT_ASSESS_PROPERTIES,FLIGHT_ASSESS_REQUIRED,FLIGHT_ASSESS_DESCRIPTION,PRINT_EVIDENCE_GUIDANCE,visualSubmission} from "./counterpart/flight-tools.js";
2
5
  import {CAMERA_STREAM_TOOLS} from "./printers/camera-tools.js";
3
6
  import { withAnnotations } from "./tool-annotations.js";
4
7
  import { withRemote } from "./counterpart/remote.js";
@@ -73,7 +76,7 @@ import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } f
73
76
  import { inspectPrintFile } from "./safety/print-file.js";
74
77
  import { previewPrintFile } from "./safety/print-preview.js";
75
78
  import { loadSafe3mfArchive } from "./safety/archive.js";
76
- import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
79
+ import { SERIAL_MODELS, internalPrintingSupported, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
77
80
  import { isDualNozzleModel } from "./safety/limits.js";
78
81
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
79
82
  import { detectProfilesRoot } from "./slicer/profile-flatten.js";
@@ -181,17 +184,26 @@ function withEmergencyMqttTimeout<T>(send: (signal: AbortSignal) => Promise<T>):
181
184
  }
182
185
 
183
186
  /**
184
- * Whether an X2D native print stores its job on the SD card or USB stick
187
+ * Whether a native print stores its job on the SD card or USB stick
185
188
  * (true) or internal storage (eMMC). An explicit try_emmc_print wins, then
186
189
  * BAMBU_NATIVE_TRY_EMMC_PRINT read as the helper reads it; otherwise a ready
187
190
  * card is used, as OrcaSlicer does, so the job can be reprinted from the
188
- * printer and read over FTPS.
191
+ * printer and read over FTPS. X1C internal printing additionally requires
192
+ * the capability bit from fresh status, including at final dispatch.
189
193
  */
190
- function nativeExternalStorage(tryEmmcPrint: boolean | undefined, raw: unknown): boolean {
191
- if (tryEmmcPrint !== undefined) return !tryEmmcPrint;
194
+ function nativeExternalStorage(tryEmmcPrint: boolean | undefined, raw: unknown, model: string): boolean {
192
195
  const configured = process.env.BAMBU_NATIVE_TRY_EMMC_PRINT?.trim();
193
- if (configured) return !["1", "true", "TRUE", "yes"].includes(configured);
194
- return externalStorageState(raw) === "normal";
196
+ const external = tryEmmcPrint !== undefined ? !tryEmmcPrint
197
+ : configured ? !["1", "true", "TRUE", "yes"].includes(configured)
198
+ : externalStorageState(raw) === "normal";
199
+ if (!external) assertNativeInternalStorage(model, raw);
200
+ return external;
201
+ }
202
+
203
+ function assertNativeInternalStorage(model: string, raw: unknown): void {
204
+ if (model === "x1c" && !internalPrintingSupported(raw)) {
205
+ throw new Error("X1C internal printing is not advertised in the fresh status. Use a ready SD card or USB stick; unsupported internal storage requests are refused.");
206
+ }
195
207
  }
196
208
 
197
209
  function requestedPrintNozzles(args: Record<string, any>): number[] | undefined {
@@ -245,6 +257,11 @@ type BambuModel = typeof VALID_BAMBU_MODELS[number];
245
257
  // the dual-nozzle H2 path. Keep it in this gate so pre-sliced multi-filament
246
258
  // jobs take the correct branch instead of the legacy 5-slot mapping.
247
259
  const H2_BAMBU_MODELS = new Set<string>(["h2d", "h2dpro", "h2s", "h2c", "x2d"]);
260
+ // Models that may print and upload over connection_mode=bambu_native. X2D
261
+ // defaults to it. X1C opts in: firmware 01.12.00.00 was seen refusing every
262
+ // direct FTPS STOR with 553 while Bambu Studio's plug-in still printed.
263
+ const NATIVE_ROUTE_MODELS = new Set<string>(["x2d", "x1c"]);
264
+ const NATIVE_ROUTE_RESTRICTION = "connection_mode=bambu_native is restricted to X2D and X1C.";
248
265
 
249
266
  const VALID_BED_TYPES = ["textured_plate", "cool_plate", "engineering_plate", "hot_plate", "supertack_plate"] as const;
250
267
  const VALID_NOZZLE_TYPES = ["stainless_steel", "hardened_steel", "tungsten_carbide", "brass"] as const;
@@ -1415,7 +1432,7 @@ class BambuPrinterMCPServer {
1415
1432
  resources: {},
1416
1433
  tools: {}
1417
1434
  },
1418
- instructions: SERVER_INSTRUCTIONS + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
1435
+ instructions: SERVER_INSTRUCTIONS + PRINT_EVIDENCE_GUIDANCE + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
1419
1436
  }
1420
1437
  );
1421
1438
 
@@ -1826,7 +1843,7 @@ class BambuPrinterMCPServer {
1826
1843
  printNozzle
1827
1844
  );
1828
1845
  if (native && args.use_ams !== false && !useAMS) {
1829
- throw new Error("Native X2D printing requires ams_mapping, ams_slots, auto_match_ams, or explicit use_ams: false for an external spool.");
1846
+ throw new Error("Native printing requires ams_mapping, ams_slots, auto_match_ams, or explicit use_ams: false for an external spool.");
1830
1847
  }
1831
1848
  const threeMfFilename = path.basename(threeMFPath);
1832
1849
  const projectName = String(args?.project_name || args?.task_name || threeMfFilename.replace(/\.3mf$/i, ''));
@@ -1928,7 +1945,7 @@ class BambuPrinterMCPServer {
1928
1945
 
1929
1946
  assertActive();
1930
1947
  if (native) {
1931
- const externalStorage = nativeExternalStorage(args?.try_emmc_print, confirmedStatus.raw);
1948
+ const externalStorage = nativeExternalStorage(args?.try_emmc_print, confirmedStatus.raw, printModel);
1932
1949
  if (externalStorage && externalStorageState(confirmedStatus.raw) !== "normal") {
1933
1950
  throw new Error("External storage was requested, but the printer reports no ready SD card or USB stick.");
1934
1951
  }
@@ -1958,7 +1975,9 @@ class BambuPrinterMCPServer {
1958
1975
  if (externalStorage && externalStorageState(dispatchStatus.raw) !== "normal") {
1959
1976
  throw new Error("The printer's SD card or USB stick is no longer ready. Check it and start the print again.");
1960
1977
  }
1978
+ if (!externalStorage) assertNativeInternalStorage(printModel, dispatchStatus.raw);
1961
1979
  assertActive();
1980
+ this.bambu.recordFlightDispatch(devIp,devId,remoteFileName,requirements,resumeFile);
1962
1981
  markPrintCommandSent();
1963
1982
  } });
1964
1983
  assertActive();
@@ -1974,7 +1993,7 @@ class BambuPrinterMCPServer {
1974
1993
  validatePrinterState(dispatchStatus, requirements);
1975
1994
  this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1976
1995
  },
1977
- assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod) { assertActive(); markPrintCommandSent(); } },
1996
+ assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod) { assertActive(); this.bambu.recordFlightDispatch(devIp,devId,remoteFileName,requirements,resumeFile); markPrintCommandSent(); } },
1978
1997
  onDispatched: method => { if (method === bridgeMethod || method === cloudFallbackMethod) retainForDispatchedUpload(); },
1979
1998
  };
1980
1999
  let jobUpdates: BridgeJobUpdate[] = [];
@@ -2081,7 +2100,7 @@ class BambuPrinterMCPServer {
2081
2100
  ): Promise<Record<string, unknown>> {
2082
2101
  assertBambuNativeAvailable();
2083
2102
  const model = await this.resolveBambuModel(args.bambu_model);
2084
- if (model !== "x2d") throw new Error("connection_mode=bambu_native is restricted to X2D.");
2103
+ if (!NATIVE_ROUTE_MODELS.has(model)) throw new Error(NATIVE_ROUTE_RESTRICTION);
2085
2104
  return this.print3mfViaBambuNetwork(
2086
2105
  { ...args, bambu_model: model, connection_type: "lan", bambu_network_method: "start_local_print" },
2087
2106
  host, bambuSerial, bambuToken, { onUpdate, signal }
@@ -2094,9 +2113,9 @@ class BambuPrinterMCPServer {
2094
2113
  ): Promise<Record<string, unknown>> {
2095
2114
  if (args.print) throw new Error("Native upload never starts printing; use print_3mf.");
2096
2115
  // Resolve and enforce the model first, as the print path does, so a
2097
- // non-X2D request is never told to install the native helper.
2116
+ // request for another model is never told to install the native helper.
2098
2117
  const model = await this.resolveBambuModel(args.bambu_model);
2099
- if (model !== "x2d") throw new Error("connection_mode=bambu_native is restricted to X2D.");
2118
+ if (!NATIVE_ROUTE_MODELS.has(model)) throw new Error(NATIVE_ROUTE_RESTRICTION);
2100
2119
  assertBambuNativeAvailable();
2101
2120
  const unsupported = ["use_ams", "ams_mapping", "ams_mapping2", "ams_mapping_info", "nozzle_mapping", "nozzles_info",
2102
2121
  "bed_leveling", "flow_calibration", "vibration_calibration", "layer_inspect", "timelapse"];
@@ -2958,7 +2977,7 @@ class BambuPrinterMCPServer {
2958
2977
  nozzle_mapping: { type: "string", description: "Raw JSON string for FULU PrintParams nozzle_mapping." },
2959
2978
  nozzles_info: { type: "string", description: "Raw JSON string for FULU PrintParams nozzles_info." },
2960
2979
  bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
2961
- flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
2980
+ flow_calibration: { type: "boolean", description: "Flow calibration task boolean. Omission resolves Studio settings (auto on P1/P1S); direct MQTT sends false for auto but does not transmit the integer auto mode. The result calibration report distinguishes resolved and transmitted options." },
2962
2981
  vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
2963
2982
  layer_inspect: { type: "boolean", description: "First-layer inspection where supported (default true, as Bambu Studio sends)." },
2964
2983
  timelapse: { type: "boolean", description: "Enable timelapse recording in FULU PrintParams (default: false)." },
@@ -3040,7 +3059,7 @@ class BambuPrinterMCPServer {
3040
3059
  connection_mode: {
3041
3060
  type: "string",
3042
3061
  enum: ["lan_mqtt_ftps", "bambu_native"],
3043
- description: "Upload transport; bambu_native uses the installed Bambu networking plug-in for X2D and never starts printing."
3062
+ description: "Upload transport; bambu_native uses the installed Bambu networking plug-in for X2D or X1C and never starts printing."
3044
3063
  },
3045
3064
  bambu_model: {
3046
3065
  type: "string",
@@ -3349,9 +3368,9 @@ class BambuPrinterMCPServer {
3349
3368
  connection_mode: {
3350
3369
  type: "string",
3351
3370
  enum: ["lan_mqtt_ftps", "bambu_network", "bambu_native", "bambu_connect"],
3352
- description: "Print path: bambu_connect hands a printable file to the signed-in Bambu Connect app for cloud-mode review; X2D otherwise defaults to bambu_native (Bambu Studio's installed local networking plug-in, storing the job on a ready SD card or USB stick, otherwise internal eMMC); lan_mqtt_ftps is the legacy direct MQTT/FTPS path; bambu_network uses the FULU bridge."
3371
+ description: "Print path: bambu_connect hands a printable file to the signed-in Bambu Connect app for cloud-mode review; X2D otherwise defaults to bambu_native (Bambu Studio's installed local networking plug-in, storing the job on a ready SD card or USB stick, otherwise internal eMMC); X1C may opt in to bambu_native, for example when its firmware refuses FTPS uploads with 553; lan_mqtt_ftps is the legacy direct MQTT/FTPS path; bambu_network uses the FULU bridge."
3353
3372
  },
3354
- try_emmc_print: { type: "boolean", description: "X2D native printing: true stores the job on internal storage (eMMC), false on the SD card or USB stick (refused unless the printer reports one ready). Omit to use the card when ready, else eMMC; BAMBU_NATIVE_TRY_EMMC_PRINT sets a server default." },
3373
+ try_emmc_print: { type: "boolean", description: "X2D native printing: true stores the job on internal storage (eMMC), false on the SD card or USB stick (refused unless the printer reports one ready). Omit to use the card when ready, else eMMC; X1C requires fresh advertised internal-printing support before using eMMC. BAMBU_NATIVE_TRY_EMMC_PRINT sets a server default." },
3355
3374
  connection_type: { type: "string", enum: ["cloud", "lan"], description: "BambuNetwork connection type when connection_mode is bambu_network; cloud uses restored internet printing, lan uses local bridge printing." },
3356
3375
  bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method when connection_mode is bambu_network; defaults to start_local_print for lan, and for cloud to Bambu Studio's order: start_local_print_with_record, then start_print if that fails." },
3357
3376
  dev_id: { type: "string", description: "Bambu device id for FULU BambuNetwork printing; defaults to BAMBU_DEV_ID or BAMBU_SERIAL." },
@@ -3401,7 +3420,7 @@ class BambuPrinterMCPServer {
3401
3420
  description: "When true, match the sliced 3MF's tray_info_idx requirements against live AMS inventory and use the resulting ams_slots. Ignored when ams_mapping or ams_slots is provided."
3402
3421
  },
3403
3422
  bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
3404
- flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
3423
+ flow_calibration: { type: "boolean", description: "Flow calibration task boolean. Omission resolves Studio settings (auto on P1/P1S); direct MQTT sends false for auto but does not transmit the integer auto mode. The result calibration report distinguishes resolved and transmitted options." },
3405
3424
  vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
3406
3425
  timelapse: { type: "boolean", description: "Enable timelapse recording (default: false)" },
3407
3426
  slicer_profile: { type: "string", description: "Path to the slicer profile/config file for auto-slicing (optional)." },
@@ -3437,7 +3456,7 @@ class BambuPrinterMCPServer {
3437
3456
  description: "Bed plate type currently installed (default: textured_plate)"
3438
3457
  },
3439
3458
  bed_leveling: { type: "boolean", description: "Auto bed leveling on or off. Omit to send what Bambu Studio's Send dialog would: the choice saved in BambuStudio.conf for this printer, else Studio's default." },
3440
- flow_calibration: { type: "boolean", description: "Flow calibration on or off. Omit to send what Bambu Studio's Send dialog would (auto on P1/P1S)." },
3459
+ flow_calibration: { type: "boolean", description: "Flow calibration task boolean. Omission resolves Studio settings (auto on P1/P1S); direct MQTT sends false for auto but does not transmit the integer auto mode. The result calibration report distinguishes resolved and transmitted options." },
3441
3460
  vibration_calibration: { type: "boolean", description: "Vibration calibration (default false, as Bambu Studio sends)." },
3442
3461
  timelapse: { type: "boolean", description: "Enable timelapse recording (default: false)" },
3443
3462
  slicer_profile: { type: "string", description: "Path to the slicer profile/config file for auto-slicing (optional)." },
@@ -3597,6 +3616,16 @@ class BambuPrinterMCPServer {
3597
3616
  additionalProperties: false
3598
3617
  }
3599
3618
  },
3619
+ {
3620
+ name: "counterpart_print_record", description: FLIGHT_RECORD_DESCRIPTION,
3621
+ inputSchema: {type:"object",properties:{...FLIGHT_RECORD_PROPERTIES,host:{type:"string",description:"Saved printer hostname or address; used only to select a local record."},bambu_serial:{type:"string",description:"Saved Bambu printer serial; used only to select a local record."}},additionalProperties:false},
3622
+ outputSchema: FLIGHT_RECORD_OUTPUT_SCHEMA
3623
+ },
3624
+ {
3625
+ name:"counterpart_print_assess",description:FLIGHT_ASSESS_DESCRIPTION,
3626
+ inputSchema:{type:"object",properties:{...FLIGHT_ASSESS_PROPERTIES,host:{type:"string",description:"Saved printer hostname or address; used only to select a local record."},bambu_serial:{type:"string",description:"Saved Bambu printer serial; used only to select a local record."}},required:FLIGHT_ASSESS_REQUIRED,additionalProperties:false},
3627
+ outputSchema:FLIGHT_RECORD_OUTPUT_SCHEMA
3628
+ },
3600
3629
  {
3601
3630
  name: "counterpart_print_progress",
3602
3631
  description: "Counterpart contract (counterpart/1): the printer's state, current job (name, task id, percent, time left, layers, stage words), temperatures, active filament and problems with Bambu's HMS messages and links. Read from the MQTT report this server keeps, so a held session asks the printer nothing; observedAt is when the printer sent it. An unreachable printer reports state offline. Read-only; not a safety check.",
@@ -3802,7 +3831,9 @@ class BambuPrinterMCPServer {
3802
3831
  ? linuxEmergency(() => nativeCommand(), signal => this.bambu.sendStopOverMqtt(host, bambuSerial, bambuToken, signal))
3803
3832
  : nativeCommand;
3804
3833
  }
3805
- if (route.mode === "bambu_native") throw new Error(nativeUnavailableReason()!);
3834
+ // Native controls are X2D-only. Another model printed natively (X1C)
3835
+ // is stopped, paused and resumed over direct MQTT, as its default route is.
3836
+ if (route.mode === "bambu_native" && x2dTarget) throw new Error(nativeUnavailableReason()!);
3806
3837
  if (route.mode !== "bambu_network") return undefined;
3807
3838
  return (assertActive?: () => void, beforeDispatch?: () => Promise<void>) => {
3808
3839
  const options = { assertDispatchAllowed: () => { extra.signal.throwIfAborted(); assertActive?.(); } };
@@ -5101,11 +5132,20 @@ class BambuPrinterMCPServer {
5101
5132
  break;
5102
5133
  }
5103
5134
 
5135
+ case "counterpart_print_assess":
5136
+ return flightRecordResult(this.bambu.flightRecords.submitVisual(flightKey(host,bambuSerial),visualSubmission(args)));
5137
+
5138
+ case "counterpart_print_record":
5139
+ return flightRecordResult(this.bambu.flightRecords.read(flightKey(host,bambuSerial),flightReadOptions(args)),args?.frame_format==="images");
5140
+
5104
5141
  case "counterpart_print_progress": {
5105
5142
  const report = await this.bambu.readProgressReport(host, bambuSerial, bambuToken);
5143
+ if (report) void this.bambu.flightRecords.sample(flightKey(host,bambuSerial), after => this.bambu.cameraSnapshot(host,bambuSerial,bambuToken,{bambuModel:this.displayModel(args,bambuSerial),timeoutMs:8000,capturedAfter:after})).catch(() => undefined);
5106
5144
  result = report
5107
5145
  ? bambuProgress(report.raw, { receivedAt: report.receivedAt, serial: bambuSerial, model: this.displayModel(args, bambuSerial) })
5108
5146
  : offlineProgress(Date.now());
5147
+ const physical=this.bambu.flightRecords.physicalForReport(flightKey(host,bambuSerial),report?.raw);
5148
+ result = {...result, physical,problems:[...physicalProblems(physical, result.state === "finished"),...result.problems]};
5109
5149
  break;
5110
5150
  }
5111
5151