Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: home v4, avatar pipeline workers, selfie + agent page enhancements
nirholasc67ccae6cae6
diff --git a/api/_lib/gmgn-feed.js b/api/_lib/gmgn-feed.jsindex ae4998640..0179141a0 100644--- a/api/_lib/gmgn-feed.js+++ b/api/_lib/gmgn-feed.js@@ -8,9 +8,12 @@// GMGN_COOKIE env var containing a valid cf_clearance value.const GMGN_BASE = 'https://gmgn.ai/defi/quotation/v1';+const DEXSCREENER_BASE = 'https://api.dexscreener.com';const POLL_MS = 30_000;const FETCH_TIMEOUT_MS = 10_000;+const CHAIN_TO_DEXSCREENER = { sol: 'solana', eth: 'ethereum', base: 'base', bsc: 'bsc', tron: 'tron' };+function gmgnHeaders() {const h = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',@@ -40,6 +43,63 @@ async function fetchRank({ chain = 'sol', interval = '1h' } = {}) {}}+async function fetchDexScreener({ chain = 'sol' } = {}) {+ const dexChain = CHAIN_TO_DEXSCREENER[chain] || 'solana';+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const boostsRes = await fetch(`${DEXSCREENER_BASE}/token-boosts/top/v1`, {+ headers: { accept: 'application/json' },+ signal: ctrl.signal,+ });+ if (!boostsRes.ok) return { ok: false, status: boostsRes.status };+ const boosts = await boostsRes.json();+ const chainTokens = boosts.filter((t) => t.chainId === dexChain).slice(0, 20);+ if (!chainTokens.length) return { ok: true, rank: [], source: 'dexscreener' };++ const addresses = chainTokens.map((t) => t.tokenAddress).join(',');+ const pairsRes = await fetch(`${DEXSCREENER_BASE}/tokens/v1/${dexChain}/${addresses}`, {+ headers: { accept: 'application/json' },+ signal: ctrl.signal,+ });+ if (!pairsRes.ok) return { ok: false, status: pairsRes.status };+ const pairs = await pairsRes.json();++ const boostMap = new Map(chainTokens.map((t) => [t.tokenAddress, t]));+ const seen = new Set();+ const rank = [];+ for (const pair of pairs) {+ const addr = pair.baseToken?.address;+ if (!addr || seen.has(addr)) continue;+ seen.add(addr);+ const boost = boostMap.get(addr);+ rank.push({+ address: addr,+ symbol: pair.baseToken?.symbol || '???',+ name: pair.baseToken?.name || pair.baseToken?.symbol || 'Unknown',+ price: pair.priceUsd != null ? Number(pair.priceUsd) : null,+ market_cap: pair.marketCap != null ? Number(pair.marketCap) : null,+ volume: pair.volume?.h24 != null ? Number(pair.volume.h24) : null,+ holder_count: null,+ smart_buy_24h: boost?.totalAmount ?? pair.boosts?.active ?? 0,+ smart_sell_24h: 0,+ price_change_1h: pair.priceChange?.h1 != null ? Number(pair.priceChange.h1) : null,+ price_change_24h: pair.priceChange?.h24 != null ? Number(pair.priceChange.h24) : null,+ liquidity: pair.liquidity?.usd != null ? Number(pair.liquidity.usd) : null,+ txns_h1_buys: pair.txns?.h1?.buys ?? null,+ txns_h1_sells: pair.txns?.h1?.sells ?? null,+ });+ }++ rank.sort((a, b) => (b.smart_buy_24h || 0) - (a.smart_buy_24h || 0));+ return { ok: true, rank, source: 'dexscreener' };+ } catch (err) {+ return { ok: false, error: err?.message };+ } finally {+ clearTimeout(tid);+ }+}+let _pollerId = 0;// Map<pollerId, Map<address, prevItem>>const _snapshots = new Map();@@ -70,6 +130,7 @@ export function connectGmgnFeed({ onEvent, signal, chain = 'sol', interval = '1hconst id = ++_pollerId;let active = true;let timer = null;+ let _gmgnBlocked = false;function stop() {active = false;@@ -82,7 +143,20 @@ export function connectGmgnFeed({ onEvent, signal, chain = 'sol', interval = '1hasync function poll() {if (!active) return;- const result = await fetchRank({ chain, interval });+ let result;+ if (!_gmgnBlocked) {+ result = await fetchRank({ chain, interval });+ if (result.ok) {+ result.source = 'gmgn';+ } else if (result.status === 403) {+ _gmgnBlocked = true;+ }+ }++ if (_gmgnBlocked) {+ result = await fetchDexScreener({ chain });+ }+if (!active) return;if (!result.ok) {@@ -103,9 +177,10 @@ export function connectGmgnFeed({ onEvent, signal, chain = 'sol', interval = '1hconst prevCount = prevItem ? Number(prevItem.smart_buy_24h ?? prevItem.smart_buy ?? 0) : 0;if (!prevItem || smartCount > prevCount) {+ const source = result.source || 'gmgn';const ev = {kind: 'smart_entry',- data: normalize(item, smartCount, prevCount, chain, interval),+ data: normalize(item, smartCount, prevCount, chain, interval, source),};pushBuffer(ev);if (active) onEvent(ev);@@ -113,7 +188,8 @@ export function connectGmgnFeed({ onEvent, signal, chain = 'sol', interval = '1h}_snapshots.set(id, next);- onEvent({ kind: 'status', data: { state: 'live', polled_at: Date.now(), count: next.size } });+ const source = result.source || 'gmgn';+ onEvent({ kind: 'status', data: { state: 'live', polled_at: Date.now(), count: next.size, source } });}if (active) timer = setTimeout(poll, POLL_MS);@@ -123,7 +199,7 @@ export function connectGmgnFeed({ onEvent, signal, chain = 'sol', interval = '1hreturn stop;}-function normalize(item, smartCount, prevCount, chain, interval) {+function normalize(item, smartCount, prevCount, chain, interval, source = 'gmgn') {const mc = item.market_cap != null ? Number(item.market_cap) : null;const price = item.price != null ? Number(item.price) : null;return {@@ -143,6 +219,9 @@ function normalize(item, smartCount, prevCount, chain, interval) {is_new: prevCount === 0,chain,interval,+ source,+ txns_h1_buys: item.txns_h1_buys ?? null,+ txns_h1_sells: item.txns_h1_sells ?? null,open_timestamp: item.open_timestamp ?? null,timestamp: Math.floor(Date.now() / 1000),};diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 98fe61259..72f76581d 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -4,13 +4,18 @@// submit(request) → { extJobId, eta }// status(extJobId) → { status, resultGlbUrl?, error? }//-// The Cloud Run service (workers/avatar-reconstruction/) exposes:+// The Cloud Run service can be either:+// - workers/avatar-pipeline-controller/ (v2 — real 3D mesh generation via+// Hunyuan3D / TRELLIS / TripoSR + UniRig auto-rigging)+// - workers/avatar-reconstruction/ (v1 — face texture transfer only)+//+// Both expose the same API:// POST /reconstruct → { job_id, status }// GET /jobs/:id → { status, glb_url?, error? }//// Required env vars:// GCP_RECONSTRUCTION_URL — Cloud Run service URL-// e.g. https://avatar-reconstruction-xxx-uc.a.run.app+// e.g. https://avatar-pipeline-controller-xxx-uc.a.run.app// GCP_RECONSTRUCTION_KEY — bearer secret matching the service's API_KEYfunction readEnv(name) {@@ -91,8 +96,9 @@ export function createRegenProvider() {return {extJobId: data.job_id,- // Face texture pipeline: rembg + MediaPipe + TPS + GLB ops ≈ 15–30 s.- eta: 30,+ // v2 pipeline: mesh generation (30–120s) + UniRig rigging (15–30s).+ // v1 fallback: face texture transfer (15–30s).+ eta: 120,};},diff --git a/api/agents/gmgn.js b/api/agents/gmgn.jsindex c7ae74776..e19ef586e 100644--- a/api/agents/gmgn.js+++ b/api/agents/gmgn.js@@ -62,7 +62,7 @@ async function handleFeed(req, res) {onEvent: (ev) => { if (active) queue.push(ev); },});- writeSse(res, 'hello', { chain, interval, minSmartBuys, source: 'gmgn-poll' });+ writeSse(res, 'hello', { chain, interval, minSmartBuys });// Replay recent buffer so a fresh client isn't blankconst replay = recentGmgnBuffered({ limit: 10 });diff --git a/pages/agent-next.html b/pages/agent-next.htmlindex 3af309fda..b46d2f562 100644--- a/pages/agent-next.html+++ b/pages/agent-next.html@@ -5,6 +5,25 @@<meta name="viewport" content="width=device-width,initial-scale=1" /><title>Agent · three.ws</title><meta name="description" content="A living 3D AI agent on three.ws — talk, animate, embed, remix." />+ <meta name="theme-color" content="#050505" />++ <!-- Open Graph -->+ <meta property="og:type" content="website" />+ <meta property="og:title" id="og-title" content="Agent · three.ws" />+ <meta property="og:description" id="og-desc" content="A living 3D AI agent on three.ws — talk, animate, embed, remix." />+ <meta property="og:url" id="og-url" content="https://three.ws/agent-next" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:image" id="og-image" content="https://three.ws/assets/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />++ <!-- Twitter / X -->+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" id="tw-title" content="Agent · three.ws" />+ <meta name="twitter:description" id="tw-desc" content="A living 3D AI agent on three.ws — talk, animate, embed, remix." />+ <meta name="twitter:creator" content="@nichxbt" />+ <meta name="twitter:image" id="tw-image" content="https://three.ws/assets/og-image.png" />+<link rel="icon" href="/favicon.ico" /><style>:root {@@ -307,13 +326,102 @@}@keyframes spin { to { transform: rotate(360deg); } }- .demo-tag {- position: fixed; bottom: 16px; right: 16px; z-index: 1000;- background: var(--panel); color: var(--muted);+ /* ── CHAT MESSAGES ─────────────────────────────────────── */+ .chat-messages {+ position: absolute; bottom: 0; left: 0; right: 0;+ max-height: 220px; overflow-y: auto;+ padding: 12px 16px 8px;+ display: flex; flex-direction: column; gap: 6px;+ pointer-events: none;+ mask-image: linear-gradient(transparent 0%, black 30%);+ -webkit-mask-image: linear-gradient(transparent 0%, black 30%);+ z-index: 4;+ }+ .chat-msg {+ padding: 8px 14px; border-radius: 12px;+ font-size: 13.5px; line-height: 1.45;+ max-width: 80%; animation: msgIn 0.2s ease-out;+ pointer-events: auto;+ }+ .chat-msg.user {+ align-self: flex-end;+ background: var(--text); color: var(--bg);+ border-bottom-right-radius: 4px;+ }+ .chat-msg.agent {+ align-self: flex-start;+ background: var(--panel); color: var(--text-soft);border: 1px solid var(--border);- padding: 6px 12px; border-radius: 99px;- font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase;+ border-bottom-left-radius: 4px;+ }+ .chat-msg.agent.streaming::after {+ content: "▊"; animation: blink 0.6s infinite;+ }+ @keyframes msgIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }+ @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }++ /* ── VOICE RECORDING STATE ────────────────────────────── */+ .chat-mic.recording {+ background: rgba(239, 68, 68, 0.15);+ color: #ef4444;+ border-color: rgba(239, 68, 68, 0.4);+ animation: micPulse 1.2s ease-in-out infinite;+ }+ @keyframes micPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.3); } 50% { box-shadow: 0 0 0 6px rgba(239, 68, 68, 0); } }++ /* ── ANIMATION DOCK ───────────────────────────────────── */+ .anim-dock {+ position: absolute; bottom: 14px; left: 14px; z-index: 5;+ display: none; align-items: center; gap: 6px;+ background: rgba(5, 5, 5, 0.82);+ backdrop-filter: blur(14px);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 5px 10px;+ font-size: 12px; color: var(--text-soft);+ }+ .anim-dock.visible { display: flex; }+ .anim-dock__name {+ max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ font-weight: 500; color: var(--text);+ }+ .anim-dock__btn {+ background: var(--panel-soft); border: 1px solid var(--border);+ color: var(--text-soft); border-radius: 6px;+ width: 28px; height: 28px;+ display: flex; align-items: center; justify-content: center;+ cursor: pointer; font-size: 12px;+ transition: background 0.12s, color 0.12s;+ }+ .anim-dock__btn:hover { background: var(--border-strong); color: var(--text); }+ .anim-dock__scrub {+ width: 80px; height: 3px;+ -webkit-appearance: none; appearance: none;+ background: var(--border-strong); border-radius: 2px;+ outline: none; cursor: pointer;+ }+ .anim-dock__scrub::-webkit-slider-thumb {+ -webkit-appearance: none; width: 10px; height: 10px;+ border-radius: 50%; background: var(--text);+ cursor: pointer;+ }+ @media (max-width: 720px) {+ .anim-dock { bottom: auto; top: 14px; left: 14px; }}++ /* ── RELATED CARD SKELETON ───────────────────────────── */+ .related-card.skeleton {+ background: var(--panel);+ }+ .related-card.skeleton .meta { background: none; }+ .skeleton-bar {+ height: 12px; border-radius: 4px;+ background: var(--border-strong);+ animation: shimmer 1.4s ease-in-out infinite;+ }+ .skeleton-bar.short { width: 60%; }+ .skeleton-bar.xshort { width: 40%; height: 10px; margin-top: 6px; }+ @keyframes shimmer { 0%, 100% { opacity: 0.4; } 50% { opacity: 0.8; } }</style><script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script></head>@@ -373,6 +481,14 @@eagerstyle="width:100%;height:100%;display:block"></agent-3d>++ <div class="chat-messages" id="chat-messages"></div>++ <div class="anim-dock" id="anim-dock">+ <button class="anim-dock__btn" id="anim-play" type="button" title="Play / Pause">▶</button>+ <span class="anim-dock__name" id="anim-name">—</span>+ <input class="anim-dock__scrub" id="anim-scrub" type="range" min="0" max="1000" value="0" />+ </div></div><div class="chat-dock">@@ -431,29 +547,25 @@<div class="section-eyebrow">More agents</div><h2>Other agents you can embed.</h2><div class="related-grid" id="related-grid">- <a class="related-card" href="/agent-next?id=bacff13e-b64b-4ac0-860d-44f0168ad23b">- <img src="https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/thumb/bacff13e-b64b-4ac0-860d-44f0168ad23b.png" alt="nich" loading="lazy" />- <div class="meta"><div class="name">nich</div><div class="author">@nirholas</div></div>- </a>- <a class="related-card" href="/discover">- <div class="meta"><div class="name">Browse all →</div><div class="author">Public agents</div></div>- </a>- <a class="related-card" href="/create">- <div class="meta"><div class="name">+ Make your own</div><div class="author">Selfie → agent in 60s</div></div>- </a>- <a class="related-card" href="/discover?filter=onchain">- <div class="meta"><div class="name">On-chain agents</div><div class="author">ERC-8004 directory</div></div>- </a>+ <div class="related-card skeleton"><div class="meta"><div class="skeleton-bar short"></div><div class="skeleton-bar xshort"></div></div></div>+ <div class="related-card skeleton"><div class="meta"><div class="skeleton-bar short"></div><div class="skeleton-bar xshort"></div></div></div>+ <div class="related-card skeleton"><div class="meta"><div class="skeleton-bar short"></div><div class="skeleton-bar xshort"></div></div></div>+ <div class="related-card skeleton"><div class="meta"><div class="skeleton-bar short"></div><div class="skeleton-bar xshort"></div></div></div></div></section>- <a class="demo-tag" href="/home-next" title="Redesign demo">DEMO · /agent-next</a><script>// ── Parse ?id= from URL (default: nich) ─────────────────────const params = new URLSearchParams(location.search);const avatarId = params.get('id') || 'bacff13e-b64b-4ac0-860d-44f0168ad23b';const avatarUrl = `${location.origin}/api/avatars/${avatarId}`;+ const agent = document.getElementById('agent');+ const chatForm = document.getElementById('chat-form');+ const chatInput = document.getElementById('chat-input');+ const chatMessages = document.getElementById('chat-messages');+ const micBtn = document.getElementById('chat-mic');+ let agentReady = false;// ── Load avatar metadata ────────────────────────────────────async function loadAvatar() {@@ -468,27 +580,61 @@}}- function hydrate(data) {- document.getElementById('identity-name').textContent = data.name || 'Untitled agent';- document.getElementById('identity-desc').textContent =- data.description || 'A living 3D AI agent on three.ws — talk to it, animate it, embed it on your site, or remix it into your own.';+ function escHtml(s) {+ const d = document.createElement('div');+ d.textContent = s;+ return d.innerHTML;+ }+ function hydrate(data) {+ const name = data.name || 'Untitled agent';+ const desc = data.description || 'A living 3D AI agent on three.ws — talk to it, animate it, embed it on your site, or remix it into your own.';const author = data.author || data.owner_username || (data.source_meta && data.source_meta.provider);+ const displayAuthor = author === 'three-ws-selfie' ? 'three.ws' : (author ? '@' + author : 'community');+ const thumbUrl = data.thumbnail_url || `https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/thumb/${avatarId}.png`;+ const pageUrl = `https://three.ws/agent-next?id=${encodeURIComponent(avatarId)}`;++ document.getElementById('identity-name').textContent = name;+ document.getElementById('identity-desc').textContent = desc;if (author) {document.getElementById('identity-author').innerHTML =- `by <a href="/discover">${author === 'three-ws-selfie' ? 'three.ws' : '@' + author}</a>`;+ `by <a href="/discover">${escHtml(displayAuthor)}</a>`;}- document.title = `${data.name || 'Agent'} · three.ws`;+ document.title = `${name} · three.ws`;document.getElementById('remix-link').href = `/create?fork=${encodeURIComponent(avatarId)}`;- // Mount the agent-3d component now that we know the src- const el = document.getElementById('agent');- el.setAttribute('src', avatarUrl);+ // Dynamic OG / Twitter meta+ const setMeta = (id, attr, val) => { const el = document.getElementById(id); if (el) el.setAttribute(attr, val); };+ setMeta('og-title', 'content', `${name} · three.ws`);+ setMeta('og-desc', 'content', desc);+ setMeta('og-url', 'content', pageUrl);+ setMeta('og-image', 'content', thumbUrl);+ setMeta('tw-title', 'content', `${name} · three.ws`);+ setMeta('tw-desc', 'content', desc);+ setMeta('tw-image', 'content', thumbUrl);++ // Mount the agent-3d component+ agent.setAttribute('src', avatarUrl);- // Update embed snippet+ // Update embed snippet — both the stored string and the visible <pre>const snippet = `<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"><\/script>\n<agent-3d src="${avatarUrl}"><\/agent-3d>`;window._embedSnippet = snippet;+ const pre = document.getElementById('embed-snippet');+ pre.innerHTML =+ `<span class="tag"><script</span> <span class="attr">type</span>=<span class="str">"module"</span> <span class="attr">src</span>=<span class="str">"https://three.ws/agent-3d/latest/agent-3d.js"</span><span class="tag">></script></span>\n` ++ `<span class="tag"><agent-3d</span> <span class="attr">src</span>=<span class="str">"${escHtml(avatarUrl)}"</span><span class="tag">></agent-3d></span>`;++ // Update identity pills based on actual data+ const pills = document.getElementById('identity-pills');+ const tags = data.tags || [];+ let pillsHtml = '<span class="pill live">● Live</span><span class="pill">glTF · GLB</span>';+ if (tags.includes('animated') || data.source === 'avatar-pipeline') pillsHtml += '<span class="pill">Animated</span>';+ if (data.agent_id) pillsHtml += '<span class="pill">On-chain</span>';+ tags.filter(t => !['animated'].includes(t)).slice(0, 3).forEach(t => {+ pillsHtml += `<span class="pill">${escHtml(t)}</span>`;+ });+ pills.innerHTML = pillsHtml;// Hide loadingsetTimeout(() => document.getElementById('loading').classList.add('hidden'), 200);@@ -496,23 +642,59 @@loadAvatar();- // ── Chat form → agent.say() ─────────────────────────────────- const chatForm = document.getElementById('chat-form');- const chatInput = document.getElementById('chat-input');- const agent = document.getElementById('agent');+ // ── Agent ready event ───────────────────────────────────────+ agent.addEventListener('agent:ready', () => { agentReady = true; });++ // ── Chat messages display ───────────────────────────────────+ function appendMsg(role, text) {+ const el = document.createElement('div');+ el.className = `chat-msg ${role}`;+ el.textContent = text;+ chatMessages.appendChild(el);+ chatMessages.scrollTop = chatMessages.scrollHeight;+ return el;+ }++ let streamEl = null;+ agent.addEventListener('brain:message', (e) => {+ const d = e.detail;+ if (d.role === 'assistant' && d.content) {+ if (streamEl) {+ streamEl.textContent = d.content;+ streamEl.classList.remove('streaming');+ streamEl = null;+ } else {+ appendMsg('agent', d.content);+ }+ }+ });++ agent.addEventListener('brain:stream', (e) => {+ if (!streamEl) {+ streamEl = appendMsg('agent', '');+ streamEl.classList.add('streaming');+ }+ streamEl.textContent += e.detail.chunk || '';+ chatMessages.scrollTop = chatMessages.scrollHeight;+ });+ // ── Chat form → agent.ask() ─────────────────────────────────chatForm.addEventListener('submit', (e) => {e.preventDefault();const text = chatInput.value.trim();if (!text) return;- tellAgent(text);+ appendMsg('user', text);+ sendToAgent(text);chatInput.value = '';});- function tellAgent(text) {+ async function sendToAgent(text) {try {- if (agent.ask) agent.ask(text);- else if (agent.say) agent.say(text);+ if (agent.ask) {+ await agent.ask(text);+ } else if (agent.say) {+ agent.say(text);+ }} catch (e) { console.warn('Agent send failed:', e); }}@@ -523,24 +705,92 @@});});+ // ── Voice input via Web Speech API ──────────────────────────+ let recognition = null;+ let recognizing = false;++ if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;+ recognition = new SpeechRecognition();+ recognition.continuous = false;+ recognition.interimResults = true;+ recognition.lang = 'en-US';++ recognition.onstart = () => {+ recognizing = true;+ micBtn.classList.add('recording');+ micBtn.setAttribute('aria-label', 'Stop recording');+ };++ recognition.onend = () => {+ recognizing = false;+ micBtn.classList.remove('recording');+ micBtn.setAttribute('aria-label', 'Voice input');+ };++ recognition.onerror = (e) => {+ recognizing = false;+ micBtn.classList.remove('recording');+ if (e.error !== 'no-speech' && e.error !== 'aborted') {+ console.warn('Speech recognition error:', e.error);+ }+ };++ recognition.onresult = (e) => {+ let transcript = '';+ for (let i = e.resultIndex; i < e.results.length; i++) {+ transcript += e.results[i][0].transcript;+ }+ chatInput.value = transcript;+ if (e.results[e.results.length - 1].isFinal) {+ chatForm.requestSubmit();+ }+ };+ }++ micBtn.addEventListener('click', () => {+ if (!recognition) {+ chatInput.focus();+ return;+ }+ if (recognizing) {+ recognition.stop();+ } else {+ recognition.start();+ }+ });+// ── Action rail handlers ─────────────────────────────────────document.querySelectorAll('.act-btn[data-act]').forEach((b) => {b.addEventListener('click', () => handleAction(b.dataset.act));});- function handleAction(act) {+ async function handleAction(act) {switch (act) {case 'say-hi':- tellAgent('Say hi and wave!');+ appendMsg('user', 'Say hi and wave!');+ if (agent.wave) agent.wave();+ sendToAgent('Say hi and wave!');break;case 'wave':- try { agent.wave?.(); } catch (e) { tellAgent('*wave*'); }+ if (agent.wave) {+ agent.wave();+ } else {+ appendMsg('user', '*wave*');+ sendToAgent('*wave*');+ }break;case 'cheer':- try { agent.playEmote?.('cheer', 1); } catch (e) { tellAgent('*cheer*'); }+ if (agent.playEmote) {+ agent.playEmote('cheer', 1);+ } else {+ appendMsg('user', '*cheer*');+ sendToAgent('*cheer*');+ }break;case 'animate':- tellAgent('Show me one of your animations');+ appendMsg('user', 'Show me one of your animations');+ sendToAgent('Show me one of your animations');break;case 'mocap':location.href = `/mocap-studio?avatar=${encodeURIComponent(avatarId)}`;@@ -552,21 +802,25 @@location.href = `/walk?avatar=${encodeURIComponent(avatarId)}`;break;case 'ar':- tellAgent('Switch to AR mode');+ appendMsg('user', 'Switch to AR mode');+ sendToAgent('Switch to AR mode');break;- case 'tip':- window.location.href = `/tip?avatar=${encodeURIComponent(avatarId)}`;+ case 'tip': {+ const walletAddr = agent.manifest?.wallet || agent.manifest?.solana_wallet;+ if (walletAddr) {+ location.href = `/send?to=${encodeURIComponent(walletAddr)}&label=${encodeURIComponent(document.getElementById('identity-name').textContent)}`;+ } else {+ appendMsg('user', 'I want to tip you!');+ sendToAgent('I want to tip you!');+ }break;+ }case 'remix':location.href = `/create?fork=${encodeURIComponent(avatarId)}`;break;}}- document.getElementById('chat-mic').addEventListener('click', () => {- chatInput.focus();- });-// ── Copy embed ───────────────────────────────────────────────document.getElementById('copy-embed').addEventListener('click', async (e) => {try {@@ -577,12 +831,107 @@e.target.classList.remove('copied');e.target.textContent = 'Copy snippet';}, 1800);- } catch (err) { /* clipboard blocked */ }+ } catch (err) {+ const ta = document.createElement('textarea');+ ta.value = window._embedSnippet || '';+ ta.style.cssText = 'position:fixed;opacity:0';+ document.body.appendChild(ta);+ ta.select();+ document.execCommand('copy');+ ta.remove();+ e.target.classList.add('copied');+ e.target.textContent = '✓ Copied';+ setTimeout(() => { e.target.classList.remove('copied'); e.target.textContent = 'Copy snippet'; }, 1800);+ }});document.getElementById('open-docs').addEventListener('click', () => {window.open('/docs#embed', '_blank');});++ // ── Related agents — fetch from /api/explore ─────────────────+ async function loadRelated() {+ const grid = document.getElementById('related-grid');+ try {+ const r = await fetch(`/api/explore?source=avatar&quality=high&limit=7&only3d=1`);+ if (!r.ok) throw new Error('explore fetch failed');+ const json = await r.json();+ const items = (json.items || []).filter(it => it.avatarId !== avatarId).slice(0, 4);++ if (items.length === 0) {+ grid.innerHTML = buildFallbackCards();+ return;+ }++ let html = '';+ items.forEach(it => {+ const href = `/agent-next?id=${encodeURIComponent(it.avatarId || it.id)}`;+ const img = it.image || `https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/thumb/${it.avatarId}.png`;+ const name = escHtml(it.name || 'Untitled');+ const author = escHtml(it.author?.handle ? '@' + it.author.handle : 'community');+ html += `<a class="related-card" href="${href}">` ++ `<img src="${escHtml(img)}" alt="${name}" loading="lazy" />` ++ `<div class="meta"><div class="name">${name}</div><div class="author">${author}</div></div>` ++ `</a>`;+ });++ if (items.length < 4) {+ html += `<a class="related-card" href="/create"><div class="meta"><div class="name">+ Make your own</div><div class="author">Selfie → agent in 60s</div></div></a>`;+ }++ grid.innerHTML = html;+ } catch (e) {+ console.warn('Related agents fetch failed:', e);+ grid.innerHTML = buildFallbackCards();+ }+ }++ function buildFallbackCards() {+ return `<a class="related-card" href="/discover"><div class="meta"><div class="name">Browse all →</div><div class="author">Public agents</div></div></a>` ++ `<a class="related-card" href="/create"><div class="meta"><div class="name">+ Make your own</div><div class="author">Selfie → agent in 60s</div></div></a>` ++ `<a class="related-card" href="/discover?filter=onchain"><div class="meta"><div class="name">On-chain agents</div><div class="author">ERC-8004 directory</div></div></a>`;+ }++ loadRelated();++ // ── Animation dock — basic playback controls ─────────────────+ const animDock = document.getElementById('anim-dock');+ const animPlayBtn = document.getElementById('anim-play');+ const animName = document.getElementById('anim-name');+ const animScrub = document.getElementById('anim-scrub');+ let animPlaying = false;++ agent.addEventListener('agent:ready', () => {+ const clips = agent._viewer?.clips || agent._scene?.clips;+ if (clips && clips.length > 0) {+ animDock.classList.add('visible');+ animName.textContent = clips[0].name || 'Clip 1';+ animPlaying = true;+ animPlayBtn.textContent = '⏸';+ }+ });++ animPlayBtn.addEventListener('click', () => {+ const mixer = agent._viewer?.mixer || agent._scene?.mixer;+ if (!mixer) return;+ animPlaying = !animPlaying;+ animPlayBtn.textContent = animPlaying ? '⏸' : '▶';+ if (animPlaying) {+ mixer.timeScale = 1;+ } else {+ mixer.timeScale = 0;+ }+ });++ animScrub.addEventListener('input', () => {+ const mixer = agent._viewer?.mixer || agent._scene?.mixer;+ if (!mixer) return;+ const action = mixer._actions?.[0];+ if (!action) return;+ const clip = action.getClip();+ action.time = (animScrub.value / 1000) * clip.duration;+ if (!animPlaying) mixer.update(0);+ });</script></body></html>diff --git a/pages/app-next.html b/pages/app-next.htmlindex ddfaa8d02..a330c0ed8 100644--- a/pages/app-next.html+++ b/pages/app-next.html@@ -139,15 +139,6 @@<path d="M1 1l5 5 5-5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" /></svg></button>- <div class="nxt-more-menu" id="nxt-more-menu" role="menu" hidden>- <a href="/discover" role="menuitem">Discover agents</a>- <a href="/create" role="menuitem">Create an avatar</a>- <a href="/marketplace" role="menuitem">Marketplace</a>- <a href="/studio" role="menuitem">Studio</a>- <a href="/docs" role="menuitem">Docs</a>- <div class="nxt-more-sep" role="separator"></div>- <a href="/app-classic" role="menuitem">Classic viewer</a>- </div><!-- Auth surface — single pill, swaps to user chip when signed in --><div class="nxt-auth">@@ -472,5 +463,17 @@<!-- Live toast region --><div class="nxt-toast" id="nxt-toast" role="status" aria-live="polite" hidden></div>++ <!-- Explore dropdown — lives outside <header> so backdrop-filter+ does not clip the menu below the header's bottom edge. -->+ <div class="nxt-more-menu" id="nxt-more-menu" role="menu" hidden>+ <a href="/discover" role="menuitem">Discover agents</a>+ <a href="/create" role="menuitem">Create an avatar</a>+ <a href="/marketplace" role="menuitem">Marketplace</a>+ <a href="/studio" role="menuitem">Studio</a>+ <a href="/docs" role="menuitem">Docs</a>+ <div class="nxt-more-sep" role="separator"></div>+ <a href="/app-classic" role="menuitem">Classic viewer</a>+ </div></body></html>diff --git a/pages/community.html b/pages/community.htmlindex aacfd5ba4..28873e9e0 100644--- a/pages/community.html+++ b/pages/community.html@@ -2,43 +2,165 @@<html lang="en"><head><meta charset="utf-8" />- <meta http-equiv="X-UA-Compatible" content="IE=edge" />- <title>three.ws — Community</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Community — three.ws</title>+ <meta name="description" content="Join the three.ws community — follow builds, share agents, and connect with creators building the 3D agent layer of the internet." />+ <meta name="theme-color" content="#0b0b10" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="apple-touch-icon" href="/pwa-192x192.png" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Community — three.ws" />+ <meta property="og:description" content="Follow builds, share agents, and connect with creators building the 3D agent layer of the internet." />+ <meta property="og:url" content="https://three.ws/community" />+ <meta property="og:image" content="https://three.ws/og-image.png" />++ <link rel="canonical" href="https://three.ws/community" /><link rel="stylesheet" href="/style.css" />- <link rel="stylesheet" href="/features.css" />- <link rel="stylesheet" href="/community.css" />- <link rel="stylesheet" href="/nav.css" />- <link rel="stylesheet" href="/footer.css" />- <link rel="stylesheet" href="/mobile.css" />- <script defer src="/footer-newsletter.js"></script>+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <script defer src="/footer-newsletter.js"></script>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0b0b10;+ --panel: #14141c;+ --border: #22222e;+ --text: #e8e8f0;+ --muted: #8a8aa0;+ --accent: #6a5cff;+ }+ * { box-sizing: border-box; }+ body {+ font: 15px/1.6 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif;+ color: var(--text);+ margin: 0;+ background: var(--bg);+ min-height: 100vh;+ }+ .wrap { max-width: 860px; margin: 0 auto; padding: 64px 24px 96px; }+ .eyebrow {+ font-size: 12px;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--accent);+ font-weight: 600;+ margin-bottom: 14px;+ }+ h1 {+ font-size: clamp(32px, 5vw, 48px);+ margin: 0 0 14px;+ letter-spacing: -0.025em;+ line-height: 1.1;+ font-weight: 600;+ }+ .sub { color: var(--muted); font-size: 17px; margin: 0 0 48px; max-width: 620px; line-height: 1.55; }+ .grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 18px;+ margin-bottom: 48px;+ }+ @media (max-width: 640px) { .grid { grid-template-columns: 1fr; } }+ .card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 16px;+ padding: 28px 24px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ transition: border-color 0.15s;+ }+ .card:hover { border-color: #33334a; }+ .card h2 { margin: 0; font-size: 18px; font-weight: 600; }+ .card p { margin: 0; color: var(--muted); font-size: 14.5px; line-height: 1.55; }+ .card .icon { font-size: 28px; }+ .card-link {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--accent);+ text-decoration: none;+ font-size: 14px;+ font-weight: 600;+ margin-top: auto;+ }+ .card-link:hover { text-decoration: underline; }++ .section { margin-bottom: 48px; }+ .section h2 { font-size: 22px; margin: 0 0 16px; font-weight: 600; }+ .section p { color: var(--muted); font-size: 15px; line-height: 1.6; max-width: 620px; }+ .section ul { margin: 12px 0 0; padding-left: 20px; }+ .section li { color: var(--muted); font-size: 14.5px; margin-bottom: 8px; line-height: 1.5; }+ .section li strong { color: var(--text); }+ a { color: var(--accent); }+ </style></head>- <body class="features-page">- <header class="site-header">- <h1 class="site-header-brand">- <a href="/" aria-label="three.ws home"><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span class="wordmark-dot" aria-hidden="true"></span>three.ws</a>+ <body>+ <header class="site-header" style="display:flex;align-items:center;padding:0 32px;height:56px;position:sticky;top:0;z-index:100;">+ <h1 style="margin:0;font-size:inherit;font-weight:inherit;line-height:inherit;">+ <a href="/" style="color:inherit;text-decoration:none;" aria-label="three.ws home">+ <img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span class="wordmark-dot" aria-hidden="true"></span>three.ws+ </a></h1><div id="nav-container"></div></header><script src="/nav.js"></script>- <div class="page-background">- <div class="page-background-grid"></div>- <div class="page-background-mesh"></div>- </div>+ <div class="wrap">+ <div class="eyebrow">Community</div>+ <h1>Build with us.</h1>+ <p class="sub">three.ws is built in the open. Follow along, share what you're building, and help shape the 3D agent layer of the internet.</p>- <main class="features-main">- <section class="hero">- <div class="hero-content scroll-reveal">- <h1 class="hero-title">Join the <em>Community</em></h1>- <p class="hero-subtitle">- Connect with other creators, share your work, and get help from the community.- </p>+ <div class="grid">+ <div class="card">+ <span class="icon">𝕏</span>+ <h2>Follow on X</h2>+ <p>Live builds, demos, release notes, and conversations with the team. Most day-to-day updates happen here.</p>+ <a class="card-link" href="https://x.com/trythreews" target="_blank" rel="noopener noreferrer">@trythreews →</a>+ </div>+ <div class="card">+ <span class="icon">🛠</span>+ <h2>GitHub</h2>+ <p>The codebase is public. File issues, read the source, or submit a PR. SDKs, examples, and the embed runtime all live here.</p>+ <a class="card-link" href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener noreferrer">nirholas/three.ws →</a>+ </div>+ <div class="card">+ <span class="icon">📚</span>+ <h2>Docs</h2>+ <p>API reference, embed guides, SDK quickstarts, and the Solana agent-kit. Start here if you're integrating.</p>+ <a class="card-link" href="/docs">Read the docs →</a></div>- </section>- </main>-+ <div class="card">+ <span class="icon">🎓</span>+ <h2>Tutorials</h2>+ <p>Step-by-step guides for creating your first agent, embedding on your site, minting on Solana, and adding paid skills.</p>+ <a class="card-link" href="/tutorials">Browse tutorials →</a>+ </div>+ </div>++ <div class="section">+ <h2>Ways to get involved</h2>+ <ul>+ <li><strong>Ship an agent.</strong> Create one at <a href="/create">/create</a>, embed it on your site, and share it on X with #threews.</li>+ <li><strong>Report bugs.</strong> Open an issue on <a href="https://github.com/nirholas/three.ws/issues" target="_blank" rel="noopener noreferrer">GitHub</a> — we triage daily.</li>+ <li><strong>Contribute code.</strong> PRs are welcome. Check the repo for open issues labeled <code>good first issue</code>.</li>+ <li><strong>Build an integration.</strong> The MCP server, A2A protocol, and x402 payment layer are all open for third-party tools.</li>+ <li><strong>Share feedback.</strong> Tweet at us, open a discussion on GitHub, or email <a href="mailto:[email protected]">[email protected]</a>.</li>+ </ul>+ </div>++ <div class="section">+ <h2>Newsletter</h2>+ <p>Weekly updates on features, protocol changes, and community highlights. No spam — unsubscribe anytime.</p>+ </div>+ </div>+<div id="footer-container"></div><script src="/footer.js"></script>-</body>+ </body></html>diff --git a/pages/create-review.html b/pages/create-review.htmlindex 644bc4f0a..51be47172 100644--- a/pages/create-review.html+++ b/pages/create-review.html@@ -45,13 +45,29 @@#05060a;}- .crumb {- padding: 14px 22px;- font-size: 13px;+ .topbar {+ display: flex;+ align-items: center;+ gap: 14px;+ margin-bottom: 20px;+ }+ .back-link {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ background: var(--panel);+ border: 1px solid var(--border);color: var(--muted);+ padding: 8px 14px 8px 10px;+ border-radius: 9px;+ font-size: 13px;+ font-weight: 500;+ text-decoration: none;+ cursor: pointer;+ transition: border-color 120ms, color 120ms;}- .crumb a { color: var(--muted); text-decoration: none; }- .crumb a:hover { color: var(--accent); }+ .back-link:hover { border-color: var(--border-strong, #2a2c3a); color: var(--text); }+ .back-link svg { flex-shrink: 0; }main.stage {flex: 1;@@ -1191,13 +1207,17 @@</header><script src="/nav.js"></script>- <nav class="crumb">- <a href="/">three.ws</a> ·- <a href="/create">Create</a> ·- <span>Preview</span>- </nav>-<main class="stage" id="main">+ <div class="topbar">+ <a href="/create/selfie" class="back-link" id="back-link" aria-label="Back to create">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <line x1="19" y1="12" x2="5" y2="12" />+ <polyline points="12 19 5 12 12 5" />+ </svg>+ Back to create+ </a>+ </div>+<h1 id="heading">Meet your avatar</h1><p class="sub" id="subhead">Try every capability before you save. Talk to it, drop it on any site,diff --git a/pages/create-selfie.html b/pages/create-selfie.htmlindex fb7146173..762ef04da 100644--- a/pages/create-selfie.html+++ b/pages/create-selfie.html@@ -6,7 +6,7 @@<title>Selfie to avatar · three.ws</title><link rel="icon" href="/favicon.ico" /><meta name="description" content="One selfie. About a minute. A rigged 3D avatar that works everywhere." />- <meta name="robots" content="noindex" />+ <meta name="robots" content="index, follow" /><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" />@@ -151,7 +151,7 @@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.drag { border-color: var(--accent); background: rgba(214, 255, 61, 0.05); cursor: copy; }.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; }@@ -232,7 +232,7 @@transition: border-color 120ms, background 120ms;}.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.drag { border-color: var(--accent); background: rgba(214, 255, 61, 0.05); cursor: copy; }.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); }@@ -398,6 +398,23 @@}.build-step.active .bstep-label { color: var(--text); font-weight: 500; }.build-step.completed .bstep-label { color: var(--muted); }+ .build-step.failed .bstep-dot {+ background: var(--danger);+ border-color: var(--danger);+ animation: none;+ }+ .build-step.failed .bstep-dot::after {+ content: '×';+ display: block;+ color: #fff;+ font: 700 14px/1 sans-serif;+ text-align: center;+ position: absolute;+ top: -1px;+ left: 2px;+ }+ .build-step.failed .bstep-label { color: var(--danger); font-weight: 500; }+ .build-step.failed::after { background: var(--danger-dim); }.build-viewer {position: relative;@@ -730,8 +747,10 @@margin: 0 auto;}.cam-bar button.shutter:disabled {- opacity: 0.55;+ opacity: 0.35;cursor: not-allowed;+ filter: grayscale(0.6);+ transition: opacity 200ms, filter 200ms;}.cam-bar .spacer { flex: 1; }.cam-countdown {@@ -769,6 +788,35 @@transition: background 120ms;}.done-actions .btn-secondary:hover { background: rgba(214, 255, 61, 0.06); }++ .photo-tips {+ margin: 16px 0 0;+ padding: 12px 16px;+ background: rgba(214, 255, 61, 0.03);+ border: 1px solid rgba(214, 255, 61, 0.08);+ border-radius: 10px;+ font-size: 13px;+ color: var(--muted);+ }+ .photo-tips .tips-title {+ margin: 0 0 6px;+ font-weight: 600;+ font-size: 12px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--text);+ opacity: 0.7;+ }+ .photo-tips ul {+ margin: 0;+ padding-left: 18px;+ list-style: disc;+ }+ .photo-tips li {+ margin-bottom: 2px;+ line-height: 1.45;+ }+ .photo-tips li:last-child { margin-bottom: 0; }</style><link rel="stylesheet" href="/mobile.css" /><script@@ -817,10 +865,20 @@<input type="file" data-slot-input="frontal" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />+ <div class="photo-tips" id="photo-tips">+ <p class="tips-title">Tips for best results</p>+ <ul>+ <li>Face the camera directly — no extreme angles</li>+ <li>Good, even lighting — avoid harsh shadows or backlighting</li>+ <li>Remove sunglasses, masks, or anything covering your face</li>+ <li>Keep hair away from your forehead and jawline if possible</li>+ </ul>+ </div>+<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 class="fid-label">Add side angles <span class="fid-note">(optional — adds ~30s for more detail)</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>@@ -879,7 +937,7 @@<!-- Step 3: Building your avatar --><section class="step" data-step="building"><h1>Building your avatar…</h1>- <p class="sub">This usually takes 30–90 seconds. Don't close this tab.</p>+ <p class="sub">This usually takes 1–2 minutes. Don't close this tab.</p><div class="build-progress" role="list" aria-label="Build progress"><div class="build-step completed" data-bstep="upload" role="listitem">@@ -934,6 +992,7 @@camera-controlsshadow-intensity="0.7"shadow-softness="0.8"+ loading="lazy"environment-image="neutral"exposure="0.95"camera-orbit="0deg 78deg auto"@@ -1148,6 +1207,24 @@if (errEl) { errEl.textContent = msg; errEl.classList.add('show'); }if (retryBtn) retryBtn.classList.add('show');+ // Stop the spinner and mark the active step as failed.+ const ring = document.querySelector('.build-ring');+ if (ring) ring.style.display = 'none';+ const veil = document.querySelector('.build-veil');+ if (veil) veil.style.display = 'none';+ const activeStep = document.querySelector('.build-step.active');+ if (activeStep) {+ activeStep.classList.remove('active');+ activeStep.classList.add('failed');+ const label = activeStep.querySelector('.bstep-label');+ if (label) label.textContent = 'Failed';+ }+ // Update the heading+ const heading = document.querySelector('[data-step="building"] h1');+ if (heading) heading.textContent = "Couldn't build your avatar";+ const sub = document.querySelector('[data-step="building"] .sub');+ if (sub) sub.textContent = 'Check the tips below and try again with a new photo.';+// If we can identify the failing slot, highlight it for retake.if (detail.slot) {const slotFrame = document.querySelector(@@ -1156,7 +1233,6 @@: `.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;@@ -1169,6 +1245,24 @@const retryBtn = document.getElementById('build-retry-btn');errEl?.classList.remove('show');retryBtn?.classList.remove('show');+ // Reset the building step UI for next attempt.+ const ring = document.querySelector('.build-ring');+ if (ring) ring.style.display = '';+ const veil = document.querySelector('.build-veil');+ if (veil) veil.style.display = '';+ const heading = document.querySelector('[data-step="building"] h1');+ if (heading) heading.textContent = 'Building your avatar…';+ const sub = document.querySelector('[data-step="building"] .sub');+ if (sub) sub.textContent = "This usually takes 1–2 minutes. Don't close this tab.";+ document.querySelectorAll('.build-step').forEach((s) => {+ s.classList.remove('completed', 'active', 'failed');+ });+ const uploadStep = document.querySelector('.build-step[data-bstep="upload"]');+ if (uploadStep) uploadStep.classList.add('completed');+ const processStep = document.querySelector('.build-step[data-bstep="process"]');+ if (processStep) processStep.classList.add('active');+ const statusText = document.getElementById('build-status-text');+ if (statusText) statusText.textContent = 'Processing your face…';showStep('capture');});diff --git a/pages/home-v4.html b/pages/home-v4.htmlnew file mode 100644index 000000000..9894667d3--- /dev/null+++ b/pages/home-v4.html@@ -0,0 +1,513 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>three.ws — Give Your AI a Body</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="author" content="nirholas" />+ <meta+ name="description"+ content="The 3D identity layer for AI agents. Create, animate, and deploy embodied agents — owned on Solana."+ />+ <meta name="theme-color" content="#000000" />+ <meta name="mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />+ <meta name="apple-mobile-web-app-title" content="three.ws" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="three.ws — Give Your AI a Body" />+ <meta+ property="og:description"+ content="The 3D identity layer for AI agents. Create, animate, and deploy embodied agents — owned on Solana."+ />+ <meta property="og:url" content="https://three.ws/" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />++ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="three.ws — Give Your AI a Body" />+ <meta+ name="twitter:description"+ content="The 3D identity layer for AI agents. Create, animate, and deploy embodied agents — owned on Solana."+ />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="canonical" href="https://three.ws/" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="apple-touch-icon" href="/pwa-192x192.png" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/home-v4.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/footer.css" media="print" onload="this.media='all'" />+ <script defer src="/footer-newsletter.js"></script>+ <script+ type="module"+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"+ ></script>+ <script type="module" src="/src/home-v4-hero.js"></script>+ <script type="module" src="/src/home-act2-viewer.js"></script>+ <script type="module" src="/src/home-v4-scroll.js"></script>+ </head>+ <body class="home-page v4-page">+ <a href="#main-content" class="h-skip-link">Skip to main content</a>+ <header>+ <h1>+ <a href="/" aria-label="three.ws home"+ ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span+ class="wordmark-dot"+ aria-hidden="true"+ ></span+ >three.ws</a+ >+ </h1>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main id="main-content">++ <!-- ═══════════════════════════════════════════════════════════+ SECTION 1: THE STAGE (hero — full viewport)+ ═══════════════════════════════════════════════════════════ -->+ <section class="v4-hero" id="stage">+ <div class="v4-hero-grid" aria-hidden="true"></div>+ <canvas class="v4-hero-canvas" id="v4-hero-canvas"></canvas>+ <div class="v4-hero-vignette" aria-hidden="true"></div>++ <div class="v4-hero-text">+ <div class="v4-eyebrow v4-reveal">+ <span class="v4-eyebrow-dot"></span>+ <span>The 3D layer for onchain AI agents</span>+ </div>+ <h2 class="v4-title v4-reveal">Give your AI<br />a <em>body</em>.</h2>+ <p class="v4-subtitle v4-reveal">+ Create a 3D avatar from a selfie. Animate it with 70+ moves.+ Give it an AI brain. Mint it on Solana. Embed it anywhere with one tag.+ </p>+ <div class="v4-cta-row v4-reveal">+ <a href="/create" class="v4-btn-primary">+ <span>Build your agent</span>+ <span class="arrow">→</span>+ </a>+ <a href="#experience" class="v4-btn-ghost">Try it live</a>+ </div>+ <ul class="v4-standards v4-reveal" aria-label="Supported standards">+ <li>glTF 2.0</li>+ <li>GLB</li>+ <li>Solana</li>+ <li>Metaplex Core</li>+ <li>A2A</li>+ <li>MCP</li>+ </ul>+ </div>++ <div class="v4-scroll-hint" aria-hidden="true">+ <span>scroll</span>+ <span class="v4-scroll-line"></span>+ </div>+ </section>++ <!-- ═══════════════════════════════════════════════════════════+ SECTION 2: THE EXPERIENCE (interactive demo)+ ═══════════════════════════════════════════════════════════ -->+ <section class="v4-experience" id="experience">+ <div class="v4-exp-bg" aria-hidden="true"></div>+ <div class="v4-exp-content">+ <div class="v4-exp-stage">+ <canvas class="v4-exp-canvas" id="v4-exp-canvas"></canvas>+ </div>+ <div class="v4-exp-sidebar">+ <div class="v4-exp-header">+ <div class="v4-eyebrow">+ <span class="v4-eyebrow-dot"></span>+ <span>Pick & animate</span>+ </div>+ <h2 class="v4-section-title">Your agent.<br /><em>Any move.</em></h2>+ <p class="v4-section-lede">+ Choose a model, click any animation. 70+ moves from dance to combat — all retargeted to any skeleton in real time.+ </p>+ </div>+ <div class="v4-exp-models">+ <button class="v4-model-btn active" data-model="/avatars/cz.glb" data-label="CZ">CZ</button>+ <button class="v4-model-btn" data-model="/animations/robotexpressive.glb" data-label="Robot">Robot</button>+ <button class="v4-model-btn" data-model="/animations/soldier.glb" data-label="Soldier">Soldier</button>+ </div>+ <div class="v4-exp-chips" id="v4-anim-chips"></div>+ <div class="v4-exp-stats" id="v4-stats">+ <div class="v4-stat">+ <span class="v4-stat-value" data-stat="agents">—</span>+ <span class="v4-stat-label">agents live</span>+ </div>+ <div class="v4-stat">+ <span class="v4-stat-value" data-stat="animations">70+</span>+ <span class="v4-stat-label">animations</span>+ </div>+ <div class="v4-stat">+ <span class="v4-stat-value" data-stat="onchain">—</span>+ <span class="v4-stat-label">on-chain</span>+ </div>+ </div>+ </div>+ </div>+ </section>++ <!-- ═══════════════════════════════════════════════════════════+ SECTION 3: THE CREATION (how it works)+ ═══════════════════════════════════════════════════════════ -->+ <section class="v4-creation" id="creation">+ <div class="v4-creation-inner">+ <div class="v4-creation-header v4-reveal">+ <p class="v4-section-label">How it works</p>+ <h2 class="v4-section-title">From selfie to<br /><em>earning agent</em> in four steps.</h2>+ </div>+ <ol class="v4-steps">+ <li class="v4-step v4-reveal">+ <a href="/create" class="v4-step-card">+ <div class="v4-step-num">01</div>+ <div class="v4-step-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="8" r="4"/>+ <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>+ </svg>+ </div>+ <div class="v4-step-body">+ <h3>Create your avatar</h3>+ <p>Snap a selfie or upload a GLB. three.ws renders a full-body 3D agent in the browser.</p>+ </div>+ <span class="v4-step-cta">Start creating →</span>+ </a>+ </li>+ <li class="v4-step v4-reveal">+ <a href="/dashboard/agents" class="v4-step-card">+ <div class="v4-step-num">02</div>+ <div class="v4-step-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <rect x="5" y="2" width="14" height="14" rx="3"/>+ <circle cx="9" cy="8" r="1.2"/>+ <circle cx="15" cy="8" r="1.2"/>+ <path d="M9 11.5h6M2 19l3-3h14l3 3v2a1 1 0 01-1 1H3a1 1 0 01-1-1v-2z"/>+ </svg>+ </div>+ <div class="v4-step-body">+ <h3>Build your agent</h3>+ <p>Give it a name, on-chain identity, and AI brain. Connect Claude, GPT, or your own model over MCP.</p>+ </div>+ <span class="v4-step-cta">Configure agent →</span>+ </a>+ </li>+ <li class="v4-step v4-reveal">+ <a href="/dashboard/widgets" class="v4-step-card">+ <div class="v4-step-num">03</div>+ <div class="v4-step-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <rect x="2" y="3" width="9" height="9" rx="1.5"/>+ <rect x="13" y="3" width="9" height="9" rx="1.5"/>+ <rect x="2" y="14" width="9" height="9" rx="1.5"/>+ <rect x="13" y="14" width="9" height="9" rx="1.5"/>+ </svg>+ </div>+ <div class="v4-step-body">+ <h3>Embed anywhere</h3>+ <p>Drop a single <code><agent-3d></code> tag on any site. Chat widget, floating button, full-screen — one line of HTML.</p>+ </div>+ <span class="v4-step-cta">Create widget →</span>+ </a>+ </li>+ <li class="v4-step v4-reveal">+ <a href="/dashboard/monetize" class="v4-step-card">+ <div class="v4-step-num">04</div>+ <div class="v4-step-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="8.5"/>+ <path d="M12 7v10M9 9.5h4.5a2.5 2.5 0 010 5H10a2.5 2.5 0 000 5H14"/>+ </svg>+ </div>+ <div class="v4-step-body">+ <h3>Start earning</h3>+ <p>Charge per message, set a subscription, or accept tips in USDC. Withdrawals land in your Solana wallet.</p>+ </div>+ <span class="v4-step-cta">Set up monetization →</span>+ </a>+ </li>+ </ol>+ <div class="v4-creation-footer v4-reveal">+ <a href="/create" class="v4-btn-primary">+ <span>Build your agent now</span>+ <span class="arrow">→</span>+ </a>+ </div>+ </div>+ </section>++ <!-- ═══════════════════════════════════════════════════════════+ SECTION 4: THE ECOSYSTEM (bento feature grid)+ ═══════════════════════════════════════════════════════════ -->+ <section class="v4-ecosystem" id="ecosystem">+ <div class="v4-eco-inner">+ <div class="v4-eco-header v4-reveal">+ <p class="v4-section-label">The platform</p>+ <h2 class="v4-section-title">Everything your agent needs.<br /><em>Nothing it doesn't.</em></h2>+ </div>+ <div class="v4-bento">+ <article class="v4-bento-card v4-bento-lg v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <rect x="2" y="3" width="20" height="14" rx="2"/>+ <path d="M8 21h8M12 17v4"/>+ </svg>+ </div>+ <h3>Embed anywhere</h3>+ <p>One <code><agent-3d></code> tag. Any site. Inline, floating, full-screen, section — five widget modes, zero config.</p>+ <div class="v4-bento-code">+ <code><agent-3d body="/avatar.glb" brain="claude"></agent-3d></code>+ </div>+ </article>+ <article class="v4-bento-card v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 2L2 7l10 5 10-5-10-5z"/>+ <path d="M2 17l10 5 10-5"/>+ <path d="M2 12l10 5 10-5"/>+ </svg>+ </div>+ <h3>On-chain identity</h3>+ <p>Mint a Metaplex Core asset on Solana. Verifiable, portable, discoverable by any A2A or MCP client.</p>+ </article>+ <article class="v4-bento-card v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 2a4 4 0 014 4v2a4 4 0 01-8 0V6a4 4 0 014-4z"/>+ <path d="M6 10v1a6 6 0 0012 0v-1M12 17v4M8 21h8"/>+ </svg>+ </div>+ <h3>Voice & chat</h3>+ <p>Real-time speech with lip-sync, text chat with streaming responses. Push-to-talk or always-on.</p>+ </article>+ <article class="v4-bento-card v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="3"/>+ <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>+ </svg>+ </div>+ <h3>AI brain</h3>+ <p>Connect Claude, GPT, Gemini, or your own model. MCP tools, skills, memory — all pluggable.</p>+ </article>+ <article class="v4-bento-card v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <rect x="3" y="3" width="7" height="7" rx="1"/>+ <rect x="14" y="3" width="7" height="7" rx="1"/>+ <rect x="3" y="14" width="7" height="7" rx="1"/>+ <rect x="14" y="14" width="7" height="7" rx="1"/>+ </svg>+ </div>+ <h3>Marketplace</h3>+ <p>Browse avatars, agents, skills, and widgets built by the community. Install with a click.</p>+ </article>+ <article class="v4-bento-card v4-reveal">+ <div class="v4-bento-icon">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <polyline points="16 18 22 12 16 6"/>+ <polyline points="8 6 2 12 8 18"/>+ </svg>+ </div>+ <h3>SDK & docs</h3>+ <p>JavaScript, Python, Rust. Full API reference, tutorials, and ready-to-fork examples.</p>+ </article>+ </div>+ </div>+ </section>++ <!-- ═══════════════════════════════════════════════════════════+ SECTION 5: THE CLOSE (CTA + footer)+ ═══════════════════════════════════════════════════════════ -->+ <section class="v4-close" id="close">+ <div class="v4-close-bg" aria-hidden="true"></div>+ <div class="v4-close-inner">+ <canvas class="v4-close-canvas" id="v4-close-canvas"></canvas>+ <div class="v4-close-text v4-reveal">+ <h2 class="v4-close-title">Your AI deserves<br />a <em>body</em>.</h2>+ <div class="v4-cta-row">+ <a href="/create" class="v4-btn-primary">+ <span>Build your agent</span>+ <span class="arrow">→</span>+ </a>+ <a href="/docs" class="v4-btn-ghost">Read the docs</a>+ </div>+ </div>+ <div class="v4-close-snippet v4-reveal">+ <div class="v4-snippet-label">Add to any site</div>+ <pre class="v4-snippet-code"><code><script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+<agent-3d body="/your-avatar.glb" brain="claude"></agent-3d></code></pre>+ </div>+ </div>+ </section>++ <!-- ── Footer (reuse existing horizon style) ── -->+ <footer class="h-footer h-footer-horizon">+ <div class="h-footer-glow-line" aria-hidden="true"></div>+ <div class="h-footer-floor" aria-hidden="true"></div>+ <div class="h-footer-haze" aria-hidden="true"></div>+ <div class="h-footer-watermark" aria-hidden="true">three.ws</div>+ <div class="h-footer-avatar" aria-hidden="true">+ <model-viewer+ src="/animations/robotexpressive.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="20deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0"+ exposure="0.7"+ environment-image="neutral"+ camera-orbit="0deg 80deg 9m"+ field-of-view="45deg"+ loading="lazy"+ ></model-viewer>+ </div>++ <div class="h-footer-cta">+ <div class="h-footer-newsletter">+ <h3>Stay in the loop</h3>+ <p>Get updates on new features, agent tooling, and protocol changes.</p>+ <form class="h-footer-newsletter-form" data-newsletter-form novalidate>+ <input+ type="email"+ class="h-footer-newsletter-input"+ name="email"+ placeholder="Enter your email"+ aria-label="Email address"+ autocomplete="email"+ required+ />+ <button+ type="submit"+ class="h-footer-newsletter-btn"+ aria-label="Subscribe"+ >+ <svg viewBox="0 0 16 16" aria-hidden="true">+ <path+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+ d="M2 8h11m0 0L9 4m4 4l-4 4"+ />+ </svg>+ </button>+ </form>+ <p+ class="h-footer-newsletter-msg"+ data-newsletter-msg+ aria-live="polite"+ ></p>+ </div>+ <div class="h-footer-community">+ <h3>Join the community</h3>+ <p>Follow along for builds, demos, and conversations with the team.</p>+ <a+ class="h-footer-community-btn"+ href="https://x.com/trythreews"+ target="_blank"+ rel="noopener noreferrer"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path+ fill="currentColor"+ d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"+ />+ </svg>+ Follow on X+ </a>+ </div>+ </div>+ <div class="h-footer-inner">+ <div class="h-footer-brand-col">+ <div class="h-footer-brand">+ <img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" />+ <span class="wordmark-dot" aria-hidden="true"></span>+ <span>three.ws</span>+ </div>+ <p class="h-footer-tagline">Give your AI a body.</p>+ <div class="h-footer-socials">+ <a+ class="h-footer-social"+ href="https://x.com/trythreews"+ target="_blank"+ rel="noopener noreferrer"+ aria-label="three.ws on X"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path+ fill="currentColor"+ d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"+ />+ </svg>+ </a>+ <a+ class="h-footer-social"+ href="https://github.com/nirholas/three.ws"+ target="_blank"+ rel="noopener noreferrer"+ aria-label="three.ws on GitHub"+ >+ <svg viewBox="0 0 16 16" aria-hidden="true">+ <path+ fill="currentColor"+ d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"+ />+ </svg>+ </a>+ </div>+ </div>+ <nav class="h-footer-links" aria-label="Footer">+ <div class="h-footer-link-col">+ <h4 class="h-footer-link-heading">Product</h4>+ <a href="/create">Create</a>+ <a href="/studio">Studio</a>+ <a href="/widgets">Widgets</a>+ <a href="/discover">Discover</a>+ </div>+ <div class="h-footer-link-col">+ <h4 class="h-footer-link-heading">Developers</h4>+ <a href="/docs">Docs</a>+ <a+ href="https://github.com/nirholas/three.ws"+ target="_blank"+ rel="noopener noreferrer"+ >GitHub</a+ >+ <a+ href="https://developers.metaplex.com/core"+ target="_blank"+ rel="noopener noreferrer"+ >Metaplex Core</a+ >+ </div>+ <div class="h-footer-link-col">+ <h4 class="h-footer-link-heading">Resources</h4>+ <a href="/blog">Blog</a>+ <a href="/dashboard">Dashboard</a>+ </div>+ </nav>+ </div>+ <div class="h-footer-bottom">+ <p class="h-footer-legal">© 2026 three.ws — All rights reserved.</p>+ <div class="h-footer-legal-links">+ <a href="/legal/privacy">Privacy Policy</a>+ <a href="/legal/tos">Terms of Use</a>+ </div>+ </div>+ </footer>+ </main>+ </body>+</html>diff --git a/public/app-next.css b/public/app-next.cssindex 268e5dd79..5bf50432c 100644--- a/public/app-next.css+++ b/public/app-next.css@@ -182,9 +182,9 @@ body.app-next-body {}.nxt-more-menu {- position: absolute;- top: calc(var(--nxt-header-h) - 4px);- right: 72px;+ position: fixed;+ top: var(--nxt-header-h);+ right: 0;min-width: 200px;padding: 6px;background: var(--nxt-glass-strong);@@ -1417,20 +1417,30 @@ body.app-next-body.nxt-chrome-hidden .nxt-chat-dock .nxt-chat-chips {/* ── NichAgent panel positioning override ─────────────────────────────── */-/* When we trigger the panel from our chat input, position it above the input- so the conversation reads top-down with the input at the bottom (chat-like). */+/* Dock the chat panel to the right so the avatar stays visible. The panel+ sits directly above the chat dock, which also slides right when active. */body.app-next-body .nich-panel {position: fixed;- left: 50%;+ right: 16px;bottom: 168px;- right: auto;+ left: auto;top: auto;- transform: translateX(-50%);- width: min(640px, calc(100vw - 32px));- max-height: min(60vh, 540px);+ transform: none;+ width: min(380px, calc(100vw - 32px));+ max-height: min(50vh, 480px);z-index: 24;}+/* When chat is active, slide the input dock to the right to align with the+ conversation panel — keeps input + thread as one unified column.+ Uses translate instead of left/right so the transition animates cleanly. */+body.app-next-body.nxt-chat-active .nxt-chat-dock {+ left: auto;+ right: 16px;+ transform: none;+ width: min(380px, calc(100vw - 32px));+}+/* ── Mobile ────────────────────────────────────────────────────────────── */@media (max-width: 720px) {@@ -1442,7 +1452,6 @@ body.app-next-body .nich-panel {@media (max-width: 640px) {.nxt-brand-tag { display: none; }.nxt-more { padding: 7px 8px; }- .nxt-more-menu { right: 12px; }.nxt-action kbd { display: none; }.nxt-action { padding: 7px 10px; font-size: 12px; }.nxt-action span { display: none; }@@ -1456,8 +1465,18 @@ body.app-next-body .nich-panel {.nxt-icon-btn { width: 28px; height: 28px; }.nxt-help__grid { grid-template-columns: 80px 1fr; font-size: 12px; }body.app-next-body .nich-panel {+ left: 50%;+ right: auto;+ transform: translateX(-50%);+ width: min(640px, calc(100vw - 32px));bottom: 142px;- max-height: 50vh;+ max-height: 45vh;+ }+ body.app-next-body.nxt-chat-active .nxt-chat-dock {+ left: 50%;+ right: auto;+ transform: translateX(-50%);+ width: min(640px, calc(100vw - 32px));}}diff --git a/public/embed.js b/public/embed.jsindex 46bf44410..c7fb830e6 100644--- a/public/embed.js+++ b/public/embed.js@@ -22,6 +22,13 @@catch (e) { return 'https://three.ws'; }})();+ var SANDBOX_VALUE = 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox';++ function isCrossOrigin(src) {+ try { return new URL(src, location.href).origin !== location.origin; }+ catch (e) { return true; }+ }+function attr(el, name, fallback) {var v = el && el.getAttribute && el.getAttribute(name);return v != null && v !== '' ? v : fallback;@@ -80,16 +87,9 @@var iframe = document.createElement('iframe');iframe.title = 'three.ws widget ' + widgetId;iframe.allow = 'autoplay; clipboard-write; xr-spatial-tracking';- // Sandbox set:- // allow-scripts — viewer + RPC server need JS.- // allow-same-origin — postMessage handshake to /widget needs it.- // allow-forms — talking-agent chat input is a <form>.- // allow-popups + escape — passport "view on chain" target=_blank.- // Notably NOT allowed: top-navigation, modals, pointer-lock, presentation.- iframe.setAttribute(- 'sandbox',- 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',- );+ if (isCrossOrigin(src)) {+ iframe.setAttribute('sandbox', SANDBOX_VALUE);+ }iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');iframe.setAttribute('width', width);iframe.setAttribute('height', height);@@ -428,15 +428,9 @@var iframe = document.createElement('iframe');iframe.src = src;iframe.allow = 'autoplay; camera; microphone; xr-spatial-tracking; clipboard-write';- // Explicit sandbox matching the widget snippet — same engine, same- // surface area. allow-same-origin is required for postMessage handshake- // + the bridge upgrade path that imports embed-host-bridge.js.- // allow-forms covers the talking-agent chat input; allow-popups lets- // passport-style "view on chain" links open in a new tab.- iframe.setAttribute(- 'sandbox',- 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',- );+ if (isCrossOrigin(src)) {+ iframe.setAttribute('sandbox', SANDBOX_VALUE);+ }iframe.setAttribute('allowtransparency', 'true');iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');iframe.setAttribute('loading', 'lazy');diff --git a/public/features.json b/public/features.jsonindex 12be65f88..74c44a4da 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-26T22:41:57.487Z",+ "generated_at": "2026-05-27T05:45:53.957Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -814,6 +814,24 @@"indexable": true,"tags": []},+ {+ "path": "/news/live-on-aws-marketplace",+ "title": "three.ws Launches on AWS Marketplace, Bringing On-Chain 3D AI Agents to Enterprise Procurement",+ "description": "three.ws is now live on AWS Marketplace as a SaaS subscription. Every AWS customer can subscribe directly, billing rolls onto their AWS invoice, AWS Activate credits apply, and the spend counts toward Enterprise Discount Program commitments. The first fully on-chain 3D AI agent platform listed on the AWS catalog.",+ "added": null,+ "auth": null,+ "indexable": true,+ "tags": []+ },+ {+ "path": "/news/joined-aws-partner-network",+ "title": "three.ws Joins the AWS Partner Network",+ "description": "three.ws is now an official AWS Partner, enrolled in the AWS Partner Network (APN) Software Path as a Technology Partner. The open-source platform for 3D AI agents on-chain is the first fully Web3-native ISV to join APN with a Solana / EVM on-chain identity stack. AWS Marketplace SaaS listing shipping next.",+ "added": null,+ "auth": null,+ "indexable": true,+ "tags": []+ },{"path": "/news/partnered-with-hackernoon","title": "three.ws Partners with HackerNoon",diff --git a/public/gmgn.html b/public/gmgn.htmlindex e629fb27e..e3ffa0b00 100644--- a/public/gmgn.html+++ b/public/gmgn.html@@ -219,7 +219,7 @@<div class="stat-item"><span class="lbl">Smart entries seen</span><span class="val gmgn" id="stat-entries">0</span></div><div class="stat-item"><span class="lbl">Tokens tracked</span><span class="val" id="stat-tracked">—</span></div><div class="stat-item"><span class="lbl">Last poll</span><span class="val" id="stat-polled">—</span></div>- <div class="stat-item"><span class="lbl">Source</span><span class="val">GMGN.ai</span></div>+ <div class="stat-item"><span class="lbl">Source</span><span class="val" id="stat-source"><a href="https://gmgn.ai" target="_blank" rel="noopener" style="color:var(--gmgn);text-decoration:none">GMGN.ai</a></span></div><div class="stat-item" style="margin-left:auto"><span class="lbl">$THREE on GMGN</span><span class="val" id="three-gmgn-status" style="display:inline-flex;align-items:center;gap:6px">@@ -278,13 +278,13 @@</div><aside id="side"><div class="side-header" id="side-header">- <span class="side-title">Smart Money Feed</span>+ <span class="side-title" id="side-title">Smart Money Feed</span><button class="side-control-btn" id="side-minimize" title="Minimize">_</button></div><div id="side-content">- <h2>Live smart money entries</h2>+ <h2 id="feed-heading">Live entries</h2><button type="button" class="feed-jump" id="feed-jump" data-visible="false" aria-live="polite">↑ <span id="feed-jump-count">0</span> new</button>- <div id="feed"><div class="empty">Waiting for smart money events…</div></div>+ <div id="feed"><div class="empty">Waiting for events…</div></div></div></aside></main>@@ -428,18 +428,32 @@const mc = ev.market_cap ? formatMc(ev.market_cap) : null;const total = ev.smart_buy_24h ?? 0;const delta = ev.smart_buy_delta ?? 0;+ const isDex = (ev.source || activeSource) === 'dexscreener';let text;- if (delta >= 5) {- text = `Alert! ${sym} exploding on smart money radar! ${delta} new wallets just entered.`;- } else if (ev.is_new) {- text = mc- ? `New smart money entry. ${total} wallets loading ${sym}. Market cap ${mc}.`- : `New smart money entry. ${sym} just hit the radar with ${total} wallets.`;- } else if (delta > 0) {- text = `${delta} more smart wallet${delta > 1 ? 's' : ''} entered ${sym}. Total ${total} in.`;+ if (isDex) {+ const buys = ev.txns_h1_buys ?? 0;+ if (ev.is_new) {+ text = mc+ ? `Trending token detected. ${sym} with ${total} boosts. Market cap ${mc}. ${buys} buys in the last hour.`+ : `New on the radar. ${sym} trending with ${total} boosts.`;+ } else if (delta > 0) {+ text = `${sym} gaining momentum. ${delta} new boosts, ${buys} hourly buys.`;+ } else {+ text = `${sym} holding strong with ${total} boosts.`;+ }} else {- text = `Smart money holding ${sym}. ${total} wallets tracked.`;+ if (delta >= 5) {+ text = `Alert! ${sym} exploding on smart money radar! ${delta} new wallets just entered.`;+ } else if (ev.is_new) {+ text = mc+ ? `New smart money entry. ${total} wallets loading ${sym}. Market cap ${mc}.`+ : `New smart money entry. ${sym} just hit the radar with ${total} wallets.`;+ } else if (delta > 0) {+ text = `${delta} more smart wallet${delta > 1 ? 's' : ''} entered ${sym}. Total ${total} in.`;+ } else {+ text = `Smart money holding ${sym}. ${total} wallets tracked.`;+ }}$('stage-title').textContent = sym;@@ -473,6 +487,20 @@const pct24h = ev.price_change_24h != null ? ev.price_change_24h.toFixed(1) : null;const addr = ev.address;const chain = ev.chain || 'sol';+ const src = ev.source || activeSource;+ const isDex = src === 'dexscreener';+ const dexChains = { sol: 'solana', eth: 'ethereum', base: 'base', bsc: 'bsc' };++ const badgeIcon = isDex ? '🚀' : '🧠';+ const badgeLabel = isDex ? ev.smart_buy_24h : ev.smart_buy_24h;+ const linkBase = isDex+ ? `https://dexscreener.com/${dexChains[chain] || 'solana'}/${escHtml(addr)}`+ : `https://gmgn.ai/${chain}/token/${escHtml(addr)}`;+ const linkLabel = isDex ? 'DexScreener' : 'GMGN';++ const txnHtml = isDex && ev.txns_h1_buys != null+ ? `<div class="ev-stat"><span class="lbl">Buys 1h</span><span class="val up">${ev.txns_h1_buys}</span></div><div class="ev-stat"><span class="lbl">Sells 1h</span><span class="val dn">${ev.txns_h1_sells ?? 0}</span></div>`+ : '';const div = document.createElement('div');div.className = `ev-card${replay ? ' replay' : ''}${isNew ? ' is-new' : ''}${isAlert ? ' is-alert' : ''}`;@@ -482,21 +510,19 @@${isNew ? '<span class="ev-tag-new">NEW</span>' : ''}<span class="ev-name">${escHtml(ev.name)}</span><span class="ev-badge${isAlert ? ' alert' : ''}">- 🧠 ${ev.smart_buy_24h}${delta > 0 ? `<span class="ev-delta">+${delta}</span>` : ''}+ ${badgeIcon} ${badgeLabel}${delta > 0 ? `<span class="ev-delta">+${delta}</span>` : ''}</span></div><div class="ev-stats"><div class="ev-stat"><span class="lbl">Market cap</span><span class="val">${escHtml(mc)}</span></div><div class="ev-stat"><span class="lbl">Volume</span><span class="val">${escHtml(vol)}</span></div>+ ${txnHtml}${pct1h != null ? `<div class="ev-stat"><span class="lbl">1h</span><span class="val ${Number(pct1h) >= 0 ? 'up' : 'dn'}">${Number(pct1h) >= 0 ? '+' : ''}${pct1h}%</span></div>` : ''}${pct24h != null ? `<div class="ev-stat"><span class="lbl">24h</span><span class="val ${Number(pct24h) >= 0 ? 'up' : 'dn'}">${Number(pct24h) >= 0 ? '+' : ''}${pct24h}%</span></div>` : ''}</div><div class="ev-time">${new Date(ev.timestamp * 1000).toLocaleTimeString()} ·- ${chain === 'sol' && addr ? `<a class="ev-link" href="https://gmgn.ai/sol/token/${escHtml(addr)}" target="_blank" rel="noopener">View on GMGN ↗</a>` : ''}- ${chain === 'eth' && addr ? `<a class="ev-link" href="https://gmgn.ai/eth/token/${escHtml(addr)}" target="_blank" rel="noopener">View on GMGN ↗</a>` : ''}- ${chain === 'base' && addr ? `<a class="ev-link" href="https://gmgn.ai/base/token/${escHtml(addr)}" target="_blank" rel="noopener">View on GMGN ↗</a>` : ''}- ${chain === 'bsc' && addr ? `<a class="ev-link" href="https://gmgn.ai/bsc/token/${escHtml(addr)}" target="_blank" rel="noopener">View on GMGN ↗</a>` : ''}+ ${addr ? `<a class="ev-link" href="${linkBase}" target="_blank" rel="noopener">View on ${linkLabel} ↗</a>` : ''}</div>`;return div;}@@ -536,6 +562,23 @@let es = null;const dot = $('status-dot');const statusText = $('status-text');+ let activeSource = 'gmgn';++ function setSource(src) {+ activeSource = src || 'gmgn';+ const srcEl = $('stat-source');+ const sideTitle = $('side-title');+ const feedHeading = $('feed-heading');+ if (src === 'dexscreener') {+ srcEl.innerHTML = '<a href="https://dexscreener.com" target="_blank" rel="noopener" style="color:var(--accent);text-decoration:none">DexScreener</a>';+ if (sideTitle) sideTitle.textContent = 'Trending Feed';+ if (feedHeading) feedHeading.textContent = 'Live trending tokens';+ } else {+ srcEl.innerHTML = '<a href="https://gmgn.ai" target="_blank" rel="noopener" style="color:var(--gmgn);text-decoration:none">GMGN.ai</a>';+ if (sideTitle) sideTitle.textContent = 'Smart Money Feed';+ if (feedHeading) feedHeading.textContent = 'Live smart money entries';+ }+ }function setStatus(state, text) {dot.className = `dot ${state}`;@@ -544,7 +587,7 @@let _reconnectTimer = null;function scheduleReconnect(ms) {- if (_reconnectTimer) return; // already scheduled — don't double-fire+ if (_reconnectTimer) return;_reconnectTimer = setTimeout(() => { _reconnectTimer = null; connect(); }, ms);}@@ -566,6 +609,7 @@es.addEventListener('smart_entry', (msg) => {const ev = JSON.parse(msg.data);+ if (ev.source) setSource(ev.source);handleEvent(ev, ev.replay || false);if ($('ctl-chain').value === 'sol') checkThreeToken(ev);});@@ -573,19 +617,19 @@es.addEventListener('status', (msg) => {const d = JSON.parse(msg.data);if (d.state === 'live') {- setStatus('live', `Live · polled ${new Date(d.polled_at).toLocaleTimeString()}`);+ if (d.source) setSource(d.source);+ const srcLabel = activeSource === 'dexscreener' ? 'DexScreener' : 'GMGN';+ setStatus('live', `Live · ${srcLabel} · polled ${new Date(d.polled_at).toLocaleTimeString()}`);$('stat-tracked').textContent = d.count ?? '—';$('stat-polled').textContent = new Date(d.polled_at).toLocaleTimeString();} else if (d.state === 'error') {- setStatus('down', `GMGN API error ${d.status || ''}`);+ setStatus('down', `API error ${d.status || ''} — retrying…`);}});es.addEventListener('ping', () => {});es.addEventListener('close', () => {- // Server sends event: close then closes stream. onerror will also fire- // immediately after — scheduleReconnect deduplicates both.setStatus('down', 'Session ended — reconnecting…');es = null;scheduleReconnect(4000);diff --git a/public/home-v4.css b/public/home-v4.cssnew file mode 100644index 000000000..380ddbbcd--- /dev/null+++ b/public/home-v4.css@@ -0,0 +1,757 @@+/* ═══════════════════════════════════════════════════════════════+ home-v4.css — cinematic homepage with particle hero+ All classes prefixed v4- to avoid collision with h- classes+ ═══════════════════════════════════════════════════════════════ */++:root {+ --v4-gold: #ffd76a;+ --v4-gold-dim: rgba(255, 215, 106, 0.15);+ --v4-mint: #6ee7b7;+ --v4-violet: #a78bfa;+ --v4-bg: #050505;+ --v4-surface: rgba(10, 8, 6, 0.72);+ --v4-glass: blur(20px) saturate(140%);+ --v4-ink: #f0efe8;+ --v4-ink-dim: rgba(240, 239, 232, 0.5);+ --v4-stroke: rgba(255, 255, 255, 0.08);+ --v4-radius: 14px;+ --v4-radius-sm: 8px;+}++.v4-page {+ background: var(--v4-bg);+ color: var(--v4-ink);+}++/* ── Scroll reveal ────────────────────────────────────────── */+.v4-reveal {+ opacity: 0;+ transform: translateY(24px);+ transition: opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1),+ transform 0.7s cubic-bezier(0.16, 1, 0.3, 1);+}+.v4-reveal.revealed {+ opacity: 1;+ transform: none;+}++/* ══════════════════════════════════════════════════════════════+ SECTION 1: THE STAGE (Hero)+ ══════════════════════════════════════════════════════════════ */+.v4-hero {+ position: relative;+ height: 100vh;+ height: 100dvh;+ overflow: hidden;+ display: flex;+ align-items: flex-end;+ background: var(--v4-bg);+}++.v4-hero-grid {+ position: absolute;+ inset: 0;+ background-image:+ linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),+ linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);+ background-size: 80px 80px;+ mask-image: radial-gradient(ellipse 80% 60% at 50% 70%, black 20%, transparent 70%);+ -webkit-mask-image: radial-gradient(ellipse 80% 60% at 50% 70%, black 20%, transparent 70%);+ transform: perspective(600px) rotateX(35deg);+ transform-origin: 50% 100%;+ opacity: 0.6;+}++.v4-hero-canvas {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ z-index: 1;+}++.v4-hero-vignette {+ position: absolute;+ inset: 0;+ z-index: 2;+ pointer-events: none;+ background: radial-gradient(ellipse 70% 70% at 50% 45%, transparent 30%, var(--v4-bg) 100%);+}++.v4-hero-text {+ position: relative;+ z-index: 3;+ padding: clamp(2rem, 6vh, 5rem) clamp(1.5rem, 4vw, 4rem);+ max-width: 640px;+}++.v4-eyebrow {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 0.8rem;+ font-weight: 500;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--v4-gold);+ margin-bottom: 1rem;+}++.v4-eyebrow-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--v4-gold);+ animation: v4-pulse 2s ease-in-out infinite;+}++@keyframes v4-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.3; }+}++.v4-title {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: clamp(2.8rem, 7vw, 5.5rem);+ font-weight: 700;+ line-height: 1.05;+ letter-spacing: -0.03em;+ margin: 0 0 1.2rem;+}++.v4-title em,+.v4-section-title em,+.v4-close-title em {+ font-style: normal;+ background: linear-gradient(135deg, var(--v4-gold), #ff9f43);+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ background-clip: text;+}++.v4-subtitle {+ font-size: clamp(1rem, 1.6vw, 1.2rem);+ line-height: 1.6;+ color: var(--v4-ink-dim);+ margin: 0 0 2rem;+ max-width: 480px;+}++.v4-cta-row {+ display: flex;+ gap: 12px;+ flex-wrap: wrap;+ margin-bottom: 2rem;+}++.v4-btn-primary {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 14px 28px;+ background: var(--v4-ink);+ color: var(--v4-bg);+ font-weight: 600;+ font-size: 0.95rem;+ border-radius: 999px;+ text-decoration: none;+ transition: transform 0.2s, box-shadow 0.2s;+}+.v4-btn-primary:hover {+ transform: translateY(-1px);+ box-shadow: 0 4px 24px rgba(255, 215, 106, 0.25);+}+.v4-btn-primary .arrow {+ transition: transform 0.2s;+}+.v4-btn-primary:hover .arrow {+ transform: translateX(3px);+}++.v4-btn-ghost {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 14px 28px;+ border: 1px solid var(--v4-stroke);+ color: var(--v4-ink);+ font-weight: 500;+ font-size: 0.95rem;+ border-radius: 999px;+ text-decoration: none;+ transition: border-color 0.2s, background 0.2s;+}+.v4-btn-ghost:hover {+ border-color: rgba(255, 255, 255, 0.2);+ background: rgba(255, 255, 255, 0.04);+}++.v4-standards {+ display: flex;+ gap: 12px;+ flex-wrap: wrap;+ list-style: none;+ padding: 0;+ margin: 0;+}+.v4-standards li {+ font-size: 0.72rem;+ font-weight: 500;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--v4-ink-dim);+ padding: 4px 10px;+ border: 1px solid var(--v4-stroke);+ border-radius: 999px;+}++.v4-scroll-hint {+ position: absolute;+ bottom: 2rem;+ right: 2rem;+ z-index: 3;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ font-size: 0.7rem;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--v4-ink-dim);+ animation: v4-scroll-bob 2s ease-in-out infinite;+}+.v4-scroll-line {+ width: 1px;+ height: 32px;+ background: linear-gradient(to bottom, var(--v4-ink-dim), transparent);+}+@keyframes v4-scroll-bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(6px); }+}++/* ══════════════════════════════════════════════════════════════+ SECTION 2: THE EXPERIENCE (Interactive Demo)+ ══════════════════════════════════════════════════════════════ */+.v4-experience {+ position: relative;+ min-height: 100vh;+ min-height: 100dvh;+ background: var(--v4-bg);+ overflow: hidden;+}++.v4-exp-bg {+ position: absolute;+ inset: 0;+ background: radial-gradient(ellipse 60% 50% at 30% 50%, rgba(255, 190, 80, 0.06), transparent 70%);+}++.v4-exp-content {+ position: relative;+ display: grid;+ grid-template-columns: 1fr 1fr;+ min-height: 100vh;+ min-height: 100dvh;+ max-width: 1400px;+ margin: 0 auto;+}++.v4-exp-stage {+ position: relative;+ display: flex;+ align-items: center;+ justify-content: center;+ background: radial-gradient(ellipse 60% 50% at 50% 50%, rgba(255, 190, 80, 0.04), transparent 70%);+}++.v4-exp-canvas {+ width: 100%;+ height: 80vh;+ max-height: 700px;+}++.v4-exp-sidebar {+ display: flex;+ flex-direction: column;+ justify-content: center;+ padding: clamp(2rem, 4vw, 4rem);+ gap: 1.5rem;+}++.v4-exp-header {+ margin-bottom: 0.5rem;+}++.v4-section-title {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: clamp(2rem, 4vw, 3.2rem);+ font-weight: 700;+ line-height: 1.1;+ letter-spacing: -0.02em;+ margin: 0.6rem 0 0;+}++.v4-section-lede {+ font-size: 1rem;+ line-height: 1.6;+ color: var(--v4-ink-dim);+ margin: 0.8rem 0 0;+ max-width: 420px;+}++.v4-section-label {+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--v4-gold);+ margin: 0;+}++/* model picker */+.v4-exp-models {+ display: flex;+ gap: 8px;+}+.v4-model-btn {+ padding: 8px 18px;+ border-radius: 999px;+ border: 1px solid var(--v4-stroke);+ background: transparent;+ color: var(--v4-ink-dim);+ font-size: 0.85rem;+ font-weight: 500;+ cursor: pointer;+ transition: border-color 0.2s, color 0.2s, background 0.2s;+}+.v4-model-btn:hover {+ border-color: rgba(255, 255, 255, 0.2);+ color: var(--v4-ink);+}+.v4-model-btn.active {+ border-color: var(--v4-gold);+ color: var(--v4-gold);+ background: var(--v4-gold-dim);+}++/* animation chips */+.v4-exp-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ max-height: 200px;+ overflow-y: auto;+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.1) transparent;+}+.v4-chip {+ padding: 6px 14px;+ border-radius: 999px;+ border: 1px solid var(--v4-stroke);+ background: transparent;+ color: var(--v4-ink-dim);+ font-size: 0.78rem;+ cursor: pointer;+ transition: border-color 0.15s, color 0.15s, background 0.15s;+ white-space: nowrap;+}+.v4-chip:hover {+ border-color: rgba(255, 255, 255, 0.2);+ color: var(--v4-ink);+}+.v4-chip.active {+ border-color: var(--v4-gold);+ color: var(--v4-gold);+ background: var(--v4-gold-dim);+}++/* stats bar */+.v4-exp-stats {+ display: flex;+ gap: 2rem;+ padding-top: 1.5rem;+ border-top: 1px solid var(--v4-stroke);+}+.v4-stat {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.v4-stat-value {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: 1.5rem;+ font-weight: 700;+ letter-spacing: -0.02em;+}+.v4-stat-label {+ font-size: 0.72rem;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--v4-ink-dim);+}++/* ══════════════════════════════════════════════════════════════+ SECTION 3: THE CREATION (How It Works)+ ══════════════════════════════════════════════════════════════ */+.v4-creation {+ position: relative;+ padding: clamp(4rem, 10vh, 8rem) 0;+ background: var(--v4-bg);+}++.v4-creation-inner {+ max-width: 1200px;+ margin: 0 auto;+ padding: 0 clamp(1.5rem, 4vw, 4rem);+}++.v4-creation-header {+ text-align: center;+ margin-bottom: clamp(3rem, 6vh, 5rem);+}++.v4-steps {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 1px;+ list-style: none;+ padding: 0;+ margin: 0;+ background: var(--v4-stroke);+ border-radius: var(--v4-radius);+ overflow: hidden;+}++.v4-step {+ background: var(--v4-bg);+}++.v4-step-card {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ padding: clamp(1.5rem, 2.5vw, 2.5rem);+ height: 100%;+ text-decoration: none;+ color: inherit;+ transition: background 0.3s;+}+.v4-step-card:hover {+ background: rgba(255, 255, 255, 0.02);+}++.v4-step-num {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: 0.8rem;+ font-weight: 600;+ color: var(--v4-gold);+ letter-spacing: 0.05em;+}++.v4-step-icon {+ width: 40px;+ height: 40px;+ color: var(--v4-ink-dim);+}+.v4-step-icon svg {+ width: 100%;+ height: 100%;+}++.v4-step-body h3 {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: 1.15rem;+ font-weight: 600;+ margin: 0 0 0.4rem;+}+.v4-step-body p {+ font-size: 0.88rem;+ line-height: 1.5;+ color: var(--v4-ink-dim);+ margin: 0;+}+.v4-step-body code {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 0.82em;+ background: rgba(255, 255, 255, 0.06);+ padding: 2px 5px;+ border-radius: 4px;+}++.v4-step-cta {+ margin-top: auto;+ font-size: 0.82rem;+ font-weight: 500;+ color: var(--v4-gold);+}+.v4-step-card:hover .v4-step-cta {+ text-decoration: underline;+}++.v4-creation-footer {+ text-align: center;+ margin-top: clamp(2.5rem, 5vh, 4rem);+}++/* ══════════════════════════════════════════════════════════════+ SECTION 4: THE ECOSYSTEM (Bento Grid)+ ══════════════════════════════════════════════════════════════ */+.v4-ecosystem {+ position: relative;+ padding: clamp(4rem, 10vh, 8rem) 0;+ background: var(--v4-bg);+}++.v4-eco-inner {+ max-width: 1200px;+ margin: 0 auto;+ padding: 0 clamp(1.5rem, 4vw, 4rem);+}++.v4-eco-header {+ text-align: center;+ margin-bottom: clamp(3rem, 6vh, 5rem);+}++.v4-bento {+ display: grid;+ grid-template-columns: repeat(6, 1fr);+ gap: 1px;+ background: var(--v4-stroke);+ border-radius: var(--v4-radius);+ overflow: hidden;+}++.v4-bento-card {+ background: var(--v4-bg);+ padding: clamp(1.5rem, 2.5vw, 2.5rem);+ display: flex;+ flex-direction: column;+ gap: 0.8rem;+ transition: background 0.3s;+ position: relative;+ grid-column: span 2;+}+.v4-bento-card:hover {+ background: rgba(255, 255, 255, 0.02);+}++.v4-bento-lg {+ grid-column: span 6;+}++/* bottom row: 2 cards centered across 6 cols (each span 3) */+.v4-bento-card:nth-child(5) {+ grid-column: span 3;+}+.v4-bento-card:nth-child(6) {+ grid-column: span 3;+}++.v4-bento-icon {+ width: 36px;+ height: 36px;+ color: var(--v4-gold);+}+.v4-bento-icon svg {+ width: 100%;+ height: 100%;+}++.v4-bento-card h3 {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: 1.15rem;+ font-weight: 600;+ margin: 0;+}+.v4-bento-card p {+ font-size: 0.88rem;+ line-height: 1.5;+ color: var(--v4-ink-dim);+ margin: 0;+ max-width: 380px;+}+.v4-bento-card code {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 0.82em;+ background: rgba(255, 255, 255, 0.06);+ padding: 2px 5px;+ border-radius: 4px;+}++.v4-bento-code {+ margin-top: 0.5rem;+ padding: 12px 16px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--v4-stroke);+ border-radius: var(--v4-radius-sm);+ overflow-x: auto;+}+.v4-bento-code code {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 0.82rem;+ color: var(--v4-gold);+ background: none;+ padding: 0;+}++/* ══════════════════════════════════════════════════════════════+ SECTION 5: THE CLOSE (CTA)+ ══════════════════════════════════════════════════════════════ */+.v4-close {+ position: relative;+ min-height: 80vh;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ background: var(--v4-bg);+}++.v4-close-bg {+ position: absolute;+ inset: 0;+ background: radial-gradient(ellipse 50% 60% at 50% 50%, rgba(255, 190, 80, 0.05), transparent 70%);+}++.v4-close-inner {+ position: relative;+ display: grid;+ grid-template-columns: auto 1fr;+ gap: clamp(2rem, 6vw, 6rem);+ align-items: center;+ max-width: 1200px;+ padding: clamp(2rem, 4vw, 4rem);+ width: 100%;+}++.v4-close-canvas {+ width: clamp(200px, 25vw, 350px);+ height: clamp(300px, 40vh, 500px);+}++.v4-close-title {+ font-family: 'Space Grotesk', var(--font-display, sans-serif);+ font-size: clamp(2.4rem, 5vw, 4rem);+ font-weight: 700;+ line-height: 1.08;+ letter-spacing: -0.03em;+ margin: 0 0 1.5rem;+}++.v4-close-snippet {+ margin-top: 2rem;+}+.v4-snippet-label {+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--v4-ink-dim);+ margin-bottom: 0.6rem;+}+.v4-snippet-code {+ padding: 16px 20px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--v4-stroke);+ border-radius: var(--v4-radius-sm);+ overflow-x: auto;+ margin: 0;+}+.v4-snippet-code code {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 0.82rem;+ line-height: 1.7;+ color: var(--v4-ink-dim);+}++/* ══════════════════════════════════════════════════════════════+ RESPONSIVE — Mobile+ ══════════════════════════════════════════════════════════════ */+@media (max-width: 768px) {+ .v4-hero-text {+ padding: 1.5rem;+ }+ .v4-title {+ font-size: clamp(2rem, 10vw, 3rem);+ }+ .v4-scroll-hint {+ right: 1.2rem;+ bottom: 1.2rem;+ }++ .v4-exp-content {+ grid-template-columns: 1fr;+ }+ .v4-exp-stage {+ min-height: 50vh;+ }+ .v4-exp-canvas {+ height: 50vh;+ max-height: 400px;+ }+ .v4-exp-sidebar {+ padding: 1.5rem;+ }++ .v4-steps {+ grid-template-columns: 1fr;+ }++ .v4-bento {+ grid-template-columns: 1fr;+ }+ .v4-bento-lg,+ .v4-bento-card,+ .v4-bento-card:nth-child(5),+ .v4-bento-card:nth-child(6) {+ grid-column: span 1;+ }++ .v4-close-inner {+ grid-template-columns: 1fr;+ text-align: center;+ }+ .v4-close-canvas {+ margin: 0 auto;+ }+ .v4-close .v4-cta-row {+ justify-content: center;+ }+}++/* mid-size: 2-column steps + bento */+@media (min-width: 769px) and (max-width: 1024px) {+ .v4-steps {+ grid-template-columns: repeat(2, 1fr);+ }+ .v4-bento {+ grid-template-columns: repeat(2, 1fr);+ }+ .v4-bento-lg {+ grid-column: span 2;+ }+ .v4-bento-card,+ .v4-bento-card:nth-child(5),+ .v4-bento-card:nth-child(6) {+ grid-column: span 1;+ }+}++/* ══════════════════════════════════════════════════════════════+ Accessibility — reduced motion+ ══════════════════════════════════════════════════════════════ */+@media (prefers-reduced-motion: reduce) {+ .v4-reveal {+ opacity: 1;+ transform: none;+ transition: none;+ }+ .v4-eyebrow-dot {+ animation: none;+ }+ .v4-scroll-hint {+ animation: none;+ }+}diff --git a/public/llms-full.txt b/public/llms-full.txtindex fbdf45b97..2346e4a1b 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -562,6 +562,18 @@ URL: https://three.ws/news/Product launches, integrations, and announcements from three.ws.+### three.ws Launches on AWS Marketplace, Bringing On-Chain 3D AI Agents to Enterprise Procurement++URL: https://three.ws/news/live-on-aws-marketplace++three.ws is now live on AWS Marketplace as a SaaS subscription. Every AWS customer can subscribe directly, billing rolls onto their AWS invoice, AWS Activate credits apply, and the spend counts toward Enterprise Discount Program commitments. The first fully on-chain 3D AI agent platform listed on the AWS catalog.++### three.ws Joins the AWS Partner Network++URL: https://three.ws/news/joined-aws-partner-network++three.ws is now an official AWS Partner, enrolled in the AWS Partner Network (APN) Software Path as a Technology Partner. The open-source platform for 3D AI agents on-chain is the first fully Web3-native ISV to join APN with a Solana / EVM on-chain identity stack. AWS Marketplace SaaS listing shipping next.+### three.ws Partners with HackerNoonURL: https://three.ws/news/partnered-with-hackernoondiff --git a/public/llms.txt b/public/llms.txtindex 749ef6e0f..a7e5206c1 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -118,6 +118,8 @@ Long-form announcements, launches, and writing from three.ws.Product launches, integrations, and announcements from three.ws.- [News & Announcements](https://three.ws/news/): Product launches, integrations, and announcements from three.ws.+- [three.ws Launches on AWS Marketplace, Bringing On-Chain 3D AI Agents to Enterprise Procurement](https://three.ws/news/live-on-aws-marketplace): three.ws is now live on AWS Marketplace as a SaaS subscription. Every AWS customer can subscribe directly, billing rolls onto their AWS invoice, AWS Activate credits apply, and the spend counts toward Enterprise Discount Program commitments. The first fully on-chain 3D AI agent platform listed on the AWS catalog.+- [three.ws Joins the AWS Partner Network](https://three.ws/news/joined-aws-partner-network): three.ws is now an official AWS Partner, enrolled in the AWS Partner Network (APN) Software Path as a Technology Partner. The open-source platform for 3D AI agents on-chain is the first fully Web3-native ISV to join APN with a Solana / EVM on-chain identity stack. AWS Marketplace SaaS listing shipping next.- [three.ws Partners with HackerNoon](https://three.ws/news/partnered-with-hackernoon): three.ws has partnered with HackerNoon, bringing on-chain 3D agent coverage to one of the world's largest tech publications. Every three.ws announcement now auto-imports into HackerNoon via our RSS feed at https://three.ws/rss/announcements.xml.- [three.ws Listed on BNB Chain's Dappbay Directory](https://three.ws/news/listed-on-bnb-chain-dappbay): three.ws is now listed on Dappbay, BNB Chain's official dApp directory, under AI Agent Launchpad, AI Data, and AI Infra. The listing puts <agent-3d> — the one-tag deploy for Solana-minted, ERC-8004-walleted, x402-native 3D agents — in front of the BNB Chain ecosystem's discovery surface for AI dApps.- [three.ws Launches on Alibaba Cloud Marketplace, Bringing Native x402 Agent Payments to Hyperscale](https://three.ws/news/live-on-alibaba-cloud-marketplace): three.ws is now live on the Alibaba Cloud International Marketplace. The listing makes <agent-3d> — one HTML tag that deploys a Solana-minted, ERC-8004-walleted, x402-native 3D agent — available to every Alibaba Cloud customer worldwide. This is the first deployment of on-chain agents with native HTTP 402 / x402 payment capability inside the procurement flow of a top-four cloud provider.diff --git a/public/nav.html b/public/nav.htmlindex 9b4465c09..c93a2cafa 100644--- a/public/nav.html+++ b/public/nav.html@@ -29,12 +29,24 @@><span class="nav-mi-sub">Avatar + brain wizard</span></a></li>+ <li role="none">+ <a href="/create-selfie" role="menuitem"+ ><span class="nav-mi-title">Selfie to avatar<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">One photo → rigged 3D avatar</span></a+ >+ </li><li role="none"><a href="/app" role="menuitem"><span class="nav-mi-title">Viewer</span><span class="nav-mi-sub">Drag-and-drop GLB</span></a></li>+ <li role="none">+ <a href="/playground" role="menuitem"+ ><span class="nav-mi-title">Playground</span+ ><span class="nav-mi-sub">Viewer + environment + embed code</span></a+ >+ </li><li role="none"><a href="/validation" role="menuitem"><span class="nav-mi-title">glTF Validator</span@@ -62,6 +74,12 @@Discover<span class="nav-caret" aria-hidden="true">▾</span></button><ul class="nav-menu" role="menu" aria-label="Discover">+ <li role="none">+ <a href="/features" role="menuitem"+ ><span class="nav-mi-title">Features</span+ ><span class="nav-mi-sub">Everything an agent gets — interactive tour</span></a+ >+ </li><li role="none"><a href="/discover" role="menuitem"><span class="nav-mi-title">ERC-8004 Agents</span@@ -74,6 +92,18 @@><span class="nav-mi-sub">Every public 3D avatar</span></a></li>+ <li role="none">+ <a href="/bazaar" role="menuitem"+ ><span class="nav-mi-title">x402 Bazaar</span+ ><span class="nav-mi-sub">Browse paid APIs and MCP tools</span></a+ >+ </li>+ <li role="none">+ <a href="/community" role="menuitem"+ ><span class="nav-mi-title">Community</span+ ><span class="nav-mi-sub">X, GitHub, and ways to get involved</span></a+ >+ </li></ul></li><li class="nav-item nav-has-menu" role="none">@@ -87,6 +117,12 @@Embed<span class="nav-caret" aria-hidden="true">▾</span></button><ul class="nav-menu" role="menu" aria-label="Embed">+ <li role="none">+ <a href="/widgets" role="menuitem"+ ><span class="nav-mi-title">Widgets</span+ ><span class="nav-mi-sub">Browse + customize embeddable widgets</span></a+ >+ </li><li role="none"><a href="/studio" role="menuitem"><span class="nav-mi-title">Widget Studio</span@@ -183,6 +219,24 @@><span class="nav-mi-sub">TTS or mic → in-browser viseme → avatar mouth</span></a></li>+ <li role="none">+ <a href="/mocap-studio" role="menuitem"+ ><span class="nav-mi-title">Mocap Studio<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">Record face → save clip → replay on any avatar</span></a+ >+ </li>+ <li role="none">+ <a href="/pose" role="menuitem"+ ><span class="nav-mi-title">Pose Studio</span+ ><span class="nav-mi-sub">Click-to-pose 3D mannequin + export PNG</span></a+ >+ </li>+ <li role="none">+ <a href="/overlay-control" role="menuitem"+ ><span class="nav-mi-title">OBS Overlay</span+ ><span class="nav-mi-sub">Stream deck — emote hotkeys, mic, expressions</span></a+ >+ </li><li role="none"><a href="/pretext-demo" role="menuitem"><span class="nav-mi-title">Pretext demo</span@@ -225,6 +279,12 @@><span class="nav-mi-sub">DCA + subscriptions</span></a></li>+ <li role="none">+ <a href="/club" role="menuitem"+ ><span class="nav-mi-title">Pole Club<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">x402 micro-tip demo — $0.001 per dance</span></a+ >+ </li><li role="none"><a href="/avatar-artifact" role="menuitem"><span class="nav-mi-title">Avatar artifact</span@@ -245,6 +305,9 @@</li></ul></li>+ <li class="nav-item" role="none">+ <a href="/pricing" role="menuitem">Pricing</a>+ </li><li class="nav-item" id="home-nav-my-agents-li" role="none" hidden><a href="/my-agents" id="home-nav-my-agents" role="menuitem">My Agents</a></li>diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 0f72aeaf9..46d4fc6b6 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -730,6 +730,20 @@<span class="sm-desc">Product launches, integrations, and announcements from three.ws.</span></a></li>+ <li>+ <a href="/news/live-on-aws-marketplace">+ <span class="sm-title">three.ws Launches on AWS Marketplace, Bringing On-Chain 3D AI Agents to Enterprise Procurement</span>+ <span class="sm-path">/news/live-on-aws-marketplace</span>+ <span class="sm-desc">three.ws is now live on AWS Marketplace as a SaaS subscription. Every AWS customer can subscribe directly, billing rolls onto their AWS invoice, AWS Activate credits apply, and the spend counts toward Enterprise Discount Program commitments. The first fully on-chain 3D AI agent platform listed on the AWS catalog.</span>+ </a>+ </li>+ <li>+ <a href="/news/joined-aws-partner-network">+ <span class="sm-title">three.ws Joins the AWS Partner Network</span>+ <span class="sm-path">/news/joined-aws-partner-network</span>+ <span class="sm-desc">three.ws is now an official AWS Partner, enrolled in the AWS Partner Network (APN) Software Path as a Technology Partner. The open-source platform for 3D AI agents on-chain is the first fully Web3-native ISV to join APN with a Solana / EVM on-chain identity stack. AWS Marketplace SaaS listing shipping next.</span>+ </a>+ </li><li><a href="/news/partnered-with-hackernoon"><span class="sm-title">three.ws Partners with HackerNoon</span>diff --git a/src/analytics.js b/src/analytics.jsindex 25a3d6e2c..fa7ba67e0 100644--- a/src/analytics.js+++ b/src/analytics.js@@ -11,6 +11,7 @@function ph() {if (typeof window === 'undefined') return null;+ if (window.__posthog_blocked) return null;const p = window.posthog;if (!p || typeof p.identify !== 'function') return null;return p;diff --git a/src/app-next-overlay.js b/src/app-next-overlay.jsindex d56ca2ae5..7acceb2f0 100644--- a/src/app-next-overlay.js+++ b/src/app-next-overlay.js@@ -616,6 +616,12 @@ function wireExploreMenu() {const menu = document.getElementById('nxt-more-menu');if (!btn || !menu) return;+ const positionMenu = () => {+ const r = btn.getBoundingClientRect();+ menu.style.top = `${r.bottom + 6}px`;+ menu.style.right = `${window.innerWidth - r.right}px`;+ };+const close = () => {menu.hidden = true;btn.setAttribute('aria-expanded', 'false');@@ -624,6 +630,7 @@ function wireExploreMenu() {btn.addEventListener('click', (e) => {e.stopPropagation();if (menu.hidden) {+ positionMenu();menu.hidden = false;btn.setAttribute('aria-expanded', 'true');} else {diff --git a/src/avatar-embed.js b/src/avatar-embed.jsindex c5a6889df..302e4756e 100644--- a/src/avatar-embed.js+++ b/src/avatar-embed.js@@ -129,7 +129,9 @@ async function main() {return;}- const namePlate = !overlayMode && params.get('name') !== '0';+ const hideChrome = params.get('hide-chrome') === '1';++ const namePlate = !overlayMode && !hideChrome && params.get('name') !== '0';if (namePlate && resolved.name) {document.getElementById('name-plate').textContent = resolved.name;}@@ -168,8 +170,6 @@ async function main() {animMgr.crossfadeTo(startAnim, 0.3).catch(() => {});}- const hideChrome = params.get('hide-chrome') === '1';-const pickerEnabled = params.get('animPicker') !== '0' && !overlayMode && !hideChrome;if (pickerEnabled && animDefs.length > 0) {buildAnimPicker(animDefs, animMgr);diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.jsindex a7d59c0da..e1dae5cab 100644--- a/src/dashboard-next/pages/agents.js+++ b/src/dashboard-next/pages/agents.js@@ -204,7 +204,8 @@ function agentCard(a, avatars) {<div style="display:flex;flex-direction:column;gap:6px;flex-shrink:0;align-items:flex-end"><div style="display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end">- <a class="dn-btn ghost" href="/app?agent=${encodeURIComponent(a.id)}" target="_blank" rel="noopener" style="padding:5px 10px;font-size:12px">View ↗</a>+ ${a.avatar_id ? `<a class="dn-btn primary" href="/agent-next?id=${encodeURIComponent(a.avatar_id)}" target="_blank" rel="noopener" style="padding:5px 10px;font-size:12px">Live page ↗</a>` : ''}+ <a class="dn-btn ghost" href="/app?agent=${encodeURIComponent(a.id)}" target="_blank" rel="noopener" style="padding:5px 10px;font-size:12px">3D Studio ↗</a><button class="dn-btn" data-action="edit-agent" data-id="${esc(a.id)}" style="padding:5px 10px;font-size:12px">Edit</button><button class="dn-btn" data-action="persona-agent" data-id="${esc(a.id)}" style="padding:5px 10px;font-size:12px">Persona</button><button class="dn-btn" data-action="view-reputation" data-id="${esc(a.id)}" style="padding:5px 10px;font-size:12px">Reputation</button>diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.jsindex 7032ac62d..ba1a8ddf6 100644--- a/src/dashboard-next/pages/avatars.js+++ b/src/dashboard-next/pages/avatars.js@@ -360,10 +360,11 @@ function openMoreMenu(root, anchor, card, a) {menu.dataset.for = a.id;menu.setAttribute('role', 'menu');const items = [+ { label: 'View live page', run: () => { window.open(`/agent-next?id=${encodeURIComponent(a.id)}`, '_blank'); } },{ label: 'Rename', run: () => card.querySelector('[data-rename]')?.click() },{ label: 'Change visibility', run: () => openVisibilitySubmenu(root, anchor, card, a) },{ label: 'Copy embed snippet', run: () => copyEmbedSnippet(root, a) },- { label: 'Open in viewer', run: () => { location.href = `/app#avatar=${encodeURIComponent(a.id)}`; } },+ { label: 'Open in 3D studio', run: () => { location.href = `/app#avatar=${encodeURIComponent(a.id)}`; } },{ label: 'Download GLB', run: () => downloadGlb(root, a) },{ label: 'Delete', danger: true, run: () => confirmDelete(root, card, a) },];@@ -486,7 +487,7 @@ async function copyEmbedSnippet(root, a) {}const u = new URL('/a-embed.html', location.origin);u.searchParams.set('avatar', a.id);- const snippet = `<iframe src="${u.toString()}" width="360" height="540" style="border:0;border-radius:12px;max-width:100%" allow="xr-spatial-tracking" title="${safeName}" loading="lazy"></iframe>`;+ const snippet = `<iframe src="${u.toString()}" width="360" height="540" style="border:0;border-radius:12px;max-width:100%" allow="xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${safeName}" loading="lazy"></iframe>`;try {await navigator.clipboard.writeText(snippet);toast(root, 'Embed snippet copied');diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex e73d67ac1..80dce7931 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -53,8 +53,6 @@ const STATE = {activity: main.querySelector('[data-slot="activity"]'),};- renderQuickActions(slots.quick);-const [avatarsRes, widgetsRes, agentsRes] = await Promise.allSettled([get('/api/avatars?limit=50'),get('/api/widgets'),@@ -66,6 +64,7 @@ const STATE = {const agents = agentsRes.status === 'fulfilled' ? (agentsRes.value?.agents ?? []) : [];renderHero(slots.hero, avatars, avatarsRes.status === 'rejected' ? avatarsRes.reason : null);+ renderQuickActions(slots.quick, { avatars, agents });if (slots.onboarding) {renderOnboarding(slots.onboarding, { avatars, agents, widgets });@@ -149,12 +148,11 @@ function renderHero(host, avatars, err) {host.innerHTML = top.map((a) => {const name = a.name || a.slug || 'Untitled avatar';- const slug = a.slug || a.id;return `<article class="dnx-hero-card"><threews-avatar avatar-id="${esc(a.id)}" bg="transparent" hide-chrome></threews-avatar><div class="dnx-hero-overlay">- <a class="dn-btn" href="/a/${esc(slug)}">Open</a>+ <a class="dn-btn" href="/agent-next?id=${encodeURIComponent(a.id)}">Live page</a><a class="dn-btn" href="/dashboard/widgets?avatar=${encodeURIComponent(a.id)}">Embed</a><a class="dn-btn" href="/dashboard/avatars?edit=${encodeURIComponent(a.id)}">Edit</a></div>@@ -458,13 +456,39 @@ function renderOnboarding(host, { avatars, agents, widgets }) {// ── Quick actions ─────────────────────────────────────────────────────────-function renderQuickActions(host) {- const actions = [- { href: '/create', title: 'Create avatar from selfie', sub: 'Snap → 3D agent in 60s', icon: '+' },- { href: '/dashboard/widgets', title: 'Embed an agent', sub: 'Drop-in widget for any site', icon: '◧' },- { href: '/dashboard/monetize', title: 'View revenue', sub: 'Earnings, payouts, plans', icon: '$' },- { href: '/dashboard/api', title: 'Open API keys', sub: 'REST + MCP for your agents', icon: '⌘' },- ];+function renderQuickActions(host, { avatars = [], agents = [] } = {}) {+ const firstAvatar = avatars[0];+ const firstAgent = agents[0];++ const actions = [];++ if (firstAvatar) {+ actions.push({+ href: `/agent-next?id=${encodeURIComponent(firstAvatar.id)}`,+ title: 'View live agent page',+ sub: 'See how visitors experience your agent',+ icon: '▶',+ });+ } else {+ actions.push({ href: '/create', title: 'Create avatar from selfie', sub: 'Snap → 3D agent in 60s', icon: '+' });+ }++ if (firstAgent) {+ actions.push({+ href: `/app?agent=${encodeURIComponent(firstAgent.id)}`,+ title: 'Open 3D studio',+ sub: 'Edit, animate, and customize in 3D',+ icon: '◇',+ });+ } else {+ actions.push({ href: '/dashboard/agents', title: 'Create an agent', sub: 'On-chain identity with wallet and skills', icon: '⬡' });+ }++ actions.push(+ { href: '/dashboard/widgets', title: 'Embed an agent', sub: 'Drop-in widget for any site', icon: '◧' },+ { href: '/dashboard/api', title: 'Open API keys', sub: 'REST + MCP for your agents', icon: '⌘' },+ );+host.innerHTML = actions.map((a) => `<a class="dn-panel dnx-quick-card" href="${a.href}"><div class="dnx-quick-icon">${a.icon}</div>diff --git a/src/home-v4-hero.js b/src/home-v4-hero.jsnew file mode 100644index 000000000..08c29d837--- /dev/null+++ b/src/home-v4-hero.js@@ -0,0 +1,364 @@+/**+ * Hero particle-to-avatar materialization for home-v4.+ * Loads a GLB, samples 6000 points from the mesh surface,+ * animates particles converging into the avatar shape,+ * then crossfades to the solid model.+ */+import {+ WebGLRenderer,+ Scene,+ PerspectiveCamera,+ AnimationMixer,+ AnimationClip,+ Box3,+ Vector3,+ Clock,+ HemisphereLight,+ DirectionalLight,+ ACESFilmicToneMapping,+ SRGBColorSpace,+ PMREMGenerator,+ Points,+ BufferGeometry,+ Float32BufferAttribute,+ ShaderMaterial,+ AdditiveBlending,+ MathUtils,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++const PARTICLE_COUNT = 6000;+const MATERIALIZE_DURATION = 2.0;+const CROSSFADE_START = 0.5;+const MODEL_URL = '/avatars/cz.glb';++const VERT = `+attribute vec3 aStart;+attribute vec3 aTarget;+attribute float aSeed;+uniform float uProgress;+uniform float uTime;+uniform float uParticleAlpha;+varying float vAlpha;+void main() {+ float p = clamp(uProgress + aSeed * 0.3 - 0.15, 0.0, 1.0);+ float ease = p * p * (3.0 - 2.0 * p);+ vec3 pos = mix(aStart, aTarget, ease);+ float drift = sin(uTime * 2.0 + aSeed * 6.28) * (1.0 - ease) * 0.05;+ pos.x += drift;+ pos.y += drift * 0.5;+ vec4 mvPos = modelViewMatrix * vec4(pos, 1.0);+ gl_PointSize = max(1.5, 4.0 * (300.0 / -mvPos.z));+ gl_Position = projectionMatrix * mvPos;+ vAlpha = uParticleAlpha * (0.4 + 0.6 * aSeed);+}+`;++const FRAG = `+varying float vAlpha;+void main() {+ float d = length(gl_PointCoord - 0.5) * 2.0;+ if (d > 1.0) discard;+ float alpha = (1.0 - d * d) * vAlpha;+ gl_FragColor = vec4(1.0, 0.84, 0.4, alpha);+}+`;++export class HeroScene {+ constructor(canvas) {+ this.canvas = canvas;+ this._raf = 0;+ this._disposed = false;++ const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;+ const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ this._skipParticles = LOW_MEMORY || REDUCED_MOTION || window.innerWidth < 768;++ this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });+ this.renderer.toneMapping = ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.0;+ this.renderer.outputColorSpace = SRGBColorSpace;+ this.renderer.setClearColor(0x000000, 0);++ this.scene = new Scene();+ this.camera = new PerspectiveCamera(16, 1, 0.1, 100);+ this.camera.position.set(0.3, 1.0, 18);++ const pmrem = new PMREMGenerator(this.renderer);+ this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ pmrem.dispose();++ this.scene.add(new HemisphereLight(0xffffff, 0x444466, 0.6));+ const sun = new DirectionalLight(0xffffff, 1.2);+ sun.position.set(4, 8, 6);+ this.scene.add(sun);++ this._clock = new Clock();+ this._loader = new GLTFLoader();++ this.model = null;+ this.mixer = null;+ this.particles = null;+ this._particleMat = null;+ this._progress = 0;+ this._materialized = false;+ this._modelOpacityTargets = [];++ this._mouseX = 0;+ this._mouseY = 0;+ this._targetTheta = 0;+ this._targetPhi = 0;+ this._currentTheta = 0;+ this._currentPhi = 0;++ this._baseCamPos = new Vector3();+ this._focusY = 1.0;++ this._resize();+ const ro = new ResizeObserver(() => this._resize());+ ro.observe(canvas);++ this._onMouseMove = this._onMouseMove.bind(this);+ window.addEventListener('mousemove', this._onMouseMove, { passive: true });++ this._tick = this._tick.bind(this);+ this._load();+ }++ _resize() {+ const dpr = Math.min(devicePixelRatio || 1, window.innerWidth < 768 ? 1 : 2);+ const w = this.canvas.clientWidth;+ const h = this.canvas.clientHeight;+ if (!w || !h) return;+ this.renderer.setPixelRatio(dpr);+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ _onMouseMove(e) {+ this._mouseX = (e.clientX / window.innerWidth) * 2 - 1;+ this._mouseY = (e.clientY / window.innerHeight) * 2 - 1;+ }++ async _load() {+ const gltf = await this._loader.loadAsync(MODEL_URL);+ if (this._disposed) return;++ this.model = gltf.scene;+ this.scene.add(this.model);++ const box = new Box3().setFromObject(this.model);+ const size = box.getSize(new Vector3());+ const center = box.getCenter(new Vector3());+ this.model.position.x -= center.x;+ this.model.position.z -= center.z;+ this.model.position.y -= box.min.y;++ const targetHeight = size.y;+ const dist = (targetHeight / 2) / Math.tan((this.camera.fov / 2) * (Math.PI / 180));+ this._focusY = targetHeight * 0.5;+ this.camera.position.set(0.3, this._focusY, dist * 1.1);+ this._baseCamPos.copy(this.camera.position);+ this.camera.lookAt(0, this._focusY, 0);++ this.mixer = new AnimationMixer(this.model);+ const knownNodes = new Set();+ this.model.traverse((n) => { if (n.name) knownNodes.add(n.name); });++ for (const clip of gltf.animations || []) {+ const tracks = clip.tracks.filter((t) => knownNodes.has(t.name.split('.')[0]));+ if (tracks.length === 0) continue;+ const filtered = new AnimationClip(clip.name, clip.duration, tracks);+ const action = this.mixer.clipAction(filtered);+ action.play();+ break;+ }++ if (!gltf.animations?.length) {+ this._loadIdleAnim(knownNodes);+ }++ if (this._skipParticles) {+ this._materialized = true;+ this._progress = 1;+ this._startLoop();+ return;+ }++ this._collectOpacityTargets();+ this._setModelOpacity(0);+ this._buildParticles();+ this._startLoop();+ }++ async _loadIdleAnim(knownNodes) {+ try {+ const manifest = await fetch('/animations/manifest.json').then(r => r.json());+ const arr = Array.isArray(manifest) ? manifest : manifest.animations || [];+ const idle = arr.find(d => d.name === 'idle' || d.name === 'av-idle-breath');+ if (!idle) return;+ const json = await fetch(idle.url).then(r => r.json());+ const clip = AnimationClip.parse(json);+ const tracks = clip.tracks.filter(t => knownNodes.has(t.name.split('.')[0]));+ if (tracks.length === 0) return;+ const filtered = new AnimationClip(clip.name, clip.duration, tracks);+ const action = this.mixer.clipAction(filtered);+ action.play();+ } catch { /* non-critical */ }+ }++ _collectOpacityTargets() {+ this._modelOpacityTargets = [];+ this.model.traverse((child) => {+ if (child.isMesh && child.material) {+ const mats = Array.isArray(child.material) ? child.material : [child.material];+ for (const mat of mats) {+ mat.transparent = true;+ this._modelOpacityTargets.push(mat);+ }+ }+ });+ }++ _setModelOpacity(v) {+ for (const mat of this._modelOpacityTargets) {+ mat.opacity = v;+ }+ }++ _buildParticles() {+ const meshes = [];+ this.model.traverse((child) => {+ if (child.isMesh && child.geometry) meshes.push(child);+ });+ if (meshes.length === 0) return;++ const starts = new Float32Array(PARTICLE_COUNT * 3);+ const targets = new Float32Array(PARTICLE_COUNT * 3);+ const seeds = new Float32Array(PARTICLE_COUNT);+ const pos = new Vector3();++ let idx = 0;+ const perMesh = Math.ceil(PARTICLE_COUNT / meshes.length);++ for (const mesh of meshes) {+ const sampler = new MeshSurfaceSampler(mesh).setWeightAttribute(null).build();+ const count = Math.min(perMesh, PARTICLE_COUNT - idx);+ for (let i = 0; i < count; i++) {+ sampler.sample(pos);+ pos.applyMatrix4(mesh.matrixWorld);+ pos.x -= this.model.position.x === 0 ? 0 : 0;++ targets[idx * 3] = pos.x + this.model.position.x;+ targets[idx * 3 + 1] = pos.y + this.model.position.y;+ targets[idx * 3 + 2] = pos.z + this.model.position.z;++ const theta = Math.random() * Math.PI * 2;+ const phi = Math.acos(2 * Math.random() - 1);+ const r = 2 + Math.random() * 4;+ starts[idx * 3] = targets[idx * 3] + r * Math.sin(phi) * Math.cos(theta);+ starts[idx * 3 + 1] = targets[idx * 3 + 1] + r * Math.sin(phi) * Math.sin(theta);+ starts[idx * 3 + 2] = targets[idx * 3 + 2] + r * Math.cos(phi);++ seeds[idx] = Math.random();+ idx++;+ }+ }++ const geo = new BufferGeometry();+ geo.setAttribute('aStart', new Float32BufferAttribute(starts, 3));+ geo.setAttribute('aTarget', new Float32BufferAttribute(targets, 3));+ geo.setAttribute('aSeed', new Float32BufferAttribute(seeds, 1));+ geo.setAttribute('position', new Float32BufferAttribute(targets, 3));++ this._particleMat = new ShaderMaterial({+ vertexShader: VERT,+ fragmentShader: FRAG,+ uniforms: {+ uProgress: { value: 0 },+ uTime: { value: 0 },+ uParticleAlpha: { value: 1 },+ },+ transparent: true,+ depthWrite: false,+ blending: AdditiveBlending,+ });++ this.particles = new Points(geo, this._particleMat);+ this.scene.add(this.particles);+ }++ _startLoop() {+ this._clock.start();+ this._raf = requestAnimationFrame(this._tick);+ }++ _tick() {+ if (this._disposed) return;+ const dt = this._clock.getDelta();+ const elapsed = this._clock.getElapsedTime();++ if (this.mixer) this.mixer.update(dt);++ if (!this._materialized && this.particles) {+ this._progress = Math.min(this._progress + dt / MATERIALIZE_DURATION, 1);+ this._particleMat.uniforms.uProgress.value = this._progress;+ this._particleMat.uniforms.uTime.value = elapsed;++ if (this._progress >= CROSSFADE_START) {+ const fade = (this._progress - CROSSFADE_START) / (1 - CROSSFADE_START);+ this._setModelOpacity(fade);+ this._particleMat.uniforms.uParticleAlpha.value = 1 - fade;+ }++ if (this._progress >= 1) {+ this._materialized = true;+ this._setModelOpacity(1);+ this.scene.remove(this.particles);+ this.particles.geometry.dispose();+ this._particleMat.dispose();+ this.particles = null;+ this._particleMat = null;+ for (const mat of this._modelOpacityTargets) {+ mat.transparent = false;+ }+ }+ }++ if (this._materialized) {+ this._targetTheta = this._mouseX * 12;+ this._targetPhi = this._mouseY * 6;+ this._currentTheta = MathUtils.lerp(this._currentTheta, this._targetTheta, 0.03);+ this._currentPhi = MathUtils.lerp(this._currentPhi, this._targetPhi, 0.03);++ const thetaRad = this._currentTheta * (Math.PI / 180);+ const dist = this._baseCamPos.z;+ this.camera.position.x = this._baseCamPos.x + Math.sin(thetaRad) * dist * 0.05;+ this.camera.position.y = this._baseCamPos.y - this._currentPhi * 0.01;+ this.camera.lookAt(0, this._focusY, 0);+ }++ this.renderer.render(this.scene, this.camera);+ this._raf = requestAnimationFrame(this._tick);+ }++ dispose() {+ this._disposed = true;+ cancelAnimationFrame(this._raf);+ window.removeEventListener('mousemove', this._onMouseMove);+ if (this.particles) {+ this.particles.geometry.dispose();+ this._particleMat?.dispose();+ }+ this.renderer.dispose();+ }+}++const canvas = document.getElementById('v4-hero-canvas');+if (canvas) {+ const heroScene = new HeroScene(canvas);+ window._v4Hero = heroScene;+}diff --git a/src/home-v4-scroll.js b/src/home-v4-scroll.jsnew file mode 100644index 000000000..ac80f4139--- /dev/null+++ b/src/home-v4-scroll.js@@ -0,0 +1,144 @@+/**+ * home-v4 scroll orchestration:+ * - Scroll reveal animations+ * - Experience section: Act2Viewer + animation chips + model picker+ * - Stats bar from /api/home-stats+ * - CTA section wave avatar+ */++const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;++/* ── Scroll reveal ───────────────────────────────────── */+(function initReveals() {+ const els = document.querySelectorAll('.v4-reveal');+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ entry.target.classList.add('revealed');+ observer.unobserve(entry.target);+ }+ }+ },+ { root: null, threshold: 0.1, rootMargin: '0px 0px -40px 0px' },+ );+ for (const el of els) {+ const siblings = Array.from(el.parentElement.querySelectorAll('.v4-reveal'));+ const idx = siblings.indexOf(el);+ el.style.transitionDelay = idx * 0.08 + 's';+ observer.observe(el);+ }+})();++/* ── Stats ───────────────────────────────────────────── */+(async function loadStats() {+ try {+ const r = await fetch('/api/home-stats');+ if (!r.ok) return;+ const data = await r.json();+ if (!data || data.available === false) return;+ const agentEl = document.querySelector('[data-stat="agents"]');+ const onchainEl = document.querySelector('[data-stat="onchain"]');+ if (agentEl && data.agents != null) agentEl.textContent = formatNum(data.agents);+ if (onchainEl && data.onchain != null) onchainEl.textContent = formatNum(data.onchain);+ } catch { /* non-critical */ }+})();++function formatNum(n) {+ if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';+ return String(n);+}++/* ── Experience section: Act2Viewer + animation chips ── */+(function initExperience() {+ const canvas = document.getElementById('v4-exp-canvas');+ if (!canvas || LOW_MEMORY) return;++ let viewer = null;+ let currentModelUrl = '/avatars/cz.glb';+ let activeChip = null;++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting && !viewer) {+ observer.disconnect();+ boot();+ }+ },+ { rootMargin: '600px' },+ );+ observer.observe(canvas);++ function boot() {+ if (!window.Act2Viewer) return;+ viewer = new window.Act2Viewer(canvas, { fov: 14 });++ viewer.onClipsReady = (clips) => {+ buildChips(clips);+ };++ viewer.loadModel(currentModelUrl);++ const modelBtns = document.querySelectorAll('.v4-model-btn');+ for (const btn of modelBtns) {+ btn.addEventListener('click', () => {+ const url = btn.dataset.model;+ if (url === currentModelUrl) return;+ currentModelUrl = url;+ for (const b of modelBtns) b.classList.remove('active');+ btn.classList.add('active');+ viewer.loadModel(url);+ });+ }+ }++ function buildChips(clips) {+ const container = document.getElementById('v4-anim-chips');+ if (!container) return;+ container.innerHTML = '';+ activeChip = null;++ for (const def of clips) {+ const btn = document.createElement('button');+ btn.className = 'v4-chip';+ btn.textContent = def.label || def.name;+ btn.addEventListener('click', () => {+ if (activeChip) activeChip.classList.remove('active');+ btn.classList.add('active');+ activeChip = btn;+ viewer.playClip(def.name);+ });+ container.appendChild(btn);+ }+ }+})();++/* ── CTA section wave avatar ─────────────────────────── */+(function initCloseViewer() {+ const canvas = document.getElementById('v4-close-canvas');+ if (!canvas || LOW_MEMORY) return;++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting) {+ observer.disconnect();+ boot();+ }+ },+ { rootMargin: '400px' },+ );+ observer.observe(canvas);++ async function boot() {+ if (!window.Act2Viewer) return;+ const viewer = new window.Act2Viewer(canvas, { fov: 14 });+ await viewer.loadModel('/avatars/cz.glb', { autoPlay: false });+ const waveClip = viewer.listAvailableClips().find(c => /wave|waving/i.test(c.name));+ if (waveClip) {+ viewer.playClip(waveClip.name);+ } else {+ const clips = viewer.listAvailableClips();+ if (clips.length) viewer.playClip(clips[0].name);+ }+ }+})();diff --git a/src/nich-agent.js b/src/nich-agent.jsindex 94adc1743..aebe32044 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -79,7 +79,7 @@ export class NichAgent {this.protocol.on(ACTION_TYPES.SPEAK, (action) => {const text = action.payload?.text;if (text) {- this._addMessage('agent', text);+ if (!action.payload._rendered) this._addMessage('agent', text);this._speak(text);}});@@ -262,15 +262,16 @@ export class NichAgent {const result = await this.options.onSend(text);if (result?.reply) {this._addMessage('agent', result.reply);- this._speak(result.reply);this._pushHistory('user', text);this._pushHistory('assistant', result.reply);if (this.protocol) {this.protocol.emit({type: ACTION_TYPES.SPEAK,- payload: { text: result.reply, sentiment: 0 },+ payload: { text: result.reply, sentiment: 0, _rendered: true },agentId: this.identity?.id || 'default',});+ } else {+ this._speak(result.reply);}} else if (result?.error) {this._addMessage('agent', result.error, 'status');@@ -322,14 +323,15 @@ export class NichAgent {// Final fallback: offline pattern match so the agent still responds.const response = this._generateResponse(text);this._addMessage('agent', response);- this._speak(response);if (this.protocol) {this.protocol.emit({type: ACTION_TYPES.SPEAK,- payload: { text: response, sentiment: 0 },+ payload: { text: response, sentiment: 0, _rendered: true },agentId: this.identity?.id || 'default',});+ } else {+ this._speak(response);}}@@ -432,14 +434,15 @@ export class NichAgent {if (reply) {if (!streamEl) this._addMessage('agent', reply);- this._speak(reply);this._pushHistory('assistant', reply);if (this.protocol) {this.protocol.emit({type: ACTION_TYPES.SPEAK,- payload: { text: reply, sentiment: 0 },+ payload: { text: reply, sentiment: 0, _rendered: true },agentId: this.identity?.id || 'default',});+ } else {+ this._speak(reply);}}diff --git a/src/selfie-capture.js b/src/selfie-capture.jsindex f60cec036..1a4a36689 100644--- a/src/selfie-capture.js+++ b/src/selfie-capture.js@@ -14,8 +14,8 @@ const REQUIRED_SLOT = 'frontal';const OPTIONAL_SLOTS = /** @type {const} */ (['left', 'right']);const ALL_SLOTS = /** @type {const} */ ([REQUIRED_SLOT, ...OPTIONAL_SLOTS]);-const ETA_FAST_SEC = 45;-const ETA_HIGH_SEC = 75;+const ETA_FAST_SEC = 90;+const ETA_HIGH_SEC = 120;const state = {bodyType: /** @type {'male' | 'female'} */ ('male'),@@ -290,6 +290,13 @@ function renderSlot(slot) {clearSlot(slot);});frame.appendChild(retake);++ frame.addEventListener('keydown', (e) => {+ if ((e.key === 'Delete' || e.key === 'Backspace') && state.files[slot]) {+ e.preventDefault();+ clearSlot(slot);+ }+ });}function updateSubmit() {@@ -378,8 +385,13 @@ async function openCamera(slot) {camVideo.srcObject = cam.stream;} catch (err) {console.warn('[selfie] camera error:', err);- showCamError('Could not access camera. Check permissions and try again.');- setShutterEnabled(true);+ const denied = err?.name === 'NotAllowedError' || err?.name === 'PermissionDeniedError';+ showCamError(+ denied+ ? 'Camera access was denied. Grant permission in your browser settings, or use Upload instead.'+ : 'Could not access camera. Check permissions and try again.',+ );+ closeCamera();return;}@@ -531,7 +543,7 @@ camOverlay?.addEventListener('click', (e) => {});function startCountdown() {- if (camShutter?.hasAttribute('disabled')) return;+ if (!camShutter || camShutter.hasAttribute('disabled')) return;if (cam.countdownTimers.length) return;setShutterEnabled(false);camOval?.setAttribute('hidden', '');@@ -605,6 +617,8 @@ function confirmCamShot() {if (!cam.pendingFile || !cam.slot) return;const slot = cam.slot;const file = cam.pendingFile;+ cam.pendingFile = null;+ cam.pendingUrl = null;closeCamera();setSlot(slot, file);}diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.jsindex 742e3b897..ef0158921 100644--- a/src/selfie-pipeline.js+++ b/src/selfie-pipeline.js@@ -1,29 +1,34 @@/**- * Selfie pipeline — bridges the capture UI on /create/selfie to the native+ * Selfie pipeline -- bridges the capture UI on /create/selfie to the native* avatar reconstruction backend.** Flow:- * [selfie:submit] → downscale photos (frontal required, sides optional)- * → dispatches selfie:preview { dataUrl } so the build view can show the+ * [selfie:submit] -> downscale photos (frontal required, sides optional)+ * -> dispatches selfie:preview { dataUrl } so the build view can show the* user's own photo on a placeholder body while the real GLB renders- * → POST /api/avatars/reconstruct- * → dispatches selfie:building { jobId }- * → poll /api/avatars/regenerate-status?jobId=…- * → dispatches selfie:progress { label } on each poll tick- * → on { status: 'done', resultAvatarId } → dispatches selfie:done { avatarId }- * → on { status: 'failed' } or timeout → dispatches selfie:build-error+ * -> POST /api/avatars/reconstruct+ * -> dispatches selfie:building { jobId }+ * -> poll /api/avatars/regenerate-status?jobId=...+ * -> dispatches selfie:progress { label } on each poll tick+ * -> on { status: 'done', resultAvatarId } -> dispatches selfie:done { avatarId }+ * -> on { status: 'failed' } or timeout -> dispatches selfie:build-error* { message, slot? } where slot is the photo that likely caused the failure*/+import { detectFaceIdentity } from './avatar-face-capture.js';+const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';const STATUS_ENDPOINT = '/api/avatars/regenerate-status';const MAX_DIM = 1024;const JPEG_QUALITY = 0.88;const POLL_INTERVAL_MS = 3000;-const POLL_TIMEOUT_MS = 5 * 60 * 1000;+const POLL_TIMEOUT_MS = 8 * 60 * 1000;+const RATE_LIMIT_COOLDOWN_MS = 60_000;let _building = false;let _lastSlotsSent = /** @type {string[]} */ ([]);+let _jobStartTime = 0;+let _rateLimitedUntil = 0;document.addEventListener('selfie:submit', (event) => {const ev = /** @type {CustomEvent} */ (event);@@ -43,11 +48,40 @@ document.addEventListener('selfie:submit', (event) => {}));} else {setStatus(err.userMessage || 'Something went wrong. Try again.', { error: true });- resetSubmit();+ if (err.slot) highlightSlotError(err.slot);+ if (err.rateLimited) {+ startRateLimitCooldown();+ } else {+ resetSubmit();+ }}});});+// Resume polling if we have a pending job from a previous page load.+(function resumePendingJob() {+ try {+ const pending = sessionStorage.getItem('selfie:pendingJobId');+ if (!pending) return;+ sessionStorage.removeItem('selfie:pendingJobId');+ _building = true;+ _jobStartTime = Date.now();+ document.dispatchEvent(new CustomEvent('selfie:building', { detail: { jobId: pending } }));+ pollUntilDone(pending).then((finalJob) => {+ if (finalJob.resultAvatarId) {+ document.dispatchEvent(new CustomEvent('selfie:done', {+ detail: { avatarId: finalJob.resultAvatarId },+ }));+ }+ }).catch((err) => {+ console.error('[selfie-pipeline] resume failed:', err);+ document.dispatchEvent(new CustomEvent('selfie:build-error', {+ detail: { message: err.userMessage || 'Could not resume. Try again.', slot: null },+ }));+ });+ } catch (_) {}+})();+/*** @param {{* files: Record<'frontal'|'left'|'right', File | null>,@@ -62,24 +96,48 @@ async function run(detail) {throw withMessage(new Error('missing frontal'), 'Add a front-facing photo to start.', 'frontal');}- setStatus('Preparing photos…');+ if (Date.now() < _rateLimitedUntil) {+ const secsLeft = Math.ceil((_rateLimitedUntil - Date.now()) / 1000);+ const e = withMessage(+ new Error('rate_limited'),+ `Too many attempts -- wait ${secsLeft}s and try again.`,+ );+ /** @type {any} */ (e).rateLimited = true;+ throw e;+ }++ setStatus('Preparing photos...');const slots = /** @type {const} */ (['frontal', 'left', 'right']);_lastSlotsSent = [];const photos = [];for (const slot of slots) {const file = detail.files[slot];if (!file) continue;- photos.push(await fileToDataUrl(file));+ const dataUrl = await fileToDataUrl(file);+ if (!dataUrl || dataUrl.length < 500) {+ throw withMessage(new Error('invalid image data'), 'One of your photos could not be processed. Try a different file.', slot);+ }+ photos.push(dataUrl);_lastSlotsSent.push(slot);}- // Emit the frontal photo immediately for the build view's fast preview —- // a real image, mapped to the placeholder body until the engine returns.+ setStatus('Checking face...');+ const failedSlot = await checkFacesLocal(detail.files);+ if (failedSlot) {+ throw withMessage(+ new Error('client face check failed'),+ failedSlot === 'frontal'+ ? "We couldn't detect a face in your photo. Make sure your face is clearly visible, well-lit, and not obscured by sunglasses or a mask."+ : `We couldn't detect a face in your ${failedSlot} angle photo. Try a clearer shot or remove it.`,+ failedSlot,+ );+ }+document.dispatchEvent(new CustomEvent('selfie:preview', {detail: { dataUrl: photos[0] },}));- setStatus('Submitting to avatar engine…');+ setStatus('Submitting to avatar engine...');const submitRes = await fetch(SUBMIT_ENDPOINT, {method: 'POST',credentials: 'include',@@ -103,9 +161,12 @@ async function run(detail) {}_building = true;+ _jobStartTime = Date.now();+ try { sessionStorage.setItem('selfie:pendingJobId', submitData.jobId); } catch (_) {}document.dispatchEvent(new CustomEvent('selfie:building', { detail: { jobId: submitData.jobId } }));const finalJob = await pollUntilDone(submitData.jobId);+ try { sessionStorage.removeItem('selfie:pendingJobId'); } catch (_) {}if (!finalJob.resultAvatarId) {throw withMessage(@@ -119,6 +180,41 @@ async function run(detail) {}));}+/**+ * Check all submitted photos for faces. Returns the first failing slot name,+ * or null if all pass. Frontal is required; sides are optional.+ * @param {Record<string, File | null>} files+ * @returns {Promise<string | null>}+ */+async function checkFacesLocal(files) {+ const slots = ['frontal', 'left', 'right'];+ for (const slot of slots) {+ const file = files[slot];+ if (!file) continue;+ const ok = await checkFaceLocal(file);+ if (!ok) return slot;+ }+ return null;+}++/**+ * Quick client-side face check via MediaPipe. Returns true if a face is+ * found, false otherwise. Never blocks submission on load failure -- if+ * MediaPipe can't load, we skip and let the server decide.+ * @param {File} file+ * @returns {Promise<boolean>}+ */+async function checkFaceLocal(file) {+ try {+ const img = await loadBitmap(file);+ const result = await detectFaceIdentity(img);+ if (img.close) img.close();+ return result !== null;+ } catch (_) {+ return true;+ }+}+/*** Poll the status endpoint until the job reaches a terminal state, throwing* with a user-facing message on failure or timeout.@@ -127,17 +223,27 @@ async function run(detail) {async function pollUntilDone(jobId) {const deadline = Date.now() + POLL_TIMEOUT_MS;let attempt = 0;+ let consecutiveErrors = 0;const url = `${STATUS_ENDPOINT}?jobId=${encodeURIComponent(jobId)}`;while (Date.now() < deadline) {- await sleep(attempt === 0 ? 1500 : POLL_INTERVAL_MS);+ const interval = attempt === 0 ? 1500 : backoffInterval(consecutiveErrors);+ await sleep(interval);attempt += 1;let res;try {res = await fetch(url, { credentials: 'include' });+ consecutiveErrors = 0;} catch (err) {- console.warn('[selfie-pipeline] poll fetch failed:', err);+ consecutiveErrors += 1;+ console.warn('[selfie-pipeline] poll fetch failed (%d):', consecutiveErrors, err);+ if (consecutiveErrors >= 5) {+ throw withMessage(+ new Error('poll network failure'),+ 'Lost connection to the avatar engine. Check your internet and try again.',+ );+ }continue;}@@ -145,13 +251,15 @@ async function pollUntilDone(jobId) {if (res.status === 404) {throw withMessage(new Error('job vanished'), 'Job disappeared. Try again.');}- // transient — keep polling+ consecutiveErrors += 1;continue;}const job = await res.json().catch(() => ({}));+ const elapsed = Date.now() - _jobStartTime;+document.dispatchEvent(new CustomEvent('selfie:progress', {- detail: { label: statusLabel(job.status, attempt), attempt },+ detail: { label: statusLabel(job.status, attempt, elapsed), attempt },}));if (job.status === 'done') return job;@@ -162,6 +270,13 @@ async function pollUntilDone(jobId) {inferFailingSlot(job.error),);}++ if (elapsed > 10 * 60 * 1000 && job.status === 'running') {+ throw withMessage(+ new Error('stalled job'),+ 'This is taking unusually long. Your avatar may still be processing -- check your dashboard in a few minutes.',+ );+ }}throw withMessage(@@ -170,47 +285,59 @@ async function pollUntilDone(jobId) {);}+/** @param {number} errors */+function backoffInterval(errors) {+ if (errors <= 0) return POLL_INTERVAL_MS;+ return Math.min(POLL_INTERVAL_MS * Math.pow(1.5, errors), 30_000);+}+/*** @param {'queued'|'running'|'done'|'failed'|undefined} status* @param {number} attempt+ * @param {number} elapsedMs*/-function statusLabel(status, attempt) {- if (status === 'queued') return 'Queued — waiting for a reconstruction slot…';+function statusLabel(status, attempt, elapsedMs) {+ if (status === 'queued') return 'Queued -- waiting for a reconstruction slot...';if (status === 'running') {- if (attempt <= 6) return 'Analyzing face geometry…';- if (attempt <= 14) return 'Building mesh…';- return 'Finishing rig…';+ if (attempt <= 4) return 'Generating 3D mesh from your photo...';+ if (attempt <= 12) return 'Building geometry and textures...';+ if (attempt <= 25) return 'Auto-rigging skeleton and skinning...';+ if (attempt <= 35) return 'Finishing avatar...';+ if (elapsedMs > 5 * 60 * 1000) return 'Still working -- this one is taking a bit longer...';+ return 'Almost there -- finalizing...';}if (status === 'done') return 'Done!';- return `Processing… (${attempt}s)`;+ return 'Processing...';}/** @param {string | null | undefined} raw */function friendlyJobError(raw) {if (!raw) return 'Avatar reconstruction failed. Try clearer photos in better light.';const lower = raw.toLowerCase();+if (lower.includes('face') && lower.includes('detect'))return 'We could not find a face in your front photo. Try a clearer, well-lit shot.';- if (lower.includes('nsfw')) return 'Your photo was flagged by content safety. Try a different shot.';- if (lower.includes('blur')) return 'Your photo looks blurry. Try again with a sharper shot in better light.';- if (lower.includes('timeout')) return 'The engine took too long. Try again in a moment.';+ if (lower.includes('nsfw'))+ return 'Your photo was flagged by content safety. Try a different shot.';+ if (lower.includes('blur'))+ return 'Your photo looks blurry. Try again with a sharper shot in better light.';++ if (lower.includes('unreachable') || lower.includes('service') || lower.includes('502') || lower.includes('503'))+ return 'The avatar engine is temporarily unavailable. Please try again in a few minutes.';+ if (lower.includes('timeout') || lower.includes('timed out'))+ return 'The engine took too long. Try again in a moment.';+ if (lower.includes('oom') || lower.includes('memory'))+ return 'The engine ran out of resources. Try again with a simpler photo.';+return 'Avatar reconstruction failed. Try again with a clearer photo.';}/**- * Server errors don't always tell us which photo caused the failure. Use the- * order we submitted (frontal first) plus error-text hints to guess so the UI- * can flag the right slot for retake. Returns null when there's nothing useful- * to infer.* @param {string | null | undefined} raw*/function inferFailingSlot(raw) {if (!_lastSlotsSent.length) return null;- if (!raw) {- // No detail — frontal is the most likely culprit and the one the user- // definitely supplied.- return _lastSlotsSent[0];- }+ if (!raw) return _lastSlotsSent[0];const lower = raw.toLowerCase();if (lower.includes('left')) return _lastSlotsSent.includes('left') ? 'left' : null;if (lower.includes('right')) return _lastSlotsSent.includes('right') ? 'right' : null;@@ -225,8 +352,6 @@ function defaultAvatarName() {}/**- * Reads a File, paints it into a canvas clamped to MAX_DIM × MAX_DIM, returns- * a JPEG data URL. Keeps upload payloads predictable across phone camera sizes.* @param {File} file*/async function fileToDataUrl(file) {@@ -238,11 +363,7 @@ async function fileToDataUrl(file) {const ctx = canvas.getContext('2d');if (!ctx) throw new Error('2d canvas unsupported');ctx.drawImage(bitmap, 0, 0, width, height);- try {- bitmap.close?.();- } catch (_) {- // ImageBitmap.close is optional on older browsers- }+ try { bitmap.close?.(); } catch (_) {}return canvas.toDataURL('image/jpeg', JPEG_QUALITY);}@@ -251,9 +372,7 @@ async function loadBitmap(file) {if (typeof createImageBitmap === 'function') {try {return await createImageBitmap(file);- } catch (_) {- // fall through to <img> fallback- }+ } catch (_) {}}return new Promise((resolve, reject) => {const img = new Image();@@ -296,11 +415,14 @@ function mapApiError(status, payload) {);if (status === 413)return withMessage(new Error(code || 'too_large'), 'Photos are too large. Try again.');- if (status === 429)- return withMessage(+ if (status === 429) {+ const e = withMessage(new Error(code || 'rate_limited'),- 'Too many attempts — wait a minute and try again.',+ 'Too many attempts -- wait a minute and try again.',);+ /** @type {any} */ (e).rateLimited = true;+ return e;+ }if (status === 501)return withMessage(new Error(code || 'not_configured'),@@ -333,9 +455,10 @@ function sleep(ms) {return new Promise((resolve) => setTimeout(resolve, ms));}-// ── UI helpers ─────────────────────────────────────────────────────────────+// ── UI helpers ────────────────────────────────────────────────────────────const submitBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('submit-btn'));let errorBanner = /** @type {HTMLElement | null} */ (null);+let _cooldownTimer = 0;/** @param {string} text @param {{ error?: boolean }} [opts] */function setStatus(text, opts = {}) {@@ -373,3 +496,33 @@ function resetSubmit() {if (labelEl) labelEl.textContent = 'Build my avatar';else submitBtn.textContent = 'Build my avatar';}++/** @param {string} slot */+function highlightSlotError(slot) {+ const frame = document.querySelector(+ slot === 'frontal'+ ? '.hero-slot[data-slot="frontal"]'+ : `.slot-frame[data-slot="${slot}"]`,+ );+ frame?.classList.add('error');+ if (slot !== 'frontal') {+ const fid = /** @type {HTMLDetailsElement|null} */ (document.getElementById('fidelity-boost'));+ if (fid) fid.open = true;+ }+}++function startRateLimitCooldown() {+ _rateLimitedUntil = Date.now() + RATE_LIMIT_COOLDOWN_MS;+ if (_cooldownTimer) clearInterval(_cooldownTimer);+ _cooldownTimer = window.setInterval(() => {+ const remaining = Math.ceil((_rateLimitedUntil - Date.now()) / 1000);+ if (remaining <= 0) {+ clearInterval(_cooldownTimer);+ _cooldownTimer = 0;+ _rateLimitedUntil = 0;+ resetSubmit();+ return;+ }+ setStatus(`Rate limited -- try again in ${remaining}s`, { error: true });+ }, 1000);+}diff --git a/src/walk.js b/src/walk.jsindex 6c9d44345..8700d4a5e 100644--- a/src/walk.js+++ b/src/walk.js@@ -200,6 +200,10 @@ let arFrozenCamLook = null;const PITCH_MIN = -0.6;const PITCH_MAX = 0.7;+const CAM_ZOOM_MIN = 0.6;+const CAM_ZOOM_MAX = 3.2;+let camZoom = 1.0;+// Place the camera at its starting pose immediately so frame 0 isn't blank.function applyCameraImmediate() {const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);@@ -280,10 +284,6 @@ function triggerJump() {const SNAP_TURN_RAD = Math.PI / 4; // 45°// ── Scroll-wheel zoom ────────────────────────────────────────────────────-const CAM_ZOOM_MIN = 0.6;-const CAM_ZOOM_MAX = 3.2;-let camZoom = 1.0; // multiplier on CAM_OFFSET distance-canvas.addEventListener('wheel', (e) => {e.preventDefault();camZoom = Math.max(CAM_ZOOM_MIN, Math.min(CAM_ZOOM_MAX, camZoom + e.deltaY * 0.001));diff --git a/vercel.json b/vercel.jsonindex 684763887..0295409c4 100644--- a/vercel.json+++ b/vercel.json@@ -527,6 +527,10 @@"src": "/home-v3/?","dest": "/home-v3.html"},+ {+ "src": "/home-v4/?",+ "dest": "/home-v4.html"+ },{"src": "/agent-next/?","dest": "/agent-next.html"@@ -1904,6 +1908,14 @@"src": "/api/(.*)","dest": "/api/$1"},+ {+ "src": "/ingest/static/(.*)",+ "dest": "https://us-assets.i.posthog.com/static/$1"+ },+ {+ "src": "/ingest/(.*)",+ "dest": "https://us.i.posthog.com/$1"+ },{"src": "/agent-3d/([0-9]+\\.[0-9]+\\.[0-9]+(?:-[A-Za-z0-9.-]+)?)/(.*)","headers": {diff --git a/vite.config.js b/vite.config.jsindex 683e21843..49f57a33a 100644--- a/vite.config.js+++ b/vite.config.js@@ -47,6 +47,16 @@ function discoverDashboardNextInputs() {const appConfig = {server: {proxy: {+ '/ingest/static': {+ target: 'https://us-assets.i.posthog.com',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/ingest/, ''),+ },+ '/ingest': {+ target: 'https://us.i.posthog.com',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/ingest/, ''),+ },'/chat': {target: 'http://localhost:5174',changeOrigin: true,@@ -176,6 +186,7 @@ creating: resolve(__dirname, 'pages/creating.html'),'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),'home-next': resolve(__dirname, 'pages/home-next.html'),'home-v3': resolve(__dirname, 'pages/home-v3.html'),+ 'home-v4': resolve(__dirname, 'pages/home-v4.html'),'agent-next': resolve(__dirname, 'pages/agent-next.html'),'discover-next': resolve(__dirname, 'pages/discover-next.html'),walk: resolve(__dirname, 'pages/walk.html'),@@ -454,6 +465,8 @@ creating: resolve(__dirname, 'pages/creating.html'),'/home-classic/': resolve(root, 'pages/home.html'),'/home-v3': resolve(root, 'pages/home-v3.html'),'/home-v3/': resolve(root, 'pages/home-v3.html'),+ '/home-v4': resolve(root, 'pages/home-v4.html'),+ '/home-v4/': resolve(root, 'pages/home-v4.html'),'/features': resolve(root, 'pages/features.html'),'/features/': resolve(root, 'pages/features.html'),'/agent': resolve(root, 'pages/agent-home.html'),@@ -729,7 +742,7 @@ creating: resolve(__dirname, 'pages/creating.html'),]);const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/').split('/').pop();if (EMBED_FILES.has(filename)) return [];- const SNIPPET = `!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias set_config reset opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_distinct_id get_session_id get_session_replay_url register register_once unregister on onFeatureFlags reloadFeatureFlags getFeatureFlag getFeatureFlagPayload isFeatureEnabled addExceptionStep captureException".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('phc_kvi8nrXqrNkLNy2NhaiwkbGyj77XpSJo54P5k2ZHYo9n',{api_host:'https://us.i.posthog.com',defaults:'2026-01-30',person_profiles:'identified_only'})`;+ const SNIPPET = `!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",p.onerror=function(){window.__posthog_blocked=!0},(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias set_config reset opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_distinct_id get_session_id get_session_replay_url register register_once unregister on onFeatureFlags reloadFeatureFlags getFeatureFlag getFeatureFlagPayload isFeatureEnabled addExceptionStep captureException".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('phc_kvi8nrXqrNkLNy2NhaiwkbGyj77XpSJo54P5k2ZHYo9n',{api_host:'/ingest',ui_host:'https://us.posthog.com',defaults:'2026-01-30',person_profiles:'identified_only'})`;return [{ tag: 'script', children: SNIPPET, injectTo: 'head' }];},},diff --git a/workers/avatar-pipeline-controller/Dockerfile b/workers/avatar-pipeline-controller/Dockerfilenew file mode 100644index 000000000..09d2886e3--- /dev/null+++ b/workers/avatar-pipeline-controller/Dockerfile@@ -0,0 +1,19 @@+FROM python:3.12-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY main.py /app/main.py++EXPOSE 8080++CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "2", \+ "--timeout-keep-alive", "300"]diff --git a/workers/avatar-pipeline-controller/cloudbuild.yaml b/workers/avatar-pipeline-controller/cloudbuild.yamlnew file mode 100644index 000000000..80357ff67--- /dev/null+++ b/workers/avatar-pipeline-controller/cloudbuild.yaml@@ -0,0 +1,57 @@+substitutions:+ _REGION: us-central1+ _SERVICE: avatar-pipeline-controller+ _REPO: avatar-pipeline-controller+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _MIN_INSTANCES: "1"+ _MAX_INSTANCES: "4"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/avatar-pipeline-controller+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ # CPU-only — no GPU needed for orchestration.+ - --cpu=2+ - --memory=2Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=600+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},FIRESTORE_PROJECT=$PROJECT_ID,SKIP_RIGGING=false+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/avatar-pipeline-controller/main.py b/workers/avatar-pipeline-controller/main.pynew file mode 100644index 000000000..80d8986e4--- /dev/null+++ b/workers/avatar-pipeline-controller/main.py@@ -0,0 +1,372 @@+"""+Avatar Pipeline Controller — orchestrates mesh generation + auto-rigging.++Same external API contract as the original avatar-reconstruction service so+the Vercel backend (api/_providers/gcp.js) needs zero changes:++ POST /reconstruct { images: [...], body_type?: str }+ → 202 { job_id, status: "queued" }++ GET /jobs/:id → { job_id, status, glb_url?, error?, updated_at, model }++ GET /health → { ok, models, router }++Internally the controller:+ 1. Picks a model backend (Hunyuan3D / TRELLIS / TripoSR) via weighted random.+ 2. POSTs images to the chosen backend's /infer endpoint.+ 3. Polls backend until the raw mesh is ready.+ 4. POSTs the raw mesh to UniRig for skeleton + skinning + blendshapes.+ 5. Uploads the final rigged GLB to GCS.+ 6. Updates Firestore with the final status + glb_url.++Environment variables:+ API_KEY — shared bearer secret+ GCS_BUCKET — Cloud Storage bucket for output GLBs+ FIRESTORE_PROJECT — GCP project hosting Firestore+ MODEL_HUNYUAN3D_URL — URL of the Hunyuan3D Cloud Run service (optional)+ MODEL_TRELLIS_URL — URL of the TRELLIS Cloud Run service (optional)+ MODEL_TRIPOSR_URL — URL of the TripoSR Cloud Run service (optional)+ UNIRIG_URL — URL of the UniRig Cloud Run service (optional)+ MODEL_WEIGHTS — JSON routing weights, e.g. '{"hunyuan3d":0.5,"trellis":0.3,"triposr":0.2}'+ SKIP_RIGGING — set to "true" to skip the UniRig stage (for testing)+"""++from __future__ import annotations++import asyncio+import json+import logging+import os+import random+import time+import traceback+import uuid+from contextlib import asynccontextmanager+from datetime import datetime, timezone+from typing import Optional++import httpx+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import firestore, storage+from pydantic import BaseModel, Field++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("controller")++# ── config ────────────────────────────────────────────────────────────────────++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+FIRESTORE_PROJECT = os.environ["FIRESTORE_PROJECT"]+SKIP_RIGGING = os.environ.get("SKIP_RIGGING", "").lower() == "true"++BACKENDS = {}+for name, env_key in [+ ("hunyuan3d", "MODEL_HUNYUAN3D_URL"),+ ("trellis", "MODEL_TRELLIS_URL"),+ ("triposr", "MODEL_TRIPOSR_URL"),+]:+ url = os.environ.get(env_key, "").strip().rstrip("/")+ if url:+ BACKENDS[name] = url++UNIRIG_URL = os.environ.get("UNIRIG_URL", "").strip().rstrip("/")++MODEL_WEIGHTS: dict[str, float] = {}+_raw_weights = os.environ.get("MODEL_WEIGHTS", "").strip()+if _raw_weights:+ try:+ MODEL_WEIGHTS = json.loads(_raw_weights)+ except json.JSONDecodeError:+ log.warning("MODEL_WEIGHTS is not valid JSON, ignoring: %s", _raw_weights)++# Fall back to equal weights for all configured backends.+if not MODEL_WEIGHTS:+ n = len(BACKENDS)+ MODEL_WEIGHTS = {k: 1.0 / max(n, 1) for k in BACKENDS}++# Normalize weights to configured backends only.+_active = {k: v for k, v in MODEL_WEIGHTS.items() if k in BACKENDS}+_total = sum(_active.values()) or 1.0+MODEL_WEIGHTS = {k: v / _total for k, v in _active.items()}++# ── global state ──────────────────────────────────────────────────────────────++_db: Optional[firestore.Client] = None+_bucket: Optional[storage.Bucket] = None+_http: Optional[httpx.AsyncClient] = None++COLLECTION = "avatar_pipeline_jobs"++MESH_POLL_INTERVAL = 3.0+MESH_POLL_TIMEOUT = 300.0+RIG_POLL_INTERVAL = 3.0+RIG_POLL_TIMEOUT = 180.0+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _db, _bucket, _http+ _db = firestore.Client(project=FIRESTORE_PROJECT)+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _http = httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=300.0))+ log.info(+ "Controller ready — backends=%s, weights=%s, unirig=%s, skip_rigging=%s",+ list(BACKENDS.keys()), MODEL_WEIGHTS, bool(UNIRIG_URL), SKIP_RIGGING,+ )+ yield+ await _http.aclose()+++app = FastAPI(title="avatar-pipeline-controller", lifespan=lifespan)+++# ── auth ──────────────────────────────────────────────────────────────────────++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++# ── Firestore helpers ─────────────────────────────────────────────────────────++def _set_job(job_id: str, data: dict) -> None:+ _db.collection(COLLECTION).document(job_id).set(+ {**data, "updated_at": datetime.now(timezone.utc)},+ merge=True,+ )+++def _get_job(job_id: str) -> dict | None:+ doc = _db.collection(COLLECTION).document(job_id).get()+ return doc.to_dict() if doc.exists else None+++# ── model routing ─────────────────────────────────────────────────────────────++def _pick_model(requested: str | None = None) -> str:+ if requested and requested in BACKENDS:+ return requested+ if not MODEL_WEIGHTS:+ raise HTTPException(status_code=503, detail="no model backends configured")+ models = list(MODEL_WEIGHTS.keys())+ weights = [MODEL_WEIGHTS[m] for m in models]+ return random.choices(models, weights=weights, k=1)[0]+++# ── pipeline worker ───────────────────────────────────────────────────────────++async def _run_pipeline(+ job_id: str,+ images: list[str],+ body_type: str,+ model_name: str,+) -> None:+ t0 = time.time()+ backend_url = BACKENDS[model_name]++ try:+ # ── Stage 1: Mesh generation ──────────────────────────────────────+ _set_job(job_id, {"status": "running", "stage": "mesh_generation"})+ log.info("[%s] submitting to %s", job_id, model_name)++ resp = await _http.post(+ f"{backend_url}/infer",+ json={"images": images, "body_type": body_type, "job_id": job_id},+ headers={"authorization": f"Bearer {API_KEY}"},+ )+ if resp.status_code != 202:+ detail = resp.json().get("detail", resp.text) if resp.status_code < 500 else resp.text+ raise RuntimeError(f"{model_name} rejected job: {resp.status_code} — {detail}")++ task = resp.json()+ task_id = task["task_id"]+ log.info("[%s] %s accepted — task_id=%s", job_id, model_name, task_id)++ # Poll for mesh completion.+ mesh_gcs_url = await _poll_backend(+ backend_url, task_id, MESH_POLL_INTERVAL, MESH_POLL_TIMEOUT, job_id, "mesh",+ )+ mesh_time = time.time() - t0+ _set_job(job_id, {"mesh_time_ms": int(mesh_time * 1000), "mesh_gcs_url": mesh_gcs_url})+ log.info("[%s] mesh ready in %.1fs — %s", job_id, mesh_time, mesh_gcs_url)++ # ── Stage 2: Auto-rigging (optional) ──────────────────────────────+ rigged_gcs_url = mesh_gcs_url+ if UNIRIG_URL and not SKIP_RIGGING:+ _set_job(job_id, {"stage": "rigging"})+ log.info("[%s] submitting to UniRig", job_id)++ rig_resp = await _http.post(+ f"{UNIRIG_URL}/rig",+ json={+ "mesh_gcs_url": mesh_gcs_url,+ "template": "wolf3d_neutral",+ "blendshapes": True,+ "job_id": job_id,+ },+ headers={"authorization": f"Bearer {API_KEY}"},+ )+ if rig_resp.status_code == 202:+ rig_task = rig_resp.json()+ rigged_gcs_url = await _poll_backend(+ UNIRIG_URL, rig_task["task_id"],+ RIG_POLL_INTERVAL, RIG_POLL_TIMEOUT, job_id, "rig",+ )+ rig_time = time.time() - t0 - mesh_time+ _set_job(job_id, {"rig_time_ms": int(rig_time * 1000)})+ log.info("[%s] rigging done in %.1fs", job_id, rig_time)+ else:+ log.warning("[%s] UniRig rejected (%d) — using unrigged mesh", job_id, rig_resp.status_code)+ else:+ log.info("[%s] skipping rigging (unirig_url=%s, skip=%s)", job_id, bool(UNIRIG_URL), SKIP_RIGGING)++ # ── Stage 3: Copy final GLB to the output bucket ─────────────────+ _set_job(job_id, {"stage": "finalizing"})+ final_url = await _copy_to_output(job_id, rigged_gcs_url)++ total_time = time.time() - t0+ _set_job(job_id, {+ "status": "done",+ "stage": "done",+ "glb_url": final_url,+ "total_time_ms": int(total_time * 1000),+ })+ log.info("[%s] pipeline done in %.1fs — %s", job_id, total_time, final_url)++ except Exception:+ err = traceback.format_exc()+ log.exception("[%s] pipeline failed", job_id)+ _set_job(job_id, {+ "status": "failed",+ "stage": "failed",+ "error": err,+ "total_time_ms": int((time.time() - t0) * 1000),+ })+++async def _poll_backend(+ base_url: str,+ task_id: str,+ interval: float,+ timeout: float,+ job_id: str,+ stage_label: str,+) -> str:+ """Poll a backend's /tasks/:id endpoint until done. Returns the GCS URL."""+ deadline = time.time() + timeout+ attempt = 0+ while time.time() < deadline:+ await asyncio.sleep(interval if attempt > 0 else 1.5)+ attempt += 1+ try:+ resp = await _http.get(+ f"{base_url}/tasks/{task_id}",+ headers={"authorization": f"Bearer {API_KEY}"},+ )+ except httpx.RequestError as exc:+ log.warning("[%s] %s poll %d failed: %s", job_id, stage_label, attempt, exc)+ continue++ if resp.status_code == 404:+ raise RuntimeError(f"{stage_label} task {task_id} vanished")+ if resp.status_code != 200:+ continue++ data = resp.json()+ status = data.get("status", "")+ if status == "done":+ url = data.get("result_gcs_url") or data.get("rigged_gcs_url") or data.get("glb_url")+ if not url:+ raise RuntimeError(f"{stage_label} returned done but no URL in response: {data}")+ return url+ if status == "failed":+ raise RuntimeError(data.get("error", f"{stage_label} failed without details"))++ raise RuntimeError(f"{stage_label} timed out after {timeout}s")+++async def _copy_to_output(job_id: str, source_gcs_url: str) -> str:+ """Copy a GLB from a backend's GCS path to the controller's output bucket."""+ loop = asyncio.get_event_loop()++ # If the source is already in our output bucket, just return it.+ expected_prefix = f"https://storage.googleapis.com/{GCS_BUCKET}/"+ if source_gcs_url.startswith(expected_prefix):+ return source_gcs_url++ # Download from source and re-upload to output bucket.+ resp = await _http.get(source_gcs_url)+ resp.raise_for_status()+ glb_bytes = resp.content++ blob_name = f"avatars/{job_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),+ )+ return f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"+++# ── routes ────────────────────────────────────────────────────────────────────++class ReconstructRequest(BaseModel):+ images: list[str] = Field(..., min_length=1, max_length=6)+ job_id: str | None = None+ body_type: str = "neutral"+ model: str | None = None++[email protected]("/reconstruct", status_code=202)+async def reconstruct(+ body: ReconstructRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)++ model_name = _pick_model(body.model)+ job_id = body.job_id or str(uuid.uuid4())++ _set_job(job_id, {+ "job_id": job_id,+ "status": "queued",+ "stage": "queued",+ "model": model_name,+ "image_count": len(body.images),+ "body_type": body.body_type,+ "created_at": datetime.now(timezone.utc),+ })++ background_tasks.add_task(_run_pipeline, job_id, body.images, body.body_type, model_name)+ return {"job_id": job_id, "status": "queued", "model": model_name}++[email protected]("/jobs/{job_id}")+async def get_job(job_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ job = _get_job(job_id)+ if job is None:+ raise HTTPException(status_code=404, detail="job not found")+ for k, v in job.items():+ if hasattr(v, "isoformat"):+ job[k] = v.isoformat()+ return job++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "pipeline": "avatar_pipeline_controller_v2",+ "backends": list(BACKENDS.keys()),+ "weights": MODEL_WEIGHTS,+ "unirig": bool(UNIRIG_URL),+ "skip_rigging": SKIP_RIGGING,+ }diff --git a/workers/avatar-pipeline-controller/requirements.txt b/workers/avatar-pipeline-controller/requirements.txtnew file mode 100644index 000000000..169b8ba1b--- /dev/null+++ b/workers/avatar-pipeline-controller/requirements.txt@@ -0,0 +1,6 @@+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0+google-cloud-firestore==2.19.0+google-cloud-storage==2.18.0diff --git a/workers/model-hunyuan3d/Dockerfile b/workers/model-hunyuan3d/Dockerfilenew file mode 100644index 000000000..d23811f4a--- /dev/null+++ b/workers/model-hunyuan3d/Dockerfile@@ -0,0 +1,32 @@+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget \+ libgl1 libglib2.0-0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++# Install torch first (cached layer).+RUN pip install torch==2.3.1 --index-url https://download.pytorch.org/whl/cu121++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY main.py /app/main.py++EXPOSE 8080++CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "300"]diff --git a/workers/model-hunyuan3d/cloudbuild.yaml b/workers/model-hunyuan3d/cloudbuild.yamlnew file mode 100644index 000000000..2517db9b2--- /dev/null+++ b/workers/model-hunyuan3d/cloudbuild.yaml@@ -0,0 +1,63 @@+substitutions:+ _REGION: us-central1+ _SERVICE: model-hunyuan3d+ _REPO: model-hunyuan3d+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "3"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/model-hunyuan3d+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=8+ - --memory=32Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=300+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/hunyuan3d-2.1,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/model-hunyuan3d/main.py b/workers/model-hunyuan3d/main.pynew file mode 100644index 000000000..dcbb645b7--- /dev/null+++ b/workers/model-hunyuan3d/main.py@@ -0,0 +1,211 @@+"""+Hunyuan3D-2.1 inference service — single-image to textured 3D mesh.++API contract (consumed by the Pipeline Controller):+ POST /infer { images: [data-uri|url, ...], body_type?: str, job_id?: str }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, result_gcs_url?, error? }++ GET /health → { ok, model, gpu_available }++The model weights are loaded from a GCS volume mount at /weights to avoid+re-downloading ~10 GB on every cold start. Pre-populate the bucket:++ # One-time setup (run locally or in Cloud Shell):+ pip install huggingface_hub+ huggingface-cli download tencent/Hunyuan3D-2.1 --local-dir /tmp/hunyuan3d-2.1+ gsutil -m cp -r /tmp/hunyuan3d-2.1 gs://three-ws-model-weights/hunyuan3d-2.1/++Environment variables:+ API_KEY — shared bearer secret+ GCS_BUCKET — Cloud Storage bucket for output meshes+ WEIGHTS_DIR — local path to model weights (default: /weights/hunyuan3d-2.1)+ MAX_CONCURRENT — max parallel inferences (default: 1)+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import os+import time+import traceback+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import torch+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from PIL import Image+from pydantic import BaseModel, Field++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("hunyuan3d")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/hunyuan3d-2.1")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))++_pipeline = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+++def _load_pipeline():+ global _pipeline+ from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline+ from hy3dgen.texgen import Hunyuan3DPaintPipeline++ log.info("Loading shape generation pipeline from %s", WEIGHTS_DIR)+ shape_pipe = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(+ WEIGHTS_DIR,+ subfolder="hunyuan3d-dit-v2-1",+ torch_dtype=torch.float16,+ use_safetensors=True,+ )+ shape_pipe = shape_pipe.to("cuda")++ log.info("Loading texture generation pipeline from %s", WEIGHTS_DIR)+ tex_pipe = Hunyuan3DPaintPipeline.from_pretrained(+ WEIGHTS_DIR,+ subfolder="hunyuan3d-paint-v2-1",+ torch_dtype=torch.float16,+ use_safetensors=True,+ )+ tex_pipe = tex_pipe.to("cuda")++ _pipeline = {"shape": shape_pipe, "texture": tex_pipe}+ log.info("Hunyuan3D-2.1 pipelines loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_pipeline)+ log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)+ yield+++app = FastAPI(title="model-hunyuan3d", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++def _decode_image(src: str) -> Image.Image:+ if src.startswith("data:image"):+ b64 = src.split(",", 1)[1]+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")+ if src.startswith("http://") or src.startswith("https://"):+ import httpx+ resp = httpx.get(src, timeout=30)+ resp.raise_for_status()+ return Image.open(io.BytesIO(resp.content)).convert("RGB")+ raise ValueError(f"unsupported image source: {src[:60]}")+++async def _run_inference(task_id: str, images: list[str], body_type: str) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ img = await loop.run_in_executor(None, _decode_image, images[0])++ def _generate():+ mesh = _pipeline["shape"](+ image=img,+ num_inference_steps=30,+ guidance_scale=5.5,+ octree_resolution=256,+ )+ textured = _pipeline["texture"](+ mesh=mesh,+ image=img,+ num_inference_steps=20,+ guidance_scale=7.5,+ )+ buf = io.BytesIO()+ textured.export(buf, file_type="glb")+ return buf.getvalue()++ glb_bytes = await loop.run_in_executor(None, _generate)++ blob_name = f"raw-meshes/hunyuan3d/{task_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),+ )+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_gcs_url": gcs_url,+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)++ except Exception:+ _tasks[task_id].update({+ "status": "failed",+ "error": traceback.format_exc(),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+ log.exception("[%s] inference failed", task_id)+++class InferRequest(BaseModel):+ images: list[str] = Field(..., min_length=1, max_length=6)+ body_type: str = "neutral"+ job_id: str | None = None++[email protected]("/infer", status_code=202)+async def infer(+ body: InferRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "hunyuan3d-2.1"}+ background_tasks.add_task(_run_inference, task_id, body.images, body.body_type)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "hunyuan3d-2.1",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "pipeline_loaded": _pipeline is not None,+ }diff --git a/workers/model-hunyuan3d/requirements.txt b/workers/model-hunyuan3d/requirements.txtnew file mode 100644index 000000000..a1e8112e6--- /dev/null+++ b/workers/model-hunyuan3d/requirements.txt@@ -0,0 +1,23 @@+# ── Hunyuan3D-2.1 ─────────────────────────────────────────────────────────────+# Install from the official Tencent repo. The hy3dgen package includes both the+# shape generation (DiT) and texture painting (Paint) pipelines.+hy3dgen @ git+https://github.com/Tencent/Hunyuan3D-2.git@main#subdirectory=hy3dgen++torch>=2.3.0+diffusers>=0.31.0+transformers>=4.44.0+accelerate>=0.34.0+safetensors>=0.4.0+trimesh>=4.4.0++# ── Image processing ──────────────────────────────────────────────────────────+Pillow>=10.3.0++# ── Server ────────────────────────────────────────────────────────────────────+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0++# ── GCP ───────────────────────────────────────────────────────────────────────+google-cloud-storage==2.18.0diff --git a/workers/model-trellis/Dockerfile b/workers/model-trellis/Dockerfilenew file mode 100644index 000000000..737c11c20--- /dev/null+++ b/workers/model-trellis/Dockerfile@@ -0,0 +1,31 @@+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget \+ libgl1 libglib2.0-0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++RUN pip install torch==2.3.1 --index-url https://download.pytorch.org/whl/cu121++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY main.py /app/main.py++EXPOSE 8080++CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "300"]diff --git a/workers/model-trellis/cloudbuild.yaml b/workers/model-trellis/cloudbuild.yamlnew file mode 100644index 000000000..6afa12d1d--- /dev/null+++ b/workers/model-trellis/cloudbuild.yaml@@ -0,0 +1,63 @@+substitutions:+ _REGION: us-central1+ _SERVICE: model-trellis+ _REPO: model-trellis+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "2"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/model-trellis+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=4+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=300+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/trellis-large,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/model-trellis/main.py b/workers/model-trellis/main.pynew file mode 100644index 000000000..99ad30c2a--- /dev/null+++ b/workers/model-trellis/main.py@@ -0,0 +1,192 @@+"""+TRELLIS inference service — single-image to textured 3D mesh via structured+latent representations (Microsoft, MIT license).++API contract (consumed by the Pipeline Controller):+ POST /infer { images: [data-uri|url, ...], body_type?: str, job_id?: str }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, result_gcs_url?, error? }++ GET /health → { ok, model, gpu_available }++Model weights pre-population:+ pip install huggingface_hub+ huggingface-cli download microsoft/TRELLIS-image-large --local-dir /tmp/trellis-large+ gsutil -m cp -r /tmp/trellis-large gs://three-ws-model-weights/trellis-large/++Environment variables:+ API_KEY — shared bearer secret+ GCS_BUCKET — Cloud Storage bucket for output meshes+ WEIGHTS_DIR — local path to model weights (default: /weights/trellis-large)+ MAX_CONCURRENT — max parallel inferences (default: 1)+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import os+import time+import traceback+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import torch+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from PIL import Image+from pydantic import BaseModel, Field++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("trellis")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/trellis-large")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))++_pipeline = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+++def _load_pipeline():+ global _pipeline+ from trellis.pipelines import TrellisImageTo3DPipeline++ log.info("Loading TRELLIS pipeline from %s", WEIGHTS_DIR)+ _pipeline = TrellisImageTo3DPipeline.from_pretrained(WEIGHTS_DIR)+ _pipeline = _pipeline.to("cuda")+ log.info("TRELLIS pipeline loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_pipeline)+ log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)+ yield+++app = FastAPI(title="model-trellis", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++def _decode_image(src: str) -> Image.Image:+ if src.startswith("data:image"):+ b64 = src.split(",", 1)[1]+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")+ if src.startswith("http://") or src.startswith("https://"):+ import httpx+ resp = httpx.get(src, timeout=30)+ resp.raise_for_status()+ return Image.open(io.BytesIO(resp.content)).convert("RGB")+ raise ValueError(f"unsupported image source: {src[:60]}")+++async def _run_inference(task_id: str, images: list[str], body_type: str) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ img = await loop.run_in_executor(None, _decode_image, images[0])++ def _generate():+ outputs = _pipeline.run(+ img,+ seed=42,+ formats=["gaussian", "mesh"],+ preprocess_image=True,+ )+ glb = _pipeline.to_glb(+ outputs["gaussian"][0],+ outputs["mesh"][0],+ simplify=0.95,+ texture_size=1024,+ )+ buf = io.BytesIO()+ glb.export(buf, file_type="glb")+ return buf.getvalue()++ glb_bytes = await loop.run_in_executor(None, _generate)++ blob_name = f"raw-meshes/trellis/{task_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),+ )+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_gcs_url": gcs_url,+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)++ except Exception:+ _tasks[task_id].update({+ "status": "failed",+ "error": traceback.format_exc(),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+ log.exception("[%s] inference failed", task_id)+++class InferRequest(BaseModel):+ images: list[str] = Field(..., min_length=1, max_length=6)+ body_type: str = "neutral"+ job_id: str | None = None++[email protected]("/infer", status_code=202)+async def infer(+ body: InferRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "trellis-large"}+ background_tasks.add_task(_run_inference, task_id, body.images, body.body_type)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "trellis-image-large",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "pipeline_loaded": _pipeline is not None,+ }diff --git a/workers/model-trellis/requirements.txt b/workers/model-trellis/requirements.txtnew file mode 100644index 000000000..39f6b31d3--- /dev/null+++ b/workers/model-trellis/requirements.txt@@ -0,0 +1,17 @@+# ── TRELLIS (Microsoft) ───────────────────────────────────────────────────────+trellis @ git+https://github.com/microsoft/TRELLIS.git@main++torch>=2.3.0+xformers>=0.0.27+safetensors>=0.4.0+trimesh>=4.4.0+Pillow>=10.3.0++# ── Server ────────────────────────────────────────────────────────────────────+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0++# ── GCP ───────────────────────────────────────────────────────────────────────+google-cloud-storage==2.18.0diff --git a/workers/model-triposr/Dockerfile b/workers/model-triposr/Dockerfilenew file mode 100644index 000000000..737c11c20--- /dev/null+++ b/workers/model-triposr/Dockerfile@@ -0,0 +1,31 @@+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget \+ libgl1 libglib2.0-0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++RUN pip install torch==2.3.1 --index-url https://download.pytorch.org/whl/cu121++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY main.py /app/main.py++EXPOSE 8080++CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "300"]diff --git a/workers/model-triposr/cloudbuild.yaml b/workers/model-triposr/cloudbuild.yamlnew file mode 100644index 000000000..8851f7d43--- /dev/null+++ b/workers/model-triposr/cloudbuild.yaml@@ -0,0 +1,63 @@+substitutions:+ _REGION: us-central1+ _SERVICE: model-triposr+ _REPO: model-triposr+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "2"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/model-triposr+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=4+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=120+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/triposr,MAX_CONCURRENT=2+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/model-triposr/main.py b/workers/model-triposr/main.pynew file mode 100644index 000000000..dcae20bca--- /dev/null+++ b/workers/model-triposr/main.py@@ -0,0 +1,202 @@+"""+TripoSR inference service — fast single-image to 3D mesh (VAST-AI, MIT).++Lightest of the three candidate models. Runs in 5-15 seconds. No PBR textures+(baked single texture), but useful as a fast-path or fallback.++API contract (consumed by the Pipeline Controller):+ POST /infer { images: [data-uri|url, ...], body_type?: str, job_id?: str }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, result_gcs_url?, error? }++ GET /health → { ok, model, gpu_available }++Model weights pre-population:+ pip install huggingface_hub+ huggingface-cli download stabilityai/TripoSR --local-dir /tmp/triposr+ gsutil -m cp -r /tmp/triposr gs://three-ws-model-weights/triposr/++Environment variables:+ API_KEY — shared bearer secret+ GCS_BUCKET — Cloud Storage bucket for output meshes+ WEIGHTS_DIR — local path to model weights (default: /weights/triposr)+ MAX_CONCURRENT — max parallel inferences (default: 2, lighter model)+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import os+import time+import traceback+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import torch+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from PIL import Image+from pydantic import BaseModel, Field++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("triposr")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/triposr")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))++_model = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+++def _load_model():+ global _model+ from tsr import TSR++ log.info("Loading TripoSR model from %s", WEIGHTS_DIR)+ _model = TSR.from_pretrained(+ WEIGHTS_DIR,+ config_name="config.yaml",+ weight_name="model.ckpt",+ )+ _model.to("cuda")+ log.info("TripoSR model loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_model)+ log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)+ yield+++app = FastAPI(title="model-triposr", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++def _decode_image(src: str) -> Image.Image:+ if src.startswith("data:image"):+ b64 = src.split(",", 1)[1]+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")+ if src.startswith("http://") or src.startswith("https://"):+ import httpx+ resp = httpx.get(src, timeout=30)+ resp.raise_for_status()+ return Image.open(io.BytesIO(resp.content)).convert("RGB")+ raise ValueError(f"unsupported image source: {src[:60]}")+++def _remove_background(img: Image.Image) -> Image.Image:+ try:+ import rembg+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ out = rembg.remove(buf.getvalue())+ return Image.open(io.BytesIO(out)).convert("RGBA")+ except Exception:+ return img.convert("RGBA")+++async def _run_inference(task_id: str, images: list[str], body_type: str) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ img = await loop.run_in_executor(None, _decode_image, images[0])+ img_nobg = await loop.run_in_executor(None, _remove_background, img)++ def _generate():+ with torch.no_grad():+ scene_codes = _model([img_nobg], device="cuda")+ meshes = _model.extract_mesh(scene_codes, resolution=256)+ mesh = meshes[0]+ buf = io.BytesIO()+ mesh.export(buf, file_type="glb")+ return buf.getvalue()++ glb_bytes = await loop.run_in_executor(None, _generate)++ blob_name = f"raw-meshes/triposr/{task_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),+ )+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_gcs_url": gcs_url,+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)++ except Exception:+ _tasks[task_id].update({+ "status": "failed",+ "error": traceback.format_exc(),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+ log.exception("[%s] inference failed", task_id)+++class InferRequest(BaseModel):+ images: list[str] = Field(..., min_length=1, max_length=6)+ body_type: str = "neutral"+ job_id: str | None = None++[email protected]("/infer", status_code=202)+async def infer(+ body: InferRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "triposr"}+ background_tasks.add_task(_run_inference, task_id, body.images, body.body_type)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "triposr",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "model_loaded": _model is not None,+ }diff --git a/workers/model-triposr/requirements.txt b/workers/model-triposr/requirements.txtnew file mode 100644index 000000000..b56e0f9cc--- /dev/null+++ b/workers/model-triposr/requirements.txt@@ -0,0 +1,18 @@+# ── TripoSR (VAST-AI / Stability AI) ──────────────────────────────────────────+tsr @ git+https://github.com/VAST-AI-Research/TripoSR.git@main++torch>=2.3.0+trimesh>=4.4.0+Pillow>=10.3.0++# Background removal (TripoSR works best with isolated subject).+rembg[gpu]==2.0.56++# ── Server ────────────────────────────────────────────────────────────────────+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0++# ── GCP ───────────────────────────────────────────────────────────────────────+google-cloud-storage==2.18.0diff --git a/workers/unirig/Dockerfile b/workers/unirig/Dockerfilenew file mode 100644index 000000000..24d07a08f--- /dev/null+++ b/workers/unirig/Dockerfile@@ -0,0 +1,34 @@+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget \+ libgl1 libglib2.0-0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++RUN pip install torch==2.3.1 --index-url https://download.pytorch.org/whl/cu121++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY main.py /app/main.py++# Wolf3D skeleton templates for blendshape transfer (added in Phase 2).+RUN mkdir -p /app/templates++EXPOSE 8080++CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "300"]diff --git a/workers/unirig/cloudbuild.yaml b/workers/unirig/cloudbuild.yamlnew file mode 100644index 000000000..6f377c025--- /dev/null+++ b/workers/unirig/cloudbuild.yaml@@ -0,0 +1,63 @@+substitutions:+ _REGION: us-central1+ _SERVICE: unirig+ _REPO: unirig+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "2"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/unirig+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=4+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=180+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/unirig,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/unirig/main.py b/workers/unirig/main.pynew file mode 100644index 000000000..2d070257b--- /dev/null+++ b/workers/unirig/main.py@@ -0,0 +1,278 @@+"""+UniRig auto-rigging service — adds skeleton, skinning weights, and ARKit-52+blendshapes to raw meshes from the 3D generation models.++VAST-AI-Research/UniRig (MIT, SIGGRAPH 2025) predicts:+ - Skeleton joint placement (humanoid hierarchy)+ - Per-vertex skinning weights+ - Blendshape transfer from a template head mesh++API contract (consumed by the Pipeline Controller):+ POST /rig { mesh_gcs_url: str, template?: str, blendshapes?: bool, job_id?: str }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, rigged_gcs_url?, error? }++ GET /health → { ok, model, gpu_available }++Model weights pre-population:+ pip install huggingface_hub+ huggingface-cli download VAST-AI/UniRig --local-dir /tmp/unirig+ gsutil -m cp -r /tmp/unirig gs://three-ws-model-weights/unirig/++Environment variables:+ API_KEY — shared bearer secret+ GCS_BUCKET — Cloud Storage bucket for output rigged GLBs+ WEIGHTS_DIR — local path to UniRig model weights (default: /weights/unirig)+ TEMPLATES_DIR — local path to skeleton/blendshape templates (default: /app/templates)+ MAX_CONCURRENT — max parallel rigging jobs (default: 1)+"""++from __future__ import annotations++import asyncio+import io+import logging+import os+import time+import traceback+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import numpy as np+import torch+import trimesh+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from pydantic import BaseModel, Field++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("unirig")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/unirig")+TEMPLATES_DIR = os.environ.get("TEMPLATES_DIR", "/app/templates")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))++_model = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+++def _load_model():+ global _model+ from unirig import UniRigModel++ log.info("Loading UniRig model from %s", WEIGHTS_DIR)+ _model = UniRigModel.from_pretrained(WEIGHTS_DIR)+ _model = _model.to("cuda")+ _model.eval()+ log.info("UniRig model loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_model)+ log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)+ yield+++app = FastAPI(title="unirig", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++# Wolf3D / ARKit-52 skeleton joint names. UniRig predicts joint placement; we+# remap its output to this hierarchy so the three.ws avatar runtime can drive it.+WOLF3D_JOINTS = [+ "Hips", "Spine", "Spine1", "Spine2", "Neck", "Head",+ "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",+ "RightShoulder", "RightArm", "RightForeArm", "RightHand",+ "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase",+ "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase",+ "LeftEye", "RightEye", "Jaw",+]++ARKIT_52_BLENDSHAPES = [+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft",+ "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight",+ "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",+ "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight",+ "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",+ "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",+ "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight",+ "mouthFrownLeft", "mouthFrownRight", "mouthFunnel", "mouthLeft",+ "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft",+ "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower",+ "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft",+ "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight",+ "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight",+ "tongueOut",+]+++async def _run_rigging(+ task_id: str,+ mesh_gcs_url: str,+ template: str,+ blendshapes: bool,+) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ # Download the raw mesh from GCS.+ import httpx+ async with httpx.AsyncClient(timeout=60) as client:+ resp = await client.get(mesh_gcs_url)+ resp.raise_for_status()+ mesh_bytes = resp.content++ def _rig():+ mesh = trimesh.load(io.BytesIO(mesh_bytes), file_type="glb", force="mesh")++ with torch.no_grad():+ result = _model.rig(+ vertices=torch.tensor(mesh.vertices, dtype=torch.float32, device="cuda"),+ faces=torch.tensor(mesh.faces, dtype=torch.long, device="cuda"),+ )++ skeleton = result["skeleton"]+ skinning_weights = result["skinning_weights"]++ joints = skeleton["joints"].cpu().numpy()+ parents = skeleton["parents"].cpu().numpy()+ weights = skinning_weights.cpu().numpy()++ import pygltflib+ glb = pygltflib.GLTF2.load_from_bytes(mesh_bytes)+ _inject_skeleton(glb, mesh, joints, parents, weights)++ if blendshapes and hasattr(result, "blendshapes"):+ _inject_blendshapes(glb, mesh, result["blendshapes"])++ buf = io.BytesIO()+ glb.save_to_bytes(buf)+ return buf.getvalue()++ rigged_bytes = await loop.run_in_executor(None, _rig)++ blob_name = f"rigged-meshes/{task_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(rigged_bytes, content_type="model/gltf-binary"),+ )+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "rigged_gcs_url": gcs_url,+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] rigging done in %.1fs — %d bytes → %s", task_id, elapsed, len(rigged_bytes), gcs_url)++ except Exception:+ _tasks[task_id].update({+ "status": "failed",+ "error": traceback.format_exc(),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+ log.exception("[%s] rigging failed", task_id)+++def _inject_skeleton(glb, mesh, joints, parents, weights):+ """+ Inject a skeleton (joints + inverse bind matrices) and skinning weights+ into the GLB. This wires the mesh as a skinned mesh node with the Wolf3D+ joint hierarchy so the three.ws avatar runtime can animate it.++ The actual implementation depends on UniRig's output format. This is a+ scaffold — the joint remapping from UniRig's predicted skeleton to Wolf3D's+ naming convention will need calibration during integration testing.+ """+ log.info("Injecting skeleton: %d joints, %d vertices", len(joints), len(mesh.vertices))+ # TODO: Full pygltflib skeleton injection.+ # This requires:+ # 1. Creating skin.joints[] node array with Wolf3D names+ # 2. Computing inverseBindMatrices accessor+ # 3. Creating a JOINTS_0 + WEIGHTS_0 accessor pair on the mesh primitive+ # 4. Remapping UniRig's joint ordering to WOLF3D_JOINTS+ # Placeholder: the rigged GLB will be returned as-is from UniRig's output+ # format. The three.ws glb-inspect.js will detect whether it's properly rigged.+++def _inject_blendshapes(glb, mesh, blendshapes_data):+ """+ Inject ARKit-52 blendshape morph targets into the GLB.++ Blendshape transfer from a template head is the research-heavy part.+ UniRig may or may not support this natively. Fallback approach:+ 1. Register the generated head mesh to a Wolf3D template via ICP+ 2. Transfer blendshape deltas using deformation transfer+ 3. Name them per ARKIT_52_BLENDSHAPES++ This is scaffolded for now — the initial deployment will ship without+ blendshapes (body animation only via skeleton). Blendshapes will be+ added in a follow-up once we validate the mesh quality from each model.+ """+ log.info("Blendshape injection requested — not yet implemented, skipping")+++class RigRequest(BaseModel):+ mesh_gcs_url: str+ template: str = "wolf3d_neutral"+ blendshapes: bool = True+ job_id: str | None = None++[email protected]("/rig", status_code=202)+async def rig(+ body: RigRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued"}+ background_tasks.add_task(+ _run_rigging, task_id, body.mesh_gcs_url, body.template, body.blendshapes,+ )+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "unirig",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "model_loaded": _model is not None,+ }diff --git a/workers/unirig/requirements.txt b/workers/unirig/requirements.txtnew file mode 100644index 000000000..5fd39974f--- /dev/null+++ b/workers/unirig/requirements.txt@@ -0,0 +1,18 @@+# ── UniRig (VAST-AI, SIGGRAPH 2025) ──────────────────────────────────────────+unirig @ git+https://github.com/VAST-AI-Research/UniRig.git@main++torch>=2.3.0+trimesh>=4.4.0+numpy<2.0+pygltflib==1.16.2+Pillow>=10.3.0+scipy>=1.11.0++# ── Server ────────────────────────────────────────────────────────────────────+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0++# ── GCP ───────────────────────────────────────────────────────────────────────+google-cloud-storage==2.18.0