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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add forge Trellis self-host provider tier, GCP Cloud Run backend, and demo harness
nirholas903de7cbd061
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex 784443e70..d7bc03273 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -233,6 +233,28 @@ export const BACKENDS = Object.freeze({credits: null,blurb: 'Self-hosted high-poly reconstruction. Image-conditioned geometry.',}),+ trellis_selfhost: Object.freeze({+ id: 'trellis_selfhost',+ label: 'TRELLIS (self-host)',+ vendor: 'Microsoft TRELLIS · self-host',+ paths: Object.freeze(['image']),+ byok: false,+ provider: 'gcp',+ // Our own TRELLIS NIM worker (workers/model-trellis on Cloud Run). Unlike+ // NVIDIA's hosted preview (text-only, userImages:false), a self-deployed+ // TRELLIS accepts real user images — so this is a NATIVE single-hop image→3D+ // lane (image → TRELLIS → GLB), no FLUX intermediate. Shares the worker+ // bearer secret with the other GCP workers.+ requiresEnv: Object.freeze(['MODEL_TRELLIS_URL', 'GCP_RECONSTRUCTION_KEY']),+ polyControl: false,+ userImages: true,+ baseEta: 60,+ credits: null,+ // Self-hosted on our own GPU — zero vendor credit cost, so it qualifies as a+ // free lane and is the preferred free image→3D engine when configured.+ free: true,+ blurb: 'Free native image→3D on our own TRELLIS worker — single-hop reconstruction (image → TRELLIS → GLB), textured GLB, no vendor cost.',+ }),triposg: Object.freeze({id: 'triposg',label: 'TripoSG',@@ -344,10 +366,13 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// Free lanes to fall back to per path when the tier's named free engine can't// serve this request — chiefly a photo submission at draft/standard (NVIDIA's-// hosted preview is text-only), which routes to the free HuggingFace Spaces lane-// instead of a paid engine. First configured + capable lane wins.+// hosted preview is text-only), which routes to a free reconstruct lane instead+// of a paid engine. First configured + capable lane wins: our self-hosted TRELLIS+// worker (native single-hop image→3D) is preferred when MODEL_TRELLIS_URL is set,+// otherwise the free HuggingFace Spaces lane. Both are env-gated, so the list+// degrades cleanly on deployments that configure only one of them.export const FREE_FALLBACK_FOR_PATH = Object.freeze({- image: Object.freeze(['huggingface']),+ image: Object.freeze(['trellis_selfhost', 'huggingface']),});// Whether a free lane can serve this (path, userImages) request right now: itdiff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 6cc656a2a..9f91992d8 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -8,6 +8,10 @@// reconstruct → GCP_RECONSTRUCTION_URL (avatar-pipeline-controller)// POST /reconstruct → { job_id } GET /jobs/:id → { status, glb_url }//+// trellis → MODEL_TRELLIS_URL (workers/model-trellis)+// Native single-image→3D via Microsoft TRELLIS. Standard task+// shape: POST /infer → { task_id } GET /tasks/:id → result_gcs_url.+//// remesh → GCP_REMESH_URL (workers/remesh)// stylize → GCP_STYLIZE_URL (workers/stylize)// retex → GCP_TEXTURE_URL (workers/texture)@@ -69,6 +73,12 @@ function serviceUrlForMode(mode) {return readEnv('GCP_SEGMENT_URL');case 'sketch':return readEnv('GCP_TRIPOSG_URL');+ case 'trellis':+ // Self-hosted Microsoft TRELLIS image→3D worker (workers/model-trellis):+ // native single-image reconstruction, no FLUX intermediate. Distinct from+ // the avatar pipeline's `reconstruct` (face-only, /reconstruct + /jobs/:id);+ // this worker speaks the standard /infer + /tasks/:id task shape.+ return readEnv('MODEL_TRELLIS_URL');case 'text2motion':return readEnv('GCP_TEXT2MOTION_URL');case 'rerig':@@ -102,6 +112,22 @@ function buildWorkerRequest(request) {};}+ if (mode === 'trellis') {+ // Self-hosted TRELLIS image→3D (workers/model-trellis). Reconstructs a+ // textured mesh from the primary reference view — a user photo, or the+ // FLUX-synthesized view for a text prompt. The worker accepts an `images`+ // array (it uses the first view); `body_type` rides along for parity with+ // the shared worker request shape.+ const photos = Array.isArray(params?.images) && params.images.length+ ? params.images+ : [sourceUrl].filter(Boolean);+ return {+ path: '/infer',+ resultKey: 'result_gcs_url',+ body: { images: photos, body_type: params?.bodyType || 'neutral' },+ };+ }+if (mode === 'remesh') {return {path: '/process',@@ -246,6 +272,7 @@ function buildWorkerRequest(request) {// progress indicator on the client side.const MODE_ETA = {reconstruct: 120,+ trellis: 60,remesh: 30,stylize: 25,retex: 180,@@ -340,7 +367,7 @@ export function createRegenProvider({ reconstructUrl } = {}) {// Report how the job was conditioned. For reconstruct the worker fuses// every image in the body; other modes are single-source.const viewsUsed =- mode === 'reconstruct' && Array.isArray(workerReq.body.images)+ (mode === 'reconstruct' || mode === 'trellis') && Array.isArray(workerReq.body.images)? workerReq.body.images.length: 0;diff --git a/api/forge.js b/api/forge.jsindex ac51f4ec3..8ef582286 100644--- a/api/forge.js+++ b/api/forge.js@@ -1063,6 +1063,11 @@ async function startJob(req, res) {// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.+ } else if (backendId === 'trellis_selfhost') {+ // Driven by the dedicated self-host TRELLIS lane below, which builds+ // its own GCP provider. Same reasoning as huggingface — never build a+ // Replicate client here, or a deployment without REPLICATE_API_TOKEN+ // would 503 on an explicitly-chosen free self-hosted engine.} else {provider = createRegenProvider();}@@ -1132,6 +1137,84 @@ async function startJob(req, res) {// fall through to a paid lane: that would spend credits the user// deliberately opted out of. So we run the free Spaces and, if every one is// busy/down, return a designed error the UI can act on (retry / switch engine).+ //+ // Self-hosted TRELLIS image-to-3D lane (platform-keyed; native single-hop).+ // Our own Microsoft TRELLIS worker (workers/model-trellis) reconstructs a+ // textured mesh DIRECTLY from the primary reference view -- the user's photo,+ // or the FLUX-synthesized view for a text prompt -- with no vendor cost. This+ // is the native single-hop image-to-3D NVIDIA's hosted preview can't do (it+ // rejects user images); a self-deployed NIM accepts them. Async like the+ // sketch lane: returns a poll token that routes back through the gcp provider's+ // status(). Reached on an explicit pick OR as the preferred free image lane+ // (FREE_FALLBACK_FOR_PATH) when MODEL_TRELLIS_URL is configured.+ if (backendId === 'trellis_selfhost') {+ let gcp;+ try {+ gcp = createGcpProvider();+ } catch {+ return json(res, 501, {+ error: 'backend_unconfigured',+ backend: 'trellis_selfhost',+ message: 'Self-hosted TRELLIS is not configured on this deployment.',+ });+ }++ let job;+ try {+ job = await gcp.submit({+ mode: 'trellis',+ sourceUrl: referenceImageUrl,+ params: { images: views },+ });+ } catch (err) {+ if (err?.code === 'mode_unconfigured') {+ return json(res, 501, {+ error: 'backend_unconfigured',+ backend: 'trellis_selfhost',+ message:+ 'Self-hosted TRELLIS is not configured on this deployment (MODEL_TRELLIS_URL is not set).',+ });+ }+ throw err;+ }++ // Wrap the gcp job envelope in a forge token so polling routes back to the+ // gcp provider -- same idiom as the sketch and Hunyuan3D lanes.+ const token = encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId });+ const clientKey = clientKeyFrom(req);+ const creationId = await createCreation({+ clientKey,+ ipHash: hashIp(ip),+ prompt: prompt || (isImageMode ? 'image-to-3d' : ''),+ aspect: isImageMode ? null : aspect,+ previewImageUrl: referenceImageUrl,+ replicateJobId: job.extJobId,+ textToImageModel: isImageMode ? null : textToImageModel,+ viewsRequested: views.length,+ viewsUsed: job.viewsUsed ?? views.length,+ multiview: views.length > 1,+ backend: backendId,+ tier: tier.id,+ path,+ });++ return json(res, 200, {+ job_id: token,+ creation_id: creationId,+ status: 'queued',+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',+ path,+ tier: tier.id,+ backend: backendId,+ prompt: prompt || null,+ preview_image_url: referenceImageUrl,+ reference_image_urls: isImageMode ? [imageUrls[0]] : [referenceImageUrl],+ text_to_image_model: isImageMode ? null : textToImageModel,+ eta_seconds: estimateEtaSeconds({ backendId, tier }),+ estimated_credits: estimateCredits({ backendId, path, tier }),+ });+ }+if (backendId === 'huggingface') {if (await runHfImageLane({diff --git a/scripts/nvidia-demo-serve.mjs b/scripts/nvidia-demo-serve.mjsnew file mode 100644index 000000000..df54710fd--- /dev/null+++ b/scripts/nvidia-demo-serve.mjs@@ -0,0 +1,39 @@+#!/usr/bin/env node+// Tiny static server for the NVIDIA demo viewer. Serves the viewer HTML and the+// generated GLBs over http so the GLTFLoader fetch works (file:// won't).+//+// node scripts/nvidia-demo-serve.mjs+// → http://localhost:4545/?model=/demo/<slug>.glb&prompt=your%20prompt+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { extname, normalize, join } from 'node:path';++const PORT = process.env.PORT || 4545;+const ROOT = process.cwd();+const TYPES = {+ '.html': 'text/html; charset=utf-8',+ '.glb': 'model/gltf-binary',+ '.gltf': 'model/gltf+json',+ '.js': 'text/javascript',+ '.mjs': 'text/javascript',+ '.json': 'application/json',+};++createServer(async (req, res) => {+ try {+ let path = decodeURIComponent(new URL(req.url, 'http://x').pathname);+ if (path === '/' || path === '') path = '/scripts/nvidia-demo-viewer.html';+ const full = join(ROOT, normalize(path).replace(/^(\.\.[/\\])+/, ''));+ if (!full.startsWith(ROOT)) { res.writeHead(403).end('forbidden'); return; }+ const body = await readFile(full);+ res.writeHead(200, {+ 'content-type': TYPES[extname(full)] || 'application/octet-stream',+ 'access-control-allow-origin': '*',+ 'cache-control': 'no-store',+ }).end(body);+ } catch {+ res.writeHead(404).end('not found');+ }+}).listen(PORT, () => {+ console.log(`Demo viewer → http://localhost:${PORT}/?model=/demo/<slug>.glb`);+});diff --git a/scripts/nvidia-demo-viewer.html b/scripts/nvidia-demo-viewer.htmlnew file mode 100644index 000000000..d9be85c66--- /dev/null+++ b/scripts/nvidia-demo-viewer.html@@ -0,0 +1,114 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>three.ws · NVIDIA TRELLIS demo</title>+<style>+ :root { color-scheme: dark; }+ * { margin: 0; box-sizing: border-box; }+ html, body { height: 100%; overflow: hidden; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; }+ #stage { position: fixed; inset: 0; background: radial-gradient(120% 120% at 50% 20%, #1a2238 0%, #0b0e18 55%, #05060c 100%); }+ canvas { display: block; }+ .badge {+ position: fixed; left: 24px; bottom: 22px; display: flex; align-items: center; gap: 10px;+ padding: 10px 16px; border-radius: 999px; background: rgba(12,16,28,.62); backdrop-filter: blur(10px);+ border: 1px solid rgba(118,185,0,.35); color: #e8edf7; font-size: 14px; letter-spacing: .2px;+ box-shadow: 0 8px 30px rgba(0,0,0,.45); opacity: 0; transition: opacity .6s ease .3s;+ }+ .badge.show { opacity: 1; }+ .dot { width: 9px; height: 9px; border-radius: 50%; background: #76b900; box-shadow: 0 0 10px #76b900; }+ .badge b { color: #76b900; font-weight: 700; }+ .prompt { position: fixed; right: 24px; bottom: 24px; max-width: 46vw; text-align: right; color: #aeb8cc; font-size: 13px; opacity: 0; transition: opacity .6s ease .5s; }+ .prompt.show { opacity: 1; }+ .hint { position: fixed; top: 20px; right: 22px; color: #566; font-size: 12px; opacity:.5; }+ .loading { position: fixed; inset: 0; display: grid; place-items: center; color: #76b900; font-size: 14px; letter-spacing: 2px; }+ .loading.hide { display: none; }+</style>+</head>+<body>+<div id="stage"></div>+<div class="loading" id="loading">GENERATING VIEW…</div>+<div class="badge" id="badge"><span class="dot"></span> image → 3D, <b>rigged & live</b> · NVIDIA TRELLIS</div>+<div class="prompt" id="prompt"></div>+<script type="importmap">+{ "imports": {+ "three": "https://unpkg.com/[email protected]/build/three.module.js",+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"+} }+</script>+<script type="module">+import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++const params = new URLSearchParams(location.search);+const modelUrl = params.get('model');+const promptText = params.get('prompt') || '';+document.getElementById('prompt').textContent = promptText ? `“${promptText}”` : '';++const stage = document.getElementById('stage');+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+renderer.setSize(innerWidth, innerHeight);+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.05;+stage.appendChild(renderer.domElement);++const scene = new THREE.Scene();+const pmrem = new THREE.PMREMGenerator(renderer);+scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.01, 100);+camera.position.set(0, 0.4, 3.2);++const key = new THREE.DirectionalLight(0xffffff, 2.4); key.position.set(3, 5, 4); scene.add(key);+const rim = new THREE.DirectionalLight(0x86b6ff, 1.6); rim.position.set(-4, 2, -4); scene.add(rim);+scene.add(new THREE.AmbientLight(0xffffff, 0.3));++const controls = new OrbitControls(camera, renderer.domElement);+controls.enableDamping = true; controls.dampingFactor = 0.06;+controls.autoRotate = true; controls.autoRotateSpeed = 2.2;+controls.minDistance = 1.2; controls.maxDistance = 8;++function frameObject(obj) {+ const box = new THREE.Box3().setFromObject(obj);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ const maxDim = Math.max(size.x, size.y, size.z) || 1;+ const scale = 1.8 / maxDim;+ obj.scale.setScalar(scale);+ obj.position.sub(center.multiplyScalar(scale));+ obj.position.y += (size.y * scale) * 0.0;+ controls.target.set(0, 0, 0);+}++const loader = new GLTFLoader();+if (modelUrl) {+ loader.load(modelUrl, (gltf) => {+ frameObject(gltf.scene);+ scene.add(gltf.scene);+ document.getElementById('loading').classList.add('hide');+ document.getElementById('badge').classList.add('show');+ document.getElementById('prompt').classList.add('show');+ // Cinematic intro: start tucked behind, sweep around to the front.+ controls.autoRotateSpeed = 6.0;+ setTimeout(() => { controls.autoRotateSpeed = 2.0; }, 2600);+ }, undefined, (err) => {+ document.getElementById('loading').textContent = 'FAILED TO LOAD MODEL';+ console.error(err);+ });+} else {+ document.getElementById('loading').textContent = 'NO ?model= PARAM';+}++addEventListener('resize', () => {+ camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();+ renderer.setSize(innerWidth, innerHeight);+});++renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, camera); });+</script>+</body>+</html>diff --git a/scripts/nvidia-demo.mjs b/scripts/nvidia-demo.mjsnew file mode 100644index 000000000..3d96da780--- /dev/null+++ b/scripts/nvidia-demo.mjs@@ -0,0 +1,119 @@+#!/usr/bin/env node+// Self-contained NVIDIA TRELLIS text→3D demo runner.+//+// Mirrors the verified protocol in api/_providers/nvidia.js but with ZERO repo+// coupling (no env.js, no R2) so it runs anywhere with just the key:+//+// NVIDIA_API_KEY=nvapi-… node scripts/nvidia-demo.mjs "a friendly robot mascot"+//+// Output: writes the GLB to demo/<slug>.glb and prints the path. Point the+// viewer (scripts/nvidia-demo-viewer.html) at it to record the X clip.++const TRELLIS_INVOKE_URL = 'https://ai.api.nvidia.com/v1/genai/microsoft/trellis';+const NVCF_STATUS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/pexec/status';+const NVCF_POLL_SECONDS = 30;+const PROMPT_MAX = 77;+const STYLE_SUFFIX = ', studio lighting';+const STYLE_WORDS = ['studio', 'light', 'bright', 'backlit', 'colorful', 'vibrant', 'cartoon', 'stylized'];++const apiKey = process.env.NVIDIA_API_KEY;+if (!apiKey) {+ console.error('✖ NVIDIA_API_KEY is not set. Run:\n NVIDIA_API_KEY=nvapi-… node scripts/nvidia-demo.mjs "your prompt"');+ process.exit(1);+}++const prompt = process.argv.slice(2).join(' ').trim() || 'a friendly robot mascot, colorful';+const tier = process.env.TIER || 'draft';+const steps = tier === 'high' ? 40 : 15; // hosted preview only completes at 15 reliably++function enhancePrompt(raw) {+ const text = String(raw || '').trim();+ const lower = text.toLowerCase();+ if (STYLE_WORDS.some((w) => lower.includes(w))) return text.slice(0, PROMPT_MAX);+ const maxBase = PROMPT_MAX - STYLE_SUFFIX.length;+ return text.slice(0, maxBase) + STYLE_SUFFIX;+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function extractGlb(res) {+ const ct = (res.headers.get('content-type') || '').toLowerCase();+ if (ct.includes('json')) {+ const data = await res.json().catch(() => null);+ const a0 = data?.artifacts?.[0];+ if (typeof a0 === 'string' && a0 && !a0.startsWith('http')) return Buffer.from(a0, 'base64');+ const inline = a0?.base64 ?? a0?.data ?? (typeof data?.output === 'string' ? data.output : null);+ if (typeof inline === 'string' && !inline.startsWith('http')) return Buffer.from(inline, 'base64');+ const url = a0?.url ?? (typeof inline === 'string' && inline.startsWith('http') ? inline : null);+ if (url) {+ const r = await fetch(url);+ if (r.ok) return Buffer.from(await r.arrayBuffer());+ }+ const arts = data?.artifacts;+ if (arts && typeof arts === 'object' && !Array.isArray(arts)) {+ const v = arts['0'] ?? Object.values(arts)[0];+ const b64 = v?.base64 ?? (typeof v === 'string' && !v.startsWith('http') ? v : null);+ if (b64) return Buffer.from(b64, 'base64');+ }+ throw new Error('No GLB in JSON response: keys=' + JSON.stringify(Object.keys(data || {})));+ }+ if (ct.includes('gltf') || ct.includes('octet-stream') || ct.startsWith('model/') || ct.includes('binary')) {+ return Buffer.from(await res.arrayBuffer());+ }+ throw new Error('Unexpected content-type: ' + ct + ' — ' + (await res.text()).slice(0, 160));+}++async function main() {+ const t0 = Date.now();+ const finalPrompt = enhancePrompt(prompt);+ console.log(`→ TRELLIS text→3D tier=${tier} steps=${steps}\n prompt: "${finalPrompt}"`);++ const res = await fetch(TRELLIS_INVOKE_URL, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${apiKey}`,+ accept: 'application/json',+ 'content-type': 'application/json',+ 'nvcf-poll-seconds': String(NVCF_POLL_SECONDS),+ },+ body: JSON.stringify({+ mode: 'text',+ prompt: finalPrompt,+ ss_sampling_steps: steps,+ slat_sampling_steps: steps,+ output_format: 'glb',+ }),+ });++ let glb;+ if (res.status === 202 || (res.ok && res.headers.get('nvcf-reqid') && !(await res.clone().json().catch(() => ({}))).artifacts?.length)) {+ const reqId = res.headers.get('nvcf-reqid');+ console.log(` queued (NVCF-REQID ${reqId}) — polling…`);+ for (let i = 0; i < 60; i++) {+ await sleep(2500);+ const p = await fetch(`${NVCF_STATUS_URL}/${encodeURIComponent(reqId)}`, {+ headers: { authorization: `Bearer ${apiKey}`, accept: 'application/json' },+ });+ if (p.status === 202) { process.stdout.write('.'); continue; }+ if (p.ok) { glb = await extractGlb(p); process.stdout.write('\n'); break; }+ if (p.status === 401 || p.status === 403) throw new Error('NVIDIA rejected the API key');+ throw new Error(`poll returned ${p.status}: ${(await p.text()).slice(0, 200)}`);+ }+ if (!glb) throw new Error('timed out waiting for TRELLIS');+ } else if (res.ok) {+ glb = await extractGlb(res);+ } else {+ throw new Error(`invoke ${res.status}: ${(await res.text()).slice(0, 300)}`);+ }++ const { mkdir, writeFile } = await import('node:fs/promises');+ const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'model';+ await mkdir('demo', { recursive: true });+ const out = `demo/${slug}.glb`;+ await writeFile(out, glb);+ const secs = ((Date.now() - t0) / 1000).toFixed(1);+ console.log(`✓ ${(glb.length / 1024).toFixed(0)} KB GLB in ${secs}s → ${out}`);+ console.log(`\nView it:\n node scripts/nvidia-demo-serve.mjs\n then open http://localhost:4545/?model=/${out}`);+}++main().catch((e) => { console.error('✖', e.message); process.exit(1); });diff --git a/tests/api/forge-trellis-selfhost.test.js b/tests/api/forge-trellis-selfhost.test.jsnew file mode 100644index 000000000..f4aab3785--- /dev/null+++ b/tests/api/forge-trellis-selfhost.test.js@@ -0,0 +1,189 @@+// Self-hosted TRELLIS image→3D lane — registration, env-gated config, routing+// precedence, and the gcp provider's `trellis` mode wire contract.+//+// This lane wires our own Microsoft TRELLIS worker (workers/model-trellis) into+// /forge as a NATIVE single-hop image→3D engine: image → TRELLIS → GLB, no FLUX+// intermediate, no vendor cost. Unlike NVIDIA's hosted preview (text-only), a+// self-deployed NIM accepts real user photos, so this is the preferred free image+// lane when MODEL_TRELLIS_URL is configured. The worker speaks the standard task+// shape (POST /infer → GET /tasks/:id → result_gcs_url), distinct from the avatar+// pipeline's face-only `reconstruct` (/reconstruct + /jobs/:id).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ BACKENDS,+ resolveBackendId,+ backendIsConfigured,+ buildCatalog,+} from '../../api/_lib/forge-tiers.js';+import { createRegenProvider } from '../../api/_providers/gcp.js';++const VARS = [+ 'MODEL_TRELLIS_URL',+ 'GCP_RECONSTRUCTION_KEY',+ 'NVIDIA_API_KEY',+ 'HF_TOKEN',+];+const saved = {};+const ORIGINAL_FETCH = globalThis.fetch;++beforeEach(() => {+ for (const v of VARS) {+ saved[v] = process.env[v];+ delete process.env[v];+ }+});+afterEach(() => {+ for (const v of VARS) {+ if (saved[v] === undefined) delete process.env[v];+ else process.env[v] = saved[v];+ }+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++describe('forge-tiers — self-hosted TRELLIS backend registration', () => {+ it('registers a free, platform-keyed image backend that accepts user photos', () => {+ const b = BACKENDS.trellis_selfhost;+ expect(b).toBeTruthy();+ expect(b.provider).toBe('gcp');+ expect(b.byok).toBe(false);+ expect(b.paths).toEqual(['image']);+ expect(b.requiresEnv).toEqual(['MODEL_TRELLIS_URL', 'GCP_RECONSTRUCTION_KEY']);+ expect(b.free).toBe(true);+ expect(b.userImages).toBe(true);+ expect(b.credits).toBeNull();+ expect(b.baseEta).toBeGreaterThan(0);+ });++ it('is configured only when BOTH the worker URL and the shared key are present', () => {+ expect(backendIsConfigured('trellis_selfhost')).toBe(false);+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ expect(backendIsConfigured('trellis_selfhost')).toBe(false); // key still missing+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(backendIsConfigured('trellis_selfhost')).toBe(true);+ });++ it('surfaces in the catalog as a free, photo-capable, selectable engine', () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ const b = buildCatalog().backends.find((x) => x.id === 'trellis_selfhost');+ expect(b).toBeTruthy();+ expect(b.free).toBe(true);+ expect(b.user_images).toBe(true);+ expect(b.byok).toBeNull();+ expect(b.configured).toBe(true);+ const est = b.estimates.image.find((e) => e.tier === 'standard');+ expect(est.eta_seconds).toBeGreaterThan(0);+ expect(est.credits).toBeNull();+ });+});++describe('forge-tiers — self-hosted TRELLIS routing precedence', () => {+ it('becomes the preferred free image lane for photo submissions when configured', () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.HF_TOKEN = 'hf_test'; // HF also live — TRELLIS must still win the photo default+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ // Draft/standard photo uploads route to our self-hosted TRELLIS, ahead of HF.+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis_selfhost');+ });++ it('does not disturb the native text→3D default (NVIDIA) or the high-tier textured engine', () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.HF_TOKEN = 'hf_test';+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ // Text prompts at draft/standard still get NVIDIA's native single-hop lane.+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false })).toBe('nvidia');+ // High tier keeps the higher-fidelity textured HuggingFace engine.+ expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('huggingface');+ });++ it('degrades cleanly to HuggingFace when the worker URL is absent', () => {+ // No MODEL_TRELLIS_URL → trellis_selfhost unconfigured → HF serves photos.+ process.env.HF_TOKEN = 'hf_test';+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('huggingface');+ });++ it('stays explicitly selectable (the handler owns any rejection)', () => {+ // Even unconfigured, an explicit pick is honored at resolution time.+ expect(+ resolveBackendId({ path: 'image', tier: 'standard', backend: 'trellis_selfhost', userImages: true }),+ ).toBe('trellis_selfhost');+ });+});++describe('gcp provider — trellis mode wire contract', () => {+ it('submits image→3D to the worker /infer endpoint and packs a pollable job', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';++ const fetchMock = vi.fn(async (url, opts) => {+ expect(url).toBe('https://trellis.example.run.app/infer');+ const body = JSON.parse(opts.body);+ expect(body.images).toEqual(['https://cdn.three.ws/photo.png']);+ expect(body.body_type).toBe('neutral');+ expect(opts.headers.authorization).toBe('Bearer secret');+ return new Response(JSON.stringify({ task_id: 'task-123', status: 'queued' }), {+ status: 202,+ headers: { 'content-type': 'application/json' },+ });+ });+ globalThis.fetch = fetchMock;++ const provider = createRegenProvider();+ const submitted = await provider.submit({+ mode: 'trellis',+ sourceUrl: 'https://cdn.three.ws/photo.png',+ params: { images: ['https://cdn.three.ws/photo.png'] },+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(submitted.extJobId).toBeTruthy();+ expect(submitted.backend).toBe('gcp');+ expect(submitted.viewsUsed).toBe(1);+ expect(submitted.eta).toBeGreaterThan(0);+ });++ it('polls /tasks/:id and surfaces result_gcs_url as the GLB url on done', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';++ // First call: submit (202 + task_id). Second call: poll (200 + done).+ const calls = [];+ globalThis.fetch = vi.fn(async (url) => {+ calls.push(url);+ if (url.endsWith('/infer')) {+ return new Response(JSON.stringify({ task_id: 'task-xyz', status: 'queued' }), {+ status: 202,+ headers: { 'content-type': 'application/json' },+ });+ }+ // poll+ expect(url).toBe('https://trellis.example.run.app/tasks/task-xyz');+ return new Response(+ JSON.stringify({+ task_id: 'task-xyz',+ status: 'done',+ result_gcs_url: 'https://storage.googleapis.com/bucket/raw-meshes/trellis/task-xyz.glb',+ }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ );+ });++ const provider = createRegenProvider();+ const submitted = await provider.submit({+ mode: 'trellis',+ sourceUrl: 'https://cdn.three.ws/photo.png',+ params: { images: ['https://cdn.three.ws/photo.png'] },+ });+ const status = await provider.status(submitted.extJobId);+ expect(status.status).toBe('done');+ expect(status.resultGlbUrl).toBe(+ 'https://storage.googleapis.com/bucket/raw-meshes/trellis/task-xyz.glb',+ );+ });+});