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: video generate API, longcat worker, next page, footer + register-ui updates
nirholase8650f375a8b
diff --git a/api/avatar/video-generate.js b/api/avatar/video-generate.jsnew file mode 100644index 000000000..0e52f767e--- /dev/null+++ b/api/avatar/video-generate.js@@ -0,0 +1,101 @@+// POST /api/avatar/video-generate+//+// Submits a talking-avatar video generation job to the LongCat-Video-Avatar-1.5+// Cloud Run worker. Returns immediately with a job_id for polling.+//+// Request body (JSON):+// image_url string — publicly accessible reference image (PNG/JPG)+// audio_url string — publicly accessible audio file (WAV/MP3)+// prompt string? — optional text description (default: natural speech)+// avatar_id string? — three.ws avatar id; resolved to a GLB render URL+// if image_url is not supplied+//+// Response 202:+// { job_id, status: "queued" }+//+// Errors:+// 400 invalid_request — missing required fields+// 502 worker_error — Cloud Run worker returned an error++import { cors, error, json, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { sql } from '../_lib/db.js';+import { publicUrl } from '../_lib/r2.js';+import { requireSession } from '../_lib/zauth.js';++function workerUrl() {+ const u = process.env.LONGCAT_WORKER_URL;+ if (!u) throw Object.assign(new Error('LONGCAT_WORKER_URL not configured'), { code: 'worker_unconfigured', status: 503 });+ return u.replace(/\/$/, '');+}++function workerKey() {+ const k = process.env.LONGCAT_WORKER_KEY;+ if (!k) throw Object.assign(new Error('LONGCAT_WORKER_KEY not configured'), { code: 'worker_unconfigured', status: 503 });+ return k;+}++async function resolveImageUrl(avatarId) {+ const rows = await sql`+ select storage_key from avatars+ where id = ${avatarId} and deleted_at is null+ limit 1+ `;+ if (!rows[0]) throw Object.assign(new Error('avatar not found'), { code: 'avatar_not_found', status: 404 });+ return publicUrl(rows[0].storage_key);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', `method ${req.method} not allowed`);++ let session;+ try {+ session = await requireSession(req);+ } catch {+ return error(res, 401, 'unauthorized', 'valid session required');+ }++ const body = req.body || {};+ let { image_url: imageUrl, audio_url: audioUrl, avatar_id: avatarId, prompt } = body;++ if (!audioUrl) return error(res, 400, 'invalid_request', 'audio_url is required');++ if (!imageUrl && avatarId) {+ try {+ imageUrl = await resolveImageUrl(avatarId);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'invalid_request', err.message);+ }+ }++ if (!imageUrl) return error(res, 400, 'invalid_request', 'image_url or avatar_id is required');++ const workerBody = {+ image_url: imageUrl,+ audio_url: audioUrl,+ prompt: prompt || 'A person talking naturally.',+ };++ let workerRes;+ try {+ workerRes = await fetch(`${workerUrl()}/generate`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${workerKey()}`,+ },+ body: JSON.stringify(workerBody),+ });+ } catch (err) {+ return error(res, 502, 'worker_unreachable', err?.message || 'worker request failed');+ }++ if (!workerRes.ok) {+ const text = await workerRes.text().catch(() => '');+ return error(res, 502, 'worker_error', `worker returned ${workerRes.status}: ${text.slice(0, 200)}`);+ }++ const result = await workerRes.json();+ return json(res, 202, { job_id: result.job_id, status: result.status });+});diff --git a/api/avatar/video-status.js b/api/avatar/video-status.jsnew file mode 100644index 000000000..60af40c75--- /dev/null+++ b/api/avatar/video-status.js@@ -0,0 +1,74 @@+// GET /api/avatar/video-status?job_id=<id>+//+// Polls the LongCat Cloud Run worker for the status of a video generation job.+//+// Query params:+// job_id string — job id returned by POST /api/avatar/video-generate+//+// Response 200:+// {+// job_id,+// status: "queued" | "running" | "done" | "failed",+// video_url: string | null, // present when status === "done"+// error: string | null, // present when status === "failed"+// updated_at: string, // ISO 8601+// }+//+// Errors:+// 400 invalid_request — missing job_id+// 404 not_found — job not found+// 502 worker_error — Cloud Run worker returned an error++import { cors, error, json, wrap } from '../_lib/http.js';+import { requireSession } from '../_lib/zauth.js';++function workerUrl() {+ const u = process.env.LONGCAT_WORKER_URL;+ if (!u) throw Object.assign(new Error('LONGCAT_WORKER_URL not configured'), { code: 'worker_unconfigured', status: 503 });+ return u.replace(/\/$/, '');+}++function workerKey() {+ const k = process.env.LONGCAT_WORKER_KEY;+ if (!k) throw Object.assign(new Error('LONGCAT_WORKER_KEY not configured'), { code: 'worker_unconfigured', status: 503 });+ return k;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', `method ${req.method} not allowed`);++ try {+ await requireSession(req);+ } catch {+ return error(res, 401, 'unauthorized', 'valid session required');+ }++ const url = new URL(req.url, 'http://x');+ const jobId = url.searchParams.get('job_id');+ if (!jobId) return error(res, 400, 'invalid_request', 'job_id is required');++ let workerRes;+ try {+ workerRes = await fetch(`${workerUrl()}/jobs/${encodeURIComponent(jobId)}`, {+ headers: { authorization: `Bearer ${workerKey()}` },+ });+ } catch (err) {+ return error(res, 502, 'worker_unreachable', err?.message || 'worker request failed');+ }++ if (workerRes.status === 404) return error(res, 404, 'not_found', 'job not found');+ if (!workerRes.ok) {+ const text = await workerRes.text().catch(() => '');+ return error(res, 502, 'worker_error', `worker returned ${workerRes.status}: ${text.slice(0, 200)}`);+ }++ const job = await workerRes.json();+ return json(res, 200, {+ job_id: job.job_id,+ status: job.status,+ video_url: job.video_url ?? null,+ error: job.error ?? null,+ updated_at: job.updated_at ?? null,+ });+});diff --git a/pages/home-next.html b/pages/home-next.htmlindex f0f83e9ab..1d23a1e6e 100644--- a/pages/home-next.html+++ b/pages/home-next.html@@ -495,7 +495,7 @@<div class="hero-canvas"><span class="canvas-tag">● Live</span><agent-3d- src="https://three.ws/api/avatars/bacff13e-b64b-4ac0-860d-44f0168ad23b"+ class="hero-agent"background="transparent"name-plate="off"eager@@ -538,7 +538,7 @@<span style="color: var(--ok);">● running</span></div><agent-3d- src="https://three.ws/api/avatars/bacff13e-b64b-4ac0-860d-44f0168ad23b"+ class="hero-agent"background="transparent"name-plate="off"eager@@ -702,6 +702,16 @@<a class="demo-tag" href="/" title="This is a redesign demo">DEMO · /home-next</a><script>+ // ── Boot the live <agent-3d> instances ───────────────────────+ // The component's `src` requires an absolute URL (the production+ // discover page does the same). Setting it after upgrade keeps+ // the page working in dev (port-forwarded Codespaces) and prod.+ const AVATAR_ID = 'bacff13e-b64b-4ac0-860d-44f0168ad23b';+ const AVATAR_SRC = `${location.origin}/api/avatars/${AVATAR_ID}`;+ document.querySelectorAll('agent-3d.hero-agent').forEach((el) => {+ el.setAttribute('src', AVATAR_SRC);+ });+// ── 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>`,diff --git a/public/footer.html b/public/footer.htmlindex bf3dc8a4b..5330ecc2a 100644--- a/public/footer.html+++ b/public/footer.html@@ -86,8 +86,15 @@<a href="https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Solscan</a><a href="https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Buy on Jupiter</a><a href="https://www.coingecko.com/en/coins/three-ws" target="_blank" rel="noopener">CoinGecko</a>+ <a href="https://www.coinbase.com/price/threews-solana-aba58c21" target="_blank" rel="noopener">Coinbase</a>+ <a href="https://phantom.com/tokens/solana/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Phantom</a><a href="/rider">Rider VR Gate</a></div>+ <div class="h-footer-link-col">+ <h4 class="h-footer-link-heading">Press</h4>+ <a href="https://www.crunchbase.com/organization/three-ws" target="_blank" rel="noopener">Crunchbase</a>+ <a href="https://www.vogue.com/photovogue/photographers/416428" target="_blank" rel="noopener">Vogue</a>+ </div></nav></div><div class="h-footer-bottom">diff --git a/public/next/index.html b/public/next/index.htmlnew file mode 100644index 000000000..10fd80cfb--- /dev/null+++ b/public/next/index.html@@ -0,0 +1,450 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>three.ws — The 3D layer of the internet</title>+ <meta name="description" content="Embodied 3D AI agents. One script tag, any website. Studio, registry, embed, payments, embodiment — the full stack for the 3D web." />+ <meta name="theme-color" content="#07070a" />+ <link rel="canonical" href="https://three.ws/next" />+ <meta property="og:title" content="three.ws — The 3D layer of the internet" />+ <meta property="og:description" content="Embodied 3D AI agents. One script tag, any website." />+ <meta property="og:type" content="website" />+ <meta property="og:url" content="https://three.ws/next" />+ <meta name="twitter:card" content="summary_large_image" />++ <link rel="preconnect" href="https://ajax.googleapis.com" crossorigin />+ <link rel="preconnect" href="https://three.ws" crossorigin />++ <style>+ :root {+ --bg: #07070a;+ --bg-2: #0c0c11;+ --panel: #0e0e12;+ --ink: #f5f5f7;+ --ink-dim: #8a8a93;+ --ink-faint: #45454c;+ --ring: rgba(255, 255, 255, 0.08);+ --ring-strong: rgba(255, 255, 255, 0.16);+ --accent: #4ade80;+ --accent-2: #a78bfa;+ --accent-3: #60a5fa;+ --radius: 16px;+ --radius-lg: 24px;+ --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; -moz-osx-font-smoothing: grayscale; }+ body { min-height: 100vh; overflow-x: hidden; }+ a { color: inherit; text-decoration: none; }+ button { font: inherit; color: inherit; }+ img { max-width: 100%; display: block; }++ /* nav */+ .nav {+ position: sticky; top: 0; z-index: 50;+ display: flex; align-items: center; justify-content: space-between;+ padding: 16px 28px;+ background: rgba(7, 7, 10, 0.72);+ backdrop-filter: saturate(180%) blur(18px);+ -webkit-backdrop-filter: saturate(180%) blur(18px);+ border-bottom: 1px solid var(--ring);+ }+ .brand { display: inline-flex; align-items: center; gap: 10px; font-weight: 600; letter-spacing: -0.01em; }+ .brand-mark {+ width: 22px; height: 22px; border-radius: 6px;+ background: conic-gradient(from 220deg, #fff, #a78bfa, #60a5fa, #4ade80, #fff);+ box-shadow: 0 0 0 1px var(--ring-strong) inset;+ }+ .nav-links { display: flex; gap: 22px; font-size: 14px; color: var(--ink-dim); }+ .nav-links a:hover { color: var(--ink); }+ .nav-cta {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 8px 14px; border-radius: 999px;+ background: var(--ink); color: #07070a; font-weight: 600; font-size: 13px;+ transition: transform .15s ease;+ }+ .nav-cta:hover { transform: translateY(-1px); }+ @media (max-width: 760px) { .nav-links { display: none; } }++ /* hero */+ .hero {+ position: relative;+ padding: 56px 24px 24px;+ text-align: center;+ overflow: hidden;+ }+ .hero::before {+ content: ''; position: absolute; inset: -20% -10% auto -10%; height: 70%;+ background:+ radial-gradient(ellipse at 30% 20%, rgba(167, 139, 250, 0.18), transparent 60%),+ radial-gradient(ellipse at 70% 40%, rgba(96, 165, 250, 0.16), transparent 60%),+ radial-gradient(ellipse at 50% 80%, rgba(74, 222, 128, 0.10), transparent 60%);+ filter: blur(40px); pointer-events: none; z-index: 0;+ }+ .hero-inner { position: relative; z-index: 1; max-width: 1100px; margin: 0 auto; }++ .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: 22px;+ }+ .eyebrow .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 10px var(--accent); }++ h1.hero-title {+ font-size: clamp(44px, 8vw, 112px);+ line-height: 0.98; letter-spacing: -0.035em; font-weight: 700;+ margin: 0 0 18px;+ }+ .grad {+ background: linear-gradient(90deg, #fff 0%, #d3c6ff 35%, #b9d8ff 65%, #c8ffd9 100%);+ -webkit-background-clip: text; background-clip: text; color: transparent;+ }+ .hero-sub {+ font-size: clamp(16px, 1.6vw, 20px); color: var(--ink-dim);+ max-width: 640px; margin: 0 auto 28px; line-height: 1.5;+ }+ .cta-row { display: inline-flex; gap: 12px; flex-wrap: wrap; justify-content: center; }+ .btn {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 12px 18px; border-radius: 12px; font-weight: 600; font-size: 14px;+ border: 1px solid transparent; transition: transform .15s ease, background .15s ease;+ }+ .btn-primary { background: var(--ink); color: #07070a; }+ .btn-primary:hover { transform: translateY(-1px); }+ .btn-ghost { background: transparent; color: var(--ink); border-color: var(--ring-strong); }+ .btn-ghost:hover { background: rgba(255,255,255,0.04); }++ /* hero stage */+ .stage-wrap {+ position: relative; margin: 40px auto 0; max-width: 1100px;+ border: 1px solid var(--ring); border-radius: var(--radius-lg);+ background: linear-gradient(180deg, #0a0a0e, #06060a);+ overflow: hidden;+ box-shadow: 0 30px 80px -30px rgba(0,0,0,0.7), 0 0 0 1px var(--ring) inset;+ }+ .stage-wrap::before {+ content: ''; position: absolute; inset: 0;+ background:+ radial-gradient(ellipse at 20% 0%, rgba(167, 139, 250, 0.18), transparent 50%),+ radial-gradient(ellipse at 80% 100%, rgba(74, 222, 128, 0.12), transparent 50%);+ pointer-events: none;+ }+ .stage-hero { position: relative; z-index: 1; height: clamp(360px, 60vh, 620px); }+ .stage-hero three-d { width: 100%; height: 100%; display: block; }+ .stage-bar {+ display: flex; align-items: center; justify-content: space-between;+ padding: 10px 14px; border-top: 1px solid var(--ring);+ font-family: var(--mono); font-size: 11px; color: var(--ink-dim);+ background: rgba(7,7,10,0.6);+ }+ .stage-bar .pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 10px var(--accent); animation: pulse 2s ease-in-out infinite; }+ @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }++ /* stack section */+ section { padding: 96px 24px; }+ .shell { max-width: 1200px; margin: 0 auto; }+ .section-eyebrow {+ font-family: var(--mono); font-size: 11px; letter-spacing: 0.2em;+ text-transform: uppercase; color: var(--ink-dim); margin-bottom: 14px;+ }+ .section-title { font-size: clamp(32px, 5vw, 56px); letter-spacing: -0.03em; font-weight: 700; margin: 0 0 14px; line-height: 1.05; }+ .section-lede { color: var(--ink-dim); max-width: 620px; font-size: 17px; line-height: 1.55; margin: 0 0 48px; }++ .stack {+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px;+ background: var(--ring); border: 1px solid var(--ring);+ border-radius: var(--radius-lg); overflow: hidden;+ }+ .stack-cell {+ background: var(--bg-2);+ padding: 28px 24px;+ display: flex; flex-direction: column; gap: 10px;+ min-height: 200px;+ transition: background .2s ease;+ }+ .stack-cell:hover { background: #111118; }+ .stack-cell .num { font-family: var(--mono); font-size: 11px; color: var(--ink-faint); letter-spacing: 0.18em; }+ .stack-cell h3 { margin: 0; font-size: 20px; letter-spacing: -0.01em; }+ .stack-cell p { margin: 0; color: var(--ink-dim); font-size: 14px; line-height: 1.55; }+ .stack-cell a.cell-link { font-family: var(--mono); font-size: 12px; color: var(--ink); margin-top: auto; }+ .stack-cell a.cell-link:hover { color: var(--accent); }+ @media (max-width: 920px) { .stack { grid-template-columns: repeat(2, 1fr); } }+ @media (max-width: 600px) { .stack { grid-template-columns: 1fr; } }++ /* embed showcase */+ .embed-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }+ @media (max-width: 920px) { .embed-grid { grid-template-columns: repeat(2, 1fr); } }+ @media (max-width: 600px) { .embed-grid { grid-template-columns: 1fr; } }+ .embed-tile {+ border: 1px solid var(--ring); border-radius: var(--radius);+ background: var(--bg-2); overflow: hidden;+ display: flex; flex-direction: column;+ }+ .embed-tile three-d { width: 100%; height: 280px; display: block; }+ .embed-tile .label {+ padding: 12px 14px; border-top: 1px solid var(--ring);+ display: flex; align-items: center; justify-content: space-between;+ font-family: var(--mono); font-size: 11px; color: var(--ink-dim);+ }+ .embed-tile .label b { color: var(--ink); font-weight: 600; letter-spacing: 0.02em; }++ /* code */+ .install { display: grid; grid-template-columns: 1.1fr 1fr; gap: 36px; align-items: center; }+ @media (max-width: 920px) { .install { grid-template-columns: 1fr; } }+ .code {+ background: #050507; border: 1px solid var(--ring); border-radius: var(--radius);+ padding: 22px 24px; font-family: var(--mono); font-size: 13px; line-height: 1.7;+ color: #d6d6de; overflow: auto;+ box-shadow: 0 20px 60px -20px rgba(0,0,0,0.6);+ }+ .code .c { color: var(--ink-faint); }+ .code .t { color: #c7b4ff; }+ .code .a { color: #9ee6a8; }+ .code .s { color: #ffd6a8; }+ .code .k { color: #9bc7ff; }+ .code .h { color: var(--ink); font-weight: 600; }++ /* metrics */+ .metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; background: var(--ring); border: 1px solid var(--ring); border-radius: var(--radius-lg); overflow: hidden; }+ .metric { background: var(--bg-2); padding: 28px 22px; }+ .metric .v { font-size: 36px; letter-spacing: -0.02em; font-weight: 700; }+ .metric .k { font-family: var(--mono); font-size: 11px; color: var(--ink-dim); letter-spacing: 0.16em; text-transform: uppercase; margin-top: 6px; }+ @media (max-width: 760px) { .metrics { grid-template-columns: repeat(2, 1fr); } }++ /* cta band */+ .cta-band {+ position: relative; margin: 0 24px 96px; padding: 64px 48px;+ border: 1px solid var(--ring-strong); border-radius: var(--radius-lg);+ background: radial-gradient(ellipse at 0% 0%, rgba(167, 139, 250, 0.18), transparent 60%),+ radial-gradient(ellipse at 100% 100%, rgba(74, 222, 128, 0.12), transparent 60%),+ linear-gradient(180deg, #0e0e14, #08080c);+ display: flex; align-items: center; justify-content: space-between; gap: 32px;+ max-width: 1200px; margin-left: auto; margin-right: auto;+ flex-wrap: wrap;+ }+ .cta-band h2 { margin: 0 0 8px; font-size: clamp(28px, 4vw, 44px); letter-spacing: -0.02em; }+ .cta-band p { margin: 0; color: var(--ink-dim); max-width: 520px; }++ /* footer */+ footer { padding: 48px 24px 80px; border-top: 1px solid var(--ring); color: var(--ink-dim); font-size: 13px; }+ .foot { max-width: 1200px; margin: 0 auto; display: flex; justify-content: space-between; gap: 24px; flex-wrap: wrap; }+ .foot-links { display: flex; gap: 22px; flex-wrap: wrap; }+ .foot-links a:hover { color: var(--ink); }++ @media (prefers-reduced-motion: reduce) {+ .pulse { animation: none !important; }+ .btn, .nav-cta { transition: none !important; }+ }+ </style>++ <script src="/embed/v1.js" defer></script>+ </head>+ <body>+ <nav class="nav" aria-label="Primary">+ <a class="brand" href="/">+ <span class="brand-mark" aria-hidden="true"></span>+ three.ws+ </a>+ <div class="nav-links">+ <a href="#stack">Stack</a>+ <a href="#embed">Embed</a>+ <a href="#install">Install</a>+ <a href="/docs">Docs</a>+ <a href="/discover">Registry</a>+ </div>+ <a class="nav-cta" href="#install">Get the tag →</a>+ </nav>++ <header class="hero">+ <div class="hero-inner">+ <span class="eyebrow"><span class="dot"></span>EMBED V1 · LIVE</span>+ <h1 class="hero-title">The <span class="grad">3D layer</span><br />of the internet.</h1>+ <p class="hero-sub">Embodied 3D AI agents you can drop on any page with one tag. Built on open registries, paid by x402, rendered by Three.js.</p>+ <div class="cta-row">+ <a class="btn btn-primary" href="#install">Drop the tag</a>+ <a class="btn btn-ghost" href="/embed/v1/preview">See it in 6 contexts →</a>+ </div>++ <div class="stage-wrap">+ <div class="stage-hero">+ <three-d+ src="https://three.ws/avatars/cz.glb"+ name="three.ws live"+ interactive+ autoplay+ ></three-d>+ </div>+ <div class="stage-bar">+ <span><span class="pulse" aria-hidden="true" style="display:inline-block;vertical-align:middle;margin-right:8px"></span>RENDERED BY <three-d></span>+ <span>SHADOW DOM · LAZY · CORS · 15KB</span>+ </div>+ </div>+ </div>+ </header>++ <section id="stack">+ <div class="shell">+ <div class="section-eyebrow">The full stack</div>+ <h2 class="section-title">Six pieces. One web layer.</h2>+ <p class="section-lede">Everything you need to create, register, embed, monetize, and embody an agent. Each layer is open, each layer is real, each layer ships today.</p>++ <div class="stack">+ <div class="stack-cell">+ <span class="num">01</span>+ <h3>Studio</h3>+ <p>Selfie to rigged avatar in seconds. Faces, fits, voices, motion — all browser-native.</p>+ <a class="cell-link" href="/character-studio">Open Studio →</a>+ </div>+ <div class="stack-cell">+ <span class="num">02</span>+ <h3>Registry</h3>+ <p>ERC-8004 on-chain identity. Agents discoverable, attestable, portable across hosts.</p>+ <a class="cell-link" href="/discover">Browse Registry →</a>+ </div>+ <div class="stack-cell">+ <span class="num">03</span>+ <h3>Embed</h3>+ <p><three-d> web component. One script tag, any site, any CMS. Lazy-mounts, shadow DOM, themeable.</p>+ <a class="cell-link" href="#install">Get the tag →</a>+ </div>+ <div class="stack-cell">+ <span class="num">04</span>+ <h3>x402 Payments</h3>+ <p>HTTP-native micropayments. Agents bill per skill, per minute, per call. Stablecoin settlement.</p>+ <a class="cell-link" href="/.well-known/x402.json">x402 manifest →</a>+ </div>+ <div class="stack-cell">+ <span class="num">05</span>+ <h3>VR Gate</h3>+ <p>WebXR embodiment. Same agent, same identity, walk in as them. $THREE-gated experiences.</p>+ <a class="cell-link" href="/vr">Enter VR →</a>+ </div>+ <div class="stack-cell">+ <span class="num">06</span>+ <h3>SDK</h3>+ <p>JS, Python, Rust. Mint, sign, attest, render, pay. Open source, MIT-licensed, on npm.</p>+ <a class="cell-link" href="/docs">Read the docs →</a>+ </div>+ </div>+ </div>+ </section>++ <section id="embed" style="background: linear-gradient(180deg, transparent, rgba(167,139,250,0.04), transparent);">+ <div class="shell">+ <div class="section-eyebrow">Embed showcase</div>+ <h2 class="section-title">Drop one anywhere.</h2>+ <p class="section-lede">Each tile below is a real <three-d> instance with isolated shadow DOM. Same syntax in your blog, your landing page, your docs.</p>++ <div class="embed-grid">+ <div class="embed-tile">+ <three-d src="https://three.ws/animations/robotexpressive.glb" name="Atlas" interactive></three-d>+ <div class="label"><b>Atlas</b><span>blog post</span></div>+ </div>+ <div class="embed-tile">+ <three-d src="https://three.ws/animations/soldier.glb" name="Vega" interactive></three-d>+ <div class="label"><b>Vega</b><span>product page</span></div>+ </div>+ <div class="embed-tile">+ <three-d src="https://three.ws/avatars/default.glb" name="Mira" interactive></three-d>+ <div class="label"><b>Mira</b><span>docs sidebar</span></div>+ </div>+ <div class="embed-tile">+ <three-d src="https://three.ws/avatars/cz.glb" name="CZ" interactive></three-d>+ <div class="label"><b>CZ</b><span>profile card</span></div>+ </div>+ <div class="embed-tile">+ <three-d src="https://three.ws/animations/soldier.glb" name="Echo" interactive></three-d>+ <div class="label"><b>Echo</b><span>landing hero</span></div>+ </div>+ <div class="embed-tile">+ <three-d src="https://three.ws/animations/robotexpressive.glb" name="Nova" interactive></three-d>+ <div class="label"><b>Nova</b><span>newsletter</span></div>+ </div>+ </div>+ </div>+ </section>++ <section id="install">+ <div class="shell">+ <div class="section-eyebrow">Install</div>+ <h2 class="section-title">Two lines. Live.</h2>+ <p class="section-lede">Paste the script tag once in <head>. Use <three-d> anywhere on the page. Works in React, Vue, Svelte, plain HTML, Notion embeds, Webflow, Shopify — any host that allows a script tag.</p>++ <div class="install">+ <div>+ <pre class="code"><span class="c"><!-- in <head> --></span>+<span class="t"><script</span> <span class="a">src</span>=<span class="s">"https://three.ws/embed/v1.js"</span> <span class="a">defer</span><span class="t">></script></span>++<span class="c"><!-- anywhere in <body> --></span>+<span class="t"><three-d</span>+ <span class="a">agent</span>=<span class="s">"eip155:8453:42"</span>+ <span class="a">name</span>=<span class="s">"Atlas"</span>+ <span class="a">interactive</span>+ <span class="a">autoplay</span>+<span class="t">></three-d></span>++<span class="c">// or via JS</span>+<span class="k">Three</span>.<span class="h">mount</span>(<span class="s">'#slot'</span>, {+ <span class="a">agent</span>: <span class="s">'eip155:8453:42'</span>,+ <span class="a">theme</span>: <span class="s">'transparent'</span>+});</pre>+ </div>+ <div>+ <h3 style="margin:0 0 12px; font-size:22px; letter-spacing:-0.01em;">Built for the open web.</h3>+ <ul style="margin:0; padding:0 0 0 18px; color:var(--ink-dim); line-height:1.8; font-size:15px;">+ <li><b style="color:var(--ink)">Lazy by default.</b> Boots only when scrolled into view.</li>+ <li><b style="color:var(--ink)">Shadow DOM.</b> Zero CSS leakage either way.</li>+ <li><b style="color:var(--ink)">Themeable.</b> <code style="font-family:var(--mono);font-size:13px;color:var(--ink)">theme="light"</code>, <code style="font-family:var(--mono);font-size:13px;color:var(--ink)">"transparent"</code>, or your own.</li>+ <li><b style="color:var(--ink)">Aliases.</b> <code style="font-family:var(--mono);font-size:13px;color:var(--ink)"><three-d></code>, <code style="font-family:var(--mono);font-size:13px;color:var(--ink)"><three-agent></code>, <code style="font-family:var(--mono);font-size:13px;color:var(--ink)"><three-ws></code> — pick your taste.</li>+ <li><b style="color:var(--ink)">Identity-native.</b> Pass an ERC-8004 ID or a direct GLB URL.</li>+ <li><b style="color:var(--ink)">15KB loader.</b> model-viewer pulled from CDN, deduped.</li>+ </ul>+ </div>+ </div>+ </div>+ </section>++ <section>+ <div class="shell">+ <div class="metrics">+ <div class="metric"><div class="v">15<span style="font-size:18px;color:var(--ink-dim)">KB</span></div><div class="k">Loader Size</div></div>+ <div class="metric"><div class="v">3</div><div class="k">Custom Element Aliases</div></div>+ <div class="metric"><div class="v">6</div><div class="k">Stack Layers</div></div>+ <div class="metric"><div class="v">∞</div><div class="k">Hosts Supported</div></div>+ </div>+ </div>+ </section>++ <aside class="cta-band">+ <div>+ <h2>Ship the 3D layer.</h2>+ <p>Open source. ERC-8004 identity. x402 payments. WebXR-ready. The whole stack is live today — drop the tag and watch your agent walk onto any page.</p>+ </div>+ <div class="cta-row">+ <a class="btn btn-primary" href="/character-studio">Open Studio</a>+ <a class="btn btn-ghost" href="/docs">Read Docs</a>+ </div>+ </aside>++ <footer>+ <div class="foot">+ <div>+ <span class="brand"><span class="brand-mark"></span>three.ws</span>+ <div style="margin-top:8px;font-size:12px;color:var(--ink-faint);">The 3D layer of the internet · © 2026</div>+ </div>+ <nav class="foot-links" aria-label="Footer">+ <a href="/discover">Registry</a>+ <a href="/character-studio">Studio</a>+ <a href="/embed/v1/preview">Embed</a>+ <a href="/docs">Docs</a>+ <a href="/blog">Blog</a>+ <a href="https://github.com/nirholas/three.ws">GitHub</a>+ </nav>+ </div>+ </footer>+ </body>+</html>diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.jsindex 5a08c41d1..c8ccf4460 100644--- a/src/erc8004/register-ui.js+++ b/src/erc8004/register-ui.js@@ -362,6 +362,12 @@ export class RegisterUI {this._signedIn = false;this._savedAvatars = null; // loaded lazily when user switches source to 'saved'+ // True when the form was pre-filled from URL params (?name=, ?avatar=,+ // ?agent=). In this case the quickstart bar is hidden — the user already+ // has a specific deployment context and the chips would just confuse them+ // (or silently overwrite the pre-filled data).+ this._urlPrefilled = !!(initial.name || initial.imageUrl || opts.avatarId);+this._build();this._bind();this._fetchBackendAgent(); // fire & forget@@ -1010,7 +1016,9 @@ export class RegisterUI {}).join('')}</ol>`;- const quickstart = pageMode+ // Hide the quickstart bar when the form was seeded from URL params —+ // the user has a specific deployment context and the chips add noise.+ const quickstart = pageMode && !this._urlPrefilled? `<div class="deploy-quickstart-bar"><span class="deploy-quickstart-bar-label">Start from</span>@@ -1019,7 +1027,7 @@ export class RegisterUI {<button class="deploy-qs-chip" data-role="qs-scratch" type="button">Scratch</button><button class="deploy-qs-chip" data-role="qs-update" type="button">Edit existing →</button></div>`- : `+ : pageMode ? '' : `<div class="erc8004-quickstart" data-role="quickstart"><div class="erc8004-quickstart-title">How would you like to start?</div><div class="erc8004-quickstart-grid">@@ -1048,16 +1056,16 @@ export class RegisterUI {<div class="erc8004-wizard-body" data-role="wizard-body"></div></div>`;- body.querySelector('[data-role="qs-saved"]').addEventListener('click', () =>+ body.querySelector('[data-role="qs-saved"]')?.addEventListener('click', () =>this._applyQuickStart('saved'),);- body.querySelector('[data-role="qs-current"]').addEventListener('click', () =>+ body.querySelector('[data-role="qs-current"]')?.addEventListener('click', () =>this._applyQuickStart('current'),);- body.querySelector('[data-role="qs-scratch"]').addEventListener('click', () =>+ body.querySelector('[data-role="qs-scratch"]')?.addEventListener('click', () =>this._applyQuickStart('scratch'),);- body.querySelector('[data-role="qs-update"]').addEventListener('click', () =>+ body.querySelector('[data-role="qs-update"]')?.addEventListener('click', () =>this._applyQuickStart('update'),);body.querySelectorAll('[data-role="goto-step"]').forEach((el) => {@@ -1147,7 +1155,7 @@ export class RegisterUI {<label class="erc8004-label">Description <span class="erc8004-req">*</span><textarea class="erc8004-input erc8004-textarea" name="description" maxlength="1000" rows="4" placeholder="Describe what your agent does, capabilities, pricing…">${esc(this.form.description)}</textarea></label>- <p class="erc8004-hint">Clear description (max 1000 chars)</p>+ <p class="erc8004-hint">Required before deploying on-chain (max 1000 chars)</p><label class="erc8004-label">Image URL<div class="erc8004-image-row">@@ -1178,8 +1186,8 @@ export class RegisterUI {this._captureFromViewer(body);});body.querySelector('[data-role="next"]').addEventListener('click', () => {- if (!this.form.name.trim() || !this.form.description.trim()) {- this._toast('Name and description are required.', true);+ if (!this.form.name.trim()) {+ this._toast('Agent name is required.', true);return;}this.wizardStep = 2;@@ -1679,6 +1687,13 @@ export class RegisterUI {const deployBtn = body.querySelector('[data-role="deploy"]');deployBtn.disabled = true;+ // Guard: name + description are required before any on-chain transaction.+ if (!this.form.name.trim() || !this.form.description.trim()) {+ this._toast('Name and description are required before deploying.', true);+ deployBtn.disabled = false;+ return;+ }+const network = _solanaNetwork(this.selectedChainId);const synthAgent = {id: this._backendAgentId || 'wizard',@@ -1848,6 +1863,13 @@ export class RegisterUI {const deployBtn = body.querySelector('[data-role="deploy"]');deployBtn.disabled = true;+ // Guard: name + description are required before any on-chain transaction.+ if (!this.form.name.trim() || !this.form.description.trim()) {+ this._toast('Name and description are required before deploying.', true);+ deployBtn.disabled = false;+ return;+ }+try {// Ensure we're on the target chainif (this.wallet && this.wallet.chainId !== this.selectedChainId) {diff --git a/workers/longcat/Dockerfile b/workers/longcat/Dockerfilenew file mode 100644index 000000000..23a389ee9--- /dev/null+++ b/workers/longcat/Dockerfile@@ -0,0 +1,71 @@+# ── Stage: base ────────────────────────────────────────────────────────────────+# CUDA 12.4 matches LongCat's torch==2.6.0+cu124 requirement.+# L4 GPU on Cloud Run (24 GB VRAM) runs Avatar-1.5 with INT8 quantization+# (~14 GB footprint at inference time).+FROM nvidia/cuda:12.4.1-cudnn-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ DEBIAN_FRONTEND=noninteractive \+ PIP_NO_CACHE_DIR=1 \+ HF_HUB_DISABLE_PROGRESS_BARS=1++# ── System dependencies ────────────────────────────────────────────────────────+RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget ffmpeg \+ libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \+ libgomp1 libsndfile1 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++# ── Clone LongCat repo ─────────────────────────────────────────────────────────+RUN git clone --depth=1 https://github.com/meituan-longcat/LongCat-Video.git /longcat++# ── Install PyTorch first (cu124 wheel) ────────────────────────────────────────+RUN pip install torch==2.6.0 torchvision torchaudio \+ --index-url https://download.pytorch.org/whl/cu124++# ── Install FlashAttention-2 pre-built wheel ───────────────────────────────────+# Build from source is ~30 min; use the pre-built cu124 + sm89 wheel for L4.+RUN pip install flash-attn==2.7.4.post1 --no-build-isolation++# ── Install LongCat model requirements (minus torch, minus flash-attn) ─────────+RUN pip install \+ numpy==1.26.4 \+ transformers==4.41.0 \+ loguru==0.7.2 \+ diffusers==0.35.1 \+ einops==0.8.0 \+ ftfy==6.2.0 \+ psutil==6.0.0 \+ av==12.0.0 \+ opencv-python-headless==4.9.0.80 \+ imageio==2.37.0 \+ imageio-ffmpeg==0.6.0 \+ librosa==0.11.0 \+ soundfile==0.13.1++# ── Install service requirements ───────────────────────────────────────────────+COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++# ── App code ───────────────────────────────────────────────────────────────────+WORKDIR /app+COPY main.py /app/main.py++# Model weights are NOT baked into the image (13.6 B params = ~27 GB bf16 /+# ~14 GB int8). They are downloaded at first startup into WEIGHTS_DIR, which+# should be a Cloud Run volume mount backed by a persistent GCS bucket so+# subsequent cold starts reuse the cached weights.++EXPOSE 8080++# Single worker — GPU is not re-entrant across processes.+CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "600"]diff --git a/workers/longcat/README.md b/workers/longcat/README.mdnew file mode 100644index 000000000..65a5dc485--- /dev/null+++ b/workers/longcat/README.md@@ -0,0 +1,114 @@+# LongCat Video Avatar Worker++FastAPI service running LongCat-Video-Avatar-1.5 on Cloud Run (NVIDIA L4 GPU).+Accepts a reference image + audio URL, generates a lip-synced talking avatar video,+and stores the MP4 in Cloud Storage.++Model: [meituan-longcat/LongCat-Video-Avatar-1.5](https://huggingface.co/meituan-longcat/LongCat-Video-Avatar-1.5) — MIT license.++## API++```+POST /generate { image_url, audio_url, prompt?, job_id? }+ → 202 { job_id, status: "queued" }++GET /jobs/:id → { job_id, status, video_url?, error?, updated_at }++GET /health → { ok, model_loaded, resolution }+```++Auth: `Authorization: Bearer <API_KEY>` on every request.++## Prerequisites++```bash+# 1. Enable GCP APIs+gcloud services enable \+ run.googleapis.com \+ cloudbuild.googleapis.com \+ artifactregistry.googleapis.com \+ storage.googleapis.com \+ firestore.googleapis.com \+ secretmanager.googleapis.com++# 2. Artifact Registry repo+gcloud artifacts repositories create longcat-video-avatar \+ --repository-format=docker \+ --location=us-central1++# 3. GCS bucket for output MP4s+gcloud storage buckets create gs://three-ws-avatar-videos \+ --location=us-central1 \+ --uniform-bucket-level-access++# Make videos publicly readable+gcloud storage buckets add-iam-policy-binding gs://three-ws-avatar-videos \+ --member=allUsers \+ --role=roles/storage.objectViewer++# 4. GCS bucket for model weights (mounted as a volume at /weights)+gcloud storage buckets create gs://three-ws-longcat-weights \+ --location=us-central1 \+ --uniform-bucket-level-access++# 5. Firestore (native mode, if not already created)+gcloud firestore databases create --location=us-central1++# 6. API key secret+echo -n "$(openssl rand -hex 32)" | \+ gcloud secrets create longcat-video-avatar-key \+ --data-file=-++# 7. Pre-download model weights into the weights bucket (one-time, ~14 GB INT8)+# Run from a machine with Python + huggingface_hub installed:+python - <<'EOF'+from huggingface_hub import snapshot_download+import subprocess, pathlib++local = pathlib.Path("/tmp/longcat-weights/LongCat-Video-Avatar")+snapshot_download(+ "meituan-longcat/LongCat-Video-Avatar-1.5",+ local_dir=str(local),+ ignore_patterns=["*.pt"],+)+EOF+gcloud storage cp -r /tmp/longcat-weights/LongCat-Video-Avatar \+ gs://three-ws-longcat-weights/LongCat-Video-Avatar+```++## Deploying++```bash+# From repo root+gcloud builds submit \+ --config workers/longcat/cloudbuild.yaml \+ --substitutions _GCS_BUCKET=three-ws-avatar-videos,_WEIGHTS_BUCKET=three-ws-longcat-weights+```++After deploy, copy the Cloud Run service URL and API key to Vercel:++```bash+# Get the service URL+gcloud run services describe longcat-video-avatar \+ --region=us-central1 \+ --format='value(status.url)'++# Get the API key value+gcloud secrets versions access latest --secret=longcat-video-avatar-key++# Set in Vercel+vercel env add LONGCAT_WORKER_URL production+vercel env add LONGCAT_WORKER_KEY production+```++## Cost estimate (us-central1 L4 GPU)++| SKU | Rate | 30-day idle (min=1) |+|-----------------------|------------|---------------------|+| L4 GPU | ~$0.70/hr | ~$504/month |+| 8 vCPU | ~$0.24/hr | ~$173/month |+| 32 GB RAM | ~$0.08/hr | ~$58/month |+| GCS egress (videos) | $0.12/GB | depends on volume |++With $100k credits this runs for ~130 months at idle. Inference per video+(720p, 8-step distilled): ~2–4 minutes on L4.diff --git a/workers/longcat/cloudbuild.yaml b/workers/longcat/cloudbuild.yamlnew file mode 100644index 000000000..6678f0cbd--- /dev/null+++ b/workers/longcat/cloudbuild.yaml@@ -0,0 +1,84 @@+# Cloud Build pipeline: build the longcat-video-avatar Docker image and deploy+# it to Cloud Run (GPU) in us-central1.+#+# Substitution variables (override via --substitutions flag or trigger config):+# _REGION — Cloud Run region (default: us-central1)+# _SERVICE — Cloud Run service name (default: longcat-video-avatar)+# _REPO — Artifact Registry repo name (default: longcat-video-avatar)+# _GCS_BUCKET — Cloud Storage bucket for output MP4s+# _WEIGHTS_BUCKET — GCS bucket holding pre-downloaded model weights+# _MIN_INSTANCES — minimum warm instances (default: 1)+# _MAX_INSTANCES — maximum instances (default: 2)+#+# Required secrets in Secret Manager (must exist before first deploy):+# longcat-video-avatar-key — the API_KEY bearer secret++substitutions:+ _REGION: us-central1+ _SERVICE: longcat-video-avatar+ _REPO: longcat-video-avatar+ _GCS_BUCKET: three-ws-avatar-videos+ _WEIGHTS_BUCKET: three-ws-longcat-weights+ _MIN_INSTANCES: "1"+ _MAX_INSTANCES: "2"++steps:+ # ── Build ──────────────────────────────────────────────────────────────────+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/longcat+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ # ── Push ───────────────────────────────────────────────────────────────────+ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ # ── Deploy to Cloud Run ────────────────────────────────────────────────────+ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --port=8080+ # GPU: NVIDIA L4 (24 GB VRAM) — Avatar-1.5 INT8 fits at ~14 GB+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --cpu=8+ - --memory=32Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ # Inference timeout: up to 10 min for 720p generation+ - --timeout=600+ - --allow-unauthenticated+ # GCS volume mount for persistent model weights — avoids re-downloading+ # 14 GB on every cold start. The weights bucket must be pre-populated+ # (see README.md for the one-time download command).+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},FIRESTORE_PROJECT=$PROJECT_ID,RESOLUTION=720p,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=longcat-video-avatar-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/longcat/main.py b/workers/longcat/main.pynew file mode 100644index 000000000..ec9fc60e6--- /dev/null+++ b/workers/longcat/main.py@@ -0,0 +1,296 @@+"""+LongCat Video Avatar service — audio-driven talking avatar video generation.++ POST /generate { image_url, audio_url, prompt?, job_id? }+ → 202 { job_id, status: "queued" }++ GET /jobs/:id → { job_id, status, video_url?, error?, updated_at }++ GET /health → { ok, model_loaded }++Environment variables (all required unless noted):+ API_KEY — shared bearer secret (set via GCP Secret Manager)+ GCS_BUCKET — Cloud Storage bucket for output MP4s+ FIRESTORE_PROJECT — GCP project hosting Firestore+ WEIGHTS_DIR — path to LongCat model weights (default: /weights)+ LONGCAT_REPO_DIR — path to cloned LongCat repo (default: /longcat)+ MAX_CONCURRENT — parallel inference jobs (default: 1; GPU-bound)+ RESOLUTION — 480p or 720p (default: 720p)+"""++from __future__ import annotations++import asyncio+import json+import logging+import os+import shutil+import subprocess+import tempfile+import traceback+import uuid+from contextlib import asynccontextmanager+from datetime import datetime, timezone+from pathlib import Path++import httpx+from fastapi import BackgroundTasks, FastAPI, HTTPException, Header+from google.cloud import firestore, storage+from pydantic import BaseModel++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("main")++# ── config ─────────────────────────────────────────────────────────────────────++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+FIRESTORE_PROJECT = os.environ["FIRESTORE_PROJECT"]+WEIGHTS_DIR = Path(os.environ.get("WEIGHTS_DIR", "/weights"))+LONGCAT_REPO_DIR = Path(os.environ.get("LONGCAT_REPO_DIR", "/longcat"))+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))+RESOLUTION = os.environ.get("RESOLUTION", "720p")++WEIGHTS_SUBDIR = WEIGHTS_DIR / "LongCat-Video-Avatar"++# ── global state ───────────────────────────────────────────────────────────────++_db: firestore.Client | None = None+_bucket: storage.Bucket | None = None+_job_sem: asyncio.Semaphore | None = None+_http: httpx.AsyncClient | None = None+++# ── lifespan ───────────────────────────────────────────────────────────────────++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _db, _bucket, _job_sem, _http++ _job_sem = asyncio.Semaphore(MAX_CONCURRENT)+ _http = httpx.AsyncClient(follow_redirects=True, timeout=300)++ _db = firestore.Client(project=FIRESTORE_PROJECT)+ _bucket = storage.Client().bucket(GCS_BUCKET)++ if not WEIGHTS_SUBDIR.exists():+ log.warning(+ "Model weights not found at %s — downloading from HuggingFace Hub...",+ WEIGHTS_SUBDIR,+ )+ _download_weights()+ else:+ log.info("Model weights found at %s", WEIGHTS_SUBDIR)++ log.info(+ "Server ready — resolution=%s, max_concurrent=%d, weights=%s",+ RESOLUTION, MAX_CONCURRENT, WEIGHTS_SUBDIR,+ )+ yield++ await _http.aclose()+++def _download_weights() -> None:+ WEIGHTS_DIR.mkdir(parents=True, exist_ok=True)+ subprocess.run(+ [+ "python", "-c",+ (+ "from huggingface_hub import snapshot_download; "+ "snapshot_download("+ " 'meituan-longcat/LongCat-Video-Avatar-1.5',"+ f" local_dir='{WEIGHTS_SUBDIR}',"+ " ignore_patterns=['*.pt']"+ ")"+ ),+ ],+ check=True,+ )+ log.info("Weights downloaded to %s", WEIGHTS_SUBDIR)+++app = FastAPI(title="longcat-video-avatar", lifespan=lifespan)+++# ── auth ───────────────────────────────────────────────────────────────────────++def _require_api_key(authorization: str) -> None:+ if not authorization.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="missing bearer token")+ if authorization[len("Bearer "):].strip() != API_KEY:+ raise HTTPException(status_code=401, detail="invalid api key")+++# ── Firestore helpers ──────────────────────────────────────────────────────────++def _set_job(job_id: str, data: dict) -> None:+ _db.collection("longcat_video_jobs").document(job_id).set(+ {**data, "updated_at": datetime.now(timezone.utc)},+ merge=True,+ )+++def _get_job(job_id: str) -> dict | None:+ doc = _db.collection("longcat_video_jobs").document(job_id).get()+ return doc.to_dict() if doc.exists else None+++# ── inference worker ───────────────────────────────────────────────────────────++async def _process_job(+ job_id: str,+ image_url: str,+ audio_url: str,+ prompt: str,+) -> None:+ async with _job_sem:+ _set_job(job_id, {"status": "running"})+ workdir = Path(tempfile.mkdtemp(prefix=f"longcat_{job_id}_"))+ try:+ log.info("[%s] downloading inputs", job_id)++ image_path = workdir / "ref_image.png"+ audio_path = workdir / "audio.wav"+ output_dir = workdir / "output"+ output_dir.mkdir()++ await _download_file(image_url, image_path)+ await _download_file(audio_url, audio_path)++ config = {+ "prompt": prompt,+ "cond_image": str(image_path),+ "cond_audio": {"person1": str(audio_path)},+ }+ config_path = workdir / "config.json"+ config_path.write_text(json.dumps(config))++ log.info("[%s] starting inference", job_id)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(+ None,+ lambda: _run_inference(job_id, config_path, output_dir),+ )++ # Find the generated MP4+ mp4_files = list(output_dir.glob("**/*.mp4"))+ if not mp4_files:+ raise RuntimeError("No MP4 output found after inference")+ mp4_path = mp4_files[0]++ log.info("[%s] uploading %d bytes to GCS", job_id, mp4_path.stat().st_size)+ blob_name = f"avatar-videos/{job_id}.mp4"+ blob = _bucket.blob(blob_name)+ blob.content_type = "video/mp4"+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_filename(str(mp4_path)),+ )+ video_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ _set_job(job_id, {"status": "done", "video_url": video_url})+ log.info("[%s] done → %s", job_id, video_url)++ except Exception:+ err = traceback.format_exc()+ log.exception("[%s] pipeline failed", job_id)+ _set_job(job_id, {"status": "failed", "error": err})++ finally:+ shutil.rmtree(workdir, ignore_errors=True)+++def _run_inference(job_id: str, config_path: Path, output_dir: Path) -> None:+ cmd = [+ "torchrun",+ "--nproc_per_node=1",+ "run_demo_avatar_single_audio_to_video.py",+ "--input_json", str(config_path),+ "--output_dir", str(output_dir),+ "--checkpoint_dir", str(WEIGHTS_SUBDIR),+ "--resolution", RESOLUTION,+ "--model_type", "avatar-v1.5",+ "--use_distill",+ "--use_int8",+ "--num_inference_steps", "8",+ ]+ log.info("[%s] cmd: %s", job_id, " ".join(cmd))+ result = subprocess.run(+ cmd,+ cwd=str(LONGCAT_REPO_DIR),+ capture_output=True,+ text=True,+ timeout=3600,+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"torchrun failed (exit {result.returncode}):\n"+ f"stdout: {result.stdout[-4000:]}\n"+ f"stderr: {result.stderr[-4000:]}"+ )+++async def _download_file(url: str, dest: Path) -> None:+ async with _http.stream("GET", url) as r:+ r.raise_for_status()+ with dest.open("wb") as f:+ async for chunk in r.aiter_bytes(65536):+ f.write(chunk)+++# ── routes ─────────────────────────────────────────────────────────────────────++class GenerateRequest(BaseModel):+ image_url: str+ audio_url: str+ prompt: str = "A person talking naturally."+ job_id: str | None = None++[email protected]("/generate", status_code=202)+async def generate(+ body: GenerateRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ job_id = body.job_id or str(uuid.uuid4())+ _set_job(job_id, {+ "job_id": job_id,+ "status": "queued",+ "image_url": body.image_url,+ "audio_url": body.audio_url,+ "prompt": body.prompt,+ "created_at": datetime.now(timezone.utc),+ })+ background_tasks.add_task(+ _process_job, job_id, body.image_url, body.audio_url, body.prompt,+ )+ return {"job_id": job_id, "status": "queued"}++[email protected]("/jobs/{job_id}")+async def get_job(job_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ job = _get_job(job_id)+ if job is None:+ raise HTTPException(status_code=404, detail="job not found")+ for k, v in job.items():+ if hasattr(v, "isoformat"):+ job[k] = v.isoformat()+ return job++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "pipeline": "longcat-avatar-1.5",+ "model_loaded": WEIGHTS_SUBDIR.exists(),+ "weights_dir": str(WEIGHTS_SUBDIR),+ "resolution": RESOLUTION,+ }diff --git a/workers/longcat/requirements.txt b/workers/longcat/requirements.txtnew file mode 100644index 000000000..dd417ddb0--- /dev/null+++ b/workers/longcat/requirements.txt@@ -0,0 +1,9 @@+# Service dependencies (LongCat model deps installed separately in Dockerfile+# from the cloned repo's requirements.txt)+fastapi==0.115.12+uvicorn[standard]==0.34.2+httpx==0.28.1+google-cloud-firestore==2.20.1+google-cloud-storage==2.19.0+huggingface-hub==0.30.2+pydantic==2.11.3