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
selfie reconstruct pipeline + R2 CORS auto-apply + save-flow resilience
oversteppingf0d2422d8e9f
diff --git a/.env.example b/.env.exampleindex 73187ce70..d21813a1d 100644--- a/.env.example+++ b/.env.example@@ -90,10 +90,15 @@ AVATURN_API_URL=https://api.avaturn.meVITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/VITE_AVATURN_DEVELOPER_ID=-# Avatar regeneration provider (optional)-# 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+# Avatar regeneration provider (optional, auto-detected when omitted).+# Resolution order when AVATAR_REGEN_PROVIDER is unset:+# 1. REPLICATE_API_TOKEN present → "replicate" (paid, fast, reliable)+# 2. GCP_RECONSTRUCTION_URL set → "gcp" (self-hosted, custom GPU)+# 3. HF_TOKEN present → "huggingface" (free HF Spaces queue)+# 4. otherwise → "none" (501 returned)+# Set this explicitly to force a provider (or "stub" for queue-only testing,+# or "none" to disable selfie reconstruct entirely).+AVATAR_REGEN_PROVIDER=# Replicate (when AVATAR_REGEN_PROVIDER=replicate). Get an API token at# https://replicate.com/account/api-tokens. Each mode maps to a model version@@ -117,6 +122,22 @@ REPLICATE_REMESH_MODEL=REPLICATE_RETEX_MODEL=REPLICATE_RERIG_MODEL=+# Hugging Face provider (when AVATAR_REGEN_PROVIDER=huggingface, or auto-+# detected when only HF_TOKEN is set). Read-only token is sufficient since+# the default target Space is public. Get one at huggingface.co/settings/tokens.+#+# Hits the Gradio /call/<api_name> queue endpoint of a public image-to-3D+# Space. Default targets tencent/Hunyuan3D-2's generation_all API, which+# accepts our 3 selfie photos as mv_image_{front,left,right} and returns+# a textured GLB. Override the target by setting the two env vars below.+#+# Reliability note: HF Spaces share free GPU pools (ZeroGPU). Queue waits+# and per-Space quotas can cause 30s-2min latency or outright rejection+# during peak hours. For production traffic, prefer REPLICATE_API_TOKEN.+HF_TOKEN=+HF_RECONSTRUCT_SPACE=tencent/Hunyuan3D-2+HF_RECONSTRUCT_API_NAME=generation_all+# ── Persona Hub (optional) ────────────────────────────────────────────────────# When set, /api/auth/persona/issue signs tokens with ES256 (asymmetric) so# tenants can verify offline via the JWK Set at /.well-known/jwks.json. Whendiff --git a/api/_providers/huggingface.js b/api/_providers/huggingface.jsnew file mode 100644index 000000000..e30e02c18--- /dev/null+++ b/api/_providers/huggingface.js@@ -0,0 +1,327 @@+// Hugging Face provider for avatar reconstruction.+//+// Calls a HF Space's modern Gradio /call/<api_name> endpoint for image-to-3D+// inference. Default target: tencent/Hunyuan3D-2's `/generation_all` endpoint,+// which takes 4 multi-view photos (front/back/left/right) and produces a+// textured GLB — a natural fit for the selfie pipeline's 3-photo capture+// (frontal → mv_image_front, left → mv_image_left, right → mv_image_right;+// back is left null).+//+// Submit is BLOCKING: Gradio queue state lives in the server-side event_id+// and there's no "reconnect to in-flight job" — once /call/<api>/<event_id>+// SSE is consumed, the result is gone. The reconstruct endpoint's+// maxDuration is bumped to 300s in vercel.json to absorb queue wait+// (typically <30s) plus processing (Hunyuan3D-2 generation_all runs 30-90s+// on the Space's GPU).+//+// status() echoes the resultGlbUrl back from a packed extJobId so the+// regenerate-status poll loop materializes the avatar without re-hitting HF.+//+// Env:+// HF_TOKEN — required, from huggingface.co/settings/tokens+// (read-only token is sufficient; the Space is public)+// HF_RECONSTRUCT_SPACE — default 'tencent/Hunyuan3D-2'+// HF_RECONSTRUCT_API_NAME — default 'generation_all'++const HF_INFERENCE_TIMEOUT_MS = 280_000; // leave headroom for response framing+const HF_DEFAULT_SPACE = 'tencent/Hunyuan3D-2';+const HF_DEFAULT_API = 'generation_all';++function readEnv(name) {+ if (typeof process !== 'undefined' && process.env && process.env[name]) return process.env[name];+ return null;+}++function packExtJobId(payload) {+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');+}+function unpackExtJobId(extJobId) {+ try {+ return JSON.parse(Buffer.from(extJobId, 'base64url').toString('utf8'));+ } catch {+ return null;+ }+}++function spaceBaseUrl(slug) {+ const host = slug.replace(/\//g, '-').toLowerCase();+ return `https://${host}.hf.space`;+}++// Gradio file-component input. data: URIs and http(s) URLs both work; the+// Space's preprocessor will fetch URLs server-side.+function toFileData(imageUrl) {+ if (!imageUrl) return null;+ return {+ path: imageUrl,+ url: imageUrl,+ meta: { _type: 'gradio.FileData' },+ };+}++function withTimeout(promise, ms, message) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(message)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++// Walk a Gradio output tree for the first GLB-looking URL. The Space returns+// outputs like:+// [ { path: "/tmp/x.glb", url: "https://...hf.space/file=/tmp/x.glb", ... },+// { ...white-mesh file...}, "Output text", {...stats...}, 1234 ]+// We want the *first* file: it's the textured mesh from /generation_all.+function extractFirstGlbUrl(data) {+ const visit = (node) => {+ if (!node) return null;+ if (typeof node === 'string') {+ if (/^https?:\/\/.+\.glb($|\?)/i.test(node)) return node;+ return null;+ }+ if (Array.isArray(node)) {+ for (const child of node) {+ const found = visit(child);+ if (found) return found;+ }+ return null;+ }+ if (typeof node === 'object') {+ if (typeof node.url === 'string' && /\.glb($|\?)/i.test(node.url)) return node.url;+ if (typeof node.path === 'string' && /\.glb($|\?)/i.test(node.path)) return node.path;+ for (const v of Object.values(node)) {+ const found = visit(v);+ if (found) return found;+ }+ }+ return null;+ };+ return visit(data);+}++// Build the 13-arg payload for tencent/Hunyuan3D-2 /generation_all.+//+// Parameters in order:+// caption(str), image(file), mv_front, mv_back, mv_left, mv_right,+// steps(int), guidance_scale(float), seed(int), octree_resolution(int),+// check_box_rembg(bool), num_chunks(int), randomize_seed(bool)+//+// We default to the Space's own defaults so users get a baseline-quality+// result; selfie callers can override via params.steps / params.seed / etc.+function buildHunyuanPayload({ photos, params }) {+ const [frontal, left, right] = photos;+ return [+ params?.caption ?? '',+ toFileData(params?.image || frontal),+ toFileData(frontal),+ null, // mv_back — we don't capture a back photo in the selfie flow+ toFileData(left),+ toFileData(right),+ Number(params?.steps ?? 30),+ Number(params?.guidance_scale ?? 5.0),+ Number(params?.seed ?? 1234),+ Number(params?.octree_resolution ?? 256),+ params?.check_box_rembg !== false,+ Number(params?.num_chunks ?? 8000),+ params?.randomize_seed !== false,+ ];+}++// Stream SSE response and resolve with the parsed `complete` payload.+// Throws on `error` event or when the stream ends without `complete`.+async function consumeSseUntilComplete(response) {+ if (!response.ok || !response.body) {+ const body = await response.text().catch(() => '');+ throw Object.assign(+ new Error(`huggingface /call stream not available: ${response.status} ${body.slice(0, 200)}`),+ { code: 'provider_error', status: 502 },+ );+ }++ const reader = response.body.getReader();+ const decoder = new TextDecoder('utf-8');+ let buffer = '';+ let pendingEvent = null;+ let result = null;+ let errorMessage = null;++ const drain = (async () => {+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let nlIdx;+ while ((nlIdx = buffer.indexOf('\n')) >= 0) {+ const line = buffer.slice(0, nlIdx).replace(/\r$/, '');+ buffer = buffer.slice(nlIdx + 1);+ if (line === '') {+ pendingEvent = null;+ continue;+ }+ if (line.startsWith('event:')) {+ pendingEvent = line.slice(6).trim();+ continue;+ }+ if (line.startsWith('data:')) {+ const dataStr = line.slice(5).trim();+ if (pendingEvent === 'complete') {+ try { result = JSON.parse(dataStr); } catch { result = dataStr; }+ return;+ }+ if (pendingEvent === 'error') {+ errorMessage = dataStr || 'inference reported error';+ return;+ }+ // heartbeat / generating / unknown: ignore+ }+ }+ }+ })();++ try {+ await withTimeout(drain, HF_INFERENCE_TIMEOUT_MS, 'huggingface SSE stream timed out');+ } catch (err) {+ try { await reader.cancel(); } catch (_) {}+ throw Object.assign(+ new Error(err?.message || 'huggingface stream timed out'),+ { code: 'provider_timeout', status: 504 },+ );+ }++ if (errorMessage) {+ throw Object.assign(new Error(`huggingface inference failed: ${errorMessage}`), {+ code: 'provider_error',+ status: 502,+ });+ }+ if (result === null) {+ throw Object.assign(new Error('huggingface stream closed without complete event'), {+ code: 'provider_error',+ status: 502,+ });+ }+ return result;+}++export function createRegenProvider() {+ const token = readEnv('HF_TOKEN');+ if (!token) {+ throw Object.assign(new Error('HF_TOKEN env var is required for the huggingface provider'), {+ code: 'provider_unconfigured',+ status: 501,+ });+ }++ const spaceSlug = readEnv('HF_RECONSTRUCT_SPACE') || HF_DEFAULT_SPACE;+ const apiName = readEnv('HF_RECONSTRUCT_API_NAME') || HF_DEFAULT_API;+ const spaceUrl = spaceBaseUrl(spaceSlug);++ const authHeaders = {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ };++ return {+ async submit(request) {+ if (request.mode !== 'reconstruct') {+ throw Object.assign(+ new Error(`huggingface provider only supports mode "reconstruct" (got "${request.mode}")`),+ { code: 'mode_unconfigured', status: 501 },+ );+ }++ const photos = Array.isArray(request.params?.images) ? request.params.images : [];+ if (photos.length === 0) {+ throw Object.assign(new Error('huggingface provider needs at least one input image'), {+ code: 'invalid_input',+ status: 400,+ });+ }++ // Build the per-Space payload. Today we only support Hunyuan3D-2's+ // /generation_all shape; when adding a different Space, branch on+ // apiName here and write its payload builder.+ const payload = apiName === HF_DEFAULT_API+ ? buildHunyuanPayload({ photos, params: request.params })+ : [toFileData(photos[0])]; // generic single-image fallback++ // Step 1 — POST to /call/<api> to enqueue. Returns an event_id.+ let queueRes;+ try {+ queueRes = await fetch(`${spaceUrl}/call/${apiName}`, {+ method: 'POST',+ headers: authHeaders,+ body: JSON.stringify({ data: payload }),+ });+ } catch (err) {+ throw Object.assign(new Error(`huggingface /call failed: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }+ if (!queueRes.ok) {+ const body = await queueRes.text().catch(() => '');+ throw Object.assign(+ new Error(`huggingface /call returned ${queueRes.status}: ${body.slice(0, 200)}`),+ { code: 'provider_error', status: 502, providerStatus: queueRes.status },+ );+ }+ const queueBody = await queueRes.json().catch(() => ({}));+ const eventId = queueBody?.event_id;+ if (!eventId) {+ throw Object.assign(new Error('huggingface /call returned no event_id'), {+ code: 'provider_error',+ status: 502,+ });+ }++ // Step 2 — GET /call/<api>/<event_id> as SSE; block until complete.+ let streamRes;+ try {+ streamRes = await fetch(`${spaceUrl}/call/${apiName}/${eventId}`, {+ headers: {+ authorization: `Bearer ${token}`,+ accept: 'text/event-stream',+ },+ });+ } catch (err) {+ throw Object.assign(new Error(`huggingface SSE GET failed: ${err?.message}`), {+ code: 'provider_unreachable',+ status: 502,+ });+ }++ const output = await consumeSseUntilComplete(streamRes);++ let glbUrl = extractFirstGlbUrl(output);+ if (!glbUrl) {+ throw Object.assign(+ new Error('huggingface inference returned no GLB in output'),+ { code: 'provider_error', status: 502 },+ );+ }++ // Gradio may emit relative /file= references; absolutize.+ if (glbUrl.startsWith('/')) glbUrl = `${spaceUrl}${glbUrl}`;+ else if (!/^https?:\/\//i.test(glbUrl)) glbUrl = `${spaceUrl}/file=${glbUrl}`;++ return {+ extJobId: packExtJobId({ resultGlbUrl: glbUrl, space: spaceSlug, api: apiName }),+ eta: 0,+ rawStatus: 'completed',+ };+ },++ async status(extJobId) {+ const payload = unpackExtJobId(extJobId);+ if (!payload?.resultGlbUrl) {+ return { status: 'failed', error: 'missing or malformed ext_job_id' };+ }+ return {+ status: 'done',+ rawStatus: 'completed',+ resultGlbUrl: payload.resultGlbUrl,+ };+ },+ };+}diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex e7436e1ca..c160717a7 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -19,10 +19,27 @@ import { randomUUID } from 'crypto';// 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.+//+// Provider name precedence:+// 1. Explicit env: AVATAR_REGEN_PROVIDER=replicate|gcp|stub+// 2. Inferred from credentials: if REPLICATE_API_TOKEN is set with no+// explicit provider, default to 'replicate'. Same for GCP_RECONSTRUCTION_URL.+// This keeps the deploy path 1-step: drop the token in env, ship.let _regenProviderCache = null;let _regenProviderName = null;+function resolveProviderName() {+ const explicit = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();+ if (explicit) return explicit;+ // Auto-detect order is paid → free: prefer Replicate's pinned-version+ // reliability, then our own GCP Cloud Run service, then the HF Spaces+ // queue (free GPU but variable wait + cold starts).+ if (process.env.REPLICATE_API_TOKEN) return 'replicate';+ if (process.env.GCP_RECONSTRUCTION_URL) return 'gcp';+ if (process.env.HF_TOKEN) return 'huggingface';+ return 'none';+}async function getRegenProvider() {- const name = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();+ const name = resolveProviderName();if (name === 'none' || !name) return { name, instance: null };if (_regenProviderCache && _regenProviderName === name) {return { name, instance: _regenProviderCache };@@ -38,6 +55,12 @@ async function getRegenProvider() {_regenProviderName = name;return { name, instance: _regenProviderCache };}+ if (name === 'huggingface' || name === 'hf') {+ const mod = await import('../_providers/huggingface.js');+ _regenProviderCache = mod.createRegenProvider();+ _regenProviderName = name;+ return { name, instance: _regenProviderCache };+ }if (name === 'gcp') {const mod = await import('../_providers/gcp.js');_regenProviderCache = mod.createRegenProvider();@@ -77,6 +100,107 @@ const handlePresign = wrap(async (req, res) => {return json(res, 200, { storage_key: key, upload_url: url, method: 'PUT', headers: { 'content-type': body.content_type }, expires_in: 300 });});+// ── upload proxy ──────────────────────────────────────────────────────────────+// Server-side upload fallback for environments where direct browser→R2 PUT is+// blocked (Codespaces previews, ephemeral domains not in the bucket CORS+// allowlist, restrictive corporate networks). The client streams the GLB to+// this endpoint and we PUT it to R2 server-side using already-authenticated+// S3 credentials. Same quotas, same key naming as presign — only the wire path+// differs. Used by account.js after a CORS-blocked presigned PUT.+//+// Body: raw octet stream (the GLB bytes). Metadata passed as query params so+// the body can be a single contiguous buffer:+// ?slug=optional-slug&content_type=model/gltf-binary&sha256=hex-or-empty+//+// Vercel Pro caps Node function request bodies at 50 MB. Realistic avatars+// are 5–15 MB; the presign+direct path remains for anything larger.+const MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024;+const PROXY_CONTENT_TYPES = new Set([+ 'model/gltf-binary',+ 'application/octet-stream',+ 'application/gltf-binary',+]);++const handleUpload = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;+ const userId = await resolvePresignUser(req, 'avatars:write');+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ const rl = await limits.upload(userId);+ if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');++ const url = new URL(req.url, 'http://x');+ const rawContentType = url.searchParams.get('content_type') || req.headers['content-type'] || 'model/gltf-binary';+ const contentType = rawContentType.split(';')[0].trim().toLowerCase();+ if (!PROXY_CONTENT_TYPES.has(contentType)) {+ return error(res, 415, 'unsupported_media_type', `content_type must be one of: ${[...PROXY_CONTENT_TYPES].join(', ')}`);+ }++ const declaredLength = Number(req.headers['content-length']);+ if (Number.isFinite(declaredLength) && declaredLength > MAX_PROXY_UPLOAD_BYTES) {+ return error(res, 413, 'payload_too_large', `body exceeds ${MAX_PROXY_UPLOAD_BYTES} bytes — use presigned upload for larger GLBs`);+ }++ let buffer;+ try {+ buffer = await readRawBody(req, MAX_PROXY_UPLOAD_BYTES);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'invalid_body', err.message || 'failed to read body');+ }+ if (!buffer.length) return error(res, 400, 'empty_body', 'no bytes received');++ try {+ await enforceQuotas(userId, buffer.length);+ } catch (err) {+ return error(res, err.status || 402, err.code || 'plan_limit', err.message);+ }++ const rawSlug = url.searchParams.get('slug');+ const slug = rawSlug ? slugSchema.parse(rawSlug) : `draft-${Math.random().toString(36).slice(2, 8)}`;+ const key = storageKeyFor({ userId, slug });++ const checksum = await sha256Hex(buffer);+ const claimedChecksum = (url.searchParams.get('sha256') || '').toLowerCase();+ if (claimedChecksum && claimedChecksum !== checksum) {+ return error(res, 400, 'checksum_mismatch', 'sha256 query param does not match received bytes');+ }++ await putObject({ key, body: buffer, contentType });++ return json(res, 200, {+ storage_key: key,+ size_bytes: buffer.length,+ content_type: contentType,+ checksum_sha256: checksum,+ });+});++function readRawBody(req, limit) {+ return new Promise((resolve, reject) => {+ const chunks = [];+ let total = 0;+ req.on('data', (chunk) => {+ total += chunk.length;+ if (total > limit) {+ const err = new Error(`body exceeds ${limit} bytes`);+ err.status = 413;+ err.code = 'payload_too_large';+ reject(err);+ req.destroy();+ return;+ }+ chunks.push(chunk);+ });+ req.on('end', () => resolve(Buffer.concat(chunks)));+ req.on('error', reject);+ });+}++async function sha256Hex(buf) {+ const { createHash } = await import('crypto');+ return createHash('sha256').update(buf).digest('hex');+}+// ── public ────────────────────────────────────────────────────────────────────// Public discovery surface — must always return 200 with a stable JSON shape so@@ -641,6 +765,7 @@ const handleReconstruct = wrap(async (req, res) => {const DISPATCH = {presign: handlePresign,+ upload: handleUpload,'presign-thumbnail': handlePresignThumbnail,'presign-usdz': handlePresignUsdz,'presign-halfbody': handlePresignHalfbody,diff --git a/api/config.js b/api/config.jsindex 5a3c71ba9..b0e79368d 100644--- a/api/config.js+++ b/api/config.js@@ -6,7 +6,16 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;if (!method(req, res, ['GET'])) return;+ const regen = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();+ const reconstructEnabled = regen !== '' && regen !== 'none';+return json(res, 200, {walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',+ features: {+ // /create/selfie uses /api/avatars/reconstruct, which 501s unless an+ // ML backend is wired. The selfie page reads this to either show the+ // capture flow or fall through to a "coming soon — try /create" panel.+ avatarReconstruct: reconstructEnabled,+ },});});diff --git a/package.json b/package.jsonindex d961437cd..353424db1 100644--- a/package.json+++ b/package.json@@ -74,7 +74,8 @@"build:rider:full": "cd rider && npm ci --prefer-offline --no-audit --no-fund --ignore-engines && npm run build && cd .. && npm run build:rider","build:avatar-studio": "npm run build --prefix character-studio","build:fast": "npm run build",- "build:vercel": "npm run build --prefix agent-payments-sdk && npm run build:avatar-studio && npm run build:lib && node avatar-sdk/build.mjs && NODE_OPTIONS=--max-old-space-size=4096 npm run build && npm run build:rider && npm run build:chat && npm run publish:lib",+ "build:vercel": "npm run build --prefix agent-payments-sdk && npm run build:avatar-studio && npm run build:lib && node avatar-sdk/build.mjs && NODE_OPTIONS=--max-old-space-size=4096 npm run build && npm run build:rider && npm run build:chat && npm run publish:lib && npm run apply:r2-cors",+ "apply:r2-cors": "node scripts/set-r2-cors.mjs || echo '[apply:r2-cors] skipped (missing creds or transient failure — see build log)'","build:all": "npm run build:chat && (npm run build & npm run build:lib & npm run build:rider & wait)","release:lib": "npm run build:lib && npm run publish:lib","clean": "rm -rf dist/* dist-lib/* || true",diff --git a/pages/create-selfie.html b/pages/create-selfie.htmlindex 1a03ae383..fb7146173 100644--- a/pages/create-selfie.html+++ b/pages/create-selfie.html@@ -5,14 +5,14 @@<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /><title>Selfie to avatar · three.ws</title><link rel="icon" href="/favicon.ico" />- <meta name="description" content="Snap three photos — three.ws builds you a rigged 3D avatar in about a minute." />+ <meta name="description" content="One selfie. About a minute. A rigged 3D avatar that works everywhere." /><meta name="robots" content="noindex" /><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" /><meta property="og:url" content="https://three.ws/create/selfie" /><meta property="og:title" content="Selfie to avatar · three.ws" />- <meta property="og:description" content="Snap three photos — three.ws builds you a rigged 3D avatar in about a minute." />+ <meta property="og:description" content="One selfie. About a minute. A rigged 3D avatar that works everywhere." /><meta property="og:image" content="https://three.ws/assets/og-image.png" /><style>@@ -129,16 +129,95 @@.choice .title { font-size: 16px; font-weight: 600; margin: 0 0 4px; }.choice .desc { color: var(--muted); font-size: 13px; line-height: 1.5; margin: 0; }+ .hero-slot-wrap {+ margin: 8px 0 18px;+ }+ .hero-slot {+ aspect-ratio: 1 / 1;+ max-width: 360px;+ margin: 0 auto;+ background: var(--panel);+ border: 1.5px dashed var(--border-strong);+ border-radius: 16px;+ position: relative;+ overflow: hidden;+ cursor: pointer;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ color: var(--muted);+ transition: border-color 120ms, background 120ms;+ }+ .hero-slot:hover, .hero-slot:focus-visible { border-color: var(--accent); color: var(--text); outline: none; }+ .hero-slot.drag { border-color: var(--accent); background: rgba(214, 255, 61, 0.05); }+ .hero-slot.filled { border-style: solid; border-color: var(--border); padding: 0; cursor: default; }+ .hero-slot.error { border-color: var(--danger); }+ .hero-slot .hero-icon { font-size: 36px; opacity: 0.7; }+ .hero-slot .hero-title { font-size: 15.5px; color: var(--text); font-weight: 600; }+ .hero-slot .hero-sub { font-size: 13px; color: var(--muted); max-width: 240px; text-align: center; line-height: 1.4; }+ .hero-slot img.preview { width: 100%; height: 100%; object-fit: cover; display: block; }+ .hero-actions {+ display: flex;+ justify-content: center;+ gap: 10px;+ margin-top: 12px;+ flex-wrap: wrap;+ }+ .hero-pill {+ background: var(--panel);+ border: 1px solid var(--border);+ color: var(--muted);+ border-radius: 999px;+ padding: 7px 14px;+ font: 500 12.5px/1 inherit;+ cursor: pointer;+ transition: color 120ms, border-color 120ms;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ }+ .hero-pill:hover { color: var(--text); border-color: var(--border-strong); }+ .hero-pill[hidden] { display: none; }+ .hero-pill svg { display: block; }++ .fidelity {+ margin: 0 0 22px;+ border: 1px solid var(--border);+ background: var(--panel);+ border-radius: 12px;+ overflow: hidden;+ }+ .fidelity summary {+ list-style: none;+ padding: 14px 16px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ color: var(--text);+ }+ .fidelity summary::-webkit-details-marker { display: none; }+ .fidelity .fid-label { font-size: 14px; font-weight: 600; }+ .fidelity .fid-note { color: var(--muted); font-size: 12.5px; font-weight: 400; }+ .fidelity .fid-chev {+ color: var(--muted);+ transition: transform 200ms;+ }+ .fidelity[open] .fid-chev { transform: rotate(180deg); }+ .fidelity .fid-body {+ padding: 4px 16px 18px;+ }.slots {display: grid;- grid-template-columns: repeat(3, 1fr);+ grid-template-columns: 1fr 1fr;gap: 12px;- margin: 8px 0 24px;}- @media (max-width: 560px) { .slots { grid-template-columns: 1fr; } }.slot-frame {aspect-ratio: 3 / 4;- background: var(--panel);+ background: var(--panel-elev);border: 1.5px dashed var(--border-strong);border-radius: 11px;position: relative;@@ -155,6 +234,7 @@.slot-frame:hover, .slot-frame:focus-visible { border-color: var(--accent); color: var(--text); outline: none; }.slot-frame.drag { border-color: var(--accent); background: rgba(214, 255, 61, 0.05); }.slot-frame.filled { border-style: solid; border-color: var(--border); padding: 0; }+ .slot-frame.error { border-color: var(--danger); }.slot-frame .slot-label { font-size: 11.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }.slot-frame .slot-hint { font-size: 13px; color: var(--text); font-weight: 500; }.slot-frame img { width: 100%; height: 100%; object-fit: cover; display: block; }@@ -172,18 +252,17 @@}.opts {- display: grid;- grid-template-columns: 1fr 1fr;- gap: 18px;margin: 0 0 22px;+ display: flex;+ flex-direction: column;+ gap: 18px;}- @media (max-width: 560px) { .opts { grid-template-columns: 1fr; } }.opt-group .opt-label {font-size: 12px;letter-spacing: 0.06em;text-transform: uppercase;color: var(--muted);- margin: 0 0 8px;+ margin: 0 0 10px;}.toggle {display: inline-flex;@@ -209,6 +288,48 @@.toggle button:hover { color: var(--text); }.opt-hint { font-size: 12px; color: var(--muted); margin: 6px 0 0; }+ .style-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 10px;+ }+ .style-card {+ background: var(--panel);+ border: 1.5px solid var(--border);+ border-radius: 11px;+ padding: 12px;+ cursor: pointer;+ text-align: left;+ color: var(--text);+ font: inherit;+ display: flex;+ gap: 12px;+ align-items: center;+ transition: border-color 120ms, transform 120ms;+ }+ .style-card:hover { border-color: var(--border-strong); transform: translateY(-1px); }+ .style-card[aria-pressed="true"] {+ border-color: var(--accent);+ background: rgba(214, 255, 61, 0.04);+ }+ .style-swatch {+ width: 44px;+ height: 44px;+ border-radius: 8px;+ flex-shrink: 0;+ background-size: cover;+ background-position: center;+ border: 1px solid var(--border);+ }+ .style-swatch.photoreal {+ background: radial-gradient(circle at 35% 30%, #f6c79b 0%, #c98c61 45%, #4a2e1d 95%);+ }+ .style-swatch.stylized {+ background: radial-gradient(circle at 35% 30%, #ffd5e8 0%, #c4a3ff 45%, #5a3aa3 95%);+ }+ .style-card .style-title { font-size: 14px; font-weight: 600; line-height: 1.2; margin: 0 0 2px; }+ .style-card .style-desc { font-size: 12px; color: var(--muted); line-height: 1.35; }+/* ── Step 3: Building ─────────────────────────────────────────────── */.build-progress {display: flex;@@ -294,22 +415,42 @@height: 100%;--poster-color: transparent;}+ .build-preview {+ position: absolute;+ top: 18px;+ left: 50%;+ transform: translateX(-50%);+ width: 110px;+ height: 110px;+ border-radius: 50%;+ object-fit: cover;+ border: 2px solid var(--accent);+ box-shadow: 0 8px 24px -4px rgba(0, 0, 0, 0.6), 0 0 0 4px rgba(214, 255, 61, 0.12);+ background: var(--panel);+ opacity: 0;+ transition: opacity 320ms ease;+ animation: preview-breathe 2.4s ease-in-out infinite;+ }+ .build-preview.show { opacity: 1; }+ @keyframes preview-breathe {+ 0%, 100% { box-shadow: 0 8px 24px -4px rgba(0, 0, 0, 0.6), 0 0 0 4px rgba(214, 255, 61, 0.12); }+ 50% { box-shadow: 0 8px 24px -4px rgba(0, 0, 0, 0.6), 0 0 0 9px rgba(214, 255, 61, 0.06); }+ }.build-veil {position: absolute;inset: 0;display: flex;- align-items: center;+ align-items: flex-end;justify-content: center;- background: rgba(5, 6, 10, 0.55);- backdrop-filter: blur(2px);- -webkit-backdrop-filter: blur(2px);+ padding-bottom: 18px;+ background: linear-gradient(to bottom, rgba(5,6,10,0.05), rgba(5,6,10,0.45) 65%);pointer-events: none;}.build-ring {- width: 72px;- height: 72px;+ width: 36px;+ height: 36px;border-radius: 50%;- border: 3px solid rgba(214, 255, 61, 0.15);+ border: 2.5px solid rgba(214, 255, 61, 0.15);border-top-color: var(--accent);animation: build-spin 1s linear infinite;}@@ -429,25 +570,39 @@.submit-bar {margin-top: 6px;+ position: sticky;+ bottom: 16px;+ z-index: 2;}.submit-bar[hidden] { display: none; }#submit-btn {width: 100%;- padding: 14px 18px;+ padding: 16px 18px;background: var(--panel);color: var(--muted);border: 1px solid var(--border);- border-radius: 10px;- font: 600 15px/1 inherit;+ border-radius: 12px;+ font: 600 15px/1.2 inherit;cursor: not-allowed;transition: background 120ms, color 120ms, border-color 120ms;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ }+ #submit-btn .meta {+ font: 500 12px/1 inherit;+ color: var(--muted);+ opacity: 0.85;}#submit-btn.ready {background: var(--accent);color: var(--accent-ink);border-color: var(--accent);cursor: pointer;+ box-shadow: 0 10px 30px -10px rgba(214, 255, 61, 0.45);}+ #submit-btn.ready .meta { color: rgba(10, 10, 10, 0.7); }#submit-btn.ready:hover { filter: brightness(1.04); }#cam-overlay {@@ -487,6 +642,44 @@pointer-events: none;}.cam-prompt strong { font-weight: 600; color: var(--accent); }+ .cam-oval {+ position: absolute;+ inset: 0;+ pointer-events: none;+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .cam-oval svg {+ width: min(70vw, 60vh);+ height: auto;+ max-height: 75vh;+ }+ .cam-oval ellipse {+ fill: none;+ stroke: rgba(255, 255, 255, 0.45);+ stroke-width: 3;+ stroke-dasharray: 12 8;+ transition: stroke 200ms;+ }+ .cam-oval.detected ellipse {+ stroke: var(--accent);+ stroke-dasharray: 0;+ filter: drop-shadow(0 0 8px rgba(214, 255, 61, 0.4));+ }+ .cam-hint {+ position: absolute;+ bottom: 100px;+ left: 0;+ right: 0;+ text-align: center;+ color: rgba(255, 255, 255, 0.85);+ font-size: 13px;+ padding: 8px 18px;+ pointer-events: none;+ transition: opacity 200ms;+ }+ .cam-hint.ok { color: var(--accent); }#cam-error {position: absolute;top: 60px;@@ -536,7 +729,46 @@border: 3px solid var(--accent-ink);margin: 0 auto;}+ .cam-bar button.shutter:disabled {+ opacity: 0.55;+ cursor: not-allowed;+ }.cam-bar .spacer { flex: 1; }+ .cam-countdown {+ position: absolute;+ inset: 0;+ display: none;+ align-items: center;+ justify-content: center;+ pointer-events: none;+ z-index: 4;+ }+ .cam-countdown.show { display: flex; }+ .cam-countdown .count-num {+ font: 700 96px/1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ color: var(--accent);+ text-shadow: 0 4px 18px rgba(0, 0, 0, 0.6), 0 0 24px rgba(214, 255, 61, 0.4);+ animation: cd-pop 1s ease-out forwards;+ }+ @keyframes cd-pop {+ 0% { transform: scale(0.5); opacity: 0; }+ 20% { transform: scale(1.15); opacity: 1; }+ 80% { transform: scale(1); opacity: 1; }+ 100% { transform: scale(0.8); opacity: 0; }+ }++ .done-actions .btn-secondary {+ width: 100%;+ padding: 12px 18px;+ background: transparent;+ color: var(--text);+ border: 1px solid var(--accent);+ border-radius: 10px;+ font: 600 14px/1 inherit;+ cursor: pointer;+ transition: background 120ms;+ }+ .done-actions .btn-secondary:hover { background: rgba(214, 255, 61, 0.06); }</style><link rel="stylesheet" href="/mobile.css" /><script@@ -560,69 +792,87 @@Your browser can't open the camera here — use Upload instead, or open this page in Safari / Chrome on a device with a camera.</p>- <!-- Step 1: pick method -->- <section class="step active" data-step="method">- <h1>How do you want to give us 3 photos?</h1>- <p class="sub">Frontal, left, and right shots of your face. Good light, plain background. We'll downscale them locally before upload.</p>+ <!-- Step 1: capture (entry) -->+ <section class="step active" data-step="capture">+ <h1>One selfie. One avatar.</h1>+ <p class="sub">Front-facing, good light, plain background. We downscale and upload locally — your photo never sits on disk.</p>- <div class="choice-grid" role="group" aria-label="Choose capture method">- <button type="button" class="choice" data-method="camera">- <span class="icon" aria-hidden="true">📷</span>- <span class="title">Use camera</span>- <p class="desc">Snap three live photos in your browser. Best if you're on a phone.</p>- </button>- <button type="button" class="choice" data-method="upload">- <span class="icon" aria-hidden="true">🖼️</span>- <span class="title">Upload files</span>- <p class="desc">Pick three JPEG / PNG files from your device. Drag-and-drop works too.</p>- </button>- </div>- </section>-- <!-- Step 2: capture slots + selectors -->- <section class="step" data-step="capture">- <h1>Three photos of your face</h1>- <p class="sub">Frontal, left (head turned ~45° left), right (~45° right). Tap a slot to start.</p>-- <div class="slots">- <div class="slot-frame" data-slot="frontal" role="button" tabindex="0" aria-label="Frontal photo slot">- <span class="slot-label">Frontal</span>- <span class="slot-hint">Face the camera</span>- </div>- <div class="slot-frame" data-slot="left" role="button" tabindex="0" aria-label="Left photo slot">- <span class="slot-label">Left</span>- <span class="slot-hint">Turn 45° left</span>+ <div class="hero-slot-wrap">+ <div class="hero-slot" data-slot="frontal" role="button" tabindex="0" aria-label="Front-facing photo">+ <span class="hero-icon" aria-hidden="true">👤</span>+ <span class="hero-title">Add a front-facing photo</span>+ <span class="hero-sub">Tap to open camera or upload — works on phone or desktop.</span></div>- <div class="slot-frame" data-slot="right" role="button" tabindex="0" aria-label="Right photo slot">- <span class="slot-label">Right</span>- <span class="slot-hint">Turn 45° right</span>+ <div class="hero-actions">+ <button type="button" class="hero-pill" data-action="open-camera" id="hero-camera-btn">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>+ Use camera+ </button>+ <button type="button" class="hero-pill" data-action="open-upload">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>+ Upload photo+ </button></div></div>- <input type="file" data-slot-input="frontal" accept="image/jpeg,image/png" hidden />- <input type="file" data-slot-input="left" accept="image/jpeg,image/png" hidden />- <input type="file" data-slot-input="right" accept="image/jpeg,image/png" hidden />+ <input type="file" data-slot-input="frontal" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />++ <details class="fidelity" id="fidelity-boost">+ <summary>+ <div>+ <div class="fid-label">Add side angles <span class="fid-note">(optional — bumps fidelity)</span></div>+ </div>+ <svg class="fid-chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>+ </summary>+ <div class="fid-body">+ <div class="slots">+ <div class="slot-frame" data-slot="left" role="button" tabindex="0" aria-label="Left side photo slot">+ <span class="slot-label">Left</span>+ <span class="slot-hint">Turn ~45° left</span>+ </div>+ <div class="slot-frame" data-slot="right" role="button" tabindex="0" aria-label="Right side photo slot">+ <span class="slot-label">Right</span>+ <span class="slot-hint">Turn ~45° right</span>+ </div>+ </div>+ <input type="file" data-slot-input="left" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />+ <input type="file" data-slot-input="right" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />+ </div>+ </details><div class="opts"><div class="opt-group">- <p class="opt-label">Body</p>- <div class="toggle" role="group" aria-label="Body type">- <button type="button" data-body="male" aria-pressed="true">Male</button>- <button type="button" data-body="female" aria-pressed="false">Female</button>+ <p class="opt-label">Style</p>+ <div class="style-grid" role="group" aria-label="Avatar style">+ <button type="button" class="style-card" data-type="v1" aria-pressed="true">+ <span class="style-swatch photoreal" aria-hidden="true"></span>+ <span>+ <span class="style-title">Photoreal</span>+ <span class="style-desc">Likeness-first. Closest to how you actually look.</span>+ </span>+ </button>+ <button type="button" class="style-card" data-type="v2" aria-pressed="false">+ <span class="style-swatch stylized" aria-hidden="true"></span>+ <span>+ <span class="style-title">Stylized</span>+ <span class="style-desc">Cleaner, cartoon-leaning. Good for streaming + games.</span>+ </span>+ </button></div></div><div class="opt-group">- <p class="opt-label">Style</p>- <div class="toggle" role="group" aria-label="Avatar style">- <button type="button" data-type="v1" aria-pressed="true">Photoreal</button>- <button type="button" data-type="v2" aria-pressed="false">Stylized</button>+ <p class="opt-label">Body</p>+ <div class="toggle" role="group" aria-label="Body type">+ <button type="button" data-body="male" aria-pressed="true">Masc</button>+ <button type="button" data-body="female" aria-pressed="false">Femme</button></div>- <p class="opt-hint">Stylized renders as a cleaner cartoon-leaning look.</p></div></div>- <div id="submit-bar" class="submit-bar" hidden>- <button id="submit-btn" type="button" disabled>Add 3 photos to continue</button>+ <div id="submit-bar" class="submit-bar">+ <button id="submit-btn" type="button" disabled>+ <span class="label">Add a photo to start</span>+ </button></div></section>@@ -660,6 +910,7 @@camera-orbit="0deg 78deg auto"loading="eager"></model-viewer>+ <img id="build-preview" class="build-preview" alt="" /><div class="build-veil"><div class="build-ring"></div></div>@@ -705,7 +956,9 @@<div class="done-actions"><button id="done-save-btn" class="btn-save" type="button">Open my avatar →</button>+ <button id="done-list-btn" class="btn-secondary" type="button">List on marketplace</button><button id="done-editor-btn" class="btn-ghost" type="button">Customize in editor</button>+ <button id="done-regen-btn" class="btn-ghost" type="button">Not quite right — try again</button></div><div class="portability-note">@@ -715,10 +968,36 @@</section></main>+ <!-- Step "unavailable" — shown when the avatar-reconstruction backend isn't+ wired in this environment (no AVATAR_REGEN_PROVIDER + provider creds).+ Hidden by default; the boot script swaps to this and hides the others+ when /api/config.features.avatarReconstruct === false. -->+ <section class="step" data-step="unavailable" hidden style="text-align:center;max-width:520px;margin:0 auto;padding:48px 24px;">+ <h1 style="margin:0 0 12px;">Selfie avatars are still warming up</h1>+ <p class="sub" style="margin:0 0 24px;color:#9aa3b2;">+ The photo-to-avatar engine is being provisioned for this environment.+ In the meantime, you can build an avatar in the studio — same outputs,+ same workflow, fully ready today.+ </p>+ <div class="done-actions" style="justify-content:center;">+ <a href="/create" class="btn-save" style="text-decoration:none;display:inline-block;">Open the avatar studio →</a>+ <a href="/app" class="btn-ghost" style="text-decoration:none;display:inline-block;">Back to my workspace</a>+ </div>+ </section>+<!-- Camera overlay (driven by selfie-capture.js) --><div id="cam-overlay" role="dialog" aria-modal="true" aria-label="Camera capture"><div id="cam-stage"><video id="cam-video" autoplay playsinline muted></video>+ <div class="cam-oval" id="cam-oval" aria-hidden="true">+ <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid meet">+ <ellipse cx="150" cy="180" rx="115" ry="155" />+ </svg>+ </div>+ <div class="cam-hint" id="cam-hint">Center your face in the oval</div>+ <div class="cam-countdown" id="cam-countdown" aria-hidden="true">+ <span class="count-num" id="cam-count-num">3</span>+ </div></div><div class="cam-prompt">Take your <strong id="cam-slot-name">photo</strong>@@ -727,7 +1006,7 @@<div class="cam-bar"><div id="cam-actions-live" style="display: contents;"><button type="button" data-cam-action="cancel">Cancel</button>- <button type="button" class="shutter" data-cam-action="shoot" aria-label="Take photo"></button>+ <button type="button" class="shutter" data-cam-action="shoot" aria-label="Take photo" id="cam-shutter"></button><div class="spacer"></div></div><div id="cam-actions-review" hidden style="display: contents;">@@ -738,19 +1017,56 @@</div><script type="module">- import '/src/selfie-capture.js';- import '/src/selfie-pipeline.js';-function showStep(name) {document.querySelectorAll('.step[data-step]').forEach((s) => {s.classList.toggle('active', s.dataset.step === name);+ if (name === 'unavailable') s.hidden = s.dataset.step !== 'unavailable';});}+ // Capability probe — /api/avatars/reconstruct returns 501 unless an ML+ // backend is wired. If it's not, switch to the "unavailable" step+ // instead of letting the user take three selfies for nothing.+ const reconstructReady = await fetch('/api/config', { credentials: 'omit' })+ .then((r) => (r.ok ? r.json() : null))+ .then((j) => j?.features?.avatarReconstruct !== false)+ .catch(() => true); // network failure: assume ready, let the real flow surface the truth++ if (!reconstructReady) {+ document.querySelectorAll('.step[data-step]').forEach((s) => {+ s.classList.remove('active');+ s.hidden = s.dataset.step !== 'unavailable';+ });+ const u = document.querySelector('.step[data-step="unavailable"]');+ if (u) { u.hidden = false; u.classList.add('active'); }+ const sb = document.getElementById('submit-bar');+ if (sb) sb.hidden = true;+ } else {+ // Only load the camera + pipeline when we actually need them.+ await import('/src/selfie-capture.js');+ await import('/src/selfie-pipeline.js');+ }+let _avatarId = null;+ let _docTitleBase = document.title;+ let _notifyPermission = (typeof Notification !== 'undefined') ? Notification.permission : 'denied';++ document.addEventListener('selfie:preview', (e) => {+ const dataUrl = /** @type {CustomEvent} */ (e).detail?.dataUrl;+ if (!dataUrl) return;+ const img = /** @type {HTMLImageElement|null} */ (document.getElementById('build-preview'));+ if (!img) return;+ img.src = dataUrl;+ requestAnimationFrame(() => img.classList.add('show'));+ });document.addEventListener('selfie:building', () => {showStep('building');+ // Ask for notification permission once, while the user is engaged — so+ // when they switch tabs mid-build we can ping them back.+ if (typeof Notification !== 'undefined' && _notifyPermission === 'default') {+ Notification.requestPermission().then((p) => { _notifyPermission = p; }).catch(() => {});+ }});document.addEventListener('selfie:progress', (e) => {@@ -772,12 +1088,10 @@_avatarId = /** @type {CustomEvent} */ (e).detail?.avatarId;if (!_avatarId) return;- // Mark all build steps completedocument.querySelectorAll('.build-step').forEach((s) => {s.className = 'build-step completed';});- // Fetch avatar to get model URL and nametry {const res = await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {credentials: 'include',@@ -791,15 +1105,63 @@}} catch (_) {}+ notifyDone();showStep('done');});+ function notifyDone() {+ // Page-visible: nothing to do. Page-hidden: flash the title and fire a+ // real OS-level notification if the user granted permission.+ if (!document.hidden) return;+ let on = true;+ const tick = window.setInterval(() => {+ document.title = on ? '✓ Avatar ready — three.ws' : _docTitleBase;+ on = !on;+ }, 900);+ const restore = () => {+ clearInterval(tick);+ document.title = _docTitleBase;+ document.removeEventListener('visibilitychange', restore);+ };+ document.addEventListener('visibilitychange', restore);++ if (_notifyPermission === 'granted' && typeof Notification !== 'undefined') {+ try {+ const n = new Notification('Your avatar is ready', {+ body: 'Tap to open it on three.ws.',+ icon: '/favicon.ico',+ tag: 'avatar-ready',+ });+ n.onclick = () => {+ window.focus();+ n.close();+ };+ } catch (_) {}+ }+ }+document.addEventListener('selfie:build-error', (e) => {- const msg = /** @type {CustomEvent} */ (e).detail?.message || 'Something went wrong. Try again.';+ const detail = /** @type {CustomEvent} */ (e).detail || {};+ const msg = detail.message || 'Something went wrong. Try again.';const errEl = document.getElementById('build-error-msg');const retryBtn = document.getElementById('build-retry-btn');if (errEl) { errEl.textContent = msg; errEl.classList.add('show'); }if (retryBtn) retryBtn.classList.add('show');++ // If we can identify the failing slot, highlight it for retake.+ if (detail.slot) {+ const slotFrame = document.querySelector(+ detail.slot === 'frontal'+ ? `.hero-slot[data-slot="${detail.slot}"]`+ : `.slot-frame[data-slot="${detail.slot}"]`,+ );+ slotFrame?.classList.add('error');+ // If a side-photo failed, make sure the fidelity panel is open.+ if (detail.slot !== 'frontal') {+ const fid = /** @type {HTMLDetailsElement|null} */ (document.getElementById('fidelity-boost'));+ if (fid) fid.open = true;+ }+ }});document.getElementById('build-retry-btn')?.addEventListener('click', () => {@@ -810,6 +1172,26 @@showStep('capture');});+ document.getElementById('done-list-btn')?.addEventListener('click', async () => {+ if (!_avatarId) return;+ const btn = /** @type {HTMLButtonElement} */ (document.getElementById('done-list-btn'));+ btn.disabled = true;+ btn.textContent = 'Saving…';+ const nameEl = /** @type {HTMLInputElement|null} */ (document.getElementById('done-name'));+ const name = nameEl?.value?.trim();+ if (name) {+ try {+ await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name, visibility: 'public' }),+ });+ } catch (_) {}+ }+ window.location.assign(`/marketplace/avatars/${encodeURIComponent(_avatarId)}`);+ });+document.getElementById('done-save-btn')?.addEventListener('click', async () => {if (!_avatarId) return;const btn = /** @type {HTMLButtonElement} */ (document.getElementById('done-save-btn'));@@ -836,6 +1218,17 @@if (!_avatarId) return;window.location.assign(`/avatars/${encodeURIComponent(_avatarId)}/edit`);});++ document.getElementById('done-regen-btn')?.addEventListener('click', () => {+ // Drop the just-built avatar and reset the capture step. Photos in+ // memory are gone; the user picks fresh ones. We don't delete the+ // avatar row — they can still open it later from /dashboard.+ _avatarId = null;+ const preview = /** @type {HTMLImageElement|null} */ (document.getElementById('build-preview'));+ if (preview) { preview.removeAttribute('src'); preview.classList.remove('show'); }+ document.dispatchEvent(new CustomEvent('selfie:reset'));+ showStep('capture');+ });</script></body></html>diff --git a/scripts/set-r2-cors.mjs b/scripts/set-r2-cors.mjsindex c160aaa10..f15988e40 100644--- a/scripts/set-r2-cors.mjs+++ b/scripts/set-r2-cors.mjs@@ -33,26 +33,45 @@ import { readFileSync, existsSync } from 'node:fs';// Lightweight .env loader so this runs standalone without dotenv as a dep.loadDotenv('.env');+loadDotenv('.env.local');++// Accept either S3_* env names (what the API runtime uses) or R2_* names (what+// Cloudflare's dashboard hands out). The R2_* path lets you point this at any+// bucket using only the four keys from a stock R2 token — no `vercel env pull`+// required.+function fallbackEndpointFromAccount(accountId) {+ if (!accountId) return null;+ return `https://${accountId.trim()}.r2.cloudflarestorage.com`;+}+process.env.S3_ENDPOINT ||= process.env.R2_ENDPOINT || fallbackEndpointFromAccount(process.env.R2_ACCOUNT_ID);+process.env.S3_ACCESS_KEY_ID ||= process.env.R2_ACCESS_KEY_ID;+process.env.S3_SECRET_ACCESS_KEY ||= process.env.R2_SECRET_ACCESS_KEY;+process.env.S3_BUCKET ||= process.env.R2_BUCKET;const required = ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET'];const missing = required.filter((k) => !process.env[k]);if (missing.length) {- console.error(`Missing env: ${missing.join(', ')}`);- console.error('Hint: run `vercel env pull .env` first.');- process.exit(1);+ // Deploy-time invocation: missing env is not a deploy failure. Local-dev+ // invocation: surface the hint. Either way, exit 0 so a CI step can chain.+ console.log(`[set-r2-cors] skipped — missing env: ${missing.join(', ')}`);+ console.log('[set-r2-cors] (local: drop R2_ACCOUNT_ID/R2_ACCESS_KEY_ID/R2_SECRET_ACCESS_KEY/R2_BUCKET in .env.local, or run `vercel env pull .env` for production creds.)');+ process.exit(0);}// Web origins allowed to read assets from R2 and to PUT uploads via presigned// URLs. Keep this list authoritative — any origin not listed will be blocked// by the browser even if the URL itself is correct.+// R2/S3 CORS supports a single `*` per origin entry. Wildcards cover ephemeral+// preview hosts (Vercel branch deploys, Codespaces port-forwards) so a new+// preview never breaks the upload flow — anything else gets blocked.const ALLOWED_ORIGINS = ['https://three.ws','https://www.three.ws','https://3d-agent.vercel.app',+ 'https://*.vercel.app',+ 'https://*.app.github.dev','http://localhost:3000','http://localhost:5173',- // GitHub Codespaces preview hosts: {name}-{port}.app.github.dev- 'https://*.app.github.dev',];const POLICY = {diff --git a/scripts/smoke-hf-reconstruct.mjs b/scripts/smoke-hf-reconstruct.mjsnew file mode 100644index 000000000..5dd21bde4--- /dev/null+++ b/scripts/smoke-hf-reconstruct.mjs@@ -0,0 +1,83 @@+#!/usr/bin/env node+/**+ * Smoke-test the HuggingFace avatar-reconstruction provider against the live+ * tencent/Hunyuan3D-2 Space. Reads HF_TOKEN from .env / .env.local and submits+ * a single multi-view request with a public test image.+ *+ * Pass / fail criteria:+ * - submit() returns { extJobId } whose status() echoes resultGlbUrl+ * - resultGlbUrl is a fetchable .glb (HEAD returns 200)+ *+ * Usage:+ * node scripts/smoke-hf-reconstruct.mjs+ *+ * The Space's queue + processing typically completes in 30-120s. Job dies+ * silently if it exceeds 280s.+ */++import { existsSync, readFileSync } from 'node:fs';++// Lightweight .env loader (matches set-r2-cors.mjs)+for (const path of ['.env', '.env.local']) {+ if (!existsSync(path)) continue;+ for (const line of readFileSync(path, 'utf8').split('\n')) {+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);+ if (!m) continue;+ const [, key, raw] = m;+ if (process.env[key]) continue;+ let val = raw;+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {+ val = val.slice(1, -1);+ }+ process.env[key] = val;+ }+}++if (!process.env.HF_TOKEN) {+ console.error('HF_TOKEN missing — put it in .env or .env.local');+ process.exit(1);+}++const { createRegenProvider } = await import('../api/_providers/huggingface.js');+const provider = createRegenProvider();++// Public CC-licensed portrait via Unsplash (head-and-shoulders, neutral background).+// If unreachable, the Space's preprocessor will fail and we'll see that error.+const TEST_IMAGE = 'https://images.unsplash.com/photo-1599566150163-29194dcaad36?w=512&q=80';++console.log('→ submitting reconstruct job to tencent/Hunyuan3D-2 (HF Space)');+console.log(' image:', TEST_IMAGE);+console.log(' this typically takes 30-120s; live progress is not surfaced.');++const t0 = Date.now();+let result;+try {+ result = await provider.submit({+ mode: 'reconstruct',+ params: { images: [TEST_IMAGE] },+ sourceUrl: TEST_IMAGE,+ });+} catch (err) {+ console.error('submit() failed:', err?.message || err);+ console.error(' code:', err?.code, 'status:', err?.status);+ process.exit(2);+}+const elapsed = ((Date.now() - t0) / 1000).toFixed(1);+console.log(`✓ submit returned in ${elapsed}s`);++const status = await provider.status(result.extJobId);+console.log(' status:', status.status);+console.log(' resultGlbUrl:', status.resultGlbUrl);++// Verify the GLB URL is fetchable.+const head = await fetch(status.resultGlbUrl, {+ method: 'HEAD',+ headers: process.env.HF_TOKEN ? { authorization: `Bearer ${process.env.HF_TOKEN}` } : {},+});+if (!head.ok) {+ console.error(`! GLB URL not fetchable: ${head.status}`);+ process.exit(3);+}+const size = head.headers.get('content-length');+console.log(`✓ GLB is fetchable, size: ${size ? Math.round(Number(size) / 1024) + ' KB' : 'unknown'}`);+console.log('PASS — HF provider round-trips successfully.');diff --git a/src/account.js b/src/account.jsindex f4497fba2..f1d1d2f28 100644--- a/src/account.js+++ b/src/account.js@@ -52,18 +52,28 @@ export async function apiFetch(path, options = {}) {headers,});+ // Two retries with 400ms → 1.2s backoff for safe methods. Covers a Vercel+ // cold start (~600ms) plus one transient proxy blip; non-mutating so re-+ // firing is free. Mutating methods (POST/PUT) never retry — the body is+ // already on the wire and the server may have committed it.let res;- try {- res = await doFetch();- } catch (networkErr) {- if (!canRetry) throw networkErr;- await new Promise((r) => setTimeout(r, 400));- res = await doFetch();- }- if (canRetry && TRANSIENT_STATUSES.has(res.status)) {- await new Promise((r) => setTimeout(r, 400));- res = await doFetch();+ let lastErr;+ const maxAttempts = canRetry ? 3 : 1;+ for (let attempt = 0; attempt < maxAttempts; attempt++) {+ if (attempt > 0) {+ await new Promise((r) => setTimeout(r, 400 * attempt * attempt));+ }+ try {+ res = await doFetch();+ } catch (networkErr) {+ lastErr = networkErr;+ res = undefined;+ continue;+ }+ if (canRetry && TRANSIENT_STATUSES.has(res.status)) continue;+ break;}+ if (!res) throw lastErr;if (res.status === 401 && !allowAnonymous) {redirectToLogin();@@ -134,18 +144,52 @@ export async function getMe() {// Uploads a GLB to our R2 bucket and creates the avatar record.// `source` may be a Blob (from CharacterStudio postMessage) or a URL string.//+// Pass `opts.onProgress(pct)` to receive 0..100 upload-percentage callbacks+// (R2 PUT only — presign + commit are negligible by comparison).+//+// Errors carry a `.stage` ('fetch' | 'canonicalize' | 'presign' | 'upload' |+// 'commit') and may carry a `.code` for the UI to act on:+// - 'upload_blocked' — XHR completed with status 0 (CORS preflight or+// a network drop between the browser and R2).+// - 'upload_failed' — R2 returned a non-2xx (auth/signature/checksum).+// - 'not_signed_in' — propagated from apiFetch when the cookie is gone.+//// No explicit auth pre-check: `presign` requires a session, so if the cookie// is missing or expired apiFetch redirects to /login (and throws with// err.redirected = true). Callers that want post-login resume should set// their sentinel BEFORE calling — apiFetch's redirect happens synchronously.-export async function saveRemoteGlbToAccount(source, meta = {}) {+export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {+ const { onProgress } = opts;++ // Preflight the session ourselves so the caller can set up post-login+ // resume state *before* any redirect. apiFetch's built-in 401 handler+ // would jump to /login synchronously, leaving no window to stash a+ // sentinel — we'd lose the staged blob across the round-trip.+ // Tolerate transient probe failures: a 5xx on /api/auth/me (Vercel cold+ // start, dev-proxy hiccup) shouldn't block the upload. If we're truly+ // signed out, the presign call below will 401 and apiFetch redirects.+ let me;+ try {+ me = await getMe();+ } catch (err) {+ console.warn('[account] getMe probe failed, proceeding optimistically:', err?.message);+ me = { id: null, optimistic: true };+ }+ if (me === null) throw stageError('auth', 'Not signed in', { code: 'not_signed_in' });+let blob;if (source instanceof Blob) {blob = source;} else {- const resp = await fetch(source, { mode: 'cors' });- if (!resp.ok) throw new Error(`failed to fetch source GLB: ${resp.status}`);- blob = await resp.blob();+ try {+ const resp = await fetch(source, { mode: 'cors' });+ if (!resp.ok)+ throw stageError('fetch', `failed to fetch source GLB: ${resp.status}`);+ blob = await resp.blob();+ } catch (err) {+ if (err.stage) throw err;+ throw stageError('fetch', err.message || 'failed to fetch source GLB');+ }}// Canonicalize humanoid bone names before upload so the pre-baked Mixamo@@ -168,18 +212,48 @@ export async function saveRemoteGlbToAccount(source, meta = {}) {const contentType = blob.type || 'model/gltf-binary';const checksum = await sha256Hex(blob);- const presign = await postJson('/api/avatars/presign', {- size_bytes: size,- content_type: contentType,- checksum_sha256: checksum,- });+ // Presign + direct browser→R2 PUT is the happy path: cheapest, doesn't+ // route bytes through our function. When the deploy origin isn't in the+ // bucket CORS allowlist (ephemeral Codespaces hosts, branch deploys with a+ // new hostname), the preflight fails. In that case fall through to the+ // server-side proxy upload so the save always completes regardless of+ // bucket CORS state.+ let storageKey = null;+ let presign = null;- const putRes = await fetch(presign.upload_url, {- method: 'PUT',- headers: { 'content-type': contentType },- body: blob,- });- if (!putRes.ok) throw new Error(`R2 upload failed: ${putRes.status}`);+ try {+ presign = await postJson('/api/avatars/presign', {+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ });+ } catch (err) {+ err.stage = err.stage || 'presign';+ throw err;+ }++ try {+ await putToR2({+ url: presign.upload_url,+ blob,+ contentType,+ onProgress,+ });+ storageKey = presign.storage_key;+ } catch (err) {+ if (err.code !== 'upload_blocked') {+ err.stage = err.stage || 'upload';+ throw err;+ }+ console.warn('[account] direct R2 PUT blocked; retrying via server proxy');+ try {+ const proxied = await uploadViaProxy({ blob, contentType, checksum, onProgress });+ storageKey = proxied.storage_key;+ } catch (proxyErr) {+ proxyErr.stage = proxyErr.stage || 'upload';+ throw proxyErr;+ }+ }const sourceMeta = {...(meta.source_meta ||@@ -187,24 +261,30 @@ export async function saveRemoteGlbToAccount(source, meta = {}) {...(retargetedBoneCount > 0 ? { retargeted_bones: retargetedBoneCount } : {}),};- const created = await postJson('/api/avatars', {- storage_key: presign.storage_key,- size_bytes: size,- content_type: contentType,- checksum_sha256: checksum,- name: meta.name || deriveAvatarName(source, checksum),- description: meta.description,- visibility: meta.visibility || 'public',- tags: meta.tags || [],- source: meta.source || 'upload',- source_meta: sourceMeta,- });+ let created;+ try {+ created = await postJson('/api/avatars', {+ storage_key: storageKey,+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ name: meta.name || deriveAvatarName(source, checksum),+ description: meta.description,+ visibility: meta.visibility || 'public',+ tags: meta.tags || [],+ source: meta.source || 'upload',+ source_meta: sourceMeta,+ });+ } catch (err) {+ err.stage = err.stage || 'commit';+ throw err;+ }const avatar = created.avatar;// Fire-and-forget thumbnail + auto-tag pipeline. Doesn't block the caller.// Uses a hidden off-screen model-viewer to render the GLB, captures a JPEG// poster, uploads to R2, and calls Claude Haiku for tags + description.- captureAndTagAvatar(avatar.id, presign.storage_key).catch((err) => {+ captureAndTagAvatar(avatar.id, storageKey).catch((err) => {console.warn('[account] thumbnail/auto-tag pipeline failed silently', err?.message);});@@ -387,6 +467,127 @@ async function captureAndTagAvatar(avatarId, storageKey) {});}+// PUT a Blob to a presigned R2 URL via XHR so the caller can render real+// upload progress and so failures can be distinguished by cause:+// - status 0 → preflight blocked, network drop, or signed-URL host+// unreachable. Almost always CORS in practice.+// - 2xx → success.+// - non-2xx → R2 returned an error (signature mismatch, expired URL,+// checksum failure). Body is text/xml; surface inline.+//+// onProgress is called with an integer 0..100. fetch() has no upload-progress+// hook in any browser, so XHR is the only path that works today.+function putToR2({ url, blob, contentType, onProgress }) {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url, true);+ xhr.setRequestHeader('content-type', contentType);+ if (onProgress) {+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) {+ onProgress(Math.min(99, Math.round((e.loaded / e.total) * 100)));+ }+ };+ xhr.upload.onload = () => onProgress(100);+ }+ xhr.onload = () => {+ if (xhr.status >= 200 && xhr.status < 300) {+ resolve();+ return;+ }+ reject(+ stageError(+ 'upload',+ `R2 upload failed: ${xhr.status} ${xhr.statusText || ''}`.trim(),+ { code: 'upload_failed', status: xhr.status },+ ),+ );+ };+ xhr.onerror = () => {+ // status 0 ⇒ no HTTP response. CORS preflight failure is by far the+ // most common cause; surface a hint the UI can render.+ reject(+ stageError(+ 'upload',+ 'Upload was blocked before reaching R2 (likely a CORS or network issue).',+ { code: 'upload_blocked' },+ ),+ );+ };+ xhr.onabort = () =>+ reject(stageError('upload', 'Upload aborted', { code: 'upload_aborted' }));+ xhr.send(blob);+ });+}++// Server-side upload fallback used when a direct R2 PUT is blocked (CORS or+// network). Streams the blob to /api/avatars/upload, which PUTs it to R2+// using server-side credentials. Same auth + quota path as presign — we get+// back the storage_key to commit with /api/avatars.+//+// Uses XHR (not fetch) so onProgress works in every browser. CSRF is fetched+// from the same single-use endpoint apiFetch uses; we don't go through+// apiFetch because it can't propagate upload progress.+async function uploadViaProxy({ blob, contentType, checksum, onProgress }) {+ const csrf = await getCsrfToken();+ _csrfToken = null; // single-use, like apiFetch+ const qs = new URLSearchParams({ content_type: contentType });+ if (checksum) qs.set('sha256', checksum);+ const url = `${API}/api/avatars/upload?${qs.toString()}`;++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('POST', url, true);+ xhr.withCredentials = true;+ xhr.setRequestHeader('content-type', contentType);+ if (csrf) xhr.setRequestHeader('x-csrf-token', csrf);+ if (onProgress) {+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) {+ onProgress(Math.min(99, Math.round((e.loaded / e.total) * 100)));+ }+ };+ xhr.upload.onload = () => onProgress(100);+ }+ xhr.onload = () => {+ if (xhr.status === 401) {+ redirectToLogin();+ reject(stageError('upload', 'session expired', { status: 401, code: 'not_signed_in' }));+ return;+ }+ let data = null;+ try {+ data = JSON.parse(xhr.responseText);+ } catch {+ /* non-JSON body */+ }+ if (xhr.status >= 200 && xhr.status < 300 && data?.storage_key) {+ resolve(data);+ return;+ }+ reject(+ stageError(+ 'upload',+ data?.error_description || `proxy upload failed: ${xhr.status}`,+ { code: data?.error || 'proxy_upload_failed', status: xhr.status },+ ),+ );+ };+ xhr.onerror = () =>+ reject(stageError('upload', 'proxy upload network error', { code: 'proxy_upload_failed' }));+ xhr.onabort = () =>+ reject(stageError('upload', 'proxy upload aborted', { code: 'upload_aborted' }));+ xhr.send(blob);+ });+}++function stageError(stage, message, extras = {}) {+ const err = new Error(message);+ err.stage = stage;+ Object.assign(err, extras);+ return err;+}+async function postJson(path, body) {const res = await apiFetch(`${API}${path}`, {method: 'POST',diff --git a/src/create.js b/src/create.jsindex df1832275..c4db65e24 100644--- a/src/create.js+++ b/src/create.js@@ -34,7 +34,38 @@ function requireAuthForSelfie() {return true;}+// Probe whether the server has an avatar-reconstruction backend wired. When+// false, the Selfie card on /create stays visible but is marked "coming soon"+// so the user can't dead-end on it; the click handler short-circuits and shows+// an explanatory toast instead of navigating to a page that would 501.+let _reconstructReady = true;+async function probeReconstruct() {+ try {+ const r = await fetch('/api/config', { credentials: 'omit' });+ if (!r.ok) return;+ const j = await r.json();+ _reconstructReady = j?.features?.avatarReconstruct !== false;+ } catch {+ // network blip — keep _reconstructReady true and let the page-level+ // gate inside /create/selfie do the final check.+ }+ if (!_reconstructReady) markSelfieUnavailable();+}++function markSelfieUnavailable() {+ const card = document.getElementById('card-selfie');+ if (!card) return;+ card.setAttribute('aria-disabled', 'true');+ card.style.opacity = '0.55';+ card.style.cursor = 'not-allowed';+ const title = card.querySelector('.card-title');+ if (title && !/coming soon/i.test(title.textContent)) {+ title.textContent = `${title.textContent} · coming soon`;+ }+}+async function boot() {+ probeReconstruct();const creator = new AvatarCreator(document.body, (blob, meta = {}) => {const provider = meta.provider || 'avaturn';// Forward-compatible source mapping:@@ -56,6 +87,13 @@ async function boot() {creator.openDefaultEditor();});wireCard('card-selfie', async () => {+ if (!_reconstructReady) {+ showStatus(+ 'Selfie avatars are still warming up — try the studio for now (it ships every feature).',+ 'info',+ );+ return;+ }if (!requireAuthForSelfie()) return;if (await isAtAvatarLimit()) return;window.location.href = '/create/selfie';diff --git a/vercel.json b/vercel.jsonindex 73a765a8c..e25bbea80 100644--- a/vercel.json+++ b/vercel.json@@ -11,6 +11,10 @@"includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**","maxDuration": 300},+ "api/avatars/[id].js": {+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**",+ "maxDuration": 300+ },"api/tts/speak.js": {"includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**","maxDuration": 60@@ -301,6 +305,40 @@"src": "/embed/","dest": "/embed.html"},+ {+ "src": "/embed/avatar",+ "headers": {+ "content-security-policy": "frame-ancestors *",+ "x-content-type-options": "nosniff",+ "referrer-policy": "strict-origin-when-cross-origin",+ "permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",+ "cross-origin-resource-policy": "cross-origin"+ },+ "dest": "/avatar-embed.html"+ },+ {+ "src": "/embed/avatar/([a-z0-9_-]{3,30})",+ "headers": {+ "content-security-policy": "frame-ancestors *",+ "x-content-type-options": "nosniff",+ "referrer-policy": "strict-origin-when-cross-origin",+ "permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",+ "cross-origin-resource-policy": "cross-origin"+ },+ "dest": "/avatar-embed.html?handle=$1"+ },+ {+ "src": "/@([a-z0-9_-]{3,30})/?",+ "dest": "/handle.html"+ },+ {+ "src": "/widget",+ "dest": "/widget.html"+ },+ {+ "src": "/widget/",+ "dest": "/widget.html"+ },{"src": "/playground","dest": "/playground.html"@@ -943,6 +981,10 @@"src": "/api/avatars/presign","dest": "/api/avatars/[id]"},+ {+ "src": "/api/avatars/upload",+ "dest": "/api/avatars/[id]"+ },{"src": "/api/avatars/view","dest": "/api/avatars/view"@@ -1079,6 +1121,10 @@"src": "/threews/claim","dest": "/threews-claim.html"},+ {+ "src": "/api/users/([^/]+)/avatar",+ "dest": "/api/users/[username]/avatar?username=$1"+ },{"src": "/api/users/([^/]+)","dest": "/api/users/[username]?username=$1"@@ -1165,6 +1211,14 @@"src": "/api/widgets/([A-Za-z0-9_-]+)/chat","dest": "/api/widgets/[id]/chat?id=$1"},+ {+ "src": "/api/widgets/([A-Za-z0-9_-]+)/transcripts",+ "dest": "/api/widgets/[id]/transcripts?id=$1"+ },+ {+ "src": "/api/widgets/([A-Za-z0-9_-]+)/knowledge",+ "dest": "/api/widgets/[id]/knowledge?id=$1"+ },{"src": "/api/widgets","dest": "/api/widgets"@@ -1598,6 +1652,10 @@"src": "/app-demo","dest": "/app-demo.html"},+ {+ "src": "/app-next",+ "dest": "/app-next.html"+ },{"src": "/chat","dest": "/chat/index.html"