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 contest screens and polling functionality

udvk874f91925d76
diff --git a/docs/omniology-arena/04-entry-desk-x402-submit.md b/docs/omniology-arena/04-entry-desk-x402-submit.md
index 5030bce40..ef71f7402 100644
--- a/docs/omniology-arena/04-entry-desk-x402-submit.md
+++ b/docs/omniology-arena/04-entry-desk-x402-submit.md
@@ -50,7 +50,26 @@ reuses the proven agent-commerce flow; **no scripted/fake stages**.
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.
+## Security (MANDATORY — see `docs/omniology-arena/SECURITY.md`)
+The desk pays a third-party endpoint with a player's real funds. You MUST
+implement and prove these before this prompt is "done":
+- **C1 — Pin the recipient.** Reject any 402 `payTo` that is not Omniology's
+ verified, fixed Solana address (add `x402_recipient_allowlist` to spend-limits
+ and enforce in `runExternalFlow`). Do NOT trust the address the endpoint
+ returns. This blocks launch if unmet.
+- **C2 — Cap the amount.** Enforce a hard per-call max (known entry fee + small
+ tolerance); reject larger challenges. Show the player the exact amount +
+ recipient and require explicit approval before paying. No silent payment.
+- **C3 — Bound the response.** Cap the external response body (≤1 MB) and verify
+ content-type before parsing.
+- **C4 — Sanitize partner content.** Any Omniology string reaching the DOM uses
+ `textContent`/escaping, never `innerHTML`. Length-clamp and strip control chars.
+- The flow is auth + CSRF gated already; do not weaken that. Never pay from a
+ shared platform wallet — the paying agent must be the player's own.
+
## Acceptance criteria
+- C1–C4 above are implemented and demonstrated (e.g. a test that a mismatched
+ `payTo` or an over-cap amount is rejected before signing).
- 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
diff --git a/docs/omniology-arena/05-omniology-mcp-server.md b/docs/omniology-arena/05-omniology-mcp-server.md
index 137e36686..50d31c16a 100644
--- a/docs/omniology-arena/05-omniology-mcp-server.md
+++ b/docs/omniology-arena/05-omniology-mcp-server.md
@@ -50,6 +50,11 @@ it makes Omniology auto-discoverable in the x402 Bazaar. It wraps Omniology's
## 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.
+- **Security (see `docs/omniology-arena/SECURITY.md`).** If this server is the
+ x402 front door, it MUST pin Omniology's verified recipient address (C1), cap
+ the entry amount (C2), bound + content-type-check the forwarded response (C3),
+ and never forward unsanitized partner content. The pinned address and price
+ come from config/`pricing`, not from whatever a response advertises.
- 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.
diff --git a/docs/omniology-arena/SECURITY.md b/docs/omniology-arena/SECURITY.md
new file mode 100644
index 000000000..619cbccc5
--- /dev/null
+++ b/docs/omniology-arena/SECURITY.md
@@ -0,0 +1,79 @@
+# Security requirements — Omniology Arena (mandatory)
+
+These controls are **hard requirements**, not suggestions. The payment path lets
+a player's agent wallet pay an endpoint Omniology controls. We verified the
+existing `/api/x402-pay` external flow: it is well-defended in most respects
+(end user pays from *their own* agent wallet; auth + CSRF required; URL is
+SSRF-guarded with DNS-rebinding pinning; the signed Solana tx is constrained to a
+single USDC `TransferChecked` — no arbitrary-instruction injection). But three
+gaps must be closed before pointing it at any third party, and two more apply to
+rendering their content. Any prompt that touches payments or renders Omniology
+data MUST implement the relevant items here and prove it in acceptance criteria.
+
+## C1 — Pin the recipient (CRITICAL, blocks launch)
+The external flow trusts whatever `payTo` the endpoint returns in the 402
+challenge ([api/x402-pay.js](../../api/x402-pay.js) ~line 340) — there is **no
+allowlist**. A compromised/malicious Omniology server can return an attacker
+address and the player signs USDC to it.
+- Obtain Omniology's **fixed** Solana receiving address out-of-band and verify it.
+- Enforce an allowlist: reject any `payTo` that is not the pinned address, before
+ building/signing. Add `x402_recipient_allowlist` to the agent spend-limits
+ shape (`api/_lib/agent-trade-guards.js` `normalizeSpendLimits`) and check it in
+ `runExternalFlow` after probing.
+- If Omniology says the receiver is "dynamic per contest," that is a **red flag** —
+ do not proceed without a verifiable scheme (e.g. a small set of pinned
+ addresses, or an on-chain program they control).
+
+## C2 — Cap the amount (CRITICAL, blocks launch)
+The external endpoint dictates the charge amount; there is **no platform-wide
+ceiling** — only optional per-agent daily/per-tx caps which may be unset.
+- Enforce a hard per-call max for the Arena desk (e.g. the known entry fee + a
+ small tolerance). Reject any challenge that exceeds it, with a clear message.
+- Surface the exact amount + recipient to the player **before** they approve.
+ No silent payment.
+
+## C3 — Bound the response (required)
+`guardedFetch` has a 20s timeout but **no body-size limit** — a malicious
+endpoint can stream gigabytes.
+- Cap the external response body (e.g. 1 MB) and reject oversize with an error.
+- Validate content-type is JSON before parsing as the contest result.
+
+## C4 — Sanitize and contain rendered content (required)
+Omniology supplies agent names, entry titles, winner names, and image URLs.
+- Canvas text (screens) is XSS-safe, but anything reaching the **DOM** (compose
+ UI, receipts, labels) MUST be escaped/`textContent`, never `innerHTML` with
+ partner strings.
+- Image/thumbnail URLs MUST be host-allowlisted (or proxied through our server)
+ before being loaded as textures — never load arbitrary remote hosts into the
+ user's browser. Designed fallback when an image is missing/blocked.
+- Treat all partner strings as untrusted: length-clamp, strip control chars.
+
+## C5 — Don't leak users to the partner (required)
+Polling Omniology's feed from the browser leaks every viewer's IP to them.
+- Proxy the contest feed through a three.ws server endpoint (read-through cache),
+ so the partner sees our server, not our users. This also lets us enforce C3/C4
+ centrally and cache the ~88s feed cheaply.
+
+## C6 — Data-only boundary (required)
+- **Never** embed Omniology's JavaScript, iframe, or third-party script into the
+ Arena or any three.ws page. Integrate via data APIs and our own rendering only.
+ A compromised partner script would run in our origin — categorically disallowed.
+
+## Containment posture (why this is safe once C1–C6 hold)
+With recipient pinned (C1), amount capped (C2), responses bounded (C3), content
+sanitized + image hosts allowlisted (C4), users un-leaked (C5), and no partner
+code in our origin (C6), even a **fully compromised Omniology** can only: show
+wrong contest data on their own screens, or fail submissions. It cannot redirect
+funds, overcharge, OOM us, inject content, or run code in our origin. The
+residual risk collapses to "is their contest legit" — a business/legal judgment
+(see the project-diligence checklist), not a technical exposure.
+
+## Non-technical gates (must clear before placement)
+- **Regulatory:** paid-entry + cash (USDC) prizes may constitute gambling/lottery
+ unless winners are determined purely by skill. We would be hosting the entry
+ point. Confirm how winners are decided and that they're structured/licensed
+ appropriately. This is the highest-severity risk and is a go/no-go.
+- **On-chain:** verify the prize/treasury wallet is genuinely funded and pays out
+ (not just recycling entry fees).
+- **Identity & reputation:** domain age, named team, track record. Placing them
+ in-world is an implicit endorsement to $THREE holders.
diff --git a/packages/omniology-mcp/src/index.js b/packages/omniology-mcp/src/index.js
new file mode 100644
index 000000000..d8c0e40e5
--- /dev/null
+++ b/packages/omniology-mcp/src/index.js
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// @three-ws/omniology-mcp — stdio MCP server for Omniology AI-agent contests.
+//
+// The contract artifact: it lets ANY MCP client/agent read and enter Omniology
+// contests, and it makes Omniology auto-discoverable in the x402 Bazaar. Three
+// free read tools wrap Omniology's live contest feed; submit_entry is x402-priced
+// in USDC on Solana — this server is the x402 front door for Omniology.
+//
+// • list_contests (free) — the running round + next open + recent winners
+// • get_contest (free) — one contest's detail + leaderboard + entries
+// • get_leaderboard (free) — a contest's ranked leaderboard
+// • submit_entry (paid) — settle USDC, then forward the entry to Omniology
+//
+// Run standalone:
+// OMNIOLOGY_BASE_URL=https://api.omniology.ai MCP_SVM_PAYMENT_ADDRESS=<wallet> \
+// node packages/omniology-mcp/src/index.js
+//
+// Or wire into Claude Code / Cursor / any MCP host — see README.md.
+
+import { realpathSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { pathToFileURL } from 'node:url';
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+import { assertBaseUrl } from './config.js';
+import { assertPaymentEnv, getResourceServer, getLastFacilitatorInitError } from './payments.js';
+import { OmniologyClient } from './omniology.js';
+import { buildListContestsTool } from './tools/list-contests.js';
+import { buildGetContestTool } from './tools/get-contest.js';
+import { buildGetLeaderboardTool } from './tools/get-leaderboard.js';
+import { buildSubmitEntryTool } from './tools/submit-entry.js';
+
+// Single source of truth for the advertised version — package.json.
+const require = createRequire(import.meta.url);
+const SERVER_VERSION = require('../package.json').version;
+
+const SERVER_INSTRUCTIONS =
+ 'Omniology contests over MCP. Three FREE read tools wrap the live contest feed: ' +
+ 'list_contests (running round + next open + recent winners), get_contest (one contest detail + ' +
+ 'leaderboard + entries), get_leaderboard (ranked leaderboard) — no payment, key, or wallet needed. ' +
+ 'submit_entry is PAID: it settles USDC on Solana via x402, then forwards your entry to Omniology. ' +
+ 'A submit_entry call without an x402 payment payload in _meta returns a PaymentRequired envelope ' +
+ '(v2 MCP transport spec); x402-capable clients sign and retry automatically. Read tools never charge.';
+
+/**
+ * Build and return a fully-registered McpServer without connecting a transport.
+ * Safe to call from tests — registration touches no payment env and makes no
+ * network call. An OmniologyClient may be injected; otherwise the default
+ * (env-configured, global fetch) client is used.
+ *
+ * @param {OmniologyClient} [client]
+ * @returns {Promise<McpServer>}
+ */
+export async function buildServer(client = new OmniologyClient()) {
+ const server = new McpServer(
+ { name: 'omniology-mcp', title: 'Omniology Contests via x402', version: SERVER_VERSION },
+ {
+ capabilities: { tools: { listChanged: false } },
+ instructions: SERVER_INSTRUCTIONS,
+ },
+ );
+
+ const tools = await Promise.all([
+ buildListContestsTool(client),
+ buildGetContestTool(client),
+ buildGetLeaderboardTool(client),
+ buildSubmitEntryTool(client),
+ ]);
+
+ for (const t of tools) {
+ server.registerTool(
+ t.name,
+ {
+ title: t.title,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ annotations: t.annotations,
+ },
+ t.handler,
+ );
+ }
+
+ return server;
+}
+
+async function main() {
+ // Fail fast and clearly on missing required env: the Omniology base URL
+ // (everything needs it) and the Solana payment address (submit_entry needs
+ // it to receive USDC). Each throws a single actionable line.
+ try {
+ assertBaseUrl();
+ assertPaymentEnv();
+ } catch (err) {
+ console.error(`[omniology-mcp] configuration error: ${err.message}`);
+ process.exit(1);
+ return;
+ }
+
+ // Warm the shared x402 resource server so the first paid call doesn't pay the
+ // facilitator /supported fetch cost.
+ await getResourceServer();
+ const initErr = getLastFacilitatorInitError();
+ if (initErr) {
+ console.error(`[omniology-mcp] facilitator init warning: ${initErr.message}`);
+ }
+
+ const server = await buildServer();
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+
+ console.error(
+ `[omniology-mcp@${SERVER_VERSION}] ready — 3 free + 1 paid tool registered over stdio`,
+ );
+}
+
+// Connect stdio ONLY when this file is the process entry point. Launched through
+// the npm bin (a symlink to this file), process.argv[1] is the symlink while
+// import.meta.url is the resolved target, so compare both directly and via
+// realpath — otherwise the server would never start under npx.
+function isProcessEntryPoint() {
+ const argvPath = process.argv[1];
+ if (!argvPath) return false;
+ if (import.meta.url === pathToFileURL(argvPath).href) return true;
+ try {
+ return import.meta.url === pathToFileURL(realpathSync(argvPath)).href;
+ } catch {
+ return false;
+ }
+}
+
+if (isProcessEntryPoint()) {
+ main().catch((err) => {
+ console.error(`omniology-mcp: ${err?.message || err}`);
+ process.exit(1);
+ });
+}
diff --git a/packages/omniology-mcp/src/omniology.js b/packages/omniology-mcp/src/omniology.js
new file mode 100644
index 000000000..fe51b6e0e
--- /dev/null
+++ b/packages/omniology-mcp/src/omniology.js
@@ -0,0 +1,220 @@
+// Real HTTP client for the Omniology contest API — the ONLY place that knows
+// Omniology's wire shapes (CONTRACTS §1). Everything else consumes normalized
+// objects, so swapping the real base URL is a one-config change.
+//
+// No mocks: every call is a live request to OMNIOLOGY_BASE. The `fetch`
+// implementation is injectable (`fetchImpl`) so tests drive real request/parse
+// logic against a deterministic fetch without monkeypatching globals.
+//
+// Endpoints (CONTRACTS §1):
+// GET /v1/contests/live — the polled feed (current round +
+// leaderboard + recent entries/winners)
+// POST /v1/contests/{id}/entries — submit an entry (forwarded after the
+// x402 USDC settlement done by this MCP)
+
+import { OMNIOLOGY_BASE, OMNIOLOGY_API_KEY, HTTP_TIMEOUT_MS, USER_AGENT } from './config.js';
+
+const DEFAULT_TIMEOUT_MS = 20000;
+
+export class OmniologyError extends Error {
+ constructor(message, { code, status } = {}) {
+ super(message);
+ this.name = 'OmniologyError';
+ this.code = code || 'omniology_error';
+ if (status !== undefined) this.status = status;
+ }
+}
+
+// ---- normalization helpers -------------------------------------------------
+// Defensive coercion. Per CONTRACTS §1.1 unknown fields arrive as `null`
+// (never omitted); we mirror that — a missing/garbage value becomes null rather
+// than an invented default, so downstream renders designed empty states.
+
+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const str = (v) => (typeof v === 'string' && v.trim() !== '' ? v : null);
+const secToMs = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.round(v * 1000) : null);
+const arr = (v) => (Array.isArray(v) ? v : []);
+
+function normalizeContest(c) {
+ if (!c || typeof c !== 'object') return null;
+ return {
+ id: str(c.id),
+ title: str(c.title),
+ round: num(c.round),
+ opensMs: secToMs(c.opened_unix),
+ closesMs: secToMs(c.closes_unix),
+ entriesCount: num(c.entries_count),
+ prizeUsdc: num(c.prize_usdc),
+ prizeAsset: str(c.prize_asset) || 'USDC',
+ };
+}
+
+function normalizeLeaderboard(list) {
+ return arr(list).map((r) => ({
+ rank: num(r?.rank),
+ entryId: str(r?.entry_id),
+ agent: str(r?.agent),
+ score: num(r?.score),
+ thumbUrl: str(r?.thumb_url),
+ }));
+}
+
+function normalizeRecentEntries(list) {
+ return arr(list).map((r) => ({
+ entryId: str(r?.entry_id),
+ agent: str(r?.agent),
+ submittedMs: secToMs(r?.submitted_unix),
+ }));
+}
+
+function normalizeRecentWinners(list) {
+ return arr(list).map((r) => ({
+ round: num(r?.round),
+ agent: str(r?.agent),
+ prizeUsdc: num(r?.prize_usdc),
+ tx: str(r?.tx),
+ }));
+}
+
+/**
+ * Normalize the raw /v1/contests/live body (CONTRACTS §1.1) into the camelCase,
+ * millisecond NormalizedFeed used across the arena (CONTRACTS §2.1).
+ */
+export function normalizeFeed(raw) {
+ const body = raw && typeof raw === 'object' ? raw : {};
+ const next = body.next && typeof body.next === 'object' ? { opensMs: secToMs(body.next.opens_unix) } : null;
+ return {
+ ok: true,
+ serverNowMs: secToMs(body.now_unix),
+ current: normalizeContest(body.current),
+ next,
+ leaderboard: normalizeLeaderboard(body.leaderboard),
+ recentEntries: normalizeRecentEntries(body.recent_entries),
+ recentWinners: normalizeRecentWinners(body.recent_winners),
+ };
+}
+
+export class OmniologyClient {
+ /**
+ * @param {object} [opts]
+ * @param {string} [opts.baseUrl] — defaults to OMNIOLOGY_BASE
+ * @param {string} [opts.apiKey] — bearer for the authenticated forward
+ * @param {number} [opts.timeoutMs]
+ * @param {Function} [opts.fetchImpl] — injectable fetch (tests)
+ * @param {string} [opts.userAgent]
+ */
+ constructor({ baseUrl, apiKey, timeoutMs, fetchImpl, userAgent } = {}) {
+ this.baseUrl = String(baseUrl ?? OMNIOLOGY_BASE ?? '').replace(/\/+$/, '');
+ this.apiKey = apiKey ?? OMNIOLOGY_API_KEY ?? '';
+ this.timeoutMs = timeoutMs ?? HTTP_TIMEOUT_MS ?? DEFAULT_TIMEOUT_MS;
+ this.userAgent = userAgent || USER_AGENT;
+ this._fetch = fetchImpl || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : null);
+ if (typeof this._fetch !== 'function') {
+ throw new OmniologyError('No fetch implementation available (Node ≥18 or inject fetchImpl).', {
+ code: 'no_fetch',
+ });
+ }
+ }
+
+ _requireBase() {
+ if (!this.baseUrl) {
+ throw new OmniologyError(
+ 'OMNIOLOGY_BASE_URL is not set — point it at the Omniology contest API.',
+ { code: 'not_configured' },
+ );
+ }
+ return this.baseUrl;
+ }
+
+ // Low-level request. Errors are sanitized: messages name the path + status
+ // only, never the bearer token, full URL with secrets, or upstream stack.
+ async _request(path, { method = 'GET', body, auth = false } = {}) {
+ const base = this._requireBase();
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
+
+ let res;
+ try {
+ res = await this._fetch(`${base}${path}`, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'user-agent': this.userAgent,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ ...(auth && this.apiKey ? { authorization: `Bearer ${this.apiKey}` } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.name === 'AbortError') {
+ throw new OmniologyError(`Omniology ${path} timed out after ${this.timeoutMs}ms.`, {
+ code: 'timeout',
+ });
+ }
+ throw new OmniologyError(`Omniology ${path} request failed.`, { code: 'network_error' });
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = null;
+ }
+
+ if (!res.ok) {
+ // Surface a clean upstream message — prefer Omniology's own error
+ // string, fall back to the status. Never echo arbitrary HTML/raw body.
+ const upstream =
+ (data && typeof data === 'object' && (str(data.message) || str(data.error))) || null;
+ throw new OmniologyError(
+ upstream || `Omniology ${path} returned HTTP ${res.status}.`,
+ { code: 'upstream_error', status: res.status },
+ );
+ }
+ if (data === null) {
+ throw new OmniologyError(`Omniology ${path} returned a non-JSON response.`, {
+ code: 'bad_response',
+ });
+ }
+ return data;
+ }
+
+ /**
+ * Fetch + normalize the live contest feed (CONTRACTS §1.1).
+ * @returns {Promise<object>} NormalizedFeed (CONTRACTS §2.1)
+ */
+ async fetchLiveFeed() {
+ const raw = await this._request('/v1/contests/live');
+ return normalizeFeed(raw);
+ }
+
+ /**
+ * Forward a paid entry submission to Omniology (CONTRACTS §1.2). Called only
+ * AFTER this MCP has verified the x402 USDC payment, so the POST itself is a
+ * plain authenticated request — Omniology trusts this server as its x402
+ * front door. Returns Omniology's raw acceptance body
+ * `{ entry_id, status, round, position }`.
+ *
+ * @param {string} contestId
+ * @param {{ entry: object, agent?: string|null }} payload
+ */
+ async submitEntry(contestId, { entry, agent = null } = {}) {
+ const id = String(contestId ?? '').trim();
+ if (!id) throw new OmniologyError('submitEntry: contestId is required.', { code: 'bad_input' });
+ const data = await this._request(`/v1/contests/${encodeURIComponent(id)}/entries`, {
+ method: 'POST',
+ auth: true,
+ body: { entry, agent: agent ?? null },
+ });
+ return {
+ entryId: str(data.entry_id),
+ status: str(data.status) || 'accepted',
+ round: num(data.round),
+ position: num(data.position),
+ };
+ }
+}
diff --git a/packages/omniology-mcp/src/payments.js b/packages/omniology-mcp/src/payments.js
new file mode 100644
index 000000000..abf6448e9
--- /dev/null
+++ b/packages/omniology-mcp/src/payments.js
@@ -0,0 +1,243 @@
+// x402 payment wiring for omniology-mcp — Solana USDC, exact scheme.
+//
+// Mirrors packages/ibm-x402-mcp/src/payments.js and mcp-server/src/payments.js.
+// Builds a single shared x402ResourceServer per process that verifies + settles
+// USDC on Solana mainnet via PayAI's facilitator. The one paid tool
+// (submit_entry) wraps its handler in `paid(cfg, fn)`; the free read tools wrap
+// theirs in `free(cfg, fn)` so every tool returns the same MCP CallToolResult
+// envelope. This server is the x402 front door for Omniology: it settles the
+// USDC payment here, then the tool forwards an authenticated entry to Omniology.
+//
+// Environment (server operator — NOT the end user):
+// MCP_SVM_PAYMENT_ADDRESS — Solana wallet that receives USDC (required)
+// X402_PAY_TO_SOLANA — fallback alias
+// X402_PAY_TO — fallback alias
+// X402_FEE_PAYER_SOLANA — transaction fee payer (optional, defaults to three.ws fee payer)
+// X402_FACILITATOR_URL — PayAI facilitator URL (optional)
+// X402_FACILITATOR_TOKEN — Bearer token for facilitator (optional)
+// X402_ASSET_MINT_SOLANA — USDC mint override (optional)
+
+import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';
+import { registerExactSvmScheme } from '@x402/svm/exact/server';
+import { createPaymentWrapper, createToolResourceUrl } from '@x402/mcp';
+import { declareDiscoveryExtension } from '@x402/extensions/bazaar';
+
+// CAIP-2 id for Solana mainnet (mirrors api/_lib/x402-spec.js).
+const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+// Canonical Solana mainnet USDC mint (read from repo, never pasted from memory).
+const DEFAULT_SOLANA_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const env = (key, fallback) => {
+ const v = process.env[key];
+ return v && v.trim() ? v.trim() : fallback;
+};
+
+function requireSvmPayTo() {
+ const addr = env('MCP_SVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_SOLANA') || env('X402_PAY_TO');
+ if (!addr) {
+ throw new Error(
+ 'set MCP_SVM_PAYMENT_ADDRESS to your Solana wallet address to receive USDC payments.',
+ );
+ }
+ return addr;
+}
+
+/**
+ * Assert the receiving Solana payment address is configured. Called once by the
+ * stdio entry point so a running server fails fast with a single clean line.
+ * Does NOT run during buildServer()/tests — tool registration stays secret-free.
+ * @throws {Error} with a single actionable message when no pay-to is set
+ */
+export function assertPaymentEnv() {
+ requireSvmPayTo();
+}
+
+function svmFeePayer() {
+ return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
+}
+
+function buildFacilitator() {
+ const url = env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');
+ const token = env('X402_FACILITATOR_TOKEN');
+ return new HTTPFacilitatorClient({
+ url,
+ createAuthHeaders: token
+ ? async () => ({ headers: { Authorization: `Bearer ${token}` } })
+ : undefined,
+ });
+}
+
+let resourceServerPromise = null;
+let lastInitError = null;
+
+// Build a single shared x402ResourceServer, register the Solana `exact` scheme,
+// and call .initialize() to fetch the facilitator's /supported. Memoized so
+// concurrent tool calls don't race during startup.
+export function getResourceServer() {
+ if (resourceServerPromise) return resourceServerPromise;
+ resourceServerPromise = (async () => {
+ const server = new x402ResourceServer([buildFacilitator()]);
+ registerExactSvmScheme(server, {});
+ try {
+ await server.initialize();
+ } catch (err) {
+ lastInitError = err;
+ console.error(`[omniology-mcp] facilitator initialize() failed: ${err.message}`);
+ }
+ return server;
+ })();
+ return resourceServerPromise;
+}
+
+export function getLastFacilitatorInitError() {
+ return lastInitError;
+}
+
+async function buildAccepts({ resourceServer, priceUsd, resourceUrl }) {
+ return resourceServer.buildPaymentRequirementsFromOptions(
+ [
+ {
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ payTo: requireSvmPayTo(),
+ price: priceUsd,
+ maxTimeoutSeconds: 60,
+ extra: {
+ name: 'USDC',
+ decimals: 6,
+ asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),
+ feePayer: svmFeePayer(),
+ },
+ },
+ ],
+ { resourceUrl },
+ );
+}
+
+/**
+ * Wrap a tool handler with Solana USDC x402 payment (exact scheme).
+ *
+ * Payment wiring is built LAZILY on first invocation — tool registration stays
+ * secret-free so buildServer() can enumerate tools without payment env. The
+ * wrapper is memoized so the first call pays the init cost once.
+ *
+ * @param {object} cfg
+ * @param {string} cfg.toolName
+ * @param {string} cfg.description
+ * @param {string} cfg.priceUsd — e.g. "$0.05"
+ * @param {object} cfg.inputSchema — JSON Schema for tool args
+ * @param {object} [cfg.example]
+ * @param {object} [cfg.outputExample]
+ * @param {Function} handler — async (args, context) → any
+ * @returns {Function} MCP tool callback
+ */
+export function paid(cfg, handler) {
+ const { toolName, description, priceUsd, inputSchema, example, outputExample } = cfg;
+
+ if (!toolName) throw new Error('paid(): toolName is required');
+ if (!description) throw new Error('paid(): description is required');
+ if (!priceUsd) throw new Error('paid(): priceUsd is required');
+ if (!inputSchema) throw new Error('paid(): inputSchema is required');
+
+ let wrapperPromise = null;
+
+ async function getWrapper() {
+ if (wrapperPromise) return wrapperPromise;
+ wrapperPromise = (async () => {
+ const resourceServer = await getResourceServer();
+ const resourceUrl = createToolResourceUrl(toolName);
+ const accepts = await buildAccepts({ resourceServer, priceUsd, resourceUrl });
+
+ const bazaar = declareDiscoveryExtension({
+ toolName,
+ description,
+ transport: 'stdio',
+ inputSchema,
+ example,
+ output: outputExample ? { example: outputExample } : undefined,
+ });
+
+ const wrap = createPaymentWrapper(resourceServer, {
+ accepts,
+ resource: { url: resourceUrl, description, mimeType: 'application/json' },
+ extensions: bazaar,
+ });
+
+ return wrap(async (args, context) => {
+ const result = await handler(args, context);
+ return buildToolResult(result);
+ });
+ })();
+ return wrapperPromise;
+ }
+
+ return async function paidToolCallback(args, context) {
+ const wrapped = await getWrapper();
+ return wrapped(args, context);
+ };
+}
+
+/**
+ * Wrap a tool handler as a FREE (no-payment) MCP tool callback — the read
+ * tools. Funnels the return value through the SAME envelope every paid tool
+ * uses (text mirror + structuredContent + isError on `ok:false`), so a free
+ * tool is indistinguishable from a paid one to the client EXCEPT it never emits
+ * a 402 PaymentRequired challenge and never touches payment env. Errors thrown
+ * by the handler are sanitized into a stable `{ ok:false, error, message }`.
+ *
+ * @param {object} cfg
+ * @param {string} cfg.toolName — used only in error messages
+ * @param {Function} handler — async (args, context) → any
+ * @returns {Function} MCP tool callback
+ */
+export function free(cfg, handler) {
+ const { toolName } = cfg || {};
+ if (!toolName) throw new Error('free(): toolName is required');
+ if (typeof handler !== 'function') throw new Error('free(): handler must be a function');
+ return async function freeToolCallback(args, context) {
+ try {
+ const result = await handler(args, context);
+ return buildToolResult(result);
+ } catch (err) {
+ return buildToolResult(
+ toolError(err?.code || 'internal_error', err?.message || String(err), {
+ ...(err?.status ? { status: err.status } : {}),
+ }),
+ );
+ }
+ };
+}
+
+/**
+ * Build the MCP CallToolResult envelope from a handler's return value.
+ * - content[0].text — JSON (or raw string) blob; always present.
+ * - structuredContent — plain objects surfaced as structured tool output.
+ * - isError:true — set ONLY for the `{ ok:false }` toolError envelope, which
+ * also cancels the x402 payment so a caller is never charged for an error.
+ *
+ * @param {unknown} result
+ * @returns {{ content: Array<{type:'text',text:string}>, structuredContent?: object, isError?: true }}
+ */
+export function buildToolResult(result) {
+ const text = typeof result === 'string' ? result : JSON.stringify(result);
+ const envelope = { content: [{ type: 'text', text }] };
+ const isPlainObject = result !== null && typeof result === 'object' && !Array.isArray(result);
+ if (isPlainObject) {
+ envelope.structuredContent = result;
+ if (result.ok === false) envelope.isError = true;
+ }
+ return envelope;
+}
+
+/**
+ * Standard tool error envelope. Every error path returns this shape so MCP
+ * clients branch on a stable `{ ok:false, error:<code>, message }` contract.
+ * @param {string} code
+ * @param {string} message
+ * @param {object} [extra]
+ */
+export function toolError(code, message, extra) {
+ return { ok: false, error: code, message, ...(extra || {}) };
+}
+
+export { NETWORK_SOLANA_MAINNET };
diff --git a/packages/omniology-mcp/src/tools/_shared.js b/packages/omniology-mcp/src/tools/_shared.js
new file mode 100644
index 000000000..433653e83
--- /dev/null
+++ b/packages/omniology-mcp/src/tools/_shared.js
@@ -0,0 +1,34 @@
+import { z } from 'zod';
+import { zodToJsonSchema } from 'zod-to-json-schema';
+
+export { toolError } from '../payments.js';
+
+// MCP ToolAnnotations for the free read tools. Each reads Omniology's live
+// contest feed: nothing local is modified (readOnlyHint) and it reaches an
+// external service (openWorldHint). The feed advances every ~88s, so identical
+// input can return different output — not idempotent.
+export const readAnnotations = Object.freeze({
+ readOnlyHint: true,
+ openWorldHint: true,
+ idempotentHint: false,
+});
+
+// MCP ToolAnnotations for submit_entry — a write to an external contest. It
+// creates a new entry (not read-only), is not idempotent (each call is a fresh
+// submission), and talks to a live service. Submitting is additive, not
+// destructive, so destructiveHint stays false.
+export const writeAnnotations = Object.freeze({
+ readOnlyHint: false,
+ openWorldHint: true,
+ idempotentHint: false,
+ destructiveHint: false,
+});
+
+export function jsonSchemaFromZod(shape) {
+ const schema = zodToJsonSchema(z.object(shape).strict(), {
+ $refStrategy: 'none',
+ target: 'jsonSchema7',
+ });
+ delete schema.$schema;
+ return schema;
+}
diff --git a/packages/omniology-mcp/src/tools/get-contest.js b/packages/omniology-mcp/src/tools/get-contest.js
new file mode 100644
index 000000000..1c39bebb3
--- /dev/null
+++ b/packages/omniology-mcp/src/tools/get-contest.js
@@ -0,0 +1,64 @@
+// `get_contest` — FREE read tool. Returns one contest's full detail (title,
+// round, open/close times, entry count, prize) plus its current leaderboard and
+// recent entries.
+//
+// Thin wrapper over Omniology's /v1/contests/live feed (CONTRACTS §1.1). The
+// feed is a live window over the current/most-recent round, so a contestId that
+// matches the running round resolves; any other id returns a clean
+// `contest_not_found` rather than fabricated history.
+
+import { z } from 'zod';
+
+import { free, toolError } from '../payments.js';
+import { jsonSchemaFromZod, readAnnotations } from './_shared.js';
+
+const TOOL_NAME = 'get_contest';
+const TOOL_DESCRIPTION =
+ 'Fetch one Omniology contest by id from the live feed: its title, round number, open/close times, ' +
+ 'entry count, USDC prize, current leaderboard, and recent entries. Read-only and free. The feed ' +
+ 'covers the running round, so an id from list_contests resolves; an unknown id returns ' +
+ 'contest_not_found.';
+
+const inputZodShape = {
+ contestId: z
+ .string()
+ .min(1)
+ .max(200)
+ .describe('Contest id, as returned by list_contests (the running round\'s id).'),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+export function buildGetContestTool(client) {
+ const handler = free({ toolName: TOOL_NAME }, async (args) => {
+ const contestId = String(args?.contestId ?? '').trim();
+ if (!contestId) {
+ return toolError('bad_input', 'contestId is required.');
+ }
+ const feed = await client.fetchLiveFeed();
+ if (!feed.current || feed.current.id !== contestId) {
+ return toolError(
+ 'contest_not_found',
+ `No live contest with id "${contestId}". Call list_contests for the current round.`,
+ { status: 404 },
+ );
+ }
+ return {
+ ok: true,
+ serverNowMs: feed.serverNowMs,
+ contest: { ...feed.current, status: 'live' },
+ leaderboard: feed.leaderboard,
+ recentEntries: feed.recentEntries,
+ };
+ });
+
+ return {
+ name: TOOL_NAME,
+ title: 'Get an Omniology contest (free)',
+ description: TOOL_DESCRIPTION,
+ annotations: readAnnotations,
+ inputSchema: inputZodShape,
+ inputJsonSchema,
+ handler,
+ };
+}
diff --git a/packages/omniology-mcp/src/tools/get-leaderboard.js b/packages/omniology-mcp/src/tools/get-leaderboard.js
new file mode 100644
index 000000000..5ed522717
--- /dev/null
+++ b/packages/omniology-mcp/src/tools/get-leaderboard.js
@@ -0,0 +1,62 @@
+// `get_leaderboard` — FREE read tool. Returns the ranked leaderboard for a
+// contest (rank, entry id, agent display name, score, thumbnail).
+//
+// Thin wrapper over Omniology's /v1/contests/live feed (CONTRACTS §1.1), whose
+// `leaderboard` is for the current/most-recent round. A contestId matching the
+// running round resolves; any other id returns `contest_not_found`.
+
+import { z } from 'zod';
+
+import { free, toolError } from '../payments.js';
+import { jsonSchemaFromZod, readAnnotations } from './_shared.js';
+
+const TOOL_NAME = 'get_leaderboard';
+const TOOL_DESCRIPTION =
+ 'Fetch the ranked leaderboard for an Omniology contest: rank, entry id, agent display name, score, ' +
+ 'and thumbnail for each placed entry. Read-only and free. Covers the current/most-recent round; an ' +
+ 'unknown id returns contest_not_found.';
+
+const inputZodShape = {
+ contestId: z
+ .string()
+ .min(1)
+ .max(200)
+ .describe('Contest id, as returned by list_contests (the running round\'s id).'),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+export function buildGetLeaderboardTool(client) {
+ const handler = free({ toolName: TOOL_NAME }, async (args) => {
+ const contestId = String(args?.contestId ?? '').trim();
+ if (!contestId) {
+ return toolError('bad_input', 'contestId is required.');
+ }
+ const feed = await client.fetchLiveFeed();
+ if (!feed.current || feed.current.id !== contestId) {
+ return toolError(
+ 'contest_not_found',
+ `No live contest with id "${contestId}". Call list_contests for the current round.`,
+ { status: 404 },
+ );
+ }
+ return {
+ ok: true,
+ serverNowMs: feed.serverNowMs,
+ contestId,
+ round: feed.current.round,
+ count: feed.leaderboard.length,
+ leaderboard: feed.leaderboard,
+ };
+ });
+
+ return {
+ name: TOOL_NAME,
+ title: 'Get an Omniology leaderboard (free)',
+ description: TOOL_DESCRIPTION,
+ annotations: readAnnotations,
+ inputSchema: inputZodShape,
+ inputJsonSchema,
+ handler,
+ };
+}
diff --git a/packages/omniology-mcp/src/tools/list-contests.js b/packages/omniology-mcp/src/tools/list-contests.js
new file mode 100644
index 000000000..653ea3068
--- /dev/null
+++ b/packages/omniology-mcp/src/tools/list-contests.js
@@ -0,0 +1,72 @@
+// `list_contests` — FREE read tool. Lists the contests the Omniology live feed
+// currently exposes: the running round and (when known) the next round's open
+// time, plus the last few winners for context.
+//
+// Thin wrapper over Omniology's /v1/contests/live feed (CONTRACTS §1.1). The
+// feed is a live ~88s window, so the canonical "list" is the current round; the
+// optional `status` filter narrows the projection without inventing data.
+
+import { z } from 'zod';
+
+import { free } from '../payments.js';
+import { jsonSchemaFromZod, readAnnotations } from './_shared.js';
+
+const TOOL_NAME = 'list_contests';
+const TOOL_DESCRIPTION =
+ 'List Omniology AI-agent contests from the live feed: the currently running round (id, title, ' +
+ 'round number, open/close times, entry count, USDC prize) and, when known, when the next round ' +
+ 'opens, plus the most recent winners. Read-only and free — no payment, key, or wallet required. ' +
+ 'Filter with status: "all" (default), "live", or "upcoming".';
+
+const inputZodShape = {
+ status: z
+ .enum(['all', 'live', 'upcoming'])
+ .optional()
+ .describe('Which contests to include: "all" (default), only the "live" round, or "upcoming".'),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+export function buildListContestsTool(client) {
+ const handler = free({ toolName: TOOL_NAME }, async (args) => {
+ const status = args?.status || 'all';
+ const feed = await client.fetchLiveFeed();
+
+ const contests = [];
+ if ((status === 'all' || status === 'live') && feed.current) {
+ contests.push({ ...feed.current, status: 'live' });
+ }
+ if ((status === 'all' || status === 'upcoming') && feed.next?.opensMs != null) {
+ // The feed only carries the next round's open time, not its identity.
+ contests.push({
+ id: null,
+ title: null,
+ round: feed.current?.round != null ? feed.current.round + 1 : null,
+ opensMs: feed.next.opensMs,
+ closesMs: null,
+ entriesCount: null,
+ prizeUsdc: null,
+ prizeAsset: 'USDC',
+ status: 'upcoming',
+ });
+ }
+
+ return {
+ ok: true,
+ serverNowMs: feed.serverNowMs,
+ count: contests.length,
+ contests,
+ recentWinners: feed.recentWinners,
+ };
+ });
+
+ return {
+ name: TOOL_NAME,
+ title: 'List Omniology contests (free)',
+ description: TOOL_DESCRIPTION,
+ annotations: readAnnotations,
+ inputSchema: inputZodShape,
+ inputJsonSchema,
+ handler,
+ };
+}
diff --git a/packages/omniology-mcp/src/tools/submit-entry.js b/packages/omniology-mcp/src/tools/submit-entry.js
new file mode 100644
index 000000000..ad53775be
--- /dev/null
+++ b/packages/omniology-mcp/src/tools/submit-entry.js
@@ -0,0 +1,105 @@
+// `submit_entry` — PAID write tool. Settles USDC on Solana (x402, exact) and
+// then forwards the entry to Omniology's submit endpoint (CONTRACTS §1.2).
+//
+// This server is the x402 FRONT DOOR for Omniology: the caller pays this MCP in
+// USDC, the payment is verified by the shared x402 resource server, and only
+// then does `submitEntryCore` POST the authenticated entry to Omniology. If the
+// forward fails, the handler returns a toolError envelope (`ok:false`) which the
+// payment wrapper treats as a failure and CANCELS the settlement — so a caller
+// is never charged for an entry Omniology rejected.
+
+import { z } from 'zod';
+
+import { paid, toolError } from '../payments.js';
+import { jsonSchemaFromZod, writeAnnotations } from './_shared.js';
+import { SUBMIT_ENTRY_PRICE_USD } from '../pricing.js';
+import { OmniologyError } from '../omniology.js';
+
+const TOOL_NAME = 'submit_entry';
+const TOOL_DESCRIPTION =
+ `Submit an entry to an Omniology contest. Paid: ${SUBMIT_ENTRY_PRICE_USD} USDC settled on Solana via ` +
+ 'x402 — the call returns a PaymentRequired challenge until a signed payment is supplied, then the ' +
+ 'verified entry is forwarded to Omniology and the acceptance (entry_id, status, round, position) is ' +
+ 'returned. `entry` is the partner-defined submission payload; `agent` is an optional display name.';
+
+// `entry` is partner-defined (CONTRACTS §1.2) — accept any JSON object and pass
+// it through untouched. We only require it to be a non-null object.
+const inputZodShape = {
+ contestId: z
+ .string()
+ .min(1)
+ .max(200)
+ .describe('Id of the contest to enter (from list_contests).'),
+ entry: z
+ .record(z.any())
+ .describe('Partner-defined entry payload, forwarded verbatim to Omniology.'),
+ agent: z
+ .string()
+ .max(200)
+ .nullish()
+ .describe('Optional display name to attribute the entry to.'),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+/**
+ * Forward a (already-paid) entry to Omniology and shape the result. Exported so
+ * the forward path is unit-testable with a DI'd client, independent of the x402
+ * payment wrapper.
+ *
+ * @param {import('../omniology.js').OmniologyClient} client
+ * @param {{ contestId: string, entry: object, agent?: string|null }} args
+ */
+export async function submitEntryCore(client, args) {
+ const contestId = String(args?.contestId ?? '').trim();
+ if (!contestId) return toolError('bad_input', 'contestId is required.');
+ if (!args?.entry || typeof args.entry !== 'object' || Array.isArray(args.entry)) {
+ return toolError('bad_input', 'entry must be a JSON object.');
+ }
+ try {
+ const result = await client.submitEntry(contestId, {
+ entry: args.entry,
+ agent: args.agent ?? null,
+ });
+ return { ok: true, ...result };
+ } catch (err) {
+ if (err instanceof OmniologyError) {
+ return toolError(err.code, err.message, err.status ? { status: err.status } : undefined);
+ }
+ return toolError('internal_error', err?.message || String(err));
+ }
+}
+
+export function buildSubmitEntryTool(client) {
+ const handler = paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ priceUsd: SUBMIT_ENTRY_PRICE_USD,
+ inputSchema: inputJsonSchema,
+ example: {
+ contestId: 'rnd_1421',
+ entry: { prompt: 'a neon koi swimming through circuitry', model: 'three.ws/forge' },
+ agent: 'Reef',
+ },
+ outputExample: {
+ ok: true,
+ entryId: 'ent_8c12e0f9',
+ status: 'accepted',
+ round: 1421,
+ position: 38,
+ },
+ },
+ async (args) => submitEntryCore(client, args),
+ );
+
+ return {
+ name: TOOL_NAME,
+ title: `Submit a contest entry (${SUBMIT_ENTRY_PRICE_USD})`,
+ description: TOOL_DESCRIPTION,
+ annotations: writeAnnotations,
+ inputSchema: inputZodShape,
+ inputJsonSchema,
+ handler,
+ };
+}
diff --git a/packages/omniology-mcp/test/registration.test.mjs b/packages/omniology-mcp/test/registration.test.mjs
new file mode 100644
index 000000000..ff4618aeb
--- /dev/null
+++ b/packages/omniology-mcp/test/registration.test.mjs
@@ -0,0 +1,122 @@
+// Tool-surface invariants for @three-ws/omniology-mcp.
+//
+// Building the tool catalog is secret-free by design: the paid wrapper is lazy
+// (see src/payments.js), so the whole surface enumerates with no payment env
+// and no Omniology base URL, and these tests never touch the network.
+//
+// Run: node --test packages/omniology-mcp/test/registration.test.mjs
+
+import { test, before } from 'node:test';
+import assert from 'node:assert/strict';
+import { z } from 'zod';
+
+import { buildServer } from '../src/index.js';
+import { buildListContestsTool } from '../src/tools/list-contests.js';
+import { buildGetContestTool } from '../src/tools/get-contest.js';
+import { buildGetLeaderboardTool } from '../src/tools/get-leaderboard.js';
+import { buildSubmitEntryTool } from '../src/tools/submit-entry.js';
+import { SUBMIT_ENTRY_PRICE_USD } from '../src/pricing.js';
+import { OmniologyClient } from '../src/omniology.js';
+
+// Guarantee enumeration works with neither payment nor Omniology env set.
+delete process.env.MCP_SVM_PAYMENT_ADDRESS;
+delete process.env.X402_PAY_TO_SOLANA;
+delete process.env.X402_PAY_TO;
+delete process.env.OMNIOLOGY_BASE_URL;
+delete process.env.OMNIOLOGY_API_KEY;
+
+const READ_TOOLS = ['list_contests', 'get_contest', 'get_leaderboard'];
+const ALL_TOOLS = [...READ_TOOLS, 'submit_entry'];
+
+// A client whose fetch must never be called during registration — if it is, the
+// test fails loudly instead of silently hitting the network.
+const noFetch = () => {
+ throw new Error('registration must not perform network I/O');
+};
+const client = new OmniologyClient({ baseUrl: 'https://example.test', fetchImpl: noFetch });
+
+let tools;
+
+before(async () => {
+ tools = await Promise.all([
+ buildListContestsTool(client),
+ buildGetContestTool(client),
+ buildGetLeaderboardTool(client),
+ buildSubmitEntryTool(client),
+ ]);
+});
+
+test('exactly the four documented tools are built', () => {
+ const names = tools.map((t) => t.name).sort();
+ assert.deepEqual(names, [...ALL_TOOLS].sort());
+});
+
+test('tool names are unique', () => {
+ const names = tools.map((t) => t.name);
+ assert.equal(new Set(names).size, names.length);
+});
+
+test('every tool has a title, description, zod input shape, handler and annotations', () => {
+ for (const t of tools) {
+ assert.ok(typeof t.title === 'string' && t.title.length > 0, `${t.name} title`);
+ assert.ok(typeof t.description === 'string' && t.description.length > 0, `${t.name} description`);
+ assert.ok(t.inputSchema && typeof t.inputSchema === 'object', `${t.name} inputSchema`);
+ assert.ok(Object.keys(t.inputSchema).length > 0, `${t.name} inputSchema has no fields`);
+ assert.equal(typeof t.handler, 'function', `${t.name} handler`);
+ assert.ok(t.annotations, `${t.name} annotations`);
+ assert.equal(typeof t.annotations.readOnlyHint, 'boolean', `${t.name} readOnlyHint`);
+ assert.equal(typeof t.annotations.openWorldHint, 'boolean', `${t.name} openWorldHint`);
+ assert.equal(typeof t.annotations.idempotentHint, 'boolean', `${t.name} idempotentHint`);
+ }
+});
+
+test('read tools are read-only & open-world; submit_entry is a write', () => {
+ for (const t of tools) {
+ assert.equal(t.annotations.openWorldHint, true, `${t.name} talks to a live service`);
+ if (READ_TOOLS.includes(t.name)) {
+ assert.equal(t.annotations.readOnlyHint, true, `${t.name} must be read-only`);
+ assert.equal(t.annotations.destructiveHint, undefined, `${t.name} must omit destructiveHint`);
+ } else {
+ assert.equal(t.annotations.readOnlyHint, false, 'submit_entry mutates external state');
+ assert.equal(t.annotations.destructiveHint, false, 'submit_entry is additive, not destructive');
+ }
+ }
+});
+
+test('submit_entry states its exact USDC price in description and title', () => {
+ const submit = tools.find((t) => t.name === 'submit_entry');
+ assert.match(SUBMIT_ENTRY_PRICE_USD, /^\$\d/);
+ assert.ok(submit.description.includes(SUBMIT_ENTRY_PRICE_USD), 'description price');
+ assert.ok(submit.title.includes(SUBMIT_ENTRY_PRICE_USD), 'title price');
+});
+
+test('input schemas validate required fields', () => {
+ const get = tools.find((t) => t.name === 'get_contest');
+ const getSchema = z.object(get.inputSchema);
+ assert.equal(getSchema.safeParse({}).success, false, 'get_contest needs contestId');
+ assert.equal(getSchema.safeParse({ contestId: 'rnd_1' }).success, true);
+
+ const submit = tools.find((t) => t.name === 'submit_entry');
+ const submitSchema = z.object(submit.inputSchema);
+ assert.equal(submitSchema.safeParse({ contestId: 'rnd_1' }).success, false, 'submit needs entry');
+ assert.equal(
+ submitSchema.safeParse({ contestId: 'rnd_1', entry: { prompt: 'x' } }).success,
+ true,
+ );
+ assert.equal(
+ submitSchema.safeParse({ contestId: 'rnd_1', entry: { prompt: 'x' }, agent: 'Reef' }).success,
+ true,
+ 'agent is optional',
+ );
+});
+
+test('buildServer registers every tool with its annotations, secret-free', async () => {
+ const server = await buildServer(client);
+ const registered = server._registeredTools;
+ assert.ok(registered, 'McpServer should expose its tool registry');
+ for (const t of tools) {
+ const entry = registered[t.name];
+ assert.ok(entry, `${t.name} not registered`);
+ assert.deepEqual(entry.annotations, t.annotations, `${t.name} annotations must survive`);
+ }
+});
diff --git a/public/arena/omniology/venue.glb b/public/arena/omniology/venue.glb
new file mode 100644
index 000000000..18a159787
Binary files /dev/null and b/public/arena/omniology/venue.glb differ
diff --git a/scripts/build-arena-hdri.mjs b/scripts/build-arena-hdri.mjs
new file mode 100644
index 000000000..0c58f6dca
--- /dev/null
+++ b/scripts/build-arena-hdri.mjs
@@ -0,0 +1,146 @@
+#!/usr/bin/env node
+/**
+ * Authors public/arena/omniology/hdri.hdr — the equirectangular HDR the
+ * /arena/omniology bootstrap pre-filters through PMREMGenerator.fromEquirect-
+ * angular() to drive PBR reflections on the venue materials. The HDR only
+ * affects materials (scene.environment), not the visible background, which
+ * stays the dark arena fog colour.
+ *
+ * Run via: npm run build:arena-hdri
+ *
+ * Why synthesise instead of shipping a Polyhaven download: the three.ws asset
+ * rails (CLAUDE.md) require every committed asset to have crystal-clear
+ * provenance. A locally-generated HDR is fully owned by three.ws and dedicated
+ * CC0 — see public/arena/omniology/LICENSES.md. Drop a real CC0 .hdr into that
+ * directory and update the LICENSES entry to upgrade fidelity later; the
+ * bootstrap reads whatever `hdri.hdr` is present.
+ *
+ * Palette mirrors the venue: a cool blue-purple hemisphere wash, a warm key
+ * glow on the +X/+Z (entry/desk) side, and a band of cyan/magenta/amber glow
+ * along the −Z screen wall so chrome bezels and the desk pick up the contest
+ * colours. Output is Radiance RGBE (`.hdr`), uncompressed, ~32 kB.
+ */
+
+import { writeFileSync, mkdirSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const OUT_DIR = resolve(ROOT, 'public/arena/omniology');
+
+const WIDTH = 128;
+const HEIGHT = 64;
+
+// Pack (r,g,b) float radiance into the Greg Ward RGBE convention.
+function packRGBE(r, g, b) {
+ const v = Math.max(r, g, b);
+ if (v < 1e-32) return [0, 0, 0, 0];
+ let e = Math.ceil(Math.log2(v));
+ let m = v / 2 ** e;
+ if (m >= 1) {
+ m *= 0.5;
+ e += 1;
+ }
+ const scale = (m * 256) / v;
+ return [
+ Math.min(255, Math.max(0, Math.round(r * scale))),
+ Math.min(255, Math.max(0, Math.round(g * scale))),
+ Math.min(255, Math.max(0, Math.round(b * scale))),
+ Math.min(255, Math.max(0, e + 128)),
+ ];
+}
+
+// Smooth gaussian bump centred at (theta0, phi0) with falloff `width`.
+function bump(theta, phi, theta0, phi0, width) {
+ const dTheta = Math.atan2(Math.sin(theta - theta0), Math.cos(theta - theta0));
+ const dPhi = phi - phi0;
+ const d2 = dTheta * dTheta + dPhi * dPhi;
+ return Math.exp(-d2 / (2 * width * width));
+}
+
+// Sample radiance for one equirectangular pixel. (u, v) in [0, 1).
+// u ↔ azimuth (theta): 0 → -π, 1 → +π (theta 0 faces -Z, the screen wall)
+// v ↔ latitude (phi): 0 → +π/2 zenith, 1 → -π/2 nadir
+function sampleRadiance(u, v) {
+ const theta = (u - 0.5) * Math.PI * 2;
+ const phi = (0.5 - v) * Math.PI;
+
+ // Base ambient — very low cool wash.
+ let r = 0.01;
+ let g = 0.014;
+ let b = 0.022;
+
+ // Hemisphere: cool blue ceiling, near-black floor — gives PBR chrome a
+ // faint tint even where no glow points.
+ const hemi = 0.5 + 0.5 * Math.sin(phi);
+ r += hemi * 0.024;
+ g += hemi * 0.034;
+ b += hemi * 0.06;
+
+ // Warm key glow on the entry/desk side (theta ≈ +π toward +Z, high up).
+ const key = bump(theta, phi, Math.PI, 0.85, 0.5);
+ r += key * 2.6;
+ g += key * 1.7;
+ b += key * 0.95;
+
+ // Contest-screen wall glow band (theta ≈ 0, toward −Z) — three coloured
+ // pools so bezels/desk pick up cyan / magenta / amber contest light.
+ const SCREEN_GLOWS = [
+ { theta: -0.42, hue: [3.0, 0.9, 2.8] }, // magenta (rim_01 side)
+ { theta: 0.0, hue: [0.7, 2.6, 3.4] }, // cyan (rim_02, centre)
+ { theta: 0.42, hue: [3.2, 1.9, 0.7] }, // amber (rim_03 side)
+ ];
+ for (const s of SCREEN_GLOWS) {
+ const w = bump(theta, phi, s.theta, 0.55, 0.26);
+ r += w * s.hue[0];
+ g += w * s.hue[1];
+ b += w * s.hue[2];
+ }
+
+ // Recessed ceiling cove — a soft cool ring near the zenith so the floor
+ // inlay and metallic floor catch an overhead sheen.
+ const cove = bump(theta, phi, theta, 1.25, 0.5) * (0.4 + 0.6 * Math.cos(theta * 3));
+ r += Math.max(0, cove) * 0.5;
+ g += Math.max(0, cove) * 0.62;
+ b += Math.max(0, cove) * 0.9;
+
+ return [r, g, b];
+}
+
+function buildHdr() {
+ const header =
+ '#?RADIANCE\n' +
+ '# Authored by three.ws build-arena-hdri (CC0 1.0)\n' +
+ 'FORMAT=32-bit_rle_rgbe\n' +
+ 'EXPOSURE=1.0\n' +
+ '\n' +
+ `-Y ${HEIGHT} +X ${WIDTH}\n`;
+ const headerBuf = Buffer.from(header, 'ascii');
+
+ const pixelBytes = Buffer.alloc(WIDTH * HEIGHT * 4);
+ for (let y = 0; y < HEIGHT; y += 1) {
+ for (let x = 0; x < WIDTH; x += 1) {
+ const u = (x + 0.5) / WIDTH;
+ const vv = (y + 0.5) / HEIGHT;
+ const [r, g, b] = sampleRadiance(u, vv);
+ const [R, G, B, E] = packRGBE(r, g, b);
+ const idx = (y * WIDTH + x) * 4;
+ pixelBytes[idx] = R;
+ pixelBytes[idx + 1] = G;
+ pixelBytes[idx + 2] = B;
+ pixelBytes[idx + 3] = E;
+ }
+ }
+ return Buffer.concat([headerBuf, pixelBytes]);
+}
+
+function main() {
+ mkdirSync(OUT_DIR, { recursive: true });
+ const buf = buildHdr();
+ const outPath = resolve(OUT_DIR, 'hdri.hdr');
+ writeFileSync(outPath, buf);
+ console.log(`[arena-hdri] wrote hdri.hdr ${(buf.length / 1024).toFixed(1)} kB (${WIDTH}x${HEIGHT})`);
+}
+
+main();
diff --git a/scripts/build-arena-venue.mjs b/scripts/build-arena-venue.mjs
new file mode 100644
index 000000000..619e74ed4
--- /dev/null
+++ b/scripts/build-arena-venue.mjs
@@ -0,0 +1,354 @@
+#!/usr/bin/env node
+/**
+ * Authors public/arena/omniology/venue.glb — the Omniology Arena interior the
+ * /arena/omniology bootstrap parents the rest of its world to. Composed at
+ * build time from procedural geometry via @gltf-transform/core so the runtime
+ * gets a real .glb (no primitives stamped at runtime) and the named-empty
+ * contract in src/game/arena/arena-venue.js + LICENSES.md is satisfied without
+ * depending on a third-party asset drop.
+ *
+ * Run via: npm run build:arena-venue
+ *
+ * Design intent — a premium, screenshot-worthy contest hall, NOT a gray box:
+ * - A hexagon-ish wide room: dark polished floor with a glowing inlay ring,
+ * a back wall canted into three angled bays that each frame a contest
+ * screen, side walls, and a sealed ceiling with a recessed light cove.
+ * - An illuminated entry desk facing the spawn, where prompt 04 mounts the
+ * submission interactable.
+ * - Emissive accent strips (floor ring, screen bezels, desk lip) so the
+ * bloom pass has something to grab and the room reads as a venue under
+ * the HDRI + lighting rig.
+ *
+ * The visual richness comes from the HDRI environment + the lighting rig +
+ * the bloom/ACES post pipeline — the geometry stays low-poly so the room holds
+ * 60fps on a mid-tier laptop and runs on mobile.
+ *
+ * Underscore separators are deliberate: three.js's GLTFLoader runs
+ * PropertyBinding.sanitizeNodeName on every node and strips `[ ] . : /`, so an
+ * empty authored as `screen.01` would arrive as `screen01` and the contract in
+ * arena-venue.js would fail to resolve it. Keep mesh node names underscored too
+ * so the loader + any e2e traversal can rely on one convention.
+ *
+ * Move/rotate/scale any anchor empty below and re-run — the runtime reads the
+ * GLB world transforms, so the spawn, screens, desk, lights, and intro camera
+ * all follow. (Acceptance criterion: move an anchor, see the runtime follow.)
+ */
+
+import { writeFileSync, mkdirSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+import { Document, NodeIO } from '@gltf-transform/core';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const OUT_DIR = resolve(ROOT, 'public/arena/omniology');
+
+// ─── Room layout constants ───────────────────────────────────────────────────
+// The room is a wide rectangle. The back wall (−Z) carries the three contest
+// screens; the entry desk + spawn sit on the +Z side. Keep walls beyond the
+// outermost anchors so arenaBounds()'s outward margin lands on real geometry.
+const ROOM_HALF_X = 11; // walls at x = ±11
+const ROOM_HALF_Z = 10; // walls at z = ±10
+const ROOM_HEIGHT = 7;
+const SCREEN_Y = 2.7; // centre height of the contest screens
+const SCREEN_WIDTH = 6.2; // metres — read back at runtime via the empty's scale.x
+
+// ─── Geometry primitives (positions / normals / indices, no UVs) ─────────────
+
+function boxGeom(sx, sy, sz) {
+ const x = sx / 2;
+ const y = sy / 2;
+ const z = sz / 2;
+ const faces = [
+ { n: [1, 0, 0], v: [[x, -y, -z], [x, y, -z], [x, y, z], [x, -y, z]] },
+ { n: [-1, 0, 0], v: [[-x, -y, z], [-x, y, z], [-x, y, -z], [-x, -y, -z]] },
+ { n: [0, 1, 0], v: [[-x, y, -z], [-x, y, z], [x, y, z], [x, y, -z]] },
+ { n: [0, -1, 0], v: [[-x, -y, z], [-x, -y, -z], [x, -y, -z], [x, -y, z]] },
+ { n: [0, 0, 1], v: [[-x, -y, z], [x, -y, z], [x, y, z], [-x, y, z]] },
+ { n: [0, 0, -1], v: [[x, -y, -z], [-x, -y, -z], [-x, y, -z], [x, y, -z]] },
+ ];
+ const positions = [];
+ const normals = [];
+ const indices = [];
+ for (const face of faces) {
+ const start = positions.length / 3;
+ for (const p of face.v) {
+ positions.push(...p);
+ normals.push(...face.n);
+ }
+ indices.push(start, start + 1, start + 2, start, start + 2, start + 3);
+ }
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
+}
+
+function planeGeom(width, depth, normalY = 1) {
+ const x = width / 2;
+ const z = depth / 2;
+ const positions =
+ normalY > 0
+ ? [-x, 0, z, x, 0, z, x, 0, -z, -x, 0, -z]
+ : [-x, 0, -z, x, 0, -z, x, 0, z, -x, 0, z];
+ const normals = [];
+ for (let i = 0; i < 4; i += 1) normals.push(0, normalY, 0);
+ const indices = [0, 1, 2, 0, 2, 3];
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
+}
+
+// A flat ring (annulus) lying in the XZ plane — the glowing floor inlay.
+function ringGeom(inner, outer, segments = 96) {
+ const positions = [];
+ const normals = [];
+ const indices = [];
+ for (let i = 0; i <= segments; i += 1) {
+ const t = (i / segments) * Math.PI * 2;
+ const c = Math.cos(t);
+ const s = Math.sin(t);
+ positions.push(outer * c, 0, outer * s);
+ normals.push(0, 1, 0);
+ positions.push(inner * c, 0, inner * s);
+ normals.push(0, 1, 0);
+ }
+ for (let i = 0; i < segments; i += 1) {
+ const a = i * 2;
+ indices.push(a, a + 2, a + 1, a + 1, a + 2, a + 3);
+ }
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
+}
+
+// ─── glTF helpers ────────────────────────────────────────────────────────────
+
+function addPrim(doc, buffer, mat, name, { positions, normals, indices }) {
+ const posAcc = doc.createAccessor(`${name}.pos`).setType('VEC3').setArray(positions).setBuffer(buffer);
+ const normAcc = doc.createAccessor(`${name}.norm`).setType('VEC3').setArray(normals).setBuffer(buffer);
+ const idxAcc = doc.createAccessor(`${name}.idx`).setType('SCALAR').setArray(indices).setBuffer(buffer);
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', posAcc)
+ .setAttribute('NORMAL', normAcc)
+ .setIndices(idxAcc)
+ .setMaterial(mat);
+ return doc.createMesh(name).addPrimitive(prim);
+}
+
+function addMesh(doc, scene, buffer, mat, name, geom, translation = [0, 0, 0], rotation = null) {
+ const mesh = addPrim(doc, buffer, mat, name, geom);
+ const node = doc.createNode(name).setMesh(mesh).setTranslation(translation);
+ if (rotation) node.setRotation(rotation);
+ scene.addChild(node);
+ return node;
+}
+
+function addEmpty(doc, scene, name, translation, { rotationY = 0, scale = null, extras = null } = {}) {
+ // Named empty = glTF Node with no mesh. Three.js exposes these as Object3D
+ // instances which collectArenaEmpties() picks up by .name.
+ const node = doc.createNode(name).setTranslation(translation);
+ if (rotationY) {
+ // Quaternion for a rotation about world Y by rotationY radians.
+ node.setRotation([0, Math.sin(rotationY / 2), 0, Math.cos(rotationY / 2)]);
+ }
+ if (scale) node.setScale(scale);
+ if (extras) node.setExtras(extras);
+ scene.addChild(node);
+ return node;
+}
+
+// ─── Materials ───────────────────────────────────────────────────────────────
+
+const mat = {};
+function buildMaterials(doc) {
+ mat.floor = doc
+ .createMaterial('ArenaFloor')
+ .setBaseColorFactor([0.03, 0.035, 0.05, 1])
+ .setMetallicFactor(0.55)
+ .setRoughnessFactor(0.32);
+ mat.floorRing = doc
+ .createMaterial('ArenaFloorRing')
+ .setBaseColorFactor([0.04, 0.06, 0.09, 1])
+ .setMetallicFactor(0.2)
+ .setRoughnessFactor(0.4)
+ .setEmissiveFactor([0.05, 0.45, 0.62]);
+ mat.wall = doc
+ .createMaterial('ArenaWall')
+ .setBaseColorFactor([0.022, 0.025, 0.038, 1])
+ .setMetallicFactor(0.1)
+ .setRoughnessFactor(0.78);
+ mat.bay = doc
+ .createMaterial('ArenaScreenBay')
+ .setBaseColorFactor([0.015, 0.017, 0.027, 1])
+ .setMetallicFactor(0.25)
+ .setRoughnessFactor(0.55);
+ mat.ceiling = doc
+ .createMaterial('ArenaCeiling')
+ .setBaseColorFactor([0.016, 0.018, 0.026, 1])
+ .setMetallicFactor(0.1)
+ .setRoughnessFactor(0.85);
+ mat.cove = doc
+ .createMaterial('ArenaCove')
+ .setBaseColorFactor([0.1, 0.12, 0.16, 1])
+ .setMetallicFactor(0.1)
+ .setRoughnessFactor(0.5)
+ .setEmissiveFactor([0.18, 0.26, 0.4]);
+ mat.bezel = doc
+ .createMaterial('ArenaBezel')
+ .setBaseColorFactor([0.05, 0.07, 0.1, 1])
+ .setMetallicFactor(0.6)
+ .setRoughnessFactor(0.3)
+ .setEmissiveFactor([0.06, 0.5, 0.7]);
+ mat.screenPanel = doc
+ .createMaterial('ArenaScreenPanel')
+ .setBaseColorFactor([0.01, 0.012, 0.02, 1])
+ .setMetallicFactor(0.0)
+ .setRoughnessFactor(0.18)
+ .setEmissiveFactor([0.03, 0.05, 0.08]);
+ mat.desk = doc
+ .createMaterial('ArenaDesk')
+ .setBaseColorFactor([0.05, 0.055, 0.07, 1])
+ .setMetallicFactor(0.5)
+ .setRoughnessFactor(0.35);
+ mat.deskLip = doc
+ .createMaterial('ArenaDeskLip')
+ .setBaseColorFactor([0.06, 0.08, 0.12, 1])
+ .setMetallicFactor(0.3)
+ .setRoughnessFactor(0.4)
+ .setEmissiveFactor([0.5, 0.32, 0.05]);
+}
+
+// ─── Screen bay layout ───────────────────────────────────────────────────────
+// Three screens across the back wall: a centre screen flat on −Z, and two
+// flanking screens canted ~22° inward so the trio wraps the viewer. Each bay
+// has a recessed housing, an emissive bezel, a dark panel the runtime screen
+// renders over, and the `screen_NN` anchor at panel centre (scaled to width).
+const SCREEN_BAYS = [
+ { id: '01', x: -7.4, z: -8.4, yaw: 0.38 },
+ { id: '02', x: 0, z: -9.6, yaw: 0 },
+ { id: '03', x: 7.4, z: -8.4, yaw: -0.38 },
+];
+
+function addScreenBay(doc, scene, buffer, bay) {
+ const { id, x, z, yaw } = bay;
+ const rot = [0, Math.sin(yaw / 2), 0, Math.cos(yaw / 2)];
+ // Housing slab behind the panel.
+ addMesh(doc, scene, buffer, mat.bay, `screen_bay_${id}`, boxGeom(SCREEN_WIDTH + 1.1, 4.5, 0.4), [x, SCREEN_Y, z], rot);
+ // Emissive bezel frame (slightly proud of the housing toward the room).
+ const fwdX = Math.sin(yaw);
+ const fwdZ = Math.cos(yaw);
+ addMesh(doc, scene, buffer, mat.bezel, `screen_bezel_${id}`, boxGeom(SCREEN_WIDTH + 0.5, 3.9, 0.12), [
+ x + fwdX * 0.22,
+ SCREEN_Y,
+ z + fwdZ * 0.22,
+ ], rot);
+ // Dark display panel the runtime mounts the live screen over.
+ addMesh(doc, scene, buffer, mat.screenPanel, `screen_panel_${id}`, boxGeom(SCREEN_WIDTH, 3.5, 0.06), [
+ x + fwdX * 0.3,
+ SCREEN_Y,
+ z + fwdZ * 0.3,
+ ], rot);
+ // Anchor empty at panel centre, facing the room. scale.x encodes the
+ // screen width the runtime reads back via resolveArenaAnchors().
+ addEmpty(doc, scene, `screen_${id}`, [x + fwdX * 0.34, SCREEN_Y, z + fwdZ * 0.34], {
+ rotationY: yaw,
+ scale: [SCREEN_WIDTH, 1, 1],
+ });
+}
+
+// ─── Document build ──────────────────────────────────────────────────────────
+
+function buildVenueDoc() {
+ const doc = new Document();
+ doc.createBuffer();
+ const buffer = doc.getRoot().listBuffers()[0];
+ const scene = doc.createScene('ArenaScene');
+ buildMaterials(doc);
+
+ // Floor + glowing inlay ring.
+ addMesh(doc, scene, buffer, mat.floor, 'arena_floor', planeGeom(ROOM_HALF_X * 2, ROOM_HALF_Z * 2, 1), [0, 0, 0]);
+ addMesh(doc, scene, buffer, mat.floorRing, 'arena_floor_ring', ringGeom(4.3, 4.7, 96), [0, 0.01, -1.5]);
+ addMesh(doc, scene, buffer, mat.floorRing, 'arena_floor_ring_inner', ringGeom(2.0, 2.18, 80), [0, 0.01, -1.5]);
+
+ // Ceiling (downward normal) + recessed emissive cove ring.
+ addMesh(doc, scene, buffer, mat.ceiling, 'arena_ceiling', planeGeom(ROOM_HALF_X * 2, ROOM_HALF_Z * 2, -1), [0, ROOM_HEIGHT, 0]);
+ addMesh(doc, scene, buffer, mat.cove, 'arena_ceiling_cove', ringGeom(5.6, 6.4, 80), [0, ROOM_HEIGHT - 0.05, -1.5]);
+
+ // Four perimeter walls (boxes — cheap, sealed, double-sided not needed since
+ // the camera stays inside and inner faces point inward by box normals).
+ addMesh(doc, scene, buffer, mat.wall, 'arena_wall_back', boxGeom(ROOM_HALF_X * 2, ROOM_HEIGHT, 0.4), [0, ROOM_HEIGHT / 2, -ROOM_HALF_Z]);
+ addMesh(doc, scene, buffer, mat.wall, 'arena_wall_front', boxGeom(ROOM_HALF_X * 2, ROOM_HEIGHT, 0.4), [0, ROOM_HEIGHT / 2, ROOM_HALF_Z]);
+ addMesh(doc, scene, buffer, mat.wall, 'arena_wall_left', boxGeom(0.4, ROOM_HEIGHT, ROOM_HALF_Z * 2), [-ROOM_HALF_X, ROOM_HEIGHT / 2, 0]);
+ addMesh(doc, scene, buffer, mat.wall, 'arena_wall_right', boxGeom(0.4, ROOM_HEIGHT, ROOM_HALF_Z * 2), [ROOM_HALF_X, ROOM_HEIGHT / 2, 0]);
+
+ // Three contest-screen bays across the back.
+ for (const bay of SCREEN_BAYS) addScreenBay(doc, scene, buffer, bay);
+
+ // Entry desk facing the spawn (+Z side), with an emissive front lip.
+ const deskZ = 5.4;
+ addMesh(doc, scene, buffer, mat.desk, 'arena_desk_body', boxGeom(3.4, 1.1, 1.0), [0, 0.55, deskZ]);
+ addMesh(doc, scene, buffer, mat.desk, 'arena_desk_top', boxGeom(3.7, 0.12, 1.2), [0, 1.16, deskZ]);
+ addMesh(doc, scene, buffer, mat.deskLip, 'arena_desk_lip', boxGeom(3.4, 0.14, 0.05), [0, 0.95, deskZ - 0.5]);
+
+ // ─── Named anchor empties (the contract in src/game/arena/arena-venue.js) ──
+
+ // Spawn — on the entry (+Z) side, facing the screens (−Z ⇒ yaw = π).
+ addEmpty(doc, scene, 'spawn_01', [0, 0, 7.0], { rotationY: Math.PI });
+
+ // Entry desk anchor — at the desk top, facing the spawn (+Z ⇒ yaw 0).
+ addEmpty(doc, scene, 'desk_01', [0, 1.16, deskZ], { rotationY: 0 });
+
+ // Lighting rig anchors. Colors/intensity/distance/shadow are authored as
+ // glTF extras → read back as node.userData by resolveArenaAnchors(). One
+ // shadow-casting key, a soft fill, three cheap rims hugging the screens.
+ addEmpty(doc, scene, 'light_key', [3.5, 6.2, 5.0], {
+ extras: { color: '#fff1e0', intensity: 3.4, castShadow: true },
+ });
+ addEmpty(doc, scene, 'light_fill', [-4.5, 5.4, 3.0], {
+ extras: { color: '#8fb4ff', intensity: 1.2, castShadow: false },
+ });
+ addEmpty(doc, scene, 'light_rim_01', [-7.4, 4.4, -6.8], {
+ extras: { color: '#ff3bd6', intensity: 2.6, distance: 22, castShadow: false },
+ });
+ addEmpty(doc, scene, 'light_rim_02', [0, 4.8, -8.2], {
+ extras: { color: '#35e0ff', intensity: 2.8, distance: 24, castShadow: false },
+ });
+ addEmpty(doc, scene, 'light_rim_03', [7.4, 4.4, -6.8], {
+ extras: { color: '#ffb13b', intensity: 2.6, distance: 22, castShadow: false },
+ });
+
+ // Intro camera — a cinematic high entry pose at the front-left corner,
+ // aimed across the room toward the contest screens. `focal` (extras) sets
+ // how far ahead the lookAt target sits; the negative yaw turns the empty's
+ // forward (−Z) to point toward room centre/−Z (toward the screens) rather
+ // than back out the entry. The bootstrap dollies from here to the player.
+ addEmpty(doc, scene, 'camera_intro', [-6.5, 3.4, 8.5], {
+ rotationY: -0.55,
+ extras: { focal: 11 },
+ });
+
+ return doc;
+}
+
+async function main() {
+ mkdirSync(OUT_DIR, { recursive: true });
+ const io = new NodeIO();
+ const doc = buildVenueDoc();
+ const bytes = await io.writeBinary(doc);
+ const outPath = resolve(OUT_DIR, 'venue.glb');
+ writeFileSync(outPath, Buffer.from(bytes));
+ console.log(`[arena-venue] wrote venue.glb ${(bytes.length / 1024).toFixed(1)} kB`);
+}
+
+main().catch((err) => {
+ console.error('[arena-venue] build failed:', err);
+ process.exit(1);
+});
diff --git a/src/game/arena/arena-venue.js b/src/game/arena/arena-venue.js
index 1088aaa07..109915004 100644
--- a/src/game/arena/arena-venue.js
+++ b/src/game/arena/arena-venue.js
@@ -208,17 +208,20 @@ export function resolveArenaAnchors(empties) {
}
/**
- * 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.
+ * Axis-aligned walkable footprint for the venue, derived from the spawn, desk,
+ * and screen anchors so the player clamp follows the authored room without a
+ * second source of truth. The clamp box is the anchor bounding box grown
+ * outward by `margin`: the venue's walls are authored to sit beyond the
+ * outermost anchors (the screens mount ON the walls, the player floor reaches
+ * up to them), so every anchor — including the entry-side spawn — stays inside
+ * the walkable region. Mirrors /play's square WORLD_BOUND clamp shape.
*
* @param {ReturnType<typeof resolveArenaAnchors>} anchors
- * @param {number} [margin] — metres to inset from the outermost anchors.
+ * @param {number} [margin] — metres of interior floor past the outermost anchor.
* @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) {
+export function arenaBounds(anchors, margin = 1.2) {
const pts = [
anchors.spawn.pos,
anchors.desk.pos,
@@ -234,11 +237,9 @@ export function arenaBounds(anchors, margin = 1.4) {
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 halfX = (maxX - minX) / 2 + margin;
+ const halfZ = (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)),
diff --git a/src/game/arena/arena.js b/src/game/arena/arena.js
new file mode 100644
index 000000000..7752b84e8
--- /dev/null
+++ b/src/game/arena/arena.js
@@ -0,0 +1,530 @@
+// Omniology Arena — world bootstrap.
+//
+// `OmniologyArena` owns the renderer, scene, camera, render loop, the local
+// player controller (keyboard / on-screen joystick / drag-to-orbit camera), a
+// placeholder lit environment, and an `update(dt)` registry that later prompts
+// hook into. It deliberately does NOT touch multiplayer, avatars, or the
+// Omniology contest feed — the entry module (omniology.js) wires those on top,
+// and prompts 02–04 mount the venue GLB, the live screens, and the entry desk
+// through `anchors` + `registerUpdatable`.
+//
+// Movement, camera, and input feel are matched 1:1 to the /play scene
+// (coincommunities.js) so the arena reads as the same engine: MOVE_SPEED,
+// RUN_SPEED, GRAVITY, JUMP_VELOCITY, the camera basis, and the joystick deadzone
+// are the same constants. Avatar loading/animation is reused from the shared
+// avatar-rig library by the entry module, not reinvented here.
+
+import {
+ Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, Vector2,
+ PCFShadowMap, SRGBColorSpace, ACESFilmicToneMapping,
+ Color, Fog,
+ HemisphereLight, DirectionalLight, AmbientLight, PointLight,
+ Mesh, MeshStandardMaterial, MeshBasicMaterial,
+ CircleGeometry, RingGeometry, GridHelper,
+} from 'three';
+import { log } from '../../shared/log.js';
+import { CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';
+
+// Locomotion + camera tuning, identical to /play so the two worlds feel the same.
+export const MOVE_SPEED = 4.2;
+export const RUN_SPEED = 8.0; // hold Shift to sprint
+export const RUN_TIMESCALE = 1.7; // speed the walk cycle up so a sprint reads as a run
+export const JUMP_VELOCITY = 5.5; // m/s upward kick on Space
+export const GRAVITY = 15; // m/s^2 pulling the jumper back down
+export const REMOTE_LERP = 0.18; // peer interpolation factor (used by RemotePlayer)
+const JOY_DEADZONE = 0.12; // swallow tiny stick grazes so the avatar doesn't drift
+
+// The walkable disc. A touch inside the server's 60m clamp so a local prediction
+// never outruns the authoritative bound and snaps back. Prompt 02 replaces the
+// placeholder floor + this bound with the venue GLB's real collision geometry.
+const ARENA_RADIUS = 26;
+
+// Default mount points. Prompt 02 resolves the real ones from the venue GLB's
+// named empties and calls `setAnchors()`. Everything downstream (spawn, screens,
+// desk) reads from here, so swapping in the venue is a single call — no consumer
+// edits. Coordinates are a sensible authored layout: spawn near the back, three
+// screens across the front wall, an entry desk to the right.
+function defaultAnchors() {
+ return {
+ spawn: { position: new Vector3(0, 0, 8), rotationY: Math.PI },
+ screens: [
+ { position: new Vector3(-9, 4.2, -15), width: 7.5, rotationY: 0.32 },
+ { position: new Vector3(0, 4.6, -16.5), width: 9, rotationY: 0 },
+ { position: new Vector3(9, 4.2, -15), width: 7.5, rotationY: -0.32 },
+ ],
+ desk: { position: new Vector3(12, 0, 2), rotationY: -Math.PI / 2 },
+ lights: [],
+ };
+}
+
+export class OmniologyArena {
+ /** @param {HTMLCanvasElement} canvas */
+ constructor(canvas) {
+ this.canvas = canvas;
+ this.anchors = defaultAnchors();
+
+ // Members registered via registerUpdatable() — each gets update(dt) per frame.
+ // 03/04 register their screen + desk handles here so they animate without
+ // editing this loop. A Set so a handle can unregister itself on dispose.
+ this._updatables = new Set();
+
+ // Local player controller state, mirrored from coincommunities.js.
+ this.keys = new Set();
+ this._joy = null;
+ this.camYaw = 0.6; this.camPitch = 0.5; this.camDist = 9;
+ const spawn = this.anchors.spawn;
+ this.localPos = new Vector3(spawn.position.x, 0, spawn.position.z);
+ this.localYaw = spawn.rotationY;
+ this.motion = 'idle';
+ this.vy = 0;
+ this.grounded = true;
+ this._dragging = false; this._lastPtr = null; this._downPtr = null;
+ this._last = performance.now();
+ this._raf = 0;
+ this._disposed = false;
+
+ // The local avatar rig is attached by the entry module once its GLB loads.
+ this.localRig = null;
+ this.localAnim = null;
+ this.localHeight = 1.7;
+
+ // Stable bound handlers so dispose() can remove every listener it added.
+ this._onResize = this._onResize.bind(this);
+ this._onKeyDown = this._onKeyDown.bind(this);
+ this._onKeyUp = this._onKeyUp.bind(this);
+ this._onPointerDown = this._onPointerDown.bind(this);
+ this._onPointerUp = this._onPointerUp.bind(this);
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onWheel = this._onWheel.bind(this);
+ this._loop = this._loop.bind(this);
+
+ this._initRenderer();
+ this._initScene();
+ this._buildEnvironment();
+ this._bindInput();
+ this._initJoystick();
+
+ this._raf = requestAnimationFrame(this._loop);
+ }
+
+ // ---------------------------------------------------------------- renderer
+ _initRenderer() {
+ let r;
+ try {
+ r = new WebGLRenderer({ canvas: this.canvas, antialias: true });
+ } catch (err) {
+ // Blocklisted GPUs / disabled hardware acceleration / some embedded
+ // browsers. Tag it so the boot guard can show a recovery message instead
+ // of a dead loader.
+ const e = new Error('WebGL unavailable: ' + (err?.message || err));
+ e.code = 'NO_WEBGL';
+ throw e;
+ }
+ r.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ r.setSize(window.innerWidth, window.innerHeight);
+ r.shadowMap.enabled = true;
+ r.shadowMap.type = PCFShadowMap;
+ r.outputColorSpace = SRGBColorSpace;
+ r.toneMapping = ACESFilmicToneMapping;
+ r.toneMappingExposure = 1.05;
+ this.renderer = r;
+ window.addEventListener('resize', this._onResize);
+ }
+
+ _initScene() {
+ const scene = new Scene();
+ this.scene = scene;
+ // Cool near-black backdrop with matched fog so the floor melts into the
+ // horizon instead of ending at a hard edge — reads as a room, not a void.
+ this._skyColor = new Color(0x07080c);
+ scene.background = this._skyColor;
+ scene.fog = new Fog(this._skyColor.getHex(), 34, 96);
+
+ this.camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 2000);
+ this.camera.position.set(0, 6, 16);
+ }
+
+ // Placeholder lit environment: a dark technical floor with a hairline grid, a
+ // glowing boundary ring, soft venue accent lights, and a cool key light that
+ // casts shadows. Prompt 02 replaces all of this with the venue GLB — every
+ // object here is tracked in `_envObjects` so disposal is total.
+ _buildEnvironment() {
+ this._envObjects = [];
+ const track = (obj) => { this._envObjects.push(obj); return obj; };
+
+ // Lighting rig.
+ const hemi = new HemisphereLight(0x9fb4ff, 0x05060a, 0.55);
+ this.scene.add(track(hemi));
+ const ambient = new AmbientLight(0xffffff, 0.18);
+ this.scene.add(track(ambient));
+
+ const key = new DirectionalLight(0xdfe8ff, 1.55);
+ key.position.set(14, 26, 12);
+ key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048);
+ key.shadow.camera.near = 1;
+ key.shadow.camera.far = 90;
+ key.shadow.camera.left = -ARENA_RADIUS - 6;
+ key.shadow.camera.right = ARENA_RADIUS + 6;
+ key.shadow.camera.top = ARENA_RADIUS + 6;
+ key.shadow.camera.bottom = -ARENA_RADIUS - 6;
+ key.shadow.bias = -0.0004;
+ this.scene.add(track(key));
+ this._keyLight = key;
+
+ // Warm-ish accent fills near the front screen wall so the space has depth and
+ // the screens (mounted in 03) sit in a pool of light, not flat dark.
+ const accentDefs = [
+ { x: -9, z: -13, color: 0x6ea8ff },
+ { x: 9, z: -13, color: 0x8a7bff },
+ ];
+ for (const def of accentDefs) {
+ const p = new PointLight(def.color, 22, 40, 2);
+ p.position.set(def.x, 6, def.z);
+ this.scene.add(track(p));
+ }
+
+ // Floor: a wide dark disc that receives shadow.
+ const floorGeo = new CircleGeometry(ARENA_RADIUS + 30, 64);
+ const floorMat = new MeshStandardMaterial({ color: 0x0c0e14, roughness: 0.92, metalness: 0.05 });
+ const floor = new Mesh(floorGeo, floorMat);
+ floor.rotation.x = -Math.PI / 2;
+ floor.receiveShadow = true;
+ this.scene.add(track(floor));
+
+ // Inner venue platform — a slightly lighter, slightly raised stage disc so the
+ // walkable area reads as an authored room within the larger ground.
+ const stageGeo = new CircleGeometry(ARENA_RADIUS, 64);
+ const stageMat = new MeshStandardMaterial({ color: 0x12151d, roughness: 0.8, metalness: 0.1 });
+ const stage = new Mesh(stageGeo, stageMat);
+ stage.rotation.x = -Math.PI / 2;
+ stage.position.y = 0.02;
+ stage.receiveShadow = true;
+ this.scene.add(track(stage));
+
+ // Hairline technical grid over the stage.
+ const grid = new GridHelper(ARENA_RADIUS * 2, ARENA_RADIUS * 2, 0x2a3142, 0x161a24);
+ grid.position.y = 0.03;
+ grid.material.transparent = true;
+ grid.material.opacity = 0.45;
+ this.scene.add(track(grid));
+ this._grid = grid;
+
+ // Glowing boundary ring at the walkable edge.
+ const ringGeo = new RingGeometry(ARENA_RADIUS - 0.25, ARENA_RADIUS, 96);
+ const ringMat = new MeshBasicMaterial({ color: 0x6ea8ff, transparent: true, opacity: 0.5, depthWrite: false });
+ const ring = new Mesh(ringGeo, ringMat);
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.04;
+ this.scene.add(track(ring));
+ this._ring = ring;
+ }
+
+ // ----------------------------------------------------------------- anchors
+ // Replace the authored placeholder anchors with the venue GLB's resolved set
+ // (prompt 02). Merges so a partial set still keeps sensible defaults, and
+ // re-seats the player at the new spawn if they haven't moved yet.
+ setAnchors(next) {
+ if (!next) return;
+ this.anchors = {
+ spawn: next.spawn || this.anchors.spawn,
+ screens: Array.isArray(next.screens) ? next.screens : this.anchors.screens,
+ desk: next.desk || this.anchors.desk,
+ lights: Array.isArray(next.lights) ? next.lights : this.anchors.lights,
+ };
+ return this.anchors;
+ }
+
+ // Move the local player to the current spawn anchor (called once the avatar is
+ // attached, and re-usable by 02 after the venue resolves its real spawn).
+ seatAtSpawn() {
+ const s = this.anchors.spawn;
+ if (!s) return;
+ this.localPos.set(s.position.x, 0, s.position.z);
+ this.localYaw = s.rotationY || 0;
+ this.vy = 0; this.grounded = true; this.motion = 'idle';
+ if (this.localRig) { this.localRig.position.copy(this.localPos); this.localRig.rotation.y = this.localYaw; }
+ }
+
+ // --------------------------------------------------------------- updatables
+ // Register an object with an update(dt) method to be ticked each frame. Returns
+ // an unregister function. 03/04 hook their screen + desk handles here.
+ registerUpdatable(obj) {
+ if (!obj || typeof obj.update !== 'function') {
+ throw new Error('OmniologyArena.registerUpdatable: object needs an update(dt) method');
+ }
+ this._updatables.add(obj);
+ return () => this._updatables.delete(obj);
+ }
+
+ // ------------------------------------------------------------ local avatar
+ // The entry module loads the local avatar via the shared avatar-rig library
+ // and hands the rig + animation manager here; the loop then drives its
+ // position, yaw, and idle/walk crossfade. Passing null detaches it.
+ attachLocalAvatar(rig, anim, height) {
+ this.localRig = rig || null;
+ this.localAnim = anim || null;
+ this.localHeight = height || 1.7;
+ if (this.localRig) {
+ this.localRig.position.copy(this.localPos);
+ this.localRig.rotation.y = this.localYaw;
+ if (!this.localRig.parent) this.scene.add(this.localRig);
+ }
+ }
+
+ // The authoritative local state to stream to peers (CommunityNet.sendMove).
+ getLocalState() {
+ return {
+ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z,
+ yaw: this.localYaw, motion: this.motion,
+ };
+ }
+
+ // Project a world point to CSS pixels for DOM overlays (nameplates, bubbles).
+ // Returns { x, y, visible }. Shared by RemotePlayer for label placement.
+ project(worldVec, into = null) {
+ const v = (into || new Vector3()).copy(worldVec).project(this.camera);
+ const w = this.renderer.domElement.clientWidth;
+ const h = this.renderer.domElement.clientHeight;
+ return {
+ x: (v.x * 0.5 + 0.5) * w,
+ y: (-v.y * 0.5 + 0.5) * h,
+ visible: v.z > -1 && v.z < 1,
+ };
+ }
+
+ // --------------------------------------------------------------- input
+ _bindInput() {
+ window.addEventListener('keydown', this._onKeyDown);
+ window.addEventListener('keyup', this._onKeyUp);
+ this.canvas.addEventListener('pointerdown', this._onPointerDown);
+ window.addEventListener('pointerup', this._onPointerUp);
+ window.addEventListener('pointermove', this._onPointerMove);
+ this.canvas.addEventListener('wheel', this._onWheel, { passive: false });
+ }
+
+ _onKeyDown(e) {
+ // Don't steal typing focus from any future HUD input.
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (e.code === 'Space') { e.preventDefault(); this._jump(); return; }
+ this.keys.add(e.key.toLowerCase());
+ }
+ _onKeyUp(e) { this.keys.delete(e.key.toLowerCase()); }
+
+ _onPointerDown(e) {
+ this._dragging = true;
+ this._lastPtr = { x: e.clientX, y: e.clientY };
+ }
+ _onPointerUp() { this._dragging = false; }
+ _onPointerMove(e) {
+ if (!this._dragging || !this._lastPtr) return;
+ const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;
+ this._lastPtr = { x: e.clientX, y: e.clientY };
+ this.camYaw -= dx * 0.005;
+ this.camPitch = Math.max(0.1, Math.min(1.2, this.camPitch + dy * 0.004));
+ }
+ _onWheel(e) {
+ e.preventDefault();
+ this.camDist = Math.max(4, Math.min(20, this.camDist * (e.deltaY > 0 ? 1.1 : 0.9)));
+ }
+
+ // Self-contained pointer-events joystick (touch + mouse-drag) — same contract
+ // and deadzone as /play, no external lib. Sums with WASD in _stepLocal.
+ _initJoystick() {
+ const zone = document.getElementById('cc-joystick');
+ if (!zone) return;
+ this._joyZone = zone;
+ const base = document.createElement('div');
+ base.className = 'cc-joy-base';
+ const thumb = document.createElement('div');
+ thumb.className = 'cc-joy-thumb';
+ base.appendChild(thumb);
+ zone.appendChild(base);
+ this._joyNodes = [base, thumb];
+
+ const RADIUS = 48;
+ let activeId = null;
+ const setFromPointer = (clientX, clientY) => {
+ const r = base.getBoundingClientRect();
+ const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
+ let dx = (clientX - cx) / RADIUS, dy = (clientY - cy) / RADIUS;
+ const m = Math.hypot(dx, dy);
+ if (m > 1) { dx /= m; dy /= m; }
+ thumb.style.transform = `translate(${dx * RADIUS}px, ${dy * RADIUS}px)`;
+ const mag = Math.min(1, m);
+ if (mag < JOY_DEADZONE) { this._joy = null; return; }
+ const k = (mag - JOY_DEADZONE) / (1 - JOY_DEADZONE) / mag;
+ this._joy = { x: dx * k, z: dy * k };
+ };
+ const release = () => {
+ activeId = null; this._joy = null;
+ thumb.style.transform = 'translate(0px, 0px)';
+ zone.classList.remove('cc-joy-active');
+ };
+ const onDown = (e) => {
+ activeId = e.pointerId;
+ zone.setPointerCapture(e.pointerId);
+ zone.classList.add('cc-joy-active');
+ setFromPointer(e.clientX, e.clientY);
+ e.preventDefault();
+ };
+ const onMove = (e) => { if (e.pointerId === activeId) { setFromPointer(e.clientX, e.clientY); e.preventDefault(); } };
+ const onUp = (e) => { if (e.pointerId === activeId) release(); };
+ zone.addEventListener('pointerdown', onDown);
+ zone.addEventListener('pointermove', onMove);
+ zone.addEventListener('pointerup', onUp);
+ zone.addEventListener('pointercancel', onUp);
+ zone.addEventListener('lostpointercapture', onUp);
+ // Kept for teardown.
+ this._joyHandlers = { onDown, onMove, onUp };
+ }
+
+ _jump() {
+ if (!this.grounded) return;
+ this.vy = JUMP_VELOCITY;
+ this.grounded = false;
+ }
+
+ // ---------------------------------------------------------------- loop
+ _loop() {
+ this._raf = requestAnimationFrame(this._loop);
+ const now = performance.now();
+ const dt = Math.min(0.05, (now - this._last) / 1000);
+ this._last = now;
+
+ this._stepLocal(dt);
+ this.localAnim?.update(dt);
+ for (const u of this._updatables) {
+ try { u.update(dt); } catch (err) { log.warn('[arena] updatable threw:', err?.message); }
+ }
+ this._updateCamera();
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ _stepLocal(dt) {
+ // Vertical integration first so a jump arcs even while standing still.
+ if (!this.grounded) {
+ this.vy -= GRAVITY * dt;
+ this.localPos.y += this.vy * dt;
+ if (this.localPos.y <= 0) { this.localPos.y = 0; this.vy = 0; this.grounded = true; }
+ }
+
+ // Movement intent from keys + joystick, mapped into the camera's basis so the
+ // controls read screen-relative (W goes away from the camera, D tracks right).
+ let ix = 0, iz = 0;
+ if (this.keys.has('w') || this.keys.has('arrowup')) iz -= 1;
+ if (this.keys.has('s') || this.keys.has('arrowdown')) iz += 1;
+ if (this.keys.has('a') || this.keys.has('arrowleft')) ix -= 1;
+ if (this.keys.has('d') || this.keys.has('arrowright')) ix += 1;
+ if (this._joy) { ix += this._joy.x; iz += this._joy.z; }
+ const running = this.keys.has('shift');
+ const mag = Math.hypot(ix, iz);
+ if (mag > 0.05) {
+ ix /= Math.max(1, mag); iz /= Math.max(1, mag);
+ const sin = Math.sin(this.camYaw), cos = Math.cos(this.camYaw);
+ const wx = ix * cos - iz * sin;
+ const wz = -ix * sin - iz * cos;
+ const speed = running ? RUN_SPEED : MOVE_SPEED;
+ this.localPos.x += wx * speed * dt;
+ this.localPos.z += wz * speed * dt;
+ const r = Math.hypot(this.localPos.x, this.localPos.z);
+ if (r > ARENA_RADIUS) { this.localPos.x *= ARENA_RADIUS / r; this.localPos.z *= ARENA_RADIUS / r; }
+ this.localYaw = Math.atan2(wx, wz);
+ const want = running ? 'run' : 'walk';
+ if (this.motion !== want) { this.motion = want; this.localAnim?.crossfadeTo(CLIP_WALK, 0.18); }
+ } else if (this.motion !== 'idle') {
+ this.motion = 'idle';
+ this.localAnim?.crossfadeTo(CLIP_IDLE, 0.2);
+ }
+ // Drive the walk cycle faster while sprinting so it reads as a run.
+ if (this.localAnim?.currentName === CLIP_WALK) {
+ this.localAnim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);
+ }
+ if (this.localRig) { this.localRig.position.copy(this.localPos); this.localRig.rotation.y = this.localYaw; }
+ }
+
+ _updateCamera() {
+ // Track the avatar on the ground plane only — ignore jump height so the
+ // camera stays planted while the character hops.
+ const tx = this.localPos.x, tz = this.localPos.z;
+ const cp = Math.cos(this.camPitch), sp = Math.sin(this.camPitch);
+ const ox = Math.sin(this.camYaw) * cp * this.camDist;
+ const oz = Math.cos(this.camYaw) * cp * this.camDist;
+ const oy = sp * this.camDist + 1.4;
+ this.camera.position.set(tx - ox, oy, tz - oz);
+ this.camera.lookAt(tx, 1.4, tz);
+ }
+
+ _onResize() {
+ this.camera.aspect = window.innerWidth / window.innerHeight;
+ this.camera.updateProjectionMatrix();
+ this.renderer.setSize(window.innerWidth, window.innerHeight);
+ }
+
+ // ---------------------------------------------------------------- teardown
+ // Full teardown modeled on coincommunities.js leave(): stop the loop, drop every
+ // listener, dispose all GPU resources (geometry/material/texture), and free the
+ // renderer so navigating away leaks nothing. The entry module disposes its own
+ // net + avatars first, then calls this.
+ dispose() {
+ if (this._disposed) return;
+ this._disposed = true;
+
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('keydown', this._onKeyDown);
+ window.removeEventListener('keyup', this._onKeyUp);
+ window.removeEventListener('pointerup', this._onPointerUp);
+ window.removeEventListener('pointermove', this._onPointerMove);
+ this.canvas.removeEventListener('pointerdown', this._onPointerDown);
+ this.canvas.removeEventListener('wheel', this._onWheel);
+
+ // Joystick listeners + DOM.
+ if (this._joyZone && this._joyHandlers) {
+ const z = this._joyZone, h = this._joyHandlers;
+ z.removeEventListener('pointerdown', h.onDown);
+ z.removeEventListener('pointermove', h.onMove);
+ z.removeEventListener('pointerup', h.onUp);
+ z.removeEventListener('pointercancel', h.onUp);
+ z.removeEventListener('lostpointercapture', h.onUp);
+ }
+ for (const n of this._joyNodes || []) n.remove();
+ this._joyNodes = null; this._joyHandlers = null;
+
+ this._updatables.clear();
+
+ // Detach (but don't dispose) the local avatar — the entry module owns it.
+ if (this.localRig?.parent) this.localRig.parent.remove(this.localRig);
+ this.localRig = null; this.localAnim = null;
+
+ // Dispose every GPU resource still in the scene graph.
+ const seenMat = new Set();
+ const disposeMaterial = (m) => {
+ if (!m || seenMat.has(m)) return;
+ seenMat.add(m);
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap', 'envMap']) {
+ m[k]?.dispose?.();
+ }
+ m.dispose?.();
+ };
+ this.scene?.traverse((obj) => {
+ obj.geometry?.dispose?.();
+ const mat = obj.material;
+ if (Array.isArray(mat)) mat.forEach(disposeMaterial); else disposeMaterial(mat);
+ });
+ // GridHelper materials/geometry live outside the standard mesh fields above.
+ this._grid?.geometry?.dispose?.();
+ if (this._grid) { (Array.isArray(this._grid.material) ? this._grid.material : [this._grid.material]).forEach((m) => m?.dispose?.()); }
+ this.scene?.clear?.();
+ this._envObjects = null;
+
+ this.renderer?.dispose?.();
+ this.renderer?.forceContextLoss?.();
+ this.renderer = null;
+ this.scene = null;
+ this.camera = null;
+ }
+}
diff --git a/src/game/arena/contest-screens.js b/src/game/arena/contest-screens.js
new file mode 100644
index 000000000..7fe59c337
--- /dev/null
+++ b/src/game/arena/contest-screens.js
@@ -0,0 +1,202 @@
+// Contest Screens — the shared polling controller and arena mount helper.
+//
+// One poller serves every screen on the Arena's walls: it polls Omniology's live
+// feed on an interval tuned to the ~88-second contest cadence, fans the same
+// NormalizedFeed out to each screen's applyFeed(), and never issues a duplicate
+// request per screen. It pauses while the tab is hidden (no point polling a feed
+// nobody can see) and resumes — with an immediate catch-up poll — on focus. When
+// it detects that the current round has just closed, it re-polls quickly to catch
+// the flip to the next round so the countdown stays in sync across the boundary.
+// On error it backs off, keeps retrying, and tells the screens to render their
+// designed, auto-retrying error state.
+//
+// mountContestScreens() is the integration point the Arena bootstrap (prompt 01)
+// calls: it creates one contest-screen per resolved venue anchor (prompt 02),
+// registers each as an updatable so it redraws every frame, wires them to the
+// single poller, and hands back a `pushEntry` so the entry desk (prompt 04) can
+// optimistically push a settled submission to every screen.
+//
+// Contract: docs/omniology-arena/CONTRACTS.md §2.2, §2.4.
+
+import { fetchLiveFeed } from './omniology-adapter.js';
+import { createContestScreen } from './contest-screen.js';
+
+const BASE_POLL_MS = 5000; // steady-state cadence (the ~88s round repolls ~17×)
+const FLIP_POLL_MS = 1500; // fast repoll right after a detected round close
+const ERROR_BASE_MS = 5000; // first backoff step on error
+const ERROR_MAX_MS = 30000; // backoff ceiling
+const FLIP_GRACE_MS = 4000; // how long after close we keep fast-polling for the flip
+
+/**
+ * Create the single shared poller. Drives one in-flight request at a time and
+ * pushes each NormalizedFeed to onFeed; routes errors to onError. Visibility-aware.
+ *
+ * @param {{ onFeed:(feed)=>void, onError:(err)=>void, pollMs?:number,
+ * getNow?:()=>number, fetchFeed?:()=>Promise<any> }} opts
+ * @returns {{ start, stop, pollNow, dispose, isRunning }}
+ */
+export function createContestPoller(opts = {}) {
+ const onFeed = typeof opts.onFeed === 'function' ? opts.onFeed : () => {};
+ const onError = typeof opts.onError === 'function' ? opts.onError : () => {};
+ const pollMs = opts.pollMs || BASE_POLL_MS;
+ const now = opts.getNow || (() => Date.now());
+ const doFetch = opts.fetchFeed || fetchLiveFeed;
+
+ let timer = null;
+ let inFlight = false;
+ let destroyed = false;
+ let running = false;
+ let errorStreak = 0;
+ let skewMs = 0; // server - client drift, to time the round flip
+ let closesMs = null; // current round close on the server clock
+ let visHandler = null;
+
+ function correctedNow() { return now() + skewMs; }
+
+ function schedule(ms) {
+ clearTimeout(timer);
+ if (destroyed || !running) return;
+ timer = setTimeout(tick, ms);
+ }
+
+ // Decide the delay until the next poll. Around a round close we poll fast to
+ // catch the flip; otherwise steady-state, unless we're backing off from errors.
+ function nextDelay() {
+ if (errorStreak > 0) return backoffDelay(errorStreak, ERROR_BASE_MS, ERROR_MAX_MS);
+ if (closesMs != null) {
+ const rem = closesMs - correctedNow();
+ if (rem <= FLIP_GRACE_MS) return FLIP_POLL_MS; // closing / just closed
+ }
+ return pollMs;
+ }
+
+ async function tick() {
+ if (destroyed || !running) return;
+ if (isHidden()) return; // visibilitychange will resume us
+ if (inFlight) { schedule(pollMs); return; }
+ inFlight = true;
+ try {
+ const feed = await doFetch();
+ errorStreak = 0;
+ if (feed) {
+ skewMs = Number(feed.serverNowMs) - now();
+ closesMs = feed.current ? feed.current.closesMs : null;
+ onFeed(feed);
+ }
+ } catch (err) {
+ errorStreak += 1;
+ onError(err);
+ } finally {
+ inFlight = false;
+ schedule(nextDelay());
+ }
+ }
+
+ function onVisibility() {
+ if (destroyed || !running) return;
+ if (isHidden()) {
+ clearTimeout(timer); // pause — no polling while nobody's watching
+ } else {
+ pollNow(); // resume with an immediate catch-up
+ }
+ }
+
+ function pollNow() {
+ if (destroyed || !running) return;
+ clearTimeout(timer);
+ tick();
+ }
+
+ function start() {
+ if (destroyed || running) return;
+ running = true;
+ if (typeof document !== 'undefined' && document.addEventListener) {
+ visHandler = onVisibility;
+ document.addEventListener('visibilitychange', visHandler);
+ }
+ pollNow();
+ }
+
+ function stop() {
+ running = false;
+ clearTimeout(timer);
+ }
+
+ function dispose() {
+ destroyed = true;
+ stop();
+ if (visHandler && typeof document !== 'undefined' && document.removeEventListener) {
+ document.removeEventListener('visibilitychange', visHandler);
+ }
+ visHandler = null;
+ }
+
+ return {
+ start, stop, pollNow, dispose,
+ isRunning: () => running,
+ };
+}
+
+/**
+ * Exponential backoff with a ceiling. attempt is 1-based (first error → base).
+ * @param {number} attempt
+ * @param {number} [base]
+ * @param {number} [max]
+ * @returns {number}
+ */
+export function backoffDelay(attempt, base = ERROR_BASE_MS, max = ERROR_MAX_MS) {
+ const ms = base * Math.pow(2, Math.max(0, attempt - 1));
+ return Math.min(max, ms);
+}
+
+function isHidden() {
+ return typeof document !== 'undefined' && document.hidden === true;
+}
+
+/**
+ * Mount one contest-screen per Arena venue anchor and wire them all to one poller.
+ * Called by the Arena bootstrap (prompt 01) once the venue anchors (prompt 02) are
+ * resolved. Each anchor in `arena.anchors.screens[]` is `{ position, rotationY?,
+ * width?, role? }`. By default the three walls take distinct roles (now-playing,
+ * leaderboard, winners); pass `opts.roles` to override.
+ *
+ * @param {{ scene:THREE.Scene, anchors:{screens:Array}, registerUpdatable:(o)=>void }} arena
+ * @param {{ roles?:string[], pollMs?:number, frame?:boolean }} [opts]
+ * @returns {{ screens, poller, pushEntry:(entry)=>void, dispose:()=>void }}
+ */
+export function mountContestScreens(arena, opts = {}) {
+ const anchors = arena?.anchors?.screens || [];
+ const defaultRoles = opts.roles || ['now', 'leaderboard', 'winners'];
+
+ const screens = anchors.map((a, i) => {
+ const screen = createContestScreen(arena.scene, {
+ position: a.position,
+ rotationY: a.rotationY ?? 0,
+ width: a.width,
+ role: a.role || defaultRoles[i % defaultRoles.length],
+ frame: opts.frame ?? a.frame,
+ });
+ screen.setStatus('loading');
+ if (typeof arena.registerUpdatable === 'function') arena.registerUpdatable(screen);
+ return screen;
+ });
+
+ const poller = createContestPoller({
+ pollMs: opts.pollMs,
+ onFeed: (feed) => { for (const s of screens) s.applyFeed(feed); },
+ onError: () => { for (const s of screens) s.setStatus('error'); },
+ });
+ poller.start();
+
+ return {
+ screens,
+ poller,
+ // Optimistic insert from the entry desk (prompt 04) — show the entry on
+ // every screen the instant a submission settles, before the next poll.
+ pushEntry: (entry) => { for (const s of screens) s.pushEntry(entry); },
+ dispose: () => {
+ poller.dispose();
+ for (const s of screens) s.dispose();
+ },
+ };
+}
diff --git a/src/game/arena/omniology-adapter.js b/src/game/arena/omniology-adapter.js
index 482c19a77..ae930d627 100644
--- a/src/game/arena/omniology-adapter.js
+++ b/src/game/arena/omniology-adapter.js
@@ -168,6 +168,124 @@ export function submitEntryRequest(contestId, entry, agent) {
};
}
+// ── compose schema + local validation (entry desk, prompt 04) ──────────────────
+//
+// Omniology's exact entry fields are pending QUESTIONS-FOR-OMNIOLOGY.md #6. This
+// is the documented default contract and the SINGLE place to update when the
+// partner confirms — the desk's compose UI renders itself from ENTRY_FIELDS, so a
+// field change never touches entry-desk.js. Validation runs BEFORE any payment so
+// a doomed entry is never charged (acceptance criteria + QUESTIONS #10).
+
+/**
+ * @typedef {object} EntryField
+ * @property {string} key
+ * @property {string} label
+ * @property {'text'|'textarea'|'url'} type
+ * @property {boolean} required
+ * @property {number} [max] max characters
+ * @property {string} [placeholder]
+ * @property {string} [hint]
+ */
+
+/** @type {EntryField[]} */
+export const ENTRY_FIELDS = [
+ { key: 'title', label: 'Title', type: 'text', required: true, max: 80, placeholder: 'Name your entry', hint: 'Shown on the leaderboard.' },
+ { key: 'prompt', label: 'Your entry', type: 'textarea', required: true, max: 600, placeholder: 'What are you submitting to this round?', hint: 'This is what gets judged.' },
+ { key: 'media_url', label: 'Image or model URL', type: 'url', required: false, placeholder: 'https://… (optional)', hint: 'Optional HTTPS link to an image or 3D model.' },
+];
+
+/**
+ * Trim string fields and drop empty optionals so the wire body is clean and
+ * deterministic. Required-but-empty fields are kept as '' so validateEntry can
+ * flag them (rather than silently omitting and shipping an incomplete entry).
+ * @param {object} values raw compose-form values
+ * @returns {object}
+ */
+export function normalizeEntry(values) {
+ const src = values && typeof values === 'object' ? values : {};
+ const out = {};
+ for (const f of ENTRY_FIELDS) {
+ const raw = src[f.key];
+ const val = typeof raw === 'string' ? raw.trim() : raw;
+ if (val === undefined || val === null || val === '') {
+ if (f.required) out[f.key] = '';
+ continue;
+ }
+ out[f.key] = val;
+ }
+ return out;
+}
+
+/**
+ * Validate a compose-form entry against Omniology's documented rules locally,
+ * before payment. Returns { ok, errors:{ [field]: message } }.
+ * @param {object} values
+ * @returns {{ ok:boolean, errors:Record<string,string> }}
+ */
+export function validateEntry(values) {
+ const entry = normalizeEntry(values);
+ const errors = {};
+ for (const f of ENTRY_FIELDS) {
+ const val = entry[f.key];
+ if (f.required && (val == null || !String(val).length)) {
+ errors[f.key] = `${f.label} is required.`;
+ continue;
+ }
+ if (val == null || val === '') continue; // empty optional — nothing to check
+ const s = String(val);
+ if (f.max && s.length > f.max) {
+ errors[f.key] = `${f.label} must be ${f.max} characters or fewer.`;
+ continue;
+ }
+ if (f.type === 'url') {
+ let ok = false;
+ try { ok = new URL(s).protocol === 'https:'; } catch { ok = false; }
+ if (!ok) errors[f.key] = 'Enter a valid https:// link, or leave it blank.';
+ }
+ }
+ return { ok: Object.keys(errors).length === 0, errors };
+}
+
+/**
+ * How entries are priced — selected by config, NEVER a hardcoded flag in the desk:
+ * 'auto' (default) — let /api/x402-pay probe the submit URL: a 402 ⇒ paid (real
+ * x402 USDC), a plain 200 ⇒ free (no funds move).
+ * 'free' — Omniology confirmed entries are free (QUESTIONS #7); the desk POSTs
+ * the submit URL directly and skips the payment stepper entirely.
+ * 'paid' — entries always carry a fee; the desk always runs the x402 flow.
+ * Reads `window.OMNIOLOGY_ENTRY_FEE`, then `<meta name="omniology-entry-fee">`,
+ * then VITE_OMNIOLOGY_ENTRY_FEE.
+ * @returns {'auto'|'free'|'paid'}
+ */
+export function entryFeeMode() {
+ let v = '';
+ if (typeof window !== 'undefined' && window.OMNIOLOGY_ENTRY_FEE) v = String(window.OMNIOLOGY_ENTRY_FEE);
+ if (!v && typeof document !== 'undefined') v = document.querySelector('meta[name="omniology-entry-fee"]')?.getAttribute('content') || '';
+ if (!v) { try { v = String(import.meta?.env?.VITE_OMNIOLOGY_ENTRY_FEE || ''); } catch (_) { /* node */ } }
+ v = v.trim().toLowerCase();
+ return v === 'free' || v === 'paid' ? v : 'auto';
+}
+
+/**
+ * Pull the player-facing confirmation out of Omniology's submit response. On the
+ * paid path the body arrives nested under the payer's result envelope
+ * ({ result: { entry_id, status, round, position } }); on the free path it is the
+ * bare body. Tolerant of either, and of string/number round/position, so the desk
+ * always shows a real confirmation rather than "undefined".
+ * @param {object} resultEnvelope
+ * @returns {{ entryId:string|null, status:string|null, round:number|null, position:number|null }}
+ */
+export function readEntryConfirmation(resultEnvelope) {
+ const env = resultEnvelope && typeof resultEnvelope === 'object' ? resultEnvelope : {};
+ const body = env.result && typeof env.result === 'object' ? env.result : env;
+ return {
+ entryId: body.entry_id ?? body.entryId ?? null,
+ status: body.status ?? null,
+ round: num(body.round),
+ position: num(body.position),
+ };
+}
+
// ── coercion helpers (defensive: the feed is external) ─────────────────────────
function nowMs() { return Date.now(); }
diff --git a/src/game/arena/omniology.js b/src/game/arena/omniology.js
new file mode 100644
index 000000000..311e984b0
--- /dev/null
+++ b/src/game/arena/omniology.js
@@ -0,0 +1,317 @@
+// Omniology Arena — entry module.
+//
+// Boots the OmniologyArena world, loads the local player's avatar through the
+// shared avatar-rig library (the same path /play uses), connects multiplayer
+// presence via CommunityNet to a namespaced `walk_world` instance, and renders
+// every remote player with a nameplate and smooth interpolation. No multiplayer
+// server changes: we join the existing `walk_world` room with a synthetic coin
+// token (`arena:omniology`, tier '') so Colyseus isolates the arena into its own
+// room instances, separate from every real coin world.
+//
+// Prompts 02–04 mount the venue GLB (via arena.setAnchors), the live contest
+// screens, and the entry desk on top — they register with the arena, they don't
+// edit this file.
+
+import { Group } from 'three';
+import { OmniologyArena, REMOTE_LERP, RUN_TIMESCALE } from './arena.js';
+import { AnimationManager } from '../../animation-manager.js';
+import { CommunityNet } from '../community-net.js';
+import {
+ resolveAvatarUrl, buildAvatar, loadManifest, CLIP_IDLE, CLIP_WALK,
+} from '../avatar-rig.js';
+import {
+ getRequestedAvatar, getPlayCosmetics, setPlayName, GUEST_SENTINEL, uploadPendingGuestAvatar, CC_NAME_KEY,
+} from '../play-handoff.js';
+import { log } from '../../shared/log.js';
+
+// The synthetic identity that namespaces the arena into its own walk_world
+// instances. NOT a coin — a stable room key. $THREE is the only coin the platform
+// references; this is plumbing (a room token), it names nothing tradeable.
+const ARENA_COIN = { mint: 'arena:omniology', name: 'Omniology Arena', symbol: 'OMNI', image: '' };
+
+// A networked peer: avatar rig + animation + nameplate, interpolated toward the
+// server's authoritative transform. A focused sibling of coincommunities.js's
+// RemotePlayer — it reuses the same avatar-rig library and the same REMOTE_LERP
+// interpolation, minus the /play-only cosmetics + mini-game coupling the arena
+// skeleton doesn't need. Registered as an arena updatable so it ticks each frame.
+class RemotePlayer {
+ constructor(arena, player) {
+ this.arena = arena;
+ this.scene = arena.scene;
+ this.rig = new Group();
+ this.anim = new AnimationManager();
+ this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z;
+ this.targetYaw = player.yaw; this.curYaw = player.yaw;
+ this.motion = player.motion || 'idle';
+ this.height = 1.7;
+ this._avatarUrl = null;
+ this._avatarToken = 0;
+ this._disposed = false;
+ this.rig.position.set(player.x, player.y, player.z);
+ this.scene.add(this.rig);
+
+ // Nameplate — reuses the shared .cc-label treatment from coincommunities.css.
+ this.label = document.createElement('div');
+ this.label.className = 'cc-label';
+ this.label.textContent = player.name || 'guest';
+ document.body.appendChild(this.label);
+
+ this.setAvatar(player.avatar);
+ }
+
+ setAvatar(url) {
+ if (url === this._avatarUrl) return;
+ this._avatarUrl = url;
+ this.rig.clear();
+ this.anim = new AnimationManager();
+ // Tag this load so a slower in-flight GLB can't attach after a newer swap.
+ const token = (this._avatarToken += 1);
+ const anim = this.anim;
+ resolveAvatarUrl(url).then((u) => buildAvatar(this.rig, u, anim).then(({ height }) => {
+ if (this._disposed || token !== this._avatarToken) return;
+ this.height = height;
+ anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0);
+ })).catch(() => {});
+ }
+
+ apply(player) {
+ this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z;
+ this.targetYaw = player.yaw;
+ if (player.name) this.label.textContent = player.name;
+ if (player.avatar !== this._avatarUrl) this.setAvatar(player.avatar);
+ if (player.motion !== this.motion) {
+ this.motion = player.motion;
+ this.anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0.18);
+ }
+ }
+
+ // Ticked by the arena loop: interpolate transform, advance animation, and
+ // re-anchor the nameplate above the head in screen space.
+ update(dt) {
+ this.rig.position.x += (this.targetX - this.rig.position.x) * REMOTE_LERP;
+ this.rig.position.y += (this.targetY - this.rig.position.y) * REMOTE_LERP;
+ this.rig.position.z += (this.targetZ - this.rig.position.z) * REMOTE_LERP;
+ let d = this.targetYaw - this.curYaw;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ this.curYaw += d * 0.2;
+ this.rig.rotation.y = this.curYaw;
+ if (this.anim.currentName === CLIP_WALK) this.anim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);
+ this.anim.update(dt);
+ this._placeLabel();
+ }
+
+ _placeLabel() {
+ const p = this.arena.project({ x: this.rig.position.x, y: this.rig.position.y + this.height + 0.2, z: this.rig.position.z });
+ if (!p.visible) { this.label.style.display = 'none'; return; }
+ this.label.style.display = '';
+ this.label.style.transform = `translate(-50%, -100%) translate(${p.x}px, ${p.y}px)`;
+ }
+
+ dispose() {
+ this._disposed = true;
+ this.scene.remove(this.rig);
+ this.rig.traverse((n) => {
+ n.geometry?.dispose?.();
+ const m = n.material;
+ if (Array.isArray(m)) m.forEach((x) => x?.dispose?.()); else m?.dispose?.();
+ });
+ this.label.remove();
+ }
+}
+
+// ----------------------------------------------------------------- status pill
+function setStatus(state, label) {
+ const pill = document.getElementById('arena-status');
+ if (!pill) return;
+ pill.dataset.state = state;
+ const text = pill.querySelector('.label');
+ if (text) text.textContent = label;
+}
+
+// Map CommunityNet status → a human pill state. Mirrors the honest states from
+// /play: connecting, online, reconnecting, single-player.
+function applyNetStatus(net, status) {
+ switch (status) {
+ case 'connecting': setStatus('connecting', 'Connecting'); break;
+ case 'online': setStatus('online', 'Live'); break;
+ case 'failed': setStatus('connecting', 'Reconnecting'); break;
+ case 'offline': setStatus('offline', 'Offline'); break;
+ case 'unavailable': setStatus('offline', 'Single-player'); break;
+ default: setStatus('connecting', 'Connecting');
+ }
+ // Let the player force a retry when we've given up.
+ const pill = document.getElementById('arena-status');
+ if (!pill) return;
+ if (status === 'offline') {
+ pill.dataset.retry = '1';
+ pill.title = 'Reconnect';
+ pill.onclick = () => net.retry();
+ } else {
+ pill.dataset.retry = '0';
+ pill.title = '';
+ pill.onclick = null;
+ }
+}
+
+// ----------------------------------------------------------------- boot
+async function hideLoader() {
+ const l = document.getElementById('kx-loading');
+ if (!l) return;
+ const boot = window.__ccBootAvatar;
+ try { await boot?.ready; } catch { /* proceed regardless */ }
+ l.classList.add('kx-hidden');
+ setTimeout(() => { try { boot?.dispose?.(); } catch {} l.remove(); }, 600);
+}
+
+async function start(canvas) {
+ const arena = new OmniologyArena(canvas);
+
+ // Kick the animation manifest fetch early (idempotent + cached); buildAvatar
+ // awaits it internally, so this just warms the cache.
+ loadManifest();
+
+ // Local avatar — resolved exactly like /play (?avatar= deep link → saved
+ // cc-avatar → default). A staged-but-not-yet-uploaded guest avatar can't be
+ // loaded by peers, so we join without one and broadcast the public URL once the
+ // background upload finishes.
+ const avatarInput = getRequestedAvatar();
+ const localRig = new Group();
+ const localAnim = new AnimationManager();
+ const url = await resolveAvatarUrl(avatarInput);
+ const { height, fallback } = await buildAvatar(localRig, url, localAnim);
+ arena.attachLocalAvatar(localRig, localAnim, height);
+ arena.seatAtSpawn();
+ if (fallback && avatarInput !== GUEST_SENTINEL) {
+ log.warn('[omniology] avatar failed to load — using stand-in:', url);
+ }
+
+ // Display name — reuse /play's persisted name (cc-name); mint a stable guest
+ // name if blank, and persist it so it sticks across worlds.
+ let name = '';
+ try { name = (localStorage.getItem(CC_NAME_KEY) || '').trim(); } catch { /* storage disabled */ }
+ if (!name) {
+ name = 'guest-' + Math.random().toString(36).slice(2, 6);
+ setPlayName(name);
+ }
+
+ const isGuest = avatarInput === GUEST_SENTINEL;
+ const netAvatar = isGuest
+ ? ''
+ : (/^https?:\/\//i.test(avatarInput) || avatarInput.startsWith('/') ? avatarInput : url);
+
+ // Connect presence. tier '' + an unset platform gate = open join (verified in
+ // WalkRoom.onAuth). The synthetic coin token isolates the arena room instances.
+ const net = new CommunityNet({
+ name,
+ avatar: netAvatar,
+ coin: ARENA_COIN,
+ tier: '',
+ cosmetics: getPlayCosmetics(),
+ });
+
+ const remotes = new Map(); // sessionId → RemotePlayer
+ const unregister = new Map(); // sessionId → arena unregister fn
+
+ const addRemote = (player, id) => {
+ if (id === net.sessionId) return; // that's us
+ if (remotes.has(id)) { remotes.get(id).apply(player); return; }
+ const r = new RemotePlayer(arena, player);
+ remotes.set(id, r);
+ unregister.set(id, arena.registerUpdatable(r));
+ };
+ const removeRemote = (id) => {
+ const r = remotes.get(id);
+ if (!r) return;
+ unregister.get(id)?.();
+ unregister.delete(id);
+ r.dispose();
+ remotes.delete(id);
+ };
+
+ net.on('status', ({ status }) => applyNetStatus(net, status));
+ net.on('add', (p, id) => addRemote(p, id));
+ net.on('change', (p, id) => { if (id !== net.sessionId) remotes.get(id)?.apply(p); });
+ net.on('remove', (id) => removeRemote(id));
+
+ // Stream our authoritative transform at the net's own 15Hz cadence. Registered
+ // as an arena updatable so it ticks inside the single render loop.
+ const mover = { update() { net.sendMove(arena.getLocalState()); } };
+ arena.registerUpdatable(mover);
+
+ if (isGuest) uploadPendingGuestAvatar((publicUrl) => net.setAvatar(publicUrl));
+
+ net.connect();
+
+ await hideLoader();
+
+ // Teardown: drop the socket, every remote, the local avatar, and the world so
+ // navigating away leaks no rAF, listeners, or GPU memory.
+ let torn = false;
+ const teardown = () => {
+ if (torn) return;
+ torn = true;
+ try { net.destroy(); } catch {}
+ for (const id of [...remotes.keys()]) removeRemote(id);
+ try {
+ localRig.traverse((n) => {
+ n.geometry?.dispose?.();
+ const m = n.material;
+ if (Array.isArray(m)) m.forEach((x) => x?.dispose?.()); else m?.dispose?.();
+ });
+ } catch {}
+ try { arena.dispose(); } catch {}
+ };
+ window.addEventListener('pagehide', teardown);
+ window.addEventListener('beforeunload', teardown);
+
+ // Expose for debugging + future HUD prompts (mirrors window.__CC__).
+ if (typeof window !== 'undefined') window.__ARENA__ = { arena, net, remotes, teardown };
+}
+
+// Swap the boot loader for an actionable error state when the world can't start
+// (most often WebGL unavailable), instead of a loader that never resolves.
+function renderBootError(err) {
+ log.error('[omniology] boot failed:', err);
+ const noWebGL = err?.code === 'NO_WEBGL' || /webgl|context/i.test(err?.message || '');
+ let overlay = document.getElementById('kx-loading');
+ if (!overlay) { overlay = document.createElement('div'); overlay.id = 'kx-loading'; document.body.appendChild(overlay); }
+ overlay.classList.remove('kx-hidden');
+ overlay.replaceChildren();
+ try { window.__ccBootAvatar?.dispose?.(); } catch {}
+
+ const card = document.createElement('div');
+ card.className = 'kx-loading-card kx-boot-error';
+ card.setAttribute('role', 'alert');
+ const mark = document.createElement('div');
+ mark.className = 'kx-loading-mark';
+ mark.textContent = noWebGL ? 'WebGL unavailable' : 'Couldn’t load the arena';
+ card.appendChild(mark);
+ const msg = document.createElement('p');
+ msg.className = 'kx-boot-error-msg';
+ msg.textContent = noWebGL
+ ? 'Your browser couldn’t start 3D graphics. Turn on hardware acceleration (or WebGL) and reload — on most browsers it’s under Settings › System.'
+ : 'Something went wrong starting the Omniology Arena. Reload to try again — if it keeps happening, your browser may be out of date.';
+ card.appendChild(msg);
+ const actions = document.createElement('div');
+ actions.className = 'kx-boot-error-actions';
+ const retry = document.createElement('button');
+ retry.type = 'button';
+ retry.className = 'kx-boot-error-btn';
+ retry.textContent = 'Try again';
+ retry.addEventListener('click', () => location.reload());
+ actions.appendChild(retry);
+ const home = document.createElement('a');
+ home.className = 'kx-boot-error-link';
+ home.href = '/';
+ home.textContent = 'Back to three.ws';
+ actions.appendChild(home);
+ card.appendChild(actions);
+ overlay.appendChild(card);
+ retry.focus();
+}
+
+const canvas = document.getElementById('kx-canvas');
+if (canvas) {
+ start(canvas).catch(renderBootError);
+}
diff --git a/tests/arena-contest-screen.test.js b/tests/arena-contest-screen.test.js
new file mode 100644
index 000000000..93bde4854
--- /dev/null
+++ b/tests/arena-contest-screen.test.js
@@ -0,0 +1,175 @@
+// Contest screen + poller — unit tests for the pure logic (CONTRACTS §2.2).
+//
+// The canvas rendering needs a real 2D context (not available headless), so these
+// pin the parts that carry the contract risk: the countdown formatting + drift
+// colouring, the ticker de-dup/cap, the shared poller's cadence, round-flip
+// fast-repoll, visibility pausing, and error backoff.
+
+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
+import {
+ formatCountdown,
+ countdownColor,
+ mergeTicker,
+} from '../src/game/arena/contest-screen.js';
+import {
+ createContestPoller,
+ backoffDelay,
+} from '../src/game/arena/contest-screens.js';
+
+describe('formatCountdown()', () => {
+ it('formats M:SS and floors at 0:00', () => {
+ expect(formatCountdown(88000)).toBe('1:28');
+ expect(formatCountdown(8000)).toBe('0:08');
+ expect(formatCountdown(0)).toBe('0:00');
+ expect(formatCountdown(-2000)).toBe('0:00');
+ });
+ it('handles null / non-finite', () => {
+ expect(formatCountdown(null)).toBe('—:—');
+ expect(formatCountdown(NaN)).toBe('—:—');
+ });
+});
+
+describe('countdownColor()', () => {
+ it('shifts calm → amber → red as the round closes', () => {
+ const calm = countdownColor(60000);
+ const warn = countdownColor(15000);
+ const danger = countdownColor(5000);
+ expect(calm).not.toBe(warn);
+ expect(warn).not.toBe(danger);
+ expect(countdownColor(60000)).toBe(calm); // stable above thresholds
+ expect(countdownColor(5000)).toBe(danger);
+ });
+});
+
+describe('mergeTicker()', () => {
+ it('dedupes by entryId, newest-first, capped', () => {
+ const existing = [
+ { entryId: 'b', agent: 'b', submittedMs: 200 },
+ { entryId: 'a', agent: 'a', submittedMs: 100 },
+ ];
+ const incoming = [
+ { entryId: 'c', agent: 'c', submittedMs: 300 },
+ { entryId: 'b', agent: 'b', submittedMs: 200 }, // dup — ignored
+ ];
+ const out = mergeTicker(existing, incoming, 10);
+ expect(out.map((e) => e.entryId)).toEqual(['c', 'b', 'a']);
+ });
+ it('caps to the requested length', () => {
+ const many = Array.from({ length: 30 }, (_, i) => ({ entryId: 's' + i, submittedMs: i }));
+ expect(mergeTicker([], many, 5)).toHaveLength(5);
+ });
+ it('collapses an optimistic entry once the feed confirms it (no double-count)', () => {
+ // applyFeed merges feed entries (incoming) over the existing buffer that
+ // holds the optimistic push — same entryId folds to a single, now-confirmed row.
+ const existing = [{ entryId: 'x1', agent: 'you', submittedMs: 500, optimistic: true }];
+ const incoming = [{ entryId: 'x1', agent: 'you', submittedMs: 500 }];
+ const out = mergeTicker(existing, incoming, 10);
+ expect(out).toHaveLength(1);
+ expect(out[0].optimistic).toBeUndefined(); // confirmed copy supersedes the optimistic one
+ });
+
+ it('lists a fresh optimistic push ahead of older entries', () => {
+ const existing = [{ entryId: 'old', agent: 'a', submittedMs: 100 }];
+ const pushed = [{ entryId: 'new', agent: 'you', submittedMs: 900, optimistic: true }];
+ const out = mergeTicker(existing, pushed, 10);
+ expect(out[0].entryId).toBe('new');
+ expect(out[0].optimistic).toBe(true);
+ });
+});
+
+describe('backoffDelay()', () => {
+ it('grows exponentially and caps', () => {
+ expect(backoffDelay(1, 5000, 30000)).toBe(5000);
+ expect(backoffDelay(2, 5000, 30000)).toBe(10000);
+ expect(backoffDelay(3, 5000, 30000)).toBe(20000);
+ expect(backoffDelay(4, 5000, 30000)).toBe(30000);
+ expect(backoffDelay(10, 5000, 30000)).toBe(30000);
+ });
+});
+
+describe('createContestPoller()', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => {
+ vi.useRealTimers();
+ delete globalThis.document;
+ });
+
+ function feedClosingIn(ms) {
+ const now = Date.now();
+ return {
+ ok: true, serverNowMs: now,
+ current: { id: 'c', round: 1, opensMs: now - 80000, closesMs: now + ms },
+ next: null, leaderboard: [], recentEntries: [], recentWinners: [],
+ };
+ }
+
+ it('polls immediately on start, then at the steady cadence', async () => {
+ const fetchFeed = vi.fn(async () => feedClosingIn(60000));
+ const onFeed = vi.fn();
+ const poller = createContestPoller({ fetchFeed, onFeed, onError: () => {}, pollMs: 5000 });
+ poller.start();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ expect(onFeed).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(fetchFeed).toHaveBeenCalledTimes(2);
+ poller.dispose();
+ });
+
+ it('fast-repolls right after a round closes to catch the flip', async () => {
+ // First feed closes in 1s; after the 1s steady? no — within FLIP grace, so
+ // the next delay is the fast 1.5s, not 5s.
+ const fetchFeed = vi.fn(async () => feedClosingIn(1000));
+ const poller = createContestPoller({ fetchFeed, onFeed: () => {}, onError: () => {}, pollMs: 5000 });
+ poller.start();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ // fast repoll fires at 1.5s, before the 5s steady cadence would
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(fetchFeed).toHaveBeenCalledTimes(2);
+ poller.dispose();
+ });
+
+ it('backs off and keeps retrying on error', async () => {
+ const fetchFeed = vi.fn(async () => { throw new Error('down'); });
+ const onError = vi.fn();
+ const poller = createContestPoller({ fetchFeed, onFeed: () => {}, onError, pollMs: 5000 });
+ poller.start();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(onError).toHaveBeenCalledTimes(1);
+ // first backoff step is 5s; nothing before then
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(fetchFeed).toHaveBeenCalledTimes(2);
+ poller.dispose();
+ });
+
+ it('stops polling after dispose', async () => {
+ const fetchFeed = vi.fn(async () => feedClosingIn(60000));
+ const poller = createContestPoller({ fetchFeed, onFeed: () => {}, onError: () => {}, pollMs: 5000 });
+ poller.start();
+ await vi.advanceTimersByTimeAsync(1);
+ poller.dispose();
+ await vi.advanceTimersByTimeAsync(20000);
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ });
+
+ it('pauses while the tab is hidden', async () => {
+ let hidden = false;
+ globalThis.document = {
+ get hidden() { return hidden; },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ };
+ const fetchFeed = vi.fn(async () => feedClosingIn(60000));
+ const poller = createContestPoller({ fetchFeed, onFeed: () => {}, onError: () => {}, pollMs: 5000 });
+ poller.start();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ hidden = true;
+ await vi.advanceTimersByTimeAsync(20000); // scheduled ticks no-op while hidden
+ expect(fetchFeed).toHaveBeenCalledTimes(1);
+ poller.dispose();
+ });
+});
diff --git a/tests/arena-omniology-adapter.test.js b/tests/arena-omniology-adapter.test.js
new file mode 100644
index 000000000..f0bd914fc
--- /dev/null
+++ b/tests/arena-omniology-adapter.test.js
@@ -0,0 +1,158 @@
+// Omniology adapter — unit tests for the wire→normalized boundary (CONTRACTS §2.1).
+//
+// The adapter is the ONLY module that knows Omniology's wire shapes, so this is
+// where the contract is pinned: base-URL resolution, the snake_case→camelCase /
+// unix-seconds→ms normalization, the no-mocks "unconfigured" surface, throwing on
+// HTTP error, and the frozen submitEntryRequest payload that prompt 04 depends on.
+
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import {
+ omniologyBase,
+ normalizeFeed,
+ fetchLiveFeed,
+ submitEntryRequest,
+} from '../src/game/arena/omniology-adapter.js';
+
+// A realistic feed straight from CONTRACTS §1.1.
+const WIRE = {
+ now_unix: 1719259200,
+ current: {
+ id: 'c_abc',
+ title: 'Best landscape',
+ round: 1421,
+ opened_unix: 1719259112,
+ closes_unix: 1719259200,
+ entries_count: 37,
+ prize_usdc: 12.5,
+ prize_asset: 'USDC',
+ },
+ next: { opens_unix: 1719259260 },
+ leaderboard: [
+ { rank: 1, entry_id: 'e1', agent: 'nova', score: 0.92, thumb_url: 'https://cdn.omniology.ai/e1.png' },
+ { rank: 2, entry_id: 'e2', agent: 'atlas', score: 0.81, thumb_url: null },
+ ],
+ recent_entries: [
+ { entry_id: 'e9', agent: 'zephyr', submitted_unix: 1719259190 },
+ ],
+ recent_winners: [
+ { round: 1420, agent: 'orion', prize_usdc: 11.0, tx: '5xSig' },
+ ],
+};
+
+describe('omniologyBase()', () => {
+ afterEach(() => {
+ delete globalThis.window;
+ delete globalThis.document;
+ });
+
+ it('returns empty string when nothing is configured', () => {
+ expect(omniologyBase()).toBe('');
+ });
+
+ it('reads window.OMNIOLOGY_BASE and strips trailing slashes', () => {
+ globalThis.window = { OMNIOLOGY_BASE: 'https://api.omniology.ai/' };
+ expect(omniologyBase()).toBe('https://api.omniology.ai');
+ });
+
+ it('reads the <meta name="omniology-base"> tag', () => {
+ globalThis.document = {
+ querySelector: (sel) =>
+ sel === 'meta[name="omniology-base"]'
+ ? { getAttribute: () => ' https://feed.omniology.ai/ ' }
+ : null,
+ };
+ expect(omniologyBase()).toBe('https://feed.omniology.ai');
+ });
+});
+
+describe('normalizeFeed()', () => {
+ it('maps the wire feed to camelCase / ms', () => {
+ const f = normalizeFeed(WIRE);
+ expect(f.ok).toBe(true);
+ expect(f.serverNowMs).toBe(1719259200 * 1000);
+ expect(f.current).toMatchObject({
+ id: 'c_abc',
+ title: 'Best landscape',
+ round: 1421,
+ opensMs: 1719259112000,
+ closesMs: 1719259200000,
+ entriesCount: 37,
+ prizeUsdc: 12.5,
+ prizeAsset: 'USDC',
+ });
+ expect(f.next).toEqual({ opensMs: 1719259260000 });
+ expect(f.leaderboard[0]).toMatchObject({ rank: 1, entryId: 'e1', agent: 'nova', score: 0.92 });
+ expect(f.leaderboard[0].thumbUrl).toBe('https://cdn.omniology.ai/e1.png');
+ expect(f.recentEntries[0]).toMatchObject({ entryId: 'e9', agent: 'zephyr', submittedMs: 1719259190000 });
+ expect(f.recentWinners[0]).toMatchObject({ round: 1420, agent: 'orion', prizeUsdc: 11, tx: '5xSig' });
+ });
+
+ it('tolerates nulls and missing fields without inventing data', () => {
+ const f = normalizeFeed({ now_unix: 1719259200, current: null, next: null });
+ expect(f.current).toBeNull();
+ expect(f.next).toBeNull();
+ expect(f.leaderboard).toEqual([]);
+ expect(f.recentEntries).toEqual([]);
+ expect(f.recentWinners).toEqual([]);
+ });
+
+ it('drops non-HTTPS thumbnails to null (designed monogram fallback)', () => {
+ const f = normalizeFeed({
+ ...WIRE,
+ leaderboard: [{ rank: 1, entry_id: 'e1', agent: 'nova', score: 0.5, thumb_url: 'http://insecure/x.png' }],
+ });
+ expect(f.leaderboard[0].thumbUrl).toBeNull();
+ });
+});
+
+describe('fetchLiveFeed()', () => {
+ afterEach(() => {
+ delete globalThis.window;
+ delete globalThis.document;
+ vi.unstubAllGlobals();
+ });
+
+ it('surfaces an unconfigured status (never fabricated data) when no base is set', async () => {
+ const f = await fetchLiveFeed();
+ expect(f.ok).toBe(false);
+ expect(f.reason).toBe('unconfigured');
+ expect(f.current).toBeNull();
+ expect(f.leaderboard).toEqual([]);
+ });
+
+ it('fetches and normalizes against a configured base', async () => {
+ globalThis.window = { OMNIOLOGY_BASE: 'https://api.omniology.ai' };
+ const fetchMock = vi.fn(async (url) => {
+ expect(url).toBe('https://api.omniology.ai/v1/contests/live');
+ return { ok: true, json: async () => WIRE };
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const f = await fetchLiveFeed();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(f.ok).toBe(true);
+ expect(f.current.round).toBe(1421);
+ });
+
+ it('throws on an HTTP error so the poller can drive the retry state', async () => {
+ globalThis.window = { OMNIOLOGY_BASE: 'https://api.omniology.ai' };
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 503 })));
+ await expect(fetchLiveFeed()).rejects.toThrow(/503/);
+ });
+});
+
+describe('submitEntryRequest()', () => {
+ afterEach(() => { delete globalThis.window; });
+
+ it('builds the frozen POST payload for the x402 desk flow', () => {
+ globalThis.window = { OMNIOLOGY_BASE: 'https://api.omniology.ai' };
+ const req = submitEntryRequest('c abc/1', { prompt: 'a cat' }, 'nova');
+ expect(req.method).toBe('POST');
+ expect(req.url).toBe('https://api.omniology.ai/v1/contests/c%20abc%2F1/entries');
+ expect(req.body).toEqual({ entry: { prompt: 'a cat' }, agent: 'nova' });
+ });
+
+ it('defaults a null agent and empty entry', () => {
+ const req = submitEntryRequest('c1');
+ expect(req.body).toEqual({ entry: {}, agent: null });
+ });
+});