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.

feat(avatars): build prompt-only avatars from a full-body reference on a full-figure image-to-3D lane plan, health-ordered, instead of the face pipeline

nirholasf9c606bff528
diff --git a/api/_lib/prompt-avatar.js b/api/_lib/prompt-avatar.js
new file mode 100644
index 000000000..540f3c277
--- /dev/null
+++ b/api/_lib/prompt-avatar.js
@@ -0,0 +1,96 @@
+// Text → avatar: the lane plan for a PROMPT with no photos.
+//
+// POST /api/avatars/reconstruct serves two very different inputs. A selfie goes
+// to the avatar-reconstruction service, a face-texture-transfer pipeline: it
+// finds the face in the photo, warps it onto a fixed template body, and throws
+// the rest of the image away. That is the right tool for a likeness and the
+// wrong one for a description. A prompt routed through it came back as the
+// template body in its own clothes with a garbled face pasted on, whatever the
+// prompt asked for ("a silver-haired explorer in a teal flight jacket and brown
+// boots" rendered as a stylized woman in purple leggings, 2026-09-18).
+//
+// So a prompt now takes the forge's full-body path instead:
+// 1. Paint ONE full-body reference image of the character from the prompt
+// (single humanoid, neutral A-pose, head to feet in frame).
+// 2. Reconstruct that image into a textured mesh on an image→3D engine that
+// keeps the whole figure: our self-hosted Hunyuan3D-2.1 worker first, then
+// self-hosted TRELLIS, then the platform/external image→3D lanes, then the
+// caller's own Meshy/Tripo key.
+// 3. The unchanged reconstruct-finalize tail auto-rigs the bare mesh (UniRig
+// on our own GPU) and materializes the avatar + agent, exactly as before.
+//
+// The face pipeline (gcp `reconstruct` mode) is never a candidate here.
+
+import { BACKENDS } from './forge-tiers.js';
+
+// Composition cues appended to the user's own words. They say nothing about
+// style, so "an anime ninja" stays anime and "a photoreal chef" stays photoreal;
+// they only fix the framing the reconstruction and the rigger both depend on:
+// one figure, whole body in frame, limbs readable and separable, nothing in the
+// hands fusing into the silhouette, a plain background that mattes cleanly.
+export const PROMPT_AVATAR_FRAMING =
+ ', full-body character, one single person standing upright in a neutral A-pose facing the camera, ' +
+ 'arms held slightly away from the body, legs slightly apart, the entire figure visible from head to feet ' +
+ 'with nothing cropped, centered, plain light gray studio background, soft even lighting, ' +
+ 'empty hands with no props, no text, sharp detail';
+
+// The Hunyuan3D worker's high tier: deepest shape octree and the sharpest PBR
+// paint pass. An avatar is the product here, and the worker is ours.
+export const PROMPT_AVATAR_TIER = 'high';
+
+export function promptAvatarImagePrompt(prompt) {
+ return `${String(prompt || '').trim()}${PROMPT_AVATAR_FRAMING}`;
+}
+
+// Ordered image→3D lane plan for a text avatar.
+//
+// `platform` is getRegenProviderCandidates() ([{ name, instance }]), `byok` the
+// caller's own provider adapters in the same shape, and `health` an optional
+// laneHealthSnapshot().byId for the self-host lanes. Returns
+// [{ name, instance, mode, lane, params }]: `name` is what lands in
+// avatar_regen_jobs.provider (so the status poll and the sweep load the same
+// adapter), `mode` is what the adapter is asked to run.
+//
+// A self-host lane whose probe says its model is not loaded or the service is
+// unreachable is moved to the back rather than dropped: its submit would be
+// accepted and the job would then fail on the worker, which costs the user the
+// whole wait. A lane that is merely in a failure cooldown keeps its place, since
+// one failed job (often a bad input) is not an outage.
+export function planPromptAvatarLanes({ platform = [], byok = [], health = {} } = {}) {
+ const byName = new Map(platform.filter((p) => p?.instance).map((p) => [p.name, p.instance]));
+ const plan = [];
+ const gcp = byName.get('gcp');
+ const supports = (instance, mode) => {
+ try {
+ return typeof instance?.supportsMode === 'function' ? Boolean(instance.supportsMode(mode)) : true;
+ } catch {
+ return false;
+ }
+ };
+ const selfHost = (mode, lane) => ({
+ name: 'gcp',
+ instance: gcp,
+ mode,
+ lane,
+ params: { tier: PROMPT_AVATAR_TIER, path: 'image' },
+ });
+
+ if (gcp && supports(gcp, 'hunyuan')) plan.push(selfHost('hunyuan', 'hunyuan3d'));
+ if (gcp && supports(gcp, 'trellis')) plan.push(selfHost('trellis', 'trellis_selfhost'));
+ // Replicate's reconstruct model is TRELLIS (generic image→3D), and the HF
+ // Spaces chain is Hunyuan3D / TRELLIS / TripoSR: both keep the whole figure.
+ for (const name of ['replicate', 'huggingface']) {
+ const instance = byName.get(name);
+ if (instance) plan.push({ name, instance, mode: 'reconstruct', lane: name, params: {} });
+ }
+ for (const p of byok) {
+ if (p?.instance) plan.push({ name: p.name, instance: p.instance, mode: 'reconstruct', lane: p.name, params: {} });
+ }
+
+ const hardDown = (entry) => {
+ if (!BACKENDS[entry.lane]) return false;
+ const rec = health?.[entry.lane];
+ return Boolean(rec && rec.status === 'down' && !rec.cooled);
+ };
+ return [...plan.filter((e) => !hardDown(e)), ...plan.filter(hardDown)];
+}
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 0f341d26c..35486d877 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -21,6 +21,8 @@ import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-
import { finalizeAutoRigStage } from '../_lib/auto-rig.js';
import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';
import { textToImage } from '../_mcp3d/text-to-image.js';
+import { planPromptAvatarLanes, promptAvatarImagePrompt } from '../_lib/prompt-avatar.js';
+import { laneHealthSnapshot } from '../_lib/forge-lane-health.js';
// ── provider error masking ──────────────────────────────────────────────────────
// The regen adapters (Replicate, GCP, and the BYOK Meshy/Tripo) attach a stable
@@ -1081,9 +1083,10 @@ const reconstructSchema = z
name: z.string().trim().min(1).max(120),
description: z.string().trim().max(500).optional(),
photos: z.array(photoUrlOrDataUri).min(1).max(6).optional(),
- // Text → avatar: a prompt is turned into a clean frontal reference image
- // (Flux), which then feeds the exact same reconstruct → auto-rig pipeline
- // as a selfie. One of `photos` or `prompt` is required.
+ // Text → avatar: a prompt is painted as one full-body reference image,
+ // reconstructed on a full-figure image→3D engine (self-hosted Hunyuan3D
+ // first), then auto-rigged by the same finalize tail as a selfie. See
+ // _lib/prompt-avatar.js. One of `photos` or `prompt` is required.
prompt: z.string().trim().min(3).max(600).optional(),
visibility: z.enum(['private', 'unlisted', 'public']).optional(),
params: z.record(z.unknown()).optional(),
@@ -1097,22 +1100,6 @@ const reconstructSchema = z
path: ['photos'],
});
-// Steer Flux toward a single, evenly-lit, front-facing subject on a plain
-// background — without overriding the user's own subject description.
-//
-// Framing is FACE-FORWARD, not full-body, and that is deliberate: the production
-// reconstruct lane (gcp) is a face-texture-transfer pipeline — it detects the
-// face in the render, warps it onto a TEMPLATE body, and discards the render's
-// own body geometry entirely. A full-figure "head to feet" render therefore
-// shrinks the face to a small fraction of the frame, and the face detector fails
-// on it — which it did at scale: text→avatar reconstructs ran ~15% success vs
-// ~82% for face-prominent selfie photos, almost all the failures logged as
-// "no face detected in any of the provided photos". A head-and-shoulders portrait
-// makes the face large and unambiguous, which is exactly what the pipeline needs
-// (the body is templated regardless). See handleReconstruct's prompt branch.
-const AVATAR_PROMPT_SUFFIX =
- ', head and shoulders portrait, face large and centered and clearly visible, looking directly at the camera, sharp focus on the face, neutral expression, plain neutral studio background, soft even lighting, single subject, high detail, photorealistic';
-
const handleReconstruct = wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -1150,7 +1137,19 @@ const handleReconstruct = wrap(async (req, res) => {
// stored) backstop them — so a single provider outage, throttle, or credit
// exhaustion fails over to the next instead of dead-ending the job. Each
// entry is { name, instance }; names are de-duplicated.
- const candidates = await resolveReconstructCandidates(req, body);
+ const reconstructCandidates = await resolveReconstructCandidates(req, body);
+
+ // A prompt with no photos never goes to the face pipeline: it runs the
+ // full-body lane plan (see _lib/prompt-avatar.js). Each entry carries the
+ // adapter mode to run, so one provider (gcp) can offer several engines.
+ const fromPrompt = !(Array.isArray(body.photos) && body.photos.length);
+ const candidates = fromPrompt
+ ? planPromptAvatarLanes({
+ platform: reconstructCandidates.filter((c) => !BYOK_REGEN_PROVIDERS.includes(c.name)),
+ byok: reconstructCandidates.filter((c) => BYOK_REGEN_PROVIDERS.includes(c.name)),
+ health: await promptLaneHealth(),
+ })
+ : reconstructCandidates.map((c) => ({ ...c, mode: 'reconstruct', lane: c.name, params: {} }));
// Nothing configured anywhere — tell the client which BYOK providers are
// accepted (unchanged 402 contract the client branches on).
@@ -1164,14 +1163,14 @@ const handleReconstruct = wrap(async (req, res) => {
});
}
- // Text → avatar: turn the prompt into a frontal reference image, then treat
- // it exactly like a selfie. Done only once the reconstruct backend is known
- // to be live, so a configuration gap never burns a Flux generation.
+ // Text → avatar: paint the prompt as one full-body reference image for the
+ // image→3D engine. Done only once a backend is known to be live, so a
+ // configuration gap never burns an image generation.
let photos = body.photos ?? null;
let referenceImageUrl = null;
- if (!photos || !photos.length) {
+ if (fromPrompt) {
try {
- const generated = await textToImage(`${body.prompt}${AVATAR_PROMPT_SUFFIX}`, {
+ const generated = await textToImage(promptAvatarImagePrompt(body.prompt), {
aspectRatio: '2:3',
});
referenceImageUrl = generated.imageUrl;
@@ -1234,18 +1233,18 @@ const handleReconstruct = wrap(async (req, res) => {
try {
submission = await submitWithTransientRetry(provider.instance, {
userId,
- mode: 'reconstruct',
- params: { ...(body.params ?? {}), images: photos, name: body.name },
+ mode: provider.mode,
+ params: { ...(body.params ?? {}), ...provider.params, images: photos, name: body.name },
sourceUrl: photos[0],
});
usedProvider = provider;
break;
} catch (err) {
const classified = classifyProviderError(err);
- attempts.push(`${provider.name}:${err?.code || err?.status || classified.code}`);
+ attempts.push(`${provider.lane}:${err?.code || err?.status || classified.code}`);
console.warn(
'[avatars] reconstruct submit failed on',
- provider.name,
+ provider.lane,
'—',
err?.code || err?.status || 'unknown',
'-',
@@ -1275,8 +1274,8 @@ const handleReconstruct = wrap(async (req, res) => {
// Same rule as POST /api/avatars: an explicit choice wins, silence falls
// back to the owner's default from /settings.
visibility: body.visibility ?? (await defaultAvatarVisibilityFor(userId, 'private')),
- ...(body.prompt
- ? { source: 'prompt', prompt: body.prompt, referenceImageUrl }
+ ...(fromPrompt
+ ? { source: 'prompt', prompt: body.prompt, referenceImageUrl, engine: usedProvider.lane }
: {}),
};
await sql`
@@ -1294,6 +1293,18 @@ const handleReconstruct = wrap(async (req, res) => {
});
});
+// Liveness of the self-host image→3D lanes the prompt plan leads with, so a
+// worker whose model failed to load is tried last instead of accepting the job
+// and failing it minutes later. Best-effort: no telemetry keeps the plan order.
+async function promptLaneHealth() {
+ try {
+ return (await laneHealthSnapshot(['hunyuan3d', 'trellis_selfhost'])).byId;
+ } catch (err) {
+ console.warn('[avatars] prompt lane health skipped:', err?.message);
+ return {};
+ }
+}
+
// Assemble the ordered provider candidate list for a reconstruct submit:
// configured platform providers (primary first) followed by the caller's BYOK
// keys (inline body key, then stored keys), de-duplicated by provider name.
diff --git a/tests/api/prompt-avatar-routing.test.js b/tests/api/prompt-avatar-routing.test.js
new file mode 100644
index 000000000..2dfa2d6b8
--- /dev/null
+++ b/tests/api/prompt-avatar-routing.test.js
@@ -0,0 +1,212 @@
+// Text → avatar routing for POST /api/avatars/reconstruct.
+//
+// A prompt used to be painted as a head-and-shoulders portrait and sent to the
+// avatar-reconstruction service, a face-texture-transfer pipeline that pastes
+// the detected face onto a fixed template body. Whatever the prompt described,
+// the result was the template body with a garbled face: the outfit in the
+// prompt never reached the mesh. These tests pin the replacement:
+//
+// 1. planPromptAvatarLanes never offers the face pipeline for a prompt, and
+// leads with our self-hosted Hunyuan3D worker, then self-hosted TRELLIS,
+// then the external image→3D lanes, then the caller's own keys.
+// 2. A self-host lane whose model failed to load is tried last, but a lane in
+// a failure cooldown keeps its place (one failed job is not an outage).
+// 3. The reference image is framed full-body (A-pose, head to feet), never the
+// face-forward portrait framing.
+// 4. The handler submits the prompt to the gcp adapter in `hunyuan` mode, fails
+// over to the next full-body lane on an upstream fault, and records the job
+// under the adapter name the status poll resolves.
+// 5. A photo submission still runs the face pipeline (`reconstruct` mode).
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ planPromptAvatarLanes,
+ promptAvatarImagePrompt,
+ PROMPT_AVATAR_FRAMING,
+} from '../../api/_lib/prompt-avatar.js';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+const state = { inserts: [], health: {}, gcpSubmit: null, textToImageCalls: [] };
+
+const sqlMock = vi.fn(async (strings, ...values) => {
+ const text = (Array.isArray(strings) ? strings.join('?') : String(strings)).toLowerCase();
+ if (text.includes('insert into avatar_regen_jobs')) {
+ state.inserts.push({ jobId: values[0], mode: values[3], params: JSON.parse(values[4]), provider: values[5], extJobId: values[6] });
+ }
+ return [];
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a), isDbUnavailableError: () => false, isDbCapacityError: () => false }));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => ({ id: 'u1' }),
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+ hasScope: () => true,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy({}, { get: () => async () => ({ success: true }) }),
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/avatars.js', async (orig) => ({
+ ...(await orig()),
+ assertAvatarSlotAvailable: async () => {},
+ isPlanLimitError: () => false,
+ defaultAvatarVisibilityFor: async () => 'private',
+}));
+
+const gcpInstance = {
+ supportsMode: (mode) => ['reconstruct', 'hunyuan', 'trellis', 'rerig'].includes(mode),
+ submit: vi.fn(async (req) => state.gcpSubmit(req)),
+ status: vi.fn(),
+};
+vi.mock('../../api/_lib/regen-provider.js', () => ({
+ getRegenProvider: async () => ({ name: 'gcp', instance: gcpInstance }),
+ getRegenProviderForMode: async () => ({ name: 'gcp', instance: gcpInstance }),
+ getRegenProviderForJob: async () => ({ name: 'gcp', instance: gcpInstance }),
+ getRegenProviderByName: () => ({ name: 'meshy', instance: null }),
+ getRegenProviderCandidates: async () => [{ name: 'gcp', instance: gcpInstance }],
+ BYOK_REGEN_PROVIDERS: ['meshy', 'tripo'],
+}));
+vi.mock('../../api/_lib/forge-provider-key.js', () => ({ resolveProviderKey: async () => null }));
+vi.mock('../../api/_lib/forge-lane-health.js', () => ({
+ laneHealthSnapshot: async () => ({ byId: state.health, statusMap: {} }),
+}));
+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
+ textToImage: vi.fn(async (prompt) => {
+ state.textToImageCalls.push(prompt);
+ return { imageUrl: 'https://cdn.example.com/ref/full-body.png' };
+ }),
+}));
+
+const { dispatch } = await import('../../api/avatars/_actions.js');
+
+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 reconstruct(body) {
+ const req = {
+ method: 'POST',
+ url: '/api/avatars/reconstruct',
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ body,
+ };
+ const res = makeRes();
+ await dispatch('reconstruct', req, res);
+ return { statusCode: res.statusCode, body: JSON.parse(res._body) };
+}
+
+const stub = (name) => ({ name, instance: { supportsMode: () => true, submit: vi.fn(), status: vi.fn() } });
+
+describe('planPromptAvatarLanes', () => {
+ it('leads with self-hosted Hunyuan3D and never offers the face pipeline', () => {
+ const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpInstance }] });
+ expect(plan.map((p) => p.mode)).toEqual(['hunyuan', 'trellis']);
+ expect(plan.every((p) => p.name === 'gcp')).toBe(true);
+ expect(plan[0].params).toMatchObject({ tier: 'high', path: 'image' });
+ });
+
+ it('orders self-host, then external image→3D, then the caller keys', () => {
+ const plan = planPromptAvatarLanes({
+ platform: [stub('huggingface'), { name: 'gcp', instance: gcpInstance }, stub('replicate')],
+ byok: [stub('meshy')],
+ });
+ expect(plan.map((p) => p.lane)).toEqual(['hunyuan3d', 'trellis_selfhost', 'replicate', 'huggingface', 'meshy']);
+ expect(plan.filter((p) => p.name !== 'gcp').every((p) => p.mode === 'reconstruct')).toBe(true);
+ });
+
+ it('omits a self-host engine the gcp adapter has no worker for', () => {
+ const gcpNoTrellis = { supportsMode: (m) => m === 'hunyuan' };
+ const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpNoTrellis }] });
+ expect(plan.map((p) => p.lane)).toEqual(['hunyuan3d']);
+ });
+
+ it('moves a lane whose model failed to load to the back', () => {
+ const plan = planPromptAvatarLanes({
+ platform: [{ name: 'gcp', instance: gcpInstance }, stub('huggingface')],
+ health: { hunyuan3d: { status: 'down', warm: false } },
+ });
+ expect(plan.map((p) => p.lane)).toEqual(['trellis_selfhost', 'huggingface', 'hunyuan3d']);
+ });
+
+ it('keeps a lane that is only in a failure cooldown in first place', () => {
+ const plan = planPromptAvatarLanes({
+ platform: [{ name: 'gcp', instance: gcpInstance }, stub('huggingface')],
+ health: { hunyuan3d: { status: 'down', warm: false, cooled: true } },
+ });
+ expect(plan[0].lane).toBe('hunyuan3d');
+ });
+
+ it('returns nothing when no image→3D engine is configured', () => {
+ expect(planPromptAvatarLanes({})).toEqual([]);
+ });
+});
+
+describe('promptAvatarImagePrompt', () => {
+ it('frames the reference full-body, never as a face-forward portrait', () => {
+ const out = promptAvatarImagePrompt(' a knight in blue armor ');
+ expect(out.startsWith('a knight in blue armor, full-body')).toBe(true);
+ expect(out).toMatch(/A-pose/);
+ expect(out).toMatch(/head to feet/);
+ expect(out).not.toMatch(/head and shoulders|face large/i);
+ expect(PROMPT_AVATAR_FRAMING).not.toMatch(/photorealistic/i);
+ });
+});
+
+describe('POST /api/avatars/reconstruct with a prompt', () => {
+ beforeEach(() => {
+ state.inserts = [];
+ state.health = {};
+ state.textToImageCalls = [];
+ gcpInstance.submit.mockClear();
+ state.gcpSubmit = async ({ mode }) => ({ extJobId: `env-${mode}`, eta: 120 });
+ });
+
+ it('paints a full-body reference and generates on self-hosted Hunyuan3D', async () => {
+ const { statusCode, body } = await reconstruct({ name: 'Explorer', prompt: 'a silver-haired explorer in a teal flight jacket' });
+ expect(statusCode).toBe(202);
+ expect(body).toMatchObject({ ok: true, provider: 'gcp', status: 'queued' });
+ expect(state.textToImageCalls[0]).toMatch(/^a silver-haired explorer in a teal flight jacket, full-body/);
+
+ const call = gcpInstance.submit.mock.calls[0][0];
+ expect(call.mode).toBe('hunyuan');
+ expect(call.params).toMatchObject({ tier: 'high', images: ['https://cdn.example.com/ref/full-body.png'] });
+
+ expect(state.inserts).toHaveLength(1);
+ expect(state.inserts[0]).toMatchObject({ mode: 'reconstruct', provider: 'gcp', extJobId: 'env-hunyuan' });
+ expect(state.inserts[0].params).toMatchObject({ source: 'prompt', engine: 'hunyuan3d', referenceImageUrl: 'https://cdn.example.com/ref/full-body.png' });
+ });
+
+ it('fails over to self-hosted TRELLIS when the Hunyuan3D worker is unreachable', async () => {
+ state.gcpSubmit = async ({ mode }) => {
+ if (mode === 'hunyuan') throw Object.assign(new Error('down'), { code: 'provider_unreachable', status: 502 });
+ return { extJobId: `env-${mode}`, eta: 60 };
+ };
+ const { statusCode } = await reconstruct({ name: 'Explorer', prompt: 'a silver-haired explorer' });
+ expect(statusCode).toBe(202);
+ const modes = gcpInstance.submit.mock.calls.map((c) => c[0].mode);
+ expect(modes).toEqual(['hunyuan', 'hunyuan', 'trellis']);
+ expect(modes).not.toContain('reconstruct');
+ expect(state.inserts[0].params.engine).toBe('trellis_selfhost');
+ });
+
+ it('still routes a photo submission through the face pipeline', async () => {
+ const { statusCode } = await reconstruct({ name: 'Me', photos: ['https://cdn.example.com/selfie.jpg'] });
+ expect(statusCode).toBe(202);
+ expect(state.textToImageCalls).toHaveLength(0);
+ expect(gcpInstance.submit.mock.calls[0][0].mode).toBe('reconstruct');
+ expect(state.inserts[0].params.source).toBeUndefined();
+ });
+});