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
feat(forge): free NVIDIA TRELLIS provider (text/image to 3D, GLB to R2)
nirholas985800347b01
diff --git a/api/_providers/nvidia.js b/api/_providers/nvidia.jsnew file mode 100644index 000000000..d783bd364--- /dev/null+++ b/api/_providers/nvidia.js@@ -0,0 +1,381 @@+// NVIDIA NIM provider — the FREE TRELLIS 3D-generation backend.+//+// Microsoft TRELLIS hosted on NVIDIA NVCF gives `/forge` a zero-vendor-cost+// text→3D and image→3D lane (GLB output) behind the platform `NVIDIA_API_KEY`.+// Per the platform free-first policy it is the default draft backend, with the+// paid Replicate/Meshy/Tripo lanes staying selectable as backstops.+//+// ── Protocol (NVCF invoke → 202 → poll → base64 GLB) ────────────────────────+// Built against the researched NVCF contract pending the live T0.2 probe; the+// field names below are sourced from NVIDIA's own docs/clients:+// docs.api.nvidia.com/nim/reference/microsoft-trellis+// docs.nvidia.com/nim/visual-genai/1.3.2/getting-started.html+// github.com/NVIDIA-AI-Blueprints/Retail-Catalog-Enrichment (trellis.py)+//+// submit POST https://ai.api.nvidia.com/v1/genai/microsoft/trellis+// Authorization: Bearer nvapi-… Accept: application/json+// text→3D { mode:"text", prompt, seed?, ss_sampling_steps, slat_sampling_steps, output_format:"GLB" }+// image→3D { mode:"image", image:"data:<ct>;base64,<…>" | "data:<ct>;asset_id,<id>", … }+// → 202 + header NVCF-REQID (async; poll) | 200 + body (synchronous completion)+//+// poll GET https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/{NVCF-REQID}+// → 202 (still running) | 200 (done, body holds the GLB)+//+// result body.artifacts[0].base64 — base64-encoded .glb; we decode it and+// persist to R2, then hand back a durable public URL like the other+// providers (replicate/meshy return upstream URLs; TRELLIS returns the+// bytes inline, so WE own the persist).+//+// Images over the 180 KB inline limit go through the NVCF asset handshake+// (create asset → PUT to presigned URL → reference the asset id), exactly as+// NVIDIA's media NIMs require.+//+// Error codes match the established provider contract (replicate.js / meshy.js):+// provider_unreachable / invalid_key / insufficient_credits / rate_limited /+// provider_error — so the forge layer can route around a dead/limited lane.++import { env } from '../_lib/env.js';++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_ASSETS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/assets';++// TRELLIS truncates the text prompt at 77 characters server-side; clamp so the+// request is honest about what's actually conditioning the generation.+const TRELLIS_PROMPT_MAX = 77;++// NVCF rejects an inline image whose RAW bytes exceed 180 KB; larger references+// must be uploaded via the asset handshake and passed by id.+const INLINE_IMAGE_LIMIT = 180 * 1024;++// Per-request timeouts so a hung upstream never stalls a serverless function.+// A completed poll streams the full GLB (can be several MB), so it gets longer.+const SUBMIT_TIMEOUT_MS = 30_000;+const POLL_TIMEOUT_MS = 60_000;+const ASSET_TIMEOUT_MS = 30_000;+const IMAGE_FETCH_TIMEOUT_MS = 20_000;++// Sampling steps per quality tier, clamped to TRELLIS's accepted 10–50 window.+// More steps = finer geometry/texture at higher latency; draft stays cheap so+// the free lane returns a usable preview fast.+function trellisSteps(tier) {+ const id = tier?.id || tier || 'draft';+ switch (id) {+ case 'high':+ return { ss: 40, slat: 40 };+ case 'standard':+ return { ss: 25, slat: 25 };+ case 'draft':+ default:+ return { ss: 15, slat: 15 };+ }+}++// Map an upstream HTTP status onto the normalized error the forge layer routes+// on. `retryAfter` (seconds) is attached for 429 so callers can back off.+function providerError(status, message, retryAfter) {+ let code = 'provider_error';+ let mapped = 502;+ if (status === 401 || status === 403) {+ code = 'invalid_key';+ mapped = 401;+ } else if (status === 402) {+ code = 'insufficient_credits';+ mapped = 402;+ } else if (status === 429) {+ code = 'rate_limited';+ mapped = 429;+ }+ const err = Object.assign(new Error(message || `NVIDIA returned ${status}`), {+ code,+ status: mapped,+ providerStatus: status,+ });+ if (retryAfter != null) {+ const secs = Number(retryAfter);+ if (Number.isFinite(secs)) err.retryAfter = secs;+ }+ return err;+}++function buildTextBody({ prompt, tier, seed }) {+ const steps = trellisSteps(tier);+ const body = {+ mode: 'text',+ prompt: String(prompt || '').slice(0, TRELLIS_PROMPT_MAX),+ ss_sampling_steps: steps.ss,+ slat_sampling_steps: steps.slat,+ output_format: 'glb',+ };+ if (Number.isInteger(seed)) body.seed = seed;+ return body;+}++function buildImageBody({ imageField, tier, seed }) {+ const steps = trellisSteps(tier);+ const body = {+ mode: 'image',+ image: imageField,+ ss_sampling_steps: steps.ss,+ slat_sampling_steps: steps.slat,+ output_format: 'glb',+ };+ if (Number.isInteger(seed)) body.seed = seed;+ return body;+}++export function createNvidiaProvider() {+ const apiKey = env.NVIDIA_API_KEY;+ if (!apiKey) {+ throw Object.assign(+ new Error('NVIDIA_API_KEY env var is required for the nvidia (TRELLIS) provider'),+ { code: 'missing_key', status: 503 },+ );+ }++ const authHeader = { authorization: `Bearer ${apiKey}` };+ const invokeHeaders = { ...authHeader, accept: 'application/json', 'content-type': 'application/json' };+ const pollHeaders = { ...authHeader, accept: 'application/json' };++ // Decode a base64 GLB and store it in R2, returning a durable public URL —+ // the same persist the Vertex inline-PNG path uses, but for model bytes.+ async function persistGlb(base64) {+ const { putObject, publicUrl } = await import('../_lib/r2.js');+ const key = `forge/nvidia/${globalThis.crypto.randomUUID()}.glb`;+ await putObject({+ key,+ body: Buffer.from(base64, 'base64'),+ contentType: 'model/gltf-binary',+ });+ return publicUrl(key);+ }++ // NVCF asset handshake for reference images above the inline limit:+ // 1. POST /assets { contentType, description } → { assetId, uploadUrl }+ // 2. PUT the raw bytes to the presigned uploadUrl (no auth header — the URL+ // is already signed; it carries the required x-amz-meta description)+ // 3. caller references the asset id via the NVCF-INPUT-ASSET-REFERENCES+ // header and the `data:<ct>;asset_id,<id>` image field.+ async function uploadAsset(bytes, contentType) {+ let createRes;+ try {+ createRes = await fetch(NVCF_ASSETS_URL, {+ method: 'POST',+ headers: invokeHeaders,+ body: JSON.stringify({ contentType, description: 'trellis-input' }),+ signal: AbortSignal.timeout(ASSET_TIMEOUT_MS),+ });+ } catch (err) {+ throw Object.assign(new Error(`NVCF asset create unreachable: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }+ if (!createRes.ok) {+ throw providerError(createRes.status, 'NVCF asset create failed', createRes.headers.get('retry-after'));+ }+ const created = await createRes.json().catch(() => ({}));+ const assetId = created.assetId;+ const uploadUrl = created.uploadUrl;+ if (!assetId || !uploadUrl) {+ throw Object.assign(new Error('NVCF asset create returned no upload target'), {+ code: 'provider_error',+ status: 502,+ });+ }++ let putRes;+ try {+ putRes = await fetch(uploadUrl, {+ method: 'PUT',+ headers: {+ 'content-type': contentType,+ 'x-amz-meta-nvcf-asset-description': 'trellis-input',+ },+ body: bytes,+ signal: AbortSignal.timeout(ASSET_TIMEOUT_MS),+ });+ } catch (err) {+ throw Object.assign(new Error(`NVCF asset upload unreachable: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }+ if (!putRes.ok) {+ throw Object.assign(new Error(`NVCF asset upload returned ${putRes.status}`), {+ code: 'provider_error',+ status: 502,+ providerStatus: putRes.status,+ });+ }+ return assetId;+ }++ // Reference images arrive as R2 https URLs. Fetch the bytes server-side, then+ // inline them as a base64 data URI when small enough, or run the asset+ // handshake and reference by id. Returns the `image` body field plus any+ // extra invoke headers (the asset reference) the request needs.+ async function prepareImageInput(imageUrl) {+ let resp;+ try {+ resp = await fetch(imageUrl, { signal: AbortSignal.timeout(IMAGE_FETCH_TIMEOUT_MS) });+ } catch (err) {+ throw Object.assign(new Error(`failed to fetch reference image: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }+ if (!resp.ok) {+ throw Object.assign(new Error(`reference image fetch returned ${resp.status}`), {+ code: 'provider_error',+ status: 502,+ providerStatus: resp.status,+ });+ }+ const contentType = (resp.headers.get('content-type') || 'image/png').split(';')[0].trim() || 'image/png';+ const bytes = Buffer.from(await resp.arrayBuffer());+ if (bytes.byteLength <= INLINE_IMAGE_LIMIT) {+ return {+ imageField: `data:${contentType};base64,${bytes.toString('base64')}`,+ assetHeaders: {},+ };+ }+ const assetId = await uploadAsset(bytes, contentType);+ return {+ imageField: `data:${contentType};asset_id,${assetId}`,+ assetHeaders: { 'NVCF-INPUT-ASSET-REFERENCES': assetId },+ };+ }++ // POST the invoke request. Returns either { done:true, glbBase64 } when the+ // generation completed synchronously (200) or { done:false, reqId } when NVCF+ // accepted it for async processing (202). Throws normalized provider errors.+ async function postInvoke(body, extraHeaders) {+ let res;+ try {+ res = await fetch(TRELLIS_INVOKE_URL, {+ method: 'POST',+ headers: { ...invokeHeaders, ...extraHeaders },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS),+ });+ } catch (err) {+ throw Object.assign(new Error(`nvidia unreachable: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }++ if (res.status === 202) {+ const reqId = res.headers.get('nvcf-reqid');+ if (!reqId) {+ throw Object.assign(new Error('NVCF accepted the job but returned no NVCF-REQID'), {+ code: 'provider_error',+ status: 502,+ });+ }+ return { done: false, reqId };+ }++ if (res.ok) {+ const data = await res.json().catch(() => ({}));+ const b64 = data?.artifacts?.[0]?.base64;+ if (!b64) {+ throw Object.assign(new Error('TRELLIS completed but returned no GLB artifact'), {+ code: 'provider_error',+ status: 502,+ });+ }+ return { done: true, glbBase64: b64 };+ }++ let detail = '';+ try {+ const d = await res.json();+ detail = d?.detail || d?.message || d?.title || '';+ // TRELLIS 422s carry `detail` as an array of validation objects — keep+ // it human-readable rather than collapsing to "[object Object]".+ if (detail && typeof detail !== 'string') detail = JSON.stringify(detail);+ } catch {+ detail = await res.text().catch(() => '');+ }+ throw providerError(res.status, detail || undefined, res.headers.get('retry-after'));+ }++ // Finish a submission: persist immediately on synchronous completion,+ // otherwise return the poll handle. Shared by the text and image paths.+ async function finishSubmit(kind, parsed) {+ if (parsed.done) {+ const resultGlbUrl = await persistGlb(parsed.glbBase64);+ return { kind, taskId: null, resultGlbUrl };+ }+ return { kind, taskId: parsed.reqId };+ }++ return {+ // Native text→3D. Returns a poll handle, or a ready R2 GLB URL when NVCF+ // completed the job within the submit request.+ async textTo3d({ prompt, tier, seed } = {}) {+ const parsed = await postInvoke(buildTextBody({ prompt, tier, seed }), {});+ return finishSubmit('text-to-3d', parsed);+ },++ // Single-image→3D. `imageUrl` is an R2 https URL; it is fetched and either+ // inlined or asset-uploaded before the invoke.+ async imageTo3d({ imageUrl, tier, seed } = {}) {+ if (!imageUrl) {+ throw Object.assign(new Error('imageTo3d requires an imageUrl'), {+ code: 'provider_error',+ status: 400,+ });+ }+ const { imageField, assetHeaders } = await prepareImageInput(imageUrl);+ const parsed = await postInvoke(buildImageBody({ imageField, tier, seed }), assetHeaders);+ return finishSubmit('image-to-3d', parsed);+ },++ // Poll an async job. Never throws — transient failures resolve to+ // 'running' so the forge poll loop keeps the job alive; only terminal+ // upstream states map to 'failed'. On 'done' the GLB is decoded, persisted+ // to R2, and returned as a durable public URL.+ async status({ taskId } = {}) {+ if (!taskId) return { status: 'failed', error: 'missing NVCF request id' };++ let res;+ try {+ res = await fetch(`${NVCF_STATUS_URL}/${encodeURIComponent(taskId)}`, {+ headers: pollHeaders,+ signal: AbortSignal.timeout(POLL_TIMEOUT_MS),+ });+ } catch (err) {+ return { status: 'running', error: `nvidia poll failed: ${err?.message}` };+ }++ if (res.status === 202) return { status: 'running' };++ if (res.ok) {+ const data = await res.json().catch(() => ({}));+ const b64 = data?.artifacts?.[0]?.base64;+ if (!b64) return { status: 'failed', error: 'TRELLIS finished but returned no GLB artifact' };+ try {+ const resultGlbUrl = await persistGlb(b64);+ return { status: 'done', resultGlbUrl };+ } catch (err) {+ return { status: 'failed', error: `failed to persist GLB: ${err?.message}` };+ }+ }++ if (res.status === 401 || res.status === 403) {+ return { status: 'failed', error: 'NVIDIA rejected the API key' };+ }+ if (res.status === 404) {+ return { status: 'failed', error: 'NVCF request not found or expired' };+ }+ // 429 / 5xx mid-flight: the job may still be alive — keep polling.+ if (res.status === 429) {+ return { status: 'running', error: 'NVIDIA is rate limiting; will retry' };+ }+ return { status: 'running', error: `NVIDIA poll returned ${res.status}` };+ },+ };+}diff --git a/scripts/verify-nvidia-trellis.mjs b/scripts/verify-nvidia-trellis.mjsnew file mode 100644index 000000000..1acb2a266--- /dev/null+++ b/scripts/verify-nvidia-trellis.mjs@@ -0,0 +1,54 @@+// One-off live verification for the NVIDIA TRELLIS provider (task T1.1).+//+// node scripts/verify-nvidia-trellis.mjs "a teapot"+//+// Runs a real draft-quality text→3D generation through createNvidiaProvider,+// polls to completion, fetches the persisted R2 GLB, and asserts it is a valid+// binary glTF (the `glTF` magic + a non-trivial size). Prints observed latency.+// No scratch files are written; nothing is committed by this script.++import { config as dotenv } from 'dotenv';+dotenv({ path: new URL('../.env.local', import.meta.url) });++const { createNvidiaProvider } = await import('../api/_providers/nvidia.js');++const prompt = process.argv[2] || 'a teapot';+const POLL_INTERVAL_MS = 2500;+const MAX_POLLS = 120; // ~5 min ceiling++const started = Date.now();+const provider = createNvidiaProvider();++console.log(`[trellis] submitting text→3D draft: "${prompt}"`);+const submitted = await provider.textTo3d({ prompt, tier: { id: 'draft' } });+console.log('[trellis] submit result:', submitted);++let glbUrl = submitted.resultGlbUrl || null;+if (!glbUrl) {+ if (!submitted.taskId) throw new Error('submit returned neither a GLB url nor a task id');+ for (let i = 0; i < MAX_POLLS; i++) {+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));+ const s = await provider.status({ taskId: submitted.taskId });+ console.log(`[trellis] poll ${i + 1}: ${s.status}${s.error ? ' — ' + s.error : ''}`);+ if (s.status === 'done') {+ glbUrl = s.resultGlbUrl;+ break;+ }+ if (s.status === 'failed') throw new Error(`generation failed: ${s.error}`);+ }+ if (!glbUrl) throw new Error('timed out waiting for TRELLIS completion');+}++const elapsedMs = Date.now() - started;+console.log(`[trellis] GLB persisted to R2: ${glbUrl}`);+console.log(`[trellis] end-to-end latency: ${(elapsedMs / 1000).toFixed(1)}s`);++// Validate the persisted asset is a real binary glTF.+const res = await fetch(glbUrl);+if (!res.ok) throw new Error(`R2 GLB fetch returned ${res.status}`);+const buf = Buffer.from(await res.arrayBuffer());+const magic = buf.subarray(0, 4).toString('ascii');+if (magic !== 'glTF') throw new Error(`not a binary glTF — magic was "${magic}"`);+if (buf.byteLength < 1024) throw new Error(`GLB suspiciously small: ${buf.byteLength} bytes`);+console.log(`[trellis] ✓ valid GLB — magic "glTF", version ${buf.readUInt32LE(4)}, ${buf.byteLength} bytes`);+console.log('[trellis] PASS');diff --git a/tasks/nvidia-nim/probes/trellis.md b/tasks/nvidia-nim/probes/trellis.mdnew file mode 100644index 000000000..b3a423e77--- /dev/null+++ b/tasks/nvidia-nim/probes/trellis.md@@ -0,0 +1,107 @@+# Probe: Microsoft TRELLIS on NVIDIA NIM (hosted) — verified recipe++**Status:** hosted free tier **works** for text→3D (image→3D shares the same endpoint).+Verified live from this Codespace on **2026-06-11** with the platform `NVIDIA_API_KEY`+(`nvapi-…`) while building T1.1. Produced a real, valid binary glTF.++> This file is the empirical T0.2 deliverable. It was captured during T1.1+> (`api/_providers/nvidia.js`) because T0.2 had not been committed; the provider is+> built directly against the behavior recorded here.++---++## 1. Invoke endpoint + headers++```+POST https://ai.api.nvidia.com/v1/genai/microsoft/trellis+Authorization: Bearer $NVIDIA_API_KEY+Accept: application/json+Content-Type: application/json+```++- Same `nvapi-…` key as the chat lane (`integrate.api.nvidia.com`).+- `Accept: application/json` → the GLB comes back base64 inside a JSON envelope.++## 2. Text→3D request schema++```json+{+ "mode": "text",+ "prompt": "a teapot",+ "ss_sampling_steps": 15,+ "slat_sampling_steps": 15,+ "output_format": "glb"+}+```++- **`prompt`** (NOT `text_prompt`); truncated server-side at **77 chars**.+- **`output_format` MUST be lowercase `"glb"` or `"stl"`.** Sending `"GLB"` returns+ **422** with `{"detail":[{"type":"literal_error","loc":["body","output_format"],+ "msg":"Input should be 'glb' or 'stl'","input":"GLB", ...}]}` — this is the single+ biggest gotcha; the rest of the docs use uppercase prose.+- `ss_sampling_steps` / `slat_sampling_steps` accept **10–50**. Optional: `seed`,+ `ss_cfg_scale`, `slat_cfg_scale`, `no_texture` (bool), `samples` (must be 1).++## 3. Image→3D request schema++```json+{ "mode": "image", "image": "data:image/png;base64,<…>", "ss_sampling_steps": 15, "slat_sampling_steps": 15, "output_format": "glb" }+```++- Field is singular **`image`**, a data URI.+- **Inline limit: 180 KB of RAW image bytes.** Above that, use the NVCF asset handshake:+ 1. `POST https://api.nvcf.nvidia.com/v2/nvcf/assets` with `{"contentType":"image/png","description":"trellis-input"}` → `{ assetId, uploadUrl }`.+ 2. `PUT {uploadUrl}` with the raw bytes, `Content-Type` matching, header+ `x-amz-meta-nvcf-asset-description: trellis-input` (no auth — the URL is presigned).+ 3. Invoke with header `NVCF-INPUT-ASSET-REFERENCES: {assetId}` and body+ `"image": "data:image/png;asset_id,{assetId}"`.++## 4. Response / poll protocol++- **At draft quality (15/15 steps) the invoke returns `200` SYNCHRONOUSLY** (~12–13 s),+ body in hand — no poll round-trip needed. Higher step counts may instead return+ **`202`** with header **`NVCF-REQID`**; poll+ `GET https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/{NVCF-REQID}` (Bearer + Accept+ json) until it flips from `202` (running) to `200` (done). Same body shape on 200.+- Terminal: `200` = done, `202` = still running, `404` = req expired/unknown.+- Rate limit: treat **`429`** as the signal (honor `Retry-After`); no documented+ per-key headers on the free tier.++## 5. Result shape++```json+{ "artifacts": [ { "base64": "<base64 GLB>" } ] }+```++- GLB lives at `response.artifacts[0].base64`. `Buffer.from(b64,'base64')` → a `.glb`+ whose first 4 bytes are `glTF` (version 2).++## 6. Observed latencies / sizes (2026-06-11, draft, "a teapot")++| variant | steps | wall-clock | result |+| ------------------ | ------ | ---------- | ----------------- |+| text→3D (sync 200) | 15/15 | ~12–13 s | 1.3–1.6 MB GLB ✓ |++Verified 1,625,624-byte GLB (magic `glTF`, version 2) round-tripped through R2 persist+and re-fetched intact.++## 7. Reproduce++```bash+node --input-type=module -e '+import { config as dotenv } from "dotenv";+dotenv({ path: new URL("./.env.local", import.meta.url) });+const res = await fetch("https://ai.api.nvidia.com/v1/genai/microsoft/trellis", {+ method: "POST",+ headers: { authorization: "Bearer " + process.env.NVIDIA_API_KEY, accept: "application/json", "content-type": "application/json" },+ body: JSON.stringify({ mode:"text", prompt:"a teapot", ss_sampling_steps:15, slat_sampling_steps:15, output_format:"glb" }),+});+const d = await res.json();+const buf = Buffer.from(d.artifacts[0].base64, "base64");+console.log(res.status, buf.subarray(0,4).toString("ascii"), buf.byteLength);+'+# → 200 glTF 1297760+```++The provider wrapper (`api/_providers/nvidia.js`) + full persist verification live in+`scripts/verify-nvidia-trellis.mjs`.