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