bambu-printer-mcp 1.1.63 → 1.1.65
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 +1 -1
- package/dist/counterpart/remote.d.ts +47 -0
- package/dist/counterpart/remote.js +141 -0
- package/dist/counterpart/sliced-file.d.ts +31 -0
- package/dist/counterpart/sliced-file.js +110 -0
- package/dist/index.js +54 -11
- package/dist/slicer/slice-cache.d.ts +28 -0
- package/dist/slicer/slice-cache.js +178 -0
- package/dist/stl/stl-manipulator.js +15 -1
- package/package.json +1 -1
- package/src/counterpart/remote.ts +160 -0
- package/src/counterpart/sliced-file.ts +115 -0
- package/src/index.ts +57 -13
- package/src/slicer/slice-cache.ts +171 -0
- package/src/stl/stl-manipulator.ts +13 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Finished slices kept for reuse: slicing the same model the same way again (Print Again, or Print after a
|
|
8
|
+
* client's estimate) restores the slicer's outputs instead of running it. A slicer run is identified by exactly
|
|
9
|
+
* what it was given: the slicer executable (its path, size and modification time, so an update slices again),
|
|
10
|
+
* this server's version, and its full argument list, with every input file replaced by its content hash and every
|
|
11
|
+
* output location by a placeholder. Profiles, filament files, the model and generated override files are all
|
|
12
|
+
* arguments, so editing any of them slices again. A run whose arguments name any other directory (its contents
|
|
13
|
+
* can't be hashed) is never cached, nor is a failed slice. Presets the slicer finds by itself, not named in its
|
|
14
|
+
* arguments (its own bundled system presets), count through the executable: a slicer update slices again.
|
|
15
|
+
*
|
|
16
|
+
* SLICE_CACHE=off turns it off; SLICE_CACHE_DIR moves it (default ~/.cache/<package name>/slices). The newest
|
|
17
|
+
* SLICE_CACHE_ENTRIES (default 16) slices are kept.
|
|
18
|
+
*/
|
|
19
|
+
export interface SlicerRun {
|
|
20
|
+
command: string;
|
|
21
|
+
args: string[];
|
|
22
|
+
/** What the slicer writes, kept and restored: files, or directories it fills. */
|
|
23
|
+
outputs: string[];
|
|
24
|
+
/** Folders it writes into that aren't kept as a whole (an --outputdir shared with other files). */
|
|
25
|
+
locations?: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const KEY_VERSION = 1;
|
|
29
|
+
/** This server's package name and version: a new release slices again. */
|
|
30
|
+
const PACKAGE = (() => {
|
|
31
|
+
try {
|
|
32
|
+
const value = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as { name?: unknown; version?: unknown };
|
|
33
|
+
return { name: String(value.name ?? "printer-mcp"), version: String(value.version ?? "") };
|
|
34
|
+
} catch {
|
|
35
|
+
return { name: "printer-mcp", version: "" };
|
|
36
|
+
}
|
|
37
|
+
})();
|
|
38
|
+
|
|
39
|
+
function enabled(): boolean {
|
|
40
|
+
return !/^(?:off|0|false|no)$/i.test(process.env.SLICE_CACHE ?? "");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sliceCacheRoot(): string {
|
|
44
|
+
return process.env.SLICE_CACHE_DIR || path.join(os.homedir(), ".cache", PACKAGE.name, "slices");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function entriesKept(): number {
|
|
48
|
+
const value = Number(process.env.SLICE_CACHE_ENTRIES);
|
|
49
|
+
return Number.isInteger(value) && value > 0 ? value : 16;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function fileHash(file: string): Promise<string> {
|
|
53
|
+
const hash = createHash("sha256");
|
|
54
|
+
for await (const chunk of fs.createReadStream(file)) hash.update(chunk as Buffer);
|
|
55
|
+
return hash.digest("hex");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function onPath(command: string): string | undefined {
|
|
59
|
+
if (path.isAbsolute(command) || command.includes("/") || command.includes("\\")) return path.resolve(command);
|
|
60
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
61
|
+
if (!dir) continue;
|
|
62
|
+
const candidate = path.join(dir, command);
|
|
63
|
+
try { if (fs.statSync(candidate).isFile()) return candidate; } catch { /* next */ }
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The run's cache key, or undefined when it can't be identified exactly (then it is never cached). */
|
|
69
|
+
export async function sliceCacheKey(run: SlicerRun): Promise<string | undefined> {
|
|
70
|
+
if (!enabled()) return undefined;
|
|
71
|
+
// Never a reason for a slice to fail: anything unreadable means this run isn't kept.
|
|
72
|
+
try { return await keyOf(run); } catch { return undefined; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function keyOf(run: SlicerRun): Promise<string | undefined> {
|
|
76
|
+
const executable = onPath(run.command);
|
|
77
|
+
if (!executable) return undefined;
|
|
78
|
+
let binary: fs.Stats;
|
|
79
|
+
try { binary = await fs.promises.stat(executable); } catch { return undefined; }
|
|
80
|
+
const outputs = run.outputs.map(output => path.resolve(output));
|
|
81
|
+
const places = [...outputs, ...(run.locations ?? []).map(location => path.resolve(location))];
|
|
82
|
+
const part = async (value: string): Promise<string | undefined> => {
|
|
83
|
+
if (!value || value.startsWith("-")) return value;
|
|
84
|
+
// A relative path is a file to the slicer too (resolved against this process's directory, as it is).
|
|
85
|
+
const resolved = path.resolve(value);
|
|
86
|
+
// An output or output folder itself: where this run writes, whatever it is called.
|
|
87
|
+
const exact = places.indexOf(resolved);
|
|
88
|
+
if (exact >= 0) return `<output ${exact}>`;
|
|
89
|
+
// A file staged inside an output folder (a generated profile, a transformed mesh) is an input: its bytes count.
|
|
90
|
+
const root = places.findIndex(place => resolved.startsWith(place + path.sep));
|
|
91
|
+
let info: fs.Stats | undefined;
|
|
92
|
+
try { info = await fs.promises.stat(resolved); } catch { info = undefined; }
|
|
93
|
+
const named = root >= 0 ? `<output ${root}>${resolved.slice(places[root].length)}` : path.isAbsolute(value) ? resolved : value;
|
|
94
|
+
// A file is its bytes (and its extension, which tells the slicer what it is), not its often random name.
|
|
95
|
+
if (info?.isFile()) return `file${path.extname(resolved).toLowerCase()}#${await fileHash(resolved)}`;
|
|
96
|
+
// A folder's contents can't be hashed: such a run is never cached.
|
|
97
|
+
if (info?.isDirectory()) return undefined;
|
|
98
|
+
return named;
|
|
99
|
+
};
|
|
100
|
+
const args: string[] = [];
|
|
101
|
+
for (const arg of run.args) {
|
|
102
|
+
const parts: string[] = [];
|
|
103
|
+
for (const piece of arg.split(";")) {
|
|
104
|
+
const value = await part(piece);
|
|
105
|
+
if (value === undefined) return undefined;
|
|
106
|
+
parts.push(value);
|
|
107
|
+
}
|
|
108
|
+
args.push(parts.join(";"));
|
|
109
|
+
}
|
|
110
|
+
return createHash("sha256").update(JSON.stringify({ v: KEY_VERSION, server: PACKAGE,
|
|
111
|
+
slicer: { path: fs.realpathSync(executable), size: binary.size, mtimeMs: binary.mtimeMs }, args })).digest("hex");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function touch(target: string, at: Date): Promise<void> {
|
|
115
|
+
const info = await fs.promises.stat(target);
|
|
116
|
+
if (info.isDirectory()) for (const name of await fs.promises.readdir(target)) await touch(path.join(target, name), at);
|
|
117
|
+
await fs.promises.utimes(target, at, at);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Puts a kept slice's outputs where this run would write them; false when there is none. */
|
|
121
|
+
export async function restoreSlice(key: string, run: SlicerRun): Promise<boolean> {
|
|
122
|
+
const entry = path.join(sliceCacheRoot(), key);
|
|
123
|
+
try {
|
|
124
|
+
const meta = JSON.parse(await fs.promises.readFile(path.join(entry, "meta.json"), "utf8")) as { outputs?: unknown; saved?: unknown };
|
|
125
|
+
if (meta.outputs !== run.outputs.length || !Array.isArray(meta.saved)) return false;
|
|
126
|
+
const saved = new Set(meta.saved.filter((index): index is number => typeof index === "number"));
|
|
127
|
+
// Every output the slicer wrote must still be there, or this is no slice at all.
|
|
128
|
+
for (const index of saved) if (!fs.existsSync(path.join(entry, String(index)))) return false;
|
|
129
|
+
const now = new Date();
|
|
130
|
+
for (const [index, output] of run.outputs.entries()) {
|
|
131
|
+
if (!saved.has(index)) continue; // the slicer didn't write this one
|
|
132
|
+
await fs.promises.mkdir(path.dirname(output), { recursive: true });
|
|
133
|
+
await fs.promises.cp(path.join(entry, String(index)), output, { recursive: true, force: true });
|
|
134
|
+
// Fresh timestamps on every restored file: a result.json must read as written by this run.
|
|
135
|
+
await touch(output, now);
|
|
136
|
+
}
|
|
137
|
+
await fs.promises.utimes(entry, now, now);
|
|
138
|
+
return true;
|
|
139
|
+
} catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Keeps a finished slice's outputs, whole or not at all; a failure to keep it never fails the slice. */
|
|
145
|
+
export async function keepSlice(key: string, run: SlicerRun): Promise<void> {
|
|
146
|
+
const root = sliceCacheRoot();
|
|
147
|
+
try {
|
|
148
|
+
await fs.promises.mkdir(root, { recursive: true, mode: 0o700 });
|
|
149
|
+
const staging = await fs.promises.mkdtemp(path.join(root, ".staging-"));
|
|
150
|
+
try {
|
|
151
|
+
const saved: number[] = [];
|
|
152
|
+
for (const [index, output] of run.outputs.entries()) {
|
|
153
|
+
if (!fs.existsSync(output)) continue;
|
|
154
|
+
await fs.promises.cp(output, path.join(staging, String(index)), { recursive: true });
|
|
155
|
+
saved.push(index);
|
|
156
|
+
}
|
|
157
|
+
await fs.promises.writeFile(path.join(staging, "meta.json"), JSON.stringify({ outputs: run.outputs.length, saved, keptAt: new Date().toISOString() }));
|
|
158
|
+
await fs.promises.rm(path.join(root, key), { recursive: true, force: true });
|
|
159
|
+
await fs.promises.rename(staging, path.join(root, key));
|
|
160
|
+
} finally {
|
|
161
|
+
await fs.promises.rm(staging, { recursive: true, force: true });
|
|
162
|
+
}
|
|
163
|
+
const entries = await Promise.all((await fs.promises.readdir(root)).filter(name => /^[0-9a-f]{64}$/.test(name))
|
|
164
|
+
.map(async name => ({ name, at: (await fs.promises.stat(path.join(root, name))).mtimeMs })));
|
|
165
|
+
for (const old of entries.sort((a, b) => b.at - a.at).slice(entriesKept())) {
|
|
166
|
+
await fs.promises.rm(path.join(root, old.name), { recursive: true, force: true });
|
|
167
|
+
}
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error(`Could not keep this slice for reuse: ${error instanceof Error ? error.message : String(error)}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -10,6 +10,7 @@ import { promisify } from 'util';
|
|
|
10
10
|
import { EventEmitter } from 'events';
|
|
11
11
|
import * as crypto from 'crypto';
|
|
12
12
|
import { execFile } from 'child_process';
|
|
13
|
+
import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
|
|
13
14
|
import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
|
|
14
15
|
import { applyProcessOverrides, type ProcessOverrides } from '../slicer/process-overrides.js';
|
|
15
16
|
import { profileJsonFiles } from '../slicer/profile-files.js';
|
|
@@ -2020,7 +2021,17 @@ export class STLManipulator extends EventEmitter {
|
|
|
2020
2021
|
throw new Error(`Unsupported slicer type: ${slicerType}`);
|
|
2021
2022
|
}
|
|
2022
2023
|
|
|
2023
|
-
|
|
2024
|
+
// The Bambu-compatible CLI's slice, kept for reuse: the same model sliced the same way again is restored,
|
|
2025
|
+
// and every check below still runs on it (slice-cache.ts).
|
|
2026
|
+
const cacheRun = cliResult && slicerType !== 'orca-slicer-api'
|
|
2027
|
+
? { command: slicerPath, args, outputs: [outputFilePath, cliResult.resultPath], locations: [path.dirname(cliResult.resultPath)] } : undefined;
|
|
2028
|
+
const cacheKey = cacheRun ? await sliceCacheKey(cacheRun) : undefined;
|
|
2029
|
+
const restored = !!cacheKey && await restoreSlice(cacheKey, cacheRun!);
|
|
2030
|
+
if (restored) {
|
|
2031
|
+
if (progressCallback) progressCallback(90, 'Reusing the same slice of this model');
|
|
2032
|
+
console.error(`Reusing slice ${cacheKey} for: ${slicerPath} ${args.join(' ')}`);
|
|
2033
|
+
}
|
|
2034
|
+
if (slicerType !== 'orca-slicer-api' && !restored) {
|
|
2024
2035
|
if (progressCallback) progressCallback(20, `Executing slicer: ${slicerPath} ${args.join(' ')}`);
|
|
2025
2036
|
console.error(`Executing: ${slicerPath} ${args.join(' ')}`);
|
|
2026
2037
|
|
|
@@ -2078,6 +2089,7 @@ export class STLManipulator extends EventEmitter {
|
|
|
2078
2089
|
if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
|
|
2079
2090
|
throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
|
|
2080
2091
|
}
|
|
2092
|
+
if (cacheKey && !restored && fs.existsSync(outputFilePath)) await keepSlice(cacheKey, cacheRun!);
|
|
2081
2093
|
|
|
2082
2094
|
if (!fs.existsSync(outputFilePath)) {
|
|
2083
2095
|
throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
|