Skip to content

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

feat(agora): enhance player mode with proximity interactions and chat functionality

nirholascaba057263b1
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 4437d52d7..4235d3629 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -1643,11 +1643,11 @@ The only piece that keeps the live graduation WebSocket open. Holds a long-lived
#### `services/agent-screen-caster` — self-hosted agent screen caster
-A reusable **Playwright caster library + CLI** (`AgentScreenCaster` class) an agent *owner* self-hosts to stream that agent's real browser work into three.ws. Authenticates with a per-agent bearer token/API key minted by `POST /api/agent/caster-config` (which returns a ready-to-paste `.env` + `docker run`). Ships task modules `pump-monitor` (watch a pump.fun coin via DOM MutationObserver) and `trade` (drive Jupiter/Raydium/pump.fun swap UIs). Pushes base64 JPEG frames to `POST /api/agent/screen-push` on a `FRAME_INTERVAL_MS` loop.
+A reusable **Playwright caster library + CLI** (`AgentScreenCaster` class) an agent *owner* self-hosts to stream that agent's real browser work into three.ws. Authenticates with a per-agent bearer token/API key minted by `POST /api/agent/caster-config` (which returns a ready-to-paste `.env` + `docker run`). Ships task modules `pump-monitor` (watch a pump.fun coin via DOM MutationObserver) and `trade` (drive Jupiter/Raydium/pump.fun swap UIs). Pushes JPEG data-URL frames to `POST /api/agent-screen-push` on a `FRAME_INTERVAL_MS` loop.
- `caster.js` — the `AgentScreenCaster` Playwright wrapper (frame loop, push primitives).
- `tasks/pump-monitor.js`, `tasks/trade.js` — bundled task modules.
-- **Env:** `AGENT_ID`*, `AGENT_BEARER_TOKEN`*, `PUSH_URL` (default `https://three.ws/api/agent/screen-push`), `FRAME_INTERVAL_MS` (400), `JPEG_QUALITY` (72), `HEADLESS`, `TASK`, `TASK_ARG`, `WALLET_STORAGE_STATE_PATH`.
+- **Env:** `AGENT_ID`*, `AGENT_BEARER_TOKEN`*, `PUSH_URL` (default `https://three.ws/api/agent-screen-push`), `FRAME_INTERVAL_MS` (400), `JPEG_QUALITY` (72), `HEADLESS`, `TASK`, `TASK_ARG`, `WALLET_STORAGE_STATE_PATH`.
---
@@ -2638,13 +2638,13 @@ The worker and `api/sniper/*` are separate processes that **communicate only thr
"Agent screen casting" streams a live view of an agent working — a real Chromium screenshot feed plus a structured activity log — so a spectator can *watch an agent do real web work* in real time. Every agent gets a **zero-cost baseline screen 24/7** (the SSE stream synthesizes a feed from the agent's real `agent_actions` DB rows when no browser is running); on top of that, an *optional* real-browser pixel feed spins up only for agents people are actively watching and is torn down when the last viewer leaves. Consumers: the 2D viewer `/agent-screen`, the live wall `/agents-live`, and in-world 3D "agent desk" surfaces.
-**Transport:** plain HTTP POST of base64 JPEG/PNG frames + **Server-Sent Events** polling Redis (~250–500ms) — no WebRTC/WebSocket/HLS. Capture is headless Chromium via Playwright (Stagehand for the per-agent worker; optional Browserbase cloud). Two frame conventions coexist (both written by the pool so a watched agent goes live everywhere at once): **dashed** (wall + 2D viewer, `POST /api/agent-screen-push` → Redis `agent:screen:{id}:frame` TTL 90s → `GET /api/agent-screen-stream`) and **slashed** (3D desk, `POST /api/agent/screen-push` → `screen:frame:{id}` TTL 10s → `GET /api/agent/screen-stream`).
+**Transport:** plain HTTP POST of base64 JPEG/PNG frames + **Server-Sent Events** polling Redis (~250–500ms) — no WebRTC/WebSocket/HLS. Capture is headless Chromium via Playwright (Stagehand for the per-agent worker; optional Browserbase cloud). One frame convention serves every surface (wall, 2D viewer, and 3D desk): `POST /api/agent-screen-push` → Redis `agent:screen:{id}:frame` TTL 90s → `GET /api/agent-screen-stream`.
-**Producers:** `workers/agent-screen-worker` (per-agent, owner-run; Stagehand `act()`/`extract()` runs user-queued tasks, rests on the agent's home when idle), `workers/agent-screen-pool` (on-demand multi-agent caster; polls `GET /api/agent/watch-wanted`, keeps ≤`MAX_BROWSERS` pages, screenshots every `FRAME_MS`, runs a real multi-step web task or a "Coin World Tour", pushes to both conventions), and `services/agent-screen-caster` (self-hosted library+CLI, above).
+**Producers:** `workers/agent-screen-worker` (per-agent, owner-run; Stagehand `act()`/`extract()` runs user-queued tasks, rests on the agent's home when idle), `workers/agent-screen-pool` (on-demand multi-agent caster; polls `GET /api/agent/watch-wanted`, keeps ≤`MAX_BROWSERS` pages, screenshots every `FRAME_MS`, runs a real multi-step web task or a "Coin World Tour"), and `services/agent-screen-caster` (self-hosted library+CLI, above).
-**API:** `POST /api/agent-screen-push` / `GET /api/agent-screen-stream` / `GET /api/agent-screen-active` (dashed), `POST /api/agent/screen-push` / `GET /api/agent/screen-stream` (slashed), `POST /api/agent/watch-intent` (viewer "I'm watching" + emoji reaction → Redis `screen:wanted`), `GET /api/agent/watch-wanted` (pool reads the set; `SCREEN_WORKER_SECRET`), `GET /api/agent/watch-status` (casting/warming/queued#N/activity handoff), `POST /api/agent/caster-config` (mint scoped `api_keys` row + emit `.env`/docker for the caster). Helper: `api/_lib/agent-screen-frame.js` (`writeScreenFrame()`).
+**API:** `POST /api/agent-screen-push` / `GET /api/agent-screen-stream` / `GET /api/agent-screen-active`, `POST /api/agent/watch-intent` (viewer "I'm watching" + emoji reaction → Redis `screen:wanted`), `GET /api/agent/watch-wanted` (pool reads the set; `SCREEN_WORKER_SECRET`), `GET /api/agent/watch-status` (casting/warming/queued#N/activity handoff), `POST /api/agent/caster-config` (mint scoped `api_keys` row + emit `.env`/docker for the caster). Helper: `api/_lib/agent-screen-frame.js` (`writeScreenFrame()`).
-**Frontend:** `pages/agent-screen.html` → `src/agent-screen.js` → `src/shared/agent-screen-client.js` (EventSource wrapper w/ backoff); 3D desks `src/game/agent-desk.js`, `src/walk-agent-desk.js`; live wall `src/agents-live.js`. **Ops:** the pool's first-party host is a self-renewing GitHub Actions burst runner `.github/workflows/agent-screen-pool.yml` (`cron: 0 */5 * * *`, `timeout 320m`), or any Docker VM/Fly/Railway. **Env:** `SCREEN_WORKER_SECRET` (API + pool), `SCREEN_POOL_MAX` (queue math), plus per-producer `AGENT_ID`/`AGENT_JWT`/`AGENT_BEARER_TOKEN`, `PUSH_URL`(`_DESK`), `MAX_BROWSERS`, `FRAME_MS`, `BROWSERBASE_API_KEY`. Falls back to the `agent_actions` feed when no live caster is pushing.
+**Frontend:** `pages/agent-screen.html` → `src/agent-screen.js` → `src/shared/agent-screen-client.js` (EventSource wrapper w/ backoff); 3D desks `src/game/agent-desk.js`, `src/walk-agent-desk.js`; live wall `src/agents-live.js`. **Ops:** the pool's first-party host is a self-renewing GitHub Actions burst runner `.github/workflows/agent-screen-pool.yml` (`cron: 0 */5 * * *`, `timeout 320m`), or any Docker VM/Fly/Railway. **Env:** `SCREEN_WORKER_SECRET` (API + pool), `SCREEN_POOL_MAX` (queue math), plus per-producer `AGENT_ID`/`AGENT_JWT`/`AGENT_BEARER_TOKEN`, `PUSH_URL`, `MAX_BROWSERS`, `FRAME_MS`, `BROWSERBASE_API_KEY`. Falls back to the `agent_actions` feed when no live caster is pushing.
---
@@ -3139,7 +3139,7 @@ Two layers resolve paths: **`vercel.json`** (`routes` array, 932 entries — pro
### Complete API Directory Index
-All **150+ directories** under `api/` plus many top-level single-file endpoints. `_`-prefixed dirs are shared internals; `[bracket].js` are dynamic routes. New since the last revision: `x402-facilitator/`, `launcher/`, `pay/`, `ops/`, `diorama.js`, `scene-capture.js`/`scene-upload.js`, `deployments.js`, `billboard.js`, `pipeline.js`, `three-signal.js`, `agent-screen-*.js`, `agent-task.js`, `agent-ask.js`, `agent-collab.js`, `agent-vanity-grind.js`, `agent-economy/volume`, expanded `agent/` (session, caster-config, launcher, market-maker, screen-push/-stream, watch-intent/-status/-wanted, anchor-script).
+All **150+ directories** under `api/` plus many top-level single-file endpoints. `_`-prefixed dirs are shared internals; `[bracket].js` are dynamic routes. New since the last revision: `x402-facilitator/`, `launcher/`, `pay/`, `ops/`, `diorama.js`, `scene-capture.js`/`scene-upload.js`, `deployments.js`, `billboard.js`, `pipeline.js`, `three-signal.js`, `agent-screen-*.js`, `agent-task.js`, `agent-ask.js`, `agent-collab.js`, `agent-vanity-grind.js`, `agent-economy/volume`, expanded `agent/` (session, caster-config, launcher, market-maker, watch-intent/-status/-wanted, anchor-script).
| Directory | Files | Purpose |
|---|---|---|
@@ -3153,7 +3153,7 @@ All **150+ directories** under `api/` plus many top-level single-file endpoints.
| `agent-3d/` | versions | 3D asset version listing. |
| `agent-economy/` | status, transact | Two-agent demo economy. |
| `agent-trade/` | demo (SSE), skill | Live A2A trade demo + tradeable skill. |
-| `agent/` | activity, dreams, reflect, send-sol, wallet, session, caster-config, launcher, market-maker, screen-push, screen-stream, watch-intent, watch-status, watch-wanted, anchor-script | Single-agent runtime + live-caster signaling + per-agent launcher/MM config. |
+| `agent/` | activity, dreams, reflect, send-sol, wallet, session, caster-config, launcher, market-maker, watch-intent, watch-status, watch-wanted, anchor-script | Single-agent runtime + live-caster signaling + per-agent launcher/MM config. |
| `agents/` | ~60+ incl `[id]/`, a2a-* (call/cart-verify/hire/mandate/paid), solana*/onchain/, register/, sas/, ens/, pumpfun/, endpoint-shopper-run, networth, copilot, recovery | Central agent surface (identity, A2A, trading/strategy/mirror, ERC-8004 register, Solana ops, portfolio). |
| `agi/` | state | AGI global state. |
| `agora/` | [action], act | Agora citizen actions. |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57a3a7dcd..e1a3ef01d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agora: sub-task hires are claimable, and stale bounties clear off the board** — 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. `[fix, improvement]`
- **Agora: verify a deliverable, then vouch for its maker in one click** — 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. (`/agora`) `[feature, improvement]`
- **Coin intelligence engine now backs off cleanly when the database is full** — 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. `[infra]`
+- **Every coin world now gets the full town experience** — 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 — market reads, fact checks, security scans, vanity addresses, 3D mesh forging, coin launches and more, each settled on-chain in USDC — 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. (`/play`) `[feature]`
+- **Live agent screens now reach the 3D world, and coin art loads everywhere** — The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall — previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail — and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone. (`/play`) `[fix, improvement]`
- **Oracle 3D graph is visible again** — 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. (`/oracle`) `[fix]`
- **Oracle coin pages now show full live market data** — 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. (`/oracle`) `[feature, improvement]`
- **Sign-in: fixed a hidden check that could silently block the Sign in button** — 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. (`/login`) `[fix]`
diff --git a/data/changelog.json b/data/changelog.json
index 53dbe2fe5..743379f84 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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": "Live agent screens now reach the 3D world, and coin art loads everywhere",
+ "summary": "The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall \u2014 previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail \u2014 and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-07-02",
"title": "Every coin world now gets the full town experience",
diff --git a/multiplayer/src/rooms/AgoraRoom.js b/multiplayer/src/rooms/AgoraRoom.js
new file mode 100644
index 000000000..8112a7454
Binary files /dev/null and b/multiplayer/src/rooms/AgoraRoom.js differ
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index cfeb03eed..c07cdb8a9 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -407,7 +407,8 @@ export class WalkRoom extends Room {
this.coinCreator = '';
// Co-op heist instances live on the room, not on a profile: a SHARED run a
// crew advances together. Keyed by mission id (one live instance per heist per
- // world). Each value: { missionId, members:Set<sessionId>, run, done:Set<zone> }.
+ // world). Each value: { missionId, members:Set<sessionId>, run } — the run
+ // carries its own per-stage seen-zone dedupe (quests.js applyEvent).
this.heists = new Map();
// Tag mini-game (R08): off-schema state. _tagImmunity tracks who is immune
// (sessionId → epoch ms immunity expires). _tagTime tracks cumulative time-as-it
@@ -1136,6 +1137,257 @@ export class WalkRoom extends Room {
if (id) this._questEvent(client, profile, { type: 'enter-zone', zone: id });
}
+ // --- Quests, jobs & heists (W05) -------------------------------------------
+ // The quest engine (quests.js) is pure data + state transitions; this section is
+ // the room's authority glue: it feeds REAL gameplay events into the engine, pays
+ // rewards through the same purse/XP idioms the activities use, and manages the
+ // co-op heist instances that live on the room (this.heists), not on a profile.
+
+ // Send the owning client its jobs board + active runs ({offers, active, day} —
+ // the shape community-net.js documents). Solo runs come straight from the
+ // engine's snapshot (which also rolls stale daily state over to today); a heist
+ // run is overlaid with the crew's SHARED instance so every member's tracker
+ // shows the same live progress, plus the current crew size.
+ _sendQuests(client) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ const snap = questSnapshot(profile.quests, utcDayKey());
+ for (let i = 0; i < snap.active.length; i++) {
+ const inst = this.heists.get(snap.active[i].id);
+ if (inst) {
+ snap.active[i] = { ...runView(inst.run, missionDef(inst.missionId)), crew: inst.members.size };
+ }
+ }
+ client.send('quests', snap);
+ }
+
+ // Accept a mission off the board. The engine owns the eligibility rules (already
+ // active, prereqs, daily/once repeats); a refusal is surfaced as a notice, never
+ // a silent no-op. Accepting a heist joins (or founds) this world's one shared
+ // instance — the crew advances a single run together and splits the pot at payout.
+ _handleQuestAccept(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'quest')) return;
+ const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
+ const mission = missionDef(id);
+ if (!mission) return;
+ const res = acceptMission(profile.quests, id, utcDayKey());
+ if (!res.ok) {
+ const text = res.reason === 'active' ? 'You already took that job.'
+ : res.reason === 'daily-done' ? 'That job is done for today — check back tomorrow.'
+ : res.reason === 'done' ? 'You’ve already completed that job.'
+ : 'That job isn’t available to you yet.';
+ client.send('notice', { kind: 'quest', text });
+ return;
+ }
+ if (isHeist(id)) {
+ let inst = this.heists.get(id);
+ if (!inst) {
+ // First accept founds the instance; the founder's fresh run IS the shared
+ // run every later member advances (it's never persisted — see quests.js).
+ inst = { missionId: id, members: new Set(), run: res.run };
+ this.heists.set(id, inst);
+ }
+ inst.members.add(client.sessionId);
+ // The crew grew — every member's tracker shows the new headcount.
+ this._sendQuestsToCrew(inst, client.sessionId);
+ }
+ this._persistEcon(client.sessionId);
+ client.send('notice', { kind: 'quest', text: `Accepted: ${mission.title}` });
+ this._sendQuests(client);
+ }
+
+ // Abandon an active mission. Solo progress is simply dropped (a daily can be
+ // re-accepted the same day); leaving a heist removes this member from the shared
+ // crew — the rest keep the run, and the instance dissolves with its last member.
+ _handleQuestAbandon(client, payload) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!this._actionOk(client.sessionId, 'quest')) return;
+ const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
+ if (!abandonMission(profile.quests, id).ok) return;
+ if (isHeist(id)) this._leaveHeistCrew(id, client.sessionId);
+ this._persistEcon(client.sessionId);
+ this._sendQuests(client);
+ }
+
+ // Act at the quest object the player is standing at (courier pickup/dropoff, a
+ // heist terminal, the vault door). The zone comes from the SERVER's authoritative
+ // position — the client's prompt is a hint, never the authority — and the event
+ // carries the zone's action so objectiveMatches can tell a pickup from a dropoff.
+ _handleQuestInteract(client) {
+ const player = this.state.players.get(client.sessionId);
+ const profile = this.econ.get(client.sessionId);
+ if (!player || !profile) return;
+ if (!this._actionOk(client.sessionId, 'questInteract')) return;
+ const zone = interactZoneInRange(player.x, player.z);
+ if (!zone) {
+ client.send('notice', { kind: 'quest', text: 'There’s nothing to use here.' });
+ return;
+ }
+ this._questEvent(client, profile, { type: 'interact', zone: zone.id, action: zone.action });
+ }
+
+ // Feed one real gameplay event (a catch, a zone entry, an interact) into every
+ // run it could advance. Called from the move path, so it stays cheap: a player
+ // has a handful of active runs at most, and live heist instances are bounded by
+ // the mission registry. Solo runs live on the profile; heists advance the crew's
+ // shared run — any member's action moves everyone, and the finale gates on
+ // assembly (the whole crew at the door, judged from server positions).
+ _questEvent(client, profile, event) {
+ const dayKey = utcDayKey();
+ let changed = false;
+ for (const [id, run] of Object.entries(profile.quests.active)) {
+ const mission = missionDef(id);
+ if (!mission || mission.kind === 'heist') continue; // heists advance via the shared instance below
+ const res = applyEvent(run, mission, event);
+ if (!res.matched) continue;
+ changed = true;
+ if (res.missionComplete) this._completeMission(client, profile, mission, dayKey);
+ }
+ for (const inst of this.heists.values()) {
+ if (!inst.members.has(client.sessionId)) continue;
+ const mission = missionDef(inst.missionId);
+ if (!mission) continue;
+ // The finale only lands with the whole crew assembled at its zone — checked
+ // BEFORE applying, so a lone cracker gets a hint instead of a silent miss.
+ const obj = mission.objectives[inst.run.stage];
+ if (obj?.finale && objectiveMatches(obj, event) && !this._heistFinaleReady(client, inst, mission, obj)) continue;
+ const res = applyEvent(inst.run, mission, event);
+ if (!res.matched) continue;
+ if (res.missionComplete) {
+ this._completeHeist(client, inst, mission, dayKey);
+ } else {
+ // Shared progress: the whole crew's trackers move together. The actor's
+ // own re-send rides on the tail below.
+ this._sendQuestsToCrew(inst, client.sessionId);
+ changed = true;
+ }
+ }
+ if (changed) {
+ this._persistEcon(client.sessionId);
+ this._sendQuests(client);
+ }
+ }
+
+ // Pay out a finished solo mission: record it in the lifetime + daily log, grant
+ // the purse + XP through the standard idioms, toast the client, and echo the
+ // milestone to the site ticker. The quests re-send rides on the caller's tail.
+ _completeMission(client, profile, mission, dayKey) {
+ recordCompletion(profile.quests, mission, dayKey);
+ const reward = missionReward(mission);
+ if (reward.gold > 0) profile.gold += reward.gold;
+ if (reward.xp) this._grantXp(client, profile, reward.xp.skill, reward.xp.amount);
+ this._sendInv(client, profile);
+ client.send('questComplete', { id: mission.id, title: mission.title, reward, kind: mission.kind, coop: false });
+ this._publishMissionComplete(client, mission, reward.gold, false);
+ }
+
+ // Pay out a finished heist to the LIVE crew: the pot splits evenly (remainder to
+ // the first member — splitPot loses no gold to rounding), each member's own
+ // completion log records it, and each gets their share + XP through their own
+ // client. The instance is consumed — a crew founds a fresh one to run it again.
+ _completeHeist(client, inst, mission, dayKey) {
+ const members = [...inst.members];
+ const reward = missionReward(mission);
+ const shares = splitPot(reward.gold, members.length);
+ members.forEach((sid, i) => {
+ const memberProfile = this.econ.get(sid);
+ if (!memberProfile) return;
+ recordCompletion(memberProfile.quests, mission, dayKey);
+ if (shares[i] > 0) memberProfile.gold += shares[i];
+ const memberClient = this.clients.find((c) => c.sessionId === sid);
+ if (memberClient) {
+ try {
+ if (reward.xp) this._grantXp(memberClient, memberProfile, reward.xp.skill, reward.xp.amount);
+ this._sendInv(memberClient, memberProfile);
+ memberClient.send('questComplete', {
+ id: mission.id, title: mission.title,
+ reward: { ...reward, gold: shares[i] },
+ kind: mission.kind, coop: true, crew: members.length,
+ });
+ this._sendQuests(memberClient);
+ } catch { /* best-effort */ }
+ }
+ this._persistEcon(sid);
+ });
+ // One ticker line for the whole crew (the total pot), not one per member.
+ this._publishMissionComplete(client, mission, reward.gold, true);
+ this.heists.delete(inst.missionId);
+ }
+
+ // The finale gate: a heist only finishes with a big-enough crew ALL standing at
+ // the finale zone — server positions, never client claims. A failed gate tells
+ // the actor why, so "nothing happened" is never the answer at the vault door.
+ _heistFinaleReady(client, inst, mission, obj) {
+ const need = Math.max(1, mission.party | 0 || 1);
+ if (inst.members.size < need) {
+ client.send('notice', { kind: 'quest', text: `This job needs a crew of ${need} — recruit before the finale.` });
+ return false;
+ }
+ for (const sid of inst.members) {
+ const p = this.state.players.get(sid);
+ const zone = p ? zoneAt(p.x, p.z) : null;
+ if (!zone || zone.id !== obj.zone) {
+ client.send('notice', { kind: 'quest', text: 'Your whole crew must be at the door for this.' });
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // Re-send the quest snapshot to every member of a heist crew (optionally skipping
+ // one — the actor, whose re-send rides on the caller). Best-effort per client so
+ // a mid-send disconnect can't break the loop for the rest of the crew.
+ _sendQuestsToCrew(inst, exceptSessionId = null) {
+ for (const sid of inst.members) {
+ if (sid === exceptSessionId) continue;
+ const c = this.clients.find((cc) => cc.sessionId === sid);
+ if (!c) continue;
+ try { this._sendQuests(c); } catch { /* best-effort */ }
+ }
+ }
+
+ // Drop one member from one heist crew; dissolves the instance with its last
+ // member, otherwise tells the remainder their headcount changed.
+ _leaveHeistCrew(missionId, sessionId) {
+ const inst = this.heists.get(missionId);
+ if (!inst || !inst.members.delete(sessionId)) return;
+ if (inst.members.size === 0) {
+ this.heists.delete(missionId);
+ return;
+ }
+ this._sendQuestsToCrew(inst);
+ }
+
+ // Drop a departing session from EVERY heist crew (onLeave) so no shared run holds
+ // a phantom member. Never throws — it runs inside the leave teardown.
+ _leaveHeists(sessionId) {
+ for (const id of [...this.heists.keys()]) {
+ try { this._leaveHeistCrew(id, sessionId); } catch { /* best-effort */ }
+ }
+ }
+
+ // "Someone pulled off <mission>" on the site-wide ticker (the reader documents
+ // mission-complete as { mission, gold, coop, coin }). Throttled per
+ // player+mission so a repeatable grind can't spam the global feed.
+ _publishMissionComplete(client, mission, gold, coop) {
+ const player = this.state.players.get(client.sessionId);
+ publishFeedEvent(
+ {
+ type: 'mission-complete',
+ ts: Date.now(),
+ actor: player?.name || 'A player',
+ mission: mission.title,
+ gold,
+ coop,
+ coin: this.state.coin || '',
+ },
+ `${player?.account || client.sessionId}:${mission.id}`,
+ );
+ }
+
_handleRename(client, payload) {
const player = this.state.players.get(client.sessionId);
if (!player) return;
diff --git a/public/changelog.json b/public/changelog.json
index 144b21a84..5ae785115 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-02T07:39:34.343Z",
+ "generated_at": "2026-07-02T08:28:20.331Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -80,6 +80,27 @@
"infra"
]
},
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "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 — market reads, fact checks, security scans, vanity addresses, 3D mesh forging, coin launches and more, each settled on-chain in USDC — 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.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "title": "Live agent screens now reach the 3D world, and coin art loads everywhere",
+ "summary": "The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall — previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail — and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone.",
+ "link": "/play",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-02",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 79a083c3c..55ee35853 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -62,6 +62,22 @@
<category>infra</category>
<description>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.</description>
</item>
+ <item>
+ <title>Every coin world now gets the full town experience</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-07-02:Every coin world now gets the full town experience</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>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 — market reads, fact checks, security scans, vanity addresses, 3D mesh forging, coin launches and more, each settled on-chain in USDC — 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.</description>
+ </item>
+ <item>
+ <title>Live agent screens now reach the 3D world, and coin art loads everywhere</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-07-02:Live agent screens now reach the 3D world, and coin art loads everywhere</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall — previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail — and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone.</description>
+ </item>
<item>
<title>Oracle 3D graph is visible again</title>
<link>https://three.ws/oracle</link>
diff --git a/public/features.json b/public/features.json
index ed6ae0e12..927d86150 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-02T07:39:34.321Z",
+ "generated_at": "2026-07-02T08:28:20.241Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agora/citizen-avatar.js b/src/agora/citizen-avatar.js
index 472f1cd35..af5c94143 100644
--- a/src/agora/citizen-avatar.js
+++ b/src/agora/citizen-avatar.js
@@ -76,8 +76,9 @@ function groundFeet(obj) {
// Build a crisp, high-DPI billboard label: bold name over a profession chip.
// Returns a Sprite that always faces the camera (sizeAttenuation on, so distant
// labels recede naturally). Drawn on a transparent rounded panel for contrast
-// against both bright sky and dark buildings.
-function buildLabelSprite(name, profession, accent) {
+// against both bright sky and dark buildings. Exported so the player mode's
+// remote humans (player-mode.js) wear the exact same nameplate as citizens.
+export function buildLabelSprite(name, profession, accent) {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const padX = 22, nameSize = 34, profSize = 22, gap = 8;
const font = (px, w) => `${w} ${px}px Inter, system-ui, sans-serif`;
diff --git a/src/agora/player-mode.css.js b/src/agora/player-mode.css.js
new file mode 100644
index 000000000..83cc00cab
--- /dev/null
+++ b/src/agora/player-mode.css.js
@@ -0,0 +1,238 @@
+// Styles for the playable Commons (player mode), shipped as a string and
+// injected once by player-mode.js — the humans.css.js pattern. Namespaced under
+// .agora-p-* so it can't collide with the scaffold (agora.css) or the other
+// Agora layers. Honours prefers-reduced-motion and gives every interactive
+// element hover/active/focus states.
+
+let _injected = false;
+export function injectPlayerCss() {
+ if (_injected || typeof document === 'undefined') return;
+ _injected = true;
+ const style = document.createElement('style');
+ style.id = 'agora-player-css';
+ style.textContent = PLAYER_CSS;
+ document.head.appendChild(style);
+}
+
+const PLAYER_CSS = `
+.agora-p-root {
+ --p-bg: rgba(12, 15, 22, 0.82);
+ --p-border: rgba(255, 255, 255, 0.12);
+ --p-text: #e8eef7;
+ --p-dim: #93a1b5;
+ --p-accent: #6ea8ff;
+ --p-ok: #36d399;
+ --p-err: #ff6b6b;
+ position: fixed;
+ inset: 0;
+ pointer-events: none;
+ z-index: 30;
+ font-family: Inter, system-ui, sans-serif;
+ color: var(--p-text);
+}
+
+/* ── Interaction prompt (press E / tap) ────────────────────────────────── */
+.agora-p-prompt {
+ position: absolute;
+ left: 50%;
+ bottom: 118px;
+ transform: translateX(-50%) translateY(6px);
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 16px;
+ background: var(--p-bg);
+ border: 1px solid var(--p-border);
+ border-radius: 14px;
+ backdrop-filter: blur(10px);
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);
+ opacity: 0;
+ transition: opacity 0.18s ease, transform 0.18s ease;
+ pointer-events: auto;
+ cursor: pointer;
+ border-left: 3px solid var(--p-accent);
+ max-width: min(86vw, 460px);
+}
+.agora-p-prompt[data-show] { opacity: 1; transform: translateX(-50%) translateY(0); }
+.agora-p-prompt:hover { border-color: var(--p-accent); }
+.agora-p-prompt:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }
+.agora-p-prompt kbd {
+ flex: none;
+ min-width: 26px;
+ text-align: center;
+ padding: 3px 7px;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.10);
+ border: 1px solid var(--p-border);
+ font: 700 12px/1.4 Inter, system-ui, sans-serif;
+}
+.agora-p-prompt-text { display: flex; flex-direction: column; min-width: 0; }
+.agora-p-prompt-title {
+ font-weight: 650; font-size: 14px;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.agora-p-prompt-sub {
+ font-size: 12px; color: var(--p-dim);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+
+/* ── Presence pill (online humans) ─────────────────────────────────────── */
+.agora-p-presence {
+ position: absolute;
+ top: 14px;
+ right: 14px;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 13px;
+ background: var(--p-bg);
+ border: 1px solid var(--p-border);
+ border-radius: 999px;
+ backdrop-filter: blur(10px);
+ font-size: 12.5px;
+ pointer-events: auto;
+ border: 1px solid var(--p-border);
+ cursor: default;
+}
+.agora-p-presence[data-clickable] { cursor: pointer; }
+.agora-p-presence[data-clickable]:hover { border-color: var(--p-accent); }
+.agora-p-presence:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }
+.agora-p-presence .dot {
+ width: 8px; height: 8px; border-radius: 50%;
+ background: var(--p-dim);
+ flex: none;
+}
+.agora-p-presence[data-state="online"] .dot { background: var(--p-ok); box-shadow: 0 0 8px var(--p-ok); }
+.agora-p-presence[data-state="connecting"] .dot { background: var(--p-accent); animation: agora-p-pulse 1.1s ease-in-out infinite; }
+.agora-p-presence[data-state="solo"] .dot,
+.agora-p-presence[data-state="offline"] .dot { background: var(--p-dim); }
+@keyframes agora-p-pulse { 50% { opacity: 0.35; } }
+
+/* ── Chat ──────────────────────────────────────────────────────────────── */
+.agora-p-chat {
+ position: absolute;
+ left: 14px;
+ bottom: 14px;
+ width: min(78vw, 340px);
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ pointer-events: auto;
+}
+.agora-p-chat-log {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: 132px;
+ overflow: hidden;
+ justify-content: flex-end;
+ mask-image: linear-gradient(to bottom, transparent, black 26%);
+}
+.agora-p-chat-line {
+ font-size: 12.5px;
+ line-height: 1.45;
+ padding: 4px 10px;
+ background: rgba(12, 15, 22, 0.66);
+ border-radius: 9px;
+ width: fit-content;
+ max-width: 100%;
+ overflow-wrap: anywhere;
+ animation: agora-p-rise 0.22s ease;
+}
+.agora-p-chat-line b { color: var(--p-accent); font-weight: 650; }
+@keyframes agora-p-rise { from { opacity: 0; transform: translateY(5px); } }
+.agora-p-chat-row { display: flex; gap: 6px; }
+.agora-p-chat-input {
+ flex: 1;
+ min-width: 0;
+ padding: 9px 12px;
+ background: var(--p-bg);
+ border: 1px solid var(--p-border);
+ border-radius: 11px;
+ color: var(--p-text);
+ font: 13px Inter, system-ui, sans-serif;
+ backdrop-filter: blur(10px);
+}
+.agora-p-chat-input::placeholder { color: var(--p-dim); }
+.agora-p-chat-input:focus { outline: none; border-color: var(--p-accent); }
+.agora-p-chat-send {
+ flex: none;
+ padding: 0 14px;
+ border-radius: 11px;
+ border: 1px solid var(--p-border);
+ background: var(--p-bg);
+ color: var(--p-text);
+ font: 600 13px Inter, system-ui, sans-serif;
+ cursor: pointer;
+ transition: border-color 0.15s ease, background 0.15s ease;
+}
+.agora-p-chat-send:hover { border-color: var(--p-accent); }
+.agora-p-chat-send:active { background: rgba(110, 168, 255, 0.18); }
+.agora-p-chat-send:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }
+
+/* Speech bubbles above remote players (DOM, projected per frame). */
+.agora-p-bubbles { position: absolute; inset: 0; overflow: hidden; }
+.agora-p-bubble {
+ position: absolute;
+ transform: translate(-50%, -100%);
+ max-width: 220px;
+ padding: 7px 11px;
+ background: rgba(245, 248, 255, 0.96);
+ color: #10151f;
+ font-size: 12.5px;
+ line-height: 1.4;
+ border-radius: 12px;
+ border-bottom-left-radius: 3px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
+ overflow-wrap: anywhere;
+ animation: agora-p-rise 0.2s ease;
+ will-change: transform;
+}
+
+/* ── Touch controls ────────────────────────────────────────────────────── */
+.agora-p-stick {
+ position: absolute;
+ left: 0;
+ bottom: 64px;
+ width: 46vw;
+ max-width: 240px;
+ height: 200px;
+ pointer-events: auto;
+ touch-action: none;
+ display: none;
+}
+.agora-p-actions {
+ position: absolute;
+ right: 12px;
+ bottom: 84px;
+ display: none;
+ flex-direction: column;
+ gap: 10px;
+ pointer-events: auto;
+}
+.agora-p-action-btn {
+ width: 58px; height: 58px;
+ border-radius: 50%;
+ border: 1px solid var(--p-border);
+ background: var(--p-bg);
+ color: var(--p-text);
+ font: 700 13px Inter, system-ui, sans-serif;
+ backdrop-filter: blur(8px);
+ cursor: pointer;
+ transition: transform 0.12s ease, border-color 0.12s ease;
+ touch-action: manipulation;
+}
+.agora-p-action-btn:active { transform: scale(0.92); border-color: var(--p-accent); }
+.agora-p-action-btn:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }
+@media (hover: none), (max-width: 640px) {
+ .agora-p-stick { display: block; }
+ .agora-p-actions { display: flex; }
+ .agora-p-chat { bottom: 76px; width: min(60vw, 260px); }
+ .agora-p-prompt { bottom: 170px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .agora-p-prompt, .agora-p-chat-line, .agora-p-bubble { animation: none; transition: none; }
+ .agora-p-presence[data-state="connecting"] .dot { animation: none; }
+}
+`;
diff --git a/src/agora/player-mode.js b/src/agora/player-mode.js
new file mode 100644
index 000000000..6ab6ddc15
--- /dev/null
+++ b/src/agora/player-mode.js
@@ -0,0 +1,569 @@
+// /agora player mode — "Enter the Commons". The embodied, GTA-style layer over
+// the spectator scaffold: your real avatar walks Times Square among the citizen
+// NPCs (who keep living their real on-chain economy — claiming, working,
+// proving, earning), other humans appear live over the shared multiplayer
+// server, and walking up to any citizen offers a proximity interaction that
+// opens their living passport (inspect → hire → vouch, via the existing
+// me-hud/passport stack).
+//
+// Loaded LAZILY by agora-world.js the moment the visitor enters play mode, so
+// the watchable Commons never pays for colyseus.js or nipplejs up front.
+//
+// Reuses, never reinvents:
+// • avatar loading + clips → src/game/avatar-rig.js (same rig as /city, /play)
+// • multiplayer client → src/walk-net.js (room 'agora_world', graceful solo)
+// • nameplates → buildLabelSprite from citizen-avatar.js
+// • movement/collision math → player-logic.js (pure, unit-tested)
+// • interaction surface → the existing passport/me-hud event bus
+//
+// The room is a dedicated 'agora_world' (multiplayer/src/rooms/AgoraRoom.js) —
+// NOT a walk_world coin shard: the Commons is city-scale (±680 m) and WalkRoom's
+// anti-cheat clamps assume a 60 m plaza. If the server is unreachable (or the
+// room isn't deployed yet) the square stays fully playable solo — the NPCs'
+// economy never depended on the presence socket.
+
+import * as THREE from 'three';
+import {
+ loadManifest, resolveAvatarUrl, buildAvatar, newAnim,
+ CLIP_IDLE, CLIP_WALK,
+} from '../game/avatar-rig.js';
+import { WalkNet } from '../walk-net.js';
+import { buildLabelSprite } from './citizen-avatar.js';
+import { CITY_HALF } from '../city/city-map.js';
+import {
+ JUMP_VEL, GRAVITY,
+ motionFor, stepMovement, easeYaw, resolveBuildingCollision,
+ nearestInteractable, chooseAvatarSource, guestName,
+} from './player-logic.js';
+import { injectPlayerCss } from './player-mode.css.js';
+import { log } from '../shared/log.js';
+
+const BOUNDS = CITY_HALF - 20; // matches the spectator PAN_BOUNDS — one world edge
+const SPAWN = { x: 3.5, z: -2.5 }; // beside the job board, facing the square
+const REMOTE_LERP = 0.22; // exponential-lerp factor toward 15 Hz snapshots
+const PROXIMITY_HZ = 5; // interactable scan rate
+const BUBBLE_MS = 5200; // how long a chat bubble hangs over a head
+const CHAT_LOG_MAX = 6;
+
+// ── Local player ─────────────────────────────────────────────────────────────
+
+class AgoraPlayer {
+ constructor(scene) {
+ this._scene = scene;
+ this.rig = new THREE.Group();
+ scene.add(this.rig);
+ this.velocity = new THREE.Vector3();
+ this.onGround = true;
+ this.motion = 'idle';
+ this.height = 1.7;
+ this._anim = null;
+ this._targetYaw = 0;
+ this._jumpQueued = false;
+ // Analogue input the keyboard and the touch stick both write into.
+ this.stick = { forward: 0, strafe: 0, running: false };
+ this._keys = new Set();
+ }
+
+ async load(avatarInput) {
+ await loadManifest();
+ const url = await resolveAvatarUrl(avatarInput || '');
+ this._anim = newAnim();
+ const { height, fallback } = await buildAvatar(this.rig, url, this._anim);
+ this.height = height;
+ this.rig.position.set(SPAWN.x, 0, SPAWN.z);
+ return { url, fallback };
+ }
+
+ queueJump() { this._jumpQueued = true; }
+
+ // Merge keyboard state into the analogue stick each frame (keyboard is ±1).
+ _input() {
+ const k = this._keys;
+ let forward = this.stick.forward;
+ let strafe = this.stick.strafe;
+ if (k.has('w') || k.has('arrowup')) forward = 1;
+ if (k.has('s') || k.has('arrowdown')) forward = -1;
+ if (k.has('a') || k.has('arrowleft')) strafe = -1;
+ if (k.has('d') || k.has('arrowright')) strafe = 1;
+ const running = this.stick.running || k.has('shift');
+ return { forward, strafe, running };
+ }
+
+ update(dt, buildingBoxes, cameraYaw) {
+ const input = this._input();
+ const step = stepMovement({
+ input, cameraYaw, running: input.running,
+ vx: this.velocity.x, vz: this.velocity.z, yaw: this._targetYaw, dt,
+ });
+ this.velocity.x = step.vx;
+ this.velocity.z = step.vz;
+ if (step.moving) this._targetYaw = step.yaw;
+
+ if (this._jumpQueued && this.onGround) {
+ this.velocity.y = JUMP_VEL;
+ this.onGround = false;
+ }
+ this._jumpQueued = false;
+ if (!this.onGround) this.velocity.y += GRAVITY * dt;
+
+ const p = this.rig.position;
+ let nx = p.x + this.velocity.x * dt;
+ let ny = p.y + this.velocity.y * dt;
+ const nz0 = p.z + this.velocity.z * dt;
+ const resolved = resolveBuildingCollision(nx, ny, nz0, buildingBoxes);
+ nx = resolved.x;
+ let nz = resolved.z;
+
+ if (ny <= 0) { ny = 0; this.velocity.y = 0; this.onGround = true; }
+ else this.onGround = false;
+
+ nx = Math.max(-BOUNDS, Math.min(BOUNDS, nx));
+ nz = Math.max(-BOUNDS, Math.min(BOUNDS, nz));
+ p.set(nx, ny, nz);
+
+ this.rig.rotation.y = easeYaw(this.rig.rotation.y, this._targetYaw, dt);
+
+ const hSpeed = Math.hypot(this.velocity.x, this.velocity.z);
+ const next = motionFor(hSpeed, input.running);
+ if (next !== this.motion) {
+ this.motion = next;
+ // The clip set is idle + walk; running is the walk clip driven faster.
+ const clip = next === 'idle' ? CLIP_IDLE : CLIP_WALK;
+ this._anim?.crossfadeTo(clip, 0.2).catch(() => {});
+ }
+ this._anim?.update(dt);
+ }
+
+ get position() { return this.rig.position; }
+
+ dispose() {
+ this._scene.remove(this.rig);
+ disposeObject(this.rig);
+ }
+}
+
+// ── Remote players (the other humans in the square) ─────────────────────────
+
+class RemotePlayers {
+ constructor(scene, bubblesEl) {
+ this._scene = scene;
+ this._bubbles = bubblesEl;
+ this._byId = new Map(); // sessionId → entry
+ }
+
+ get count() { return this._byId.size; }
+
+ upsert(player, sessionId) {
+ let entry = this._byId.get(sessionId);
+ if (entry && entry.avatarUrl !== (player.avatar || '')) {
+ // Live avatar swap: rebuild rather than patch a half-loaded rig.
+ this.remove(sessionId);
+ entry = null;
+ }
+ if (!entry) {
+ entry = this._create(player, sessionId);
+ this._byId.set(sessionId, entry);
+ }
+ entry.target.x = player.x;
+ entry.target.y = player.y;
+ entry.target.z = player.z;
+ entry.target.yaw = player.yaw;
+ const motion = player.motion === 'idle' ? 'idle' : 'walk';
+ if (motion !== entry.motion && entry.anim) {
+ entry.motion = motion;
+ entry.anim.crossfadeTo(motion === 'idle' ? CLIP_IDLE : CLIP_WALK, 0.2).catch(() => {});
+ } else {
+ entry.motion = motion;
+ }
+ return entry;
+ }
+
+ _create(player, sessionId) {
+ const group = new THREE.Group();
+ group.position.set(player.x, player.y, player.z);
+ this._scene.add(group);
+ const entry = {
+ sessionId,
+ group,
+ anim: null,
+ avatarUrl: player.avatar || '',
+ name: player.name || 'visitor',
+ target: { x: player.x, y: player.y, z: player.z, yaw: player.yaw },
+ motion: 'idle',
+ height: 1.7,
+ bubbleEl: null,
+ bubbleUntil: 0,
+ gone: false,
+ };
+ // Async body load; the entry is live (and lerping) before the GLB lands.
+ (async () => {
+ const anim = newAnim();
+ const { height } = await buildAvatar(group, player.avatar || '', anim);
+ if (entry.gone) { disposeObject(group); return; }
+ entry.anim = anim;
+ entry.height = height;
+ const accent = `#${(Number(player.color) >>> 0).toString(16).padStart(6, '0').slice(-6)}`;
+ const label = buildLabelSprite(entry.name, 'visitor', accent);
+ label.position.y = height + 0.42;
+ group.add(label);
+ })().catch((err) => log.warn('[agora-play] remote avatar failed', err?.message));
+ return entry;
+ }
+
+ remove(sessionId) {
+ const entry = this._byId.get(sessionId);
+ if (!entry) return;
+ entry.gone = true;
+ this._byId.delete(sessionId);
+ this._scene.remove(entry.group);
+ disposeObject(entry.group);
+ entry.bubbleEl?.remove();
+ }
+
+ say(sessionId, text) {
+ const entry = this._byId.get(sessionId);
+ if (!entry) return;
+ if (!entry.bubbleEl) {
+ entry.bubbleEl = document.createElement('div');
+ entry.bubbleEl.className = 'agora-p-bubble';
+ this._bubbles.appendChild(entry.bubbleEl);
+ }
+ entry.bubbleEl.textContent = String(text || '').slice(0, 200);
+ entry.bubbleUntil = performance.now() + BUBBLE_MS;
+ }
+
+ tick(dt, camera, viewW, viewH) {
+ const k = 1 - Math.pow(1 - REMOTE_LERP, dt * 60);
+ for (const entry of this._byId.values()) {
+ const p = entry.group.position;
+ p.x += (entry.target.x - p.x) * k;
+ p.y += (entry.target.y - p.y) * k;
+ p.z += (entry.target.z - p.z) * k;
+ entry.group.rotation.y = easeYaw(entry.group.rotation.y, entry.target.yaw, dt, 10);
+ entry.anim?.update(dt);
+
+ // Project the speech bubble (screen-space DOM) over the head.
+ if (entry.bubbleEl) {
+ if (performance.now() > entry.bubbleUntil) {
+ entry.bubbleEl.remove();
+ entry.bubbleEl = null;
+ } else {
+ _v.set(p.x, p.y + entry.height + 0.55, p.z).project(camera);
+ if (_v.z > 1) {
+ entry.bubbleEl.style.display = 'none';
+ } else {
+ entry.bubbleEl.style.display = '';
+ entry.bubbleEl.style.left = `${(_v.x * 0.5 + 0.5) * viewW}px`;
+ entry.bubbleEl.style.top = `${(-_v.y * 0.5 + 0.5) * viewH}px`;
+ }
+ }
+ }
+ }
+ }
+
+ dispose() {
+ for (const id of [...this._byId.keys()]) this.remove(id);
+ }
+}
+
+const _v = new THREE.Vector3();
+
+function disposeObject(root) {
+ root.traverse((n) => {
+ if (n.isMesh || n.isSkinnedMesh) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) {
+ if (!m) continue;
+ for (const key of Object.keys(m)) {
+ const val = m[key];
+ if (val && val.isTexture) val.dispose();
+ }
+ m.dispose?.();
+ }
+ }
+ if (n.isSprite) {
+ n.material?.map?.dispose?.();
+ n.material?.dispose?.();
+ }
+ });
+}
+
+// ── Mount ────────────────────────────────────────────────────────────────────
+
+/**
+ * Mount the playable layer.
+ *
+ * @param {object} ctx
+ * @param {THREE.Scene} ctx.scene
+ * @param {THREE.Camera} ctx.camera
+ * @param {object} ctx.population CitizenPopulation (the NPC crowd)
+ * @param {Array} ctx.buildingBoxes AABBs from buildCity
+ * @param {() => number} ctx.getCameraYaw cityCamera.yaw supplier
+ * @param {(id) => void} ctx.openPassport opens a citizen's passport panel
+ * @returns {Promise<{update(dt):void, playerPosition:THREE.Vector3, playerHeight:number, dispose():void}>}
+ */
+export async function mountPlayerMode(ctx) {
+ injectPlayerCss();
+ const { scene, camera, population, buildingBoxes, getCameraYaw, openPassport } = ctx;
+
+ // ── HUD scaffold (all states designed) ─────────────────────────────────────
+ const root = el('div', 'agora-p-root');
+ const bubbles = el('div', 'agora-p-bubbles');
+ const prompt = el('button', 'agora-p-prompt');
+ prompt.type = 'button';
+ prompt.innerHTML = `<kbd>E</kbd><span class="agora-p-prompt-text"><span class="agora-p-prompt-title"></span><span class="agora-p-prompt-sub"></span></span>`;
+ const presence = el('button', 'agora-p-presence');
+ presence.type = 'button';
+ presence.dataset.state = 'connecting';
+ presence.innerHTML = `<span class="dot"></span><span class="agora-p-presence-text">connecting…</span>`;
+ const chat = el('div', 'agora-p-chat');
+ const chatLog = el('div', 'agora-p-chat-log');
+ const chatRow = el('div', 'agora-p-chat-row');
+ const chatInput = el('input', 'agora-p-chat-input');
+ chatInput.placeholder = 'Say something to the square…';
+ chatInput.maxLength = 200;
+ chatInput.setAttribute('aria-label', 'Chat with other visitors');
+ const chatSend = el('button', 'agora-p-chat-send');
+ chatSend.type = 'button';
+ chatSend.textContent = 'Send';
+ chatRow.append(chatInput, chatSend);
+ chat.append(chatLog, chatRow);
+ const stickZone = el('div', 'agora-p-stick');
+ const actions = el('div', 'agora-p-actions');
+ const jumpBtn = el('button', 'agora-p-action-btn');
+ jumpBtn.type = 'button';
+ jumpBtn.textContent = 'JUMP';
+ jumpBtn.setAttribute('aria-label', 'Jump');
+ const interactBtn = el('button', 'agora-p-action-btn');
+ interactBtn.type = 'button';
+ interactBtn.textContent = 'E';
+ interactBtn.setAttribute('aria-label', 'Interact with the nearest citizen');
+ actions.append(interactBtn, jumpBtn);
+ root.append(bubbles, prompt, presence, chat, stickZone, actions);
+ document.body.appendChild(root);
+
+ // ── Identity + avatar ──────────────────────────────────────────────────────
+ const params = new URLSearchParams(location.search);
+ const getStored = (k) => { try { return localStorage.getItem(k); } catch { return null; } };
+ const setStored = (k, v) => { try { localStorage.setItem(k, v); } catch { /* private mode */ } };
+ const avatarChoice = chooseAvatarSource(params, getStored);
+ if (avatarChoice.source.startsWith('param')) setStored('agora:avatar', avatarChoice.value);
+ const name = guestName(getStored, Math.random());
+ setStored('agora:name', name);
+
+ const player = new AgoraPlayer(scene);
+ const { url: avatarUrl } = await player.load(avatarChoice.value);
+
+ // ── Multiplayer presence (dedicated Commons room; graceful solo) ───────────
+ const remotes = new RemotePlayers(scene, bubbles);
+ const net = new WalkNet({ name, avatar: avatarUrl, room: 'agora_world' });
+ const presenceText = presence.querySelector('.agora-p-presence-text');
+ function renderPresence() {
+ const state = net.status === 'online' ? 'online'
+ : net.status === 'connecting' ? 'connecting'
+ : net.status === 'unavailable' ? 'solo'
+ : 'offline';
+ presence.dataset.state = state;
+ if (state === 'online') {
+ const n = remotes.count + 1;
+ presenceText.textContent = `${n} ${n === 1 ? 'human' : 'humans'} in the square`;
+ presence.removeAttribute('data-clickable');
+ presence.title = '';
+ } else if (state === 'connecting') {
+ presenceText.textContent = 'connecting…';
+ presence.removeAttribute('data-clickable');
+ } else if (state === 'solo') {
+ presenceText.textContent = 'solo square — citizens still at work';
+ presence.removeAttribute('data-clickable');
+ presence.title = 'No multiplayer server configured for this environment';
+ } else {
+ presenceText.textContent = 'solo — tap to reconnect';
+ presence.setAttribute('data-clickable', '');
+ presence.title = 'Reconnect to the shared square';
+ }
+ }
+ const offStatus = net.on('status', renderPresence);
+ const offAdd = net.on('add', (p, sessionId) => {
+ if (sessionId === net.mySessionId) return;
+ remotes.upsert(p, sessionId);
+ renderPresence();
+ });
+ const offChange = net.on('change', (p, sessionId) => {
+ if (sessionId === net.mySessionId) return;
+ remotes.upsert(p, sessionId);
+ });
+ const offRemove = net.on('remove', (sessionId) => {
+ remotes.remove(sessionId);
+ renderPresence();
+ });
+ const offChat = net.on('chat', (msg) => {
+ if (!msg || !msg.text) return;
+ appendChatLine(msg.name || 'visitor', msg.text);
+ if (msg.id && msg.id !== net.mySessionId) remotes.say(msg.id, msg.text);
+ });
+ presence.addEventListener('click', () => {
+ if (presence.hasAttribute('data-clickable')) net.retry();
+ });
+ net.connect();
+
+ function appendChatLine(who, text) {
+ const line = el('div', 'agora-p-chat-line');
+ const b = document.createElement('b');
+ b.textContent = who;
+ line.append(b, document.createTextNode(` ${String(text).slice(0, 200)}`));
+ chatLog.appendChild(line);
+ while (chatLog.children.length > CHAT_LOG_MAX) chatLog.firstChild.remove();
+ }
+ function sendChat() {
+ const text = chatInput.value.trim();
+ if (!text) return;
+ if (net.status === 'online') {
+ net.sendChat(text);
+ } else {
+ // Honest solo echo — your words still appear, marked as unheard.
+ appendChatLine(`${name} (solo)`, text);
+ }
+ chatInput.value = '';
+ }
+ chatSend.addEventListener('click', sendChat);
+ chatInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); sendChat(); }
+ e.stopPropagation(); // typing must never move the avatar
+ });
+
+ // ── Input (keyboard) ───────────────────────────────────────────────────────
+ const TRACKED = new Set(['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'shift']);
+ function typingSomewhere() {
+ const ae = document.activeElement;
+ return !!(ae && (/^(INPUT|TEXTAREA|SELECT)$/.test(ae.tagName) || ae.isContentEditable
+ || (ae.closest && ae.closest('.agora-passport, .agora-panel, .agora-h-root, [role="dialog"]'))));
+ }
+ const onKeyDown = (e) => {
+ if (typingSomewhere()) return;
+ const k = e.key.toLowerCase();
+ if (k === ' ') { e.preventDefault(); player.queueJump(); return; }
+ if (k === 'e') { interact(); return; }
+ if (!TRACKED.has(k)) return;
+ if (k.startsWith('arrow')) e.preventDefault();
+ player._keys.add(k);
+ };
+ const onKeyUp = (e) => player._keys.delete(e.key.toLowerCase());
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('keyup', onKeyUp);
+ jumpBtn.addEventListener('click', () => player.queueJump());
+ interactBtn.addEventListener('click', () => interact());
+ prompt.addEventListener('click', () => interact());
+
+ // ── Touch stick (lazy nipplejs — only where touch is the medium) ──────────
+ let stickManager = null;
+ if (window.matchMedia?.('(hover: none), (max-width: 640px)').matches) {
+ import('nipplejs').then(({ default: nipplejs }) => {
+ stickManager = nipplejs.create({
+ zone: stickZone,
+ mode: 'dynamic',
+ color: '#6ea8ff',
+ size: 110,
+ });
+ stickManager.on('move', (_e, data) => {
+ const a = data.angle?.radian ?? 0;
+ const f = Math.min(1, (data.distance || 0) / 55);
+ player.stick.forward = Math.sin(a) * f;
+ player.stick.strafe = Math.cos(a) * f;
+ player.stick.running = f > 0.92; // full extension sprints
+ });
+ stickManager.on('end', () => {
+ player.stick.forward = 0;
+ player.stick.strafe = 0;
+ player.stick.running = false;
+ });
+ }).catch((err) => log.warn('[agora-play] touch stick unavailable', err?.message));
+ }
+
+ // ── Proximity interaction (the NPC handshake) ──────────────────────────────
+ let promptTarget = null;
+ let proximityAccum = 0;
+ function scanProximity() {
+ const p = player.position;
+ const candidates = [];
+ for (const inst of population.instances || []) {
+ const c = inst?.citizen;
+ if (!c) continue;
+ const pos = population.worldPosition(c.id);
+ if (!pos) continue;
+ candidates.push({
+ id: c.id,
+ kind: 'citizen',
+ x: pos.x,
+ z: pos.z,
+ name: c.displayName || 'Citizen',
+ profession: c.professions?.[0]?.label || c.profession || 'Citizen',
+ busy: !!inst.busy, // live economy state — set when a real claim walks them to work
+ });
+ }
+ const hit = nearestInteractable(p.x, p.z, candidates);
+ if (hit?.id !== promptTarget?.id) {
+ if (promptTarget) population.highlight(null);
+ promptTarget = hit;
+ if (hit) {
+ population.highlight(hit.id);
+ prompt.querySelector('.agora-p-prompt-title').textContent = `Meet ${hit.name}`;
+ prompt.querySelector('.agora-p-prompt-sub').textContent = hit.busy
+ ? `${hit.profession} — busy on a job right now. See their live work.`
+ : `${hit.profession} — open their living passport`;
+ prompt.setAttribute('data-show', '');
+ prompt.setAttribute('aria-label', `Interact with ${hit.name}, ${hit.profession}`);
+ } else {
+ prompt.removeAttribute('data-show');
+ }
+ }
+ }
+ function interact() {
+ if (!promptTarget) return;
+ openPassport(promptTarget.id);
+ }
+
+ // ── Per-frame update (driven by agora-world's single rAF) ─────────────────
+ function update(dt) {
+ player.update(dt, buildingBoxes, getCameraYaw());
+ net.sendState({
+ x: player.position.x,
+ y: player.position.y,
+ z: player.position.z,
+ yaw: player.rig.rotation.y,
+ motion: player.motion,
+ });
+ remotes.tick(dt, camera, window.innerWidth, window.innerHeight);
+ proximityAccum += dt;
+ if (proximityAccum >= 1 / PROXIMITY_HZ) {
+ proximityAccum = 0;
+ scanProximity();
+ }
+ }
+
+ function dispose() {
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('keyup', onKeyUp);
+ offStatus(); offAdd(); offChange(); offRemove(); offChat();
+ try { stickManager?.destroy(); } catch { /* already gone */ }
+ try { net.destroy(); } catch { /* already gone */ }
+ remotes.dispose();
+ if (promptTarget) population.highlight(null);
+ player.dispose();
+ root.remove();
+ }
+
+ renderPresence();
+ return {
+ update,
+ get playerPosition() { return player.position; },
+ get playerHeight() { return player.height; },
+ dispose,
+ };
+}
+
+function el(tag, className) {
+ const node = document.createElement(tag);
+ node.className = className;
+ return node;
+}
diff --git a/src/walk-net.js b/src/walk-net.js
index 6d007a05d..8ba24e4a0 100644
--- a/src/walk-net.js
+++ b/src/walk-net.js
@@ -69,6 +69,9 @@ export class WalkNet {
* @param {object} opts
* @param {string} [opts.name] Display name (1–24 chars after server clean)
* @param {string} [opts.url] Override server URL (otherwise resolved from meta)
+ * @param {string} [opts.room] Room type to join (default 'walk_world'). The Agora
+ * Commons joins its dedicated 'agora_world' room through the same client —
+ * identical status model, throttle, and reconnect semantics.
* @param {string} [opts.avatar] Loadable GLB URL for this player's avatar / 3D agent
* @param {string} [opts.agent] three.ws agent id this player embodies (cross-links)
* @param {string} [opts.coin] Coin mint — joins that coin's community world ('' = mainland)
@@ -79,6 +82,7 @@ export class WalkNet {
constructor(opts = {}) {
this.name = opts.name || 'guest';
this.url = opts.url || defaultServerUrl();
+ this.roomName = opts.room || ROOM_NAME;
this.avatar = opts.avatar || '';
this.agent = opts.agent || '';
// Coin community this client is entering. `coin` (the mint) doubles as the
@@ -176,7 +180,7 @@ export class WalkNet {
// holding the WS upgrade) would otherwise strand us in 'connecting'
// forever — joinOrCreate has no timeout. On timeout this throws and the
// catch below schedules a reconnect.
- const room = await joinRoomWithTimeout(this.client, ROOM_NAME, {
+ const room = await joinRoomWithTimeout(this.client, this.roomName, {
name: this.name,
avatar: this.avatar,
agent: this.agent,