Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Wire NIM forge frontend and tests; refine studio MCP tool and page index

nirholasbbdc39c0a473
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4a956899..a6b6d18c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **CA → x402** (`/ca2x402`) — Paste any token contract address and get a live, agent-payable x402 endpoint for its market intel — price, momentum, and a bullish/bearish signal — for $0.01 USDC, discoverable in the x402 bazaar.
- **Cosmos — Living Worlds** (`/cosmos`) — Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.
- **Custody Integrity** (`/integrity`) — Provable, on-chain-anchored custody for every three.ws agent wallet. The platform commits a Merkle root over every wallet's on-chain state to Solana — verify the latest root yourself, no account required.
+- **Forge · NIM — Self-Hosted Image to 3D** (`/forge-nim`) — Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.
- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
- **Instant Agent Genesis** (`/genesis`) — A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.
- **Live Trading Theater** (`/theater`) — Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index ca9c12af3..94ea9d058 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -195,14 +195,14 @@ const TIER_PROP = {
enum: TIER_IDS,
default: DEFAULT_TIER,
description:
- 'Quality tier: draft (~12k poly, fast), standard (~30k, balanced), high (~200k + PBR, slower). Honoured by poly-aware backends (Meshy/Tripo/Hunyuan3D); the TRELLIS default records it as provenance.',
+ 'Quality tier: draft (~12k poly, fast), standard (~30k, balanced), high (~200k + PBR, slower). Honoured by the poly-aware engines (the geometry, sculpt, and detail engines); the default image engine records it as provenance.',
};
const PATH_PROP = {
type: 'string',
enum: PATHS,
default: DEFAULT_PATH,
description:
- 'Generation path: "image" (FLUX→TRELLIS reference-image reconstruction, the platform-keyed default) or "geometry" (native text/image→mesh via Meshy/Tripo/Rodin — cleaner topology, but BYOK: needs your own provider key).',
+ 'Generation path: "image" (reference-image reconstruction on the platform-keyed image engine, the default) or "geometry" (native text/image→mesh on a geometry engine — cleaner topology, but bring-your-own-key: needs your own provider key).',
};
const MCP_UNSELECTABLE_BACKENDS = new Set([
// replicate_byok runs on the platform reconstruction path with the caller's
@@ -217,12 +217,65 @@ const MCP_UNSELECTABLE_BACKENDS = new Set([
// the separate forge_free tool, which targets the NVIDIA lane via /api/forge.
'huggingface',
]);
+
+// ── White-labeled engine taxonomy ────────────────────────────────────────────
+// The MCP wire speaks only in three.ws-branded engine names; the underlying
+// generation vendors never surface in a tool schema, response, or artifact. Each
+// public engine maps to one internal forge backend. Legacy vendor ids are still
+// ACCEPTED on input as hidden back-compat aliases (resolveEngineArg), but only
+// the branded names are advertised. The default is "auto" — the platform picks
+// the best engine for the chosen path and tier.
+const ENGINES = Object.freeze({
+ 'three-image': Object.freeze({ internal: 'trellis', label: 'three.ws Image engine' }),
+ 'three-geometry': Object.freeze({ internal: 'meshy', label: 'three.ws Geometry engine' }),
+ 'three-geometry-pro': Object.freeze({ internal: 'tripo', label: 'three.ws Geometry Pro engine' }),
+ 'three-sculpt': Object.freeze({ internal: 'rodin', label: 'three.ws Sculpt engine' }),
+ 'three-detail': Object.freeze({ internal: 'hunyuan3d', label: 'three.ws Detail engine' }),
+ 'three-instant': Object.freeze({ internal: 'stability', label: 'three.ws Instant engine' }),
+ 'three-sketch': Object.freeze({ internal: 'triposg', label: 'three.ws Sketch engine' }),
+});
+// Internal backend id → branded engine id, for shaping responses. Every platform
+// image lane (the hosted, self-hosted, and free reconstruction backends) presents
+// as the single "three.ws Image engine" — the caller never learns which one ran.
+const INTERNAL_TO_ENGINE = Object.freeze({
+ trellis: 'three-image',
+ nvidia: 'three-image',
+ trellis_selfhost: 'three-image',
+ huggingface: 'three-image',
+ replicate_byok: 'three-image',
+ meshy: 'three-geometry',
+ tripo: 'three-geometry-pro',
+ rodin: 'three-sculpt',
+ hunyuan3d: 'three-detail',
+ stability: 'three-instant',
+ triposg: 'three-sketch',
+});
+function engineIdFor(internalId) {
+ return INTERNAL_TO_ENGINE[internalId] || 'three-image';
+}
+function engineLabelFor(internalId) {
+ return ENGINES[engineIdFor(internalId)]?.label || 'three.ws engine';
+}
+// Map a caller's engine argument to an internal backend id. Accepts a branded
+// engine id (preferred), "auto"/empty (→ undefined, the platform picks), or a
+// legacy vendor id (hidden back-compat, excluding the never-selectable lanes).
+// Anything unrecognised falls through to undefined so resolveBackendId applies
+// the platform default — forgiving at the boundary, never a hard 422.
+function resolveEngineArg(args) {
+ const raw = typeof args?.backend === 'string' ? args.backend.trim() : '';
+ if (!raw || raw === 'auto') return undefined;
+ if (ENGINES[raw]) return ENGINES[raw].internal;
+ if (BACKENDS[raw] && !MCP_UNSELECTABLE_BACKENDS.has(raw)) return raw;
+ return undefined;
+}
const BACKEND_PROP = {
+ // Intentionally no `enum`: branded names are the advertised vocabulary (below),
+ // but legacy vendor ids are still accepted silently for back-compat, which a
+ // strict enum would reject. resolveEngineArg validates and normalizes instead.
type: 'string',
- // Every other backend is selectable here.
- enum: Object.keys(BACKENDS).filter((id) => !MCP_UNSELECTABLE_BACKENDS.has(id)),
+ default: 'auto',
description:
- 'Force a specific backend (trellis, meshy, tripo, rodin, stability, hunyuan3d). Defaults to the best one for the chosen path. Backends outside the path are ignored.',
+ 'three.ws generation engine. "auto" (default) lets the platform pick the best engine for the chosen path and tier. Override with: three-image (image-reconstruction), three-geometry or three-geometry-pro (native text/image→mesh, clean quad topology), three-sculpt (high-poly detail), three-instant (fast single-image), three-sketch (sketch→mesh). An engine that does not serve the chosen path is ignored.',
};
// "needs a BYOK key" — a designed, branchable result (mirrors /api/forge's
@@ -230,20 +283,24 @@ const BACKEND_PROP = {
// so a caller without one is told exactly how to enable the path.
function needsKeyResult(backendId) {
const meta = BACKENDS[backendId];
+ // The bring-your-own-key path is the one place a credential provider name must
+ // be disclosed — the caller has to know which key to supply. The engine itself
+ // is still presented under its three.ws brand.
+ const provider = meta?.byok || backendId;
return {
content: [
{
type: 'text',
text:
- `${meta?.label || backendId} needs your own API key. ` +
- `Send it as the "x-forge-provider-key" request header (or store a ${meta?.byok || backendId} key on your three.ws account) and retry, ` +
+ `The ${engineLabelFor(backendId)} runs on a bring-your-own-key provider. ` +
+ `Send your ${provider} key as the "x-forge-provider-key" request header (or store a ${provider} key on your three.ws account) and retry, ` +
'or use the default image path (omit "path", or set path="image").',
},
],
structuredContent: {
status: 'needs_key',
- backend: backendId,
- provider: meta?.byok || backendId,
+ engine: engineIdFor(backendId),
+ provider,
},
isError: true,
};
diff --git a/data/pages.json b/data/pages.json
index df174fc92..4508f130a 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -265,6 +265,14 @@
"changefreq": "weekly",
"added": "2026-06-04"
},
+ {
+ "path": "/forge-nim",
+ "title": "Forge · NIM — Self-Hosted Image to 3D",
+ "description": "Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.",
+ "priority": 0.7,
+ "changefreq": "monthly",
+ "added": "2026-06-23"
+ },
{
"path": "/forge-studio",
"title": "Studio — Object + Avatar from text",
diff --git a/public/changelog.xml b/public/changelog.xml
index ca1df32e4..7f9b53e06 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -86,6 +86,14 @@
<category>launch</category>
<description>Provable, on-chain-anchored custody for every three.ws agent wallet. The platform commits a Merkle root over every wallet's on-chain state to Solana — verify the latest root yourself, no account required.</description>
</item>
+ <item>
+ <title>Forge · NIM — Self-Hosted Image to 3D</title>
+ <link>https://three.ws/forge-nim</link>
+ <guid isPermaLink="false">2026-06-23:Forge · NIM — Self-Hosted Image to 3D</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.</description>
+ </item>
<item>
<title>Guardian console — recover &amp; inherit agent wallets</title>
<link>https://three.ws/guardian</link>
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 9e2157f34..ab622cd21 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -200,6 +200,12 @@ URL: https://three.ws/forge
Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+### Forge · NIM — Self-Hosted Image to 3D
+
+URL: https://three.ws/forge-nim
+
+Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.
+
### Studio — Object + Avatar from text
URL: https://three.ws/forge-studio
diff --git a/public/llms.txt b/public/llms.txt
index 284a4ece0..79a29b7ef 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -44,6 +44,7 @@ Create and customize an agent.
- [Viewer](https://three.ws/app): Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser.
- [Describe it to 3D](https://three.ws/create/prompt): Type a description. About a minute later: a rigged 3D avatar you can animate and download.
- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+- [Forge · NIM — Self-Hosted Image to 3D](https://three.ws/forge-nim): Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.
- [Studio — Object + Avatar from text](https://three.ws/forge-studio): One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
- [Cosmos — Living Worlds](https://three.ws/cosmos): Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.
- [Scene Studio](https://three.ws/scene): Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes.
diff --git a/src/nim-forge.js b/src/nim-forge.js
new file mode 100644
index 000000000..63d2d2775
--- /dev/null
+++ b/src/nim-forge.js
@@ -0,0 +1,291 @@
+// Driver for the isolated TRELLIS NIM image→3D demo (/nim-forge).
+//
+// Fully standalone: it talks ONLY to /api/nim-forge, which proxies a self-hosted
+// Microsoft TRELLIS NIM. The browser downscales the chosen photo before upload
+// (keeps the request small + gives TRELLIS a clean single-object view), posts it,
+// and renders the returned GLB in <model-viewer> from an in-memory blob URL — no
+// R2, no production Forge code involved.
+
+const API = '/api/nim-forge';
+const MAX_EDGE = 1024; // downscale longest edge to this before upload
+const JPEG_QUALITY = 0.9;
+
+const $ = (id) => document.getElementById(id);
+const els = {
+ badge: $('status-badge'),
+ statusText: $('status-text'),
+ modeImage: $('mode-image'),
+ modeText: $('mode-text'),
+ paneImage: $('pane-image'),
+ paneText: $('pane-text'),
+ drop: $('drop'),
+ file: $('file'),
+ preview: $('preview'),
+ clear: $('clear'),
+ prompt: $('prompt'),
+ tiers: $('tiers'),
+ generate: $('generate'),
+ stage: $('stage'),
+ panelEmpty: $('panel-empty'),
+ panelLoading: $('panel-loading'),
+ panelError: $('panel-error'),
+ errorMsg: $('error-msg'),
+ elapsed: $('elapsed'),
+ substep: $('substep'),
+ viewer: $('viewer'),
+ resultbar: $('resultbar'),
+ resultMeta: $('result-meta'),
+ download: $('download'),
+};
+
+const state = {
+ mode: 'image',
+ tier: 'standard',
+ imageDataUri: null,
+ busy: false,
+ blobUrl: null,
+ timer: null,
+};
+
+// ── Readiness badge ─────────────────────────────────────────────────────────
+async function checkReadiness() {
+ try {
+ const res = await fetch(API, { method: 'GET' });
+ const data = await res.json();
+ if (data.configured) {
+ els.badge.dataset.state = 'up';
+ els.statusText.textContent = 'NIM online · /v1/infer';
+ } else {
+ els.badge.dataset.state = 'down';
+ els.statusText.textContent = 'NIM not configured';
+ }
+ } catch {
+ els.badge.dataset.state = 'down';
+ els.statusText.textContent = 'engine unreachable';
+ }
+}
+
+// ── Mode switch ─────────────────────────────────────────────────────────────
+function setMode(mode) {
+ state.mode = mode;
+ const isImage = mode === 'image';
+ els.modeImage.setAttribute('aria-pressed', String(isImage));
+ els.modeText.setAttribute('aria-pressed', String(!isImage));
+ els.paneImage.hidden = !isImage;
+ els.paneText.hidden = isImage;
+ updateGenerate();
+}
+
+// ── Tier switch ─────────────────────────────────────────────────────────────
+function setTier(tier) {
+ state.tier = tier;
+ for (const b of els.tiers.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.tier === tier));
+ }
+}
+
+// ── Image handling: downscale to a clean data-uri ───────────────────────────
+function fileToDownscaledDataUri(file) {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ const url = URL.createObjectURL(file);
+ img.onload = () => {
+ URL.revokeObjectURL(url);
+ const scale = Math.min(1, MAX_EDGE / Math.max(img.width, img.height));
+ const w = Math.max(1, Math.round(img.width * scale));
+ const h = Math.max(1, Math.round(img.height * scale));
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d');
+ // White matte so PNGs with transparency don't reconstruct against black.
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, w, h);
+ ctx.drawImage(img, 0, 0, w, h);
+ resolve(canvas.toDataURL('image/jpeg', JPEG_QUALITY));
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error('Could not read that image.'));
+ };
+ img.src = url;
+ });
+}
+
+async function acceptFile(file) {
+ if (!file || !file.type.startsWith('image/')) {
+ showError('Please choose a PNG, JPEG, or WebP image.');
+ return;
+ }
+ try {
+ const dataUri = await fileToDownscaledDataUri(file);
+ state.imageDataUri = dataUri;
+ els.preview.src = dataUri;
+ els.preview.hidden = false;
+ els.drop.classList.add('has-image');
+ updateGenerate();
+ } catch (err) {
+ showError(err.message || 'Could not read that image.');
+ }
+}
+
+function clearImage() {
+ state.imageDataUri = null;
+ els.preview.src = '';
+ els.preview.hidden = true;
+ els.drop.classList.remove('has-image');
+ els.file.value = '';
+ updateGenerate();
+}
+
+// ── Generate button enablement ──────────────────────────────────────────────
+function updateGenerate() {
+ if (state.busy) return;
+ const ready = state.mode === 'image' ? Boolean(state.imageDataUri) : els.prompt.value.trim().length >= 3;
+ els.generate.disabled = !ready;
+ els.generate.textContent = ready
+ ? 'Generate'
+ : state.mode === 'image'
+ ? 'Add a photo to start'
+ : 'Describe an object to start';
+}
+
+// ── Stage panel switching ───────────────────────────────────────────────────
+function showPanel(which) {
+ els.panelEmpty.classList.toggle('is-active', which === 'empty');
+ els.panelLoading.classList.toggle('is-active', which === 'loading');
+ els.panelError.classList.toggle('is-active', which === 'error');
+ els.viewer.classList.toggle('is-active', which === 'result');
+ els.resultbar.classList.toggle('is-active', which === 'result');
+}
+
+function showError(msg) {
+ stopTimer();
+ els.errorMsg.textContent = msg;
+ showPanel('error');
+ state.busy = false;
+ updateGenerate();
+}
+
+function startTimer() {
+ const t0 = performance.now();
+ els.elapsed.textContent = '0.0s';
+ state.timer = setInterval(() => {
+ els.elapsed.textContent = `${((performance.now() - t0) / 1000).toFixed(1)}s`;
+ }, 100);
+}
+function stopTimer() {
+ if (state.timer) {
+ clearInterval(state.timer);
+ state.timer = null;
+ }
+}
+
+// ── Generate ────────────────────────────────────────────────────────────────
+async function generate() {
+ if (state.busy) return;
+ const payload = { tier: state.tier };
+ if (state.mode === 'image') {
+ if (!state.imageDataUri) return;
+ payload.image = state.imageDataUri;
+ } else {
+ const p = els.prompt.value.trim();
+ if (p.length < 3) return;
+ payload.prompt = p;
+ }
+
+ state.busy = true;
+ els.generate.disabled = true;
+ els.generate.textContent = 'Generating…';
+ els.substep.textContent = state.mode === 'image' ? 'Reconstructing mesh on the NIM…' : 'Generating mesh on the NIM…';
+ showPanel('loading');
+ startTimer();
+
+ let data;
+ try {
+ const res = await fetch(API, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data.message || `Request failed (${res.status}).`);
+ } catch (err) {
+ showError(err.message || 'The NIM request failed.');
+ return;
+ }
+
+ if (!data.glb_base64) {
+ showError(data.message || 'The NIM returned no model.');
+ return;
+ }
+
+ // Decode base64 → Blob → object URL for <model-viewer>.
+ try {
+ const bytes = Uint8Array.from(atob(data.glb_base64), (c) => c.charCodeAt(0));
+ const blob = new Blob([bytes], { type: 'model/gltf-binary' });
+ if (state.blobUrl) URL.revokeObjectURL(state.blobUrl);
+ state.blobUrl = URL.createObjectURL(blob);
+ els.viewer.setAttribute('src', state.blobUrl);
+ els.download.href = state.blobUrl;
+ const kb = (data.bytes / 1024).toFixed(0);
+ const secs = (data.ms / 1000).toFixed(1);
+ els.resultMeta.innerHTML = `<b>${kb} KB</b> GLB · ${secs}s · ${data.steps ?? '—'} steps · TRELLIS NIM`;
+ showPanel('result');
+ } catch {
+ showError('Could not decode the returned model.');
+ return;
+ }
+
+ stopTimer();
+ state.busy = false;
+ updateGenerate();
+}
+
+// ── Wire up ─────────────────────────────────────────────────────────────────
+els.modeImage.addEventListener('click', () => setMode('image'));
+els.modeText.addEventListener('click', () => setMode('text'));
+els.tiers.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-tier]');
+ if (btn) setTier(btn.dataset.tier);
+});
+els.file.addEventListener('change', (e) => {
+ const f = e.target.files?.[0];
+ if (f) acceptFile(f);
+});
+els.clear.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ clearImage();
+});
+els.prompt.addEventListener('input', updateGenerate);
+els.generate.addEventListener('click', generate);
+
+// Drag + drop onto the drop zone.
+['dragenter', 'dragover'].forEach((ev) =>
+ els.drop.addEventListener(ev, (e) => {
+ e.preventDefault();
+ els.drop.classList.add('is-over');
+ }),
+);
+['dragleave', 'drop'].forEach((ev) =>
+ els.drop.addEventListener(ev, (e) => {
+ e.preventDefault();
+ els.drop.classList.remove('is-over');
+ }),
+);
+els.drop.addEventListener('drop', (e) => {
+ const f = e.dataTransfer?.files?.[0];
+ if (f) acceptFile(f);
+});
+
+// When the model finishes loading, drop the spinner if it was somehow still up.
+els.viewer.addEventListener('load', () => {
+ if (!state.busy) showPanel('result');
+});
+els.viewer.addEventListener('error', () => {
+ if (!state.busy) showError('The viewer could not load the model.');
+});
+
+checkReadiness();
+updateGenerate();
diff --git a/tests/api/nim-forge.test.js b/tests/api/nim-forge.test.js
new file mode 100644
index 000000000..2e678e6aa
--- /dev/null
+++ b/tests/api/nim-forge.test.js
@@ -0,0 +1,183 @@
+// Isolated TRELLIS NIM demo endpoint (/api/nim-forge) — readiness, the /v1/infer
+// request contract, GLB extraction across artifact shapes, and error mapping.
+// Global fetch is stubbed; no live NIM is contacted.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const ORIGINAL_FETCH = globalThis.fetch;
+process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
+process.env.NIM_TRELLIS_KEY = 'nim-secret';
+
+const { default: handler } = await import('../../api/nim-forge.js');
+
+function makeReq(method = 'GET', body = null) {
+ const req = { url: '/api/nim-forge', method, headers: { host: 'x' } };
+ if (body !== null) {
+ req.headers['content-type'] = 'application/json';
+ const buf = Buffer.from(JSON.stringify(body));
+ req.on = (ev, fn) => {
+ if (ev === 'data') queueMicrotask(() => fn(buf));
+ if (ev === 'end') queueMicrotask(fn);
+ return req;
+ };
+ }
+ return req;
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+async function call(method = 'GET', body = null) {
+ const res = makeRes();
+ await handler(makeReq(method, body), res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON */ }
+ return { res, body: parsed };
+}
+
+const PNG_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/AP+AAAAAElFTkSuQmCC';
+
+function jsonResponse(body, status = 200, headers = {}) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json', ...headers },
+ });
+}
+
+beforeEach(() => {
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_KEY = 'nim-secret';
+});
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ vi.restoreAllMocks();
+});
+
+describe('GET /api/nim-forge — readiness', () => {
+ it('reports configured without leaking the URL or key', async () => {
+ const { res, body } = await call('GET');
+ expect(res.statusCode).toBe(200);
+ expect(body.configured).toBe(true);
+ expect(body.endpoint).toBe('/v1/infer');
+ expect(JSON.stringify(body)).not.toContain('nim.example');
+ expect(JSON.stringify(body)).not.toContain('nim-secret');
+ });
+});
+
+describe('POST /api/nim-forge — image→3D contract', () => {
+ it('posts mode:image to <NIM>/v1/infer with auth and returns the GLB', async () => {
+ const glb = Buffer.from('GLB\0trellis-mesh');
+ const glbB64 = glb.toString('base64');
+ const fetchMock = vi.fn(async (url, opts) => {
+ expect(url).toBe('https://nim.example.run.app/v1/infer');
+ expect(opts.method).toBe('POST');
+ expect(opts.headers.authorization).toBe('Bearer nim-secret');
+ const sent = JSON.parse(opts.body);
+ expect(sent.mode).toBe('image');
+ expect(sent.image).toBe(PNG_DATA_URI);
+ expect(sent.output_format).toBe('glb');
+ expect(sent.ss_sampling_steps).toBe(25); // standard tier
+ return jsonResponse({ artifacts: [{ base64: glbB64 }] }, 200);
+ });
+ globalThis.fetch = fetchMock;
+
+ const { res, body } = await call('POST', { image: PNG_DATA_URI, tier: 'standard' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(res.statusCode).toBe(200);
+ expect(body.glb_base64).toBe(glbB64);
+ expect(body.bytes).toBe(glb.length);
+ expect(body.mode).toBe('image_to_3d');
+ expect(body.steps).toBe(25);
+ });
+
+ it('maps quality tiers to sampling steps', async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({ artifacts: [{ base64: Buffer.from('x').toString('base64') }] }));
+ const draft = await call('POST', { image: PNG_DATA_URI, tier: 'draft' });
+ expect(draft.body.steps).toBe(15);
+ const high = await call('POST', { image: PNG_DATA_URI, tier: 'high' });
+ expect(high.body.steps).toBe(40);
+ });
+
+ it('extracts a GLB returned as raw model bytes (Accept ignored)', async () => {
+ const glb = Buffer.from('GLBrawbytes');
+ globalThis.fetch = vi.fn(async () => new Response(glb, {
+ status: 200,
+ headers: { 'content-type': 'model/gltf-binary' },
+ }));
+ const { res, body } = await call('POST', { image: PNG_DATA_URI });
+ expect(res.statusCode).toBe(200);
+ expect(body.glb_base64).toBe(glb.toString('base64'));
+ });
+
+ it('supports text→3D when no image is given', async () => {
+ const fetchMock = vi.fn(async (url, opts) => {
+ const sent = JSON.parse(opts.body);
+ expect(sent.mode).toBe('text');
+ expect(sent.prompt).toBe('a red fox');
+ return jsonResponse({ artifacts: [{ base64: Buffer.from('m').toString('base64') }] });
+ });
+ globalThis.fetch = fetchMock;
+ const { res, body } = await call('POST', { prompt: 'a red fox' });
+ expect(res.statusCode).toBe(200);
+ expect(body.mode).toBe('text_to_3d');
+ });
+});
+
+describe('POST /api/nim-forge — validation + error mapping', () => {
+ it('rejects a request with neither image nor prompt', async () => {
+ const { res, body } = await call('POST', { tier: 'standard' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_request');
+ });
+
+ it('rejects an image that is not a base64 data-uri', async () => {
+ const { res, body } = await call('POST', { image: 'https://example.com/photo.png' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_image');
+ });
+
+ it('surfaces an upstream NIM error as a 502 with the detail', async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({ detail: 'bad image' }, 422));
+ const { res, body } = await call('POST', { image: PNG_DATA_URI });
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('nim_error');
+ expect(body.upstream_status).toBe(422);
+ expect(body.message).toContain('bad image');
+ });
+
+ it('reports nim_unreachable when the NIM connection throws', async () => {
+ globalThis.fetch = vi.fn(async () => { throw new Error('ECONNREFUSED'); });
+ const { res, body } = await call('POST', { image: PNG_DATA_URI });
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('nim_unreachable');
+ });
+
+ it('reports nim_no_glb when the NIM returns no artifact', async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({ artifacts: [] }, 200));
+ const { res, body } = await call('POST', { image: PNG_DATA_URI });
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('nim_no_glb');
+ });
+});
+
+describe('POST /api/nim-forge — unconfigured deployment', () => {
+ it('returns 503 with a setup hint when no NIM URL is set', async () => {
+ vi.resetModules();
+ delete process.env.NIM_TRELLIS_URL;
+ delete process.env.MODEL_TRELLIS_URL;
+ const { default: freshHandler } = await import('../../api/nim-forge.js?unconfigured');
+ const res = makeRes();
+ await freshHandler(makeReq('POST', { image: PNG_DATA_URI }), res);
+ const body = JSON.parse(res._body);
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('unconfigured');
+ expect(body.message).toContain('NIM_TRELLIS_URL');
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index b2a27e0b3..b5df95a27 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -315,6 +315,7 @@ const appConfig = {
create: resolve(__dirname, 'pages/create.html'),
'create-agent': resolve(__dirname, 'pages/create-agent.html'),
forge: resolve(__dirname, 'pages/forge.html'),
+ 'nim-forge': resolve(__dirname, 'pages/nim-forge.html'),
dad: resolve(__dirname, 'pages/dad.html'),
'forge-studio': resolve(__dirname, 'pages/forge-studio.html'),
'forge-embed': resolve(__dirname, 'pages/forge-embed.html'),