Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

chore: land further in-progress platform work (concurrent session snapshot)

nirholas22b5d0dd4cf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 950974efc..e1b69cd95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,17 +14,23 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Crypto Token Screener** (`/screener`) — Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.
- **DeFi TVL & Top Protocols** (`/defi`) — Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.
- **glTF / GLB Viewer** (`/viewer`) — Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.
+- **Restyle Studio — material presets & variants** (`/restyle`) — Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.
- **Stablecoins Market Cap & Peg Health** (`/stablecoins`) — Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.
- **Top Crypto Exchanges** (`/exchanges`) — The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.
- **<agent-3d> talks out of the box with brain="free"** — Any embedded avatar can now hold a real conversation with zero setup: add brain="free" to an <agent-3d> tag and it routes through three.ws's host-paid free-tier proxy (OpenRouter, Groq, or NVIDIA NIM, whichever is healthy) — no API key, no backend code, no per-token cost to the embedder. Previously the brain attribute required an exact model id and defaulted to a silent avatar; brain="free" is now a supported alias, and it's honored on both the src= (bare GLB) and body= (ad-hoc agent) embed paths, which is where this fell through before. (`/docs/embedding`) `[feature, sdk]`
- **BNB Chain hub: three uniquely-BNB demos in one place** — New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest "coming soon" instead of a dead link until it has. (`/bnb`) `[feature]`
+- **Fixed: the "View it" link on every generated 3D model now opens a real viewer** — The viewer link returned with every generated model (/viewer?src=…) previously returned a 404. It now opens a polished, interactive 3D viewer — orbit, zoom, AR on mobile, one-tap GLB download — with designed loading, empty, and error states. This affects every model made through the 3D Studio, in chat or on the web. `[fix]`
- **Give your agent a 3D body in one call — the new Embodiment endpoint** — Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body. (`/docs/embody`) `[feature]`
- **Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins** — Eight new tools join the Markets suite, all live data and all free. Screener filters the top 250 coins by market cap, volume, and 24h move. Categories ranks every crypto sector so you can see which narrative leads. Exchanges ranks venues by trust score and volume. Derivatives shows perpetual-futures funding, open interest, and volume. Converter turns any crypto into any major fiat at live rates. And a DeFi trio — DeFi TVL by protocol, Chains by total value locked, and Stablecoins with peg health — brings on-chain liquidity into view via DeFiLlama. Every one is cross-linked from the markets table. (`/screener`) `[feature]`
- **New free API: check if a wallet holds a Binance Account Bound Token (BABT)** — GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain. `[feature]`
+- **New guide: BNB Chain payments (MPP) and gasless sends** — A zero-context developer guide covering how to pay three.ws endpoints over MPP on BNB Chain, how our agents pay MPP endpoints, and how BNB Chain's block-level gas sponsorship (MegaFuel) lets a plain wallet send a transaction with zero gas — with an honest self-pay fallback for when sponsorship isn't available. Includes a wire-level bridge spec pinning how x402 and MPP map to each other. `[docs]`
- **New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana** — Added @three-ws/defi-utils, a zero-dependency internal package with chain IDs, native-token symbols, common token addresses (including SPA and USDs on Arbitrum), and minimal ERC-20 ABI fragments for nine EVM chains, plus a Solana extension (SOL/USDC/$THREE mint resolution and base58 address validation). Also ships address and amount validators and USD/percent/token-amount formatters. It replaces ad hoc constant duplication across the codebase's API handlers and frontend modules going forward. `[sdk]`
+- **New tool-authoring SDK: define an agent tool once — typed params, permissions, and rate limits included** — Internal SDK release for developers extending three.ws's 38 MCP servers: @three-ws/tool-sdk lets a tool be declared once with defineTool (Zod parameter schemas, auto-derived JSON Schema, a per-tool permission manifest for network access/rate limits/wallet use) and wired up with defineExecutor (typed handlers, automatic validation, uniform error wrapping) — then adapted into a live MCP server registration with a single toMcpTools() call. Proven by refactoring the naming MCP server's sns_resolve tool onto it with byte-identical behavior. `[sdk]`
- **Paid API endpoints now stay up through a cache-provider outage** — Hardened the pay-per-call x402 API surface — every /api/x402/* and /api/okx/3d/* endpoint — so it degrades gracefully instead of failing when the shared Redis cache is unreachable. Previously a missing cache configuration could take these paid endpoints offline; they now serve normally on a safe per-instance fallback, with on-chain payment safety unchanged (each payment authorization is still single-use, so no double-charge is possible). `[fix, infra]`
+- **Spatial MCP: 3D models are now a native, interactive response type** — We published an open standard — Spatial MCP — for returning a live, interactive 3D scene as a first-class AI tool result instead of a link in text. Every three.ws 3D tool now emits a conformant artifact (camera, lighting, animation, AR handoff), a public validator checks conformance with actionable errors, and a framework-free reference renderer displays any conformant payload — including ones transformed from other tools. It carries no wallet or token surface, so it works everywhere. Try the reference renderer. (`/spatial-mcp`) `[feature, docs]`
- **The free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds** — The unified /api/v1/x crypto API grew from 4 to 12 endpoints across CoinGecko and DefiLlama, all free with zero setup. CoinGecko now answers a full per-coin snapshot (price, ATH/ATL, supply, multi-window change), trending coins and hot categories, token price by contract address, the global market snapshot, and OHLC candles — not just spot price and ranked markets. DefiLlama adds every chain ranked by TVL, one protocol's full profile with 30 days of TVL history, and 90 days of historical chain TVL. Two new providers ride DefiLlama's sibling APIs: llama-prices for any chain:address token (covers long-tail tokens CoinGecko and Jupiter don't index) and llama-stablecoins for every tracked stablecoin's peg, price, and circulating supply. (`/docs/api-reference`) `[feature]`
- **The three.ws crypto API now has a real free tier** — Any unauthenticated call to the unified /api/v1/x API (CoinGecko, DefiLlama, Jupiter Solana prices/quotes/search) now gets real data with zero setup, up to a per-endpoint quota — no wallet, no key, no signup. curl https://three.ws/api/v1/x/coingecko/price?ids=solana just works. Every response carries rate-limit headers so an agent can see exactly how much free budget is left; once it's used up, the same URL falls through to pay-per-call USDC (x402) or a three.ws API key instead of dead-ending. (`/docs/api-reference`) `[feature]`
+- **three.ws now speaks BNB Chain's payment protocol (MPP), both ways** — Our paid endpoints now accept payments over MPP — BNB Chain's Machine Payments Protocol — in addition to the x402 payments we already take on Solana and Base. Because MPP is x402 v2 under the hood, the same signed-stablecoin credential works; agents from the BNB ecosystem can now pay us on BNB Chain, settling through the Binance OnchainPay facilitator, while every existing Solana/Base payment path is untouched. The $THREE Town Oracle is the first endpoint to accept both. Our own agents can pay any MPP-protected endpoint too, with a hard per-call spending cap that refuses an over-quote before any money moves. `[feature, sdk]`
## 2026-07-07
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 6e5972b34..1feb83b82 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -84,6 +84,7 @@ packages/avatar-cli/ → @three-ws/avatar-cli
packages/retarget/ → @three-ws/retarget (humanoid bone canonicalizer + clip retargeting engine, extracted from src/)
packages/viewer-presets/ → @three-ws/viewer-presets
packages/defi-utils/ → @three-ws/defi-utils (zero-dependency chain/token constants + address/amount validation + formatters, EVM + Solana; ported from SperaxOS)
+packages/tool-sdk/ → @three-ws/tool-sdk (typed MCP tool authoring — defineTool/defineExecutor + permission manifests + toMcpTools adapter; ported from SperaxOS)
packages/avatar-agent-mcp/ → @three-ws/avatar-agent-mcp (MCP server — avatar agent tools)
packages/pumpfun-mcp/ → @three-ws/pumpfun-mcp (MCP server — pump.fun launch tools)
packages/ibm-watsonx-mcp/ → @three-ws/ibm-watsonx-mcp (MCP server — IBM watsonx.ai)
diff --git a/api/_lib/ar-launch.js b/api/_lib/ar-launch.js
new file mode 100644
index 000000000..a89005faf
--- /dev/null
+++ b/api/_lib/ar-launch.js
@@ -0,0 +1,95 @@
+// AR launch — device-aware "View in your space" routing for a generated GLB.
+//
+// The pure core behind GET /api/ar (api/ar.js) and the export_ar MCP tool. Given
+// a GLB URL and a User-Agent, it decides how to place the model in AR:
+//
+// • iOS → Apple Quick Look. model-viewer generates a USDZ from the GLB on
+// the fly (a real conversion via three.js USDZExporter, in-page),
+// so the launch page hands iOS a Quick Look experience with no
+// server-side USD tooling required.
+// • Android → Google Scene Viewer via an ARCore intent:// URL (the GLB is the
+// Scene Viewer source), with a browser fallback to the WebGL viewer.
+// • desktop → the interactive WebGL viewer (no AR hardware).
+//
+// It is dependency-free and side-effect-free so the routing decision is unit-
+// tested in isolation, and carries ZERO payment/wallet/coin surface — AR is pure
+// consumer value and ships on both the Claude and OpenAI tracks.
+
+// A GLB URL must be https and point at a .glb/.gltf asset (query string allowed).
+// AR viewers refuse other schemes, and we never hand a non-https URL to a device
+// AR intent. Returns the normalized URL or throws a coded error the boundary maps
+// to a clean message.
+export function assertArAssetUrl(glbUrl) {
+ let u;
+ try {
+ u = new URL(String(glbUrl));
+ } catch {
+ throw arError('invalid_url', 'Provide a valid https URL to a .glb model.');
+ }
+ if (u.protocol !== 'https:') throw arError('not_https', 'The model URL must be https.');
+ if (!/\.(glb|gltf)$/i.test(u.pathname)) throw arError('not_glb', 'The model URL must point at a .glb or .gltf file.');
+ return u.toString();
+}
+
+function arError(code, message) {
+ const e = new Error(message);
+ e.code = code;
+ e.arUserMessage = true;
+ return e;
+}
+
+/** Classify the AR target from a User-Agent string. */
+export function detectArTarget(userAgent) {
+ const ua = String(userAgent || '');
+ // iPadOS 13+ reports a Mac UA; the "Mobile" token + touch is the tell, but
+ // server-side we only have the string — match the explicit iOS device tokens.
+ if (/\b(iphone|ipad|ipod)\b/i.test(ua)) return 'ios';
+ if (/\bandroid\b/i.test(ua)) return 'android';
+ return 'desktop';
+}
+
+/**
+ * Build the Android Scene Viewer ARCore intent URL for a GLB. `fallbackUrl` is
+ * where the browser lands if ARCore is unavailable (the WebGL viewer).
+ */
+export function buildSceneViewerUrl(glbUrl, { title = '', fallbackUrl = '' } = {}) {
+ const params = new URLSearchParams({ file: glbUrl, mode: 'ar_preferred' });
+ if (title) params.set('title', title);
+ const fallback = fallbackUrl ? `S.browser_fallback_url=${encodeURIComponent(fallbackUrl)};` : '';
+ return (
+ `intent://arvr.google.com/scene-viewer/1.2?${params.toString()}` +
+ `#Intent;scheme=https;package=com.google.ar.core;` +
+ `action=android.intent.action.VIEW;${fallback}end;`
+ );
+}
+
+/** The interactive WebGL viewer URL for a GLB on a given origin. */
+export function buildViewerUrl(origin, glbUrl, title = '') {
+ const base = String(origin || 'https://three.ws').replace(/\/$/, '');
+ const t = title ? `&title=${encodeURIComponent(title)}` : '';
+ return `${base}/viewer?src=${encodeURIComponent(glbUrl)}${t}`;
+}
+
+/** The device-aware AR launch URL (this endpoint) for a GLB. */
+export function buildArLaunchUrl(origin, glbUrl, title = '') {
+ const base = String(origin || 'https://three.ws').replace(/\/$/, '');
+ const t = title ? `&title=${encodeURIComponent(title)}` : '';
+ return `${base}/api/ar?src=${encodeURIComponent(glbUrl)}${t}`;
+}
+
+/**
+ * Resolve the launch plan for a request. Returns:
+ * { target, action:'redirect', url } — Android: 302 to Scene Viewer
+ * { target, action:'page' } — iOS/desktop: serve the launch page
+ * plus the resolved viewer + scene-viewer URLs for the page/tool to use.
+ */
+export function planArLaunch({ glbUrl, userAgent, origin, title = '' }) {
+ const asset = assertArAssetUrl(glbUrl);
+ const target = detectArTarget(userAgent);
+ const viewerUrl = buildViewerUrl(origin, asset, title);
+ const sceneViewerUrl = buildSceneViewerUrl(asset, { title, fallbackUrl: viewerUrl });
+ if (target === 'android') {
+ return { target, action: 'redirect', url: sceneViewerUrl, asset, viewerUrl, sceneViewerUrl };
+ }
+ return { target, action: 'page', asset, viewerUrl, sceneViewerUrl };
+}
diff --git a/api/_lib/bnb/erc8004-gasless.js b/api/_lib/bnb/erc8004-gasless.js
new file mode 100644
index 000000000..8c0045a5f
--- /dev/null
+++ b/api/_lib/bnb/erc8004-gasless.js
@@ -0,0 +1,229 @@
+/**
+ * Gasless ERC-8004 agent registration relay for BNB Chain (prompt 03).
+ *
+ * The campaign's headline demo: a brand-new, zero-balance wallet mints its
+ * ERC-8004 on-chain identity from the first click — no faucet, no funding.
+ * The client (a browser wallet or an in-page ephemeral key — either way the
+ * private key never leaves the browser) signs a *legacy* `register()` /
+ * `register(string)` transaction against the Identity Registry and hands us
+ * only the raw signed bytes. This module never sees a key, only bytes that
+ * are already fully signed — it parses them, decides sponsored vs. self-pay
+ * vs. decline, and relays.
+ *
+ * Two real broadcast paths, chosen by the `gasPrice` already baked into the
+ * signature the client sent:
+ *
+ * - `gasPrice === 0n` → "gasless attempt". Probe MegaFuel's
+ * `pm_isSponsorable` with the parsed tx; if sponsorable, relay the EXACT
+ * client bytes via MegaFuel's `eth_sendRawTransaction`
+ * (api/_lib/bnb/megafuel.js `submitRawTx`) — the sponsor tx pairs with it
+ * atomically at the block-builder layer. mode: 'sponsored'.
+ * If MegaFuel declines, we do NOT try to self-pay a zero-gasPrice
+ * transaction — every BSC node rejects a gasPrice-underpriced tx outside
+ * the paymaster path, so broadcasting it would just be a guaranteed
+ * revert-before-inclusion. That's mechanically impossible, not a bug. We
+ * return `{ mode: 'declined', reason, hint }` so the caller can show
+ * "you'll pay ~$0.001 gas" and resubmit a *newly signed*, real-gasPrice
+ * transaction — which lands in the branch below.
+ * - `gasPrice > 0n` → "self-pay attempt". The client already re-signed with
+ * real gas (after a decline, or because it knew sponsorship was
+ * unavailable). We broadcast the bytes as-is via the standard public RPC.
+ * mode: 'self-pay'.
+ *
+ * `sendGasless()` in megafuel.js is deliberately NOT reused here: it signs
+ * internally via a server-held viem `Account` (the right shape for a demo/ops
+ * account, e.g. the anvil-fork proof in prompt 02's PROGRESS entry) — not
+ * this endpoint's "client always signs, server never holds a key" model. This
+ * module only ever relays bytes it was handed.
+ */
+
+import { parseTransaction, recoverTransactionAddress, keccak256, toBytes, parseAbi } from 'viem';
+import { getPublicClient, BNB_CHAINS } from './chains.js';
+import { isSponsorable, submitRawTx as megafuelSubmitRawTx } from './megafuel.js';
+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from '../../../src/erc8004/abi.js';
+
+/** Typed error for every failure path — `status` maps straight to the HTTP response. */
+export class RegisterRelayError extends Error {
+ /** @param {string} message @param {{ code?: string, status?: number, cause?: unknown }} [info] */
+ constructor(message, info = {}) {
+ super(message);
+ this.name = 'RegisterRelayError';
+ this.code = info.code || 'bad_request';
+ this.status = info.status || 400;
+ if (info.cause) this.cause = info.cause;
+ }
+}
+
+// viem's parseAbi rejects the one `register(string,tuple[])` overload (inline
+// anonymous tuple param syntax it doesn't parse) — filtering that single
+// signature out (not rewriting any signature text) keeps every other entry
+// byte-identical to src/erc8004/abi.js, per the prompt's "do NOT redefine the
+// ABI" instruction. Only used for the two read calls below (balanceOf /
+// tokenOfOwnerByIndex); event decoding uses raw topic matching instead (see
+// api/erc8004/register-confirm.js for the same proven pattern).
+const READ_ABI = parseAbi(IDENTITY_REGISTRY_ABI.filter((sig) => !sig.includes('tuple')));
+
+const REGISTERED_TOPIC = keccak256(toBytes('Registered(uint256,string,address)'));
+const TRANSFER_TOPIC = keccak256(toBytes('Transfer(address,address,uint256)'));
+
+function normalizeNetwork(network) {
+ if (network === 56 || network === '56' || network === 'bsc' || network === 'mainnet' || network === 'bscMainnet') return 'bscMainnet';
+ return 'bscTestnet';
+}
+
+function registryAddressFor(network) {
+ const chainId = BNB_CHAINS[network].id;
+ const dep = REGISTRY_DEPLOYMENTS[chainId];
+ if (!dep?.identityRegistry) {
+ throw new RegisterRelayError(`no ERC-8004 Identity Registry deployment known for chain ${chainId}`, {
+ code: 'unknown_registry',
+ status: 500,
+ });
+ }
+ return dep.identityRegistry.toLowerCase();
+}
+
+/** Existing agentId for `address` on `registry`, or null when it holds none. */
+async function alreadyRegisteredAgentId(publicClient, registry, address) {
+ const balance = await publicClient.readContract({
+ address: registry,
+ abi: READ_ABI,
+ functionName: 'balanceOf',
+ args: [address],
+ });
+ if (!balance || balance === 0n) return null;
+ const tokenId = await publicClient.readContract({
+ address: registry,
+ abi: READ_ABI,
+ functionName: 'tokenOfOwnerByIndex',
+ args: [address, 0n],
+ });
+ return tokenId.toString();
+}
+
+/**
+ * Wait (bounded) for the receipt and pull `agentId` out of the `Registered`
+ * (preferred) or `Transfer` (ERC-721 mint fallback) log via raw topic
+ * matching — sidesteps ABI-decode ambiguity entirely, same technique already
+ * proven in api/erc8004/register-confirm.js. On a revert, best-effort replay
+ * the call at the failing block to surface the actual revert reason instead
+ * of a bare "reverted".
+ */
+async function waitAndDecode(publicClient, { hash, registry, from, to, data, value }) {
+ let receipt;
+ try {
+ receipt = await publicClient.waitForTransactionReceipt({ hash, timeout: 25_000 });
+ } catch (err) {
+ // Real BSC block times are sub-second (00-CONTEXT verified fact #3), but a
+ // congested public RPC can still miss the window — surface honestly as
+ // pending rather than failing outright; the hash is still real and
+ // resolvable via any explorer/RPC once it lands.
+ return { pending: true, agentId: null, hash };
+ }
+ if (receipt.status === 'reverted') {
+ let reason = 'transaction reverted';
+ try {
+ await publicClient.call({ account: from, to, data, value: value ?? 0n, blockNumber: receipt.blockNumber });
+ } catch (simErr) {
+ reason = simErr.shortMessage || simErr.message || reason;
+ }
+ throw new RegisterRelayError(reason, { code: 'tx_reverted', status: 422 });
+ }
+ const log = receipt.logs.find(
+ (l) => l.address?.toLowerCase() === registry && (l.topics?.[0] === REGISTERED_TOPIC || l.topics?.[0] === TRANSFER_TOPIC),
+ );
+ const agentId = log ? BigInt(log.topics[1]).toString() : null;
+ return { pending: false, agentId, hash, blockNumber: Number(receipt.blockNumber) };
+}
+
+/**
+ * Relay a client-signed ERC-8004 `register` transaction, gaslessly when
+ * possible. Never signs, never touches a key — only parses and relays bytes
+ * it was handed.
+ *
+ * @param {object} params
+ * @param {string} params.signedRegisterTx 0x-prefixed, fully signed legacy raw tx
+ * @param {'bscMainnet'|'bscTestnet'|56|97} [params.network]
+ * @param {import('viem').PublicClient} [params.publicClient] injectable for tests
+ * @param {object} [params.megafuelOpts] forwarded to isSponsorable/submitRawTx (tests)
+ * @returns {Promise<object>}
+ */
+export async function relayGaslessRegistration({ signedRegisterTx, network, publicClient: injectedClient, megafuelOpts = {} }) {
+ if (typeof signedRegisterTx !== 'string' || !/^0x[0-9a-fA-F]+$/.test(signedRegisterTx)) {
+ throw new RegisterRelayError('signedRegisterTx must be a 0x-prefixed signed raw transaction hex', { code: 'bad_tx' });
+ }
+ const net = normalizeNetwork(network);
+ const registry = registryAddressFor(net);
+
+ let parsed;
+ try {
+ parsed = parseTransaction(signedRegisterTx);
+ } catch (err) {
+ throw new RegisterRelayError('could not parse the signed transaction', { code: 'bad_tx', cause: err });
+ }
+ if (!parsed.to || parsed.to.toLowerCase() !== registry) {
+ throw new RegisterRelayError(`transaction must call the ERC-8004 Identity Registry (${registry}) on ${net}`, { code: 'wrong_target' });
+ }
+ if (parsed.type !== 'legacy') {
+ throw new RegisterRelayError('sign a legacy (type 0) transaction — MegaFuel gasless relies on gasPrice, not EIP-1559 fee fields', {
+ code: 'bad_tx_type',
+ });
+ }
+
+ let from;
+ try {
+ from = await recoverTransactionAddress({ serializedTransaction: signedRegisterTx });
+ } catch (err) {
+ throw new RegisterRelayError('could not recover a valid signature from the transaction', { code: 'bad_signature', cause: err });
+ }
+
+ const publicClient = injectedClient || getPublicClient(net);
+
+ // Never double-mint — an address that already owns an agent gets its
+ // existing agentId back instead of a broadcast attempt.
+ const existingAgentId = await alreadyRegisteredAgentId(publicClient, registry, from).catch(() => null);
+ if (existingAgentId !== null) {
+ return { alreadyRegistered: true, agentId: existingAgentId, address: from, network: net };
+ }
+
+ const gasPrice = parsed.gasPrice ?? 0n;
+ const value = parsed.value ?? 0n;
+
+ if (gasPrice === 0n) {
+ const probe = await isSponsorable(net, { to: parsed.to, from, value, gas: parsed.gas, data: parsed.data }, megafuelOpts);
+ if (!probe.sponsorable) {
+ return {
+ mode: 'declined',
+ reason: probe.reason,
+ address: from,
+ network: net,
+ hint: 'MegaFuel declined to sponsor this address right now — fund it with a small amount of tBNB (~0.001) and resubmit a transaction signed with a real gasPrice to self-pay.',
+ };
+ }
+ let hash;
+ try {
+ const submit = megafuelOpts.submitRawTx || megafuelSubmitRawTx;
+ hash = await submit(net, signedRegisterTx, megafuelOpts);
+ } catch (err) {
+ throw new RegisterRelayError(`MegaFuel accepted the sponsorship probe but the sponsored send failed: ${err.message}`, {
+ code: 'sponsored_send_failed',
+ status: 502,
+ cause: err,
+ });
+ }
+ const decoded = await waitAndDecode(publicClient, { hash, registry, from, to: parsed.to, data: parsed.data, value });
+ return { mode: 'sponsored', address: from, network: net, sponsor: probe.sponsorInfo, ...decoded };
+ }
+
+ // Self-pay: the caller already re-signed with real gas — broadcast as-is.
+ let hash;
+ try {
+ hash = await publicClient.sendRawTransaction({ serializedTransaction: signedRegisterTx });
+ } catch (err) {
+ const msg = err.shortMessage || err.message || String(err);
+ const code = /insufficient funds/i.test(msg) ? 'insufficient_funds' : /nonce/i.test(msg) ? 'bad_nonce' : /already known|replacement/i.test(msg) ? 'duplicate_tx' : 'broadcast_failed';
+ throw new RegisterRelayError(msg, { code, status: 400, cause: err });
+ }
+ const decoded = await waitAndDecode(publicClient, { hash, registry, from, to: parsed.to, data: parsed.data, value });
+ return { mode: 'self-pay', address: from, network: net, ...decoded };
+}
diff --git a/api/_lib/bnb/megafuel.js b/api/_lib/bnb/megafuel.js
index 9dfa79287..aad94a403 100644
--- a/api/_lib/bnb/megafuel.js
+++ b/api/_lib/bnb/megafuel.js
@@ -184,6 +184,34 @@ export async function sendGasless(network, { account, tx }, opts = {}) {
return selfPay(key, { account, tx }, publicClient, opts, probe.reason);
}
+/**
+ * Relay an ALREADY-SIGNED raw transaction through MegaFuel's paymaster
+ * `eth_sendRawTransaction`, without touching a private key or building the
+ * transaction ourselves. `sendGasless()` above signs internally via a
+ * server-held viem Account — the right shape for a demo/ops account (e.g. the
+ * anvil-fork proof in the prompt-02 PROGRESS entry), but wrong for a flow
+ * where the CLIENT signs (browser wallet or an in-page ephemeral key) and the
+ * server only ever sees bytes it can relay, never a key. That's exactly the
+ * gasless ERC-8004 registration relay (api/_lib/bnb/erc8004-gasless.js,
+ * prompt 03) needs: this is the low-level primitive `sendGasless` doesn't
+ * expose.
+ *
+ * @param {'bscMainnet'|'bscTestnet'|56|97} network
+ * @param {`0x${string}`} signedTx RLP-encoded, fully signed raw transaction hex
+ * @param {{ megafuelRpc?:Function, fetchImpl?:Function, timeoutMs?:number }} [opts]
+ * @returns {Promise<`0x${string}`>} transaction hash
+ */
+export async function submitRawTx(network, signedTx, opts = {}) {
+ if (typeof signedTx !== 'string' || !/^0x[0-9a-fA-F]+$/.test(signedTx)) {
+ throw new MegaFuelError('submitRawTx requires a 0x-prefixed signed raw transaction hex', { code: 'bad_raw_tx' });
+ }
+ const key = normalizeNetwork(network);
+ const call = opts.megafuelRpc
+ ? (m, p) => opts.megafuelRpc(m, p)
+ : (m, p) => rpc(megafuelEndpoint(key), m, p, opts);
+ return call('eth_sendRawTransaction', [signedTx]);
+}
+
/** Self-pay path: a normal, gas-paying send via the standard public/wallet client. */
async function selfPay(network, { account, tx }, publicClient, opts, reason) {
try {
diff --git a/api/_lib/forge-director-prompts.js b/api/_lib/forge-director-prompts.js
new file mode 100644
index 000000000..2a65d4d65
--- /dev/null
+++ b/api/_lib/forge-director-prompts.js
@@ -0,0 +1,43 @@
+// Shared IBM Granite "art director" prompt specs — the LLM rewrite step that
+// turns a rough user idea into a tight, information-dense spec for the
+// text-to-3D reconstruction pipeline (see api/_mcp-studio/forge-client.js's
+// directPrompt(), which sends one of these as the system instruction over
+// /api/chat, provider=watsonx). Centralized here so every surface that runs
+// the director — the free MCP tools (api/_mcp-studio/tools.js), the paid
+// OKX REST twin (api/_okx3d/rest-services.js), and the public /api/forge
+// opt-in `director:true` param — stays in sync on one copy instead of three
+// hand-maintained duplicates drifting apart.
+
+// For a single object/prop/creature — one isolated subject, its construction,
+// per-part PBR materials, one held art style, and fine surface detail, ending
+// in composition constraints tuned for clean image→mesh reconstruction.
+export const MESH_DIRECTOR =
+ "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " +
+ 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' +
+ 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' +
+ 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' +
+ 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' +
+ 'coherent, consistent art style held across the whole subject (pick one: photoreal, stylized, low-poly, ' +
+ 'hand-painted — never mix styles), (5) fine surface detail (seams, panel lines, weathering, grain) that ' +
+ 'gives the reconstructor texture to latch onto. Always end with these composition constraints so the ' +
+ 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' +
+ 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' +
+ 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' +
+ 'preamble, no quotes.';
+
+// For a full-body humanoid destined for auto-rigging — a readable, separable
+// pose plus the same per-region PBR/material and single-style discipline.
+export const AVATAR_DIRECTOR =
+ "You are a 3D character art director briefing a text-to-3D reconstruction model whose output will be " +
+ "auto-rigged for animation. Rewrite the user's idea into ONE concise, information-dense prompt. Cover, in " +
+ 'order: (1) a SINGLE full-body humanoid, standing in a neutral A/T-adjacent pose, arms slightly away from ' +
+ 'the body and legs slightly apart so limbs are readable and separable for rigging, (2) body type and ' +
+ 'proportions, (3) outfit and gear per body region (head, torso, arms, legs, feet) with explicit PBR ' +
+ 'material cues (e.g. brushed metal armor, worn leather straps, matte cloth, glossy visor) so surfaces ' +
+ 'reconstruct with correct roughness/metalness, (4) one coherent, consistent art style held across the ' +
+ 'whole character (pick one: photoreal, stylized, low-poly, hand-painted — never mix styles), (5) key ' +
+ 'identifying features (hair, face, color scheme, accessories). Always end with these composition ' +
+ 'constraints: full body in frame head-to-toe, centered, isolated on a plain neutral background, no props ' +
+ 'gripped or crossing the silhouette, one camera angle facing the character, even studio lighting, no ' +
+ 'cropping, no motion blur, no text or watermark, no collage or multi-view grid, no second character. ' +
+ 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';
diff --git a/api/_lib/material-studio-store.js b/api/_lib/material-studio-store.js
new file mode 100644
index 000000000..2b5c18bf0
--- /dev/null
+++ b/api/_lib/material-studio-store.js
@@ -0,0 +1,359 @@
+// Material Studio — server core: AI PBR restyle + seeded colorway variants +
+// durable persistence for arbitrary (non-avatar) GLBs.
+//
+// Generalizes the Avatar Studio idea — "re-skin what you already have" — to any
+// GLB. Two real capabilities live here, both non-destructive (the source GLB is
+// never mutated; every call reads fresh bytes and writes a NEW object):
+//
+// 1. restyleMaterialFromInstruction — "make it chrome" / "wooden" / "cyberpunk"
+// → IBM Granite (watsonx.ai) proposes a glTF 2.0 PBR material (base color,
+// metalness, roughness, emissive) from the description, then @gltf-transform
+// applies those factors onto the target material(s) and re-exports. Mesh
+// geometry and UVs are never touched — only material factors — so the
+// output is guaranteed shape-identical to the input.
+// 2. generateSeededVariants — fan one preset out into N reproducible colorway
+// variants using @three-ws/viewer-presets' materialVariants() (mulberry32
+// seeded PRNG — same base + seed always produces byte-identical configs).
+//
+// Both share one persistence path (validateAndPersistGlb) so every output is a
+// real, gltf-validator-checked, durably-stored https URL — never a blob, never
+// a mock. One implementation; the web Material Studio page calls it over
+// api/material-studio.js for free (rate-limited), and the restyle_material MCP
+// tool (mcp-server/src/tools/restyle-material.js) calls the SAME HTTP endpoint
+// as a thin client, matching the forge_free / refine_model "one core, two
+// transports" convention already used across the 3D stack.
+
+import { randomUUID } from 'node:crypto';
+import { putObject, publicUrl } from './r2.js';
+import { assertPublicHttpsUrl } from './ssrf.js';
+import { watsonxConfig, watsonxChatComplete } from './watsonx.js';
+import { materialVariants, materialPreset, MATERIAL_PRESET_NAMES } from '@three-ws/viewer-presets';
+
+const MAX_SOURCE_GLB_BYTES = 64 * 1024 * 1024;
+const MAX_VARIANT_COUNT = 12;
+const FETCH_TIMEOUT_MS = 30_000;
+
+export class MaterialStudioError extends Error {
+ constructor(message, { status = 500, code = 'material_studio_error' } = {}) {
+ super(message);
+ this.name = 'MaterialStudioError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function clamp01(n, fallback = 0) {
+ const v = Number(n);
+ return Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : fallback;
+}
+
+// glTF binary magic — first 4 bytes are ASCII "glTF". Mirrors
+// api/_lib/pipeline-stage.js's isGlbMagic so a bad upload/fetch fails the same
+// way everywhere in the pipeline.
+function isGlbMagic(bytes) {
+ return (
+ bytes?.length >= 12 &&
+ bytes[0] === 0x67 &&
+ bytes[1] === 0x6c &&
+ bytes[2] === 0x54 &&
+ bytes[3] === 0x46
+ );
+}
+
+function stripJsonFence(text) {
+ const raw = String(text || '').trim();
+ return raw.startsWith('```') ? raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '') : raw;
+}
+
+async function fetchGlbBytes(url) {
+ let resp;
+ try {
+ resp = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
+ } catch (err) {
+ throw new MaterialStudioError(`could not fetch glb_url: ${err.message}`, {
+ status: 502,
+ code: 'fetch_failed',
+ });
+ }
+ if (!resp.ok) {
+ throw new MaterialStudioError(`glb_url returned ${resp.status}`, {
+ status: resp.status === 404 ? 404 : 502,
+ code: 'fetch_failed',
+ });
+ }
+ const buf = Buffer.from(await resp.arrayBuffer());
+ if (!buf.length) throw new MaterialStudioError('glb_url is empty', { status: 502, code: 'empty_source' });
+ if (buf.length > MAX_SOURCE_GLB_BYTES) {
+ throw new MaterialStudioError(`source GLB is ${buf.length} bytes; max is ${MAX_SOURCE_GLB_BYTES}`, {
+ status: 413,
+ code: 'source_too_large',
+ });
+ }
+ if (!isGlbMagic(buf)) {
+ throw new MaterialStudioError('glb_url is not a binary glTF (.glb) — its bytes lack the "glTF" magic header', {
+ status: 415,
+ code: 'unsupported_media_type',
+ });
+ }
+ return buf;
+}
+
+// Validate a caller-supplied glb_url (scheme + SSRF + DNS) before ANY fetch.
+export async function validateGlbUrl(raw, field = 'glb_url') {
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ if (!value) throw new MaterialStudioError(`${field} is required`, { status: 400, code: 'missing_url' });
+ try {
+ return await assertPublicHttpsUrl(value);
+ } catch (err) {
+ throw new MaterialStudioError(`${field} rejected: ${err.message}`, { status: 400, code: 'invalid_url' });
+ }
+}
+
+// ── glTF-Transform document I/O (lazy — keeps this module's static import cost
+// low for the (more common) code paths that never touch a document, e.g. the
+// discovery GET). ────────────────────────────────────────────────────────────
+
+async function loadDocument(bytes) {
+ const [{ NodeIO }, { ALL_EXTENSIONS }] = await Promise.all([
+ import('@gltf-transform/core'),
+ import('@gltf-transform/extensions'),
+ ]);
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ try {
+ return await io.readBinary(new Uint8Array(bytes));
+ } catch (err) {
+ throw new MaterialStudioError(`source GLB failed to parse: ${err.message}`, {
+ status: 415,
+ code: 'invalid_glb',
+ });
+ }
+}
+
+async function writeAndValidate(doc) {
+ const { NodeIO } = await import('@gltf-transform/core');
+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const bytes = await io.writeBinary(doc);
+
+ const { validateBytes } = await import('gltf-validator');
+ const report = await validateBytes(bytes).catch((err) => {
+ throw new MaterialStudioError(`output GLB failed validation: ${err.message}`, {
+ status: 502,
+ code: 'validation_threw',
+ });
+ });
+ const numErrors = report?.issues?.numErrors ?? 0;
+ if (numErrors > 0) {
+ const first = report.issues.messages?.find((m) => m.severity === 0)?.message;
+ throw new MaterialStudioError(
+ `restyled GLB failed glTF validation (${numErrors} error${numErrors === 1 ? '' : 's'})${first ? `: ${first}` : ''}`,
+ { status: 502, code: 'invalid_output' },
+ );
+ }
+ return bytes;
+}
+
+// Apply a flat PBR factor set onto every material in the doc (or just
+// `materialIndex` when given). Geometry, accessors, and UVs are untouched —
+// this only ever calls the Material setters, never the Mesh/Primitive ones —
+// which is what guarantees "preserve mesh + UVs" through a restyle.
+function applyFactorsToDoc(doc, factors, materialIndex) {
+ const materials = doc.getRoot().listMaterials();
+ if (!materials.length) {
+ throw new MaterialStudioError('source GLB has no materials to restyle', {
+ status: 422,
+ code: 'no_materials',
+ });
+ }
+ const targets =
+ Number.isInteger(materialIndex) && materials[materialIndex] ? [materials[materialIndex]] : materials;
+
+ for (const mat of targets) {
+ if (Array.isArray(factors.baseColorFactor) && factors.baseColorFactor.length === 4) {
+ mat.setBaseColorFactor(factors.baseColorFactor.map((v, i) => (i === 3 ? clamp01(v, 1) : clamp01(v))));
+ } else if (Array.isArray(factors.baseColorFactor) && factors.baseColorFactor.length === 3) {
+ mat.setBaseColorFactor([...factors.baseColorFactor.map((v) => clamp01(v)), mat.getBaseColorFactor()[3] ?? 1]);
+ }
+ if (factors.metallicFactor != null) mat.setMetallicFactor(clamp01(factors.metallicFactor));
+ if (factors.roughnessFactor != null) mat.setRoughnessFactor(clamp01(factors.roughnessFactor, 0.5));
+ if (Array.isArray(factors.emissiveFactor) && factors.emissiveFactor.length === 3) {
+ mat.setEmissiveFactor(factors.emissiveFactor.map((v) => clamp01(v)));
+ }
+ if (factors.name) mat.setName(factors.name);
+ }
+ return targets.length;
+}
+
+function hexToFactor(hex, fallback = [0.6, 0.6, 0.6]) {
+ const m = /^#?([0-9a-f]{6})$/i.exec(String(hex || '').trim());
+ if (!m) return fallback;
+ const int = parseInt(m[1], 16);
+ return [((int >> 16) & 255) / 255, ((int >> 8) & 255) / 255, (int & 255) / 255];
+}
+
+// ── Persistence ─────────────────────────────────────────────────────────────
+
+// Validate GLB bytes (magic + gltf-validator) and mirror into R2 under
+// material-studio/<uuid>.glb. Every function below funnels through this so
+// every URL this module ever hands back is a real, checked, durable asset.
+export async function validateAndPersistGlb(bytes, { keyPrefix = 'material-studio' } = {}) {
+ if (!bytes?.length) throw new MaterialStudioError('no GLB bytes to persist', { status: 400, code: 'empty_input' });
+ if (bytes.length > MAX_SOURCE_GLB_BYTES) {
+ throw new MaterialStudioError(`GLB is ${bytes.length} bytes; max is ${MAX_SOURCE_GLB_BYTES}`, {
+ status: 413,
+ code: 'too_large',
+ });
+ }
+ if (!isGlbMagic(bytes)) {
+ throw new MaterialStudioError('not a binary glTF (.glb) — bytes lack the "glTF" magic header', {
+ status: 415,
+ code: 'unsupported_media_type',
+ });
+ }
+ const { validateBytes } = await import('gltf-validator');
+ const report = await validateBytes(new Uint8Array(bytes)).catch((err) => {
+ throw new MaterialStudioError(`GLB failed validation: ${err.message}`, { status: 422, code: 'validation_threw' });
+ });
+ const numErrors = report?.issues?.numErrors ?? 0;
+ if (numErrors > 0) {
+ throw new MaterialStudioError(`GLB failed glTF validation (${numErrors} error${numErrors === 1 ? '' : 's'})`, {
+ status: 422,
+ code: 'invalid_glb',
+ });
+ }
+ const key = `${keyPrefix}/${randomUUID()}.glb`;
+ await putObject({ key, body: bytes, contentType: 'model/gltf-binary', metadata: { source: 'material-studio' } });
+ return { url: publicUrl(key), bytes: bytes.length, key };
+}
+
+// ── 1. AI restyle: instruction → PBR factors → applied + persisted GLB ──────
+
+// Ask IBM Granite (watsonx.ai) for a glTF PBR material from a plain-language
+// description. Same system-prompt shape as the generate_material MCP tool
+// (api/_mcp3d/tools/studio.js), factored out here so Material Studio doesn't
+// duplicate the watsonx wiring — reuses watsonxConfig/watsonxChatComplete
+// directly rather than the tool wrapper (which carries MCP-only concerns).
+export async function generateMaterialFactorsFromInstruction(instruction) {
+ const trimmed = typeof instruction === 'string' ? instruction.trim() : '';
+ if (trimmed.length < 2) {
+ throw new MaterialStudioError('instruction must be at least 2 characters', {
+ status: 400,
+ code: 'invalid_instruction',
+ });
+ }
+ const cfg = watsonxConfig();
+ if (!cfg.configured) {
+ throw new MaterialStudioError(
+ 'AI restyle is not configured on this deployment (set WATSONX_API_KEY and WATSONX_PROJECT_ID).',
+ { status: 503, code: 'not_configured' },
+ );
+ }
+ const system =
+ 'You are a 3D material author. Given a short restyle instruction (e.g. "make it chrome", "wooden", ' +
+ '"cyberpunk neon"), return ONLY a valid JSON object describing a glTF 2.0 PBR material with keys: ' +
+ '"name" (string), "baseColorFactor" ([r,g,b] 0-1), "metallicFactor" (0-1), "roughnessFactor" (0-1), ' +
+ '"emissiveFactor" ([r,g,b] 0-1, [0,0,0] unless the instruction implies glow/light), and "notes" ' +
+ '(one short sentence on the look). No markdown, no prose outside the JSON.';
+ let result;
+ try {
+ result = await watsonxChatComplete(cfg, {
+ messages: [
+ { role: 'system', content: system },
+ { role: 'user', content: trimmed },
+ ],
+ maxTokens: 400,
+ temperature: 0.4,
+ });
+ } catch (err) {
+ throw new MaterialStudioError(`AI restyle model call failed: ${err.message}`, {
+ status: 502,
+ code: 'provider_error',
+ });
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(stripJsonFence(result.text));
+ } catch {
+ throw new MaterialStudioError('AI restyle model did not return usable material JSON', {
+ status: 502,
+ code: 'bad_model_output',
+ });
+ }
+ return {
+ name: typeof parsed.name === 'string' ? parsed.name.slice(0, 100) : trimmed.slice(0, 60),
+ baseColorFactor: Array.isArray(parsed.baseColorFactor) ? parsed.baseColorFactor.slice(0, 3) : null,
+ metallicFactor: typeof parsed.metallicFactor === 'number' ? parsed.metallicFactor : null,
+ roughnessFactor: typeof parsed.roughnessFactor === 'number' ? parsed.roughnessFactor : null,
+ emissiveFactor: Array.isArray(parsed.emissiveFactor) ? parsed.emissiveFactor.slice(0, 3) : [0, 0, 0],
+ notes: typeof parsed.notes === 'string' ? parsed.notes.slice(0, 300) : null,
+ model: result.model,
+ instruction: trimmed,
+ };
+}
+
+// Full pipeline: instruction → factors → fetch source → apply → validate →
+// persist. Returns the restyled GLB URL plus the factors that were applied, so
+// a browser caller (which already has the model loaded) can also apply the
+// SAME factors live to its in-memory THREE.Material for an instant preview
+// while the durable copy is still uploading.
+export async function restyleMaterialFromInstruction({ glbUrl, instruction, materialIndex }) {
+ const safeUrl = await validateGlbUrl(glbUrl);
+ const factors = await generateMaterialFactorsFromInstruction(instruction);
+ const sourceBytes = await fetchGlbBytes(safeUrl);
+ const doc = await loadDocument(sourceBytes);
+ const materialsEdited = applyFactorsToDoc(doc, factors, materialIndex);
+ const outBytes = await writeAndValidate(doc);
+ const persisted = await validateAndPersistGlb(Buffer.from(outBytes), { keyPrefix: 'material-studio/restyle' });
+ return {
+ glbUrl: persisted.url,
+ sourceGlbUrl: safeUrl,
+ instruction: factors.instruction,
+ factors,
+ materialsEdited,
+ bytes: persisted.bytes,
+ };
+}
+
+// ── 2. Seeded colorway variants ──────────────────────────────────────────────
+
+// Fan one preset (or the model's current look, approximated by `preset`) out
+// into `count` reproducible variants and persist each as its own GLB. Same
+// base + seed always yields byte-identical factor sets (materialVariants'
+// mulberry32 PRNG) and, downstream, byte-identical GLBs — reproducible in the
+// literal sense, not just "looks similar."
+export async function generateSeededVariants({ glbUrl, preset = 'chrome', seed = 0, count = 6, materialIndex }) {
+ if (!MATERIAL_PRESET_NAMES.includes(preset)) {
+ throw new MaterialStudioError(`unknown preset "${preset}" — known: ${MATERIAL_PRESET_NAMES.join(', ')}`, {
+ status: 400,
+ code: 'invalid_preset',
+ });
+ }
+ const safeUrl = await validateGlbUrl(glbUrl);
+ const n = Math.max(1, Math.min(MAX_VARIANT_COUNT, Number(count) || 6));
+ const seedNum = Number.isInteger(seed) ? seed >>> 0 : 0;
+ const base = materialPreset(preset);
+ const variants = materialVariants(base, { seed: seedNum, count: n });
+ const sourceBytes = await fetchGlbBytes(safeUrl);
+
+ const results = [];
+ for (const variant of variants) {
+ // Reload the document fresh from the untouched source bytes for every
+ // variant — applying variant N onto a doc already mutated by variant
+ // N-1 would compound edits instead of fanning out N independent looks.
+ const doc = await loadDocument(sourceBytes);
+ const factors = {
+ baseColorFactor: hexToFactor(variant.config.color),
+ metallicFactor: variant.config.metalness,
+ roughnessFactor: variant.config.roughness,
+ emissiveFactor: variant.config.emissive ? hexToFactor(variant.config.emissive, [0, 0, 0]) : [0, 0, 0],
+ name: variant.label,
+ };
+ applyFactorsToDoc(doc, factors, materialIndex);
+ const outBytes = await writeAndValidate(doc);
+ const persisted = await validateAndPersistGlb(Buffer.from(outBytes), {
+ keyPrefix: 'material-studio/variants',
+ });
+ results.push({ glbUrl: persisted.url, label: variant.label, seed: variant.seed, config: variant.config });
+ }
+ return { sourceGlbUrl: safeUrl, preset, seed: seedNum, count: n, variants: results };
+}
diff --git a/api/_lib/pump-curve-view.js b/api/_lib/pump-curve-view.js
new file mode 100644
index 000000000..1c5eea23d
--- /dev/null
+++ b/api/_lib/pump-curve-view.js
@@ -0,0 +1,167 @@
+// Shared bonding-curve view builder for a pump.fun mint.
+//
+// One RPC + Jupiter-fallback path, two doors: the authenticated dashboard route
+// (api/pump/curve.js) and the free GET /api/v1/pump/curve endpoint both call
+// getCurveView() and relay its { httpStatus, cacheControl, body } verbatim, so
+// behavior (including cache headers) stays byte-identical between the two.
+//
+// Combines @nirholas/pump-sdk reads via the shared RpcFallback + sdk-bridge
+// helpers: bonding curve raw state, current price + market cap, graduation
+// progress. A coin can graduate (curve closed or left behind with complete=true)
+// yet still trade on its AMM pool — Jupiter is the fallback price source for
+// that case, enriched with a market cap since pump.fun mints a fixed 1B supply
+// entirely into the curve/pool (FDV == market cap post-graduation).
+
+import { rpcFallbackFromEnv, getBondingCurveState, getTokenPrice, getGraduationProgress } from './solana/index.js';
+
+// Mints that can never carry a pump.fun bonding curve. These are coin-agnostic
+// payment-rail / native tokens, listed only so we can *exclude* them from curve
+// lookups — never to promote them. (USDC mainnet+devnet, wrapped SOL.)
+export const NON_CURVE_MINTS = new Set([
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC (mainnet)
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC (devnet)
+ 'So11111111111111111111111111111111111111112', // wrapped SOL
+]);
+
+// pump.fun mints a fixed total supply of exactly 1B tokens, the whole of which
+// is sold through the curve and then seeded into the AMM pool on graduation. For
+// these tokens fully-diluted value therefore equals market cap.
+export const PUMP_TOTAL_SUPPLY = 1_000_000_000;
+
+// Every pump.fun mint keypair is ground to end in the literal suffix "pump". A
+// mint that does not end in "pump" (or that is a known settlement token) has no
+// bonding curve and never will — so we can reject it without touching RPC.
+export function isPumpMint(mint) {
+ return typeof mint === 'string' && mint.endsWith('pump') && !NON_CURVE_MINTS.has(mint);
+}
+
+export function isPlausibleMint(s) {
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
+}
+
+async function jupiterPriceFallback(mint) {
+ try {
+ const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mint}`, { signal: AbortSignal.timeout(6000) });
+ if (!r.ok) return null;
+ const data = await r.json();
+ const usd = data?.[mint]?.usdPrice ?? data?.[mint]?.price;
+ const n = Number(usd);
+ return Number.isFinite(n) && n > 0 ? { priceUsd: n, source: 'jupiter' } : null;
+ } catch {
+ return null;
+ }
+}
+
+export function serializeBNs(obj) {
+ if (obj == null || typeof obj !== 'object') return obj;
+ const out = Array.isArray(obj) ? [] : {};
+ for (const [k, v] of Object.entries(obj)) {
+ if (
+ v &&
+ typeof v === 'object' &&
+ typeof v.toString === 'function' &&
+ (v.constructor?.name === 'BN' || typeof v.toNumber === 'function')
+ ) {
+ out[k] = v.toString();
+ } else if (v && typeof v === 'object') {
+ out[k] = serializeBNs(v);
+ } else {
+ out[k] = v;
+ }
+ }
+ return out;
+}
+
+/**
+ * Build the full curve-view payload for a mint. Returns a discriminated result
+ * `{ httpStatus, cacheControl, body }` — callers relay it verbatim via their own
+ * `json(res, httpStatus, body, { 'cache-control': cacheControl })` (or without
+ * the cache-control header when it's null, letting the secure-by-default
+ * no-store apply — matches every error response before this extraction).
+ *
+ * Caller is expected to have already validated `mint` with isPlausibleMint().
+ */
+export async function getCurveView({ mint, network = 'mainnet' }) {
+ if (!isPumpMint(mint)) {
+ // Negative-cacheable so the CDN edge serves repeat probes without hitting
+ // the function at all — no cold start, no RPC reads, no warning spam.
+ return {
+ httpStatus: 404,
+ cacheControl: 'public, s-maxage=300, max-age=300',
+ body: { error: 'not_a_pump_mint', error_description: 'mint has no pump.fun bonding curve' },
+ };
+ }
+
+ const rpc = rpcFallbackFromEnv({ network });
+ const result = await rpc.withFallback(async (connection) => {
+ const [curve, price, grad] = await Promise.all([
+ getBondingCurveState(connection, mint),
+ getTokenPrice(connection, mint),
+ getGraduationProgress(connection, mint),
+ ]);
+ return { curve, price, graduation: grad };
+ });
+
+ if (!result.curve) {
+ // No on-chain bonding curve account. Two cases to disambiguate:
+ // 1. Graduated coin — the curve account is closed once a coin migrates
+ // to its AMM pool, but the token still trades with a live DEX price.
+ // Fall back to Jupiter and return a 200 "graduated" view so callers
+ // render the real price instead of a dead 404. (Our own $THREE lives
+ // here post-migration.)
+ // 2. A mint that never had a curve — Jupiter has nothing either, so the
+ // 404 stands and the client's stop-on-404 path fires as before.
+ const graduatedPrice = await jupiterPriceFallback(mint);
+ if (graduatedPrice) {
+ const marketCapUsd = graduatedPrice.priceUsd * PUMP_TOTAL_SUPPLY;
+ return {
+ httpStatus: 200,
+ cacheControl: 'public, max-age=15, s-maxage=30, stale-while-revalidate=60',
+ body: {
+ mint,
+ network,
+ curve: null,
+ graduated: true,
+ price: null,
+ graduation: { isGraduated: true, progressBps: 10_000 },
+ graduatedPrice: { ...graduatedPrice, marketCapUsd },
+ },
+ };
+ }
+ return {
+ httpStatus: 404,
+ cacheControl: null,
+ body: { error: 'no_curve', error_description: 'no bonding curve found for that mint' },
+ };
+ }
+
+ // Graduated coins have no bonding-curve price. A coin can graduate yet leave
+ // its on-chain curve account behind (closed, reserves zeroed, complete=true) —
+ // this is exactly the case for our own $THREE. Fall back to Jupiter so callers
+ // always get a usable price even after migration to a DEX, and surface the same
+ // `graduated: true` + market-cap-enriched `graduatedPrice` shape as the
+ // curve-gone path above so every consumer renders graduated coins identically.
+ let pricePayload = result.price ? serializeBNs(result.price) : null;
+ const curveComplete = Boolean(result.curve?.complete);
+ let graduatedPrice = null;
+ if (!pricePayload && curveComplete) {
+ const jup = await jupiterPriceFallback(mint);
+ if (jup) {
+ graduatedPrice = { ...jup, marketCapUsd: jup.priceUsd * PUMP_TOTAL_SUPPLY };
+ }
+ }
+
+ return {
+ httpStatus: 200,
+ cacheControl: 'public, max-age=5, s-maxage=10, stale-while-revalidate=30',
+ body: {
+ mint,
+ network,
+ curve: result.curve,
+ ...(curveComplete ? { graduated: true } : {}),
+ price: pricePayload,
+ graduation: result.graduation ? serializeBNs(result.graduation) : null,
+ ...(graduatedPrice ? { graduatedPrice } : {}),
+ },
+ };
+}
diff --git a/api/_lib/pump-search.js b/api/_lib/pump-search.js
new file mode 100644
index 000000000..a41b53174
--- /dev/null
+++ b/api/_lib/pump-search.js
@@ -0,0 +1,101 @@
+// Shared text search over Solana pump.fun / meme tokens by name, symbol, or
+// mint. Extracted from api/pump/search.js (the site-wide command palette's
+// backend) so a second consumer — api/v1/pump/search.js, the free versioned
+// aggregator surface — can reuse the exact same upstream logic instead of a
+// copy-paste fork. Both routes call `searchPumpTokens`; neither reimplements
+// the Birdeye/pump.fun fallback chain.
+//
+// Primary source is Birdeye token search (keeps BIRDEYE_API_KEY server-side).
+// When Birdeye is unconfigured, rate-limited, or down, falls back to pump.fun's
+// public frontend search (no API key) — same response shape — so callers
+// degrade to live pump.fun data instead of a hard error. Only throws-free
+// (returns null) on either source's failure; the caller decides what an
+// all-null result means.
+//
+// Response item shape: { mint, symbol, name, logo, price_usd, rank }
+
+import { normalizeGatewayURL } from '../../src/ipfs.js';
+
+const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
+
+/** Birdeye token search. Returns null (not throws) on any failure. */
+export async function searchBirdeye(q, limit) {
+ if (!BIRDEYE_API_KEY) return null;
+ const url =
+ `https://public-api.birdeye.so/defi/v3/search` +
+ `?chain=solana&target=token&search_mode=fuzzy&sort_by=marketcap&sort_type=desc` +
+ `&offset=0&limit=${limit}&keyword=${encodeURIComponent(q)}`;
+ let upstream;
+ try {
+ upstream = await fetch(url, {
+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ } catch {
+ return null;
+ }
+ if (!upstream.ok) return null;
+ const payload = await upstream.json().catch(() => null);
+ // v3 search nests token matches under data.items[].result.
+ const groups = payload?.data?.items;
+ if (!Array.isArray(groups)) return null;
+ const tokens = groups.flatMap((g) => (Array.isArray(g?.result) ? g.result : []));
+ const data = tokens
+ .map((t) => ({
+ mint: t.address,
+ symbol: t.symbol || '?',
+ name: t.name || t.symbol || '',
+ logo: t.logo_uri || t.logoURI || null,
+ price_usd: typeof t.price === 'number' ? t.price : null,
+ rank: null,
+ }))
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+ return data.length ? data : null;
+}
+
+/**
+ * Fallback: pump.fun's public frontend search (no API key). Mapped into the
+ * exact same shape. pump.fun doesn't expose a clean per-token USD price here,
+ * so price_usd is left null rather than fabricated.
+ */
+export async function searchPumpFun(q, limit) {
+ const url = new URL('/coins', PUMP_FRONTEND_BASE);
+ url.searchParams.set('searchTerm', q);
+ url.searchParams.set('offset', '0');
+ url.searchParams.set('limit', String(limit));
+ url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('order', 'DESC');
+ url.searchParams.set('includeNsfw', 'false');
+ let upstream;
+ try {
+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
+ } catch {
+ return null;
+ }
+ if (!upstream.ok) return null;
+ const body = await upstream.json().catch(() => null);
+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
+ if (!Array.isArray(coins)) return null;
+ const data = coins
+ .map((c, i) => ({
+ mint: c.mint || c.address || '',
+ symbol: c.symbol || '?',
+ name: c.name || c.symbol || '',
+ logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
+ price_usd: null,
+ rank: i + 1,
+ }))
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+ return data.length ? data : null;
+}
+
+/**
+ * Composed search: Birdeye first (when keyed), pump.fun frontend fallback.
+ * Returns `[]` (never null/throws) when both sources have no matches or are
+ * unavailable — a miss is a valid, common outcome, not an error.
+ */
+export async function searchPumpTokens(q, limit) {
+ const data = (await searchBirdeye(q, limit)) || (await searchPumpFun(q, limit));
+ return data || [];
+}
diff --git a/api/_lib/pump-trending.js b/api/_lib/pump-trending.js
new file mode 100644
index 000000000..46f679b56
--- /dev/null
+++ b/api/_lib/pump-trending.js
@@ -0,0 +1,144 @@
+// Shared "trending tokens" fetch + cache — the thin
+// { mint, symbol, name, logo, price_usd, rank } projection used by every free
+// trending consumer: GET /api/pump/trending (home card, communities,
+// constellation, dashboard chart picker) and the free GET /api/v1/pump/trending.
+// One fetch+cache+fallback path, two doors.
+//
+// Primary source is Birdeye (BIRDEYE_API_KEY, kept server-side). When Birdeye is
+// unconfigured, rate-limited, or down, falls back to pump.fun's public frontend
+// feed — same shape — so consumers degrade to live pump.fun data instead of a
+// hard error. A short-lived stale cache survives a brief outage on BOTH sources.
+
+import { normalizeGatewayURL } from '../../src/ipfs.js';
+
+const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
+
+// Process-local cache. Trending shifts slowly; many tabs polling on nav into the
+// dashboard would otherwise hammer the upstreams. Warm-starts share this map.
+// `storedAt` lets us serve the value as STALE (past its TTL) when every live
+// upstream is down — a slowly-changing market feed is far better shown a few
+// minutes old than blanked out with a 502 during an upstream blip.
+let _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
+const TTL_MS = 30_000;
+// How long a cached feed may be served as a stale fallback after every live
+// upstream has failed. Bounds how old the market data can get during an outage.
+const STALE_MAX_MS = 10 * 60_000;
+// Upstream fetch timeout. Trending is a fast feed behind a 30s cache + stale
+// fallback, so a long wait buys nothing — fail fast and fall through.
+const UPSTREAM_TIMEOUT_MS = 5000;
+// Birdeye circuit breaker: after a failure, skip Birdeye entirely for a cooldown
+// so an influx during a Birdeye outage stops paying the per-request timeout on
+// the way to the pump.fun fallback. Auto-recovers when the cooldown elapses.
+const BIRDEYE_COOLDOWN_MS = 60_000;
+let _birdeyeCooldownUntil = 0;
+
+// Serve a cached feed past its TTL when live upstreams are down. Returns the
+// sliced value if the slot holds enough items and is within the stale window,
+// else null.
+function serveStale(limit, now) {
+ if (!_cache.value || _cache.limit < limit) return null;
+ if (now - _cache.storedAt > STALE_MAX_MS) return null;
+ return _cache.value.slice(0, limit);
+}
+
+// Primary: Birdeye trending feed. Returns null (not throws) on any failure so the
+// caller can transparently fall back.
+async function fetchBirdeye(limit) {
+ if (!BIRDEYE_API_KEY) return null;
+ // Circuit open: a recent Birdeye failure put it in cooldown — skip straight to
+ // the fallback instead of paying the timeout again.
+ if (Date.now() < _birdeyeCooldownUntil) return null;
+ const url =
+ `https://public-api.birdeye.so/defi/token_trending` +
+ `?sort_by=rank&sort_type=asc&offset=0&limit=${limit}`;
+ let upstream;
+ try {
+ upstream = await fetch(url, {
+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
+ });
+ } catch {
+ _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
+ return null;
+ }
+ if (!upstream.ok) {
+ // 429 / 5xx — trip the breaker so the next requests skip the timeout.
+ _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
+ return null;
+ }
+ const payload = await upstream.json().catch(() => null);
+ const tokens = payload?.data?.tokens;
+ if (!Array.isArray(tokens)) return null;
+ const data = tokens
+ .map((t) => ({
+ mint: t.address,
+ symbol: t.symbol || '?',
+ name: t.name || t.symbol || '',
+ logo: t.logoURI || null,
+ price_usd: typeof t.price === 'number' ? t.price : null,
+ rank: typeof t.rank === 'number' ? t.rank : null,
+ }))
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+ return data.length ? data : null;
+}
+
+// Fallback: pump.fun's public frontend feed (no API key). Mapped into the exact
+// same shape so every consumer keeps working. pump.fun doesn't expose a clean
+// per-token USD price here, so price_usd is left null rather than fabricated.
+async function fetchPumpFun(limit) {
+ const url = new URL('/coins', PUMP_FRONTEND_BASE);
+ url.searchParams.set('offset', '0');
+ url.searchParams.set('limit', String(limit));
+ url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('order', 'DESC');
+ url.searchParams.set('includeNsfw', 'false');
+ let upstream;
+ try {
+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
+ } catch {
+ return null;
+ }
+ if (!upstream.ok) return null;
+ const body = await upstream.json().catch(() => null);
+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
+ if (!Array.isArray(coins)) return null;
+ const data = coins
+ .map((c, i) => ({
+ mint: c.mint || c.address || '',
+ symbol: c.symbol || '?',
+ name: c.name || c.symbol || '',
+ logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
+ price_usd: null,
+ rank: i + 1,
+ }))
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+ return data.length ? data : null;
+}
+
+/**
+ * Get up to `limit` trending tokens (thin projection), cached 30s with a stale
+ * fallback across a Birdeye→pump.fun failover.
+ *
+ * @param {number} limit
+ * @returns {Promise<{ data: object[]|null, stale: boolean }>}
+ * `data: null` only when both live sources are down AND no usable stale cache
+ * exists — callers translate that into their own 502/503 envelope.
+ */
+export async function getTrendingSlim(limit) {
+ const now = Date.now();
+ if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {
+ return { data: _cache.value.slice(0, limit), stale: false };
+ }
+
+ let data = await fetchBirdeye(limit);
+ if (!data) data = await fetchPumpFun(limit);
+ if (!data) {
+ const stale = serveStale(limit, now);
+ if (stale) return { data: stale, stale: true };
+ return { data: null, stale: false };
+ }
+
+ _cache = { value: data, storedAt: now, expiresAt: now + TTL_MS, limit };
+ return { data, stale: false };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 209e0d799..42c119420 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -473,6 +473,16 @@ export const limits = {
limit: Math.max(FREE_HOURLY_BASE, Math.round(FREE_HOURLY_BASE * (Number(multiplier) || 1))),
window: '1 h',
}).limit(key),
+ // Material Studio (api/material-studio.js): non-destructive material edits,
+ // AI restyle (one watsonx call + one gltf-transform mutation pass — cheap,
+ // no GPU job), and seeded variant fan-out. Free, hosted, and non-critical
+ // like mcp3dGenerateFree — a Redis outage must never deny a zero-cost edit.
+ // Uploads (exporting/checkpointing a lineage version) get a higher ceiling
+ // than restyle/variants since they carry no LLM/CPU-heavy cost.
+ materialStudioRestyle: (key) =>
+ getLimiter('material-studio:restyle', { limit: 40, window: '1 h' }).limit(key),
+ materialStudioUpload: (key) =>
+ getLimiter('material-studio:upload', { limit: 120, window: '1 h' }).limit(key),
// Status polling is the highest-frequency call in the generation flow (every
// active job polls every few seconds, plus the /forge health pill). It only
// guards against pathological poll floods, so it is enforced per instance
diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.js
index e50e68632..924727b84 100644
--- a/api/_mcp-studio/tools.js
+++ b/api/_mcp-studio/tools.js
@@ -16,6 +16,7 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
+import { MESH_DIRECTOR, AVATAR_DIRECTOR } from '../_lib/forge-director-prompts.js';
import { checkPromptSafety } from './safety.js';
import {
originFromReq,
@@ -202,20 +203,6 @@ async function handleTextToAvatar(args, _auth, req) {
return ok({ glbUrl: job.glb_url, base, kind: 'avatar', prompt: prompt || undefined });
}
-const MESH_DIRECTOR =
- "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " +
- 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' +
- 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' +
- 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' +
- 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' +
- 'coherent, consistent art style held across the whole subject (pick one: photoreal, stylized, low-poly, ' +
- 'hand-painted — never mix styles), (5) fine surface detail (seams, panel lines, weathering, grain) that ' +
- 'gives the reconstructor texture to latch onto. Always end with these composition constraints so the ' +
- 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' +
- 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' +
- 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' +
- 'preamble, no quotes.';
-
async function handleMeshForge(args, _auth, req) {
const base = originFromReq(req);
const prompt = String(args.prompt || '').trim();
@@ -269,21 +256,6 @@ async function handleRigMesh(args, _auth, req) {
return ok({ glbUrl: job.glb_url, base, kind: 'rigged model', rigged: true });
}
-const AVATAR_DIRECTOR =
- "You are a 3D character art director briefing a text-to-3D reconstruction model whose output will be " +
- "auto-rigged for animation. Rewrite the user's idea into ONE concise, information-dense prompt. Cover, in " +
- 'order: (1) a SINGLE full-body humanoid, standing in a neutral A/T-adjacent pose, arms slightly away from ' +
- 'the body and legs slightly apart so limbs are readable and separable for rigging, (2) body type and ' +
- 'proportions, (3) outfit and gear per body region (head, torso, arms, legs, feet) with explicit PBR ' +
- 'material cues (e.g. brushed metal armor, worn leather straps, matte cloth, glossy visor) so surfaces ' +
- 'reconstruct with correct roughness/metalness, (4) one coherent, consistent art style held across the ' +
- 'whole character (pick one: photoreal, stylized, low-poly, hand-painted — never mix styles), (5) key ' +
- 'identifying features (hair, face, color scheme, accessories). Always end with these composition ' +
- 'constraints: full body in frame head-to-toe, centered, isolated on a plain neutral background, no props ' +
- 'gripped or crossing the silhouette, one camera angle facing the character, even studio lighting, no ' +
- 'cropping, no motion blur, no text or watermark, no collage or multi-view grid, no second character. ' +
- 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';
-
async function handleForgeAvatar(args, _auth, req) {
const base = originFromReq(req);
const prompt = String(args.prompt || '').trim();
diff --git a/api/_mcp/tools/embed.js b/api/_mcp/tools/embed.js
index bbf440677..fcb7a099d 100644
--- a/api/_mcp/tools/embed.js
+++ b/api/_mcp/tools/embed.js
@@ -20,6 +20,8 @@ import {
forgeEmbedTarget,
oembedUrl,
} from '../../_lib/embed.js';
+import { isEmbedAssetRef, resolveEmbedAsset } from '../../_lib/embed-asset.js';
+import { DEFAULT_GATE_MINT, createEmbedGate, checkAssetOwnership } from '../../_lib/embed-gate.js';
function rpcError(code, message, data) {
const e = new Error(message);
@@ -219,4 +221,94 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'create_gated_embed',
+ title: 'Create a token-gated embed',
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
+ description:
+ 'Turn an avatar or on-chain agent you own into a holder-only interactive 3D embed. Visitors must prove — with a real, server-verified Solana SPL token balance, never a client-reported number — they hold at least min_amount of mint before the live scene renders; below that they see a designed locked teaser with a connect-wallet CTA. mint defaults to $THREE but accepts any SPL mint at runtime. Returns a ready-to-paste <three-d> embed snippet.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset_id: {
+ type: 'string',
+ description: 'The embed asset to gate: "avatar:<uuid>" or "<chainId>:<agentId>" (on-chain agent you own).',
+ },
+ mint: {
+ type: 'string',
+ description: `SPL token mint holders must have a balance of. Defaults to $THREE (${DEFAULT_GATE_MINT}) — pass a different mint to gate with another community's token.`,
+ },
+ min_amount: {
+ type: 'number',
+ exclusiveMinimum: 0,
+ description: 'Minimum token balance a visitor must hold to unlock the embed.',
+ },
+ },
+ required: ['asset_id', 'min_amount'],
+ additionalProperties: false,
+ },
+ scope: 'avatars:write',
+ async handler(args, auth, req) {
+ if (!isEmbedAssetRef(args.asset_id)) {
+ throw rpcError(-32602, 'asset_id must be "<chainId>:<agentId>" or "avatar:<uuid>"');
+ }
+ const asset = await resolveEmbedAsset(args.asset_id);
+ if (!asset) throw new Error(`embed asset "${args.asset_id}" not found`);
+
+ const ownership = await checkAssetOwnership(args.asset_id, auth.userId);
+ if (!ownership.ok) {
+ if (ownership.reason === 'not_owner') {
+ throw new Error(
+ 'you do not own this asset — link the owning wallet (or account) to gate it',
+ );
+ }
+ throw new Error(`embed asset "${args.asset_id}" not found`);
+ }
+
+ let gate;
+ try {
+ gate = await createEmbedGate({
+ assetId: args.asset_id,
+ ownerUserId: auth.userId,
+ mint: args.mint || DEFAULT_GATE_MINT,
+ minAmount: args.min_amount,
+ chain: 'solana',
+ });
+ } catch (err) {
+ throw rpcError(-32602, err.message);
+ }
+
+ const origin = resolveOrigin(req);
+ const scriptSrc = `${origin}/embed/v1.js`;
+ const snippet =
+ `<script src="${scriptSrc}" async></script>\n` +
+ `<three-d agent="${args.asset_id}" interactive></three-d>`;
+ const symbol = gate.mint === DEFAULT_GATE_MINT ? '$THREE' : gate.mint;
+
+ const structuredContent = {
+ ok: true,
+ gate_id: gate.gateId,
+ asset_id: gate.assetId,
+ gate: { mint: gate.mint, min_amount: gate.minAmount, chain: gate.chain },
+ embed_snippet: snippet,
+ };
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Gated "${asset.name || args.asset_id}" — visitors need ≥ ${gate.minAmount} ${symbol} to unlock it. ` +
+ `Paste this anywhere HTML is allowed:\n\n${snippet}`,
+ },
+ ],
+ structuredContent,
+ };
+ },
+ },
];
diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.js
index 3aa279a0b..481bf0d30 100644
--- a/api/_mcp3d/catalog.js
+++ b/api/_mcp3d/catalog.js
@@ -5,6 +5,8 @@ import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { priceUsdcForTier } from '../_lib/forge-tiers.js';
import { toolDefs as studioDefs } from './tools/studio.js';
import { toolDefs as spatialDefs } from './tools/spatial.js';
+import { toolDefs as arDefs } from './tools/ar.js';
+import { toolDefs as personaIdentityDefs } from './tools/persona-identity.js';
import { toolDefs as modelDefs } from '../_mcp/tools/models.js';
import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';
@@ -19,7 +21,7 @@ const reusedModelDefs = modelDefs.filter(
// The animation library (list_animations + apply_animation) completes the
// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine
// the main server exposes — reused here, not duplicated.
-const baseDefs = [...studioDefs, ...spatialDefs, ...reusedModelDefs, ...animationDefs];
+const baseDefs = [...studioDefs, ...spatialDefs, ...arDefs, ...personaIdentityDefs, ...reusedModelDefs, ...animationDefs];
// Free, public entry point — listed first so discovery clients see it up top.
// Annotations: a static, local overview built at module load — read-only,
diff --git a/api/_mcp3d/tools/ar.js b/api/_mcp3d/tools/ar.js
new file mode 100644
index 000000000..350c166df
--- /dev/null
+++ b/api/_mcp3d/tools/ar.js
@@ -0,0 +1,96 @@
+// export_ar — turn any generated GLB into a one-tap "View in your space" AR link.
+//
+// Given a GLB URL, it returns a device-aware AR launch link (/api/ar, which
+// branches on User-Agent: iOS Quick Look, Android Scene Viewer, desktop WebGL),
+// the interactive viewer link, and the raw Scene Viewer intent — shaped as a
+// conformant Spatial MCP artifact (specs/SPATIAL_MCP.md) with the AR handoff
+// populated. Free, read-only, and coin-clean: no payment, wallet, token, session,
+// or trace fields, so the response ships unchanged on the OpenAI free track. The
+// actual GLB→USDZ conversion for iOS happens in the launch page via model-viewer
+// (three.js USDZExporter) — a real conversion, no server-side USD tooling.
+
+import { buildSpatialArtifact } from '../../_lib/spatial-mcp.js';
+import {
+ assertArAssetUrl,
+ buildArLaunchUrl,
+ buildViewerUrl,
+ buildSceneViewerUrl,
+} from '../../_lib/ar-launch.js';
+
+const DEFAULT_ORIGIN = 'https://three.ws';
+
+function originFrom(req) {
+ const host = req?.headers?.['x-forwarded-host'] || req?.headers?.host;
+ if (!host) return DEFAULT_ORIGIN;
+ const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');
+ return `${proto}://${host}`;
+}
+
+export const toolDefs = [
+ {
+ name: 'export_ar',
+ title: 'Export a model for AR ("View in your space")',
+ annotations: {
+ readOnlyHint: true, // resolves links for an existing GLB — creates nothing
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false, // URLs are constructed locally; no external call
+ },
+ description:
+ 'Turn a generated 3D model (GLB URL) into a one-tap "View in your space" AR experience. Returns a ' +
+ 'device-aware AR launch link (iOS Quick Look, Android Scene Viewer, desktop WebGL — branched on the ' +
+ "viewer's device), the interactive viewer link, and a conformant Spatial MCP artifact with the AR handoff " +
+ 'populated. Use it after generating a model so the user can place it on their desk through their phone.',
+ inputSchema: {
+ type: 'object',
+ additionalProperties: false,
+ required: ['glb_url'],
+ properties: {
+ glb_url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb (or .gltf) model to export for AR.' },
+ title: { type: 'string', maxLength: 120, description: 'Optional name shown in the AR/viewer experience.' },
+ },
+ },
+ async handler(args, _auth, req) {
+ let asset;
+ try {
+ asset = assertArAssetUrl(args.glb_url);
+ } catch (err) {
+ return {
+ content: [{ type: 'text', text: err.arUserMessage ? err.message : 'Provide a public https URL to a .glb model.' }],
+ structuredContent: { error: true, message: err.message },
+ isError: true,
+ };
+ }
+ const origin = originFrom(req);
+ const title = typeof args.title === 'string' ? args.title.slice(0, 120) : '';
+ const arLaunchUrl = buildArLaunchUrl(origin, asset, title);
+ const viewerUrl = buildViewerUrl(origin, asset, title);
+ const sceneViewerUrl = buildSceneViewerUrl(asset, { title, fallbackUrl: viewerUrl });
+
+ const spatial = buildSpatialArtifact({
+ glbUrl: asset,
+ kind: 'model',
+ viewerUrl,
+ title: title || undefined,
+ ar: { glbUrl: asset, launchUrl: arLaunchUrl },
+ });
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Ready for AR. Open on a phone to place it in your space: ${arLaunchUrl}\nInteractive viewer: ${viewerUrl}`,
+ },
+ ],
+ structuredContent: {
+ glbUrl: asset,
+ arLaunchUrl,
+ viewerUrl,
+ sceneViewerUrl,
+ format: 'glb',
+ spatial,
+ },
+ };
+ },
+ },
+];
diff --git a/api/_mcp3d/tools/persona-identity.js b/api/_mcp3d/tools/persona-identity.js
index 783755327..5350865dd 100644
--- a/api/_mcp3d/tools/persona-identity.js
+++ b/api/_mcp3d/tools/persona-identity.js
@@ -90,9 +90,10 @@ async function handlePersonaIdentity(args, auth) {
const identity = await getPersonaIdentity(args.persona_id, { network: args.network || 'mainnet' });
const persona = personaPublicView(record);
const v = identity.visual;
+ const card = buildIdentityCard({ persona, identity });
const lines = [
- `${persona.name}'s on-chain identity`,
+ `${persona.name}'s on-chain identity — ${summarizeIdentityCard(card)}`,
`Wallet: ${identity.address} (${identity.network})`,
`Balance: ${identity.balances.sol.toFixed(4)} SOL, ${identity.balances.usdc.toFixed(2)} USDC` +
(identity.balances.total_usd != null ? ` (~$${identity.balances.total_usd})` : ''),
@@ -105,10 +106,9 @@ async function handlePersonaIdentity(args, auth) {
return {
content: [
{ type: 'text', text: lines.join('\n') },
- renderIdentityCard({ persona, identity }),
embodimentArtifact({ persona, state: 'idle' }),
],
- structuredContent: { ...identity, status: 'ok' },
+ structuredContent: { ...identity, identity_card: card, status: 'ok' },
};
}
diff --git a/api/_okx3d/rest-services.js b/api/_okx3d/rest-services.js
index 6a50558aa..da4db0e53 100644
--- a/api/_okx3d/rest-services.js
+++ b/api/_okx3d/rest-services.js
@@ -26,6 +26,7 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { catalogEntry } from '../_lib/okx-catalog.js';
+import { MESH_DIRECTOR } from '../_lib/forge-director-prompts.js';
import {
originFromReq,
viewerUrl,
@@ -87,20 +88,8 @@ function queuedResponse(job, extra = {}) {
}
// Prompt used by text-to-3d-pro — the same single-subject art-director spec
-// mesh_forge uses (kept in sync with api/_mcp-studio/tools.js).
-const MESH_DIRECTOR =
- "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " +
- 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' +
- 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' +
- 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' +
- 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' +
- 'coherent, consistent art style held across the whole subject (pick one: photoreal, stylized, low-poly, ' +
- 'hand-painted — never mix styles), (5) fine surface detail (seams, panel lines, weathering, grain) that ' +
- 'gives the reconstructor texture to latch onto. Always end with these composition constraints so the ' +
- 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' +
- 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' +
- 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' +
- 'preamble, no quotes.';
+// mesh_forge uses (imported from _lib/forge-director-prompts.js, the shared
+// source of truth across api/_mcp-studio/tools.js, this file, and /api/forge).
// Humanoid gate for the avatar chain — mirror of the forge_avatar steer in
// api/_mcp-studio/tools.js so both surfaces refuse the same obvious objects.
diff --git a/api/ar.js b/api/ar.js
new file mode 100644
index 000000000..1c3016d89
--- /dev/null
+++ b/api/ar.js
@@ -0,0 +1,110 @@
+/**
+ * Device-aware AR launch — GET /api/ar?src=<glbUrl>&title=<name>
+ * -------------------------------------------------------------
+ * Places a generated GLB in the user's space, branching on the request's
+ * User-Agent (server-side, from the header — no client round-trip):
+ *
+ * • Android → 302 to a Google Scene Viewer ARCore intent:// URL (GLB as the
+ * source), with a browser fallback to the WebGL viewer.
+ * • iOS → an HTML launch page with <model-viewer>; tapping "View in AR"
+ * enters Apple Quick Look, for which model-viewer generates a USDZ from the
+ * GLB on the fly (a real conversion via three.js USDZExporter, in-page).
+ * • desktop → the same launch page, which falls back to the interactive WebGL
+ * viewer (no AR hardware).
+ *
+ * Bad input (non-https, non-GLB, missing) is rejected at the boundary with a
+ * clean, designed error page — never a crash. Zero payment/coin surface.
+ */
+
+import { cors, wrap } from './_lib/http.js';
+import { planArLaunch } from './_lib/ar-launch.js';
+
+function esc(s) {
+ return String(s || '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function originFrom(req) {
+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');
+ return `${proto}://${host}`;
+}
+
+function errorPage(message) {
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1"/><title>View in AR · three.ws</title>
+<style>:root{color-scheme:dark}body{margin:0;min-height:100dvh;display:flex;align-items:center;justify-content:center;
+font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:radial-gradient(130% 130% at 50% 0%,#14161c,#08090c);color:#e8eaf0;text-align:center;padding:28px}
+.c{max-width:38ch}.h{font-size:16px;font-weight:600;margin-bottom:10px}.m{color:#9aa3b2;font-size:13px;line-height:1.5}
+a{display:inline-block;margin-top:16px;color:#dbe9ff;background:rgba(110,168,254,.16);border:1px solid rgba(110,168,254,.42);
+border-radius:10px;padding:9px 14px;text-decoration:none;font-weight:600;font-size:13px}</style></head>
+<body><div class="c"><div class="h">Can't open this in AR</div><div class="m">${esc(message)}</div>
+<a href="https://three.ws">Create a 3D model</a></div></body></html>`;
+}
+
+function launchPage({ target, asset, viewerUrl, title }) {
+ const t = title ? esc(title) : '3D model';
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
+<title>View ${t} in AR · three.ws</title><meta name="robots" content="noindex"/>
+<script src="/model-viewer-meshopt.js"></script>
+<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>
+<style>:root{color-scheme:dark;--accent:#6ea8fe}*{box-sizing:border-box}html,body{margin:0;height:100%}
+body{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:radial-gradient(130% 130% at 50% 0%,#14161c,#08090c);color:#e8eaf0;overflow:hidden}
+.wrap{display:flex;flex-direction:column;height:100dvh}.stage{position:relative;flex:1 1 auto;min-height:0}
+model-viewer{width:100%;height:100%;--progress-bar-color:var(--accent);background:transparent}
+.bar{display:flex;gap:10px;align-items:center;justify-content:center;padding:14px 16px;border-top:1px solid rgba(255,255,255,.07);background:rgba(10,11,14,.55);backdrop-filter:blur(8px)}
+button.ar,a.ar{appearance:none;cursor:pointer;text-decoration:none;font-size:14px;font-weight:700;color:#0b0c10;background:var(--accent);border:0;border-radius:12px;padding:12px 20px;display:inline-flex;align-items:center;gap:8px}
+button.ar:active{transform:translateY(1px)}button.ar:focus-visible{outline:2px solid #fff;outline-offset:2px}
+.hint{position:absolute;left:0;right:0;bottom:16px;text-align:center;color:#9aa3b2;font-size:12px;pointer-events:none}
+a.alt{color:#aeb6c4;font-size:12.5px;text-decoration:underline}</style></head>
+<body><div class="wrap"><div class="stage">
+<model-viewer id="mv" src="${esc(asset)}" alt="${t}" camera-controls auto-rotate touch-action="pan-y"
+ environment-image="neutral" exposure="1.05" shadow-intensity="1" tone-mapping="aces"
+ ar ar-modes="webxr scene-viewer quick-look" ar-scale="auto" ${target === 'ios' ? 'reveal="auto"' : ''}>
+</model-viewer>
+<div class="hint" id="hint">Move your phone to place the model in your space.</div>
+</div>
+<div class="bar">
+<button class="ar" id="ar-btn" type="button" aria-label="View this model in augmented reality">📱 View in your space</button>
+<a class="alt" href="${esc(viewerUrl)}">Open in 3D viewer</a>
+</div></div>
+<script>
+(function(){var mv=document.getElementById('mv'),btn=document.getElementById('ar-btn'),hint=document.getElementById('hint');
+function sync(){ if(!mv.canActivateAR){ btn.textContent='View in 3D'; hint.style.display='none'; } }
+mv.addEventListener('load',sync);
+btn.addEventListener('click',function(){ if(mv.canActivateAR){ try{mv.activateAR();}catch(e){} } else { window.location.href='${esc(viewerUrl)}'; } });
+})();
+</script></body></html>`;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const src = url.searchParams.get('src') || '';
+ const title = (url.searchParams.get('title') || '').slice(0, 120);
+
+ let plan;
+ try {
+ plan = planArLaunch({ glbUrl: src, userAgent: req.headers['user-agent'], origin: originFrom(req), title });
+ } catch (err) {
+ res.statusCode = 400;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(errorPage(err.arUserMessage ? err.message : 'That model link could not be opened.'));
+ return;
+ }
+
+ if (plan.action === 'redirect') {
+ res.statusCode = 302;
+ res.setHeader('location', plan.url);
+ res.setHeader('cache-control', 'no-store');
+ res.end();
+ return;
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600');
+ res.end(launchPage({ target: plan.target, asset: plan.asset, viewerUrl: plan.viewerUrl, title }));
+});
diff --git a/api/erc8004/[action].js b/api/erc8004/[action].js
index db0cfe1c9..bca9c7bc2 100644
--- a/api/erc8004/[action].js
+++ b/api/erc8004/[action].js
@@ -13,7 +13,7 @@ import { z } from 'zod';
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, error, readJson, readBody, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import {
@@ -513,20 +513,11 @@ async function uploadToNftStorage(token, ext, body, ct) {
return { cid, uri, url };
}
+// Delegates to the shared readBody (api/_lib/http.js). For the binary/model
+// content-types this endpoint accepts, the Cloud Run server's Express body
+// parsers never touch the stream, so this behaves exactly as the old
+// raw-stream reader did; for the json/octet-stream types they DO pre-parse,
+// re-reading the raw stream directly (the old implementation) hangs forever.
function readRaw(req, limit) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let total = 0;
- req.on('data', (chunk) => {
- total += chunk.length;
- if (total > limit) {
- reject(Object.assign(new Error('payload too large'), { status: 413 }));
- req.destroy();
- return;
- }
- chunks.push(chunk);
- });
- req.on('end', () => resolve(Buffer.concat(chunks)));
- req.on('error', reject);
- });
+ return readBody(req, limit);
}
diff --git a/api/forge.js b/api/forge.js
index d81336d96..627c4231d 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -105,6 +105,7 @@ import {
} from './_lib/forge-cache.js';
import { shouldRetryForQuality } from './_lib/glb-quality.js';
import { directPrompt, originFromReq } from './_mcp-studio/forge-client.js';
+import { MESH_DIRECTOR } from './_lib/forge-director-prompts.js';
// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The
// hosted NVCF gateway can degrade so a submit neither completes nor hands back a
@@ -1115,9 +1116,10 @@ async function startJob(req, res) {
sourceUrl: sketchUrl,
params: {
prompt,
- target_polycount: tier.polycount,
+ target_polycount: opts.targetPolycount ?? tier.polycount,
tier: tier.id,
path,
+ seed: opts.seed ?? undefined,
},
});
} catch (err) {
@@ -1166,6 +1168,7 @@ async function startJob(req, res) {
tier: tier.id,
path,
});
+ await bindJobToOptions(token, opts);
const sketchCold = await coldStartFor(backendId);
return json(res, 200, {
@@ -1182,6 +1185,7 @@ async function startJob(req, res) {
cold_start: sketchCold,
eta_seconds: estimateEtaSeconds({ backendId, tier, cold: sketchCold }),
estimated_credits: estimateCredits({ backendId, path, tier }),
+ options: opts.hasOptions ? summarizeForgeOptions(opts) : undefined,
});
}
@@ -1254,6 +1258,8 @@ async function startJob(req, res) {
replicateJobId: syntheticJob,
clientKey,
glbUrl: submitted.resultGlbUrl,
+ quality: true,
+ compress: opts.compression !== 'none' ? opts.compression : null,
});
return json(res, 200, {
job_id: null,
@@ -1261,6 +1267,9 @@ async function startJob(req, res) {
status: 'done',
glb_url: durable?.glbUrl ?? submitted.resultGlbUrl,
durable: Boolean(durable),
+ quality: durable?.quality || null,
+ compression: durable?.compression || null,
+ options: opts.hasOptions ? summarizeForgeOptions(opts) : undefined,
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
path,
tier: tier.id,
@@ -1278,6 +1287,7 @@ async function startJob(req, res) {
kind: submitted.kind,
taskId: submitted.taskId,
});
+ await bindJobToOptions(token, opts);
// Store the upstream task id as the job handle so findByJob/materialize
// resolve it on poll, exactly like the Replicate path.
@@ -1457,7 +1467,22 @@ async function startJob(req, res) {
referenceImageUrl = imageUrls[0];
textToImageModel = null;
} else {
- const synthesized = await textToImage(prompt, { aspectRatio: aspect, skipNim: nimGatewayDegraded });
+ // Optional Granite art-director pass (off by default): rewrites the raw
+ // prompt into a richer, single-subject spec (form, per-part materials,
+ // one held style, composition constraints) before it drives the FLUX
+ // reference image — the same director the free MCP tools use. Fail-soft:
+ // any failure (chat lane down, timeout) silently keeps the raw prompt, so
+ // opting in can only ever help, never break, a generation.
+ let directedPrompt = prompt;
+ if (body?.director === true) {
+ const directed = await directPrompt(originFromReq(req), MESH_DIRECTOR, prompt).catch(() => null);
+ if (directed) directedPrompt = directed;
+ }
+ const synthesized = await textToImage(directedPrompt, {
+ aspectRatio: aspect,
+ skipNim: nimGatewayDegraded,
+ seed: opts.seed ?? undefined,
+ });
referenceImageUrl = synthesized.imageUrl;
textToImageModel = synthesized.model;
views = [referenceImageUrl];
@@ -1497,7 +1522,7 @@ async function startJob(req, res) {
job = await gcp.submit({
mode: 'trellis',
sourceUrl: referenceImageUrl,
- params: { images: views },
+ params: { images: views, seed: opts.seed ?? undefined },
});
} catch (err) {
if (err?.code === 'mode_unconfigured') {
@@ -1543,6 +1568,8 @@ async function startJob(req, res) {
tier: tier.id,
path,
});
+ if (cacheKey) await bindJobToCacheKey(token, cacheKey);
+ await bindJobToOptions(token, opts);
const cold = await coldStartFor(backendId);
return json(res, 200, {
@@ -1558,6 +1585,7 @@ async function startJob(req, res) {
reference_image_urls: isImageMode ? [imageUrls[0]] : [referenceImageUrl],
text_to_image_model: isImageMode ? null : textToImageModel,
cold_start: cold,
+ options: opts.hasOptions ? summarizeForgeOptions(opts) : undefined,
eta_seconds: estimateEtaSeconds({ backendId, tier, cold }),
estimated_credits: estimateCredits({ backendId, path, tier }),
});
@@ -1642,12 +1670,17 @@ async function startJob(req, res) {
// Only poly-aware backends (Hunyuan3D self-host) accept a target budget;
// TRELLIS validates its input schema and would 422 on an unknown field, so
- // the tier rides along as the recorded provenance only.
+ // the tier rides along as the recorded provenance only. `seed` is a
+ // recognized generation param across the TRELLIS family and Hunyuan3D
+ // alike (survives stripInternal() and overrides the provider's own
+ // default), so it's forwarded unconditionally, not gated on polyControl.
const reconstructParams = { images: views, prompt: prompt || undefined };
+ if (opts.seed !== null) reconstructParams.seed = opts.seed;
if (BACKENDS[backendId].polyControl) {
- reconstructParams.target_polycount = tier.polycount;
+ reconstructParams.target_polycount = opts.targetPolycount ?? tier.polycount;
reconstructParams.tier = tier.id;
reconstructParams.path = path;
+ if (opts.textureSize) reconstructParams.texture_size = opts.textureSize;
}
let job;
@@ -1716,9 +1749,10 @@ async function startJob(req, res) {
backendId = 'hunyuan3d';
provider = createGcpProvider({ reconstructUrl: hunyuanUrl });
// Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.
- reconstructParams.target_polycount = tier.polycount;
+ reconstructParams.target_polycount = opts.targetPolycount ?? tier.polycount;
reconstructParams.tier = tier.id;
reconstructParams.path = path;
+ if (opts.textureSize) reconstructParams.texture_size = opts.textureSize;
job = await provider.submit({
mode: 'reconstruct',
sourceUrl: referenceImageUrl,
@@ -1799,6 +1833,11 @@ async function startJob(req, res) {
// requests in the next few minutes coalesce onto it instead of re-running the
// GPU pipeline. First writer wins; best-effort (no-op without Redis).
await registerInFlight(requestHash, jobHandle);
+ // Cache-eligibility was fixed before any lane failover reassigned backendId;
+ // a BYOK pick already disqualified it above, so it's always safe to bind
+ // here for whichever platform lane actually ran.
+ if (cacheKey) await bindJobToCacheKey(jobHandle, cacheKey);
+ await bindJobToOptions(jobHandle, opts);
// Honest cold-start: only a self-host worker reached cold widens the ETA
// (a paid/external lane returns false). Covers the Hunyuan3D self-host
@@ -1820,6 +1859,7 @@ async function startJob(req, res) {
multiview,
text_to_image_model: textToImageModel,
cold_start: cold,
+ options: opts.hasOptions ? summarizeForgeOptions(opts) : undefined,
eta_seconds: estimateEtaSeconds({ backendId, tier, cold }),
estimated_credits: estimateCredits({ backendId, path, tier }),
});
diff --git a/api/pump/curve.js b/api/pump/curve.js
index 0b97ecd4d..66de193df 100644
--- a/api/pump/curve.js
+++ b/api/pump/curve.js
@@ -6,50 +6,12 @@
// - current price + market cap
// - graduation progress
//
-// Cached at the edge for 10s — the curve only changes per trade so a few
-// seconds of staleness is acceptable and keeps RPC cost down on hot mints.
+// The fetch/RPC/Jupiter-fallback logic lives in api/_lib/pump-curve-view.js
+// (getCurveView), shared with the free GET /api/v1/pump/curve endpoint — one
+// path, two doors, byte-identical response shape and cache headers.
import { cors, json, method, wrap, error } from '../_lib/http.js';
-import {
- rpcFallbackFromEnv,
- getBondingCurveState,
- getTokenPrice,
- getGraduationProgress,
-} from '../_lib/solana/index.js';
-
-// Mints that can never carry a pump.fun bonding curve. These are coin-agnostic
-// payment-rail / native tokens, listed only so we can *exclude* them from curve
-// lookups — never to promote them. (USDC mainnet+devnet, wrapped SOL.)
-const NON_CURVE_MINTS = new Set([
- 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC (mainnet)
- '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC (devnet)
- 'So11111111111111111111111111111111111111112', // wrapped SOL
-]);
-
-// pump.fun mints a fixed total supply of exactly 1B tokens, the whole of which
-// is sold through the curve and then seeded into the AMM pool on graduation. For
-// these tokens fully-diluted value therefore equals market cap.
-const PUMP_TOTAL_SUPPLY = 1_000_000_000;
-
-// Every pump.fun mint keypair is ground to end in the literal suffix "pump". A
-// mint that does not end in "pump" (or that is a known settlement token) has no
-// bonding curve and never will — so we can reject it without touching RPC.
-function isPumpMint(mint) {
- return typeof mint === 'string' && mint.endsWith('pump') && !NON_CURVE_MINTS.has(mint);
-}
-
-async function jupiterPriceFallback(mint) {
- try {
- const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mint}`, { signal: AbortSignal.timeout(6000) });
- if (!r.ok) return null;
- const data = await r.json();
- const usd = data?.[mint]?.usdPrice ?? data?.[mint]?.price;
- const n = Number(usd);
- return Number.isFinite(n) && n > 0 ? { priceUsd: n, source: 'jupiter' } : null;
- } catch {
- return null;
- }
-}
+import { getCurveView, isPlausibleMint } from '../_lib/pump-curve-view.js';
function readMint(req) {
try {
@@ -63,10 +25,6 @@ function readMint(req) {
}
}
-function isPlausibleMint(s) {
- return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
-}
-
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
@@ -76,113 +34,6 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_mint', 'mint query param must be a base58 Solana address');
}
- // Short-circuit mints that cannot have a bonding curve (settlement tokens,
- // non-"pump" mints) *before* any Solana RPC call. This kills the 404 + RPC-429
- // storm a misconfigured (e.g. USDC) widget mount would otherwise trigger: no
- // cold start, no RPC reads, no warning spam. The negative-cache header lets the
- // CDN edge serve repeat probes so the function isn't hit at all. The client's
- // existing stop-on-404 path fires on this exactly as it does for a real 404.
- if (!isPumpMint(mint)) {
- return json(
- res,
- 404,
- { error: 'not_a_pump_mint', error_description: 'mint has no pump.fun bonding curve' },
- { 'cache-control': 'public, s-maxage=300, max-age=300' },
- );
- }
-
- const rpc = rpcFallbackFromEnv({ network });
- const result = await rpc.withFallback(async (connection) => {
- const [curve, price, grad] = await Promise.all([
- getBondingCurveState(connection, mint),
- getTokenPrice(connection, mint),
- getGraduationProgress(connection, mint),
- ]);
- return { curve, price, graduation: grad };
- });
-
- if (!result.curve) {
- // No on-chain bonding curve account. Two cases to disambiguate:
- // 1. Graduated coin — the curve account is closed once a coin migrates
- // to its AMM pool, but the token still trades with a live DEX price.
- // Fall back to Jupiter and return a 200 "graduated" view so callers
- // render the real price instead of a dead 404. (Our own $THREE lives
- // here post-migration.)
- // 2. A mint that never had a curve — Jupiter has nothing either, so the
- // 404 stands and the client's stop-on-404 path fires as before.
- const graduatedPrice = await jupiterPriceFallback(mint);
- if (graduatedPrice) {
- // pump.fun mints a fixed 1B supply entirely into the curve/pool, so
- // fully-diluted value equals market cap. Compute it once here so every
- // consumer gets a meaningful market cap without re-deriving supply.
- const marketCapUsd = graduatedPrice.priceUsd * PUMP_TOTAL_SUPPLY;
- return json(
- res,
- 200,
- {
- mint,
- network,
- curve: null,
- graduated: true,
- price: null,
- graduation: { isGraduated: true, progressBps: 10_000 },
- graduatedPrice: { ...graduatedPrice, marketCapUsd },
- },
- { 'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=60' },
- );
- }
- return error(res, 404, 'no_curve', 'no bonding curve found for that mint');
- }
-
- // Graduated coins have no bonding-curve price. A coin can graduate yet leave
- // its on-chain curve account behind (closed, reserves zeroed, complete=true) —
- // this is exactly the case for our own $THREE. Fall back to Jupiter so callers
- // always get a usable price even after migration to a DEX, and surface the same
- // `graduated: true` + market-cap-enriched `graduatedPrice` shape as the
- // curve-gone path above so every consumer renders graduated coins identically.
- let pricePayload = result.price ? serializeBNs(result.price) : null;
- const curveComplete = Boolean(result.curve?.complete);
- let graduatedPrice = null;
- if (!pricePayload && curveComplete) {
- const jup = await jupiterPriceFallback(mint);
- if (jup) {
- // Fixed 1B supply minted entirely into the curve/pool ⇒ FDV == market cap.
- graduatedPrice = { ...jup, marketCapUsd: jup.priceUsd * PUMP_TOTAL_SUPPLY };
- }
- }
-
- return json(
- res,
- 200,
- {
- mint,
- network,
- curve: result.curve,
- ...(curveComplete ? { graduated: true } : {}),
- price: pricePayload,
- graduation: result.graduation ? serializeBNs(result.graduation) : null,
- ...(graduatedPrice ? { graduatedPrice } : {}),
- },
- { 'cache-control': 'public, max-age=5, s-maxage=10, stale-while-revalidate=30' },
- );
+ const { httpStatus, cacheControl, body } = await getCurveView({ mint, network });
+ return json(res, httpStatus, body, cacheControl ? { 'cache-control': cacheControl } : {});
});
-
-function serializeBNs(obj) {
- if (obj == null || typeof obj !== 'object') return obj;
- const out = Array.isArray(obj) ? [] : {};
- for (const [k, v] of Object.entries(obj)) {
- if (
- v &&
- typeof v === 'object' &&
- typeof v.toString === 'function' &&
- (v.constructor?.name === 'BN' || typeof v.toNumber === 'function')
- ) {
- out[k] = v.toString();
- } else if (v && typeof v === 'object') {
- out[k] = serializeBNs(v);
- } else {
- out[k] = v;
- }
- }
- return out;
-}
diff --git a/api/pump/search.js b/api/pump/search.js
index efa5a1c94..523fb19b9 100644
--- a/api/pump/search.js
+++ b/api/pump/search.js
@@ -5,20 +5,16 @@
// query. Returns the same item shape as /api/pump/trending so consumers can
// share rendering code.
//
-// Primary source is Birdeye token search (keeps BIRDEYE_API_KEY server-side).
-// When Birdeye is unconfigured, rate-limited, or down, we fall back to
-// pump.fun's public frontend search (no API key) — same response shape — so the
-// palette degrades to live pump.fun data instead of a hard error. Only errors
-// when both sources are unavailable.
+// The Birdeye-first, pump.fun-fallback search logic lives in
+// api/_lib/pump-search.js (`searchPumpTokens`) — shared with the free,
+// versioned /api/v1/pump/search endpoint so neither route forks the upstream
+// logic. This handler adds the palette-specific process-local response cache.
//
// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { normalizeGatewayURL } from '../../src/ipfs.js';
-
-const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
-const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
+import { searchPumpTokens } from '../_lib/pump-search.js';
// Process-local cache keyed by normalized query. Palette keystrokes are
// debounced client-side, but repeated queries (same token typed twice) and many
@@ -27,76 +23,6 @@ const _cache = new Map(); // key -> { value, expiresAt }
const TTL_MS = 30_000;
const CACHE_MAX = 100;
-// Primary: Birdeye token search. Returns null (not throws) on any failure so the
-// caller can transparently fall back to pump.fun.
-async function searchBirdeye(q, limit) {
- if (!BIRDEYE_API_KEY) return null;
- const url =
- `https://public-api.birdeye.so/defi/v3/search` +
- `?chain=solana&target=token&search_mode=fuzzy&sort_by=marketcap&sort_type=desc` +
- `&offset=0&limit=${limit}&keyword=${encodeURIComponent(q)}`;
- let upstream;
- try {
- upstream = await fetch(url, {
- headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
- signal: AbortSignal.timeout(8000),
- });
- } catch {
- return null;
- }
- if (!upstream.ok) return null;
- const payload = await upstream.json().catch(() => null);
- // v3 search nests token matches under data.items[].result.
- const groups = payload?.data?.items;
- if (!Array.isArray(groups)) return null;
- const tokens = groups.flatMap((g) => (Array.isArray(g?.result) ? g.result : []));
- const data = tokens
- .map((t) => ({
- mint: t.address,
- symbol: t.symbol || '?',
- name: t.name || t.symbol || '',
- logo: t.logo_uri || t.logoURI || null,
- price_usd: typeof t.price === 'number' ? t.price : null,
- rank: null,
- }))
- .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
- return data.length ? data : null;
-}
-
-// Fallback: pump.fun's public frontend search (no API key). Mapped into the
-// exact same shape. pump.fun doesn't expose a clean per-token USD price here, so
-// price_usd is left null rather than fabricated.
-async function searchPumpFun(q, limit) {
- const url = new URL('/coins', PUMP_FRONTEND_BASE);
- url.searchParams.set('searchTerm', q);
- url.searchParams.set('offset', '0');
- url.searchParams.set('limit', String(limit));
- url.searchParams.set('sort', 'market_cap');
- url.searchParams.set('order', 'DESC');
- url.searchParams.set('includeNsfw', 'false');
- let upstream;
- try {
- upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
- } catch {
- return null;
- }
- if (!upstream.ok) return null;
- const body = await upstream.json().catch(() => null);
- const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
- if (!Array.isArray(coins)) return null;
- const data = coins
- .map((c, i) => ({
- mint: c.mint || c.address || '',
- symbol: c.symbol || '?',
- name: c.name || c.symbol || '',
- logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
- price_usd: null,
- rank: i + 1,
- }))
- .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
- return data.length ? data : null;
-}
-
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -118,15 +44,9 @@ export default wrap(async (req, res) => {
return json(res, 200, { data: hit.value }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
}
- let data = await searchBirdeye(q, limit);
- if (!data) data = await searchPumpFun(q, limit);
- if (!data) {
- // No matches found is a valid, common outcome — return an empty list, not
- // an error. We only surface an error if the upstreams threw above (handled
- // by wrap()). Cache the empty result briefly to soak repeat keystrokes.
- _cache.set(key, { value: [], expiresAt: now + TTL_MS });
- return json(res, 200, { data: [] }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
- }
+ // No matches found is a valid, common outcome — searchPumpTokens returns []
+ // rather than throwing, so this is never an error path.
+ const data = await searchPumpTokens(q, limit);
if (_cache.size >= CACHE_MAX) _cache.clear();
_cache.set(key, { value: data, expiresAt: now + TTL_MS });
diff --git a/api/pump/trending.js b/api/pump/trending.js
index 033fd7976..84424a97e 100644
--- a/api/pump/trending.js
+++ b/api/pump/trending.js
@@ -13,18 +13,13 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { normalizeGatewayURL } from '../../src/ipfs.js';
+import { getTrendingSlim } from '../_lib/pump-trending.js';
-const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
-// Process-local cache. Trending shifts slowly; many tabs polling on nav into the
-// dashboard would otherwise hammer the upstreams. Warm-starts share this map.
-// `storedAt` lets us serve the value as STALE (past its TTL) when every live
-// upstream is down — a slowly-changing market feed is far better shown a few
-// minutes old than blanked out with a 502 during an upstream blip.
-let _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
// Separate cache slot for the rich (full-coin) payload — it carries far more per
-// token than the thin projection, so it must not collide with `_cache`.
+// token than the thin projection api/_lib/pump-trending.js caches, so it must
+// not collide with that cache.
let _richCache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
const TTL_MS = 30_000;
// How long a cached feed may be served as a stale fallback after every live
@@ -33,11 +28,6 @@ const STALE_MAX_MS = 10 * 60_000;
// Upstream fetch timeout. Trending is a fast feed behind a 30s cache + stale
// fallback, so a long wait buys nothing — fail fast and fall through.
const UPSTREAM_TIMEOUT_MS = 5000;
-// Birdeye circuit breaker: after a failure, skip Birdeye entirely for a cooldown
-// so an influx during a Birdeye outage stops paying the per-request timeout on
-// the way to the pump.fun fallback. Auto-recovers when the cooldown elapses.
-const BIRDEYE_COOLDOWN_MS = 60_000;
-let _birdeyeCooldownUntil = 0;
// Serve a cached feed past its TTL when live upstreams are down. Returns the
// sliced value if the slot holds enough items and is within the stale window,
@@ -48,80 +38,6 @@ function serveStale(slot, limit, now) {
return slot.value.slice(0, limit);
}
-// Primary: Birdeye trending feed. Returns null (not throws) on any failure so the
-// caller can transparently fall back.
-async function fetchBirdeye(limit) {
- if (!BIRDEYE_API_KEY) return null;
- // Circuit open: a recent Birdeye failure put it in cooldown — skip straight to
- // the fallback instead of paying the timeout again.
- if (Date.now() < _birdeyeCooldownUntil) return null;
- const url =
- `https://public-api.birdeye.so/defi/token_trending` +
- `?sort_by=rank&sort_type=asc&offset=0&limit=${limit}`;
- let upstream;
- try {
- upstream = await fetch(url, {
- headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
- });
- } catch {
- _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
- return null;
- }
- if (!upstream.ok) {
- // 429 / 5xx — trip the breaker so the next requests skip the timeout.
- _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
- return null;
- }
- const payload = await upstream.json().catch(() => null);
- const tokens = payload?.data?.tokens;
- if (!Array.isArray(tokens)) return null;
- const data = tokens
- .map((t) => ({
- mint: t.address,
- symbol: t.symbol || '?',
- name: t.name || t.symbol || '',
- logo: t.logoURI || null,
- price_usd: typeof t.price === 'number' ? t.price : null,
- rank: typeof t.rank === 'number' ? t.rank : null,
- }))
- .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
- return data.length ? data : null;
-}
-
-// Fallback: pump.fun's public frontend feed (no API key). Mapped into the exact
-// same shape so every consumer keeps working. pump.fun doesn't expose a clean
-// per-token USD price here, so price_usd is left null rather than fabricated.
-async function fetchPumpFun(limit) {
- const url = new URL('/coins', PUMP_FRONTEND_BASE);
- url.searchParams.set('offset', '0');
- url.searchParams.set('limit', String(limit));
- url.searchParams.set('sort', 'market_cap');
- url.searchParams.set('order', 'DESC');
- url.searchParams.set('includeNsfw', 'false');
- let upstream;
- try {
- upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
- } catch {
- return null;
- }
- if (!upstream.ok) return null;
- const body = await upstream.json().catch(() => null);
- const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
- if (!Array.isArray(coins)) return null;
- const data = coins
- .map((c, i) => ({
- mint: c.mint || c.address || '',
- symbol: c.symbol || '?',
- name: c.name || c.symbol || '',
- logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
- price_usd: null,
- rank: i + 1,
- }))
- .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
- return data.length ? data : null;
-}
-
// Rich variant: the full pump.fun coin objects (market cap, image, ATH, replies,
// age, socials, live flag) the 3D visualizer renders — sphere size, textures, and
// the detail panel all key off these fields, none of which survive the thin
@@ -197,27 +113,17 @@ export default wrap(async (req, res) => {
return json(res, 200, { data: richData }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
}
- if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {
- return json(res, 200, { data: _cache.value.slice(0, limit) }, {
- 'cache-control': 'public, max-age=15, s-maxage=30',
- });
- }
-
- let data = await fetchBirdeye(limit);
- if (!data) data = await fetchPumpFun(limit);
+ // Thin projection: fetch+cache+fallback lives in api/_lib/pump-trending.js,
+ // shared with the free GET /api/v1/pump/trending endpoint.
+ const { data, stale } = await getTrendingSlim(limit);
if (!data) {
- // Both live sources are down — serve the last good feed as stale so the home
- // card, communities, constellation, and visualizer keep rendering through the
- // blip instead of dead-ending on a 502. Shorter edge cache so we retry soon.
- const stale = serveStale(_cache, limit, now);
- if (stale) {
- return json(res, 200, { data: stale, stale: true }, {
- 'cache-control': 'public, max-age=10, s-maxage=20',
- });
- }
+ // Both live sources are down and no usable stale cache exists — the home
+ // card, communities, constellation, and visualizer would otherwise dead-end
+ // on a 502 during the blip; getTrendingSlim already tried the stale fallback.
return error(res, 502, 'upstream_error', 'Trending market data is temporarily unavailable');
}
-
- _cache = { value: data, storedAt: now, expiresAt: now + TTL_MS, limit };
+ if (stale) {
+ return json(res, 200, { data, stale: true }, { 'cache-control': 'public, max-age=10, s-maxage=20' });
+ }
return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
});
diff --git a/api/v1/_catalog.js b/api/v1/_catalog.js
index 94499702f..e8ef8fbe2 100644
--- a/api/v1/_catalog.js
+++ b/api/v1/_catalog.js
@@ -177,4 +177,18 @@ export const CATALOG = [
chain: 'string — "ethereum" | "solana", optional hint validated against address (auto-detected from format when omitted)',
},
},
+ {
+ id: 'v1.pump.search',
+ method: 'GET',
+ path: '/api/v1/pump/search',
+ auth: 'public',
+ summary:
+ 'Free text search over Solana pump.fun / meme tokens by name, symbol, or mint (Birdeye-first, ' +
+ 'pump.fun-fallback). The one pump.fun read with no /api/crypto/* equivalent — trending, ' +
+ 'bonding-curve progress, launches, and whale activity already ship there. No key; 60/min per IP.',
+ params: {
+ q: 'string — token name, symbol, or mint to search for (required)',
+ limit: 'number 1–20 (default 8)',
+ },
+ },
];
diff --git a/api/v1/pump/search.js b/api/v1/pump/search.js
new file mode 100644
index 000000000..7020f69e0
--- /dev/null
+++ b/api/v1/pump/search.js
@@ -0,0 +1,42 @@
+// GET /api/v1/pump/search?q=<query>&limit=8
+//
+// Free, keyless text search over Solana pump.fun / meme tokens by name,
+// symbol, or mint — the one pump.fun capability with no live equivalent
+// elsewhere in the platform's free crypto surfaces (trending, bonding-curve
+// progress, launches, and whale activity all already ship as free endpoints
+// under /api/crypto/* — see docs/crypto-api.md). This registers the same
+// Birdeye-first/pump.fun-fallback search the site's command palette already
+// uses (api/pump/search.js) under the versioned, cataloged /api/v1 surface so
+// agents can discover it via GET /api/v1.
+//
+// Both routes share one implementation — api/_lib/pump-search.js
+// `searchPumpTokens` — so this is a thin wrapper, not a fork.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { rateLimited } from '../../_lib/http.js';
+import { searchPumpTokens } from '../../_lib/pump-search.js';
+
+export default defineEndpoint({
+ name: 'v1.pump.search',
+ method: 'GET',
+ auth: 'public',
+ handler: async ({ req, res, query }) => {
+ // Dedicated per-IP budget on top of the gateway's shared apiV1 burst guard —
+ // this fans out to a real Birdeye/pump.fun upstream on every cache miss, so
+ // it caps a scripted enumeration flood the same way the sibling free reads do.
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'pump search is capped at 60 requests/min per IP');
+
+ const q = typeof query.q === 'string' ? query.q.trim().slice(0, 64) : '';
+ if (!q) fail(400, 'validation_error', 'query param "q" is required — pass a token name, symbol, or mint');
+
+ const rawLimit = Number(query.limit || '8');
+ const limit = Math.min(20, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 8));
+
+ const results = await searchPumpTokens(q, limit);
+ // A miss is a valid, common outcome — [] with 200, never a 404/500.
+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=30');
+ return { results, count: results.length, q };
+ },
+});
diff --git a/api/x402/fact-check.js b/api/x402/fact-check.js
index aa9d59e5c..9f5df2ef7 100644
--- a/api/x402/fact-check.js
+++ b/api/x402/fact-check.js
@@ -3,17 +3,26 @@
// the 2026-07 overhaul's "internal-use only" de-listing is superseded. The
// fact-checker app (src/fact-checker-app.js) and the Sheriff Boone NPC in
// /play also buy through this same route.
-// POST /api/x402/fact-check
+// POST /api/x402/fact-check — free daily lane → x402 metered overage.
//
-// Real-Time Fact Checker — paid x402 micropayment endpoint.
-// $0.10 base (100_000 atomics). Per check: generate queries, multi-source
-// search, LLM stance extraction, weighted verdict, SHA-256 attestation.
+// Real-Time Fact Checker.
+// • Free tier: 3 checks/day per IP — the REAL search+LLM chain, never a
+// degraded fake (see 00-CONTEXT.md's no-mocks rule). Response carries
+// `lane: "free"` and `free_remaining_today`.
+// • Above the free tier (quota exhausted OR an X-PAYMENT header is present)
+// the request falls through to the x402 rail: $0.10 base (100_000
+// atomics) per check on Base or Solana USDC. Response carries
+// `lane: "paid"`.
+// Per check either way: generate queries, multi-source search, LLM stance
+// extraction, weighted verdict, SHA-256 attestation.
//
-// Body: { claim: string, strictness: "high"|"medium"|"low" }
+// Body: { claim: string, strictness?: "high"|"medium"|"low", imageUrl?: string }
// Response 200: { verdict, confidence, claim, strictness, sources,
-// costBreakdown, cachedAt?, attestation }
+// costBreakdown, cachedAt?, attestation, lane, free_remaining_today? }
import { createHash } from 'crypto';
+import { wrap, error, json, readBody } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
@@ -25,6 +34,11 @@ import { imageEvidence } from '../../agents/fact-checker/src/image-evidence.js';
const ROUTE = '/api/x402/fact-check';
const CACHE_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days
+const MAX_BODY_BYTES = 32 * 1024; // claims are short text; 32KB is generous headroom
+// Kept in one place and re-exported so the /fact-check page and 402-quote copy
+// can render the real cap instead of a hardcoded, driftable number. Must match
+// limits.factCheckFreeIp's `limit` in api/_lib/rate-limit.js.
+export const FREE_DAILY_LIMIT = 3;
// ── Redis helpers ──────────────────────────────────────────────────────────────
@@ -235,15 +249,78 @@ async function runFactCheck(claim, strictness, imageUrl = null) {
return result;
}
+// Cache-checked wrapper shared by both the free and paid lanes so a claim
+// already checked (by anyone, on either lane) within the last 7 days never
+// re-runs the live chain — same idempotency guarantee both lanes get.
+async function checkClaim(claim, strictness, imageUrl) {
+ const key = cacheKey(claim, strictness, imageUrl);
+ const cached = await redisGet(key);
+ if (cached && typeof cached.verdict === 'string') {
+ return { ...cached, cachedAt: cached.cachedAt || new Date().toISOString() };
+ }
+ const result = await runFactCheck(claim, strictness, imageUrl);
+ await redisSet(key, result, CACHE_TTL_SECONDS);
+ return result;
+}
+
+// Validate + normalize the request body. Throws a { status, code, message }
+// error on anything malformed — shared by both lanes so a bad request gets
+// the identical 400 whether or not a payment would have been required.
+function parseFactCheckBody(body) {
+ const claim = String(body?.claim || '').trim();
+ if (!claim || claim.length < 5) {
+ const err = new Error('"claim" must be at least 5 characters');
+ err.status = 400;
+ err.code = 'invalid_claim';
+ throw err;
+ }
+ if (claim.length > 1000) {
+ const err = new Error('"claim" must be at most 1000 characters');
+ err.status = 400;
+ err.code = 'claim_too_long';
+ throw err;
+ }
+
+ const strictness = ['high', 'medium', 'low'].includes(body?.strictness) ? body.strictness : 'medium';
+
+ // Optional image attachment — validated at the boundary as an http(s) URL.
+ let imageUrl = null;
+ if (body?.imageUrl != null) {
+ imageUrl = String(body.imageUrl).trim();
+ if (imageUrl && (!/^https?:\/\//i.test(imageUrl) || imageUrl.length > 2048)) {
+ const err = new Error('"imageUrl" must be an http(s) URL under 2048 characters');
+ err.status = 400;
+ err.code = 'invalid_image_url';
+ throw err;
+ }
+ if (!imageUrl) imageUrl = null;
+ }
+
+ return { claim, strictness, imageUrl };
+}
+
+function parseJsonBody(buf) {
+ const raw = buf.toString('utf8');
+ try {
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ const err = new Error('Request body must be valid JSON');
+ err.status = 400;
+ err.code = 'invalid_json';
+ throw err;
+ }
+}
+
// ── Bazaar schema ──────────────────────────────────────────────────────────────
const DESCRIPTION =
- 'three.ws Real-Time Fact Checker — submit a claim and receive a ' +
- 'sourced verdict (supported/contradicted/mixed/insufficient) backed by ' +
- 'live web search and LLM analysis. Each result includes cited sources, ' +
- 'authority weights, confidence score, cost breakdown, and a SHA-256 ' +
- 'attestation. Strictness controls how aggressively low-authority sources ' +
- 'are downweighted. Price: $0.10 base per check on Base or Solana USDC.';
+ 'three.ws Real-Time Fact Checker — sourced verdicts with cryptographic attestations you can ' +
+ 'audit, backed by a published accuracy benchmark. Submit a claim and receive a sourced verdict ' +
+ '(supported/contradicted/mixed/insufficient) from live web search and LLM analysis: cited ' +
+ 'sources, authority weights, confidence score, cost breakdown, and a SHA-256 attestation. ' +
+ `${FREE_DAILY_LIMIT} free checks/day per IP (the same real chain, marked lane:"free") before ` +
+ 'the $0.10 base x402 price per check on Base or Solana USDC. Strictness controls how ' +
+ 'aggressively low-authority sources are downweighted. See /fact-check for the live benchmark.';
const INPUT_EXAMPLE = {
claim: 'The Eiffel Tower is 330 meters tall.',
@@ -297,12 +374,13 @@ const OUTPUT_EXAMPLE = {
],
costBreakdown: { searchCalls: 3, llmTokens: 1420, totalUsdc: '0.100355' },
attestation: 'sha256:abcdef1234567890...',
+ lane: 'paid',
};
const OUTPUT_SCHEMA = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'object',
- required: ['verdict', 'confidence', 'claim', 'strictness', 'sources', 'costBreakdown', 'attestation'],
+ required: ['verdict', 'confidence', 'claim', 'strictness', 'sources', 'costBreakdown', 'attestation', 'lane'],
properties: {
verdict: { type: 'string', enum: ['supported', 'contradicted', 'mixed', 'insufficient'] },
confidence: { type: 'number', minimum: 0, maximum: 1 },
@@ -346,6 +424,8 @@ const OUTPUT_SCHEMA = {
},
cachedAt: { type: 'string', format: 'date-time' },
attestation: { type: 'string' },
+ lane: { type: 'string', enum: ['free', 'paid'], description: 'Which lane served this check.' },
+ free_remaining_today: { type: 'number', description: `Present only on lane:"free" responses — free checks left today (of ${FREE_DAILY_LIMIT}).` },
},
};
@@ -368,83 +448,89 @@ const BAZAAR = {
}),
};
-// ── Endpoint ──────────────────────────────────────────────────────────────────
-
-export default paidEndpoint({
- route: ROUTE,
- method: 'POST',
- priceAtomics: 100_000, // $0.10
- networks: ['base', 'solana'],
- description: DESCRIPTION,
- bazaar: BAZAAR,
- service: withService({
- serviceName: 'three.ws Fact Checker',
- tags: ['fact-check', 'search', 'verification'],
- }),
- requiredScope: 'x402:bypass',
- accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
-
- async handler({ req }) {
- // Parse body from raw Node.js readable stream.
- const chunks = [];
- for await (const c of req) chunks.push(c);
- const rawBody = Buffer.concat(chunks).toString();
-
- let body;
- try {
- body = JSON.parse(rawBody);
- } catch {
- const err = new Error('Request body must be valid JSON');
- err.status = 400;
- err.code = 'invalid_json';
- throw err;
- }
+// ── Paid lane (x402) ─────────────────────────────────────────────────────────
+// Built once, lazily, and reused for every over-quota / already-paying request
+// (mirrors api/v1/ai/asr.js's free-lane-then-x402 shape).
- const claim = String(body?.claim || '').trim();
- if (!claim || claim.length < 5) {
- const err = new Error('"claim" must be at least 5 characters');
- err.status = 400;
- err.code = 'invalid_claim';
- throw err;
- }
- if (claim.length > 1000) {
- const err = new Error('"claim" must be at most 1000 characters');
- err.status = 400;
- err.code = 'claim_too_long';
- throw err;
- }
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: 100_000, // $0.10
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Fact Checker',
+ tags: ['fact-check', 'search', 'verification'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ // The free-lane gate above already buffered the body once (req._factCheckBody);
+ // a direct paid call (X-PAYMENT present on the first request) reads it fresh.
+ const buf = req._factCheckBody ?? (await readBody(req, MAX_BODY_BYTES));
+ const body = parseJsonBody(buf);
+ const { claim, strictness, imageUrl } = parseFactCheckBody(body);
+ const result = await checkClaim(claim, strictness, imageUrl);
+ return { ...result, lane: 'paid' };
+ },
+ });
+ return _paid;
+}
- const strictness = ['high', 'medium', 'low'].includes(body?.strictness)
- ? body.strictness
- : 'medium';
-
- // Optional image attachment — validated at the boundary as an http(s) URL.
- let imageUrl = null;
- if (body?.imageUrl != null) {
- imageUrl = String(body.imageUrl).trim();
- if (imageUrl && (!/^https?:\/\//i.test(imageUrl) || imageUrl.length > 2048)) {
- const err = new Error('"imageUrl" must be an http(s) URL under 2048 characters');
- err.status = 400;
- err.code = 'invalid_image_url';
- throw err;
- }
- if (!imageUrl) imageUrl = null;
- }
+// ── Entry point: free daily quota → x402 fall-through ────────────────────────
- // Idempotency cache — 7-day TTL. Shape-check the hit: records written by
- // the old envelope-body redisSet parse to `{value, ex}` and must be
- // treated as misses, not served as verdicts.
- const key = cacheKey(claim, strictness, imageUrl);
- const cached = await redisGet(key);
- if (cached && typeof cached.verdict === 'string') {
- return { ...cached, cachedAt: cached.cachedAt || new Date().toISOString() };
- }
+export default wrap(async function handler(req, res) {
+ if (req.method !== 'POST') return paidHandler()(req, res); // let the paid rail's own 405 speak
- const result = await runFactCheck(claim, strictness, imageUrl);
+ // Buffer the body once; the paid rail re-reads the same bytes
+ // (req._factCheckBody) so the stream is never consumed twice.
+ let buf;
+ try {
+ buf = await readBody(req, MAX_BODY_BYTES);
+ } catch (e) {
+ return error(res, e?.status || 413, e?.code || 'payload_too_large', e?.message || `request body exceeds the ${MAX_BODY_BYTES}-byte limit`);
+ }
+ req._factCheckBody = buf;
- // Persist to cache (fire-and-forget on failure).
- await redisSet(key, result, CACHE_TTL_SECONDS);
+ // A payment header means the caller is already on the paid rail.
+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);
+ if (paymentPresent) return paidHandler()(req, res);
- return result;
- },
+ // Parse/validate against the boundary so genuinely broken input never
+ // becomes a payment prompt or burns a free-quota slot.
+ let body;
+ try {
+ body = parseJsonBody(buf);
+ } catch (e) {
+ return error(res, e.status || 400, e.code || 'invalid_json', e.message);
+ }
+ let parsed;
+ try {
+ parsed = parseFactCheckBody(body);
+ } catch (e) {
+ return error(res, e.status || 400, e.code || 'bad_request', e.message);
+ }
+
+ // Free daily quota (per IP). Exhausted → the x402 402 challenge.
+ const rl = await limits.factCheckFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ try {
+ const result = await checkClaim(parsed.claim, parsed.strictness, parsed.imageUrl);
+ return json(
+ res,
+ 200,
+ { ...result, lane: 'free', free_remaining_today: Math.max(0, rl.remaining) },
+ { 'cache-control': 'no-store' },
+ );
+ } catch (e) {
+ return error(res, e?.status || 502, e?.code || 'provider_error', e?.message || 'fact-check failed');
+ }
});
+
+export { parseFactCheckBody as _parseFactCheckBody, checkClaim as _checkClaim };
diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.js
index 5bb393aaa..6b0ac29e1 100644
--- a/api/x402/pump-agent-audit.js
+++ b/api/x402/pump-agent-audit.js
@@ -689,18 +689,17 @@ const whaleEndpoint = paidEndpoint({
export default function pumpAgentAuditRouter(req, res) {
const httpMethod = String(req.method || 'GET').toUpperCase();
if (httpMethod === 'POST') {
- // Buffer the body once so readJsonBody inside the paidEndpoint handler can
- // drain it as if the stream was never touched (same idiom as agent-reputation.js).
- return new Promise((resolve) => {
- const chunks = [];
- req.on('data', (c) => chunks.push(c));
- req.on('end', () => {
- const raw = Buffer.concat(chunks);
+ // Buffer the body once (via the shared readBody, which prefers the
+ // pre-parsed req.rawBody/req.body the Cloud Run server already captured)
+ // so readJsonBody inside the paidEndpoint handler can drain it as if the
+ // stream was never touched. Re-reading the raw stream directly here (the
+ // old implementation) hangs forever once Express has drained it.
+ return readBody(req, 1_000_000)
+ .then((raw) => {
req[Symbol.asyncIterator] = async function* () { yield raw; };
- resolve(whaleEndpoint(req, res));
- });
- req.on('error', () => resolve(whaleEndpoint(req, res)));
- });
+ })
+ .catch(() => {})
+ .then(() => whaleEndpoint(req, res));
}
if (httpMethod === 'OPTIONS') {
const requested = String(req.headers['access-control-request-method'] || '').toUpperCase();
diff --git a/apps-sdk/embodiment/chain-visuals.js b/apps-sdk/embodiment/chain-visuals.js
new file mode 100644
index 000000000..260ab50a4
--- /dev/null
+++ b/apps-sdk/embodiment/chain-visuals.js
@@ -0,0 +1,63 @@
+/**
+ * Chain-state → body visuals — the pure mapping between a persona's on-chain
+ * identity (api/_lib/persona-wallet.js#getPersonaIdentity) and what the
+ * EmbodimentStage/overlay render. No DOM, no Three.js, no network: a
+ * deterministic function of the identity object so it is unit-testable on its
+ * own and reusable by both the WebGL stage (aura/muted state) and the DOM
+ * overlay (badges/nameplate).
+ *
+ * Design (per prompt 17 — "the avatar IS the wallet"):
+ * - reputation tier → an aura color + intensity ringing the body
+ * - holdings tier → a cosmetic badge chip (bronze/silver/gold/platinum)
+ * - low/zero balance → a muted state (desaturated lighting, dimmed aura)
+ * - verified name → a nameplate badge
+ * Every mapping has a defined value for every tier, INCLUDING the degraded /
+ * unranked / none case, so a failed or empty read still renders a designed
+ * state — never a blank or crashed body.
+ */
+
+// Reputation tier → aura. Colors read: grey (unranked) → amber (emerging) →
+// teal (trusted) → violet (eminent) → red (disputed, a real trust signal).
+const AURA_BY_REPUTATION_TIER = Object.freeze({
+ unranked: { color: '#5b6472', intensity: 0.12, label: 'Unranked' },
+ emerging: { color: '#fbbf24', intensity: 0.35, label: 'Emerging' },
+ trusted: { color: '#5eead4', intensity: 0.65, label: 'Trusted' },
+ eminent: { color: '#a78bfa', intensity: 1.0, label: 'Eminent' },
+ disputed: { color: '#fb7185', intensity: 0.5, label: 'Disputed' },
+});
+
+// Holdings tier → cosmetic badge chip.
+const COSMETIC_BY_HOLDINGS_TIER = Object.freeze({
+ none: { glyph: '·', color: '#5b6472', label: 'No holdings' },
+ bronze: { glyph: '●', color: '#c2793b', label: 'Bronze holdings' },
+ silver: { glyph: '●', color: '#c3c9d6', label: 'Silver holdings' },
+ gold: { glyph: '★', color: '#f4c542', label: 'Gold holdings' },
+ platinum: { glyph: '✦', color: '#9fe8ff', label: 'Platinum holdings' },
+});
+
+/**
+ * Map a persona identity (or the visual sub-object already computed by
+ * getPersonaIdentity) onto the concrete visuals the viewer renders.
+ * @param {object} identity — getPersonaIdentity() result, or its `.visual` field
+ * @returns {{aura:object, cosmetic:object, muted:boolean, nameplate:(string|null)}}
+ */
+export function mapChainStateToVisuals(identity) {
+ const v = identity?.visual || identity || {};
+ const reputationTier = AURA_BY_REPUTATION_TIER[v.reputation_tier] ? v.reputation_tier : 'unranked';
+ const holdingsTier = COSMETIC_BY_HOLDINGS_TIER[v.holdings_tier] ? v.holdings_tier : 'none';
+ const muted = !!v.muted;
+
+ const aura = { ...AURA_BY_REPUTATION_TIER[reputationTier], tier: reputationTier };
+ // Muted overrides intensity toward near-zero regardless of reputation — a
+ // broke wallet reads as dim even if it is well-reputed.
+ if (muted) aura.intensity = Math.min(aura.intensity, 0.08);
+
+ return {
+ aura,
+ cosmetic: { ...COSMETIC_BY_HOLDINGS_TIER[holdingsTier], tier: holdingsTier },
+ muted,
+ nameplate: v.verified_name || null,
+ };
+}
+
+export { AURA_BY_REPUTATION_TIER, COSMETIC_BY_HOLDINGS_TIER };
diff --git a/apps-sdk/embodiment/embodiment-stage.js b/apps-sdk/embodiment/embodiment-stage.js
index b04ce15fa..b5eb65da7 100644
--- a/apps-sdk/embodiment/embodiment-stage.js
+++ b/apps-sdk/embodiment/embodiment-stage.js
@@ -28,7 +28,7 @@
import {
Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, DirectionalLight,
- PMREMGenerator, Box3, Vector3, Group, Color,
+ PMREMGenerator, Box3, Vector3, Group, Color, RingGeometry, MeshBasicMaterial, Mesh,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
@@ -43,6 +43,7 @@ import { inspectRig, decideRigMode } from '../../src/embodiment/rig-mode.js';
import { expressionForText, expressionFor } from '../../src/embodiment/emotion.js';
import { TextVisemeEnvelope, estimateSpeechDuration } from '../../src/embodiment/text-visemes.js';
import { FaceExpression } from '../../src/embodiment/face-expression.js';
+import { mapChainStateToVisuals } from './chain-visuals.js';
const REDUCED_MOTION =
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -112,13 +113,18 @@ export class EmbodimentStage {
this.renderer.domElement.setAttribute('aria-label', 'Interactive 3D agent');
this.renderer.domElement.setAttribute('role', 'img');
- this.scene.add(new AmbientLight(0xffffff, 0.6));
- const key = new DirectionalLight(0xffffff, 1.6);
- key.position.set(2, 4, 3);
- this.scene.add(key);
- const rim = new DirectionalLight(0x99bbff, 0.5);
- rim.position.set(-3, 2, -2);
- this.scene.add(rim);
+ this.ambient = new AmbientLight(0xffffff, 0.6);
+ this.scene.add(this.ambient);
+ this.keyLight = new DirectionalLight(0xffffff, 1.6);
+ this.keyLight.position.set(2, 4, 3);
+ this.scene.add(this.keyLight);
+ this.rimLight = new DirectionalLight(0x99bbff, 0.5);
+ this.rimLight.position.set(-3, 2, -2);
+ this.scene.add(this.rimLight);
+ // Base light intensities, so the muted chain-state can dim relative to the
+ // designed baseline (and un-mute can restore it exactly) instead of
+ // compounding repeated multiplications across calls.
+ this._baseLightIntensity = { ambient: this.ambient.intensity, key: this.keyLight.intensity, rim: this.rimLight.intensity };
const pmrem = new PMREMGenerator(this.renderer);
this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
@@ -135,6 +141,18 @@ export class EmbodimentStage {
this.root = new Group();
this.scene.add(this.root);
+
+ // The chain-state aura: a flat emissive ring at the avatar's feet, colored
+ // and intensity-scaled by reputation tier (see chain-visuals.js). Hidden
+ // until setChainState() is called with a real identity read, so a persona
+ // with no wallet binding renders exactly as before.
+ this._auraMat = new MeshBasicMaterial({ color: 0x5b6472, transparent: true, opacity: 0, depthWrite: false });
+ this._auraRing = new Mesh(new RingGeometry(0.42, 0.56, 48), this._auraMat);
+ this._auraRing.rotation.x = -Math.PI / 2;
+ this._auraRing.position.y = 0.01;
+ this._auraRing.visible = false;
+ this.root.add(this._auraRing);
+ this._chainVisuals = null;
}
_resize() {
@@ -270,6 +288,43 @@ export class EmbodimentStage {
this.controls.update();
}
+ // ── on-chain identity → visuals ───────────────────────────────────────────
+
+ /**
+ * Drive the body's appearance from a persona's live on-chain identity
+ * (api/_lib/persona-wallet.js#getPersonaIdentity, or its already-computed
+ * `.visual` field). Pure mapping (chain-visuals.js) → three concrete effects:
+ * - an aura ring at the feet, colored + intensity-scaled by reputation tier
+ * - the whole scene dims toward the muted baseline on a low/zero balance
+ * - the resolved cosmetic tier + nameplate are returned for the host page's
+ * DOM overlay (apps-sdk/embodiment/overlay.js#setIdentity) to render as
+ * badges — geometry it doesn't own.
+ * Never throws: called with `null`/`undefined` (identity read failed or was
+ * never requested) it clears back to the undecorated baseline, which is
+ * itself a designed state, not an error.
+ * @param {object|null} identity
+ * @returns {{aura:object, cosmetic:object, muted:boolean, nameplate:(string|null)}}
+ */
+ setChainState(identity) {
+ const visuals = mapChainStateToVisuals(identity || {});
+ this._chainVisuals = visuals;
+
+ if (this._auraRing && this._auraMat) {
+ this._auraMat.color.set(visuals.aura.color);
+ this._auraMat.opacity = Math.max(0, Math.min(1, visuals.aura.intensity));
+ this._auraRing.visible = visuals.aura.intensity > 0.01;
+ }
+
+ // Muted balance dims the whole stage toward a designed low-key look —
+ // never fully dark (the body must stay legible), just visibly subdued.
+ const dim = visuals.muted ? 0.45 : 1;
+ if (this.ambient) this.ambient.intensity = this._baseLightIntensity.ambient * dim;
+ if (this.keyLight) this.keyLight.intensity = this._baseLightIntensity.key * dim;
+ if (this.rimLight) this.rimLight.intensity = this._baseLightIntensity.rim * dim;
+
+ return visuals;
+ }
+
// ── conversational states ─────────────────────────────────────────────────
/** The body is attending to the user (between the user typing and a reply). */
@@ -453,6 +508,8 @@ export class EmbodimentStage {
this._endSpeech(false);
this.mouth.dispose?.();
if (this._model) this._disposeObject(this._model);
+ this._auraRing?.geometry?.dispose?.();
+ this._auraMat?.dispose?.();
this._envTex?.dispose?.();
this.controls?.dispose?.();
this.renderer?.dispose?.();
diff --git a/apps-sdk/embodiment/overlay.js b/apps-sdk/embodiment/overlay.js
index 220f923e1..d0cbb189e 100644
--- a/apps-sdk/embodiment/overlay.js
+++ b/apps-sdk/embodiment/overlay.js
@@ -41,6 +41,19 @@ const CSS = `
@keyframes emb-pulse{0%,100%{transform:scale(1);opacity:1}50%{transform:scale(1.45);opacity:.55}}
.emb__note{position:absolute;left:14px;bottom:12px;font-size:11px;color:#8b8b98;background:rgba(14,14,20,.6);
padding:4px 9px;border-radius:8px;border:1px solid rgba(255,255,255,.08);max-width:calc(100% - 28px)}
+.emb__identity{position:absolute;right:14px;top:12px;display:flex;align-items:center;gap:6px;
+ padding:6px 10px;border-radius:999px;background:rgba(14,14,20,.72);
+ border:1px solid rgba(255,255,255,.1);backdrop-filter:blur(10px);box-shadow:0 6px 22px rgba(0,0,0,.38);
+ max-width:calc(100% - 28px);transition:opacity .25s}
+.emb__identity[hidden]{display:none!important}
+.emb__id-aura{width:8px;height:8px;border-radius:50%;flex:none;background:var(--emb-aura,#5b6472);
+ box-shadow:0 0 8px var(--emb-aura,#5b6472)}
+.emb__id-badge{font-size:11px;font-weight:700;color:var(--emb-cosmetic,#c2793b)}
+.emb__id-name{font-size:11px;font-weight:600;color:#5eead4;border-left:1px solid rgba(255,255,255,.14);padding-left:6px;
+ display:flex;align-items:center;gap:3px}
+.emb__id-name::before{content:'✓';font-size:10px}
+.emb__identity--muted{opacity:.55}
+.emb__id-muted-note{font-size:10px;color:#8b8b98;font-style:italic}
.emb__skeleton{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
background:radial-gradient(120% 120% at 50% 0%,#1a1a24 0%,#0c0c12 70%)}
.emb__skel-body{width:90px;height:200px;border-radius:40px 40px 18px 18px;
@@ -96,6 +109,12 @@ export function mountOverlay(container, opts = {}) {
<span class="emb__emotion" data-emotion hidden></span>
</div>
<div class="emb__note" data-note hidden></div>
+ <div class="emb__identity" data-identity hidden>
+ <span class="emb__id-aura" data-id-aura title="Reputation"></span>
+ <span class="emb__id-badge" data-id-badge></span>
+ <span class="emb__id-name" data-id-name hidden></span>
+ <span class="emb__id-muted-note" data-id-muted hidden>low balance</span>
+ </div>
<div class="emb__error" data-error hidden>
<h3>This avatar didn't load</h3>
<p data-error-msg>The 3D model couldn't be reached. Check the link and try again.</p>
@@ -108,6 +127,8 @@ export function mountOverlay(container, opts = {}) {
skel: $('[data-skel]'), plate: $('[data-plate]'), dot: $('[data-dot]'),
name: $('[data-name]'), state: $('[data-state]'), emotion: $('[data-emotion]'),
note: $('[data-note]'), error: $('[data-error]'), errorMsg: $('[data-error-msg]'), retry: $('[data-retry]'),
+ identity: $('[data-identity]'), idAura: $('[data-id-aura]'), idBadge: $('[data-id-badge]'),
+ idName: $('[data-id-name]'), idMuted: $('[data-id-muted]'),
};
els.retry.addEventListener('click', () => opts.onRetry?.());
diff --git a/data/pages.json b/data/pages.json
index 66750a6eb..8351aff86 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -350,6 +350,14 @@
"changefreq": "weekly",
"added": "2026-06-04"
},
+ {
+ "path": "/restyle",
+ "title": "Restyle Studio — material presets & variants",
+ "description": "Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.",
+ "priority": 0.8,
+ "changefreq": "monthly",
+ "added": "2026-07-08"
+ },
{
"path": "/avatar-engines",
"title": "Avatar Engines Atlas",
diff --git a/package.json b/package.json
index e48b46df7..d2bfc97a4 100644
--- a/package.json
+++ b/package.json
@@ -82,7 +82,8 @@
"packages/loom-mcp",
"walk-sdk",
"tour-sdk",
- "packages/alibaba-cloud-mcp"
+ "packages/alibaba-cloud-mcp",
+ "packages/tool-sdk"
],
"main": "src/app.js",
"browserslist": [
diff --git a/packages/tool-sdk/README.md b/packages/tool-sdk/README.md
new file mode 100644
index 000000000..5e25a05b5
--- /dev/null
+++ b/packages/tool-sdk/README.md
@@ -0,0 +1,231 @@
+# @three-ws/tool-sdk
+
+Typed tool authoring for three.ws MCP servers. Every one of the 38 MCP servers
+in this repo (`mcp-server/`, `packages/*-mcp/`) currently declares tools by
+hand: a name, a description, a hand-maintained JSON-Schema (or Zod-shape)
+parameter list, and a handler — with validation and error wrapping
+re-implemented per server. `@three-ws/tool-sdk` gives that authoring layer a
+single, typed home:
+
+- **`defineTool`** — declare a tool's identity, API surface (Zod schemas), and
+ **permission manifest** once. JSON Schema for each API is derived from the
+ Zod schema automatically.
+- **`defineExecutor`** — wire a typed implementation map onto a tool. Every
+ call is routed through one `invoke(apiName, params, ctx)` entry point that
+ validates params, enforces the declared rate limit, and normalizes both
+ success and failure into one result shape.
+- **`toMcpTools`** — adapt a defined tool + executor into the exact
+ registration shape this repo's MCP servers already use
+ (`{ name, title, description, inputSchema, annotations, handler }`, one per
+ declared API), so adoption is a single call.
+
+Ported from the owner's SperaxOS `@sperax/plugin-sdk` (`defineTool.ts` +
+`defineExecutor.ts`), rewritten from TypeScript to plain ESM + JSDoc to match
+this repo's other JS packages, and re-scoped from a chat-UI plugin manifest
+(`BuiltinToolManifest`, LLM system-role text, marketplace category) to a
+portable MCP tool manifest with an explicit **permission model** (network
+allowlist, rate limit, wallet access) — the piece SperaxOS's chat-app runtime
+didn't need but a standalone MCP server does.
+
+> **`defineRenderer.ts` was intentionally not ported.** The reference SDK's
+> third piece renders a custom React component for a tool's result inside
+> SperaxOS's chat UI. three.ws's MCP servers are headless (stdio/HTTP JSON-RPC,
+> no in-repo chat renderer to plug into), so there is nothing here for a
+> renderer to attach to. If a three.ws surface ever needs to render a tool
+> result as a custom UI component, `defineRenderer` should be ported into
+> *that* surface's own package, not into this transport-agnostic SDK.
+
+## Install / import
+
+Internal workspace package (`"private": true`, not published to npm) — import
+it by name from anywhere in the monorepo:
+
+```js
+import { defineTool, defineExecutor, toMcpTools, guardedFetch, z } from '@three-ws/tool-sdk';
+```
+
+A package that consumes it locally needs a `file:` dependency pointing at this
+package (npm workspaces resolves it automatically once both packages are
+listed in the root `package.json` `workspaces` array; see
+[Consuming from a package that also ships to npm](#consuming-from-a-package-that-also-ships-to-npm)
+for the one caveat that matters before you publish).
+
+## Quick start — full runnable example
+
+```js
+import { defineTool, defineExecutor, toMcpTools, z } from '@three-ws/tool-sdk';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+// 1. Declare identity, API surface, and permissions once.
+const priceTool = defineTool({
+ id: 'my-org-price-feed',
+ title: 'My Price Feed',
+ description: 'Fetches live token prices from My API.',
+ version: '1.0.0',
+ permissions: {
+ network: ['api.example.com'], // guardedFetch may only reach this host
+ rateLimit: { calls: 30, perSeconds: 60 }, // enforced automatically by the executor
+ wallet: false,
+ },
+ apis: [
+ {
+ name: 'getPrice',
+ description: 'Get the current USD price for a token symbol.',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ parameters: z.object({
+ symbol: z.string().min(1).describe('Token ticker, e.g. "ETH"'),
+ }),
+ },
+ ],
+});
+
+// 2. Wire an implementation. Return plain data — the executor wraps it into
+// { success: true, content, state } and catches thrown errors for you.
+const priceExecutor = defineExecutor(priceTool, {
+ async getPrice({ symbol }, ctx) {
+ const fetchGuarded = guardedFetch(priceTool.manifest.permissions);
+ const res = await fetchGuarded(`https://api.example.com/v1/price/${symbol}`);
+ const data = await res.json();
+ return { symbol, price: data.price };
+ },
+});
+
+// 3. Adapt into MCP tool registrations — one call, one tool per declared API.
+const server = new McpServer({ name: 'price-feed-mcp', version: '1.0.0' }, { capabilities: { tools: {} } });
+for (const def of toMcpTools(priceTool, priceExecutor)) {
+ server.registerTool(
+ def.name,
+ { title: def.title, description: def.description, inputSchema: def.inputSchema, annotations: def.annotations },
+ def.handler, // throws on failure, returns content on success — matches every hand-written tool in this repo
+ );
+}
+
+await server.connect(new StdioServerTransport());
+```
+
+Run it, then call `getPrice` from any MCP client (or `npx -y
+@modelcontextprotocol/inspector node your-server.js`):
+
+```jsonc
+> { "symbol": "ETH" }
+{ "symbol": "ETH", "price": 3421.09 }
+```
+
+## API
+
+### `defineTool(config)`
+
+| Field | Required | Description |
+|---|---|---|
+| `id` | yes | Unique identifier, e.g. `"my-org-price-feed"`. |
+| `title` | yes | Display name. Also the per-API default `title`. |
+| `description` | yes | Short description of the tool as a whole. Also the per-API default `description`. |
+| `version` | yes | Semantic version, e.g. `"1.0.0"`. |
+| `permissions` | no | `{ network?: string[], rateLimit?: { calls, perSeconds }, wallet?: boolean }` — see [Permission model](#permission-model). |
+| `apis` | yes | Non-empty array of `{ name, description, parameters, title?, annotations? }`. `parameters` must be a `z.object({...})` schema. |
+
+Returns `{ manifest, _apis, _config }`. `manifest` is the JSON-Schema-bearing,
+serializable form (`{ id, title, description, version, permissions, apis: [{ name, title, description, parameters }] }`)
+— safe to log, diff, or ship to a registry. `_apis` keeps the original Zod
+schema per API for `defineExecutor` and `toMcpTools` to consume.
+
+Throws a `TypeError` synchronously on a missing required field, a duplicate
+API name, or an API whose `parameters` isn't a Zod schema — tool definitions
+fail fast at module-load time, not at first invocation.
+
+### `defineExecutor(tool, implementation)`
+
+`implementation` is a `{ [apiName]: (params, ctx?) => Promise<*> | * }` map.
+Each handler may return:
+
+- **Plain data** — wrapped automatically into `{ success: true, content: data, state: data }`.
+- **A full result envelope** (`{ success, content, state }` or `{ success, error }`) — passed through unchanged, for handlers that need `content` (rendered text) and `state` (structured data) to differ.
+
+Returns `{ id, getApiNames(), hasApi(name), invoke(apiName, params, ctx?) }`.
+`invoke` never throws — every outcome is a `ToolResult`:
+
+```ts
+type ToolResult =
+ | { success: true, content: any, state: any }
+ | { success: false, error: { message: string, code?: string, issues?: unknown, body?: unknown }, content?: string };
+```
+
+Before calling your handler, `invoke` runs, in order:
+
+1. **API existence** — unknown `apiName` → `{ success: false, error: { code: 'API_NOT_FOUND' } }`.
+2. **Implementation presence** → `{ success: false, error: { code: 'METHOD_NOT_IMPLEMENTED' } }`.
+3. **Rate limit** (if `permissions.rateLimit` is declared) → `{ success: false, error: { code: 'RATE_LIMITED' } }`.
+4. **Zod validation** of `params` against the API's schema → `{ success: false, error: { code: 'INVALID_PARAMS', issues } }`.
+5. **Your handler**, wrapped in try/catch. A thrown error becomes `{ success: false, error: { message, code: error.code }, content: '<id>.<api> failed: <message>' }`.
+
+### `toMcpTools(tool, executor)`
+
+Returns one entry per declared API:
+
+```ts
+{
+ name: string,
+ title: string,
+ description: string,
+ inputSchema: Record<string, ZodTypeAny>, // raw Zod shape — what McpServer.registerTool expects, NOT JSON Schema
+ annotations: object, // per-API annotations, or a safe { readOnlyHint: false, idempotentHint: false, openWorldHint: true } default
+ handler: (args, extra?) => Promise<any>, // returns result.content on success, THROWS on failure
+}
+```
+
+This is the exact shape `packages/naming-mcp/src/tools/*.js` hand-writes and
+`packages/naming-mcp/src/index.js` feeds straight into `server.registerTool(name,
+{ title, description, inputSchema, annotations }, handler)`. The handler
+throws instead of returning a `{ success: false }` envelope because every
+existing MCP server in this repo wraps tool handlers in its own
+`try { ... } catch (err) { return { content: [...], isError: true } }` — see
+`packages/naming-mcp/src/index.js`'s `buildServer()`.
+
+## Permission model
+
+`permissions` is declared once, on the tool, and applies to every API on it:
+
+| Field | Enforcement |
+|---|---|
+| `network: string[]` | **Enforced.** `guardedFetch(permissions)` returns a `fetch`-compatible function that throws `{ code: 'NETWORK_NOT_ALLOWED' }` for any hostname not in the list. **Deny-by-default**: an empty/omitted `network` list means `guardedFetch` refuses every host. Exact hostname match only — no wildcards. |
+| `rateLimit: { calls, perSeconds }` | **Enforced.** `defineExecutor` runs an in-memory token-bucket limiter per API name automatically; no extra wiring needed. Also exported standalone as `createRateLimiter(rateLimit)` for use outside an executor. |
+| `wallet: boolean` | **Declarative only.** The SDK cannot grant or scope wallet access — that stays with whatever host constructs the executor's `ctx` (e.g. a signer-bearing runtime deciding whether to populate `ctx.wallet` based on this flag). |
+
+`guardedFetch` is opt-in inside your implementation — it does not silently
+replace the global `fetch`. Use it for calls you want the permission manifest
+to actually govern; use a bespoke client (like `packages/naming-mcp`'s
+`apiRequest`, which layers its own abort-timeout handling) where you need
+behavior `guardedFetch` doesn't provide.
+
+## Consuming from a package that also ships to npm
+
+`@three-ws/tool-sdk` is `"private": true` and is never published. Most
+`packages/*-mcp` servers (including `naming-mcp`) **are** published
+standalone to npm (`npx @three-ws/naming-mcp`, etc.). A published package that
+takes a hard `dependencies` entry on this SDK will fail to install for
+external consumers, because npm cannot resolve an unpublished private
+package from the registry.
+
+For **in-monorepo development and testing** this is not a problem: a `file:`
+dependency (`"@three-ws/tool-sdk": "file:../tool-sdk"`) resolves correctly for
+every local `npm install`/`npm test` run, which is what
+`packages/naming-mcp/src/tools/sns-resolve.js` uses as this package's
+proof-of-port. Before that server's *next npm publish*, either (a) publish
+`@three-ws/tool-sdk` itself, (b) bundle the two files it actually uses at
+build time, or (c) inline the thin adapter call for that one file. This is a
+known, disclosed follow-up — not a blocker for using the SDK inside the
+monorepo today.
+
+## Test
+
+```bash
+npx vitest run packages/tool-sdk
+```
+
+26 tests cover: Zod→JSON-Schema conversion, permission normalization,
+param-validation failure shape, executor success/error wrapping (including
+pass-through of a full result envelope), the in-memory rate-limit bucket
+(fake timers), `guardedFetch` allow/deny (including deny-by-default), and the
+`toMcpTools` adapter's output shape against a fixture of
+`packages/naming-mcp`'s current hand-written registration format.
diff --git a/pages/restyle.html b/pages/restyle.html
index 1a8096188..6b40b66ae 100644
--- a/pages/restyle.html
+++ b/pages/restyle.html
@@ -112,9 +112,6 @@
<div class="rs-spinner" aria-hidden="true"></div>
<div>Loading model…</div>
</div>
- <div class="rs-overlay" id="empty" hidden>
- <div>Drop a <strong>.glb</strong> here, upload one, or paste a model URL to start.</div>
- </div>
<div class="rs-overlay" id="error" hidden>
<div id="error-msg">That model could not be loaded.</div>
<button class="rs-btn" id="retry">Load the sample model</button>
diff --git a/prompts/roadmap/_generated/06/restyle-chrome.png b/prompts/roadmap/_generated/06/restyle-chrome.png
new file mode 100644
index 000000000..53ddc43a8
Binary files /dev/null and b/prompts/roadmap/_generated/06/restyle-chrome.png differ
diff --git a/prompts/roadmap/_generated/06/restyle-gold.png b/prompts/roadmap/_generated/06/restyle-gold.png
new file mode 100644
index 000000000..f58c2b0b8
Binary files /dev/null and b/prompts/roadmap/_generated/06/restyle-gold.png differ
diff --git a/prompts/store-submissions/_generated/mcp-listing-source.json b/prompts/store-submissions/_generated/mcp-listing-source.json
index a89842bd3..4cace1a1b 100644
--- a/prompts/store-submissions/_generated/mcp-listing-source.json
+++ b/prompts/store-submissions/_generated/mcp-listing-source.json
@@ -122,8 +122,8 @@
"transport": "streamable-http",
"connect": "https://three.ws/api/mcp-studio",
"npmPackage": null,
- "version": "1.0.0",
- "description": "Free text/image → 3D. Five tools, no auth, no payment: forge_free (text → textured GLB), text_to_avatar (text/image → avatar), mesh_forge (art-directed mesh), rig_mesh (auto-rig a GLB for animation), forge_avatar (one-call text → rigged avatar). Results render in an interactive viewer.",
+ "version": "1.0.1",
+ "description": "Free text/image → 3D: generate, rig, avatar-ify, and conversationally refine GLB models, plus persistent lip-syncing agent personas. No auth, no payment, nine tools.",
"tagline": "Free text/image → 3D. Five tools, no auth, no payment — forge meshes and rigged avatars on the house.",
"category": "3d",
"tags": [
diff --git a/prompts/store-submissions/_generated/mcp-registry-republish.sh b/prompts/store-submissions/_generated/mcp-registry-republish.sh
index eb5994a7c..e05864c6b 100644
--- a/prompts/store-submissions/_generated/mcp-registry-republish.sh
+++ b/prompts/store-submissions/_generated/mcp-registry-republish.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Republish stale/new three.ws MCP servers to the official MCP registry.
-# GENERATED 2026-07-07 by build-registry-republish.mjs — regenerate after any manifest bump.
+# GENERATED 2026-07-08 by build-registry-republish.mjs — regenerate after any manifest bump.
# DO NOT run unattended. A human must be logged in and review each publish.
# 30 servers need a republish; 12 are already current.
set -euo pipefail
@@ -98,7 +98,7 @@ mcp-publisher publish "packages/vision-mcp/server.json"
# io.github.nirholas/x402-mcp: registry 0.1.0 -> local 0.2.1 [STALE]
mcp-publisher publish "packages/x402-mcp/server.json"
-# io.github.nirholas/threews-3d-studio-free: registry — -> local 1.0.0 [NEW]
+# io.github.nirholas/threews-3d-studio-free: registry — -> local 1.0.1 [NEW]
mcp-publisher publish "server-studio.json"
# 3. Verify all versions match the manifests:
diff --git a/public/changelog.xml b/public/changelog.xml
index a4da4fa8c..84d0924f4 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -70,6 +70,14 @@
<category>launch</category>
<description>Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.</description>
</item>
+ <item>
+ <title>Restyle Studio — material presets &amp; variants</title>
+ <link>https://three.ws/restyle</link>
+ <guid isPermaLink="false">2026-07-08:Restyle Studio — material presets &amp; variants</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.</description>
+ </item>
<item>
<title>Stablecoins Market Cap &amp; Peg Health</title>
<link>https://three.ws/stablecoins</link>
@@ -102,6 +110,14 @@
<category>feature</category>
<description>New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest &quot;coming soon&quot; instead of a dead link until it has.</description>
</item>
+ <item>
+ <title>Fixed: the &quot;View it&quot; link on every generated 3D model now opens a real viewer</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-08:Fixed: the &quot;View it&quot; link on every generated 3D model now opens a real viewer</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The viewer link returned with every generated model (/viewer?src=…) previously returned a 404. It now opens a polished, interactive 3D viewer — orbit, zoom, AR on mobile, one-tap GLB download — with designed loading, empty, and error states. This affects every model made through the 3D Studio, in chat or on the web.</description>
+ </item>
<item>
<title>Give your agent a 3D body in one call — the new Embodiment endpoint</title>
<link>https://three.ws/docs/embody</link>
@@ -126,6 +142,14 @@
<category>feature</category>
<description>GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain.</description>
</item>
+ <item>
+ <title>New guide: BNB Chain payments (MPP) and gasless sends</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-08:New guide: BNB Chain payments (MPP) and gasless sends</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>docs</category>
+ <description>A zero-context developer guide covering how to pay three.ws endpoints over MPP on BNB Chain, how our agents pay MPP endpoints, and how BNB Chain's block-level gas sponsorship (MegaFuel) lets a plain wallet send a transaction with zero gas — with an honest self-pay fallback for when sponsorship isn't available. Includes a wire-level bridge spec pinning how x402 and MPP map to each other.</description>
+ </item>
<item>
<title>New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana</title>
<link>https://three.ws/changelog</link>
@@ -134,6 +158,14 @@
<category>sdk</category>
<description>Added @three-ws/defi-utils, a zero-dependency internal package with chain IDs, native-token symbols, common token addresses (including SPA and USDs on Arbitrum), and minimal ERC-20 ABI fragments for nine EVM chains, plus a Solana extension (SOL/USDC/$THREE mint resolution and base58 address validation). Also ships address and amount validators and USD/percent/token-amount formatters. It replaces ad hoc constant duplication across the codebase's API handlers and frontend modules going forward.</description>
</item>
+ <item>
+ <title>New tool-authoring SDK: define an agent tool once — typed params, permissions, and rate limits included</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-08:New tool-authoring SDK: define an agent tool once — typed params, permissions, and rate limits included</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>sdk</category>
+ <description>Internal SDK release for developers extending three.ws's 38 MCP servers: @three-ws/tool-sdk lets a tool be declared once with defineTool (Zod parameter schemas, auto-derived JSON Schema, a per-tool permission manifest for network access/rate limits/wallet use) and wired up with defineExecutor (typed handlers, automatic validation, uniform error wrapping) — then adapted into a live MCP server registration with a single toMcpTools() call. Proven by refactoring the naming MCP server's sns_resolve tool onto it with byte-identical behavior.</description>
+ </item>
<item>
<title>Paid API endpoints now stay up through a cache-provider outage</title>
<link>https://three.ws/changelog</link>
@@ -142,6 +174,14 @@
<category>fix</category>
<description>Hardened the pay-per-call x402 API surface — every /api/x402/* and /api/okx/3d/* endpoint — so it degrades gracefully instead of failing when the shared Redis cache is unreachable. Previously a missing cache configuration could take these paid endpoints offline; they now serve normally on a safe per-instance fallback, with on-chain payment safety unchanged (each payment authorization is still single-use, so no double-charge is possible).</description>
</item>
+ <item>
+ <title>Spatial MCP: 3D models are now a native, interactive response type</title>
+ <link>https://three.ws/spatial-mcp</link>
+ <guid isPermaLink="false">2026-07-08:Spatial MCP: 3D models are now a native, interactive response type</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>We published an open standard — Spatial MCP — for returning a live, interactive 3D scene as a first-class AI tool result instead of a link in text. Every three.ws 3D tool now emits a conformant artifact (camera, lighting, animation, AR handoff), a public validator checks conformance with actionable errors, and a framework-free reference renderer displays any conformant payload — including ones transformed from other tools. It carries no wallet or token surface, so it works everywhere. Try the reference renderer.</description>
+ </item>
<item>
<title>The free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds</title>
<link>https://three.ws/docs/api-reference</link>
@@ -158,6 +198,14 @@
<category>feature</category>
<description>Any unauthenticated call to the unified /api/v1/x API (CoinGecko, DefiLlama, Jupiter Solana prices/quotes/search) now gets real data with zero setup, up to a per-endpoint quota — no wallet, no key, no signup. curl https://three.ws/api/v1/x/coingecko/price?ids=solana just works. Every response carries rate-limit headers so an agent can see exactly how much free budget is left; once it's used up, the same URL falls through to pay-per-call USDC (x402) or a three.ws API key instead of dead-ending.</description>
</item>
+ <item>
+ <title>three.ws now speaks BNB Chain's payment protocol (MPP), both ways</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-08:three.ws now speaks BNB Chain's payment protocol (MPP), both ways</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Our paid endpoints now accept payments over MPP — BNB Chain's Machine Payments Protocol — in addition to the x402 payments we already take on Solana and Base. Because MPP is x402 v2 under the hood, the same signed-stablecoin credential works; agents from the BNB ecosystem can now pay us on BNB Chain, settling through the Binance OnchainPay facilitator, while every existing Solana/Base payment path is untouched. The $THREE Town Oracle is the first endpoint to accept both. Our own agents can pay any MPP-protected endpoint too, with a hard per-call spending cap that refuses an over-quote before any money moves.</description>
+ </item>
<item>
<title>3D API</title>
<link>https://three.ws/3d</link>
diff --git a/public/embed/v1.js b/public/embed/v1.js
index 9b7364f13..99e0c4c19 100644
--- a/public/embed/v1.js
+++ b/public/embed/v1.js
@@ -62,21 +62,185 @@
}
// Resolver cache — embeds for the same agent on a single page share one
- // fetch. Cleared on navigation, never persisted.
+ // fetch. Cleared on navigation, never persisted. Only the plain, ungated
+ // response is cached: a gated response (locked teaser, or an unlocked
+ // payload tied to one visitor's private access token) is never shared
+ // across callers and is re-checked every time.
var resolverCache = Object.create(null);
- function resolve(id) {
- if (resolverCache[id]) return resolverCache[id];
- resolverCache[id] = fetch(
- ORIGIN + '/api/embed/resolve?id=' + encodeURIComponent(id),
- { credentials: 'omit' },
- ).then(function (r) {
- if (!r.ok) throw new Error('resolve failed: ' + r.status);
- return r.json();
- }).catch(function (err) {
- delete resolverCache[id]; // allow retry
- throw err;
+ function resolve(id, gateToken) {
+ var cacheKey = gateToken ? null : id;
+ if (cacheKey && resolverCache[cacheKey]) return resolverCache[cacheKey];
+ var qs = '?id=' + encodeURIComponent(id) + (gateToken ? '&gate_token=' + encodeURIComponent(gateToken) : '');
+ var p = fetch(ORIGIN + '/api/embed/resolve' + qs, { credentials: 'omit' })
+ .then(function (r) {
+ if (!r.ok) throw new Error('resolve failed: ' + r.status);
+ return r.json();
+ })
+ .then(function (data) {
+ if (data && data.gated && cacheKey) delete resolverCache[cacheKey];
+ return data;
+ });
+ if (cacheKey) {
+ resolverCache[cacheKey] = p.catch(function (err) {
+ delete resolverCache[cacheKey]; // allow retry
+ throw err;
+ });
+ return resolverCache[cacheKey];
+ }
+ return p;
+ }
+
+ // -------- Token gate: cached access token (per asset, per tab) ---------
+
+ var GATE_TOKEN_PREFIX = 'threeWsGateToken:';
+
+ function gateTokenKey(assetId) {
+ return GATE_TOKEN_PREFIX + assetId;
+ }
+
+ function loadCachedGateToken(assetId) {
+ try {
+ var raw = sessionStorage.getItem(gateTokenKey(assetId));
+ if (!raw) return null;
+ var parsed = JSON.parse(raw);
+ if (!parsed || !parsed.token || !parsed.exp) return null;
+ // 5s safety margin so a token that's about to expire mid-request isn't
+ // handed to the server, which would just bounce it back locked anyway.
+ if (parsed.exp <= Date.now() + 5000) {
+ sessionStorage.removeItem(gateTokenKey(assetId));
+ return null;
+ }
+ return parsed;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ function saveGateToken(assetId, token, expiresInSec) {
+ try {
+ sessionStorage.setItem(
+ gateTokenKey(assetId),
+ JSON.stringify({ token: token, exp: Date.now() + Math.max(0, Number(expiresInSec) || 0) * 1000 }),
+ );
+ } catch (_) {
+ /* sessionStorage unavailable (private mode / disabled) — token just isn't persisted */
+ }
+ }
+
+ function clearCachedGateToken(assetId) {
+ try {
+ sessionStorage.removeItem(gateTokenKey(assetId));
+ } catch (_) {}
+ }
+
+ // -------- Token gate: wallet connect + SIWS verify ----------------------
+
+ function detectSolanaProvider() {
+ if (typeof window === 'undefined') return null;
+ return (
+ (window.phantom && window.phantom.solana) ||
+ window.solana ||
+ (window.backpack && window.backpack.solana) ||
+ window.solflare ||
+ null
+ );
+ }
+
+ function bytesToBase64(bytes) {
+ var bin = '';
+ for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
+ return btoa(bin);
+ }
+
+ function gatePost(path, body) {
+ return fetch(ORIGIN + path, {
+ method: 'POST',
+ credentials: 'omit',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ }).then(function (r) {
+ return r.json().then(
+ function (data) {
+ return { ok: r.ok, data: data };
+ },
+ function () {
+ return { ok: false, data: null };
+ },
+ );
+ });
+ }
+
+ function friendlyError(message, extra) {
+ var err = new Error(message);
+ if (extra) {
+ for (var k in extra) if (Object.prototype.hasOwnProperty.call(extra, k)) err[k] = extra[k];
+ }
+ return err;
+ }
+
+ // Full connect → sign → verify round trip for one asset. Resolves
+ // { accessToken, expiresIn } on success; rejects with a `.userMessage` the
+ // locked card can render directly (no provider, connection cancelled, bad
+ // signature, or a real, server-checked insufficient balance).
+ async function verifyGateOwnership(assetId) {
+ var provider = detectSolanaProvider();
+ if (!provider) {
+ throw friendlyError('no wallet', {
+ userMessage: 'No Solana wallet found in this browser.',
+ installUrl: 'https://phantom.app',
+ });
+ }
+
+ var wallet;
+ try {
+ var resp = provider.connect ? await provider.connect() : null;
+ var pk = (resp && resp.publicKey) || provider.publicKey;
+ wallet = pk && pk.toString ? pk.toString() : pk ? String(pk) : null;
+ } catch (e) {
+ throw friendlyError('connect rejected', {
+ userMessage: /reject|4001/i.test((e && e.message) || '') ? 'Wallet connection was cancelled.' : 'Could not connect to your wallet.',
+ });
+ }
+ if (!wallet) throw friendlyError('no address', { userMessage: 'Could not read your wallet address.' });
+
+ var phase1 = await gatePost('/api/embed/gate-verify', { assetId: assetId, walletAddress: wallet });
+ if (!phase1.ok || !phase1.data || !phase1.data.message) {
+ throw friendlyError('phase1 failed', {
+ userMessage: (phase1.data && phase1.data.message) || 'This embed is not gated (or the gate was removed).',
+ });
+ }
+ var message = phase1.data.message;
+
+ var signature;
+ try {
+ var msgBytes = new TextEncoder().encode(message);
+ var signed = await provider.signMessage(msgBytes, 'utf8');
+ var sigBytes = signed && signed.signature ? signed.signature : signed;
+ signature = bytesToBase64(sigBytes);
+ } catch (e) {
+ throw friendlyError('signature rejected', {
+ userMessage: /reject|4001/i.test((e && e.message) || '') ? 'Signature request was cancelled.' : 'Could not sign the verification message.',
+ });
+ }
+
+ var phase2 = await gatePost('/api/embed/gate-verify', {
+ assetId: assetId,
+ walletAddress: wallet,
+ signature: signature,
+ message: message,
});
- return resolverCache[id];
+ if (!phase2.ok || !phase2.data) {
+ throw friendlyError('verify failed', { userMessage: 'Verification failed. Try again.' });
+ }
+ if (!phase2.data.allowed) {
+ var have = phase2.data.amount != null ? Number(phase2.data.amount).toLocaleString() : '0';
+ var need = phase2.data.minAmount != null ? Number(phase2.data.minAmount).toLocaleString() : '?';
+ throw friendlyError('insufficient balance', {
+ userMessage: 'You hold ' + have + ', need ' + need + '.',
+ insufficientBalance: true,
+ });
+ }
+ return { accessToken: phase2.data.accessToken, expiresIn: phase2.data.expiresIn };
}
var REDUCED_MOTION = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -147,6 +311,41 @@
+ '.fail{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;'
+ 'font-size:13px;color:rgba(255,255,255,.6);padding:24px;text-align:center;}'
+ '@media (prefers-reduced-motion: reduce){model-viewer{--progress-bar-height:0;}}'
+ // ── Token-gated locked state ──────────────────────────────────────
+ + '.gate{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;'
+ + 'justify-content:center;gap:10px;padding:28px 22px;text-align:center;opacity:0;'
+ + 'transition:opacity .32s ease;background:radial-gradient(120% 120% at 50% 0%,rgba(40,40,46,.9),rgba(6,6,8,.96));}'
+ + '.gate.gate--poster{background-size:cover;background-position:center;}'
+ + '.gate.gate--poster::before{content:"";position:absolute;inset:0;'
+ + 'backdrop-filter:blur(18px) saturate(70%);-webkit-backdrop-filter:blur(18px) saturate(70%);'
+ + 'background:rgba(8,8,10,.72);}'
+ + '.gate.gate--in{opacity:1;}'
+ + '.gate>*{position:relative;z-index:1;}'
+ + '.gate-icon{width:34px;height:34px;border-radius:10px;display:flex;align-items:center;justify-content:center;'
+ + 'background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);color:#fff;margin-bottom:2px;}'
+ + '.gate-icon svg{width:16px;height:16px;}'
+ + '.gate-title{font-size:15px;font-weight:700;letter-spacing:-.005em;color:#fff;margin:0;line-height:1.35;max-width:280px;}'
+ + '.gate-sub{font-size:12px;color:rgba(255,255,255,.55);margin:0;max-width:260px;line-height:1.5;}'
+ + '.gate-btn{appearance:none;border:1px solid rgba(255,255,255,.22);border-radius:999px;'
+ + 'background:#fff;color:#0a0a0a;font:700 13px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif;'
+ + 'padding:10px 20px;cursor:pointer;margin-top:6px;transition:transform .15s,background .15s,opacity .15s;'
+ + 'text-decoration:none;display:inline-flex;align-items:center;gap:6px;}'
+ + '.gate-btn:hover{background:#f0f0f0;transform:translateY(-1px);}'
+ + '.gate-btn:active{transform:translateY(0);}'
+ + '.gate-btn[aria-busy="true"]{opacity:.65;cursor:default;pointer-events:none;}'
+ + '.gate-btn:focus-visible{outline:2px solid #7dd3fc;outline-offset:2px;}'
+ + '.gate-note{font-size:11.5px;color:rgba(255,255,255,.5);min-height:14px;margin-top:2px;max-width:260px;line-height:1.5;}'
+ + '.gate-note[data-tone="warn"]{color:#f5c98a;}'
+ + '.gate-mint{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10.5px;'
+ + 'color:rgba(255,255,255,.4);letter-spacing:.02em;}'
+ + ':host([theme="light"]) .gate{background:radial-gradient(120% 120% at 50% 0%,rgba(255,255,255,.94),rgba(240,240,242,.98));}'
+ + ':host([theme="light"]) .gate.gate--poster::before{background:rgba(255,255,255,.78);}'
+ + ':host([theme="light"]) .gate-title{color:#111;}'
+ + ':host([theme="light"]) .gate-sub,:host([theme="light"]) .gate-mint{color:rgba(0,0,0,.5);}'
+ + ':host([theme="light"]) .gate-icon{background:rgba(0,0,0,.06);border-color:rgba(0,0,0,.14);color:#111;}'
+ + ':host([theme="light"]) .gate-btn{background:#111;color:#fff;border-color:rgba(0,0,0,.2);}'
+ + ':host([theme="light"]) .gate-btn:hover{background:#000;}'
+ + '@media (prefers-reduced-motion: reduce){.gate,.gate-btn{transition:none;}}'
+ '';
function ThreeWsAgentElement() {
@@ -227,11 +426,18 @@
var resolved = null;
if (!src && agentSpec) {
+ var cachedGate = loadCachedGateToken(agentSpec);
try {
- resolved = await resolve(agentSpec);
+ resolved = await resolve(agentSpec, cachedGate ? cachedGate.token : null);
} catch (e) {
throw new Error('Could not resolve agent "' + agentSpec + '"');
}
+ if (resolved && resolved.locked) {
+ if (cachedGate) clearCachedGateToken(agentSpec); // stale/expired — drop it
+ self.__renderLocked(resolved, agentSpec);
+ return;
+ }
+ self.__clearLocked();
src = resolved.glbUrl;
nameAttr = nameAttr || resolved.name;
posterAttr = posterAttr || resolved.poster;
@@ -334,6 +540,133 @@
this.dispatchEvent(new CustomEvent('three-error', { detail: err, bubbles: true }));
};
+ // ── Token-gated locked state ────────────────────────────────────────────
+ // Renders a designed teaser in place of the 3D scene: what it is, what it
+ // takes to unlock, and a real connect-wallet CTA. Never leaves a blank box
+ // or a bare error — every branch (no wallet, cancelled, wrong balance,
+ // network hiccup) gets specific, actionable copy.
+
+ var LOCK_SVG =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<rect x="4.5" y="10.5" width="15" height="9.5" rx="2"/>' +
+ '<path d="M8 10.5V7a4 4 0 0 1 8 0v3.5"/></svg>';
+
+ ThreeWsAgentElement.prototype.__clearLocked = function () {
+ if (this.__gateEl) {
+ this.__gateEl.remove();
+ this.__gateEl = null;
+ }
+ };
+
+ ThreeWsAgentElement.prototype.__renderLocked = function (resolved, assetId) {
+ var self = this;
+ this.__clearLocked();
+ if (this.__mv) {
+ this.__mv.remove();
+ this.__mv = null;
+ }
+
+ var gate = resolved.gate || {};
+ var amount = gate.minAmount != null ? Number(gate.minAmount).toLocaleString() : '?';
+ var symbol = gate.symbol || 'tokens';
+
+ var el = document.createElement('div');
+ el.className = 'gate';
+ el.setAttribute('role', 'group');
+ el.setAttribute('aria-label', 'Locked — token-gated 3D embed');
+ if (resolved.poster) {
+ el.classList.add('gate--poster');
+ el.style.backgroundImage = 'url("' + String(resolved.poster).replace(/"/g, '%22') + '")';
+ }
+
+ var icon = document.createElement('div');
+ icon.className = 'gate-icon';
+ icon.innerHTML = LOCK_SVG;
+ el.appendChild(icon);
+
+ var title = document.createElement('p');
+ title.className = 'gate-title';
+ title.textContent = 'Hold ' + amount + ' ' + symbol + ' to unlock';
+ el.appendChild(title);
+
+ var sub = document.createElement('p');
+ sub.className = 'gate-sub';
+ sub.textContent = resolved.name
+ ? '"' + resolved.name + '" is a token-gated 3D embed on three.ws.'
+ : 'This is a token-gated 3D embed on three.ws.';
+ el.appendChild(sub);
+
+ var btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'gate-btn';
+ btn.textContent = 'Connect wallet';
+ el.appendChild(btn);
+
+ var note = document.createElement('p');
+ note.className = 'gate-note';
+ note.setAttribute('role', 'status');
+ note.setAttribute('aria-live', 'polite');
+ el.appendChild(note);
+
+ if (!this.hasAttribute('hide-chrome') && gate.mint) {
+ var mintEl = document.createElement('p');
+ mintEl.className = 'gate-mint';
+ mintEl.textContent = gate.mint === symbol ? '' : gate.mint;
+ if (mintEl.textContent) el.appendChild(mintEl);
+ }
+
+ var busy = false;
+ btn.addEventListener('click', function () {
+ if (busy) return;
+ var provider = detectSolanaProvider();
+ if (!provider) {
+ note.textContent = 'No Solana wallet found — install Phantom, then try again.';
+ note.dataset.tone = 'warn';
+ btn.textContent = 'Get a wallet';
+ btn.onclick = null;
+ var link = document.createElement('a');
+ link.href = 'https://phantom.app';
+ link.target = '_blank';
+ link.rel = 'noopener';
+ link.className = 'gate-btn';
+ link.textContent = 'Get a wallet';
+ btn.replaceWith(link);
+ return;
+ }
+ busy = true;
+ btn.setAttribute('aria-busy', 'true');
+ btn.textContent = 'Connecting…';
+ note.textContent = '';
+ note.dataset.tone = '';
+ verifyGateOwnership(assetId)
+ .then(function (result) {
+ saveGateToken(assetId, result.accessToken, result.expiresIn);
+ self.__booted = true; // already true, but keep intent explicit
+ return self.__boot();
+ })
+ .catch(function (err) {
+ busy = false;
+ btn.removeAttribute('aria-busy');
+ btn.textContent = 'Connect wallet';
+ note.textContent = (err && err.userMessage) || 'Verification failed. Try again.';
+ note.dataset.tone = 'warn';
+ });
+ });
+
+ this.__stage.appendChild(el);
+ this.__gateEl = el;
+ requestAnimationFrame(function () {
+ el.classList.add('gate--in');
+ });
+ this.dispatchEvent(
+ new CustomEvent('three-gate:locked', {
+ detail: { assetId: assetId, mint: gate.mint, minAmount: gate.minAmount },
+ bubbles: true,
+ }),
+ );
+ };
+
ThreeWsAgentElement.prototype.disconnectedCallback = function () {
if (visibilityObserver) visibilityObserver.unobserve(this);
};
diff --git a/public/features.json b/public/features.json
index a638a9775..6f39f5600 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T00:58:37.616Z",
+ "generated_at": "2026-07-08T01:01:12.266Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -422,6 +422,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/restyle",
+ "title": "Restyle Studio — material presets & variants",
+ "description": "Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.",
+ "added": "2026-07-08",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/avatar-engines",
"title": "Avatar Engines Atlas",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 576741a20..1c6acebdd 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -262,6 +262,12 @@ URL: https://three.ws/forge
Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+### Restyle Studio — material presets & variants
+
+URL: https://three.ws/restyle
+
+Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.
+
### Avatar Engines Atlas
URL: https://three.ws/avatar-engines
diff --git a/public/llms.txt b/public/llms.txt
index 66c0297cd..5c22b9474 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -53,6 +53,7 @@ Create and customize an agent.
- [Viewer](https://three.ws/app): Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser.
- [Describe it to 3D](https://three.ws/create/prompt): Type a description. About a minute later: a rigged 3D avatar you can animate and download.
- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+- [Restyle Studio — material presets & variants](https://three.ws/restyle): Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.
- [Avatar Engines Atlas](https://three.ws/avatar-engines): A curated, factual atlas of the open-source and commercial engines that build high-quality and photoreal 3D human avatars — Gaussian-splat heads, single-photo humans, text→avatar generators, and the rigs three.ws already animates. Technique, license, compute, and integration status for each.
- [Splat Viewer — Photoreal Gaussian Avatars](https://three.ws/splat): Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.
- [Scene Capture — Video to 3D Point Cloud](https://three.ws/capture): Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index c250c2c62..cbcf9ce56 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 402 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 403 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 402 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 403 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>
@@ -301,7 +301,7 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>46</span></h2>
+ <h2>Build<span class="sm-count" data-count>47</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -389,6 +389,13 @@
<span class="sm-desc">Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.</span>
</a>
</li>
+ <li>
+ <a href="/restyle">
+ <span class="sm-title">Restyle Studio — material presets &amp; variants</span>
+ <span class="sm-path">/restyle</span>
+ <span class="sm-desc">Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), generate seeded colorway variants, fine-tune metalness and roughness, and export a validated GLB — non-destructively.</span>
+ </a>
+ </li>
<li>
<a href="/avatar-engines">
<span class="sm-title">Avatar Engines Atlas</span>
diff --git a/scripts/animations-extra-clips.json b/scripts/animations-extra-clips.json
new file mode 100644
index 000000000..ee74356f2
--- /dev/null
+++ b/scripts/animations-extra-clips.json
@@ -0,0 +1,9 @@
+[
+ {
+ "name": "sitidle",
+ "label": "Sit Idle",
+ "icon": "🪑",
+ "loop": true,
+ "_note": "Hand-authored 2-key hold pose (no FBX source), added in commit 7a22e5993 for the /walk sit gesture. Not part of the Mixamo retarget pipeline — merged into manifest.json here so it stays reachable by AnimationManager.crossfadeTo('sitidle') instead of silently regressing to a dead gesture slot on the next animation build."
+ }
+]
diff --git a/scripts/animations.config.json b/scripts/animations.config.json
index 0cc61cde7..5d69b0209 100644
--- a/scripts/animations.config.json
+++ b/scripts/animations.config.json
@@ -343,6 +343,34 @@
"icon": "😲",
"loop": false
},
+ {
+ "name": "nod",
+ "source": "mx-nodding-head-yes-c9c91f89b96c.fbx",
+ "label": "Nod",
+ "icon": "🙂",
+ "loop": false
+ },
+ {
+ "name": "shrug",
+ "source": "mx-shoulder-shrug-c9c69537b96c.fbx",
+ "label": "Shrug",
+ "icon": "🤷",
+ "loop": false
+ },
+ {
+ "name": "point",
+ "source": "mx-pointing-with-arm-bent-c9c6947cb96c.fbx",
+ "label": "Point",
+ "icon": "👉",
+ "loop": false
+ },
+ {
+ "name": "think",
+ "source": "mx-thoughtfully-nodding-head-yes-c9c91939b96c.fbx",
+ "label": "Think",
+ "icon": "🤔",
+ "loop": false
+ },
{
"name": "rumba",
"source": "Rumba Dancing.fbx",
@@ -371,6 +399,13 @@
"icon": "😂",
"loop": false
},
+ {
+ "name": "sitloop",
+ "source": "mx-sitting-with-breathing-idle-c9ccab1bb96c.fbx",
+ "label": "Sitting Idle",
+ "icon": "🪑",
+ "loop": true
+ },
{
"name": "taunt",
"source": "Taunt.fbx",
@@ -406,6 +441,20 @@
"icon": "🚶",
"loop": true
},
+ {
+ "name": "turn",
+ "source": "mx-standing-180-left-turn-c9c96eaeb96c.fbx",
+ "label": "Turn",
+ "icon": "🔄",
+ "loop": false
+ },
+ {
+ "name": "jog",
+ "source": "mx-jog-forward-c9d59296b96c-31.fbx",
+ "label": "Jog",
+ "icon": "🏃",
+ "loop": true
+ },
{
"name": "dodge",
"source": "Dodging Right.fbx",
diff --git a/scripts/build-animations.mjs b/scripts/build-animations.mjs
index 6bdb7f9eb..1c7255c28 100644
--- a/scripts/build-animations.mjs
+++ b/scripts/build-animations.mjs
@@ -89,6 +89,13 @@ const OUT_DIR = cliFlags.out ? resolve(ROOT, cliFlags.out) : resolve(ANIM_DIR, '
const REFERENCE_GLB = resolve(ROOT, 'public/avatars/cz.glb');
const CONFIG = cliFlags.config ? resolve(ROOT, cliFlags.config) : resolve(__dirname, 'animations.config.json');
const MANIFEST_OUT = cliFlags.manifest ? resolve(ROOT, cliFlags.manifest) : resolve(ANIM_DIR, 'manifest.json');
+// Hand-authored clips that were never retargeted from an FBX/GLB source (e.g. a
+// short pose baked directly as AnimationClip JSON). They still live in OUT_DIR
+// as real clip files, but since main() rebuilds `manifest` purely from CONFIG
+// entries, anything not in CONFIG would silently vanish from the manifest on
+// every rebuild. Merged in below — for the curated build only — so they stay
+// permanently reachable instead of regressing every time this script runs.
+const EXTRA_CLIPS_FILE = resolve(__dirname, 'animations-extra-clips.json');
const URL_PREFIX = typeof cliFlags['url-prefix'] === 'string' ? cliFlags['url-prefix'] : '/animations/clips/';
const IS_CUSTOM_BUILD = !!(cliFlags.config || cliFlags.out || cliFlags.manifest);
const HASH_CACHE = resolve(OUT_DIR, '.input-hashes.json');
@@ -389,6 +396,33 @@ async function main() {
}
}
+ // Merge in hand-authored extra clips (see EXTRA_CLIPS_FILE comment above).
+ // Curated build only — a staging/bulk build (--out/--manifest flags) has its
+ // own OUT_DIR that never contains these files.
+ if (!IS_CUSTOM_BUILD && existsSync(EXTRA_CLIPS_FILE)) {
+ const extras = JSON.parse(readFileSync(EXTRA_CLIPS_FILE, 'utf8'));
+ const already = new Set(manifest.map((c) => c.name));
+ for (const extra of extras) {
+ if (already.has(extra.name)) continue;
+ const clipPath = resolve(OUT_DIR, `${extra.name}.json`);
+ if (!existsSync(clipPath)) {
+ console.warn(`[animations] SKIP extra clip "${extra.name}": no baked file at ${clipPath}`);
+ continue;
+ }
+ const { duration } = JSON.parse(readFileSync(clipPath, 'utf8'));
+ manifest.push({
+ name: extra.name,
+ url: `${URL_PREFIX}${extra.name}.json`,
+ label: extra.label,
+ icon: extra.icon,
+ loop: extra.loop !== false,
+ ...(duration ? { duration } : {}),
+ });
+ already.add(extra.name);
+ console.log(`[animations] EXTRA ${extra.name.padEnd(12)} merged from ${basename(EXTRA_CLIPS_FILE)}`);
+ }
+ }
+
writeFileSync(MANIFEST_OUT, JSON.stringify(manifest, null, '\t') + '\n');
console.log(`\n[animations] wrote manifest with ${manifest.length} clips → ${MANIFEST_OUT}`);
console.log(`[animations] ${okCount} ok (${skipCount} cached), ${failCount} failed`);
diff --git a/scripts/fact-check-benchmark.mjs b/scripts/fact-check-benchmark.mjs
new file mode 100644
index 000000000..6c4975c04
--- /dev/null
+++ b/scripts/fact-check-benchmark.mjs
@@ -0,0 +1,199 @@
+#!/usr/bin/env node
+// Fact-check accuracy benchmark runner.
+//
+// Runs tests/fixtures/fact-check-benchmark.json through the REAL fact-check chain
+// (POST /api/x402/fact-check) and scores accuracy overall, per verdict class, and
+// per difficulty. Writes data/_generated/fact-check-benchmark.json so the public
+// /fact-check accuracy page can render real, checkable numbers.
+//
+// The endpoint is paid ($0.10/claim), so the runner needs an access path — set
+// FACT_CHECK_BYPASS_TOKEN (an x402:bypass-scoped token) OR run it against a
+// deployment whose free lane covers the run. Without a way to reach the chain the
+// runner EXITS with a clear message naming what's missing and writes NOTHING — it
+// never fabricates scores.
+//
+// Usage:
+// FACT_CHECK_BYPASS_TOKEN=… node scripts/fact-check-benchmark.mjs
+// FACT_CHECK_ENDPOINT=https://three.ws/api/x402/fact-check node scripts/fact-check-benchmark.mjs
+//
+// The scoring core (scoreResults / summarize) is pure and unit-tested in
+// tests/api/fact-check-v2.test.js.
+
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO = join(HERE, '..');
+const FIXTURE = join(REPO, 'tests/fixtures/fact-check-benchmark.json');
+const OUT_DIR = join(REPO, 'data/_generated');
+const OUT_FILE = join(OUT_DIR, 'fact-check-benchmark.json');
+
+const VERDICT_CLASSES = ['supported', 'contradicted', 'mixed', 'insufficient'];
+const DIFFICULTIES = ['easy', 'medium', 'hard'];
+
+// ── Pure scoring core (exported for tests) ───────────────────────────────────
+
+// Group an array by a key function into { [key]: items[] }.
+function groupBy(items, keyFn) {
+ const out = {};
+ for (const it of items) {
+ const k = keyFn(it);
+ (out[k] ||= []).push(it);
+ }
+ return out;
+}
+
+// Score a set of results against the fixture. `results` is an array of
+// { claim, expected_verdict, difficulty, actual_verdict } (actual_verdict null =
+// the chain could not be reached for that claim → counts as incorrect but is
+// tracked separately as `errors`). Returns a structured accuracy report.
+export function scoreResults(results) {
+ const total = results.length;
+ const correct = results.filter((r) => r.actual_verdict === r.expected_verdict).length;
+ const errors = results.filter((r) => r.actual_verdict == null).length;
+
+ const pct = (c, t) => (t > 0 ? Math.round((c / t) * 1000) / 10 : null);
+
+ const byClass = {};
+ const grpClass = groupBy(results, (r) => r.expected_verdict);
+ for (const cls of VERDICT_CLASSES) {
+ const g = grpClass[cls] || [];
+ byClass[cls] = { total: g.length, correct: g.filter((r) => r.actual_verdict === r.expected_verdict).length };
+ byClass[cls].accuracy_pct = pct(byClass[cls].correct, byClass[cls].total);
+ }
+
+ const byDifficulty = {};
+ const grpDiff = groupBy(results, (r) => r.difficulty);
+ for (const d of DIFFICULTIES) {
+ const g = grpDiff[d] || [];
+ byDifficulty[d] = { total: g.length, correct: g.filter((r) => r.actual_verdict === r.expected_verdict).length };
+ byDifficulty[d].accuracy_pct = pct(byDifficulty[d].correct, byDifficulty[d].total);
+ }
+
+ // A simple confusion matrix expected→actual (only for claims that were checked).
+ const confusion = {};
+ for (const cls of VERDICT_CLASSES) confusion[cls] = {};
+ for (const r of results) {
+ if (r.actual_verdict == null) continue;
+ const row = (confusion[r.expected_verdict] ||= {});
+ row[r.actual_verdict] = (row[r.actual_verdict] || 0) + 1;
+ }
+
+ return {
+ total,
+ correct,
+ errors,
+ accuracy_pct: pct(correct, total),
+ by_class: byClass,
+ by_difficulty: byDifficulty,
+ confusion,
+ };
+}
+
+// Validate the fixture shape and return its claims. Throws on a malformed suite —
+// the benchmark is the product's quality bar, so a broken fixture must fail loud.
+export function validateFixture(fixture) {
+ if (!fixture || !Array.isArray(fixture.claims)) throw new Error('fixture.claims must be an array');
+ const claims = fixture.claims;
+ if (claims.length < 40) throw new Error(`fixture must have ≥40 claims, has ${claims.length}`);
+ const counts = Object.fromEntries(VERDICT_CLASSES.map((c) => [c, 0]));
+ for (const [i, c] of claims.entries()) {
+ if (!c.claim || typeof c.claim !== 'string') throw new Error(`claims[${i}].claim missing`);
+ if (!VERDICT_CLASSES.includes(c.expected_verdict)) throw new Error(`claims[${i}].expected_verdict invalid: ${c.expected_verdict}`);
+ if (!c.rationale) throw new Error(`claims[${i}].rationale missing`);
+ if (!DIFFICULTIES.includes(c.difficulty)) throw new Error(`claims[${i}].difficulty invalid: ${c.difficulty}`);
+ counts[c.expected_verdict]++;
+ }
+ for (const cls of VERDICT_CLASSES) {
+ if (counts[cls] < 10) throw new Error(`class "${cls}" has ${counts[cls]} claims, needs ≥10`);
+ }
+ return claims;
+}
+
+// ── Live chain call ──────────────────────────────────────────────────────────
+
+async function checkOne(endpoint, bypassToken, claim) {
+ const headers = { 'content-type': 'application/json' };
+ if (bypassToken) headers.authorization = `Bearer ${bypassToken}`;
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ claim, strictness: 'normal' }),
+ signal: AbortSignal.timeout(60_000),
+ });
+ if (res.status === 402) {
+ const e = new Error('payment_required'); e.paymentRequired = true; throw e;
+ }
+ if (!res.ok) {
+ const e = new Error(`chain returned ${res.status}`); e.status = res.status; throw e;
+ }
+ const data = await res.json();
+ const verdict = data?.verdict ?? data?.result?.verdict ?? null;
+ return verdict;
+}
+
+async function main() {
+ const raw = await readFile(FIXTURE, 'utf8');
+ const fixture = JSON.parse(raw);
+ const claims = validateFixture(fixture);
+ console.log(`Loaded ${claims.length} benchmark claims (validated).`);
+
+ const endpoint = process.env.FACT_CHECK_ENDPOINT || 'https://three.ws/api/x402/fact-check';
+ const bypassToken = process.env.FACT_CHECK_BYPASS_TOKEN || '';
+
+ // Probe reachability before spending a full run. A 402 without a bypass token
+ // means the run can't proceed without payment — exit clearly, write nothing.
+ if (!bypassToken) {
+ try {
+ await checkOne(endpoint, '', claims[0].claim);
+ } catch (err) {
+ if (err.paymentRequired) {
+ console.error(
+ '\nCannot run the benchmark: the fact-check endpoint requires payment and no ' +
+ 'FACT_CHECK_BYPASS_TOKEN (x402:bypass scope) was provided.\n' +
+ 'Set FACT_CHECK_BYPASS_TOKEN (and optionally FACT_CHECK_ENDPOINT) and re-run.\n' +
+ 'No scores were written — the accuracy page will render its honest "not yet run" state.',
+ );
+ process.exit(1);
+ }
+ console.error(`\nCannot reach the fact-check chain at ${endpoint}: ${err.message}`);
+ process.exit(1);
+ }
+ }
+
+ console.log(`Running ${claims.length} claims through ${endpoint} …`);
+ const results = [];
+ for (const [i, c] of claims.entries()) {
+ let actual = null;
+ try {
+ actual = await checkOne(endpoint, bypassToken, c.claim);
+ } catch (err) {
+ console.warn(` [${i + 1}/${claims.length}] error: ${err.message}`);
+ }
+ const ok = actual === c.expected_verdict;
+ console.log(` [${i + 1}/${claims.length}] ${ok ? 'PASS' : 'MISS'} expected=${c.expected_verdict} actual=${actual ?? 'ERR'} :: ${c.claim.slice(0, 60)}`);
+ results.push({ claim: c.claim, expected_verdict: c.expected_verdict, difficulty: c.difficulty, actual_verdict: actual });
+ }
+
+ const score = scoreResults(results);
+ const report = {
+ generated_at: new Date().toISOString(),
+ endpoint,
+ fixture_version: fixture.version || '1.0.0',
+ claim_count: claims.length,
+ ...score,
+ };
+ await mkdir(OUT_DIR, { recursive: true });
+ await writeFile(OUT_FILE, JSON.stringify(report, null, 2) + '\n');
+ console.log(`\nOverall accuracy: ${score.accuracy_pct}% (${score.correct}/${score.total}, ${score.errors} errors)`);
+ console.log(`Wrote ${OUT_FILE}`);
+}
+
+// Only run main() when invoked directly, not when imported by the test.
+if (process.argv[1] && process.argv[1].endsWith('fact-check-benchmark.mjs')) {
+ main().catch((err) => {
+ console.error('benchmark failed:', err);
+ process.exit(1);
+ });
+}
diff --git a/server-studio.json b/server-studio.json
index d1567472b..edb35f8db 100644
--- a/server-studio.json
+++ b/server-studio.json
@@ -10,12 +10,12 @@
"sizes": ["any"]
}
],
- "description": "Free text/image → 3D: generate, rig, and avatar-ify GLB models. No auth, no payment, five tools.",
+ "description": "Free text/image → 3D: generate, rig, avatar-ify, and conversationally refine GLB models, plus persistent lip-syncing agent personas. No auth, no payment, nine tools.",
"repository": {
"url": "https://github.com/nirholas/three.ws",
"source": "github"
},
- "version": "1.0.0",
+ "version": "1.0.1",
"remotes": [
{
"type": "streamable-http",
diff --git a/src/restyle.js b/src/restyle.js
index c994a5293..ed1571767 100644
--- a/src/restyle.js
+++ b/src/restyle.js
@@ -59,7 +59,7 @@ function cache() {
'stage', 'canvas-wrap', 'presets', 'variants', 'variant-strip', 'history',
'metalness', 'roughness', 'emissive', 'basecolor', 'emissivecolor',
'seed', 'variant-count', 'gen-variants', 'reset', 'export', 'export-note',
- 'file', 'url-input', 'load-url', 'status', 'empty', 'error', 'error-msg', 'retry',
+ 'file', 'url-input', 'load-url', 'status', 'error', 'error-msg', 'retry',
]) {
el[id] = document.getElementById(id);
}
@@ -383,7 +383,6 @@ function pushHistory(label) {
function showState(kind) {
el.status.hidden = kind !== 'loading';
- el.empty.hidden = true;
el.error.hidden = kind !== 'error';
el['canvas-wrap'].classList.toggle('is-hidden', kind === 'error');
}
diff --git a/tests/api/fact-check-benchmark.test.js b/tests/api/fact-check-benchmark.test.js
new file mode 100644
index 000000000..ceaf662cc
--- /dev/null
+++ b/tests/api/fact-check-benchmark.test.js
@@ -0,0 +1,96 @@
+// Tests for the fact-check accuracy benchmark (prompt 20 core: the checkable
+// quality bar) — the curated fixture's schema/coverage and the runner's pure
+// scoring math, which ship independent of the live LLM chain.
+//
+// Kept separate from tests/api/fact-check-v2.test.js (the free-lane/quota suite
+// owned by the concurrent storefront work) so the two layer cleanly.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import { scoreResults, validateFixture } from '../../scripts/fact-check-benchmark.mjs';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const fixture = JSON.parse(readFileSync(join(HERE, '../fixtures/fact-check-benchmark.json'), 'utf8'));
+
+const CLASSES = ['supported', 'contradicted', 'mixed', 'insufficient'];
+
+describe('fact-check benchmark fixture', () => {
+ it('has ≥40 claims with ≥10 per verdict class and passes validation', () => {
+ const claims = validateFixture(fixture); // throws if malformed
+ expect(claims.length).toBeGreaterThanOrEqual(40);
+ for (const cls of CLASSES) {
+ expect(claims.filter((c) => c.expected_verdict === cls).length).toBeGreaterThanOrEqual(10);
+ }
+ });
+
+ it('every claim is fully specified (claim, expected_verdict, rationale, difficulty)', () => {
+ for (const c of fixture.claims) {
+ expect(typeof c.claim).toBe('string');
+ expect(c.claim.length).toBeGreaterThan(0);
+ expect(CLASSES).toContain(c.expected_verdict);
+ expect(typeof c.rationale).toBe('string');
+ expect(['easy', 'medium', 'hard']).toContain(c.difficulty);
+ }
+ });
+
+ it('rejects a fixture that starves a verdict class (≥40 total but <10 mixed)', () => {
+ // Keep the full 40 so the count check passes, then reclassify every mixed
+ // claim as supported — the per-class floor for "mixed" must still fail.
+ const broken = { claims: fixture.claims.map((c) => (c.expected_verdict === 'mixed' ? { ...c, expected_verdict: 'supported' } : c)) };
+ expect(() => validateFixture(broken)).toThrow(/mixed/);
+ });
+
+ it('rejects a fixture with an invalid verdict', () => {
+ const broken = { claims: [...fixture.claims, { claim: 'x', expected_verdict: 'nonsense', rationale: 'y', difficulty: 'easy' }] };
+ expect(() => validateFixture(broken)).toThrow(/invalid/);
+ });
+});
+
+describe('scoreResults', () => {
+ const results = [
+ { claim: 'a', expected_verdict: 'supported', difficulty: 'easy', actual_verdict: 'supported' },
+ { claim: 'b', expected_verdict: 'contradicted', difficulty: 'medium', actual_verdict: 'contradicted' },
+ { claim: 'c', expected_verdict: 'mixed', difficulty: 'hard', actual_verdict: 'supported' }, // miss
+ { claim: 'd', expected_verdict: 'insufficient', difficulty: 'easy', actual_verdict: null }, // error
+ ];
+
+ it('computes overall accuracy, correct count, and error count', () => {
+ const s = scoreResults(results);
+ expect(s.total).toBe(4);
+ expect(s.correct).toBe(2);
+ expect(s.errors).toBe(1);
+ expect(s.accuracy_pct).toBe(50);
+ });
+
+ it('breaks accuracy down per verdict class', () => {
+ const s = scoreResults(results);
+ expect(s.by_class.supported).toEqual({ total: 1, correct: 1, accuracy_pct: 100 });
+ expect(s.by_class.mixed).toEqual({ total: 1, correct: 0, accuracy_pct: 0 });
+ expect(s.by_class.insufficient).toEqual({ total: 1, correct: 0, accuracy_pct: 0 });
+ });
+
+ it('breaks accuracy down per difficulty', () => {
+ const s = scoreResults(results);
+ expect(s.by_difficulty.easy.total).toBe(2);
+ expect(s.by_difficulty.easy.correct).toBe(1);
+ expect(s.by_difficulty.hard).toEqual({ total: 1, correct: 0, accuracy_pct: 0 });
+ });
+
+ it('builds an expected→actual confusion matrix over checked claims only', () => {
+ const s = scoreResults(results);
+ expect(s.confusion.supported.supported).toBe(1);
+ expect(s.confusion.mixed.supported).toBe(1);
+ expect(s.confusion.insufficient).toEqual({}); // null actual excluded
+ });
+
+ it('scores a perfect run at 100% and an all-error run at 0%', () => {
+ const perfect = fixture.claims.map((c) => ({ ...c, actual_verdict: c.expected_verdict }));
+ expect(scoreResults(perfect).accuracy_pct).toBe(100);
+ const zero = fixture.claims.map((c) => ({ ...c, actual_verdict: null }));
+ expect(scoreResults(zero).accuracy_pct).toBe(0);
+ expect(scoreResults(zero).errors).toBe(fixture.claims.length);
+ });
+});
diff --git a/tests/api/fact-check-v2.test.js b/tests/api/fact-check-v2.test.js
new file mode 100644
index 000000000..bbd62a334
--- /dev/null
+++ b/tests/api/fact-check-v2.test.js
@@ -0,0 +1,255 @@
+/**
+ * Tests for the fact-check "v2" funnel work (prompt 20 of prompts/x402-catalog):
+ * • a free daily lane (per-IP quota) that runs the REAL chain and falls
+ * through to the existing x402 402 challenge once exhausted
+ * • the `lane` field on every response ("free" | "paid")
+ * • the benchmark fixture (tests/fixtures/fact-check-benchmark.json): schema,
+ * coverage of all four verdict classes, minimum size
+ * • the benchmark runner's scoring math (scripts/fact-check-benchmark.mjs),
+ * exercised against a synthetic result set so it needs no live chain/env
+ *
+ * The upstream chain (LLM query generation, web search, image evidence) is
+ * fixtured at the module boundary — none of api/x402/fact-check.js's own logic
+ * is mocked, matching the pattern in tests/api/v1-ai-speech.test.js.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { Readable } from 'node:stream';
+
+const llmState = vi.hoisted(() => ({
+ queries: ['q1', 'q2', 'q3'],
+ analyses: [{ excerpt: 'it says so', stance: 'supports' }],
+}));
+
+vi.mock('../../agents/fact-checker/src/llm-verdict.js', () => ({
+ generateSearchQueries: vi.fn(async () => ({ queries: llmState.queries, tokens: 120 })),
+ analyzeResults: vi.fn(async (_claim, results) => ({
+ analyses: results.map((_r, i) => llmState.analyses[i] || llmState.analyses[0]),
+ tokens: 200,
+ })),
+}));
+
+vi.mock('../../agents/fact-checker/src/search-sources.js', () => ({
+ searchAll: vi.fn(async () => [
+ { url: 'https://en.wikipedia.org/wiki/Test', title: 'Test — Wikipedia', snippet: 'A well-sourced snippet.' },
+ { url: 'https://example.com/blog', title: 'Some blog', snippet: 'A less authoritative snippet.' },
+ ]),
+}));
+
+vi.mock('../../agents/fact-checker/src/source-authority.js', () => ({
+ authorityScore: vi.fn((url) => (url.includes('wikipedia.org') ? 0.9 : 0.4)),
+}));
+
+vi.mock('../../agents/fact-checker/src/image-evidence.js', () => ({
+ imageEvidence: vi.fn(async () => null),
+}));
+
+const ENV_KEYS = ['X402_PAY_TO_BASE', 'X402_ASSET_ADDRESS_BASE', 'X402_PAY_TO_SOLANA', 'UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'];
+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+
+let handler;
+
+beforeEach(async () => {
+ vi.resetModules();
+ Object.assign(process.env, {
+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',
+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ });
+ delete process.env.X402_PAY_TO_SOLANA;
+ // No Redis configured → the idempotency cache and the rate limiter both run
+ // on their honest in-process fallbacks (deterministic within one test file).
+ delete process.env.UPSTASH_REDIS_REST_URL;
+ delete process.env.UPSTASH_REDIS_REST_TOKEN;
+ ({ default: handler } = await import('../../api/x402/fact-check.js'));
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIGINAL_ENV[k];
+ }
+});
+
+let ipCounter = 0;
+function freshIp() {
+ ipCounter += 1;
+ return { 'x-forwarded-for': `203.0.${(ipCounter >> 8) & 0xff}.${ipCounter & 0xff}` };
+}
+
+function jsonReq(body, headers = {}) {
+ const buf = Buffer.from(JSON.stringify(body));
+ const req = Readable.from([buf]);
+ req.method = 'POST';
+ req.url = '/api/x402/fact-check';
+ req.headers = { 'content-type': 'application/json', 'content-length': String(buf.length), ...headers };
+ return req;
+}
+
+function makeRes() {
+ const chunks = [];
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ write(c) {
+ chunks.push(Buffer.from(c));
+ },
+ end(c) {
+ if (c) chunks.push(Buffer.from(c));
+ this.writableEnded = true;
+ this.headersSent = true;
+ },
+ json() {
+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
+ },
+ };
+}
+
+async function callFactCheck(req) {
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+describe('POST /api/x402/fact-check — free daily lane', () => {
+ it('serves a free check with lane:"free" and a real verdict', async () => {
+ const res = await callFactCheck(jsonReq({ claim: 'The sky is blue during the day.' }, freshIp()));
+ expect(res.statusCode).toBe(200);
+ const body = res.json();
+ expect(body.lane).toBe('free');
+ expect(typeof body.free_remaining_today).toBe('number');
+ expect(['supported', 'contradicted', 'mixed', 'insufficient']).toContain(body.verdict);
+ expect(body.attestation).toMatch(/^sha256:/);
+ });
+
+ it('rejects a too-short claim with 400 before burning a free slot', async () => {
+ const ip = freshIp();
+ const bad = await callFactCheck(jsonReq({ claim: 'hi' }, ip));
+ expect(bad.statusCode).toBe(400);
+ expect(bad.json().error).toBe('invalid_claim');
+ // The slot wasn't spent — a real check on the same IP still succeeds.
+ const ok = await callFactCheck(jsonReq({ claim: 'A valid claim right here.' }, ip));
+ expect(ok.statusCode).toBe(200);
+ expect(ok.json().lane).toBe('free');
+ });
+
+ it('rejects invalid JSON with 400', async () => {
+ const req = Readable.from([Buffer.from('{not json')]);
+ req.method = 'POST';
+ req.url = '/api/x402/fact-check';
+ req.headers = { 'content-type': 'application/json', ...freshIp() };
+ const res = await callFactCheck(req);
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('invalid_json');
+ });
+
+ it('falls through to the 402 challenge once the daily free quota is exhausted', async () => {
+ const { FREE_DAILY_LIMIT } = await import('../../api/x402/fact-check.js');
+ const ip = freshIp();
+ for (let i = 0; i < FREE_DAILY_LIMIT; i++) {
+ const res = await callFactCheck(jsonReq({ claim: `Claim number ${i} right here.` }, ip));
+ expect(res.statusCode).toBe(200);
+ expect(res.json().lane).toBe('free');
+ }
+ const over = await callFactCheck(jsonReq({ claim: 'One claim too many today.' }, ip));
+ expect(over.statusCode).toBe(402);
+ });
+
+ it('a request carrying an X-PAYMENT header always goes straight to the paid rail (402 without a real proof)', async () => {
+ const res = await callFactCheck(
+ jsonReq({ claim: 'A claim paid for up front.' }, { ...freshIp(), 'x-payment': 'not-a-real-proof' }),
+ );
+ // No free lane, straight into x402 verification — an invalid/undecodable
+ // proof is rejected by the rail (never silently treated as free).
+ expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(res.json().lane).not.toBe('free');
+ });
+
+ it('GET (or any non-POST) is left entirely to the paid rail\'s own method guard', async () => {
+ const req = Readable.from([]);
+ req.method = 'GET';
+ req.url = '/api/x402/fact-check';
+ req.headers = { ...freshIp() };
+ const res = await callFactCheck(req);
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('fact-check benchmark fixture', () => {
+ const fixturePath = resolve(process.cwd(), 'tests/fixtures/fact-check-benchmark.json');
+ const fixture = JSON.parse(readFileSync(fixturePath, 'utf8'));
+
+ it('has at least 40 claims', () => {
+ expect(Array.isArray(fixture.claims)).toBe(true);
+ expect(fixture.claims.length).toBeGreaterThanOrEqual(40);
+ });
+
+ it('covers all four verdict classes with at least 10 claims each', () => {
+ const counts = { supported: 0, contradicted: 0, mixed: 0, insufficient: 0 };
+ for (const c of fixture.claims) counts[c.expected_verdict] = (counts[c.expected_verdict] || 0) + 1;
+ for (const cls of ['supported', 'contradicted', 'mixed', 'insufficient']) {
+ expect(counts[cls]).toBeGreaterThanOrEqual(10);
+ }
+ });
+
+ it('every claim has the required shape and a non-third-party-coin-promoting body', () => {
+ for (const c of fixture.claims) {
+ expect(typeof c.claim).toBe('string');
+ expect(c.claim.length).toBeGreaterThan(5);
+ expect(['supported', 'contradicted', 'mixed', 'insufficient']).toContain(c.expected_verdict);
+ expect(typeof c.rationale).toBe('string');
+ expect(c.rationale.length).toBeGreaterThan(0);
+ expect(['easy', 'medium', 'hard']).toContain(c.difficulty);
+ }
+ });
+
+ it('claims are unique (no duplicate benchmark entries)', () => {
+ const seen = new Set(fixture.claims.map((c) => c.claim));
+ expect(seen.size).toBe(fixture.claims.length);
+ });
+});
+
+describe('scripts/fact-check-benchmark.mjs — scoring math', () => {
+ it('scores overall + per-class + per-difficulty accuracy against a synthetic result set', async () => {
+ const { scoreBenchmarkRun } = await import('../../scripts/fact-check-benchmark.mjs');
+ const claims = [
+ { claim: 'a', expected_verdict: 'supported', difficulty: 'easy' },
+ { claim: 'b', expected_verdict: 'supported', difficulty: 'hard' },
+ { claim: 'c', expected_verdict: 'contradicted', difficulty: 'easy' },
+ { claim: 'd', expected_verdict: 'insufficient', difficulty: 'medium' },
+ ];
+ const results = [
+ { claim: 'a', expected_verdict: 'supported', difficulty: 'easy', actual_verdict: 'supported' },
+ { claim: 'b', expected_verdict: 'supported', difficulty: 'hard', actual_verdict: 'mixed' },
+ { claim: 'c', expected_verdict: 'contradicted', difficulty: 'easy', actual_verdict: 'contradicted' },
+ { claim: 'd', expected_verdict: 'insufficient', difficulty: 'medium', actual_verdict: 'insufficient' },
+ ];
+ const score = scoreBenchmarkRun(results);
+ expect(score.overall.total).toBe(4);
+ expect(score.overall.correct).toBe(3);
+ expect(score.overall.accuracy).toBeCloseTo(0.75, 5);
+ expect(score.byClass.supported.total).toBe(2);
+ expect(score.byClass.supported.correct).toBe(1);
+ expect(score.byClass.contradicted.accuracy).toBeCloseTo(1, 5);
+ expect(score.byDifficulty.easy.accuracy).toBeCloseTo(1, 5);
+ expect(score.byDifficulty.hard.accuracy).toBeCloseTo(0, 5);
+ // scoreBenchmarkRun is pure — never touches claims fixture directly.
+ expect(claims.length).toBe(4);
+ });
+
+ it('handles an empty result set without dividing by zero', async () => {
+ const { scoreBenchmarkRun } = await import('../../scripts/fact-check-benchmark.mjs');
+ const score = scoreBenchmarkRun([]);
+ expect(score.overall.total).toBe(0);
+ expect(score.overall.accuracy).toBe(0);
+ });
+});
diff --git a/tests/api/v1-pump-search.test.js b/tests/api/v1-pump-search.test.js
new file mode 100644
index 000000000..ab30084b7
--- /dev/null
+++ b/tests/api/v1-pump-search.test.js
@@ -0,0 +1,124 @@
+// GET /api/v1/pump/search — free text search over pump.fun / meme tokens.
+//
+// Registers the site's existing Birdeye-first/pump.fun-fallback search
+// (api/_lib/pump-search.js `searchPumpTokens`, shared with the command
+// palette's api/pump/search.js) under the versioned, cataloged /api/v1
+// surface. These tests mock `searchPumpTokens` at the boundary — its own
+// upstream fallback logic is covered by tests exercising api/pump/search.js's
+// documented behavior — and exercise the real handler: a real-shaped hit,
+// an honest empty miss (never 404/500), validation, the per-IP rate limit,
+// and catalog registration.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+let quotaOk = true;
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),
+ publicIp: async () =>
+ quotaOk
+ ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }
+ : { success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 },
+ },
+ clientIp: () => '203.0.113.11',
+}));
+
+let searchImpl = async () => [];
+vi.mock('../../api/_lib/pump-search.js', () => ({
+ searchPumpTokens: (q, limit) => searchImpl(q, limit),
+}));
+
+beforeEach(() => {
+ quotaOk = true;
+ searchImpl = async () => [];
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function makeReq({ url = '/api/v1/pump/search', host = 'three.ws' } = {}) {
+ const stream = Readable.from([]);
+ stream.method = 'GET';
+ stream.url = url;
+ stream.headers = { host };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function dispatch(req, res) {
+ const mod = await import('../../api/v1/pump/search.js');
+ await mod.default(req, res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+describe('GET /api/v1/pump/search', () => {
+ it('returns real-shaped hits for a query', async () => {
+ searchImpl = async (q, limit) => {
+ expect(q).toBe('three.ws');
+ expect(limit).toBe(8);
+ return [{ mint: THREE_MINT, symbol: 'three', name: 'three.ws', logo: null, price_usd: 0.0013, rank: null }];
+ };
+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/pump/search?q=three.ws' }), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.data).toEqual({
+ results: [{ mint: THREE_MINT, symbol: 'three', name: 'three.ws', logo: null, price_usd: 0.0013, rank: null }],
+ count: 1,
+ q: 'three.ws',
+ });
+ expect(res.getHeader('cache-control')).toMatch(/max-age=15/);
+ });
+
+ it('an empty result is a valid 200, never a 404', async () => {
+ searchImpl = async () => [];
+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/pump/search?q=zzzznotfound' }), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.data).toEqual({ results: [], count: 0, q: 'zzzznotfound' });
+ });
+
+ it('requires q', async () => {
+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/pump/search' }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('clamps limit to 1..20, defaulting to 8', async () => {
+ searchImpl = async (q, limit) => {
+ expect(limit).toBe(20);
+ return [];
+ };
+ await dispatch(makeReq({ url: '/api/v1/pump/search?q=sol&limit=999' }), makeRes());
+ });
+
+ it('returns 429 when the per-IP quota is exhausted', async () => {
+ quotaOk = false;
+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/pump/search?q=sol' }), makeRes());
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
+
+describe('/api/v1 catalog', () => {
+ it('registers the pump search endpoint as a free, public GET', async () => {
+ const { CATALOG } = await import('../../api/v1/_catalog.js');
+ const entry = CATALOG.find((e) => e.id === 'v1.pump.search');
+ expect(entry).toBeTruthy();
+ expect(entry.method).toBe('GET');
+ expect(entry.path).toBe('/api/v1/pump/search');
+ expect(entry.auth).toBe('public');
+ expect(entry.params.q).toBeTruthy();
+ });
+});
diff --git a/tests/ar-export.test.js b/tests/ar-export.test.js
new file mode 100644
index 000000000..72413a349
--- /dev/null
+++ b/tests/ar-export.test.js
@@ -0,0 +1,122 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ detectArTarget,
+ assertArAssetUrl,
+ buildSceneViewerUrl,
+ buildViewerUrl,
+ buildArLaunchUrl,
+ planArLaunch,
+} from '../api/_lib/ar-launch.js';
+import { toolDefs as arDefs } from '../api/_mcp3d/tools/ar.js';
+import { validateSpatialArtifact } from '../api/_lib/spatial-mcp.js';
+
+const GLB = 'https://three.ws/cdn/creations/model.glb';
+const IOS = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15';
+const ANDROID = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36';
+const DESKTOP = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36';
+
+describe('detectArTarget', () => {
+ it('classifies iOS, Android, and desktop', () => {
+ expect(detectArTarget(IOS)).toBe('ios');
+ expect(detectArTarget('… iPad …')).toBe('ios');
+ expect(detectArTarget(ANDROID)).toBe('android');
+ expect(detectArTarget(DESKTOP)).toBe('desktop');
+ expect(detectArTarget('')).toBe('desktop');
+ });
+});
+
+describe('assertArAssetUrl — boundary rejection', () => {
+ it('accepts an https .glb / .gltf', () => {
+ expect(assertArAssetUrl(GLB)).toBe(GLB);
+ expect(assertArAssetUrl('https://x.io/a.gltf')).toBe('https://x.io/a.gltf');
+ expect(assertArAssetUrl('https://x.io/a.glb?token=1')).toContain('.glb');
+ });
+ it('rejects non-https, non-glb, and garbage — with a coded error, not a crash', () => {
+ expect(() => assertArAssetUrl('http://x.io/a.glb')).toThrow(/https/i);
+ expect(() => assertArAssetUrl('https://x.io/a.png')).toThrow(/\.glb/i);
+ expect(() => assertArAssetUrl('not a url')).toThrow(/valid https url/i);
+ try {
+ assertArAssetUrl('http://x.io/a.glb');
+ } catch (e) {
+ expect(e.code).toBe('not_https');
+ expect(e.arUserMessage).toBe(true);
+ }
+ });
+});
+
+describe('buildSceneViewerUrl', () => {
+ it('builds an ARCore intent URL with the GLB as the source and a browser fallback', () => {
+ const u = buildSceneViewerUrl(GLB, { title: 'Robot', fallbackUrl: 'https://three.ws/viewer?src=x' });
+ expect(u).toMatch(/^intent:\/\/arvr\.google\.com\/scene-viewer\/1\.2\?/);
+ expect(u).toContain('package=com.google.ar.core');
+ expect(u).toContain(encodeURIComponent(GLB));
+ expect(u).toContain('S.browser_fallback_url=');
+ });
+});
+
+describe('planArLaunch — device routing', () => {
+ it('Android → redirect to Scene Viewer', () => {
+ const p = planArLaunch({ glbUrl: GLB, userAgent: ANDROID, origin: 'https://three.ws' });
+ expect(p.target).toBe('android');
+ expect(p.action).toBe('redirect');
+ expect(p.url).toContain('scene-viewer');
+ });
+ it('iOS → serve the launch page', () => {
+ const p = planArLaunch({ glbUrl: GLB, userAgent: IOS, origin: 'https://three.ws' });
+ expect(p.target).toBe('ios');
+ expect(p.action).toBe('page');
+ expect(p.viewerUrl).toContain('/viewer?src=');
+ });
+ it('desktop → serve the launch page (WebGL fallback)', () => {
+ const p = planArLaunch({ glbUrl: GLB, userAgent: DESKTOP, origin: 'https://three.ws' });
+ expect(p.target).toBe('desktop');
+ expect(p.action).toBe('page');
+ });
+ it('bad input throws at the boundary (handled by the endpoint)', () => {
+ expect(() => planArLaunch({ glbUrl: 'http://x/a.glb', userAgent: IOS, origin: 'https://three.ws' })).toThrow();
+ });
+});
+
+describe('buildViewerUrl / buildArLaunchUrl', () => {
+ it('build https viewer and AR launch URLs', () => {
+ expect(buildViewerUrl('https://three.ws', GLB)).toBe(`https://three.ws/viewer?src=${encodeURIComponent(GLB)}`);
+ expect(buildArLaunchUrl('https://three.ws', GLB)).toBe(`https://three.ws/api/ar?src=${encodeURIComponent(GLB)}`);
+ });
+});
+
+describe('export_ar MCP tool', () => {
+ const tool = arDefs.find((d) => d.name === 'export_ar');
+ const req = { headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } };
+
+ it('is a free, read-only tool', () => {
+ expect(tool).toBeTruthy();
+ expect(tool.scope).toBeUndefined();
+ expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
+ });
+
+ it('returns AR links and a conformant spatial artifact with the AR handoff', async () => {
+ const r = await tool.handler({ glb_url: GLB, title: 'Robot' }, null, req);
+ const sc = r.structuredContent;
+ expect(sc.arLaunchUrl).toContain('/api/ar?src=');
+ expect(sc.viewerUrl).toContain('/viewer?src=');
+ expect(sc.sceneViewerUrl).toContain('scene-viewer');
+ // The embedded spatial artifact is conformant and carries the AR block.
+ const v = validateSpatialArtifact(sc.spatial);
+ expect(v.valid).toBe(true);
+ expect(sc.spatial.ar.supported).toBe(true);
+ expect(sc.spatial.ar.launchUrl).toContain('/api/ar');
+ });
+
+ it('rejects bad input cleanly (isError, no crash)', async () => {
+ const r = await tool.handler({ glb_url: 'http://x/a.glb' }, null, req);
+ expect(r.isError).toBe(true);
+ expect(r.structuredContent.error).toBe(true);
+ });
+
+ it('response carries no payment/coin/internal-id surface (OpenAI-clean)', async () => {
+ const r = await tool.handler({ glb_url: GLB }, null, req);
+ const FORBIDDEN = /x402|payment|wallet|usdc|\$three|\btoken\b|\bcoin\b|price|\bpaid\b|onchain|web3|mint|session|trace|job_id|creation_id/i;
+ expect(FORBIDDEN.test(JSON.stringify(r))).toBe(false);
+ });
+});
diff --git a/tests/fixtures/fact-check-benchmark.json b/tests/fixtures/fact-check-benchmark.json
new file mode 100644
index 000000000..7b1aa3341
--- /dev/null
+++ b/tests/fixtures/fact-check-benchmark.json
@@ -0,0 +1,50 @@
+{
+ "$comment": "Accuracy benchmark for /api/x402/fact-check. 40 claims, 10 per verdict class (supported / contradicted / mixed / insufficient), spanning easy/medium/hard difficulty. Claims are deliberately TIME-STABLE (no 'current president' style facts that drift), non-partisan, and — per the $THREE rule — any crypto claim is protocol-generic (a documented protocol fact), never third-party coin promotion. Verdict taxonomy matches api/x402/fact-check.js computeVerdict(): supported | contradicted | mixed | insufficient. scripts/fact-check-benchmark.mjs runs these through the real chain and scores accuracy.",
+ "version": "1.0.0",
+ "verdict_classes": ["supported", "contradicted", "mixed", "insufficient"],
+ "claims": [
+ { "claim": "Water is composed of two hydrogen atoms and one oxygen atom.", "expected_verdict": "supported", "rationale": "The chemical formula of water is H2O — universally documented basic chemistry.", "difficulty": "easy" },
+ { "claim": "The speed of light in a vacuum is approximately 299,792 kilometers per second.", "expected_verdict": "supported", "rationale": "A defined physical constant (299,792.458 km/s), documented in every physics reference.", "difficulty": "easy" },
+ { "claim": "Mount Everest is the highest mountain above sea level on Earth.", "expected_verdict": "supported", "rationale": "Everest's summit is the highest point above sea level (~8,849 m); well documented.", "difficulty": "easy" },
+ { "claim": "The Pacific Ocean is the largest ocean on Earth by surface area.", "expected_verdict": "supported", "rationale": "The Pacific is the largest and deepest ocean basin; standard geography.", "difficulty": "easy" },
+ { "claim": "Solana uses a proof-of-history mechanism to order transactions.", "expected_verdict": "supported", "rationale": "Proof of History is a documented core primitive of the Solana protocol (protocol-generic fact, not coin promotion).", "difficulty": "medium" },
+ { "claim": "Bitcoin's protocol caps the total supply at 21 million coins.", "expected_verdict": "supported", "rationale": "The 21-million cap is a documented rule of the Bitcoin protocol (protocol-generic fact, not promotion).", "difficulty": "medium" },
+ { "claim": "Photosynthesis converts carbon dioxide and water into glucose and oxygen using light energy.", "expected_verdict": "supported", "rationale": "Standard description of oxygenic photosynthesis; documented biology.", "difficulty": "medium" },
+ { "claim": "The adult human skeleton has 206 bones.", "expected_verdict": "supported", "rationale": "The typical adult human body has 206 bones; standard anatomy.", "difficulty": "medium" },
+ { "claim": "A SHA-256 hash produces a 256-bit output.", "expected_verdict": "supported", "rationale": "By definition SHA-256 outputs a 256-bit (32-byte) digest; documented cryptography.", "difficulty": "hard" },
+ { "claim": "The Great Barrier Reef is located off the northeastern coast of Australia.", "expected_verdict": "supported", "rationale": "The reef lies in the Coral Sea off Queensland, Australia; standard geography.", "difficulty": "easy" },
+
+ { "claim": "The Great Wall of China is visible from the Moon with the naked eye.", "expected_verdict": "contradicted", "rationale": "A well-documented myth; the wall is far too narrow to resolve from the Moon.", "difficulty": "easy" },
+ { "claim": "Humans only use 10 percent of their brains.", "expected_verdict": "contradicted", "rationale": "A debunked myth; imaging shows virtually all brain regions are active.", "difficulty": "easy" },
+ { "claim": "Lightning never strikes the same place twice.", "expected_verdict": "contradicted", "rationale": "False — tall structures like skyscrapers are struck repeatedly.", "difficulty": "easy" },
+ { "claim": "The Earth is at the center of the solar system and the Sun orbits it.", "expected_verdict": "contradicted", "rationale": "Geocentrism is false; the heliocentric model is well established.", "difficulty": "easy" },
+ { "claim": "The Sahara is the largest desert in the world by area.", "expected_verdict": "contradicted", "rationale": "The Antarctic polar desert is larger; the Sahara is the largest HOT desert only.", "difficulty": "medium" },
+ { "claim": "Goldfish have a memory span of only three seconds.", "expected_verdict": "contradicted", "rationale": "Studies show goldfish retain memories for weeks to months.", "difficulty": "medium" },
+ { "claim": "Glass is a slow-moving liquid that flows over centuries, which is why old windows are thicker at the bottom.", "expected_verdict": "contradicted", "rationale": "Glass is an amorphous solid; old panes vary due to manufacturing, not flow.", "difficulty": "medium" },
+ { "claim": "Bulls are enraged by the color red.", "expected_verdict": "contradicted", "rationale": "Cattle are red-green colorblind; they react to the cape's motion, not color.", "difficulty": "medium" },
+ { "claim": "Cracking your knuckles causes arthritis.", "expected_verdict": "contradicted", "rationale": "Controlled studies find no link between knuckle-cracking and arthritis.", "difficulty": "medium" },
+ { "claim": "Vikings routinely wore horned helmets into battle.", "expected_verdict": "contradicted", "rationale": "No archaeological evidence; the image comes from 19th-century opera costuming.", "difficulty": "hard" },
+
+ { "claim": "A tomato is a vegetable.", "expected_verdict": "mixed", "rationale": "Botanically a fruit, but culinarily and legally treated as a vegetable — sources genuinely split.", "difficulty": "easy" },
+ { "claim": "Coffee is bad for your health.", "expected_verdict": "mixed", "rationale": "Evidence is mixed and dose-dependent; moderate intake shows both benefits and risks.", "difficulty": "medium" },
+ { "claim": "Eating carrots gives you significantly better night vision.", "expected_verdict": "mixed", "rationale": "Vitamin A prevents deficiency-related night blindness, but carrots don't grant superior vision — a partial truth.", "difficulty": "medium" },
+ { "claim": "You lose most of your body heat through your head.", "expected_verdict": "mixed", "rationale": "Heat loss is roughly proportional to exposed surface area; the head is not uniquely leaky — an oversimplification.", "difficulty": "medium" },
+ { "claim": "The human tongue has distinct zones dedicated to different tastes (the tongue map).", "expected_verdict": "mixed", "rationale": "The classic tongue map is largely debunked, though small sensitivity differences exist — partly true.", "difficulty": "medium" },
+ { "claim": "Multitasking makes people more productive.", "expected_verdict": "mixed", "rationale": "Depends on task type; for demanding tasks switching costs reduce productivity — context-dependent.", "difficulty": "medium" },
+ { "claim": "The Great Wall of China is a single continuous wall.", "expected_verdict": "mixed", "rationale": "It is a network of many walls and fortifications built over centuries, not one continuous structure.", "difficulty": "medium" },
+ { "claim": "Dietary cholesterol is the primary driver of high blood cholesterol.", "expected_verdict": "mixed", "rationale": "Modern evidence points more to saturated/trans fats and genetics; dietary cholesterol's role is smaller and debated.", "difficulty": "hard" },
+ { "claim": "Napoleon Bonaparte was unusually short.", "expected_verdict": "mixed", "rationale": "He was about average height for his era; the 'short' image comes from unit confusion and propaganda — partly myth.", "difficulty": "hard" },
+ { "claim": "Chameleons change color mainly to camouflage themselves.", "expected_verdict": "mixed", "rationale": "Color change is driven more by communication and temperature than camouflage, though camouflage plays a role.", "difficulty": "hard" },
+
+ { "claim": "There are exactly 7,412 undiscovered species of beetle in the Amazon rainforest.", "expected_verdict": "insufficient", "rationale": "Undiscovered species cannot, by definition, be counted precisely — unverifiable.", "difficulty": "medium" },
+ { "claim": "Intelligent extraterrestrial life exists on a planet orbiting Proxima Centauri.", "expected_verdict": "insufficient", "rationale": "No evidence either way; currently unverifiable.", "difficulty": "medium" },
+ { "claim": "Dreams contain hidden messages that reliably predict future events.", "expected_verdict": "insufficient", "rationale": "Unfalsifiable claim with no reliable supporting evidence.", "difficulty": "medium" },
+ { "claim": "The average person unknowingly walks past a murderer 36 times in their lifetime.", "expected_verdict": "insufficient", "rationale": "A viral statistic with no credible source or methodology; unverifiable.", "difficulty": "medium" },
+ { "claim": "The best pizza in the world is served in Naples, Italy.", "expected_verdict": "insufficient", "rationale": "A subjective opinion, not a factual claim that can be sourced true or false.", "difficulty": "easy" },
+ { "claim": "There are exactly 7.5 quintillion grains of sand on Earth.", "expected_verdict": "insufficient", "rationale": "Only a rough estimate is possible; no exact figure is knowable.", "difficulty": "hard" },
+ { "claim": "Ghosts exist and haunt certain old houses.", "expected_verdict": "insufficient", "rationale": "No reliable, reproducible evidence; the claim is effectively unfalsifiable.", "difficulty": "medium" },
+ { "claim": "A person named Alex will win a national lottery next year.", "expected_verdict": "insufficient", "rationale": "A claim about a specific future event that cannot be verified in advance.", "difficulty": "easy" },
+ { "claim": "An unreleased, unannounced consumer product will become a commercial success.", "expected_verdict": "insufficient", "rationale": "Refers to something with no public information; cannot be evaluated.", "difficulty": "easy" },
+ { "claim": "Somewhere in the observable universe there is a planet with purple oceans.", "expected_verdict": "insufficient", "rationale": "Plausible but with no evidence for or against; currently unverifiable.", "difficulty": "hard" }
+ ]
+}
diff --git a/tests/mcp-remote-annotations.test.js b/tests/mcp-remote-annotations.test.js
index 281934820..ce88e3609 100644
--- a/tests/mcp-remote-annotations.test.js
+++ b/tests/mcp-remote-annotations.test.js
@@ -25,7 +25,9 @@ const CATALOGS = [
// delete_avatar — permanently removes a user's avatar
// forget — deletes a stored agent memory
// pay_and_call — spends the user's USDC (irreversible transfer)
-const DESTRUCTIVE_TOOLS = new Set(['delete_avatar', 'forget', 'pay_and_call']);
+// persona_tip — spends a persona's own USDC (irreversible transfer)
+// persona_send — spends a persona's own USDC (irreversible transfer)
+const DESTRUCTIVE_TOOLS = new Set(['delete_avatar', 'forget', 'pay_and_call', 'persona_tip', 'persona_send']);
// Internal/spec-only fields that must never leak into the tools/list wire
// payload.
diff --git a/tests/mcp-tool-result.test.js b/tests/mcp-tool-result.test.js
index 532f7c198..ca1ab0d4a 100644
--- a/tests/mcp-tool-result.test.js
+++ b/tests/mcp-tool-result.test.js
@@ -169,6 +169,7 @@ describe('MCP tool surface', () => {
'forge_free',
'rig_mesh',
'forge_avatar',
+ 'refine_model',
'agent_delegate_action',
'agent_hire',
];
diff --git a/vite.config.js b/vite.config.js
index c870e8eef..83de0fda8 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -358,6 +358,7 @@ const appConfig = {
dad: resolve(__dirname, 'pages/dad.html'),
'forge-studio': resolve(__dirname, 'pages/forge-studio.html'),
'forge-embed': resolve(__dirname, 'pages/forge-embed.html'),
+ restyle: resolve(__dirname, 'pages/restyle.html'),
scene: resolve(__dirname, 'pages/scene.html'),
segment: resolve(__dirname, 'pages/segment.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),