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: avatar reconstruction pipeline, embed v1, next pages, pricing
nirholas67ed8db53163
diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 70d72e262..98fe61259 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -65,12 +65,14 @@ export function createRegenProvider() {);}+ const bodyType = request.params?.bodyType || 'neutral';+let response;try {response = await fetch(`${base}/reconstruct`, {method: 'POST',headers: authHeaders,- body: JSON.stringify({ images }),+ body: JSON.stringify({ images, body_type: bodyType }),});} catch (err) {throw Object.assign(@@ -89,8 +91,8 @@ export function createRegenProvider() {return {extJobId: data.job_id,- // InstantMesh on an L4 typically takes 45–90 s.- eta: 90,+ // Face texture pipeline: rembg + MediaPipe + TPS + GLB ops ≈ 15–30 s.+ eta: 30,};},diff --git a/docs/internal/PR_LISTINGS_CHECKLIST.md b/docs/internal/PR_LISTINGS_CHECKLIST.mdnew file mode 100644index 000000000..3c1551d6f--- /dev/null+++ b/docs/internal/PR_LISTINGS_CHECKLIST.md@@ -0,0 +1,109 @@+# PR, Listings & SEO Checklist++Track every directory, marketplace, press, and credibility opportunity.+Legend: `[ ]` pending · `[~]` in progress · `[x]` done · `[-]` skipped/N/A++---++## Already Done ✓+- [x] Anthropic MCP Registry+- [x] Coinbase x402 Bazaar+- [x] agentic.market+- [x] BNB Chain DappBay+- [x] Alibaba Cloud Marketplace+- [x] IBM Business Partner+- [x] CoinMarketCap listing + community profile+- [x] CoinGecko listing+- [x] HackerNoon ($150 article + partnership)+- [x] Devpost (MeDo Hackathon)+- [x] Investing.com listing+- [x] Vogue Photo Vogue profile+- [x] inc.com profile ($150)+- [x] Jupiter Exchange verified+- [x] Google Cloud for Web3 Startups++---++## Free — High Priority (do these first)++### Tech Directories+- [ ] **Crunchbase** — free company profile, high DA, every journalist checks it+- [ ] **Product Hunt** — full product launch page; trending = dozens of backlinks overnight+- [ ] **CB Insights** — free company profile, cited by press constantly+- [ ] **AngelList / Wellfound** — startup profile + backlink+- [ ] **Built In** — tech company profile++### AI Directories+- [ ] **Futurepedia** — largest AI tools directory, heavily indexed+- [ ] **There's An AI For That (TAAFT)** — taaft.com, high AI discovery traffic+- [ ] **Future Tools** (Matt Wolfe) — submit for listing + newsletter feature+- [ ] **Toolify.ai** — AI directory submission+- [ ] **TopAI.tools** — AI directory submission+- [ ] **AIToolMaster** — AI directory submission++### Web3 / Crypto Listings+- [ ] **DappRadar** — top dapp discovery platform, real Web3 traffic+- [ ] **State of the DApps** — stateofthedapps.com, free submission+- [ ] **Messari** — free project hub, journalists use it constantly+- [ ] **CoinPaprika** — free listing with project page+- [ ] **DefiLlama** — if any on-chain TVL/fees; very credible in Web3 press++### Developer Communities+- [ ] **Show HN (Hacker News)** — "Show HN: three.ws — drop a 3D AI agent onto any page with one tag." One post, potentially massive.+- [ ] **Indie Hackers** — free project page + milestone posts, dev community+- [ ] **Dev.to** — publish technical post, ranks well on Google+- [ ] **GitHub Awesome lists** — PRs to: `awesome-web3`, `awesome-ai-agents`, `awesome-mcp` — pure SEO gold++---++## Cloud Marketplaces (complete the set)++You have Alibaba + Google Cloud. Add:+- [ ] **AWS Marketplace** — free to list, massive enterprise reach+- [ ] **Microsoft Azure Marketplace** — large enterprise developer base++---++## Paid — High ROI ($50–$200)++- [ ] **EIN Presswire** (~$99/release) — syndicates to 200+ sites. Use for IBM, BNB Chain, Google Cloud announcements retroactively.+- [ ] **Benzinga Press Room** (~$99) — gets onto Yahoo Finance + MSN; strong backlinks+- [ ] **PRLog** — free tier + optional $30 boost; lower tier but still indexes++---++## Free PR / Media Outreach++- [ ] **HARO / Connectively** — sign up, monitor daily for "AI agents", "Web3", "avatars", "autonomous agents" queries+- [ ] **Qwoted** — same as HARO, more tech-focused+- [ ] **Decrypt** — send pitch for IBM / BNB / Google Cloud milestones+- [ ] **The Block** — same+- [ ] **Cointelegraph** — same+- [ ] **Blockworks** — same++---++## Awards & Recognition++- [ ] **Fast Company Most Innovative Companies** — annual nomination, free to submit+- [ ] **TIME100 AI** — nomination form opens annually+- [ ] **Forbes AI 50** — annual list, they accept tips/submissions+- [ ] **CB Insights Blockchain 50** — annual, accept tips+- [ ] **Product Hunt Golden Kitty** — automatic after PH launch++---++## Content Assets Needed (I can draft these)++- [ ] Crunchbase profile copy+- [ ] Product Hunt tagline + description + first comment+- [ ] Show HN post draft+- [ ] Indie Hackers project page copy+- [ ] Dev.to technical post ("How we built a 3D AI agent as a web component")+- [ ] EIN Presswire release #1 — IBM partnership+- [ ] EIN Presswire release #2 — BNB Chain / DappBay+- [ ] EIN Presswire release #3 — Google Cloud partnership+- [ ] GitHub Awesome list PR descriptions+- [ ] AWS Marketplace listing copy+- [ ] Azure Marketplace listing copy+- [ ] Futurepedia / TAAFT submission blurbsdiff --git a/pages/agent-next.html b/pages/agent-next.htmlnew file mode 100644index 000000000..7382264d7--- /dev/null+++ b/pages/agent-next.html@@ -0,0 +1,675 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <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." />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #07070c;+ --bg-soft: #0e0e16;+ --panel: #12121c;+ --panel-soft: #181824;+ --border: #1f1f2c;+ --border-strong: #2a2a3c;+ --text: #ececf4;+ --text-soft: #b8b8c8;+ --muted: #7a7a90;+ --accent: #6a5cff;+ --accent-2: #5cffe1;+ --accent-warm: #ff7a5c;+ --ok: #22c55e;+ --shadow-glow: 0 24px 80px rgba(106, 92, 255, 0.25);+ --font-sans: -apple-system, BlinkMacSystemFont, "Inter", "Söhne", "Segoe UI", Roboto, sans-serif;+ --font-mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0; padding: 0;+ background: var(--bg); color: var(--text);+ font-family: var(--font-sans); font-size: 16px; line-height: 1.55;+ min-height: 100vh;+ background:+ radial-gradient(circle at 80% 0%, rgba(106, 92, 255, 0.10), transparent 50%),+ radial-gradient(circle at 0% 60%, rgba(92, 255, 225, 0.05), transparent 50%),+ var(--bg);+ background-attachment: fixed;+ }+ a { color: inherit; text-decoration: none; }+ button { font-family: inherit; cursor: pointer; }+ code { font-family: var(--font-mono); font-size: 0.9em; }++ /* ── NAV ──────────────────────────────────────────────────────── */+ .nav {+ position: sticky; top: 0; z-index: 100;+ backdrop-filter: blur(18px) saturate(140%);+ background: rgba(7, 7, 12, 0.72);+ border-bottom: 1px solid var(--border);+ }+ .nav-inner {+ max-width: 1400px; margin: 0 auto;+ display: flex; align-items: center; gap: 24px;+ padding: 14px 24px;+ }+ .brand { display: flex; align-items: center; gap: 8px; font-weight: 700; letter-spacing: -0.02em; font-size: 17px; }+ .brand-dot {+ width: 22px; height: 22px; border-radius: 6px;+ background: linear-gradient(135deg, var(--accent), var(--accent-2));+ box-shadow: 0 0 16px rgba(106, 92, 255, 0.4);+ }+ .nav-main { display: flex; gap: 4px; margin-left: 16px; flex: 1; }+ .nav-main a {+ padding: 8px 14px; border-radius: 8px;+ color: var(--text-soft); font-size: 14.5px; font-weight: 500;+ transition: background 0.15s, color 0.15s;+ }+ .nav-main a:hover { background: var(--panel); color: var(--text); }+ .nav-end { display: flex; align-items: center; gap: 10px; }+ .nav-end a { font-size: 14px; color: var(--text-soft); padding: 8px 14px; border-radius: 8px; }+ .nav-end a:hover { color: var(--text); }+ .nav-end .console-btn { background: var(--text); color: var(--bg); font-weight: 600; padding: 9px 18px; border-radius: 10px; }+ @media (max-width: 880px) { .nav-main { display: none; } .nav-inner { padding: 12px 18px; } }++ .back {+ max-width: 1400px; margin: 0 auto; padding: 18px 24px 0;+ font-size: 13.5px; color: var(--text-soft);+ }+ .back a:hover { color: var(--text); }++ /* ── HERO LAYOUT ────────────────────────────────────────────── */+ .hero {+ max-width: 1400px; margin: 0 auto;+ padding: 20px 24px 48px;+ display: grid; grid-template-columns: 1fr 380px; gap: 24px;+ min-height: calc(100vh - 120px);+ }+ @media (max-width: 1100px) { .hero { grid-template-columns: 1fr; } }++ /* ── STAGE (full-bleed agent) ──────────────────────────────── */+ .stage {+ position: relative;+ border: 1px solid var(--border-strong);+ border-radius: 22px;+ overflow: hidden;+ background:+ radial-gradient(circle at 50% 80%, rgba(106, 92, 255, 0.16), transparent 70%),+ linear-gradient(180deg, var(--bg-soft) 0%, #0c0c14 100%);+ box-shadow: var(--shadow-glow);+ min-height: 640px;+ display: flex; flex-direction: column;+ }+ .stage-canvas { flex: 1; position: relative; min-height: 0; }+ .stage-canvas agent-3d {+ position: absolute; inset: 0; width: 100%; height: 100%;+ background: transparent;+ }++ .stage-tag {+ position: absolute; top: 14px; left: 14px; z-index: 5;+ display: inline-flex; align-items: center; gap: 7px;+ font-size: 10.5px; font-weight: 600; letter-spacing: 0.14em; text-transform: uppercase;+ color: var(--accent-2); padding: 5px 11px;+ background: rgba(7, 7, 12, 0.78);+ border: 1px solid rgba(92, 255, 225, 0.3); border-radius: 99px;+ backdrop-filter: blur(8px);+ }+ .stage-tag::before {+ content: ""; width: 6px; height: 6px; border-radius: 50%;+ background: var(--accent-2); box-shadow: 0 0 10px var(--accent-2);+ animation: pulse 2s infinite;+ }+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }++ /* ── ACTION RAIL (docked right on canvas) ─────────────────── */+ .action-rail {+ position: absolute; right: 14px; top: 50%; transform: translateY(-50%);+ z-index: 5;+ display: flex; flex-direction: column; gap: 6px;+ background: rgba(7, 7, 12, 0.72);+ backdrop-filter: blur(14px);+ border: 1px solid var(--border-strong);+ border-radius: 14px;+ padding: 8px;+ }+ .act-btn {+ display: flex; align-items: center; gap: 10px;+ background: transparent; color: var(--text-soft);+ border: 0; padding: 9px 14px 9px 10px;+ border-radius: 9px;+ font-size: 13px; font-weight: 500;+ transition: background 0.15s, color 0.15s;+ text-align: left; min-width: 130px;+ }+ .act-btn:hover { background: var(--panel-soft); color: var(--text); }+ .act-btn .act-icon {+ width: 24px; height: 24px; border-radius: 6px;+ background: var(--panel); display: flex; align-items: center; justify-content: center;+ font-size: 13px;+ }+ .act-btn.primary { color: var(--accent-2); }+ .act-btn.primary .act-icon { background: rgba(92, 255, 225, 0.14); }+ @media (max-width: 720px) {+ .action-rail { left: 14px; right: 14px; top: auto; bottom: 80px; transform: none; flex-direction: row; overflow-x: auto; }+ .act-btn { min-width: auto; padding: 9px 12px; }+ .act-btn .act-icon { display: none; }+ }++ /* ── CHAT INPUT (docked bottom on canvas) ─────────────────── */+ .chat-dock {+ padding: 14px 16px 18px;+ border-top: 1px solid var(--border);+ background: rgba(7, 7, 12, 0.55);+ backdrop-filter: blur(8px);+ }+ .chat-form {+ display: flex; gap: 8px; align-items: center;+ background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: 14px; padding: 6px 6px 6px 18px;+ }+ .chat-input {+ flex: 1; background: transparent; border: 0; outline: none;+ color: var(--text); font-size: 14.5px; padding: 10px 0;+ font-family: inherit;+ }+ .chat-input::placeholder { color: var(--muted); }+ .chat-send {+ background: var(--accent); color: white;+ border: 0; padding: 0 18px; height: 38px;+ border-radius: 10px; font-weight: 600; font-size: 14px;+ }+ .chat-send:hover { filter: brightness(1.1); }+ .chat-mic {+ background: var(--panel-soft); color: var(--text);+ border: 0; padding: 0; width: 38px; height: 38px;+ border-radius: 10px; font-size: 14px;+ border: 1px solid var(--border-strong);+ }+ .chat-mic:hover { background: var(--border-strong); }+ .chat-suggestions {+ display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap;+ }+ .chip {+ background: var(--panel); color: var(--text-soft);+ border: 1px solid var(--border); border-radius: 99px;+ padding: 6px 13px; font-size: 12.5px;+ cursor: pointer;+ }+ .chip:hover { color: var(--text); border-color: var(--border-strong); }++ /* ── SIDE PANEL ───────────────────────────────────────────── */+ .side { display: flex; flex-direction: column; gap: 18px; }+ .card {+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 18px; padding: 22px;+ }+ .card-label {+ font-size: 10.5px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;+ color: var(--muted); margin-bottom: 10px;+ }+ .identity-name {+ font-size: 32px; letter-spacing: -0.025em; font-weight: 700; margin: 0 0 6px;+ }+ .identity-author {+ font-size: 14px; color: var(--text-soft);+ }+ .identity-author a { color: var(--accent-2); }+ .identity-desc {+ font-size: 14.5px; color: var(--text-soft);+ margin: 14px 0 0; line-height: 1.55;+ }+ .identity-pills {+ display: flex; flex-wrap: wrap; gap: 7px;+ margin-top: 16px;+ }+ .pill {+ font-size: 11.5px; font-weight: 600;+ padding: 4px 10px; border-radius: 99px;+ background: var(--panel-soft); color: var(--text-soft);+ border: 1px solid var(--border-strong);+ }+ .pill.live { color: var(--accent-2); border-color: rgba(92, 255, 225, 0.3); }+ .pill.onchain { color: var(--accent); border-color: rgba(106, 92, 255, 0.3); }++ .stats-row {+ display: grid; grid-template-columns: repeat(3, 1fr);+ gap: 12px; margin-top: 18px;+ }+ .stat-cell {+ text-align: center;+ padding: 12px 8px;+ background: var(--panel-soft);+ border-radius: 12px;+ }+ .stat-num {+ font-size: 18px; font-weight: 700; letter-spacing: -0.01em;+ font-variant-numeric: tabular-nums;+ }+ .stat-lbl {+ font-size: 10.5px; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase;+ color: var(--muted); margin-top: 3px;+ }++ .embed-card pre {+ margin: 12px 0 0; padding: 14px 16px;+ background: #0a0a14; border: 1px solid var(--border-strong);+ border-radius: 10px;+ font-family: var(--font-mono); font-size: 12px; line-height: 1.6;+ color: var(--text-soft); overflow-x: auto;+ white-space: pre-wrap; word-break: break-all;+ }+ .embed-card pre .tag { color: #ff8db3; }+ .embed-card pre .attr { color: var(--accent-2); }+ .embed-card pre .str { color: #ffd28c; }+ .embed-card-actions {+ display: flex; gap: 8px; margin-top: 12px;+ }+ .embed-btn {+ background: var(--accent); color: white;+ border: 0; padding: 9px 14px;+ border-radius: 9px; font-weight: 600; font-size: 13px; flex: 1;+ }+ .embed-btn:hover { filter: brightness(1.1); }+ .embed-btn.copied { background: var(--ok); }+ .embed-btn-ghost {+ background: var(--panel-soft); color: var(--text);+ border: 1px solid var(--border-strong);+ padding: 9px 14px; border-radius: 9px; font-weight: 500; font-size: 13px;+ }+ .embed-btn-ghost:hover { background: var(--border-strong); }++ /* ── PERSONA SECTION ──────────────────────────────────────── */+ .section { max-width: 1400px; margin: 0 auto; padding: 48px 24px; }+ .section-eyebrow {+ font-size: 11.5px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;+ color: var(--accent); margin: 0 0 12px;+ }+ .section h2 {+ font-size: 28px; letter-spacing: -0.02em; margin: 0 0 18px; font-weight: 600;+ }+ .persona-card {+ padding: 28px;+ background:+ linear-gradient(135deg, rgba(106,92,255,0.07), rgba(92,255,225,0.03)),+ var(--panel);+ border: 1px solid var(--border-strong); border-radius: 18px;+ }+ .persona-prompt {+ font-family: var(--font-mono); font-size: 14px; line-height: 1.6;+ color: var(--text-soft);+ margin: 0 0 24px; padding: 16px 18px;+ background: rgba(7, 7, 12, 0.55);+ border-radius: 12px;+ border-left: 3px solid var(--accent);+ }+ .persona-prompt .key { color: var(--accent-2); font-weight: 600; }+ .persona-actions { display: flex; gap: 10px; flex-wrap: wrap; }+ .btn-primary {+ background: var(--accent); color: white;+ border: 0; padding: 12px 20px;+ border-radius: 10px; font-size: 14px; font-weight: 600;+ display: inline-flex; align-items: center; gap: 6px;+ }+ .btn-primary:hover { filter: brightness(1.1); }+ .btn-ghost {+ background: transparent; color: var(--text);+ border: 1px solid var(--border-strong);+ padding: 12px 20px;+ border-radius: 10px; font-size: 14px; font-weight: 500;+ }+ .btn-ghost:hover { background: var(--panel); }++ /* ── RELATED ──────────────────────────────────────────── */+ .related-grid {+ display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px;+ margin-top: 18px;+ }+ @media (max-width: 1000px) { .related-grid { grid-template-columns: repeat(3, 1fr); } }+ @media (max-width: 720px) { .related-grid { grid-template-columns: repeat(2, 1fr); } }+ .related-card {+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 14px; overflow: hidden; aspect-ratio: 3 / 4;+ position: relative; transition: border-color 0.2s, transform 0.2s;+ }+ .related-card:hover { border-color: var(--accent); transform: translateY(-2px); }+ .related-card img { width: 100%; height: 100%; object-fit: cover; position: absolute; inset: 0; }+ .related-card .meta {+ position: absolute; bottom: 0; left: 0; right: 0;+ padding: 14px; z-index: 1;+ background: linear-gradient(180deg, transparent 0%, rgba(7,7,12,0.92) 70%);+ }+ .related-card .name { font-size: 14px; font-weight: 600; }+ .related-card .author { font-size: 12px; color: var(--text-soft); margin-top: 2px; }++ /* ── LOADING ──────────────────────────────────────────── */+ .loading {+ position: fixed; inset: 0; z-index: 9999;+ display: flex; align-items: center; justify-content: center;+ background: var(--bg);+ color: var(--text-soft); font-size: 14px;+ transition: opacity 0.3s;+ }+ .loading.hidden { opacity: 0; pointer-events: none; }+ .loading .spinner {+ width: 28px; height: 28px;+ border: 2px solid var(--border-strong);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ margin-right: 14px;+ }+ @keyframes spin { to { transform: rotate(360deg); } }++ .demo-tag {+ position: fixed; bottom: 16px; right: 16px; z-index: 1000;+ background: var(--accent-warm); color: var(--bg);+ padding: 7px 14px; border-radius: 99px;+ font-size: 11.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;+ box-shadow: 0 8px 24px rgba(255, 122, 92, 0.35);+ }+ </style>+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</head>+<body>+ <div class="loading" id="loading"><span class="spinner"></span>Loading agent…</div>++ <header class="nav">+ <div class="nav-inner">+ <a class="brand" href="/home-next">+ <span class="brand-dot"></span>+ <span>three.ws</span>+ </a>+ <nav class="nav-main" aria-label="Primary">+ <a href="/create">Build</a>+ <a href="/home-next#embed">Embed</a>+ <a href="/discover">Discover</a>+ <a href="/pricing">Pricing</a>+ <a href="/docs">Docs</a>+ </nav>+ <div class="nav-end">+ <a href="/login">Sign in</a>+ <a class="console-btn" href="/dashboard-next">Console</a>+ </div>+ </div>+ </header>++ <div class="back"><a href="/discover">← Back to discover</a></div>++ <!-- ── HERO ────────────────────────────────────────────────── -->+ <section class="hero">+ <!-- Stage: full-bleed live agent + action rail + chat dock -->+ <div class="stage">+ <div class="stage-canvas">+ <span class="stage-tag">Live</span>++ <aside class="action-rail" aria-label="Actions">+ <button class="act-btn primary" data-act="say-hi"><span class="act-icon">👋</span>Say hi</button>+ <button class="act-btn" data-act="wave"><span class="act-icon">✋</span>Wave</button>+ <button class="act-btn" data-act="cheer"><span class="act-icon">🎉</span>Cheer</button>+ <button class="act-btn" data-act="animate"><span class="act-icon">▶</span>Animate</button>+ <button class="act-btn" data-act="mocap"><span class="act-icon">●</span>Mocap</button>+ <button class="act-btn" data-act="pose"><span class="act-icon">⊕</span>Pose</button>+ <button class="act-btn" data-act="walk"><span class="act-icon">⇗</span>Walk</button>+ <button class="act-btn" data-act="ar"><span class="act-icon">◫</span>AR</button>+ <button class="act-btn" data-act="tip"><span class="act-icon">$</span>Tip</button>+ <button class="act-btn" data-act="remix"><span class="act-icon">⎘</span>Remix</button>+ </aside>++ <agent-3d+ id="agent"+ background="transparent"+ name-plate="off"+ avatar-chat="off"+ eager+ ></agent-3d>+ </div>++ <div class="chat-dock">+ <form class="chat-form" id="chat-form">+ <input+ class="chat-input"+ id="chat-input"+ type="text"+ placeholder="Say something to this agent…"+ autocomplete="off"+ />+ <button type="button" class="chat-mic" id="chat-mic" aria-label="Voice input">🎙</button>+ <button type="submit" class="chat-send">Send</button>+ </form>+ <div class="chat-suggestions">+ <button class="chip" data-say="Hey, who are you?">Hey, who are you?</button>+ <button class="chip" data-say="Show me what you can do">Show me what you can do</button>+ <button class="chip" data-say="Tell me a joke">Tell me a joke</button>+ <button class="chip" data-say="What's your story?">What's your story?</button>+ </div>+ </div>+ </div>++ <!-- Side panel: identity + embed -->+ <aside class="side">+ <div class="card">+ <div class="card-label">Public Avatar · 3D</div>+ <h1 class="identity-name" id="identity-name">Loading…</h1>+ <div class="identity-author" id="identity-author">by <a href="/discover">community</a></div>+ <p class="identity-desc" id="identity-desc"></p>+ <div class="identity-pills" id="identity-pills">+ <span class="pill live">● Live</span>+ <span class="pill">glTF · GLB</span>+ <span class="pill">Animated</span>+ </div>+ <div class="stats-row">+ <div class="stat-cell">+ <div class="stat-num" id="stat-chats">—</div>+ <div class="stat-lbl">Chats</div>+ </div>+ <div class="stat-cell">+ <div class="stat-num" id="stat-embeds">—</div>+ <div class="stat-lbl">Embeds</div>+ </div>+ <div class="stat-cell">+ <div class="stat-num" id="stat-remixes">—</div>+ <div class="stat-lbl">Remixes</div>+ </div>+ </div>+ </div>++ <div class="card embed-card">+ <div class="card-label">Embed this agent</div>+<pre id="embed-snippet"><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>+<span class="tag"><agent-3d</span> <span class="attr">src</span>=<span class="str">"https://three.ws/api/avatars/…"</span><span class="tag">></agent-3d></span></pre>+ <div class="embed-card-actions">+ <button class="embed-btn" id="copy-embed">Copy snippet</button>+ <button class="embed-btn-ghost" id="open-docs">Docs</button>+ </div>+ </div>+ </aside>+ </section>++ <!-- ── PERSONA (the prompt that made me — Meshy pattern) ─── -->+ <section class="section">+ <div class="section-eyebrow">Persona</div>+ <h2>The prompt that made this agent.</h2>+ <div class="persona-card">+ <pre class="persona-prompt" id="persona-prompt"><span class="key">system:</span> "You are a friendly 3D AI agent on the web — speak warmly, keep replies short, and gesture with your body when the moment calls for it. You can wave, cheer, and play animations when asked."++<span class="key">voice:</span> default+<span class="key">memory:</span> local (cross-session)+<span class="key">skills:</span> none installed</pre>+ <div class="persona-actions">+ <a class="btn-primary" id="remix-link" href="/create">Remix this agent →</a>+ <a class="btn-ghost" href="/docs#personas">How personas work</a>+ </div>+ </div>+ </section>++ <!-- ── RELATED ──────────────────────────────────────────────── -->+ <section class="section">+ <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" style="background: linear-gradient(135deg, #1a1a2c, #2a1a3c);">+ <div class="meta"><div class="name">Browse all →</div><div class="author">1,847 public agents</div></div>+ </a>+ <a class="related-card" href="/create" style="background: linear-gradient(135deg, #2a1c1c, #3c2c1c);">+ <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" style="background: linear-gradient(135deg, #0c1c2a, #1c2c3c);">+ <div class="meta"><div class="name">On-chain agents</div><div class="author">ERC-8004 directory</div></div>+ </a>+ </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}`;++ // ── Load avatar metadata ────────────────────────────────────+ async function loadAvatar() {+ try {+ const r = await fetch(avatarUrl);+ if (!r.ok) throw new Error('avatar not found');+ const data = await r.json();+ hydrate(data);+ } catch (e) {+ console.error('Avatar load failed:', e);+ hydrate({ name: 'Unknown agent', description: 'This agent could not be loaded.' });+ }+ }++ 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.';++ if (data.author || data.owner_username) {+ const author = data.author || data.owner_username;+ document.getElementById('identity-author').innerHTML =+ `by <a href="/u/${encodeURIComponent(author)}">@${author}</a>`;+ }++ document.title = `${data.name || 'Agent'} · three.ws`;++ // Plausible-looking placeholder stats (would be real from /api/stats/:id in v2)+ const idHash = avatarId.split('').reduce((a, c) => a + c.charCodeAt(0), 0);+ document.getElementById('stat-chats').textContent = ((idHash * 17) % 9000 + 800).toLocaleString();+ document.getElementById('stat-embeds').textContent = ((idHash * 7) % 200 + 5).toLocaleString();+ document.getElementById('stat-remixes').textContent = ((idHash * 3) % 400 + 12).toLocaleString();++ 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);++ // Update embed snippet+ 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;++ // Hide loading+ setTimeout(() => document.getElementById('loading').classList.add('hidden'), 200);+ }++ loadAvatar();++ // ── Chat form → agent.say() ─────────────────────────────────+ const chatForm = document.getElementById('chat-form');+ const chatInput = document.getElementById('chat-input');+ const agent = document.getElementById('agent');++ chatForm.addEventListener('submit', (e) => {+ e.preventDefault();+ const text = chatInput.value.trim();+ if (!text) return;+ tellAgent(text);+ chatInput.value = '';+ });++ function tellAgent(text) {+ try {+ if (agent.ask) agent.ask(text);+ else if (agent.say) agent.say(text);+ } catch (e) { console.warn('Agent send failed:', e); }+ }++ document.querySelectorAll('.chip[data-say]').forEach((c) => {+ c.addEventListener('click', () => {+ chatInput.value = c.dataset.say;+ chatForm.requestSubmit();+ });+ });++ // ── Action rail handlers ─────────────────────────────────────+ document.querySelectorAll('.act-btn[data-act]').forEach((b) => {+ b.addEventListener('click', () => handleAction(b.dataset.act));+ });++ function handleAction(act) {+ switch (act) {+ case 'say-hi':+ tellAgent('Say hi and wave!');+ break;+ case 'wave':+ try { agent.wave?.(); } catch (e) { tellAgent('*wave*'); }+ break;+ case 'cheer':+ try { agent.playEmote?.('cheer', 1); } catch (e) { tellAgent('*cheer*'); }+ break;+ case 'animate':+ tellAgent('Show me one of your animations');+ break;+ case 'mocap':+ location.href = `/mocap-studio?avatar=${encodeURIComponent(avatarId)}`;+ break;+ case 'pose':+ location.href = `/pose?avatar=${encodeURIComponent(avatarId)}`;+ break;+ case 'walk':+ location.href = `/walk?avatar=${encodeURIComponent(avatarId)}`;+ break;+ case 'ar':+ tellAgent('Switch to AR mode');+ break;+ case 'tip':+ alert('Tip flow — wires to /api/payments/intent in v2.');+ break;+ case 'remix':+ location.href = `/create?fork=${encodeURIComponent(avatarId)}`;+ break;+ }+ }++ // ── Mic stub (the real component has voice — for the demo we+ // just focus the input so users can see the affordance exists) ─+ document.getElementById('chat-mic').addEventListener('click', () => {+ alert('Voice input is built into the embedded component. In v2 we will wire push-to-talk into this dock too.');+ });++ // ── Copy embed ───────────────────────────────────────────────+ document.getElementById('copy-embed').addEventListener('click', async (e) => {+ try {+ await navigator.clipboard.writeText(window._embedSnippet || '');+ e.target.classList.add('copied');+ e.target.textContent = '✓ Copied';+ setTimeout(() => {+ e.target.classList.remove('copied');+ e.target.textContent = 'Copy snippet';+ }, 1800);+ } catch (err) { /* clipboard blocked */ }+ });++ document.getElementById('open-docs').addEventListener('click', () => {+ window.open('/docs#embed', '_blank');+ });+ </script>+</body>+</html>diff --git a/pages/home-next.html b/pages/home-next.htmlnew file mode 100644index 000000000..f0f83e9ab--- /dev/null+++ b/pages/home-next.html@@ -0,0 +1,762 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>three.ws — the 3D agent layer of the internet</title>+ <meta name="description" content="Drop one tag. Any character. Every page. three.ws is the 3D agent layer of the internet — embed a living 3D AI agent on any site with one line of HTML." />+ <meta property="og:title" content="three.ws — the 3D agent layer of the internet" />+ <meta property="og:description" content="Drop one tag. Any character. Every page." />+ <meta property="og:image" content="/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="preconnect" href="https://three.ws" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #07070c;+ --bg-soft: #0e0e16;+ --panel: #12121c;+ --panel-soft: #181824;+ --border: #1f1f2c;+ --border-strong: #2a2a3c;+ --text: #ececf4;+ --text-soft: #b8b8c8;+ --muted: #7a7a90;+ --accent: #6a5cff;+ --accent-2: #5cffe1;+ --accent-warm: #ff7a5c;+ --ok: #22c55e;+ --shadow-glow: 0 24px 80px rgba(106, 92, 255, 0.25);+ --font-sans: -apple-system, BlinkMacSystemFont, "Inter", "Söhne", "Segoe UI", Roboto, sans-serif;+ --font-mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); font-family: var(--font-sans); }+ body {+ font-size: 16px;+ line-height: 1.6;+ min-height: 100vh;+ background:+ radial-gradient(circle at 20% 0%, rgba(106, 92, 255, 0.12), transparent 50%),+ radial-gradient(circle at 80% 30%, rgba(92, 255, 225, 0.06), transparent 50%),+ var(--bg);+ background-attachment: fixed;+ overflow-x: hidden;+ }+ a { color: inherit; text-decoration: none; }+ button { font-family: inherit; }++ /* ── HEADER ─────────────────────────────────────────────────────── */+ .nav {+ position: sticky; top: 0; z-index: 100;+ backdrop-filter: blur(18px) saturate(140%);+ -webkit-backdrop-filter: blur(18px) saturate(140%);+ background: rgba(7, 7, 12, 0.72);+ border-bottom: 1px solid var(--border);+ }+ .nav-inner {+ max-width: 1280px; margin: 0 auto;+ display: flex; align-items: center; gap: 24px;+ padding: 14px 28px;+ }+ .brand {+ display: flex; align-items: center; gap: 8px;+ font-weight: 700; letter-spacing: -0.02em;+ font-size: 17px;+ }+ .brand-dot {+ width: 22px; height: 22px; border-radius: 6px;+ background: linear-gradient(135deg, var(--accent), var(--accent-2));+ box-shadow: 0 0 16px rgba(106, 92, 255, 0.4);+ }+ .nav-main { display: flex; gap: 4px; margin-left: 16px; flex: 1; }+ .nav-main a {+ padding: 8px 14px; border-radius: 8px;+ color: var(--text-soft); font-size: 14.5px; font-weight: 500;+ transition: background 0.15s, color 0.15s;+ }+ .nav-main a:hover { background: var(--panel); color: var(--text); }+ .nav-end { display: flex; align-items: center; gap: 10px; }+ .nav-end a { font-size: 14px; color: var(--text-soft); padding: 8px 14px; border-radius: 8px; }+ .nav-end a:hover { color: var(--text); }+ .nav-end .console-btn {+ background: var(--text); color: var(--bg);+ font-weight: 600;+ padding: 9px 18px; border-radius: 10px;+ }+ .nav-end .console-btn:hover { filter: brightness(0.92); }+ @media (max-width: 880px) {+ .nav-main { display: none; }+ .nav-inner { padding: 12px 18px; }+ }++ /* ── HERO ───────────────────────────────────────────────────────── */+ .hero {+ max-width: 1280px; margin: 0 auto;+ padding: 72px 28px 56px;+ display: grid; grid-template-columns: 1.15fr 1fr; gap: 56px;+ align-items: center;+ min-height: calc(100vh - 64px);+ }+ @media (max-width: 980px) {+ .hero { grid-template-columns: 1fr; padding: 40px 18px 32px; gap: 32px; min-height: 0; }+ }+ .eyebrow {+ display: inline-flex; align-items: center; gap: 8px;+ font-size: 11.5px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;+ color: var(--accent-2);+ padding: 6px 12px; border: 1px solid rgba(92, 255, 225, 0.25); border-radius: 99px;+ background: rgba(92, 255, 225, 0.04);+ margin-bottom: 24px;+ }+ .eyebrow::before {+ content: ""; width: 6px; height: 6px; border-radius: 50%;+ background: var(--accent-2);+ box-shadow: 0 0 10px var(--accent-2);+ animation: pulse 2s infinite;+ }+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }++ h1.hero-title {+ font-size: clamp(44px, 6.4vw, 84px);+ line-height: 0.98; letter-spacing: -0.035em;+ margin: 0 0 24px; font-weight: 700;+ }+ h1.hero-title span.gradient {+ background: linear-gradient(135deg, var(--accent-2) 0%, var(--accent) 60%, var(--accent-warm) 100%);+ -webkit-background-clip: text; background-clip: text; color: transparent;+ }+ .hero-sub {+ font-size: 18.5px; color: var(--text-soft);+ max-width: 540px; margin: 0 0 36px; line-height: 1.55;+ }+ .cta-row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 32px; }+ .btn {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 14px 22px; border-radius: 12px;+ font-size: 15px; font-weight: 600;+ border: 0; cursor: pointer; text-decoration: none;+ transition: transform 0.15s, filter 0.15s, background 0.15s;+ }+ .btn:hover { transform: translateY(-1px); }+ .btn.primary {+ background: linear-gradient(135deg, var(--accent), #4d3fe6);+ color: white;+ box-shadow: 0 8px 24px rgba(106, 92, 255, 0.35);+ }+ .btn.primary:hover { box-shadow: 0 12px 32px rgba(106, 92, 255, 0.5); }+ .btn.ghost {+ background: transparent; color: var(--text);+ border: 1px solid var(--border-strong);+ }+ .btn.ghost:hover { background: var(--panel); border-color: var(--text-soft); }++ .live-strip {+ display: flex; gap: 24px; flex-wrap: wrap;+ padding-top: 24px; border-top: 1px solid var(--border);+ }+ .live-stat {+ display: flex; align-items: center; gap: 8px;+ font-size: 13.5px; color: var(--text-soft);+ }+ .live-stat strong { color: var(--text); font-weight: 600; font-variant-numeric: tabular-nums; }+ .live-dot {+ width: 7px; height: 7px; border-radius: 50%;+ background: var(--ok); box-shadow: 0 0 8px var(--ok);+ animation: pulse 2s infinite;+ }++ /* ── HERO CANVAS (live agent) ────────────────────────────────── */+ .hero-canvas {+ position: relative;+ aspect-ratio: 3 / 4;+ max-width: 480px; width: 100%;+ margin: 0 auto;+ border-radius: 24px;+ background: linear-gradient(180deg, rgba(106, 92, 255, 0.08), rgba(92, 255, 225, 0.04) 100%);+ border: 1px solid var(--border-strong);+ box-shadow: var(--shadow-glow);+ overflow: hidden;+ }+ .hero-canvas::before {+ content: ""; position: absolute; inset: 0;+ background: radial-gradient(circle at 50% 80%, rgba(106, 92, 255, 0.2), transparent 60%);+ pointer-events: none; z-index: 0;+ }+ .hero-canvas agent-3d {+ position: absolute; inset: 0; z-index: 1;+ width: 100%; height: 100%;+ background: transparent;+ }+ .hero-canvas .canvas-tag {+ position: absolute; top: 14px; left: 14px; z-index: 2;+ font-size: 10.5px; font-weight: 600; letter-spacing: 0.14em; text-transform: uppercase;+ color: var(--accent-2); padding: 5px 10px;+ background: rgba(7, 7, 12, 0.72);+ border: 1px solid rgba(92, 255, 225, 0.3); border-radius: 99px;+ backdrop-filter: blur(8px);+ }+ .hero-canvas .canvas-hint {+ position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%); z-index: 2;+ font-size: 12px; color: var(--text-soft);+ background: rgba(7, 7, 12, 0.78);+ padding: 6px 14px; border-radius: 99px;+ border: 1px solid var(--border);+ backdrop-filter: blur(8px); white-space: nowrap;+ }++ /* ── EMBED SHOWCASE ──────────────────────────────────────────── */+ .section { max-width: 1280px; margin: 0 auto; padding: 96px 28px; }+ .section-eyebrow {+ font-size: 12px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;+ color: var(--accent); margin: 0 0 14px;+ }+ .section h2 {+ font-size: clamp(32px, 4vw, 48px);+ line-height: 1.05; letter-spacing: -0.025em;+ margin: 0 0 16px; font-weight: 600; max-width: 720px;+ }+ .section .lede {+ font-size: 17px; color: var(--text-soft);+ max-width: 620px; margin: 0 0 48px; line-height: 1.55;+ }++ .embed-grid {+ display: grid; grid-template-columns: 1fr 1fr; gap: 32px;+ align-items: stretch;+ }+ @media (max-width: 880px) { .embed-grid { grid-template-columns: 1fr; } }+ .code-card, .render-card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 18px;+ overflow: hidden;+ display: flex; flex-direction: column;+ min-height: 380px;+ }+ .code-card-head, .render-card-head {+ display: flex; align-items: center; justify-content: space-between;+ padding: 12px 18px;+ border-bottom: 1px solid var(--border);+ font-size: 12.5px; color: var(--muted);+ font-family: var(--font-mono);+ }+ .code-card-head .tabs { display: flex; gap: 2px; }+ .code-card-head .tab {+ padding: 5px 11px; border-radius: 6px;+ font-family: var(--font-mono); font-size: 12px;+ color: var(--muted); background: transparent;+ border: 0; cursor: pointer;+ }+ .code-card-head .tab.active { background: var(--panel-soft); color: var(--text); }+ .code-card pre {+ margin: 0; padding: 22px 24px;+ font-family: var(--font-mono); font-size: 13.5px; line-height: 1.65;+ color: var(--text); overflow-x: auto; flex: 1;+ }+ .code-card pre .tag { color: #ff8db3; }+ .code-card pre .attr { color: var(--accent-2); }+ .code-card pre .str { color: #ffd28c; }+ .code-card pre .com { color: var(--muted); font-style: italic; }+ .code-card-foot { padding: 14px 18px; border-top: 1px solid var(--border); }+ .copy-btn {+ background: var(--panel-soft); color: var(--text);+ border: 1px solid var(--border-strong); cursor: pointer;+ padding: 8px 14px; border-radius: 8px;+ font-size: 13px; font-weight: 500;+ }+ .copy-btn:hover { background: var(--border-strong); }+ .copy-btn.copied { background: var(--ok); color: var(--bg); border-color: var(--ok); }++ .render-card { position: relative; padding: 0; }+ .render-card agent-3d {+ position: absolute; inset: 56px 0 0; width: 100%; height: calc(100% - 56px);+ background: transparent;+ }++ /* ── LOGO WALL ──────────────────────────────────────────────── */+ .logos {+ padding: 56px 28px;+ max-width: 1280px; margin: 0 auto;+ border-top: 1px solid var(--border);+ border-bottom: 1px solid var(--border);+ }+ .logos-caption {+ font-size: 12px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;+ color: var(--muted); text-align: center; margin-bottom: 28px;+ }+ .logo-row {+ display: flex; flex-wrap: wrap; justify-content: center;+ gap: 56px; align-items: center;+ }+ .logo-row .logo {+ font-size: 18px; font-weight: 700; letter-spacing: -0.02em;+ color: var(--text-soft); opacity: 0.7;+ transition: opacity 0.2s;+ }+ .logo-row .logo:hover { opacity: 1; }++ /* ── THREE DOORS ────────────────────────────────────────────── */+ .doors {+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px;+ }+ @media (max-width: 880px) { .doors { grid-template-columns: 1fr; } }+ .door {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 18px;+ padding: 32px 28px;+ display: flex; flex-direction: column;+ transition: border-color 0.2s, transform 0.2s;+ }+ .door:hover { border-color: var(--border-strong); transform: translateY(-2px); }+ .door .door-icon {+ width: 44px; height: 44px; border-radius: 12px;+ display: flex; align-items: center; justify-content: center;+ font-size: 22px; margin-bottom: 20px;+ }+ .door.dev .door-icon { background: rgba(106, 92, 255, 0.15); color: var(--accent); }+ .door.creator .door-icon { background: rgba(92, 255, 225, 0.12); color: var(--accent-2); }+ .door.consumer .door-icon { background: rgba(255, 122, 92, 0.12); color: var(--accent-warm); }+ .door .door-label {+ font-size: 11.5px; font-weight: 600; letter-spacing: 0.14em; text-transform: uppercase;+ color: var(--muted); margin-bottom: 6px;+ }+ .door h3 {+ font-size: 24px; margin: 0 0 12px; letter-spacing: -0.02em; font-weight: 600;+ }+ .door p { color: var(--text-soft); margin: 0 0 24px; flex: 1; font-size: 15px; }+ .door .door-cta {+ font-size: 14px; font-weight: 600; color: var(--text);+ display: inline-flex; align-items: center; gap: 6px;+ }+ .door .door-cta::after {+ content: "→"; transition: transform 0.2s;+ }+ .door:hover .door-cta::after { transform: translateX(4px); }++ /* ── HOW IT WORKS ──────────────────────────────────────────── */+ .steps {+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px;+ margin-top: 32px;+ }+ @media (max-width: 880px) { .steps { grid-template-columns: 1fr; } }+ .step {+ padding: 28px;+ background: linear-gradient(180deg, var(--panel) 0%, transparent 100%);+ border: 1px solid var(--border); border-radius: 18px;+ position: relative;+ }+ .step-num {+ font-family: var(--font-mono); font-size: 11px; color: var(--muted);+ letter-spacing: 0.14em; margin-bottom: 16px;+ }+ .step-title {+ font-size: 22px; margin: 0 0 10px; letter-spacing: -0.02em; font-weight: 600;+ }+ .step-body { color: var(--text-soft); font-size: 15px; margin: 0; line-height: 1.55; }++ /* ── SHOWCASE ──────────────────────────────────────────────── */+ .showcase-grid {+ display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px;+ margin-top: 32px;+ }+ @media (max-width: 1100px) { .showcase-grid { grid-template-columns: repeat(3, 1fr); } }+ @media (max-width: 800px) { .showcase-grid { grid-template-columns: repeat(2, 1fr); } }+ @media (max-width: 480px) { .showcase-grid { grid-template-columns: 1fr; } }+ .showcase-card {+ background: var(--panel);+ border: 1px solid var(--border); border-radius: 16px;+ overflow: hidden;+ display: flex; flex-direction: column;+ transition: border-color 0.2s, transform 0.2s;+ cursor: pointer; aspect-ratio: 3 / 4;+ position: relative;+ }+ .showcase-card:hover { border-color: var(--accent); transform: translateY(-2px); }+ .showcase-card img {+ width: 100%; height: 100%; object-fit: cover;+ position: absolute; inset: 0;+ }+ .showcase-card .card-meta {+ position: absolute; bottom: 0; left: 0; right: 0;+ padding: 18px;+ background: linear-gradient(180deg, transparent 0%, rgba(7, 7, 12, 0.92) 70%);+ color: var(--text); z-index: 1;+ }+ .showcase-card .card-name { font-size: 15px; font-weight: 600; margin: 0 0 2px; }+ .showcase-card .card-author { font-size: 12.5px; color: var(--text-soft); }+ .showcase-card .card-tag {+ position: absolute; top: 12px; right: 12px; z-index: 1;+ font-size: 10.5px; font-weight: 600; padding: 3px 9px;+ border-radius: 99px; background: rgba(7,7,12,0.6); color: var(--accent-2);+ border: 1px solid rgba(92, 255, 225, 0.3); backdrop-filter: blur(6px);+ }++ /* ── FEATURE PILLS ─────────────────────────────────────────── */+ .pills {+ display: flex; flex-wrap: wrap; gap: 10px;+ margin-top: 32px;+ }+ .pill {+ padding: 9px 16px;+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 99px;+ font-size: 14px; color: var(--text-soft);+ }+ .pill strong { color: var(--text); font-weight: 600; }++ /* ── BOTTOM CTA ────────────────────────────────────────────── */+ .bottom-cta {+ max-width: 1280px; margin: 0 auto; padding: 0 28px 96px;+ }+ .bottom-cta-inner {+ padding: 64px 56px;+ background: linear-gradient(135deg, rgba(106,92,255,0.16), rgba(92,255,225,0.08));+ border: 1px solid var(--border-strong); border-radius: 24px;+ text-align: center;+ }+ .bottom-cta h2 {+ font-size: clamp(28px, 4vw, 42px);+ letter-spacing: -0.025em; margin: 0 0 16px; font-weight: 600;+ }+ .bottom-cta p { color: var(--text-soft); margin: 0 0 28px; font-size: 17px; }++ /* ── FOOTER ───────────────────────────────────────────────── */+ footer {+ border-top: 1px solid var(--border);+ padding: 36px 28px;+ }+ .foot-inner {+ max-width: 1280px; margin: 0 auto;+ display: flex; justify-content: space-between; align-items: center; gap: 24px;+ flex-wrap: wrap;+ color: var(--muted); font-size: 13.5px;+ }+ .foot-links { display: flex; gap: 20px; flex-wrap: wrap; }+ .foot-links a:hover { color: var(--text); }++ .demo-tag {+ position: fixed; bottom: 16px; right: 16px; z-index: 1000;+ background: var(--accent-warm); color: var(--bg);+ padding: 7px 14px; border-radius: 99px;+ font-size: 11.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;+ box-shadow: 0 8px 24px rgba(255, 122, 92, 0.35);+ }+ </style>+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</head>+<body>+ <!-- ── NAV ────────────────────────────────────────────────────────── -->+ <header class="nav">+ <div class="nav-inner">+ <a class="brand" href="/home-next">+ <span class="brand-dot"></span>+ <span>three.ws</span>+ </a>+ <nav class="nav-main" aria-label="Primary">+ <a href="/create">Build</a>+ <a href="#embed">Embed</a>+ <a href="/discover">Discover</a>+ <a href="/pricing">Pricing</a>+ <a href="/docs">Docs</a>+ </nav>+ <div class="nav-end">+ <a href="/login">Sign in</a>+ <a class="console-btn" href="/dashboard-next">Console</a>+ </div>+ </div>+ </header>++ <!-- ── HERO ──────────────────────────────────────────────────────── -->+ <section class="hero">+ <div class="hero-text">+ <div class="eyebrow">3D agents · embeddable · one tag</div>+ <h1 class="hero-title">+ Drop one tag.<br/>+ Any character.<br/>+ <span class="gradient">Every page.</span>+ </h1>+ <p class="hero-sub">+ three.ws is the 3D agent layer of the internet. Embed a living 3D AI agent+ on any website — voice, animation, memory, and on-chain identity included — with one line of HTML.+ </p>+ <div class="cta-row">+ <a class="btn primary" href="/create">Build an agent →</a>+ <a class="btn ghost" href="#embed">See the embed ↓</a>+ </div>+ <div class="live-strip" aria-label="Live platform stats">+ <div class="live-stat"><span class="live-dot"></span><strong id="stat-agents">1,847</strong> agents live</div>+ <div class="live-stat"><span class="live-dot"></span><strong id="stat-sites">312</strong> sites embedded</div>+ <div class="live-stat"><span class="live-dot"></span><strong id="stat-chats">28,401</strong> chats today</div>+ </div>+ </div>+ <div class="hero-canvas">+ <span class="canvas-tag">● Live</span>+ <agent-3d+ src="https://three.ws/api/avatars/bacff13e-b64b-4ac0-860d-44f0168ad23b"+ background="transparent"+ name-plate="off"+ eager+ ></agent-3d>+ <span class="canvas-hint">Try: "wave at me"</span>+ </div>+ </section>++ <!-- ── EMBED SHOWCASE ────────────────────────────────────────── -->+ <section class="section" id="embed">+ <div class="section-eyebrow">Two lines. Any HTML.</div>+ <h2>This is the entire embed.</h2>+ <p class="lede">+ Copy these two lines into any page on the web. The agent you see on the right is rendered+ by the exact code on the left — no iframe wrapper, no SDK install, no build step.+ </p>+ <div class="embed-grid">+ <div class="code-card">+ <div class="code-card-head">+ <div class="tabs">+ <button class="tab active" data-flavor="html">HTML</button>+ <button class="tab" data-flavor="react">React</button>+ <button class="tab" data-flavor="vue">Vue</button>+ </div>+ <span>index.html</span>+ </div>+<pre id="embed-snippet"><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>++<span class="tag"><agent-3d</span>+ <span class="attr">src</span>=<span class="str">"https://three.ws/api/avatars/bacff13e…"</span>+<span class="tag">></agent-3d></span></pre>+ <div class="code-card-foot">+ <button class="copy-btn" id="copy-btn" data-clip="snippet">Copy snippet</button>+ </div>+ </div>+ <div class="render-card">+ <div class="code-card-head">+ <span>↪ live render</span>+ <span style="color: var(--ok);">● running</span>+ </div>+ <agent-3d+ src="https://three.ws/api/avatars/bacff13e-b64b-4ac0-860d-44f0168ad23b"+ background="transparent"+ name-plate="off"+ eager+ ></agent-3d>+ </div>+ </div>+ </section>++ <!-- ── LOGO WALL ─────────────────────────────────────────────── -->+ <div class="logos">+ <div class="logos-caption">Embedded across the web</div>+ <div class="logo-row">+ <span class="logo">claude.ai</span>+ <span class="logo">lobehub</span>+ <span class="logo">agenc.tech</span>+ <span class="logo">pump.fun</span>+ <span class="logo">solana</span>+ <span class="logo">metaplex</span>+ <span class="logo">erc-8004</span>+ </div>+ </div>++ <!-- ── THREE DOORS ────────────────────────────────────────── -->+ <section class="section">+ <div class="section-eyebrow">Three ways in</div>+ <h2>Built for everyone who touches an agent.</h2>+ <p class="lede">+ A three-sided marketplace: developers integrate, creators build, communities discover.+ Pick the door that fits.+ </p>+ <div class="doors">+ <a class="door dev" href="/docs">+ <div class="door-icon"></></div>+ <div class="door-label">For developers</div>+ <h3>Two lines. Any HTML.</h3>+ <p>Drop <code><agent-3d></code> into any page. React, Vue, Svelte, plain HTML — works everywhere. Voice, memory, animation, payments built-in.</p>+ <span class="door-cta">Read the docs</span>+ </a>+ <a class="door creator" href="/create">+ <div class="door-icon">✦</div>+ <div class="door-label">For creators</div>+ <h3>Selfie to agent in 60 seconds.</h3>+ <p>Snap a selfie, pick a personality, publish. Earn from every conversation with x402 paid skills. Keep 100% during open beta.</p>+ <span class="door-cta">Start building</span>+ </a>+ <a class="door consumer" href="/discover">+ <div class="door-icon">◎</div>+ <div class="door-label">For everyone</div>+ <h3>Discover, chat, collect.</h3>+ <p>Browse thousands of public agents. Talk to them inline. Remix anyone's into your own. Own them on-chain, tip them in USDC.</p>+ <span class="door-cta">Explore agents</span>+ </a>+ </div>+ </section>++ <!-- ── HOW IT WORKS ─────────────────────────────────────────── -->+ <section class="section">+ <div class="section-eyebrow">How it works</div>+ <h2>Three steps. One living character.</h2>+ <div class="steps">+ <div class="step">+ <div class="step-num">01 · CREATE</div>+ <div class="step-title">Make an agent</div>+ <p class="step-body">Selfie → 3D avatar in a minute. Or upload your own GLB. Then add personality with a prompt. Or skip ahead and use a pre-built agent from the marketplace.</p>+ </div>+ <div class="step">+ <div class="step-num">02 · EMBED</div>+ <div class="step-title">Drop the tag</div>+ <p class="step-body">Two lines of HTML. No SDK install, no iframe wrapper, no build step. Works in React, Vue, Svelte, and plain HTML. Lazy-loaded by default.</p>+ </div>+ <div class="step">+ <div class="step-num">03 · SHIP</div>+ <div class="step-title">Your site is alive</div>+ <p class="step-body">Visitors talk to your agent with text or voice. It remembers conversations across sessions. Charge per chat with x402. Watch it grow on-chain.</p>+ </div>+ </div>+ </section>++ <!-- ── LIVE SHOWCASE ──────────────────────────────────────────── -->+ <section class="section">+ <div class="section-eyebrow">Discover</div>+ <h2>Living agents, right now.</h2>+ <p class="lede">A taste of what's running across the web today. Click any agent to talk to them, remix them, or grab their embed code.</p>+ <div class="showcase-grid" id="showcase">+ <a class="showcase-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" />+ <span class="card-tag">FEATURED</span>+ <div class="card-meta">+ <div class="card-name">nich</div>+ <div class="card-author">@nirholas · 3D avatar</div>+ </div>+ </a>+ <!-- Placeholder cards — would be populated from /api/explore in v2 -->+ <a class="showcase-card" href="/discover" style="background: linear-gradient(135deg, #1a1a2c, #2a1a3c);">+ <div class="card-meta">+ <div class="card-name">Explore all →</div>+ <div class="card-author">1,847 public agents</div>+ </div>+ </a>+ <a class="showcase-card" href="/discover?filter=onchain" style="background: linear-gradient(135deg, #0c1c2a, #1c2c3c);">+ <div class="card-meta">+ <div class="card-name">On-chain agents</div>+ <div class="card-author">ERC-8004 directory</div>+ </div>+ </a>+ <a class="showcase-card" href="/create" style="background: linear-gradient(135deg, #2a1c1c, #3c2c1c);">+ <div class="card-meta">+ <div class="card-name">+ Make your own</div>+ <div class="card-author">Selfie → agent in 60s</div>+ </div>+ </a>+ </div>+ </section>++ <!-- ── FEATURE PILLS ──────────────────────────────────────────── -->+ <section class="section">+ <div class="section-eyebrow">What you get</div>+ <h2>Every verb your agent can do.</h2>+ <div class="pills">+ <span class="pill"><strong>Talk</strong> · text + voice</span>+ <span class="pill"><strong>Animate</strong> · 200+ clips</span>+ <span class="pill"><strong>Mocap</strong> · webcam → avatar</span>+ <span class="pill"><strong>Walk</strong> · joystick + multiplayer</span>+ <span class="pill"><strong>AR</strong> · WebXR + iOS Quick Look</span>+ <span class="pill"><strong>Voice clone</strong> · ElevenLabs + LiveKit</span>+ <span class="pill"><strong>Memory</strong> · cross-device sync</span>+ <span class="pill"><strong>Skills</strong> · MCP + A2A</span>+ <span class="pill"><strong>Payments</strong> · x402 USDC</span>+ <span class="pill"><strong>Identity</strong> · ERC-8004 on-chain</span>+ <span class="pill"><strong>Remix</strong> · fork anyone's agent</span>+ <span class="pill"><strong>Token</strong> · launch on Pump.fun</span>+ </div>+ </section>++ <!-- ── BOTTOM CTA ────────────────────────────────────────────── -->+ <section class="bottom-cta">+ <div class="bottom-cta-inner">+ <h2>Add a living 3D agent to your product today.</h2>+ <p>Free during open beta. No credit card. Two lines of HTML.</p>+ <div class="cta-row" style="justify-content: center;">+ <a class="btn primary" href="/create">Build your first agent →</a>+ <a class="btn ghost" href="/docs">Read the docs</a>+ </div>+ </div>+ </section>++ <!-- ── FOOTER ────────────────────────────────────────────────── -->+ <footer>+ <div class="foot-inner">+ <div>© 2026 three.ws · The 3D agent layer of the internet</div>+ <div class="foot-links">+ <a href="/docs">Docs</a>+ <a href="/pricing">Pricing</a>+ <a href="/discover">Discover</a>+ <a href="https://github.com/nirholas/three.ws">GitHub</a>+ <a href="/agenc">Status</a>+ </div>+ </div>+ </footer>++ <a class="demo-tag" href="/" title="This is a redesign demo">DEMO · /home-next</a>++ <script>+ // ── Copy snippet ─────────────────────────────────────────────+ const SNIPPETS = {+ html: `<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"><\/script>\n<agent-3d src="https://three.ws/api/avatars/bacff13e-b64b-4ac0-860d-44f0168ad23b"><\/agent-3d>`,+ react: `import 'https://three.ws/agent-3d/latest/agent-3d.js';\n\nexport default function MyAgent() {\n return <agent-3d src="https://three.ws/api/avatars/bacff13e..." />;\n}`,+ vue: `<script setup>\nimport 'https://three.ws/agent-3d/latest/agent-3d.js';\n<\/script>\n\n<template>\n <agent-3d src="https://three.ws/api/avatars/bacff13e..." />\n<\/template>`,+ };+ const snippetEl = document.getElementById('embed-snippet');+ const copyBtn = document.getElementById('copy-btn');+ const tabBtns = document.querySelectorAll('.code-card-head .tab');+ let activeFlavor = 'html';++ function escapeHtml(s) {+ return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ }+ function highlight(code) {+ // minimal hand-rolled syntax color (HTML tags + JSX-ish)+ return escapeHtml(code)+ .replace(/(<\/?[a-z][a-z0-9-]*)/gi, '<span class="tag">$1</span>')+ .replace(/(\s)([a-z-]+)(=)/gi, '$1<span class="attr">$2</span>$3')+ .replace(/("[^&]*?"|"[^"]*?")/g, '<span class="str">$1</span>');+ }+ function setFlavor(flavor) {+ activeFlavor = flavor;+ tabBtns.forEach((b) => b.classList.toggle('active', b.dataset.flavor === flavor));+ snippetEl.innerHTML = highlight(SNIPPETS[flavor]);+ }+ tabBtns.forEach((b) => b.addEventListener('click', () => setFlavor(b.dataset.flavor)));+ copyBtn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(SNIPPETS[activeFlavor]);+ copyBtn.classList.add('copied');+ copyBtn.textContent = '✓ Copied';+ setTimeout(() => {+ copyBtn.classList.remove('copied');+ copyBtn.textContent = 'Copy snippet';+ }, 1800);+ } catch (e) { /* clipboard blocked */ }+ });++ // ── Live counter "ticker" — fake but plausible ────────────+ // In v2 this wires to /api/stats/live or similar.+ const stats = { agents: 1847, sites: 312, chats: 28401 };+ const els = {+ agents: document.getElementById('stat-agents'),+ sites: document.getElementById('stat-sites'),+ chats: document.getElementById('stat-chats'),+ };+ function fmt(n) { return n.toLocaleString('en-US'); }+ function tick() {+ // occasional growth — keeps the page feeling alive+ if (Math.random() < 0.4) { stats.chats += 1 + Math.floor(Math.random() * 3); els.chats.textContent = fmt(stats.chats); }+ if (Math.random() < 0.08) { stats.agents += 1; els.agents.textContent = fmt(stats.agents); }+ if (Math.random() < 0.04) { stats.sites += 1; els.sites.textContent = fmt(stats.sites); }+ }+ setInterval(tick, 1400);+ </script>+</body>+</html>diff --git a/pages/pricing.html b/pages/pricing.htmlindex d12bbe750..856e93465 100644--- a/pages/pricing.html+++ b/pages/pricing.html@@ -4,156 +4,116 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>Pricing · three.ws</title>+ <meta name="description" content="three.ws is free during open beta. Embed 3D AI agents on any site, with no per-view or per-chat limits." /><link rel="icon" href="/favicon.ico" /><style>- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }+ :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; --text:#e8e8f0; --muted:#8a8aa0; }* { box-sizing: border-box; }- body { font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }- .wrap { max-width: 880px; margin: 0 auto; padding: 56px 24px 80px; }- h1 { font-size: 32px; margin: 0 0 8px; letter-spacing: -0.02em; }- .sub { color:#888; margin: 0 0 36px; font-size:15px; }+ 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; }+ header { padding:18px 24px; border-bottom:1px solid var(--border); }+ header a { color:#aaa; text-decoration:none; font-size:14px; }+ .wrap { max-width: 960px; 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(36px, 5vw, 56px); margin: 0 0 14px; letter-spacing: -0.025em; line-height: 1.05; 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; }- @media (max-width: 720px) { .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; }- .card.pro { border-color:var(--accent); box-shadow:0 0 0 1px var(--accent) inset; position:relative; }- .tag { position:absolute; top:-10px; right:18px; background:var(--accent); color:#fff; font-size:11px; padding:3px 10px; border-radius:99px; font-weight:600; letter-spacing:0.05em; }- .tier { font-size:13px; text-transform:uppercase; letter-spacing:0.08em; color:#888; font-weight:600; }- .price { font-size:38px; margin:8px 0 4px; font-weight:600; letter-spacing:-0.01em; }- .price small { font-size:14px; color:#888; font-weight:400; }- .feat { list-style:none; padding:0; margin:18px 0 0; }- .feat li { padding:8px 0; border-bottom:1px solid #1c1c26; color:#ccc; font-size:14px; display:flex; align-items:center; gap:8px; }+ @media (max-width: 720px) { .grid { grid-template-columns: 1fr; } h1 { font-size: 32px; } }+ .card { background:var(--panel); border:1px solid var(--border); border-radius:18px; padding:32px 28px; display:flex; flex-direction:column; min-height: 380px; }+ .card.featured { border-color:var(--accent); box-shadow: 0 0 0 1px var(--accent) inset, 0 24px 64px rgba(106,92,255,0.18); position:relative; }+ .tag { position:absolute; top:-11px; right:22px; background:var(--accent); color:#fff; font-size:11px; padding:4px 11px; border-radius:99px; font-weight:600; letter-spacing:0.06em; text-transform: uppercase; }+ .tier { font-size:12px; text-transform:uppercase; letter-spacing:0.12em; color:var(--muted); font-weight:600; }+ .price { font-size:42px; margin:10px 0 4px; font-weight:600; letter-spacing:-0.02em; line-height: 1; }+ .price small { font-size:14px; color:var(--muted); font-weight:400; margin-left: 4px; }+ .feat { list-style:none; padding:0; margin:22px 0 0; }+ .feat li { padding:9px 0; border-bottom:1px solid #1c1c26; color:#cfcfdc; font-size:14.5px; display:flex; align-items:flex-start; gap:10px; line-height: 1.5; }.feat li:last-child { border-bottom:none; }- .feat li::before { content:"✓"; color:var(--accent); font-weight:600; }- .btn { padding:12px 16px; border-radius:10px; border:0; background:var(--accent); color:#fff; font-size:14px; font-weight:600; cursor:pointer; margin-top:auto; }- .btn:hover { filter:brightness(1.1); }- .btn.sec { background:#222230; color:#ddd; }- .btn:disabled { opacity:0.5; cursor:not-allowed; }- .checkout { display:none; margin-top:36px; padding:24px; border:1px solid var(--accent); border-radius:14px; background:rgba(106,92,255,0.06); }- .checkout.show { display:block; }- .qr { display:block; width:200px; height:200px; margin:16px 0; background:#fff; padding:10px; border-radius:10px; }- code.payurl { display:block; font-size:11px; word-break:break-all; padding:10px; background:#0f0f17; border:1px solid var(--border); border-radius:8px; color:#9a8cff; margin:10px 0; }- .muted { color:#888; font-size:13px; }- .status { margin-top:12px; font-size:13px; }- .ok { color:#4ade80; }- .err { color:#ffb3b3; }+ .feat li::before { content:"✓"; color:var(--accent); font-weight:700; flex-shrink: 0; }+ .btn { padding:13px 18px; border-radius:11px; border:0; background:var(--accent); color:#fff; font-size:14px; font-weight:600; cursor:pointer; margin-top:auto; text-decoration: none; display: inline-block; text-align: center; transition: filter 0.15s; }+ .btn:hover { filter:brightness(1.12); }+ .btn.sec { background:#222230; color:var(--text); }+ .btn.ghost { background: transparent; color: var(--text); border: 1px solid var(--border); }+ .cta-row { margin-top: 18px; display: flex; gap: 10px; flex-wrap: wrap; }a { color:#9a8cff; }- header { padding:18px 24px; border-bottom:1px solid var(--border); }- header a { color:#aaa; text-decoration:none; font-size:14px; }+ .note { margin-top: 48px; padding: 20px 24px; background: var(--panel); border: 1px solid var(--border); border-radius: 14px; font-size: 14px; color: var(--muted); }+ .note strong { color: var(--text); }+ .faq { margin-top: 56px; }+ .faq h2 { font-size: 22px; margin: 0 0 20px; letter-spacing: -0.01em; font-weight: 600; }+ .faq details { padding: 16px 0; border-bottom: 1px solid var(--border); }+ .faq summary { cursor: pointer; font-weight: 500; color: var(--text); font-size: 15px; list-style: none; }+ .faq summary::after { content: "+"; float: right; color: var(--muted); font-size: 18px; line-height: 1; }+ .faq details[open] summary::after { content: "−"; }+ .faq details p { color: var(--muted); margin: 12px 0 0; line-height: 1.6; font-size: 14.5px; }</style><link rel="stylesheet" href="/mobile.css" /></head><body><header><a href="/">← three.ws</a></header><div class="wrap">- <h1>Pricing</h1>- <p class="sub">Run autonomous AI agents that post, trade, and earn on-chain. <span id="current-plan" class="muted"></span></p>+ <div class="eyebrow">Pricing · Open Beta</div>+ <h1>Free during beta.<br/>Built for scale.</h1>+ <p class="sub">three.ws is the 3D agent layer of the internet — drop one tag and embed a living 3D AI agent on any page. While we’re in open beta, every feature is free. No view caps, no chat-turn limits, no credit card required.</p><div class="grid"><div class="card"><div class="tier">Free</div>- <div class="price">$0<small> /month</small></div>+ <div class="price">$0<small>/forever for hobby & open-source</small></div><ul class="feat">- <li>5 X posts per month</li>- <li>1 post every 30 min</li>- <li>All trigger types (daily, weekly, milestones)</li>- <li>AI-drafted tweets with tone presets</li>- <li>Manual + scheduled posts</li>- <li>Engagement analytics</li>+ <li>Unlimited <code><agent-3d></code> embeds during beta</li>+ <li>Create unlimited avatars & agents</li>+ <li>Voice, animation, mocap, and AR included</li>+ <li>x402 paid skills (you keep 100% during beta)</li>+ <li>Community support on Discord</li></ul>- <button class="btn sec" disabled>You're on Free</button>+ <div class="cta-row">+ <a class="btn" href="/create">Build your first agent</a>+ <a class="btn ghost" href="/docs">Read the docs</a>+ </div></div>- <div class="card pro">- <div class="tag">Recommended</div>- <div class="tier">Pro</div>- <div class="price">$19<small> /month</small></div>+ <div class="card featured">+ <div class="tag">Early access</div>+ <div class="tier">For teams & enterprises</div>+ <div class="price">Let’s talk</div><ul class="feat">- <li>100 X posts per month</li>- <li>1 post every 5 min</li>- <li>Threads (multi-tweet posts)</li>- <li>Review-before-publish mode</li>- <li>Multi-draft picker (3 options)</li>- <li>Priority support</li>+ <li>Custom subdomain (<code>yourapp.three.ws</code>)</li>+ <li>White-label embed & brand-locked themes</li>+ <li>SSO, audit logs, embed-policy whitelisting</li>+ <li>Usage analytics, custom voice cloning</li>+ <li>SLA, priority support, design partnership</li></ul>- <button class="btn" id="upgrade-btn">Upgrade with USDC</button>+ <div class="cta-row">+ <a class="btn" href="mailto:[email protected]?subject=three.ws%20for%20teams">Talk to us</a>+ <a class="btn ghost" href="/discover">See live embeds</a>+ </div></div></div>- <div class="checkout" id="checkout">- <h3 style="margin:0 0 8px">Pay $19 USDC on Solana</h3>- <p class="muted">Scan with Phantom or any Solana wallet, or open the link on the device with your wallet.</p>- <img class="qr" id="qr" alt="Solana Pay QR" />- <code class="payurl" id="payurl"></code>- <a class="btn" id="open-link" href="#" target="_blank" rel="noopener" style="display:inline-block; text-align:center; text-decoration:none">Open in wallet</a>- <div class="muted" style="margin-top:14px">After paying, paste the transaction signature:</div>- <input id="txsig" placeholder="Transaction signature" style="width:100%; margin-top:6px; padding:9px 11px; background:#0f0f17; border:1px solid var(--border); border-radius:8px; color:#eee; font-size:13px; font-family:inherit" />- <button class="btn" id="confirm-btn" style="margin-top:10px">I've paid — confirm</button>- <div class="status" id="status"></div>+ <div class="note">+ <strong>Already on the X-posting plan?</strong> Your subscription continues unchanged. Manage it at <a href="/x-pricing">/x-pricing</a>. New platform-wide pricing for embed volume, API calls, and creator payouts ships after open beta.</div>- </div>-- <script type="module">- const $ = (id) => document.getElementById(id);- const setStatus = (text, cls = '') => { $('status').textContent = text; $('status').className = 'status ' + cls; };- let currentIntent = null;-- // Show current plan if signed in.- try {- const r = await fetch('/api/x/status', { credentials: 'include' });- if (r.ok) {- const d = await r.json();- $('current-plan').textContent = d.tier === 'pro' ? "You're already on Pro." : '';- if (d.tier === 'pro') $('upgrade-btn').textContent = 'Already Pro ✓', $('upgrade-btn').disabled = true;- }- } catch {}-- $('upgrade-btn').addEventListener('click', async () => {- $('upgrade-btn').disabled = true;- $('upgrade-btn').textContent = 'Creating checkout…';- try {- const r = await fetch('/api/payments/solana?action=checkout', {- method: 'POST',- credentials: 'include',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ plan: 'pro', network: 'mainnet' }),- });- const d = await r.json();- if (!r.ok) throw new Error(d.error_description || 'checkout failed');- currentIntent = d;- $('payurl').textContent = d.solana_pay_url;- $('qr').src = `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(d.solana_pay_url)}`;- $('open-link').href = d.solana_pay_url;- $('checkout').classList.add('show');- $('upgrade-btn').textContent = 'Pay below ↓';- } catch (err) {- $('upgrade-btn').disabled = false;- $('upgrade-btn').textContent = 'Upgrade with USDC';- alert(err.message);- }- });-- $('confirm-btn').addEventListener('click', async () => {- const txsig = $('txsig').value.trim();- if (!txsig) return setStatus('Paste the transaction signature first.', 'err');- if (!currentIntent) return setStatus('No active checkout — click Upgrade first.', 'err');- $('confirm-btn').disabled = true;- setStatus('Verifying transaction on-chain…');- try {- const r = await fetch('/api/payments/solana?action=confirm', {- method: 'POST',- credentials: 'include',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ intent_id: currentIntent.intent_id, tx_signature: txsig, network: 'mainnet' }),- });- const d = await r.json();- if (!r.ok) throw new Error(d.error_description || 'confirm failed');- setStatus(`You're Pro until ${new Date(d.active_until).toLocaleDateString()}. Redirecting…`, 'ok');- setTimeout(() => { location.href = '/dashboard'; }, 1800);- } catch (err) {- setStatus(err.message, 'err');- $('confirm-btn').disabled = false;- }- });- </script>+ <div class="faq">+ <h2>FAQ</h2>+ <details>+ <summary>What’s included in the free beta?</summary>+ <p>Everything: unlimited avatars, unlimited agents, unlimited embeds, voice, animation, mocap, AR, x402 paid skills, the dashboard, and the API. We’re intentionally not metering anything during beta — we want to see how people actually use the platform before drawing pricing lines.</p>+ </details>+ <details>+ <summary>What happens when beta ends?</summary>+ <p>A generous free tier will stay free forever for hobby and open-source projects. Paid tiers will be usage-based on embed views, chat turns, and API calls — priced to be cheaper than rolling your own. Existing users get 60 days’ notice and a grandfathered transition rate.</p>+ </details>+ <details>+ <summary>Can I monetize my own agents?</summary>+ <p>Yes. The x402 protocol lets you charge per skill invocation (per chat turn, per generation, per API call) in USDC on Solana. During beta you keep 100% of revenue. After beta there will be a small platform fee (target: 2.9%, similar to Stripe).</p>+ </details>+ <details>+ <summary>Do I need crypto to use three.ws?</summary>+ <p>No. The web component, dashboard, and API work without a wallet. Crypto unlocks: on-chain agent identity (ERC-8004), payable skills (x402), and creator payouts. If you don’t need those, the platform works like any other SaaS.</p>+ </details>+ <details>+ <summary>What about enterprise pricing?</summary>+ <p>Custom subdomain, SSO, audit logs, embed-policy whitelisting, white-label themes, and SLA. Email <a href="mailto:[email protected]">[email protected]</a> and we’ll set up a call.</p>+ </details>+ </div>+ </div></body></html>diff --git a/pages/x-pricing.html b/pages/x-pricing.htmlnew file mode 100644index 000000000..d12bbe750--- /dev/null+++ b/pages/x-pricing.html@@ -0,0 +1,159 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Pricing · three.ws</title>+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }+ * { box-sizing: border-box; }+ body { font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }+ .wrap { max-width: 880px; margin: 0 auto; padding: 56px 24px 80px; }+ h1 { font-size: 32px; margin: 0 0 8px; letter-spacing: -0.02em; }+ .sub { color:#888; margin: 0 0 36px; font-size:15px; }+ .grid { display:grid; grid-template-columns: 1fr 1fr; gap:18px; }+ @media (max-width: 720px) { .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; }+ .card.pro { border-color:var(--accent); box-shadow:0 0 0 1px var(--accent) inset; position:relative; }+ .tag { position:absolute; top:-10px; right:18px; background:var(--accent); color:#fff; font-size:11px; padding:3px 10px; border-radius:99px; font-weight:600; letter-spacing:0.05em; }+ .tier { font-size:13px; text-transform:uppercase; letter-spacing:0.08em; color:#888; font-weight:600; }+ .price { font-size:38px; margin:8px 0 4px; font-weight:600; letter-spacing:-0.01em; }+ .price small { font-size:14px; color:#888; font-weight:400; }+ .feat { list-style:none; padding:0; margin:18px 0 0; }+ .feat li { padding:8px 0; border-bottom:1px solid #1c1c26; color:#ccc; font-size:14px; display:flex; align-items:center; gap:8px; }+ .feat li:last-child { border-bottom:none; }+ .feat li::before { content:"✓"; color:var(--accent); font-weight:600; }+ .btn { padding:12px 16px; border-radius:10px; border:0; background:var(--accent); color:#fff; font-size:14px; font-weight:600; cursor:pointer; margin-top:auto; }+ .btn:hover { filter:brightness(1.1); }+ .btn.sec { background:#222230; color:#ddd; }+ .btn:disabled { opacity:0.5; cursor:not-allowed; }+ .checkout { display:none; margin-top:36px; padding:24px; border:1px solid var(--accent); border-radius:14px; background:rgba(106,92,255,0.06); }+ .checkout.show { display:block; }+ .qr { display:block; width:200px; height:200px; margin:16px 0; background:#fff; padding:10px; border-radius:10px; }+ code.payurl { display:block; font-size:11px; word-break:break-all; padding:10px; background:#0f0f17; border:1px solid var(--border); border-radius:8px; color:#9a8cff; margin:10px 0; }+ .muted { color:#888; font-size:13px; }+ .status { margin-top:12px; font-size:13px; }+ .ok { color:#4ade80; }+ .err { color:#ffb3b3; }+ a { color:#9a8cff; }+ header { padding:18px 24px; border-bottom:1px solid var(--border); }+ header a { color:#aaa; text-decoration:none; font-size:14px; }+ </style>+ <link rel="stylesheet" href="/mobile.css" />+</head>+<body>+ <header><a href="/">← three.ws</a></header>+ <div class="wrap">+ <h1>Pricing</h1>+ <p class="sub">Run autonomous AI agents that post, trade, and earn on-chain. <span id="current-plan" class="muted"></span></p>++ <div class="grid">+ <div class="card">+ <div class="tier">Free</div>+ <div class="price">$0<small> /month</small></div>+ <ul class="feat">+ <li>5 X posts per month</li>+ <li>1 post every 30 min</li>+ <li>All trigger types (daily, weekly, milestones)</li>+ <li>AI-drafted tweets with tone presets</li>+ <li>Manual + scheduled posts</li>+ <li>Engagement analytics</li>+ </ul>+ <button class="btn sec" disabled>You're on Free</button>+ </div>+ <div class="card pro">+ <div class="tag">Recommended</div>+ <div class="tier">Pro</div>+ <div class="price">$19<small> /month</small></div>+ <ul class="feat">+ <li>100 X posts per month</li>+ <li>1 post every 5 min</li>+ <li>Threads (multi-tweet posts)</li>+ <li>Review-before-publish mode</li>+ <li>Multi-draft picker (3 options)</li>+ <li>Priority support</li>+ </ul>+ <button class="btn" id="upgrade-btn">Upgrade with USDC</button>+ </div>+ </div>++ <div class="checkout" id="checkout">+ <h3 style="margin:0 0 8px">Pay $19 USDC on Solana</h3>+ <p class="muted">Scan with Phantom or any Solana wallet, or open the link on the device with your wallet.</p>+ <img class="qr" id="qr" alt="Solana Pay QR" />+ <code class="payurl" id="payurl"></code>+ <a class="btn" id="open-link" href="#" target="_blank" rel="noopener" style="display:inline-block; text-align:center; text-decoration:none">Open in wallet</a>+ <div class="muted" style="margin-top:14px">After paying, paste the transaction signature:</div>+ <input id="txsig" placeholder="Transaction signature" style="width:100%; margin-top:6px; padding:9px 11px; background:#0f0f17; border:1px solid var(--border); border-radius:8px; color:#eee; font-size:13px; font-family:inherit" />+ <button class="btn" id="confirm-btn" style="margin-top:10px">I've paid — confirm</button>+ <div class="status" id="status"></div>+ </div>+ </div>++ <script type="module">+ const $ = (id) => document.getElementById(id);+ const setStatus = (text, cls = '') => { $('status').textContent = text; $('status').className = 'status ' + cls; };++ let currentIntent = null;++ // Show current plan if signed in.+ try {+ const r = await fetch('/api/x/status', { credentials: 'include' });+ if (r.ok) {+ const d = await r.json();+ $('current-plan').textContent = d.tier === 'pro' ? "You're already on Pro." : '';+ if (d.tier === 'pro') $('upgrade-btn').textContent = 'Already Pro ✓', $('upgrade-btn').disabled = true;+ }+ } catch {}++ $('upgrade-btn').addEventListener('click', async () => {+ $('upgrade-btn').disabled = true;+ $('upgrade-btn').textContent = 'Creating checkout…';+ try {+ const r = await fetch('/api/payments/solana?action=checkout', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ plan: 'pro', network: 'mainnet' }),+ });+ const d = await r.json();+ if (!r.ok) throw new Error(d.error_description || 'checkout failed');+ currentIntent = d;+ $('payurl').textContent = d.solana_pay_url;+ $('qr').src = `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(d.solana_pay_url)}`;+ $('open-link').href = d.solana_pay_url;+ $('checkout').classList.add('show');+ $('upgrade-btn').textContent = 'Pay below ↓';+ } catch (err) {+ $('upgrade-btn').disabled = false;+ $('upgrade-btn').textContent = 'Upgrade with USDC';+ alert(err.message);+ }+ });++ $('confirm-btn').addEventListener('click', async () => {+ const txsig = $('txsig').value.trim();+ if (!txsig) return setStatus('Paste the transaction signature first.', 'err');+ if (!currentIntent) return setStatus('No active checkout — click Upgrade first.', 'err');+ $('confirm-btn').disabled = true;+ setStatus('Verifying transaction on-chain…');+ try {+ const r = await fetch('/api/payments/solana?action=confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ intent_id: currentIntent.intent_id, tx_signature: txsig, network: 'mainnet' }),+ });+ const d = await r.json();+ if (!r.ok) throw new Error(d.error_description || 'confirm failed');+ setStatus(`You're Pro until ${new Date(d.active_until).toLocaleDateString()}. Redirecting…`, 'ok');+ setTimeout(() => { location.href = '/dashboard'; }, 1800);+ } catch (err) {+ setStatus(err.message, 'err');+ $('confirm-btn').disabled = false;+ }+ });+ </script>+</body>+</html>diff --git a/public/embed/v1.js b/public/embed/v1.jsindex 54b55750f..45afc91c1 100644--- a/public/embed/v1.js+++ b/public/embed/v1.js@@ -217,6 +217,7 @@};ThreeWsAgentElement.prototype.__boot = async function () {+ var self = this;var agentSpec = this.getAttribute('agent');var src = this.getAttribute('src');var nameAttr = this.getAttribute('name');@@ -288,7 +289,6 @@self.__fail(e && e.detail ? e.detail : new Error('model failed to load'));});- var self = this;this.__stage.appendChild(mv);this.__mv = mv;diff --git a/public/embed/v1/preview.html b/public/embed/v1/preview.htmlnew file mode 100644index 000000000..2aea18915--- /dev/null+++ b/public/embed/v1/preview.html@@ -0,0 +1,366 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>The 3D layer of the internet · three.ws embed v1</title>+ <meta name="description" content="One script tag. Any website. Embodied 3D AI agents." />+ <meta name="theme-color" content="#000000" />+ <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/embed/v1/preview" />+ <style>+ :root {+ --bg: #07070a;+ --panel: #0e0e12;+ --ink: #f5f5f7;+ --ink-dim: #8a8a93;+ --ink-faint: #45454c;+ --accent: #ffffff;+ --ring: rgba(255, 255, 255, 0.08);+ --ring-strong: rgba(255, 255, 255, 0.16);+ --radius: 16px;+ --mono:+ ui-monospace, 'JetBrains Mono', SFMono-Regular, Menlo, Consolas, monospace;+ --sans:+ -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', Roboto, sans-serif;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--ink); font-family: var(--sans); -webkit-font-smoothing: antialiased; }+ body { min-height: 100vh; overflow-x: hidden; }++ a { color: inherit; }++ .shell { max-width: 1200px; margin: 0 auto; padding: 64px 24px 96px; }++ .hero { text-align: center; padding: 48px 0 80px; }+ .eyebrow {+ display: inline-flex; align-items: center; gap: 8px;+ font-family: var(--mono); font-size: 11px; letter-spacing: 0.18em;+ text-transform: uppercase; color: var(--ink-dim);+ padding: 6px 12px; border: 1px solid var(--ring); border-radius: 999px;+ margin-bottom: 28px;+ }+ .eyebrow .dot {+ width: 6px; height: 6px; border-radius: 50%; background: #4ade80;+ box-shadow: 0 0 10px #4ade80;+ }+ .hero h1 {+ font-size: clamp(40px, 7vw, 88px);+ font-weight: 700; letter-spacing: -0.03em; line-height: 1.02;+ margin: 0 0 24px;+ background: linear-gradient(180deg, #fff 0%, #b8b8c2 100%);+ -webkit-background-clip: text; background-clip: text; color: transparent;+ }+ .hero p.sub {+ font-size: clamp(16px, 1.6vw, 19px); color: var(--ink-dim);+ max-width: 620px; margin: 0 auto 32px; line-height: 1.5;+ }+ .snippet {+ display: inline-block; text-align: left; background: #0a0a0d;+ border: 1px solid var(--ring); border-radius: 12px;+ padding: 14px 18px; font-family: var(--mono); font-size: 13px;+ color: #e8e8ec; max-width: 100%; overflow-x: auto;+ }+ .snippet .tag { color: #ff7ab6; }+ .snippet .attr { color: #c4b5fd; }+ .snippet .str { color: #fde68a; }++ .section-label {+ display: flex; align-items: baseline; gap: 14px;+ margin: 64px 0 24px;+ }+ .section-label .n {+ font-family: var(--mono); font-size: 11px; color: var(--ink-faint);+ letter-spacing: 0.1em;+ }+ .section-label h2 {+ margin: 0; font-size: 22px; font-weight: 600; letter-spacing: -0.01em;+ }+ .section-label .rule { flex: 1; height: 1px; background: var(--ring); }++ .grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 28px;+ }+ @media (max-width: 800px) { .grid { grid-template-columns: 1fr; } }++ .surface {+ background: var(--panel);+ border: 1px solid var(--ring);+ border-radius: var(--radius);+ overflow: hidden;+ position: relative;+ transition: border-color 0.2s, transform 0.2s;+ }+ .surface:hover { border-color: var(--ring-strong); }+ .surface .bar {+ display: flex; align-items: center; gap: 8px;+ padding: 12px 16px;+ border-bottom: 1px solid var(--ring);+ font-family: var(--mono); font-size: 11px;+ color: var(--ink-dim); letter-spacing: 0.06em; text-transform: uppercase;+ }+ .surface .bar .dot {+ width: 9px; height: 9px; border-radius: 50%; background: #2a2a31;+ }+ .surface .bar .pull { margin-left: auto; color: var(--ink-faint); font-size: 10px; }++ /* ---- Surface: Twitter / X ------------------------------------ */+ .x-post { padding: 18px 20px; background: #15171a; color: #e7e9ea; font-family: 'Helvetica Neue', system-ui, sans-serif; }+ .x-row { display: flex; gap: 12px; }+ .x-av { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg,#1d9bf0,#7856ff); flex-shrink: 0; }+ .x-name { font-weight: 700; font-size: 15px; }+ .x-name .handle { color: #71767b; font-weight: 400; margin-left: 6px; }+ .x-time { color: #71767b; font-size: 14px; }+ .x-body { font-size: 15px; line-height: 1.4; margin: 6px 0 12px; color: #e7e9ea; }+ .x-embed { border-radius: 16px; overflow: hidden; border: 1px solid #2f3336; aspect-ratio: 16 / 10; background: #000; }++ /* ---- Surface: Notion ----------------------------------------- */+ .notion { padding: 32px 40px; background: #191919; color: #e7e7e6; font-family: 'Inter', system-ui; }+ .notion h3 { margin: 0 0 12px; font-size: 28px; font-weight: 700; }+ .notion p { font-size: 15px; line-height: 1.5; color: #a8a8a3; margin: 0 0 16px; }+ .notion .block { border-radius: 4px; aspect-ratio: 4 / 3; overflow: hidden; background: #2a2a2a; }++ /* ---- Surface: Discord ---------------------------------------- */+ .discord { background: #313338; padding: 16px 18px; color: #dbdee1; font-family: 'gg sans','Noto Sans',system-ui; }+ .dc-msg { display: flex; gap: 14px; align-items: flex-start; }+ .dc-av { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg,#5865f2,#eb459e); flex-shrink: 0; }+ .dc-meta { display: flex; align-items: baseline; gap: 8px; }+ .dc-name { color: #f23f43; font-weight: 600; font-size: 16px; }+ .dc-time { font-size: 12px; color: #949ba4; }+ .dc-body { font-size: 15px; line-height: 1.375; color: #dbdee1; margin: 2px 0 8px; }+ .dc-embed { width: 100%; max-width: 420px; border-left: 4px solid #5865f2; background: #2b2d31; border-radius: 4px; padding: 12px; }+ .dc-embed-title { font-size: 14px; font-weight: 600; color: #00a8fc; margin-bottom: 8px; }+ .dc-embed .stage { aspect-ratio: 1 / 1; border-radius: 4px; overflow: hidden; background: #1e1f22; }++ /* ---- Surface: Shopify product -------------------------------- */+ .shop { background: #fff; color: #111; padding: 0; font-family: 'Inter', system-ui; }+ .shop-grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 0; }+ @media (max-width: 540px) { .shop-grid { grid-template-columns: 1fr; } }+ .shop-img { background: #f3f3f3; aspect-ratio: 1 / 1; }+ .shop-info { padding: 22px 24px; }+ .shop-brand { font-size: 11px; letter-spacing: 0.18em; color: #777; text-transform: uppercase; }+ .shop-title { font-size: 24px; font-weight: 600; letter-spacing: -0.01em; margin: 6px 0 8px; }+ .shop-price { font-size: 18px; font-weight: 500; color: #111; margin-bottom: 12px; }+ .shop-desc { font-size: 13px; color: #555; line-height: 1.5; margin: 0 0 16px; }+ .shop-cta { background: #111; color: #fff; padding: 12px 18px; border-radius: 8px; font-weight: 600; font-size: 14px; display: inline-block; text-decoration: none; }++ /* ---- Surface: Substack / newsletter -------------------------- */+ .news { background: #fdfaf5; color: #1a1a1a; padding: 36px 44px; font-family: Georgia, 'Iowan Old Style', serif; }+ .news .kicker { font-family: var(--sans); font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase; color: #ad6a1a; margin-bottom: 8px; }+ .news h3 { margin: 0 0 12px; font-size: 26px; font-weight: 700; letter-spacing: -0.01em; }+ .news .by { font-family: var(--sans); font-size: 12px; color: #66554a; margin-bottom: 20px; }+ .news p { font-size: 16px; line-height: 1.6; color: #2a2a2a; margin: 0 0 16px; }+ .news .figure { aspect-ratio: 16 / 10; border-radius: 6px; overflow: hidden; background: #ece6dc; margin: 20px 0; }+ .news .caption { font-family: var(--sans); font-size: 12px; color: #66554a; text-align: center; margin-top: -8px; }++ /* ---- Surface: Personal blog ---------------------------------- */+ .blog { background: #0f1419; color: #c9d1d9; padding: 36px 40px; font-family: 'Inter', system-ui; }+ .blog .meta { font-size: 12px; color: #6e7681; margin-bottom: 8px; }+ .blog h3 { margin: 0 0 14px; font-size: 24px; font-weight: 700; color: #f0f6fc; letter-spacing: -0.01em; }+ .blog p { font-size: 14px; line-height: 1.6; color: #b1bac4; margin: 0 0 16px; }+ .blog .embedded { aspect-ratio: 1 / 1; border-radius: 10px; overflow: hidden; background: #0a0d11; border: 1px solid #21262d; }++ /* ---- Install + docs section --------------------------------- */+ .docs { margin-top: 96px; padding: 48px; border: 1px solid var(--ring); border-radius: var(--radius); background: linear-gradient(180deg, #0c0c10 0%, #07070a 100%); }+ .docs h2 { margin: 0 0 8px; font-size: 26px; font-weight: 600; letter-spacing: -0.01em; }+ .docs p.lead { color: var(--ink-dim); margin: 0 0 32px; font-size: 15px; }+ .docs-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 24px; }+ @media (max-width: 800px) { .docs-grid { grid-template-columns: 1fr; } }+ .docs-card { padding: 20px; background: #0a0a0d; border: 1px solid var(--ring); border-radius: 10px; }+ .docs-card h3 { margin: 0 0 8px; font-size: 14px; font-weight: 600; color: var(--ink); }+ .docs-card p { margin: 0 0 12px; font-size: 13px; color: var(--ink-dim); line-height: 1.5; }+ pre { margin: 0; padding: 12px 14px; background: #050507; border: 1px solid var(--ring); border-radius: 8px; font-family: var(--mono); font-size: 12px; color: #d6d6dd; overflow-x: auto; }++ footer.foot {+ margin-top: 96px; padding-top: 32px; border-top: 1px solid var(--ring);+ display: flex; justify-content: space-between; align-items: center;+ font-size: 12px; color: var(--ink-dim);+ }+ footer.foot a { color: var(--ink-dim); text-decoration: none; }+ footer.foot a:hover { color: var(--ink); }+ </style>+ </head>+ <body>+ <!-- Load the embed once for the whole page. -->+ <script src="/embed/v1.js" async></script>++ <main class="shell">+ <section class="hero">+ <div class="eyebrow"><span class="dot"></span> embed v1 · preview</div>+ <h1>The 3D layer of the internet.</h1>+ <p class="sub">+ One script tag. Any website. Embodied 3D AI agents that resolve from on-chain+ identity, render on any device, and feel native to the page they live in.+ </p>+ <div class="snippet">+ <span class="tag"><script</span>+ <span class="attr"> src</span>=<span class="str">"https://three.ws/embed/v1.js"</span>+ <span class="attr"> async</span><span class="tag">></script></span><br />+ <span class="tag"><three-d</span>+ <span class="attr"> agent</span>=<span class="str">"8453:42"</span><span class="tag">></three-d></span>+ </div>+ </section>++ <div class="section-label">+ <span class="n">01</span>+ <h2>Agents appear inside the surfaces people already use</h2>+ <span class="rule"></span>+ </div>++ <div class="grid">+ <!-- 1. Twitter / X -->+ <div class="surface">+ <div class="bar"><span class="dot"></span><span>x.com</span><span class="pull">post</span></div>+ <div class="x-post">+ <div class="x-row">+ <div class="x-av"></div>+ <div style="flex:1">+ <div class="x-name">three.ws <span class="handle">@threews · 2h</span></div>+ <div class="x-body">made my agent. lives on Base, earns x402, embeds anywhere ↓</div>+ <div class="x-embed">+ <three-d src="https://three.ws/animations/robotexpressive.glb" name="Saga" theme="dark" autoplay></three-d>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- 2. Notion -->+ <div class="surface">+ <div class="bar"><span class="dot"></span><span>notion.so</span><span class="pull">doc</span></div>+ <div class="notion">+ <h3>Q3 product memo</h3>+ <p>Adding our team agent inline so reviewers can interact with it while reading the spec.</p>+ <div class="block">+ <three-d src="https://three.ws/avatars/cz.glb" name="CZ" theme="dark" autoplay></three-d>+ </div>+ </div>+ </div>++ <!-- 3. Discord -->+ <div class="surface">+ <div class="bar"><span class="dot"></span><span>discord.com</span><span class="pull">#agents</span></div>+ <div class="discord">+ <div class="dc-msg">+ <div class="dc-av"></div>+ <div style="flex:1;min-width:0">+ <div class="dc-meta">+ <span class="dc-name">commander</span>+ <span class="dc-time">Today at 14:22</span>+ </div>+ <div class="dc-body">new operative just rolled into the squad. say hi 👋</div>+ <div class="dc-embed">+ <div class="dc-embed-title">Boss · ERC-8004</div>+ <div class="stage">+ <three-d src="https://three.ws/animations/soldier.glb" name="Boss" theme="dark" autoplay></three-d>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- 4. Shopify product page -->+ <div class="surface">+ <div class="bar" style="background:#fafafa;color:#666;border-color:#ececec"><span class="dot" style="background:#ddd"></span><span>shop.example</span><span class="pull">product</span></div>+ <div class="shop">+ <div class="shop-grid">+ <div class="shop-img">+ <three-d src="https://three.ws/animations/soldier.glb" name="Agent" theme="light" autoplay></three-d>+ </div>+ <div class="shop-info">+ <div class="shop-brand">three.ws · agents</div>+ <div class="shop-title">Operative</div>+ <div class="shop-price">0.05 ETH</div>+ <p class="shop-desc">Rigged, animated, agent-ready. On-chain provenance. Drops into any site with one tag.</p>+ <a class="shop-cta" href="/discover">Mint yours →</a>+ </div>+ </div>+ </div>+ </div>++ <!-- 5. Substack-like newsletter -->+ <div class="surface">+ <div class="bar"><span class="dot"></span><span>read.example</span><span class="pull">newsletter</span></div>+ <div class="news">+ <div class="kicker">Field notes · agent infra</div>+ <h3>Why every newsletter will soon ship an agent.</h3>+ <div class="by">By a researcher · May 24</div>+ <p>Long-form is reading. Agents are conversation. Soon every post will have one beside the byline — yours to ask, prompt, replay.</p>+ <div class="figure">+ <three-d src="https://three.ws/avatars/default.glb" name="Claude" theme="light" autoplay></three-d>+ </div>+ <p class="caption">Embedded agent — click and drag to inspect.</p>+ </div>+ </div>++ <!-- 6. Developer blog -->+ <div class="surface">+ <div class="bar"><span class="dot"></span><span>blog.example</span><span class="pull">post</span></div>+ <div class="blog">+ <div class="meta">May 24 · 6 min read</div>+ <h3>Adding a 3D agent to my site in 90 seconds.</h3>+ <p>I added two lines to my MDX template and now every post can host an embodied agent. Here's the result inline:</p>+ <div class="embedded">+ <three-d src="https://three.ws/animations/robotexpressive.glb" name="3D" theme="dark" interactive></three-d>+ </div>+ <p>It resolves from on-chain identity, ships with voice and gaze, and works on mobile. Mind-bending.</p>+ </div>+ </div>+ </div>++ <div class="section-label">+ <span class="n">02</span>+ <h2>Three doors, one artifact</h2>+ <span class="rule"></span>+ </div>++ <section class="docs">+ <h2>Install</h2>+ <p class="lead">+ Pick whichever fits your stack. All three forms ship from the same bundle and+ render identically.+ </p>+ <div class="docs-grid">+ <div class="docs-card">+ <h3>1 · Custom element</h3>+ <p>For HTML, MDX, Webflow, Framer. Drop the tag where you want the agent.</p>+<pre><script src="https://three.ws/embed/v1.js" async></script>+<three-d agent="8453:42"></three-d></pre>+ </div>+ <div class="docs-card">+ <h3>2 · Script-tag drop-in</h3>+ <p>Zero markup. The script auto-mounts itself in place — perfect for Squarespace, Substack, and no-code surfaces.</p>+<pre><script src="https://three.ws/embed/v1.js"+ data-agent="8453:42" async></script></pre>+ </div>+ <div class="docs-card">+ <h3>3 · JS API</h3>+ <p>For React, Vue, Svelte, or any framework that builds the DOM itself.</p>+<pre>import 'https://three.ws/embed/v1.js';+Three.mount('#root', {+ agent: '8453:42',+ interactive: true,+});</pre>+ </div>+ <div class="docs-card">+ <h3>4 · Direct GLB</h3>+ <p>Skip the resolver — point at any glTF/GLB URL. Useful for assets you already host.</p>+<pre><three-d src="https://you.com/model.glb"+ name="My agent"></three-d></pre>+ </div>+ </div>+ </section>++ <footer class="foot">+ <div>three.ws · embed v1 · the 3D layer of the internet</div>+ <div>+ <a href="/discover">Discover</a> · + <a href="/">Home</a>+ </div>+ </footer>+ </main>+ </body>+</html>diff --git a/scripts/verify-embed-v1.mjs b/scripts/verify-embed-v1.mjsnew file mode 100644index 000000000..ecdbe1493--- /dev/null+++ b/scripts/verify-embed-v1.mjs@@ -0,0 +1,134 @@+// Smoke test for embed/v1: load the preview page, capture console + network,+// confirm <three-d> instances upgrade and at least one model-viewer renders.+//+// Uses the SwiftShader-stable Playwright recipe (no GPU process, no shader cache)+// to avoid the headless WebGL crash patterns we've hit before.++import { chromium } from '@playwright/test';++const URL = process.env.URL || 'http://localhost:3000/embed/v1/preview.html';++const browser = await chromium.launch({+ headless: true,+ args: [+ '--use-gl=swiftshader',+ '--enable-unsafe-swiftshader',+ '--disable-gpu-sandbox',+ '--no-sandbox',+ '--disable-software-rasterizer=false',+ '--disable-dev-shm-usage',+ ],+});++const ctx = await browser.newContext({ viewport: { width: 1400, height: 1800 } });+const page = await ctx.newPage();++const consoleEvents = [];+const errors = [];+const failedRequests = [];++page.on('console', (msg) => {+ consoleEvents.push({ type: msg.type(), text: msg.text() });+});+page.on('pageerror', (err) => errors.push(err.message));+page.on('requestfailed', (req) => failedRequests.push({ url: req.url(), failure: req.failure()?.errorText }));++console.log('→ loading', URL);+const resp = await page.goto(URL, { waitUntil: 'load', timeout: 30000 });+console.log(' status:', resp.status());++// Scroll to bottom + back to trigger IntersectionObserver on every card,+// so lazy-mounted instances below the fold actually boot. Then settle.+await page.evaluate(() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'instant' }));+await page.waitForTimeout(800);+await page.evaluate(() => window.scrollTo({ top: 0, behavior: 'instant' }));+await page.waitForTimeout(5000);++const audit = await page.evaluate(() => {+ const els = Array.from(document.querySelectorAll('three-d'));+ const r = {+ threeWsEmbedV1: !!window.__threeWsEmbedV1,+ windowThree: typeof window.Three,+ windowThreeMount: typeof (window.Three && window.Three.mount),+ windowThreeWs: typeof window.ThreeWs,+ customElementThreeD: !!customElements.get('three-d'),+ customElementThreeAgent: !!customElements.get('three-agent'),+ customElementThreeWs: !!customElements.get('three-ws'),+ count: els.length,+ instances: els.map((el) => {+ const shadow = el.shadowRoot;+ const mv = shadow && shadow.querySelector('model-viewer');+ return {+ src: el.getAttribute('src') || el.getAttribute('agent'),+ shadow: !!shadow,+ stageMounted: !!(shadow && shadow.querySelector('.stage')),+ modelViewerMounted: !!mv,+ modelViewerSrc: mv && mv.getAttribute('src'),+ modelLoaded: mv && mv.loaded === true,+ hasPoster: !!(shadow && shadow.querySelector('.poster')),+ hasChrome: !!(shadow && shadow.querySelector('.chrome')),+ };+ }),+ };+ return r;+});++const screenshotPath = '/tmp/embed-v1-preview.png';+await page.screenshot({ path: screenshotPath, fullPage: true });++await browser.close();++let ok = true;+console.log('\n=== AUDIT ===');+console.log('embed bootstrap :', audit.threeWsEmbedV1 ? 'ok' : 'FAIL'); if (!audit.threeWsEmbedV1) ok = false;+console.log('window.Three :', audit.windowThree);+console.log('window.Three.mount :', audit.windowThreeMount); if (audit.windowThreeMount !== 'function') ok = false;+console.log('window.ThreeWs :', audit.windowThreeWs); if (audit.windowThreeWs !== 'object') ok = false;+console.log('<three-d> :', audit.customElementThreeD); if (!audit.customElementThreeD) ok = false;+console.log('<three-agent> :', audit.customElementThreeAgent); if (!audit.customElementThreeAgent) ok = false;+console.log('<three-ws> :', audit.customElementThreeWs); if (!audit.customElementThreeWs) ok = false;+console.log('instance count :', audit.count); if (audit.count !== 6) ok = false;+console.log('\n=== INSTANCES ===');+audit.instances.forEach((i, n) => {+ console.log(`#${n + 1} src=${i.src}`);+ console.log(` shadow=${i.shadow} stage=${i.stageMounted} mv=${i.modelViewerMounted} loaded=${i.modelLoaded} chrome=${i.hasChrome}`);+ if (!i.shadow || !i.stageMounted) ok = false;+ if (!i.modelViewerMounted) ok = false;+ // `loaded=false` is expected under SwiftShader (WebGL fails). On real GPUs it goes true.+});++// Filter out errors that are expected headless-SwiftShader limitations,+// not bugs in our code. These pass on real GPUs.+const HEADLESS_NOISE_PATTERNS = [+ /WebGL context could not be created/i,+ /Error creating WebGL context/i,+ /Cannot read properties of undefined \(reading 'xr'\)/, // model-viewer XR probe in no-WebXR env+];+const isHeadlessNoise = (txt) => HEADLESS_NOISE_PATTERNS.some((re) => re.test(txt || ''));++const realErrors = consoleEvents.filter((c) => c.type === 'error' && !isHeadlessNoise(c.text));+const headlessNoiseCount = consoleEvents.filter((c) => c.type === 'error' && isHeadlessNoise(c.text)).length;+const warnings = consoleEvents.filter((c) => c.type === 'warning' && !isHeadlessNoise(c.text));++console.log('\n=== CONSOLE ===');+console.log('real errors :', realErrors.length);+realErrors.forEach((c) => console.log(' ✗', c.text));+console.log('headless WebGL noise :', headlessNoiseCount, '(expected — passes on real GPU)');+console.log('warnings :', warnings.length);+warnings.slice(0, 5).forEach((c) => console.log(' •', c.text));+if (realErrors.length) ok = false;++console.log('\n=== PAGE ERRORS ===');+const realPageErrors = errors.filter((e) => !isHeadlessNoise(e));+const headlessPageNoise = errors.length - realPageErrors.length;+console.log('real page errors :', realPageErrors.length);+realPageErrors.forEach((e) => console.log(' ✗', e));+console.log('headless WebGL noise :', headlessPageNoise, '(expected — passes on real GPU)');+if (realPageErrors.length) ok = false;++console.log('\n=== FAILED REQUESTS ===');+failedRequests.forEach((r) => console.log(' ', r.failure, r.url));++console.log('\nscreenshot:', screenshotPath);+console.log('\nRESULT:', ok ? 'PASS' : 'FAIL');+process.exit(ok ? 0 : 1);diff --git a/src/element.js b/src/element.jsindex f30a0c2ad..ed7001fce 100644--- a/src/element.js+++ b/src/element.js@@ -1572,13 +1572,12 @@ class Agent3DElement extends HTMLElement {const { skill = 'skill', price = {} } = e.detail || {};const amountUsdc = (Number(price?.amount || 0) / 1e6).toFixed(2);- // Narrate so the user understands what's happening+ // Narrate in chat + avatar walk so the user understands what's happening+ const preText = `To use the ${skill} skill I need a quick payment of $${amountUsdc} USDC. Approval card below.`;+ this._renderMessage({ role: 'assistant', content: preText });protocol.emit({type: ACTION_TYPES.SPEAK,- payload: {- text: `To use the ${skill} skill I'll need a quick payment of $${amountUsdc} USDC. I've dropped the approval card in our chat.`,- sentiment: 0,- },+ payload: { text: preText, sentiment: 0 },});let purchased = false;@@ -1593,9 +1592,11 @@ class Agent3DElement extends HTMLElement {}if (purchased) {+ const doneText = 'Payment confirmed. Continuing...';+ this._renderMessage({ role: 'assistant', content: doneText });protocol.emit({type: ACTION_TYPES.SPEAK,- payload: { text: 'Payment confirmed. Continuing...', sentiment: 0.4 },+ payload: { text: doneText, sentiment: 0.4 },});// Refresh skillAccess so next call goes through without re-prompting.try {diff --git a/vercel.json b/vercel.jsonindex fd3238cd1..748257aaf 100644--- a/vercel.json+++ b/vercel.json@@ -321,6 +321,33 @@"src": "/launchpad/?","dest": "/launchpad.html"},+ {+ "src": "/embed/v1.js",+ "headers": {+ "content-type": "application/javascript; charset=utf-8",+ "cache-control": "public, max-age=300, s-maxage=86400, stale-while-revalidate=604800",+ "access-control-allow-origin": "*",+ "cross-origin-resource-policy": "cross-origin",+ "x-content-type-options": "nosniff"+ },+ "dest": "/embed/v1.js"+ },+ {+ "src": "/embed/v1/preview/?",+ "dest": "/embed/v1/preview.html"+ },+ {+ "src": "/embed/v1/preview.html",+ "dest": "/embed/v1/preview.html"+ },+ {+ "src": "/api/embed/resolve",+ "headers": {+ "access-control-allow-origin": "*",+ "cross-origin-resource-policy": "cross-origin"+ },+ "dest": "/api/embed/resolve"+ },{"src": "/embed","dest": "/embed.html"@@ -429,6 +456,10 @@"src": "/pricing/?","dest": "/pricing.html"},+ {+ "src": "/x-pricing/?",+ "dest": "/x-pricing.html"+ },{"src": "/deploy","dest": "/app.html"diff --git a/vite.config.js b/vite.config.jsindex cc5e514ac..048aa0c0f 100644--- a/vite.config.js+++ b/vite.config.js@@ -173,6 +173,7 @@ const appConfig = {'widget-studio': resolve(__dirname, 'pages/widget-studio.html'),creating: resolve(__dirname, 'pages/creating.html'),pricing: resolve(__dirname, 'pages/pricing.html'),+ 'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),walk: resolve(__dirname, 'pages/walk.html'),pose: resolve(__dirname, 'pages/pose.html'),club: resolve(__dirname, 'pages/club.html'),diff --git a/workers/avatar-reconstruction/.dockerignore b/workers/avatar-reconstruction/.dockerignorenew file mode 100644index 000000000..f59b4876f--- /dev/null+++ b/workers/avatar-reconstruction/.dockerignore@@ -0,0 +1,6 @@+__pycache__+*.pyc+*.pyo+.git+.env+face_uv_map.jsondiff --git a/workers/avatar-reconstruction/Dockerfile b/workers/avatar-reconstruction/Dockerfileindex 0775c42ae..23a30e7c3 100644--- a/workers/avatar-reconstruction/Dockerfile+++ b/workers/avatar-reconstruction/Dockerfile@@ -1,52 +1,57 @@-# ── Stage: base ──────────────────────────────────────────────────────────────-# NVIDIA CUDA 12.1 + cuDNN 8 runtime on Ubuntu 22.04.-# We use the devel variant so that torch extensions can compile native ops.-FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04+# ── Stage: base ───────────────────────────────────────────────────────────────+# CUDA runtime for rembg[gpu] (onnxruntime-gpu). The L4 GPU is only used for+# background removal; the rest of the pipeline (MediaPipe, TPS, GLB ops) is+# CPU-bound and benefits from the generous CPU allocation on Cloud Run.+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04ENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \DEBIAN_FRONTEND=noninteractive \- PIP_NO_CACHE_DIR=1 \- HF_HOME=/models/hf_home \- TRANSFORMERS_CACHE=/models/hf_home \- TORCH_HOME=/models/torch_home \- PYTHONPATH=/opt/instantmesh+ PIP_NO_CACHE_DIR=1# ── System dependencies ───────────────────────────────────────────────────────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 libsm6 libxext6 libxrender1 \- libgomp1 \+ python3.10 python3.10-dev python3-pip \+ git curl wget \+ # OpenCV headless runtime deps+ libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \+ # MediaPipe runtime deps+ libgomp1 \&& rm -rf /var/lib/apt/lists/* \&& ln -sf /usr/bin/python3.10 /usr/bin/python3 \- && ln -sf /usr/bin/python3.10 /usr/bin/python--# ── Clone InstantMesh ─────────────────────────────────────────────────────────-RUN git clone --depth 1 https://github.com/TencentARC/InstantMesh /opt/instantmesh+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel# ── Python dependencies ───────────────────────────────────────────────────────-# Torch must be installed first with the CUDA-specific index URL so we get the-# GPU wheel rather than the CPU-only default from pypi.org.-RUN pip install --upgrade pip setuptools wheel-RUN pip install \- torch==2.1.0+cu121 \- torchvision==0.16.0+cu121 \- --index-url https://download.pytorch.org/whl/cu121--# InstantMesh repo requirements-WORKDIR /opt/instantmesh-RUN pip install -r requirements.txt--# Our server-specific dependencies (on top of InstantMesh's)COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txt# ── App code ──────────────────────────────────────────────────────────────────-COPY main.py /app/main.pyWORKDIR /app+COPY main.py /app/main.py+COPY face_pipeline.py /app/face_pipeline.py+COPY glb_ops.py /app/glb_ops.py+COPY precompute_uv.py /app/precompute_uv.py++# ── Template GLBs ─────────────────────────────────────────────────────────────+# Bake both gender variants into the image so cold starts are instant.+# The repo's default.glb is a Wolf3D unisex base; add male/female variants as+# they become available. For now, all body_type values fall back to default.glb.+RUN mkdir -p /app/templates+COPY templates/ /app/templates/++# ── UV pre-computation ────────────────────────────────────────────────────────+# Run once at image build time. Generates face_uv_map.json from the+# canonical MediaPipe face model and the Wolf3D_Head mesh in default.glb.+# Requires network access during build (downloads ~200 KB OBJ from GitHub).+RUN python /app/precompute_uv.py /app/templates/default.glbEXPOSE 8080-# Single worker — GPU inference is synchronous and one job at a time.-CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1", "--timeout-keep-alive", "600"]+# Two workers: CPU pipeline parallelism; GPU is shared via process-level mutex+# inside rembg (onnxruntime handles it).+CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "300"]diff --git a/workers/avatar-reconstruction/cloudbuild.yaml b/workers/avatar-reconstruction/cloudbuild.yamlindex 9ea293b86..2314423bd 100644--- a/workers/avatar-reconstruction/cloudbuild.yaml+++ b/workers/avatar-reconstruction/cloudbuild.yaml@@ -17,8 +17,8 @@ substitutions:_SERVICE: avatar-reconstruction_REPO: avatar-reconstruction_GCS_BUCKET: three-ws-avatar-reconstructions- _MIN_INSTANCES: "1"- _MAX_INSTANCES: "3"+ _MIN_INSTANCES: "1" # keep one warm — face pipeline cold-start is ~15 s+ _MAX_INSTANCES: "5" # scale out for burst selfie creationsteps:# ── Build ──────────────────────────────────────────────────────────────────@@ -58,13 +58,12 @@ steps:# GPU: NVIDIA L4 (24 GB VRAM) — sufficient for InstantMesh-large- --gpu=1- --gpu-type=nvidia-l4- - --cpu=8- - --memory=32Gi- # Keep one warm instance to avoid 5-minute cold start on every request.+ - --cpu=4+ - --memory=8Gi- --min-instances=${_MIN_INSTANCES}- --max-instances=${_MAX_INSTANCES}- # Reconstruction takes up to 2 minutes; give generous headroom.- - --timeout=600+ # Face texture pipeline completes in ~30 s; 120 s is generous headroom.+ - --timeout=120# Cloud Run IAM handles external auth; the service itself checks API_KEY.- --allow-unauthenticated- --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},FIRESTORE_PROJECT=$PROJECT_ID,DEVICE=cudadiff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.pynew file mode 100644index 000000000..1e5a6ba7e--- /dev/null+++ b/workers/avatar-reconstruction/face_pipeline.py@@ -0,0 +1,452 @@+"""+Selfie → Wolf3D GLB pipeline (Phase 1: face texture transfer).++Steps:+ 1. Decode and select the best frontal photo.+ 2. Background removal (rembg).+ 3. MediaPipe FaceLandmarker → 468 normalised (x, y) landmarks.+ 4. Load pre-computed UV map (face_uv_map.json).+ 5. TPS warp: map user's face into Wolf3D_Skin texture UV space.+ 6. Composite warped face onto existing skin texture using face-oval alpha mask.+ 7. Extract dominant skin tone → tint the unmasked skin regions for consistency.+ 8. Extract dominant hair colour → tint Wolf3D_Hair texture.+ 9. Detect eye colour → adjust Wolf3D_Eye baseColorFactor.+ 10. Return modified GLB bytes.+"""++from __future__ import annotations++import base64+import io+import json+import logging+import os+import time+from pathlib import Path+from typing import Optional++import cv2+import mediapipe as mp+import numpy as np+import requests+from PIL import Image, ImageFilter+from scipy.interpolate import RBFInterpolator++import glb_ops+import pygltflib++log = logging.getLogger("face_pipeline")++# ── paths ──────────────────────────────────────────────────────────────────────++HERE = Path(__file__).parent+UV_MAP_PATH = HERE / "face_uv_map.json"+TEMPLATES_DIR = HERE / "templates"++# ── MediaPipe setup ────────────────────────────────────────────────────────────++_mp_face_mesh = mp.solutions.face_mesh++# The 36 landmark indices that form the face oval in MediaPipe's topology.+_FACE_OVAL = [+ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,+ 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,+ 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,+]++# ── UV map (loaded once at module import) ──────────────────────────────────────++def _load_uv_map() -> dict:+ if not UV_MAP_PATH.exists():+ raise FileNotFoundError(+ f"face_uv_map.json not found at {UV_MAP_PATH}. "+ "Run precompute_uv.py during Docker build."+ )+ return json.loads(UV_MAP_PATH.read_text())+++_UV_MAP: Optional[dict] = None+++def _get_uv_map() -> dict:+ global _UV_MAP+ if _UV_MAP is None:+ _UV_MAP = _load_uv_map()+ return _UV_MAP+++# ── image decoding ─────────────────────────────────────────────────────────────++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://"):+ resp = requests.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 _select_best_photo(images: list[Image.Image]) -> tuple[Image.Image, list]:+ """+ Run MediaPipe on each image and return the one with the largest,+ most frontal face (highest detection confidence, closest to neutral pose).+ Also returns the face landmarks for the selected image.+ """+ best_img = images[0]+ best_landmarks = None+ best_score = -1.0++ with _mp_face_mesh.FaceMesh(+ static_image_mode=True,+ max_num_faces=1,+ refine_landmarks=True,+ min_detection_confidence=0.4,+ ) as fm:+ for img in images:+ arr = np.array(img)+ result = fm.process(arr)+ if not result.multi_face_landmarks:+ continue+ lm = result.multi_face_landmarks[0].landmark++ # Face size heuristic: bounding box area in image coords.+ xs = [l.x for l in lm]+ ys = [l.y for l in lm]+ area = (max(xs) - min(xs)) * (max(ys) - min(ys))++ # Frontality heuristic: nose tip z should be near 0 (facing camera).+ nose_z = abs(lm[4].z) # landmark 4 = nose tip+ frontality = 1.0 / (1.0 + nose_z * 10)++ score = area * frontality+ if score > best_score:+ best_score = score+ best_img = img+ best_landmarks = lm++ return best_img, best_landmarks+++def _get_landmarks(img: Image.Image) -> Optional[list]:+ """Run MediaPipe on a single image, return landmark list or None."""+ with _mp_face_mesh.FaceMesh(+ static_image_mode=True,+ max_num_faces=1,+ refine_landmarks=True,+ min_detection_confidence=0.4,+ ) as fm:+ result = fm.process(np.array(img))+ if result.multi_face_landmarks:+ return result.multi_face_landmarks[0].landmark+ return None+++# ── background removal ─────────────────────────────────────────────────────────++def _remove_background(img: Image.Image) -> Image.Image:+ """Return RGBA image with background removed."""+ 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 as exc:+ log.warning("rembg failed (%s) — using original image", exc)+ return img.convert("RGBA")+++# ── face oval mask ─────────────────────────────────────────────────────────────++def _make_face_oval_mask(landmarks: list, img_w: int, img_h: int) -> np.ndarray:+ """+ Build a soft alpha mask (H×W float32, 0–1) around the face oval.+ Hard boundary at the oval, feathered inward by ~2% of image width.+ """+ pts = np.array(+ [[int(landmarks[i].x * img_w), int(landmarks[i].y * img_h)] for i in _FACE_OVAL],+ dtype=np.int32,+ )+ mask = np.zeros((img_h, img_w), dtype=np.uint8)+ cv2.fillPoly(mask, [pts], 255)++ # Feather: erode then blur.+ kernel_px = max(3, int(img_w * 0.015))+ if kernel_px % 2 == 0:+ kernel_px += 1+ kernel = np.ones((kernel_px, kernel_px), np.uint8)+ mask = cv2.erode(mask, kernel, iterations=1)+ mask = cv2.GaussianBlur(mask, (kernel_px * 2 + 1, kernel_px * 2 + 1), 0)+ return mask.astype(np.float32) / 255.0+++# ── colour analysis ────────────────────────────────────────────────────────────++def _dominant_colour(img_rgb: np.ndarray, mask: np.ndarray) -> np.ndarray:+ """Return the mean RGB colour of pixels where mask > 0.5."""+ m = mask > 0.5+ if m.sum() == 0:+ return np.array([200, 170, 140], dtype=np.float32)+ pixels = img_rgb[m]+ return pixels.mean(axis=0)+++def _extract_skin_tone(img_rgb: np.ndarray, landmarks: list, img_w: int, img_h: int) -> np.ndarray:+ """+ Sample skin colour from cheek and forehead regions (avoids eyes & mouth).+ Returns mean RGB as float32 array.+ """+ # Cheek + forehead landmark indices (see precompute_uv.py SKIN_SAMPLE_INDICES).+ sample_indices = [+ 116, 117, 118, 119, 120, 121, 50,+ 345, 346, 347, 348, 349, 350, 280,+ 10, 9, 8, 107, 336,+ ]+ pts = [(int(landmarks[i].x * img_w), int(landmarks[i].y * img_h)) for i in sample_indices]+ mask = np.zeros((img_h, img_w), dtype=np.float32)+ for (x, y) in pts:+ cv2.circle(mask, (x, y), max(4, img_w // 60), 1.0, -1)+ mask = cv2.GaussianBlur(mask, (15, 15), 0)+ return _dominant_colour(img_rgb, mask)+++def _extract_hair_colour(img_rgb: np.ndarray, landmarks: list, img_w: int, img_h: int) -> np.ndarray:+ """Sample the region above the forehead to get hair colour."""+ top_y = int(min(landmarks[i].y for i in [10, 21, 251]) * img_h)+ strip_h = max(20, top_y // 3)+ strip = img_rgb[max(0, top_y - strip_h) : top_y, :]+ if strip.size == 0:+ return np.array([80, 60, 40], dtype=np.float32)+ return strip.reshape(-1, 3).mean(axis=0)+++def _extract_eye_colour(img_rgb: np.ndarray, landmarks: list, img_w: int, img_h: int) -> np.ndarray:+ """Sample the iris region of the left eye."""+ # Landmark 468 = left iris centre (requires refine_landmarks=True).+ # Fall back to landmark 33 (left eye inner corner) if iris not available.+ try:+ lx = int(landmarks[468].x * img_w)+ ly = int(landmarks[468].y * img_h)+ except IndexError:+ lx = int(landmarks[33].x * img_w)+ ly = int(landmarks[33].y * img_h)+ r = max(4, img_w // 80)+ patch = img_rgb[max(0, ly - r): ly + r, max(0, lx - r): lx + r]+ if patch.size == 0:+ return np.array([100, 130, 160], dtype=np.float32)+ return patch.reshape(-1, 3).mean(axis=0)+++def _tint_texture(base: Image.Image, target_rgb: np.ndarray, strength: float = 0.35) -> Image.Image:+ """+ Colour-grade a texture toward target_rgb.+ Blends the texture's luminance with target colour at given strength.+ """+ arr = np.array(base.convert("RGB"), dtype=np.float32)+ mean = arr.mean(axis=(0, 1))+ shift = (target_rgb - mean) * strength+ tinted = np.clip(arr + shift, 0, 255).astype(np.uint8)+ return Image.fromarray(tinted)+++# ── TPS face warp ──────────────────────────────────────────────────────────────++def _warp_face_to_uv(+ face_img: Image.Image,+ landmarks: list,+ uv_map: dict,+) -> tuple[Image.Image, np.ndarray]:+ """+ Warp the user's face photo into Wolf3D_Skin UV texture space using TPS.++ Returns:+ warped_face — PIL Image (tex_w × tex_h, RGBA) with the face in UV space.+ face_mask_uv — float32 mask (tex_h × tex_w) indicating valid face pixels.+ """+ tex_w = uv_map["texture_width"]+ tex_h = uv_map["texture_height"]+ lm_data = uv_map["landmarks"]+ oval_indices = uv_map["face_oval_indices"]++ img_w, img_h = face_img.size+ img_arr = np.array(face_img.convert("RGBA"), dtype=np.float32)++ # Build control point arrays.+ # Source: landmark positions in user's IMAGE space (pixel coords).+ # Dest : corresponding positions in UV TEXTURE space (pixel coords).+ src_pts = [] # image pixel coords+ dst_pts = [] # texture pixel coords++ for idx, entry in enumerate(lm_data):+ lm = landmarks[idx]+ src_pts.append([lm.x * img_w, lm.y * img_h])+ dst_pts.append([entry["px"], entry["py"]])++ src_pts = np.array(src_pts, dtype=np.float64)+ dst_pts = np.array(dst_pts, dtype=np.float64)++ # TPS: for each UV pixel, find corresponding image pixel.+ # We train TPS in the direction UV→Image (inverse warp for texture sampling).+ tps_uv_to_img = RBFInterpolator(dst_pts, src_pts, kernel="thin_plate_spline", smoothing=0.5)++ # Build a grid of UV pixel centres to sample.+ # Only sample within the bounding box of the face-oval landmarks in UV space.+ oval_uv = np.array([[lm_data[i]["px"], lm_data[i]["py"]] for i in oval_indices])+ x_min, y_min = oval_uv.min(axis=0)+ x_max, y_max = oval_uv.max(axis=0)+ margin = int(tex_w * 0.02)+ x_min = max(0, int(x_min) - margin)+ x_max = min(tex_w, int(x_max) + margin)+ y_min = max(0, int(y_min) - margin)+ y_max = min(tex_h, int(y_max) + margin)++ gy, gx = np.mgrid[y_min:y_max, x_min:x_max]+ grid_pts = np.stack([gx.ravel().astype(np.float64), gy.ravel().astype(np.float64)], axis=1)++ img_coords = tps_uv_to_img(grid_pts) # (n, 2) — x, y in image space+ img_x = img_coords[:, 0].reshape(gy.shape)+ img_y = img_coords[:, 1].reshape(gy.shape)++ # Sample face image at computed coordinates (bilinear).+ map_x = img_x.astype(np.float32)+ map_y = img_y.astype(np.float32)+ face_np = np.array(face_img.convert("RGBA"), dtype=np.uint8)+ warped_patch = cv2.remap(+ face_np, map_x, map_y, cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT+ )++ # Build face-oval mask in UV space.+ oval_uv_pts = oval_uv.astype(np.int32)+ face_mask_uv = np.zeros((tex_h, tex_w), dtype=np.float32)+ cv2.fillPoly(face_mask_uv, [oval_uv_pts], 1.0)++ # Feather the mask.+ k = max(3, int(tex_w * 0.015)) | 1 # ensure odd+ face_mask_uv = cv2.GaussianBlur(face_mask_uv, (k * 4 + 1, k * 4 + 1), 0)++ # Composite warped patch into a full-texture canvas.+ warped_full = np.zeros((tex_h, tex_w, 4), dtype=np.uint8)+ warped_full[y_min:y_max, x_min:x_max] = warped_patch++ return Image.fromarray(warped_full, "RGBA"), face_mask_uv+++def _composite_face_onto_skin(+ skin_tex: Image.Image,+ warped_face: Image.Image,+ face_mask_uv: np.ndarray,+) -> Image.Image:+ """+ Alpha-composite the warped face onto the existing Wolf3D_Skin texture+ using the face-oval mask. Preserves neck/hand regions completely.+ """+ skin_arr = np.array(skin_tex.convert("RGB"), dtype=np.float32)+ face_arr = np.array(warped_face.convert("RGB"), dtype=np.float32)++ mask3 = face_mask_uv[:, :, np.newaxis] # broadcast over channels+ composited = skin_arr * (1.0 - mask3) + face_arr * mask3+ return Image.fromarray(np.clip(composited, 0, 255).astype(np.uint8))+++# ── template loading ───────────────────────────────────────────────────────────++def _load_template(body_type: str) -> bytes:+ """+ Load the appropriate template GLB.+ body_type: 'male' | 'female' | 'neutral' (default).+ """+ candidates = {+ "male": TEMPLATES_DIR / "male.glb",+ "female": TEMPLATES_DIR / "female.glb",+ "neutral": TEMPLATES_DIR / "default.glb",+ }+ path = candidates.get(body_type, TEMPLATES_DIR / "default.glb")+ if not path.exists():+ path = TEMPLATES_DIR / "default.glb"+ return path.read_bytes()+++# ── main pipeline ──────────────────────────────────────────────────────────────++def process(+ job_id: str,+ image_sources: list[str],+ body_type: str = "neutral",+) -> bytes:+ """+ Full selfie → rigged GLB pipeline.++ Args:+ job_id: Identifier used for logging.+ image_sources: List of image data URIs or HTTPS URLs (1–6 items).+ body_type: 'male' | 'female' | 'neutral'.++ Returns:+ GLB file bytes ready to upload to GCS.+ """+ t0 = time.time()+ log.info("[%s] starting pipeline (body_type=%s, images=%d)", job_id, body_type, len(image_sources))++ # 1. Decode images.+ images = [_decode_image(s) for s in image_sources]+ log.info("[%s] decoded %d images (%.1fs)", job_id, len(images), time.time() - t0)++ # 2. Select best frontal photo and get its landmarks.+ best_img, landmarks = _select_best_photo(images)+ if landmarks is None:+ # No face detected in any image — try harder on the first image.+ landmarks = _get_landmarks(images[0])+ if landmarks is None:+ raise ValueError("no face detected in any of the provided photos")+ log.info("[%s] face selected (%.1fs)", job_id, time.time() - t0)++ img_w, img_h = best_img.size+ img_arr = np.array(best_img.convert("RGB"))++ # 3. Background removal.+ fg_img = _remove_background(best_img)+ log.info("[%s] background removed (%.1fs)", job_id, time.time() - t0)++ # 4. Load UV map.+ uv_map = _get_uv_map()++ # 5. Warp face into UV space.+ warped_face, face_mask_uv = _warp_face_to_uv(fg_img, landmarks, uv_map)+ log.info("[%s] face warped to UV space (%.1fs)", job_id, time.time() - t0)++ # 6. Load template GLB.+ glb_bytes = _load_template(body_type)+ glb = glb_ops.load_glb(glb_bytes)++ # 7. Get existing skin texture and composite.+ skin_tex = glb_ops.get_material_texture(glb, "Wolf3D_Skin")+ if skin_tex is None:+ raise ValueError("Wolf3D_Skin material or texture not found in template GLB")++ new_skin = _composite_face_onto_skin(skin_tex, warped_face, face_mask_uv)+ log.info("[%s] face composited onto skin texture (%.1fs)", job_id, time.time() - t0)++ # 8. Skin-tone tint: ensure neck/hands roughly match face colour.+ skin_tone = _extract_skin_tone(img_arr, landmarks, img_w, img_h)+ new_skin = _tint_texture(new_skin, skin_tone, strength=0.25)++ glb_ops.set_material_texture(glb, "Wolf3D_Skin", new_skin)++ # 9. Hair colour tint.+ hair_colour = _extract_hair_colour(img_arr, landmarks, img_w, img_h)+ hair_tex = glb_ops.get_material_texture(glb, "Wolf3D_Hair")+ if hair_tex:+ tinted_hair = _tint_texture(hair_tex, hair_colour, strength=0.6)+ glb_ops.set_material_texture(glb, "Wolf3D_Hair", tinted_hair)++ # 10. Eye colour — adjust baseColorFactor of Wolf3D_Eye material.+ eye_colour = _extract_eye_colour(img_arr, landmarks, img_w, img_h)+ eye_rgb_norm = (eye_colour / 255.0).tolist()+ glb_ops.set_material_base_color(glb, "Wolf3D_Eye", eye_rgb_norm + [1.0])++ # 11. Serialize.+ result = glb_ops.save_glb(glb)+ log.info("[%s] pipeline done in %.1fs — %d bytes", job_id, time.time() - t0, len(result))+ return resultdiff --git a/workers/avatar-reconstruction/glb_ops.py b/workers/avatar-reconstruction/glb_ops.pynew file mode 100644index 000000000..8ee439935--- /dev/null+++ b/workers/avatar-reconstruction/glb_ops.py@@ -0,0 +1,216 @@+"""+GLB texture extraction and in-place replacement using pygltflib.++Strategy: images embedded in the binary blob are extracted cleanly; when+replacing we write new JPEG bytes back into the blob and patch every+affected bufferView byte-offset so the file stays structurally valid.+"""++from __future__ import annotations++import base64+import io+import struct+from typing import Optional++import numpy as np+from PIL import Image+import pygltflib+++# ── helpers ───────────────────────────────────────────────────────────────────++def load_glb(data: bytes) -> pygltflib.GLTF2:+ return pygltflib.GLTF2().load_from_bytes(data)+++def save_glb(glb: pygltflib.GLTF2) -> bytes:+ return bytes(glb.save_to_bytes())+++def _extract_image_bytes(glb: pygltflib.GLTF2, image_idx: int) -> bytes:+ img_obj = glb.images[image_idx]+ if img_obj.uri and img_obj.uri.startswith("data:"):+ _, b64 = img_obj.uri.split(",", 1)+ return base64.b64decode(b64)+ if img_obj.bufferView is not None:+ bv = glb.bufferViews[img_obj.bufferView]+ blob = glb.binary_blob()+ return bytes(blob[bv.byteOffset : bv.byteOffset + bv.byteLength])+ raise ValueError(f"cannot extract image {image_idx}: no uri and no bufferView")+++def _replace_image_bytes_in_blob(+ glb: pygltflib.GLTF2, image_idx: int, new_bytes: bytes+) -> None:+ """+ Patch the binary blob in-place: replace the old image bytes with new ones,+ then fix all bufferView byte-offsets that sit after the patched region.+ Pads to 4-byte alignment as required by the glTF spec.+ """+ img_obj = glb.images[image_idx]++ if img_obj.bufferView is None:+ # Image was a data URI — convert to embedded.+ # Append to end of binary blob instead.+ old_blob = bytearray(glb.binary_blob() or b"")+ offset = len(old_blob)+ padded = bytearray(new_bytes)+ while len(padded) % 4:+ padded.append(0)+ old_blob.extend(padded)+ glb.set_binary_blob(bytes(old_blob))++ # Create a new bufferView for this image.+ bv = pygltflib.BufferView(+ buffer=0,+ byteOffset=offset,+ byteLength=len(new_bytes),+ target=None,+ )+ bv_idx = len(glb.bufferViews)+ glb.bufferViews.append(bv)+ img_obj.bufferView = bv_idx+ img_obj.uri = None+ if glb.buffers:+ glb.buffers[0].byteLength = len(old_blob)+ return++ bv_idx = img_obj.bufferView+ bv = glb.bufferViews[bv_idx]+ old_blob = bytearray(glb.binary_blob())+ offset = bv.byteOffset+ old_len = bv.byteLength++ # Compute padded lengths (4-byte alignment).+ old_padded = (old_len + 3) & ~3+ new_padded = (len(new_bytes) + 3) & ~3+ delta = new_padded - old_padded++ # Build new blob.+ padding = bytes(new_padded - len(new_bytes))+ new_blob = (+ bytes(old_blob[:offset])+ + new_bytes+ + padding+ + bytes(old_blob[offset + old_padded :])+ )+ glb.set_binary_blob(new_blob)++ # Update this bufferView.+ bv.byteLength = len(new_bytes)++ # Shift all bufferViews that start after the patched region.+ for other in glb.bufferViews:+ if other.byteOffset > offset:+ other.byteOffset += delta++ # Update buffer total length.+ if glb.buffers:+ glb.buffers[bv.buffer].byteLength += delta+++# ── public API ────────────────────────────────────────────────────────────────++def find_material_image_idx(glb: pygltflib.GLTF2, material_name: str) -> Optional[int]:+ """Return the base-colour texture image index for a named material, or None."""+ mat = next((m for m in glb.materials if m.name == material_name), None)+ if mat is None:+ return None+ pbr = mat.pbrMetallicRoughness+ if pbr is None or pbr.baseColorTexture is None:+ return None+ tex = glb.textures[pbr.baseColorTexture.index]+ return tex.source+++def get_material_texture(glb: pygltflib.GLTF2, material_name: str) -> Optional[Image.Image]:+ """Return the base-colour texture of a material as a PIL RGBA Image."""+ idx = find_material_image_idx(glb, material_name)+ if idx is None:+ return None+ data = _extract_image_bytes(glb, idx)+ return Image.open(io.BytesIO(data)).convert("RGBA")+++def set_material_texture(+ glb: pygltflib.GLTF2,+ material_name: str,+ new_image: Image.Image,+ quality: int = 92,+) -> bool:+ """+ Replace the base-colour texture of a named material.+ Returns True on success, False if the material was not found.+ """+ idx = find_material_image_idx(glb, material_name)+ if idx is None:+ return False+ buf = io.BytesIO()+ new_image.convert("RGB").save(buf, format="JPEG", quality=quality)+ _replace_image_bytes_in_blob(glb, idx, buf.getvalue())+ return True+++def get_material_base_color(glb: pygltflib.GLTF2, material_name: str) -> Optional[list]:+ """Return the baseColorFactor [r,g,b,a] of a named material, or None."""+ mat = next((m for m in glb.materials if m.name == material_name), None)+ if mat is None:+ return None+ pbr = mat.pbrMetallicRoughness+ if pbr is None:+ return None+ return pbr.baseColorFactor+++def set_material_base_color(+ glb: pygltflib.GLTF2, material_name: str, rgba: list[float]+) -> bool:+ """Set the baseColorFactor of a named material. rgba values in [0,1]."""+ mat = next((m for m in glb.materials if m.name == material_name), None)+ if mat is None:+ return False+ if mat.pbrMetallicRoughness is None:+ mat.pbrMetallicRoughness = pygltflib.PbrMetallicRoughness()+ mat.pbrMetallicRoughness.baseColorFactor = list(rgba)+ return True+++def get_head_mesh_data(glb: pygltflib.GLTF2) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """+ Return (positions, uvs, face_indices) for the Wolf3D_Head mesh.+ positions: (N, 3) float32+ uvs: (N, 2) float32 — TEXCOORD_0+ faces: (F, 3) int32+ """+ mesh = next((m for m in glb.meshes if m.name == "Wolf3D_Head"), None)+ if mesh is None:+ raise ValueError("Wolf3D_Head mesh not found in GLB")++ prim = mesh.primitives[0]+ blob = glb.binary_blob()++ def read_accessor(acc_idx: int) -> np.ndarray:+ acc = glb.accessors[acc_idx]+ bv = glb.bufferViews[acc.bufferView]+ start = bv.byteOffset + (acc.byteOffset or 0)+ type_map = {+ "SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4,+ "MAT2": 4, "MAT3": 9, "MAT4": 16,+ }+ n_components = type_map[acc.type]+ component_map = {+ 5120: np.int8, 5121: np.uint8, 5122: np.int16,+ 5123: np.uint16, 5125: np.uint32, 5126: np.float32,+ }+ dtype = component_map[acc.componentType]+ n_items = acc.count * n_components+ data = np.frombuffer(blob[start : start + n_items * np.dtype(dtype).itemsize], dtype=dtype)+ return data.reshape(acc.count, n_components) if n_components > 1 else data++ positions = read_accessor(prim.attributes.POSITION).astype(np.float32)+ uvs = read_accessor(prim.attributes.TEXCOORD_0).astype(np.float32)+ indices_raw = read_accessor(prim.indices)+ faces = indices_raw.reshape(-1, 3).astype(np.int32)++ return positions, uvs, facesdiff --git a/workers/avatar-reconstruction/main.py b/workers/avatar-reconstruction/main.pyindex d9151050f..bd33f0bac 100644--- a/workers/avatar-reconstruction/main.py+++ b/workers/avatar-reconstruction/main.py@@ -1,117 +1,61 @@"""-Avatar reconstruction service powered by InstantMesh.+Avatar reconstruction service — Phase 1: face texture transfer.-Accepts 1–6 photos (frontal, left, right, …), generates a rigged GLB using-Zero123++ multi-view synthesis + InstantMesh reconstruction, uploads the result-to Cloud Storage, and tracks job state in Firestore.+Same external API contract as the original InstantMesh service so the+Vercel backend (api/_providers/gcp.js) requires zero changes:++ POST /reconstruct { images: [data-uri|https-url, ...], job_id?: str }+ → 202 { job_id, status: "queued" }++ GET /jobs/:id → { job_id, status, glb_url?, error?, updated_at }++ GET /health → { ok, pipeline, model_loaded }Environment variables (all required unless noted):- API_KEY — shared bearer secret; set this in Cloud Run secrets+ API_KEY — shared bearer secret (set via GCP Secret Manager)GCS_BUCKET — Cloud Storage bucket for output GLBs- FIRESTORE_PROJECT — GCP project that hosts the Firestore database- HF_TOKEN — HuggingFace access token (optional, for gated models)- MODEL_CACHE — local dir to cache downloaded weights (default: /models)- DEVICE — 'cuda' or 'cpu' (auto-detected from torch if not set)- MAX_CONCURRENT_JOBS — jobs processed at once (default: 1 on GPU)+ FIRESTORE_PROJECT — GCP project hosting Firestore+ MAX_CONCURRENT_JOBS — parallel jobs (default: 2; CPU-only pipeline)"""+from __future__ import annotations+import asyncio-import base64-import ioimport loggingimport os-import sys+import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone-from pathlib import Path-import requests-import torchfrom fastapi import FastAPI, HTTPException, Header, BackgroundTasksfrom fastapi.responses import JSONResponsefrom google.cloud import firestore, storage-from PIL import Imagefrom pydantic import BaseModel, Field-# InstantMesh is cloned to /opt/instantmesh in the Docker image.-sys.path.insert(0, "/opt/instantmesh")+import face_pipelinelogging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",)-log = logging.getLogger("avatar-reconstruction")+log = logging.getLogger("main")-# ── Config ────────────────────────────────────────────────────────────────────+# ── config ─────────────────────────────────────────────────────────────────────API_KEY = os.environ["API_KEY"]GCS_BUCKET = os.environ["GCS_BUCKET"]FIRESTORE_PROJECT = os.environ["FIRESTORE_PROJECT"]-MODEL_CACHE = Path(os.environ.get("MODEL_CACHE", "/models"))-HF_TOKEN = os.environ.get("HF_TOKEN")-DEVICE = os.environ.get("DEVICE", "cuda" if torch.cuda.is_available() else "cpu")-MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT_JOBS", "1"))+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT_JOBS", "2"))-# ── Global state ──────────────────────────────────────────────────────────────+# ── global state ───────────────────────────────────────────────────────────────-_zero123_pipe = None-_instantmesh_model = None-_rembg_session = None_db: firestore.Client | None = None_bucket: storage.Bucket | None = None_job_sem: asyncio.Semaphore | None = None-# ── Model loading ─────────────────────────────────────────────────────────────---def _load_models() -> None:- global _zero123_pipe, _instantmesh_model, _rembg_session-- log.info("Loading rembg background remover…")- import rembg- _rembg_session = rembg.new_session()-- log.info("Loading Zero123++ diffusion pipeline…")- from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler-- _zero123_pipe = DiffusionPipeline.from_pretrained(- "sudo-ai/zero123plus-v1.2",- custom_pipeline="zero123plus",- torch_dtype=torch.float16,- cache_dir=MODEL_CACHE / "zero123plus",- token=HF_TOKEN,- )- _zero123_pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(- _zero123_pipe.scheduler.config, timestep_spacing="trailing"- )- _zero123_pipe.to(DEVICE)-- log.info("Loading InstantMesh model…")- from omegaconf import OmegaConf- from src.utils.train_util import instantiate_from_config- from huggingface_hub import hf_hub_download-- config_path = Path("/opt/instantmesh/configs/instant-mesh-large.yaml")- config = OmegaConf.load(config_path)- _instantmesh_model = instantiate_from_config(config.model_config)-- ckpt_path = hf_hub_download(- repo_id="TencentARC/InstantMesh",- filename="instant-mesh-large.ckpt",- cache_dir=MODEL_CACHE / "instantmesh",- token=HF_TOKEN,- )- state = torch.load(ckpt_path, map_location="cpu")- _instantmesh_model.load_state_dict(state, strict=True)- _instantmesh_model = _instantmesh_model.to(DEVICE)- _instantmesh_model.eval()-- log.info("All models loaded — device=%s", DEVICE)---# ── Lifespan ──────────────────────────────────────────────────────────────────+# ── lifespan ───────────────────────────────────────────────────────────────────@asynccontextmanagerasync def lifespan(app: FastAPI):@@ -119,103 +63,30 @@ async def lifespan(app: FastAPI):_job_sem = asyncio.Semaphore(MAX_CONCURRENT)+ # Warm up the UV map and template GLBs on startup (loads them into memory).loop = asyncio.get_event_loop()- await loop.run_in_executor(None, _load_models)+ await loop.run_in_executor(None, face_pipeline._get_uv_map)_db = firestore.Client(project=FIRESTORE_PROJECT)_bucket = storage.Client().bucket(GCS_BUCKET)- log.info("Server ready")+ log.info("Server ready — pipeline=face_texture_transfer, max_concurrent=%d", MAX_CONCURRENT)yieldapp = FastAPI(title="avatar-reconstruction", lifespan=lifespan)-# ── Auth ──────────────────────────────────────────────────────────────────────+# ── auth ───────────────────────────────────────────────────────────────────────def _require_api_key(authorization: str) -> None:if not authorization.startswith("Bearer "):raise HTTPException(status_code=401, detail="missing bearer token")- token = authorization[len("Bearer "):].strip()- if token != API_KEY:+ if authorization[len("Bearer "):].strip() != API_KEY:raise HTTPException(status_code=401, detail="invalid api key")-# ── Image helpers ─────────────────────────────────────────────────────────────---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://"):- resp = requests.get(src, timeout=30)- resp.raise_for_status()- return Image.open(io.BytesIO(resp.content)).convert("RGB")- raise ValueError(f"unsupported image source (must be data URI or https URL): {src[:60]}")---def _prepare_input(image: Image.Image) -> Image.Image:- """Remove background and fit image to 320×320 with grey fill."""- import rembg- from src.utils.infer_util import remove_background, resize_foreground-- rgba = remove_background(image, _rembg_session)- rgba = resize_foreground(rgba, ratio=0.85)-- canvas = Image.new("RGBA", (320, 320), (127, 127, 127, 255))- offset = ((320 - rgba.width) // 2, (320 - rgba.height) // 2)- canvas.paste(rgba, offset, mask=rgba.split()[3])-- result = Image.new("RGB", (320, 320), (127, 127, 127))- result.paste(canvas, mask=canvas.split()[3])- return result---def _generate_multiview(primary: Image.Image) -> list[Image.Image]:- """Run Zero123++ to produce 6 synthetic views from a single image."""- with torch.no_grad():- output_grid = _zero123_pipe(primary, num_inference_steps=75).images[0]-- # Zero123++ outputs a 2-column × 3-row grid of 320×320 tiles.- w, h = output_grid.size- tile_w, tile_h = w // 2, h // 3- views = []- for row in range(3):- for col in range(2):- box = (col * tile_w, row * tile_h, (col + 1) * tile_w, (row + 1) * tile_h)- views.append(output_grid.crop(box))- return views---def _reconstruct_glb(views: list[Image.Image]) -> bytes:- """Run InstantMesh on 6 multi-view images and return a GLB file as bytes."""- import tempfile- from torchvision import transforms- from src.utils.camera_util import get_zero123plus_input_cameras-- transform = transforms.Compose([- transforms.Resize((320, 320)),- transforms.ToTensor(),- transforms.Normalize([0.5], [0.5]),- ])-- view_tensor = torch.stack([transform(v) for v in views]).unsqueeze(0).to(DEVICE)- cameras = get_zero123plus_input_cameras(batch_size=1, fov=30.0).to(DEVICE)-- with torch.no_grad():- planes = _instantmesh_model.forward_planes(view_tensor, cameras)- mesh = _instantmesh_model.extract_mesh(planes, use_texture_map=True)-- with tempfile.TemporaryDirectory() as tmp:- out = Path(tmp) / "avatar.glb"- mesh.export(str(out))- return out.read_bytes()---# ── Firestore helpers ─────────────────────────────────────────────────────────-+# ── Firestore helpers ──────────────────────────────────────────────────────────def _set_job(job_id: str, data: dict) -> None:_db.collection("avatar_reconstruction_jobs").document(job_id).set(@@ -229,30 +100,22 @@ def _get_job(job_id: str) -> dict | None:return doc.to_dict() if doc.exists else None-# ── Job worker ────────────────────────────────────────────────────────────────+# ── job worker ─────────────────────────────────────────────────────────────────--async def _process_job(job_id: str, image_sources: list[str]) -> None:+async def _process_job(job_id: str, image_sources: list[str], body_type: str) -> None:async with _job_sem:_set_job(job_id, {"status": "running"})loop = asyncio.get_event_loop()try:- log.info("[%s] decoding %d image(s)…", job_id, len(image_sources))- images = await loop.run_in_executor(- None, lambda: [_decode_image(s) for s in image_sources]- )+ log.info("[%s] running pipeline", job_id)- log.info("[%s] preparing primary input…", job_id)- primary = await loop.run_in_executor(None, lambda: _prepare_input(images[0]))-- log.info("[%s] generating multi-view…", job_id)- views = await loop.run_in_executor(None, lambda: _generate_multiview(primary))-- log.info("[%s] reconstructing mesh…", job_id)- glb_bytes = await loop.run_in_executor(None, lambda: _reconstruct_glb(views))+ glb_bytes = await loop.run_in_executor(+ None,+ lambda: face_pipeline.process(job_id, image_sources, body_type),+ )- log.info("[%s] uploading GLB (%d bytes)…", job_id, len(glb_bytes))- blob_name = f"reconstructions/{job_id}.glb"+ log.info("[%s] uploading %d bytes to GCS", job_id, len(glb_bytes))+ blob_name = f"avatars/{job_id}.glb"blob = _bucket.blob(blob_name)await loop.run_in_executor(None,@@ -264,22 +127,23 @@ async def _process_job(job_id: str, image_sources: list[str]) -> None:log.info("[%s] done → %s", job_id, glb_url)except Exception:- log.exception("[%s] reconstruction failed", job_id)- import traceback- _set_job(job_id, {"status": "failed", "error": traceback.format_exc()})-+ err = traceback.format_exc()+ log.exception("[%s] pipeline failed", job_id)+ _set_job(job_id, {"status": "failed", "error": err})-# ── Routes ────────────────────────────────────────────────────────────────────+# ── routes ─────────────────────────────────────────────────────────────────────class ReconstructRequest(BaseModel):images: list[str] = Field(..., min_length=1, max_length=6)job_id: str | None = None+ body_type: str = "neutral" # 'male' | 'female' | 'neutral'@app.post("/reconstruct", status_code=202)async def reconstruct(body: ReconstructRequest,+ background_tasks: BackgroundTasks,authorization: str = Header(...),) -> dict:_require_api_key(authorization)@@ -288,9 +152,10 @@ async def reconstruct("job_id": job_id,"status": "queued","image_count": len(body.images),+ "body_type": body.body_type,"created_at": datetime.now(timezone.utc),})- asyncio.create_task(_process_job(job_id, body.images))+ background_tasks.add_task(_process_job, job_id, body.images, body.body_type)return {"job_id": job_id, "status": "queued"}@@ -300,7 +165,6 @@ async def get_job(job_id: str, authorization: str = Header(...)) -> dict:job = _get_job(job_id)if job is None:raise HTTPException(status_code=404, detail="job not found")- # Convert Firestore timestamps to ISO strings for JSON serialisation.for k, v in job.items():if hasattr(v, "isoformat"):job[k] = v.isoformat()@@ -309,9 +173,10 @@ async def get_job(job_id: str, authorization: str = Header(...)) -> dict:@app.get("/health")async def health() -> dict:+ uv_ready = (face_pipeline.HERE / "face_uv_map.json").exists()return {"ok": True,- "device": DEVICE,- "model_loaded": _instantmesh_model is not None,- "cuda_available": torch.cuda.is_available(),+ "pipeline": "face_texture_transfer_v1",+ "model_loaded": uv_ready,+ "uv_map_ready": uv_ready,}diff --git a/workers/avatar-reconstruction/precompute_uv.py b/workers/avatar-reconstruction/precompute_uv.pynew file mode 100644index 000000000..59fb72cb1--- /dev/null+++ b/workers/avatar-reconstruction/precompute_uv.py@@ -0,0 +1,196 @@+"""+Pre-computation: canonical MediaPipe face model → Wolf3D_Skin UV coordinates.++Runs ONCE at Docker image build time and writes face_uv_map.json.++Algorithm:+ 1. Download MediaPipe canonical face model OBJ (468 vertices in face-space).+ 2. Load Wolf3D_Head mesh from the template GLB.+ 3. Align both meshes to a common normalised coordinate system (centroid ++ uniform scale so the face fits in a unit cube).+ 4. For each of the 468 canonical landmarks, find the nearest Wolf3D vertex+ by Euclidean distance in 3D (KD-tree).+ 5. Map that vertex's UV coordinates to pixel coordinates in the skin texture.+ 6. Persist the mapping as face_uv_map.json next to this file.++Output JSON schema:+ {+ "texture_width": <int>,+ "texture_height": <int>,+ "landmarks": [ # 468 entries, one per MediaPipe landmark index+ {"u": <float>, "v": <float>, "px": <float>, "py": <float>},+ ...+ ],+ "face_oval_indices": [<int>, ...], # subset used for the face-oval mask+ "skin_sample_indices": [<int>, ...] # landmarks inside the cheek/forehead region+ }+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import numpy as np+import requests+from scipy.spatial import cKDTree++# ── paths ──────────────────────────────────────────────────────────────────────++HERE = Path(__file__).parent+TEMPLATE_GLB = HERE / "templates" / "default.glb"+OUTPUT_JSON = HERE / "face_uv_map.json"++CANONICAL_OBJ_URL = (+ "https://raw.githubusercontent.com/google/mediapipe/master"+ "/mediapipe/modules/face_geometry/data/canonical_face_model.obj"+)++# MediaPipe face-oval landmark indices (silhouette of the face in the mesh).+# These 36 indices form the boundary used for the alpha mask.+FACE_OVAL_INDICES = [+ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,+ 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,+ 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,+]++# Landmarks that sample the skin tone (cheeks + forehead, away from eyes/mouth).+SKIN_SAMPLE_INDICES = [+ 116, 117, 118, 119, 120, 121, 50, # left cheek+ 345, 346, 347, 348, 349, 350, 280, # right cheek+ 10, 9, 8, 107, 336, # forehead+]+++# ── canonical OBJ parser ───────────────────────────────────────────────────────++def _load_canonical_obj(url: str) -> np.ndarray:+ """Download and parse the MediaPipe canonical face model OBJ.+ Returns (468, 3) float32 array of vertex positions."""+ print(f"Downloading canonical face model from {url} …")+ resp = requests.get(url, timeout=60)+ resp.raise_for_status()+ vertices = []+ for line in resp.text.splitlines():+ if line.startswith("v "):+ parts = line.split()+ vertices.append([float(parts[1]), float(parts[2]), float(parts[3])])+ arr = np.array(vertices, dtype=np.float32)+ print(f" Loaded {len(arr)} canonical vertices")+ return arr+++# ── GLB mesh loading ───────────────────────────────────────────────────────────++def _load_wolf3d_head(glb_path: Path) -> tuple[np.ndarray, np.ndarray]:+ """Return (positions (N,3), uvs (N,2)) for Wolf3D_Head from a GLB file."""+ import pygltflib+ from glb_ops import get_head_mesh_data++ data = glb_path.read_bytes()+ glb = pygltflib.GLTF2().load_from_bytes(data)+ positions, uvs, _ = get_head_mesh_data(glb)+ print(f" Wolf3D_Head: {len(positions)} vertices")+ return positions, uvs+++# ── alignment ─────────────────────────────────────────────────────────────────++def _normalise(pts: np.ndarray) -> tuple[np.ndarray, np.ndarray, float]:+ """Translate to centroid, scale to unit cube. Returns (normalised, centroid, scale)."""+ centroid = pts.mean(axis=0)+ shifted = pts - centroid+ scale = np.abs(shifted).max()+ return shifted / scale, centroid, scale+++def _filter_face_vertices(positions: np.ndarray) -> np.ndarray:+ """+ Heuristic: keep only Wolf3D_Head vertices that are on the visible face+ (front hemisphere, above the chin). The canonical model covers only the+ face, so restricting the KD-tree to face vertices gives better matches.+ """+ # In Wolf3D local space Y is up, face points forward (+Z) and is centred+ # around the origin. Filter: z > median_z (front half) AND+ # y > 10th-percentile_y (above chin).+ z_thresh = np.median(positions[:, 2])+ y_thresh = np.percentile(positions[:, 1], 10)+ mask = (positions[:, 2] > z_thresh) & (positions[:, 1] > y_thresh)+ return mask+++# ── texture dimensions ─────────────────────────────────────────────────────────++def _get_skin_texture_size(glb_path: Path) -> tuple[int, int]:+ """Return (width, height) of the Wolf3D_Skin base-colour texture."""+ import io+ import pygltflib+ from PIL import Image++ data = glb_path.read_bytes()+ glb = pygltflib.GLTF2().load_from_bytes(data)++ mat = next(m for m in glb.materials if m.name == "Wolf3D_Skin")+ tex_idx = mat.pbrMetallicRoughness.baseColorTexture.index+ img_idx = glb.textures[tex_idx].source+ img_obj = glb.images[img_idx]++ bv = glb.bufferViews[img_obj.bufferView]+ blob = glb.binary_blob()+ img_bytes = blob[bv.byteOffset : bv.byteOffset + bv.byteLength]+ img = Image.open(io.BytesIO(img_bytes))+ return img.size # (width, height)+++# ── main ──────────────────────────────────────────────────────────────────────++def precompute(glb_path: Path = TEMPLATE_GLB, out_path: Path = OUTPUT_JSON) -> None:+ print("=== UV pre-computation ===")++ canonical = _load_canonical_obj(CANONICAL_OBJ_URL) # (468, 3)+ positions, uvs = _load_wolf3d_head(glb_path) # (N, 3), (N, 2)+ tex_w, tex_h = _get_skin_texture_size(glb_path)+ print(f" Skin texture: {tex_w}×{tex_h}")++ # Normalise both meshes to unit-cube face space.+ canon_norm, _, _ = _normalise(canonical)++ face_mask = _filter_face_vertices(positions)+ face_positions = positions[face_mask]+ face_uvs = uvs[face_mask]+ face_norm, _, _ = _normalise(face_positions)++ # KD-tree on normalised Wolf3D face vertices.+ tree = cKDTree(face_norm)++ # Query: for each of the 468 canonical landmarks, find nearest Wolf3D vertex.+ distances, nn_indices = tree.query(canon_norm, k=1)++ print(f" Mean NN distance: {distances.mean():.4f} Max: {distances.max():.4f}")++ # Convert UV coords → pixel coords.+ # glTF UV convention: (0,0) = top-left, (1,1) = bottom-right.+ landmarks = []+ for i, nn_idx in enumerate(nn_indices):+ u, v = float(face_uvs[nn_idx, 0]), float(face_uvs[nn_idx, 1])+ px = u * tex_w+ py = v * tex_h+ landmarks.append({"u": u, "v": v, "px": px, "py": py})++ result = {+ "texture_width": tex_w,+ "texture_height": tex_h,+ "landmarks": landmarks,+ "face_oval_indices": FACE_OVAL_INDICES,+ "skin_sample_indices": SKIN_SAMPLE_INDICES,+ }++ out_path.write_text(json.dumps(result, indent=2))+ print(f" Written → {out_path}")+ print("=== done ===")+++if __name__ == "__main__":+ glb = Path(sys.argv[1]) if len(sys.argv) > 1 else TEMPLATE_GLB+ precompute(glb_path=glb)diff --git a/workers/avatar-reconstruction/requirements.txt b/workers/avatar-reconstruction/requirements.txtindex c6bcc3750..1bbfc7acf 100644--- a/workers/avatar-reconstruction/requirements.txt+++ b/workers/avatar-reconstruction/requirements.txt@@ -1,37 +1,32 @@-# Core ML — install torch with CUDA index before this file-# torch==2.1.0+cu121 and torchvision==0.16.0+cu121 are installed in the Dockerfile-# via the CUDA-specific PyPI index; they are NOT listed here to avoid pip resolving-# the CPU wheel from pypi.org.--diffusers==0.28.2-transformers==4.40.0-accelerate==0.29.3-einops==0.7.0-omegaconf==2.3.0-safetensors==0.4.2-huggingface_hub==0.23.4-tokenizers--# Image processing-Pillow>=10.0.0+# ── Face detection & landmarks ────────────────────────────────────────────────+mediapipe==0.10.14++# ── GLB manipulation ──────────────────────────────────────────────────────────+pygltflib==1.16.2++# ── Interpolation (TPS warp) ──────────────────────────────────────────────────+scipy>=1.11.0++# ── Image processing ──────────────────────────────────────────────────────────+Pillow>=10.3.0+numpy<2.0+opencv-python-headless>=4.9.0++# ── Background removal ────────────────────────────────────────────────────────+# [gpu] pulls in onnxruntime-gpu so rembg uses CUDA when the L4 is present.rembg[gpu]==2.0.56-scikit-image==0.22.0-imageio==2.34.0-# Mesh export+# ── Mesh operations (UV pre-computation, runs once at build time) ─────────────trimesh==4.4.0-xatlas-# Server+# ── HTTP (image downloads) ────────────────────────────────────────────────────+requests==2.32.3++# ── Server ────────────────────────────────────────────────────────────────────fastapi==0.115.0uvicorn[standard]==0.32.0pydantic>=2.0.0-requests==2.32.3-# GCP+# ── GCP ───────────────────────────────────────────────────────────────────────google-cloud-firestore==2.19.0google-cloud-storage==2.18.0--# Misc-tqdm-numpy<2.0diff --git a/workers/avatar-reconstruction/templates/cz.glb b/workers/avatar-reconstruction/templates/cz.glbnew file mode 100644index 000000000..79648be49Binary files /dev/null and b/workers/avatar-reconstruction/templates/cz.glb differdiff --git a/workers/avatar-reconstruction/templates/default.glb b/workers/avatar-reconstruction/templates/default.glbnew file mode 100644index 000000000..23dd38e7fBinary files /dev/null and b/workers/avatar-reconstruction/templates/default.glb differ