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: add Omniology Arena — multiplayer venue, contest screens, and MCP server

nirholasc10147aedcda
diff --git a/.gitignore b/.gitignore
index 64ce92c5e..e7ad78fac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -282,3 +282,4 @@ pages/ibm/hello.html
three-ws-prod-log-export-2026-06-24T13-33-58.json
three-ws-prod-log-export-2026-06-25T07-22-45.json
three-ws-prod-log-export-2026-06-25T19-38-22.json
+docs/omniology-arena/QUESTIONS-FOR-OMNIOLOGY.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96d8cbd85..dfcf603e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-25
- **Production error sweep: tier page, image understanding, and on-chain indexing** — We pulled a full day of production logs and fixed what was actually failing. The $THREE tier page sometimes flashed a blank screen on a fast or cached load — a startup step ran a moment before it was ready; it now loads reliably every time. Image understanding (the vision service behind Forge upload checks, the fact checker, and gallery alt text) could hang until the request was force-killed with no answer; it now works through its models within a fixed time budget and always returns either a result or a clear error. Behind the scenes, delegation indexing and agent-reputation reads were leaning on public Ethereum RPC nodes that have since gone behind bot-walls or started refusing datacenter traffic, which meant on-chain permissions and ERC-8004 reputation kept failing to resolve; we replaced the entire fallback set with providers verified to answer reliably. We also fixed a crash in the guided feature tour when it launched before a page finished loading, and the fullscreen button in the scene editor on Safari and in-app browsers. No action needed. `[fix, infra]`
+- **Pump dashboard now loads inside X/Twitter's in-app browser** — Opening the Pump trading desk from a link tapped inside X/Twitter (or a similar embedded mobile browser) showed a blank page. Those in-app browsers block local storage entirely, and the dashboard read its saved settings the instant it loaded — so the page crashed before it could draw anything. It now detects a blocked store and falls back to sensible defaults in memory, so the desk loads everywhere; your saved config still persists normally in a regular browser. No action needed. (`/pump-dashboard`) `[fix]`
+- **Stability sweep: live page, dashboards, and the galaxy feed never hard-fail** — A second pass on the day's production logs, this time on resilience. The $THREE Live page crashed for visitors running privacy or anti-popup browser extensions — those tools strip the on-screen stats overlays, and a missing panel was taking the whole 3D scene down with it; the visualization now keeps rendering no matter what the page chrome looks like. Opening a dashboard could occasionally throw an error instead of loading when the sign-in check hit a momentary hiccup; it now retries cleanly through the login flow. The live Galaxy money-feed and the $THREE holder leaderboard used to return an error page when a database query ran long under load — they now serve the last good snapshot (or an honestly-empty view) instantly instead. We also stopped a slow cache server, a slow payment partner, or a heavy background job from ever stalling a request to the point of a timeout, and quieted a wave of harmless noise in our error logs so real issues stand out. No action needed. `[fix, improvement]`
## 2026-06-24
diff --git a/data/changelog.json b/data/changelog.json
index 1c30a423d..be6fb7e3d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-25",
+ "title": "Pump dashboard now loads inside X/Twitter's in-app browser",
+ "summary": "Opening the Pump trading desk from a link tapped inside X/Twitter (or a similar embedded mobile browser) showed a blank page. Those in-app browsers block local storage entirely, and the dashboard read its saved settings the instant it loaded — so the page crashed before it could draw anything. It now detects a blocked store and falls back to sensible defaults in memory, so the desk loads everywhere; your saved config still persists normally in a regular browser. No action needed.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/pump-dashboard"
+ },
{
"date": "2026-06-25",
"title": "Stability sweep: live page, dashboards, and the galaxy feed never hard-fail",
diff --git a/docs/omniology-arena/01-scaffold-and-multiplayer.md b/docs/omniology-arena/01-scaffold-and-multiplayer.md
new file mode 100644
index 000000000..d9a66b01e
--- /dev/null
+++ b/docs/omniology-arena/01-scaffold-and-multiplayer.md
@@ -0,0 +1,39 @@
+# Prompt 01 — Arena scaffold + multiplayer presence
+
+You are a senior engineer on three.ws. Build the foundational surface for the
+**Omniology Arena**: a new standalone 3D world route where a player spawns into a
+lit space, moves with keyboard/touch, and sees other real players present via the
+existing Colyseus multiplayer server — with **zero changes to the multiplayer
+server**. This is the skeleton that prompts 02–06 plug into.
+
+## Read first (required)
+- `docs/omniology-arena/README.md` and `docs/omniology-arena/CONTRACTS.md`
+- `CLAUDE.md` (operating rules — non-negotiable: no mocks, no stubs, finish what you write, design every state)
+- `pages/play.html` — the reference page (canvas `#kx-canvas`, loading `#kx-loading`, `<meta name="game-server">` ~line 24)
+- `src/game/coincommunities.js` — reference world bootstrap. Study: `enter()`, the render loop `_loop()` (~2706–2745), local movement `_stepLocal()` (~2755–2800), camera `_updateCamera()` (~2848–2860), and `RemotePlayer` (~126–284). Constants: `MOVE_SPEED 4.2`, `RUN_SPEED 8.0`, `GRAVITY 15`, `JUMP_VELOCITY 5.5`, `REMOTE_LERP 0.18`, joystick deadzone `0.12`.
+- `src/game/community-net.js` — the Colyseus client wrapper. Note `ROOM_NAME = 'walk_world'`, the `joinOrCreate('walk_world', { token, tier, name, avatar, … })` call, and the server-URL resolution order (`window.GAME_SERVER_URL` → localhost → `<meta name="game-server">` → `VITE_GAME_SERVER_URL`).
+- `src/game/avatar-rig.js` — `buildAvatar(rig, url, anim)`, `resolveAvatarUrl()`, the animation manifest at `/animations/manifest.json`.
+- `multiplayer/src/index.js` — confirm `gameServer.define('walk_world', WalkRoom).filterBy(['coin','tier'])`, and read `WalkRoom.onAuth` to confirm an **open** join (no holder/play gate) works when `tier:''` and `PLAY_GATE_MINT` is unset. Report what you find — if a global gate would block open access, surface it (do not work around it silently).
+
+## Verify before you build
+- Check whether `pages/arena.html`, `pages/play/arena.html`, and `src/play-arena.js` already exist and what they are (`vite.config.js` inputs ~468–479, `vercel.json` routes ~878–892). **Do not collide.** Build the new surface at route **`/arena/omniology`** (page `pages/arena/omniology.html`, vite input key `arena-omniology`, vercel route `/arena/omniology/?` → that html). If an existing arena page is clearly unused scaffolding, note it but do not delete without cause.
+
+## Build
+1. **Page** `pages/arena/omniology.html`: copy the structure of `pages/play.html` — a full-screen `<canvas>`, a designed loading overlay, and the `<meta name="game-server" content="…">` tag (same value as play.html). Add `<meta name="omniology-base" content="">` (empty for now; CONTRACTS §3). Module script → `/src/game/arena/omniology.js`.
+2. **Wiring**: add the vite input (`vite.config.js`) and the vercel route (`vercel.json`). Match the surrounding formatting exactly.
+3. **Bootstrap** `src/game/arena/arena.js`: an `OmniologyArena` class that owns `scene`, `renderer` (shadows on, `PCFShadowMap`), `camera`, a render loop, and a `registerUpdatable(obj)` registry whose members get `update(dt)` each frame (per CONTRACTS §2.4). Provide an `anchors` field initialized to sensible defaults now (a spawn point, a few forward screen positions, a desk position) — prompt 02 will overwrite these from the venue GLB. Expose `dispose()` with full teardown (geometry/material/texture disposal, listener removal) modeled on `coincommunities.js leave()`.
+4. **Entry module** `src/game/arena/omniology.js`: read player name/avatar (reuse whatever `/play` uses to resolve the local avatar and the boot-avatar preview), instantiate `OmniologyArena`, and connect multiplayer via `CommunityNet` with `coin: { mint: 'arena:omniology', name: 'Omniology Arena', symbol: 'OMNI', image: '' }`, `tier: ''`. Render the local avatar and all remote players (reuse `RemotePlayer` or extract its logic — prefer reuse). Name labels, interpolation at `REMOTE_LERP`, and the 15Hz move send must work.
+5. **Controls**: keyboard + on-screen joystick + drag-to-orbit camera, identical feel to `/play`. Mobile must work (touch joystick, touch drag). Reuse the `/play` input code rather than reinventing it.
+6. **Environment placeholder**: a simple lit ground + sky/fog so the space reads as a real room (prompt 02 replaces it with the venue). Not a void.
+
+## Acceptance criteria
+- Visiting `/arena/omniology` (via `npm run dev`, port 3000) loads with a designed loading state, then a navigable lit space.
+- Two browser tabs see each other move in real time, with name labels and smooth interpolation. Confirm in the Network/WS tab that it joined a `walk_world` instance keyed to `arena:omniology` (isolated from real coin worlds).
+- No multiplayer-server file was modified. No console errors or warnings from your code.
+- Local + remote avatars load and animate (idle/walk), no T-pose flash.
+- `dispose()` fully tears down on navigation away (no leaked rAF, listeners, or GPU memory).
+- `npm test` still passes. Review your own `git diff` before declaring done.
+
+## Hand-off to prompt 02
+Leave clear `anchors` defaults and a documented way for the venue loader to
+replace them. Do not author the venue here.
diff --git a/docs/omniology-arena/02-venue-and-anchors.md b/docs/omniology-arena/02-venue-and-anchors.md
new file mode 100644
index 000000000..5bfae5151
--- /dev/null
+++ b/docs/omniology-arena/02-venue-and-anchors.md
@@ -0,0 +1,58 @@
+# Prompt 02 — Premium venue GLB + named anchors
+
+Build the physical Omniology Arena: a premium, authored 3D venue with named
+anchor points (spawn, screen mounts, entry-desk spot, lighting), loaded into the
+bootstrap from prompt 01. Model the anchor contract on `/club`'s proven system.
+
+## Read first (required)
+- `docs/omniology-arena/README.md`, `docs/omniology-arena/CONTRACTS.md`, `CLAUDE.md`
+- `src/club-venue.js` — the named-empty contract. Study `REQUIRED_VENUE_EMPTIES`, `collectVenueEmpties(root, required)` (throws if any missing — **no silent fallback**), and `resolveVenueAnchors(empties, slotCount)`. Note the **underscore naming convention** (`screen_01`, not `screen.01`) and *why* (GLTF `sanitizeNodeName` strips `[]:./`).
+- `src/club.js` — how the club loads the venue GLB, runs `collectVenueEmpties`, applies anchors, sets up HDRI via `PMREMGenerator`, lighting rig, bloom/tone-mapping post pipeline, and per-mesh shadow opt-in. Reuse these patterns.
+- `scripts/build-club-venue.mjs`, `scripts/build-club-hdri.mjs` — how club assets are generated procedurally with `@gltf-transform/core` and wired to `npm run build:club-venue` / `build:club-hdri`. Mirror this approach.
+- `public/club/venue/LICENSES.md` — asset provenance discipline you must follow.
+- `src/game/arena/arena.js` from prompt 01 — the `anchors` field you will populate.
+
+## Build
+1. **Anchor module** `src/game/arena/arena-venue.js`: export `ARENA_REQUIRED_EMPTIES`, `collectArenaEmpties(root)`, and `resolveArenaAnchors(empties)` returning a typed object:
+ ```
+ { spawn:{pos,yaw}, screens:[{pos,yaw,width}], desk:{pos,yaw}, lights:[…], camera_intro:{pos,lookAt} }
+ ```
+ Reuse `collectVenueEmpties` semantics (hard error listing missing anchors). Cover it with a test like `tests/club-venue-load.test.js` → `tests/arena-venue.test.js`.
+2. **Venue GLB** at `public/arena/omniology/venue.glb`, generated by a new
+ `scripts/build-arena-venue.mjs` (procedural, like the club builder) OR a
+ designed GLB if you author one — either way it must contain every
+ `ARENA_REQUIRED_EMPTIES` anchor with underscore names. Required anchors at
+ minimum: `spawn_01`, `screen_01`…`screen_03` (the contest walls), `desk_01`
+ (entry desk), `light_key`, `light_fill`, `light_rim_01..0N`, `camera_intro`.
+ Add `npm run build:arena-venue` to `package.json` and document assets in a new
+ `public/arena/omniology/LICENSES.md`.
+3. **HDRI / environment** `public/arena/omniology/hdri.hdr` via
+ `scripts/build-arena-hdri.mjs` (or reuse a suitable existing CC0 asset with
+ provenance). Apply via `PMREMGenerator` exactly like club.
+4. **Mount in bootstrap**: in `OmniologyArena`, replace the prompt-01 placeholder
+ environment — load the venue GLB + HDRI in parallel (with a real progress
+ indicator feeding the loading overlay), run `collectArenaEmpties` +
+ `resolveArenaAnchors`, and overwrite `this.anchors`. Spawn the local player at
+ `spawn.pos/yaw`. Set up the lighting rig from the light anchors. Add a tasteful
+ post pipeline (bloom + ACES tone mapping + vignette) gated by a perf check.
+5. **Collision / bounds**: define the walkable region (venue footprint) and clamp
+ the player to it (client-side clamp like `/play`'s `WORLD_BOUND`; reuse zone
+ helpers from `src/game/world-zones.js` if useful). Keep players inside the room.
+6. **Performance**: instance/merge repeated structural meshes; one key light with
+ shadows, the rest cheap; respect a perf profile (mirror `src/club-perf.js`).
+ The venue must hold 60fps on a mid-tier laptop and run on mobile.
+
+## Acceptance criteria
+- `/arena/omniology` shows a premium, well-lit, screenshot-worthy room (not a gray
+ box). Spawn, lighting, and camera intro come from GLB anchors — confirm by moving
+ an anchor in the build script and seeing the runtime follow.
+- Missing an anchor throws a clear authoring error (verified by the new test).
+- `npm run build:arena-venue` (and the HDRI builder) are reproducible and the
+ outputs are committed with a `LICENSES.md`.
+- Multiplayer from prompt 01 still works; players spawn at `spawn_01` and are bounded.
+- No console errors/warnings. `npm test` passes (including the new anchor test).
+- 60fps mid-tier; verified in a real browser.
+
+## Hand-off
+`this.anchors.screens[]` and `this.anchors.desk` are the mount points prompts 03
+and 04 consume. Do not build screens or the desk here.
diff --git a/docs/omniology-arena/03-live-contest-screens.md b/docs/omniology-arena/03-live-contest-screens.md
new file mode 100644
index 000000000..6845c845b
--- /dev/null
+++ b/docs/omniology-arena/03-live-contest-screens.md
@@ -0,0 +1,65 @@
+# Prompt 03 — Live contest screens
+
+Build the in-world screens that show Omniology's live contests: the current
+contest with a ~88-second countdown, a leaderboard, and a live ticker of recent
+entries. Real data from Omniology's feed — no mocks, no sample arrays.
+
+## Read first (required)
+- `docs/omniology-arena/README.md`, `docs/omniology-arena/CONTRACTS.md` (esp. §1.1 feed shape and §2.1/§2.2 module contracts), `CLAUDE.md`
+- `src/game/chart-screen.js` — the proven live-screen pattern to generalize: a `CanvasTexture` (sRGB, anisotropy) on a `PlaneGeometry`, a poll loop with `clearTimeout`/`setTimeout`, a `draw()` that paints loading/live/empty/error states, a `~10fps` redraw (`REDRAW_MS = 100`) via `update(dt)`, clickable raycast, and a clean `dispose()`. Mirror its structure closely.
+- `src/game/coincommunities.js` `_buildScreen()` / `_drawScreen()` (~592–720) — event-driven redraw and canvas layout reference.
+- `src/game/arena/arena.js` (prompt 01) — `registerUpdatable()` and `this.anchors.screens[]` (prompt 02).
+
+## Build
+1. **Adapter** `src/game/arena/omniology-adapter.js` per CONTRACTS §2.1 — the
+ ONLY module that knows Omniology's wire shapes. `omniologyBase()` reads
+ `<meta name="omniology-base">` or `VITE_OMNIOLOGY_BASE`. `fetchLiveFeed()`
+ calls `GET {base}/v1/contests/live`, normalizes to `NormalizedFeed`
+ (ms timestamps, camelCase), and throws on network error. Also export
+ `submitEntryRequest(contestId, entry, agent)` for prompt 04 (define it now so
+ the boundary is fixed). **If `omniologyBase()` is empty, `fetchLiveFeed()`
+ must surface a clear "unconfigured" status — never return fabricated data.**
+2. **Screen component** `src/game/arena/contest-screen.js` per CONTRACTS §2.2 —
+ `createContestScreen(scene, { position, width, rotationY })`. Three logical
+ panels rendered to the canvas:
+ - **Now playing**: contest title, round number, prize (USDC), and a large
+ countdown to `closesMs` corrected by `serverNowMs` drift. Color shifts as
+ time runs low. When a round flips (round number changes), animate a brief
+ "NEW ROUND" sweep.
+ - **Leaderboard**: top entries with rank, agent, score, optional thumbnail.
+ - **Live ticker**: recent entries scrolling in; `pushEntry()` inserts
+ optimistically (used by the desk in prompt 04).
+ - A pulsing LIVE/OFFLINE status badge driven by `setStatus()`.
+3. **Polling controller**: one poller (not one per screen) calls
+ `fetchLiveFeed()` on an interval tuned to the 88s cadence (e.g. every 5s, and
+ immediately re-poll right after a detected round close to catch the flip).
+ Pause polling on `document.hidden`; resume on focus. Feed each screen via
+ `applyFeed()`. On error, `setStatus('error')` with a designed retry/backoff.
+4. **Mount**: in the arena bootstrap, create one `contest-screen` per
+ `this.anchors.screens[]` entry, add to scene, and `registerUpdatable()` each
+ so they redraw and advance the countdown every frame. (You may give the three
+ walls different roles — e.g. wall 1 now-playing, wall 2 leaderboard, wall 3
+ winners — via an option flag, but one component handles all.)
+5. **States (all designed, per CLAUDE.md)**: loading (skeleton on the canvas),
+ live (data), empty (between rounds / no contest — tell the viewer what's
+ next, e.g. "Next round opens in…"), error (Omniology unreachable — calm,
+ non-alarming, auto-retrying), unconfigured (no base URL set — a tasteful
+ "connecting to Omniology" placeholder, not fake leaderboard rows).
+
+## Acceptance criteria
+- With `VITE_OMNIOLOGY_BASE` (or the meta tag) pointed at Omniology's real or
+ sandbox feed, the screens show live contests, a counting-down ~88s clock that
+ stays in sync across a round flip, a populated leaderboard, and entries
+ ticking in. Verified in a real browser against a real endpoint.
+- With no base configured, screens show the designed unconfigured/connecting
+ state — never invented data. (This satisfies no-mocks while unblocked of the
+ partner.)
+- Network tab shows real GET polls; polling pauses when the tab is hidden.
+- Multiple screens share one poller; no duplicate requests per screen.
+- `dispose()` cleans canvas/texture/geometry and cancels timers.
+- No console errors/warnings. `npm test` passes. 60fps maintained with screens live.
+
+## Hand-off
+Export the screen handles (or a `pushEntry` hook) so prompt 04's desk can call
+`pushEntry()` on successful submission. Keep `submitEntryRequest()` in the
+adapter stable — prompt 04 depends on it.
diff --git a/docs/omniology-arena/04-entry-desk-x402-submit.md b/docs/omniology-arena/04-entry-desk-x402-submit.md
new file mode 100644
index 000000000..5030bce40
--- /dev/null
+++ b/docs/omniology-arena/04-entry-desk-x402-submit.md
@@ -0,0 +1,68 @@
+# Prompt 04 — Entry desk + x402 submission
+
+Build the in-world entry desk: a player walks up, presses E (or taps), composes
+an entry, and submits it to Omniology with a real USDC-on-Solana x402 payment —
+streamed live (challenge → settle → receipt) and reflected on the screens. This
+reuses the proven agent-commerce flow; **no scripted/fake stages**.
+
+## Read first (required)
+- `docs/omniology-arena/README.md`, `docs/omniology-arena/CONTRACTS.md` (esp. §1.2 submit, §2.1 `submitEntryRequest`, §2.3 desk contract), `CLAUDE.md`
+- `src/game/agent-commerce.js` — the reference end-to-end flow. Study: the
+ `fetch('/api/x402-pay', { headers:{accept:'text/event-stream'}, body:{…} })`
+ call (~428–435), the SSE consume loop (~443–467) handling
+ `challenge → built → settled → result` / `error`, the reusable `_sse(res)`
+ async-generator parser (~569–589), and how it renders the receipt with the
+ Solscan tx link.
+- `api/x402-pay.js` — the **external flow** (`runExternalFlow` / `handleExternalPay`, ~553–697 and ~921–1029). Confirm the exact request body it accepts to pay an arbitrary external URL (`url`, `method`, `body`, `agentId`, `service_label`, `stream`) and the exact SSE event names + data shapes it emits. Build against what the code actually does — quote the lines you relied on in your final report.
+- `src/game/play-systems.js` — the interaction/action-button framework (how an interactable/zone is defined and how E/tap triggers it). Reuse this for the desk's proximity prompt.
+- `src/game/arena/arena.js` (`this.anchors.desk`), `src/game/arena/omniology-adapter.js` (`submitEntryRequest`), and the screen `pushEntry()` from prompt 03.
+
+## Build
+1. **Desk object + interactable** `src/game/arena/entry-desk.js` per CONTRACTS
+ §2.3 — `createEntryDesk(scene, { position, rotationY, getAgentId,
+ getContestId, buildEntry, onSubmitted })`. Place a tasteful desk/kiosk mesh at
+ `anchors.desk`. Register a proximity interactable (reuse play-systems): when
+ the player is in range, show an "Enter contest — press E" prompt with proper
+ hover/active/focus affordances.
+2. **Compose UI** (`buildEntry`): an in-world/overlay form to assemble the entry
+ per Omniology's required fields (from CONTRACTS §1.2 / answers to QUESTIONS).
+ Validate locally against Omniology's rules **before** payment (one entry per
+ round, content limits, etc.) so we never charge for a doomed entry. Designed
+ empty/invalid states.
+3. **Submit flow**: on confirm, build the request via
+ `submitEntryRequest(contestId, entry, agent)` and `POST /api/x402-pay` with
+ `Accept: text/event-stream` and `{ url, method, body, agentId, service_label:
+ 'Omniology' }`. Consume the SSE stream with the `_sse` parser. Drive a live
+ stepper UI from the **real** events:
+ - `challenge` → show the fee (USDC) and "awaiting signature"
+ - `built` → "signed"
+ - `settled` → "settled on Solana" + Solscan link from `data.explorer`
+ - `result` → success: show the confirmation (entry id / round / position from
+ Omniology's response body) and call `onSubmitted(...)`
+ - `error` → designed, recoverable error (and make clear no funds moved if it
+ failed before `settled`; if `settle_uncertain`, show the exact warning the
+ API returns — do not silently retry).
+4. **Cross-wire to screens**: `onSubmitted` calls the screen `pushEntry({ agent,
+ entryId })` so the player sees their entry hit the live ticker immediately,
+ then the next poll reconciles it. Also play a small in-world celebration
+ (sound + light pulse) on success — tasteful, gated by reduced-motion.
+5. **Free-entry path**: if Omniology confirms entries are free (QUESTIONS #7),
+ POST directly to the submit URL (no x402) and skip the payment stepper. Keep
+ both paths implemented and selected by the adapter, not by a hardcoded flag.
+
+## Acceptance criteria
+- Walking to the desk and pressing E opens the compose UI; submitting runs a
+ **real** x402 payment and returns Omniology's real confirmation. Verified in a
+ real browser end-to-end against Omniology's real/sandbox submit endpoint, with
+ a real Solscan tx link (when an entry fee applies).
+- Every SSE stage is backed by a real event from `/api/x402-pay` — confirm by
+ reading the stream in the Network tab; no `setTimeout`-driven fake progress.
+- Local validation rejects bad entries before any payment.
+- The submitted entry appears on the live ticker immediately and persists after
+ the next poll.
+- Error/declined/uncertain states are all designed and accurate. Interactive
+ elements have hover/active/focus states. Keyboard accessible.
+- No console errors/warnings. `npm test` passes. Review your `git diff`.
+
+## Hand-off
+The Arena is now functionally complete. Prompt 06 does the polish/QA/launch pass.
diff --git a/docs/omniology-arena/05-omniology-mcp-server.md b/docs/omniology-arena/05-omniology-mcp-server.md
new file mode 100644
index 000000000..137e36686
--- /dev/null
+++ b/docs/omniology-arena/05-omniology-mcp-server.md
@@ -0,0 +1,70 @@
+# Prompt 05 — `@three-ws/omniology-mcp` server
+
+Build a real MCP server that exposes Omniology's contests as agent-callable
+tools (`list_contests`, `get_contest`, `get_leaderboard`, `submit_entry`), with
+`submit_entry` x402-priced in USDC. This is the contract artifact: it lets *any*
+MCP client/agent — not just our 3D world — read and enter Omniology contests, and
+it makes Omniology auto-discoverable in the x402 Bazaar. It wraps Omniology's
+**real** HTTP API (CONTRACTS §1). No mocks.
+
+## Read first (required)
+- `docs/omniology-arena/README.md`, `docs/omniology-arena/CONTRACTS.md` (§1 external contract), `CLAUDE.md`
+- `STRUCTURE.md` — the `packages/*-mcp` conventions and the published MCP list.
+- A representative existing server to mirror exactly — read **all** of one, e.g.
+ `packages/marketplace-mcp/` (its `package.json`, `server.json`, `src/index.js`).
+ Also skim `packages/activity-mcp/` or `packages/intel-mcp/` for read-only tool
+ shape, and `mcp-server/src/payments.js` + `mcp-server/src/tools/pose-seed.js`
+ for the x402 `paid()` wrapper pattern (`@x402/mcp`, Solana USDC settlement).
+- `mcp-bridge/src/bazaar-discover.js` — how a server gets discovered (so you set
+ `server.json` / discovery metadata correctly).
+
+## Build
+1. **Package** `packages/omniology-mcp/` named `@three-ws/omniology-mcp`,
+ matching the structure, scripts, ESM style, hand-written types, and
+ `node --test` suite of the reference package. Add it to the npm workspaces in
+ the root `package.json` and to the workspace list in `STRUCTURE.md`.
+2. **Config**: read Omniology's base URL from env
+ (`OMNIOLOGY_BASE_URL`), with a clear startup error if a paid tool is invoked
+ without required payment env (lazy-validate like `mcp-server/src/payments.js`).
+3. **Read tools** (free): `list_contests`, `get_contest(contestId)`,
+ `get_leaderboard(contestId)` — thin, validated wrappers over Omniology's feed
+ (CONTRACTS §1.1) with Zod input schemas, `zod-to-json-schema` output, and
+ sanitized errors. Real `fetch` to the real API.
+4. **Write tool** (x402-priced): `submit_entry(contestId, entry, agent?)` wrapped
+ with the `paid()` helper so it settles USDC on Solana before forwarding the
+ POST to Omniology's submit endpoint (CONTRACTS §1.2). If Omniology's own
+ endpoint already speaks x402, the tool can delegate the challenge; if not,
+ this server *is* the x402 front door for them — implement the settlement here
+ and forward authenticated. Pricing read from a `pricing` module like the other
+ servers.
+5. **`server.json`** manifest (stdio transport) under `io.github.nirholas/*`
+ namespace, consistent with sibling servers, with accurate tool descriptions
+ and discovery metadata.
+6. **Tests** (`node --test`): tool registration, input validation, error
+ sanitization, and the free/paid wrapper wiring. Network calls in tests must
+ hit a real injected fetch (dependency-injected), not a global monkeypatch —
+ follow the sibling package's test style. No live-network dependency in CI.
+7. **Docs**: a `README.md` with install + a real usage example, and add a row to
+ the MCP table in `STRUCTURE.md`.
+
+## Guardrails
+- Only `$THREE` may be referenced as a coin. USDC is the payment asset — fine.
+ No other token anywhere in code, tests, fixtures, or docs.
+- Real APIs only. If Omniology's endpoints aren't live yet, build against the
+ CONTRACTS shapes with a DI'd HTTP client and verify against their sandbox the
+ moment it exists — but ship no fabricated contest data.
+
+## Acceptance criteria
+- `cd packages/omniology-mcp && node --test test/*.test.js` is green.
+- The server boots over stdio and registers all four tools; read tools return
+ real Omniology data against a real/sandbox base URL; `submit_entry` performs a
+ real USDC settlement then forwards the entry.
+- `server.json` validates against the repo's manifest auditor
+ (`scripts/audit-mcp-manifests.mjs`).
+- Added to workspaces + `STRUCTURE.md`. `npm test` at root still passes.
+- Changelog: add an `sdk` entry to `data/changelog.json` (holder-readable) for
+ the new MCP server, then `npm run build:pages`.
+
+## Hand-off
+This server is independently shippable and is also what we hand Omniology if they
+prefer we run the x402 front door for them. It does not depend on prompts 01–04.
diff --git a/docs/omniology-arena/06-polish-qa-launch.md b/docs/omniology-arena/06-polish-qa-launch.md
new file mode 100644
index 000000000..0ba22e348
--- /dev/null
+++ b/docs/omniology-arena/06-polish-qa-launch.md
@@ -0,0 +1,65 @@
+# Prompt 06 — Polish, QA, and launch
+
+The Omniology Arena is functionally built (prompts 01–05). This pass makes it
+demo-perfect and durable: every state designed, responsive, accessible,
+performant, tested, documented, and verified end-to-end in a real browser. The
+goal is that it "just works 100%" with no follow-up babysitting.
+
+## Read first (required)
+- `docs/omniology-arena/README.md`, `CONTRACTS.md`, and prompts `01`–`05`
+- `CLAUDE.md` — especially the **Definition of done** and **Self-review protocol** checklists. You are enforcing them here.
+- The files produced by prompts 01–04 under `src/game/arena/`, the page
+ `pages/arena/omniology.html`, and the venue assets under `public/arena/omniology/`.
+- `src/club-perf.js` (perf profiles) and the weaknesses noted in the build plan.
+
+## Do
+1. **State audit** — for the world, screens, and desk verify all of: loading,
+ empty, error, populated, overflow (very long agent names, 0 / 1 / many
+ leaderboard rows, 0 entries, a stalled round), unconfigured, and
+ network-failure-mid-submit. Fix any undesigned or ugly state. Skeleton
+ loaders, not spinners. No blank voids.
+2. **Responsiveness** — verify at 320px, 768px, 1440px. Touch controls, the
+ compose UI, and the proximity prompt must all work on mobile. No fixed widths
+ that break.
+3. **Accessibility** — keyboard navigation for the desk/compose UI, focus rings,
+ ARIA labels on interactive controls, sufficient contrast on canvas text,
+ `prefers-reduced-motion` honored across bloom/celebration/animations.
+4. **Performance** — profile a populated room (multiple players + 3 live screens +
+ desk). Hold 60fps mid-tier and run on mobile. Apply the improvements the recon
+ flagged where they pay off: instance/merge structural and repeated meshes,
+ LOD or billboard distant remote avatars, share one poller across screens,
+ ensure polling/animation pause on `document.hidden`. Cap draw calls. No jank.
+5. **Resilience** — Omniology feed down → screens degrade calmly and auto-recover.
+ Multiplayer server unreachable → the world still loads single-player with a
+ clear notice. Submit failure → no double-charge, accurate messaging. A round
+ flipping mid-submit is handled.
+6. **Cross-links** — make the Arena reachable and navigable: add it where users
+ would look for it (the relevant directory/nav/launch surface), and ensure
+ leaving returns cleanly. A dead-end isn't done.
+7. **Tests** — add/extend tests: the venue anchor test (02), adapter
+ normalization (03), and the desk's SSE event handling against the documented
+ `/api/x402-pay` event shapes (04). `npm test` green.
+8. **Changelog** — add a holder-readable `feature` entry to `data/changelog.json`
+ for the Omniology Arena (plain language, no jargon; optional `link` to the
+ live path), then `npm run build:pages` to regenerate + validate.
+9. **Final verification** — run `npm run dev`, walk the full journey in a real
+ browser: spawn → see another player → watch a live ~88s contest on screens →
+ walk to the desk → submit a real entry → see it confirm and hit the ticker.
+ Capture that there are **no console errors or warnings** and that the Network
+ tab shows real API calls succeeding. Run the repo's responsive-audit script if
+ present.
+
+## Acceptance criteria (the bar)
+- Every box in CLAUDE.md's **Definition of done** is true and you can say so
+ explicitly, per surface.
+- The full end-to-end journey works in a real browser with real data, zero
+ console errors/warnings.
+- 60fps mid-tier; mobile usable. All states designed. A11y verified.
+- `npm test` passes; changelog entry added and `build:pages` is green.
+- `git diff` reviewed line-by-line; every change justified. You would be proud to
+ demo this to a room of senior engineers and to Omniology.
+
+## Do NOT
+- Do not commit/push unless explicitly told. Do not modify the multiplayer server.
+- Do not reference any coin other than `$THREE` (USDC payment asset is fine).
+- Do not leave any TODO, stub, mock, sample array, or `setTimeout` fake progress.
diff --git a/docs/omniology-arena/CONTRACTS.md b/docs/omniology-arena/CONTRACTS.md
new file mode 100644
index 000000000..c6490ea24
--- /dev/null
+++ b/docs/omniology-arena/CONTRACTS.md
@@ -0,0 +1,179 @@
+# Shared Contracts — Omniology Arena
+
+This file is the single source of truth for the interfaces that the build
+prompts share. If a shape changes, change it here and the prompts inherit it.
+
+There are two kinds of contracts:
+- **External** — what Omniology's service must expose (consumed by prompts 03, 04, 05).
+- **Internal** — module boundaries between our own prompts so they compose cleanly.
+
+---
+
+## 1. External contract — Omniology service
+
+> Verify the canonical Solana mainnet **USDC mint** by reading it from the repo
+> (`api/_lib/x402-spec.js` / `api/_lib/env.js`). Do **not** hardcode a mint from
+> memory. All amounts are atomic (USDC = 6 decimals; 1 USDC = `1000000`).
+
+### 1.1 Contest feed (read) — for the screens (prompt 03)
+
+A single polled endpoint is enough. Free (no x402) is preferred for reads so the
+screens stay cheap to refresh.
+
+```
+GET {OMNIOLOGY_BASE}/v1/contests/live
+Accept: application/json
+
+200 →
+{
+ "now_unix": 1719259200, // server time, for countdown drift correction
+ "current": {
+ "id": "string",
+ "title": "string",
+ "round": 1421, // monotonically increasing round number
+ "opened_unix": 1719259112,
+ "closes_unix": 1719259200, // ~88s after opened
+ "entries_count": 37,
+ "prize_usdc": 12.5,
+ "prize_asset": "USDC"
+ },
+ "next": { "opens_unix": 1719259200 } | null,
+ "leaderboard": [ // for the CURRENT or most-recent round
+ { "rank": 1, "entry_id": "string", "agent": "display name", "score": 0.92, "thumb_url": "https://…" | null }
+ ],
+ "recent_entries": [ // newest first, for the live ticker
+ { "entry_id": "string", "agent": "display name", "submitted_unix": 1719259190 }
+ ],
+ "recent_winners": [ // last few rounds, for "past winners" panel
+ { "round": 1420, "agent": "display name", "prize_usdc": 11.0, "tx": "solana sig" | null }
+ ]
+}
+```
+
+Notes:
+- `closes_unix - now_unix` drives the on-screen countdown (the ~88s clock).
+- All `*_url` fields must be HTTPS and CORS-readable from `three.ws`, or proxied.
+- If a field is unknown, send `null` — never omit. Screens render designed empty
+ states for nulls; they must not invent data.
+
+### 1.2 Submit entry (write, x402-priced) — for the desk (prompt 04)
+
+```
+POST {OMNIOLOGY_BASE}/v1/contests/{contestId}/entries
+Content-Type: application/json
+Body: { "entry": { …partner-defined… }, "agent": "display name" | null }
+```
+
+- **First call returns `402 Payment Required`** with a standard x402 challenge:
+ - `scheme: "exact"`, `network: "solana-mainnet"`
+ - `asset`: canonical Solana mainnet USDC mint (per repo)
+ - `amount`: atomic USDC (the entry fee; may be `"0"` only if entry is free —
+ but then there is nothing to pay and the desk uses a plain POST, see below)
+ - `payTo`: Omniology's Solana receiver
+ - `extra.feePayer`: a funded Solana account that co-signs (required for SVM exact)
+ - `resource`: `{ url, description, serviceName: "Omniology" }`
+- Client signs + retries with `X-PAYMENT`. On success return `200` with:
+ - header `X-PAYMENT-RESPONSE` (base64 receipt: `{ transaction, payer, network }`)
+ - body: `{ "entry_id": "string", "status": "accepted", "round": 1421, "position": 38 }`
+
+If entry submission is **free** (no payment), say so in `QUESTIONS` — the desk
+will POST directly and skip x402 entirely. Do not return a `402` with `amount: 0`.
+
+### 1.3 MCP surface (optional but preferred) — prompt 05
+
+The same two capabilities exposed as MCP tools so agents (not just our world)
+can use them, and so the service auto-registers in the x402 Bazaar:
+- `list_contests` / `get_contest` / `get_leaderboard` → read (1.1)
+- `submit_entry` → x402-priced write (1.2)
+
+---
+
+## 2. Internal contract — our modules
+
+These are the boundaries between prompts. Keep these signatures stable so each
+prompt can be built and tested independently.
+
+### 2.1 `src/game/arena/omniology-adapter.js` (produced in 03, used by 03 & 04)
+
+The ONLY place that knows Omniology's wire shapes. Everything else consumes
+normalized objects, so swapping the real base URL is a one-file change.
+
+```js
+// Config: reads base URL from <meta name="omniology-base"> or VITE_OMNIOLOGY_BASE.
+export function omniologyBase() // → string ('' if unconfigured)
+export async function fetchLiveFeed() // → NormalizedFeed (throws on network error)
+export function submitEntryRequest(contestId, entry, agent)
+ // → { url, method:'POST', body } — the exact payload for /api/x402-pay external flow
+
+// NormalizedFeed:
+// {
+// ok: boolean,
+// serverNowMs: number,
+// current: { id, title, round, opensMs, closesMs, entriesCount, prizeUsdc } | null,
+// leaderboard: [{ rank, entryId, agent, score, thumbUrl }],
+// recentEntries: [{ entryId, agent, submittedMs }],
+// recentWinners: [{ round, agent, prizeUsdc, tx }]
+// }
+```
+
+### 2.2 `src/game/arena/contest-screen.js` (produced in 03)
+
+Generalized live screen, modeled on `src/game/chart-screen.js`.
+
+```js
+export function createContestScreen(scene, { position, width, rotationY }) // → handle
+// handle = {
+// group, // THREE.Group added to scene
+// update(dt), // call each frame; redraws ~10fps, advances countdown
+// applyFeed(normalizedFeed), // push latest poll result
+// pushEntry({ agent, entryId }),// optimistic live ticker insert (called by the desk)
+// setStatus('loading'|'live'|'empty'|'error'),
+// dispose()
+// }
+```
+
+### 2.3 `src/game/arena/entry-desk.js` (produced in 04)
+
+```js
+export function createEntryDesk(scene, {
+ position, rotationY,
+ getAgentId, // () → current player's paying agent id
+ getContestId, // () → current contest id (from the adapter feed)
+ buildEntry, // async () → entry object (opens the in-world compose UI)
+ onSubmitted, // ({ entryId, agent, payment }) → void (wire to screen.pushEntry)
+}) // → handle { group, update(dt), interact(), dispose() }
+```
+
+The desk calls `POST /api/x402-pay` with
+`{ url, method, body }` from `submitEntryRequest(...)` plus the paying
+`agentId`, `Accept: text/event-stream`, and consumes the SSE sequence
+`challenge → built → settled → result` (or `error`). See prompt 04 for the
+verified event shapes and the reusable `_sse` parser from
+`src/game/agent-commerce.js`.
+
+### 2.4 Bootstrap registry (produced in 01)
+
+The arena bootstrap exposes mount points so 02/03/04 attach without editing each
+other:
+
+```js
+// src/game/arena/arena.js
+class OmniologyArena {
+ scene, renderer, camera
+ anchors // resolved from the venue GLB (02): { spawn, screens:[], desk, lights:[] }
+ registerUpdatable(obj /* has update(dt) */) // 03/04 register their handles here
+}
+```
+
+---
+
+## 3. Environment / config keys (no secrets in client)
+
+| Key | Where | Purpose |
+|---|---|---|
+| `<meta name="game-server">` | `pages/arena/omniology.html` | Colyseus URL (copy from `pages/play.html`) |
+| `<meta name="omniology-base">` or `VITE_OMNIOLOGY_BASE` | page / build env | Omniology feed + submit base URL |
+| `X402_*` (agent wallet, facilitator, USDC) | server env (already set) | Used by `/api/x402-pay`; no client exposure |
+
+The paying wallet and facilitator are server-side and already configured for the
+existing agent-commerce flow — prompt 04 reuses them, it does not add new secrets.
diff --git a/docs/omniology-arena/README.md b/docs/omniology-arena/README.md
new file mode 100644
index 000000000..e3ab6d9d4
--- /dev/null
+++ b/docs/omniology-arena/README.md
@@ -0,0 +1,98 @@
+# Omniology Arena — Build Plan
+
+A dedicated, premium 3D multiplayer venue inside three.ws for **Omniology**
+(omniology.ai) — an external collaborator running AI-agent contests every ~88 seconds
+with USDC-on-Solana prizes. Players and agents walk into the Arena, watch live
+contests on in-world screens, and submit entries from inside the 3D world.
+
+This venue is the **best-of** `/play` (open-world multiplayer) and `/club`
+(authored named-venue) — rebuilt clean as its own surface, not bolted onto either.
+
+---
+
+## How to use this folder
+
+Each `NN-*.md` file is a **self-contained build prompt** meant to be run in its
+own fresh chat, in order. Every prompt:
+
+- names the exact repo files to read first,
+- states what it produces and what it consumes from earlier prompts,
+- ends with hard acceptance criteria.
+
+Run them in sequence: **01 → 02 → 03 → 04 → 05 → 06**. Prompt 05 (the Omniology
+MCP server) and the Omniology-side API can proceed in parallel once the contract
+in `CONTRACTS.md` is agreed.
+
+Before running any prompt, the agent in that chat must read:
+- `docs/omniology-arena/README.md` (this file)
+- `docs/omniology-arena/CONTRACTS.md` (shared interfaces)
+- the repo root `CLAUDE.md` (operating rules — non-negotiable)
+
+---
+
+## Architecture decisions (already made — do not relitigate)
+
+1. **Dedicated route, isolated surface.** The Arena is its own page + bootstrap
+ module at route `/arena/omniology` (confirm no collision with any existing
+ `pages/arena.html` / `pages/play/arena.html` first; namespace under
+ `/arena/omniology` so a third party's space never entangles the core worlds).
+
+2. **Reuse the `walk_world` Colyseus room via a namespaced token — NO server
+ changes.** The multiplayer server (`multiplayer/src/index.js`) defines
+ `walk_world` with `filterBy(['coin','tier'])`. The client joins with a stable
+ synthetic token (e.g. `coin.mint = 'arena:omniology'`, `tier: ''`). Colyseus
+ isolates that into its own room instances automatically. Presence, movement,
+ remote avatars, name labels, voice, and cosmetics all come for free. **We do
+ not define a new room or redeploy the multiplayer server.** Rationale: lowest
+ operational risk, nothing new to maintain server-side.
+
+3. **Contest state never touches our game server.** The live contest feed and
+ entry submission live entirely in Omniology's service. Screens *poll*
+ Omniology's feed; the entry desk *submits* via our existing universal x402
+ payer (`/api/x402-pay` → external flow). The Colyseus room only carries player
+ presence. This keeps Omniology's uptime decoupled from our world.
+
+4. **The building is the only core-side asset we author.** A premium venue GLB
+ with named anchors (modeled on `/club`'s `club-venue.js` contract), plus its
+ environment/lighting. Everything else reuses existing systems as libraries.
+
+5. **No mocks, ever (CLAUDE.md).** Screens and the desk wire to Omniology's
+ *real* endpoints. Where Omniology's API is not yet live, we ship real,
+ designed loading/empty/error states (not sample data). The moment the real
+ base URL + contract land, it's live with no code rewrite — only config.
+
+6. **$THREE is the only coin.** USDC is fine as a payment asset (it is not a
+ coin we promote). Never render, name, or hardcode any other token anywhere in
+ this venue. Read the canonical USDC mint from the repo's x402 spec — never
+ paste a mint from memory.
+
+---
+
+## Surface map (what gets built, by prompt)
+
+| Prompt | Deliverable | Depends on |
+|---|---|---|
+| **01** | Route + page + bootstrap skeleton; multiplayer presence in a namespaced `walk_world`; local player movement/camera; empty lit space you can walk around with others | — |
+| **02** | Premium Arena venue GLB + named-anchor module (build script + loader + anchor resolution); environment, lighting, spawn, collision/bounds | 01 |
+| **03** | Generalized live in-world screens (current contest, ~88s countdown, leaderboard, recent entries) fed by Omniology's contest feed via an adapter; mounted on venue screen anchors | 02 + CONTRACTS |
+| **04** | In-world entry desk interactable → `/api/x402-pay` external flow → live SSE settlement UI → receipt; pushes the new entry to the screens from 03 | 03 + CONTRACTS |
+| **05** | `@three-ws/omniology-mcp` server (`list_contests`, `get_contest`, `get_leaderboard`, `submit_entry`), x402-priced, `server.json`, modeled on `packages/*-mcp` | CONTRACTS |
+| **06** | Polish pass: all states designed, responsive, a11y, performance (instancing/LOD), tests, changelog entry, real-browser end-to-end verification | 01–05 |
+
+---
+
+## The one hard external dependency
+
+For screens (03) and submission (04) to be **100% working with no mocks**,
+Omniology must expose the endpoints in `CONTRACTS.md`. The questions we need
+answered to lock that contract are in `QUESTIONS-FOR-OMNIOLOGY.md` — send those
+first. Until the feed URL exists, 03/04 are built against the documented
+contract behind a thin adapter, and verified against their real endpoint as soon
+as it's live.
+
+---
+
+## Status
+
+These files are **uncommitted working docs**. They are not pushed to either
+mirror. Commit them only if/when the project is greenlit.
diff --git a/packages/omniology-mcp/LICENSE b/packages/omniology-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/omniology-mcp/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/omniology-mcp/package.json b/packages/omniology-mcp/package.json
new file mode 100644
index 000000000..39c213165
--- /dev/null
+++ b/packages/omniology-mcp/package.json
@@ -0,0 +1,64 @@
+{
+ "name": "@three-ws/omniology-mcp",
+ "version": "0.1.0",
+ "description": "x402 MCP server for Omniology AI-agent contests: list/get contests + leaderboards (free) and submit_entry priced in USDC on Solana.",
+ "type": "module",
+ "author": "nirholas <[email protected]>",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "mcpName": "io.github.nirholas/omniology-mcp",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/omniology-mcp"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "omniology",
+ "contests",
+ "leaderboard",
+ "x402",
+ "usdc",
+ "solana",
+ "pay-per-use",
+ "ai-agent",
+ "three.ws"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "bin": {
+ "omniology-mcp": "src/index.js"
+ },
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "start": "node src/index.js",
+ "test": "node --test \"test/**/*.test.mjs\"",
+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@x402/core": "^2.13.0",
+ "@x402/extensions": "^2.13.0",
+ "@x402/mcp": "^2.13.0",
+ "@x402/svm": "^2.13.0",
+ "zod": "^3.23.8",
+ "zod-to-json-schema": "3.25.2"
+ }
+}
diff --git a/packages/omniology-mcp/server.json b/packages/omniology-mcp/server.json
new file mode 100644
index 000000000..d83f2a2fd
--- /dev/null
+++ b/packages/omniology-mcp/server.json
@@ -0,0 +1,80 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/omniology-mcp",
+ "title": "Omniology Contests via x402",
+ "description": "Read Omniology AI-agent contests and leaderboards (free); submit_entry settles USDC on Solana via x402.",
+ "websiteUrl": "https://three.ws",
+ "icons": [
+ {
+ "src": "https://three.ws/three-ws-mcp-icon.svg",
+ "mimeType": "image/svg+xml",
+ "sizes": [
+ "any"
+ ]
+ }
+ ],
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github",
+ "subfolder": "packages/omniology-mcp"
+ },
+ "version": "0.1.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "@three-ws/omniology-mcp",
+ "version": "0.1.0",
+ "runtimeHint": "npx",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "OMNIOLOGY_BASE_URL",
+ "description": "Base URL of the Omniology contest API (serves /v1/contests/live and /v1/contests/{id}/entries). Required.",
+ "isRequired": true,
+ "isSecret": false,
+ "format": "string"
+ },
+ {
+ "name": "OMNIOLOGY_API_KEY",
+ "description": "Bearer token this server sends to Omniology when forwarding a paid entry submission. Optional — set when Omniology authenticates the front door.",
+ "isRequired": false,
+ "isSecret": true,
+ "format": "string"
+ },
+ {
+ "name": "OMNIOLOGY_SUBMIT_PRICE_USD",
+ "description": "Price charged for submit_entry, e.g. \"$0.05\". Defaults to $0.05 USDC.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "OMNIOLOGY_TIMEOUT_MS",
+ "description": "Per-request timeout in milliseconds for calls to the Omniology API. Defaults to 20000.",
+ "isRequired": false,
+ "format": "number"
+ },
+ {
+ "name": "MCP_SVM_PAYMENT_ADDRESS",
+ "description": "Solana wallet that receives USDC payments for submit_entry (server operator's receiving wallet). Required to accept x402 payments.",
+ "isRequired": true,
+ "isSecret": false,
+ "format": "string"
+ },
+ {
+ "name": "X402_FEE_PAYER_SOLANA",
+ "description": "Solana account that sponsors transaction fees for x402 payments. Defaults to the three.ws fee payer.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "X402_FACILITATOR_URL",
+ "description": "x402 facilitator endpoint for payment verification and settlement. Defaults to https://facilitator.payai.network.",
+ "isRequired": false,
+ "format": "string"
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/omniology-mcp/src/config.js b/packages/omniology-mcp/src/config.js
new file mode 100644
index 000000000..1ce7acbad
--- /dev/null
+++ b/packages/omniology-mcp/src/config.js
@@ -0,0 +1,51 @@
+// Centralized env for the Omniology MCP server.
+//
+// The read tools wrap Omniology's PUBLIC contest feed; submit_entry settles
+// USDC on Solana (x402) and then forwards an authenticated POST to Omniology.
+// The only knobs here are which Omniology deployment to talk to, an optional
+// bearer token for the authenticated forward, and timeouts. The Solana payment
+// env (MCP_SVM_PAYMENT_ADDRESS, X402_*) lives in payments.js.
+
+export function env(key, fallback) {
+ const v = process.env[key];
+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;
+}
+
+// Base URL of the Omniology contest API (serves /v1/contests/live and
+// /v1/contests/{id}/entries). No default — Omniology is an external service, so
+// an unconfigured server fails clearly at startup rather than guessing a host.
+export const OMNIOLOGY_BASE = env('OMNIOLOGY_BASE_URL', '').replace(/\/+$/, '');
+
+// Optional bearer token sent to Omniology ONLY on the authenticated forward of
+// a paid submit_entry. Never exposed to the MCP client.
+export const OMNIOLOGY_API_KEY = env('OMNIOLOGY_API_KEY', '');
+
+// Per-request timeout (ms) for calls to Omniology.
+export const HTTP_TIMEOUT_MS = (() => {
+ const raw = env('OMNIOLOGY_TIMEOUT_MS');
+ if (raw === undefined) return 20000;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw Object.assign(new Error(`OMNIOLOGY_TIMEOUT_MS must be a positive number (got "${raw}")`), {
+ code: 'bad_config',
+ });
+ }
+ return n;
+})();
+
+// Identifies this client to Omniology in request logs.
+export const USER_AGENT = '@three-ws/omniology-mcp';
+
+/**
+ * Assert OMNIOLOGY_BASE_URL is configured. Called once by the stdio entry point
+ * so a running server fails fast with a single clean line instead of only
+ * erroring on the first tool call. Not run during buildServer()/tests.
+ * @throws {Error} when OMNIOLOGY_BASE_URL is unset
+ */
+export function assertBaseUrl() {
+ if (!OMNIOLOGY_BASE) {
+ throw new Error(
+ 'OMNIOLOGY_BASE_URL is not set — point it at the Omniology contest API (e.g. https://api.omniology.ai).',
+ );
+ }
+}
diff --git a/packages/omniology-mcp/src/pricing.js b/packages/omniology-mcp/src/pricing.js
new file mode 100644
index 000000000..854da090a
--- /dev/null
+++ b/packages/omniology-mcp/src/pricing.js
@@ -0,0 +1,23 @@
+// Single source of truth for what submit_entry costs.
+//
+// Like the sibling x402 MCP servers, the price lives in one module so the tool
+// description, getting-started catalog, and the x402 `accepts` requirement can
+// never drift. The default is a flat per-submission fee; operators override it
+// with OMNIOLOGY_SUBMIT_PRICE_USD (e.g. "$0.10"). This is the MCP front-door
+// fee — distinct from any contest entry fee Omniology settles on its own side.
+
+import { env } from './config.js';
+
+function normalizePrice(raw) {
+ const value = String(raw).trim();
+ if (!/^\$\d+(\.\d+)?$/.test(value)) {
+ throw Object.assign(
+ new Error(`OMNIOLOGY_SUBMIT_PRICE_USD must look like "$0.05" (got "${raw}")`),
+ { code: 'bad_config' },
+ );
+ }
+ return value;
+}
+
+// USDC price for one submit_entry call, settled `exact` on Solana mainnet.
+export const SUBMIT_ENTRY_PRICE_USD = normalizePrice(env('OMNIOLOGY_SUBMIT_PRICE_USD', '$0.05'));
diff --git a/pages/arena/omniology.html b/pages/arena/omniology.html
new file mode 100644
index 000000000..620fd3f65
--- /dev/null
+++ b/pages/arena/omniology.html
@@ -0,0 +1,153 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <title>Omniology Arena · three.ws</title>
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1, viewport-fit=cover"
+ />
+ <meta
+ name="description"
+ content="The Omniology Arena — a live 3D venue on three.ws. Walk in as your avatar, meet other players in real time, and watch AI-agent contests unfold on the in-world screens."
+ />
+ <meta name="theme-color" content="#060607" />
+
+ <!--
+ Multiplayer server URL — the deployed Colyseus host (Cloud Run). Local dev
+ ignores this and uses ws://localhost:2567 automatically (see
+ defaultServerUrl in src/game/community-net.js), so `npm run dev:walk-all`
+ still works out of the box. Copied verbatim from pages/play.html.
+ -->
+ <meta name="game-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" />
+
+ <!--
+ Omniology service base URL — the live contest feed + entry-submission API
+ (CONTRACTS §3). Empty until the partner endpoint is live; prompts 03/04 read
+ it via src/game/arena/omniology-adapter.js (meta first, then VITE_OMNIOLOGY_BASE).
+ Leaving it blank keeps the screens/desk in their designed empty states — never
+ mock data — until the real base lands, which is a config-only change.
+ -->
+ <meta name="omniology-base" content="" />
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Omniology Arena · three.ws" />
+ <meta property="og:description" content="A live 3D venue on three.ws — walk in, meet other players in real time, and watch AI-agent contests on the in-world screens." />
+ <meta property="og:url" content="https://three.ws/arena/omniology" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Omniology Arena · three.ws" />
+ <meta name="twitter:description" content="Step into the Omniology Arena — a live multiplayer 3D venue on three.ws." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <!-- Shared world chrome: loading overlay, boot-avatar card, nameplates,
+ bubbles, and the on-screen joystick (#cc-joystick / .cc-joy-*). Reusing
+ /play's stylesheet keeps the arena visually consistent with the core
+ worlds and gives every presence label the same treatment. -->
+ <link rel="stylesheet" href="/src/game/coincommunities.css" />
+ <style>
+ /* Arena-only chrome layered over the shared world styles. Kept tiny and
+ self-contained; the venue HUD (screens, entry desk) arrives in 02–04. */
+ #arena-brand {
+ position: fixed; top: 14px; left: 16px; z-index: 40;
+ display: inline-flex; align-items: center; gap: 9px;
+ padding: 8px 12px; border-radius: var(--cc-radius, 4px);
+ background: var(--cc-panel, rgba(12, 12, 14, 0.78));
+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));
+ backdrop-filter: saturate(150%) blur(14px);
+ -webkit-backdrop-filter: saturate(150%) blur(14px);
+ color: var(--cc-text, #f5f5f6);
+ font: 600 13px/1 "Inter", system-ui, sans-serif;
+ letter-spacing: 0.04em; text-transform: uppercase;
+ transition: border-color 0.18s ease, transform 0.18s ease;
+ }
+ #arena-brand:hover, #arena-brand:focus-visible {
+ border-color: var(--cc-edge-hi, rgba(255, 255, 255, 0.55));
+ transform: translateY(-1px);
+ outline: none;
+ }
+ #arena-brand img { width: 18px; height: 18px; display: block; }
+ #arena-brand small {
+ color: var(--cc-dim, #8c8c92); font-weight: 500;
+ text-transform: none; letter-spacing: 0;
+ }
+ #arena-status {
+ position: fixed; top: 14px; right: 16px; z-index: 40;
+ display: inline-flex; align-items: center; gap: 7px;
+ padding: 8px 13px; border-radius: 999px;
+ background: var(--cc-panel, rgba(12, 12, 14, 0.78));
+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));
+ backdrop-filter: saturate(150%) blur(14px);
+ -webkit-backdrop-filter: saturate(150%) blur(14px);
+ color: var(--cc-dim, #8c8c92);
+ font: 600 11px/1 "Inter", system-ui, sans-serif;
+ letter-spacing: 0.08em; text-transform: uppercase;
+ cursor: default; user-select: none;
+ }
+ #arena-status[data-retry="1"] { cursor: pointer; }
+ #arena-status .dot {
+ width: 8px; height: 8px; border-radius: 50%;
+ background: var(--cc-faint, #5a5a60);
+ box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
+ transition: background 0.2s ease, box-shadow 0.2s ease;
+ }
+ #arena-status[data-state="online"] { color: var(--cc-text, #f5f5f6); }
+ #arena-status[data-state="online"] .dot {
+ background: var(--cc-live, #fff);
+ box-shadow: 0 0 10px rgba(255, 255, 255, 0.85);
+ animation: arena-pulse 1.8s ease-in-out infinite;
+ }
+ #arena-status[data-state="connecting"] .dot { animation: arena-blink 1s ease-in-out infinite; }
+ @keyframes arena-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.55; } }
+ @keyframes arena-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.25; } }
+ @media (prefers-reduced-motion: reduce) {
+ #arena-status .dot { animation: none !important; }
+ }
+ @media (max-width: 560px) {
+ #arena-brand small { display: none; }
+ }
+ </style>
+ </head>
+ <body>
+ <div id="kx-loading">
+ <div class="kx-loading-card">
+ <img class="kx-loading-logo" src="/three.svg" alt="three.ws" width="38" height="38" />
+ <div class="kx-loading-mark">OMNIOLOGY ARENA</div>
+ <div class="kx-boot-stage">
+ <canvas id="kx-boot-avatar" aria-hidden="true"></canvas>
+ <div class="kx-boot-fallback" aria-hidden="true"></div>
+ </div>
+ <div class="kx-loading-sub">Entering the arena…</div>
+ <div class="kx-boot-bar" role="status" aria-label="Loading"><span></span></div>
+ </div>
+ </div>
+
+ <canvas id="kx-canvas"></canvas>
+
+ <a id="arena-brand" href="/" aria-label="Back to three.ws">
+ <img src="/three.svg" alt="" />
+ Arena<small>Omniology</small>
+ </a>
+ <div id="arena-status" data-state="connecting" role="status" aria-live="polite">
+ <span class="dot" aria-hidden="true"></span>
+ <span class="label">Connecting</span>
+ </div>
+
+ <!-- On-screen / drag joystick mount (touch + mouse). Styled by coincommunities.css;
+ the thumb + base are created by the arena controller at runtime. -->
+ <div id="cc-joystick" aria-hidden="true"></div>
+
+ <script type="module" src="/src/game/boot-avatar.js"></script>
+ <script type="module" src="/src/game/arena/omniology.js"></script>
+</body>
+</html>
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index 9f7b0b616..14c413fd2 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -1764,6 +1764,61 @@
} from '/src/wallet.js';
import { emptyStateHTML } from '/src/shared/state-kit.js';
+ // Some embedded webviews — notably the in-app browsers X/Twitter
+ // and a few Android wrappers ship — expose `window.localStorage`
+ // as `null`, or throw on access in private mode. Reading it
+ // directly during module init crashed the whole page. Route every
+ // storage call through this shim: it probes the real store once,
+ // and silently degrades to an in-memory map when it's unavailable
+ // so the dashboard still loads (config just won't persist).
+ const safeStorage = (() => {
+ let store = null;
+ try {
+ store = window.localStorage;
+ const probe = '__twx_probe__';
+ store.setItem(probe, '1');
+ store.removeItem(probe);
+ } catch {
+ store = null;
+ }
+ const mem = new Map();
+ return {
+ getItem(key) {
+ if (store) {
+ try {
+ return store.getItem(key);
+ } catch {
+ /* fall through to in-memory */
+ }
+ }
+ return mem.has(key) ? mem.get(key) : null;
+ },
+ setItem(key, value) {
+ const v = String(value);
+ if (store) {
+ try {
+ store.setItem(key, v);
+ return;
+ } catch {
+ /* fall through to in-memory */
+ }
+ }
+ mem.set(key, v);
+ },
+ removeItem(key) {
+ if (store) {
+ try {
+ store.removeItem(key);
+ return;
+ } catch {
+ /* fall through to in-memory */
+ }
+ }
+ mem.delete(key);
+ },
+ };
+ })();
+
const PAGE_TITLES = {
dashboard: 'Dashboard',
feed: 'Live Feed',
@@ -1780,16 +1835,16 @@
};
const state = {
- apiUrl: localStorage.getItem('pumpbot-api-url') || location.origin,
- wsUrl: localStorage.getItem('pumpbot-ws-url') || 'wss://pumpportal.fun/api/data',
- apiKey: localStorage.getItem('pumpbot-api-key') || '',
+ apiUrl: safeStorage.getItem('pumpbot-api-url') || location.origin,
+ wsUrl: safeStorage.getItem('pumpbot-ws-url') || 'wss://pumpportal.fun/api/data',
+ apiKey: safeStorage.getItem('pumpbot-api-key') || '',
// Default to the same-origin proxy (/api/solana-rpc), which forwards
// to a keyed Helius upstream server-side. The public RPC 403s
// browser requests, so we also migrate anyone whose stored value is
// that old broken default onto the proxy; genuine custom RPCs are
// preserved untouched.
rpcUrl: (() => {
- const stored = localStorage.getItem('pumpbot-rpc-url');
+ const stored = safeStorage.getItem('pumpbot-rpc-url');
return stored && stored !== 'https://api.mainnet-beta.solana.com'
? stored
: '/api/solana-rpc';
@@ -1802,7 +1857,7 @@
activityCount: 0,
feedPaused: false,
alertRules: (() => {
- const v = safeParseJson(localStorage.getItem('pumpbot-alerts') || '[]', []);
+ const v = safeParseJson(safeStorage.getItem('pumpbot-alerts') || '[]', []);
return Array.isArray(v) ? v : [];
})(),
// Deep-link target: /pump-dashboard?agent=<id> (e.g. straight from the
@@ -3039,7 +3094,7 @@
}
const { rules } = await resp.json();
state.alertRules = Array.isArray(rules) ? rules : [];
- localStorage.setItem('pumpbot-alerts', JSON.stringify(state.alertRules));
+ safeStorage.setItem('pumpbot-alerts', JSON.stringify(state.alertRules));
setRuleFormSignedOut(false);
renderRulesList(state.alertRules);
populateAgentOptions();
@@ -4156,10 +4211,10 @@
state.wsUrl = $('pd-cfg-ws-url').value.trim() || 'wss://pumpportal.fun/api/data';
state.apiKey = $('pd-cfg-api-key').value.trim();
state.rpcUrl = $('pd-cfg-rpc-url').value.trim() || '/api/solana-rpc';
- localStorage.setItem('pumpbot-api-url', state.apiUrl);
- localStorage.setItem('pumpbot-ws-url', state.wsUrl);
- localStorage.setItem('pumpbot-api-key', state.apiKey);
- localStorage.setItem('pumpbot-rpc-url', state.rpcUrl);
+ safeStorage.setItem('pumpbot-api-url', state.apiUrl);
+ safeStorage.setItem('pumpbot-ws-url', state.wsUrl);
+ safeStorage.setItem('pumpbot-api-key', state.apiKey);
+ safeStorage.setItem('pumpbot-rpc-url', state.rpcUrl);
$('pd-api-endpoint-display').textContent = state.apiUrl;
connectApi();
// A manual save is an explicit retry — reset the backoff so the new
diff --git a/public/changelog.json b/public/changelog.json
index 0054e5f4b..9c030ce91 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-25T08:09:10.560Z",
+ "generated_at": "2026-06-25T21:00:11.813Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -27,6 +27,27 @@
"infra"
]
},
+ {
+ "date": "2026-06-25",
+ "type": "update",
+ "title": "Pump dashboard now loads inside X/Twitter's in-app browser",
+ "summary": "Opening the Pump trading desk from a link tapped inside X/Twitter (or a similar embedded mobile browser) showed a blank page. Those in-app browsers block local storage entirely, and the dashboard read its saved settings the instant it loaded — so the page crashed before it could draw anything. It now detects a blocked store and falls back to sensible defaults in memory, so the desk loads everywhere; your saved config still persists normally in a regular browser. No action needed.",
+ "link": "/pump-dashboard",
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-06-25",
+ "type": "update",
+ "title": "Stability sweep: live page, dashboards, and the galaxy feed never hard-fail",
+ "summary": "A second pass on the day's production logs, this time on resilience. The $THREE Live page crashed for visitors running privacy or anti-popup browser extensions — those tools strip the on-screen stats overlays, and a missing panel was taking the whole 3D scene down with it; the visualization now keeps rendering no matter what the page chrome looks like. Opening a dashboard could occasionally throw an error instead of loading when the sign-in check hit a momentary hiccup; it now retries cleanly through the login flow. The live Galaxy money-feed and the $THREE holder leaderboard used to return an error page when a database query ran long under load — they now serve the last good snapshot (or an honestly-empty view) instantly instead. We also stopped a slow cache server, a slow payment partner, or a heavy background job from ever stalling a request to the point of a timeout, and quieted a wave of harmless noise in our error logs so real issues stand out. No action needed.",
+ "link": null,
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-24",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 0b1d890b9..210c5716c 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,22 @@
<category>fix</category>
<description>We pulled a full day of production logs and fixed what was actually failing. The $THREE tier page sometimes flashed a blank screen on a fast or cached load — a startup step ran a moment before it was ready; it now loads reliably every time. Image understanding (the vision service behind Forge upload checks, the fact checker, and gallery alt text) could hang until the request was force-killed with no answer; it now works through its models within a fixed time budget and always returns either a result or a clear error. Behind the scenes, delegation indexing and agent-reputation reads were leaning on public Ethereum RPC nodes that have since gone behind bot-walls or started refusing datacenter traffic, which meant on-chain permissions and ERC-8004 reputation kept failing to resolve; we replaced the entire fallback set with providers verified to answer reliably. We also fixed a crash in the guided feature tour when it launched before a page finished loading, and the fullscreen button in the scene editor on Safari and in-app browsers. No action needed.</description>
</item>
+ <item>
+ <title>Pump dashboard now loads inside X/Twitter's in-app browser</title>
+ <link>https://three.ws/pump-dashboard</link>
+ <guid isPermaLink="false">2026-06-25:Pump dashboard now loads inside X/Twitter's in-app browser</guid>
+ <pubDate>Thu, 25 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Opening the Pump trading desk from a link tapped inside X/Twitter (or a similar embedded mobile browser) showed a blank page. Those in-app browsers block local storage entirely, and the dashboard read its saved settings the instant it loaded — so the page crashed before it could draw anything. It now detects a blocked store and falls back to sensible defaults in memory, so the desk loads everywhere; your saved config still persists normally in a regular browser. No action needed.</description>
+ </item>
+ <item>
+ <title>Stability sweep: live page, dashboards, and the galaxy feed never hard-fail</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-25:Stability sweep: live page, dashboards, and the galaxy feed never hard-fail</guid>
+ <pubDate>Thu, 25 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>A second pass on the day's production logs, this time on resilience. The $THREE Live page crashed for visitors running privacy or anti-popup browser extensions — those tools strip the on-screen stats overlays, and a missing panel was taking the whole 3D scene down with it; the visualization now keeps rendering no matter what the page chrome looks like. Opening a dashboard could occasionally throw an error instead of loading when the sign-in check hit a momentary hiccup; it now retries cleanly through the login flow. The live Galaxy money-feed and the $THREE holder leaderboard used to return an error page when a database query ran long under load — they now serve the last good snapshot (or an honestly-empty view) instantly instead. We also stopped a slow cache server, a slow payment partner, or a heavy background job from ever stalling a request to the point of a timeout, and quieted a wave of harmless noise in our error logs so real issues stand out. No action needed.</description>
+ </item>
<item>
<title>Agora — the Commons</title>
<link>https://three.ws/agora</link>
diff --git a/public/features.json b/public/features.json
index d16fc21cc..b9a46f307 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-25T08:09:09.821Z",
+ "generated_at": "2026-06-25T21:00:11.789Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/game/arena/arena-venue.js b/src/game/arena/arena-venue.js
new file mode 100644
index 000000000..1088aaa07
--- /dev/null
+++ b/src/game/arena/arena-venue.js
@@ -0,0 +1,265 @@
+// Pure helpers for resolving named empties inside the authored Omniology
+// Arena venue GLB. Modeled on src/club-venue.js so the two venues share one
+// proven contract: the GLB is the single source of truth for where things
+// mount, the runtime reads named empties (never analytical fallbacks), and a
+// missing anchor is a loud, named authoring error — not a silent shrug.
+//
+// Lifted out of the bootstrap so it can be unit-tested without booting a
+// WebGLRenderer or the DOM (see tests/arena-venue.test.js). The runtime
+// imports every symbol from here.
+//
+// Names use underscores rather than dots because three.js's GLTFLoader runs
+// `PropertyBinding.sanitizeNodeName` on every loaded node and strips the
+// characters `[ ] . : /`. A node authored as `screen.01` in Blender would
+// arrive at runtime as `screen01` and fail to resolve. Author every empty
+// with underscores; the build script in scripts/build-arena-venue.mjs mirrors
+// this convention.
+
+import { Vector3, Quaternion, Euler } from 'three';
+
+/** How many contest-wall screens the venue authors (screen_01..screen_03). */
+export const ARENA_SCREEN_SLOTS = 3;
+
+/** How many rim lights the lighting rig authors (light_rim_01..light_rim_03). */
+export const ARENA_RIM_LIGHTS = 3;
+
+/**
+ * Default screen width (metres) used when an artist leaves a screen empty at
+ * unit scale. Authors size a screen by scaling its empty on X; the runtime
+ * reads that world scale as the panel width so prompts 03/04 mount a screen
+ * that fills the authored wall. Anything at (or below) unit scale is treated
+ * as "unset" and falls back to this.
+ */
+export const DEFAULT_SCREEN_WIDTH_M = 6;
+
+/** How far ahead of the intro camera its lookAt target sits when unauthored. */
+const DEFAULT_CAMERA_FOCAL_M = 7;
+
+/**
+ * Named empties the venue GLB MUST expose. Missing any of these is a
+ * load-time error (see collectArenaEmpties). Grouped by role:
+ *
+ * - spawn_01 local player drop-in (position + facing)
+ * - screen_01..03 the three contest walls (prompts 03/04 mount screens)
+ * - desk_01 the entry desk (prompt 04 mounts the interactable)
+ * - light_key the single shadow-casting key light
+ * - light_fill a soft, cheap fill light (no shadows)
+ * - light_rim_01..03 cheap accent rims around the room
+ * - camera_intro the cinematic intro camera pose (position + aim)
+ *
+ * The per-role suffixes are zero-padded two-digit strings so the venue can be
+ * re-authored (re-order screens, add/remove a rim) by changing the slot
+ * constants above + this list together, without renaming unrelated empties.
+ */
+export const ARENA_REQUIRED_EMPTIES = [
+ 'spawn_01',
+ ...Array.from({ length: ARENA_SCREEN_SLOTS }, (_, i) => `screen_${pad(i + 1)}`),
+ 'desk_01',
+ 'light_key',
+ 'light_fill',
+ ...Array.from({ length: ARENA_RIM_LIGHTS }, (_, i) => `light_rim_${pad(i + 1)}`),
+ 'camera_intro',
+];
+
+function pad(n) {
+ return String(n).padStart(2, '0');
+}
+
+/**
+ * Yaw (rotation about world Y, radians) of a node, extracted from its world
+ * quaternion. Uses 'YXZ' order so the Y component is the heading even when the
+ * node also carries pitch/roll. Matches how /play and /club read facing.
+ *
+ * @param {import('three').Object3D} node
+ * @returns {number}
+ */
+function worldYaw(node) {
+ const q = node.getWorldQuaternion(new Quaternion());
+ return new Euler().setFromQuaternion(q, 'YXZ').y;
+}
+
+/**
+ * The node's forward direction in world space (local -Z, the glTF/three.js
+ * "look" axis), normalized. Lets the intro camera aim by rotating its empty in
+ * Blender rather than hardcoding a target.
+ *
+ * @param {import('three').Object3D} node
+ * @returns {Vector3}
+ */
+function worldForward(node) {
+ const q = node.getWorldQuaternion(new Quaternion());
+ return new Vector3(0, 0, -1).applyQuaternion(q).normalize();
+}
+
+/**
+ * Walk the venue scene graph and return every required named empty as a Map
+ * keyed by name. Throws with the missing-empty list if anything from
+ * `required` is absent — the contract is explicit that we surface the error
+ * rather than silently falling back to analytical positions.
+ *
+ * @param {import('three').Object3D} root
+ * @param {string[]} [required] — defaults to ARENA_REQUIRED_EMPTIES.
+ * @returns {Map<string, import('three').Object3D>}
+ */
+export function collectArenaEmpties(root, required = ARENA_REQUIRED_EMPTIES) {
+ if (!root || typeof root.traverse !== 'function') {
+ throw new Error('collectArenaEmpties: expected an Object3D with .traverse()');
+ }
+ const requiredSet = new Set(required);
+ const found = new Map();
+ root.traverse((n) => {
+ if (n && typeof n.name === 'string' && requiredSet.has(n.name)) {
+ found.set(n.name, n);
+ }
+ });
+ const missing = required.filter((name) => !found.has(name));
+ if (missing.length) {
+ throw new Error(
+ `Arena venue GLB is missing required named empties: ${missing.join(', ')}. ` +
+ 'Author them (underscore names) in scripts/build-arena-venue.mjs or your ' +
+ '.blend and re-export — the runtime has no fallback.',
+ );
+ }
+ return found;
+}
+
+/**
+ * Resolve the typed anchor object the bootstrap binds the venue to. Every
+ * field is read from the GLB world transforms so moving/rotating/scaling an
+ * empty in the build script moves the runtime feature with it.
+ *
+ * Light color / intensity / distance / shadow are authored as glTF node
+ * `extras` (exposed by GLTFLoader as `node.userData`); each falls back to a
+ * sensible per-role default so a hand-placed empty still lights the room.
+ *
+ * @param {Map<string, import('three').Object3D>} empties
+ * @returns {{
+ * spawn: { pos: Vector3, yaw: number },
+ * screens: Array<{ pos: Vector3, yaw: number, width: number, node: import('three').Object3D }>,
+ * desk: { pos: Vector3, yaw: number, node: import('three').Object3D },
+ * lights: Array<{ name: string, kind: 'key'|'fill'|'rim', pos: Vector3, color: number, intensity: number, distance: number, castShadow: boolean }>,
+ * camera_intro: { pos: Vector3, lookAt: Vector3 },
+ * }}
+ */
+export function resolveArenaAnchors(empties) {
+ const get = (name) => {
+ const node = empties.get(name);
+ if (!node) {
+ throw new Error(`resolveArenaAnchors: anchor "${name}" was not collected first`);
+ }
+ return node;
+ };
+
+ const spawnNode = get('spawn_01');
+ const spawn = {
+ pos: spawnNode.getWorldPosition(new Vector3()),
+ yaw: worldYaw(spawnNode),
+ };
+
+ const screens = [];
+ for (let i = 0; i < ARENA_SCREEN_SLOTS; i += 1) {
+ const node = get(`screen_${pad(i + 1)}`);
+ const scaleX = node.getWorldScale(new Vector3()).x;
+ screens.push({
+ pos: node.getWorldPosition(new Vector3()),
+ yaw: worldYaw(node),
+ width: scaleX > 1.001 ? scaleX : DEFAULT_SCREEN_WIDTH_M,
+ node,
+ });
+ }
+
+ const deskNode = get('desk_01');
+ const desk = {
+ pos: deskNode.getWorldPosition(new Vector3()),
+ yaw: worldYaw(deskNode),
+ node: deskNode,
+ };
+
+ const lights = [];
+ const lightDefaults = {
+ key: { color: 0xfff1e0, intensity: 3.2, distance: 0, castShadow: true },
+ fill: { color: 0x8fb4ff, intensity: 1.1, distance: 0, castShadow: false },
+ rim: { color: 0x35e0ff, intensity: 2.4, distance: 26, castShadow: false },
+ };
+ const lightNames = ['light_key', 'light_fill', ...Array.from({ length: ARENA_RIM_LIGHTS }, (_, i) => `light_rim_${pad(i + 1)}`)];
+ for (const name of lightNames) {
+ const node = get(name);
+ const kind = name.includes('key') ? 'key' : name.includes('fill') ? 'fill' : 'rim';
+ const def = lightDefaults[kind];
+ const extras = node.userData || {};
+ lights.push({
+ name,
+ kind,
+ pos: node.getWorldPosition(new Vector3()),
+ color: parseColor(extras.color, def.color),
+ intensity: numberOr(extras.intensity, def.intensity),
+ distance: numberOr(extras.distance, def.distance),
+ castShadow: extras.castShadow != null ? !!extras.castShadow : def.castShadow,
+ });
+ }
+
+ const camNode = get('camera_intro');
+ const camPos = camNode.getWorldPosition(new Vector3());
+ const focal = numberOr(camNode.userData?.focal, DEFAULT_CAMERA_FOCAL_M);
+ const lookAt = camPos.clone().add(worldForward(camNode).multiplyScalar(focal));
+ const camera_intro = { pos: camPos, lookAt };
+
+ return { spawn, screens, desk, lights, camera_intro };
+}
+
+/**
+ * Axis-aligned walkable footprint for the venue, derived from the screen,
+ * desk, and spawn anchors so the player clamp follows the authored room. A
+ * margin keeps the avatar off the walls. Returned as half-extents on X/Z
+ * around a centre, mirroring /play's square WORLD_BOUND clamp shape.
+ *
+ * @param {ReturnType<typeof resolveArenaAnchors>} anchors
+ * @param {number} [margin] — metres to inset from the outermost anchors.
+ * @returns {{ center: { x: number, z: number }, halfX: number, halfZ: number,
+ * clamp: (x: number, z: number) => { x: number, z: number } }}
+ */
+export function arenaBounds(anchors, margin = 1.4) {
+ const pts = [
+ anchors.spawn.pos,
+ anchors.desk.pos,
+ ...anchors.screens.map((s) => s.pos),
+ ];
+ let minX = Infinity;
+ let maxX = -Infinity;
+ let minZ = Infinity;
+ let maxZ = -Infinity;
+ for (const p of pts) {
+ minX = Math.min(minX, p.x);
+ maxX = Math.max(maxX, p.x);
+ minZ = Math.min(minZ, p.z);
+ maxZ = Math.max(maxZ, p.z);
+ }
+ // Pull the walls in by `margin` from the anchors that sit ON the walls
+ // (screens, desk), so the player floor area is the interior.
+ const center = { x: (minX + maxX) / 2, z: (minZ + maxZ) / 2 };
+ const halfX = Math.max(1, (maxX - minX) / 2 - margin);
+ const halfZ = Math.max(1, (maxZ - minZ) / 2 - margin);
+ const clamp = (x, z) => ({
+ x: Math.max(center.x - halfX, Math.min(center.x + halfX, x)),
+ z: Math.max(center.z - halfZ, Math.min(center.z + halfZ, z)),
+ });
+ return { center, halfX, halfZ, clamp };
+}
+
+function numberOr(value, fallback) {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+/**
+ * Accept a color as a hex number (0xrrggbb), a '#rrggbb' string, or fall back.
+ * Kept tiny so the module has no THREE.Color dependency for parsing extras.
+ */
+function parseColor(value, fallback) {
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ if (typeof value === 'string') {
+ const hex = value.trim().replace(/^#/, '');
+ if (/^[0-9a-fA-F]{6}$/.test(hex)) return parseInt(hex, 16);
+ }
+ return fallback;
+}
diff --git a/src/game/arena/contest-screen.js b/src/game/arena/contest-screen.js
new file mode 100644
index 000000000..85be3b5d1
--- /dev/null
+++ b/src/game/arena/contest-screen.js
@@ -0,0 +1,612 @@
+// Contest Screen — a live in-world jumbotron for an Omniology contest.
+//
+// The Arena's walls carry physical LED screens that show Omniology's live
+// contests: the current round with its ~88-second countdown, a leaderboard, the
+// recent winners, and a live ticker of entries landing in real time. Each screen
+// is an HTML canvas wrapped in a CanvasTexture on an unlit plane — a real object
+// in the 3D world you can walk up to and click, not a DOM overlay. The canvas
+// repaints in place (~10fps) as the countdown ticks and the feed updates.
+//
+// This generalizes src/game/chart-screen.js: same CanvasTexture-on-PlaneGeometry
+// rig, same poll-driven state machine, same designed loading / live / empty /
+// error states — adapted to contests. One component handles all three wall roles
+// (now-playing, leaderboard, winners) via the `role` option; the dominant panel
+// changes per role but every screen shares the header, LIVE badge, countdown, and
+// ticker. Data is real, normalized by omniology-adapter.js — no mocks (CLAUDE.md).
+//
+// Contract: docs/omniology-arena/CONTRACTS.md §2.2.
+
+import {
+ Group, Mesh, MeshBasicMaterial, MeshStandardMaterial,
+ PlaneGeometry, BoxGeometry,
+ CanvasTexture, SRGBColorSpace, DoubleSide,
+} from 'three';
+
+const CW = 1280, CH = 720; // 16:9 canvas backing the screen
+const REDRAW_MS = 100; // ~10fps redraw — smooth ticker, cheap on the GPU
+const TICKER_CAP = 24; // recent entries kept for the scrolling ticker
+const SWEEP_S = 1.4; // "NEW ROUND" sweep duration when the round flips
+
+// Restrained, premium palette — light-on-near-black to match the world UI, with a
+// single directional accent that shifts as the countdown runs low.
+const COL = {
+ bg0: '#08080b', bg1: '#101015',
+ panel: 'rgba(255,255,255,0.04)',
+ stroke: 'rgba(255,255,255,0.10)',
+ grid: 'rgba(255,255,255,0.06)',
+ text: '#f5f5f6', dim: '#9a9aa2', faint: '#5a5a62',
+ live: '#5fd08a', warn: '#f2c14e', danger: '#e06c75',
+ accent: '#7cc4ff',
+};
+
+// ── pure helpers (exported for unit tests — no canvas/DOM needed) ───────────────
+
+/**
+ * Format a millisecond duration as a contest clock: M:SS, floored at 0:00.
+ * @param {number|null} ms
+ * @returns {string}
+ */
+export function formatCountdown(ms) {
+ if (ms == null || !Number.isFinite(ms)) return '—:—';
+ const total = Math.max(0, Math.floor(ms / 1000));
+ const m = Math.floor(total / 60);
+ const s = total % 60;
+ return `${m}:${String(s).padStart(2, '0')}`;
+}
+
+/**
+ * Countdown accent: calm → amber → red as the round closes. Thresholds are tuned
+ * to the ~88s cadence (last 18s warn, last 8s danger).
+ * @param {number|null} remainingMs
+ * @returns {string}
+ */
+export function countdownColor(remainingMs) {
+ if (remainingMs == null || !Number.isFinite(remainingMs)) return COL.dim;
+ if (remainingMs <= 8000) return COL.danger;
+ if (remainingMs <= 18000) return COL.warn;
+ return COL.live;
+}
+
+/**
+ * Merge incoming ticker entries (newest-first) ahead of the existing buffer,
+ * deduped by entryId, capped. Optimistic inserts (from the desk) and feed entries
+ * both flow through here so the ticker never double-counts a submission.
+ * @param {Array} existing current buffer (newest-first)
+ * @param {Array} incoming new entries to fold in
+ * @param {number} [cap]
+ * @returns {Array}
+ */
+export function mergeTicker(existing, incoming, cap = TICKER_CAP) {
+ const out = [];
+ const seen = new Set();
+ for (const e of [...incoming, ...existing]) {
+ if (!e) continue;
+ const key = e.entryId || `${e.agent}:${e.submittedMs}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(e);
+ }
+ out.sort((a, b) => (b.submittedMs || 0) - (a.submittedMs || 0));
+ return out.slice(0, cap);
+}
+
+function fmtUsdc(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n <= 0) return '—';
+ if (n >= 1000) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 });
+ return '$' + n.toFixed(n < 10 ? 2 : 1);
+}
+
+function fmtScore(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return '—';
+ return n <= 1 ? n.toFixed(3) : n.toFixed(1);
+}
+
+function relTime(ms, now) {
+ const s = Math.max(0, Math.round((now - ms) / 1000));
+ if (s < 4) return 'now';
+ if (s < 60) return s + 's';
+ const m = Math.round(s / 60);
+ return m < 60 ? m + 'm' : Math.round(m / 60) + 'h';
+}
+
+function ellipsize(ctx, text, maxW) {
+ if (ctx.measureText(text).width <= maxW) return text;
+ let t = text;
+ while (t.length > 1 && ctx.measureText(t + '…').width > maxW) t = t.slice(0, -1);
+ return t + '…';
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ const rr = Math.min(r, w / 2, h / 2);
+ ctx.beginPath();
+ ctx.moveTo(x + rr, y);
+ ctx.arcTo(x + w, y, x + w, y + h, rr);
+ ctx.arcTo(x + w, y + h, x, y + h, rr);
+ ctx.arcTo(x, y + h, x, y, rr);
+ ctx.arcTo(x, y, x + w, y, rr);
+ ctx.closePath();
+}
+
+function monogram(name) {
+ const s = String(name || '?').trim();
+ return (s[0] || '?').toUpperCase();
+}
+
+// ── factory ────────────────────────────────────────────────────────────────────
+
+/**
+ * Build a live contest screen and add it to the scene.
+ * @param {THREE.Scene} scene
+ * @param {{position:[number,number,number]|{x,y,z}, width?:number, rotationY?:number, role?:'now'|'leaderboard'|'winners', frame?:boolean}} opts
+ * @returns {{group, mesh, role, update, applyFeed, pushEntry, setStatus, openExternal, dispose}}
+ */
+export function createContestScreen(scene, opts = {}) {
+ const role = opts.role === 'leaderboard' || opts.role === 'winners' ? opts.role : 'now';
+ const width = opts.width || 12;
+ const height = (width * CH) / CW;
+ const rotationY = opts.rotationY || 0;
+ const pos = toXYZ(opts.position, [0, 0, 0]);
+
+ const group = new Group();
+ group.position.set(pos[0], pos[1], pos[2]);
+ group.rotation.y = rotationY;
+
+ // Optional bezel + posts so a free-standing screen reads as a real rig. When a
+ // venue wall already frames the panel (the common Arena case), pass frame:false
+ // to mount just the lit face flush to the wall.
+ if (opts.frame !== false) {
+ const bezel = new Mesh(
+ new BoxGeometry(width + 0.5, height + 0.5, 0.3),
+ new MeshStandardMaterial({ color: 0x050506, roughness: 0.4, metalness: 0.7 }),
+ );
+ bezel.position.set(0, 0, -0.18);
+ bezel.castShadow = true;
+ group.add(bezel);
+ }
+
+ // Live face: canvas → CanvasTexture → unlit plane (glows like an LED wall).
+ const canvas = document.createElement('canvas');
+ canvas.width = CW; canvas.height = CH;
+ const ctx = canvas.getContext('2d');
+ const tex = new CanvasTexture(canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 4;
+ const panel = new Mesh(
+ new PlaneGeometry(width, height),
+ new MeshBasicMaterial({ map: tex, side: DoubleSide, toneMapped: false }),
+ );
+ panel.userData.contestScreen = true; // raycast tag
+ group.add(panel);
+
+ scene.add(group);
+
+ // ── live state ──────────────────────────────────────────────────────────────
+ let feed = null; // latest NormalizedFeed
+ let status = 'loading'; // loading | live | empty | error | unconfigured
+ let ticker = []; // newest-first entry buffer for the scroll
+ let thumbs = new Map(); // entryId → HTMLImageElement (lazy, CORS-safe)
+ let skewMs = 0; // serverNow - clientNow at last applyFeed (drift)
+ let closesMs = null; // current round close (server clock)
+ let lastRound = null; // for round-flip detection
+ let sweepT = 0; // remaining "NEW ROUND" sweep seconds
+ let t = 0; // elapsed seconds (pulse + ticker scroll)
+ let acc = 0; // redraw accumulator
+ let destroyed = false;
+
+ function correctedNow() { return Date.now() + skewMs; }
+ function remainingMs() { return closesMs == null ? null : closesMs - correctedNow(); }
+
+ // Lazily load a leaderboard thumbnail; the row renders its monogram until the
+ // image lands, and silently keeps the monogram if the load is blocked.
+ function ensureThumb(entryId, url) {
+ if (!url || thumbs.has(entryId)) return;
+ const im = new Image();
+ im.crossOrigin = 'anonymous';
+ im.referrerPolicy = 'no-referrer';
+ im.onload = () => { thumbs.set(entryId, im); };
+ im.onerror = () => { thumbs.set(entryId, null); };
+ thumbs.set(entryId, null); // reserve the slot so we don't re-request
+ im.src = url;
+ }
+
+ // ── public surface ────────────────────────────────────────────────────────
+ function applyFeed(next) {
+ if (!next) return;
+ feed = next;
+ skewMs = Number(next.serverNowMs) - Date.now();
+
+ if (next.ok === false) {
+ status = next.reason === 'unconfigured' ? 'unconfigured' : 'error';
+ closesMs = null;
+ return;
+ }
+
+ const cur = next.current;
+ closesMs = cur ? cur.closesMs : null;
+
+ // Round flip → trigger the "NEW ROUND" sweep (skip the very first feed).
+ if (cur && cur.round != null && lastRound != null && cur.round !== lastRound) {
+ sweepT = SWEEP_S;
+ ticker = []; // a fresh round starts its ticker clean
+ }
+ if (cur && cur.round != null) lastRound = cur.round;
+
+ // Fold the feed's recent entries into the ticker (dedupe vs optimistic).
+ ticker = mergeTicker(ticker, next.recentEntries || [], TICKER_CAP);
+ for (const e of next.leaderboard || []) ensureThumb(e.entryId, e.thumbUrl);
+
+ status = cur ? 'live' : 'empty';
+ }
+
+ // Optimistic ticker insert, called by the entry desk (prompt 04) the instant a
+ // submission settles — so the submitter sees their entry before the next poll.
+ function pushEntry(entry) {
+ if (!entry) return;
+ const e = {
+ entryId: entry.entryId || `local:${Math.round(correctedNow())}`,
+ agent: entry.agent || 'you',
+ submittedMs: entry.submittedMs || correctedNow(),
+ optimistic: true,
+ };
+ ticker = mergeTicker(ticker, [e], TICKER_CAP);
+ }
+
+ function setStatus(s) {
+ if (['loading', 'live', 'empty', 'error', 'unconfigured'].includes(s)) status = s;
+ }
+
+ // ── rendering ───────────────────────────────────────────────────────────────
+ function paintBackground() {
+ const bg = ctx.createLinearGradient(0, 0, 0, CH);
+ bg.addColorStop(0, COL.bg1); bg.addColorStop(1, COL.bg0);
+ ctx.fillStyle = bg; ctx.fillRect(0, 0, CW, CH);
+ // subtle vignette frame
+ ctx.strokeStyle = COL.stroke; ctx.lineWidth = 2;
+ ctx.strokeRect(10, 10, CW - 20, CH - 20);
+ }
+
+ function paintHeader() {
+ const padX = 44;
+ const cur = feed?.current;
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+
+ // Role label + contest title.
+ const roleLabel = role === 'leaderboard' ? 'LEADERBOARD' : role === 'winners' ? 'PAST WINNERS' : 'NOW PLAYING';
+ ctx.fillStyle = COL.accent;
+ ctx.font = '800 18px Inter, system-ui, sans-serif';
+ ctx.fillText(roleLabel, padX, 44);
+
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 34px Inter, system-ui, sans-serif';
+ const title = cur ? cur.title : 'Omniology Arena';
+ ctx.fillText(ellipsize(ctx, title.toUpperCase(), 720), padX, 80);
+
+ if (cur && cur.round != null) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '600 20px Inter, system-ui, sans-serif';
+ ctx.fillText(`ROUND ${cur.round}`, padX, 108);
+ }
+
+ // LIVE / status badge (top-right), pulsing dot.
+ const pulse = 0.5 + 0.5 * Math.sin(t * 4);
+ const label = status === 'live' ? 'LIVE'
+ : status === 'error' ? 'RECONNECTING'
+ : status === 'unconfigured' ? 'CONNECTING'
+ : status === 'empty' ? 'STANDBY'
+ : '···';
+ ctx.font = '700 18px Inter, system-ui, sans-serif';
+ const badgeW = ctx.measureText(label).width + 64;
+ const bx = CW - padX - badgeW, by = 26, bh = 40;
+ roundRect(ctx, bx, by, badgeW, bh, 20);
+ ctx.fillStyle = COL.panel; ctx.fill();
+ ctx.strokeStyle = COL.stroke; ctx.lineWidth = 1; ctx.stroke();
+ ctx.beginPath();
+ ctx.arc(bx + 26, by + bh / 2, 6, 0, Math.PI * 2);
+ const dot = status === 'live' ? `rgba(95,208,138,${pulse})`
+ : status === 'error' ? COL.danger
+ : status === 'unconfigured' ? `rgba(124,196,255,${pulse})`
+ : COL.faint;
+ ctx.fillStyle = dot; ctx.fill();
+ ctx.fillStyle = COL.text;
+ ctx.fillText(label, bx + 44, by + 26);
+ }
+
+ // Big countdown block, shared by the now-playing role and used compact in headers.
+ function paintCountdown(x, y, scale = 1) {
+ const rem = remainingMs();
+ const col = countdownColor(rem);
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ ctx.fillStyle = COL.faint;
+ ctx.font = `700 ${Math.round(16 * scale)}px Inter, system-ui, sans-serif`;
+ ctx.fillText('CLOSES IN', x, y - Math.round(70 * scale));
+ ctx.fillStyle = col;
+ ctx.font = `800 ${Math.round(120 * scale)}px "SF Mono", ui-monospace, Menlo, monospace`;
+ const txt = formatCountdown(rem);
+ ctx.fillText(txt, x, y);
+ // thin progress arc-ish bar under the clock showing the ~88s drain
+ if (closesMs != null && feed?.current?.opensMs != null) {
+ const dur = Math.max(1, closesMs - feed.current.opensMs);
+ const frac = Math.max(0, Math.min(1, (rem ?? 0) / dur));
+ const w = ctx.measureText(txt).width;
+ const barY = y + Math.round(18 * scale), barH = Math.round(8 * scale);
+ roundRect(ctx, x, barY, w, barH, barH / 2); ctx.fillStyle = COL.grid; ctx.fill();
+ roundRect(ctx, x, barY, w * frac, barH, barH / 2); ctx.fillStyle = col; ctx.fill();
+ }
+ }
+
+ function paintStatChip(x, y, w, label, value, accent) {
+ roundRect(ctx, x, y, w, 92, 14);
+ ctx.fillStyle = COL.panel; ctx.fill();
+ ctx.strokeStyle = COL.stroke; ctx.lineWidth = 1; ctx.stroke();
+ ctx.fillStyle = COL.faint; ctx.font = '700 15px Inter, system-ui, sans-serif';
+ ctx.fillText(label, x + 18, y + 30);
+ ctx.fillStyle = accent || COL.text; ctx.font = '800 40px Inter, system-ui, sans-serif';
+ ctx.fillText(value, x + 18, y + 74);
+ }
+
+ function paintLeaderboardRows(x, y, w, rows, maxRows, compact) {
+ const rh = compact ? 52 : 64;
+ if (!rows.length) {
+ ctx.fillStyle = COL.dim; ctx.font = '600 22px Inter, system-ui, sans-serif';
+ ctx.fillText('No scored entries yet this round.', x, y + 40);
+ return;
+ }
+ rows.slice(0, maxRows).forEach((e, i) => {
+ const ry = y + i * rh;
+ // rank pill
+ ctx.fillStyle = i === 0 ? COL.warn : i === 1 ? COL.dim : i === 2 ? '#c98a5a' : COL.faint;
+ ctx.font = `800 ${compact ? 22 : 26}px Inter, system-ui, sans-serif`;
+ ctx.textAlign = 'right';
+ ctx.fillText(String(e.rank ?? i + 1), x + 34, ry + (compact ? 30 : 36));
+ ctx.textAlign = 'left';
+ // thumb / monogram
+ const av = compact ? 30 : 40, ax = x + 50, ay = ry + (compact ? 4 : 6);
+ ctx.save();
+ roundRect(ctx, ax, ay, av, av, 8); ctx.fillStyle = '#1a1a20'; ctx.fill(); ctx.clip();
+ const im = thumbs.get(e.entryId);
+ if (im) ctx.drawImage(im, ax, ay, av, av);
+ else {
+ ctx.fillStyle = COL.dim; ctx.font = `700 ${compact ? 16 : 20}px Inter, system-ui, sans-serif`;
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
+ ctx.fillText(monogram(e.agent), ax + av / 2, ay + av / 2);
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ }
+ ctx.restore();
+ // agent + score
+ ctx.fillStyle = COL.text; ctx.font = `700 ${compact ? 22 : 26}px Inter, system-ui, sans-serif`;
+ const nameX = ax + av + 16;
+ ctx.fillText(ellipsize(ctx, e.agent, w - (nameX - x) - 120), nameX, ry + (compact ? 30 : 38));
+ ctx.fillStyle = COL.accent; ctx.font = `800 ${compact ? 22 : 26}px "SF Mono", ui-monospace, monospace`;
+ ctx.textAlign = 'right';
+ ctx.fillText(fmtScore(e.score), x + w, ry + (compact ? 30 : 38));
+ ctx.textAlign = 'left';
+ if (i < Math.min(rows.length, maxRows) - 1) {
+ ctx.strokeStyle = COL.grid; ctx.lineWidth = 1;
+ ctx.beginPath(); ctx.moveTo(x, ry + rh - 6); ctx.lineTo(x + w, ry + rh - 6); ctx.stroke();
+ }
+ });
+ }
+
+ function paintWinnersRows(x, y, w) {
+ const rows = feed?.recentWinners || [];
+ if (!rows.length) {
+ ctx.fillStyle = COL.dim; ctx.font = '600 22px Inter, system-ui, sans-serif';
+ ctx.fillText('Winners appear here as rounds settle.', x, y + 40);
+ return;
+ }
+ const rh = 70;
+ rows.slice(0, 6).forEach((wn, i) => {
+ const ry = y + i * rh;
+ ctx.fillStyle = COL.faint; ctx.font = '700 16px Inter, system-ui, sans-serif';
+ ctx.fillText(`ROUND ${wn.round}`, x, ry + 24);
+ ctx.fillStyle = COL.text; ctx.font = '700 28px Inter, system-ui, sans-serif';
+ ctx.fillText(ellipsize(ctx, wn.agent, w - 220), x, ry + 54);
+ ctx.fillStyle = COL.live; ctx.font = '800 28px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText(fmtUsdc(wn.prizeUsdc), x + w, ry + 44);
+ ctx.textAlign = 'left';
+ ctx.strokeStyle = COL.grid; ctx.lineWidth = 1;
+ ctx.beginPath(); ctx.moveTo(x, ry + rh - 8); ctx.lineTo(x + w, ry + rh - 8); ctx.stroke();
+ });
+ }
+
+ function paintTicker() {
+ const tickY = CH - 32, bandTop = CH - 64;
+ ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(0, bandTop, CW, 64);
+ ctx.strokeStyle = COL.grid; ctx.lineWidth = 1;
+ ctx.beginPath(); ctx.moveTo(0, bandTop); ctx.lineTo(CW, bandTop); ctx.stroke();
+ // "ENTRIES" tag
+ const padX = 44;
+ ctx.fillStyle = COL.accent; ctx.font = '800 16px Inter, system-ui, sans-serif';
+ ctx.fillText('ENTRIES', padX, tickY + 6);
+ const startX = padX + 96;
+ ctx.save();
+ ctx.beginPath(); ctx.rect(startX, bandTop, CW - startX - 20, 64); ctx.clip();
+ const now = correctedNow();
+ if (ticker.length) {
+ ctx.font = '700 20px Inter, system-ui, sans-serif';
+ const seg = ticker.map((e) => ({
+ e,
+ txt: `${e.agent} · ${relTime(e.submittedMs, now)}`,
+ }));
+ const gap = 56;
+ const widths = seg.map((s) => ctx.measureText(s.txt).width + gap + (s.e.optimistic ? 20 : 0));
+ const total = widths.reduce((a, b) => a + b, 0) || 1;
+ const scroll = (t * 70) % total;
+ let x = startX - scroll;
+ for (let pass = 0; pass < 2; pass++) {
+ let xx = x + pass * total;
+ seg.forEach((s, i) => {
+ if (s.e.optimistic) {
+ ctx.fillStyle = COL.live;
+ ctx.beginPath(); ctx.arc(xx + 6, tickY - 6, 5, 0, Math.PI * 2); ctx.fill();
+ xx += 20;
+ }
+ const dotX = xx;
+ ctx.fillStyle = s.e.optimistic ? COL.live : COL.text;
+ ctx.fillText(s.e.agent, dotX, tickY);
+ const lead = ctx.measureText(s.e.agent).width;
+ ctx.fillStyle = COL.dim;
+ ctx.fillText(` · ${relTime(s.e.submittedMs, now)}`, dotX + lead, tickY);
+ xx += widths[i] - (s.e.optimistic ? 20 : 0);
+ });
+ }
+ } else {
+ ctx.fillStyle = COL.faint; ctx.font = '600 18px Inter, system-ui, sans-serif';
+ ctx.fillText('Awaiting entries…', startX, tickY);
+ }
+ ctx.restore();
+ }
+
+ // Non-live states: skeleton (loading) and centered, calm messaging otherwise.
+ function paintState() {
+ const cx = CW / 2, midY = 300;
+ if (status === 'loading') {
+ // skeleton shimmer bars
+ const sh = 0.04 + 0.03 * (0.5 + 0.5 * Math.sin(t * 3));
+ ctx.fillStyle = `rgba(255,255,255,${sh})`;
+ for (let i = 0; i < 4; i++) {
+ roundRect(ctx, 44, 150 + i * 70, (CW - 88) * (i === 0 ? 0.5 : 0.9), 44, 10); ctx.fill();
+ }
+ ctx.fillStyle = COL.dim; ctx.font = '600 24px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('Loading live contest…', cx, CH - 120);
+ ctx.textAlign = 'left';
+ return;
+ }
+
+ const dots = '.'.repeat(1 + (Math.floor(t * 2) % 3));
+ let head, sub;
+ if (status === 'unconfigured') {
+ head = 'Connecting to Omniology';
+ sub = 'Live contests will appear here once the feed is configured.';
+ } else if (status === 'error') {
+ head = `Reconnecting to Omniology${dots}`;
+ sub = 'The contest feed is briefly unreachable. Retrying automatically.';
+ } else {
+ // empty / between rounds
+ const next = feed?.next;
+ const nextRem = next?.opensMs != null ? next.opensMs - correctedNow() : null;
+ head = 'Between rounds';
+ sub = nextRem != null && nextRem > 0
+ ? `Next round opens in ${formatCountdown(nextRem)}`
+ : 'The next contest is about to begin.';
+ }
+
+ // pulsing ring as a calm "alive" signal
+ const pulse = 0.5 + 0.5 * Math.sin(t * 3);
+ ctx.beginPath();
+ ctx.arc(cx, midY - 30, 26 + pulse * 4, 0, Math.PI * 2);
+ ctx.strokeStyle = status === 'error' ? `rgba(224,108,117,${0.3 + pulse * 0.4})`
+ : `rgba(124,196,255,${0.3 + pulse * 0.4})`;
+ ctx.lineWidth = 3; ctx.stroke();
+
+ ctx.textAlign = 'center';
+ ctx.fillStyle = COL.text; ctx.font = '800 40px Inter, system-ui, sans-serif';
+ ctx.fillText(head, cx, midY + 50);
+ ctx.fillStyle = COL.dim; ctx.font = '500 24px Inter, system-ui, sans-serif';
+ ctx.fillText(sub, cx, midY + 100);
+ ctx.textAlign = 'left';
+ }
+
+ function paintSweep() {
+ if (sweepT <= 0) return;
+ const p = 1 - sweepT / SWEEP_S; // 0 → 1 across the sweep
+ const x = -CW + p * 2 * CW; // band slides left→right
+ ctx.save();
+ const grad = ctx.createLinearGradient(x, 0, x + CW, 0);
+ grad.addColorStop(0, 'rgba(124,196,255,0)');
+ grad.addColorStop(0.5, 'rgba(124,196,255,0.18)');
+ grad.addColorStop(1, 'rgba(124,196,255,0)');
+ ctx.fillStyle = grad; ctx.fillRect(0, 0, CW, CH);
+ const a = Math.sin(p * Math.PI); // fade in/out
+ ctx.globalAlpha = a;
+ ctx.fillStyle = COL.accent; ctx.font = '900 64px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
+ ctx.fillText('NEW ROUND', CW / 2, CH / 2);
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ ctx.restore();
+ }
+
+ function draw() {
+ paintBackground();
+ paintHeader();
+
+ const live = status === 'live' || (status === 'empty' && role === 'winners' && (feed?.recentWinners?.length));
+ if (!live && status !== 'live') {
+ // winners panel still shows its list during 'empty' (history persists);
+ // every other role shows the designed state screen.
+ if (!(role === 'winners' && feed?.recentWinners?.length)) {
+ paintState();
+ paintTicker();
+ paintSweep();
+ tex.needsUpdate = true;
+ return;
+ }
+ }
+
+ const padX = 44, bodyTop = 150;
+ if (role === 'leaderboard') {
+ paintLeaderboardRows(padX, bodyTop, CW - padX * 2, feed?.leaderboard || [], 7, false);
+ } else if (role === 'winners') {
+ paintWinnersRows(padX, bodyTop, CW - padX * 2);
+ } else {
+ // now-playing: countdown + stat chips on the left, top-3 board on the right
+ paintCountdown(padX, 300, 1);
+ const chipW = (560 - 20) / 2;
+ paintStatChip(padX, 360, chipW, 'PRIZE POOL', fmtUsdc(feed?.current?.prizeUsdc), COL.live);
+ paintStatChip(padX + chipW + 20, 360, chipW, 'ENTRIES', String(feed?.current?.entriesCount ?? 0), COL.text);
+ // right column: live top 3
+ const rx = 700, rw = CW - rx - padX;
+ ctx.fillStyle = COL.faint; ctx.font = '700 16px Inter, system-ui, sans-serif';
+ ctx.fillText('TOP ENTRIES', rx, bodyTop - 12);
+ paintLeaderboardRows(rx, bodyTop + 6, rw, feed?.leaderboard || [], 4, true);
+ }
+
+ paintTicker();
+ paintSweep();
+ tex.needsUpdate = true;
+ }
+
+ // first paint
+ draw();
+
+ return {
+ group,
+ mesh: panel,
+ role,
+ update(dt) {
+ if (destroyed) return;
+ t += dt;
+ if (sweepT > 0) sweepT = Math.max(0, sweepT - dt);
+ acc += dt;
+ if (acc >= REDRAW_MS / 1000) { acc = 0; draw(); }
+ },
+ applyFeed,
+ pushEntry,
+ setStatus,
+ openExternal() {
+ window.open('https://omniology.ai', '_blank', 'noopener,noreferrer');
+ },
+ dispose() {
+ destroyed = true;
+ thumbs.clear();
+ scene.remove(group);
+ group.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) { m?.map?.dispose?.(); m?.dispose?.(); }
+ }
+ });
+ },
+ };
+}
+
+function toXYZ(p, fallback) {
+ if (Array.isArray(p)) return [p[0] ?? 0, p[1] ?? 0, p[2] ?? 0];
+ if (p && typeof p === 'object') return [p.x ?? 0, p.y ?? 0, p.z ?? 0];
+ return fallback;
+}
diff --git a/src/game/arena/omniology-adapter.js b/src/game/arena/omniology-adapter.js
new file mode 100644
index 000000000..482c19a77
--- /dev/null
+++ b/src/game/arena/omniology-adapter.js
@@ -0,0 +1,212 @@
+// Omniology adapter — the ONLY module that knows Omniology's wire shapes.
+//
+// Omniology (omniology.ai) is an external collaborator running AI-agent contests
+// every ~88 seconds with USDC-on-Solana prizes. Their service exposes a single
+// polled feed for the in-world screens and an x402-priced submit endpoint for the
+// entry desk. This adapter is the boundary: it reads the configured base URL,
+// fetches the raw feed, and normalizes it into the camelCase / millisecond shape
+// the rest of the Arena consumes. Everything downstream (contest-screen.js,
+// entry-desk.js) speaks NormalizedFeed only — so swapping the real base URL, or
+// adapting to a wire-shape change, is a one-file edit here.
+//
+// Contract: docs/omniology-arena/CONTRACTS.md §1.1 (feed), §1.2 (submit), §2.1.
+// No mocks, ever (CLAUDE.md): when no base URL is configured, fetchLiveFeed()
+// surfaces an explicit `unconfigured` status — it NEVER fabricates contest data.
+
+// ── config ───────────────────────────────────────────────────────────────────
+
+/**
+ * Resolve Omniology's base URL (no trailing slash) from, in priority order:
+ * 1. window.OMNIOLOGY_BASE — runtime override (tests / embeds)
+ * 2. <meta name="omniology-base"> — baked into the Arena page
+ * 3. VITE_OMNIOLOGY_BASE — build-time env
+ * Returns '' when nothing is configured, which fetchLiveFeed() treats as the
+ * designed "unconfigured" state rather than an error.
+ * @returns {string}
+ */
+export function omniologyBase() {
+ if (typeof window !== 'undefined' && window.OMNIOLOGY_BASE) {
+ return clean(window.OMNIOLOGY_BASE);
+ }
+ if (typeof document !== 'undefined') {
+ const v = document.querySelector('meta[name="omniology-base"]')?.getAttribute('content');
+ if (v && v.trim()) return clean(v);
+ }
+ try {
+ const env = import.meta?.env?.VITE_OMNIOLOGY_BASE;
+ if (env) return clean(String(env));
+ } catch (_) { /* import.meta unavailable outside a bundler (e.g. node tests) */ }
+ return '';
+}
+
+function clean(url) {
+ return String(url).trim().replace(/\/+$/, '');
+}
+
+// ── read: live contest feed ───────────────────────────────────────────────────
+
+/**
+ * GET {base}/v1/contests/live and normalize to NormalizedFeed.
+ *
+ * - Unconfigured (no base URL): resolves to a NormalizedFeed with `ok:false` and
+ * `reason:'unconfigured'` — never fabricated data. The screens render their
+ * "connecting to Omniology" placeholder for this.
+ * - Network / HTTP error: THROWS (the poller catches it and drives the designed,
+ * auto-retrying error state). This matches the CONTRACTS §2.1 boundary.
+ *
+ * @returns {Promise<NormalizedFeed>}
+ */
+export async function fetchLiveFeed() {
+ const base = omniologyBase();
+ if (!base) return unconfiguredFeed();
+
+ const res = await fetch(`${base}/v1/contests/live`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`Omniology feed HTTP ${res.status}`);
+ const data = await res.json();
+ return normalizeFeed(data);
+}
+
+/**
+ * Normalize Omniology's wire feed (snake_case, unix seconds) into the Arena's
+ * internal shape (camelCase, ms). Exported so the adapter's contract is unit
+ * testable without a live endpoint. Tolerant of nulls per CONTRACTS §1.1: an
+ * unknown field becomes null/empty, never invented.
+ * @param {object} data
+ * @returns {NormalizedFeed}
+ */
+export function normalizeFeed(data) {
+ const d = data || {};
+ const serverNowMs = secToMs(d.now_unix) ?? nowMs();
+
+ const c = d.current;
+ const current = c && c.id != null ? {
+ id: str(c.id),
+ title: str(c.title) || 'Live contest',
+ round: num(c.round) ?? 0,
+ opensMs: secToMs(c.opened_unix),
+ closesMs: secToMs(c.closes_unix),
+ entriesCount: num(c.entries_count) ?? 0,
+ prizeUsdc: num(c.prize_usdc) ?? 0,
+ prizeAsset: str(c.prize_asset) || 'USDC',
+ } : null;
+
+ const next = d.next && d.next.opens_unix != null
+ ? { opensMs: secToMs(d.next.opens_unix) }
+ : null;
+
+ const leaderboard = asArray(d.leaderboard).map((e, i) => ({
+ rank: num(e?.rank) ?? i + 1,
+ entryId: str(e?.entry_id),
+ agent: str(e?.agent) || 'anon',
+ score: num(e?.score),
+ thumbUrl: httpsUrl(e?.thumb_url),
+ }));
+
+ const recentEntries = asArray(d.recent_entries).map((e) => ({
+ entryId: str(e?.entry_id),
+ agent: str(e?.agent) || 'anon',
+ submittedMs: secToMs(e?.submitted_unix) ?? serverNowMs,
+ }));
+
+ const recentWinners = asArray(d.recent_winners).map((w) => ({
+ round: num(w?.round) ?? 0,
+ agent: str(w?.agent) || 'anon',
+ prizeUsdc: num(w?.prize_usdc) ?? 0,
+ tx: w?.tx ? str(w.tx) : null,
+ }));
+
+ return {
+ ok: true,
+ reason: null,
+ serverNowMs,
+ current,
+ next,
+ leaderboard,
+ recentEntries,
+ recentWinners,
+ };
+}
+
+function unconfiguredFeed() {
+ return {
+ ok: false,
+ reason: 'unconfigured',
+ serverNowMs: nowMs(),
+ current: null,
+ next: null,
+ leaderboard: [],
+ recentEntries: [],
+ recentWinners: [],
+ };
+}
+
+// ── write: submit entry (consumed by the entry desk, prompt 04) ────────────────
+
+/**
+ * Build the exact request the entry desk hands to `POST /api/x402-pay` for the
+ * external x402 flow (CONTRACTS §1.2 / §2.3). Defined here now so the boundary is
+ * frozen before prompt 04 — keep this signature stable.
+ *
+ * The server-side x402 payer handles the 402 challenge → sign → retry; this only
+ * describes the target request. The paying agentId is attached by the desk, not
+ * here (no wallet/secret ever touches this client module).
+ *
+ * @param {string} contestId
+ * @param {object} entry partner-defined entry payload
+ * @param {string|null} [agent] display name, or null
+ * @returns {{ url:string, method:'POST', body:{ entry:object, agent:string|null } }}
+ */
+export function submitEntryRequest(contestId, entry, agent) {
+ const base = omniologyBase();
+ const id = encodeURIComponent(String(contestId ?? ''));
+ return {
+ url: `${base}/v1/contests/${id}/entries`,
+ method: 'POST',
+ body: { entry: entry ?? {}, agent: agent ?? null },
+ };
+}
+
+// ── coercion helpers (defensive: the feed is external) ─────────────────────────
+
+function nowMs() { return Date.now(); }
+
+function num(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function str(v) {
+ return v == null ? '' : String(v);
+}
+
+function secToMs(v) {
+ const n = num(v);
+ return n == null ? null : Math.round(n * 1000);
+}
+
+function asArray(v) {
+ return Array.isArray(v) ? v : [];
+}
+
+// Only surface CORS-readable HTTPS thumbnails; anything else (http, data:, junk)
+// becomes null so the screen renders its designed monogram fallback instead of a
+// broken-image box.
+function httpsUrl(v) {
+ const s = str(v).trim();
+ return /^https:\/\//i.test(s) ? s : null;
+}
+
+/**
+ * @typedef {object} NormalizedFeed
+ * @property {boolean} ok true on a real feed, false when unconfigured
+ * @property {string|null} reason 'unconfigured' when ok is false, else null
+ * @property {number} serverNowMs server clock (ms) for countdown drift correction
+ * @property {{id:string,title:string,round:number,opensMs:number|null,closesMs:number|null,entriesCount:number,prizeUsdc:number,prizeAsset:string}|null} current
+ * @property {{opensMs:number|null}|null} next
+ * @property {Array<{rank:number,entryId:string,agent:string,score:number|null,thumbUrl:string|null}>} leaderboard
+ * @property {Array<{entryId:string,agent:string,submittedMs:number}>} recentEntries
+ * @property {Array<{round:number,agent:string,prizeUsdc:number,tx:string|null}>} recentWinners
+ */
diff --git a/tests/arena-venue.test.js b/tests/arena-venue.test.js
new file mode 100644
index 000000000..3d70951ef
--- /dev/null
+++ b/tests/arena-venue.test.js
@@ -0,0 +1,200 @@
+// Tests for the named-empty contract between the authored Omniology Arena
+// venue GLB and the runtime. We don't boot the bootstrap here — that pulls in
+// a WebGLRenderer + the live DOM — instead we exercise the pure helpers in
+// src/game/arena/arena-venue.js against a synthetic three.js scene graph.
+//
+// Locks in the guarantees the prompt 02 spec demands:
+// 1. When the venue exposes every required empty, the runtime reads spawn /
+// screen / desk / light / camera transforms FROM those empties (world
+// space), so moving an empty in the build script moves the runtime
+// feature with it.
+// 2. When ANY required empty is missing, the load fails loudly and the error
+// names which empty is absent — so the author can fix it without guessing.
+
+import { describe, it, expect } from 'vitest';
+import { Group, Object3D, Vector3 } from 'three';
+
+import {
+ ARENA_REQUIRED_EMPTIES,
+ ARENA_SCREEN_SLOTS,
+ ARENA_RIM_LIGHTS,
+ DEFAULT_SCREEN_WIDTH_M,
+ collectArenaEmpties,
+ resolveArenaAnchors,
+ arenaBounds,
+} from '../src/game/arena/arena-venue.js';
+
+/**
+ * Build a synthetic scene that satisfies ARENA_REQUIRED_EMPTIES. Each named
+ * empty gets a deterministic world position (and, where it matters, a yaw,
+ * scale, or extras) so the tests can assert on exact values.
+ *
+ * @param {object} [opts]
+ * @param {Set<string>} [opts.omit] — names to skip (sad-path test).
+ */
+function makeSyntheticArena({ omit = new Set() } = {}) {
+ const root = new Group();
+ root.name = 'arena';
+
+ const positions = {
+ spawn_01: [0, 0, 6],
+ screen_01: [-8, 3, -8],
+ screen_02: [0, 3, -10],
+ screen_03: [8, 3, -8],
+ desk_01: [0, 0, 4],
+ light_key: [4, 7, 4],
+ light_fill: [-4, 6, 2],
+ light_rim_01: [-9, 5, -9],
+ light_rim_02: [0, 5, -11],
+ light_rim_03: [9, 5, -9],
+ camera_intro: [0, 2.2, 12],
+ };
+
+ const nodes = {};
+ for (const [name, [x, y, z]] of Object.entries(positions)) {
+ if (omit.has(name)) continue;
+ const obj = new Object3D();
+ obj.name = name;
+ obj.position.set(x, y, z);
+ root.add(obj);
+ nodes[name] = obj;
+ }
+
+ // Author a known yaw + width on screen_01 and an intro-camera yaw so the
+ // resolver's world-transform reads are exercised, not just positions.
+ if (nodes.screen_01) {
+ nodes.screen_01.rotation.y = Math.PI / 2;
+ nodes.screen_01.scale.set(9, 1, 1); // width = 9 m
+ }
+ if (nodes.spawn_01) nodes.spawn_01.rotation.y = Math.PI;
+ if (nodes.camera_intro) nodes.camera_intro.rotation.y = Math.PI; // faces +Z toward spawn
+ // Author light extras (glTF extras → userData) on the key light.
+ if (nodes.light_key) nodes.light_key.userData = { color: '#ff8800', intensity: 5, castShadow: true };
+
+ root.updateMatrixWorld(true);
+ return { root, positions, nodes };
+}
+
+describe('ARENA_REQUIRED_EMPTIES', () => {
+ it('enumerates spawn, every screen + rim slot, desk, key/fill, and intro camera', () => {
+ expect(ARENA_REQUIRED_EMPTIES).toContain('spawn_01');
+ expect(ARENA_REQUIRED_EMPTIES).toContain('desk_01');
+ expect(ARENA_REQUIRED_EMPTIES).toContain('light_key');
+ expect(ARENA_REQUIRED_EMPTIES).toContain('light_fill');
+ expect(ARENA_REQUIRED_EMPTIES).toContain('camera_intro');
+
+ const screens = ARENA_REQUIRED_EMPTIES.filter((n) => /^screen_\d{2}$/.test(n));
+ const rims = ARENA_REQUIRED_EMPTIES.filter((n) => /^light_rim_\d{2}$/.test(n));
+ expect(screens).toHaveLength(ARENA_SCREEN_SLOTS);
+ expect(rims).toHaveLength(ARENA_RIM_LIGHTS);
+ });
+});
+
+describe('collectArenaEmpties', () => {
+ it('returns a Map keyed by name covering every required empty', () => {
+ const { root } = makeSyntheticArena();
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+
+ expect(empties.size).toBe(ARENA_REQUIRED_EMPTIES.length);
+ for (const name of ARENA_REQUIRED_EMPTIES) {
+ expect(empties.has(name)).toBe(true);
+ expect(empties.get(name).name).toBe(name);
+ }
+ });
+
+ it('throws naming every missing empty when the venue is incomplete', () => {
+ const { root } = makeSyntheticArena({ omit: new Set(['screen_02', 'light_key']) });
+ expect(() => collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES)).toThrow(/screen_02/);
+ expect(() => collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES)).toThrow(/light_key/);
+ });
+
+ it('rejects a non-Object3D root with a clear error', () => {
+ expect(() => collectArenaEmpties(null)).toThrow(/Object3D/);
+ expect(() => collectArenaEmpties({})).toThrow(/Object3D/);
+ });
+});
+
+describe('resolveArenaAnchors', () => {
+ it('reads spawn / screen / desk transforms from the empties (world space)', () => {
+ const { root, positions } = makeSyntheticArena();
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+ const anchors = resolveArenaAnchors(empties);
+
+ expect(anchors.spawn.pos).toBeInstanceOf(Vector3);
+ expect(anchors.spawn.pos.toArray()).toEqual(positions.spawn_01);
+ expect(anchors.spawn.yaw).toBeCloseTo(Math.PI, 5);
+
+ expect(anchors.screens).toHaveLength(ARENA_SCREEN_SLOTS);
+ expect(anchors.screens[0].pos.toArray()).toEqual(positions.screen_01);
+ expect(anchors.screens[0].yaw).toBeCloseTo(Math.PI / 2, 5);
+ expect(anchors.screens[0].width).toBe(9); // from scale.x
+ // Unscaled screens fall back to the default width.
+ expect(anchors.screens[1].width).toBe(DEFAULT_SCREEN_WIDTH_M);
+
+ expect(anchors.desk.pos.toArray()).toEqual(positions.desk_01);
+ expect(anchors.desk.node.name).toBe('desk_01');
+ });
+
+ it('resolves the lighting rig with per-role defaults and authored extras', () => {
+ const { root } = makeSyntheticArena();
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+ const anchors = resolveArenaAnchors(empties);
+
+ const key = anchors.lights.find((l) => l.name === 'light_key');
+ expect(key.kind).toBe('key');
+ expect(key.castShadow).toBe(true);
+ expect(key.color).toBe(0xff8800); // authored via extras '#ff8800'
+ expect(key.intensity).toBe(5); // authored via extras
+
+ const fill = anchors.lights.find((l) => l.name === 'light_fill');
+ expect(fill.kind).toBe('fill');
+ expect(fill.castShadow).toBe(false); // default — fill never shadows
+
+ const rims = anchors.lights.filter((l) => l.kind === 'rim');
+ expect(rims).toHaveLength(ARENA_RIM_LIGHTS);
+ for (const rim of rims) expect(rim.castShadow).toBe(false);
+ });
+
+ it('aims the intro camera by the empty facing (rotating it re-aims lookAt)', () => {
+ const { root, positions } = makeSyntheticArena();
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+ const anchors = resolveArenaAnchors(empties);
+
+ expect(anchors.camera_intro.pos.toArray()).toEqual(positions.camera_intro);
+ // camera_intro is rotated 180° about Y, so its forward (-Z) points +Z;
+ // lookAt sits ahead of the camera at greater Z than the camera itself.
+ expect(anchors.camera_intro.lookAt.z).toBeGreaterThan(anchors.camera_intro.pos.z);
+ expect(anchors.camera_intro.lookAt.x).toBeCloseTo(anchors.camera_intro.pos.x, 5);
+ });
+
+ it('honors a parent transform when computing world positions', () => {
+ const { root } = makeSyntheticArena();
+ root.position.set(10, 0, -2);
+ root.updateMatrixWorld(true);
+
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+ const anchors = resolveArenaAnchors(empties);
+ // spawn_01 local (0,0,6) + parent (10,0,-2) → world (10,0,4).
+ expect(anchors.spawn.pos.toArray()).toEqual([10, 0, 4]);
+ });
+});
+
+describe('arenaBounds', () => {
+ it('derives a walkable footprint that contains the spawn and clamps outside it', () => {
+ const { root } = makeSyntheticArena();
+ const empties = collectArenaEmpties(root, ARENA_REQUIRED_EMPTIES);
+ const anchors = resolveArenaAnchors(empties);
+ const bounds = arenaBounds(anchors);
+
+ // Spawn must be reachable (inside the clamp).
+ const s = anchors.spawn.pos;
+ const clampedSpawn = bounds.clamp(s.x, s.z);
+ expect(clampedSpawn.x).toBeCloseTo(s.x, 5);
+ expect(clampedSpawn.z).toBeCloseTo(s.z, 5);
+
+ // A point far outside the room is pulled back onto the bound.
+ const far = bounds.clamp(999, 999);
+ expect(far.x).toBeLessThanOrEqual(bounds.center.x + bounds.halfX + 1e-6);
+ expect(far.z).toBeLessThanOrEqual(bounds.center.z + bounds.halfZ + 1e-6);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 114643549..1c9bb68cc 100644
--- a/vercel.json
+++ b/vercel.json
@@ -882,6 +882,10 @@
"src": "/play/arena/?",
"dest": "/play/arena.html"
},
+ {
+ "src": "/arena/omniology/?",
+ "dest": "/arena/omniology.html"
+ },
{
"src": "/arena/?",
"dest": "/arena.html"
diff --git a/vite.config.js b/vite.config.js
index c2222fbf5..837dbcd97 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -471,6 +471,7 @@ const appConfig = {
'play-ufo': resolve(__dirname, 'pages/play/ufo.html'),
agi: resolve(__dirname, 'pages/agi.html'),
arena: resolve(__dirname, 'pages/arena.html'),
+ 'arena-omniology': resolve(__dirname, 'pages/arena/omniology.html'),
'smart-money': resolve(__dirname, 'pages/smart-money.html'),
pose: resolve(__dirname, 'pages/pose.html'),
'pose-mini': resolve(__dirname, 'pages/pose-mini.html'),
@@ -844,6 +845,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/vaults/': resolve(root, 'pages/vaults.html'),
'/alpha-copilot': resolve(root, 'pages/alpha-copilot.html'),
'/alpha-copilot/': resolve(root, 'pages/alpha-copilot.html'),
+ '/arena/omniology': resolve(root, 'pages/arena/omniology.html'),
+ '/arena/omniology/': resolve(root, 'pages/arena/omniology.html'),
'/arena': resolve(root, 'pages/arena.html'),
'/arena/': resolve(root, 'pages/arena.html'),
'/mirror': resolve(root, 'pages/mirror.html'),