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: extend Omniology Arena with atelier adapter, entry-desk tests, and contest screens

nirholasa325fa037b0a
diff --git a/docs/omniology-arena/CONTRACTS.md b/docs/omniology-arena/CONTRACTS.md
index c6490ea24..735c808f0 100644
--- a/docs/omniology-arena/CONTRACTS.md
+++ b/docs/omniology-arena/CONTRACTS.md
@@ -1,179 +1,204 @@
# Shared Contracts — Omniology Arena
-This file is the single source of truth for the interfaces that the build
-prompts share. If a shape changes, change it here and the prompts inherit it.
+Single source of truth for the interfaces the build prompts share. This version
+is written against **Omniology's real published API** (from omniology.ai/docs),
+not a proposed shape. If their API changes, change it here and prompts inherit it.
-There are two kinds of contracts:
-- **External** — what Omniology's service must expose (consumed by prompts 03, 04, 05).
-- **Internal** — module boundaries between our own prompts so they compose cleanly.
+> **Verify live before building.** Re-fetch `https://www.omniology.ai/docs` and,
+> if reachable, their OpenAPI/MCP descriptor at the engine base. Confirm field
+> names against a real response. Treat the shapes below as accurate-as-of-writing
+> but verify, since a wrong field name silently breaks the screens/desk.
+
+Engine base URL: **`https://omniology-engine.fly.dev`** · MCP endpoint: **`{base}/mcp`**
---
-## 1. External contract — Omniology service
+## 0. The big design facts (read first)
+
+- **Submission is NOT x402.** It is a **3-step handshake**: ask the engine to
+ build an entry transaction → **we sign it with the agent's key and broadcast it
+ to Solana ourselves** → confirm. So `/api/x402-pay` is the wrong tool for the
+ desk. Prompt 04 builds a dedicated server endpoint instead (see §2.4), reusing
+ the *safe primitives* from `api/x402-pay.js` (auth, CSRF, agent-keypair load,
+ SSRF-guarded fetch, spend caps) but implementing the handshake.
+- **We sign a transaction Omniology constructs.** This is the central risk. The
+ engine returns a base64 `pending_tx`; before signing we MUST decode and verify
+ it pays **exactly** `expected_fee_micro_usdc` USDC to the contest's
+ `deposit_address` and contains **no other instructions** (SECURITY.md C7).
+- **Fees are sub-cent** (e.g. 0.01–0.02 USDC) and Omniology is the Solana
+ fee-payer. A hard per-entry USDC cap (e.g. ≤ $0.10) makes worst-case loss
+ trivial even if their feed is compromised.
+- **Agents must register once** (ed25519 challenge) before they can enter.
+- **Eligibility is partly enforced by them**: OFAC screening + geo-block of AZ,
+ IA, MD, VT, WA (`GEO_BLOCKED`), VPN circumvention is a ToS violation. Confirm
+ whether *we* must also enforce geo for our users (open question).
+
+---
-> Verify the canonical Solana mainnet **USDC mint** by reading it from the repo
-> (`api/_lib/x402-spec.js` / `api/_lib/env.js`). Do **not** hardcode a mint from
-> memory. All amounts are atomic (USDC = 6 decimals; 1 USDC = `1000000`).
+## 1. External contract — Omniology engine
-### 1.1 Contest feed (read) — for the screens (prompt 03)
+> USDC amounts: `entry_fee_usdc` is human USDC; `expected_fee_micro_usdc` is
+> atomic (6 decimals). The canonical Solana mainnet USDC mint must be read from
+> the repo's x402 spec (`api/_lib/x402-spec.js` / `api/_lib/env.js`) — do not
+> paste a mint from memory — and cross-checked against the transfer in `pending_tx`.
-A single polled endpoint is enough. Free (no x402) is preferred for reads so the
-screens stay cheap to refresh.
+### 1.1 List active contests — feed for the screens (prompt 03)
```
-GET {OMNIOLOGY_BASE}/v1/contests/live
+GET {base}/v1/contests/active?track=ALL // ALL | ART | STORY | JOKE
Accept: application/json
-200 →
-{
- "now_unix": 1719259200, // server time, for countdown drift correction
- "current": {
- "id": "string",
- "title": "string",
- "round": 1421, // monotonically increasing round number
- "opened_unix": 1719259112,
- "closes_unix": 1719259200, // ~88s after opened
- "entries_count": 37,
- "prize_usdc": 12.5,
- "prize_asset": "USDC"
- },
- "next": { "opens_unix": 1719259200 } | null,
- "leaderboard": [ // for the CURRENT or most-recent round
- { "rank": 1, "entry_id": "string", "agent": "display name", "score": 0.92, "thumb_url": "https://…" | null }
- ],
- "recent_entries": [ // newest first, for the live ticker
- { "entry_id": "string", "agent": "display name", "submitted_unix": 1719259190 }
- ],
- "recent_winners": [ // last few rounds, for "past winners" panel
- { "round": 1420, "agent": "display name", "prize_usdc": 11.0, "tx": "solana sig" | null }
- ]
+200 → [ {
+ "contest_id": "uuid",
+ "track": "ART|STORY|JOKE",
+ "theme": "string",
+ "entry_fee_usdc": 0.02,
+ "current_pot_usdc": 1.84,
+ "current_entries": 92,
+ "time_remaining_seconds": 41,
+ "submission_closes_at": "ISO8601",
+ "judging_completes_at": "ISO8601",
+ "status": "open|collecting_submissions|judging|payout|closed|dispute",
+ "payload_format": "plain_text|markdown|base64_image",
+ "max_payload_chars": 280,
+ "deposit_address": "base58 pubkey", // per-contest pool address
+ "rubric": { "originality":"…","theme_alignment":"…","execution":"…","surprise":"…" }
+} … ]
+```
+
+### 1.2 Contest rules (optional, prompt 04 compose UI)
+
+```
+GET {base}/v1/contests/{contest_id} → same shape as one item above (+ rules detail)
+```
+
+### 1.3 Enter a contest — 3-step handshake (prompt 04, server-side)
+
+```
+// STEP 1 — request the unsigned entry transaction
+POST {base}/v1/contests/{contest_id}/enter
+{ "agent_id": "uuid", "payload": "string", "include_feedback": false }
+200 → {
+ "status": "pending_agent_signature",
+ "pending_tx": "base64 serialized Solana tx", // WE inspect + sign this
+ "entry_ticket_pda": "base58 pubkey",
+ "expected_fee_micro_usdc": 20000
}
+
+// STEP 2 — (our server) decode + VERIFY pending_tx (SECURITY.md C7), sign with the
+// agent keypair, broadcast to Solana, get the transaction_signature.
+
+// STEP 3 — confirm
+POST {base}/v1/contests/{contest_id}/enter
+{ "agent_id": "uuid", "payload": "string", "transaction_signature": "sig" }
+200 → { "status":"confirmed", "entry_id":"uuid", "accepted": true, "position": 93, "judging_at":"ISO8601" }
```
-Notes:
-- `closes_unix - now_unix` drives the on-screen countdown (the ~88s clock).
-- All `*_url` fields must be HTTPS and CORS-readable from `three.ws`, or proxied.
-- If a field is unknown, send `null` — never omit. Screens render designed empty
- states for nulls; they must not invent data.
+### 1.4 Entry status / result (prompt 04 follow-up, optional now)
+
+```
+GET {base}/v1/entries/{entry_id}
+200 → { "entry_id","contest_status":"judging|payout|closed","rank","total_entries",
+ "score","won","payout_amount_usdc","payout_tx":"sig|null","judge_feedback":"string|null" }
+```
-### 1.2 Submit entry (write, x402-priced) — for the desk (prompt 04)
+### 1.5 Agent registration — prerequisite for entering
```
-POST {OMNIOLOGY_BASE}/v1/contests/{contestId}/entries
-Content-Type: application/json
-Body: { "entry": { …partner-defined… }, "agent": "display name" | null }
+POST (engine, see docs) — register_agent
+{ "wallet_address":"base58", "message_body":"omniology-register-v1:<WALLET>:<UNIX_TS>",
+ "signed_message":"base58 ed25519 sig", "display_name"?, "specialty"?:["ART|STORY|JOKE"],
+ "operator_email"?, "model"? }
+// signed_message is base58 (NOT base64); timestamp within ±300s of server time.
```
-- **First call returns `402 Payment Required`** with a standard x402 challenge:
- - `scheme: "exact"`, `network: "solana-mainnet"`
- - `asset`: canonical Solana mainnet USDC mint (per repo)
- - `amount`: atomic USDC (the entry fee; may be `"0"` only if entry is free —
- but then there is nothing to pay and the desk uses a plain POST, see below)
- - `payTo`: Omniology's Solana receiver
- - `extra.feePayer`: a funded Solana account that co-signs (required for SVM exact)
- - `resource`: `{ url, description, serviceName: "Omniology" }`
-- Client signs + retries with `X-PAYMENT`. On success return `200` with:
- - header `X-PAYMENT-RESPONSE` (base64 receipt: `{ transaction, payer, network }`)
- - body: `{ "entry_id": "string", "status": "accepted", "round": 1421, "position": 38 }`
+### 1.6 MCP surface (already exists — `{base}/mcp`)
-If entry submission is **free** (no payment), say so in `QUESTIONS` — the desk
-will POST directly and skip x402 entirely. Do not return a `402` with `amount: 0`.
+Tools: `register_agent`, `list_active_contests`, `get_contest_rules`,
+`submit_entry`, `check_payout`, `get_my_history`, `get_leaderboard`,
+`get_theme_history`, `get_judge_rubric_explainer`. **`get_leaderboard` is the
+leaderboard source** — the REST `/active` feed does not include a leaderboard.
+Confirm whether there is a REST equivalent or whether screens consume the MCP tool.
-### 1.3 MCP surface (optional but preferred) — prompt 05
+### 1.7 Errors / limits
-The same two capabilities exposed as MCP tools so agents (not just our world)
-can use them, and so the service auto-registers in the x402 Bazaar:
-- `list_contests` / `get_contest` / `get_leaderboard` → read (1.1)
-- `submit_entry` → x402-priced write (1.2)
+`429 RATE_LIMITED` (+ `Retry-After`), `RATE_LIMITED_DUPLICATE_ENTRY`,
+`OFAC_SANCTIONED`, `GEO_BLOCKED`. New-contest creation pauses 08:00 & 20:00 UTC
+(1h); active contests still finish.
---
## 2. Internal contract — our modules
-These are the boundaries between prompts. Keep these signatures stable so each
-prompt can be built and tested independently.
-
### 2.1 `src/game/arena/omniology-adapter.js` (produced in 03, used by 03 & 04)
-
-The ONLY place that knows Omniology's wire shapes. Everything else consumes
-normalized objects, so swapping the real base URL is a one-file change.
+The only client module that knows Omniology shapes. Reads through OUR proxy
+(§2.5), never the engine directly (privacy + central enforcement, SECURITY.md C5).
```js
-// Config: reads base URL from <meta name="omniology-base"> or VITE_OMNIOLOGY_BASE.
-export function omniologyBase() // → string ('' if unconfigured)
-export async function fetchLiveFeed() // → NormalizedFeed (throws on network error)
-export function submitEntryRequest(contestId, entry, agent)
- // → { url, method:'POST', body } — the exact payload for /api/x402-pay external flow
-
-// NormalizedFeed:
-// {
-// ok: boolean,
-// serverNowMs: number,
-// current: { id, title, round, opensMs, closesMs, entriesCount, prizeUsdc } | null,
-// leaderboard: [{ rank, entryId, agent, score, thumbUrl }],
-// recentEntries: [{ entryId, agent, submittedMs }],
-// recentWinners: [{ round, agent, prizeUsdc, tx }]
+export function omniologyBase() // proxy base, from <meta name="omniology-base"> / VITE_OMNIOLOGY_BASE
+export async function fetchLiveFeed() // GET /active via proxy → NormalizedFeed (throws on net error)
+export async function fetchLeaderboard(contestId) // → [{ rank, agent, score, thumbUrl }]
+// NormalizedFeed: {
+// ok, serverNowMs,
+// contests: [{ id, track, theme, entryFeeUsdc, potUsdc, entries, closesMs,
+// status, payloadFormat, maxPayloadChars, depositAddress, rubric }],
+// current // the one to feature (soonest-closing 'open'/'collecting' contest) | null
// }
```
### 2.2 `src/game/arena/contest-screen.js` (produced in 03)
-
-Generalized live screen, modeled on `src/game/chart-screen.js`.
-
```js
-export function createContestScreen(scene, { position, width, rotationY }) // → handle
-// handle = {
-// group, // THREE.Group added to scene
-// update(dt), // call each frame; redraws ~10fps, advances countdown
-// applyFeed(normalizedFeed), // push latest poll result
-// pushEntry({ agent, entryId }),// optimistic live ticker insert (called by the desk)
-// setStatus('loading'|'live'|'empty'|'error'),
-// dispose()
-// }
+export function createContestScreen(scene, { position, width, rotationY, role })
+// role: 'now'|'leaderboard'|'winners'
+// handle = { group, update(dt), applyFeed(NormalizedFeed), applyLeaderboard(rows),
+// pushEntry({agent}), setStatus('loading'|'live'|'empty'|'error'|'unconfigured'), dispose() }
```
+The countdown uses `closesMs - serverNowMs` drift-corrected; a `track`/round
+change triggers a "new contest" sweep.
### 2.3 `src/game/arena/entry-desk.js` (produced in 04)
-
```js
export function createEntryDesk(scene, {
position, rotationY,
- getAgentId, // () → current player's paying agent id
- getContestId, // () → current contest id (from the adapter feed)
- buildEntry, // async () → entry object (opens the in-world compose UI)
- onSubmitted, // ({ entryId, agent, payment }) → void (wire to screen.pushEntry)
-}) // → handle { group, update(dt), interact(), dispose() }
+ getAgentId, // () → player's registered Omniology agent id (see 2.6)
+ getContest, // () → featured contest { id, theme, entryFeeUsdc, payloadFormat, maxPayloadChars }
+ composeEntry, // async (contest) → payload string (in-world compose UI, validates maxPayloadChars/format)
+ onConfirmed, // ({ entryId, position, payment }) → void (wire to screen.pushEntry)
+}) // → { group, update(dt), interact(), dispose() }
```
-The desk calls `POST /api/x402-pay` with
-`{ url, method, body }` from `submitEntryRequest(...)` plus the paying
-`agentId`, `Accept: text/event-stream`, and consumes the SSE sequence
-`challenge → built → settled → result` (or `error`). See prompt 04 for the
-verified event shapes and the reusable `_sse` parser from
-`src/game/agent-commerce.js`.
-
-### 2.4 Bootstrap registry (produced in 01)
-
-The arena bootstrap exposes mount points so 02/03/04 attach without editing each
-other:
-
-```js
-// src/game/arena/arena.js
-class OmniologyArena {
- scene, renderer, camera
- anchors // resolved from the venue GLB (02): { spawn, screens:[], desk, lights:[] }
- registerUpdatable(obj /* has update(dt) */) // 03/04 register their handles here
-}
-```
+### 2.4 Server endpoint `api/arena/omniology-enter.js` (produced in 04)
+The desk calls THIS, not `/api/x402-pay`. It performs the §1.3 handshake
+server-side (agent keys are custodial/server-side). Model its safety scaffolding
+on `api/x402-pay.js`:
+- `requireAuth` + `requireCsrf`; `agentId` must belong to the user (`loadAgentKeypairForUser`).
+- All engine calls through the SSRF-guarded `guardedFetch` (host-pinned to the engine).
+- `reserveSpendUsd` spend-cap reservation; plus a **hard per-entry cap** (≤ $0.10).
+- **C7 inspect-before-sign** on `pending_tx` (SECURITY.md) before signing/broadcast.
+- Streams SSE stages to the desk: `building → verifying → signed → broadcast → confirmed` (+ `error`).
+ (Mirror the `_sse` parser in `src/game/agent-commerce.js` on the client.)
+
+### 2.5 Server proxy `api/arena/omniology-feed.js` (produced in 03)
+Read-through, short-TTL cache (~5s, the 88s cadence is cheap) over
+`GET {engine}/v1/contests/active` and the leaderboard. Enforces response size
+limit + content-type (SECURITY.md C3) and strips/clamps partner strings (C4).
+The client only ever talks to this, never the engine.
+
+### 2.6 Registration
+Entering requires a registered Omniology agent (§1.5). Decide and document: do we
+register the player's three.ws agent on first desk use (server-side, signing the
+ed25519 challenge with the agent key), or require pre-registration? Prompt 04
+owns this; default to **lazy server-side registration on first entry**.
---
-## 3. Environment / config keys (no secrets in client)
+## 3. Config keys
| Key | Where | Purpose |
|---|---|---|
| `<meta name="game-server">` | `pages/arena/omniology.html` | Colyseus URL (copy from `pages/play.html`) |
-| `<meta name="omniology-base">` or `VITE_OMNIOLOGY_BASE` | page / build env | Omniology feed + submit base URL |
-| `X402_*` (agent wallet, facilitator, USDC) | server env (already set) | Used by `/api/x402-pay`; no client exposure |
+| `OMNIOLOGY_ENGINE_BASE` | server env | `https://omniology-engine.fly.dev` (used by the proxy + enter endpoints) |
+| `<meta name="omniology-base">` / `VITE_OMNIOLOGY_BASE` | page / build env | OUR proxy base (e.g. `/api/arena`) — never the engine directly |
+| `X402_*`, agent-wallet, RPC, facilitator | server env (already set) | reused for agent keypair load + Solana broadcast |
-The paying wallet and facilitator are server-side and already configured for the
-existing agent-commerce flow — prompt 04 reuses them, it does not add new secrets.
+No new client secrets. Agent signing is server-side only.
diff --git a/docs/omniology-arena/SECURITY.md b/docs/omniology-arena/SECURITY.md
index 619cbccc5..64ea4dea1 100644
--- a/docs/omniology-arena/SECURITY.md
+++ b/docs/omniology-arena/SECURITY.md
@@ -10,27 +10,43 @@ 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).
+## C7 — Inspect the transaction before signing (CRITICAL, blocks launch)
+**This is now the central control.** Omniology's real submit flow is NOT x402: the
+engine returns a base64 `pending_tx` that **we sign with the player's agent key
+and broadcast** (CONTRACTS §1.3). Signing a transaction a third party built is
+the highest-risk operation in the whole integration. Before signing, the server
+endpoint MUST fully decode `pending_tx` and assert ALL of:
+- It contains **exactly one** SPL `TransferChecked` of the USDC mint (canonical
+ mainnet mint read from the repo), for **exactly** `expected_fee_micro_usdc`,
+ to the contest's `deposit_address` from the **proxied** `/active` feed (not a
+ value pulled from the same step-1 response alone — cross-check against the feed).
+- **No other instructions**: no `Approve`/`SetAuthority`/delegate, no additional
+ transfers, no SOL movement charged to the agent, no unknown programs.
+- `feePayer` is **Omniology's** account, not the agent (they pay network fees).
+- A sane recent blockhash; reject if it tries to make the agent the fee payer.
+Reject and do not sign if any assertion fails. Cover this with a unit test that
+feeds a tampered `pending_tx` (wrong recipient, extra instruction, inflated
+amount) and asserts rejection.
-## 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.
+## C1 — Cross-check the recipient + cap the amount (CRITICAL, blocks launch)
+The `deposit_address` is **per-contest** (returned in the feed), so a single
+static allowlist doesn't fit. Instead:
+- The recipient is verified transitively by C7: the signed transfer must pay the
+ `deposit_address` that OUR server-side proxy fetched from `/active` over TLS —
+ not an address asserted only by the step-1 enter response.
+- Because the address is dynamic, the **hard per-entry USDC cap is the real
+ backstop**: reject any `expected_fee_micro_usdc` above a small ceiling (e.g.
+ ≤ $0.10). Sub-cent fees mean worst-case loss per entry is negligible even if
+ the engine is compromised. Surface the exact fee + contest to the player before
+ they confirm.
+- If Omniology ever asks us to sign anything that is not a single sub-cent USDC
+ transfer to a feed-published pool address, **stop** — that is the red flag.
+
+## C2 — (folded into C1)
+The Omniology flow has no separate attacker-set "amount" step to cap beyond the
+per-entry ceiling already covered in C1 + the transaction inspection in C7. Keep
+the rule: **show the player the exact fee + contest before they confirm; never
+sign silently.**
## C3 — Bound the response (required)
`guardedFetch` has a 20s timeout but **no body-size limit** — a malicious
diff --git a/pages/home.html b/pages/home.html
index fa01a3ea2..9d20fb923 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -4975,14 +4975,36 @@
for (const [k, v] of Object.entries(AGENT_ATTRS)) el.setAttribute(k, v);
return el;
}
+ async function fetchAvatarGlb(id) {
+ const r = await fetch(`${location.origin}/api/avatars/${id}`);
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ const d = await r.json();
+ const glb = devProxyGlb(d.avatar?.model_url || d.avatar?.url);
+ if (!glb) throw new Error('no model url');
+ return glb;
+ }
+ // The curated hero avatar can disappear (deleted, or a fresh deploy whose
+ // DB row hasn't been seeded yet) — fall back to a real featured avatar so
+ // the stage is never just an error card.
+ async function resolveFeaturedGlb() {
+ const r = await fetch(`${location.origin}/api/avatars/featured?limit=12`);
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ const d = await r.json();
+ const list = Array.isArray(d.avatars) ? d.avatars : [];
+ for (const a of list) {
+ try { return await fetchAvatarGlb(a.id); } catch (_) { /* try next */ }
+ }
+ throw new Error('no featured avatar with a model');
+ }
async function bootHeroAvatar() {
const heroInner = document.getElementById('hero-stage-inner');
try {
- const r = await fetch(`${location.origin}/api/avatars/${AVATAR_ID}`);
- if (!r.ok) throw new Error('HTTP ' + r.status);
- const d = await r.json();
- const glb = devProxyGlb(d.avatar?.model_url || d.avatar?.url);
- if (!glb) throw new Error('no model url');
+ let glb;
+ try {
+ glb = await fetchAvatarGlb(AVATAR_ID);
+ } catch (_) {
+ glb = await resolveFeaturedGlb();
+ }
if (heroInner) {
heroInner.innerHTML = '';
const heroEl = spawnAgent(glb);
diff --git a/src/game/arena/atelier-adapter.js b/src/game/arena/atelier-adapter.js
new file mode 100644
index 000000000..21a9b296a
--- /dev/null
+++ b/src/game/arena/atelier-adapter.js
@@ -0,0 +1,250 @@
+// Atelier adapter — the ONLY module that knows Atelier's marketplace wire shapes.
+//
+// Atelier (atelierai.xyz) is a "hire an AI agent" marketplace settling in USDC on
+// Solana/Base, with x402 as its native agent-to-agent rail. three.ws registers
+// into that economy as the 3D/avatar specialist; the Atelier World renders the
+// marketplace as a walkable plaza where each agent is a booth you walk up to and
+// hire. This adapter is the boundary: it reads the configured base URL, fetches
+// the raw agent registry, and normalizes it into the camelCase shape the rest of
+// the world consumes (atelier-plaza.js). Everything downstream speaks
+// NormalizedRoster / NormalizedAgent only — so swapping the real base URL, or
+// adapting to a wire-shape change, is a one-file edit here.
+//
+// No mocks, ever (CLAUDE.md): when no base URL is configured, fetchRoster()
+// surfaces an explicit `unconfigured` status — it NEVER fabricates marketplace
+// agents. The one always-present booth is the real three.ws 3D Studio (see
+// STUDIO_AGENT), which is a live product surface, not sample data.
+
+// ── config ───────────────────────────────────────────────────────────────────
+
+/**
+ * Resolve Atelier's base URL (no trailing slash) from, in priority order:
+ * 1. window.ATELIER_BASE — runtime override (tests / embeds)
+ * 2. <meta name="atelier-base"> — baked into the world page
+ * 3. VITE_ATELIER_BASE — build-time env
+ * Returns '' when nothing is configured, which fetchRoster() treats as the
+ * designed "unconfigured" state rather than an error.
+ * @returns {string}
+ */
+export function atelierBase() {
+ if (typeof window !== 'undefined' && window.ATELIER_BASE) {
+ return clean(window.ATELIER_BASE);
+ }
+ if (typeof document !== 'undefined') {
+ const v = document.querySelector('meta[name="atelier-base"]')?.getAttribute('content');
+ if (v && v.trim()) return clean(v);
+ }
+ try {
+ const env = import.meta?.env?.VITE_ATELIER_BASE;
+ if (env) return clean(String(env));
+ } catch (_) { /* import.meta unavailable outside a bundler (e.g. node tests) */ }
+ return '';
+}
+
+function clean(url) {
+ return String(url).trim().replace(/\/+$/, '');
+}
+
+// ── the always-present three.ws booth ──────────────────────────────────────────
+
+/**
+ * The three.ws 3D Studio — three.ws's own listing in the Atelier economy, the
+ * "make it 3D / make it move" specialist. Always rendered in the plaza (it's a
+ * real product surface: the forge), so the world is never empty and the strategy
+ * — three.ws registered as Atelier's 3D agent — is tangible the moment you walk
+ * in. `featured` floats it to the central dais; `internal` routes "hire" to the
+ * forge rather than the external x402 flow.
+ * @type {NormalizedAgent}
+ */
+export const STUDIO_AGENT = Object.freeze({
+ id: 'threews-studio',
+ name: 'three.ws 3D Studio',
+ tagline: 'Turn any character into a rigged, animated 3D avatar.',
+ specialty: '3D · Avatars · Rigging',
+ avatarUrl: '',
+ priceUsdc: 0,
+ pricePeriod: 'free lane + paid tiers',
+ rating: null,
+ jobsDone: null,
+ hireUrl: '/forge',
+ featured: true,
+ internal: true,
+});
+
+// ── read: agent roster ──────────────────────────────────────────────────────────
+
+/**
+ * GET {base}/v1/agents and normalize to NormalizedRoster.
+ *
+ * - Unconfigured (no base URL): resolves to a roster with `ok:false`,
+ * `reason:'unconfigured'`, and just the STUDIO_AGENT — never fabricated
+ * marketplace agents. The plaza renders its "connecting to Atelier" empty
+ * state around the studio dais.
+ * - Network / HTTP error: THROWS (the poller catches it and drives the designed,
+ * auto-retrying error state).
+ *
+ * @returns {Promise<NormalizedRoster>}
+ */
+export async function fetchRoster() {
+ const base = atelierBase();
+ if (!base) return unconfiguredRoster();
+
+ const res = await fetch(`${base}/v1/agents`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`Atelier roster HTTP ${res.status}`);
+ const data = await res.json();
+ return normalizeRoster(data, base);
+}
+
+/**
+ * Normalize Atelier's wire roster (snake_case, unix seconds) into the world's
+ * internal shape (camelCase, ms). Exported so the adapter's contract is unit
+ * testable without a live endpoint. Tolerant of nulls: an unknown field becomes
+ * null/empty, never invented. The STUDIO_AGENT is always prepended.
+ *
+ * @param {object} data
+ * @param {string} [base] resolved base URL, used to absolutize relative hire paths
+ * @returns {NormalizedRoster}
+ */
+export function normalizeRoster(data, base = '') {
+ const d = data || {};
+ const serverNowMs = secToMs(d.now_unix) ?? nowMs();
+ const agents = asArray(d.agents)
+ .map((a) => normalizeAgent(a, base))
+ .filter(Boolean);
+ return {
+ ok: true,
+ reason: null,
+ serverNowMs,
+ agents: [STUDIO_AGENT, ...agents],
+ };
+}
+
+/**
+ * Normalize a single wire agent. Returns null for an entry with no id (it can't
+ * be hired or addressed, so it's dropped rather than rendered as a dead booth).
+ * @param {object} a
+ * @param {string} [base]
+ * @returns {NormalizedAgent|null}
+ */
+export function normalizeAgent(a, base = '') {
+ if (!a || a.id == null) return null;
+ const id = str(a.id);
+ const hire = str(a.hire_url);
+ return {
+ id,
+ name: str(a.name) || 'Untitled agent',
+ tagline: str(a.tagline) || '',
+ specialty: str(a.specialty) || '',
+ avatarUrl: httpsUrl(a.avatar_url),
+ priceUsdc: num(a.price_usdc) ?? 0,
+ pricePeriod: str(a.price_period) || 'per task',
+ rating: num(a.rating),
+ jobsDone: num(a.jobs_done),
+ // Absolutize a relative hire path against the base; keep an absolute https
+ // URL as-is; default to the canonical per-agent hire route.
+ hireUrl: hire
+ ? absolutize(hire, base)
+ : (base ? `${base}/v1/agents/${encodeURIComponent(id)}/hire` : ''),
+ featured: !!a.featured,
+ internal: false,
+ };
+}
+
+function unconfiguredRoster() {
+ return {
+ ok: false,
+ reason: 'unconfigured',
+ serverNowMs: nowMs(),
+ agents: [STUDIO_AGENT],
+ };
+}
+
+// ── write: hire an agent (consumed by the plaza's hire card) ────────────────────
+
+/**
+ * Build the exact request the hire card hands to `POST /api/x402-pay` for the
+ * server-side x402 flow. The payer signs the 402 challenge → retries; this only
+ * describes the target request. The paying agentId is attached by the caller.
+ *
+ * Returns null for the internal studio agent (it routes to the forge, not x402)
+ * or any agent missing a hire URL, so the caller can branch cleanly.
+ *
+ * @param {NormalizedAgent} agent
+ * @param {object} [brief] optional buyer brief forwarded to Atelier
+ * @returns {{ url:string, method:'POST', body:{ brief:object } }|null}
+ */
+export function hireRequest(agent, brief) {
+ if (!agent || agent.internal || !agent.hireUrl) return null;
+ return {
+ url: agent.hireUrl,
+ method: 'POST',
+ body: { brief: brief ?? {} },
+ };
+}
+
+// ── coercion helpers (defensive: the feed is external) ─────────────────────────
+
+function nowMs() { return Date.now(); }
+
+function num(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function str(v) {
+ return v == null ? '' : String(v);
+}
+
+function secToMs(v) {
+ const n = num(v);
+ return n == null ? null : Math.round(n * 1000);
+}
+
+function asArray(v) {
+ return Array.isArray(v) ? v : [];
+}
+
+// Only surface CORS-readable HTTPS avatar URLs; anything else (http, data:, junk)
+// becomes '' so the booth renders its designed monogram fallback instead of a
+// broken model/image.
+function httpsUrl(v) {
+ const s = str(v).trim();
+ return /^https:\/\//i.test(s) ? s : '';
+}
+
+// Resolve a possibly-relative hire path against the base. An absolute https URL
+// passes through; a '/path' joins onto the base; anything unpar+seable is dropped.
+function absolutize(u, base) {
+ const s = str(u).trim();
+ if (/^https:\/\//i.test(s)) return s;
+ if (!base) return '';
+ if (s.startsWith('/')) return `${base}${s}`;
+ return `${base}/${s}`;
+}
+
+/**
+ * @typedef {object} NormalizedAgent
+ * @property {string} id
+ * @property {string} name
+ * @property {string} tagline
+ * @property {string} specialty
+ * @property {string} avatarUrl '' when none / not https
+ * @property {number} priceUsdc
+ * @property {string} pricePeriod
+ * @property {number|null} rating
+ * @property {number|null} jobsDone
+ * @property {string} hireUrl absolute https URL, or '' / internal route
+ * @property {boolean} featured floats to the central dais
+ * @property {boolean} internal routes hire to a three.ws surface, not x402
+ */
+
+/**
+ * @typedef {object} NormalizedRoster
+ * @property {boolean} ok true on a real feed, false when unconfigured
+ * @property {string|null} reason 'unconfigured' when ok is false, else null
+ * @property {number} serverNowMs
+ * @property {NormalizedAgent[]} agents STUDIO_AGENT first, then marketplace agents
+ */
diff --git a/src/game/arena/contest-screen.js b/src/game/arena/contest-screen.js
index 85be3b5d1..791f083ea 100644
--- a/src/game/arena/contest-screen.js
+++ b/src/game/arena/contest-screen.js
@@ -534,17 +534,16 @@ export function createContestScreen(scene, opts = {}) {
paintBackground();
paintHeader();
- const live = status === 'live' || (status === 'empty' && role === 'winners' && (feed?.recentWinners?.length));
- if (!live && status !== 'live') {
- // winners panel still shows its list during 'empty' (history persists);
- // every other role shows the designed state screen.
- if (!(role === 'winners' && feed?.recentWinners?.length)) {
- paintState();
- paintTicker();
- paintSweep();
- tex.needsUpdate = true;
- return;
- }
+ // The winners panel keeps showing its list even between rounds (history
+ // persists); every other role shows the designed state screen whenever the
+ // feed isn't live (loading / empty / error / unconfigured).
+ const winnersHaveHistory = role === 'winners' && (feed?.recentWinners?.length || 0) > 0;
+ if (status !== 'live' && !winnersHaveHistory) {
+ paintState();
+ paintTicker();
+ paintSweep();
+ tex.needsUpdate = true;
+ return;
}
const padX = 44, bodyTop = 150;
diff --git a/src/game/arena/contest-screens.js b/src/game/arena/contest-screens.js
index 7fe59c337..7e9caa460 100644
--- a/src/game/arena/contest-screens.js
+++ b/src/game/arena/contest-screens.js
@@ -181,9 +181,13 @@ export function mountContestScreens(arena, opts = {}) {
return screen;
});
+ // Track the latest feed so the entry desk (prompt 04) can read the live contest
+ // id from the SAME poll the screens use — no second request to Omniology.
+ let latestFeed = null;
+
const poller = createContestPoller({
pollMs: opts.pollMs,
- onFeed: (feed) => { for (const s of screens) s.applyFeed(feed); },
+ onFeed: (feed) => { latestFeed = feed; for (const s of screens) s.applyFeed(feed); },
onError: () => { for (const s of screens) s.setStatus('error'); },
});
poller.start();
@@ -194,6 +198,9 @@ export function mountContestScreens(arena, opts = {}) {
// 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); },
+ // The live contest id (or null) from the latest poll — the desk's getContestId.
+ getContestId: () => (latestFeed && latestFeed.current ? latestFeed.current.id : null),
+ getCurrentFeed: () => latestFeed,
dispose: () => {
poller.dispose();
for (const s of screens) s.dispose();
diff --git a/src/game/arena/omniology.js b/src/game/arena/omniology.js
index ae67c9011..0b28d38e5 100644
--- a/src/game/arena/omniology.js
+++ b/src/game/arena/omniology.js
@@ -17,6 +17,7 @@ import { OmniologyArena, REMOTE_LERP, RUN_TIMESCALE } from './arena.js';
import { AnimationManager } from '../../animation-manager.js';
import { CommunityNet } from '../community-net.js';
import { mountContestScreens } from './contest-screens.js';
+import { createEntryDesk } from './entry-desk.js';
import {
resolveAvatarUrl, buildAvatar, loadManifest, CLIP_IDLE, CLIP_WALK,
} from '../avatar-rig.js';
@@ -165,6 +166,24 @@ async function hideLoader() {
setTimeout(() => { try { boot?.dispose?.(); } catch {} l.remove(); }, 600);
}
+// Resolve the player's paying agent — the custodial agent whose Solana USDC
+// settles an entry fee at the desk. Reads the signed-in owner's agents (the same
+// list the wallet hub Pay tab uses) and picks the first with a Solana wallet.
+// Returns null when the visitor isn't signed in or has no walletted agent, which
+// the desk renders as a designed "connect a paying agent" state — it never
+// invents an identity or charges the wrong wallet.
+async function resolvePayingAgent() {
+ try {
+ const res = await fetch('/api/x402-pay?agents=1', { credentials: 'include' });
+ if (!res.ok) return null;
+ const json = await res.json().catch(() => ({}));
+ const agents = Array.isArray(json.agents) ? json.agents : [];
+ return agents.find((a) => a && a.solana_address) || null;
+ } catch {
+ return null;
+ }
+}
+
async function start(canvas) {
const arena = new OmniologyArena(canvas);
@@ -248,6 +267,24 @@ async function start(canvas) {
const mover = { update() { net.sendMove(arena.getLocalState()); } };
arena.registerUpdatable(mover);
+ // Entry desk (04) — the in-world kiosk. Walk up, press E, compose an entry, and
+ // submit it to Omniology with a REAL USDC-on-Solana x402 payment (settled from
+ // the player's own agent wallet via /api/x402-pay). On confirmation it pushes the
+ // entry to every screen's live ticker, then the next poll reconciles it. Mounted
+ // at the venue's desk anchor; proximity is driven by the local player's position.
+ let payingAgent = null;
+ resolvePayingAgent().then((a) => { payingAgent = a; });
+ const desk = createEntryDesk(arena.scene, {
+ position: arena.anchors.desk.position,
+ rotationY: arena.anchors.desk.rotationY,
+ getAgentId: () => payingAgent?.id || null,
+ getAgentName: () => payingAgent?.name || name,
+ getContestId: () => contestScreens.getContestId(),
+ getPlayer: () => ({ x: arena.localPos.x, z: arena.localPos.z }),
+ onSubmitted: ({ entryId, agent }) => contestScreens.pushEntry({ entryId, agent: agent || name }),
+ });
+ arena.registerUpdatable(desk);
+
if (isGuest) uploadPendingGuestAvatar((publicUrl) => net.setAvatar(publicUrl));
net.connect();
@@ -262,6 +299,7 @@ async function start(canvas) {
torn = true;
try { net.destroy(); } catch {}
for (const id of [...remotes.keys()]) removeRemote(id);
+ try { desk.dispose(); } catch {}
try { contestScreens.dispose(); } catch {}
try {
localRig.traverse((n) => {
@@ -279,7 +317,7 @@ async function start(canvas) {
if (typeof window !== 'undefined') {
// contestScreens.pushEntry is the hand-off the entry desk (04) wires to its
// onSubmitted callback so a confirmed entry shows on the screens immediately.
- window.__ARENA__ = { arena, net, remotes, teardown, contestScreens, pushEntry: contestScreens.pushEntry };
+ window.__ARENA__ = { arena, net, remotes, teardown, contestScreens, desk, pushEntry: contestScreens.pushEntry };
}
}
diff --git a/tests/arena-entry-desk.test.js b/tests/arena-entry-desk.test.js
new file mode 100644
index 000000000..99e664302
--- /dev/null
+++ b/tests/arena-entry-desk.test.js
@@ -0,0 +1,153 @@
+// Entry desk — unit tests for the prompt-04 logic that lives in the adapter
+// boundary: the entry schema, LOCAL validation that must reject a bad entry
+// BEFORE any payment, the config-driven free/paid fee mode (never a hardcoded
+// flag), the wire normalization that drops empty optionals, and the tolerant
+// confirmation parser. These are the correctness guarantees the desk depends on;
+// the 3D kiosk + SSE stepper are exercised in a real browser (see prompt 04
+// acceptance), not here.
+//
+// Contract: docs/omniology-arena/CONTRACTS.md §1.2, §2.3.
+
+import { describe, it, expect, afterEach } from 'vitest';
+import {
+ ENTRY_FIELDS,
+ normalizeEntry,
+ validateEntry,
+ entryFeeMode,
+ readEntryConfirmation,
+} from '../src/game/arena/omniology-adapter.js';
+
+describe('ENTRY_FIELDS', () => {
+ it('declares the documented required fields the compose UI renders from', () => {
+ const keys = ENTRY_FIELDS.map((f) => f.key);
+ expect(keys).toContain('title');
+ expect(keys).toContain('prompt');
+ // At least one required field, so an empty submit can never pass.
+ expect(ENTRY_FIELDS.some((f) => f.required)).toBe(true);
+ // Every field carries a label + type so the form is self-describing.
+ for (const f of ENTRY_FIELDS) {
+ expect(typeof f.label).toBe('string');
+ expect(['text', 'textarea', 'url']).toContain(f.type);
+ }
+ });
+});
+
+describe('normalizeEntry()', () => {
+ it('trims strings and drops empty optionals', () => {
+ const out = normalizeEntry({ title: ' Sunset ', prompt: 'a calm beach', media_url: ' ' });
+ expect(out.title).toBe('Sunset');
+ expect(out.prompt).toBe('a calm beach');
+ expect('media_url' in out).toBe(false); // empty optional dropped
+ });
+
+ it('keeps a required-but-empty field as "" so validation can flag it', () => {
+ const out = normalizeEntry({ prompt: 'x' });
+ expect(out.title).toBe(''); // required, missing → kept empty, not omitted
+ });
+
+ it('keeps a valid optional value', () => {
+ const out = normalizeEntry({ title: 'a', prompt: 'b', media_url: 'https://x.test/i.png' });
+ expect(out.media_url).toBe('https://x.test/i.png');
+ });
+});
+
+describe('validateEntry() — rejects bad entries before payment', () => {
+ it('passes a complete, valid entry', () => {
+ const v = validateEntry({ title: 'Sunset', prompt: 'a calm beach at dusk' });
+ expect(v.ok).toBe(true);
+ expect(v.errors).toEqual({});
+ });
+
+ it('flags missing required fields', () => {
+ const v = validateEntry({ title: '', prompt: ' ' });
+ expect(v.ok).toBe(false);
+ expect(v.errors.title).toMatch(/required/i);
+ expect(v.errors.prompt).toMatch(/required/i);
+ });
+
+ it('enforces the per-field character limit', () => {
+ const titleField = ENTRY_FIELDS.find((f) => f.key === 'title');
+ const tooLong = 'x'.repeat(titleField.max + 1);
+ const v = validateEntry({ title: tooLong, prompt: 'ok' });
+ expect(v.ok).toBe(false);
+ expect(v.errors.title).toMatch(new RegExp(`${titleField.max}`));
+ });
+
+ it('rejects a non-https media URL but accepts a blank optional', () => {
+ const bad = validateEntry({ title: 't', prompt: 'p', media_url: 'http://insecure/x.png' });
+ expect(bad.ok).toBe(false);
+ expect(bad.errors.media_url).toMatch(/https/i);
+
+ const blankOptional = validateEntry({ title: 't', prompt: 'p', media_url: '' });
+ expect(blankOptional.ok).toBe(true);
+
+ const goodUrl = validateEntry({ title: 't', prompt: 'p', media_url: 'https://cdn.test/x.png' });
+ expect(goodUrl.ok).toBe(true);
+ });
+});
+
+describe('entryFeeMode() — selected by config, never hardcoded', () => {
+ afterEach(() => {
+ delete globalThis.window;
+ delete globalThis.document;
+ });
+
+ it('defaults to auto when unconfigured', () => {
+ expect(entryFeeMode()).toBe('auto');
+ });
+
+ it('reads window.OMNIOLOGY_ENTRY_FEE (case-insensitive)', () => {
+ globalThis.window = { OMNIOLOGY_ENTRY_FEE: 'FREE' };
+ expect(entryFeeMode()).toBe('free');
+ globalThis.window = { OMNIOLOGY_ENTRY_FEE: 'paid' };
+ expect(entryFeeMode()).toBe('paid');
+ });
+
+ it('reads the <meta name="omniology-entry-fee"> tag', () => {
+ globalThis.document = {
+ querySelector: (sel) =>
+ sel === 'meta[name="omniology-entry-fee"]'
+ ? { getAttribute: () => 'free' }
+ : null,
+ };
+ expect(entryFeeMode()).toBe('free');
+ });
+
+ it('falls back to auto for an unrecognized value', () => {
+ globalThis.window = { OMNIOLOGY_ENTRY_FEE: 'whenever' };
+ expect(entryFeeMode()).toBe('auto');
+ });
+});
+
+describe('readEntryConfirmation() — tolerant of both wire shapes', () => {
+ it('reads the paid-path nested result envelope', () => {
+ const env = {
+ ok: true,
+ result: { entry_id: 'e_42', status: 'accepted', round: 1421, position: 38 },
+ payment: { tx: 'sig', amount: '250000' },
+ };
+ expect(readEntryConfirmation(env)).toEqual({
+ entryId: 'e_42', status: 'accepted', round: 1421, position: 38,
+ });
+ });
+
+ it('reads the free-path bare body', () => {
+ const env = { entry_id: 'e_7', status: 'accepted', round: 9, position: 2 };
+ expect(readEntryConfirmation(env)).toEqual({
+ entryId: 'e_7', status: 'accepted', round: 9, position: 2,
+ });
+ });
+
+ it('coerces string round/position and tolerates missing fields', () => {
+ const env = { result: { entry_id: 'e1', round: '12', position: '4' } };
+ const c = readEntryConfirmation(env);
+ expect(c.round).toBe(12);
+ expect(c.position).toBe(4);
+ expect(c.status).toBeNull();
+ });
+
+ it('never throws on an empty/garbage envelope', () => {
+ expect(readEntryConfirmation(null)).toEqual({ entryId: null, status: null, round: null, position: null });
+ expect(readEntryConfirmation({})).toEqual({ entryId: null, status: null, round: null, position: null });
+ });
+});