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): Replicate-backed regen provider + persona hub docs

nirholasdd22854b3464
diff --git a/.env.example b/.env.example
index 47d10d92e..8653054ad 100644
--- a/.env.example
+++ b/.env.example
@@ -81,10 +81,26 @@ VITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/
VITE_AVATURN_DEVELOPER_ID=
# Avatar regeneration provider (optional)
-# Set to "stub" for testing, or a provider name when configured.
-# Unset or "none" → API returns 501 regen_unconfigured.
+# Set to "stub" for queue-only testing, "replicate" for a real ML backend
+# (see below), or leave as "none" → /api/avatars/regenerate returns 501.
AVATAR_REGEN_PROVIDER=none
+# Replicate (when AVATAR_REGEN_PROVIDER=replicate). Get an API token at
+# https://replicate.com/account/api-tokens. Each mode maps to a model version
+# hash from replicate.com — pick a model that takes a GLB URL (or text prompt
+# for restyle) and returns a GLB asset.
+#
+# Recommended starting points:
+# restyle → text-to-3D models like Hunyuan3D or Tripo (use their replicate page)
+# remesh → mesh-cleanup pipelines
+# retex → image-conditioned texturing models
+# rerig → RigNet / Mixamo-style auto-rig models
+REPLICATE_API_TOKEN=
+REPLICATE_RESTYLE_MODEL=
+REPLICATE_REMESH_MODEL=
+REPLICATE_RETEX_MODEL=
+REPLICATE_RERIG_MODEL=
+
# ── ERC-7710 Delegation Relayer (POST /api/permissions/redeem) ───────────────
# Enable the server-side relayer endpoint (default: false).
PERMISSIONS_RELAYER_ENABLED=false
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.js
new file mode 100644
index 000000000..d9cc5c2d1
--- /dev/null
+++ b/api/_providers/replicate.js
@@ -0,0 +1,194 @@
+// Replicate provider for avatar regeneration jobs.
+//
+// Implements the contract documented in api/avatars/REGENERATE.md:
+// - submit(request) → { jobId, eta, extJobId }
+// - status(extJobId) → { status, resultGlbUrl?, error? }
+//
+// Each regen `mode` maps to a Replicate model that takes a GLB or image and
+// returns a regenerated GLB asset. The choice of model is configurable via
+// env so the provider can be tuned without code changes:
+//
+// REPLICATE_API_TOKEN — required, from replicate.com/account
+// REPLICATE_RESTYLE_MODEL — version hash for text-to-3D (Hunyuan3D, Tripo, etc.)
+// REPLICATE_REMESH_MODEL — version hash for mesh cleanup
+// REPLICATE_RETEX_MODEL — version hash for re-texturing
+// REPLICATE_RERIG_MODEL — version hash for rig regeneration
+//
+// At submit time the provider POSTs to the Replicate predictions API. The
+// returned prediction id is stored as `ext_job_id`. The status endpoint
+// polls Replicate to translate the predictions API state into our 4-state
+// machine.
+
+const REPLICATE_BASE = 'https://api.replicate.com/v1';
+
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env && process.env[name]) return process.env[name];
+ return null;
+}
+
+const MODE_TO_ENV = Object.freeze({
+ restyle: 'REPLICATE_RESTYLE_MODEL',
+ remesh: 'REPLICATE_REMESH_MODEL',
+ retex: 'REPLICATE_RETEX_MODEL',
+ rerig: 'REPLICATE_RERIG_MODEL',
+});
+
+function modelForMode(mode) {
+ const envName = MODE_TO_ENV[mode];
+ if (!envName) return null;
+ return readEnv(envName);
+}
+
+// Map our 4 modes onto the input shape each model expects. The exact shape
+// depends on the model; we default to a generic { source_url, prompt, mode }
+// payload and let provider-side models pick the fields they care about.
+// Caller-supplied params override the default shape.
+function buildInput({ mode, sourceUrl, params }) {
+ const base = {
+ mode,
+ source_url: sourceUrl,
+ source_glb: sourceUrl,
+ // Pass through every caller param; later spread wins so explicit
+ // overrides take precedence over the defaults above.
+ prompt: typeof params?.prompt === 'string' ? params.prompt : undefined,
+ };
+ return { ...base, ...(params || {}) };
+}
+
+function translateStatus(replicateStatus) {
+ switch (replicateStatus) {
+ case 'starting':
+ case 'queued':
+ return 'queued';
+ case 'processing':
+ return 'running';
+ case 'succeeded':
+ return 'done';
+ case 'failed':
+ case 'canceled':
+ return 'failed';
+ default:
+ return 'queued';
+ }
+}
+
+// Extract the first plausible GLB url from a Replicate `output` field. Different
+// models emit different shapes — sometimes a string, sometimes an array, sometimes
+// a nested object — so we accept a small whitelist of common forms.
+function extractGlbUrl(output) {
+ if (!output) return null;
+ if (typeof output === 'string') return output;
+ if (Array.isArray(output)) {
+ for (const v of output) {
+ if (typeof v === 'string' && /\.glb(\?|$)/i.test(v)) return v;
+ }
+ // Fall back to the first stringy entry if nothing matched the .glb pattern.
+ for (const v of output) {
+ if (typeof v === 'string' && /^https?:\/\//.test(v)) return v;
+ }
+ }
+ if (typeof output === 'object') {
+ for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {
+ if (typeof output[key] === 'string') return output[key];
+ }
+ }
+ return null;
+}
+
+export function createRegenProvider() {
+ const token = readEnv('REPLICATE_API_TOKEN');
+ if (!token) {
+ throw new Error('REPLICATE_API_TOKEN env var is required for the replicate provider');
+ }
+
+ const authHeaders = {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ };
+
+ return {
+ async submit(request) {
+ const version = modelForMode(request.mode);
+ if (!version) {
+ throw Object.assign(
+ new Error(
+ `replicate provider has no model configured for mode "${request.mode}" — set ${MODE_TO_ENV[request.mode] || 'the matching REPLICATE_*_MODEL env var'}`,
+ ),
+ { code: 'mode_unconfigured', status: 501 },
+ );
+ }
+
+ const input = buildInput({
+ mode: request.mode,
+ sourceUrl: request.sourceUrl,
+ params: request.params,
+ });
+
+ let response;
+ try {
+ response = await fetch(`${REPLICATE_BASE}/predictions`, {
+ method: 'POST',
+ headers: authHeaders,
+ body: JSON.stringify({ version, input }),
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`replicate submit failed: ${err?.message}`), {
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ }
+
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ throw Object.assign(
+ new Error(data?.detail || data?.title || `replicate returned ${response.status}`),
+ { code: 'provider_error', status: 502, providerStatus: response.status },
+ );
+ }
+
+ return {
+ extJobId: data.id,
+ eta: typeof data.eta === 'number' ? data.eta : undefined,
+ rawStatus: data.status,
+ };
+ },
+
+ async status(extJobId) {
+ if (!extJobId) {
+ return { status: 'failed', error: 'missing ext_job_id' };
+ }
+
+ let response;
+ try {
+ response = await fetch(`${REPLICATE_BASE}/predictions/${encodeURIComponent(extJobId)}`, {
+ headers: authHeaders,
+ });
+ } catch (err) {
+ return { status: 'running', error: `provider poll failed: ${err?.message}` };
+ }
+
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ return {
+ status: 'failed',
+ error: data?.detail || `replicate returned ${response.status}`,
+ };
+ }
+
+ const status = translateStatus(data.status);
+ const result = {
+ status,
+ rawStatus: data.status,
+ };
+
+ if (status === 'done') {
+ const glb = extractGlbUrl(data.output);
+ if (glb) result.resultGlbUrl = glb;
+ else result.error = 'model finished but no GLB found in output';
+ }
+ if (status === 'failed' && data.error) result.error = String(data.error);
+
+ return result;
+ },
+ };
+}
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 740252640..3dcc2cfce 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -2,7 +2,7 @@
// presign, public, regenerate, regenerate-status
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { presignUpload, headObject, r2 } from '../_lib/r2.js';
+import { presignUpload, headObject, r2, publicUrl } from '../_lib/r2.js';
import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';
import { listAvatars, createAvatar } from '../_lib/avatars.js';
import { HeadObjectCommand } from '@aws-sdk/client-s3';
@@ -15,6 +15,35 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { z } from 'zod';
import { randomUUID } from 'crypto';
+// ── regen provider loader ─────────────────────────────────────────────────────
+// Dynamically import a provider module by name so we don't pay the cost of
+// loading e.g. the Replicate SDK on every request when regeneration is unused.
+// Cached per-process after first load.
+let _regenProviderCache = null;
+let _regenProviderName = null;
+async function getRegenProvider() {
+ const name = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();
+ if (name === 'none' || !name) return { name, instance: null };
+ if (_regenProviderCache && _regenProviderName === name) {
+ return { name, instance: _regenProviderCache };
+ }
+ if (name === 'stub') {
+ _regenProviderCache = null;
+ _regenProviderName = name;
+ return { name, instance: null };
+ }
+ if (name === 'replicate') {
+ const mod = await import('../_providers/replicate.js');
+ _regenProviderCache = mod.createRegenProvider();
+ _regenProviderName = name;
+ return { name, instance: _regenProviderCache };
+ }
+ throw Object.assign(new Error(`unknown AVATAR_REGEN_PROVIDER: ${name}`), {
+ code: 'regen_provider_unknown',
+ status: 501,
+ });
+}
+
// ── presign ───────────────────────────────────────────────────────────────────
async function resolvePresignUser(req, requiredScope) {
@@ -86,14 +115,69 @@ const handleRegenerate = wrap(async (req, res) => {
const body = parse(regenerateSchema, await readJson(req));
const rows = await sql`select id, name, storage_key from avatars where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null limit 1`;
if (!rows[0]) return error(res, 404, 'not_found', 'source avatar not found or not owned');
- const provider = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();
- if (provider === 'none' || !provider) return error(res, 501, 'regen_unconfigured', 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.');
- if (provider === 'stub') {
+
+ let provider;
+ try {
+ provider = await getRegenProvider();
+ } catch (err) {
+ return error(res, err.status || 501, err.code || 'regen_provider_error', err.message);
+ }
+
+ if (provider.name === 'none') {
+ return error(
+ res,
+ 501,
+ 'regen_unconfigured',
+ 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',
+ );
+ }
+
+ if (provider.name === 'stub') {
const jobId = `stub-${randomUUID()}`;
- await sql`insert into avatar_regen_jobs (job_id, user_id, source_avatar_id, mode, params, status, created_at) values (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', now())`;
+ await sql`
+ insert into avatar_regen_jobs
+ (job_id, user_id, source_avatar_id, mode, params, status, provider, created_at, updated_at)
+ values
+ (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', 'stub', now(), now())
+ `;
return json(res, 202, { ok: true, jobId, status: 'queued', eta: null });
}
- return error(res, 501, 'regen_provider_error', `Unknown provider: ${provider}`);
+
+ // Real provider — submit the job, persist the external id.
+ const sourceUrl = publicUrl(rows[0].storage_key);
+ let submission;
+ try {
+ submission = await provider.instance.submit({
+ userId,
+ sourceAvatarId: body.sourceAvatarId,
+ mode: body.mode,
+ params: body.params ?? {},
+ sourceUrl,
+ sourceStorageKey: rows[0].storage_key,
+ });
+ } catch (err) {
+ return error(
+ res,
+ err.status || 502,
+ err.code || 'regen_provider_error',
+ err.message || 'provider rejected submission',
+ );
+ }
+
+ const jobId = `${provider.name}-${randomUUID()}`;
+ await sql`
+ insert into avatar_regen_jobs
+ (job_id, user_id, source_avatar_id, mode, params, status, provider, ext_job_id, created_at, updated_at)
+ values
+ (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', ${provider.name}, ${submission.extJobId ?? null}, now(), now())
+ `;
+ return json(res, 202, {
+ ok: true,
+ jobId,
+ status: 'queued',
+ eta: submission.eta ?? null,
+ provider: provider.name,
+ });
});
// ── regenerate-status ─────────────────────────────────────────────────────────
@@ -109,12 +193,59 @@ const handleRegenerateStatus = wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const jobId = url.searchParams.get('jobId');
if (!jobId) return error(res, 400, 'invalid_request', 'jobId required');
- const rows = await sql`select job_id, status, result_avatar_id, error, created_at from avatar_regen_jobs where job_id = ${jobId} and user_id = ${userId} limit 1`;
+ const rows = await sql`
+ select job_id, status, result_avatar_id, result_glb_url, error, provider, ext_job_id, created_at
+ from avatar_regen_jobs
+ where job_id = ${jobId} and user_id = ${userId}
+ limit 1
+ `;
if (!rows[0]) return error(res, 404, 'not_found', 'job not found');
- const job = rows[0];
+ let job = rows[0];
+
+ // Pull a fresh status from the provider when the job is still in flight
+ // and we have an external id to query. The status endpoint serves as our
+ // poll trigger — no separate cron needed for short-lived jobs.
+ if ((job.status === 'queued' || job.status === 'running') && job.provider && job.provider !== 'stub' && job.ext_job_id) {
+ try {
+ const provider = await getRegenProvider();
+ if (provider.instance) {
+ const update = await provider.instance.status(job.ext_job_id);
+ const nextStatus = update.status;
+ const nextResultUrl = update.resultGlbUrl ?? null;
+ const nextError = update.error ?? null;
+ if (
+ nextStatus !== job.status ||
+ nextResultUrl !== job.result_glb_url ||
+ nextError !== job.error
+ ) {
+ await sql`
+ update avatar_regen_jobs
+ set status = ${nextStatus},
+ result_glb_url = ${nextResultUrl},
+ error = ${nextError},
+ updated_at = now()
+ where job_id = ${jobId} and user_id = ${userId}
+ `;
+ job = {
+ ...job,
+ status: nextStatus,
+ result_glb_url: nextResultUrl,
+ error: nextError,
+ };
+ }
+ }
+ } catch (err) {
+ // Surface the polling error but don't fail the request — the job
+ // row stays as-is and the client can retry later.
+ job = { ...job, error: job.error || `provider poll failed: ${err?.message}` };
+ }
+ }
+
const response = { ok: true, jobId: job.job_id, status: job.status };
if (job.result_avatar_id) response.resultAvatarId = job.result_avatar_id;
+ if (job.result_glb_url) response.resultGlbUrl = job.result_glb_url;
if (job.error) response.error = job.error;
+ if (job.provider) response.provider = job.provider;
return json(res, 200, response);
});
diff --git a/docs/persona-hub.md b/docs/persona-hub.md
new file mode 100644
index 000000000..19c5a9fa0
--- /dev/null
+++ b/docs/persona-hub.md
@@ -0,0 +1,143 @@
+# Persona Hub
+
+Persona Hub is three.ws's cross-app sign-in: a user creates and stores their three.ws avatar once, then any site that embeds the `<three-ws-signin>` widget can ask the user to share that avatar in a single click. The user's three.ws session never leaves three.ws; the tenant receives only a short-lived JWT bearing the avatar URL.
+
+This is the architectural answer to "what Ready Player Me's Hub was, before it was acquired" — same pattern (one avatar, hundreds of sites), redesigned around three.ws's auth stack.
+
+---
+
+## How it works
+
+```
+ tenant site three.ws (popup) three.ws backend
+ │ │ │
+ 1. ├── <three-ws-signin> ───────┤ │
+ │ button clicked │ │
+ │ │ │
+ 2. ├── window.open() ──────────►│ /persona/authorize.html │
+ │ │ (consent screen) │
+ │ │ │
+ 3. │ │ GET /api/auth/persona/me ───►│
+ │ │ ◄────────── user + avatars │
+ │ │ │
+ 4. │ │ user picks avatar, clicks │
+ │ │ "Authorize" │
+ │ │ │
+ 5. │ │ POST /api/auth/persona/issue►│
+ │ │ body { tenant_origin, │
+ │ │ avatar_id } │
+ │ │ ◄──── { token, avatar } │
+ │ │ │
+ 6. │◄── postMessage ────────────┤ closes popup │
+ │ { token, avatar } │ │
+ │ │ │
+ 7. ├── (optional) verify │ │
+ │ GET /api/auth/persona/verify?token=…&audience=… ──────►│
+ │ ◄────────────── { sub, avatar, exp } │
+```
+
+The cookie carrying the user's three.ws session is `__Host-sid` — locked to the exact host. The popup runs on three.ws so the consent screen can read it; the tenant never sees it. Cross-site avatar sharing happens entirely via the postMessage-delivered JWT.
+
+---
+
+## Embedding the widget
+
+```html
+<script src="https://three.ws/persona/widget.js" defer></script>
+
+<three-ws-signin
+ client-origin="https://coolgame.three.ws"
+ label="Sign in with three.ws">
+</three-ws-signin>
+```
+
+Listen for the result:
+
+```js
+const el = document.querySelector('three-ws-signin');
+el.addEventListener('three-ws:authorized', (e) => {
+ const { token, avatar, expires_in } = e.detail;
+ // avatar: { id, url, thumbnail_url, name }
+ // token: 24h JWT — verify server-side before trusting
+});
+el.addEventListener('three-ws:cancelled', () => {
+ // user closed the popup or hit Cancel
+});
+```
+
+### Programmatic API
+
+If you don't want a custom element, use the promise wrapper:
+
+```js
+const result = await window.ThreeWsPersona.signIn({
+ clientOrigin: 'https://coolgame.three.ws',
+});
+// result.token, result.avatar
+```
+
+---
+
+## Allowed tenant origins
+
+`/api/auth/persona/issue` accepts these origins for `tenant_origin`:
+
+- `https://three.ws`
+- `https://<anything>.three.ws`
+- `http://localhost[:port]` and `http://127.0.0.1[:port]` (dev only)
+
+Other origins return `400 invalid_request`. This is the chokepoint that prevents arbitrary sites from minting tokens claiming any user's three.ws avatar. Add subdomains by updating `validateTenantOrigin()` in [api/auth/persona/[action].js](../api/auth/persona/%5Baction%5D.js).
+
+---
+
+## Verifying tokens server-side
+
+Tenants verify the token from their backend:
+
+```js
+const res = await fetch(
+ `https://three.ws/api/auth/persona/verify?token=${encodeURIComponent(token)}&audience=${encodeURIComponent('https://coolgame.three.ws')}`,
+);
+const claims = await res.json();
+if (!res.ok) throw new Error(claims.error_description);
+
+// claims.sub — three.ws user id (stable across sessions)
+// claims.aud — must match the tenant origin you embedded with
+// claims.avatar — { id, url, thumbnail_url, name }
+// claims.scope — "persona:read avatar:read"
+// claims.exp — Unix timestamp
+```
+
+Tokens are HS256-signed with `JWT_SECRET`. Tenants that prefer offline verification can use the JWKS endpoint at `/.well-known/jwks.json` (not yet shipped — use `/verify` for now).
+
+---
+
+## Endpoint reference
+
+| Endpoint | Auth | Description |
+|---|---|---|
+| `GET /api/auth/persona/me` | three.ws session | Lists the user's avatars for the consent UI. |
+| `POST /api/auth/persona/issue` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
+| `GET /api/auth/persona/verify?token=&audience=` | none | Verifies a token's signature, issuer, audience, expiry. |
+
+JWT claims:
+
+| Claim | Value |
+|---|---|
+| `iss` | `https://three.ws` |
+| `sub` | three.ws user id |
+| `aud` | tenant origin (validated against the issued audience) |
+| `scope` | `persona:read avatar:read` |
+| `token_use` | `persona` |
+| `avatar` | `{ id, url, thumbnail_url, name }` |
+| `iat` / `exp` | issued at / expires at (24h TTL) |
+| `jti` | unique token id |
+
+---
+
+## Threat model notes
+
+- **Origin spoofing.** The popup posts back only to the `tenant_origin` it was opened with. The browser enforces this via the second argument to `postMessage`, so a malicious script on another tab cannot receive the token.
+- **Replay between tenants.** Each token's `aud` is bound to the issuing tenant. `verify` requires the caller to supply the audience — if a token issued for `coolgame.three.ws` is replayed against `evilgame.three.ws`, verification fails.
+- **State CSRF.** The widget generates a per-popup `state` nonce; the popup echoes it back in the postMessage payload. The widget rejects messages whose `state` doesn't match.
+- **Token theft via XSS on tenant.** A compromised tenant could leak tokens, but the blast radius is limited to that user's avatar URL (already publicly fetchable in most flows) plus their three.ws user id. No write scopes are granted by a persona token.
diff --git a/migrations/20260517000000_avatar_regen_jobs.sql b/migrations/20260517000000_avatar_regen_jobs.sql
new file mode 100644
index 000000000..31afde1a8
--- /dev/null
+++ b/migrations/20260517000000_avatar_regen_jobs.sql
@@ -0,0 +1,29 @@
+-- Avatar regeneration job table.
+--
+-- Tracks the lifecycle of asynchronous ML regeneration jobs (re-mesh, re-texture,
+-- re-rig, re-style). The persistence here is the source of truth; provider-side
+-- IDs (Replicate prediction id, Meshy task id, etc.) live in ext_job_id so the
+-- status endpoint can re-query the provider.
+
+CREATE TABLE IF NOT EXISTS avatar_regen_jobs (
+ job_id text PRIMARY KEY,
+ user_id uuid NOT NULL,
+ source_avatar_id uuid NOT NULL,
+ mode text NOT NULL, -- remesh | retex | rerig | restyle
+ params jsonb,
+ status text NOT NULL, -- queued | running | done | failed
+ provider text, -- replicate | meshy | stub | …
+ ext_job_id text, -- provider-side job id
+ result_glb_url text, -- temporary URL returned by provider
+ result_avatar_id uuid, -- our avatar id after import
+ error text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS idx_avatar_regen_jobs_user
+ ON avatar_regen_jobs (user_id, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS idx_avatar_regen_jobs_status
+ ON avatar_regen_jobs (status)
+ WHERE status IN ('queued', 'running');