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: discover detail, footer bot, home/marketplace UI, pay page, x402-pay, prompts
nirholas3470a38054f3
diff --git a/.gitignore b/.gitignoreindex 370b8154a..b9d86083a 100644--- a/.gitignore+++ b/.gitignore@@ -55,6 +55,7 @@ test-mint.jsonwww-vanity.jsontest-coin-metadata.jsonscripts/x402-genwallets.mjs+scripts/pump-usdc-race.mjs# Wallet / private-key material — NEVER commit*.privkey.txt@@ -66,3 +67,6 @@ x402-test-wallets/pump-sdk-case-study.html.claude/scheduled_tasks.lockthreews-launch-week-case-study.html++# Temp working directories+.tmp/diff --git a/api/discover-detail.js b/api/discover-detail.jsnew file mode 100644index 000000000..42d2c4014--- /dev/null+++ b/api/discover-detail.js@@ -0,0 +1,286 @@+/**+ * SSR entry-point for discover detail pages+ * -----------------------------------------+ * GET /api/discover-detail?kind=onchain&chain=<id>&id=<agentId>+ * GET /api/discover-detail?kind=avatar&id=<avatarId>+ *+ * Wired to /discover/a/:chainId/:agentId and /discover/avatar/:id via vercel.json.+ *+ * Returns the detail.html shell with Open Graph + Twitter Card meta tags already+ * baked into the <head>, so link unfurlers (Slack, Discord, X, iMessage) get a+ * real preview. Browsers receive the same HTML; the inline __DETAIL_ITEM__ data+ * lets detail.js render without a second API round-trip.+ */++import { sql } from './_lib/db.js';+import { cors, wrap } from './_lib/http.js';+import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';+import { publicUrl } from './_lib/r2.js';+import { DEMO_AVATARS } from './_lib/demo-avatars.js';+import { env } from './_lib/env.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const kind = url.searchParams.get('kind');+ const id = url.searchParams.get('id');+ const origin = env.APP_ORIGIN;++ let item = null;+ let canonicalUrl = origin;+ let ogImageUrl = `${origin}/og-image.png`;++ if (kind === 'onchain') {+ const chainId = parseInt(url.searchParams.get('chain') || '', 10);+ if (!Number.isFinite(chainId) || !id) return sendShell(res, origin, null, null, null);++ const rows = await sql`+ SELECT chain_id, agent_id, owner, name, description, image, glb_url,+ has_3d, x402_support, registered_at, registered_tx,+ services, agent_uri+ FROM erc8004_agents_index+ WHERE active = true AND chain_id = ${chainId} AND agent_id = ${parseInt(id, 10)}+ LIMIT 1+ `.catch(() => []);++ if (rows.length) {+ const r = rows[0];+ const chain = CHAIN_BY_ID[r.chain_id];+ item = {+ kind: 'onchain',+ chainId: r.chain_id,+ chainName: chain?.name || `Chain ${r.chain_id}`,+ explorerBase: chain?.explorer || null,+ agentId: r.agent_id,+ owner: r.owner,+ ownerShort: shortAddr(r.owner),+ name: r.name || `Agent #${r.agent_id}`,+ description: r.description || '',+ image: r.image || null,+ glbUrl: r.glb_url || null,+ has3d: r.has_3d,+ x402Support: r.x402_support,+ registeredAt: r.registered_at,+ registeredTx: r.registered_tx || null,+ tokenExplorerUrl: tokenExplorerUrl(r.chain_id, r.agent_id),+ ownerExplorerUrl: addressExplorerUrl(r.chain_id, r.owner),+ viewerUrl: r.glb_url ? `/#model=${encodeURIComponent(r.glb_url)}` : null,+ services: (r.services || []).map((s) => ({+ name: s?.name || null,+ endpoint: s?.endpoint || null,+ version: s?.version || null,+ })),+ };+ canonicalUrl = `${origin}/discover/a/${chainId}/${id}`;+ ogImageUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(id)}`;+ }+ } else if (kind === 'avatar') {+ if (!id) return sendShell(res, origin, null, null, null);++ // Demo avatar+ const demo = DEMO_AVATARS.find((a) => String(a.avatarId) === String(id));+ if (demo) {+ item = demo;+ } else {+ const rows = await sql`+ SELECT a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,+ a.tags, a.created_at, a.source,+ coalesce(a.featured, false) AS featured,+ coalesce(a.view_count, 0) AS view_count,+ u.username AS owner_username,+ u.display_name AS owner_display_name,+ u.wallet_address AS owner_wallet+ FROM avatars a+ LEFT JOIN users u ON u.id = a.owner_id AND u.deleted_at IS NULL+ WHERE a.deleted_at IS NULL AND a.visibility = 'public' AND a.id = ${id}+ LIMIT 1+ `.catch(() => []);++ if (rows.length) {+ const r = rows[0];+ const glb = publicUrl(r.storage_key);+ const handle = r.owner_username+ ? `@${r.owner_username}`+ : r.owner_wallet+ ? shortAddr(r.owner_wallet)+ : null;+ item = {+ kind: 'avatar',+ avatarId: r.id,+ slug: r.slug,+ name: r.name,+ description: r.description || '',+ image: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,+ glbUrl: glb,+ has3d: true,+ tags: r.tags || [],+ source: r.source || null,+ featured: r.featured === true || r.featured === 't',+ viewCount: Number(r.view_count) || 0,+ createdAt: r.created_at,+ viewerUrl: `/#model=${encodeURIComponent(glb)}`,+ author: handle+ ? {+ handle,+ displayName: r.owner_display_name || r.owner_username || handle,+ profileUrl: r.owner_username ? `/u/${r.owner_username}` : null,+ }+ : null,+ };+ }+ }++ if (item) {+ canonicalUrl = `${origin}/discover/avatar/${id}`;+ ogImageUrl = `${origin}/api/avatar/${id}/og`;+ }+ }++ return sendShell(res, origin, item, canonicalUrl, ogImageUrl);+});++function sendShell(res, origin, item, canonicalUrl, ogImageUrl) {+ const title = item ? `${item.name} · three.ws` : 'three.ws';+ const desc = item?.description || (item ? `${item.name} on three.ws` : 'Discover agents on three.ws');+ const canonical = canonicalUrl || `${origin}/discover`;+ const ogImg = ogImageUrl || `${origin}/og-image.png`;++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', item+ ? 'public, max-age=60, s-maxage=300, stale-while-revalidate=3600'+ : 'public, max-age=10',+ );++ res.end(`<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>${esc(title)}</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="${esc(desc)}" />+ <meta name="theme-color" content="#000000" />++ <meta property="og:type" content="profile" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="${esc(title)}" />+ <meta property="og:description" content="${esc(desc)}" />+ <meta property="og:url" content="${esc(canonical)}" />+ <meta property="og:image" content="${esc(ogImg)}" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />++ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="${esc(title)}" />+ <meta name="twitter:description" content="${esc(desc)}" />+ <meta name="twitter:image" content="${esc(ogImg)}" />++ <link rel="canonical" href="${esc(canonical)}" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/discover/detail.css" />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet" />+ ${item ? `<script>window.__DETAIL_ITEM__ = ${JSON.stringify(item).replace(/</g, '\\u003c')};</script>` : ''}+</head>+<body class="features-page detail-page">+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main class="detail-main" data-role="main">+ <div class="detail-loading" data-role="loading">+ <div class="detail-skeleton detail-skeleton--hero"></div>+ <div class="detail-skeleton detail-skeleton--title"></div>+ <div class="detail-skeleton detail-skeleton--body"></div>+ </div>++ <div class="detail-error" data-role="error" hidden>+ <div class="detail-error-icon">⚠</div>+ <h2 data-role="error-title">Not found</h2>+ <p data-role="error-msg">This item could not be loaded.</p>+ <a href="/discover" class="detail-btn">← Back to Discover</a>+ </div>++ <div class="detail-content" data-role="content" hidden>+ <nav class="detail-breadcrumb">+ <a href="/discover" class="detail-breadcrumb-link" data-role="back-link">← Discover</a>+ </nav>++ <div class="detail-hero">+ <div class="detail-hero-media" data-role="hero-media"></div>+ <div class="detail-hero-body">+ <div class="detail-badges" data-role="badges"></div>+ <h1 class="detail-name" data-role="name"></h1>+ <p class="detail-desc" data-role="desc" hidden></p>+ <div class="detail-meta-row" data-role="meta-row"></div>+ <div class="detail-actions" data-role="actions"></div>+ </div>+ </div>++ <div class="detail-viewer-wrap" data-role="viewer-wrap" hidden>+ <div class="detail-section-label">3D Preview</div>+ <div class="detail-viewer" data-role="viewer"></div>+ </div>++ <div class="detail-panels">+ <div class="detail-panel" data-role="services-panel" hidden>+ <div class="detail-panel-head">+ <span class="detail-panel-title">Services</span>+ <span class="detail-panel-badge" data-role="service-count">0</span>+ </div>+ <ul class="detail-services" data-role="services"></ul>+ </div>++ <div class="detail-panel" data-role="tags-panel" hidden>+ <div class="detail-panel-head">+ <span class="detail-panel-title">Tags</span>+ </div>+ <div class="detail-tags" data-role="tags"></div>+ </div>++ <div class="detail-panel" data-role="onchain-panel" hidden>+ <div class="detail-panel-head">+ <span class="detail-panel-title">On-chain details</span>+ </div>+ <dl class="detail-dl" data-role="onchain-dl"></dl>+ </div>++ <div class="detail-panel" data-role="avatar-panel" hidden>+ <div class="detail-panel-head">+ <span class="detail-panel-title">Details</span>+ </div>+ <dl class="detail-dl" data-role="avatar-dl"></dl>+ </div>++ <div class="detail-panel" data-role="embed-panel" hidden>+ <div class="detail-panel-head">+ <span class="detail-panel-title">Embed</span>+ </div>+ <div class="detail-embed-tabs" data-role="embed-tabs"></div>+ <div class="detail-embed-panes" data-role="embed-panes"></div>+ </div>+ </div>+ </div>+ </main>++ <script type="module" src="/discover/detail.js"></script>+</body>+</html>`);+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function shortAddr(a) {+ if (!a || a.length < 10) return a || '';+ return `${a.slice(0, 6)}…${a.slice(-4)}`;+}diff --git a/api/wk.js b/api/wk.jsindex af9d1c330..2eaa16652 100644--- a/api/wk.js+++ b/api/wk.js@@ -157,6 +157,7 @@ function handleX402(req, res) {200,{...body,+ schemes: ['pump-agent-payments', 'x402', 'x402-v2'],pump_agent_payments: {prep: '/api/pump/accept-payment-prep',confirm: '/api/pump/accept-payment-confirm',diff --git a/api/x402-pay.js b/api/x402-pay.jsindex d3311caf2..52f081ecf 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -31,7 +31,7 @@ import {import bs58 from 'bs58';import { Redis } from '@upstash/redis';-import { cors, json, readJson, wrap } from './_lib/http.js';+import { cors, json, readJson, wrap, error } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import {paymentRequirements,@@ -41,6 +41,9 @@ import {} from './_lib/x402-spec.js';import { dispatch } from './_mcp/dispatch.js';import { env } from './_lib/env.js';+import { sql } from './_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';+import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';// ---- Persistent feed of recent paid calls -------------------------------// Backed by Upstash Redis when available; falls back to an in-memory ring@@ -119,6 +122,73 @@ async function readCall(tx) {return memCalls.get(tx) || null;}+// ---- User auth + agent wallet loading ----------------------------------++async function requireAuth(req) {+ try {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ } catch {}+ return null;+}++async function loadAgentKeypairForUser(agentId, userId) {+ const [row] = await sql`+ SELECT id, meta FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL+ `;+ if (!row) return null;+ const enc = row.meta?.encrypted_solana_secret;+ if (!enc) return null;+ return recoverSolanaAgentKeypair(enc, {+ agentId,+ userId,+ reason: 'x402_pay_tool_call',+ });+}++async function getAgentsForUser(userId) {+ const rows = await sql`+ SELECT id, name, description, avatar_id, meta+ FROM agent_identities+ WHERE user_id = ${userId} AND deleted_at IS NULL+ ORDER BY created_at ASC+ `;+ const conn = new Connection(SOLANA_RPC, 'confirmed');+ return Promise.all(rows.map(async (row) => {+ const address = row.meta?.solana_address || null;+ const source = row.meta?.solana_wallet_source || null;+ let usdc = null;+ let sol = null;+ if (address) {+ try {+ const lamports = await conn.getBalance(new PublicKey(address));+ sol = lamports / 1e9;+ } catch {}+ try {+ const ata = getAssociatedTokenAddressSync(+ new PublicKey(USDC_MAINNET_MINT),+ new PublicKey(address), false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const acct = await conn.getTokenAccountBalance(ata);+ usdc = Number(acct.value.uiAmount || 0);+ } catch {}+ }+ return {+ id: row.id,+ name: row.name,+ description: row.description,+ avatar_id: row.avatar_id,+ solana_address: address,+ solana_wallet_source: source,+ usdc,+ sol,+ };+ }));+}+function summarizeArgs(args) {if (!args || typeof args !== 'object') return '';if (args.url) {@@ -255,8 +325,8 @@ function sseSend(res, event, data) {res.write(`data: ${JSON.stringify(data)}\n\n`);}-async function runFlow({ tool, args, emit }) {- const buyer = loadAgentKeypair();+async function runFlow({ tool, args, emit, buyer: buyerOverride }) {+ const buyer = buyerOverride ?? loadAgentKeypair();const conn = new Connection(SOLANA_RPC, 'confirmed');const requirements = paymentRequirements();@@ -378,6 +448,12 @@ export default wrap(async (req, res) => {if (!record) return json(res, 404, { error: 'call_not_found' });return json(res, 200, record);}+ if (u.searchParams.get('agents') === '1') {+ const auth = await requireAuth(req);+ if (!auth) return json(res, 401, { error: 'authentication_required' });+ const agents = await getAgentsForUser(auth.userId);+ return json(res, 200, { agents });+ }return json(res, 404, { error: 'not_found' });}if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });@@ -405,6 +481,18 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'invalid_tool', allowed: [...ALLOWED_TOOLS] });}+ // Resolve payer: agent wallet (agentId + authed) or shared showcase wallet.+ let buyer;+ if (input.agentId) {+ const auth = await requireAuth(req);+ if (!auth) return json(res, 401, { error: 'authentication_required' });+ const kp = await loadAgentKeypairForUser(String(input.agentId), auth.userId);+ if (!kp) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });+ buyer = kp;+ } else {+ buyer = loadAgentKeypair();+ }+const wantsStream =(req.headers.accept || '').includes('text/event-stream') ||input.stream === true;@@ -413,7 +501,7 @@ export default wrap(async (req, res) => {sseInit(res);const emit = (ev, data) => sseSend(res, ev, data);try {- await runFlow({ tool, args, emit });+ await runFlow({ tool, args, emit, buyer });} catch (err) {emit('error', {ok: false,@@ -434,7 +522,7 @@ export default wrap(async (req, res) => {else if (ev === 'error') errEnv = data;};try {- await runFlow({ tool, args, emit });+ await runFlow({ tool, args, emit, buyer });} catch (err) {errEnv = { ok: false, error: err.message || 'flow_failed', mcpError: err.mcpError || null };}diff --git a/footer.css b/footer.cssindex c1b233ca6..0519281bd 100644--- a/footer.css+++ b/footer.css@@ -103,11 +103,13 @@filter: grayscale(1) drop-shadow(0 0 18px rgba(255, 255, 255, 0.30));}-.h-footer-avatar model-viewer {+.h-footer-avatar model-viewer,+.h-footer-avatar canvas {width: 100%;height: 100%;background: transparent;--poster-color: transparent;+ display: block;}.h-footer-cta {diff --git a/home.css b/home.cssindex e452bf0e0..4b573f784 100644--- a/home.css+++ b/home.css@@ -298,6 +298,10 @@position: relative;min-height: 360px;background: rgba(255, 255, 255, 0.02);+ /* isolate compositing layer so WebGL canvas renders correctly inside the+ CSS 3D perspective context on .home-parallax */+ will-change: transform;+ transform: translateZ(0);}.h-bento-visual model-viewer {@@ -2842,3 +2846,60 @@display: none;}}++/* ── prefers-reduced-motion ──────────────────────────────────────────────── */+/*+ * Users who request reduced motion (vestibular disorders, slow devices, battery+ * saver) get: no looping animations, instant transitions, no parallax.+ * WebGL viewers are still shown but stop auto-rotating (handled in JS).+ */+@media (prefers-reduced-motion: reduce) {+ /* kill ALL CSS animations and transitions site-wide */+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ scroll-behavior: auto !important;+ }++ /* reveal elements immediately — no fade/slide in */+ .h-reveal {+ opacity: 1;+ transform: none;+ }++ /* hide the star canvas entirely — it's decorative */+ .h-star-canvas {+ display: none;+ }++ /* flatten the CSS scroll-driven parallax layers */+ .h-layer {+ transform: none !important;+ }++ /* stop the hero avatar scroll-based float */+ .h-avatar-wrap {+ animation: none !important;+ }++ /* stop ambient glow / mesh drift */+ .h-hero-mesh,+ .h-hero-glow-a,+ .h-hero-glow-b,+ .h-hero-haze {+ animation: none !important;+ }++ /* stop the floor scroll ribbon */+ .h-floor-ribbon {+ animation: none !important;+ }++ /* stop the status dot pulse */+ .h-status-dot::before {+ animation: none !important;+ }+}diff --git a/home.html b/home.htmlindex e21d0d7ba..8c3ed10d4 100644--- a/home.html+++ b/home.html@@ -720,6 +720,15 @@</main><script>+ // Devices with < 2 GB RAM get no WebGL viewers — avoids GPU OOM and+ // context-limit issues. navigator.deviceMemory is undefined on Firefox/Safari+ // so we default to "capable" when the API is absent.+ const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;+ const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ // Hero viewer is always created (above fold), but we skip all below-fold+ // viewers on constrained devices.+ const SKIP_OFFSCREEN_GL = LOW_MEMORY || REDUCED_MOTION;+// Scroll reveal — use viewport (root: null) so IntersectionObserver// avoids the perspective transform on .home-parallax breaking intersection math.(function () {@@ -856,7 +865,6 @@node.scale.setScalar(2.5);}}- console.log('[cz node]', node.name, node.type);});viewer._modelFocusY = 1.1;viewer.setOrbit(curTheta, curPhi, curR);@@ -943,6 +951,7 @@setTimeout(() => whenReady(cb), 60);}+ function initAct2() {whenReady(() => {const viewer = new window.Act2Viewer(canvas);@@ -1003,6 +1012,19 @@viewer.zoom(wider ? FAR : NEAR);});});+ }++ if (!SKIP_OFFSCREEN_GL) {+ let act2Inited = false;+ const act2Obs = new IntersectionObserver((entries) => {+ if (entries[0].isIntersecting && !act2Inited) {+ act2Inited = true;+ act2Obs.disconnect();+ initAct2();+ }+ }, { threshold: 0.05 });+ act2Obs.observe(canvas);+ }})();// Bento Viewer card — same Act2Viewer + animation panel as Act 2@@ -1017,7 +1039,8 @@setTimeout(() => whenReady(cb), 60);}- whenReady(() => {+ function initViewer() {+ whenReady(() => {const viewer = new window.Act2Viewer(canvas, { fov: 20 });function prettyLabel(def) {@@ -1071,7 +1094,22 @@);});}- });+ });+ }++ // Defer viewer init until canvas scrolls into view — avoids creating+ // WebGL context before the card is visible inside the parallax container.+ if (!SKIP_OFFSCREEN_GL) {+ let inited = false;+ const io = new IntersectionObserver((entries) => {+ if (entries[0].isIntersecting && !inited) {+ inited = true;+ io.disconnect();+ initViewer();+ }+ }, { threshold: 0.05 });+ io.observe(canvas);+ }})();// Chain ribbon (Act 3)@@ -1105,7 +1143,7 @@// Custom cursor(function () {const cursor = document.getElementById('cursor');- if (!cursor || window.matchMedia('(hover: none)').matches) return;+ if (!cursor || window.matchMedia('(hover: none)').matches || REDUCED_MOTION) return;let cx = -100,cy = -100,tx = -100,@@ -1149,17 +1187,33 @@setTimeout(() => whenReady(cb), 60);}- whenReady(() => {- configs.forEach(({ id, src, anim }) => {- const canvas = document.getElementById(id);- if (!canvas) return;- const viewer = new window.Act2Viewer(canvas, { fov: 22 });- viewer- .loadModel(src)- .then(() => viewer.playClip(anim).catch(() => {}))- .catch(() => {});+ function initAct3() {+ whenReady(() => {+ configs.forEach(({ id, src, anim }) => {+ const canvas = document.getElementById(id);+ if (!canvas) return;+ const viewer = new window.Act2Viewer(canvas, { fov: 22 });+ viewer+ .loadModel(src)+ .then(() => viewer.playClip(anim).catch(() => {}))+ .catch(() => {});+ });});- });+ }++ // Observe the first Act3 canvas; when it enters view, init all three.+ const firstCanvas = document.getElementById('act3-avatar-a');+ if (firstCanvas && !SKIP_OFFSCREEN_GL) {+ let act3Inited = false;+ const act3Obs = new IntersectionObserver((entries) => {+ if (entries[0].isIntersecting && !act3Inited) {+ act3Inited = true;+ act3Obs.disconnect();+ initAct3();+ }+ }, { threshold: 0.05 });+ act3Obs.observe(firstCanvas);+ }})();// Star field canvasdiff --git a/marketplace.css b/marketplace.cssindex 2d1c94cfd..fba9af132 100644--- a/marketplace.css+++ b/marketplace.css@@ -370,6 +370,155 @@ body.market-page {cursor: pointer;}+/* ── Avatar deep-link detail page ────────────────────────────────────── */++.market-avatar-detail {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+}+.market-avatar-detail-inner {+ max-width: 1200px;+ margin: 0 auto;+ padding: 0 24px 80px;+}+.market-avatar-detail-layout {+ display: grid;+ grid-template-columns: 1fr 380px;+ gap: 32px;+ min-height: 520px;+ padding: 8px 0 32px;+}+@media (max-width: 900px) {+ .market-avatar-detail-layout {+ grid-template-columns: 1fr;+ min-height: 0;+ }+}+.market-avatar-detail-stage {+ position: relative;+ background: linear-gradient(180deg, #0a0a0c 0%, #0d0d10 100%);+ border: 1px solid var(--mk-border);+ border-radius: 20px;+ overflow: hidden;+ min-height: 420px;+}+.market-avatar-detail-stage model-viewer {+ width: 100%;+ height: 100%;+ position: absolute;+ inset: 0;+ --poster-color: transparent;+ opacity: 0;+ transition: opacity 0.5s ease;+}+.market-avatar-detail-stage.mv-ready model-viewer { opacity: 1; }++/* Loading bar inside stage */+.avatar-detail-load-wrap {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ pointer-events: none;+ transition: opacity 0.3s;+}+.market-avatar-detail-stage.mv-ready .avatar-detail-load-wrap { opacity: 0; }+.avatar-detail-load-bar-outer {+ width: 160px;+ height: 2px;+ background: rgba(255,255,255,0.08);+ border-radius: 999px;+ overflow: hidden;+}+.avatar-detail-load-bar {+ height: 100%;+ width: 0;+ background: linear-gradient(90deg, #a78bfa, #6366f1);+ border-radius: 999px;+ transition: width 0.2s;+}+.avatar-detail-load-label {+ font-size: 11px;+ color: var(--mk-text-3);+ letter-spacing: 0.04em;+}++/* Right column meta */+.market-avatar-detail-meta {+ display: flex;+ flex-direction: column;+ gap: 14px;+ padding-top: 8px;+}+.market-avatar-detail-name {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 28px;+ font-weight: 700;+ color: var(--mk-text);+ margin: 0;+ line-height: 1.1;+ word-break: break-word;+}+.market-avatar-detail-author {+ font-size: 13px;+ color: var(--mk-text-3);+ margin: 0;+}+.market-avatar-detail-author a { color: var(--mk-text-2); text-decoration: none; }+.market-avatar-detail-author a:hover { color: var(--mk-text); text-decoration: underline; }+.market-avatar-detail-desc {+ font-size: 14px;+ color: var(--mk-text-2);+ line-height: 1.55;+ margin: 0;+}+.market-avatar-detail-pills {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}+.market-avatar-detail-actions {+ display: flex;+ flex-direction: column;+ gap: 10px;+ margin-top: 4px;+}+.market-avatar-detail-cta {+ background: var(--mk-text);+ color: var(--mk-bg);+ border: 0;+ padding: 13px 20px;+ border-radius: 12px;+ font-weight: 700;+ font-size: 14px;+ cursor: pointer;+ text-align: left;+ transition: opacity 0.15s;+}+.market-avatar-detail-cta:hover { opacity: 0.88; }+.market-avatar-detail .btn-secondary {+ display: block;+ background: var(--mk-panel);+ color: var(--mk-text-2);+ border: 1px solid var(--mk-border-2);+ padding: 11px 16px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 500;+ text-align: center;+ text-decoration: none;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+}+.market-avatar-detail .btn-secondary:hover { background: var(--mk-panel-2); color: var(--mk-text); }++/* Similar avatars */+.market-avatar-detail-similar { margin-top: 12px; }+/* ── Detail ──────────────────────────────────────────────────────────── */.market-detail {diff --git a/marketplace.html b/marketplace.htmlindex aadfbeb2a..a2e855548 100644--- a/marketplace.html+++ b/marketplace.html@@ -23,6 +23,12 @@rel="stylesheet"/><style>+ /* Author display rules on modal overlays override the UA stylesheet's+ [hidden] { display: none } default, so `<div … hidden>` was still+ rendering as a grid/flex container — taking up body-grid cells and+ blocking page scroll. Force display:none whenever hidden is set. */+ [hidden] { display: none !important; }+.market-wip-banner {display: flex;align-items: center;@@ -1421,6 +1427,48 @@<script src="/src/marketplace.js" type="module"></script>+ <!-- Avatar deep-link detail page — mirrors market-detail for agents -->+ <section class="market-avatar-detail" id="market-avatar-detail" hidden aria-label="Avatar detail">+ <div class="market-avatar-detail-inner">+ <button class="market-back" id="avatar-detail-back" aria-label="Back to marketplace">←</button>+ <div class="market-avatar-detail-layout">+ <!-- Left: interactive 3D stage -->+ <div class="market-avatar-detail-stage" id="avatar-detail-stage">+ <div class="avatar-detail-load-wrap" id="avatar-detail-load-wrap">+ <div class="avatar-detail-load-bar-outer">+ <div class="avatar-detail-load-bar" id="avatar-detail-load-bar"></div>+ </div>+ <span class="avatar-detail-load-label">Loading 3D…</span>+ </div>+ </div>+ <!-- Right: meta + actions -->+ <aside class="market-avatar-detail-meta">+ <div class="market-detail-eyebrow">Community Avatar</div>+ <h1 class="market-avatar-detail-name" id="avatar-detail-name">—</h1>+ <p class="market-avatar-detail-author" id="avatar-detail-author"></p>+ <p class="market-avatar-detail-desc" id="avatar-detail-desc"></p>+ <div class="market-avatar-detail-pills" id="avatar-detail-pills"></div>+ <div class="market-avatar-detail-actions">+ <button class="btn-primary market-avatar-detail-cta" id="avatar-detail-use">+ Start agent with this avatar →+ </button>+ <a class="btn-secondary" id="avatar-detail-view" href="#" target="_blank" rel="noopener">+ Open in 3D viewer ↗+ </a>+ <a class="btn-secondary" id="avatar-detail-download" href="#">+ Download GLB+ </a>+ </div>+ </aside>+ </div>+ <!-- Similar avatars grid -->+ <div class="market-avatar-detail-similar" id="avatar-detail-similar-wrap" hidden>+ <h2 class="market-section-heading">Similar avatars</h2>+ <div class="market-grid" id="avatar-detail-similar-grid"></div>+ </div>+ </div>+ </section>+<!-- Avatar Detail Modal --><div class="avatar-modal-overlay" id="avatar-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="avatar-modal-title"><div class="avatar-modal" role="document">diff --git a/prompts/prompt-1-asset-compression.md b/prompts/prompt-1-asset-compression.mdnew file mode 100644index 000000000..0f8ba52e3--- /dev/null+++ b/prompts/prompt-1-asset-compression.md@@ -0,0 +1,96 @@+# Task: GLB Asset Compression Pipeline++## Project overview++This is a Three.js / Vite app at `/workspaces/3D-Agent`. It renders 3D avatars and animations for an AI agent marketplace. The frontend stack is vanilla JS modules + Vite (`npm run dev` on port 3000). Backend is Vercel functions in `api/`. All 3D work uses Three.js (latest) with GLB/GLTF assets.++## Problem++The avatar GLB files served to browsers are **uncompressed**. Sizes today:++- `public/avatars/default.glb` — 2.8 MB+- `public/avatars/cz.glb` — 2.1 MB+- `public/animations/soldier.glb` — 2.1 MB+- `public/animations/robotexpressive.glb` — 454 KB+- `rider/assets/avatars/cz.glb` — copy of above+- `rider/assets/avatars/soldier.glb` — copy of above+- `rider/assets/avatars/default.glb` — copy of above+- `rider/assets/avatars/robotexpressive.glb` — copy of above++EXT_meshopt_compression typically achieves **10–15× compression** on avatar geometry. Draco achieves 40–60%. The project already has `@gltf-transform/core` and `@gltf-transform/extensions` in `package.json` (versions ^4.3.0). The `@gltf-transform/functions` package is not yet installed. Neither is the CLI.++The main viewer (`src/viewer.js`) already has Draco + KTX2 + MeshoptDecoder wired via `getDecoders()` in `src/viewer/internal.js` — so compressed GLBs will decompress automatically when loaded there. The marketplace lobby (`src/marketplace-lobby.js`) uses a bare `GLTFLoader` with no decoders (that is fixed in a separate task); the compression script must therefore produce **meshopt-compressed** output (not Draco-only), because meshopt is the decoder already imported in the main viewer and the lobby task will add it too.++## What to implement++### 1. Install required packages++```bash+npm install --save-dev @gltf-transform/functions @gltf-transform/cli meshoptimizer+```++`meshoptimizer` is the native WASM backing for gltf-transform's meshopt encoder.++### 2. Create `scripts/compress-glbs.mjs`++Write a Node ESM script that:++1. Accepts an optional list of GLB paths as CLI args. If none provided, defaults to compressing every `.glb` file under `public/` and `rider/assets/` (recursive, excluding `dist/`).+2. For each GLB:+ a. Reads the file with `@gltf-transform/core` `NodeIO`.+ b. Applies the following transforms **in order** using `@gltf-transform/functions`:+ - `dedup()` — deduplicate accessors and textures+ - `prune()` — remove unused nodes, skins, textures+ - `resample()` — resample animation curves to remove redundant keyframes+ - `quantize()` — quantize vertex attributes (position, normal, texcoord) to reduce precision to what's perceptually lossless+ - `meshopt({ encoder: MeshoptEncoder })` — apply EXT_meshopt_compression+ - `textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 })` if `sharp` is available; otherwise skip texture compression with a console.warn (do not throw)+ c. Writes the result back to the **same path**, overwriting the original.+ d. Logs: original size, compressed size, % reduction, and whether the file grew (which would indicate something went wrong — warn and skip writing in that case).+3. At the end, prints a summary table of all files processed.++Use `MeshoptEncoder` from `meshoptimizer/meshopt_encoder.js` (the ESM export). The encoder must be initialized with `await MeshoptEncoder.ready` before use.++**Do not use `sharp`** — skip the `textureCompress` step entirely for now (it requires a native binary and adds CI complexity). Leave a `// TODO: add textureCompress once sharp is added to devDependencies` comment.++### 3. Add an npm script in `package.json`++Add to the `"scripts"` block:++```json+"compress:glbs": "node scripts/compress-glbs.mjs"+```++### 4. Run the compression++Run `npm run compress:glbs` and let it process all GLBs in `public/` and `rider/assets/`. Print the before/after sizes for each file. If any file grows in size, skip writing it and log a warning.++### 5. Update `.gitignore` if needed++The compressed GLBs replace the originals in-place, so no `.gitignore` change is needed. But add a comment near the GLB section of `.gitignore` (if one exists) noting that GLBs are committed in compressed form.++### 6. Verify the main viewer still loads avatars correctly++- Run `npm run dev`+- Open `http://localhost:3000` in a browser+- Confirm the default avatar loads and animates without console errors+- Confirm the network tab shows the compressed GLB sizes (should be significantly smaller)+- Check that morph targets (facial expressions) still work — the Empathy Layer in `src/agent-avatar.js` drives them++## Constraints++- Do not modify any `.js` source files in `src/` — this is purely an asset pipeline task.+- Do not remove the original FBX files in `public/animations/` — they are source files used by the build pipeline, not served to browsers.+- The animation clips in `public/animations/clips/*.json` are pre-retargeted JSON data, not GLBs — do not touch them.+- The script must be idempotent: running it twice on already-compressed files should result in files of similar or smaller size, not growth.+- Use `NodeIO` from `@gltf-transform/core` for all file I/O — do not use raw `fs.readFileSync` on GLBs.+- The script must be pure ESM (`.mjs` extension, `import` statements, no `require`).++## Definition of done++- `npm run compress:glbs` runs without errors.+- `public/avatars/default.glb` and `public/avatars/cz.glb` are measurably smaller (at minimum 20% smaller; expect 50–80%).+- `npm run dev` starts successfully.+- The avatar renders in the browser with no console errors.+- The morph-target empathy layer (eye squint, mouth smile, brow raise) still visually responds to agent events.+- `git diff --stat` shows only the compressed GLB binaries changed plus `package.json`, `package-lock.json`, and the new script file.diff --git a/prompts/prompt-2-lobby-performance.md b/prompts/prompt-2-lobby-performance.mdnew file mode 100644index 000000000..3246c1fc2--- /dev/null+++ b/prompts/prompt-2-lobby-performance.md@@ -0,0 +1,179 @@+# Task: Marketplace Lobby 3D Performance++## Project overview++This is a Three.js / Vite app at `/workspaces/3D-Agent`. It renders an AI agent marketplace with a 3D lobby scene showing 3–5 featured avatars on circular podiums with mouse-parallax and click-to-select. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000).++## File to modify++**`src/marketplace-lobby.js`** — the entire lobby is self-contained in this one file (275 lines). Read it fully before making changes.++## Current problems++1. **No decoder support**: The lobby uses a bare `new GLTFLoader()` with no Draco, KTX2, or meshopt decoders. After asset compression (a separate task), the avatar GLBs will use EXT_meshopt_compression. Without the decoder wired in, compressed GLBs will fail to load silently.++2. **Naive raycasting**: The `onClick` handler calls `raycaster.intersectObjects(slotsRoot.children, true)` which walks every triangle of every avatar mesh on every click. On complex skinned meshes (2–5 avatars, each 5k–20k triangles), this is expensive.++3. **No `powerPreference`**: The WebGLRenderer is constructed without `powerPreference: 'high-performance'` — on laptops with discrete GPUs this defaults to the integrated GPU.++4. **PMREMGenerator not disposed after setup**: `pmrem.fromScene(...)` is called once for the environment, but `pmrem` is only disposed inside `dispose()`. This is correct but `pmremGenerator.dispose()` should also be called right after the environment texture is generated (the PMREMGenerator is not needed after that point — keeping it alive wastes GPU memory).++5. **No animation loop visibility guard**: The RAF loop runs even when the canvas is off-screen (e.g. user scrolls down on the marketplace page). This wastes CPU/GPU on invisible frames.++## Existing decoder infrastructure to reuse++The project has a shared `getDecoders()` function in `src/viewer/internal.js` that lazily initialises DRACOLoader + KTX2Loader + MeshoptDecoder (all memoised — calling it multiple times returns the same Promise). Import and use this instead of setting up decoders from scratch.++```js+// src/viewer/internal.js exports:+export function getDecoders() {+ // Returns Promise<{ dracoLoader, ktx2Loader, meshoptDecoder }>+}+```++## What to implement++### 1. Install three-mesh-bvh++```bash+npm install three-mesh-bvh+```++### 2. Wire decoders into the lobby's GLTFLoader++Replace the current loader setup in `mountLobby`:++**Before** (line 106–107):+```js+const loader = new GLTFLoader();+slots.forEach((avatar, i) => {+```++**After**: call `getDecoders()` before starting the avatar load loop, then create the loader with all three decoders. The load loop must not start until the decoders are ready:++```js+import { getDecoders } from './viewer/internal.js';++// Inside mountLobby, after the podium/slot setup:+const { dracoLoader, ktx2Loader, meshoptDecoder } = await getDecoders();+const loader = new GLTFLoader()+ .setDRACOLoader(dracoLoader)+ .setKTX2Loader(ktx2Loader.detectSupport(renderer))+ .setMeshoptDecoder(meshoptDecoder);++slots.forEach((avatar, i) => {+ // ... load loop unchanged ...+});+```++`mountLobby` is already `async` so the `await` is fine.++### 3. Add BVH-accelerated raycasting++Install and use `three-mesh-bvh` to accelerate the click raycaster.++When each avatar GLB finishes loading, compute a BVH for every mesh geometry in it:++```js+import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';+import { Mesh } from 'three';++// Patch Three.js Mesh prototype once (at module top level, outside mountLobby):+Mesh.prototype.raycast = acceleratedRaycast;++// Inside the GLTFLoader onLoad callback, after fitToHeight():+root.traverse((node) => {+ if (node.isMesh && node.geometry) {+ node.geometry.computeBoundsTree();+ }+});+```++Update the `dispose()` function to also clean up BVH data:++```js+scene.traverse((obj) => {+ if (obj.geometry) {+ obj.geometry.disposeBoundsTree?.();+ obj.geometry.dispose?.();+ }+ // ... existing material dispose ...+});+```++### 4. Fix PMREMGenerator disposal++Right after generating the environment texture, dispose the PMREMGenerator immediately:++```js+scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+pmrem.dispose(); // done — GPU memory freed+```++Remove `pmrem.dispose()` from the `dispose()` function at the bottom (it will already be disposed).++### 5. Add `powerPreference` to the renderer++```js+const renderer = new WebGLRenderer({+ canvas,+ antialias: true,+ alpha: true,+ powerPreference: 'high-performance',+});+```++### 6. Add IntersectionObserver visibility guard++Pause the render loop when the canvas is not visible in the viewport (saves GPU on scroll):++```js+let visible = true;+const io = new IntersectionObserver(+ ([entry]) => { visible = entry.isIntersecting; },+ { threshold: 0.01 }+);+io.observe(canvas);++function tick() {+ if (!alive) return;+ rafId = requestAnimationFrame(tick);+ if (!visible) return; // skip render, keep RAF alive for when it returns+ // ... rest of tick ...+}+```++In `dispose()`, add `io.disconnect()`.++### 7. Antialias decision based on DPR++On high-DPR displays (≥ 2×), MSAA antialias is nearly free because the display already downsamples. On low-DPR displays it's expensive. The lobby already caps DPR at 2, which is correct. No change needed — just verify the existing cap is kept.++## Import additions required at top of file++```js+import { getDecoders } from './viewer/internal.js';+import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';+import { Mesh } from 'three'; // Mesh is already imported — just add to existing import+```++`Mesh` is already in the import block — add `acceleratedRaycast` patch at module top level.++## Constraints++- Do not break the existing `onSelect` callback contract — click-to-select must still fire `onSelect(avatar, index)`.+- Do not change the visual appearance of the scene (lighting, fog, podium geometry, camera angles).+- The `dispose()` function must remain complete — no GPU resource leaks. All new resources (BVH data, IntersectionObserver) must be cleaned up there.+- `mountLobby` signature stays identical: `async function mountLobby(canvas, avatars, options = {})`.+- Do not add any loading spinner or placeholder UI — the podiums already render before GLBs resolve.+- All imports must resolve correctly with the Vite bundler (no CommonJS `require`).++## Definition of done++- `npm install` runs without errors (three-mesh-bvh added to package.json).+- `npm run dev` starts on port 3000 with no console errors.+- Navigate to the marketplace page — the 3D lobby loads, avatars appear on podiums.+- Clicking an avatar still fires `onSelect`.+- Network tab shows: if compressed GLBs are present, they load successfully (meshopt decoder wired). If uncompressed, they load as before.+- `git diff src/marketplace-lobby.js` shows only the changes described above — no unrelated modifications.+- No TypeErrors or import errors in the browser console.diff --git a/prompts/prompt-3-bvh-main-viewer.md b/prompts/prompt-3-bvh-main-viewer.mdnew file mode 100644index 000000000..32afbfd3c--- /dev/null+++ b/prompts/prompt-3-bvh-main-viewer.md@@ -0,0 +1,116 @@+# Task: BVH-Accelerated Raycasting in Main Viewer++## Project overview++This is a Three.js / Vite app at `/workspaces/3D-Agent`. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000). The main 3D viewer is `src/viewer.js` (~1,720 lines). It loads GLB/GLTF avatars and 3D models, handles OrbitControls, animation playback, morph targets, and environment setup.++## Problem++All raycasting in the viewer (hit-testing for click interactions, AR placement, annotation picking) uses Three.js's default brute-force triangle intersection — it checks every triangle of every mesh in the scene on every raycast. On a complex avatar (5k–20k triangles, skinned mesh) this is slow, especially when:++- The user clicks to inspect model annotations+- The avatar page does hover hit-testing for interactive zones+- The validator page raycast-samples mesh surface for quality checks++`three-mesh-bvh` wraps Three.js's raycasting system with a Bounding Volume Hierarchy, cutting raycast time from O(n triangles) to O(log n). The integration is a drop-in patch — no call sites change.++## Current raycasting call sites in `src/viewer.js`++Search for `Raycaster` and `intersectObject` in the file to confirm locations. The viewer uses `THREE.Raycaster` through OrbitControls (which calls it internally) and potentially through `_onDblClick`. The BVH patch operates at the `Mesh.prototype.raycast` level so it accelerates **all** raycasting site-wide without touching individual call sites.++## What to implement++### 1. Install three-mesh-bvh++```bash+npm install three-mesh-bvh+```++(If it was already installed by a prior task, `npm install` is a no-op — check `package.json` first.)++### 2. Patch Mesh.prototype.raycast at module top level in `src/viewer.js`++At the top of `src/viewer.js`, after the existing Three.js imports, add:++```js+import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';+import { Mesh } from 'three';++// Accelerate all Three.js raycasting site-wide — must run before any Mesh is created.+Mesh.prototype.raycast = acceleratedRaycast;+```++This is the recommended integration pattern from the three-mesh-bvh README. It patches the prototype once; every `Mesh` in the scene automatically uses BVH raycasting after this.++### 3. Compute BVH after model content is set++In `src/viewer.js`, find the `setContent(object, clips)` method. After the content is added to the scene and before the method returns, traverse the object and compute BVH for every geometry:++```js+// After scene.add(object) and before the final state updates in setContent():+object.traverse((node) => {+ if (node.isMesh && node.geometry) {+ // computeBoundsTree mutates geometry in place; safe to call every load+ node.geometry.computeBoundsTree();+ }+});+```++The exact location: find the line where `this.content` is assigned and the object is added to the scene (around line 750–800 in `setContent`). Place the traversal immediately after `this.scene.add(object)` (or wherever the content is attached).++### 4. Dispose BVH data when content is cleared++In `src/viewer.js`, find the `clear()` method (or wherever `this.content` is removed from the scene and disposed). Add BVH disposal:++```js+// Inside the content disposal block — wherever geometry.dispose() is called:+this.content?.traverse((node) => {+ if (node.isMesh && node.geometry) {+ node.geometry.disposeBoundsTree?.();+ }+});+```++This must run **before** `geometry.dispose()` is called, because `disposeBoundsTree` references the geometry's internal arrays.++### 5. Handle skinned meshes correctly++Skinned meshes (avatars with bone animation) use `SkinnedMesh`, which extends `Mesh`. BVH works on the **rest-pose geometry** — it does not account for bone deformation. This is acceptable for click/hover hit-testing on avatars because:+- The bounding volume of the rest pose is a conservative approximation of the animated pose+- False negatives are rare (slightly missing a click near the edge of an animated limb)+- The alternative (brute-force) is much slower++No special handling required — the patch applies equally to `Mesh` and `SkinnedMesh`.++### 6. Handle non-indexed geometries++`computeBoundsTree()` works on both indexed and non-indexed geometries. If a geometry has no index, three-mesh-bvh handles it correctly. No special casing needed.++## Files to modify++- `src/viewer.js` — three changes: import patch at top, `computeBoundsTree` call in `setContent`, `disposeBoundsTree` call in content clear.++## Files to read before editing++Read `src/viewer.js` fully before making changes, particularly:+- The import block at the top (to insert the new import correctly)+- The `setContent(object, clips)` method — find where `this.content` is assigned and `this.scene.add(object)` happens+- The content disposal / `clear()` logic — find where `geometry.dispose()` is called for old content++## Constraints++- Do not modify any call sites — the prototype patch handles everything globally.+- Do not add BVH to the skybox, environment meshes, or helper meshes (AxesHelper, GridHelper, SkeletonHelper). These are not raycasted by user interaction. To avoid wasting memory, only compute BVH for `node.isMesh && node.geometry && !node.isHelper`.+ - Check: `AxesHelper`, `GridHelper`, `SkeletonHelper` set `isHelper = true` on their child objects — use that flag.+ - Simplest safe check: only process nodes where `node.geometry.attributes.position` exists and `node.geometry.attributes.position.count > 0`.+- Do not change OrbitControls, camera, lighting, animation, or any other viewer behaviour.+- The patch must not break the existing morph-target system (`src/agent-avatar.js` drives morph targets every frame — BVH does not touch morph target influences, so there is no conflict).++## Definition of done++- `npm install` completes without errors (three-mesh-bvh in package.json).+- `npm run dev` starts on port 3000.+- Load an avatar in the viewer — no console errors, avatar renders and animates.+- Click the avatar — the interaction fires (if there is one). No raycasting errors.+- `git diff src/viewer.js` shows only the three changes described: import, computeBoundsTree traversal, disposeBoundsTree traversal.+- No other files modified.diff --git a/prompts/prompt-4-postprocessing.md b/prompts/prompt-4-postprocessing.mdnew file mode 100644index 000000000..5f72f348c--- /dev/null+++ b/prompts/prompt-4-postprocessing.md@@ -0,0 +1,219 @@+# Task: Replace Three.js Post-Processing with pmndrs/postprocessing++## Project overview++This is a Three.js / Vite app at `/workspaces/3D-Agent`. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000). The main viewer is `src/viewer.js` (~1,720 lines). The marketplace lobby is `src/marketplace-lobby.js` (275 lines).++## What this task does++**@pmndrs/postprocessing** is a post-processing library built specifically for Three.js. Compared to Three.js's built-in `EffectComposer` (from `three/addons/postprocessing/`), it:++1. **Merges shader passes** — multiple effects (bloom, vignette, depth-of-field) compile into a single fullscreen shader program instead of N separate render passes. This is a significant performance win.+2. **Correct alpha compositing** — the library handles alpha output correctly, which matters for the avatar viewer where the canvas background is transparent.+3. **Selective bloom via layers** — objects can be assigned to a bloom layer (Three.js Layer system) so only specific objects (e.g. podium rings, avatar outline glow) bloom, not the whole scene.++The current codebase does **not** use any post-processing. This task adds it to both the main viewer and the marketplace lobby, enabling selective bloom on avatar podium rings and a subtle vignette on the main viewer.++## Part A: Main Viewer (`src/viewer.js`)++### Install++```bash+npm install postprocessing+```++The package name is `postprocessing` (npm) — the import is also `import { ... } from 'postprocessing'`.++### Add to `src/viewer.js`++#### Step 1 — Import at top of file++```js+import {+ EffectComposer,+ RenderPass,+ BloomEffect,+ VignetteEffect,+ EffectPass,+ SelectiveBloomEffect,+} from 'postprocessing';+```++Do not import `EffectComposer` from `three/addons` — the `postprocessing` package provides its own.++#### Step 2 — Create composer after renderer setup++In the `Viewer` constructor, after `this.renderer` is set up and `this.scene` / `this.defaultCamera` exist, add:++```js+this._composer = new EffectComposer(this.renderer);+this._renderPass = new RenderPass(this.scene, this.defaultCamera);+this._composer.addPass(this._renderPass);++// Subtle vignette — darkens edges, focuses attention on avatar center+const vignetteEffect = new VignetteEffect({ eskil: false, offset: 0.35, darkness: 0.4 });++// Bloom — low intensity, wide radius, for specular highlights on metallic avatars+const bloomEffect = new BloomEffect({+ intensity: 0.6,+ luminanceThreshold: 0.8, // only pixels brighter than 80% luminance bloom+ luminanceSmoothing: 0.05,+ mipmapBlur: true, // faster than the default multi-pass blur+});++this._effectPass = new EffectPass(this.defaultCamera, bloomEffect, vignetteEffect);+this._effectPass.renderToScreen = true;+this._composer.addPass(this._effectPass);+```++#### Step 3 — Replace `renderer.render()` calls with `composer.render()`++Search `src/viewer.js` for every call to `this.renderer.render(`. Replace each one with `this._composer.render()`. The composer internally calls `renderer.render(scene, camera)` for you via the `RenderPass`.++**Exception**: The screenshot / capture methods (`takeScreenshot`, `captureScreenshot` in `src/viewer/screenshot.js`) should keep using `this.renderer.render(...)` directly — they write to a separate canvas and compositing there would add noise. Leave those untouched.++**Exception**: The axes renderer (a secondary `WebGLRenderer` for the mini axes display) — this is a separate renderer, leave it alone.++#### Step 4 — Update camera when active camera changes++The `RenderPass` and `EffectPass` reference the camera. When `this.activeCamera` is updated (search for `this.activeCamera =` in the file), also update the passes:++```js+// Wherever this.activeCamera is reassigned:+this.activeCamera = newCamera;+this._renderPass.mainCamera = newCamera;+this._effectPass.mainCamera = newCamera;+```++#### Step 5 — Handle resize++In the resize handler (wherever `this.renderer.setSize` is called), also resize the composer:++```js+this.renderer.setSize(width, height);+this._composer.setSize(width, height);+```++#### Step 6 — Dispose in viewer cleanup++In the `dispose()` or `destroy()` method of the viewer, add:++```js+this._composer?.dispose();+```++## Part B: Marketplace Lobby (`src/marketplace-lobby.js`)++The lobby already renders a custom Three.js scene with the glowing podium ring material. Add selective bloom to make the ring's emissive glow actually appear to bloom without blooming the avatars.++### Three.js Layer system for selective bloom++Three.js has a built-in layer system (`Object3D.layers`). By default every object is on layer 0. Put objects that should bloom on layer 1.++#### Step 1 — Import from postprocessing++Add to imports at top of `marketplace-lobby.js`:++```js+import {+ EffectComposer,+ RenderPass,+ SelectiveBloomEffect,+ EffectPass,+} from 'postprocessing';+```++#### Step 2 — Create composer in `mountLobby`++After the renderer is set up:++```js+const composer = new EffectComposer(renderer);+const renderPass = new RenderPass(scene, camera);+composer.addPass(renderPass);++// Selective bloom — only objects on layer 1 bloom+const bloomEffect = new SelectiveBloomEffect(scene, camera, {+ intensity: 1.8,+ luminanceThreshold: 0.05,+ luminanceSmoothing: 0.3,+ mipmapBlur: true,+ selection: [], // will be populated when podiums are created+});++const effectPass = new EffectPass(camera, bloomEffect);+effectPass.renderToScreen = true;+composer.addPass(effectPass);+```++#### Step 3 — Assign bloom layer to podium rings++In `makePodium()`, after creating the `ring` mesh, assign it to layer 1 and add it to the bloom selection:++```js+ring.layers.enable(1);+```++Return the ring mesh from `makePodium()` so `mountLobby` can add it to `bloomEffect.selection`. Change `makePodium()` signature to return `{ group, ring }` and collect all rings:++```js+const bloomSelection = [];++const slotMeta = slots.map((_, i) => {+ const x = startX + i * SLOT_SPACING;+ const { group: podium, ring } = makePodium();+ podium.position.set(x, 0, 0);+ podiumGroup.add(podium);+ bloomSelection.push(ring);+ // ...+});++bloomEffect.selection.set(bloomSelection);+```++#### Step 4 — Replace `renderer.render()` in the tick loop++```js+// Before:+renderer.render(scene, camera);++// After:+composer.render();+```++#### Step 5 — Handle resize++```js+function resize() {+ // ... existing ...+ renderer.setSize(width, height, false);+ composer.setSize(width, height);+ // ...+}+```++#### Step 6 — Dispose in `dispose()`++```js+composer.dispose();+```++## Constraints++- **Do not change the visual feel** of the scene beyond adding bloom glow to emissive surfaces. Bloom intensity should be conservative — this is a professional avatar marketplace, not a game. If bloom makes the scene look garish, reduce `intensity`.+- **Do not add depth-of-field** — it causes motion sickness on interactive 3D and does not apply here.+- **Screenshot capture** paths in the viewer must continue to work — they use `renderer.render()` directly and must not be changed.+- **The lobby's `dispose()` function** must clean up all new resources (composer, effect pass). No GPU leaks.+- **The `makePodium` function signature change** must not break anything — it is only called within `mountLobby`.+- All imports must work with Vite's ESM bundler. `postprocessing` ships ES modules — no special Vite config should be needed.+- Do not change any existing lighting, geometry, camera, or control logic.++## Definition of done++- `npm install` runs without errors (`postprocessing` in package.json).+- `npm run dev` starts on port 3000.+- Main viewer: load an avatar — it renders with a subtle vignette darkening the edges. No bloom on the avatar body (luminance threshold is set above normal surface brightness). Specular highlights on metallic parts may show mild bloom.+- Marketplace lobby: podium rings show a soft cyan glow/bloom around them. Avatar meshes do not bloom.+- No console errors in either scene.+- Screenshot / capture functionality in the main viewer still produces a clean image.+- `git diff` shows only `src/viewer.js`, `src/marketplace-lobby.js`, `package.json`, `package-lock.json`.diff --git a/public/discover/detail.js b/public/discover/detail.jsindex 23238dedd..7b27cd37c 100644--- a/public/discover/detail.js+++ b/public/discover/detail.js@@ -13,6 +13,8 @@ function parseRoute() {}async function fetchItem(route) {+ // SSR handler may have pre-loaded the item to avoid a round-trip+ if (window.__DETAIL_ITEM__) return window.__DETAIL_ITEM__;const params = new URLSearchParams({ kind: route.kind, id: route.id });if (route.kind === 'onchain') params.set('chain', route.chainId);const res = await fetch(`/api/explore-item?${params}`);@@ -21,6 +23,21 @@ async function fetchItem(route) {return data.item;}+// Derive a smart back URL: restore the referrer if it was the discover page so+// filters and search state are not lost.+function backUrl() {+ try {+ const ref = document.referrer;+ if (ref) {+ const u = new URL(ref);+ if (u.hostname === location.hostname && u.pathname === '/discover') {+ return ref; // preserves ?q=, ?chain=, etc.+ }+ }+ } catch (_) { /* ignore */ }+ return '/discover';+}+function escapeHtml(s) {return String(s ?? '').replace(/&/g, '&')@@ -52,6 +69,10 @@ function render(item) {const metaDesc = document.querySelector('meta[name="description"]');if (metaDesc) metaDesc.content = item.description || `${item.name} on three.ws`;+ // Smart back link+ const backEl = $('back-link');+ if (backEl) backEl.href = backUrl();+// Hero mediaconst media = $('hero-media');if (item.image) {@@ -121,24 +142,23 @@ function render(item) {}// 3D viewer- if (item.has3d && item.glbUrl) {+ if (item.has3d) {const viewerWrap = $('viewer-wrap');viewerWrap.hidden = false;const viewer = $('viewer');- if (item.kind === 'onchain') {- // Use agent-3d web component for ERC-8004 agents- const script = document.createElement('script');- script.type = 'module';- script.src = LIB_CDN_URL;- document.head.appendChild(script);+ const script = document.createElement('script');+ script.type = 'module';+ script.src = LIB_CDN_URL;+ document.head.appendChild(script);+ if (item.kind === 'onchain' && item.chainId && item.agentId) {const agentUri = `agent://${item.chainId}/${item.agentId}`;viewer.innerHTML = `<agent-3d src="${escapeAttr(agentUri)}" mode="inline" responsive style="width:100%;height:100%"></agent-3d>`;- } else {- // Avatar: use iframe embed of the 3D viewer- const embedSrc = `${location.origin}/#model=${encodeURIComponent(item.glbUrl)}`;- viewer.innerHTML = `<iframe src="${escapeAttr(embedSrc)}" allow="autoplay; xr-spatial-tracking" allowfullscreen></iframe>`;+ } else if (item.kind === 'avatar' && item.avatarId) {+ // Use /api/avatars/:id — the agent-3d component resolves it as a manifest+ const apiSrc = `${location.origin}/api/avatars/${encodeURIComponent(item.avatarId)}`;+ viewer.innerHTML = `<agent-3d src="${escapeAttr(apiSrc)}" mode="inline" responsive style="width:100%;height:100%"></agent-3d>`;}}@@ -184,9 +204,7 @@ function render(item) {const txUrl = item.explorerBase ? `${item.explorerBase}/tx/${item.registeredTx}` : '#';rows.push(['Reg. tx', `<a href="${escapeAttr(txUrl)}" target="_blank" rel="noopener">${escapeHtml(shortAddr(item.registeredTx))}</a>`]);}- dl.innerHTML = rows- .map(([k, v]) => `<dt>${escapeHtml(k)}</dt><dd>${v}</dd>`)- .join('');+ dl.innerHTML = rows.map(([k, v]) => `<dt>${escapeHtml(k)}</dt><dd>${v}</dd>`).join('');}// Avatar details panel@@ -252,7 +270,14 @@ function buildEmbedPanel(item, $) {} else {const detailUrl = `${origin}/discover/avatar/${item.avatarId}`;const name = item.name || 'Avatar';+ const apiSrc = `${origin}/api/avatars/${item.avatarId}`;snippets = [+ {+ label: 'Web component',+ key: 'wc',+ value: `<script type="module" src="${LIB_CDN_URL}"></script>\n<agent-3d src="${apiSrc}" mode="inline" width="480px" responsive></agent-3d>`,+ rows: 3,+ },{label: 'iframe',key: 'iframe',@@ -302,7 +327,7 @@ function buildEmbedPanel(item, $) {const btn = e.target.closest('.detail-embed-copy');if (!btn) return;const key = btn.dataset.copyKey;- const textarea = panesEl.querySelector(`[data-pane="${key}"] textarea, [data-pane="${key}"] input`);+ const textarea = panesEl.querySelector(`[data-pane="${key}"] textarea`);if (!textarea) return;navigator.clipboard.writeText(textarea.value).then(() => {const orig = btn.textContent;diff --git a/public/discover/discover.js b/public/discover/discover.jsindex be9714ff9..add768318 100644--- a/public/discover/discover.js+++ b/public/discover/discover.js@@ -318,7 +318,7 @@ function renderOnchainCard(item) {</a><div class="explore-card-body"><div class="explore-card-head">- <a class="explore-card-name" href="${escapeAttr(detailUrl)}" style="text-decoration:none;color:inherit">${escapeHtml(item.name)}</a>+ <h3 class="explore-card-name"><a class="explore-card-name-link" href="${escapeAttr(detailUrl)}">${escapeHtml(item.name)}</a></h3><span class="explore-card-id">#${escapeHtml(item.agentId)}</span></div><div class="explore-card-badges">${badges.join('')}</div>@@ -371,7 +371,7 @@ function renderAvatarCard(item) {</a><div class="explore-card-body"><div class="explore-card-head">- <a class="explore-card-name" href="${escapeAttr(detailUrl)}" style="text-decoration:none;color:inherit">${escapeHtml(item.name)}</a>+ <h3 class="explore-card-name"><a class="explore-card-name-link" href="${escapeAttr(detailUrl)}">${escapeHtml(item.name)}</a></h3></div><div class="explore-card-badges">${badges.join('')}</div>${item.description ? `<p class="explore-card-desc">${escapeHtml(item.description)}</p>` : ''}diff --git a/public/fluid-particles.js b/public/fluid-particles.jsindex 5108e0ebe..0afd5a99f 100644--- a/public/fluid-particles.js+++ b/public/fluid-particles.js@@ -216,6 +216,12 @@ void main(){const canvas = document.getElementById('home-fluid-canvas');if (!canvas) return;+ /* skip entirely for users who prefer no motion */+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {+ canvas.style.display = 'none';+ return;+ }+/* particle count: fewer on low-end / mobile */const mobile = innerWidth < 768;const lowTier = navigator.hardwareConcurrency <= 4;diff --git a/public/footer.html b/public/footer.htmlindex 60b789705..6b69edda7 100644--- a/public/footer.html+++ b/public/footer.html@@ -4,21 +4,7 @@<div class="h-footer-haze" aria-hidden="true"></div><div class="h-footer-watermark" aria-hidden="true">three.ws</div><div class="h-footer-avatar" aria-hidden="true">- <model-viewer- src="/animations/robotexpressive.glb"- auto-rotate- auto-rotate-delay="0"- rotation-per-second="20deg"- interaction-prompt="none"- camera-controls="false"- disable-zoom- shadow-intensity="0"- exposure="0.7"- environment-image="neutral"- camera-orbit="0deg 80deg 9m"- field-of-view="35deg"- loading="lazy"- ></model-viewer>+ <canvas id="footer-bot-canvas"></canvas></div><div class="h-footer-cta">diff --git a/public/footer.js b/public/footer.jsindex 5d3f13e23..914129415 100644--- a/public/footer.js+++ b/public/footer.js@@ -32,11 +32,29 @@.then((html) => {container.innerHTML = html;- if (container.querySelector('model-viewer')) {- ensureScript({- src: 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js',- type: 'module',- });+ if (container.querySelector('#footer-bot-canvas')) {+ if (document.querySelector('meta[name="has-three-bundle"]')) {+ // This page already has a Vite-bundled Three.js — load the canvas+ // renderer that shares that instance, avoiding a duplicate load.+ ensureScript({ src: '/footer-bot.js', type: 'module' });+ } else {+ // Plain HTML page (login, register, etc.) — fall back to model-viewer.+ ensureScript({+ src: 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js',+ type: 'module',+ });+ // model-viewer needs a <model-viewer> element; swap the canvas for one.+ const avatar = container.querySelector('.h-footer-avatar');+ if (avatar) {+ avatar.innerHTML = `<model-viewer+ src="/animations/robotexpressive.glb"+ auto-rotate auto-rotate-delay="0" rotation-per-second="20deg"+ interaction-prompt="none" camera-controls="false" disable-zoom+ shadow-intensity="0" exposure="0.7" environment-image="neutral"+ camera-orbit="0deg 80deg 9m" field-of-view="35deg" loading="lazy"+ ></model-viewer>`;+ }+ }}ensureScript({ src: '/footer-newsletter.js', attr: 'defer' });diff --git a/public/home.css b/public/home.cssindex 1143d264b..66d19008a 100644--- a/public/home.css+++ b/public/home.css@@ -298,6 +298,8 @@position: relative;min-height: 360px;background: rgba(255, 255, 255, 0.02);+ will-change: transform;+ transform: translateZ(0);}.h-bento-visual model-viewer {@@ -2627,3 +2629,40 @@display: none;}}++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ scroll-behavior: auto !important;+ }++ .h-reveal {+ opacity: 1;+ transform: none;+ }++ .h-star-canvas {+ display: none;+ }++ .h-layer {+ transform: none !important;+ }++ .h-avatar-wrap,+ .h-hero-mesh,+ .h-hero-glow-a,+ .h-hero-glow-b,+ .h-hero-haze,+ .h-floor-ribbon {+ animation: none !important;+ }++ .h-status-dot::before {+ animation: none !important;+ }+}diff --git a/public/pay/index.html b/public/pay/index.htmlindex c6246abb2..b617e9b59 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -506,6 +506,75 @@.quick button[data-cmd="search_public_avatars:"] { display: none; }.pill .label { display: none; }}++ /* Agent picker */+ .agent-bar {+ border-bottom: 1px solid var(--border);+ background: var(--bg-2);+ padding: 10px 28px;+ display: flex; gap: 10px; align-items: center; flex-wrap: wrap;+ font-size: 13px;+ }+ .agent-bar .label { color: var(--muted); white-space: nowrap; }+ .agent-list { display: flex; gap: 8px; flex-wrap: wrap; flex: 1; min-width: 0; }+ .agent-card {+ display: flex; gap: 8px; align-items: center;+ padding: 7px 12px;+ border: 1px solid var(--border); border-radius: 10px;+ cursor: pointer; background: var(--panel);+ transition: border-color 0.15s, background 0.15s;+ font-size: 12px;+ }+ .agent-card:hover { border-color: var(--accent); background: rgba(139,92,246,0.06); }+ .agent-card.selected { border-color: var(--accent-2); background: rgba(34,211,238,0.07); }+ .agent-card .av {+ width: 24px; height: 24px; border-radius: 6px;+ background: conic-gradient(from 200deg, var(--accent), var(--accent-2));+ display: flex; align-items: center; justify-content: center;+ font-size: 10px; font-weight: 700; color: #0a0b10; flex: 0 0 auto;+ }+ .agent-card .av img { width: 24px; height: 24px; border-radius: 6px; object-fit: cover; }+ .agent-card .name { font-weight: 600; }+ .agent-card .bal { color: var(--muted); font-family: var(--mono); font-size: 11px; }+ .agent-card .no-wallet {+ color: var(--orange); font-size: 10px; font-family: var(--mono);+ background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3);+ padding: 2px 6px; border-radius: 4px;+ }+ .agent-bar .login-cta {+ color: var(--muted); font-size: 12px;+ }+ .agent-bar .login-cta a { color: var(--accent-2); }+ .agent-bar .login-cta .demo-note { font-style: italic; }++ /* Generate wallet modal */+ .gen-overlay {+ position: fixed; inset: 0; background: rgba(0,0,0,0.7);+ backdrop-filter: blur(8px);+ display: none; align-items: center; justify-content: center; z-index: 100;+ }+ .gen-overlay.show { display: flex; }+ .gen-modal {+ background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: 16px; padding: 28px 32px; max-width: 420px; width: calc(100% - 32px);+ animation: walkIn 0.25s ease-out;+ }+ .gen-modal h3 { margin: 0 0 6px; font-size: 18px; }+ .gen-modal p { color: var(--muted); margin: 0 0 18px; font-size: 13px; }+ .gen-modal .actions { display: flex; flex-direction: column; gap: 8px; }+ .gen-modal button {+ padding: 12px 16px; border-radius: 10px;+ border: 1px solid var(--border); background: var(--panel-2);+ color: var(--text); cursor: pointer; font-size: 13px; font-family: inherit;+ display: flex; align-items: center; gap: 10px;+ transition: border-color 0.15s;+ }+ .gen-modal button:hover { border-color: var(--accent); }+ .gen-modal button.primary { background: var(--accent); color: #fff; border-color: var(--accent); }+ .gen-modal button.primary:hover { background: #7c3aed; }+ .gen-modal .cancel { color: var(--muted); margin-top: 8px; font-size: 12px; text-align: center; cursor: pointer; }+ .gen-modal .cancel:hover { color: var(--text); }+ .gen-modal .spinner { font-size: 18px; animation: spin 1.2s linear infinite; }</style></head><body>@@ -533,6 +602,16 @@<main><section class="chat">+ <div class="agent-bar" id="agentBar">+ <span class="label">agent wallet</span>+ <div class="agent-list" id="agentList">+ <span class="login-cta" id="agentLoginCta" style="display:none">+ <a href="/login?redirect=/pay">Sign in</a> to use your own agent's wallet.+ <span class="demo-note">Using shared demo wallet for now.</span>+ </span>+ <span id="agentLoading" style="color:var(--muted);font-size:12px">loading agents…</span>+ </div>+ </div><div class="conv" id="conv"><div class="msg agent"><div class="av">3</div>@@ -574,6 +653,21 @@</div></footer>+<div class="gen-overlay" id="genOverlay">+ <div class="gen-modal">+ <h3 id="genTitle">Set up Solana wallet</h3>+ <p id="genBody">Your agent needs a Solana wallet to pay for tool calls. Generate one now or import a vanity address.</p>+ <div class="actions">+ <button class="primary" id="genBtn">+ <span id="genSpinner" style="display:none" class="spinner">↻</span>+ ⚡ Generate wallet instantly+ </button>+ <button id="vanityBtn">🎨 Grind a vanity address instead</button>+ </div>+ <div class="cancel" id="genCancel">cancel</div>+ </div>+</div>+<div class="overlay" id="walkthrough"><div class="walkthrough"><h1>How this works</h1>@@ -594,6 +688,117 @@ const promptEl = $('prompt'), sendBtn = $('send'), quickEl = $('quick');const walletText = $('walletText'), walletPill = $('walletPill');const tickerText = $('tickerText'), tickerPill = $('tickerPill');const feedStrip = $('feedStrip'), walkthrough = $('walkthrough'), closeWalk = $('closeWalk');+const agentList = $('agentList'), agentLoading = $('agentLoading'), agentLoginCta = $('agentLoginCta');+const genOverlay = $('genOverlay'), genCancel = $('genCancel'), genBtn = $('genBtn'), vanityBtn = $('vanityBtn');+const genSpinner = $('genSpinner');++// ---- Agent state --------------------------------------------------------+let selectedAgent = null; // { id, name, solana_address, usdc, sol }+let pendingGenAgentId = null;++function setSelectedAgent(agent) {+ selectedAgent = agent;+ // update wallet pill to show selected agent's balance+ if (agent) {+ walletText.textContent = `${agent.name} · ${+ agent.usdc != null ? agent.usdc.toFixed(3) + ' USDC' : '? USDC'+ } · ${agent.sol != null ? agent.sol.toFixed(4) + ' SOL' : ''} · ${+ agent.solana_address ? agent.solana_address.slice(0,4)+'…'+agent.solana_address.slice(-4) : '?'+ }`;+ }+ // re-render agent cards to highlight selected+ renderAgentCards(window._agentCache || []);+}++function renderAgentCards(agents) {+ window._agentCache = agents;+ agentLoading.style.display = 'none';+ // remove existing cards+ for (const el of agentList.querySelectorAll('.agent-card')) el.remove();+ if (!agents.length) {+ agentLoginCta.style.display = 'block';+ agentLoginCta.innerHTML = `No agents yet. <a href="/create">Create your first agent →</a>`;+ return;+ }+ agents.forEach(agent => {+ const el = document.createElement('div');+ el.className = 'agent-card' + (selectedAgent?.id === agent.id ? ' selected' : '');+ el.dataset.agentId = agent.id;+ const avatarHtml = agent.avatar_id+ ? `<img src="https://three.ws/avatars/${agent.avatar_id}/thumbnail.png" onerror="this.style.display='none';this.nextSibling.style.display='flex'" alt="" /><span style="display:none">${escape(agent.name[0]||'?')}</span>`+ : `<span>${escape(agent.name[0]||'?')}</span>`;+ const walletHtml = agent.solana_address+ ? `<span class="bal">${agent.usdc != null ? agent.usdc.toFixed(3)+' USDC' : ''}</span>`+ : `<span class="no-wallet">no wallet</span>`;+ el.innerHTML = `<div class="av">${avatarHtml}</div><div><div class="name">${escape(agent.name)}</div>${walletHtml}</div>`;+ el.addEventListener('click', () => {+ if (!agent.solana_address) {+ openGenOverlay(agent);+ } else {+ setSelectedAgent(agent);+ }+ });+ agentList.appendChild(el);+ });+}++async function loadAgents() {+ try {+ const r = await fetch('/api/x402-pay?agents=1');+ if (r.status === 401) {+ agentLoading.style.display = 'none';+ agentLoginCta.style.display = 'block';+ return;+ }+ if (!r.ok) throw new Error('load_failed');+ const { agents } = await r.json();+ renderAgentCards(agents);+ // auto-select first agent with a wallet+ if (!selectedAgent) {+ const withWallet = agents.find(a => a.solana_address);+ if (withWallet) setSelectedAgent(withWallet);+ }+ } catch {+ agentLoading.style.display = 'none';+ agentLoginCta.style.display = 'block';+ }+}++function openGenOverlay(agent) {+ pendingGenAgentId = agent.id;+ $('genTitle').textContent = `Set up wallet for "${agent.name}"`;+ $('genBody').textContent = `This agent needs a Solana wallet to pay $0.001 USDC per tool call. Generate one now (instant) or grind a vanity address.`;+ genOverlay.classList.add('show');+}++genCancel.addEventListener('click', () => { genOverlay.classList.remove('show'); pendingGenAgentId = null; });+vanityBtn.addEventListener('click', () => {+ window.open(`/vanity-wallet?agent=${pendingGenAgentId}`, '_blank');+ genOverlay.classList.remove('show');+});+genBtn.addEventListener('click', async () => {+ if (!pendingGenAgentId) return;+ genBtn.disabled = true;+ genSpinner.style.display = '';+ genBtn.childNodes[1].textContent = ' Generating…';+ try {+ const r = await fetch(`/api/agents/${pendingGenAgentId}/solana`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });+ if (!r.ok) throw new Error((await r.json()).error || 'gen_failed');+ genOverlay.classList.remove('show');+ // reload agents to get the new address+ await loadAgents();+ const agent = (window._agentCache || []).find(a => a.id === pendingGenAgentId);+ if (agent) setSelectedAgent(agent);+ pendingGenAgentId = null;+ addMsg('agent', `✅ Wallet generated for <strong>${escape(agent?.name || 'your agent')}</strong>. Address: <code>${agent?.solana_address || ''}</code>. Fund it with USDC to start making paid calls.`);+ } catch (err) {+ addMsg('agent', `<div class="err">Failed to generate wallet: ${escape(err.message)}</div>`);+ } finally {+ genBtn.disabled = false;+ genSpinner.style.display = 'none';+ genBtn.childNodes[1].textContent = ' Generate wallet instantly';+ }+});const DEMO_MODEL = 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';const TOOL_PRICE_USDC = 0.001;@@ -924,7 +1129,7 @@ async function run(call, displayLabel) {const res = await fetch('/api/x402-pay', {method: 'POST',headers: { 'content-type': 'application/json', accept: 'text/event-stream' },- body: JSON.stringify(call),+ body: JSON.stringify(selectedAgent ? { ...call, agentId: selectedAgent.id } : call),});if (!res.ok || !res.body) {const text = await res.text();@@ -992,6 +1197,21 @@ function bumpTicker() {// ---- Wallet balance + activity feed ------------------------------------async function refreshBalance() {+ // If using an agent wallet, reload agents to get fresh balances.+ if (selectedAgent) {+ try {+ const r = await fetch('/api/x402-pay?agents=1');+ if (r.ok) {+ const { agents } = await r.json();+ window._agentCache = agents;+ const updated = agents.find(a => a.id === selectedAgent.id);+ if (updated) { selectedAgent = updated; setSelectedAgent(updated); }+ renderAgentCards(agents);+ }+ } catch {}+ return;+ }+ // Shared demo wallettry {const r = await fetch('/api/x402-pay?balance=1');if (!r.ok) throw new Error('bal_fetch_failed');@@ -1061,6 +1281,16 @@ refreshFeed();setInterval(refreshBalance, 30_000);setInterval(refreshFeed, 20_000);+// Agent picker — try to load if there's any sign the user is logged in.+// The localStorage hint is set by the main site on login.+const authHint = (() => { try { return JSON.parse(localStorage.getItem('3dagent:auth-hint') || 'null'); } catch { return null; } })();+if (authHint?.authed) {+ loadAgents();+} else {+ // Not obviously logged in — try anyway (session cookie may exist).+ loadAgents().catch(() => {});+}+// Deep-link prefill: /pay?validate=https://...glb auto-fires the call.const params = new URLSearchParams(location.search);for (const [tool, alias] of [diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 1ee7b86f9..a5d01527c 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -288,7 +288,7 @@ function bindWalletActions() {await connection.confirmTransaction(signature);alert(`Withdrawal of ${amount} SOL to ${recipientAddress} successful!`);- console.log('Transaction signature:', signature);+modal.classList.add('hidden');withdrawAmountInput.value = '';recipientAddressInput.value = '';@@ -301,7 +301,7 @@ function bindWalletActions() {swapBtn.addEventListener('click', () => {alert("Swap functionality coming soon!");- console.log('Swap button clicked');+});}@@ -471,7 +471,7 @@ connectWalletBtn.addEventListener('click', async () => {try {const resp = await provider.connect();wallet = resp.publicKey;- console.log('Wallet connected:', wallet.toString());+connectWalletBtn.textContent = `${wallet.toString().slice(0, 4)}...${wallet.toString().slice(-4)}`;} catch (err) {console.error('Failed to connect to wallet:', err);diff --git a/src/footer-bot.js b/src/footer-bot.jsnew file mode 100644index 000000000..03cc70612--- /dev/null+++ b/src/footer-bot.js@@ -0,0 +1,67 @@+import * as THREE from 'three';+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';++const canvas = document.getElementById('footer-bot-canvas');+if (!canvas) throw new Error('[footer-bot] canvas not found');++const parent = canvas.parentElement;+const w = parent?.clientWidth || 300;+const h = parent?.clientHeight || 400;++const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });+renderer.setSize(w, h);+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 0.7;+renderer.outputColorSpace = THREE.SRGBColorSpace;++const scene = new THREE.Scene();++// Match model-viewer camera-orbit="0deg 80deg 9m" field-of-view="35deg"+const camera = new THREE.PerspectiveCamera(35, w / h, 0.1, 100);+const phi = THREE.MathUtils.degToRad(80);+camera.position.set(0, 9 * Math.cos(phi), 9 * Math.sin(phi));+camera.lookAt(0, 0, 0);++// Neutral environment (exposure 0.7, no shadows)+scene.add(new THREE.AmbientLight(0xffffff, 1.5));+const sun = new THREE.DirectionalLight(0xffffff, 2.0);+sun.position.set(1, 2, 3);+scene.add(sun);+const fill = new THREE.DirectionalLight(0xffffff, 0.5);+fill.position.set(-1, 1, -2);+scene.add(fill);++let mixer = null;+const clock = new THREE.Clock();+let robot = null;++new GLTFLoader().load('/animations/robotexpressive.glb', (gltf) => {+ robot = gltf.scene;+ scene.add(robot);+ if (gltf.animations.length > 0) {+ mixer = new THREE.AnimationMixer(robot);+ mixer.clipAction(gltf.animations[0]).play();+ }+});++// 20deg/sec auto-rotate, matching model-viewer rotation-per-second="20deg"+const rotSpeed = THREE.MathUtils.degToRad(20);++(function animate() {+ requestAnimationFrame(animate);+ const dt = clock.getDelta();+ if (mixer) mixer.update(dt);+ if (robot) robot.rotation.y += rotSpeed * dt;+ renderer.render(scene, camera);+})();++if (typeof ResizeObserver !== 'undefined' && parent) {+ new ResizeObserver(() => {+ const pw = parent.clientWidth || 300;+ const ph = parent.clientHeight || 400;+ camera.aspect = pw / ph;+ camera.updateProjectionMatrix();+ renderer.setSize(pw, ph);+ }).observe(parent);+}diff --git a/src/idle-animation.js b/src/idle-animation.jsindex 86188dc89..d68d827e7 100644--- a/src/idle-animation.js+++ b/src/idle-animation.js@@ -226,7 +226,7 @@ export class IdleAnimation {!this._hipBone &&this._morphMeshes.length === 0) {- console.log(+ console.warn('[IdleAnimation] No bones or morph targets found on avatar root — channels will be no-ops.',);}diff --git a/src/marketplace.js b/src/marketplace.jsindex bb2bffca5..1d84e7fbb 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -94,6 +94,8 @@ const els = {function readRoute() {const m = location.pathname.match(/^\/marketplace\/agents\/([^/]+)/);if (m) return { view: 'detail', id: m[1] };+ const av = location.pathname.match(/^\/marketplace\/avatars\/([^/]+)/);+ if (av) return { view: 'avatar-detail', id: av[1] };const params = new URLSearchParams(location.search);const tab = params.get('tab');const tag = (params.get('tag') || '').trim().toLowerCase().slice(0, 40) || null;@@ -828,8 +830,7 @@ function renderGrid() {return;}const id = card.dataset.avatarId;- const avatar = state.publicAvatars.find((a) => a.avatarId === id);- if (avatar) openAvatarModal(avatar);+ if (id) navTo(`/marketplace/avatars/${encodeURIComponent(id)}`);});});els.grid.querySelectorAll('[data-onchain-href]').forEach((card) => {@@ -1578,6 +1579,171 @@ async function loadDetail(id) {}}+// ── Avatar deep-link detail ───────────────────────────────────────────────++/** Normalise the /api/avatars/:id response shape to the explore-API shape. */+function _normaliseAvatar(a) {+ return {+ avatarId: a.id || a.avatarId || '',+ slug: a.slug || null,+ name: a.name || 'Untitled avatar',+ description: a.description || '',+ glbUrl: a.model_url || a.url || a.glbUrl || a.glb_url || '',+ image: a.thumbnail_url || a.image || null,+ tags: Array.isArray(a.tags) ? a.tags : [],+ author: a.author || null,+ createdAt: a.created_at || a.createdAt || null,+ viewCount: Number(a.view_count || a.viewCount || 0),+ featured: a.featured || false,+ viewerUrl: a.viewerUrl || null,+ };+}++let _avatarDetailId = null;+let _avatarDetailMv = null;++async function loadAvatarDetail(id) {+ if (_avatarDetailId === id) return; // already loaded for this ID+ _avatarDetailId = id;++ // Reset stage.+ const stage = $('avatar-detail-stage');+ const bar = $('avatar-detail-load-bar');+ const wrap = $('avatar-detail-load-wrap');+ if (stage) {+ if (_avatarDetailMv) { try { _avatarDetailMv.src = ''; } catch {} }+ // Remove previous model-viewer but keep the load-wrap.+ stage.querySelectorAll('model-viewer').forEach((el) => el.remove());+ stage.classList.remove('mv-ready');+ if (bar) bar.style.width = '0%';+ if (wrap) wrap.style.opacity = '1';+ }++ $('avatar-detail-name').textContent = 'Loading…';+ $('avatar-detail-desc').textContent = '';+ $('avatar-detail-author').innerHTML = '';+ $('avatar-detail-pills').innerHTML = '';+ const similarWrap = $('avatar-detail-similar-wrap');+ if (similarWrap) similarWrap.hidden = true;++ // Try the loaded list first (instant if user browsed there), then fetch.+ let avatar = state.publicAvatars.find((a) => a.avatarId === id || a.slug === id);+ if (!avatar) {+ try {+ const r = await fetch(`${API}/avatars/${encodeURIComponent(id)}`);+ if (r.ok) {+ const j = await r.json();+ avatar = _normaliseAvatar(j?.avatar || j?.data?.avatar || j);+ }+ } catch (err) {+ console.error('[marketplace] avatar detail fetch', err);+ }+ }++ if (!avatar?.glbUrl) {+ $('avatar-detail-name').textContent = 'Avatar not found';+ return;+ }++ // Populate meta.+ $('avatar-detail-name').textContent = avatar.name || 'Untitled avatar';+ $('avatar-detail-desc').textContent = avatar.description || 'A 3D avatar published to the community.';++ const authorEl = $('avatar-detail-author');+ if (avatar.author?.handle) {+ authorEl.innerHTML = avatar.author.profileUrl+ ? `by <a href="${escapeHtml(avatar.author.profileUrl)}" rel="author">${escapeHtml(avatar.author.displayName || avatar.author.handle)}</a>`+ : `by ${escapeHtml(avatar.author.displayName || avatar.author.handle)}`;+ }++ const pillsEl = $('avatar-detail-pills');+ const pills = [];+ if (Number(avatar.viewCount) > 0) pills.push(`<span class="stat-pill">⊙ ${fmtNumber(avatar.viewCount)} views</span>`);+ if (avatar.createdAt) pills.push(`<span class="stat-pill">${escapeHtml(liveTime(avatar.createdAt))}</span>`);+ pills.push('<span class="stat-pill">3D · GLB</span>');+ (avatar.tags || []).forEach((t) => {+ pills.push(`<button type="button" class="stat-pill tag-pill" data-tag="${escapeHtml(t)}">#${escapeHtml(t)}</button>`);+ });+ pillsEl.innerHTML = pills.join('');+ pillsEl.querySelectorAll('[data-tag]').forEach((btn) => {+ btn.addEventListener('click', () => navTo(`/marketplace?tag=${encodeURIComponent(btn.dataset.tag)}`));+ });++ // CTAs.+ const useBtn = $('avatar-detail-use');+ const viewBtn = $('avatar-detail-view');+ const dlBtn = $('avatar-detail-download');+ if (useBtn) useBtn.onclick = () => {+ const p = new URLSearchParams();+ if (avatar.glbUrl) p.set('avatar_glb', avatar.glbUrl);+ if (avatar.name) p.set('avatar_name', avatar.name);+ location.href = `/create?${p}`;+ };+ if (viewBtn) viewBtn.href = avatar.viewerUrl || (avatar.glbUrl ? `/#model=${encodeURIComponent(avatar.glbUrl)}` : '#');+ if (dlBtn) { dlBtn.href = avatar.glbUrl || '#'; dlBtn.setAttribute('download', (avatar.slug || avatar.avatarId || 'avatar') + '.glb'); }++ // Update page title + meta for social sharing.+ document.title = `${avatar.name} — Community Avatar · three.ws`;+ const descMeta = document.querySelector('meta[name="description"]');+ if (descMeta) descMeta.content = avatar.description || `A 3D avatar on three.ws — use it as the face of an AI agent.`;++ // Inject model-viewer into stage.+ if (stage) {+ const mv = document.createElement('model-viewer');+ mv.setAttribute('src', avatar.glbUrl);+ mv.setAttribute('alt', avatar.name || 'Avatar');+ mv.setAttribute('auto-rotate', '');+ mv.setAttribute('rotation-per-second', '12deg');+ mv.setAttribute('camera-controls', '');+ mv.setAttribute('interaction-prompt', 'when-focused');+ mv.setAttribute('exposure', '1.05');+ mv.setAttribute('shadow-intensity', '0.7');+ mv.setAttribute('tone-mapping', 'aces');+ if (avatar.image) mv.setAttribute('poster', avatar.image);+ mv.style.cssText = 'width:100%;height:100%;position:absolute;inset:0;';+ if (bar) {+ mv.addEventListener('progress', (e) => {+ bar.style.width = Math.round((e.detail?.totalProgress || 0) * 100) + '%';+ });+ }+ mv.addEventListener('load', () => {+ stage.classList.add('mv-ready');+ }, { once: true });+ stage.appendChild(mv);+ _avatarDetailMv = mv;+ }++ // Similar avatars — show others from the loaded list (same tags).+ const similar = state.publicAvatars+ .filter((a) => a.avatarId !== id && (a.tags || []).some((t) => (avatar.tags || []).includes(t)))+ .slice(0, 8);+ if (similar.length && similarWrap) {+ similarWrap.hidden = false;+ const grid = $('avatar-detail-similar-grid');+ if (grid) {+ grid.innerHTML = similar.map((a) => renderAvatarCard(a)).join('');+ grid.querySelectorAll('[data-avatar-id]').forEach((card) => {+ card.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ navTo(`/marketplace/avatars/${encodeURIComponent(card.dataset.avatarId)}`);+ });+ });+ attachModelViewerBehavior();+ observeCardModelViewers();+ }+ }++ // Fire-and-forget view tracking.+ if (avatar.avatarId && !String(avatar.avatarId).startsWith('avatar_demo_')) {+ fetch(`${API}/avatars/view`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatar.avatarId }),+ keepalive: true,+ }).catch(() => {});+ }+}+function renderDetailError(msg) {$('d-name').textContent = msg;$('d-author').textContent = '';@@ -1822,6 +1988,9 @@ function bindEvents() {}});els.back.addEventListener('click', () => navTo('/marketplace'));+ // Avatar detail back button.+ const avatarDetailBack = $('avatar-detail-back');+ if (avatarDetailBack) avatarDetailBack.addEventListener('click', () => { _avatarDetailId = null; navTo('/marketplace'); });$('d-fork').addEventListener('click', fork);$('d-bookmark').addEventListener('click', toggleBookmark);bindTabs();@@ -2469,13 +2638,25 @@ function render() {const setHidden = (el, hidden) => { if (el) el.hidden = hidden; };- if (r.view === 'detail') {+ const avatarDetailSec = $('market-avatar-detail');+ if (r.view === 'avatar-detail') {+ loadAvatarDetail(r.id);+ setHidden(discovery, true);+ setHidden(detail, true);+ setHidden(tools, true);+ setHidden(skillsSec, true);+ setHidden(mineSec, true);+ setHidden(purchasesSec, true);+ setHidden(avatarDetailSec, false);+ avatarDetailSec?.scrollIntoView({ behavior: 'instant', block: 'start' });+ } else if (r.view === 'detail') {loadDetail(r.id);setHidden(discovery, true);setHidden(tools, true);setHidden(skillsSec, true);setHidden(mineSec, true);setHidden(purchasesSec, true);+ setHidden(avatarDetailSec, true);setHidden(detail, false);} else if (r.view === 'tools') {setHidden(detail, true);@@ -2511,11 +2692,13 @@ function render() {loadPurchases();} else {setHidden(detail, true);+ setHidden(avatarDetailSec, true);setHidden(tools, true);setHidden(skillsSec, true);setHidden(mineSec, true);setHidden(purchasesSec, true);setHidden(discovery, false);+ document.title = 'Agent Marketplace · three.ws';}}diff --git a/style.css b/style.cssindex ee676e2c5..009b1e3c2 100644--- a/style.css+++ b/style.css@@ -6278,6 +6278,14 @@ textarea.erc8004-code {text-overflow: ellipsis;white-space: nowrap;}+.explore-card-name-link {+ color: inherit;+ text-decoration: none;+}+.explore-card-name-link:hover {+ text-decoration: underline;+ text-underline-offset: 2px;+}.explore-card-id {font-size: 11px;color: rgba(255, 255, 255, 0.35);diff --git a/tests/seed-skills.test.mjs b/tests/seed-skills.test.mjsindex 050b68202..23e33bae7 100644--- a/tests/seed-skills.test.mjs+++ b/tests/seed-skills.test.mjs@@ -1,62 +1,46 @@-import { test } from 'vitest';-import { AgentSkills } from './src/agent-skills.js';-import { sql } from './api/_lib/db.js';+import { test, vi, expect } from 'vitest';++// Mock db before any imports that pull it in transitively.+vi.mock('../api/_lib/db.js', () => ({+ sql: Object.assign(vi.fn(async () => []), {+ json: (v) => v,+ end: vi.fn(async () => {}),+ }),+}));++// Paths are relative to this file (tests/), so ../src/ → src/ at repo root.+const { AgentSkills } = await import('../src/agent-skills.js');test('Seed skills to the database', async () => {- const _noop = () => {};- const _stub = { emit: _noop, on: _noop, off: _noop, add: _noop, query: () => [] };- const skills = new AgentSkills(_stub, _stub).list();-- console.log(`Found ${skills.length} skills to seed.`);-- for (const skill of skills) {- const { name, description, inputSchema, mcpExposed } = skill;-- if (!description) {- console.warn(`Skipping skill "${name}" because it has no description.`);- continue;- }-- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');-- let category = 'utility';- const nameParts = name.split('-');- if (nameParts.length > 1) {- category = nameParts[0];- }-- const newSkill = {- name,- slug,- description,- category,- is_public: true,- schema_json: inputSchema ? [ { function: { name: name, parameters: inputSchema } } ] : null,- };-- console.log(`Seeding skill: ${newSkill.name}`);-- try {- await sql`- insert into marketplace_skills (- name, slug, description, category, is_public, schema_json- ) values (- ${newSkill.name}, ${newSkill.slug}, ${newSkill.description}, ${newSkill.category}, ${newSkill.is_public}, ${sql.json(newSkill.schema_json)}- )- on conflict (slug) do update set- name = excluded.name,- description = excluded.description,- category = excluded.category,- is_public = excluded.is_public,- schema_json = excluded.schema_json,- updated_at = now()- `;- console.log(` -> Successfully seeded skill: ${newSkill.name}`);- } catch (error) {- console.error(` -> Error seeding skill ${newSkill.name}:`, error);- }- }-- console.log('Seeding complete.');- await sql.end();+ const _noop = () => {};+ const _stub = { emit: _noop, on: _noop, off: _noop, add: _noop, query: () => [] };+ const skills = new AgentSkills(_stub, _stub).list();++ expect(skills.length).toBeGreaterThan(0);++ const seeded = [];+ for (const skill of skills) {+ const { name, description, inputSchema } = skill;+ if (!description) continue;++ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');+ let category = 'utility';+ const nameParts = name.split('-');+ if (nameParts.length > 1) category = nameParts[0];++ const entry = {+ name,+ slug,+ description,+ category,+ is_public: true,+ schema_json: inputSchema ? [{ function: { name, parameters: inputSchema } }] : null,+ };++ expect(typeof entry.name).toBe('string');+ expect(entry.slug).toMatch(/^[a-z0-9-]+$/);+ seeded.push(entry);+ }++ expect(seeded.length).toBeGreaterThan(0);}, 60000);diff --git a/vercel.json b/vercel.jsonindex af01f0343..de0eafc9b 100644--- a/vercel.json+++ b/vercel.json@@ -284,6 +284,10 @@"src": "/marketplace/agents/([^/]+)","dest": "/marketplace.html"},+ {+ "src": "/marketplace/avatars/([^/]+)",+ "dest": "/marketplace.html"+ },{"src": "/api/agents/me","dest": "/api/agents"@@ -986,11 +990,11 @@},{"src": "/discover/a/(\\d+)/(\\d+)",- "dest": "/discover/detail.html"+ "dest": "/api/discover-detail?kind=onchain&chain=$1&id=$2"},{"src": "/discover/avatar/([^/]+)",- "dest": "/discover/detail.html"+ "dest": "/api/discover-detail?kind=avatar&id=$1"},{"src": "/discover/(.*)",diff --git a/vite.config.js b/vite.config.jsindex 6981cec92..33c07eb2d 100644--- a/vite.config.js+++ b/vite.config.js@@ -73,14 +73,24 @@ const appConfig = {},build: {chunkSizeWarningLimit: 1000,+ // Skip computing gzip/brotli sizes during build — saves several seconds on+ // large bundles (Three.js, ethers) without affecting the output.+ reportCompressedSize: false,rollupOptions: {output: {manualChunks(id) {if (id.includes('node_modules/three/')) return 'three';if (id.includes('node_modules/ethers/')) return 'ethers';},+ // footer-bot.js needs a stable, unhashed filename so footer.js can+ // load it by a predictable URL without knowing the build hash.+ entryFileNames: (chunk) =>+ chunk.name === 'footer-bot'+ ? 'footer-bot.js'+ : 'assets/[name]-[hash].js',},input: {+ 'footer-bot': resolve(__dirname, 'src/footer-bot.js'),app: resolve(__dirname, 'app.html'),'app-demo': resolve(__dirname, 'app-demo.html'),home: resolve(__dirname, 'home.html'),@@ -221,6 +231,8 @@ const appConfig = {let filePath = fileMap[path];if (!filePath && /^\/marketplace\/agents\/[^/]+\/?$/.test(path))filePath = resolve(root, 'marketplace.html');+ else if (!filePath && /^\/marketplace\/avatars\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'marketplace.html');// /agents/:id → rich detail page (UUID expected, validated client-side)else if (!filePath && /^\/agents\/[^/]+\/?$/.test(path))filePath = resolve(root, 'agent-detail.html');@@ -243,7 +255,13 @@ const appConfig = {else if (!filePath && /^\/pay\/calls\/[1-9A-HJ-NP-Za-km-z]+\/?$/.test(path))filePath = resolve(root, 'public/pay/calls/index.html');// Serve the rider webpack app as static files.- if (path === '/rider' || path === '/rider/') {+ // /footer-bot.js — serve the Vite-processed src/footer-bot.js at a+ // stable URL in dev so footer.js can load it without knowing the hash.+ if (path === '/footer-bot.js') {+ req.url = '/src/footer-bot.js';+ return next();+ }+ if (path === '/rider' || path === '/rider/') {const html = readFileSync(resolve(root, 'rider/index.html'), 'utf8');res.setHeader('Content-Type', 'text/html; charset=utf-8');return res.end(html);@@ -276,6 +294,17 @@ const appConfig = {});},},+ {+ // Stamp every Vite-processed HTML page so footer.js can detect that+ // Three.js is already bundled and skip loading the model-viewer CDN script.+ name: 'three-bundle-meta',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ return [{ tag: 'meta', attrs: { name: 'has-three-bundle', content: 'true' }, injectTo: 'head' }];+ },+ },+ },{name: 'copy-static-docs',closeBundle() {