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: add keepBody option for photo-session avatars and improve code formatting

qbdzaa006c5edc8c
diff --git a/api/_lib/avaturn-headless.js b/api/_lib/avaturn-headless.js
index 36ebf94e6..636b580ba 100644
--- a/api/_lib/avaturn-headless.js
+++ b/api/_lib/avaturn-headless.js
@@ -76,6 +76,7 @@ async function pullGlb(exportUrl, maxBytes) {
* seed: string,
* bodyType?: 'male'|'female',
* sessionUrl?: string,
+ * keepBody?: boolean,
* timeoutMs?: number,
* maxBytes?: number,
* }} opts
@@ -85,11 +86,15 @@ export async function exportRandomAvaturnAvatar({
seed,
bodyType = 'male',
sessionUrl,
+ keepBody = false,
timeoutMs = 110_000,
maxBytes = DEFAULT_MAX_GLB_BYTES,
}) {
const harness = new URL('/internal/avaturn-forge.html', env.APP_ORIGIN);
if (sessionUrl) harness.searchParams.set('session', sessionUrl);
+ // Photo-session avatars are a reconstructed person — keep that body/face and
+ // only vary outfit + colors, never swap to a random catalog body.
+ if (keepBody) harness.searchParams.set('keepBody', '1');
harness.searchParams.set('seed', String(seed));
harness.searchParams.set('bodyType', bodyType);
@@ -97,18 +102,25 @@ export async function exportRandomAvaturnAvatar({
const page = await browser.newPage();
try {
await page.goto(harness.toString(), { waitUntil: 'domcontentloaded', timeout: 30_000 });
- await page.waitForFunction('window.__avaturnDone === true', { timeout: timeoutMs, polling: 1000 });
+ await page.waitForFunction('window.__avaturnDone === true', {
+ timeout: timeoutMs,
+ polling: 1000,
+ });
const { error, result } = await page.evaluate(() => ({
error: window.__avaturnError,
result: window.__avaturnResult,
}));
if (error) {
- throw Object.assign(new Error(`avaturn export failed: ${error}`), { code: 'export_failed' });
+ throw Object.assign(new Error(`avaturn export failed: ${error}`), {
+ code: 'export_failed',
+ });
}
const exportUrl = result?.url;
if (!exportUrl) {
- throw Object.assign(new Error('avaturn export produced no url'), { code: 'export_failed' });
+ throw Object.assign(new Error('avaturn export produced no url'), {
+ code: 'export_failed',
+ });
}
const glbBytes = await pullGlb(exportUrl, maxBytes);
diff --git a/api/_lib/avaturn-photo.js b/api/_lib/avaturn-photo.js
index eb0323aa0..4c91994fb 100644
--- a/api/_lib/avaturn-photo.js
+++ b/api/_lib/avaturn-photo.js
@@ -65,7 +65,12 @@ export async function createAvaturnSession({ photos, bodyType = 'male', external
'content-type': 'application/json',
accept: 'application/json',
},
- body: JSON.stringify({ external_user_id: externalUserId, photos, body_type: bodyType, version: 'v2' }),
+ body: JSON.stringify({
+ external_user_id: externalUserId,
+ photos,
+ body_type: bodyType,
+ version: 'v2',
+ }),
signal: AbortSignal.timeout(SESSION_TIMEOUT_MS),
});
if (!r.ok) {
diff --git a/api/_lib/avaturn-seed.js b/api/_lib/avaturn-seed.js
index cc091eb89..86ea7a9e8 100644
--- a/api/_lib/avaturn-seed.js
+++ b/api/_lib/avaturn-seed.js
@@ -61,7 +61,16 @@ export function pickOne(arr, rng) {
// actually offers — missing slots are simply skipped, never faked. The Avaturn
// catalog tags each asset with a category/type; we normalize a few common
// spellings so grouping is stable across catalog revisions.
-export const WEARABLE_SLOTS = ['outfit', 'top', 'bottom', 'shoes', 'hair', 'headwear', 'glasses', 'outerwear'];
+export const WEARABLE_SLOTS = [
+ 'outfit',
+ 'top',
+ 'bottom',
+ 'shoes',
+ 'hair',
+ 'headwear',
+ 'glasses',
+ 'outerwear',
+];
const SLOT_ALIASES = {
clothing: 'outfit',
@@ -83,7 +92,9 @@ const SLOT_ALIASES = {
* @returns {string}
*/
export function normalizeSlot(raw) {
- const k = String(raw || '').trim().toLowerCase();
+ const k = String(raw || '')
+ .trim()
+ .toLowerCase();
return SLOT_ALIASES[k] || k;
}
@@ -110,9 +121,21 @@ export function groupAssetsBySlot(assets) {
// Natural hair shades — kept realistic so results stay on-model rather than
// cartoonish. setHairColor takes a `#rrggbb` string.
export const HAIR_COLORS = [
- '#0b0b0b', '#1c1310', '#2a1a0f', '#3b2412', '#4a2f1a',
- '#5c3a1e', '#6b4423', '#7a5230', '#8d6239', '#a87c4f',
- '#c69a63', '#d9b380', '#e3c79a', '#9a9a9a', '#d8d8d8',
+ '#0b0b0b',
+ '#1c1310',
+ '#2a1a0f',
+ '#3b2412',
+ '#4a2f1a',
+ '#5c3a1e',
+ '#6b4423',
+ '#7a5230',
+ '#8d6239',
+ '#a87c4f',
+ '#c69a63',
+ '#d9b380',
+ '#e3c79a',
+ '#9a9a9a',
+ '#d8d8d8',
];
// Avaturn eye colors are an enum keyed by name; these are the standard set.
@@ -140,9 +163,7 @@ export function pickRandomLook(seed, { bodies, assets, bodyType }) {
// fall back to the whole list so we always pick something real.
let bodyPool = Array.isArray(bodies) ? bodies.filter((b) => b && b.id) : [];
if (bodyType) {
- const matched = bodyPool.filter(
- (b) => normalizeSlot(b.gender ?? b.body_type) === bodyType,
- );
+ const matched = bodyPool.filter((b) => normalizeSlot(b.gender ?? b.body_type) === bodyType);
if (matched.length) bodyPool = matched;
}
const body = pickOne(bodyPool, rng);
@@ -216,7 +237,11 @@ export const AGE_BANDS = [
{ key: 'young-adult', desc: 'in their early twenties', grayBias: 0 },
{ key: 'adult', desc: 'in their early thirties', grayBias: 0.05 },
{ key: 'middle-aged', desc: 'in their late forties, a few soft laugh lines', grayBias: 0.3 },
- { key: 'senior', desc: 'in their late sixties, natural wrinkles and gentle age lines', grayBias: 0.85 },
+ {
+ key: 'senior',
+ desc: 'in their late sixties, natural wrinkles and gentle age lines',
+ grayBias: 0.85,
+ },
];
// A broad, respectful spread of appearances. `skin` is the gentle Avaturn
diff --git a/api/admin/seeder.js b/api/admin/seeder.js
index 00b9524db..b80ae7fe3 100644
--- a/api/admin/seeder.js
+++ b/api/admin/seeder.js
@@ -89,7 +89,9 @@ async function loadRecent() {
const joints = Number(meta.skeleton_joint_count) || null;
const p = meta.profile || null;
// "East Asian woman, senior" style label for photo-lane avatars.
- const person = p ? [p.ethnicity, p.gender, p.age].filter(Boolean).join(' · ').replace(/-/g, ' ') : null;
+ const person = p
+ ? [p.ethnicity, p.gender, p.age].filter(Boolean).join(' · ').replace(/-/g, ' ')
+ : null;
return {
id: a.id,
slug: a.slug,
diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.js
index a9f0fa787..f3567541d 100644
--- a/api/cron/avaturn-seed-cron.js
+++ b/api/cron/avaturn-seed-cron.js
@@ -36,7 +36,11 @@ import { putObject } from '../_lib/r2.js';
import { inspectGlb } from '../_lib/glb-inspect.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 {
+ generateDiverseFace,
+ createAvaturnSession,
+ photoLaneConfigured,
+} from '../_lib/avaturn-photo.js';
import { randomUUID } from 'node:crypto';
const CIRCUIT_NAME = 'avaturn-seed';
@@ -89,12 +93,16 @@ async function runOnce() {
const circuit = await circuitState(CIRCUIT_NAME);
if (circuit.open) {
const minsLeft = Math.ceil((circuit.openUntil - Date.now()) / 60_000);
- return { skipped: true, reason: `circuit open for ${minsLeft}m more (${circuit.failures} failures)` };
+ return {
+ skipped: true,
+ reason: `circuit open for ${minsLeft}m more (${circuit.failures} failures)`,
+ };
}
const baseWord = OG_USERNAMES[Math.floor(Math.random() * OG_USERNAMES.length)];
const username = await claimUsername(baseWord);
- if (!username) return { skipped: true, reason: 'could not claim OG username — retry next tick' };
+ if (!username)
+ return { skipped: true, reason: 'could not claim OG username — retry next tick' };
const displayName = username.replace(/\d+$/, '').replace(/\b\w/g, (c) => c.toUpperCase());
const email = `${username}@avaturn.three.ws`;
@@ -119,7 +127,8 @@ async function runOnce() {
let sessionUrl;
let profile = null;
let faceModel = null;
- const photoLane = photoLaneConfigured() && (await isFlagEnabled('avaturn_seed_photo', { fallback: false }));
+ const photoLane =
+ photoLaneConfigured() && (await isFlagEnabled('avaturn_seed_photo', { fallback: false }));
if (photoLane) {
try {
profile = pickDiversityProfile(seed);
@@ -130,14 +139,22 @@ async function runOnce() {
} catch (err) {
profile = null;
sessionUrl = undefined;
- console.warn('[avaturn-seed] photo lane failed, using catalog lane:', err?.message || err);
+ console.warn(
+ '[avaturn-seed] photo lane failed, using catalog lane:',
+ err?.message || err,
+ );
}
}
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 });
+ const { glbBytes, exportUrl, look } = await exportRandomAvaturnAvatar({
+ seed,
+ bodyType,
+ sessionUrl,
+ keepBody: !!sessionUrl,
+ });
const slug = toSlug(displayName);
const storageKey = `u/${user.id}/${slug}.glb`;
@@ -185,7 +202,9 @@ async function runOnce() {
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 tags = profile
+ ? ['avatar', 'avaturn', 'human', profile.gender]
+ : ['avatar', 'avaturn'];
await sql`
insert into avatars
@@ -206,9 +225,20 @@ async function runOnce() {
`;
await circuitRecordSuccess(CIRCUIT_NAME);
- return { ok: true, username, user_id: user.id, slug, size_bytes: glbBytes.length, body_type: bodyType, lane: profile ? 'photo' : 'catalog' };
+ return {
+ ok: true,
+ username,
+ user_id: user.id,
+ slug,
+ size_bytes: glbBytes.length,
+ body_type: bodyType,
+ lane: profile ? 'photo' : 'catalog',
+ };
} catch (err) {
- await circuitRecordFailure(CIRCUIT_NAME, { threshold: CIRCUIT_THRESHOLD, baseMs: CIRCUIT_BASE_MS });
+ await circuitRecordFailure(CIRCUIT_NAME, {
+ threshold: CIRCUIT_THRESHOLD,
+ baseMs: CIRCUIT_BASE_MS,
+ });
// Roll back the synthetic account so the next tick starts clean.
await sql`delete from users where id = ${user.id}`.catch(() => {});
return { ok: false, reason: `${err?.code || 'error'}: ${err?.message || err}` };
@@ -234,7 +264,11 @@ export default wrapCron(async (req, res) => {
// Single headless export in flight at a time, fleet-wide.
const slot = await acquireBlockingSlot(CIRCUIT_NAME, { max: 1, ttlMs: SLOT_TTL_MS });
if (!slot.ok) {
- return json(res, 200, { ok: true, skipped: 'in_flight', reason: 'a prior export is still running' });
+ return json(res, 200, {
+ ok: true,
+ skipped: 'in_flight',
+ reason: 'a prior export is still running',
+ });
}
try {
const result = await runOnce();
diff --git a/docs/ops/runtime-flags.md b/docs/ops/runtime-flags.md
index 19591957a..00311faf7 100644
--- a/docs/ops/runtime-flags.md
+++ b/docs/ops/runtime-flags.md
@@ -60,3 +60,4 @@ one-line description.
| key | env fallback | controls |
|---|---|---|
| `avaturn_seed` | `AVATURN_SEED_ENABLED` | The per-minute headless [Avaturn seed cron](../../api/cron/avaturn-seed-cron.js) — forges a fully-rigged Avaturn avatar and publishes it public to the gallery. Off by default; arm it to start seeding. |
+| `avaturn_seed_photo` | _(none)_ | Diverse-humans lane. When on **and** `AVATURN_API_KEY` is set, each tick draws a person from a gender/age/ethnicity/build matrix, generates their face ([avaturn-photo.js](../../api/_lib/avaturn-photo.js) → text→image), and reconstructs it with Avaturn v2 into a distinct rigged human — so the gallery fills with genuinely different people, not one base face reskinned. Falls back to the catalog lane on any failure. Requires `avaturn_seed` to also be on. |
diff --git a/public/internal/avaturn-forge.html b/public/internal/avaturn-forge.html
index cd0a158b9..2ed7a39c1 100644
--- a/public/internal/avaturn-forge.html
+++ b/public/internal/avaturn-forge.html
@@ -118,6 +118,9 @@ function extractExportUrl(result) {
const params = new URLSearchParams(location.search);
const bodyType = params.get('bodyType') || 'male';
const seed = params.get('seed') || String(hashSeed('fallback'));
+ // Photo-session avatars are a reconstructed person: keep that body/face and
+ // only vary outfit + colors. Catalog sessions swap to a random base body.
+ const keepBody = params.get('keepBody') === '1';
// Use an explicit session URL if one was supplied (authenticated path),
// otherwise drive the public demo editor — no API key needed.
const editorUrl = params.get('session') || defaultEditorUrl(bodyType);
@@ -150,7 +153,8 @@ function extractExportUrl(result) {
window.__avaturnLook = look;
step('apply-body');
- if (look.bodyId) await quiet(sdk.setActiveBody(look.bodyId));
+ // keepBody: preserve the photo-reconstructed person; only catalog runs swap body.
+ if (!keepBody && look.bodyId) await quiet(sdk.setActiveBody(look.bodyId));
step('apply-assets');
for (const id of look.assetIds) await quiet(sdk.setActiveAsset(id));
diff --git a/src/admin-seeder.js b/src/admin-seeder.js
index 557f7c94e..89b33ce05 100644
--- a/src/admin-seeder.js
+++ b/src/admin-seeder.js
@@ -164,7 +164,12 @@ function renderGallery(recent) {
if (!a.glb_url) return '';
const name = esc(a.name || 'Avatar');
const joints = a.joints ? `${a.joints} bones` : 'rigged';
- const body = a.body_type ? `<span class="sd-chip body">${esc(a.body_type)}</span>` : '';
+ // Photo-lane avatars show the person they depict; catalog-lane show body type.
+ const tag = a.person || a.body_type;
+ const body = tag ? `<span class="sd-chip body">${esc(tag)}</span>` : '';
+ const sub = a.person
+ ? `${esc(a.person)} · ${fmtAgo(a.created_at)}`
+ : fmtAgo(a.created_at);
const open = a.profile_url
? `<a class="sd-card-open" href="${esc(a.profile_url)}" target="_blank" rel="noopener" title="Open profile">↗</a>`
: `<a class="sd-card-open" href="${esc(a.glb_url)}" target="_blank" rel="noopener" title="Open model">↗</a>`;
@@ -184,7 +189,7 @@ function renderGallery(recent) {
<div class="sd-card-body">
<div style="min-width:0">
<div class="sd-card-name">${name}</div>
- <div class="sd-card-sub">${fmtAgo(a.created_at)}</div>
+ <div class="sd-card-sub">${sub}</div>
</div>
${open}
</div>