Skip to content

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.

docs(README): broaden onchain identity coverage beyond EVM (ERC-8004 + Metaplex Core)

nirholase4882986d426
diff --git a/.claude/commands/scaffold-agent.md b/.claude/commands/scaffold-agent.md
new file mode 100644
index 000000000..621546b2d
--- /dev/null
+++ b/.claude/commands/scaffold-agent.md
@@ -0,0 +1,113 @@
+---
+description: Scaffold a new three.ws AI agent in the current project — creates an entry file wired to the three.ws SDK, MCP tools, and x402 payments. Pass a name: /scaffold-agent MyAgent
+---
+
+You are scaffolding a new three.ws agent into the user's project. The argument `$ARGUMENTS` is the agent name (default: `MyAgent` if blank).
+
+## Step 1 — Detect project type
+
+Check the current working directory for:
+- `package.json` → Node.js / browser project
+- `vite.config.*` → Vite frontend
+- `next.config.*` → Next.js
+- No package.json → standalone HTML
+
+Read `package.json` if present to understand the existing stack.
+
+## Step 2 — Install dependencies
+
+For Node.js projects, run:
+
+```bash
+npm install @nirholas/agent-kit @x402/mcp @modelcontextprotocol/sdk/client
+```
+
+If the project uses a lockfile other than `package-lock.json` (yarn.lock → yarn, pnpm-lock.yaml → pnpm), use the right package manager.
+
+## Step 3 — Create the agent entry file
+
+Create `agent.js` (or `agent.ts` if TypeScript is detected) in the project root with this structure, substituting `$ARGUMENTS` for the agent name:
+
+```js
+import { AgentKit } from '@nirholas/agent-kit';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+
+// Connect to the three.ws paid MCP tools
+const transport = new StdioClientTransport({
+ command: 'npx',
+ args: ['-y', '@3d-agent/mcp-server'],
+ env: {
+ MCP_EVM_PAYMENT_ADDRESS: process.env.EVM_WALLET_ADDRESS ?? '',
+ MCP_SVM_PAYMENT_ADDRESS: process.env.SOLANA_WALLET_ADDRESS ?? '',
+ },
+});
+
+const mcp = new Client({ name: '<AgentName>', version: '1.0.0' });
+await mcp.connect(transport);
+
+// Mount the three.ws chat + avatar panel
+const agent = new AgentKit({
+ name: '<AgentName>',
+ description: 'A three.ws AI agent',
+ endpoint: process.env.AGENT_ENDPOINT ?? 'http://localhost:3000',
+ onMessage: async (text, context) => {
+ // Your LLM call goes here — replace with Anthropic, OpenAI, or Vercel AI SDK
+ return `Echo: ${text}`;
+ },
+});
+
+// Use paid MCP tools
+export async function getPose(prompt) {
+ const result = await mcp.callTool('get_pose_seed', { prompt });
+ return JSON.parse(result.content[0].text);
+}
+
+export async function getTokenSnapshot(mint) {
+ const result = await mcp.callTool('pump_snapshot', { mint });
+ return JSON.parse(result.content[0].text);
+}
+
+export { agent, mcp };
+```
+
+Replace `<AgentName>` with the actual value from `$ARGUMENTS`.
+
+## Step 4 — Create `.env.example`
+
+If `.env.example` does not already exist, create it:
+
+```env
+# three.ws agent configuration
+AGENT_ENDPOINT=http://localhost:3000
+
+# Wallet addresses for x402 USDC payments to the MCP server
+EVM_WALLET_ADDRESS=0x...
+SOLANA_WALLET_ADDRESS=...
+
+# Optional: Helius for richer pump.fun data
+HELIUS_API_KEY=
+
+# Optional: Coinbase CDP for Bazaar discovery
+CDP_API_KEY_ID=
+CDP_API_KEY_SECRET=
+```
+
+If `.env.example` already exists, append only the missing keys.
+
+## Step 5 — Add npm script
+
+In `package.json`, add under `"scripts"`:
+```json
+"agent": "node agent.js"
+```
+
+## Step 6 — Report
+
+Tell the user:
+1. What files were created or modified
+2. To copy `.env.example` → `.env` and fill in wallet addresses
+3. To run `npm run agent` to start
+4. That the agent will be available at `http://localhost:3000` by default
+
+If any step fails (missing package.json, write permission error, etc.), report the exact error and ask how to proceed.
diff --git a/.claude/commands/setup-mcp.md b/.claude/commands/setup-mcp.md
new file mode 100644
index 000000000..8dcc5e7ba
--- /dev/null
+++ b/.claude/commands/setup-mcp.md
@@ -0,0 +1,81 @@
+---
+description: Configure the @3d-agent/mcp-server in Claude Desktop, Claude Code, or Cursor — outputs the exact JSON snippet and optionally writes it to your config file.
+---
+
+You are helping the user add the `@3d-agent/mcp-server` to their MCP client config. Follow these steps precisely:
+
+## Step 1 — Detect OS and find the config file
+
+Check the user's platform:
+
+- **macOS Claude Desktop:** `~/Library/Application Support/Claude/claude_desktop_config.json`
+- **Windows Claude Desktop:** `%APPDATA%\Claude\claude_desktop_config.json`
+- **Claude Code (project):** `.mcp.json` in the current working directory
+- **Claude Code (global):** `~/.claude/claude_desktop_config.json`
+- **Cursor:** `~/.cursor/mcp.json`
+
+Use `uname -s` or `$OS` to detect the platform. Check which of these files already exists with the shell.
+
+## Step 2 — Collect wallet addresses
+
+Ask the user (in a single message) for:
+
+1. **EVM wallet address** (Base USDC payouts) — `0x...` format
+2. **Solana wallet address** (Solana USDC payouts) — base58 format
+3. **Helius API key** (optional, improves pump_snapshot data — get free at helius.dev)
+4. **CDP API key ID + secret** (optional, enables Coinbase Bazaar discovery — get at portal.cdp.coinbase.com)
+
+If the user skips any optional field, omit that env var from the config.
+
+## Step 3 — Generate the config snippet
+
+Produce the exact JSON block to add to their config file under `"mcpServers"`:
+
+```json
+{
+ "mcpServers": {
+ "3d-agent": {
+ "command": "npx",
+ "args": ["-y", "@3d-agent/mcp-server"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "<their EVM address>",
+ "MCP_SVM_PAYMENT_ADDRESS": "<their Solana address>"
+ }
+ }
+ }
+}
+```
+
+Add optional env vars only if the user supplied them:
+- `"HELIUS_API_KEY": "<key>"` — better pump.fun token data
+- `"CDP_API_KEY_ID": "<id>"` and `"CDP_API_KEY_SECRET": "<secret>"` — Coinbase Bazaar discovery
+- `"SOLANA_RPC_URL": "https://mainnet.helius-rpc.com/?api-key=<key>"` — if Helius key provided
+
+If the config file already exists, read it first and **merge** the `"3d-agent"` entry into the existing `"mcpServers"` object rather than replacing the whole file.
+
+## Step 4 — Write or show
+
+Ask the user: "Should I write this to `<config path>` now, or do you want to paste it yourself?"
+
+- If they say write: use the Write or Edit tool to update the file.
+- If they say paste: display the final JSON block in a code fence with clear copy instructions.
+
+## Step 5 — Verify
+
+After writing, confirm the file is valid JSON with:
+```bash
+node -e "JSON.parse(require('fs').readFileSync('<path>', 'utf8')); console.log('valid')"
+```
+
+Then tell the user to restart Claude Desktop / Claude Code / Cursor for the tools to appear.
+
+## Tools available
+
+Once configured, these four paid tools will be available (settled in USDC via x402):
+
+| Tool | Price | What it does |
+|------|-------|--------------|
+| `get_pose_seed` | $0.001 | Deterministic pose map for a three.ws avatar |
+| `pump_snapshot` | $0.005 | Live pump.fun token snapshot — price, volume, holders |
+| `agent_reputation` | $0.01 | ERC-8004 reputation lookup on any EVM chain |
+| `vanity_grinder` | up to $0.50 | Mine a Solana keypair with a custom address prefix |
diff --git a/.claude/commands/use-tools.md b/.claude/commands/use-tools.md
new file mode 100644
index 000000000..2d8f8abdb
--- /dev/null
+++ b/.claude/commands/use-tools.md
@@ -0,0 +1,67 @@
+---
+description: Show ready-to-run code for calling any of the four @3d-agent/mcp-server paid tools. Pass a tool name: /use-tools pump_snapshot
+---
+
+You are producing a working code example for a specific three.ws MCP tool. `$ARGUMENTS` is the tool name the user wants to use. If blank, show a menu of all four tools.
+
+## Tool catalog
+
+| Tool | Price | Input | Output |
+|------|-------|-------|--------|
+| `get_pose_seed` | $0.001 | `{ prompt: string }` | Pose map with Euler rotations (radians) + previewUrl |
+| `pump_snapshot` | $0.005 | `{ mint: string }` | USD price, 24h volume, holders, metadata, bundle signals |
+| `agent_reputation` | $0.01 | `{ agentId: string, chainId?: number }` | Reputation score, stake, recent events from ReputationRegistry |
+| `vanity_grinder` | up to $0.50 | `{ prefix: string, suffix?: string }` | Solana keypair whose address starts with `prefix` |
+
+## If `$ARGUMENTS` is blank
+
+List all four tools in a table and ask: "Which tool do you want to use?"
+
+## If `$ARGUMENTS` names a tool
+
+Produce a complete, runnable Node.js script for that tool. The script must:
+
+1. Spawn the MCP server via `StdioClientTransport` using `npx @3d-agent/mcp-server`
+2. Set `MCP_EVM_PAYMENT_ADDRESS` and `MCP_SVM_PAYMENT_ADDRESS` from env
+3. Use `wrapMCPClientWithPayment` from `@x402/mcp` for automatic 402 retry with a real EVM private key from `process.env.AGENT_EVM_PRIVATE_KEY`
+4. Call the tool and `console.log` the parsed result
+5. Close the transport
+
+### Template for `get_pose_seed`
+
+```js
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { wrapMCPClientWithPayment } from '@x402/mcp';
+import { x402Client } from '@x402/core/client';
+import { ExactEvmScheme } from '@x402/evm/exact/client';
+import { privateKeyToAccount } from 'viem/accounts';
+
+const transport = new StdioClientTransport({
+ command: 'npx',
+ args: ['-y', '@3d-agent/mcp-server'],
+ env: {
+ MCP_EVM_PAYMENT_ADDRESS: process.env.MCP_EVM_PAYMENT_ADDRESS,
+ MCP_SVM_PAYMENT_ADDRESS: process.env.MCP_SVM_PAYMENT_ADDRESS ?? '',
+ },
+});
+
+const mcp = new Client({ name: 'demo', version: '1.0.0' });
+await mcp.connect(transport);
+
+const account = privateKeyToAccount(process.env.AGENT_EVM_PRIVATE_KEY);
+const x402 = new x402Client().register('eip155:8453', new ExactEvmScheme(account));
+const paid = wrapMCPClientWithPayment(mcp, x402, { autoPayment: true });
+
+const result = await paid.callTool('get_pose_seed', { prompt: 'warrior stance' });
+console.log(JSON.parse(result.content[0].text));
+
+await transport.close();
+```
+
+Adapt the tool name, input, and any tool-specific notes (e.g., for `vanity_grinder` note that the returned secret key must be treated as a secret and stored securely; for `agent_reputation` note that `agentId` can be an EVM address and `chainId` defaults to Base).
+
+After the code block, add a one-paragraph note on:
+- What env vars are required (`AGENT_EVM_PRIVATE_KEY`, `MCP_EVM_PAYMENT_ADDRESS`, and optionally `MCP_SVM_PAYMENT_ADDRESS`)
+- That the x402 payment (~$0.001–$0.50 USDC) is deducted automatically from the EVM wallet on each successful call
+- Where to get a free Helius RPC if they want better Solana data for `pump_snapshot`
diff --git a/.mcp.json b/.mcp.json
index f7740a4c8..5dbac999e 100644
--- a/.mcp.json
+++ b/.mcp.json
@@ -5,6 +5,14 @@
"headers": {
"Authorization": "Bearer sk_live_nFp3_eDJzJolnNjU27Jf1KKWuj4agpQs7Q-79Q"
}
+ },
+ "3d-agent-local": {
+ "command": "node",
+ "args": ["mcp-server/src/index.js"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "${MCP_EVM_PAYMENT_ADDRESS}",
+ "MCP_SVM_PAYMENT_ADDRESS": "${MCP_SVM_PAYMENT_ADDRESS}"
+ }
}
}
}
\ No newline at end of file
diff --git a/README.md b/README.md
index 3981b194a..bc07f29b5 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,16 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
![three.ws skills demo](https://github.com/nirholas/3D-Agent/raw/refs/heads/main/.github/assets/skills.gif)
+[![Live site](https://img.shields.io/badge/live-three.ws-2ea44f?logo=vercel&logoColor=white)](https://three.ws)
+[![Version](https://img.shields.io/badge/version-1.5.1-2ea44f)](package.json)
+[![License](https://img.shields.io/badge/license-Apache--2.0-2ea44f)](LICENSE)
+[![Node](https://img.shields.io/badge/node-24.x-2ea44f?logo=node.js&logoColor=white)](package.json)
+[![Three.js](https://img.shields.io/badge/three.js-r176-2ea44f?logo=three.js&logoColor=white)](https://threejs.org)
+[![MCP Registry](https://img.shields.io/badge/MCP%20Registry-io.github.nirholas%2Fthree.ws-2ea44f)](https://registry.modelcontextprotocol.io/?q=three.ws)
+[![Code of Conduct](https://img.shields.io/badge/code%20of%20conduct-Contributor%20Covenant-2ea44f)](CODE_OF_CONDUCT.md)
+
+**Quick links:** [Live site](https://three.ws) · [Quickstart](#getting-started) · [Examples](#examples) · [API reference](#api-reference) · [Tutorials](#tutorials) · [Roadmap](#roadmap) · [Design specs](#design-docs--specs)
+
---
## Table of Contents
@@ -19,7 +29,9 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
- [Ecosystem Directories](#ecosystem-directories)
- [Screenshots](#screenshots)
- [Architecture](#architecture)
+ - [Design Docs & Specs](#design-docs--specs)
- [Tech Stack](#tech-stack)
+ - [Browser Support](#browser-support)
- [Getting Started](#getting-started)
- [Examples](#examples)
- [Tutorials](#tutorials)
@@ -48,6 +60,7 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
- [News CMS & Syndication](#news-cms--syndication)
- [Security Hardening](#security-hardening)
- [Developer SDKs](#developer-sdks)
+- [Claude Code Integration](#claude-code-integration)
- [Demos Hub](#demos-hub)
- [Skill Library](#skill-library)
- [Animation System](#animation-system)
@@ -56,12 +69,14 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
- [API Reference](#api-reference)
- [Authentication & OAuth 2.1](#authentication--oauth-21)
- [MCP Server](#mcp-server)
-- [On-Chain Identity (ERC-8004)](#on-chain-identity-erc-8004)
+- [On-Chain Identity (ERC-8004 + Metaplex Core)](#on-chain-identity-erc-8004--metaplex-core)
- [Pump.fun Integration](#pumpfun-integration)
- [Database Schema](#database-schema)
- [Build & Deployment](#build--deployment)
+ - [Versioning & Compatibility](#versioning--compatibility)
- [Environment Variables](#environment-variables)
- [Testing](#testing)
+- [FAQ & Troubleshooting](#faq--troubleshooting)
- [Contributing](#contributing)
- [Contributors](#contributors)
- [License](#license)
@@ -78,7 +93,7 @@ At its core, it does four things:
2. **Embody** — wraps any avatar with an LLM brain. The agent listens to the user, thinks with Claude, executes tools (animations, gestures, memory operations, skill calls), and expresses emotion through morph-target blending on the 3D model in real time.
-3. **Register** — optionally mints the agent as an ERC-8004 token on any EVM chain, giving it a stable on-chain identity, a wallet address, signed action history, and a reputation score that cannot be forged.
+3. **Register** — optionally mints the agent on-chain: as an **ERC-8004 token on any EVM chain**, or as a **Metaplex Core NFT on Solana**. Either path gives the agent a stable on-chain identity, a wallet address, signed action history, and a reputation score that cannot be forged.
4. **Embed** — distributes the agent as an `<agent-3d>` web component that anyone can drop into a page, or as one of five purpose-built widget types (turntable, animation gallery, talking agent, passport card, hotspot tour) with Open Graph and oEmbed support built in.
@@ -92,7 +107,7 @@ three.ws is production-ready and serves [three.ws](https://three.ws) live. The e
One day, creating your agent should be as simple as taking a selfie.
-Point your camera at yourself — or anyone — and watch a fully realized 3D avatar emerge: your face, your voice, your personality, alive in the browser. That avatar becomes an agent with memory and skills, registered onchain as an ERC-8004 token, permanent and verifiable by anyone forever. No 3D software. No wallet setup. No uploads. Just a photo and a name.
+Point your camera at yourself — or anyone — and watch a fully realized 3D avatar emerge: your face, your voice, your personality, alive in the browser. That avatar becomes an agent with memory and skills, registered onchain — as an ERC-8004 token on EVM or a Metaplex Core asset on Solana — permanent and verifiable by anyone forever. No 3D software. No wallet setup. No uploads. Just a photo and a name.
This is the direction three.ws is heading: **photo → avatar → agent → onchain identity**, in a single flow. The infrastructure is already here — the viewer, the runtime, the contracts, the embedding layer. What comes next is closing the gap between a picture of a person and a living, ownable, embeddable piece of them that exists on the internet permanently.
@@ -102,19 +117,19 @@ This is the direction three.ws is heading: **photo → avatar → agent → onch
three.ws ships in four phases. Each phase closes a specific gap between the current platform and the end-state vision: **anyone can mint a 3D agent of themselves, own it onchain, and embed it anywhere on the internet.**
-| Phase | Theme | Status |
-| ----- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
-| **0** | Platform foundations (viewer, runtime, ERC-8004, embed layer) | ✅ Shipped |
-| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress — capture UX + quality gates shipped; GPU reconstruction backend wiring |
-| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next |
-| **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 Scaffolding — bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; contracts + audits next |
-| **4** | Open inference network (decentralized GPU layer) | 🔮 Future — livepeer dep landed for early experimentation |
+| Phase | Theme | Status |
+| ----- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| **0** | Platform foundations (viewer, runtime, ERC-8004 + Metaplex Core identity, embed layer) | ✅ Shipped |
+| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress — capture UX + quality gates shipped; GPU reconstruction backend wiring |
+| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next |
+| **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 Scaffolding — bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; contracts + audits next |
+| **4** | Open inference network (decentralized GPU layer) | 🔮 Future — livepeer dep landed for early experimentation |
---
### Phase 0 — Foundations _(Shipped)_
-The full stack is live at [three.ws](https://three.ws): WebGL viewer, LLM agent runtime, ERC-8004 identity contracts, OAuth 2.1 server, MCP endpoint, and the `<agent-3d>` web component. Anyone can register an agent today — but the avatar still has to come from a 3D artist or a third-party tool.
+The full stack is live at [three.ws](https://three.ws): WebGL viewer, LLM agent runtime, ERC-8004 identity contracts (EVM) and Metaplex Core mints (Solana), OAuth 2.1 server, MCP endpoint, and the `<agent-3d>` web component. Anyone can register an agent today — but the avatar still has to come from a 3D artist or a third-party tool.
**What works:** model upload, agent runtime, onchain registration, embedding, signed action history, reputation scores.
**What doesn't:** there is no automated path from a real human face to a usable 3D avatar.
@@ -130,7 +145,7 @@ The full stack is live at [three.ws](https://three.ws): WebGL viewer, LLM agent
- Mobile-first capture UX with realtime quality gates (lighting, framing, blur)
- Multi-view face reconstruction pipeline (FLAME / 3DMM fitting on top of a base body mesh)
- Hosted inference workers (GPU-backed) for sub-minute generation
-- Output written directly to R2 + minted as a draft ERC-8004 token
+- Output written directly to R2 and minted as a draft agent token — ERC-8004 on EVM, Metaplex Core asset on Solana
**Compute requirements**
@@ -256,7 +271,7 @@ If you want to support the project — compute credits, grants, partnerships, or
**Identity & On-Chain**
-- ERC-8004 smart contracts (IdentityRegistry, ReputationRegistry, ValidationRegistry) deployable on any EVM chain
+- ERC-8004 smart contracts (IdentityRegistry, ReputationRegistry, ValidationRegistry) deployable on any EVM chain — plus a **program-free Metaplex Core analog on Solana** (asset pubkey = agent ID, SPL Memo–anchored reputation + validation attestations)
- Each agent is an ERC-721 token with a stable `agentId`, owner wallet, delegated signer (EIP-712), and IPFS-pinned manifest
- Signed action log — every `speak`, `remember`, `skill-done`, and `validate` event is recorded on-chain-optionally or in the database with a cryptographic signature
- EIP-7710 delegated permissions for composable agent-to-agent authorization
@@ -333,10 +348,10 @@ A map of every user-facing route. Full detail (source files, feature description
three.ws is available on major cloud marketplaces and open to infrastructure partnerships.
-| Cloud | Status |
-| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |
-| **Google Cloud** | three.ws runs on WebGL, Vercel edge, and EVM — a natural fit for GCP's AI infrastructure, Vertex AI, and global CDN. Open to co-listing, credits, and joint GTM. |
+| Cloud | Status |
+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |
+| **Google Cloud** | three.ws runs on WebGL, Vercel edge, EVM (15+ chains), and Solana (Metaplex Core) — a natural fit for GCP's AI infrastructure, Vertex AI, and global CDN. Open to co-listing, credits, and joint GTM. |
## Ecosystem Directories
@@ -373,8 +388,8 @@ The platform is organized into four layers. All layers communicate through a sin
↓ protocol events
┌────────────────────────────────────────────────────────────┐
│ Layer 3: Identity & Persistence │
-│ Agent passport · ERC-8004 on-chain registry │
-│ Signed action log · Memory store · Wallet linking │
+│ Agent passport · ERC-8004 (EVM) + Metaplex Core (Solana) │
+│ Signed action log · Memory store · Cross-chain SIWX │
└────────────────────────────────────────────────────────────┘
↓ protocol events
┌────────────────────────────────────────────────────────────┐
@@ -394,6 +409,28 @@ The event bus decouples every component. The avatar emotion system reacts to `sp
The backend is stateless serverless functions. All persistent state lives in Postgres (Neon), object storage (Cloudflare R2), or on-chain. Cron jobs handle scheduled blockchain operations (ERC-8004 crawl, DCA execution, subscription execution).
+### Design Docs & Specs
+
+The architecture above is the bird's-eye view; each load-bearing surface has a dedicated spec that defines its wire format, invariants, and extension points. New contributors should skim the spec for any subsystem they're about to change.
+
+| Spec | What it covers |
+| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
+| [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md) | Agent manifest JSON schema — body, brain, voice, memory, skills, signing. The contract every `<agent-3d>` reads. |
+| [specs/3D_AGENT_CARD.md](specs/3D_AGENT_CARD.md) | The on-chain passport card layout — fields, signing, and rendering rules. |
+| [specs/SKILL_SPEC.md](specs/SKILL_SPEC.md) | Skill bundle layout (`SKILL.md`, `tools.json`, `handlers.js`), trust modes, and distribution. |
+| [specs/PERMISSIONS_SPEC.md](specs/PERMISSIONS_SPEC.md) | EIP-7710 delegated permissions model — capability scopes, redemption, revocation. |
+| [specs/MEMORY_SPEC.md](specs/MEMORY_SPEC.md) | Memory file format, types, salience model, and storage modes. |
+| [specs/STAGE_SPEC.md](specs/STAGE_SPEC.md) | Scene/stage configuration: camera presets, lighting, environment maps, hotspots. |
+| [specs/EDITOR_SPEC.md](specs/EDITOR_SPEC.md) | Widget Studio + Embed Editor configuration surface and persistence shape. |
+| [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md) | The `<agent-3d>` element and chromeless iframe — attributes, JS API, and lifecycle. |
+| [specs/EMBED_HOST_PROTOCOL.md](specs/EMBED_HOST_PROTOCOL.md) | `postMessage` wire protocol between the iframe and its host page (origin lock, message kinds, RTT). |
+| [specs/CLAUDE_ARTIFACT.md](specs/CLAUDE_ARTIFACT.md) | Claude Artifact viewer integration — snippet loading and sandbox boundaries. |
+| [specs/ENS_AGENT_CLAIM.md](specs/ENS_AGENT_CLAIM.md) | ENS-based agent claim flow for verifiable owner ↔ agent binding. |
+| [specs/VALIDATORS.md](specs/VALIDATORS.md) | Validator attestation rules — what gets signed, who can sign, how to read attestations. |
+| [specs/SECURITY.md](specs/SECURITY.md) | Threat model, trust boundaries, and the hardening checklist for production deployments. |
+
+Longer-form architecture and how-to documentation lives under [docs/](docs/): [docs/architecture.md](docs/architecture.md), [docs/agent-system.md](docs/agent-system.md), [docs/web-component.md](docs/web-component.md), [docs/api-reference.md](docs/api-reference.md), [docs/mcp.md](docs/mcp.md), [docs/permissions.md](docs/permissions.md), [docs/security.md](docs/security.md), [docs/smart-contracts.md](docs/smart-contracts.md), and more.
+
---
## Tech Stack
@@ -418,6 +455,26 @@ The backend is stateless serverless functions. All persistent state lives in Pos
- **Framework**: Foundry for compiling, testing, and deploying the ERC-8004 contracts.
- **Standards**: ERC-721, EIP-712, EIP-7710.
+### Browser Support
+
+The viewer targets every browser that ships WebGL 2.0 on a desktop or modern mobile device. Concrete support matrix:
+
+| Browser | Minimum | Notes |
+| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------ |
+| Chrome / Edge (Chromium) | 113+ | Full feature set including WebGPU experiments behind a flag. Recommended for development. |
+| Safari (macOS / iOS) | 16.4+ | WebGL 2.0, Web Speech recognition (iOS 16.4 added support behind a permission prompt). Voice input requires HTTPS. |
+| Firefox | 115+ | KTX2 / Meshopt decoders all supported. Web Speech recognition is feature-gated by user-locale. |
+| Mobile Safari | iOS 16.4+ | Touch controls and gyroscope mapped through `OrbitControls`. |
+| Android Chrome | 113+ | Full feature set; AR button surfaces a Scene Viewer intent when present. |
+
+**Capabilities and graceful degradation**
+
+- **WebGL 2.0** is required; the viewer refuses to boot without it and shows a fallback message.
+- **WebAssembly** is required for the Draco / KTX2 / Meshopt decoders that ship under [`public/draco/`](public/draco/) and `node_modules/three/examples/jsm/libs/`.
+- **`getUserMedia` (microphone)** requires HTTPS — see [Common gotchas](#common-gotchas). Without it the agent falls back to text input.
+- **`speechSynthesis`** is detected at runtime; agents fall back to silent text replies when TTS is unavailable.
+- **WebGPU** is not required and is not used yet — Phase 4 reserves it for client-side inference experiments.
+
---
## Getting Started
@@ -701,13 +758,13 @@ You can find your agent ID in the agent's settings page. This method is great fo
Step-by-step guides in [`docs/tutorials/`](docs/tutorials/):
-| Tutorial | What you'll build | Time |
-| -------------------------------------------------------------- | ---------------------------------------------------------------- | ------- |
-| [Build Your First Agent](docs/tutorials/first-agent.md) | A talking 3D character on a shareable page, from zero | ~20 min |
-| [Embed on Your Website](docs/tutorials/embed-on-website.md) | Add an agent to any page — plain HTML, React, Webflow, WordPress | ~15 min |
-| [Write a Custom Skill](docs/tutorials/custom-skill.md) | A new tool the agent can call (e.g., fetch live weather data) | ~30 min |
-| [Register On-Chain](docs/tutorials/register-onchain.md) | Mint your agent as an ERC-8004 token with permanent identity | ~20 min |
-| [Build a Personal AI Site](docs/tutorials/personal-ai-site.md) | A full personal site with an embedded AI version of yourself | ~45 min |
+| Tutorial | What you'll build | Time |
+| -------------------------------------------------------------- | -------------------------------------------------------------------- | ------- |
+| [Build Your First Agent](docs/tutorials/first-agent.md) | A talking 3D character on a shareable page, from zero | ~20 min |
+| [Embed on Your Website](docs/tutorials/embed-on-website.md) | Add an agent to any page — plain HTML, React, Webflow, WordPress | ~15 min |
+| [Write a Custom Skill](docs/tutorials/custom-skill.md) | A new tool the agent can call (e.g., fetch live weather data) | ~30 min |
+| [Register On-Chain](docs/tutorials/register-onchain.md) | Mint your agent onchain — ERC-8004 on EVM or Metaplex Core on Solana | ~20 min |
+| [Build a Personal AI Site](docs/tutorials/personal-ai-site.md) | A full personal site with an embedded AI version of yourself | ~45 min |
### Common gotchas
@@ -742,7 +799,7 @@ For sandboxed iframes use the widget embed path instead — it runs in its own b
- `contracts/`: Solidity smart contracts for on-chain identity (ERC-8004) and the multichain payment factory.
- `multiplayer/`: Colyseus WebSocket server for `/walk` and other realtime rooms; deployable on Fly.io.
- `sdk/`: `@nirholas/agent-kit` and the Avatar SDK (`sdk/agent-sdk/`).
-- `agent-payments-sdk/`: EVM agent payments SDK.
+- `agent-payments-sdk/`: EVM agent payments SDK (Base / BSC / other EVM chains).
- `solana-agent-sdk/`: SDK for Solana blockchain interactions (Metaplex Core mints, SIWS, attestations).
- `pump-fun-skills/`: Skills related to the pump.fun integration.
- `scripts/`: Node.js scripts for development, build, deployment, and pump.fun launch automation.
@@ -1243,7 +1300,7 @@ three.ws ships with Mobile Wallet Adapter (MWA) wired into the web app and a rel
- MWA detection prefers seed-vault-backed signing on Seeker / Saga devices, falls back to WalletConnect elsewhere
- dApp Store listing assets, icons, and staging copy live under `public/seeker/`
- Release pipeline scripts handle build → sign → submit for the dApp Store update
-- On Seeker hardware, users sign x402 payments and ERC-8004 registrations from the seed vault — no browser extension required
+- On Seeker hardware, users sign x402 payments and Solana agent registrations (Metaplex Core mints, attestations) from the seed vault — no browser extension required
---
@@ -1251,12 +1308,12 @@ three.ws ships with Mobile Wallet Adapter (MWA) wired into the web app and a rel
Anyone takes 3 selfies (left, center, right) and receives a rigged, animatable 3D avatar in under a minute. The pipeline ships native — no third-party black box.
-| Module | Path | Role |
-| ------------- | ------------------------------------------------ | ---------------------------------------------------------------------------------- |
-| Capture UX | [src/selfie-capture.js](src/selfie-capture.js) | Mobile-first 3-shot capture with real-time quality gates (lighting, framing, blur) |
-| Pipeline | [src/selfie-pipeline.js](src/selfie-pipeline.js) | Multi-view fit → FLAME / 3DMM face → base body mesh → rigged GLB |
-| Sandbox route | `/creating` | Isolated reconstruction test bench, decoupled from the main flow |
-| Output | Cloudflare R2 | Meshopt-compressed GLB pinned to IPFS and minted as a draft ERC-8004 token |
+| Module | Path | Role |
+| ------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
+| Capture UX | [src/selfie-capture.js](src/selfie-capture.js) | Mobile-first 3-shot capture with real-time quality gates (lighting, framing, blur) |
+| Pipeline | [src/selfie-pipeline.js](src/selfie-pipeline.js) | Multi-view fit → FLAME / 3DMM face → base body mesh → rigged GLB |
+| Sandbox route | `/creating` | Isolated reconstruction test bench, decoupled from the main flow |
+| Output | Cloudflare R2 | Meshopt-compressed GLB pinned to IPFS and minted as a draft agent token — ERC-8004 on EVM or Metaplex Core on Solana |
Reconstruction inference runs against the same Anthropic-token-billed Vercel function pool as the agent runtime, with optional offload to the **Livepeer Inference Network** (see below) for GPU-heavy steps.
@@ -1300,7 +1357,7 @@ The per-agent fine-tuned system prompt is stored in the manifest, signed, and pi
## WASM Vanity Grinder
-`/vanity-wallet` is a browser-based vanity-address grinder compiled to WebAssembly. Generate EVM addresses with a prefix (`0xBEEF…`) or pattern in seconds, fully client-side, without leaking the private key to any server.
+`/vanity-wallet` is a browser-based vanity-address grinder compiled to WebAssembly. Generate **EVM addresses** with a prefix (`0xBEEF…`) or pattern, or **Solana addresses** (base58 prefix / suffix, e.g. `…pump`) in seconds, fully client-side, without leaking the private key to any server.
| Module | Path | Role |
| -------------- | ------------------------------- | ------------------------------------------------------ |
@@ -1385,6 +1442,61 @@ The agent-kit also exposes `attestFeedback`, `attestValidation`, and `listAttest
---
+## Claude Code Integration
+
+three.ws ships as a first-class Claude Code SDK. There are two ways to integrate — pick one or use both:
+
+### 1. MCP server (paid tools via `npx`)
+
+Add the `@3d-agent/mcp-server` to your Claude Desktop, Cursor, or Claude Code config in one step:
+
+```json
+{
+ "mcpServers": {
+ "3d-agent": {
+ "command": "npx",
+ "args": ["-y", "@3d-agent/mcp-server"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
+ "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"
+ }
+ }
+ }
+}
+```
+
+| Config file location | Platform |
+| ----------------------------------------------------------------- | ---------------------------- |
+| `~/Library/Application Support/Claude/claude_desktop_config.json` | macOS Claude Desktop |
+| `%APPDATA%\Claude\claude_desktop_config.json` | Windows Claude Desktop |
+| `.mcp.json` in your project root | Claude Code (project-scoped) |
+| `~/.cursor/mcp.json` | Cursor |
+
+Once configured, Claude can call these tools directly in conversation — no API key required, each call is settled in USDC via x402:
+
+| Tool | Price | What it does |
+| ------------------ | ----------- | ----------------------------------------------------------------------------------------- |
+| `get_pose_seed` | $0.001 | Pose map for a three.ws avatar from a plain-text prompt |
+| `pump_snapshot` | $0.005 | Live pump.fun token snapshot — price, volume, holders, trust signals |
+| `agent_reputation` | $0.01 | Agent reputation — ERC-8004 ReputationRegistry on EVM, attestation-memo roll-up on Solana |
+| `vanity_grinder` | up to $0.50 | Mine a Solana keypair with a custom address prefix |
+
+See [`mcp-server/README.md`](mcp-server/README.md) for full environment variable reference and programmatic client usage.
+
+### 2. Slash commands (`.claude/commands/`)
+
+This repo ships three Claude Code slash commands that work in any project referencing this repo:
+
+| Command | What it does |
+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `/setup-mcp` | Detects your OS, collects wallet addresses, and writes the MCP config to the right file — end-to-end, no manual JSON editing |
+| `/scaffold-agent` | Scaffolds a new three.ws agent in your project: installs dependencies, creates `agent.js` with MCP client wiring, and adds `.env.example` |
+| `/use-tools [tool_name]` | Produces a complete, runnable Node.js script for calling a specific paid MCP tool with automatic x402 payment handling |
+
+Commands live in [`.claude/commands/`](.claude/commands/) and are picked up automatically by Claude Code when you open this repo.
+
+---
+
## Demos Hub
`/demos` is a curated index of sandbox pages that exercise individual platform capabilities in isolation. Each demo is a single HTML file in [`public/demos/`](public/demos/) — perfect for screen recordings, bug reproductions, or showing off one feature without the rest of the app.
@@ -1484,7 +1596,7 @@ Every agent can mint a coin alongside its avatar — turning the agent into a tr
| Pump.fun bridge | `POST /api/pump/launch-prep` | Route the launch through pump.fun's bonding curve |
| Direct mint | `contracts/script/` | Deploy a standalone ERC-20 / SPL-22 alongside the agent |
-The coin's metadata points back at the agent's ERC-8004 token, and the agent's manifest references the coin — a two-way binding that the bazaar, marketplace, and reputation registry all read from.
+The coin's metadata points back at the agent's onchain identity — ERC-8004 token on EVM or Metaplex Core asset on Solana — and the agent's manifest references the coin. The two-way binding is read from the bazaar, marketplace, and reputation registry on either chain.
---
@@ -1510,19 +1622,23 @@ The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface i
### Agent API
-| Method | Route | Auth | Description |
-| -------- | ------------------------------ | ------- | -------------------------------- |
-| GET | `/api/agents` | session | List your agents |
-| POST | `/api/agents` | session | Create an agent |
-| GET | `/api/agents/:id` | — | Get agent detail |
-| PATCH | `/api/agents/:id` | session | Update agent |
-| DELETE | `/api/agents/:id` | session | Delete agent |
-| GET | `/api/agents/:id/manifest` | — | Download manifest JSON |
-| POST | `/api/agents/:id/sign` | session | Sign a message with agent wallet |
-| GET/POST | `/api/agents/:id/embed-policy` | session | Manage iframe origin allowlist |
-| POST | `/api/agents/register-prep` | session | Prep EVM on-chain registration |
-| POST | `/api/agents/register-confirm` | session | Confirm EVM registration |
-| POST | `/api/agent-actions` | session | Record signed agent action |
+| Method | Route | Auth | Description |
+| -------- | --------------------------------- | ------- | ---------------------------------------------------------- |
+| GET | `/api/agents` | session | List your agents |
+| POST | `/api/agents` | session | Create an agent |
+| GET | `/api/agents/:id` | — | Get agent detail |
+| PATCH | `/api/agents/:id` | session | Update agent |
+| DELETE | `/api/agents/:id` | session | Delete agent |
+| GET | `/api/agents/:id/manifest` | — | Download manifest JSON |
+| POST | `/api/agents/:id/sign` | session | Sign a message with agent wallet |
+| GET/POST | `/api/agents/:id/embed-policy` | session | Manage iframe origin allowlist |
+| POST | `/api/agents/register-prep` | session | Prep EVM on-chain registration (ERC-8004) |
+| POST | `/api/agents/register-confirm` | session | Confirm EVM registration (ERC-8004) |
+| POST | `/api/agents/register-solana` | session | Mint a Metaplex Core agent NFT on Solana |
+| GET | `/api/agents/solana-attestations` | — | Read Solana feedback / validation memos for an agent |
+| GET | `/api/agents/solana-card` | — | Solana agent passport card (mirrors EVM `/a/[chain]/[id]`) |
+| GET | `/api/agents/solana-reputation` | — | Solana off-chain reputation snapshot |
+| POST | `/api/agent-actions` | session | Record signed agent action |
### Avatar API
@@ -1708,13 +1824,20 @@ _Pump.fun_ ([`api/_mcp/tools/pumpfun.js`](api/_mcp/tools/pumpfun.js))
---
-## On-Chain Identity (ERC-8004)
+## On-Chain Identity (ERC-8004 + Metaplex Core)
+
+three.ws supports two onchain identity paths as first-class peers — every reputation, attestation, and discovery surface reads from both, and SIWX brokers proofs between them so a single agent can hold reputation on both at once.
+
+- **EVM path** — ERC-8004, a draft standard for verifiable 3D agent identity, deployed on Base, BSC, and other supported EVM chains. The `contracts/` directory contains a full Foundry implementation (IdentityRegistry, ReputationRegistry, ValidationRegistry).
+- **Solana path** — Metaplex Core asset minted via the `solana-agent-sdk`. No custom on-chain program is required: the asset pubkey is the agent ID, and feedback / validation events are written as on-chain memos that the indexer rolls up into a reputation score (see the [Solana variant](#solana-variant--same-shape-no-deployed-program) section below).
+
+### ERC-8004 (EVM)
ERC-8004 is a draft standard for verifiable 3D agent identity. The `contracts/` directory contains a full Foundry implementation.
### Contracts
-**IdentityRegistry.sol** — the primary contract. Each agent is an ERC-721 token with:
+**IdentityRegistry.sol** — the primary EVM contract. Each agent is an ERC-721 token with:
- `agentId` — stable numeric ID (the token ID)
- `owner` — EVM address of the agent's owner
@@ -1722,9 +1845,11 @@ ERC-8004 is a draft standard for verifiable 3D agent identity. The `contracts/`
- `tokenURI` — IPFS URL of the agent manifest JSON
- `metadata` — on-chain name, description, image pointer
-**ReputationRegistry.sol** — stores signed feedback scores. Each reviewer can submit one score per agent. Scores are averaged for an on-chain reputation metric.
+On **Solana**, the equivalent identity is a **Metaplex Core asset**: the asset pubkey is the agent ID, the asset's `update_authority` is the owner, and the asset's URI points at the same IPFS-pinned manifest. No custom program is deployed — Metaplex Core handles mint, transfer, and update natively.
+
+**ReputationRegistry.sol** — stores signed feedback scores. Each reviewer can submit one score per agent. Scores are averaged for an on-chain reputation metric. The **Solana analog** is an SPL Memo with envelope `threews.feedback.v1`, posted in a transaction whose accounts include the agent's Metaplex Core asset pubkey — readable by any client via `getSignaturesForAddress`.
-**ValidationRegistry.sol** — records validator attestations for off-chain proofs (glTF validation reports, skill audits, security reviews).
+**ValidationRegistry.sol** — records validator attestations for off-chain proofs (glTF validation reports, skill audits, security reviews). The **Solana analog** uses SPL Memo with envelope `threews.validation.v1` against the agent's Metaplex Core asset pubkey.
### Deployment Addresses
@@ -1770,6 +1895,22 @@ A custom vanity-prefixed CREATE2 deployer at `0x00000000D49195AE81759cd247cFeDD9
The agent is now an ERC-721 token. Its manifest lives on IPFS. Its action history is anchored to its `agentId`. Any third party can verify the agent's identity, owner, and reputation without trusting three.ws.
+### Registration Flow (Solana)
+
+Solana ships an ERC-8004 analog without any custom on-chain program — identity is a Metaplex Core asset, reputation + validation are SPL Memo–anchored attestations referencing that asset.
+
+```
+1. POST /api/agents/register-solana → { tx }
+ (server builds a Metaplex Core mint instruction; client signs)
+
+2. User signs and submits the tx with their Solana wallet (Phantom / Backpack / Seeker MWA)
+
+3. POST /api/agents/register-solana?step=confirm → { asset, agentId }
+ (server verifies the mint, writes back the asset pubkey as the agent's ID)
+```
+
+The agent is now a Metaplex Core NFT. Its asset pubkey is the canonical agent ID. Anyone can read every feedback / validation attestation about it via `getSignaturesForAddress(assetPubkey)` — see [Solana variant — same shape, no deployed program](#solana-variant--same-shape-no-deployed-program) below.
+
### On-Chain Indexing
`api/cron/erc8004-crawl.js` runs every 15 minutes to index new IdentityRegistry mint events. Indexed agents appear in `/discover` and can be imported via `/hydrate`.
@@ -2084,6 +2225,31 @@ server {
}
```
+### Versioning & Compatibility
+
+three.ws follows [Semantic Versioning](https://semver.org). The authoritative version lives in [package.json](package.json); the current release is reflected in the badge at the top of this README.
+
+**What "stable" means**
+
+| Surface | Stability | Versioning |
+| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| `<agent-3d>` web component attributes, JS API, and events | **Stable** — semver-major bumps for breaking changes | Pin a major in your `<script>` tag, e.g. `/agent-3d/1.x/agent-3d.js` |
+| `agent-manifest/0.2` JSON schema | **Stable** within `0.2.x`; `0.3` will be additive where possible | Indicated by the `spec` field on every manifest |
+| Public REST API (`/api/agents`, `/api/widgets`, `/api/avatars`, `/api/chat`) | **Stable** — additive changes only without a major bump | Tracked in the OpenAPI doc at `/openapi.json` |
+| OAuth 2.1 endpoints (`/oauth/*`, `/.well-known/*`) | **Stable** — frozen by the relevant RFCs | n/a |
+| MCP surface at `POST /api/mcp` | **Stable** — pinned to protocol version `2025-06-18`; tool catalogue is additive | The protocol version is part of every response |
+| Internal Vercel functions, helpers under `api/_lib/`, `api/_mcp/` | **Unstable** — no compatibility guarantees | Subject to refactor between releases |
+| Solidity contracts in `contracts/` | **Stable per deployment** — see [contracts/DEPLOYMENTS.md](contracts/DEPLOYMENTS.md) for addresses | New chains add rows; existing deployments are immutable |
+
+**Pinning recommendations**
+
+- For production embeds, pin to the patch version (`/agent-3d/1.5.1/agent-3d.js`) and bump deliberately.
+- For prototypes, pin to the major (`/agent-3d/1.x/agent-3d.js`) so you receive bug-fixes automatically.
+- For agent manifests, always set the `spec` field — the loader rejects manifests with an unknown spec rather than guessing.
+- For API consumers, request `application/json` and inspect the response `version` header (present on every endpoint).
+
+**Deprecation policy.** Stable surfaces get a deprecation notice in the changelog plus a runtime warning for at least one minor release before removal. Anything marked **unstable** in the table above may change at any time.
+
---
## Environment Variables
@@ -2230,9 +2396,50 @@ CREATE2 vanity grinds for the multichain factory and payment contracts are recor
---
+## FAQ & Troubleshooting
+
+**Does three.ws require a wallet to use?**
+No. The viewer, agent runtime, manifest editor, and `/app` work without a wallet or an account. A wallet is only required for on-chain registration (ERC-8004 mint, Solana Metaplex Core mint) and for paid surfaces (x402 endpoints, agent token launches).
+
+**Does my GLB get uploaded anywhere?**
+Not unless you explicitly choose to publish or register the agent. Drag-and-drop in the viewer is fully client-side — the file never leaves the browser. The "Publish" and "Register" flows are the points where the GLB is uploaded to R2.
+
+**Which LLM does the agent use?**
+The default is Anthropic Claude (`claude-sonnet-4-6` for production, `claude-haiku-4-5-20251001` for low-cost development). Brain routing is configurable per-agent through the manifest and via the `brain` attribute on `<agent-3d>`. Other providers can be wired in by extending [`src/runtime/providers.js`](src/runtime/providers.js).
+
+**Can I run three.ws fully offline?**
+Yes for the viewer, no for the agent runtime. With `sandbox` set on `<agent-3d>` the element refuses all network calls; you can still load a local GLB, play animations, and exercise the manifest. The LLM brain, voice, and on-chain features require network connectivity.
+
+**Why does the avatar appear black or all-white?**
+Usually a missing HDR environment or a material that expects an environment map. Confirm the GLB has a default scene, that the lighting attributes (`exposure`, `env`) are set, and that your build has access to `public/env/` (the HDR assets ship there). For all-white avatars, check that morph targets aren't being zeroed by an empty emotion mix.
+
+**The agent never speaks back. What's wrong?**
+Most often the chat input isn't reaching the brain. Check (in order): (1) the `brain` attribute or `manifest.brain` is set; (2) the network panel shows a `POST /api/chat` (or the configured proxy) succeeding; (3) the response body isn't blocked by a Content Security Policy; (4) TTS is supported and not muted at the OS level. If running locally, set `ANTHROPIC_API_KEY` in `.env.local`.
+
+**Why does microphone capture fail on my deployment?**
+`getUserMedia` requires HTTPS. Localhost is exempt; any remote deployment needs TLS. Vercel and Netlify provide it automatically. Self-hosted deployments must terminate TLS in front of the app.
+
+**How big can a GLB be?**
+Hard ceiling: 50 MB before the loader refuses (configurable via the `maxBytes` attribute). Soft target: ≤8 MB for sub-3-second cold start over a typical broadband connection. Run `npx gltf-transform draco input.glb output.glb` and `npx gltf-transform ktx output.glb output.ktx2.glb` to compress aggressively without visual loss.
+
+**Can I host the web component on my own CDN?**
+Yes. Run `npm run build:lib` and serve the resulting `dist-lib/agent-3d.js` from anywhere. Update the `<script>` tag in your embed snippet accordingly. The element has no hard-coded origin assumption — it only contacts the backend you point its `manifest`/`brain` attributes at.
+
+**How do I rotate `JWT_SECRET` without invalidating sessions?**
+Increment `JWT_KID` and add the new secret. Existing tokens continue to validate against the old `kid`; new tokens sign with the new one. Drop the old `kid` from rotation after the session window (default 30 days) expires.
+
+**Where do I get help?**
+
+- Bugs and feature requests: [open a GitHub issue](https://github.com/nirholas/three.ws/issues)
+- Security: see [Reporting Security Issues](#reporting-security-issues)
+- Discussion and showcase: [GitHub Discussions](https://github.com/nirholas/three.ws/discussions)
+- Live status: [three.ws](https://three.ws)
+
+---
+
## Contributing
-See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor guide.
+See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor guide. Contributors are expected to follow the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md) in every project space — issues, pull requests, discussions, and any community channel that links to this repository.
**Quick rules:**
@@ -2256,13 +2463,30 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor guide.
- Set `CHAT_MODEL=claude-haiku-4-5-20251001` locally to keep API costs low during development
- The MCP server can be tested with `curl` — it's plain JSON-RPC over HTTP
+### Reporting Security Issues
+
+Please **do not** file public GitHub issues for vulnerabilities. Disclosure runs on a coordinated timeline so users get a fix before details circulate.
+
+1. Email **[email protected]** (or open a [private GitHub security advisory](https://github.com/nirholas/three.ws/security/advisories/new) on the mirror repos) with a clear write-up: affected component, reproduction steps, and the impact you observed.
+2. You will receive an acknowledgement within two business days.
+3. We aim to ship a fix or mitigation within 30 days for high-severity reports, and to credit reporters in the release notes (unless you ask to remain anonymous).
+
+The current threat model and hardening notes live in [specs/SECURITY.md](specs/SECURITY.md) and [docs/security.md](docs/security.md). The [Security Hardening](#security-hardening) section above summarises the in-tree controls.
+
+In-scope: this repository and its deployed surfaces (`three.ws`, `cdn.three.ws`, `*.three.ws`). Out-of-scope: third-party services we integrate with (Vercel, Neon, Cloudflare R2, Upstash, Privy, Anthropic, ElevenLabs, pump.fun) — please report directly to them.
+
---
## Contributors
-Thanks to everyone who has contributed to this project.
+Thanks to everyone who has contributed to this project. Commit-level contributors are visible in [the GitHub contributors graph](https://github.com/nirholas/three.ws/graphs/contributors); a few standouts:
+- [@nirholas](https://github.com/nirholas) — maintainer
- [@humanoidrobot-glitch](https://github.com/humanoidrobot-glitch) — thank you for your contributions!
+- [@overstepping](https://github.com/overstepping) — thank you for your contributions!
+- [@swarmsyy](https://github.com/swarmsyy) — thank you for your contributions!
+
+Want your name here? Open a PR — see [Contributing](#contributing).
---
diff --git a/STRUCTURE.md b/STRUCTURE.md
new file mode 100644
index 000000000..f5cb74e58
--- /dev/null
+++ b/STRUCTURE.md
@@ -0,0 +1,108 @@
+# Repository Structure
+
+Ready Player Me ships their platform across 30 public GitHub repos —
+[visage](https://github.com/readyplayerme/visage),
+[animation-library](https://github.com/readyplayerme/animation-library),
+[rpm-react-avatar-creator](https://github.com/readyplayerme/rpm-react-avatar-creator),
+[Example-iframe](https://github.com/readyplayerme/Example-iframe),
+[content-validation-schemas](https://github.com/readyplayerme/content-validation-schemas),
+several Unity/Unreal SDKs, and so on.
+
+three.ws ships the same surfaces from a **single npm-workspaces monorepo**.
+This file maps each RPM-equivalent surface to where it lives in this
+repository, so external developers can find what they need without reading 50
+top-level directories.
+
+When an internal surface gains an external consumer that needs an independent
+release cadence, we promote it to its own published package (and optionally its
+own repo via `git subtree split`). See [Promotion path](#promotion-path) at the
+bottom.
+
+## RPM → three.ws surface map
+
+| Ready Player Me repo | three.ws equivalent | Status | Notes |
+|---|---|---|---|
+| [visage](https://github.com/readyplayerme/visage) (web renderer) | [avatar-sdk/](avatar-sdk) `→ /viewer` | Published as `@three-ws/avatar` | Drop-in viewer with `<three-ws-avatar>` web component |
+| [rpm-react-avatar-creator](https://github.com/readyplayerme/rpm-react-avatar-creator) | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath |
+| Avatar Creator (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator |
+| [Example-iframe](https://github.com/readyplayerme/Example-iframe) | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html` |
+| [animation-library](https://github.com/readyplayerme/animation-library) | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline. **Not** derived from RPM's animation-library, whose license forbids redistribution outside RPM avatars |
+| [content-validation-schemas](https://github.com/readyplayerme/content-validation-schemas) | [packages/avatar-schema/](packages/avatar-schema) | Published as `@three-ws/avatar-schema` | JSON Schema for on-chain avatar manifests — three.ws's differentiator |
+| [Lyra-Sample](https://github.com/readyplayerme/Lyra-Sample), [VR-Demo](https://github.com/readyplayerme/VR-Demo) | [multiplayer/](multiplayer), [examples/coach-leo/](examples/coach-leo) | In-repo | Integration demos |
+| [rpm-unity-sdk-core](https://github.com/readyplayerme/rpm-unity-sdk-core), [rpm-unreal-sdk](https://github.com/readyplayerme/rpm-unreal-sdk) | — | Out of scope | three.ws is browser-native; no Unity/Unreal SDKs planned |
+| Avatar service backend | [api/](api) + [workers/](workers) | In-repo | Vercel functions + Cloudflare workers |
+| _(no RPM equivalent — our moat)_ | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 |
+| _(no RPM equivalent — our moat)_ | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs |
+| _(no RPM equivalent — our moat)_ | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge) | Published as `@three-ws/mcp-server` | Model Context Protocol surface |
+
+## npm workspaces
+
+Declared in [package.json](package.json):
+
+```
+agent-payments-sdk/ → @three-ws/agent-payments
+avatar-sdk/ → @three-ws/avatar
+character-studio/ → @m3-org/characterstudio (fork)
+mcp-bridge/ → @three-ws/mcp-bridge
+mcp-server/ → @three-ws/mcp-server
+multiplayer/ → @three-ws/multiplayer
+packages/* → @three-ws/* (new — for clean publishable spec/schema packages)
+```
+
+`packages/` is reserved for spec/schema/protocol packages with no runtime
+dependencies on the main app — things that need to be installable by external
+consumers (e.g. another team building an avatar viewer that wants to validate
+our manifest format).
+
+Runtime SDKs and apps live at the top level for historical compatibility with
+the deploy pipeline and existing import paths.
+
+## Where things actually live
+
+- **3D viewer & creator** — [avatar-sdk/](avatar-sdk), [character-studio/](character-studio)
+- **Avatar / accessory assets** — [public/avatars/](public/avatars), [public/accessories/](public/accessories)
+- **Animations** — [public/animations/](public/animations) (Mixamo FBX → built GLB clips), [scripts/build-animations.mjs](scripts/build-animations.mjs)
+- **On-chain identity & contracts** — [contracts/](contracts), [packages/avatar-schema/](packages/avatar-schema)
+- **API endpoints** — [api/](api) (Vercel functions), [workers/](workers) (Cloudflare workers)
+- **Examples & demos** — [examples/](examples), [multiplayer/](multiplayer)
+- **Cross-chain SDKs** — [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk)
+- **MCP integration** — [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge)
+- **Specs & protocol docs** — [specs/](specs)
+- **Frontend pages** — [src/](src), [pages/](pages), [public/](public)
+- **Tests** — [tests/](tests)
+
+## Promotion path
+
+A surface graduates to its own repo only when there is a concrete external
+need that the monorepo cannot serve:
+
+1. **A third party wants to consume it without pulling our whole tree.**
+ Mitigation: publish to npm under `@three-ws/*` first. If the npm package
+ is enough, no repo split is needed.
+2. **Independent release cadence required.** When the surface needs its own
+ semver line decoupled from the app.
+3. **External contributors blocked.** When the repo size or unrelated CI cost
+ is a real friction for outside PRs.
+
+Promotion procedure (when triggered):
+
+```bash
+# Cleanly split a directory's full history into a new repo
+git subtree split --prefix=packages/avatar-schema -b avatar-schema-split
+cd ../ && mkdir avatar-schema-repo && cd avatar-schema-repo
+git init && git pull ../three.ws avatar-schema-split
+git remote add origin https://github.com/nirholas/avatar-schema.git
+git push -u origin main
+# Then in three.ws: replace the workspace dir with a normal npm dep
+```
+
+Until the trigger fires, splitting is premature: each new repo adds release
+overhead, CI cost, and cross-repo PR coordination tax for zero functional
+gain.
+
+## See also
+
+- [README.md](README.md) — product overview, quickstart, full feature list
+- [CONTRIBUTING.md](CONTRIBUTING.md) — how to propose changes
+- [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) — attribution for derived code and assets
+- [CLAUDE.md](CLAUDE.md) — operating rules for AI agents working in this repo
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..04ee2fc21
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,82 @@
+# Third-Party Notices
+
+three.ws is licensed under [Apache-2.0](LICENSE). It incorporates third-party
+material whose original copyright notices and license terms are reproduced
+below as required.
+
+This file is not exhaustive of npm dependencies — each dependency retains its
+own license as declared in its package metadata. The entries here cover code
+and assets that were copied, forked, or otherwise vendored into this
+repository.
+
+---
+
+## 1. CharacterStudio — [character-studio/](character-studio)
+
+The `character-studio/` directory is derived from
+[M3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio),
+copyright (c) 2022 Atlas Foundation, distributed under the MIT License.
+
+The upstream LICENSE text is reproduced in [character-studio/LICENSE](character-studio/LICENSE).
+
+Modifications by three.ws contributors include integration with the three.ws
+runtime, additional chain providers, and UI changes. Modified portions remain
+under the MIT License with respect to upstream Atlas Foundation copyright; new
+contributions by three.ws are dual-available under Apache-2.0.
+
+---
+
+## 2. Mixamo animations — [public/animations/](public/animations)
+
+The `*.fbx` clips in `public/animations/` and the retargeted `*.glb` clips in
+`public/animations/clips/` are sourced from
+[Adobe Mixamo](https://www.mixamo.com/). Per Adobe's Mixamo FAQ, Mixamo
+animations are licensed royalty-free for personal, commercial, and
+non-profit projects, including as part of products distributed to third
+parties.
+
+The build-time retargeting pipeline that produces the GLB clips is implemented
+in [scripts/build-animations.mjs](scripts/build-animations.mjs).
+
+Mixamo is a trademark of Adobe Inc.
+
+---
+
+## 3. Avatar reference meshes — [public/avatars/](public/avatars)
+
+The reference avatar meshes (`cz.glb`, `default.glb`) used as canonical skeleton
+targets for the animation retargeting pipeline are compatible with the
+[Avaturn](https://avaturn.me/) skeleton layout. Sample assets shipped here are
+used per the originating service's terms for personal and commercial use.
+
+If you ship a downstream product that bundles these meshes, verify the current
+terms of the upstream avatar service for your use case.
+
+---
+
+## 4. Asset notice — accessories
+
+The `*.glb` accessories in [public/accessories/](public/accessories) (hats,
+glasses, earrings) and the procedural club props built by
+[scripts/build-club-props.mjs](scripts/build-club-props.mjs) are original
+content authored for three.ws unless otherwise noted in a sibling
+`ATTRIBUTION.txt` next to a specific asset.
+
+---
+
+## 5. npm dependencies
+
+All npm packages declared in [package.json](package.json) and every workspace
+manifest retain their declared licenses. Run `npx license-checker --summary`
+from the repo root for a current rollup. Notable copyleft-adjacent or
+attribution-requiring dependencies in the dependency tree are listed by that
+report; this file does not duplicate it.
+
+---
+
+## Reporting
+
+If you believe this repository ships content whose attribution is missing,
+incorrect, or whose license terms are not being honored, open an issue at
+<https://github.com/nirholas/three.ws/issues> or email
+<[email protected]> and we will correct it promptly.
diff --git a/api/agent-oembed.js b/api/agent-oembed.js
index 130c45d04..0c9f4e843 100644
--- a/api/agent-oembed.js
+++ b/api/agent-oembed.js
@@ -13,8 +13,8 @@ import { env } from './_lib/env.js';
import { cors, wrap, error } from './_lib/http.js';
import { resolveOnChainAgent, SERVER_CHAIN_META } from './_lib/onchain.js';
-const WIDTH = 420;
-const HEIGHT = 520;
+const DEFAULT_WIDTH = 420;
+const DEFAULT_HEIGHT = 520;
const THUMB_WIDTH = 1200;
const THUMB_HEIGHT = 630;
@@ -25,6 +25,9 @@ export default wrap(async (req, res) => {
const target = url.searchParams.get('url');
const format = (url.searchParams.get('format') || 'json').toLowerCase();
+ const WIDTH = clampDim(url.searchParams.get('maxwidth'), DEFAULT_WIDTH, 100, 2000);
+ const HEIGHT = clampDim(url.searchParams.get('maxheight'), DEFAULT_HEIGHT, 100, 2000);
+
if (!target) return error(res, 400, 'invalid_request', 'url parameter required');
const onchain = extractOnChain(target);
@@ -181,3 +184,9 @@ function escapeAttr(s) {
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
+
+function clampDim(raw, def, min, max) {
+ const n = raw != null ? parseInt(raw, 10) : NaN;
+ if (!Number.isFinite(n) || n <= 0) return def;
+ return Math.max(min, Math.min(max, n));
+}
diff --git a/api/home-stats.js b/api/home-stats.js
new file mode 100644
index 000000000..b14fb1f18
--- /dev/null
+++ b/api/home-stats.js
@@ -0,0 +1,52 @@
+/**
+ * Public marketing stats for the home page.
+ *
+ * GET /api/home-stats
+ *
+ * Returns real counts pulled from Neon. Used by the SaaS prologue strip on
+ * the home page to render live "trusted by" numbers. No auth, edge-cached for
+ * 60s at the CDN. If the DB is unreachable the response is { available: false }
+ * and the home page hides the metrics strip — we never serve fabricated numbers.
+ */
+
+import { sql } from './_lib/db.js';
+import { cors, json, method, wrap } from './_lib/http.js';
+
+const TTL_SECONDS = 60;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ try {
+ const [agentsRow, onchainRow, widgetsRow, chainsRow, attRow] = await Promise.all([
+ sql`SELECT COUNT(*)::int AS n FROM agent_identities WHERE deleted_at IS NULL`,
+ sql`SELECT COUNT(*)::int AS n FROM erc8004_agents_index WHERE active = true`,
+ sql`SELECT COUNT(*)::int AS n FROM widgets WHERE deleted_at IS NULL`,
+ sql`SELECT COUNT(DISTINCT chain_id)::int AS n FROM erc8004_agents_index WHERE active = true`,
+ sql`SELECT COUNT(*)::int AS n FROM solana_attestations`,
+ ]);
+
+ const stats = {
+ available: true,
+ agents: agentsRow[0]?.n ?? 0,
+ onchain_agents: onchainRow[0]?.n ?? 0,
+ widgets: widgetsRow[0]?.n ?? 0,
+ chains: chainsRow[0]?.n ?? 0,
+ attestations: attRow[0]?.n ?? 0,
+ updated_at: new Date().toISOString(),
+ };
+
+ return json(res, 200, stats, {
+ 'cache-control': `public, s-maxage=${TTL_SECONDS}, stale-while-revalidate=${TTL_SECONDS * 5}`,
+ });
+ } catch (err) {
+ console.warn('[home-stats] db_unavailable', err?.message || err);
+ return json(
+ res,
+ 200,
+ { available: false, reason: 'db_unavailable' },
+ { 'cache-control': 'public, s-maxage=15' },
+ );
+ }
+});
diff --git a/api/skills/index.js b/api/skills/index.js
index 42d47ae9f..621fc8c8b 100644
--- a/api/skills/index.js
+++ b/api/skills/index.js
@@ -191,7 +191,7 @@ function runListQuery(p) {
const limitPlus = limit + 1;
if (sort === 'new') {
- const cursorActive = cursor && cursorCreatedAt != null;
+ const cursorActive = Boolean(cursor && cursorCreatedAt != null);
return sql`
SELECT
ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
@@ -235,7 +235,7 @@ function runListQuery(p) {
}
if (sort === 'az') {
- const cursorActive = cursor && cursorName != null;
+ const cursorActive = Boolean(cursor && cursorName != null);
return sql`
SELECT
ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
@@ -279,7 +279,7 @@ function runListQuery(p) {
}
// popular (default)
- const cursorActive = cursor && cursorInstallCount != null;
+ const cursorActive = Boolean(cursor && cursorInstallCount != null);
return sql`
SELECT
ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
diff --git a/api/users/me/bookmarks.js b/api/users/me/bookmarks.js
new file mode 100644
index 000000000..e8a214277
--- /dev/null
+++ b/api/users/me/bookmarks.js
@@ -0,0 +1,55 @@
+/**
+ * GET /api/users/me/bookmarks
+ * Returns the authenticated caller's bookmarked agent IDs and lightweight metadata.
+ * Used by the marketplace client to render filled-in star buttons on grid cards.
+ */
+
+import { sql } from '../../_lib/db.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';
+import { cors, error, json, method, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { publicUrl } from '../../_lib/r2.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id || bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const rows = await sql`
+ SELECT
+ ab.agent_id,
+ ab.created_at,
+ ai.name AS agent_name,
+ ai.description AS agent_description,
+ ai.category AS agent_category,
+ av.thumbnail_key
+ FROM agent_bookmarks ab
+ JOIN agent_identities ai ON ai.id = ab.agent_id AND ai.deleted_at IS NULL
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ab.user_id = ${userId}
+ ORDER BY ab.created_at DESC
+ `;
+
+ const bookmarks = rows.map((r) => ({
+ agent_id: r.agent_id,
+ bookmarked_at: r.created_at,
+ agent_name: r.agent_name,
+ agent_description: r.agent_description,
+ agent_category: r.agent_category,
+ agent_thumbnail: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ }));
+
+ return json(
+ res,
+ 200,
+ { data: { bookmarks, agent_ids: bookmarks.map((b) => b.agent_id) } },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/character-studio/LICENSE b/character-studio/LICENSE
new file mode 100644
index 000000000..79172f9e1
--- /dev/null
+++ b/character-studio/LICENSE
@@ -0,0 +1,25 @@
+MIT License
+
+Copyright (c) 2022 Atlas Foundation
+Copyright (c) 2025 three.ws contributors (modifications)
+
+This directory is derived from M3-org/CharacterStudio
+(https://github.com/M3-org/CharacterStudio).
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/dvis.mjs b/dvis.mjs
new file mode 100644
index 000000000..17e588015
--- /dev/null
+++ b/dvis.mjs
@@ -0,0 +1,26 @@
+import { chromium } from 'playwright';
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 390, height: 800 } });
+await page.goto('http://localhost:3000/marketplace', { waitUntil: 'domcontentloaded' });
+await page.waitForTimeout(1500);
+await page.waitForSelector('.home-nav .nav-root', { state: 'attached', timeout: 10000 });
+await page.waitForTimeout(500);
+
+const positions = await page.evaluate(() => {
+ const rect = (el) => el?.getBoundingClientRect();
+ return {
+ homeNav: rect(document.querySelector('.home-nav')),
+ burger: rect(document.querySelector('.home-nav .nav-burger')),
+ navContainer: rect(document.getElementById('nav-container')),
+ h1: rect(document.querySelector('.site-header-brand')),
+ header: rect(document.querySelector('.site-header')),
+ };
+});
+console.log('Positions:', JSON.stringify(positions, null, 2));
+
+const burger = await page.locator('.home-nav .nav-burger').first();
+await burger.click();
+await page.waitForTimeout(400);
+const rootBox = await page.locator('.home-nav .nav-root').first().boundingBox();
+console.log('Nav root open:', JSON.stringify(rootBox));
+await browser.close();
diff --git a/home-mobile.mjs b/home-mobile.mjs
new file mode 100644
index 000000000..f08493504
--- /dev/null
+++ b/home-mobile.mjs
@@ -0,0 +1,17 @@
+import { chromium } from 'playwright';
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 390, height: 800 } });
+await page.goto('http://localhost:3000/', { waitUntil: 'domcontentloaded' });
+await page.waitForTimeout(1500);
+const data = await page.evaluate(() => {
+ const rect = (el) => el?.getBoundingClientRect();
+ return {
+ homeNav: rect(document.querySelector('.home-nav')),
+ burger: rect(document.querySelector('.home-nav .nav-burger')),
+ navContainer: rect(document.getElementById('nav-container')),
+ h1: rect(document.querySelector('.site-header-brand, header h1')),
+ header: rect(document.querySelector('.site-header, header')),
+ };
+});
+console.log(JSON.stringify(data, null, 2));
+await browser.close();
diff --git a/mcp-server/README.md b/mcp-server/README.md
index 5f9ce197b..e8d585db1 100644
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@ -1,148 +1,139 @@
# @3d-agent/mcp-server
-A local MCP server that exposes the three.ws stack as **paid MCP tools** for
-Claude Desktop, Cursor, and any MCP-compatible client. Each tool quotes a
-USDC price; calls without payment return an `x402` `PaymentRequired`
-envelope (v2 MCP transport spec — `isError: true` + `structuredContent` +
-`content[0].text`). Successful settlements are returned in
-`_meta["x402/payment-response"]` per the spec.
+Four paid MCP tools from [three.ws](https://three.ws) — pose generation, pump.fun token snapshots, ERC-8004 agent reputation, and Solana vanity address mining. Each call is settled in USDC via the [x402](https://x402.org) payment protocol. No subscription, no API key — pay per call.
-## Tools
-
-| Tool | Scheme | Price | What it returns |
-|------|--------|-------|-----------------|
-| `get_pose_seed` | `exact` | $0.001 | Deterministic seed + full Euler-rotation pose map (radians) for the three.ws pose-studio mannequin, picked from the in-repo preset library by matching prompt tokens against preset IDs/labels/groups. Includes a previewUrl pointing at `https://three.ws/pose?seed=…&preset=…`. |
-| `pump_snapshot` | `exact` | $0.005 | Live token snapshot — USD price (Jupiter), 24h volume + pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution (Solana RPC `getTokenLargestAccounts`). Adds Helius DAS data when `HELIUS_API_KEY` is set. |
-| `agent_reputation` | `exact` | $0.01 | ERC-8004 reputation: aggregate `getReputation`, `getTotalStake`, and the latest `ReputationSubmitted` / `ReputationStaked` events from the canonical ReputationRegistry on the requested chain (default Base). Resolves agentId from a wallet when the input is an EVM address. |
-| `vanity_grinder` | `upto` | up to $0.50 | Solana keypair whose base58 address starts with the chosen `prefix` (and optionally ends with `suffix`). Returns the full base58 secret key — handle as a secret. Actual settled USDC scales with iterations: `$0.01 base + $0.0000001 per attempt`, capped at $0.50. |
+---
-All four tools are advertised to the x402 Bazaar via the per-tool
-`declareDiscoveryExtension({ toolName, transport: 'stdio', inputSchema, … })`
-extension that ships in the payment-required envelope. Bazaar-enabled
-facilitators index these tools under `type: "mcp"` once a buyer pays for them.
+## Quickstart (30 seconds)
-## Architecture
+Paste this into your **Claude Desktop** config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS, `%APPDATA%\Claude\claude_desktop_config.json` on Windows):
-```
-┌─────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐
-│ Claude Desktop │────▶│ @3d-agent/mcp │────▶│ x402 facilitator │
-│ / Cursor │ │ (stdio transport) │ │ (CDP for Base, │
-│ │ │ │ │ PayAI for Solana) │
-└─────────────────┘ └─────────────────────┘ └──────────────────────┘
- │ │
- │ tools/call (no _meta) │ 1. extract _meta["x402/payment"]
- │──────────────────────▶│ 2. resourceServer.verifyPayment
- │ │ 3. run tool handler
- │ │ 4. resourceServer.settlePayment
- │ │ 5. attach _meta["x402/payment-response"]
- │ result + payment-meta │
- │◀──────────────────────│
+```json
+{
+ "mcpServers": {
+ "3d-agent": {
+ "command": "npx",
+ "args": ["-y", "@3d-agent/mcp-server"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
+ "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"
+ }
+ }
+ }
+}
```
-The server itself is the x402 **resource server**. It owns:
+Restart Claude Desktop. The four tools appear immediately — no install step required.
-- A shared `x402ResourceServer` with `ExactEvmScheme` (eip155:*),
- `UptoEvmScheme` (vanity grinder), and `ExactSvmScheme` (solana:*) registered.
-- A CDP `HTTPFacilitatorClient` when `CDP_API_KEY_ID` + `CDP_API_KEY_SECRET`
- are set (preferred for Base — required for CDP Bazaar discovery).
-- PayAI HTTP facilitators as fallback (Base + Solana).
+**Using Claude Code?** Run `/setup-mcp` in any project that includes this repo and Claude will detect your OS, collect your wallet addresses, and write the config for you.
-See [`src/payments.js`](src/payments.js).
+---
-## Wallet config
+## Tools
-Set at least one of:
+| Tool | Price | What it returns |
+|------|-------|-----------------|
+| `get_pose_seed` | $0.001 | Deterministic seed + full Euler-rotation pose map (radians) for the three.ws pose-studio mannequin, matched from the in-repo preset library. Includes a `previewUrl` at `https://three.ws/pose?seed=…&preset=…`. |
+| `pump_snapshot` | $0.005 | Live token snapshot — USD price (Jupiter), 24h volume + pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution (Solana RPC). Adds Helius DAS data when `HELIUS_API_KEY` is set. |
+| `agent_reputation` | $0.01 | ERC-8004 reputation: `getReputation`, `getTotalStake`, and the latest `ReputationSubmitted` / `ReputationStaked` events from the canonical ReputationRegistry on the requested chain (default Base). Resolves `agentId` from a wallet address automatically. |
+| `vanity_grinder` | up to $0.50 | Solana keypair whose base58 address starts with `prefix` (and optionally ends with `suffix`). Returns the full base58 secret key — treat as a secret. Actual settled USDC scales with iterations: `$0.01 base + $0.0000001/attempt`, capped at $0.50. |
-- `MCP_EVM_PAYMENT_ADDRESS` (or `X402_PAY_TO_BASE`) — Base USDC payouts.
-- `MCP_SVM_PAYMENT_ADDRESS` (or `X402_PAY_TO_SOLANA`) — Solana USDC payouts.
+---
-Default USDC assets (overridable):
+## Installation
-- Base: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (`X402_ASSET_ADDRESS_BASE`).
-- Solana: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` (`X402_ASSET_MINT_SOLANA`).
+The server runs locally on your machine and speaks stdio JSON-RPC — your MCP client spawns it automatically via the `npx` command above. You do not need to `npm install` globally.
-CDP facilitator (recommended for Base + Bazaar):
+If you prefer a global install:
-```
-CDP_API_KEY_ID=...
-CDP_API_KEY_SECRET=...
-X402_CDP_FACILITATOR_URL=https://api.cdp.coinbase.com/platform/v2/x402
+```bash
+npm install -g @3d-agent/mcp-server
```
-Without CDP credentials the server falls back to the public PayAI facilitator
-(`X402_FACILITATOR_URL_BASE`, `X402_FACILITATOR_URL_SOLANA`,
-`X402_FACILITATOR_TOKEN_*`).
+Then replace `"command": "npx", "args": ["-y", "@3d-agent/mcp-server"]` with `"command": "3d-agent-mcp"` in your config.
-Tool-specific config:
+---
-| Env var | Used by | Default |
-|---------|---------|---------|
-| `SOLANA_RPC_URL` | `pump_snapshot`, `vanity_grinder` | `https://api.mainnet-beta.solana.com` |
-| `HELIUS_API_KEY` | `pump_snapshot` (optional) | unset |
-| `MCP_POSE_PREVIEW_BASE` | `get_pose_seed` previewUrl | `https://three.ws/pose` |
-| `MCP_AGENT_REP_RPC_<chainId>` | `agent_reputation` per-chain RPC override | public RPC for that chain |
-| `MCP_AGENT_REP_LOG_WINDOW` | `agent_reputation` event scan window (blocks) | `200000` |
+## Environment variables
-## Run standalone
+### Required (at least one)
-From the monorepo root:
+| Var | Description |
+|-----|-------------|
+| `MCP_EVM_PAYMENT_ADDRESS` | Base USDC payout address (`0x...`) |
+| `MCP_SVM_PAYMENT_ADDRESS` | Solana USDC payout address (base58) |
-```bash
-npm install
-node mcp-server/src/index.js
-```
+### Optional
-The server speaks stdio JSON-RPC and prints `[mcp-server] ready — 4 paid
-tools registered over stdio` to stderr once initialization finishes.
+| Var | Default | Description |
+|-----|---------|-------------|
+| `HELIUS_API_KEY` | unset | Adds Helius DAS enrichment to `pump_snapshot` |
+| `SOLANA_RPC_URL` | `https://api.mainnet-beta.solana.com` | Solana RPC endpoint for `pump_snapshot` and `vanity_grinder` |
+| `CDP_API_KEY_ID` | unset | Coinbase CDP facilitator — recommended for Base + Bazaar discovery |
+| `CDP_API_KEY_SECRET` | unset | Coinbase CDP facilitator secret |
+| `X402_CDP_FACILITATOR_URL` | CDP default | Override CDP facilitator URL |
+| `MCP_POSE_PREVIEW_BASE` | `https://three.ws/pose` | Base URL for `get_pose_seed` preview links |
+| `MCP_AGENT_REP_RPC_<chainId>` | public RPC | Per-chain RPC override for `agent_reputation` |
+| `MCP_AGENT_REP_LOG_WINDOW` | `200000` | Block window for `agent_reputation` event scan |
-### MCP inspector
+---
-```bash
-npx -y @modelcontextprotocol/inspector node mcp-server/src/index.js
-```
+## Claude Code slash commands
-Then in the inspector UI, list tools and try calling `get_pose_seed` with
-`{ "prompt": "wave hello" }`. The first call returns the
-`PaymentRequired` envelope; the inspector lets you craft an `_meta`
-payload to retry with a real x402 payment.
+This repo ships three slash commands in `.claude/commands/` that work in any project that references this repo:
-## Claude Desktop
+| Command | What it does |
+|---------|--------------|
+| `/setup-mcp` | Detects your OS, collects wallet addresses, and writes the MCP config to the right file |
+| `/scaffold-agent` | Scaffolds a new three.ws agent in the current project with MCP client wiring |
+| `/use-tools [tool_name]` | Produces a complete, runnable code example for a specific paid tool |
-Edit `~/Library/Application Support/Claude/claude_desktop_config.json`
-(macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
+---
-```json
-{
- "mcpServers": {
- "3d-agent": {
- "command": "node",
- "args": ["/absolute/path/to/three.ws/mcp-server/src/index.js"],
- "env": {
- "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
- "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet",
- "CDP_API_KEY_ID": "...",
- "CDP_API_KEY_SECRET": "...",
- "SOLANA_RPC_URL": "https://mainnet.helius-rpc.com/?api-key=YOUR_HELIUS_KEY",
- "HELIUS_API_KEY": "YOUR_HELIUS_KEY"
- }
- }
- }
-}
+## Programmatic client
+
+Use `@x402/mcp`'s `wrapMCPClientWithPayment` to call these tools from another Node service. The wrapper auto-handles 402 retries:
+
+```js
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { wrapMCPClientWithPayment } from '@x402/mcp';
+import { x402Client } from '@x402/core/client';
+import { ExactEvmScheme } from '@x402/evm/exact/client';
+import { privateKeyToAccount } from 'viem/accounts';
+
+const transport = new StdioClientTransport({
+ command: 'npx',
+ args: ['-y', '@3d-agent/mcp-server'],
+ env: {
+ MCP_EVM_PAYMENT_ADDRESS: process.env.MCP_EVM_PAYMENT_ADDRESS,
+ MCP_SVM_PAYMENT_ADDRESS: process.env.MCP_SVM_PAYMENT_ADDRESS ?? '',
+ },
+});
+
+const mcp = new Client({ name: 'agent', version: '1.0.0' });
+await mcp.connect(transport);
+
+const account = privateKeyToAccount(process.env.AGENT_EVM_PRIVATE_KEY);
+const x402 = new x402Client().register('eip155:8453', new ExactEvmScheme(account));
+const paid = wrapMCPClientWithPayment(mcp, x402, { autoPayment: true });
+
+const result = await paid.callTool('get_pose_seed', { prompt: 'warrior stance' });
+console.log(JSON.parse(result.content[0].text));
```
-Restart Claude Desktop. The four tools appear under "3d-agent" in the
-tool picker. Ask Claude: *"Use get_pose_seed to give me a warrior pose."*
+---
## Cursor
-In Cursor's settings (`Cursor > Settings > Features > MCP`):
+In Cursor's MCP settings (`Cursor > Settings > Features > MCP`):
```json
{
"mcpServers": {
"3d-agent": {
- "command": "node",
- "args": ["/absolute/path/to/three.ws/mcp-server/src/index.js"],
+ "command": "npx",
+ "args": ["-y", "@3d-agent/mcp-server"],
"env": {
"MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
"MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"
@@ -152,48 +143,53 @@ In Cursor's settings (`Cursor > Settings > Features > MCP`):
}
```
-Cursor's MCP integration handles the x402 payment loop automatically when
-its companion x402 client is configured. Otherwise the agent will see the
-`PaymentRequired` envelope and can negotiate payment programmatically.
+---
-## Programmatic client
+## Run from source
-Use `@x402/mcp`'s `x402MCPClient` (or `createx402MCPClient` factory) to call
-these tools from another Node service. The client auto-handles 402 retries:
+From the monorepo root:
-```js
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
-import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
-import { wrapMCPClientWithPayment } from '@x402/mcp';
-import { x402Client } from '@x402/core/client';
-import { ExactEvmScheme } from '@x402/evm/exact/client';
-import { privateKeyToAccount } from 'viem/accounts';
+```bash
+npm install
+node mcp-server/src/index.js
+```
-const transport = new StdioClientTransport({
- command: 'node',
- args: ['/abs/path/three.ws/mcp-server/src/index.js'],
-});
-const mcp = new Client({ name: 'agent', version: '1.0.0' });
-await mcp.connect(transport);
+Inspect tools interactively:
-const account = privateKeyToAccount(process.env.AGENT_EVM_PRIVATE_KEY);
-const x402 = new x402Client().register('eip155:8453', new ExactEvmScheme(account));
-const paid = wrapMCPClientWithPayment(mcp, x402, { autoPayment: true });
+```bash
+npm run inspect --prefix mcp-server
+```
-const result = await paid.callTool('get_pose_seed', { prompt: 'warrior stance' });
-console.log(JSON.parse(result.content[0].text));
+---
+
+## Payment flow
+
+The server is the x402 **resource server**. On each tool call:
+
+1. Client sends a `tools/call` request (no payment yet).
+2. Server returns `PaymentRequired` (v2 MCP transport spec) with the USDC amount and payment address.
+3. A payment-aware client (or `wrapMCPClientWithPayment`) signs and submits the on-chain payment.
+4. Client retries the `tools/call` with `_meta["x402/payment"]` attached.
+5. Server verifies + settles via the configured facilitator, runs the tool, and returns the result with `_meta["x402/payment-response"]`.
+
+`vanity_grinder` uses the x402 `upto` scheme — the client authorizes up to $0.50 and the server settles the actual metered amount after mining completes.
+
+---
+
+## Architecture
+
+```
+┌─────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐
+│ Claude Desktop │────▶│ @3d-agent/mcp │────▶│ x402 facilitator │
+│ / Cursor / │ │ (stdio transport) │ │ (CDP for Base, │
+│ your agent │ │ │ │ PayAI for Solana) │
+└─────────────────┘ └─────────────────────┘ └──────────────────────┘
```
-## Notes on the `upto` flow
+Source: [`mcp-server/`](https://github.com/nirholas/three.ws/tree/main/mcp-server)
-`vanity_grinder` uses the x402 `upto` scheme: the client signs an
-authorization for a maximum of $0.50 USDC, and the server-side
-`paidUpto()` wrapper calls `resourceServer.settlePayment(...,
-settlementOverrides: { amount: <actual> })` so the facilitator settles the
-real metered amount. The Permit2 nonce makes each authorization
-single-use; partial settlement is enforced by the facilitator contract.
+---
-## Pricing source-of-truth
+## License
-Per-tool prices are declared in each tool file's `priceUsd` argument to
-`paid()` / `paidUpto()`. Changing them is a one-line edit per tool.
+Apache-2.0 — see [LICENSE](LICENSE).
diff --git a/package-lock.json b/package-lock.json
index 84bf24f73..c8b5a37c6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -991,6 +991,7 @@
"mcp-server": {
"name": "@3d-agent/mcp-server",
"version": "1.0.0",
+ "license": "Apache-2.0",
"dependencies": {
"@coinbase/x402": "^2.1.0",
"@modelcontextprotocol/sdk": "^1.29.0",
diff --git a/packages/avatar-schema/LICENSE b/packages/avatar-schema/LICENSE
new file mode 100644
index 000000000..e8823c963
--- /dev/null
+++ b/packages/avatar-schema/LICENSE
@@ -0,0 +1,19 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+Copyright 2025-2026 three.ws contributors
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+The full license text is reproduced in the project root LICENSE file.
diff --git a/packages/avatar-schema/README.md b/packages/avatar-schema/README.md
new file mode 100644
index 000000000..32dd4a433
--- /dev/null
+++ b/packages/avatar-schema/README.md
@@ -0,0 +1,101 @@
+# @three-ws/avatar-schema
+
+JSON Schema and validator for **three.ws on-chain avatar manifests** — the
+canonical, hash-anchored format any cross-chain client can use to resolve and
+verify an avatar.
+
+This is the on-chain equivalent of Ready Player Me's
+[content-validation-schemas](https://github.com/readyplayerme/content-validation-schemas):
+a tiny, dependency-light spec package that lets any third-party viewer,
+indexer, or marketplace integrate with three.ws avatars without pulling in the
+full runtime.
+
+## Install
+
+```bash
+npm i @three-ws/avatar-schema
+```
+
+## Use
+
+```js
+import { validate, assertValid } from '@three-ws/avatar-schema';
+
+const manifest = await (await fetch('https://three.ws/avatars/nicholas.eth.json')).json();
+
+const result = validate(manifest);
+if (!result.valid) {
+ console.error(result.errors);
+}
+
+// Or throw on first failure:
+assertValid(manifest);
+```
+
+The raw JSON Schema is exported separately so you can bind it to any other
+validator (Python `jsonschema`, Go `gojsonschema`, etc.):
+
+```js
+import schema from '@three-ws/avatar-schema/schema';
+```
+
+Or by absolute URL: <https://three.ws/schema/avatar.v1.json>.
+
+## What's in a manifest
+
+An on-chain avatar manifest binds a 3D mesh (and optional animations and
+accessories) to an owner identity on a specific chain. Every binary asset is
+referenced by content-addressed URI plus SHA-256, so clients can verify they
+fetched the exact bytes the manifest signer attested to.
+
+| Field | Required | Purpose |
+|---|---|---|
+| `schemaVersion` | yes | Always `1` for this version of the schema |
+| `id` | yes | CAIP-10 account id or `*.eth` / `*.ws` / `*.sol` name |
+| `name` | yes | Human-readable name |
+| `mesh` | yes | URI + SHA-256 + format (`glb`/`gltf`/`vrm`) |
+| `skeleton` | yes | One of `avaturn`/`mixamo`/`rpm`/`vrm-humanoid`/`custom` |
+| `animations` | no | Pointer to an animation-manifest URI + SHA-256 |
+| `accessories` | no | Array of slotted accessories (hat, glasses, etc.) |
+| `traits` | no | NFT-style flat key/value attributes |
+| `owner` | yes | `{ chain, address }` — current on-chain holder |
+| `creator` | no | Original creator (omit if same as owner) |
+| `createdAt` | yes | ISO 8601 UTC timestamp |
+| `signature` | no | EIP-712 / ed25519 / secp256k1 signature over the manifest |
+
+See [examples/basic.json](examples/basic.json) for a fully-populated example.
+
+## Why this exists
+
+Ready Player Me operates a single avatar service. There is no need for an
+open, verifiable manifest format because RPM is the source of truth.
+
+three.ws is decentralized: avatars are owned by wallets on multiple chains and
+rendered by viewers the avatar owner doesn't control. A common schema lets:
+
+- **Viewers** validate an avatar before rendering it, instead of trusting any
+ URL they're handed.
+- **Indexers** rebuild a global view of all three.ws avatars by scanning
+ on-chain registrations and pulling manifests.
+- **Marketplaces** verify ownership and accessory composition without
+ bespoke per-vendor logic.
+- **Cross-chain bridges** carry the same identity across EVM, Solana, and
+ beyond using CAIP-2 / CAIP-10 ids.
+
+## Versioning
+
+The schema uses an integer `schemaVersion`. Breaking changes get a new file
+(`avatar.v2.json`), a new const, and a new published major version of this
+package. Old versions remain valid forever.
+
+## Test
+
+```bash
+npm test
+```
+
+Tests use Node's built-in `node:test`. No extra runner required.
+
+## License
+
+Apache-2.0 — see [LICENSE](LICENSE).
diff --git a/packages/avatar-schema/examples/basic.json b/packages/avatar-schema/examples/basic.json
new file mode 100644
index 000000000..b9a7d2f81
--- /dev/null
+++ b/packages/avatar-schema/examples/basic.json
@@ -0,0 +1,33 @@
+{
+ "schemaVersion": 1,
+ "id": "nicholas.eth",
+ "name": "Nicholas",
+ "mesh": {
+ "uri": "ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi/avatar.glb",
+ "sha256": "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
+ "format": "glb",
+ "kBytes": 1840
+ },
+ "skeleton": "avaturn",
+ "animations": {
+ "uri": "https://three.ws/animations/manifest.json",
+ "sha256": "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
+ },
+ "accessories": [
+ {
+ "slot": "head",
+ "uri": "https://three.ws/accessories/hat-cowboy.glb",
+ "sha256": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
+ }
+ ],
+ "traits": {
+ "rarity": "rare",
+ "tier": 3,
+ "verified": true
+ },
+ "owner": {
+ "chain": "eip155:1",
+ "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
+ },
+ "createdAt": "2026-05-21T09:30:00.000Z"
+}
diff --git a/packages/avatar-schema/package.json b/packages/avatar-schema/package.json
new file mode 100644
index 000000000..a1be275a4
--- /dev/null
+++ b/packages/avatar-schema/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@three-ws/avatar-schema",
+ "version": "0.1.0",
+ "description": "JSON Schema and validator for three.ws on-chain avatar manifests — the canonical, hash-anchored format any cross-chain client can use to resolve an avatar.",
+ "keywords": [
+ "three.ws",
+ "avatar",
+ "schema",
+ "json-schema",
+ "on-chain",
+ "manifest",
+ "web3",
+ "evm",
+ "solana",
+ "ens",
+ "readyplayerme-alternative"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws.git",
+ "directory": "packages/avatar-schema"
+ },
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./schema": "./schema/avatar.v1.json",
+ "./schema/v1": "./schema/avatar.v1.json"
+ },
+ "files": [
+ "schema",
+ "src",
+ "examples",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "node --test test/"
+ },
+ "dependencies": {
+ "ajv": "^8.18.0",
+ "ajv-formats": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+}
diff --git a/packages/avatar-schema/schema/avatar.v1.json b/packages/avatar-schema/schema/avatar.v1.json
new file mode 100644
index 000000000..7f772af01
--- /dev/null
+++ b/packages/avatar-schema/schema/avatar.v1.json
@@ -0,0 +1,156 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://three.ws/schema/avatar.v1.json",
+ "title": "three.ws on-chain avatar manifest",
+ "description": "Canonical, hash-anchored description of an on-chain avatar. A signed instance of this document is what three.ws agents resolve when they fetch an avatar by id from any chain.",
+ "type": "object",
+ "required": ["schemaVersion", "id", "name", "mesh", "skeleton", "owner", "createdAt"],
+ "additionalProperties": false,
+ "properties": {
+ "schemaVersion": {
+ "description": "Version of this manifest schema. Always 1 for documents validated against avatar.v1.json.",
+ "type": "integer",
+ "const": 1
+ },
+ "id": {
+ "description": "Canonical avatar identifier. Either a CAIP-10 account id (e.g. eip155:1:0xabc...) or a name from a supported name service (.eth, .ws, .sol).",
+ "type": "string",
+ "anyOf": [
+ { "pattern": "^[a-z0-9-]{3,8}:[a-zA-Z0-9_-]{1,32}:[a-zA-Z0-9]{1,64}$" },
+ { "pattern": "^[a-z0-9][a-z0-9-]{0,62}\\.(eth|ws|sol)$" }
+ ]
+ },
+ "name": {
+ "description": "Human-readable avatar name.",
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64
+ },
+ "mesh": {
+ "description": "Pointer to the 3D mesh that renders this avatar.",
+ "type": "object",
+ "required": ["uri", "sha256", "format"],
+ "additionalProperties": false,
+ "properties": {
+ "uri": {
+ "description": "Content-addressed or HTTP(S) URI. Prefer ipfs:// or ar:// for immutability.",
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "sha256": {
+ "description": "SHA-256 of the mesh bytes, lowercase hex.",
+ "type": "string",
+ "pattern": "^[a-f0-9]{64}$"
+ },
+ "format": {
+ "description": "Mesh container format.",
+ "type": "string",
+ "enum": ["glb", "gltf", "vrm"]
+ },
+ "kBytes": {
+ "description": "Mesh size in kilobytes (informational).",
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "skeleton": {
+ "description": "Skeleton layout the mesh conforms to. Determines which animation libraries can drive it without runtime retargeting.",
+ "type": "string",
+ "enum": ["avaturn", "mixamo", "rpm", "vrm-humanoid", "custom"]
+ },
+ "animations": {
+ "description": "Optional pointer to an animation manifest (list of clips by name → uri/sha256). If omitted, the avatar relies on whatever default clips the host viewer ships.",
+ "type": "object",
+ "required": ["uri", "sha256"],
+ "additionalProperties": false,
+ "properties": {
+ "uri": { "type": "string", "format": "uri-reference" },
+ "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }
+ }
+ },
+ "accessories": {
+ "description": "Equipped accessory items (hats, glasses, etc.). Each entry binds a slot to a content-addressed asset.",
+ "type": "array",
+ "maxItems": 16,
+ "items": {
+ "type": "object",
+ "required": ["slot", "uri", "sha256"],
+ "additionalProperties": false,
+ "properties": {
+ "slot": {
+ "type": "string",
+ "enum": ["head", "eyes", "ears", "neck", "torso", "back", "hands", "waist", "feet"]
+ },
+ "uri": { "type": "string", "format": "uri-reference" },
+ "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }
+ }
+ }
+ },
+ "traits": {
+ "description": "Free-form key/value traits (NFT-style). String/number/boolean values only; no nested objects.",
+ "type": "object",
+ "additionalProperties": {
+ "type": ["string", "number", "boolean"]
+ },
+ "maxProperties": 32
+ },
+ "owner": {
+ "description": "Current on-chain owner. Wallet address scoped by chain id.",
+ "type": "object",
+ "required": ["chain", "address"],
+ "additionalProperties": false,
+ "properties": {
+ "chain": {
+ "description": "CAIP-2 chain id (e.g. eip155:1, solana:mainnet-beta).",
+ "type": "string",
+ "pattern": "^[a-z0-9-]{3,8}:[a-zA-Z0-9_-]{1,32}$"
+ },
+ "address": {
+ "description": "Wallet address. Format depends on chain.",
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ }
+ }
+ },
+ "creator": {
+ "description": "Original creator. Omit if same as owner.",
+ "type": "object",
+ "required": ["chain", "address"],
+ "additionalProperties": false,
+ "properties": {
+ "chain": { "type": "string", "pattern": "^[a-z0-9-]{3,8}:[a-zA-Z0-9_-]{1,32}$" },
+ "address": { "type": "string", "minLength": 1, "maxLength": 128 }
+ }
+ },
+ "createdAt": {
+ "description": "ISO 8601 UTC timestamp.",
+ "type": "string",
+ "format": "date-time"
+ },
+ "signature": {
+ "description": "Optional signature over the canonical JSON serialization of this manifest, with the signature field itself removed. Algorithm-specific.",
+ "type": "object",
+ "required": ["algorithm", "value", "signer"],
+ "additionalProperties": false,
+ "properties": {
+ "algorithm": {
+ "type": "string",
+ "enum": ["eip-712", "ed25519", "secp256k1"]
+ },
+ "value": {
+ "description": "Signature bytes, hex-encoded with leading 0x.",
+ "type": "string",
+ "pattern": "^0x[a-fA-F0-9]+$"
+ },
+ "signer": {
+ "description": "Wallet address that produced the signature. Should match owner.address unless delegated.",
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ }
+ }
+ }
+ }
+}
diff --git a/packages/avatar-schema/src/index.d.ts b/packages/avatar-schema/src/index.d.ts
new file mode 100644
index 000000000..9f12c3436
--- /dev/null
+++ b/packages/avatar-schema/src/index.d.ts
@@ -0,0 +1,74 @@
+import type { ErrorObject } from 'ajv';
+
+export type MeshFormat = 'glb' | 'gltf' | 'vrm';
+export type SkeletonKind = 'avaturn' | 'mixamo' | 'rpm' | 'vrm-humanoid' | 'custom';
+export type AccessorySlot =
+ | 'head'
+ | 'eyes'
+ | 'ears'
+ | 'neck'
+ | 'torso'
+ | 'back'
+ | 'hands'
+ | 'waist'
+ | 'feet';
+export type SignatureAlgorithm = 'eip-712' | 'ed25519' | 'secp256k1';
+
+export interface MeshRef {
+ uri: string;
+ sha256: string;
+ format: MeshFormat;
+ kBytes?: number;
+}
+
+export interface AnimationsRef {
+ uri: string;
+ sha256: string;
+}
+
+export interface AccessoryRef {
+ slot: AccessorySlot;
+ uri: string;
+ sha256: string;
+}
+
+export interface ChainAccount {
+ /** CAIP-2 chain id, e.g. "eip155:1" or "solana:mainnet-beta". */
+ chain: string;
+ address: string;
+}
+
+export interface Signature {
+ algorithm: SignatureAlgorithm;
+ /** Hex-encoded with leading 0x. */
+ value: string;
+ signer: string;
+}
+
+export interface AvatarManifestV1 {
+ schemaVersion: 1;
+ /** CAIP-10 account id or a *.eth / *.ws / *.sol name. */
+ id: string;
+ name: string;
+ mesh: MeshRef;
+ skeleton: SkeletonKind;
+ animations?: AnimationsRef;
+ accessories?: AccessoryRef[];
+ traits?: Record<string, string | number | boolean>;
+ owner: ChainAccount;
+ creator?: ChainAccount;
+ /** ISO 8601 UTC timestamp. */
+ createdAt: string;
+ signature?: Signature;
+}
+
+export type ValidationResult =
+ | { valid: true }
+ | { valid: false; errors: ErrorObject[] };
+
+export declare const schema: object;
+export declare const SCHEMA_VERSION: 1;
+export declare const SCHEMA_ID: 'https://three.ws/schema/avatar.v1.json';
+
+export declare function validate(manifest: unknown): ValidationResult;
+export declare function assertValid(manifest: unknown): asserts manifest is AvatarManifestV1;
diff --git a/packages/avatar-schema/src/index.js b/packages/avatar-schema/src/index.js
new file mode 100644
index 000000000..bf7018490
--- /dev/null
+++ b/packages/avatar-schema/src/index.js
@@ -0,0 +1,45 @@
+import Ajv from 'ajv/dist/2020.js';
+import addFormats from 'ajv-formats';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+export const schema = JSON.parse(
+ readFileSync(resolve(__dirname, '../schema/avatar.v1.json'), 'utf8'),
+);
+
+const ajv = new Ajv({ allErrors: true, strict: true });
+addFormats(ajv);
+const compiled = ajv.compile(schema);
+
+/**
+ * Validate an avatar manifest against avatar.v1.json.
+ *
+ * @param {unknown} manifest - parsed JSON object to check.
+ * @returns {{ valid: true } | { valid: false, errors: import('ajv').ErrorObject[] }}
+ */
+export function validate(manifest) {
+ const ok = compiled(manifest);
+ if (ok) return { valid: true };
+ return { valid: false, errors: compiled.errors ?? [] };
+}
+
+/**
+ * Throw on invalid manifest. Useful in pipelines that want to fail fast.
+ *
+ * @param {unknown} manifest
+ * @returns {void}
+ */
+export function assertValid(manifest) {
+ const result = validate(manifest);
+ if (result.valid) return;
+ const summary = result.errors
+ .map((e) => `${e.instancePath || '/'} ${e.message}`)
+ .join('; ');
+ throw new Error(`Invalid avatar manifest: ${summary}`);
+}
+
+export const SCHEMA_VERSION = 1;
+export const SCHEMA_ID = 'https://three.ws/schema/avatar.v1.json';
diff --git a/packages/avatar-schema/test/validate.test.js b/packages/avatar-schema/test/validate.test.js
new file mode 100644
index 000000000..4f452e444
--- /dev/null
+++ b/packages/avatar-schema/test/validate.test.js
@@ -0,0 +1,83 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+import { validate, assertValid, schema, SCHEMA_VERSION, SCHEMA_ID } from '../src/index.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const example = JSON.parse(
+ readFileSync(resolve(__dirname, '../examples/basic.json'), 'utf8'),
+);
+
+test('schema exports are stable', () => {
+ assert.equal(SCHEMA_VERSION, 1);
+ assert.equal(SCHEMA_ID, 'https://three.ws/schema/avatar.v1.json');
+ assert.equal(schema.$id, SCHEMA_ID);
+});
+
+test('valid example passes', () => {
+ const result = validate(example);
+ assert.equal(result.valid, true);
+});
+
+test('assertValid does not throw for valid example', () => {
+ assert.doesNotThrow(() => assertValid(example));
+});
+
+test('missing required field fails', () => {
+ const { mesh, ...broken } = example;
+ const result = validate(broken);
+ assert.equal(result.valid, false);
+ assert.ok(result.errors.some((e) => e.message?.includes("'mesh'")));
+});
+
+test('wrong schemaVersion fails', () => {
+ const broken = { ...example, schemaVersion: 2 };
+ const result = validate(broken);
+ assert.equal(result.valid, false);
+});
+
+test('non-hex sha256 fails', () => {
+ const broken = { ...example, mesh: { ...example.mesh, sha256: 'NOT-HEX' } };
+ const result = validate(broken);
+ assert.equal(result.valid, false);
+ assert.ok(result.errors.some((e) => e.instancePath.includes('sha256')));
+});
+
+test('invalid CAIP-2 chain fails', () => {
+ const broken = { ...example, owner: { chain: 'NOT VALID', address: '0xabc' } };
+ const result = validate(broken);
+ assert.equal(result.valid, false);
+});
+
+test('ENS-style id accepted', () => {
+ const result = validate({ ...example, id: 'alice.eth' });
+ assert.equal(result.valid, true);
+});
+
+test('three.ws name id accepted', () => {
+ const result = validate({ ...example, id: 'agent-007.ws' });
+ assert.equal(result.valid, true);
+});
+
+test('CAIP-10 id accepted', () => {
+ const result = validate({
+ ...example,
+ id: 'eip155:1:0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
+ });
+ assert.equal(result.valid, true);
+});
+
+test('additional properties rejected', () => {
+ const broken = { ...example, somethingUnknown: 'nope' };
+ const result = validate(broken);
+ assert.equal(result.valid, false);
+});
+
+test('assertValid throws with summary for invalid input', () => {
+ assert.throws(
+ () => assertValid({ schemaVersion: 1 }),
+ (err) => err instanceof Error && err.message.startsWith('Invalid avatar manifest:'),
+ );
+});
diff --git a/pages/create-review.html b/pages/create-review.html
new file mode 100644
index 000000000..6a397c300
--- /dev/null
+++ b/pages/create-review.html
@@ -0,0 +1,410 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Preview your avatar · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <meta
+ name="description"
+ content="Preview the 3D avatar you just generated, then save it to your three.ws account."
+ />
+ <meta name="robots" content="noindex" />
+
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #d6ff3d;
+ --accent-ink: #0a0a0a;
+ --bg: #05060a;
+ --panel: #0f1018;
+ --border: #1e1f2b;
+ --text: #eee;
+ --muted: #8a8d98;
+ }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; margin: 0; padding: 0; }
+ body {
+ font: 15px/1.55 -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif;
+ color: var(--text);
+ background: var(--bg);
+ display: flex;
+ flex-direction: column;
+ min-height: 100vh;
+ overflow-x: hidden;
+ }
+ body::before {
+ content: '';
+ position: fixed;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+ background:
+ radial-gradient(800px 500px at 50% -100px, rgba(106, 92, 255, 0.12) 0, transparent 70%),
+ radial-gradient(600px 400px at 50% 110%, rgba(214, 255, 61, 0.05) 0, transparent 70%),
+ #05060a;
+ }
+
+ .crumb {
+ padding: 14px 22px;
+ font-size: 13px;
+ color: var(--muted);
+ }
+ .crumb a { color: var(--muted); text-decoration: none; }
+ .crumb a:hover { color: var(--accent); }
+
+ main.stage {
+ flex: 1;
+ max-width: 1100px;
+ width: 100%;
+ margin: 0 auto;
+ padding: 16px 22px 80px;
+ }
+ h1 {
+ font-size: 28px;
+ font-weight: 600;
+ letter-spacing: -0.015em;
+ margin: 0 0 6px;
+ }
+ .sub {
+ color: var(--muted);
+ margin: 0 0 28px;
+ max-width: 64ch;
+ }
+
+ .grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 380px;
+ gap: 28px;
+ align-items: start;
+ }
+ @media (max-width: 880px) {
+ .grid { grid-template-columns: 1fr; }
+ }
+
+ .viewer {
+ background: var(--panel);
+ border: 1.5px solid var(--border);
+ border-radius: 14px;
+ aspect-ratio: 4 / 5;
+ min-height: 480px;
+ position: relative;
+ overflow: hidden;
+ }
+ .viewer model-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+ }
+ .viewer-loading {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--muted);
+ font-size: 13px;
+ gap: 8px;
+ }
+ .spinner-sm {
+ width: 16px;
+ height: 16px;
+ border: 2px solid rgba(255, 255, 255, 0.1);
+ border-top-color: rgba(255, 255, 255, 0.55);
+ border-radius: 50%;
+ animation: spin 0.75s linear infinite;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+
+ .panel {
+ background: var(--panel);
+ border: 1.5px solid var(--border);
+ border-radius: 14px;
+ padding: 22px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ }
+ .panel h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ letter-spacing: -0.005em;
+ }
+ .tags { display: flex; gap: 6px; flex-wrap: wrap; }
+ .meta-tag {
+ display: inline-block;
+ background: var(--border);
+ color: var(--muted);
+ padding: 2px 9px;
+ border-radius: 6px;
+ font-size: 11px;
+ letter-spacing: 0.02em;
+ }
+ .label {
+ display: block;
+ font-size: 12px;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ margin-bottom: 6px;
+ }
+ .panel input {
+ width: 100%;
+ background: #07080d;
+ color: var(--text);
+ border: 1.5px solid var(--border);
+ border-radius: 9px;
+ padding: 10px 12px;
+ font: inherit;
+ }
+ .panel input:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+
+ .cta {
+ background: var(--accent);
+ color: var(--accent-ink);
+ border: none;
+ border-radius: 10px;
+ padding: 12px 16px;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 0.15s, opacity 0.15s;
+ }
+ .cta:hover { filter: brightness(1.04); }
+ .cta:disabled { opacity: 0.45; cursor: not-allowed; }
+
+ .secondary {
+ background: transparent;
+ color: var(--text);
+ border: 1.5px solid var(--border);
+ border-radius: 10px;
+ padding: 10px 14px;
+ font: inherit;
+ cursor: pointer;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .secondary:hover { border-color: #2c2d3d; color: var(--text); }
+
+ .guest-note {
+ font-size: 12.5px;
+ color: var(--muted);
+ line-height: 1.5;
+ }
+ .guest-note strong { color: var(--text); font-weight: 600; }
+
+ .empty {
+ text-align: center;
+ background: var(--panel);
+ border: 1.5px solid var(--border);
+ border-radius: 14px;
+ padding: 48px 24px;
+ color: var(--muted);
+ max-width: 520px;
+ margin: 32px auto 0;
+ }
+ .empty a { color: var(--accent); }
+
+ #save-loading {
+ position: fixed;
+ inset: 0;
+ z-index: 9999;
+ background: #000;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 16px;
+ }
+ #save-loading img { width: 56px; height: 56px; animation: pulse 1.6s ease-in-out infinite; }
+ #save-loading .label { color: rgba(255, 255, 255, 0.82); font-size: 15px; font-weight: 500; }
+ #save-loading .sublabel { color: rgba(255, 255, 255, 0.42); font-size: 12.5px; }
+ @keyframes pulse {
+ 0%, 100% { opacity: 0.55; transform: scale(1); }
+ 50% { opacity: 1; transform: scale(1.06); }
+ }
+
+ .status-toast {
+ position: fixed;
+ bottom: 32px;
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 11px 20px;
+ border-radius: 12px;
+ font-size: 13px;
+ font-weight: 500;
+ border: 1px solid var(--border);
+ background: var(--panel);
+ z-index: 50;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
+ }
+ .status-toast.error { border-color: rgba(255, 92, 92, 0.4); color: #ffb3b3; background: #140a0a; }
+ .status-toast.success { border-color: rgba(214, 255, 61, 0.3); color: var(--accent); }
+ </style>
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ <script>
+ // Optimistic auth check so the page can decide whether to show
+ // "Save to my account" vs. "Sign in to save". Authoritative answer
+ // arrives via the /api/auth/me round-trip below.
+ window.__authed = null;
+ fetch('/api/auth/me', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => {
+ window.__authed = !!(data && data.user);
+ document.dispatchEvent(new CustomEvent('three-ws:auth-resolved', {
+ detail: { authed: window.__authed, user: data?.user || null },
+ }));
+ })
+ .catch(() => {
+ window.__authed = false;
+ document.dispatchEvent(new CustomEvent('three-ws:auth-resolved', {
+ detail: { authed: false, user: null },
+ }));
+ });
+ </script>
+ </head>
+ <body>
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <nav class="crumb">
+ <a href="/">three.ws</a> &middot;
+ <a href="/create">Create</a> &middot;
+ <span>Preview</span>
+ </nav>
+
+ <main class="stage" id="main">
+ <h1 id="heading">Preview your avatar</h1>
+ <p class="sub" id="subhead">
+ This is what we just built. Save it to your account to use it across
+ three.ws, or start over with a different look.
+ </p>
+
+ <div id="empty-card" class="empty" hidden>
+ <p style="margin: 0 0 12px">No avatar in progress.</p>
+ <p style="margin: 0"><a href="/create">← Start a new avatar</a></p>
+ </div>
+
+ <div id="content" class="grid" hidden>
+ <div class="viewer">
+ <div class="viewer-loading" id="viewer-loading">
+ <div class="spinner-sm" aria-hidden="true"></div>
+ <span>Loading 3D preview…</span>
+ </div>
+ <model-viewer
+ id="mv"
+ camera-controls
+ touch-action="pan-y"
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ interaction-prompt="none"
+ shadow-intensity="0.6"
+ shadow-softness="0.8"
+ exposure="1"
+ environment-image="neutral"
+ camera-orbit="0deg 80deg auto"
+ style="visibility: hidden"
+ ></model-viewer>
+ </div>
+
+ <div class="panel">
+ <h2 id="avatar-name">Your avatar</h2>
+ <div class="tags">
+ <span class="meta-tag" id="tag-source">—</span>
+ <span class="meta-tag" id="tag-size">— KB</span>
+ </div>
+
+ <div>
+ <label class="label" for="f-name">Name</label>
+ <input
+ id="f-name"
+ maxlength="120"
+ placeholder="e.g. My agent"
+ autocomplete="off"
+ />
+ </div>
+
+ <button class="cta" id="save-btn" type="button" disabled>
+ Save to my account
+ </button>
+ <button class="secondary" id="start-over-btn" type="button">
+ Start over
+ </button>
+
+ <p class="guest-note" id="guest-note" hidden>
+ <strong>Not signed in.</strong> Your preview lives in this browser
+ only. Sign in to save it permanently and use it as an agent.
+ </p>
+ </div>
+ </div>
+ </main>
+
+ <footer class="h-footer-horizon">
+ <div class="h-footer-glow-line" aria-hidden="true"></div>
+ <div class="h-footer-floor" aria-hidden="true"></div>
+ <div class="h-footer-haze" aria-hidden="true"></div>
+ <div class="h-footer-watermark" aria-hidden="true">three.ws</div>
+ <div class="h-footer-inner">
+ <div class="h-footer-brand-col">
+ <div class="h-footer-brand">
+ <img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" />
+ <span class="wordmark-dot" aria-hidden="true"></span>
+ <span>three.ws</span>
+ </div>
+ <p class="h-footer-tagline">Give your AI a body.</p>
+ </div>
+ <nav class="h-footer-links" aria-label="Footer">
+ <div class="h-footer-link-col">
+ <h4 class="h-footer-link-heading">Product</h4>
+ <a href="/create">Create</a>
+ <a href="/studio">Studio</a>
+ <a href="/widgets">Widgets</a>
+ <a href="/discover">Discover</a>
+ </div>
+ <div class="h-footer-link-col">
+ <h4 class="h-footer-link-heading">Resources</h4>
+ <a href="/blog">Blog</a>
+ <a href="/dashboard">Dashboard</a>
+ </div>
+ </nav>
+ </div>
+ <div class="h-footer-bottom">
+ <p class="h-footer-legal">© 2026 three.ws — All rights reserved.</p>
+ <div class="h-footer-legal-links">
+ <a href="/legal/privacy">Privacy Policy</a>
+ <a href="/legal/tos">Terms of Use</a>
+ </div>
+ </div>
+ </footer>
+
+ <div
+ class="status-toast"
+ id="status-toast"
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ hidden
+ ></div>
+
+ <script type="module" src="/src/create-review.js"></script>
+ </body>
+</html>
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index 5ce9a7239..1a03ae383 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -209,6 +209,224 @@
.toggle button:hover { color: var(--text); }
.opt-hint { font-size: 12px; color: var(--muted); margin: 6px 0 0; }
+ /* ── Step 3: Building ─────────────────────────────────────────────── */
+ .build-progress {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ margin: 0 0 28px;
+ }
+ .build-step {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 10px 0;
+ position: relative;
+ }
+ .build-step:not(:last-child)::after {
+ content: '';
+ position: absolute;
+ left: 9px;
+ top: 30px;
+ bottom: -10px;
+ width: 2px;
+ background: var(--border);
+ }
+ .build-step.completed::after { background: rgba(214, 255, 61, 0.3); }
+ .bstep-dot {
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ border: 2px solid var(--border-strong);
+ background: var(--panel);
+ flex-shrink: 0;
+ margin-top: 1px;
+ position: relative;
+ z-index: 1;
+ }
+ .build-step.completed .bstep-dot {
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ .build-step.completed .bstep-dot::after {
+ content: '';
+ display: block;
+ width: 5px;
+ height: 9px;
+ border: 2px solid var(--accent-ink);
+ border-top: none;
+ border-left: none;
+ transform: rotate(45deg) translate(-1px, -1px);
+ position: absolute;
+ top: 2px;
+ left: 5px;
+ }
+ .build-step.active .bstep-dot {
+ border-color: var(--accent);
+ animation: bstep-pulse 1.4s ease-in-out infinite;
+ }
+ @keyframes bstep-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(214, 255, 61, 0.4); }
+ 50% { box-shadow: 0 0 0 6px rgba(214, 255, 61, 0); }
+ }
+ .bstep-label {
+ font-size: 14px;
+ color: var(--muted);
+ line-height: 1.4;
+ padding-top: 1px;
+ }
+ .build-step.active .bstep-label { color: var(--text); font-weight: 500; }
+ .build-step.completed .bstep-label { color: var(--muted); }
+
+ .build-viewer {
+ position: relative;
+ width: 100%;
+ max-width: 320px;
+ margin: 0 auto 24px;
+ aspect-ratio: 3 / 4;
+ border-radius: 16px;
+ overflow: hidden;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ }
+ .build-viewer model-viewer {
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ }
+ .build-veil {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(5, 6, 10, 0.55);
+ backdrop-filter: blur(2px);
+ -webkit-backdrop-filter: blur(2px);
+ pointer-events: none;
+ }
+ .build-ring {
+ width: 72px;
+ height: 72px;
+ border-radius: 50%;
+ border: 3px solid rgba(214, 255, 61, 0.15);
+ border-top-color: var(--accent);
+ animation: build-spin 1s linear infinite;
+ }
+ @keyframes build-spin { to { transform: rotate(360deg); } }
+
+ .build-error {
+ display: none;
+ padding: 12px 14px;
+ background: rgba(239, 77, 77, 0.08);
+ border: 1px solid var(--danger-dim);
+ border-radius: 9px;
+ color: #f4b5b5;
+ font-size: 13.5px;
+ margin: 0 0 16px;
+ }
+ .build-error.show { display: block; }
+ .build-retry {
+ width: 100%;
+ max-width: 320px;
+ margin: 0 auto;
+ display: none;
+ padding: 12px 18px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ color: var(--text);
+ font: 600 14px/1 inherit;
+ cursor: pointer;
+ text-align: center;
+ }
+ .build-retry.show { display: block; }
+ .build-retry:hover { border-color: var(--border-strong); }
+
+ /* ── Step 4: Done ─────────────────────────────────────────────────── */
+ .done-viewer {
+ width: 100%;
+ max-width: 320px;
+ margin: 0 auto 24px;
+ aspect-ratio: 3 / 4;
+ border-radius: 16px;
+ overflow: hidden;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ }
+ .done-viewer model-viewer {
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ }
+ .name-row {
+ margin: 0 0 20px;
+ }
+ .name-input {
+ width: 100%;
+ padding: 12px 14px;
+ background: var(--panel);
+ border: 1px solid var(--border-strong);
+ border-radius: 10px;
+ color: var(--text);
+ font: 15px/1 inherit;
+ outline: none;
+ transition: border-color 120ms;
+ }
+ .name-input:focus { border-color: var(--accent); }
+ .name-input::placeholder { color: var(--muted); }
+ .done-actions {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .btn-save {
+ width: 100%;
+ padding: 14px 18px;
+ background: var(--accent);
+ color: var(--accent-ink);
+ border: none;
+ border-radius: 10px;
+ font: 600 15px/1 inherit;
+ cursor: pointer;
+ transition: filter 120ms;
+ }
+ .btn-save:hover { filter: brightness(1.06); }
+ .btn-save:disabled { opacity: 0.55; cursor: not-allowed; filter: none; }
+ .btn-ghost {
+ width: 100%;
+ padding: 12px 18px;
+ background: var(--panel);
+ color: var(--muted);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ font: 500 14px/1 inherit;
+ cursor: pointer;
+ transition: color 120ms, border-color 120ms;
+ }
+ .btn-ghost:hover { color: var(--text); border-color: var(--border-strong); }
+ .portability-note {
+ margin-top: 24px;
+ padding: 14px 16px;
+ background: rgba(214, 255, 61, 0.04);
+ border: 1px solid rgba(214, 255, 61, 0.12);
+ border-radius: 10px;
+ font-size: 13px;
+ color: var(--muted);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+ .portability-note a {
+ color: var(--accent);
+ text-decoration: none;
+ white-space: nowrap;
+ font-weight: 500;
+ }
+ .portability-note a:hover { text-decoration: underline; }
+
.submit-bar {
margin-top: 6px;
}
@@ -321,6 +539,10 @@
.cam-bar .spacer { flex: 1; }
</style>
<link rel="stylesheet" href="/mobile.css" />
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
</head>
<body>
<main class="stage">
@@ -403,6 +625,94 @@
<button id="submit-btn" type="button" disabled>Add 3 photos to continue</button>
</div>
</section>
+
+ <!-- Step 3: Building your avatar -->
+ <section class="step" data-step="building">
+ <h1>Building your avatar…</h1>
+ <p class="sub">This usually takes 30–90 seconds. Don't close this tab.</p>
+
+ <div class="build-progress" role="list" aria-label="Build progress">
+ <div class="build-step completed" data-bstep="upload" role="listitem">
+ <span class="bstep-dot" aria-hidden="true"></span>
+ <span class="bstep-label">Photos uploaded</span>
+ </div>
+ <div class="build-step active" data-bstep="process" role="listitem">
+ <span class="bstep-dot" aria-hidden="true"></span>
+ <span class="bstep-label" id="build-status-text" aria-live="polite">Processing your face…</span>
+ </div>
+ <div class="build-step" data-bstep="finish" role="listitem">
+ <span class="bstep-dot" aria-hidden="true"></span>
+ <span class="bstep-label">Finishing rig</span>
+ </div>
+ </div>
+
+ <div class="build-viewer" aria-hidden="true">
+ <model-viewer
+ src="/avatars/default.glb"
+ auto-rotate
+ rotation-per-second="12deg"
+ interaction-prompt="none"
+ disable-zoom
+ disable-pan
+ shadow-intensity="0.5"
+ environment-image="neutral"
+ exposure="0.9"
+ camera-orbit="0deg 78deg auto"
+ loading="eager"
+ ></model-viewer>
+ <div class="build-veil">
+ <div class="build-ring"></div>
+ </div>
+ </div>
+
+ <p id="build-error-msg" class="build-error" role="alert"></p>
+ <button id="build-retry-btn" class="build-retry" type="button">← Try again</button>
+ </section>
+
+ <!-- Step 4: Done -->
+ <section class="step" data-step="done">
+ <h1>Your avatar is ready</h1>
+ <p class="sub">Name it and open it in your workspace.</p>
+
+ <div class="done-viewer">
+ <model-viewer
+ id="done-model"
+ auto-rotate
+ rotation-per-second="10deg"
+ interaction-prompt="none"
+ camera-controls
+ shadow-intensity="0.7"
+ shadow-softness="0.8"
+ environment-image="neutral"
+ exposure="0.95"
+ camera-orbit="0deg 78deg auto"
+ loading="eager"
+ alt="Your new avatar"
+ ></model-viewer>
+ </div>
+
+ <div class="name-row">
+ <input
+ type="text"
+ id="done-name"
+ class="name-input"
+ placeholder="Name your avatar"
+ maxlength="60"
+ autocomplete="off"
+ aria-label="Avatar name"
+ />
+ </div>
+
+ <div class="done-actions">
+ <button id="done-save-btn" class="btn-save" type="button">Open my avatar →</button>
+ <button id="done-editor-btn" class="btn-ghost" type="button">Customize in editor</button>
+ </div>
+
+ <div class="portability-note">
+ <span>This avatar works in any three.ws-powered app.</span>
+ <a href="/docs/embed" target="_blank" rel="noopener">Learn how to embed →</a>
+ </div>
+ </section>
</main>
<!-- Camera overlay (driven by selfie-capture.js) -->
@@ -430,6 +740,102 @@
<script type="module">
import '/src/selfie-capture.js';
import '/src/selfie-pipeline.js';
+
+ function showStep(name) {
+ document.querySelectorAll('.step[data-step]').forEach((s) => {
+ s.classList.toggle('active', s.dataset.step === name);
+ });
+ }
+
+ let _avatarId = null;
+
+ document.addEventListener('selfie:building', () => {
+ showStep('building');
+ });
+
+ document.addEventListener('selfie:progress', (e) => {
+ const label = /** @type {CustomEvent} */ (e).detail?.label;
+ if (!label) return;
+ const el = document.getElementById('build-status-text');
+ if (el) el.textContent = label;
+
+ // Advance the step indicator to "finish" on later attempts
+ const processStep = document.querySelector('.build-step[data-bstep="process"]');
+ const finishStep = document.querySelector('.build-step[data-bstep="finish"]');
+ if (label.toLowerCase().includes('finish') || label.toLowerCase().includes('rig')) {
+ processStep?.classList.replace('active', 'completed');
+ finishStep?.classList.add('active');
+ }
+ });
+
+ document.addEventListener('selfie:done', async (e) => {
+ _avatarId = /** @type {CustomEvent} */ (e).detail?.avatarId;
+ if (!_avatarId) return;
+
+ // Mark all build steps complete
+ document.querySelectorAll('.build-step').forEach((s) => {
+ s.className = 'build-step completed';
+ });
+
+ // Fetch avatar to get model URL and name
+ try {
+ const res = await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {
+ credentials: 'include',
+ });
+ if (res.ok) {
+ const avatar = await res.json();
+ const modelEl = document.getElementById('done-model');
+ if (modelEl && avatar.model_url) modelEl.setAttribute('src', avatar.model_url);
+ const nameEl = /** @type {HTMLInputElement|null} */ (document.getElementById('done-name'));
+ if (nameEl && avatar.name) nameEl.value = avatar.name;
+ }
+ } catch (_) {}
+
+ showStep('done');
+ });
+
+ document.addEventListener('selfie:build-error', (e) => {
+ const msg = /** @type {CustomEvent} */ (e).detail?.message || 'Something went wrong. Try again.';
+ const errEl = document.getElementById('build-error-msg');
+ const retryBtn = document.getElementById('build-retry-btn');
+ if (errEl) { errEl.textContent = msg; errEl.classList.add('show'); }
+ if (retryBtn) retryBtn.classList.add('show');
+ });
+
+ document.getElementById('build-retry-btn')?.addEventListener('click', () => {
+ const errEl = document.getElementById('build-error-msg');
+ const retryBtn = document.getElementById('build-retry-btn');
+ errEl?.classList.remove('show');
+ retryBtn?.classList.remove('show');
+ showStep('capture');
+ });
+
+ document.getElementById('done-save-btn')?.addEventListener('click', async () => {
+ if (!_avatarId) return;
+ const btn = /** @type {HTMLButtonElement} */ (document.getElementById('done-save-btn'));
+ btn.disabled = true;
+ btn.textContent = 'Saving…';
+
+ const nameEl = /** @type {HTMLInputElement|null} */ (document.getElementById('done-name'));
+ const name = nameEl?.value?.trim();
+ if (name) {
+ try {
+ await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {
+ method: 'PATCH',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name }),
+ });
+ } catch (_) {}
+ }
+
+ window.location.assign(`/avatars/${encodeURIComponent(_avatarId)}`);
+ });
+
+ document.getElementById('done-editor-btn')?.addEventListener('click', () => {
+ if (!_avatarId) return;
+ window.location.assign(`/avatars/${encodeURIComponent(_avatarId)}/edit`);
+ });
</script>
</body>
</html>
diff --git a/pages/create.html b/pages/create.html
index 058a73a5c..f2c429942 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -667,15 +667,12 @@
fetch('/api/auth/me', { credentials: 'include' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (data) {
- if (!data || !data.user) {
- sessionStorage.setItem('login_redirect', '/create');
- location.replace('/login');
- } else {
- var el = document.getElementById('page-loading');
- if (el) el.remove();
- }
+ window.__authed = !!(data && data.user);
+ var el = document.getElementById('page-loading');
+ if (el) el.remove();
})
.catch(function () {
+ window.__authed = false;
var el = document.getElementById('page-loading');
if (el) el.remove();
});
diff --git a/pages/home.html b/pages/home.html
index 5afd6a908..af723d7ab 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -50,9 +50,11 @@
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/home.css" />
<link rel="stylesheet" href="/home-polish.css" />
+ <link rel="stylesheet" href="/home-saas.css" />
<link rel="stylesheet" href="/footer.css" />
<script defer src="/footer-newsletter.js"></script>
<script defer src="/home-polish.js"></script>
+ <script defer src="/home-saas.js"></script>
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/mobile.css" />
<script
diff --git a/pages/marketplace.html b/pages/marketplace.html
index ce6fbc9a9..6e98faf98 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -24,6 +24,20 @@
blocking page scroll. Force display:none whenever hidden is set. */
[hidden] { display: none !important; }
+ /* Screen-reader-only utility: visible to assistive tech, hidden visually.
+ Used to label search/sort controls without changing the topbar layout. */
+ .market-visually-hidden {
+ position: absolute !important;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+ }
+
.market-wip-banner {
display: flex;
align-items: center;
@@ -907,6 +921,147 @@
.market-skills-tab {
padding: 0 24px 32px;
}
+ #skills-cat-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0 0 14px;
+ }
+ #skills-cat-chips .market-chip {
+ font-size: 11px;
+ padding: 4px 10px;
+ }
+ #skills-cat-chips .market-chip .chip-count {
+ background: rgba(255, 255, 255, 0.08);
+ color: inherit;
+ padding: 1px 6px;
+ margin-left: 4px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 600;
+ }
+ #skills-cat-chips .market-chip.active .chip-count {
+ background: rgba(0, 0, 0, 0.15);
+ }
+ .market-skill-card .skill-desc {
+ font-size: 12px;
+ color: #a1a1aa;
+ line-height: 1.45;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ min-height: 32px;
+ }
+ .market-skill-card .skill-meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ font-size: 11px;
+ color: #71717a;
+ }
+ .market-skill-card .skill-meta .cat-pill {
+ background: rgba(125, 211, 252, 0.1);
+ color: #7dd3fc;
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: capitalize;
+ }
+ .market-skill-card .skill-meta .installs,
+ .market-skill-card .skill-meta .rating {
+ font-family: 'Space Grotesk', sans-serif;
+ font-weight: 500;
+ }
+ .market-skill-card.installed {
+ border-color: rgba(52, 211, 153, 0.35);
+ box-shadow: 0 0 0 1px rgba(52, 211, 153, 0.08);
+ }
+ .market-skill-card .skill-installed-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: #34d399;
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .market-skill-rating {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-top: 4px;
+ }
+ .market-skill-rating button {
+ background: transparent;
+ border: 0;
+ color: #71717a;
+ font-size: 20px;
+ cursor: pointer;
+ padding: 0;
+ line-height: 1;
+ font-family: inherit;
+ }
+ .market-skill-rating button.active,
+ .market-skill-rating button:hover {
+ color: #fde047;
+ }
+ .market-skill-rating .rating-count {
+ font-size: 11px;
+ color: #71717a;
+ margin-left: 8px;
+ }
+ .market-skill-tools {
+ background: rgba(125, 211, 252, 0.04);
+ border: 1px solid rgba(125, 211, 252, 0.12);
+ border-radius: 10px;
+ padding: 10px 12px;
+ margin-top: 6px;
+ }
+ .market-skill-tools h4 {
+ margin: 0 0 6px;
+ font-size: 11px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: #7dd3fc;
+ font-weight: 600;
+ }
+ .market-skill-tools ul {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .market-skill-tools li {
+ font-family: 'Space Grotesk', sans-serif;
+ font-size: 12px;
+ color: #e4e4e7;
+ }
+ .market-skill-tools li small {
+ display: block;
+ color: #71717a;
+ font-family: inherit;
+ font-size: 11px;
+ }
+ .market-skill-content {
+ background: #050505;
+ border: 1px solid #1f1f1f;
+ border-radius: 10px;
+ padding: 12px 14px;
+ margin-top: 6px;
+ max-height: 280px;
+ overflow-y: auto;
+ font-family: 'Space Grotesk', sans-serif;
+ font-size: 12px;
+ line-height: 1.55;
+ color: #d4d4d8;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
.market-skill-card {
background: var(--mk-panel, #111);
border: 1px solid var(--mk-border, #1f1f1f);
@@ -1130,6 +1285,47 @@
text-align: center;
min-height: 1.2em;
}
+ .payment-status.ok { color: #86efac; }
+ .payment-status.err { color: #fca5a5; }
+
+ .payment-qr {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ margin-top: 14px;
+ }
+ .payment-qr:empty { display: none; }
+ .payment-qr canvas {
+ background: #fff;
+ border-radius: 8px;
+ padding: 8px;
+ }
+ .payment-qr .muted { color: #9ca3af; }
+ .payment-qr .small { font-size: 11px; text-align: center; }
+
+ .payment-chain-picker {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 12px;
+ flex-wrap: wrap;
+ }
+ .payment-chain-pill {
+ background: #1a1a1a;
+ border: 1px solid #2a2a2a;
+ color: #cbd5e1;
+ padding: 6px 12px;
+ border-radius: 999px;
+ font-size: 12px;
+ cursor: pointer;
+ transition: all 0.15s;
+ }
+ .payment-chain-pill:hover { border-color: #404040; }
+ .payment-chain-pill.active {
+ background: #6366f1;
+ border-color: #6366f1;
+ color: #fff;
+ }
</style>
<meta property="og:type" content="website" />
<meta property="og:title" content="Agent Marketplace · three.ws" />
@@ -1180,6 +1376,11 @@
<main class="market-main" id="market-main">
<!-- Discovery view -->
<section class="market-discovery" id="market-discovery">
+ <!-- Stable, screen-reader-only page heading. The hero title below
+ is announced as the slide rotates, which is useful but isn't
+ a stable document landmark. This gives assistive tech a single
+ anchor for the page identity. -->
+ <h1 class="market-visually-hidden">Agent Marketplace</h1>
<!-- Weekly curated theme strip (loads from /api/marketplace/theme) -->
<aside class="market-theme-strip" id="market-theme-strip" hidden>
<span class="market-theme-eyebrow">This week</span>
@@ -1195,7 +1396,7 @@
Featured · Community Avatars
<span class="market-hero-beta-pill" aria-label="Marketplace is in beta">BETA</span>
</div>
- <h1 class="market-hero-title" id="market-hero-title">—</h1>
+ <h2 class="market-hero-title" id="market-hero-title">—</h2>
<p class="market-hero-desc" id="market-hero-desc">—</p>
<div class="market-hero-stats" id="market-hero-stats"></div>
<div class="market-hero-actions">
@@ -1215,19 +1416,22 @@
</div>
<header class="market-topbar">
+ <label class="market-visually-hidden" for="market-search">Search agents and avatars</label>
<input
id="market-search"
type="search"
placeholder="Search agents and avatars…"
autocomplete="off"
+ aria-label="Search agents and avatars"
/>
- <div class="market-filter-chips" id="market-filter-chips" role="tablist" aria-label="Filter">
- <button class="market-chip active" data-filter="all" role="tab">All</button>
- <button class="market-chip" data-filter="agents" role="tab">Agents</button>
- <button class="market-chip" data-filter="avatars" role="tab">Avatars</button>
- <button class="market-chip" data-filter="onchain" role="tab" title="ERC-8004 agents indexed onchain across Base, Polygon, and Solana" aria-label="Onchain — ERC-8004 agents indexed across all supported chains">Onchain <span class="chip-count" id="chip-count-onchain"></span></button>
+ <div class="market-filter-chips" id="market-filter-chips" role="tablist" aria-label="Filter agents and avatars">
+ <button class="market-chip active" data-filter="all" role="tab" aria-selected="true">All</button>
+ <button class="market-chip" data-filter="agents" role="tab" aria-selected="false">Agents</button>
+ <button class="market-chip" data-filter="avatars" role="tab" aria-selected="false">Avatars</button>
+ <button class="market-chip" data-filter="onchain" role="tab" aria-selected="false" title="ERC-8004 agents indexed onchain across Base, Polygon, and Solana" aria-label="Onchain — ERC-8004 agents indexed across all supported chains">Onchain <span class="chip-count" id="chip-count-onchain"></span></button>
</div>
- <select id="market-sort" class="market-sort">
+ <label class="market-visually-hidden" for="market-sort">Sort marketplace results</label>
+ <select id="market-sort" class="market-sort" aria-label="Sort marketplace results">
<option value="recommended">Recommended</option>
<option value="recent">Recent</option>
<option value="popular">Popular</option>
@@ -1390,14 +1594,43 @@
<button class="market-chip" data-skill-filter="free" role="tab">Free</button>
<button class="market-chip" data-skill-filter="paid" role="tab">Paid</button>
</div>
+ <select id="skills-sort" class="market-sort" aria-label="Sort skills">
+ <option value="popular">Popular</option>
+ <option value="new">New</option>
+ <option value="az">A–Z</option>
+ </select>
</header>
<div class="market-skills-tab">
+ <div class="market-cat-chips" id="skills-cat-chips" role="navigation" aria-label="Skill categories"></div>
<div class="market-grid" id="skills-grid">
<div class="market-empty">Loading skills…</div>
</div>
+ <div class="market-loadmore" id="skills-loadmore-row" hidden>
+ <button id="skills-loadmore">Load more</button>
+ </div>
</div>
</section>
+ <!-- Skill detail modal -->
+ <div class="avatar-modal-overlay" id="skill-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="skill-modal-title">
+ <div class="avatar-modal" role="document" style="grid-template-columns: 1fr;">
+ <button class="avatar-modal-close" id="skill-modal-close" aria-label="Close">×</button>
+ <div class="avatar-modal-side">
+ <div class="avatar-modal-eyebrow" id="skill-modal-eyebrow">Skill</div>
+ <h2 class="avatar-modal-title" id="skill-modal-title">—</h2>
+ <p class="avatar-modal-desc" id="skill-modal-desc"></p>
+ <div class="avatar-modal-meta" id="skill-modal-meta"></div>
+ <div id="skill-modal-rating" class="market-skill-rating" hidden></div>
+ <div id="skill-modal-tools" class="market-skill-tools" hidden></div>
+ <div id="skill-modal-content" class="market-skill-content" hidden></div>
+ <div class="avatar-modal-actions">
+ <button class="btn-primary" id="skill-modal-install">Install</button>
+ <button class="btn-secondary" id="skill-modal-author" hidden></button>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Plugins tab -->
<section class="market-tools" id="market-tools" hidden>
<header class="market-topbar plugins-topbar">
@@ -1656,6 +1889,8 @@
<button class="btn-primary payment-confirm-btn" id="payment-confirm-btn" disabled>Confirm Purchase</button>
+ <div class="payment-qr" id="payment-qr" aria-live="polite"></div>
+
<div class="payment-status" id="payment-status" role="status" aria-live="polite"></div>
</div>
</div>
diff --git a/public/agent/index.html b/public/agent/index.html
index 3c75b7e6f..8367999ec 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -932,9 +932,9 @@
const agentUrl = `${origin}/agent/${identity.id}`;
const snippets = {
- iframe: `<iframe src="${embedUrl}" width="420" height="520" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking"></iframe>`,
+ iframe: `<iframe src="${embedUrl}" width="420" height="520" title="three.ws agent" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" loading="lazy"></iframe>`,
link: agentUrl,
- webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n<agent-three.ws-id="${identity.id}" style="width:420px;height:520px"></agent-3d>`,
+ webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n<agent-3d agent-id="${identity.id}" style="width:420px;height:520px"></agent-3d>`,
};
let current = 'iframe';
diff --git a/public/home-saas.css b/public/home-saas.css
new file mode 100644
index 000000000..f002c0561
--- /dev/null
+++ b/public/home-saas.css
@@ -0,0 +1,1117 @@
+/* ───────────────────────────────────────────────────────────────────────────
+ home-saas.css — Unicorn-SaaS prologue stack stacked ABOVE the existing
+ cinematic hero. Purely additive; does not touch any existing .h-* class.
+ Loaded after /home.css and /home-polish.css from pages/home.html.
+ ─────────────────────────────────────────────────────────────────────────── */
+
+:root {
+ --saas-bg: #08070b;
+ --saas-bg-2: #0e0c12;
+ --saas-fg: #f5f1ea;
+ --saas-fg-soft: rgba(245, 241, 234, 0.66);
+ --saas-fg-mute: rgba(245, 241, 234, 0.45);
+ --saas-border: rgba(255, 255, 255, 0.08);
+ --saas-border-2: rgba(255, 255, 255, 0.14);
+ --saas-amber: #ffd76a;
+ --saas-amber-2: #ff8f4d;
+ --saas-mint: #6ee7b7;
+ --saas-violet: #b794f4;
+ --saas-radius: 14px;
+ --saas-radius-lg: 22px;
+ --saas-shadow:
+ 0 1px 0 rgba(255, 255, 255, 0.04) inset,
+ 0 18px 60px -20px rgba(0, 0, 0, 0.7);
+ --saas-pad-x: clamp(1rem, 4vw, 2rem);
+ --saas-w-max: 1240px;
+}
+
+/* ── Top-level wrapper. Stacks all prologue sections, sits above .h-hero-act ── */
+
+.h-saas {
+ position: relative;
+ z-index: 60;
+ background: var(--saas-bg);
+ color: var(--saas-fg);
+ font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif;
+ overflow: clip;
+}
+
+.h-saas * {
+ box-sizing: border-box;
+}
+
+.h-saas-inner {
+ max-width: var(--saas-w-max);
+ margin: 0 auto;
+ padding: 0 var(--saas-pad-x);
+}
+
+.h-saas-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.55rem;
+ padding: 0.4rem 0.85rem;
+ border-radius: 999px;
+ border: 1px solid var(--saas-border-2);
+ background: rgba(255, 255, 255, 0.025);
+ font-size: 0.74rem;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--saas-fg-soft);
+}
+
+.h-saas-eyebrow .dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--saas-amber);
+ box-shadow: 0 0 10px rgba(255, 215, 106, 0.65);
+}
+
+/* ── 1. Announcement bar ── */
+
+.h-saas-bar {
+ position: relative;
+ background:
+ linear-gradient(90deg, rgba(255, 175, 60, 0.08), rgba(110, 231, 183, 0.08)),
+ var(--saas-bg-2);
+ border-bottom: 1px solid var(--saas-border);
+ padding: 0.62rem var(--saas-pad-x);
+ z-index: 65;
+}
+
+.h-saas-bar-inner {
+ max-width: var(--saas-w-max);
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.7rem;
+ flex-wrap: wrap;
+ font-size: 0.82rem;
+ color: var(--saas-fg-soft);
+}
+
+.h-saas-bar-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ padding: 0.18rem 0.55rem;
+ border-radius: 999px;
+ background: rgba(110, 231, 183, 0.14);
+ border: 1px solid rgba(110, 231, 183, 0.32);
+ color: var(--saas-mint);
+ font-size: 0.7rem;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+.h-saas-bar-pill .pulse {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--saas-mint);
+ box-shadow: 0 0 0 0 rgba(110, 231, 183, 0.5);
+ animation: h-saas-pulse 2.2s ease-out infinite;
+}
+
+@keyframes h-saas-pulse {
+ 0% {
+ box-shadow: 0 0 0 0 rgba(110, 231, 183, 0.55);
+ }
+ 100% {
+ box-shadow: 0 0 0 9px rgba(110, 231, 183, 0);
+ }
+}
+
+.h-saas-bar a {
+ color: var(--saas-fg);
+ font-weight: 600;
+ text-decoration: none;
+ border-bottom: 1px solid rgba(255, 215, 106, 0.4);
+ transition: border-color 0.15s ease;
+}
+
+.h-saas-bar a:hover {
+ border-color: var(--saas-amber);
+}
+
+.h-saas-bar-close {
+ margin-left: 0.5rem;
+ background: transparent;
+ border: 0;
+ color: var(--saas-fg-mute);
+ cursor: pointer;
+ font: inherit;
+ padding: 0.15rem 0.4rem;
+ border-radius: 6px;
+ transition: color 0.15s ease, background 0.15s ease;
+}
+
+.h-saas-bar-close:hover {
+ color: var(--saas-fg);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+.h-saas-bar[hidden] {
+ display: none;
+}
+
+/* ── 2. Hero (split, SaaS-style) ── */
+
+.h-saas-hero {
+ position: relative;
+ padding: clamp(4.5rem, 9vh, 7.2rem) 0 clamp(3rem, 6vh, 5rem);
+ overflow: hidden;
+}
+
+.h-saas-hero::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background:
+ radial-gradient(60% 50% at 20% 30%, rgba(255, 175, 60, 0.14), transparent 65%),
+ radial-gradient(50% 50% at 90% 20%, rgba(110, 231, 183, 0.1), transparent 60%),
+ radial-gradient(40% 40% at 70% 90%, rgba(183, 148, 244, 0.08), transparent 60%);
+ pointer-events: none;
+}
+
+.h-saas-hero::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background-image:
+ linear-gradient(rgba(255, 255, 255, 0.04) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(255, 255, 255, 0.04) 1px, transparent 1px);
+ background-size: 64px 64px;
+ mask-image: radial-gradient(80% 60% at 50% 30%, #000 30%, transparent 90%);
+ -webkit-mask-image: radial-gradient(80% 60% at 50% 30%, #000 30%, transparent 90%);
+ pointer-events: none;
+ opacity: 0.55;
+}
+
+.h-saas-hero-inner {
+ position: relative;
+ display: grid;
+ grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
+ gap: clamp(2rem, 5vw, 4rem);
+ align-items: center;
+}
+
+@media (max-width: 960px) {
+ .h-saas-hero-inner {
+ grid-template-columns: 1fr;
+ }
+}
+
+.h-saas-h1 {
+ font-size: clamp(2.6rem, 5.6vw, 4.6rem);
+ font-weight: 700;
+ line-height: 1.02;
+ letter-spacing: -0.035em;
+ margin: 1rem 0 1.2rem;
+ color: var(--saas-fg);
+}
+
+.h-saas-h1 em {
+ font-style: normal;
+ background: linear-gradient(135deg, var(--saas-amber) 0%, var(--saas-amber-2) 60%, var(--saas-violet) 110%);
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+}
+
+.h-saas-sub {
+ font-size: clamp(1.05rem, 1.6vw, 1.22rem);
+ line-height: 1.55;
+ color: var(--saas-fg-soft);
+ max-width: 58ch;
+ margin: 0 0 1.8rem;
+ text-wrap: pretty;
+}
+
+.h-saas-cta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.7rem;
+ margin-bottom: 1.8rem;
+}
+
+.h-saas-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.85rem 1.4rem;
+ border-radius: 10px;
+ font-size: 0.96rem;
+ font-weight: 600;
+ font-family: inherit;
+ text-decoration: none;
+ cursor: pointer;
+ transition: transform 0.15s ease, box-shadow 0.2s ease, background 0.2s ease, border-color 0.2s ease;
+ border: 1px solid transparent;
+ white-space: nowrap;
+}
+
+.h-saas-btn--primary {
+ background: linear-gradient(135deg, var(--saas-amber), var(--saas-amber-2));
+ color: #1a0f04;
+ box-shadow:
+ 0 8px 24px -8px rgba(255, 143, 77, 0.55),
+ 0 1px 0 rgba(255, 255, 255, 0.35) inset;
+}
+
+.h-saas-btn--primary:hover {
+ transform: translateY(-1px);
+ box-shadow:
+ 0 14px 32px -10px rgba(255, 143, 77, 0.7),
+ 0 1px 0 rgba(255, 255, 255, 0.4) inset;
+}
+
+.h-saas-btn--ghost {
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--saas-fg);
+ border-color: var(--saas-border-2);
+}
+
+.h-saas-btn--ghost:hover {
+ background: rgba(255, 255, 255, 0.08);
+ border-color: rgba(255, 255, 255, 0.28);
+}
+
+.h-saas-btn .arrow {
+ transition: transform 0.18s ease;
+}
+
+.h-saas-btn:hover .arrow {
+ transform: translateX(3px);
+}
+
+/* Social-proof row under CTAs */
+
+.h-saas-proof {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+ color: var(--saas-fg-mute);
+ font-size: 0.85rem;
+}
+
+.h-saas-avatars {
+ display: flex;
+ align-items: center;
+}
+
+.h-saas-avatars .av {
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+ border: 2px solid var(--saas-bg);
+ background: linear-gradient(135deg, #ffd76a, #b794f4);
+ margin-left: -8px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
+}
+
+.h-saas-avatars .av:first-child {
+ margin-left: 0;
+}
+
+.h-saas-avatars .av:nth-child(2) {
+ background: linear-gradient(135deg, #6ee7b7, #5c93ff);
+}
+
+.h-saas-avatars .av:nth-child(3) {
+ background: linear-gradient(135deg, #ff8f4d, #ff5ca8);
+}
+
+.h-saas-avatars .av:nth-child(4) {
+ background: linear-gradient(135deg, #b794f4, #ffd76a);
+}
+
+.h-saas-avatars .av:nth-child(5) {
+ background: linear-gradient(135deg, #5c93ff, #6ee7b7);
+ font-family: inherit;
+ font-size: 0.65rem;
+ color: #08070b;
+ display: grid;
+ place-items: center;
+ font-weight: 700;
+}
+
+.h-saas-stars {
+ letter-spacing: 0.08em;
+ color: var(--saas-amber);
+ font-size: 0.95rem;
+}
+
+/* Hero right: product card */
+
+.h-saas-pcard {
+ position: relative;
+ border: 1px solid var(--saas-border-2);
+ border-radius: var(--saas-radius-lg);
+ background:
+ radial-gradient(120% 90% at 50% 0%, rgba(255, 175, 60, 0.16), transparent 60%),
+ linear-gradient(180deg, rgba(20, 17, 24, 0.95), rgba(8, 7, 11, 0.95));
+ box-shadow: var(--saas-shadow);
+ overflow: hidden;
+ aspect-ratio: 4 / 3.2;
+ min-height: 340px;
+}
+
+.h-saas-pcard-bar {
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ padding: 0.7rem 0.9rem;
+ border-bottom: 1px solid var(--saas-border);
+ background: rgba(255, 255, 255, 0.02);
+}
+
+.h-saas-pcard-bar .d {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.14);
+}
+
+.h-saas-pcard-bar .d:nth-child(1) { background: #ff5f57; }
+.h-saas-pcard-bar .d:nth-child(2) { background: #febc2e; }
+.h-saas-pcard-bar .d:nth-child(3) { background: #28c840; }
+
+.h-saas-pcard-bar .url {
+ margin-left: 0.7rem;
+ flex: 1;
+ font-size: 0.74rem;
+ color: var(--saas-fg-mute);
+ background: rgba(255, 255, 255, 0.04);
+ padding: 0.18rem 0.6rem;
+ border-radius: 6px;
+ border: 1px solid var(--saas-border);
+}
+
+.h-saas-pcard-stage {
+ position: relative;
+ height: calc(100% - 38px);
+ display: grid;
+ place-items: center;
+}
+
+.h-saas-pcard-stage model-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+}
+
+.h-saas-pcard-hud {
+ position: absolute;
+ left: 14px;
+ bottom: 14px;
+ right: 14px;
+ display: flex;
+ justify-content: space-between;
+ gap: 0.5rem;
+ pointer-events: none;
+ flex-wrap: wrap;
+}
+
+.h-saas-pcard-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ padding: 0.34rem 0.7rem;
+ border-radius: 8px;
+ background: rgba(8, 7, 11, 0.72);
+ border: 1px solid var(--saas-border-2);
+ font-size: 0.72rem;
+ font-weight: 600;
+ color: var(--saas-fg);
+ backdrop-filter: blur(6px);
+ -webkit-backdrop-filter: blur(6px);
+}
+
+.h-saas-pcard-chip .pulse {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--saas-mint);
+ box-shadow: 0 0 0 0 rgba(110, 231, 183, 0.5);
+ animation: h-saas-pulse 2s ease-out infinite;
+}
+
+.h-saas-pcard-chip.tx code {
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 0.7rem;
+ color: var(--saas-mint);
+}
+
+/* ── 3. Logo marquee ── */
+
+.h-saas-logos {
+ position: relative;
+ padding: 2.4rem 0 2.8rem;
+ border-top: 1px solid var(--saas-border);
+ border-bottom: 1px solid var(--saas-border);
+ background: var(--saas-bg-2);
+}
+
+.h-saas-logos-title {
+ text-align: center;
+ font-size: 0.74rem;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--saas-fg-mute);
+ margin: 0 0 1.4rem;
+}
+
+.h-saas-marquee {
+ position: relative;
+ overflow: hidden;
+ mask-image: linear-gradient(90deg, transparent 0, #000 8%, #000 92%, transparent 100%);
+ -webkit-mask-image: linear-gradient(90deg, transparent 0, #000 8%, #000 92%, transparent 100%);
+}
+
+.h-saas-marquee-track {
+ display: flex;
+ gap: 3.2rem;
+ width: max-content;
+ animation: h-saas-marquee 36s linear infinite;
+}
+
+.h-saas-marquee:hover .h-saas-marquee-track {
+ animation-play-state: paused;
+}
+
+@keyframes h-saas-marquee {
+ to {
+ transform: translateX(-50%);
+ }
+}
+
+.h-saas-mark {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.55rem;
+ color: var(--saas-fg-soft);
+ font-weight: 600;
+ font-size: 1.05rem;
+ letter-spacing: -0.01em;
+ white-space: nowrap;
+ opacity: 0.82;
+ transition: color 0.2s ease, opacity 0.2s ease;
+}
+
+.h-saas-mark:hover {
+ color: var(--saas-fg);
+ opacity: 1;
+}
+
+.h-saas-mark .glyph {
+ display: inline-grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: 6px;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--saas-border);
+ font-size: 0.78rem;
+ font-weight: 700;
+ color: var(--saas-fg);
+}
+
+/* ── 4. Live metrics band ── */
+
+.h-saas-metrics {
+ padding: clamp(3rem, 6vh, 5rem) 0;
+ position: relative;
+}
+
+.h-saas-metrics[hidden] {
+ display: none;
+}
+
+.h-saas-metrics-head {
+ text-align: center;
+ margin-bottom: 2.2rem;
+}
+
+.h-saas-metrics-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 1px;
+ background: var(--saas-border);
+ border: 1px solid var(--saas-border);
+ border-radius: var(--saas-radius);
+ overflow: hidden;
+}
+
+@media (max-width: 720px) {
+ .h-saas-metrics-grid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+
+.h-saas-metric {
+ background: var(--saas-bg-2);
+ padding: 1.6rem 1.3rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+}
+
+.h-saas-metric-num {
+ font-size: clamp(1.7rem, 3vw, 2.4rem);
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ background: linear-gradient(135deg, var(--saas-amber), var(--saas-amber-2));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ font-variant-numeric: tabular-nums;
+}
+
+.h-saas-metric-label {
+ font-size: 0.74rem;
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ color: var(--saas-fg-mute);
+}
+
+/* ── 5. Section heading helper ── */
+
+.h-saas-section {
+ padding: clamp(3.6rem, 8vh, 6rem) 0;
+ position: relative;
+}
+
+.h-saas-section + .h-saas-section {
+ border-top: 1px solid var(--saas-border);
+}
+
+.h-saas-section-head {
+ max-width: 720px;
+ margin: 0 auto 2.4rem;
+ text-align: center;
+}
+
+.h-saas-section-title {
+ font-size: clamp(1.7rem, 3.4vw, 2.6rem);
+ font-weight: 700;
+ letter-spacing: -0.025em;
+ line-height: 1.12;
+ margin: 0.9rem 0 0.7rem;
+ color: var(--saas-fg);
+}
+
+.h-saas-section-sub {
+ color: var(--saas-fg-soft);
+ font-size: 1.02rem;
+ line-height: 1.55;
+ margin: 0;
+}
+
+/* ── 6. Audience tabs ── */
+
+.h-saas-tabs {
+ display: inline-flex;
+ gap: 0.3rem;
+ padding: 0.32rem;
+ border: 1px solid var(--saas-border-2);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.025);
+ margin-bottom: 2rem;
+}
+
+.h-saas-tab {
+ padding: 0.55rem 1.1rem;
+ background: transparent;
+ border: 0;
+ color: var(--saas-fg-soft);
+ font: 600 0.86rem/1 'Space Grotesk', 'Inter', sans-serif;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.18s ease, color 0.18s ease;
+}
+
+.h-saas-tab[aria-selected='true'] {
+ background: linear-gradient(135deg, rgba(255, 215, 106, 0.18), rgba(255, 143, 77, 0.18));
+ color: var(--saas-amber);
+ box-shadow: 0 0 0 1px rgba(255, 215, 106, 0.3) inset;
+}
+
+.h-saas-tabwrap {
+ text-align: center;
+}
+
+.h-saas-tabpanel {
+ margin-top: 1.2rem;
+ max-width: 720px;
+ margin-left: auto;
+ margin-right: auto;
+ color: var(--saas-fg-soft);
+ font-size: 1.05rem;
+ line-height: 1.55;
+ min-height: 4.5rem;
+}
+
+.h-saas-tabpanel strong {
+ color: var(--saas-fg);
+ font-weight: 600;
+}
+
+/* ── 7. Use case cards (real avatars) ── */
+
+.h-saas-cases {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 1.1rem;
+}
+
+@media (max-width: 880px) {
+ .h-saas-cases {
+ grid-template-columns: 1fr;
+ }
+}
+
+.h-saas-case {
+ position: relative;
+ background:
+ radial-gradient(80% 50% at 50% 0%, rgba(255, 175, 60, 0.08), transparent 60%),
+ var(--saas-bg-2);
+ border: 1px solid var(--saas-border-2);
+ border-radius: var(--saas-radius);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ transition: border-color 0.2s ease, transform 0.2s ease;
+}
+
+.h-saas-case:hover {
+ border-color: rgba(255, 215, 106, 0.4);
+ transform: translateY(-2px);
+}
+
+.h-saas-case-stage {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ background: radial-gradient(60% 60% at 50% 50%, rgba(255, 175, 60, 0.1), transparent 70%);
+}
+
+.h-saas-case-stage model-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+}
+
+.h-saas-case-body {
+ padding: 1.1rem 1.2rem 1.3rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+}
+
+.h-saas-case-kicker {
+ font-size: 0.7rem;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--saas-amber);
+ font-weight: 700;
+}
+
+.h-saas-case-title {
+ font-size: 1.08rem;
+ font-weight: 600;
+ color: var(--saas-fg);
+ margin: 0;
+ letter-spacing: -0.01em;
+}
+
+.h-saas-case-desc {
+ font-size: 0.92rem;
+ color: var(--saas-fg-soft);
+ line-height: 1.5;
+ margin: 0.1rem 0 0.5rem;
+}
+
+.h-saas-case-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ color: var(--saas-amber);
+ font-size: 0.86rem;
+ font-weight: 600;
+ text-decoration: none;
+ margin-top: auto;
+}
+
+.h-saas-case-link:hover {
+ color: var(--saas-fg);
+}
+
+/* ── 8. Code snippet card ── */
+
+.h-saas-codecard {
+ max-width: 760px;
+ margin: 0 auto;
+ border: 1px solid var(--saas-border-2);
+ border-radius: var(--saas-radius);
+ background: linear-gradient(180deg, #14101a, #0c0a10);
+ overflow: hidden;
+ box-shadow: var(--saas-shadow);
+}
+
+.h-saas-codecard-bar {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.65rem 0.9rem;
+ border-bottom: 1px solid var(--saas-border);
+ background: rgba(255, 255, 255, 0.02);
+}
+
+.h-saas-codecard-bar .d {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+}
+
+.h-saas-codecard-bar .d:nth-child(1) { background: #ff5f57; }
+.h-saas-codecard-bar .d:nth-child(2) { background: #febc2e; }
+.h-saas-codecard-bar .d:nth-child(3) { background: #28c840; }
+
+.h-saas-codecard-bar .filename {
+ flex: 1;
+ text-align: center;
+ font-size: 0.78rem;
+ color: var(--saas-fg-mute);
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+}
+
+.h-saas-copy {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--saas-border);
+ color: var(--saas-fg-soft);
+ border-radius: 7px;
+ padding: 0.3rem 0.7rem;
+ font: 600 0.74rem 'Space Grotesk', sans-serif;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+
+.h-saas-copy:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--saas-fg);
+}
+
+.h-saas-copy[data-copied='true'] {
+ background: rgba(110, 231, 183, 0.14);
+ border-color: rgba(110, 231, 183, 0.45);
+ color: var(--saas-mint);
+}
+
+.h-saas-codecard pre {
+ margin: 0;
+ padding: 1.2rem 1.3rem 1.4rem;
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 0.86rem;
+ line-height: 1.65;
+ color: #d6cebf;
+ overflow-x: auto;
+}
+
+.h-saas-codecard .tag { color: #ff8f4d; }
+.h-saas-codecard .attr { color: #ffd76a; }
+.h-saas-codecard .val { color: #6ee7b7; }
+.h-saas-codecard .c { color: rgba(255, 255, 255, 0.32); font-style: italic; }
+
+/* ── 9. Integration grid ── */
+
+.h-saas-int-grid {
+ display: grid;
+ grid-template-columns: repeat(6, 1fr);
+ gap: 1px;
+ background: var(--saas-border);
+ border: 1px solid var(--saas-border);
+ border-radius: var(--saas-radius);
+ overflow: hidden;
+}
+
+@media (max-width: 960px) {
+ .h-saas-int-grid {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+
+@media (max-width: 520px) {
+ .h-saas-int-grid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+
+.h-saas-int {
+ background: var(--saas-bg-2);
+ padding: 1.4rem 1rem;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.55rem;
+ min-height: 110px;
+ transition: background 0.18s ease;
+}
+
+.h-saas-int:hover {
+ background: rgba(255, 255, 255, 0.04);
+}
+
+.h-saas-int .glyph {
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ background: linear-gradient(135deg, rgba(255, 175, 60, 0.16), rgba(110, 231, 183, 0.1));
+ border: 1px solid var(--saas-border-2);
+ font-size: 0.86rem;
+ font-weight: 700;
+ color: var(--saas-fg);
+}
+
+.h-saas-int-name {
+ font-size: 0.86rem;
+ font-weight: 600;
+ color: var(--saas-fg-soft);
+ letter-spacing: -0.005em;
+}
+
+/* ── 10. Pricing teaser ── */
+
+.h-saas-price {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 2.4rem;
+ align-items: center;
+ max-width: 1000px;
+ margin: 0 auto;
+}
+
+@media (max-width: 800px) {
+ .h-saas-price {
+ grid-template-columns: 1fr;
+ }
+}
+
+.h-saas-price-copy h2 {
+ font-size: clamp(1.6rem, 3.2vw, 2.4rem);
+ font-weight: 700;
+ letter-spacing: -0.025em;
+ margin: 0.9rem 0 0.7rem;
+ line-height: 1.1;
+ color: var(--saas-fg);
+}
+
+.h-saas-price-copy p {
+ color: var(--saas-fg-soft);
+ font-size: 1.02rem;
+ line-height: 1.55;
+ margin: 0 0 1.4rem;
+}
+
+.h-saas-price-bullets {
+ list-style: none;
+ margin: 0 0 1.6rem;
+ padding: 0;
+ display: grid;
+ gap: 0.55rem;
+}
+
+.h-saas-price-bullets li {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.6rem;
+ color: var(--saas-fg-soft);
+ font-size: 0.95rem;
+ line-height: 1.5;
+}
+
+.h-saas-price-bullets li::before {
+ content: '';
+ flex: 0 0 18px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background:
+ radial-gradient(circle at 50% 50%, rgba(110, 231, 183, 0.7), rgba(110, 231, 183, 0) 60%),
+ rgba(110, 231, 183, 0.08);
+ border: 1px solid rgba(110, 231, 183, 0.45);
+ margin-top: 0.18rem;
+ position: relative;
+}
+
+.h-saas-price-card {
+ position: relative;
+ background:
+ radial-gradient(120% 100% at 50% 0%, rgba(255, 175, 60, 0.16), transparent 60%),
+ var(--saas-bg-2);
+ border: 1px solid var(--saas-border-2);
+ border-radius: var(--saas-radius-lg);
+ padding: 2rem 1.8rem;
+ box-shadow: var(--saas-shadow);
+}
+
+.h-saas-price-tier {
+ font-size: 0.72rem;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--saas-amber);
+ font-weight: 700;
+}
+
+.h-saas-price-amount {
+ font-size: clamp(2.4rem, 4vw, 3.2rem);
+ font-weight: 700;
+ letter-spacing: -0.03em;
+ margin: 0.3rem 0 0.1rem;
+ line-height: 1;
+ color: var(--saas-fg);
+}
+
+.h-saas-price-amount small {
+ font-size: 0.96rem;
+ color: var(--saas-fg-mute);
+ font-weight: 500;
+ margin-left: 0.4rem;
+}
+
+.h-saas-price-note {
+ color: var(--saas-fg-mute);
+ font-size: 0.82rem;
+ margin: 0.2rem 0 1.4rem;
+}
+
+.h-saas-price-card .h-saas-btn {
+ width: 100%;
+ justify-content: center;
+}
+
+.h-saas-price-foot {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.6rem;
+ margin-top: 1rem;
+ font-size: 0.82rem;
+ color: var(--saas-fg-mute);
+}
+
+.h-saas-price-foot a {
+ color: var(--saas-fg-soft);
+ text-decoration: none;
+ border-bottom: 1px solid var(--saas-border-2);
+ transition: border-color 0.15s ease, color 0.15s ease;
+}
+
+.h-saas-price-foot a:hover {
+ color: var(--saas-fg);
+ border-color: var(--saas-fg-soft);
+}
+
+/* ── 11. Closing CTA band ── */
+
+.h-saas-cta-band {
+ position: relative;
+ padding: clamp(3.6rem, 8vh, 6rem) var(--saas-pad-x);
+ text-align: center;
+ background:
+ radial-gradient(60% 80% at 50% 50%, rgba(255, 175, 60, 0.16), transparent 70%),
+ linear-gradient(180deg, #0e0c12, #08070b);
+ border-top: 1px solid var(--saas-border);
+ border-bottom: 1px solid var(--saas-border);
+ overflow: hidden;
+}
+
+.h-saas-cta-band::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background-image:
+ linear-gradient(rgba(255, 255, 255, 0.04) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(255, 255, 255, 0.04) 1px, transparent 1px);
+ background-size: 48px 48px;
+ mask-image: radial-gradient(50% 50% at 50% 50%, #000, transparent 80%);
+ -webkit-mask-image: radial-gradient(50% 50% at 50% 50%, #000, transparent 80%);
+ pointer-events: none;
+ opacity: 0.6;
+}
+
+.h-saas-cta-band > * {
+ position: relative;
+}
+
+.h-saas-cta-h {
+ font-size: clamp(2rem, 4.6vw, 3.6rem);
+ font-weight: 700;
+ letter-spacing: -0.03em;
+ line-height: 1.05;
+ margin: 0.6rem 0 0.8rem;
+ max-width: 18ch;
+ margin-left: auto;
+ margin-right: auto;
+ color: var(--saas-fg);
+}
+
+.h-saas-cta-h em {
+ font-style: normal;
+ background: linear-gradient(135deg, var(--saas-amber), var(--saas-amber-2));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+}
+
+.h-saas-cta-p {
+ color: var(--saas-fg-soft);
+ font-size: 1.1rem;
+ margin: 0 auto 1.6rem;
+ max-width: 48ch;
+}
+
+.h-saas-cta-row {
+ display: inline-flex;
+ gap: 0.7rem;
+ flex-wrap: wrap;
+ justify-content: center;
+}
+
+/* ── Reveal-on-scroll (additive; matches existing .h-reveal cadence) ── */
+
+.h-saas-reveal {
+ opacity: 0;
+ transform: translateY(14px);
+ transition: opacity 0.6s ease, transform 0.6s ease;
+ will-change: opacity, transform;
+}
+
+.h-saas-reveal.is-in {
+ opacity: 1;
+ transform: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .h-saas-reveal {
+ opacity: 1;
+ transform: none;
+ transition: none;
+ }
+ .h-saas-marquee-track {
+ animation: none;
+ }
+ .h-saas-bar-pill .pulse,
+ .h-saas-pcard-chip .pulse {
+ animation: none;
+ }
+}
diff --git a/public/home-saas.js b/public/home-saas.js
new file mode 100644
index 000000000..19e324271
--- /dev/null
+++ b/public/home-saas.js
@@ -0,0 +1,207 @@
+/* home-saas.js — wires the unicorn-SaaS prologue stack on /home.
+ *
+ * Owns:
+ * • announcement bar dismiss (localStorage)
+ * • live metrics counter (fetches /api/home-stats; hides if unavailable)
+ * • audience tabs (Creators / Developers / DAOs / Enterprises)
+ * • code-snippet copy-to-clipboard
+ * • reveal-on-scroll via IntersectionObserver
+ *
+ * No build step. Loaded with `defer`. Idempotent across re-imports.
+ */
+
+(() => {
+ if (window.__threeWsHomeSaasInited) return;
+ window.__threeWsHomeSaasInited = true;
+
+ const ready = (fn) => {
+ if (document.readyState !== 'loading') fn();
+ else document.addEventListener('DOMContentLoaded', fn, { once: true });
+ };
+
+ ready(() => {
+ initBar();
+ initReveal();
+ initMetrics();
+ initTabs();
+ initCopy();
+ });
+
+ // ── 1. Announcement bar dismiss ────────────────────────────────────────
+ function initBar() {
+ const bar = document.querySelector('[data-saas-bar]');
+ if (!bar) return;
+ const KEY = 'three-ws-saas-bar-dismissed-v1';
+ try {
+ if (localStorage.getItem(KEY)) {
+ bar.hidden = true;
+ return;
+ }
+ } catch (_) {
+ /* localStorage unavailable in private mode — show bar */
+ }
+ const close = bar.querySelector('[data-saas-bar-close]');
+ if (close) {
+ close.addEventListener('click', () => {
+ bar.hidden = true;
+ try {
+ localStorage.setItem(KEY, '1');
+ } catch (_) {
+ /* ignore */
+ }
+ });
+ }
+ }
+
+ // ── 2. Reveal-on-scroll ───────────────────────────────────────────────
+ function initReveal() {
+ const targets = document.querySelectorAll('.h-saas-reveal');
+ if (!targets.length) return;
+ if (!('IntersectionObserver' in window)) {
+ targets.forEach((el) => el.classList.add('is-in'));
+ return;
+ }
+ const io = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) {
+ entry.target.classList.add('is-in');
+ io.unobserve(entry.target);
+ }
+ }
+ },
+ { rootMargin: '0px 0px -8% 0px', threshold: 0.08 },
+ );
+ targets.forEach((el) => io.observe(el));
+ }
+
+ // ── 3. Live metrics (real /api/home-stats) ───────────────────────────
+ async function initMetrics() {
+ const root = document.querySelector('[data-saas-metrics]');
+ if (!root) return;
+
+ let stats;
+ try {
+ const res = await fetch('/api/home-stats', {
+ credentials: 'omit',
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error('http_' + res.status);
+ stats = await res.json();
+ } catch (err) {
+ console.debug('[home-saas] metrics unavailable', err?.message || err);
+ root.hidden = true;
+ return;
+ }
+
+ if (!stats || stats.available === false) {
+ root.hidden = true;
+ return;
+ }
+
+ const fields = root.querySelectorAll('[data-saas-metric]');
+ let anyShown = false;
+ fields.forEach((el) => {
+ const key = el.dataset.saasMetric;
+ const val = stats[key];
+ if (typeof val !== 'number' || val < 0) {
+ const item = el.closest('.h-saas-metric');
+ if (item) item.hidden = true;
+ return;
+ }
+ anyShown = true;
+ animateCount(el, val);
+ });
+
+ if (!anyShown) root.hidden = true;
+ }
+
+ function animateCount(el, target) {
+ const duration = 1100;
+ const start = performance.now();
+ const from = 0;
+ const ease = (t) => 1 - Math.pow(1 - t, 3);
+ function tick(now) {
+ const t = Math.min(1, (now - start) / duration);
+ const v = Math.floor(from + (target - from) * ease(t));
+ el.textContent = format(v);
+ if (t < 1) requestAnimationFrame(tick);
+ else el.textContent = format(target);
+ }
+ requestAnimationFrame(tick);
+ }
+
+ function format(n) {
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1) + 'M';
+ if (n >= 10_000) return (n / 1_000).toFixed(0) + 'k';
+ if (n >= 1_000) return (n / 1_000).toFixed(1) + 'k';
+ return n.toLocaleString();
+ }
+
+ // ── 4. Audience tabs ─────────────────────────────────────────────────
+ function initTabs() {
+ const wrap = document.querySelector('[data-saas-tabs]');
+ if (!wrap) return;
+ const tabs = Array.from(wrap.querySelectorAll('[role="tab"]'));
+ const panel = document.querySelector('[data-saas-tabpanel]');
+ if (!tabs.length || !panel) return;
+
+ const select = (idx) => {
+ tabs.forEach((t, i) => {
+ const on = i === idx;
+ t.setAttribute('aria-selected', on ? 'true' : 'false');
+ t.tabIndex = on ? 0 : -1;
+ });
+ const active = tabs[idx];
+ panel.innerHTML = active.dataset.saasCopy || '';
+ };
+
+ tabs.forEach((tab, i) => {
+ tab.addEventListener('click', () => select(i));
+ tab.addEventListener('keydown', (e) => {
+ if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ select((i + 1) % tabs.length);
+ tabs[(i + 1) % tabs.length].focus();
+ } else if (e.key === 'ArrowLeft') {
+ e.preventDefault();
+ const prev = (i - 1 + tabs.length) % tabs.length;
+ select(prev);
+ tabs[prev].focus();
+ }
+ });
+ });
+
+ const initial = tabs.findIndex((t) => t.getAttribute('aria-selected') === 'true');
+ select(initial < 0 ? 0 : initial);
+ }
+
+ // ── 5. Copy code snippet ─────────────────────────────────────────────
+ function initCopy() {
+ const btns = document.querySelectorAll('[data-saas-copy]');
+ btns.forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const targetSel = btn.dataset.saasCopy;
+ const target = targetSel ? document.querySelector(targetSel) : null;
+ if (!target) return;
+ const text = target.innerText.trim();
+ try {
+ await navigator.clipboard.writeText(text);
+ btn.dataset.copied = 'true';
+ const orig = btn.textContent;
+ btn.textContent = 'Copied';
+ setTimeout(() => {
+ btn.removeAttribute('data-copied');
+ btn.textContent = orig;
+ }, 1600);
+ } catch (err) {
+ console.warn('[home-saas] clipboard failed', err);
+ btn.textContent = 'Press ⌘C';
+ setTimeout(() => {
+ btn.textContent = 'Copy';
+ }, 1600);
+ }
+ });
+ });
+ }
+})();
diff --git a/public/nav.css b/public/nav.css
index cf5a36ee4..a73add059 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -109,6 +109,20 @@
line-height: 1.2;
}
+/* The header is a flex row of <h1> + <div id="nav-container">. Default flex
+ items shrink to content width, so on mobile the nav-container collapses to
+ just the burger and clings to the h1 — making the burger appear mid-header
+ and shoving the mobile menu's `right: 0` anchor off-screen to the left.
+ Force the wrapper to absorb the remaining width so the burger sits at the
+ right edge and the menu opens flush right. */
+#nav-container {
+ flex: 1 1 auto;
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ min-width: 0;
+}
+
.home-nav {
margin-left: auto;
display: flex;
diff --git a/scratch/nav-verify.mjs b/scratch/nav-verify.mjs
new file mode 100644
index 000000000..0dd936d1f
--- /dev/null
+++ b/scratch/nav-verify.mjs
@@ -0,0 +1,43 @@
+import { chromium } from 'playwright';
+
+const browser = await chromium.launch();
+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+const page = await ctx.newPage();
+
+const errors = [];
+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
+page.on('console', (msg) => {
+ if (msg.type() === 'error' && !msg.text().includes('CORS')) errors.push('err: ' + msg.text().slice(0, 120));
+});
+
+await page.goto('http://localhost:3000/marketplace', { waitUntil: 'networkidle', timeout: 30000 });
+await page.waitForSelector('.home-nav .nav-root', { timeout: 5000 });
+await page.waitForTimeout(800);
+
+await page.screenshot({ path: '/tmp/v-header.png', clip: { x: 0, y: 0, width: 1440, height: 80 } });
+
+const buildBtn = await page.locator('.home-nav .nav-trigger', { hasText: 'Build' }).first();
+await buildBtn.click();
+await page.waitForTimeout(400);
+await page.screenshot({ path: '/tmp/v-build.png', clip: { x: 0, y: 0, width: 600, height: 320 } });
+await page.mouse.click(10, 600);
+await page.waitForTimeout(200);
+
+const labsBtn = await page.locator('.home-nav .nav-trigger', { hasText: 'Labs' }).first();
+await labsBtn.click();
+await page.waitForTimeout(400);
+await page.screenshot({ path: '/tmp/v-labs.png', clip: { x: 600, y: 0, width: 840, height: 720 } });
+await page.mouse.click(10, 600);
+await page.waitForTimeout(200);
+
+await page.setViewportSize({ width: 390, height: 800 });
+await page.waitForTimeout(400);
+await page.screenshot({ path: '/tmp/v-mobile.png', clip: { x: 0, y: 0, width: 390, height: 80 } });
+
+const burger = await page.locator('.home-nav .nav-burger').first();
+await burger.click();
+await page.waitForTimeout(400);
+await page.screenshot({ path: '/tmp/v-mobile-open.png', clip: { x: 0, y: 0, width: 390, height: 600 } });
+
+console.log('errors:', JSON.stringify(errors, null, 2));
+await browser.close();
diff --git a/scripts/debug-home-v2.mjs b/scripts/debug-home-v2.mjs
index fc0a26971..a6820aebb 100644
--- a/scripts/debug-home-v2.mjs
+++ b/scripts/debug-home-v2.mjs
@@ -1,30 +1,30 @@
import { chromium } from 'playwright';
-const browser = await chromium.launch();
+const browser = await chromium.launch({
+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'],
+});
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
-page.on('pageerror', (e) => console.log('PAGEERROR:', e.message));
-page.on('console', (m) => { if (m.type() === 'error') console.log('CONSOLE.ERR:', m.text()); });
-
-await page.goto('http://localhost:3000/home-v2', { waitUntil: 'domcontentloaded' });
-await page.waitForTimeout(1500);
-const info = await page.evaluate(() => {
- const wrap = document.getElementById('hv2-chips-wrap');
- const chips = document.getElementById('hv2-chips');
- const tryme = document.getElementById('hv2-tryme');
- const danceChip = document.querySelector('.hv2-chip[data-anim="dance"]');
- const heroAct = document.querySelector('.h-hero-act');
- const r = (el) => el ? el.getBoundingClientRect().toJSON() : null;
- const cs = (el) => {
- if (!el) return null;
- const s = getComputedStyle(el);
- return { display: s.display, visibility: s.visibility, opacity: s.opacity, position: s.position, zIndex: s.zIndex, pointerEvents: s.pointerEvents };
- };
- return {
- wrapExists: !!wrap, chipsExists: !!chips, danceExists: !!danceChip, trymeExists: !!tryme,
- wrapRect: r(wrap), chipsRect: r(chips), danceRect: r(danceChip), trymeRect: r(tryme), heroRect: r(heroAct),
- wrapCs: cs(wrap), chipsCs: cs(chips), danceCs: cs(danceChip), trymeCs: cs(tryme),
- };
+page.on('pageerror', (e) => console.log('PAGEERROR:', e.message, '\n', e.stack?.slice(0, 500)));
+page.on('console', (m) => {
+ const t = m.type();
+ if (t === 'error' || t === 'warning') console.log(`[${t}]`, m.text());
});
-console.log(JSON.stringify(info, null, 2));
-await page.screenshot({ path: '/tmp/home-v2-debug.png' });
+page.on('crash', () => console.log('PAGE CRASHED'));
+
+try {
+ await page.goto('http://localhost:3000/home-v2', { waitUntil: 'domcontentloaded', timeout: 15000 });
+ console.log('NAV: ok');
+ await page.waitForTimeout(2000);
+ console.log('AFTER WAIT');
+ const has = await page.evaluate(() => ({
+ tryme: !!document.getElementById('hv2-tryme'),
+ chips: !!document.getElementById('hv2-chips'),
+ bodyLen: document.body?.innerHTML.length || 0,
+ }));
+ console.log('STATE:', JSON.stringify(has));
+} catch (e) {
+ console.log('OUTER ERROR:', e.message);
+}
+
+await page.screenshot({ path: '/tmp/home-v2-debug.png' }).catch(() => {});
await browser.close();
diff --git a/scripts/screenshot-home-v2.mjs b/scripts/screenshot-home-v2.mjs
new file mode 100644
index 000000000..5830eb7dd
--- /dev/null
+++ b/scripts/screenshot-home-v2.mjs
@@ -0,0 +1,32 @@
+import { chromium } from 'playwright';
+
+const browser = await chromium.launch({
+ args: ['--disable-gpu', '--disable-webgl', '--disable-webgl2', '--no-sandbox'],
+});
+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+
+// Stub the heavy Three.js viewer and model-viewer so the page paints layout
+// without any WebGL (which crashes this Codespace's headless chromium).
+await ctx.addInitScript(() => {
+ class Stub {
+ constructor() { this._manifest = []; this.model = { position: { x: 0 }, traverse: () => {} }; }
+ async loadModel() { return this; }
+ async playClip() { return this; }
+ setOrbit() {} zoom() {}
+ }
+ Object.defineProperty(window, 'Act2Viewer', { configurable: true, get() { return Stub; }, set() {} });
+ try { customElements.define('model-viewer', class extends HTMLElement {}); } catch (_) {}
+});
+
+await ctx.route('**/ajax.googleapis.com/**', (r) => r.fulfill({ status: 204, body: '', contentType: 'application/javascript' }));
+await ctx.route('**/fluid-particles.js', (r) => r.fulfill({ status: 200, body: '', contentType: 'application/javascript' }));
+await ctx.route('**/src/home-act2-viewer.js', (r) => r.fulfill({ status: 200, body: '', contentType: 'application/javascript' }));
+
+const page = await ctx.newPage();
+await page.goto('http://localhost:3000/home-v2', { waitUntil: 'domcontentloaded' });
+await page.waitForTimeout(1200);
+
+await page.screenshot({ path: '/tmp/home-v2-hero.png', fullPage: false });
+console.log('wrote /tmp/home-v2-hero.png');
+
+await browser.close();
diff --git a/scripts/verify-home-v2.mjs b/scripts/verify-home-v2.mjs
index 3b7188b4e..47b6691cd 100644
--- a/scripts/verify-home-v2.mjs
+++ b/scripts/verify-home-v2.mjs
@@ -1,53 +1,167 @@
import { chromium } from 'playwright';
-const browser = await chromium.launch();
-const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
+/**
+ * Verifies the v2 hero markup, click wiring, and DOM state without booting any
+ * real WebGL contexts. The hosted headless chromium in this Codespace cannot
+ * sustain multiple Three.js + model-viewer canvases on this page (GPU stall →
+ * page crash). The actual rendering is exercised by users in real browsers;
+ * here we just confirm the interactive surface behaves correctly:
+ *
+ * - chip strip + TRY ME badge are in the DOM at the right spot
+ * - clicking a chip dispatches to viewer.playClip(name)
+ * - clicking dismisses the TRY ME badge
+ * - the click counter increments on every real interaction
+ *
+ * We do this by replacing window.Act2Viewer with a recording stub injected
+ * before the page scripts run.
+ */
+
+const browser = await chromium.launch({
+ args: ['--disable-gpu', '--disable-webgl', '--disable-webgl2', '--no-sandbox'],
+});
+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+
+// Stub Act2Viewer + neutralize model-viewer before any page script runs.
+await ctx.addInitScript(() => {
+ window.__playedClips = [];
+ window.__viewerLoads = [];
+ class StubViewer {
+ constructor(canvas) {
+ this.canvas = canvas;
+ this._manifest = [
+ { name: 'idle', loop: true },
+ { name: 'dance', loop: true },
+ { name: 'wave', loop: false },
+ { name: 'capoeira', loop: true },
+ { name: 'jump', loop: false },
+ { name: 'thriller', loop: false },
+ { name: 'falling', loop: false },
+ { name: 'pray', loop: false },
+ ];
+ this.currentAction = { getClip: () => ({ duration: 0.05 }) };
+ this.mixer = { stopAllAction: () => {} };
+ this.model = { position: { x: 0 }, traverse: () => {} };
+ queueMicrotask(() => {
+ if (typeof this.onClipsReady === 'function') {
+ this.onClipsReady(this._manifest);
+ }
+ });
+ }
+ async loadModel(url) { window.__viewerLoads.push(url); return this; }
+ async playClip(name) { window.__playedClips.push(name); return this; }
+ setOrbit() {}
+ zoom() {}
+ }
+ Object.defineProperty(window, 'Act2Viewer', {
+ configurable: true,
+ get() { return StubViewer; },
+ set() { /* swallow the real module's assignment */ },
+ });
+ // Stub the model-viewer custom element so the depth-3 ghost canvas doesn't
+ // fire a real WebGL context.
+ try {
+ customElements.define('model-viewer', class extends HTMLElement {});
+ } catch (_) {}
+});
+
+// Block the third-party model-viewer module bundle entirely — even with a
+// stubbed custom element it loads a heavy Three.js + draco worker that
+// crashes the headless GPU. Also stub the heavy fluid-particles canvas.
+await ctx.route('**/ajax.googleapis.com/**', (route) => route.fulfill({ status: 204, body: '', contentType: 'application/javascript' }));
+await ctx.route('**/fluid-particles.js', (route) => route.fulfill({ status: 200, body: '/* stubbed */', contentType: 'application/javascript' }));
+await ctx.route('**/src/home-act2-viewer.js', (route) => route.fulfill({
+ status: 200,
+ contentType: 'application/javascript',
+ body: '/* stubbed — Act2Viewer is provided by addInitScript before this loads */',
+}));
+
+const page = await ctx.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
page.on('console', (msg) => {
if (msg.type() === 'error') errors.push(`console.error: ${msg.text()}`);
});
+page.on('framenavigated', (f) => {
+ if (f === page.mainFrame()) console.log('NAV →', f.url());
+});
await page.goto('http://localhost:3000/home-v2', { waitUntil: 'domcontentloaded' });
-await page.locator('#hv2-chips .hv2-chip[data-anim="dance"]').waitFor({ state: 'attached', timeout: 6000 });
-await page.locator('#hv2-tryme').waitFor({ state: 'attached', timeout: 6000 });
+await page.locator('#hv2-chips .hv2-chip[data-anim="dance"]').waitFor({ state: 'attached', timeout: 8000 });
+await page.locator('#hv2-tryme').waitFor({ state: 'attached', timeout: 8000 });
-// Wait for the viewer to actually load the model + animations.
-// Act2Viewer plays "falling" on first load; once viewer.currentAction is set we can poke it.
+// Let the inline hero-avatar IIFE attach its handlers (it polls every 60ms for
+// window.Act2Viewer, then loads + plays "falling" before wiring clicks).
await page.waitForFunction(
- () => {
- const c = document.getElementById('hero-avatar');
- return c && parseFloat(getComputedStyle(c).opacity) > 0.5;
- },
- { timeout: 20000 },
+ () => Array.isArray(window.__viewerLoads) && window.__viewerLoads.length > 0,
+ { timeout: 8000 },
);
+// One more tick so the post-loadModel `then` runs and the click handler binds.
+await page.waitForTimeout(400);
const beforeCount = await page.locator('#hv2-counter-num').innerText();
const trymeHiddenBefore = await page.locator('#hv2-tryme').evaluate((el) => el.classList.contains('is-hidden'));
-await page.click('.hv2-chip[data-anim="dance"]');
-await page.waitForTimeout(800);
+await page.locator('.hv2-chip[data-anim="dance"]').click();
+await page.waitForTimeout(100);
+const afterClipsDance = await page.evaluate(() => window.__playedClips.slice());
const afterCount = await page.locator('#hv2-counter-num').innerText();
const trymeHiddenAfter = await page.locator('#hv2-tryme').evaluate((el) => el.classList.contains('is-hidden'));
const danceActive = await page.locator('.hv2-chip[data-anim="dance"]').evaluate((el) => el.dataset.active === 'true');
-await page.click('.hv2-chip[data-anim="wave"]');
-await page.waitForTimeout(600);
+await page.locator('.hv2-chip[data-anim="wave"]').click();
+await page.waitForTimeout(100);
+const afterClipsWave = await page.evaluate(() => window.__playedClips.slice());
const after2Count = await page.locator('#hv2-counter-num').innerText();
-await page.screenshot({ path: '/tmp/home-v2-hero.png', fullPage: false });
+await page.locator('.hv2-chip[data-anim="__random"]').click();
+await page.waitForTimeout(100);
+const afterClipsRandom = await page.evaluate(() => window.__playedClips.slice());
+const after3Count = await page.locator('#hv2-counter-num').innerText();
-console.log(JSON.stringify({
+const result = {
+ heroLoad: await page.evaluate(() => window.__viewerLoads[0] || null),
beforeCount,
afterCount,
after2Count,
+ after3Count,
trymeHiddenBefore,
trymeHiddenAfter,
danceActive,
+ clipsAfterDance: afterClipsDance,
+ clipsAfterWave: afterClipsWave,
+ clipsAfterRandom: afterClipsRandom,
errors,
-}, null, 2));
+};
+
+// Pass/fail assertions
+const failures = [];
+if (result.heroLoad !== '/avatars/cz.glb') failures.push(`expected hero to loadModel('/avatars/cz.glb'), got ${result.heroLoad}`);
+if (result.beforeCount !== '0') failures.push(`counter should start at 0, was ${result.beforeCount}`);
+if (result.afterCount !== '1') failures.push(`counter after 1 click should be 1, was ${result.afterCount}`);
+if (result.after2Count !== '2') failures.push(`counter after 2 clicks should be 2, was ${result.after2Count}`);
+if (result.after3Count !== '3') failures.push(`counter after 3 clicks should be 3, was ${result.after3Count}`);
+if (result.trymeHiddenBefore) failures.push('tryme should be visible on first load');
+if (!result.trymeHiddenAfter) failures.push('tryme should be hidden after first click');
+if (!result.danceActive) failures.push('dance chip should be data-active=true after click');
+if (!result.clipsAfterDance.includes('dance')) failures.push(`expected 'dance' clip to play, got ${JSON.stringify(result.clipsAfterDance)}`);
+if (!result.clipsAfterWave.includes('wave')) failures.push(`expected 'wave' clip to play, got ${JSON.stringify(result.clipsAfterWave)}`);
+if (result.clipsAfterRandom.length <= result.clipsAfterWave.length) failures.push('random chip did not trigger a new clip');
+// Real errors only — ignore the GL driver perf warnings that aren't errors anyway.
+const realErrors = result.errors.filter((e) => !/GL Driver|GL_CLOSE_PATH_NV|model-viewer/.test(e));
+if (realErrors.length) failures.push(`console errors: ${realErrors.join(' | ')}`);
+
+await page.screenshot({ path: '/tmp/home-v2-hero.png', fullPage: false });
+
+console.log(JSON.stringify(result, null, 2));
+if (failures.length) {
+ console.error('\nFAILURES:');
+ failures.forEach((f) => console.error(' -', f));
+ await browser.close();
+ process.exit(1);
+}
+console.log('\nOK: hero v2 chips + tryme + counter wiring verified.');
await browser.close();
diff --git a/src/attach-avatar-to-agent.js b/src/attach-avatar-to-agent.js
new file mode 100644
index 000000000..3015f2b53
--- /dev/null
+++ b/src/attach-avatar-to-agent.js
@@ -0,0 +1,41 @@
+import { apiFetch } from './account.js';
+
+/**
+ * Associates an avatar with the caller's default agent. The /api/agents POST
+ * endpoint doesn't accept `avatar_id`, so we get-or-create via /me and then
+ * PUT to attach. Returns the updated agent record.
+ *
+ * Shared by /create and /create/review — kept in its own module so neither
+ * page's top-level boot() runs when the other imports it.
+ *
+ * @param {string} avatarId
+ * @param {string} [name] - Default agent name to use when no agent exists yet.
+ * @returns {Promise<object>}
+ */
+export async function attachAvatarToAgent(avatarId, name) {
+ const meRes = await apiFetch('/api/agents/me');
+ const meData = await meRes.json();
+ if (!meRes.ok) throw new Error(meData.error_description || 'Failed to load agent.');
+
+ let agent = meData.agent;
+ if (!agent) {
+ const createRes = await apiFetch('/api/agents', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: name || 'My Agent' }),
+ });
+ const createData = await createRes.json();
+ if (!createRes.ok)
+ throw new Error(createData.error_description || 'Failed to create agent.');
+ agent = createData.agent;
+ }
+
+ const putRes = await apiFetch('/api/agents/' + agent.id, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ avatar_id: avatarId }),
+ });
+ const putData = await putRes.json();
+ if (!putRes.ok) throw new Error(putData.error_description || 'Failed to attach avatar.');
+ return putData.agent;
+}
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index 88bc70437..7450f3677 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -6,6 +6,13 @@
* /api/avatars/:id with the resulting appearance JSON and the server bakes a
* canonical GLB (see api/_lib/bake.js).
*
+ * UX model — mirrors Ready Player Me's wardrobe:
+ * • Hover a tile → that item is applied to the 3D stage immediately (preview).
+ * • Mouseleave → revert to the committed state.
+ * • Click → commit. Stays applied. Chip appears in the chip bar.
+ * • Chip × → quick-remove without hunting through tabs.
+ * • Search box → filters the active tab's tiles by name.
+ *
* Architecture mirrors avatar-page.js — same look-and-feel, owner-gated by the
* presence of `avatar.owner_id` in the API response (the avatars endpoint
* strips owner_id for non-owners via stripOwnerFor).
@@ -35,13 +42,36 @@ const esc = (s) =>
let avatar = null;
let presets = []; // from /accessories/presets.json
+let presetsById = new Map();
let scene = null;
let accessoryManager = null;
// Appearance state — `current` reflects what the server has, `working` is what
-// the UI is showing live. We're dirty when they differ.
+// the UI has committed (locally) and will save. We're dirty when they differ.
+// `previewedId` is what's *temporarily* applied on hover, never persisted.
let currentAppearance = null;
let workingAppearance = { outfit: null, accessories: [], morphs: {} };
+let previewedId = null;
+
+// Monotonic token guards async preset loads from out-of-order arrivals when
+// the user hover-skims many tiles. Only the latest hover applies its result.
+let previewToken = 0;
+
+// Serializes every accessoryManager mutation so two GLB loads can't race for
+// the same single-slot kind (the manager's slot-clear is synchronous at call
+// entry; without serialization, two in-flight loads can both attach). Commits
+// run unconditionally; hovers/leaves token-skip if they were superseded by the
+// time they reach the head of the chain.
+let opQueue = Promise.resolve();
+function queueOp(fn) {
+ const next = opQueue.then(fn).catch((err) => {
+ console.warn('[avatar-edit] queued op failed:', err);
+ });
+ opQueue = next;
+ return next;
+}
+
+let searchQuery = '';
// Tab definitions: which preset kind goes on which tab.
const TABS = [
@@ -56,6 +86,12 @@ const KIND_EMOJI = {
glasses: '🕶️',
earrings: '💎',
};
+const KIND_LABEL = {
+ outfit: 'Outfit',
+ hat: 'Hat',
+ glasses: 'Glasses',
+ earrings: 'Earrings',
+};
let activeTab = 'outfit';
// ── Init ───────────────────────────────────────────────────────────────
@@ -87,31 +123,45 @@ async function init() {
currentAppearance = normalizeAppearance(avatar.appearance);
workingAppearance = clone(currentAppearance);
+ // Boot the 3D stage in parallel with the presets fetch. The wardrobe panel
+ // renders as soon as presets arrive so the user can browse while the GLB
+ // streams in. Hover/click interactions gate on accessoryManager being
+ // ready — until then they set a "loading" status.
+ const scenePromise = bootScene();
+
presets = await fetchPresets();
+ presetsById = new Map(presets.map((p) => [p.id, p]));
+
+ renderTabs();
+ renderChips();
+ renderActivePanel();
+ bindHeader();
- // 3D preview — reuse TalkScene's renderer; we don't need the mouth target
- // here, just the loaded scene + auto-frame.
+ await scenePromise;
+}
+
+async function bootScene() {
+ // IMPORTANT: load the BASE GLB, not the baked one. The customizer applies
+ // appearance on the client; loading the already-baked URL would stack
+ // outfits.
scene = new TalkScene();
try {
- // IMPORTANT: load the BASE GLB, not the baked one. The customizer
- // applies appearance on the client; loading the already-baked URL
- // would stack outfits.
- await scene.mount({ container: $('ae-stage'), glbUrl: avatar.base_model_url || avatar.model_url });
- $('ae-loading').remove();
+ await scene.mount({
+ container: $('ae-stage'),
+ glbUrl: avatar.base_model_url || avatar.model_url,
+ });
+ $('ae-loading')?.remove();
+ accessoryManager = new AccessoryManager({
+ content: scene.root,
+ invalidate: () => {},
+ });
+ await accessoryManager.hydrateFromAppearance(currentAppearance);
} catch (err) {
- $('ae-loading').textContent = `Could not load GLB: ${err.message}`;
- return;
+ const loadingEl = $('ae-loading');
+ if (loadingEl) loadingEl.textContent = `Could not load GLB: ${err.message}`;
+ // The tabs still rendered — user can browse the catalog, just no live
+ // 3D preview. Save is still gated on dirty state below.
}
-
- accessoryManager = new AccessoryManager({
- content: scene.root,
- invalidate: () => {},
- });
- await accessoryManager.hydrateFromAppearance(currentAppearance);
-
- renderTabs();
- renderActivePanel();
- bindHeader();
}
// ── API ────────────────────────────────────────────────────────────────
@@ -183,6 +233,7 @@ function renderTabs() {
el.querySelectorAll('.ae-tab').forEach((btn) => {
btn.addEventListener('click', () => {
activeTab = btn.dataset.tab;
+ searchQuery = '';
el.querySelectorAll('.ae-tab').forEach((b) => b.classList.toggle('active', b === btn));
renderActivePanel();
});
@@ -192,31 +243,128 @@ function renderTabs() {
function renderActivePanel() {
const tab = TABS.find((t) => t.id === activeTab);
const panel = $('ae-panel');
- const items = presets.filter((p) => tab.kinds.includes(p.kind));
-
- // Render a "None" tile first so users can clear the current pick.
- const tiles = [
- `<button class="ae-tile ae-tile-none${tileSelected(tab, null) ? ' selected' : ''}"
- type="button" data-id="" data-kind="${tab.id}">
- <div class="ae-tile-preview" aria-hidden="true">∅</div>
- <div class="ae-tile-name">None</div>
- <div class="ae-tile-kind">remove</div>
- </button>`,
- ...items.map(
- (p) => `
- <button class="ae-tile${tileSelected(tab, p.id) ? ' selected' : ''}"
- type="button" data-id="${esc(p.id)}" data-kind="${tab.id}">
- <div class="ae-tile-preview" aria-hidden="true">${KIND_EMOJI[p.kind] || '◇'}</div>
- <div class="ae-tile-name">${esc(p.name)}</div>
- <div class="ae-tile-kind">${esc(p.kind)}</div>
- </button>
- `,
- ),
- ];
-
- panel.innerHTML = `<div class="ae-grid">${tiles.join('')}</div>`;
+ const q = searchQuery.trim().toLowerCase();
+ const items = presets.filter(
+ (p) => tab.kinds.includes(p.kind) && (!q || p.name.toLowerCase().includes(q)),
+ );
+
+ const searchHtml = `
+ <div class="ae-search-wrap">
+ <input class="ae-search" id="ae-search" type="search"
+ placeholder="Search ${esc(tab.label.toLowerCase())}…"
+ value="${esc(searchQuery)}" autocomplete="off" />
+ </div>`;
+
+ if (items.length === 0 && q) {
+ panel.innerHTML = searchHtml + `<div class="ae-empty">No matches for “${esc(searchQuery)}”.</div>`;
+ bindSearch();
+ return;
+ }
+
+ // Render a "None" tile first (only when no search is active) so users can
+ // clear the current pick without scrolling. Hidden during search to avoid
+ // the confusing "None" matching every empty query.
+ const tiles = [];
+ if (!q) {
+ tiles.push(`
+ <button class="ae-tile ae-tile-none${tileSelected(tab, null) ? ' selected' : ''}"
+ type="button" data-id="" data-kind="${tab.id}">
+ <div class="ae-tile-preview" aria-hidden="true">∅</div>
+ <div class="ae-tile-name">None</div>
+ <div class="ae-tile-kind">remove</div>
+ </button>
+ `);
+ }
+ for (const p of items) {
+ const previewing = previewedId === p.id;
+ const selected = tileSelected(tab, p.id);
+ tiles.push(`
+ <button class="ae-tile${selected ? ' selected' : ''}${previewing ? ' previewing' : ''}"
+ type="button" data-id="${esc(p.id)}" data-kind="${tab.id}">
+ <div class="ae-tile-preview" aria-hidden="true">
+ ${tilePreviewMarkup(p)}
+ </div>
+ <div class="ae-tile-name">${esc(p.name)}</div>
+ <div class="ae-tile-kind">${esc(KIND_LABEL[p.kind] || p.kind)}</div>
+ </button>
+ `);
+ }
+
+ panel.innerHTML = searchHtml + `<div class="ae-grid">${tiles.join('')}</div>`;
+ bindSearch();
+ bindTiles(panel, tab);
+}
+
+function tilePreviewMarkup(preset) {
+ const emoji = KIND_EMOJI[preset.kind] || '◇';
+ if (!preset.thumbnail) return emoji;
+ // Render the emoji underneath as a graceful fallback. The <img> sits on
+ // top when it loads; if the file 404s, onerror strips the <img> and the
+ // emoji is what the user sees. Avoids broken-image icons while the
+ // thumbnail pipeline catches up to the presets.json declarations.
+ return `
+ <span style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;">${emoji}</span>
+ <img src="${esc(preset.thumbnail)}" alt="" loading="lazy"
+ style="position:absolute;inset:0;"
+ onerror="this.remove()" />
+ `;
+}
+
+function bindSearch() {
+ const input = $('ae-search');
+ if (!input) return;
+ input.addEventListener('input', (e) => {
+ searchQuery = e.target.value;
+ renderActivePanel();
+ // Re-focus to keep typing fluid after the re-render.
+ const next = $('ae-search');
+ if (next) {
+ next.focus();
+ next.setSelectionRange(searchQuery.length, searchQuery.length);
+ }
+ });
+}
+
+function bindTiles(panel, tab) {
panel.querySelectorAll('.ae-tile').forEach((btn) => {
- btn.addEventListener('click', () => onTileClick(tab, btn.dataset.id));
+ const presetId = btn.dataset.id;
+ btn.addEventListener('click', () => onTileClick(tab, presetId));
+ // Hover-to-try-on lives only on real items (not the "None" tile —
+ // removing on hover and re-applying on leave would just churn for no
+ // information value).
+ if (!presetId) return;
+ btn.addEventListener('mouseenter', () => onTileHover(tab, presetId));
+ btn.addEventListener('mouseleave', () => onTileLeave());
+ // Touch / keyboard analogs: focus previews, blur reverts.
+ btn.addEventListener('focus', () => onTileHover(tab, presetId));
+ btn.addEventListener('blur', () => onTileLeave());
+ });
+}
+
+function renderChips() {
+ const el = $('ae-chips');
+ const picks = [];
+ if (workingAppearance.outfit) picks.push(workingAppearance.outfit);
+ for (const id of workingAppearance.accessories) picks.push(id);
+
+ el.innerHTML = picks
+ .map((id) => {
+ const p = presetsById.get(id);
+ if (!p) return '';
+ return `
+ <span class="ae-chip" data-id="${esc(id)}">
+ <span class="ae-chip-kind">${esc(KIND_LABEL[p.kind] || p.kind)}</span>
+ <span>${esc(p.name)}</span>
+ <button type="button" aria-label="Remove ${esc(p.name)}" data-remove="${esc(id)}">×</button>
+ </span>
+ `;
+ })
+ .join('');
+
+ el.querySelectorAll('button[data-remove]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ await removeCommitted(btn.dataset.remove);
+ });
});
}
@@ -228,65 +376,212 @@ function tileSelected(tab, presetId) {
}
// Accessory kinds (hat/glasses/earrings) live in the accessories array.
const matching = workingAppearance.accessories.filter((id) => {
- const preset = presets.find((p) => p.id === id);
+ const preset = presetsById.get(id);
return preset && tab.kinds.includes(preset.kind);
});
if (!presetId) return matching.length === 0;
return matching.includes(presetId);
}
+// ── Hover preview ──────────────────────────────────────────────────────
+
+function onTileHover(tab, presetId) {
+ // Already committed in this slot — hovering is a no-op (it's literally what
+ // the stage is showing already).
+ if (isCommitted(presetId)) {
+ previewedId = null;
+ return;
+ }
+ if (previewedId === presetId) return;
+
+ previewedId = presetId;
+ highlightPreviewingTile(presetId);
+
+ const myToken = ++previewToken;
+ const preset = presetsById.get(presetId);
+ if (!preset) return;
+
+ // Before the GLB streams in, we can't render a live preview. Show a hint
+ // in the status bar so the hover isn't silently inert.
+ if (!accessoryManager) {
+ setStatus('', `${preset.name} · waiting for avatar to load…`);
+ return;
+ }
+
+ queueOp(async () => {
+ // If another hover/leave/click bumped the token before our turn, skip.
+ if (myToken !== previewToken) return;
+ // For single-slot kinds the manager boots whatever's currently in that
+ // slot — exactly the preview behavior we want. Earrings layer on top.
+ await accessoryManager.applyPreset(preset);
+ if (myToken === previewToken) {
+ setStatus('', `Previewing ${preset.name} · click to keep`);
+ }
+ });
+}
+
+function onTileLeave() {
+ if (!previewedId) return;
+ const leavingId = previewedId;
+ previewedId = null;
+ const myToken = ++previewToken;
+ highlightPreviewingTile(null);
+
+ if (isCommitted(leavingId)) {
+ setStatusForDirtyState();
+ return;
+ }
+
+ const preset = presetsById.get(leavingId);
+ if (!preset) {
+ setStatusForDirtyState();
+ return;
+ }
+
+ queueOp(async () => {
+ if (myToken !== previewToken) return;
+ if (!accessoryManager) {
+ setStatusForDirtyState();
+ return;
+ }
+ // Take the preview off.
+ accessoryManager.removePreset(leavingId);
+ // If we displaced a committed single-slot item to show the preview, put
+ // it back. (Earrings are layered, not displaced, so nothing to restore.)
+ if (preset.kind !== 'earrings') {
+ const committedInSlot = committedIdForKind(preset.kind);
+ if (committedInSlot && committedInSlot !== leavingId) {
+ const restore = presetsById.get(committedInSlot);
+ if (restore) await accessoryManager.applyPreset(restore);
+ }
+ }
+ if (myToken === previewToken) setStatusForDirtyState();
+ });
+}
+
+function highlightPreviewingTile(id) {
+ document.querySelectorAll('.ae-tile.previewing').forEach((el) => el.classList.remove('previewing'));
+ if (!id) return;
+ const el = document.querySelector(`.ae-tile[data-id="${cssEscape(id)}"]`);
+ el?.classList.add('previewing');
+}
+
+function cssEscape(s) {
+ return String(s).replace(/["\\]/g, '\\$&');
+}
+
+function isCommitted(presetId) {
+ if (!presetId) return false;
+ return (
+ workingAppearance.outfit === presetId ||
+ workingAppearance.accessories.includes(presetId)
+ );
+}
+
+function committedIdForKind(kind) {
+ if (kind === 'outfit') return workingAppearance.outfit || null;
+ for (const id of workingAppearance.accessories) {
+ const p = presetsById.get(id);
+ if (p && p.kind === kind) return id;
+ }
+ return null;
+}
+
+// ── Commit / remove ────────────────────────────────────────────────────
+
async function onTileClick(tab, presetId) {
- if (tab.kinds.includes('outfit')) {
- await applyOutfit(presetId || null);
+ // A click commits the current hover state. The item may already be on the
+ // stage from a hover, or we may be clicking without hovering (touch /
+ // keyboard). Either way, route through the queue and run unconditionally:
+ // commits should never be token-skipped.
+ previewedId = null;
+ previewToken++;
+
+ await queueOp(async () => {
+ if (tab.kinds.includes('outfit')) {
+ await applyOutfit(presetId || null);
+ } else {
+ await applyAccessory(tab, presetId || null);
+ }
+ });
+ renderActivePanel();
+ renderChips();
+ updateDirtyState();
+}
+
+async function removeCommitted(id) {
+ const preset = presetsById.get(id);
+ if (!preset) return;
+ previewedId = null;
+ previewToken++;
+ await queueOp(async () => {
+ accessoryManager?.removePreset(id);
+ });
+ if (workingAppearance.outfit === id) {
+ workingAppearance.outfit = null;
} else {
- await applyAccessory(tab, presetId || null);
+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
}
renderActivePanel();
+ renderChips();
updateDirtyState();
}
async function applyOutfit(presetId) {
- // Remove the previous outfit from the live preview first.
- if (workingAppearance.outfit) {
- accessoryManager.removePreset(workingAppearance.outfit);
+ // Manager's single-slot logic handles removal of the previous outfit when
+ // applyPreset() is called for a new one. Only do an explicit remove when
+ // the new pick is null (the "None" tile).
+ if (!presetId) {
+ if (workingAppearance.outfit) accessoryManager?.removePreset(workingAppearance.outfit);
+ workingAppearance.outfit = null;
+ return;
}
+ const preset = presetsById.get(presetId);
+ if (!preset) return;
+ if (accessoryManager) await accessoryManager.applyPreset(preset);
workingAppearance.outfit = presetId;
- if (presetId) {
- const preset = presets.find((p) => p.id === presetId);
- if (preset) await accessoryManager.applyPreset(preset);
- }
}
async function applyAccessory(tab, presetId) {
- // For single-slot kinds (hat, glasses) remove whatever's currently in
- // that slot before applying. Earrings allow multiples (both ears).
- const wasInSlot = workingAppearance.accessories.filter((id) => {
- const p = presets.find((x) => x.id === id);
+ // Earrings (and any future non-single kinds) allow multiples — toggle on
+ // repeat-click. Single-slot kinds (hat, glasses) just replace.
+ const inSlot = workingAppearance.accessories.filter((id) => {
+ const p = presetsById.get(id);
return p && tab.kinds.includes(p.kind);
});
- if (tab.single) {
- for (const id of wasInSlot) {
- accessoryManager.removePreset(id);
+ if (!presetId) {
+ for (const id of inSlot) {
+ accessoryManager?.removePreset(id);
workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
}
+ return;
}
- if (presetId) {
- // Toggle behaviour for non-single kinds — clicking an already-applied
- // preset removes it.
- if (!tab.single && wasInSlot.includes(presetId)) {
- accessoryManager.removePreset(presetId);
- workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== presetId);
- } else {
- const preset = presets.find((p) => p.id === presetId);
- if (preset) {
- await accessoryManager.applyPreset(preset);
- if (!workingAppearance.accessories.includes(presetId)) {
- workingAppearance.accessories.push(presetId);
- }
- }
+ if (tab.single) {
+ for (const id of inSlot) {
+ if (id === presetId) continue; // about to re-apply same id — manager dedupes
+ accessoryManager?.removePreset(id);
+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
+ }
+ const preset = presetsById.get(presetId);
+ if (preset && accessoryManager) await accessoryManager.applyPreset(preset);
+ if (!workingAppearance.accessories.includes(presetId)) {
+ workingAppearance.accessories.push(presetId);
}
+ return;
+ }
+
+ // Non-single (earrings): clicking an already-applied preset removes it.
+ if (inSlot.includes(presetId)) {
+ accessoryManager?.removePreset(presetId);
+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== presetId);
+ return;
+ }
+ const preset = presetsById.get(presetId);
+ if (preset && accessoryManager) await accessoryManager.applyPreset(preset);
+ if (!workingAppearance.accessories.includes(presetId)) {
+ workingAppearance.accessories.push(presetId);
}
}
@@ -298,6 +593,8 @@ function bindHeader() {
$('ae-reset').disabled = true;
try {
await saveAppearance();
+ renderChips();
+ renderActivePanel();
} catch (err) {
setStatus('err', err.message);
} finally {
@@ -306,13 +603,20 @@ function bindHeader() {
});
$('ae-reset').addEventListener('click', async () => {
// Roll the live preview back to the saved appearance.
- const wasIds = [
- workingAppearance.outfit,
- ...workingAppearance.accessories,
- ].filter(Boolean);
- for (const id of wasIds) accessoryManager.removePreset(id);
- workingAppearance = clone(currentAppearance);
- await accessoryManager.hydrateFromAppearance(workingAppearance);
+ previewedId = null;
+ previewToken++;
+ await queueOp(async () => {
+ const wasIds = [
+ workingAppearance.outfit,
+ ...workingAppearance.accessories,
+ ].filter(Boolean);
+ if (accessoryManager) {
+ for (const id of wasIds) accessoryManager.removePreset(id);
+ }
+ workingAppearance = clone(currentAppearance);
+ if (accessoryManager) await accessoryManager.hydrateFromAppearance(workingAppearance);
+ });
+ renderChips();
renderActivePanel();
updateDirtyState();
setStatus('', 'Reverted to last saved.');
@@ -323,8 +627,13 @@ function updateDirtyState() {
const dirty = !appearanceEquals(workingAppearance, currentAppearance);
$('ae-save').disabled = !dirty;
$('ae-reset').disabled = !dirty;
+ setStatusForDirtyState();
+}
+
+function setStatusForDirtyState() {
+ const dirty = !appearanceEquals(workingAppearance, currentAppearance);
if (!dirty) {
- setStatus('', 'No unsaved changes.');
+ setStatus('', 'Hover any item to try it on. Click to keep.');
} else {
setStatus('', 'Unsaved changes.');
}
diff --git a/src/create-review.js b/src/create-review.js
new file mode 100644
index 000000000..6a7d03c22
--- /dev/null
+++ b/src/create-review.js
@@ -0,0 +1,239 @@
+/**
+ * /create/review — preview the in-progress avatar before it touches the server.
+ *
+ * Flow:
+ * 1. Read the staged blob from IndexedDB via guest-avatar.js.
+ * 2. Render it in the page's <model-viewer> from an object URL.
+ * 3. "Save to my account":
+ * - If unauthed: redirect to /login?next=/create/review with a sentinel
+ * flag so we auto-resume the save when the user returns.
+ * - If authed: presign + upload + attach to default agent, then go to /app.
+ * 4. "Start over": clear the staged record and bounce back to /create.
+ * 5. On post-login resume, the sentinel triggers the save automatically.
+ */
+
+import { saveRemoteGlbToAccount } from './account.js';
+import { attachAvatarToAgent } from './attach-avatar-to-agent.js';
+import { load as loadGuest, clear as clearGuest } from './guest-avatar.js';
+
+const RESUME_KEY = '3dagent:guest-avatar-resume';
+const $ = (sel) => document.querySelector(sel);
+
+let staged = /** @type {Awaited<ReturnType<typeof loadGuest>>} */ (null);
+let objectUrl = /** @type {string | null} */ (null);
+
+async function boot() {
+ staged = await loadGuest();
+ if (!staged) {
+ $('#content').hidden = true;
+ $('#empty-card').hidden = false;
+ return;
+ }
+
+ $('#content').hidden = false;
+ $('#empty-card').hidden = true;
+
+ renderPreview(staged);
+ wireControls();
+
+ // Auth state is resolved async via /api/auth/me from the page's inline
+ // script. If it's already resolved (cache hit), apply now; otherwise wait
+ // for the dispatched event.
+ if (window.__authed === null) {
+ document.addEventListener('three-ws:auth-resolved', applyAuthState, { once: true });
+ } else {
+ applyAuthState({ detail: { authed: window.__authed } });
+ }
+}
+
+function renderPreview(record) {
+ const mv = $('#mv');
+ objectUrl = URL.createObjectURL(record.blob);
+ mv.src = objectUrl;
+
+ $('#avatar-name').textContent = record.name;
+ $('#f-name').value = record.name;
+ $('#tag-source').textContent = record.meta?.source || record.meta?.provider || 'glb';
+ $('#tag-size').textContent =
+ record.size > 0 ? `${Math.round(record.size / 1024)} KB` : '— KB';
+
+ mv.addEventListener(
+ 'load',
+ () => {
+ $('#viewer-loading').hidden = true;
+ mv.style.visibility = '';
+ },
+ { once: true },
+ );
+ mv.addEventListener(
+ 'error',
+ () => {
+ $('#viewer-loading').innerHTML =
+ '<span style="color:#ffb3b3">Couldn\'t render this model.</span>';
+ },
+ { once: true },
+ );
+}
+
+function wireControls() {
+ const saveBtn = $('#save-btn');
+ const startOverBtn = $('#start-over-btn');
+ const nameInput = $('#f-name');
+
+ nameInput.addEventListener('input', () => {
+ const value = nameInput.value.trim();
+ $('#avatar-name').textContent = value || 'Your avatar';
+ });
+
+ saveBtn.addEventListener('click', () => onSave());
+ startOverBtn.addEventListener('click', () => onStartOver());
+}
+
+function applyAuthState({ detail }) {
+ const saveBtn = $('#save-btn');
+ const guestNote = $('#guest-note');
+ saveBtn.disabled = false;
+ if (detail.authed) {
+ saveBtn.textContent = 'Save to my account';
+ guestNote.hidden = true;
+ // Returning from a /login round-trip with the resume flag set — finish
+ // what the user started.
+ if (sessionStorage.getItem(RESUME_KEY) === '1') {
+ sessionStorage.removeItem(RESUME_KEY);
+ onSave({ auto: true });
+ }
+ } else {
+ saveBtn.textContent = 'Sign in to save';
+ guestNote.hidden = false;
+ }
+}
+
+async function onSave({ auto = false } = {}) {
+ if (!staged) return;
+ const saveBtn = $('#save-btn');
+ const startOverBtn = $('#start-over-btn');
+
+ if (window.__authed === false) {
+ // Stash a sentinel so the post-login round-trip auto-resumes the save.
+ sessionStorage.setItem(RESUME_KEY, '1');
+ const next = encodeURIComponent('/create/review');
+ window.location.href = `/login?next=${next}`;
+ return;
+ }
+
+ saveBtn.disabled = true;
+ startOverBtn.disabled = true;
+ showSaveOverlay('Saving your avatar…', 'Uploading to your account.');
+
+ try {
+ const name = $('#f-name').value.trim() || staged.name;
+ const meta = {
+ ...staged.meta,
+ name,
+ };
+ const avatar = await saveRemoteGlbToAccount(staged.blob, meta);
+ updateSaveOverlay('Preparing your agent…');
+ const agent = await attachAvatarToAgent(avatar.id, name);
+ updateSaveOverlay('Opening your avatar…');
+ await clearGuest();
+ releaseObjectUrl();
+ window.location.href = '/app?agent=' + agent.id;
+ } catch (err) {
+ hideSaveOverlay();
+ saveBtn.disabled = false;
+ startOverBtn.disabled = false;
+ console.error('[create-review] save failed', err);
+
+ if (err.code === 'not_signed_in') {
+ // Session expired between the cached auth hint and the actual save.
+ sessionStorage.setItem(RESUME_KEY, '1');
+ const next = encodeURIComponent('/create/review');
+ window.location.href = `/login?next=${next}`;
+ return;
+ }
+
+ if (err.data?.error === 'plan_limit_count') {
+ showStatus(
+ "You've reached your avatar limit. Delete an avatar first, then come back to save this one.",
+ 'error',
+ );
+ return;
+ }
+
+ showStatus(
+ auto
+ ? "Save couldn't finish automatically — try the button again."
+ : err.message || 'Save failed. Try again.',
+ 'error',
+ );
+ }
+}
+
+async function onStartOver() {
+ const ok = window.confirm('Discard this avatar and start over?');
+ if (!ok) return;
+ await clearGuest();
+ releaseObjectUrl();
+ window.location.href = '/create';
+}
+
+function releaseObjectUrl() {
+ if (objectUrl) {
+ URL.revokeObjectURL(objectUrl);
+ objectUrl = null;
+ }
+}
+
+function showSaveOverlay(label, sublabel) {
+ let el = document.getElementById('save-loading');
+ if (!el) {
+ el = document.createElement('div');
+ el.id = 'save-loading';
+ el.setAttribute('role', 'status');
+ el.setAttribute('aria-live', 'polite');
+ el.setAttribute('aria-busy', 'true');
+ el.innerHTML = `
+ <img src="/three.svg" alt="" />
+ <div class="label"></div>
+ <div class="sublabel"></div>
+ `;
+ document.body.appendChild(el);
+ document.documentElement.style.overflow = 'hidden';
+ document.body.style.overflow = 'hidden';
+ }
+ el.querySelector('.label').textContent = label;
+ el.querySelector('.sublabel').textContent = sublabel || '';
+}
+
+function updateSaveOverlay(label, sublabel) {
+ const el = document.getElementById('save-loading');
+ if (!el) return;
+ el.querySelector('.label').textContent = label;
+ if (sublabel !== undefined) el.querySelector('.sublabel').textContent = sublabel;
+}
+
+function hideSaveOverlay() {
+ const el = document.getElementById('save-loading');
+ if (!el) return;
+ el.remove();
+ document.documentElement.style.overflow = '';
+ document.body.style.overflow = '';
+}
+
+function showStatus(msg, type = 'info') {
+ const el = document.getElementById('status-toast');
+ el.textContent = msg;
+ el.className = 'status-toast ' + type;
+ el.hidden = false;
+ setTimeout(() => {
+ el.hidden = true;
+ }, 5000);
+}
+
+window.addEventListener('beforeunload', releaseObjectUrl);
+
+boot().catch((err) => {
+ console.error('[create-review] boot failed', err);
+ $('#content').hidden = true;
+ $('#empty-card').hidden = false;
+});
diff --git a/src/create.js b/src/create.js
index e681eac09..603f4628a 100644
--- a/src/create.js
+++ b/src/create.js
@@ -1,5 +1,6 @@
-import { apiFetch, saveRemoteGlbToAccount } from './account.js';
+import { apiFetch } from './account.js';
import { AvatarCreator } from './avatar-creator.js';
+import { stage as stageGuestAvatar } from './guest-avatar.js';
// GLB magic bytes: ASCII "glTF"
const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];
@@ -19,6 +20,20 @@ document.addEventListener('three-ws:arkit-report', (event) => {
);
});
+// The selfie pipeline (/create/selfie) hits a server-side reconstruction job
+// that requires auth + counts against plan quota — we keep that gate. The
+// default editor, Studio iframe and direct GLB upload all stay anonymous;
+// we stash the resulting blob in IndexedDB and let /create/review handle the
+// "sign in to save" step after the user has seen their avatar.
+function requireAuthForSelfie() {
+ if (window.__authed === false) {
+ const next = encodeURIComponent('/create/selfie');
+ window.location.replace(`/login?next=${next}`);
+ return false;
+ }
+ return true;
+}
+
async function boot() {
const creator = new AvatarCreator(document.body, (blob, meta = {}) => {
const provider = meta.provider || 'avaturn';
@@ -28,7 +43,7 @@ async function boot() {
// with the canonical provider stored in source_meta so server-side auto-link still triggers
const source = provider === 'avaturn' ? 'avaturn' : 'import';
const source_meta = { provider, ...(meta.sourceUrl ? { source_url: meta.sourceUrl } : {}) };
- return saveAndRedirect(blob, { source, source_meta });
+ return stageAndReview(blob, { source, source_meta, provider });
});
document.getElementById('back-btn')?.addEventListener('click', () => {
@@ -37,14 +52,12 @@ async function boot() {
});
wireCard('card-default-editor', async () => {
- if (await isAtAvatarLimit()) return;
+ if (window.__authed && (await isAtAvatarLimit())) return;
creator.openDefaultEditor();
});
wireCard('card-selfie', async () => {
+ if (!requireAuthForSelfie()) return;
if (await isAtAvatarLimit()) return;
- // Real 3-photo flow lives at /create/selfie. Captures via camera or
- // upload, submits to /api/avatars/reconstruct, polls the job, then
- // redirects to /avatars/<id> when the GLB has been materialized.
window.location.href = '/create/selfie';
});
wireCard('card-upload-glb', (e) => {
@@ -92,7 +105,7 @@ async function handleGlbFile(file) {
}
const name = file.name.replace(/\.glb$/i, '').trim() || 'My Avatar';
- await saveAndRedirect(file, { source: 'upload', name });
+ await stageAndReview(file, { source: 'upload', name });
}
async function isAtAvatarLimit() {
@@ -113,30 +126,22 @@ async function isAtAvatarLimit() {
return false;
}
-async function saveAndRedirect(blob, meta = {}) {
- showSaveOverlay('Saving your avatar…', 'This usually takes a few seconds.');
+// Stash the freshly generated GLB locally and send the user to /create/review,
+// where they preview the avatar before deciding whether to sign in and save.
+// Anonymous users get to see what they built before the auth wall; signed-in
+// users still go through the same review step so the flow is consistent.
+async function stageAndReview(blob, meta = {}) {
+ showSaveOverlay('Preparing preview…');
try {
- const avatar = await saveRemoteGlbToAccount(blob, meta);
- updateSaveOverlay('Preparing your agent…');
- const agent = await attachAvatarToAgent(avatar.id, meta.name);
- updateSaveOverlay('Opening your avatar…');
- window.location.href = '/app?agent=' + agent.id;
+ await stageGuestAvatar(blob, meta);
} catch (err) {
hideSaveOverlay();
- if (err.code === 'not_signed_in') {
- sessionStorage.setItem('login_redirect', '/create');
- window.location.replace('/login');
- return;
- }
- if (err.data?.error === 'plan_limit_count') {
- showStatus(
- "You've reached your avatar limit. Delete an avatar to create a new one.",
- 'error',
- );
- return;
- }
- if (!err.redirected) showStatus(err.message || 'Upload failed.', 'error');
+ console.error('[create] failed to stage guest avatar:', err);
+ showStatus('Could not save your avatar locally. Check browser storage settings.', 'error');
+ return;
}
+ updateSaveOverlay('Opening preview…');
+ window.location.href = '/create/review';
}
function showSaveOverlay(label, sublabel) {
@@ -176,36 +181,6 @@ function hideSaveOverlay() {
document.body.style.overflow = '';
}
-// Associates the uploaded avatar with the caller's default agent. POST /api/agents
-// doesn't accept avatar_id, so we get-or-create via /me and then PUT to attach.
-async function attachAvatarToAgent(avatarId, name) {
- const meRes = await apiFetch('/api/agents/me');
- const meData = await meRes.json();
- if (!meRes.ok) throw new Error(meData.error_description || 'Failed to load agent.');
-
- let agent = meData.agent;
- if (!agent) {
- const createRes = await apiFetch('/api/agents', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ name: name || 'My Agent' }),
- });
- const createData = await createRes.json();
- if (!createRes.ok)
- throw new Error(createData.error_description || 'Failed to create agent.');
- agent = createData.agent;
- }
-
- const putRes = await apiFetch('/api/agents/' + agent.id, {
- method: 'PUT',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ avatar_id: avatarId }),
- });
- const putData = await putRes.json();
- if (!putRes.ok) throw new Error(putData.error_description || 'Failed to attach avatar.');
- return putData.agent;
-}
-
function showStatus(msg, type = 'info') {
const el = document.getElementById('status-toast');
el.textContent = msg;
diff --git a/src/guest-avatar.js b/src/guest-avatar.js
new file mode 100644
index 000000000..2e3f465e3
--- /dev/null
+++ b/src/guest-avatar.js
@@ -0,0 +1,155 @@
+/**
+ * Guest avatar store — persists an in-progress avatar locally so users can
+ * finish the create flow without signing in first. The flow is:
+ *
+ * 1. /create produces a GLB Blob from the default editor / Studio / file upload.
+ * 2. We stage(blob, meta) into IndexedDB before navigating to /create/review.
+ * 3. /create/review reads it back, renders it, and on "Save" either uploads
+ * immediately (signed-in user) or sends the user through /login?next=/create/review
+ * and the page picks up where it left off after auth.
+ *
+ * Blobs go in IndexedDB (multi-MB GLBs would blow the localStorage quota).
+ * A short JSON metadata pointer lives in localStorage so we can detect a
+ * pending guest avatar even before the IDB connection opens — useful for the
+ * /login post-auth check.
+ */
+
+const DB_NAME = 'three-ws-guest';
+const STORE = 'avatars';
+const KEY = 'pending';
+const META_KEY = '3dagent:guest-avatar-meta';
+
+function openDb() {
+ return new Promise((resolve, reject) => {
+ const req = indexedDB.open(DB_NAME, 1);
+ req.onupgradeneeded = () => {
+ const db = req.result;
+ if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE);
+ };
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error || new Error('indexeddb open failed'));
+ });
+}
+
+async function tx(mode, fn) {
+ const db = await openDb();
+ try {
+ return await new Promise((resolve, reject) => {
+ const t = db.transaction(STORE, mode);
+ const store = t.objectStore(STORE);
+ let result;
+ Promise.resolve(fn(store))
+ .then((r) => {
+ result = r;
+ })
+ .catch(reject);
+ t.oncomplete = () => resolve(result);
+ t.onerror = () => reject(t.error || new Error('idb transaction failed'));
+ t.onabort = () => reject(t.error || new Error('idb transaction aborted'));
+ });
+ } finally {
+ db.close();
+ }
+}
+
+/**
+ * Stage a GLB Blob with provenance metadata. Replaces any previously staged
+ * avatar — the user can only have one pending guest avatar at a time.
+ *
+ * @param {Blob} blob - The GLB binary.
+ * @param {{
+ * source?: 'avaturn' | 'import' | 'upload' | 'three-ws-studio' | 'three-ws-selfie' | string,
+ * source_meta?: Record<string, unknown>,
+ * name?: string,
+ * provider?: string,
+ * sourceUrl?: string | null,
+ * }} [meta]
+ * @returns {Promise<{ id: string, size: number, createdAt: number }>}
+ */
+export async function stage(blob, meta = {}) {
+ if (!(blob instanceof Blob)) throw new TypeError('stage() requires a Blob');
+ const id = cryptoRandomId();
+ const size = blob.size;
+ const createdAt = Date.now();
+ const name = meta.name || `Avatar #${id.slice(0, 6)}`;
+
+ await tx('readwrite', (store) =>
+ new Promise((resolve, reject) => {
+ const req = store.put({ blob, meta, id, name, size, createdAt }, KEY);
+ req.onsuccess = () => resolve();
+ req.onerror = () => reject(req.error || new Error('idb put failed'));
+ }),
+ );
+
+ const pointer = { id, name, size, createdAt, source: meta.source || meta.provider || 'unknown' };
+ try {
+ localStorage.setItem(META_KEY, JSON.stringify(pointer));
+ } catch {
+ // quota or storage disabled — IDB is the source of truth, pointer is best-effort
+ }
+
+ return { id, size, createdAt };
+}
+
+/**
+ * Returns the staged avatar's metadata pointer, or null if nothing is staged.
+ * Cheap synchronous-ish check (reads localStorage; doesn't open IDB).
+ */
+export function peek() {
+ try {
+ const raw = localStorage.getItem(META_KEY);
+ if (!raw) return null;
+ const pointer = JSON.parse(raw);
+ if (!pointer || typeof pointer !== 'object') return null;
+ return pointer;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Returns the full staged record (blob + meta) or null if nothing is staged.
+ * @returns {Promise<{ blob: Blob, meta: object, id: string, name: string, size: number, createdAt: number } | null>}
+ */
+export async function load() {
+ try {
+ return await tx('readonly', (store) =>
+ new Promise((resolve, reject) => {
+ const req = store.get(KEY);
+ req.onsuccess = () => resolve(req.result || null);
+ req.onerror = () => reject(req.error || new Error('idb get failed'));
+ }),
+ );
+ } catch (err) {
+ console.warn('[guest-avatar] load failed:', err);
+ return null;
+ }
+}
+
+/**
+ * Drop the staged avatar after a successful save or an explicit "start over".
+ */
+export async function clear() {
+ try {
+ localStorage.removeItem(META_KEY);
+ } catch {
+ /* ignore */
+ }
+ try {
+ await tx('readwrite', (store) =>
+ new Promise((resolve, reject) => {
+ const req = store.delete(KEY);
+ req.onsuccess = () => resolve();
+ req.onerror = () => reject(req.error || new Error('idb delete failed'));
+ }),
+ );
+ } catch (err) {
+ console.warn('[guest-avatar] clear failed:', err);
+ }
+}
+
+function cryptoRandomId() {
+ const bytes = new Uint8Array(8);
+ (globalThis.crypto || window.crypto).getRandomValues(bytes);
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
+}
diff --git a/src/marketplace.js b/src/marketplace.js
index af67078e8..e1f0fdd03 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -20,6 +20,7 @@ import {
const API = '/api';
let purchasedSkills = new Set();
+let bookmarkedAgents = new Set();
function isLikelyAuthed() {
try {
@@ -44,6 +45,48 @@ async function fetchUserPurchases() {
}
}
+async function fetchUserBookmarks() {
+ if (!isLikelyAuthed()) return;
+ try {
+ const r = await fetch(`${API}/users/me/bookmarks`, { credentials: 'include' });
+ if (!r.ok) return;
+ const j = await r.json();
+ bookmarkedAgents = new Set(j.data?.agent_ids || []);
+ } catch (err) {
+ console.error('[marketplace] bookmarks', err);
+ }
+}
+
+async function toggleAgentBookmarkFromCard(agentId, btn) {
+ if (!isLikelyAuthed()) {
+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
+ return;
+ }
+ const wasOn = bookmarkedAgents.has(agentId);
+ btn.classList.toggle('on', !wasOn);
+ btn.setAttribute('aria-pressed', String(!wasOn));
+ btn.textContent = !wasOn ? '★' : '☆';
+ try {
+ const r = await fetch(`${API}/marketplace/agents/${agentId}/bookmark`, {
+ method: wasOn ? 'DELETE' : 'POST',
+ credentials: 'include',
+ });
+ if (!r.ok) throw new Error(`bookmark failed ${r.status}`);
+ const j = await r.json().catch(() => ({}));
+ const nowOn = !!j?.data?.bookmarked;
+ if (nowOn) bookmarkedAgents.add(agentId);
+ else bookmarkedAgents.delete(agentId);
+ btn.classList.toggle('on', nowOn);
+ btn.setAttribute('aria-pressed', String(nowOn));
+ btn.textContent = nowOn ? '★' : '☆';
+ } catch (err) {
+ btn.classList.toggle('on', wasOn);
+ btn.setAttribute('aria-pressed', String(wasOn));
+ btn.textContent = wasOn ? '★' : '☆';
+ console.error('[marketplace] toggle bookmark', err);
+ }
+}
+
const CATEGORY_LABELS = {
academic: 'Academic',
@@ -102,6 +145,11 @@ const els = {
// ── Routing ───────────────────────────────────────────────────────────────
+// Filter values that round-trip through ?tab= on the list view. Kept here so
+// readRoute and syncFilterToUrl agree on which strings are valid.
+const LIST_FILTER_TABS = new Set(['agents', 'avatars', 'onchain']);
+const SORT_VALUES = new Set(['recommended', 'recent', 'popular']);
+
function readRoute() {
const m = location.pathname.match(/^\/marketplace\/agents\/([^/]+)/);
if (m) return { view: 'detail', id: m[1] };
@@ -110,12 +158,37 @@ function readRoute() {
const params = new URLSearchParams(location.search);
const tab = params.get('tab');
const tag = (params.get('tag') || '').trim().toLowerCase().slice(0, 40) || null;
+ const q = (params.get('q') || '').trim().slice(0, 200);
+ const sort = SORT_VALUES.has(params.get('sort')) ? params.get('sort') : null;
if (tab === 'tools') return { view: 'tools', tag };
if (tab === 'skills') return { view: 'skills', tag };
if (tab === 'mine') return { view: 'mine', tag };
if (tab === 'purchases') return { view: 'purchases', tag };
- if (tab === 'avatars') return { view: 'list', filter: 'avatars', tag };
- return { view: 'list', tag };
+ const filter = LIST_FILTER_TABS.has(tab) ? tab : 'all';
+ return { view: 'list', filter, tag, q, sort };
+}
+
+// Push the current list-view filter/search/sort into the URL so back/forward
+// and page refresh both restore the same view. Uses replaceState by default
+// to avoid flooding history with every keystroke; pass push=true when the
+// change is user-meaningful (filter chip click, sort change).
+function syncFilterToUrl({ push = false } = {}) {
+ if (!location.pathname.startsWith('/marketplace')) return;
+ // Only sync from the discovery list view — detail / tools / mine views
+ // own their own URLs and we shouldn't trample them.
+ const path = location.pathname;
+ if (path !== '/marketplace') return;
+ const url = new URL(location.href);
+ const set = (key, val) => {
+ if (val) url.searchParams.set(key, val);
+ else url.searchParams.delete(key);
+ };
+ set('tab', LIST_FILTER_TABS.has(state.filter) ? state.filter : null);
+ set('q', state.q || null);
+ set('sort', state.sort && state.sort !== 'recommended' ? state.sort : null);
+ if (url.href === location.href) return;
+ if (push) history.pushState({}, '', url);
+ else history.replaceState({}, '', url);
}
function navTo(path, replace = false) {
@@ -361,7 +434,7 @@ async function loadList(reset = false) {
renderGrid();
} catch (err) {
console.error('[marketplace] list', err);
- els.grid.innerHTML = '<div class="market-empty">Failed to load agents.</div>';
+ els.grid.innerHTML = renderErrorState('agents');
} finally {
state.loading = false;
}
@@ -799,9 +872,13 @@ function bindFilterChips() {
const chips = document.querySelectorAll('#market-filter-chips .market-chip');
chips.forEach((chip) => {
chip.addEventListener('click', () => {
- chips.forEach((c) => c.classList.remove('active'));
- chip.classList.add('active');
+ chips.forEach((c) => {
+ const isActive = c === chip;
+ c.classList.toggle('active', isActive);
+ c.setAttribute('aria-selected', isActive ? 'true' : 'false');
+ });
state.filter = chip.dataset.filter || 'all';
+ syncFilterToUrl({ push: true });
// Hero showcases community avatars; hide it for non-avatar filters.
const hero = $('market-hero');
if (hero) {
@@ -1498,6 +1575,20 @@ function renderEmptyState() {
</div>`;
}
+// Error state with a retry CTA. Shown when an API call rejects so the user
+// can recover without manually refreshing the page.
+function renderErrorState(scope = 'agents') {
+ const label = scope === 'avatars' ? 'avatars' : scope === 'onchain' ? 'onchain agents' : 'agents';
+ return `
+ <div class="market-empty-cta" role="alert">
+ <h3>Couldn't load ${escapeHtml(label)}</h3>
+ <p>The marketplace server didn't respond. Check your connection and try again.</p>
+ <div class="market-empty-cta-actions">
+ <button type="button" class="market-empty-cta-btn primary" data-empty-action="empty-retry" data-retry-scope="${escapeHtml(scope)}">Retry</button>
+ </div>
+ </div>`;
+}
+
// Single delegated click handler so empty-state buttons keep working across
// re-renders (els.grid is innerHTML-replaced on every renderGrid).
function bindEmptyStateActions() {
@@ -1515,20 +1606,41 @@ function bindEmptyStateActions() {
const search = $('market-search');
if (search) search.value = '';
document.querySelectorAll('.market-chip[data-filter]').forEach((c) => {
- c.classList.toggle('active', c.dataset.filter === 'all');
+ const isActive = c.dataset.filter === 'all';
+ c.classList.toggle('active', isActive);
+ c.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
const hero = $('market-hero');
if (hero && state.featured.length) {
hero.hidden = false;
startHeroAutoplay();
}
+ // Drop ?tab=, ?q=, ?tag= from the URL so the cleared state survives
+ // refresh and the back button restores whatever the user came from.
+ navTo('/marketplace');
+ state.publicAvatarsLoaded = false;
+ state.onchainLoaded = false;
loadList(true);
+ loadPublicAvatars();
+ loadOnchainAgents(true);
} else if (action === 'empty-submit-agent') {
openSubmitModal();
} else if (action === 'empty-create-avatar') {
// /create is a separate page, not an SPA route on marketplace — use a
// real navigation so the browser actually loads the avatar builder.
location.href = '/create';
+ } else if (action === 'empty-retry') {
+ const scope = btn.dataset.retryScope || 'agents';
+ els.grid.innerHTML = '<div class="market-empty">Retrying…</div>';
+ if (scope === 'avatars') {
+ state.publicAvatarsLoaded = false;
+ loadPublicAvatars();
+ } else if (scope === 'onchain') {
+ state.onchainLoaded = false;
+ loadOnchainAgents(true);
+ } else {
+ loadList(true);
+ }
}
});
}
@@ -1621,8 +1733,11 @@ function renderCard(a) {
const previewStrip = a.thumbnail_url
? `<div class="thumb" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`
: `<div class="thumb">${placeholderHtml(a.name)}</div>`;
+ const bmOn = bookmarkedAgents.has(a.id);
+ const starBtn = `<button type="button" class="card-star${bmOn ? ' on' : ''}" data-agent-bm="${escapeHtml(a.id)}" aria-label="Bookmark agent" aria-pressed="${bmOn}" title="${bmOn ? 'Remove bookmark' : 'Bookmark agent'}">${bmOn ? '★' : '☆'}</button>`;
return `<div class="market-card-agent" data-id="${a.id}">
${previewStrip}
+ ${starBtn}
<div class="head">
${avatarBlock}
<div style="min-width:0;flex:1">
@@ -2253,6 +2368,7 @@ function bindEvents() {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
state.q = e.target.value.trim();
+ syncFilterToUrl();
// All three feeds (agents, avatars, onchain) accept ?q= on the server.
// If we only re-fetch agents on search, the grid keeps stale avatar +
// onchain cards from the previous query — and the empty state never
@@ -2266,6 +2382,7 @@ function bindEvents() {
});
els.sortSel.addEventListener('change', (e) => {
state.sort = e.target.value;
+ syncFilterToUrl({ push: true });
loadList(true);
});
els.loadMore.addEventListener('click', () => {
@@ -2908,12 +3025,35 @@ function render() {
if (r.view === 'list' && r.filter && r.filter !== state.filter) {
state.filter = r.filter;
document.querySelectorAll('#market-filter-chips .market-chip').forEach((c) => {
- c.classList.toggle('active', c.dataset.filter === r.filter);
+ const isActive = c.dataset.filter === r.filter;
+ c.classList.toggle('active', isActive);
+ c.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
// Re-render so the grid reflects the new filter without a refetch.
if (state.publicAvatarsLoaded) renderGrid();
}
+ // Route-driven search + sort restore — refresh / back / forward all need
+ // the controls to match the URL so the UI doesn't lie about what's loaded.
+ if (r.view === 'list') {
+ const routeQ = r.q || '';
+ if (routeQ !== state.q) {
+ state.q = routeQ;
+ if (els.search && els.search.value !== routeQ) els.search.value = routeQ;
+ state.publicAvatarsLoaded = false;
+ state.onchainLoaded = false;
+ loadList(true);
+ loadPublicAvatars();
+ loadOnchainAgents(true);
+ }
+ const routeSort = r.sort || 'recommended';
+ if (routeSort !== state.sort) {
+ state.sort = routeSort;
+ if (els.sortSel && els.sortSel.value !== routeSort) els.sortSel.value = routeSort;
+ loadList(true);
+ }
+ }
+
// Route-driven tag filter — re-render whenever ?tag= changes.
const newTag = r.tag ?? null;
if (newTag !== state.tag) {
diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.js
index 348358fdc..adabc710d 100644
--- a/src/selfie-pipeline.js
+++ b/src/selfie-pipeline.js
@@ -4,9 +4,11 @@
*
* Flow:
* [selfie:submit] → downscale photos → POST /api/avatars/reconstruct
- * → on 202 { jobId } → poll /api/avatars/regenerate-status?jobId=…
- * → on { status: 'done', resultAvatarId } → navigate to /avatars/<id>
- * → on { status: 'failed' } or timeout → surface a three.ws-branded error
+ * → dispatches selfie:building { jobId }
+ * → poll /api/avatars/regenerate-status?jobId=…
+ * → dispatches selfie:progress { label } on each poll tick
+ * → on { status: 'done', resultAvatarId } → dispatches selfie:done { avatarId }
+ * → on { status: 'failed' } or timeout → dispatches selfie:build-error { message }
*/
const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';
@@ -16,16 +18,25 @@ const JPEG_QUALITY = 0.88;
const POLL_INTERVAL_MS = 3000;
const POLL_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — image-to-3D models take 30-180s
+let _building = false;
+
document.addEventListener('selfie:submit', (event) => {
const ev = /** @type {CustomEvent} */ (event);
+ _building = false;
run(ev.detail).catch((err) => {
console.error('[selfie-pipeline]', err);
if (err?.redirect) {
window.location.assign(err.redirect);
return;
}
- setStatus(err.userMessage || 'Something went wrong. Try again.', { error: true });
- resetSubmit();
+ if (_building) {
+ document.dispatchEvent(new CustomEvent('selfie:build-error', {
+ detail: { message: err.userMessage || 'Something went wrong. Try again.' },
+ }));
+ } else {
+ setStatus(err.userMessage || 'Something went wrong. Try again.', { error: true });
+ resetSubmit();
+ }
});
});
@@ -38,6 +49,7 @@ document.addEventListener('selfie:submit', (event) => {
* }} detail
*/
async function run(detail) {
+ _building = false;
if (!detail?.files?.frontal || !detail.files.left || !detail.files.right) {
throw withMessage(new Error('missing photos'), 'Please add all 3 photos.');
}
@@ -72,6 +84,9 @@ async function run(detail) {
throw withMessage(new Error('no jobId'), 'The avatar engine did not return a job.');
}
+ _building = true;
+ document.dispatchEvent(new CustomEvent('selfie:building', { detail: { jobId: submitData.jobId } }));
+
const finalJob = await pollUntilDone(submitData.jobId);
if (!finalJob.resultAvatarId) {
@@ -81,8 +96,9 @@ async function run(detail) {
);
}
- setStatus('Opening your avatar…');
- window.location.assign(`/avatars/${encodeURIComponent(finalJob.resultAvatarId)}`);
+ document.dispatchEvent(new CustomEvent('selfie:done', {
+ detail: { avatarId: finalJob.resultAvatarId },
+ }));
}
/**
@@ -116,7 +132,9 @@ async function pollUntilDone(jobId) {
}
const job = await res.json().catch(() => ({}));
- setStatus(statusLabel(job.status, attempt));
+ document.dispatchEvent(new CustomEvent('selfie:progress', {
+ detail: { label: statusLabel(job.status, attempt), attempt },
+ }));
if (job.status === 'done') return job;
if (job.status === 'failed') {
@@ -138,10 +156,14 @@ async function pollUntilDone(jobId) {
* @param {number} attempt
*/
function statusLabel(status, attempt) {
- if (status === 'queued') return 'Queued…';
- if (status === 'running') return `Reconstructing your avatar… (${attempt}s)`;
- if (status === 'done') return 'Done — loading…';
- return `Working… (${attempt}s)`;
+ if (status === 'queued') return 'Queued — waiting for a reconstruction slot…';
+ if (status === 'running') {
+ if (attempt <= 6) return 'Analyzing face geometry…';
+ if (attempt <= 14) return 'Building mesh…';
+ return 'Finishing rig…';
+ }
+ if (status === 'done') return 'Done!';
+ return `Processing… (${attempt}s)`;
}
/** @param {string | null | undefined} raw */
diff --git a/tests/e2e/avatar-edit.spec.js b/tests/e2e/avatar-edit.spec.js
new file mode 100644
index 000000000..9da6d8115
--- /dev/null
+++ b/tests/e2e/avatar-edit.spec.js
@@ -0,0 +1,105 @@
+/**
+ * Smoke test for the wardrobe editor's new RPM-style UX:
+ * • hover applies a preset to the 3D stage and marks the tile .previewing
+ * • leave reverts to the committed state
+ * • click commits and adds a chip
+ * • chip × removes the committed item
+ * • search filters the visible tiles
+ *
+ * Avatar auth is bypassed by intercepting /api/avatars/:id with a synthetic
+ * owner-gated avatar that points at the public sample GLB.
+ */
+
+import { test, expect } from '@playwright/test';
+
+const AVATAR_FIXTURE = {
+ avatar: {
+ id: 'test-avatar',
+ owner_id: 'test-owner',
+ name: 'Test Avatar',
+ model_url: '/avatars/default.glb',
+ base_model_url: '/avatars/default.glb',
+ appearance: null,
+ },
+};
+
+test('wardrobe editor: hover, commit, chip, search', async ({ page }) => {
+ test.setTimeout(120_000);
+
+ page.on('pageerror', (err) => {
+ throw new Error(`Page error: ${err.message}`);
+ });
+
+ // Stub auth-gated avatar fetch + PATCH so the editor boots without a real
+ // session. We don't intercept presets.json or the GLBs — those are served
+ // by Vite from /public.
+ await page.route('**/api/avatars/test-avatar', async (route) => {
+ const req = route.request();
+ if (req.method() === 'GET') {
+ return route.fulfill({ json: AVATAR_FIXTURE });
+ }
+ if (req.method() === 'PATCH') {
+ const body = JSON.parse(req.postData() || '{}');
+ return route.fulfill({
+ json: {
+ avatar: {
+ ...AVATAR_FIXTURE.avatar,
+ appearance: body.appearance || null,
+ baked: false,
+ },
+ },
+ });
+ }
+ return route.fallback();
+ });
+
+ await page.goto('/pages/avatar-edit.html?id=test-avatar');
+
+ // Wait for the stage to mount and the first panel to render.
+ await expect(page.locator('#ae-title')).toContainText('Test Avatar');
+ await expect(page.locator('.ae-tab.active')).toHaveText(/Outfits/);
+ await expect(page.locator('.ae-search')).toBeVisible();
+
+ // Chip bar starts empty (placeholder copy via :empty::before).
+ const chipBar = page.locator('#ae-chips');
+ await expect(chipBar.locator('.ae-chip')).toHaveCount(0);
+
+ // Hover the first real outfit tile and confirm the previewing class is set.
+ const firstOutfit = page.locator('.ae-tile[data-id="outfit-casual"]');
+ await expect(firstOutfit).toBeVisible();
+ await firstOutfit.hover();
+ await expect(firstOutfit).toHaveClass(/previewing/);
+ await expect(page.locator('#ae-status')).toContainText(/Previewing/i);
+
+ // Move mouse off — previewing class should drop.
+ await page.locator('#ae-title').hover();
+ await expect(firstOutfit).not.toHaveClass(/previewing/);
+
+ // Click to commit. Chip appears in the chip bar.
+ await firstOutfit.click();
+ await expect(firstOutfit).toHaveClass(/selected/);
+ await expect(chipBar.locator('.ae-chip')).toHaveCount(1);
+ await expect(chipBar.locator('.ae-chip')).toContainText('Casual');
+
+ // Search filters: typing "form" should narrow outfits to "Formal".
+ await page.locator('.ae-search').fill('form');
+ await expect(page.locator('.ae-tile').filter({ hasText: 'Formal' })).toHaveCount(1);
+ await expect(page.locator('.ae-tile').filter({ hasText: 'Casual' })).toHaveCount(0);
+ // The None tile is hidden during search.
+ await expect(page.locator('.ae-tile-none')).toHaveCount(0);
+
+ // Clear search.
+ await page.locator('.ae-search').fill('');
+
+ // Remove via chip ×.
+ await chipBar.locator('.ae-chip button[data-remove]').first().click();
+ await expect(chipBar.locator('.ae-chip')).toHaveCount(0);
+
+ // Switch to the Hats tab, hover a hat, confirm previewing.
+ await page.locator('.ae-tab', { hasText: 'Hats' }).click();
+ const beanie = page.locator('.ae-tile[data-id="hat-beanie"]');
+ await beanie.hover();
+ await expect(beanie).toHaveClass(/previewing/);
+ await beanie.click();
+ await expect(chipBar.locator('.ae-chip')).toContainText('Beanie');
+});