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
Add the animation marketplace; Solana RPC + forge/nvidia hardening
nirholas759dad71a745
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 93b1d503f..e65375a72 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-15+- **Sniper Arena — autonomous AI agents trading live** (`/play/arena`) — Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.- **After you launch a coin, jump straight to viewing or managing it** — The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place. (`/pump-dashboard`) `[improvement]`- **Agent reputation now reflects a real pump.fun track record** — An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new "SIGNAL" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet. (`/pump-dashboard`) `[improvement, fix]`- **Agents and items are now clearly separate — a teapot won't get a brain** — Every 3D model you create is now clearly one of two things: an Agent (a character that thinks, talks, remembers, and can go on-chain) or an Item (a 3D object or prop for scenes and trading). On the review screen the choice is spelled out with a short description of each, and we pick a smart default — models from the selfie, studio, and character tools start as agents, while anything you type into existence with prompt-to-3D starts as an item, so a teapot is never pre-loaded with a brain. Pick Item and the agent-only capabilities (voice, persona, on-chain identity) step aside for a gentle note — with a one-click "made a character? make it an agent" escape hatch if the guess was wrong. The Forge tagger now groups its labels the same way, calling out that only avatars and creatures can become agents. (`/create`) `[improvement]`@@ -27,6 +28,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Rate and vouch for Solana agents from their passport** — Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new "Rate this agent" panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds. (`/agent-passport.html`) `[feature]`- **Register an existing agent on-chain in one click** — Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new "Register on-chain" control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done. (`/agents`) `[feature]`- **Registered agents now carry an on-chain "Validated" badge** — When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green "Validated" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows "Validation failed" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration. (`/marketplace`) `[feature, security]`+- **Sniper Arena — watch AI agents trade pump.fun live** — Agents can now trade pump.fun autonomously. A new always-on engine watches every launch in real time, scores it against an agent's strategy (market-cap band, creator track record, socials), and — when it qualifies — buys from the agent's own Solana wallet, then manages the position to a take-profit, stop-loss, trailing stop, or timeout exit. Arming an agent is opt-in and capped: you set a daily budget, a per-trade size, and a mandatory stop-loss, with a kill switch that halts new buys instantly. The new Sniper Arena at three.ws/play/arena shows it all happening live — a P&L leaderboard, a streaming trade ticker where every fill links to its on-chain transaction, and the top agent's 3D avatar reacting to its own wins. Autonomous trading is experimental and you can lose the funds you commit. (`/play/arena`) `[feature]`- **Strategy Lab now catches broken trading strategies before they run** — Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes. (`/strategy-lab`) `[improvement]`- **The Forge always returns a model — the default never dead-ends** — Typing a prompt into the Forge on the default Standard setting now always produces a 3D model, even when our paid reconstruction provider is throttled or over its quota. Previously a busy upstream could leave the default flow stuck on a "generator is busy, try again" message that never cleared. Now, if the paid engine is unavailable, a text prompt transparently falls back to the free NVIDIA lane and still hands you a finished model — and the result clearly shows which engine produced it, so the change is never hidden. Free-first, always a working fallback. (`/forge`) `[fix]`- **The Forge grows itself — a new avatar or accessory every minute, tied to real accounts** — A new auto-generation system creates a fresh 3D avatar or accessory every minute using the free NVIDIA lane and adds it to the community gallery. Each model is attributed to a new user account with an OG single-word username — wolf, raven, iron, frost — so the gallery reads like a real creator community. The system cycles through 200+ curated prompts covering fantasy warriors, sci-fi soldiers, mythological creatures, and matching weapons, armor, and accessories, cycling through the full library before repeating. Every model is a permanent GLB stored in our own CDN. (`/forge`) `[feature]`@@ -34,6 +36,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The pump.fun graduations feed stays fresh around the clock** — The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list. `[infra, improvement]`- **The site footer and top pages are now polished on phones** — On mobile the footer's link columns ran off the right edge and got cut off — the contract address and legal links were unreachable — because an old style rule for the 3D viewer's corner credit was hijacking the main footer's layout. The footer now stacks into clean, tappable columns on every page. We also did a mobile pass across the most-used pages — Home, Discover, Create, Forge, Marketplace, Gallery, and Pay — eliminating sideways scrolling, enlarging tap targets to a comfortable size, and stopping form fields from zooming the page when you tap them. `[fix, improvement]`- **The top navigation is back on every page** — The site header was being clipped to a sliver on most pages — the menu, search, and account controls were cut off and the dropdowns wouldn't open. An old style rule meant for the standalone 3D viewer's compact toolbar was leaking onto the shared navigation, forcing it to a fixed height and hiding everything below it. The viewer rule is now scoped to only the viewer, so the full navigation renders at its natural height across the whole site. `[fix]`+- **There's a cover at the Pole Club door** — The club now has a line outside. Before the room opens you pay a $0.01 USDC cover at the door via x402, and an on-chain bouncer checks the paying wallet — banned wallets are turned away, everyone else gets in with a door tier (newcomer, regular, or VIP) based on their past club nights. Pay once and you're in for the night; reopen the page and the velvet rope drops automatically. The 3D room loads behind the door while you're in line, so it's warm the moment you step in. (`/club`) `[feature]`- **three.ws can now register itself on-chain on Solana** — Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official "three.ws Agents" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport. (`/.well-known/agent-registration.json`) `[feature, infra]`- **three.ws now registers itself as an on-chain agent (ERC-8004)** — The platform that helps you put your agents on-chain now does the same for itself. three.ws publishes a 3D Agent Card — a verifiable manifest of its name, its default 3D avatar, and its A2A/MCP/x402 service endpoints — at three.ws/.well-known/3d-agent-card.json, and ships a one-command tool that mints the platform agent in the canonical ERC-8004 IdentityRegistry on Base (with a Base Sepolia rehearsal first). The card cryptographically commits to the avatar: the SHA-256 in the card matches the exact GLB bytes served, so any indexer or wallet can independently verify the model hasn't been swapped. Other agents and directories can now discover and trust three.ws the same way three.ws lets them be discovered. `[feature, infra]`- **USDC-paired agent coins now record and display correct trade amounts** — Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts. `[fix, feature]`diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex 15ccc69f0..830532ddb 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -20,10 +20,54 @@ function deriveWsUrl(httpUrl) {return String(httpUrl).replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');}-const COOLDOWN_MS = 30_000;+// Cooldown durations by failure class. Quota exhaustion (e.g. Helius -32429+// "max usage reached") means the provider is dead for the billing window, so we+// park it for hours instead of re-hammering it on every RPC call and every cron+// tick — that re-hammering was the source of the 429 retry storm in the logs.+// Plain rate-limits, auth rejections, and transient 5xx/network blips cool down+// for shorter, proportionate windows.+const QUOTA_COOLDOWN_MS = 6 * 3_600_000; // 6h — daily/monthly quota exhausted+const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m — transient 429+const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m — bad/expired key on this provider only+const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m — provider 5xx+const NETWORK_COOLDOWN_MS = 30_000; // 30s — fetch threw (DNS/connection blip)const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';const PUBLIC_DEVNET = 'https://api.devnet.solana.com';+// Process-wide endpoint cooldown, keyed by full URL. Shared across every+// Connection built in this lambda instance — both solanaConnection() and+// RpcFallback — so once one provider reports quota-exhausted, ALL callers skip+// it until it recovers. Per-instance state is correct on Vercel: it self-heals+// on cooldown expiry and a cold start simply re-probes.+const _endpointCooldown = new Map();++function cooldownMsFor(status, bodyText) {+ if (status === 429) {+ return /max usage reached|-32429|quota|usage limit|credits?\s*exhausted/i.test(bodyText || '')+ ? QUOTA_COOLDOWN_MS+ : RATE_LIMIT_COOLDOWN_MS;+ }+ if (status === 401 || status === 403) return AUTH_COOLDOWN_MS;+ if (status >= 500) return SERVER_COOLDOWN_MS;+ return RATE_LIMIT_COOLDOWN_MS;+}++/** True when `url` is currently parked in cooldown and should be skipped. */+export function isEndpointCooling(url) {+ return (_endpointCooldown.get(url) || 0) > Date.now();+}++/**+ * Park `url` in cooldown for a window sized to the failure class. Returns the+ * chosen cooldown in ms so callers can log it. `bodyText` (a 429 body or error+ * message) is scanned for a quota signal to pick the long window.+ */+export function markEndpointCooldown(url, status, bodyText) {+ const ms = cooldownMsFor(status, bodyText);+ _endpointCooldown.set(url, Date.now() + ms);+ return ms;+}+function dedupe(list) {const seen = new Set();return list.filter((u) => u && typeof u === 'string' && !seen.has(u) && seen.add(u));@@ -79,35 +123,52 @@ function shouldRotate(status) {return status === 401 || status === 403 || status === 429 || status >= 500;}-// Per-Connection rotating fetch. Cooldown state is captured in this closure, so-// it's shared across every JSON-RPC call made through one Connection instance.-function makeRotatingFetch(endpoints) {- const cooldownUntil = new Array(endpoints.length).fill(0);+// Rotating fetch backing a Connection. It NEVER surfaces a rotate-worthy status+// (401/403/429/5xx) to @solana/web3.js — it either returns a healthy response or+// throws — so web3.js's internal 429 backoff loop ("Server responded with 429 …+// Retrying after Nms") never fires. Cooldowns live in the process-wide map, so a+// quota-dead provider is skipped on the very next call (and next cron tick), not+// re-probed every time.+export function makeRotatingFetch(endpoints) {return async function rotatingFetch(_info, init) {let lastErr = null;let attempted = false;- for (let i = 0; i < endpoints.length; i++) {- if (cooldownUntil[i] > Date.now()) continue;+ for (const url of endpoints) {+ if (isEndpointCooling(url)) continue;attempted = true;try {- const resp = await fetch(endpoints[i], init);+ const resp = await fetch(url, init);if (shouldRotate(resp.status)) {- cooldownUntil[i] = Date.now() + COOLDOWN_MS;- lastErr = new Error(`solana rpc ${resp.status} @ ${maskUrl(endpoints[i])}`);- if (i + 1 < endpoints.length) {- console.warn(`[solana-rpc] ${maskUrl(endpoints[i])} ${resp.status} — failing over`);- }+ // Read the body only on the failure path (we never return it) so a+ // quota signal can pick the long cooldown.+ const bodyText = resp.status === 429 ? await resp.clone().text().catch(() => '') : '';+ const ms = markEndpointCooldown(url, resp.status, bodyText);+ // Logged only on the transition into cooldown — cooling endpoints+ // are skipped above without a line, so this fires once per window+ // per provider instead of on every RPC call.+ console.warn(+ `[solana-rpc] ${maskUrl(url)} ${resp.status} — cooling ${Math.round(ms / 60_000)}m, failing over`,+ );+ lastErr = new Error(`solana rpc ${resp.status} @ ${maskUrl(url)}`);continue;}return resp;} catch (err) {- cooldownUntil[i] = Date.now() + COOLDOWN_MS;+ // A thrown fetch is a transient network/DNS blip, not a quota signal —+ // cool only briefly so a healthy provider isn't parked for long.+ _endpointCooldown.set(url, Date.now() + NETWORK_COOLDOWN_MS);lastErr = err;}}- // Every endpoint is cooling down — don't hard-fail; take one more shot at- // the primary (its cooldown may have just lapsed under load).- if (!attempted) return fetch(endpoints[0], init);+ // Every endpoint is cooling down. Rather than blindly re-hit the (likely+ // dead) primary, take one shot at whichever recovers soonest — its cooldown+ // may have just lapsed and it's the least-bad option.+ if (!attempted) {+ const soonest = endpoints+ .slice()+ .sort((a, b) => (_endpointCooldown.get(a) || 0) - (_endpointCooldown.get(b) || 0))[0];+ return fetch(soonest, init);+ }throw lastErr || new Error('all solana rpc endpoints failed');};}@@ -124,6 +185,10 @@ export function solanaConnection({ url = null, commitment = 'confirmed', networkreturn new Connection(primary, {commitment,wsEndpoint: deriveWsUrl(primary),+ // Never let web3.js run its own 429 backoff loop: with >1 endpoint the+ // rotating fetch already hides 429s, and with a single endpoint we want to+ // fail fast to the caller rather than spend seconds retrying a dead lane.+ disableRetryOnRateLimit: true,...(endpoints.length > 1 ? { fetch: makeRotatingFetch(endpoints) } : {}),});}diff --git a/api/_lib/solana/rpc-fallback.js b/api/_lib/solana/rpc-fallback.jsindex 8c6325483..f7c14d236 100644--- a/api/_lib/solana/rpc-fallback.js+++ b/api/_lib/solana/rpc-fallback.js@@ -12,11 +12,20 @@// burn through fallbacks).import { Connection } from '@solana/web3.js';-import { solanaRpcEndpoints } from './connection.js';+import { solanaRpcEndpoints, isEndpointCooling, markEndpointCooldown } from './connection.js';const MAX_CONSECUTIVE_FAILS = 3;const COOLDOWN_MS = 60_000;+// Recover the upstream HTTP status from a thrown web3.js error so we can size the+// shared per-provider cooldown (a quota 429 parks the provider for hours, a plain+// 429 for minutes). web3.js surfaces 429 bodies verbatim, e.g.+// "429 Too Many Requests: {…-32429…max usage reached…}".+function statusFromErr(err) {+ const m = String((err && err.message) || err).match(/\b(401|403|429|500|502|503|504)\b/);+ return m ? Number(m[1]) : 429;+}+export function deriveWsUrl(httpUrl) {return String(httpUrl).replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');}@@ -65,6 +74,10 @@ export class RpcFallback {this.connections[this.currentIndex] = new Connection(url, {commitment: this.commitment,wsEndpoint: deriveWsUrl(url),+ // Fail fast on 429 so we rotate to the next provider immediately+ // instead of web3.js running its 500/1000/2000/4000ms backoff loop+ // ("Server responded with 429 … Retrying after Nms") on a dead lane.+ disableRetryOnRateLimit: true,});}return this.connections[this.currentIndex];@@ -86,9 +99,13 @@ export class RpcFallback {async withFallback(fn) {const tried = new Set();while (tried.size < this.urls.length) {- if (this.cooldownUntil[this.currentIndex] > Date.now()) {+ // Skip endpoints parked in the shared process-wide cooldown (e.g. Helius+ // after a quota 429) or this instance's local cooldown — don't re-probe a+ // known-dead lane on every call. Count it as tried so the loop still+ // terminates when everything is cooling.+ if (isEndpointCooling(this.currentUrl) || this.cooldownUntil[this.currentIndex] > Date.now()) {+ tried.add(this.currentIndex);this._rotate();- if (tried.has(this.currentIndex)) break;continue;}tried.add(this.currentIndex);@@ -98,7 +115,14 @@ export class RpcFallback {return result;} catch (err) {if (isRetryable(err)) {- console.warn('[rpc-fallback] %s rotated: %s', maskUrl(this.currentUrl), String(err).slice(0, 120));+ const status = statusFromErr(err);+ const ms = markEndpointCooldown(this.currentUrl, status, String((err && err.message) || err));+ console.warn(+ '[rpc-fallback] %s %s — cooling %dm, rotating',+ maskUrl(this.currentUrl),+ status,+ Math.round(ms / 60_000),+ );this.reportFailure();} else {throw err;diff --git a/api/_lib/zauth.js b/api/_lib/zauth.jsindex f6000399e..1e1619837 100644--- a/api/_lib/zauth.js+++ b/api/_lib/zauth.js@@ -34,6 +34,45 @@ const ZAUTH_HOST = (process.env.ZAUTH_API_ENDPOINT || 'https://back.zauthx402.coconst _inflight = new Set();let _fetchWrapped = false;+// Circuit breaker for the telemetry collector. From the Vercel runtime the+// collector can be persistently unreachable ("fetch failed"), which both wastes+// drain time on every monitored request and spams a warning per call. After N+// consecutive failed submissions we trip the breaker: instrument() becomes a+// no-op (no POST, no drain) until a cooldown elapses — logged once on trip and+// once on recovery, not per request. State is per-lambda-instance, which is+// correct: it self-heals on expiry and a cold start re-probes.+const _CIRCUIT_THRESHOLD = Number(process.env.ZAUTH_CIRCUIT_FAILURE_THRESHOLD) || 5;+const _CIRCUIT_COOLDOWN_MS = Number(process.env.ZAUTH_CIRCUIT_COOLDOWN_MS) || 300_000;+let _collectorFailures = 0;+let _collectorDownUntil = 0;++function isCollectorDown() {+ return _collectorDownUntil > Date.now();+}++function noteCollectorSuccess() {+ _collectorFailures = 0;+ if (_collectorDownUntil) {+ _collectorDownUntil = 0;+ console.log('[zauth] collector recovered — telemetry resumed');+ }+}++function noteCollectorFailure(err) {+ // Individual failures are only interesting in debug mode; steady-state we want+ // a single line when the breaker trips, not one per request.+ if (env.ZAUTH_DEBUG === '1') console.warn('[zauth] telemetry delivery failed (non-fatal):', err?.message || err);+ if (isCollectorDown()) return;+ _collectorFailures += 1;+ if (_collectorFailures >= _CIRCUIT_THRESHOLD) {+ _collectorDownUntil = Date.now() + _CIRCUIT_COOLDOWN_MS;+ _collectorFailures = 0;+ console.warn(+ `[zauth] collector unreachable — pausing telemetry for ${Math.round(_CIRCUIT_COOLDOWN_MS / 60_000)}m`,+ );+ }+}+// The SDK's flush() early-returns while a previous batch is still submitting// (`isFlushing`) and nothing ever re-triggers it, so an event queued during// submission is stranded until some later request happens to queue another@@ -65,12 +104,19 @@ function trackZauthFetch() {if (url.includes(ZAUTH_HOST)) {_inflight.add(promise);promise.then(- () => { _inflight.delete(promise); if (env.ZAUTH_DEBUG === '1') console.log('[zauth] Batch submitted'); },- // Telemetry is fire-and-forget: a transient network blip reaching- // back.zauthx402.com (or the lambda freezing mid-POST) must never be- // logged at error level — it isn't a request failure and was- // drowning genuine errors in the function logs. Warn, not error.- (err) => { _inflight.delete(promise); console.warn('[zauth] telemetry delivery failed (non-fatal):', err?.message || err); },+ () => {+ _inflight.delete(promise);+ noteCollectorSuccess();+ if (env.ZAUTH_DEBUG === '1') console.log('[zauth] Batch submitted');+ },+ // Telemetry is fire-and-forget: a transient blip reaching the collector+ // (or the lambda freezing mid-POST) is not a request failure. Feed the+ // circuit breaker, which logs once when the collector is sustainedly+ // down rather than once per request.+ (err) => {+ _inflight.delete(promise);+ noteCollectorFailure(err);+ },);}return promise;@@ -300,6 +346,10 @@ function shimRequest(req) {export function instrument(req, res) {const mw = getMiddleware();if (!mw) return false;+ // Collector circuit breaker tripped: skip monitoring entirely (no POST, no+ // drain await) until the cooldown elapses. Returning false means the caller+ // won't await drain() for this request.+ if (isCollectorDown()) return false;// Idempotency: dispatcher routes (wk.js, x402/service.js) run wrap() at the// top level AND invoke paidEndpoint-built handlers (also wrap()-ed) inside —// without this guard the SDK middleware would observe and report the samediff --git a/api/_providers/nvidia.js b/api/_providers/nvidia.jsindex f90285b19..9a41fd7b3 100644--- a/api/_providers/nvidia.js+++ b/api/_providers/nvidia.js@@ -65,7 +65,11 @@ function enhanceTrellisPrompt(raw) {// Per-request timeouts so a hung upstream never stalls a serverless function.// A completed poll streams the full GLB (can be several MB), so it gets longer.-const SUBMIT_TIMEOUT_MS = 30_000;+// Submit must cover a SYNCHRONOUS draft completion: the probe clocked ~12–13 s+// in isolation, but under real NVCF load TRELLIS routinely runs longer and was+// aborting at 30 s ("operation aborted due to timeout"). 45 s leaves headroom+// and still returns well inside the forge function's budget.+const SUBMIT_TIMEOUT_MS = 45_000;const POLL_TIMEOUT_MS = 60_000;// Sampling steps per quality tier, clamped to TRELLIS's accepted 10–50 window.@@ -111,6 +115,37 @@ function providerError(status, message, retryAfter) {return err;}+// Pull the GLB out of a successful TRELLIS response. The documented and common+// shape is JSON `{ artifacts: [{ base64 }] }`, but NVCF can also return the raw+// GLB bytes directly (model/gltf-binary or octet-stream) — accept both. When+// neither matches, return a compact diagnostic (content-type + top-level keys or+// a body snippet) instead of a blind failure, so the real upstream shape shows+// up in the logs and the gap can be closed precisely rather than guessed at.+async function extractGlbBase64(res) {+ const ct = (res.headers.get('content-type') || '').toLowerCase();+ if (ct.includes('json')) {+ const data = await res.json().catch(() => null);+ const b64 =+ data?.artifacts?.[0]?.base64 ||+ data?.artifacts?.[0]?.data ||+ (typeof data?.output === 'string' ? data.output : null) ||+ data?.output?.[0]?.base64 ||+ null;+ if (b64) return { base64: b64 };+ return {+ base64: null,+ diag: `json keys=${data && typeof data === 'object' ? JSON.stringify(Object.keys(data)) : 'unparseable'}`,+ };+ }+ if (ct.includes('gltf') || ct.includes('octet-stream') || ct.startsWith('model/') || ct.includes('binary')) {+ const buf = Buffer.from(await res.arrayBuffer());+ if (buf.length > 0) return { base64: buf.toString('base64') };+ return { base64: null, diag: `empty ${ct} body` };+ }+ const text = await res.text().catch(() => '');+ return { base64: null, diag: `ct=${ct || 'none'} body[0:160]=${text.slice(0, 160)}` };+}+function buildTextBody({ prompt, tier, seed }) {const steps = trellisSteps(tier);const body = {@@ -181,15 +216,15 @@ export function createNvidiaProvider() {}if (res.ok) {- const data = await res.json().catch(() => ({}));- const b64 = data?.artifacts?.[0]?.base64;- if (!b64) {+ const { base64, diag } = await extractGlbBase64(res);+ if (!base64) {+ console.warn('[nvidia] sync 200 but no GLB artifact — %s', diag);throw Object.assign(new Error('TRELLIS completed but returned no GLB artifact'), {code: 'provider_error',status: 502,});}- return { done: true, glbBase64: b64 };+ return { done: true, glbBase64: base64 };}let detail = '';@@ -243,11 +278,13 @@ export function createNvidiaProvider() {if (res.status === 202) return { status: 'running' };if (res.ok) {- const data = await res.json().catch(() => ({}));- const b64 = data?.artifacts?.[0]?.base64;- if (!b64) return { status: 'failed', error: 'TRELLIS finished but returned no GLB artifact' };+ const { base64, diag } = await extractGlbBase64(res);+ if (!base64) {+ console.warn('[nvidia] poll 200 but no GLB artifact — %s', diag);+ return { status: 'failed', error: 'TRELLIS finished but returned no GLB artifact' };+ }try {- const resultGlbUrl = await persistGlb(b64);+ const resultGlbUrl = await persistGlb(base64);return { status: 'done', resultGlbUrl };} catch (err) {return { status: 'failed', error: `failed to persist GLB: ${err?.message}` };diff --git a/api/animations/sell.js b/api/animations/sell.jsnew file mode 100644index 000000000..713a57f62--- /dev/null+++ b/api/animations/sell.js@@ -0,0 +1,214 @@+// POST /api/animations/sell — list (or update / delist) an animation clip for+// sale in the marketplace.+//+// A creator authors an animation in the Studio (/pose), saves it (POST+// /api/animations/clips), bakes a self-contained animated GLB, uploads it to R2+// via /api/animations/presign, then calls this endpoint to set a price + payout+// and flip `listed = true`. The clip then surfaces in GET /api/marketplace/+// animations and sells through the x402 paid-download endpoint+// (api/x402/animation-download.js) — buy once in USDC, re-download free forever+// by signing in with the same wallet.+//+// Body (list / update):+// { id, price, currency?, artifact_key, artifact_bytes?, artifact_mime?,+// payto_base?, payto_solana?, payto_bsc?, listed? }+// Body (delist):+// { id, action: 'delist' }+//+// price is a human USDC amount (e.g. 2.5). 0 / null lists the clip as a free+// download. Payout addresses default to the seller's default payout wallets+// (agent_payout_wallets) when omitted; a paid listing needs at least one.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { publicUrl } from '../_lib/r2.js';+import { z } from 'zod';++// USDC only for now — the x402 facilitator settles USDC on Base + Solana.+const SUPPORTED_CURRENCIES = ['USDC'];+const MAX_PRICE = 100_000; // $100k ceiling — sanity bound, not a product limit.++const EVM_ADDR = /^0x[0-9a-fA-F]{40}$/;+const SOL_ADDR = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const listSchema = z.object({+ id: z.string().uuid(),+ action: z.literal('list').optional(),+ price: z.number().nonnegative().max(MAX_PRICE).optional(),+ currency: z.enum(SUPPORTED_CURRENCIES).default('USDC'),+ // The sellable artifact: a baked animated GLB staged in the caller's R2+ // namespace by /api/animations/presign.+ artifact_key: z.string().trim().min(1).max(512),+ artifact_bytes: z.number().int().positive().max(200 * 1024 * 1024).optional(),+ artifact_mime: z.enum(['model/gltf-binary', 'model/gltf+json']).default('model/gltf-binary'),+ payto_base: z.string().trim().regex(EVM_ADDR).optional(),+ payto_solana: z.string().trim().regex(SOL_ADDR).optional(),+ payto_bsc: z.string().trim().regex(EVM_ADDR).optional(),+ listed: z.boolean().default(true),+});++const delistSchema = z.object({+ id: z.string().uuid(),+ action: z.literal('delist'),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req, 'avatars:write');+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');++ const rl = await limits.avatarPatch(auth.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many listing changes');++ const raw = await readJson(req);+ if (!raw || typeof raw !== 'object') return error(res, 400, 'invalid_request', 'body required');++ if (raw.action === 'delist') return handleDelist(req, res, auth, raw);+ return handleList(req, res, auth, raw);+});++async function handleList(req, res, auth, raw) {+ const parsed = listSchema.safeParse(raw);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; '));+ }+ const input = parsed.data;++ // The artifact must live in the caller's own R2 namespace — never let a+ // seller point a listing at another user's (or a system) object.+ const ns = `u/${auth.userId}/`;+ if (!input.artifact_key.startsWith(ns)) {+ return error(res, 403, 'forbidden', 'artifact_key must be in your own upload namespace');+ }++ const [clip] = await sql`+ select id, owner_id, name, slug, deleted_at+ from animation_clips+ where id = ${input.id} and deleted_at is null+ limit 1+ `;+ if (!clip || clip.owner_id !== auth.userId) {+ return error(res, 404, 'not_found', 'animation not found or not yours');+ }++ const priced = input.price && input.price > 0;++ // Resolve payout addresses: explicit overrides win, else fall back to the+ // seller's default payout wallets. A paid listing needs somewhere to settle.+ const payto = await resolvePayto(auth.userId, input);+ if (priced && !payto.base && !payto.solana) {+ return error(+ res,+ 422,+ 'payout_required',+ 'Add a Base or Solana payout wallet (or pass payto_base / payto_solana) before pricing this animation.',+ );+ }++ const priceAmount = priced ? input.price : null;+ const priceCurrency = priced ? input.currency : null;++ // Visibility is left untouched here: the marketplace feed keys on `listed`,+ // so a listed clip surfaces with public metadata + poster while its baked+ // motion data stays gated behind the x402 paywall (a private clip's+ // GET /api/animations/clips/:id still 404s for non-owners). Listing for sale+ // is intentionally not the same as publishing the clip free to the gallery.+ let row;+ try {+ [row] = await sql`+ update animation_clips set+ listed = ${input.listed},+ price_amount = ${priceAmount},+ price_currency = ${priceCurrency},+ artifact_key = ${input.artifact_key},+ artifact_bytes = ${input.artifact_bytes ?? null},+ artifact_mime = ${input.artifact_mime},+ creator_payto_base = ${payto.base},+ creator_payto_solana = ${payto.solana},+ creator_payto_bsc = ${payto.bsc}+ where id = ${input.id} and owner_id = ${auth.userId} and deleted_at is null+ returning id, slug, name, visibility, listed, price_amount, price_currency,+ artifact_bytes, artifact_mime, thumbnail_key, purchase_count+ `;+ } catch (err) {+ console.error('[animations/sell]', err?.message || err);+ return error(res, 500, 'db_error', 'Failed to update listing');+ }+ if (!row) return error(res, 404, 'not_found', 'animation not found or not yours');++ return json(res, 200, { listing: shape(row, payto) });+}++async function handleDelist(req, res, auth, raw) {+ const parsed = delistSchema.safeParse(raw);+ if (!parsed.success) return error(res, 400, 'validation_error', 'id required');++ const [row] = await sql`+ update animation_clips set listed = false+ where id = ${parsed.data.id} and owner_id = ${auth.userId} and deleted_at is null+ returning id, slug, name, visibility, listed, price_amount, price_currency,+ artifact_bytes, artifact_mime, thumbnail_key, purchase_count,+ creator_payto_base, creator_payto_solana, creator_payto_bsc+ `;+ if (!row) return error(res, 404, 'not_found', 'animation not found or not yours');+ return json(res, 200, {+ listing: shape(row, {+ base: row.creator_payto_base,+ solana: row.creator_payto_solana,+ bsc: row.creator_payto_bsc,+ }),+ });+}++// Explicit payout overrides win; otherwise pull the seller's default wallets.+async function resolvePayto(userId, input) {+ const out = {+ base: input.payto_base || null,+ solana: input.payto_solana || null,+ bsc: input.payto_bsc || null,+ };+ const missing = ['base', 'solana', 'bsc'].filter((c) => !out[c]);+ if (missing.length) {+ const rows = await sql`+ select chain, address from agent_payout_wallets+ where user_id = ${userId} and chain = any(${missing})+ order by is_default desc, created_at desc+ `;+ for (const c of missing) {+ const hit = rows.find((r) => r.chain === c);+ if (hit) out[c] = hit.address;+ }+ }+ return out;+}++function shape(row, payto) {+ return {+ id: row.id,+ slug: row.slug,+ name: row.name,+ visibility: row.visibility,+ listed: !!row.listed,+ price: row.price_amount ? { amount: String(row.price_amount), currency: row.price_currency } : null,+ artifact_bytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : null,+ artifact_mime: row.artifact_mime || null,+ thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,+ purchase_count: Number(row.purchase_count || 0),+ payout: { base: payto.base || null, solana: payto.solana || null, bsc: payto.bsc || null },+ };+}++async function resolveAuth(req, requiredScope) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (!bearer) return null;+ if (!hasScope(bearer.scope, requiredScope)) return null;+ return bearer;+}++export const __test__ = { listSchema, delistSchema, shape, resolvePayto };diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.jsindex 7b06be52f..44eabf99e 100644--- a/api/cron/forge-seed-cron.js+++ b/api/cron/forge-seed-cron.js@@ -25,7 +25,11 @@ import { SEED_PROMPTS, OG_USERNAMES } from '../_lib/seed-prompts.js';import { randomUUID } from 'node:crypto';const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';-const FETCH_TIMEOUT_MS = 25_000;+// Must exceed the forge endpoint's worst-case synchronous wait on the free+// NVIDIA lane (SUBMIT_TIMEOUT_MS = 45 s in api/_providers/nvidia.js) so the cron+// never aborts a generation that is legitimately still completing; still inside+// the 60 s function budget.+const FETCH_TIMEOUT_MS = 50_000;const MAX_CONCURRENT_PENDING = 3;const MIN_JOB_AGE_SECONDS = 20;diff --git a/api/forge.js b/api/forge.jsindex d6e890f62..241813e7a 100644--- a/api/forge.js+++ b/api/forge.js@@ -271,6 +271,90 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {return true;}+// Free Hugging Face Spaces image→3D lane (Hunyuan3D / TRELLIS / TripoSR on free+// GPU Spaces — the same provider the avatar reconstruction pipeline runs). The+// platform photo→3D default is the Replicate TRELLIS lane; when that account is+// over-quota or unreachable a photo upload would otherwise dead-end, because the+// free NVIDIA NIM fallback is text-only. This lane gives image mode the same+// "never dead-end" guarantee text mode already has — gated on HF_TOKEN, so it is+// a transparent no-op on deployments that don't set it. The provider blocks+// until the GLB is ready (Space queue + inference, within the 300s budget), so+// this returns status:'done' synchronously like the NVIDIA sync branch — no+// poll handle to route. Returns true once a 200 is written, false when the lane+// is unavailable so the caller can surface its own error.+async function runHfImageLane({ req, res, ip, imageUrls, prompt, aspect, tier, path }) {+ let provider;+ try {+ const mod = await import('./_providers/huggingface.js');+ provider = mod.createRegenProvider();+ } catch (err) {+ // HF_TOKEN absent or the Space chain is empty — the lane isn't available+ // on this deployment; fall through so the caller surfaces the real error.+ console.warn(`[forge] free HuggingFace image lane unavailable: ${err?.message || err}`);+ return false;+ }++ let resultGlbUrl;+ try {+ const submitted = await provider.submit({+ mode: 'reconstruct',+ sourceUrl: imageUrls[0],+ params: { images: imageUrls, prompt: prompt || undefined },+ });+ // submit() blocks and packs the finished GLB into extJobId; status() echoes+ // it back without re-hitting the Space.+ const finished = await provider.status(submitted.extJobId);+ resultGlbUrl = finished?.resultGlbUrl;+ if (!resultGlbUrl) throw new Error('HuggingFace returned no GLB');+ } catch (err) {+ console.warn(`[forge] free HuggingFace image lane failed: ${err?.message || err}`);+ return false;+ }++ const backendId = 'huggingface';+ const clientKey = clientKeyFrom(req);+ const syntheticJob = randomUUID().replace(/-/g, '');+ const creationId = await createCreation({+ clientKey,+ ipHash: hashIp(ip),+ prompt: prompt || 'image-to-3d',+ aspect,+ previewImageUrl: imageUrls[0],+ replicateJobId: syntheticJob,+ textToImageModel: null,+ viewsRequested: imageUrls.length,+ viewsUsed: imageUrls.length,+ multiview: imageUrls.length > 1,+ backend: backendId,+ tier: tier.id,+ path,+ });+ // Best-effort copy to R2 so the model survives the Space's ephemeral file URL;+ // fail-soft to the raw HF url so the client still gets a model either way.+ const durable = await materializeCreation({+ replicateJobId: syntheticJob,+ clientKey,+ glbUrl: resultGlbUrl,+ });+ json(res, 200, {+ job_id: null,+ creation_id: durable?.id ?? creationId,+ status: 'done',+ glb_url: durable?.glbUrl ?? resultGlbUrl,+ durable: Boolean(durable),+ mode: 'image_to_3d',+ path,+ tier: tier.id,+ backend: backendId,+ prompt: prompt || null,+ preview_image_url: imageUrls[0],+ reference_image_urls: [imageUrls[0]],+ eta_seconds: estimateEtaSeconds({ backendId, tier }),+ estimated_credits: estimateCredits({ backendId, path, tier }),+ });+ return true;+}+async function startJob(req, res) {const ip = clientIp(req);const body = await readJson(req, 8_000).catch(() => null);@@ -717,37 +801,46 @@ async function startJob(req, res) {params: reconstructParams,});} catch (submitErr) {- // Image→3D free fallback: when the standing platform TRELLIS lane- // (Replicate) is over-quota or unreachable, retry on the self-hosted- // Hunyuan3D Cloud Run worker if it's wired — so a photo upload never- // dead-ends. The text→3D fallback (free NVIDIA NIM, in the outer catch)+ // Image→3D free fallback chain: when the standing platform TRELLIS lane+ // (Replicate) is over-quota or unreachable, a photo upload must never+ // dead-end — the text→3D fallback (free NVIDIA NIM, in the outer catch)// can't take photos, so image mode would otherwise have no escape. Scoped- // to the default trellis lane: a text prompt prefers the genuinely-free- // NVIDIA lane over paid GPU compute, and an explicitly chosen Hunyuan3D /- // BYOK backend that fails surfaces its own error. Provenance reports- // backend:hunyuan3d so the downgrade stays visible.+ // to the default trellis lane: an explicitly chosen Hunyuan3D / BYOK+ // backend that fails surfaces its own error. Provenance reports the lane+ // that actually ran so the downgrade stays visible.+ const upstreamGone =+ isImageMode && backendId === 'trellis' && isUpstreamUnavailable(submitErr);+ if (!upstreamGone) throw submitErr;++ // Fallback #1 — self-hosted Hunyuan3D Cloud Run worker, when wired.const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;- const canFallbackToHunyuan =- isImageMode &&- backendId === 'trellis' &&- hunyuanUrl &&- process.env.GCP_RECONSTRUCTION_KEY &&- isUpstreamUnavailable(submitErr);- if (!canFallbackToHunyuan) throw submitErr;- console.warn(- `[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); degrading image→3D to self-hosted Hunyuan3D`,- );- backendId = 'hunyuan3d';- provider = createGcpProvider({ reconstructUrl: hunyuanUrl });- // Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.- reconstructParams.target_polycount = tier.polycount;- reconstructParams.tier = tier.id;- reconstructParams.path = path;- job = await provider.submit({- mode: 'reconstruct',- sourceUrl: referenceImageUrl,- params: reconstructParams,- });+ if (hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY) {+ console.warn(+ `[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); degrading image→3D to self-hosted Hunyuan3D`,+ );+ backendId = 'hunyuan3d';+ provider = createGcpProvider({ reconstructUrl: hunyuanUrl });+ // Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.+ reconstructParams.target_polycount = tier.polycount;+ reconstructParams.tier = tier.id;+ reconstructParams.path = path;+ job = await provider.submit({+ mode: 'reconstruct',+ sourceUrl: referenceImageUrl,+ params: reconstructParams,+ });+ } else {+ // Fallback #2 — free Hugging Face Spaces image→3D (gated on HF_TOKEN).+ // It blocks and writes its own status:'done' response; if it does, the+ // request is complete. Otherwise fall through to surface the real error.+ console.warn(+ `[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); trying free HuggingFace image→3D lane`,+ );+ if (await runHfImageLane({ req, res, ip, imageUrls: views, prompt, aspect, tier, path })) {+ return;+ }+ throw submitErr;+ }}// How the job was actually conditioned. The provider reports back whichdiff --git a/api/marketplace/animations.js b/api/marketplace/animations.jsnew file mode 100644index 000000000..0ddc03c59--- /dev/null+++ b/api/marketplace/animations.js@@ -0,0 +1,177 @@+// GET /api/marketplace/animations — the marketplace feed of creator-listed+// avatar animations.+//+// Surfaces animation_clips where listed = true: clips a creator priced + staged+// an animated GLB for, via api/animations/sell.js. Each row carries its price,+// thumbnail, creator, and the x402 download route the buyer pays against+// (api/x402/animation-download.js). Read-only + public — no auth required.+//+// ?q= full-text-ish match on name / description+// ?tag= single tag filter+// ?kind= animation | loop | sequence+// ?price= free | paid+// ?sort= recent (default) | popular | price_low | price_high+// ?limit= 1..60 (default 24)+// ?cursor= opaque pagination cursor++import { sql } from '../_lib/db.js';+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { publicUrl } from '../_lib/r2.js';++const SORTS = {+ recent: 'created_at desc',+ popular: 'purchase_count desc, created_at desc',+ price_low: 'price_amount asc nulls first, created_at desc',+ price_high: 'price_amount desc nulls last, created_at desc',+};++const DOWNLOAD_ROUTE = '/api/x402/animation-download';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');++ // Single-listing lookup (?id=) — public metadata + poster for the purchase+ // modal / deep link. Never returns the baked clip JSON (that's the product).+ const idParam = (url.searchParams.get('id') || '').trim();+ if (idParam) return handleOne(res, idParam);++ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 60);+ const q = (url.searchParams.get('q') || '').trim().slice(0, 80);+ const tag = (url.searchParams.get('tag') || '').trim().slice(0, 40);+ const kind = url.searchParams.get('kind');+ const price = url.searchParams.get('price');+ const sort = SORTS[url.searchParams.get('sort')] || SORTS.recent;+ const cursor = url.searchParams.get('cursor');++ // Positional-parameter WHERE — the Neon client doesn't interpolate nested+ // sql`` fragments (same pattern as api/animations/clips.js).+ const params = [];+ const conds = ['c.listed = true', 'c.deleted_at is null', 'c.artifact_key is not null'];++ if (q) {+ params.push(`%${q}%`);+ conds.push(`(c.name ilike $${params.length} or c.description ilike $${params.length})`);+ }+ if (tag) {+ params.push(tag);+ conds.push(`$${params.length} = any(c.tags)`);+ }+ if (kind && /^[a-z]+$/.test(kind)) {+ params.push(kind);+ conds.push(`c.kind = $${params.length}`);+ }+ if (price === 'free') conds.push('(c.price_amount is null or c.price_amount <= 0)');+ if (price === 'paid') conds.push('c.price_amount > 0');+ if (cursor) {+ const decoded = decodeCursor(cursor);+ if (decoded) {+ params.push(decoded.createdAt);+ conds.push(`c.created_at < $${params.length}`);+ }+ }+ params.push(limit + 1);++ let rows;+ try {+ rows = await sql(+ `select c.id, c.slug, c.name, c.description, c.kind, c.duration_ms,+ c.frame_count, c.fps, c.loop, c.tags, c.thumbnail_key,+ c.price_amount, c.price_currency, c.artifact_bytes,+ c.play_count, c.purchase_count, c.created_at,+ u.display_name as creator_name, u.username as creator_username,+ u.avatar_url as creator_avatar+ from animation_clips c+ left join users u on u.id = c.owner_id+ where ${conds.join(' and ')}+ order by ${sort}+ limit $${params.length}`,+ params,+ );+ } catch (err) {+ console.error('[marketplace/animations]', err?.message || err);+ return error(res, 500, 'db_error', 'Failed to load animations');+ }++ const hasMore = rows.length > limit;+ const page = hasMore ? rows.slice(0, limit) : rows;+ const items = page.map(shape);+ const nextCursor = hasMore ? encodeCursor({ createdAt: rows[limit - 1].created_at }) : null;++ res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');+ return json(res, 200, { items, next_cursor: nextCursor });+});++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++async function handleOne(res, id) {+ if (!UUID_RE.test(id)) return error(res, 400, 'invalid_request', 'id must be a uuid');+ let row;+ try {+ [row] = await sql`+ select c.id, c.slug, c.name, c.description, c.kind, c.duration_ms,+ c.frame_count, c.fps, c.loop, c.tags, c.thumbnail_key,+ c.price_amount, c.price_currency, c.artifact_bytes,+ c.play_count, c.purchase_count, c.created_at,+ u.display_name as creator_name, u.username as creator_username,+ u.avatar_url as creator_avatar+ from animation_clips c+ left join users u on u.id = c.owner_id+ where c.id = ${id} and c.listed = true and c.deleted_at is null+ and c.artifact_key is not null+ limit 1+ `;+ } catch (err) {+ console.error('[marketplace/animations/one]', err?.message || err);+ return error(res, 500, 'db_error', 'Failed to load animation');+ }+ if (!row) return error(res, 404, 'not_found', 'animation listing not found');+ res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');+ return json(res, 200, { item: shape(row) });+}++function shape(row) {+ const paid = row.price_amount != null && Number(row.price_amount) > 0;+ return {+ id: row.id,+ slug: row.slug,+ name: row.name,+ description: row.description,+ kind: row.kind,+ duration_ms: row.duration_ms,+ duration: row.duration_ms / 1000,+ frame_count: row.frame_count,+ fps: row.fps,+ loop: row.loop,+ tags: row.tags || [],+ thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,+ price: paid ? { amount: String(row.price_amount), currency: row.price_currency || 'USDC' } : null,+ free: !paid,+ size_bytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : null,+ play_count: Number(row.play_count || 0),+ purchase_count: Number(row.purchase_count || 0),+ download_url: `${DOWNLOAD_ROUTE}?id=${row.id}`,+ creator: {+ name: row.creator_name || row.creator_username || 'Anonymous',+ username: row.creator_username || null,+ avatar_url: row.creator_avatar || null,+ },+ created_at: row.created_at,+ };+}++function encodeCursor({ createdAt }) {+ return Buffer.from(JSON.stringify({ c: createdAt })).toString('base64url');+}+function decodeCursor(cursor) {+ try {+ const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));+ return { createdAt: new Date(obj.c) };+ } catch {+ return null;+ }+}++export const __test__ = { shape, encodeCursor, decodeCursor, SORTS };diff --git a/api/x402/animation-download.js b/api/x402/animation-download.jsnew file mode 100644index 000000000..e19a349e9--- /dev/null+++ b/api/x402/animation-download.js@@ -0,0 +1,197 @@+// GET /api/x402/animation-download?id=<uuid>+//+// Paid download for a creator-listed animation clip from the three.ws Animation+// Studio (/pose). A creator prices a clip + uploads a self-contained animated+// GLB (api/animations/sell.js, listed = true). Buyers pay once in USDC (Base or+// Solana) to unlock the GLB; every later download from the same wallet is free+// via Sign-In-With-X (CAIP-122). Free listings (no price) skip the paywall and+// return the file directly.+//+// The response is JSON with a short-lived presigned R2 URL — the client fetches+// the GLB directly from R2 (proxying real GLBs would blow the function+// response-size limit). Mirrors api/x402/asset-download.js.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { sql } from '../_lib/db.js';+import { presignGet } from '../_lib/r2.js';+import { error } from '../_lib/http.js';+import { env } from '../_lib/env.js';++const ROUTE = '/api/x402/animation-download';+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const PRESIGN_TTL_SECONDS = 60;++const DESCRIPTION =+ 'three.ws Animation Bazaar — pay once in USDC to unlock a creator-authored ' ++ 'avatar animation as a self-contained animated GLB hosted on R2. Wallets ' ++ 'that have already paid can re-download for free by signing in with SIWX ' ++ '(CAIP-122). Each clip carries its own price and creator payout address; the ' ++ 'response returns a short-lived presigned URL the client uses to fetch the ' ++ 'GLB directly from R2.';++const INPUT_EXAMPLE = { id: '00000000-0000-0000-0000-000000000000' };++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['id'],+ properties: {+ id: {+ type: 'string',+ format: 'uuid',+ description: 'Animation clip id from the marketplace animations feed.',+ },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ id: '00000000-0000-0000-0000-000000000000',+ slug: 'spin-kick-combo',+ name: 'Spin Kick Combo',+ mimeType: 'model/gltf-binary',+ sizeBytes: 248_400,+ expiresAt: '2026-06-15T18:48:09.000Z',+ downloadUrl: 'https://three.ws/cdn/u/.../spin-kick-combo.glb?X-Amz-Algorithm=...',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'id', 'name', 'mimeType', 'downloadUrl', 'expiresAt'],+ properties: {+ ok: { type: 'boolean', const: true },+ id: { type: 'string', format: 'uuid' },+ slug: { type: 'string' },+ name: { type: 'string' },+ mimeType: { type: 'string' },+ sizeBytes: { type: 'integer', minimum: 0 },+ expiresAt: { type: 'string', format: 'date-time' },+ downloadUrl: { type: 'string', format: 'uri' },+ },+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++async function loadListing(id) {+ const rows = await sql`+ select id, slug, name, listed, price_amount, price_currency, artifact_key,+ artifact_mime, artifact_bytes, creator_payto_base,+ creator_payto_solana, creator_payto_bsc+ from animation_clips+ where id = ${id} and deleted_at is null+ limit 1+ `;+ return rows[0] || null;+}++// USDC atomic units (6 decimals) from the stored human amount.+function priceAtomics(amount) {+ return String(Math.round(Number(amount) * 1_000_000));+}++// EIP-4361 statements are single-line and restricted to RFC 3986 chars — strip+// anything illegal so browser wallets render a signable message.+const SIWE_STATEMENT_DISALLOWED = /[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;= ]+/g;+function buildSiwxStatement(name) {+ const clean = String(name || '').replace(SIWE_STATEMENT_DISALLOWED, '').replace(/\s+/g, ' ').trim();+ return clean+ ? `Sign in to re-download ${clean} without re-paying.`+ : 'Sign in to re-download this animation without re-paying.';+}++function buildPayToOverride(row) {+ const out = {};+ if (row.creator_payto_base) out.base = row.creator_payto_base;+ if (row.creator_payto_solana) out.solana = row.creator_payto_solana;+ if (row.creator_payto_bsc) out.bsc = row.creator_payto_bsc;+ return Object.keys(out).length ? out : undefined;+}++async function presignPayload(row) {+ const url = await presignGet({ key: row.artifact_key, expiresIn: PRESIGN_TTL_SECONDS });+ return {+ ok: true,+ id: row.id,+ slug: row.slug,+ name: row.name,+ mimeType: row.artifact_mime || 'model/gltf-binary',+ sizeBytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : 0,+ expiresAt: new Date(Date.now() + PRESIGN_TTL_SECONDS * 1000).toISOString(),+ downloadUrl: url,+ };+}++export default async function handler(req, res) {+ const id = req.query?.id ? String(req.query.id).trim() : '';+ if (!UUID_RE.test(id)) {+ return error(res, 400, 'id_required', 'query parameter "id" must be a clip uuid');+ }++ let row;+ try {+ row = await loadListing(id);+ } catch (err) {+ return error(res, 502, 'animation_lookup_failed', err.message);+ }+ if (!row || !row.listed || !row.artifact_key) {+ return error(res, 404, 'animation_not_found', `no listed animation with id "${id}"`);+ }++ // Free listing — no paywall, hand back the presigned URL directly.+ if (!row.price_amount || Number(row.price_amount) <= 0) {+ try {+ return res.status(200).json(await presignPayload(row));+ } catch (err) {+ return error(res, 502, 'presign_failed', err.message);+ }+ }++ const inner = paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: priceAtomics(row.price_amount),+ networks: ['base', 'solana'],+ description: `${DESCRIPTION} — currently delivering: ${row.name}.`,+ mimeType: 'application/json',+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Animation Bazaar',+ tags: ['3d', 'animation', 'glb', 'avatar', 'motion', 'download'],+ }),+ payTo: buildPayToOverride(row),+ // Per-clip SIWX grant: bake the id into the resource URL so paying for+ // one clip can't unlock another via signature (the grant row is keyed on+ // (resource, address)). The 402 challenge advertises the same URL.+ resourceUrlBuilder: () => `${env.APP_ORIGIN}${ROUTE}?id=${encodeURIComponent(row.id)}`,+ siwx: {+ statement: buildSiwxStatement(row.name),+ ttlSeconds: null, // permanent per (clip, wallet) once paid+ expirationSeconds: 300,+ },+ async handler(ctx) {+ // Count only fresh paid settlements — not free SIWX re-downloads.+ if (ctx?.payer && !ctx?.bypass) {+ queueMicrotask(async () => {+ try {+ await sql`update animation_clips set purchase_count = purchase_count + 1 where id = ${row.id}`;+ } catch (err) {+ console.warn('[animation-download] purchase_count bump failed', err?.message);+ }+ });+ }+ return presignPayload(row);+ },+ });++ return inner(req, res);+}diff --git a/data/changelog.json b/data/changelog.jsonindex fd7fb58a2..898040851 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,20 @@{"$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-15",+ "title": "Sniper Arena — watch AI agents trade pump.fun live",+ "summary": "Agents can now trade pump.fun autonomously. A new always-on engine watches every launch in real time, scores it against an agent's strategy (market-cap band, creator track record, socials), and — when it qualifies — buys from the agent's own Solana wallet, then manages the position to a take-profit, stop-loss, trailing stop, or timeout exit. Arming an agent is opt-in and capped: you set a daily budget, a per-trade size, and a mandatory stop-loss, with a kill switch that halts new buys instantly. The new Sniper Arena at three.ws/play/arena shows it all happening live — a P&L leaderboard, a streaming trade ticker where every fill links to its on-chain transaction, and the top agent's 3D avatar reacting to its own wins. Autonomous trading is experimental and you can lose the funds you commit.",+ "tags": ["feature"],+ "link": "/play/arena"+ },+ {+ "date": "2026-06-15",+ "title": "There's a cover at the Pole Club door",+ "summary": "The club now has a line outside. Before the room opens you pay a $0.01 USDC cover at the door via x402, and an on-chain bouncer checks the paying wallet — banned wallets are turned away, everyone else gets in with a door tier (newcomer, regular, or VIP) based on their past club nights. Pay once and you're in for the night; reopen the page and the velvet rope drops automatically. The 3D room loads behind the door while you're in line, so it's warm the moment you step in.",+ "tags": ["feature"],+ "link": "/club"+ },{"date": "2026-06-15","title": "Pose any avatar — a full motion library on the avatar page",diff --git a/public/changelog.json b/public/changelog.jsonindex 5871e9fb2..7d58c3897 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-06-15T15:13:26.566Z",+ "generated_at": "2026-06-15T15:45:28.924Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-15",+ "type": "launch",+ "title": "Sniper Arena — autonomous AI agents trading live",+ "summary": "Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.",+ "link": "/play/arena",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-15","type": "update",@@ -223,6 +233,16 @@"security"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Sniper Arena — watch AI agents trade pump.fun live",+ "summary": "Agents can now trade pump.fun autonomously. A new always-on engine watches every launch in real time, scores it against an agent's strategy (market-cap band, creator track record, socials), and — when it qualifies — buys from the agent's own Solana wallet, then manages the position to a take-profit, stop-loss, trailing stop, or timeout exit. Arming an agent is opt-in and capped: you set a daily budget, a per-trade size, and a mandatory stop-loss, with a kill switch that halts new buys instantly. The new Sniper Arena at three.ws/play/arena shows it all happening live — a P&L leaderboard, a streaming trade ticker where every fill links to its on-chain transaction, and the top agent's 3D avatar reacting to its own wins. Autonomous trading is experimental and you can lose the funds you commit.",+ "link": "/play/arena",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-15","type": "update",@@ -295,6 +315,16 @@"fix"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "There's a cover at the Pole Club door",+ "summary": "The club now has a line outside. Before the room opens you pay a $0.01 USDC cover at the door via x402, and an on-chain bouncer checks the paying wallet — banned wallets are turned away, everyone else gets in with a door tier (newcomer, regular, or VIP) based on their past club nights. Pay once and you're in for the night; reopen the page and the velvet rope drops automatically. The 3D room loads behind the door while you're in line, so it's warm the moment you step in.",+ "link": "/club",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-15","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 3ecce52c8..a63d7feee 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Sniper Arena — autonomous AI agents trading live</title>+ <link>https://three.ws/play/arena</link>+ <guid isPermaLink="false">2026-06-15:Sniper Arena — autonomous AI agents trading live</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.</description>+ </item><item><title>After you launch a coin, jump straight to viewing or managing it</title><link>https://three.ws/pump-dashboard</link>@@ -174,6 +182,14 @@<category>feature</category><description>When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green "Validated" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows "Validation failed" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration.</description></item>+ <item>+ <title>Sniper Arena — watch AI agents trade pump.fun live</title>+ <link>https://three.ws/play/arena</link>+ <guid isPermaLink="false">2026-06-15:Sniper Arena — watch AI agents trade pump.fun live</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agents can now trade pump.fun autonomously. A new always-on engine watches every launch in real time, scores it against an agent's strategy (market-cap band, creator track record, socials), and — when it qualifies — buys from the agent's own Solana wallet, then manages the position to a take-profit, stop-loss, trailing stop, or timeout exit. Arming an agent is opt-in and capped: you set a daily budget, a per-trade size, and a mandatory stop-loss, with a kill switch that halts new buys instantly. The new Sniper Arena at three.ws/play/arena shows it all happening live — a P&L leaderboard, a streaming trade ticker where every fill links to its on-chain transaction, and the top agent's 3D avatar reacting to its own wins. Autonomous trading is experimental and you can lose the funds you commit.</description>+ </item><item><title>Strategy Lab now catches broken trading strategies before they run</title><link>https://three.ws/strategy-lab</link>@@ -230,6 +246,14 @@<category>fix</category><description>The site header was being clipped to a sliver on most pages — the menu, search, and account controls were cut off and the dropdowns wouldn't open. An old style rule meant for the standalone 3D viewer's compact toolbar was leaking onto the shared navigation, forcing it to a fixed height and hiding everything below it. The viewer rule is now scoped to only the viewer, so the full navigation renders at its natural height across the whole site.</description></item>+ <item>+ <title>There's a cover at the Pole Club door</title>+ <link>https://three.ws/club</link>+ <guid isPermaLink="false">2026-06-15:There's a cover at the Pole Club door</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The club now has a line outside. Before the room opens you pay a $0.01 USDC cover at the door via x402, and an on-chain bouncer checks the paying wallet — banned wallets are turned away, everyone else gets in with a door tier (newcomer, regular, or VIP) based on their past club nights. Pay once and you're in for the night; reopen the page and the velvet rope drops automatically. The 3D room loads behind the door while you're in line, so it's warm the moment you step in.</description>+ </item><item><title>three.ws can now register itself on-chain on Solana</title><link>https://three.ws/.well-known/agent-registration.json</link>diff --git a/public/demos-embed/gallery.html b/public/demos-embed/gallery.htmlindex 0ac0e925e..a458bb27c 100644--- a/public/demos-embed/gallery.html+++ b/public/demos-embed/gallery.html@@ -199,7 +199,6 @@<label for="gallery-sort-embed">Sort:</label><select id="gallery-sort-embed" data-role="sort"><option value="newest">Newest</option>- <option value="popular">Most viewed</option><option value="alpha">A → Z</option></select></div>diff --git a/public/features.json b/public/features.jsonindex 2bb81993a..30c28dc9d 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T15:13:26.376Z",+ "generated_at": "2026-06-15T15:45:28.873Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -536,6 +536,16 @@"tags": [],"showcase": false},+ {+ "path": "/play/arena",+ "title": "Sniper Arena — autonomous AI agents trading live",+ "description": "Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.",+ "added": "2026-06-15",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/pumpfun","title": "Pump.fun Stream",diff --git a/public/gallery/gallery.js b/public/gallery/gallery.jsindex 5b97e11f7..5045f1ff9 100644--- a/public/gallery/gallery.js+++ b/public/gallery/gallery.js@@ -213,9 +213,7 @@ async function loadPage() {let avatars = Array.isArray(data.avatars) ? data.avatars : [];// Client-side sort- if (state.sortBy === 'popular') {- avatars = [...avatars].sort((a, b) => (b.view_count || 0) - (a.view_count || 0));- } else if (state.sortBy === 'alpha') {+ if (state.sortBy === 'alpha') {avatars = [...avatars].sort((a, b) =>(a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),);diff --git a/public/gallery/index.html b/public/gallery/index.htmlindex 0f66c3797..f4608d116 100644--- a/public/gallery/index.html+++ b/public/gallery/index.html@@ -118,7 +118,6 @@<label for="gallery-sort">Sort:</label><select id="gallery-sort" data-role="sort"><option value="newest">Newest</option>- <option value="popular">Most viewed</option><option value="alpha">A → Z</option></select></div>diff --git a/public/llms-full.txt b/public/llms-full.txtindex 5ce4ed4b0..28defda33 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -326,6 +326,12 @@ URL: https://three.ws/play/agent-walletWatch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.+### Sniper Arena — autonomous AI agents trading live++URL: https://three.ws/play/arena++Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.+### Pump.fun StreamURL: https://three.ws/pumpfundiff --git a/public/llms.txt b/public/llms.txtindex 001554207..4e33dba2c 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -75,6 +75,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.- [Pay (x402)](https://three.ws/pay): Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.- [Agent Wallet (x402 on Solana)](https://three.ws/play/agent-wallet): Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.+- [Sniper Arena — autonomous AI agents trading live](https://three.ws/play/arena): Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.- [Pump.fun Stream](https://three.ws/pumpfun): Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.- [Pump Live](https://three.ws/pump-live): Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.diff --git a/public/marketplace.css b/public/marketplace.cssindex 6325ad3c6..b1e2a4c8f 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -4402,3 +4402,177 @@ body.market-page > header {.card-heart:hover,.card-star:hover { transform: none; }}++/* ── Creator animation listings + purchase modal ─────────────────────────────+ Marketplace surface for clips authored in the Animation Studio (/pose) and+ listed for sale via /api/animations/sell. Rendered by src/marketplace.js. */+.market-anim-listings { margin-bottom: 8px; }+.market-anim-listings-head,+.market-anim-library-head {+ display: flex;+ align-items: baseline;+ gap: 10px;+ margin: 4px 0 14px;+}+.market-anim-library-head {+ margin-top: 28px;+ padding-top: 20px;+ border-top: 1px solid var(--stroke);+}+.market-anim-listings-title { font-size: 15px; font-weight: 700; color: #fafafa; margin: 0; }+.market-anim-listings-sub { font-size: 12px; color: #a1a1aa; }+.market-anim-listings-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }++.anim-listing-card {+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: 16px;+ overflow: hidden;+ cursor: pointer;+ display: flex;+ flex-direction: column;+ transition: border-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;+}+.anim-listing-card:hover,+.anim-listing-card:focus-visible {+ border-color: rgba(255, 255, 255, 0.2);+ transform: translateY(-2px);+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.34);+ outline: none;+}+.anim-listing-media {+ position: relative;+ aspect-ratio: 4 / 3;+ background:+ radial-gradient(circle at 50% 55%, rgba(255, 255, 255, 0.06), transparent 70%),+ linear-gradient(180deg, #0a0a0a, #060606);+}+.anim-listing-thumb { width: 100%; height: 100%; object-fit: cover; display: block; }+.anim-listing-thumb-empty {+ width: 100%; height: 100%;+ display: flex; align-items: center; justify-content: center;+ font-size: 38px; opacity: 0.5;+}+.anim-listing-price {+ position: absolute;+ top: 10px; right: 10px;+ font-size: 11px; font-weight: 700;+ padding: 4px 9px;+ border-radius: 999px;+ backdrop-filter: blur(8px);+ letter-spacing: 0.02em;+}+.anim-listing-price.paid {+ background: rgba(99, 102, 241, 0.22);+ color: #c7d2fe;+ border: 1px solid rgba(129, 140, 248, 0.45);+}+.anim-listing-price.free {+ background: rgba(52, 211, 153, 0.18);+ color: #6ee7b7;+ border: 1px solid rgba(52, 211, 153, 0.4);+}+.anim-listing-body { padding: 12px 14px 6px; flex: 1; }+.anim-listing-name {+ font-size: 14px; font-weight: 600; color: #fafafa;+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+}+.anim-listing-creator { font-size: 12px; color: #a1a1aa; margin-top: 2px; }+.anim-listing-meta { display: flex; gap: 5px; margin-top: 9px; flex-wrap: wrap; }+.anim-listing-cta {+ padding: 10px 14px 13px;+ font-size: 12px; font-weight: 600; color: #fafafa;+ opacity: 0.55;+ transition: opacity 0.15s ease;+}+.anim-listing-card:hover .anim-listing-cta,+.anim-listing-card:focus-visible .anim-listing-cta { opacity: 0.95; }++.anim-buy-overlay {+ position: fixed; inset: 0; z-index: 1000;+ display: flex; align-items: center; justify-content: center;+ padding: 20px;+ background: rgba(0, 0, 0, 0.66);+ backdrop-filter: blur(4px);+ animation: anim-buy-fade 0.16s ease;+}+@keyframes anim-buy-fade { from { opacity: 0; } to { opacity: 1; } }+.anim-buy-card {+ position: relative;+ width: min(720px, 100%);+ max-height: 90vh;+ overflow: auto;+ display: grid;+ grid-template-columns: 1fr 1fr;+ background: var(--surface-1, #0d0d0d);+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: 20px;+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.6);+ animation: anim-buy-rise 0.2s ease;+}+@keyframes anim-buy-rise {+ from { transform: translateY(10px); opacity: 0; }+ to { transform: translateY(0); opacity: 1; }+}+.anim-buy-close {+ position: absolute; top: 12px; right: 12px; z-index: 2;+ width: 32px; height: 32px;+ border-radius: 50%;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(0, 0, 0, 0.4);+ color: #fafafa; cursor: pointer;+ font-size: 14px; line-height: 1;+ transition: background 0.15s ease;+}+.anim-buy-close:hover { background: rgba(255, 255, 255, 0.12); }+.anim-buy-media {+ position: relative;+ background:+ radial-gradient(circle at 50% 55%, rgba(255, 255, 255, 0.06), transparent 70%),+ linear-gradient(180deg, #0a0a0a, #050505);+ border-radius: 20px 0 0 20px;+ min-height: 320px;+}+.anim-buy-media img { width: 100%; height: 100%; object-fit: cover; border-radius: 20px 0 0 20px; }+.anim-buy-media-empty {+ position: absolute; inset: 0;+ display: flex; align-items: center; justify-content: center;+ font-size: 64px; opacity: 0.45;+}+.anim-buy-info { padding: 26px 24px 22px; min-width: 0; }+.anim-buy-name { font-size: 20px; font-weight: 700; color: #fafafa; margin: 0; line-height: 1.2; }+.anim-buy-creator { font-size: 13px; color: #a1a1aa; margin: 4px 0 0; }+.anim-buy-desc { font-size: 13px; color: #d4d4d8; line-height: 1.5; margin: 12px 0 0; }+.anim-buy-meta { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 14px; }+.anim-buy-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; }+.anim-buy-actions { margin-top: 20px; }+.anim-buy-go { width: 100%; }+.anim-buy-note { font-size: 12px; color: #a1a1aa; line-height: 1.5; margin: 12px 0 0; }+.anim-buy-note-err { color: #fca5a5; }+.anim-buy-snippet { margin-top: 16px; border-top: 1px solid var(--stroke); padding-top: 12px; }+.anim-buy-snippet summary { font-size: 12px; font-weight: 600; color: #c7d2fe; cursor: pointer; }+.anim-buy-endpoint { display: flex; align-items: center; gap: 8px; margin-top: 10px; }+.anim-buy-endpoint code {+ flex: 1; min-width: 0;+ font-size: 11px; color: #d4d4d8;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--stroke);+ border-radius: 8px;+ padding: 7px 9px;+ overflow-x: auto; white-space: nowrap;+}+.anim-buy-code {+ margin: 10px 0 0;+ font-size: 11px; line-height: 1.5; color: #d4d4d8;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--stroke);+ border-radius: 10px;+ padding: 12px;+ overflow-x: auto;+}+.anim-buy-code code { white-space: pre; }+@media (max-width: 600px) {+ .anim-buy-card { grid-template-columns: 1fr; }+ .anim-buy-media { border-radius: 20px 20px 0 0; min-height: 200px; }+ .anim-buy-media img { border-radius: 20px 20px 0 0; }+}diff --git a/public/nav.css b/public/nav.cssindex 6c7b727e1..9fd5b64c9 100644--- a/public/nav.css+++ b/public/nav.css@@ -319,11 +319,21 @@border-radius: 13px;box-shadow: 0 20px 54px rgba(0,0,0,0.55), 0 2px 8px rgba(0,0,0,0.4);display: grid; gap: 1px;+ /* Cap every dropdown to the viewport so long menus (Build, Discover, …)+ scroll their tail instead of running off the bottom of the screen where+ the items become unclickable. The header is ~56px tall and the popover+ opens 9px below it, so reserve ~90px total to keep a comfortable margin. */+ max-height: calc(100vh - 90px);+ overflow-y: auto;+ overscroll-behavior: contain;opacity: 0; transform: translateY(-6px) scale(0.985);transform-origin: top left; pointer-events: none;transition: opacity 0.16s ease, transform 0.16s ease;z-index: 200;}+.nav-pop::-webkit-scrollbar { width: 4px; }+.nav-pop::-webkit-scrollbar-track { background: transparent; }+.nav-pop::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 2px; }/* invisible hover bridge so the menu doesn't close in the gap */.nav-pop::before {content: ""; position: absolute; top: -10px; left: 0; right: 0; height: 12px;@@ -338,22 +348,15 @@max-width: calc(100vw - 24px);}/* Labs mega menu — categorized columns, right-anchored (it's the last group).- Capped to the viewport so the tail of a long menu scrolls instead of being- clipped offscreen. */+ The viewport cap + scroll are inherited from .nav-pop. */.nav-pop.mega {left: auto; right: 0;transform-origin: top right;min-width: 632px;max-width: calc(100vw - 24px);- max-height: calc(100vh - 90px);- overflow-y: auto;- overscroll-behavior: contain;grid-template-columns: repeat(3, 1fr);gap: 2px 6px; padding: 8px;}-.nav-pop.mega::-webkit-scrollbar { width: 4px; }-.nav-pop.mega::-webkit-scrollbar-track { background: transparent; }-.nav-pop.mega::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 2px; }.nav-col { display: flex; flex-direction: column; gap: 1px; min-width: 0; }.nav-col-h {font-family: var(--nv-font-mono); font-size: var(--text-xs);diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex e99b0f5fe..214e6cc98 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 262 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 263 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 262 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 263 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -452,7 +452,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>31</span></h2>+ <h2>Crypto<span class="sm-count" data-count>32</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -477,6 +477,13 @@<span class="sm-desc">Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.</span></a></li>+ <li>+ <a href="/play/arena">+ <span class="sm-title">Sniper Arena — autonomous AI agents trading live</span>+ <span class="sm-path">/play/arena</span>+ <span class="sm-desc">Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.</span>+ </a>+ </li><li><a href="/pumpfun"><span class="sm-title">Pump.fun Stream</span>diff --git a/src/animation-manager.js b/src/animation-manager.jsindex 8f80850d7..c34ffbe32 100644--- a/src/animation-manager.js+++ b/src/animation-manager.js@@ -1,5 +1,6 @@import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';import { canonicalizeBoneName } from './glb-canonicalize.js';+import { canonicalNodeMapFromObject, retargetClip } from './animation-retarget.js';import { log } from './shared/log.js';// Minimum number of canonical bones a skinned model must expose before the@@ -46,8 +47,8 @@ export class AnimationManager {this._animationDefs = [];/** @type {Set<string>} Clip names that failed to load — buttons grayed out in UI. */this._failed = new Set();- /** @type {Set<string>|null} Bone/node names of the currently attached model. */- this._boneNames = null;+ /** @type {Map<string,string>|null} canonical bone → actual node name on the attached model. */+ this._canonicalToNode = null;/** @type {boolean} Whether the attached model's rig can play the canonical clip library. */this._canonicalClipsSupported = false;}@@ -66,17 +67,35 @@ export class AnimationManager {this.actions.clear();this.currentAction = null;this.currentName = null;- this._boneNames = _collectBoneNames(model);+ // Build the canonical→node map once. Every clip is retargeted through it,+ // so the library drives ANY humanoid rig — Mixamo, VRM-via-Mixamo,+ // CharacterStudio, Blender — not just an already-canonical Avaturn rig.+ this._canonicalToNode = canonicalNodeMapFromObject(model);this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);for (const [name, clip] of this.clips) {- const filtered = _filterClip(clip, this._boneNames);- const action = this.mixer.clipAction(filtered);+ const bound = this._retarget(clip);+ if (!bound) continue;+ const action = this.mixer.clipAction(bound);action.enabled = true;this.actions.set(name, action);}}+ /**+ * Retarget a canonical-skeleton library clip onto the attached model's actual+ * bone names. Returns null when the rig shares too few bones to perform the+ * motion (a static prop, a non-humanoid rig), so callers skip building a dead+ * action. A clip whose tracks already match the rig 1:1 round-trips unchanged.+ * @param {THREE.AnimationClip} clip+ * @returns {THREE.AnimationClip|null}+ */+ _retarget(clip) {+ if (!this._canonicalToNode || this._canonicalToNode.size === 0) return null;+ const { clip: out } = retargetClip(clip, this._canonicalToNode);+ return out;+ }+/** Detach, stop all actions, dispose mixer. */detach() {if (this.mixer) {@@ -85,7 +104,7 @@ export class AnimationManager {this.mixer = null;}this.model = null;- this._boneNames = null;+ this._canonicalToNode = null;this._canonicalClipsSupported = false;this.actions.clear();this.currentAction = null;@@ -155,12 +174,14 @@ export class AnimationManager {this.clips.set(name, clip);if (this.model && this.mixer) {- const filtered = _filterClip(clip, this._boneNames);- const action = this.mixer.clipAction(filtered);- action.enabled = true;- action.setLoop(opts.loop === false ? LoopOnce : LoopRepeat);- if (opts.loop === false) action.clampWhenFinished = true;- this.actions.set(name, action);+ const bound = this._retarget(clip);+ if (bound) {+ const action = this.mixer.clipAction(bound);+ action.enabled = true;+ action.setLoop(opts.loop === false ? LoopOnce : LoopRepeat);+ if (opts.loop === false) action.clampWhenFinished = true;+ this.actions.set(name, action);+ }}return clip;}@@ -304,12 +325,6 @@ export class AnimationManager {}}-function _collectBoneNames(model) {- const names = new Set();- model.traverse((n) => { if (n.name) names.add(n.name); });- return names;-}-// A pre-baked clip only deforms the mesh when its tracks address real skeleton// bones. Require both a SkinnedMesh and enough canonically-named bones so we// don't mistake a static prop (whose node happens to be named "Head") for a@@ -326,16 +341,3 @@ function _modelSupportsCanonicalClips(model) {});return hasSkinnedMesh && canonical.size >= MIN_CANONICAL_BONES;}--function _filterClip(clip, boneNames) {- if (!boneNames || boneNames.size === 0) return clip;- const valid = clip.tracks.filter((t) => {- const dot = t.name.indexOf('.');- const bone = dot !== -1 ? t.name.slice(0, dot) : t.name;- return boneNames.has(bone);- });- if (valid.length === clip.tracks.length) return clip;- const copy = clip.clone();- copy.tracks = valid;- return copy;-}diff --git a/src/app.js b/src/app.jsindex 1fea05c6b..7c8801f4a 100644--- a/src/app.js+++ b/src/app.js@@ -1719,7 +1719,12 @@ class App {});if (!rootFile) {+ // No model in the dropped/selected set — show the designed error and+ // stop. Falling through to view() would hand `undefined` to+ // URL.createObjectURL ("Overload resolution failed") and throw an+ // uncaught TypeError that pages the ops channel.this.onError('No .gltf or .glb asset found.');+ return;}return this.view(rootFile, rootPath, fileMap);diff --git a/src/avatar-page.js b/src/avatar-page.jsindex 9f7fd6be1..26b3999af 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -363,7 +363,7 @@ function renderShell(glbUrl) {</div><div class="av-panel" data-panel="pose"><div class="av-pose" id="av-pose">- <div class="av-pose-loading" id="av-pose-loading">Open this tab to load the pose stage.</div>+ <div class="av-pose-loading" id="av-pose-loading">Loading the pose stage…</div><div class="av-pose-body" id="av-pose-body" hidden><div class="av-pose-transport" id="av-pose-transport"><span class="av-pose-now" id="av-pose-now">Idle</span>diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.jsindex af1f4f516..8d9e24963 100644--- a/src/glb-canonicalize.js+++ b/src/glb-canonicalize.js@@ -61,6 +61,23 @@ const LOOKUP = (() => {*/export function canonicalizeBoneName(name) {if (typeof name !== 'string' || !name) return null;+ const direct = _lookupBone(name);+ if (direct) return direct;+ // glTF/FBX node de-dup suffix: exporters (CharacterStudio, Blender's glTF+ // writer, FBX2glTF) append `_NN` to keep node names unique, producing+ // `mixamorig:Hips_01`, `Spine1_03`, `LeftForeArm_010`. The plain lookup+ // can't see past the suffix, so retry once with a trailing `_<digits>`+ // removed — but only when the un-stripped form didn't already resolve, so a+ // genuinely numbered bone like `left_hand_index_1` still maps to+ // `LeftHandIndex1` before we'd ever strip its index.+ const deduped = name.replace(/_\d+$/, '');+ if (deduped !== name) return _lookupBone(deduped);+ return null;+}++// Reduce a single bone-name variant to canonical form via the lookup table.+// Strips vendor prefixes and separators; returns null on no match.+function _lookupBone(name) {let s = name;// Strip well-known vendor prefixes (case-insensitive, in priority order).s = s.replace(/^mixamorig\d*[_:]?/i, '');diff --git a/src/marketplace.js b/src/marketplace.jsindex a1c0f882f..3982d0b45 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -3089,31 +3089,148 @@ function bindAgentPricingModal() {// ── Animations tab ───────────────────────────────────────────────────────-const animState = { loaded: false, loading: false, items: [], filter: 'all', q: '' };+const animState = {+ loaded: false, loading: false, items: [], filter: 'all', q: '',+ listings: [], listingsLoaded: false,+};async function loadAnimationsTab(force = false) {if (animState.loading) return;- if (animState.loaded && !force) { renderAnimationsGrid(); return; }+ if (animState.loaded && !force) { renderCreatorListings(); renderAnimationsGrid(); return; }animState.loading = true;const grid = $('animations-grid');if (grid) grid.innerHTML = renderSkeletons(8);- try {- const r = await fetch('/animations/manifest.json');- if (!r.ok) throw new Error(`manifest ${r.status}`);- const raw = await r.json();- const arr = Array.isArray(raw) ? raw : (raw.animations || []);- animState.items = arr;+ const listEl = ensureListingsContainer();+ if (listEl) listEl.querySelector('.market-anim-listings-grid').innerHTML = renderSkeletons(4);++ // Curated preset library + creator listings load independently — one failing+ // must not blank the other.+ const [presetRes, listingRes] = await Promise.allSettled([+ fetch('/animations/manifest.json').then((r) => {+ if (!r.ok) throw new Error(`manifest ${r.status}`);+ return r.json();+ }),+ fetch('/api/marketplace/animations?limit=48').then((r) => {+ if (!r.ok) throw new Error(`listings ${r.status}`);+ return r.json();+ }),+ ]);++ if (presetRes.status === 'fulfilled') {+ const raw = presetRes.value;+ animState.items = Array.isArray(raw) ? raw : (raw.animations || []);animState.loaded = true;- } catch (err) {- log.error('[marketplace] animations', err);- if (grid) grid.innerHTML = renderErrorState('animations');- } finally {- animState.loading = false;+ } else {+ log.error('[marketplace] animations presets', presetRes.reason);+ if (grid && !animState.items.length) grid.innerHTML = renderErrorState('animations');+ }++ if (listingRes.status === 'fulfilled') {+ animState.listings = listingRes.value.items || [];+ } else {+ log.error('[marketplace] animations listings', listingRes.reason);+ animState.listings = [];}+ animState.listingsLoaded = true;+ animState.loading = false;++ renderCreatorListings();renderAnimationsGrid();bindAnimationsEvents();}+// ── Creator listings (paid / free marketplace clips) ──────────────────────+// Inserted as its own section above the curated preset library. The preset+// grid (#animations-grid) keeps its existing markup; this block is created+// on demand so the static HTML stays untouched.+function ensureListingsContainer() {+ let section = $('animations-listings');+ if (section) return section;+ const tab = document.querySelector('#market-animations-section .market-skills-tab');+ const grid = $('animations-grid');+ if (!tab || !grid) return null;+ section = document.createElement('div');+ section.id = 'animations-listings';+ section.className = 'market-anim-listings';+ section.innerHTML = `+ <div class="market-anim-listings-head">+ <h3 class="market-anim-listings-title">From creators</h3>+ <span class="market-anim-listings-sub" id="animations-listings-sub"></span>+ </div>+ <div class="market-grid market-anim-listings-grid" id="animations-listings-grid"></div>+ <div class="market-anim-library-head"><h3 class="market-anim-listings-title">Animation library</h3>+ <span class="market-anim-listings-sub">Curated clips, free on any avatar</span></div>`;+ tab.insertBefore(section, grid);+ return section;+}++function renderCreatorListings() {+ const section = ensureListingsContainer();+ if (!section) return;+ const grid = section.querySelector('.market-anim-listings-grid');+ const sub = $('animations-listings-sub');+ const q = animState.q.toLowerCase();++ const filtered = animState.listings.filter((it) => {+ if (animState.filter === 'loop' && it.loop !== true) return false;+ if (animState.filter === 'action' && it.loop !== false) return false;+ if (q && !(`${it.name} ${it.creator?.name || ''} ${(it.tags || []).join(' ')}`.toLowerCase().includes(q))) return false;+ return true;+ });++ // Hide the whole "From creators" header + library divider when there are no+ // listings at all (keeps the preset library looking intentional, not empty).+ if (!animState.listings.length) { section.hidden = true; return; }+ section.hidden = false;+ if (sub) sub.textContent = `${filtered.length} for sale`;++ if (!filtered.length) {+ grid.innerHTML = `<div class="market-empty">No creator animations match your filter.</div>`;+ return;+ }++ grid.innerHTML = filtered.map((it) => {+ const priceLabel = it.free ? 'Free' : `${formatPrice(it.price.amount)} ${it.price.currency}`;+ const dur = it.duration ? `${it.duration.toFixed(it.duration % 1 ? 1 : 0)}s` : '';+ const typeLabel = it.loop !== false ? 'Loop' : 'Action';+ const thumb = it.thumbnail_url+ ? `<img class="anim-listing-thumb" src="${escapeHtml(it.thumbnail_url)}" alt="" loading="lazy" />`+ : `<div class="anim-listing-thumb anim-listing-thumb-empty">🎬</div>`;+ return `<article class="anim-listing-card" data-listing-id="${escapeHtml(it.id)}" tabindex="0" role="button" aria-label="${escapeHtml(it.name)} — ${priceLabel}">+ <div class="anim-listing-media">+ ${thumb}+ <span class="anim-listing-price ${it.free ? 'free' : 'paid'}">${escapeHtml(priceLabel)}</span>+ </div>+ <div class="anim-listing-body">+ <div class="anim-listing-name">${escapeHtml(it.name)}</div>+ <div class="anim-listing-creator">${escapeHtml(it.creator?.name || 'Anonymous')}</div>+ <div class="anim-listing-meta">+ <span class="anim-type-pill ${it.loop !== false ? 'loop' : 'action'}">${typeLabel}</span>+ ${dur ? `<span class="stat-pill">${escapeHtml(dur)}</span>` : ''}+ ${it.purchase_count ? `<span class="stat-pill">${it.purchase_count} sold</span>` : ''}+ </div>+ </div>+ <div class="anim-listing-cta">${it.free ? 'Get →' : 'Buy →'}</div>+ </article>`;+ }).join('');++ grid.querySelectorAll('.anim-listing-card').forEach((card) => {+ const id = card.dataset.listingId;+ const open = () => openAnimationPurchase(id);+ card.addEventListener('click', open);+ card.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); }+ });+ });+}++function formatPrice(amount) {+ const n = Number(amount);+ if (!isFinite(n)) return amount;+ // Trim trailing zeros: 2.50 → 2.5, 2.00 → 2.+ return `$${n.toFixed(2).replace(/\.?0+$/, '')}`;+}+function renderAnimationsGrid() {const grid = $('animations-grid');if (!grid) return;@@ -3168,6 +3285,7 @@ function bindAnimationsEvents() {if (search) {search.addEventListener('input', () => {animState.q = search.value.trim();+ renderCreatorListings();renderAnimationsGrid();});}@@ -3175,11 +3293,125 @@ function bindAnimationsEvents() {btn.addEventListener('click', () => {animState.filter = btn.dataset.animFilter;document.querySelectorAll('[data-anim-filter]').forEach((b) => b.classList.toggle('active', b === btn));+ renderCreatorListings();renderAnimationsGrid();});});}+// ── Creator-animation purchase modal ──────────────────────────────────────+// Self-contained overlay: poster, metadata, and the buy/get action. Free clips+// download the GLB directly; paid clips pay once in USDC via the x402 endpoint+// (buy once, re-download free with the same wallet) and surface a ready-to-run+// snippet for agents/CLIs.+async function openAnimationPurchase(id) {+ const item = animState.listings.find((x) => x.id === id);+ if (!item) return;++ const existing = $('anim-buy-overlay');+ if (existing) existing.remove();++ const overlay = document.createElement('div');+ overlay.id = 'anim-buy-overlay';+ overlay.className = 'anim-buy-overlay';+ overlay.setAttribute('role', 'dialog');+ overlay.setAttribute('aria-modal', 'true');+ overlay.setAttribute('aria-label', `Get ${item.name}`);++ const priceLabel = item.free ? 'Free' : `${formatPrice(item.price.amount)} ${item.price.currency}`;+ const endpoint = `${location.origin}${item.download_url}`;+ const dur = item.duration ? `${item.duration.toFixed(item.duration % 1 ? 1 : 0)}s` : '';+ const snippet =+ `import { wrapFetchWithPayment } from '@three-ws/x402-fetch';\n` ++ `const res = await wrapFetchWithPayment(fetch, wallet)('${endpoint}');\n` ++ `const { downloadUrl } = await res.json(); // GLB, ready to play on any avatar`;++ overlay.innerHTML = `+ <div class="anim-buy-card">+ <button class="anim-buy-close" type="button" aria-label="Close">✕</button>+ <div class="anim-buy-media">+ ${item.thumbnail_url+ ? `<img src="${escapeHtml(item.thumbnail_url)}" alt="" />`+ : `<div class="anim-buy-media-empty">🎬</div>`}+ <span class="anim-listing-price ${item.free ? 'free' : 'paid'}">${escapeHtml(priceLabel)}</span>+ </div>+ <div class="anim-buy-info">+ <h2 class="anim-buy-name">${escapeHtml(item.name)}</h2>+ <p class="anim-buy-creator">by ${escapeHtml(item.creator?.name || 'Anonymous')}</p>+ ${item.description ? `<p class="anim-buy-desc">${escapeHtml(item.description)}</p>` : ''}+ <div class="anim-buy-meta">+ <span class="anim-type-pill ${item.loop !== false ? 'loop' : 'action'}">${item.loop !== false ? 'Loop' : 'Action'}</span>+ ${dur ? `<span class="stat-pill">${escapeHtml(dur)}</span>` : ''}+ ${item.frame_count ? `<span class="stat-pill">${item.frame_count} keys</span>` : ''}+ ${item.purchase_count ? `<span class="stat-pill">${item.purchase_count} sold</span>` : ''}+ </div>+ ${(item.tags || []).length ? `<div class="anim-buy-tags">${item.tags.slice(0, 6).map((t) => `<span class="anim-cat-pill">${escapeHtml(t)}</span>`).join('')}</div>` : ''}+ <div class="anim-buy-actions">+ <button class="btn-primary anim-buy-go" type="button">${item.free ? 'Download GLB' : `Buy for ${escapeHtml(priceLabel)}`}</button>+ </div>+ <p class="anim-buy-note" id="anim-buy-note">${item.free+ ? 'Free download — a self-contained animated GLB that plays on any three.ws avatar.'+ : 'Pay once in USDC (Base or Solana). Re-download free anytime by signing in with the same wallet.'}</p>+ ${item.free ? '' : `+ <details class="anim-buy-snippet">+ <summary>Pay programmatically (agents / CLI)</summary>+ <div class="anim-buy-endpoint">+ <code>${escapeHtml(endpoint)}</code>+ <button class="market-chip anim-buy-copy-url" type="button">Copy URL</button>+ </div>+ <pre class="anim-buy-code"><code>${escapeHtml(snippet)}</code></pre>+ </details>`}+ </div>+ </div>`;++ document.body.appendChild(overlay);+ const close = () => overlay.remove();+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });+ overlay.querySelector('.anim-buy-close').addEventListener('click', close);+ const escHandler = (e) => { if (e.key === 'Escape') { close(); document.removeEventListener('keydown', escHandler); } };+ document.addEventListener('keydown', escHandler);++ const copyUrl = overlay.querySelector('.anim-buy-copy-url');+ copyUrl?.addEventListener('click', () => {+ navigator.clipboard?.writeText(endpoint).then(() => {+ const t = copyUrl.textContent; copyUrl.textContent = 'Copied ✓';+ setTimeout(() => { copyUrl.textContent = t; }, 1400);+ });+ });++ const goBtn = overlay.querySelector('.anim-buy-go');+ const note = overlay.querySelector('#anim-buy-note');+ goBtn?.addEventListener('click', async () => {+ if (item.free) {+ goBtn.disabled = true; goBtn.textContent = 'Preparing…';+ try {+ const r = await fetch(endpoint, { headers: { accept: 'application/json' } });+ const body = await r.json();+ if (!r.ok || !body.downloadUrl) throw new Error(body.error_description || body.error || `download failed (${r.status})`);+ triggerDownload(body.downloadUrl, `${item.slug || 'animation'}.glb`);+ goBtn.textContent = 'Downloaded ✓';+ if (note) note.textContent = 'Your download has started. The GLB plays on any three.ws avatar.';+ if (item.purchase_count != null) item.purchase_count += 0;+ } catch (err) {+ goBtn.disabled = false; goBtn.textContent = 'Download GLB';+ if (note) { note.textContent = err.message; note.classList.add('anim-buy-note-err'); }+ }+ } else {+ // Paid: x402 settlement happens wallet-side. Surface the endpoint ++ // snippet (revealed below) — there's no custodial in-browser signer.+ const details = overlay.querySelector('.anim-buy-snippet');+ if (details) { details.open = true; details.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }+ if (note) note.textContent = 'Pay from your wallet using the endpoint below. Once settled, the response carries a presigned GLB download URL.';+ }+ });+}++function triggerDownload(url, filename) {+ const a = document.createElement('a');+ a.href = url; a.download = filename; a.rel = 'noopener';+ document.body.appendChild(a); a.click(); a.remove();+}+// ── Animation detail page ─────────────────────────────────────────────────// Rich, deep-linkable page at /marketplace/animations/:name. Plays the clip// live on a preview avatar, shows clip metadata, and lists more animations.diff --git a/src/pose-library.js b/src/pose-library.jsindex f055c5c27..f7d2af4d2 100644--- a/src/pose-library.js+++ b/src/pose-library.js@@ -57,7 +57,8 @@ export class PoseLibrary {this.user = undefined; // undefined = unknown, null = signed out, object = signed inthis.savedClip = null; // { id, slug, name, visibility } when editing a saved clipthis.tab = 'mine';- this.onSell = null; // Task 6 sets this to wire the Sell action+ // Wire the per-card Sell / Manage-sale action to the listing flow.+ this.onSell = (clip) => this.openSellDialog(clip);}mount() {@@ -523,6 +524,150 @@ export class PoseLibrary {}}+ // ── Sell / list on the marketplace ────────────────────────────────────────+ // List a saved animation for sale: bake a self-contained animated GLB, stage+ // it in R2, then price it via /api/animations/sell. The clip surfaces in the+ // marketplace animations feed and sells through the x402 paid-download+ // endpoint (buy once in USDC, re-download free with the same wallet).+ async openSellDialog(clip) {+ // Bake the artifact from the live rig, so the clip being listed must be the+ // one currently loaded. Re-open it first if needed (also lets the seller+ // see exactly what they're listing).+ if (this.savedClip?.id !== clip.id) {+ this.api.setStatus(`Loading “${clip.name}” to prepare the listing…`);+ await this._open(clip);+ if (this.savedClip?.id !== clip.id) {+ this.api.setStatus('Could not load that animation to list it.', 'error');+ return;+ }+ }++ const overlay = this._overlay();+ const listed = !!clip.listed;+ const curPrice = clip.price ? Number(clip.price.amount) : 0;++ const priceInput = el('input', {+ class: 'pl-input', id: 'pl-price', type: 'number', min: '0', step: '0.01',+ value: curPrice ? String(curPrice) : '', placeholder: '0.00 (free)', 'aria-label': 'Price in USDC',+ });+ const priceHint = el('p', { class: 'pl-link-note' }, ['Buyers pay once in USDC (Base or Solana) and own the animated GLB. Leave blank or 0 to list it as a free download. Earnings settle to your default payout wallet.']);+ const errLine = el('div', { class: 'pl-dialog-err', role: 'alert', hidden: true });+ const statusLine = el('p', { class: 'pl-dialog-sub', hidden: true, role: 'status' });++ const primaryBtn = el('button', { class: 'pose-btn pose-btn-primary', type: 'submit' }, [listed ? 'Update listing' : 'List for sale']);+ const delistBtn = listed ? el('button', { class: 'pose-btn pl-danger', type: 'button' }, ['Remove from sale']) : null;++ const form = el('form', { class: 'pl-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Sell animation' }, [+ el('h2', { class: 'pl-dialog-title' }, [listed ? 'Manage marketplace listing' : 'Sell this animation']),+ el('p', { class: 'pl-dialog-sub' }, [`“${clip.name}” will be published to the three.ws animation marketplace, playable on any avatar.`]),+ el('label', { class: 'pl-field' }, [el('span', {}, ['Price (USDC)']), priceInput]),+ priceHint,+ statusLine,+ errLine,+ el('div', { class: 'pl-dialog-actions' }, [+ el('button', { class: 'pose-btn', type: 'button', onclick: () => overlay.remove() }, ['Cancel']),+ delistBtn,+ primaryBtn,+ ]),+ ]);++ const setBusy = (busy, label) => {+ primaryBtn.disabled = busy;+ if (delistBtn) delistBtn.disabled = busy;+ if (label) { statusLine.hidden = false; statusLine.textContent = label; }+ };++ form.addEventListener('submit', async (ev) => {+ ev.preventDefault();+ errLine.hidden = true;+ const price = Math.max(0, Number(priceInput.value) || 0);+ setBusy(true, 'Baking the animated GLB…');+ try {+ const listing = await this._listForSale(clip, price, (msg) => (statusLine.textContent = msg));+ overlay.remove();+ Object.assign(clip, { listed: listing.listed, price: listing.price });+ this._refreshCard(clip);+ this.api.setStatus(+ listing.price+ ? `Listed “${clip.name}” for ${listing.price.amount} ${listing.price.currency}. View it in the marketplace.`+ : `Listed “${clip.name}” as a free download in the marketplace.`,+ );+ } catch (err) {+ setBusy(false);+ statusLine.hidden = true;+ errLine.hidden = false;+ errLine.textContent = err.message;+ }+ });++ delistBtn?.addEventListener('click', async () => {+ errLine.hidden = true;+ setBusy(true, 'Removing from sale…');+ try {+ const body = await apiFetch('/api/animations/sell', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id: clip.id, action: 'delist' }),+ });+ overlay.remove();+ Object.assign(clip, { listed: false, price: body.listing.price });+ this._refreshCard(clip);+ this.api.setStatus(`“${clip.name}” removed from the marketplace.`);+ } catch (err) {+ setBusy(false);+ statusLine.hidden = true;+ errLine.hidden = false;+ errLine.textContent = err.message;+ }+ });++ overlay.appendChild(form);+ document.body.appendChild(overlay);+ priceInput.focus();+ }++ // Bake → upload → price. Returns the listing payload from /api/animations/sell.+ async _listForSale(clip, price, onProgress = () => {}) {+ const { buffer } = await this.api.bakeArtifact();+ const bytes = buffer.byteLength;++ onProgress('Staging the file…');+ const presign = await apiFetch('/api/animations/presign', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ size_bytes: bytes, content_type: 'model/gltf-binary', slug: clip.slug }),+ });++ onProgress('Uploading…');+ const put = await fetch(presign.upload_url, {+ method: 'PUT',+ headers: { 'content-type': 'model/gltf-binary' },+ body: buffer,+ });+ if (!put.ok) throw new Error(`Upload failed (${put.status})`);++ onProgress('Publishing the listing…');+ const body = await apiFetch('/api/animations/sell', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ id: clip.id,+ price,+ artifact_key: presign.storage_key,+ artifact_bytes: bytes,+ artifact_mime: 'model/gltf-binary',+ listed: true,+ }),+ });+ return body.listing;+ }++ // Re-render a card in place after a listing change.+ _refreshCard(clip) {+ const card = document.querySelector(`.pl-card[data-id="${clip.id}"]`);+ if (card) card.replaceWith(this._card(clip, this.tab));+ }+_resetSaveBtn() {const saveBtn = document.querySelector('#pose-save');if (saveBtn) { saveBtn.textContent = 'Save'; saveBtn.title = 'Save this animation to your account (Ctrl/Cmd+S)'; }diff --git a/src/pose-studio.js b/src/pose-studio.jsindex 5a329f4a7..e65bd80b2 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -1569,6 +1569,9 @@ function boot() {},bake: () => bakeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),serialize: () => serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),+ // Bake the live rig (mesh + embedded clip) to a self-contained binary+ // GLB — the sellable artifact for a marketplace listing.+ bakeArtifact: () => bakeAnimatedGlb(),captureThumbnail: () => {renderer.render(scene, camera);return renderer.domElement.toDataURL('image/png');@@ -1584,6 +1587,7 @@ function boot() {getDocument: () => timeline.getDocument(),loadDocument: (d) => timeline.loadDocument(d),serializeClip: () => timeline.serialize(),+ bakeArtifact: () => timeline.bakeArtifact(),captureThumbnail: () => timeline.captureThumbnail(),keyframeCount: () => timeline.keyframeCount(),currentAvatarId: () => state.avatar?.id || null,diff --git a/tests/api/forge-fallback.test.js b/tests/api/forge-fallback.test.jsindex ed29692b0..1e7ed44f3 100644--- a/tests/api/forge-fallback.test.js+++ b/tests/api/forge-fallback.test.js@@ -47,6 +47,24 @@ vi.mock('../../api/_providers/replicate.js', () => ({}),}));+// Free Hugging Face Spaces image→3D lane (fallback #2, after Hunyuan3D). Its+// submit() blocks and packs the GLB into extJobId; status() echoes it back. The+// real provider throws when HF_TOKEN is unset, so the mock mirrors that gating —+// the lane is only available on deployments that configure a token.+const hfSubmit = vi.fn(async () => ({ extJobId: 'hf-packed-job', rawStatus: 'completed' }));+const hfStatus = vi.fn(async () => ({ status: 'done', resultGlbUrl: 'https://cdn.example/hf.glb' }));+vi.mock('../../api/_providers/huggingface.js', () => ({+ createRegenProvider: () => {+ if (!process.env.HF_TOKEN) {+ throw Object.assign(new Error('HF_TOKEN env var is required'), {+ code: 'provider_unconfigured',+ status: 501,+ });+ }+ return { submit: hfSubmit, status: hfStatus };+ },+}));+// FLUX text-to-image (the standard-tier intermediate view) succeeds — the// failure under test is the reconstruction submit, not image synthesis.vi.mock('../../api/_mcp3d/text-to-image.js', () => ({@@ -153,10 +171,47 @@ describe('forge free-first fallback when the paid lane is over-quota', () => {expect(gcpSubmit.mock.calls[0][0].params.target_polycount).toBeGreaterThan(0);});- it('surfaces the honest busy state for an image upload when no Hunyuan3D worker is wired', async () => {+ it('degrades an image upload to the free HuggingFace lane when no Hunyuan3D worker is wired but HF_TOKEN is set', async () => {+ const savedUrl = process.env.GCP_HUNYUAN3D_URL;+ delete process.env.GCP_HUNYUAN3D_URL;+ process.env.HF_TOKEN = 'test-hf-token';+ gcpSubmit.mockClear();+ nvidiaTextTo3d.mockClear();+ hfSubmit.mockClear();+ hfStatus.mockClear();+ try {+ const req = makeReq({+ image_urls: ['https://cdn.example/photo.png'],+ prompt: 'a mug',+ tier: 'standard',+ path: 'image',+ skip_validation: true,+ });+ const res = makeRes();+ await handler(req, res);++ // The HF Spaces lane blocks and returns the finished model synchronously,+ // so image→3D never dead-ends. Provenance reports the lane that ran.+ expect(res.statusCode).toBe(200);+ expect(res.body.status).toBe('done');+ expect(res.body.backend).toBe('huggingface');+ expect(res.body.glb_url).toBe('https://cdn.example/hf.glb');+ expect(hfSubmit).toHaveBeenCalled();+ // The Hunyuan3D worker wasn't wired, and NVIDIA is text-only — neither runs.+ expect(gcpSubmit).not.toHaveBeenCalled();+ expect(nvidiaTextTo3d).not.toHaveBeenCalled();+ } finally {+ process.env.GCP_HUNYUAN3D_URL = savedUrl;+ delete process.env.HF_TOKEN;+ }+ });++ it('surfaces the honest busy state for an image upload when neither Hunyuan3D nor HF_TOKEN is configured', async () => {const savedUrl = process.env.GCP_HUNYUAN3D_URL;delete process.env.GCP_HUNYUAN3D_URL;+ delete process.env.HF_TOKEN;gcpSubmit.mockClear();+ hfSubmit.mockClear();try {const req = makeReq({image_urls: ['https://cdn.example/photo.png'],@@ -173,6 +228,7 @@ describe('forge free-first fallback when the paid lane is over-quota', () => {expect(res.statusCode).toBe(429);expect(res.body.error).toBe('rate_limited');expect(gcpSubmit).not.toHaveBeenCalled();+ expect(hfSubmit).not.toHaveBeenCalled();} finally {process.env.GCP_HUNYUAN3D_URL = savedUrl;}diff --git a/tests/api/providers-nvidia.test.js b/tests/api/providers-nvidia.test.jsindex ead082828..5eb00e40c 100644--- a/tests/api/providers-nvidia.test.js+++ b/tests/api/providers-nvidia.test.js@@ -92,7 +92,9 @@ describe('nvidia provider — text→3D submit', () => {expect(calls[0].headers.authorization).toBe('Bearer nvapi-test-key');const body = calls[0].body;expect(body.mode).toBe('text');- expect(body.prompt).toBe('a tiny brass teapot');+ // buildTextBody runs enhanceTrellisPrompt, which appends a lighting cue when+ // the prompt carries none — keeps draft renders from coming out flat/unlit.+ expect(body.prompt).toBe('a tiny brass teapot, studio lighting');expect(body.output_format).toBe('glb');expect(body.ss_sampling_steps).toBe(15); // draft tierexpect(body.slat_sampling_steps).toBe(15);diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.jsindex a7d4be7a1..410ff5e16 100644--- a/tests/glb-canonicalize.test.js+++ b/tests/glb-canonicalize.test.js@@ -140,6 +140,36 @@ describe('canonicalizeBoneName', () => {expect(canonicalizeBoneName('mixamorig:left_arm')).toBe('LeftArm');expect(canonicalizeBoneName('DEF-left_fore_arm')).toBe('LeftForeArm');});++ // glTF/FBX exporters (CharacterStudio, Blender, FBX2glTF) append a `_NN`+ // node-de-dup index to keep names unique. These are the bone names that ship+ // in real uploaded avatars — without stripping the suffix the whole animation+ // library silently fails to bind to them.+ it.each([+ ['mixamorig:Hips_01', 'Hips'],+ ['mixamorig:Spine_02', 'Spine'],+ ['mixamorig:Spine1_03', 'Spine1'], // base name itself ends in a digit+ ['mixamorig:Spine2_04', 'Spine2'],+ ['mixamorig:Neck_05', 'Neck'],+ ['mixamorig:LeftForeArm_010','LeftForeArm'],+ ['mixamorig:LeftToeBase_058','LeftToeBase'],+ ['mixamorig:RightUpLeg_060', 'RightUpLeg'],+ ['Hips_01', 'Hips'],+ ['LeftHandIndex1_016', 'LeftHandIndex1'], // digit base + dedup suffix+ ])('strips the glTF node-de-dup suffix: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });++ it('only strips the suffix when the plain form does not already resolve', () => {+ // A genuinely numbered finger bone must keep its index — the un-stripped+ // form resolves first, so we never reach the suffix strip.+ expect(canonicalizeBoneName('left_hand_index_1')).toBe('LeftHandIndex1');+ expect(canonicalizeBoneName('LeftHandIndex1')).toBe('LeftHandIndex1');+ // End-effector / non-bone nodes still fall through to null after stripping.+ expect(canonicalizeBoneName('mixamorig:HeadTop_End_07')).toBeNull();+ expect(canonicalizeBoneName('mixamorig:LeftToe_End_059')).toBeNull();+ expect(canonicalizeBoneName('Tail_01')).toBeNull();+ });});describe('canonicalizeJointNodes (in-place rewrite)', () => {