#!/usr/bin/env node // 3D Maker Place - local maker agent // Registers with the network, claims work, runs your own desktop tool, reports back. // // MP_AGENT_KEY=mp_xxxxxxxx node agent.mjs // MP_TASK_COMMAND='prusa-slicer --export-gcode --output {file} {input}' node agent.mjs // // Processing jobs (slice / repair / validate) download the mesh for you and run // the command with it as {input} (also MP_INPUT), the output path as {file} // (MP_OUT) and the model id as {model_id} (MP_MODEL_ID). Whatever the command // writes to {file} is uploaded back to the network - gcode, 3mf, zip, json... // When a model was split across machines, MP_PART_INDEX / MP_PART_COUNT / // MP_BATCH_ID say which piece this run is, and {input} is that piece only. // // Generation jobs run a command with these variables set, and it must write a // .glb/.gltf/.stl/.obj/.ply to MP_OUT: // MP_IMAGE reference image (or generated concept frame) to reconstruct // MP_IMAGES every frame the maker attached, comma separated // MP_IMAGE_2 the second frame, when they attached two // MP_PROMPT the user's prompt // MP_ENGINE engine id the job was routed to (triposr, trellis, hunyuan3d, local) // MP_WEIGHTS the open-weights repo to run, e.g. microsoft/TRELLIS // MP_TOPOLOGY triangle | quad // MP_POLYCOUNT target polygon count // MP_OUT path the finished mesh must be written to // // One command per engine, so a machine can take several engines without editing // anything between jobs. The engine-specific variable wins over the general one: // MP_GENERATE_COMMAND_TRELLIS='python trellis_run.py' // MP_GENERATE_COMMAND_TRIPOSR='python triposr_run.py' // MP_GENERATE_COMMAND_HUNYUAN3D='python hunyuan3d_run.py' // MP_GENERATE_COMMAND='python run.py' (fallback for any engine) // // Without MP_TASK_COMMAND the agent only reports jobs it is offered, so you can // wire your own slicer, mesh repair or validation step into it. // // The agent simply sits and polls - run it from a service, a terminal or the Windows // tray app, and it stays quiet until the network hands it a job. Set MP_LOG to a file // path to keep a timestamped record, including how long each build took. const BASE = process.env.MP_BASE || "https://3dmakerplace.com"; const KEY = process.env.MP_AGENT_KEY; const CMD = process.env.MP_TASK_COMMAND || ""; // The general command, or the one the routed engine asked for. const genCommandFor = (engineId) => process.env["MP_GENERATE_COMMAND_" + String(engineId || "").toUpperCase()] || process.env.MP_GENERATE_COMMAND || ""; const OUT_DIR = process.env.MP_OUT || "./out"; // The detail a run is asked for, per rung of the effort ladder. The extraction grid and the // sampling steps are what buy surface detail: without them the machine falls back to its own // quick defaults, which is the difference between a preview mesh and a printable one. const DETAIL = { draft: { MP_RESOLUTION: "384", MP_STEPS: "20", MP_REFINE_RES: "768" }, standard: { MP_RESOLUTION: "512", MP_STEPS: "35", MP_REFINE_RES: "1024" }, ultra: { MP_RESOLUTION: "768", MP_STEPS: "60", MP_REFINE_RES: "1536" }, }; const detailEnv = (effort) => DETAIL[String(effort || "standard")] || DETAIL.standard; const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); const run = promisify(execFile); const fs = await import("node:fs/promises"); const path = await import("node:path"); // Every path handed to a pipeline is absolute. The runner starts the pipeline in the pipeline's // own folder, so a relative MP_OUT landed the finished mesh beside the pipeline while this agent // looked for it beside itself - a run that worked was then reported as having written nothing. const OUT = path.resolve(OUT_DIR); // Pipelines print torrents of progress bars and warnings, and execFile stops the child once its // output passes the default buffer - which looked like the pipeline crashing part-way through. const BUFFER = 64 * 1024 * 1024; // The tray app launches the agent with no window: MP_LOG keeps a running record of // every poll, job and error so the machine can be checked without a console. const LOG = process.env.MP_LOG || ""; const log = (line) => { const text = String(line); console.log(text); if (LOG) fs.appendFile(LOG, new Date().toISOString() + " " + text + "\n").catch(() => {}); }; // The Windows tray app draws its icon and tooltip from this file. The agent rewrites it // every time its state changes, so the machine shows "checking in", "idle" or // "processing" while it works, without anyone opening the log. const STATUS = process.env.MP_STATUS || "./agent-status.json"; const writeStatus = (state, detail = "") => fs.writeFile(STATUS, JSON.stringify({ state, detail, at: Date.now() })).catch(() => {}); if (!KEY) { log("Set MP_AGENT_KEY to the key shown when you registered the agent."); process.exit(1); } const call = async (path, options = {}) => { const response = await fetch(BASE + path, { ...options, headers: { Authorization: "Bearer " + KEY, "Content-Type": "application/json" }, }); const body = await response.json().catch(() => ({})); if (!response.ok) throw new Error(body.error || response.status + " " + response.statusText); return body; }; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Splits a command line the way a shell would for quoted arguments, so a tool that // lives in a path with spaces ("C:/Program Files/...") still runs. const splitArgs = (text) => (String(text).match(/"[^"]*"|'[^']*'|\S+/g) || []).map((part) => part.replace(/^["']|["']$/g, "")); // Streams a finished mesh back into the app's private storage. async function uploadMesh(file) { const bytes = await fs.readFile(file); const form = new FormData(); form.append("file", new Blob([bytes]), path.basename(file)); const response = await fetch(BASE + "/api/agent/upload", { method: "POST", headers: { Authorization: "Bearer " + KEY }, body: form, }); const body = await response.json().catch(() => ({})); if (!response.ok) throw new Error(body.error || "mesh upload failed"); return { fileUri: body.file_uri, fileFormat: body.file_format }; } // Nothing to do is the normal state of a tray agent: one quiet line every ten minutes // shows the machine is still checking in. let idlePolls = 0; async function tick() { writeStatus("checking"); const { job } = await call("/api/agent/jobs"); if (!job) { writeStatus("idle"); idlePolls += 1; if (idlePolls % 120 === 1) log("watching for work - nothing waiting"); return sleep(5000); } idlePolls = 0; log("[job] " + job.type + " " + (job.task || job.engine || "") + " - " + (job.model_name || job.prompt || job.id)); writeStatus( "processing", (job.type === "generation" ? "generating" : job.task || "processing") + " - " + String(job.model_name || job.prompt || job.id).slice(0, 48), ); const started = Date.now(); let resultUrl = ""; let failed = false; let notes = ""; if (job.type === "generation") { const GEN = genCommandFor(job.engine_id); if (!GEN) { return call("/api/agent/complete", { method: "POST", body: JSON.stringify({ jobId: job.id, type: "generation", failed: true, seconds: 1, notes: "No generation command for " + (job.engine || job.engine_id) + ". Set MP_GENERATE_COMMAND_" + String(job.engine_id || "").toUpperCase() + " or MP_GENERATE_COMMAND to run these open weights on this GPU", }), }); } try { await fs.mkdir(OUT, { recursive: true }); const mesh = OUT + "/" + job.id + ".glb"; const argv = splitArgs(GEN); // The site turns these posts into a percentage, and a heartbeat that goes quiet is // how a run that stopped moving is told apart from one still working. const eta = Math.max(30, Number(job.eta_seconds) || 180); const began = Date.now(); const label = "running " + (job.engine || "the pipeline"); const report = (stage, percent) => call("/api/agent/progress", { method: "POST", body: JSON.stringify({ jobId: job.id, stage, percent }), }).catch(() => {}); await report(label, 3); const beat = setInterval(() => { const spent = Math.round((Date.now() - began) / 1000); const percent = Math.min(92, Math.round((spent / eta) * 100)); report(label + " ยท " + spent + "s", percent); }, 15000); await run(argv[0], argv.slice(1), { maxBuffer: BUFFER, env: { ...process.env, MP_PROMPT: job.prompt || "", MP_IMAGE: job.image_url || "", // Extra reference frames, when the maker attached a second one. MP_IMAGES: (job.image_urls || []).join(","), MP_IMAGE_2: (job.image_urls || [])[1] || "", // Where the network is, so the runner can refresh its own pipeline adapter. MP_BASE: BASE, MP_ENGINE: job.engine_id || "", // Open weights the network routed this job to, e.g. microsoft/TRELLIS. MP_WEIGHTS: job.weights?.repo || "", MP_TOPOLOGY: job.topology || "triangle", MP_POLYCOUNT: String(job.polycount || 0), // Grid, steps and refinement for the rung the maker chose. ...detailEnv(job.effort), MP_OUT: mesh, }, }).finally(() => clearInterval(beat)); // Pipelines written for one format often ignore MP_OUT and write their own file: // take whichever mesh actually landed next to it. let written = mesh; for (const candidate of [mesh, OUT + "/" + job.id + ".gltf", OUT + "/" + job.id + ".stl", OUT + "/" + job.id + ".obj", OUT + "/" + job.id + ".ply"]) { if (await fs.stat(candidate).then(() => true).catch(() => false)) { written = candidate; break; } } if (written === mesh && !(await fs.stat(written).then(() => true).catch(() => false))) { throw new Error("the generation command wrote no mesh to MP_OUT"); } await report("uploading the mesh", 96); const uploaded = await uploadMesh(written); await call("/api/agent/complete", { method: "POST", body: JSON.stringify({ jobId: job.id, type: "generation", resultUrl: uploaded.fileUri, fileFormat: uploaded.fileFormat, seconds: Math.round((Date.now() - started) / 1000), }), }); log("[done] " + job.id + " in " + Math.round((Date.now() - started) / 1000) + "s"); } catch (error) { // execFile's own message is often just the command line, so the reason (no pipeline // installed, python error, missing weights) comes from the child's own output. When // it printed nothing at all, report the exit code and what to fix instead of a bare // "Command failed: node openmesh-runner.mjs". const said = [error.stderr, error.stdout] .filter(Boolean) .join(" ") .replace(/[ \t]+/g, " ") .trim(); const exit = error.code == null ? error.signal || "no exit code" : "exit code " + error.code; const detail = said ? said.slice(-1400) : "the generation command stopped (" + exit + ") without printing a reason - this machine is still running an older agent or runner. Run start-maker-agent.bat again so it updates, then retry"; await call("/api/agent/complete", { method: "POST", body: JSON.stringify({ jobId: job.id, type: "generation", failed: true, seconds: Math.round((Date.now() - started) / 1000), notes: detail.slice(0, 1400), }), }); log("[failed] " + job.id + " - " + detail.slice(0, 1400)); } return; } if (!CMD) { log("no MP_TASK_COMMAND configured - reporting the job as skipped"); return call("/api/agent/complete", { method: "POST", body: JSON.stringify({ jobId: job.id, type: job.type, failed: true, seconds: 1, notes: "Agent has no task command configured" }), }); } try { await fs.mkdir(OUT, { recursive: true }); let input = ""; if (job.file_url) { input = OUT + "/" + job.id + "-input." + (job.file_format || "stl"); const response = await fetch(job.file_url); if (!response.ok) throw new Error("could not download the model (" + response.status + ")"); await fs.writeFile(input, Buffer.from(await response.arrayBuffer())); } const output = OUT + "/" + job.id + ".gcode"; const argv = splitArgs( CMD.replaceAll("{input}", input) .replaceAll("{file}", output) .replaceAll("{model_id}", job.model_id || job.id), ); await run(argv[0], argv.slice(1), { maxBuffer: BUFFER, env: { ...process.env, MP_MODEL_ID: job.model_id || "", MP_INPUT: input, MP_OUT: output, // Set on pieces of a model split across several machines. MP_PART_INDEX: job.part_index == null ? "" : String(job.part_index), MP_PART_COUNT: job.part_count == null ? "" : String(job.part_count), MP_BATCH_ID: job.batch_id || "", }, }); // Only send something back if the command actually produced it. const produced = await fs.stat(output).then(() => true).catch(() => false); if (produced) resultUrl = (await uploadMesh(output)).fileUri; } catch (error) { failed = true; notes = String(error.message || error).slice(0, 300); } await call("/api/agent/complete", { method: "POST", body: JSON.stringify({ jobId: job.id, type: job.type, resultUrl, notes, failed, seconds: Math.round((Date.now() - started) / 1000), }), }); log((failed ? "[failed] " : "[done] ") + job.id + (notes ? " - " + notes : "")); } log("3D Maker Place agent connected to " + BASE + " - asking for work every 5 seconds"); while (true) { try { await tick(); } catch (error) { log("[error] " + String(error.message || error)); await sleep(10000); } }