bambu-printer-mcp 1.1.90 → 1.1.91

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 (42) hide show
  1. package/README.md +43 -0
  2. package/dist/counterpart/flight-record.d.ts +155 -0
  3. package/dist/counterpart/flight-record.js +831 -0
  4. package/dist/counterpart/flight-tools.d.ts +213 -0
  5. package/dist/counterpart/flight-tools.js +232 -0
  6. package/dist/counterpart/fresh-frame.d.ts +16 -0
  7. package/dist/counterpart/fresh-frame.js +26 -0
  8. package/dist/counterpart/make-3mf.js +1 -4
  9. package/dist/counterpart/physical-evidence.d.ts +70 -0
  10. package/dist/counterpart/physical-evidence.js +103 -0
  11. package/dist/counterpart/print-geometry.d.ts +13 -0
  12. package/dist/counterpart/print-geometry.js +181 -0
  13. package/dist/counterpart/remote.js +2 -0
  14. package/dist/counterpart/schemas.d.ts +32 -0
  15. package/dist/counterpart/schemas.js +2 -0
  16. package/dist/counterpart/visual-evidence.d.ts +38 -0
  17. package/dist/counterpart/visual-evidence.js +155 -0
  18. package/dist/index.js +24 -1
  19. package/dist/printers/bambu.d.ts +9 -2
  20. package/dist/printers/bambu.js +32 -6
  21. package/dist/safety/print-preview.d.ts +2 -0
  22. package/dist/safety/print-preview.js +1 -1
  23. package/dist/slicer/3mf-xml.d.ts +7 -0
  24. package/dist/slicer/3mf-xml.js +61 -0
  25. package/dist/stl/stl-manipulator.js +5 -2
  26. package/dist/tool-annotations.js +2 -0
  27. package/package.json +2 -1
  28. package/src/counterpart/flight-record.ts +984 -0
  29. package/src/counterpart/flight-tools.ts +282 -0
  30. package/src/counterpart/fresh-frame.ts +45 -0
  31. package/src/counterpart/make-3mf.ts +1 -5
  32. package/src/counterpart/physical-evidence.ts +185 -0
  33. package/src/counterpart/print-geometry.ts +192 -0
  34. package/src/counterpart/remote.ts +2 -0
  35. package/src/counterpart/schemas.ts +3 -0
  36. package/src/counterpart/visual-evidence.ts +212 -0
  37. package/src/index.ts +25 -2
  38. package/src/printers/bambu.ts +34 -5
  39. package/src/safety/print-preview.ts +1 -1
  40. package/src/slicer/3mf-xml.ts +52 -0
  41. package/src/stl/stl-manipulator.ts +4 -1
  42. 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";
@@ -1415,7 +1418,7 @@ class BambuPrinterMCPServer {
1415
1418
  resources: {},
1416
1419
  tools: {}
1417
1420
  },
1418
- instructions: SERVER_INSTRUCTIONS + (CAD_ENABLED ? " For headless dimensioned designs and parameter edits, read the cad_design prompt before using cad_run." : "")
1421
+ 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
1422
  }
1420
1423
  );
1421
1424
 
@@ -1959,6 +1962,7 @@ class BambuPrinterMCPServer {
1959
1962
  throw new Error("The printer's SD card or USB stick is no longer ready. Check it and start the print again.");
1960
1963
  }
1961
1964
  assertActive();
1965
+ this.bambu.recordFlightDispatch(devIp,devId,remoteFileName,requirements,resumeFile);
1962
1966
  markPrintCommandSent();
1963
1967
  } });
1964
1968
  assertActive();
@@ -1974,7 +1978,7 @@ class BambuPrinterMCPServer {
1974
1978
  validatePrinterState(dispatchStatus, requirements);
1975
1979
  this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1976
1980
  },
1977
- assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod) { assertActive(); markPrintCommandSent(); } },
1981
+ assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod) { assertActive(); this.bambu.recordFlightDispatch(devIp,devId,remoteFileName,requirements,resumeFile); markPrintCommandSent(); } },
1978
1982
  onDispatched: method => { if (method === bridgeMethod || method === cloudFallbackMethod) retainForDispatchedUpload(); },
1979
1983
  };
1980
1984
  let jobUpdates: BridgeJobUpdate[] = [];
@@ -3597,6 +3601,16 @@ class BambuPrinterMCPServer {
3597
3601
  additionalProperties: false
3598
3602
  }
3599
3603
  },
3604
+ {
3605
+ name: "counterpart_print_record", description: FLIGHT_RECORD_DESCRIPTION,
3606
+ 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},
3607
+ outputSchema: FLIGHT_RECORD_OUTPUT_SCHEMA
3608
+ },
3609
+ {
3610
+ name:"counterpart_print_assess",description:FLIGHT_ASSESS_DESCRIPTION,
3611
+ 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},
3612
+ outputSchema:FLIGHT_RECORD_OUTPUT_SCHEMA
3613
+ },
3600
3614
  {
3601
3615
  name: "counterpart_print_progress",
3602
3616
  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.",
@@ -5101,11 +5115,20 @@ class BambuPrinterMCPServer {
5101
5115
  break;
5102
5116
  }
5103
5117
 
5118
+ case "counterpart_print_assess":
5119
+ return flightRecordResult(this.bambu.flightRecords.submitVisual(flightKey(host,bambuSerial),visualSubmission(args)));
5120
+
5121
+ case "counterpart_print_record":
5122
+ return flightRecordResult(this.bambu.flightRecords.read(flightKey(host,bambuSerial),flightReadOptions(args)),args?.frame_format==="images");
5123
+
5104
5124
  case "counterpart_print_progress": {
5105
5125
  const report = await this.bambu.readProgressReport(host, bambuSerial, bambuToken);
5126
+ 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
5127
  result = report
5107
5128
  ? bambuProgress(report.raw, { receivedAt: report.receivedAt, serial: bambuSerial, model: this.displayModel(args, bambuSerial) })
5108
5129
  : offlineProgress(Date.now());
5130
+ const physical=this.bambu.flightRecords.physicalForReport(flightKey(host,bambuSerial),report?.raw);
5131
+ result = {...result, physical,problems:[...physicalProblems(physical, result.state === "finished"),...result.problems]};
5109
5132
  break;
5110
5133
  }
5111
5134
 
@@ -1,3 +1,6 @@
1
+ import {snapshotFrame} from "../counterpart/fresh-frame.js";
2
+ import {FlightRecords,flightKey,type PrintGeometry} from "../counterpart/flight-record.js";
3
+ import {geometryFromGcode,geometryFromFile} from "../counterpart/print-geometry.js";
1
4
  import { PrinterRefusal, markPrintCommandSent } from "../refusal.js";
2
5
  import {CameraStreams, type FrameOptions} from "./camera-stream.js";
3
6
  import {openTcpCameraSource, openRtspCameraSource} from "./camera-sources.js";
@@ -598,6 +601,7 @@ export type ProgressReport = { raw: Record<string, any>; receivedAt: number };
598
601
  /** The inspected bytes and limits of a started job, for the resume prompt and byte check. */
599
602
  export type CheckedFile = {
600
603
  sha256: string;
604
+ expected?: PrintGeometry;
601
605
  /** A project's printed plate: its number and the SHA-256 of its Metadata/plate_<index>.gcode. */
602
606
  plate?: { index: number; sha256: string };
603
607
  model: string;
@@ -716,13 +720,21 @@ function reportsJob(raw: Record<string, any>, remotePath: string): boolean {
716
720
  export async function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile> {
717
721
  const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
718
722
  let plate: CheckedFile["plate"];
723
+ let expected: PrintGeometry | undefined;
719
724
  const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
720
725
  if (plateNumber && /\.3mf$/i.test(filePath)) {
721
726
  const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath!);
722
- if (entry) plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
727
+ if (entry) {
728
+ const bytes = await entry.async("nodebuffer");
729
+ plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(bytes).digest("hex") };
730
+ if (bytes.length <= 64 * 1024 * 1024) expected = geometryFromGcode(bytes.toString("utf8"));
731
+ }
732
+ } else if (!/\.3mf$/i.test(filePath)) {
733
+ expected = await geometryFromFile(filePath);
723
734
  }
735
+
724
736
  return {
725
- sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
737
+ sha256: inspection.sha256, ...(plate ? { plate } : {}), ...(expected ? { expected } : {}), model: inspection.model,
726
738
  maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
727
739
  materials: [...new Set(used.length ? used : inspection.materials)],
728
740
  };
@@ -753,6 +765,7 @@ export type PrintPreflight = { finishedJob?: string; serial: string; model: stri
753
765
  export {cameraFrameParser} from "./camera-wire.js";
754
766
 
755
767
  export class BambuImplementation {
768
+ readonly flightRecords = new FlightRecords();
756
769
  private printerStore: BambuClientStore;
757
770
  readonly cameraStreams = new CameraStreams();
758
771
  /**
@@ -846,16 +859,26 @@ export class BambuImplementation {
846
859
  * verified: a resume then re-reads it if it can and otherwise matches the
847
860
  * unique name, as KAN-216 does for firmware that cannot download a file.
848
861
  */
862
+ /** At the existing send-authorization boundary: record evidence even if the reply/helper is lost. */
863
+ recordFlightDispatch(host:string,serial:string,remotePath:string,requirements:PrinterStateRequirements,file:CheckedFile):void {
864
+ this.flightRecords.begin(flightKey(host,serial),{sha256:file.sha256,jobName:remotePath,mapping:requirements.amsMapping,materials:file.materials,plate:file.plate,expected:file.expected});
865
+ }
866
+
849
867
  recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements, file: CheckedFile, uploadedHere = true): void {
850
868
  if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? "")) throw new Error("A started job needs the SHA-256 of its inspected bytes.");
851
869
  this.checkedJobs.set(`${host}\n${serial}`, {
852
870
  ...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
853
871
  });
872
+ if(!this.flightRecords.accept(flightKey(host,serial),remotePath)){
873
+ this.recordFlightDispatch(host,serial,remotePath,requirements,file);
874
+ this.flightRecords.accept(flightKey(host,serial),remotePath);
875
+ }
854
876
  this.clearedErrors.delete(serial);
855
877
  }
856
878
 
857
879
  /** Feed one merged report to the resume record (internal; the client store calls it for every report). */
858
880
  observeReport(host: string, serial: string, raw: Record<string, any> | undefined): void {
881
+ if (raw) this.flightRecords.observe(flightKey(host, serial), raw);
859
882
  const key = `${host}\n${serial}`;
860
883
  const checked = this.checkedJobs.get(key);
861
884
  if (!checked || !raw || typeof raw.gcode_state !== "string") return;
@@ -1273,6 +1296,7 @@ export class BambuImplementation {
1273
1296
  assertActive();
1274
1297
  if (legacyContainer) {
1275
1298
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1299
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1276
1300
  markPrintCommandSent();
1277
1301
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath })); } catch (error) { watcher.dispose(); throw error; }
1278
1302
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
@@ -1355,6 +1379,7 @@ export class BambuImplementation {
1355
1379
  }
1356
1380
 
1357
1381
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
1382
+ this.recordFlightDispatch(host,serial,remoteProjectPath,requirements,resumeFile);
1358
1383
  markPrintCommandSent();
1359
1384
  try { await printer.publish(projectFileCmd); } catch (error) { watcher.dispose(); throw error; }
1360
1385
  this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
@@ -2016,6 +2041,7 @@ export class BambuImplementation {
2016
2041
  const printer = await this.getPrinter(host, serial, token);
2017
2042
  assertActive();
2018
2043
  const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
2044
+ this.recordFlightDispatch(host,serial,remotePath,requirements,resumeFile);
2019
2045
  markPrintCommandSent();
2020
2046
  try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath })); } catch (error) { watcher.dispose(); throw error; }
2021
2047
  this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
@@ -2174,6 +2200,7 @@ export class BambuImplementation {
2174
2200
  token: string,
2175
2201
  options: {
2176
2202
  savePath?: string;
2203
+ capturedAfter?: string;
2177
2204
  timeoutMs?: number;
2178
2205
  bambuModel?: string;
2179
2206
  /**
@@ -2196,6 +2223,7 @@ export class BambuImplementation {
2196
2223
  sizeBytes: number;
2197
2224
  base64: string;
2198
2225
  savedTo?: string;
2226
+ capturedAt?: string;
2199
2227
  width?: number;
2200
2228
  height?: number;
2201
2229
  note?: string;
@@ -2204,10 +2232,11 @@ export class BambuImplementation {
2204
2232
  const timeoutMs = options.timeoutMs ?? 8_000;
2205
2233
  const stream = this.cameraStreams.get(JSON.stringify([host, _serial]));
2206
2234
  if (stream && !stream.stopped) {
2207
- const jpeg = await stream.latest(Math.min(timeoutMs, 10_000));
2208
- if (!jpeg) throw new Error("The active camera stream has not produced a live frame");
2235
+ const frame = await snapshotFrame(stream,timeoutMs,options.capturedAfter);
2236
+ if (frame.status!=="frame"||!frame.base64) throw new Error("The active camera stream has not produced a live frame");
2237
+ const jpeg=Buffer.from(frame.base64,"base64");
2209
2238
  if (options.savePath) await (await import("node:fs/promises")).writeFile(options.savePath, jpeg);
2210
- return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport,
2239
+ return {status: "success", format: "image/jpeg", sizeBytes: jpeg.length, base64: jpeg.toString("base64"), transport: stream.transport, capturedAt:frame.capturedAt,
2211
2240
  ...(options.savePath ? {savedTo: options.savePath} : {})};
2212
2241
  }
2213
2242
  const model = (options.bambuModel ?? "").toLowerCase();
@@ -153,7 +153,7 @@ function parameterWords(text: string): Map<string, number> {
153
153
  }
154
154
 
155
155
  /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
156
- function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
156
+ export function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
157
157
  if (i !== undefined || j !== undefined) return [x + (i ?? 0), y + (j ?? 0)];
158
158
  if (r === undefined || r === 0 || (tx === x && ty === y)) return undefined;
159
159
  const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);