Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: avatar-studio rebrand + marketplace stub filtering + solana x402 test
nirholas2b3fdb3d0617
diff --git a/api/_lib/seed-default-agent.js b/api/_lib/seed-default-agent.jsindex 657c7396b..b3473d974 100644--- a/api/_lib/seed-default-agent.js+++ b/api/_lib/seed-default-agent.js@@ -1,5 +1,8 @@-// Seeds a default published agent for a brand-new user so they have something-// reachable, forkable, and ready to attach an avatar to as soon as they sign in.+// Seeds a default DRAFT agent for a brand-new user so they have something+// reachable in their "Mine" list and ready to attach an avatar to as soon as+// they sign in. Kept unpublished so the public marketplace doesn't fill up+// with stub "My First Agent" rows — users opt into publishing when they've+// actually customised the agent.//// Idempotent: if the user already has any agent (published or draft), the// function is a no-op. Safe to call from any signup path (email, SIWE, SIWS).@@ -38,8 +41,8 @@ export async function seedDefaultAgent(userId) {'general',ARRAY['starter']::text[],'{"bullets": ["Answers questions","Helps with writing","Suggests next steps"], "skills": [], "library": []}'::jsonb,- true,- now()+ false,+ null)RETURNING id`;diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 9d49264e7..5aa7346ef 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -45,6 +45,14 @@ const CATEGORIES = [const SORTS = new Set(['recommended', 'recent', 'popular']);+// Auto-named / stub agent names that should never appear in the public+// marketplace. Sources: api/agents.js default ('Agent'), seed-default-agent.js+// ('My First Agent'), src/create.js + src/app.js ('My Agent'), avatar imports+// ('Avatar #abcdef' or '<avatar> agent'), and obvious test/placeholder strings.+// Postgres POSIX regex — anchored explicitly because `~*` is unanchored.+const AGENT_AUTONAMED_RE_SQL =+ '^(Agent|My Agent|My First Agent|Demo Agent|Untitled.*|TEST|Test|test|mo[a-z0-9]{4,}|draft-[a-z0-9]+|new_project_[0-9]+|Avatar[ ]*#[0-9a-f]{4,}([ ]*agent)?|https?://.+)$';+const createAgentSchema = z.object({name: z.string().trim().min(1, 'name required').max(100),description: z.string().trim().min(1, 'description required').max(500),@@ -298,6 +306,7 @@ async function handleList(req, res, url) {LEFT JOIN users u ON u.id = ai.user_idWHERE ai.is_published = trueAND ai.deleted_at IS NULL+ AND ai.name !~* ${AGENT_AUTONAMED_RE_SQL}AND (${cat}::text IS NULL OR ai.category = ${cat})AND (${qLike}::text IS NULLdiff --git a/avatar-sdk/src/creator.js b/avatar-sdk/src/creator.jsindex 0ce46d65e..f86aaf3c5 100644--- a/avatar-sdk/src/creator.js+++ b/avatar-sdk/src/creator.js@@ -1,5 +1,5 @@// Programmatic Avatar Creator — opens an iframe modal where the user builds-// or photographs an avatar via Character Studio or Avaturn, listens for the+// or photographs an avatar in the three.ws Avatar Studio, listens for the// `export` postMessage, and resolves with the GLB Blob.//// This is the thin client-only wrapper. Apps that already have their own@@ -12,7 +12,7 @@// the `saveBlob()` helper instead, which posts to three.ws's /api/avatars// pipeline using a bearer token.-const DEFAULT_STUDIO_URL = 'https://studio.three.ws';+const DEFAULT_STUDIO_URL = 'https://three.ws/avatar-studio/';const DEFAULT_THREE_WS_ORIGIN = 'https://three.ws';export class AvatarCreator {diff --git a/character-studio/index.html b/character-studio/index.htmlindex 15d9183b2..ec0f0bcdf 100644--- a/character-studio/index.html+++ b/character-studio/index.html@@ -5,7 +5,7 @@<link rel="icon" type="image/svg+xml" href="src/favicon.ico" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /><meta name="HandheldFriendly" content="true" />- <title>Character Studio</title>+ <title>Avatar Studio · three.ws</title></head><body>diff --git a/character-studio/src/App.jsx b/character-studio/src/App.jsxindex ace5ea2fc..a709e484f 100644--- a/character-studio/src/App.jsx+++ b/character-studio/src/App.jsx@@ -159,9 +159,7 @@ export default function App() {[ViewMode.BATCHDOWNLOAD]: <BatchDownload />,[ViewMode.LOAD]: <Load />,[ViewMode.MINT]: <Mint />,- [ViewMode.SAVE]: <Save />,- [ViewMode.STUDIO]: <Studio />,- }+ [ViewMode.SAVE]: <Save />,[ViewMode.STUDIO]: <Studio />,}diff --git a/character-studio/src/components/ExportMenu.jsx b/character-studio/src/components/ExportMenu.jsxindex 3bb931d02..115a4f72a 100644--- a/character-studio/src/components/ExportMenu.jsx+++ b/character-studio/src/components/ExportMenu.jsx@@ -69,7 +69,7 @@ export const ExportMenu = ({currentPrice, onPurchaseClick}) => {[arrayBuffer],);} catch (err) {- console.error('[CharacterStudio] saveToAccount failed:', err);+ console.error('[three.ws Avatar Studio] saveToAccount failed:', err);} finally {setSaving(false);}diff --git a/character-studio/vite.config.js b/character-studio/vite.config.jsindex e4b3a431d..4ba04a3cd 100644--- a/character-studio/vite.config.js+++ b/character-studio/vite.config.js@@ -2,6 +2,10 @@ import { defineConfig } from 'vite'import react from '@vitejs/plugin-react-swc'export default defineConfig({+ // Hosted at https://three.ws/avatar-studio/ in production — all emitted asset+ // URLs need this prefix. The iframe SDK (avatar-sdk/src/creator.js) loads this+ // base URL directly.+ base: '/avatar-studio/',plugins: [react()],server: {port: 5173,diff --git a/marketplace.css b/marketplace.cssindex fba9af132..eebdb7361 100644--- a/marketplace.css+++ b/marketplace.css@@ -447,6 +447,42 @@ body.market-page {letter-spacing: 0.04em;}+/* Empty / not-found state inside stage. Replaces the fake-loading bar when+ * the avatar can't be loaded, so the user gets a real CTA instead of a+ * spinner that never resolves. */+.avatar-detail-empty {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ padding: 24px;+ text-align: center;+}+.market-avatar-detail-stage.is-empty .avatar-detail-load-wrap { display: none; }+.avatar-detail-empty-glyph {+ font-size: 40px;+ color: var(--mk-text-3);+ line-height: 1;+}+.avatar-detail-empty-title {+ margin: 4px 0 0;+ font-family: 'Space Grotesk', sans-serif;+ font-size: 18px;+ font-weight: 600;+ color: var(--mk-text);+}+.avatar-detail-empty-msg {+ margin: 0;+ font-size: 13px;+ color: var(--mk-text-2);+ max-width: 320px;+ line-height: 1.5;+}+.avatar-detail-empty-cta { margin-top: 6px; min-width: 160px; }+/* Right column meta */.market-avatar-detail-meta {display: flex;diff --git a/marketplace.html b/marketplace.htmlindex 5cdaa5897..df8b2bac9 100644--- a/marketplace.html+++ b/marketplace.html@@ -1030,6 +1030,10 @@/><meta property="og:url" content="https://three.ws/marketplace" /><meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Agent Marketplace · three.ws" />+ <meta name="twitter:description" content="Discover, fork, and chat with community-published AI agents." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" /><script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script><link rel="stylesheet" href="/nav.css" />@@ -1337,6 +1341,57 @@</div></div></div>++ <!-- 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 class="avatar-detail-empty" id="avatar-detail-empty" hidden>+ <span class="avatar-detail-empty-glyph" aria-hidden="true">◌</span>+ <h2 class="avatar-detail-empty-title">Avatar not found</h2>+ <p class="avatar-detail-empty-msg">This avatar may have been removed or the link is wrong.</p>+ <a class="btn-secondary avatar-detail-empty-cta" href="/marketplace?tab=avatars">Browse avatars</a>+ </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>+ <button type="button" class="btn-secondary" id="avatar-detail-share">+ Share+ </button>+ </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></main><!-- Submit Agent Modal -->@@ -1413,48 +1468,6 @@<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/package.json b/package.jsonindex d47e7a366..96229525b 100644--- a/package.json+++ b/package.json@@ -60,8 +60,9 @@"build:chat": "cd chat && node scripts/ensure-deps.mjs && npm run build && cd .. && mkdir -p dist/chat && cp -rf public/chat/. dist/chat/","build:rider": "mkdir -p dist/rider && cp rider/index.html dist/rider/ && cp -rf rider/assets dist/rider/ && cp -rf rider/build dist/rider/ && cp -rf rider/vendor dist/rider/","build:rider:full": "cd rider && npm ci --prefer-offline --no-audit --no-fund --ignore-engines && npm run build && cd .. && npm run build:rider",+ "build:avatar-studio": "npm run build --prefix character-studio","build:fast": "npm run build",- "build:vercel": "npm run build --prefix agent-payments-sdk && NODE_OPTIONS=--max-old-space-size=4096 npm run build && npm run build:lib && npm run build:rider && npm run build:chat && npm run publish:lib",+ "build:vercel": "npm run build --prefix agent-payments-sdk && npm run build:avatar-studio && NODE_OPTIONS=--max-old-space-size=4096 npm run build && npm run build:lib && npm run build:rider && npm run build:chat && npm run publish:lib","build:all": "npm run build:chat && (npm run build & npm run build:lib & npm run build:rider & wait)","release:lib": "npm run build:lib && npm run publish:lib","clean": "rm -rf dist/* dist-lib/* || true",diff --git a/public/demos/avatar-sdk.html b/public/demos/avatar-sdk.htmlindex f6e68a75e..a2bb63d39 100644--- a/public/demos/avatar-sdk.html+++ b/public/demos/avatar-sdk.html@@ -120,6 +120,10 @@ creator.open();</pre>const mod = await import('/avatar-sdk/src/creator.js');line(creatorLog, 'opening three.ws Avatar Creator iframe modal…', 'info');const creator = new mod.AvatarCreator({+ // Same-origin so dev (codespace) and production (three.ws)+ // both load the local Avatar Studio build instead of the+ // hard-coded https://three.ws/avatar-studio/ default.+ studioUrl: new URL('/avatar-studio/', location.origin).toString(),onExport: (glbBlob) => {line(creatorLog, `✓ export received (${glbBlob.size} bytes)`, 'ok');},diff --git a/scripts/x402-test-solana.mjs b/scripts/x402-test-solana.mjsnew file mode 100644index 000000000..b61d132f6--- /dev/null+++ b/scripts/x402-test-solana.mjs@@ -0,0 +1,252 @@+#!/usr/bin/env node+// scripts/x402-test-solana.mjs+// Drives a real x402 USDC payment from a local Solana keypair against+// three.ws x402 endpoints, using the PayAI Solana facilitator flow:+//+// 1. GET endpoint → 402 with PaymentRequirements (network=solana:..., feePayer=2wKupLR9...)+// 2. Build SPL TransferChecked with feePayer = PayAI; sign as source authority only.+// 3. Serialize partially-signed tx → base64 → X-PAYMENT payload `{ transaction }`.+// 4. Retry GET with X-PAYMENT header. Server /verifies and /settles via PayAI;+// PayAI co-signs as fee payer and broadcasts.+//+// Usage:+// node scripts/x402-test-solana.mjs # canary only+// node scripts/x402-test-solana.mjs --all # every Solana-supporting endpoint+// node scripts/x402-test-solana.mjs --only=skill-marketplace++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import bs58 from 'bs58';+import {+ ComputeBudgetProgram,+ Connection,+ Keypair,+ PublicKey,+ Transaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferCheckedInstruction,+ getMint,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);++const BASE_URL = process.env.X402_BASE_URL || 'https://three.ws';+const RPC = process.env.SOLANA_RPC || 'https://api.mainnet-beta.solana.com';+const SECRET_PATH = path.join(__dirname, '.secrets', 'rider-vault.json');++const X402_VERSION = 2;+const SOLANA_MAINNET_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';++// real agent_id from skill-marketplace listing+const REAL_AGENT_ID = '76bca598-103f-4e3a-8c95-b0d64993258a';+// USDC mint stands in as any tradeable Solana mint for audit endpoints+const SAMPLE_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++const ENDPOINTS = [+ { name: 'symbol-availability', method: 'GET', url: '/api/x402/symbol-availability?ticker=WWWTEST' },+ { name: 'skill-marketplace', method: 'GET', url: `/api/x402/skill-marketplace?agent_id=${REAL_AGENT_ID}` },+ { name: 'agent-reputation', method: 'GET', url: `/api/x402/agent-reputation?agent_id=${REAL_AGENT_ID}` },+ // Aodd9L... is a real pump-agent mint (from skill-marketplace listing).+ { name: 'pump-agent-audit', method: 'GET', url: `/api/x402/pump-agent-audit?mint=Aodd9LBDCue4HN6KyhpSai7yudFCoEWJ3FLHdgYajQzb` },+ {+ name: 'mint-to-mesh-batch',+ method: 'POST',+ url: '/api/x402/mint-to-mesh-batch',+ body: { mints: [SAMPLE_MINT] },+ },+ {+ name: 'onchain-identity-verify',+ method: 'GET',+ url: `/api/x402/onchain-identity-verify?agent_id=${REAL_AGENT_ID}&chain=solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp&contract_or_mint=Aodd9LBDCue4HN6KyhpSai7yudFCoEWJ3FLHdgYajQzb`,+ },+];++function loadKeypair() {+ const raw = JSON.parse(fs.readFileSync(SECRET_PATH, 'utf8'));+ const kp = Keypair.fromSecretKey(bs58.decode(raw.secretKeyBase58));+ if (raw.address && raw.address !== kp.publicKey.toBase58()) {+ throw new Error(`secret file address mismatch: file=${raw.address} derived=${kp.publicKey.toBase58()}`);+ }+ return kp;+}++function pickSolanaRequirement(envelope) {+ const accepts = envelope.accepts || [];+ return (+ accepts.find((a) => a.scheme === 'exact' && a.network === SOLANA_MAINNET_CAIP2) ||+ accepts.find((a) => a.scheme === 'exact' && String(a.network).startsWith('solana')) ||+ null+ );+}++async function buildAndSignTransferTx({ kp, connection, requirement }) {+ const payer = kp.publicKey;+ const mint = new PublicKey(requirement.asset);+ const payTo = new PublicKey(requirement.payTo);+ const feePayer = new PublicKey(requirement.extra.feePayer);+ const amount = BigInt(requirement.amount);++ const mintInfo = await getMint(connection, mint);+ const senderAta = getAssociatedTokenAddressSync(mint, payer, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);++ const tx = new Transaction();+ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ tx.recentBlockhash = blockhash;+ tx.feePayer = feePayer;++ // x402 SVM "exact" scheme V1 instruction layout (per x402-foundation+ // reference facilitator, github.com/x402-foundation/x402): exactly+ // [SetComputeUnitLimit, SetComputeUnitPrice, TransferChecked] (+ optional+ // Lighthouse/Memo trailers). No ATA-create allowed — receiver ATA must+ // already exist.+ const receiverInfo = await connection.getAccountInfo(receiverAta);+ if (!receiverInfo) {+ throw new Error(`receiver ATA ${receiverAta.toBase58()} does not exist; x402 SVM exact disallows ATA creation in the same tx`);+ }+ tx.add(ComputeBudgetProgram.setComputeUnitLimit({ units: 20_000 }));+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }));+ tx.add(+ createTransferCheckedInstruction(+ senderAta, mint, receiverAta, payer,+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ),+ );++ tx.partialSign(kp);+ const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });+ return Buffer.from(serialized).toString('base64');+}++function encodePaymentHeader(payload) {+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');+}++async function runOne(endpoint, kp, connection) {+ const url = `${BASE_URL}${endpoint.url}`;+ const method = endpoint.method || 'GET';+ const bodyInit = endpoint.body+ ? { body: JSON.stringify(endpoint.body), headers: { 'content-type': 'application/json' } }+ : {};+ process.stdout.write(`\n→ ${endpoint.name.padEnd(24)} ${method} ${url}\n`);+ const t0 = Date.now();++ // 1. Probe for 402.+ const probe = await fetch(url, { method, ...bodyInit });+ if (probe.status === 200) {+ console.log(` ! 200 unprompted — endpoint not gated`);+ return { name: endpoint.name, ok: true, note: 'not gated' };+ }+ if (probe.status !== 402) {+ const body = await probe.text();+ console.log(` ✗ unexpected ${probe.status}: ${body.slice(0, 200)}`);+ return { name: endpoint.name, ok: false, status: probe.status };+ }+ const envelope = await probe.json();+ const requirement = pickSolanaRequirement(envelope);+ if (!requirement) {+ console.log(` ✗ envelope has no Solana accepts entry`);+ return { name: endpoint.name, ok: false, note: 'no solana accept' };+ }+ const usd = (Number(requirement.amount) / 1e6).toFixed(6);+ console.log(` • 402 ok; price=${requirement.amount} atomics ($${usd}); feePayer=${requirement.extra.feePayer.slice(0, 8)}…`);++ // 2 + 3. Build, sign, encode.+ let txBase64;+ try {+ txBase64 = await buildAndSignTransferTx({ kp, connection, requirement });+ } catch (err) {+ console.log(` ✗ build/sign failed: ${err.message}`);+ return { name: endpoint.name, ok: false, error: err.message };+ }++ const paymentPayload = {+ x402Version: X402_VERSION,+ scheme: 'exact',+ network: requirement.network,+ resource: {+ url: envelope.resource?.url || url,+ mimeType: envelope.resource?.mimeType || 'application/json',+ },+ accepted: requirement,+ payload: { transaction: txBase64 },+ };++ // 4. Retry with X-PAYMENT.+ const retryHeaders = { 'X-PAYMENT': encodePaymentHeader(paymentPayload) };+ if (bodyInit.headers) Object.assign(retryHeaders, bodyInit.headers);+ const res = await fetch(url, {+ method,+ headers: retryHeaders,+ ...(bodyInit.body ? { body: bodyInit.body } : {}),+ });+ const dt = Date.now() - t0;+ const body = await res.text();+ const short = body.length > 240 ? body.slice(0, 240) + '…' : body;++ if (res.status === 200) {+ const payTx = res.headers.get('x-payment-tx');+ const payNet = res.headers.get('x-payment-network');+ console.log(` ✓ 200 in ${dt}ms network=${payNet || '?'} tx=${payTx || '?'}`);+ const respHeader = res.headers.get('x-payment-response');+ if (respHeader) {+ try {+ const decoded = JSON.parse(Buffer.from(respHeader, 'base64').toString('utf8'));+ console.log(` settle: ${JSON.stringify(decoded).slice(0, 200)}`);+ } catch {}+ }+ console.log(` body: ${short}`);+ return { name: endpoint.name, ok: true, tx: payTx };+ }+ console.log(` ✗ ${res.status} in ${dt}ms`);+ console.log(` body: ${short}`);+ return { name: endpoint.name, ok: false, status: res.status, body: short };+}++async function main() {+ const args = process.argv.slice(2);+ const runAll = args.includes('--all');+ const onlyName = args.find((a) => a.startsWith('--only='))?.slice('--only='.length);++ const kp = loadKeypair();+ const connection = new Connection(RPC, 'confirmed');++ console.log(`payer: ${kp.publicKey.toBase58()}`);+ console.log(`rpc: ${RPC}`);+ console.log(`base: ${BASE_URL}`);++ const list = onlyName+ ? ENDPOINTS.filter((e) => e.name === onlyName)+ : runAll+ ? ENDPOINTS+ : ENDPOINTS.slice(0, 1);+ if (list.length === 0) {+ console.error(`no endpoint matches --only=${onlyName}`);+ process.exit(1);+ }++ const results = [];+ for (const ep of list) {+ // eslint-disable-next-line no-await-in-loop+ results.push(await runOne(ep, kp, connection));+ }++ console.log('\n--- summary ---');+ for (const r of results) {+ console.log(` ${r.ok ? '✓' : '✗'} ${r.name}${r.tx ? ` tx=${r.tx}` : ''}${r.status ? ` status=${r.status}` : ''}${r.note ? ` (${r.note})` : ''}`);+ }+ process.exit(results.every((r) => r.ok) ? 0 : 1);+}++main().catch((err) => {+ console.error('fatal:', err);+ process.exit(1);+});diff --git a/src/buffer-polyfill.js b/src/buffer-polyfill.jsnew file mode 100644index 000000000..1e5524bd3--- /dev/null+++ b/src/buffer-polyfill.js@@ -0,0 +1,9 @@+// Browser Buffer polyfill. Bundled transitive deps (Metaplex/Anchor discriminators,+// bs58, borsh, spl-token-metadata) reference `Buffer` at module-init time. This+// must execute as a module body BEFORE any of those modules evaluate — so it+// lives in its own file and is imported first by the entry. (If the assignment+// lived inside lib.js's body, `import` hoisting would run every transitive dep+// — including the offending top-level `Buffer.from(...)` calls — before lib.js's+// body ran the polyfill.)+import { Buffer as _NodeBuffer } from 'buffer';+if (typeof globalThis.Buffer === 'undefined') globalThis.Buffer = _NodeBuffer;diff --git a/src/lib.js b/src/lib.jsindex 59a08ece0..f24dc6981 100644--- a/src/lib.js+++ b/src/lib.js@@ -1,6 +1,10 @@// Library entry — imported by the CDN bundle <script type="module" src="agent-3d.js">.// Registers the custom element and exposes public API classes for programmatic use.+// Buffer polyfill MUST be the very first import so its body runs before any+// transitive Solana/Anchor/Metaplex dep that touches `Buffer` at module init.+import './buffer-polyfill.js';+import { Agent3DElement } from './element.js';import { AgentStageElement } from './stage-element.js';diff --git a/src/marketplace.js b/src/marketplace.jsindex feb6997a8..27c4f2082 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -340,8 +340,9 @@ async function loadList(reset = false) {const r = await fetch(url);const j = await r.json();// Real endpoint wraps as { data: { items, next_cursor } }; legacy mock returns a bare array.- const items = Array.isArray(j) ? j : (j?.data?.items ?? []);+ const rawItems = Array.isArray(j) ? j : (j?.data?.items ?? []);const nextCursor = Array.isArray(j) ? null : (j?.data?.next_cursor ?? null);+ const items = rawItems.filter((a) => !isAutoNamedAgent(a.name));state.items = reset ? items : [...state.items, ...items];state.cursor = nextCursor;renderGrid();@@ -371,6 +372,18 @@ function isAutoNamedAvatar(name) {return AVATAR_AUTONAMED_RE.test(n);}+// Mirrors server-side AGENT_AUTONAMED_RE_SQL in api/marketplace/[action].js.+// Defense-in-depth: even if a stale CDN cache or partial rollout serves+// unfiltered rows, the marketplace UI still hides obvious stubs.+const AGENT_AUTONAMED_RE =+ /^(Agent|My Agent|My First Agent|Demo Agent|Untitled.*|TEST|Test|test|mo[a-z0-9]{4,}|draft-[a-z0-9]+|new_project_\d+|Avatar\s*#[0-9a-f]{4,}(\s*agent)?|https?:\/\/.+)$/i;++function isAutoNamedAgent(name) {+ const n = String(name || '').trim();+ if (!n) return true;+ return AGENT_AUTONAMED_RE.test(n);+}+async function loadPublicAvatars() {try {const url = new URL(`${API}/explore`, location.origin);@@ -1384,6 +1397,8 @@ function renderAvatarCard(a, spotlight = false) {// allocates a WebGL context, so we also stash the URL in `data-src` and// the observer promotes it to `src` on intersect — no GLB download, no// scene parse, no animation loop until the card is actually on screen.+ // reveal="auto" (default) means model-viewer un-veils the model on load;+ // no explicit dismissPoster() call needed.const preview = a.image? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`: a.glbUrl@@ -1399,7 +1414,6 @@ function renderAvatarCard(a, spotlight = false) {shadow-intensity="0.4"tone-mapping="aces"loading="lazy"- reveal="manual"></model-viewer>`: `<div class="thumb-fallback">◉</div>`;const isSpotlight = spotlight || a.featured;@@ -1579,22 +1593,79 @@ function _normaliseAvatar(a) {let _avatarDetailId = null;let _avatarDetailMv = null;+// Defaults for restoring social meta when leaving an avatar detail view.+const _socialMetaDefaults = {+ title: 'Agent Marketplace · three.ws',+ description: 'Discover, fork, and chat with community-published AI agents.',+ url: 'https://three.ws/marketplace',+ image: 'https://three.ws/og-image.png',+};++// Update <title>, meta[name=description], and the og:* / twitter:* tags so the+// avatar detail page previews correctly when pasted into chats and crawlers.+function setSocialMeta({ title, description, url, image }) {+ if (title) document.title = title;+ const set = (selector, value) => {+ if (value == null) return;+ const el = document.querySelector(selector);+ if (el) el.setAttribute('content', value);+ };+ set('meta[name="description"]', description);+ set('meta[property="og:title"]', title);+ set('meta[property="og:description"]', description);+ set('meta[property="og:url"]', url);+ set('meta[property="og:image"]', image);+ set('meta[name="twitter:title"]', title);+ set('meta[name="twitter:description"]', description);+ set('meta[name="twitter:image"]', image);+}++function resetSocialMeta() { setSocialMeta(_socialMetaDefaults); }++function _renderAvatarDetailEmpty() {+ const stage = $('avatar-detail-stage');+ const emptyEl = $('avatar-detail-empty');+ const loadWrap = $('avatar-detail-load-wrap');+ if (stage) stage.classList.add('is-empty');+ if (loadWrap) loadWrap.hidden = true;+ if (emptyEl) emptyEl.hidden = false;+ $('avatar-detail-name').textContent = 'Avatar not found';+ $('avatar-detail-desc').textContent = '';+ $('avatar-detail-author').innerHTML = '';+ $('avatar-detail-pills').innerHTML = '';+ // Hide the action column entirely — no fake CTAs pointing at "#".+ const actions = document.querySelector('.market-avatar-detail-actions');+ if (actions) actions.hidden = true;+ const similarWrap = $('avatar-detail-similar-wrap');+ if (similarWrap) similarWrap.hidden = true;+ setSocialMeta({+ title: 'Avatar not found · three.ws',+ description: 'This avatar may have been removed or the link is wrong.',+ url: location.origin + location.pathname,+ image: _socialMetaDefaults.image,+ });+}+async function loadAvatarDetail(id) {- if (_avatarDetailId === id) return; // already loaded for this ID- _avatarDetailId = id;+ if (_avatarDetailId === id) return; // already rendered for this ID- // Reset stage.+ // Reset stage. Note: we intentionally do NOT set `_avatarDetailId = id`+ // here — only after a successful render, so a transient fetch failure+ // doesn't cache an empty state and block retries.const stage = $('avatar-detail-stage');const bar = $('avatar-detail-load-bar');const wrap = $('avatar-detail-load-wrap');+ const empty = $('avatar-detail-empty');+ const actions = document.querySelector('.market-avatar-detail-actions');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');+ stage.classList.remove('mv-ready', 'is-empty');if (bar) bar.style.width = '0%';- if (wrap) wrap.style.opacity = '1';+ if (wrap) { wrap.hidden = false; wrap.style.opacity = '1'; }+ if (empty) empty.hidden = true;}+ if (actions) actions.hidden = false;$('avatar-detail-name').textContent = 'Loading…';$('avatar-detail-desc').textContent = '';@@ -1618,8 +1689,8 @@ async function loadAvatarDetail(id) {}if (!avatar?.glbUrl) {- $('avatar-detail-name').textContent = 'Avatar not found';- return;+ _renderAvatarDetailEmpty();+ return; // don't cache id — let the user retry by navigating again}// Populate meta.@@ -1633,36 +1704,62 @@ async function loadAvatarDetail(id) {: `by ${escapeHtml(avatar.author.displayName || avatar.author.handle)}`;}+ // Tag chips lead so the user reads what the avatar is *about* first; the+ // "3D · GLB" technical chip and view/recency stats follow.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>`);});+ pills.push('<span class="stat-pill">3D · GLB</span>');+ 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>`);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');+ const useBtn = $('avatar-detail-use');+ const viewBtn = $('avatar-detail-view');+ const dlBtn = $('avatar-detail-download');+ const shareBtn = $('avatar-detail-share');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 ? `/app#model=${encodeURIComponent(avatar.glbUrl)}` : '#');- if (dlBtn) { dlBtn.href = avatar.glbUrl || '#'; dlBtn.setAttribute('download', (avatar.slug || avatar.avatarId || 'avatar') + '.glb'); }+ if (viewBtn) viewBtn.href = avatar.viewerUrl || `/app#model=${encodeURIComponent(avatar.glbUrl)}`;+ if (dlBtn) { dlBtn.href = avatar.glbUrl; dlBtn.setAttribute('download', (avatar.slug || avatar.avatarId || 'avatar') + '.glb'); }+ if (shareBtn) {+ shareBtn.onclick = async () => {+ const shareUrl = location.href;+ const shareTitle = `${avatar.name || 'Avatar'} — three.ws`;+ const shareText = avatar.description || 'Check out this 3D avatar on three.ws';+ if (navigator.share) {+ try { await navigator.share({ title: shareTitle, text: shareText, url: shareUrl }); return; }+ catch { /* user cancelled or share unsupported — fall through to copy */ }+ }+ try {+ await navigator.clipboard.writeText(shareUrl);+ const original = shareBtn.textContent;+ shareBtn.textContent = 'Link copied ✓';+ shareBtn.classList.add('copied');+ setTimeout(() => { shareBtn.textContent = original; shareBtn.classList.remove('copied'); }, 1800);+ } catch (err) {+ console.error('[marketplace] share copy', err);+ }+ };+ }- // 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.`;+ // Social meta — make the avatar's own thumbnail/glb show up in link unfurls.+ setSocialMeta({+ title: `${avatar.name} — Community Avatar · three.ws`,+ description: avatar.description || 'A 3D avatar on three.ws — use it as the face of an AI agent.',+ url: location.origin + location.pathname,+ image: avatar.image || _socialMetaDefaults.image,+ });// Inject model-viewer into stage.if (stage) {@@ -1690,7 +1787,17 @@ async function loadAvatarDetail(id) {_avatarDetailMv = mv;}- // Similar avatars — show others from the loaded list (same tags).+ // Mark this id as the active render so re-entries are no-ops, but only+ // now that the render succeeded — a failed fetch above leaves the id null+ // so the user's next click can retry.+ _avatarDetailId = id;++ // Similar avatars — show others with overlapping tags. Deep links land+ // here with state.publicAvatars empty (no list ever fetched); pull the+ // list now so the "Similar avatars" block isn't permanently empty.+ if (!state.publicAvatarsLoaded) {+ await loadPublicAvatars();+ }const similar = state.publicAvatars.filter((a) => a.avatarId !== id && (a.tags || []).some((t) => (avatar.tags || []).includes(t))).slice(0, 8);@@ -2648,6 +2755,12 @@ function render() {const setHidden = (el, hidden) => { if (el) el.hidden = hidden; };const avatarDetailSec = $('market-avatar-detail');+ // Leaving the avatar-detail view: clear the cached id so re-entry reloads+ // cleanly, and restore the page's default social meta.+ if (r.view !== 'avatar-detail' && _avatarDetailId !== null) {+ _avatarDetailId = null;+ resetSocialMeta();+ }if (r.view === 'avatar-detail') {loadAvatarDetail(r.id);setHidden(discovery, true);@@ -2673,6 +2786,7 @@ function render() {setHidden(skillsSec, true);setHidden(mineSec, true);setHidden(purchasesSec, true);+ setHidden(avatarDetailSec, true);setHidden(tools, false);if (!pluginState.loaded) loadPlugins(true);} else if (r.view === 'skills') {@@ -2681,6 +2795,7 @@ function render() {setHidden(tools, true);setHidden(mineSec, true);setHidden(purchasesSec, true);+ setHidden(avatarDetailSec, true);setHidden(skillsSec, false);loadSkillsTab();} else if (r.view === 'mine') {@@ -2689,6 +2804,7 @@ function render() {setHidden(tools, true);setHidden(skillsSec, true);setHidden(purchasesSec, true);+ setHidden(avatarDetailSec, true);setHidden(mineSec, false);loadMine();} else if (r.view === 'purchases') {@@ -2697,6 +2813,7 @@ function render() {setHidden(tools, true);setHidden(skillsSec, true);setHidden(mineSec, true);+ setHidden(avatarDetailSec, true);setHidden(purchasesSec, false);loadPurchases();} else {diff --git a/vercel.json b/vercel.jsonindex d32867b97..76c4ced97 100644--- a/vercel.json+++ b/vercel.json@@ -324,6 +324,18 @@"src": "/studio/(.*)","dest": "/studio/$1"},+ {+ "src": "/avatar-studio",+ "dest": "/avatar-studio/index.html"+ },+ {+ "src": "/avatar-studio/",+ "dest": "/avatar-studio/index.html"+ },+ {+ "src": "/avatar-studio/(.*)",+ "dest": "/avatar-studio/$1"+ },{"src": "/demos","dest": "/demos/index.html"diff --git a/vite.config.js b/vite.config.jsindex 9dd0f1117..107fbed6c 100644--- a/vite.config.js+++ b/vite.config.js@@ -393,6 +393,30 @@ const appConfig = {res.setHeader('Content-Type', 'text/html; charset=utf-8');return res.end(html);}+ // Avatar Studio (rebranded Character Studio fork) — serve the+ // production build out of character-studio/build/ at /avatar-studio/*+ // so the demo iframe works in dev. Run `npm run build --prefix+ // character-studio` first to populate the build dir.+ if (path === '/avatar-studio' || path === '/avatar-studio/') {+ const indexPath = resolve(root, 'character-studio/build/index.html');+ if (existsSync(indexPath)) {+ res.setHeader('Content-Type', 'text/html; charset=utf-8');+ return createReadStream(indexPath).pipe(res);+ }+ res.statusCode = 503;+ return res.end('Avatar Studio build missing — run `npm run build --prefix character-studio`');+ }+ if (path.startsWith('/avatar-studio/')) {+ const ext = path.split('.').pop().toLowerCase();+ const mimes = { js: 'application/javascript', map: 'application/json', css: 'text/css', json: 'application/json', html: 'text/html', ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', glb: 'model/gltf-binary', gltf: 'model/gltf+json', vrm: 'application/octet-stream', obj: 'text/plain', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', svg: 'image/svg+xml', ico: 'image/x-icon', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', wasm: 'application/wasm' };+ const rel = path.slice('/avatar-studio/'.length);+ const fileDisk = resolve(root, 'character-studio/build', rel);+ if (existsSync(fileDisk) && statSync(fileDisk).isFile()) {+ res.setHeader('Content-Type', mimes[ext] || 'application/octet-stream');+ return createReadStream(fileDisk).pipe(res);+ }+ return next();+ }if (path.startsWith('/rider/')) {const ext = path.split('.').pop().toLowerCase();const mimes = { js: 'application/javascript', map: 'application/json', css: 'text/css', json: 'application/json', html: 'text/html', ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', glb: 'model/gltf-binary', gltf: 'model/gltf+json', obj: 'text/plain', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', svg: 'image/svg+xml', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf' };@@ -511,6 +535,22 @@ const appConfig = {});},},+ {+ // Mirror the rebranded Character Studio build (the @m3-org fork in+ // character-studio/, served as "Avatar Studio" under three.ws) into+ // dist/avatar-studio/. The avatar-sdk Creator iframe loads this URL.+ // The fork must be built (`npm run build --prefix character-studio`)+ // before the main build runs — wired into npm run build:vercel.+ name: 'copy-avatar-studio',+ closeBundle() {+ const src = resolve(__dirname, 'character-studio/build');+ if (!existsSync(src)) {+ console.warn('[copy-avatar-studio] character-studio/build/ missing — run `npm run build --prefix character-studio` first');+ return;+ }+ cpSync(src, resolve(__dirname, 'dist/avatar-studio'), { recursive: true });+ },+ },{// publicDir copies `public/agent/index.html` verbatim to// `dist/agent/index.html`, but we also register it as a Vite