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
Refactor code structure for improved readability and maintainability
nirholas57737a4879eb
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 5c68a9a48..496d92e55 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -73,7 +73,7 @@ bottom.| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html`, [agent-native-3d/](examples/agent-native-3d) (below) || Agent-native 3D + embeddable distribution | MCP tool [api/_mcp/tools/agents.js](api/_mcp/tools/agents.js) (`attach_avatar_to_agent`); shared oEmbed provider [api/agent-oembed.js](api/agent-oembed.js) `→ /api/oembed` + builder [api/_lib/embed.js](api/_lib/embed.js) (`forgeEmbedTarget`, shared by `get_embed_code` in [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js)); Forge share page oEmbed discovery [api/forge-share.js](api/forge-share.js) `→ /forge/share/:id`; distribution snippet builders [src/forge-embed-snippets.js](src/forge-embed-snippets.js) + panel [src/forge-embed-panel.js](src/forge-embed-panel.js); autonomous demo [examples/agent-native-3d/](examples/agent-native-3d) | In-repo | Closes the loop: create → own → discover/remix → **use everywhere**. `attach_avatar_to_agent` gives a registered agent identity a persistent body (chains into `register_agent` for on-chain identity + `anchor_provenance` for a signed authenticity credential). Any Forge creation now unfurls via real oEmbed (paste `/forge/share/:id` into Notion/Discord/Slack) with the same `type:rich` iframe payload `get_embed_code` returns via MCP. The Forge "Embed this model" panel hands out five real distribution flavours from one GLB — iframe, `<model-viewer>`, `<agent-3d>`, a `@three-ws/page-agent` talking guide, and a `@three-ws/walk` companion — all built from one shared, pure snippet module so every surface stays byte-identical. `examples/agent-native-3d/run.mjs` drives the full agent-native chain live against `/api/mcp-studio` (mesh_forge → rig_mesh → create_agent_persona → persona_say → get_agent_persona → every distribution snippet) with zero mocks and a documented, logged fallback if the shared free-tier generation lane is rate-limited at run time. Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#share-routes-on-chain-agents). Docs: [docs/mcp.md#attach_avatar_to_agent](docs/mcp.md#attach_avatar_to_agent). Roadmap prompt 10 (closes the roadmap campaign). || Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) |-| Self-hosted 3D GPU fleet (the engines behind the Forge) | [workers/model-trellis/](workers/model-trellis), [workers/model-hunyuan3d/](workers/model-hunyuan3d) (2.0 + 2.1 PBR + 2.1 RTX), [workers/model-triposg/](workers/model-triposg), [workers/model-triposr/](workers/model-triposr), [workers/unirig/](workers/unirig), [workers/avatar-reconstruction/](workers/avatar-reconstruction), CPU stages [workers/rembg/](workers/rembg) · [workers/remesh/](workers/remesh) · [workers/segment/](workers/segment) · [workers/stylize/](workers/stylize) | Live · Cloud Run GPU (us-central1 + trellis/hunyuan replicas in us-east4) | Every generation engine the Forge dispatches to, each with its own `cloudbuild.yaml`. L4 services share a 3-GPU regional quota (increase to 16 pending); the Hunyuan3D-2.1 PBR realism lane also ships an RTX PRO 6000 build (`model-hunyuan3d-21-rtx`, quota granted 1000) as the warm primary. Ops map: [docs/ops/gcp-credits-plan.md](docs/ops/gcp-credits-plan.md) |+| Self-hosted 3D GPU fleet (the engines behind the Forge) | [workers/model-trellis/](workers/model-trellis), [workers/model-hunyuan3d/](workers/model-hunyuan3d) (2.0 + 2.1 PBR + 2.1 RTX), [workers/model-triposg/](workers/model-triposg), [workers/model-triposr/](workers/model-triposr), [workers/model-text2motion/](workers/model-text2motion), [workers/rig/](workers/rig) (auto-rigging, supersedes the deprecated [workers/unirig/](workers/unirig)), [workers/avatar-reconstruction/](workers/avatar-reconstruction), CPU stages [workers/rembg/](workers/rembg) · [workers/remesh/](workers/remesh) · [workers/segment/](workers/segment) · [workers/stylize/](workers/stylize) | Live · Cloud Run GPU (us-central1 + trellis/hunyuan replicas in us-east4) | Every generation engine the Forge dispatches to, each with its own `cloudbuild.yaml`. L4 services share a 3-GPU regional quota (increase to 16 filed 2026-07-16, still reconciling); the Hunyuan3D-2.1 PBR realism lane also ships an RTX PRO 6000 build (`model-hunyuan3d-21-rtx`, quota granted 1000) as the warm primary. `model-text2motion` (MDM, MIT) is the text→motion lane behind `GCP_TEXT2MOTION_URL`, the `text_to_animation` MCP tool, and `POST /api/forge-motion` — prompt in, a retargetable three.js `AnimationClip` out, applied with the same engine (`src/animation-retarget.js`) as the curated animation library. Ops map: [docs/ops/gcp-credits-plan.md](docs/ops/gcp-credits-plan.md) || Avatar Composer (modular studio generation) | [api/_lib/avatar-composer/](api/_lib/avatar-composer) | In-repo · wired into the studio seed lane | Assembles a rigged, ARKit-expression-ready GLB by mixing skinned parts (hair / top / bottom / footwear / glasses) across the RPM base bodies onto **one shared 67-joint skeleton**, then recolors each part and scales the rig — the Ready-Player-Me / Avaturn "one skeleton, many parts" architecture in pure JS on `@gltf-transform`, no GPU or external service. Replaces the recolor-one-of-five-bodies studio lane so two draws almost never look alike. Borrowed parts keep their own inverse binds but remap onto the identity skeleton; mixing is restricted to a base's rest-pose group so parts always fit. Consumed by [api/cron/avaturn-seed-cron.js](api/cron/avaturn-seed-cron.js) (legacy [studio-avatar.js](api/_lib/studio-avatar.js) recolor is the fallback) and the one-click [api/avatars/surprise.js](api/avatars/surprise.js) endpoint (instant avatar, previewed in [public/gallery/surprise.js](public/gallery/surprise.js)). Docs: [api/_lib/avatar-composer/README.md](api/_lib/avatar-composer/README.md). Tests: [tests/avatar-composer.test.js](tests/avatar-composer.test.js) || Auto-rigging worker (Mixamo skeleton + ARKit-52 blendshapes) | [workers/rig/](workers/rig) | Code-complete · deploy pending (asset staging + Cloud Build, see its README) | Make-It-Animatable engine (MIT) predicts the 52-bone Mixamo skeleton + weights; [workers/rig/rig_glb.py](workers/rig/rig_glb.py) grafts them into the original GLB (textures untouched); ICT-FaceKit (MIT) ARKit-52 expression transfer for emotions/lipsync. Contract-compatible replacement for the retired `unirig` service behind `GCP_UNIRIG_URL`; cutover is one env-var update. Canonicalization proof: `rig worker skeleton` cases in [tests/glb-canonicalize.test.js](tests/glb-canonicalize.test.js) || Parametric avatar base (change-everything sliders) | Baker [scripts/build-parametric-base.mjs](scripts/build-parametric-base.mjs) → [public/avatars/parametric-base.glb](public/avatars), CC0 source data [avatar-sources/anny/](avatar-sources/anny), studio wiring [src/avatar-studio.js](src/avatar-studio.js) (`?base=parametric`) + [src/avatar-sculpt.js](src/avatar-sculpt.js) | Live in Avatar Studio (Base switcher) | One canonical humanoid whose identity is **122 baked morph-target sliders** (nose/ears/mouth/eyes/jaw/cheeks/head shape/neck plus gender, muscle, weight, age, height, torso, hips, limbs), built from the CC0 MakeHuman/MPFB2 body vendored via [naver/anny](https://github.com/naver/anny). 52-bone `mixamorig:*` skeleton, so the full clip library retargets onto every slider combination. Sparse-accessor morphs keep the GLB at ~4 MB. Roadmap to conforming hair/garments + sculpt brush: [prompts/roadmap/avatar-parametric-editor.md](prompts/roadmap/avatar-parametric-editor.md). Tests: [tests/parametric-base.test.js](tests/parametric-base.test.js) |diff --git a/api/_lib/forge-reference-image.js b/api/_lib/forge-reference-image.jsindex 480929d51..9021d3ba3 100644--- a/api/_lib/forge-reference-image.js+++ b/api/_lib/forge-reference-image.js@@ -54,10 +54,59 @@// (persisted to R2, same as textToImage), model is a provider/model label, and// lane is 'vertex-reference' or the fallthrough provider's own label.+import { createHash } from 'node:crypto';import { getGcpAccessToken } from './gcp-auth.js';import { putObject, publicUrl } from './r2.js';import { subjectNegativePrompt } from '../forge-enhance.js';import { textToImage } from '../_mcp3d/text-to-image.js';+import { parseJsonLoose } from './vision.js';+import { getRedis } from './redis.js';++// Reference-set cache: the SAME enhanced prompt (already director-rewritten,+// so two users typing differently-worded ideas that converge on one directed+// spec both benefit) within 24h reuses its generated reference image set+// instead of re-spending a Vertex image (and QA-scoring) call. Keyed on a hash+// of everything that changes the output — prompt, aspect, negatives — mirroring+// the content-addressing idiom in forge-cache.js. Fail-open in every direction:+// no Redis, or any command error, degrades to "miss", never blocking generation.+const REF_CACHE_PREFIX = 'fr:ref:';+const REF_CACHE_TTL_S = Math.max(0, Number(process.env.FORGE_REFERENCE_CACHE_TTL_S) || 24 * 3600);++function referenceCacheKey(prompt, { aspectRatio, negativePrompt }) {+ const text = String(prompt || '').trim().toLowerCase();+ if (!text) return null;+ const basis = JSON.stringify([text, aspectRatio || '1:1', String(negativePrompt || '').trim().toLowerCase()]);+ return createHash('sha256').update(basis).digest('hex').slice(0, 40);+}++function referenceCacheEnabled() {+ if (/^(0|false|off|no)$/i.test(String(process.env.FORGE_REFERENCE_CACHE ?? '').trim())) return false;+ return Boolean(getRedis());+}++async function getCachedReference(key) {+ const r = getRedis();+ if (!r || !key || !referenceCacheEnabled()) return null;+ try {+ const raw = await r.get(`${REF_CACHE_PREFIX}${key}`);+ if (!raw) return null;+ const value = typeof raw === 'string' ? JSON.parse(raw) : raw;+ return value && typeof value.imageUrl === 'string' && value.imageUrl ? value : null;+ } catch {+ return null;+ }+}++async function putCachedReference(key, value) {+ const r = getRedis();+ if (!r || !key || !referenceCacheEnabled()) return;+ if (!value?.imageUrl) return;+ try {+ await r.set(`${REF_CACHE_PREFIX}${key}`, JSON.stringify(value), { ex: REF_CACHE_TTL_S });+ } catch {+ /* best-effort */+ }+}// Gemini image model on Vertex ("Nano Banana"): live, credit-billed, uses the// :generateContent shape. Overridable without a code change.@@ -205,6 +254,77 @@ async function generateViaVertex({ instruction, aspectRatio }) {return { b64, mime: imgPart.inlineData.mimeType || 'image/png', model: `vertex-ai/${model}` };}+// ── Reference-image QA gate ──────────────────────────────────────────────────+// GPU reconstruction time (self-host TRELLIS/Hunyuan3D, or a paid vendor) is+// far more expensive than one more Gemini vision call, so before handing a+// reference off to the mesh step we score it with a cheap Vertex flash vision+// pass: is the subject complete, centered, photorealistic, and the background+// clean? A single retry with corrective feedback folded into the instruction+// gets a second roll; whichever scored higher ships (best-of-2), never a hard+// gate — any scoring failure just ships the first image unscored.+const QA_PASS_SCORE = Number(process.env.FORGE_REFERENCE_QA_PASS_SCORE) || 70;+const QA_MODEL = process.env.VERTEX_QUALITY_MODEL || 'gemini-2.5-flash';++function qaRubric(prompt) {+ return [+ 'You are a quality inspector for a text-to-3D pipeline. You are shown ONE reference image that will be ' ++ 'reconstructed into a 3D mesh — its quality directly determines the mesh quality.',+ prompt ? `It was generated for this subject: "${String(prompt).slice(0, 300)}".` : '',+ 'Judge four things: (1) is exactly ONE subject present, fully in frame, not cropped or cut off; ' ++ '(2) is it centered; (3) does it read as a real photograph (not a cartoon, illustration, or CG render); ' ++ '(4) is the background a plain, clean, uncluttered studio sweep with nothing else in the scene.',+ 'Reply with ONLY this JSON object, nothing else:',+ '{"score": <int 0-100 overall>, "complete": <bool>, "centered": <bool>, "photoreal": <bool>, ' ++ '"clean_background": <bool>, "issue": "<one short phrase naming the main problem, or empty string>"}',+ ].filter(Boolean).join(' ');+}++// Score one generated reference image via the same Vertex Gemini vision lane.+// Returns a normalized verdict or null on any failure (fail-open: the caller+// ships the image unscored rather than blocking on a QA outage).+async function scoreReferenceImage({ b64, mime, prompt }) {+ try {+ const project = process.env.GOOGLE_CLOUD_PROJECT;+ if (!project) return null;+ const location = process.env.GOOGLE_CLOUD_LOCATION_QUALITY || process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';+ const token = await getGcpAccessToken();+ const host = location === 'global' ? 'https://aiplatform.googleapis.com' : `https://${location}-aiplatform.googleapis.com`;+ const endpoint = `${host}/v1/projects/${project}/locations/${location}/publishers/google/models/${QA_MODEL}:generateContent`;+ const res = await fetch(endpoint, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({+ contents: [{ role: 'user', parts: [{ text: qaRubric(prompt) }, { inlineData: { mimeType: mime, data: b64 } }] }],+ generationConfig: {+ temperature: 0,+ responseMimeType: 'application/json',+ maxOutputTokens: 300,+ thinkingConfig: { thinkingBudget: 0 },+ },+ }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) return null;+ const data = await res.json();+ const text = (data?.candidates?.[0]?.content?.parts || []).map((p) => p?.text || '').join('').trim();+ if (!text) return null;+ const raw = parseJsonLoose(text);+ const score = Number(raw?.score);+ if (!Number.isFinite(score)) return null;+ return {+ score: Math.max(0, Math.min(100, Math.round(score))),+ complete: raw?.complete !== false,+ centered: raw?.centered !== false,+ photoreal: raw?.photoreal !== false,+ cleanBackground: raw?.clean_background !== false,+ issue: typeof raw?.issue === 'string' ? raw.issue.slice(0, 160) : '',+ };+ } catch (err) {+ console.warn(`[forge-reference-image] QA scoring failed, shipping unscored: ${err?.message}`);+ return null;+ }+}+// Generate the reconstruction reference image for a directed text→3D prompt.//// generateReferenceImage(directedPrompt, {@@ -227,13 +347,56 @@ export async function generateReferenceImage(? String(negativePrompt).trim(): subjectNegativePrompt(prompt, { realistic: true });+ // Same directed prompt (+aspect +negatives) within 24h reuses its reference+ // set instead of re-spending a Vertex image generation + QA-scoring pass.+ // Credits are approved, but latency is a UX cost this avoids for free.+ const cacheKey = referenceCacheKey(prompt, { aspectRatio, negativePrompt: negatives });+ const cached = await getCachedReference(cacheKey);+ if (cached) {+ console.log(`[forge-reference-image] cache hit (24h) for key ${cacheKey}`);+ return { ...cached, lane: 'vertex-reference-cached' };+ }+if (vertexImageEnabled()) {try {const instruction = buildReferenceInstruction(prompt, negatives);- const { b64, model } = await generateViaVertex({ instruction, aspectRatio });- const imageUrl = await persistImageBase64(b64);- console.log(`[forge-reference-image] served by ${model} (vertex-reference lane)`);- return { imageUrl, model, lane: 'vertex-reference' };+ let generated = await generateViaVertex({ instruction, aspectRatio });+ let verdict = await scoreReferenceImage({ b64: generated.b64, mime: generated.mime, prompt });++ // One retry with corrective feedback on a scoring failure: fold the+ // vision model's own named issue into the instruction as an explicit+ // "the previous attempt failed on X, fix it" line, then keep whichever+ // of the two attempts scored higher (best-of-2). GPU reconstruction+ // time dwarfs the cost of one extra vision call, so this is cheap+ // insurance against a bad reference wasting the expensive step downstream.+ if (verdict && verdict.score < QA_PASS_SCORE) {+ const issue = verdict.issue || 'the subject was incomplete, off-center, not photoreal, or the background was cluttered';+ const retryInstruction = `${instruction} IMPORTANT: a previous attempt at this shot failed on: ${issue}. Fix that specifically this time.`;+ try {+ const retried = await generateViaVertex({ instruction: retryInstruction, aspectRatio });+ const retryVerdict = await scoreReferenceImage({ b64: retried.b64, mime: retried.mime, prompt });+ if (!verdict || (retryVerdict && retryVerdict.score > verdict.score)) {+ generated = retried;+ verdict = retryVerdict;+ }+ } catch (err) {+ console.warn(`[forge-reference-image] QA retry generation failed, keeping first attempt: ${err?.message}`);+ }+ }++ if (verdict) {+ console.log(+ `[forge-reference-image] qa score=${verdict.score} complete=${verdict.complete} ` ++ `centered=${verdict.centered} photoreal=${verdict.photoreal} clean_bg=${verdict.cleanBackground}` ++ (verdict.issue ? ` issue="${verdict.issue}"` : ''),+ );+ }++ const imageUrl = await persistImageBase64(generated.b64);+ console.log(`[forge-reference-image] served by ${generated.model} (vertex-reference lane)`);+ const result = { imageUrl, model: generated.model, qaScore: verdict?.score ?? null };+ await putCachedReference(cacheKey, result);+ return { ...result, lane: 'vertex-reference' };} catch (err) {// Any Vertex failure (unconfigured token, safety block, throttle, tier// change) degrades to the existing chain - the reference image still getsdiff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 08e295b4d..4efd450ac 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -146,6 +146,17 @@ const POLL_HINT ='Call generation_status with this job_id to check progress. ' +'Reconstruction typically finishes in 30–90 seconds.';+// An MCP tool call is one-shot text, not a pollable UI — so the honesty bar+// (CLAUDE.md: no fabricated progress) means baking the REAL eta_seconds this+// job was submitted with into the poll instruction, not a generic static+// range. Falls back to `fallback` (a category-appropriate static estimate)+// only when the caller genuinely has no eta signal for this lane.+function pollHint(etaSeconds, fallback) {+ const eta = Number(etaSeconds) > 0 ? Math.round(Number(etaSeconds)) : null;+ if (eta == null) return `Call generation_status with this job_id to check progress. ${fallback}`;+ return `Call generation_status with this job_id to check progress — usually ~${eta}s.`;+}+// Ceiling on a GLB copied into durable storage by save_avatar. Matches the// reconstruct + forge pipelines so a runaway model can't ingest an unbounded blob.const MAX_GLB_BYTES = 64 * 1024 * 1024;@@ -427,6 +438,7 @@ async function submitGeometryJob({kind: submitted.kind,taskId: submitted.taskId,});+ const etaSeconds = estimateEtaSeconds({ backendId, tier });return {content: [@@ -434,7 +446,8 @@ async function submitGeometryJob({type: 'text',text:`Started ${isImageMode ? 'image-to-3D' : 'text-to-3D'} on the ${engineLabelFor(backendId)} ` +- `(${path} path, ${tier.id} tier).\nJob ID: ${token}\n${POLL_HINT}`,+ `(${path} path, ${tier.id} tier).\nJob ID: ${token}\n` ++ pollHint(etaSeconds, 'Reconstruction typically finishes in 30–90 seconds.'),},],structuredContent: {@@ -446,7 +459,7 @@ async function submitGeometryJob({engine: engineIdFor(backendId),prompt: prompt || null,source_image_url: isImageMode ? primaryImage : null,- eta_seconds: estimateEtaSeconds({ backendId, tier }),+ eta_seconds: etaSeconds,estimated_credits: estimateCredits({ backendId, path, tier }),},};@@ -632,7 +645,8 @@ export const toolDefs = [text:`Started generating a 3D model for "${args.prompt}" (${tier.id} tier).\n` +`Reference image: ${imageUrl}\n` +- `Job ID: ${job.extJobId}\n${POLL_HINT}`,+ `Job ID: ${job.extJobId}\n` ++ pollHint(job.eta, 'Reconstruction typically finishes in 30–90 seconds.'),},],structuredContent: {@@ -771,7 +785,9 @@ export const toolDefs = [content: [{type: 'text',- text: `${summary}\nJob ID: ${job.extJobId}\n${POLL_HINT}`,+ text:+ `${summary}\nJob ID: ${job.extJobId}\n` ++ pollHint(job.eta, 'Reconstruction typically finishes in 30–90 seconds.'),},],structuredContent: {@@ -1017,7 +1033,7 @@ export const toolDefs = [text:`Started reconstructing a 3D scene from the video (${params.mode}).\n` +`Job ID: ${job.extJobId}\n` +- 'Poll with generation_status. Reconstruction typically takes a few minutes for a longer clip.',+ pollHint(job.eta, 'Reconstruction typically takes a few minutes for a longer clip.'),}],structuredContent: {job_id: job.extJobId,@@ -1143,7 +1159,7 @@ export const toolDefs = [type: 'text',text:`Background removal started.\nJob ID: ${job.extJobId}\n` +- 'Poll with generation_status. Typically completes in 3–10 seconds.',+ pollHint(job.eta, 'Typically completes in 3–10 seconds.'),},],structuredContent: {@@ -1220,7 +1236,7 @@ export const toolDefs = [type: 'text',text:`Mesh processing started (${args.operation || 'full'}).\nJob ID: ${job.extJobId}\n` +- 'Poll with generation_status. Typically completes in 10–60 seconds.',+ pollHint(job.eta, 'Typically completes in 10–60 seconds.'),},],structuredContent: {@@ -1301,7 +1317,7 @@ export const toolDefs = [type: 'text',text:`Stylization started (${style}).\nJob ID: ${job.extJobId}\n` +- 'Poll with generation_status. Typically completes in 10–40 seconds.',+ pollHint(job.eta, 'Typically completes in 10–40 seconds.'),},],structuredContent: {@@ -1397,7 +1413,7 @@ export const toolDefs = [type: 'text',text:`Segmentation started (${args.method || 'auto'}).\nJob ID: ${job.extJobId}\n` +- 'Poll with generation_status — when done it lists every named part. Typically completes in 10–60 seconds.',+ `${pollHint(job.eta, 'Typically completes in 10–60 seconds.')} When done it lists every named part.`,},],structuredContent: {@@ -1485,7 +1501,7 @@ export const toolDefs = [type: 'text',text:`Texture generation started for "${args.prompt}".\nJob ID: ${job.extJobId}\n` +- 'Poll with generation_status. Typically completes in 2–5 minutes.',+ pollHint(job.eta, 'Typically completes in 2–5 minutes.'),},],structuredContent: {@@ -1614,7 +1630,7 @@ export const toolDefs = [text:`Region retexture started${args.prompt ? ` for "${args.prompt}"` : ''}.\n` +`Job ID: ${job.extJobId}\n` +- 'Poll with generation_status. Typically completes in 30–90 seconds. ' ++ `${pollHint(job.eta, 'Typically completes in 30–90 seconds.')} ` +'To stack edits, feed the resulting GLB back in as mesh_url.',},],diff --git a/avatar-sdk/README.md b/avatar-sdk/README.mdindex fe797fd2b..29af418f8 100644--- a/avatar-sdk/README.md+++ b/avatar-sdk/README.md@@ -96,9 +96,12 @@ The package exposes focused subpath exports so you only ship what you use.### `<three-ws-viewer>`A minimal viewer element: loads a GLB at `src`, frames it, and renders with-`OrbitControls` and a `RoomEnvironment` image-based light. Supports-`EXT_meshopt_compression` and `KHR_draco_mesh_compression` GLBs transparently-(both decoders are lazy-loaded on first use).+`OrbitControls` and real photographic HDRI image-based lighting (patch:+previously a procedural `RoomEnvironment`; now fetches a curated HDRI from+three.ws and falls back to the procedural room on a slow network or a+CSP-blocked embed). Supports `EXT_meshopt_compression` and+`KHR_draco_mesh_compression` GLBs transparently (both decoders are+lazy-loaded on first use).| Attribute | Description ||---|---|diff --git a/docs/mcp.md b/docs/mcp.mdindex 907c67159..5cc66c7b3 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -588,6 +588,27 @@ Returns `{ mint, sources: [...], dexscreener?, jupiter?, solana?, skipped: [...]---+### `text_to_animation`++Generate a brand-new motion from a natural-language prompt ("waving confidently", "a slow tai-chi sweep") with a text-to-motion diffusion model (MDM, MIT), then retarget it onto a caller-supplied rigged humanoid GLB — the same retarget engine `apply_animation` uses. Unlike the curated animation library, the motion does not pre-exist: it's synthesized for the prompt, on the self-host `model-text2motion` GPU worker (`workers/model-text2motion/`).++```json+{+ "type": "object",+ "properties": {+ "prompt": { "type": "string", "minLength": 3, "maxLength": 1000 },+ "model_url": { "type": "string", "format": "uri", "description": "Public https URL of a rigged humanoid .glb to animate." },+ "duration_seconds": { "type": "number", "minimum": 1, "maximum": 10, "default": 4 }+ },+ "required": ["prompt", "model_url"],+ "additionalProperties": false+}+```++Returns the retargeted three.js `AnimationClip` JSON (or a baked animated GLB) plus a retarget report, the same shape `apply_animation` returns. Requires the text2motion worker configured on the deployment (`GCP_TEXT2MOTION_URL`) — errors with `-32001` if unset. Also reachable outside MCP via `POST /api/forge-motion` (`GET /api/forge-motion?job=<id>` to poll).++---+## Rate limits| Scope | Limit |diff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.jsindex 3597ef762..b5a2141dc 100644--- a/mcp-server/src/tools/_studio-core.js+++ b/mcp-server/src/tools/_studio-core.js@@ -309,9 +309,6 @@ function meshDirectorInstruction(prompt) {);}-// Back-compat constant (subject-agnostic) for any caller still importing it-// directly; runMeshForge below now calls meshDirectorInstruction(prompt).-const MESH_DIRECTOR_INSTRUCTION = meshDirectorInstruction('');function avatarDirectorInstruction(prompt) {const subject = classifySubjectLite(prompt) === 'animal' ? 'animal' : 'person';@@ -333,9 +330,6 @@ function avatarDirectorInstruction(prompt) {);}-// Back-compat constant (person default) for any caller still importing it-// directly; runForgeAvatar/runTextToAvatar below now call avatarDirectorInstruction(prompt).-const AVATAR_DIRECTOR_INSTRUCTION = avatarDirectorInstruction('');// ---------------------------------------------------------------------------// forge_free — text → textured 3D GLB on the FREE NVIDIA NIM (TRELLIS) lane.@@ -566,7 +560,7 @@ export async function runMeshForge({ prompt, image_url, image_urls, aspect_ratiodirectedPrompt = await directPrompt({base,rawPrompt: trimmedPrompt,- instruction: MESH_DIRECTOR_INSTRUCTION,+ instruction: meshDirectorInstruction(trimmedPrompt),model: env('MESH_FORGE_DIRECTOR_MODEL'),});}@@ -756,7 +750,7 @@ export async function runForgeAvatar({directedPrompt = await directPrompt({base,rawPrompt: trimmedPrompt,- instruction: AVATAR_DIRECTOR_INSTRUCTION,+ instruction: avatarDirectorInstruction(trimmedPrompt),});}const effectivePrompt = directedPrompt || trimmedPrompt;@@ -1069,8 +1063,20 @@ export async function runTextToAvatar({ prompt, images, seed, texture }) {reason: !version ? 'REPLICATE_TEXT_TO_AVATAR_MODEL is not set' : 'REPLICATE_API_TOKEN is not set',});}+ // Granite avatar director (text mode only, fail-soft): without this the+ // Replicate lane reconstructed straight from the raw words with none of the+ // photoreal briefing the platform's own forge_avatar chain already gets.+ let effectivePrompt = prompt;+ if (prompt && (!images || images.length === 0) && env('TEXT_TO_AVATAR_DIRECTOR', '1') !== '0') {+ const directed = await directPrompt({+ base: apiBaseFrom(['MESH_FORGE_API_BASE']),+ rawPrompt: prompt,+ instruction: avatarDirectorInstruction(prompt),+ });+ if (directed) effectivePrompt = directed;+ }const input = {- prompt: prompt || undefined,+ prompt: effectivePrompt || undefined,image: images && images.length ? images[0] : undefined,images: images && images.length ? images : undefined,seed: typeof seed === 'number' ? seed : undefined,diff --git a/prompts/okx-ai/assets/okx-avatar-440.jpg b/prompts/okx-ai/assets/okx-avatar-440.jpgnew file mode 100644index 000000000..7c507e157Binary files /dev/null and b/prompts/okx-ai/assets/okx-avatar-440.jpg differdiff --git a/prompts/okx-ai/assets/okx-logo-1024.jpg b/prompts/okx-ai/assets/okx-logo-1024.jpgnew file mode 100644index 000000000..bbf7471e0Binary files /dev/null and b/prompts/okx-ai/assets/okx-logo-1024.jpg differdiff --git a/public/ar-forge.html b/public/ar-forge.htmlindex e89b26662..66d306f33 100644--- a/public/ar-forge.html+++ b/public/ar-forge.html@@ -263,6 +263,11 @@var POLL_MS = 3000, MAX_POLL_MS = 300000, LS_KEY = 'twx_ar_forge_recent';var runSeq = 0, elapsedTimer = null, current = null; // { glb, prompt }++ function overlay(el) {+ [idle, working, failed].forEach(function (n) { n.classList.add('hidden'); });+ if (el) el.classList.remove('hidden');+ }// Real ETA + cold-start signal from the initial /api/forge response (see// api/_lib/forge-lane-health.js#coldStartFor + estimateEtaSeconds). No poll// response repeats these, so they're captured once at submit time and thediff --git a/src/ar-studio.js b/src/ar-studio.jsindex 5ec1293b7..1fcf312e9 100644--- a/src/ar-studio.js+++ b/src/ar-studio.js@@ -38,6 +38,7 @@ import {} from './ar/studio-coords.js';import { StudioNet } from './ar/studio-net.js';import { MultiPlaceSession } from './ar/multi-place.js';+import { forgeStageNarration } from './shared/forge-frames.js';import {createPinchState, pinchEnd, pinchMove, pinchStart, touchDist,PINCH_SCALE_MAX, PINCH_SCALE_MIN,@@ -1397,13 +1398,25 @@ async function startForge(prompt) {const seq = ++forgeSeq;if (forgeGo) forgeGo.disabled = true;const t0 = Date.now();- forgeChipState('working', `Forging "${prompt.length > 42 ? `${prompt.slice(0, 39)}…` : prompt}"`);+ // Real ETA + cold-start signal from the initial /api/forge response (see+ // api/_lib/forge-lane-health.js#coldStartFor). No poll response repeats+ // these fields, so they're captured once here and folded into every later+ // forgeStageNarration() call via the shared eta_seconds/cold_start contract.+ let etaSeconds = null;+ let coldStart = false;+ forgeChipState('working', 'Sending your prompt to the forge…');+ const setStage = (status) => {+ if (!forgeChip) return;+ const elapsedS = (Date.now() - t0) / 1000;+ const remaining = etaSeconds != null ? Math.max(0, Math.round(etaSeconds - elapsedS)) : null;+ const narration = forgeStageNarration({ status, eta_seconds: remaining ?? undefined });+ const label = forgeChip.querySelector('.ars-chip-label');+ const el = forgeChip.querySelector('.ars-chip-elapsed');+ if (label) label.textContent = coldStart && status !== 'done' ? `Cold start — ${narration}` : narration;+ if (el) el.textContent = `${Math.round(elapsedS)}s`;+ };const elapsed = setInterval(() => {- if (forgeChip?.dataset.state === 'working') {- const s = Math.round((Date.now() - t0) / 1000);- const el = forgeChip.querySelector('.ars-chip-elapsed');- if (el) el.textContent = `${s}s`;- }+ if (forgeChip?.dataset.state === 'working') setStage('running');}, 1000);try {@@ -1421,10 +1434,13 @@ async function startForge(prompt) {throw new Error(data.message || `The forge is busy — try again in about ${secs}s.`);}if (!res.ok) throw new Error(data.message || `The generator returned ${res.status}.`);+ if (Number(data.eta_seconds) > 0) etaSeconds = Math.round(Number(data.eta_seconds));+ coldStart = Boolean(data.cold_start);let done = data;if (!(data.status === 'done' && data.glb_url)) {if (!data.job_id) throw new Error('The forge did not accept the job. Try again.');+ setStage('queued');done = await pollForge(data.job_id, seq);}if (!done || seq !== forgeSeq) return;diff --git a/tests/mcp-forge-free.test.js b/tests/mcp-forge-free.test.jsindex 0848713c4..97d04188f 100644--- a/tests/mcp-forge-free.test.js+++ b/tests/mcp-forge-free.test.js@@ -8,7 +8,8 @@ import { buildForgeFreeTool } from '../mcp-server/src/tools/forge-free.js';// - input is validated before any network call,// - the synchronous-done forge response is shaped into a free result,// - a queued job is polled to completion,-// - the request pins backend:"nvidia" so the happy path is never the paid lane,+// - the request never pins a paid backend — the router's own free-lane+// default (photoreal image-intermediate pipeline first) picks the engine,// - upstream states (not_configured / busy / failed) become designed toolErrors// (ok:false → isError, which on a paid tool cancels billing; here it just// gives the caller a stable error contract).@@ -99,8 +100,12 @@ describe('forge_free — handler', () => {const [url, opts] = fetchMock.mock.calls[0];expect(url).toMatch(/\/api\/forge$/);const body = JSON.parse(opts.body);- // The free lane must be pinned so the happy path is never the paid Replicate lane.- expect(body).toMatchObject({ backend: 'nvidia', path: 'image', prompt: 'a glossy white robot mascot' });+ // No backend pin: the forge router's own free-lane default resolves to the+ // zero-cost photoreal image-intermediate pipeline (self-host TRELLIS →+ // Hunyuan3D → HuggingFace → NVIDIA NIM last resort), never the paid+ // Replicate lane, without forcing NVIDIA's native text-only preview.+ expect(body).toMatchObject({ path: 'image', prompt: 'a glossy white robot mascot' });+ expect(body.backend).toBeUndefined();// Tier defaults to draft (fast, free).expect(body.tier).toBe('draft');diff --git a/workers/model-text2motion/Dockerfile b/workers/model-text2motion/Dockerfileindex 9d471f0d7..ebb992692 100644--- a/workers/model-text2motion/Dockerfile+++ b/workers/model-text2motion/Dockerfile@@ -21,17 +21,35 @@ RUN apt-get update && apt-get install -y --no-install-recommends \# torch first (cached layer), matching the CUDA 12.1 base.RUN pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121-# MDM (Motion Diffusion Model, MIT) is not a pip package — clone it, install its-# requirements, and put it on PYTHONPATH (mdm_sampler.py imports from it).+# MDM (Motion Diffusion Model, MIT) is not a pip package — clone it and put it+# on PYTHONPATH (mdm_sampler.py imports from it). The repo ships an+# `environment.yml` (conda, Python 3.7 / torch 1.7 / cuda 11.0), not a+# `requirements.txt` — pinning that stack would conflict with the torch 2.3.1+# /cu121 install above, so this installs the actual pip-importable surface+# `mdm_sampler.py` touches (create_model_and_diffusion → model.mdm → CLIP ++# model.rotation2xyz → model.smpl → smplx; diffusion.*; data_loaders.humanml.*+# → scipy/tqdm). spacy is NOT installed: it's part of MDM's HumanML3D dataset+# *training* pipeline (text tokenization for building the dataset cache), which+# this inference-only worker never imports — confirmed by walking every+# module-level import reachable from `create_model_and_diffusion`.RUN git clone --depth 1 https://github.com/GuyTevet/motion-diffusion-model.git /opt/mdm \- && pip install -r /opt/mdm/requirements.txt \- && pip install git+https://github.com/openai/CLIP.git \- && python -m spacy download en_core_web_sm--# MDM auxiliary data (CLIP weights, glove, evaluators) and the SMPL body models-# + the trained checkpoint are mounted at runtime from the weights bucket-# (MOTION_MODEL_DIR=/weights/mdm) — they are large and license-gated, so they-# live in Cloud Storage, not the image.+ && pip install scipy tqdm smplx \+ && pip install git+https://github.com/openai/CLIP.git++# MDM auxiliary data (glove, evaluators) and the trained checkpoint are mounted+# at runtime from the weights bucket (MOTION_MODEL_DIR=/weights/mdm). The real+# SMPL body model (`body_models/smpl/SMPL_NEUTRAL.pkl`) is NOT staged: it is+# gated behind SMPL's own registration/license (smpl.is.tue.mpg.de) and this+# worker never needs it — `model.mdm.MDM` eagerly constructs a+# `Rotation2xyz`/`SMPL` submodule that loads it, but that submodule's OUTPUT+# (SMPL vertex/joint xyz) is never consumed here: motion comes back from the+# diffusion sampler as HumanML3D feature vectors, decoded via `recover_from_ric`+# + this worker's own direction-alignment IK (see mdm_sampler.py's+# `_positions_to_local_quats`). `mdm_sampler.py` monkeypatches+# `model.mdm.Rotation2xyz` to a real (but license-file-free) `nn.Module` stand-in+# before constructing the model, purely so `.to(device)`/`.eval()` — which walk+# into `self.rot2xyz.smpl_model` — have a real module to call, never a mock of+# actual generation output.COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtdiff --git a/workers/model-text2motion/mdm_sampler.py b/workers/model-text2motion/mdm_sampler.pyindex 030a7a3d8..0ad0624a5 100644--- a/workers/model-text2motion/mdm_sampler.py+++ b/workers/model-text2motion/mdm_sampler.py@@ -40,9 +40,41 @@ class MdmSampler:from types import SimpleNamespaceimport torch+ import torch.nn as nn+ import model.mdm as mdm_modulefrom model.cfg_sampler import ClassifierFreeSampleModelfrom utils.model_util import create_model_and_diffusion, load_model_wo_clip+ # MDM.__init__ unconditionally builds `self.rot2xyz = Rotation2xyz(...)`,+ # whose constructor loads the real SMPL body model (a .pkl gated behind+ # SMPL's own registration/license at smpl.is.tue.mpg.de — not something+ # an automated pipeline can fetch). This worker never calls+ # `rot2xyz(...)` (the thing that would actually need real SMPL data):+ # motion comes back from the diffusion sampler as HumanML3D feature+ # vectors, decoded via `recover_from_ric` + this module's own+ # direction-alignment IK (`_positions_to_local_quats`), never via+ # rotation2xyz. But `MDM._apply`/`MDM.train` (invoked by the+ # `.to(device)`/`.eval()` calls below, which is how the model actually+ # loads onto the GPU) reach into `self.rot2xyz.smpl_model._apply`/+ # `.train`, so it still needs to be a real `nn.Module` — just one that+ # never had to load a license-gated file to exist. Patched on the+ # already-imported `model.mdm` module object so it takes effect+ # regardless of import order.+ class _StubSmplModel(nn.Module):+ def forward(self, *a, **kw):+ raise RuntimeError("SMPL rotation2xyz output is not used by this worker")++ class _StubRotation2xyz:+ def __init__(self, device, dataset="amass"):+ self.device = device+ self.dataset = dataset+ self.smpl_model = _StubSmplModel().to(device)++ def __call__(self, *a, **kw):+ raise RuntimeError("Rotation2xyz.__call__ is not used by this worker")++ mdm_module.Rotation2xyz = _StubRotation2xyz+# utils.parser_util.generate_args() takes no parameters and parses# sys.argv (a CLI-only entry point, not usable from a server process —# a prior version of this file called it as `generate_args(model_path=...)`,@@ -63,7 +95,16 @@ class MdmSampler:model, diffusion = create_model_and_diffusion(args, dummy_data)state = torch.load(os.path.join(self.model_dir, "model.pt"), map_location="cpu")load_model_wo_clip(model, state)- model.to(self.device).eval()+ # NOT `model.to(device).eval()`: torch's Module.to() returns+ # `self._apply(convert)` (verified against torch 2.3.1's own source),+ # but MDM's `_apply` override (`def _apply(self, fn): super()._apply(fn);+ # self.rot2xyz.smpl_model._apply(fn)`) never returns `self` — an+ # upstream bug that makes `.to()` return None regardless of which+ # smpl_model is attached. `model` itself is still correctly mutated+ # in place, so call `.to()`/`.eval()` for their side effects only and+ # keep using the original reference.+ model.to(self.device)+ model.eval()# Classifier-free guidance sampling wrapper — matches sample/generate.py's# own gating (skip the wrapper entirely when guidance_param == 1).if self._guidance_param != 1:diff --git a/workers/model-text2motion/requirements.txt b/workers/model-text2motion/requirements.txtindex c2756666b..49092d66f 100644--- a/workers/model-text2motion/requirements.txt+++ b/workers/model-text2motion/requirements.txt@@ -1,8 +1,9 @@-# Worker-level deps. MDM's own requirements (clip, spacy, smplx, chumpy, …) are-# installed from its cloned repo in the Dockerfile, mirroring how model-triposr-# installs TripoSR's requirements.+# Worker-level deps. MDM's own inference-path deps (CLIP, scipy, tqdm, smplx)+# are pip-installed directly in the Dockerfile (the cloned repo ships no+# requirements.txt of its own — see the Dockerfile comment).fastapi==0.115.0uvicorn[standard]==0.32.0pydantic>=2.0.0numpy>=1.24.0google-cloud-storage==2.18.0+httpx>=0.27.0