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.

feat(x402): implement free tier lane for aggregator with dynamic rate limiting

fudjia9758059f2052
diff --git a/STRUCTURE.md b/STRUCTURE.md
index e80f782f3..6e5972b34 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -65,6 +65,7 @@ bottom.
| Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |
+| BABT holder check (BNB Chain) | Lib [api/_lib/bnb/babt.js](api/_lib/bnb/babt.js) `hasBabt()`, free API [api/bnb/babt-check.js](api/bnb/babt-check.js) `→ GET /api/bnb/babt-check?address=` | In-repo · shipped | Free, rate-limited on-chain check for whether a BSC address holds a Binance Account Bound Token (BABT) — a real, live, KYC-backed soulbound token (1.16M+ mainnet holders, verified via `eth_getCode`/`balanceOf` against the real contract `0x2B09d47D...5215D7c8`). Verification writeup + honest comparison vs. Gitcoin Passport/World ID/Coinbase attestations: [docs/bnb-babt-findings.md](docs/bnb-babt-findings.md). Spike prompt: `prompts/bnb-chain/20-babt-verification-spike.md`. |
## npm workspaces
diff --git a/api/_lib/aggregator.js b/api/_lib/aggregator.js
index 0910e01cc..2e1514736 100644
--- a/api/_lib/aggregator.js
+++ b/api/_lib/aggregator.js
@@ -11,6 +11,7 @@ import { paidEndpoint } from './x402-paid-endpoint.js';
import { buildBazaarSchema } from './x402-spec.js';
import { installAccessControl } from './x402/access-control.js';
import { withService } from './x402/bazaar-helpers.js';
+import { readBody } from './http.js';
const UPSTREAM_TIMEOUT_MS = 20_000;
@@ -180,28 +181,18 @@ export function getPaidHandler(provider, endpoint) {
return handler;
}
-// Minimal JSON body reader for the paid POST path (paidEndpoint leaves the
-// stream untouched). Mirrors http.js readJson but without its content-type
-// hard-fail, since the x402 dance has already consumed headers.
-function readJsonStream(req, limit = 1_000_000) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let total = 0;
- req.on('data', (c) => {
- total += c.length;
- if (total > limit) {
- req.destroy();
- reject(Object.assign(new Error('payload too large'), { status: 413 }));
- } else chunks.push(c);
- });
- req.on('end', () => {
- if (!chunks.length) return resolve(undefined);
- try {
- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
- } catch {
- reject(Object.assign(new Error('invalid JSON body'), { status: 400, code: 'validation_error' }));
- }
- });
- req.on('error', reject);
- });
+// Minimal JSON body reader for the paid POST path. Mirrors http.js readJson
+// but without its content-type hard-fail, since the x402 dance has already
+// consumed headers. Delegates to the shared readBody, which prefers the
+// pre-parsed req.rawBody/req.body the Cloud Run server already captured —
+// re-reading the raw stream (as this function used to) hangs forever once
+// Express has drained it.
+async function readJsonStream(req, limit = 1_000_000) {
+ const buf = await readBody(req, limit);
+ if (!buf.length) return undefined;
+ try {
+ return JSON.parse(buf.toString('utf8'));
+ } catch {
+ throw Object.assign(new Error('invalid JSON body'), { status: 400, code: 'validation_error' });
+ }
}
diff --git a/api/_lib/persona-identity-card.js b/api/_lib/persona-identity-card.js
new file mode 100644
index 000000000..39a5fe94f
--- /dev/null
+++ b/api/_lib/persona-identity-card.js
@@ -0,0 +1,67 @@
+/**
+ * The persona identity card — a structured, verifiable projection of a
+ * persona's on-chain identity, in the SAME spirit as prompt 08's provenance
+ * card (mcp-server/src/lib/agent-commerce.js#buildProvenance): a pure,
+ * deterministic builder over already-fetched data, embedded directly in a
+ * tool's structuredContent so both the host model and any UI can render it
+ * without a second round-trip. Nothing here performs I/O — callers fetch the
+ * identity first (getPersonaIdentity) and pass the result in.
+ */
+
+function formatUsd(n) {
+ if (n == null || !Number.isFinite(Number(n))) return null;
+ return `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`;
+}
+
+/**
+ * @param {object} args
+ * @param {object} args.persona — personaPublicView() projection (name, persona_id, …)
+ * @param {object} args.identity — getPersonaIdentity() result
+ * @returns {object} the identity card block
+ */
+export function buildIdentityCard({ persona, identity }) {
+ const v = identity.visual || {};
+ return {
+ kind: 'persona_identity_card',
+ version: 1,
+ personaId: persona.persona_id,
+ name: persona.name,
+ wallet: {
+ address: identity.address,
+ network: identity.network,
+ explorer: identity.explorer,
+ },
+ balance: {
+ sol: identity.balances.sol,
+ usdc: identity.balances.usdc,
+ totalUsdDisplay: formatUsd(identity.balances.total_usd),
+ },
+ reputation: {
+ tier: v.reputation_tier,
+ verifiedFeedback: identity.reputation.feedback.verified,
+ totalFeedback: identity.reputation.feedback.total,
+ scoreAvgVerified: identity.reputation.feedback.score_avg_verified,
+ source: 'threews-solana-attestations',
+ },
+ holdings: {
+ tier: v.holdings_tier,
+ assetCount: identity.holdings.count,
+ totalUsdDisplay: formatUsd(identity.holdings.total_usd),
+ },
+ verifiedName: v.verified_name,
+ muted: !!v.muted,
+ fetchedAt: identity.fetched_at,
+ };
+}
+
+/** A one-line human-readable summary of the card, for the tool's text content. */
+export function summarizeIdentityCard(card) {
+ const parts = [
+ `${card.name} — ${card.wallet.address.slice(0, 4)}…${card.wallet.address.slice(-4)} (${card.wallet.network})`,
+ `${card.reputation.tier} reputation`,
+ `${card.holdings.tier} holdings tier`,
+ ];
+ if (card.verifiedName) parts.push(`verified as ${card.verifiedName}`);
+ if (card.muted) parts.push('balance muted');
+ return parts.join(' · ');
+}
diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.js
index 4b1e57013..a8c833ce0 100644
--- a/api/_lib/x402/ring-catalog.js
+++ b/api/_lib/x402/ring-catalog.js
@@ -943,6 +943,24 @@ export const RING_CATALOG = [
note: 'autobuy:false — every call runs a real Cloud Run GPU remesh worker job and persists a new GLB.',
},
+ // ── embody — real GPU generation, the priciest single-call service ──────────
+ {
+ slug: 'embody',
+ sourceFile: 'api/x402/embody.js',
+ path: '/api/x402/embody',
+ method: 'POST',
+ body: () => ({ name: 'Ring Canary Body', prompt: 'a small friendly robot mascot' }),
+ priceAtomicDefault: 1_000_000,
+ priceSlug: 'embody',
+ tier: 'commerce',
+ kind: 'service',
+ network: null,
+ autobuy: false,
+ weight: 0,
+ businessEffect: 'Generates a rigged, animated GLB + a durable embeddable persona (agent_id, viewer/profile URLs, embed_html) via the free NVIDIA TRELLIS generate→auto-rig chain.',
+ note: 'autobuy:false — every call is a real GPU generation ($1.00, the priciest single-call service in the catalog) and creates a durable persona row; not a cheap read-only ping.',
+ },
+
// ── remix — real generation + on-chain creator royalty ──────────────────────
{
slug: 'remix-asset',
diff --git a/api/_mcp3d/tools/persona-identity.js b/api/_mcp3d/tools/persona-identity.js
new file mode 100644
index 000000000..783755327
--- /dev/null
+++ b/api/_mcp3d/tools/persona-identity.js
@@ -0,0 +1,235 @@
+// three.ws 3D Studio MCP — embodied on-chain identity.
+//
+// Binds a persona (api/_lib/persona-store.js) to a real, deterministic Solana
+// wallet (api/_lib/persona-wallet.js): the SAME persona_id always re-derives
+// the SAME address, no private key is ever stored, and none is ever returned
+// in a tool response or written to a log. Three tools:
+//
+// persona_identity(persona_id) — read wallet address, live SOL/USDC
+// balance, ERC-8004-style reputation, token holdings, and a resolved SNS
+// nameplate, plus the derived visual tiers the embodiment viewer renders.
+// persona_tip(persona_id, to, usdc) — a small, social value transfer FROM
+// the persona's own wallet, e.g. tipping another agent's wallet.
+// persona_send(persona_id, to, usdc) — the general-purpose USDC send.
+//
+// persona_tip and persona_send share one guarded settlement path
+// (sendPersonaUsdc): a hard per-call cap, a hard cumulative per-session cap,
+// and a confirmation threshold above which the call must carry confirm:true.
+// Real settlement rides the same MEV-aware execution engine every other
+// outbound transfer on the platform uses — no mocked transfer, ever.
+//
+// Claude/paid-track only: NOT reused by the free studio (api/_mcp-studio),
+// which asserts zero wallet/crypto surface in its own catalog test.
+
+import { limits } from '../../_lib/rate-limit.js';
+import { getPersona, isPersonaId, personaPublicView } from '../../_lib/persona-store.js';
+import {
+ getPersonaIdentity,
+ sendPersonaUsdc,
+ personaWalletAddress,
+} from '../../_lib/persona-wallet.js';
+import { PERSONA_SPEND_CAPS } from '../../_lib/persona-spend-ledger.js';
+import { embodimentArtifact } from '../../_lib/embodiment-artifact.js';
+import { buildIdentityCard, summarizeIdentityCard } from '../../_lib/persona-identity-card.js';
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+function rateKey(auth) {
+ return auth.userId || auth.rateKey || 'anon';
+}
+async function enforce(limiter, auth) {
+ const rl = await limiter(rateKey(auth));
+ if (!rl.success) {
+ throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ }
+}
+
+function toolError(text, structuredContent = { ok: false }) {
+ return { content: [{ type: 'text', text }], structuredContent, isError: true };
+}
+
+async function loadPersonaOrError(personaId) {
+ if (!isPersonaId(personaId)) {
+ return { error: toolError('That is not a valid persona_id.', { status: 'invalid_id' }) };
+ }
+ const record = await getPersona(personaId);
+ if (!record) {
+ return { error: toolError('No persona found for that id. Create one with create_agent_persona first.', { status: 'not_found' }) };
+ }
+ return { record };
+}
+
+// Gate an irreversible value transfer on an explicit confirm flag once its
+// amount clears PERSONA_SPEND_CAPS.confirmAboveUsdc — same shape as the SOL
+// wallet_send confirmation gate (packages/avatar-agent-mcp), reused here inline
+// since USDC amount + persona name are needed in the message.
+function confirmationGate({ confirm, usdc, personaName, action }) {
+ if (Number(usdc) <= PERSONA_SPEND_CAPS.confirmAboveUsdc) return null;
+ if (confirm === true) return null;
+ return toolError(
+ `${action}: sending $${usdc} USDC from ${personaName} is above the $${PERSONA_SPEND_CAPS.confirmAboveUsdc} confirmation threshold. ` +
+ 'Re-issue the call with confirm:true to proceed.',
+ { status: 'confirmation_required', threshold_usdc: PERSONA_SPEND_CAPS.confirmAboveUsdc },
+ );
+}
+
+const NETWORK_PROP = { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' };
+
+const READ_ANNOTATIONS = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true };
+const VALUE_ANNOTATIONS = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
+
+async function handlePersonaIdentity(args, auth) {
+ await enforce(limits.mcp3dPersonaIdentity, auth);
+ const { record, error } = await loadPersonaOrError(args.persona_id);
+ if (error) return error;
+
+ const identity = await getPersonaIdentity(args.persona_id, { network: args.network || 'mainnet' });
+ const persona = personaPublicView(record);
+ const v = identity.visual;
+
+ const lines = [
+ `${persona.name}'s on-chain identity`,
+ `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})` : ''),
+ `Reputation: ${v.reputation_tier} (${identity.reputation.feedback.verified} verified / ${identity.reputation.feedback.total} total feedback)`,
+ `Holdings: ${identity.holdings.count} asset(s), ~$${identity.holdings.total_usd} — tier ${v.holdings_tier}`,
+ v.verified_name ? `Verified name: ${v.verified_name}` : 'No verified SNS name resolved.',
+ v.muted ? 'Balance is at/near zero — the body renders in its muted state.' : null,
+ ].filter(Boolean);
+
+ return {
+ content: [
+ { type: 'text', text: lines.join('\n') },
+ renderIdentityCard({ persona, identity }),
+ embodimentArtifact({ persona, state: 'idle' }),
+ ],
+ structuredContent: { ...identity, status: 'ok' },
+ };
+}
+
+async function handlePersonaValueOp(args, auth, { tool, verb }) {
+ await enforce(limits.mcp3dPersonaSpend, auth);
+ const { record, error } = await loadPersonaOrError(args.persona_id);
+ if (error) return error;
+ const persona = personaPublicView(record);
+
+ const usdc = Number(args.usdc);
+ const gateResult = confirmationGate({ confirm: args.confirm, usdc, personaName: persona.name, action: verb });
+ if (gateResult) return gateResult;
+
+ const result = await sendPersonaUsdc({
+ personaId: args.persona_id,
+ sessionId: args.session_id || null,
+ to: args.to,
+ usdc,
+ tool,
+ network: args.network || 'mainnet',
+ memo: args.memo || null,
+ });
+
+ if (result.status === 'blocked') {
+ return toolError(
+ `${verb} blocked: ${result.message}`,
+ { status: 'blocked', code: result.code, ...result },
+ );
+ }
+ if (result.status === 'failed') {
+ return toolError(
+ `${verb} failed: ${result.message || result.code}`,
+ { status: 'failed', code: result.code, ...result },
+ );
+ }
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `${persona.name} sent $${result.usdc} USDC to ${result.to}.\n` +
+ `Signature: ${result.signature}\nExplorer: ${result.explorer}\n` +
+ `Session spend: $${result.session_spent_usdc} / $${result.session_cap_usdc} USDC cap.`,
+ },
+ ],
+ structuredContent: { ...result, persona_id: persona.persona_id, persona_name: persona.name },
+ };
+}
+
+const VALUE_INPUT_PROPS = {
+ persona_id: { type: 'string', minLength: 8, maxLength: 64, description: 'The persona whose wallet pays.' },
+ to: { type: 'string', minLength: 32, maxLength: 64, description: 'Destination Solana address (USDC associated token account is created if needed).' },
+ usdc: { type: 'number', exclusiveMinimum: 0, description: `Amount in USDC. Hard per-call cap: $${PERSONA_SPEND_CAPS.maxPerCallUsdc}.` },
+ session_id: {
+ type: 'string',
+ maxLength: 128,
+ description: 'Groups calls under one cumulative session spend cap (default $' + PERSONA_SPEND_CAPS.maxPerSessionUsdc + '). Omit to bucket by persona + UTC day.',
+ },
+ memo: { type: 'string', maxLength: 180, description: 'Optional note stamped alongside the transfer in the returned receipt.' },
+ network: NETWORK_PROP,
+ confirm: {
+ type: 'boolean',
+ description: `Must be true when usdc exceeds $${PERSONA_SPEND_CAPS.confirmAboveUsdc} — the irreversible-transfer confirmation gate.`,
+ },
+};
+
+export const toolDefs = [
+ {
+ name: 'persona_identity',
+ title: "Read a persona's on-chain identity — wallet, reputation, holdings",
+ annotations: READ_ANNOTATIONS,
+ description:
+ "Read a persona's real on-chain identity: its deterministic Solana wallet address, live SOL/USDC balance, " +
+ 'ERC-8004-style reputation (verified feedback + validation record), token holdings, and a resolved SNS ' +
+ 'nameplate if it holds a verified .sol name. Also returns the visual tiers (reputation tier, holdings tier, ' +
+ 'muted-balance flag, verified name) the embodiment viewer maps onto the body — aura, cosmetic, muted state, ' +
+ 'nameplate. Every persona has a wallet the moment it exists; a fresh persona legitimately reads as zero ' +
+ 'balance / unranked reputation until it is funded or interacted with. No sign-in required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ persona_id: { type: 'string', minLength: 8, maxLength: 64, description: 'The persona to read.' },
+ network: NETWORK_PROP,
+ },
+ required: ['persona_id'],
+ additionalProperties: false,
+ },
+ handler: handlePersonaIdentity,
+ },
+ {
+ name: 'persona_tip',
+ title: "Tip USDC from a persona's own wallet",
+ annotations: VALUE_ANNOTATIONS,
+ description:
+ "Send a small USDC tip FROM a persona's own wallet to a destination Solana address — e.g. tipping " +
+ 'another agent for a good answer or hiring result. Real, irreversible on-chain settlement, hard-capped ' +
+ `at $${PERSONA_SPEND_CAPS.maxPerCallUsdc}/call and $${PERSONA_SPEND_CAPS.maxPerSessionUsdc} cumulative per session. ` +
+ `Amounts over $${PERSONA_SPEND_CAPS.confirmAboveUsdc} require confirm:true. Fails cleanly with the exact reason ` +
+ '(insufficient balance, over cap, confirmation required) — never a silent no-op.',
+ inputSchema: { type: 'object', properties: VALUE_INPUT_PROPS, required: ['persona_id', 'to', 'usdc'], additionalProperties: false },
+ async handler(args, auth) {
+ return handlePersonaValueOp(args, auth, { tool: 'persona_tip', verb: 'Tip' });
+ },
+ },
+ {
+ name: 'persona_send',
+ title: "Send USDC from a persona's own wallet",
+ annotations: VALUE_ANNOTATIONS,
+ description:
+ "Send USDC FROM a persona's own wallet to a destination Solana address — the general-purpose value op " +
+ 'behind persona-initiated payments (settling a hire, paying an invoice, funding another wallet). Real, ' +
+ `irreversible on-chain settlement, hard-capped at $${PERSONA_SPEND_CAPS.maxPerCallUsdc}/call and ` +
+ `$${PERSONA_SPEND_CAPS.maxPerSessionUsdc} cumulative per session. Amounts over $${PERSONA_SPEND_CAPS.confirmAboveUsdc} ` +
+ 'require confirm:true. USDC is the only settlement asset here — any other mint is out of scope for this tool.',
+ inputSchema: { type: 'object', properties: VALUE_INPUT_PROPS, required: ['persona_id', 'to', 'usdc'], additionalProperties: false },
+ async handler(args, auth) {
+ return handlePersonaValueOp(args, auth, { tool: 'persona_send', verb: 'Send' });
+ },
+ },
+];
+
+// Exposed for tests that want the raw address without a full identity read.
+export { personaWalletAddress };
diff --git a/api/embed/gate-create.js b/api/embed/gate-create.js
new file mode 100644
index 000000000..40ad4843c
--- /dev/null
+++ b/api/embed/gate-create.js
@@ -0,0 +1,100 @@
+// POST /api/embed/gate-create
+//
+// create_gated_embed(asset_id, gate) — turn an existing embeddable asset
+// (avatar or on-chain agent) into a holder-only interactive 3D embed. The
+// caller must own the asset; the gate config `{ mint, min_amount, chain }` is
+// persisted alongside the embed record (embed_gates) and enforced server-side
+// by api/embed/resolve.js on every subsequent fetch — this endpoint never
+// hands back the glbUrl itself, only the gate + a ready-to-paste snippet.
+//
+// `mint` defaults to $THREE but is a runtime parameter — the coin-agnostic
+// plumbing exception in CLAUDE.md — so any community can gate with their own
+// SPL token. This endpoint never suggests or defaults to any other mint.
+import { z } from 'zod';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { env } from '../_lib/env.js';
+import { parse } from '../_lib/validate.js';
+import { isEmbedAssetRef, resolveEmbedAsset } from '../_lib/embed-asset.js';
+import { DEFAULT_GATE_MINT, createEmbedGate, checkAssetOwnership } from '../_lib/embed-gate.js';
+
+const bodySchema = z.object({
+ assetId: z.string().trim().min(3).max(80),
+ gate: z.object({
+ mint: z.string().trim().min(3).max(64).optional(),
+ minAmount: z.number().positive(),
+ chain: z.enum(['solana']).optional(),
+ }),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ res.setHeader('cache-control', 'no-store');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required to gate an embed');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.embedGateCreateIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(bodySchema, await readJson(req));
+
+ if (!isEmbedAssetRef(body.assetId)) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'assetId must be "<chainId>:<agentId>", "eip155:<chainId>:<agentId>", or "avatar:<uuid>"',
+ );
+ }
+
+ const asset = await resolveEmbedAsset(body.assetId);
+ if (!asset) return error(res, 404, 'not_found', 'embed asset not found');
+
+ const ownership = await checkAssetOwnership(body.assetId, userId);
+ if (!ownership.ok) {
+ if (ownership.reason === 'not_owner') {
+ return error(
+ res,
+ 403,
+ 'not_owner',
+ 'you do not own this asset — link the owning wallet (or account) to gate it',
+ );
+ }
+ return error(res, 404, 'not_found', 'embed asset not found');
+ }
+
+ let gate;
+ try {
+ gate = await createEmbedGate({
+ assetId: body.assetId,
+ ownerUserId: userId,
+ mint: body.gate.mint || DEFAULT_GATE_MINT,
+ minAmount: body.gate.minAmount,
+ chain: body.gate.chain || 'solana',
+ });
+ } catch (err) {
+ return error(res, err.status || 400, 'validation_error', err.message);
+ }
+
+ const scriptSrc = `${env.APP_ORIGIN}/embed/v1.js`;
+ const snippet =
+ `<script src="${scriptSrc}" async></script>\n` +
+ `<three-d agent="${body.assetId}" interactive></three-d>`;
+
+ return json(res, 201, {
+ gateId: gate.gateId,
+ assetId: gate.assetId,
+ gate: { mint: gate.mint, minAmount: gate.minAmount, chain: gate.chain },
+ name: asset.name || null,
+ embed: {
+ scriptSrc,
+ snippet,
+ previewUrl: `${env.APP_ORIGIN}/embed/v1/gated.html?asset=${encodeURIComponent(body.assetId)}`,
+ },
+ });
+});
diff --git a/api/embed/gate-verify.js b/api/embed/gate-verify.js
new file mode 100644
index 000000000..a6843a77d
--- /dev/null
+++ b/api/embed/gate-verify.js
@@ -0,0 +1,171 @@
+// POST /api/embed/gate-verify
+//
+// Two-phase SIWS wallet-ownership proof for a token-gated embed, mirroring
+// api/scene/gate-check.js's phase1 (nonce)/phase2 (signature + on-chain check)
+// shape so the two gating systems feel like one product even though they're
+// stored separately (embed_gates vs. scene_gates).
+//
+// Phase 1 — { assetId, walletAddress } → { message, gate }
+// Issues a one-time nonce embedded in a human-readable SIWS message the
+// caller's wallet signs. Nothing is granted yet.
+//
+// Phase 2 — { assetId, walletAddress, signature, message } → { allowed, ... }
+// Verifies the ed25519 signature, burns the nonce, then reads the wallet's
+// REAL on-chain SPL balance for the gate's mint (never a client-reported
+// number). On success mints a short-lived signed access token
+// (api/_lib/embed-gate-token.js) that api/embed/resolve.js accepts in place
+// of re-running the chain read on every asset fetch.
+//
+// Anti-abuse: rate-limited per IP (flood guard) AND per wallet (the bucket
+// that actually bounds a determined attacker, since IPs are cheap to rotate
+// but a wallet's signing key is not).
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { randomToken } from '../_lib/crypto.js';
+import { verifySiwsSignature } from '../_lib/siws.js';
+import { parse } from '../_lib/validate.js';
+import { readEmbedGateByAsset, getSplTokenBalance, meetsGateThreshold } from '../_lib/embed-gate.js';
+import { signEmbedGateToken, EMBED_GATE_TOKEN_TTL_S } from '../_lib/embed-gate-token.js';
+
+const NONCE_TTL_SEC = 10 * 60;
+
+const phase1Schema = z.object({
+ assetId: z.string().trim().min(3).max(80),
+ walletAddress: z.string().trim().min(1).max(128),
+});
+
+const phase2Schema = z.object({
+ assetId: z.string().trim().min(3).max(80),
+ walletAddress: z.string().trim().min(1).max(128),
+ signature: z.string().min(1).max(512),
+ message: z.string().min(1).max(1024),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+ res.setHeader('cache-control', 'no-store');
+
+ const rl = await limits.embedGateVerifyIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const raw = await readJson(req);
+ if (raw && raw.signature != null) return handlePhase2(res, raw);
+ return handlePhase1(res, raw);
+});
+
+async function handlePhase1(res, raw) {
+ const body = parse(phase1Schema, raw);
+
+ const gate = await readEmbedGateByAsset(body.assetId);
+ if (!gate) return error(res, 404, 'not_found', 'this embed is not gated');
+
+ let nonce = '';
+ while (nonce.length < 16) {
+ nonce += randomToken(20).replace(/[^A-Za-z0-9]/g, '');
+ }
+ nonce = nonce.slice(0, 16);
+
+ await sql`
+ insert into embed_gate_nonces (nonce, gate_id, address, expires_at)
+ values (${nonce}, ${gate.id}, ${body.walletAddress}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)
+ `;
+
+ const message = [
+ 'three.ws token-gated embed verification.',
+ '',
+ `Asset: ${body.assetId}`,
+ `Wallet: ${body.walletAddress}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${new Date().toISOString()}`,
+ ].join('\n');
+
+ return json(res, 200, {
+ message,
+ chain: gate.chain,
+ gate: { mint: gate.mint, minAmount: Number(gate.min_amount) },
+ });
+}
+
+async function handlePhase2(res, raw) {
+ const body = parse(phase2Schema, raw);
+
+ const walletRl = await limits.embedGateVerifyWallet(body.walletAddress);
+ if (!walletRl.success) return rateLimited(res, walletRl);
+
+ const gate = await readEmbedGateByAsset(body.assetId);
+ if (!gate) return error(res, 404, 'not_found', 'this embed is not gated');
+
+ let valid;
+ try {
+ valid = verifySiwsSignature(body.message, body.signature, body.walletAddress);
+ } catch {
+ return error(res, 401, 'invalid_signature', 'Solana signature verification failed');
+ }
+ if (!valid) return error(res, 401, 'invalid_signature', 'signature does not match wallet');
+
+ const nonceMatch = body.message.match(/^Nonce: (.+)$/m);
+ if (!nonceMatch) return error(res, 400, 'invalid_message', 'nonce not found in message');
+ const nonce = nonceMatch[1].trim();
+
+ const [nonceRow] = await sql`
+ select nonce, gate_id, address, expires_at, consumed_at
+ from embed_gate_nonces where nonce = ${nonce} limit 1
+ `;
+ if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');
+ if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');
+ if (new Date(nonceRow.expires_at) < new Date()) return error(res, 400, 'nonce_expired', 'nonce expired — restart verification');
+ if (nonceRow.gate_id !== gate.id) return error(res, 400, 'invalid_nonce', 'nonce gate mismatch');
+ if (nonceRow.address !== body.walletAddress) return error(res, 400, 'invalid_nonce', 'nonce wallet mismatch');
+
+ const burned = await sql`
+ update embed_gate_nonces set consumed_at = now()
+ where nonce = ${nonce} and consumed_at is null
+ returning nonce
+ `;
+ if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');
+
+ const minAmount = Number(gate.min_amount);
+
+ let balance;
+ try {
+ balance = await getSplTokenBalance(body.walletAddress, gate.mint);
+ } catch (err) {
+ return json(res, 200, {
+ allowed: false,
+ reason: err?.message || 'balance check failed — try again',
+ minAmount,
+ mint: gate.mint,
+ });
+ }
+
+ if (!meetsGateThreshold(balance, minAmount)) {
+ return json(res, 200, {
+ allowed: false,
+ reason: `insufficient balance: hold ${minAmount}, have ${balance}`,
+ amount: balance,
+ minAmount,
+ mint: gate.mint,
+ });
+ }
+
+ const accessToken = await signEmbedGateToken({
+ gateId: gate.id,
+ assetId: body.assetId,
+ wallet: body.walletAddress,
+ mint: gate.mint,
+ minAmount,
+ amount: balance,
+ });
+
+ return json(res, 200, {
+ allowed: true,
+ accessToken,
+ expiresIn: EMBED_GATE_TOKEN_TTL_S,
+ amount: balance,
+ minAmount,
+ mint: gate.mint,
+ });
+}
diff --git a/api/embed/resolve.js b/api/embed/resolve.js
index a1bd32ac8..367c51fbe 100644
--- a/api/embed/resolve.js
+++ b/api/embed/resolve.js
@@ -1,5 +1,5 @@
/**
- * GET /api/embed/resolve?id=<spec>
+ * GET /api/embed/resolve?id=<spec>&gate_token=<token>
*
* Resolves a flexible ID spec to the minimal payload an embed needs to render
* an agent: { glbUrl, name, poster, kind, ...minimal metadata }.
@@ -10,15 +10,25 @@
* - "avatar:<uuid>" → public avatar e.g. "avatar:8e3...c1"
*
* Cross-origin by design (Access-Control-Allow-Origin: *). Cached aggressively
- * at the edge so an embed loading in 10k pages doesn't hammer the DB.
+ * at the edge so an embed loading in 10k pages doesn't hammer the DB — EXCEPT
+ * when the asset is token-gated (api/_lib/embed-gate.js), where the response
+ * depends on the caller's own access token and must never be shared/cached.
*
- * Resolution logic lives in api/_lib/embed-asset.js so the token-gate verifier
- * can resolve the same shape behind an on-chain balance check.
+ * Token gating: when an asset carries an active embed_gates row, the real
+ * glbUrl is withheld unless `gate_token` is a valid, unexpired access token
+ * minted by api/embed/gate-verify.js for THIS asset's current gate. Without
+ * one (or with an expired one) the response is a designed "locked" payload —
+ * still 200, never an error — carrying the gate's public terms (mint,
+ * minAmount) so the widget can render the locked state and prompt a wallet
+ * connect + verify. Resolution logic lives in api/_lib/embed-asset.js so this
+ * handler and the gate verifier resolve the exact same asset shape.
*/
import { cors, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { resolveEmbedAsset, isEmbedAssetRef } from '../_lib/embed-asset.js';
+import { readEmbedGateByAsset, DEFAULT_GATE_MINT } from '../_lib/embed-gate.js';
+import { verifyEmbedGateToken } from '../_lib/embed-gate-token.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -43,17 +53,59 @@ export default wrap(async (req, res) => {
const payload = await resolveEmbedAsset(id);
if (!payload) return error(res, 404, 'not_found', 'asset not found');
- return embedJson(res, payload);
+ const gate = await readEmbedGateByAsset(id);
+ if (!gate) return embedJson(res, payload, { cacheable: true });
+
+ const gateToken = (url.searchParams.get('gate_token') || '').trim();
+ const claim = gateToken
+ ? await verifyEmbedGateToken(gateToken, { assetId: id, gateId: gate.id })
+ : null;
+
+ if (claim) {
+ return embedJson(res, { ...payload, gated: true, unlocked: true }, { cacheable: false });
+ }
+
+ // Locked — never leak glbUrl. The teaser (name/poster) is the same public
+ // metadata resolveEmbedAsset would return for an ungated asset, so a
+ // visitor can see what they'd unlock without the payload leaking the model.
+ const symbol = gate.mint === DEFAULT_GATE_MINT ? '$THREE' : shortMint(gate.mint);
+ return embedJson(
+ res,
+ {
+ kind: payload.kind,
+ id: payload.id,
+ name: payload.name,
+ description: payload.description,
+ poster: payload.poster,
+ gated: true,
+ locked: true,
+ gate: {
+ gateId: gate.id,
+ mint: gate.mint,
+ symbol,
+ minAmount: Number(gate.min_amount),
+ chain: gate.chain,
+ },
+ },
+ { cacheable: false },
+ );
});
-function embedJson(res, payload) {
+function shortMint(mint) {
+ const s = String(mint || '');
+ return s.length > 8 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
+}
+
+function embedJson(res, payload, { cacheable }) {
res.statusCode = 200;
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('access-control-allow-origin', '*');
res.setHeader('cross-origin-resource-policy', 'cross-origin');
res.setHeader(
'cache-control',
- 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400',
+ cacheable
+ ? 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400'
+ : 'private, no-store',
);
res.end(JSON.stringify(payload));
}
diff --git a/api/forge.js b/api/forge.js
index 05b013294..d81336d96 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -1346,7 +1346,7 @@ async function startJob(req, res) {
console.warn('[forge] NVIDIA NIM TRELLIS lane in cooldown; routing to reconstruct lane');
nimGatewayDegraded = true;
backendId = 'trellis';
- } else if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) {
+ } else if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts, cacheKey })) {
return;
} else {
// nvidia failed → fall through to the image-intermediate TRELLIS path
@@ -1596,6 +1596,8 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ opts,
+ cacheKey,
})
)
return;
@@ -1631,6 +1633,8 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ opts,
+ cacheKey,
})
)
return;
@@ -1741,6 +1745,8 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ opts,
+ cacheKey,
})
) {
return;
@@ -1866,7 +1872,7 @@ async function startJob(req, res) {
`[forge] paid TRELLIS lane unavailable (${err?.providerStatus || err?.code}); degrading text→3D to free NVIDIA NIM`,
);
try {
- if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
+ if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts, cacheKey })) return;
} catch (fallbackErr) {
console.warn(`[forge] NVIDIA NIM fallback also failed: ${fallbackErr?.message || fallbackErr}`);
}
diff --git a/api/openapi-json.js b/api/openapi-json.js
index 19207e5b8..376f02c39 100644
--- a/api/openapi-json.js
+++ b/api/openapi-json.js
@@ -46,7 +46,7 @@ export default wrap(async (req, res) => {
'/oauth/authorize, or use a Bearer API key from the dashboard. ' +
'Available MCP tools: list_my_avatars, get_avatar, search_public_avatars, ' +
'render_avatar, delete_avatar, validate_model, inspect_model, optimize_model. ' +
- 'Paid REST endpoints under /api/x402/* and /api/insights/* settle in USDC over ' +
+ 'Paid REST endpoints under /api/x402/* settle in USDC over ' +
'x402 (HTTP 402); pay programmatically with @x402/fetch — no API key required.',
},
servers: [{ url: origin }],
diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.js
index e8f4d6d13..5bb393aaa 100644
--- a/api/x402/pump-agent-audit.js
+++ b/api/x402/pump-agent-audit.js
@@ -25,6 +25,7 @@ import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
import { priceFor } from '../_lib/x402-prices.js';
import { recentPumpLaunches } from '../_lib/pump-launch-feed.js';
+import { readBody } from '../_lib/http.js';
const ROUTE = '/api/x402/pump-agent-audit';
diff --git a/data/changelog.json b/data/changelog.json
index 2fdde3dab..8b8e891d5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-08",
+ "title": "Spatial MCP: 3D models are now a native, interactive response type",
+ "summary": "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.",
+ "tags": [
+ "feature",
+ "docs"
+ ],
+ "link": "/spatial-mcp"
+ },
+ {
+ "date": "2026-07-08",
+ "title": "Fixed: the \"View it\" link on every generated 3D model now opens a real viewer",
+ "summary": "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.",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-07-08",
"title": "New free API: check if a wallet holds a Binance Account Bound Token (BABT)",
diff --git a/pages/restyle.html b/pages/restyle.html
new file mode 100644
index 000000000..1a8096188
--- /dev/null
+++ b/pages/restyle.html
@@ -0,0 +1,185 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Restyle Studio · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="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." />
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://three.ws/restyle" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Restyle Studio · three.ws" />
+ <meta property="og:description" content="Apply PBR material presets and seeded variants to any GLB, fine-tune materials live, and export a validated model — non-destructively." />
+ <meta property="og:url" content="https://three.ws/restyle" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Restyle+Studio&amp;d=Apply+PBR+material+presets+and+seeded+variants+to+any+GLB%2C+fine-tune+materials%2C+and+export+a+validated+model.&amp;p=%2Frestyle" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="stylesheet" href="/style.css" />
+ <style>
+ .rs-main { max-width: 1240px; margin: 0 auto; padding: 28px 20px 64px; }
+ .rs-head { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px 20px; margin-bottom: 20px; }
+ .rs-head h1 { font-size: clamp(24px, 4vw, 34px); font-weight: 700; letter-spacing: -0.02em; margin: 0; }
+ .rs-head p { color: var(--text-2); margin: 4px 0 0; max-width: 62ch; }
+ .rs-layout { display: grid; grid-template-columns: 1.5fr 1fr; gap: 18px; align-items: start; }
+ @media (max-width: 900px) { .rs-layout { grid-template-columns: 1fr; } }
+
+ .rs-stage { position: relative; aspect-ratio: 4 / 3; border-radius: 16px; overflow: hidden;
+ background: radial-gradient(120% 120% at 50% 0%, color-mix(in srgb, var(--text) 6%, transparent), transparent 60%), var(--bg-2, #0c0d12);
+ border: 1px solid var(--border, #23252d); }
+ .rs-canvas { position: absolute; inset: 0; }
+ .rs-canvas.is-hidden { opacity: 0; }
+ .rs-overlay { position: absolute; inset: 0; display: grid; place-content: center; text-align: center;
+ gap: 10px; padding: 24px; color: var(--text-2); }
+ .rs-spinner { width: 34px; height: 34px; border-radius: 50%; margin: 0 auto;
+ border: 3px solid color-mix(in srgb, var(--text) 18%, transparent); border-top-color: var(--text); animation: rs-spin 0.8s linear infinite; }
+ @keyframes rs-spin { to { transform: rotate(360deg); } }
+ .rs-stage-hint { position: absolute; left: 12px; bottom: 12px; font-size: 12px; color: var(--text-3);
+ background: color-mix(in srgb, var(--bg, #000) 60%, transparent); padding: 4px 8px; border-radius: 8px; pointer-events: none; }
+
+ .rs-panel { display: flex; flex-direction: column; gap: 18px; }
+ .rs-card { border: 1px solid var(--border, #23252d); border-radius: 14px; padding: 14px 15px; background: var(--bg-2, #0c0d12); }
+ .rs-card h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--text-3); margin: 0 0 10px; }
+
+ .rs-presets { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }
+ .rs-preset { display: flex; align-items: center; gap: 9px; padding: 8px 10px; border-radius: 10px; cursor: pointer;
+ border: 1px solid var(--border, #23252d); background: transparent; color: var(--text); font-size: 13px; text-align: left;
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.05s ease; }
+ .rs-preset:hover { border-color: color-mix(in srgb, var(--text) 40%, transparent); background: color-mix(in srgb, var(--text) 5%, transparent); }
+ .rs-preset:active { transform: translateY(1px); }
+ .rs-preset:focus-visible { outline: 2px solid var(--accent, #7aa2ff); outline-offset: 2px; }
+ .rs-preset.is-active { border-color: var(--accent, #7aa2ff); background: color-mix(in srgb, var(--accent, #7aa2ff) 12%, transparent); }
+ .rs-preset__swatch { width: 20px; height: 20px; border-radius: 6px; flex: none;
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text) 20%, transparent); }
+
+ .rs-slider { display: grid; grid-template-columns: 84px 1fr; align-items: center; gap: 10px; margin: 9px 0; font-size: 13px; color: var(--text-2); }
+ .rs-slider input[type="range"] { width: 100%; accent-color: var(--accent, #7aa2ff); }
+ .rs-colors { display: flex; gap: 14px; margin-top: 6px; }
+ .rs-color { display: flex; align-items: center; gap: 7px; font-size: 13px; color: var(--text-2); }
+ .rs-color input[type="color"] { width: 34px; height: 26px; border: none; background: none; padding: 0; border-radius: 6px; cursor: pointer; }
+
+ .rs-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
+ .rs-row label { font-size: 13px; color: var(--text-2); }
+ .rs-input { width: 66px; padding: 6px 8px; border-radius: 8px; border: 1px solid var(--border, #23252d); background: var(--bg, #000); color: var(--text); font: inherit; }
+ .rs-strip { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
+ .rs-swatch { width: 40px; height: 40px; border-radius: 9px; cursor: pointer; border: 1px solid color-mix(in srgb, var(--text) 22%, transparent);
+ transition: transform 0.08s ease; }
+ .rs-swatch:hover { transform: scale(1.08); }
+ .rs-swatch:focus-visible { outline: 2px solid var(--accent, #7aa2ff); outline-offset: 2px; }
+
+ .rs-btn { padding: 9px 14px; border-radius: 10px; border: 1px solid var(--border, #23252d); background: transparent;
+ color: var(--text); font: inherit; font-size: 13px; cursor: pointer; transition: background 0.15s ease, border-color 0.15s ease; }
+ .rs-btn:hover { background: color-mix(in srgb, var(--text) 6%, transparent); }
+ .rs-btn:focus-visible { outline: 2px solid var(--accent, #7aa2ff); outline-offset: 2px; }
+ .rs-btn--primary { background: var(--text); color: var(--bg, #000); border-color: var(--text); font-weight: 600; }
+ .rs-btn--primary:hover { opacity: 0.9; background: var(--text); }
+ .rs-btn[disabled] { opacity: 0.5; cursor: default; }
+
+ .rs-history { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 12px; color: var(--text-3); min-height: 18px; }
+ .rs-step { padding: 2px 7px; border-radius: 999px; background: color-mix(in srgb, var(--text) 8%, transparent); }
+ .rs-step.is-current { color: var(--text); background: color-mix(in srgb, var(--accent, #7aa2ff) 20%, transparent); }
+ .rs-arrow { color: var(--text-3); }
+ .rs-note { font-size: 12px; color: var(--text-3); margin-top: 8px; min-height: 16px; }
+ .rs-sources { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+ .rs-file { font-size: 12px; color: var(--text-2); }
+ .rs-hint { font-size: 12px; color: var(--text-3); margin-top: 8px; }
+ .rs-hint a { color: var(--accent, #7aa2ff); }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <main class="rs-main">
+ <div class="rs-head">
+ <div>
+ <h1>Restyle Studio</h1>
+ <p>Re-skin any 3D model in your browser — apply a PBR material preset, fan out seeded colorway
+ variants, fine-tune metalness and roughness live, then export a validated GLB. Your original is
+ never touched; Reset restores it instantly.</p>
+ </div>
+ </div>
+
+ <div class="rs-layout">
+ <!-- Stage -->
+ <div class="rs-stage" id="stage">
+ <div class="rs-canvas" id="canvas-wrap"></div>
+ <div class="rs-overlay" id="status" hidden>
+ <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>
+ </div>
+ <div class="rs-stage-hint">Drag to orbit · scroll to zoom · drop a .glb to load</div>
+ </div>
+
+ <!-- Controls -->
+ <div class="rs-panel">
+ <div class="rs-card">
+ <h2>Load a model</h2>
+ <div class="rs-sources">
+ <label class="rs-btn" for="file">Upload GLB<input id="file" type="file" accept=".glb,.gltf,model/gltf-binary" hidden /></label>
+ <input class="rs-input" id="url-input" style="width: 150px" type="url" placeholder="https://…/model.glb" />
+ <button class="rs-btn" id="load-url">Load URL</button>
+ </div>
+ <div class="rs-hint">No model? The platform's sample avatar loads by default. Make one in <a href="/forge">Forge</a>.</div>
+ </div>
+
+ <div class="rs-card">
+ <h2>Material presets</h2>
+ <div class="rs-presets" id="presets"></div>
+ </div>
+
+ <div class="rs-card">
+ <h2>Fine-tune</h2>
+ <div class="rs-slider"><span>Metalness</span><input id="metalness" type="range" min="0" max="1" step="0.01" /></div>
+ <div class="rs-slider"><span>Roughness</span><input id="roughness" type="range" min="0" max="1" step="0.01" /></div>
+ <div class="rs-slider"><span>Emissive</span><input id="emissive" type="range" min="0" max="4" step="0.05" /></div>
+ <div class="rs-colors">
+ <label class="rs-color">Base <input id="basecolor" type="color" value="#888888" /></label>
+ <label class="rs-color">Glow <input id="emissivecolor" type="color" value="#000000" /></label>
+ </div>
+ </div>
+
+ <div class="rs-card">
+ <h2>Seeded variants</h2>
+ <div class="rs-row">
+ <label>Seed <input class="rs-input" id="seed" type="number" value="42" min="0" /></label>
+ <label>Count <input class="rs-input" id="variant-count" type="number" value="6" min="1" max="12" /></label>
+ <button class="rs-btn" id="gen-variants">Generate</button>
+ </div>
+ <div id="variants" hidden>
+ <div class="rs-strip" id="variant-strip"></div>
+ </div>
+ <div class="rs-hint">Same seed → same set, every time. Variants fan out from the last preset you applied.</div>
+ </div>
+
+ <div class="rs-card">
+ <h2>History &amp; export</h2>
+ <div class="rs-history" id="history"></div>
+ <div class="rs-row" style="margin-top: 12px">
+ <button class="rs-btn" id="reset">Reset to original</button>
+ <button class="rs-btn rs-btn--primary" id="export">Export GLB</button>
+ </div>
+ <div class="rs-note" id="export-note"></div>
+ <div class="rs-hint">Prompt-driven AI re-texture (UV-preserving) is available via the
+ <a href="/mcp">retexture_model MCP tool</a>.</div>
+ </div>
+ </div>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
+ <script type="module" src="/src/restyle.js"></script>
+ </body>
+</html>
diff --git a/prompts/store-submissions/_generated/claude-reviewer-guide.md b/prompts/store-submissions/_generated/claude-reviewer-guide.md
index fac0d1548..b0603a735 100644
--- a/prompts/store-submissions/_generated/claude-reviewer-guide.md
+++ b/prompts/store-submissions/_generated/claude-reviewer-guide.md
@@ -49,6 +49,15 @@ boots with a built-in default payout address, so every paid tool advertises a va
---
+> **Live-status note (2026-07-08).** A close-out re-audit of this prompt re-ran the free smoke
+> test live and found the production free lane currently exceeding a reviewer client's
+> patience window (90–100s) during degraded conditions, plus documented an architectural
+> caveat on the review-mode entitlement below (real, working, but self-activatable on this
+> stdio transport — low real exposure since most read tools proxy to already-public
+> endpoints). **Re-run §2 immediately before filing the Claude submission** and treat a repeat
+> hang as a P1. Full analysis: [`claude-tool-call-evidence.md` §"2026-07-08
+> re-verification"](./claude-tool-call-evidence.md#2026-07-08-re-verification-prompt-02-close-out-audit).
+
## 2. Free smoke test (no auth, no payment) — do this first
Call **`forge_free`**:
@@ -127,7 +136,11 @@ claude mcp add 3d-agent \
(The reviewer token is supplied in the **private reviewer notes** of the submission, not in
this repo. Review mode is **off** unless `MCP_REVIEW_SECRET` is set, so it can never be
-abused on a normal install.)
+abused on a normal install. Caveat: because this connector's transport is stdio, the "server"
+and the caller are the same locally-spawned process — a technically inclined installer could
+set both env vars to a matching value themselves. Real exposure is low: most read tools proxy
+to already-public three.ws endpoints, and generation tools still require real vendor
+credentials the self-activator won't have. See the evidence file for the full breakdown.)
With the entitlement active:
diff --git a/prompts/store-submissions/_generated/claude-tool-call-evidence.md b/prompts/store-submissions/_generated/claude-tool-call-evidence.md
index 1342133ae..fa467565f 100644
--- a/prompts/store-submissions/_generated/claude-tool-call-evidence.md
+++ b/prompts/store-submissions/_generated/claude-tool-call-evidence.md
@@ -145,3 +145,77 @@ real generated GLB URL + viewer link. See `claude-reviewer-guide.md` §"Funded r
- Free path (`forge_free`) produces a viewable, durable GLB end-to-end with no auth/payment.
- Review entitlement returns real results (demonstrated on `get_pose_seed`); generation
tools return real GLBs on a credentialed instance and clean structured errors otherwise.
+
+---
+
+## 2026-07-08 re-verification (prompt 02 close-out audit)
+
+Re-ran the free smoke test live against production ahead of marking this prompt complete.
+Two findings — one operational, one architectural. Neither changes the verdict above (the
+implementation is correct and real), but both matter for submission timing.
+
+### A. Free lane currently exceeds the reviewer's patience window
+
+Four consecutive live attempts against production hung with **zero response**:
+
+| # | Method | Payload | Result |
+|---|---|---|---|
+| 1 | `forge_free` (MCP tool) | `{"prompt":"a small friendly owl mascot...","tier":"draft"}` | `timeout` after 90003ms |
+| 2 | `forge_free` (MCP tool) | `{"prompt":"a small owl mascot, blue feathers","tier":"draft"}` | `timeout` after 90006ms |
+| 3 | `curl -X POST /api/forge` | `{"prompt":"a small owl mascot...","tier":"draft","free":true}` | no response, 100s client timeout |
+| 4 | `curl -X POST /api/forge` | `{"prompt":"a red toy car","tier":"draft","free":true,"backend":"nvidia","path":"image"}` | no response, 60s client timeout |
+
+None of these four requests appear in Cloud Run's `run.googleapis.com/requests` log for the
+matching window (`resource.labels.service_name="three-ws-api"`), while other production
+traffic to `/api/forge` (health polls, `?action=rig` calls) logged and returned normally in
+the same window — so the request IS reaching the origin and being worked, just not completing
+inside 60–100s.
+
+Cross-checked against `GET https://three.ws/api/forge?health=1` (fast, 1.5s): `nvidia`,
+`huggingface`, and `trellis` backends all report `status: "ok"` (auth/quota checks pass), but
+`limiter.status: "down"` ("The rate-limiter store is unconfigured — paid generation lanes fail
+closed"). Tracing the code path (`api/forge.js` → `runNvidiaTextLane` →
+`api/_providers/nvidia.js`, `SUBMIT_TIMEOUT_MS = 45_000`) shows the free NIM lane has its own
+45s submit timeout before falling back to the image-intermediate TRELLIS/FLUX lane inside the
+*same* request — so a cold/degraded NIM gateway plus a slow fallback can legitimately push
+total server-side latency past the 90–100s window a reviewer's client will wait, even though
+every individual upstream call is timeout-bounded and the handler is designed to degrade
+gracefully (see `runForgeFree`'s retry/durability logic in `mcp-server/src/tools/_studio-core.js`).
+This reads as a **live reliability regression in the free lane**, not a flaw in the reviewer
+guide or the review-mode entitlement — but it means the guide's central "free end-to-end
+proof" claim is **not reproducible right now** and must be re-verified green immediately
+before the Claude Connectors Directory submission is filed. Action for whoever files the
+submission: re-run `forge_free` right before submitting; if it still hangs, treat as a P1 (the
+free path is the whole point of the reviewer story) — check `/api/forge?health=1` first, and
+if `nvidia`/`huggingface`/`trellis` all show `ok` while a live submit still hangs, the fault is
+in the submit/fallback chain latency, not backend availability.
+
+### B. Review-mode entitlement is self-activatable on the stdio transport (architectural note)
+
+`reviewModeActive()` (`mcp-server/src/payments.js`) is a straight string-equality check between
+two `process.env` reads — `MCP_REVIEW_SECRET` and `MCP_REVIEW_MODE`. Because this connector's
+transport is **stdio** (the "server" is the same local `npx`-spawned process the caller
+controls), there is no operator-vs-caller boundary to enforce the shared-secret model against:
+anyone installing the package can pass `-e MCP_REVIEW_SECRET=x -e MCP_REVIEW_MODE=x` themselves
+and activate review mode for free — no operator provisioning required. This is real, working
+code (not a mock), so it satisfies prompt 02's "no mock bypass" requirement, but it is **not**
+a reviewer-exclusive gate the way an OAuth-flagged account would be.
+
+Actual exposure is bounded, checked per tool family:
+- **Read tools that proxy to already-public three.ws endpoints** (`aixbt_intel` →
+ `/api/aixbt/intel`, `sentiment_pulse` → `/api/social/sentiment-pulse`, etc.) — those HTTP
+ endpoints are public and unauthenticated already (rate-limited only), so self-activating
+ review mode just skips a $0.01–$0.01 convenience fee on data anyone could `curl` for free
+ regardless. Low/no real exposure.
+- **Generation tools that need real vendor credentials** (`text_to_avatar` needs
+ `REPLICATE_API_TOKEN`+`REPLICATE_TEXT_TO_AVATAR_MODEL` in the *caller's own* local env) —
+ review mode alone does not unlock these; a self-activator without those keys still gets a
+ clean `not_configured` error, exactly as demonstrated in §3 above.
+- **`vanity_grinder`** runs its grind loop as real local/CPU work regardless of payment gate,
+ so bypassing the charge only saves the caller their own compute cost, not the operator's.
+
+Net: this is a known trade-off of the shared-secret pattern applied to a stdio transport, not
+a code defect — flagging for owner awareness, not blocking submission. If tighter enforcement
+is wanted later, the fix is architectural (move the paid-tool-bypass decision to something the
+caller cannot self-supply, e.g. an OAuth-gated remote transport instead of stdio-local env
+vars) and is out of scope for this prompt.
diff --git a/public/changelog.json b/public/changelog.json
index c5a5e37ff..c3f72e8bc 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T00:57:16.888Z",
+ "generated_at": "2026-07-08T00:58:37.633Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 7b0b17212..a638a9775 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T00:57:16.867Z",
+ "generated_at": "2026-07-08T00:58:37.616Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/restyle.js b/src/restyle.js
index 91c03b55b..c994a5293 100644
--- a/src/restyle.js
+++ b/src/restyle.js
@@ -327,7 +327,6 @@ function wireControls() {
el['gen-variants'].addEventListener('click', generateVariants);
el.reset.addEventListener('click', resetModel);
el.export.addEventListener('click', exportModel);
- el['ai-run'].addEventListener('click', aiRestyle);
el.retry.addEventListener('click', () => loadModel(DEFAULT_MODEL, 'sample'));
el.file.addEventListener('change', (e) => {