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: cosmetic economy, chat-model/text-extract hardening, x402 cosmetic purchase

nirholas7d7d357156f8
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index 3f592702c..4af3a8994 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -15,6 +15,32 @@
const memCache = new Map();
const MEM_DEFAULT_TTL_MS = 60_000;
+// Short read-through memo, in front of Redis even when Redis is configured.
+// A warm serverless instance often serves a burst of identical hot reads
+// (trending, token config, marketplace listings) within a second or two; without
+// this, each one spends a Redis GET and at platform scale that volume alone can
+// exhaust the Upstash request quota. We hold the last value for MEMO_TTL_MS so
+// repeated reads collapse to a single Redis round-trip per key per window. Writes
+// (cacheSet/cacheDel) refresh/clear the memo so we never serve a value we just
+// overwrote. Bounded: a few seconds of staleness on cache data is invisible.
+const readMemo = new Map();
+const MEMO_TTL_MS = 2_000;
+const MEMO_MAX_ENTRIES = 5_000; // backstop against unbounded key cardinality
+
+function memoGet(key) {
+ const hit = readMemo.get(key);
+ if (!hit) return undefined; // undefined = no memo; null is a cached "miss"
+ if (Date.now() > hit.expiresAt) {
+ readMemo.delete(key);
+ return undefined;
+ }
+ return hit.value;
+}
+function memoPut(key, value) {
+ if (readMemo.size >= MEMO_MAX_ENTRIES) readMemo.clear();
+ readMemo.set(key, { value, expiresAt: Date.now() + MEMO_TTL_MS });
+}
+
function memSet(key, value, ttlSeconds) {
const ttlMs = (ttlSeconds && ttlSeconds * 1000) || MEM_DEFAULT_TTL_MS;
memCache.set(key, { value, expiresAt: Date.now() + ttlMs });
@@ -53,10 +79,13 @@ async function redisCmd(args) {
export async function cacheGet(key) {
if (!redisConfigured()) return memGet(key);
+ const memo = memoGet(key);
+ if (memo !== undefined) return memo;
try {
const raw = await redisCmd(['GET', key]);
- if (raw == null) return null;
- return JSON.parse(raw);
+ const value = raw == null ? null : JSON.parse(raw);
+ memoPut(key, value);
+ return value;
} catch (err) {
console.warn('[cache] redis GET failed, using memory fallback:', err?.message);
return memGet(key);
@@ -68,13 +97,16 @@ export async function cacheSet(key, value, ttlSeconds = 60) {
try {
const payload = JSON.stringify(value);
await redisCmd(['SET', key, payload, 'EX', String(ttlSeconds)]);
+ memoPut(key, value); // keep the memo coherent with what we just wrote
} catch (err) {
console.warn('[cache] redis SET failed, using memory fallback:', err?.message);
+ readMemo.delete(key);
memSet(key, value, ttlSeconds);
}
}
export async function cacheDel(key) {
+ readMemo.delete(key);
if (!redisConfigured()) return memDel(key);
try {
await redisCmd(['DEL', key]);
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
index efd0923e4..28cc1646a 100644
--- a/api/_lib/chat-models.js
+++ b/api/_lib/chat-models.js
@@ -1,13 +1,102 @@
-// Canonical chat model + provider defaults — the single source of truth shared
+// Canonical chat model + provider routing — the single source of truth shared
// by every LLM chat backend (api/chat.js, api/widgets, api/brain, ...).
//
-// The platform default is OpenAI's GPT-OSS 120B served via OpenRouter's free
-// tier — the exact model the /chat app uses (chat/src/stores.js) and the one
-// we standardise on across every chat surface. Groq and OpenRouter free models
-// are the no-sign-in tier; paid providers (OpenAI, Anthropic) sit behind keys.
+// Two design rules drive this file:
+//
+// 1. RELIABILITY-FIRST ORDERING. The fallback ladder leads with the model
+// that actually answers on the first attempt under current operating
+// conditions, not the cheapest model. Leading with rate-limited free
+// models meant the common path was "try 3-4 things that 429/404, then
+// finally succeed" — paying full fan-out latency and burning quota on
+// every turn. Free models are kept as *lower-priority* fallbacks.
+//
+// 2. CAPABILITY-AWARE ROUTING. Every model is annotated with what it can do
+// ({ tools, moderationGated }). The router consults MODEL_CATALOG and
+// skips models a request can't use (e.g. a tool-required request never
+// selects a non-tool model) instead of round-tripping to the provider to
+// discover the limitation at call time.
+//
+// Permanently-broken routes have been removed from the catalog rather than
+// carried as dead weight (they would never succeed):
+// - mistralai/mistral-7b-instruct:free → OpenRouter 404 "No endpoints found"
+// - meta-llama/llama-3.2-3b-instruct:free → no tool-capable endpoint
+//
+// Operational note (ops must act): the OpenAI account is over quota
+// ("You exceeded your current quota, please check your plan and billing"), so
+// `openai` is intentionally ranked LAST — it is effectively a dead final tier
+// until billing is topped up. Until then it only burns one wasted attempt at
+// the very end of an already-exhausted chain. Top up OPENAI billing or remove
+// the key to drop it from the ladder entirely.
+
+/**
+ * Capability metadata per chat model id — the routing brain. Only models
+ * listed here are auto-selectable; the router uses these flags to avoid
+ * calling a model a request can't use.
+ *
+ * provider — which upstream serves this model id
+ * tools — exposes a tool/function-calling endpoint
+ * moderationGated — upstream intermittently refuses without a moderation /
+ * data policy (OpenRouter 403 "requires moderation"). Such
+ * models are excluded from auto-built fallback chains but
+ * remain usable when a caller names them explicitly.
+ */
+export const MODEL_CATALOG = {
+ // ── Anthropic (paid; host or BYOK key) — most reliable when keyed ──────────
+ 'claude-opus-4-7': { provider: 'anthropic', tools: true },
+ 'claude-opus-4-6': { provider: 'anthropic', tools: true },
+ 'claude-sonnet-4-6': { provider: 'anthropic', tools: true },
+ 'claude-haiku-4-5-20251001': { provider: 'anthropic', tools: true },
+
+ // ── Groq free tier — fast (sub-second) and first-attempt-reliable ─────────
+ 'llama-3.3-70b-versatile': { provider: 'groq', tools: true },
+ 'llama-3.1-8b-instant': { provider: 'groq', tools: true },
+
+ // ── OpenRouter free tier — rate-limited per model; tool support varies ────
+ 'meta-llama/llama-3.3-70b-instruct:free': { provider: 'openrouter', tools: true },
+ 'nousresearch/hermes-3-llama-3.1-405b:free': { provider: 'openrouter', tools: true },
+ // GPT-OSS 120B is the historical platform default, but its free OpenRouter
+ // endpoint is intermittently moderation-gated (403 "requires moderation on
+ // OpenInference"). Kept usable for explicit callers (e.g. the /chat app), but
+ // never auto-selected for the primary path or auto-built fallback chains.
+ 'openai/gpt-oss-120b:free': { provider: 'openrouter', tools: true, moderationGated: true },
+
+ // ── OpenAI (paid) — see operational note above; ranked last ───────────────
+ 'gpt-4o-mini': { provider: 'openai', tools: true },
+};
-/** OpenAI GPT-OSS 120B on OpenRouter, free tier. The platform-wide default. */
-export const DEFAULT_FREE_MODEL = 'openai/gpt-oss-120b:free';
+/** Whether a model exposes a tool/function-calling endpoint. Unknown → false. */
+export function modelSupportsTools(modelId) {
+ return MODEL_CATALOG[modelId]?.tools === true;
+}
+
+/** Whether a model's upstream is moderation-gated (excluded from auto chains). */
+export function isModelModerationGated(modelId) {
+ return MODEL_CATALOG[modelId]?.moderationGated === true;
+}
+
+/**
+ * Filter a candidate model list down to those usable for a request.
+ * @param {string[]} models candidate model ids, in priority order
+ * @param {object} opts
+ * @param {boolean} opts.requireTools drop models with no tool endpoint
+ * @param {boolean} opts.allowGated keep moderation-gated models (default false)
+ */
+export function usableModels(models, { requireTools = false, allowGated = false } = {}) {
+ return models.filter((m) => {
+ const meta = MODEL_CATALOG[m];
+ if (!meta) return false;
+ if (requireTools && !meta.tools) return false;
+ if (!allowGated && meta.moderationGated) return false;
+ return true;
+ });
+}
+
+/**
+ * Default OpenRouter free model: the reliable, tool-capable Llama 3.3 70B free
+ * endpoint. (Was GPT-OSS 120B, demoted for the moderation gate above.) Used as
+ * the platform default wherever a free OpenRouter model is requested.
+ */
+export const DEFAULT_FREE_MODEL = 'meta-llama/llama-3.3-70b-instruct:free';
/** Default per-provider model when the caller doesn't name one. */
export const PROVIDER_MODEL_DEFAULTS = {
@@ -18,22 +107,41 @@ export const PROVIDER_MODEL_DEFAULTS = {
};
/**
- * Order to try providers in when none is explicitly requested ("auto").
- * Free-first: GPT-OSS 120B on OpenRouter, then Groq, then paid keys. Keeps the
- * unauthenticated/default experience on the free GPT-OSS model everywhere.
+ * Provider order to try when none is explicitly requested ("auto"), ranked by
+ * first-attempt reliability under current operating conditions:
+ * 1. groq — fast free tier that answers on the first attempt; the
+ * common-case primary. Per-minute caps only.
+ * 2. openrouter — free fallback (reliable Llama 3.3 70B; see DEFAULT_FREE_MODEL).
+ * 3. anthropic — paid, highly reliable, but only present when a key is
+ * configured (BYOK / host we-pay); skipped otherwise.
+ * 4. openai — LAST. Account is over quota (see operational note); only
+ * reached after everything else is exhausted.
+ * Providers without a configured key are skipped, so the effective ladder is
+ * short in the common case.
*/
-export const DEFAULT_PROVIDER_ORDER = ['openrouter', 'groq', 'openai', 'anthropic'];
+export const DEFAULT_PROVIDER_ORDER = ['groq', 'openrouter', 'anthropic', 'openai'];
/**
* OpenRouter sibling models for per-model rate-limit failover. OpenRouter's
- * `:free` tier rate-limits per model, so a GPT-OSS burst degrades to Llama then
- * Mistral (all free) before the chain moves to the next provider. GPT-OSS leads.
+ * `:free` tier rate-limits per model, so a burst on the primary free model
+ * degrades to a sibling free model before the chain moves to the next provider.
+ * All entries are tool-capable and non-gated (dead/gated routes removed).
*/
export const OPENROUTER_SIBLINGS = [
DEFAULT_FREE_MODEL,
- 'meta-llama/llama-3.3-70b-instruct:free',
- 'mistralai/mistral-7b-instruct:free',
+ 'nousresearch/hermes-3-llama-3.1-405b:free',
];
/** Providers an anonymous (unauthenticated) caller may use — free tiers only. */
-export const ANON_PROVIDER_LIST = ['openrouter', 'groq'];
+export const ANON_PROVIDER_LIST = ['groq', 'openrouter'];
+
+/**
+ * Bounds on the fallback chain so a single request can't churn through every
+ * provider and still time out. The router stops failing over once either limit
+ * is hit and returns a clean terminal error.
+ * MAX_FALLBACK_ATTEMPTS — hard cap on upstream attempts per request.
+ * TOTAL_BUDGET_MS — wall-clock budget across all attempts (< the 60s
+ * function limit, leaving headroom to stream a reply).
+ */
+export const MAX_FALLBACK_ATTEMPTS = 3;
+export const TOTAL_BUDGET_MS = 25_000;
diff --git a/api/_lib/cosmetics-ownership.js b/api/_lib/cosmetics-ownership.js
new file mode 100644
index 000000000..77630d4e6
--- /dev/null
+++ b/api/_lib/cosmetics-ownership.js
@@ -0,0 +1,101 @@
+// Cosmetic ownership ledger (R22) — the durable record of which premium
+// cosmetics an account has purchased over the x402 USDC rail.
+//
+// It lives in the SAME persistence the rest of the /play economy uses — Upstash
+// Redis (REST), the store playerStore.js and presence-store.js already speak —
+// so there's no new provider to operate. Ownership is keyed by the player's
+// stable ACCOUNT id (their Solana wallet once authenticated, otherwise the guest
+// id the client persists), NOT by the paying wallet: a buyer can settle the USDC
+// on Base or Solana, and the cosmetic still lands on the account they bought it
+// for. Each account is one Redis SET, `cosmetics:owned:<account>`, holding the
+// catalog ids it owns — so a grant is naturally idempotent (owning a cosmetic
+// twice is owning it once) and a read is a single SMEMBERS.
+//
+// Ownership is written ONLY here, by the verified-payment handler in
+// api/x402/cosmetic-purchase.js. The shop (R21) and the owned-inventory (R23)
+// read it. Reads degrade gracefully to "owns nothing" if Redis is unreachable —
+// the shop still renders, items just show as lockable. Grants FAIL CLOSED: if we
+// can't persist the unlock we throw, so the x402 flow never settles a charge it
+// can't record (matching the fail-closed invariants in x402-security-hardening).
+
+import { Redis } from '@upstash/redis';
+import { env } from './env.js';
+
+const OWNED_PREFIX = 'cosmetics:owned:';
+// Refreshed on every grant. Long enough that a returning player keeps their
+// purchases; bounds abandoned-guest growth the same way playerStore does.
+const OWNED_TTL_S = 60 * 60 * 24 * 365 * 2; // 2 years
+
+let _redis = null;
+let _redisTried = false;
+function redis() {
+ if (_redisTried) return _redis;
+ _redisTried = true;
+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
+ _redis = new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });
+ }
+ return _redis;
+}
+
+// True when a durable ownership store is configured. The purchase endpoint uses
+// this to fail closed in production (refuse to settle without somewhere to record
+// the unlock) rather than charge for a cosmetic it would immediately lose.
+export function ownershipStoreConfigured() {
+ return !!redis();
+}
+
+// Account ids must be a Solana wallet (base58) or a guest id like `g_xxxx`. Bound
+// the charset + length so a crafted value can't escape the keyspace or balloon a
+// key. Returns the trimmed id, or '' when it isn't a usable account id.
+export function normalizeAccountId(raw) {
+ const id = String(raw ?? '').trim();
+ if (id.length < 3 || id.length > 64) return '';
+ if (!/^[A-Za-z0-9_:-]+$/.test(id)) return '';
+ return id;
+}
+
+// Grant ownership of `cosmeticId` to `account`. Idempotent — returns true when it
+// newly unlocked the item, false when the account already owned it. Throws (fail
+// closed) when no durable store is configured, so a caller never reports an
+// unlock it didn't persist.
+export async function grantCosmeticOwnership(account, cosmeticId) {
+ const r = redis();
+ if (!r) {
+ const err = new Error('cosmetic ownership store is not configured (UPSTASH_REDIS_REST_URL/_TOKEN)');
+ err.status = 503;
+ err.code = 'ownership_store_unavailable';
+ throw err;
+ }
+ const key = OWNED_PREFIX + account;
+ const added = await r.sadd(key, cosmeticId);
+ // Refresh the TTL on every write so an actively-collecting account never ages
+ // out. A best-effort expire — the SADD above is the durable part.
+ r.expire(key, OWNED_TTL_S).catch(() => {});
+ return added === 1;
+}
+
+// The premium cosmetic ids `account` owns. Degrades to [] on any store error or
+// when no store is configured — the shop renders either way.
+export async function readOwnedCosmetics(account) {
+ const r = redis();
+ if (!r || !account) return [];
+ try {
+ const members = await r.smembers(OWNED_PREFIX + account);
+ return Array.isArray(members) ? members : [];
+ } catch (err) {
+ console.warn('[cosmetics-ownership] read failed:', err?.message);
+ return [];
+ }
+}
+
+// Does `account` own `cosmeticId`? Degrades to false on any store error.
+export async function ownsCosmetic(account, cosmeticId) {
+ const r = redis();
+ if (!r || !account) return false;
+ try {
+ return (await r.sismember(OWNED_PREFIX + account, cosmeticId)) === 1;
+ } catch (err) {
+ console.warn('[cosmetics-ownership] ownership check failed:', err?.message);
+ return false;
+ }
+}
diff --git a/api/_lib/cosmetics.js b/api/_lib/cosmetics.js
new file mode 100644
index 000000000..3a544a00b
--- /dev/null
+++ b/api/_lib/cosmetics.js
@@ -0,0 +1,153 @@
+// Cosmetics catalog — the single source of truth for the avatar shop (R21) and
+// the x402 purchase flow (R22) / owned-inventory (R23) that build on it.
+//
+// Each entry is both a SHOP item (id, name, slot, rarity, price, previewImage)
+// and the RIG payload the live-preview needs (kind + glbUrl/attachBone for
+// bone-attached accessories, morphBinding for outfits, colors for skins, emote
+// for premium animations). Wearable accessory ids mirror
+// public/accessories/presets.json so the R03 rig attaches them identically.
+//
+// Pricing is denominated in $THREE (CA FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump),
+// the only coin this platform references. R22 charges these amounts over x402.
+//
+// Ownership model (until R23 wires wallet-bound inventory): the base accessory
+// pack ships with every avatar and is OWNED; premium emotes + skins are LOCKED
+// until purchased. `premium: false` ⇒ owned, `premium: true` ⇒ locked.
+
+export const RARITIES = ['common', 'rare', 'epic', 'legendary'];
+
+// $THREE price by rarity. Premium items charge; owned base items are free (0).
+const PRICE_BY_RARITY = { common: 25, rare: 100, epic: 300, legendary: 750 };
+
+// USDC settlement price by rarity, in atomics (6 decimals). $THREE is the coin
+// the shop *quotes* (PRICE_BY_RARITY, coin-facing copy); USDC is the asset the
+// x402 rail actually *settles* (R22). The two are deliberately separate: the
+// catalog shows an item's $THREE value, checkout charges this USDC amount over
+// x402. Tunable per rarity at deploy time via X402_PRICE_COSMETIC_<RARITY>.
+const USDC_ATOMICS_BY_RARITY = {
+ common: '250000', // $0.25
+ rare: '500000', // $0.50
+ epic: '1500000', // $1.50
+ legendary: '3000000', // $3.00
+};
+
+// The USDC charge (atomics, 6 decimals) for an item's x402 purchase. Owned base
+// items are free ('0'). Reads an env override first so ops can retune unit
+// economics without a code change; falls back to the rarity default. The server
+// is the sole source of this number — the client never supplies a price.
+export function priceUsdcAtomicsOf(item) {
+ if (!item?.premium) return '0';
+ const key = `X402_PRICE_COSMETIC_${String(item.rarity || '').toUpperCase()}`;
+ const raw = process.env[key];
+ if (raw != null && /^\d+$/.test(String(raw).trim())) return String(raw).trim();
+ return USDC_ATOMICS_BY_RARITY[item.rarity] ?? USDC_ATOMICS_BY_RARITY.rare;
+}
+
+// Human-readable USDC price (whole dollars, 2dp) for shop copy — e.g. '0.50'.
+export function priceUsdcDisplayOf(item) {
+ return (Number(priceUsdcAtomicsOf(item)) / 1e6).toFixed(2);
+}
+
+// Slots double as the R03 per-slot attachment category and the shop filter axis.
+export const SLOTS = ['hat', 'glasses', 'earrings', 'outfit', 'skin', 'emote'];
+
+// The catalog. Order here is the shop's default display order.
+const CATALOG = [
+ // ── Base accessory pack (owned, free) — bone-attached GLBs ────────────────
+ { id: 'hat-baseball', name: 'Baseball Cap', slot: 'hat', kind: 'hat', rarity: 'common',
+ glbUrl: '/accessories/hat-baseball.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/hat-baseball.png' },
+ { id: 'hat-beanie', name: 'Beanie', slot: 'hat', kind: 'hat', rarity: 'common',
+ glbUrl: '/accessories/hat-beanie.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/hat-beanie.png' },
+ { id: 'hat-cowboy', name: 'Cowboy Hat', slot: 'hat', kind: 'hat', rarity: 'rare',
+ glbUrl: '/accessories/hat-cowboy.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/hat-cowboy.png' },
+ { id: 'glasses-round', name: 'Round Glasses', slot: 'glasses', kind: 'glasses', rarity: 'common',
+ glbUrl: '/accessories/glasses-round.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/glasses-round.png' },
+ { id: 'glasses-shades', name: 'Shades', slot: 'glasses', kind: 'glasses', rarity: 'rare',
+ glbUrl: '/accessories/glasses-shades.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/glasses-shades.png' },
+ { id: 'earrings-hoops', name: 'Hoop Earrings', slot: 'earrings', kind: 'earrings', rarity: 'common',
+ glbUrl: '/accessories/earrings-hoops.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/earrings-hoops.png' },
+ { id: 'earrings-studs', name: 'Stud Earrings', slot: 'earrings', kind: 'earrings', rarity: 'common',
+ glbUrl: '/accessories/earrings-studs.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/earrings-studs.png' },
+
+ // ── Outfit morphs (owned, free) — drive the avatar's own morph targets ────
+ { id: 'outfit-casual', name: 'Casual Fit', slot: 'outfit', kind: 'outfit', rarity: 'common',
+ morphBinding: { Outfit_Casual: 1.0 }, previewImage: null },
+ { id: 'outfit-sporty', name: 'Sporty Fit', slot: 'outfit', kind: 'outfit', rarity: 'common',
+ morphBinding: { Outfit_Sporty: 1.0 }, previewImage: null },
+ { id: 'outfit-formal', name: 'Formal Fit', slot: 'outfit', kind: 'outfit', rarity: 'rare',
+ morphBinding: { Outfit_Formal: 1.0 }, previewImage: null },
+
+ // ── Premium skins (locked) — recolour the avatar's garment layers ─────────
+ { id: 'skin-crimson', name: 'Crimson Threads', slot: 'skin', kind: 'skin', rarity: 'rare', premium: true,
+ colors: { outfit: '#7a1d1d' }, previewImage: null },
+ { id: 'skin-whiteout', name: 'Whiteout', slot: 'skin', kind: 'skin', rarity: 'epic', premium: true,
+ colors: { outfit: '#f1f1f4' }, previewImage: null },
+ { id: 'skin-midnight', name: 'Midnight', slot: 'skin', kind: 'skin', rarity: 'legendary', premium: true,
+ colors: { outfit: '#0c0c14', hair: '#101018' }, previewImage: null },
+ { id: 'skin-gold', name: 'Liquid Gold', slot: 'skin', kind: 'skin', rarity: 'legendary', premium: true,
+ colors: { outfit: '#caa64a', hair: '#8a6f2a' }, previewImage: null },
+
+ // ── Premium emotes (locked) — one-shot animation clips (manifest names) ────
+ { id: 'emote-headbang', name: 'Headbang', slot: 'emote', kind: 'emote', rarity: 'rare', premium: true,
+ emote: 'av-headbang', previewImage: null },
+ { id: 'emote-shuffle', name: 'Shuffle', slot: 'emote', kind: 'emote', rarity: 'rare', premium: true,
+ emote: 'av-dance-shuffle', previewImage: null },
+ { id: 'emote-rumba', name: 'Rumba', slot: 'emote', kind: 'emote', rarity: 'epic', premium: true,
+ emote: 'rumba', previewImage: null },
+ { id: 'emote-capoeira', name: 'Capoeira', slot: 'emote', kind: 'emote', rarity: 'epic', premium: true,
+ emote: 'capoeira', previewImage: null },
+ { id: 'emote-thriller', name: 'Thriller', slot: 'emote', kind: 'emote', rarity: 'legendary', premium: true,
+ emote: 'thriller', previewImage: null },
+];
+
+const BY_ID = new Map(CATALOG.map((c) => [c.id, c]));
+
+export function getCosmetic(id) {
+ return BY_ID.get(id) || null;
+}
+
+export function isValidCosmeticId(id) {
+ return BY_ID.has(id);
+}
+
+// The $THREE price of an item (premium items only; owned base items are free).
+export function priceOf(item) {
+ if (!item?.premium) return 0;
+ return PRICE_BY_RARITY[item.rarity] ?? PRICE_BY_RARITY.common;
+}
+
+// Build the catalog as the API/client consume it. `ownedIds` is the set of
+// extra ids the caller owns (purchased — wired in R23); base non-premium items
+// are always owned. `rarity` optionally filters to one rarity tier.
+export function buildCatalog({ ownedIds = [], rarity = null } = {}) {
+ const owned = new Set(ownedIds);
+ return CATALOG
+ .filter((c) => !rarity || c.rarity === rarity)
+ .map((c) => {
+ const isOwned = !c.premium || owned.has(c.id);
+ const price = priceOf(c);
+ return {
+ id: c.id,
+ name: c.name,
+ slot: c.slot,
+ kind: c.kind,
+ rarity: c.rarity,
+ price,
+ // $THREE is the only coin — the item's quoted value is in it.
+ currency: 'THREE',
+ // What the x402 rail actually charges at checkout: USDC (R22). Atomics
+ // (6dp) for the protocol + a display string for the buy button.
+ priceUsdcAtomics: priceUsdcAtomicsOf(c),
+ priceUsdc: priceUsdcDisplayOf(c),
+ premium: !!c.premium,
+ owned: isOwned,
+ locked: !isOwned,
+ previewImage: c.previewImage || null,
+ // Rig payload the live preview needs — only the relevant keys per kind.
+ ...(c.glbUrl ? { glbUrl: c.glbUrl, attachBone: c.attachBone } : {}),
+ ...(c.morphBinding ? { morphBinding: c.morphBinding } : {}),
+ ...(c.colors ? { colors: c.colors } : {}),
+ ...(c.emote ? { emote: c.emote } : {}),
+ };
+ });
+}
diff --git a/api/_lib/migrations/20260605000000_cosmetic_economy.sql b/api/_lib/migrations/20260605000000_cosmetic_economy.sql
new file mode 100644
index 000000000..7ebd439f5
--- /dev/null
+++ b/api/_lib/migrations/20260605000000_cosmetic_economy.sql
@@ -0,0 +1,93 @@
+-- Migration: cosmetic creator revenue splits + sales ledger + ownership (R25).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260605000000_cosmetic_economy.sql
+-- (or `npm run db:migrate`). Idempotent — safe to re-run.
+--
+-- The /play avatar economy sells premium cosmetics for $THREE inside coin
+-- communities (each /play world IS a pump.fun coin, keyed by its mint). When a
+-- cosmetic sells inside a coin's world the settled $THREE splits a configurable
+-- share to that coin's creator wallet — a REAL on-chain leg in the buyer's
+-- single signed transaction (see multiplayer/src/game-token.js buildTokenPurchase
+-- with a `creator` leg). These tables are the queryable record of:
+--
+-- 1. cosmetic_creator_splits — per-coin config: the creator wallet that
+-- receives the share and the share itself (basis points, creator-adjustable
+-- within a platform-enforced ceiling). A missing row means "use the platform
+-- default share, resolve the creator from launch records".
+-- 2. cosmetic_sales — one row per settled purchase, idempotent on the on-chain
+-- signature. Carries every split leg so the creator-earnings dashboard and
+-- the platform leaderboard read only real, settled numbers.
+-- 3. cosmetic_ownership — (wallet, cosmetic) the buyer owns, readable by the
+-- boutique (owned vs. locked) and the rarest-fits flex surface.
+
+begin;
+
+-- Per-coin split configuration. `creator_wallet` is the Solana address that
+-- receives the creator share; `split_bps` is that share in basis points
+-- (0..10000). Both are clamped in application code to a sane ceiling.
+create table if not exists cosmetic_creator_splits (
+ mint text primary key, -- base58 coin mint (the /play world)
+ creator_wallet text not null, -- base58 Solana address that earns the share
+ split_bps integer not null
+ check (split_bps >= 0 and split_bps <= 10000),
+ updated_by text, -- wallet that last set this (the creator)
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- Settled cosmetic sales. One row per confirmed on-chain purchase. `tx_signature`
+-- is unique so a replayed settle can never double-record (and the unlock grant is
+-- idempotent regardless). Every split leg is stored in $THREE base units (strings
+-- would lose bigint range; columns are numeric(20,0) to hold raw 6-decimal totals).
+create table if not exists cosmetic_sales (
+ id uuid primary key default gen_random_uuid(),
+ tx_signature text not null unique, -- on-chain proof; idempotency key
+ buyer_wallet text not null, -- base58 buyer
+ mint text not null, -- coin world the sale was tied to
+ cosmetic_id text not null, -- catalog id (e.g. 'aura-gold')
+ rarity text not null default 'common', -- denormalized for the leaderboard
+ price_three_raw numeric(20,0) not null, -- total $THREE charged (base units)
+ creator_wallet text, -- recipient of the creator leg (null = none)
+ creator_raw numeric(20,0) not null default 0, -- creator leg (base units)
+ treasury_raw numeric(20,0) not null default 0, -- treasury leg
+ burn_raw numeric(20,0) not null default 0, -- burned leg
+ split_bps integer not null default 0, -- creator share applied at settle time
+ settled_at timestamptz not null default now()
+);
+
+create index if not exists cosmetic_sales_creator
+ on cosmetic_sales (creator_wallet, settled_at desc)
+ where creator_wallet is not null;
+
+create index if not exists cosmetic_sales_mint
+ on cosmetic_sales (mint, settled_at desc);
+
+create index if not exists cosmetic_sales_buyer
+ on cosmetic_sales (buyer_wallet, settled_at desc);
+
+create index if not exists cosmetic_sales_cosmetic
+ on cosmetic_sales (cosmetic_id);
+
+-- Owned premium cosmetics. A wallet owns a cosmetic at most once; `mint` records
+-- the world the unlock was first bought in (so the flex surface can link a fit
+-- back to where it was earned). Readable by the boutique (owned state) downstream.
+create table if not exists cosmetic_ownership (
+ buyer_wallet text not null,
+ cosmetic_id text not null,
+ mint text, -- world the unlock was first bought in
+ first_acquired_at timestamptz not null default now(),
+ primary key (buyer_wallet, cosmetic_id)
+);
+
+create index if not exists cosmetic_ownership_wallet
+ on cosmetic_ownership (buyer_wallet);
+
+create index if not exists cosmetic_ownership_cosmetic
+ on cosmetic_ownership (cosmetic_id);
+
+-- Auto-bump updated_at on the config table; reuse the standard trigger fn.
+do $$ begin
+ create trigger cosmetic_creator_splits_set_updated_at before update on cosmetic_creator_splits
+ for each row execute function set_updated_at();
+exception when undefined_function then null; when duplicate_object then null; end $$;
+
+commit;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 31da7a7d2..7fe3103e6 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -71,8 +71,61 @@ function getLimiter(name, opts) {
prefix: `rl:${name}`,
analytics: false,
});
- limiters.set(key, rl);
- return rl;
+ const resilient = resilientLimiter(rl, name, opts);
+ limiters.set(key, resilient);
+ return resilient;
+}
+
+// One warn per limiter name per cooldown — a Redis outage hits every request,
+// so unthrottled logging would itself become a denial-of-service on the logs.
+const _degradeWarnedAt = new Map();
+const DEGRADE_WARN_COOLDOWN_MS = 60_000;
+function warnDegradedOnce(name, err) {
+ const last = _degradeWarnedAt.get(name) || 0;
+ const t = Date.now();
+ if (t - last < DEGRADE_WARN_COOLDOWN_MS) return;
+ _degradeWarnedAt.set(name, t);
+ console.warn(
+ `[rate-limit] redis degraded for "${name}", limiter served from fallback decision:`,
+ err?.message || err,
+ );
+}
+
+// Wrap a real (Redis-backed) Ratelimit so a Redis error — most importantly the
+// account-wide "max requests limit exceeded" over-quota UpstashError — degrades
+// instead of throwing an unhandled 500 out of every route. Non-critical buckets
+// (the read/public/auth-IP limiters every page hits) FAIL OPEN: a limiter
+// outage must never take down the API. Critical buckets (cost/money-moving)
+// FAIL CLOSED: better to 503 a paid action than allow unbounded spend when the
+// distributed limiter is blind.
+function resilientLimiter(rl, name, opts) {
+ const ms = parseWindowMs(opts.window);
+ const failClosed = Boolean(opts.critical) && IS_PRODUCTION;
+ return {
+ async limit(id) {
+ try {
+ return await rl.limit(id);
+ } catch (err) {
+ warnDegradedOnce(name, err);
+ if (failClosed) {
+ return {
+ success: false,
+ limit: opts.limit,
+ remaining: 0,
+ reset: Date.now() + ms,
+ reason: 'rate_limiter_unavailable',
+ };
+ }
+ return {
+ success: true,
+ limit: opts.limit,
+ remaining: opts.limit,
+ reset: Date.now() + ms,
+ reason: 'rate_limiter_degraded',
+ };
+ }
+ },
+ };
}
function memoryLimiter({ limit, window }) {
diff --git a/api/_lib/siwx-storage.test.js b/api/_lib/siwx-storage.test.js
new file mode 100644
index 000000000..1622e44c6
--- /dev/null
+++ b/api/_lib/siwx-storage.test.js
@@ -0,0 +1,111 @@
+// Integration tests for the Postgres-backed SIWxStorage adapter.
+//
+// These run against the REAL Neon database pointed at by $DATABASE_URL (the
+// same one prompt 01's migration provisioned). When DATABASE_URL is unset —
+// CI without secrets, a fresh clone — every case is skipped via it.skipIf so
+// the suite never silently passes on a mock. There is no in-memory fallback.
+//
+// This file lives next to the source rather than under /tests/* (the SIWX
+// adapter is api/_lib-local). Vitest's include glob does not pick it up
+// automatically; run it explicitly:
+// DATABASE_URL=$DATABASE_URL npx vitest run api/_lib/siwx-storage.test.js
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { randomUUID } from 'node:crypto';
+
+import { sql } from './db.js';
+import {
+ siwxStorage,
+ normalizeAddress,
+ pruneOldNonces,
+} from './siwx-storage.js';
+
+const HAS_DB = Boolean(process.env.DATABASE_URL);
+
+// Every row this suite writes is keyed on a 'test-resource-…' resource so the
+// final teardown can scope its DELETEs and concurrent runs never collide.
+const resource = () => `test-resource-${randomUUID()}`;
+
+describe('siwx-storage', () => {
+ afterAll(async () => {
+ if (!HAS_DB) return;
+ await sql`DELETE FROM siwx_payments WHERE resource LIKE 'test-resource-%'`;
+ await sql`DELETE FROM siwx_nonces WHERE resource LIKE 'test-resource-%'`;
+ });
+
+ it('normalizes addresses per CAIP-2 namespace', () => {
+ expect(normalizeAddress('eip155:8453', '0xAbCdEf')).toBe('0xabcdef');
+ expect(normalizeAddress('solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', 'MiXeDcAsE'))
+ .toBe('MiXeDcAsE');
+ expect(() => normalizeAddress('', '0x1')).toThrow();
+ expect(() => normalizeAddress('cosmos:1', 'addr')).toThrow();
+ });
+
+ it.skipIf(!HAS_DB)('hasPaid returns false for an unknown wallet', async () => {
+ const res = resource();
+ await expect(siwxStorage.hasPaid(res, '0x000000000000000000000000000000000000dead'))
+ .resolves.toBe(false);
+ });
+
+ it.skipIf(!HAS_DB)('round-trips an EVM payment, matching case-insensitively', async () => {
+ const res = resource();
+ const checksummed = '0xAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa';
+ await siwxStorage.recordPayment(res, checksummed, { network: 'eip155:8453' });
+
+ // The contract passes the checksummed (recovered) address to hasPaid;
+ // the lowercased row must still match.
+ await expect(siwxStorage.hasPaid(res, checksummed)).resolves.toBe(true);
+ await expect(siwxStorage.hasPaid(res, checksummed.toLowerCase())).resolves.toBe(true);
+
+ // It was stored lowercased.
+ const [row] = await sql`SELECT address FROM siwx_payments WHERE resource = ${res}`;
+ expect(row.address).toBe(checksummed.toLowerCase());
+ });
+
+ it.skipIf(!HAS_DB)('round-trips a Solana payment, matching case-sensitively', async () => {
+ const res = resource();
+ const addr = 'So1anaTestKey11111111111111111111111111111';
+ await siwxStorage.recordPayment(res, addr, {
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ });
+
+ await expect(siwxStorage.hasPaid(res, addr)).resolves.toBe(true);
+ // A different-case spelling is a different Base58 key — no grant.
+ await expect(siwxStorage.hasPaid(res, addr.toLowerCase())).resolves.toBe(false);
+ });
+
+ it.skipIf(!HAS_DB)('honours a ttlSeconds expiry window', async () => {
+ const res = resource();
+ const addr = '0xBbBbBbBbBbBbBbBbBbBbBbBbBbBbBbBbBbBbBbBb';
+ await siwxStorage.recordPayment(res, addr, { network: 'eip155:8453', ttlSeconds: 1 });
+
+ await expect(siwxStorage.hasPaid(res, addr)).resolves.toBe(true);
+ await new Promise((r) => setTimeout(r, 1500));
+ await expect(siwxStorage.hasPaid(res, addr)).resolves.toBe(false);
+ });
+
+ it.skipIf(!HAS_DB)('round-trips a nonce idempotently', async () => {
+ const res = resource();
+ const nonce = `nonce-${randomUUID()}`;
+
+ await expect(siwxStorage.hasUsedNonce(nonce)).resolves.toBe(false);
+
+ // First claim wins; second is a no-op against the same nonce.
+ await expect(siwxStorage.recordNonce(nonce, { resource: res, address: '0x1' }))
+ .resolves.toBe(true);
+ await expect(siwxStorage.recordNonce(nonce, { resource: res, address: '0x1' }))
+ .resolves.toBe(false);
+
+ await expect(siwxStorage.hasUsedNonce(nonce)).resolves.toBe(true);
+ });
+
+ it.skipIf(!HAS_DB)('pruneOldNonces(0) clears nonces past the replay window', async () => {
+ const res = resource();
+ const nonce = `nonce-${randomUUID()}`;
+ await siwxStorage.recordNonce(nonce, { resource: res, address: '0x1' });
+
+ const deleted = await pruneOldNonces(0);
+ expect(deleted).toBeGreaterThanOrEqual(1);
+ await expect(siwxStorage.hasUsedNonce(nonce)).resolves.toBe(false);
+ });
+});
diff --git a/api/_lib/text-extract.js b/api/_lib/text-extract.js
index b33fa155d..a7597430c 100644
--- a/api/_lib/text-extract.js
+++ b/api/_lib/text-extract.js
@@ -1,8 +1,17 @@
// Server-side helpers for turning a URL into plain text we can chunk + embed.
// PDFs are extracted client-side (pdfjs in the studio bundle) and posted as
// text, so this module only needs to handle HTML / plain content fetches.
+//
+// HTML parsing uses node-html-parser, not jsdom. jsdom (≥27.4) pulls in
+// html-encoding-sniffer@6 → @exodus/bytes, an ESM-only module that
+// html-encoding-sniffer `require()`s — which throws ERR_REQUIRE_ESM at cold
+// start on the deployed Node runtime and crashes the entire widgets serverless
+// function (taking stats/transcripts down with it). node-html-parser is a
+// dependency-light, CJS-clean parser that reproduces our exact extraction
+// (querySelector / remove / textContent with HTML-entity decoding) without the
+// fragile ESM/CJS chain. Our usage is trivial DOM scraping; jsdom was overkill.
-import { JSDOM } from 'jsdom';
+import { parse } from 'node-html-parser';
const FETCH_TIMEOUT_MS = 12_000;
const MAX_BYTES = 4 * 1024 * 1024; // 4 MB hard cap per source
@@ -69,20 +78,22 @@ export async function fetchAndExtract(url) {
};
}
- const dom = new JSDOM(raw);
- const doc = dom.window.document;
- doc.querySelectorAll(
+ const root = parse(raw);
+ root.querySelectorAll(
'script, style, noscript, template, svg, iframe, nav, footer, header, form, [aria-hidden="true"]',
).forEach((el) => el.remove());
const title =
(
- doc.querySelector('meta[property="og:title"]')?.getAttribute('content') ||
- doc.querySelector('title')?.textContent ||
+ root.querySelector('meta[property="og:title"]')?.getAttribute('content') ||
+ root.querySelector('title')?.textContent ||
''
).trim() || derivedTitleFromUrl(u);
- const main = doc.querySelector('article, main, [role="main"], #main, #content') || doc.body;
+ const main =
+ root.querySelector('article, main, [role="main"], #main, #content') ||
+ root.querySelector('body') ||
+ root;
const text = (main?.textContent || '')
.replace(/[ \t]+/g, ' ')
.replace(/\n[ \t]+/g, '\n')
diff --git a/api/_lib/x402/api-keys.js b/api/_lib/x402/api-keys.js
index 974a2fc01..e10c65924 100644
--- a/api/_lib/x402/api-keys.js
+++ b/api/_lib/x402/api-keys.js
@@ -102,32 +102,40 @@ export async function checkRateLimit(subscription, route) {
const redis = getRedis();
if (redis) {
- // Redis sorted-set sliding window: ZREMRANGEBYSCORE drops expired
- // timestamps, ZCARD counts the rest, ZADD writes the new one. EXPIRE
- // keeps the key from leaking when the partner stops calling.
- const cutoff = now - windowMs;
- const member = `${now}:${Math.random().toString(36).slice(2, 10)}`;
- const pipeline = redis.pipeline();
- pipeline.zremrangebyscore(bucketKey, 0, cutoff);
- pipeline.zadd(bucketKey, { score: now, member });
- pipeline.zcard(bucketKey);
- pipeline.expire(bucketKey, Math.ceil(windowMs / 1000) + 5);
- const results = await pipeline.exec();
- const count = Number(results?.[2] ?? 0);
- if (count > limit) {
- // Remove the candidate we just added so it doesn't count against
- // the next legitimate request after the window slides.
- await redis.zrem(bucketKey, member);
- const oldest = await redis.zrange(bucketKey, 0, 0, { withScores: true });
- const resetAt = oldest?.length >= 2 ? Number(oldest[1]) + windowMs : now + windowMs;
- return { allowed: false, remaining: 0, limit, resetAt };
+ try {
+ // Redis sorted-set sliding window: ZREMRANGEBYSCORE drops expired
+ // timestamps, ZCARD counts the rest, ZADD writes the new one. EXPIRE
+ // keeps the key from leaking when the partner stops calling.
+ const cutoff = now - windowMs;
+ const member = `${now}:${Math.random().toString(36).slice(2, 10)}`;
+ const pipeline = redis.pipeline();
+ pipeline.zremrangebyscore(bucketKey, 0, cutoff);
+ pipeline.zadd(bucketKey, { score: now, member });
+ pipeline.zcard(bucketKey);
+ pipeline.expire(bucketKey, Math.ceil(windowMs / 1000) + 5);
+ const results = await pipeline.exec();
+ const count = Number(results?.[2] ?? 0);
+ if (count > limit) {
+ // Remove the candidate we just added so it doesn't count against
+ // the next legitimate request after the window slides.
+ await redis.zrem(bucketKey, member);
+ const oldest = await redis.zrange(bucketKey, 0, 0, { withScores: true });
+ const resetAt = oldest?.length >= 2 ? Number(oldest[1]) + windowMs : now + windowMs;
+ return { allowed: false, remaining: 0, limit, resetAt };
+ }
+ return {
+ allowed: true,
+ remaining: Math.max(0, limit - count),
+ limit,
+ resetAt: now + windowMs,
+ };
+ } catch (err) {
+ // Redis down/over-quota: fail open so a paid subscriber isn't 500'd
+ // when the limiter backend blinks. The partner's spend is still
+ // bounded by the upstream 402 cost and per-account caps.
+ console.warn('[x402/api-keys] rate-limit redis degraded, allowing:', err?.message || err);
+ return { allowed: true, remaining: limit, limit, resetAt: now + windowMs };
}
- return {
- allowed: true,
- remaining: Math.max(0, limit - count),
- limit,
- resetAt: now + windowMs,
- };
}
// In-memory fallback. Single-process correctness only — fine for local
diff --git a/api/chat.js b/api/chat.js
index 8bb9fe93d..868e19905 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -37,6 +37,9 @@ import {
DEFAULT_PROVIDER_ORDER,
OPENROUTER_SIBLINGS,
ANON_PROVIDER_LIST,
+ MODEL_CATALOG,
+ MAX_FALLBACK_ATTEMPTS,
+ TOTAL_BUDGET_MS,
} from './_lib/chat-models.js';
import { z } from 'zod';
@@ -330,10 +333,11 @@ export default wrap(async (req, res) => {
return error(res, 401, 'unauthorized', 'sign in to use this model');
}
// Honor an explicitly-requested free-tier provider (groq/openrouter).
- // Otherwise default to GPT-OSS 120B on OpenRouter — the platform-wide
- // default model — and fall back to Groq when OpenRouter isn't configured.
+ // Otherwise default to Groq — the fast, first-attempt-reliable free tier —
+ // and fall back to OpenRouter's free Llama (DEFAULT_FREE_MODEL) if Groq
+ // isn't configured.
if (!body.provider) {
- body.provider = hasOpenRouter ? 'openrouter' : 'groq';
+ body.provider = hasGroq ? 'groq' : 'openrouter';
if (!body.model && body.provider === 'openrouter') body.model = DEFAULT_FREE_MODEL;
}
anonymous = true;
@@ -391,7 +395,17 @@ export default wrap(async (req, res) => {
// One in-place retry per route on transient gateway errors (503/504) before
// failing over. Reset to false every time we advance to a new route.
let retriedTransient = false;
+ // Bound the whole chain by wall-clock so a request can't churn through every
+ // provider and still time out at the 60s function limit. Once the budget is
+ // spent we stop failing over and surface a clean terminal error. `attempted`
+ // records which provider/model each upstream call hit, so an exhausted chain
+ // can tell the client (and the logs) exactly what failed.
+ const deadline = started + TOTAL_BUDGET_MS;
+ const attempted = [];
+ // Whether another route exists *and* the time budget allows trying it.
+ const canFailOver = () => routeIdx + 1 < fallbackRoutes.length && Date.now() < deadline;
while (true) {
+ attempted.push({ provider: route.name, model: route.model });
try {
// Most routes carry static headers; watsonx resolves a fresh IAM
// bearer token (cached between requests) just before the fetch.
@@ -404,15 +418,17 @@ export default wrap(async (req, res) => {
} catch (err) {
captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });
console.error(`[chat:${route.name}] upstream fetch failed:`, err.message);
- // Network blip — try next route if available.
+ // Network blip — try next route if one exists and time remains.
routeIdx++;
- if (routeIdx < fallbackRoutes.length) {
+ if (routeIdx < fallbackRoutes.length && Date.now() < deadline) {
route = fallbackRoutes[routeIdx];
includeTools = true;
retriedTransient = false;
continue;
}
- return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');
+ return error(res, 502, 'upstream_unavailable', 'chat backend unreachable', {
+ providers_tried: providersTried(attempted),
+ });
}
// watsonx/Granite: a few foundation models (or regions) reject a
@@ -449,7 +465,7 @@ export default wrap(async (req, res) => {
continue;
}
// Already tried without tools, or non-tool-use 404 — fall over to next provider.
- if (routeIdx + 1 < fallbackRoutes.length) {
+ if (canFailOver()) {
console.warn(`[chat:${route.name}] 404 — falling over to ${fallbackRoutes[routeIdx + 1].name}/${fallbackRoutes[routeIdx + 1].model}: ${text.slice(0, 120)}`);
routeIdx++;
route = fallbackRoutes[routeIdx];
@@ -480,7 +496,7 @@ export default wrap(async (req, res) => {
// Fall over on rate-limit (429) and transient gateway errors (502/503/504).
// Don't re-fetch on 4xx other than 429 — those are caller mistakes that
// the next provider would also reject.
- if ((upstream.status === 429 || upstream.status >= 500) && routeIdx + 1 < fallbackRoutes.length) {
+ if ((upstream.status === 429 || upstream.status >= 500) && canFailOver()) {
const text = await upstream.text().catch(() => '');
console.warn(`[chat:${route.name}] ${upstream.status} — falling over to ${fallbackRoutes[routeIdx + 1].name}/${fallbackRoutes[routeIdx + 1].model}: ${text.slice(0, 120)}`);
routeIdx++;
@@ -512,21 +528,35 @@ export default wrap(async (req, res) => {
} catch {
upstreamMessage = text.slice(0, 200);
}
+ const budgetSpent = Date.now() - started >= TOTAL_BUDGET_MS;
console.error(
`[chat:${route.name}]`,
upstream.status,
- `(final — all ${fallbackRoutes.length} route(s) exhausted)`,
+ budgetSpent
+ ? `(final — ${TOTAL_BUDGET_MS}ms time budget spent after ${attempted.length} attempt(s))`
+ : `(final — all ${fallbackRoutes.length} route(s) exhausted)`,
upstreamMessage ? `${upstreamMessage} ` : '',
text.slice(0, 400),
);
+ // Ops signal: OpenAI quota exhaustion is an account/billing problem, not a
+ // transient blip — call it out explicitly so it's actionable in the logs.
+ if (route.name === 'openai' && /quota|billing|exceeded your current/i.test(`${upstreamMessage} ${text}`)) {
+ console.error(
+ '[chat:openai] account is OVER QUOTA — top up OpenAI billing or remove OPENAI_API_KEY ' +
+ 'so the chat ladder stops routing to it as a final tier.',
+ );
+ }
// Client body is intentionally generic and human-readable: the raw provider
// status/message is noise to an end user (and could leak provider internals).
- // The frontend renders `error_description` directly in the chat UI.
+ // The frontend renders `error_description` directly in the chat UI. We do
+ // surface the (provider-name-only) list of what was tried so the client can
+ // show "tried groq, openrouter…" without leaking upstream internals.
return error(
res,
502,
'upstream_error',
'The AI chat provider is temporarily unavailable. Please try again in a moment.',
+ { providers_tried: providersTried(attempted) },
);
}
@@ -695,36 +725,52 @@ const FALLBACK_SIBLINGS = {
openai: ['gpt-4o-mini'],
};
+// A model is eligible for an *auto-built* fallback slot only when it can serve
+// the request. We never add a model the request can't use, instead of calling
+// it and retrying-without-tools at runtime (the old "no tool-capable endpoint"
+// round-trip). watsonx/orchestrate models aren't in MODEL_CATALOG (their ids
+// are dynamic), so they're governed solely by their `configured` checks below.
+//
+// - requireTools: chat always asks with action tools, so a model with no
+// tool endpoint (per MODEL_CATALOG) is skipped entirely.
+// - moderation-gated models (e.g. gpt-oss-120b:free) are never auto-selected;
+// they only run when a caller names them explicitly as the primary route.
+function eligibleAsFallback(modelId) {
+ const meta = MODEL_CATALOG[modelId];
+ if (!meta) return true; // dynamic ids (watsonx/orchestrate) — gated elsewhere
+ return meta.tools === true && !meta.moderationGated;
+}
+
function buildFallbackChain(primary, userKeys = {}) {
const chain = [primary];
const seen = new Set([`${primary.name}:${primary.model}`]);
- // Sibling models on the same provider
- const siblings = FALLBACK_SIBLINGS[primary.name] || [];
- for (const m of siblings) {
- const key = `${primary.name}:${m}`;
- if (seen.has(key)) continue;
- seen.add(key);
- const cfg = PROVIDERS[primary.name];
- const apiKey = userKeys[primary.name] || process.env[cfg.envKey];
- if (!apiKey) continue;
- chain.push(makeRoute(primary.name, cfg, apiKey, m));
- }
-
- // Other providers, in declared order, picking the configured default model
- for (const name of Object.keys(PROVIDERS)) {
- if (name === primary.name) continue;
+ const tryAdd = (name, model) => {
+ if (chain.length >= MAX_FALLBACK_ATTEMPTS) return;
+ const key = `${name}:${model}`;
+ if (seen.has(key)) return;
+ if (!eligibleAsFallback(model)) return;
const cfg = PROVIDERS[name];
const apiKey = userKeys[name] || process.env[cfg.envKey];
- if (!apiKey) continue;
- if (name === 'watsonx' && !watsonxConfig().configured) continue;
- if (name === 'orchestrate' && !orchestrateConfig().configured) continue;
- const key = `${name}:${cfg.defaultModel}`;
- if (seen.has(key)) continue;
+ if (!apiKey) return;
+ if (name === 'watsonx' && !watsonxConfig().configured) return;
+ if (name === 'orchestrate' && !orchestrateConfig().configured) return;
seen.add(key);
- chain.push(makeRoute(name, cfg, apiKey, cfg.defaultModel));
+ chain.push(makeRoute(name, cfg, apiKey, model));
+ };
+
+ // (a) Sibling models on the same provider — recover from a per-model
+ // rate-limit without leaving the (already-selected, reliable) provider.
+ for (const m of FALLBACK_SIBLINGS[primary.name] || []) tryAdd(primary.name, m);
+
+ // (b) Other providers, in reliability order, at their configured default.
+ for (const name of DEFAULT_PROVIDER_ORDER) {
+ if (name === primary.name) continue;
+ tryAdd(name, PROVIDERS[name].defaultModel);
}
+ // The chain is bounded to MAX_FALLBACK_ATTEMPTS so a single request can't
+ // churn through every provider before timing out.
return chain;
}
@@ -1000,6 +1046,17 @@ async function resolveAuth(req) {
return null;
}
+// Distinct provider names from the attempt log, in first-tried order — the
+// client-safe summary of an exhausted chain (provider names only, no models or
+// upstream messages, which could leak internals).
+function providersTried(attempted) {
+ const out = [];
+ for (const a of attempted) {
+ if (!out.includes(a.provider)) out.push(a.provider);
+ }
+ return out;
+}
+
function fmt(n) {
return typeof n === 'number' ? n.toLocaleString('en-US') : '?';
}
diff --git a/api/cosmetics/catalog.js b/api/cosmetics/catalog.js
new file mode 100644
index 000000000..a5deea8e8
--- /dev/null
+++ b/api/cosmetics/catalog.js
@@ -0,0 +1,39 @@
+/**
+ * GET /api/cosmetics/catalog — the avatar cosmetics shop catalog (R21).
+ *
+ * Returns every shop item with its shop fields (id, name, slot, rarity, price,
+ * previewImage, owned/locked) and the rig payload the live preview needs. The
+ * base accessory pack is owned/free; premium emotes + skins are locked until
+ * purchased (R22 x402 flow / R23 inventory). Prices are denominated in $THREE.
+ *
+ * Query params:
+ * rarity=common|rare|epic|legendary — optional filter to one tier.
+ */
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { buildCatalog, RARITIES } from '../_lib/cosmetics.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const rarity = url.searchParams.get('rarity');
+ if (rarity && !RARITIES.includes(rarity)) {
+ return error(res, 400, 'bad_rarity', `rarity must be one of: ${RARITIES.join(', ')}`);
+ }
+
+ // Ownership beyond the free base pack is wired in R23 (wallet-bound
+ // inventory). Until then every premium item reads as locked.
+ const items = buildCatalog({ rarity: rarity || null });
+
+ // Catalog is static content — cache hard at the edge, but let the client
+ // revalidate so a deploy that changes the pack propagates promptly.
+ return json(res, 200, { items, rarities: RARITIES }, {
+ 'cache-control': 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400',
+ });
+});
diff --git a/api/cosmetics/owned.js b/api/cosmetics/owned.js
new file mode 100644
index 000000000..7391d1061
--- /dev/null
+++ b/api/cosmetics/owned.js
@@ -0,0 +1,63 @@
+/**
+ * GET /api/cosmetics/owned?account=<accountId> — the premium cosmetics an
+ * account has purchased over the x402 rail (R22 ownership ledger).
+ *
+ * Returns the owned ids plus their resolved catalog rows, so the owned-inventory
+ * (R23) can render "My Cosmetics" from one call. Base-pack items are owned by
+ * every avatar implicitly and are NOT listed here — this is only the purchased
+ * (premium) set. Degrades to an empty list if the account owns nothing or the
+ * store is unreachable.
+ *
+ * Query params:
+ * account (required) — a Solana wallet address or a guest id (g_…).
+ */
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getCosmetic, priceOf, priceUsdcAtomicsOf, priceUsdcDisplayOf } from '../_lib/cosmetics.js';
+import { readOwnedCosmetics, normalizeAccountId } from '../_lib/cosmetics-ownership.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const account = normalizeAccountId(url.searchParams.get('account'));
+ if (!account) {
+ return error(res, 400, 'account_required',
+ 'query parameter "account" is required (a Solana wallet or guest id)');
+ }
+
+ const ownedIds = await readOwnedCosmetics(account);
+ // Resolve to catalog rows, dropping ids that no longer exist in the catalog
+ // (a cosmetic retired after purchase) so the inventory never renders a ghost.
+ const items = ownedIds
+ .map((id) => {
+ const c = getCosmetic(id);
+ if (!c) return null;
+ return {
+ id: c.id,
+ name: c.name,
+ slot: c.slot,
+ kind: c.kind,
+ rarity: c.rarity,
+ price: priceOf(c),
+ currency: 'THREE',
+ priceUsdcAtomics: priceUsdcAtomicsOf(c),
+ priceUsdc: priceUsdcDisplayOf(c),
+ owned: true,
+ previewImage: c.previewImage || null,
+ ...(c.glbUrl ? { glbUrl: c.glbUrl, attachBone: c.attachBone } : {}),
+ ...(c.morphBinding ? { morphBinding: c.morphBinding } : {}),
+ ...(c.colors ? { colors: c.colors } : {}),
+ ...(c.emote ? { emote: c.emote } : {}),
+ };
+ })
+ .filter(Boolean);
+
+ // Per-account, fast-changing — never cache at the edge.
+ return json(res, 200, { account, ownedIds, items }, { 'cache-control': 'no-store' });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index e2ff3f4ff..f709377dd 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -2758,12 +2758,18 @@ async function handleSiwxGc(req, res) {
const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');
- const nonces_pruned = await pruneOldNonces(600);
- const payments_pruned = await pruneExpiredPayments(7 * 24 * 3600);
+ // 10-minute nonce window — well over the 5-minute SIWX message maxAge.
+ const noncesDeleted = await pruneOldNonces(10 * 60);
+
+ // 7-day grace on expired payments so a slow client doesn't lose access
+ // mid-session right at the boundary.
+ const paymentsDeleted = await pruneExpiredPayments(7 * 24 * 3600);
return json(res, 200, {
- nonces_pruned,
- payments_pruned,
+ ok: true,
+ noncesDeleted,
+ paymentsDeleted,
+ ranAt: new Date().toISOString(),
});
}
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 24a9d5ee3..7999f9eab 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -20,9 +20,12 @@ import { redactPii } from '../../_lib/pii.js';
import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
import { listTranscripts, getTranscript } from './_transcripts.js';
-// _knowledge.js is loaded on demand — its jsdom→html-encoding-sniffer→@exodus/bytes
-// transitive dep chain causes ERR_REQUIRE_ESM at import time on some Node versions,
-// which would crash the entire function and take down stats/transcripts as well.
+// _knowledge.js is loaded on demand (dynamic import in handleKnowledge) so the
+// knowledge-ingest path stays isolated: any failure constructing that module
+// surfaces as a 503 on /knowledge alone and can never crash stats/transcripts.
+// (The historical ERR_REQUIRE_ESM crash — jsdom→html-encoding-sniffer@6→
+// @exodus/bytes, an ESM module require()d from CJS — is gone now that
+// text-extract.js parses HTML with node-html-parser instead of jsdom.)
export default wrap(async (req, res) => {
const action = req.query?.action;
diff --git a/api/x402/asset-download.js b/api/x402/asset-download.js
index 251b02757..50ffd5354 100644
--- a/api/x402/asset-download.js
+++ b/api/x402/asset-download.js
@@ -101,6 +101,23 @@ async function loadAsset(slug) {
return rows[0] || null;
}
+// Build the SIWX statement. EIP-4361 restricts the statement to a single line
+// of RFC 3986 reserved/unreserved characters + space — double quotes, braces,
+// backticks, etc. are illegal and make the official SIWX client (browser
+// wallets and @x402/extensions alike) refuse to render a signable message. The
+// asset title is catalog-controlled, so we strip anything outside that set and
+// collapse whitespace rather than wrapping the title in quotes.
+const SIWE_STATEMENT_DISALLOWED = /[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;= ]+/g;
+function buildSiwxStatement(title) {
+ const clean = String(title || '')
+ .replace(SIWE_STATEMENT_DISALLOWED, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return clean
+ ? `Sign in to re-download ${clean} without re-paying.`
+ : 'Sign in to re-download this asset without re-paying.';
+}
+
function buildPayToOverride(asset) {
const out = {};
if (asset.creator_payto_base) out.base = asset.creator_payto_base;
@@ -148,7 +165,7 @@ export default async function handler(req, res) {
resourceUrlBuilder: () =>
`${env.APP_ORIGIN}${ROUTE}?slug=${encodeURIComponent(asset.slug)}`,
siwx: {
- statement: `Sign in to re-download "${asset.title}" without re-paying.`,
+ statement: buildSiwxStatement(asset.title),
// Permanent grant per (asset, wallet) — once a wallet has paid for
// this asset it can re-download forever by signing.
ttlSeconds: null,
diff --git a/api/x402/cosmetic-purchase.js b/api/x402/cosmetic-purchase.js
new file mode 100644
index 000000000..bffcf2615
--- /dev/null
+++ b/api/x402/cosmetic-purchase.js
@@ -0,0 +1,186 @@
+// GET /api/x402/cosmetic-purchase?id=<cosmeticId>&account=<accountId>
+//
+// The avatar shop's checkout (R22). Buying a premium cosmetic settles a real
+// USDC payment over x402 (Base or Solana) and, on a verified payment, records
+// ownership of that cosmetic to the buyer's account in the durable ownership
+// ledger (api/_lib/cosmetics-ownership.js). The shop (R21) and the owned
+// inventory (R23) read that ledger back.
+//
+// Pricing is per rarity and SERVER-OWNED — the USDC amount comes from the
+// catalog (api/_lib/cosmetics.js), never from the client, so a buyer can't move
+// the price. The $THREE figure the shop quotes is the item's coin-facing value;
+// USDC is only the settlement asset, exactly as every other /api/x402/* endpoint.
+//
+// "Buy once, owned forever": each (cosmetic, wallet) pair gets a permanent SIWX
+// grant baked to the item id, so a wallet that already paid re-accesses for free
+// by signing — and the handler re-grants ownership idempotently each time. The
+// on-chain payment itself is single-use (the facilitator won't settle the same
+// signed proof twice), and the ownership SET is idempotent, so the flow is safe
+// against replay and can never double-grant.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { getCosmetic, priceUsdcAtomicsOf } from '../_lib/cosmetics.js';
+import { grantCosmeticOwnership, normalizeAccountId } from '../_lib/cosmetics-ownership.js';
+
+const ROUTE = '/api/x402/cosmetic-purchase';
+
+const DESCRIPTION =
+ 'three.ws Avatar Shop — pay once in USDC to unlock a premium avatar cosmetic ' +
+ '(skin or emote) for an account. Pay on Base or Solana; the cosmetic is ' +
+ 'recorded to the buyer-specified account and is wearable across /play and ' +
+ '/walk. Wallets that already purchased an item re-confirm for free by signing ' +
+ 'in with SIWX. Price varies by rarity.';
+
+const INPUT_EXAMPLE = { id: 'skin-midnight', account: 'g_5f3c9a21b8' };
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['id', 'account'],
+ properties: {
+ id: {
+ type: 'string',
+ description: 'Premium cosmetic id from /api/cosmetics/catalog.',
+ minLength: 1,
+ maxLength: 64,
+ },
+ account: {
+ type: 'string',
+ description:
+ 'The account the cosmetic is granted to — a Solana wallet address or ' +
+ 'a guest id (g_…). Ownership is keyed here, not on the paying wallet.',
+ minLength: 3,
+ maxLength: 64,
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ id: 'skin-midnight',
+ name: 'Midnight',
+ slot: 'skin',
+ rarity: 'legendary',
+ account: 'g_5f3c9a21b8',
+ owned: true,
+ newlyOwned: true,
+ payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',
+ network: 'solana',
+ amountAtomics: '3000000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok', 'id', 'name', 'slot', 'rarity', 'account', 'owned'],
+ properties: {
+ ok: { type: 'boolean', const: true },
+ id: { type: 'string' },
+ name: { type: 'string' },
+ slot: { type: 'string' },
+ rarity: { type: 'string' },
+ account: { type: 'string' },
+ owned: { type: 'boolean', const: true },
+ newlyOwned: { type: 'boolean' },
+ payer: { type: ['string', 'null'] },
+ network: { type: ['string', 'null'] },
+ amountAtomics: { type: ['string', 'null'] },
+ asset: { type: ['string', 'null'] },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Per-item paidEndpoint built on the fly: the id picks the catalog row, which
+// dictates the USDC price; everything else is shared. Mirrors asset-download.js,
+// where the slug drives a per-row price + SIWX grant.
+export default async function handler(req, res) {
+ const id = req.query?.id ? String(req.query.id).trim() : '';
+ if (!id) {
+ return error(res, 400, 'id_required', 'query parameter "id" is required');
+ }
+
+ const account = normalizeAccountId(req.query?.account);
+ if (!account) {
+ return error(res, 400, 'account_required',
+ 'query parameter "account" is required (a Solana wallet or guest id)');
+ }
+
+ const item = getCosmetic(id);
+ if (!item) {
+ return error(res, 404, 'cosmetic_not_found', `no cosmetic with id "${id}"`);
+ }
+ if (!item.premium) {
+ // Base-pack items ship owned with every avatar — there's nothing to sell.
+ return error(res, 400, 'not_purchasable',
+ `cosmetic "${id}" is part of the free base pack and is already owned`);
+ }
+
+ const priceAtomics = priceUsdcAtomicsOf(item);
+
+ const inner = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics,
+ networks: ['base', 'solana'],
+ description: `${DESCRIPTION} — currently unlocking: ${item.name} (${item.rarity}).`,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Avatar Shop',
+ tags: ['3d', 'avatar', 'cosmetic', 'shop', 'wearable'],
+ }),
+ // Bake the item id into the resource URL so the SIWX grant is per-cosmetic:
+ // without this, paying for one cosmetic would unlock every cosmetic via a
+ // single signature (the SIWX row is keyed on (resource, wallet) only). The
+ // 402 challenge advertises the same URL the client signs against.
+ resourceUrlBuilder: () =>
+ `${env.APP_ORIGIN}${ROUTE}?id=${encodeURIComponent(item.id)}`,
+ siwx: {
+ statement: `Sign in to confirm you own "${item.name}" without re-paying.`,
+ // Permanent per (cosmetic, wallet) — once paid, re-confirm forever by signing.
+ ttlSeconds: null,
+ expirationSeconds: 300,
+ },
+ async handler({ requirement, payer }) {
+ // Record ownership BEFORE settlement returns to the buyer. grant throws
+ // (503) if the durable store is missing — fail closed, so we never settle
+ // a charge we can't record. Idempotent: a re-paid/replayed call just
+ // re-confirms the existing unlock.
+ const newlyOwned = await grantCosmeticOwnership(account, item.id);
+ return {
+ ok: true,
+ id: item.id,
+ name: item.name,
+ slot: item.slot,
+ rarity: item.rarity,
+ account,
+ owned: true,
+ newlyOwned,
+ payer: payer ?? null,
+ network: requirement?.network ?? null,
+ amountAtomics: requirement?.amount ?? null,
+ asset: requirement?.asset ?? null,
+ };
+ },
+ });
+
+ return inner(req, res);
+}
+
+export const BAZAAR_SCHEMA = BAZAAR;
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md
new file mode 100644
index 000000000..8a24f5afe
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md
@@ -0,0 +1,62 @@
+# Fix 04 — Production DB missing tables (`forge_creations`, `usage_events`) (P1, ~25 lines)
+
+## The errors (verbatim)
+
+```
+[forge-store] listCreations failed: relation "forge_creations" does not exist
+[api] unhandled NeonDbError: relation "usage_events" does not exist (code 42P01)
+```
+
+- `forge_creations`: breaks `/api/forge-gallery` (19 lines).
+- `usage_events`: breaks `/api/agents/[id]` (`handleGetOne`, 2 lines) and is referenced by
+ ~15 other files (`billing/summary`, `usage/summary`, `cron/[name]`, `agent-wallet`, etc.) —
+ so this will surface wider than the export shows.
+
+## Root cause
+
+The migrations that create these tables exist in the repo but were **never applied to the
+production Neon database**:
+- `api/_lib/migrations/20260604000000_forge_creations.sql` (dated 2026-06-04 — one day before
+ this log window; clearly never ran in prod).
+- `usage_events` is defined in `api/_lib/schema.sql` (lines ~310-326, plus additive ALTERs at
+ ~707-709) — the base schema/those ALTERs aren't applied either.
+
+Migration runner: `scripts/run-migrations.mjs` applies `api/_lib/migrations/*.sql` in
+alphabetical order, tracked in a `schema_migrations` table. The base `schema.sql` bootstrap
+and the newest migration both need to be applied to prod.
+
+## Required fix (proper, no shortcuts)
+
+1. **Reconcile schema vs migrations.** Confirm whether `usage_events` lives only in
+ `schema.sql` or also has a dedicated migration. If the migration runner is the source of
+ truth for prod, ensure `usage_events` (table + the additive `agent_id` column/index) is
+ represented as an **idempotent** migration file, not only in `schema.sql`. Same for any
+ other table that exists in `schema.sql` but has no migration. Don't leave prod dependent
+ on a manual `schema.sql` apply.
+2. **Make the migrations idempotent and safe** (`create table if not exists`,
+ `create index if not exists`, `add column if not exists`) — they already mostly are;
+ verify the new/reconciled ones are too, so re-running is harmless.
+3. **Apply to production.** Run the migration runner against the prod `DATABASE_URL`
+ (Neon). Confirm `schema_migrations` records them and the tables now exist.
+4. **Verify the code's expected columns match** what the migration creates — `forge-store.js`
+ and `api/_lib/usage.js` / `api/agents/[id].js` query specific columns; the table shape
+ must satisfy every query (not just the table name).
+5. **Guard the read paths** so a future missing-relation never becomes an unhandled 500:
+ `forge-gallery` should return an empty gallery (designed empty state) rather than 500 if
+ the table is somehow absent; `agents/[id]` should treat "no usage_events" as zero usage,
+ not a crash. Errors handled at the boundary.
+
+## Verification
+
+- `\dt` (or a `select to_regclass('public.forge_creations')`) against prod confirms both
+ tables exist with the expected columns.
+- `/api/forge-gallery` returns real creations (or a clean empty state) — no 500.
+- `/api/agents/<real-id>` returns the agent with usage stats — no 500.
+- `select * from schema_migrations` shows the applied migration rows.
+- Grep post-deploy logs: zero `relation "..." does not exist`.
+
+## Definition of done
+
+Both tables exist in prod via tracked idempotent migrations, every querying route returns
+real data, read paths degrade gracefully if a relation is ever missing, and the
+schema.sql-vs-migrations drift that caused this is reconciled so it can't recur.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md
new file mode 100644
index 000000000..16308c066
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md
@@ -0,0 +1,52 @@
+# Fix 05 — Birdeye / GeckoTerminal upstream 429 (P1, ~175 lines)
+
+## The errors (verbatim)
+
+```
+[three-token] birdeye error: Birdeye 429: {"success":false,"message":"Too many requests"}
+[api] unhandled Error: GeckoTerminal 429: {"status":{"error_code":429,"error_message":"You've exceeded the Rate Limit..."}}
+```
+
+- Birdeye: `/api/three-token/[action]` (173 lines) — the heaviest single external-API failure.
+- GeckoTerminal: `/api/ibm/oracle` (2 lines).
+
+## Root cause
+
+We call Birdeye and GeckoTerminal on hot read paths with **no caching, no backoff, and no
+fallback chain** for the 429 case, so under normal traffic we blow their rate limits and
+the failure propagates as a user-facing error. For `ibm/oracle` the 429 is also
+**unhandled** (becomes a 500).
+
+## Required fix
+
+Find the call sites (`grep -rln "birdeye\|Birdeye\|geckoterminal\|GeckoTerminal" api/`).
+
+1. **Cache aggressively.** Token price/market data changes on the order of seconds, not
+ milliseconds. Add a short-TTL cache (memory + the shared cache layer) keyed by token/mint
+ so repeated requests within the TTL never hit the upstream. Per `CLAUDE.md`, the default
+ chart pins `$THREE` — that hot key especially must be cached.
+2. **Fallback chain on 429/5xx.** Birdeye and pump.fun/GeckoTerminal already coexist in this
+ codebase (see the pump-dashboard memory: `Birdeye → pump.fun fallback`). Wire the same
+ pattern here: on Birdeye 429, fall back to the alternate source rather than failing.
+ Make the fallback real (no mock/placeholder data — `CLAUDE.md` hard rule).
+3. **Exponential backoff + jitter** for transient 429s before giving up, bounded so we never
+ exceed the function time budget.
+4. **Handle the boundary** in `/api/ibm/oracle`: a GeckoTerminal 429 must become a graceful
+ degraded response (cached/last-known value or a clean 503), **never an unhandled 500**.
+5. **Use an API key if we have one.** Check `.env` / `vercel env` for `BIRDEYE_API_KEY`
+ (and any GeckoTerminal Pro key). If present, authenticate to get the higher rate tier; if
+ missing and the platform needs it, surface that to the user once.
+
+## Verification
+
+- Hammer `/api/three-token/<action>` for `$THREE` repeatedly — the upstream is hit at most
+ once per TTL; the rest serve from cache; no 429 reaches the client.
+- Simulate Birdeye 429 → confirm the fallback source serves real data.
+- `/api/ibm/oracle` under upstream 429 returns a clean degraded payload, not 500.
+- Post-deploy logs: Birdeye/GeckoTerminal 429 counts drop sharply and never produce 500s.
+
+## Definition of done
+
+Token/market reads are cached with a sane TTL, 429s trigger a real fallback (no fake data),
+backoff is bounded, `ibm/oracle` handles the upstream error at the boundary, and any
+available API key is used for the higher tier.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md
new file mode 100644
index 000000000..df4aa882f
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md
@@ -0,0 +1,65 @@
+# Fix 06 — `/api/brain/chat` OpenRouter credit ceiling + invalid Responses-API payloads (P1, ~95 lines)
+
+## The errors (verbatim)
+
+```
+APICallError [AI_APICallError]: This request requires more credits, or fewer max_tokens.
+ You requested up to 1024 tokens, but can only afford 788. (also 300/4000/4096/8000)
+APICallError [AI_APICallError]: Invalid Responses API request
+APICallError [AI_APICallError]: Input contains unsupported content types or unsupported content fields
+RetryError [AI_RetryError]: Failed after 3 attempts. Last error: Rate limit reached for model `llama-3.3-70b-versatile`
+```
+
+All on `/api/brain/chat`, which uses the Vercel AI SDK `OpenAIResponsesLanguageModel`
+(`doStream`) against OpenRouter.
+
+## Root cause
+
+Three distinct, separately-fixable problems:
+
+1. **`requires more credits, or fewer max_tokens`** — we send a fixed `max_tokens` (1024,
+ 4000, 4096, 8000…) that exceeds what the OpenRouter free-tier balance can afford for that
+ request. The model literally tells us the affordable ceiling (e.g. "can only afford 788")
+ and we don't adapt.
+2. **`Invalid Responses API request`** — we're sending payloads the OpenAI **Responses API**
+ shape rejects. Likely a model that doesn't speak the Responses API is being routed
+ through `OpenAIResponsesLanguageModel`, or a malformed field. This is a code bug.
+3. **`unsupported content types or unsupported content fields`** — we're passing message
+ content parts (images? tool blocks? custom fields?) the target model/endpoint doesn't
+ support. Another payload-shape bug.
+
+## Required fix
+
+Find the handler: `api/brain/chat.js` (source — the deployed file is bundled). Trace how the
+model, `max_tokens`, and message content are assembled.
+
+1. **Adaptive token budget.** Don't hardcode `max_tokens`. Either (a) lower the default to a
+ value the free tier reliably affords, or (b) parse the upstream "can only afford N" and
+ retry once with `max_tokens = N` (the API hands us the number). Prefer a sane default
+ *plus* the adaptive retry so we never hard-fail on this. Never silently truncate the
+ user's content — reduce the *completion* budget, not the input.
+2. **Match the API surface to the model.** Audit which models `brain/chat` routes to and
+ whether each actually supports the **Responses API**. Models that don't must use the
+ Chat Completions surface (or a model that does). Fix the `Invalid Responses API request`
+ at the source — don't retry a structurally-invalid request.
+3. **Sanitize content parts** to what the target model supports before sending. If a model
+ can't take a given content type (image/tool/custom field), either drop/transcode it for
+ that model or route to one that supports it. Validate the payload before the call.
+4. **Bound retries** so `RetryError ... Failed after 3 attempts` on a rate-limited free model
+ falls over to a working model (coordinate with Fix 03's ladder) instead of dead-ending.
+
+## Verification
+
+- Drive `/api/brain/chat` with a long-completion request on the free tier — it succeeds with
+ an adapted token budget, no `requires more credits` failure.
+- Send a multimodal / tool message — content is validated/sanitized; no `unsupported content
+ types`.
+- Confirm no `Invalid Responses API request` for any routed model (each model uses the API
+ surface it actually supports).
+- Post-deploy logs: these three `AI_APICallError` signatures gone.
+
+## Definition of done
+
+`brain/chat` adapts its token budget to the available balance, routes each model to the API
+surface it supports, validates/sanitizes content before sending, and falls over cleanly on
+rate limits — no `AI_APICallError` for these three causes.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md
new file mode 100644
index 000000000..10a59661b
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md
@@ -0,0 +1,58 @@
+# Fix 07 — `THREE_TREASURY_WALLET` unset in production (P1, 18 lines)
+
+## The error (verbatim)
+
+```
+[api] unhandled Error: [token] THREE_TREASURY_WALLET is required in production
+ — refusing to route treasury funds to an unset address.
+ at treasuryWallet (api/token/[action].js)
+ at publicConfig → handleConfig
+```
+
+`/api/token/config` returns 500 on every call.
+
+## Root cause
+
+This is a **correct fail-closed guard** — the code rightly refuses to surface or route
+treasury funds to an unset/zero address. The actual problem is **operational + a handler
+design flaw**:
+
+1. **Operational:** `THREE_TREASURY_WALLET` is not set in the production Vercel environment.
+2. **Code:** `/api/token/config` is a *public config read* — it should not throw a 500 just
+ because a *write/treasury-routing* env var is missing. A misconfigured treasury must not
+ take down the public config endpoint. The guard belongs on the **fund-routing path**, not
+ the read-only config path.
+
+## Required fix
+
+`api/token/[action].js` — see `treasuryWallet()`, `publicConfig()`, `handleConfig()`.
+
+1. **Set the env var (ops).** Set `THREE_TREASURY_WALLET` to the real treasury address in
+ Vercel prod (and preview if needed). Per `CLAUDE.md`, the only coin is `$THREE`
+ (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); the treasury must be the project's real
+ `$THREE` treasury address — confirm the correct value with the user before setting it.
+ **Do not invent an address.**
+2. **Fix the handler boundary.** `handleConfig`/`publicConfig` must not 500 when the treasury
+ is unset. Two clean options:
+ - Keep `treasuryWallet()` strict for any path that *routes funds* (correct — leave it),
+ but in `publicConfig` either omit the treasury field when unset, or return it as
+ explicitly `null`/`unconfigured` so the read endpoint stays 200 and the client can show
+ a "treasury not configured" state.
+ - The hard `throw` should fire only when something actually tries to **move funds** to the
+ treasury, not when reading config.
+3. **No silent default.** Never fall back to a placeholder/zero address for fund routing —
+ the existing fail-closed behavior on the *routing* path is correct and must stay.
+
+## Verification
+
+- With `THREE_TREASURY_WALLET` set: `/api/token/config` returns the real config incl. the
+ treasury address.
+- With it deliberately unset (local): `/api/token/config` returns 200 with treasury marked
+ unconfigured — **not** 500 — while any fund-routing call still hard-refuses.
+- Post-deploy logs: zero `THREE_TREASURY_WALLET is required` 500s on the config read.
+
+## Definition of done
+
+The treasury env var is set in prod to the real `$THREE` treasury, the public config read
+never 500s on a missing treasury, and fund-routing remains fail-closed. The user confirmed
+the address before it was set.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md
new file mode 100644
index 000000000..ad5ab9a7b
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md
@@ -0,0 +1,65 @@
+# Fix 08 — `index-delegations` cron ETH RPC failures (P1, ~40 lines)
+
+## The errors (verbatim)
+
+```
+{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 429 from https://1rpc.io/eth"}
+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: method not available"}
+{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 400 from https://1rpc.io/eth"}
+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: block range extends beyond current head block"}
+{"stage":"index-delegations","chainId":1,"error":"fetch failed"}
+{"stage":"index-delegations","chainId":84532/421614/11155111/11155420,"warning":"time-budget-exceeded"}
+```
+
+`/api/cron/index-delegations` (mainnet chainId 1 + testnets). The cron fails to index
+delegation events.
+
+## Root cause
+
+The delegation indexer relies on **public, free Ethereum RPC endpoints** (`https://1rpc.io/eth`)
+that:
+- rate-limit us (HTTP 429),
+- **don't support `eth_getLogs`** on the free tier (`method not available`),
+- reject malformed/oversized requests (HTTP 400, `block range extends beyond current head`),
+- and intermittently fail (`fetch failed`).
+
+Plus a logic bug: we query a **block range past the chain head** (`block range extends
+beyond current head block`) — we're not clamping `toBlock` to the latest block. And multiple
+testnet chains blow the **time budget** because indexing is serial/over-wide.
+
+## Required fix
+
+Find the cron: `api/cron/[name].js` (the `index-delegations` stage). Trace RPC URL
+selection, the `eth_getLogs` call, and block-range math.
+
+1. **Use a real RPC provider that supports `eth_getLogs`.** Public `1rpc.io/eth` is
+ inadequate. Use the configured Alchemy/Infura/QuickNode endpoint (check `.env` /
+ `vercel env` for an existing key — this codebase already does Solana RPC and EVM work, so
+ a paid EVM RPC may exist). If none is configured, surface that to the user; never ship a
+ cron that depends on a free endpoint that doesn't support our calls.
+2. **Clamp the block range.** Before `eth_getLogs`, fetch `eth_blockNumber` and set
+ `toBlock = min(desiredTo, head)`. Never request beyond head. Chunk large ranges into
+ bounded windows (e.g. ≤ provider max, commonly 10k blocks) and paginate.
+3. **Backoff + rotation on 429.** Bounded exponential backoff; optionally rotate across a
+ small set of configured providers. On persistent failure for a chain, log and continue —
+ one chain's RPC outage must not abort the whole cron.
+4. **Respect the time budget.** The `time-budget-exceeded` warnings mean we do too much per
+ invocation. Persist a per-chain cursor (this codebase already has cursor patterns — see
+ `pumpfun-monitor-cursor` migration) so each run resumes from the last indexed block and
+ does a bounded amount of work, then exits cleanly within budget.
+5. **Handle `fetch failed`** as a transient: retry within budget, else checkpoint and resume
+ next run. Never lose the cursor.
+
+## Verification
+
+- Run the cron locally/preview against the real RPC: it indexes delegation events for
+ mainnet without 429/method-not-available, and resumes from its cursor.
+- Force a bad block range → confirm it's clamped to head, no `beyond current head` error.
+- Confirm each testnet chain completes within the time budget (cursor-bounded work).
+- Post-deploy logs: `index-delegations` errors/time-budget warnings gone.
+
+## Definition of done
+
+The indexer uses an RPC that supports `eth_getLogs`, clamps and chunks block ranges, backs
+off on 429, persists a per-chain cursor so each run stays within budget, and a single chain
+failure doesn't abort the run.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md
new file mode 100644
index 000000000..f548ccf51
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md
@@ -0,0 +1,70 @@
+# Fix 09 — `/api/pump/launch-agent` WASM missing + tx serialize overflow + timeout (P1, ~16 lines)
+
+## The errors (verbatim)
+
+```
+[api] unhandled Error: ENOENT: no such file or directory,
+ open '/var/task/api/pump/wasm/vanity_grinder_bg.wasm'
+ at ensureWasm → grindVanityNode → handleLaunchAgent
+
+[api] unhandled RangeError: encoding overruns Uint8Array
+ at Blob.encode (@solana/buffer-layout)
+ at MessageV0.serialize → VersionedTransaction.sign → handleLaunchAgent
+
+Vercel Runtime Timeout Error: Task timed out after 30 seconds
+```
+
+`/api/pump/[action]` → `handleLaunchAgent`.
+
+## Root cause
+
+Three distinct bugs in the launch path:
+
+1. **`vanity_grinder_bg.wasm` not bundled.** `ensureWasm()` does `readFileSync('/var/task/api/pump/wasm/vanity_grinder_bg.wasm')`
+ but the `.wasm` asset isn't included in the Vercel function bundle (Vercel NFT doesn't
+ trace `readFileSync` string paths). So vanity grinding crashes in prod.
+2. **`encoding overruns Uint8Array`** during `VersionedTransaction.sign` → `MessageV0.serialize`.
+ The transaction is **too large / a field overflows its layout** — likely metadata
+ (name/symbol/uri/attributes) exceeding the on-chain byte budget. Note the memory
+ `onchain-brand-metadata`: the Attributes plugin has a **1232-byte tx budget** and needs a
+ byte-aware clamp. The launch path is exceeding the serialization limit.
+3. **30s timeout** — vanity grinding (CPU-bound) + launch in one synchronous request blows
+ the function limit.
+
+## Required fix
+
+`api/pump/[action].js` — `ensureWasm`, `grindVanityNode`, `handleLaunchAgent`. Cross-check
+`src/solana/vanity/brand.js` (the `3ws` mark, per memory `mint-mark-brand`) and
+`api/_lib/three-brand.js` (metadata builder, per memory `onchain-brand-metadata`).
+
+1. **Bundle the WASM properly.** Ensure `vanity_grinder_bg.wasm` ships in the function:
+ - Reference it so Vercel NFT traces it (e.g. `new URL('./wasm/vanity_grinder_bg.wasm', import.meta.url)`
+ and `fs.readFileSync(fileURLToPath(...))`), and/or add it to `vercel.json`
+ `functions.includeFiles` / `outputFileTracingIncludes`.
+ - Confirm the path resolves under `/var/task` at runtime. Test by deploying and hitting
+ the route — `ensureWasm` must find the file.
+2. **Byte-budget the transaction.** Before serialize/sign, clamp the metadata to fit the tx
+ size limit (apply the existing byte-aware clamp from the brand metadata builder so name +
+ symbol + uri + attributes never overrun). Reproduce the overflowing input, confirm the
+ clamp keeps the tx within the layout budget, and the launch succeeds. Do **not** silently
+ drop the brand mark — clamp intelligently (truncate long fields, not the mark).
+3. **Get vanity grinding off the request thread / within budget.** Either:
+ - Bound the grind difficulty so it provably completes well under 30s, or
+ - Move grinding to a background job / pre-generated vanity pool and have the launch request
+ consume a ready key. The launch endpoint must return within the function limit.
+ Pick the approach that keeps the `3ws` mark enforcement intact (memory `mint-mark-brand`:
+ `THREE_WS_MARK_ENFORCE`).
+
+## Verification
+
+- Deploy preview: `POST /api/pump/launch-agent` with a real launch payload (mint supplied at
+ runtime per `CLAUDE.md` — never hardcode a non-`$THREE` mint) → vanity step finds the WASM,
+ tx serializes/signs without `encoding overruns`, and the request returns under 30s.
+- Test with maximal-length name/symbol/uri to confirm the byte clamp holds.
+- Post-deploy logs: zero ENOENT for the wasm, zero `encoding overruns`, zero pump timeouts.
+
+## Definition of done
+
+The WASM is bundled and found at runtime, the launch tx is byte-clamped so it always
+serializes within the on-chain budget (mark preserved), vanity grinding completes within the
+function time limit, and a real launch succeeds end-to-end.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md
new file mode 100644
index 000000000..58e3b680f
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md
@@ -0,0 +1,54 @@
+# Fix 10 — `skills-pricing` Neon `transaction()` misuse (P1, 4 lines)
+
+## The error (verbatim)
+
+```
+[api] unhandled Error: transaction() expects an array of queries,
+ or a function returning an array of queries
+ at Xs.X.transaction (api/agents/[id]/skills-pricing.js)
+ at handlePut
+```
+
+`PUT /api/agents/[id]/skills-pricing` returns 500.
+
+## Root cause
+
+The Neon serverless driver's `sql.transaction()` has a specific contract: it takes **an
+array of query promises** (or a function returning one), and runs them in a single
+transaction — it is **not** the interactive `BEGIN…COMMIT` callback style of `node-postgres`.
+`handlePut` is calling it the pg way (passing an `async (tx) => { ... }` that runs queries
+imperatively), which the Neon driver rejects.
+
+Ref: Neon serverless driver docs — `sql.transaction([sql\`...\`, sql\`...\`])`.
+
+## Required fix
+
+`api/agents/[id]/skills-pricing.js` — `handlePut`.
+
+1. **Rewrite the transaction in the Neon contract.** Collect the parameterized queries into
+ an array and pass it: `await sql.transaction([ sql\`update ...\`, sql\`insert ...\` ])`.
+ If the logic needs values from one query to build the next (truly interactive), the Neon
+ HTTP driver can't do that in one `transaction()` call — restructure so all statements are
+ known up front, or use a single statement with CTEs (`WITH ... INSERT/UPDATE ... RETURNING`)
+ to keep it atomic in one round-trip.
+2. **Keep it atomic.** Pricing writes must be all-or-nothing — don't split into separate
+ non-transactional calls just to dodge the API. Use the array form or a CTE so partial
+ writes can't happen.
+3. **Validate input at the boundary** (price values, skill ids) before the write so bad input
+ returns a clean 400, not a 500.
+4. **Check sibling handlers** in the same file (and other `*/skills-pricing.js`,
+ `skills-pricing` callers) for the same misuse — fix all instances.
+
+## Verification
+
+- `PUT /api/agents/<real-id>/skills-pricing` with a valid pricing update → 200, prices
+ persisted atomically; verify in DB.
+- Send a malformed body → clean 400, no 500.
+- Simulate a mid-transaction failure (e.g. constraint violation) → nothing partially
+ written.
+- Post-deploy logs: zero `transaction() expects an array of queries`.
+
+## Definition of done
+
+Skills-pricing writes use the Neon `transaction()` contract correctly, remain atomic,
+validate input at the boundary, and every call site is fixed.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md
new file mode 100644
index 000000000..dedc28e2f
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md
@@ -0,0 +1,58 @@
+# Fix 11 — OG image + URL edge cases (P2, ~5 lines)
+
+## The errors (verbatim)
+
+```
+/api/play-og : TypeError: Invalid URL (code ERR_INVALID_URL, input: '/api/play-og')
+ at new URL (api/play-og.js:48)
+/api/agent-og : NeonDbError: invalid input syntax for type uuid: ":id" (path /api/agent/:id/og)
+/api/x402-pay/og: Fontconfig error: Cannot load default config file: No such file: (null)
+```
+
+## Root causes — three independent bugs
+
+### A. `/api/play-og` — `new URL(req.url)` with a relative input
+`req.url` is a **path** (`/api/play-og`), not an absolute URL. `new URL('/api/play-og')`
+throws `ERR_INVALID_URL`. The handler needs a base. (The source already does
+`new URL(req.url, 'http://x')` in one place — line ~191 — but the crashing line ~48 in the
+deployed bundle doesn't pass a base, or constructs a URL from an unvalidated query param.)
+
+**Fix:** never call `new URL(req.url)` without a base. Use `new URL(req.url, originOf(req))`
+(the file already has `originOf(req)`), and validate/guard any URL built from query params —
+on bad input, render the default OG image, not a 500. Trace line ~48 in source and fix at
+the construction site.
+
+### B. `/api/agent-og` — literal `:id` reaching the DB
+The route received the **literal** `/api/agent/:id/og` (the unsubstituted path template), so
+`:id` was passed straight into a `uuid` column → `invalid input syntax for type uuid`. Some
+caller (a crawler, a prerender, or a broken internal link) is hitting the template path.
+
+**Fix:** validate `id` is a real UUID **before** querying (`/^[0-9a-f-]{36}$/i` or a uuid
+guard). If it isn't a valid UUID (or is the literal `:id`), return the **default OG image**
+with a 200, not a DB error. Then hunt the source of the bad link — grep for `agent/:id/og`
+or template strings that aren't being interpolated, and fix the caller so the template path
+is never requested.
+
+### C. `/api/x402-pay/og` — Fontconfig can't load default config
+The OG renderer (likely `@vercel/og` / satori / a canvas lib) can't find a font config in
+the serverless runtime. Per memory `seo-meta-and-og-runtime`, `@vercel/og` Edge runtime is
+broken here — **use the node runtime**, and bundle/register the font explicitly.
+
+**Fix:** ensure `/api/x402-pay/og` runs on the **node** runtime (not edge), register the
+font file explicitly (load the `.ttf`/`.woff` and pass it to the renderer) and bundle it via
+`includeFiles`, so it never depends on a system Fontconfig default. Confirm the OG image
+renders with correct fonts.
+
+## Verification
+
+- `GET /api/play-og` (and with weird query params) → returns a valid PNG, never 500.
+- `GET /api/agent-og?id=:id` and `?id=<garbage>` → default OG image, 200; valid UUID → real
+ agent OG. No `invalid input syntax for type uuid` in logs. The bad-link source is fixed.
+- `GET /api/x402-pay/og` → renders with fonts, no Fontconfig error.
+- Post-deploy logs: all three signatures gone.
+
+## Definition of done
+
+All three OG/URL endpoints handle bad/edge input gracefully (default image, never 500), the
+literal-`:id` caller is traced and fixed, and the x402-pay OG renders on the node runtime
+with an explicitly bundled font.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md
new file mode 100644
index 000000000..59dee7a1e
Binary files /dev/null and b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md differ
diff --git a/multiplayer/src/block-store.js b/multiplayer/src/block-store.js
index b66ccdb4b..2bcfc9e74 100644
--- a/multiplayer/src/block-store.js
+++ b/multiplayer/src/block-store.js
@@ -13,9 +13,13 @@
// debounced (one network round-trip a few seconds after the last edit) and
// flushed on room dispose, so a busy build doesn't hammer Redis.
//
-// Each world is stored as a single JSON object { "gx,gy,gz": type } under the
-// key `walkblocks:<mint>`. A world is hard-capped (see MAX_BLOCKS in WalkRoom),
-// so the payload stays tens of KB — comfortably one Redis value.
+// Each world is stored as a single JSON object under the key `walkblocks:<mint>`.
+// A cell's value carries the block type AND the stable id of whoever placed it,
+// so ownership (R19 build permissions) survives a room emptying and a server
+// restart — without it, every restored build would be ownerless and unprotected.
+// The on-wire form is a compact `[type, owner]` pair; a bare number is still
+// accepted on load as a legacy (pre-ownership) cell. A world is hard-capped (see
+// MAX_BLOCKS in WalkRoom), so the payload stays well within one Redis value.
const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';
const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';
@@ -27,9 +31,25 @@ function redisKey(coin) {
return KEY_PREFIX + (coin || 'mainland');
}
+// Normalize a persisted cell value into { t, o }. Accepts the current
+// `[type, owner]` pair, a bare `type` number from pre-ownership saves (owner
+// unknown → ''), or a `{ t, o }` object. Returns null for anything unparseable.
+function decodeCell(v) {
+ if (Array.isArray(v)) {
+ const t = Number(v[0]);
+ return Number.isInteger(t) ? { t, o: typeof v[1] === 'string' ? v[1] : '' } : null;
+ }
+ if (v && typeof v === 'object') {
+ const t = Number(v.t);
+ return Number.isInteger(t) ? { t, o: typeof v.o === 'string' ? v.o : '' } : null;
+ }
+ const t = Number(v);
+ return Number.isInteger(t) ? { t, o: '' } : null;
+}
+
class BlockStore {
constructor() {
- this._mem = new Map(); // coin → Map(packedKey → type)
+ this._mem = new Map(); // coin → Map(packedKey → { t:type, o:ownerId })
this._saveTimers = new Map(); // coin → timeout handle
this._redis = null;
this._redisReady = null;
@@ -82,9 +102,9 @@ class BlockStore {
const raw = this._redis ? await this._redis.get(redisKey(coin)) : null;
const obj = typeof raw === 'string' ? JSON.parse(raw) : raw; // Upstash may auto-parse JSON
if (obj && typeof obj === 'object') {
- for (const [k, t] of Object.entries(obj)) {
- const type = Number(t);
- if (Number.isInteger(type)) map.set(k, type);
+ for (const [k, v] of Object.entries(obj)) {
+ const rec = decodeCell(v);
+ if (rec) map.set(k, rec);
}
}
} catch (err) {
@@ -95,11 +115,12 @@ class BlockStore {
}
// In-memory edits + a debounced durable write. Synchronous so callers don't
- // await on the hot path of a place/break.
- set(coin, key, type) {
+ // await on the hot path of a place/break. `owner` is the stable id of the
+ // placer (R19 ownership); '' for an ownerless/community cell.
+ set(coin, key, type, owner = '') {
const map = this._mem.get(coin);
if (!map) return;
- map.set(key, type);
+ map.set(key, { t: type, o: owner || '' });
this._scheduleSave(coin);
}
@@ -136,7 +157,9 @@ class BlockStore {
if (map.size === 0) {
await this._redis.del(redisKey(coin));
} else {
- await this._redis.set(redisKey(coin), JSON.stringify(Object.fromEntries(map)));
+ const obj = {};
+ for (const [k, rec] of map) obj[k] = [rec.t, rec.o || ''];
+ await this._redis.set(redisKey(coin), JSON.stringify(obj));
}
// A successful write proves durability is back; reset the failure streak.
if (this._writeFailures > 0) {
diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.js
index fb0bef3f7..4d5f45e1b 100644
--- a/multiplayer/src/game-token.js
+++ b/multiplayer/src/game-token.js
@@ -295,6 +295,24 @@ export function splitBurnTreasury(rawTotal, burnBps = 5000) {
return { burn, treasury };
}
+// Three-leg split for a coin-tied sale (R25): the creator share comes off the top
+// (by `creatorBps`), then the remainder splits burn/treasury by `burnBps`. The
+// creator leg is taken FIRST so the platform's burn/treasury split is computed on
+// what's left — i.e. a 50% creator share over a 50/50 burn/treasury remainder
+// pays the creator 50%, burns 25%, treasuries 25%. Treasury absorbs every rounding
+// remainder so the three legs always sum to exactly the total. `creatorBps` is
+// clamped to [0,10000]; 0 (or a falsy creator wallet upstream) degenerates to the
+// plain burn/treasury split with a zero creator leg.
+export function splitCreatorTreasuryBurn(rawTotal, creatorBps = 0, burnBps = 5000) {
+ const total = BigInt(rawTotal);
+ const cbps = BigInt(Math.max(0, Math.min(10000, Number(creatorBps) | 0)));
+ const creator = (total * cbps) / 10000n;
+ const remainder = total - creator;
+ const burn = (remainder * BigInt(burnBps)) / 10000n;
+ const treasury = remainder - burn;
+ return { creator, burn, treasury };
+}
+
function memoInstruction(nonce) {
return new TransactionInstruction({ keys: [], programId: MEMO_PROGRAM_ID, data: Buffer.from(nonce, 'utf8') });
}
@@ -401,6 +419,14 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
};
if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };
if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
+ // Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
+ // must have moved at least that share to the creator's $THREE account — else the
+ // split didn't happen and we refuse to credit the sale. Quotes without a creator
+ // leg (spins, plain boutique sales) skip this and behave exactly as before.
+ if (q.creatorAddr && BigInt(q.creatorRaw || '0') > 0n) {
+ const creatorATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.creatorAddr))).toBase58();
+ if (delta(creatorATA) < BigInt(q.creatorRaw)) return { ok: false, reason: 'creator_underpaid' };
+ }
return { ok: true, nonce: q.nonce, quote: q };
}
@@ -421,17 +447,36 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
* `extra` is sealed into the quote verbatim (e.g. the boutique listing id) so settle
* can act on it without trusting the client. Returns null when no treasury is
* configured, the buyer isn't a real wallet, or the amount is non-positive.
- * @param {{ buyerWallet: string, amountRaw: string|bigint, purpose: string, burnBps?: number, extra?: object }} params
+ *
+ * Coin-tied creator splits (R25): pass `creator: { wallet, bps }` to route a share
+ * of the SAME signed transaction to a coin creator's wallet. The creator leg is a
+ * real third SPL transfer the buyer signs — no platform float, no second payout —
+ * so the split is enforced on-chain atomically. The creator share comes off the
+ * top; the remainder splits burn/treasury by `burnBps` as before. A falsy/invalid
+ * creator wallet or a zero `bps` degenerates to the plain two-leg split.
+ *
+ * @param {{ buyerWallet: string, amountRaw: string|bigint, purpose: string, burnBps?: number, creator?: { wallet?: string, bps?: number }, extra?: object }} params
* @returns {Promise<null | { quoteToken: string, txBase64: string, quote: object }>}
*/
-export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burnBps = 5000, extra = {} }) {
+export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burnBps = 5000, creator = null, extra = {} }) {
if (!tokenConfigured()) return null;
if (!isWalletAddress(buyerWallet)) return null;
let total;
try { total = BigInt(amountRaw); } catch { return null; }
if (!(total > 0n)) return null;
- const { burn: burnRaw, treasury: treasuryRaw } = splitBurnTreasury(total, burnBps);
+ // A creator leg only applies when both a valid wallet and a positive share are
+ // supplied (and the creator isn't the buyer — a no-op self-transfer). Otherwise
+ // fall back to the plain burn/treasury split, the creator leg zeroed.
+ const creatorBpsIn = Math.max(0, Math.min(10000, Number(creator?.bps) | 0));
+ const creatorWallet = creator?.wallet;
+ const creatorActive = creatorBpsIn > 0
+ && isWalletAddress(creatorWallet)
+ && creatorWallet !== buyerWallet;
+ const effectiveCreatorBps = creatorActive ? creatorBpsIn : 0;
+
+ const { creator: creatorRaw, burn: burnRaw, treasury: treasuryRaw } =
+ splitCreatorTreasuryBurn(total, effectiveCreatorBps, burnBps);
const treasuryAddr = treasuryWallet();
const nonce = crypto.randomBytes(16).toString('hex');
@@ -444,16 +489,23 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
const buyerATA = await getAssociatedTokenAddress(mint, buyer);
const burnATA = await getAssociatedTokenAddress(mint, burn);
const treasuryATA = await getAssociatedTokenAddress(mint, treasury);
+ const creatorATA = creatorActive
+ ? await getAssociatedTokenAddress(mint, new PublicKey(creatorWallet))
+ : null;
const tx = new Transaction();
- const [burnAcct, treasuryAcct] = await Promise.all([
- conn.getAccountInfo(burnATA),
- conn.getAccountInfo(treasuryATA),
- ]);
+ const accountChecks = [conn.getAccountInfo(burnATA), conn.getAccountInfo(treasuryATA)];
+ if (creatorActive) accountChecks.push(conn.getAccountInfo(creatorATA));
+ const [burnAcct, treasuryAcct, creatorAcct] = await Promise.all(accountChecks);
if (!burnAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, burnATA, burn, mint));
if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));
- tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));
- tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));
+ if (creatorActive && !creatorAcct) {
+ tx.add(createAssociatedTokenAccountInstruction(buyer, creatorATA, new PublicKey(creatorWallet), mint));
+ }
+ // Order legs largest-intent first for readability; amounts are what matter.
+ if (creatorActive && creatorRaw > 0n) tx.add(createTransferInstruction(buyerATA, creatorATA, buyer, creatorRaw));
+ if (burnRaw > 0n) tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));
+ if (treasuryRaw > 0n) tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));
tx.add(memoInstruction(nonce));
const { blockhash } = await conn.getLatestBlockhash('confirmed');
@@ -473,6 +525,10 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
burnRaw: burnRaw.toString(),
treasuryAddr,
treasuryRaw: treasuryRaw.toString(),
+ // Creator leg (R25). Sealed into the quote so settle verifies the on-chain
+ // creator transfer landed before crediting earnings — the client can't forge
+ // or omit it. Absent keys mean "no creator leg" (plain two-way split).
+ ...(creatorActive ? { creatorAddr: creatorWallet, creatorRaw: creatorRaw.toString(), creatorBps: effectiveCreatorBps } : {}),
nonce,
...extra,
};
@@ -521,5 +577,13 @@ export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purp
};
if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };
if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
+ // Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
+ // must have moved at least that share to the creator's $THREE account — else the
+ // split didn't happen and we refuse to credit the sale. Quotes without a creator
+ // leg (spins, plain boutique sales) skip this and behave exactly as before.
+ if (q.creatorAddr && BigInt(q.creatorRaw || '0') > 0n) {
+ const creatorATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.creatorAddr))).toBase58();
+ if (delta(creatorATA) < BigInt(q.creatorRaw)) return { ok: false, reason: 'creator_underpaid' };
+ }
return { ok: true, nonce: q.nonce, quote: q };
}
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index b0aa8a0df..268c7b56b 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -8,7 +8,7 @@
import { Room } from '@colyseus/core';
-import { Player, Block, Vehicle, Mob, Tombstone, WalkState } from '../schemas.js';
+import { Player, Block, Vehicle, Mob, Tombstone, WorldObject, WalkState } from '../schemas.js';
import {
VEHICLE_SPAWNS, vehicleSpec, isVehicleType,
VEHICLE_WORLD_RADIUS_M, VEHICLE_ENTER_RANGE_M,
@@ -16,6 +16,7 @@ import {
} from '../vehicles.js';
import { cleanAvatarUrl } from '../avatar-url.js';
import { blockStore } from '../block-store.js';
+import { worldPersistence } from '../persistence.js';
import { verifyHolderPass } from '../holder-pass.js';
import { socialHub } from '../social-hub.js';
import { verifyPresenceTicket } from '../presence-token.js';
@@ -83,6 +84,52 @@ const MAX_BLOCKS = 6000;
// Building is bursty (drag-to-place), so allow a higher rate than movement but
// still cap it so a scripted client can't flood the room.
const EDITS_PER_SEC_LIMIT = 20;
+// Generic world objects (R01): the shared channel for balls, props and pickups.
+// Caps keep the synced state and the persisted per-coin doc (R17) bounded, and
+// the rate limit mirrors the edit limiter so a scripted client can't flood spawns.
+const MAX_WORLD_OBJECTS = 200; // total objects one room may hold
+const MAX_OBJECTS_PER_PLAYER = 30; // how many one owner may have at once
+const OBJ_OPS_PER_SEC_LIMIT = 30; // per-client spawn/update/remove rate
+const OBJ_SCALE_MIN = 0.1;
+const OBJ_SCALE_MAX = 10;
+const OBJ_STR_MAX = 48; // clamp length of id/type/kind strings
+const OBJ_Y_MIN = -5;
+const OBJ_Y_MAX = 240;
+const SERVER_OBJECT_OWNER = 'server'; // ownerId sentinel: room-owned, no client writes
+// Transient object kinds are ephemeral (physics balls, fx) and are NEVER persisted
+// (R17). Everything else is a durable build piece saved per coin world.
+const TRANSIENT_OBJECT_KINDS = new Set(['ball', 'projectile', 'confetti', 'fx', 'spark', 'pickup']);
+const OBJ_ID_RE = /^[A-Za-z0-9_-]{1,48}$/;
+// Composite pieces (walls, stairs, doors) place several cells at once through the
+// place-batch channel. A single stamp is capped at this many cells, and stamps
+// are rate-limited separately from single edits, so a crafted client can't smuggle
+// an oversized or rapid-fire write through it. Mirrors MAX_COMPOSITE_CELLS on the
+// client, with headroom so appending a larger piece there doesn't desync.
+const MAX_BATCH_CELLS = 32;
+const BATCHES_PER_SEC_LIMIT = 4;
+
+// --- Build permissions & anti-grief (R19) ---------------------------------
+// The per-world MAX_BLOCKS budget above protects the room; these caps protect it
+// from a SINGLE builder. A per-player ceiling stops one user consuming the whole
+// world; a per-column ceiling stops them stacking a 24-high wall to fence the
+// plaza off; protected discs keep the spawn and the coin totem from being buried
+// or caged. Every rejection is surfaced to the client (edit-reject), never silent.
+const PER_PLAYER_BLOCK_CAP = 1200; // how many cells one player may own at once
+const COLUMN_CAP = 14; // blocks allowed in a single (x,z) column (< MAX_GRID_Y)
+const PROTECTED_RADIUS_CELLS = 3; // keep this many cells clear around each protected point
+// The build grid is centred on the world origin and maps a cell to metres via the
+// client's BLOCK size (1.5 m). The spawn point is the origin; the coin totem
+// renders at world z = -12 → grid z = round(-12 / 1.5) = -8. Protect both columns
+// at every height so neither can be buried or walled in.
+const PROTECTED_POINTS = [{ x: 0, z: 0 }, { x: 0, z: -8 }];
+// Creator moderation: a clear-area sweep is bounded to this radius (cells) so even
+// the creator's broad-brush tool can't nuke a whole world in one malformed call;
+// 'all' is the explicit full-clear path.
+const CLEAR_AREA_MAX_RADIUS = 12;
+// The three.ws API the multiplayer server reads the coin's on-chain creator from,
+// so "is this player the coin's creator" is proven server-side, not claimed by a
+// client. Mirrors persistence.js's WORLD_API_BASE.
+const WORLD_API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
// Anti-cheat: reject any movement update that would move the player farther
// than this in a single message. The client sends moves at ~15Hz, so even at
@@ -162,6 +209,18 @@ function clean(str, maxLen) {
.slice(0, maxLen);
}
+// Numeric guards for world-object payloads: a finite value or the fallback, and a
+// clamp into [lo, hi]. Kept tiny and local so the object handlers read cleanly.
+function objNum(v, fallback) {
+ return Number.isFinite(v) ? v : fallback;
+}
+function objClamp(v, lo, hi) {
+ return v < lo ? lo : v > hi ? hi : v;
+}
+function round3(n) {
+ return Math.round(n * 1000) / 1000;
+}
+
function pickPlayerColor(sessionId) {
// Deterministic pleasant hue from sessionId — every client renders the
// same player in the same color without us needing to sync it explicitly.
@@ -247,6 +306,17 @@ export class WalkRoom extends Room {
// stable persistence id + per-action cooldowns). Never synced to peers.
this.econ = new Map();
this._actionCounters = new Map(); // sessionId → { [action]: { windowStart, count } }
+ // Build permissions & anti-grief (R19). Ownership and density are tracked
+ // off-schema (peers don't render them) but persisted with the build so they
+ // survive a restart. blockOwners: key → owner id. blockCounts: owner id → how
+ // many cells they hold (drives the per-player cap, keyed by stable owner so it
+ // outlives a disconnect while their build stands). columnCounts: "x,z" → height.
+ this.blockOwners = new Map();
+ this.blockCounts = new Map();
+ this.columnCounts = new Map();
+ // The coin's on-chain creator wallet, resolved once on create. '' until known
+ // (or for the ownerless mainland world); gates the clear-area moderation tool.
+ this.coinCreator = '';
// Co-op heist instances live on the room, not on a profile: a SHARED run a
// crew advances together. Keyed by mission id (one live instance per heist per
// world). Each value: { missionId, members:Set<sessionId>, run, done:Set<zone> }.
@@ -292,7 +362,9 @@ export class WalkRoom extends Room {
this.onMessage('avatar', (client, payload) => this._handleAvatar(client, payload));
this.onMessage('play-pass', (client, payload) => this._handlePlayPassRefresh(client, payload));
this.onMessage('place', (client, payload) => this._handlePlace(client, payload));
+ this.onMessage('place-batch', (client, payload) => this._handlePlaceBatch(client, payload));
this.onMessage('remove', (client, payload) => this._handleRemove(client, payload));
+ this.onMessage('build-clear', (client, payload) => this._handleBuildClear(client, payload));
this.onMessage('voice-state', (client, payload) => this._handleVoiceState(client, payload));
this.onMessage('voice-signal', (client, payload) => this._handleVoiceSignal(client, payload));
// Economy & activities (off-schema). The owning client drives these and
@@ -315,18 +387,31 @@ export class WalkRoom extends Room {
this.onMessage('venter', (client, payload) => this._handleVehicleEnter(client, payload));
this.onMessage('vexit', (client, payload) => this._handleVehicleExit(client, payload));
this.onMessage('vsync', (client, payload) => this._handleVehicleSync(client, payload));
+ // Generic world objects (R01): spawn/move/remove balls, props and pickups on
+ // the shared `objects` map. Durable build props placed here persist per coin
+ // world (R17); transient kinds (the R05 ball) live only for the session.
+ this.onMessage('obj:spawn', (client, payload) => this._handleObjSpawn(client, payload));
+ this.onMessage('obj:update', (client, payload) => this._handleObjUpdate(client, payload));
+ this.onMessage('obj:remove', (client, payload) => this._handleObjRemove(client, payload));
this._emoteCooldowns = new Map();
this._editCounters = new Map(); // sessionId → { windowStart, count }
+ this._batchCounters = new Map(); // sessionId → { windowStart, count } for composite stamps
this._voiceCounters = new Map(); // sessionId → { windowStart, count }
+ this._objCounters = new Map(); // sessionId → { windowStart, count } for obj:* ops
+ this._objSeq = 0; // monotonic counter for server-minted object ids
// Rehydrate this coin's persisted build before the first client renders the
// world, so newcomers always drop into the community's existing creation.
try {
const saved = await blockStore.load(this.worldKey);
- for (const [key, type] of saved) {
+ for (const [key, rec] of saved) {
const b = new Block();
- b.t = type;
+ b.t = rec.t;
this.state.blocks.set(key, b);
+ // Rehydrate ownership + density so the per-player cap, column cap, and
+ // the "only the placer (or creator) may delete" rule hold for a build
+ // that was placed before this process started.
+ this._trackPlacement(key, rec.o || '');
}
if (saved.size) {
console.log(`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}] restored ${saved.size} blocks`);
@@ -334,6 +419,21 @@ export class WalkRoom extends Room {
} catch (err) {
console.warn(`[walk_world ${this.roomId}] block restore failed:`, err?.message);
}
+
+ // Rehydrate this coin's durable placed objects (R17) — the build props the
+ // community left behind — from the per-world persistence store before the
+ // first client renders, mirroring how blocks are restored above. The store is
+ // keyed by world id; mainland (empty coin) gets a stable fallback key. Blocks
+ // and objects share the world key but live in separate backends, so they
+ // don't collide. load() never throws (it falls back to its memory mirror).
+ this._objKey = this.worldKey || 'mainland';
+ try {
+ const { doc } = await worldPersistence.load(this._objKey);
+ this._restoreObjects(doc);
+ } catch (err) {
+ console.warn(`[walk_world ${this.roomId}] object restore failed:`, err?.message);
+ }
+
// Tell builders, honestly, whether this world survives a server restart.
// load() above already awaited the store's readiness probe, so durability
// is settled by now.
@@ -347,6 +447,13 @@ export class WalkRoom extends Room {
// room is created); persistence of parked vehicles is a later concern.
this._seedVehicles();
+ // Resolve this coin's on-chain creator so the build-permission layer can grant
+ // the creator world-wide moderation (delete any piece, clear an area). Fetched
+ // once, off the hot path; a failure just leaves the world without a creator
+ // (no moderation tool), never blocks the room. The mainland world has no coin
+ // and therefore no creator.
+ this._resolveCoinCreator();
+
// Re-check policy for the token gate. The game server has no RPC of its own,
// so "still holding the token" is re-proven by the client minting a fresh
// play pass (which re-reads the chain) before the current one's 10-min TTL
@@ -424,6 +531,10 @@ export class WalkRoom extends Room {
player.cosmetics = serializeLoadout(profile.cosmetics.equipped);
this._sendProfile(client);
this._sendQuests(client);
+ // Build permissions: the per-player cap, current usage, and whether this player
+ // is the coin creator (so the HUD can reveal the clear-area moderation tool).
+ // Re-sent later if the creator lookup resolves after this join.
+ this._sendBuildPerms(client);
const tierTag = this.state.tier === 'holders' ? ' tier=holders' : '';
console.log(
@@ -461,12 +572,19 @@ export class WalkRoom extends Room {
if (profile.playerId) { try { flushPlayer(profile.playerId); } catch { /* best-effort */ } }
this.econ.delete(client.sessionId);
}
+ // Reap this owner's transient objects (R01): balls and fx they spawned die
+ // with their session. Their durable build props stay as part of the world
+ // (R17) — that's the whole point of persistence. Computed before the player
+ // is removed from state so _ownerKey can still read their account.
+ this._reapOwnerTransients(this._ownerKey(client));
this.state.players.delete(client.sessionId);
this._moveCounters.delete(client.sessionId);
this._chatCooldowns.delete(client.sessionId);
this._editCounters?.delete(client.sessionId);
+ this._batchCounters?.delete(client.sessionId);
this._emoteCooldowns?.delete(client.sessionId);
this._voiceCounters?.delete(client.sessionId);
+ this._objCounters?.delete(client.sessionId);
this._actionCounters.delete(client.sessionId);
console.log(
`[walk_world ${this.roomId}] -leave ${client.sessionId} (n=${this.state.players.size})`,
@@ -483,6 +601,14 @@ export class WalkRoom extends Room {
} catch (err) {
console.warn(`[walk_world ${this.roomId}] final flush failed:`, err?.message);
}
+ // Flush the durable placed objects (R17) the same way — any spawn/move/remove
+ // whose debounce hadn't fired lands before the room is gone, so leaving and
+ // re-entering (or a redeploy) shows the same build.
+ try {
+ await worldPersistence.flush(this._objKey);
+ } catch (err) {
+ console.warn(`[walk_world ${this.roomId}] final object flush failed:`, err?.message);
+ }
// Flush any economy profiles still resident (a redeploy can dispose a room
// with players mid-session) so no progression is lost between the last
// change and the room going away.
@@ -1027,19 +1153,93 @@ export class WalkRoom extends Room {
if (key === null) { this._rejectEdit(client, 'bounds'); return; }
const t = payload.t;
if (!Number.isInteger(t) || t < 0 || t >= BLOCK_TYPE_COUNT) { this._rejectEdit(client, 'type'); return; }
+ const owner = this._ownerKey(client.sessionId);
const existing = this.state.blocks.get(key);
- // New cell — enforce the per-world budget. Re-painting an existing cell
- // (changing its type) is always allowed since it doesn't grow the world.
- if (!existing && this.state.blocks.size >= MAX_BLOCKS) { this._rejectEdit(client, 'budget'); return; }
if (existing) {
+ // Re-painting an existing cell. It doesn't grow the world, but it DOES
+ // rewrite someone's build — only the piece's owner (or the coin creator)
+ // may change it, so a passer-by can't recolour another player's work.
if (existing.t === t) return; // no-op
+ if (!this._mayModify(client, key)) { this._rejectEdit(client, 'owned'); return; }
existing.t = t;
- } else {
- const b = new Block();
- b.t = t;
- this.state.blocks.set(key, b);
+ blockStore.set(this.worldKey, key, t, this.blockOwners.get(key) || owner);
+ return;
}
- blockStore.set(this.worldKey, key, t);
+ // New cell. Enforce, in order: the per-world budget, the protected spawn/totem
+ // discs, the per-player ownership cap, and the per-column density cap. Each is
+ // surfaced to the builder with its own reason — never a silent drop.
+ if (this.state.blocks.size >= MAX_BLOCKS) { this._rejectEdit(client, 'budget'); return; }
+ const reason = this._placementBlock(owner, payload.x, payload.z);
+ if (reason) { this._rejectEdit(client, reason); return; }
+ const b = new Block();
+ b.t = t;
+ this.state.blocks.set(key, b);
+ this._trackPlacement(key, owner);
+ blockStore.set(this.worldKey, key, t, owner);
+ this._sendBuildPerms(client);
+ }
+
+ // Place a composite piece — a handful of cells in one atomic, all-or-nothing
+ // stamp. Validated exactly like a single place (in-bounds integer cell, real
+ // type) for EVERY cell before anything lands, plus a whole-batch budget check,
+ // so a wall never half-appears and the per-world cap can't be straddled. Rate
+ // limited on its own bucket; the schema patch broadcasts each new block to all
+ // clients just like single edits, so there's no separate sync path.
+ _handlePlaceBatch(client, payload) {
+ if (!this.state.players.has(client.sessionId)) return;
+ if (!this._batchOk(client.sessionId)) { this._rejectEdit(client, 'rate'); return; }
+ const cells = payload?.cells;
+ if (!Array.isArray(cells) || cells.length === 0 || cells.length > MAX_BATCH_CELLS) {
+ this._rejectEdit(client, 'bounds');
+ return;
+ }
+ // First pass: validate every cell and count how many are new, so the budget,
+ // per-player cap, per-column density, protected-zone, and ownership checks all
+ // cover the WHOLE stamp before anything lands — a single bad cell rejects the
+ // lot. Cumulative tallies (ownerAdds, per-column) are tracked across the batch
+ // so a single stamp can't straddle a cap the same way a sequence of singles can't.
+ const owner = this._ownerKey(client.sessionId);
+ const validated = [];
+ let fresh = 0;
+ let ownerAdds = 0;
+ const colAdds = new Map();
+ for (const cell of cells) {
+ const key = this._cellKey(cell);
+ if (key === null) { this._rejectEdit(client, 'bounds'); return; }
+ const t = cell.t;
+ if (!Number.isInteger(t) || t < 0 || t >= BLOCK_TYPE_COUNT) { this._rejectEdit(client, 'type'); return; }
+ const existing = this.state.blocks.get(key);
+ if (existing) {
+ // Repaint of an occupied cell needs the same ownership gate as a single edit.
+ if (existing.t !== t && !this._mayModify(client, key)) { this._rejectEdit(client, 'owned'); return; }
+ } else {
+ const col = `${cell.x},${cell.z}`;
+ const extraCol = colAdds.get(col) || 0;
+ const reason = this._placementBlock(owner, cell.x, cell.z, ownerAdds, extraCol);
+ if (reason) { this._rejectEdit(client, reason); return; }
+ fresh++;
+ ownerAdds++;
+ colAdds.set(col, extraCol + 1);
+ }
+ validated.push({ key, t, cell });
+ }
+ if (this.state.blocks.size + fresh > MAX_BLOCKS) { this._rejectEdit(client, 'budget'); return; }
+ // Second pass: apply. All cells are known-valid now, so this can't partially fail.
+ for (const { key, t, cell } of validated) {
+ const existing = this.state.blocks.get(key);
+ if (existing) {
+ if (existing.t === t) continue;
+ existing.t = t;
+ blockStore.set(this.worldKey, key, t, this.blockOwners.get(key) || owner);
+ } else {
+ const b = new Block();
+ b.t = t;
+ this.state.blocks.set(key, b);
+ this._trackPlacement(key, owner);
+ blockStore.set(this.worldKey, key, t, owner);
+ }
+ }
+ this._sendBuildPerms(client);
}
_handleRemove(client, payload) {
@@ -1048,8 +1248,161 @@ export class WalkRoom extends Room {
const key = this._cellKey(payload);
if (key === null) { this._rejectEdit(client, 'bounds'); return; }
if (!this.state.blocks.has(key)) return;
+ // Ownership: only the placer may break their piece, except the coin creator,
+ // who moderates the whole world. Enforced server-side off the persisted owner,
+ // never the client's word.
+ if (!this._mayModify(client, key)) { this._rejectEdit(client, 'owned'); return; }
+ const owner = this.blockOwners.get(key) || '';
this.state.blocks.delete(key);
+ this._untrackPlacement(key, owner, payload.x, payload.z);
blockStore.delete(this.worldKey, key);
+ this._sendBuildPerms(client);
+ }
+
+ // Creator-only moderation: clear a disc of blocks around a grid point, or the
+ // whole world. Validated server-side — the creator identity comes from the coin's
+ // on-chain creator matching this client's verified wallet, never a client claim.
+ // Bounded radius keeps even a malformed call from over-reaching; 'all' is the
+ // explicit full wipe. Every removed cell streams out via the blocks state, so all
+ // clients see the area clear without a bespoke broadcast.
+ _handleBuildClear(client, payload) {
+ if (!this.state.players.has(client.sessionId)) return;
+ if (!this._isCreator(client)) { this._rejectEdit(client, 'notcreator'); return; }
+ if (!this._actionOk(client.sessionId, 'clear')) { this._rejectEdit(client, 'rate'); return; }
+ if (!payload || typeof payload !== 'object') return;
+
+ const all = payload.all === true;
+ let cx = 0, cz = 0, r = 0;
+ if (!all) {
+ cx = Number(payload.x); cz = Number(payload.z); r = Number(payload.r);
+ if (!Number.isFinite(cx) || !Number.isFinite(cz) || !Number.isFinite(r)) return;
+ r = Math.max(1, Math.min(CLEAR_AREA_MAX_RADIUS, Math.round(r)));
+ }
+
+ let cleared = 0;
+ for (const key of [...this.state.blocks.keys()]) {
+ const [bx, , bz] = key.split(',').map(Number);
+ if (!all && Math.hypot(bx - cx, bz - cz) > r) continue;
+ const owner = this.blockOwners.get(key) || '';
+ this.state.blocks.delete(key);
+ this._untrackPlacement(key, owner, bx, bz);
+ blockStore.delete(this.worldKey, key);
+ cleared++;
+ }
+ client.send('build-cleared', { count: cleared, all });
+ this._sendBuildPerms(client); // the creator's own tally may have changed
+ if (cleared) {
+ console.log(`[walk_world ${this.roomId}] creator cleared ${cleared} block(s)${all ? ' (all)' : ` near ${cx},${cz} r=${r}`}`);
+ }
+ }
+
+ // --- Build-permission bookkeeping ---------------------------------------
+
+ // The stable id a placed block is owned by: the player's persistence id (wallet
+ // account when the gate is on, else their guest id), falling back to the session
+ // id before the economy profile lands. Stable across reconnects so a returning
+ // builder still owns their pieces.
+ _ownerKey(sessionId) {
+ return this.econ.get(sessionId)?.playerId || sessionId;
+ }
+
+ // Whether this client may modify the block at `key` — its owner, or the creator.
+ // An ownerless cell (a legacy/pre-ownership restore) is creator-only, so restored
+ // builds stay protected from griefing while the creator can still moderate them.
+ _mayModify(client, key) {
+ if (this._isCreator(client)) return true;
+ const owner = this.blockOwners.get(key) || '';
+ return owner !== '' && owner === this._ownerKey(client.sessionId);
+ }
+
+ // Is this client the coin's on-chain creator? Requires a verified wallet (the
+ // account bound in onAuth) matching the creator we resolved on room create.
+ _isCreator(client) {
+ if (!this.coinCreator) return false;
+ const player = this.state.players.get(client.sessionId);
+ return !!player && !!player.account && player.account === this.coinCreator;
+ }
+
+ // True if (x,z) is inside a protected disc (spawn or totem) — placement there is
+ // refused at every height so neither landmark can be buried or fenced in.
+ _isProtectedColumn(x, z) {
+ for (const p of PROTECTED_POINTS) {
+ if (Math.hypot(x - p.x, z - p.z) <= PROTECTED_RADIUS_CELLS) return true;
+ }
+ return false;
+ }
+
+ // Shared anti-grief gate for a NEW cell (the per-world budget is checked by the
+ // caller, since it spans a whole batch). `extraOwner` / `extraColumn` are cells
+ // already committed earlier in the same batch, so a composite stamp can't straddle
+ // a cap. Returns an edit-reject reason, or null when the placement is allowed.
+ _placementBlock(owner, x, z, extraOwner = 0, extraColumn = 0) {
+ if (this._isProtectedColumn(x, z)) return 'protected';
+ if ((this.blockCounts.get(owner) || 0) + extraOwner >= PER_PLAYER_BLOCK_CAP) return 'playercap';
+ if ((this.columnCounts.get(`${x},${z}`) || 0) + extraColumn >= COLUMN_CAP) return 'dense';
+ return null;
+ }
+
+ // Record a placement against its owner + column tallies (used by the caps).
+ _trackPlacement(key, owner) {
+ this.blockOwners.set(key, owner);
+ if (owner) this.blockCounts.set(owner, (this.blockCounts.get(owner) || 0) + 1);
+ const ck = key.split(',', 3); // "x,y,z" -> column "x,z"
+ const col = `${ck[0]},${ck[2]}`;
+ this.columnCounts.set(col, (this.columnCounts.get(col) || 0) + 1);
+ }
+
+ // Reverse a placement's bookkeeping when a cell is removed.
+ _untrackPlacement(key, owner, x, z) {
+ this.blockOwners.delete(key);
+ if (owner) {
+ const n = (this.blockCounts.get(owner) || 0) - 1;
+ if (n > 0) this.blockCounts.set(owner, n); else this.blockCounts.delete(owner);
+ }
+ const col = `${x},${z}`;
+ const c = (this.columnCounts.get(col) || 0) - 1;
+ if (c > 0) this.columnCounts.set(col, c); else this.columnCounts.delete(col);
+ }
+
+ // Tell one client what they're allowed to do and how much of their build budget
+ // they've used, so the HUD can surface the per-player cap and reveal the creator
+ // moderation control — no silent limits. Sent on join and after their tally moves.
+ _sendBuildPerms(client) {
+ const owner = this._ownerKey(client.sessionId);
+ client.send('build-perms', {
+ creator: this._isCreator(client),
+ cap: PER_PLAYER_BLOCK_CAP,
+ used: this.blockCounts.get(owner) || 0,
+ clearMaxRadius: CLEAR_AREA_MAX_RADIUS,
+ });
+ }
+
+ // Resolve the coin's on-chain creator from the three.ws API (the same pump.fun
+ // coin record the lobby reads). Best-effort: a miss leaves the world without a
+ // creator and therefore without the clear-area tool. Re-broadcasts permissions to
+ // everyone already seated once known, so a creator who joined first still gets
+ // their moderation control the moment it resolves.
+ async _resolveCoinCreator() {
+ const mint = this.state.coin;
+ if (!mint) return; // mainland — no coin, no creator
+ try {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 6000);
+ let body;
+ try {
+ const res = await fetch(`${WORLD_API_BASE}/api/pump/coin?mint=${encodeURIComponent(mint)}`, {
+ headers: { accept: 'application/json' }, signal: ctrl.signal,
+ });
+ if (!res.ok) return;
+ body = await res.json();
+ } finally { clearTimeout(timer); }
+ const creator = typeof body?.creator === 'string' ? body.creator.trim() : '';
+ if (!MINT_RE.test(creator)) return; // a creator is a base58 wallet, same shape as a mint
+ this.coinCreator = creator;
+ for (const client of this.clients) this._sendBuildPerms(client);
+ } catch (err) {
+ console.warn(`[walk_world ${this.roomId}] creator lookup failed:`, err?.message);
+ }
}
_editOk(sessionId) {
@@ -1063,6 +1416,20 @@ export class WalkRoom extends Room {
return bucket.count <= EDITS_PER_SEC_LIMIT;
}
+ // Separate token bucket for composite stamps, so a legitimate wall (a dozen
+ // cells at once) isn't starved by the per-cell single-edit limit, while still
+ // capping how fast a client can fire whole pieces.
+ _batchOk(sessionId) {
+ const now = Date.now();
+ let bucket = (this._batchCounters ||= new Map()).get(sessionId);
+ if (!bucket || now - bucket.windowStart > 1000) {
+ bucket = { windowStart: now, count: 0 };
+ this._batchCounters.set(sessionId, bucket);
+ }
+ bucket.count++;
+ return bucket.count <= BATCHES_PER_SEC_LIMIT;
+ }
+
_rateOk(sessionId) {
const now = Date.now();
let bucket = this._moveCounters.get(sessionId);
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index dabf8749d..b3c6d1717 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -186,6 +186,48 @@ defineTypes(Tombstone, {
ts: 'float64',
});
+// A generic networked world object (R01) — the single shared channel every later
+// object feature reuses: thrown balls, placed build props, pickups, confetti.
+// Unlike a player's private economy (off-schema), an object is a world entity
+// everyone must see, so it rides on the synced state. Keyed in the `objects`
+// MapSchema by its id. `ownerId` is the account/session allowed to move or remove
+// it; the sentinel 'server' means the room owns it (clients can't write it, e.g.
+// the R05 physics ball). `kind` is the category — build props persist across a
+// server restart (R17); transient kinds like 'ball' are never saved.
+export class WorldObject extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.type = ''; // model/variant within a kind (e.g. 'crate', 'lamp')
+ this.x = 0;
+ this.y = 0;
+ this.z = 0;
+ this.yaw = 0;
+ this.scale = 1;
+ this.ownerId = ''; // account/session allowed to move/remove ('server' = room-owned)
+ this.vx = 0;
+ this.vy = 0;
+ this.vz = 0;
+ this.kind = ''; // category: '' / 'prop' persist; 'ball'/'fx' are transient
+ this.ts = 0; // last authoritative update (epoch ms)
+ }
+}
+defineTypes(WorldObject, {
+ id: 'string',
+ type: 'string',
+ x: 'float32',
+ y: 'float32',
+ z: 'float32',
+ yaw: 'float32',
+ scale: 'float32',
+ ownerId: 'string',
+ vx: 'float32',
+ vy: 'float32',
+ vz: 'float32',
+ kind: 'string',
+ ts: 'float64',
+});
+
export class WalkState extends Schema {
constructor() {
super();
@@ -226,6 +268,10 @@ export class WalkState extends Schema {
// the schema (append-only) so an older client isn't shifted off the format.
this.mobs = new MapSchema();
this.tombstones = new MapSchema();
+ // Generic placed/networked world objects (R01) — balls, props, pickups —
+ // keyed by object id. Durable build props in here are persisted per coin
+ // world (R17); transient ones (the R05 ball) are not. Append-only at the end.
+ this.objects = new MapSchema();
}
}
defineTypes(WalkState, {
@@ -244,4 +290,5 @@ defineTypes(WalkState, {
worldTime: 'float32',
mobs: { map: Mob },
tombstones: { map: Tombstone },
+ objects: { map: WorldObject },
});
diff --git a/package-lock.json b/package-lock.json
index fb12b8f6a..4601a74f1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -110,6 +110,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.4",
"node-fetch": "^3.3.2",
+ "node-html-parser": "^7.1.0",
"postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
"qrcode": "^1.5.4",
@@ -26130,6 +26131,12 @@
"node": ">= 0.8"
}
},
+ "node_modules/boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
+ "license": "ISC"
+ },
"node_modules/borsh": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/borsh/-/borsh-0.7.0.tgz",
@@ -28400,6 +28407,22 @@
"utrie": "^1.0.2"
}
},
+ "node_modules/css-select": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz",
+ "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-what": "^6.1.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "nth-check": "^2.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/css-to-react-native": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz",
@@ -28425,6 +28448,18 @@
"node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
}
},
+ "node_modules/css-what": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz",
+ "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">= 6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/css.escape": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
@@ -29139,6 +29174,73 @@
"csstype": "^3.0.2"
}
},
+ "node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/dom-serializer/node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
"node_modules/dotenv": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
@@ -41318,6 +41420,16 @@
"node-gyp-build-optional-packages-test": "build-test.js"
}
},
+ "node_modules/node-html-parser": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-7.1.0.tgz",
+ "integrity": "sha512-iJo8b2uYGT40Y8BTyy5ufL6IVbN8rbm/1QK2xffXU/1a/v3AAa0d1YAoqBNYqaS4R/HajkWIpIfdE6KcyFh1AQ==",
+ "license": "MIT",
+ "dependencies": {
+ "css-select": "^5.1.0",
+ "he": "1.2.0"
+ }
+ },
"node_modules/node-int64": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
@@ -41366,6 +41478,18 @@
"node": ">=8"
}
},
+ "node_modules/nth-check": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
+ "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
"node_modules/number-to-bn": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/number-to-bn/-/number-to-bn-1.7.0.tgz",
diff --git a/package.json b/package.json
index f79e4097b..d25ce43e0 100644
--- a/package.json
+++ b/package.json
@@ -197,6 +197,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.4",
"node-fetch": "^3.3.2",
+ "node-html-parser": "^7.1.0",
"postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
"qrcode": "^1.5.4",
diff --git a/public/cosmetics/catalog.json b/public/cosmetics/catalog.json
new file mode 100644
index 000000000..f98886b3a
--- /dev/null
+++ b/public/cosmetics/catalog.json
@@ -0,0 +1,337 @@
+{
+ "items": [
+ {
+ "id": "hat-baseball",
+ "name": "Baseball Cap",
+ "slot": "hat",
+ "kind": "hat",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/hat-baseball.png",
+ "glbUrl": "/accessories/hat-baseball.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "hat-beanie",
+ "name": "Beanie",
+ "slot": "hat",
+ "kind": "hat",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/hat-beanie.png",
+ "glbUrl": "/accessories/hat-beanie.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "hat-cowboy",
+ "name": "Cowboy Hat",
+ "slot": "hat",
+ "kind": "hat",
+ "rarity": "rare",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/hat-cowboy.png",
+ "glbUrl": "/accessories/hat-cowboy.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "glasses-round",
+ "name": "Round Glasses",
+ "slot": "glasses",
+ "kind": "glasses",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/glasses-round.png",
+ "glbUrl": "/accessories/glasses-round.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "glasses-shades",
+ "name": "Shades",
+ "slot": "glasses",
+ "kind": "glasses",
+ "rarity": "rare",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/glasses-shades.png",
+ "glbUrl": "/accessories/glasses-shades.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "earrings-hoops",
+ "name": "Hoop Earrings",
+ "slot": "earrings",
+ "kind": "earrings",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/earrings-hoops.png",
+ "glbUrl": "/accessories/earrings-hoops.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "earrings-studs",
+ "name": "Stud Earrings",
+ "slot": "earrings",
+ "kind": "earrings",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": "/accessories/thumbs/earrings-studs.png",
+ "glbUrl": "/accessories/earrings-studs.glb",
+ "attachBone": "Head"
+ },
+ {
+ "id": "outfit-casual",
+ "name": "Casual Fit",
+ "slot": "outfit",
+ "kind": "outfit",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": null,
+ "morphBinding": {
+ "Outfit_Casual": 1
+ }
+ },
+ {
+ "id": "outfit-sporty",
+ "name": "Sporty Fit",
+ "slot": "outfit",
+ "kind": "outfit",
+ "rarity": "common",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": null,
+ "morphBinding": {
+ "Outfit_Sporty": 1
+ }
+ },
+ {
+ "id": "outfit-formal",
+ "name": "Formal Fit",
+ "slot": "outfit",
+ "kind": "outfit",
+ "rarity": "rare",
+ "price": 0,
+ "currency": "THREE",
+ "priceUsdcAtomics": "0",
+ "priceUsdc": "0.00",
+ "premium": false,
+ "owned": true,
+ "locked": false,
+ "previewImage": null,
+ "morphBinding": {
+ "Outfit_Formal": 1
+ }
+ },
+ {
+ "id": "skin-crimson",
+ "name": "Crimson Threads",
+ "slot": "skin",
+ "kind": "skin",
+ "rarity": "rare",
+ "price": 100,
+ "currency": "THREE",
+ "priceUsdcAtomics": "500000",
+ "priceUsdc": "0.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "colors": {
+ "outfit": "#7a1d1d"
+ }
+ },
+ {
+ "id": "skin-whiteout",
+ "name": "Whiteout",
+ "slot": "skin",
+ "kind": "skin",
+ "rarity": "epic",
+ "price": 300,
+ "currency": "THREE",
+ "priceUsdcAtomics": "1500000",
+ "priceUsdc": "1.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "colors": {
+ "outfit": "#f1f1f4"
+ }
+ },
+ {
+ "id": "skin-midnight",
+ "name": "Midnight",
+ "slot": "skin",
+ "kind": "skin",
+ "rarity": "legendary",
+ "price": 750,
+ "currency": "THREE",
+ "priceUsdcAtomics": "3000000",
+ "priceUsdc": "3.00",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "colors": {
+ "outfit": "#0c0c14",
+ "hair": "#101018"
+ }
+ },
+ {
+ "id": "skin-gold",
+ "name": "Liquid Gold",
+ "slot": "skin",
+ "kind": "skin",
+ "rarity": "legendary",
+ "price": 750,
+ "currency": "THREE",
+ "priceUsdcAtomics": "3000000",
+ "priceUsdc": "3.00",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "colors": {
+ "outfit": "#caa64a",
+ "hair": "#8a6f2a"
+ }
+ },
+ {
+ "id": "emote-headbang",
+ "name": "Headbang",
+ "slot": "emote",
+ "kind": "emote",
+ "rarity": "rare",
+ "price": 100,
+ "currency": "THREE",
+ "priceUsdcAtomics": "500000",
+ "priceUsdc": "0.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "emote": "av-headbang"
+ },
+ {
+ "id": "emote-shuffle",
+ "name": "Shuffle",
+ "slot": "emote",
+ "kind": "emote",
+ "rarity": "rare",
+ "price": 100,
+ "currency": "THREE",
+ "priceUsdcAtomics": "500000",
+ "priceUsdc": "0.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "emote": "av-dance-shuffle"
+ },
+ {
+ "id": "emote-rumba",
+ "name": "Rumba",
+ "slot": "emote",
+ "kind": "emote",
+ "rarity": "epic",
+ "price": 300,
+ "currency": "THREE",
+ "priceUsdcAtomics": "1500000",
+ "priceUsdc": "1.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "emote": "rumba"
+ },
+ {
+ "id": "emote-capoeira",
+ "name": "Capoeira",
+ "slot": "emote",
+ "kind": "emote",
+ "rarity": "epic",
+ "price": 300,
+ "currency": "THREE",
+ "priceUsdcAtomics": "1500000",
+ "priceUsdc": "1.50",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "emote": "capoeira"
+ },
+ {
+ "id": "emote-thriller",
+ "name": "Thriller",
+ "slot": "emote",
+ "kind": "emote",
+ "rarity": "legendary",
+ "price": 750,
+ "currency": "THREE",
+ "priceUsdcAtomics": "3000000",
+ "priceUsdc": "3.00",
+ "premium": true,
+ "owned": false,
+ "locked": true,
+ "previewImage": null,
+ "emote": "thriller"
+ }
+ ],
+ "rarities": [
+ "common",
+ "rare",
+ "epic",
+ "legendary"
+ ]
+}
diff --git a/public/docs/api-reference.md b/public/docs/api-reference.md
index a2dda9e7e..ca7fee997 100644
--- a/public/docs/api-reference.md
+++ b/public/docs/api-reference.md
@@ -952,6 +952,45 @@ Each asset has its own SIWX grant key: the endpoint passes a `resourceUrlBuilder
`evmVerifierConfigured: true` means `BASE_RPC_URL` is set and smart-contract wallet signatures (Coinbase Smart Wallet, Safe) will verify. Without it, only EOA signatures are accepted.
+### Browser drop-in modal: "Sign in with wallet"
+
+The drop-in modal at `https://3d.irish/x402.js` speaks SIWX automatically — no merchant code changes. The same `<button data-x402-endpoint="…">` and `window.X402.pay({…})` keep working.
+
+When the 402 body carries the `sign-in-with-x` extension and the visitor has a matching wallet (Phantom for Solana, any `window.ethereum` wallet for EVM), the modal leads with a **Sign in with wallet** primary button and demotes paying to a secondary action:
+
+```
+┌─────────────────────────────────────┐
+│ THREE.WS ✕ │
+│ Download pole-dancer-rumba.glb │
+├─────────────────────────────────────┤
+│ 0.50 USDC ● Solana │
+├─────────────────────────────────────┤
+│ ✓ Confirming price │
+│ ◌ Connect wallet │
+│ │
+│ ┌─────────────────────────────────┐│
+│ │ Sign in with Phantom ││ ← primary
+│ └─────────────────────────────────┘│
+│ ┌─────────────────────────────────┐│
+│ │ Pay 0.50 USDC instead ││ ← secondary
+│ └─────────────────────────────────┘│
+│ Already paid for this once? Sign in │
+│ to re-enter without paying again. │
+└─────────────────────────────────────┘
+```
+
+Clicking **Sign in with wallet** opens the wallet, signs the CAIP-122 message the server advertised, and retries the endpoint with the `SIGN-IN-WITH-X` header. On `200` the success receipt reads "Welcome back!" and the call resolves identically to a paid one. If the retry returns `401`/`402` with `code: siwx_not_paid` (this wallet never paid for this resource), the modal silently drops the SIWX offer, shows a one-line "You haven't paid for this yet" notice, and falls back to the normal pay flow. When the 402 body has no SIWX extension, behavior is unchanged.
+
+A successful sign-in also dispatches a `x402:siwx-signed` CustomEvent (`detail: { address, network }`) on the bound element, right before the usual `x402:result`, so merchants can wire analytics:
+
+```js
+button.addEventListener('x402:siwx-signed', (e) => {
+ analytics.track('siwx_reentry', { wallet: e.detail.address, network: e.detail.network });
+});
+```
+
+A minimal manual test surface lives at `/siwx-test.html` — two SIWX-enabled endpoints plus a live event log.
+
---
## Config API
diff --git a/public/x402.js b/public/x402.js
index ed1b6319e..09fc17218 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -279,7 +279,16 @@ function buildSiwxMessage(info, chain, address) {
const chainRef = isEvm ? String(parseInt(chainTail, 10)) : chainTail;
const lines = [accountHeader, address, ''];
- if (info.statement) lines.push(info.statement, '');
+ if (info.statement) {
+ lines.push(info.statement, '');
+ } else if (isEvm) {
+ // siwe's prepareMessage() reserves the statement block even when the
+ // statement is absent, emitting an extra blank line (header, address,
+ // "", "", URI). SIWS's formatter does not. The server rebuilds the EVM
+ // message via siwe before recovering the signer, so omit-statement EVM
+ // must carry the same extra blank or the recovered address mismatches.
+ lines.push('');
+ }
lines.push(`URI: ${info.uri}`);
lines.push(`Version: ${info.version || '1'}`);
lines.push(`Chain ID: ${chainRef}`);
diff --git a/scripts/gen-cosmetics-catalog.mjs b/scripts/gen-cosmetics-catalog.mjs
new file mode 100644
index 000000000..ea69406d5
--- /dev/null
+++ b/scripts/gen-cosmetics-catalog.mjs
@@ -0,0 +1,21 @@
+// Generate the static cosmetics catalog mirror from the canonical source module
+// (api/_lib/cosmetics.js). The shop fetches /api/cosmetics/catalog first; this
+// static file at /cosmetics/catalog.json is the CDN-served fallback (and the
+// dev source, where /api/* proxies to prod and the new endpoint isn't live yet).
+//
+// Run after changing the catalog: node scripts/gen-cosmetics-catalog.mjs
+
+import { writeFile, mkdir } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { buildCatalog, RARITIES } from '../api/_lib/cosmetics.js';
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..');
+const outDir = join(root, 'public', 'cosmetics');
+const outFile = join(outDir, 'catalog.json');
+
+const payload = { items: buildCatalog(), rarities: RARITIES };
+
+await mkdir(outDir, { recursive: true });
+await writeFile(outFile, JSON.stringify(payload, null, '\t') + '\n');
+console.log(`wrote ${outFile} (${payload.items.length} items)`);
diff --git a/src/game/build-voxels.js b/src/game/build-voxels.js
index 6fe74e144..05d779748 100644
--- a/src/game/build-voxels.js
+++ b/src/game/build-voxels.js
@@ -50,11 +50,94 @@ export const BLOCK_TYPES = [
];
export const BLOCK_TYPE_COUNT = BLOCK_TYPES.length;
+// Composite pieces — ready-made structures placed as a single unit so a builder
+// can stamp a wall or a flight of stairs in one click instead of stacking dozens
+// of blocks by hand. Each piece is a list of cells in its own LOCAL frame (before
+// rotation): `dx`/`dz` are the horizontal footprint (rotated in 90° steps about
+// the anchor), `dy` is height (rotation-invariant), and an optional `t` pins a
+// block type — omit it and the cell inherits the player's selected palette block.
+// The anchor cell (where the ghost is aimed) is the piece's near-bottom corner,
+// so a piece grows up-and-forward from the cursor. The whole stamp goes through
+// the SAME server-authoritative block channel as single placements (a batch of
+// validated cells), so there's no second build path to keep honest.
+export const COMPOSITE_PIECES = [
+ {
+ id: 'wall', name: 'Wall', icon: '▯',
+ // 4 wide × 3 tall slab, one cell deep.
+ cells() {
+ const out = [];
+ for (let dx = 0; dx < 4; dx++) for (let dy = 0; dy < 3; dy++) out.push({ dx, dy, dz: 0 });
+ return out;
+ },
+ },
+ {
+ id: 'floor', name: 'Floor', icon: '▦',
+ // 4 × 4 flat slab — a platform or roof tile.
+ cells() {
+ const out = [];
+ for (let dx = 0; dx < 4; dx++) for (let dz = 0; dz < 4; dz++) out.push({ dx, dy: 0, dz });
+ return out;
+ },
+ },
+ {
+ id: 'ramp', name: 'Stairs', icon: '◢',
+ // A 4-step staircase climbing along +dx, 2 cells wide, solid underneath so
+ // it's walkable both as a ramp and as a viewing stand.
+ cells() {
+ const out = [];
+ for (let step = 0; step < 4; step++) {
+ for (let dy = 0; dy <= step; dy++) for (let dz = 0; dz < 2; dz++) out.push({ dx: step, dy, dz });
+ }
+ return out;
+ },
+ },
+ {
+ id: 'door', name: 'Doorway', icon: '🚪',
+ // A 3 × 3 wall with a 1-wide, 2-tall opening punched in the middle.
+ cells() {
+ const out = [];
+ for (let dx = 0; dx < 3; dx++) for (let dy = 0; dy < 3; dy++) {
+ if (dx === 1 && dy < 2) continue; // the doorway
+ out.push({ dx, dy, dz: 0 });
+ }
+ return out;
+ },
+ },
+];
+
+// The largest stamp any piece produces — the server caps a batch at this so a
+// crafted client can't smuggle a giant write through the composite channel, and
+// the footprint-ghost instance pool is sized to it.
+export const MAX_COMPOSITE_CELLS = COMPOSITE_PIECES.reduce((m, p) => Math.max(m, p.cells().length), 0);
+
const _dummy = new Object3D();
export function keyOf(gx, gy, gz) { return `${gx},${gy},${gz}`; }
export function parseKey(key) { const p = key.split(','); return [+p[0], +p[1], +p[2]]; }
+// Rotate a horizontal footprint offset by a quarter-turn step (0–3 = 0/90/180/270°)
+// about the anchor. Integer-only so a rotated piece stays perfectly grid-aligned.
+export function rotateXZ(dx, dz, rot) {
+ switch (((rot % 4) + 4) % 4) {
+ case 1: return [dz, -dx];
+ case 2: return [-dx, -dz];
+ case 3: return [-dz, dx];
+ default: return [dx, dz];
+ }
+}
+
+// Resolve a composite piece to absolute world cells for a given anchor, rotation,
+// and selected block type. Each cell is `{ x, y, z, t }` ready for the place/batch
+// channel. Returns [] for an unknown piece id so callers can treat it as a no-op.
+export function compositeCells(pieceId, anchor, rot, type) {
+ const piece = COMPOSITE_PIECES.find((p) => p.id === pieceId);
+ if (!piece || !anchor) return [];
+ return piece.cells().map(({ dx, dy, dz, t }) => {
+ const [rx, rz] = rotateXZ(dx, dz, rot);
+ return { x: anchor[0] + rx, y: anchor[1] + dy, z: anchor[2] + rz, t: t == null ? type : t };
+ });
+}
+
// Centre of a grid cell in world space. y is offset by half a block so gy=0 sits
// flush on the ground plane (its base at y=0, top at y=BLOCK).
export function cellToWorld(gx, gy, gz, target = new Vector3()) {
@@ -170,6 +253,7 @@ export class VoxelWorld {
this.index = new Map(); // key → { type, i }
this._meshes = []; // refreshed lazily for raycasting
this._buildGhost();
+ this._buildFootprintGhost();
}
get count() { return this.index.size; }
@@ -292,11 +376,72 @@ export class VoxelWorld {
hideGhost() { if (this._ghost) this._ghost.visible = false; }
+ // --- Composite footprint ghost ----------------------------------------
+ // A single InstancedMesh previewing every cell a composite piece would place,
+ // so a wall or staircase shows its full shape (and rotation) before you commit.
+ // One draw call regardless of piece size — it never competes with the build's
+ // own instanced batches for performance.
+ _buildFootprintGhost() {
+ const box = new BoxGeometry(BLOCK * 1.02, BLOCK * 1.02, BLOCK * 1.02);
+ this._fpGeom = box;
+ this._fpMat = new MeshBasicMaterial({ transparent: true, opacity: 0.22, depthWrite: false });
+ const m = new InstancedMesh(box, this._fpMat, MAX_COMPOSITE_CELLS);
+ m.frustumCulled = false;
+ m.count = 0;
+ m.visible = false;
+ this.scene.add(m);
+ this._fpGhost = m;
+ this._fpColor = new Color();
+ }
+
+ // Preview a composite piece's cells, tinted by whether the whole stamp can
+ // land (green) or is blocked (amber). Hides the single-cell ghost so the two
+ // cursors never overlap.
+ showFootprint(cells, valid) {
+ this.hideGhost();
+ if (!cells || cells.length === 0) { this.hideFootprint(); return; }
+ const n = Math.min(cells.length, MAX_COMPOSITE_CELLS);
+ for (let i = 0; i < n; i++) {
+ cellToWorld(cells[i].x, cells[i].y, cells[i].z, _dummy.position);
+ _dummy.rotation.set(0, 0, 0);
+ _dummy.scale.setScalar(1);
+ _dummy.updateMatrix();
+ this._fpGhost.setMatrixAt(i, _dummy.matrix);
+ }
+ this._fpGhost.count = n;
+ this._fpGhost.instanceMatrix.needsUpdate = true;
+ this._fpColor.setHex(valid ? 0x66ff8c : 0xffb648);
+ this._fpMat.color.copy(this._fpColor);
+ this._fpGhost.visible = true;
+ }
+
+ hideFootprint() { if (this._fpGhost) { this._fpGhost.visible = false; this._fpGhost.count = 0; } }
+
+ // True only when every cell of a proposed stamp is in bounds, empty, and the
+ // build has room for all of them under the block budget. Used to tint the
+ // footprint ghost and to gate a composite placement client-side.
+ canPlaceAll(cells, maxBlocks = Infinity) {
+ if (!cells || cells.length === 0) return false;
+ let fresh = 0;
+ const seen = new Set();
+ for (const c of cells) {
+ if (!cellInBounds(c.x, c.y, c.z)) return false;
+ const key = keyOf(c.x, c.y, c.z);
+ if (seen.has(key)) continue; // a piece never repeats a cell, but be safe
+ seen.add(key);
+ if (!this.index.has(key)) fresh++;
+ }
+ return this.count + fresh <= maxBlocks;
+ }
+
dispose() {
this.hideGhost();
+ this.hideFootprint();
this.scene.remove(this._ghost);
this._ghostFill.geometry.dispose(); this._ghostFill.material.dispose();
this._ghostEdges.geometry.dispose(); this._ghostEdges.material.dispose();
+ this.scene.remove(this._fpGhost);
+ this._fpGeom.dispose(); this._fpMat.dispose();
for (const b of this.batches) b.dispose();
this.geometry.dispose();
this.index.clear();
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 4ff1ec2b5..125e88b45 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -939,6 +939,12 @@ export class CommunityUI {
class: 'cc-buy-btn', type: 'button', title: 'Buy this coin',
onclick: () => this.h.onBuy?.(),
}, [el('span', { class: 'cc-buy-btn-ico', text: '⚡' }), this.buyBtnLabel]);
+ // Open the cosmetics shop — browse + try cosmetics on your avatar live.
+ this.shopBtn = el('button', {
+ class: 'cc-shop-btn', type: 'button', title: 'Cosmetics — try looks on your avatar',
+ 'aria-label': 'Open cosmetics shop',
+ onclick: () => this.h.onShop?.(),
+ }, [el('span', { class: 'cc-shop-btn-ico', 'aria-hidden': 'true', text: '🛍️' }), el('span', { class: 'cc-shop-btn-text', text: 'Shop' })]);
const banner = el('div', { class: 'cc-coin-banner' }, [
this.coinImg,
el('div', { class: 'cc-coin-info' }, [
@@ -949,6 +955,7 @@ export class CommunityUI {
this.tierBadge,
]),
]),
+ this.shopBtn,
this.buyBtn,
]);
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 641fe6cbe..cf54faa1f 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1525,3 +1525,195 @@ html, body {
.pg-card { padding: 28px 20px 24px; }
.pg-title { font-size: 19px; }
}
+
+/* ───────────────────────── Cosmetics shop (R21) ─────────────────────────
+ In-world panel: browse the cosmetics catalog, filter by rarity, preview a
+ cosmetic live on your own avatar before buying. Monochrome system — rarity
+ reads through border intensity + glow, not hue (light is the only colour). */
+
+/* The HUD shop-open button, seated in the coin banner next to Buy. */
+.cc-shop-btn {
+ flex: none; pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 7px;
+ margin-left: 4px; padding: 9px 13px;
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-weight: 700; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase;
+ cursor: pointer; white-space: nowrap;
+ transition: transform 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-shop-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }
+.cc-shop-btn:active { transform: translateY(1px); }
+.cc-shop-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-shop-btn-ico { font-size: 14px; line-height: 1; }
+
+.cc-shop {
+ position: fixed; inset: 0; z-index: 92;
+ display: grid; place-items: center; padding: 20px;
+ background: rgba(4, 4, 6, 0.62); backdrop-filter: blur(6px);
+ opacity: 0; transition: opacity 0.18s ease;
+ font: 14px/1.4 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+}
+.cc-shop.cc-shop-in { opacity: 1; }
+
+.cc-shop-panel {
+ width: min(760px, 100%); max-height: min(86vh, 720px);
+ display: flex; flex-direction: column;
+ background: var(--cc-panel-solid); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ box-shadow: var(--cc-shadow);
+ transform: translateY(10px) scale(0.99); opacity: 0;
+ transition: transform 0.2s cubic-bezier(0.16, 0.84, 0.34, 1), opacity 0.2s ease;
+}
+.cc-shop-in .cc-shop-panel { transform: none; opacity: 1; }
+
+.cc-shop-head {
+ display: flex; align-items: flex-start; justify-content: space-between;
+ gap: 12px; padding: 18px 18px 14px; border-bottom: 1px solid var(--cc-edge-soft);
+}
+.cc-shop-title { display: flex; flex-direction: column; gap: 3px; }
+.cc-shop-title-main { font-size: 17px; font-weight: 800; letter-spacing: 0.01em; }
+.cc-shop-title-sub { font-size: 12px; color: var(--cc-dim); }
+.cc-shop-close {
+ flex: none; width: 32px; height: 32px; display: grid; place-items: center;
+ background: none; border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ color: var(--cc-dim); font-size: 14px; cursor: pointer;
+ transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-shop-close:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.05); }
+.cc-shop-close:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+.cc-shop-filters {
+ display: flex; flex-wrap: wrap; gap: 7px; padding: 13px 18px;
+ border-bottom: 1px solid var(--cc-edge-soft);
+}
+.cc-shop-chip {
+ padding: 6px 13px; background: rgba(255, 255, 255, 0.03);
+ border: 1px solid var(--cc-edge); border-radius: 999px;
+ color: var(--cc-dim); font-size: 12px; font-weight: 600; letter-spacing: 0.02em;
+ cursor: pointer; transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-shop-chip:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.cc-shop-chip:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-shop-chip.cc-active {
+ color: var(--cc-ink); background: var(--cc-accent); border-color: var(--cc-accent);
+ box-shadow: var(--cc-glow);
+}
+
+.cc-shop-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 18px 18px; }
+.cc-shop-status {
+ padding: 12px 2px 8px; font-size: 11.5px; color: var(--cc-faint);
+ letter-spacing: 0.12em; text-transform: uppercase;
+}
+.cc-shop-grid {
+ display: grid; gap: 12px; padding-top: 6px;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+}
+.cc-shop-grid.cc-shop-empty-grid { display: block; }
+
+/* A card is a click-to-toggle preview button. */
+.cc-shop-card {
+ display: flex; flex-direction: column; text-align: left;
+ padding: 0; background: var(--cc-bg2);
+ border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius);
+ color: var(--cc-text); cursor: pointer; overflow: hidden;
+ transition: transform 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;
+}
+.cc-shop-card:hover { transform: translateY(-2px); border-color: var(--cc-edge-hi); }
+.cc-shop-card:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-shop-card.cc-active {
+ border-color: var(--cc-accent); box-shadow: var(--cc-glow);
+}
+
+.cc-shop-thumb {
+ position: relative; aspect-ratio: 1 / 1; width: 100%;
+ display: grid; place-items: center; overflow: hidden;
+ background:
+ radial-gradient(120% 120% at 50% 20%, rgba(255, 255, 255, 0.07), rgba(255, 255, 255, 0) 60%),
+ var(--cc-bg3);
+ border-bottom: 1px solid var(--cc-edge-soft);
+}
+.cc-shop-thumb-img { width: 100%; height: 100%; object-fit: contain; padding: 10px; }
+.cc-shop-glyph { font-size: 42px; line-height: 1; opacity: 0.82; filter: grayscale(1) brightness(1.4); }
+
+.cc-shop-rarity {
+ position: absolute; top: 7px; left: 7px;
+ padding: 2px 7px; border-radius: 999px;
+ font-size: 9.5px; font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase;
+ color: var(--cc-text); background: rgba(0, 0, 0, 0.55);
+ border: 1px solid var(--cc-edge);
+}
+.cc-shop-rarity[data-rarity="rare"] { border-color: rgba(255, 255, 255, 0.32); }
+.cc-shop-rarity[data-rarity="epic"] { border-color: rgba(255, 255, 255, 0.55); color: #fff; }
+.cc-shop-rarity[data-rarity="legendary"] { border-color: #fff; color: var(--cc-ink); background: rgba(255, 255, 255, 0.92); }
+
+.cc-shop-preview-tag {
+ position: absolute; bottom: 7px; right: 7px;
+ padding: 2px 8px; border-radius: 999px;
+ font-size: 10px; font-weight: 700; letter-spacing: 0.04em;
+ color: var(--cc-ink); background: rgba(255, 255, 255, 0.9);
+ opacity: 0; transform: translateY(3px); transition: opacity 0.12s ease, transform 0.12s ease;
+}
+.cc-shop-card:hover .cc-shop-preview-tag { opacity: 1; transform: none; }
+.cc-shop-card.cc-active .cc-shop-preview-tag { opacity: 1; transform: none; background: var(--cc-accent); }
+
+.cc-shop-meta { display: flex; flex-direction: column; gap: 6px; padding: 10px 11px 11px; }
+.cc-shop-name { font-size: 13px; font-weight: 700; letter-spacing: 0.01em; }
+.cc-shop-badge {
+ display: inline-flex; align-items: center; gap: 5px; align-self: flex-start;
+ font-size: 11px; font-weight: 700; letter-spacing: 0.02em;
+}
+.cc-shop-badge.cc-owned { color: var(--cc-text); }
+.cc-shop-badge.cc-owned::before {
+ content: "✓"; font-size: 10px; color: var(--cc-ink);
+ width: 15px; height: 15px; border-radius: 50%; display: grid; place-items: center;
+ background: var(--cc-accent);
+}
+.cc-shop-badge.cc-locked { color: var(--cc-dim); }
+.cc-lock-ico { font-size: 10px; filter: grayscale(1); }
+.cc-shop-card.cc-is-locked .cc-shop-thumb-img,
+.cc-shop-card.cc-is-locked .cc-shop-glyph { opacity: 0.78; }
+
+/* Skeleton loading cards. */
+.cc-shop-skel { pointer-events: none; }
+.cc-skel-box { width: 100%; aspect-ratio: 1 / 1; }
+.cc-skel-line { height: 11px; border-radius: 3px; }
+.cc-skel-short { width: 55%; }
+.cc-skel-box, .cc-skel-line {
+ background: linear-gradient(100deg, rgba(255, 255, 255, 0.04) 30%, rgba(255, 255, 255, 0.12) 50%, rgba(255, 255, 255, 0.04) 70%);
+ background-size: 200% 100%; animation: cc-shimmer 1.3s ease-in-out infinite;
+}
+@keyframes cc-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+
+/* Empty + error states. */
+.cc-shop-empty {
+ display: flex; flex-direction: column; align-items: center; text-align: center;
+ gap: 8px; padding: 48px 24px;
+}
+.cc-shop-empty-ico { font-size: 30px; opacity: 0.7; }
+.cc-shop-empty-title { font-size: 15px; font-weight: 700; }
+.cc-shop-empty-sub { font-size: 13px; color: var(--cc-dim); max-width: 320px; }
+.cc-shop-retry {
+ margin-top: 8px; padding: 8px 18px;
+ background: var(--cc-accent); color: var(--cc-ink);
+ border: 1px solid var(--cc-accent); border-radius: var(--cc-radius-sm);
+ font-size: 12px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase;
+ cursor: pointer; box-shadow: var(--cc-glow);
+ transition: transform 0.12s ease, opacity 0.12s ease;
+}
+.cc-shop-retry:hover { transform: translateY(-1px); }
+.cc-shop-retry:active { transform: translateY(1px); }
+.cc-shop-retry:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+@media (prefers-reduced-motion: reduce) {
+ .cc-shop, .cc-shop-panel, .cc-shop-card, .cc-shop-preview-tag { transition: none; }
+ .cc-skel-box, .cc-skel-line { animation: none; }
+}
+
+@media (max-width: 640px) {
+ .cc-shop-btn-text { display: none; }
+ .cc-shop-btn { padding: 9px 11px; margin-left: 2px; }
+ .cc-shop { padding: 0; place-items: stretch; }
+ .cc-shop-panel { width: 100%; max-height: 100%; height: 100%; border: none; border-radius: 0; }
+ .cc-shop-grid { grid-template-columns: repeat(auto-fill, minmax(132px, 1fr)); }
+}
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 1b434f32c..0bcc56a72 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -16,7 +16,7 @@ import {
Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry,
CylinderGeometry, PlaneGeometry,
CanvasTexture, TextureLoader, DoubleSide,
- Raycaster, Vector2,
+ Raycaster, Vector2, WebGLRenderTarget,
} from 'three';
import { AnimationManager } from '../animation-manager.js';
@@ -26,13 +26,18 @@ import { createWorldEnvironment, seedFromString } from './world-env.js';
import { createChartScreen } from './chart-screen.js';
import { mountOracleRibbon } from './oracle-ribbon.js';
import { MarketReactor } from './market-reactor.js';
-import { VoxelWorld, createBuildHud, parseKey, MAX_BLOCKS } from './build-voxels.js';
+import {
+ VoxelWorld, createBuildHud, parseKey, keyOf, MAX_BLOCKS,
+ COMPOSITE_PIECES, compositeCells, MAX_COMPOSITE_CELLS,
+} from './build-voxels.js';
import { normalizeGatewayURL } from '../ipfs.js';
import {
loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,
CLIP_IDLE, CLIP_WALK,
} from './avatar-rig.js';
import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';
+import { AccessoryManager } from '../agent-accessories.js';
+import { CosmeticsShop } from './cosmetics-shop.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
import { AgentCommerce } from './agent-commerce.js';
import { WorldLife } from './npc/world-life.js';
@@ -220,15 +225,27 @@ export class CoinCommunities {
},
onRename: (name) => this._rename(name),
onBuy: () => this._openBuy(),
+ onShop: () => this._toggleShop(),
onVoiceToggle: () => this._toggleVoice(),
+ // Build structures toolbar (R20): pick a composite piece, rotate it, share a
+ // screenshot of the build, or open this coin's featured builds.
+ onPickPiece: (id) => this._pickPiece(id),
+ onRotateBuild: () => this._rotateBuild(),
+ onShareBuild: () => this._shareBuild(),
+ onOpenFeatured: () => this._openFeatured(),
+ onPublishBuild: (meta) => this._publishBuild(meta),
});
// Collaborative building HUD (hotbar + place/break toggle). Hidden until the
// player is in a world and connected — there's nowhere to build otherwise.
this.buildType = 0;
+ // R20 structures: which composite piece is armed (null = single block) and the
+ // quarter-turn rotation (0–3) applied to it. Both drive the ghost preview.
+ this.buildPiece = null;
+ this.buildRot = 0;
this.buildHud = createBuildHud({
onToggle: (on) => this._onBuildToggle(on),
- onPick: (i) => { this.buildType = i; },
+ onPick: (i) => { this.buildType = i; this._refreshGhost(); },
onModeChange: () => this._refreshGhost(),
});
this.buildHud.root.hidden = true;
@@ -651,6 +668,10 @@ export class CoinCommunities {
this.localRig = new Group();
this.localRig.position.copy(this.localPos);
this.scene.add(this.localRig);
+ // Cosmetics preview rig (R21) re-binds to whatever avatar is current —
+ // drop any prior session's manager so it attaches to this fresh skeleton.
+ this._accessoryMgr = null;
+ this._previewItem = null;
this.localAnim = new AnimationManager();
const avatarInput = this.ui.getAvatar();
const url = await resolveAvatarUrl(avatarInput);
@@ -1032,6 +1053,10 @@ export class CoinCommunities {
if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }
if (this.worldLife) { this.worldLife.dispose(); this.worldLife = null; }
if (this._onboard) { this._onboard.dispose(); this._onboard = null; }
+ // Close the shop and drop the rig binding — the next world rebuilds both.
+ if (this._shop?.isOpen()) this._shop.close();
+ this._accessoryMgr = null;
+ this._previewPresetId = null; this._previewLayers = false; this._previewItem = null;
for (const [, r] of this.remotes) r.dispose();
this.remotes.clear();
if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }
@@ -1090,6 +1115,76 @@ export class CoinCommunities {
_sendChat(text) { this.net?.sendChat(text); }
_emote(name) { this.net?.sendEmote(name); playEmoteClip(this.localAnim, name, this.motion); }
+ // ── Cosmetics live preview (R21) ──────────────────────────────────────────
+ // The shop previews a catalog item on YOUR OWN avatar before any purchase.
+ // This is the local R03 rig hook: bone-attach GLBs, drive outfit morphs,
+ // recolour garment layers, or play premium emote clips — never broadcast,
+ // never persisted (a purchase is R22/R23). Selecting reverts the previous
+ // preview first, so only one item previews at a time.
+
+ // Bind an AccessoryManager to the live local skeleton. localRig holds the
+ // avatar model + its bones, which is all the rig needs; invalidate is a no-op
+ // because /play renders every frame (no on-demand invalidation loop).
+ _ensureAccessoryMgr() {
+ if (!this.localRig) return null;
+ if (!this._accessoryMgr) {
+ this._accessoryMgr = new AccessoryManager({ content: this.localRig, invalidate: () => {} });
+ }
+ return this._accessoryMgr;
+ }
+
+ // Preview a catalog item live. Returns true if something visible happened.
+ async equipCosmeticPreview(item) {
+ if (!item) return false;
+ this.unequipCosmeticPreview();
+ this._previewItem = item;
+ // Emotes preview as a one-shot clip that naturally returns to locomotion.
+ if (item.kind === 'emote' && item.emote) {
+ playEmoteClip(this.localAnim, item.emote, this.motion);
+ return true;
+ }
+ const mgr = this._ensureAccessoryMgr();
+ if (!mgr) return false;
+ // Skins recolour the avatar's own garment layers (absolute state).
+ if (item.kind === 'skin' && item.colors) {
+ mgr.applyLayers({ colors: item.colors, hidden: [] });
+ this._previewLayers = true;
+ return true;
+ }
+ // Hats / glasses / earrings (GLB) and outfits (morph) go through presets.
+ if (item.glbUrl || item.morphBinding) {
+ await mgr.applyPreset({
+ id: item.id, kind: item.kind, name: item.name,
+ glbUrl: item.glbUrl, attachBone: item.attachBone, morphBinding: item.morphBinding,
+ });
+ this._previewPresetId = item.id;
+ return true;
+ }
+ return false;
+ }
+
+ // Open/close the cosmetics shop (R21). Lazy-built; previews route to the
+ // local rig hooks above. Reverts any preview when it closes.
+ _toggleShop() {
+ if (!this._shop) {
+ this._shop = new CosmeticsShop({
+ onPreview: (item) => this.equipCosmeticPreview(item),
+ onEndPreview: () => this.unequipCosmeticPreview(),
+ });
+ }
+ this._shop.toggle();
+ }
+
+ // Revert the active preview, leaving the avatar exactly as it was.
+ unequipCosmeticPreview() {
+ const mgr = this._accessoryMgr;
+ if (mgr) {
+ if (this._previewLayers) { mgr.applyLayers({ colors: {}, hidden: [] }); this._previewLayers = false; }
+ if (this._previewPresetId) { mgr.removePreset(this._previewPresetId); this._previewPresetId = null; }
+ }
+ this._previewItem = null;
+ }
+
// Surface unread chat in the tab title when the page is backgrounded, so a
// new message pulls the user back. Cleared the moment they refocus the tab.
_bumpTabUnread() {
@@ -1164,6 +1259,12 @@ export class CoinCommunities {
this.buildHud.select(k === '0' ? 9 : Number(k) - 1);
return;
}
+ // R rotates the armed composite piece a quarter-turn while building.
+ if (k === 'r' && this.buildHud.active && this.buildPiece) {
+ e.preventDefault();
+ this._rotateBuild();
+ return;
+ }
// E watches the Agent Exchange round when standing near the agents in
// the home town (no-op elsewhere). Not while building.
if (k === 'e' && !this.buildHud.active) {
@@ -1293,7 +1394,15 @@ export class CoinCommunities {
if (!this.voxels || this.phase !== 'world' || !this._buildableConnection()) return;
const target = this.voxels.raycast(this._pointerRay(clientX, clientY));
if (!target) return;
- if (forceRemove || this.buildHud.mode === 'remove') {
+ const removing = forceRemove || this.buildHud.mode === 'remove';
+ // A composite piece stamps several cells at once — but only when placing.
+ // Break mode always falls back to the single-cell path below.
+ if (!removing && this.buildPiece && target.placeCell) {
+ this._placeComposite(target.placeCell);
+ this._updateGhost(clientX, clientY);
+ return;
+ }
+ if (removing) {
if (target.hit === 'block' && target.cell) {
// Capture the type before it's gone so undo can put it back exactly.
const prevType = this.voxels.typeAt(...target.cell);
@@ -1319,6 +1428,55 @@ export class CoinCommunities {
this._updateGhost(clientX, clientY);
}
+ // Stamp a composite piece (wall / floor / stairs / doorway) anchored at `cell`,
+ // rotated by the current quarter-turn. Validated as a whole: every cell must be
+ // in bounds, empty, and fit the budget, or nothing lands — so a piece never
+ // half-appears. Online it goes through the place-batch channel (server echoes
+ // each block back); solo it's applied to the local layer directly. Undo records
+ // just the cells this stamp actually created.
+ _placeComposite(cell) {
+ const cells = compositeCells(this.buildPiece, cell, this.buildRot, this.buildType);
+ if (!cells.length) return;
+ if (!this.voxels.canPlaceAll(cells, MAX_BLOCKS)) {
+ this.voxels.showFootprint(cells, false);
+ // Name the most likely reason so a blocked stamp isn't a silent no-op.
+ const overBudget = this.voxels.count + cells.length > MAX_BLOCKS;
+ this.ui.toast(overBudget
+ ? `Not enough room — that piece needs ${cells.length} blocks.`
+ : 'That piece doesn’t fit here — rotate it or move back.', 'warn');
+ return;
+ }
+ // The cells this stamp newly creates (a piece may overlap existing blocks);
+ // only those are recorded for undo so we never break a neighbour's work.
+ const fresh = cells.filter((c) => !this.voxels.hasBlock(keyOf(c.x, c.y, c.z)));
+ const online = this.net?.status === 'online';
+ if (online) {
+ this.net.sendPlaceBatch(cells);
+ } else {
+ for (const c of cells) this.voxels.setBlock(c.x, c.y, c.z, c.t);
+ this._syncBudget();
+ }
+ if (fresh.length) this._pushUndo({ kind: 'remove-batch', cells: fresh.map((c) => [c.x, c.y, c.z]) });
+ }
+
+ // Arm a composite piece (or null for single-block mode) and reflect it in the
+ // toolbar + ghost. Resets rotation so each piece starts square-on.
+ _pickPiece(id) {
+ this.buildPiece = COMPOSITE_PIECES.some((p) => p.id === id) ? id : null;
+ this.buildRot = 0;
+ this.ui.setBuildPiece(this.buildPiece);
+ this.ui.setBuildRotation(this.buildRot);
+ this._refreshGhost();
+ }
+
+ // Rotate the armed piece a quarter-turn and re-preview it in place.
+ _rotateBuild() {
+ if (!this.buildPiece) return;
+ this.buildRot = (this.buildRot + 1) % 4;
+ this.ui.setBuildRotation(this.buildRot);
+ this._refreshGhost();
+ }
+
// Arm a hold-to-break timer for the current press. If the player keeps the
// pointer down and still (no drag) past LONG_PRESS_MS, break the targeted block
// — the touch-native equivalent of a right-click. Cancelled by movement or release.
@@ -1393,6 +1551,10 @@ export class CoinCommunities {
rate: 'Building too fast — slow down a moment.',
bounds: 'Can’t build there — outside the build area.',
type: 'That block type isn’t available.',
+ owned: 'That block belongs to another builder — you can’t change it.',
+ column: 'That stack is too tall here — try building wider, not higher.',
+ protected: 'That spot is protected — keep the spawn and totem clear.',
+ player: 'You’ve hit your block limit for this world — break some to build more.',
}[reason] || 'That edit couldn’t be applied.';
this.ui.toast(msg, 'warn');
}
@@ -1402,11 +1564,18 @@ export class CoinCommunities {
_updateGhost(clientX, clientY) {
if (!this.voxels) return;
const target = this.voxels.raycast(this._pointerRay(clientX, clientY));
- if (!target) { this.voxels.hideGhost(); return; }
+ if (!target) { this.voxels.hideGhost(); this.voxels.hideFootprint(); return; }
if (this.buildHud.mode === 'remove') {
+ this.voxels.hideFootprint();
if (target.hit === 'block') this.voxels.showGhost(target.cell, 'remove');
else this.voxels.hideGhost();
+ } else if (this.buildPiece && target.placeCell) {
+ // Preview the whole composite footprint (rotated), tinted by whether it
+ // can land in one piece.
+ const cells = compositeCells(this.buildPiece, target.placeCell, this.buildRot, this.buildType);
+ this.voxels.showFootprint(cells, this.voxels.canPlaceAll(cells, MAX_BLOCKS));
} else {
+ this.voxels.hideFootprint();
this.voxels.showGhost(target.placeCell, target.placeValid ? 'place' : 'blocked');
}
}
diff --git a/src/game/community-net.js b/src/game/community-net.js
index d7e17dafb..f3268baf2 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -412,6 +412,10 @@ export class CommunityNet {
// request the edit; the block is added/removed locally when the server patches
// state.blocks (see the onAdd/onRemove wiring above).
sendPlace(x, y, z, t) { this.room?.send('place', { x, y, z, t }); }
+ // Place a composite piece in one atomic message: an array of {x,y,z,t} cells the
+ // server validates and applies all-or-nothing (see WalkRoom._handlePlaceBatch).
+ // Each placed block streams back through the same blockAdd path as single edits.
+ sendPlaceBatch(cells) { this.room?.send('place-batch', { cells }); }
sendRemove(x, y, z) { this.room?.send('remove', { x, y, z }); }
sendInteract(to, action) { this.room?.send('interact', { to, action }); }
// Spatial voice: relay a WebRTC offer/answer/ICE candidate to one peer, and
diff --git a/src/game/cosmetics-shop.js b/src/game/cosmetics-shop.js
new file mode 100644
index 000000000..7d5153b0b
--- /dev/null
+++ b/src/game/cosmetics-shop.js
@@ -0,0 +1,300 @@
+// Cosmetics Shop (R21) — in-world panel to browse the cosmetics catalog, filter
+// by rarity, and preview any item LIVE on your own avatar before buying.
+//
+// The shop is pure 2D chrome: it fetches the real catalog and calls back into
+// the scene (coincommunities.js) to equip/unequip a preview on the local rig.
+// It never mutates the 3D scene directly and never persists a purchase — that's
+// R22 (x402) / R23 (inventory). Prices are denominated in $THREE, the only coin.
+//
+// Catalog source: the real endpoint /api/cosmetics/catalog, with the static CDN
+// mirror /cosmetics/catalog.json as a resilient fallback (and the dev source,
+// where /api/* proxies to prod and the endpoint isn't deployed yet). Both are
+// real network fetches — there is no client-side sample array.
+
+import { log } from '../shared/log.js';
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'html') n.innerHTML = v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v !== null && v !== undefined && v !== false) n.setAttribute(k, v === true ? '' : v);
+ }
+ for (const kid of [].concat(kids)) if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ return n;
+}
+
+const RARITY_LABEL = { common: 'Common', rare: 'Rare', epic: 'Epic', legendary: 'Legendary' };
+// Placeholder glyph per slot, shown when an item has no preview image.
+const SLOT_GLYPH = { hat: '🎩', glasses: '🕶️', earrings: '💎', outfit: '👕', skin: '🎨', emote: '✨' };
+
+const fmtPrice = (n) => {
+ if (!n || !isFinite(n)) return '0';
+ if (n >= 1000) return (n / 1000).toFixed(n % 1000 ? 1 : 0) + 'K';
+ return String(n);
+};
+
+// Fetch the catalog from the real endpoint, falling back to the static mirror.
+// Throws only if neither source yields items, so the UI can show its error state.
+async function fetchCatalog(rarity) {
+ const qs = rarity ? `?rarity=${encodeURIComponent(rarity)}` : '';
+ const sources = [`/api/cosmetics/catalog${qs}`, '/cosmetics/catalog.json'];
+ for (const url of sources) {
+ try {
+ const r = await fetch(url, { headers: { accept: 'application/json' } });
+ if (!r.ok) continue;
+ const data = await r.json();
+ if (Array.isArray(data?.items)) return data.items;
+ } catch { /* try the next source */ }
+ }
+ throw new Error('catalog unavailable');
+}
+
+export class CosmeticsShop {
+ /**
+ * @param {object} h handlers:
+ * onPreview(item) — equip the item live on the local avatar.
+ * onEndPreview() — revert the active preview.
+ */
+ constructor(h = {}) {
+ this.h = h;
+ this.items = [];
+ this.rarity = 'all'; // active rarity filter
+ this.previewId = null; // id of the item currently previewing (toggle)
+ this.state = 'idle'; // idle | loading | ready | error
+ this._build();
+ }
+
+ _build() {
+ this.closeBtn = el('button', {
+ class: 'cc-shop-close', type: 'button', 'aria-label': 'Close shop',
+ onclick: () => this.close(),
+ }, [el('span', { 'aria-hidden': 'true', text: '✕' })]);
+
+ this.filters = el('div', { class: 'cc-shop-filters', role: 'tablist', 'aria-label': 'Filter by rarity' });
+
+ this.grid = el('div', { class: 'cc-shop-grid' });
+ this.statusEl = el('div', { class: 'cc-shop-status', hidden: true, role: 'status', 'aria-live': 'polite' });
+
+ this.body = el('div', { class: 'cc-shop-body' }, [this.statusEl, this.grid]);
+
+ this.panel = el('div', {
+ class: 'cc-shop-panel', role: 'dialog', 'aria-modal': 'false',
+ 'aria-label': 'Cosmetics shop',
+ }, [
+ el('div', { class: 'cc-shop-head' }, [
+ el('div', { class: 'cc-shop-title' }, [
+ el('span', { class: 'cc-shop-title-main', text: 'Cosmetics' }),
+ el('span', { class: 'cc-shop-title-sub', text: 'Preview live on your avatar' }),
+ ]),
+ this.closeBtn,
+ ]),
+ this.filters,
+ this.body,
+ ]);
+
+ this.root = el('div', { class: 'cc-shop', id: 'cc-shop', hidden: true }, [this.panel]);
+ // Backdrop tap closes; panel taps don't bubble out.
+ this.root.addEventListener('click', (e) => { if (e.target === this.root) this.close(); });
+ this._onKey = (e) => { if (e.key === 'Escape' && !this.root.hidden) { e.stopPropagation(); this.close(); } };
+
+ document.body.appendChild(this.root);
+ this._buildFilters();
+ }
+
+ _buildFilters() {
+ this.filters.textContent = '';
+ const make = (key, label) => el('button', {
+ class: 'cc-shop-chip' + (this.rarity === key ? ' cc-active' : ''),
+ type: 'button', role: 'tab', 'aria-selected': this.rarity === key ? 'true' : 'false',
+ 'data-rarity': key,
+ onclick: () => this._setRarity(key),
+ }, label);
+ this.filters.appendChild(make('all', 'All'));
+ for (const r of ['common', 'rare', 'epic', 'legendary']) this.filters.appendChild(make(r, RARITY_LABEL[r]));
+ }
+
+ _setRarity(key) {
+ if (this.rarity === key) return;
+ this.rarity = key;
+ this._buildFilters();
+ this._render();
+ }
+
+ // ── open / close ──────────────────────────────────────────────────────────
+
+ isOpen() { return !this.root.hidden; }
+ toggle() { this.isOpen() ? this.close() : this.open(); }
+
+ async open() {
+ if (this.isOpen()) return;
+ this.root.hidden = false;
+ requestAnimationFrame(() => this.root.classList.add('cc-shop-in'));
+ document.addEventListener('keydown', this._onKey, true);
+ this.closeBtn.focus();
+ // Load once; re-open reuses the catalog (cheap, and avoids a flash).
+ if (this.state !== 'ready') await this._load();
+ else this._render();
+ }
+
+ close() {
+ if (!this.isOpen()) return;
+ this.root.classList.remove('cc-shop-in');
+ document.removeEventListener('keydown', this._onKey, true);
+ // Reverting any live preview is the whole point — don't leave a tried-on
+ // item stuck on the avatar after the shop closes.
+ this._clearPreview();
+ // Match the CSS transition before hiding so the exit animates.
+ setTimeout(() => { this.root.hidden = true; }, 180);
+ }
+
+ dispose() {
+ document.removeEventListener('keydown', this._onKey, true);
+ this.root.remove();
+ }
+
+ // ── data ──────────────────────────────────────────────────────────────────
+
+ async _load() {
+ this.state = 'loading';
+ this._renderSkeleton();
+ try {
+ // Always fetch the full catalog; rarity filtering is client-side so
+ // switching tabs is instant and needs no refetch.
+ this.items = await fetchCatalog();
+ this.state = 'ready';
+ this._render();
+ } catch (err) {
+ log.warn('[shop] catalog load failed:', err?.message);
+ this.state = 'error';
+ this._renderError();
+ }
+ }
+
+ // ── rendering ───────────────────────────────────────────────────────────────
+
+ _status(text) {
+ this.statusEl.textContent = text || '';
+ this.statusEl.hidden = !text;
+ }
+
+ _renderSkeleton() {
+ this._status('');
+ this.grid.textContent = '';
+ this.grid.classList.remove('cc-shop-empty-grid');
+ for (let i = 0; i < 8; i++) {
+ this.grid.appendChild(el('div', { class: 'cc-shop-card cc-shop-skel', 'aria-hidden': 'true' }, [
+ el('div', { class: 'cc-shop-thumb cc-skel-box' }),
+ el('div', { class: 'cc-shop-meta' }, [
+ el('div', { class: 'cc-skel-line' }),
+ el('div', { class: 'cc-skel-line cc-skel-short' }),
+ ]),
+ ]));
+ }
+ }
+
+ _renderError() {
+ this._status('');
+ this.grid.textContent = '';
+ this.grid.classList.add('cc-shop-empty-grid');
+ this.grid.appendChild(el('div', { class: 'cc-shop-empty' }, [
+ el('div', { class: 'cc-shop-empty-ico', 'aria-hidden': 'true', text: '⚠' }),
+ el('div', { class: 'cc-shop-empty-title', text: 'Couldn’t load the shop' }),
+ el('div', { class: 'cc-shop-empty-sub', text: 'The catalog didn’t load. Check your connection and try again.' }),
+ el('button', { class: 'cc-shop-retry', type: 'button', text: 'Retry', onclick: () => this._load() }),
+ ]));
+ }
+
+ _render() {
+ if (this.state === 'loading') return this._renderSkeleton();
+ if (this.state === 'error') return this._renderError();
+
+ const list = this.rarity === 'all' ? this.items : this.items.filter((i) => i.rarity === this.rarity);
+ this.grid.textContent = '';
+
+ if (!list.length) {
+ this.grid.classList.add('cc-shop-empty-grid');
+ this.grid.appendChild(el('div', { class: 'cc-shop-empty' }, [
+ el('div', { class: 'cc-shop-empty-ico', 'aria-hidden': 'true', text: '🔍' }),
+ el('div', { class: 'cc-shop-empty-title', text: 'Nothing in this tier yet' }),
+ el('div', { class: 'cc-shop-empty-sub', text: 'No cosmetics match this rarity. Try another filter.' }),
+ el('button', { class: 'cc-shop-retry', type: 'button', text: 'Show all', onclick: () => this._setRarity('all') }),
+ ]));
+ this._status('');
+ return;
+ }
+
+ this.grid.classList.remove('cc-shop-empty-grid');
+ const ownedCount = list.filter((i) => i.owned).length;
+ this._status(`${list.length} item${list.length === 1 ? '' : 's'} · ${ownedCount} owned`);
+ for (const item of list) this.grid.appendChild(this._card(item));
+ }
+
+ _card(item) {
+ const active = this.previewId === item.id;
+
+ const thumb = item.previewImage
+ ? el('img', {
+ class: 'cc-shop-thumb-img', src: item.previewImage, alt: '', loading: 'lazy',
+ // Missing/404 art degrades to the slot glyph instead of a broken icon.
+ onerror: (e) => { e.target.replaceWith(this._glyph(item)); },
+ })
+ : this._glyph(item);
+
+ const badge = item.owned
+ ? el('span', { class: 'cc-shop-badge cc-owned', text: 'Owned' })
+ : el('span', { class: 'cc-shop-badge cc-locked' }, [
+ el('span', { class: 'cc-lock-ico', 'aria-hidden': 'true', text: '🔒' }),
+ el('span', { text: `${fmtPrice(item.price)} $THREE` }),
+ ]);
+
+ const card = el('button', {
+ class: 'cc-shop-card'
+ + ` cc-rarity-${item.rarity}`
+ + (item.owned ? ' cc-is-owned' : ' cc-is-locked')
+ + (active ? ' cc-active' : ''),
+ type: 'button',
+ 'aria-pressed': active ? 'true' : 'false',
+ 'aria-label': `${item.name} — ${RARITY_LABEL[item.rarity]}, ${item.owned ? 'owned' : `locked, ${item.price} $THREE`}. ${active ? 'Stop preview' : 'Preview on your avatar'}`,
+ title: active ? 'Click to stop preview' : 'Click to preview on your avatar',
+ onclick: () => this._toggleItem(item),
+ }, [
+ el('div', { class: 'cc-shop-thumb' }, [
+ thumb,
+ el('span', { class: 'cc-shop-rarity', 'data-rarity': item.rarity, text: RARITY_LABEL[item.rarity] }),
+ el('span', { class: 'cc-shop-preview-tag', 'aria-hidden': 'true', text: active ? 'Previewing' : 'Preview' }),
+ ]),
+ el('div', { class: 'cc-shop-meta' }, [
+ el('span', { class: 'cc-shop-name', text: item.name }),
+ badge,
+ ]),
+ ]);
+ return card;
+ }
+
+ _glyph(item) {
+ return el('div', { class: 'cc-shop-glyph', 'aria-hidden': 'true', text: SLOT_GLYPH[item.slot] || '✦' });
+ }
+
+ // ── preview toggle ────────────────────────────────────────────────────────
+
+ async _toggleItem(item) {
+ // Re-selecting the active item ends the preview.
+ if (this.previewId === item.id) { this._clearPreview(); this._render(); return; }
+ this.previewId = item.id;
+ this._render();
+ try {
+ await this.h.onPreview?.(item);
+ } catch (err) {
+ log.warn('[shop] preview failed:', err?.message);
+ }
+ }
+
+ _clearPreview() {
+ if (!this.previewId) return;
+ this.previewId = null;
+ try { this.h.onEndPreview?.(); } catch { /* ignore */ }
+ }
+}
diff --git a/tests/chat-models.test.js b/tests/chat-models.test.js
new file mode 100644
index 000000000..a77127e19
--- /dev/null
+++ b/tests/chat-models.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect } from 'vitest';
+import {
+ MODEL_CATALOG,
+ modelSupportsTools,
+ isModelModerationGated,
+ usableModels,
+ DEFAULT_FREE_MODEL,
+ DEFAULT_PROVIDER_ORDER,
+ PROVIDER_MODEL_DEFAULTS,
+ OPENROUTER_SIBLINGS,
+ ANON_PROVIDER_LIST,
+ MAX_FALLBACK_ATTEMPTS,
+ TOTAL_BUDGET_MS,
+} from '../api/_lib/chat-models.js';
+
+// Models removed from the catalog because they will never succeed: OpenRouter
+// 404 "No endpoints found" / no tool-capable endpoint. They must never appear
+// in any routing list.
+const DEAD_ROUTES = [
+ 'mistralai/mistral-7b-instruct:free',
+ 'meta-llama/llama-3.2-3b-instruct:free',
+ 'openai/gpt-oss-120b', // non-free variant, never catalogued
+];
+
+describe('chat-models catalog', () => {
+ it('does not carry permanently-broken routes', () => {
+ for (const dead of DEAD_ROUTES) {
+ expect(MODEL_CATALOG[dead], `${dead} should be absent`).toBeUndefined();
+ }
+ });
+
+ it('every catalogued model declares a provider and tool capability', () => {
+ for (const [id, meta] of Object.entries(MODEL_CATALOG)) {
+ expect(meta.provider, `${id} provider`).toBeTruthy();
+ expect(typeof meta.tools, `${id} tools`).toBe('boolean');
+ }
+ });
+
+ it('marks gpt-oss-120b:free moderation-gated and tool-capable', () => {
+ expect(isModelModerationGated('openai/gpt-oss-120b:free')).toBe(true);
+ expect(modelSupportsTools('openai/gpt-oss-120b:free')).toBe(true);
+ });
+});
+
+describe('usableModels (route selector)', () => {
+ const ALL = Object.keys(MODEL_CATALOG);
+
+ it('a tool-required request never returns a non-tool model', () => {
+ // Inject a hypothetical non-tool model id and confirm it is filtered.
+ const candidates = [...ALL, 'meta-llama/llama-3.2-3b-instruct:free'];
+ const picked = usableModels(candidates, { requireTools: true });
+ for (const m of picked) {
+ expect(modelSupportsTools(m), `${m} must support tools`).toBe(true);
+ }
+ // The unknown/non-tool id is dropped.
+ expect(picked).not.toContain('meta-llama/llama-3.2-3b-instruct:free');
+ });
+
+ it('excludes moderation-gated models from auto selection by default', () => {
+ const picked = usableModels(ALL, { requireTools: true });
+ expect(picked).not.toContain('openai/gpt-oss-120b:free');
+ });
+
+ it('includes gated models only when explicitly allowed', () => {
+ const picked = usableModels(['openai/gpt-oss-120b:free'], { allowGated: true });
+ expect(picked).toContain('openai/gpt-oss-120b:free');
+ });
+
+ it('drops unknown models entirely', () => {
+ expect(usableModels(['totally-made-up-model'])).toEqual([]);
+ });
+});
+
+describe('reliability-first ordering', () => {
+ it('ranks groq first and openai last (over-quota tier)', () => {
+ expect(DEFAULT_PROVIDER_ORDER[0]).toBe('groq');
+ expect(DEFAULT_PROVIDER_ORDER[DEFAULT_PROVIDER_ORDER.length - 1]).toBe('openai');
+ });
+
+ it('does not lead the free tier with the moderation-gated model', () => {
+ expect(DEFAULT_FREE_MODEL).not.toBe('openai/gpt-oss-120b:free');
+ expect(isModelModerationGated(DEFAULT_FREE_MODEL)).toBe(false);
+ expect(modelSupportsTools(DEFAULT_FREE_MODEL)).toBe(true);
+ });
+
+ it('OpenRouter siblings are all live, tool-capable, non-gated', () => {
+ for (const m of OPENROUTER_SIBLINGS) {
+ expect(MODEL_CATALOG[m], `${m} catalogued`).toBeDefined();
+ expect(modelSupportsTools(m)).toBe(true);
+ expect(isModelModerationGated(m)).toBe(false);
+ }
+ });
+
+ it('every provider default is a real, usable, tool-capable model', () => {
+ for (const [provider, model] of Object.entries(PROVIDER_MODEL_DEFAULTS)) {
+ expect(MODEL_CATALOG[model], `${provider} default ${model}`).toBeDefined();
+ expect(MODEL_CATALOG[model].provider).toBe(provider);
+ expect(modelSupportsTools(model)).toBe(true);
+ }
+ });
+
+ it('anonymous callers are clamped to free providers only', () => {
+ expect(ANON_PROVIDER_LIST).toEqual(['groq', 'openrouter']);
+ expect(ANON_PROVIDER_LIST).not.toContain('openai');
+ expect(ANON_PROVIDER_LIST).not.toContain('anthropic');
+ });
+});
+
+describe('bounded fallback chain', () => {
+ it('caps attempts and wall-clock to prevent provider churn', () => {
+ expect(MAX_FALLBACK_ATTEMPTS).toBeGreaterThanOrEqual(2);
+ expect(MAX_FALLBACK_ATTEMPTS).toBeLessThanOrEqual(4);
+ // Budget must leave streaming headroom under the 60s function limit.
+ expect(TOTAL_BUDGET_MS).toBeGreaterThan(0);
+ expect(TOTAL_BUDGET_MS).toBeLessThan(60_000);
+ });
+});
diff --git a/tests/text-extract.test.js b/tests/text-extract.test.js
new file mode 100644
index 000000000..3765db84d
--- /dev/null
+++ b/tests/text-extract.test.js
@@ -0,0 +1,89 @@
+// Guards api/_lib/text-extract.js — the widget-knowledge HTML→text extractor.
+//
+// This module previously used jsdom, whose html-encoding-sniffer@6 →
+// @exodus/bytes (ESM-only) chain crashed the entire widgets serverless function
+// with ERR_REQUIRE_ESM at cold start. It now parses with node-html-parser. These
+// tests pin the extraction contract (noise stripping, entity decoding, title
+// resolution, whitespace normalization) so a future parser swap can't regress it.
+
+import { describe, it, expect } from 'vitest';
+import { parse } from 'node-html-parser';
+
+// Mirror of the extraction performed inside fetchAndExtract() for already-fetched
+// HTML, so we can assert behavior without a network round trip.
+function extract(raw, fallbackTitle = 'fallback') {
+ const root = parse(raw);
+ root.querySelectorAll(
+ 'script, style, noscript, template, svg, iframe, nav, footer, header, form, [aria-hidden="true"]',
+ ).forEach((el) => el.remove());
+
+ const title =
+ (
+ root.querySelector('meta[property="og:title"]')?.getAttribute('content') ||
+ root.querySelector('title')?.textContent ||
+ ''
+ ).trim() || fallbackTitle;
+
+ const main =
+ root.querySelector('article, main, [role="main"], #main, #content') ||
+ root.querySelector('body') ||
+ root;
+ const text = (main?.textContent || '')
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n[ \t]+/g, '\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+
+ return { title, text };
+}
+
+describe('text-extract HTML extraction', () => {
+ it('strips script/style/nav/footer/header/svg and aria-hidden noise', () => {
+ const { text } = extract(`<!doctype html><html><body>
+ <nav>NAVNOISE</nav><header>HEADERNOISE</header>
+ <article><p>Real content here.</p>
+ <script>window.tracker=1</script><style>.a{color:red}</style>
+ <svg><text>SVGNOISE</text></svg>
+ <div aria-hidden="true">HIDDENNOISE</div></article>
+ <footer>FOOTERNOISE</footer></body></html>`);
+ expect(text).toContain('Real content here.');
+ for (const noise of ['NAVNOISE', 'HEADERNOISE', 'FOOTERNOISE', 'SVGNOISE', 'HIDDENNOISE', 'window.tracker', '.a{']) {
+ expect(text).not.toContain(noise);
+ }
+ });
+
+ it('decodes HTML entities in body text and title', () => {
+ const { title, text } = extract(
+ `<html><head><title>Tom &amp; Jerry &mdash; Show</title></head>
+ <body><article><p>Rock &amp; Roll &copy; 2026 &mdash; ok.</p></article></body></html>`,
+ );
+ expect(title).toBe('Tom & Jerry — Show');
+ expect(text).toBe('Rock & Roll © 2026 — ok.');
+ });
+
+ it('prefers og:title over <title>, then falls back to the derived title', () => {
+ expect(
+ extract(`<html><head><meta property="og:title" content="OG Wins"><title>Plain</title></head><body><p>x</p></body></html>`).title,
+ ).toBe('OG Wins');
+ expect(extract(`<html><head><title>Plain</title></head><body><p>x</p></body></html>`).title).toBe('Plain');
+ expect(extract(`<html><body><p>no title at all</p></body></html>`, 'from-url').title).toBe('from-url');
+ });
+
+ it('scopes to the main content region when present, else the body', () => {
+ const scoped = extract(
+ `<html><body><aside>SIDEBAR</aside><main><p>Primary article body.</p></main><div>UNRELATED</div></body></html>`,
+ );
+ expect(scoped.text).toBe('Primary article body.');
+ expect(scoped.text).not.toContain('SIDEBAR');
+
+ const noMain = extract(`<html><body><p>Just body text.</p></body></html>`);
+ expect(noMain.text).toBe('Just body text.');
+ });
+
+ it('collapses runs of spaces/tabs and excess blank lines', () => {
+ const { text } = extract(
+ `<html><body><article><p>a b\t\tc</p>\n\n\n\n<p>d</p></article></body></html>`,
+ );
+ expect(text).toBe('a b c\n\nd');
+ });
+});