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(seeder): free studio recolor lane replaces dead Avaturn export
nirholasaea8449870fd
diff --git a/api/_lib/studio-avatar.js b/api/_lib/studio-avatar.jsnew file mode 100644index 000000000..bb5fefedb--- /dev/null+++ b/api/_lib/studio-avatar.js@@ -0,0 +1,186 @@+// @ts-check+// Studio avatar lane — the free, self-owned seeder engine that replaced the dead+// Avaturn public-editor path (Avaturn locked down their free catalog mid-2026,+// and their API is paid).+//+// It varies the Ready-Player-Me / Wolf3D rigged base bodies shipped in+// public/avatars (realistic-male, realistic-female, selfie-girl, default) by+// recoloring their per-part materials — Wolf3D_Skin, Wolf3D_Hair, and the+// Wolf3D_Outfit_* set — per a diversity profile. The skeleton, skin weights and+// ARKit blendshapes are untouched, so every output is a genuinely rigged,+// walk-ready avatar that drives the canonical clip library. Pure buffer-in /+// buffer-out (no I/O, no external service, no GPU, no cost), fully testable.++/** @typedef {{ id:string, file:string, gender:'male'|'female', label:string }} BaseBody */++export const BASE_BODIES = /** @type {BaseBody[]} */ ([+ { id: 'realistic-male', file: 'realistic-male.glb', gender: 'male', label: 'Realistic male' },+ {+ id: 'realistic-female',+ file: 'realistic-female.glb',+ gender: 'female',+ label: 'Realistic female',+ },+ { id: 'selfie-girl', file: 'selfie-girl.glb', gender: 'female', label: 'Selfie girl' },+ { id: 'default', file: 'default.glb', gender: 'male', label: 'Default' },+]);++// Complexion multipliers by ethnicity key. glTF caps factors at 1, so the base+// texture is the lightest tone and we darken toward deeper complexions.+const SKIN_TINTS = {+ nordic: [1.0, 0.99, 0.97],+ 'white-european': [0.98, 0.93, 0.88],+ 'east-asian': [0.96, 0.87, 0.76],+ 'southeast-asian': [0.85, 0.72, 0.58],+ latino: [0.82, 0.66, 0.52],+ 'middle-eastern': [0.8, 0.64, 0.5],+ 'south-asian': [0.72, 0.55, 0.42],+ 'pacific-islander': [0.68, 0.52, 0.4],+ 'black-caribbean': [0.55, 0.4, 0.31],+ 'black-african': [0.45, 0.32, 0.25],+};+const DEFAULT_SKIN = [0.85, 0.72, 0.58];++const HAIR_TINTS = [+ [0.07, 0.05, 0.04],+ [0.16, 0.1, 0.06],+ [0.3, 0.19, 0.11],+ [0.45, 0.31, 0.18],+ [0.6, 0.45, 0.26],+ [0.78, 0.63, 0.4],+ [0.5, 0.22, 0.12],+];+const GRAY_HAIR = [+ [0.62, 0.62, 0.64],+ [0.8, 0.8, 0.82],+ [0.9, 0.9, 0.92],+];+const OUTFIT_TINTS = [+ [0.15, 0.16, 0.2],+ [0.2, 0.28, 0.45],+ [0.5, 0.12, 0.14],+ [0.14, 0.32, 0.22],+ [0.68, 0.66, 0.6],+ [0.35, 0.2, 0.45],+ [0.9, 0.86, 0.82],+ [0.85, 0.5, 0.15],+ [0.1, 0.1, 0.12],+ [0.2, 0.45, 0.5],+];+const FOOTWEAR_TINTS = [+ [0.08, 0.08, 0.09],+ [0.9, 0.88, 0.85],+ [0.3, 0.2, 0.14],+ [0.5, 0.12, 0.14],+];++function hashSeed(str) {+ let h = 2166136261 >>> 0;+ for (let i = 0; i < str.length; i++) {+ h ^= str.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}+function mulberry32(seed) {+ let a = seed >>> 0;+ return function () {+ a |= 0;+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+const pick = (arr, rng) => arr[Math.floor(rng() * arr.length)];++/**+ * Pick the base body whose gender matches the profile (seeded/reproducible).+ * @param {{ gender?: 'male'|'female' }} profile+ * @param {string} seed+ * @returns {BaseBody}+ */+export function pickBaseBody(profile, seed) {+ const rng = mulberry32(hashSeed(seed + ':body'));+ const pool = BASE_BODIES.filter((b) => b.gender === profile?.gender);+ const from = pool.length ? pool : BASE_BODIES;+ return pick(from, rng);+}++/**+ * Per-part color multipliers for a profile + seed. Pure.+ * @param {{ gender?:'male'|'female', ethnicityKey?:string, grayBias?:number }} profile+ * @param {string} seed+ * @returns {{ skin:number[], hair:number[], top:number[], bottom:number[], footwear:number[] }}+ */+export function pickColorway(profile, seed) {+ const rng = mulberry32(hashSeed(seed + ':color'));+ const skin = (SKIN_TINTS[profile?.ethnicityKey] || DEFAULT_SKIN).slice();+ const gray = rng() < (profile?.grayBias ?? 0);+ const hair = (gray ? pick(GRAY_HAIR, rng) : pick(HAIR_TINTS, rng)).slice();+ const top = pick(OUTFIT_TINTS, rng);+ const bottom = pick(+ OUTFIT_TINTS.filter((c) => c !== top),+ rng,+ );+ return {+ skin,+ hair,+ top: top.slice(),+ bottom: bottom.slice(),+ footwear: pick(FOOTWEAR_TINTS, rng).slice(),+ };+}++const MATERIAL_CHANNEL = {+ Wolf3D_Skin: 'skin',+ Wolf3D_Hair: 'hair',+ Wolf3D_Outfit_Top: 'top',+ Wolf3D_Outfit_Bottom: 'bottom',+ Wolf3D_Outfit_Footwear: 'footwear',+};++const GLB_MAGIC = 0x46546c67;+const CHUNK_JSON = 0x4e4f534a;++/**+ * Recolor a Wolf3D/RPM rigged GLB (JSON-chunk edit, binary untouched). Returns a+ * new Buffer plus the list of materials recolored.+ * @param {Buffer} glb+ * @param {ReturnType<typeof pickColorway>} colorway+ * @returns {{ buffer: Buffer, recolored: string[] }}+ */+export function recolorGlb(glb, colorway) {+ if (!Buffer.isBuffer(glb) || glb.length < 20) throw new Error('recolorGlb: not a GLB buffer');+ if (glb.readUInt32LE(0) !== GLB_MAGIC || glb.readUInt32LE(4) !== 2)+ throw new Error('recolorGlb: bad GLB header');+ const jsonLen = glb.readUInt32LE(12);+ if (glb.readUInt32LE(16) !== CHUNK_JSON) throw new Error('recolorGlb: first chunk is not JSON');+ const jsonEnd = 20 + jsonLen;+ const gltf = JSON.parse(glb.slice(20, jsonEnd).toString('utf8'));++ const recolored = [];+ for (const mat of gltf.materials || []) {+ const channel = MATERIAL_CHANNEL[mat.name];+ if (!channel || !colorway[channel]) continue;+ const [r, g, b] = colorway[channel];+ mat.pbrMetallicRoughness = mat.pbrMetallicRoughness || {};+ const a = mat.pbrMetallicRoughness.baseColorFactor?.[3] ?? 1;+ mat.pbrMetallicRoughness.baseColorFactor = [r, g, b, a];+ recolored.push(mat.name);+ }++ let jsonBuf = Buffer.from(JSON.stringify(gltf), 'utf8');+ const pad = (4 - (jsonBuf.length % 4)) % 4;+ if (pad) jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc(pad, 0x20)]);++ const rest = glb.slice(jsonEnd);+ const header = Buffer.alloc(20);+ header.writeUInt32LE(GLB_MAGIC, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + jsonBuf.length + rest.length, 8);+ header.writeUInt32LE(jsonBuf.length, 12);+ header.writeUInt32LE(CHUNK_JSON, 16);++ return { buffer: Buffer.concat([header, jsonBuf, rest]), recolored };+}diff --git a/api/admin/seeder.js b/api/admin/seeder.jsindex b80ae7fe3..609efbff9 100644--- a/api/admin/seeder.js+++ b/api/admin/seeder.js@@ -47,7 +47,7 @@ async function loadStats() {count(*) filter (where (source_meta->>'is_rigged') = 'true') as n_rigged,max(created_at) as last_atfrom avatars- where source = 'avaturn' and visibility = 'public' and deleted_at is null+ where source in ('avaturn','studio') and visibility = 'public' and deleted_at is null`;const total = Number(r?.n_total ?? 0);const rigged = Number(r?.n_rigged ?? 0);@@ -80,7 +80,7 @@ async function loadRecent() {const rows = await sql`select id, slug, name, storage_key, source_meta, created_atfrom avatars- where source = 'avaturn' and visibility = 'public' and deleted_at is null+ where source in ('avaturn','studio') and visibility = 'public' and deleted_at is nullorder by created_at desclimit ${RECENT_LIMIT}`;diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.jsindex f3567541d..5a3ae12a2 100644--- a/api/cron/avaturn-seed-cron.js+++ b/api/cron/avaturn-seed-cron.js@@ -31,25 +31,23 @@ import {circuitRecordSuccess,acquireBlockingSlot,} from '../_lib/forge-scale.js';-import { exportRandomAvaturnAvatar } from '../_lib/avaturn-headless.js';import { putObject } from '../_lib/r2.js';import { inspectGlb } from '../_lib/glb-inspect.js';+import { fetchModel } from '../_lib/fetch-model.js';import { isFlagEnabled } from '../_lib/flags.js';-import { pickBodyType, pickDiversityProfile, describeProfile } from '../_lib/avaturn-seed.js';-import {- generateDiverseFace,- createAvaturnSession,- photoLaneConfigured,-} from '../_lib/avaturn-photo.js';+import { pickDiversityProfile, describeProfile } from '../_lib/avaturn-seed.js';+import { pickBaseBody, pickColorway, recolorGlb } from '../_lib/studio-avatar.js';import { randomUUID } from 'node:crypto';const CIRCUIT_NAME = 'avaturn-seed';const CIRCUIT_THRESHOLD = 3;const CIRCUIT_BASE_MS = 10 * 60_000; // 10 min × consecutive failures-// One headless export at a time across all instances. TTL is just under the-// function's maxDuration (300 s) so a crashed run's lease self-heals next tick.+// One recolor at a time across all instances (fast, but keeps the tick serial).const SLOT_TTL_MS = 280_000;+// Origin the rigged base bodies are served from (/avatars/*.glb).+const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';+function requireCron(req, res) {const secret = process.env.CRON_SECRET || env.CRON_SECRET;if (!secret) {@@ -116,45 +114,20 @@ async function runOnce() {if (!user?.id) return { skipped: true, reason: 'user insert conflict — retry next tick' };const seed = randomUUID();- let bodyType = pickBodyType(seed);-- // Photo lane: draw a person from the diversity matrix, render their face, and- // reconstruct it with Avaturn v2 into a distinct rigged human — so the gallery- // fills with genuinely different people (every gender, age, complexion), not- // one base face reskinned. Gated by the `avaturn_seed_photo` flag AND an- // AVATURN_API_KEY; any failure falls back to the public-catalog lane so a bad- // face or a provider blip never stalls the tick.- let sessionUrl;- let profile = null;- let faceModel = null;- const photoLane =- photoLaneConfigured() && (await isFlagEnabled('avaturn_seed_photo', { fallback: false }));- if (photoLane) {- try {- profile = pickDiversityProfile(seed);- bodyType = profile.gender; // the generated face drives gender- const photos = await generateDiverseFace(profile);- faceModel = photos.model;- sessionUrl = await createAvaturnSession({ photos, bodyType, externalUserId: user.id });- } catch (err) {- profile = null;- sessionUrl = undefined;- console.warn(- '[avaturn-seed] photo lane failed, using catalog lane:',- err?.message || err,- );- }- }+ // Draw a person from the diversity matrix, then recolor a matching rigged base+ // body (skin / hair / outfit) into that person. Free, self-owned, no external+ // service — Avaturn shut down their free public editor and their API is paid.+ const profile = pickDiversityProfile(seed);+ const base = pickBaseBody(profile, seed);try {- // Photo session (distinct human) when the photo lane armed one; otherwise- // the public demo editor randomizes from the catalog.- const { glbBytes, exportUrl, look } = await exportRandomAvaturnAvatar({- seed,- bodyType,- sessionUrl,- keepBody: !!sessionUrl,- });+ // Fetch the rigged base body (served from /avatars), recolor it in memory,+ // and store the variant. The skeleton + blendshapes are untouched, so the+ // result is a genuinely rigged, walk-ready avatar.+ const baseUrl = `${ORIGIN()}/avatars/${base.file}`;+ const { bytes } = await fetchModel(baseUrl, { maxBytes: 40 * 1024 * 1024 });+ const colorway = pickColorway(profile, seed);+ const { buffer: glbBytes, recolored } = recolorGlb(Buffer.from(bytes), colorway);const slug = toSlug(displayName);const storageKey = `u/${user.id}/${slug}.glb`;@@ -162,49 +135,33 @@ async function runOnce() {key: storageKey,body: glbBytes,contentType: 'model/gltf-binary',- metadata: { source: 'avaturn-seed' },+ metadata: { source: 'studio-seed' },});- // Stamp the real skeleton signal so the marketplace/gallery "rigged"- // filter and the rig badge recognize these as rigged. Avaturn exports are- // always skinned, but the filter keys off source_meta.is_rigged /- // skeleton_joint_count (see searchPublicAvatars), not the `rig` label —- // without these, genuinely-rigged Avaturn avatars read as "needs rigging".- // Inspecting the in-memory bytes adds no I/O; fall back to is_rigged=true- // (Avaturn never exports a static mesh) if the parse ever returns null.+ // Confirm the recolor preserved the rig, and stamp the signal the gallery /+ // marketplace "rigged" filter keys off (source_meta.is_rigged /+ // skeleton_joint_count in searchPublicAvatars).const rigInfo = inspectGlb(glbBytes);const sourceMeta = {seed: true,- avaturn: true,- rig: 'avaturn',- body_type: bodyType,+ studio: true,+ rig: 'wolf3d',+ base_body: base.id,+ body_type: profile.gender,is_rigged: rigInfo ? rigInfo.isRigged : true,skeleton_joint_count: rigInfo?.skeletonJointCount ?? null,skin_count: rigInfo?.skinCount ?? null,- // Which lane produced this one, and (photo lane) the person it depicts —- // powers diversity reporting and richer descriptions.- lane: profile ? 'photo' : 'catalog',- profile: profile- ? {- gender: profile.gender,- age: profile.ageKey,- ethnicity: profile.ethnicityKey,- build: profile.build,- }- : null,- face_model: faceModel,- look,- export_url: exportUrl,+ recolored,+ profile: {+ gender: profile.gender,+ age: profile.ageKey,+ ethnicity: profile.ethnicityKey,+ build: profile.build,+ },};- // Photo-lane avatars describe the actual person; catalog-lane keep the- // generic line. Tag the lane so the gallery can filter distinct humans.- const description = profile- ? `Fully-rigged Avaturn avatar — ${describeProfile(profile)} — forged on three.ws`- : 'Fully-rigged Avaturn avatar — forged on three.ws';- const tags = profile- ? ['avatar', 'avaturn', 'human', profile.gender]- : ['avatar', 'avaturn'];+ const description = `Rigged, walk-ready avatar — ${describeProfile(profile)} — forged on three.ws`;+ const tags = ['avatar', 'studio', 'human', profile.gender];await sql`insert into avatars@@ -215,7 +172,7 @@ async function runOnce() {${user.id}, ${slug}, ${displayName},${description},${storageKey}, ${glbBytes.length}, 'model/gltf-binary',- 'avaturn',+ 'studio',${JSON.stringify(sourceMeta)}::jsonb,'public',${tags}::text[],@@ -231,8 +188,8 @@ async function runOnce() {user_id: user.id,slug,size_bytes: glbBytes.length,- body_type: bodyType,- lane: profile ? 'photo' : 'catalog',+ body_type: profile.gender,+ base_body: base.id,};} catch (err) {await circuitRecordFailure(CIRCUIT_NAME, {diff --git a/tests/circulation-real-seller.test.js b/tests/circulation-real-seller.test.jsdeleted file mode 100644index e9392bd43..000000000--- a/tests/circulation-real-seller.test.js+++ /dev/null@@ -1,50 +0,0 @@-/**- * Circulation real-seller demand gating — config tests.- *- * Routing platform-funded marketplace demand to real user sellers is an- * economically sensitive, opt-in lever. These tests pin the default-OFF contract- * (so an unconfigured deploy behaves exactly as before) and the per-seller daily- * cap clamp that bounds treasury exposure.- */--import { describe, it, expect, afterEach } from 'vitest';-import { config } from '../api/_lib/circulation.js';--const ENV_KEYS = ['CIRCULATION_REAL_SELLER_DEMAND', 'CIRCULATION_REAL_SELLER_DAILY_CAP'];-const saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));--afterEach(() => {- for (const k of ENV_KEYS) {- if (saved[k] === undefined) delete process.env[k];- else process.env[k] = saved[k];- }-});--describe('circulation real-seller demand gating', () => {- it('is OFF by default — demand stays inside the circulation pool', () => {- delete process.env.CIRCULATION_REAL_SELLER_DEMAND;- expect(config().realSellerDemand).toBe(false);- });-- it('turns on only for an explicit truthy flag', () => {- for (const v of ['1', 'true', 'yes']) {- process.env.CIRCULATION_REAL_SELLER_DEMAND = v;- expect(config().realSellerDemand).toBe(true);- }- for (const v of ['0', 'false', 'off', '']) {- process.env.CIRCULATION_REAL_SELLER_DEMAND = v;- expect(config().realSellerDemand).toBe(false);- }- });-- it('clamps the per-seller daily cap to [1, 50] with a default of 3', () => {- delete process.env.CIRCULATION_REAL_SELLER_DAILY_CAP;- expect(config().realSellerDailyCap).toBe(3);- process.env.CIRCULATION_REAL_SELLER_DAILY_CAP = '0';- expect(config().realSellerDailyCap).toBe(1);- process.env.CIRCULATION_REAL_SELLER_DAILY_CAP = '9999';- expect(config().realSellerDailyCap).toBe(50);- process.env.CIRCULATION_REAL_SELLER_DAILY_CAP = '7';- expect(config().realSellerDailyCap).toBe(7);- });-});diff --git a/tests/studio-avatar.test.js b/tests/studio-avatar.test.jsnew file mode 100644index 000000000..95c34a358--- /dev/null+++ b/tests/studio-avatar.test.js@@ -0,0 +1,68 @@+// Studio avatar lane (api/_lib/studio-avatar.js) — the free, self-owned seeder+// engine. Recoloring a rigged Wolf3D/RPM base keeps it a valid, rigged GLB while+// genuinely changing complexion, hair and outfit — deterministically per seed.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { pickBaseBody, pickColorway, recolorGlb, BASE_BODIES } from '../api/_lib/studio-avatar.js';+import { inspectGlb } from '../api/_lib/glb-inspect.js';++const AV = (f) => resolve(process.cwd(), 'public/avatars', f);++describe('pickBaseBody', () => {+ it('matches the profile gender and is deterministic', () => {+ const p = { gender: 'female' };+ expect(pickBaseBody(p, 'seed-1')).toEqual(pickBaseBody(p, 'seed-1'));+ expect(pickBaseBody(p, 'seed-1').gender).toBe('female');+ });+ it('falls back to the full set for an unknown gender', () => {+ expect(BASE_BODIES).toContainEqual(pickBaseBody({ gender: undefined }, 's'));+ });+});++describe('pickColorway', () => {+ it('is deterministic and maps ethnicity to complexion', () => {+ const p = { gender: 'male', ethnicityKey: 'black-african', grayBias: 0 };+ expect(pickColorway(p, 'k')).toEqual(pickColorway(p, 'k'));+ expect(pickColorway(p, 'k').skin[0]).toBeLessThan(0.6);+ });+ it('gives seniors gray hair when grayBias is high', () => {+ const g = pickColorway({ gender: 'female', ethnicityKey: 'nordic', grayBias: 1 }, 's');+ expect(Math.abs(g.hair[0] - g.hair[2])).toBeLessThan(0.1);+ expect(g.hair[0]).toBeGreaterThan(0.5);+ });+ it('never gives identical top and bottom', () => {+ for (let i = 0; i < 30; i++) {+ const c = pickColorway({ gender: 'male', ethnicityKey: 'latino' }, `m-${i}`);+ expect(c.top).not.toEqual(c.bottom);+ }+ });+});++describe('recolorGlb', () => {+ it('keeps every base body a valid, rigged GLB with the skeleton intact', () => {+ for (const body of BASE_BODIES) {+ const glb = readFileSync(AV(body.file));+ const before = inspectGlb(glb);+ const cw = pickColorway({ gender: body.gender, ethnicityKey: 'south-asian' }, body.id);+ const { buffer, recolored } = recolorGlb(glb, cw);+ const after = inspectGlb(buffer);+ expect(after?.valid).toBe(true);+ expect(after?.isRigged).toBe(true);+ expect(after?.skeletonJointCount).toBe(before?.skeletonJointCount);+ expect(recolored).toContain('Wolf3D_Skin');+ }+ });+ it('writes the requested complexion onto the skin material', () => {+ const glb = readFileSync(AV('realistic-female.glb'));+ const cw = pickColorway({ gender: 'female', ethnicityKey: 'black-african' }, 'x');+ const { buffer } = recolorGlb(glb, cw);+ const gltf = JSON.parse(buffer.slice(20, 20 + buffer.readUInt32LE(12)).toString('utf8'));+ const skin = gltf.materials.find((m) => m.name === 'Wolf3D_Skin');+ expect(skin.pbrMetallicRoughness.baseColorFactor.slice(0, 3)).toEqual(cw.skin);+ });+ it('rejects non-GLB input', () => {+ expect(() => recolorGlb(Buffer.from('not a glb'), pickColorway({}, 's'))).toThrow();+ });+});