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,831 @@
1
+ /** Bounded private per-job evidence. No printer transport, polling, model call or control lives here. */
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { assessVisual, assessmentRequest, validateVisualSubmission, } from "./visual-evidence.js";
7
+ import { assessPhysical, } from "./physical-evidence.js";
8
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
9
+ const stem = (value) => path.posix
10
+ .basename(value.replace(/\\/g, "/"))
11
+ .replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
12
+ export const flightKey = (host, serial) => `${host}\n${serial}`;
13
+ const num = (v) => typeof v === "number" && Number.isFinite(v)
14
+ ? v
15
+ : typeof v === "string" &&
16
+ /^-?\d+(\.\d+)?$/.test(v) &&
17
+ Number.isFinite(Number(v))
18
+ ? Number(v)
19
+ : null;
20
+ const token = (v) => typeof v === "string" && /^[a-zA-Z0-9 _.-]{1,48}$/.test(v) ? v : null;
21
+ const diagnosticScalar = (value) => {
22
+ if (typeof value === "number")
23
+ return Number.isFinite(value) ? value : null;
24
+ if (typeof value === "boolean")
25
+ return value;
26
+ return typeof value === "string" &&
27
+ /^(?:-?\d+(?:\.\d+)?|(?:0x)?[a-f\d]{1,16})$/i.test(value)
28
+ ? value
29
+ : null;
30
+ };
31
+ const fields = (source, keys) => Object.fromEntries(keys
32
+ .filter((k) => source?.[k] !== undefined)
33
+ .map((k) => [k, diagnosticScalar(source[k])]));
34
+ function tray(value) {
35
+ return {
36
+ ...fields(value, [
37
+ "id",
38
+ "state",
39
+ "remain",
40
+ "nozzle_temp_min",
41
+ "nozzle_temp_max",
42
+ ]),
43
+ tray_type: token(value?.tray_type),
44
+ tray_info_idx: token(value?.tray_info_idx),
45
+ tray_color: typeof value?.tray_color === "string" &&
46
+ /^[\da-f]{6}([\da-f]{2})?$/i.test(value.tray_color)
47
+ ? value.tray_color
48
+ : null,
49
+ };
50
+ }
51
+ /** An allowlist, not a recursive dump/redactor. Unknown fields and arbitrary strings never reach disk. */
52
+ export function flightSnapshot(raw) {
53
+ const snapshot = {
54
+ ...fields(raw, [
55
+ "layer_num",
56
+ "total_layer_num",
57
+ "mc_percent",
58
+ "print_error",
59
+ "fail_reason",
60
+ "mc_print_stage",
61
+ "mc_print_sub_stage",
62
+ "stg_cur",
63
+ "ams_status",
64
+ "hw_switch_state",
65
+ "home_flag",
66
+ "nozzle_temper",
67
+ "nozzle_target_temper",
68
+ "bed_temper",
69
+ "bed_target_temper",
70
+ ]),
71
+ gcode_state: token(raw.gcode_state),
72
+ };
73
+ if (raw.observation_source === "adapter-progress")
74
+ snapshot.observation_source = "adapter-progress";
75
+ if (Array.isArray(raw.adapter_problems))
76
+ snapshot.adapter_problems = raw.adapter_problems
77
+ .slice(0, 32)
78
+ .map((p) => ({
79
+ code: token(p?.code),
80
+ severity: ["fatal", "error", "warning", "info"].includes(p?.severity)
81
+ ? p.severity
82
+ : null,
83
+ }));
84
+ if (Array.isArray(raw.hms))
85
+ snapshot.hms = raw.hms
86
+ .slice(0, 32)
87
+ .map((h) => fields(h, ["attr", "code"]));
88
+ if (Array.isArray(raw.stg))
89
+ snapshot.stg = raw.stg.slice(0, 64).map(num);
90
+ if (raw.ams && typeof raw.ams === "object")
91
+ snapshot.ams = {
92
+ ...fields(raw.ams, [
93
+ "tray_now",
94
+ "tray_tar",
95
+ "tray_pre",
96
+ "tray_exist_bits",
97
+ ]),
98
+ ams: Array.isArray(raw.ams.ams)
99
+ ? raw.ams.ams.slice(0, 16).map((a) => ({
100
+ ...fields(a, ["id"]),
101
+ tray: Array.isArray(a?.tray) ? a.tray.slice(0, 16).map(tray) : [],
102
+ }))
103
+ : [],
104
+ };
105
+ if (raw.vt_tray)
106
+ snapshot.vt_tray = tray(raw.vt_tray);
107
+ if (Array.isArray(raw.vir_slot))
108
+ snapshot.vir_slot = raw.vir_slot.slice(0, 4).map(tray);
109
+ if (raw.device?.extruder)
110
+ snapshot.extruder = {
111
+ ...fields(raw.device.extruder, ["state"]),
112
+ info: Array.isArray(raw.device.extruder.info)
113
+ ? raw.device.extruder.info
114
+ .slice(0, 4)
115
+ .map((i) => fields(i, ["id", "temp", "snow", "hnow", "hpre", "htar"]))
116
+ : [],
117
+ };
118
+ if (raw.xcam)
119
+ snapshot.xcam = fields(raw.xcam, [
120
+ "cfg",
121
+ "printing_monitor",
122
+ "spaghetti_detector",
123
+ "print_halt",
124
+ ]);
125
+ return snapshot;
126
+ }
127
+ const activeExecution = (raw) => ["PREPARE", "PREPARING", "SLICING", "RUNNING", "PRINTING", "PAUSE", "PAUSED"].includes(String(raw?.gcode_state).toUpperCase());
128
+ const executionIds = (raw) => Object.fromEntries(["task_id", "subtask_id"].flatMap(key => {
129
+ const value = raw?.[key];
130
+ if ((typeof value !== "string" && typeof value !== "number") || !String(value).length || String(value).length > 128 || ["0", "-1"].includes(String(value)))
131
+ return [];
132
+ return [[key, hash(String(value))]];
133
+ }));
134
+ const changedExecution = (record, raw) => Object.entries(executionIds(raw)).some(([key, value]) => record.execution?.[key] !== undefined && record.execution[key] !== value);
135
+ export class FlightRecords {
136
+ constructor(options = {}) {
137
+ this.cache = new Map();
138
+ this.pending = new Map();
139
+ this.recentReports = new Map();
140
+ this.superseded = new Set();
141
+ this.warned = false;
142
+ this.ownerToken = randomUUID();
143
+ this.dir =
144
+ options.dir ??
145
+ process.env.COUNTERPART_RECORD_DIR ??
146
+ (process.env.BAMBU_RESUME_STATE_DIR
147
+ ? path.join(process.env.BAMBU_RESUME_STATE_DIR, "print-records")
148
+ : path.join(os.homedir(), ".config", "bambu-printer-mcp", "print-records"));
149
+ this.maxCaptureMs = Math.max(1, Math.min(10000, options.maxCaptureMs ?? 10000));
150
+ this.now = options.now ?? Date.now;
151
+ this.maxEvents = Math.max(2, Math.min(2048, options.maxEvents ?? 2048));
152
+ this.maxJobs = Math.max(1, Math.min(10, options.maxJobs ?? 10));
153
+ this.maxBytes = Math.max(4096, Math.min(1024 * 1024, options.maxBytes ?? 1024 * 1024));
154
+ }
155
+ begin(key, input) {
156
+ if (!/^[a-f\d]{64}$/.test(input.sha256))
157
+ throw Error("A print record requires an inspected artifact SHA-256.");
158
+ const printerKey = hash(key);
159
+ const id = randomUUID();
160
+ const record = {
161
+ version: 1,
162
+ seenActive: false,
163
+ owner: { pid: process.pid, token: this.ownerToken },
164
+ id,
165
+ printerKey,
166
+ dispatchedAt: new Date(this.now()).toISOString(),
167
+ dispatch: {
168
+ sha256: input.sha256,
169
+ jobHash: hash(stem(input.jobName)),
170
+ outcome: "unconfirmed",
171
+ ...(input.mapping
172
+ ? {
173
+ mapping: input.mapping
174
+ .slice(0, 64)
175
+ .map((n) => Number.isInteger(n) && n >= -1 && n <= 4095 ? n : -1),
176
+ }
177
+ : {}),
178
+ ...(input.materials
179
+ ? {
180
+ materials: input.materials
181
+ .slice(0, 64)
182
+ .map((m) => token(m) ?? "unknown"),
183
+ }
184
+ : {}),
185
+ ...(input.plate && /^[a-f\d]{64}$/.test(input.plate.sha256)
186
+ ? { plate: { index: input.plate.index, sha256: input.plate.sha256 } }
187
+ : {}),
188
+ },
189
+ ...(input.expected ? { expected: structuredClone(input.expected) } : {}),
190
+ reports: [],
191
+ latest: {},
192
+ droppedReports: 0,
193
+ nextSeq: 1,
194
+ frames: [],
195
+ skippedCheckpoints: [],
196
+ droppedFrames: 0,
197
+ sampledCheckpoints: [],
198
+ storage: "durable",
199
+ };
200
+ this.recentReports.delete(printerKey);
201
+ this.cache.set(printerKey, record);
202
+ this.save(record);
203
+ this.prune();
204
+ return id;
205
+ }
206
+ accept(key, jobName) {
207
+ const record = this.get(key);
208
+ if (!record ||
209
+ record.dispatch.jobHash !== hash(stem(jobName)) ||
210
+ !this.canWrite(record))
211
+ return false;
212
+ if (!record.seenActive)
213
+ record.dispatch.outcome = "accepted";
214
+ record.dispatch.acceptedAt = new Date(this.now()).toISOString();
215
+ this.save(record);
216
+ return true;
217
+ }
218
+ observe(key, raw, at = this.now()) {
219
+ const record = this.get(key);
220
+ if (!record || !Number.isFinite(at) || at < Date.parse(record.dispatchedAt))
221
+ return;
222
+ const previousAt = record.reports[record.reports.length - 1]?.at;
223
+ if (previousAt && at < Date.parse(previousAt))
224
+ return;
225
+ const names = [raw.subtask_name, raw.gcode_file].filter((n) => typeof n === "string" && !!n);
226
+ const named = names.some((n) => hash(stem(n)) === record.dispatch.jobHash);
227
+ if (named && (changedExecution(record, raw) || (record.endedAt && activeExecution(raw))))
228
+ this.invalidateExecution(record);
229
+ const matches = named && !this.isSuperseded(record);
230
+ this.recentReports.set(record.printerKey, { id: record.id, at, matches });
231
+ while (this.recentReports.size > this.maxJobs) {
232
+ const first = this.recentReports.keys().next().value;
233
+ if (first === undefined)
234
+ break;
235
+ this.recentReports.delete(first);
236
+ }
237
+ if (!matches || !this.canWrite(record))
238
+ return;
239
+ if (record.endedAt)
240
+ return;
241
+ const ids = activeExecution(raw) ? executionIds(raw) : {};
242
+ const identityChanged = Object.keys(ids).some(key => record.execution?.[key] === undefined);
243
+ if (identityChanged)
244
+ record.execution = { ...record.execution, ...ids };
245
+ const snapshot = flightSnapshot(raw);
246
+ const changes = Object.fromEntries(Object.entries(snapshot).filter(([k, v]) => JSON.stringify(v) !== JSON.stringify(record.latest[k])));
247
+ if (!Object.keys(changes).length) {
248
+ if (identityChanged)
249
+ this.save(record);
250
+ return;
251
+ }
252
+ const state = String(snapshot.gcode_state);
253
+ if (["PREPARE", "SLICING", "RUNNING", "PAUSE"].includes(state)) {
254
+ record.seenActive = true;
255
+ record.dispatch.outcome = "observed-active";
256
+ }
257
+ if (record.seenActive && ["FINISH", "FAILED", "IDLE"].includes(state))
258
+ record.endedAt = new Date(at).toISOString();
259
+ record.latest = { ...record.latest, ...changes };
260
+ record.reports.push({
261
+ seq: record.nextSeq++,
262
+ at: new Date(at).toISOString(),
263
+ changes,
264
+ });
265
+ while (record.reports.length > this.maxEvents) {
266
+ record.reports.shift();
267
+ record.droppedReports++;
268
+ }
269
+ this.save(record);
270
+ }
271
+ /** Progress may expose saved evidence only for the job in this returned report. */
272
+ physicalForReport(key, raw) {
273
+ const record = this.get(key);
274
+ const names = [raw?.subtask_name, raw?.gcode_file].filter((name) => typeof name === "string" && !!name);
275
+ const named = record && names.some((name) => hash(stem(name)) === record.dispatch.jobHash);
276
+ if (record && named && (changedExecution(record, raw) || (record.endedAt && activeExecution(raw))))
277
+ this.invalidateExecution(record);
278
+ if (!record || !named || this.isSuperseded(record)) {
279
+ return {
280
+ status: "unknown",
281
+ evidence: [],
282
+ limitations: [
283
+ "No retained physical evidence matches the currently reported job.",
284
+ "Firmware completion is separate from physical success.",
285
+ ],
286
+ };
287
+ }
288
+ // Bind this read to the matched record even if another MCP dispatches concurrently.
289
+ return this.read(key, { jobId: record.id }).physical;
290
+ }
291
+ read(key, options = {}) {
292
+ if (options.jobId &&
293
+ !/^[a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(options.jobId))
294
+ throw Error("Invalid print record ID.");
295
+ const jobs = options.listJobs ? this.jobSummaries(key) : undefined;
296
+ const record = this.get(key, options.jobId);
297
+ if (!record)
298
+ return {
299
+ contract: "counterpart/1",
300
+ status: "unavailable",
301
+ ...(jobs ? { jobs } : {}),
302
+ physical: assessPhysical([]),
303
+ };
304
+ const result = structuredClone(record);
305
+ delete result.owner;
306
+ result.executionSuperseded = this.isSuperseded(record);
307
+ const observations = this.visuals(record);
308
+ result.visualObservations = observations;
309
+ if (options.frameIds &&
310
+ (options.frameIds.length > 4 ||
311
+ options.frameIds.some((id) => !result.frames.some((f) => f.id === id))))
312
+ throw Error("Requested frame is not part of this job (at most four).");
313
+ const request = assessmentRequest(result.frames, observations, result.expected);
314
+ const selected = new Set(options.frameIds ??
315
+ (request
316
+ ? [request.frameId, ...request.referenceFrameIds]
317
+ : observations.length
318
+ ? [
319
+ observations.at(-1).frameId,
320
+ ...(observations.at(-1).referenceFrameId
321
+ ? [observations.at(-1).referenceFrameId]
322
+ : []),
323
+ ]
324
+ : result.frames
325
+ .filter((f) => f.status === "captured")
326
+ .slice(-4)
327
+ .map((f) => f.id)).slice(0, 4));
328
+ const retainedVisual = assessVisual(result.frames, observations, result.expected);
329
+ const verify = new Set([
330
+ ...(retainedVisual?.evidence ?? []),
331
+ ...observations
332
+ .slice(-1)
333
+ .flatMap((o) => [
334
+ o.frameId,
335
+ ...(o.referenceFrameId ? [o.referenceFrameId] : []),
336
+ ]),
337
+ ]);
338
+ for (const frame of result.frames) {
339
+ if (frame.status !== "captured")
340
+ continue;
341
+ try {
342
+ const file = this.frameFile(record, frame.id), stat = fs.lstatSync(file);
343
+ if (!stat.isFile() || stat.size > 512 * 1024)
344
+ throw Error("saved-frame-unavailable");
345
+ if ((options.includeFrames && selected.has(frame.id)) ||
346
+ verify.has(frame.id)) {
347
+ const bytes = fs.readFileSync(file);
348
+ if (createHash("sha256").update(bytes).digest("hex") !== frame.sha256)
349
+ throw Error("saved-frame-changed");
350
+ if (options.includeFrames && selected.has(frame.id))
351
+ frame.base64 = bytes.toString("base64");
352
+ }
353
+ }
354
+ catch {
355
+ frame.status = "unavailable";
356
+ frame.reason = "saved-frame-unavailable";
357
+ }
358
+ }
359
+ const visual = assessVisual(result.frames, observations, result.expected);
360
+ const physical = visual?.status === "suspect_no_extrusion"
361
+ ? visual
362
+ : options.measurements?.length
363
+ ? assessPhysical(result.frames, options.measurements)
364
+ : (visual ?? assessPhysical(result.frames));
365
+ physical.assessment = assessmentRequest(result.frames, observations, result.expected);
366
+ if (options.evidenceOnly) {
367
+ result.omittedReports = result.reports.length;
368
+ result.reports = [];
369
+ if (result.expected) {
370
+ const layers = result.expected.layers.filter((l) => result.frames.some((f) => selected.has(f.id) && f.layer === l.layer));
371
+ result.omittedGeometryLayers =
372
+ result.expected.layers.length - layers.length;
373
+ result.expected = { ...result.expected, layers };
374
+ }
375
+ }
376
+ return {
377
+ contract: "counterpart/1",
378
+ status: "recorded",
379
+ ...(jobs ? { jobs } : {}),
380
+ record: result,
381
+ physical,
382
+ };
383
+ }
384
+ /** Persist only the client's frame-bound visual observation, without printer I/O or journal ownership changes. */
385
+ submitVisual(key, input) {
386
+ const value = validateVisualSubmission(input), record = this.get(key, value.jobId);
387
+ if (!record || record.dispatch.sha256 !== value.artifactSha256)
388
+ throw Error("Visual observation does not match the saved job/artifact.");
389
+ const frame = record.frames.find((f) => f.id === value.frameId &&
390
+ f.role !== "baseline" &&
391
+ f.status === "captured" &&
392
+ f.sha256 === value.imageSha256);
393
+ if (!frame)
394
+ throw Error("Visual observation frame/hash is unavailable or mismatched.");
395
+ try {
396
+ const image = this.frameFile(record, frame.id), stat = fs.lstatSync(image);
397
+ if (!stat.isFile() || stat.size > 512 * 1024)
398
+ throw Error("invalid");
399
+ const bytes = fs.readFileSync(image);
400
+ if (createHash("sha256").update(bytes).digest("hex") !== frame.sha256)
401
+ throw Error("changed");
402
+ }
403
+ catch {
404
+ throw Error("Saved visual frame is unavailable or its hash changed.");
405
+ }
406
+ if (value.referenceFrameId &&
407
+ !record.frames.some((f) => f.id === value.referenceFrameId &&
408
+ f.role === "baseline" &&
409
+ f.status === "captured"))
410
+ throw Error("Reference frame is not a saved baseline candidate for this job.");
411
+ const observations = this.visuals(record), prior = observations.find((o) => o.frameId === value.frameId);
412
+ if (prior &&
413
+ JSON.stringify(validateVisualSubmission(prior)) === JSON.stringify(value))
414
+ return this.read(key, { jobId: record.id });
415
+ // Reinterpreting the same frame cannot clear a warning; recovery needs a higher-layer frame.
416
+ if (prior && assessVisual(record.frames, [prior], record.expected)?.status === "suspect_no_extrusion")
417
+ return this.read(key, { jobId: record.id });
418
+ const next = [
419
+ ...observations.filter((o) => o.frameId !== value.frameId),
420
+ {
421
+ ...value,
422
+ at: new Date(this.now()).toISOString(),
423
+ source: "client-vision",
424
+ },
425
+ ].slice(-64);
426
+ const text = JSON.stringify({
427
+ version: 1,
428
+ jobId: record.id,
429
+ observations: next,
430
+ });
431
+ if (Buffer.byteLength(text) > 64 * 1024)
432
+ throw Error("Visual observation storage limit exceeded.");
433
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
434
+ const file = this.visualFile(record), tmp = file + "." + process.pid + ".tmp";
435
+ if (!fs.existsSync(this.file(record)))
436
+ throw Error("The saved job was pruned; its observation was not stored.");
437
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
438
+ fs.renameSync(tmp, file);
439
+ if (!fs.existsSync(this.file(record))) {
440
+ try {
441
+ fs.unlinkSync(file);
442
+ }
443
+ catch { }
444
+ throw Error("The saved job was pruned; its observation was not stored.");
445
+ }
446
+ return this.read(key, { jobId: record.id });
447
+ }
448
+ visualFile(record) {
449
+ return this.file(record).replace(/\.json$/, ".visual.json");
450
+ }
451
+ visuals(record) {
452
+ try {
453
+ const file = this.visualFile(record), stat = fs.lstatSync(file);
454
+ if (!stat.isFile() || stat.size > 64 * 1024)
455
+ return [];
456
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
457
+ if (data.version !== 1 ||
458
+ data.jobId !== record.id ||
459
+ !Array.isArray(data.observations))
460
+ return [];
461
+ return data.observations
462
+ .slice(-64)
463
+ .flatMap((v) => {
464
+ try {
465
+ const value = validateVisualSubmission(v);
466
+ if (value.jobId !== record.id ||
467
+ value.artifactSha256 !== record.dispatch.sha256 ||
468
+ typeof v.at !== "string" ||
469
+ !Number.isFinite(Date.parse(v.at)) ||
470
+ !record.frames.some((f) => f.id === value.frameId && f.sha256 === value.imageSha256))
471
+ return [];
472
+ return [{ ...value, at: v.at, source: "client-vision" }];
473
+ }
474
+ catch {
475
+ return [];
476
+ }
477
+ })
478
+ .sort((a, b) => {
479
+ const x = record.frames.find((f) => f.id === a.frameId), y = record.frames.find((f) => f.id === b.frameId);
480
+ return x.layer - y.layer || x.capturedAt.localeCompare(y.capturedAt);
481
+ });
482
+ }
483
+ catch {
484
+ return [];
485
+ }
486
+ }
487
+ trimFrames(record) {
488
+ const observations = this.visuals(record);
489
+ const protectedFrames = new Set(assessVisual(record.frames, observations, record.expected)?.evidence ?? []);
490
+ const anomaly = observations
491
+ .filter((o) => o.visibility === "clear" &&
492
+ o.footprintVisible &&
493
+ o.attempted &&
494
+ o.deposition === "absent")
495
+ .at(-1)?.frameId;
496
+ while (record.frames.length > 32) {
497
+ const index = record.frames.findIndex((f) => f.role !== "baseline" && f.role !== "first_layer" && f.id !== anomaly && !protectedFrames.has(f.id));
498
+ if (index < 0)
499
+ break;
500
+ const [removed] = record.frames.splice(index, 1);
501
+ try {
502
+ fs.unlinkSync(this.frameFile(record, removed.id));
503
+ }
504
+ catch { }
505
+ record.droppedFrames = (record.droppedFrames ?? 0) + 1;
506
+ }
507
+ }
508
+ /** Called only after existing reports/reads, never on a timer; a sample cannot block the print. */
509
+ async sample(key, capture) {
510
+ const record = this.get(key), layer = num(record?.latest.layer_num), state = record?.latest.gcode_state;
511
+ const received = record
512
+ ? this.recentReports.get(record.printerKey)
513
+ : undefined;
514
+ if (!record ||
515
+ this.isSuperseded(record) ||
516
+ !received?.matches ||
517
+ received.id !== record.id ||
518
+ this.now() - received.at > 15000 ||
519
+ !this.canWrite(record) ||
520
+ this.pending.has(record.printerKey))
521
+ return;
522
+ const baseline = state === "PREPARE" || state === "SLICING";
523
+ let checkpoint, zMm, role;
524
+ const stage = JSON.stringify([
525
+ record.latest.mc_print_stage,
526
+ record.latest.mc_print_sub_stage,
527
+ record.latest.stg_cur,
528
+ ]);
529
+ if (baseline) {
530
+ const existing = record.frames.filter((f) => f.role === "baseline");
531
+ if (existing.length >= 3 || existing.some((f) => f.stage === stage))
532
+ return;
533
+ checkpoint = -100 - existing.length;
534
+ zMm = 0;
535
+ role = "baseline";
536
+ }
537
+ else {
538
+ if (state !== "RUNNING" || !layer || !record.expected?.heightMm)
539
+ return;
540
+ const geometry = record.expected.layers.find((l) => l.layer === layer);
541
+ if (!geometry)
542
+ return;
543
+ const due = [0.05, 0.3, 0.6, 0.9]
544
+ .map((ratio, index) => ({ ratio, index }))
545
+ .filter((t) => geometry.zMm >= t.ratio * record.expected.heightMm &&
546
+ !record.frames.some((f) => f.checkpoint === t.index) &&
547
+ !record.skippedCheckpoints.includes(t.index) &&
548
+ !record.sampledCheckpoints?.includes(t.index));
549
+ const attempts = record.frames.filter((f) => f.role === "first_layer");
550
+ const first = layer <= 2 &&
551
+ attempts.length < 2 &&
552
+ !attempts.some((f) => f.layer === layer);
553
+ const periodicCheckpoint = 100000 + Math.floor(layer / 10);
554
+ const periodic = !record.frames.some((f) => f.role !== "baseline") ||
555
+ (layer >= 10 &&
556
+ !record.sampledCheckpoints?.includes(periodicCheckpoint) &&
557
+ !record.frames.some(f => f.checkpoint === periodicCheckpoint));
558
+ if (!first && !periodic && !due.length)
559
+ return;
560
+ const chosen = due.at(-1);
561
+ checkpoint =
562
+ chosen?.index ?? (first ? -10 : 100000 + Math.floor(layer / 10));
563
+ record.skippedCheckpoints.push(...due.slice(0, -1).map((t) => t.index));
564
+ if (chosen)
565
+ (record.sampledCheckpoints ?? (record.sampledCheckpoints = [])).push(chosen.index);
566
+ if (periodic && layer >= 10)
567
+ (record.sampledCheckpoints ?? (record.sampledCheckpoints = [])).push(periodicCheckpoint);
568
+ zMm = geometry.zMm;
569
+ role = first ? "first_layer" : periodic ? "periodic" : "height";
570
+ }
571
+ const frame = {
572
+ id: randomUUID(),
573
+ checkpoint,
574
+ role,
575
+ ...(baseline ? { stage } : {}),
576
+ layer: layer ?? 0,
577
+ expectedHeightMm: zMm,
578
+ reportAt: new Date(received.at).toISOString(),
579
+ capturedAt: new Date(this.now()).toISOString(),
580
+ status: "unavailable",
581
+ reason: "capture-pending",
582
+ };
583
+ record.frames.push(frame);
584
+ this.trimFrames(record);
585
+ this.save(record);
586
+ const work = (async () => {
587
+ try {
588
+ let timer;
589
+ const result = await Promise.race([
590
+ capture(frame.reportAt),
591
+ new Promise((_, reject) => {
592
+ timer = setTimeout(() => reject(Error("camera-deadline")), this.maxCaptureMs);
593
+ }),
594
+ ]).finally(() => clearTimeout(timer));
595
+ const capturedAt = result.capturedAt === undefined
596
+ ? this.now()
597
+ : Date.parse(result.capturedAt);
598
+ if (!Number.isFinite(capturedAt) ||
599
+ capturedAt < Date.parse(frame.reportAt) ||
600
+ capturedAt - Date.parse(frame.reportAt) > 15000 ||
601
+ capturedAt > this.now() + 1000)
602
+ throw Error("stale-frame");
603
+ frame.capturedAt = new Date(capturedAt).toISOString();
604
+ const current = this.get(key);
605
+ if (current?.id !== record.id ||
606
+ this.isSuperseded(record) ||
607
+ this.recentReports.get(record.printerKey)?.matches !== true ||
608
+ this.recentReports.get(record.printerKey)?.id !== record.id ||
609
+ current.latest.gcode_state !== state ||
610
+ num(current.latest.layer_num) !== layer ||
611
+ (baseline &&
612
+ JSON.stringify([
613
+ current.latest.mc_print_stage,
614
+ current.latest.mc_print_sub_stage,
615
+ current.latest.stg_cur,
616
+ ]) !== stage))
617
+ throw Error("job-or-layer-changed");
618
+ if (!result.base64 ||
619
+ result.base64.length > Math.ceil((512 * 1024 * 4) / 3) + 4)
620
+ throw Error("frame-unavailable");
621
+ const bytes = Buffer.from(result.base64, "base64");
622
+ if (bytes.length > 512 * 1024 || bytes[0] !== 255 || bytes[1] !== 216)
623
+ throw Error("invalid-frame");
624
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
625
+ fs.writeFileSync(this.frameFile(record, frame.id), bytes, {
626
+ mode: 0o600,
627
+ });
628
+ frame.sha256 = createHash("sha256").update(bytes).digest("hex");
629
+ frame.status = "captured";
630
+ delete frame.reason;
631
+ }
632
+ catch {
633
+ frame.reason = "camera-unavailable-or-job-changed";
634
+ }
635
+ finally {
636
+ if (this.get(key)?.id === record.id || fs.existsSync(this.file(record)))
637
+ this.save(record);
638
+ this.pending.delete(record.printerKey);
639
+ }
640
+ })();
641
+ this.pending.set(record.printerKey, work);
642
+ await work;
643
+ }
644
+ /** One process writes a dispatched job; fresh observations can take over after its process exits. */
645
+ canWrite(record) {
646
+ if (record.owner?.token === this.ownerToken)
647
+ return true;
648
+ if (record.owner) {
649
+ try {
650
+ process.kill(record.owner.pid, 0);
651
+ return false;
652
+ }
653
+ catch (error) {
654
+ if (error.code !== "ESRCH")
655
+ return false;
656
+ }
657
+ }
658
+ record.owner = { pid: process.pid, token: this.ownerToken };
659
+ return true;
660
+ }
661
+ jobSummaries(key) {
662
+ const prefix = hash(key) + "-";
663
+ return this.files()
664
+ .filter((name) => name.startsWith(prefix))
665
+ .flatMap((name) => {
666
+ const record = this.get(key, name.slice(prefix.length, -5));
667
+ return record
668
+ ? [
669
+ {
670
+ id: record.id,
671
+ dispatchedAt: record.dispatchedAt,
672
+ sha256: record.dispatch.sha256,
673
+ outcome: record.dispatch.outcome,
674
+ },
675
+ ]
676
+ : [];
677
+ })
678
+ .sort((a, b) => b.dispatchedAt.localeCompare(a.dispatchedAt))
679
+ .slice(0, this.maxJobs);
680
+ }
681
+ isSuperseded(record) {
682
+ return this.superseded.has(record.id) || fs.existsSync(this.file(record) + ".superseded");
683
+ }
684
+ /** Monotonic one-byte sidecar: another observer cannot overwrite the live owner's journal. */
685
+ invalidateExecution(record) {
686
+ this.superseded.add(record.id);
687
+ while (this.superseded.size > this.maxJobs)
688
+ this.superseded.delete(this.superseded.values().next().value);
689
+ const file = this.file(record), marker = file + ".superseded";
690
+ try {
691
+ if (fs.existsSync(file))
692
+ fs.writeFileSync(marker, "1", { flag: "wx", mode: 0o600 });
693
+ if (!fs.existsSync(file) && fs.existsSync(marker))
694
+ fs.unlinkSync(marker);
695
+ }
696
+ catch { /* Existing markers are already durable; storage failure stays volatile. */ }
697
+ }
698
+ file(record) {
699
+ return path.join(this.dir, `${record.printerKey}-${record.id}.json`);
700
+ }
701
+ frameFile(record, id) {
702
+ return path.join(this.dir, `${record.printerKey}-${record.id}-${id}.jpg`);
703
+ }
704
+ files() {
705
+ try {
706
+ return fs
707
+ .readdirSync(this.dir)
708
+ .filter((f) => /^[a-f\d]{64}-[a-f\d-]{36}\.json$/.test(f));
709
+ }
710
+ catch {
711
+ return [];
712
+ }
713
+ }
714
+ get(key, id) {
715
+ const printerKey = hash(key);
716
+ let cached = this.cache.get(printerKey);
717
+ if (cached?.storage === "durable" && !fs.existsSync(this.file(cached))) {
718
+ this.cache.delete(printerKey);
719
+ cached = undefined;
720
+ }
721
+ if (id && cached?.owner?.token === this.ownerToken && cached.id === id)
722
+ return cached;
723
+ // A latest-job read must discover dispatches made by another MCP process,
724
+ // even while this process still owns a retained older job.
725
+ let latest;
726
+ for (const name of this.files().filter((f) => f.startsWith(printerKey + "-") &&
727
+ (!id || f === `${printerKey}-${id}.json`))) {
728
+ try {
729
+ const file = path.join(this.dir, name), stat = fs.lstatSync(file);
730
+ if (!stat.isFile() || stat.size > this.maxBytes)
731
+ continue;
732
+ const saved = JSON.parse(fs.readFileSync(file, "utf8"));
733
+ if (saved.version !== 1 ||
734
+ saved.printerKey !== printerKey ||
735
+ this.file(saved) !== file ||
736
+ !saved.dispatch?.sha256 ||
737
+ !Array.isArray(saved.reports) ||
738
+ !Array.isArray(saved.frames))
739
+ continue;
740
+ if (!latest || saved.dispatchedAt > latest.dispatchedAt)
741
+ latest = saved;
742
+ }
743
+ catch {
744
+ /* A corrupt/incomplete file is unavailable, never a reason to connect to the printer. */
745
+ }
746
+ }
747
+ if (!id &&
748
+ cached?.storage === "volatile" &&
749
+ (!latest || cached.dispatchedAt >= latest.dispatchedAt))
750
+ latest = cached;
751
+ if (latest && !id) {
752
+ if (cached?.id === latest.id && cached.owner?.token === this.ownerToken)
753
+ return cached;
754
+ this.cache.set(printerKey, latest);
755
+ }
756
+ return latest;
757
+ }
758
+ save(record) {
759
+ try {
760
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
761
+ record.storage = "durable";
762
+ let text = JSON.stringify(record);
763
+ while (Buffer.byteLength(text) > this.maxBytes &&
764
+ record.reports.length > 1) {
765
+ record.reports.shift();
766
+ record.droppedReports++;
767
+ text = JSON.stringify(record);
768
+ }
769
+ if (Buffer.byteLength(text) > this.maxBytes) {
770
+ record.expected = undefined;
771
+ text = JSON.stringify(record);
772
+ }
773
+ if (Buffer.byteLength(text) > this.maxBytes)
774
+ throw Error("record-too-large");
775
+ const file = this.file(record), temporary = `${file}.${process.pid}.tmp`;
776
+ fs.writeFileSync(temporary, text, { mode: 0o600 });
777
+ fs.renameSync(temporary, file);
778
+ record.storage = "durable";
779
+ }
780
+ catch {
781
+ record.storage = "volatile";
782
+ if (!this.warned) {
783
+ this.warned = true;
784
+ console.error("Print flight record storage is unavailable; diagnostics may not survive restart.");
785
+ }
786
+ }
787
+ }
788
+ prune() {
789
+ while (this.cache.size > this.maxJobs) {
790
+ const oldest = this.cache.keys().next().value;
791
+ if (oldest === undefined)
792
+ break;
793
+ this.cache.delete(oldest);
794
+ }
795
+ try {
796
+ const files = this.files()
797
+ .map((name) => ({
798
+ name,
799
+ time: fs.statSync(path.join(this.dir, name)).mtimeMs,
800
+ }))
801
+ .sort((a, b) => b.time - a.time);
802
+ for (const { name } of files.slice(this.maxJobs)) {
803
+ // Retention must not depend on parsing an older, possibly corrupt record.
804
+ const prefix = name.slice(0, -5);
805
+ fs.unlinkSync(path.join(this.dir, name));
806
+ try {
807
+ fs.unlinkSync(path.join(this.dir, name + ".superseded"));
808
+ }
809
+ catch { }
810
+ try {
811
+ fs.unlinkSync(path.join(this.dir, prefix + ".visual.json"));
812
+ }
813
+ catch { }
814
+ for (const file of fs
815
+ .readdirSync(this.dir)
816
+ .filter((file) => file.startsWith(prefix + "-") && /^[a-f\d-]+\.jpg$/.test(file))) {
817
+ try {
818
+ fs.unlinkSync(path.join(this.dir, file));
819
+ }
820
+ catch { }
821
+ }
822
+ const printerKey = name.slice(0, 64), id = name.slice(65, -5);
823
+ if (this.cache.get(printerKey)?.id === id)
824
+ this.cache.delete(printerKey);
825
+ }
826
+ }
827
+ catch {
828
+ /* Diagnostic retention must never fail a printer operation. */
829
+ }
830
+ }
831
+ }