bambu-printer-mcp 1.1.61 → 1.1.63

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.
@@ -0,0 +1,297 @@
1
+ /**
2
+ * counterpart_propose_filaments (counterpart/1): which loaded spool prints each of a model's colours, proposed before
3
+ * slicing. Nearest colour in OKLab with the asked-for material preferred; one print feeds from one source. Each spool
4
+ * carries the words a person reads ("A2", "Sunflower Yellow PLA Basic") and every part an explicit verdict, so a client
5
+ * renders the result instead of re-deriving it. Pure: the server supplies the live trays.
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
10
+
11
+ /** One loaded spool as a client shows it. `feed` groups the spools that can feed one print together. */
12
+ export type ProposalTray = {
13
+ slot: number; label: string; name: string; colour: string; material: string; filamentId: string; feed: string;
14
+ /** This server can slice with it (a filament profile is resolved for it). */
15
+ sliceable: boolean;
16
+ /** The resolved slicer filament profile (absolute path), the one slice_stl takes in load_filaments. */
17
+ profile?: string;
18
+ };
19
+ export type ProposalFilament = { index: number; name?: string; colour?: string; material?: string };
20
+ /** A filament slot no part names (a painted region): it follows the chosen spools' feed. `prints` false: not on this plate. */
21
+ export type PaintedFilament = { index: number; colour?: string; material?: string; prints?: boolean };
22
+ export type ChosenSpool = { index: number; slot: number; colour?: string; material?: string; filamentId?: string };
23
+ export type Verdict = "same-colour" | "closest" | "no-colour" | "none";
24
+ export type ProposalRow = {
25
+ index: number; slot?: number; verdict: Verdict; distance?: number; materialMismatch?: boolean;
26
+ /** What the person should know about this suggestion, in their words. */
27
+ note?: string;
28
+ };
29
+ export type ProposalProblem = { code: string; message: string; index?: number };
30
+ export type FilamentProposal = {
31
+ contract: typeof COUNTERPART_CONTRACT;
32
+ /** The spools a person may choose from: every loaded one for a sliced file, the sliceable ones otherwise. */
33
+ trays: ProposalTray[];
34
+ proposal: ProposalRow[];
35
+ /** Every filament slot (parts and painted) to its spool, when the proposal or the person's choice is printable. */
36
+ mapping?: Array<{ index: number; slot: number }>;
37
+ problems: ProposalProblem[];
38
+ };
39
+
40
+ /** A colour this close (OKLab) to the asked-for one is the same colour to a person. */
41
+ export const SAME_COLOUR = 0.08;
42
+ const MATERIAL_PENALTY = 0.15;
43
+ const REUSE_PENALTY = 0.1;
44
+ const DISTINCT = 0.05;
45
+
46
+ function oklab(hex: string): [number, number, number] | undefined {
47
+ const match = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(hex.trim());
48
+ if (!match) return undefined;
49
+ const value = Number.parseInt(match[1]!, 16);
50
+ const linear = (channel: number) => { const s = channel / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
51
+ const r = linear(value >> 16 & 255), g = linear(value >> 8 & 255), b = linear(value & 255);
52
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
53
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
54
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
55
+ return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
56
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
57
+ }
58
+
59
+ /** Perceptual distance between two `#RRGGBB` colours (0 identical, about 1 black to white). Alpha is ignored. */
60
+ export function colourDistance(a: string, b: string): number {
61
+ const left = oklab(a), right = oklab(b);
62
+ if (!left || !right) return Number.POSITIVE_INFINITY;
63
+ return Math.hypot(left[0] - right[0], left[1] - right[1], left[2] - right[2]);
64
+ }
65
+
66
+ type Match = { slot: number; distance?: number; materialMismatch?: boolean; guessed?: boolean };
67
+ const materialOf = (value: string | undefined) => value?.trim().toUpperCase() || undefined;
68
+
69
+ function pick(filament: { colour?: string; material?: string }, loaded: ProposalTray[], assigned: Map<number, string[]>, requireMaterial: boolean): Match | undefined {
70
+ if (!loaded.length) return undefined;
71
+ const wanted = materialOf(filament.material);
72
+ const mismatch = (tray: ProposalTray) => wanted !== undefined && materialOf(tray.material) !== wanted;
73
+ const eligible = requireMaterial && wanted ? loaded.filter(tray => !mismatch(tray)) : loaded;
74
+ if (!eligible.length) return undefined;
75
+ const target = filament.colour ? oklab(filament.colour) : undefined;
76
+ if (!target) {
77
+ const free = eligible.filter(tray => !assigned.has(tray.slot));
78
+ const pool = free.length ? free : eligible;
79
+ const chosen = pool.find(tray => !mismatch(tray)) ?? pool[0]!;
80
+ assigned.set(chosen.slot, [...(assigned.get(chosen.slot) ?? [])]);
81
+ return { slot: chosen.slot, guessed: true, ...(mismatch(chosen) ? { materialMismatch: true } : {}) };
82
+ }
83
+ let best: { tray: ProposalTray; distance: number; score: number } | undefined;
84
+ for (const tray of eligible) {
85
+ const distance = colourDistance(filament.colour!, tray.colour);
86
+ const shared = (assigned.get(tray.slot) ?? []).some(colour => colourDistance(colour, filament.colour!) > DISTINCT);
87
+ const score = distance + (mismatch(tray) ? MATERIAL_PENALTY : 0) + (shared ? REUSE_PENALTY : 0);
88
+ if (!best || score < best.score || (score === best.score && tray.slot < best.tray.slot)) best = { tray, distance, score };
89
+ }
90
+ assigned.set(best!.tray.slot, [...(assigned.get(best!.tray.slot) ?? []), filament.colour!]);
91
+ return { slot: best!.tray.slot, distance: best!.distance, ...(mismatch(best!.tray) ? { materialMismatch: true } : {}) };
92
+ }
93
+
94
+ /**
95
+ * One match per filament, in order; undefined where nothing can serve it. Several filaments of one colour may share a
96
+ * spool. With `requireMaterial` (an already-sliced file) only spools of the asked-for material qualify. Automatic matches
97
+ * never mix feeds: the first feed listed (the AMS) is preferred, another feed only when it alone serves every colour.
98
+ */
99
+ export function matchColours(model: Array<{ colour?: string; material?: string }>, trays: ProposalTray[], options: { requireMaterial?: boolean } = {}): (Match | undefined)[] {
100
+ const loaded = trays.filter(tray => oklab(tray.colour));
101
+ const run = (pool: ProposalTray[]) => { const assigned = new Map<number, string[]>(); return model.map(filament => pick(filament, pool, assigned, !!options.requireMaterial)); };
102
+ const matches = run(loaded);
103
+ const feedOf = new Map(loaded.map(tray => [tray.slot, tray.feed]));
104
+ const feeds = [...new Set(loaded.map(tray => tray.feed))];
105
+ if (new Set(matches.flatMap(match => match ? [feedOf.get(match.slot)] : [])).size <= 1) return matches;
106
+ const perFeed = feeds.map(feed => run(loaded.filter(tray => tray.feed === feed)));
107
+ return perFeed.find(result => result.every(match => match)) ?? perFeed[0]!;
108
+ }
109
+
110
+ /** The colour names Bambu Studio itself uses for its filaments (profiles/BBL/filament/filaments_color_codes.json). */
111
+ export type ColourNames = { spool(filamentId: string, colour: string): string | undefined; colour(colour: string): string | undefined };
112
+ export const NO_COLOUR_NAMES: ColourNames = { spool: () => undefined, colour: () => undefined };
113
+
114
+ export function loadColourNames(filamentProfileDir: string | undefined): ColourNames {
115
+ if (!filamentProfileDir) return NO_COLOUR_NAMES;
116
+ let data: unknown;
117
+ try {
118
+ const file = path.join(filamentProfileDir, "filaments_color_codes.json");
119
+ if (fs.statSync(file).size > 8 * 1024 * 1024) return NO_COLOUR_NAMES;
120
+ data = (JSON.parse(fs.readFileSync(file, "utf8")) as { data?: unknown }).data;
121
+ } catch { return NO_COLOUR_NAMES; }
122
+ if (!Array.isArray(data)) return NO_COLOUR_NAMES;
123
+ const byId = new Map<string, string>(), byColour = new Map<string, string>();
124
+ for (const entry of data) {
125
+ const colours = Array.isArray(entry?.fila_color) ? entry.fila_color : [];
126
+ const name = typeof entry?.fila_color_name?.en === "string" ? entry.fila_color_name.en.trim().slice(0, 64) : "";
127
+ const id = typeof entry?.fila_id === "string" ? entry.fila_id.trim().toUpperCase() : "";
128
+ // Single colours only: a gradient or multi-colour spool's first colour is not its name.
129
+ if (colours.length !== 1 || typeof colours[0] !== "string" || !name || !/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(colours[0])) continue;
130
+ const hex8 = (colours[0].slice(1) + "FF").slice(0, 8).toUpperCase();
131
+ if (id && !byId.has(`${id}#${hex8}`)) byId.set(`${id}#${hex8}`, name);
132
+ if (id && !byId.has(`${id}#${hex8.slice(0, 6)}`)) byId.set(`${id}#${hex8.slice(0, 6)}`, name);
133
+ // A bare colour's name: the shortest Bambu uses for exactly that opaque colour ("White", not "Jade White").
134
+ if (hex8.endsWith("FF")) {
135
+ const key = hex8.slice(0, 6), known = byColour.get(key);
136
+ if (!known || name.length < known.length) byColour.set(key, name);
137
+ }
138
+ }
139
+ const hex = (value: string) => value.replace(/^#/, "").toUpperCase();
140
+ return {
141
+ spool: (filamentId, colour) => byId.get(`${filamentId.toUpperCase()}#${hex(colour)}`) ?? byId.get(`${filamentId.toUpperCase()}#${hex(colour).slice(0, 6)}`),
142
+ colour: colour => byColour.get(hex(colour).slice(0, 6)),
143
+ };
144
+ }
145
+
146
+ /** Where a Bambu tray sits, as Bambu Studio labels it: AMS units A–D with trays 1–4, AMS HT units by letter. */
147
+ export function bambuTrayLabel(amsId: number, trayId: number): string {
148
+ const letter = (n: number) => String.fromCharCode(65 + Math.max(0, Math.min(n, 25)));
149
+ return amsId >= 128 ? `AMS HT ${letter(amsId - 128)}` : `${letter(amsId)}${trayId + 1}`;
150
+ }
151
+
152
+ /** A spool's name: its colour name (when Bambu names it) and product ("Sunflower Yellow PLA Basic"), else the product. */
153
+ export function spoolName(product: string, colourName: string | undefined): string {
154
+ return (colourName ? `${colourName} ${product}` : product).trim().slice(0, 128);
155
+ }
156
+
157
+ const partName = (filament: ProposalFilament) => filament.name?.trim() || `Part ${filament.index}`;
158
+
159
+ export function proposeFilaments(input: {
160
+ trays: ProposalTray[]; filaments: ProposalFilament[]; painted?: PaintedFilament[]; chosen?: ChosenSpool[]; sliced?: boolean; names?: ColourNames;
161
+ }): FilamentProposal {
162
+ const names = input.names ?? NO_COLOUR_NAMES;
163
+ const sliced = !!input.sliced;
164
+ const live = input.trays;
165
+ const menu = sliced ? live : live.filter(tray => tray.sliceable);
166
+ const problems: ProposalProblem[] = [];
167
+ const result = (proposal: ProposalRow[], mapping?: Array<{ index: number; slot: number }>): FilamentProposal =>
168
+ ({ contract: COUNTERPART_CONTRACT, trays: menu, proposal, ...(mapping && !problems.length ? { mapping } : {}), problems });
169
+ const describe = (tray: ProposalTray) => `${tray.label} ${tray.name}`;
170
+ const colourWords = (colour: string) => names.colour(colour) ?? colour.toUpperCase();
171
+
172
+ // A sliced file's painted slots need their material on the same feed: they take part in choosing the feed,
173
+ // so the proposal never picks a feed that can't print them when another one can.
174
+ const required = sliced ? (input.painted ?? []).filter(slot => slot.material && slot.prints !== false
175
+ && !input.filaments.some(filament => filament.index === slot.index)) : [];
176
+ const matches = matchColours([...input.filaments, ...required], menu, { requireMaterial: sliced }).slice(0, input.filaments.length);
177
+ const proposal: ProposalRow[] = input.filaments.map((filament, i) => {
178
+ const match = matches[i];
179
+ if (!match) return { index: filament.index, verdict: "none" as const };
180
+ const tray = menu.find(item => item.slot === match.slot)!;
181
+ const row: ProposalRow = { index: filament.index, slot: match.slot,
182
+ verdict: match.guessed ? "no-colour" : (match.distance ?? 0) <= SAME_COLOUR ? "same-colour" : "closest",
183
+ ...(match.distance !== undefined ? { distance: match.distance } : {}), ...(match.materialMismatch ? { materialMismatch: true } : {}) };
184
+ if (row.verdict === "no-colour") row.note = "The model doesn’t say this part’s colour — pick its spool.";
185
+ else if (row.verdict === "closest") {
186
+ // The colour may be loaded but not chosen: on another feed (one print feeds from one source), in another
187
+ // material, or on a spool another colour of this model already prints from. Say which, never "isn't loaded".
188
+ const words = colourWords(filament.colour!);
189
+ const loaded = menu.find(item => item.slot !== tray.slot && colourDistance(item.colour, filament.colour!) <= SAME_COLOUR);
190
+ const wanted = materialOf(filament.material);
191
+ row.note = !loaded ? `${words} isn’t loaded. Closest loaded: ${describe(tray)}.`
192
+ : loaded.feed !== tray.feed ? `${words} is loaded on ${loaded.label}, but one print feeds from one source. Closest here: ${describe(tray)}.`
193
+ : wanted && materialOf(loaded.material) !== wanted ? `${words} is loaded on ${loaded.label} in ${loaded.material}, not ${filament.material}. Closest in ${filament.material}: ${describe(tray)}.`
194
+ : `${words} is on ${loaded.label}, which another colour of this model already prints from. Closest other spool: ${describe(tray)}.`;
195
+ }
196
+ if (match.materialMismatch) row.note = `${row.note ? row.note + " " : ""}Prints in ${tray.material}, not ${filament.material}.`;
197
+ return row;
198
+ });
199
+
200
+ if (!input.filaments.length) return result(proposal);
201
+ // The spools that will print, in filament order: the person's choices, validated, or the proposal.
202
+ let chosen: ProposalTray[];
203
+ if (input.chosen) {
204
+ if (input.chosen.length !== input.filaments.length || input.filaments.some((filament, i) => input.chosen![i]!.index !== filament.index)) {
205
+ problems.push({ code: "choices-incomplete", message: "Choose a spool for every colour in this model, then try again." });
206
+ return result(proposal);
207
+ }
208
+ chosen = [];
209
+ for (const [i, choice] of input.chosen.entries()) {
210
+ const tray = live.find(item => item.slot === choice.slot);
211
+ const filament = input.filaments[i]!;
212
+ if (!tray || (choice.colour !== undefined && choice.colour.toUpperCase() !== tray.colour.toUpperCase())
213
+ || (choice.material !== undefined && materialOf(choice.material) !== materialOf(tray.material)) || (choice.filamentId !== undefined && choice.filamentId !== tray.filamentId)) {
214
+ problems.push({ code: "spool-changed", index: filament.index, message: "A chosen filament changed. Choose the current spools and try again." });
215
+ continue;
216
+ }
217
+ if (sliced && filament.material && materialOf(tray.material) !== materialOf(filament.material))
218
+ problems.push({ code: "sliced-material", index: filament.index, message: `“${partName(filament)}” was sliced for ${filament.material}, so it can only print from a ${filament.material} spool. Choose one, or share the designer’s editable 3MF to change material.` });
219
+ if (!sliced && !tray.sliceable)
220
+ problems.push({ code: "no-profile", index: filament.index, message: `The ${tray.material} spool you chose has no slicing profile on this computer. Choose another spool.` });
221
+ chosen.push(tray);
222
+ }
223
+ if (problems.length) return result(proposal);
224
+ if (new Set(chosen.map(tray => tray.feed)).size > 1) {
225
+ problems.push({ code: "mixed-feeds", message: "One print feeds from one source: put every colour on AMS spools, or every colour on the external spool." });
226
+ return result(proposal);
227
+ }
228
+ } else {
229
+ const missing = matches.findIndex(match => !match);
230
+ if (!menu.length) { problems.push({ code: "nothing-loaded", message: "No filament is loaded. Load a spool in the AMS, then try again." }); return result(proposal); }
231
+ if (missing >= 0) {
232
+ const filament = input.filaments[missing]!;
233
+ const elsewhere = sliced && filament.material && live.some(tray => materialOf(tray.material) === materialOf(filament.material));
234
+ problems.push({ code: elsewhere ? "material-on-another-feed" : "material-not-loaded", index: filament.index, message: elsewhere
235
+ ? `“${partName(filament)}” needs ${filament.material}, but one print feeds from one source and no single source holds every colour’s material. Load the spools on one source, then try again.`
236
+ : sliced && filament.material
237
+ ? `No ${filament.material} spool is loaded for “${partName(filament)}”, and this file was sliced for ${filament.material}. Load one, then try again.`
238
+ : "No filament is loaded. Load a spool in the AMS, then try again." });
239
+ return result(proposal);
240
+ }
241
+ chosen = matches.map(match => menu.find(tray => tray.slot === match!.slot)!);
242
+ }
243
+
244
+ const mapping = new Map(input.filaments.map((filament, i) => [filament.index, chosen[i]!.slot]));
245
+ const feed = chosen[0]!.feed;
246
+ const chosenSlots = new Set(chosen.map(tray => tray.slot));
247
+ const primary = live[0]?.feed;
248
+ // A painted slot follows the chosen feed: on the external spool(s) exactly those chosen; on the AMS any AMS spool.
249
+ const fillerPool = menu.filter(tray => feed === primary ? tray.feed === feed : chosenSlots.has(tray.slot));
250
+ for (const painted of input.painted ?? []) {
251
+ if (mapping.has(painted.index)) continue;
252
+ const [match] = matchColours([painted], fillerPool, { requireMaterial: sliced });
253
+ if (match) mapping.set(painted.index, match.slot);
254
+ else if (sliced && painted.material && painted.prints !== false)
255
+ problems.push({ code: "painted-material", index: painted.index, message: `A painted part of this file was sliced for ${painted.material}, and no ${painted.material} spool on the chosen feed source can print it. Load one, then try again.` });
256
+ else mapping.set(painted.index, chosen[0]!.slot);
257
+ }
258
+ return result(proposal, [...mapping.entries()].sort((a, b) => a[0] - b[0]).map(([index, slot]) => ({ index, slot })));
259
+ }
260
+
261
+ const colour = { type: "string", pattern: "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" };
262
+ export const PROPOSE_FILAMENTS_INPUT_PROPERTIES = {
263
+ filaments: {
264
+ type: "array", maxItems: 64,
265
+ description: "The model's filaments a person sees, in project order: 1-based index, part name, the colour it belongs in and its material when known.",
266
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, name: { type: "string", maxLength: 256 }, colour, material: { type: "string", maxLength: 64 } }, required: ["index"], additionalProperties: false },
267
+ },
268
+ painted: {
269
+ type: "array", maxItems: 64,
270
+ description: "Filament slots no part names (painted regions). Each follows the chosen spools' feed; prints false when the selected plate never uses it.",
271
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, colour, material: { type: "string", maxLength: 64 }, prints: { type: "boolean" } }, required: ["index"], additionalProperties: false },
272
+ },
273
+ chosen: {
274
+ type: "array", maxItems: 64,
275
+ description: "The person's spool for each filament, in the same order: checked against what is loaded now. Omit for the proposal alone.",
276
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, slot: { type: "integer", minimum: 0, maximum: 4095 }, colour, material: { type: "string", maxLength: 128 }, filamentId: { type: "string", maxLength: 128 } }, required: ["index", "slot"], additionalProperties: false },
277
+ },
278
+ sliced: { type: "boolean", description: "The file is already sliced: its materials are fixed, so only spools of the same material qualify." },
279
+ } as const;
280
+
281
+ export const PROPOSE_FILAMENTS_OUTPUT_SCHEMA = {
282
+ type: "object" as const,
283
+ properties: {
284
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
285
+ trays: { type: "array", items: { type: "object", properties: {
286
+ slot: { type: "integer" }, label: { type: "string" }, name: { type: "string" }, colour: { type: "string" }, material: { type: "string" },
287
+ filamentId: { type: "string" }, feed: { type: "string" }, sliceable: { type: "boolean" }, profile: { type: "string" },
288
+ }, required: ["slot", "label", "name", "colour", "material", "filamentId", "feed", "sliceable"] } },
289
+ proposal: { type: "array", items: { type: "object", properties: {
290
+ index: { type: "integer" }, slot: { type: "integer" }, verdict: { type: "string", enum: ["same-colour", "closest", "no-colour", "none"] },
291
+ distance: { type: "number" }, materialMismatch: { type: "boolean" }, note: { type: "string" },
292
+ }, required: ["index", "verdict"] } },
293
+ mapping: { type: "array", items: { type: "object", properties: { index: { type: "integer" }, slot: { type: "integer" } }, required: ["index", "slot"] } },
294
+ problems: { type: "array", items: { type: "object", properties: { code: { type: "string" }, message: { type: "string" }, index: { type: "integer" } }, required: ["code", "message"] } },
295
+ },
296
+ required: ["contract", "trays", "proposal", "problems"],
297
+ };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * counterpart_setup_fields (counterpart/1): the printers this server drives and the settings it reads for each, by the
3
+ * environment variable names it reads (`env`, and older `aliases` it reads first). A client renders these fields, writes the values
4
+ * to this server's .env and never needs its own printer or model tables. Pure: no printer traffic, no secrets returned.
5
+ */
6
+ import { normalizeModel } from "../safety/limits.js";
7
+ import { SERIAL_MODELS } from "../safety/printer-state.js";
8
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
9
+
10
+ export const SETUP_FIELD_NAMES = ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"] as const;
11
+ export type SetupField = {
12
+ /** The client's form field this is: an address, a port, a serial number, a model choice or a secret. */
13
+ name: typeof SETUP_FIELD_NAMES[number];
14
+ /** The variable to write. */
15
+ env: string;
16
+ /** Older names for it that this server reads before `env`: a client writing `env` removes these lines, or the old value wins. */
17
+ aliases?: string[];
18
+ label: string; hint?: string; required: boolean;
19
+ /** A path on this computer (a slicer app, a profiles folder): a client may offer a file chooser. */
20
+ input?: "path";
21
+ /** Written as typed, or upper-cased (Bambu serial numbers). */
22
+ transform?: "uppercase";
23
+ choices?: Array<{ value: string; label: string }>;
24
+ /** A model field: the model a serial number names, by its first `prefixLength` characters. */
25
+ fromSerial?: { prefixLength: number; models: Record<string, string> };
26
+ };
27
+ export type SetupKind = {
28
+ kind: typeof PRINTER_KINDS[number]; label: string;
29
+ /** Values this server needs for the kind whatever the person enters (MCP_TRANSPORT, PRINTER_TYPE). */
30
+ env: Record<string, string>;
31
+ fields: SetupField[];
32
+ };
33
+ /** The slicer this server runs, as it resolves it now, and the settings that choose it (for every printer). */
34
+ export type SlicerSetup = {
35
+ type: string;
36
+ /** The slicer app it would run, and whether that app is there. */
37
+ path?: string; found: boolean;
38
+ /** The Bambu profiles folder it would read (Bambu Studio and Orca), and whether it has BBL's profiles. */
39
+ profilesRoot?: string; profilesFound?: boolean;
40
+ fields: SetupField[];
41
+ };
42
+ export type SetupFields = { contract: typeof COUNTERPART_CONTRACT; server: { name: string; version: string }; kinds: SetupKind[]; model?: string; slicer?: SlicerSetup };
43
+
44
+ const SLICER_LABELS: Record<string, string> = {
45
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer-bambulab (FULU)", "orca-slicer-api": "OrcaSlicer API (remote)",
46
+ prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
47
+ };
48
+ /**
49
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
50
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
51
+ * default to isn't there.
52
+ */
53
+ export function slicerSetup(options: { types: readonly string[]; type: string; path?: string; found: boolean; profilesRoot?: string; profilesFound?: boolean; remote?: boolean }): SlicerSetup {
54
+ const label = SLICER_LABELS[options.type] ?? options.type;
55
+ const fields: SetupField[] = [
56
+ { name: "slicer", env: "SLICER_TYPE", label: "Slicer", required: false, choices: options.types.map(value => ({ value, label: SLICER_LABELS[value] ?? value })) },
57
+ ];
58
+ if (!options.remote) fields.push({ name: "slicer-path", env: "SLICER_PATH", label: `${label} app`, input: "path", required: !options.found,
59
+ hint: options.found ? `Found at ${options.path}. Set this only to use another copy.`
60
+ : options.path ? `${label} isn't at ${options.path}. Install it, or choose where it is.` : `Where ${label} is installed.` });
61
+ if (options.profilesFound !== undefined) fields.push({ name: "profiles", env: "BAMBU_PROFILES_ROOT", label: "Bambu profiles folder", input: "path", required: !options.profilesFound,
62
+ hint: options.profilesFound ? `Found at ${options.profilesRoot}. Set this only to use other profiles.` : `The folder with ${label}'s BBL profiles (it holds BBL/machine). Install ${label}, or choose the folder.` });
63
+ return { type: options.type, ...(options.path !== undefined ? { path: options.path } : {}), found: options.found,
64
+ ...(options.profilesRoot !== undefined ? { profilesRoot: options.profilesRoot } : {}), ...(options.profilesFound !== undefined ? { profilesFound: options.profilesFound } : {}), fields };
65
+ }
66
+
67
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
68
+ export function serialModelValues(valid: readonly string[]): Record<string, string> {
69
+ return Object.fromEntries(Object.entries(SERIAL_MODELS).flatMap(([prefix, name]) => {
70
+ const model = normalizeModel(name);
71
+ return model && valid.includes(model) ? [[prefix, model]] : [];
72
+ }));
73
+ }
74
+
75
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
76
+ export function modelChoices(valid: readonly string[]): Array<{ value: string; label: string }> {
77
+ const names = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
78
+ return valid.map(value => ({ value, label: names.get(value) ?? value.toUpperCase() }));
79
+ }
80
+
81
+ export function bambuSetupFields(options: { server: { name: string; version: string }; models: readonly string[]; serial?: string; slicer?: SlicerSetup }): SetupFields {
82
+ const fromSerial = { prefixLength: 3, models: serialModelValues(options.models) };
83
+ const model = options.serial ? fromSerial.models[options.serial.trim().slice(0, 3).toUpperCase()] : undefined;
84
+ return {
85
+ contract: COUNTERPART_CONTRACT,
86
+ server: options.server,
87
+ kinds: [{
88
+ kind: "bambu", label: "Bambu Lab", env: { MCP_TRANSPORT: "stdio" },
89
+ fields: [
90
+ { name: "host", env: "PRINTER_HOST", aliases: ["BAMBU_PRINTER_HOST"], label: "Address", hint: "The printer's IP address: on the printer, Settings → WLAN", required: true },
91
+ { name: "serial", env: "BAMBU_SERIAL", aliases: ["BAMBU_PRINTER_SERIAL"], label: "Serial number", hint: "On the printer: Settings → Device", required: true, transform: "uppercase" },
92
+ { name: "model", env: "BAMBU_MODEL", aliases: ["BAMBU_PRINTER_MODEL"], label: "Model", required: true, choices: modelChoices(options.models), fromSerial },
93
+ { name: "secret", env: "BAMBU_TOKEN", aliases: ["BAMBU_PRINTER_ACCESS_TOKEN"], label: "Access code", hint: "On the printer: Settings → WLAN → Access Code", required: true },
94
+ ],
95
+ }],
96
+ ...(model ? { model } : {}),
97
+ ...(options.slicer ? { slicer: options.slicer } : {}),
98
+ };
99
+ }
100
+
101
+ const field = {
102
+ type: "object",
103
+ properties: {
104
+ name: { type: "string", enum: [...SETUP_FIELD_NAMES] }, env: { type: "string" }, aliases: { type: "array", items: { type: "string" }, description: "Older names this server reads before env: a client writing env removes these, or the old value wins." },
105
+ label: { type: "string" }, hint: { type: "string" }, required: { type: "boolean" }, input: { type: "string", enum: ["path"] }, transform: { type: "string", enum: ["uppercase"] },
106
+ choices: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" } }, required: ["value", "label"] } },
107
+ fromSerial: { type: "object", properties: { prefixLength: { type: "integer" }, models: { type: "object", additionalProperties: { type: "string" } } }, required: ["prefixLength", "models"] },
108
+ },
109
+ required: ["name", "env", "label", "required"],
110
+ };
111
+ export const SETUP_FIELDS_OUTPUT_SCHEMA = {
112
+ type: "object" as const,
113
+ properties: {
114
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
115
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
116
+ kinds: { type: "array", items: { type: "object", properties: {
117
+ kind: { type: "string", enum: [...PRINTER_KINDS] }, label: { type: "string" },
118
+ env: { type: "object", additionalProperties: { type: "string" } }, fields: { type: "array", items: field },
119
+ }, required: ["kind", "label", "env", "fields"] } },
120
+ model: { type: "string" },
121
+ slicer: { type: "object", properties: {
122
+ type: { type: "string" }, path: { type: "string" }, found: { type: "boolean" }, profilesRoot: { type: "string" }, profilesFound: { type: "boolean" },
123
+ fields: { type: "array", items: field },
124
+ }, required: ["type", "found", "fields"] },
125
+ },
126
+ required: ["contract", "server", "kinds"],
127
+ };
package/src/index.ts CHANGED
@@ -60,6 +60,9 @@ import { isDualNozzleModel } from "./safety/limits.js";
60
60
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
61
61
  import { detectProfilesRoot } from "./slicer/profile-flatten.js";
62
62
  import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js";
63
+ import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
64
+ import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup, type SlicerSetup } from "./counterpart/setup.js";
65
+ import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName, type ColourNames, type ProposalTray } from "./counterpart/filaments.js";
63
66
  import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
64
67
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
65
68
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
@@ -135,6 +138,7 @@ const SERVER_INFO = {
135
138
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
136
139
  const OUTPUT_SCHEMA_TOOLS = new Set([
137
140
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
141
+ "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
138
142
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
139
143
  "camera_stream_start", "camera_frame", "camera_stream_stop",
140
144
  ]);
@@ -318,6 +322,10 @@ type PrinterFilamentInventory = {
318
322
  profile_resolution: "exact-model-nozzle" | "model" | "generic" | "unresolved";
319
323
  match_confidence: "high" | "medium" | "low" | "none";
320
324
  display_name: string;
325
+ /** Where the tray sits, as Bambu Studio labels it ("A2"). */
326
+ label: string | null;
327
+ /** The spool as a person names it: Bambu's colour name and product ("Sunflower Yellow PLA Basic"). */
328
+ spool_name: string | null;
321
329
  profile_candidates: string[];
322
330
  }>;
323
331
  recommended: {
@@ -335,6 +343,44 @@ const COLLAR_CHARM_POLICY = getCollarCharmRolePolicy();
335
343
 
336
344
  let filamentProfileIndexCache: FilamentProfileIndex | null = null;
337
345
 
346
+ /** The configured slicer's BBL filament profile folder, when the slicer configuration resolves. */
347
+ function filamentProfileDirectory(): string | undefined {
348
+ try {
349
+ const { slicerType, slicerPath } = resolveSlicerConfig(undefined);
350
+ return path.join(detectProfilesRoot(slicerPath, slicerType), "BBL", "filament");
351
+ } catch { return undefined; }
352
+ }
353
+ /** An executable path, or a bare command found on PATH. */
354
+ function executableExists(command: string): boolean {
355
+ if (!command) return false;
356
+ if (command.includes("/") || command.includes("\\")) return fs.existsSync(command);
357
+ return (process.env.PATH ?? "").split(path.delimiter).some(dir => dir && fs.existsSync(path.join(dir, command)));
358
+ }
359
+ /** A Bambu profile tree: BBL's machine profiles, or Orca's packed BBL.opc. */
360
+ function bblProfilesAt(root: string): boolean {
361
+ return fs.existsSync(path.join(root, "BBL", "machine")) || fs.existsSync(path.join(root, "BBL.opc"));
362
+ }
363
+ /** The slicer this server would run now and the settings that choose it, for counterpart_setup_fields. */
364
+ function slicerSetupNow(): SlicerSetup {
365
+ let config: { slicerType: string; slicerPath: string };
366
+ try { config = resolveSlicerConfig(undefined); } catch { config = { slicerType: String(DEFAULT_SLICER_TYPE), slicerPath: "" }; }
367
+ if (config.slicerType === "orca-slicer-api") return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, found: Boolean(process.env.SLICER_API_URL), remote: true });
368
+ const bbl = ["bambustudio", "orcaslicer", "orcaslicer-bambulab"].includes(config.slicerType);
369
+ let profilesRoot: string | undefined;
370
+ try { profilesRoot = bbl ? detectProfilesRoot(config.slicerPath, config.slicerType) : undefined; } catch { profilesRoot = undefined; }
371
+ return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, path: config.slicerPath, found: executableExists(config.slicerPath),
372
+ ...(bbl ? { profilesFound: Boolean(profilesRoot && bblProfilesAt(profilesRoot)), ...(profilesRoot ? { profilesRoot } : {}) } : {}) });
373
+ }
374
+ let colourNamesCache: ColourNames | null = null;
375
+ /** Bambu Studio's own colour names for its filaments, read once from the configured slicer's profiles. */
376
+ function colourNames(): ColourNames {
377
+ if (colourNamesCache) return colourNamesCache;
378
+ const names = loadColourNames(filamentProfileDirectory());
379
+ // A slicer installed later still names its colours: only a table that loaded is kept.
380
+ if (names !== NO_COLOUR_NAMES) colourNamesCache = names;
381
+ return names;
382
+ }
383
+
338
384
  function buildFilamentProfileIndex(): FilamentProfileIndex {
339
385
  const byName = new Map<string, string>();
340
386
  const baseNameByFilamentId = new Map<string, string>();
@@ -501,6 +547,9 @@ function normalizePrinterFilamentInventory(
501
547
  profile_resolution: profileResolution.resolution,
502
548
  match_confidence: matchConfidence,
503
549
  display_name: displayParts.length > 0 ? displayParts.join(" ") : "empty/unknown",
550
+ label: amsId !== null && trayId !== null ? bambuTrayLabel(amsId, trayId) : null,
551
+ spool_name: trayType ? spoolName(traySubBrands || trayType,
552
+ trayInfoIdx && trayColor ? colourNames().spool(trayInfoIdx, trayColor) : undefined) : null,
504
553
  profile_candidates: profileResolution.paths,
505
554
  });
506
555
  }
@@ -2082,6 +2131,8 @@ class BambuPrinterMCPServer {
2082
2131
  metadata_keys: Object.keys(parsed.metadata),
2083
2132
  summary: summarizeSliceSettings(config),
2084
2133
  raw_key_count: Object.keys(config).length,
2134
+ // ownProcessTemplate itself, for a call that names no profile or template, so this can't drift from slicing.
2135
+ own_process: (await ownProcessTemplate({}, sourcePath, undefined)) !== undefined,
2085
2136
  };
2086
2137
  }
2087
2138
 
@@ -2570,7 +2621,7 @@ class BambuPrinterMCPServer {
2570
2621
  },
2571
2622
  {
2572
2623
  name: "get_slice_settings",
2573
- description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything.",
2624
+ description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF, own_process is true when the file carries its own process (a designer's Bambu Studio or Orca project), so slice_stl and print_3mf's auto-slice slice it with that process unless the call names slicer_profile, template_name or template_3mf_path.",
2574
2625
  inputSchema: {
2575
2626
  type: "object",
2576
2627
  properties: {
@@ -3414,6 +3465,44 @@ class BambuPrinterMCPServer {
3414
3465
  },
3415
3466
  outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
3416
3467
  },
3468
+ {
3469
+ name: "counterpart_discover_printers",
3470
+ description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
3471
+ inputSchema: {
3472
+ type: "object",
3473
+ properties: { duration_ms: { type: "integer", minimum: 500, maximum: 15000, description: "How long to listen (default 4000)." } },
3474
+ additionalProperties: false
3475
+ },
3476
+ outputSchema: DISCOVER_OUTPUT_SCHEMA
3477
+ },
3478
+ {
3479
+ name: "counterpart_setup_fields",
3480
+ description: "Counterpart contract (counterpart/1): the printers this server drives and the settings it reads for each, by .env variable name (first canonical, then aliases): label, hint, whether required, the model choices and the model each serial-number prefix names. Pass serial to get the model it names. Sends nothing to a printer and returns no configured values.",
3481
+ inputSchema: {
3482
+ type: "object",
3483
+ properties: { serial: { type: "string", maxLength: 64, description: "A Bambu serial number: model is the one it names, when known." } },
3484
+ additionalProperties: false
3485
+ },
3486
+ outputSchema: SETUP_FIELDS_OUTPUT_SCHEMA
3487
+ },
3488
+ {
3489
+ name: "counterpart_propose_filaments",
3490
+ description: "Counterpart contract (counterpart/1): which loaded AMS spool prints each of a model's colours, before slicing. Reads the live AMS once. trays lists the spools a person may choose (label like \"A2\", a person-readable name, colour, material, feed). proposal gives each filament its nearest spool in OKLab colour with the asked-for material preferred, and a verdict: same-colour, closest (that colour isn't loaded; note says so), no-colour or none. One print feeds from one source. Pass chosen to check the person's spools against what is loaded now; mapping then lists every filament slot's spool (painted slots included), and problems says why a choice can't print.",
3491
+ inputSchema: {
3492
+ type: "object",
3493
+ properties: {
3494
+ ...PROPOSE_FILAMENTS_INPUT_PROPERTIES,
3495
+ bambu_model: { type: "string", description: "Printer model; defaults to BAMBU_MODEL. Selects the filament profiles that decide which spools can slice." },
3496
+ nozzle_diameter: { type: "string", description: "Nozzle diameter (default NOZZLE_DIAMETER or 0.4)." },
3497
+ host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
3498
+ bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
3499
+ bambu_token: { type: "string", description: "Access token (default: value from env); never returned." }
3500
+ },
3501
+ required: ["filaments"],
3502
+ additionalProperties: false
3503
+ },
3504
+ outputSchema: PROPOSE_FILAMENTS_OUTPUT_SCHEMA
3505
+ },
3417
3506
  {
3418
3507
  name: "counterpart_print_route",
3419
3508
  description: "Counterpart contract (counterpart/1): how this server reaches the printer for prints and for Stop/Pause/Resume. route is \"lan\" (the local network through FULU's BambuNetwork bridge, or the configured X2D native or Bambu Connect mode), \"cloud\" (Bambu Cloud through FULU's bridge) or \"developer\" (the local network straight to a printer in LAN Only + Developer Mode, whose Pause, Resume and Stop need no Bambu app). options lists each with its label, whether it can be chosen here (and why not) and what controls do on it; choices lists the ids that can be chosen. mode and type are BAMBU_DEFAULT_CONNECTION_MODE and BAMBU_DEFAULT_CONNECTION_TYPE as resolved. Pass route to change it: the change applies to the next print and control at once, and is saved to the .env file in this server's working directory when that file exists (savedTo; null otherwise). Sends nothing to the printer.",
@@ -4817,6 +4906,39 @@ class BambuPrinterMCPServer {
4817
4906
  );
4818
4907
  break;
4819
4908
 
4909
+ case "counterpart_discover_printers": {
4910
+ const requested = Number(args?.duration_ms);
4911
+ const found = await discoverBambu(Number.isFinite(requested) ? requested : 4000);
4912
+ // Only models bambu_model accepts: the X1 (serial 00W) has none, so it stays unset.
4913
+ result = { contract: "counterpart/1", network: found.state, printers: found.printers.map(({ model, ...printer }) =>
4914
+ ({ ...printer, ...(model && (VALID_BAMBU_MODELS as readonly string[]).includes(model) ? { model } : {}) })) };
4915
+ break;
4916
+ }
4917
+
4918
+ case "counterpart_setup_fields":
4919
+ result = bambuSetupFields({ server: SERVER_INFO, models: VALID_BAMBU_MODELS, slicer: slicerSetupNow(), ...(typeof args?.serial === "string" ? { serial: args.serial } : {}) });
4920
+ break;
4921
+
4922
+ case "counterpart_propose_filaments": {
4923
+ const requestedModel = (String(args?.bambu_model ?? DEFAULT_BAMBU_MODEL ?? "")).trim().toLowerCase();
4924
+ const normalizedModel = requestedModel ? validateBambuModel(requestedModel) : undefined;
4925
+ const inventory = await this.getResolvedPrinterFilamentInventory(host, bambuSerial, bambuToken, normalizedModel,
4926
+ String(args?.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER));
4927
+ const trays: ProposalTray[] = inventory.trays.flatMap(tray => {
4928
+ const colour = normalizeRgbColor(tray.tray_color);
4929
+ if (!tray.loaded || tray.slot === null || !colour || !tray.tray_type || !tray.label) return [];
4930
+ // print_3mf's tray value: an AMS-HT unit (id 128 and up, one tray) is its unit id, not ams_id × 4 + tray.
4931
+ const slot = tray.ams_id !== null && tray.ams_id >= 128 ? tray.ams_id : tray.slot;
4932
+ return [{ slot, label: tray.label, name: tray.spool_name ?? tray.tray_type, colour: `#${colour.toUpperCase()}`,
4933
+ material: tray.tray_type, filamentId: tray.tray_info_idx ?? "", feed: "ams", sliceable: Boolean(tray.resolved_profile_path),
4934
+ ...(tray.resolved_profile_path ? { profile: tray.resolved_profile_path } : {}) }];
4935
+ });
4936
+ result = proposeFilaments({ trays, filaments: Array.isArray(args?.filaments) ? args.filaments : [],
4937
+ ...(Array.isArray(args?.painted) ? { painted: args.painted } : {}), ...(Array.isArray(args?.chosen) ? { chosen: args.chosen } : {}),
4938
+ sliced: args?.sliced === true, names: colourNames() });
4939
+ break;
4940
+ }
4941
+
4820
4942
  case "counterpart_printer_info":
4821
4943
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
4822
4944
  break;
@@ -4,7 +4,7 @@ import { BambuClient, GetVersionCommand, PushAllCommand } from "bambu-node";
4
4
  import { isDualNozzleModel, normalizeMaterial, normalizeModel } from "./limits.js";
5
5
 
6
6
  const MAX_REPORT_AGE_MS = 15_000;
7
- const MODEL_IDS: Record<string, string> = {
7
+ export const MODEL_IDS: Record<string, string> = {
8
8
  O1C: "H2C", O1C2: "H2C", O1D: "H2D", O1E: "H2D Pro", O1S: "H2S", N6: "X2D",
9
9
  N2S: "A1", A1M: "A1 Mini", C11: "P1P", C12: "P1S", C13: "X1E", "BL-P001": "X1C", "BL-P002": "X1",
10
10
  };
@@ -40,6 +40,8 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
40
40
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
41
41
  list_printer_files: READ_OUTSIDE,
42
42
  counterpart_print_progress: READ_OUTSIDE,
43
+ counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
44
+ counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
43
45
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.
44
46
  bambu_network_bridge_status: hints(false, true, true, true),
45
47
  camera_frame: READ_OUTSIDE,
@@ -56,6 +58,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
56
58
  list_templates: READ_LOCAL,
57
59
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
58
60
  counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
61
+ counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
59
62
 
60
63
  // Local outputs in the server's temporary directory
61
64
  extend_stl_base: LOCAL_OUTPUT,