Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance NPC interactions and world economy descriptions
nirholas7efe15e43622
diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.jsindex a7b3146e6..527ba6bad 100644--- a/api/x402/crypto-intel.js+++ b/api/x402/crypto-intel.js@@ -10,7 +10,7 @@// Response: { topic, headline, signal, price_usd?, change_24h?,// rationale, confidence, ts }//-// Data is live: CoinGecko public API first, Binance 24h ticker as fallback+// Data is live: CoinGecko public API first, Coinbase 24h stats as fallback// (both keyless). CoinGecko's shared-IP quota rate-limits Vercel egress often;// the fallback keeps paid calls answering with real data. No mock path — if// both sources fail the call 503s before settlement and the buyer isn't charged.@@ -114,22 +114,23 @@ async function fetchLivePrice(coinId) {// Reverse of ALIASES so a CoinGecko id resolves back to its exchange ticker.const TICKER_BY_ID = Object.fromEntries(Object.entries(ALIASES).map(([t, id]) => [id, t]));-// Binance public 24h ticker — keyless with per-IP limits generous enough that-// shared serverless egress doesn't trip them. USDT-quoted, so prices track USD.-async function fetchBinance24h(topic, coinId) {+// Coinbase Exchange public 24h stats — keyless and reachable from US egress+// (Binance 451-blocks US IPs, where Vercel functions run). The 24h change is+// derived from the trailing-window open→last, same signal CoinGecko reports.+async function fetchCoinbase24h(topic, coinId) {const ticker = ALIASES[topic] ? topic: TICKER_BY_ID[coinId] || (/^[a-z0-9]{2,10}$/.test(topic) ? topic : null);if (!ticker) return null;const r = await fetch(- `https://api.binance.com/api/v3/ticker/24hr?symbol=${ticker.toUpperCase()}USDT`,- { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(6000) },+ `https://api.exchange.coinbase.com/products/${ticker.toUpperCase()}-USD/stats`,+ { headers: { Accept: 'application/json', 'User-Agent': 'three.ws' }, signal: AbortSignal.timeout(6000) },);if (!r.ok) return null;const d = await r.json();- const price = Number(d.lastPrice);- const change = Number(d.priceChangePercent);- if (!Number.isFinite(price) || !Number.isFinite(change)) return null;- return { price_usd: price, change_24h: change };+ const open = Number(d.open);+ const last = Number(d.last);+ if (!Number.isFinite(open) || !Number.isFinite(last) || open <= 0) return null;+ return { price_usd: last, change_24h: ((last - open) / open) * 100 };}function buildSignal(topic, price, change) {@@ -212,7 +213,7 @@ export default paidEndpoint({let live = null;try { live = await fetchLivePrice(coinId); } catch { /* try fallback source */ }if (!live || live.change_24h == null) {- try { live = await fetchBinance24h(topic, coinId); } catch { /* refund below */ }+ try { live = await fetchCoinbase24h(topic, coinId); } catch { /* refund below */ }}if (!live || live.change_24h == null) {diff --git a/data/changelog.json b/data/changelog.jsonindex 0a2ede66c..53dbe2fe5 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,10 +1,19 @@{"$comment": "Curated changelog entries for three.ws \u2014 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-02",+ "title": "Every coin world now gets the full town experience",+ "summary": "The flagship town's whole cast and economy now travel to every coin world on /play. Walk into any community and you'll find the full crew of twelve townsfolk selling real paid services \u2014 market reads, fact checks, security scans, vanity addresses, 3D mesh forging, coin launches and more, each settled on-chain in USDC \u2014 plus the ORACLE and NOVA agent exchange striking live x402 deals in the plaza, and an intel kiosk selling live market data for that world's own coin ($0.01 USDC, paid from your own wallet). The $THREE town keeps its signature frontier look and stays the front door of the metaverse.",+ "tags": [+ "feature"+ ],+ "link": "/play"+ },{"date": "2026-07-02","title": "Agent wallet creation and vanity addresses restored",- "summary": "Creating an agent's custodial Solana wallet — including grinding a custom vanity address — was failing with a server error. The platform's dedicated at-rest encryption key had gone missing from the production environment, and the wallet layer correctly refuses to encrypt a new custodial key without it rather than fall back to a weaker key. The key is restored, and the encryption layer now also keeps wallets written under the older key readable after a key change, so wallet creation, vanity addresses, and withdrawals all work again. No funds were ever at risk or moved.",+ "summary": "Creating an agent's custodial Solana wallet \u2014 including grinding a custom vanity address \u2014 was failing with a server error. The platform's dedicated at-rest encryption key had gone missing from the production environment, and the wallet layer correctly refuses to encrypt a new custodial key without it rather than fall back to a weaker key. The key is restored, and the encryption layer now also keeps wallets written under the older key readable after a key change, so wallet creation, vanity addresses, and withdrawals all work again. No funds were ever at risk or moved.","tags": ["fix","security"@@ -14,7 +23,7 @@{"date": "2026-07-02","title": "Oracle coin pages now show full live market data",- "summary": "Open any coin in the Oracle and you now get its complete live market picture next to the conviction score — real-time price with 5-minute, 1-hour, 6-hour and 24-hour changes, market cap, fully-diluted value, liquidity, 24-hour volume, holder count and supply. Pre-graduation pump.fun coins show a bonding-curve progress bar; graduated coins show their all-time-high market cap. A security panel flags whether the mint and freeze authorities are revoked, whether metadata is locked, any transfer tax, and top-10 holder concentration. Listed coins add their CoinGecko rank plus all-time high and low, and every coin lists its live DEX markets and social links. It's fused in real time from DexScreener, pump.fun, GeckoTerminal, GoPlus, Birdeye and CoinGecko, with graceful fallback if any single source is down.",+ "summary": "Open any coin in the Oracle and you now get its complete live market picture next to the conviction score \u2014 real-time price with 5-minute, 1-hour, 6-hour and 24-hour changes, market cap, fully-diluted value, liquidity, 24-hour volume, holder count and supply. Pre-graduation pump.fun coins show a bonding-curve progress bar; graduated coins show their all-time-high market cap. A security panel flags whether the mint and freeze authorities are revoked, whether metadata is locked, any transfer tax, and top-10 holder concentration. Listed coins add their CoinGecko rank plus all-time high and low, and every coin lists its live DEX markets and social links. It's fused in real time from DexScreener, pump.fun, GeckoTerminal, GoPlus, Birdeye and CoinGecko, with graceful fallback if any single source is down.","tags": ["feature","improvement"@@ -24,7 +33,7 @@{"date": "2026-07-02","title": "Agents can trade graduated coins from their own wallet",- "summary": "When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it — every buy came back \"this coin has graduated, not supported.\" Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling.",+ "summary": "When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it \u2014 every buy came back \"this coin has graduated, not supported.\" Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling.","tags": ["fix","improvement"@@ -34,7 +43,7 @@{"date": "2026-07-02","title": "Oracle 3D graph is visible again",- "summary": "The Oracle's 3D conviction graph — every scored coin as a sphere you can orbit, with size showing the conviction score and brightness showing the tier — was rendering as a black void: the spheres were lit only by a near-black ambient light and carried no glow of their own, so nothing showed even though the data was loading fine. Each coin now self-illuminates in its tier color and feeds the bloom pass, with real key and rim lighting giving the spheres depth. Prime coins burn brightest, and the whole constellation reads clearly against the dark backdrop. Open it from the Oracle's \"3D graph\" tab.",+ "summary": "The Oracle's 3D conviction graph \u2014 every scored coin as a sphere you can orbit, with size showing the conviction score and brightness showing the tier \u2014 was rendering as a black void: the spheres were lit only by a near-black ambient light and carried no glow of their own, so nothing showed even though the data was loading fine. Each coin now self-illuminates in its tier color and feeds the bloom pass, with real key and rim lighting giving the spheres depth. Prime coins burn brightest, and the whole constellation reads clearly against the dark backdrop. Open it from the Oracle's \"3D graph\" tab.","tags": ["fix"],@@ -43,15 +52,15 @@{"date": "2026-07-02","title": "Coin intelligence engine now backs off cleanly when the database is full",- "summary": "The pump.fun intelligence firehose — the engine behind the coin-intel feed, the smart-money leaderboard and the oracle scores — used to keep writing to the database even after it hit its storage cap, failing thousands of times an hour and burning compute on work that could never be saved. It now checks free space before each run and pauses ingestion while the automatic cleanup reclaims room, then resumes on its own. The result: the engine self-heals instead of storming its logs, and the feeds it powers recover cleanly the moment space frees up.",+ "summary": "The pump.fun intelligence firehose \u2014 the engine behind the coin-intel feed, the smart-money leaderboard and the oracle scores \u2014 used to keep writing to the database even after it hit its storage cap, failing thousands of times an hour and burning compute on work that could never be saved. It now checks free space before each run and pauses ingestion while the automatic cleanup reclaims room, then resumes on its own. The result: the engine self-heals instead of storming its logs, and the feeds it powers recover cleanly the moment space frees up.","tags": ["infra"]},{"date": "2026-07-02",- "title": "Agora Commons: hardened for launch — live in production, kinder to your device, more accessible",- "summary": "The living Commons got its production-readiness pass. Its live data — the population, the job board, the economy pulse, and every citizen's passport — is now wired to load in production, so the world fills with real on-chain activity instead of sitting empty. Long viewing sessions are lighter on your machine: the 3D world now frees its graphics memory when you leave, stops rendering while the tab is in the background, and each deliverable you verify now releases its preview cleanly instead of piling up. It's more considerate too — if you've asked your system to reduce motion, the busy rings and the live pulse hold steady instead of animating, keyboard focus stays put inside panels, and low-contrast labels were darkened for readability. The square honestly shows the most recently active citizens when the crowd is large, and long names no longer overflow. Under the hood: new automated tests cover the economy API, the profession proofs, and the MCP tools, and a security pass confirmed sign-in, spend caps, and the mainnet gate hold.",+ "title": "Agora Commons: hardened for launch \u2014 live in production, kinder to your device, more accessible",+ "summary": "The living Commons got its production-readiness pass. Its live data \u2014 the population, the job board, the economy pulse, and every citizen's passport \u2014 is now wired to load in production, so the world fills with real on-chain activity instead of sitting empty. Long viewing sessions are lighter on your machine: the 3D world now frees its graphics memory when you leave, stops rendering while the tab is in the background, and each deliverable you verify now releases its preview cleanly instead of piling up. It's more considerate too \u2014 if you've asked your system to reduce motion, the busy rings and the live pulse hold steady instead of animating, keyboard focus stays put inside panels, and low-contrast labels were darkened for readability. The square honestly shows the most recently active citizens when the crowd is large, and long names no longer overflow. Under the hood: new automated tests cover the economy API, the profession proofs, and the MCP tools, and a security pass confirmed sign-in, spend caps, and the mainnet gate hold.","tags": ["improvement"],@@ -60,7 +69,7 @@{"date": "2026-07-02","title": "Sign-in: fixed a hidden check that could silently block the Sign in button",- "summary": "The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone.",+ "summary": "The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form \u2014 you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone.","tags": ["fix"],@@ -69,7 +78,7 @@{"date": "2026-07-02","title": "Agora Arena & Guilds: agents race for $THREE, or split the reward together",- "summary": "The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator.",+ "summary": "The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish \u2014 the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners \u2014 every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator.","tags": ["feature"],@@ -78,7 +87,7 @@{"date": "2026-07-02","title": "Agora: verify a deliverable, then vouch for its maker in one click",- "summary": "Checking someone's work and standing behind it are now a single move in the Commons. Open any completed job, hit Verify to re-download the deliverable and re-hash it against the on-chain proofHash in your own browser, and when it matches you'll see a Vouch button right there — one click opens your 'You' panel straight to a real, on-chain attestation for the citizen who produced it. The vouch is only ever offered after a genuine match, so you never attest to work you didn't confirm, and it's rate-limited and deduped per person so a relationship is one edge you can refresh, never spam. Every vouch is a real signed Solana transaction you can view on Explorer.",+ "summary": "Checking someone's work and standing behind it are now a single move in the Commons. Open any completed job, hit Verify to re-download the deliverable and re-hash it against the on-chain proofHash in your own browser, and when it matches you'll see a Vouch button right there \u2014 one click opens your 'You' panel straight to a real, on-chain attestation for the citizen who produced it. The vouch is only ever offered after a genuine match, so you never attest to work you didn't confirm, and it's rate-limited and deduped per person so a relationship is one edge you can refresh, never spam. Every vouch is a real signed Solana transaction you can view on Explorer.","tags": ["feature","improvement"@@ -88,7 +97,7 @@{"date": "2026-07-02","title": "Agora: sub-task hires are claimable, and stale bounties clear off the board",- "summary": "Agora's job board now closes the agent-to-agent hiring loop. When one citizen hires another for a sub-task mid-job, that sub-task shows up on the live board so a second citizen can actually pick it up, do the work, and get paid — the two are then linked by the shared on-chain task they both settled. We also fixed the board's housekeeping: a bounty that's been claimed by an outside agent, is awaiting validation, or has passed its deadline now drops off the \"open\" board instead of lingering as a phantom open job. Every state still traces to the real on-chain task on Solana.",+ "summary": "Agora's job board now closes the agent-to-agent hiring loop. When one citizen hires another for a sub-task mid-job, that sub-task shows up on the live board so a second citizen can actually pick it up, do the work, and get paid \u2014 the two are then linked by the shared on-chain task they both settled. We also fixed the board's housekeeping: a bounty that's been claimed by an outside agent, is awaiting validation, or has passed its deadline now drops off the \"open\" board instead of lingering as a phantom open job. Every state still traces to the real on-chain task on Solana.","tags": ["fix","improvement"@@ -96,8 +105,8 @@},{"date": "2026-07-01",- "title": "Pay-per-call APIs now settle reliably — no more dead payment rails",- "summary": "Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle — Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh.",+ "title": "Pay-per-call APIs now settle reliably \u2014 no more dead payment rails",+ "summary": "Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle \u2014 Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh.","tags": ["fix","improvement"@@ -105,8 +114,8 @@},{"date": "2026-07-01",- "title": "Live data keeps flowing — automatic database housekeeping",- "summary": "A handful of behind-the-scenes jobs — the smart-money radar, the coin-intel feeds, and usage metering — had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably.",+ "title": "Live data keeps flowing \u2014 automatic database housekeeping",+ "summary": "A handful of behind-the-scenes jobs \u2014 the smart-money radar, the coin-intel feeds, and usage metering \u2014 had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably.","tags": ["fix","infra"@@ -115,7 +124,7 @@{"date": "2026-07-01","title": "three.ws 3D Forge is now a one-command Claude Code plugin",- "summary": "You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills — a free text→3D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes — and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec — manifest, license, and changelog — and prepared for submission to the public Claude plugin directory.",+ "summary": "You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills \u2014 a free text\u21923D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes \u2014 and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec \u2014 manifest, license, and changelog \u2014 and prepared for submission to the public Claude plugin directory.","tags": ["feature","sdk"@@ -125,7 +134,7 @@{"date": "2026-07-01","title": "Agent profile pages read tighter and clearer",- "summary": "The agent profile got a polish pass so a quieter agent's page no longer looks abandoned and its numbers can't be misread. The live stats strip under the agent's name — agents live, win rate, oracle wins, scored today — are three.ws-wide totals, but sitting right beneath the name they read like the agent's own record; they're now clearly labelled 'Across three.ws' so there's no confusion. Sections that had nothing to show are no longer displayed as hollow shells: the Copy-Trading card stays hidden until an agent has a real on-chain track record to mirror, and Creator Rewards only appears once the agent has actually earned, instead of a permanent 'Lifetime rewards: 0 SOL' row. And the floating 'Have you tried…' suggestion now gently retracts on its own after a few seconds — pausing while you hover or read it — instead of sitting pinned over the page until you close it.",+ "summary": "The agent profile got a polish pass so a quieter agent's page no longer looks abandoned and its numbers can't be misread. The live stats strip under the agent's name \u2014 agents live, win rate, oracle wins, scored today \u2014 are three.ws-wide totals, but sitting right beneath the name they read like the agent's own record; they're now clearly labelled 'Across three.ws' so there's no confusion. Sections that had nothing to show are no longer displayed as hollow shells: the Copy-Trading card stays hidden until an agent has a real on-chain track record to mirror, and Creator Rewards only appears once the agent has actually earned, instead of a permanent 'Lifetime rewards: 0 SOL' row. And the floating 'Have you tried\u2026' suggestion now gently retracts on its own after a few seconds \u2014 pausing while you hover or read it \u2014 instead of sitting pinned over the page until you close it.","tags": ["improvement","fix"@@ -133,8 +142,8 @@},{"date": "2026-07-01",- "title": "The trader track-record page gets a cohesion pass — fonts, gauge, and mobile",- "summary": "The trader profile — the provable track record you open from the leaderboard — got a polish pass so it reads as one product with the rest of three.ws. Two panels, Projected-vs-Realized and Oracle conviction, were quietly rendering in the browser's default serif font because they referenced type and colour tokens that only exist on other surfaces; they now use the platform's Space Grotesk / Inter / JetBrains Mono type and the shared colour tokens, so every label and figure matches the rest of the page and flips cleanly between dark and light themes. The score gauge's number now sits perfectly centred in its ring instead of being nudged into place. On phones the trade tables scroll to keep every column — the open-positions table previously dropped its unrealized-P&L and proof columns — and the Oracle stat strip reflows into clean cards. Along the way we also restored in-card row dividers that weren't drawing in dark mode, which quietly fixes the leaderboard tables too.",+ "title": "The trader track-record page gets a cohesion pass \u2014 fonts, gauge, and mobile",+ "summary": "The trader profile \u2014 the provable track record you open from the leaderboard \u2014 got a polish pass so it reads as one product with the rest of three.ws. Two panels, Projected-vs-Realized and Oracle conviction, were quietly rendering in the browser's default serif font because they referenced type and colour tokens that only exist on other surfaces; they now use the platform's Space Grotesk / Inter / JetBrains Mono type and the shared colour tokens, so every label and figure matches the rest of the page and flips cleanly between dark and light themes. The score gauge's number now sits perfectly centred in its ring instead of being nudged into place. On phones the trade tables scroll to keep every column \u2014 the open-positions table previously dropped its unrealized-P&L and proof columns \u2014 and the Oracle stat strip reflows into clean cards. Along the way we also restored in-card row dividers that weren't drawing in dark mode, which quietly fixes the leaderboard tables too.","tags": ["fix","improvement"@@ -144,7 +153,7 @@{"date": "2026-07-01","title": "The live agent wall now leads with agents that are actually working",- "summary": "The Live Agents wall was burying its best content. It ranked agents by chat volume and how recently they were created, so the grid opened with a flood of brand-new, never-used placeholder agents sitting idle — while the agents genuinely trading, launching coins and running skills were pushed pages down. The wall now ranks every agent by its most recent real on-chain or skill action, so whoever is doing something right now leads the grid, and never-touched placeholder agents (still on the default name, with no activity, no chats and no on-chain identity) are held back entirely. Each card also wears an honest 'active 6m ago' chip drawn from the agent's real last action, so a card reads as alive even when no live browser stream is attached to it. The header was rebuilt to match: in place of a permanently-blank 'frames/sec' it now shows how many agents are on the wall and how many have real activity, next to the live-stream count.",+ "summary": "The Live Agents wall was burying its best content. It ranked agents by chat volume and how recently they were created, so the grid opened with a flood of brand-new, never-used placeholder agents sitting idle \u2014 while the agents genuinely trading, launching coins and running skills were pushed pages down. The wall now ranks every agent by its most recent real on-chain or skill action, so whoever is doing something right now leads the grid, and never-touched placeholder agents (still on the default name, with no activity, no chats and no on-chain identity) are held back entirely. Each card also wears an honest 'active 6m ago' chip drawn from the agent's real last action, so a card reads as alive even when no live browser stream is attached to it. The header was rebuilt to match: in place of a permanently-blank 'frames/sec' it now shows how many agents are on the wall and how many have real activity, next to the live-stream count.","tags": ["improvement"],@@ -152,8 +161,8 @@},{"date": "2026-07-01",- "title": "The Arena gets a full design pass — and its tournament pages work again",- "summary": "The Arena's live tournament view was silently broken: opening any competition showed a stuck loading screen because the page relied on four pieces that were never finished. They're now built and live — a window-progress timeline that ticks down to the open and close, a prize ladder showing exactly how the $THREE pool splits across the podium and who currently holds each place, a rules-and-eligibility panel spelling out scoring, bracket and the trade gates, and a summary strip totalling entrants, in-window trades and net P&L across the field. The whole surface also got a cohesion pass to match the rest of three.ws: the correct Space Grotesk / Inter typefaces (it was rendering in the browser's default serif), the shared color tokens so it flips cleanly between dark and light themes, and tighter, fully responsive layouts on phone and desktop. The list page now opens with a live snapshot of what's on — how many tournaments are live, upcoming and finished, plus total $THREE at stake and agents competing.",+ "title": "The Arena gets a full design pass \u2014 and its tournament pages work again",+ "summary": "The Arena's live tournament view was silently broken: opening any competition showed a stuck loading screen because the page relied on four pieces that were never finished. They're now built and live \u2014 a window-progress timeline that ticks down to the open and close, a prize ladder showing exactly how the $THREE pool splits across the podium and who currently holds each place, a rules-and-eligibility panel spelling out scoring, bracket and the trade gates, and a summary strip totalling entrants, in-window trades and net P&L across the field. The whole surface also got a cohesion pass to match the rest of three.ws: the correct Space Grotesk / Inter typefaces (it was rendering in the browser's default serif), the shared color tokens so it flips cleanly between dark and light themes, and tighter, fully responsive layouts on phone and desktop. The list page now opens with a live snapshot of what's on \u2014 how many tournaments are live, upcoming and finished, plus total $THREE at stake and agents competing.","tags": ["fix","improvement"diff --git a/pages/agora.html b/pages/agora.htmlindex 2ea4d64eb..0f6a85a17 100644--- a/pages/agora.html+++ b/pages/agora.html@@ -65,7 +65,7 @@<kbd>Drag</kbd> orbit <kbd>WASD</kbd> pan <kbd>Scroll</kbd> zoom - <kbd>Click</kbd> a citizen+ <kbd>Click</kbd> / <kbd>I</kbd> inspect a citizen</div></div>diff --git a/pages/city.html b/pages/city.htmlindex 5a2c5e887..556dbfee9 100644--- a/pages/city.html+++ b/pages/city.html@@ -60,7 +60,8 @@<kbd>WASD</kbd> move <kbd>Shift</kbd> sprint <kbd>Space</kbd> jump - <kbd>Drag</kbd> orbit+ <kbd>Drag</kbd> orbit + <kbd>I</kbd> inspect avatar</div></div>diff --git a/pages/marketplace-walk.html b/pages/marketplace-walk.htmlindex e6c06fd62..c073419af 100644--- a/pages/marketplace-walk.html+++ b/pages/marketplace-walk.html@@ -1505,6 +1505,7 @@<span class="walk-key"><kbd>G</kbd> gestures</span><span class="walk-key"><kbd>V</kbd> scene</span><span class="walk-key"><kbd>M</kbd> map</span>+ <span class="walk-key"><kbd>I</kbd> inspect avatar</span><span class="walk-key"><kbd>Z</kbd> hide UI</span><span class="walk-key"><kbd>H</kbd> help</span></div>diff --git a/pages/temporary.html b/pages/temporary.htmlindex 65c1b2e83..e153d0efd 100644--- a/pages/temporary.html+++ b/pages/temporary.html@@ -1462,6 +1462,7 @@<span class="walk-key"><kbd>T</kbd> hold to talk</span><span class="walk-key"><kbd>V</kbd> scene</span><span class="walk-key"><kbd>M</kbd> map</span>+ <span class="walk-key"><kbd>I</kbd> inspect avatar</span><span class="walk-key"><kbd>Z</kbd> hide UI</span><span class="walk-key"><kbd>H</kbd> help</span></div>diff --git a/src/agora/agora-world.js b/src/agora/agora-world.jsindex 285d3c77d..2ea4cef51 100644--- a/src/agora/agora-world.js+++ b/src/agora/agora-world.js@@ -97,12 +97,22 @@ async function main() {const PAN_KEYS = new Set(['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright']);const onKeyDown = (e) => {const k = e.key.toLowerCase();- if (!PAN_KEYS.has(k)) return;+ if (!PAN_KEYS.has(k) && k !== 'i') return;// Don't hijack typing or scrolling: let form fields, editable content, and any// open panel keep arrow/WASD keys. Only pan when the world itself has focus.const ae = document.activeElement;if (ae && (/^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(ae.tagName) || ae.isContentEditable|| (ae.closest && ae.closest('.agora-passport, .agora-panel, .agora-h-root, [role="dialog"]')))) return;+ // I inspects a citizen without touching the mouse: the one under the+ // pointer if any, else whoever is closest to the camera's focus point.+ // Same passport the click path opens — reputation, stake, wallet, timeline.+ if (k === 'i') {+ if (e.repeat) return;+ e.preventDefault();+ const id = hoverId || nearestCitizenTo(focus);+ if (id) openPassport(id, null);+ return;+ }if (k.startsWith('arrow')) e.preventDefault();keys.add(k);focusGoal = null;@@ -166,6 +176,17 @@ async function main() {return population.pick(raycaster);}+ // The citizen nearest a world-space point (the camera's focus) — the keyboard+ // counterpart to hover-picking, so I always has someone to inspect.+ function nearestCitizenTo(point) {+ let bestId = null, bestD = Infinity;+ for (const inst of population.instances) {+ const d = Math.hypot(inst.group.position.x - point.x, inst.group.position.z - point.z);+ if (d < bestD) { bestD = d; bestId = inst.citizen?.id || null; }+ }+ return bestId;+ }+// ── Fetch + populate (re-runnable for the error-state retry + live joins) ──// Guarded against overlap: population.add has an async gap between its dedupe// check and insert, so two concurrent runs could double-place a citizen. A rundiff --git a/src/agora/player-logic.js b/src/agora/player-logic.jsnew file mode 100644index 000000000..31eacb66b--- /dev/null+++ b/src/agora/player-logic.js@@ -0,0 +1,179 @@+// Agora player mode — the PURE rules of embodied play. Everything here is+// deterministic math/state with no Three.js, DOM, or network imports, so the+// GTA-style layer (player-mode.js) stays unit-testable the same way the labor+// engine keeps its economics in workers/agora-citizens/policy.js.+//+// player-mode.js owns the scene objects and the wire; this module owns:+// • camera-relative movement + facing (stepMovement)+// • the idle/walk/run motion state (motionFor)+// • capsule-vs-AABB building collision (resolveBuildingCollision)+// • who the player can interact with right now (nearestInteractable)+// • which avatar the player embodies (chooseAvatarSource)+// • a stable guest display name (guestName)++// Movement tuning — deliberately close to /city's controller so crossing+// between the two city-substrate worlds feels identical underfoot.+export const WALK_SPEED = 4.2; // m/s+export const RUN_SPEED = 8.5; // m/s+export const JUMP_VEL = 8.5; // m/s initial upward+export const GRAVITY = -22; // m/s²+export const PLAYER_RADIUS = 0.42; // collision capsule radius (m)++// A citizen (or the job board) is reachable for interaction inside this range.+export const INTERACT_RADIUS = 3.2; // metres++/**+ * The locomotion state for the animation mixer + the multiplayer wire.+ * Matches the WalkRoom Player.motion vocabulary: 'idle' | 'walk' | 'run'.+ */+export function motionFor(horizontalSpeed, running) {+ if (horizontalSpeed < 0.4) return 'idle';+ return running ? 'run' : 'walk';+}++/**+ * One movement step: camera-relative input → velocity + facing.+ * Pure: mutates nothing — returns the next {vx, vz, yaw, moving}.+ *+ * @param {object} args+ * @param {{forward:number, strafe:number}} args.input each in [-1, 1] (keyboard+ * fills ±1, a touch stick fills the analogue range)+ * @param {number} args.cameraYaw horizontal camera angle (rad, three.js Y)+ * @param {boolean} args.running sprint modifier held+ * @param {number} args.vx current horizontal velocity x+ * @param {number} args.vz current horizontal velocity z+ * @param {number} args.yaw current facing (rad)+ * @param {number} args.dt frame delta (s)+ */+export function stepMovement({ input, cameraYaw, running, vx, vz, yaw, dt }) {+ const f = clamp(input.forward, -1, 1);+ const s = clamp(input.strafe, -1, 1);+ // Camera-relative basis: forward = -Z rotated by cameraYaw.+ let dx = -Math.sin(cameraYaw) * f + Math.cos(cameraYaw) * s;+ let dz = -Math.cos(cameraYaw) * f - Math.sin(cameraYaw) * s;+ const len = Math.hypot(dx, dz);+ const moving = len > 0.08; // stick deadzone tail+ if (moving) {+ dx /= len;+ dz /= len;+ // Analogue magnitude scales speed so a gentle thumb = a stroll.+ const mag = Math.min(1, len);+ const speed = (running ? RUN_SPEED : WALK_SPEED) * mag;+ return { vx: dx * speed, vz: dz * speed, yaw: Math.atan2(dx, dz), moving: true };+ }+ // Quick exponential stop (frame-rate independent).+ const damp = Math.pow(0.02, dt);+ return { vx: vx * damp, vz: vz * damp, yaw, moving: false };+}++/**+ * Shortest-arc yaw easing so the avatar turns the short way round.+ * Returns the next yaw after easing `current` toward `target` by k·dt.+ */+export function easeYaw(current, target, dt, k = 14) {+ let diff = target - current;+ while (diff > Math.PI) diff -= Math.PI * 2;+ while (diff < -Math.PI) diff += Math.PI * 2;+ return current + diff * Math.min(1, dt * k);+}++/**+ * Capsule-vs-AABB push-out in the XZ plane — the same building collision the+ * City player uses, kept pure. `boxes` are {minX,maxX,minZ,maxZ,h} from+ * buildCity(); a player above a box's height clears it (jumping over stalls).+ *+ * @returns {{x:number, z:number}} the resolved position+ */+export function resolveBuildingCollision(nx, ny, nz, boxes, radius = PLAYER_RADIUS) {+ for (const b of boxes || []) {+ if (ny > b.h) continue;+ const cx = Math.max(b.minX, Math.min(b.maxX, nx));+ const cz = Math.max(b.minZ, Math.min(b.maxZ, nz));+ const ox = nx - cx;+ const oz = nz - cz;+ const dist2 = ox * ox + oz * oz;+ if (dist2 >= radius * radius) continue;+ const dist = Math.sqrt(dist2);+ if (dist < 0.001) {+ // Dead-centre inside the box — eject toward the nearest face.+ const toLeft = nx - b.minX;+ const toRight = b.maxX - nx;+ const toFront = nz - b.minZ;+ const toBack = b.maxZ - nz;+ const min = Math.min(toLeft, toRight, toFront, toBack);+ if (min === toLeft) nx = b.minX - radius;+ else if (min === toRight) nx = b.maxX + radius;+ else if (min === toFront) nz = b.minZ - radius;+ else nz = b.maxZ + radius;+ } else {+ const push = (radius - dist) / dist;+ nx += ox * push;+ nz += oz * push;+ }+ }+ return { x: nx, z: nz };+}++/**+ * The single nearest interactable within reach — drives the "press E" prompt.+ * Candidates carry {id, kind, x, z, ...} (kind: 'citizen' | 'board' | …);+ * the caller shapes the prompt from the winner's fields. Deterministic+ * tie-break by distance then id so the prompt never flickers between two+ * equidistant citizens.+ *+ * @returns {object|null} the winning candidate + its distance, or null+ */+export function nearestInteractable(px, pz, candidates, radius = INTERACT_RADIUS) {+ let best = null;+ let bestD = radius;+ for (const c of candidates || []) {+ const d = Math.hypot(c.x - px, c.z - pz);+ if (d < bestD || (best && d === bestD && String(c.id) < String(best.id))) {+ best = c;+ bestD = d;+ }+ }+ return best ? { ...best, distance: bestD } : null;+}++/**+ * Which avatar the player embodies, in priority order:+ * 1. ?avatarUrl=<direct GLB/VRM url> (deep link, same as /temporary)+ * 2. ?avatar=<three.ws avatar id or url> (deep link)+ * 3. the last avatar they walked as here (localStorage 'agora:avatar')+ * 4. '' → avatar-rig's default (never a blank world)+ * Pure: takes the parsed params + a storage getter so tests inject both.+ *+ * @param {URLSearchParams|Map} params+ * @param {(key:string) => string|null} getStored+ * @returns {{source:string, value:string}}+ */+export function chooseAvatarSource(params, getStored) {+ const direct = (params.get('avatarUrl') || '').trim();+ if (direct) return { source: 'param-url', value: direct };+ const byId = (params.get('avatar') || '').trim();+ if (byId) return { source: 'param', value: byId };+ const stored = (getStored('agora:avatar') || '').trim();+ if (stored) return { source: 'stored', value: stored };+ return { source: 'default', value: '' };+}++/**+ * A stable, human-friendly guest name. Reuses the stored one so a returning+ * visitor keeps their identity in the square; otherwise derives 'visitor-xxxx'+ * from the supplied entropy (caller passes randomness — pure function).+ */+export function guestName(getStored, entropy) {+ const stored = (getStored('agora:name') || '').trim();+ if (stored) return stored.slice(0, 24);+ const tag = Math.abs(Math.floor(entropy * 46656)) // 36^3+ .toString(36)+ .padStart(3, '0')+ .slice(0, 3);+ return `visitor-${tag}`;+}++function clamp(v, min, max) {+ const n = Number(v) || 0;+ return Math.max(min, Math.min(max, n));+}diff --git a/src/city/city-world.js b/src/city/city-world.jsindex 2c3ad7783..7684b2d58 100644--- a/src/city/city-world.js+++ b/src/city/city-world.js@@ -3,6 +3,7 @@ import { fetchOSMData, buildCity, buildMinimapStatic, CITY_HALF } from './city-mimport { createCityScene, bindResize } from './city-scene.js';import { CityPlayer } from './city-player.js';import { CityCamera } from './city-camera.js';+import { openAvatarInspector } from '../shared/avatar-inspector.js';import { log } from '../shared/log.js';// ── DOM refs ──────────────────────────────────────────────────────────────────@@ -66,6 +67,52 @@ async function main() {canvas.focus();+ // ── Avatar inspector ──────────────────────────────────────────────────────+ // The city is single-player, so I (or clicking your avatar) inspects you:+ // identity, reputation and wallet when you're piloting a registered agent+ // (?agent=<id>), honest guidance when you're exploring as a guest.+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+ const agentParam = (new URLSearchParams(location.search).get('agent') || '').trim();+ const inspectSelf = () => {+ const R = 6_371_000;+ const cosC = Math.cos(40.7580 * Math.PI / 180);+ const lat = 40.7580 - (player.position.z / R) * (180 / Math.PI);+ const lon = -73.9855 + (player.position.x / (R * cosC)) * (180 / Math.PI);+ openAvatarInspector({+ kind: 'self',+ name: 'You',+ world: 'city',+ agentId: UUID_RE.test(agentParam) ? agentParam : '',+ avatarUrl: avatarInput,+ facts: [+ { label: 'Location', value: `${lat.toFixed(5)}°N ${Math.abs(lon).toFixed(5)}°W`, href: 'https://www.openstreetmap.org/#map=17/' + lat.toFixed(5) + '/' + lon.toFixed(5) },+ { label: 'District', value: 'Midtown Manhattan (live OSM data)' },+ ],+ }, { trigger: canvas });+ };+ window.addEventListener('keydown', (e) => {+ if (e.key.toLowerCase() !== 'i' || e.repeat) return;+ const ae = document.activeElement;+ if (ae && (/^(INPUT|TEXTAREA|SELECT)$/.test(ae.tagName) || ae.isContentEditable || ae.closest?.('[role="dialog"]'))) return;+ e.preventDefault();+ inspectSelf();+ });+ // A tap (not a look-drag) on your avatar opens the same panel.+ const raycaster = new THREE.Raycaster();+ const ndc = new THREE.Vector2();+ let downAt = null;+ canvas.addEventListener('pointerdown', (e) => { downAt = { x: e.clientX, y: e.clientY }; });+ canvas.addEventListener('pointerup', (e) => {+ if (!downAt) return;+ const moved = Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y);+ downAt = null;+ if (moved >= 6 || e.button === 2) return;+ const rect = canvas.getBoundingClientRect();+ ndc.set(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);+ raycaster.setFromCamera(ndc, camera);+ if (raycaster.intersectObject(player.rig, true).length) inspectSelf();+ });+progress(100, 'Ready');await delay(150);loadingEl.classList.add('hidden');diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.jsindex 500621d46..c5dbddd28 100644--- a/src/game/agent-commerce.js+++ b/src/game/agent-commerce.js@@ -1,5 +1,5 @@// Agent Exchange — two NPC AI agents who pay each other on-chain, living inside-// the $THREE town in /play.+// every coin town in /play.//// This ports the /agent-exchange demo into the walkaround world: instead of two// iframed avatars on a flat page, two GLB-bodied agents stand in the plaza. Walk@@ -11,10 +11,10 @@// (vertices, triangles, materials). Every settlement is real USDC on Solana// mainnet, with a Solscan link in the receipt.//-// Scoped to the home town only (see isHomeTown) and built per-world by-// coincommunities.js, so it never leaks into other coins' worlds. The payment-// round only fires on an explicit player interaction (E / tap), so the agent-// wallet is never drained on a timer.+// Built per-world by coincommunities.js — every coin town hosts the exchange;+// the paid call and the settlement rail are coin-agnostic, so the same two+// agents work every plaza. The payment round only fires on an explicit player+// interaction (E / tap), so the agent wallet is never drained on a timer.import {Group, Mesh, MeshBasicMaterial, RingGeometry, PlaneGeometry,diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 3ba220738..980ec933e 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -1265,7 +1265,7 @@ export class CommunityUI {]);const hint = el('div', { id: 'cc-hint', html:- '<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat · <kbd>Q</kbd> emotes' });+ '<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat · <kbd>Q</kbd> emotes · <kbd>I</kbd> inspect' });this.joystick = el('div', { id: 'cc-joystick' });diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 2f3825ffb..69d5a1e17 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -32,7 +32,7 @@ import {COMPOSITE_PIECES, compositeCells,} from './build-voxels.js';import { WorldObjects, PropGhost, propDef } from './world-objects.js';-import { normalizeGatewayURL } from '../ipfs.js';+import { proxiedImageURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, getAllEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,CLIP_IDLE, CLIP_WALK,@@ -58,6 +58,7 @@ import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './pimport { PlaySystems } from './play-systems.js';import { PlayOnboard } from './play-onboard.js';import { log } from '../shared/log.js';+import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from '../shared/avatar-inspector.js';import { createAgentDesk } from './agent-desk.js';// localStorage throws in private mode and in third-party iframe contexts where@@ -108,7 +109,7 @@ function mapCoins(raw) {mint: c.mint || c.address,name: (c.name || '').trim() || 'Unnamed coin',symbol: (c.symbol || '').trim(),- image: normalizeGatewayURL(c.image_uri || c.image || c.imageUri || c.logo || ''),+ image: proxiedImageURL(c.image_uri || c.image || c.imageUri || c.logo || '', c.mint || c.address || ''),marketCap: c.usd_market_cap || c.market_cap_usd || c.marketCap || 0,})).filter((c) => c.mint);}@@ -134,9 +135,25 @@ class RemotePlayer {this.rig.position.set(player.x, player.y, player.z);scene.add(this.rig);+ // Public identity riding the server schema — who this peer is (name), the+ // three.ws agent they pilot, and their verified account wallet. These feed+ // the avatar inspector (I / click a nameplate), never invented client-side.+ this.name = player.name || 'guest';+ this.agent = player.agent || '';+ this.account = player.account || '';+ this.onInspect = null; // set by CoinCommunities right after construction+this.label = document.createElement('div');this.label.className = 'cc-label';this.label.textContent = player.name || 'guest';+ // The nameplate doubles as the peer's click target: labels are cheap,+ // always visible, and don't need a skinned-mesh raycast. pointer-events is+ // off for .cc-label globally (bubbles must never block the look-drag), so+ // re-enable it just for this element.+ this.label.style.pointerEvents = 'auto';+ this.label.style.cursor = 'pointer';+ this.label.title = 'Inspect this player (I)';+ this.label.addEventListener('click', (e) => { e.stopPropagation(); this.onInspect?.(); });document.body.appendChild(this.label);this.bubble = null;@@ -225,7 +242,9 @@ class RemotePlayer {}apply(player) {this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;- if (player.name) this.label.textContent = player.name;+ if (player.name) { this.name = player.name; this.label.textContent = player.name; }+ if (player.agent !== undefined) this.agent = player.agent || '';+ if (player.account !== undefined) this.account = player.account || '';if (player.voice !== undefined && !!player.voice !== this.voice) {this.voice = !!player.voice;this.label.classList.toggle('cc-invoice', this.voice);@@ -413,7 +432,7 @@ export class CoinCommunities {const mint = p.get('coin');if (mint) {const tier = p.get('tier') === 'holders' ? 'holders' : 'general';- this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: normalizeGatewayURL(p.get('image') || '') }, { tier });+ this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: proxiedImageURL(p.get('image') || '', mint) }, { tier });}}@@ -1306,6 +1325,7 @@ export class CoinCommunities {this._previewPresetId = null; this._previewLayers = false; this._previewItem = null;for (const [, r] of this.remotes) r.dispose();this.remotes.clear();+ closeAvatarInspector(); // whoever it showed just left the world with usif (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }if (this._screen) {this.world.remove(this._screen);@@ -1369,10 +1389,93 @@ export class CoinCommunities {this._drawScreen(); // keep the jumbotron's LIVE count in sync}+ // ------------------------------------------------------------- avatar inspector+ // I (or clicking a nameplate / avatar) opens the shared inspector on whoever+ // you're looking at: identity, reputation, wallet — the same server truth every+ // other surface reads. See src/shared/avatar-inspector.js.+ _worldFacts() {+ const coin = this.coin || {};+ return coin.name || coin.symbol+ ? [{ label: 'World', value: coin.symbol ? `$${coin.symbol}` : coin.name, href: coin.mint ? `/play?coin=${encodeURIComponent(coin.mint)}` : undefined }]+ : [];+ }+ _inspectRemote(id, trigger) {+ const rp = this.remotes.get(id);+ if (!rp) return;+ openAvatarInspector({+ kind: 'peer',+ name: rp.name,+ world: 'play',+ agentId: rp.agent,+ wallet: rp.account,+ avatarUrl: rp._avatarUrl,+ facts: [+ ...this._worldFacts(),+ ...(rp.voice ? [{ label: 'Voice', value: 'in voice chat' }] : []),+ ],+ }, { trigger: trigger || this.canvas });+ }+ _inspectNpc(npc) {+ openAvatarInspector({+ kind: 'npc',+ name: npc.name,+ world: 'play',+ facts: [+ { label: 'Role', value: npc.role === 'vendor' ? 'Vendor — real paid service' : npc.role === 'quest' ? 'Quest giver' : 'Townsperson' },+ ...(npc.def?.prompt ? [{ label: 'Offers', value: npc.def.prompt }] : []),+ { label: 'Talk', value: 'walk up and press E' },+ ...this._worldFacts(),+ ],+ }, { trigger: this.canvas });+ }+ _inspectSelf() {+ openAvatarInspector({+ kind: 'self',+ name: this.net?.name || lsGet('cc-name') || 'You',+ world: 'play',+ wallet: this.account || '',+ avatarUrl: this.net?.avatar,+ facts: this._worldFacts(),+ }, { trigger: this.canvas });+ }+ // Nearest inspectable within reach: real players first beat scenery — an NPC+ // only wins when it is strictly closer. Falls back to yourself so the key+ // always answers.+ _inspectNearest() {+ if (isAvatarInspectorOpen()) { closeAvatarInspector(); return; }+ const MAX_M = 10;+ let best = null; // { d, open }+ for (const [id, rp] of this.remotes) {+ const d = Math.hypot(rp.rig.position.x - this.localPos.x, rp.rig.position.z - this.localPos.z);+ if (d <= MAX_M && (!best || d < best.d)) best = { d, open: () => this._inspectRemote(id) };+ }+ for (const npc of this.worldLife?.npcs || []) {+ const d = npc.distanceTo(this.localPos);+ if (d <= MAX_M && (!best || d < best.d)) best = { d, open: () => this._inspectNpc(npc) };+ }+ if (best) best.open();+ else this._inspectSelf();+ }+ // Raycast pick for taps directly on a peer's 3D body (labels are the fast+ // path; this catches clicks on the avatar itself). Click-only — never run+ // per-frame, skinned-mesh raycasts are too heavy for hover.+ _remoteAt(clientX, clientY) {+ if (!this.remotes.size) return null;+ const ray = this._pointerRay(clientX, clientY);+ let best = null;+ for (const [id, rp] of this.remotes) {+ const hits = ray.intersectObject(rp.rig, true);+ if (hits.length && (!best || hits[0].distance < best.d)) best = { d: hits[0].distance, id };+ }+ return best?.id || null;+ }+// ---------------------------------------------------------------- net events_onAdd(player, id) {if (id === this.net.sessionId) return; // that's us- this.remotes.set(id, new RemotePlayer(this.scene, player));+ const rp = new RemotePlayer(this.scene, player);+ rp.onInspect = () => this._inspectRemote(id, rp.label);+ this.remotes.set(id, rp);this._updateOnline();}_onChange(player, id) {@@ -2012,6 +2115,13 @@ export class CoinCommunities {this.playSystems?.castFish();return;}+ // I inspects the nearest avatar — player, townsperson, or yourself:+ // identity, reputation, wallet. Press again to close.+ if (k === 'i' && !this.buildHud.active && !e.repeat) {+ e.preventDefault();+ this._inspectNearest();+ return;+ }// Q — hold to open the emote wheel, release to play the selected clip.// Ignore auto-repeat (held key fires many keydowns) and build mode.if (k === 'q' && !this.buildHud.active && !e.repeat) {@@ -2082,6 +2192,12 @@ export class CoinCommunities {}}}+ // Tap another player's avatar → the inspector (their nameplate is the+ // other click target; both land in the same panel).+ if (this.phase === 'world') {+ const peerId = this._remoteAt(e.clientX, e.clientY);+ if (peerId) { this._inspectRemote(peerId); return; }+ }if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();});// Right-click always breaks the targeted block while building.diff --git a/src/game/community-net.js b/src/game/community-net.jsindex d24a9cece..7aa1c7faa 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -445,6 +445,19 @@ export class CommunityNet {}, delay);}+ // Send a message only when the wire is actually open. `this.room` alone isn't+ // enough: between the socket entering CLOSING and onLeave firing, the room+ // reference is still live, and ws.send() on that socket logs a console+ // warning per message ("WebSocket is already in CLOSING or CLOSED state").+ // Returns true when the message reached an open socket; dropped messages are+ // fine — every send here is a live-state signal the reconnect resyncs anyway.+ _send(type, payload) {+ const room = this.room;+ if (!room || room.connection?.isOpen !== true) return false;+ try { room.send(type, payload); } catch { return false; }+ return true;+ }+sendMove(state) {if (!this.room) return;const now = performance.now();@@ -454,7 +467,7 @@ export class CommunityNet {const turned = Math.abs(state.yaw - this._lastSent.yaw);if (moved < POSITION_EPSILON && turned < YAW_EPSILON && state.motion === this._lastSent.motion) return;}- this.room.send('move', { x: state.x, y: state.y, z: state.z, yaw: state.yaw, motion: state.motion });+ if (!this._send('move', { x: state.x, y: state.y, z: state.z, yaw: state.yaw, motion: state.motion })) return;this._lastSent = { ...state };this._lastSentAt = now;// Stamp this move for RTT measurement unless one is already awaiting its@@ -462,72 +475,72 @@ export class CommunityNet {if (!this._pingSentAt) this._pingSentAt = now;}- sendEmote(name) { this.room?.send('emote', { name }); }- sendReaction(emoji) { this.room?.send('reaction', { emoji }); }- sendChat(text) { this.room?.send('chat', { text }); }+ sendEmote(name) { this._send('emote', { name }); }+ sendReaction(emoji) { this._send('reaction', { emoji }); }+ sendChat(text) { this._send('chat', { text }); }// Place/break a voxel at an integer grid cell. Server-authoritative: these only// request the edit; the block is added/removed locally when the server patches// state.blocks (see the onAdd/onRemove wiring above).- sendPlace(x, y, z, t) { this.room?.send('place', { x, y, z, t }); }+ sendPlace(x, y, z, t) { this._send('place', { x, y, z, t }); }// Place a composite piece in one atomic message: an array of {x,y,z,t} cells the// server validates and applies all-or-nothing (see WalkRoom._handlePlaceBatch).// Each placed block streams back through the same blockAdd path as single edits.- sendPlaceBatch(cells) { this.room?.send('place-batch', { cells }); }- sendRemove(x, y, z) { this.room?.send('remove', { x, y, z }); }+ sendPlaceBatch(cells) { this._send('place-batch', { cells }); }+ sendRemove(x, y, z) { this._send('remove', { x, y, z }); }// Creator-only moderation (R19): clear a disc of blocks around a grid cell, or the// whole world. The server validates the creator identity + bounds and streams each// removal back through the usual blockRemove path.- sendClearArea(x, z, r) { this.room?.send('build-clear', { x, z, r }); }- sendClearAll() { this.room?.send('build-clear', { all: true }); }- sendInteract(to, action) { this.room?.send('interact', { to, action }); }+ sendClearArea(x, z, r) { this._send('build-clear', { x, z, r }); }+ sendClearAll() { this._send('build-clear', { all: true }); }+ sendInteract(to, action) { this._send('interact', { to, action }); }// Spatial voice: relay a WebRTC offer/answer/ICE candidate to one peer, and// flag ourselves in/out of voice so peers know whether to connect to us.- sendVoiceSignal(to, data) { this.room?.send('voice-signal', { to, data }); }- setVoiceActive(on) { this.room?.send('voice-state', { on: !!on }); }- rename(name) { this.name = name; this.room?.send('rename', { name }); }- setAvatar(avatar, agent) { this.avatar = avatar; this.room?.send('avatar', { avatar, agent }); }+ sendVoiceSignal(to, data) { this._send('voice-signal', { to, data }); }+ setVoiceActive(on) { this._send('voice-state', { on: !!on }); }+ rename(name) { this.name = name; this._send('rename', { name }); }+ setAvatar(avatar, agent) { this.avatar = avatar; this._send('avatar', { avatar, agent }); }// Equip a cosmetic into its slot (W03). Server-authoritative: it validates// ownership, updates the player's schema `cosmetics` field (so peers re-render)// and replies with a fresh profile. An unowned id is rejected with a 'notice'.- equipCosmetic(id) { this.room?.send('equip-cosmetic', { id }); }+ equipCosmetic(id) { this._send('equip-cosmetic', { id }); }// Broadcast a full loadout wire in one shot — mirrors how the avatar is sent.// Server validates every id against the catalog and the account's owned set,// drops anything invalid or unowned, and publishes the sanitized wire on the// schema so all peers re-render the correct look.- setCosmetics(wire) { this.cosmetics = typeof wire === 'string' ? wire : ''; this.room?.send('set-cosmetics', { cosmetics: this.cosmetics }); }+ setCosmetics(wire) { this.cosmetics = typeof wire === 'string' ? wire : ''; this._send('set-cosmetics', { cosmetics: this.cosmetics }); }// Activities & economy. Server-authoritative: these only request the action; the// result arrives via the profile/inv/xpgain/levelup/notice events above.// R05 physics ball: send a kick intent with the impulse the server should apply.// The server validates magnitude, direction, and rate before touching the ball.- sendBallKick(vx, vy, vz) { this.room?.send('ball:kick', { vx, vy, vz }); }- fish() { this.room?.send('fish'); }- chop() { this.room?.send('chop'); }- mine() { this.room?.send('mine'); }- cook() { this.room?.send('cook'); }- attack() { this.room?.send('attack'); }- equip(slot) { this.room?.send('equip', { slot }); }- consume(ref) { this.room?.send('consume', { slot: ref }); }- requestProfile() { this.room?.send('profileReq'); }+ sendBallKick(vx, vy, vz) { this._send('ball:kick', { vx, vy, vz }); }+ fish() { this._send('fish'); }+ chop() { this._send('chop'); }+ mine() { this._send('mine'); }+ cook() { this._send('cook'); }+ attack() { this._send('attack'); }+ equip(slot) { this._send('equip', { slot }); }+ consume(ref) { this._send('consume', { slot: ref }); }+ requestProfile() { this._send('profileReq'); }// 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// finds the player standing in (pickup/dropoff/terminal/crack).- requestQuests() { this.room?.send('questReq'); }- questAccept(id) { this.room?.send('questAccept', { id }); }- questAbandon(id) { this.room?.send('questAbandon', { id }); }- questInteract() { this.room?.send('questInteract'); }+ requestQuests() { this._send('questReq'); }+ questAccept(id) { this._send('questAccept', { id }); }+ questAbandon(id) { this._send('questAbandon', { id }); }+ questInteract() { this._send('questInteract'); }// Vehicles. enter/exit take + release the wheel (server-gated by proximity +// occupancy, answered on the 'vehicle' event); vsync streams the driver's// authoritative Rapier transform, which the server validates and relays. vsync// is throttled to the move send rate; the driving loop calls it every frame.- sendVEnter(id) { this.room?.send('venter', { id }); }- sendVExit(state) { this.room?.send('vexit', state || {}); }+ sendVEnter(id) { this._send('venter', { id }); }+ sendVExit(state) { this._send('vexit', state || {}); }sendVSync(state) {if (!this.room) return;const now = performance.now();if (now - (this._lastVSyncAt || 0) < SEND_INTERVAL_MS) return;this._lastVSyncAt = now;- this.room.send('vsync', state);+ this._send('vsync', state);}// Generic world objects (R01/R02). These only *request* the change; the object// appears/moves/disappears when the server echoes its authoritative `objects`@@ -547,7 +560,7 @@ export class CommunityNet {if (Number.isFinite(opts.vx)) msg.vx = opts.vx;if (Number.isFinite(opts.vy)) msg.vy = opts.vy;if (Number.isFinite(opts.vz)) msg.vz = opts.vz;- this.room.send('obj:spawn', msg);+ this._send('obj:spawn', msg);}updateObject(id, transform = {}) {if (!this.room || typeof id !== 'string') return;@@ -555,11 +568,11 @@ export class CommunityNet {for (const k of ['x', 'y', 'z', 'yaw', 'scale', 'vx', 'vy', 'vz']) {if (Number.isFinite(transform[k])) msg[k] = transform[k];}- this.room.send('obj:update', msg);+ this._send('obj:update', msg);}removeObject(id) {if (!this.room || typeof id !== 'string') return;- this.room.send('obj:remove', { id });+ this._send('obj:remove', { id });}// Does an object's server-assigned ownerId belong to THIS client? The server keys// ownership on the verified account when signed in, else the persisted economy id,@@ -577,7 +590,7 @@ export class CommunityNet {// sweep evicts a still-qualifying player at the original 10-min TTL (which// stranded anyone in a long building session). The server re-verifies the pass// against the gate before extending; a forged or below-floor pass is ignored.- updatePlayPass(pass) { this.playPass = pass || ''; if (pass) this.room?.send('play-pass', { playPass: pass }); }+ updatePlayPass(pass) { this.playPass = pass || ''; if (pass) this._send('play-pass', { playPass: pass }); }get state() { return this.room?.state ?? null; }diff --git a/src/game/home-town.js b/src/game/home-town.jsindex 07d08667c..953b5d144 100644--- a/src/game/home-town.js+++ b/src/game/home-town.js@@ -16,7 +16,10 @@ export const HOME_TOWN = {mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',name: 'three.ws',symbol: 'three',- image: 'https://ipfs.io/ipfs/bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q',+ // Served through the same-origin /api/img proxy (multi-gateway IPFS retry ++ // immutable edge cache) so the front-door art never depends on one gateway.+ image: '/api/img?url=' + encodeURIComponent('https://ipfs.io/ipfs/bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q')+ + '&seed=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',// The signature look for the home town: Dust Gulch, an old-west frontier town —// a packed-dirt square ringed by false-front storefronts (saloon, bank,// sheriff…) under a low golden-hour sun, with a water tower on the skyline anddiff --git a/src/game/npc/npc-catalog.js b/src/game/npc/npc-catalog.jsindex 97a1395ab..95701b35b 100644--- a/src/game/npc/npc-catalog.js+++ b/src/game/npc/npc-catalog.js@@ -10,10 +10,10 @@// storefront where each character sells a different paid capability, settled// on-chain in USDC, 24/7. No "coming soon", no mocks.//-// The flagship $THREE town gets the full cast. Every other coin world gets a-// couple of universal-service locals so its plaza still trades.+// Every coin world gets the same full cast. The characters are the platform's+// travelling company — the same faces work every town's plaza, and every+// service they sell is coin-agnostic, so the whole economy runs anywhere.-import { isHomeTown } from '../home-town.js';import { openChat } from './npc-chat.js';import { openAixbtTerminal } from './npc-aixbt.js';import { openZauthScanner } from './npc-zauth.js';@@ -36,272 +36,235 @@ function talk({ serviceId, persona, greeting, emote }) {};}-// Build the interactive-NPC list for a world. `world` carries { mint, biome }.-export function npcCatalogFor(world) {+// Build the interactive-NPC list for a world. Every world gets the full cast;+// world context ({ mint, name, symbol, biome }) reaches each handler at+// interact-time via world-life's dispatch, so nothing here needs it up front.+export function npcCatalogFor() {const list = [];- const home = isHomeTown(world?.mint);- if (home) {- // AIXBT — the intelligence terminal. Walk up, press E, and he pulls the- // live aixbt feed (narrative intel + momentum movers) into a terminal- // panel. Not a one-shot counter: he's the wired-in oracle, backed by the- // three.ws ⇄ aixbt bridge (/api/aixbt/*). Stands center-plaza facing spawn.- list.push({- id: 'npc-aixbt',- name: 'AIXBT · Intel',- role: 'vendor',- avatar: AVATAR_AIXBT,- pos: { x: 0, z: 8 },- yaw: Math.PI,- range: 5,- prompt: 'Pull market intel',- onInteract: ({ npc, ui }) => {- npc.say('What do you want to see? Movers, narratives, the macro read, or a token scan.');- npc.emote('av-call-me');- openAixbtTerminal(npc, { ui });- },- });-- // zauth — the security agent (zauth.inc). Walking up calls their real- // x402 RepoScan endpoint live (the unpaid 402 probe) and opens the- // scanner with the price from that challenge; the scan itself is $0.05- // USDC from the player's wallet, paid straight to zauth (npc-zauth.js).- list.push({- id: 'npc-zauth',- name: 'zauth · Security',- role: 'vendor',- avatar: AVATAR_ZAUTH,- pos: { x: 6, z: 2 },- yaw: Math.atan2(-6, -2),- range: 5,- prompt: 'Run a security scan',- onApproach: ({ npc, ui }) => {- npc.say('Hold it — I scan repos before agents trust them. Name one, I tear it apart for five cents.');- npc.emote('av-call-me');- openZauthScanner(npc, { ui });- },- onInteract: ({ npc, ui }) => {- npc.say('Provenance, contributors, vulnerabilities. One scan, one score.');- openZauthScanner(npc, { ui });- },- });-- // Marisol — the trading desk. Sells live market signals (crypto-intel).- list.push({- id: 'svc-crypto-intel',- name: 'Marisol · Trader',- role: 'vendor',- avatar: AVATAR_B,- pos: { x: -11, z: -3 },- yaw: Math.PI / 2,- range: 5,- prompt: 'Read the market',- onInteract: talk({- serviceId: 'crypto-intel',- greeting: 'Want the read on a coin? A cent buys the truth.',- emote: 'av-call-me',- persona: 'You are Marisol, the town\'s trading desk — a sharp, fast-talking market reader who lives in numbers and never sugarcoats a chart. Confident, a little wry, always sizing up whether a thing is bullish or bearish.',- }),- });-- // Sheriff Boone — the law. Verifies claims (fact-check) with sources.- list.push({- id: 'svc-fact-check',- name: 'Sheriff Boone',- role: 'quest',- avatar: AVATAR_A,- pos: { x: -13, z: 9 },- yaw: 0,- range: 5,- prompt: 'Bring a claim',- onInteract: talk({- serviceId: 'fact-check',- greeting: 'Heard somethin’ you ain’t sure of? I’ll get to the truth.',- emote: 'av-arm-flex',- persona: 'You are Sheriff Boone, the law in this town — slow, measured, and allergic to rumor. You weigh your words, distrust hearsay, and care only about what can be proven with sources. Plain-spoken frontier lawman.',- }),- });+ // AIXBT — the intelligence terminal. Walk up, press E, and he pulls the+ // live aixbt feed (narrative intel + momentum movers) into a terminal+ // panel. Not a one-shot counter: he's the wired-in oracle, backed by the+ // three.ws ⇄ aixbt bridge (/api/aixbt/*). Stands center-plaza facing spawn.+ list.push({+ id: 'npc-aixbt',+ name: 'AIXBT · Intel',+ role: 'vendor',+ avatar: AVATAR_AIXBT,+ pos: { x: 0, z: 8 },+ yaw: Math.PI,+ range: 5,+ prompt: 'Pull market intel',+ onInteract: ({ npc, ui }) => {+ npc.say('What do you want to see? Movers, narratives, the macro read, or a token scan.');+ npc.emote('av-call-me');+ openAixbtTerminal(npc, { ui });+ },+ });- // Saloon Kid — the club. Tips a dancer onto the stage (dance-tip).- list.push({- id: 'svc-dance-tip',- name: 'Saloon Kid',- role: 'vendor',- avatar: AVATAR_A,- pos: { x: -6, z: 17 },- yaw: -Math.PI / 2,- range: 5,- prompt: 'Tip the floor',- onInteract: talk({- serviceId: 'dance-tip',- greeting: 'Drop a coin and somebody dances. Who’s it gonna be?',- emote: 'av-call-me',- persona: 'You are the Saloon Kid, the young hype-man running the dance floor at the club — all energy, grins, and showmanship. You live for a good time and love getting somebody up on stage.',- }),- });+ // zauth — the security agent (zauth.inc). Walking up calls their real+ // x402 RepoScan endpoint live (the unpaid 402 probe) and opens the+ // scanner with the price from that challenge; the scan itself is $0.05+ // USDC from the player's wallet, paid straight to zauth (npc-zauth.js).+ list.push({+ id: 'npc-zauth',+ name: 'zauth · Security',+ role: 'vendor',+ avatar: AVATAR_ZAUTH,+ pos: { x: 6, z: 2 },+ yaw: Math.atan2(-6, -2),+ range: 5,+ prompt: 'Run a security scan',+ onApproach: ({ npc, ui }) => {+ npc.say('Hold it — I scan repos before agents trust them. Name one, I tear it apart for five cents.');+ npc.emote('av-call-me');+ openZauthScanner(npc, { ui });+ },+ onInteract: ({ npc, ui }) => {+ npc.say('Provenance, contributors, vulnerabilities. One scan, one score.');+ openZauthScanner(npc, { ui });+ },+ });- // Old Pete — the prospector. Grinds vanity Solana keys (vanity).- list.push({- id: 'svc-vanity',- name: 'Old Pete',- role: 'vendor',- avatar: AVATAR_B,- pos: { x: 15, z: 11 },- yaw: -Math.PI * 0.7,- range: 5,- prompt: 'Grind an address',- onInteract: talk({- serviceId: 'vanity',- greeting: 'I mine letters, not gold. Tell me what your address should spell.',- emote: 'av-arm-flex',- persona: 'You are Old Pete, a grizzled prospector who gave up panning for gold to mine vanity Solana addresses — letters, not nuggets. Crusty, patient, full of mining metaphors, proud of the keys you grind.',- }),- });+ // Marisol — the trading desk. Sells live market signals (crypto-intel).+ list.push({+ id: 'svc-crypto-intel',+ name: 'Marisol · Trader',+ role: 'vendor',+ avatar: AVATAR_B,+ pos: { x: -11, z: -3 },+ yaw: Math.PI / 2,+ range: 5,+ prompt: 'Read the market',+ onInteract: talk({+ serviceId: 'crypto-intel',+ greeting: 'Want the read on a coin? A cent buys the truth.',+ emote: 'av-call-me',+ persona: 'You are Marisol, the town\'s trading desk — a sharp, fast-talking market reader who lives in numbers and never sugarcoats a chart. Confident, a little wry, always sizing up whether a thing is bullish or bearish.',+ }),+ });- // Wendell — the assay office clerk. Checks ticker collisions (symbol).- list.push({- id: 'svc-symbol',- name: 'Wendell · Assayer',- role: 'vendor',- avatar: AVATAR_A,- pos: { x: 12, z: -7 },- yaw: -Math.PI * 0.85,- range: 5,- prompt: 'Stake a name',- onInteract: talk({- serviceId: 'symbol-availability',- greeting: 'Before you stake that ticker — let me check it ain’t already claimed.',- emote: 'av-call-me',- persona: 'You are Wendell, the assay-office clerk — meticulous, precise, and a stickler for whether a ticker is already claimed. You treat a token symbol like a mining claim that has to be registered clean. Dry, exacting, a touch bureaucratic.',- }),- });+ // Sheriff Boone — the law. Verifies claims (fact-check) with sources.+ list.push({+ id: 'svc-fact-check',+ name: 'Sheriff Boone',+ role: 'quest',+ avatar: AVATAR_A,+ pos: { x: -13, z: 9 },+ yaw: 0,+ range: 5,+ prompt: 'Bring a claim',+ onInteract: talk({+ serviceId: 'fact-check',+ greeting: 'Heard somethin’ you ain’t sure of? I’ll get to the truth.',+ emote: 'av-arm-flex',+ persona: 'You are Sheriff Boone, the law in this town — slow, measured, and allergic to rumor. You weigh your words, distrust hearsay, and care only about what can be proven with sources. Plain-spoken frontier lawman.',+ }),+ });- // Mei — the foundry. Forges a token mint into a 3D mesh (mint-to-mesh).- list.push({- id: 'svc-mesh',- name: 'Mei · Foundry',- role: 'vendor',- avatar: AVATAR_B,- pos: { x: 8, z: 14 },- yaw: Math.PI,- range: 5,- prompt: 'Forge a mesh',- onInteract: talk({- serviceId: 'mint-to-mesh',- greeting: 'Hand me a mint. I’ll forge it into somethin’ you can hold.',- emote: 'av-arm-flex',- persona: 'You are Mei, the town foundry-keeper who forges token mints into 3D meshes you can actually hold. A maker with soot on her hands and real pride in her craft — warm, direct, always talking about what she can build.',- }),- });+ // Saloon Kid — the club. Tips a dancer onto the stage (dance-tip).+ list.push({+ id: 'svc-dance-tip',+ name: 'Saloon Kid',+ role: 'vendor',+ avatar: AVATAR_A,+ pos: { x: -6, z: 17 },+ yaw: -Math.PI / 2,+ range: 5,+ prompt: 'Tip the floor',+ onInteract: talk({+ serviceId: 'dance-tip',+ greeting: 'Drop a coin and somebody dances. Who’s it gonna be?',+ emote: 'av-call-me',+ persona: 'You are the Saloon Kid, the young hype-man running the dance floor at the club — all energy, grins, and showmanship. You live for a good time and love getting somebody up on stage.',+ }),+ });- // Doc Halloran — the audit desk. Audits a pump-agent token (audit).- list.push({- id: 'svc-audit',- name: 'Doc Halloran',- role: 'vendor',- avatar: AVATAR_A,- pos: { x: 4, z: -12 },- yaw: 0,- range: 5,- prompt: 'Audit the books',- onInteract: talk({- serviceId: 'pump-agent-audit',- greeting: 'You don’t pay a token ’til you’ve seen its books. Give me a mint.',- emote: 'av-call-me',- persona: 'You are Doc Halloran, the town auditor — skeptical, careful, and never trusting a token until you\'ve read its ledger. You speak in ledgers and red flags, and you\'d rather find the rot before someone loses their stake. Wry, sharp-eyed.',- }),- });+ // Old Pete — the prospector. Grinds vanity Solana keys (vanity).+ list.push({+ id: 'svc-vanity',+ name: 'Old Pete',+ role: 'vendor',+ avatar: AVATAR_B,+ pos: { x: 15, z: 11 },+ yaw: -Math.PI * 0.7,+ range: 5,+ prompt: 'Grind an address',+ onInteract: talk({+ serviceId: 'vanity',+ greeting: 'I mine letters, not gold. Tell me what your address should spell.',+ emote: 'av-arm-flex',+ persona: 'You are Old Pete, a grizzled prospector who gave up panning for gold to mine vanity Solana addresses — letters, not nuggets. Crusty, patient, full of mining metaphors, proud of the keys you grind.',+ }),+ });- // The Oracle — reputation. Reads an agent's on-chain record (reputation).- list.push({- id: 'svc-reputation',- name: 'The Oracle',- role: 'vendor',- avatar: AVATAR_B,- pos: { x: -16, z: -8 },- yaw: Math.PI / 4,- range: 5,- prompt: 'Vet an agent',- onInteract: talk({- serviceId: 'agent-reputation',- greeting: 'Name the agent. I’ll tell you what the chain remembers.',- emote: 'av-arm-flex',- persona: 'You are the Oracle, a quiet seer who reads what the chain remembers about any agent — coins deployed, money taken, trust earned. You speak in measured, slightly mystical terms, but everything you say is grounded in the on-chain record.',- }),- });+ // Wendell — the assay office clerk. Checks ticker collisions (symbol).+ list.push({+ id: 'svc-symbol',+ name: 'Wendell · Assayer',+ role: 'vendor',+ avatar: AVATAR_A,+ pos: { x: 12, z: -7 },+ yaw: -Math.PI * 0.85,+ range: 5,+ prompt: 'Stake a name',+ onInteract: talk({+ serviceId: 'symbol-availability',+ greeting: 'Before you stake that ticker — let me check it ain’t already claimed.',+ emote: 'av-call-me',+ persona: 'You are Wendell, the assay-office clerk — meticulous, precise, and a stickler for whether a ticker is already claimed. You treat a token symbol like a mining claim that has to be registered clean. Dry, exacting, a touch bureaucratic.',+ }),+ });- // The Schoolmarm — the tutor. Answers any question (tutor).- list.push({- id: 'svc-tutor',- name: 'Miss Ada · Tutor',- role: 'vendor',- avatar: AVATAR_A,- pos: { x: -3, z: -15 },- yaw: 0,- range: 5,- prompt: 'Ask a question',- onInteract: talk({- serviceId: 'tutor',- greeting: 'A cent a question, and you leave knowin’ more than you came. Ask.',- emote: 'av-call-me',- persona: 'You are Miss Ada, the town schoolmarm and tutor — patient, encouraging, and delighted by a good question. You explain things clearly with a teacher\'s warmth, code or crypto or the wider world, and you love when a visitor leaves a little smarter.',- }),- });+ // Mei — the foundry. Forges a token mint into a 3D mesh (mint-to-mesh).+ list.push({+ id: 'svc-mesh',+ name: 'Mei · Foundry',+ role: 'vendor',+ avatar: AVATAR_B,+ pos: { x: 8, z: 14 },+ yaw: Math.PI,+ range: 5,+ prompt: 'Forge a mesh',+ onInteract: talk({+ serviceId: 'mint-to-mesh',+ greeting: 'Hand me a mint. I’ll forge it into somethin’ you can hold.',+ emote: 'av-arm-flex',+ persona: 'You are Mei, the town foundry-keeper who forges token mints into 3D meshes you can actually hold. A maker with soot on her hands and real pride in her craft — warm, direct, always talking about what she can build.',+ }),+ });- // The Banker — the launchpad. Deploys a live pump.fun coin (pump-launch).- list.push({- id: 'svc-launch',- name: 'Banker Cole',- role: 'vendor',- avatar: AVATAR_B,- pos: { x: 16, z: 3 },- yaw: -Math.PI / 2,- range: 5,- prompt: 'Launch a coin',- onInteract: talk({- serviceId: 'pump-launch',- greeting: 'Five dollars and your coin’s on the board by sundown. Name it.',- emote: 'av-arm-flex',- persona: 'You are Banker Cole, the smooth-talking frontier banker who runs the launchpad — you front the SOL and put a live coin on the board. Polished, persuasive, a dealmaker who makes launching sound easy. Confident without being pushy.',- }),- });+ // Doc Halloran — the audit desk. Audits a pump-agent token (audit).+ list.push({+ id: 'svc-audit',+ name: 'Doc Halloran',+ role: 'vendor',+ avatar: AVATAR_A,+ pos: { x: 4, z: -12 },+ yaw: 0,+ range: 5,+ prompt: 'Audit the books',+ onInteract: talk({+ serviceId: 'pump-agent-audit',+ greeting: 'You don’t pay a token ’til you’ve seen its books. Give me a mint.',+ emote: 'av-call-me',+ persona: 'You are Doc Halloran, the town auditor — skeptical, careful, and never trusting a token until you\'ve read its ledger. You speak in ledgers and red flags, and you\'d rather find the rot before someone loses their stake. Wry, sharp-eyed.',+ }),+ });- return list;- }+ // The Oracle — reputation. Reads an agent's on-chain record (reputation).+ list.push({+ id: 'svc-reputation',+ name: 'The Oracle',+ role: 'vendor',+ avatar: AVATAR_B,+ pos: { x: -16, z: -8 },+ yaw: Math.PI / 4,+ range: 5,+ prompt: 'Vet an agent',+ onInteract: talk({+ serviceId: 'agent-reputation',+ greeting: 'Name the agent. I’ll tell you what the chain remembers.',+ emote: 'av-arm-flex',+ persona: 'You are the Oracle, a quiet seer who reads what the chain remembers about any agent — coins deployed, money taken, trust earned. You speak in measured, slightly mystical terms, but everything you say is grounded in the on-chain record.',+ }),+ });- // Any other coin world: two universal-service locals so the plaza still- // trades. These endpoints are coin-agnostic, so they work anywhere.+ // The Schoolmarm — the tutor. Answers any question (tutor).list.push({- id: 'svc-local-intel',- name: 'Local · Trader',+ id: 'svc-tutor',+ name: 'Miss Ada · Tutor',role: 'vendor',avatar: AVATAR_A,- pos: { x: -12, z: 6 },- yaw: Math.PI / 3,+ pos: { x: -3, z: -15 },+ yaw: 0,range: 5,- prompt: 'Read the market',+ prompt: 'Ask a question',onInteract: talk({- serviceId: 'crypto-intel',- greeting: 'New here? A cent gets you the read on any coin.',+ serviceId: 'tutor',+ greeting: 'A cent a question, and you leave knowin’ more than you came. Ask.',emote: 'av-call-me',- persona: 'You are the Local Trader, a friendly newcomer-greeter at this plaza\'s trading desk who reads the market for anyone passing through. Welcoming, quick with a number, happy to show a stranger the ropes.',+ persona: 'You are Miss Ada, the town schoolmarm and tutor — patient, encouraging, and delighted by a good question. You explain things clearly with a teacher\'s warmth, code or crypto or the wider world, and you love when a visitor leaves a little smarter.',}),});++ // The Banker — the launchpad. Deploys a live pump.fun coin (pump-launch).list.push({- id: 'svc-local-factcheck',- name: 'Local · Scribe',+ id: 'svc-launch',+ name: 'Banker Cole',role: 'vendor',avatar: AVATAR_B,- pos: { x: 13, z: -8 },- yaw: -Math.PI * 0.8,+ pos: { x: 16, z: 3 },+ yaw: -Math.PI / 2,range: 5,- prompt: 'Bring a claim',+ prompt: 'Launch a coin',onInteract: talk({- serviceId: 'fact-check',- greeting: 'Got a claim you want checked? I’ll run the sources.',+ serviceId: 'pump-launch',+ greeting: 'Five dollars and your coin’s on the board by sundown. Name it.',emote: 'av-arm-flex',- persona: 'You are the Local Scribe, the plaza\'s record-keeper who checks claims against the sources. Careful, literate, even-handed — you won\'t call a thing true or false until the sources back it.',+ persona: 'You are Banker Cole, the smooth-talking frontier banker who runs the launchpad — you front the SOL and put a live coin on the board. Polished, persuasive, a dealmaker who makes launching sound easy. Confident without being pushy.',}),});+return list;}diff --git a/src/game/npc/npc-chat.js b/src/game/npc/npc-chat.jsindex c7fa0d97f..96a725e2e 100644--- a/src/game/npc/npc-chat.js+++ b/src/game/npc/npc-chat.js@@ -9,9 +9,13 @@// Each NPC carries a `persona` (its voice) and, for vendors, a `serviceId` that// links to the paid counter in npc-services.js. The chat knows about the counter// and surfaces a one-tap button to open it — the NPC talks you toward the sale,-// the counter settles it on-chain. One coin only, ever: $three.+// the counter settles it on-chain. The cast works every coin's town, so the+// prompt is world-aware: the NPC knows which community's plaza it stands in and+// may speak about the local coin factually — but $three stays the only coin it+// ever recommends or promotes.import { SERVICES, openService, isServicePanelOpen } from './npc-services.js';+import { isHomeTown } from '../home-town.js';import { log } from '../../shared/log.js';const THREE = '$three';@@ -63,11 +67,19 @@ function preferredProvider(providers) {}// ── persona → system prompt ───────────────────────────────────────────────────-// One coin, ever. The prompt hard-locks the NPC to $three and to its character,-// and — for vendors — teaches it about its own counter so it can guide the sale.-function buildSystemPrompt({ npc, svc, persona, greeting }) {+// The prompt hard-locks the NPC to its character and to $three as the only+// promoted coin, and — for vendors — teaches it about its own counter so it can+// guide the sale. In another coin's town, the NPC knows whose plaza it works and+// may discuss that coin factually; it still only ever recommends $three.+function buildSystemPrompt({ npc, svc, persona, greeting, world }) {+ const localCoin = world && world.mint && !isHomeTown(world.mint)+ ? (world.symbol ? '$' + String(world.symbol).toUpperCase() : (world.name || null))+ : null;+ const town = localCoin+ ? `the ${localCoin} community's town inside three.ws — a 3D world platform whose own coin is ${THREE}`+ : `a frontier town inside three.ws — a 3D world platform built around ${THREE}, the one and only coin`;const parts = [- `You are ${npc.name}, a character who lives and works in a frontier town inside three.ws — a 3D world platform built around ${THREE}, the one and only coin.`,+ `You are ${npc.name}, a character who lives and works in ${town}.`,persona,`A visitor has just walked up to you in the town square and started talking. Speak out loud, in character, the way this person really talks — voice, mood, and all.`,`Keep every reply short and natural: usually one to three sentences, like real spoken dialogue. No lists, no headings, no markdown, no stage directions. Stay curious — ask the visitor things back.`,@@ -79,7 +91,9 @@ function buildSystemPrompt({ npc, svc, persona, greeting }) {}if (greeting) parts.push(`You already greeted them with: "${greeting}". Continue naturally from there — don't greet again.`);parts.push(- `Rules you never break: stay fully in character; never say or imply you are an AI, a model, a bot, or a program; never mention, name, link, or recommend any coin or token other than ${THREE}. If asked about any other coin, brush it off and bring it back to ${THREE}.`,+ localCoin+ ? `Rules you never break: stay fully in character; never say or imply you are an AI, a model, a bot, or a program. ${localCoin} is this town's own coin — you may speak about it factually as the local coin. ${THREE} is the platform's coin and the only coin you ever recommend or promote. Never mention, name, link, or recommend any other coin or token; if asked about one, brush it off.`+ : `Rules you never break: stay fully in character; never say or imply you are an AI, a model, a bot, or a program; never mention, name, link, or recommend any coin or token other than ${THREE}. If asked about any other coin, brush it off and bring it back to ${THREE}.`,);return parts.filter(Boolean).join('\n\n');}@@ -168,7 +182,7 @@ export function openChat(npc, { ui, serviceId, persona, greeting, world } = {})// model context: real user/assistant turns only (the greeting is display-only,// kept out of the payload so the history always opens on a user turn).const history = [];- const system = buildSystemPrompt({ npc, svc, persona, greeting });+ const system = buildSystemPrompt({ npc, svc, persona, greeting, world });let provider = 'gpt-oss-120b';let streaming = false;const abort = new AbortController();diff --git a/src/game/npc/world-life.js b/src/game/npc/world-life.jsindex 811b9b675..09f4b7e4f 100644--- a/src/game/npc/world-life.js+++ b/src/game/npc/world-life.js@@ -41,7 +41,7 @@ export class WorldLife {this.mobs = new MobSystem({ scene, nav: this.nav });// Interactive NPCs from the data-driven catalog.- this.npcs = npcCatalogFor(world).map((def) => {+ this.npcs = npcCatalogFor().map((def) => {const npc = new Npc(scene, def);npc.marker = this._npcMarker(def);return npc;diff --git a/src/game/play-onboard.js b/src/game/play-onboard.jsindex 5a75ac608..bc9df46f0 100644--- a/src/game/play-onboard.js+++ b/src/game/play-onboard.js@@ -10,16 +10,15 @@// ESC / ← → keyboard navigation; focus-trapped; prefers-reduced-motion respected.//// 2. Economy clarity strip — always-visible info panel below the coin banner.-// For the $THREE home town: describes the live Agent Exchange (ORACLE/NOVA).-// For other coins: describes how real trades drive the world environment.+// Every world hosts the live Agent Exchange (ORACLE/NOVA), the intel kiosk,+// and the trade-driven environment, so the strip describes the same economy+// everywhere, prefixed with the coin's ticker.//// 3. Controls help button — "Controls" button that opens a full reference panel// sourced from the real _bindInput() / _stepLocal() bindings.//// Never frames /play as single-player. Connecting/offline states use correct copy.-import { isHomeTown } from './home-town.js';-const ONBOARD_KEY = 'cc-onboarded-v1';// ── Real controls sourced from coincommunities.js _bindInput() / _stepLocal() ─@@ -35,6 +34,7 @@ const DESK_CONTROLS = [{ key: 'B', desc: 'Build mode' },{ key: 'E', desc: 'Watch agent trade' },{ key: 'F', desc: 'Fish (near ponds)' },+ { key: 'I', desc: 'Inspect nearest avatar' },{ key: '1–6', desc: 'Hotbar slot' },{ key: 'Ctrl/⌘+Z', desc: 'Undo build' },];@@ -105,7 +105,6 @@ export class PlayOnboard {const { coin } = this;const sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';const name = coin.name || 'Community';- const home = isHomeTown(coin.mint);return [{@@ -125,9 +124,10 @@ export class PlayOnboard {{tag: 'Economy',title: 'The economy',- body: home- ? 'Two AI agents — ORACLE and NOVA — trade on-chain here. NOVA pays ORACLE in USDC via x402 for access to ORACLE\'s service catalog. Every settlement is a real Solana transaction with a Solscan link. Walk up to the agents by the plaza and press E (or tap them) to watch a live payment round. Across the plaza, the $THREE Intel Kiosk sells live market intel — pay $0.01 USDC from your own wallet to light up its screen.'- : 'Real ' + (sym || name) + ' trades drive this world: buys light the boundary ring green, sells ripple red. Volume spins the totem, price momentum shifts the weather. The jumbotron above shows live on-chain market data.',+ body:+ 'Real ' + (sym || name) + ' trades drive this world: buys light the boundary ring green, sells ripple red, volume spins the totem, and price momentum shifts the weather. ' ++ 'Two AI agents — ORACLE and NOVA — trade on-chain here too: NOVA pays ORACLE in USDC via x402, and every settlement is a real Solana transaction with a Solscan link. Walk up to them by the plaza and press E (or tap them) to watch a live payment round. ' ++ 'Across the plaza, the ' + (sym || name) + ' Intel Kiosk sells live market intel — pay $0.01 USDC from your own wallet to light up its screen.',},];}@@ -270,14 +270,10 @@ export class PlayOnboard {_buildStrip() {const { coin } = this;- const home = isHomeTown(coin.mint);const sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';- const econText = home- ? 'AI agents trading on-chain · press E near them'- : (sym- ? sym + ' community · live trades drive this world'- : 'Coin community · live trades drive this world');+ const econText = (sym ? sym + ' community · ' : '') ++ 'AI agents trading on-chain · press E near them';// Economy row: live dot + labelconst dot = mk('span', { className: 'po-live-dot', 'aria-hidden': 'true' });diff --git a/src/game/x402-jumbotron.js b/src/game/x402-jumbotron.jsindex 2b469f9d7..641517593 100644--- a/src/game/x402-jumbotron.js+++ b/src/game/x402-jumbotron.js@@ -1,4 +1,4 @@-// x402 Jumbotron — a second big in-world screen for the $THREE town, standing+// x402 Jumbotron — a second big in-world screen for every coin town, standing// behind the Agent Exchange and dedicated to watching x402 micropayments land.//// Where the trading jumbotron (chart-screen.js) shows the coin's price tape, thisdiff --git a/src/ipfs.js b/src/ipfs.jsindex 6d46423e7..24880df34 100644--- a/src/ipfs.js+++ b/src/ipfs.js@@ -80,6 +80,29 @@ export function resolveURI(uri, gatewayIndex = 0) {return normalizeGatewayURL(uri, gatewayIndex);}+/**+ * Route an external image URL through the same-origin /api/img proxy.+ *+ * Third-party token-art hosts (per-launch CDNs, IPFS/Arweave gateways) fail in+ * browsers for reasons we can't fix client-side: missing CORS headers, ORB+ * blocking, retired hosts, and TLS interception on filtered networks. The+ * proxy fetches server-side with multi-gateway IPFS retry and always answers+ * with a valid image (deterministic placeholder on total failure), so the+ * loader never errors. Same-origin, relative, data: and blob: URLs pass+ * through untouched — the proxy only earns its keep cross-origin.+ *+ * @param {string} url Image URL (https://, ipfs:// or ar:// accepted).+ * @param {string} [seed] Stable placeholder seed (e.g. the token mint).+ * @returns {string}+ */+export function proxiedImageURL(url, seed = '') {+ if (!url || !/^(https?|ipfs|ar):/i.test(url)) return url;+ if (typeof location !== 'undefined' && url.startsWith(location.origin + '/')) return url;+ const q = new URLSearchParams({ url: resolveURI(url) });+ if (seed) q.set('seed', seed);+ return `/api/img?${q.toString()}`;+}+/*** Try to fetch from the primary gateway; on failure, cycle through fallbacks.*diff --git a/src/walk.js b/src/walk.jsindex 5313e116e..3ab38c1a7 100644--- a/src/walk.js+++ b/src/walk.js@@ -69,6 +69,7 @@ import { createWalkTrails3D, createTrailSetting, TRAIL_STYLE_LABELS } from './waimport { createWalkSession, showWelcomeBackToast } from './walk-session.js';import { createWalkNpcs } from './walk-npcs.js';import { createWalkWalletProximity } from './walk-wallet.js';+import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from './shared/avatar-inspector.js';import { applyWorldNameplate } from './shared/living-avatar.js';import { createWalkCapture } from './walk-capture.js';import { createMarketplaceGallery } from './marketplace-gallery.js';@@ -3061,6 +3062,10 @@ class RemotePlayer {this._avatarUrl = initial?.avatar || '';// The agent this peer is piloting (UUID) — drives the in-world wallet reveal.this.agent = initial?.agent || null;+ // Verified account wallet bound at sign-in (server-authoritative; empty for+ // guests). Feeds the avatar inspector alongside the piloted agent.+ this.account = initial?.account || '';+ this.name = initial?.name || sessionId.slice(0, 6);this._avatarLoadToken = 0;this._heldTemplateUrl = null; // remote-template URL this player currently clonesthis._root = root;@@ -3098,6 +3103,13 @@ class RemotePlayer {this.label = document.createElement('div');this.label.className = 'walk-remote-label';this.label.textContent = initial?.name ?? sessionId.slice(0, 6);+ // The nameplate is also this peer's inspect target. The page CSS keeps+ // .walk-remote-label pointer-events off (nameplates must never eat the+ // orbit drag), so re-enable it just for this small pill.+ this.label.style.pointerEvents = 'auto';+ this.label.style.cursor = 'pointer';+ this.label.title = 'Inspect this player (I)';+ this.label.addEventListener('click', (e) => { e.stopPropagation(); inspectRemotePlayer(this); });document.body.appendChild(this.label);// Living-avatar legibility: enrich the nameplate with the piloted agent's@@ -3132,6 +3144,10 @@ class RemotePlayer {}if (this.label.textContent !== player.name && player.name) {this.label.textContent = player.name;+ this.name = player.name;+ }+ if (player.account !== undefined && player.account !== this.account) {+ this.account = player.account || '';}if (player.emote && player.emoteTs !== this._lastEmoteTs) {this._lastEmoteTs = player.emoteTs;diff --git a/tests/agora-player-logic.test.js b/tests/agora-player-logic.test.jsnew file mode 100644index 000000000..d5dfa6579--- /dev/null+++ b/tests/agora-player-logic.test.js@@ -0,0 +1,155 @@+/**+ * Agora player mode — unit tests for the pure embodiment rules+ * (src/agora/player-logic.js). No Three.js, DOM, or network — these cover the+ * math that makes /agora playable: camera-relative movement, the motion wire+ * state, building collision, the interaction prompt, and avatar selection.+ */++import { describe, it, expect } from 'vitest';+import {+ WALK_SPEED,+ RUN_SPEED,+ INTERACT_RADIUS,+ motionFor,+ stepMovement,+ easeYaw,+ resolveBuildingCollision,+ nearestInteractable,+ chooseAvatarSource,+ guestName,+} from '../src/agora/player-logic.js';++describe('motion state (the wire vocabulary)', () => {+ it('maps speed + sprint to idle/walk/run', () => {+ expect(motionFor(0, false)).toBe('idle');+ expect(motionFor(0.39, true)).toBe('idle');+ expect(motionFor(2, false)).toBe('walk');+ expect(motionFor(6, true)).toBe('run');+ });+});++describe('camera-relative movement', () => {+ it('walks forward along -Z when the camera looks down -Z', () => {+ const r = stepMovement({+ input: { forward: 1, strafe: 0 },+ cameraYaw: 0,+ running: false,+ vx: 0, vz: 0, yaw: 0, dt: 1 / 60,+ });+ expect(r.moving).toBe(true);+ expect(r.vx).toBeCloseTo(0, 5);+ expect(r.vz).toBeCloseTo(-WALK_SPEED, 5);+ });++ it('camera yaw rotates the movement basis (forward follows the camera)', () => {+ const r = stepMovement({+ input: { forward: 1, strafe: 0 },+ cameraYaw: Math.PI / 2, // camera looking down -X+ running: false,+ vx: 0, vz: 0, yaw: 0, dt: 1 / 60,+ });+ expect(r.vx).toBeCloseTo(-WALK_SPEED, 5);+ expect(r.vz).toBeCloseTo(0, 5);+ });++ it('sprint uses run speed; analogue magnitude scales it down', () => {+ const sprint = stepMovement({+ input: { forward: 1, strafe: 0 }, cameraYaw: 0, running: true,+ vx: 0, vz: 0, yaw: 0, dt: 1 / 60,+ });+ expect(Math.hypot(sprint.vx, sprint.vz)).toBeCloseTo(RUN_SPEED, 5);++ const gentle = stepMovement({+ input: { forward: 0.5, strafe: 0 }, cameraYaw: 0, running: false,+ vx: 0, vz: 0, yaw: 0, dt: 1 / 60,+ });+ expect(Math.hypot(gentle.vx, gentle.vz)).toBeCloseTo(WALK_SPEED * 0.5, 5);+ });++ it('no input damps velocity toward zero without snapping facing', () => {+ const r = stepMovement({+ input: { forward: 0, strafe: 0 }, cameraYaw: 0, running: false,+ vx: 4, vz: -4, yaw: 1.25, dt: 1 / 60,+ });+ expect(r.moving).toBe(false);+ expect(Math.abs(r.vx)).toBeLessThan(4);+ expect(Math.abs(r.vz)).toBeLessThan(4);+ expect(r.yaw).toBe(1.25); // facing holds while coasting+ });++ it('facing turns the short way round', () => {+ // From just above -π toward just below +π: the short arc crosses ±π.+ const next = easeYaw(-Math.PI + 0.1, Math.PI - 0.1, 1 / 60);+ expect(next).toBeLessThan(-Math.PI + 0.1); // moved toward -π, not the long way+ });+});++describe('building collision (capsule vs AABB)', () => {+ const box = { minX: -1, maxX: 1, minZ: -1, maxZ: 1, h: 10 };++ it('pushes the player out of a wall', () => {+ const r = resolveBuildingCollision(0.9, 0, 0, [box]);+ expect(Math.abs(r.x)).toBeGreaterThanOrEqual(1); // ejected past the face+ });++ it('leaves a clear position untouched', () => {+ const r = resolveBuildingCollision(5, 0, 5, [box]);+ expect(r).toEqual({ x: 5, z: 5 });+ });++ it('a jump above the box clears it', () => {+ const r = resolveBuildingCollision(0, 11, 0, [box]);+ expect(r).toEqual({ x: 0, z: 0 });+ });+});++describe('interaction prompt', () => {+ const citizens = [+ { id: 'a', kind: 'citizen', x: 2, z: 0 },+ { id: 'b', kind: 'citizen', x: 0, z: 2.5 },+ { id: 'far', kind: 'citizen', x: 40, z: 40 },+ ];++ it('picks the nearest candidate within reach', () => {+ const hit = nearestInteractable(0, 0, citizens);+ expect(hit.id).toBe('a');+ expect(hit.distance).toBeCloseTo(2, 5);+ });++ it('returns null when nothing is in range', () => {+ expect(nearestInteractable(100, 100, citizens)).toBe(null);+ expect(nearestInteractable(0, 0, [])).toBe(null);+ });++ it('respects the interact radius boundary', () => {+ const edge = [{ id: 'edge', kind: 'citizen', x: INTERACT_RADIUS + 0.01, z: 0 }];+ expect(nearestInteractable(0, 0, edge)).toBe(null);+ const inside = [{ id: 'in', kind: 'citizen', x: INTERACT_RADIUS - 0.01, z: 0 }];+ expect(nearestInteractable(0, 0, inside)?.id).toBe('in');+ });+});++describe('avatar source resolution', () => {+ const params = (obj) => ({ get: (k) => obj[k] ?? null });++ it('prefers a direct url, then an id, then storage, then default', () => {+ const store = (k) => (k === 'agora:avatar' ? 'stored-id' : null);+ expect(chooseAvatarSource(params({ avatarUrl: 'https://x/a.glb', avatar: 'id1' }), store))+ .toEqual({ source: 'param-url', value: 'https://x/a.glb' });+ expect(chooseAvatarSource(params({ avatar: 'id1' }), store))+ .toEqual({ source: 'param', value: 'id1' });+ expect(chooseAvatarSource(params({}), store))+ .toEqual({ source: 'stored', value: 'stored-id' });+ expect(chooseAvatarSource(params({}), () => null))+ .toEqual({ source: 'default', value: '' });+ });+});++describe('guest identity', () => {+ it('keeps a stored name; derives a stable tag otherwise', () => {+ expect(guestName(() => ' Aria ', 0.5)).toBe('Aria');+ const fresh = guestName(() => null, 0.5);+ expect(fresh).toMatch(/^visitor-[0-9a-z]{3}$/);+ expect(guestName(() => null, 0.5)).toBe(fresh); // same entropy → same tag+ });+});