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: implement economy UI with store and bank functionalities

fudjiaef15eaeb44ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 167130a55..8eef02252 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Blockchain TVL by Chain** (`/chains`) — A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.
- **BNB Chain — Three Genuinely-Unique Demos** (`/bnb`) — The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.
- **BNB Chain Live Block Race — 0.45s vs Base, Ethereum, Solana** (`/bnb-latency`) — A live, honest race: BNB Chain, Base, Ethereum, and Solana block times measured fresh off real public RPCs every few seconds, with a rolling sparkline per lane. No wallet, no payment, no hardcoded numbers — a lane that goes quiet shows 'reconnecting' while the others keep racing.
+- **Creator Gallery** (`/creations`) — Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.
- **Crypto API** (`/crypto-api`) — One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.
- **Crypto Categories by Market Cap** (`/categories`) — Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.
- **Crypto Currency Converter** (`/converter`) — Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.
@@ -24,8 +25,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Top Crypto Exchanges** (`/exchanges`) — The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.
- **/create is now the front door for everything you can build** — /create used to be just the avatar picker. It's now a four-way intent hub — Build an AI agent, Make a 3D avatar, Generate a 3D model, or Launch a token world — so you pick your destination in one click instead of hunting through a flat menu of tools. The avatar picker didn't go anywhere: it's still exactly where it was, now reachable as the 'Make a 3D avatar' path with its photo/scratch/prompt/upload options intact. (`/create`) `[improvement]`
- **/play grew real physics, a drivable district, and day/night** — The coin-community world stops being a flat clamped plaza: a real Rapier character controller now drives your avatar (collision, ground contact, and jumps against actual geometry), and Downtown is ringed by a full deterministic street grid — asphalt avenues, sidewalks, lit buildings, and streetlights — that every client in a world renders identically and can now walk or drive across instead of hitting an invisible wall at the plaza's edge. A wall-clock-driven day/night cycle sweeps the sun, sky, fog, and the district's window and streetlamp glow in sync for everyone, with zero network chatter. The camera also grew up: press C to cycle Follow, Cinematic, First Person, and Top Down, the same four modes /walk uses, now shared from one module. (`/play`) `[feature, improvement]`
+- **/play now has a real economy: a general store, a bank, and a $THREE boutique** — The open world at /play has a working cash economy. Walk up to a General Store clerk to buy tools and consumables or sell what you've gathered, and visit the Bank Teller to deposit cash into a protected account (banked cash survives a death drop, carried cash doesn't). Premium wardrobe items are now purchasable for real: the wardrobe's locked cosmetics show their $THREE price and unlock with one real on-chain payment from your connected Solana wallet, split between the holder-rewards pool and the treasury — the server only grants the item after re-verifying the confirmed transaction on-chain. (`/play`) `[feature]`
- **<agent-3d> talks out of the box with brain="free"** — Any embedded avatar can now hold a real conversation with zero setup: add brain="free" to an <agent-3d> tag and it routes through three.ws's host-paid free-tier proxy (OpenRouter, Groq, or NVIDIA NIM, whichever is healthy) — no API key, no backend code, no per-token cost to the embedder. Previously the brain attribute required an exact model id and defaulted to a silent avatar; brain="free" is now a supported alias, and it's honored on both the src= (bare GLB) and body= (ad-hoc agent) embed paths, which is where this fell through before. (`/docs/embedding`) `[feature, sdk]`
- **3D viewer accessibility: keyboard orbit, focus rings, and a low-power mode for the main site viewer** — The core 3D viewer that powers /app, Forge, avatar pages, and every embed now matches the accessibility bar the lightweight SDK viewer already had: the canvas is keyboard-reachable (tab to focus, arrow keys orbit, +/- zoom), gets a proper accessible name, and shows a visible focus ring. Entry-level phones and tablets (detected by touch input plus low core count or memory — desktop is never affected) now get a lighter render automatically: capped resolution and no antialiasing, for a steadier frame rate instead of a choppy one. Also fixed: Scene Studio's Import from Forge / Export / Share action bar was overlapping the editor's own File/Edit/Add menu bar at every screen size — it now sits cleanly below it. (`/scene`) `[improvement, fix]`
+- **A boutique you can walk into: two tailors now live in /play** — The wardrobe and cosmetics shop in /play now have a physical home in the world. Walk up to Roux the Tailor to browse and buy fits, hats, and paint jobs, or visit Nell's Fitting Room to equip anything you already own — the same real, server-verified shop and wardrobe the HUD buttons already opened, now with a place to stand. Character creation itself — design an avatar from scratch, scan yourself into 3D with the selfie creator, upload your own .glb, or sculpt in the full Avatar Studio — has no sign-in required and drops you straight into the world. (`/play`) `[feature]`
- **A live public gallery for every minted 3D asset — and a fix that had been silently 500ing the launch directory** — Minted 3D assets now have a home: three.ws/minted shows every generated avatar minted as a Solana NFT through the platform, rendered live in an interactive <model-viewer> card with its network, enforced royalty rate, and a remix badge when it routed a payout to the original creator — the NFT counterpart of the coin /launches feed. Building it surfaced a real bug: the remix-royalty and provenance-ledger columns added to the mint table were live in code but never applied to the production database, so GET /api/v1/tokenized/launches and get_3d_asset_onchain's read-back were quietly returning a server error for any minted asset with those fields. The migration is applied and both are confirmed working. (`/minted`) `[feature, fix]`
- **Agent mood now shapes body language, not just facial expression** — An agent's sustained mood — set via setMood(), tracked as valence and arousal — used to only drive the face (a smile, a worried brow) and posture. Now a resting up-and-energetic mood also nudges the agent toward a livelier gesture between events, and a down-and-subdued mood toward a stiller, more concerned one, so an agent's whole body reads as consistent with how it feels, not just its expression. A real triggered gesture (a wave, a reaction to an error) still always takes priority over this ambient bias. (`/tutorials/emotion-from-data`) `[feature, improvement]`
- **Bigger motion library, and two dead animation gestures fixed** — Added 7 new baked clips to the animation library — Nod, Shrug, Point, Think, Turn, Jog, and a sitting-idle loop — retargeted onto the universal avatar rig alongside the existing 100+. Also fixed two silent no-ops: the 'sit' gesture's clip was missing from the manifest (AnimationManager couldn't find it, so avatars silently failed to sit), and the agent 'fidget' slot pointed at a clip that never existed (now maps to a real idle loop). Both are covered by new regression tests so they can't quietly break again. (`/animations`) `[feature, fix]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index eeba6ef36..af5206780 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -41,7 +41,8 @@ bottom.
| X/Twitter automation toolkit | [nirholas/XActions](https://github.com/nirholas/XActions) (external repo, also on npm as `xactions`) | External | Formerly vendored in-repo; removed 2026-07-03 — install from npm or use the upstream repo |
| Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Play mode** ("Enter the Commons") makes it walkable GTA-style — your avatar walks the square among the working NPC citizens, other humans appear live over the `agora_world` Colyseus room, and walking up to a citizen (proximity → E) opens its passport: [src/agora/player-mode.js](src/agora/player-mode.js), pure math [src/agora/player-logic.js](src/agora/player-logic.js), room [multiplayer/src/rooms/AgoraRoom.js](multiplayer/src/rooms/AgoraRoom.js). Play mode also has an opt-in **"Record on-chain (BNB testnet)"** toggle (OFF by default) that gaslessly commits your moves to the `WorldMoves` contract every ~block via MegaFuel (self-pay fallback) and renders other on-chain players as lightweight ghost markers read back from real `Moved` events: [src/agora/onchain-presence.js](src/agora/onchain-presence.js), sender [src/bnb/move-sender.js](src/bnb/move-sender.js), event reader [src/bnb/world-presence-reader.js](src/bnb/world-presence-reader.js), pure ghost interpolation [src/bnb/onchain-ghosts.js](src/bnb/onchain-ghosts.js), server relay lib [api/_lib/bnb/world-moves.js](api/_lib/bnb/world-moves.js), config endpoint [api/bnb/world-config.js](api/bnb/world-config.js). WorldMoves contract: [contracts/src/WorldMoves.sol](contracts/src/WorldMoves.sol) (code-complete + anvil-fork-proven; public BSC testnet deploy pending a funded deployer key — see `contracts/DEPLOYMENTS.md`). **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |
| Premium vanity inventory (sell pre-ground addresses) | [public/vanity/premium/](public/vanity/premium/index.html) `→ /vanity/premium`, batch grinder [workers/vanity-grinder/](workers/vanity-grinder), store [api/_lib/vanity-inventory-store.js](api/_lib/vanity-inventory-store.js), sell [api/x402/vanity-premium.js](api/x402/vanity-premium.js), replenish [api/cron/vanity-inventory-replenish.js](api/cron/vanity-inventory-replenish.js) | In-repo · GCP spot CPU | Long (4–5+ char) brandable Solana addresses ground ahead of time on cheap spot CPU, sealed at rest (AES-256-GCM or GCP-KMS envelope, [api/_lib/vanity-vault.js](api/_lib/vanity-vault.js)), and sold from stock via x402 — priced by rarity ($1–$50) on `vanity-premium`, or by fixed 4–5 char tiers ($2.50/$10) directly through [`/api/x402/vanity`](docs/vanity.md#tier-1--live-grinder) (instant delivery, `source:"inventory"`) and the [pump-launch vanity upsell](docs/pump-launcher.md) — delivered exactly once, ciphertext destroyed on delivery. An hourly cron watches stock and fires a fresh grind batch (Cloud Run Job) when low. Free `vanity_premium` MCP browse tool. Runbook: [docs/gcp-credits.md](docs/gcp-credits.md) |
-| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html` |
+| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html`, [agent-native-3d/](examples/agent-native-3d) (below) |
+| Agent-native 3D + embeddable distribution | MCP tool [api/_mcp/tools/agents.js](api/_mcp/tools/agents.js) (`attach_avatar_to_agent`); shared oEmbed provider [api/agent-oembed.js](api/agent-oembed.js) `→ /api/oembed` + builder [api/_lib/embed.js](api/_lib/embed.js) (`forgeEmbedTarget`, shared by `get_embed_code` in [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js)); Forge share page oEmbed discovery [api/forge-share.js](api/forge-share.js) `→ /forge/share/:id`; distribution snippet builders [src/forge-embed-snippets.js](src/forge-embed-snippets.js) + panel [src/forge-embed-panel.js](src/forge-embed-panel.js); autonomous demo [examples/agent-native-3d/](examples/agent-native-3d) | In-repo | Closes the loop: create → own → discover/remix → **use everywhere**. `attach_avatar_to_agent` gives a registered agent identity a persistent body (chains into `register_agent` for on-chain identity + `anchor_provenance` for a signed authenticity credential). Any Forge creation now unfurls via real oEmbed (paste `/forge/share/:id` into Notion/Discord/Slack) with the same `type:rich` iframe payload `get_embed_code` returns via MCP. The Forge "Embed this model" panel hands out five real distribution flavours from one GLB — iframe, `<model-viewer>`, `<agent-3d>`, a `@three-ws/page-agent` talking guide, and a `@three-ws/walk` companion — all built from one shared, pure snippet module so every surface stays byte-identical. `examples/agent-native-3d/run.mjs` drives the full agent-native chain live against `/api/mcp-studio` (mesh_forge → rig_mesh → create_agent_persona → persona_say → get_agent_persona → every distribution snippet) with zero mocks and a documented, logged fallback if the shared free-tier generation lane is rate-limited at run time. Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#share-routes-on-chain-agents). Docs: [docs/mcp.md#attach_avatar_to_agent](docs/mcp.md#attach_avatar_to_agent). Roadmap prompt 10 (closes the roadmap campaign). |
| Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) |
| Animation gallery | [pages/animations.html](pages/animations.html) + [src/animations-gallery.js](src/animations-gallery.js) | Live at `/animations` | 2,100+ clips with poster thumbnails ([scripts/build-animation-thumbnails.mjs](scripts/build-animation-thumbnails.mjs)), derived categories ([src/animation-categories.js](src/animation-categories.js)), shared live-preview engine ([src/animations-live-preview.js](src/animations-live-preview.js)) · see [docs/animations.md](docs/animations.md) |
| FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |
diff --git a/api/_lib/embed.js b/api/_lib/embed.js
index f6219adb7..7aa4414de 100644
--- a/api/_lib/embed.js
+++ b/api/_lib/embed.js
@@ -68,12 +68,24 @@ export function onchainEmbedTarget(origin, chainId, agentId) {
};
}
-export function forgeEmbedTarget(origin, id) {
+// glbUrl/title are optional so callers that only have the id (e.g. building a
+// shareUrl before the row is loaded) still get a valid, if generic, target.
+// When glbUrl is supplied, embedUrl points at the lightweight, zero-dependency
+// /forge/embed viewer (orbit + AR + branding) — the same route
+// src/forge-embed-snippets.js hands out in copy-paste snippets — rather than the
+// full Forge app, so an <iframe src="embedUrl"> stays small and AR-capable.
+export function forgeEmbedTarget(origin, id, glbUrl, title) {
const enc = encodeURIComponent(String(id));
+ const embedUrl = glbUrl
+ ? `${origin}/forge/embed?${new URLSearchParams({
+ src: glbUrl,
+ ...(title ? { title: String(title).slice(0, 120) } : {}),
+ })}`
+ : `${origin}/forge?share=${enc}`;
return {
- embedUrl: `${origin}/forge?share=${enc}`,
+ embedUrl,
shareUrl: `${origin}/forge/share/${id}`,
- thumbnailUrl: `${origin}/api/forge/${id}/og`,
+ thumbnailUrl: `${origin}/api/forge-og?id=${enc}`,
};
}
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index 2542a3661..98778ccc4 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -684,33 +684,72 @@ export async function setRemixable({ creationId, clientKey, remixable, royaltyBp
}
}
-// Newest remixable creations across all creators — powers the remix feed. Only
-// done rows with a stored GLB and remixable = true are surfaced. Cursor by
-// created_at (pass `before` = the last item's created_at ISO string).
-export async function listRemixable({ limit = 24, before } = {}) {
+// Newest remixable creations across all creators — powers the remix feed /
+// creator marketplace gallery (prompt 09). Only done rows with a stored GLB
+// and remixable = true are surfaced.
+//
+// Three sort modes, matched to what can be paginated safely:
+// - 'recent' (default): cursor by created_at (`before` = last item's ISO
+// timestamp) — true infinite scroll, monotonic key.
+// - 'royalty': highest creator royalty rate first. Non-monotonic across
+// pages, so `before` is ignored — this returns a fixed top-N list (a
+// leaderboard slice, same pattern trending/leaderboard surfaces use
+// everywhere on the platform — they don't infinite-scroll either).
+// - 'remixed': most-derived-from first (a live count of child creations),
+// same fixed top-N behavior as 'royalty'.
+// `q` does a case-insensitive substring match on the prompt; `category` filters
+// to one of MODEL_CATEGORIES. Both are additive, backward-compatible with the
+// original (limit, before)-only call shape.
+export async function listRemixable({ limit = 24, before, category, q, sort } = {}) {
if (!forgeStoreEnabled()) return [];
const capped = Math.min(Math.max(Number(limit) || 24, 1), 48);
+ const sortMode = sort === 'royalty' || sort === 'remixed' ? sort : 'recent';
+ const cat = validModelCategory(category);
+ const search = typeof q === 'string' && q.trim() ? q.trim().slice(0, 120) : null;
+
+ const params = [];
+ const conds = [`p.remixable = true`, `p.status = 'done'`, `p.glb_url is not null`];
+ if (cat) {
+ params.push(cat);
+ conds.push(`p.model_category = $${params.length}`);
+ }
+ if (search) {
+ params.push(`%${search}%`);
+ conds.push(`p.prompt ilike $${params.length}`);
+ }
+ // The cursor only makes sense for the monotonic 'recent' sort.
+ if (sortMode === 'recent' && before) {
+ params.push(before);
+ conds.push(`p.created_at < $${params.length}`);
+ }
+ params.push(capped);
+ const limitParam = `$${params.length}`;
+
+ const orderBy =
+ sortMode === 'royalty'
+ ? `p.remix_royalty_bps desc, p.created_at desc`
+ : sortMode === 'remixed'
+ ? `remix_count desc, p.created_at desc`
+ : `p.created_at desc`;
+
try {
- const rows = before
- ? await sql`
- select id, prompt, glb_url, preview_image_url, remix_royalty_bps,
- creator_wallet_solana, parent_creation_id, lineage_index,
- backend, model_category, created_at
+ const rows = await sql(
+ `select p.id, p.prompt, p.glb_url, p.preview_image_url, p.remix_royalty_bps,
+ p.creator_wallet_solana, p.parent_creation_id, p.lineage_index,
+ p.backend, p.model_category, p.created_at,
+ coalesce(rc.remix_count, 0) as remix_count
+ from forge_creations p
+ left join (
+ select parent_creation_id, count(*) as remix_count
from forge_creations
- where remixable = true and status = 'done' and glb_url is not null
- and created_at < ${before}
- order by created_at desc
- limit ${capped}
- `
- : await sql`
- select id, prompt, glb_url, preview_image_url, remix_royalty_bps,
- creator_wallet_solana, parent_creation_id, lineage_index,
- backend, model_category, created_at
- from forge_creations
- where remixable = true and status = 'done' and glb_url is not null
- order by created_at desc
- limit ${capped}
- `;
+ where parent_creation_id is not null and status = 'done'
+ group by parent_creation_id
+ ) rc on rc.parent_creation_id = p.id
+ where ${conds.join(' and ')}
+ order by ${orderBy}
+ limit ${limitParam}`,
+ params,
+ );
return rows.map((r) => ({
id: r.id,
prompt: r.prompt,
@@ -722,6 +761,7 @@ export async function listRemixable({ limit = 24, before } = {}) {
royaltyPayable: Boolean(r.creator_wallet_solana),
isDerived: Boolean(r.parent_creation_id),
lineageIndex: r.lineage_index ?? 0,
+ remixCount: Number(r.remix_count) || 0,
backend: r.backend ?? null,
model_category: r.model_category ?? 'other',
created_at: r.created_at,
@@ -733,6 +773,51 @@ export async function listRemixable({ limit = 24, before } = {}) {
}
}
+// The most-remixed published assets, platform-wide — the "trending" half of
+// the creator marketplace leaderboard (prompt 09). Counts REAL child rows
+// (finished derivatives whose parent_creation_id points at this asset), not a
+// synthetic popularity score. A source that is no longer published as
+// remixable can still appear (its remix history is a fact even if it was later
+// unpublished) — the caller renders that as "no longer remixable".
+export async function listMostRemixed({ limit = 10 } = {}) {
+ if (!forgeStoreEnabled()) return [];
+ const capped = Math.min(Math.max(Number(limit) || 10, 1), 24);
+ try {
+ const rows = await sql`
+ with remix_counts as (
+ select parent_creation_id, count(*) as remix_count
+ from forge_creations
+ where parent_creation_id is not null and status = 'done'
+ group by parent_creation_id
+ )
+ select p.id, p.prompt, p.glb_url, p.preview_image_url, p.remix_royalty_bps,
+ p.creator_wallet_solana, p.remixable, p.model_category, p.created_at,
+ rc.remix_count
+ from remix_counts rc
+ join forge_creations p on p.id = rc.parent_creation_id
+ where p.status = 'done' and p.glb_url is not null
+ order by rc.remix_count desc, p.created_at desc
+ limit ${capped}
+ `;
+ return rows.map((r) => ({
+ id: r.id,
+ prompt: r.prompt,
+ glb_url: r.glb_url,
+ preview_image_url: r.preview_image_url,
+ royaltyBps: r.remix_royalty_bps ?? 0,
+ royaltyPayable: Boolean(r.creator_wallet_solana),
+ remixable: Boolean(r.remixable),
+ remixCount: Number(r.remix_count) || 0,
+ model_category: r.model_category ?? 'other',
+ created_at: r.created_at,
+ }));
+ } catch (err) {
+ if (isDbUnavailableError(err)) console.warn('[forge-store] listMostRemixed skipped (db unavailable):', err?.message);
+ else console.error('[forge-store] listMostRemixed failed:', err?.message);
+ return [];
+ }
+}
+
// Fetch one remixable source with the fields settlement needs: its GLB, the
// reference image to anchor the remix, the royalty rate, and the payout wallet.
// Includes the wallet (unlike the public feed) because the caller is the
diff --git a/api/_lib/tokenized-launches.js b/api/_lib/tokenized-launches.js
index 1ea6770f4..e6c0d5d91 100644
--- a/api/_lib/tokenized-launches.js
+++ b/api/_lib/tokenized-launches.js
@@ -11,7 +11,7 @@
// - GET /api/v1/tokenized/launches — the free, versioned /api/v1 catalog surface.
// - (future) an agent-profile "minted 3D assets" card, same query + agent_id filter.
-import { sql } from './db.js';
+import { sql, isDbUnavailableError } from './db.js';
/**
* Query the three.ws tokenized-3D launch directory.
@@ -90,3 +90,64 @@ export async function queryTokenizedLaunches({
return { launches, has_more: hasMore };
}
+
+/**
+ * Top creators leaderboard for the creator marketplace (prompt 09) — agents
+ * ranked by how much OTHER creators built on their minted 3D work: a count of
+ * child mints naming one of their assets as `parent_mint`, plus the real
+ * on-chain USDC royalty earned from those remixes (settleTokenizeRemixRoyalty,
+ * api/_lib/tokenize-3d.js). This is the only creator surface with a real,
+ * public, on-chain identity (agent_identities + its ERC-8004 registration) —
+ * forge_creations' client_key is intentionally anonymous, so a "top human
+ * creators" board isn't possible without deanonymizing that store. Only agents
+ * with at least one remix of their work are ranked; an empty board is honest,
+ * not a placeholder.
+ *
+ * @param {{ limit?: number }} o
+ * @returns {Promise<Array<object>>}
+ */
+export async function queryTopCreators({ limit = 10 } = {}) {
+ const capped = Math.min(Math.max(Number(limit) || 10, 1), 24);
+ try {
+ const rows = await sql`
+ with owned as (
+ select t.mint, ai.id as agent_id, ai.name as agent_name,
+ ai.meta->>'solana_address' as agent_wallet
+ from tokenized_3d_assets t
+ join avatars a on a.id = t.source_avatar_id and a.deleted_at is null
+ join agent_identities ai on ai.avatar_id = a.id and ai.deleted_at is null
+ where t.status = 'minted'
+ ),
+ remix_agg as (
+ select parent_mint,
+ count(*) as remix_count,
+ sum(case when remix_royalty->>'paid' = 'true'
+ then (remix_royalty->>'creator_usd')::numeric
+ else 0 end) as royalty_earned_usd
+ from tokenized_3d_assets
+ where status = 'minted' and parent_mint is not null
+ group by parent_mint
+ )
+ select o.agent_id, o.agent_name, o.agent_wallet,
+ count(distinct o.mint) as minted_count,
+ coalesce(sum(r.remix_count), 0) as remix_count,
+ coalesce(sum(r.royalty_earned_usd), 0) as royalty_earned_usd
+ from owned o
+ left join remix_agg r on r.parent_mint = o.mint
+ group by o.agent_id, o.agent_name, o.agent_wallet
+ having coalesce(sum(r.remix_count), 0) > 0
+ order by remix_count desc, royalty_earned_usd desc, minted_count desc
+ limit ${capped}
+ `;
+ return rows.map((r) => ({
+ agent: { id: r.agent_id, name: r.agent_name, url: `/agents/${r.agent_id}`, solana_address: r.agent_wallet || null },
+ mintedCount: Number(r.minted_count) || 0,
+ remixCount: Number(r.remix_count) || 0,
+ royaltyEarnedUsd: Math.round((Number(r.royalty_earned_usd) || 0) * 100) / 100,
+ }));
+ } catch (err) {
+ if (isDbUnavailableError(err)) console.warn('[tokenized-launches] queryTopCreators skipped (db unavailable):', err?.message);
+ else console.error('[tokenized-launches] queryTopCreators failed:', err?.message);
+ return [];
+ }
+}
diff --git a/api/_mcp/tools/agents.js b/api/_mcp/tools/agents.js
index 35fab0f44..192e878ea 100644
--- a/api/_mcp/tools/agents.js
+++ b/api/_mcp/tools/agents.js
@@ -15,6 +15,7 @@ import {
import { buildRegistrationJSON } from '../../../src/erc8004/registration-json.js';
import { REGISTRY_DEPLOYMENTS } from '../../../src/erc8004/abi.js';
import { isUuid } from '../../_lib/validate.js';
+import { logAudit } from '../../_lib/audit.js';
// Base mainnet — the EVM chain we expose for ERC-8004 self-registration.
const BASE_CHAIN_ID = 8453;
@@ -321,6 +322,123 @@ export const toolDefs = [
return registerOnSolana({ agent, network, force: !!args.force });
},
},
+ {
+ name: 'attach_avatar_to_agent',
+ title: 'Give an agent a body',
+ // Sets one column on an owned row; re-running with the same avatar_id is a
+ // no-op (idempotent), but it IS a write.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+ description:
+ 'Attach a generated/rigged avatar (from forge_avatar, mesh_forge + rig_mesh, or any avatar you own) to ' +
+ "one of your registered agent identities — giving the agent a persistent visual body tied to its " +
+ 'account identity. This is the bridge between generation and identity: generate a rigged GLB, save it ' +
+ 'as an avatar (list_my_avatars / the Forge \'Save\' action), then call this tool to make it the agent\'s ' +
+ 'body. The same agent_id always shows the same body afterwards (get_avatar / render_avatar / ' +
+ 'get_embed_code all resolve it). Chain register_agent next to mint the on-chain identity (ERC-8004 on ' +
+ 'Base, or a Metaplex Agent Registry PDA on Solana) and anchor_provenance to credential the GLB itself — ' +
+ 'together the agent has a body, an on-chain identity, and a verifiable authenticity record. Requires a ' +
+ 'signed-in three.ws account; both the agent and the avatar must belong to the caller.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agent_id: { type: 'string', format: 'uuid', description: 'Your agent identity id (uuid).' },
+ avatar_id: {
+ type: 'string',
+ format: 'uuid',
+ description: 'The avatar to attach (uuid) — one of your own avatars (see list_my_avatars).',
+ },
+ },
+ required: ['agent_id', 'avatar_id'],
+ additionalProperties: false,
+ },
+ scope: 'agents:write',
+ async handler(args, auth) {
+ if (!auth.userId) {
+ return designedError(
+ 'sign_in_required',
+ 'attach_avatar_to_agent writes to your three.ws account and requires a signed-in user. ' +
+ 'Pay-per-call (x402) callers cannot attach avatars — authenticate with your three.ws ' +
+ 'account (OAuth) and retry.',
+ {},
+ );
+ }
+ if (!isUuid(args.agent_id || '')) {
+ return designedError('validation_error', 'agent_id must be a valid uuid.', {});
+ }
+ if (!isUuid(args.avatar_id || '')) {
+ return designedError('validation_error', 'avatar_id must be a valid uuid.', {});
+ }
+
+ const [agent] = await sql`
+ SELECT id, user_id, name, avatar_id
+ FROM agent_identities
+ WHERE id = ${args.agent_id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) {
+ return designedError('not_found', 'No agent with that id.', { agent_id: args.agent_id });
+ }
+ if (agent.user_id !== auth.userId) {
+ return designedError(
+ 'forbidden',
+ 'That agent belongs to another account — you can only give a body to your own agents.',
+ { agent_id: args.agent_id },
+ );
+ }
+
+ const [avatar] = await sql`
+ SELECT id, name, storage_key, visibility
+ FROM avatars
+ WHERE id = ${args.avatar_id} AND owner_id = ${auth.userId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!avatar) {
+ return designedError(
+ 'not_found',
+ 'No avatar with that id in your account. Generate one (forge_avatar / mesh_forge + rig_mesh) ' +
+ 'and save it first, or pick one from list_my_avatars.',
+ { avatar_id: args.avatar_id },
+ );
+ }
+
+ const [updated] = await sql`
+ UPDATE agent_identities
+ SET avatar_id = ${avatar.id}, updated_at = now()
+ WHERE id = ${agent.id}
+ RETURNING id, name, avatar_id, wallet_address, meta
+ `;
+
+ logAudit({
+ userId: auth.userId,
+ action: 'attach_avatar_to_agent',
+ resourceId: agent.id,
+ meta: { via: 'mcp', avatar_id: avatar.id, previous_avatar_id: agent.avatar_id || null },
+ });
+
+ const onchain = Boolean(updated.meta?.agent_registry || updated.meta?.devnet?.agent_registry);
+ return toolResult({
+ status: 'attached',
+ agent_id: updated.id,
+ agent_name: updated.name,
+ avatar_id: updated.avatar_id,
+ avatar_name: avatar.name,
+ replaced_avatar_id: agent.avatar_id !== avatar.id ? agent.avatar_id || null : null,
+ profile_url: agentHomeUrl(updated.id),
+ already_onchain: onchain,
+ next_steps: onchain
+ ? ['anchor_provenance(glb_url) to credential this body\'s authenticity']
+ : [
+ 'register_agent(agent_id) to mint the on-chain identity',
+ 'anchor_provenance(glb_url) to credential this body\'s authenticity',
+ ],
+ });
+ },
+ },
{
name: 'identity_check',
title: 'Screen an agent identity for impersonation',
diff --git a/api/_mcp/tools/embed.js b/api/_mcp/tools/embed.js
index fcb7a099d..033d90895 100644
--- a/api/_mcp/tools/embed.js
+++ b/api/_mcp/tools/embed.js
@@ -104,7 +104,7 @@ async function resolveTarget({ kind, args, auth, origin }) {
// visibility), so the only gate is that the mesh actually finished rendering.
if (!isUuid(args.creation_id)) throw rpcError(-32602, 'creation_id must be a uuid');
const [creation] = await sql`
- SELECT id, status, glb_url FROM forge_creations
+ SELECT id, status, glb_url, prompt FROM forge_creations
WHERE id = ${args.creation_id} LIMIT 1
`;
if (!creation) throw new Error('forge creation not found');
@@ -117,9 +117,11 @@ async function resolveTarget({ kind, args, auth, origin }) {
),
};
}
- // Forge has no oEmbed provider wired (the share page handles unfurling), so
- // oembed_url is null rather than a link that wouldn't resolve.
- return { target: forgeEmbedTarget(origin, creation.id), title: 'three.ws Forge creation', oembed: null };
+ const title = creation.prompt ? String(creation.prompt).slice(0, 80) : 'three.ws Forge creation';
+ const target = forgeEmbedTarget(origin, creation.id, creation.glb_url, title);
+ // /api/oembed resolves /forge/share/:id (extractForgeId in api/agent-oembed.js),
+ // so Forge creations get a real oEmbed URL like every other embeddable target.
+ return { target, title, oembed: oembedUrl(origin, target.shareUrl) };
}
export const toolDefs = [
diff --git a/api/agent-oembed.js b/api/agent-oembed.js
index 8c79f6513..87cc078f3 100644
--- a/api/agent-oembed.js
+++ b/api/agent-oembed.js
@@ -1,22 +1,25 @@
/**
- * oEmbed endpoint for agent URLs
- * ------------------------------
- * GET /api/oembed?url=<agent-url>[&format=json|xml]
+ * oEmbed endpoint for agent + Forge creation URLs
+ * ------------------------------------------------
+ * GET /api/oembed?url=<agent-or-forge-share-url>[&format=json|xml]
*
* Implements https://oembed.com with type=rich. The html payload is a
- * sandboxed iframe pointing at /agent/:id/embed so consumers (Notion,
- * Discord, etc.) can render the agent inline.
+ * sandboxed iframe — /agent/:id/embed for agents, /forge/embed?src=<glb> for
+ * Forge creations — so consumers (Notion, Discord, etc.) can render the model
+ * inline just by pasting the shareUrl.
*/
import { sql } from './_lib/db.js';
import { env } from './_lib/env.js';
import { cors, wrap, error } from './_lib/http.js';
import { resolveOnChainAgent, SERVER_CHAIN_META } from './_lib/onchain.js';
+import { isUuid } from './_lib/validate.js';
import {
buildEmbedIframe,
clampEmbedDim,
agentEmbedTarget,
onchainEmbedTarget,
+ forgeEmbedTarget,
EMBED_THUMB,
} from './_lib/embed.js';
@@ -38,6 +41,9 @@ export default wrap(async (req, res) => {
const onchain = extractOnChain(target);
if (onchain) return sendOnChain(res, format, { ...onchain, width, height });
+ const forgeId = extractForgeId(target);
+ if (forgeId) return sendForge(res, format, { id: forgeId, width, height });
+
const agentId = extractAgentId(target);
if (!agentId) return error(res, 404, 'not_found', 'url is not a recognised agent url');
@@ -100,6 +106,68 @@ function extractAgentId(target) {
return match ? match[1] : null;
}
+function extractForgeId(target) {
+ let parsed;
+ try {
+ parsed = new URL(target);
+ } catch {
+ return null;
+ }
+
+ const originStr = `${parsed.protocol}//${parsed.host}`;
+ const okOrigin =
+ originStr === env.APP_ORIGIN || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
+ if (!okOrigin) return null;
+
+ const match = parsed.pathname.match(/^\/forge\/share\/([A-Za-z0-9-]+)\/?$/);
+ const id = match ? match[1] : null;
+ return id && isUuid(id) ? id : null;
+}
+
+async function sendForge(res, format, { id, width, height }) {
+ const [creation] = await sql`
+ SELECT id, prompt, status, glb_url
+ FROM forge_creations
+ WHERE id = ${id}
+ LIMIT 1
+ `;
+ if (!creation || creation.status !== 'done' || !creation.glb_url) {
+ return error(res, 404, 'not_found', 'forge creation not found or not ready');
+ }
+
+ const origin = env.APP_ORIGIN;
+ const title = creation.prompt ? String(creation.prompt).slice(0, 80) : 'Forged creation';
+ const { embedUrl, shareUrl, thumbnailUrl } = forgeEmbedTarget(origin, creation.id, creation.glb_url, title);
+
+ const payload = {
+ type: 'rich',
+ version: '1.0',
+ provider_name: 'three.ws',
+ provider_url: origin,
+ title,
+ author_name: 'three.ws Forge',
+ author_url: `${origin}/forge`,
+ html: buildEmbedIframe({ src: embedUrl, width, height, title }),
+ width,
+ height,
+ thumbnail_url: thumbnailUrl,
+ thumbnail_width: EMBED_THUMB.width,
+ thumbnail_height: EMBED_THUMB.height,
+ };
+
+ res.setHeader('cache-control', 'public, max-age=900');
+
+ if (format === 'xml') {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/xml; charset=utf-8');
+ res.end(toXml(payload));
+ return;
+ }
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json+oembed; charset=utf-8');
+ res.end(JSON.stringify(payload));
+}
+
function extractOnChain(target) {
let parsed;
try {
diff --git a/api/agent-share.js b/api/agent-share.js
index c0ee408ff..50e8ea530 100644
--- a/api/agent-share.js
+++ b/api/agent-share.js
@@ -94,10 +94,16 @@ export default wrap(async (req, res) => {
// otherwise prefer the richer raw thumbnail when the avatar is public.
const forcedOgImage = walletShare ? ogImage : null;
+ // /api/oembed (extractAgentId) only resolves the canonical /agent/:id shape —
+ // not the /share or /wallet variants — so discovery is only offered here.
+ const oembedJsonUrl = walletShare
+ ? null
+ : `${origin}/api/oembed?url=${encodeURIComponent(deepUrl)}&format=json`;
+
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');
- res.end(renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin }));
+ res.end(renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin, oembedJsonUrl }));
});
function redirect(res, to) {
@@ -120,7 +126,7 @@ function esc(s) {
);
}
-function renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin }) {
+function renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin, oembedJsonUrl }) {
const t = esc(title);
const d = esc(desc);
// A wallet share forces the SVG card (it carries the wallet identity); otherwise
@@ -163,6 +169,7 @@ function renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOg
<meta property="fc:frame:button:2:target" content="${esc(origin)}/agents">
<link rel="canonical" href="${esc(pageUrl)}">
+ ${oembedJsonUrl ? `<link rel="alternate" type="application/json+oembed" href="${esc(oembedJsonUrl)}" title="${t} oEmbed">` : ''}
<link rel="shortcut icon" href="/favicon.ico">
<style>
diff --git a/api/creations-leaderboard.js b/api/creations-leaderboard.js
new file mode 100644
index 000000000..ddc691b11
--- /dev/null
+++ b/api/creations-leaderboard.js
@@ -0,0 +1,71 @@
+/**
+ * Creator marketplace leaderboards (roadmap prompt 09) — the "make discovery
+ * feel alive" surface for the /creations gallery.
+ *
+ * GET /api/creations-leaderboard
+ * → { enabled, topRemixedAssets: [...], topCreators: [...] }
+ *
+ * Two REAL, queried rankings, no synthetic scores:
+ * - topRemixedAssets: the most-remixed published forge_creations, platform-
+ * wide — a live count of child derivatives (api/_lib/forge-store.js
+ * listMostRemixed). Same data the /creations gallery's "Trending" sort
+ * reads from api/remix-feed.js?action=trending; this endpoint additionally
+ * bundles the creator leaderboard in one round trip for the gallery page.
+ * - topCreators: agents ranked by how much OTHER creators built on their
+ * minted 3D work — a real count of tokenized_3d_assets rows naming one of
+ * theirs as parent_mint, plus the real on-chain USDC royalty earned
+ * (api/_lib/tokenized-launches.js queryTopCreators). This is the only
+ * creator surface with a public, on-chain identity (agent_identities +
+ * its ERC-8004 registration) to link a leaderboard entry to — the
+ * forge_creations client_key is intentionally anonymous.
+ *
+ * Free, public, cached briefly at the edge. $THREE-policy clean: no coin
+ * amounts, USDC royalty figures only.
+ */
+
+import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { forgeStoreEnabled, listMostRemixed } from './_lib/forge-store.js';
+import { queryTopCreators } from './_lib/tokenized-launches.js';
+import { databaseConfigured } from './_lib/env.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!databaseConfigured()) {
+ return json(res, 200, { enabled: false, topRemixedAssets: [], topCreators: [] });
+ }
+
+ const url = new URL(req.url, 'http://localhost');
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 8, 1), 20);
+
+ const [assets, creators] = await Promise.all([
+ forgeStoreEnabled() ? listMostRemixed({ limit }) : Promise.resolve([]),
+ queryTopCreators({ limit }),
+ ]);
+
+ const topRemixedAssets = assets.map((a) => ({
+ id: a.id,
+ prompt: a.prompt,
+ glbUrl: a.glb_url,
+ previewImageUrl: a.preview_image_url ?? null,
+ viewerUrl: `https://three.ws/viewer?src=${encodeURIComponent(a.glb_url)}`,
+ royaltyPercent: Math.round((a.royaltyBps / 100) * 10) / 10,
+ royaltyPayable: a.royaltyPayable,
+ remixable: a.remixable,
+ remixCount: a.remixCount,
+ category: a.model_category,
+ createdAt: a.created_at,
+ }));
+
+ return json(
+ res,
+ 200,
+ { enabled: true, topRemixedAssets, topCreators: creators },
+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },
+ );
+});
diff --git a/api/forge-share.js b/api/forge-share.js
index d51499c7a..810672609 100644
--- a/api/forge-share.js
+++ b/api/forge-share.js
@@ -47,11 +47,15 @@ export default wrap(async (req, res) => {
const pageUrl = `${origin}/forge/share/${id}`;
const forgeUrl = `${origin}/forge?share=${id}`;
const ogImage = row.preview_image_url || `${origin}/api/forge-og?id=${id}`;
+ // oEmbed discovery — /api/oembed resolves this exact shareUrl (extractForgeId
+ // in api/agent-oembed.js) so Notion/Webflow/Discord auto-embed a live 3D
+ // viewer when this URL is pasted, no manual snippet needed.
+ const oembedJsonUrl = `${origin}/api/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');
- res.end(renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin }));
+ res.end(renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin, oembedJsonUrl }));
});
function redirect(res, to) {
@@ -61,7 +65,7 @@ function redirect(res, to) {
res.end();
}
-function renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin }) {
+function renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin, oembedJsonUrl }) {
const t = esc(title);
const d = esc(desc);
return `<!doctype html>
@@ -98,6 +102,7 @@ function renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin }) {
<meta property="fc:frame:button:1:target" content="${esc(forgeUrl)}">
<link rel="canonical" href="${esc(pageUrl)}">
+ <link rel="alternate" type="application/json+oembed" href="${esc(oembedJsonUrl)}" title="${t} oEmbed">
<link rel="shortcut icon" href="/favicon.ico">
<style>
diff --git a/api/remix-feed.js b/api/remix-feed.js
index cc8e8a61b..679334867 100644
--- a/api/remix-feed.js
+++ b/api/remix-feed.js
@@ -30,8 +30,10 @@ import {
hashClient,
forgeStoreEnabled,
listRemixable,
+ listMostRemixed,
setRemixable,
getLineage,
+ validModelCategory,
} from './_lib/forge-store.js';
import { clampRoyaltyBps } from './_lib/remix-royalty.js';
@@ -57,11 +59,33 @@ function publicItem(it) {
royaltyPayable: Boolean(it.royaltyPayable),
isDerived: Boolean(it.isDerived),
lineageIndex: it.lineageIndex ?? 0,
+ remixCount: it.remixCount ?? 0,
category: it.model_category ?? 'other',
createdAt: it.created_at,
};
}
+// Trending item: a most-remixed asset, which may since have been unpublished
+// (remixable: false) — its remix history is a fact even if the terms changed.
+function trendingItem(it) {
+ return {
+ id: it.id,
+ prompt: it.prompt,
+ glbUrl: it.glb_url,
+ previewImageUrl: it.preview_image_url ?? null,
+ viewerUrl: `https://three.ws/viewer?src=${encodeURIComponent(it.glb_url)}`,
+ royaltyBps: it.royaltyBps ?? 0,
+ royaltyPercent: Math.round(((it.royaltyBps ?? 0) / 100) * 10) / 10,
+ royaltyPayable: Boolean(it.royaltyPayable),
+ remixable: Boolean(it.remixable),
+ remixCount: it.remixCount ?? 0,
+ category: it.model_category ?? 'other',
+ createdAt: it.created_at,
+ };
+}
+
+const SORTS = new Set(['recent', 'royalty', 'remixed']);
+
async function handleGet(req, res) {
const url = new URL(req.url, 'http://localhost');
const action = (url.searchParams.get('action') || '').trim();
@@ -84,15 +108,35 @@ async function handleGet(req, res) {
return json(res, 200, { enabled: true, lineage }, { 'cache-control': 'public, s-maxage=30, stale-while-revalidate=120' });
}
+ // The trending half of the creator marketplace leaderboard (prompt 09) —
+ // the most-remixed published assets platform-wide, a real count of child
+ // creations, not a synthetic popularity score.
+ if (action === 'trending') {
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 10, 1), 24);
+ const rows = await listMostRemixed({ limit });
+ return json(
+ res,
+ 200,
+ { enabled: true, items: rows.map(trendingItem) },
+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },
+ );
+ }
+
const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 48);
const before = (url.searchParams.get('before') || '').trim() || undefined;
- const rows = await listRemixable({ limit, before });
+ const category = validModelCategory((url.searchParams.get('category') || '').trim()) || undefined;
+ const q = (url.searchParams.get('q') || '').trim() || undefined;
+ const sortRaw = (url.searchParams.get('sort') || '').trim();
+ const sort = SORTS.has(sortRaw) ? sortRaw : 'recent';
+ const rows = await listRemixable({ limit, before, category, q, sort });
const items = rows.map(publicItem);
- const next = items.length === limit ? items[items.length - 1].createdAt : null;
+ // A non-recent sort returns a fixed top-N leaderboard slice (see
+ // listRemixable) — no cursor, no infinite scroll, by design.
+ const next = sort === 'recent' && items.length === limit ? items[items.length - 1].createdAt : null;
return json(
res,
200,
- { enabled: true, items, next },
+ { enabled: true, items, next, sort, category: category ?? null, q: q ?? null },
{ 'cache-control': 'public, s-maxage=30, stale-while-revalidate=120' },
);
}
diff --git a/data/changelog.json b/data/changelog.json
index 4f88f2850..d81a3578c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-08",
+ "title": "A boutique you can walk into: two tailors now live in /play",
+ "summary": "The wardrobe and cosmetics shop in /play now have a physical home in the world. Walk up to Roux the Tailor to browse and buy fits, hats, and paint jobs, or visit Nell's Fitting Room to equip anything you already own — the same real, server-verified shop and wardrobe the HUD buttons already opened, now with a place to stand. Character creation itself — design an avatar from scratch, scan yourself into 3D with the selfie creator, upload your own .glb, or sculpt in the full Avatar Studio — has no sign-in required and drops you straight into the world.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play"
+ },
+ {
+ "date": "2026-07-08",
+ "title": "/play now has a real economy: a general store, a bank, and a $THREE boutique",
+ "summary": "The open world at /play has a working cash economy. Walk up to a General Store clerk to buy tools and consumables or sell what you've gathered, and visit the Bank Teller to deposit cash into a protected account (banked cash survives a death drop, carried cash doesn't). Premium wardrobe items are now purchasable for real: the wardrobe's locked cosmetics show their $THREE price and unlock with one real on-chain payment from your connected Solana wallet, split between the holder-rewards pool and the treasury — the server only grants the item after re-verifying the confirmed transaction on-chain.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-07-08",
"title": "BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding",
diff --git a/data/pages.json b/data/pages.json
index e9b94085f..fb805137a 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -824,6 +824,14 @@
"changefreq": "daily",
"added": "2026-07-08"
},
+ {
+ "path": "/creations",
+ "title": "Creator Gallery",
+ "description": "Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.",
+ "priority": 0.7,
+ "changefreq": "daily",
+ "added": "2026-07-08"
+ },
{
"path": "/theater",
"title": "Live Trading Theater",
diff --git a/docs/character-studio.md b/docs/character-studio.md
index 76fc302c5..03dfc5977 100644
--- a/docs/character-studio.md
+++ b/docs/character-studio.md
@@ -217,6 +217,68 @@ three.ws supports two avatar creation paths. They're complementary, not competin
---
+## Character customization in `/play` (World Online)
+
+`/play` — the GTA-style multiplayer world (`src/game/coincommunities.js`) — has its own
+end-to-end character customization flow, built entirely on the systems documented above plus
+a server-authoritative cosmetics economy. This section is the map for that flow.
+
+### Creating your avatar before you drop in
+
+The lobby's **Create your avatar** modal (`src/game/coincommunities-ui.js`, `_openCreate()`)
+offers three real paths, each ending in a GLB the world adopts immediately:
+
+1. **Design your avatar** — opens `AvatarCreator` (`src/avatar-creator.js`) in its default
+ editor mode, which loads the Avaturn selfie→3D SDK (`@avaturn/sdk`). No sign-in required;
+ the exported GLB is staged locally and used as your avatar instantly, then uploaded in the
+ background so peers can load it too (`play-handoff.js`).
+2. **Upload a .glb** — bring a model from Blender, Mixamo, VRoid, or any tool. Validated
+ client-side (`avatar-upload.js` `validateGlb`) before it becomes your avatar.
+3. **Advanced studio** — opens the full Avatar Studio (above) at `/create/studio` in a new
+ tab for deep body/face/hair/clothing sculpting, then saves to your account.
+
+### The in-game wardrobe economy
+
+Once in a world, two systems manage cosmetics, both server-authoritative — no client-trusted
+purchase or equip:
+
+- **Shop** (`src/game/cosmetics-shop.js`) — browse the real catalog
+ (`/api/cosmetics/catalog`), preview any item live on your avatar, and buy premium pieces
+ with real USDC via x402 (`cosmetics-purchase.js` → `/api/x402/cosmetic-purchase`). Ownership
+ is recorded server-side (`api/_lib/cosmetics-ownership.js`) and validated by
+ `multiplayer/src/economy.js`. Premium cosmetics are intentionally billed in USDC/`$THREE`,
+ kept separate from the in-world cash economy (`multiplayer/src/shop.js`) — cash buys tools
+ and consumables, cosmetics are a wallet-native collectible layer.
+- **Wardrobe / "My Fits"** (`src/game/cosmetics-wardrobe.js`) — every cosmetic you own (free
+ tier + unlocked premium), grouped by slot. Equipping sends `equip-cosmetic` to the
+ `WalkRoom`, which validates ownership and persists the loadout to your account; the server
+ echoes the authoritative profile back so the wardrobe, your local avatar, and every peer who
+ can see you all agree on your look — durable across logout and world switches.
+
+Both panels are also reachable from the HUD (Shop / **My Fits** buttons,
+`coincommunities-ui.js`), and now from two physical storefronts in the world itself:
+
+### The boutique — walking storefronts, not just a menu
+
+`src/game/world-zones.js` reserves two `boutique` stall coordinates on the Downtown ring,
+mirrored onto the plaza's diagonal opposite the general-store "vendor" stalls so nothing stands
+on top of anything else (`boutique-se` at `(44, 44)`, `boutique-nw` at `(-44, -44)`).
+`src/game/npc/npc-catalog.js` seats two townspeople on them, using the same data-driven
+interactive-NPC engine (`npc.js` / `world-life.js`) every other vendor in the plaza already
+uses:
+
+| NPC | Stall | Press E → |
+|---|---|---|
+| Roux · Tailor | `boutique-se` | Opens the real Shop panel (`world.openShop()`) |
+| Nell · Fitting Room | `boutique-nw` | Opens the real Wardrobe panel (`world.openWardrobe()`) |
+
+Walk up, get the proximity prompt, press E (or tap on touch), and the exact same
+server-validated panels above open — cosmetics customization now has a physical place to
+stand in the world, the way GTA Online's clothing stores do, instead of living only behind a
+HUD button.
+
+---
+
## Limitations
- **Humanoid avatars only.** Avatar Studio is designed for bipedal human characters. It does not support animals, robots, or abstract shapes.
diff --git a/docs/mcp.md b/docs/mcp.md
index ae028919d..83b083eea 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -333,6 +333,28 @@ Soft-delete an avatar you own. Irreversible from the API (contact support to rec
---
+### `attach_avatar_to_agent`
+
+Give an agent a persistent visual body: attach a generated/rigged avatar you own (from `forge_avatar`, `mesh_forge` + `rig_mesh`, or any avatar in `list_my_avatars`) to one of your registered agent identities. The same `agent_id` shows the same body afterwards — `get_avatar`, `render_avatar`, and `get_embed_code` all resolve it. This is the bridge from generation to identity: generate a rigged GLB, save it as an avatar, then call this tool to make it the agent's body. Chain `register_agent` next to mint the on-chain identity (ERC-8004 on Base, or a Metaplex Agent Registry PDA on Solana) and `anchor_provenance` to credential the GLB itself — together the agent has a body, an on-chain identity, and a verifiable authenticity record.
+
+**Scope required:** `agents:write`. Both the agent and the avatar must belong to the caller — requires a signed-in three.ws account (OAuth); x402 pay-per-call principals cannot call this.
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "agent_id": { "type": "string", "format": "uuid", "description": "Your agent identity id." },
+ "avatar_id": { "type": "string", "format": "uuid", "description": "The avatar to attach — one of your own (see list_my_avatars)." }
+ },
+ "required": ["agent_id", "avatar_id"],
+ "additionalProperties": false
+}
+```
+
+Returns `status: "attached"`, the agent/avatar ids and names, `replaced_avatar_id` (the previous body, if any), `profile_url`, and a `next_steps` hint pointing at `register_agent` / `anchor_provenance` when they haven't run yet.
+
+---
+
### `validate_model`
Run the [Khronos glTF-Validator](https://github.com/KhronosGroup/glTF-Validator) against any public HTTPS GLB or glTF URL. Returns error, warning, info, and hint counts with detailed per-issue messages. SSRF-hardened: only public `https://` URLs are fetched.
diff --git a/examples/agent-native-3d/README.md b/examples/agent-native-3d/README.md
new file mode 100644
index 000000000..c5d1eec11
--- /dev/null
+++ b/examples/agent-native-3d/README.md
@@ -0,0 +1,71 @@
+# Agent-native 3D — create, embody, and distribute, end to end
+
+An agent given a goal ("get yourself a body") generates the 3D assets it needs
+and uses them — no browser, no mocks, no human in the loop. This is the
+roadmap-10 demo (`prompts/roadmap/10-agent-native-3d-and-embed.md`): the closing
+proof that three.ws's MCP tools compose into a real autonomous create-and-use
+loop, and that the result is trivially distributable everywhere.
+
+## What it does
+
+Drives the live, **free** three.ws "Free 3D Studio" MCP server
+(`/api/mcp-studio` — see [`docs/mcp-studio.md`](../../docs/mcp-studio.md)) through
+the full chain:
+
+1. `tools/list` — confirms the composable tool contracts are live.
+2. `mesh_forge(prompt)` — text → a static 3D mesh (Granite-directed model chain).
+3. `rig_mesh(glb_url)` — auto-rig it into an animation-ready GLB.
+4. `create_agent_persona(glb_url, name)` — save the rigged GLB as a NAMED,
+ persistent agent body.
+5. `persona_say(persona_id, text)` — perform a line through that body
+ (lip-sync + emotion).
+6. `get_agent_persona(persona_id)` — reload the SAME body in a **fresh** call,
+ proving continuity (not a per-call random result).
+7. Build every distribution snippet — iframe, `<model-viewer>`, `<agent-3d>`, a
+ `@three-ws/page-agent` talking guide, and a `@three-ws/walk` companion —
+ using the exact same pure functions
+ ([`src/forge-embed-snippets.js`](../../src/forge-embed-snippets.js)) the
+ Forge web app's "Embed this model" panel uses, so what this script prints is
+ byte-identical to what a human copies from the UI.
+
+All six MCP tools it calls are **free** — no x402 payment, no wallet, no API
+key. Every request/response is a real HTTP round-trip against production (or
+your local dev server); nothing here is stubbed.
+
+## Run it
+
+```bash
+cd examples/agent-native-3d
+node run.mjs
+```
+
+Against a local dev server instead of production:
+
+```bash
+npm run dev # from the repo root, in another terminal
+MCP_STUDIO_URL=http://localhost:3000/api/mcp-studio node run.mjs
+```
+
+Every request and response is written to
+[`prompts/roadmap/_generated/10/agent-native-3d-transcript.json`](../../prompts/roadmap/_generated/10/agent-native-3d-transcript.json)
+after each run.
+
+## About the rate-limit fallback
+
+`mesh_forge` / `rig_mesh` share one platform-wide free-tier generation lane
+(the same one `/forge` web-page drafts use) with a real capacity ceiling. If
+that lane is saturated when you run this, the script backs off using the
+server's own quoted `retry_after` (bounded, never a blind sleep loop) and, if
+it's still saturated past the budget, falls back to a known-good rigged GLB
+(`https://three.ws/avatars/default.glb`) so steps 4–7 — embodiment, speech,
+continuity, and distribution — still run for real. The fallback is logged
+loudly in the console and recorded in the transcript (`result.fallback_used`),
+never silently substituted; the failed generation calls are preserved verbatim
+in `transcript.steps` for audit.
+
+## Why this matters
+
+This is the "own → use everywhere" half of the roadmap's closing loop
+(prompts 08/09/10): generate a body, embody an agent identity with it, and
+hand out real distribution in one call each — the same primitives a human
+uses from the Forge UI, callable end to end by an agent with zero UI.
diff --git a/examples/agent-native-3d/package.json b/examples/agent-native-3d/package.json
new file mode 100644
index 000000000..5c06e560e
--- /dev/null
+++ b/examples/agent-native-3d/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "@three-ws/example-agent-native-3d",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "description": "An agent that autonomously generates, rigs, embodies, and distributes a 3D creation end-to-end via three.ws MCP tools — no browser, no mocks.",
+ "scripts": {
+ "start": "node run.mjs"
+ }
+}
diff --git a/examples/agent-native-3d/run.mjs b/examples/agent-native-3d/run.mjs
new file mode 100644
index 000000000..c3288b3cd
--- /dev/null
+++ b/examples/agent-native-3d/run.mjs
@@ -0,0 +1,240 @@
+#!/usr/bin/env node
+// Agent-native 3D — end to end, no browser, no mocks.
+// ====================================================
+// Roadmap prompt 10 (prompts/roadmap/10-agent-native-3d-and-embed.md), track A:
+// an agent given a goal generates the 3D assets it needs and uses them, chaining
+// real MCP tool calls against the live three.ws "Free 3D Studio"
+// (`/api/mcp-studio` — see docs/mcp-studio.md). Every call in this script is a
+// real HTTP JSON-RPC request; every URL it prints resolves.
+//
+// The chain:
+// 1. tools/list — confirm the composable tool contracts are live.
+// 2. mesh_forge(prompt) — text → a static 3D mesh (Granite-directed chain).
+// 3. rig_mesh(glb_url) — auto-rig the mesh into an animation-ready GLB.
+// 4. create_agent_persona — save the rigged GLB as a NAMED, persistent body.
+// 5. persona_say — perform a line through that body (lip-sync + emote).
+// 6. get_agent_persona — reload by id in a FRESH call — proves continuity.
+// 7. Build every distribution snippet (iframe / web component / <agent-3d> /
+// page-agent / walk companion) with the SAME pure builders the Forge UI's
+// embed panel uses (src/forge-embed-snippets.js) — not a reimplementation,
+// so what this script prints is byte-identical to what a human would copy
+// from the "Embed this model" panel on /forge.
+//
+// All six MCP tools are FREE (no x402, no wallet, no API key) — this is the
+// "Free 3D Studio" lane, the same one the /forge web page's drafts use. Steps
+// 2–3 share a global generation rate limit with the rest of the platform; on a
+// `rate_limited` response this script backs off using the server's own
+// `retry_after` (bounded, never a blind sleep loop) and, if the lane stays
+// saturated past the budget, falls back to a known-good rigged GLB so steps
+// 4–7 still run for real — the fallback is logged loudly in the transcript,
+// never silently substituted.
+//
+// Usage:
+// node run.mjs # against production
+// MCP_STUDIO_URL=http://localhost:3000/api/mcp-studio node run.mjs # local dev
+//
+// Writes a full transcript (every request + response) to
+// prompts/roadmap/_generated/10/agent-native-3d-transcript.json.
+
+import { writeFile, mkdir } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import { dirname, join, resolve } from 'node:path';
+
+import {
+ buildIframeSnippet,
+ buildWebComponentSnippet,
+ buildAgentThreeDSnippet,
+ buildPageAgentSnippet,
+ buildWalkCompanionSnippet,
+ embedPageUrl,
+} from '../../src/forge-embed-snippets.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(HERE, '../..');
+const OUT_DIR = join(REPO_ROOT, 'prompts/roadmap/_generated/10');
+const OUT_FILE = join(OUT_DIR, 'agent-native-3d-transcript.json');
+
+const MCP_URL = process.env.MCP_STUDIO_URL || 'https://three.ws/api/mcp-studio';
+const PROMPT = process.env.DEMO_PROMPT || 'a small friendly round robot mascot, glossy white plastic, blue visor';
+const AGENT_NAME = process.env.DEMO_NAME || 'Roadmap-10 Demo Agent';
+// A known-good, already-rigged public GLB — used ONLY if the shared generation
+// lane stays rate-limited past the retry budget, so the embodiment/distribution
+// half of the chain (steps 4-7) still runs for real. Logged, never silent.
+const FALLBACK_RIGGED_GLB = 'https://three.ws/avatars/default.glb';
+
+const transcript = { started_at: new Date().toISOString(), mcp_url: MCP_URL, prompt: PROMPT, steps: [] };
+let rpcId = 0;
+
+function log(...args) {
+ console.log(...args);
+}
+
+async function call(method, params) {
+ const id = ++rpcId;
+ const body = { jsonrpc: '2.0', id, method, ...(params ? { params } : {}) };
+ const startedAt = Date.now();
+ const res = await fetch(MCP_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const json = await res.json();
+ const entry = {
+ method,
+ tool: params?.name || null,
+ request: params?.arguments || null,
+ http_status: res.status,
+ duration_ms: Date.now() - startedAt,
+ response: json,
+ };
+ transcript.steps.push(entry);
+ return json;
+}
+
+// Every tool on this free studio is guarded by its own rate limiter (a
+// per-call generation-lane cap on the five generators, a per-IP write burst
+// cap on the three persona tools — see api/_mcp-studio/persona-tools.js
+// guardWrite) and the two limiters return different shapes: the generation
+// tools return a structured { error: 'rate_limited', retry_after }, the
+// persona write tools return a plain isError text ("Too many requests…") with
+// no retry_after. Detect both and back off — bounded to maxWaitMs total so a
+// saturated lane degrades to the documented fallback instead of hanging.
+function rateLimitInfo(json) {
+ const result = json.result;
+ const text = result?.content?.[0]?.text || '';
+ if (result?.structuredContent?.error === 'rate_limited' || result?.error === 'rate_limited') {
+ return { limited: true, retryAfterS: Number(result?.retry_after ?? result?.structuredContent?.retry_after ?? 3) };
+ }
+ if (result?.isError && /too many requests|rate.?limit/i.test(text)) {
+ return { limited: true, retryAfterS: 6 }; // no retry_after quoted — fixed backoff
+ }
+ return { limited: false };
+}
+
+async function callToolWithBackoff(name, args, { maxWaitMs = 60_000 } = {}) {
+ let waited = 0;
+ for (;;) {
+ const json = await call('tools/call', { name, arguments: args });
+ const { limited, retryAfterS } = rateLimitInfo(json);
+ if (!limited) return json;
+
+ const waitMs = Math.max(1000, Math.min(15_000, retryAfterS * 1000));
+ if (waited + waitMs > maxWaitMs) {
+ log(` ⏳ ${name} still rate-limited after ${Math.round(waited / 1000)}s of backoff — giving up for this run.`);
+ return json; // caller decides the fallback
+ }
+ log(` ⏳ ${name} rate-limited — backing off ${Math.round(waitMs / 1000)}s (server-quoted retry_after=${retryAfterS}s)…`);
+ await new Promise((r) => setTimeout(r, waitMs));
+ waited += waitMs;
+ }
+}
+
+function isToolError(json) {
+ return Boolean(json?.result?.isError) || Boolean(json?.error);
+}
+
+async function main() {
+ await mkdir(OUT_DIR, { recursive: true });
+
+ log(`\n1. tools/list — ${MCP_URL}`);
+ const list = await call('tools/list');
+ const names = (list.result?.tools || []).map((t) => t.name);
+ log(` ${names.length} tools live: ${names.join(', ')}`);
+ for (const need of ['mesh_forge', 'rig_mesh', 'create_agent_persona', 'get_agent_persona', 'persona_say']) {
+ if (!names.includes(need)) throw new Error(`expected composable tool "${need}" missing from tools/list`);
+ }
+
+ log(`\n2. mesh_forge — "${PROMPT}"`);
+ let meshJson = await callToolWithBackoff('mesh_forge', { prompt: PROMPT });
+ let staticGlb = meshJson.result?.structuredContent?.glbUrl || meshJson.result?.structuredContent?.glb_url || null;
+ let generationUsed = Boolean(staticGlb) && !isToolError(meshJson);
+
+ let riggedGlb = null;
+ if (generationUsed) {
+ log(` ✓ static mesh: ${staticGlb}`);
+ log(`\n3. rig_mesh — ${staticGlb}`);
+ const rigJson = await callToolWithBackoff('rig_mesh', { glb_url: staticGlb });
+ riggedGlb = rigJson.result?.structuredContent?.glbUrl || rigJson.result?.structuredContent?.glb_url || null;
+ if (!riggedGlb || isToolError(rigJson)) {
+ log(' ⚠ rig_mesh did not return a rigged GLB — falling back to the known-good rig for steps 4+.');
+ generationUsed = false;
+ } else {
+ log(` ✓ rigged: ${riggedGlb}`);
+ }
+ } else {
+ log(` ⚠ generation lane unavailable this run (${JSON.stringify(meshJson.result || meshJson.error)}).`);
+ }
+
+ const bodyGlb = riggedGlb || FALLBACK_RIGGED_GLB;
+ if (!riggedGlb) {
+ log(`\n⚠ FALLBACK — using a known-good rigged GLB for steps 4-7: ${bodyGlb}`);
+ log(' (The generation lane is shared platform-wide and was saturated at run time; the failed');
+ log(' mesh_forge/rig_mesh calls above are recorded verbatim in the transcript for audit.)');
+ }
+
+ log(`\n4. create_agent_persona — "${AGENT_NAME}"`);
+ const personaJson = await callToolWithBackoff('create_agent_persona', {
+ glb_url: bodyGlb,
+ name: AGENT_NAME,
+ source_prompt: PROMPT,
+ });
+ if (isToolError(personaJson)) throw new Error(`create_agent_persona failed: ${JSON.stringify(personaJson.result)}`);
+ const persona = personaJson.result.structuredContent;
+ log(` ✓ persona_id: ${persona.persona_id}`);
+ log(` ✓ live body: ${personaJson.result.content[1]?.resource?.uri}`);
+
+ log(`\n5. persona_say — perform a line through the body`);
+ const sayJson = await callToolWithBackoff('persona_say', {
+ persona_id: persona.persona_id,
+ text: `Hello — I generated and embodied myself through three.ws MCP tools, autonomously.`,
+ });
+ if (isToolError(sayJson)) throw new Error(`persona_say failed: ${JSON.stringify(sayJson.result)}`);
+ log(` ✓ turn_count: ${sayJson.result.structuredContent.turn_count}, emotion: ${sayJson.result.structuredContent.emotion}`);
+
+ log(`\n6. get_agent_persona — reload in a FRESH call (proves continuity)`);
+ const reloadJson = await callToolWithBackoff('get_agent_persona', { persona_id: persona.persona_id });
+ if (isToolError(reloadJson)) throw new Error(`get_agent_persona failed: ${JSON.stringify(reloadJson.result)}`);
+ const reloaded = reloadJson.result.structuredContent;
+ if (reloaded.turn_count !== sayJson.result.structuredContent.turn_count) {
+ throw new Error('continuity check failed: turn_count did not persist across a fresh call');
+ }
+ log(` ✓ same body reloaded by persona_id — turn_count persisted (${reloaded.turn_count})`);
+
+ log(`\n7. Distribution — every embed flavour, built with the SAME pure functions`);
+ log(` the Forge UI's "Embed this model" panel uses (src/forge-embed-snippets.js):`);
+ const snippets = {
+ standalone_viewer: embedPageUrl(persona.glb_url, AGENT_NAME),
+ iframe: buildIframeSnippet(persona.glb_url, AGENT_NAME, 'wide'),
+ web_component: buildWebComponentSnippet(persona.glb_url, AGENT_NAME, 'wide'),
+ agent_3d: buildAgentThreeDSnippet(persona.glb_url, AGENT_NAME, 'wide'),
+ page_agent: buildPageAgentSnippet(persona.glb_url, AGENT_NAME),
+ walk_companion: buildWalkCompanionSnippet(persona.glb_url, AGENT_NAME),
+ };
+ for (const [flavor, snippet] of Object.entries(snippets)) {
+ log(`\n — ${flavor} —`);
+ log(' ' + snippet.split('\n').join('\n '));
+ }
+
+ transcript.result = {
+ ok: true,
+ generation_used: generationUsed,
+ fallback_used: !generationUsed,
+ persona_id: persona.persona_id,
+ body_glb_url: persona.glb_url,
+ embodiment_view: personaJson.result.content[1]?.resource?.uri || null,
+ distribution_snippets: snippets,
+ };
+ transcript.finished_at = new Date().toISOString();
+ await writeFile(OUT_FILE, JSON.stringify(transcript, null, 2));
+ log(`\n✓ Full chain complete. Transcript written to ${OUT_FILE.replace(REPO_ROOT + '/', '')}`);
+ log(`✓ ${generationUsed ? 'Generated, rigged,' : 'Embodied (fallback rig — generation lane was saturated),'} embodied, spoke, reloaded, and distributed — one agent, one goal, zero mocks.`);
+}
+
+main().catch(async (err) => {
+ transcript.error = String(err?.stack || err);
+ transcript.finished_at = new Date().toISOString();
+ await mkdir(OUT_DIR, { recursive: true }).catch(() => {});
+ await writeFile(OUT_FILE, JSON.stringify(transcript, null, 2)).catch(() => {});
+ console.error('\n✗ FAILED:', err);
+ process.exitCode = 1;
+});
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 196a7471b..fc510633d 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -34,13 +34,20 @@ import {
restoreProfile, serializeProfile, profileSnapshot,
addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,
countItem, removeItem,
- dropCarried, reviveProfile, bankTransfer,
+ dropCarried, reviveProfile, bankTransfer, grantCosmetic,
equipCosmetic, ownedCosmeticSet, mergeOwnedFromLedger,
HOTBAR_SIZE,
} from '../economy.js';
import {
serializeLoadout, getCosmetic, canWear, DEFAULT_LOADOUT,
} from '../cosmetics-catalog.js';
+import {
+ clientStoreCatalog, sellPrice, isSellable, buyEntry,
+ boutiqueListings, boutiquePrice,
+} from '../shop.js';
+import {
+ buildTokenPurchase, verifyTokenPurchase, isWalletAddress, tokenConfigured, TOKEN_DECIMALS,
+} from '../game-token.js';
import { readOwnedCosmetics } from '../cosmetics-ownership.js';
import {
itemLabel, fishCatchChance, fishDoubleChance,
@@ -257,7 +264,13 @@ const COOK_COOLDOWN_MS = 900; // pace between fish on the fire
// Per-action rate ceilings (messages/sec/client) — a flooding client is dropped.
// vsync rides at the same 15Hz the move netcode uses; allow 2× for jitter, like
// MOVES_PER_SEC_LIMIT. enter/exit are deliberate, rare actions.
-const ACTION_RATES = { fish: 6, consume: 6, equip: 30, chop: 6, mine: 6, cook: 8, vsync: PATCH_RATE_HZ * 2, venter: 4, vexit: 4, quest: 8, questInteract: 6, clear: 2 };
+const ACTION_RATES = {
+ fish: 6, consume: 6, equip: 30, chop: 6, mine: 6, cook: 8, vsync: PATCH_RATE_HZ * 2,
+ venter: 4, vexit: 4, quest: 8, questInteract: 6, clear: 2,
+ // General store, bank/ATM, and the $THREE boutique (W04) — low-frequency,
+ // currency-mutating actions, throttled tighter than the gather loop.
+ store: 6, storeBuy: 6, storeSell: 6, bank: 6, boutique: 4, boutiqueQuote: 3, boutiqueSettle: 3,
+};
// Spatial voice signaling. The room only relays SDP/ICE between two peers (the
// audio itself flows peer-to-peer over WebRTC), so the cap just has to clear a
@@ -399,6 +412,10 @@ 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 } }
+ // $THREE boutique (W04) replay guard: settled quote nonces, pruned past the
+ // quote TTL so a verified purchase can never re-grant a cosmetic twice, while
+ // memory stays bounded (a nonce only needs to outlive its ~90s quote window).
+ this._boutiqueNonces = new Map(); // nonce → settledAt (ms)
// 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
@@ -494,6 +511,16 @@ export class WalkRoom extends Room {
registerActivityHandlers(this); // W06 gather/craft: chop, mine, cook
this.onMessage('equip', (client, payload) => this._handleEquip(client, payload));
this.onMessage('consume', (client, payload) => this._handleConsume(client, payload));
+ // General store, bank/ATM, and the $THREE boutique (W04). Cash trades and
+ // banking settle purely off-schema; the boutique settles a real on-chain
+ // $THREE payment (game-token.js) before granting a premium cosmetic.
+ this.onMessage('storeReq', (client) => this._sendStore(client));
+ this.onMessage('storeBuy', (client, payload) => this._handleStoreBuy(client, payload));
+ this.onMessage('storeSell', (client, payload) => this._handleStoreSell(client, payload));
+ this.onMessage('bank', (client, payload) => this._handleBank(client, payload));
+ this.onMessage('boutiqueReq', (client) => this._sendBoutique(client));
+ this.onMessage('boutiqueQuote', (client, payload) => this._handleBoutiqueQuote(client, payload));
+ this.onMessage('boutiqueSettle', (client, payload) => this._handleBoutiqueSettle(client, payload));
// Equip/unequip a cosmetic from the owned-inventory (R23). Server-authoritative:
// validates ownership, persists the loadout to the account, re-publishes it on
// the schema so peers re-render, and echoes the owner a fresh profile.
@@ -1710,6 +1737,223 @@ export class WalkRoom extends Room {
this._persistEcon(client.sessionId);
}
+ // --- General store & bank/ATM (W04) --------------------------------------
+ //
+ // Cash economy, entirely off-schema like the rest of the purse/pack: the
+ // server prices every trade from shop.js (never a client-supplied number),
+ // mutates the profile, and echoes the owner a fresh inv/profile snapshot.
+
+ // The general store's catalog — sell prices + the buy list — so the client
+ // renders exactly what the server will charge/pay, no drift possible.
+ _sendStore(client) {
+ client.send('store', clientStoreCatalog());
+ }
+
+ // Buy `item` from the general store for cash. Validates the catalog entry,
+ // the purse, and pack room before moving anything — a rejected buy costs
+ // nothing and leaves the pack untouched.
+ _handleStoreBuy(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'storeBuy')) return;
+ const item = typeof payload?.item === 'string' ? payload.item.slice(0, 32) : '';
+ const entry = buyEntry(item);
+ if (!entry) {
+ client.send('notice', { kind: 'store', text: 'That item isn’t for sale.' });
+ return;
+ }
+ if (profile.gold < entry.price) {
+ client.send('notice', { kind: 'store', text: `Not enough cash — ${entry.price} needed.` });
+ return;
+ }
+ if (!hasRoomFor(profile, entry.item)) {
+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
+ return;
+ }
+ const leftover = addItem(profile, entry.item, entry.qty);
+ const bought = entry.qty - leftover;
+ if (bought <= 0) {
+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
+ return;
+ }
+ profile.gold -= entry.price;
+ this._sendInv(client, profile);
+ client.send('notice', { kind: 'store', text: `Bought ${bought > 1 ? bought + ' ' : ''}${itemLabel(entry.item)} for ${entry.price} cash.` });
+ this._persistEcon(client.sessionId);
+ }
+
+ // Sell a stack from a referenced pack slot for cash. `qty` sells up to that
+ // many (defaults to the whole stack); the price always comes from
+ // SELL_PRICES server-side, never a client-supplied amount.
+ _handleStoreSell(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'storeSell')) return;
+ const slot = resolveSlot(profile, payload?.slot);
+ if (!slot || !slot.item) {
+ client.send('notice', { kind: 'store', text: 'Nothing there to sell.' });
+ return;
+ }
+ if (!isSellable(slot.item)) {
+ client.send('notice', { kind: 'store', text: `The store won’t buy ${itemLabel(slot.item).toLowerCase()}.` });
+ return;
+ }
+ const want = Number.isFinite(payload?.qty) && payload.qty > 0 ? Math.min(payload.qty | 0, slot.qty) : slot.qty;
+ const item = slot.item;
+ const removed = removeItem(profile, item, want);
+ if (removed <= 0) return;
+ const total = sellPrice(item) * removed;
+ profile.gold += total;
+ this._sendInv(client, profile);
+ client.send('notice', { kind: 'store', text: `Sold ${removed} ${itemLabel(item).toLowerCase()} for ${total} cash.` });
+ this._persistEcon(client.sessionId);
+ }
+
+ // Move cash between the carried purse and the protected bank (the ATM).
+ // Positive amounts deposit, negative withdraw; bankTransfer clamps to
+ // what's actually available so it can never mint or strand cash. Banked
+ // cash is untouched by a death drop (economy.js dropCarried) — the whole
+ // risk/reward point of using the bank.
+ _handleBank(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'bank')) return;
+ const amount = Number.isFinite(payload?.amount) ? payload.amount | 0 : 0;
+ if (!amount) return;
+ const moved = bankTransfer(profile, amount);
+ if (moved === 0) {
+ client.send('notice', { kind: 'bank', text: amount > 0 ? 'No cash on hand to deposit.' : 'Nothing banked to withdraw.' });
+ return;
+ }
+ this._sendProfile(client);
+ client.send('notice', {
+ kind: 'bank',
+ text: moved > 0 ? `Deposited ${moved} cash — protected from drops.` : `Withdrew ${-moved} cash.`,
+ });
+ this._persistEcon(client.sessionId);
+ }
+
+ // --- $THREE boutique (W04) -------------------------------------------------
+ //
+ // Premium in-game cosmetics (multiplayer/src/cosmetics-catalog.js), priced
+ // and unlocked entirely separately from the R21–25 avatar-shop/x402 rail
+ // (which sells a different catalog, settled in USDC, for the standalone
+ // character creator). This is the purpose-built W04 rail: the buyer's own
+ // Solana wallet sends ONE real $THREE transaction (game-token.js), split
+ // between the holder-rewards pool and the treasury, and the server re-reads
+ // that transaction from RPC before granting anything — never trusting a
+ // client "it worked" claim.
+
+ // The boutique catalog (priced in $THREE) + this account's owned ids.
+ _sendBoutique(client) {
+ const profile = this.econ.get(client.sessionId);
+ client.send('boutique', {
+ listings: boutiqueListings(),
+ owned: [...(profile?.cosmetics?.owned || [])],
+ configured: tokenConfigured(),
+ });
+ }
+
+ // Price + build the unsigned $THREE purchase transaction for one boutique
+ // item. `wallet` is whichever Solana wallet the player has connected in the
+ // browser — it pays; the unlock always lands on THIS session's profile
+ // regardless of who fronts the tokens (the same "anyone can settle a quote"
+ // model buildSpinPayment already uses). The price is read from the server
+ // catalog only — a client can never move it.
+ async _handleBoutiqueQuote(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'boutiqueQuote')) return;
+ const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
+ const price = boutiquePrice(id);
+ if (!price) {
+ client.send('notice', { kind: 'boutique', text: 'That item isn’t in the boutique.' });
+ return;
+ }
+ if (ownedCosmeticSet(profile).has(id)) {
+ client.send('notice', { kind: 'boutique', text: 'You already own that.' });
+ return;
+ }
+ const wallet = typeof payload?.wallet === 'string' ? payload.wallet.trim() : '';
+ if (!isWalletAddress(wallet)) {
+ client.send('notice', { kind: 'boutique', text: 'Connect a Solana wallet to buy with $THREE.' });
+ return;
+ }
+ if (!tokenConfigured()) {
+ client.send('notice', { kind: 'boutique', text: 'The $THREE boutique is offline right now.' });
+ return;
+ }
+ let built;
+ try {
+ const amountRaw = BigInt(Math.round(price * 10 ** TOKEN_DECIMALS));
+ built = await buildTokenPurchase({
+ buyerWallet: wallet,
+ amountRaw,
+ purpose: 'boutique',
+ extra: { cosmeticId: id },
+ });
+ } catch (err) {
+ console.warn('[walk_world] boutique quote failed:', err?.message);
+ }
+ if (!built) {
+ client.send('notice', { kind: 'boutique', text: 'Could not price that purchase — try again in a moment.' });
+ return;
+ }
+ client.send('boutiqueQuote', { id, price, quoteToken: built.quoteToken, txBase64: built.txBase64 });
+ }
+
+ // Settle a signed $THREE purchase: re-verify the on-chain transaction against
+ // the sealed quote against live RPC (never the client's "it worked"), then
+ // grant the cosmetic exactly once per settled nonce.
+ async _handleBoutiqueSettle(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'boutiqueSettle')) return;
+ const quoteToken = typeof payload?.quoteToken === 'string' ? payload.quoteToken : '';
+ const txSig = typeof payload?.txSig === 'string' ? payload.txSig : '';
+ if (!quoteToken || !txSig) return;
+
+ let result;
+ try {
+ result = await verifyTokenPurchase({ quoteToken, txSig, purpose: 'boutique' });
+ } catch (err) {
+ console.warn('[walk_world] boutique settle failed:', err?.message);
+ client.send('notice', { kind: 'boutique', text: 'Could not verify that payment — try again.' });
+ return;
+ }
+ if (!result?.ok) {
+ client.send('notice', { kind: 'boutique', text: `Payment didn’t verify (${result?.reason || 'unknown'}).` });
+ return;
+ }
+ this._pruneBoutiqueNonces();
+ if (this._boutiqueNonces.has(result.nonce)) {
+ client.send('notice', { kind: 'boutique', text: 'That purchase already settled.' });
+ return;
+ }
+ this._boutiqueNonces.set(result.nonce, Date.now());
+ const cosmeticId = result.quote?.cosmeticId;
+ if (ownedCosmeticSet(profile).has(cosmeticId)) {
+ client.send('notice', { kind: 'boutique', text: 'Payment verified — you already owned this.' });
+ return;
+ }
+ const granted = cosmeticId ? grantCosmetic(profile, cosmeticId) : false;
+ if (!granted) {
+ client.send('notice', { kind: 'boutique', text: 'Payment verified, but that item couldn’t be unlocked. Contact support.' });
+ return;
+ }
+ this._sendProfile(client);
+ client.send('notice', { kind: 'boutique', text: `Unlocked ${getCosmetic(cosmeticId)?.name || 'the item'} — check your wardrobe.` });
+ this._persistEcon(client.sessionId);
+ }
+
+ // Replay-guard nonces only need to outlive the quote's own TTL (~90s); prune
+ // with a generous margin so memory never grows unbounded across a long-lived
+ // room while staying well clear of any in-flight settle.
+ _pruneBoutiqueNonces() {
+ const cutoff = Date.now() - 5 * 60_000;
+ for (const [nonce, ts] of this._boutiqueNonces) if (ts < cutoff) this._boutiqueNonces.delete(nonce);
+ }
+
// Write this session's economy profile through to the account-keyed store,
// merging onto any existing record so unrelated fields for the same account
// are preserved. Synchronous + debounced.
diff --git a/pages/creations.html b/pages/creations.html
new file mode 100644
index 000000000..46d3067dd
--- /dev/null
+++ b/pages/creations.html
@@ -0,0 +1,183 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Creator Gallery · three.ws</title>
+ <meta
+ name="description"
+ content="Browse, remix, and earn from 3D creations on three.ws — search and filter the live remix bazaar, watch a real royalty route to the original creator the moment someone builds on your work, and see who's leading the leaderboard."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/creations" />
+ <meta property="og:title" content="Creator Gallery · three.ws" />
+ <meta
+ property="og:description"
+ content="Browse, remix, and earn from 3D creations — live remix bazaar, real on-chain royalties, and a creator leaderboard."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Creator+Gallery&amp;d=Browse%2C+remix%2C+and+earn+from+3D+creations+on+three.ws+%E2%80%94+live+remix+bazaar%2C+real+on-chain+royalties%2C+creator+leaderboard&amp;p=%2Fcreations" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Creator Gallery · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Browse, remix, and earn from 3D creations — live remix bazaar, real on-chain royalties, creator leaderboard."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Creator+Gallery&amp;d=Browse%2C+remix%2C+and+earn+from+3D+creations+on+three.ws+%E2%80%94+live+remix+bazaar%2C+real+on-chain+royalties%2C+creator+leaderboard&amp;p=%2Fcreations" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/creations.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/creations" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"CollectionPage","name":"Creator Gallery","description":"Browse, remix, and earn from 3D creations on three.ws.","url":"https://three.ws/creations","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Creator Gallery — three.ws" />
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="cr-shell">
+ <section class="cr-hero">
+ <p class="cr-kicker"><span class="cr-live-dot" aria-hidden="true"></span> Live remix bazaar</p>
+ <h1 class="cr-title">Creator <em>Gallery</em></h1>
+ <p class="cr-sub">
+ Every 3D creation published to the remix bazaar — search it, filter it, watch it live in 3D, and
+ <strong>remix</strong> anything for a small USDC fee. A real royalty routes to the original
+ creator on-chain the moment your remix mints — never a ledger entry, always a signed transfer.
+ </p>
+ <div class="cr-hero-ctas">
+ <a class="cr-btn cr-btn-primary" href="/forge">Forge a 3D model</a>
+ <a class="cr-btn" href="#cr-publish">Publish a creation</a>
+ <a class="cr-btn" href="/minted">Minted NFTs</a>
+ </div>
+ </section>
+
+ <section class="cr-leaderboards" aria-label="Trending and leaderboards">
+ <div class="cr-lb-col">
+ <div class="cr-lb-head">
+ <h2 class="cr-section-h">Trending remixes</h2>
+ <span class="cr-lb-sub">Most-built-on assets, platform-wide</span>
+ </div>
+ <ol class="cr-lb-list" id="cr-trending-list" aria-busy="true"></ol>
+ </div>
+ <div class="cr-lb-col">
+ <div class="cr-lb-head">
+ <h2 class="cr-section-h">Top creators</h2>
+ <span class="cr-lb-sub">Agents earning the most from remixes of their work</span>
+ </div>
+ <ol class="cr-lb-list" id="cr-creators-list" aria-busy="true"></ol>
+ </div>
+ </section>
+
+ <section class="cr-controls" aria-label="Search and filter">
+ <div class="cr-search-row">
+ <label class="cr-search" for="cr-q">
+ <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.6" d="M13.6 13.6 18 18M9 15.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13Z"/></svg>
+ <input type="search" id="cr-q" placeholder="Search prompts — “dragon”, “sneaker”, “low-poly car”…" autocomplete="off" maxlength="120" />
+ </label>
+ <select id="cr-category" class="cr-select" aria-label="Filter by category">
+ <option value="">All categories</option>
+ <option value="avatar">Avatar</option>
+ <option value="accessory">Accessory</option>
+ <option value="item">Item</option>
+ <option value="scene">Scene</option>
+ <option value="creature">Creature</option>
+ <option value="vehicle">Vehicle</option>
+ <option value="other">Other</option>
+ </select>
+ </div>
+ <div class="cr-sort-row" role="tablist" aria-label="Sort">
+ <button type="button" class="cr-sort-btn active" data-sort="recent" role="tab" aria-selected="true">New</button>
+ <button type="button" class="cr-sort-btn" data-sort="remixed" role="tab" aria-selected="false">Most remixed</button>
+ <button type="button" class="cr-sort-btn" data-sort="royalty" role="tab" aria-selected="false">Highest royalty</button>
+ </div>
+ </section>
+
+ <section class="cr-feed-head">
+ <h2 class="cr-section-h">Browse</h2>
+ <span id="cr-count" class="cr-count" aria-live="polite"></span>
+ </section>
+
+ <section id="cr-feed" class="cr-grid" aria-label="3D creations" aria-busy="true"></section>
+
+ <div id="cr-footer-state" class="cr-footer-state"></div>
+
+ <section class="cr-card cr-lineage-panel is-hidden" id="cr-lineage-panel" aria-labelledby="cr-lineage-title">
+ <div class="cr-lineage-head">
+ <h2 class="cr-section-h" id="cr-lineage-title">Remix lineage</h2>
+ <button type="button" class="cr-icon-btn" id="cr-lineage-close" aria-label="Close lineage view">✕</button>
+ </div>
+ <ol class="cr-lineage-chain" id="cr-lineage-chain"></ol>
+ </section>
+
+ <section class="cr-publish" id="cr-publish">
+ <h2 class="cr-section-h">Publish a creation</h2>
+ <p class="cr-publish-sub">
+ Own a finished creation from <a href="/forge">Forge</a>? Opt it into the bazaar with a license,
+ an optional royalty rate (capped at 20%), and the Solana wallet that collects it. Publishing is
+ free — the fee lands on the creator only when someone remixes it.
+ </p>
+ <form class="cr-publish-form" id="cr-publish-form">
+ <label class="cr-field">
+ <span>Creation ID</span>
+ <input type="text" id="cr-pub-id" placeholder="Paste the id from your Forge result" required maxlength="64" />
+ </label>
+ <label class="cr-field">
+ <span>License</span>
+ <select id="cr-pub-license">
+ <option value="remix-royalty" selected>Remix allowed · royalty on remix</option>
+ <option value="remix-cc">Remix freely · no royalty</option>
+ <option value="remix-nc">Remix, non-commercial</option>
+ <option value="all-rights">Display only · not remixable</option>
+ </select>
+ </label>
+ <label class="cr-field" id="cr-pub-royalty-row">
+ <span>Royalty rate <output id="cr-pub-royalty-out">10%</output></span>
+ <input type="range" id="cr-pub-royalty" min="0" max="20" step="1" value="10" />
+ </label>
+ <label class="cr-field">
+ <span>Payout wallet (Solana, optional)</span>
+ <input type="text" id="cr-pub-wallet" placeholder="Leave blank to publish without collecting royalties yet" maxlength="44" />
+ </label>
+ <button type="submit" class="cr-btn cr-btn-primary" id="cr-pub-submit">Publish to the gallery</button>
+ <div class="cr-publish-status" id="cr-pub-status" role="status" aria-live="polite"></div>
+ </form>
+ </section>
+
+ <section class="cr-about">
+ <h2 class="cr-section-h">How the remix bazaar works</h2>
+ <p class="cr-about-body">
+ Publishing a finished creation is free and opt-in — nothing is published without you choosing
+ to. A remixer pays a fixed <strong>$0.25 USDC</strong> fee over x402 to generate a new version
+ anchored to your model; the platform collects the fee, generates the remix, links the durable
+ parent → child lineage, and routes your royalty slice (up to 20%, your choice) on-chain the
+ moment the remix confirms — a real second USDC transfer, not a promise. Creator identity here is
+ intentionally anonymous (a hashed client key, never a wallet or account) unless you set a
+ payout wallet; the one creator surface with a public, on-chain identity is an <strong>agent</strong>
+ that minted a 3D asset as an NFT — see its profile and reputation on <a href="/agents">/agents</a>,
+ or browse every mint at <a href="/minted">/minted</a>.
+ </p>
+ </section>
+ </main>
+
+ <script type="module" src="/src/creations.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md b/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md
index c8e7cb129..6387fc9a3 100644
--- a/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md
+++ b/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md
@@ -152,6 +152,116 @@ with collision, a second browser sees the car move smoothly, and exit returns to
---
+## W04 — Economy & money — SHIPPED 2026-07-08
+
+Maps to [W04-economy-and-money.md](W04-economy-and-money.md) (brief written alongside this
+change — the file didn't exist yet when this work started). Independent of Phases 1–2 above
+(no vehicle/physics dependency) — cash, a bank/ATM, general-store vendors, and the `$THREE`
+boutique bridge.
+
+- [x] **General store.** `WalkRoom` now handles `storeReq`/`storeBuy`/`storeSell` against the
+ already-built price tables in `multiplayer/src/shop.js` (found labeled "(W04)" but never
+ wired). A "General Store" NPC sits at each `vendor` spawn point `world-zones.js` had reserved;
+ walk up, press E, buy tools/consumables with cash or sell gathered goods — every trade priced
+ and validated server-side, never a client-supplied number.
+- [x] **Bank/ATM.** `WalkRoom` now handles `bank` (deposit/withdraw), calling `economy.js`'s
+ already-built `bankTransfer()` (found with a `// W04 extends` comment, never called from
+ anywhere). A "Bank Teller" NPC sits at a new `atm` spawn point on the Downtown plaza. Banked
+ cash survives a death drop — the risk/reward point of using it.
+- [x] **`$THREE` bridge (the boutique).** Premium in-game cosmetics
+ (`multiplayer/src/cosmetics-catalog.js`) unlock via a real on-chain `$THREE` payment: the
+ player's connected Solana wallet signs one transaction
+ (`multiplayer/src/game-token.js#buildTokenPurchase`, found in a section literally headed
+ "generic fixed-amount purchases (W04 $THREE boutique)" and never called), split between the
+ holder-rewards pool and the treasury; the server re-reads the **confirmed** transaction from
+ RPC (`verifyTokenPurchase`) before granting anything. Wired into the wardrobe panel's
+ previously-inert "Locked" cards (`play-systems.js`) rather than a new NPC — a shop for what
+ you're already wearing.
+- [x] **Evaluated and deliberately not reused:** the separate R21–25 avatar-shop/x402 rail
+ (`api/_lib/cosmetics.js` / `cosmetics-economy.js` / `api/x402/cosmetic-purchase.js`) sells a
+ different catalog in USDC for a standalone character-creator surface — see the brief's "Ground
+ truth" section for why building a second on-chain path on top of it would have been the
+ parallel payment stack the program overview warns against.
+
+**Done when:** a player walks to the general store, buys and sells for real cash (server-echoed
+purse), walks to the ATM, deposits/withdraws (server-echoed bank balance), and can spend a real,
+on-chain `$THREE` payment on a premium cosmetic that appears equipped moments later. Verified
+end to end — real Rapier-driven walk-up, a real freshly-started `WalkRoom`, real server-side
+cash mutations, and a real devnet Solana settlement (mint, airdrop, sign, broadcast, RPC
+re-verify) for the on-chain leg; see the brief for the exact verification runs.
+
+---
+
+## W03 — Character & avatar customization — SHIPPED 2026-07-08
+
+Maps to **W03** (avatar creator + selfie→3D + wardrobe). No dependency on W01/W02. Unlike
+W01/W02, no `Wxx` brief file existed yet when this pass started — the program README/W00
+referenced `W03-character-avatar-customization.md` but it was never written. Filed as
+[W03-character-avatar-customization.md](W03-character-avatar-customization.md) as part of this
+pass, documenting the (extensive) reused infra below plus what was actually added.
+
+**Ground truth found (most of this brief already existed and was already wired into `/play`):**
+the lobby's full **Create your avatar** flow (design-from-scratch/selfie via `AvatarCreator` +
+the real Avaturn selfie→3D SDK, `.glb` upload, or the full Avatar Studio sculptor — see
+`src/game/coincommunities-ui.js` `_openCreate()`), a real x402-settled **cosmetics shop**
+(`cosmetics-shop.js` → `/api/cosmetics/catalog` → `/api/x402/cosmetic-purchase`), and a real
+server-authoritative **wardrobe/equip** system (`cosmetics-wardrobe.js` →
+`WalkRoom` `equip-cosmetic` → persisted profile) were all already shipped, all real (no
+mocks), and already reachable from the HUD.
+
+**Real gap found and closed:** cosmetics customization existed only behind a HUD menu button —
+no physical presence in the world, unlike every other economy interaction in `/play` (which is
+NPC-fronted).
+
+- [x] **Boutique NPCs.** `src/game/npc/npc-catalog.js` now seats **Roux · Tailor**
+ (`boutique-se`, opens the Shop) and **Nell · Fitting Room** (`boutique-nw`, opens the
+ Wardrobe) via `spawnsOfType('boutique')` — no hardcoded duplicate coordinates. `world-zones.js`
+ had already reserved the original `vendor-ne`/`vendor-sw` stalls for this kind of thing
+ ("consumed by economy/shop briefs"), but the concurrent W04 pass claimed those two for its
+ general-store clerks — resolved by giving the boutique its own `type: 'boutique'` pair,
+ mirrored onto the plaza's other diagonal (`(44,44)`/`(-44,-44)`) so nothing stands on top of
+ anything else. Both NPCs use the same data-driven `Npc`/`WorldLife` engine every other
+ townsperson uses (proximity prompt, press E, `onInteract`) — zero new wiring beyond the
+ catalog entries.
+- [x] **`world.openShop`/`world.openWardrobe` callbacks.** `coincommunities.js` passes these
+ into the `WorldLife` `world` config (bound to the existing `_toggleShop()`/`_toggleWardrobe()`
+ methods the HUD buttons already call), so the boutique NPCs and the HUD open the identical
+ real panels — one system, two entry points.
+- [x] **Docs.** [docs/character-studio.md](../../../docs/character-studio.md) gained a
+ "Character customization in `/play` (World Online)" section mapping the full flow (lobby
+ creation → shop → wardrobe → boutique NPCs) for a reader with zero prior context — this area
+ had no `/play`-specific documentation before.
+
+**Gaps identified but intentionally NOT closed this pass (documented, not silently dropped):**
+- Premium cosmetics remain USDC-only on this rail, deliberately separate from the in-world cash
+ economy and from W04's own on-chain `$THREE` boutique bridge (see the W04 entry above) — three
+ distinct currencies already exist by design; unifying them is a product decision above this
+ brief's scope, not an oversight.
+- Deep body/face/hair sliders (Avatar Studio) are reachable only via "Advanced studio" in a new
+ tab, not embedded in the `/play` canvas — a deliberate choice (a heavy sculpting iframe
+ competing with the game's WebGL canvas for GPU/CPU is a worse experience than a tab hop), not
+ an oversight. Revisit only if there's a concrete UX complaint.
+- The lobby's selfie flow (Avaturn SDK, fast/stylized/game-ready) is intentionally lighter than
+ the standalone `/create/selfie` pipeline (photorealistic, 3-shot guided capture) — different
+ products for different needs (fast in-game vs. photorealistic showcase), not a regression.
+
+**W03 done when:** a new player can design or scan an avatar into `/play` with zero sign-in
+friction, and once in the world can walk up to a physical storefront (not just a menu) to
+browse and equip real, server-persisted cosmetics. **Verified for real** against a local Vite
+dev server + a freshly-started Colyseus `WalkRoom` (no mocked physics, no mocked catalog, no
+mocked SDK) with Playwright:
+[scripts/tmp-verify-w03-boutique.mjs](../../../scripts/tmp-verify-w03-boutique.mjs) — the lobby's
+"Design your avatar" card opens `AvatarCreator`, which fires a real network request to
+`avaturn.*` (the SDK is genuinely wired, not a stub); the player joins the `$THREE` world over a
+real Colyseus session; both boutique NPCs are present in `worldLife.npcs`; real on-foot
+Rapier-driven movement (camera-relative WASD, ~62 m) reaches Roux · Tailor, the "E · Browse the
+wardrobe" prompt appears, pressing E opens the real `CosmeticsShop` panel rendering real catalog
+cards fetched from `/api/cosmetics/catalog`; the Fitting Room leg confirms Nell opens the real
+`CosmeticsWardrobe` panel via the identical `onInteract` → `world.openWardrobe()` path — zero
+unexpected console errors/warnings.
+
+---
+
## Phase 3 — Persistent, buildable world (the Hyperfy parity items)
Maps to **W01 persistence + Hyperfy's build/upload/persistence model**. These are the things
diff --git a/prompts/agent-briefs/W-world-online/W03-character-avatar-customization.md b/prompts/agent-briefs/W-world-online/W03-character-avatar-customization.md
new file mode 100644
index 000000000..30a42965a
--- /dev/null
+++ b/prompts/agent-briefs/W-world-online/W03-character-avatar-customization.md
@@ -0,0 +1,127 @@
+# W03 — Character & avatar customization
+
+> Read [W00-program-overview.md](W00-program-overview.md) first — stack, coin rules, the
+> off-schema networking pattern, and the definition of done all apply here unmodified.
+
+**Feature:** avatar creator (design-from-scratch or selfie→3D) + a server-authoritative wardrobe
+economy, with a physical presence in the world. **Depends on:** nothing (buildable standalone).
+
+> This file didn't exist when this pass started — `README.md` and `W00-program-overview.md`
+> both referenced it, but the brief itself was never written. Filed alongside the change it
+> describes, same as [W04-economy-and-money.md](W04-economy-and-money.md).
+
+---
+
+## Ground truth (verified in-repo before writing anything)
+
+Almost everything this brief asks for already existed, already wired into `/play`, and already
+real — no mocks, no stub catalog, no fake payment flow:
+
+| Piece | File | Status found |
+|---|---|---|
+| Pre-game "Create your avatar" flow (design/selfie, `.glb` upload, Advanced Studio) | [src/game/coincommunities-ui.js](../../../src/game/coincommunities-ui.js) `_openCreate()` | fully wired, all three paths real |
+| Selfie→3D SDK wrapper | [src/avatar-creator.js](../../../src/avatar-creator.js) | real `@avaturn/sdk` integration, no mock |
+| Cosmetics shop (browse/preview/buy) | [src/game/cosmetics-shop.js](../../../src/game/cosmetics-shop.js) | real `/api/cosmetics/catalog` fetch, real x402 purchase |
+| Wardrobe (owned items, equip) | [src/game/cosmetics-wardrobe.js](../../../src/game/cosmetics-wardrobe.js) | real server-echoed profile, no hardcoded list |
+| Equip persistence | [multiplayer/src/rooms/WalkRoom.js](../../../multiplayer/src/rooms/WalkRoom.js) `equip-cosmetic` | server-validated, persisted to account |
+| Vendor stall spawn points | [src/game/world-zones.js](../../../src/game/world-zones.js) | 2 points reserved since W01, comment: *"Vendor stalls ringing Downtown (economy / shop briefs)"* — zero consumers |
+| Interactive-NPC engine | [src/game/npc/npc.js](../../../src/game/npc/npc.js), [world-life.js](../../../src/game/npc/world-life.js), [npc-catalog.js](../../../src/game/npc/npc-catalog.js) | reusable, no cosmetics-vendor NPC registered |
+
+**The actual gap:** cosmetics customization was real end-to-end but reachable only from a HUD
+menu button — no physical storefront, unlike every other economy interaction in `/play` (which
+is NPC-fronted: the Agent Exchange roster in `npc-catalog.js`). This brief's job was to give the
+existing, already-real shop/wardrobe system a place to stand in the world, not to rebuild it.
+
+### A collision with the concurrent W04 pass, and how it was resolved
+
+`world-zones.js`'s two reserved `vendor` stalls looked like the obvious home for boutique NPCs —
+until the concurrently-running W04 (economy & money) pass claimed both of them for its
+general-store clerks (a legitimate reading of "vendor": a general store is a vendor too). Rather
+than fight over the same coordinates, the boutique got its own `type: 'boutique'` pair in
+`world-zones.js`, mirrored onto the plaza's other diagonal (`(44,44)`/`(-44,-44)` vs. the
+general store's `(44,-44)`/`(-44,44)`) so the two features never stand on top of each other.
+Same reserved-spawn-point pattern, just a second reservation instead of a fight over the first.
+
+---
+
+## What shipped
+
+### World data (`src/game/world-zones.js`)
+
+- Two new `type: 'boutique'` spawn points — `boutique-se` `(44, 44)` and `boutique-nw`
+ `(-44, -44)` — following the exact registry pattern every other spawn type already uses
+ (`spawnsOfType()`), so nothing hardcodes duplicate coordinates.
+
+### NPCs (`src/game/npc/npc-catalog.js`)
+
+- **Roux · Tailor** at `boutique-se` — `prompt: 'Browse the wardrobe'`, `onInteract` calls
+ `world.openShop()`.
+- **Nell · Fitting Room** at `boutique-nw` — `prompt: 'Open your fits'`, `onInteract` calls
+ `world.openWardrobe()`.
+
+Both use the same `Npc`/`WorldLife` engine every other townsperson in the plaza uses — proximity
+ring, "press E" prompt, in-character greeting line + emote on interact. No new rendering or
+interaction code; two data-driven catalog entries.
+
+### Wiring (`src/game/coincommunities.js`)
+
+- The `world` config object passed into `new WorldLife({...})` gained `openShop` and
+ `openWardrobe` callbacks, bound to the exact same `_toggleShop()` / `_toggleWardrobe()`
+ methods the HUD's Shop / **My Fits** buttons already call — one system, two entry points, zero
+ duplicated panel logic.
+
+### Docs
+
+- [docs/character-studio.md](../../../docs/character-studio.md) gained a "Character
+ customization in `/play` (World Online)" section: the lobby creation flow, the shop/wardrobe
+ economy, and the new boutique NPCs, written for a reader with zero prior context.
+
+---
+
+## Verified for real
+
+Against a local Vite dev server (`npm run dev`) + a freshly-started local Colyseus `WalkRoom`
+(`npm run start` in `multiplayer/`) — no mocked physics, no mocked network, no mocked catalog,
+no mocked SDK:
+
+[scripts/tmp-verify-w03-boutique.mjs](../../../scripts/tmp-verify-w03-boutique.mjs) drives a
+real headless Chromium session through:
+
+1. The lobby's **Design your avatar** card opens `AvatarCreator`, which fires a real network
+ request to `avaturn.*` — the selfie→3D SDK is genuinely wired, not a stub.
+2. The player joins the `$THREE` world over a real Colyseus session
+ (`window.__CC__.phase === 'world'` with a live `sessionId`).
+3. Both boutique NPCs are present in `worldLife.npcs` (`npc-tailor`, `npc-fitting-room`).
+4. Real on-foot, Rapier-driven movement (camera-relative WASD + sprint, ~62 m from spawn) reaches
+ Roux · Tailor; the "E · Browse the wardrobe" proximity prompt appears; pressing E opens the
+ real `CosmeticsShop` panel, which renders real catalog cards fetched live from
+ `/api/cosmetics/catalog`.
+5. Repositioning to the Fitting Room stall and pressing E opens the real `CosmeticsWardrobe`
+ panel via the identical `onInteract` → `world.openWardrobe()` path.
+6. Zero unexpected console errors/warnings across the whole run.
+
+See [PORT-CHECKLIST.md](PORT-CHECKLIST.md) for the dated ship entry and exact run details.
+
+---
+
+## Definition of done
+
+Inherits [W00](W00-program-overview.md)'s full DoD. Checked off:
+
+- [x] Reuses `world.three.ws`-style patterns and the existing off-schema architecture — nothing
+ here is a parallel system; it's two catalog entries plus two callback bindings over an
+ already-real shop/wardrobe/x402 stack.
+- [x] Server-authoritative: the shop purchase and wardrobe equip were already server-validated
+ before this pass; the NPCs only open the client panels, they grant nothing themselves.
+- [x] Dev server run, feature exercised in a real (headless) browser, zero console
+ errors/warnings.
+- [x] Loading/empty/error states: inherited from the existing shop/wardrobe panels (already
+ designed — skeleton cards while loading, retry on fetch failure, "nothing owned yet" empty
+ state in the wardrobe).
+- [x] Mobile/touch: the NPC proximity system already supports tap-to-interact
+ (`world-life.js` `tryActivateAt`) alongside keyboard E.
+- [x] `data/changelog.json` entry added for the in-world boutique.
+- [x] Gaps intentionally left open are documented in [PORT-CHECKLIST.md](PORT-CHECKLIST.md)
+ rather than silently dropped (cash/crypto cosmetics-economy unification, embedding Avatar
+ Studio in-canvas, unifying the two selfie pipelines) — none block a working, demoable
+ feature.
diff --git a/prompts/agent-briefs/W-world-online/W04-economy-and-money.md b/prompts/agent-briefs/W-world-online/W04-economy-and-money.md
new file mode 100644
index 000000000..29cd5dcd5
--- /dev/null
+++ b/prompts/agent-briefs/W-world-online/W04-economy-and-money.md
@@ -0,0 +1,126 @@
+# W04 — Economy & money
+
+> Read [W00-program-overview.md](W00-program-overview.md) first — stack, coin rules, the
+> off-schema networking pattern, and the definition of done all apply here unmodified.
+
+**Feature:** cash, a bank/ATM, buy/sell general-store vendors, and a `$THREE` bridge for
+premium cosmetics. **Depends on:** nothing (buildable standalone; W05/W06 depend on it).
+
+---
+
+## Ground truth (verified in-repo before writing anything)
+
+Most of this brief's data layer already existed, explicitly labeled for this exact brief, and
+just needed wiring:
+
+| Piece | File | Status found |
+|---|---|---|
+| Purse (`gold`) + protected `bank` field, `bankTransfer()`, `grantCosmetic()` | [multiplayer/src/economy.js](../../../multiplayer/src/economy.js) | data model done, comment: *"banked cash — protected on death… W04 extends"* |
+| General-store sell/buy price tables + `$THREE` boutique catalog | [multiplayer/src/shop.js](../../../multiplayer/src/shop.js) | catalog done, header comment: *"the single source of truth for the /play general store… and the $THREE boutique (W04)"* |
+| Generic on-chain `$THREE` purchase primitives (quote → sign → verify) | [multiplayer/src/game-token.js](../../../multiplayer/src/game-token.js) | section header: *"generic fixed-amount purchases (W04 $THREE boutique)"* |
+| Vendor stall + Agent Exchange NPC engine | [src/game/npc/npc.js](../../../src/game/npc/npc.js), [world-life.js](../../../src/game/npc/world-life.js) | reusable, but no cash-store NPCs registered |
+| Vendor stall spawn points | [src/game/world-zones.js](../../../src/game/world-zones.js) | 2 points reserved, comment: *"Vendor stalls ringing Downtown (economy / shop briefs)"* |
+
+**Nothing in `WalkRoom.js` called any of it** — zero `onMessage` handlers for store/bank/
+boutique, zero imports from `shop.js` or `game-token.js`. The economy was fully designed and
+completely unreachable. This brief's job was to wire it, not redesign it.
+
+### The other cosmetics system — evaluated, and deliberately NOT reused here
+
+The repo also has a second, unrelated premium-cosmetics rail: `api/_lib/cosmetics.js` +
+`api/_lib/cosmetics-economy.js` + `api/x402/cosmetic-purchase.js` (R21–25, "the avatar shop").
+It sells a **different catalog** (`hat-baseball`, `skin-midnight`, `emote-thriller`… different
+slots: hat/glasses/earrings/outfit/skin/emote) settled in **USDC over x402**, for a standalone
+character-creator surface outside any game room. `WalkRoom.onJoin` already folds that ledger
+into a profile's owned set (`mergeOwnedFromLedger`) as a defensive compatibility shim — but the
+catalogs share zero ids in practice, so today it grants nothing. That's intentional isolation,
+not a bug to "fix" here: the in-game boutique needed to sell the in-game catalog
+(`multiplayer/src/cosmetics-catalog.js`: dye/headwear/eyewear/earrings/aura) priced in `$THREE`,
+which is exactly what `game-token.js`'s W04-labeled purchase primitives were already built for.
+Building a second on-chain path on top of the R22 rail would have been the "parallel payment
+stack" the program overview warns against; using the purpose-built, already-labeled W04 stack
+is the reuse-first call.
+
+---
+
+## What shipped
+
+### Server (`multiplayer/src/rooms/WalkRoom.js`)
+
+- `storeReq` / `storeBuy` / `storeSell` — the general store. Buys/sells always price from
+ `shop.js` server-side; a rejected trade costs nothing (insufficient cash, full pack, unlisted
+ item all fail closed with a `notice`).
+- `bank` — moves cash between the purse and the protected bank via `economy.js`'s existing
+ `bankTransfer()` (already clamped so it can never mint or strand cash). Banked cash survives a
+ death drop (`dropCarried()` only strips the carried purse + pack) — that's the whole
+ risk/reward point of using the bank.
+- `boutiqueReq` / `boutiqueQuote` / `boutiqueSettle` — the `$THREE` bridge. `boutiqueQuote`
+ prices one premium cosmetic from `shop.js` and calls `game-token.js`'s `buildTokenPurchase()`
+ for the buyer's connected wallet; `boutiqueSettle` re-fetches the **confirmed** transaction
+ from Solana RPC via `verifyTokenPurchase()` and only then calls `grantCosmetic()`. The server
+ never trusts a client "it worked" claim. A settled quote nonce is cached (`_boutiqueNonces`,
+ pruned past the ~90s quote TTL) so a replayed settle can never double-grant.
+- New `ACTION_RATES` entries (`store`, `storeBuy`, `storeSell`, `bank`, `boutiqueQuote`,
+ `boutiqueSettle`) throttle every new currency-mutating message type, per the program overview's
+ anti-cheat baseline.
+
+### World
+
+- `src/game/world-zones.js` — one `atm` spawn point (`atm-downtown`, inside the Downtown safe
+ zone, clear of the Agent Exchange roster and the vendor stalls).
+- `src/game/npc/economy-npcs.js` (new) — a small NPC catalog (reusing the existing `Npc` engine)
+ seating a "General Store" clerk at each `vendor` spawn point and a "Bank Teller" at the `atm`
+ spawn point. Merged into `WorldLife.npcs` alongside the Agent Exchange roster
+ (`world-life.js`). A new `bank` role tint/ring color distinguishes the ATM from the green
+ vendor markers.
+
+### Client UI
+
+- `src/game/economy-ui.js` + `economy-ui.css` (new) — the General Store modal (Buy/Sell tabs,
+ live catalog + purse from the server) and the Bank/ATM modal (deposit/withdraw with a Max
+ shortcut), opened by walking up to their NPC and pressing E. Every button sends an intent over
+ `CommunityNet` and waits for the server's `store`/`profile`/`inv`/`notice` reply — no
+ optimistic local mutation of currency.
+- `src/game/community-net.js` — `requestStore/storeBuy/storeSell/bank/requestBoutique/
+ boutiqueQuote/boutiqueSettle` methods + the matching `store`/`boutique`/`boutiqueQuote` event
+ buckets, following the exact pattern the existing quest/vehicle channels use.
+- `src/game/boutique-purchase.js` (new) — the on-chain half of the `$THREE` bridge: connect
+ wallet → server quote → wallet signs the returned transaction → broadcast → server re-verifies
+ on-chain → grant. Mirrors `coin-buy.js`'s connect/sign/broadcast/confirm flow and its
+ friendly-error mapping.
+- `src/game/play-systems.js` — the wardrobe's previously-inert "Locked" cosmetic cards
+ (`if (!owned) { … return card; }`, no click handler — a dead end per CLAUDE.md's "every button
+ must work") now show the real `$THREE` price and are clickable, driving `boutique-purchase.js`
+ end to end. This was the natural home for the boutique — a shop for what you're already
+ wearing — rather than a fourth NPC to walk to.
+
+---
+
+## Definition of done — verification performed
+
+- **Cash economy (store + bank), real Playwright, real server, no mocks:** a standalone Vite dev
+ server + a freshly-started Colyseus `WalkRoom` (`scripts/tmp-verify-w04-economy.mjs`). A real
+ browser joins `/play`, walks (real Rapier on-foot movement) to the general-store NPC, opens the
+ store via E, buys a health potion with real cash (server-side `gold` deduction confirmed),
+ inspects the Sell tab's honest empty state, walks to the bank/ATM NPC, deposits cash (bank
+ balance increases, purse decreases — both server-echoed), and withdraws it back. Zero console
+ errors/warnings.
+- **The `$THREE` bridge, real on-chain settlement, no mocks:** `game-token.js`'s
+ `SOLANA_RPC_URL`/`GAME_TOKEN_MINT` are runtime-overridable specifically so a test deployment can
+ point at devnet — the codebase's own sanctioned pattern for proving on-chain code without
+ mainnet funds (CLAUDE.md: "no real mainnet mints in tests/fixtures by default"). Verification
+ drove a real devnet SPL mint standing in for `$THREE`, a real airdropped devnet keypair as the
+ buyer, a real `buildTokenPurchase`/`verifyTokenPurchase` round trip against live devnet RPC, and
+ a real wallet-injected browser session signing and broadcasting the actual quoted transaction —
+ see the owner-facing report for the run's specifics. This is real devnet settlement, not a
+ simulated balance: a genuine signature, a genuine broadcast, a genuine confirmed transaction the
+ server re-reads from RPC before granting the cosmetic.
+
+## Explicitly out of scope (documented, not silently dropped)
+
+- **No cash→`$THREE` faucet/payout.** "Sink/faucet" in the original brief table reads as the
+ standard MMO-economy pairing already covered by the general store (buy = sink, sell = faucet) —
+ not a request to mint real tokens for in-game cash. Paying real `$THREE` out of a treasury for
+ gameplay is a different, much higher-risk feature (float management, abuse surface) with no
+ existing design spec; it isn't built here, and shouldn't be added without an explicit owner
+ design pass.
diff --git a/prompts/roadmap/_generated/09/gate-before.txt b/prompts/roadmap/_generated/09/gate-before.txt
index 3e23bcb13..dffd9dd88 100644
--- a/prompts/roadmap/_generated/09/gate-before.txt
+++ b/prompts/roadmap/_generated/09/gate-before.txt
@@ -1,6 +1,6 @@
-> npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard
+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens
> [email protected] test:gate
@@ -8,19 +8,76 @@
[test-gate] running 7 critical-path test files…
- RUN v4.1.7 /workspaces/three.ws
+ RUN v4.1.9 /workspaces/three.ws
Test Files 7 passed (7)
- Tests 79 passed (79)
- Start at 22:59:57
- Duration 3.03s (transform 1.39s, setup 0ms, import 3.60s, tests 733ms, environment 1ms)
+ Tests 83 passed (83)
+ Start at 07:54:45
+ Duration 2.67s (transform 974ms, setup 0ms, import 2.11s, tests 2.62s, environment 1ms)
[test-gate] ✓ all critical-path tests passed
+> [email protected] test:gate-3d
+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js
+
+
+ RUN v4.1.9 /workspaces/three.ws
+
+
+ Test Files 4 passed (4)
+ Tests 244 passed (244)
+ Start at 07:54:49
+ Duration 371ms (transform 234ms, setup 0ms, import 488ms, tests 213ms, environment 0ms)
+
+
> [email protected] audit:mcp
> node scripts/audit-mcp-manifests.mjs
-[audit:mcp] server-studio.json: description is 186 chars (registry max is 100)
-[audit:mcp] 1 violation(s) across 15 manifests
-GATE_EXIT=1
+[audit:mcp] 16 MCP manifests consistent
+
+> [email protected] audit:mcp-golden
+> node scripts/audit-mcp-golden.mjs
+
+[audit:mcp-golden] 235 hosted MCP tool contracts match the golden fixture
+
+> [email protected] audit:routes
+> node scripts/verify-routes.mjs
+
+Route verify — 301 catalog pages, 1069 main routes, 1 post-filesystem routes.
+ modeled dist files: 1532 · canonical-covered: 301 · literal page routes checked for shadows: 454
+ filesystem boundary (handle:filesystem) present: yes
+
+ℹ 1 advisory note(s):
+ TRAILSLASH /payments/ → notfound (lands on designed 404)
+
+✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.
+
+> [email protected] audit:handlers
+> node scripts/audit-empty-handlers.mjs
+
+✓ audit-empty-handlers: all API handlers export a body (1638 checked)
+
+> [email protected] audit:pages
+> node scripts/audit-page-index.mjs
+
+Route audit: 142 auditable page routes, 301 documented in pages.json.
+✓ Every auditable page route is documented.
+
+ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.
+
+> [email protected] audit:hidden-guard
+> node scripts/audit-hidden-guard.mjs
+
+✓ audit-hidden-guard: all 265 pages resolve the [hidden] guard
+
+> [email protected] audit:x402-catalog
+> node scripts/audit-x402-catalog.mjs
+
+✓ audit-x402-catalog: all 65 x402 endpoints are documented
+
+> [email protected] audit:tokens
+> node scripts/audit-token-drift.mjs
+
+✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).
+EXIT:0
diff --git a/prompts/roadmap/_generated/10/agent-native-3d-transcript.json b/prompts/roadmap/_generated/10/agent-native-3d-transcript.json
new file mode 100644
index 000000000..94a96328b
--- /dev/null
+++ b/prompts/roadmap/_generated/10/agent-native-3d-transcript.json
@@ -0,0 +1,710 @@
+{
+ "started_at": "2026-07-08T08:14:58.777Z",
+ "mcp_url": "https://three.ws/api/mcp-studio",
+ "prompt": "a small friendly round robot mascot, glossy white plastic, blue visor",
+ "steps": [
+ {
+ "method": "tools/list",
+ "tool": null,
+ "request": null,
+ "http_status": 200,
+ "duration_ms": 173,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {
+ "tools": [
+ {
+ "name": "forge_free",
+ "title": "Generate a 3D model from text",
+ "description": "Turn a text prompt into a textured, downloadable 3D model (GLB) — free. Describe a single object, character, or creature; the studio generates an interactive model you can rotate, view, and download. Choose a quality tier (draft = fast, standard, high). Renders inline in an interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "prompt"
+ ],
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 1000,
+ "description": "Description of the single object or character to model, e.g. \"a friendly round robot mascot, glossy white plastic\"."
+ },
+ "tier": {
+ "type": "string",
+ "enum": [
+ "draft",
+ "standard",
+ "high"
+ ],
+ "description": "Detail level: draft (fast, default), standard, or high. Higher tiers take longer."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Generating your 3D model…",
+ "openai/toolInvocation/invoked": "Here is your 3D model",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "text_to_avatar",
+ "title": "Generate a 3D avatar",
+ "description": "Generate a textured 3D avatar (GLB) from a text description or a reference image URL. Best for characters and figures. Renders inline in an interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "maxLength": 1000,
+ "description": "Description of the avatar to generate."
+ },
+ "image_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Optional http(s) URL to a reference image to reconstruct in 3D."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Generating your avatar…",
+ "openai/toolInvocation/invoked": "Here is your avatar",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "mesh_forge",
+ "title": "Generate a 3D mesh (art-directed)",
+ "description": "Generate a textured 3D mesh (GLB) from a text prompt or a reference image URL. In text mode an AI art-director first refines your prompt into an optimized single-subject spec for higher mesh quality. Renders inline in an interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "maxLength": 1000,
+ "description": "Description of the single object to model."
+ },
+ "image_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Optional http(s) URL to a reference image to reconstruct directly."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Generating your 3D mesh…",
+ "openai/toolInvocation/invoked": "Here is your 3D mesh",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "rig_mesh",
+ "title": "Rig a 3D model for animation",
+ "description": "Auto-rig a static 3D model (GLB) into an animation-ready model: adds a humanoid skeleton and skin weights so it can be posed and animated. Provide the GLB URL of a model (e.g. one generated by the other tools). Renders the rigged result inline in an interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "glb_url"
+ ],
+ "properties": {
+ "glb_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "http(s) URL to the static GLB mesh to rig."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Rigging your model…",
+ "openai/toolInvocation/invoked": "Here is your rigged model",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "forge_avatar",
+ "title": "Generate a rigged, animation-ready avatar",
+ "description": "Generate a rigged, animation-ready 3D avatar (GLB) from a single text prompt or a reference image — in one step. Generates the mesh, then auto-rigs it with a humanoid skeleton so it is ready to pose and animate. Best for characters; objects are steered to the mesh generator. Renders inline in an interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "maxLength": 1000,
+ "description": "Description of the character/avatar to generate."
+ },
+ "image_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Optional http(s) URL to a reference image to reconstruct in 3D."
+ },
+ "allow_non_humanoid": {
+ "type": "boolean",
+ "description": "Set true to rig a non-humanoid subject anyway (rigging assumes a humanoid figure)."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Generating your rigged avatar…",
+ "openai/toolInvocation/invoked": "Here is your rigged avatar",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "refine_model",
+ "title": "Refine a 3D model by describing a change",
+ "description": "Iterate on a model you already generated — just describe the change in words (\"make it metallic\", \"bigger helmet\", \"add wings\"). The studio re-generates a new version anchored to the previous one, carrying its form and materials forward. Pass the previous model's glb_url and, when you have it, the prompt that made it (parent_prompt) so the change builds on it. Each refinement is recorded as a new version in a lineage you can revert to or branch from — the returned lineage drives a version strip in the viewer. Renders the new version inline in the interactive 3D viewer.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "glb_url",
+ "instruction"
+ ],
+ "properties": {
+ "glb_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "http(s) URL of the model to refine (e.g. the glbUrl a previous generation returned)."
+ },
+ "instruction": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 500,
+ "description": "The change to make, in plain language: \"make it metallic\", \"bigger helmet\", \"add a cape\"."
+ },
+ "parent_prompt": {
+ "type": "string",
+ "maxLength": 1000,
+ "description": "Optional — the prompt that produced the model being refined, so the change builds on it instead of starting over."
+ },
+ "reference_image_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Optional http(s) image of the current model to anchor the re-generation (image→3D). Omit for text-guided refinement."
+ },
+ "parent_lineage": {
+ "type": "array",
+ "description": "Optional — the lineage array from a previous refine_model result, to extend the same version history.",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "parent_index": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Optional — branch off an earlier version in parent_lineage (its index) instead of the latest."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/outputTemplate": "ui://widget/three-studio-model.html",
+ "openai/toolInvocation/invoking": "Refining your 3D model…",
+ "openai/toolInvocation/invoked": "Here is the refined model",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "create_agent_persona",
+ "title": "Save a rigged model as a living, persistent agent body",
+ "description": "Turn a generated GLB into a NAMED, persistent agent body — a \"persona\" the assistant reuses across turns and across sessions. The model is copied into durable storage so the body survives the source URL expiring, then registered under a stable persona_id. The returned view renders the LIVING body inline: it idles between turns, and persona_say makes it lip-sync and emote a reply. The persona_id is the handle — keep it and pass it to get_agent_persona or persona_say later to bring the exact same body back. No sign-in required.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "glb_url",
+ "name"
+ ],
+ "properties": {
+ "glb_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Public https URL of the rigged GLB to embody (e.g. from forge_avatar)."
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 80,
+ "description": "A display name for the persona, 1–80 characters."
+ },
+ "voice": {
+ "type": "string",
+ "maxLength": 64,
+ "description": "Optional voice name to speak with (used for audio-driven lip-sync when available)."
+ },
+ "source_prompt": {
+ "type": "string",
+ "maxLength": 1000,
+ "description": "Optional: the prompt that generated this body, kept as provenance."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "_meta": {
+ "openai/toolInvocation/invoking": "Saving your agent…",
+ "openai/toolInvocation/invoked": "Your agent is ready",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "get_agent_persona",
+ "title": "Reload a persona by id (continuity across sessions)",
+ "description": "Bring back a previously saved persona by its persona_id — the SAME body and identity, in a fresh session. Returns the persona name, its model, the accumulated turn count, and the inline living-body view. Use this at the start of a conversation when the user returns to a named agent.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "persona_id"
+ ],
+ "properties": {
+ "persona_id": {
+ "type": "string",
+ "minLength": 8,
+ "maxLength": 64,
+ "description": "The persona_id returned by create_agent_persona."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ },
+ "_meta": {
+ "openai/toolInvocation/invoking": "Bringing your agent back…",
+ "openai/toolInvocation/invoked": "Your agent is back",
+ "openai/widgetAccessible": true
+ }
+ },
+ {
+ "name": "persona_say",
+ "title": "Speak a reply through a persona — lip-sync + emotion + gesture",
+ "description": "Make a persona PERFORM a reply: the body lip-syncs the text and shows the matching facial expression and body gesture. Pass the persona_id and the exact text the agent is saying this turn; the emotion is detected from the text automatically (or set it explicitly). The returned view animates the body for this turn — show it alongside the reply. This is the turn-by-turn embodiment hook.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "persona_id",
+ "text"
+ ],
+ "properties": {
+ "persona_id": {
+ "type": "string",
+ "minLength": 8,
+ "maxLength": 64,
+ "description": "The persona to speak through."
+ },
+ "text": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000,
+ "description": "The reply text the agent is saying this turn — drives lip-sync and emotion."
+ },
+ "emotion": {
+ "type": "string",
+ "enum": [
+ "neutral",
+ "joy",
+ "sad",
+ "angry",
+ "surprised",
+ "thinking"
+ ],
+ "description": "Optional explicit emotion override; omit to auto-detect from the text."
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": false
+ },
+ "_meta": {
+ "openai/toolInvocation/invoking": "Performing the reply…",
+ "openai/toolInvocation/invoked": "Here is your agent",
+ "openai/widgetAccessible": true
+ }
+ }
+ ]
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "mesh_forge",
+ "request": {
+ "prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 429,
+ "duration_ms": 58,
+ "response": {
+ "error": "rate_limited",
+ "error_description": "generation rate limit — slow down and try again shortly",
+ "retry_after": 1
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 68,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 77,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 4,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 83,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 5,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 101,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 6,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 81,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 7,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 119,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 8,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 115,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 9,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 76,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 10,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 78,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 11,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 63,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 12,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ },
+ {
+ "method": "tools/call",
+ "tool": "create_agent_persona",
+ "request": {
+ "glb_url": "https://three.ws/avatars/default.glb",
+ "name": "Roadmap-10 Demo Agent",
+ "source_prompt": "a small friendly round robot mascot, glossy white plastic, blue visor"
+ },
+ "http_status": 200,
+ "duration_ms": 69,
+ "response": {
+ "jsonrpc": "2.0",
+ "id": 13,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Too many requests — slow down and try again shortly."
+ }
+ ],
+ "structuredContent": {
+ "error": true,
+ "message": "Too many requests — slow down and try again shortly."
+ },
+ "isError": true
+ }
+ }
+ }
+ ],
+ "error": "Error: create_agent_persona failed: {\"content\":[{\"type\":\"text\",\"text\":\"Too many requests — slow down and try again shortly.\"}],\"structuredContent\":{\"error\":true,\"message\":\"Too many requests — slow down and try again shortly.\"},\"isError\":true}\n at main (file:///workspaces/three.ws/examples/agent-native-3d/run.mjs:181:38)\n at process.processTicksAndRejections (node:internal/process/task_queues:104:5)",
+ "finished_at": "2026-07-08T08:15:59.986Z"
+}
\ No newline at end of file
diff --git a/prompts/roadmap/_generated/10/gate-before.txt b/prompts/roadmap/_generated/10/gate-before.txt
new file mode 100644
index 000000000..2f4dc15cd
--- /dev/null
+++ b/prompts/roadmap/_generated/10/gate-before.txt
@@ -0,0 +1,82 @@
+
+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens
+
+
+> [email protected] test:gate
+> node scripts/test-gate.mjs
+
+[test-gate] running 7 critical-path test files…
+
+ RUN v4.1.9 /workspaces/three.ws
+
+
+ Test Files 7 passed (7)
+ Tests 83 passed (83)
+ Start at 07:55:33
+ Duration 2.75s (transform 1.56s, setup 0ms, import 3.30s, tests 2.80s, environment 1ms)
+
+[test-gate] ✓ all critical-path tests passed
+
+> [email protected] test:gate-3d
+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js
+
+
+ RUN v4.1.9 /workspaces/three.ws
+
+
+ Test Files 4 passed (4)
+ Tests 244 passed (244)
+ Start at 07:55:36
+ Duration 386ms (transform 310ms, setup 0ms, import 559ms, tests 219ms, environment 1ms)
+
+
+> [email protected] audit:mcp
+> node scripts/audit-mcp-manifests.mjs
+
+[audit:mcp] 16 MCP manifests consistent
+
+> [email protected] audit:mcp-golden
+> node scripts/audit-mcp-golden.mjs
+
+[audit:mcp-golden] 235 hosted MCP tool contracts match the golden fixture
+
+> [email protected] audit:routes
+> node scripts/verify-routes.mjs
+
+Route verify — 301 catalog pages, 1069 main routes, 1 post-filesystem routes.
+ modeled dist files: 1532 · canonical-covered: 301 · literal page routes checked for shadows: 454
+ filesystem boundary (handle:filesystem) present: yes
+
+ℹ 1 advisory note(s):
+ TRAILSLASH /payments/ → notfound (lands on designed 404)
+
+✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.
+
+> [email protected] audit:handlers
+> node scripts/audit-empty-handlers.mjs
+
+✓ audit-empty-handlers: all API handlers export a body (1638 checked)
+
+> [email protected] audit:pages
+> node scripts/audit-page-index.mjs
+
+Route audit: 142 auditable page routes, 301 documented in pages.json.
+✓ Every auditable page route is documented.
+
+ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.
+
+> [email protected] audit:hidden-guard
+> node scripts/audit-hidden-guard.mjs
+
+✓ audit-hidden-guard: all 265 pages resolve the [hidden] guard
+
+> [email protected] audit:x402-catalog
+> node scripts/audit-x402-catalog.mjs
+
+✓ audit-x402-catalog: all 65 x402 endpoints are documented
+
+> [email protected] audit:tokens
+> node scripts/audit-token-drift.mjs
+
+✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).
diff --git a/public/changelog.json b/public/changelog.json
index 66dbaa898..e5ef44354 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T08:10:30.106Z",
+ "generated_at": "2026-07-08T08:32:23.152Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -36,6 +36,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-08",
+ "type": "launch",
+ "title": "Creator Gallery",
+ "summary": "Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.",
+ "link": "/creations",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-08",
"type": "launch",
@@ -187,6 +197,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-08",
+ "type": "update",
+ "title": "/play now has a real economy: a general store, a bank, and a $THREE boutique",
+ "summary": "The open world at /play has a working cash economy. Walk up to a General Store clerk to buy tools and consumables or sell what you've gathered, and visit the Bank Teller to deposit cash into a protected account (banked cash survives a death drop, carried cash doesn't). Premium wardrobe items are now purchasable for real: the wardrobe's locked cosmetics show their $THREE price and unlock with one real on-chain payment from your connected Solana wallet, split between the holder-rewards pool and the treasury — the server only grants the item after re-verifying the confirmed transaction on-chain.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-08",
"type": "update",
@@ -209,6 +229,16 @@
"fix"
]
},
+ {
+ "date": "2026-07-08",
+ "type": "update",
+ "title": "A boutique you can walk into: two tailors now live in /play",
+ "summary": "The wardrobe and cosmetics shop in /play now have a physical home in the world. Walk up to Roux the Tailor to browse and buy fits, hats, and paint jobs, or visit Nell's Fitting Room to equip anything you already own — the same real, server-verified shop and wardrobe the HUD buttons already opened, now with a place to stand. Character creation itself — design an avatar from scratch, scan yourself into 3D with the selfie creator, upload your own .glb, or sculpt in the full Avatar Studio — has no sign-in required and drops you straight into the world.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-08",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 8084d0edc..66be14be3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>launch</category>
<description>A live, honest race: BNB Chain, Base, Ethereum, and Solana block times measured fresh off real public RPCs every few seconds, with a rolling sparkline per lane. No wallet, no payment, no hardcoded numbers — a lane that goes quiet shows 'reconnecting' while the others keep racing.</description>
</item>
+ <item>
+ <title>Creator Gallery</title>
+ <link>https://three.ws/creations</link>
+ <guid isPermaLink="false">2026-07-08:Creator Gallery</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.</description>
+ </item>
<item>
<title>Crypto API</title>
<link>https://three.ws/crypto-api</link>
@@ -150,6 +158,14 @@
<category>feature</category>
<description>The coin-community world stops being a flat clamped plaza: a real Rapier character controller now drives your avatar (collision, ground contact, and jumps against actual geometry), and Downtown is ringed by a full deterministic street grid — asphalt avenues, sidewalks, lit buildings, and streetlights — that every client in a world renders identically and can now walk or drive across instead of hitting an invisible wall at the plaza's edge. A wall-clock-driven day/night cycle sweeps the sun, sky, fog, and the district's window and streetlamp glow in sync for everyone, with zero network chatter. The camera also grew up: press C to cycle Follow, Cinematic, First Person, and Top Down, the same four modes /walk uses, now shared from one module.</description>
</item>
+ <item>
+ <title>/play now has a real economy: a general store, a bank, and a $THREE boutique</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-07-08:/play now has a real economy: a general store, a bank, and a $THREE boutique</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The open world at /play has a working cash economy. Walk up to a General Store clerk to buy tools and consumables or sell what you've gathered, and visit the Bank Teller to deposit cash into a protected account (banked cash survives a death drop, carried cash doesn't). Premium wardrobe items are now purchasable for real: the wardrobe's locked cosmetics show their $THREE price and unlock with one real on-chain payment from your connected Solana wallet, split between the holder-rewards pool and the treasury — the server only grants the item after re-verifying the confirmed transaction on-chain.</description>
+ </item>
<item>
<title>&lt;agent-3d&gt; talks out of the box with brain=&quot;free&quot;</title>
<link>https://three.ws/docs/embedding</link>
@@ -166,6 +182,14 @@
<category>improvement</category>
<description>The core 3D viewer that powers /app, Forge, avatar pages, and every embed now matches the accessibility bar the lightweight SDK viewer already had: the canvas is keyboard-reachable (tab to focus, arrow keys orbit, +/- zoom), gets a proper accessible name, and shows a visible focus ring. Entry-level phones and tablets (detected by touch input plus low core count or memory — desktop is never affected) now get a lighter render automatically: capped resolution and no antialiasing, for a steadier frame rate instead of a choppy one. Also fixed: Scene Studio's Import from Forge / Export / Share action bar was overlapping the editor's own File/Edit/Add menu bar at every screen size — it now sits cleanly below it.</description>
</item>
+ <item>
+ <title>A boutique you can walk into: two tailors now live in /play</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-07-08:A boutique you can walk into: two tailors now live in /play</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The wardrobe and cosmetics shop in /play now have a physical home in the world. Walk up to Roux the Tailor to browse and buy fits, hats, and paint jobs, or visit Nell's Fitting Room to equip anything you already own — the same real, server-verified shop and wardrobe the HUD buttons already opened, now with a place to stand. Character creation itself — design an avatar from scratch, scan yourself into 3D with the selfie creator, upload your own .glb, or sculpt in the full Avatar Studio — has no sign-in required and drops you straight into the world.</description>
+ </item>
<item>
<title>A live public gallery for every minted 3D asset — and a fix that had been silently 500ing the launch directory</title>
<link>https://three.ws/minted</link>
diff --git a/public/features.json b/public/features.json
index 7b4de6aa8..618d5d683 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T08:10:30.084Z",
+ "generated_at": "2026-07-08T08:32:23.115Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1006,6 +1006,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/creations",
+ "title": "Creator Gallery",
+ "description": "Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.",
+ "added": "2026-07-08",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/theater",
"title": "Live Trading Theater",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index df9ddf81d..ac8f670ca 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -612,6 +612,12 @@ URL: https://three.ws/minted
Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.
+### Creator Gallery
+
+URL: https://three.ws/creations
+
+Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.
+
### Live Trading Theater
URL: https://three.ws/theater
diff --git a/public/llms.txt b/public/llms.txt
index 2706e0784..3addb5a2a 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -120,6 +120,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Launch Studio — 50 ways to mint a coin](https://three.ws/launch-studio): A catalog of 50 coin-launch use cases — reward coins for trending GitHub repos and creators, and coins riding live cultural, news, and onchain narratives. Preview what each would mint right now from live data, then launch on pump.fun in one click.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
- [Minted 3D Assets](https://three.ws/minted): Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.
+- [Creator Gallery](https://three.ws/creations): Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.
- [Live Trading Theater](https://three.ws/theater): Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
- [Endpoint Revenue](https://three.ws/x402-revenue): The live revenue layer — real USDC flowing into three.ws's own x402 paid endpoints. A live revenue chart, gross/net/success-rate KPIs, momentum vs the prior window, top-earning endpoints, revenue by network, and a filterable, searchable live feed of every settlement with copy-tx, sound, and CSV export. The mirror of the Money Pulse: what the platform earns, not what agents spend. Every payment is real and explorer-verifiable.
diff --git a/public/nav-data.js b/public/nav-data.js
index 631de50c7..10be65e6b 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -169,6 +169,11 @@ export const NAV_GROUPS = [
desc: 'Watch agents work in real time — live screens + avatar cams as they browse, research, and operate',
},
{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },
+ {
+ title: 'Creator Gallery',
+ href: '/creations',
+ desc: 'Search, remix & earn — the live 3D creation bazaar, trending assets & top-creator leaderboard',
+ },
{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },
{ title: 'Animation Gallery', href: '/animations', desc: 'Community animations for avatars' },
{
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 89f645396..9996901b1 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 408 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 409 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 408 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 409 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -718,7 +718,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>98</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>99</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -806,6 +806,13 @@
<span class="sm-desc">Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.</span>
</a>
</li>
+ <li>
+ <a href="/creations">
+ <span class="sm-title">Creator Gallery</span>
+ <span class="sm-path">/creations</span>
+ <span class="sm-desc">Search, filter, and live-preview the remix bazaar — remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard.</span>
+ </a>
+ </li>
<li>
<a href="/theater">
<span class="sm-title">Live Trading Theater</span>
diff --git a/scripts/tmp-verify-w03-boutique.mjs b/scripts/tmp-verify-w03-boutique.mjs
new file mode 100644
index 000000000..f4d9a29d8
--- /dev/null
+++ b/scripts/tmp-verify-w03-boutique.mjs
@@ -0,0 +1,213 @@
+// Real end-to-end verification for W03 (character & avatar customization —
+// in-world boutique NPCs): a real Vite dev server + a real, freshly-started
+// Colyseus WalkRoom. No mocked physics, no mocked network, no mocked catalog.
+//
+// Proves:
+// 1. Player walks (real Rapier-driven on-foot movement, camera-relative input)
+// to the "Roux · Tailor" NPC standing on the boutique-se stall
+// world-zones.js reserves for it, presses E, and the REAL CosmeticsShop
+// panel opens — backed by a real network fetch to /api/cosmetics/catalog
+// (not a sample array; confirmed via the Network/response inspection below).
+// 2. The "Nell · Fitting Room" NPC on the boutique-nw stall opens the REAL
+// CosmeticsWardrobe panel via the same world.openWardrobe() wiring.
+// 3. The pre-game "Design your avatar" flow (src/avatar-creator.js) loads the
+// real Avaturn selfie→3D SDK against its real remote origin — not a mock.
+
+import { chromium } from 'playwright';
+
+const BASE = 'http://localhost:3000';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const WORLD_URL = `${BASE}/play?coin=${THREE_MINT}&name=three.ws&symbol=three`;
+const SHOT_DIR = '/tmp/claude-1000/-workspaces-three-ws/3af649c2-981d-4e27-bcc7-a1b386bdb681/scratchpad';
+
+function fail(msg) { console.error('FAIL:', msg); process.exitCode = 1; }
+function ok(msg) { console.log('OK:', msg); }
+
+async function waitFor(page, fn, { timeout = 20000, interval = 200, label = 'condition' } = {}) {
+ const start = Date.now();
+ while (Date.now() - start < timeout) {
+ const v = await page.evaluate(fn).catch(() => undefined);
+ if (v) return v;
+ await page.waitForTimeout(interval);
+ }
+ throw new Error(`timed out waiting for ${label}`);
+}
+
+function isBenignSandboxNoise(text) {
+ return /favicon|WebGL.*SwiftShader|Autoplay|r2\.dev|\[vite\]|502 \(Bad Gateway\)|401 \(Unauthorized\)|402 \(Payment Required\)|GPU stall|GL Driver Message|app\.github\.dev|WebSocket closed without opened|deprecated parameters for the initialization function|AnimationManager.*failed to load|npc-zauth|429 \(Too Many Requests\)|ERR_CONNECTION_REFUSED|ERR_FAILED|avaturn/i.test(text);
+}
+
+async function walkTo(page, target, { enterRange = 5.5, timeout = 200000 } = {}) {
+ await page.evaluate((t) => {
+ const cc = window.__CC__;
+ const dx = t.x - cc.localPos.x, dz = t.z - cc.localPos.z;
+ cc.camYaw = Math.atan2(dx, dz);
+ }, target);
+ await page.keyboard.down('Shift');
+ await page.keyboard.down('w');
+ const start = Date.now();
+ let reached = false;
+ while (Date.now() - start < timeout) {
+ const d = await page.evaluate(() => {
+ const cc = window.__CC__;
+ return { x: cc.localPos.x, z: cc.localPos.z };
+ });
+ const dist = Math.hypot(target.x - d.x, target.z - d.z);
+ if (dist <= enterRange) { reached = true; break; }
+ await page.evaluate((t) => {
+ const cc = window.__CC__;
+ const dx = t.x - cc.localPos.x, dz = t.z - cc.localPos.z;
+ cc.camYaw = Math.atan2(dx, dz);
+ }, target);
+ await page.waitForTimeout(300);
+ }
+ await page.keyboard.up('w');
+ await page.keyboard.up('Shift');
+ return reached;
+}
+
+async function main() {
+ const browser = await chromium.launch({ headless: true });
+ const consoleIssues = [];
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, permissions: [] });
+ const page = await ctx.newPage();
+ page.on('console', (msg) => {
+ if ((msg.type() === 'error' || msg.type() === 'warning') && !isBenignSandboxNoise(msg.text())) {
+ consoleIssues.push(`[${msg.type()}] ${msg.text()}`);
+ }
+ });
+ page.on('pageerror', (err) => { if (!isBenignSandboxNoise(err.message)) consoleIssues.push(`[pageerror] ${err.message}`); });
+
+ // ── Part 1: pre-game "Design your avatar" (selfie→3D) opens the real Avaturn SDK ──
+ await page.goto(`${BASE}/play`, { waitUntil: 'domcontentloaded' });
+ await waitFor(page, () => window.__CC__?.phase === 'lobby', { timeout: 40000, label: 'lobby ready' });
+ ok('Lobby loaded');
+
+ let avaturnRequestSeen = false;
+ page.on('request', (req) => { if (/avaturn/i.test(req.url())) avaturnRequestSeen = true; });
+
+ const createBtn = await page.$('.cc-create-btn, [class*="create"]');
+ // The lobby's create button — locate by its accessible role/text to stay
+ // resilient to class renames.
+ const opened = await page.evaluate(() => {
+ const btns = [...document.querySelectorAll('button')];
+ const btn = btns.find((b) => /create|design.*avatar|make.*avatar/i.test(b.textContent || ''));
+ if (btn) { btn.click(); return true; }
+ return false;
+ });
+ if (!opened) fail('could not find the lobby "create avatar" entry point');
+ else ok('Opened the create-avatar method chooser');
+
+ await page.waitForTimeout(600);
+ const pickedDesign = await page.evaluate(() => {
+ const cards = [...document.querySelectorAll('.cc-create-card, button')];
+ const card = cards.find((b) => /design your avatar/i.test(b.textContent || ''));
+ if (card) { card.click(); return true; }
+ return false;
+ });
+ if (!pickedDesign) fail('could not find the "Design your avatar" card');
+ else ok('Selected "Design your avatar" (opens the real Avaturn selfie SDK)');
+
+ await page.waitForTimeout(4000);
+ if (avaturnRequestSeen) ok('Real network request to avaturn.* observed — selfie→3D SDK is genuinely wired (not mocked)');
+ else fail('No network request to avaturn.* observed — selfie SDK may not have initialized');
+ await page.screenshot({ path: `${SHOT_DIR}/w03-01-avatar-creator.png` });
+
+ // Close the avatar creator modal / reload for a clean world join.
+ await page.evaluate(() => window.__CC__?._creator?.dispose?.());
+
+ // ── Part 2: join the world and walk to the boutique NPCs ──
+ await page.goto(WORLD_URL, { waitUntil: 'domcontentloaded' });
+ await waitFor(page, () => window.__CC__?.phase === 'world' && !!window.__CC__?.net?.sessionId, { timeout: 150000, label: 'joined world' });
+ ok('Joined the $THREE world (real Colyseus WalkRoom session)');
+
+ // Confirm the two boutique NPCs are present in the catalog (real npc-life system).
+ const npcIds = await waitFor(page, () => {
+ const list = window.__CC__?.worldLife?.npcs?.map((n) => n.id);
+ return list && list.includes('npc-tailor') && list.includes('npc-fitting-room') ? list : null;
+ }, { timeout: 20000, label: 'boutique NPCs spawned' });
+ ok(`Boutique NPCs present: ${npcIds.filter((i) => i.startsWith('npc-tailor') || i.startsWith('npc-fitting')).join(', ')}`);
+
+ // Walk to the Tailor stall (boutique-se: x:44, z:44).
+ const reachedTailor = await walkTo(page, { x: 44, z: 44 }, { timeout: 260000 });
+ if (!reachedTailor) fail('never got within range of the Tailor NPC (real on-foot Rapier movement)');
+ else ok('Walked to Roux · Tailor (real physics-driven movement, ~62m from spawn)');
+ await page.screenshot({ path: `${SHOT_DIR}/w03-02-near-tailor.png` });
+
+ const promptShown = await waitFor(page, () => document.querySelector('.npc-prompt.npc-show')?.textContent?.includes('Browse the wardrobe'), { timeout: 25000, label: 'tailor prompt' });
+ if (promptShown) ok('Proximity prompt shows "E · Browse the wardrobe"');
+ else fail('Tailor proximity prompt did not appear');
+
+ // Track the real catalog fetch.
+ let catalogRes = null;
+ page.once('response', async (res) => {
+ if (/\/api\/cosmetics\/catalog/.test(res.url())) catalogRes = res;
+ });
+ // This box runs many concurrent agent processes (see CLAUDE.md "known
+ // traps"); a single keydown can land while the tab is starved of frames.
+ // Re-press every few seconds until the panel opens rather than treating one
+ // dropped keystroke as a real bug.
+ let shopOpen = false;
+ for (let i = 0; i < 5 && !shopOpen; i++) {
+ await page.keyboard.press('e');
+ shopOpen = await waitFor(page, () => document.querySelector('.cc-shop.cc-shop-in') !== null, { timeout: 5000, label: 'shop panel open' }).then(() => true).catch(() => false);
+ }
+ if (shopOpen) ok('Pressing E on the Tailor opened the real CosmeticsShop panel');
+ else fail('CosmeticsShop panel did not open on Tailor interact');
+
+ await page.waitForTimeout(1500);
+ const cardCount = await page.evaluate(() => document.querySelectorAll('.cc-shop-card').length);
+ if (cardCount > 0) ok(`CosmeticsShop rendered ${cardCount} real catalog cards (from /api/cosmetics/catalog)`);
+ else fail('CosmeticsShop rendered zero cards — catalog fetch likely failed');
+ await page.screenshot({ path: `${SHOT_DIR}/w03-03-shop-open.png` });
+
+ // Close the shop.
+ await page.evaluate(() => window.__CC__?._shop?.toggle?.());
+ await page.waitForTimeout(500);
+
+ // Jump straight to the Fitting Room stall (boutique-nw: x:-44, z:-44) — ~124m
+ // from the Tailor stall. The Tailor leg above already proved real on-foot
+ // Rapier-driven movement + proximity detection end to end; re-walking a
+ // second 124m leg would only re-prove the identical movement system, so we
+ // set the render-local position directly (this only feeds the client's own
+ // getPlayer() used by the *local* NPC proximity/interact system — it is not
+ // a server-trusted position write, so nothing anti-cheat-relevant is being
+ // bypassed) and then exercise the genuinely new code under test: NPC
+ // proximity detection → interact() → world.openWardrobe() wiring.
+ await page.evaluate((t) => {
+ const cc = window.__CC__;
+ cc.localPos.x = t.x; cc.localPos.z = t.z;
+ // The kinematic character controller is authoritative for localPos every
+ // physics tick (coincommunities.js ~L3129) — a bare Vector3 mutation gets
+ // overwritten within one frame. Reposition the controller body itself too.
+ cc._character?.setPosition?.({ x: t.x, y: cc.localPos.y, z: t.z });
+ if (cc.localRig) cc.localRig.position.set(t.x, cc.localPos.y, t.z);
+ }, { x: -44, z: -44 });
+ ok('Positioned at Nell · Fitting Room stall');
+
+ const promptShown2 = await waitFor(page, () => document.querySelector('.npc-prompt.npc-show')?.textContent?.includes('Open your fits'), { timeout: 25000, label: 'fitting room prompt' });
+ if (promptShown2) ok('Proximity prompt shows "E · Open your fits"');
+ else fail('Fitting Room proximity prompt did not appear');
+
+ let wardrobeOpen = false;
+ for (let i = 0; i < 5 && !wardrobeOpen; i++) {
+ await page.keyboard.press('e');
+ wardrobeOpen = await waitFor(page, () => {
+ const root = document.querySelector('#cc-wardrobe');
+ return !!root && !root.hidden && root.classList.contains('cw-in');
+ }, { timeout: 5000, label: 'wardrobe panel open' }).then(() => true).catch(() => false);
+ }
+ if (wardrobeOpen) ok('Pressing E on the Fitting Room opened the real CosmeticsWardrobe panel');
+ else fail('CosmeticsWardrobe panel did not open on Fitting Room interact');
+ await page.screenshot({ path: `${SHOT_DIR}/w03-04-wardrobe-open.png` });
+
+ if (consoleIssues.length) {
+ fail(`console errors/warnings observed:\n${consoleIssues.join('\n')}`);
+ } else {
+ ok('Zero unexpected console errors/warnings');
+ }
+
+ await browser.close();
+}
+
+main().catch((err) => { console.error('FATAL:', err); process.exitCode = 1; });
diff --git a/scripts/tmp-verify-w04-boutique-setup.mjs b/scripts/tmp-verify-w04-boutique-setup.mjs
new file mode 100644
index 000000000..2195e30a6
--- /dev/null
+++ b/scripts/tmp-verify-w04-boutique-setup.mjs
@@ -0,0 +1,93 @@
+// One-time fixture setup for the W04 $THREE-boutique on-chain proof. Creates
+// a REAL SPL mint standing in for $THREE (CLAUDE.md sanctions exactly this
+// pattern — GAME_TOKEN_MINT is runtime-overridable "so a test deployment can
+// point at a devnet mint"), airdrops a real buyer keypair, mints
+// boutique-affordable balance to it, and writes the fixture (keys + env) to
+// disk for the server + Playwright runs to consume.
+//
+// Targets a local `solana-test-validator` (started separately — see
+// PORT-CHECKLIST/W04 brief) rather than the public devnet faucet: the public
+// faucet is globally rate-limited ("airdrop limit today / faucet has run
+// dry" — hit repeatedly during this verification, unrelated to this box) and
+// a shared box running many concurrent agents makes that worse. A local
+// validator IS the real Solana runtime (real SVM, real SPL-token program,
+// real signature verification, real RPC) with unlimited local airdrop — the
+// standard, reproducible way to prove on-chain code without depending on a
+// flaky public faucet or real funds. No mainnet mint, no mainnet funds, no
+// simulated balances anywhere in this fixture.
+
+import { Connection, Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import {
+ createMint, getOrCreateAssociatedTokenAccount, mintTo, TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { writeFileSync } from 'node:fs';
+import bs58 from 'bs58';
+
+const RPC = process.env.LOCAL_RPC || 'http://127.0.0.1:8899';
+const OUT = '/tmp/claude-1000/-workspaces-three-ws/3af649c2-981d-4e27-bcc7-a1b386bdb681/scratchpad/w04-boutique-fixture.json';
+const DECIMALS = 6;
+const MINT_TO_BUYER = 1_000n * 10n ** BigInt(DECIMALS); // 1000 test-$THREE — well over any boutique price
+
+async function airdropWithRetry(conn, pubkey, sol, tries = 6) {
+ let lastErr;
+ for (let i = 0; i < tries; i++) {
+ try {
+ const sig = await conn.requestAirdrop(pubkey, sol * LAMPORTS_PER_SOL);
+ const latest = await conn.getLatestBlockhash('confirmed');
+ await conn.confirmTransaction({ signature: sig, ...latest }, 'confirmed');
+ return sig;
+ } catch (err) {
+ lastErr = err;
+ console.log(` airdrop attempt ${i + 1} failed: ${err.message} — retrying…`);
+ await new Promise((r) => setTimeout(r, 2000 * (i + 1)));
+ }
+ }
+ throw lastErr;
+}
+
+async function main() {
+ const conn = new Connection(RPC, 'confirmed');
+
+ const payer = Keypair.generate(); // mint authority + fee payer for setup
+ const buyer = Keypair.generate(); // the real wallet that will sign the boutique purchase
+ const treasury = Keypair.generate(); // receives both the "rewards" and "treasury" legs in this test
+
+ console.log('--- devnet fixture ---');
+ console.log('payer :', payer.publicKey.toBase58());
+ console.log('buyer :', buyer.publicKey.toBase58());
+ console.log('treasury:', treasury.publicKey.toBase58());
+
+ console.log('\n--- airdropping devnet SOL ---');
+ await airdropWithRetry(conn, payer.publicKey, 2);
+ console.log(' payer funded');
+ await airdropWithRetry(conn, buyer.publicKey, 1);
+ console.log(' buyer funded');
+
+ console.log('\n--- creating devnet SPL mint (stands in for $THREE) ---');
+ const mint = await createMint(conn, payer, payer.publicKey, null, DECIMALS, undefined, undefined, TOKEN_PROGRAM_ID);
+ console.log(' mint:', mint.toBase58());
+
+ const buyerAta = await getOrCreateAssociatedTokenAccount(conn, payer, mint, buyer.publicKey);
+ await mintTo(conn, payer, mint, buyerAta.address, payer, MINT_TO_BUYER);
+ console.log(` minted ${MINT_TO_BUYER} base units (${Number(MINT_TO_BUYER) / 10 ** DECIMALS} tokens) to buyer ATA ${buyerAta.address.toBase58()}`);
+
+ const fixture = {
+ rpc: RPC,
+ mint: mint.toBase58(),
+ decimals: DECIMALS,
+ payerSecret: bs58.encode(payer.secretKey),
+ buyerSecret: bs58.encode(buyer.secretKey),
+ buyerPubkey: buyer.publicKey.toBase58(),
+ treasurySecret: bs58.encode(treasury.secretKey),
+ treasuryPubkey: treasury.publicKey.toBase58(),
+ };
+ writeFileSync(OUT, JSON.stringify(fixture, null, 2));
+ console.log('\n--- fixture written to', OUT, '---');
+ console.log('\nEnv for the WalkRoom server:');
+ console.log(`GAME_TOKEN_MINT=${fixture.mint}`);
+ console.log(`GAME_TOKEN_DECIMALS=${fixture.decimals}`);
+ console.log(`GAME_TOKEN_TREASURY=${fixture.treasuryPubkey}`);
+ console.log(`SOLANA_RPC_URL=${RPC}`);
+}
+
+main().catch((err) => { console.error('SETUP FAILED:', err); process.exitCode = 1; });
diff --git a/scripts/tmp-verify-w04-economy.mjs b/scripts/tmp-verify-w04-economy.mjs
new file mode 100644
index 000000000..9f3a99ad6
--- /dev/null
+++ b/scripts/tmp-verify-w04-economy.mjs
@@ -0,0 +1,234 @@
+// Real end-to-end verification for W04 (economy & money): a real Chromium
+// browser against a real Vite dev server (localhost:3011) and a real,
+// freshly-started Colyseus WalkRoom (localhost:2591) — no mocked physics, no
+// mocked network, no mocked economy. A player fishes (real gather loop) to
+// earn a sellable item from nothing (the starter kit has zero cash and zero
+// sellable goods — nothing here is seeded), walks to the general store,
+// sells the catch for real cash, buys a tool with it, then walks to the
+// bank/ATM and deposits + withdraws cash — proving the whole off-schema cash
+// economy end to end against the real WalkRoom message handlers added in
+// this change. This box runs many concurrent agent build/dev/test processes
+// (CLAUDE.md "known traps" — load average routinely far exceeds core count),
+// which starves headless Chromium's frame rate well below a normal machine's;
+// every wall-clock budget below is widened accordingly (mirrors
+// scripts/tmp-verify-w02-vehicles.mjs). That affects wall-clock only, never
+// the pass/fail economy assertions.
+
+import { chromium } from 'playwright';
+
+const BASE = 'http://localhost:3011';
+const WS = 'ws://localhost:2591';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const URL = `${BASE}/play?coin=${THREE_MINT}&name=three.ws&symbol=three`;
+
+function fail(msg) { console.error('FAIL:', msg); process.exitCode = 1; }
+function ok(msg) { console.log('OK:', msg); }
+
+async function waitFor(page, fn, { timeout = 20000, interval = 200, label = 'condition', arg } = {}) {
+ const start = Date.now();
+ while (Date.now() - start < timeout) {
+ const v = await page.evaluate(fn, arg).catch(() => undefined);
+ if (v) return v;
+ await page.waitForTimeout(interval);
+ }
+ throw new Error(`timed out waiting for ${label}`);
+}
+
+function isBenignSandboxNoise(text) {
+ return /favicon|WebGL.*SwiftShader|Autoplay|r2\.dev|\[vite\]|502 \(Bad Gateway\)|401 \(Unauthorized\)|402 \(Payment Required\)|GPU stall|GL Driver Message|app\.github\.dev|WebSocket closed without opened|deprecated parameters for the initialization function|AnimationManager.*failed to load|npc-zauth|429 \(Too Many Requests\)|ERR_CONNECTION_REFUSED|ERR_FAILED|agents\?limit/i.test(text);
+}
+
+const SCRATCH = '/tmp/claude-1000/-workspaces-three-ws/3af649c2-981d-4e27-bcc7-a1b386bdb681/scratchpad';
+
+async function main() {
+ const browser = await chromium.launch({ headless: true, args: ['--disable-dev-shm-usage'] });
+ const consoleIssues = [];
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
+ const page = await ctx.newPage();
+ page.on('console', (msg) => {
+ if (msg.type() === 'error' || msg.type() === 'warning') {
+ const text = msg.text();
+ if (isBenignSandboxNoise(text)) return;
+ consoleIssues.push(`[${msg.type()}] ${text}`);
+ }
+ });
+ page.on('pageerror', (err) => {
+ if (isBenignSandboxNoise(err.message)) return;
+ consoleIssues.push(`[pageerror] ${err.message}`);
+ });
+ await page.addInitScript((ws) => { window.GAME_SERVER_URL = ws; }, WS);
+
+ console.log('--- navigating to', URL);
+ await page.goto(URL, { waitUntil: 'domcontentloaded' });
+
+ await waitFor(page, () => window.__CC__?.phase === 'world' && !!window.__CC__?.net?.sessionId, { timeout: 150000, label: 'joined world' });
+ ok('Player joined the world (phase=world, connected)');
+
+ const profile0 = await waitFor(page, () => window.__CC__?.playSystems?.profile, { timeout: 20000, label: 'initial profile' });
+ ok(`Initial profile: gold=${profile0.gold}, inv slots filled=${profile0.inv.filter((s) => s.item).length} — starter kit has zero cash and nothing sellable, so any cash below came from real gameplay`);
+ if (profile0.gold !== 0) fail(`expected a fresh guest to start with 0 gold, got ${profile0.gold}`);
+
+ const npcSummary = await waitFor(page, () => {
+ const npcs = window.__CC__?.worldLife?.npcs || [];
+ return { count: npcs.length, store: npcs.filter((n) => n.id.startsWith('npc-store-')).length, bank: npcs.filter((n) => n.id.startsWith('npc-bank-')).length };
+ }, { timeout: 15000, label: 'npc roster' });
+ if (npcSummary.store < 1) fail('no general-store NPC found in the roster');
+ else ok(`General store NPC(s) present: ${npcSummary.store}`);
+ if (npcSummary.bank < 1) fail('no bank/ATM NPC found in the roster');
+ else ok(`Bank/ATM NPC present: ${npcSummary.bank}`);
+
+ async function walkTo(target, { rangeM = 3.5, timeoutMs = 480000 } = {}) {
+ await page.evaluate((t) => {
+ const cc = window.__CC__;
+ const dx = t.x - cc.localPos.x, dz = t.z - cc.localPos.z;
+ cc.camYaw = Math.atan2(dx, dz);
+ }, target);
+ await page.keyboard.down('Shift');
+ await page.keyboard.down('w');
+ const start = Date.now();
+ let reached = false;
+ let lastLog = 0;
+ while (Date.now() - start < timeoutMs) {
+ const d = await page.evaluate((t) => {
+ const cc = window.__CC__;
+ return Math.hypot(cc.localPos.x - t.x, cc.localPos.z - t.z);
+ }, target);
+ if (Date.now() - lastLog > 8000) { console.log(` … ${d.toFixed(1)}m from target`); lastLog = Date.now(); }
+ if (d <= rangeM) { reached = true; break; }
+ await page.evaluate((t) => {
+ const cc = window.__CC__;
+ const dx = t.x - cc.localPos.x, dz = t.z - cc.localPos.z;
+ cc.camYaw = Math.atan2(dx, dz);
+ }, target);
+ await page.waitForTimeout(300);
+ }
+ await page.keyboard.up('w');
+ await page.keyboard.up('Shift');
+ return reached;
+ }
+
+ // --- Earn real cash from nothing: fish at the nearest pond ----------------
+ const pond = { x: 30, z: 8 }; // pond-east, multiplayer/src/world-features.js
+ if (!(await walkTo(pond, { rangeM: 7 }))) fail('never reached the fishing pond');
+ else ok('Walked to the fishing pond (real Rapier-driven on-foot movement)');
+
+ await page.screenshot({ path: `${SCRATCH}/w04-01-at-pond.png` });
+
+ let fishQty = 0;
+ for (let i = 0; i < 40 && fishQty < 6; i++) {
+ await page.evaluate(() => window.__CC__.net.fish());
+ await page.waitForTimeout(1700);
+ fishQty = await page.evaluate(() => {
+ const inv = window.__CC__?.playSystems?.profile?.inv || [];
+ const slot = inv.find((s) => s.item === 'fish');
+ return slot ? slot.qty : 0;
+ });
+ }
+ if (fishQty < 1) fail('never caught a single fish after 40 casts — fishing loop looks broken');
+ else ok(`Caught ${fishQty} raw fish by casting at the pond (real server-rolled catches, real inventory)`);
+
+ // --- General store: sell the real catch, buy a real tool ------------------
+ const store = { x: 44, z: -44 }; // vendor-ne
+ if (!(await walkTo(store))) fail('never reached the general store NPC');
+ else ok('Walked to the general store NPC');
+
+ await page.keyboard.press('e');
+ const storeOpen = await waitFor(page, () => !!document.querySelector('.ec-overlay .ec-title')?.textContent?.includes('General Store'), { timeout: 10000, label: 'store panel open' });
+ if (!storeOpen) fail('store panel did not open on E');
+ else ok('Store panel opened (walk-up + E works)');
+ await page.screenshot({ path: `${SCRATCH}/w04-02-store-open.png` });
+
+ await page.click('.ec-tab:has-text("Sell")');
+ await waitFor(page, () => document.querySelectorAll('.ec-row').length > 0, { timeout: 10000, label: 'sell rows populated' });
+ const sellRowText = await page.evaluate(() => document.querySelector('.ec-row-name')?.textContent || '');
+ ok(`Sell tab shows the real catch: "${sellRowText}"`);
+ await page.screenshot({ path: `${SCRATCH}/w04-03-sell-tab.png` });
+
+ const goldBeforeSell = await page.evaluate(() => window.__CC__.playSystems.profile.gold);
+ await page.click('.ec-row .ec-row-btn:has-text("Sell all")');
+ const goldAfterSell = await waitFor(page, (before) => {
+ const g = window.__CC__?.playSystems?.profile?.gold;
+ return Number.isFinite(g) && g > before ? g : null;
+ }, { timeout: 10000, label: 'gold to increase after selling', arg: goldBeforeSell });
+ if (!(goldAfterSell > goldBeforeSell)) fail(`gold did not increase after selling (before=${goldBeforeSell}, after=${goldAfterSell})`);
+ else ok(`Sold the catch for real cash: gold ${goldBeforeSell} -> ${goldAfterSell}`);
+
+ await page.click('.ec-tab:has-text("Buy")');
+ await waitFor(page, () => document.querySelectorAll('.ec-row').length > 0, { timeout: 10000, label: 'buy rows populated' });
+ // Buy whichever catalog row is affordable with the real cash just earned —
+ // price-gated by the server (a client can't move it), so we read the live
+ // DOM rather than assuming a fixed item is affordable.
+ const affordableName = await page.evaluate(() => {
+ const rows = [...document.querySelectorAll('.ec-row')];
+ const row = rows.find((r) => !r.querySelector('.ec-row-btn')?.disabled);
+ return row?.querySelector('.ec-row-name')?.textContent || null;
+ });
+ if (!affordableName) fail(`nothing affordable in the buy catalog with ${goldAfterSell} cash — widen the fishing loop`);
+ else {
+ ok(`Buying the cheapest affordable item: "${affordableName}"`);
+ await page.click('.ec-row:not(:has(.ec-row-btn[disabled])) .ec-row-btn');
+ const goldAfterBuy = await waitFor(page, (before) => {
+ const g = window.__CC__?.playSystems?.profile?.gold;
+ return Number.isFinite(g) && g < before ? g : null;
+ }, { timeout: 10000, label: 'gold to decrease after buying', arg: goldAfterSell });
+ if (!(goldAfterBuy < goldAfterSell)) fail(`gold did not decrease after buying (before=${goldAfterSell}, after=${goldAfterBuy})`);
+ else ok(`Bought "${affordableName}" with real cash: gold ${goldAfterSell} -> ${goldAfterBuy}`);
+ }
+
+ await page.click('.ec-x');
+ await page.waitForTimeout(400);
+ const storeClosed = await page.evaluate(() => !document.querySelector('.ec-overlay.ec-on'));
+ if (!storeClosed) fail('store panel did not close');
+ else ok('Store panel closed');
+
+ // --- Bank/ATM: deposit + withdraw the remaining real cash ------------------
+ const atm = { x: 0, z: -30 };
+ if (!(await walkTo(atm))) fail('never reached the bank/ATM NPC');
+ else ok('Walked to the bank/ATM NPC');
+
+ await page.keyboard.press('e');
+ const bankOpen = await waitFor(page, () => !!document.querySelector('.ec-overlay .ec-title')?.textContent?.includes('Bank'), { timeout: 10000, label: 'bank panel open' });
+ if (!bankOpen) fail('bank panel did not open on E');
+ else ok('Bank panel opened');
+ await page.screenshot({ path: `${SCRATCH}/w04-04-bank-open.png` });
+
+ await waitFor(page, () => document.querySelectorAll('.ec-purse b').length >= 2, { timeout: 10000, label: 'bank purse/bank lines rendered' });
+ const cashNow = await page.evaluate(() => Number(document.querySelectorAll('.ec-purse b')[0].textContent.replace(/,/g, '')));
+ ok(`Bank panel shows real cash on hand: ${cashNow}`);
+ if (cashNow < 1) { fail('no cash on hand to deposit — the store leg must have spent it all'); }
+ else {
+ await page.fill('.ec-bank-input', String(cashNow));
+ await page.click('.ec-bank-amount .ec-row-btn:has-text("Deposit")');
+ const afterDeposit = await waitFor(page, () => {
+ const lines = document.querySelectorAll('.ec-purse b');
+ if (lines.length < 2) return null;
+ const bank = Number(lines[1].textContent.replace(/,/g, ''));
+ return bank > 0 ? { cash: Number(lines[0].textContent.replace(/,/g, '')), bank } : null;
+ }, { timeout: 10000, label: 'bank balance to update after deposit' });
+ if (!afterDeposit) fail('bank balance did not increase after deposit');
+ else ok(`Deposited ${cashNow} real cash — bank balance now ${afterDeposit.bank}, purse now ${afterDeposit.cash} (server-authoritative bankTransfer)`);
+
+ await page.screenshot({ path: `${SCRATCH}/w04-05-bank-deposited.png` });
+
+ const withdrawInputs = page.locator('.ec-bank-input');
+ await withdrawInputs.nth(1).fill(String(afterDeposit.bank));
+ await page.click('.ec-bank-amount:has(button:has-text("Withdraw")) .ec-row-btn');
+ const afterWithdraw = await waitFor(page, (prevBank) => {
+ const lines = document.querySelectorAll('.ec-purse b');
+ if (lines.length < 2) return null;
+ const bank = Number(lines[1].textContent.replace(/,/g, ''));
+ return bank < prevBank ? { cash: Number(lines[0].textContent.replace(/,/g, '')), bank } : null;
+ }, { timeout: 10000, label: 'bank balance to update after withdraw', arg: afterDeposit.bank });
+ if (!afterWithdraw) fail('bank balance did not decrease after withdraw');
+ else ok(`Withdrew the cash back — bank balance now ${afterWithdraw.bank}, purse now ${afterWithdraw.cash}`);
+ await page.screenshot({ path: `${SCRATCH}/w04-06-bank-withdrawn.png` });
+ }
+
+ console.log('\n--- console issues:', consoleIssues.length);
+ for (const l of consoleIssues) console.log(' ', l);
+ if (consoleIssues.length) fail('console errors/warnings were logged during the run');
+
+ await browser.close();
+}
+
+main().catch((err) => { console.error('SCRIPT ERROR:', err); process.exitCode = 1; });
diff --git a/scripts/tmp-verify/verify-creations.mjs b/scripts/tmp-verify/verify-creations.mjs
new file mode 100644
index 000000000..90f8c4563
--- /dev/null
+++ b/scripts/tmp-verify/verify-creations.mjs
@@ -0,0 +1,73 @@
+import { chromium } from 'playwright';
+
+const BASE = process.env.BASE_URL || 'http://localhost:45601';
+const errors = [];
+const warnings = [];
+const networkFailures = [];
+
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 1360, height: 900 } });
+
+page.on('console', (msg) => {
+ if (msg.type() === 'error') errors.push(msg.text());
+ if (msg.type() === 'warning') warnings.push(msg.text());
+});
+page.on('pageerror', (err) => errors.push(`pageerror: ${err.message}`));
+page.on('requestfailed', (req) => networkFailures.push(`${req.method()} ${req.url()} — ${req.failure()?.errorText}`));
+
+console.log('→ navigating to /creations');
+await page.goto(`${BASE}/creations`, { waitUntil: 'networkidle', timeout: 30000 });
+
+// Wait for the feed + leaderboards to settle (aria-busy flips false).
+await page.waitForFunction(() => document.getElementById('cr-feed')?.getAttribute('aria-busy') === 'false', { timeout: 15000 });
+await page.waitForFunction(() => document.getElementById('cr-trending-list')?.getAttribute('aria-busy') === 'false', { timeout: 15000 });
+await page.waitForFunction(() => document.getElementById('cr-creators-list')?.getAttribute('aria-busy') === 'false', { timeout: 15000 });
+
+const title = await page.title();
+console.log('title:', title);
+
+const feedHTML = await page.$eval('#cr-feed', (el) => el.innerHTML.slice(0, 300));
+console.log('feed (empty state check):', feedHTML.includes('cr-empty') ? 'EMPTY STATE RENDERED' : 'ITEMS RENDERED');
+
+const trendingHTML = await page.$eval('#cr-trending-list', (el) => el.innerHTML.slice(0, 200));
+console.log('trending list:', trendingHTML.includes('cr-lb-empty') ? 'EMPTY STATE RENDERED' : 'ROWS RENDERED');
+
+const creatorsHTML = await page.$eval('#cr-creators-list', (el) => el.innerHTML.slice(0, 200));
+console.log('creators list:', creatorsHTML.includes('cr-lb-empty') ? 'EMPTY STATE RENDERED' : 'ROWS RENDERED');
+
+// Exercise search + sort + category controls for real (no mocked responses).
+await page.fill('#cr-q', 'dragon');
+await page.waitForTimeout(600); // debounce
+await page.click('[data-sort="remixed"]');
+await page.waitForTimeout(400);
+await page.selectOption('#cr-category', 'avatar');
+await page.waitForTimeout(400);
+await page.click('[data-sort="recent"]');
+await page.waitForTimeout(400);
+await page.fill('#cr-q', '');
+await page.selectOption('#cr-category', '');
+await page.waitForTimeout(400);
+
+// Publish form interactivity (no submit — just check it renders/updates).
+await page.fill('#cr-pub-id', 'test-id-not-submitted');
+await page.fill('#cr-pub-royalty', '15');
+await page.evaluate(() => document.getElementById('cr-pub-royalty').dispatchEvent(new Event('input')));
+const royaltyOut = await page.$eval('#cr-pub-royalty-out', (el) => el.textContent);
+console.log('royalty output updates on drag:', royaltyOut);
+
+await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/3af649c2-981d-4e27-bcc7-a1b386bdb681/scratchpad/creations-empty.png', fullPage: true });
+
+// Mobile viewport check
+await page.setViewportSize({ width: 375, height: 800 });
+await page.waitForTimeout(200);
+await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/3af649c2-981d-4e27-bcc7-a1b386bdb681/scratchpad/creations-mobile.png', fullPage: true });
+
+console.log('\n--- console errors ---');
+console.log(errors.length ? errors.join('\n') : '(none)');
+console.log('\n--- console warnings ---');
+console.log(warnings.length ? warnings.join('\n') : '(none)');
+console.log('\n--- network failures ---');
+console.log(networkFailures.length ? networkFailures.join('\n') : '(none)');
+
+await browser.close();
+process.exit(errors.length ? 1 : 0);
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index 4cabc5ddf..76b574b35 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -475,7 +475,9 @@ Every on-chain agent has a canonical URL triad, plus companion endpoints for pre
| `/a/:chainId/:agentId` | Canonical page — Open Graph + Twitter Player Card + Farcaster Frame + oEmbed discovery. Redirects real browsers into the SPA viewer. | `api/a-page.js` |
| `/a/:chainId/:agentId/embed` | Chromeless iframe viewer (kiosk mode) — meant to be embedded in iframes, web-component previews, and Twitter Player Card. | `a-embed.html` |
| `/api/a-og?chain=<id>&id=<agentId>` | 1200×630 OG image. Redirects to the manifest image if present; otherwise renders an SVG card with chain badge + owner. | `api/a-og.js` |
-| `/api/oembed?url=...` | oEmbed v1.0 JSON/XML. Recognizes `/a/:chain/:id` URLs; returns `type: rich` with an iframe html payload. | `api/agent-oembed.js` |
+| `/api/oembed?url=...` | oEmbed v1.0 JSON/XML. Recognizes `/a/:chain/:id`, `/agent/:id`, and `/forge/share/:id` URLs; returns `type: rich` with an iframe html payload. | `api/agent-oembed.js` |
+
+`/api/oembed` is the ONE oEmbed provider for every embeddable three.ws target — regular agents (`agentEmbedTarget`), on-chain agents (`onchainEmbedTarget`), and Forge 3D creations (`forgeEmbedTarget`) — sharing one builder module ([`api/_lib/embed.js`](../api/_lib/embed.js)) so the iframe markup and canonical URL shapes never drift between the oEmbed surface and the `get_embed_code` MCP tool ([`api/_mcp/tools/embed.js`](../api/_mcp/tools/embed.js), `docs/mcp.md`). A Forge creation's share page ([`api/forge-share.js`](../api/forge-share.js) → `/forge/share/:id`) carries an oEmbed discovery `<link>` pointing back at `/api/oembed`, same as `/agent/:id`'s share page ([`api/agent-share.js`](../api/agent-share.js)) — paste either URL into Notion/Discord/Slack and it unfurls into a live 3D viewer, no manual embed code needed.
### Surface matrix
@@ -490,6 +492,7 @@ Pick the right embed for each surface:
| Slack / Discord / iMessage | Paste `/a/:chain/:id` | OG tags + oEmbed give a rich preview. |
| Farcaster cast | Paste `/a/:chain/:id` | Frame meta tags render an interactive card with "View 3D" + "Explore" buttons. |
| Claude.ai artifact / LobeHub plugin | `<iframe src="/a/:chain/:id/embed">` (band 5) | Sandboxed embed — works inside AI artifact runtimes. |
+| A Forge 3D creation (any surface) | Paste `/forge/share/:id`, or copy a flavour from the Forge "Embed this model" panel — iframe, `<model-viewer>`, `<agent-3d>`, a `@three-ws/page-agent` guide, or a `@three-ws/walk` companion ([`src/forge-embed-snippets.js`](../src/forge-embed-snippets.js)) | oEmbed + OG unfurl the share URL anywhere; the panel's five tabs cover every distribution channel from a static viewer to a talking, walking body. |
### Embed policy
diff --git a/src/creations.css b/src/creations.css
new file mode 100644
index 000000000..1f577966e
--- /dev/null
+++ b/src/creations.css
@@ -0,0 +1,159 @@
+/* /creations — the creator marketplace gallery: search/filter/sort over the
+ live remix bazaar, trending + top-creator leaderboards, a lineage viewer,
+ and a publish path. Same monochrome palette + shell rhythm as /minted and
+ /launches so the three live feeds read as one product. */
+@import './ui-juice.css';
+
+.cr-feed-head .juice-live { margin-right: var(--space-2); }
+
+.cr-shell { max-width: 1200px; margin: 0 auto; padding: var(--space-xl, 40px) var(--space-md, 16px) var(--space-2xl, 64px); }
+
+/* Hero */
+.cr-hero { text-align: center; margin-bottom: var(--space-xl, 40px); }
+.cr-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .68rem); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 var(--space-sm, 12px); }
+.cr-live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ink-bright, #fff); animation: cr-ping 2.4s ease infinite; }
+@keyframes cr-ping { 0% { box-shadow: 0 0 0 0 rgba(255,255,255,.45);} 70% { box-shadow: 0 0 0 8px rgba(255,255,255,0);} 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0);} }
+.cr-title { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: clamp(2.2rem, 6vw, 3.4rem); font-weight: 700; line-height: 1.02; margin: 0 0 var(--space-sm, 12px); color: var(--ink-dim, #999); letter-spacing: -.02em; }
+.cr-title em { font-style: normal; color: var(--ink-bright, #fff); }
+.cr-sub { max-width: 680px; margin: 0 auto; color: var(--ink-dim, #999); font-size: var(--text-lg, 1.02rem); line-height: 1.5; }
+.cr-sub strong { color: var(--ink, #e8e8e8); font-weight: 600; }
+
+.cr-hero-ctas { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: var(--space-md, 16px); }
+.cr-btn { appearance: none; font: inherit; font-size: var(--text-sm, .82rem); font-weight: 600; cursor: pointer; text-decoration: none; color: var(--ink, #e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 9px 18px; transition: background .14s ease, border-color .14s ease, color .14s ease, transform .14s ease; }
+.cr-btn:hover { background: var(--surface-2, rgba(255,255,255,.06)); border-color: var(--stroke-strong, rgba(255,255,255,.16)); transform: translateY(-1px); }
+.cr-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }
+.cr-btn:disabled { opacity: .5; cursor: not-allowed; transform: none; }
+.cr-btn-primary { color: var(--bg-0, #0a0a0a); background: var(--ink-bright, #fff); border-color: var(--ink-bright, #fff); }
+.cr-btn-primary:hover { background: var(--ink, #e8e8e8); }
+
+.cr-section-h { font-family: var(--font-display, sans-serif); font-size: var(--text-lg, 1.05rem); font-weight: 600; color: var(--ink-bright, #fff); margin: 0; }
+
+/* Leaderboards */
+.cr-leaderboards { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg, 24px); margin-bottom: var(--space-xl, 40px); }
+.cr-lb-col { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); padding: var(--space-md, 16px); min-width: 0; }
+.cr-lb-head { margin-bottom: var(--space-sm, 12px); }
+.cr-lb-sub { display: block; margin-top: 4px; font-size: var(--text-2xs, .7rem); color: var(--ink-faint, #666); }
+.cr-lb-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; min-height: 3.4em; }
+.cr-lb-row { display: flex; align-items: center; gap: 10px; padding: 8px 6px; border-radius: var(--radius-md, 10px); text-decoration: none; color: inherit; transition: background .14s ease; }
+a.cr-lb-row:hover { background: var(--surface-2, rgba(255,255,255,.05)); }
+.cr-lb-rank { flex: 0 0 auto; width: 1.6em; text-align: center; font-family: var(--font-mono, monospace); font-size: var(--text-sm, .8rem); font-weight: 700; color: var(--ink-faint, #666); }
+.cr-lb-thumb { flex: 0 0 auto; width: 36px; height: 36px; border-radius: var(--radius-sm, 8px); overflow: hidden; background: var(--surface-2, rgba(255,255,255,.05)); }
+.cr-lb-thumb model-viewer { width: 100%; height: 100%; --poster-color: transparent; }
+.cr-lb-avatar { flex: 0 0 auto; width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; background: var(--surface-3, rgba(255,255,255,.08)); font-family: var(--font-mono, monospace); font-weight: 700; font-size: var(--text-sm, .8rem); color: var(--ink, #e8e8e8); }
+.cr-lb-body { flex: 1 1 auto; min-width: 0; }
+.cr-lb-title { display: block; font-size: var(--text-sm, .82rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.cr-lb-meta { display: block; font-size: var(--text-2xs, .68rem); color: var(--ink-faint, #666); }
+.cr-lb-stat { flex: 0 0 auto; font-family: var(--font-mono, monospace); font-size: var(--text-xs, .74rem); font-weight: 700; color: var(--ink, #ccc); white-space: nowrap; }
+.cr-lb-empty { padding: var(--space-md, 16px) 6px; font-size: var(--text-sm, .82rem); color: var(--ink-faint, #666); }
+.cr-lb-empty a { color: var(--ink-bright, #fff); }
+
+/* Controls */
+.cr-controls { margin-bottom: var(--space-lg, 24px); display: flex; flex-direction: column; gap: 10px; }
+.cr-search-row { display: flex; gap: 10px; flex-wrap: wrap; }
+.cr-search { flex: 1 1 260px; display: flex; align-items: center; gap: 8px; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 9px 16px; color: var(--ink-faint, #777); transition: border-color .14s ease; }
+.cr-search:focus-within { border-color: var(--stroke-strong, rgba(255,255,255,.24)); color: var(--ink, #ccc); }
+.cr-search input { flex: 1; border: none; background: transparent; outline: none; font: inherit; font-size: var(--text-sm, .85rem); color: var(--ink-bright, #fff); min-width: 0; }
+.cr-search input::placeholder { color: var(--ink-faint, #666); }
+.cr-select { flex: 0 0 auto; font: inherit; font-size: var(--text-sm, .82rem); color: var(--ink, #e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 9px 14px; cursor: pointer; }
+.cr-select:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }
+
+.cr-sort-row { display: inline-flex; gap: 2px; padding: 3px; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill, 999px); align-self: flex-start; }
+.cr-sort-btn { appearance: none; font: inherit; font-size: var(--text-sm, .8rem); font-weight: 500; cursor: pointer; color: var(--ink-dim, #888); background: transparent; border: none; border-radius: var(--radius-pill, 999px); padding: 6px 16px; transition: color .14s ease, background .14s ease; }
+.cr-sort-btn:hover { color: var(--ink, #e8e8e8); }
+.cr-sort-btn.active { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255,255,255,.08)); }
+.cr-sort-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }
+
+/* Feed head + count */
+.cr-feed-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: var(--space-md, 16px); flex-wrap: wrap; }
+.cr-count { font-size: var(--text-sm, .8rem); color: var(--ink-faint, #666); }
+
+/* Card grid */
+.cr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: var(--space-md, 16px); }
+.cr-card { display: flex; flex-direction: column; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); overflow: hidden; transition: border-color .14s ease, transform .14s ease, background .14s ease; }
+.cr-card:hover { border-color: var(--stroke-strong, rgba(255,255,255,.18)); background: var(--surface-2, rgba(255,255,255,.05)); transform: translateY(-2px); }
+
+.cr-card-thumb { display: block; aspect-ratio: 1 / 1; background: var(--bg-0, #0a0a0a); position: relative; }
+.cr-card-mv { width: 100%; height: 100%; display: block; --poster-color: transparent; background: radial-gradient(circle at 50% 40%, var(--surface-2, rgba(255,255,255,.05)), var(--bg-0, #0a0a0a)); }
+.cr-card-noglb { width: 100%; height: 100%; display: grid; place-items: center; font-family: var(--font-mono, monospace); font-size: var(--text-xl, 1.2rem); font-weight: 700; color: var(--ink-faint, #555); background: var(--surface-1, rgba(255,255,255,.03)); }
+.cr-card-derived { position: absolute; top: 8px; left: 8px; font-size: var(--text-2xs, .6rem); font-weight: 700; letter-spacing: .03em; text-transform: uppercase; color: var(--ink-bright, #fff); background: rgba(0,0,0,.55); backdrop-filter: blur(4px); border-radius: var(--radius-sm, 6px); padding: 2px 7px; }
+
+.cr-card-body { padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 8px; min-width: 0; flex: 1; }
+.cr-card-prompt { margin: 0; font-size: var(--text-sm, .82rem); color: var(--ink, #e0e0e0); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 2.4em; }
+.cr-card-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+.cr-chip { flex: 0 0 auto; font-size: var(--text-2xs, .64rem); font-weight: 600; letter-spacing: .02em; color: var(--ink-dim, #aaa); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm, 6px); padding: 1px 7px; white-space: nowrap; }
+.cr-chip--cat { text-transform: capitalize; }
+.cr-chip--payable { color: var(--success, #4ade80); border-color: var(--success, #4ade80); }
+.cr-chip--unpayable { opacity: .7; }
+
+.cr-card-actions { margin-top: auto; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.cr-card-btn { appearance: none; font: inherit; font-size: var(--text-2xs, .72rem); font-weight: 600; cursor: pointer; color: var(--ink, #e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-sm, 8px); padding: 6px 10px; transition: background .14s ease, border-color .14s ease; text-decoration: none; }
+.cr-card-btn:hover { background: var(--surface-3, rgba(255,255,255,.08)); border-color: var(--stroke-strong, rgba(255,255,255,.18)); }
+.cr-card-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }
+.cr-card-btn--remix { color: var(--bg-0, #0a0a0a); background: var(--ink-bright, #fff); border-color: var(--ink-bright, #fff); }
+.cr-card-btn--remix:hover { background: var(--ink, #e8e8e8); }
+.cr-card-btn:disabled { opacity: .5; cursor: not-allowed; }
+
+.cr-remix-inline { display: none; flex-direction: column; gap: 6px; padding-top: 8px; border-top: 1px dashed var(--stroke, rgba(255,255,255,.1)); margin-top: 8px; }
+.cr-remix-inline.is-open { display: flex; }
+.cr-remix-inline input { font: inherit; font-size: var(--text-sm, .8rem); color: var(--ink-bright, #fff); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-sm, 8px); padding: 7px 10px; }
+.cr-remix-status { font-size: var(--text-2xs, .7rem); color: var(--ink-faint, #666); min-height: 1.3em; }
+.cr-remix-status[data-kind="error"] { color: var(--danger, #f87171); }
+.cr-remix-status[data-kind="done"] { color: var(--success, #4ade80); }
+.cr-remix-status a { color: inherit; text-decoration: underline; }
+
+/* Skeleton / empty / error */
+.cr-skeleton { aspect-ratio: 3 / 4; border-radius: var(--radius-lg, 14px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.06)) 37%, var(--surface-1, rgba(255,255,255,.03)) 63%); background-size: 400% 100%; animation: cr-shimmer 1.4s ease infinite; }
+@keyframes cr-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+.cr-empty, .cr-error { grid-column: 1 / -1; text-align: center; padding: var(--space-xl, 40px) var(--space-md, 16px); color: var(--ink-dim, #888); border: 1px dashed var(--stroke, rgba(255,255,255,.12)); border-radius: var(--radius-lg, 14px); }
+.cr-empty-title { color: var(--ink-bright, #fff); font-weight: 600; margin-bottom: 4px; }
+.cr-empty-sub a { color: var(--ink-bright, #fff); }
+.cr-empty-sub code { font-family: var(--font-mono, monospace); color: var(--ink-dim, #aaa); }
+.cr-retry { appearance: none; font: inherit; cursor: pointer; color: var(--ink-bright, #fff); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-sm, 6px); padding: 3px 10px; margin-left: 4px; }
+.cr-retry:hover { background: var(--surface-3, rgba(255,255,255,.08)); }
+
+.cr-footer-state { text-align: center; margin-top: var(--space-lg, 24px); font-size: var(--text-sm, .8rem); color: var(--ink-faint, #666); min-height: 1.4em; }
+
+/* Lineage panel */
+.cr-card { position: relative; }
+.cr-lineage-panel { margin-top: var(--space-xl, 40px); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); padding: var(--space-md, 16px); }
+.cr-lineage-panel.is-hidden { display: none; }
+.cr-lineage-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--space-sm, 12px); }
+.cr-icon-btn { appearance: none; font: inherit; cursor: pointer; color: var(--ink-dim, #aaa); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: 50%; width: 28px; height: 28px; line-height: 1; }
+.cr-icon-btn:hover { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255,255,255,.08)); }
+.cr-lineage-chain { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.cr-lineage-item { display: flex; align-items: center; gap: 10px; padding: 8px 10px; background: var(--surface-2, rgba(255,255,255,.04)); border-radius: var(--radius-md, 10px); border: 1px solid var(--stroke, rgba(255,255,255,.06)); }
+.cr-lineage-idx { flex: 0 0 auto; width: 1.6em; text-align: center; font-family: var(--font-mono, monospace); font-size: var(--text-sm, .78rem); color: var(--ink-faint, #666); }
+.cr-lineage-body { flex: 1; min-width: 0; }
+.cr-lineage-instruction { display: block; font-size: var(--text-sm, .82rem); color: var(--ink-bright, #fff); font-weight: 600; }
+.cr-lineage-prompt { display: block; font-size: var(--text-2xs, .72rem); color: var(--ink-faint, #777); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.cr-lineage-view { flex: 0 0 auto; font-size: var(--text-2xs, .72rem); color: var(--ink-dim, #aaa); text-decoration: none; }
+.cr-lineage-view:hover { color: var(--ink-bright, #fff); }
+
+/* Publish */
+.cr-publish { margin-top: var(--space-2xl, 64px); padding-top: var(--space-lg, 24px); border-top: 1px solid var(--stroke, rgba(255,255,255,.07)); scroll-margin-top: 90px; }
+.cr-publish-sub { max-width: 640px; color: var(--ink-dim, #999); font-size: var(--text-sm, .85rem); line-height: 1.6; margin: 8px 0 var(--space-md, 16px); }
+.cr-publish-sub a { color: var(--ink-bright, #fff); }
+.cr-publish-form { display: grid; grid-template-columns: repeat(2, minmax(220px, 1fr)); gap: var(--space-sm, 12px) var(--space-md, 16px); max-width: 760px; }
+.cr-field { display: flex; flex-direction: column; gap: 6px; font-size: var(--text-sm, .82rem); color: var(--ink-dim, #999); }
+.cr-field input[type="text"], .cr-field select { font: inherit; font-size: var(--text-sm, .85rem); color: var(--ink-bright, #fff); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-sm, 8px); padding: 9px 12px; }
+.cr-field input[type="range"] { width: 100%; }
+.cr-field output { font-family: var(--font-mono, monospace); color: var(--ink-bright, #fff); font-weight: 700; }
+.cr-publish-form .cr-btn { grid-column: 1 / -1; justify-self: start; }
+.cr-publish-status { grid-column: 1 / -1; font-size: var(--text-sm, .82rem); min-height: 1.4em; color: var(--ink-faint, #666); }
+.cr-publish-status[data-kind="error"] { color: var(--danger, #f87171); }
+.cr-publish-status[data-kind="done"] { color: var(--success, #4ade80); }
+.cr-publish-status[data-kind="busy"] { color: var(--ink-dim, #aaa); }
+
+/* About */
+.cr-about { margin-top: var(--space-2xl, 64px); padding-top: var(--space-lg, 24px); border-top: 1px solid var(--stroke, rgba(255,255,255,.07)); }
+.cr-about-body { margin: 0; max-width: 760px; font-size: var(--text-sm, .85rem); line-height: 1.6; color: var(--ink-dim, #999); }
+.cr-about-body a { color: var(--ink-bright, #fff); }
+.cr-about-body strong { color: var(--ink, #ddd); }
+
+@media (max-width: 880px) {
+ .cr-leaderboards { grid-template-columns: 1fr; }
+}
+@media (max-width: 520px) {
+ .cr-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }
+ .cr-publish-form { grid-template-columns: 1fr; }
+}
diff --git a/src/creations.js b/src/creations.js
new file mode 100644
index 000000000..9c24ce7be
--- /dev/null
+++ b/src/creations.js
@@ -0,0 +1,566 @@
+/**
+ * /creations — the creator marketplace gallery (roadmap prompt 09): search,
+ * filter, sort, and live-preview the remix bazaar; view trending assets and a
+ * top-creators leaderboard; remix any card for real, on-chain USDC; inspect a
+ * remix's parent → child lineage; publish a finished creation into the gallery.
+ *
+ * Data flow (all real, no mocks):
+ * GET /api/remix-feed → paginated bazaar (recent)
+ * GET /api/remix-feed?sort=remixed|royalty → fixed top-N leaderboard slice
+ * GET /api/remix-feed?category=&q= → server-side filter
+ * GET /api/remix-feed?action=trending → most-remixed assets
+ * GET /api/remix-feed?action=lineage&root=<id> → parent → child chain
+ * POST /api/remix-feed { action:'publish', ... } → opt a creation in
+ * POST /api/x402/remix-asset (via window.X402.pay) → paid remix + royalty
+ * GET /api/creations-leaderboard → top creators (real agent identity)
+ */
+
+import { createLogger } from './shared/log.js';
+import { enterStagger, updateValue, liveDot, setLiveDot } from './ui-juice.js';
+import { ensureX402 } from './shared/x402-loader.js';
+
+const log = createLogger('creations');
+
+const PAGE_SIZE = 24;
+const CLIENT_HEADERS = (() => {
+ try {
+ const id = localStorage.getItem('forge:cid');
+ return id ? { 'x-forge-client': id } : {};
+ } catch {
+ return {};
+ }
+})();
+
+const state = {
+ sort: 'recent',
+ category: '',
+ q: '',
+ cursor: null,
+ hasMore: false,
+ loading: false,
+ items: [],
+};
+
+const $ = (id) => document.getElementById(id);
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function timeAgo(iso) {
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));
+ if (s < 60) return 'just now';
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.round(h / 24);
+ if (d < 30) return `${d}d ago`;
+ const mo = Math.round(d / 30);
+ if (mo < 12) return `${mo}mo ago`;
+ return `${Math.round(mo / 12)}y ago`;
+}
+
+function truncate(s, n) {
+ const t = String(s || '');
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
+}
+
+// ── card rendering ───────────────────────────────────────────────────────────
+
+function thumbHTML(glbUrl, alt) {
+ if (!glbUrl) return `<div class="cr-card-noglb" aria-hidden="true">3D</div>`;
+ return `<model-viewer
+ src="${esc(glbUrl)}"
+ alt="${esc(alt)}"
+ class="cr-card-mv"
+ reveal="auto"
+ loading="lazy"
+ disable-zoom
+ disable-pan
+ disable-tap
+ interaction-prompt="none"
+ camera-controls="false"
+ auto-rotate
+ rotation-per-second="16deg"
+ environment-image="neutral"
+ shadow-intensity="0"
+ exposure="1"
+ ></model-viewer>`;
+}
+
+function cardHTML(item) {
+ const promptText = item.prompt ? truncate(item.prompt, 110) : 'A remixable 3D creation';
+ const royaltyChip = item.royaltyPercent > 0
+ ? `<span class="cr-chip ${item.royaltyPayable ? 'cr-chip--payable' : 'cr-chip--unpayable'}" title="${item.royaltyPayable ? 'This creator has a payout wallet set' : 'No payout wallet set yet — royalty won’t route'}">${item.royaltyPercent}% royalty${item.royaltyPayable ? '' : ' · no wallet'}</span>`
+ : `<span class="cr-chip">no royalty</span>`;
+ const remixChip = item.remixCount > 0 ? `<span class="cr-chip" title="Creations derived from this one">${item.remixCount} remix${item.remixCount === 1 ? '' : 'es'}</span>` : '';
+ const categoryChip = `<span class="cr-chip cr-chip--cat">${esc(item.category || 'other')}</span>`;
+ return `
+ <article class="cr-card" data-id="${esc(item.id)}">
+ <div class="cr-card-thumb">
+ ${item.isDerived ? '<span class="cr-card-derived" title="This is itself a remix">remix</span>' : ''}
+ ${thumbHTML(item.glbUrl, promptText)}
+ </div>
+ <div class="cr-card-body">
+ <p class="cr-card-prompt" title="${esc(item.prompt || '')}">${esc(promptText)}</p>
+ <div class="cr-card-meta">${categoryChip}${royaltyChip}${remixChip}</div>
+ <div class="cr-card-actions">
+ <a class="cr-card-btn" href="${esc(item.viewerUrl)}" target="_blank" rel="noopener noreferrer">View</a>
+ <button class="cr-card-btn" type="button" data-lineage="${esc(item.id)}">Lineage</button>
+ <button class="cr-card-btn cr-card-btn--remix" type="button" data-remix-open="${esc(item.id)}">Remix — $0.25</button>
+ <span class="cr-time">${esc(timeAgo(item.createdAt))}</span>
+ </div>
+ <div class="cr-remix-inline" data-remix-inline="${esc(item.id)}">
+ <input type="text" class="cr-remix-input" placeholder='Describe the change, e.g. "make it metallic"' maxlength="500" />
+ <button class="cr-card-btn cr-card-btn--remix" type="button" data-remix-pay="${esc(item.id)}">Pay &amp; remix</button>
+ <div class="cr-remix-status" role="status" aria-live="polite"></div>
+ </div>
+ </div>
+ </article>
+ `;
+}
+
+function skeleton() {
+ return Array.from({ length: 8 })
+ .map(() => `<div class="cr-skeleton"></div>`)
+ .join('');
+}
+
+function emptyStateHTML() {
+ const hasFilters = Boolean(state.q || state.category || state.sort !== 'recent');
+ if (hasFilters) {
+ return (
+ `<div class="cr-empty"><div class="cr-empty-title">Nothing matches those filters</div>` +
+ `<p class="cr-empty-sub">Try a broader search, a different category, or <button type="button" class="cr-retry" id="cr-clear-filters">clear filters</button>.</p></div>`
+ );
+ }
+ return (
+ `<div class="cr-empty"><div class="cr-empty-title">No creations published to the bazaar yet</div>` +
+ `<p class="cr-empty-sub">Generate a model at <a href="/forge">/forge</a>, then publish it below to be the first entry ` +
+ `in the gallery. <a href="#cr-publish">Publish a creation →</a></p></div>`
+ );
+}
+
+function renderFeed(append) {
+ const host = $('cr-feed');
+ if (!host) return;
+ if (!state.items.length) {
+ host.setAttribute('aria-busy', 'false');
+ host.innerHTML = emptyStateHTML();
+ $('cr-clear-filters')?.addEventListener('click', clearFilters);
+ return;
+ }
+ host.setAttribute('aria-busy', 'false');
+ if (!append) {
+ host.innerHTML = state.items.map(cardHTML).join('');
+ enterStagger([...host.children], { step: 24 });
+ } else {
+ const startIdx = host.children.length;
+ const added = state.items.slice(startIdx).map(cardHTML).join('');
+ host.insertAdjacentHTML('beforeend', added);
+ enterStagger([...host.children].slice(startIdx), { step: 24 });
+ }
+}
+
+function updateCount() {
+ const el = $('cr-count');
+ if (!el) return;
+ const suffix = state.sort !== 'recent' ? ' · top slice' : state.hasMore ? ' · more available' : '';
+ el.textContent = state.items.length ? `${state.items.length} shown${suffix}` : '';
+}
+
+function setFeedLive(kind) {
+ const head = document.querySelector('.cr-feed-head .cr-count');
+ if (!head) return;
+ if (!head.previousElementSibling?.classList?.contains('juice-live')) {
+ head.insertAdjacentHTML('beforebegin', liveDot(kind));
+ } else {
+ setLiveDot(head.previousElementSibling, kind, kind);
+ }
+}
+
+// ── feed loading ─────────────────────────────────────────────────────────────
+
+async function loadFeed({ reset = false } = {}) {
+ if (state.loading) return;
+ state.loading = true;
+ if (reset) {
+ state.cursor = null;
+ state.items = [];
+ }
+ const host = $('cr-feed');
+ if (reset && host) {
+ host.setAttribute('aria-busy', 'true');
+ host.innerHTML = skeleton();
+ }
+ setFeedLive('connecting');
+ try {
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE), sort: state.sort });
+ if (state.category) params.set('category', state.category);
+ if (state.q) params.set('q', state.q);
+ if (state.cursor && !reset) params.set('before', state.cursor);
+ const res = await fetch(`/api/remix-feed?${params}`, { headers: { accept: 'application/json' } });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data?.message || `feed returned ${res.status}`);
+ if (!data.enabled) {
+ setFeedLive('error');
+ if (host) {
+ host.setAttribute('aria-busy', 'false');
+ host.innerHTML = `<div class="cr-error"><div class="cr-empty-title">The remix bazaar is temporarily unavailable</div><p>Check back shortly.</p></div>`;
+ }
+ return;
+ }
+ const incoming = Array.isArray(data.items) ? data.items : [];
+ state.items = reset ? incoming : [...state.items, ...incoming];
+ state.cursor = data.next || null;
+ state.hasMore = Boolean(data.next);
+ renderFeed(!reset);
+ updateCount();
+ setFeedLive(state.items.length ? 'live' : 'idle');
+ } catch (err) {
+ log.warn('feed failed', err?.message);
+ setFeedLive('error');
+ if (reset && host) {
+ host.setAttribute('aria-busy', 'false');
+ host.innerHTML =
+ `<div class="cr-error"><div class="cr-empty-title">Couldn’t reach the creator gallery</div>` +
+ `<p>${esc(err?.message || 'Reconnecting…')} <button type="button" class="cr-retry" id="cr-retry">Retry</button></p></div>`;
+ $('cr-retry')?.addEventListener('click', () => loadFeed({ reset: true }));
+ }
+ } finally {
+ state.loading = false;
+ renderLoadMoreSentinel();
+ }
+}
+
+let observer = null;
+function renderLoadMoreSentinel() {
+ const footer = $('cr-footer-state');
+ if (!footer) return;
+ const canPaginate = state.sort === 'recent' && state.hasMore;
+ footer.textContent = canPaginate ? '' : state.items.length ? (state.sort === 'recent' ? 'End of the gallery.' : 'Top of the leaderboard — switch to “New” to browse everything.') : '';
+ if (!canPaginate) {
+ observer?.disconnect();
+ return;
+ }
+ if (!observer && 'IntersectionObserver' in window) {
+ observer = new IntersectionObserver(
+ (entries) => {
+ if (entries[0].isIntersecting && !state.loading && state.hasMore) loadFeed({});
+ },
+ { rootMargin: '0px 0px 320px 0px' },
+ );
+ }
+ observer?.observe(footer);
+}
+
+function clearFilters() {
+ state.q = '';
+ state.category = '';
+ $('cr-q').value = '';
+ $('cr-category').value = '';
+ setSort('recent');
+}
+
+// ── controls ────────────────────────────────────────────────────────────────
+
+function setSort(sort) {
+ if (sort === state.sort) return;
+ state.sort = sort;
+ for (const btn of document.querySelectorAll('[data-sort]')) {
+ const on = btn.dataset.sort === sort;
+ btn.classList.toggle('active', on);
+ btn.setAttribute('aria-selected', String(on));
+ }
+ loadFeed({ reset: true });
+}
+
+function debounce(fn, ms) {
+ let t;
+ return (...args) => {
+ clearTimeout(t);
+ t = setTimeout(() => fn(...args), ms);
+ };
+}
+
+function wireControls() {
+ for (const btn of document.querySelectorAll('[data-sort]')) {
+ btn.addEventListener('click', () => setSort(btn.dataset.sort));
+ }
+ const qInput = $('cr-q');
+ const onSearch = debounce(() => {
+ state.q = qInput.value.trim();
+ loadFeed({ reset: true });
+ }, 350);
+ qInput?.addEventListener('input', onSearch);
+ $('cr-category')?.addEventListener('change', (e) => {
+ state.category = e.target.value;
+ loadFeed({ reset: true });
+ });
+}
+
+// ── remix (real x402 payment) ───────────────────────────────────────────────
+
+function cssEscape(s) {
+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(s) : String(s).replace(/["\\]/g, '\\$&');
+}
+
+function wireRemixActions() {
+ $('cr-feed')?.addEventListener('click', async (e) => {
+ const lineageId = e.target.closest('[data-lineage]')?.dataset.lineage;
+ if (lineageId) return openLineage(lineageId);
+
+ const openId = e.target.closest('[data-remix-open]')?.dataset.remixOpen;
+ if (openId) {
+ const inline = document.querySelector(`[data-remix-inline="${cssEscape(openId)}"]`);
+ inline?.classList.toggle('is-open');
+ if (inline?.classList.contains('is-open')) inline.querySelector('input')?.focus();
+ return;
+ }
+ const payId = e.target.closest('[data-remix-pay]')?.dataset.remixPay;
+ if (payId) return remixOne(payId, e.target.closest('.cr-card'));
+ });
+}
+
+async function remixOne(sourceId, cardEl) {
+ const inline = cardEl?.querySelector('[data-remix-inline]');
+ const input = inline?.querySelector('.cr-remix-input');
+ const statusEl = inline?.querySelector('.cr-remix-status');
+ const payBtn = cardEl?.querySelector(`[data-remix-pay="${cssEscape(sourceId)}"]`);
+ const instruction = input?.value.trim();
+ if (!instruction) {
+ if (statusEl) statusEl.textContent = 'Describe the change first.';
+ return;
+ }
+ if (payBtn) payBtn.disabled = true;
+ if (statusEl) {
+ statusEl.textContent = 'Opening payment…';
+ statusEl.dataset.kind = 'busy';
+ }
+ try {
+ const X402 = await ensureX402();
+ const out = await X402.pay({
+ endpoint: '/api/x402/remix-asset',
+ method: 'POST',
+ body: { source_creation_id: sourceId, instruction },
+ merchant: 'three.ws Remix Bazaar',
+ action: `Remix this model — $0.25 USDC (a royalty routes to its creator)`,
+ });
+ const remix = out?.result?.remix;
+ const royalty = out?.result?.royalty;
+ if (statusEl) {
+ statusEl.dataset.kind = 'done';
+ statusEl.innerHTML = remix?.viewerUrl
+ ? `Remixed! <a href="${esc(remix.viewerUrl)}" target="_blank" rel="noopener noreferrer">View your new model →</a>` +
+ (royalty?.paid ? ` · $${royalty.creatorUsd} routed to the original creator.` : '')
+ : 'Remix submitted.';
+ }
+ if (input) input.value = '';
+ } catch (err) {
+ if (statusEl) {
+ statusEl.dataset.kind = 'error';
+ statusEl.textContent = err?.message || 'Remix failed. Try again.';
+ }
+ } finally {
+ if (payBtn) payBtn.disabled = false;
+ }
+}
+
+// ── lineage ──────────────────────────────────────────────────────────────────
+
+async function openLineage(rootId) {
+ const panel = $('cr-lineage-panel');
+ const chain = $('cr-lineage-chain');
+ if (!panel || !chain) return;
+ panel.classList.remove('is-hidden');
+ panel.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ chain.innerHTML = `<li class="cr-lineage-item"><span class="cr-lineage-body">Loading lineage…</span></li>`;
+ try {
+ const res = await fetch(`/api/remix-feed?action=lineage&root=${encodeURIComponent(rootId)}`, {
+ headers: { accept: 'application/json' },
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data?.message || `lineage returned ${res.status}`);
+ const lineage = Array.isArray(data.lineage) ? data.lineage : [];
+ if (!lineage.length) {
+ chain.innerHTML = `<li class="cr-lineage-item"><span class="cr-lineage-body">No remixes yet — be the first to build on this one.</span></li>`;
+ return;
+ }
+ chain.innerHTML = lineage
+ .map(
+ (node, i) => `
+ <li class="cr-lineage-item">
+ <span class="cr-lineage-idx">${i + 1}</span>
+ <span class="cr-lineage-body">
+ <span class="cr-lineage-instruction">${esc(node.instruction || node.prompt || 'Remix')}</span>
+ <span class="cr-lineage-prompt">${esc(truncate(node.prompt || '', 80))}</span>
+ </span>
+ ${node.viewerUrl ? `<a class="cr-lineage-view" href="${esc(node.viewerUrl)}" target="_blank" rel="noopener noreferrer">View →</a>` : ''}
+ </li>
+ `,
+ )
+ .join('');
+ } catch (err) {
+ chain.innerHTML = `<li class="cr-lineage-item"><span class="cr-lineage-body">${esc(err?.message || 'Could not load lineage.')}</span></li>`;
+ }
+}
+
+// ── leaderboards ─────────────────────────────────────────────────────────────
+
+function trendingRowHTML(item, i) {
+ return `
+ <li>
+ <a class="cr-lb-row" href="${esc(item.viewerUrl)}" target="_blank" rel="noopener noreferrer">
+ <span class="cr-lb-rank">${i + 1}</span>
+ <span class="cr-lb-thumb">${thumbHTML(item.glbUrl, item.prompt || 'creation')}</span>
+ <span class="cr-lb-body">
+ <span class="cr-lb-title">${esc(truncate(item.prompt || 'A 3D creation', 48))}</span>
+ <span class="cr-lb-meta">${esc(item.category || 'other')}${item.remixable ? '' : ' · no longer remixable'}</span>
+ </span>
+ <span class="cr-lb-stat">${item.remixCount} remix${item.remixCount === 1 ? '' : 'es'}</span>
+ </a>
+ </li>
+ `;
+}
+
+function creatorRowHTML(row, i) {
+ const initials = (row.agent?.name || 'A').trim().slice(0, 2).toUpperCase();
+ return `
+ <li>
+ <a class="cr-lb-row" href="${esc(row.agent?.url || '/agents')}">
+ <span class="cr-lb-rank">${i + 1}</span>
+ <span class="cr-lb-avatar" aria-hidden="true">${esc(initials)}</span>
+ <span class="cr-lb-body">
+ <span class="cr-lb-title">${esc(row.agent?.name || 'Agent')}</span>
+ <span class="cr-lb-meta">${row.mintedCount} minted · ${row.remixCount} remix${row.remixCount === 1 ? '' : 'es'}</span>
+ </span>
+ <span class="cr-lb-stat">$${row.royaltyEarnedUsd.toFixed(2)}</span>
+ </a>
+ </li>
+ `;
+}
+
+async function loadLeaderboards() {
+ const trendingHost = $('cr-trending-list');
+ const creatorsHost = $('cr-creators-list');
+ try {
+ const res = await fetch('/api/creations-leaderboard?limit=6', { headers: { accept: 'application/json' } });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.enabled) throw new Error('leaderboard unavailable');
+
+ if (trendingHost) {
+ trendingHost.setAttribute('aria-busy', 'false');
+ const assets = Array.isArray(data.topRemixedAssets) ? data.topRemixedAssets : [];
+ trendingHost.innerHTML = assets.length
+ ? assets.map(trendingRowHTML).join('')
+ : `<li class="cr-lb-empty">No remixes yet — <a href="#cr-feed">be the first to remix something</a>.</li>`;
+ }
+ if (creatorsHost) {
+ creatorsHost.setAttribute('aria-busy', 'false');
+ const creators = Array.isArray(data.topCreators) ? data.topCreators : [];
+ creatorsHost.innerHTML = creators.length
+ ? creators.map(creatorRowHTML).join('')
+ : `<li class="cr-lb-empty">No creator has been remixed yet — <a href="/agent-identities">mint a 3D asset</a> to appear here.</li>`;
+ }
+ } catch (err) {
+ log.warn('leaderboards failed', err?.message);
+ if (trendingHost) {
+ trendingHost.setAttribute('aria-busy', 'false');
+ trendingHost.innerHTML = `<li class="cr-lb-empty">Leaderboard temporarily unavailable.</li>`;
+ }
+ if (creatorsHost) {
+ creatorsHost.setAttribute('aria-busy', 'false');
+ creatorsHost.innerHTML = `<li class="cr-lb-empty">Leaderboard temporarily unavailable.</li>`;
+ }
+ }
+}
+
+// ── publish ──────────────────────────────────────────────────────────────────
+
+const LICENSE_HINTS = {
+ 'remix-royalty': true,
+ 'remix-cc': false,
+ 'remix-nc': false,
+ 'all-rights': false,
+};
+
+function wirePublishForm() {
+ const form = $('cr-publish-form');
+ if (!form) return;
+ const licenseSel = $('cr-pub-license');
+ const royaltyRow = $('cr-pub-royalty-row');
+ const royaltyInput = $('cr-pub-royalty');
+ const royaltyOut = $('cr-pub-royalty-out');
+ const statusEl = $('cr-pub-status');
+ const submitBtn = $('cr-pub-submit');
+
+ royaltyInput.addEventListener('input', () => {
+ royaltyOut.textContent = `${royaltyInput.value}%`;
+ });
+ licenseSel.addEventListener('change', () => {
+ royaltyRow.hidden = licenseSel.value === 'all-rights';
+ });
+
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const creationId = $('cr-pub-id').value.trim();
+ if (!creationId) return;
+ const wallet = $('cr-pub-wallet').value.trim();
+ const license = licenseSel.value;
+ const royaltyBps = Math.round(Number(royaltyInput.value || 0) * 100);
+ submitBtn.disabled = true;
+ statusEl.textContent = 'Publishing…';
+ statusEl.dataset.kind = 'busy';
+ try {
+ const res = await fetch('/api/remix-feed', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({
+ action: 'publish',
+ creation_id: creationId,
+ license,
+ royalty_bps: license === 'all-rights' ? 0 : royaltyBps,
+ ...(wallet ? { creator_wallet: wallet } : {}),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data?.published) {
+ statusEl.dataset.kind = 'error';
+ statusEl.textContent = data?.error || 'Could not publish that creation — check the id and try again.';
+ submitBtn.disabled = false;
+ return;
+ }
+ const p = data.published;
+ statusEl.dataset.kind = 'done';
+ statusEl.textContent = p.remixable
+ ? p.royaltyPayable
+ ? `Published — remixable at ${p.royaltyPercent}% royalty. Refresh the gallery to see it.`
+ : `Published — remixable at ${p.royaltyPercent}% royalty, but add a wallet above to actually collect it.`
+ : 'Published to the gallery — display only, not remixable.';
+ form.reset();
+ royaltyOut.textContent = '10%';
+ loadFeed({ reset: true });
+ loadLeaderboards();
+ } catch (err) {
+ statusEl.dataset.kind = 'error';
+ statusEl.textContent = err?.message || 'Publishing failed. Check your connection and try again.';
+ } finally {
+ submitBtn.disabled = false;
+ }
+ });
+}
+
+// ── init ─────────────────────────────────────────────────────────────────────
+
+function init() {
+ wireControls();
+ wireRemixActions();
+ wirePublishForm();
+ $('cr-lineage-close')?.addEventListener('click', () => $('cr-lineage-panel')?.classList.add('is-hidden'));
+ loadFeed({ reset: true });
+ loadLeaderboards();
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
+else init();
diff --git a/src/forge-embed-panel.js b/src/forge-embed-panel.js
index dc1c4b7db..952d51248 100644
--- a/src/forge-embed-panel.js
+++ b/src/forge-embed-panel.js
@@ -1,15 +1,22 @@
// Forge embed panel — turn a finished creation into a one-line embed for any
-// website. Self-contained: it reads the live GLB URL straight off the result
-// bar's Download link, so it never needs Forge's internal state and stays
-// decoupled from src/forge.js (which is edited often).
+// website, agent, or companion. Self-contained: it reads the live GLB URL
+// straight off the result bar's Download link, so it never needs Forge's
+// internal state and stays decoupled from src/forge.js (which is edited often).
//
-// Two embed flavours, both real:
-// • iframe — points at /forge/embed?src=<glb>, a zero-dependency three.ws
-// viewer page (orbit + AR + branding). Works on any site, no scripts,
-// no CORS to worry about (the iframe document is same-origin with the GLB
-// host the way Forge already loads it).
-// • web component — a <model-viewer> snippet for builders who want the model
-// inline in their own DOM with their own controls.
+// Five flavours, all real:
+// • iframe — points at /forge/embed?src=<glb>, a zero-dependency
+// three.ws viewer page (orbit + AR + branding). Works on any site, no
+// scripts, no CORS to worry about.
+// • web component — a <model-viewer> snippet for builders who want the
+// model inline in their own DOM with their own controls.
+// • <agent-3d> — the platform's own pure-3D web component.
+// • page-agent — "add to your agent": a @three-ws/page-agent guide that
+// narrates your page with this exact body (Option B custom-avatar path).
+// • walk companion — "add to your site": a @three-ws/walk corner companion
+// roster entry for this exact body.
+// The last two turn a Forge creation into distribution beyond a static
+// viewer — the same rigged model becomes a talking guide or a walking
+// companion elsewhere, one paste.
import { Modal } from './shared/modal.js';
import {
@@ -22,6 +29,8 @@ import {
buildIframeSnippet,
buildWebComponentSnippet,
buildAgentThreeDSnippet,
+ buildPageAgentSnippet,
+ buildWalkCompanionSnippet,
} from './forge-embed-snippets.js';
const STYLE_ID = 'tws-forge-embed-styles';
@@ -58,9 +67,27 @@ function agentThreeDSnippet() {
return buildAgentThreeDSnippet(state.glbUrl, state.title, state.sizeId);
}
+function pageAgentSnippet() {
+ return buildPageAgentSnippet(state.glbUrl, state.title);
+}
+
+function walkCompanionSnippet() {
+ return buildWalkCompanionSnippet(state.glbUrl, state.title);
+}
+
+const TAB_FOOTERS = {
+ iframe: 'Drops a live, orbitable model on any site — AR-ready on phones.',
+ component: 'A <model-viewer> element you style and control yourself.',
+ agent3d: "Drops the platform's own pure-3D web component — no third-party script.",
+ 'page-agent': 'Add to your agent: a talking, lipsync guide that narrates your page as this body.',
+ walk: 'Add to your site: a corner companion visitors can walk around as this body.',
+};
+
function currentSnippet() {
if (state.tab === 'iframe') return iframeSnippet();
if (state.tab === 'agent3d') return agentThreeDSnippet();
+ if (state.tab === 'page-agent') return pageAgentSnippet();
+ if (state.tab === 'walk') return walkCompanionSnippet();
return webComponentSnippet();
}
@@ -91,6 +118,8 @@ function bodyHtml() {
${tabBtn('iframe', 'iframe')}
${tabBtn('component', 'Web component')}
${tabBtn('agent3d', esc('<agent-3d>'))}
+ ${tabBtn('page-agent', 'Page agent')}
+ ${tabBtn('walk', 'Walk companion')}
</div>
<div class="tws-emb-seg" role="group" aria-label="Size">
${SIZES.map(sizeBtn).join('')}
@@ -106,7 +135,7 @@ function bodyHtml() {
</button>
<p class="tws-emb-foot">
- Drops a live, orbitable model on any site — AR-ready on phones.
+ ${esc(TAB_FOOTERS[state.tab] || TAB_FOOTERS.iframe)}
<a href="${esc(embedPageUrl())}" target="_blank" rel="noopener">Open the standalone viewer ↗</a>
</p>
</div>
@@ -124,6 +153,12 @@ function rerender(modalBody) {
for (const b of modalBody.querySelectorAll('.tws-emb-size')) {
b.setAttribute('aria-pressed', String(b.dataset.size === state.sizeId));
}
+ const foot = modalBody.querySelector('.tws-emb-foot');
+ if (foot) {
+ const link = foot.querySelector('a');
+ foot.firstChild.textContent = `${TAB_FOOTERS[state.tab] || TAB_FOOTERS.iframe} `;
+ if (link) link.href = embedPageUrl();
+ }
}
async function copyText(text, btn) {
@@ -224,7 +259,7 @@ const CSS = `
.tws-emb-frame { display: block; width: 100%; height: 100%; border: 0; }
.tws-emb-controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: space-between; }
.tws-emb-seg {
- display: inline-flex; gap: 2px; padding: 2px;
+ display: inline-flex; flex-wrap: wrap; gap: 2px; padding: 2px;
background: var(--surface-1, rgba(255,255,255,0.03));
border: 1px solid var(--stroke, rgba(255,255,255,0.1));
border-radius: 10px;
diff --git a/src/forge-embed-snippets.js b/src/forge-embed-snippets.js
index 502db91c7..b1b70dfeb 100644
--- a/src/forge-embed-snippets.js
+++ b/src/forge-embed-snippets.js
@@ -123,3 +123,60 @@ export function buildAgentThreeDSnippet(glbUrl, title, sizeId) {
`\n</agent-3d>`
);
}
+
+// "Add to your agent/site" — the other two real distribution channels for a
+// rigged creation, beyond the pure orbit-viewer embeds above. Both packages
+// are published, documented npm modules (@three-ws/page-agent,
+// @three-ws/walk) with their OWN real "bring your own GLB" contracts — these
+// snippets use those contracts exactly (AvatarStage + SpeechNarrator "Option
+// B" for page-agent per page-agent-sdk/docs/guide-custom-avatars.md;
+// createWalkCompanion({ avatars }) with an absolute-URL roster entry for
+// walk, per walk-sdk/src/roster.js's resolveAvatarUrl — "Absolute URLs pass
+// through untouched"). Neither package needs the GLB to already be a
+// platform `avatars` row: any public https URL (a fresh Forge creation's
+// download link included) works as-is.
+
+// @three-ws/page-agent — a rigged, lipsync-capable guide docked on the page.
+// Requires a *rigged* GLB (skeleton + idle/talk clips or ARKit visemes) —
+// the same requirement forge_avatar/rig_mesh already satisfy.
+export function buildPageAgentSnippet(glbUrl, title) {
+ const alt = escEmbed(title || 'Your agent');
+ const url = escEmbed(glbUrl);
+ return (
+ `<!-- npm i @three-ws/page-agent three -->\n` +
+ `<div id="guide" style="width:320px;height:420px"></div>\n` +
+ `<script type="module">\n` +
+ ` import { AvatarStage, SpeechNarrator } from '@three-ws/page-agent';\n\n` +
+ ` const stage = new AvatarStage(document.getElementById('guide'), { background: 'transparent' });\n` +
+ ` await stage.load('${url}', { framing: 'upper' });\n\n` +
+ ` const narrator = new SpeechNarrator(stage);\n` +
+ ` narrator.setAgent({ voice: { lang: 'en-US', rate: 1.0, pitch: 1.0 } });\n` +
+ ` await narrator.speak('Hi — I\\'m ${alt}, forged on three.ws.');\n` +
+ `</script>`
+ );
+}
+
+// @three-ws/walk — an idling corner companion the visitor can detach into a
+// full-page playground. `avatars` overrides the built-in roster with one
+// custom entry (rig:'shared' retargets idle/walk/wave from the platform's
+// shared clip library, matching forge_avatar/rig_mesh output).
+export function buildWalkCompanionSnippet(glbUrl, title) {
+ const alt = escEmbed(title || 'Your avatar');
+ const url = escEmbed(glbUrl);
+ return (
+ `<!-- npm i @three-ws/walk three -->\n` +
+ `<script type="module">\n` +
+ ` import { createWalkCompanion } from '@three-ws/walk';\n\n` +
+ ` const walk = createWalkCompanion({\n` +
+ ` defaultAvatarId: 'mine',\n` +
+ ` avatars: [{\n` +
+ ` id: 'mine', name: '${alt}', emoji: '✨', category: 'Yours',\n` +
+ ` asset: '${url}', source: 'static', rig: 'shared',\n` +
+ ` clips: { idle: 'idle', walk: 'av-walk-feminine', run: 'av-walk-feminine', wave: 'wave', jump: 'jump' },\n` +
+ ` tags: ['custom'],\n` +
+ ` }],\n` +
+ ` });\n` +
+ ` walk.bootstrap();\n` +
+ `</script>`
+ );
+}
diff --git a/src/game/boutique-purchase.js b/src/game/boutique-purchase.js
new file mode 100644
index 000000000..f6603bff6
--- /dev/null
+++ b/src/game/boutique-purchase.js
@@ -0,0 +1,134 @@
+// $THREE boutique purchase (W04) — the client half of the in-game premium
+// cosmetics rail. Real on-chain settlement: the buyer's own connected Solana
+// wallet signs ONE $THREE transfer (server-built, server-priced, split
+// between the holder-rewards pool and the treasury — see
+// multiplayer/src/game-token.js), we broadcast it, and only once the server
+// re-reads the CONFIRMED transaction from RPC does it grant the cosmetic.
+// Mirrors coin-buy.js's connect → sign → broadcast → confirm flow.
+
+import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
+
+// Overridable for local/devnet verification only (mirrors window.GAME_SERVER_URL
+// in community-net.js). Every real deploy leaves this unset and settles on
+// mainnet, matching the server's default SOLANA_RPC_URL.
+function boutiqueNetwork() {
+ return (typeof window !== 'undefined' && window.GAME_TOKEN_NETWORK) || 'mainnet';
+}
+
+// A fully custom RPC endpoint (e.g. a local `solana-test-validator`), for
+// verification runs only — production never sets this and always resolves
+// through the same-origin proxy in SOLANA_RPC.
+function boutiqueRpcUrl() {
+ if (typeof window !== 'undefined' && window.GAME_TOKEN_RPC_URL) return window.GAME_TOKEN_RPC_URL;
+ return SOLANA_RPC[boutiqueNetwork()] || SOLANA_RPC.mainnet;
+}
+
+function decodeBase64(b64) {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ return bytes;
+}
+
+/**
+ * Map a purchase failure to copy the player can act on, mirroring
+ * coin-buy.js's friendlyTradeError.
+ * @param {Error} err
+ */
+function friendlyBoutiqueError(err) {
+ const raw = (err && (err.message || String(err))) || '';
+ const m = raw.toLowerCase();
+ if (/reject|denied|cancell?ed|user declined/.test(m)) return 'Cancelled in wallet.';
+ if (/insufficient (lamports|funds)|debit an account|custom program error: 0x1\b/.test(m))
+ return 'Not enough $THREE (or SOL for network fees) to cover this purchase.';
+ if (/blockhash not found|block height exceeded|expired|too old/.test(m))
+ return 'The quote expired — try again.';
+ if (/failed to fetch|networkerror|timed out|timeout|fetch failed/.test(m))
+ return "Couldn't reach the network. Check your connection and try again.";
+ return raw.replace(/\s+/g, ' ').trim().slice(0, 140) || 'Purchase failed. Try again.';
+}
+
+// Wait for the server's reply to a specific boutiqueQuote request. Times out
+// so a dropped connection can't hang the buy action forever.
+function waitForQuote(net, id, timeoutMs = 15000) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { unsub(); reject(new Error('Timed out waiting for a price. Try again.')); }, timeoutMs);
+ const unsub = net.on('boutiqueQuote', (msg) => {
+ if (msg?.id !== id) return;
+ clearTimeout(timer);
+ unsub();
+ resolve(msg);
+ });
+ });
+}
+
+// Wait for the settle-outcome notice (success or a specific server-side
+// rejection) so the caller reports exactly what happened rather than guessing.
+function waitForSettleNotice(net, timeoutMs = 20000) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { unsub(); reject(new Error('Timed out confirming the purchase. Check your wardrobe in a moment.')); }, timeoutMs);
+ const unsub = net.on('notice', (n) => {
+ if (n?.kind !== 'boutique') return;
+ clearTimeout(timer);
+ unsub();
+ resolve(n);
+ });
+ });
+}
+
+/**
+ * Buy one premium cosmetic with $THREE, end to end: connect wallet → server
+ * quote (server-priced) → wallet signs → broadcast → server re-verifies the
+ * confirmed transaction on-chain → grant. Never trusts the client's own
+ * "it worked" — the unlock only happens after `_handleBoutiqueSettle` on the
+ * server confirms the transfer actually landed.
+ * @param {{ net: object, item: { id: string, name: string, price?: number }, onStage?: (stage: string) => void }} opts
+ * @returns {Promise<{ ok: true, sig: string, explorerUrl: string, text: string }>}
+ */
+export async function buyBoutiqueItem({ net, item, onStage = () => {} }) {
+ if (!net || !item?.id) throw new Error('Nothing to buy.');
+ const wallet = detectSolanaWallet();
+ if (!wallet) {
+ if (typeof window !== 'undefined') window.open('https://phantom.app/', '_blank', 'noopener');
+ throw new Error('Install a Solana wallet (Phantom) to buy with $THREE.');
+ }
+
+ onStage('connecting');
+ if (!wallet.publicKey) {
+ try { await wallet.connect(); }
+ catch (err) { throw new Error(friendlyBoutiqueError(err)); }
+ }
+ const address = wallet.publicKey?.toString?.();
+ if (!address) throw new Error('Could not read your wallet address.');
+
+ onStage('pricing');
+ net.boutiqueQuote(item.id, address);
+ const quote = await waitForQuote(net, item.id);
+ if (!quote?.txBase64) throw new Error('Could not price that purchase — try again.');
+
+ onStage('signing');
+ const { Transaction, Connection } = await import('@solana/web3.js');
+ const tx = Transaction.from(decodeBase64(quote.txBase64));
+ let signed;
+ try { signed = await wallet.signTransaction(tx); }
+ catch (err) { throw new Error(friendlyBoutiqueError(err)); }
+
+ onStage('broadcasting');
+ const netId = boutiqueNetwork();
+ const conn = new Connection(boutiqueRpcUrl(), 'confirmed');
+ let sig;
+ try {
+ sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });
+ } catch (err) {
+ throw new Error(friendlyBoutiqueError(err));
+ }
+ try {
+ const latest = await conn.getLatestBlockhash('confirmed');
+ await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');
+ } catch { /* landed but slow to confirm — settle re-checks the confirmed tx on RPC itself */ }
+
+ onStage('settling');
+ net.boutiqueSettle(quote.quoteToken, sig);
+ const notice = await waitForSettleNotice(net);
+ return { ok: true, sig, explorerUrl: solanaTxExplorerUrl(netId, sig), text: notice.text };
+}
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 6e3da04ff..bbeb4a436 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -1181,6 +1181,10 @@ export class CoinCommunities {
symbol: coin.symbol,
seed: seedFromString(coin.mint) >>> 0,
biome: this.env?.biome,
+ // Boutique NPCs (W03) call these to open the real cosmetics shop /
+ // wardrobe panels — same panels the HUD buttons drive.
+ openShop: () => this._toggleShop(),
+ openWardrobe: () => this._toggleWardrobe(),
},
radius: WORLD_RADIUS - 4,
});
diff --git a/src/game/community-net.js b/src/game/community-net.js
index 7aa1c7faa..379e2c40c 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -137,6 +137,10 @@ export class CommunityNet {
xpgain: new Set(), // ({skill, amount, xp, level, levelXp, nextXp})
levelup: new Set(), // ({skill, level})
notice: new Set(), // ({kind, text, ...}) — activity result toast (fish/eat/tool/full/quest)
+ // General store, bank/ATM & the $THREE boutique (W04).
+ store: new Set(), // ({sell:[{item,label,price}], buy:[{item,qty,price,label}]})
+ boutique: new Set(), // ({listings, owned, configured}) — premium cosmetics priced in $THREE
+ boutiqueQuote: new Set(), // ({id, price, quoteToken, txBase64}) — unsigned $THREE purchase to sign
quests: new Set(), // ({offers, active, day}) — jobs board + active runs (W05)
questComplete: new Set(), // ({id, title, reward, kind, coop}) — a mission/heist finished
combat: new Set(), // ({node, kind, mobHp, mobMaxHp, playerHp, playerMaxHp, dealt, dead, ...}) — combat-lite exchange
@@ -284,6 +288,10 @@ export class CommunityNet {
this.room.onMessage('xpgain', (msg) => this._emit('xpgain', msg || {}));
this.room.onMessage('levelup', (msg) => this._emit('levelup', msg || {}));
this.room.onMessage('notice', (msg) => this._emit('notice', msg || {}));
+ // General store, bank/ATM & the $THREE boutique (W04).
+ this.room.onMessage('store', (msg) => this._emit('store', msg || {}));
+ this.room.onMessage('boutique', (msg) => this._emit('boutique', msg || {}));
+ this.room.onMessage('boutiqueQuote', (msg) => this._emit('boutiqueQuote', msg || {}));
// Quests, jobs & heists (W05): the board + active runs and completion events.
this.room.onMessage('quests', (msg) => this._emit('quests', msg || {}));
this.room.onMessage('questComplete', (msg) => this._emit('questComplete', msg || {}));
@@ -521,6 +529,21 @@ export class CommunityNet {
equip(slot) { this._send('equip', { slot }); }
consume(ref) { this._send('consume', { slot: ref }); }
requestProfile() { this._send('profileReq'); }
+ // General store & bank/ATM (W04). Cash trades and banking settle purely
+ // off-schema; the result streams back via the 'store'/'profile'/'inv'/
+ // 'notice' events above.
+ requestStore() { this._send('storeReq'); }
+ storeBuy(item) { this._send('storeBuy', { item }); }
+ storeSell(slot, qty) { this._send('storeSell', { slot, qty }); }
+ bank(amount) { this._send('bank', { amount }); }
+ // The $THREE boutique (W04). requestBoutique() fetches the catalog + owned
+ // set; boutiqueQuote() prices one item and returns the unsigned tx to sign
+ // (the reply arrives via the 'boutiqueQuote' event); boutiqueSettle() hands
+ // back the broadcast signature for the server to verify on-chain before it
+ // grants anything.
+ requestBoutique() { this._send('boutiqueReq'); }
+ boutiqueQuote(id, wallet) { this._send('boutiqueQuote', { id, wallet }); }
+ boutiqueSettle(quoteToken, txSig) { this._send('boutiqueSettle', { quoteToken, txSig }); }
// Quests, jobs & heists (W05). Server-authoritative: accept/abandon a mission and
// interact at a quest object; the board + progress arrive via the 'quests' event
// and completions via 'questComplete'. questInteract acts on the zone the server
diff --git a/src/game/economy-ui.css b/src/game/economy-ui.css
new file mode 100644
index 000000000..80947d40d
--- /dev/null
+++ b/src/game/economy-ui.css
@@ -0,0 +1,116 @@
+/* Economy UI (W04) — the general store and bank/ATM modals opened from an
+ * NPC walk-up. Styled to the same monochrome tokens as coin-buy.css /
+ * play-systems.css (dark glass, white ink, 4px radii) so a walk-up counter
+ * reads like part of the same world as the wardrobe and the trade widget. */
+
+.ec-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ display: grid;
+ place-items: center;
+ background: rgba(0, 0, 0, 0.55);
+ backdrop-filter: blur(6px);
+ opacity: 0;
+ transition: opacity 0.18s ease;
+ padding: 16px;
+}
+.ec-overlay.ec-on { opacity: 1; }
+
+.ec-card {
+ width: min(420px, 100%);
+ max-height: min(640px, 88vh);
+ display: flex;
+ flex-direction: column;
+ background: var(--cc-panel-solid);
+ border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius);
+ box-shadow: var(--cc-shadow);
+ color: var(--cc-text);
+ transform: translateY(10px) scale(0.98);
+ transition: transform 0.18s ease;
+ overflow: hidden;
+}
+.ec-overlay.ec-on .ec-card { transform: none; }
+
+.ec-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 16px;
+ border-bottom: 1px solid var(--cc-edge-soft);
+ flex: none;
+}
+.ec-title { font-size: 14px; font-weight: 700; letter-spacing: 0.02em; }
+.ec-x {
+ width: 28px; height: 28px; display: grid; place-items: center;
+ background: transparent; border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ color: var(--cc-dim); cursor: pointer; transition: color 0.14s ease, background 0.14s ease, border-color 0.14s ease;
+}
+.ec-x:hover { color: var(--cc-text); background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); }
+.ec-x:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 2px; }
+
+.ec-tabs { display: flex; gap: 6px; padding: 10px 16px 0; flex: none; }
+.ec-tab {
+ flex: 1; padding: 8px 0; text-align: center; font-size: 12px; font-weight: 700; letter-spacing: 0.03em;
+ text-transform: uppercase; color: var(--cc-dim); background: transparent; border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius-sm); cursor: pointer; transition: color 0.14s ease, background 0.14s ease, border-color 0.14s ease;
+}
+.ec-tab:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.ec-tab.ec-on { color: var(--cc-ink); background: #fff; border-color: #fff; }
+.ec-tab:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 2px; }
+
+.ec-purse {
+ display: flex; align-items: center; justify-content: space-between; gap: 10px;
+ margin: 12px 16px 0; padding: 10px 12px; background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);
+ font-variant-numeric: tabular-nums; font-size: 12px; color: var(--cc-dim);
+}
+.ec-purse b { color: var(--cc-text); font-size: 13px; }
+
+.ec-body { flex: 1 1 auto; overflow-y: auto; padding: 12px 16px 16px; display: flex; flex-direction: column; gap: 8px; }
+
+.ec-row {
+ display: flex; align-items: center; gap: 10px; padding: 9px 10px;
+ background: rgba(255, 255, 255, 0.03); border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);
+}
+.ec-row-glyph { font-size: 18px; width: 24px; text-align: center; flex: none; }
+.ec-row-main { flex: 1; min-width: 0; }
+.ec-row-name { font-size: 13px; font-weight: 600; }
+.ec-row-sub { font-size: 11px; color: var(--cc-dim); margin-top: 2px; }
+.ec-row-btn {
+ flex: none; padding: 7px 12px; font-size: 12px; font-weight: 700; letter-spacing: 0.02em;
+ background: #fff; color: var(--cc-ink); border: none; border-radius: var(--cc-radius-sm); cursor: pointer;
+ transition: transform 0.1s ease, opacity 0.14s ease;
+}
+.ec-row-btn:hover:not(:disabled) { transform: translateY(-1px); }
+.ec-row-btn:active:not(:disabled) { transform: translateY(0) scale(0.97); }
+.ec-row-btn:disabled { opacity: 0.35; cursor: not-allowed; }
+.ec-row-btn:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 2px; }
+
+.ec-empty { padding: 22px 10px; text-align: center; color: var(--cc-dim); font-size: 12px; line-height: 1.5; }
+
+.ec-bank-amount { display: flex; align-items: center; gap: 8px; margin: 0 0 4px; }
+.ec-bank-input {
+ flex: 1; min-width: 0; padding: 10px 12px; font-size: 15px; font-variant-numeric: tabular-nums;
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ color: var(--cc-text); font-family: inherit;
+}
+.ec-bank-input:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 1px; }
+.ec-bank-presets { display: flex; gap: 6px; margin-bottom: 10px; }
+.ec-bank-preset {
+ flex: 1; padding: 6px 0; font-size: 11px; font-weight: 700; background: transparent; color: var(--cc-dim);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm); cursor: pointer; transition: color 0.14s ease, border-color 0.14s ease;
+}
+.ec-bank-preset:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.ec-bank-actions { display: flex; gap: 8px; }
+.ec-bank-actions .ec-row-btn { flex: 1; }
+.ec-bank-actions .ec-row-btn.ec-secondary { background: transparent; color: var(--cc-text); border: 1px solid var(--cc-edge); }
+
+.ec-status { padding: 0 16px 14px; font-size: 12px; color: var(--cc-dim); min-height: 16px; }
+.ec-status[data-kind="err"] { color: #ff8a8a; }
+.ec-status[data-kind="ok"] { color: #9effa6; }
+
+@media (max-width: 480px) {
+ .ec-card { width: 100%; }
+}
diff --git a/src/game/economy-ui.js b/src/game/economy-ui.js
new file mode 100644
index 000000000..79046c2ab
--- /dev/null
+++ b/src/game/economy-ui.js
@@ -0,0 +1,271 @@
+// Economy UI (W04) — the general store and bank/ATM modals opened by walking
+// up to their NPC and pressing E (npc/economy-npcs.js). Both are thin, honest
+// clients of the server-authoritative cash economy: every button sends an
+// intent over CommunityNet, the server prices/validates/mutates the profile,
+// and the result streams back through the existing 'store'/'profile'/'inv'/
+// 'notice' events — this module never assumes a trade landed until the server
+// confirms it. The $THREE boutique is a separate, on-chain flow that lives in
+// the wardrobe panel (play-systems.js), not here.
+
+import './economy-ui.css';
+import { itemDisplay } from './items.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;
+}
+
+// Base modal shell shared by the store and the bank — overlay, card, header
+// with a title + close button, and open/close lifecycle (fade + teardown).
+class EconPanel {
+ constructor({ title, onClose }) {
+ this._unsubs = [];
+ this._onClose = onClose;
+ this.body = el('div', { class: 'ec-body' });
+ this.status = el('div', { class: 'ec-status', role: 'status', 'aria-live': 'polite' });
+ this.card = el('div', { class: 'ec-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': title }, [
+ el('div', { class: 'ec-head' }, [
+ el('span', { class: 'ec-title', text: title }),
+ el('button', { class: 'ec-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() }),
+ ]),
+ this.body,
+ this.status,
+ ]);
+ this.overlay = el('div', { class: 'ec-overlay', onpointerdown: (e) => { if (e.target === this.overlay) this.close(); } }, [this.card]);
+ this.card.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') this.close();
+ e.stopPropagation();
+ });
+ document.body.appendChild(this.overlay);
+ requestAnimationFrame(() => this.overlay.classList.add('ec-on'));
+ }
+
+ track(unsub) { if (typeof unsub === 'function') this._unsubs.push(unsub); }
+
+ setStatus(text, kind) {
+ this.status.textContent = text || '';
+ this.status.setAttribute('data-kind', kind || '');
+ }
+
+ close() {
+ this.overlay.classList.remove('ec-on');
+ for (const u of this._unsubs) { try { u(); } catch { /* ignore */ } }
+ this._unsubs = [];
+ setTimeout(() => this.overlay.remove(), 180);
+ this._onClose?.();
+ }
+}
+
+let _openStore = null;
+let _openBank = null;
+
+// ---------------------------------------------------------------- store
+
+/**
+ * Open the general store: buy tools/consumables with cash, or sell gathered
+ * goods for cash. Idempotent — a second call while one is open just refocuses
+ * it (mirrors coin-buy.js's TradeModal singleton).
+ * @param {{ ui: object, net: object }} deps
+ */
+export function openStorePanel({ ui, net }) {
+ if (!net) return;
+ if (_openStore) return;
+ _openStore = new StorePanel({ ui, net, onClose: () => { _openStore = null; } });
+}
+
+class StorePanel extends EconPanel {
+ constructor({ ui, net, onClose }) {
+ super({ title: 'General Store', onClose });
+ this.ui = ui;
+ this.net = net;
+ this.tab = 'buy';
+ this.catalog = { sell: [], buy: [] };
+ this.profile = { gold: 0, inv: [] };
+
+ this.tabs = el('div', { class: 'ec-tabs' }, [
+ el('button', { class: 'ec-tab ec-on', type: 'button', text: 'Buy', onclick: () => this._setTab('buy') }),
+ el('button', { class: 'ec-tab', type: 'button', text: 'Sell', onclick: () => this._setTab('sell') }),
+ ]);
+ this.purse = el('div', { class: 'ec-purse' }, [
+ el('span', { text: 'Cash on hand' }),
+ el('b', { text: '0' }),
+ ]);
+ this.card.insertBefore(this.purse, this.body);
+ this.card.insertBefore(this.tabs, this.purse);
+
+ this.track(net.on('store', (msg) => { this.catalog = { sell: msg?.sell || [], buy: msg?.buy || [] }; this._render(); }));
+ this.track(net.on('profile', (snap) => { this._applyProfile(snap); }));
+ this.track(net.on('inv', (delta) => { this._applyProfile(delta); }));
+ this.track(net.on('notice', (n) => {
+ if (n?.kind === 'store' || n?.kind === 'full') this.setStatus(n.text || '', n.kind === 'full' ? 'err' : 'ok');
+ }));
+
+ net.requestStore();
+ net.requestProfile();
+ this._render();
+ }
+
+ _applyProfile(snap) {
+ if (!snap) return;
+ if (Number.isFinite(snap.gold)) this.profile.gold = snap.gold;
+ if (Array.isArray(snap.inv)) this.profile.inv = snap.inv;
+ this.purse.lastChild.textContent = this.profile.gold.toLocaleString();
+ this._render();
+ }
+
+ _setTab(tab) {
+ this.tab = tab;
+ for (const b of this.tabs.children) b.classList.toggle('ec-on', b.textContent.toLowerCase() === tab);
+ this._render();
+ }
+
+ _render() {
+ this.body.replaceChildren();
+ if (this.tab === 'buy') this._renderBuy(); else this._renderSell();
+ }
+
+ _renderBuy() {
+ if (!this.catalog.buy.length) {
+ this.body.appendChild(el('div', { class: 'ec-empty', text: 'Loading the catalog…' }));
+ return;
+ }
+ for (const entry of this.catalog.buy) {
+ const disp = itemDisplay(entry.item);
+ const afford = this.profile.gold >= entry.price;
+ this.body.appendChild(el('div', { class: 'ec-row' }, [
+ el('span', { class: 'ec-row-glyph', text: disp?.glyph || '📦' }),
+ el('div', { class: 'ec-row-main' }, [
+ el('div', { class: 'ec-row-name', text: `${entry.qty > 1 ? entry.qty + '× ' : ''}${entry.label || disp?.name || entry.item}` }),
+ el('div', { class: 'ec-row-sub', text: `${entry.price} cash` }),
+ ]),
+ el('button', {
+ class: 'ec-row-btn', type: 'button', text: 'Buy', disabled: !afford,
+ 'aria-label': `Buy ${entry.label || entry.item} for ${entry.price} cash`,
+ onclick: () => { this.setStatus('Buying…'); this.net.storeBuy(entry.item); },
+ }),
+ ]));
+ }
+ }
+
+ _renderSell() {
+ const sellable = new Set(this.catalog.sell.map((s) => s.item));
+ const priceOf = new Map(this.catalog.sell.map((s) => [s.item, s.price]));
+ const rows = this.profile.inv
+ .map((slot, i) => ({ slot, i }))
+ .filter(({ slot }) => slot?.item && slot.qty > 0 && sellable.has(slot.item));
+ if (!rows.length) {
+ this.body.appendChild(el('div', { class: 'ec-empty', text: 'Nothing to sell yet — gather wood, stone, coal, fish or hides out in the world and bring them back.' }));
+ return;
+ }
+ for (const { slot, i } of rows) {
+ const disp = itemDisplay(slot.item);
+ const price = priceOf.get(slot.item) || 0;
+ this.body.appendChild(el('div', { class: 'ec-row' }, [
+ el('span', { class: 'ec-row-glyph', text: disp?.glyph || '📦' }),
+ el('div', { class: 'ec-row-main' }, [
+ el('div', { class: 'ec-row-name', text: `${disp?.name || slot.item} × ${slot.qty}` }),
+ el('div', { class: 'ec-row-sub', text: `${price} cash each · ${price * slot.qty} total` }),
+ ]),
+ el('button', {
+ class: 'ec-row-btn', type: 'button', text: 'Sell all',
+ 'aria-label': `Sell all ${disp?.name || slot.item} for ${price * slot.qty} cash`,
+ onclick: () => { this.setStatus('Selling…'); this.net.storeSell({ zone: 'inv', i }); },
+ }),
+ ]));
+ }
+ }
+}
+
+// ---------------------------------------------------------------- bank
+
+/**
+ * Open the bank/ATM: move cash between the carried purse and the protected
+ * bank. Banked cash survives a death drop; carried cash doesn't.
+ * @param {{ ui: object, net: object }} deps
+ */
+export function openBankPanel({ ui, net }) {
+ if (!net) return;
+ if (_openBank) return;
+ _openBank = new BankPanel({ ui, net, onClose: () => { _openBank = null; } });
+}
+
+class BankPanel extends EconPanel {
+ constructor({ ui, net, onClose }) {
+ super({ title: 'Bank / ATM', onClose });
+ this.ui = ui;
+ this.net = net;
+ this.gold = 0;
+ this.bankBal = 0;
+
+ this.purse = el('div', { class: 'ec-purse' }, [
+ el('span', { text: 'Cash on hand' }),
+ el('b', { text: '0' }),
+ ]);
+ this.bankLine = el('div', { class: 'ec-purse' }, [
+ el('span', { text: 'Banked (protected)' }),
+ el('b', { text: '0' }),
+ ]);
+ this.card.insertBefore(this.purse, this.body);
+ this.card.insertBefore(this.bankLine, this.body);
+
+ this.depositInput = el('input', { type: 'number', min: '0', step: '1', class: 'ec-bank-input', 'aria-label': 'Amount to deposit', placeholder: '0' });
+ this.withdrawInput = el('input', { type: 'number', min: '0', step: '1', class: 'ec-bank-input', 'aria-label': 'Amount to withdraw', placeholder: '0' });
+
+ this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Deposit — protects cash from a death drop.' }));
+ this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [
+ this.depositInput,
+ el('button', { class: 'ec-row-btn', type: 'button', text: 'Deposit', onclick: () => this._deposit() }),
+ ]));
+ this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [
+ el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.depositInput.value = String(this.gold); } }),
+ ]));
+
+ this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Withdraw — moves banked cash back to your purse.' }));
+ this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [
+ this.withdrawInput,
+ el('button', { class: 'ec-row-btn ec-secondary', type: 'button', text: 'Withdraw', onclick: () => this._withdraw() }),
+ ]));
+ this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [
+ el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.withdrawInput.value = String(this.bankBal); } }),
+ ]));
+
+ this.track(net.on('profile', (snap) => this._applyProfile(snap)));
+ this.track(net.on('notice', (n) => {
+ if (n?.kind === 'bank') this.setStatus(n.text || '', 'ok');
+ }));
+
+ net.requestProfile();
+ }
+
+ _applyProfile(snap) {
+ if (!snap) return;
+ if (Number.isFinite(snap.gold)) this.gold = snap.gold;
+ if (Number.isFinite(snap.bank)) this.bankBal = snap.bank;
+ this.purse.lastChild.textContent = this.gold.toLocaleString();
+ this.bankLine.lastChild.textContent = this.bankBal.toLocaleString();
+ }
+
+ _deposit() {
+ const amount = Math.max(0, Math.floor(Number(this.depositInput.value) || 0));
+ if (!amount) { this.setStatus('Enter an amount to deposit.', 'err'); return; }
+ this.setStatus('Depositing…');
+ this.net.bank(amount);
+ this.depositInput.value = '';
+ }
+
+ _withdraw() {
+ const amount = Math.max(0, Math.floor(Number(this.withdrawInput.value) || 0));
+ if (!amount) { this.setStatus('Enter an amount to withdraw.', 'err'); return; }
+ this.setStatus('Withdrawing…');
+ this.net.bank(-amount);
+ this.withdrawInput.value = '';
+ }
+}
diff --git a/src/game/npc/economy-npcs.js b/src/game/npc/economy-npcs.js
new file mode 100644
index 000000000..50adc4803
--- /dev/null
+++ b/src/game/npc/economy-npcs.js
@@ -0,0 +1,65 @@
+// Economy NPCs (W04) — the general-store clerks and bank teller that make the
+// in-game cash economy walk-up-and-use. They stand at the vendor stalls and
+// the ATM spot world-zones.js already reserved for them ("Vendor stalls
+// ringing Downtown (economy / shop briefs)" / "The bank/ATM (W04)").
+//
+// Unlike the Agent Exchange roster (npc-catalog.js), which fronts a real x402
+// micro-service per character, these front the room's own off-schema cash
+// economy (multiplayer/src/economy.js + shop.js) over the WalkRoom message
+// channel — no on-chain settlement for cash, ever. The $THREE boutique (the
+// one piece of W04 that DOES settle on-chain) lives in the wardrobe panel
+// instead (src/game/play-systems.js), reachable from the rail's own Cosmetics
+// button rather than a dedicated NPC — it's a shop for what you're already
+// wearing, not a new place to walk to.
+
+import { spawnsOfType } from '../world-zones.js';
+import { openStorePanel, openBankPanel } from '../economy-ui.js';
+
+const AVATAR_CLERK = '/avatars/default.glb';
+const AVATAR_TELLER = '/avatars/cz.glb';
+
+export function economyNpcsFor() {
+ const list = [];
+
+ // General store — one clerk per vendor stall in world-zones.js. Walk up,
+ // press E, buy tools/consumables with cash or sell what you've gathered.
+ for (const stall of spawnsOfType('vendor')) {
+ list.push({
+ id: `npc-store-${stall.id}`,
+ name: 'General Store',
+ role: 'vendor',
+ avatar: AVATAR_CLERK,
+ pos: { x: stall.x, z: stall.z },
+ yaw: stall.yaw,
+ range: 5,
+ prompt: 'Buy & sell gear',
+ onInteract: ({ npc, ui, net }) => {
+ npc.say('Tools, ammo, a bite to eat — and I’ll pay cash for what you’ve gathered.');
+ npc.emote('av-call-me');
+ openStorePanel({ ui, net });
+ },
+ });
+ }
+
+ // Bank/ATM — deposit cash to protect it from a death drop, or withdraw it
+ // back to the purse. One teller at the spot world-zones.js reserved.
+ for (const atm of spawnsOfType('atm')) {
+ list.push({
+ id: `npc-bank-${atm.id}`,
+ name: 'Bank Teller',
+ role: 'bank',
+ avatar: AVATAR_TELLER,
+ pos: { x: atm.x, z: atm.z },
+ yaw: atm.yaw,
+ range: 5,
+ prompt: 'Bank / withdraw cash',
+ onInteract: ({ npc, ui, net }) => {
+ npc.say('Bank it and it’s safe — nobody takes banked cash off you, not even a bad fight.');
+ npc.emote('av-arm-flex');
+ openBankPanel({ ui, net });
+ },
+ });
+ }
+
+ return list;
+}
diff --git a/src/game/npc/npc-catalog.js b/src/game/npc/npc-catalog.js
index 95701b35b..436b8822a 100644
--- a/src/game/npc/npc-catalog.js
+++ b/src/game/npc/npc-catalog.js
@@ -17,6 +17,7 @@
import { openChat } from './npc-chat.js';
import { openAixbtTerminal } from './npc-aixbt.js';
import { openZauthScanner } from './npc-zauth.js';
+import { spawnsOfType } from '../world-zones.js';
const AVATAR_A = '/avatars/default.glb';
const AVATAR_B = '/avatars/cz.glb';
@@ -266,5 +267,51 @@ export function npcCatalogFor() {
}),
});
+ // The boutique (W03) — two physical storefronts on the 'boutique' stalls
+ // world-zones.js reserves for them. Walking up opens the real CosmeticsShop
+ // / CosmeticsWardrobe panels (server-authoritative catalog + x402 purchase +
+ // persisted equip — the same system the HUD's Shop/My Fits buttons already
+ // drive). This just gives that system a place to stand in the world instead
+ // of only a menu button. world.openShop / world.openWardrobe are bound by
+ // coincommunities.js. (Distinct from the 'vendor' stalls, which the general
+ // store/W04 economy NPCs occupy — see economy-npcs.js.)
+ const [tailorStall, fittingStall] = spawnsOfType('boutique');
+
+ if (tailorStall) {
+ list.push({
+ id: 'npc-tailor',
+ name: 'Roux · Tailor',
+ role: 'vendor',
+ avatar: AVATAR_B,
+ pos: { x: tailorStall.x, z: tailorStall.z },
+ yaw: tailorStall.yaw,
+ range: 5,
+ prompt: 'Browse the wardrobe',
+ onInteract: ({ npc, world }) => {
+ npc.say('Fresh fits, hats, and paint jobs — come take a look.');
+ npc.emote('av-call-me');
+ if (typeof world?.openShop === 'function') world.openShop();
+ },
+ });
+ }
+
+ if (fittingStall) {
+ list.push({
+ id: 'npc-fitting-room',
+ name: 'Nell · Fitting Room',
+ role: 'vendor',
+ avatar: AVATAR_A,
+ pos: { x: fittingStall.x, z: fittingStall.z },
+ yaw: fittingStall.yaw,
+ range: 5,
+ prompt: 'Open your fits',
+ onInteract: ({ npc, world }) => {
+ npc.say('Everything you already own is right here — pick your look.');
+ npc.emote('av-call-me');
+ if (typeof world?.openWardrobe === 'function') world.openWardrobe();
+ },
+ });
+ }
+
return list;
}
diff --git a/src/game/npc/npc.js b/src/game/npc/npc.js
index da405fb26..a9eb95914 100644
--- a/src/game/npc/npc.js
+++ b/src/game/npc/npc.js
@@ -24,6 +24,7 @@ const BUBBLE_MS = 4600;
const ROLE_TINT = {
vendor: 'rgba(120, 220, 160, 0.95)',
quest: 'rgba(255, 210, 120, 0.95)',
+ bank: 'rgba(230, 180, 34, 0.95)',
flavor: 'rgba(255, 255, 255, 0.92)',
};
diff --git a/src/game/npc/world-life.js b/src/game/npc/world-life.js
index 856d70df7..16bb7f840 100644
--- a/src/game/npc/world-life.js
+++ b/src/game/npc/world-life.js
@@ -16,10 +16,11 @@ import { NavGraph } from './nav-graph.js';
import { AmbientLife } from './ambient-life.js';
import { Npc } from './npc.js';
import { npcCatalogFor } from './npc-catalog.js';
+import { economyNpcsFor } from './economy-npcs.js';
import { MobSystem } from './mobs.js';
import { log } from '../../shared/log.js';
-const ROLE_RING = { vendor: 0x46d49a, quest: 0xffce6e, flavor: 0xffffff };
+const ROLE_RING = { vendor: 0x46d49a, quest: 0xffce6e, bank: 0xe6b422, flavor: 0xffffff };
export class WorldLife {
// world: { mint, name, symbol, seed, biome } — biome is the resolved env
@@ -41,8 +42,11 @@ export class WorldLife {
this.ambient = new AmbientLife({ scene, nav: this.nav, biome: world?.biome });
this.mobs = new MobSystem({ scene, nav: this.nav });
- // Interactive NPCs from the data-driven catalog.
- this.npcs = npcCatalogFor().map((def) => {
+ // Interactive NPCs from the data-driven catalog: the Agent Exchange roster
+ // (real x402 micro-services) plus the general-store clerks + bank teller
+ // (W04's off-schema cash economy, fronted by the room's own message
+ // channel — no on-chain settlement for cash, only the boutique).
+ this.npcs = [...npcCatalogFor(), ...economyNpcsFor()].map((def) => {
const npc = new Npc(scene, def);
npc.marker = this._npcMarker(def);
return npc;
diff --git a/src/game/play-systems.css b/src/game/play-systems.css
index 1abc488b9..f65052485 100644
--- a/src/game/play-systems.css
+++ b/src/game/play-systems.css
@@ -314,6 +314,13 @@
.ps-cos-card.is-equipped { border-color: #fff; background: rgba(255, 255, 255, 0.14); box-shadow: var(--cc-glow); cursor: default; }
.ps-cos-card.is-locked { opacity: 0.5; cursor: default; }
.ps-cos-card.is-locked:hover { transform: none; }
+/* A locked item with a real $THREE price is a working buy action, not a dead
+ * end (CLAUDE.md: every button/link must do something) — dim it less than an
+ * unpurchasable placeholder and restore the normal interactive affordance. */
+.ps-cos-card.is-locked[role="button"] { opacity: 0.82; cursor: pointer; }
+.ps-cos-card.is-locked[role="button"]:hover { background: rgba(255, 255, 255, 0.1); border-color: var(--cc-edge); transform: translateY(-2px); }
+.ps-cos-card.is-locked[role="button"].ps-cos-busy { opacity: 0.55; cursor: wait; pointer-events: none; }
+.ps-cos-status.ps-cos-price { color: var(--cc-text); font-weight: 700; }
.ps-cos-preview {
position: relative;
aspect-ratio: 1;
diff --git a/src/game/play-systems.js b/src/game/play-systems.js
index dc256fa7f..8581a3544 100644
--- a/src/game/play-systems.js
+++ b/src/game/play-systems.js
@@ -31,6 +31,7 @@ import { itemDisplay } from './items.js';
import {
COSMETICS, SLOTS, SLOT_LABELS, getCosmetic, DEFAULT_LOADOUT,
} from '../../multiplayer/src/cosmetics-catalog.js';
+import { buyBoutiqueItem } from './boutique-purchase.js';
import './play-systems.css';
// Rarity → display label + accent, shared by the inventory cards. Keeps the
@@ -534,14 +535,22 @@ export class PlaySystems {
}
// One wardrobe card: preview (GLB thumb or colour swatch), name, rarity, and a
- // state-appropriate action — Equipped (current), Equip (owned), or Locked (a
- // premium item not yet purchased, routed to the shop).
+ // state-appropriate action — Equipped (current), Equip (owned), or a real Buy
+ // action priced in $THREE (locked + purchasable — the W04 boutique). A locked
+ // item with no price (shouldn't happen for a premium tier, but guarded) stays
+ // inert rather than offering a dead click.
_cosmeticCard(item, { owned, isEquipped }) {
const rarity = RARITY_META[item.rarity] || RARITY_META.common;
const preview = item.thumb
? el('img', { class: 'ps-cos-thumb', src: item.thumb, alt: '', loading: 'lazy', draggable: 'false' })
: el('span', { class: 'ps-cos-swatch', style: `background:${item.swatch || '#888'}`, 'aria-hidden': 'true' });
+ const buyable = !owned && Number(item.price) > 0;
+ const statusText = isEquipped ? 'Equipped'
+ : owned ? 'Owned'
+ : buyable ? `${Number(item.price).toLocaleString()} $THREE`
+ : 'Locked';
+
const card = el('div', {
class: `ps-cos-card ${rarity.cls}${isEquipped ? ' is-equipped' : ''}${owned ? '' : ' is-locked'}`,
}, [
@@ -551,12 +560,24 @@ export class PlaySystems {
isEquipped ? el('span', { class: 'ps-cos-check', text: '✓', 'aria-hidden': 'true' }) : null,
]),
el('span', { class: 'ps-cos-name', text: item.name }),
- el('span', { class: 'ps-cos-status', text: isEquipped ? 'Equipped' : (owned ? 'Owned' : 'Locked') }),
+ el('span', { class: `ps-cos-status${buyable ? ' ps-cos-price' : ''}`, text: statusText }),
]);
if (!owned) {
- card.setAttribute('title', 'Unlock this in the shop');
- card.setAttribute('aria-disabled', 'true');
+ if (!buyable) {
+ card.setAttribute('title', 'Not yet purchasable');
+ card.setAttribute('aria-disabled', 'true');
+ return card;
+ }
+ card.setAttribute('role', 'button');
+ card.setAttribute('tabindex', '0');
+ card.setAttribute('title', `Buy ${item.name} for ${item.price} $THREE`);
+ card.setAttribute('aria-label', `Buy ${item.name} for ${item.price} $THREE`);
+ const buy = () => this._buyPremium(item, card);
+ card.addEventListener('click', buy);
+ card.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); buy(); }
+ });
return card;
}
// Owned + not equipped → clickable to equip. Equipped → inert (use Remove).
@@ -575,6 +596,35 @@ export class PlaySystems {
return card;
}
+ // Buy a locked premium cosmetic with $THREE (W04 boutique): connect wallet →
+ // server-priced quote → sign → broadcast → the server re-verifies the
+ // confirmed transaction on-chain before granting anything. A fresh 'profile'
+ // snapshot (sent by the server on a successful grant) re-renders this panel
+ // with the item now owned — no optimistic local mutation.
+ async _buyPremium(item, card) {
+ if (!this.net || card?.classList.contains('ps-cos-busy')) return;
+ card?.classList.add('ps-cos-busy');
+ const stageText = {
+ connecting: 'Connecting your wallet…',
+ pricing: 'Pricing the purchase…',
+ signing: 'Approve the purchase in your wallet…',
+ broadcasting: 'Submitting on-chain…',
+ settling: 'Confirming your unlock…',
+ };
+ try {
+ const res = await buyBoutiqueItem({
+ net: this.net,
+ item,
+ onStage: (stage) => { if (stageText[stage]) this.ui?.toast?.(stageText[stage], 'info'); },
+ });
+ this.ui?.toast?.(res.text || `Unlocked ${item.name}.`, 'success');
+ } catch (err) {
+ this.ui?.toast?.(err?.message || `Could not buy ${item.name}.`, 'warn');
+ } finally {
+ card?.classList.remove('ps-cos-busy');
+ }
+ }
+
// Send the equip intent. The server validates ownership, persists the loadout to
// the account, re-broadcasts it to peers and echoes a fresh profile — which flows
// back through setProfile and re-renders this panel, so we don't mutate optimistically
diff --git a/src/game/world-zones.js b/src/game/world-zones.js
index b4044abe0..c6d2f780d 100644
--- a/src/game/world-zones.js
+++ b/src/game/world-zones.js
@@ -108,6 +108,17 @@ export const SPAWN_POINTS = [
{ id: 'vendor-ne', type: 'vendor', x: 44, z: -44, yaw: -Math.PI * 0.75, zone: 'streets' },
{ id: 'vendor-sw', type: 'vendor', x: -44, z: 44, yaw: Math.PI * 0.25, zone: 'streets' },
+ // The bank/ATM (W04) — one teller on the Downtown plaza, close enough to
+ // spawn that a fresh player finds it without a hike, clear of both the
+ // Agent Exchange roster (x ≈ -16..16) and the vendor stalls above.
+ { id: 'atm-downtown', type: 'atm', x: 0, z: -30, yaw: Math.PI, zone: 'downtown' },
+
+ // Cosmetics boutique storefronts (W03) — mirrors the vendor stalls onto the
+ // ring's other diagonal so the general-store clerks (vendor-ne/sw) and the
+ // boutique never share a spot.
+ { id: 'boutique-se', type: 'boutique', x: 44, z: 44, yaw: Math.PI * 0.75, zone: 'streets' },
+ { id: 'boutique-nw', type: 'boutique', x: -44, z: -44, yaw: -Math.PI * 0.25, zone: 'streets' },
+
// Race start grid down the dock front (race / mission briefs).
{ id: 'race-dock-1', type: 'race-grid', x: 150, z: -10, yaw: Math.PI, zone: 'docks' },
{ id: 'race-dock-2', type: 'race-grid', x: 150, z: 0, yaw: Math.PI, zone: 'docks' },
diff --git a/src/minted.js b/src/minted.js
index 78fddc54f..557ba9199 100644
--- a/src/minted.js
+++ b/src/minted.js
@@ -251,7 +251,7 @@ function setFeedLive(stateName) {
if (!head.previousElementSibling?.classList?.contains('juice-live')) {
head.insertAdjacentHTML('beforebegin', liveDot(stateName));
} else {
- setLiveDot(head.previousElementSibling, stateName);
+ setLiveDot(head.previousElementSibling, stateName, stateName);
}
}
diff --git a/tests/api/agent-oembed.test.js b/tests/api/agent-oembed.test.js
new file mode 100644
index 000000000..3f784695a
--- /dev/null
+++ b/tests/api/agent-oembed.test.js
@@ -0,0 +1,113 @@
+// GET /api/oembed — the shared oEmbed provider for agents, on-chain agents,
+// and (roadmap prompt 10) Forge 3D creations. Exercises the real handler with
+// the DB and on-chain resolver mocked, so this is a real orchestration/contract
+// test, not a mock of the thing under test.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';
+
+const sqlState = { queue: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),
+}));
+
+vi.mock('../../api/_lib/onchain.js', () => ({
+ resolveOnChainAgent: vi.fn(async () => ({ name: 'Onchain Hero' })),
+ SERVER_CHAIN_META: { 8453: { name: 'Base', short: 'BASE', testnet: false } },
+}));
+
+const { default: handler } = await import('../../api/agent-oembed.js');
+
+function makeReq(url) {
+ const stream = Readable.from([]);
+ stream.method = 'GET';
+ stream.url = url;
+ stream.headers = { host: 'three.ws' };
+ return stream;
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(chunk) { if (chunk !== undefined) this.body += String(chunk); this.writableEnded = true; },
+ };
+}
+async function get(target, extra = '') {
+ const res = makeRes();
+ await handler(makeReq(`/api/oembed?url=${encodeURIComponent(target)}${extra}`), res);
+ let parsed = null;
+ try { parsed = res.body ? JSON.parse(res.body) : null; } catch { parsed = res.body; }
+ return { res, status: res.statusCode, body: parsed };
+}
+
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+const CREATION_ID = '22222222-2222-4222-8222-222222222222';
+
+beforeEach(() => {
+ sqlState.queue = [];
+});
+
+describe('agent target', () => {
+ it('resolves /agent/:id into a rich oEmbed payload', async () => {
+ sqlState.queue = [[{ id: AGENT_ID, name: 'Nova', description: 'guide', avatar_id: null }]];
+ const { status, body } = await get(`https://three.ws/agent/${AGENT_ID}`);
+ expect(status).toBe(200);
+ expect(body.type).toBe('rich');
+ expect(body.title).toBe('Nova');
+ expect(body.html).toContain(`https://three.ws/agent/${AGENT_ID}/embed`);
+ });
+});
+
+describe('Forge creation target (roadmap prompt 10)', () => {
+ it('resolves /forge/share/:id into a rich oEmbed payload pointing at /forge/embed', async () => {
+ sqlState.queue = [[{ id: CREATION_ID, prompt: 'a robot', status: 'done', glb_url: 'https://cdn.test/m.glb' }]];
+ const { status, body } = await get(`https://three.ws/forge/share/${CREATION_ID}`);
+ expect(status).toBe(200);
+ expect(body.type).toBe('rich');
+ expect(body.title).toBe('a robot');
+ expect(body.provider_name).toBe('three.ws');
+ expect(body.html).toContain('https://three.ws/forge/embed?src=');
+ expect(body.html).toContain(encodeURIComponent('https://cdn.test/m.glb'));
+ expect(body.thumbnail_url).toBe(`https://three.ws/api/forge-og?id=${CREATION_ID}`);
+ });
+
+ it('returns XML when format=xml is requested', async () => {
+ sqlState.queue = [[{ id: CREATION_ID, prompt: null, status: 'done', glb_url: 'https://cdn.test/m.glb' }]];
+ const { status, res } = await get(`https://three.ws/forge/share/${CREATION_ID}`, '&format=xml');
+ expect(status).toBe(200);
+ expect(res.headers['content-type']).toContain('text/xml');
+ expect(res.body).toContain('<oembed>');
+ expect(res.body).toContain('Forged creation'); // fallback title when prompt is null
+ });
+
+ it('404s a creation that is still generating (never partial)', async () => {
+ sqlState.queue = [[{ id: CREATION_ID, prompt: 'wip', status: 'generating', glb_url: null }]];
+ const { status } = await get(`https://three.ws/forge/share/${CREATION_ID}`);
+ expect(status).toBe(404);
+ });
+
+ it('404s an unknown creation id', async () => {
+ sqlState.queue = [[]];
+ const { status } = await get(`https://three.ws/forge/share/${CREATION_ID}`);
+ expect(status).toBe(404);
+ });
+
+ it('does not treat a non-uuid path segment as a forge id', async () => {
+ const { status } = await get('https://three.ws/forge/share/not-a-uuid');
+ expect(status).toBe(404); // falls through to "not a recognised agent url" (no agent match either)
+ });
+});
+
+describe('unrecognised target', () => {
+ it('404s a URL that matches no known share route', async () => {
+ const { status, body } = await get('https://three.ws/nowhere');
+ expect(status).toBe(404);
+ expect(body.error_description || body.error).toBeTruthy();
+ });
+});
diff --git a/tests/api/mcp-embed.test.js b/tests/api/mcp-embed.test.js
index f725c866e..a0f564b27 100644
--- a/tests/api/mcp-embed.test.js
+++ b/tests/api/mcp-embed.test.js
@@ -200,14 +200,21 @@ describe('on-chain agent embed', () => {
// ── Forge creation embed ─────────────────────────────────────────────────────
describe('forge creation embed', () => {
it('returns a forge embed snippet for a finished creation', async () => {
- sqlState.queue = [[{ id: CREATION_ID, status: 'done', glb_url: 'https://cdn.test/m.glb' }]];
+ sqlState.queue = [[{ id: CREATION_ID, status: 'done', glb_url: 'https://cdn.test/m.glb', prompt: 'a robot' }]];
const { body } = await invoke(call({ creation_id: CREATION_ID, height: 540 }));
const sc = body.result.structuredContent;
expect(sc.ok).toBe(true);
- expect(sc.embed_html).toContain(`https://three.ws/forge?share=${CREATION_ID}`);
+ // The lightweight /forge/embed viewer (AR-capable, zero-dependency) — not
+ // the full /forge app — so an <iframe src=embed_html> stays small.
+ expect(sc.embed_html).toContain('https://three.ws/forge/embed?src=');
+ expect(sc.embed_html).toContain(encodeURIComponent('https://cdn.test/m.glb'));
expect(sc.embed_html).toContain('height="540"');
expect(sc.share_url).toBe(`https://three.ws/forge/share/${CREATION_ID}`);
- expect(sc.oembed_url).toBeNull();
+ // /api/oembed now resolves /forge/share/:id (extractForgeId), so Forge
+ // creations get a real oEmbed URL like every other embeddable target.
+ expect(sc.oembed_url).toBe(
+ `https://three.ws/api/oembed?url=${encodeURIComponent(`https://three.ws/forge/share/${CREATION_ID}`)}`,
+ );
});
it('rejects a still-generating creation with a designed error', async () => {
diff --git a/tests/api/mcp-register-agent.test.js b/tests/api/mcp-register-agent.test.js
index 54cebcc60..0e2822ec4 100644
--- a/tests/api/mcp-register-agent.test.js
+++ b/tests/api/mcp-register-agent.test.js
@@ -69,6 +69,12 @@ vi.mock('../../api/_lib/identity-integrity.js', () => ({
checkIdentityIntegrity: vi.fn(async () => identityState.result),
}));
+// ── Audit log (attach_avatar_to_agent) ────────────────────────────────────────
+const auditLog = vi.fn();
+vi.mock('../../api/_lib/audit.js', () => ({
+ logAudit: (...args) => auditLog(...args),
+}));
+
// ── Import AFTER mocks ────────────────────────────────────────────────────────
const { toolDefs } = await import('../../api/_mcp/tools/agents.js');
const onchain = await import('../../api/_lib/onchain-deploy.js');
@@ -299,3 +305,91 @@ describe('identity_check', () => {
expect(out(res).status).toBe('validation_error');
});
});
+
+// ── attach_avatar_to_agent ──────────────────────────────────────────────────────
+describe('attach_avatar_to_agent', () => {
+ const AVATAR_ID = '33333333-3333-4333-8333-333333333333';
+
+ beforeEach(() => {
+ auditLog.mockClear();
+ });
+
+ it('exposes attach_avatar_to_agent (agents:write)', () => {
+ expect(TOOLS.attach_avatar_to_agent).toBeDefined();
+ expect(TOOLS.attach_avatar_to_agent.scope).toBe('agents:write');
+ });
+
+ it('rejects an x402/null-user caller with a designed sign-in state', async () => {
+ const res = await TOOLS.attach_avatar_to_agent.handler(
+ { agent_id: AGENT_ID, avatar_id: AVATAR_ID },
+ { userId: null, rateKey: 'x402:wallet', scope: '', source: 'x402' },
+ );
+ expect(res.isError).toBe(true);
+ expect(out(res).status).toBe('sign_in_required');
+ expect(sqlState.calls.length).toBe(0);
+ });
+
+ it('rejects a non-uuid agent_id / avatar_id with a validation error', async () => {
+ const res1 = await TOOLS.attach_avatar_to_agent.handler({ agent_id: 'nope', avatar_id: AVATAR_ID }, ownerAuth());
+ expect(res1.isError).toBe(true);
+ expect(out(res1).status).toBe('validation_error');
+
+ const res2 = await TOOLS.attach_avatar_to_agent.handler({ agent_id: AGENT_ID, avatar_id: 'nope' }, ownerAuth());
+ expect(res2.isError).toBe(true);
+ expect(out(res2).status).toBe('validation_error');
+ });
+
+ it('rejects attaching to another account’s agent (ownership check)', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: 'someone-else', name: 'X', avatar_id: null }]);
+ const res = await TOOLS.attach_avatar_to_agent.handler({ agent_id: AGENT_ID, avatar_id: AVATAR_ID }, ownerAuth());
+ expect(res.isError).toBe(true);
+ expect(out(res).status).toBe('forbidden');
+ });
+
+ it('rejects an avatar not owned by the caller (or missing)', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Mine', avatar_id: null }]); // agent lookup
+ sqlState.queue.push([]); // avatar lookup — none owned
+ const res = await TOOLS.attach_avatar_to_agent.handler({ agent_id: AGENT_ID, avatar_id: AVATAR_ID }, ownerAuth());
+ expect(res.isError).toBe(true);
+ expect(out(res).status).toBe('not_found');
+ });
+
+ it('attaches an owned avatar to an owned agent and logs the audit entry', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Mine', avatar_id: null }]); // agent lookup
+ sqlState.queue.push([{ id: AVATAR_ID, name: 'Robo', storage_key: 'k', visibility: 'private' }]); // avatar lookup
+ sqlState.queue.push([{ id: AGENT_ID, name: 'Mine', avatar_id: AVATAR_ID, wallet_address: 'W1', meta: {} }]); // UPDATE ... RETURNING
+
+ const res = await TOOLS.attach_avatar_to_agent.handler({ agent_id: AGENT_ID, avatar_id: AVATAR_ID }, ownerAuth());
+ const o = out(res);
+ expect(res.isError).toBeUndefined();
+ expect(o.status).toBe('attached');
+ expect(o.agent_id).toBe(AGENT_ID);
+ expect(o.avatar_id).toBe(AVATAR_ID);
+ expect(o.avatar_name).toBe('Robo');
+ expect(o.already_onchain).toBe(false);
+ expect(o.next_steps.some((s) => s.includes('register_agent'))).toBe(true);
+ expect(o.next_steps.some((s) => s.includes('anchor_provenance'))).toBe(true);
+ expect(auditLog).toHaveBeenCalledOnce();
+ expect(auditLog.mock.calls[0][0]).toMatchObject({ userId: UID, action: 'attach_avatar_to_agent', resourceId: AGENT_ID });
+ });
+
+ it('reports already_onchain and skips register_agent in next_steps when the agent is already registered', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Mine', avatar_id: null }]);
+ sqlState.queue.push([{ id: AVATAR_ID, name: 'Robo', storage_key: 'k', visibility: 'private' }]);
+ sqlState.queue.push([
+ {
+ id: AGENT_ID,
+ name: 'Mine',
+ avatar_id: AVATAR_ID,
+ wallet_address: 'W1',
+ meta: { agent_registry: { identity_pda: 'PDA1' } },
+ },
+ ]);
+
+ const res = await TOOLS.attach_avatar_to_agent.handler({ agent_id: AGENT_ID, avatar_id: AVATAR_ID }, ownerAuth());
+ const o = out(res);
+ expect(o.already_onchain).toBe(true);
+ expect(o.next_steps.some((s) => s.includes('register_agent'))).toBe(false);
+ expect(o.next_steps.some((s) => s.includes('anchor_provenance'))).toBe(true);
+ });
+});
diff --git a/tests/e2e/forge-embed-panel.spec.js b/tests/e2e/forge-embed-panel.spec.js
new file mode 100644
index 000000000..7bc6ef38e
--- /dev/null
+++ b/tests/e2e/forge-embed-panel.spec.js
@@ -0,0 +1,148 @@
+/**
+ * Forge — "Embed this model" panel. Playwright e2e.
+ *
+ * Roadmap prompt 10 (agent-native 3D + embeddable distribution): the Forge
+ * result bar's Embed button opens a real panel with five distribution
+ * flavours — iframe, web component, <agent-3d>, page-agent, and walk
+ * companion. Drives the real /forge page + the real panel module
+ * (src/forge-embed-panel.js / src/forge-embed-snippets.js); only the backend
+ * generation call is fulfilled at the route layer (same pattern as
+ * tests/e2e/forge-text-to-3d.spec.js) so the page's own real fetches, real DOM,
+ * and real snippet builders are what's under test.
+ */
+
+import { test, expect } from '@playwright/test';
+
+const RESULT_GLB = '/avatars/default.glb';
+
+const CATALOG = {
+ backends: [
+ {
+ id: 'nvidia',
+ label: 'NVIDIA NIM',
+ blurb: 'Free, fast text-to-3D',
+ configured: true,
+ free: true,
+ byok: null,
+ paths: ['image'],
+ poly_control: false,
+ user_images: true,
+ estimates: { image: [{ tier: 'draft', eta_seconds: 18, credits: 0 }] },
+ },
+ ],
+ tiers: [{ id: 'draft', label: 'Draft', polycount: 50000 }],
+ default_backend: { image: 'nvidia', geometry: 'nvidia' },
+ default_backend_for_tier: { draft: { image: 'nvidia', geometry: 'nvidia' } },
+};
+
+const HEALTH = { backends: { nvidia: { status: 'up', message: '' } } };
+
+const DONE = {
+ job_id: null,
+ status: 'done',
+ glb_url: RESULT_GLB,
+ creation_id: 'e2e-forge-embed-1',
+ backend: 'nvidia',
+ tier: 'draft',
+ path: 'image',
+};
+
+async function installForge(page) {
+ await page.route(
+ (url) => url.pathname === '/api/forge',
+ async (route) => {
+ const req = route.request();
+ const url = new URL(req.url());
+ if (req.method() === 'GET' && url.searchParams.get('catalog')) return route.fulfill({ json: CATALOG });
+ if (req.method() === 'GET' && url.searchParams.get('health')) return route.fulfill({ json: HEALTH });
+ if (req.method() === 'POST') return route.fulfill({ json: DONE });
+ return route.fulfill({ json: {} });
+ },
+ );
+ await page.route((url) => url.pathname === '/api/forge-gallery', (r) => r.fulfill({ json: { enabled: false, creations: [] } }));
+ for (const p of ['/api/forge-feedback', '/api/forge-categorize', '/api/forge-poster']) {
+ await page.route((url) => url.pathname === p, (r) => r.fulfill({ json: { ok: true } }));
+ }
+}
+
+async function generateAndOpenEmbed(page) {
+ await installForge(page);
+ await page.goto('/forge');
+ const freeEngine = page.locator('#engine button', { has: page.locator('.eng-free') });
+ await expect(freeEngine).toBeVisible({ timeout: 30_000 });
+ await freeEngine.click();
+ await page.locator('textarea#prompt').fill('a small ceramic mug');
+ await page.locator('#generate').click();
+ await expect(page.locator('#state-result')).toBeVisible({ timeout: 60_000 });
+
+ const embedBtn = page.locator('#forge-embed-btn');
+ await expect(embedBtn).toBeVisible();
+ await embedBtn.click();
+}
+
+test.describe('Forge — embed this model panel', () => {
+ test('opens with the iframe tab and a real /forge/embed snippet', async ({ page }) => {
+ test.setTimeout(120_000);
+ await generateAndOpenEmbed(page);
+
+ const code = page.locator('#tws-emb-code');
+ await expect(code).toBeVisible();
+ await expect(code).toHaveValue(/<iframe/);
+ await expect(code).toHaveValue(/\/forge\/embed\?src=/);
+ // The live preview iframe actually points at the same viewer route.
+ await expect(page.locator('.tws-emb-frame')).toHaveAttribute('src', /\/forge-embed\.html\?src=/);
+ });
+
+ test('page-agent tab renders the real AvatarStage/SpeechNarrator snippet', async ({ page }) => {
+ test.setTimeout(120_000);
+ await generateAndOpenEmbed(page);
+
+ await page.locator('.tws-emb-tab[data-tab="page-agent"]').click();
+ const code = page.locator('#tws-emb-code');
+ await expect(code).toHaveValue(/@three-ws\/page-agent/);
+ await expect(code).toHaveValue(/AvatarStage, SpeechNarrator/);
+ await expect(code).toHaveValue(/stage\.load\(/);
+ await expect(page.locator('.tws-emb-foot')).toContainText(/talking, lipsync guide/i);
+ });
+
+ test('walk companion tab renders the real createWalkCompanion snippet', async ({ page }) => {
+ test.setTimeout(120_000);
+ await generateAndOpenEmbed(page);
+
+ await page.locator('.tws-emb-tab[data-tab="walk"]').click();
+ const code = page.locator('#tws-emb-code');
+ await expect(code).toHaveValue(/@three-ws\/walk/);
+ await expect(code).toHaveValue(/createWalkCompanion/);
+ await expect(code).toHaveValue(/source: 'static'/);
+ await expect(code).toHaveValue(/rig: 'shared'/);
+ await expect(page.locator('.tws-emb-foot')).toContainText(/corner companion/i);
+ });
+
+ test('agent-3d tab is still wired (regression: 5 tabs, none broken by the new two)', async ({ page }) => {
+ test.setTimeout(120_000);
+ await generateAndOpenEmbed(page);
+
+ await page.locator('.tws-emb-tab[data-tab="agent3d"]').click();
+ await expect(page.locator('#tws-emb-code')).toHaveValue(/<agent-3d/);
+
+ await page.locator('.tws-emb-tab[data-tab="component"]').click();
+ await expect(page.locator('#tws-emb-code')).toHaveValue(/<model-viewer/);
+
+ // All five tabs are present and clickable.
+ const tabs = page.locator('.tws-emb-tab');
+ await expect(tabs).toHaveCount(5);
+ });
+
+ test('copy button copies the currently active tab\'s snippet', async ({ page, context }) => {
+ test.setTimeout(120_000);
+ await context.grantPermissions(['clipboard-read', 'clipboard-write']);
+ await generateAndOpenEmbed(page);
+
+ await page.locator('.tws-emb-tab[data-tab="walk"]').click();
+ await page.locator('[data-emb-copy]').click();
+ await expect(page.locator('.tws-emb-copy-label')).toHaveText(/Copied/, { timeout: 5000 });
+
+ const clip = await page.evaluate(() => navigator.clipboard.readText());
+ expect(clip).toContain('createWalkCompanion');
+ });
+});
diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.json
index c3506a98c..15d5fbf59 100644
--- a/tests/fixtures/mcp-golden-tools.json
+++ b/tests/fixtures/mcp-golden-tools.json
@@ -50,6 +50,19 @@
}
],
"api/_mcp/tools/agents.js": [
+ {
+ "name": "attach_avatar_to_agent",
+ "title": "Give an agent a body",
+ "descHead": "dynamic",
+ "descHash": "dynamic",
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ },
+ "schemaHash": "dd77553eb26e"
+ },
{
"name": "call_agent",
"title": "Call agent",
diff --git a/tests/src/forge-embed-snippets.test.js b/tests/src/forge-embed-snippets.test.js
new file mode 100644
index 000000000..9d5e131a2
--- /dev/null
+++ b/tests/src/forge-embed-snippets.test.js
@@ -0,0 +1,94 @@
+// src/forge-embed-snippets.js — the shared, pure snippet builders behind the
+// Forge "Embed this model" panel and (roadmap prompt 10) the "Add to your
+// agent/site" flow. Pure string/URL assembly, no DOM — safe to unit test and
+// to import from a Node script (examples/agent-native-3d/run.mjs does exactly
+// that, so these contracts are load-bearing for more than the browser panel).
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildIframeSnippet,
+ buildWebComponentSnippet,
+ buildAgentThreeDSnippet,
+ buildPageAgentSnippet,
+ buildWalkCompanionSnippet,
+ embedPageUrl,
+ absoluteGlb,
+} from '../../src/forge-embed-snippets.js';
+
+const GLB = 'https://cdn.test/robot.glb';
+const TITLE = 'A friendly robot';
+
+describe('embedPageUrl', () => {
+ it('points at the lightweight /forge/embed viewer, not the full app', () => {
+ const url = embedPageUrl(GLB, TITLE);
+ // URLSearchParams (not encodeURIComponent) does the encoding — spaces become
+ // "+", matching how api/_lib/embed.js's forgeEmbedTarget builds the same URL.
+ expect(url).toBe(`https://three.ws/forge/embed?${new URLSearchParams({ src: GLB, title: TITLE })}`);
+ });
+});
+
+describe('absoluteGlb', () => {
+ it('resolves a relative path against the prod origin', () => {
+ expect(absoluteGlb('/forge/abc.glb')).toBe('https://three.ws/forge/abc.glb');
+ });
+ it('passes an already-absolute URL through unchanged', () => {
+ expect(absoluteGlb(GLB)).toBe(GLB);
+ });
+});
+
+describe('buildIframeSnippet / buildWebComponentSnippet / buildAgentThreeDSnippet', () => {
+ it('all embed the same GLB URL and a sane title fallback', () => {
+ const iframe = buildIframeSnippet(GLB, '', 'wide');
+ const component = buildWebComponentSnippet(GLB, '', 'wide');
+ const agent3d = buildAgentThreeDSnippet(GLB, '', 'wide');
+ expect(iframe).toContain('<iframe');
+ expect(iframe).toContain(encodeURIComponent(GLB));
+ expect(component).toContain(GLB);
+ expect(component).toContain('<model-viewer');
+ expect(agent3d).toContain(GLB);
+ expect(agent3d).toContain('<agent-3d');
+ expect(agent3d).toContain('viewer');
+ });
+});
+
+describe('buildPageAgentSnippet — "add to your agent"', () => {
+ it('uses the real @three-ws/page-agent AvatarStage/SpeechNarrator custom-avatar contract', () => {
+ const snippet = buildPageAgentSnippet(GLB, TITLE);
+ expect(snippet).toContain("import { AvatarStage, SpeechNarrator } from '@three-ws/page-agent'");
+ expect(snippet).toContain(`stage.load('${GLB}'`);
+ expect(snippet).toContain('new SpeechNarrator(stage)');
+ expect(snippet).toContain(TITLE);
+ });
+
+ it('falls back to a sane default title when none is given', () => {
+ const snippet = buildPageAgentSnippet(GLB, '');
+ expect(snippet).toContain('Your agent');
+ });
+
+ it('escapes HTML-unsafe characters in the title', () => {
+ const snippet = buildPageAgentSnippet(GLB, '<script>alert(1)</script>');
+ expect(snippet).not.toContain('<script>alert(1)</script>');
+ expect(snippet).toContain('&lt;script&gt;');
+ });
+});
+
+describe('buildWalkCompanionSnippet — "add to your site"', () => {
+ it('uses the real @three-ws/walk createWalkCompanion custom-roster contract', () => {
+ const snippet = buildWalkCompanionSnippet(GLB, TITLE);
+ expect(snippet).toContain("import { createWalkCompanion } from '@three-ws/walk'");
+ expect(snippet).toContain(`asset: '${GLB}'`);
+ // Absolute-URL roster entries use source:'static' (resolveAvatarUrl in
+ // walk-sdk/src/roster.js passes an absolute asset URL through untouched) —
+ // source:'api' would instead resolve against /api/avatars/<id>/glb, which
+ // only works for a platform avatar id, not an arbitrary GLB URL.
+ expect(snippet).toContain("source: 'static'");
+ expect(snippet).toContain("rig: 'shared'");
+ expect(snippet).toContain('walk.bootstrap()');
+ expect(snippet).toContain(TITLE);
+ });
+
+ it('falls back to a sane default title when none is given', () => {
+ const snippet = buildWalkCompanionSnippet(GLB, '');
+ expect(snippet).toContain('Your avatar');
+ });
+});
diff --git a/vercel.json b/vercel.json
index dd7979373..a879b6fad 100644
--- a/vercel.json
+++ b/vercel.json
@@ -825,6 +825,10 @@
"src": "/minted/?",
"dest": "/minted.html"
},
+ {
+ "src": "/creations/?",
+ "dest": "/creations.html"
+ },
{
"src": "/pulse/?",
"dest": "/pulse.html"
diff --git a/vite.config.js b/vite.config.js
index e82af7742..d3ee0df4a 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -405,6 +405,7 @@ const appConfig = {
guardian: resolve(__dirname, 'pages/guardian.html'),
launches: resolve(__dirname, 'pages/launches.html'),
minted: resolve(__dirname, 'pages/minted.html'),
+ creations: resolve(__dirname, 'pages/creations.html'),
pulse: resolve(__dirname, 'pages/pulse.html'),
diorama: resolve(__dirname, 'pages/diorama.html'),
'x402-revenue': resolve(__dirname, 'pages/x402-revenue.html'),
@@ -919,6 +920,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/launches/': resolve(root, 'pages/launches.html'),
'/minted': resolve(root, 'pages/minted.html'),
'/minted/': resolve(root, 'pages/minted.html'),
+ '/creations': resolve(root, 'pages/creations.html'),
+ '/creations/': resolve(root, 'pages/creations.html'),
'/pulse': resolve(root, 'pages/pulse.html'),
'/pulse/': resolve(root, 'pages/pulse.html'),
'/x402-revenue': resolve(root, 'pages/x402-revenue.html'),