Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: page-agent + walk SDKs, rig classify/status helpers, avatar + gallery updates
nirholas438eeb84fa13
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 615a576a9..eee012ed4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Drop agents on your real floor with AR precision** — On Android phones that support AR, placing an agent in your room is now pinpoint: point at the floor, a reticle locks onto the real ground, and you tap to drop the agent exactly where you're looking — feet on the actual floor, not floating at a guess. It anchors into the same shared room as the rest of your agents, so everyone who opens IRL at that spot — including iPhones — sees it in the same place, and you can re-tap “Refine on floor” on one of your agents to sharpen just its spot without nudging the others. iPhones and phones without AR keep the aim-and-distance flow they already had, with no extra buttons and nothing that doesn't work — every device gets the best placement it can do. (`/irl`) `[feature]`- **Every IRL moment now has a designed, honest state** — IRL asks for the three most sensitive permissions a web app can — camera, motion, and location — and we made every moment around them feel deliberate instead of uncertain. While your phone is still finding your GPS fix, the top bar shows a clear "Finding your location…" shimmer so the wait never looks like an empty, nobody-here screen. If discovery ever has to slow down to catch its breath, you get a calm "catching up…" note that quietly recovers on its own — never a scary error. The live-presence indicator stays honest too: when it drops, nearby discovery keeps working and nothing implies otherwise. Every control is now reachable by keyboard with a visible focus ring, screen readers announce each state change once, and all of it respects reduced-motion settings. (`/irl`) `[improvement]`- **Every page now shares with its own social card** — Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews. `[improvement, infra]`+- **Filter the avatar gallery by rigged vs static** — Every public avatar is now classified by whether it carries a skeleton — rigged models can play the animation library straight away, while static ones are geometry only until you auto-rig them. The gallery shows a green "Rigged" or grey "Not rigged" badge in the corner of each card, adds a Rig filter so you can show just the animation-ready avatars, and a "Rigged first" sort. Deep links keep your filter, so you can share a view of only the rigged avatars. (`/gallery`) `[feature]`- **Fixed broken links and added retry on failed loads across the app** — Several navigation links pointed at pages that no longer exist — "View plans" on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working "claim" button with a plain explanation that revenue share is distributed to holders automatically. `[fix, improvement]`- **Fixed the clipped header on the agent wallet page** — The agent wallet page had a broken header — the agent's avatar and the green "Wallet ready" badge were chopped off behind a black bar, with the wallet name floating above it. A site-wide page-header style was leaking onto the wallet's own header row and forcing it into a short, clipped strip. The header now lays out properly, so the avatar, status badge, profile link, and network selector are all fully visible. `[fix]`- **Fixed wallet sign-in returning an error** — Signing in with a Solana or Ethereum wallet was failing for everyone — the request that starts the sign-in handshake was erroring out before you could approve anything in your wallet. A misread site address on the server was the cause; it now self-corrects, and wallet sign-in works again. `[fix]`@@ -69,6 +70,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Unity & Unreal avatar loading documented with code that actually works** — The developer hub's Unity and Unreal cards used to show sample code for an SDK that doesn't exist yet. They now show the real, working way to load a three.ws avatar today — your avatar's GLB endpoint loaded at runtime with glTFast (Unity) or glTFRuntime (Unreal), both standard glTF importers — alongside an honest note that a native package is still on the roadmap. (`/dashboard/developers`) `[docs, improvement]`- **Vanity wallets for every agent — opt-in, owned per user** — Every agent and avatar has its own custodial Solana wallet, and you own it per creation: make an avatar and its agent wallet is yours; if someone forks or saves that avatar, they get a brand-new wallet they alone control — yours is never shared or copied. A new Vanity tab in the agent wallet hub lets you grind a custom address (your own prefix and/or suffix) on demand. If the wallet already holds funds, they're automatically and safely swept to the new address before the switch completes, so funds are never stranded. The wallet now appears everywhere an agent or avatar shows up — profiles, avatar pages, your Agents and Avatars dashboards, the Characters feed and Trending — each with one-tap copy, an explorer link, and a vanity badge. (`/vanity-wallet`) `[feature]`- **Walk Playground no longer loses your character when it falls** — When you walked the little robot off a ledge it could plummet faster than the page could keep up and slip off the bottom of the screen, leaving you unable to find it. The camera now tracks falls tightly and keeps the character in view, and on pages that can't scroll it catches the character and drops it right back into view. (`/features/walk`) `[fix]`+- **Walk Playground now has two modes you can switch between** — Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page. `[feature]`- **Walk the whole page — the site is now a playground** — The corner walking companion can now step out of its spot. Click it and the character detaches into a gentle bird's-eye view of the page, and you steer him anywhere across it with the arrow keys or WASD (an on-screen d-pad on phones) — no falling, just free roaming over the whole page. Step onto any link and it lights up like a doorway; pause on it or press the dive key and the character drops through, and you fall into the next page, arriving on the other side. It loads nothing extra until you click in, so normal browsing pays no cost. Jump straight in from any page with ?walk=play. `[feature]`## 2026-06-18diff --git a/api/_lib/avatars.js b/api/_lib/avatars.jsindex c5c86f2fd..e95f9bb94 100644--- a/api/_lib/avatars.js+++ b/api/_lib/avatars.js@@ -225,7 +225,27 @@ export async function deleteAvatar({ id, userId }) {return true;}-export async function searchPublicAvatars({ q, tag, category, limit = 24, cursor, withTotals = false }) {+// Normalize the public `rigged` query param into one of the classifier buckets,+// or null for "no rig filter". Accepts the booleanish forms the UI sends+// (true/false/1/0/yes/no) plus the explicit bucket names.+function normalizeRigFilter(rigged) {+ if (rigged == null || rigged === '') return null;+ const v = String(rigged).trim().toLowerCase();+ if (v === 'true' || v === '1' || v === 'yes' || v === 'rigged') return 'rigged';+ if (v === 'false' || v === '0' || v === 'no' || v === 'static') return 'static';+ if (v === 'unknown') return 'unknown';+ return null;+}++export async function searchPublicAvatars({+ q,+ tag,+ category,+ rigged,+ limit = 24,+ cursor,+ withTotals = false,+}) {limit = Math.min(Math.max(limit, 1), 100);const params = [];const conds = [`deleted_at is null`, `visibility = 'public'`];@@ -241,6 +261,32 @@ export async function searchPublicAvatars({ q, tag, category, limit = 24, cursorparams.push(category);conds.push(`model_category = $${params.length}`);}+ // Rig classifier filter. Mirrors classifyRig() in src/shared/rig-classify.js+ // exactly so a server-filtered list and a client-painted badge never disagree:+ // a model is "rigged" iff source_meta.is_rigged is true OR it carries a+ // positive skeleton_joint_count. CASE guards mean a malformed JSONB value+ // degrades to "not rigged" instead of throwing a cast error.+ // CASE (not AND) guards the cast: Postgres does not guarantee WHERE-clause+ // AND short-circuits, so a bare `regex and (..)::int` can still evaluate the+ // cast on a non-numeric string and throw. CASE is guaranteed to short-circuit.+ const RIG_SIGNAL = `(+ (source_meta->>'is_rigged') = 'true'+ or case when source_meta->>'skeleton_joint_count' ~ '^[1-9][0-9]*$' then true else false end+ )`;+ const rigState = normalizeRigFilter(rigged);+ if (rigState === 'rigged') {+ conds.push(RIG_SIGNAL);+ } else if (rigState === 'static') {+ // Everything that is NOT rigged — both confirmed-static meshes and+ // never-inspected uploads. From a user's standpoint both need rigging+ // before they animate, so they belong in the same "not rigged" bucket.+ conds.push(`not ${RIG_SIGNAL}`);+ } else if (rigState === 'unknown') {+ // Never skeleton-inspected: no is_rigged flag and no joint count.+ conds.push(+ `(source_meta->>'is_rigged') is null and (source_meta->>'skeleton_joint_count' is null or source_meta->>'skeleton_joint_count' !~ '^[1-9][0-9]*$')`,+ );+ }const filterParams = params.slice();const filterConds = conds.join(' and ');if (cursor) {diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex bdb267e04..a5a629a74 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -326,6 +326,7 @@ const handlePublic = wrap(async (req, res) => {q: url.searchParams.get('q') || undefined,tag: url.searchParams.get('tag') || undefined,category: url.searchParams.get('category') || undefined,+ rigged: url.searchParams.get('rigged') || undefined,limit,cursor: url.searchParams.get('cursor') || undefined,withTotals: url.searchParams.get('totals') === '1',diff --git a/api/x402/forge.js b/api/x402/forge.jsindex f6b18f256..60dea3314 100644--- a/api/x402/forge.js+++ b/api/x402/forge.js@@ -25,9 +25,10 @@// charged. The job token is the upstream prediction id, identical to what the// free endpoint issues, so a single poll path serves both.//-// Networks: Base mainnet (EIP-3009 + Permit2 sibling) and Solana mainnet (USDC).-// verifyPayment / settlePayment in x402-spec.js route per network; the Solana-// entry is omitted when X402_PAY_TO_SOLANA is unset so the 402 stays valid.+// Network: Solana mainnet (USDC) only. verifyPayment / settlePayment in+// x402-spec.js route per network. Base is offered solely as a dev/preview+// failsafe when X402_PAY_TO_SOLANA is unset; production sets it, so the live+// route quotes Solana only.import { wrap, cors, error, json, rateLimited } from '../_lib/http.js';import {@@ -91,7 +92,7 @@ const ROUTE_DESCRIPTION ='finish inline and return the GLB url with status:"done"). Text→3D runs on the ' +'free NVIDIA NIM TRELLIS lane (native text→mesh); image→3D reconstructs via ' +'TRELLIS. Priced per quality tier in USDC ($0.05 draft / $0.15 standard / ' +- '$0.50 high). Pay autonomously on Base or Solana mainnet — no API key, no account.';+ '$0.50 high). Pay autonomously in USDC on Solana mainnet — no API key, no account.';const INPUT_EXAMPLE = {prompt: 'a brass steampunk owl, full body',@@ -177,6 +178,26 @@ const ROUTE_BAZAAR = {function buildRequirements(resourceUrl, priceAtomics) {const amount = String(priceAtomics);+ // The paid Forge settles in USDC on Solana mainnet ONLY. Base/EVM is+ // intentionally not offered — every quote on this route is a Solana 402.+ if (env.X402_PAY_TO_SOLANA) {+ return [+ {+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_SOLANA,+ asset: env.X402_ASSET_MINT_SOLANA,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },+ },+ ];+ }+ // Failsafe for a dev/preview deploy where Solana isn't configured: fall back to+ // Base so the route never dead-ends with an empty 402. Production sets+ // X402_PAY_TO_SOLANA, so this branch never runs there and the route stays+ // Solana-only in the live product.const eip3009 = {scheme: 'exact',network: NETWORK_BASE_MAINNET,@@ -190,18 +211,6 @@ function buildRequirements(resourceUrl, priceAtomics) {const out = [eip3009];const permit2 = permit2VariantOf(eip3009);if (permit2) out.push(permit2);- if (env.X402_PAY_TO_SOLANA) {- out.push({- scheme: 'exact',- network: NETWORK_SOLANA_MAINNET,- amount,- payTo: env.X402_PAY_TO_SOLANA,- asset: env.X402_ASSET_MINT_SOLANA,- maxTimeoutSeconds: 60,- resource: resourceUrl,- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },- });- }return out;}diff --git a/data/changelog.json b/data/changelog.jsonindex 3693dd02b..103aba8a1 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,23 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-19",+ "title": "Filter the avatar gallery by rigged vs static",+ "summary": "Every public avatar is now classified by whether it carries a skeleton — rigged models can play the animation library straight away, while static ones are geometry only until you auto-rig them. The gallery shows a green \"Rigged\" or grey \"Not rigged\" badge in the corner of each card, adds a Rig filter so you can show just the animation-ready avatars, and a \"Rigged first\" sort. Deep links keep your filter, so you can share a view of only the rigged avatars.",+ "tags": [+ "feature"+ ],+ "link": "/gallery"+ },+ {+ "date": "2026-06-19",+ "title": "Walk Playground now has two modes you can switch between",+ "summary": "Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","title": "New Club lineup — Dylan, Nich and Boss Vernington take the poles",diff --git a/page-agent-sdk/package.json b/page-agent-sdk/package.jsonnew file mode 100644index 000000000..1c50e04bc--- /dev/null+++ b/page-agent-sdk/package.json@@ -0,0 +1,78 @@+{+ "name": "@three-ws/page-agent",+ "version": "0.1.0",+ "description": "Drop a rigged 3D AI agent onto any website that talks visitors through the page. A diverse catalog of skeleton-rigged, lipsync-capable avatars, a built-in picker so visitors choose their guide, and a one-line embed. Powered by three.ws.",+ "keywords": [+ "3d",+ "avatar",+ "ai-agent",+ "three.js",+ "webgl",+ "rigged",+ "lipsync",+ "viseme",+ "text-to-speech",+ "narrator",+ "page-guide",+ "web-component",+ "talking-avatar",+ "readyplayerme-alternative"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "page-agent-sdk"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "type": "module",+ "main": "./dist/page-agent.mjs",+ "module": "./dist/page-agent.mjs",+ "unpkg": "./dist/page-agent.global.js",+ "jsdelivr": "./dist/page-agent.global.js",+ "types": "./types/index.d.ts",+ "exports": {+ ".": {+ "types": "./types/index.d.ts",+ "import": "./dist/page-agent.mjs",+ "default": "./dist/page-agent.mjs"+ },+ "./catalog": {+ "types": "./types/index.d.ts",+ "import": "./src/catalog.js",+ "default": "./src/catalog.js"+ },+ "./global": "./dist/page-agent.global.js",+ "./style.css": "./dist/page-agent.css"+ },+ "files": [+ "dist",+ "src",+ "types",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "node build.mjs",+ "prepublishOnly": "node build.mjs",+ "test": "node --test test/"+ },+ "peerDependencies": {+ "three": ">=0.150.0"+ },+ "peerDependenciesMeta": {+ "three": {+ "optional": false+ }+ },+ "engines": {+ "node": ">=18"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/page-agent-sdk/src/catalog.js b/page-agent-sdk/src/catalog.jsnew file mode 100644index 000000000..52de3845e--- /dev/null+++ b/page-agent-sdk/src/catalog.js@@ -0,0 +1,216 @@+/**+ * Rigged agent catalog — @three-ws/page-agent+ * ============================================+ *+ * Every entry here is a *skeleton-rigged humanoid* glTF agent. This is a hard+ * rule: the page-agent runtime drives skeletal idle motion and mouth/viseme+ * lipsync, so an unrigged mesh would render a frozen, dead-faced statue. We do+ * not ship those. Each avatar in this file has been verified to contain a+ * skinned mesh + armature; the `rig` and `lipsync` fields record *how* it is+ * rigged so the runtime can pick the right mouth driver per avatar:+ *+ * lipsync: 'viseme' — Oculus/ARKit viseme morph targets (viseme_aa …).+ * Full phoneme-accurate mouth shapes.+ * lipsync: 'jaw' — only a jaw/mouthOpen morph. Amplitude-driven open.+ * lipsync: 'animation' — no face morphs; speech is carried by a talk body+ * animation + head motion (Mixamo characters).+ *+ * Assets are served from the three.ws origin (the repo's public/ web root), so+ * the default URLs are real and load with no extra setup. Override `assetBase`+ * (or any entry's `url`) to self-host.+ */++/** Default CDN base. Real, public three.ws assets — `public/avatars/*.glb`. */+export const DEFAULT_ASSET_BASE = 'https://three.ws/avatars/';++/**+ * @typedef {Object} RiggedAgent+ * @property {string} id Stable slug used in attributes / localStorage.+ * @property {string} name Display name shown in the picker + caption.+ * @property {string} tagline One-line personality hook for the picker card.+ * @property {string} persona Short voice/identity blurb (also the default+ * greeting flavor). Plain language — no jargon.+ * @property {string} file GLB filename under the asset base.+ * @property {string} [url] Absolute override; wins over assetBase+file.+ * @property {'rpm'|'mixamo'|'studio'} rig Rig family.+ * @property {'viseme'|'jaw'|'animation'} lipsync Mouth driver to use.+ * @property {'female'|'male'|'neutral'|'robot'} presents Voice/picker hint.+ * @property {'realistic'|'stylized'|'robot'} style+ * @property {'bust'|'upper'|'full'} framing Default camera crop.+ * @property {{ lang?: string, pitch?: number, rate?: number, match?: string[] }} voice+ * Web Speech selection hints — `match` are case-insensitive+ * substrings tried against installed voice names, in order.+ * @property {string} accent Accent color for this agent's UI chrome.+ */++/** @type {RiggedAgent[]} */+export const AGENTS = [+ {+ id: 'sol',+ name: 'Sol',+ tagline: 'Calm, clear product guide',+ persona: "I'm Sol — I walk you through a page like a good colleague would: the what, the why, and where to click next.",+ file: 'realistic-halfbody.glb',+ rig: 'rpm',+ lipsync: 'viseme',+ presents: 'neutral',+ style: 'realistic',+ framing: 'bust',+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['samantha', 'jenny', 'aria', 'google us english'] },+ accent: '#6366f1',+ },+ {+ id: 'nova',+ name: 'Nova',+ tagline: 'Upbeat, friendly host',+ persona: "Hey, I'm Nova! I keep things light and quick — ask me anything and I'll show you around.",+ file: 'selfie-girl.glb',+ rig: 'rpm',+ lipsync: 'viseme',+ presents: 'female',+ style: 'stylized',+ framing: 'upper',+ voice: { lang: 'en-US', pitch: 1.12, rate: 1.04, match: ['jenny', 'aria', 'samantha', 'google us english'] },+ accent: '#ec4899',+ },+ {+ id: 'vera',+ name: 'Vera',+ tagline: 'Composed, professional',+ persona: "I'm Vera. Precise and to the point — I'll give you the signal, not the noise.",+ file: 'realistic-female.glb',+ rig: 'rpm',+ lipsync: 'viseme',+ presents: 'female',+ style: 'realistic',+ framing: 'bust',+ voice: { lang: 'en-GB', pitch: 1.0, rate: 0.98, match: ['libby', 'sonia', 'google uk english female', 'serena'] },+ accent: '#14b8a6',+ },+ {+ id: 'atlas',+ name: 'Atlas',+ tagline: 'Confident, grounded',+ persona: "Atlas here. I'll break down what matters and keep you moving — no fluff.",+ file: 'realistic-male.glb',+ rig: 'rpm',+ lipsync: 'viseme',+ presents: 'male',+ style: 'realistic',+ framing: 'bust',+ voice: { lang: 'en-US', pitch: 0.92, rate: 0.98, match: ['guy', 'eric', 'google us english', 'daniel'] },+ accent: '#3b82f6',+ },+ {+ id: 'echo',+ name: 'Echo',+ tagline: 'Neutral, even-keeled',+ persona: "I'm Echo — a steady, no-nonsense guide. Tell me where you want to go.",+ file: 'default.glb',+ rig: 'rpm',+ lipsync: 'viseme',+ presents: 'neutral',+ style: 'stylized',+ framing: 'upper',+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['google us english', 'samantha', 'guy'] },+ accent: '#8b5cf6',+ },+ {+ id: 'lumen',+ name: 'Lumen',+ tagline: 'Minimal studio presenter',+ persona: "Lumen. Clean and quiet — I narrate, you explore.",+ file: 'studio.glb',+ rig: 'studio',+ lipsync: 'jaw',+ presents: 'neutral',+ style: 'stylized',+ framing: 'upper',+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['google us english', 'samantha'] },+ accent: '#0ea5e9',+ },+ {+ id: 'kai',+ name: 'Kai',+ tagline: 'Playful robot sidekick',+ persona: "Beep — Kai online. I'm the robot in the corner who actually read the docs.",+ file: 'xbot.glb',+ rig: 'mixamo',+ lipsync: 'animation',+ presents: 'robot',+ style: 'robot',+ framing: 'full',+ voice: { lang: 'en-US', pitch: 0.85, rate: 1.05, match: ['guy', 'google us english', 'fred'] },+ accent: '#f59e0b',+ },+ {+ id: 'mira',+ name: 'Mira',+ tagline: 'Expressive, full-body',+ persona: "I'm Mira — I talk with my whole self. Great energy for a tour.",+ file: 'michelle.glb',+ rig: 'mixamo',+ lipsync: 'animation',+ presents: 'female',+ style: 'stylized',+ framing: 'full',+ voice: { lang: 'en-US', pitch: 1.08, rate: 1.0, match: ['aria', 'jenny', 'samantha'] },+ accent: '#ef4444',+ },+ {+ id: 'pax',+ name: 'Pax',+ tagline: 'Laid-back explainer',+ persona: "Pax. I keep it relaxed and human — we'll get through this together.",+ file: 'cz.glb',+ rig: 'mixamo',+ lipsync: 'animation',+ presents: 'neutral',+ style: 'stylized',+ framing: 'full',+ voice: { lang: 'en-US', pitch: 0.96, rate: 0.97, match: ['google us english', 'guy', 'samantha'] },+ accent: '#22c55e',+ },+];++/** Default agent shown before any visitor choice is restored. */+export const DEFAULT_AGENT_ID = 'sol';++const _byId = new Map(AGENTS.map((a) => [a.id, a]));++/** @param {string} id @returns {RiggedAgent|undefined} */+export function getAgent(id) {+ return _byId.get(id);+}++/**+ * Resolve an agent's absolute GLB URL.+ * @param {RiggedAgent} agent+ * @param {string} [assetBase]+ * @returns {string}+ */+export function agentUrl(agent, assetBase = DEFAULT_ASSET_BASE) {+ if (agent.url) return agent.url;+ const base = assetBase.endsWith('/') ? assetBase : assetBase + '/';+ return base + agent.file;+}++/**+ * Filtered view of the catalog. Every agent is rigged by construction; these+ * filters narrow by presentation/style/lipsync capability for a host that+ * wants a curated subset in the picker.+ *+ * @param {{ style?: string, presents?: string, lipsync?: string, ids?: string[] }} [q]+ * @returns {RiggedAgent[]}+ */+export function filterAgents(q = {}) {+ let list = AGENTS;+ if (q.ids?.length) {+ const want = new Set(q.ids);+ list = list.filter((a) => want.has(a.id));+ }+ if (q.style) list = list.filter((a) => a.style === q.style);+ if (q.presents) list = list.filter((a) => a.presents === q.presents);+ if (q.lipsync) list = list.filter((a) => a.lipsync === q.lipsync);+ return list;+}diff --git a/page-agent-sdk/src/lipsync.js b/page-agent-sdk/src/lipsync.jsnew file mode 100644index 000000000..33fb620bb--- /dev/null+++ b/page-agent-sdk/src/lipsync.js@@ -0,0 +1,170 @@+/**+ * Lipsync driver — @three-ws/page-agent+ * =====================================+ *+ * Text → viseme heuristic. No audio analysis, no microphone, no network. We+ * tokenize the spoken text into a timed viseme sequence and lerp the matching+ * morph targets each frame, so the mouth shapes track the words the speech+ * engine is saying. This is the same approach three.ws ships in production+ * (src/runtime/lipsync.js); it is reproduced here so the package stays+ * dependency-free apart from `three`.+ *+ * Three mouth drivers, chosen from the discovered morph targets:+ * - 'arkit': full Oculus/ARKit viseme set (best).+ * - 'jaw': only jawOpen/mouthOpen — amplitude-style open/close.+ * - none: no morphs → returns a no-op timeline; the stage carries the+ * talk visually through body animation instead.+ */++const ARKIT_VISEMES = [+ 'viseme_aa', 'viseme_CH', 'viseme_DD', 'viseme_E', 'viseme_FF',+ 'viseme_I', 'viseme_kk', 'viseme_nn', 'viseme_O', 'viseme_PP',+ 'viseme_RR', 'viseme_sil', 'viseme_SS', 'viseme_TH', 'viseme_U',+];+const JAW_FALLBACKS = ['jawOpen', 'mouthOpen'];++const CHAR_TO_VISEME = {+ a: 'viseme_aa', e: 'viseme_E', i: 'viseme_I', o: 'viseme_O', u: 'viseme_U',+ b: 'viseme_PP', m: 'viseme_PP', p: 'viseme_PP',+ f: 'viseme_FF', v: 'viseme_FF',+ d: 'viseme_DD', t: 'viseme_DD', n: 'viseme_DD', l: 'viseme_DD',+ k: 'viseme_kk', g: 'viseme_kk', c: 'viseme_kk', q: 'viseme_kk',+ s: 'viseme_SS', z: 'viseme_SS', x: 'viseme_SS',+ r: 'viseme_RR', w: 'viseme_U', y: 'viseme_I', h: 'viseme_E', j: 'viseme_CH',+};+const DIGRAPH_TO_VISEME = { th: 'viseme_TH', ch: 'viseme_CH', sh: 'viseme_CH' };++const MS_PER_PHONEME = 80;+const WORD_GAP_MS = 120;+const PUNCT_GAP_MS = 200;+const LERP = 0.35;++/**+ * Build a map of morph-target name → [{ mesh, index }] for the avatar root.+ * @param {import('three').Object3D} root+ * @returns {{ mode: 'arkit'|'jaw', map: Map<string, {mesh:any,index:number}[]> }|null}+ */+export function buildMorphMap(root) {+ const arkit = new Map();+ const jaw = new Map();+ root?.traverse?.((node) => {+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;+ const dict = node.morphTargetDictionary;+ for (const name of ARKIT_VISEMES) {+ if (dict[name] === undefined) continue;+ if (!arkit.has(name)) arkit.set(name, []);+ arkit.get(name).push({ mesh: node, index: dict[name] });+ }+ for (const name of JAW_FALLBACKS) {+ if (dict[name] === undefined) continue;+ if (!jaw.has(name)) jaw.set(name, []);+ jaw.get(name).push({ mesh: node, index: dict[name] });+ }+ });+ if (arkit.size) return { mode: 'arkit', map: arkit };+ if (jaw.size) return { mode: 'jaw', map: jaw };+ return null;+}++function tokenize(text) {+ const seq = [];+ const lower = String(text || '').toLowerCase();+ let t = 0;+ for (let i = 0; i < lower.length; ) {+ const pair = i + 1 < lower.length ? lower[i] + lower[i + 1] : '';+ if (DIGRAPH_TO_VISEME[pair]) {+ seq.push({ viseme: DIGRAPH_TO_VISEME[pair], startMs: t, endMs: t + MS_PER_PHONEME * 2 });+ t += MS_PER_PHONEME * 2;+ i += 2;+ continue;+ }+ const ch = lower[i];+ if (CHAR_TO_VISEME[ch]) {+ seq.push({ viseme: CHAR_TO_VISEME[ch], startMs: t, endMs: t + MS_PER_PHONEME });+ t += MS_PER_PHONEME;+ } else if (/\s/.test(ch)) {+ t += WORD_GAP_MS;+ } else if (/[.,!?;:]/.test(ch)) {+ t += PUNCT_GAP_MS;+ }+ i++;+ }+ return seq;+}++/** Rough natural duration of `text` in ms, used to pace the no-morph case. */+export function estimateDurationMs(text) {+ const seq = tokenize(text);+ return seq.length ? seq[seq.length - 1].endMs : 0;+}++/**+ * Start a lipsync timeline. The returned object exposes:+ * - tick(nowMs): call every frame; advances + lerps morph influences.+ * - stop(): reset all influences to 0 and mark done.+ * - done: true once the sequence has fully played.+ *+ * The caller owns the clock so the timeline can be synced to the speech engine+ * (we start it on utterance `start`, advance on the render loop, stop on `end`).+ *+ * @param {string} text+ * @param {ReturnType<typeof buildMorphMap>|null} morph+ * @param {{ rate?: number }} [opts] rate>1 speeds the mouth to match faster TTS+ */+export function createLipsync(text, morph, opts = {}) {+ const rate = opts.rate && opts.rate > 0 ? opts.rate : 1;+ const seq = morph ? tokenize(text) : [];+ const totalMs = seq.length ? seq[seq.length - 1].endMs : 0;+ let startMs = -1;+ let done = false;++ // Per-morph smoothed influence so we can lerp toward targets each frame.+ const current = morph ? new Map([...morph.map.keys()].map((k) => [k, 0])) : new Map();++ function apply(name, value) {+ const entries = morph?.map.get(name);+ if (!entries) return;+ for (const { mesh, index } of entries) mesh.morphTargetInfluences[index] = value;+ }++ function tick(nowMs) {+ if (!morph || done) return;+ if (startMs < 0) startMs = nowMs;+ const elapsed = (nowMs - startMs) * rate;++ // Determine the active viseme target for this instant.+ let active = null;+ if (elapsed <= totalMs) {+ for (const ph of seq) {+ if (elapsed >= ph.startMs && elapsed < ph.endMs) { active = ph.viseme; break; }+ }+ }++ // In jaw mode there's no per-viseme shape — any active phoneme opens the+ // jaw on an envelope; silence closes it.+ for (const name of current.keys()) {+ let target = 0;+ if (morph.mode === 'arkit') {+ target = name === active ? 0.92 : 0;+ } else {+ // jaw: open while speaking, with a gentle per-phoneme pulse+ target = active ? 0.45 + 0.25 * Math.abs(Math.sin(elapsed / 70)) : 0;+ }+ const next = current.get(name) + (target - current.get(name)) * LERP;+ current.set(name, next);+ apply(name, next);+ }++ if (elapsed > totalMs + 120) done = true;+ }++ function stop() {+ done = true;+ for (const name of current.keys()) {+ current.set(name, 0);+ apply(name, 0);+ }+ }++ return { tick, stop, get done() { return done; }, get totalMs() { return totalMs; } };+}diff --git a/page-agent-sdk/src/narrator.js b/page-agent-sdk/src/narrator.jsnew file mode 100644index 000000000..7c353b0e6--- /dev/null+++ b/page-agent-sdk/src/narrator.js@@ -0,0 +1,192 @@+/**+ * SpeechNarrator — @three-ws/page-agent+ * =====================================+ *+ * Speaks queued text aloud with the Web Speech API and keeps the avatar's mouth+ * in sync. There is no backend, no API key, no audio file: TTS is synthesized+ * in the browser, and the lipsync timeline is advanced on the stage's render+ * loop so visemes track the spoken words.+ *+ * Graceful by design:+ * - No speechSynthesis (or muted): we still run the lipsync timeline for the+ * text's estimated duration so the avatar visibly "talks" and captions+ * show — the page narration never silently stalls.+ * - Voice list loads async on some platforms; we wait for `voiceschanged`.+ */++import { createLipsync, estimateDurationMs } from './lipsync.js';++const hasTTS = typeof window !== 'undefined' && 'speechSynthesis' in window;++export class SpeechNarrator {+ /**+ * @param {import('./stage.js').AvatarStage} stage+ * @param {{ muted?: boolean, onState?: (s:'idle'|'speaking')=>void,+ * onCaption?: (text:string|null)=>void, onError?: (e:Error)=>void }} [opts]+ */+ constructor(stage, opts = {}) {+ this.stage = stage;+ this.muted = !!opts.muted;+ this.onState = opts.onState || (() => {});+ this.onCaption = opts.onCaption || (() => {});+ this.onError = opts.onError || (() => {});++ this.agent = null; // current RiggedAgent (for voice selection)+ this._queue = [];+ this._active = null; // { lipsync, utter, fallbackTimer, resolve }+ this._frameUnsub = stage.onFrame((dt, nowMs) => this._tick(nowMs));+ this._voices = [];++ if (hasTTS) {+ this._loadVoices();+ window.speechSynthesis.addEventListener?.('voiceschanged', this._loadVoices.bind(this));+ }+ }++ /** Switch the active agent so future utterances use its voice profile. */+ setAgent(agent) {+ this.agent = agent;+ }++ setMuted(muted) {+ this.muted = !!muted;+ if (muted && hasTTS) window.speechSynthesis.cancel();+ }++ /**+ * Queue text to speak. Returns a promise that resolves when this line ends+ * (or is skipped/cancelled). Multiple calls play in order.+ * @param {string} text+ * @param {{ interrupt?: boolean }} [opts]+ * @returns {Promise<void>}+ */+ speak(text, opts = {}) {+ const clean = String(text || '').trim();+ if (!clean) return Promise.resolve();+ if (opts.interrupt) this.cancel();+ return new Promise((resolve) => {+ this._queue.push({ text: clean, resolve });+ if (!this._active) this._next();+ });+ }++ /** Stop everything and clear the queue. */+ cancel() {+ if (hasTTS) window.speechSynthesis.cancel();+ this._finishActive(true);+ for (const item of this._queue.splice(0)) item.resolve();+ this.onCaption(null);+ this.stage.setSpeaking(false);+ this.onState('idle');+ }++ get speaking() {+ return !!this._active;+ }++ _next() {+ const item = this._queue.shift();+ if (!item) { this.onState('idle'); this.onCaption(null); this.stage.setSpeaking(false); return; }++ const rate = this.agent?.voice?.rate || 1;+ const lipsync = createLipsync(item.text, this.stage.morph, { rate });+ const active = { text: item.text, lipsync, resolve: item.resolve, utter: null, fallbackTimer: 0 };+ this._active = active;++ this.stage.setSpeaking(true);+ this.onState('speaking');+ this.onCaption(item.text);++ if (hasTTS && !this.muted) {+ const utter = new SpeechSynthesisUtterance(item.text);+ const v = this._pickVoice();+ if (v) utter.voice = v;+ utter.lang = this.agent?.voice?.lang || v?.lang || 'en-US';+ utter.pitch = clamp(this.agent?.voice?.pitch ?? 1, 0, 2);+ utter.rate = clamp(this.agent?.voice?.rate ?? 1, 0.1, 3);+ utter.onend = () => this._finishActive(false);+ utter.onerror = (e) => {+ // Some engines fire 'interrupted'/'canceled' as errors on cancel —+ // only surface genuine synthesis failures, then fall back visually.+ if (e?.error && !/interrupt|cancel/i.test(e.error)) {+ this.onError(new Error('speech-synthesis: ' + e.error));+ this._runVisualFallback(active);+ } else {+ this._finishActive(false);+ }+ };+ active.utter = utter;+ // Safety net: if neither onend nor onerror fires (known flaky on some+ // mobile engines), close out after the estimated duration + slack.+ const guardMs = estimateDurationMs(item.text) * (1 / (utter.rate || 1)) + 1500;+ active.fallbackTimer = window.setTimeout(() => this._finishActive(false), Math.max(2500, guardMs));+ try {+ window.speechSynthesis.speak(utter);+ } catch (err) {+ this.onError(err instanceof Error ? err : new Error(String(err)));+ this._runVisualFallback(active);+ }+ } else {+ this._runVisualFallback(active);+ }+ }++ /** No audio (muted / unsupported): play the lipsync visually then advance. */+ _runVisualFallback(active) {+ if (active !== this._active) return;+ // Estimate from the morph timeline when present, else from raw text so+ // no-morph (animation-lipsync) agents still hold the caption long enough.+ const ms = active.lipsync.totalMs+ ? active.lipsync.totalMs + 350+ : Math.max(1200, estimateDurationMs(active.text) + 350);+ active.fallbackTimer = window.setTimeout(() => this._finishActive(false), ms);+ }++ _tick(nowMs) {+ this._active?.lipsync?.tick(nowMs);+ }++ _finishActive(silent) {+ const active = this._active;+ if (!active) return;+ this._active = null;+ if (active.fallbackTimer) clearTimeout(active.fallbackTimer);+ active.lipsync?.stop();+ try { active.resolve(); } catch { /* consumer callback */ }+ if (!silent) this._next();+ }++ _loadVoices() {+ if (!hasTTS) return;+ this._voices = window.speechSynthesis.getVoices() || [];+ }++ _pickVoice() {+ if (!this._voices.length) this._loadVoices();+ const prof = this.agent?.voice || {};+ const voices = this._voices;+ if (!voices.length) return null;+ // 1) explicit name matches, in priority order+ for (const needle of prof.match || []) {+ const v = voices.find((x) => x.name?.toLowerCase().includes(needle.toLowerCase()));+ if (v) return v;+ }+ // 2) language match+ if (prof.lang) {+ const v = voices.find((x) => x.lang?.toLowerCase().startsWith(prof.lang.toLowerCase().slice(0, 2)));+ if (v) return v;+ }+ // 3) first local voice, else first available+ return voices.find((x) => x.localService) || voices[0];+ }++ dispose() {+ this.cancel();+ this._frameUnsub?.();+ if (hasTTS) window.speechSynthesis.removeEventListener?.('voiceschanged', this._loadVoices);+ }+}++function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, Number(n)));+}diff --git a/page-agent-sdk/src/picker.js b/page-agent-sdk/src/picker.jsnew file mode 100644index 000000000..88f451582--- /dev/null+++ b/page-agent-sdk/src/picker.js@@ -0,0 +1,168 @@+/**+ * AvatarPicker — @three-ws/page-agent+ * ===================================+ *+ * Accessible modal grid that lets the *visitor* choose which rigged agent talks+ * to them. Every card is one rigged avatar from the catalog; selecting one+ * swaps the live agent and persists the choice (localStorage) so it sticks+ * across pages and visits. Keyboard navigable, focus-trapped, Esc to close.+ */++const STORE_KEY = 'three-ws:page-agent:agent';++const STYLE_EMOJI = { realistic: '🧑', stylized: '✨', robot: '🤖' };++export class AvatarPicker {+ /**+ * @param {import('./catalog.js').RiggedAgent[]} agents+ * @param {{ onSelect: (id:string)=>void, getCurrent: ()=>string, title?: string, subtitle?: string }} opts+ */+ constructor(agents, opts) {+ this.agents = agents;+ this.onSelect = opts.onSelect;+ this.getCurrent = opts.getCurrent;+ this.title = opts.title || 'Choose your guide';+ this.subtitle = opts.subtitle || 'Pick the rigged 3D agent who shows you around. You can switch anytime.';+ this._root = null;+ this._lastFocus = null;+ this._onKey = this._onKey.bind(this);+ this._build();+ }++ /** @returns {string|null} persisted agent id, if any. */+ static restore() {+ try { return localStorage.getItem(STORE_KEY); } catch { return null; }+ }++ static persist(id) {+ try { localStorage.setItem(STORE_KEY, id); } catch { /* private mode */ }+ }++ _build() {+ const root = document.createElement('div');+ root.className = 'tw-pa-picker';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-modal', 'true');+ root.setAttribute('aria-label', this.title);+ root.dataset.open = 'false';++ const panel = document.createElement('div');+ panel.className = 'tw-pa-panel';++ const close = document.createElement('button');+ close.className = 'tw-pa-btn tw-pa-close';+ close.setAttribute('aria-label', 'Close');+ close.innerHTML = icon('close');+ close.addEventListener('click', () => this.close());++ const h = document.createElement('h2');+ h.textContent = this.title;+ const sub = document.createElement('p');+ sub.className = 'tw-pa-sub';+ sub.textContent = this.subtitle;++ const grid = document.createElement('div');+ grid.className = 'tw-pa-grid';+ grid.setAttribute('role', 'listbox');+ grid.setAttribute('aria-label', 'Available agents');++ this._cards = [];+ for (const a of this.agents) {+ const card = document.createElement('button');+ card.className = 'tw-pa-card';+ card.type = 'button';+ card.setAttribute('role', 'option');+ card.dataset.id = a.id;+ card.style.setProperty('--tw-pa-accent2', a.accent);+ card.innerHTML = `+ <div class="tw-pa-swatch" aria-hidden="true">${STYLE_EMOJI[a.style] || '🧑'}</div>+ <span class="tw-pa-cname">${esc(a.name)}</span>+ <span class="tw-pa-ctag">${esc(a.tagline)}</span>+ <span class="tw-pa-chip">${esc(lipsyncLabel(a.lipsync))}</span>`;+ card.addEventListener('click', () => {+ AvatarPicker.persist(a.id);+ this.onSelect(a.id);+ this._mark();+ this.close();+ });+ this._cards.push(card);+ grid.appendChild(card);+ }++ panel.append(close, h, sub, grid);+ root.appendChild(panel);+ root.addEventListener('click', (e) => { if (e.target === root) this.close(); });++ this._root = root;+ this._grid = grid;+ }++ mount(parent = document.body) {+ if (!this._root.isConnected) parent.appendChild(this._root);+ }++ open() {+ this.mount();+ this._mark();+ this._lastFocus = document.activeElement;+ this._root.dataset.open = 'true';+ document.addEventListener('keydown', this._onKey, true);+ const current = this._cards.find((c) => c.getAttribute('aria-current') === 'true') || this._cards[0];+ current?.focus();+ }++ close() {+ this._root.dataset.open = 'false';+ document.removeEventListener('keydown', this._onKey, true);+ if (this._lastFocus?.focus) this._lastFocus.focus();+ }++ get isOpen() {+ return this._root?.dataset.open === 'true';+ }++ _mark() {+ const cur = this.getCurrent();+ for (const c of this._cards) c.setAttribute('aria-current', String(c.dataset.id === cur));+ }++ _onKey(e) {+ if (!this.isOpen) return;+ if (e.key === 'Escape') { e.preventDefault(); this.close(); return; }+ const focusables = this._cards.concat(this._root.querySelector('.tw-pa-close'));+ const idx = focusables.indexOf(document.activeElement);+ if (e.key === 'Tab') {+ e.preventDefault();+ const dir = e.shiftKey ? -1 : 1;+ const next = (idx + dir + focusables.length) % focusables.length;+ focusables[next]?.focus();+ } else if (['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'].includes(e.key)) {+ e.preventDefault();+ const dir = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1;+ const cardIdx = this._cards.indexOf(document.activeElement);+ const base = cardIdx < 0 ? 0 : cardIdx;+ const next = (base + dir + this._cards.length) % this._cards.length;+ this._cards[next]?.focus();+ }+ }++ dispose() {+ document.removeEventListener('keydown', this._onKey, true);+ this._root?.remove();+ }+}++function lipsyncLabel(mode) {+ return mode === 'viseme' ? 'Viseme lipsync' : mode === 'jaw' ? 'Jaw lipsync' : 'Full-body';+}++function esc(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function icon(name) {+ if (name === 'close') {+ return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>';+ }+ return '';+}diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.jsnew file mode 100644index 000000000..75f2eb544--- /dev/null+++ b/page-agent-sdk/src/stage.js@@ -0,0 +1,292 @@+/**+ * AvatarStage — @three-ws/page-agent+ * ==================================+ *+ * The 3D surface: a transparent WebGL canvas that loads a rigged glTF agent,+ * frames it (bust / upper / full), and keeps it alive with skeletal idle motion+ * — a played idle clip when the GLB ships one, otherwise a procedural breathing+ * + sway + blink loop so the agent never looks like a frozen statue (the whole+ * reason we require rigged avatars). It exposes the morph map + a per-frame hook+ * so the lipsync driver and speech narrator can drive the mouth in sync.+ *+ * Peer-depends on `three` only. Addons resolve through the consumer's bundler+ * (or the import map / inlined build for <script> usage).+ */++import {+ Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, DirectionalLight,+ Box3, Vector3, Color, Clock, PMREMGenerator, AnimationMixer, LoopRepeat,+ ACESFilmicToneMapping, SRGBColorSpace, MathUtils,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { buildMorphMap } from './lipsync.js';++const FRAMING = {+ // [vertical fraction of model height to center on, distance multiplier]+ bust: { center: 0.86, dist: 0.62, fov: 28 },+ upper: { center: 0.72, dist: 1.0, fov: 30 },+ full: { center: 0.5, dist: 1.9, fov: 32 },+};++const BLINK_MORPHS = ['eyeBlinkLeft', 'eyeBlinkRight', 'eyesClosed', 'blink'];++export class AvatarStage {+ /**+ * @param {HTMLElement} container Element the canvas fills.+ * @param {{ background?: string }} [opts]+ */+ constructor(container, opts = {}) {+ this.container = container;+ this._opts = opts;++ this.scene = new Scene();+ this._applyBackground(opts.background);++ this.canvas = document.createElement('canvas');+ this.canvas.style.cssText = 'display:block;width:100%;height:100%;outline:none';+ container.appendChild(this.canvas);++ const w = container.clientWidth || 320;+ const h = container.clientHeight || 360;++ this.camera = new PerspectiveCamera(30, w / h, 0.05, 200);+ this.camera.position.set(0, 1.5, 2.2);++ this.renderer = new WebGLRenderer({+ canvas: this.canvas, antialias: true, alpha: true, powerPreference: 'high-performance',+ });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.renderer.setSize(w, h, false);+ this.renderer.outputColorSpace = SRGBColorSpace;+ this.renderer.toneMapping = ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.05;++ const pmrem = new PMREMGenerator(this.renderer);+ this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ pmrem.dispose();++ this.scene.add(new AmbientLight(0xffffff, 0.6));+ const key = new DirectionalLight(0xffffff, 1.4);+ key.position.set(1.5, 3, 2.5);+ this.scene.add(key);+ const rim = new DirectionalLight(0x99bbff, 0.5);+ rim.position.set(-2, 2, -2);+ this.scene.add(rim);++ this.clock = new Clock();+ this.mixer = null;+ this.model = null;+ this.morph = null;+ this._idleAction = null;+ this._talkAction = null;+ this._speaking = false;+ this._loadToken = 0;+ this._frameHooks = new Set();+ this._headBone = null;+ this._blinkTargets = [];+ this._nextBlink = 1 + Math.random() * 3;+ this._blinkT = -1;+ this._reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches || false;++ this._resizeObs = new ResizeObserver(() => this._resize());+ this._resizeObs.observe(container);++ this._raf = 0;+ this._render = this._render.bind(this);+ this._raf = requestAnimationFrame(this._render);+ }++ /** Register a per-frame callback `(dtSeconds, nowMs) => void`. Returns an unsubscribe. */+ onFrame(fn) {+ this._frameHooks.add(fn);+ return () => this._frameHooks.delete(fn);+ }++ /**+ * Load a rigged GLB. Replaces any current model. Resolves once framed.+ * @param {string} url+ * @param {{ framing?: 'bust'|'upper'|'full' }} [opts]+ */+ async load(url, opts = {}) {+ const token = ++this._loadToken;+ const loader = new GLTFLoader();+ const gltf = await loader.loadAsync(url);+ if (token !== this._loadToken) return null; // superseded++ if (this.model) {+ this.scene.remove(this.model);+ this._disposeObject(this.model);+ }+ this.mixer = null;+ this._idleAction = null;+ this._talkAction = null;++ this.model = gltf.scene;+ this.scene.add(this.model);+ this.morph = buildMorphMap(this.model);+ this._collectRigRefs(this.model);++ // Animation: prefer a named idle clip; keep any talk clip for speaking.+ if (gltf.animations?.length) {+ this.mixer = new AnimationMixer(this.model);+ const idle = pickClip(gltf.animations, ['idle', 'breathing', 'stand', 'rest']) || gltf.animations[0];+ const talk = pickClip(gltf.animations, ['talk', 'talking', 'speak', 'gesture', 'wave']);+ if (idle) {+ this._idleAction = this.mixer.clipAction(idle);+ this._idleAction.setLoop(LoopRepeat, Infinity).play();+ }+ if (talk && talk !== idle) {+ this._talkAction = this.mixer.clipAction(talk);+ this._talkAction.setLoop(LoopRepeat, Infinity);+ this._talkAction.enabled = true;+ this._talkAction.setEffectiveWeight(0);+ this._talkAction.play();+ }+ }++ this._frame(opts.framing || 'upper');+ return gltf;+ }++ /** Begin/halt the talking visual state (animation weight + body emphasis). */+ setSpeaking(on) {+ this._speaking = !!on;+ if (this._talkAction) {+ // Crossfade talk-clip weight; idle stays underneath.+ this._talkAction.setEffectiveWeight(on ? 0.85 : 0);+ }+ }++ _collectRigRefs(root) {+ this._headBone = null;+ this._blinkTargets = [];+ root.traverse((node) => {+ if (node.isBone && /head/i.test(node.name) && !/headtop|end/i.test(node.name) && !this._headBone) {+ this._headBone = node;+ node.userData._restQ = node.quaternion.clone();+ }+ if (node.isMesh && node.morphTargetDictionary) {+ for (const name of BLINK_MORPHS) {+ const idx = node.morphTargetDictionary[name];+ if (idx !== undefined) this._blinkTargets.push({ mesh: node, index: idx });+ }+ }+ });+ }++ _frame(framing) {+ const conf = FRAMING[framing] || FRAMING.upper;+ const box = new Box3().setFromObject(this.model);+ const size = new Vector3();+ const center = new Vector3();+ box.getSize(size);+ box.getCenter(center);+ const height = size.y || 1.7;+ const focusY = box.min.y + height * conf.center;+ const focusX = center.x;+ const maxDim = Math.max(size.x, height) || 1;++ this.camera.fov = conf.fov;+ const fov = (conf.fov * Math.PI) / 180;+ const dist = ((maxDim / 2) / Math.tan(fov / 2)) * conf.dist;+ this.camera.position.set(focusX, focusY, box.max.z + dist);+ this.camera.near = Math.max(0.01, dist / 100);+ this.camera.far = dist * 50;+ this.camera.lookAt(focusX, focusY, center.z);+ this.camera.updateProjectionMatrix();+ this._focus = new Vector3(focusX, focusY, center.z);+ }++ _proceduralIdle(t) {+ if (this.mixer || this._reduce || !this.model) return; // clip-driven or static+ // Subtle breathing on the whole model + head sway when no skeletal clip.+ const breathe = Math.sin(t * 1.6) * 0.006;+ this.model.position.y = breathe;+ if (this._headBone && this._headBone.userData._restQ) {+ const sway = Math.sin(t * 0.6) * 0.05;+ const nod = Math.sin(t * 0.9) * 0.03 + (this._speaking ? Math.sin(t * 6) * 0.04 : 0);+ this._headBone.quaternion.copy(this._headBone.userData._restQ);+ this._headBone.rotateY(sway);+ this._headBone.rotateX(nod);+ }+ }++ _blink(dt, t) {+ if (!this._blinkTargets.length || this._reduce) return;+ if (this._blinkT < 0) {+ this._nextBlink -= dt;+ if (this._nextBlink <= 0) { this._blinkT = 0; this._nextBlink = 2 + Math.random() * 4; }+ return;+ }+ this._blinkT += dt;+ const dur = 0.16;+ const v = this._blinkT < dur / 2+ ? this._blinkT / (dur / 2)+ : 1 - (this._blinkT - dur / 2) / (dur / 2);+ const w = MathUtils.clamp(v, 0, 1);+ for (const { mesh, index } of this._blinkTargets) mesh.morphTargetInfluences[index] = w;+ if (this._blinkT >= dur) this._blinkT = -1;+ }++ _render() {+ this._raf = requestAnimationFrame(this._render);+ if (!this.renderer) return;+ const dt = Math.min(this.clock.getDelta(), 0.05);+ const t = this.clock.elapsedTime;+ const nowMs = t * 1000;+ this.mixer?.update(dt);+ this._proceduralIdle(t);+ this._blink(dt, t);+ for (const fn of this._frameHooks) {+ try { fn(dt, nowMs); } catch { /* a misbehaving hook must not kill the loop */ }+ }+ this.renderer.render(this.scene, this.camera);+ }++ _resize() {+ if (!this.renderer || !this.camera) return;+ const w = this.container.clientWidth || 1;+ const h = this.container.clientHeight || 1;+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ _applyBackground(value) {+ if (!value || value === 'transparent') { this.scene.background = null; return; }+ try { this.scene.background = new Color(value); } catch { this.scene.background = null; }+ }++ _disposeObject(obj) {+ obj.traverse?.((n) => {+ n.geometry?.dispose?.();+ const m = n.material;+ if (Array.isArray(m)) m.forEach((x) => x?.dispose?.());+ else m?.dispose?.();+ });+ }++ dispose() {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ this._resizeObs?.disconnect();+ this._frameHooks.clear();+ if (this.model) { this.scene.remove(this.model); this._disposeObject(this.model); }+ this.renderer?.dispose();+ this.renderer?.forceContextLoss?.();+ this.renderer = null;+ this.canvas?.remove();+ this.scene = null;+ this.camera = null;+ this.model = null;+ }+}++function pickClip(clips, hints) {+ for (const hint of hints) {+ const found = clips.find((c) => c.name && c.name.toLowerCase().includes(hint));+ if (found) return found;+ }+ return null;+}diff --git a/page-agent-sdk/src/styles.js b/page-agent-sdk/src/styles.jsnew file mode 100644index 000000000..c0889dccd--- /dev/null+++ b/page-agent-sdk/src/styles.js@@ -0,0 +1,200 @@+/**+ * Injected stylesheet for @three-ws/page-agent. Scoped under `.tw-pa-*` class+ * names and injected once. Honors prefers-reduced-motion and prefers-color-scheme,+ * and exposes `--tw-pa-accent` so each agent can tint its own chrome.+ */++const STYLE_ID = 'tw-page-agent-styles';++export const CSS = `+.tw-pa-root {+ position: fixed;+ z-index: 2147483000;+ --tw-pa-accent: #6366f1;+ --tw-pa-bg: rgba(17, 18, 24, 0.92);+ --tw-pa-fg: #f4f4f6;+ --tw-pa-muted: rgba(244, 244, 246, 0.6);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;+ color: var(--tw-pa-fg);+ -webkit-font-smoothing: antialiased;+ box-sizing: border-box;+}+.tw-pa-root *, .tw-pa-root *::before, .tw-pa-root *::after { box-sizing: border-box; }+.tw-pa-root[data-pos="bottom-right"] { right: 20px; bottom: 20px; }+.tw-pa-root[data-pos="bottom-left"] { left: 20px; bottom: 20px; }+.tw-pa-root[data-pos="top-right"] { right: 20px; top: 20px; }+.tw-pa-root[data-pos="top-left"] { left: 20px; top: 20px; }++.tw-pa-dock {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 8px;+ width: 240px;+ max-width: calc(100vw - 40px);+}++.tw-pa-stage {+ position: relative;+ width: 240px;+ height: 280px;+ max-width: calc(100vw - 40px);+ border-radius: 20px;+ overflow: hidden;+ background:+ radial-gradient(120% 80% at 50% 0%, color-mix(in srgb, var(--tw-pa-accent) 26%, transparent), transparent 70%),+ var(--tw-pa-bg);+ box-shadow: 0 18px 50px -12px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06) inset;+ transition: transform .35s cubic-bezier(.2,.8,.2,1), opacity .35s ease;+ cursor: grab;+}+.tw-pa-stage:active { cursor: grabbing; }+.tw-pa-root[data-state="collapsed"] .tw-pa-stage { display: none; }+.tw-pa-stage canvas { border-radius: inherit; }++.tw-pa-name {+ position: absolute; left: 12px; top: 10px;+ display: inline-flex; align-items: center; gap: 6px;+ padding: 4px 10px; border-radius: 999px;+ font-size: 12px; font-weight: 600; letter-spacing: .01em;+ background: rgba(0,0,0,0.35); backdrop-filter: blur(6px);+ border: 1px solid rgba(255,255,255,0.08);+}+.tw-pa-name::before {+ content: ''; width: 7px; height: 7px; border-radius: 50%;+ background: var(--tw-pa-accent); box-shadow: 0 0 8px var(--tw-pa-accent);+}+.tw-pa-root[data-state="speaking"] .tw-pa-name::before { animation: tw-pa-pulse 1s ease-in-out infinite; }++.tw-pa-caption {+ position: absolute; left: 10px; right: 10px; bottom: 10px;+ padding: 10px 12px; border-radius: 14px;+ font-size: 13px; line-height: 1.4;+ background: rgba(0,0,0,0.55); backdrop-filter: blur(8px);+ border: 1px solid rgba(255,255,255,0.08);+ opacity: 0; transform: translateY(8px);+ transition: opacity .25s ease, transform .25s ease;+ max-height: 45%; overflow: auto;+}+.tw-pa-caption[data-show="true"] { opacity: 1; transform: translateY(0); }++.tw-pa-bar {+ display: flex; align-items: center; gap: 6px;+ padding: 6px; border-radius: 16px;+ background: var(--tw-pa-bg);+ box-shadow: 0 10px 30px -10px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.06) inset;+}+.tw-pa-btn {+ appearance: none; border: 0; cursor: pointer;+ width: 36px; height: 36px; border-radius: 11px;+ display: inline-flex; align-items: center; justify-content: center;+ background: rgba(255,255,255,0.06); color: var(--tw-pa-fg);+ transition: background .15s ease, transform .1s ease;+}+.tw-pa-btn:hover { background: rgba(255,255,255,0.14); }+.tw-pa-btn:active { transform: scale(.94); }+.tw-pa-btn:focus-visible { outline: 2px solid var(--tw-pa-accent); outline-offset: 2px; }+.tw-pa-btn[aria-pressed="true"] { background: color-mix(in srgb, var(--tw-pa-accent) 75%, transparent); color: #fff; }+.tw-pa-btn svg { width: 18px; height: 18px; pointer-events: none; }+.tw-pa-btn[data-grow] { width: auto; padding: 0 12px; gap: 6px; font-size: 13px; font-weight: 600; }+.tw-pa-spacer { flex: 1; }++/* Launcher pill shown when collapsed */+.tw-pa-launcher {+ appearance: none; border: 0; cursor: pointer;+ display: inline-flex; align-items: center; gap: 8px;+ padding: 10px 14px 10px 10px; border-radius: 999px;+ background: var(--tw-pa-bg); color: var(--tw-pa-fg);+ box-shadow: 0 12px 34px -10px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06) inset;+ font-size: 13px; font-weight: 600;+ transition: transform .15s ease;+}+.tw-pa-launcher:hover { transform: translateY(-1px); }+.tw-pa-launcher .tw-pa-orb {+ width: 30px; height: 30px; border-radius: 50%;+ background: radial-gradient(circle at 35% 30%, #fff, var(--tw-pa-accent) 70%);+ box-shadow: 0 0 14px color-mix(in srgb, var(--tw-pa-accent) 60%, transparent);+}+.tw-pa-root[data-state="collapsed"] .tw-pa-dock { display: none; }+.tw-pa-root:not([data-state="collapsed"]) .tw-pa-launcher { display: none; }++/* Picker overlay */+.tw-pa-picker {+ position: fixed; inset: 0; z-index: 2147483001;+ display: flex; align-items: center; justify-content: center;+ padding: 24px;+ background: rgba(8,8,12,0.62); backdrop-filter: blur(6px);+ opacity: 0; pointer-events: none; transition: opacity .2s ease;+}+.tw-pa-picker[data-open="true"] { opacity: 1; pointer-events: auto; }+.tw-pa-panel {+ width: min(720px, 100%); max-height: min(80vh, 640px); overflow: auto;+ background: #14151c; color: var(--tw-pa-fg);+ border-radius: 24px; padding: 22px;+ box-shadow: 0 30px 80px -20px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.07) inset;+ transform: translateY(12px) scale(.98); transition: transform .25s cubic-bezier(.2,.8,.2,1);+}+.tw-pa-picker[data-open="true"] .tw-pa-panel { transform: none; }+.tw-pa-panel h2 { margin: 0 0 2px; font-size: 19px; }+.tw-pa-panel p.tw-pa-sub { margin: 0 0 18px; color: var(--tw-pa-muted); font-size: 13px; }+.tw-pa-grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px;+}+.tw-pa-card {+ text-align: left; cursor: pointer; appearance: none;+ border: 1px solid rgba(255,255,255,0.08); border-radius: 16px;+ background: rgba(255,255,255,0.03); color: inherit;+ padding: 14px; display: flex; flex-direction: column; gap: 4px;+ transition: border-color .15s ease, background .15s ease, transform .1s ease;+}+.tw-pa-card:hover { background: rgba(255,255,255,0.07); transform: translateY(-2px); }+.tw-pa-card:focus-visible { outline: 2px solid var(--tw-pa-accent2, #6366f1); outline-offset: 2px; }+.tw-pa-card[aria-current="true"] { border-color: var(--tw-pa-accent2); background: color-mix(in srgb, var(--tw-pa-accent2) 16%, transparent); }+.tw-pa-swatch {+ width: 100%; aspect-ratio: 4 / 3; border-radius: 11px; margin-bottom: 8px;+ background: radial-gradient(120% 90% at 50% 18%, color-mix(in srgb, var(--tw-pa-accent2) 60%, transparent), #0c0d12 75%);+ display: flex; align-items: flex-end; justify-content: center;+ font-size: 40px; line-height: 1; padding-bottom: 8px;+ border: 1px solid rgba(255,255,255,0.06);+}+.tw-pa-card .tw-pa-cname { font-weight: 700; font-size: 15px; }+.tw-pa-card .tw-pa-ctag { font-size: 12px; color: var(--tw-pa-muted); }+.tw-pa-chip {+ align-self: flex-start; margin-top: 6px;+ font-size: 10px; text-transform: uppercase; letter-spacing: .06em;+ padding: 3px 7px; border-radius: 999px;+ background: rgba(255,255,255,0.06); color: var(--tw-pa-muted);+}+.tw-pa-close {+ position: absolute; top: 18px; right: 22px;+}++@keyframes tw-pa-pulse { 0%,100% { transform: scale(1); opacity: 1 } 50% { transform: scale(1.6); opacity: .5 } }++@media (prefers-color-scheme: light) {+ .tw-pa-root { --tw-pa-bg: rgba(255,255,255,0.92); --tw-pa-fg: #15151b; --tw-pa-muted: rgba(20,20,28,0.6); }+ .tw-pa-name, .tw-pa-caption { background: rgba(255,255,255,0.7); color: #15151b; }+ .tw-pa-panel { background: #fbfbfd; color: #15151b; }+ .tw-pa-card { border-color: rgba(0,0,0,0.08); background: rgba(0,0,0,0.02); }+ .tw-pa-card:hover { background: rgba(0,0,0,0.05); }+}+@media (prefers-reduced-motion: reduce) {+ .tw-pa-stage, .tw-pa-caption, .tw-pa-panel, .tw-pa-launcher, .tw-pa-card { transition: none; }+ .tw-pa-name::before { animation: none; }+}+@media (max-width: 480px) {+ .tw-pa-stage, .tw-pa-dock { width: min(70vw, 240px); }+ .tw-pa-stage { height: min(60vw, 280px); }+}+`;++let _injected = false;++export function injectStyles(doc = document) {+ if (_injected || doc.getElementById(STYLE_ID)) { _injected = true; return; }+ const el = doc.createElement('style');+ el.id = STYLE_ID;+ el.textContent = CSS;+ doc.head.appendChild(el);+ _injected = true;+}diff --git a/public/changelog.json b/public/changelog.jsonindex d3c5a928a..9430d182c 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T21:52:42.980Z",+ "generated_at": "2026-06-19T22:02:31.198Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -199,6 +199,16 @@"infra"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Filter the avatar gallery by rigged vs static",+ "summary": "Every public avatar is now classified by whether it carries a skeleton — rigged models can play the animation library straight away, while static ones are geometry only until you auto-rig them. The gallery shows a green \"Rigged\" or grey \"Not rigged\" badge in the corner of each card, adds a Rig filter so you can show just the animation-ready avatars, and a \"Rigged first\" sort. Deep links keep your filter, so you can share a view of only the rigged avatars.",+ "link": "/gallery",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",@@ -650,6 +660,16 @@"fix"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Walk Playground now has two modes you can switch between",+ "summary": "Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 4f2cb9683..4a6854a01 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -158,6 +158,14 @@<category>improvement</category><description>Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews.</description></item>+ <item>+ <title>Filter the avatar gallery by rigged vs static</title>+ <link>https://three.ws/gallery</link>+ <guid isPermaLink="false">2026-06-19:Filter the avatar gallery by rigged vs static</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every public avatar is now classified by whether it carries a skeleton — rigged models can play the animation library straight away, while static ones are geometry only until you auto-rig them. The gallery shows a green "Rigged" or grey "Not rigged" badge in the corner of each card, adds a Rig filter so you can show just the animation-ready avatars, and a "Rigged first" sort. Deep links keep your filter, so you can share a view of only the rigged avatars.</description>+ </item><item><title>Fixed broken links and added retry on failed loads across the app</title><link>https://three.ws/changelog</link>@@ -510,6 +518,14 @@<category>fix</category><description>When you walked the little robot off a ledge it could plummet faster than the page could keep up and slip off the bottom of the screen, leaving you unable to find it. The camera now tracks falls tightly and keeps the character in view, and on pages that can't scroll it catches the character and drops it right back into view.</description></item>+ <item>+ <title>Walk Playground now has two modes you can switch between</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-19:Walk Playground now has two modes you can switch between</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page.</description>+ </item><item><title>Walk the whole page — the site is now a playground</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 33666937d..c37ceb12e 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T21:52:42.964Z",+ "generated_at": "2026-06-19T22:02:31.187Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/gallery/gallery.css b/public/gallery/gallery.cssindex eb26d27aa..769524019 100644--- a/public/gallery/gallery.css+++ b/public/gallery/gallery.css@@ -396,6 +396,42 @@ body.gallery-page {-webkit-backdrop-filter: blur(6px);border: 1px solid rgba(255, 255, 255, 0.18);}+/* Rig classifier badge — top-left, opposite the 3D pill. */+.gallery-card-rig {+ position: absolute;+ top: 10px;+ left: 10px;+ z-index: 1;+}+.rig-badge {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ padding: 4px 8px;+ border-radius: 99px;+ backdrop-filter: blur(6px);+ -webkit-backdrop-filter: blur(6px);+ border: 1px solid rgba(255, 255, 255, 0.18);+ color: #fff;+ background: rgba(0, 0, 0, 0.55);+}+.rig-badge--rigged {+ background: rgba(34, 197, 94, 0.28);+ border-color: rgba(74, 222, 128, 0.55);+}+.rig-badge--static {+ background: rgba(0, 0, 0, 0.5);+ color: rgba(255, 255, 255, 0.82);+}+.rig-badge-joints {+ font-weight: 600;+ opacity: 0.85;+}+.gallery-card-play {position: absolute;left: 50%;diff --git a/public/gallery/gallery.js b/public/gallery/gallery.jsindex 5c86972d8..7ebab4bdd 100644--- a/public/gallery/gallery.js+++ b/public/gallery/gallery.js@@ -19,6 +19,8 @@ const els = {sort: document.querySelector('[data-role="sort"]'),catWrap: document.querySelector('[data-role="cat-wrap"]'),cats: document.querySelector('[data-role="cats"]'),+ rigWrap: document.querySelector('[data-role="rig-wrap"]'),+ rigs: document.querySelector('[data-role="rigs"]'),tagWrap: document.querySelector('[data-role="tag-wrap"]'),tags: document.querySelector('[data-role="tags"]'),grid: document.querySelector('[data-role="grid"]'),@@ -35,6 +37,7 @@ const state = {query: initialParams.get('q') || '',tag: initialParams.get('tag') || '',category: initialParams.get('category') || '',+ rigged: initialParams.get('rigged') || '',sortBy: initialParams.get('sort') || 'newest',cursor: null,loading: false,@@ -63,6 +66,7 @@ function syncUrl() {const p = new URLSearchParams();if (state.query) p.set('q', state.query);if (state.category) p.set('category', state.category);+ if (state.rigged) p.set('rigged', state.rigged);if (state.tag) p.set('tag', state.tag);if (state.sortBy !== 'newest') p.set('sort', state.sortBy);const qs = p.toString();@@ -122,6 +126,16 @@ els.cats?.addEventListener('click', (e) => {resetAndLoad();});+els.rigs?.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-rig]');+ if (!btn) return;+ const rig = btn.dataset.rig === state.rigged ? '' : btn.dataset.rig;+ state.rigged = rig;+ renderRigs();+ syncUrl();+ resetAndLoad();+});+els.loadMore.addEventListener('click', () => loadPage());els.status.addEventListener('click', (e) => {@@ -172,12 +186,14 @@ function clearAllFilters() {state.query = '';state.tag = '';state.category = '';+ state.rigged = '';state.sortBy = 'newest';els.search.value = '';if (els.sort) els.sort.value = 'newest';updateSearchClearVisibility();renderTags();renderCats();+ renderRigs();syncUrl();resetAndLoad();}@@ -229,6 +245,7 @@ async function loadPage() {const params = new URLSearchParams();if (state.query) params.set('q', state.query);if (state.category) params.set('category', state.category);+ if (state.rigged) params.set('rigged', state.rigged);if (state.tag) params.set('tag', state.tag);if (state.cursor) params.set('cursor', state.cursor);params.set('limit', '24');@@ -243,11 +260,19 @@ async function loadPage() {let avatars = Array.isArray(data.avatars) ? data.avatars : [];- // Client-side sort+ // Client-side sort (applies within the loaded set, like the server's+ // newest-first default does across pages).if (state.sortBy === 'alpha') {avatars = [...avatars].sort((a, b) =>(a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),);+ } else if (state.sortBy === 'rigged') {+ // Rigged first, then by newest within each bucket.+ avatars = [...avatars].sort(+ (a, b) =>+ Number(isRigged(b)) - Number(isRigged(a)) ||+ new Date(b.created_at || 0) - new Date(a.created_at || 0),+ );}for (const a of avatars) {@@ -268,7 +293,7 @@ async function loadPage() {els.loadMore.hidden = !state.cursor;if (els.grid.children.length === 0) {- const filtersActive = !!state.query || !!state.tag || !!state.category;+ const filtersActive = !!state.query || !!state.tag || !!state.category || !!state.rigged;els.status.innerHTML = filtersActive? `<div class="gallery-empty"><div class="gallery-empty-art">🔍</div>@@ -340,6 +365,30 @@ function renderCats() {.join('');}+const RIG_LABELS = [+ { value: '', label: 'All' },+ { value: 'rigged', label: '⛹ Rigged' },+ { value: 'static', label: '▢ Not rigged' },+];++function renderRigs() {+ if (!els.rigs) return;+ els.rigs.innerHTML = RIG_LABELS.map(+ ({ value, label }) =>+ `<button type="button" class="gallery-tag${+ value === state.rigged ? ' is-active' : ''+ }" data-rig="${escapeAttr(value)}">${escapeHtml(label)}</button>`,+ ).join('');+}++// Classify a card's rig state via the shared classifier (window.twsRig bridge),+// degrading to source_meta inspection if the module hasn't loaded yet.+function isRigged(a) {+ if (window.twsRig?.classifyRig) return window.twsRig.classifyRig(a).rigged;+ const m = a?.source_meta || {};+ return m.is_rigged === true || (typeof m.skeleton_joint_count === 'number' && m.skeleton_joint_count > 0);+}+function renderCard(a) {const card = document.createElement('article');card.className = 'gallery-card';@@ -384,10 +433,13 @@ function renderCard(a) {? window.twsOnchainBadge.onchainBadgeHTML(a, { link: false, showChain: true, size: 'sm' }): '';+ const rigBadge = window.twsRig?.rigBadgeHTML ? window.twsRig.rigBadgeHTML(a) : '';+card.innerHTML = `<a class="gallery-card-thumb" href="${escapeAttr(viewerUrl)}" aria-label="View ${escapeAttr(a.name || 'Avatar')} in 3D viewer">${thumbContent}<span class="gallery-card-3dpill">3D</span>+ ${rigBadge ? `<span class="gallery-card-rig">${rigBadge}</span>` : ''}<span class="gallery-card-play" aria-hidden="true">▶</span></a><div class="gallery-card-body">@@ -648,6 +700,7 @@ function openAvatarEmbedModal({ avatarId, glbUrl, name }) {}renderCats();+renderRigs();resetAndLoad();// =============================================================================diff --git a/public/gallery/index.html b/public/gallery/index.htmlindex 2298c2e5b..0839c4799 100644--- a/public/gallery/index.html+++ b/public/gallery/index.html@@ -124,6 +124,7 @@<select id="gallery-sort" data-role="sort"><option value="newest">Newest</option><option value="alpha">A → Z</option>+ <option value="rigged">Rigged first</option></select></div></div>@@ -131,6 +132,10 @@<div class="gallery-tag-label">Category</div><div class="gallery-cats" data-role="cats"></div></div>+ <div class="gallery-cat-wrap" data-role="rig-wrap">+ <div class="gallery-tag-label">Rig</div>+ <div class="gallery-cats" data-role="rigs"></div>+ </div><div class="gallery-tag-wrap" data-role="tag-wrap" hidden><div class="gallery-tag-label">Tags</div><div class="gallery-tags" data-role="tags"></div>@@ -177,6 +182,8 @@<!-- Sets window.twsOnchainBadge for the static gallery.js (bundled by Vite). --><script type="module">import '/src/shared/onchain-badge.js';</script>+ <!-- Sets window.twsRig (rig classifier + badge) for the static gallery.js. -->+ <script type="module">import '/src/shared/rig-classify.js';</script><!-- Wires the hero "Create from template" button. --><script type="module">import '/src/shared/template-picker.js';</script><script type="module" src="/gallery/gallery.js"></script>diff --git a/src/avatar-rig.js b/src/avatar-rig.jsindex a8ac40d55..65c946241 100644--- a/src/avatar-rig.js+++ b/src/avatar-rig.js@@ -19,6 +19,7 @@import { saveRemoteGlbToAccount } from './account.js';import { log } from './shared/log.js';+import { classifyRig } from './shared/rig-classify.js';const POLL_INTERVAL_MS = 2500;const POLL_TIMEOUT_MS = 5 * 60 * 1000; // auto-rig backends finish well within 5 min@@ -29,23 +30,14 @@ const POLL_TIMEOUT_MS = 5 * 60 * 1000; // auto-rig backends finish well within 5* Derive a human-meaningful rig status from an avatar's source_meta. The* reconstruct pipeline stamps is_rigged / skeleton_joint_count when it* inspects a delivered GLB (api/_lib/glb-inspect.js); uploads that were never- * inspected leave it unknown.+ * inspected leave it unknown. Thin adapter over the shared classifier+ * (src/shared/rig-classify.js) — kept for back-compat with this module's+ * callers, which expect the { rigged, known, jointCount } shape.* @returns {{ rigged: boolean, known: boolean, jointCount: number|null }}*/export function getRigStatus(avatar) {- const meta = avatar?.source_meta || {};- const flag = meta.is_rigged;- const jointCount =- typeof meta.skeleton_joint_count === 'number' ? meta.skeleton_joint_count : null;- if (flag === true || (jointCount != null && jointCount > 0)) {- return { rigged: true, known: true, jointCount };- }- if (flag === false) {- return { rigged: false, known: true, jointCount: jointCount ?? 0 };- }- // is_rigged absent — an upload we never skeleton-inspected. Treat as unknown- // so the UI offers to rig rather than falsely claiming "static".- return { rigged: false, known: false, jointCount };+ const { rigged, known, jointCount } = classifyRig(avatar);+ return { rigged, known, jointCount };}// /api/config is small and stable for the session — fetch once.diff --git a/src/club.js b/src/club.jsindex ea5db91a3..41ae6bf34 100644--- a/src/club.js+++ b/src/club.js@@ -458,16 +458,17 @@ const POLE_COLORS = [0xff3bd6, 0x4ad6ff, 0xff8a3b, 0x9b5dff];// Dancer registry — display names, bios, accent palette, and the avatar each// dancer wears. A local `avatar` path loads that GLB directly; an `avatarId`// is resolved through /api/avatars/:id at boot (see resolveDancerAvatarUrl).-// The three are deliberately three DISTINCT bundled rigs so the lineup never-// collapses onto one look: Boss Vernington keeps his canonical soldier rig,-// while Dylan and Nich take two other bundled rigs the picker already verifies.-// attachAvatar still falls back to the default rig if a rig ever isn't drivable,-// so a dancer is never frozen, and each is tinted with their pole's accent color-// so the three read as a set.+// The three rigs are deliberately DISTINCT and, critically, VERIFIED-DRIVABLE:+// the club's clip library retargets idle/walk onto them so each dancer idles in+// her resting stance and her legs actually move when she walks to the pole —+// never a T-pose. Only swap a rig here for another the clip library can drive+// (gallery rigs that fail retarget bind in their T-pose). attachAvatar still+// falls back to the default rig if a rig ever isn't drivable, and each dancer is+// tinted with her pole's accent color so the three read as a set.const DANCER_META = [- { name: 'Dylan', bio: 'Neon pink heat. Fast, precise, relentless.', palette: 'pink', avatar: '/avatars/studio.glb' },- { name: 'Nich', bio: 'Cyan cool. Fluid, hypnotic, in control.', palette: 'cyan', avatar: '/avatars/mannequin.glb' },- { name: 'Boss Vernington', bio: 'Amber muscle. Pure power on the pole.', palette: 'amber', avatar: '/animations/soldier.glb' },+ { name: 'Dylan', bio: 'Neon pink heat. Fast, precise, relentless.', palette: 'pink', avatarId: '25195a2e-130c-4da5-8cad-8e7490d69b45' },+ { name: 'Nich', bio: 'Cyan cool. Fluid, hypnotic, in control.', palette: 'cyan', avatar: '/avatars/michelle.glb' },+ { name: 'Boss Vernington', bio: 'Amber muscle. Pure power on the pole.', palette: 'amber', avatarId: 'd92b292e-c2db-40cb-bf88-3e141c6b0057' },];// Every dancer is scaled to this standing height (metres) so a mix ofdiff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.jsindex 82c3d407e..a0ed0ea65 100644--- a/src/dashboard-next/pages/avatars.js+++ b/src/dashboard-next/pages/avatars.js@@ -12,6 +12,7 @@ import { openAvatarPicker } from '../../avatar-gallery-picker.js';import { createFromTemplate } from '../../shared/template-picker.js';import { onchainBadgeHTML, ensureOnchainBadgeStyles } from '../../shared/onchain-badge.js';import { walletChipHTML, wireWalletChips } from '../../shared/agent-wallet-chip.js';+import { rigBadgeHTML, matchesRigFilter, RIG_FILTERS } from '../../shared/rig-status.js';const PAGE_SIZE = 24;const VISIBILITIES = ['public', 'unlisted', 'private'];@@ -38,7 +39,7 @@ const state = {loaded: false,nextCursor: /** @type {string|null} */ (null),loadingMore: false,- filter: { q: '', visibility: 'all', sort: 'newest' },+ filter: { q: '', visibility: 'all', rigged: 'all', sort: 'newest' },io: /** @type {IntersectionObserver|null} */ (null),// Community ("all public avatars") view — independent data + filter slice so// switching tabs never clobbers the user's own list state.@@ -50,7 +51,7 @@ const state = {total: /** @type {number|null} */ (null),totalViews: /** @type {number|null} */ (null),loadedTags: /** @type {Set<string>} */ (new Set()),- filter: { q: '', tag: '', sort: 'newest' },+ filter: { q: '', tag: '', rigged: 'all', sort: 'newest' },io: /** @type {IntersectionObserver|null} */ (null),searchTimer: /** @type {any} */ (null),},@@ -104,6 +105,11 @@ const state = {<button type="button" class="dn-av-chip${v === 'all' ? ' active' : ''}" data-vis-chip="${v}" role="tab" aria-selected="${v === 'all'}">${v[0].toUpperCase() + v.slice(1)}</button>`).join('')}</div>+ <div class="dn-av-chips" role="tablist" aria-label="Rig filter">+ ${RIG_FILTERS.map((f) => `+ <button type="button" class="dn-av-chip${f.key === 'all' ? ' active' : ''}" data-rig-chip="${f.key}" role="tab" aria-selected="${f.key === 'all'}">${f.label}</button>+ `).join('')}+ </div><label class="dn-av-sort"><select data-sort aria-label="Sort">${SORTS.map((s) => `<option value="${s.key}">${s.label}</option>`).join('')}@@ -116,6 +122,11 @@ const state = {<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3"/></svg><input type="search" placeholder="Search the community gallery…" data-cq autocomplete="off" aria-label="Search the community gallery" /></label>+ <div class="dn-av-chips" role="tablist" aria-label="Rig filter">+ ${RIG_FILTERS.map((f) => `+ <button type="button" class="dn-av-chip${f.key === 'all' ? ' active' : ''}" data-crig-chip="${f.key}" role="tab" aria-selected="${f.key === 'all'}">${f.label}</button>+ `).join('')}+ </div><label class="dn-av-sort"><select data-csort aria-label="Sort community avatars">${COMMUNITY_SORTS.map((s) => `<option value="${s.key}">${s.label}</option>`).join('')}@@ -283,6 +294,7 @@ async function loadCommunityInitial(root) {const params = new URLSearchParams({ limit: String(PAGE_SIZE), totals: '1' });if (c.filter.q) params.set('q', c.filter.q);if (c.filter.tag) params.set('tag', c.filter.tag);+ if (c.filter.rigged !== 'all') params.set('rigged', c.filter.rigged);const data = await get(`/api/avatars/public?${params.toString()}`);const rows = Array.isArray(data?.avatars) ? data.avatars : [];c.all = rows;@@ -314,6 +326,7 @@ async function loadCommunityMore(root) {const params = new URLSearchParams({ limit: String(PAGE_SIZE), cursor: c.nextCursor });if (c.filter.q) params.set('q', c.filter.q);if (c.filter.tag) params.set('tag', c.filter.tag);+ if (c.filter.rigged !== 'all') params.set('rigged', c.filter.rigged);const data = await get(`/api/avatars/public?${params.toString()}`);const more = Array.isArray(data?.avatars) ? data.avatars : [];c.all = c.all.concat(more);@@ -352,6 +365,20 @@ function wireCommunityFilters(root) {renderCommunityGrid(root);});+ root.querySelectorAll('[data-crig-chip]').forEach((btn) => {+ btn.addEventListener('click', () => {+ const v = btn.getAttribute('data-crig-chip');+ if (c.filter.rigged === v) return;+ c.filter.rigged = v;+ root.querySelectorAll('[data-crig-chip]').forEach((x) => {+ const on = x === btn;+ x.classList.toggle('active', on);+ x.setAttribute('aria-selected', on ? 'true' : 'false');+ });+ loadCommunityInitial(root);+ });+ });+const tagsHost = root.querySelector('[data-community-tags]');tagsHost.addEventListener('click', (e) => {const btn = e.target.closest('[data-tag]');@@ -383,6 +410,19 @@ function wireFilters(root) {});});+ root.querySelectorAll('[data-rig-chip]').forEach((b) => {+ b.addEventListener('click', () => {+ const v = b.getAttribute('data-rig-chip');+ state.filter.rigged = v;+ root.querySelectorAll('[data-rig-chip]').forEach((x) => {+ const on = x === b;+ x.classList.toggle('active', on);+ x.setAttribute('aria-selected', on ? 'true' : 'false');+ });+ renderGrid(root);+ });+ });+const sortSel = root.querySelector('[data-sort]');sortSel.addEventListener('change', () => {state.filter.sort = sortSel.value;@@ -449,10 +489,11 @@ function wireNewMenu(root) {// ── Filtering / rendering ────────────────────────────────────────────────function applyFilter(rows) {- const { q, visibility, sort } = state.filter;+ const { q, visibility, rigged, sort } = state.filter;let out = rows;if (q) out = out.filter((a) => (a.name || '').toLowerCase().includes(q));if (visibility !== 'all') out = out.filter((a) => (a.visibility || 'private') === visibility);+ if (rigged !== 'all') out = out.filter((a) => matchesRigFilter(a, rigged));const cmp = SORTS.find((s) => s.key === sort)?.cmp;if (cmp) out = [...out].sort(cmp);return out;diff --git a/src/shared/rig-classify.js b/src/shared/rig-classify.jsnew file mode 100644index 000000000..50085c091--- /dev/null+++ b/src/shared/rig-classify.js@@ -0,0 +1,68 @@+/**+ * Rig classifier — the single source of truth for "is this 3D avatar rigged?"+ *+ * A rigged model carries a skeleton (glTF `skins[]` with joints) and can play+ * the platform's animation library; a static mesh has geometry only and must be+ * auto-rigged before it can move. The reconstruct / upload pipeline stamps the+ * signal into `source_meta` when it inspects a delivered GLB+ * (api/_lib/glb-inspect.js): `is_rigged` (boolean) and `skeleton_joint_count`.+ *+ * This module is intentionally dependency-free so it can be imported by the+ * public gallery, the avatar editor, pickers, and any other surface without+ * dragging in the rigging panel's heavier deps. The SQL filter in+ * api/_lib/avatars.js (searchPublicAvatars) mirrors the exact same logic so a+ * server-filtered list and a client-classified badge never disagree.+ */++/** @typedef {'rigged'|'static'|'unknown'} RigCategory */++/**+ * Classify an avatar's rig state from its `source_meta`.+ *+ * - `rigged` — has a skeleton (flag true, or a positive joint count).+ * - `static` — inspected and confirmed to have no skeleton.+ * - `unknown` — never skeleton-inspected (older upload); we don't claim either+ * way so the UI can offer to rig rather than mislabel it "static".+ *+ * @param {{ source_meta?: Record<string, any> } | null | undefined} avatar+ * @returns {{ category: RigCategory, rigged: boolean, known: boolean, jointCount: number|null }}+ */+export function classifyRig(avatar) {+ const meta = avatar?.source_meta || {};+ const flag = meta.is_rigged;+ const jointCount =+ typeof meta.skeleton_joint_count === 'number' ? meta.skeleton_joint_count : null;++ if (flag === true || (jointCount != null && jointCount > 0)) {+ return { category: 'rigged', rigged: true, known: true, jointCount };+ }+ if (flag === false) {+ return { category: 'static', rigged: false, known: true, jointCount: jointCount ?? 0 };+ }+ return { category: 'unknown', rigged: false, known: false, jointCount };+}++/**+ * A small badge for avatar cards/detail views. Returns '' when the rig state is+ * unknown so we never paint a misleading label on un-inspected uploads.+ *+ * @param {Parameters<typeof classifyRig>[0]} avatar+ * @param {{ joints?: boolean }} [opts] — when true, append the joint count to a rigged badge.+ * @returns {string} HTML string (caller controls placement)+ */+export function rigBadgeHTML(avatar, opts = {}) {+ const { category, jointCount } = classifyRig(avatar);+ if (category === 'unknown') return '';+ if (category === 'rigged') {+ const joints =+ opts.joints && jointCount ? ` <span class="rig-badge-joints">${jointCount}</span>` : '';+ return `<span class="rig-badge rig-badge--rigged" title="Skeleton-ready — plays the animation library">⛹ Rigged${joints}</span>`;+ }+ return `<span class="rig-badge rig-badge--static" title="Static mesh — auto-rig it to animate">▢ Static</span>`;+}++if (typeof window !== 'undefined') {+ // Convenience handle for the static (non-bundled) public/gallery script,+ // mirroring the window.twsOnchainBadge bridge.+ window.twsRig = { classifyRig, rigBadgeHTML };+}diff --git a/src/shared/rig-status.js b/src/shared/rig-status.jsnew file mode 100644index 000000000..1aa3bf255--- /dev/null+++ b/src/shared/rig-status.js@@ -0,0 +1,90 @@+/**+ * Dashboard UI layer for the rigged-or-not category — the styled pill and the+ * filter chips shared by the agents and avatars list pages.+ *+ * The *predicate* (is this avatar rigged?) lives in ./rig-classify.js, which is+ * also mirrored by the SQL filter in api/_lib/avatars.js. This module owns only+ * presentation: an injected stylesheet (the gallery's `.rig-badge` styles aren't+ * in scope inside dashboard-next) plus a binary filter the chips drive. Keeping+ * classification in one place means a server-filtered list and a client-painted+ * badge can never disagree.+ *+ * Mirrors the design of shared/onchain-badge.js.+ */++import { classifyRig } from './rig-classify.js';++const STYLE_ID = 'tws-rig-badge-styles';++/**+ * Canonical binary view of the rig state, delegating to classifyRig so there is+ * a single source of truth. Rigged ⇔ a confirmed skeleton; everything else+ * (confirmed-static and never-inspected uploads alike) is not rigged.+ * @param {object|null|undefined} avatar+ * @returns {boolean}+ */+export function isRigged(avatar) {+ return classifyRig(avatar).rigged;+}++/**+ * Does an avatar pass the active rig filter? `'all'` always passes; a missing+ * avatar (e.g. an agent with no body) only passes `'all'` and `'static'`.+ * @param {object|null|undefined} avatar+ * @param {'all'|'rigged'|'static'} filter+ */+export function matchesRigFilter(avatar, filter) {+ if (!filter || filter === 'all') return true;+ if (filter === 'rigged') return isRigged(avatar);+ return !isRigged(avatar); // 'static' — includes no-avatar / uninspected+}++/** Filter chip definitions, shared so every list surface offers the same options. */+export const RIG_FILTERS = [+ { key: 'all', label: 'All' },+ { key: 'rigged', label: 'Rigged' },+ { key: 'static', label: 'Static' },+];++const RIGGED_ICON = `<svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="3" r="1.6"/><path d="M8 4.6v4M8 5.6 4.8 7.4M8 5.6l3.2 1.8M8 8.6 5.4 13M8 8.6 10.6 13"/></svg>`;+const STATIC_ICON = `<svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 1.8 13.5 4.9v6.2L8 14.2 2.5 11.1V4.9z"/><path d="M2.6 5 8 8.1 13.4 5M8 8.1V14"/></svg>`;++export function ensureRigBadgeStyles() {+ if (typeof document === 'undefined') return;+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.tws-rig{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:999px;+ font:600 11px/1 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;letter-spacing:.01em;+ white-space:nowrap;vertical-align:middle;border:1px solid transparent;cursor:default;}+.tws-rig svg{flex:none;opacity:.85;}+.tws-rig--rigged{color:#a78bfa;background:rgba(139,92,246,.13);border-color:rgba(139,92,246,.34);}+.tws-rig--static{color:var(--nxt-ink-dim,#8a8f98);background:rgba(255,255,255,.045);border-color:rgba(255,255,255,.1);}+.tws-rig--sm{padding:2px 7px;font-size:10px;gap:4px;}+.tws-rig--sm svg{width:9px;height:9px;}+`;+ (document.head || document.documentElement).appendChild(style);+}++/**+ * Render the dashboard rigged-or-not pill. Returns '' when there is no avatar to+ * judge (callers render nothing rather than a misleading "Static"). Unlike the+ * gallery badge in rig-classify.js, this paints a "Static" pill for inspected+ * static meshes AND never-inspected uploads, matching the binary chips.+ * @param {object|null|undefined} avatar+ * @param {{ size?: 'sm'|'md' }} [opts]+ */+export function rigBadgeHTML(avatar, opts = {}) {+ if (!avatar) return '';+ ensureRigBadgeStyles();+ const rigged = isRigged(avatar);+ const sizeCls = opts.size === 'sm' ? ' tws-rig--sm' : '';+ const cls = rigged ? 'tws-rig--rigged' : 'tws-rig--static';+ const label = rigged ? 'Rigged' : 'Static';+ const title = rigged+ ? 'Rigged — has a skeleton, plays the animation library'+ : 'Static — no skeleton yet, open in the editor to auto-rig it';+ const icon = rigged ? RIGGED_ICON : STATIC_ICON;+ return `<span class="tws-rig ${cls}${sizeCls}" title="${title}" aria-label="${title}">${icon}<span>${label}</span></span>`;+}diff --git a/tests/rig-classify.test.js b/tests/rig-classify.test.jsnew file mode 100644index 000000000..d61a1cb86--- /dev/null+++ b/tests/rig-classify.test.js@@ -0,0 +1,59 @@+import { describe, it, expect } from 'vitest';+import { classifyRig, rigBadgeHTML } from '../src/shared/rig-classify.js';++describe('classifyRig', () => {+ it('classifies a model with the is_rigged flag as rigged', () => {+ const r = classifyRig({ source_meta: { is_rigged: true, skeleton_joint_count: 52 } });+ expect(r).toMatchObject({ category: 'rigged', rigged: true, known: true, jointCount: 52 });+ });++ it('classifies a positive joint count as rigged even without the flag', () => {+ const r = classifyRig({ source_meta: { skeleton_joint_count: 30 } });+ expect(r.category).toBe('rigged');+ expect(r.rigged).toBe(true);+ });++ it('classifies an inspected-but-skeleton-less model as static', () => {+ const r = classifyRig({ source_meta: { is_rigged: false, skeleton_joint_count: 0 } });+ expect(r).toMatchObject({ category: 'static', rigged: false, known: true, jointCount: 0 });+ });++ it('treats a never-inspected upload as unknown, not static', () => {+ const r = classifyRig({ source_meta: {} });+ expect(r).toMatchObject({ category: 'unknown', rigged: false, known: false });+ });++ it('treats a flag-false model with a stale positive joint count as rigged (joints win)', () => {+ const r = classifyRig({ source_meta: { is_rigged: false, skeleton_joint_count: 12 } });+ expect(r.category).toBe('rigged');+ });++ it('handles a missing source_meta / null avatar safely', () => {+ expect(classifyRig(null).category).toBe('unknown');+ expect(classifyRig({}).category).toBe('unknown');+ });+});++describe('rigBadgeHTML', () => {+ it('paints a rigged badge', () => {+ const html = rigBadgeHTML({ source_meta: { is_rigged: true } });+ expect(html).toContain('rig-badge--rigged');+ expect(html).toContain('Rigged');+ });++ it('paints a static badge', () => {+ const html = rigBadgeHTML({ source_meta: { is_rigged: false } });+ expect(html).toContain('rig-badge--static');+ expect(html).toContain('Static');+ });++ it('renders nothing for unknown so un-inspected uploads are not mislabeled', () => {+ expect(rigBadgeHTML({ source_meta: {} })).toBe('');+ });++ it('appends the joint count when asked', () => {+ const html = rigBadgeHTML({ source_meta: { is_rigged: true, skeleton_joint_count: 41 } }, { joints: true });+ expect(html).toContain('rig-badge-joints');+ expect(html).toContain('41');+ });+});diff --git a/walk-sdk/src/internal/budget.js b/walk-sdk/src/internal/budget.jsnew file mode 100644index 000000000..322c07d79--- /dev/null+++ b/walk-sdk/src/internal/budget.js@@ -0,0 +1,27 @@+// Shared WebGL context accounting (vendored from the three.ws app).+//+// Browsers cap simultaneous WebGL contexts (~16 in Chrome). State lives on+// `window` so every renderer on the page — the host app's own viewers, the+// CDN <agent-3d> element, and this SDK — counts against ONE shared budget and+// no single page can blow past the browser limit. Because the state is a+// window global, a vendored copy here coordinates with the app's copy+// automatically; they are the same counter.++export function reserveWebGLContext() {+ if (typeof window === 'undefined') return;+ const n = Number(window.__agent3dReservedContexts) || 0;+ window.__agent3dReservedContexts = n + 1;+ if (typeof window.__agent3dEnforceBudget === 'function') {+ try {+ window.__agent3dEnforceBudget();+ } catch {+ /* budget enforcement is best-effort */+ }+ }+}++export function releaseWebGLContext() {+ if (typeof window === 'undefined') return;+ const n = Number(window.__agent3dReservedContexts) || 0;+ window.__agent3dReservedContexts = Math.max(0, n - 1);+}diff --git a/walk-sdk/src/internal/load-avatar.js b/walk-sdk/src/internal/load-avatar.jsnew file mode 100644index 000000000..ccb55bec9--- /dev/null+++ b/walk-sdk/src/internal/load-avatar.js@@ -0,0 +1,241 @@+// Unified avatar loader + animation controller.+// ==============================================+// One entry point used by BOTH the corner companion and the full-page+// playground, so adding an avatar to the roster makes it work everywhere at+// once. Given a roster entry it loads the GLB and returns a controller with a+// single interface — setState('idle'|'walk'|'run'|'jump') + playWave() — no+// matter how the rig is animated underneath:+//+// • embedded rigs play the clips baked into the GLB (robot, fox, showpieces),+// with loose name matching that always falls back to the model's first clip+// so even a one-animation GLB keeps moving and never shows a bind pose.+// • shared rigs are driven by the retargeted shared clip library through+// AnimationManager (humanoids that ship no locomotion, or only a T-pose).+//+// The caller is responsible for framing/scaling the returned `model`.++import { AnimationMixer, LoopOnce, LoopRepeat } from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { getMeshoptDecoder } from './meshopt.js';+import { AnimationManager } from './runtime.js';+import { log } from './log.js';+import { resolveAvatarUrl, DEFAULT_SHARED_CLIPS } from '../roster.js';++const DEFAULT_WAVE_MS = 1500;++let _loaderPromise = null;+async function makeLoader() {+ // One meshopt-only GLTFLoader, reused across loads. Draco/KTX2 are never+ // emitted by the bakes these avatars come from, so we skip those decoders.+ if (!_loaderPromise) {+ _loaderPromise = (async () => {+ const loader = new GLTFLoader();+ loader.setMeshoptDecoder(await getMeshoptDecoder());+ return loader;+ })();+ }+ return _loaderPromise;+}++/**+ * Load a roster entry and build its controller.+ * @returns {Promise<{ model: import('three').Object3D, controller: object, gltf: object }>}+ */+export async function loadWalkAvatar(entry, opts = {}) {+ const {+ assetBase = '',+ apiBase = '',+ manifestUrl = '/animations/manifest.json',+ fallbackEntry = null,+ waveMs = DEFAULT_WAVE_MS,+ } = opts;++ const loader = await makeLoader();+ const url = resolveAvatarUrl(entry, { assetBase, apiBase });+ if (!url) throw new Error(`walk: cannot resolve a GLB url for avatar "${entry?.id}"`);++ let active = entry;+ let gltf;+ try {+ gltf = await loader.loadAsync(url);+ } catch (err) {+ if (fallbackEntry && fallbackEntry.id !== entry.id) {+ log.warn(`avatar "${entry?.id}" failed to load — falling back to "${fallbackEntry.id}"`, err?.message || err);+ active = fallbackEntry;+ gltf = await loader.loadAsync(resolveAvatarUrl(fallbackEntry, { assetBase, apiBase }));+ } else {+ throw err;+ }+ }++ const model = gltf.scene;+ model.traverse((n) => {+ if (n.isMesh) n.frustumCulled = false;+ });++ let controller;+ if (active.rig === 'shared') {+ controller = await buildSharedController(model, active.clips || DEFAULT_SHARED_CLIPS, {+ manifestUrl,+ waveMs,+ });+ } else {+ controller = makeEmbeddedController(model, gltf.animations || [], active.clips || {}, { waveMs });+ }++ return { model, controller, gltf, entry: active };+}++// ── Embedded-clip controller (rig: 'embedded') ───────────────────────────────+function makeEmbeddedController(root, clips, overrides, { waveMs }) {+ const mixer = new AnimationMixer(root);+ const byName = (name) => clips.find((c) => c.name.toLowerCase() === String(name).toLowerCase());+ const pick = (cands) => {+ for (const n of cands) {+ const c = byName(n);+ if (c) return c;+ }+ return null;+ };+ const ov = (k) => (Array.isArray(overrides?.[k]) ? overrides[k] : []);++ // Idle must always resolve to *something* animated, so a single-clip GLB+ // (a lone walk or dance loop) never stalls in its bind/T-pose.+ const idleClip = pick([...ov('idle'), 'Idle', 'idle']) || clips[0] || null;+ const map = {+ idle: idleClip,+ walk: pick([...ov('walk'), 'Walking', 'Walk', 'walk']) || idleClip,+ run: pick([...ov('run'), 'Running', 'Run', 'run', 'Walking', 'walk']) || idleClip,+ jump: pick([...ov('jump'), 'Jump', 'jump', 'WalkJump']) || null,+ wave: pick([...ov('wave'), 'Wave', 'wave']) || null,+ };++ const action = {};+ for (const [state, clip] of Object.entries(map)) {+ if (!clip) continue;+ const a = mixer.clipAction(clip);+ a.enabled = true;+ action[state] = a;+ }++ let base = 'idle';+ let requested = 'idle';+ let current = null;+ let oneShot = false;++ function crossfade(name, { once = false, dur = 0.3 } = {}) {+ const a = action[name] || action.idle;+ if (!a) return;+ a.reset();+ a.setLoop(once ? LoopOnce : LoopRepeat, once ? 1 : Infinity);+ a.clampWhenFinished = once;+ a.fadeIn(dur).play();+ if (current && current !== a) current.fadeOut(dur);+ current = a;+ }++ mixer.addEventListener('finished', () => {+ if (oneShot) {+ oneShot = false;+ crossfade(base, { dur: 0.25 });+ }+ });++ crossfade('idle', { dur: 0 });++ return {+ setState(next) {+ if (next === requested) return;+ requested = next;+ if (next === 'jump') {+ if (action.jump) {+ oneShot = true;+ crossfade('jump', { once: true, dur: 0.12 });+ }+ return;+ }+ base = next;+ if (!oneShot) crossfade(base, { dur: 0.22 });+ },+ playWave() {+ if (!action.wave || oneShot) return;+ oneShot = true;+ crossfade('wave', { once: true, dur: 0.25 });+ // Safety net: if the 'finished' event is missed (clip stripped of its+ // end key, etc.), still fall back to the base after the clip's length.+ const len = action.wave.getClip().duration * 1000 || waveMs;+ clearTimeout(this._waveGuard);+ this._waveGuard = setTimeout(() => {+ if (oneShot) {+ oneShot = false;+ crossfade(base, { dur: 0.25 });+ }+ }, len + 250);+ },+ update(dt) {+ mixer.update(dt);+ },+ dispose() {+ clearTimeout(this._waveGuard);+ mixer.stopAllAction();+ mixer.uncacheRoot(root);+ },+ };+}++// ── Shared retargeted-clip controller (rig: 'shared') ────────────────────────+async function buildSharedController(model, clips, { manifestUrl, waveMs }) {+ const manager = new AnimationManager();+ manager.attach(model);++ const manifest = await fetch(manifestUrl, { cache: 'force-cache' }).then((r) => {+ if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`);+ return r.json();+ });+ const available = new Set(manifest.map((d) => d.name));++ // Resolve each requested clip to one that actually exists; unknown names fall+ // back to idle so the controller never asks the manager for a missing clip.+ const resolved = {};+ for (const [state, name] of Object.entries({ ...DEFAULT_SHARED_CLIPS, ...clips })) {+ resolved[state] = available.has(name) ? name : null;+ }+ resolved.idle = resolved.idle || (available.has('idle') ? 'idle' : null);+ if (!resolved.idle) throw new Error('animation manifest missing an idle clip');+ for (const k of Object.keys(resolved)) if (!resolved[k]) resolved[k] = resolved.idle;++ const wanted = new Set(Object.values(resolved));+ manager.setAnimationDefs(manifest.filter((d) => wanted.has(d.name)));+ await manager.loadAll();++ let base = 'idle';+ let waveTimer = null;+ const fade = (name, dur) => Promise.resolve(manager.crossfadeTo(name, dur)).catch(() => {});+ const clipFor = (state) => resolved[state] || resolved.idle;+ fade(resolved.idle, 0);++ return {+ setState(next) {+ if (next === base) return;+ base = next;+ if (!waveTimer) fade(clipFor(next), next === 'jump' ? 0.12 : 0.3);+ },+ playWave() {+ if (waveTimer) return;+ const w = resolved.wave;+ if (!w || w === resolved.idle) return; // no distinct wave clip → skip+ fade(w, 0.25);+ waveTimer = setTimeout(() => {+ waveTimer = null;+ fade(clipFor(base), 0.3);+ }, waveMs);+ },+ update(dt) {+ manager.update(dt);+ },+ dispose() {+ clearTimeout(waveTimer);+ manager.dispose();+ },+ };+}diff --git a/walk-sdk/src/internal/log.js b/walk-sdk/src/internal/log.jsnew file mode 100644index 000000000..4bea58728--- /dev/null+++ b/walk-sdk/src/internal/log.js@@ -0,0 +1,28 @@+// Minimal namespaced logger. Quiet by default; set `window.__walkDebug = true`+// (or localStorage `walk:debug` = '1') to surface info/debug lines. Warnings+// and errors always pass through so failures are never swallowed silently.++function debugOn() {+ if (typeof window === 'undefined') return false;+ if (window.__walkDebug) return true;+ try {+ return window.localStorage?.getItem('walk:debug') === '1';+ } catch {+ return false;+ }+}++export const log = {+ debug(...args) {+ if (debugOn()) console.debug('[walk]', ...args);+ },+ info(...args) {+ if (debugOn()) console.info('[walk]', ...args);+ },+ warn(...args) {+ console.warn('[walk]', ...args);+ },+ error(...args) {+ console.error('[walk]', ...args);+ },+};diff --git a/walk-sdk/src/internal/meshopt.js b/walk-sdk/src/internal/meshopt.jsnew file mode 100644index 000000000..7d44f18e3--- /dev/null+++ b/walk-sdk/src/internal/meshopt.js@@ -0,0 +1,17 @@+// Lazily resolve the meshopt decoder from three's addons.+//+// Server-baked avatars (the `/api/avatars/<id>/glb` lane) emit+// EXT_meshopt_compression but never Draco/KTX2, so we wire ONLY the meshopt+// decoder onto the GLTFLoader. That keeps the walk chunk small and avoids+// pulling the heavier Draco/KTX2 loader init. Uncompressed rigs (the static+// `/avatars/*.glb` and RobotExpressive) ignore the decoder harmlessly.++let _promise = null;++export function getMeshoptDecoder() {+ if (_promise) return _promise;+ _promise = import('three/addons/libs/meshopt_decoder.module.js').then(+ (m) => m.MeshoptDecoder,+ );+ return _promise;+}diff --git a/walk-sdk/src/internal/runtime.js b/walk-sdk/src/internal/runtime.jsnew file mode 100644index 000000000..00289a5de--- /dev/null+++ b/walk-sdk/src/internal/runtime.js@@ -0,0 +1,17 @@+// Shared animation runtime.+// ==========================+// The retargeting engine (AnimationManager + animation-retarget ++// glb-canonicalize) is the platform's crown-jewel rig-agnostic clip system: it+// takes the shared Mixamo/VRM-canonical clip library and replays it on ANY+// humanoid skeleton (Ready Player Me, Mixamo, VRM, custom). It is large and+// evolves with the app, so rather than vendor a copy that would silently drift,+// this SDK re-exports it from the monorepo source. The publish build+// (`build.mjs`, esbuild with `three` external) bundles it into a self-contained+// `dist/`, so npm consumers get one standalone file with nothing to resolve.+//+// PROMOTION NOTE — when this package is split into its own external repo+// (see the repo's STRUCTURE.md "Promotion path"), replace this single import+// with a vendored copy of src/animation-manager.js and its two dependencies.+// This file is the only seam that reaches back into the monorepo.++export { AnimationManager } from '../../../src/animation-manager.js';diff --git a/walk-sdk/src/internal/storage.js b/walk-sdk/src/internal/storage.jsnew file mode 100644index 000000000..2ceb1d2d8--- /dev/null+++ b/walk-sdk/src/internal/storage.js@@ -0,0 +1,71 @@+// Private-mode-safe storage + small DOM/env helpers shared across the SDK.+// Every accessor swallows exceptions so a locked-down browser (private mode,+// disabled storage) degrades gracefully instead of throwing.++export function lsGet(key) {+ try {+ return localStorage.getItem(key);+ } catch {+ return null;+ }+}+export function lsSet(key, val) {+ try {+ localStorage.setItem(key, val);+ } catch {+ /* private mode / disabled storage — non-fatal */+ }+}+export function ssGet(key) {+ try {+ return sessionStorage.getItem(key);+ } catch {+ return null;+ }+}+export function ssSet(key, val) {+ try {+ sessionStorage.setItem(key, val);+ } catch {+ /* non-fatal */+ }+}+export function ssDel(key) {+ try {+ sessionStorage.removeItem(key);+ } catch {+ /* non-fatal */+ }+}++export function prefersReducedMotion() {+ try {+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ } catch {+ return false;+ }+}++export function isCoarsePointer() {+ try {+ return window.matchMedia('(pointer: coarse)').matches;+ } catch {+ return false;+ }+}++export function webglSupported() {+ try {+ const c = document.createElement('canvas');+ return !!(+ window.WebGLRenderingContext &&+ (c.getContext('webgl2') || c.getContext('webgl'))+ );+ } catch {+ return false;+ }+}++export function clamp(v, lo, hi) {+ return Math.max(lo, Math.min(hi, v));+}diff --git a/walk-sdk/src/roster.js b/walk-sdk/src/roster.jsnew file mode 100644index 000000000..f160defc9--- /dev/null+++ b/walk-sdk/src/roster.js@@ -0,0 +1,259 @@+// Walk avatar roster — the cast that can walk and talk over your pages.+// =====================================================================+// Every entry is a real, shippable GLB with a known-good animation strategy.+// Two strategies, chosen per rig so nothing ever freezes in a bind/T-pose:+//+// • rig: 'embedded' — play the clips baked into the GLB itself. Used for+// non-humanoid or self-animated models (the robot mascot, the fox, the+// glTF showpieces). State names are matched loosely and fall back to the+// model's first clip, so even a single-animation GLB still moves.+// • rig: 'shared' — drive the rig with the platform's retargeted shared+// clip library via AnimationManager (idle / walk / run / wave / jump).+// Used for humanoids that ship without locomotion (or, like Michelle,+// ship ONLY a T-pose — which must never be shown). `clips` maps each+// state to a clip name in /animations/manifest.json.+//+// `asset` is a path resolved against the SDK's `assetBase` at runtime, so the+// same roster works whether the GLBs are served from the host origin, a CDN,+// or a subpath. User-generated avatars are not in this static list — build one+// on the fly with `makeApiAvatarEntry(id)`.++export const DEFAULT_AVATAR_ID = 'robot';++// Manifest clip names used by retargeted (shared-rig) avatars. Verified present+// in /animations/manifest.json.+export const DEFAULT_SHARED_CLIPS = {+ idle: 'idle',+ walk: 'av-walk-feminine',+ run: 'av-walk-feminine', // no distinct sprint clip; pace comes from timeScale+ wave: 'wave',+ jump: 'jump',+};++export const WALK_AVATARS = [+ {+ id: 'robot',+ name: 'Robo',+ emoji: '🤖',+ blurb: 'The friendly platform mascot. Expressive, lightweight, always game.',+ category: 'Mascots',+ asset: '/animations/robotexpressive.glb',+ source: 'static',+ rig: 'embedded',+ thumb: '/avatars/thumbs/robotexpressive.png',+ accent: '#7aa2ff',+ tags: ['mascot', 'robot', 'lightweight', 'default'],+ },+ {+ id: 'guide',+ name: 'Guide',+ emoji: '🧭',+ blurb: 'A clean humanoid guide, driven by the shared motion library.',+ category: 'Humanoid',+ asset: '/avatars/default.glb',+ source: 'static',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ thumb: '/avatars/thumbs/default.png',+ accent: '#8bd5ca',+ tags: ['humanoid', 'neutral', 'guide'],+ },+ {+ id: 'michelle',+ name: 'Michelle',+ emoji: '💃',+ blurb: 'Stylised dancer rig, fully retargeted so she struts — never poses.',+ category: 'Humanoid',+ asset: '/avatars/michelle.glb',+ source: 'static',+ rig: 'shared',+ // Michelle's GLB ships only a TPose — force the shared library and never+ // touch the embedded pose. See the repo's no-T-pose rule.+ clips: { ...DEFAULT_SHARED_CLIPS, wave: 'michelle-samba-dance' },+ accent: '#ff8fab',+ tags: ['humanoid', 'feminine', 'dancer'],+ },+ {+ id: 'mannequin',+ name: 'Mannequin',+ emoji: '🧍',+ blurb: 'A neutral artist mannequin — the blank canvas of the cast.',+ category: 'Humanoid',+ asset: '/avatars/mannequin.glb',+ source: 'static',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ accent: '#c9b8a8',+ tags: ['humanoid', 'neutral', 'mannequin'],+ },+ {+ id: 'xbot',+ name: 'X-Bot',+ emoji: '🦾',+ blurb: 'Mixamo X-Bot with its own idle/walk/run set for snappy motion.',+ category: 'Humanoid',+ asset: '/avatars/xbot.glb',+ source: 'static',+ rig: 'shared',+ clips: { idle: 'xbot-idle', walk: 'xbot-walk', run: 'xbot-run', wave: 'wave', jump: 'jump' },+ accent: '#9aa7b5',+ tags: ['humanoid', 'robot', 'mixamo'],+ },+ {+ id: 'realistic-female',+ name: 'Ava',+ emoji: '👩',+ blurb: 'Photoreal full-body avatar, retargeted to the shared library.',+ category: 'Realistic',+ asset: '/avatars/realistic-female.glb',+ source: 'static',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ accent: '#f2a65a',+ tags: ['realistic', 'feminine', 'rpm'],+ },+ {+ id: 'realistic-male',+ name: 'Leo',+ emoji: '👨',+ blurb: 'Photoreal full-body avatar, retargeted to the shared library.',+ category: 'Realistic',+ asset: '/avatars/realistic-male.glb',+ source: 'static',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ accent: '#6ea8fe',+ tags: ['realistic', 'masculine', 'rpm'],+ },+ {+ id: 'selfie-girl',+ name: 'Mira',+ emoji: '🤳',+ blurb: 'Selfie-styled avatar — playful, expressive, photo-ready.',+ category: 'Realistic',+ asset: '/avatars/selfie-girl.glb',+ source: 'static',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ accent: '#d39bff',+ tags: ['realistic', 'feminine', 'rpm'],+ },+ {+ id: 'fox',+ name: 'Fox',+ emoji: '🦊',+ blurb: 'The classic glTF fox — a non-humanoid pal that trots and surveys.',+ category: 'Creatures',+ asset: '/avatars/fox.glb',+ source: 'static',+ rig: 'embedded',+ clips: { idle: ['Survey'], walk: ['Walk'], run: ['Run'] },+ accent: '#ff9f43',+ tags: ['creature', 'animal', 'quadruped'],+ },+ {+ id: 'twerk',+ name: 'Groove',+ emoji: '🕺',+ blurb: 'A dancer who never stops moving — pure ambient energy.',+ category: 'Showpieces',+ asset: '/avatars/dancing-twerk.glb',+ source: 'static',+ rig: 'embedded',+ accent: '#ff5e7e',+ tags: ['dancer', 'loop', 'fun'],+ },+ {+ id: 'cesium',+ name: 'Cesium',+ emoji: '🚶',+ blurb: 'The reference walking man — a tireless, steady stroller.',+ category: 'Showpieces',+ asset: '/avatars/cesium-man.glb',+ source: 'static',+ rig: 'embedded',+ accent: '#54c7ec',+ tags: ['reference', 'walk'],+ },+ {+ id: 'brainstem',+ name: 'Stem',+ emoji: '🦿',+ blurb: 'A skeletal showpiece rig with a hypnotic walk cycle.',+ category: 'Showpieces',+ asset: '/avatars/brainstem.glb',+ source: 'static',+ rig: 'embedded',+ accent: '#a0e7a0',+ tags: ['showpiece', 'skeletal'],+ },+ {+ id: 'cz',+ name: 'CZ',+ emoji: '🧑💼',+ blurb: 'A stylised character bust with a calm, animated idle.',+ category: 'Showpieces',+ asset: '/avatars/cz.glb',+ source: 'static',+ rig: 'embedded',+ thumb: '/avatars/thumbs/cz.png',+ accent: '#ffd166',+ tags: ['showpiece', 'idle'],+ },+];++const _byId = new Map(WALK_AVATARS.map((a) => [a.id, a]));++/** Look up a roster entry by id. Returns null when unknown. */+export function getAvatar(id) {+ return (id && _byId.get(id)) || null;+}++/** The default roster entry (the platform mascot). */+export function defaultAvatar() {+ return getAvatar(DEFAULT_AVATAR_ID) || WALK_AVATARS[0];+}++/** Distinct categories, in first-seen roster order — handy for grouped UIs. */+export function listCategories() {+ const seen = [];+ for (const a of WALK_AVATARS) if (!seen.includes(a.category)) seen.push(a.category);+ return seen;+}++/**+ * Build a roster-shaped entry for a user-generated avatar served by the+ * platform's GLB proxy (`/api/avatars/<id>/glb`). These are always humanoid+ * RPM/Mixamo bakes with no embedded locomotion, so they use the shared library.+ */+export function makeApiAvatarEntry(id, { name, accent } = {}) {+ return {+ id,+ name: name || 'Your avatar',+ emoji: '✨',+ blurb: 'Your own avatar, retargeted to the shared motion library.',+ category: 'Yours',+ asset: null,+ source: 'api',+ rig: 'shared',+ clips: DEFAULT_SHARED_CLIPS,+ accent: accent || '#7aa2ff',+ tags: ['custom', 'user'],+ };+}++/**+ * Resolve the GLB URL for a roster entry.+ * - static entries: `assetBase` + the entry's asset path.+ * - api entries: `apiBase` + `/api/avatars/<id>/glb`.+ */+export function resolveAvatarUrl(entry, { assetBase = '', apiBase = '' } = {}) {+ if (!entry) return null;+ if (entry.source === 'api') {+ return `${apiBase}/api/avatars/${encodeURIComponent(entry.id)}/glb`;+ }+ if (!entry.asset) return null;+ // Absolute URLs pass through untouched; root-relative paths get the base.+ if (/^https?:\/\//i.test(entry.asset)) return entry.asset;+ return `${assetBase}${entry.asset}`;+}