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 auto-rigging functionality for GLB models

nirholascf463d61bd4e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a862ae94..9c42b7cfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,11 +9,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **KOL Tracker** (`/tracker`) — Solana crypto KOLs ranked by realized P&L computed from their own wallet's on-chain trade history, with win rate, volume, trade count, and X follower counts for verified handles.
- **Tutorial · 3D AI Shopping Assistant for Shopify** (`/tutorials/shopify-shopping-assistant`) — Add a chat assistant with a 3D face to your Shopify store: it reads your live catalog, recommends real products as cards with add-to-cart, and answers shipping and returns, all from one script tag.
- **We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.** (`/blog/autonomous-trading-experiment`) — Two weeks of fully autonomous pump.fun trading on Solana: 11 armed strategies, 90 closed real-money trades, every entry thesis, every exit, every mistake. Plus the 83,000 coins the fleet did not buy, the winners it missed, and a paperhands audit of every sell. Complete dataset included.
+- **A full notification center, plus two new things it tells you about** — The bell in the nav now links to a dedicated /notifications page: your full history, filterable by category (sales, purchases, social, in person, market alerts, creations, account), with load-more paging so nothing gets lost past the dropdown's last 20. We also closed two gaps in what triggers a notification. Fork royalty streams (an avatar you created earning a slice of income from everyone who forked it) now notify the upstream creator the moment a payout confirms on-chain, with the SOL/USD amount and which fork paid it. And finishing a mission or co-op heist in /play now lands in your inbox too, not just the site-wide activity ticker. Both respect your existing per-category mute preferences in notification settings. (`/notifications`) `[feature]`
- **Agent wallet and portfolio views stay reliable when an RPC provider is capped** — Agent portfolio and wallet-balance reads no longer fail when a Solana RPC provider hits its daily request limit. Balance lookups now fall back across several free, unthrottled Solana nodes, so net-worth snapshots and holdings keep loading during provider throttling instead of erroring out. `[fix, infra]`
- **All 90 trades from the autonomous fleet, published and graded** — The autonomous sniper fleet has closed 90 real-money trades across 8 strategies and 8 wallets, and we published every single one: entry thesis, exit, on-chain receipts, and an honest grade per trade. The deep dive also audits everything the fleet did not do: the 83,000 launches it observed and declined, proof the conviction scorer’s top band hits 77.5% winners at scale (and why zero of those coins were bought), the missed monsters that were invisible at minute zero, and a paperhands check showing every one of the 90 sells was vindicated. Full dataset downloadable as JSON. (`/blog/autonomous-trading-experiment`) `[docs, feature]`
- **Avatars now generate on our strongest 3D lane by default** — Every avatar made through the avatar tools (forge_avatar, text_to_avatar, and the /forge web page's avatar mode) now requests our highest-fidelity generation tier automatically, which routes people/character prompts to our self-hosted Hunyuan3D lane instead of the faster draft lane. That means better proportions, cleaner hands, and less texture warping at the neck and hairline, at no extra cost or extra steps. We also tuned the avatar prompt director to always ask for relaxed, open hands with fingers visible, since closed fists and hidden hands were the single biggest source of mangled-hand meshes. If auto-rigging ever fails after a great mesh generates, you still keep the finished mesh, rigging alone, and can retry rigging separately. (`/forge`) `[improvement]`
- **Fixed: wallets showing $0 of $THREE on the tiers page** — Holders reported the site not recognising their $THREE balance: /three showed "You hold $0" (Member tier) for wallets with real bags, across Phantom, Solflare, and Brave Wallet. Root cause: when our primary balance provider ran out of quota, the backup on-chain read only queried the classic SPL token program, and $THREE (like all pump.fun coins) lives on Token-2022, so it was invisible. The backup path now reads both token programs and rides the same deep multi-provider RPC failover as the rest of the platform, so holder tiers, fee discounts, and quota boosts resolve correctly even when individual RPC providers are down. (`/three`) `[fix]`
- **Opening a 3D object gives you a viewer, not a chatbot** — Previewing a prop from the CC0 object library (a wrench, a vase, an ammo box) used to drop you into the embodied-agent surface, complete with an "Ask the agent" box and prompts like "Why are you embodied?" that make no sense for an inanimate object. Objects now open in a dedicated viewer mode: the agent chat and avatar controls are gone, replaced by the things you actually want for a 3D thing — Restyle to recolor or AI-restyle its materials, View in AR to place it in your room, and Download the CC0 GLB. Avatars are untouched and still open with the full agent experience. (`/objects`) `[improvement]`
+- **Real materials: skin, glass, and car paint that actually behave like the real thing** — Avatars now get a subtle skin sheen, wet-looking corneas, and double-sided hair automatically the moment a humanoid model loads in any three.ws viewer, no extra step needed. Restyle Studio's material presets grew a real-physics tier alongside the classic looks: skin, car paint with a genuine clearcoat layer, brushed steel with directional anisotropic highlights, and a real-glass preset that actually refracts (KHR_materials_transmission) instead of faking transparency. The AI restyle tool ("make it chrome", "cyberpunk neon") can now propose clearcoat, transmission, and sheen too when an instruction calls for it. The text-guided texture worker also gained an optional material_class hint (person/metal/wood/fabric/plastic/glass) that bakes measured real-world roughness values instead of one flat guess for every material. (`/restyle`) `[feature, improvement]`
- **Restyled models now show up on your creator portfolio** — Your public portfolio at /u/:username (and /profile for yourself) already collected your forged 3D models and saved worlds into one "Creations" feed alongside your avatars, agents, launched coins, skills, and plugins. Restyled models were the missing piece: an AI material restyle ("make it chrome", "cyberpunk neon") or a seeded colorway variant fan-out from the Restyle Studio now records to your account when you're signed in, and shows up in Creations with a live 3D thumbnail, the instruction or preset used, and a link to the viewer, right next to your other work. (`/profile`) `[feature]`
- **The Concierge becomes a Shopify shopping assistant, with product cards** — The embeddable AI concierge (the floating chat with a 3D avatar) now turns into a full shopping assistant on any Shopify store, from the same one script tag. It reads your live catalog and policies straight from Shopify's public endpoints, no app, no API key, and no product feed to keep in sync, then helps shoppers find the right thing and shows real product cards with the live image, price, and an add-to-cart button. It understands how people actually shop ("a gift under $75", "cheapest hoodie", "anything on sale?") and answers shipping and returns from your published policies. Because the cards are drawn from your real catalog, it can never invent a product, a price, or a discount. (`/tutorials/shopify-shopping-assistant`) `[feature, sdk]`
- **The sniper learns from its own postmortem: conviction-crossing entries and smarter trailing stops** — Two upgrades shipped straight from the 90-trade analysis. First, a new oracle_crossing trigger: instead of judging a coin at launch, when the conviction scorer has no signal yet, an arm can now buy the moment a coin first crosses its conviction bar. Measured over the fleet window, that band pumped or graduated 77.5% of the time versus an 11.8% base rate, and the crossing lands a median of two minutes after launch. The formerly idle strict arm is re-armed on it with a sell-the-initials ladder. Second, trailing stops now arm only once a position has been above breakeven; armed underwater they only converted recoverable dips into locked losses while the hard stop-loss already capped the downside. (`/blog/autonomous-trading-experiment`) `[feature, improvement]`
@@ -330,6 +332,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-12
- **Docs · The autonomous economy** (`/docs/autonomous-economy`) — How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.
+- **Notifications** (`/notifications`) — Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.
- **Rankings** (`/rankings`) — The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.
- **Robinhood Chain** (`/markets/robinhood`) — The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs DEX premium for every Stock Token, a memecoin screener across NOXA and The Odyssey launchpads, recent launches, and chain TVL — plus a real wallet-connect buy flow for its coins.
- **Search** (`/search`) — One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.
@@ -614,7 +617,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-06
-- **Agent Identity Studio — 3D avatars for AI agents** (`/agent-identities`) — Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.
+- **Agent Identity Studio: 3D avatars for AI agents** (`/agent-identities`) — Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.
- **Premium Vanity Inventory** (`/vanity/premium`) — Buy a long, brandable Solana vanity address delivered instantly from stock — 4–5+ character prefixes the live grinder can't reach, ground ahead of time on batch CPU and sold via x402. Keys are encrypted at rest, priced by rarity, and delivered exactly once.
- **3D generation, rigging, and export, now individually-priced services for AI agents** — The 3D studio is now sold piece by piece on OKX.AI, OKX's agent marketplace, where AI agents buy from each other. Eight sharply-scoped services, each with its own endpoint and price: text→3D from $0.01, art-directed Pro generation and image→3D at $0.30, auto-rigging at $0.25, a one-call rigged avatar at $0.50, animation retargeting at $0.10, deterministic pose seeds at $0.02, and rig-preserving FBX export for Unity/Unreal at $0.10. Payment settles in stablecoins on X Layer over the OKX Agent Payments Protocol (the existing Solana and Base rails are still accepted), you are only charged once a job is accepted, and discovery, health, job polling, and previews stay free. The full machine-readable catalog lives at /api/okx/3d/catalog. (`/docs/okx-marketplace`) `[feature]`
- **Agent Identity Studio, 3D avatars for AI agents, sold agent-to-agent** — Every AI agent on a marketplace shows a profile picture, and almost all of them are flat generated images. The new Agent Identity Studio gives an agent a real 3D identity: send a brand brief (any language) and $1.50 over the x402 rail, and the pipeline designs a character, generates the mesh, rigs a humanoid skeleton, and delivers posed studio renders, a square profile picture that stays sharp at thumbnail size, three full-body shots, and the rigged GLB itself for use in three.ws scenes, games, or any glTF runtime. Job status polling is free, you're only charged when a job is accepted, and failed steps retry at no cost. See the demo identities, generated end-to-end by the pipeline, briefs included, on the new showcase page. (`/agent-identities`) `[feature]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 33cb418f6..b0ff60208 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -86,6 +86,7 @@ bottom.
| Forge model categorization | Classifier [api/_lib/forge-classify.js](api/_lib/forge-classify.js), wired at generation in [api/_lib/forge-store.js](api/_lib/forge-store.js) (`createCreation`), backfill [scripts/backfill-forge-categories.mjs](scripts/backfill-forge-categories.mjs), coloured badges in [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin | Live | Assigns every forge model a `model_category` (avatar/accessory/item/scene/creature/vehicle/other) from its prompt with a deterministic, dependency-free keyword classifier — most-specific-first so "a knight riding a horse" is an avatar, not a creature. Nothing set the category before, so ~99.8% of the corpus was `other` and the category badges, filters, and Forge-Off category dimension were dead; the classifier now runs inline on every generation (all lanes) and reclassifies ~85% of the 9.8k-row back catalogue (dry-run verified). Coloured category pills render across the showcase/gallery/community feed. Tests: [tests/forge-classify.test.js](tests/forge-classify.test.js). |
| Forge thumbnail coverage | [api/_lib/forge-thumbs.js](api/_lib/forge-thumbs.js) + cron [api/cron/forge-thumbnail-backfill.js](api/cron/forge-thumbnail-backfill.js) (`*/5`) | Live | Gives every finished forge model a real picture. The dominant free NVIDIA/TRELLIS lane is geometry-first and paints no reference image, so ~83% of finished `forge_creations` land with `preview_image_url = NULL` and render as gradient placeholders on every browse surface (showcase, gallery, `/community`, `/search`, creator portfolios). This cron claims the newest previewless models, renders each GLB to a 768² PNG via the shared headless-chromium renderer ([api/_lib/render-glb.js](api/_lib/render-glb.js)), uploads it, and fills the preview slot — object confirmed in R2 **before** the key is committed (same ORB-safety invariant as avatars), and **fill-only** so a maker's captured poster always wins. Self-provisioning claim ledger (`forge_thumbnail_backfill`, created at runtime), bounded attempts, lease-based reclaim, browser-death batch abort with attempt refund. `?dry_run=1` reports coverage. Tests: [tests/forge-thumbs.test.js](tests/forge-thumbs.test.js). |
| Forge-Off (community voting + weekly board) | Store [api/_lib/forge-store.js](api/_lib/forge-store.js) (`castVote`/`removeVote`/`listShowcase` sort+voter/`forgeOffWeekStart`), endpoint [api/forge-vote.js](api/forge-vote.js), board read [api/forge-gallery.js](api/forge-gallery.js) (`scope=community&sort=top&window=week`), weekly crown cron [api/cron/forge-off-crown.js](api/cron/forge-off-crown.js) (`7 0 * * 1`), UI [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin [src/forge-studio/forge-showcase.js](src/forge-studio/forge-showcase.js), schema [migration 20260625120000_forge_board.sql](api/_lib/migrations/20260625120000_forge_board.sql) | Live | Turns the "Fresh from the Forge" strip on [/forge](pages/forge.html) into a live board: auth-free upvotes (one per browser, keyed to the same `forge:cid` id as "Your creations"), a Fresh/Top-this-week sort toggle, optimistic vote pills that reconcile against the authoritative `vote_count` (recomputed from `forge_votes`, never a drifting counter), and a Monday-00:07-UTC cron that permanently crowns each week's top-voted creation into `forge_board_winners`. The crown is the writer the [Sketchfab showcase](docs/sketchfab.md) cron's strongest tier had been waiting on. Docs: [docs/forge-off.md](docs/forge-off.md). Tests: [tests/api/forge-gallery-community.test.js](tests/api/forge-gallery-community.test.js) |
+| Realism quality bench | Benchmark [data/quality-bench/prompts.json](data/quality-bench/prompts.json) (23 fixed prompts + 3 CC0 reference photos), runner [scripts/quality-bench.mjs](scripts/quality-bench.mjs), shared generate/render/judge core [api/_lib/quality-bench.js](api/_lib/quality-bench.js), dashboard [api/quality-bench.js](api/quality-bench.js) + [pages/quality-bench.html](pages/quality-bench.html) `→ /quality-bench` (internal, not in `data/pages.json`), weekly smoke cron [api/cron/quality-bench.js](api/cron/quality-bench.js) (`23 3 * * 1`) | Live | The measurement loop the realism campaign hangs on: fires the fixed prompt set through the real `/api/forge` path, renders 3 canonical views per result with the same headless three.js renderer as the avatar clip/OG-card renders ([api/_lib/render-clip.js](api/_lib/render-clip.js)), and scores every view with Vertex Gemini vision (`gemini-2.5-pro`, temperature 0, scored twice and averaged, judge never sees forge's internal prompt-enhancement text). Runs are committed append-only JSON under `data/quality-bench/runs/`; the dashboard renders score trends by lane/tier/subject-class, a worst-5 critique gallery, and the full results table. `node scripts/quality-bench.mjs --compare=latest,previous` exits nonzero on a >1.0 mean drop — run it before/after any forge change that could affect quality. Docs: [data/quality-bench/README.md](data/quality-bench/README.md). |
| Sketchfab showcase (community models → official account) | Cron [api/cron/sketchfab-showcase.js](api/cron/sketchfab-showcase.js), lib [api/_lib/sketchfab.js](api/_lib/sketchfab.js), ledger migration [api/_lib/migrations/20260714130000_sketchfab_uploads.sql](api/_lib/migrations/20260714130000_sketchfab_uploads.sql) | Live · dormant until `SKETCHFAB_API_TOKEN` is set | Publishes the best community forge models to the official three.ws Sketchfab account, prompt and backlink included. Selection order: forge-board winners (now populated by the [Forge-Off](docs/forge-off.md) crown cron), then top-voted (>=1 vote), then creator-accepted (accepted or downloaded, refinement children excluded, title-quality heuristic). Brand safety is two layers: a SQL denylist plus NemoGuard re-moderation; blocked rows park as `blocked` in the `sketchfab_uploads` ledger (states `pending`/`uploaded`/`live`/`failed`/`blocked`). `?dry_run=1` exercises selection before the token is wired; `SKETCHFAB_UPLOADS_PER_RUN` clamps 1-5 (default 2). Docs: [docs/sketchfab.md](docs/sketchfab.md) |
| Third-party display-name safety | [api/_lib/display-name-safety.js](api/_lib/display-name-safety.js), applied at ERC-8004 metadata hydration in [api/cron/[name].js](api/cron/%5Bname%5D.js) | Live | The ERC-8004 crawler indexes 126k+ on-chain agents and renders each one's `name`/`description`/`image` from attacker-controlled metadata. Visibility used to be decided solely by the agent's own `meta.active`, so a Base-registered agent whose name was a racial slur shipped to `/marketplace`. `matchedSlurStem()` now withholds such rows (`active = false`), which removes them from every feed at once since explore/marketplace/agents/search all filter `active = true`. Deliberately narrow — **whole-word** hate slurs only, never general profanity, and hex-address aware: leet folding turns `0xdb6b887289c380…` into letter soup, so long alphanumeric runs are excluded from the spaced-out-evasion pass. A false positive silently delists a legitimate agent, so precision outranks recall. Backfill for already-indexed rows: [scripts/deactivate-slur-agents.mjs](scripts/deactivate-slur-agents.mjs) (`--dry-run`). Tests: [tests/display-name-safety.test.js](tests/display-name-safety.test.js) — pins the real agent names an earlier substring matcher wrongly flagged. |
| FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |
diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.js
index 27a1a033a..321ad852c 100644
--- a/api/_lib/avatar-render.js
+++ b/api/_lib/avatar-render.js
@@ -1,14 +1,14 @@
-// Avatar render core — the headless-chromium + three.js pipeline that turns a
+// Avatar render core, the headless-chromium + three.js pipeline that turns a
// stored GLB into a PNG/JPEG/WebP, plus the param-resolution and R2 cache layer
// around it. Extracted so BOTH the public HTTP endpoint (api/avatar/render.js)
-// and the render_avatar_image MCP tool share one implementation — there is no
+// and the render_avatar_image MCP tool share one implementation, there is no
// duplicated chromium code anywhere else.
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()
// so Vercel's NFT does not statically trace the chromium binary tree on every
-// route in a function package — that trace was the 45-min build timeout.
+// route in a function package, that trace was the 45-min build timeout.
import { env } from './env.js';
import { publicUrl, putObject, headObject } from './r2.js';
import { PRESETS } from '../../src/pose-presets.js';
@@ -217,7 +217,7 @@ export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload =
return { cached: true, key, imageUrl: publicUrl(key), buffer: null, contentType };
}
} catch {
- // Cache miss — render fresh.
+ // Cache miss, render fresh.
}
const cameraOrbit = { theta: params.scenePreset.theta, phi: params.scenePreset.phi, radius: null };
@@ -347,7 +347,7 @@ renderer.setSize(${width}, ${height}, false);
renderer.setPixelRatio(1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
// Neutral (Khronos PBR Neutral) tone mapping renders asset colors faithfully
-// without the shadow-crushing ACES rolloff — the right choice for a product
+// without the shadow-crushing ACES rolloff, the right choice for a product
// render where the character must read clearly.
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1.15;
@@ -360,7 +360,7 @@ const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);
// Image-based lighting is what makes PBR materials read: metal and glossy
// surfaces draw their reflections from scene.environment, so with none set they
-// collapse to near-black — the "dark, murky" render. RoomEnvironment is three's
+// collapse to near-black, the "dark, murky" render. RoomEnvironment is three's
// built-in procedural studio environment (no external HDR asset to host).
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index 7045d7c05..8db832be0 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -81,6 +81,8 @@ export const USER_EVENT_TYPES = new Set([
'agent_review', // someone reviewed your agent; { actor, agent_id, agent_name, rating, link }
'dm_received', // a friend sent you a DM while you were away; { actor, link }
'pump_launch_filled',// a launch you own graduated its bonding curve; { name, mint, link }
+ 'quest_complete', // a /play mission or co-op heist you finished; { mission, gold, coop, link }
+ 'royalty_paid', // a fork of your avatar paid an upstream royalty; { actor, sol, usd, depth, signature, link }
// types already produced by purchase-confirm / buy-asset confirm flows
'skill_purchased',
'skill_purchase_confirmed',
diff --git a/api/_lib/forge-director-prompts.js b/api/_lib/forge-director-prompts.js
index b2df62d81..1844059fa 100644
--- a/api/_lib/forge-director-prompts.js
+++ b/api/_lib/forge-director-prompts.js
@@ -9,11 +9,15 @@
// hand-maintained duplicates drifting apart.
import { BRAND_MARK_DIRECTIVE, resolveLogoPrompt } from '../../mcp-server/src/tools/_logo-lexicon.js';
+import { classifySubject } from '../forge-enhance.js';
// Deterministic brand-mark resolution ("<brand name> logo" → the real mark's
// geometry). Re-exported here so every api/ director call-site gets the
// lexicon from the same module it already imports the director prompts from.
-export { resolveLogoPrompt };
+// `classifySubject` (person/animal/vehicle/food/object) is re-exported too so
+// callers can pick the subject-aware director variant below without a second
+// import from forge-enhance.js.
+export { resolveLogoPrompt, classifySubject };
// The mesh reconstructor never sees the user's words — it only ever sees the
// ONE reference image the director's rewritten prompt produces. So the single
@@ -33,29 +37,90 @@ const PHOTOREAL_CUES =
'perfectly clean or perfectly smooth; a small amount of natural asymmetry and imperfection reads as more real ' +
'than a flawless surface';
-// For a single object/prop/creature — one isolated subject, its construction,
-// per-part PBR materials, one held art style, and fine surface detail, ending
-// in composition constraints tuned for clean image→mesh reconstruction.
-export const MESH_DIRECTOR =
- "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " +
- 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' +
- 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' +
- 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' +
- 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' +
- 'coherent, consistent art style held across the whole subject. Default to photoreal — most real-world objects ' +
- 'should look like an actual photograph of the physical thing. Only choose stylized, low-poly, or hand-painted ' +
- "when the user's own words clearly call for that look (cartoon, chibi, voxel, pixel art, toy, anime, retro " +
- 'game, etc.) — never mix styles. When the style is photoreal, weave in these cues: ' + PHOTOREAL_CUES + '. (5) ' +
- 'fine surface detail (seams, panel lines, weathering, grain) that gives the reconstructor texture to latch ' +
- "onto. If the idea names a brand, meme, app, or term you do not recognize, keep the user's concrete object " +
- 'noun as the subject and describe its canonical physical form (a pill is a two-tone medicine capsule, a ' +
- 'rocket is a finned cylinder with a nose cone); never substitute a different object. ' +
- BRAND_MARK_DIRECTIVE +
- 'Always end with these composition constraints so the ' +
- 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' +
- 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' +
- 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' +
- 'preamble, no quotes.';
+// Per-subject-class material/construction cues layered into the MESH_DIRECTOR
+// briefing (step 3 below). Each class fails reconstruction in a DIFFERENT way —
+// a creature's tell is fur/anatomy, a vehicle's is panel/wheel symmetry, food's
+// is an inedible plastic sheen, architecture's is scale and flat facades — so a
+// single generic "materials" instruction under-serves all of them. Mirrors the
+// SUBJECT_REALISM_HINT map in forge-enhance.js but tuned for the MESH_DIRECTOR's
+// construction-first briefing rather than a rewrite-prompt's prose.
+const MESH_SUBJECT_HINTS = Object.freeze({
+ person:
+ 'This is a person or humanoid character: call out real skin (visible pores, subtle asymmetry, faint ' +
+ 'subsurface glow at ears/nose/fingers), hair as many fine strands rather than a sculpted cap, and ' +
+ 'ordinary human proportions — never doll-like symmetry or oversized eyes.',
+ animal:
+ 'This is an animal or creature: call out real fur/feather/scale direction and texture, correct species ' +
+ 'anatomy (leg count, joint bend direction, muzzle/beak shape), a moist natural nose, and lifelike eyes ' +
+ 'with a catchlight — never a plush-toy or cartoon proportion.',
+ vehicle:
+ 'This is a vehicle: call out painted or brushed-metal body panels with accurate panel gaps, correct wheel ' +
+ 'count and symmetry, rubber tread, and glass/chrome trim — sitting still, fully in frame, three-quarter or ' +
+ 'side product view, never mid-motion.',
+ food:
+ 'This is food or a drink: call out real edible surface texture (crumb, grain, glaze, condensation), ' +
+ 'natural moisture and appetizing true-to-life color — never a plastic replica or wax-model sheen.',
+ architecture:
+ 'This is a building or structure: call out real construction materials at true scale (brick coursing, ' +
+ 'poured concrete, glass curtain wall, weathered stone), consistent perspective, and legible window/door ' +
+ 'proportions — never a toy-scale or flat, textureless facade.',
+ object:
+ 'Call out the object\'s real material, finish, and surface micro-detail (grain, brush marks, wear, weave) ' +
+ 'so the reconstructor bakes a convincing true-to-life texture rather than a flat, plastic one.',
+});
+
+// Architecture reads as a distinct subject class from the generic "object" net
+// for MESH_DIRECTOR's purposes (scale and facade realism are a different
+// failure mode from a handheld prop), even though forge-enhance.js's
+// classifySubject() folds it into 'object' upstream. Detected locally, ordered
+// before the generic object fallback so a named building/structure gets its
+// own construction guidance.
+const ARCHITECTURE_RE =
+ /\b(building|house|tower|skyscraper|bridge|castle|cathedral|church|temple|mansion|cabin|cottage|barn|warehouse|stadium|lighthouse|windmill|architecture|facade|structure)\b/i;
+
+// Resolve the MESH_DIRECTOR hint key for a raw prompt: architecture first (a
+// finer-grained class than classifySubject's 'object' bucket), then whatever
+// classifySubject() already detects (person/animal/vehicle/food), else 'object'.
+export function meshSubjectClass(prompt) {
+ if (ARCHITECTURE_RE.test(String(prompt || ''))) return 'architecture';
+ return classifySubject(prompt);
+}
+
+// Build the MESH_DIRECTOR system prompt for a given subject class — one
+// isolated subject, its construction, per-part PBR materials, one held art
+// style, subject-specific realism cues, and fine surface detail, ending in
+// composition constraints tuned for clean image→mesh reconstruction.
+export function meshDirectorFor(subject = 'object') {
+ const hint = MESH_SUBJECT_HINTS[subject] || MESH_SUBJECT_HINTS.object;
+ return (
+ "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " +
+ 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' +
+ 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' +
+ 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' +
+ 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness — and ' +
+ 'specifically: ' + hint + ' (4) a coherent, consistent art style held across the whole subject. Default to ' +
+ 'photoreal — most real-world objects should look like an actual photograph of the physical thing. Only ' +
+ "choose stylized, low-poly, or hand-painted when the user's own words clearly call for that look (cartoon, " +
+ 'chibi, voxel, pixel art, toy, anime, retro game, etc.) — never mix styles. When the style is photoreal, ' +
+ 'weave in these cues: ' + PHOTOREAL_CUES + '. (5) ' +
+ 'fine surface detail (seams, panel lines, weathering, grain) that gives the reconstructor texture to latch ' +
+ "onto. If the idea names a brand, meme, app, or term you do not recognize, keep the user's concrete object " +
+ 'noun as the subject and describe its canonical physical form (a pill is a two-tone medicine capsule, a ' +
+ 'rocket is a finned cylinder with a nose cone); never substitute a different object. ' +
+ BRAND_MARK_DIRECTIVE +
+ 'Always end with these composition constraints so the ' +
+ 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' +
+ 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' +
+ 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' +
+ 'preamble, no quotes.'
+ );
+}
+
+// Back-compat default (subject-agnostic 'object' briefing) — existing
+// call-sites and tests that import the flat constant keep working unchanged;
+// new call-sites should classify the prompt and call meshDirectorFor(subject)
+// directly for the subject-aware briefing.
+export const MESH_DIRECTOR = meshDirectorFor('object');
// Human-specific realism cues layered on top of PHOTOREAL_CUES for avatars —
// the difference between "video-game NPC" and an actual person is almost
@@ -69,29 +134,55 @@ const PHOTOREAL_HUMAN_CUES =
'painted-on helmet shape. Eyes have visible iris detail, a natural wet highlight, and real catchlights from ' +
'the studio lighting';
-// For a full-body humanoid destined for auto-rigging — a readable, separable
-// pose plus the same per-region PBR/material and single-style discipline.
-export const AVATAR_DIRECTOR =
- "You are a 3D character art director briefing a text-to-3D reconstruction model whose output will be " +
- "auto-rigged for animation. Rewrite the user's idea into ONE concise, information-dense prompt. Cover, in " +
- 'order: (1) a SINGLE full-body humanoid, standing in a neutral A/T-adjacent pose, arms slightly away from ' +
- 'the body and legs slightly apart so limbs are readable and separable for rigging, (2) body type and ' +
- 'proportions, (3) outfit and gear per body region (head, torso, arms, legs, feet) with explicit PBR ' +
- 'material cues (e.g. brushed metal armor, worn leather straps, matte cloth, glossy visor) so surfaces ' +
- 'reconstruct with correct roughness/metalness, (4) one coherent, consistent art style held across the ' +
- 'whole character. Default to photoreal — a real human being photographed, not a game character or a toy — ' +
- "unless the user's own words clearly call for something else (anime, cartoon, chibi, voxel, robot, creature, " +
- 'toy, low-poly, hand-painted, etc.); never mix styles. When the character is a photoreal human, weave in ' +
- 'these cues: ' + PHOTOREAL_CUES + '; and specifically: ' + PHOTOREAL_HUMAN_CUES + '. (5) key identifying ' +
- 'features (hair, face, color scheme, accessories). When the idea is sparse or generic ("a woman", "a knight", ' +
- '"a cool guy"), do NOT default to the same safe, average person: commit to specific, memorable choices the ' +
- 'user did not rule out: a particular age, build, and face character; a distinctive hairstyle and hair color; a ' +
- 'named 2-3 color palette; one signature garment, pattern, or accessory that makes this character instantly ' +
- 'recognizable in a lineup. Draw these choices from the mood and connotations of the words the user chose so two ' +
- 'different ideas never converge on the same person. If the idea names a brand, meme, or term you do not ' +
- "recognize, keep the user's stated character concept as the subject and render its canonical look; never " +
- 'substitute a different character. Always end with these composition ' +
- 'constraints: full body in frame head-to-toe, centered, isolated on a plain neutral background, no props ' +
- 'gripped or crossing the silhouette, one camera angle facing the character, even studio lighting, no ' +
- 'cropping, no motion blur, no text or watermark, no collage or multi-view grid, no second character. ' +
- 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';
+// Creature-specific realism cues — the avatar-flavored twin of
+// PHOTOREAL_HUMAN_CUES for a non-human full-body character (a dragon, a
+// beast-person, an animal-headed avatar) that still needs a humanoid-ish rig.
+// Fur/scale/feather direction and species-correct anatomy are the tell for a
+// creature reconstruction the way skin/hair/eyes are for a human one.
+const PHOTOREAL_CREATURE_CUES =
+ 'render real fur, feathers, or scales with directional flow and natural variation (not a painted-on flat ' +
+ 'texture), a moist natural nose/snout or beak, lifelike eyes with a catchlight, and anatomically correct ' +
+ 'proportions for the creature — never a plush-toy or cartoon-mascot look';
+
+// Build the AVATAR_DIRECTOR system prompt for a subject class. 'person' (the
+// default) weaves in PHOTOREAL_HUMAN_CUES; 'animal' (a creature/beast avatar
+// that still needs a rig) swaps in PHOTOREAL_CREATURE_CUES instead, since the
+// realism tell is completely different — skin/hair/eyes vs. fur/scale/anatomy.
+// Every other subject class falls back to the person cues: an avatar is a
+// full-body character by definition, and the humanoid gate upstream
+// (classifyHumanoidPrompt) already filters out non-character subjects before
+// this director ever runs.
+export function avatarDirectorFor(subject = 'person') {
+ const subjectCues = subject === 'animal' ? PHOTOREAL_CREATURE_CUES : PHOTOREAL_HUMAN_CUES;
+ return (
+ "You are a 3D character art director briefing a text-to-3D reconstruction model whose output will be " +
+ "auto-rigged for animation. Rewrite the user's idea into ONE concise, information-dense prompt. Cover, in " +
+ 'order: (1) a SINGLE full-body humanoid, standing in a neutral A/T-adjacent pose, arms slightly away from ' +
+ 'the body and legs slightly apart so limbs are readable and separable for rigging, (2) body type and ' +
+ 'proportions, (3) outfit and gear per body region (head, torso, arms, legs, feet) with explicit PBR ' +
+ 'material cues (e.g. brushed metal armor, worn leather straps, matte cloth, glossy visor) so surfaces ' +
+ 'reconstruct with correct roughness/metalness, (4) one coherent, consistent art style held across the ' +
+ 'whole character. Default to photoreal — a real human being (or, for a creature/beast character, a real ' +
+ "animal) photographed, not a game character or a toy — unless the user's own words clearly call for " +
+ 'something else (anime, cartoon, chibi, voxel, robot, toy, low-poly, hand-painted, etc.); never mix styles. ' +
+ 'When the character is photoreal, weave in these cues: ' + PHOTOREAL_CUES + '; and specifically: ' +
+ subjectCues + '. (5) key identifying ' +
+ 'features (hair, face, color scheme, accessories). When the idea is sparse or generic ("a woman", "a knight", ' +
+ '"a cool guy"), do NOT default to the same safe, average person: commit to specific, memorable choices the ' +
+ 'user did not rule out: a particular age, build, and face character; a distinctive hairstyle and hair color; a ' +
+ 'named 2-3 color palette; one signature garment, pattern, or accessory that makes this character instantly ' +
+ 'recognizable in a lineup. Draw these choices from the mood and connotations of the words the user chose so two ' +
+ 'different ideas never converge on the same person. If the idea names a brand, meme, or term you do not ' +
+ "recognize, keep the user's stated character concept as the subject and render its canonical look; never " +
+ 'substitute a different character. Always end with these composition ' +
+ 'constraints: full body in frame head-to-toe, centered, isolated on a plain neutral background, no props ' +
+ 'gripped or crossing the silhouette, one camera angle facing the character, even studio lighting, no ' +
+ 'cropping, no motion blur, no text or watermark, no collage or multi-view grid, no second character. ' +
+ 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.'
+ );
+}
+
+// Back-compat default (person briefing) — existing call-sites and tests that
+// import the flat constant keep working unchanged; new call-sites should
+// classify the prompt and call avatarDirectorFor(subject) directly.
+export const AVATAR_DIRECTOR = avatarDirectorFor('person');
diff --git a/api/_lib/fork-royalties.js b/api/_lib/fork-royalties.js
index 069a73143..5281b99ee 100644
--- a/api/_lib/fork-royalties.js
+++ b/api/_lib/fork-royalties.js
@@ -24,6 +24,7 @@
// real income paths (tip + money-stream settlement) in api/agents/solana-wallet.js.
import { sql } from './db.js';
+import { insertNotification } from './notify.js';
// ── Platform policy constants (the fairness guardrails) ──────────────────────
@@ -443,7 +444,7 @@ async function recordSkips(forkAgentId, sourceEventId, kind, network, splits) {
async function settlePayouts({ forkAgentId, network, claimed, sourceEventId, kind }) {
// Load the fork's signer + verify it can cover the splits.
const [forkAgent] = await sql`
- select id, user_id, meta from agent_identities where id = ${forkAgentId} and deleted_at is null limit 1
+ select id, user_id, name, meta from agent_identities where id = ${forkAgentId} and deleted_at is null limit 1
`;
if (!forkAgent?.meta?.encrypted_solana_secret) {
await failRows(claimed, 'fork_wallet_unavailable');
@@ -537,6 +538,19 @@ async function settlePayouts({ forkAgentId, network, claimed, sourceEventId, kin
`.catch(() => {});
await mirrorCustody({ forkAgentId, ancestorAgentId: t.ancestor_agent_id, recipient: t.to,
lamports: t.lamports, signature: r.signature, network, kind, rerouted: t.rerouted });
+ if (t.ancestor_owner_id) {
+ let usd = null;
+ try { const { lamportsToUsd } = await import('./agent-trade-guards.js'); usd = await lamportsToUsd(t.lamports); } catch { /* unpriced */ }
+ insertNotification(t.ancestor_owner_id, 'royalty_paid', {
+ actor: forkAgent.name || 'A fork of your avatar',
+ sol: Number(t.lamports) / 1e9,
+ usd,
+ depth: t.depth,
+ signature: r.signature,
+ tx_signature: r.signature,
+ link: `/agent/${encodeURIComponent(t.ancestor_agent_id)}`,
+ });
+ }
}
}
}
diff --git a/api/_lib/material-studio-store.js b/api/_lib/material-studio-store.js
index 6a95adf7c..979724514 100644
--- a/api/_lib/material-studio-store.js
+++ b/api/_lib/material-studio-store.js
@@ -177,7 +177,14 @@ async function writeAndValidate(doc) {
// `materialIndex` when given). Geometry, accessors, and UVs are untouched —
// this only ever calls the Material setters, never the Mesh/Primitive ones —
// which is what guarantees "preserve mesh + UVs" through a restyle.
-function applyFactorsToDoc(doc, factors, materialIndex) {
+//
+// `factors` may additionally carry the measured-value extension fields
+// (clearcoatFactor/clearcoatRoughnessFactor, transmissionFactor, ior,
+// sheenColorFactor/sheenRoughnessFactor) — these are real KHR_materials_*
+// extensions, lazily attached to the document only when a factor set
+// actually uses them, so a plain restyle never grows a document with unused
+// extension declarations.
+async function applyFactorsToDoc(doc, factors, materialIndex) {
const materials = doc.getRoot().listMaterials();
if (!materials.length) {
throw new MaterialStudioError('source GLB has no materials to restyle', {
@@ -188,6 +195,21 @@ function applyFactorsToDoc(doc, factors, materialIndex) {
const targets =
Number.isInteger(materialIndex) && materials[materialIndex] ? [materials[materialIndex]] : materials;
+ const hasClearcoat = factors.clearcoatFactor != null || factors.clearcoatRoughnessFactor != null;
+ const hasTransmission = factors.transmissionFactor != null;
+ const hasIor = factors.ior != null;
+ const hasSheen = Array.isArray(factors.sheenColorFactor) || factors.sheenRoughnessFactor != null;
+
+ let KHRMaterialsClearcoat, KHRMaterialsTransmission, KHRMaterialsIOR, KHRMaterialsSheen;
+ if (hasClearcoat || hasTransmission || hasIor || hasSheen) {
+ // Extension classes import lazily — the (more common) factor-only
+ // restyle path never pays this cost.
+ ({ KHRMaterialsClearcoat, KHRMaterialsTransmission, KHRMaterialsIOR, KHRMaterialsSheen } = await import(
+ '@gltf-transform/extensions'
+ ));
+ }
+ let clearcoatExt, transmissionExt, iorExt, sheenExt;
+
for (const mat of targets) {
if (Array.isArray(factors.baseColorFactor) && factors.baseColorFactor.length === 4) {
mat.setBaseColorFactor(factors.baseColorFactor.map((v, i) => (i === 3 ? clamp01(v, 1) : clamp01(v))));
@@ -200,6 +222,35 @@ function applyFactorsToDoc(doc, factors, materialIndex) {
mat.setEmissiveFactor(factors.emissiveFactor.map((v) => clamp01(v)));
}
if (factors.name) mat.setName(factors.name);
+
+ if (hasClearcoat) {
+ clearcoatExt = clearcoatExt || doc.createExtension(KHRMaterialsClearcoat);
+ const clearcoat = clearcoatExt.createClearcoat();
+ if (factors.clearcoatFactor != null) clearcoat.setClearcoatFactor(clamp01(factors.clearcoatFactor));
+ if (factors.clearcoatRoughnessFactor != null) {
+ clearcoat.setClearcoatRoughnessFactor(clamp01(factors.clearcoatRoughnessFactor));
+ }
+ mat.setExtension('KHR_materials_clearcoat', clearcoat);
+ }
+ if (hasTransmission) {
+ transmissionExt = transmissionExt || doc.createExtension(KHRMaterialsTransmission);
+ const transmission = transmissionExt.createTransmission().setTransmissionFactor(clamp01(factors.transmissionFactor));
+ mat.setExtension('KHR_materials_transmission', transmission);
+ }
+ if (hasIor) {
+ iorExt = iorExt || doc.createExtension(KHRMaterialsIOR);
+ const ior = iorExt.createIOR().setIOR(Math.min(2.333, Math.max(1, Number(factors.ior) || 1.5)));
+ mat.setExtension('KHR_materials_ior', ior);
+ }
+ if (hasSheen) {
+ sheenExt = sheenExt || doc.createExtension(KHRMaterialsSheen);
+ const sheen = sheenExt.createSheen();
+ if (Array.isArray(factors.sheenColorFactor) && factors.sheenColorFactor.length === 3) {
+ sheen.setSheenColorFactor(factors.sheenColorFactor.map((v) => clamp01(v)));
+ }
+ if (factors.sheenRoughnessFactor != null) sheen.setSheenRoughnessFactor(clamp01(factors.sheenRoughnessFactor));
+ mat.setExtension('KHR_materials_sheen', sheen);
+ }
}
return targets.length;
}
@@ -305,10 +356,16 @@ export async function generateMaterialFactorsFromInstruction(instruction) {
}
const system =
'You are a 3D material author. Given a short restyle instruction (e.g. "make it chrome", "wooden", ' +
- '"cyberpunk neon"), return ONLY a valid JSON object describing a glTF 2.0 PBR material with keys: ' +
- '"name" (string), "baseColorFactor" ([r,g,b] 0-1), "metallicFactor" (0-1), "roughnessFactor" (0-1), ' +
- '"emissiveFactor" ([r,g,b] 0-1, [0,0,0] unless the instruction implies glow/light), and "notes" ' +
- '(one short sentence on the look). No markdown, no prose outside the JSON.';
+ '"cyberpunk neon", "car paint", "frosted glass"), return ONLY a valid JSON object describing a glTF 2.0 ' +
+ 'PBR material with keys: "name" (string), "baseColorFactor" ([r,g,b] 0-1), "metallicFactor" (0-1), ' +
+ '"roughnessFactor" (0-1), "emissiveFactor" ([r,g,b] 0-1, [0,0,0] unless the instruction implies glow/light), ' +
+ 'and "notes" (one short sentence on the look). Additionally, ONLY when the instruction implies these real ' +
+ 'physical effects, include: "clearcoatFactor" (0-1) + "clearcoatRoughnessFactor" (0-1) for a lacquered/' +
+ 'wet/car-paint/varnished look; "transmissionFactor" (0-1) + "ior" (1-2.333, real glass is ~1.45, water ' +
+ '~1.33, diamond ~2.42) for see-through glass/liquid/crystal; "sheenColorFactor" ([r,g,b] 0-1) + ' +
+ '"sheenRoughnessFactor" (0-1) for fabric/velvet/skin-like soft grazing highlights. Omit any key that does ' +
+ 'not apply — do not invent clearcoat/transmission/sheen for a plain metal or plastic instruction. ' +
+ 'No markdown, no prose outside the JSON.';
let result;
try {
result = await watsonxChatComplete(cfg, {
@@ -340,6 +397,12 @@ export async function generateMaterialFactorsFromInstruction(instruction) {
metallicFactor: typeof parsed.metallicFactor === 'number' ? parsed.metallicFactor : null,
roughnessFactor: typeof parsed.roughnessFactor === 'number' ? parsed.roughnessFactor : null,
emissiveFactor: Array.isArray(parsed.emissiveFactor) ? parsed.emissiveFactor.slice(0, 3) : [0, 0, 0],
+ clearcoatFactor: typeof parsed.clearcoatFactor === 'number' ? parsed.clearcoatFactor : null,
+ clearcoatRoughnessFactor: typeof parsed.clearcoatRoughnessFactor === 'number' ? parsed.clearcoatRoughnessFactor : null,
+ transmissionFactor: typeof parsed.transmissionFactor === 'number' ? parsed.transmissionFactor : null,
+ ior: typeof parsed.ior === 'number' ? parsed.ior : null,
+ sheenColorFactor: Array.isArray(parsed.sheenColorFactor) ? parsed.sheenColorFactor.slice(0, 3) : null,
+ sheenRoughnessFactor: typeof parsed.sheenRoughnessFactor === 'number' ? parsed.sheenRoughnessFactor : null,
notes: typeof parsed.notes === 'string' ? parsed.notes.slice(0, 300) : null,
model: result.model,
instruction: trimmed,
@@ -362,7 +425,7 @@ export async function restyleMaterialFromInstruction({
const factors = await generateMaterialFactorsFromInstruction(instruction);
const sourceBytes = await fetchGlbBytes(safeUrl);
const doc = await loadDocument(sourceBytes);
- const materialsEdited = applyFactorsToDoc(doc, factors, materialIndex);
+ const materialsEdited = await applyFactorsToDoc(doc, factors, materialIndex);
const outBytes = await writeAndValidate(doc);
const persisted = await validateAndPersistGlb(Buffer.from(outBytes), { keyPrefix: 'material-studio/restyle' });
@@ -435,8 +498,14 @@ export async function generateSeededVariants({
roughnessFactor: variant.config.roughness,
emissiveFactor: variant.config.emissive ? hexToFactor(variant.config.emissive, [0, 0, 0]) : [0, 0, 0],
name: variant.label,
+ clearcoatFactor: variant.config.clearcoat ?? null,
+ clearcoatRoughnessFactor: variant.config.clearcoatRoughness ?? null,
+ transmissionFactor: variant.config.transmission ?? null,
+ ior: variant.config.ior ?? null,
+ sheenColorFactor: variant.config.sheenColor ? hexToFactor(variant.config.sheenColor, [0, 0, 0]) : null,
+ sheenRoughnessFactor: variant.config.sheenRoughness ?? null,
};
- applyFactorsToDoc(doc, factors, materialIndex);
+ await applyFactorsToDoc(doc, factors, materialIndex);
const outBytes = await writeAndValidate(doc);
const persisted = await validateAndPersistGlb(Buffer.from(outBytes), {
keyPrefix: 'material-studio/variants',
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.js
index de36588e2..47b5b6136 100644
--- a/api/_lib/notify-prefs.js
+++ b/api/_lib/notify-prefs.js
@@ -69,6 +69,7 @@ const TYPE_CATEGORY = {
referral_signup: 'sales',
referral_reward: 'sales',
pump_launch_filled: 'sales',
+ royalty_paid: 'sales',
skill_purchase_confirmed: 'purchases',
asset_purchase_confirmed: 'purchases',
@@ -83,6 +84,7 @@ const TYPE_CATEGORY = {
follow: 'social',
dm_received: 'social',
agent_review: 'social',
+ quest_complete: 'social',
irl_interaction: 'irl',
irl_reply: 'irl',
@@ -219,6 +221,8 @@ const PUSH_COPY = {
follow: (p) => ['New follower 👤', p.actor ? `${p.actor} started following you` : 'Someone started following you'],
dm_received: (p) => ['New message 💬', p.actor ? `${p.actor} sent you a message` : 'You have a new message'],
agent_review: (p) => ['New review ⭐', p.actor ? `${p.actor} reviewed your agent` : 'Your agent received a review'],
+ quest_complete: (p) => ['Quest complete 🏆', p.mission ? `You finished "${p.mission}"${p.gold ? ` — earned ${p.gold} gold` : ''}` : 'You finished a quest'],
+ royalty_paid: (p) => ['Royalty earned 💰', p.usd ? `A fork paid you $${Number(p.usd).toFixed(3)} in royalties` : (p.sol ? `A fork paid you ${Number(p.sol).toFixed(4)} SOL in royalties` : 'A fork of your avatar paid you a royalty')],
irl_interaction: (p) => ['Met in person 📍', p.message ? `“${p.message}”` : 'Someone interacted with your agent in person'],
irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],
pump_alert: (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],
diff --git a/api/_lib/okx-catalog.js b/api/_lib/okx-catalog.js
index aaa18d22d..a10ad9dde 100644
--- a/api/_lib/okx-catalog.js
+++ b/api/_lib/okx-catalog.js
@@ -1,11 +1,11 @@
-// OKX.AI (X Layer agent marketplace) service catalog — the single source of
+// OKX.AI (X Layer agent marketplace) service catalog, the single source of
// truth for every A2MCP service agent #2632 "three.ws 3D Studio" sells on
// OKX.AI. Endpoints, the free catalog/health service, tests, AND the listing
// update submitted to OKX all read from this module, so the live endpoints can
// never drift from the marketplace listing.
//
-// OKX listing format: every service carries a 2-part description — part 1 says
-// what the service does, part 2 says what the caller must provide — and each
+// OKX listing format: every service carries a 2-part description, part 1 says
+// what the service does, part 2 says what the caller must provide, and each
// part must fit in 200 display-width characters, where East-Asian wide glyphs
// count 2 and everything else counts 1 (OKX rejects over-length listings).
// `validateCatalog()` enforces this; tests/okx-catalog.test.js runs it in CI.
@@ -51,7 +51,7 @@ function usdToAtomics(usd) {
}
// One row per marketplace service. Fields:
-// id URL slug — the service's route is /api/okx/3d/<id>
+// id URL slug, the service's route is /api/okx/3d/<id>
// name Listing display name
// kind 'a2mcp' (MCP Streamable HTTP JSON-RPC) | 'rest' (plain JSON GET)
// describes 2-part OKX listing description { capability, input }
@@ -107,7 +107,7 @@ export const OKX_CATALOG = Object.freeze([
type: 'string',
format: 'uri',
description:
- 'Optional public image to guide the look. Validated before any charge — an ' +
+ 'Optional public image to guide the look. Validated before any charge, an ' +
'unreachable URL fails the call without settling payment.',
},
},
@@ -116,7 +116,7 @@ export const OKX_CATALOG = Object.freeze([
// ── Work order 03: the decomposed 3D studio ────────────────────────────
// Micro-priced REST services, one capability per endpoint, all backed by
// the same engines /api/mcp-3d runs on (api/_okx3d/rest-services.js maps
- // each id to its engine — no logic duplicated). Prices clear worst-case
+ // each id to its engine, no logic duplicated). Prices clear worst-case
// lane cost; the math is recorded in prompts/okx-ai/PROGRESS.md.
{
id: 'text-to-3d',
@@ -375,13 +375,13 @@ export function catalogEntry(id) {
return OKX_CATALOG.find((e) => e.id === id) || null;
}
-// The OKX listing description string: part ① and part ② joined on a newline —
+// The OKX listing description string: part ① and part ② joined on a newline,
// the layout the approved sellers use. Work order 05 submits this verbatim.
export function listingDescription(entry) {
return `${entry.describes.capability}\n${entry.describes.input}`;
}
-// The machine-readable index the free catalog service returns — the exact
+// The machine-readable index the free catalog service returns, the exact
// payload OKX buyers (and work order 05's listing update) consume.
export function catalogIndex() {
return {
@@ -402,7 +402,7 @@ export function catalogIndex() {
};
}
-// Catalog integrity check — throws on the first malformed entry. Tests call
+// Catalog integrity check, throws on the first malformed entry. Tests call
// this; anything that would get the listing rejected fails CI instead.
export function validateCatalog(catalog = OKX_CATALOG) {
const seen = new Set();
@@ -437,7 +437,7 @@ export function validateCatalog(catalog = OKX_CATALOG) {
if (e.kind === 'a2mcp' && (!e.tool || !e.inputSchema)) {
throw new Error(`${ctx}: a2mcp row needs tool + inputSchema`);
}
- // Paid REST rows must document their POST body — the catalog service and
+ // Paid REST rows must document their POST body, the catalog service and
// the listing both surface the schema, and buyers have nothing else.
if (e.kind === 'rest' && !free && !e.inputSchema) {
throw new Error(`${ctx}: paid rest row needs inputSchema`);
diff --git a/api/_lib/quality-bench.js b/api/_lib/quality-bench.js
new file mode 100644
index 000000000..2e6efe255
--- /dev/null
+++ b/api/_lib/quality-bench.js
@@ -0,0 +1,201 @@
+// Shared core for the realism eval harness (scripts/quality-bench.mjs — the full,
+// resumable, git-committed run — and api/cron/quality-bench.js — the bounded
+// weekly regression sweep that runs in-process on Cloud Run). One place for the
+// generate → render → judge pipeline so the two callers can never drift apart on
+// what "a scored view" means.
+//
+// See prompts/quality-bar/09-realism-eval-harness.md for the mission spec and
+// data/quality-bench/README.md for how to run/read/extend the bench.
+
+import { renderClip } from './render-clip.js';
+import { vertexGeminiAvailable, vertexGeminiChatUrl, vertexGeminiHeaders } from './vertex-gemini.js';
+
+// Judge model — fixed here (not env-tunable) so every run in the repo's history
+// used the same rung unless this constant itself changed via a reviewed commit.
+export const JUDGE_MODEL = 'google/gemini-2.5-pro';
+export const JUDGE_PROMPT_VERSION = 1;
+const JUDGE_MAX_TOKENS = 700;
+
+// Front, three-quarter, side — matches the studio-product framing render-clip.js
+// already uses for avatar thumbnails (phi=78deg, just above eye level).
+export const CANONICAL_VIEWS = [
+ { label: 'front', theta: 0, phi: 78 },
+ { label: 'three-quarter', theta: 40, phi: 78 },
+ { label: 'side', theta: 90, phi: 78 },
+];
+
+export const RENDER_BACKGROUND = '#14151a';
+
+// Never receives forge's internal art-director/enhanced prompt text — only the
+// benchmark's own fixed prompt string and subject-class watchlist — so the judge
+// can't inflate prompt-adherence by grading against its own prior expansion
+// (anti-gaming rule in the mission spec).
+export function buildJudgePrompt({ prompt, subjectClass, watch, viewLabel }) {
+ return `You are a strict, expert 3D-asset realism critic. You are shown ONE rendered view ("${viewLabel}") of a textured 3D model generated from this brief:
+
+Subject class: ${subjectClass}
+Original brief: "${prompt}"
+
+Known failure modes to specifically check for on this subject class:
+${watch.map((w) => `- ${w}`).join('\n')}
+
+Score the render on four axes, 1-10 (10 = indistinguishable from a real photograph / studio 3D render, 1 = broken):
+- photorealism: does material/lighting/surface read as real, not "game asset" or plastic?
+- geometryIntegrity: is the mesh coherent (no blobs, no fused limbs/parts, no melted details)?
+- textureFidelity: are textures sharp, non-tiling, and free of baked-in artifacts?
+- promptAdherence: does the render actually depict the brief above?
+
+Reply with ONLY a JSON object, no markdown fence, no prose outside the JSON:
+{"photorealism": <1-10 integer>, "geometryIntegrity": <1-10 integer>, "textureFidelity": <1-10 integer>, "promptAdherence": <1-10 integer>, "critique": "<one sentence, concrete, naming the specific defect or strength you observed>"}`;
+}
+
+function parseJudgeJson(text) {
+ const trimmed = String(text || '').trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
+ const start = trimmed.search(/[{[]/);
+ const candidate = start >= 0 ? trimmed.slice(start) : trimmed;
+ const parsed = JSON.parse(candidate);
+ for (const k of ['photorealism', 'geometryIntegrity', 'textureFidelity', 'promptAdherence']) {
+ const n = Number(parsed[k]);
+ if (!Number.isFinite(n)) throw new Error(`judge reply missing numeric ${k}`);
+ parsed[k] = Math.max(1, Math.min(10, n));
+ }
+ if (typeof parsed.critique !== 'string') parsed.critique = '';
+ return parsed;
+}
+
+// One judge call against one rendered PNG. Throws on any failure (unconfigured
+// Vertex, transport error, unparseable reply) — callers must record that as a
+// failed score, never fabricate one.
+export async function judgeOnce({ png, promptEntry, viewLabel }) {
+ if (!vertexGeminiAvailable()) {
+ throw Object.assign(new Error('Vertex Gemini unavailable: GOOGLE_CLOUD_PROJECT is not set in this environment'), { code: 'judge_unconfigured' });
+ }
+ const headers = await vertexGeminiHeaders();
+ const text = buildJudgePrompt({ ...promptEntry, viewLabel });
+ const dataUri = `data:image/png;base64,${png.toString('base64')}`;
+ const body = {
+ model: JUDGE_MODEL,
+ temperature: 0,
+ max_tokens: JUDGE_MAX_TOKENS,
+ messages: [
+ { role: 'user', content: [
+ { type: 'text', text },
+ { type: 'image_url', image_url: { url: dataUri } },
+ ] },
+ ],
+ };
+ const res = await fetch(vertexGeminiChatUrl(), { method: 'POST', headers, body: JSON.stringify(body) });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(`judge call ${res.status}: ${JSON.stringify(data).slice(0, 300)}`);
+ const content = data?.choices?.[0]?.message?.content || '';
+ const parsed = parseJudgeJson(content);
+ return { ...parsed, modelVersion: data?.model || data?.modelVersion || JUDGE_MODEL };
+}
+
+export function avgScores(scores) {
+ const dims = ['photorealism', 'geometryIntegrity', 'textureFidelity', 'promptAdherence'];
+ const out = {};
+ for (const d of dims) out[d] = scores.reduce((s, x) => s + x[d], 0) / scores.length;
+ out.mean = dims.reduce((s, d) => s + out[d], 0) / dims.length;
+ return out;
+}
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+export async function loadCatalog(baseUrl) {
+ const res = await fetch(`${baseUrl}/api/forge?catalog`);
+ if (!res.ok) throw new Error(`catalog fetch failed: ${res.status}`);
+ return res.json();
+}
+
+export async function submitForge(baseUrl, { prompt, mode, referenceImageUrl, tier, backend }) {
+ const body = { prompt, tier, backend };
+ if (mode === 'image' && referenceImageUrl) body.image_urls = [referenceImageUrl];
+ const res = await fetch(`${baseUrl}/api/forge`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const err = new Error(data?.error || data?.message || `forge submit ${res.status}`);
+ err.status = res.status;
+ err.code = data?.code;
+ throw err;
+ }
+ return data;
+}
+
+export async function pollForge(baseUrl, jobId, { timeoutMs = 10 * 60 * 1000, intervalMs = 4000 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const res = await fetch(`${baseUrl}/api/forge?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data?.error || `poll ${res.status}`);
+ if (data.status === 'done') return data;
+ if (data.status === 'failed') {
+ const err = new Error(data?.error || 'generation failed');
+ err.code = 'generation_failed';
+ throw err;
+ }
+ await sleep(intervalMs);
+ }
+ throw new Error(`poll timed out after ${timeoutMs}ms`);
+}
+
+export async function generate(baseUrl, params) {
+ const submitted = await submitForge(baseUrl, params);
+ if (submitted.status === 'done' && submitted.glb_url) return submitted;
+ if (submitted.job_id) return pollForge(baseUrl, submitted.job_id);
+ throw new Error(`unexpected forge response shape: ${JSON.stringify(submitted).slice(0, 300)}`);
+}
+
+// Run one (prompt, lane, tier) combo end to end: generate -> render 3 views ->
+// judge each view twice -> average. Never throws for a generation/scoring
+// failure — returns a result object with status set instead, so a caller
+// iterating many combos never has one bad lane abort the whole sweep.
+export async function runOne(baseUrl, promptEntry, lane, tier) {
+ const result = { promptId: promptEntry.id, subjectClass: promptEntry.subjectClass, lane, tier, startedAt: new Date().toISOString() };
+ try {
+ const gen = await generate(baseUrl, {
+ prompt: promptEntry.prompt,
+ mode: promptEntry.mode,
+ referenceImageUrl: promptEntry.referenceImageUrl,
+ tier,
+ backend: lane,
+ });
+ result.glbUrl = gen.glb_url;
+ result.creationId = gen.creation_id ?? null;
+ result.views = [];
+ for (const view of CANONICAL_VIEWS) {
+ const viewResult = { view: view.label };
+ try {
+ const { png } = await renderClip({
+ glbUrl: gen.glb_url,
+ width: 1024,
+ height: 1024,
+ background: RENDER_BACKGROUND,
+ cameraOrbit: { theta: view.theta, phi: view.phi },
+ });
+ const scores = [];
+ for (let i = 0; i < 2; i += 1) scores.push(await judgeOnce({ png, promptEntry, viewLabel: view.label }));
+ viewResult.scores = scores;
+ viewResult.avg = avgScores(scores);
+ } catch (viewErr) {
+ viewResult.error = viewErr.message;
+ }
+ result.views.push(viewResult);
+ }
+ const okViews = result.views.filter((v) => v.avg);
+ result.status = okViews.length ? 'ok' : 'scoring_failed';
+ result.meanScore = okViews.length ? okViews.reduce((s, v) => s + v.avg.mean, 0) / okViews.length : null;
+ } catch (genErr) {
+ result.status = 'lane_failed';
+ result.error = genErr.message;
+ result.meanScore = 0;
+ }
+ result.finishedAt = new Date().toISOString();
+ return result;
+}
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.js
index 76900c6bd..e6071daeb 100644
--- a/api/_lib/render-clip.js
+++ b/api/_lib/render-clip.js
@@ -10,13 +10,13 @@
// 4. Renders one PNG.
//
// The same module powers both transparent OG cards and the full clip
-// renderer — single source of truth for headless three.js rendering so the
+// renderer, single source of truth for headless three.js rendering so the
// MCP tool, the OG card, and any future video renderer share lighting +
// framing.
// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()
// so Vercel's NFT doesn't statically trace the chromium tree for every route
-// that transitively imports this module — that trace caused 45-min build hangs.
+// that transitively imports this module, that trace caused 45-min build hangs.
import { env } from './env.js';
import { fetchModel } from './fetch-model.js';
import { PRESETS } from '../../src/pose-presets.js';
@@ -89,7 +89,7 @@ renderer.setSize(${width}, ${height}, false);
renderer.setPixelRatio(1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
// Neutral (Khronos PBR Neutral) tone mapping renders asset colors faithfully
-// without the shadow-crushing ACES rolloff — the right choice for a product
+// without the shadow-crushing ACES rolloff, the right choice for a product
// render where the character must read clearly.
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1.15;
@@ -102,7 +102,7 @@ const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);
// Image-based lighting is what makes PBR materials read: metal and glossy
// surfaces draw their reflections from scene.environment, so with none set they
-// collapse to near-black — the "dark, murky" render. RoomEnvironment is three's
+// collapse to near-black, the "dark, murky" render. RoomEnvironment is three's
// built-in procedural studio environment (no external HDR asset to host).
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index ff8279e80..78718cb23 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -1,4 +1,4 @@
-// x402 protocol — facilitator-mediated micropayments.
+// x402 protocol, facilitator-mediated micropayments.
// Spec: https://x402.org / https://github.com/coinbase/x402
//
// This module implements the *standard* x402 wire flow used by agentic.market,
@@ -16,7 +16,7 @@
// }
//
// In addition to the body, the same envelope is emitted base64-encoded as the
-// `payment-required` HTTP response header — required by agentic.market's
+// `payment-required` HTTP response header, required by agentic.market's
// Bazaar validator, which reads the header on its discovery probe.
//
// Networks use CAIP-2 IDs in v2: `eip155:<chainId>` for EVM, `solana:<genesis-prefix>`
@@ -85,7 +85,7 @@ export const X402_VERSION = 2;
// requirement opts into the Permit2 asset-transfer method, the facilitator
// (CDP's x402ExactPermit2Proxy) lets the payer skip broadcasting the Permit2
// approval themselves. EIP-2612 sponsorship is the preferred path for tokens
-// that implement EIP-2612 (Base USDC v2 does — the facilitator submits the
+// that implement EIP-2612 (Base USDC v2 does, the facilitator submits the
// off-chain permit via settleWithPermit). ERC-20 approval sponsorship is the
// universal fallback for any other ERC-20: the client signs (but does not
// broadcast) a raw approve(Permit2, MaxUint256) tx and the facilitator
@@ -105,7 +105,7 @@ export const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
export const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
// Networks the CDP facilitator settles when credentials are configured.
-// Confirmed against the live /supported probe — CDP advertises exact for Base
+// Confirmed against the live /supported probe, CDP advertises exact for Base
// and Arbitrum but NOT Optimism, so Optimism is deliberately absent: no accept
// entry routes there, and listing it only made /api/x402-status report 503.
const CDP_EVM_NETWORKS = new Set([
@@ -128,7 +128,7 @@ const DIRECT_NETWORKS = new Set([NETWORK_BSC_MAINNET]);
//
// Returns null when:
// 1. The source accept is not an EVM `exact` entry (BSC direct + Solana).
-// 2. CDP credentials are missing — Permit2 settlement is a CDP-only path
+// 2. CDP credentials are missing, Permit2 settlement is a CDP-only path
// (PayAI's facilitator only advertises `exact` with EIP-3009). Emitting
// a Permit2 sibling we can't actually settle would mislead clients into
// signing a typed-data we'd then reject at /verify time.
@@ -157,7 +157,7 @@ function pushEvmAccepts(out, accept) {
}
// One v2 PaymentRequirements entry per supported network. Base mainnet first
-// — agentic.market's validator inspects the first entry for its supported-network
+//, agentic.market's validator inspects the first entry for its supported-network
// check, and Base is the most broadly recognized option in the Bazaar.
//
// In v2, `resource` / `description` / `mimeType` are top-level on the 402 body
@@ -190,9 +190,9 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
});
// $THREE alongside USDC on the same Solana rail (opt-in via
- // X402_ACCEPT_THREE_SOLANA — see env.js). Pushed AFTER the USDC entry so
+ // X402_ACCEPT_THREE_SOLANA, see env.js). Pushed AFTER the USDC entry so
// clients that pick the first Solana accept keep settling USDC; the modal
- // surfaces both as a token chooser. Same fee-payer co-sign path — the
+ // surfaces both as a token chooser. Same fee-payer co-sign path, the
// checkout server transfers any SPL mint, so no extra wiring is needed.
if (env.X402_ACCEPT_THREE_SOLANA && env.X402_FEE_PAYER_SOLANA) {
out.push({
@@ -218,7 +218,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
});
}
if (env.X402_PAY_TO_BSC) {
- // BSC uses the contract-mediated "direct" scheme — see x402-bsc-direct.js
+ // BSC uses the contract-mediated "direct" scheme, see x402-bsc-direct.js
// for the wire flow. Clients call ThreeWSPayments.pay(ref) themselves and
// hand back the resulting tx hash via the X-PAYMENT header.
out.push({
@@ -236,7 +236,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
},
});
}
- // OKX Agent Payments Protocol rail — USD₮0 on X Layer (eip155:196), per
+ // OKX Agent Payments Protocol rail, USD₮0 on X Layer (eip155:196), per
// specs/okx-agent-payments.md. Advertised only when settlement is actually
// possible (OKX facilitator creds or the direct-redemption relayer key).
// USD₮0 shares USDC's 6-decimal atomic scale, so per-tool amounts carry
@@ -248,7 +248,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
}
// Lazy CDP auth-headers factory. createCdpAuthHeaders() returns an async fn that,
-// when invoked, returns { verify, settle, supported, list } header maps — each
+// when invoked, returns { verify, settle, supported, list } header maps, each
// including a Correlation-Context tag and (when keys are set) a per-operation
// signed JWT in Authorization. We instantiate once per process; the inner fn
// re-signs on every call (JWTs are short-lived).
@@ -278,20 +278,20 @@ export function facilitatorFor(network) {
const solana = resolveSolanaFacilitator();
return { url: solana.url, token: env.X402_FACILITATOR_TOKEN_SOLANA, self: solana.self };
}
- // BSC settles via on-chain pay() — no facilitator needed. The {direct:true}
+ // BSC settles via on-chain pay(), no facilitator needed. The {direct:true}
// marker tells verifyPayment/settlePayment to bypass HTTP entirely and call
// the local verifier in x402-bsc-direct.js.
if (DIRECT_NETWORKS.has(network) || network === 'bsc') {
return { direct: true };
}
- // X Layer settles via the OKX Agent Payments Protocol rail — the official
+ // X Layer settles via the OKX Agent Payments Protocol rail, the official
// OKX facilitator when credentialed, direct EIP-3009 redemption otherwise.
// The {okxXLayer:true} marker routes to x402-xlayer-okx.js.
if (network === NETWORK_XLAYER_MAINNET || network === 'xlayer') {
return { okxXLayer: true };
}
// EVM mainnets supported by Coinbase CDP. When CDP keys are set, route all
- // of them through CDP (required for CDP Bazaar / agentic.market — only
+ // of them through CDP (required for CDP Bazaar / agentic.market, only
// endpoints whose first verify+settle is processed by CDP get cataloged).
// Base mainnet falls back to X402_FACILITATOR_URL_BASE (PayAI by default)
// when CDP keys are absent; other EVM chains require CDP.
@@ -319,13 +319,13 @@ export function facilitatorFor(network) {
// CDP creds are set, otherwise to X402_FACILITATOR_URL_BASE. Treat Base as
// settleable ONLY when we can trust it will verify+settle:
//
-// 1. CDP credentials are configured — Base routes to Coinbase's facilitator, a
+// 1. CDP credentials are configured, Base routes to Coinbase's facilitator, a
// known-good, platform-trusted path.
// 2. The operator has EXPLICITLY opted in via X402_ADVERTISE_BASE=true.
//
// A bare X402_FACILITATOR_URL_BASE being SET is deliberately NOT enough. Prod had
// it pointed at a facilitator host that answers every /verify with `404 Application
-// not found` — so a Base accept was advertised (buyers pick it first), the buyer
+// not found`, so a Base accept was advertised (buyers pick it first), the buyer
// paid, verification 404'd, and they got a 502. A URL string is not proof the
// endpoint behind it works; only CDP or a deliberate operator opt-in is. Self-heals
// the moment either is set. Solana is unaffected: it settles via whatever
@@ -341,24 +341,24 @@ export function baseSettleable() {
// will reject AFTER the buyer has paid. Solana settlement routes via
// resolveSolanaFacilitator():
//
-// • EXTERNAL facilitator (PayAI, or an explicit non-self URL) — it holds its
+// • EXTERNAL facilitator (PayAI, or an explicit non-self URL), it holds its
// own sponsor key and co-signs; we trust that path, so the accept settles.
-// • Our SELF-hosted facilitator — settle co-signs sponsor-mode payments with
+// • Our SELF-hosted facilitator, settle co-signs sponsor-mode payments with
// X402_FEE_PAYER_SECRET_BASE58 (api/_lib/x402/self-facilitator.js). Without
// that secret loaded, EVERY sponsor-mode settle throws
// `sponsor_key_unconfigured` and the buyer eats a 502 AFTER submitting a
-// signed payment — the exact production failure this gate closes (80× 502 on
+// signed payment, the exact production failure this gate closes (80× 502 on
// /api/x402/dance-tip, crypto-intel, three-intel in the 2026-07-03 export).
// So self-routing is settleable only when the co-signing secret is present.
//
// The 402 challenge already requires X402_FEE_PAYER_SOLANA (the advertised
// sponsor PUBKEY); this adds the matching requirement that we can actually SIGN
-// for it. Self-heals the instant the secret is set — no redeploy needed.
+// for it. Self-heals the instant the secret is set, no redeploy needed.
export function solanaSettleable() {
const route = resolveSolanaFacilitator();
if (!route.self) return true; // external facilitator co-signs with its own key
// SELF-PAY (X402_RING_SELF_PAY): the buyer signs its own 1-signature fee and the
- // self-facilitator only BROADCASTS the already-signed tx — no sponsor key is
+ // self-facilitator only BROADCASTS the already-signed tx, no sponsor key is
// used (settleRingPayment's `if (!selfPay)` branch skips loadFeePayerKeypair).
// So self-routing is settleable when self-pay is on, even with no sponsor
// secret. Sponsor mode still requires the co-signing secret.
@@ -370,7 +370,7 @@ export function solanaSettleable() {
// call send402()/verifyPayment() directly instead of going through paidEndpoint().
// Emits the platform-standard accept set for a USDC price:
//
-// 1. Solana first — the always-on, self-hosted settle rail (first-accept clients
+// 1. Solana first, the always-on, self-hosted settle rail (first-accept clients
// and wallet modals settle here).
// 2. Base second, but ONLY when baseSettleable() (CDP creds or explicit opt-in)
// AND the Base pay-to/asset are configured. A dead or unconfigured Base
@@ -489,8 +489,8 @@ const FACILITATOR_TIMEOUT_MS_DEFAULT = (() => {
// Upstream statuses that signal a transient facilitator / payment-network
// hiccup (gateway down, settlement service overloaded) rather than a rejected
-// payment. A 4xx — including 402 (payment required), 409 (idempotency
-// conflict), and 400-with-isValid:false — is a definitive answer and is never
+// payment. A 4xx, including 402 (payment required), 409 (idempotency
+// conflict), and 400-with-isValid:false, is a definitive answer and is never
// retried.
const TRANSIENT_FACILITATOR_STATUS = new Set([502, 503, 504]);
@@ -523,14 +523,14 @@ async function callFacilitator(
if (idempotencyKey) {
// Both casing variants appear in the wild (PayAI uses `Idempotency-Key`,
// some Cloudflare-fronted facilitators normalize to lowercase). Send both
- // for maximum compatibility — fetch headers are case-insensitive on the
+ // for maximum compatibility, fetch headers are case-insensitive on the
// wire so this is just a Node-level convenience.
headers['Idempotency-Key'] = idempotencyKey;
}
// Retries are only safe for idempotent calls: /verify mutates no state, and
// /settle carries the deterministic Idempotency-Key from buildIdempotencyKey
// so a re-sent settle is de-duplicated by the facilitator instead of paying
- // twice. A settle without a key (legacy callers) gets a single attempt — we
+ // twice. A settle without a key (legacy callers) gets a single attempt, we
// won't risk a double-spend to recover from a blip.
const retryable = path === '/verify' || Boolean(idempotencyKey);
const serializedBody = JSON.stringify(body);
@@ -546,12 +546,12 @@ async function callFacilitator(
signal: AbortSignal.timeout(timeoutMs || FACILITATOR_TIMEOUT_MS_DEFAULT),
});
} catch (err) {
- // Network failure / timeout — transient. Retry once for idempotent
+ // Network failure / timeout, transient. Retry once for idempotent
// calls before giving up.
if (retryable && attempt < retries) {
attempt += 1;
console.warn(
- `[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message} — retry ${attempt}/${retries} in 500ms`,
+ `[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message}, retry ${attempt}/${retries} in 500ms`,
);
await new Promise((r) => setTimeout(r, 500));
continue;
@@ -584,12 +584,12 @@ async function callFacilitator(
}
}
if (!res.ok) {
- // PayAI returns 400 with { isValid: false } for invalid payments —
+ // PayAI returns 400 with { isValid: false } for invalid payments,
// pass through so verifyPayment can emit a clean 402 to the caller.
if (path === '/verify' && data.isValid === false) return data;
const detail = summarizeUpstream(data, text);
// A 400 from /verify means the facilitator rejected the *payment
- // payload itself* (malformed X-PAYMENT header, wrong scheme, etc.) —
+ // payload itself* (malformed X-PAYMENT header, wrong scheme, etc.),
// that's a client error, not an upstream outage. CDP signals it with
// an `errorMessage` and no `isValid` field, so the PayAI passthrough
// above misses it and we'd otherwise 502. Normalize to an
@@ -604,13 +604,13 @@ async function callFacilitator(
invalidReason: detail || 'payment payload rejected by facilitator',
};
}
- // Transient upstream 5xx — the payment network or settlement service
+ // Transient upstream 5xx, the payment network or settlement service
// blinked. Retry once for idempotent calls; the Idempotency-Key keeps
// a re-sent settle from double-paying.
if (retryable && TRANSIENT_FACILITATOR_STATUS.has(res.status) && attempt < retries) {
attempt += 1;
console.warn(
- `[x402] facilitator ${path} ${res.status} (host=${host}, network=${network}): ${detail} — retry ${attempt}/${retries} in 500ms`,
+ `[x402] facilitator ${path} ${res.status} (host=${host}, network=${network}): ${detail}, retry ${attempt}/${retries} in 500ms`,
);
await new Promise((r) => setTimeout(r, 500));
continue;
@@ -633,7 +633,7 @@ async function callFacilitator(
// /api/x402-status to surface misconfigurations before a paying client hits them.
//
// When CDP credentials are configured we probe every CDP-supported EVM network,
-// not just Base — `wk.js` advertises Arbitrum acceptance for /api/x402/model-check
+// not just Base, `wk.js` advertises Arbitrum acceptance for /api/x402/model-check
// and `permit2VariantOf` emits Permit2 siblings on any EVM `exact` accept, so
// the status surface needs to confirm the facilitator supports each of those
// networks. Without CDP creds, Base is the only EVM we can actually settle.
@@ -646,8 +646,8 @@ export async function probeFacilitators() {
...evmNetworks.map((network) => ({ network, ...facilitatorFor(network) })),
{ network: NETWORK_SOLANA_MAINNET, ...facilitatorFor(NETWORK_SOLANA_MAINNET) },
];
- // The self-hosted facilitator is probed whenever its flag is on — even when
- // an explicit external URL wins the routing — and reported as a distinct
+ // The self-hosted facilitator is probed whenever its flag is on, even when
+ // an explicit external URL wins the routing, and reported as a distinct
// entry, so a mis-enveloped deploy shows the self facilitator's health right
// next to wherever settlement actually routes.
if (selfFacilitatorEnabled()) {
@@ -763,7 +763,7 @@ function detectAssetTransferMethod(paymentPayload) {
// True for accepts[] entries that exist only to advertise an authentication
// alternative (USE-21 auth-hints): zero-amount placeholders flagged with
// `extra.authRequired`. They are redeemed by presenting the matching auth
-// header (Authorization / SIGN-IN-WITH-X) BEFORE the payment dance — never by
+// header (Authorization / SIGN-IN-WITH-X) BEFORE the payment dance, never by
// an X-PAYMENT header. verifyPayment must exclude them from requirement
// matching so the invariant is enforced structurally rather than relying on
// the real entries happening to sort first: otherwise a crafted payload (e.g.
@@ -778,14 +778,14 @@ function isAuthHintAccept(requirement) {
// Match the decoded payload to one of the offered requirements. The match is
// by (network, assetTransferMethod) when we can detect the method from the
-// payload shape — needed because we now publish two accept entries per EVM
+// payload shape, needed because we now publish two accept entries per EVM
// network (EIP-3009 first, Permit2 sibling second), and the facilitator's
// /verify call has to receive the same `extra` block the client signed
// against. Falls back to first-match-by-network for non-EVM payloads (Solana
// SPL, BSC direct).
function selectRequirement(paymentPayload, allRequirements) {
// OKX-dialect payloads (PAYMENT-SIGNATURE header) carry the chosen entry as
- // `accepted` instead of top-level scheme/network — see x402-xlayer-okx.js.
+ // `accepted` instead of top-level scheme/network, see x402-xlayer-okx.js.
const network =
paymentPayload?.network ||
paymentPayload?.accepted?.network ||
@@ -816,7 +816,7 @@ function selectRequirement(paymentPayload, allRequirements) {
// Extract the signed amount from a v2 PaymentPayload, regardless of scheme.
// Returns a BigInt in the asset's atomic units (USDC → 6-decimal micros).
// Returns null when the payload's amount can't be located without trusting
-// the facilitator — Solana SPL transfers carry the amount inside an opaque
+// the facilitator, Solana SPL transfers carry the amount inside an opaque
// serialized transaction we won't parse client-side, so we leave that check
// to the facilitator + the on-chain confirmation. Returning null means
// "facilitator-trusted amount"; returning a BigInt means "we just verified
@@ -828,7 +828,7 @@ function selectRequirement(paymentPayload, allRequirements) {
export function decodeSignedAmount(paymentPayload) {
const inner = paymentPayload?.payload;
if (!inner || typeof inner !== 'object') return null;
- // EIP-3009 transferWithAuthorization — `authorization.value` is the
+ // EIP-3009 transferWithAuthorization, `authorization.value` is the
// EIP-712 typed-data field clients sign. uint256 string in atomic units.
if (inner.authorization && typeof inner.authorization === 'object') {
const v = inner.authorization.value;
@@ -840,7 +840,7 @@ export function decodeSignedAmount(paymentPayload) {
}
}
}
- // Permit2 PermitWitnessTransferFrom — `permitted.amount` is what the user
+ // Permit2 PermitWitnessTransferFrom, `permitted.amount` is what the user
// authorizes. @x402/evm exposes the structured permit object pre-broadcast.
if (inner.permit2Authorization && typeof inner.permit2Authorization === 'object') {
const permitted = inner.permit2Authorization?.permit?.permitted;
@@ -877,12 +877,12 @@ export function decodeSignedAmount(paymentPayload) {
export function decodeSignedRecipient(paymentPayload) {
const inner = paymentPayload?.payload;
if (!inner || typeof inner !== 'object') return null;
- // EIP-3009 transferWithAuthorization — `authorization.to` is signed.
+ // EIP-3009 transferWithAuthorization, `authorization.to` is signed.
if (inner.authorization && typeof inner.authorization === 'object') {
const to = inner.authorization.to;
if (typeof to === 'string' && to) return to.toLowerCase();
}
- // Permit2 — the spend recipient travels in the witness/transfer details.
+ // Permit2, the spend recipient travels in the witness/transfer details.
// Clients shape this a few ways; check the known locations and bail out
// (null = facilitator-trusted) rather than guess when none are present.
if (inner.permit2Authorization && typeof inner.permit2Authorization === 'object') {
@@ -900,7 +900,7 @@ export function decodeSignedRecipient(paymentPayload) {
// generate distinct keys.
function buildIdempotencyKey({ paymentPayload, requirement }) {
const material = JSON.stringify({
- // Order matters for deterministic hashing — stringify the fields in a
+ // Order matters for deterministic hashing, stringify the fields in a
// fixed shape rather than the raw payload (which has insertion-order
// dependence in some clients).
network: requirement?.network,
@@ -919,11 +919,11 @@ function buildIdempotencyKey({ paymentPayload, requirement }) {
// on `directVerified` so settlePayment can synthesise a response without
// re-hitting the RPC.
//
-// `builderCode` is the extension block we declared on the 402 challenge —
+// `builderCode` is the extension block we declared on the 402 challenge,
// when present, we reject any payment whose `extensions[BUILDER_CODE].a`
// does not exactly echo the declared app code (anti-tamper). Built so the
// resource server enforces the echo invariant the spec normally puts on the
-// facilitator — important because not every facilitator implements it yet,
+// facilitator, important because not every facilitator implements it yet,
// and the on-chain calldata suffix needs trustworthy `a` to be useful.
//
// When the caller doesn't pass `builderCode`, we derive it from
@@ -933,14 +933,14 @@ function buildIdempotencyKey({ paymentPayload, requirement }) {
// explicitly to opt out (e.g. test harnesses).
// CDP's /verify and /settle validate the forwarded paymentPayload against a
// strict envelope schema. Clients speaking the PAYMENT-SIGNATURE dialect
-// (@x402/fetch v2, OKX) echo unsigned listing copy into the payload —
-// `resource` and `extensions` blocks copied verbatim from our own 402 body —
+// (@x402/fetch v2, OKX) echo unsigned listing copy into the payload,
+// `resource` and `extensions` blocks copied verbatim from our own 402 body,
// and CDP rejects the whole payment when that echo trips its validator
// ("'paymentPayload' is invalid: must match one of [x402V2PaymentPayload,
// x402V1PaymentPayload]"). That let per-endpoint listing copy break payment
// settlement (14 endpoints deterministically failed while 31 passed, split
-// purely by echoed content). None of the echoed fields are signed — the
-// EIP-712 / SPL signature covers `payload` only — and none are needed to
+// purely by echoed content). None of the echoed fields are signed, the
+// EIP-712 / SPL signature covers `payload` only, and none are needed to
// verify or settle, so for CDP we forward the minimal envelope it always
// accepts. Non-CDP facilitators (PayAI, the self-facilitator) keep the
// original payload untouched.
@@ -958,7 +958,7 @@ function minimalPaymentPayloadForCdp(paymentPayload) {
export async function verifyPayment({ paymentHeader, requirements, builderCode }) {
const all = Array.isArray(requirements) ? requirements : [requirements];
// Auth-hint placeholder entries (amount="0" / extra.authRequired) are never
- // payable via X-PAYMENT — drop them before matching so the zero-amount
+ // payable via X-PAYMENT, drop them before matching so the zero-amount
// bypass can't be reached regardless of accepts[] ordering. The auth-hint
// redemption path never calls verifyPayment (it short-circuits on the auth
// header in x402-paid-endpoint.js), so this filter only ever removes
@@ -967,7 +967,7 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
if (!payable.length) {
throw new X402Error(
'invalid_payment',
- 'this resource has no payable accepts[] entries — use the advertised authentication method instead of X-PAYMENT',
+ 'this resource has no payable accepts[] entries, use the advertised authentication method instead of X-PAYMENT',
402,
);
}
@@ -1012,7 +1012,7 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
}
}
// Defense-in-depth recipient check. The EIP-712 signature commits to the
- // recipient, so confirm the payer signed funds to OUR payTo — a compromised
+ // recipient, so confirm the payer signed funds to OUR payTo, a compromised
// facilitator can't redirect a wrong-recipient authorization past us. Null
// (Solana SPL / unknown shape) falls through to facilitator trust.
const signedRecipient = decodeSignedRecipient(paymentPayload);
@@ -1057,7 +1057,7 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
);
}
// Facilitator response cross-check. When it echoes network/asset (most do),
- // confirm they match the requirement we sent — a compromised or buggy
+ // confirm they match the requirement we sent, a compromised or buggy
// facilitator could otherwise verify a payment intended for chain A as if
// it were chain B. Missing echoed fields don't fail (older facilitators).
if (result.network && result.network !== requirement.network) {
@@ -1081,7 +1081,7 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
// Solana defense-in-depth: the amount/recipient live inside the opaque
// serialized transaction, so the facilitator was historically the only
// guard. Statically decode the signed SPL transfer and reject if it pays
- // us less than required (or to the wrong ATA/mint) — symmetric with the
+ // us less than required (or to the wrong ATA/mint), symmetric with the
// EVM signed-amount/recipient checks above. Undecodable payloads stay
// facilitator-trusted (inconclusive) so a parsing quirk never blocks a
// valid payment.
@@ -1096,7 +1096,7 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
// Settle the verified payment on-chain via the matching facilitator.
// For direct-scheme networks (BSC), the user already broadcast the tx during
-// verifyPayment — settle just synthesises the response shape callers expect.
+// verifyPayment, settle just synthesises the response shape callers expect.
//
// Two call shapes supported:
// 1. settlePayment({ verified }) ← preferred. `verified` is the object
@@ -1197,7 +1197,7 @@ export function encodePaymentResponseHeader(settleResult, extensions) {
network: settleResult.network,
payer: settleResult.payer,
// SettleResponse extras the OKX Agent Payments Protocol receipt carries
- // (specs/okx-agent-payments.md §1.4): `status` ("success"/"pending" —
+ // (specs/okx-agent-payments.md §1.4): `status` ("success"/"pending",
// pending buyers poll /settle/status), `amount` in atomic units. Other
// rails' facilitators don't return them; absent stays absent.
...(settleResult.status ? { status: settleResult.status } : {}),
@@ -1214,9 +1214,9 @@ export function encodePaymentResponseHeader(settleResult, extensions) {
// challenge, the /.well-known/x402.json discovery file, and any operator
// dashboards stay in sync.
export const RESOURCE_DESCRIPTION =
- 'three.ws MCP — Streamable HTTP transport (MCP 2025-06-18) exposing 3D avatar viewer, glTF/GLB model validation/inspection/optimization, and Solana agent data as JSON-RPC 2.0 tool calls. Pay-per-call in USDC on Base mainnet (eip155:8453) or Solana mainnet. ≤256 tools/call output, ≤32-message JSON-RPC batches. Operated by three.ws.';
+ 'three.ws MCP, Streamable HTTP transport (MCP 2025-06-18) exposing 3D avatar viewer, glTF/GLB model validation/inspection/optimization, and Solana agent data as JSON-RPC 2.0 tool calls. Pay-per-call in USDC on Base mainnet (eip155:8453) or Solana mainnet. ≤256 tools/call output, ≤32-message JSON-RPC batches. Operated by three.ws.';
-// Build the bazaar.schema *meta-schema* — the JSON Schema that validates the
+// Build the bazaar.schema *meta-schema*, the JSON Schema that validates the
// `{input, output}` shape of the extension itself, NOT the endpoint's response
// body. The user's response-body schema gets nested at
// `schema.properties.output.properties.example`. Matches the reference
@@ -1275,7 +1275,7 @@ export function buildBazaarSchema({
return schema;
}
-// Bazaar discovery extension — shape required by agentic.market's validator.
+// Bazaar discovery extension, shape required by agentic.market's validator.
// `info.input.{type,method,body|queryParams|pathParams}` describes how to call
// the resource; `info.output.{type,example}` shows what comes back; top-level
// `schema` is the meta-schema built by `buildBazaarSchema` above.
@@ -1317,7 +1317,7 @@ export function bazaarExtension() {
params: {
type: 'object',
description:
- 'For tools/call: { name, arguments }. Tool names include validate_model, inspect_model, optimize_model, search_public_avatars, solana_register, solana_reputation, and others — see tools/list.',
+ 'For tools/call: { name, arguments }. Tool names include validate_model, inspect_model, optimize_model, search_public_avatars, solana_register, solana_reputation, and others, see tools/list.',
},
},
};
@@ -1377,7 +1377,7 @@ export function bazaarExtension() {
// True when any offered requirement asks the client to use the Permit2
// asset-transfer method. When so, we automatically advertise BOTH gas-
-// sponsoring extensions at the top level — the facilitator (CDP's
+// sponsoring extensions at the top level, the facilitator (CDP's
// x402ExactPermit2Proxy) submits the approval atomically with settlement so
// the payer never broadcasts the approval tx themselves. EIP-2612 is the
// preferred path for tokens that implement it (Base USDC v2 does);
@@ -1393,7 +1393,7 @@ function hasPermit2Accept(accepts) {
// Build the v2 PaymentRequired body. Top-level `resource` carries url/description/
// mimeType (per v2 spec); per-accept entries no longer repeat them.
//
-// `description`, `mimeType`, and `bazaar` are per-route — each paid endpoint
+// `description`, `mimeType`, and `bazaar` are per-route, each paid endpoint
// wants its own catalog entry on agentic.market, not the MCP boilerplate.
// Callers may pass an `extensions` object to add or override entries (e.g. an
// endpoint that wants to declare a custom extension); when omitted we still
@@ -1403,7 +1403,7 @@ function hasPermit2Accept(accepts) {
// on-chain attribution without having to opt in per-route.
// USE-13: `serviceName`, `tags`, `iconUrl` belong on the `resource` object
// per the Bazaar spec. Facilitators apply soft-drop validation so silently
-// invalid fields are skipped, but we keep them within limits here too —
+// invalid fields are skipped, but we keep them within limits here too,
// printable-ASCII, ≤32 chars (serviceName/tag), ≤5 tags, absolute https URL.
export async function build402Body({
resourceUrl,
@@ -1435,7 +1435,7 @@ export async function build402Body({
// x402-paid-endpoint.js wrapper pre-signs and passes offers via
// extraExtensions to avoid signing twice; hand-rolled callers (launchpad,
// vanity, etc.) get offers here automatically. Signing failure is silently
- // absorbed — the protocol stays valid without the extension.
+ // absorbed, the protocol stays valid without the extension.
if (!extraExtensions?.[OFFER_RECEIPT]) {
try {
const offersFragment = await buildOffersExtension(
@@ -1483,7 +1483,7 @@ export async function build402Body({
// Ceiling for the base64 PAYMENT-REQUIRED header mirror. Node's default
// http client limit is 16 KB for the ENTIRE header block, and x402scan's
// registration probe flags any response whose headers exceed 16 KB
-// (HEADERS_OVERFLOW — "some clients will fail to parse this response").
+// (HEADERS_OVERFLOW, "some clients will fail to parse this response").
// Endpoints with rich bazaar schemas + per-accept signed offers were
// emitting 11–17 KB headers, which the production LB then dropped entirely.
// 8 KB leaves comfortable room for the ~0.5 KB of ordinary headers.
@@ -1506,7 +1506,7 @@ function bazaarWithoutInfo(bazaar) {
// `schema.properties.input.properties.{body|queryParams}` and
// `schema.properties.output.properties.example`), but replaces the potentially
// large per-field JSON Schemas with `{ type: 'object' }`. The canonical JSON
-// body still carries the full, detailed schema — this is only the size-capped
+// body still carries the full, detailed schema, this is only the size-capped
// header fallback for routes whose real schema is too big to mirror verbatim.
function compactDiscoveryBazaar(bazaar) {
const schema = bazaar?.schema;
@@ -1559,10 +1559,10 @@ function compactDiscoveryBazaar(bazaar) {
// payment-execution extensions (signed offers, gas-sponsoring hints, SIWX /
// auth-hints, builder-code) but KEEP the `bazaar` discovery extension, because
// agent-discovery crawlers (agentcash, x402scan's Bazaar) read the challenge
-// from THIS header, not the JSON body — dropping bazaar makes every paid route
+// from THIS header, not the JSON body, dropping bazaar makes every paid route
// look schema-less to them. We try, in order: full bazaar, bazaar without the
-// `info` examples, then a compact bazaar with `{type:'object'}` field schemas —
-// picking the first that fits — before falling back to the extension-less slim
+// `info` examples, then a compact bazaar with `{type:'object'}` field schemas,
+// picking the first that fits, before falling back to the extension-less slim
// mirror, then null. Header-only payers still get everything needed to pay
// (accepts is always complete); the JSON body remains the canonical, complete
// envelope with the full detailed schemas per the v2 spec.
@@ -1592,7 +1592,7 @@ export async function send402(res, opts = {}) {
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('cache-control', 'no-store');
// v2 spec: the full envelope ({x402Version, error, resource, accepts,
- // extensions}) ships in the response body — that is the canonical read
+ // extensions}) ships in the response body, that is the canonical read
// for `@x402/fetch` and other SDK clients. The `PAYMENT-REQUIRED` header
// carries a base64 mirror for header-only crawlers, capped by
// paymentRequiredHeaderValue() so the total header block stays parseable
diff --git a/api/_lib/x402-xlayer-okx.js b/api/_lib/x402-xlayer-okx.js
index 3cac0910a..c7b2b965f 100644
--- a/api/_lib/x402-xlayer-okx.js
+++ b/api/_lib/x402-xlayer-okx.js
@@ -1,4 +1,4 @@
-// OKX Agent Payments Protocol rail — x402 `exact` + EIP-3009 on X Layer (chain 196).
+// OKX Agent Payments Protocol rail, x402 `exact` + EIP-3009 on X Layer (chain 196).
//
// The OKX.AI marketplace (agents hire agents; A2MCP services) requires sellers
// to speak its x402 v2 dialect on X Layer. The wire contract in
@@ -12,25 +12,25 @@
// 2. The accepts entry: { scheme:'exact', network:'eip155:196', amount:<base
// units>, payTo, maxTimeoutSeconds:86400, asset:<USD₮0>, extra:{ symbol:
// 'USDT', name:'USD₮0', version:'1', transferMethod:'eip3009' } }.
-// extra.name/version are the token's EIP-712 domain — USD₮0's on-chain
+// extra.name/version are the token's EIP-712 domain, USD₮0's on-chain
// domain is name "USD₮0", version "1" (verified via eth_call).
// 3. The buyer replays with `PAYMENT-SIGNATURE: <base64 JSON>` decoding to
// { x402Version:2, accepted:<chosen accepts entry>, payload:{
// authorization:{from,to,value,validAfter,validBefore,nonce}, signature },
-// resource } — note `accepted`, not the standard x402 top-level
+// resource }, note `accepted`, not the standard x402 top-level
// scheme/network fields.
// 4. Verification is seller-side and on-chain: EIP-712 signature recovery
-// (ERC-1271-aware — OKX agentic wallets may be smart accounts), recipient/
+// (ERC-1271-aware, OKX agentic wallets may be smart accounts), recipient/
// amount/time-window checks, unused authorizationState, and a balanceOf
// check. Insufficient balance re-issues the 402 with top-level
-// error:"insufficient_balance" — the exact behavior captured from the
+// error:"insufficient_balance", the exact behavior captured from the
// approved seller.
// 5. Settlement routes through OKX's official facilitator when OKX SA API
-// credentials are configured — POST https://web3.okx.com/api/v6/pay/x402/
+// credentials are configured, POST https://web3.okx.com/api/v6/pay/x402/
// settle with syncSettle:true (HMAC-SHA256 auth; the exact client the
// official @okxweb3/app-x402-core SDK ships). Verification likewise gets
// a facilitator /verify pass on top of the local checks. Without OKX
-// creds, the seller redeems the authorization DIRECTLY — broadcasts
+// creds, the seller redeems the authorization DIRECTLY, broadcasts
// transferWithAuthorization from a relayer key (OKB gas); per the
// protocol docs "settlement happens on-chain when the recipient redeems
// the authorization."
@@ -58,13 +58,13 @@ export const XLAYER_CHAIN_ID = 196;
// USD₮0's EIP-712 domain, verified on-chain (name()/symbol() both return
// "USD₮0") and matched against the live approved-seller 402s (extra.name
-// "USD₮0", extra.version "1"). The ₮ is U+20AE — keep it exact: the domain
+// "USD₮0", extra.version "1"). The ₮ is U+20AE, keep it exact: the domain
// separator hashes the byte string.
const USDT0_DOMAIN_NAME = 'USD₮0';
const USDT0_DOMAIN_VERSION = '1';
const USDT0_SYMBOL = 'USDT';
-// EIP-3009 typed data — the struct the buyer's wallet signs.
+// EIP-3009 typed data, the struct the buyer's wallet signs.
const TRANSFER_WITH_AUTHORIZATION_TYPES = {
TransferWithAuthorization: [
{ name: 'from', type: 'address' },
@@ -128,7 +128,7 @@ const EIP3009_ABI = [
},
];
-// RPC failover for chain 196 — X Layer is not in the shared erc8004 chain
+// RPC failover for chain 196, X Layer is not in the shared erc8004 chain
// registry, so the endpoint list lives here: explicit override first, then
// viem's curated default, then OKX's public node.
function xlayerEndpoints() {
@@ -155,7 +155,7 @@ export function okxFacilitatorConfigured() {
return Boolean(env.OKX_API_KEY && env.OKX_SECRET_KEY && env.OKX_PASSPHRASE);
}
-// Singleton facilitator client (official SDK). syncSettle:true — the seller
+// Singleton facilitator client (official SDK). syncSettle:true, the seller
// waits for on-chain confirmation before responding, per the SDK's
// recommended seller configuration, so PAYMENT-RESPONSE always carries a
// confirmed transaction.
@@ -174,7 +174,7 @@ function okxFacilitator() {
// Can we actually settle on X Layer right now? Advertise the rail only when
// the receiver, the asset, and a working settlement route (OKX facilitator
-// creds, or the direct-redemption relayer key) are all configured — the same
+// creds, or the direct-redemption relayer key) are all configured, the same
// never-402-then-502 rule baseSettleable()/solanaSettleable() enforce.
export function xlayerSettleable() {
return Boolean(
@@ -381,7 +381,7 @@ export async function verifyOkxXLayerPayment({ paymentPayload, requirement }) {
throw new X402Error('invalid_payment', 'insufficient_balance', 402);
}
- // Facilitator pass — when the OKX SA API creds are configured, the official
+ // Facilitator pass, when the OKX SA API creds are configured, the official
// facilitator gets the final word on validity (it is also the settlement
// submitter). The local checks above stay as defense-in-depth, mirroring
// how the CDP/PayAI paths cross-check facilitator answers.
@@ -433,9 +433,9 @@ function relayerAccount() {
}
// Settle the verified payment. Primary route: the official OKX facilitator
-// (POST /api/v6/pay/x402/settle, syncSettle:true) — it broadcasts the
+// (POST /api/v6/pay/x402/settle, syncSettle:true), it broadcasts the
// EIP-3009 redemption and waits for confirmation. Fallback (no OKX creds):
-// redeem directly — broadcast transferWithAuthorization from the relayer
+// redeem directly, broadcast transferWithAuthorization from the relayer
// (OKB gas) and wait for inclusion. Both return the same {success,
// transaction, network, payer} shape the other facilitator paths yield, so
// X-PAYMENT-RESPONSE / PAYMENT-RESPONSE emission is identical.
@@ -466,7 +466,7 @@ export async function settleOkxXLayerPayment({ verified, requirement, paymentPay
}
// syncSettle:true → status "success" with a confirmed tx. A "pending"
// (async facilitator mode) still means the facilitator accepted the
- // settlement — surface it with the tx for /settle/status polling.
+ // settlement, surface it with the tx for /settle/status polling.
if (!result?.success && result?.status !== 'pending') {
throw new X402Error(
'settle_failed',
@@ -517,7 +517,7 @@ export async function settleOkxXLayerPayment({ verified, requirement, paymentPay
transaction: hash,
network: NETWORK_XLAYER_MAINNET,
payer: verified.payer,
- // Direct redemption waited for the receipt — the transfer is
+ // Direct redemption waited for the receipt, the transfer is
// confirmed, matching the facilitator's syncSettle "success".
status: 'success',
amount: verified.amount,
@@ -548,7 +548,7 @@ function splitSignature(signature) {
// Live subsystem probe for the free health endpoint (WO-03's "real checks, not
// {ok:true}"): RPC liveness, fee-token readability, and whether the settlement
-// relayer is configured + gas-funded. Never throws — health reports state.
+// relayer is configured + gas-funded. Never throws, health reports state.
export async function xlayerRailHealth() {
const out = {
network: NETWORK_XLAYER_MAINNET,
diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.js
index 2367f2066..d38701b7e 100644
--- a/api/_mcp-studio/tools.js
+++ b/api/_mcp-studio/tools.js
@@ -16,7 +16,13 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
-import { MESH_DIRECTOR, AVATAR_DIRECTOR, resolveLogoPrompt } from '../_lib/forge-director-prompts.js';
+import {
+ meshDirectorFor,
+ meshSubjectClass,
+ avatarDirectorFor,
+ classifySubject,
+ resolveLogoPrompt,
+} from '../_lib/forge-director-prompts.js';
import { checkPromptSafety } from './safety.js';
import {
originFromReq,
@@ -227,9 +233,29 @@ async function handleForgeFree(args, _auth, req) {
// 402/timeout. True high-by-default lands when the async self-host Hunyuan3D
// worker deploys (GCP_HUNYUAN3D_URL).
const tier = VALID_TIER.has(args.tier) ? args.tier : 'standard';
+ // Known brand marks resolve deterministically; everything else runs the
+ // subject-classified Granite director (fail-soft: original prompt on any
+ // failure) so this free lane gets the same photoreal-reference treatment as
+ // mesh_forge instead of reconstructing straight from the raw words.
+ let effective = prompt;
+ let markImageUrls;
+ const knownMark = resolveLogoPrompt(prompt);
+ if (knownMark) {
+ effective = knownMark.prompt;
+ if (knownMark.imagePath) markImageUrls = [`${base}${knownMark.imagePath}`];
+ } else {
+ const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt);
+ if (directed) effective = directed;
+ }
let job;
try {
- job = await generate(base, { prompt, path: 'image', tier, internal: true }, { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS' });
+ job = await generate(
+ base,
+ markImageUrls
+ ? { prompt: effective, imageUrls: markImageUrls, tier, internal: true }
+ : { prompt: effective, path: 'image', tier, internal: true },
+ { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS' },
+ );
} catch (err) {
return toolError(failureMessage(err));
}
@@ -251,11 +277,20 @@ async function handleTextToAvatar(args, _auth, req) {
} catch (err) {
return toolError(err.userMessage ? err.message : 'That image URL could not be used.');
}
+ // Granite avatar director (text mode only, fail-soft): without this the raw
+ // words reconstructed straight into TRELLIS/Hunyuan3D with no photoreal
+ // reference-image briefing at all — the realism gap forge_avatar already closes.
+ let effective = prompt;
+ if (prompt && !imageUrl) {
+ const subject = classifySubject(prompt) === 'animal' ? 'animal' : 'person';
+ const directed = await directPrompt(avatarDirectorFor(subject), prompt);
+ if (directed) effective = directed;
+ }
let job;
try {
job = await generate(
base,
- { prompt: prompt || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: 'standard', internal: true },
+ { prompt: effective || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: 'standard', internal: true },
{ timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS' },
);
} catch (err) {
@@ -292,7 +327,7 @@ async function handleMeshForge(args, _auth, req) {
effective = knownMark.prompt;
if (knownMark.imagePath) markImageUrls = [`${base}${knownMark.imagePath}`];
} else {
- const directed = await directPrompt(MESH_DIRECTOR, prompt);
+ const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt);
if (directed) effective = directed;
}
}
@@ -357,7 +392,8 @@ async function handleForgeAvatar(args, _auth, req) {
// Stage 1 — generate the mesh (Granite director in text mode, fail-soft).
let effective = prompt;
if (prompt && !imageUrl) {
- const directed = await directPrompt(AVATAR_DIRECTOR, prompt);
+ const subject = classifySubject(prompt) === 'animal' ? 'animal' : 'person';
+ const directed = await directPrompt(avatarDirectorFor(subject), prompt);
if (directed) effective = directed;
}
let gen;
diff --git a/api/_mcp3d/discovery.js b/api/_mcp3d/discovery.js
index faf448a6e..65be4b719 100644
--- a/api/_mcp3d/discovery.js
+++ b/api/_mcp3d/discovery.js
@@ -11,11 +11,11 @@ import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { withService } from '../_lib/x402/bazaar-helpers.js';
export const RESOURCE_DESCRIPTION =
- 'three.ws 3D Studio MCP — Streamable HTTP (MCP 2025-06-18) that turns text or images into ' +
+ 'three.ws 3D Studio MCP: Streamable HTTP (MCP 2025-06-18) that turns text or images into ' +
'interactive, animation-ready 3D models: text_to_3d (prompt → GLB), image_to_3d (1–4 reference ' +
'views → GLB), generation_status (poll a job for the finished model), auto_rig_model, plus mesh ' +
'editing (retexture, remesh, stylize, segment) and PBR material generation. Connect with a ' +
- 'three.ws account (OAuth) or pay per call in USDC on Base or Solana mainnet — no API key. ' +
+ 'three.ws account (OAuth) or pay per call in USDC on Base or Solana mainnet, no API key. ' +
'Operated by three.ws.';
// Endpoint-level v2 bazaar discovery entry, shaped exactly like the validator
@@ -65,7 +65,7 @@ function studioBazaarExtension() {
params: {
type: 'object',
description:
- 'For tools/call: { name, arguments }. Tool names: text_to_3d, image_to_3d, generation_status, auto_rig_model, retexture_model, remesh_model, stylize_model, segment_model, generate_material, direct_prompt — see tools/list.',
+ 'For tools/call: { name, arguments }. Tool names: text_to_3d, image_to_3d, generation_status, auto_rig_model, retexture_model, remesh_model, stylize_model, segment_model, generate_material, direct_prompt, see tools/list.',
},
},
};
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index 8c05f109f..08e295b4d 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -1447,6 +1447,12 @@ export const toolDefs = [
enum: [512, 1024, 2048],
default: 1024,
},
+ material_class: {
+ type: 'string',
+ enum: ['person', 'metal', 'wood', 'fabric', 'plastic', 'glass'],
+ description:
+ 'Optional. Bakes measured real-world roughness/metallic values for this material family instead of a flat guess, and nudges the prompt with material-appropriate descriptors (e.g. "metal" adds brushed-metal micro-detail cues).',
+ },
},
required: ['mesh_url', 'prompt'],
additionalProperties: false,
@@ -1470,6 +1476,7 @@ export const toolDefs = [
negative_prompt: args.negative_prompt,
num_views: args.num_views || 8,
texture_size: args.texture_size || 1024,
+ material_class: args.material_class || null,
},
});
return {
diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.js
index 369aa7f76..36a0d07c0 100644
--- a/api/_okx3d/identity.js
+++ b/api/_okx3d/identity.js
@@ -1,4 +1,4 @@
-// Agent Identity Studio pipeline — the engine behind the paid
+// Agent Identity Studio pipeline, the engine behind the paid
// /api/okx/3d/identity-studio A2MCP service (see api/_lib/okx-catalog.js).
//
// Turns a brand brief into a complete 3D identity for an AI agent:
@@ -8,9 +8,9 @@
// → posed studio renders (/api/render/avatar-clip + sharp compositing)
// → PFP crop (square, reads at 128px) + full-body set, persisted to R2.
//
-// Every GPU/render stage is driven over the deployed three.ws HTTP surfaces —
+// Every GPU/render stage is driven over the deployed three.ws HTTP surfaces,
// the exact pattern the npx MCP server (mcp-server/src/tools/_studio-core.js)
-// uses — so this module behaves identically inside the Vercel function and in
+// uses, so this module behaves identically inside the Vercel function and in
// a local run (scripts/okx-identity-demo.mjs), and holds no provider keys.
//
// Job model: state lives as one JSON document in R2. create() validates the
@@ -19,7 +19,7 @@
// identity_status poll advances the pipeline by ONE bounded step (a single
// upstream poll, or one render), so no request outlives its function budget
// and polling is what drives the job to completion. Failed generate/rig
-// stages retry free up to MAX_STAGE_ATTEMPTS — the buyer pays once, for
+// stages retry free up to MAX_STAGE_ATTEMPTS, the buyer pays once, for
// deliverables, not for our transient failures.
import { createHash } from 'node:crypto';
@@ -40,7 +40,7 @@ const MAX_STAGE_ATTEMPTS = 3;
// The PFP pose is pinned to a neutral standing preset: the head-crop geometry
// below assumes the top of the model's alpha bounding box is the head, which
// raised-arm poses would break. Full-body poses draw from a shortlist that
-// reads well as a brand identity (confident, natural stances — no floor poses).
+// reads well as a brand identity (confident, natural stances, no floor poses).
const PFP_POSE = 'contrapposto';
const FULLBODY_POSES = [
'hands-on-hips',
@@ -64,7 +64,7 @@ export const IDENTITY_DIRECTOR_INSTRUCTION =
'outfit, materials, colors, and one signature visual motif. Standing neutral pose, arms slightly ' +
'away from the body, plain background. No scene, no props held across the body, no multiple ' +
'characters, no text or logos. The brief may be in any language; ALWAYS write the prompt in ' +
- 'English. Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';
+ 'English. Output ONLY the rewritten prompt as a single line, no preamble, no quotes.';
function pipelineError(code, message, extra = {}) {
return Object.assign(new Error(message), { code, ...extra });
@@ -108,7 +108,7 @@ async function saveState(state) {
// ---------------------------------------------------------------------------
// LLM prompt director over the in-process free-provider chain (Groq → OpenRouter
-// → NVIDIA NIM via api/_lib/llm.js — the same server keys the platform funds).
+// → NVIDIA NIM via api/_lib/llm.js, the same server keys the platform funds).
// Runs in-process instead of over the deployed /api/chat SSE endpoint: this
// module executes inside the Vercel function, and a server-to-server call to
// /api/chat is anonymous, so it hits the anon rate limiter / provider gate and
@@ -134,7 +134,7 @@ async function directIdentityPrompt({ agentName, brief, styleHints }) {
return refined.length >= 3 && refined.length <= 1000 ? refined : null;
}
-// The generation lane's text→image encoder truncates/chokes on long prompts —
+// The generation lane's text→image encoder truncates/chokes on long prompts,
// verified against production /api/forge: ~250-char prompts generate cleanly,
// ~430-char prompts fail. Keep every prompt we send under this budget, cut at
// a word boundary.
@@ -148,17 +148,17 @@ function clampPrompt(text, max = MAX_GENERATION_PROMPT_CHARS) {
}
// Deterministic fallback when the director is unreachable. Forces the humanoid
-// framing rigging requires — an identity brief ("a finance data agent") rarely
+// framing rigging requires, an identity brief ("a finance data agent") rarely
// names a humanoid subject, so unlike forge_avatar there is no humanoid gate
// here: the subject is BY CONSTRUCTION a humanoid character embodying the
// brief. A text-to-3D encoder wants a visual SUBJECT, not backstory, so this
// leads with the (visual) style hints and reduces the brief to its first
-// sentence — the core descriptor — rather than dumping the whole narrative and
+// sentence, the core descriptor, rather than dumping the whole narrative and
// truncating it mid-clause. Stays inside the generation prompt budget (~130
// chars of frame text leaves ~170 for hints + subject) and never leaves a
// dangling comma or half-word at a cut.
export function fallbackIdentityPrompt({ brief, styleHints }) {
- // The style hints ARE the visual direction — give them priority and their own
+ // The style hints ARE the visual direction, give them priority and their own
// budget so a long brief can never crowd them out of the prompt.
const hints = styleHints ? cleanClause(clampPrompt(styleHints, 90)) : '';
// First sentence only (handles both Latin ".!?" and CJK "。!?").
@@ -189,7 +189,7 @@ export async function shapeIdentityPrompt({ agentName, brief, styleHints }) {
}
// ---------------------------------------------------------------------------
-// /api/forge client (submit / single poll / rig) — adapted from the npx MCP
+// /api/forge client (submit / single poll / rig), adapted from the npx MCP
// server's _studio-core.js, minus the internal polling loop: this pipeline
// polls upstream once per identity_status call instead of blocking.
// ---------------------------------------------------------------------------
@@ -197,7 +197,7 @@ export async function shapeIdentityPrompt({ agentName, brief, styleHints }) {
async function submitForge(base, payload) {
let res;
try {
- // The default free lane (NVIDIA NIM TRELLIS) completes SYNCHRONOUSLY —
+ // The default free lane (NVIDIA NIM TRELLIS) completes SYNCHRONOUSLY,
// the submit response can take minutes and already carry the finished
// GLB, so the submit timeout must cover a full generation, not just an
// enqueue ack. Async backends still return a job_id quickly.
@@ -230,7 +230,7 @@ async function pollForgeOnce(base, jobId) {
signal: AbortSignal.timeout(15_000),
});
} catch (err) {
- // A transient poll failure is not a job failure — report still-running.
+ // A transient poll failure is not a job failure, report still-running.
return { status: 'running', _pollError: String(err?.message || err) };
}
const data = await res.json().catch(() => ({}));
@@ -311,7 +311,7 @@ async function renderTransparent(base, { glbUrl, posePresetId, theta, size = 160
}
// Trim the transparent render to the model's alpha bounding box. Returns the
-// trimmed buffer plus its dimensions — the head-crop math keys off these.
+// trimmed buffer plus its dimensions, the head-crop math keys off these.
async function trimToModel(sharp, png) {
const trimmed = await sharp(png).trim({ threshold: 8 }).png().toBuffer({ resolveWithObject: true });
return { buffer: trimmed.data, width: trimmed.info.width, height: trimmed.info.height };
@@ -368,7 +368,7 @@ async function uploadRender(id, name, png) {
// Job lifecycle
// ---------------------------------------------------------------------------
-// Deterministic pose plan seeded from the job id — reproducible per job, varied
+// Deterministic pose plan seeded from the job id, reproducible per job, varied
// across jobs. Slot n picks from the remaining shortlist by seed byte.
export function buildRenderPlan(id) {
const seed = createHash('sha256').update(id).digest();
@@ -479,7 +479,7 @@ export async function createIdentityJob({
error: null,
});
if (state.gen.glbUrl) {
- // Synchronous free-lane completion — jump straight to rigging.
+ // Synchronous free-lane completion, jump straight to rigging.
await beginRig(base, state);
}
return { jobId: encodeIdentityJobToken(id), state };
@@ -498,7 +498,7 @@ async function beginRig(base, state) {
return saveState(state);
}
-// A generate/rig/render failure retries free while attempts remain — the
+// A generate/rig/render failure retries free while attempts remain, the
// buyer paid for deliverables, not for our transient upstream weather. The
// retry itself happens on the NEXT status poll (the failed stage's job handle
// is cleared, and advance re-submits), so one bad resubmission can never go
@@ -521,7 +521,7 @@ async function failStage(state, stage, err) {
state.error = { stage, code: err?.code || 'provider_error', message: String(err?.message || err), retrying: true };
if (stage === 'generate') state.gen.jobId = null;
else if (stage === 'rig') state.rig.jobId = null;
- // render: cursor stays put — the next poll re-runs the same render.
+ // render: cursor stays put, the next poll re-runs the same render.
state.attempts[stage] = attempts + 1;
return saveState(state);
}
@@ -535,7 +535,7 @@ export async function advanceIdentityJob(id, { base = BASE } = {}) {
const state = await loadState(id);
if (!state) return null;
- // Rate-limit backoff window — this poll is a no-op until it elapses.
+ // Rate-limit backoff window, this poll is a no-op until it elapses.
if (state.nextAttemptAt && Date.now() < state.nextAttemptAt) return state;
if (state.nextAttemptAt) {
delete state.nextAttemptAt;
@@ -543,7 +543,7 @@ export async function advanceIdentityJob(id, { base = BASE } = {}) {
if (state.stage === 'generate') {
if (!state.gen.glbUrl && !state.gen.jobId) {
- // A previous attempt failed — this poll performs the free retry.
+ // A previous attempt failed, this poll performs the free retry.
try {
const gen = await submitForge(
base,
@@ -573,7 +573,7 @@ export async function advanceIdentityJob(id, { base = BASE } = {}) {
if (state.stage === 'generate' && state.gen.glbUrl) await beginRig(base, state);
} else if (state.stage === 'rig') {
if (!state.rig.jobId) {
- // Rig submission failed earlier — retry it on this poll.
+ // Rig submission failed earlier, retry it on this poll.
await beginRig(base, state);
} else {
const status = await pollForgeOnce(base, state.rig.jobId);
diff --git a/api/_okx3d/rest-services.js b/api/_okx3d/rest-services.js
index 7637fb28b..5a394896b 100644
--- a/api/_okx3d/rest-services.js
+++ b/api/_okx3d/rest-services.js
@@ -1,13 +1,13 @@
-// OKX.AI REST services — engine adapters for the decomposed 3D studio.
+// OKX.AI REST services: engine adapters for the decomposed 3D studio.
//
// One exported invoke() per catalog row (api/_lib/okx-catalog.js), each a thin
-// wrapper over an engine the platform already runs — NO duplicated pipeline
+// wrapper over an engine the platform already runs, NO duplicated pipeline
// logic:
//
// text-to-3d → /api/forge submit on the free NVIDIA NIM TRELLIS lane
// (draft tier) via _mcp-studio/forge-client.js
// text-to-3d-pro → Granite art director (fail-soft) + /api/forge submit at
-// standard/high tier — the mesh_forge chain
+// standard/high tier, the mesh_forge chain
// image-to-3d → /api/forge submit, image lane (TRELLIS reconstruct)
// rig → /api/forge?action=rig submit (UniRig worker)
// avatar → the forge_avatar chain: generate to completion, then
@@ -17,7 +17,7 @@
// fbx-export → remesh_model MCP tool handler, operation=convert
//
// Contract with the route (api/okx/3d/[service].js): invoke AFTER payment
-// verification and BEFORE settlement — a thrown error means the buyer is not
+// verification and BEFORE settlement, a thrown error means the buyer is not
// charged. Async lanes return { status:'queued', job_id, poll_url } (polling
// GET /api/forge?job=<id> is free, no payment or account); fast lanes return
// their result inline with status:'done'.
@@ -26,7 +26,7 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { catalogEntry } from '../_lib/okx-catalog.js';
-import { MESH_DIRECTOR, resolveLogoPrompt } from '../_lib/forge-director-prompts.js';
+import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from '../_lib/forge-director-prompts.js';
import {
originFromReq,
viewerUrl,
@@ -87,11 +87,11 @@ function queuedResponse(job, extra = {}) {
};
}
-// Prompt used by text-to-3d-pro — the same single-subject art-director spec
+// Prompt used by text-to-3d-pro, the same single-subject art-director spec
// mesh_forge uses (imported from _lib/forge-director-prompts.js, the shared
// source of truth across api/_mcp-studio/tools.js, this file, and /api/forge).
-// Humanoid gate for the avatar chain — mirror of the forge_avatar steer in
+// Humanoid gate for the avatar chain, mirror of the forge_avatar steer in
// api/_mcp-studio/tools.js so both surfaces refuse the same obvious objects.
const NON_HUMANOID = /\b(chair|sofa|couch|table|desk|lamp|car|truck|vehicle|building|house|tree|plant|sword|gun|bottle|cup|mug|phone|laptop|rock|stone|food|fruit|flower|dog|cat|horse|cow|fish|bird|dragon|snake|spider|dinosaur)\b/i;
const HUMANOID = /\b(human|person|man|woman|boy|girl|character|avatar|hero|warrior|knight|robot|android|figure|mascot|humanoid|biped|wizard|elf|orc|zombie|ninja|soldier|astronaut)\b/i;
@@ -122,7 +122,7 @@ async function callStudioTool(name, args, { req, payer }) {
}
const HANDLERS = {
- // $0.01 — the free NVIDIA NIM TRELLIS lane, draft tier, submit-then-poll.
+ // $0.01, the free NVIDIA NIM TRELLIS lane, draft tier, submit-then-poll.
async 'text-to-3d'(args, ctx) {
const job = await startForge(ctx.base, {
prompt: args.prompt,
@@ -133,7 +133,7 @@ const HANDLERS = {
return queuedResponse(job, { mode: 'text_to_3d', tier: 'draft' });
},
- // $0.30 — Granite director (fail-soft) + the standard/high generation lane.
+ // $0.30, Granite director (fail-soft) + the standard/high generation lane.
// Known brand marks skip the director for the deterministic lexicon spec.
async 'text-to-3d-pro'(args, ctx) {
const tier = args.tier === 'high' ? 'high' : 'standard';
@@ -153,7 +153,7 @@ const HANDLERS = {
return queuedResponse(job, { mode: 'text_to_3d', tier });
},
- // $0.30 — image lane (TRELLIS reconstruct of caller-supplied views).
+ // $0.30, image lane (TRELLIS reconstruct of caller-supplied views).
async 'image-to-3d'(args, ctx) {
const job = await startForge(ctx.base, {
prompt: args.prompt || undefined,
@@ -163,13 +163,13 @@ const HANDLERS = {
return queuedResponse(job, { mode: 'image_to_3d' });
},
- // $0.25 — UniRig auto-rigging, submit-then-poll.
+ // $0.25, UniRig auto-rigging, submit-then-poll.
async rig(args, ctx) {
const job = await startRig(ctx.base, args.glb_url);
return queuedResponse(job, { mode: 'rig' });
},
- // $0.50 — the forge_avatar chain: mesh to completion, then the rig job.
+ // $0.50, the forge_avatar chain: mesh to completion, then the rig job.
// The mesh GLB is returned even while the rig is still polling, so a rig
// failure never loses the paid generation.
async avatar(args, ctx) {
@@ -178,7 +178,7 @@ const HANDLERS = {
}
if (args.prompt && !args.image_url && args.allow_non_humanoid !== true && looksNonHumanoid(args.prompt)) {
throw inputError(
- 'That looks like an object rather than a character. Auto-rigging needs a humanoid figure — use text-to-3d for objects, or set allow_non_humanoid to override.',
+ 'That looks like an object rather than a character. Auto-rigging needs a humanoid figure, use text-to-3d for objects, or set allow_non_humanoid to override.',
);
}
const gen = await generate(
@@ -191,7 +191,7 @@ const HANDLERS = {
{ timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS' },
);
if (gen._timedOut || !gen.glb_url) {
- const e = new Error('Generation took too long — you were not charged; try again.');
+ const e = new Error('Generation took too long, you were not charged; try again.');
e.status = 504;
e.code = 'generation_timeout';
throw e;
@@ -204,19 +204,19 @@ const HANDLERS = {
});
},
- // $0.10 — in-process clip retargeting; completes inside the request.
+ // $0.10, in-process clip retargeting; completes inside the request.
async retarget(args, ctx) {
const result = await callStudioTool('apply_animation', args, ctx);
return { status: 'done', ...(result.structuredContent || {}) };
},
- // $0.02 — deterministic pose-seed resolution; completes inside the request.
+ // $0.02, deterministic pose-seed resolution; completes inside the request.
async 'pose-seed'(args, ctx) {
const result = await callStudioTool('pose_model', { prompt: args.prompt }, ctx);
return { status: 'done', ...(result.structuredContent || {}) };
},
- // $0.10 — remesh convert (rig-preserving FBX by default), submit-then-poll.
+ // $0.10, remesh convert (rig-preserving FBX by default), submit-then-poll.
async 'fbx-export'(args, ctx) {
const result = await callStudioTool(
'remesh_model',
diff --git a/api/_okx3d/tools.js b/api/_okx3d/tools.js
index 22e715b6e..1a2f09361 100644
--- a/api/_okx3d/tools.js
+++ b/api/_okx3d/tools.js
@@ -1,4 +1,4 @@
-// Agent Identity Studio — MCP tool catalog, dispatcher, pricing, and 402
+// Agent Identity Studio, MCP tool catalog, dispatcher, pricing, and 402
// challenge metadata for the /api/okx/3d/identity-studio A2MCP endpoint.
// Prices and descriptions come from api/_lib/okx-catalog.js (single source of
// truth shared with the free catalog service and the OKX listing).
@@ -38,7 +38,7 @@ const createIdentityDef = {
name: ENTRY.tool, // create_identity
title: 'Create Agent Identity (paid)',
description:
- `$${ENTRY.priceUsd} per identity — ${ENTRY.describes.capability} ` +
+ `$${ENTRY.priceUsd} per identity, ${ENTRY.describes.capability} ` +
`Async: returns a job_id immediately; poll ${STATUS_TOOL} (free) every few seconds until ` +
'status is "done" (typically 3–6 minutes). You are charged only when the job is accepted: ' +
'invalid input or an unreachable reference image fails before settlement, and failed ' +
@@ -80,7 +80,7 @@ const identityStatusDef = {
name: STATUS_TOOL,
title: 'Identity Job Status (free)',
description:
- 'FREE — poll an Agent Identity Studio job. Each call advances the pipeline one step ' +
+ 'FREE, poll an Agent Identity Studio job. Each call advances the pipeline one step ' +
'(generation → rig → renders) and reports progress; when status is "done" it returns the ' +
'deliverables: PFP PNG (1024 + 128 preview), full-body render set, rigged GLB, and a ' +
'three.ws viewer link. No payment or account required.',
@@ -120,7 +120,7 @@ const gettingStarted = buildGettingStartedTool({
priceFor: (name) => (name === ENTRY.tool ? { amount_usdc: Number(ENTRY.priceUsd) } : null),
access: [
`Pay per identity with x402 (USDC): $${ENTRY.priceUsd} per create_identity call.`,
- `${STATUS_TOOL} and this tool are free — no payment, account, or key.`,
+ `${STATUS_TOOL} and this tool are free, no payment, account, or key.`,
'Full service index (free): https://three.ws/api/okx/3d/catalog',
],
links: {
@@ -143,7 +143,7 @@ export const TOOLS = Object.fromEntries(
);
// Free tools servable to the anonymous principal with no OAuth/x402: discovery
-// plus status polling — the "status/preview free" half of the service promise.
+// plus status polling, the "status/preview free" half of the service promise.
// The paid tool is deliberately NOT here.
export function isPublicIdentityTool(name) {
return name === GETTING_STARTED_TOOL || name === STATUS_TOOL;
@@ -168,7 +168,7 @@ export const dispatch = makeDispatcher({
// 402 challenge metadata: how facilitators/indexers see this endpoint.
export const IDENTITY_CHALLENGE = {
description:
- 'three.ws Agent Identity Studio — A2MCP (MCP Streamable HTTP) service that turns an AI ' +
+ 'three.ws Agent Identity Studio, A2MCP (MCP Streamable HTTP) service that turns an AI ' +
"agent's brand brief into a complete 3D identity: rigged GLB avatar + posed studio renders " +
`with an OKX-avatar-slot PFP crop. $${ENTRY.priceUsd} per identity, USDC via x402; job ` +
'status polling is free. Operated by three.ws.',
diff --git a/api/_providers/gcp.js b/api/_providers/gcp.js
index 7faf1eb8b..fd5d43f27 100644
--- a/api/_providers/gcp.js
+++ b/api/_providers/gcp.js
@@ -233,6 +233,12 @@ function buildWorkerRequest(request) {
negative_prompt: params?.negative_prompt || 'blurry, low quality, distorted',
num_views: params?.num_views || 8,
texture_size: params?.texture_size || 1024,
+ // person|metal|wood|fabric|plastic|glass — bakes measured-value
+ // roughness/metallic factors instead of the flat default and
+ // nudges the SDXL prompt with material-appropriate descriptors
+ // (workers/texture/main.py MATERIAL_CLASS_PBR). Optional: omit to
+ // keep the old flat-guess behavior.
+ material_class: params?.material_class || null,
},
};
}
diff --git a/api/cron/quality-bench.js b/api/cron/quality-bench.js
new file mode 100644
index 000000000..8e6dca94d
--- /dev/null
+++ b/api/cron/quality-bench.js
@@ -0,0 +1,129 @@
+// GET /api/cron/quality-bench — weekly bounded realism-regression smoke test.
+//
+// This is NOT the full 23-prompt x all-lanes x all-tiers baseline (that one is
+// run by hand/CI via `node scripts/quality-bench.mjs` and its result committed
+// to data/quality-bench/runs/ — Cloud Run's filesystem is ephemeral and this
+// handler can't commit to git). Instead it runs a small fixed subset — enough
+// prompts to span a few subject classes, on the platform's default standard-tier
+// image lane — end to end for real (real forge generation, real render, real
+// Vertex Gemini judge), and diffs the result against the most recent COMMITTED
+// baseline run for the same lane/tier. It logs a structured summary line via
+// console.log/console.error either way — Cloud Logging IS "the run log" here —
+// so `gcloud logging read` surfaces a regression without anyone needing to run
+// the full bench first. For a real before/after gate on a specific change, run
+// `node scripts/quality-bench.mjs --compare=latest,previous` by hand — see
+// data/quality-bench/README.md.
+
+import { readFile, readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { loadCatalog, runOne } from '../_lib/quality-bench.js';
+
+export const maxDuration = 300;
+
+// A small, fixed, cheap-to-run cross-section of the full bench: one
+// people/organic subject, one hard-surface subject, one architecture subject.
+// Kept deliberately short so the whole sweep fits inside maxDuration.
+const SMOKE_PROMPT_IDS = ['qb01', 'qb09', 'qb12'];
+const SMOKE_TIER = 'standard';
+const REGRESSION_THRESHOLD = 1.0;
+
+const BENCH_DIR = path.join(process.cwd(), 'data', 'quality-bench');
+const RUNS_DIR = path.join(BENCH_DIR, 'runs');
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+async function loadPrompts() {
+ const raw = JSON.parse(await readFile(path.join(BENCH_DIR, 'prompts.json'), 'utf8'));
+ return raw.prompts;
+}
+
+// Mean score for (lane, tier) across every committed run's results — the
+// standing baseline this sweep compares a fresh smoke run against.
+async function baselineMean(lane, tier) {
+ let files = [];
+ try {
+ files = (await readdir(RUNS_DIR)).filter((f) => f.endsWith('.json'));
+ } catch {
+ return null;
+ }
+ const scores = [];
+ for (const file of files) {
+ try {
+ const run = JSON.parse(await readFile(path.join(RUNS_DIR, file), 'utf8'));
+ for (const r of run.results || []) {
+ if (r.lane === lane && r.tier === tier && typeof r.meanScore === 'number') scores.push(r.meanScore);
+ }
+ } catch {
+ // skip a corrupt run file
+ }
+ }
+ if (!scores.length) return null;
+ return scores.reduce((a, b) => a + b, 0) / scores.length;
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ const baseUrl = `https://${req.headers.host || 'three.ws'}`;
+
+ let catalog;
+ try {
+ catalog = await loadCatalog(baseUrl);
+ } catch (err) {
+ error(res, 502, 'catalog_unavailable', String(err?.message || err));
+ return;
+ }
+ const lane = catalog.default_backend_for_tier?.[SMOKE_TIER]?.image;
+ if (!lane) {
+ error(res, 503, 'no_lane', `no default image lane for tier "${SMOKE_TIER}"`);
+ return;
+ }
+
+ const allPrompts = await loadPrompts();
+ const prompts = SMOKE_PROMPT_IDS.map((id) => allPrompts.find((p) => p.id === id)).filter(Boolean);
+
+ const results = [];
+ for (const p of prompts) {
+ results.push(await runOne(baseUrl, p, lane, SMOKE_TIER));
+ }
+
+ const scored = results.filter((r) => typeof r.meanScore === 'number');
+ const smokeMean = scored.length ? scored.reduce((s, r) => s + r.meanScore, 0) / scored.length : null;
+ const baseline = await baselineMean(lane, SMOKE_TIER);
+
+ const summary = {
+ kind: 'quality-bench-smoke',
+ lane,
+ tier: SMOKE_TIER,
+ promptIds: SMOKE_PROMPT_IDS,
+ smokeMean,
+ baselineMean: baseline,
+ delta: smokeMean != null && baseline != null ? smokeMean - baseline : null,
+ perPrompt: results.map((r) => ({ promptId: r.promptId, status: r.status, meanScore: r.meanScore, error: r.error || null })),
+ };
+
+ const regressed = summary.delta != null && summary.delta < -REGRESSION_THRESHOLD;
+ if (regressed) {
+ console.error('[cron] quality-bench REGRESSION', summary);
+ } else {
+ console.log('[cron] quality-bench smoke run', summary);
+ }
+
+ json(res, regressed ? 200 : 200, { ok: true, regressed, ...summary });
+});
diff --git a/api/forge.js b/api/forge.js
index 50c42e0ed..1322f3aa1 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -139,7 +139,7 @@ import {
} from './_lib/forge-failover.js';
import { decideSelfhostMissing } from './_lib/forge-selfhost-recovery.js';
import { directPrompt } from './_mcp-studio/forge-client.js';
-import { MESH_DIRECTOR, resolveLogoPrompt } from './_lib/forge-director-prompts.js';
+import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/forge-director-prompts.js';
// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The
// hosted NVCF gateway can degrade so a submit neither completes nor hands back a
@@ -1863,7 +1863,12 @@ async function startJob(req, res) {
if (knownMark) {
directedPrompt = knownMark.prompt;
} else {
- const directed = await directPrompt(MESH_DIRECTOR, prompt).catch(() => null);
+ // Subject-classified briefing (person/animal/vehicle/food/architecture/
+ // object) so the director reaches for the material/construction cues
+ // that actually matter for THIS subject's failure mode.
+ const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt).catch(
+ () => null,
+ );
if (directed) directedPrompt = directed;
}
}
diff --git a/api/gpt-forge.js b/api/gpt-forge.js
index 92020ac6f..2cca55498 100644
--- a/api/gpt-forge.js
+++ b/api/gpt-forge.js
@@ -147,7 +147,7 @@ import {
} from './_lib/forge-failover.js';
import { decideSelfhostMissing } from './_lib/forge-selfhost-recovery.js';
import { directPrompt } from './_mcp-studio/gpt-forge-client.js';
-import { MESH_DIRECTOR, resolveLogoPrompt } from './_lib/forge-director-prompts.js';
+import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/forge-director-prompts.js';
// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The
// hosted NVCF gateway can degrade so a submit neither completes nor hands back a
@@ -1871,7 +1871,9 @@ async function startJob(req, res) {
if (knownMark) {
directedPrompt = knownMark.prompt;
} else {
- const directed = await directPrompt(MESH_DIRECTOR, prompt).catch(() => null);
+ const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt).catch(
+ () => null,
+ );
if (directed) directedPrompt = directed;
}
}
diff --git a/api/internal/quest-notify.js b/api/internal/quest-notify.js
new file mode 100644
index 000000000..d7f5f5ca6
--- /dev/null
+++ b/api/internal/quest-notify.js
@@ -0,0 +1,54 @@
+// POST /api/internal/quest-notify — the multiplayer server → API bridge for
+// quest/mission notifications. WalkRoom already publishes a public
+// 'mission-complete' ticker event (api/_lib/feed.js) when a player finishes a
+// /play job or co-op heist, but that ticker is anonymous-by-design (world-
+// readable) and carries no per-user id. This endpoint is the missing link: the
+// authoritative Colyseus process (which verified the player's presence ticket
+// on join) reports the SAME completion here, scoped to the player's real
+// account id, so it lands in their bell inbox.
+//
+// Trust model mirrors api/world/[action].js save: only a request bearing a
+// valid world-service token (signed by multiplayer/src/persistence.js's
+// signServiceToken, svc:'world') is accepted — a browser can't forge a quest
+// completion for another account.
+
+import { json, method, wrap, error, readJson, cors } from '../_lib/http.js';
+import { extractBearer } from '../_lib/auth.js';
+import { verifyWorldServiceToken } from '../_lib/world-service-auth.js';
+import { insertNotification } from '../_lib/notify.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export default wrap(async (req, res) => {
+ // Server-to-server only — no browser origin ever calls this directly.
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const service = await verifyWorldServiceToken(extractBearer(req));
+ if (!service) return error(res, 401, 'unauthorized', 'valid world service token required');
+
+ let body;
+ try {
+ body = await readJson(req, 4096);
+ } catch (err) {
+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
+ }
+
+ const accountUid = typeof body?.accountUid === 'string' ? body.accountUid.trim() : '';
+ if (!UUID_RE.test(accountUid)) return error(res, 400, 'validation_error', 'accountUid must be a user id');
+
+ const mission = typeof body?.mission === 'string' ? body.mission.slice(0, 120) : null;
+ const gold = Number.isFinite(body?.gold) ? Math.max(0, Math.round(body.gold)) : null;
+ const coop = !!body?.coop;
+ const coin = typeof body?.coin === 'string' ? body.coin.slice(0, 32) : null;
+
+ insertNotification(accountUid, 'quest_complete', {
+ mission,
+ gold,
+ coop,
+ coin,
+ link: '/play',
+ });
+
+ return json(res, 200, { ok: true });
+});
diff --git a/api/mcp-3d.js b/api/mcp-3d.js
index 6be60f501..0d87142a7 100644
--- a/api/mcp-3d.js
+++ b/api/mcp-3d.js
@@ -1,8 +1,8 @@
-// three.ws 3D Studio — MCP server (Streamable HTTP transport, MCP 2025-06-18).
-// POST /api/mcp-3d — tool calls GET /api/mcp-3d — SSE DELETE — terminate.
+// three.ws 3D Studio: MCP server (Streamable HTTP transport, MCP 2025-06-18).
+// POST /api/mcp-3d: tool calls GET /api/mcp-3d: SSE DELETE: terminate.
//
-// A second, focused MCP server alongside /api/mcp: it does one thing — turn
-// text or images into interactive 3D models — and shares the main server's
+// A second, focused MCP server alongside /api/mcp: it does one thing, turn
+// text or images into interactive 3D models, and shares the main server's
// OAuth/x402 auth, rate limiting, and transport plumbing. Registered with the
// MCP Registry as io.github.nirholas/three-ws-3d-studio (see server-3d.json).
import { cors, readJson, wrap } from './_lib/http.js';
@@ -39,7 +39,7 @@ export default wrap(async (req, res) => {
// discovery so the OAuth flow starts where it should.
const body = await readJson(req, 1_000_000);
- // x402 price for the WHOLE request — the sum of every priced studio
+ // x402 price for the WHOLE request, the sum of every priced studio
// tools/call in the (possibly batched) body, tier-aware for the generation
// tools. The advertised 402 amount, the verified payment, and the settled
// charge are all keyed off this total, mirroring /api/x402/forge pricing.
@@ -75,7 +75,7 @@ export default wrap(async (req, res) => {
// signed payment proof across dispatch+settle so a captured/retried X-PAYMENT
// can't re-run the priced (and here often generation-grade) tools before the
// first settle lands. Released in the finally; the consumed on-chain nonce
- // blocks any replay thereafter. Fails open — see reservePaymentProof.
+ // blocks any replay thereafter. Fails open, see reservePaymentProof.
let releaseProof = async () => {};
if (x402Ctx) {
const guard = await reservePaymentProof(
@@ -97,9 +97,9 @@ export default wrap(async (req, res) => {
// OAuth users run tools operator-funded (bounded by rate limits). x402
// callers pay per tool: the verified payment covers the batch's summed
- // per-tool price (tier-aware for generation — see _mcp3d/pricing.js), and
+ // per-tool price (tier-aware for generation, see _mcp3d/pricing.js), and
// settling it here means the charge lands only after the work succeeded.
- // Only settle if a call succeeded — a wholesale failure is free.
+ // Only settle if a call succeeded, a wholesale failure is free.
if (x402Ctx) {
const anySuccess = responses.some(
(r) => r && !r.error && !(r.result && r.result.isError),
diff --git a/api/notifications/index.js b/api/notifications/index.js
index 229488f30..82aa35730 100644
--- a/api/notifications/index.js
+++ b/api/notifications/index.js
@@ -21,8 +21,21 @@ export default wrap(async (req, res) => {
// shape so the parameter can't smuggle anything unexpected into the query.
const typeRaw = (params.get('type') || '').trim();
const type = /^[a-z0-9_]{1,40}$/.test(typeRaw) ? typeRaw : null;
+ // Optional cursor for "load more" on the full notification-center page
+ // (pages/notifications.html): pass the last row's created_at to page past it.
+ // The bell dropdown never sends this — it only ever wants the latest page.
+ const beforeRaw = params.get('before');
+ const before = beforeRaw && !Number.isNaN(Date.parse(beforeRaw)) ? new Date(beforeRaw) : null;
- const notifications = type
+ const notifications = type && before
+ ? await sql`
+ select id, type, payload, read_at, created_at
+ from user_notifications
+ where user_id = ${user.id} and type = ${type} and created_at < ${before}
+ order by created_at desc
+ limit ${limit}
+ `
+ : type
? await sql`
select id, type, payload, read_at, created_at
from user_notifications
@@ -30,6 +43,14 @@ export default wrap(async (req, res) => {
order by created_at desc
limit ${limit}
`
+ : before
+ ? await sql`
+ select id, type, payload, read_at, created_at
+ from user_notifications
+ where user_id = ${user.id} and created_at < ${before}
+ order by created_at desc
+ limit ${limit}
+ `
: await sql`
select id, type, payload, read_at, created_at
from user_notifications
@@ -53,5 +74,6 @@ export default wrap(async (req, res) => {
created_at: n.created_at,
})),
unread_count,
+ has_more: notifications.length === limit,
});
});
diff --git a/api/okx/3d/[service].js b/api/okx/3d/[service].js
index 2c6c6788f..7534b2e6f 100644
--- a/api/okx/3d/[service].js
+++ b/api/okx/3d/[service].js
@@ -1,12 +1,12 @@
-// OKX.AI marketplace services — one Vercel function, many fronts.
+// OKX.AI marketplace services, one Vercel function, many fronts.
// Routes /api/okx/3d/<service> per the catalog in api/_lib/okx-catalog.js:
//
-// /api/okx/3d/catalog GET, free — machine-readable service index
-// /api/okx/3d/health GET, free — live subsystem health (real probes)
+// /api/okx/3d/catalog GET, free, machine-readable service index
+// /api/okx/3d/health GET, free, live subsystem health (real probes)
// /api/okx/3d/identity-studio A2MCP (MCP Streamable HTTP): POST tool calls,
// GET SSE, DELETE terminate. create_identity is
// x402-priced; identity_status + getting_started
-// are free. Transport mirrors api/mcp-3d.js —
+// are free. Transport mirrors api/mcp-3d.js,
// verify → dispatch → settle-on-success.
// /api/okx/3d/<paid service> REST (work order 03): plain JSON POST, one
// capability + one price per endpoint. Unpaid
@@ -85,7 +85,7 @@ async function probe(name, fn) {
async function healthReport() {
const subsystems = await Promise.all([
probe('generation', async () => {
- // /api/forge serves its catalog/config on GET without starting a job —
+ // /api/forge serves its catalog/config on GET without starting a job,
// reachable + parseable proves the generation front door is up.
const res = await fetch(`${BASE}/api/forge`, {
headers: { accept: 'application/json' },
@@ -117,7 +117,7 @@ async function healthReport() {
}
}),
probe('retarget', async () => {
- // The animation library the retarget service reads clips from — a
+ // The animation library the retarget service reads clips from, a
// reachable, non-empty manifest proves the clip lane is servable.
const res = await fetch(`${BASE}/animations/manifest.json`, {
headers: { accept: 'application/json' },
@@ -146,7 +146,7 @@ async function healthReport() {
}
// Per-service accepts: the OKX X Layer entry leads (that is the rail this
-// surface exists for — the buyer CLI auto-selects the first `exact` entry),
+// surface exists for, the buyer CLI auto-selects the first `exact` entry),
// followed by the platform's existing rails so non-OKX agents can pay too.
// One service, one price: every entry carries the same catalog amount.
function restRequirements(resourceUrl, entry) {
@@ -156,7 +156,7 @@ function restRequirements(resourceUrl, entry) {
return out;
}
-// Free GET descriptor — per-service discovery, mirroring GET /api/x402/forge:
+// Free GET descriptor, per-service discovery, mirroring GET /api/x402/forge:
// what it does, what it costs, how to call it. No payment, no account.
function restDescriptor(res, entry) {
return json(
@@ -170,7 +170,7 @@ function restDescriptor(res, entry) {
price_usd: entry.priceUsd,
description: listingDescription(entry),
input_schema: entry.inputSchema,
- poll: 'GET /api/forge?job=<job_id> — free',
+ poll: 'GET /api/forge?job=<job_id>, free',
catalog: `${BASE}/api/okx/3d/catalog`,
},
{ 'cache-control': 'public, max-age=300' },
@@ -213,7 +213,7 @@ async function handleRestService(req, res, entry) {
res,
503,
'rail_unconfigured',
- 'No payment rail is configured on this deployment — set the X Layer envs per specs/okx-agent-payments.md.',
+ 'No payment rail is configured on this deployment, set the X Layer envs per specs/okx-agent-payments.md.',
);
}
@@ -259,7 +259,7 @@ async function handleRestService(req, res, entry) {
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
- // Engine runs AFTER verify, BEFORE settle — a thrown engine error means
+ // Engine runs AFTER verify, BEFORE settle, a thrown engine error means
// the buyer was not charged, and we say so.
let result;
try {
@@ -268,7 +268,7 @@ async function handleRestService(req, res, entry) {
const status = err.status || 502;
const message =
status >= 500
- ? 'The service could not complete and your payment was not taken — please retry shortly.'
+ ? 'The service could not complete and your payment was not taken, please retry shortly.'
: err.message;
if (status >= 500) console.warn(`[okx/3d/${entry.id}] engine failed (${status}): ${err?.message || err}`);
return error(res, status, err.code || 'service_failed', message);
@@ -315,7 +315,7 @@ async function handleIdentityStudio(req, res) {
const resourcePath = '/api/okx/3d/identity-studio';
const resourceUrl = resolveResourceUrl(req, resourcePath);
// The flagship sells on OKX.AI, so its 402 must LEAD with the X Layer
- // (eip155:196) accept — exactly like the WO-03 REST services — or an OKX
+ // (eip155:196) accept, exactly like the WO-03 REST services, or an OKX
// buyer can't pay it. Priced at the create_identity fee; gated on the X Layer
// envs being present. Prepended into the MCP challenge + verify path.
const xlayerAccepts = xlayerSettleable()
@@ -359,7 +359,7 @@ async function handleIdentityStudio(req, res) {
if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
// Single-use lock on the payment proof across dispatch+settle, mirroring
- // /api/mcp-3d — a replayed X-PAYMENT can't run a second job before the
+ // /api/mcp-3d, a replayed X-PAYMENT can't run a second job before the
// first settle lands.
let releaseProof = async () => {};
if (x402Ctx) {
@@ -382,7 +382,7 @@ async function handleIdentityStudio(req, res) {
// Settle only after the work was accepted: a create_identity that failed
// validation (bad brief, unreachable reference image) returns isError and
- // the payment is never settled — the pay-only-on-acceptance promise the
+ // the payment is never settled, the pay-only-on-acceptance promise the
// catalog description makes.
if (x402Ctx) {
const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));
@@ -437,7 +437,7 @@ export default wrap(async (req, res) => {
return json(res, 404, {
error: 'unknown_service',
message: known
- ? `service "${service}" is catalogued but not yet routable — see the catalog for status`
+ ? `service "${service}" is catalogued but not yet routable, see the catalog for status`
: `no such service "${service}"`,
services: OKX_CATALOG.map((e) => e.endpoint),
});
diff --git a/api/quality-bench.js b/api/quality-bench.js
new file mode 100644
index 000000000..9de7ff76e
--- /dev/null
+++ b/api/quality-bench.js
@@ -0,0 +1,82 @@
+// GET /api/quality-bench — serves the committed realism-eval run history so the
+// /quality-bench dashboard (and any external tooling) can read it without a DB
+// round-trip. Every run is a JSON file committed under data/quality-bench/runs/;
+// this endpoint just lists and returns them, plus the fixed prompt set.
+//
+// GET /api/quality-bench -> { prompts, runs: [{ file, runId, startedAt, finishedAt, meanScore }] }
+// GET /api/quality-bench?run=<file> -> the full run JSON
+
+import { readFile, readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { cors, json, method, wrap, error } from './_lib/http.js';
+
+const BENCH_DIR = path.join(process.cwd(), 'data', 'quality-bench');
+const RUNS_DIR = path.join(BENCH_DIR, 'runs');
+
+function overallMean(run) {
+ const scores = (run.results || []).map((r) => r.meanScore).filter((n) => typeof n === 'number');
+ if (!scores.length) return null;
+ return scores.reduce((a, b) => a + b, 0) / scores.length;
+}
+
+async function listRunSummaries() {
+ let files = [];
+ try {
+ files = (await readdir(RUNS_DIR)).filter((f) => f.endsWith('.json')).sort();
+ } catch {
+ return [];
+ }
+ const summaries = [];
+ for (const file of files) {
+ try {
+ const run = JSON.parse(await readFile(path.join(RUNS_DIR, file), 'utf8'));
+ summaries.push({
+ file,
+ runId: run.runId,
+ startedAt: run.startedAt,
+ finishedAt: run.finishedAt,
+ baseUrl: run.baseUrl,
+ lanes: run.lanes,
+ tiers: run.tiers,
+ judgeModel: run.judgeModel,
+ resultCount: (run.results || []).length,
+ meanScore: overallMean(run),
+ });
+ } catch {
+ // skip an unreadable/corrupt run file rather than failing the whole listing
+ }
+ }
+ return summaries;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const runFile = url.searchParams.get('run');
+
+ if (runFile) {
+ const safeName = path.basename(runFile);
+ if (!/^[a-zA-Z0-9._-]+\.json$/.test(safeName)) {
+ return error(res, 400, 'bad_request', 'invalid run file name');
+ }
+ try {
+ const run = JSON.parse(await readFile(path.join(RUNS_DIR, safeName), 'utf8'));
+ return json(res, 200, run, { 'cache-control': 'public, max-age=300' });
+ } catch {
+ return error(res, 404, 'not_found', `run file "${safeName}" not found`);
+ }
+ }
+
+ let prompts = [];
+ try {
+ const raw = JSON.parse(await readFile(path.join(BENCH_DIR, 'prompts.json'), 'utf8'));
+ prompts = raw.prompts || [];
+ } catch {
+ // prompts.json missing is a build problem, not a caller error — return empty
+ }
+
+ const runs = await listRunSummaries();
+ return json(res, 200, { prompts, runs }, { 'cache-control': 'public, max-age=120' });
+});
diff --git a/apps-sdk/embodiment/embodiment-stage.js b/apps-sdk/embodiment/embodiment-stage.js
index b5eb65da7..2c2cf7ffe 100644
--- a/apps-sdk/embodiment/embodiment-stage.js
+++ b/apps-sdk/embodiment/embodiment-stage.js
@@ -28,13 +28,13 @@
import {
Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, DirectionalLight,
- PMREMGenerator, Box3, Vector3, Group, Color, RingGeometry, MeshBasicMaterial, Mesh,
+ Box3, Vector3, Group, Color, RingGeometry, MeshBasicMaterial, Mesh,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { getDecoders } from '../../src/viewer/internal.js';
+import { applyCinematicDefaults, loadEnvironment, detectQualityTier } from '../../src/shared/cinematic-render.js';
import { AnimationManager } from '../../src/animation-manager.js';
import { AvatarMouthTarget } from '../../src/voice/avatar-morph-target.js';
@@ -107,8 +107,12 @@ export class EmbodimentStage {
this.renderer = new WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
this.renderer.setSize(w, h);
- this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
- this.renderer.outputColorSpace = 'srgb';
+ // ACES tone mapping + correct sRGB output + soft shadow type + a
+ // pixel-ratio cap that respects the host device's real capability
+ // (the Apps SDK panel runs inside ChatGPT/Claude's own page, so we
+ // cannot assume a desktop-class GPU). Same bar every other viewer
+ // on the platform meets — see src/shared/cinematic-render.js.
+ applyCinematicDefaults(this.renderer, { tier: detectQualityTier() });
c.appendChild(this.renderer.domElement);
this.renderer.domElement.setAttribute('aria-label', 'Interactive 3D agent');
this.renderer.domElement.setAttribute('role', 'img');
@@ -126,10 +130,15 @@ export class EmbodimentStage {
// compounding repeated multiplications across calls.
this._baseLightIntensity = { ambient: this.ambient.intensity, key: this.keyLight.intensity, rim: this.rimLight.intensity };
- const pmrem = new PMREMGenerator(this.renderer);
- this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
- this.scene.environment = this._envTex;
- pmrem.dispose();
+ // Embodiment mounts cross-origin, inside ChatGPT/Claude's own page — an
+ // absolute path like `/hdri/studio.hdr` would resolve against the HOST
+ // page's origin (chatgpt.com, claude.ai) and 404, not three.ws. Passing
+ // `null` skips the HDRI fetch entirely and uses the procedural
+ // RoomEnvironment fallback baked into loadEnvironment(), which needs no
+ // network request and is still a physically-plausible IBL source.
+ loadEnvironment(this.renderer, this.scene, null).then((envTex) => {
+ this._envTex = envTex;
+ });
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.js
index 9bb26a3ed..c14a333f3 100644
--- a/avatar-sdk/src/viewer.js
+++ b/avatar-sdk/src/viewer.js
@@ -64,6 +64,24 @@ function getDracoLoader() {
return _dracoPromise;
}
+// Real photographic IBL — every viewer on the platform is lit by an actual
+// HDRI, not just the procedural RoomEnvironment. `<three-ws-viewer>` embeds
+// on arbitrary third-party sites, so a root-relative path (`/hdri/studio.hdr`)
+// would resolve against the HOST page's origin and 404; this fetches from
+// three.ws's own absolute origin, same pattern as AR_LAUNCH_ORIGIN above.
+// Lazy + memoized: the decoded HDRI texture is shared across every viewer
+// instance on the page (each still gets its own PMREM-derived env map, so
+// per-instance disposal never affects a sibling viewer).
+let _hdriPromise = null;
+function getHdriTexture() {
+ if (!_hdriPromise) {
+ _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
+ new RGBELoader().loadAsync(`${AR_LAUNCH_ORIGIN}/hdri/studio.hdr`),
+ );
+ }
+ return _hdriPromise;
+}
+
// Low-power heuristic: coarse pointer (touch) + few cores/little memory almost
// always means an entry-level phone. `deviceMemory` is Chromium-only and
// absent on iOS/Firefox, so it only ever *adds* signal, never gates alone.
@@ -263,9 +281,27 @@ class ThreeWsViewerElement extends HTMLElement {
// instead — visually close, meaningfully cheaper on first paint.
if (!this._lowPower) {
const pmrem = new PMREMGenerator(this._renderer);
+ pmrem.compileEquirectangularShader();
+ // Paint immediately with the procedural room so the model is never
+ // unlit while the real HDRI streams in over the network — then swap
+ // to the photographic environment once it lands.
this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
this._scene.environment = this._envTex;
- pmrem.dispose();
+ getHdriTexture()
+ .then((hdrTexture) => {
+ if (!this._renderer || !this._scene) { pmrem.dispose(); return; } // torn down before it landed
+ const prevEnv = this._envTex;
+ this._envTex = pmrem.fromEquirectangular(hdrTexture).texture;
+ this._scene.environment = this._envTex;
+ prevEnv?.dispose();
+ pmrem.dispose();
+ })
+ .catch(() => {
+ // Real HDRI unreachable from this embed's host (offline, CSP,
+ // blocked cross-origin request) — the procedural room stays as
+ // a correct, if less photographic, fallback.
+ pmrem.dispose();
+ });
}
this._scene.add(new AmbientLight(0xffffff, this._lowPower ? 0.75 : 0.55));
diff --git a/data/agent-identities.json b/data/agent-identities.json
index a52241a79..f8de22913 100644
--- a/data/agent-identities.json
+++ b/data/agent-identities.json
@@ -1,11 +1,11 @@
{
- "$comment": "Agent Identity Studio demo identities — the saved inputs and pipeline outputs behind three.ws/agent-identities. Each entry is a REAL run of the production pipeline (scripts/okx-identity-demo.mjs); results are written back here by the script, never by hand.",
+ "$comment": "Agent Identity Studio demo identities, the saved inputs and pipeline outputs behind three.ws/agent-identities. Each entry is a REAL run of the production pipeline (scripts/okx-identity-demo.mjs); results are written back here by the script, never by hand.",
"identities": [
{
"slug": "ledgerlynx",
"kind": "finance data agent",
"agentName": "LedgerLynx",
- "brief": "A meticulous on-chain accounting agent that reconciles wallets and flags anomalies in real time. Calm, precise, incorruptible — dresses like a sharp auditor from the future.",
+ "brief": "A meticulous on-chain accounting agent that reconciles wallets and flags anomalies in real time. Calm, precise, incorruptible, dresses like a sharp auditor from the future.",
"styleHints": "deep navy and silver palette, brushed-metal accents, subtle circuit-trace pinstripes",
"result": {
"jobIdPrefix": "f1.eyJwIjoib2t4a",
@@ -159,7 +159,7 @@
},
{
"slug": "three-ws-3d-studio",
- "kind": "our own listing — OKX.AI agent #2632",
+ "kind": "our own listing, OKX.AI agent #2632",
"agentName": "three.ws 3D Studio",
"brief": "The 3D identity studio of three.ws: an artisan engineer agent that forges avatars, rigs skeletons, and lights studio renders for other AI agents. Equal parts craftsman and machine.",
"styleHints": "charcoal work jacket with violet and cyan accents, holographic measuring tools, craftsman apron",
diff --git a/data/changelog.json b/data/changelog.json
index 54f9089de..6c9ce5c23 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -15546,6 +15546,16 @@
"fix"
]
},
+ {
+ "date": "2026-07-23",
+ "title": "Real materials: skin, glass, and car paint that actually behave like the real thing",
+ "summary": "Avatars now get a subtle skin sheen, wet-looking corneas, and double-sided hair automatically the moment a humanoid model loads in any three.ws viewer, no extra step needed. Restyle Studio's material presets grew a real-physics tier alongside the classic looks: skin, car paint with a genuine clearcoat layer, brushed steel with directional anisotropic highlights, and a real-glass preset that actually refracts (KHR_materials_transmission) instead of faking transparency. The AI restyle tool (\"make it chrome\", \"cyberpunk neon\") can now propose clearcoat, transmission, and sheen too when an instruction calls for it. The text-guided texture worker also gained an optional material_class hint (person/metal/wood/fabric/plastic/glass) that bakes measured real-world roughness values instead of one flat guess for every material.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/restyle"
+ },
{
"date": "2026-07-22",
"title": "Animation Studio toolbar cleanup",
diff --git a/data/pages.json b/data/pages.json
index 239280849..fe06ef5e6 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -190,6 +190,14 @@
"changefreq": "weekly",
"added": "2026-06-17"
},
+ {
+ "path": "/notifications",
+ "title": "Notifications",
+ "description": "Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.",
+ "priority": 0.5,
+ "changefreq": "daily",
+ "added": "2026-07-12"
+ },
{
"path": "/skills",
"title": "Skills Marketplace",
@@ -1888,7 +1896,7 @@
},
{
"path": "/agent-identities",
- "title": "Agent Identity Studio — 3D avatars for AI agents",
+ "title": "Agent Identity Studio: 3D avatars for AI agents",
"description": "Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.",
"priority": 0.8,
"changefreq": "weekly",
diff --git a/data/quality-bench/README.md b/data/quality-bench/README.md
new file mode 100644
index 000000000..e7b1a7865
--- /dev/null
+++ b/data/quality-bench/README.md
@@ -0,0 +1,149 @@
+# Realism quality bench
+
+The measurement loop for the forge realism campaign: a fixed 23-prompt benchmark,
+a generate → render → judge pipeline that runs the REAL `/api/forge` path and
+scores the result with Vertex Gemini vision, and a dashboard so "did quality go
+up" is a number, not a vibe.
+
+## What's here
+
+- `prompts.json` — the fixed benchmark set. 20 text prompts spanning people
+ (portrait, full body), animals, food, vehicles, tools, furniture,
+ architecture, nature, and fantasy, plus 3 image→3D cases that reconstruct a
+ real CC0 reference photo (`refs/chair.jpg`, `refs/sneaker.jpg`,
+ `refs/teapot.jpg` — sources in `refs/SOURCES.md`). Each entry has an `id`,
+ `subjectClass`, `prompt`, `mode` (`text` or `image`), and a `watch` list of
+ the realism failure modes to specifically look for on that subject
+ (plastic skin, melted text/detail, blob geometry, texture tiling, etc.).
+ **Never edit an existing id's prompt/subjectClass/watch once a run has been
+ committed against it** — scores across runs are only comparable when the
+ input is byte-identical. Add a new id instead.
+- `runs/` — one committed JSON file per run, append-only (a run file is never
+ edited after `finishedAt` is set; a re-run creates a new file). This is the
+ full history the dashboard reads.
+- `refs/` — the 3 CC0 reference photos for the image→3D cases, plus
+ `SOURCES.md` documenting where each came from and its license.
+
+## Running the bench
+
+```sh
+# Full sweep: every live image-capable lane, standard + high tier
+node scripts/quality-bench.mjs
+
+# One lane, one tier, a couple of prompts (fast iteration)
+node scripts/quality-bench.mjs --lane=trellis_selfhost --tier=standard --prompts=qb01,qb09
+
+# Against a non-production deployment
+node scripts/quality-bench.mjs --base-url=https://staging.three.ws
+
+# See what would run without spending anything
+node scripts/quality-bench.mjs --dry-run
+
+# Resume a run that crashed or was interrupted — never re-submits a completed
+# (prompt, lane, tier) combo
+node scripts/quality-bench.mjs --resume=run-2026-07-23T12-00-00-000Z.json
+```
+
+Flags: `--lane=<id|id,id|all>` (default `all` = every lane `/api/forge?catalog`
+reports as `configured`), `--tier=<draft|standard|high|all>` (default
+`standard,high`), `--prompts=<id,id,...|all>` (default `all`), `--base-url`
+(default `https://three.ws`), `--resume=<run file>`, `--dry-run`.
+
+**Credentials.** Forge generation needs nothing locally — the script calls the
+live `/api/forge` HTTP path on `--base-url`, which runs against that
+deployment's own configured lanes and credentials. Scoring needs
+`GOOGLE_CLOUD_PROJECT` set and GCP credentials resolvable the same way every
+other Vertex Gemini caller in this repo resolves them (`GCP_SERVICE_ACCOUNT_JSON`
+env var, or the ambient Cloud Run/GCE metadata server) — see
+`api/_lib/gcp-auth.js`. Without those, the script still runs real generations
+and renders, but every view's score comes back as an error (never a fabricated
+number) and that (prompt, lane, tier) combo is recorded with `status:
+"scoring_failed"`.
+
+**Idempotency / cost control.** The runner writes the run file to disk after
+every single completed `(prompt, lane, tier)` result, so a crash loses at most
+one in-flight generation. `--resume` skips every combo already recorded.
+`/api/forge` itself caches identical `(prompt, tier, backend)` submissions, so
+re-running an already-generated combo doesn't re-spend GPU time — it reuses the
+prior real generation.
+
+## Reading a run
+
+Each run file (`runs/run-<timestamp>.json`) has:
+
+```jsonc
+{
+ "runId": "run-2026-07-23T12-00-00-000Z",
+ "startedAt": "...", "finishedAt": "...",
+ "baseUrl": "https://three.ws",
+ "judgeModel": "google/gemini-2.5-pro",
+ "judgePromptVersion": 1,
+ "lanes": ["trellis_selfhost", "hunyuan3d", ...],
+ "tiers": ["standard", "high"],
+ "results": [
+ {
+ "promptId": "qb01", "subjectClass": "people-portrait",
+ "lane": "trellis_selfhost", "tier": "standard",
+ "status": "ok", "glbUrl": "...", "creationId": "...",
+ "views": [
+ { "view": "front", "scores": [ { "photorealism": 7, "geometryIntegrity": 6, "textureFidelity": 7, "promptAdherence": 8, "critique": "...", "modelVersion": "gemini-2.5-pro-..." }, { /* 2nd scoring */ } ], "avg": { "photorealism": 7, "...": "...", "mean": 6.8 } },
+ { "view": "three-quarter", "...": "..." },
+ { "view": "side", "...": "..." }
+ ],
+ "meanScore": 6.6
+ }
+ ]
+}
+```
+
+`meanScore` on a result averages that combo's per-view means (each view's mean
+already averages its two independent judge scorings). A `lane_failed` result
+means the lane was down or the generation errored (`error` field has the
+reason) — recorded as `meanScore: 0`, never dropped, so an outage shows up as a
+visible dip rather than a gap in the data. A `scoring_failed` result means
+generation and render succeeded but the judge couldn't be reached — `meanScore`
+is `null` (excluded from means) and each view's `error` explains why.
+
+The dashboard at `/quality-bench` (`api/quality-bench.js` +
+`pages/quality-bench.html`) renders this run history: score trends by lane,
+tier, and subject class, a worst-5 gallery with critiques, and a full results
+table. It's an internal path (not in `data/pages.json`) — no changelog entry
+unless it's made public.
+
+## Regression gate
+
+```sh
+node scripts/quality-bench.mjs --compare=latest,previous
+# or by explicit filename:
+node scripts/quality-bench.mjs --compare=run-2026-07-30T00-00-00-000Z.json,run-2026-07-23T12-00-00-000Z.json
+```
+
+Exits nonzero (and prints `REGRESSION: ...`) when the first run's overall mean
+score dropped more than 1.0 point versus the second. Run this before/after any
+forge change that could affect output quality (a new tier's sampler budget, a
+new lane, a prompt-enhancement change) — see the note in `docs/forge.md`
+(or wherever the forge pipeline is documented) linking back here.
+
+A separate weekly Cloud Scheduler job (`api/cron/quality-bench.js`, schedule
+`23 3 * * 1` in `vercel.json`) runs a small 3-prompt smoke sweep against the
+platform's default standard-tier lane and logs a structured summary line
+(`[cron] quality-bench smoke run {...}` or `... REGRESSION {...}`) comparing
+against every committed run's mean for that lane/tier — Cloud Run's filesystem
+is ephemeral so it can't commit a run file itself; check
+`gcloud logging read 'resource.type="cloud_run_revision" textPayload:"quality-bench"' --freshness=7d`
+for its output. The full, authoritative baseline is the one committed by
+running `scripts/quality-bench.mjs` by hand (or from CI) and checking the
+resulting `runs/*.json` file in.
+
+## Extending the bench
+
+Add a new prompt: append an entry to `prompts.json` with a fresh `id` (next in
+sequence), pick the narrowest `subjectClass` that fits, and write a `watch`
+list naming the specific realism failures that subject tends to produce (not
+generic ones already covered — check existing entries first). Never reuse or
+edit an existing id.
+
+Add a new lane: nothing to do here — `scripts/quality-bench.mjs` reads live
+lanes from `/api/forge?catalog`, so a new backend in
+`api/_lib/forge-tiers.js` is picked up automatically once it reports
+`configured: true`.
diff --git a/data/quality-bench/prompts.json b/data/quality-bench/prompts.json
new file mode 100644
index 000000000..28c627d9b
--- /dev/null
+++ b/data/quality-bench/prompts.json
@@ -0,0 +1,267 @@
+{
+ "$comment": "Fixed realism benchmark for the 3D forge pipeline. Never edit an existing id's prompt/subjectClass once a run has been committed against it \u2014 scores across runs are only comparable when the input is byte-identical. Add new ids instead. See data/quality-bench/README.md.",
+ "version": 1,
+ "prompts": [
+ {
+ "id": "qb01",
+ "subjectClass": "people-portrait",
+ "prompt": "photorealistic portrait bust of a middle-aged woman with short curly gray hair, wearing a navy wool sweater, neutral studio lighting, plain background",
+ "watch": [
+ "plastic/waxy skin shading",
+ "flattened facial geometry",
+ "hair fused into a solid cap",
+ "asymmetric or melted eyes"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb02",
+ "subjectClass": "people-fullbody",
+ "prompt": "a barefoot young man in worn denim overalls standing relaxed with arms at his sides, full body, photorealistic, studio lighting, plain background",
+ "watch": [
+ "broken limb proportions",
+ "melted hands or feet",
+ "blob geometry at joints",
+ "fabric fused to skin"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb03",
+ "subjectClass": "animals",
+ "prompt": "an alert red fox sitting upright in autumn leaves, photorealistic fur detail, studio lighting, plain background",
+ "watch": [
+ "fur clumping into a plastic shell",
+ "incorrect leg count or fused legs",
+ "flattened muzzle geometry"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb04",
+ "subjectClass": "animals",
+ "prompt": "a bottlenose dolphin leaping out of ocean water, wet skin highlights, mid-air pose, plain background",
+ "watch": [
+ "rubbery/matte skin instead of wet highlights",
+ "fin geometry collapse",
+ "water splash baked as a flat texture blob"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb05",
+ "subjectClass": "food",
+ "prompt": "a fresh strawberry shortcake slice on a white ceramic plate, whipped cream and berry juice, photorealistic, studio lighting",
+ "watch": [
+ "waxy/plastic food texture",
+ "cream and cake layers fused into one blob",
+ "berries rendered as flat decals"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb06",
+ "subjectClass": "food",
+ "prompt": "a wood-fired margherita pizza fresh from the oven, melted mozzarella and basil leaves, photorealistic, studio lighting",
+ "watch": [
+ "toppings fused into the crust",
+ "unrealistic uniform char pattern",
+ "cheese rendered as a flat opaque disc"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb07",
+ "subjectClass": "vehicles",
+ "prompt": "a vintage 1960s cafe racer motorcycle, chrome exhaust pipe and brown leather seat, photorealistic studio render, plain background",
+ "watch": [
+ "melted/matte chrome",
+ "spoke wheel geometry collapsing into a disc",
+ "engine block reduced to a blob"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb08",
+ "subjectClass": "vehicles",
+ "prompt": "a modern electric pickup truck, matte black paint, photorealistic studio render, three-quarter view, plain background",
+ "watch": [
+ "panel gaps missing",
+ "glass rendered as an opaque blob",
+ "wheel well geometry distortion"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb09",
+ "subjectClass": "tools",
+ "prompt": "a well-worn wooden-handled claw hammer with a scratched steel head, photorealistic studio render, plain background",
+ "watch": [
+ "wood grain smeared or melted",
+ "claw geometry fused into a solid wedge",
+ "steel head losing its metallic highlight"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb10",
+ "subjectClass": "tools",
+ "prompt": "a professional stainless steel chef's knife with a dark walnut handle, photorealistic studio render, plain background",
+ "watch": [
+ "blade thickness errors (too thick/blobby)",
+ "handle grain distortion",
+ "edge geometry not reading as sharp"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb11",
+ "subjectClass": "furniture",
+ "prompt": "a mid-century modern leather lounge chair with tapered walnut legs, photorealistic studio render, plain background",
+ "watch": [
+ "leg geometry collapsing or fusing to the seat",
+ "leather seam distortion",
+ "cushion volume looking inflated/blobby"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb12",
+ "subjectClass": "architecture",
+ "prompt": "a small stone cottage with a thatched roof and a wooden plank door, moss growing on the walls, photorealistic exterior render",
+ "watch": [
+ "thatch roof reduced to a smooth blob",
+ "door/window openings melting shut",
+ "stone texture tiling repetition"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb13",
+ "subjectClass": "architecture",
+ "prompt": "a modern glass and steel skyscraper facade viewed from street level, photorealistic render",
+ "watch": [
+ "window grid distortion or bleeding",
+ "glass rendered fully opaque",
+ "steel mullions fused into the glass"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb14",
+ "subjectClass": "nature",
+ "prompt": "a moss-covered granite boulder beside a mountain stream, wet rock texture, photorealistic render",
+ "watch": [
+ "texture tiling repetition",
+ "blobby silhouette with no rock facets",
+ "moss painted as a flat green decal"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb15",
+ "subjectClass": "nature",
+ "prompt": "a single red maple leaf with dew drops on its surface, veins clearly visible, macro photorealistic render, plain background",
+ "watch": [
+ "flat/plastic leaf surface with no thickness",
+ "dew drops merging into the leaf as a texture smear",
+ "veins missing entirely"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb16",
+ "subjectClass": "fantasy",
+ "prompt": "an ornate dragon-scale armored gauntlet, battle-worn, photorealistic metal and leather materials, plain background",
+ "watch": [
+ "scale pattern melting into a smooth surface",
+ "finger joint geometry fusing shut",
+ "metal losing specular highlights"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb17",
+ "subjectClass": "fantasy",
+ "prompt": "a glowing enchanted crystal staff wrapped in aged leather cord, photorealistic render, plain background",
+ "watch": [
+ "crystal rendered as an opaque blob with no internal glow",
+ "leather cord fused flat to the shaft",
+ "glow baked as a flat texture instead of an emissive read"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb18",
+ "subjectClass": "people-portrait",
+ "prompt": "photorealistic headshot of an elderly man with a full white beard and weathered skin, warm window light, plain background",
+ "watch": [
+ "plastic/waxy skin shading",
+ "beard geometry melting into the chin",
+ "wrinkles missing or painted as flat lines"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb19",
+ "subjectClass": "animals",
+ "prompt": "a resting golden retriever puppy lying on a wooden floor, photorealistic fur detail, plain background",
+ "watch": [
+ "fur clumping into a plastic shell",
+ "paw geometry fusing into a single pad",
+ "eyes losing wet specular highlight"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb20",
+ "subjectClass": "furniture",
+ "prompt": "an antique brass floor lamp with a pleated cream fabric shade, photorealistic studio render, plain background",
+ "watch": [
+ "brass rendered as a flat matte blob with no reflections",
+ "shade pleats melting into a smooth cone",
+ "base geometry losing its turned-metal detail"
+ ],
+ "mode": "text"
+ },
+ {
+ "id": "qb21",
+ "subjectClass": "furniture",
+ "prompt": "reconstruct this antique wooden chair as a photorealistic textured 3D model, preserving its carved details and worn finish",
+ "referenceImage": "refs/chair.jpg",
+ "watch": [
+ "carved backrest detail melting into a smooth panel",
+ "leg taper collapsing",
+ "wood grain texture washed out or tiling"
+ ],
+ "mode": "image",
+ "referenceImageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Antique_Wooden_Chair_from_Bharat.jpg/960px-Antique_Wooden_Chair_from_Bharat.jpg"
+ },
+ {
+ "id": "qb22",
+ "subjectClass": "apparel",
+ "prompt": "reconstruct this running shoe as a photorealistic textured 3D model, preserving the mesh upper, sole tread, and logo details",
+ "referenceImage": "refs/sneaker.jpg",
+ "watch": [
+ "mesh upper turned into a solid plastic shell",
+ "sole tread pattern lost or smeared",
+ "logo geometry melting"
+ ],
+ "mode": "image",
+ "referenceImageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Imani-bahati-unpaired-gray-nike-running-shoe.jpg/960px-Imani-bahati-unpaired-gray-nike-running-shoe.jpg"
+ },
+ {
+ "id": "qb23",
+ "subjectClass": "tableware",
+ "prompt": "reconstruct this covered teapot as a photorealistic textured 3D model, preserving its lid, spout, and carved surface detail",
+ "referenceImage": "refs/teapot.jpg",
+ "watch": [
+ "spout or lid fusing to the body",
+ "carved surface detail flattened to a texture decal",
+ "handle geometry collapsing"
+ ],
+ "mode": "image",
+ "referenceImageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Covered_teapot%2C_China%2C_early_19th_century%2C_nephrite%2C_Honolulu_Museum_of_Art.jpg/960px-Covered_teapot%2C_China%2C_early_19th_century%2C_nephrite%2C_Honolulu_Museum_of_Art.jpg"
+ }
+ ]
+}
diff --git a/data/quality-bench/refs/SOURCES.md b/data/quality-bench/refs/SOURCES.md
new file mode 100644
index 000000000..c9c725bd2
--- /dev/null
+++ b/data/quality-bench/refs/SOURCES.md
@@ -0,0 +1,13 @@
+# Reference photo sources
+
+All three reference photos are CC0 (public domain dedication), downloaded from
+Wikimedia Commons. Kept locally so the benchmark never depends on a third
+party staying online, and so the exact bytes fed to image->3D never drift.
+
+| File | Title | Source |
+|---|---|---|
+| `chair.jpg` | Antique Wooden Chair from Bharat | https://commons.wikimedia.org/wiki/File:Antique_Wooden_Chair_from_Bharat.jpg |
+| `sneaker.jpg` | Imani Bahati, unpaired gray Nike running shoe | https://commons.wikimedia.org/wiki/File:Imani-bahati-unpaired-gray-nike-running-shoe.jpg |
+| `teapot.jpg` | Covered teapot, China, early 19th century, nephrite, Honolulu Museum of Art | https://commons.wikimedia.org/wiki/File:Covered_teapot,_China,_early_19th_century,_nephrite,_Honolulu_Museum_of_Art.jpg |
+
+Downloaded 2026-07-23. Re-verify CC0 status on Commons if these are ever swapped.
diff --git a/data/quality-bench/refs/chair.jpg b/data/quality-bench/refs/chair.jpg
new file mode 100644
index 000000000..87264ab42
Binary files /dev/null and b/data/quality-bench/refs/chair.jpg differ
diff --git a/data/quality-bench/refs/sneaker.jpg b/data/quality-bench/refs/sneaker.jpg
new file mode 100644
index 000000000..b3bdb5236
Binary files /dev/null and b/data/quality-bench/refs/sneaker.jpg differ
diff --git a/data/quality-bench/refs/teapot.jpg b/data/quality-bench/refs/teapot.jpg
new file mode 100644
index 000000000..c27a8e3ba
Binary files /dev/null and b/data/quality-bench/refs/teapot.jpg differ
diff --git a/docs/forge.md b/docs/forge.md
index 56014ce2e..f84348c3f 100644
--- a/docs/forge.md
+++ b/docs/forge.md
@@ -119,6 +119,17 @@ console.log(job.glb_url); // downloadable, textured GLB
- **Photo input** accepts up to four views of one object; text-only engines are filtered out of the photo modes automatically.
- Rate limits are per client IP on the shared 3D generation buckets.
+## Measuring realism
+
+Any change that could affect output quality (a tier's sampler budget, a new
+lane, a prompt-enhancement change) should be checked against the realism
+benchmark before and after: `node scripts/quality-bench.mjs` runs a fixed
+23-prompt set through this real `/api/forge` path and scores the result with
+Vertex Gemini vision; `node scripts/quality-bench.mjs --compare=latest,previous`
+exits nonzero on a >1.0 mean-score drop. See
+[data/quality-bench/README.md](../data/quality-bench/README.md) and the
+dashboard at [/quality-bench](https://three.ws/quality-bench) (internal).
+
## Related
- [The Forge pipeline](./forge-pipeline.md) is the architecture deep dive: the engine grid, routing, failover, job lifecycle, workers, and payments, end to end. [How the Forge works](./how-forge-works.md) is the same story in plain language.
diff --git a/docs/okx-marketplace.md b/docs/okx-marketplace.md
index 57740311e..52d5fd924 100644
--- a/docs/okx-marketplace.md
+++ b/docs/okx-marketplace.md
@@ -9,7 +9,7 @@ the artifact. Our marketplace listing is agent **#2632 "three.ws 3D Studio"**.
> [x402 payments](./x402.md) · seller-side protocol spec: [`specs/okx-agent-payments.md`](../specs/okx-agent-payments.md)
The **single source of truth** for every service (names, 2-part OKX descriptions, prices,
-endpoints, input schemas) is [`api/_lib/okx-catalog.js`](../api/_lib/okx-catalog.js) — the
+endpoints, input schemas) is [`api/_lib/okx-catalog.js`](../api/_lib/okx-catalog.js), the
free catalog endpoint below serves it verbatim, so the docs, the endpoints, and the OKX
listing can never drift apart.
@@ -29,19 +29,19 @@ curl https://three.ws/api/okx/3d/health
---
-## Agent Identity Studio — `$1.50` per identity
+## Agent Identity Studio, `$1.50` per identity
**The flagship.** Turns an AI agent's brand brief into a complete 3D identity:
- a **square PFP** (1024 px PNG + 128 px preview) framed head-and-shoulders, sized for the
OKX.AI avatar slot and legible at marketplace thumbnail size;
-- a **full-body render set** — three distinct poses from the three.ws pose library, studio
+- a **full-body render set**, three distinct poses from the three.ws pose library, studio
lighting, consistent backdrop;
- the **rigged, animation-ready GLB** itself (humanoid skeleton + skin weights), usable in
three.ws scenes, games, and any glTF runtime;
- a live [three.ws viewer](https://three.ws/viewer) link and pose-studio link.
-Endpoint: `https://three.ws/api/okx/3d/identity-studio` — an A2MCP service (MCP Streamable
+Endpoint: `https://three.ws/api/okx/3d/identity-studio`, an A2MCP service (MCP Streamable
HTTP, JSON-RPC `tools/call`). Demo identities generated end-to-end by this pipeline:
[three.ws/agent-identities](https://three.ws/agent-identities).
@@ -73,7 +73,7 @@ Arguments:
| `agent_name` | yes | ≤80 chars, rendered into the identity brief |
| `brief` | yes | any language; >2000 chars is truncated and the response flags `brief_truncated` |
| `style_hints` | no | palette / materials / era / mood |
-| `reference_image_url` | no | public image guiding the look — validated **before** any charge |
+| `reference_image_url` | no | public image guiding the look, validated **before** any charge |
Success returns `{ job_id, status: "queued", poll_tool: "identity_status", eta_seconds }`.
@@ -95,24 +95,24 @@ the full-body set, `rigged_glb_url`, `mesh_glb_url`, `viewer_url`, and `pose_stu
### Payment semantics
-Each guarantee below is enforced in code — the request path is
+Each guarantee below is enforced in code, the request path is
`verify → dispatch → settle-on-success` ([`api/okx/3d/[service].js`](../api/okx/3d/%5Bservice%5D.js)),
-so an engine error is answered *before* settlement — and is covered by the endpoint's unit
+so an engine error is answered *before* settlement, and is covered by the endpoint's unit
tests.
-- **You pay only when the job is accepted.** Input validation — including fetching your
- `reference_image_url` — runs before settlement; an invalid brief or unreachable image
+- **You pay only when the job is accepted.** Input validation, including fetching your
+ `reference_image_url`, runs before settlement; an invalid brief or unreachable image
fails the call and **no payment settles**.
- **Failed stages retry free.** Generation and rigging each retry up to 3 total attempts on
transient upstream failures; renders re-run on the next poll. Only exhausted retries mark
the job `failed`, with the last actionable error in `last_error`.
-- **Status polling is free and unauthenticated** — job tokens are HMAC-signed, so they are
+- **Status polling is free and unauthenticated**, job tokens are HMAC-signed, so they are
the only capability needed to read a job.
- One payment ↔ one job: the payment proof is single-use across dispatch + settlement
(replay-guarded), and the settled amount always equals the advertised price.
> **Not yet demonstrated end to end.** The X Layer rail reports `settleable: true` in
-> production, but no *funded* call has settled on-chain against this endpoint yet — the payer
+> production, but no *funded* call has settled on-chain against this endpoint yet, the payer
> wallet is unfunded, so every real attempt returns `insufficient_balance`. Treat the bullets
> above as the implemented and unit-tested contract, not as a claim of an observed on-chain
> settlement. The first settled transaction hash will be recorded in
@@ -120,14 +120,14 @@ tests.
### Also on this endpoint (free)
-- `getting_started` — overview of the server, tools, prices, and links.
-- `GET https://three.ws/api/okx/3d/identity-studio` — SSE / discovery challenge.
+- `getting_started`, overview of the server, tools, prices, and links.
+- `GET https://three.ws/api/okx/3d/identity-studio`, SSE / discovery challenge.
---
## Decomposed 3D studio services
-Micro-priced, single-capability REST endpoints — plain JSON `POST`, one price each, all
+Micro-priced, single-capability REST endpoints, plain JSON `POST`, one price each, all
backed by the same engines the [MCP 3D studio](./mcp.md) runs (no separate pipeline).
`GET` on any of them returns its free descriptor (price, description, input schema).
@@ -144,13 +144,12 @@ backed by the same engines the [MCP 3D studio](./mcp.md) runs (no separate pipel
The buyer flow is the same for all of them: unpaid `POST` → 402 → sign
(`onchainos payment pay --payload '<402 body>'`) → replay with
-`PAYMENT-SIGNATURE`. Generation-grade services reply `{status:"queued", job_id, poll_url}`
-— polling `GET https://three.ws/api/forge?job=<job_id>` is free and unlimited; fast
+`PAYMENT-SIGNATURE`. Generation-grade services reply `{status:"queued", job_id, poll_url}`, polling `GET https://three.ws/api/forge?job=<job_id>` is free and unlimited; fast
services (`retarget`, `pose-seed`) reply `{status:"done", …}` inline. Settlement happens
**after** the engine accepts the job; invalid input, the avatar humanoid gate, or an
engine failure answers before settlement and never charges.
-### Text → 3D Model (GLB) — $0.01
+### Text → 3D Model (GLB), $0.01
Textured GLB from a text prompt on the fast draft lane (NVIDIA NIM TRELLIS).
@@ -160,7 +159,7 @@ curl -i -X POST https://three.ws/api/okx/3d/text-to-3d \
-d '{"prompt":"a brass steampunk owl, full body"}'
```
-### Text → 3D Model (Pro) — $0.30
+### Text → 3D Model (Pro), $0.30
An LLM art director refines the prompt, then a higher-quality lane generates the GLB.
`tier:"standard"` (default) or `tier:"high"` (max geometric detail + PBR textures).
@@ -171,7 +170,7 @@ curl -i -X POST https://three.ws/api/okx/3d/text-to-3d-pro \
-d '{"prompt":"ornate elven longsword","tier":"high"}'
```
-### Image → 3D Model — $0.30
+### Image → 3D Model, $0.30
Reconstructs a textured GLB from 1–4 public photos of one object.
@@ -181,7 +180,7 @@ curl -i -X POST https://three.ws/api/okx/3d/image-to-3d \
-d '{"image_urls":["https://example.com/owl-front.jpg","https://example.com/owl-side.jpg"]}'
```
-### GLB Auto-Rigging — $0.25
+### GLB Auto-Rigging, $0.25
Adds an animation-ready humanoid skeleton and skin weights to a static GLB (UniRig lane).
@@ -191,11 +190,11 @@ curl -i -X POST https://three.ws/api/okx/3d/rig \
-d '{"glb_url":"https://cdn.three.ws/models/knight.glb"}'
```
-### Text → Rigged Avatar — $0.50
+### Text → Rigged Avatar, $0.50
Mesh generation + auto-rig in one call. Obvious non-humanoid prompts are refused **before**
payment settles (`allow_non_humanoid: true` overrides). The paid response returns the mesh
-GLB immediately (`mesh_glb_url` + viewer link) plus the rig job to poll — a rig hiccup
+GLB immediately (`mesh_glb_url` + viewer link) plus the rig job to poll, a rig hiccup
never loses the paid generation.
```bash
@@ -204,9 +203,9 @@ curl -i -X POST https://three.ws/api/okx/3d/avatar \
-d '{"prompt":"a heroic knight in silver armor, full body"}'
```
-### Animation Retargeting — $0.10
+### Animation Retargeting, $0.10
-Retargets a curated clip (idle, walk, dance, …) onto any rigged humanoid GLB — returns the
+Retargets a curated clip (idle, walk, dance, …) onto any rigged humanoid GLB, returns the
retargeted AnimationClip JSON keyed to the rig's actual bones plus a bone-coverage report.
Completes inside the request. Clip names are free at
[`/animations/manifest.json`](https://three.ws/animations/manifest.json).
@@ -217,7 +216,7 @@ curl -i -X POST https://three.ws/api/okx/3d/retarget \
-d '{"model_url":"https://cdn.three.ws/models/knight-rigged.glb","animation":"idle"}'
```
-### Pose Seed — $0.02
+### Pose Seed, $0.02
Deterministic pose resolution: natural-language description → stable seed + full
joint-rotation map for humanoid rigs. Same prompt, same pose, every time. Completes inside
@@ -229,7 +228,7 @@ curl -i -X POST https://three.ws/api/okx/3d/pose-seed \
-d '{"prompt":"confident standing pose, arms crossed"}'
```
-### FBX Export (rig-preserving) — $0.10
+### FBX Export (rig-preserving), $0.10
GLB → FBX for Unity/Unreal; a rigged GLB keeps its skeleton, skin weights, and blendshapes.
Other formats: `obj`, `stl`, `ply`, `usdz`, `3mf`.
@@ -242,11 +241,11 @@ curl -i -X POST https://three.ws/api/okx/3d/fbx-export \
### Guarantees (all decomposed services)
-- **Pay only after the job is accepted** — verify runs before the engine, settle after it;
+- **Pay only after the job is accepted**, verify runs before the engine, settle after it;
failure replies state explicitly that the payment was not taken.
-- **Retried payments are safe** — the same payment + body replays the same response
+- **Retried payments are safe**, the same payment + body replays the same response
(idempotency cache); a payment proof is single-use across dispatch + settlement.
-- **One service, one price** — every rail advertised in a service's 402 quotes the same
+- **One service, one price**, every rail advertised in a service's 402 quotes the same
amount, derived from the catalog module.
---
diff --git a/multiplayer/src/quest-notify.js b/multiplayer/src/quest-notify.js
new file mode 100644
index 000000000..837b66add
--- /dev/null
+++ b/multiplayer/src/quest-notify.js
@@ -0,0 +1,63 @@
+// Quest-complete notification bridge — reports a finished /play mission or
+// co-op heist to the API so it lands in the player's bell inbox, not just the
+// anonymous site-wide ticker (publishFeedEvent in ./feed.js). Signs the same
+// short-lived world-service token persistence.js uses for world saves
+// (svc:'world'), verified server-side by api/_lib/world-service-auth.js —
+// only this trusted game process can post a notification for an account.
+//
+// Best-effort and fire-and-forget: a flaky API must never block or crash the
+// mission-complete flow, which already broadcasts to the players in real time.
+
+import crypto from 'node:crypto';
+
+const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
+const TOKEN_TTL_SEC = 120;
+
+function secret() {
+ return (
+ process.env.MULTIPLAYER_SHARED_SECRET ||
+ process.env.HOLDER_PASS_SECRET ||
+ 'dev-insecure-multiplayer-secret'
+ );
+}
+
+// Mirrors persistence.js's signServiceToken byte-for-byte.
+function signServiceToken() {
+ const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL_SEC;
+ const payload = Buffer.from(JSON.stringify({ svc: 'world', exp }), 'utf8').toString('base64url');
+ const sig = crypto.createHmac('sha256', secret()).update(payload).digest('base64url');
+ return `${payload}.${sig}`;
+}
+
+// Report a finished quest for the given account id (the verified presence-
+// ticket uid — NEVER the wallet/session account string). No-op if accountUid
+// is missing (an unauthenticated player still plays, just doesn't get an inbox
+// entry). Never throws.
+export async function reportQuestComplete({ accountUid, mission, gold, coop, coin }) {
+ if (!accountUid) return false;
+ let bodyString;
+ try {
+ bodyString = JSON.stringify({ accountUid, mission, gold, coop, coin });
+ } catch {
+ return false;
+ }
+ try {
+ const res = await fetch(`${API_BASE}/api/internal/quest-notify`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${signServiceToken()}`,
+ },
+ body: bodyString,
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!res.ok) {
+ console.warn(`[quest-notify] ${API_BASE}/api/internal/quest-notify → ${res.status}`);
+ return false;
+ }
+ return true;
+ } catch (err) {
+ console.warn('[quest-notify] failed to report quest completion:', err?.message || err);
+ return false;
+ }
+}
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 78a4cb97a..82a4f229d 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -76,6 +76,7 @@ import {
} from '../quests.js';
import { hydratePlayer, loadPlayer, savePlayer, flushPlayer } from '../playerStore.js';
import { publishFeedEvent } from '../feed.js';
+import { reportQuestComplete } from '../quest-notify.js';
// Platform entry gate (wallet-first sign-in + game-token balance). When a game
// token is pinned (PLAY_GATE_MINT, falling back to THREE_MINT) every join must
@@ -1474,6 +1475,12 @@ export class WalkRoom extends Room {
},
`${player?.account || client.sessionId}:${mission.id}`,
);
+ // Per-user bell notification, distinct from the anonymous ticker above —
+ // only fires for a player whose presence ticket verified a real account.
+ const accountUid = client.userData?.accountUid;
+ if (accountUid) {
+ reportQuestComplete({ accountUid, mission: mission.title, gold, coop, coin: this.state.coin || '' });
+ }
}
_handleRename(client, payload) {
diff --git a/package-lock.json b/package-lock.json
index 091ea50de..4b43cf021 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -190,6 +190,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@axe-core/playwright": "^4.12.1",
"@playwright/test": "^1.60.0",
"@x402/fetch": "^2.14.0",
"es-module-lexer": "^2.0.0",
@@ -2561,6 +2562,19 @@
"node": ">=18.0.0"
}
},
+ "node_modules/@axe-core/playwright": {
+ "version": "4.12.1",
+ "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.12.1.tgz",
+ "integrity": "sha512-rMd7xriptqKpP+w5265i4Hdkv2X5kbu6uiBi/B2I7uf3hieRBM3qDCfaKPtxfiYb2mKXfF+yLODJwIx+Jv1GDw==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "axe-core": "~4.12.1"
+ },
+ "peerDependencies": {
+ "playwright-core": ">= 1.0.0"
+ }
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -26190,6 +26204,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/axe-core": {
+ "version": "4.12.1",
+ "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.12.1.tgz",
+ "integrity": "sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/axios": {
"version": "1.18.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz",
@@ -52117,7 +52141,7 @@
},
"packages/agent-sniper": {
"name": "@three-ws/agent-sniper",
- "version": "0.1.5",
+ "version": "0.1.6",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
@@ -53345,7 +53369,7 @@
},
"walk-sdk": {
"name": "@three-ws/walk",
- "version": "0.2.1",
+ "version": "0.3.0",
"license": "SEE LICENSE IN LICENSE",
"engines": {
"node": ">=18"
diff --git a/package.json b/package.json
index 53da74cf5..92890ed91 100644
--- a/package.json
+++ b/package.json
@@ -205,6 +205,7 @@
"test:core": "vitest run --maxWorkers=1",
"test:gate": "node scripts/test-gate.mjs",
"test:e2e": "playwright test",
+ "audit:a11y": "playwright test tests/e2e/a11y-top-pages.spec.js",
"test:pages": "node scripts/test-pages.mjs",
"verify:ibm": "node scripts/verify-ibm-pages.mjs",
"verify:zauth": "node scripts/verify-zauth-runtime.mjs",
@@ -378,6 +379,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@axe-core/playwright": "^4.12.1",
"@playwright/test": "^1.60.0",
"@x402/fetch": "^2.14.0",
"es-module-lexer": "^2.0.0",
diff --git a/packages/threews-avatar-mcp/src/avatar-app.html b/packages/threews-avatar-mcp/src/avatar-app.html
index d13a2fd64..c9c440d4f 100644
--- a/packages/threews-avatar-mcp/src/avatar-app.html
+++ b/packages/threews-avatar-mcp/src/avatar-app.html
@@ -20,9 +20,11 @@
<model-viewer id="viewer"
camera-controls
auto-rotate
- shadow-intensity="1"
- exposure="1"
+ shadow-intensity="1.0"
+ shadow-softness="0.9"
+ exposure="1.5"
tone-mapping="aces"
+ environment-image="neutral"
camera-orbit="0deg 80deg 2m"
ar ar-modes="webxr scene-viewer quick-look"
alt="three.ws avatar"></model-viewer>
diff --git a/packages/viewer-presets/README.md b/packages/viewer-presets/README.md
index 4b6c44449..fd3c93823 100644
--- a/packages/viewer-presets/README.md
+++ b/packages/viewer-presets/README.md
@@ -97,10 +97,28 @@ so the plane fades in seamlessly.
Where the rig above tunes how a scene is *lit*, this module tunes how a model's
*surfaces* read. `MATERIAL_PRESETS` is a curated set of physically-plausible
-MeshStandardMaterial looks — `chrome`, `gold`, `copper`, `brushedSteel`,
-`gunmetal`, `matte`, `glossy`, `rubber`, `ceramic`, `glass`, `wood`, `stone`,
-`neon`, `holographic` — each a frozen parameter set (color, metalness, roughness,
-emissive, envMapIntensity, and transparency for glass).
+looks — `chrome`, `gold`, `copper`, `brushedSteel`, `gunmetal`, `matte`,
+`glossy`, `rubber`, `ceramic`, `glass`, `realGlass`, `wood`, `stone`, `fabric`,
+`skin`, `carPaint`, `neon`, `holographic` — each a frozen parameter set.
+
+Most presets are plain `MeshStandardMaterial` fields (color, metalness,
+roughness, emissive, envMapIntensity, transparency for the legacy `glass`).
+A few use **measured, physically-real** `MeshPhysicalMaterial`-only fields —
+`applyMaterialPreset` writes these when the target material has the field and
+silently skips them on a plain Standard material:
+
+| Preset | Physical fields | Real-world basis |
+|---|---|---|
+| `skin` | `sheen`, `sheenColor`, `sheenRoughness`, `specularIntensity` | roughness 0.45–0.6 (measured bare-skin range), 0 metalness, sheen approximates subsurface scattering, specular F0 below the 0.04 default (skin reflects ~2.8%) |
+| `carPaint` | `clearcoat`, `clearcoatRoughness` | KHR_materials_clearcoat — a near-mirror lacquer layer over a metallic base coat |
+| `realGlass` | `transmission`, `thickness`, `ior`, `attenuationColor`, `attenuationDistance` | KHR_materials_transmission — real refraction, not alpha blending; `ior: 1.45` is soda-lime glass |
+| `brushedSteel` | `anisotropy`, `anisotropyRotation` | KHR_materials_anisotropy — directional micro-groove scattering from brushing |
+| `fabric` | `sheen`, `sheenColor`, `sheenRoughness` | soft grazing-angle highlight woven cloth shows |
+
+`realGlass` and `glass` are deliberately both kept: `glass` is the cheap
+opacity-blend look (works on any renderer, any material type); `realGlass`
+needs a `MeshPhysicalMaterial` and the renderer's transmission pass but
+actually refracts what's behind it.
```js
import { applyMaterialPreset, materialVariants } from '@three-ws/viewer-presets/materials';
diff --git a/packages/viewer-presets/package.json b/packages/viewer-presets/package.json
index f08c730f0..1cbd09b1d 100644
--- a/packages/viewer-presets/package.json
+++ b/packages/viewer-presets/package.json
@@ -1,6 +1,6 @@
{
"name": "@three-ws/viewer-presets",
- "version": "0.3.0",
+ "version": "0.4.0",
"description": "Tuned visual presets for three.ws avatar viewers — light rigs, floor reflection, bloom, and PBR material presets (chrome/gold/glass/…) with seeded variants.",
"keywords": [
"three.ws",
diff --git a/packages/viewer-presets/src/index.d.ts b/packages/viewer-presets/src/index.d.ts
index a898710f8..ea5818185 100644
--- a/packages/viewer-presets/src/index.d.ts
+++ b/packages/viewer-presets/src/index.d.ts
@@ -68,6 +68,25 @@ export interface MaterialPreset {
envMapIntensity?: number;
transparent?: boolean;
opacity?: number;
+ /** 0..1, MeshPhysicalMaterial only (KHR_materials_clearcoat) */
+ clearcoat?: number;
+ clearcoatRoughness?: number;
+ /** 0..1, MeshPhysicalMaterial only (KHR_materials_transmission) */
+ transmission?: number;
+ thickness?: number;
+ /** index of refraction, 1..2.333 */
+ ior?: number;
+ attenuationColor?: string;
+ attenuationDistance?: number;
+ /** 0..1, MeshPhysicalMaterial only */
+ sheen?: number;
+ sheenColor?: string;
+ sheenRoughness?: number;
+ specularIntensity?: number;
+ specularColor?: string;
+ /** 0..1, MeshPhysicalMaterial only (KHR_materials_anisotropy) */
+ anisotropy?: number;
+ anisotropyRotation?: number;
}
export interface MaterialVariant {
diff --git a/packages/viewer-presets/src/materials.js b/packages/viewer-presets/src/materials.js
index 25ed93ffe..6d7d712ed 100644
--- a/packages/viewer-presets/src/materials.js
+++ b/packages/viewer-presets/src/materials.js
@@ -28,15 +28,39 @@ export const MATERIAL_PRESETS = Object.freeze({
chrome: freeze({ label: 'Chrome', color: '#c9ced4', metalness: 1, roughness: 0.05, envMapIntensity: 1.6 }),
gold: freeze({ label: 'Gold', color: '#ffcf5c', metalness: 1, roughness: 0.18, envMapIntensity: 1.4 }),
copper: freeze({ label: 'Copper', color: '#c4744a', metalness: 1, roughness: 0.28, envMapIntensity: 1.3 }),
- brushedSteel: freeze({ label: 'Brushed steel', color: '#b7bcc2', metalness: 0.95, roughness: 0.45, envMapIntensity: 1.1 }),
+ // Real brushed-metal anisotropy: the elongated micro-grooves from brushing
+ // scatter reflections along one axis only. anisotropy/anisotropyRotation
+ // are MeshPhysicalMaterial-only fields (three >=0.140) — assignPreset()
+ // sets them just like clearcoat/transmission, guarded so plain
+ // MeshStandardMaterial targets silently skip the field.
+ brushedSteel: freeze({ label: 'Brushed steel', color: '#b7bcc2', metalness: 0.95, roughness: 0.45, envMapIntensity: 1.1, anisotropy: 0.85, anisotropyRotation: 0 }),
gunmetal: freeze({ label: 'Gunmetal', color: '#3b4048', metalness: 0.9, roughness: 0.5, envMapIntensity: 1 }),
matte: freeze({ label: 'Matte plastic', color: '#8b90a0', metalness: 0, roughness: 0.9, envMapIntensity: 0.6 }),
glossy: freeze({ label: 'Glossy plastic', color: '#4f8bff', metalness: 0, roughness: 0.18, envMapIntensity: 1 }),
rubber: freeze({ label: 'Rubber', color: '#26282c', metalness: 0, roughness: 0.95, envMapIntensity: 0.4 }),
ceramic: freeze({ label: 'Glazed ceramic', color: '#f2efe9', metalness: 0, roughness: 0.28, envMapIntensity: 1 }),
+ // Legacy fake-glass look (opacity blend, no real refraction) — kept for
+ // callers/tests that expect the old cheap preset. `realGlass` below is the
+ // physically-correct KHR_materials_transmission version.
glass: freeze({ label: 'Glass', color: '#dff1ff', metalness: 0, roughness: 0.05, envMapIntensity: 1.5, transparent: true, opacity: 0.35 }),
+ // Real glass via transmission (light actually refracts through the
+ // surface rather than alpha-blending) + IOR 1.45 (soda-lime glass).
+ // Requires a MeshPhysicalMaterial + the renderer's transmission render
+ // target (three.js sets this up automatically once `transmission > 0`).
+ realGlass: freeze({ label: 'Glass (real)', color: '#f4fbff', metalness: 0, roughness: 0.03, envMapIntensity: 1.4, transmission: 1, thickness: 0.6, ior: 1.45, attenuationColor: '#eef8ff', attenuationDistance: 1.2 }),
wood: freeze({ label: 'Wood', color: '#8a5a34', metalness: 0, roughness: 0.72, envMapIntensity: 0.6 }),
stone: freeze({ label: 'Stone', color: '#8d8b86', metalness: 0, roughness: 0.85, envMapIntensity: 0.5 }),
+ fabric: freeze({ label: 'Fabric', color: '#6b6456', metalness: 0, roughness: 0.88, envMapIntensity: 0.4, sheen: 0.6, sheenColor: '#8a8272', sheenRoughness: 0.7 }),
+ // Real human skin: 0 metalness, 0.45-0.6 roughness (measured range for
+ // bare skin), a warm sheen layer approximating subsurface scattering, and
+ // a below-default specular F0 (skin reflects ~2.8% at normal incidence
+ // vs. the ~4% MeshStandardMaterial default) so highlights read soft.
+ skin: freeze({ label: 'Skin', color: '#e8b892', metalness: 0, roughness: 0.52, envMapIntensity: 0.7, sheen: 0.35, sheenColor: '#ffe0c2', sheenRoughness: 0.6, specularIntensity: 0.6 }),
+ // Automotive base-coat + clearcoat: KHR_materials_clearcoat. The base
+ // coat carries the color/metalness, the clearcoat is a separate, always
+ // non-metal, near-mirror lacquer layer on top — this is what makes car
+ // paint read as "wet" rather than flat metallic.
+ carPaint: freeze({ label: 'Car paint', color: '#b3101c', metalness: 0.6, roughness: 0.35, envMapIntensity: 1.2, clearcoat: 1, clearcoatRoughness: 0.03 }),
neon: freeze({ label: 'Neon', color: '#0b0b12', metalness: 0, roughness: 0.4, emissive: '#00ffd5', emissiveIntensity: 1.6, envMapIntensity: 0.8 }),
holographic: freeze({ label: 'Holographic', color: '#b6a8ff', metalness: 1, roughness: 0.12, emissive: '#2a1f5c', emissiveIntensity: 0.35, envMapIntensity: 1.8 }),
});
@@ -159,8 +183,16 @@ function isStandardLike(m) {
return !!m && 'metalness' in m && 'roughness' in m && !!m.color && typeof m.color.getHex === 'function';
}
+// Physical-only (MeshPhysicalMaterial) scalar/color fields a preset may set.
+// Absent on plain MeshStandardMaterial, so every read/write below is guarded
+// by an `in m` check — a preset with clearcoat/transmission/anisotropy still
+// applies its color/metalness/roughness cleanly to a Standard-only target,
+// it just quietly skips the physical-only layer.
+const PHYSICAL_SCALAR_FIELDS = ['clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'sheen', 'sheenRoughness', 'specularIntensity', 'anisotropy', 'anisotropyRotation', 'attenuationDistance'];
+const PHYSICAL_COLOR_FIELDS = ['sheenColor', 'attenuationColor', 'specularColor'];
+
function captureMaterial(m) {
- return {
+ const cap = {
m,
color: m.color.getHex(),
metalness: m.metalness,
@@ -171,6 +203,9 @@ function captureMaterial(m) {
transparent: m.transparent,
opacity: m.opacity,
};
+ for (const f of PHYSICAL_SCALAR_FIELDS) if (f in m) cap[f] = m[f];
+ for (const f of PHYSICAL_COLOR_FIELDS) if (m[f]) cap[f] = m[f].getHex();
+ return cap;
}
function restoreMaterial(cap) {
@@ -183,6 +218,8 @@ function restoreMaterial(cap) {
m.envMapIntensity = cap.envMapIntensity;
m.transparent = cap.transparent;
m.opacity = cap.opacity;
+ for (const f of PHYSICAL_SCALAR_FIELDS) if (f in cap) m[f] = cap[f];
+ for (const f of PHYSICAL_COLOR_FIELDS) if (f in cap && m[f]) m[f].setHex(cap[f]);
m.needsUpdate = true;
}
@@ -195,13 +232,29 @@ function assignPreset(THREE, m, cfg) {
m.emissiveIntensity = cfg.emissiveIntensity != null ? cfg.emissiveIntensity : cfg.emissive ? 1 : 0;
}
if (cfg.envMapIntensity != null && 'envMapIntensity' in m) m.envMapIntensity = cfg.envMapIntensity;
- if (cfg.transparent != null) {
+ for (const f of PHYSICAL_SCALAR_FIELDS) {
+ if (cfg[f] != null && f in m) m[f] = cfg[f];
+ }
+ for (const f of PHYSICAL_COLOR_FIELDS) {
+ if (cfg[f] != null && m[f]) m[f].set(cfg[f]);
+ }
+ if (cfg.transmission != null && 'transmission' in m) {
+ // Real transmission replaces alpha-blend transparency entirely — a
+ // realGlass preset must not also carry the old opacity-blend path.
+ m.transparent = false;
+ m.opacity = 1;
+ } else if (cfg.transparent != null) {
m.transparent = !!cfg.transparent;
if (cfg.opacity != null) m.opacity = cfg.opacity;
} else {
- // Opaque preset: undo any prior transparency so switching glass→chrome is clean.
+ // Opaque preset: undo any prior transparency/transmission so switching
+ // glass→chrome is clean.
m.transparent = false;
m.opacity = 1;
+ if ('transmission' in m) m.transmission = 0;
+ if ('clearcoat' in m && cfg.clearcoat == null) m.clearcoat = 0;
+ if ('anisotropy' in m && cfg.anisotropy == null) m.anisotropy = 0;
+ if ('sheen' in m && cfg.sheen == null) m.sheen = 0;
}
m.needsUpdate = true;
}
@@ -302,4 +355,18 @@ function freeze(o) {
* @property {number} [envMapIntensity]
* @property {boolean} [transparent]
* @property {number} [opacity] 0..1, only with transparent
+ * @property {number} [clearcoat] 0..1, MeshPhysicalMaterial only (KHR_materials_clearcoat)
+ * @property {number} [clearcoatRoughness] 0..1
+ * @property {number} [transmission] 0..1, MeshPhysicalMaterial only (KHR_materials_transmission)
+ * @property {number} [thickness] world units, paired with transmission
+ * @property {number} [ior] 1..2.333, index of refraction
+ * @property {string} [attenuationColor] hex, paired with transmission
+ * @property {number} [attenuationDistance] world units
+ * @property {number} [sheen] 0..1, MeshPhysicalMaterial only
+ * @property {string} [sheenColor] hex
+ * @property {number} [sheenRoughness] 0..1
+ * @property {number} [specularIntensity] 0..1, MeshPhysicalMaterial only
+ * @property {string} [specularColor] hex
+ * @property {number} [anisotropy] 0..1, MeshPhysicalMaterial only (KHR_materials_anisotropy)
+ * @property {number} [anisotropyRotation] radians
*/
diff --git a/packages/viewer-presets/test/presets.test.js b/packages/viewer-presets/test/presets.test.js
index 4388b348d..c82eda7bd 100644
--- a/packages/viewer-presets/test/presets.test.js
+++ b/packages/viewer-presets/test/presets.test.js
@@ -51,6 +51,29 @@ function fakeRoot(materials) {
return { traverse: (fn) => nodes.forEach(fn) };
}
+// A MeshPhysicalMaterial-shaped fake — adds the clearcoat/transmission/sheen/
+// anisotropy fields real MeshStandardMaterial lacks, so presets that use them
+// (skin, carPaint, realGlass, brushedSteel) have something to write into.
+function fakePhysicalMaterial() {
+ return {
+ ...fakeStandardMaterial(),
+ clearcoat: 0,
+ clearcoatRoughness: 0,
+ transmission: 0,
+ thickness: 0,
+ ior: 1.5,
+ attenuationColor: new FakeColor(0xffffff),
+ attenuationDistance: Infinity,
+ sheen: 0,
+ sheenColor: new FakeColor(0x000000),
+ sheenRoughness: 1,
+ specularIntensity: 1,
+ specularColor: new FakeColor(0xffffff),
+ anisotropy: 0,
+ anisotropyRotation: 0,
+ };
+}
+
test('LIGHT_CONFIG preserves visage angles', () => {
assert.equal(LIGHT_CONFIG.fillLightAngle, Math.PI / 3);
assert.equal(LIGHT_CONFIG.backLightAngle, Math.PI / 8);
@@ -260,3 +283,60 @@ test('materialVariants clamps count into [1,64]', () => {
assert.equal(materialVariants('wood', { count: 0 }).length, 1);
assert.equal(materialVariants('wood', { count: 999 }).length, 64);
});
+
+// ── measured-value physical presets ──────────────────────────────────────────
+
+test('MATERIAL_PRESETS exposes the measured-value physical presets', () => {
+ assert.equal(MATERIAL_PRESETS.skin.metalness, 0);
+ assert.ok(MATERIAL_PRESETS.skin.roughness >= 0.45 && MATERIAL_PRESETS.skin.roughness <= 0.6);
+ assert.equal(MATERIAL_PRESETS.carPaint.clearcoat, 1);
+ assert.equal(MATERIAL_PRESETS.realGlass.transmission, 1);
+ assert.equal(MATERIAL_PRESETS.realGlass.ior, 1.45);
+ assert.ok(MATERIAL_PRESETS.brushedSteel.anisotropy > 0);
+});
+
+test('applyMaterialPreset writes clearcoat onto a MeshPhysicalMaterial target', () => {
+ const mat = fakePhysicalMaterial();
+ applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'carPaint');
+ assert.equal(mat.clearcoat, 1);
+ assert.equal(mat.clearcoatRoughness, MATERIAL_PRESETS.carPaint.clearcoatRoughness);
+ assert.equal(mat.metalness, MATERIAL_PRESETS.carPaint.metalness);
+});
+
+test('applyMaterialPreset writes transmission onto a MeshPhysicalMaterial target and clears legacy transparency', () => {
+ const mat = fakePhysicalMaterial();
+ applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'realGlass');
+ assert.equal(mat.transmission, 1);
+ assert.equal(mat.ior, 1.45);
+ assert.equal(mat.transparent, false, 'transmission replaces alpha-blend, not stacks with it');
+});
+
+test('applyMaterialPreset writes sheen onto skin and anisotropy onto brushedSteel', () => {
+ const skinMat = fakePhysicalMaterial();
+ applyMaterialPreset(FakeTHREE, fakeRoot([skinMat]), 'skin');
+ assert.equal(skinMat.sheen, MATERIAL_PRESETS.skin.sheen);
+ assert.equal(skinMat.specularIntensity, MATERIAL_PRESETS.skin.specularIntensity);
+
+ const steelMat = fakePhysicalMaterial();
+ applyMaterialPreset(FakeTHREE, fakeRoot([steelMat]), 'brushedSteel');
+ assert.equal(steelMat.anisotropy, MATERIAL_PRESETS.brushedSteel.anisotropy);
+});
+
+test('applyMaterialPreset physical fields are a no-op on a plain Standard-shaped material', () => {
+ const mat = fakeStandardMaterial(); // no clearcoat/transmission/sheen/anisotropy fields
+ const handle = applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'carPaint');
+ assert.equal(handle.count, 1, 'still applies the standard-material fields');
+ assert.equal(mat.metalness, MATERIAL_PRESETS.carPaint.metalness);
+ assert.equal('clearcoat' in mat, false);
+});
+
+test('applyMaterialPreset restore() reverts physical fields exactly', () => {
+ const mat = fakePhysicalMaterial();
+ const before = { clearcoat: mat.clearcoat, transmission: mat.transmission, sheen: mat.sheen };
+ const handle = applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'realGlass');
+ assert.notEqual(mat.transmission, before.transmission);
+ handle.restore();
+ assert.equal(mat.clearcoat, before.clearcoat);
+ assert.equal(mat.transmission, before.transmission);
+ assert.equal(mat.sheen, before.sheen);
+});
diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.js
index 1eacec267..3c0e2ece2 100644
--- a/page-agent-sdk/src/stage.js
+++ b/page-agent-sdk/src/stage.js
@@ -21,6 +21,7 @@ import {
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { buildMorphMap } from './lipsync.js';
+import { DEFAULT_ASSET_BASE } from './catalog.js';
// Catalog rigs served by three.ws (e.g. cz.glb) carry EXT_meshopt_compression;
// GLTFLoader throws "setMeshoptDecoder must be called" without a decoder.
@@ -33,6 +34,24 @@ function getMeshoptDecoder() {
return _meshoptPromise;
}
+// Real photographic IBL, not just the procedural RoomEnvironment. <page-agent>
+// embeds on arbitrary third-party pages, so a root-relative path would
+// resolve against the HOST page's origin and 404 — fetch from three.ws's own
+// absolute origin instead (same origin catalog.js already uses for rig
+// assets). Lazy + memoized: the decoded texture is shared across every stage
+// on the page; each still derives its own PMREM env map, so per-stage
+// disposal never affects a sibling.
+const HDRI_ORIGIN = new URL(DEFAULT_ASSET_BASE).origin;
+let _hdriPromise = null;
+function getHdriTexture() {
+ if (!_hdriPromise) {
+ _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
+ new RGBELoader().loadAsync(`${HDRI_ORIGIN}/hdri/studio.hdr`),
+ );
+ }
+ return _hdriPromise;
+}
+
const FRAMING = {
// [vertical fraction of model height to center on, distance multiplier]
bust: { center: 0.86, dist: 0.62, fov: 28 },
@@ -74,9 +93,27 @@ export class AvatarStage {
this.renderer.toneMappingExposure = 1.05;
const pmrem = new PMREMGenerator(this.renderer);
+ pmrem.compileEquirectangularShader();
+ // Paint immediately with the procedural room so the agent is never
+ // unlit while the real HDRI streams in over the network — then swap to
+ // the photographic environment once it lands.
this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
this.scene.environment = this._envTex;
- pmrem.dispose();
+ getHdriTexture()
+ .then((hdrTexture) => {
+ if (!this.renderer || !this.scene) { pmrem.dispose(); return; } // torn down before it landed
+ const prevEnv = this._envTex;
+ this._envTex = pmrem.fromEquirectangular(hdrTexture).texture;
+ this.scene.environment = this._envTex;
+ prevEnv?.dispose();
+ pmrem.dispose();
+ })
+ .catch(() => {
+ // Real HDRI unreachable from this embed's host (offline, CSP,
+ // blocked cross-origin request) — the procedural room stays as a
+ // correct, if less photographic, fallback.
+ pmrem.dispose();
+ });
this.scene.add(new AmbientLight(0xffffff, 0.6));
const key = new DirectionalLight(0xffffff, 1.4);
diff --git a/pages/forge.html b/pages/forge.html
index 66972c87b..e4cb39504 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -3069,6 +3069,9 @@
<button class="chip" type="button" data-i18n="forge.a_glazed_ceramic_teapot_2">a glazed ceramic teapot</button>
<button class="chip" type="button" data-i18n="forge.a_sci_fi_combat_helmet_brushed_metal_2">a sci-fi combat helmet, brushed metal</button>
<button class="chip" type="button" data-i18n="forge.a_low_poly_red_fox_sitting_2">a low-poly red fox, sitting</button>
+ <button class="chip" type="button" data-i18n="forge.a_worn_leather_messenger_bag">a worn leather messenger bag, brass buckles</button>
+ <button class="chip" type="button" data-i18n="forge.a_crystal_dragon_figurine">a crystal dragon figurine, catching the light</button>
+ <button class="chip" type="button" data-i18n="forge.a_chrome_toaster">a chrome toaster, mid-century diner style</button>
</div>
<p class="forge-empty-hint" data-i18n="forge.or_click_a_starter_it_generates_immediately">Or click a starter: it generates immediately.</p>
</div>
@@ -3308,6 +3311,35 @@
</svg>
View in AR
</button>
+ <a
+ class="btn btn-ghost"
+ id="forge-irl-btn"
+ href="/irl"
+ title="Place this model in your real room, anchored and shareable (IRL)"
+ data-i18n-attr="title:forge.place_this_model_in_your_real_title">
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M12 2v4" />
+ <path d="M12 18v4" />
+ <path d="M4.93 4.93l2.83 2.83" />
+ <path d="M16.24 16.24l2.83 2.83" />
+ <path d="M2 12h4" />
+ <path d="M18 12h4" />
+ <path d="M4.93 19.07l2.83-2.83" />
+ <path d="M16.24 7.76l2.83-2.83" />
+ <circle cx="12" cy="12" r="3" />
+ </svg>
+ Place IRL
+ </a>
<button
class="btn btn-refine is-hidden"
type="button"
@@ -3501,6 +3533,9 @@
<script type="module" src="/src/forge-prompt-studio.js"></script>
<script type="module" src="/src/forge-enhance.js"></script>
<script type="module" src="/src/forge-refine.js"></script>
+ <script type="module" src="/src/forge-rig.js"></script>
+ <script type="module" src="/src/forge-materials.js"></script>
+ <script type="module" src="/src/forge-conversational-refine.js"></script>
<script type="module" src="/src/forge-stylize.js"></script>
<script type="module" src="/src/forge-optimize.js"></script>
<script type="module" src="/src/forge-gameready.js"></script>
diff --git a/pages/notifications.html b/pages/notifications.html
new file mode 100644
index 000000000..adcdc2883
--- /dev/null
+++ b/pages/notifications.html
@@ -0,0 +1,169 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Notifications · three.ws</title>
+ <meta name="description" content="Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place." />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ --bg: #0d0d0d;
+ --bg-2: #141414;
+ --card: #181818;
+ --line: rgba(255,255,255,0.07);
+ --line-2: rgba(255,255,255,0.12);
+ --text: #e7e9ee;
+ --muted: rgba(231,233,238,0.55);
+ --dim: rgba(231,233,238,0.35);
+ --blue: #3b82f6;
+ --radius: 12px;
+ --skeleton-base: rgba(255,255,255,0.04);
+ --skeleton-sheen: rgba(255,255,255,0.08);
+ }
+ [data-theme="light"] {
+ --bg: #f5f5f5;
+ --bg-2: #ffffff;
+ --card: #ffffff;
+ --line: rgba(0,0,0,0.07);
+ --line-2: rgba(0,0,0,0.12);
+ --text: #111;
+ --muted: rgba(0,0,0,0.55);
+ --dim: rgba(0,0,0,0.35);
+ --skeleton-base: rgba(0,0,0,0.04);
+ --skeleton-sheen: rgba(0,0,0,0.08);
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;text-decoration:none;}
+ .page-shell{max-width:720px;margin:0 auto;padding:0 20px 100px;}
+ .page-hero{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;padding:48px 0 24px;flex-wrap:wrap;}
+ .page-hero h1{font-size:28px;font-weight:700;letter-spacing:-0.02em;}
+ .page-hero p{color:var(--muted);margin-top:8px;font-size:14px;}
+ .page-actions{display:flex;align-items:center;gap:8px;}
+ .n-btn{display:inline-flex;align-items:center;gap:6px;font-size:13px;font-weight:500;padding:8px 14px;border-radius:8px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s;font-family:inherit;text-decoration:none;}
+ .n-btn:hover{border-color:rgba(255,255,255,0.3);}
+ [data-theme="light"] .n-btn:hover{border-color:rgba(0,0,0,0.3);}
+ .n-btn:disabled{opacity:.45;cursor:default;}
+ .n-btn:focus-visible{outline:2px solid var(--blue);outline-offset:1px;}
+ /* Filter tabs */
+ .n-tabs{display:flex;gap:4px;border-bottom:1px solid var(--line-2);margin-bottom:8px;overflow-x:auto;}
+ .n-tab{padding:10px 16px;font-size:13px;font-weight:500;color:var(--muted);cursor:pointer;border-bottom:2px solid transparent;transition:color .15s,border-color .15s;background:none;border-top:none;border-left:none;border-right:none;white-space:nowrap;font-family:inherit;}
+ .n-tab:hover{color:var(--text);}
+ .n-tab.active{color:var(--text);border-bottom-color:var(--blue);}
+ /* List */
+ .n-list{display:flex;flex-direction:column;}
+ .n-row{display:flex;align-items:flex-start;gap:14px;padding:16px 4px;border-bottom:1px solid var(--line);cursor:pointer;transition:background .12s;border-radius:8px;}
+ .n-row:hover{background:var(--bg-2);}
+ .n-row:focus-visible{outline:2px solid var(--blue);outline-offset:-2px;}
+ .n-row.is-unread{background:rgba(59,130,246,0.05);}
+ .n-row.is-unread:hover{background:rgba(59,130,246,0.09);}
+ .n-icon{font-size:20px;line-height:1;margin-top:2px;flex-shrink:0;width:24px;text-align:center;}
+ .n-body{flex:1;min-width:0;}
+ .n-msg{font-size:14px;color:var(--text);line-height:1.5;word-break:break-word;}
+ .n-row.is-unread .n-msg{font-weight:600;}
+ .n-time{font-size:12px;color:var(--dim);margin-top:3px;}
+ .n-dot{width:8px;height:8px;border-radius:50%;background:var(--blue);flex-shrink:0;margin-top:6px;}
+ .n-del{background:none;border:0;color:var(--dim);cursor:pointer;font-size:16px;padding:4px 6px;border-radius:6px;flex-shrink:0;opacity:0;transition:opacity .12s,color .12s,background .12s;}
+ .n-row:hover .n-del{opacity:1;}
+ .n-del:hover{color:#ef4444;background:rgba(239,68,68,0.1);}
+ .n-del:focus-visible{opacity:1;outline:2px solid var(--blue);}
+ /* Empty / loading / error */
+ .n-empty{text-align:center;padding:100px 20px;color:var(--muted);}
+ .n-empty-icon{font-size:36px;margin-bottom:14px;}
+ .n-empty h3{font-size:18px;font-weight:600;color:var(--text);margin-bottom:8px;}
+ .n-empty p{font-size:14px;line-height:1.5;max-width:360px;margin:0 auto;}
+ .n-auth-wall{text-align:center;padding:120px 20px;}
+ .n-auth-wall h2{font-size:22px;font-weight:700;margin-bottom:12px;}
+ .n-auth-wall p{color:var(--muted);font-size:14px;margin-bottom:24px;}
+ .n-error{background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.25);border-radius:10px;padding:16px 20px;color:#ef4444;font-size:13px;margin-bottom:20px;}
+ .skeleton{background:var(--skeleton-base);background-image:linear-gradient(90deg,var(--skeleton-base) 0%,var(--skeleton-sheen) 50%,var(--skeleton-base) 100%);background-size:200% 100%;border-radius:6px;animation:shimmer 1.4s ease-in-out infinite;}
+ @keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}
+ .n-skel-row{display:flex;gap:14px;padding:16px 4px;}
+ .n-skel-row .skeleton:first-child{width:24px;height:24px;border-radius:50%;}
+ .n-skel-body{flex:1;display:flex;flex-direction:column;gap:8px;}
+ .n-load-more{display:flex;justify-content:center;padding:24px 0;}
+ @media(max-width:480px){
+ .page-hero{padding:32px 0 20px;}
+ .page-hero h1{font-size:24px;}
+ }
+ </style>
+
+ <link rel="canonical" href="https://three.ws/notifications">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Notifications · three.ws">
+ <meta property="og:description" content="Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place.">
+ <meta property="og:url" content="https://three.ws/notifications">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Notifications&amp;d=Every+payment%2C+sale%2C+remix%2C+follow%2C+quest%2C+and+royalty+notification+on+three.ws.&amp;p=%2Fnotifications">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Notifications · three.ws">
+ <meta name="twitter:description" content="Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Notifications&amp;d=Every+payment%2C+sale%2C+remix%2C+follow%2C+quest%2C+and+royalty+notification+on+three.ws.&amp;p=%2Fnotifications">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Notifications","description":"Every payment, sale, remix, follow, quest, and royalty notification on three.ws.","url":"https://three.ws/notifications","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Notifications — three.ws">
+ <meta name="twitter:site" content="@trythreews">
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="page-shell">
+ <div class="page-hero">
+ <div>
+ <h1>Notifications</h1>
+ <p>Everything that happened while you were away.</p>
+ </div>
+ <div class="page-actions">
+ <a href="/dashboard/settings" class="n-btn" aria-label="Notification preferences">⚙ Preferences</a>
+ <button type="button" id="n-mark-all" class="n-btn">Mark all read</button>
+ </div>
+ </div>
+
+ <div id="n-auth-wall" class="n-auth-wall" hidden>
+ <h2>Sign in to see your notifications</h2>
+ <p>Track payments, sales, follows, remixes, quests, and royalties across three.ws.</p>
+ <a href="/login?next=/notifications" class="n-btn">Sign in</a>
+ </div>
+
+ <div id="n-error" class="n-error" hidden></div>
+
+ <div id="n-main" hidden>
+ <div class="n-tabs" id="n-tabs" role="tablist">
+ <button class="n-tab active" role="tab" aria-selected="true" data-type="">All</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="sales">Sales & earnings</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="purchases">Purchases</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="social">Social</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="irl">In person</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="alerts">Market alerts</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="creations">Creations</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="account">Account</button>
+ </div>
+ <div id="n-list" class="n-list"></div>
+ <div id="n-load-more" class="n-load-more" hidden>
+ <button type="button" id="n-load-more-btn" class="n-btn">Load more</button>
+ </div>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/notifications-page.js"></script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/quality-bench.html b/pages/quality-bench.html
new file mode 100644
index 000000000..5a40d84c8
--- /dev/null
+++ b/pages/quality-bench.html
@@ -0,0 +1,208 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Realism Quality Bench · three.ws</title>
+ <meta name="robots" content="noindex, nofollow" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ body { background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }
+ .qb-wrap { max-width: 1200px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3rem) 1.25rem 5rem; }
+ .qb-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem; flex-wrap: wrap; gap: 1rem; }
+ .qb-title { font-size: clamp(1.4rem, 3vw, 1.85rem); font-weight: 800; letter-spacing: -0.025em; margin: 0; }
+ .qb-sub { color: rgba(255,255,255,0.45); font-size: 13.5px; margin: 0 0 2rem; }
+ .qb-controls { display: flex; gap: 0.75rem; margin-bottom: 1.5rem; flex-wrap: wrap; align-items: center; }
+ .qb-controls select { font: inherit; font-size: 13px; padding: 8px 12px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #e2e8f0; }
+
+ .qb-empty { padding: 3rem; text-align: center; border-radius: 14px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); color: rgba(255,255,255,0.5); }
+ .qb-empty code { background: rgba(255,255,255,0.08); padding: 2px 6px; border-radius: 4px; }
+
+ .qb-runs { display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 2.5rem; }
+ .qb-run-row { display: grid; grid-template-columns: 1fr auto auto auto; gap: 1rem; align-items: center; padding: 0.75rem 1rem; border-radius: 10px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); font-size: 13px; }
+ .qb-run-row.selected { border-color: rgba(124,92,255,0.5); background: rgba(124,92,255,0.08); }
+ .qb-run-row button { font: inherit; font-size: 12px; padding: 5px 10px; border-radius: 7px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #e2e8f0; cursor: pointer; }
+ .qb-run-mean { font-weight: 700; font-variant-numeric: tabular-nums; }
+ .qb-run-mean.good { color: #2fbf71; }
+ .qb-run-mean.warn { color: #f0a93b; }
+ .qb-run-mean.bad { color: #f87171; }
+
+ .qb-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.35); margin: 0 0 0.85rem; }
+
+ .qb-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0.75rem; margin-bottom: 2.5rem; }
+ .qb-cell { padding: 1rem; border-radius: 12px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); }
+ .qb-cell-label { font-size: 12px; color: rgba(255,255,255,0.5); margin-bottom: 0.4rem; }
+ .qb-cell-score { font-size: 1.5rem; font-weight: 800; font-variant-numeric: tabular-nums; }
+
+ .qb-worst { display: flex; flex-direction: column; gap: 0.6rem; margin-bottom: 2.5rem; }
+ .qb-worst-item { display: grid; grid-template-columns: auto 1fr auto; gap: 1rem; align-items: center; padding: 0.85rem 1.1rem; border-radius: 10px; background: rgba(248,113,113,0.05); border: 1px solid rgba(248,113,113,0.15); }
+ .qb-worst-id { font-size: 12px; font-weight: 700; color: rgba(255,255,255,0.6); }
+ .qb-worst-critique { font-size: 12.5px; color: rgba(255,255,255,0.55); }
+ .qb-worst-score { font-weight: 800; color: #f87171; }
+
+ .qb-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+ .qb-table th, .qb-table td { text-align: left; padding: 0.5rem 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.06); }
+ .qb-table th { color: rgba(255,255,255,0.4); font-weight: 600; text-transform: uppercase; font-size: 10.5px; letter-spacing: 0.06em; }
+ .qb-table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid rgba(255,255,255,0.07); }
+ </style>
+</head>
+<body>
+ <div class="qb-wrap">
+ <div class="qb-header">
+ <h1 class="qb-title">Realism Quality Bench</h1>
+ </div>
+ <p class="qb-sub">Fixed 23-prompt benchmark, judged by Vertex Gemini vision on photorealism / geometry / texture / prompt-adherence. Internal tooling — not a public surface.</p>
+
+ <div id="qb-content">
+ <div class="qb-empty">Loading run history…</div>
+ </div>
+ </div>
+
+ <script src="/nav.js"></script>
+ <script type="module">
+ const el = document.getElementById('qb-content');
+ const DIMS = ['photorealism', 'geometryIntegrity', 'textureFidelity', 'promptAdherence'];
+
+ function scoreClass(mean) {
+ if (mean == null) return '';
+ if (mean >= 7.5) return 'good';
+ if (mean >= 5.5) return 'warn';
+ return 'bad';
+ }
+
+ function fmt(n) {
+ return typeof n === 'number' ? n.toFixed(2) : '—';
+ }
+
+ function renderEmpty(index) {
+ el.innerHTML = `<div class="qb-empty">No runs recorded yet. Kick one off with:<br/><br/><code>node scripts/quality-bench.mjs --tier=standard,high</code></div>`;
+ }
+
+ function meanByGroup(run, keyFn) {
+ const map = new Map();
+ for (const r of run.results || []) {
+ const key = keyFn(r);
+ if (!map.has(key)) map.set(key, []);
+ if (typeof r.meanScore === 'number') map.get(key).push(r.meanScore);
+ }
+ const out = {};
+ for (const [key, scores] of map) {
+ out[key] = scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : null;
+ }
+ return out;
+ }
+
+ function worstN(run, n) {
+ const flat = [];
+ for (const r of run.results || []) {
+ for (const v of r.views || []) {
+ if (!v.avg) continue;
+ flat.push({ promptId: r.promptId, lane: r.lane, tier: r.tier, view: v.view, mean: v.avg.mean, critique: v.scores?.[0]?.critique || '' });
+ }
+ }
+ flat.sort((a, b) => a.mean - b.mean);
+ return flat.slice(0, n);
+ }
+
+ function renderRun(index, selectedFile, run) {
+ const byLane = meanByGroup(run, (r) => r.lane);
+ const byTier = meanByGroup(run, (r) => r.tier);
+ const bySubject = meanByGroup(run, (r) => r.subjectClass);
+ const worst = worstN(run, 5);
+
+ const runsHtml = index.map((s) => {
+ const cls = scoreClass(s.meanScore);
+ const sel = s.file === selectedFile ? ' selected' : '';
+ return `<div class="qb-run-row${sel}">
+ <div>${s.runId} <span style="color:rgba(255,255,255,0.35)">(${s.lanes?.length || 0} lanes, ${s.tiers?.join('/') || ''})</span></div>
+ <div>${s.resultCount} results</div>
+ <div class="qb-run-mean ${scoreClass(s.meanScore)}">${fmt(s.meanScore)}</div>
+ <button data-file="${s.file}">View</button>
+ </div>`;
+ }).join('');
+
+ const cellsHtml = (label, map) => Object.entries(map).map(([k, v]) => `
+ <div class="qb-cell">
+ <div class="qb-cell-label">${label}: ${k}</div>
+ <div class="qb-cell-score ${scoreClass(v)}">${fmt(v)}</div>
+ </div>`).join('');
+
+ const worstHtml = worst.map((w) => `
+ <div class="qb-worst-item">
+ <div class="qb-worst-id">${w.promptId} · ${w.lane}/${w.tier} · ${w.view}</div>
+ <div class="qb-worst-critique">${w.critique.replace(/</g, '&lt;')}</div>
+ <div class="qb-worst-score">${fmt(w.mean)}</div>
+ </div>`).join('') || '<div class="qb-empty">No scored views in this run.</div>';
+
+ const rows = (run.results || []).map((r) => `
+ <tr>
+ <td>${r.promptId}</td>
+ <td>${r.subjectClass}</td>
+ <td>${r.lane}</td>
+ <td>${r.tier}</td>
+ <td>${r.status}</td>
+ <td>${fmt(r.meanScore)}</td>
+ </tr>`).join('');
+
+ el.innerHTML = `
+ <div class="qb-section-title">Run history</div>
+ <div class="qb-runs">${runsHtml}</div>
+
+ <div class="qb-section-title">By lane — run ${run.runId}</div>
+ <div class="qb-grid">${cellsHtml('lane', byLane)}</div>
+
+ <div class="qb-section-title">By tier</div>
+ <div class="qb-grid">${cellsHtml('tier', byTier)}</div>
+
+ <div class="qb-section-title">By subject class</div>
+ <div class="qb-grid">${cellsHtml('subject', bySubject)}</div>
+
+ <div class="qb-section-title">Worst 5 (lowest-scoring views)</div>
+ <div class="qb-worst">${worstHtml}</div>
+
+ <div class="qb-section-title">All results</div>
+ <div class="qb-table-wrap">
+ <table class="qb-table">
+ <thead><tr><th>Prompt</th><th>Subject</th><th>Lane</th><th>Tier</th><th>Status</th><th>Mean</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ `;
+
+ el.querySelectorAll('.qb-run-row button').forEach((btn) => {
+ btn.addEventListener('click', () => loadRun(index, btn.dataset.file));
+ });
+ }
+
+ async function loadRun(index, file) {
+ el.innerHTML = '<div class="qb-empty">Loading run…</div>';
+ const res = await fetch(`/api/quality-bench?run=${encodeURIComponent(file)}`);
+ if (!res.ok) {
+ el.innerHTML = `<div class="qb-empty">Failed to load run "${file}".</div>`;
+ return;
+ }
+ const run = await res.json();
+ renderRun(index, file, run);
+ }
+
+ async function boot() {
+ try {
+ const res = await fetch('/api/quality-bench');
+ if (!res.ok) throw new Error(`status ${res.status}`);
+ const { runs } = await res.json();
+ if (!runs.length) return renderEmpty();
+ await loadRun(runs, runs[runs.length - 1].file);
+ } catch (err) {
+ el.innerHTML = `<div class="qb-empty">Could not load quality-bench data: ${String(err.message || err).replace(/</g, '&lt;')}</div>`;
+ }
+ }
+
+ boot();
+ </script>
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/prompts/okx-ai/00-CONTEXT.md b/prompts/okx-ai/00-CONTEXT.md
index 90cfd8bda..b363dc8a3 100644
--- a/prompts/okx-ai/00-CONTEXT.md
+++ b/prompts/okx-ai/00-CONTEXT.md
@@ -1,4 +1,4 @@
-# OKX.AI Launch — Shared Context (read this FIRST, every prompt requires it)
+# OKX.AI Launch: Shared Context (read this FIRST, every prompt requires it)
You are working on getting **three.ws listed and selling on OKX.AI**, OKX's on-chain agent
marketplace (agents hire agents; payments settle on X Layer). This file is the single source
@@ -29,15 +29,14 @@ of truth for facts every work order depends on. Do not re-derive these; do not c
## Our existing code (the thing being fixed)
-- **A2MCP endpoint**: [api/mcp-3d.js](../../api/mcp-3d.js) — MCP server for the 3D studio, prices
+- **A2MCP endpoint**: [api/mcp-3d.js](../../api/mcp-3d.js), MCP server for the 3D studio, prices
tool batches via `priceBatch` + `studioX402Amount` ([api/_mcp3d/pricing.js](../../api/_mcp3d/pricing.js)).
-- **402 challenge builder**: `paymentRequirements()` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
- — emits x402 v2 `accepts` entries for **Solana / Base / BSC / Arbitrum via Coinbase/PayAI/CDP
+- **402 challenge builder**: `paymentRequirements()` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js), emits x402 v2 `accepts` entries for **Solana / Base / BSC / Arbitrum via Coinbase/PayAI/CDP
facilitators. There is NO X Layer entry and NO OKX facilitator entry. This is the exact
reason we were rejected.**
- Payment helpers: [api/_mcp/payments.js](../../api/_mcp/payments.js) (`send402`, `sendX402Error`),
settlement via `settlePayment` in x402-spec.js.
-- The MCP tools themselves (mesh generation, rigging, retargeting) work and are deployed —
+- The MCP tools themselves (mesh generation, rigging, retargeting) work and are deployed,
the rejection is ONLY about the payment rail.
## Client-side protocol knowledge already in this repo
@@ -55,10 +54,10 @@ verifies/settles, exact required fields) is what prompt 01 pins down.
- **3D category is EMPTY.** Query "3D model avatar rendering game asset" → 1 result, a novelty
trading-card generator. No text→3D, no rigging, no avatars. We would be first and only.
-- **The winning pattern** — "Onchain Data Explorer", **174 sales** (most-sold agent found):
+- **The winning pattern**, "Onchain Data Explorer", **174 sales** (most-sold agent found):
~19 tiny, sharply-scoped A2MCP endpoints, micro-priced ($0.000015–$0.000075 per call).
Granular + cheap + composable + free discovery endpoints.
-- **The losing pattern** — "TO1 Intelligence": 100+ services sprayed at $0.25 → 0 sales.
+- **The losing pattern**, "TO1 Intelligence": 100+ services sprayed at $0.25 → 0 sales.
- Everything that sells is **A2MCP fixed-price**. A2A "negotiated" listings ≈ 0 sales.
- Creative/media: 2 agents total, both 2D, both 0 sales. Prices $0.5–$1.0.
@@ -87,7 +86,7 @@ for the 6-digit OTP from that inbox and run `onchainos wallet verify <otp>`. Nev
Never simulate a payment where a real one is specified.
4. **Concurrent agents share this worktree.** Stage explicit paths only (never `git add -A`),
re-check `git status` before committing.
-5. **Push with `git push threews main`** — the only push target (owner decision 2026-07-07).
+5. **Push with `git push threews main`**, the only push target (owner decision 2026-07-07).
Never push, pull, fetch, or merge `threeD` (retired `nirholas/3D-Agent` mirror, diverged history).
6. **`npx vercel build` trap:** it overwrites `api/*.js` in place. If you ran it, check
`head -1` of changed api files for `__defProp` before committing; recover with
@@ -96,16 +95,16 @@ for the 6-digit OTP from that inbox and run `onchainos wallet verify <otp>`. Nev
re-activate (resubmission), preserving the agent ID.
8. **Progress log:** append a dated entry to `prompts/okx-ai/PROGRESS.md` when you finish
(create it if absent): what you did, what you verified, what's blocked, what's next.
- The next work order's chat has no memory of yours — this file is the handoff.
+ The next work order's chat has no memory of yours, this file is the handoff.
## Work-order sequence
| # | File | Depends on |
|---|---|---|
-| 01 | `01-protocol-research.md` — pin down the seller-side OKX payments spec | — |
-| 02 | `02-payments-integration.md` — implement OKX rail on our endpoint | 01 |
-| 03 | `03-service-decomposition.md` — split into micro-priced A2MCP services | 02 |
-| 04 | `04-e2e-real-payment-test.md` — pay ourselves for real, verify settlement | 02, 03 |
-| 05 | `05-relisting-resubmission.md` — update #2632 + resubmit for review | 04 |
-| 06 | `06-agent-pfp-wedge.md` — the "avatars for OKX agents" flagship service | 02 (parallel ok) |
-| 07 | `07-final-audit-and-watch.md` — full audit, docs closure, approval watch | all |
+| 01 | `01-protocol-research.md`, pin down the seller-side OKX payments spec |, |
+| 02 | `02-payments-integration.md`, implement OKX rail on our endpoint | 01 |
+| 03 | `03-service-decomposition.md`, split into micro-priced A2MCP services | 02 |
+| 04 | `04-e2e-real-payment-test.md`, pay ourselves for real, verify settlement | 02, 03 |
+| 05 | `05-relisting-resubmission.md`, update #2632 + resubmit for review | 04 |
+| 06 | `06-agent-pfp-wedge.md`, the "avatars for OKX agents" flagship service | 02 (parallel ok) |
+| 07 | `07-final-audit-and-watch.md`, full audit, docs closure, approval watch | all |
diff --git a/prompts/okx-ai/04-e2e-real-payment-test.md b/prompts/okx-ai/04-e2e-real-payment-test.md
index 4b62b79f7..95a1b73a5 100644
--- a/prompts/okx-ai/04-e2e-real-payment-test.md
+++ b/prompts/okx-ai/04-e2e-real-payment-test.md
@@ -1,4 +1,4 @@
-# Work Order 04 — End-to-end REAL payment test (we pay ourselves and verify settlement)
+# Work Order 04: End-to-end REAL payment test (we pay ourselves and verify settlement)
Read `prompts/okx-ai/00-CONTEXT.md`, `specs/okx-agent-payments.md`, and
`prompts/okx-ai/PROGRESS.md` (02 + 03 must be done). Read `/workspaces/three.ws/CLAUDE.md`.
@@ -8,41 +8,41 @@ Read `prompts/okx-ai/00-CONTEXT.md`, `specs/okx-agent-payments.md`, and
Before resubmitting the listing, prove the whole machine with real money: act as an OKX
buyer agent, pay our own endpoint through the OKX Agent Payments Protocol on X Layer,
receive the artifact, and confirm settlement landed in our wallet on-chain. If OKX's
-reviewer does exactly this and anything breaks, we get rejected again — so we do it first,
+reviewer does exactly this and anything breaks, we get rejected again, so we do it first,
against production, and we do not stop at the first green result.
**The owner has explicitly committed to funding wallets for this. Compute what you need,
-present the funding request, and wait — do not simulate instead.**
+present the funding request, and wait, do not simulate instead.**
-## Phase 1 — Funding plan
+## Phase 1, Funding plan
1. Session preflight (00-CONTEXT). Identify the buyer wallet the CLI signs with
- (`onchainos wallet status`; the TEE account's X Layer address — surface it).
+ (`onchainos wallet status`; the TEE account's X Layer address, surface it).
2. Compute required funds and present ONE consolidated funding request to the owner:
- Fee token (`0x779d…3736`) for: cheapest service ($0.01), one mid service, the flagship
Text→Rigged Avatar ($0.50), ×2 for retries + margin.
- - Gas (OKB on X Layer) if the chosen scheme requires buyer-side gas — the spec says
+ - Gas (OKB on X Layer) if the chosen scheme requires buyer-side gas, the spec says
whether the facilitator sponsors gas (Permit2/EIP-3009 paths usually do); cite it.
- Exact addresses, chain, token contract, amounts. Wait for the owner's confirmation.
3. Verify funds arrived on-chain before proceeding (balance query via CLI or X Layer RPC).
-## Phase 2 — The gauntlet (production endpoints, real payments)
+## Phase 2, The gauntlet (production endpoints, real payments)
Run each numbered case; capture EVERYTHING (commands, headers, decoded challenges, tx
hashes) into `prompts/okx-ai/e2e-evidence/` as you go:
-1. **Free lane**: health + catalog endpoints — correct, live data, no payment demanded.
+1. **Free lane**: health + catalog endpoints, correct, live data, no payment demanded.
2. **Cheapest paid service** ($0.01 Text→3D): unpaid call → 402; `onchainos payment pay`
→ authorization header; replay → job runs → real GLB delivered. Download the GLB,
verify it parses and has geometry (not zero-byte, not an error JSON saved as .glb).
3. **Flagship** ($0.50 Text→Rigged Avatar): same flow; verify the GLB additionally contains
- a skeleton + skinned mesh (bones present, skin weights non-empty — use the repo's
+ a skeleton + skinned mesh (bones present, skin weights non-empty, use the repo's
existing GLB inspection utils from the rig/retarget test suite).
-4. **Settlement verification (the part everyone skips — do not skip):** for each payment,
+4. **Settlement verification (the part everyone skips, do not skip):** for each payment,
find the settlement tx on X Layer (explorer/RPC), confirm the fee token transfer to OUR
payTo `0x75d0…cf69` for the exact advertised amount, and confirm any `PAYMENT-RESPONSE`
header matches the on-chain reality. Record tx hashes.
-5. **Adversarial cases** (all against production, all must fail SAFELY — tool must not run,
+5. **Adversarial cases** (all against production, all must fail SAFELY, tool must not run,
error must be actionable, a fresh challenge must be offered where applicable):
a. Replay the same authorization header twice → second attempt rejected (no double-spend
of one payment, no free second job).
@@ -51,19 +51,19 @@ hashes) into `prompts/okx-ai/e2e-evidence/` as you go:
with fresh challenge.
d. Garbage payment header → clean 4xx, no crash, no tool execution.
6. **Failure refund/no-charge semantics:** force a failing job (invalid input that passes
- payment but fails generation — e.g. rig a non-humanoid prop through the humanoid-gated
+ payment but fails generation, e.g. rig a non-humanoid prop through the humanoid-gated
lane). Verify our pay-only-on-success promise holds mechanically: either the payment is
not settled, or the documented refund path executes. Whatever the code actually does,
- confirm it matches what our listing/docs PROMISE — a mismatch is a release blocker: fix
+ confirm it matches what our listing/docs PROMISE, a mismatch is a release blocker: fix
the code or fix the promise (and its docs) before proceeding.
7. **Legacy rails regression:** one paid call over an existing rail (Base/Solana per
existing test rig) still works.
-## Phase 3 — Fix loop
+## Phase 3, Fix loop
Any failure: diagnose root cause, fix (code per 02/03 conventions), redeploy, re-run the
FULL failed case plus cases 2 and 5a (regression floor). Repeat until the entire gauntlet
-passes in one clean sequence. Log each iteration in PROGRESS.md — iterations are evidence
+passes in one clean sequence. Log each iteration in PROGRESS.md, iterations are evidence
of rigor, not embarrassment.
## Definition of done
@@ -76,7 +76,7 @@ of rigor, not embarrassment.
- [ ] Pay-only-on-success promise verified mechanically or promise corrected everywhere
- [ ] Any code fixes committed per repo rules + pushed to `threews` (only push target)
- [ ] `docs/okx-marketplace.md` updated with a "verified behavior" section: settlement
- timing, refund semantics, replay protection — stated from evidence, not intention
+ timing, refund semantics, replay protection, stated from evidence, not intention
- [ ] `data/changelog.json`: only if user-visible behavior changed in the fix loop
- [ ] `prompts/okx-ai/PROGRESS.md` appended: gauntlet table (case → result → evidence
pointer), remaining risks, explicit GO/NO-GO for Work Order 05
@@ -84,7 +84,7 @@ of rigor, not embarrassment.
## Anti-laziness gates
- No case is "covered by" another case. Run all of them, individually, against production.
-- A 200 response is not success — success is the artifact being real (GLB parses, skeleton
+- A 200 response is not success, success is the artifact being real (GLB parses, skeleton
present) AND the money being on-chain in our wallet.
- If you cannot verify settlement on-chain, the test is not passed. Find the tx or find
the bug.
diff --git a/prompts/okx-ai/05-relisting-resubmission.md b/prompts/okx-ai/05-relisting-resubmission.md
index f7a8c4a54..4769b1b15 100644
--- a/prompts/okx-ai/05-relisting-resubmission.md
+++ b/prompts/okx-ai/05-relisting-resubmission.md
@@ -1,4 +1,4 @@
-# Work Order 05 — Update agent #2632 and resubmit the listing
+# Work Order 05: Update agent #2632 and resubmit the listing
Read `prompts/okx-ai/00-CONTEXT.md` and `prompts/okx-ai/PROGRESS.md` end to end. **Hard
gate: 04 must show an explicit GO.** If there is no GO from 04, stop and say so. Read
@@ -7,12 +7,12 @@ gate: 04 must show an explicit GO.** If there is no GO from 04, stop and say so.
## Mission
Resubmit "three.ws 3D Studio" (#2632) with the decomposed service catalog and the now-real
-OKX payment rail. This is the shot that reverses the rejection — treat the submission
+OKX payment rail. This is the shot that reverses the rejection, treat the submission
itself as a product: every string a reviewer reads, every endpoint they probe, must be
-exact. **Update the existing agent #2632 — never deactivate, never re-create; the ID, its
+exact. **Update the existing agent #2632, never deactivate, never re-create; the ID, its
wallet binding, and its history are assets.**
-## Step 1 — Pre-submission verification sweep
+## Step 1, Pre-submission verification sweep
You are the reviewer for an hour. Against PRODUCTION:
@@ -20,50 +20,50 @@ You are the reviewer for an hour. Against PRODUCTION:
for the free lane). Any drift from what 03/04 recorded = stop and fix first.
2. Diff every service's name/description/price/URL between the catalog module
(`api/_lib/okx-catalog.js`), the live free catalog endpoint, and the table you're about
- to submit. Must be identical — three copies, zero drift.
+ to submit. Must be identical, three copies, zero drift.
3. Validate every description against OKX limits (2-part format; each part ≤200 chars in
East-Asian display width, CJK=2/ASCII=1; no links/tech-stack/example-prompts inside
- service descriptions — those rules are in `.claude/skills/okx-agent-identity/references/invariants.md`,
+ service descriptions, those rules are in `.claude/skills/okx-agent-identity/references/invariants.md`,
which read in full before this step, along with `references/update.md`).
4. Agent-level profile: keep the existing description unless evidence says it hurt review
(do not silently rewrite identity copy); profile photo URL must be the existing OKX CDN
- asset (`https://static.okx.com/cdn/.../49eab781-....png`) — OKX rejects non-CDN links.
+ asset (`https://static.okx.com/cdn/.../49eab781-....png`), OKX rejects non-CDN links.
-## Step 2 — The update flow (interactive — human in the loop)
+## Step 2, The update flow (interactive, human in the loop)
Session preflight per 00-CONTEXT (login = [email protected]; the human relays the OTP).
Follow the okx-agent-identity update flow **exactly** (`.claude/skills/okx-agent-identity/`
SKILL.md + references/update.md): fetch current state via `agent get-agents --agent-ids 2632`
first; build the `--service` JSON with per-service `operation` deltas (`create` for new
-entries, `update`/`delete` with `id` for existing ones — pull existing service ids via
+entries, `update`/`delete` with `id` for existing ones, pull existing service ids via
`agent service-list --agent-id 2632`); `serviceType: "A2MCP"`, `fee` as plain quoted number
string, `endpoint` = the per-service production URL; run the validate-listing QA; render the
diff card and get the human's explicit confirm before the write. The skill's confirmation
-gates exist for a reason — an on-chain write is irreversible; do not shortcut them even
+gates exist for a reason, an on-chain write is irreversible; do not shortcut them even
though this is "our own" agent.
-## Step 3 — Resubmit for review
+## Step 3, Resubmit for review
Per the rejection email, resubmission happens through the agent flow: after the update
-lands, run the activate step (`--preferred-language en-US` is required — see invariants.md
+lands, run the activate step (`--preferred-language en-US` is required, see invariants.md
flag gotchas). Confirm the CLI/backend response shows the listing entered review
(approval status moves off "Listing rejected" to pending/in-review). Capture the exact
before/after approval-status values.
-## Step 4 — Record + set the watch
+## Step 4, Record + set the watch
- PROGRESS.md: submitted catalog (verbatim), tx/CLI outputs, timestamp, approval status
after submission, and the daily check command:
`onchainos agent get-my-agents` (or `get-agents --agent-ids 2632`).
-- `data/changelog.json`: no entry yet — the changelog entry ships when the listing is
+- `data/changelog.json`: no entry yet, the changelog entry ships when the listing is
APPROVED (07 owns that), not when submitted.
## Definition of done
- [ ] Pre-submission sweep: every catalog endpoint verified live + three-way string diff clean
- [ ] Update executed through the skill's full flow (pre-fetch, deltas by service id,
- validate, human-confirmed diff card) — no bypassed gates
+ validate, human-confirmed diff card), no bypassed gates
- [ ] Resubmission confirmed: approval status captured before + after, listing is in review
- [ ] Nothing was deactivated/deleted; agent is still #2632
- [ ] PROGRESS.md appended with the full submission record
@@ -71,11 +71,11 @@ before/after approval-status values.
## Anti-laziness gates
-- Do not paraphrase, trim, or "improve" 03's final descriptions during entry — submit the
+- Do not paraphrase, trim, or "improve" 03's final descriptions during entry, submit the
validated strings byte-for-byte. If entry-time validation rejects one, fix it in the
- catalog module FIRST, redeploy, re-verify the free catalog endpoint, then resubmit — the
+ catalog module FIRST, redeploy, re-verify the free catalog endpoint, then resubmit, the
three copies must never diverge, even for one review cycle.
- If the CLI or backend errors mid-update, read
- `.claude/skills/okx-agent-identity/references/errors.md` and resolve properly — never
+ `.claude/skills/okx-agent-identity/references/errors.md` and resolve properly, never
retry-loop a business error, never leave the listing half-updated without recording
exactly which services landed.
diff --git a/prompts/okx-ai/06-agent-pfp-wedge.md b/prompts/okx-ai/06-agent-pfp-wedge.md
index f83ae1776..8d26ea076 100644
--- a/prompts/okx-ai/06-agent-pfp-wedge.md
+++ b/prompts/okx-ai/06-agent-pfp-wedge.md
@@ -1,4 +1,4 @@
-# Work Order 06 — "Agent Identity Studio": 3D avatars for OKX.AI agents themselves
+# Work Order 06: "Agent Identity Studio": 3D avatars for OKX.AI agents themselves
Read `prompts/okx-ai/00-CONTEXT.md`, `prompts/okx-ai/PROGRESS.md` (02 must be done; runs in
parallel with 04/05 otherwise), and `/workspaces/three.ws/CLAUDE.md`.
@@ -9,24 +9,24 @@ The sharpest wedge on OKX.AI: **our customers are the other agents on the platfo
registered agent has a `profilePicture`, and OKX's own identity flow includes a set-avatar
step (`onchainos agent upload` + update). Almost all current agents use flat generated
images. We sell them a distinctive 3D identity: text/brand brief → 3D avatar → posed,
-lit, high-res renders sized for the OKX CDN avatar slot — plus the underlying rigged GLB
+lit, high-res renders sized for the OKX CDN avatar slot, plus the underlying rigged GLB
so their identity works anywhere in 3D (three.ws scenes, games, metaverse embeds).
This is a product, not a listing blurb. Build it end to end.
## Product definition
-**Service: "Agent Identity Studio"** — one A2MCP service (joins the 03 catalog):
+**Service: "Agent Identity Studio"**, one A2MCP service (joins the 03 catalog):
- **Input** (JSON): agent name, personality/brand description, style hints (optional),
reference image URL (optional).
-- **Pipeline** (all capabilities already exist in this codebase — wire, don't rebuild):
+- **Pipeline** (all capabilities already exist in this codebase, wire, don't rebuild):
1. Brief → avatar prompt (existing prompt-shaping used by the avatar lane).
2. `forge_avatar`-equivalent chain: mesh generation + humanoid auto-rig.
3. Pose + frame: 3-5 distinct poses from the pose/clip library (rigged, retargeted),
- rendered against clean backdrops — headshot crop for the PFP slot + full-body shot.
+ rendered against clean backdrops, headshot crop for the PFP slot + full-body shot.
Rendering: check what already exists for server-side GLB rendering (screenshot workers,
- preview pipelines) before adding anything new. Real renders of THEIR avatar — never
+ preview pipelines) before adding anything new. Real renders of THEIR avatar, never
stock/template output.
4. Deliverables: PNG set (PFP-cropped square + full-body), the rigged GLB, and a three.ws
viewer link (existing viewer URL pattern).
@@ -38,31 +38,31 @@ This is a product, not a listing blurb. Build it end to end.
## Requirements
1. **Wired into the 03 architecture**: entry in the catalog module, own endpoint URL, own
- OKX 402, tests alongside the other services — not a parallel one-off.
+ OKX 402, tests alongside the other services, not a parallel one-off.
2. **Output quality is the product.** Generate at least 3 full pipeline runs from genuinely
different briefs (e.g. a finance data agent, a creative/art agent, a trading bot).
Inspect every deliverable: PFP reads clearly at 128×128 (OKX list size), full-body is
coherent, GLB is rigged (skeleton + skin weights verified with the repo's GLB inspection
- utils). If any output is mediocre — fix the pipeline (prompt shaping, pose choice,
+ utils). If any output is mediocre, fix the pipeline (prompt shaping, pose choice,
framing, lighting) and rerun. CLAUDE.md: "would someone screenshot this?" is the bar.
3. **Dogfood publicly**: run OUR agent's own brief through it and (via the okx-agent-identity
upload/update flow, with the human confirming the on-chain write) set #2632's profile
photo to the result. Our listing's face becomes our portfolio piece. Coordinate with 05:
if 05 hasn't submitted yet, hand the asset to 05 via PROGRESS.md instead of racing it
with a second update; if 05 already submitted and the listing is mid-review, do NOT touch
- the listing — record the asset and defer the swap to 07 (post-approval).
+ the listing, record the asset and defer the swap to 07 (post-approval).
4. **Showcase page on three.ws**: a gallery page (following existing page/site conventions +
- design tokens) showing the demo identities — each with renders + embedded 3D viewer.
+ design tokens) showing the demo identities, each with renders + embedded 3D viewer.
This is the `link` target for the changelog entry and the proof-of-quality URL the
listing description can reference. Register it in `data/pages.json`.
## Testing
-- Full 03-style integration: unpaid 402 → pay (real, X Layer, per 04's runbook — request
+- Full 03-style integration: unpaid 402 → pay (real, X Layer, per 04's runbook, request
funding if the wallet is dry) → job → all three deliverable types verified real.
-- Edge cases: brief in Chinese (half the marketplace is zh — output must not degrade),
+- Edge cases: brief in Chinese (half the marketplace is zh, output must not degrade),
absurdly long brief (truncate/handle honestly), reference image 404 (clean actionable
- error, no charge settled for undeliverable work — consistent with 04's verified
+ error, no charge settled for undeliverable work, consistent with 04's verified
pay-only-on-success semantics).
- `npm test` green; preview deploy verified.
@@ -72,7 +72,7 @@ This is a product, not a listing blurb. Build it end to end.
X Layer payment
- [ ] 3+ demo identities generated, inspected, iterated to genuinely excellent
- [ ] #2632's own avatar produced (set live, or handed off per requirement 3's coordination
- rule — recorded either way)
+ rule, recorded either way)
- [ ] Showcase page live, in `data/pages.json`, linked from the site's nav per existing
conventions
- [ ] Docs: service section added to `docs/okx-marketplace.md` with a runnable example
@@ -83,10 +83,10 @@ This is a product, not a listing blurb. Build it end to end.
## Anti-laziness gates
-- The demo briefs must be REAL runs of the full pipeline, saved with their inputs — not
+- The demo briefs must be REAL runs of the full pipeline, saved with their inputs, not
cherry-picked outputs from manual retries you can't reproduce. If it took prompt-shaping
fixes to get quality reliably, those fixes live in code now.
-- Renders at final crop size are the acceptance test — a beautiful 1024px render that turns
+- Renders at final crop size are the acceptance test, a beautiful 1024px render that turns
to mud at 128px fails requirement 2.
- "GLB is rigged" means you verified bones + weights programmatically, not that the
generator lane usually rigs things.
diff --git a/prompts/okx-ai/07-final-audit-and-watch.md b/prompts/okx-ai/07-final-audit-and-watch.md
index 26516a4e2..cb7f529c0 100644
--- a/prompts/okx-ai/07-final-audit-and-watch.md
+++ b/prompts/okx-ai/07-final-audit-and-watch.md
@@ -1,4 +1,4 @@
-# Work Order 07 — Final audit, docs closure, approval watch, first-sale readiness
+# Work Order 07: Final audit, docs closure, approval watch, first-sale readiness
Read `prompts/okx-ai/00-CONTEXT.md` and ALL of `prompts/okx-ai/PROGRESS.md`. 01–05 must be
complete (06 ideally too). Read `/workspaces/three.ws/CLAUDE.md`.
@@ -7,9 +7,9 @@ complete (06 ideally too). Read `/workspaces/three.ws/CLAUDE.md`.
Close the loop: independently audit everything shipped in this work stream, close every
docs/changelog gap, watch the resubmission through review, and make sure the day we get
-approved is the day we're ready to sell — not the day we start scrambling.
+approved is the day we're ready to sell, not the day we start scrambling.
-## Part 1 — Independent adversarial audit
+## Part 1, Independent adversarial audit
Trust nothing in PROGRESS.md until re-verified. Sample-run the critical path yourself,
against production, TODAY:
@@ -18,7 +18,7 @@ against production, TODAY:
when unrelated deploys touch shared code).
2. One real paid call end to end incl. on-chain settlement check (04's runbook; request
funding if dry).
-3. Replay-protection spot check (04 case 5a) — still rejects.
+3. Replay-protection spot check (04 case 5a), still rejects.
4. Free lane: health honest, catalog 1:1 with the catalog module and with the submitted
listing (pull the live listing: `onchainos agent service-list --agent-id 2632`).
5. Run the repo's completionist audit (the completionist agent) over every file this work
@@ -27,30 +27,30 @@ against production, TODAY:
files, repo root clean.
6. `npm test` green; `npm run build:pages` green (validates changelog entries).
-## Part 2 — Docs closure sweep
+## Part 2, Docs closure sweep
Per CLAUDE.md's Documentation section, verify each layer exists and is CORRECT (read them
as a zero-context outsider):
-- [ ] `specs/okx-agent-payments.md` — matches implemented reality, incl. every 04 fix
-- [ ] `docs/okx-marketplace.md` — every service documented, every curl example actually
+- [ ] `specs/okx-agent-payments.md`, matches implemented reality, incl. every 04 fix
+- [ ] `docs/okx-marketplace.md`, every service documented, every curl example actually
runs (run them), linked from `docs/start-here.md`
-- [ ] `STRUCTURE.md` — rows for the new surface(s)
-- [ ] `data/pages.json` — any new pages registered (06's showcase)
-- [ ] `data/changelog.json` — entries from 02/03/06 present + well-formed; stale claims
+- [ ] `STRUCTURE.md`, rows for the new surface(s)
+- [ ] `data/pages.json`, any new pages registered (06's showcase)
+- [ ] `data/changelog.json`, entries from 02/03/06 present + well-formed; stale claims
corrected (docs that promise what 04 disproved are release blockers)
- [ ] README(s) in any new package/worker directories created by this stream
-## Part 3 — Approval watch + launch runbook
+## Part 3, Approval watch + launch runbook
1. Check current approval status (`onchainos agent get-agents --agent-ids 2632`).
-2. Write `prompts/okx-ai/RUNBOOK.md` — the operator's guide for the human + future agents:
+2. Write `prompts/okx-ai/RUNBOOK.md`, the operator's guide for the human + future agents:
- Daily status-check one-liner; how to read approval states (approvalDisplayStatus map).
- - **If APPROVED**: activation confirmation; the launch checklist — changelog entry
+ - **If APPROVED**: activation confirmation; the launch checklist, changelog entry
announcing the listing (tags: `feature`; this is THE holder-visible moment), Telegram
changelog push per repo process, set 06's avatar live if deferred, verify the listing
renders correctly in the marketplace UI (search for us as a buyer would:
- `onchainos agent search --query "3D avatar rigging GLB"` — confirm we appear, cells
+ `onchainos agent search --query "3D avatar rigging GLB"`, confirm we appear, cells
read well, prices right).
- **If REJECTED again**: capture the exact remark (`approvalRemark` + email), append to
PROGRESS.md, map the stated reason to the responsible work order, fix, re-run 05.
@@ -59,9 +59,9 @@ as a zero-context outsider):
(existing error-reporting path from api/_mcp/payments.js), what to monitor daily.
3. If the platform exposes review timing/messaging via the task/chat surface, note in the
RUNBOOK how the human triggers the check (the okx-task-watch flow exists for live
- monitoring — reference it as the tool for the human to invoke, don't leave a daemon).
+ monitoring, reference it as the tool for the human to invoke, don't leave a daemon).
-## Part 4 — Memory
+## Part 4, Memory
Write/update the agent-memory file for this work stream (per the memory system in the
system prompt) so future sessions don't re-derive: agent #2632 state, what shipped, where
@@ -83,4 +83,4 @@ evidence lives, RUNBOOK location, current watch status. Update `MEMORY.md` index
- This audit exists BECAUSE the prior work orders claimed done. Re-verify with fresh eyes;
every "verified in 04" claim you re-test and confirm, say so; every one you can't
reproduce is a defect to fix now.
-- Do not write the RUNBOOK from imagination — every command in it must be one you ran.
+- Do not write the RUNBOOK from imagination, every command in it must be one you ran.
diff --git a/prompts/okx-ai/PROGRESS.md b/prompts/okx-ai/PROGRESS.md
index 57ef3a2fd..f0fc18184 100644
--- a/prompts/okx-ai/PROGRESS.md
+++ b/prompts/okx-ai/PROGRESS.md
@@ -1,12 +1,12 @@
-# OKX.AI Launch — Progress Log
+# OKX.AI Launch: Progress Log
Handoff file for the work-order sequence in this directory. Each session appends a dated
entry: what was done, what was verified, what's blocked, what's next. (Created by the
-Work Order 04 session — no earlier entries existed because no earlier work order has run.)
+Work Order 04 session, no earlier entries existed because no earlier work order has run.)
---
-## 2026-07-10 — Work Order 07 (partial): RUNBOOK written, live re-verification, listing drift found
+## 2026-07-10, Work Order 07 (partial): RUNBOOK written, live re-verification, listing drift found
Ran the unfunded half of WO-07's Part 1 audit against production and wrote the missing
`prompts/okx-ai/RUNBOOK.md` deliverable. Every command in the RUNBOOK was executed; nothing
@@ -16,7 +16,7 @@ in it is written from imagination.
- `onchainos agent get-agents --agent-ids 2632` → `approvalDisplayStatus: 5`
(`approvalLabel: "Listing rejected"`), `status: 2`, `soldCount: 0`, `role: 2`,
- `approvalRemark: ""`. **Unchanged.** Note the remark field is EMPTY — the 2026-07-04
+ `approvalRemark: ""`. **Unchanged.** Note the remark field is EMPTY, the 2026-07-04
rejection reason arrived only by email, so never expect `approvalRemark` to carry it.
- Unpaid `POST /api/okx/3d/identity-studio` → **402** (challenge still spec-valid).
- `GET /api/okx/3d/catalog` → **11 services**, exactly 1:1 with `api/_lib/okx-catalog.js`.
@@ -24,9 +24,9 @@ in it is written from imagination.
retarget).
- `onchainos agent search --query "3D avatar rigging GLB"` → 2 results, **agent 2632 absent**
(correct: we are not listed).
-- `onchainos agent feedback-list` exists ("Query Agent reviews") — the first-sale review path.
+- `onchainos agent feedback-list` exists ("Query Agent reviews"), the first-sale review path.
-### ⚠️ NEW FINDING — the live listing is stale and shares ZERO service names with our catalog
+### ⚠️ NEW FINDING, the live listing is stale and shares ZERO service names with our catalog
`onchainos agent service-list --agent-id 2632` publishes **7** services; our catalog module
defines **11**; **not one name matches**.
@@ -63,23 +63,23 @@ approval-watch execution branch remain, since approval status is unchanged.
---
-## 2026-07-08 — Work Order 05 session #2: found + fixed a live PROD OUTAGE; OKX rail pre-staged; WO 04/05 still owner-gated
+## 2026-07-08, Work Order 05 session #2: found + fixed a live PROD OUTAGE; OKX rail pre-staged; WO 04/05 still owner-gated
-**Outcome: the WO-05 hard gate (needs a GO from WO 04) is still unmet — no resubmit was
+**Outcome: the WO-05 hard gate (needs a GO from WO 04) is still unmet, no resubmit was
attempted. But the pre-submission sweep uncovered a live production outage of the ENTIRE
x402 paid surface, which I fixed. I then found + fixed a WRONG-PLATFORM config bug and
brought the OKX X Layer rail genuinely LIVE in real production. Agent #2632 untouched.**
-### ⭐ CORRECTION to the 2026-07-07 "rail LIVE" claim — it was on the WRONG PLATFORM
+### ⭐ CORRECTION to the 2026-07-07 "rail LIVE" claim, it was on the WRONG PLATFORM
The 2026-07-07 session set `X402_PAY_TO_XLAYER` + `X402_XLAYER_RELAYER_KEY` (relayer
`0x9e48…B7a3`) in **Vercel** prod+preview and recorded the rail as live/validated. **But
production runs on Cloud Run, not Vercel** (migrated 2026-07-07). Those Vercel env vars never
-reached production, so live prod (`three.ws` → Cloud Run) was STILL advertising Solana-only —
+reached production, so live prod (`three.ws` → Cloud Run) was STILL advertising Solana-only,
the rejection cause was NOT actually resolved, despite the evidence file
`03b-rail-deployed-validation.txt` claiming otherwise. A resubmission based on that claim would
have been re-probed against Cloud Run, seen no `eip155:196`, and been rejected again. **The
-Vercel relayer `0x9e48…B7a3` is orphaned — Vercel is dead; do not fund it.**
+Vercel relayer `0x9e48…B7a3` is orphaned, Vercel is dead; do not fund it.**
**Fixed on the correct platform (Cloud Run, revisions 00011 + 00014):** set
`X402_PAY_TO_XLAYER=0x75d0…cf69`, `X402_ASSET_ADDRESS_XLAYER=0x779ded…713736`, and a FRESH
@@ -90,28 +90,28 @@ now advertise **`eip155:196` FIRST** then Solana, at the exact WO-03 prices (tex
pro 300000, image 300000, rig 250000, avatar 500000, retarget 100000, pose-seed 20000, fbx 100000).
**The rejection cause (missing OKX rail in the challenge) is now genuinely resolved in real prod.**
-### ⚠️ `onchainos agent x402-check` is NOT a reliable listing gate — do not trust its verdict
+### ⚠️ `onchainos agent x402-check` is NOT a reliable listing gate, do not trust its verdict
The 2026-07-07 evidence leaned on `x402-check … valid=true`. **That does not reproduce and is
misleading:** `x402-check` probes with a **GET**, and against the APPROVED oklink seller
(#2023, 174 sales) GET→405 so x402-check returns **`valid:false`** ("HTTP 405, not 402"). If
its GET-verdict were the gate, no approved seller could exist. Our endpoints return GET→200
-(the free per-service descriptor) so x402-check likewise says invalid — **immaterial.** The
+(the free per-service descriptor) so x402-check likewise says invalid, **immaterial.** The
REAL, validated contract is **POST→402 with a well-formed OKX challenge**, which we satisfy
byte-shape-identically to oklink (POST→402, eip155:196 first, USD₮0 asset, `exact` scheme).
Verify the rail with a POST, not x402-check's GET. (Minor: oklink does GET→405 where we do
GET→200; evidence shows GET behavior is not the gate, but a future session may choose to match
-405 for zero deviation — it would require changing the free-descriptor design + its test.)
+405 for zero deviation, it would require changing the free-descriptor design + its test.)
### Still owner-gated: SETTLEMENT FUNDING only (rail advertising is done)
The rail advertises and `verify` works unfunded, but `settle` (relayer redeems the EIP-3009
authorization) needs gas, and the buyer leg needs a real balance. Live-checked X Layer balance
= **$0**. To complete WO 04 (real settled self-payment) and then WO 05 (resubmit), fund:
-- **Relayer `0x1F4a753c61b54Bdec7AE0AF338A887E63Cdbbb74`** — ~0.05 OKB for redemption gas.
-- **Buyer/payTo `0x75d00a2713565171f33216e5aa2a375e076ecf69`** — USD₮0 (`0x779ded…713736`),
+- **Relayer `0x1F4a753c61b54Bdec7AE0AF338A887E63Cdbbb74`**, ~0.05 OKB for redemption gas.
+- **Buyer/payTo `0x75d00a2713565171f33216e5aa2a375e076ecf69`**, USD₮0 (`0x779ded…713736`),
≥ $2.98 for one call of every service, ~$5 buffer.
-(OKX HMAC creds `OKX_API_KEY/SECRET/PASSPHRASE` remain OPTIONAL — the relayer route settles
+(OKX HMAC creds `OKX_API_KEY/SECRET/PASSPHRASE` remain OPTIONAL, the relayer route settles
without them; `facilitator_configured:false` is expected and fine.)
---
@@ -121,16 +121,16 @@ _Original entry below was written before the rail was lit; the CORRECTION above
### The outage (found during Step 1 verification, fixed)
Probing the catalog endpoints against production, **every `/api/okx/3d/*` endpoint returned
-HTTP 500** — including the free `health`/`catalog` — and so did **every `/api/x402/*`
+HTTP 500**, including the free `health`/`catalog`, and so did **every `/api/x402/*`
endpoint** (`dance-tip`, `model-check`, `onchain-identity-verify`, …). Cloud Run logs showed
the root cause: `api/_lib/x402/idempotency-cache.js` **hard-throws at module import** in
production when Upstash is unconfigured (the deliberate fail-closed guard from commit
`88e2bad5f`). Upstash creds are absent from the Cloud Run service entirely (Secret Manager
has none; `.env.example` only documents the names). So the whole paid surface was 500ing at
-module load — a regression from the "Solana-only 402" state the 2026-07-07 sessions saw.
+module load, a regression from the "Solana-only 402" state the 2026-07-07 sessions saw.
**Fix (revision `three-ws-api-00010-kkb`):** set `X402_ALLOW_MEMORY_FALLBACK=1` on the
-Cloud Run service — the author-sanctioned escape hatch (docs/ops/gcp-production.md line 218).
+Cloud Run service, the author-sanctioned escape hatch (docs/ops/gcp-production.md line 218).
Financial safety is unaffected: EIP-3009 nonces are single-use on-chain, so no double-charge;
the flag only degrades cross-replica work/response dedup to per-instance. **Verified restored:**
`/api/okx/3d/health` → 200 (all subsystems ok), `catalog` → 200, `text-to-3d` unpaid POST →
@@ -138,38 +138,38 @@ the flag only degrades cross-replica work/response dedup to per-instance. **Veri
an owner action; flagged in the ops runbook, which now also documents the crash-not-degrade
failure mode.
-### OKX X Layer rail — pre-staged, honestly dark (revision `three-ws-api-00011-mcf`)
+### OKX X Layer rail, pre-staged, honestly dark (revision `three-ws-api-00011-mcf`)
Set the two **public** address vars on the service:
`X402_PAY_TO_XLAYER=0x75d00a2713565171f33216e5aa2a375e076ecf69`,
`X402_ASSET_ADDRESS_XLAYER=0x779ded0c9e1022225f8e0630b35a9b54be713736`. These alone keep
`xlayerSettleable()` **false** (it also requires OKX facilitator creds OR
-`X402_XLAYER_RELAYER_KEY`), so the live 402 still advertises **Solana-only** — the honest
+`X402_XLAYER_RELAYER_KEY`), so the live 402 still advertises **Solana-only**, the honest
"not yet live" state, no half-working rail exposed. Health probe confirms:
`payment-rail{ settleable:false, facilitator_configured:false, block read OK, token:"USD₮0" }`.
-### Why WO 04/05 remain genuinely blocked (not laziness — a hard no-mocks dependency)
+### Why WO 04/05 remain genuinely blocked (not laziness, a hard no-mocks dependency)
Live-checked the wallet's **X Layer balance = $0** (no OKB, no USD₮0). The onchainos TEE
-buyer wallet == seller `payTo` == `0x75d0…cf69`, so WO 04's E2E is a self-payment — but even
+buyer wallet == seller `payTo` == `0x75d0…cf69`, so WO 04's E2E is a self-payment, but even
a self-payment's EIP-3009 authorization fails on-chain `verify` (`insufficient_balance`)
with a zero balance. There is **no way to run a real settlement without real USD₮0 in the
-wallet** — fabricating one would violate the no-mocks rule. So the WO-04 GO that gates WO-05
+wallet**, fabricating one would violate the no-mocks rule. So the WO-04 GO that gates WO-05
cannot be produced this session.
### The single owner action that unblocks the whole tail
Fund/provision ONE of these, then WO 04 → (its GO) → WO 05 resubmit proceed:
-- **Settlement authority** — EITHER OKX facilitator creds (`OKX_API_KEY`/`OKX_SECRET_KEY`/
+- **Settlement authority**, EITHER OKX facilitator creds (`OKX_API_KEY`/`OKX_SECRET_KEY`/
`OKX_PASSPHRASE`, facilitator-paid gas, no relayer to manage) OR a
`X402_XLAYER_RELAYER_KEY` funded with a little OKB for gas. With either set, the X Layer
accept auto-advertises (rejection cause fixed at the challenge level).
-- **Buyer funds for the E2E test** — USD₮0 (`0x779ded…713736`) to `0x75d0…cf69` on X Layer
+- **Buyer funds for the E2E test**, USD₮0 (`0x779ded…713736`) to `0x75d0…cf69` on X Layer
(chainId 196). ≥ ~$3 covers one paid call of every catalog service; ~$5 for buffer.
### State captured (Step 3 "before")
-Agent #2632 approval status unchanged — `approvalDisplayStatus: 5` ("Listing rejected"),
+Agent #2632 approval status unchanged, `approvalDisplayStatus: 5` ("Listing rejected"),
`status: 2` ("not listed"), `soldCount: 0`. No update/activate CLI write was issued. The
"after" is deferred to the resubmission session once settlement is funded.
@@ -182,24 +182,24 @@ Agent #2632 approval status unchanged — `approvalDisplayStatus: 5` ("Listing r
---
-## 2026-07-07 — Work Order 02 session: COMPLETE — OKX/X Layer rail gaps closed, verified, documented
+## 2026-07-07, Work Order 02 session: COMPLETE, OKX/X Layer rail gaps closed, verified, documented
**Outcome: our A2MCP/MCP endpoints are first-class OKX Agent Payments Protocol sellers.**
The `eip155:196` USD₮0 accept, the OKX facilitator verify/settle route, and the x402-v2
-receipt header names all flow through the SAME `x402-spec.js` seams every other rail uses —
+receipt header names all flow through the SAME `x402-spec.js` seams every other rail uses,
no parallel payment stack. The spec gained a new **§5 "Implementation"** section mapping
every clause + gap to `file:line`. The rail code was already in HEAD (converged from the
concurrent WO-02/03/04 sessions, commit `05de055d6`); this session closed the remaining G8
header gaps, added endpoint-level tests, unblocked the deploy, and did the real local +
buyer's-eye verification. **Note:** the rail is already LIVE in production (WO-04 session #2
below); for X Layer relayer/funding specifics defer to the relayer-reconciliation entry
-below — THE relayer is `0x9e48…B7a3`, USD₮0 buyer/seller is `0x75d0…cf69`.
+below, THE relayer is `0x9e48…B7a3`, USD₮0 buyer/seller is `0x75d0…cf69`.
### What this session changed (on top of the converged HEAD implementation)
- **G8 finished on the MCP endpoints.** `api/mcp-3d.js` and `api/okx/3d/[service].js` now
emit BOTH `PAYMENT-RESPONSE` (x402 v2, what OKX buyers decode) and `x-payment-response`
- (v1 alias) on a settled paid call — they previously set only the v1 name.
+ (v1 alias) on a settled paid call, they previously set only the v1 name.
- **Receipt carries `status` + `amount`.** `encodePaymentResponseHeader()`
([x402-spec.js](../../api/_lib/x402-spec.js)) passes through the OKX SettleResponse
`status` ("success"/"pending") and `amount` (spec §1.4); the X Layer settle
@@ -219,13 +219,13 @@ below — THE relayer is `0x9e48…B7a3`, USD₮0 buyer/seller is `0x75d0…cf69
future deploy was broken. Trimmed to 96 chars. Not this WO's file, but it blocked my
preview deploy and the team's next prod deploy.
-### Verification captured (real, not theatrical) — evidence in `e2e-evidence/02-*`
+### Verification captured (real, not theatrical), evidence in `e2e-evidence/02-*`
- **Tests:** `mcp-3d-challenge` 15/15; with `okx-3d-services` + `mcp-3d` + `x402-spec` +
`mcp` = **110/110** in one run. One pre-existing unrelated failure elsewhere
- (`x402-pipeline` "partial-failure semantics" — fails with my changes stashed too).
+ (`x402-pipeline` "partial-failure semantics", fails with my changes stashed too).
- **Local integration (real module over `node:http`, OKX env set):** unpaid
- `POST tools/call text_to_3d` → `HTTP/1.1 402` with TWO accepts — Base (`eip155:8453`) AND
+ `POST tools/call text_to_3d` → `HTTP/1.1 402` with TWO accepts, Base (`eip155:8453`) AND
X Layer (`eip155:196`). Field-by-field vs spec §1.1, all present: `scheme:exact`,
`payTo:0x75d0…cf69`, `asset:0x779ded…713736`, `amount:"150000"` (text_to_3d standard,
6-dp USD₮0), `maxTimeoutSeconds:86400`,
@@ -236,30 +236,30 @@ below — THE relayer is `0x9e48…B7a3`, USD₮0 buyer/seller is `0x75d0…cf69
`value:"150000"` to our payTo on `eip155:196`. CLI did not reject our challenge.
- **Full unfunded round-trip:** replaying that `PAYMENT-SIGNATURE` against our endpoint ran
our REAL verify (EIP-712 recovery + `authorizationState` + `balanceOf` on X Layer RPC)
- and returned `402 error:"insufficient_balance"` with a fresh full challenge — the tool did
+ and returned `402 error:"insufficient_balance"` with a fresh full challenge, the tool did
NOT run. Verify-gates-execution proven; funded success leg is WO-04's.
-### 6 requirements — status
+### 6 requirements, status
-1. Challenge (OKX-valid 402, all `extra` fields, decimals-scaled) — ✅ verified locally.
-2. Verify before work (real on-chain, invalid→fresh challenge, tool doesn't run) — ✅.
-3. Settle after success + `PAYMENT-RESPONSE` — ✅ (paid-leg unit test; live settle is WO-04).
-4. Multi-rail coexistence (Base accept still present) — ✅ same challenge.
-5. Free lane intact (getting_started / discovery) — ✅ existing tests green.
-6. Amounts consistent (advertised == verified == settled from `priceBatch`) — ✅.
+1. Challenge (OKX-valid 402, all `extra` fields, decimals-scaled), ✅ verified locally.
+2. Verify before work (real on-chain, invalid→fresh challenge, tool doesn't run), ✅.
+3. Settle after success + `PAYMENT-RESPONSE`, ✅ (paid-leg unit test; live settle is WO-04).
+4. Multi-rail coexistence (Base accept still present), ✅ same challenge.
+5. Free lane intact (getting_started / discovery), ✅ existing tests green.
+6. Amounts consistent (advertised == verified == settled from `priceBatch`), ✅.
### Blocked on / owner action
-- **OKX facilitator creds** (`OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`) — enable the
+- **OKX facilitator creds** (`OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`), enable the
preferred gasless facilitator settle route. Without them the rail still settles via the
reconciled relayer `0x9e48…B7a3` (direct EIP-3009 redemption, OKB gas). Not a blocker for
the challenge/verify the listing review checks.
-- **Funding** — defer to the relayer-reconciliation + WO-04 entries below (OKB → relayer
+- **Funding**, defer to the relayer-reconciliation + WO-04 entries below (OKB → relayer
`0x9e48…B7a3`; USD₮0 → `0x75d0…cf69`). Only needed for WO-04's funded success leg.
---
-## 2026-07-07 — Relayer-key reconciliation: ONE authoritative X Layer relayer, funding target corrected
+## 2026-07-07, Relayer-key reconciliation: ONE authoritative X Layer relayer, funding target corrected
**Read this before funding anything.** Two concurrent sessions (this WO-03 re-dispatch and the
WO-04 session #2 entry below) each generated a *different* throwaway `X402_XLAYER_RELAYER_KEY`
@@ -269,13 +269,13 @@ The deployed key is not readable (Vercel masks it; health does not expose the ad
disagreement could not be settled by observation. Resolved it deterministically instead:
- **`vercel env rm` then `vercel env add` the relayer key in BOTH production and preview**, then
- redeployed prod. The live key now derives **`0x9e48594212487777497bAeB4716dd13250F4B7a3`** —
+ redeployed prod. The live key now derives **`0x9e48594212487777497bAeB4716dd13250F4B7a3`**,
verified: I hold this private key, it is the only relayer entry in Vercel env, and
post-redeploy health reports `payment-rail settleable:true` (valid secp256k1 key loaded
server-side; the key lives durably in Vercel env, so settlement runs server-side and WO-04
- needs no local copy — only this address funded with OKB gas).
+ needs no local copy, only this address funded with OKB gas).
- **THE relayer to fund is `0x9e48…B7a3`. The `0x1B60…AB2a` address in the WO-04 entry below is
- SUPERSEDED** — that key was removed from Vercel and is no longer deployed; do not fund it.
+ SUPERSEDED**, that key was removed from Vercel and is no longer deployed; do not fund it.
- Safe to do now: both wallets were unfunded (0 balance), so no value moved and nothing was
stranded. Post-redeploy re-check: 8/8 services still `x402-check valid:true` at target prices;
relayer `0x9e48…B7a3` OKB balance = 0 (the WO-04 gas ask stands, just against this address).
@@ -285,12 +285,12 @@ buyer/seller `0x75d0…cf69`. Everything else in the WO-04 entry below holds.
---
-## 2026-07-07 — Work Order 04 session #2: rail deployed to prod, gauntlet armed, PAUSED on funding
+## 2026-07-07, Work Order 04 session #2: rail deployed to prod, gauntlet armed, PAUSED on funding
**Outcome: the X Layer / OKX rail is now LIVE on production and every funding-independent
leg of the gauntlet passes. Presented the consolidated funding request
([`e2e-evidence/FUNDING-REQUEST.md`](e2e-evidence/FUNDING-REQUEST.md)) and paused per Phase 1.
-No money spent yet — wallet holds 0 on all chains.**
+No money spent yet, wallet holds 0 on all chains.**
### What changed this session (deploy, not code)
@@ -303,9 +303,9 @@ Fixed by provisioning prod env + redeploy:
`0x1B60Cb12cE894Efc2470bB18Bf2D41755b49AB2a`; private key lives ONLY in Vercel env +
session scratchpad, never committed.** This is the direct-redemption settle path (Path B),
used when OKX facilitator creds are absent.
-- `X402_ASSET_ADDRESS_XLAYER` already defaults to USD₮0 in `env.js` — no action.
+- `X402_ASSET_ADDRESS_XLAYER` already defaults to USD₮0 in `env.js`, no action.
- Redeployed prod (a transient "deployment failed, retry later" fired once during the
- dep-install phase but the build had already completed; the env change is live — confirmed
+ dep-install phase but the build had already completed; the env change is live, confirmed
below).
### Verified LIVE against production (evidence in `e2e-evidence/`)
@@ -319,15 +319,14 @@ Fixed by provisioning prod env + redeploy:
| Seller verify path live | real signed header replayed unfunded → `HTTP 402 insufficient_balance` + fresh `eip155:196` challenge (on-chain `balanceOf` ran) | `02-replay-unfunded.json` |
| Garbage header (case 5d) | → `HTTP 400 invalid_payment` ("X-PAYMENT JSON parse failed"), no crash, no tool run | `05d-garbage-body.txt` |
-`payment-rail` health: `settleable:true, facilitator_configured:false, token USD₮0, block ~64.6M`
-— i.e. Path B (relayer) is the active settle route until OKX creds land.
+`payment-rail` health: `settleable:true, facilitator_configured:false, token USD₮0, block ~64.6M`, i.e. Path B (relayer) is the active settle route until OKX creds land.
-### Funding request presented (Phase 1) — PAUSED here
+### Funding request presented (Phase 1), PAUSED here
Buyer == seller (`0x75d0…cf69` both sides) ⇒ settlement is a self-transfer, net-zero, so the
USD₮0 float is one-time (covers the largest single call, not the sum). Ask:
- **2.0 USD₮0** → `0x75d0…cf69` on X Layer 196 (floor 0.5 = the avatar flagship).
-- **0.3 OKB** → relayer `0x1B60…AB2a` on X Layer (Path B gas) — OR provide `OKX_API_KEY`/
+- **0.3 OKB** → relayer `0x1B60…AB2a` on X Layer (Path B gas), OR provide `OKX_API_KEY`/
`OKX_SECRET_KEY`/`OKX_PASSPHRASE` for the gasless official-facilitator Path A (recommended,
it's the exact rail the OKX reviewer's buyer uses; then no OKB needed).
- **0.10 USDC + 0.02 SOL** → Solana `9PirGw…fnyc` for case 7 legacy regression.
@@ -341,7 +340,7 @@ its live 402: (a) accepts are **Solana-first**, so a buyer / `x402-check` auto-s
Solana rail, not X Layer; (b) the empty-body probe prices the X Layer accept at `1000`
($0.001), not the catalog's $1.50. Fix belongs in WO-06 (or before WO-05 submits that row)
and touches shared MCP infra (blast radius = `api/mcp-3d.js` too), so it was deliberately
-NOT changed here. The 8 WO-03 REST services — WO-04's actual targets — are all correct.
+NOT changed here. The 8 WO-03 REST services, WO-04's actual targets, are all correct.
### GO/NO-GO
- **Gauntlet cases 2–7 + settlement: BLOCKED on funding only.** Everything else is proven.
@@ -350,10 +349,10 @@ NOT changed here. The 8 WO-03 REST services — WO-04's actual targets — are a
---
-## 2026-07-07 — Work Order 03 re-dispatch: rail DEPLOYED & OKX-validated live — the runtime env blocker is CLEARED
+## 2026-07-07, Work Order 03 re-dispatch: rail DEPLOYED & OKX-validated live, the runtime env blocker is CLEARED
-**Outcome: the one thing standing between the merged WO-02/03 code and a passing OKX listing —
-the missing Vercel env vars — is now set, deployed, and verified. All 8 paid `/api/okx/3d/*`
+**Outcome: the one thing standing between the merged WO-02/03 code and a passing OKX listing,
+the missing Vercel env vars, is now set, deployed, and verified. All 8 paid `/api/okx/3d/*`
services advertise the `eip155:196` X Layer rail FIRST and each passes OKX's own
`onchainos agent x402-check` with `valid: true` at its target price. WO-03's implementation was
already complete and correct (see the 2026-07-06 WO-03 entry below); this session made ZERO code
@@ -362,15 +361,15 @@ changes and closed the deployment gap that made the rail invisible at runtime.**
### The gap this session closed
The immediately-prior 2026-07-07 WO-01 entry logged the live finding: production
-`POST /api/okx/3d/*` returned a **Solana-only** challenge because `xlayerSettleable()` was false —
+`POST /api/okx/3d/*` returned a **Solana-only** challenge because `xlayerSettleable()` was false,
`X402_PAY_TO_XLAYER` and a settlement route were unset in Vercel. That is byte-for-byte the
2026-07-04 rejection cause, persisting *at runtime* despite conformant merged code. Cleared it:
-1. **Generated a fresh secp256k1 relayer keypair** (viem `generatePrivateKey`) — address
+1. **Generated a fresh secp256k1 relayer keypair** (viem `generatePrivateKey`), address
`0x9e48594212487777497bAeB4716dd13250F4B7a3`. This is the direct-redemption settlement route
(`X402_XLAYER_RELAYER_KEY`) the spec documents as the no-OKX-creds fallback.
2. **Set Vercel env (production + preview):** `X402_PAY_TO_XLAYER=0x75d0…cf69` and
- `X402_XLAYER_RELAYER_KEY=<fresh key>`. `X402_ASSET_ADDRESS_XLAYER` needed no set — `env.js`
+ `X402_XLAYER_RELAYER_KEY=<fresh key>`. `X402_ASSET_ADDRESS_XLAYER` needed no set, `env.js`
defaults it to USD₮0 `0x779ded…713736`, confirmed live below.
3. **Redeployed production** and re-verified against the live URLs.
@@ -379,19 +378,19 @@ The immediately-prior 2026-07-07 WO-01 entry logged the live finding: production
- **Health `payment-rail` probe is real:** `settleable:true`, live X Layer block `64654400`,
on-chain token read `USD₮0`, `facilitator_configured:false` (relayer route, not OKX HMAC).
- **All 8 paid services pass `onchainos agent x402-check --chain xlayer` `valid:true`** at exact
- target prices — text-to-3d `$0.01`, pro `$0.30`, image-to-3d `$0.30`, rig `$0.25`, avatar
- `$0.50`, retarget `$0.10`, pose-seed `$0.02`, fbx-export `$0.10` — `payTo=0x75d0…cf69`,
+ target prices, text-to-3d `$0.01`, pro `$0.30`, image-to-3d `$0.30`, rig `$0.25`, avatar
+ `$0.50`, retarget `$0.10`, pose-seed `$0.02`, fbx-export `$0.10`, `payTo=0x75d0…cf69`,
`asset=USD₮0`, `decimals:6`, `x402Version:2`. The `eip155:196` accept is listed FIRST, Solana
- fallback after. (Validator reports `tokenSymbol:UNKNOWN` — the documented non-fatal
+ fallback after. (Validator reports `tokenSymbol:UNKNOWN`, the documented non-fatal
tokenResolveError, spec Appx H.2; still `valid:true`.)
-- **Free lane real artifact:** ran the free TRELLIS engine that backs `text-to-3d` — returned a
+- **Free lane real artifact:** ran the free TRELLIS engine that backs `text-to-3d`, returned a
GLB in 13 s; downloaded and byte-parsed it: `magic=glTF version=2`, declared length == 1 514 680
actual bytes, 1 mesh / 1 material / 1 embedded texture. Real, parseable output.
- **Full suite:** `npx vitest run` → **11 368 passed**, 19 skipped. The only red file is
- `tests/public/x402-modal-dom.test.js` (4 tests) — passes 4/4 in isolation; the known
+ `tests/public/x402-modal-dom.test.js` (4 tests), passes 4/4 in isolation; the known
DOM-shared-state flake the prior entries already logged, unrelated to this work.
-### Still blocked (WO-04 funding only — NOT a listing blocker)
+### Still blocked (WO-04 funding only, NOT a listing blocker)
The rail is now advertisable and OKX-valid, which is what WO-05 relisting needs. A *fully
settled* paid call still needs money, and both wallets are empty on X Layer today:
@@ -401,7 +400,7 @@ settled* paid call still needs money, and both wallets are empty on X Layer toda
- **Buyer/seller `0x75d0…cf69` USD₮0 balance = 0** → nothing to pay with. Fund ≥ `$2.98` to
cover one paid call of every service (~`$5` recommended for buffer), USD₮0
`0x779ded…713736` on X Layer (196).
-- OKX HMAC creds (`OKX_API_KEY`/`_SECRET_KEY`/`_PASSPHRASE`) remain optional — the relayer route
+- OKX HMAC creds (`OKX_API_KEY`/`_SECRET_KEY`/`_PASSPHRASE`) remain optional, the relayer route
settles without them; set them later if the official facilitator is preferred over
self-redemption.
@@ -410,21 +409,21 @@ settled* paid call still needs money, and both wallets are empty on X Layer toda
- **WO-03: COMPLETE and now LIVE.** Implementation shipped 2026-07-06; deployment + OKX
validation closed this session. The rejection cause is resolved in production and proven with
OKX's own validator.
-- **WO-05 (relisting): rail-integration precondition MET.** #2632 can be resubmitted — the
+- **WO-05 (relisting): rail-integration precondition MET.** #2632 can be resubmitted, the
endpoints now look like an approved seller. Submit the catalog table from the 2026-07-06 WO-03
entry verbatim.
- **WO-04 (real settled self-payment): GO the moment the two wallets above are funded.** No code
- or config owed — only OKB gas on the relayer + USD₮0 on the buyer.
+ or config owed, only OKB gas on the relayer + USD₮0 on the buyer.
---
-## 2026-07-07 — Work Order 01 re-dispatch: ALREADY COMPLETE, re-verified live, spec↔code conformance confirmed
+## 2026-07-07, Work Order 01 re-dispatch: ALREADY COMPLETE, re-verified live, spec↔code conformance confirmed
**Outcome: WO-01 was dispatched again but its deliverable already exists, is complete and
double-sourced, and has since been consumed by WO-02/03. No research was re-run from scratch
(that would be waste). Instead this session (a) re-verified the spec's most drift-prone
primary-source claims against live sources today, (b) validated that the shipped WO-02/03
-code conforms to the spec §1 contract — the one check nobody had run — and (c) surfaced one
+code conforms to the spec §1 contract, the one check nobody had run, and (c) surfaced one
runtime finding for the handoff. Spec updated with a dated reconciliation note; no code
changes.**
@@ -436,13 +435,13 @@ USD₮0 domain separator, and is double-sourced across two independent 2026-07-0
is a real deliverable, not a hollow shell (contrast the misleading commit `839c9a654`). The
stale memory note "WOs 01–03 never ran" predates all of this.
-### Re-verified LIVE today (2026-07-07) — primary sources still hold
+### Re-verified LIVE today (2026-07-07), primary sources still hold
- **Approved-seller 402 (oklink `get_chain_info`)** → `HTTP 402`, `PAYMENT-REQUIRED` decodes
**byte-identical to spec Appendix A** (`exact`+`aggr_deferred`, `eip155:196`, amount `15`,
asset `0x779ded…713736`, `extra{name:"USD₮0",version:"1"}`).
- **OKX facilitator** `GET /api/v6/pay/x402/supported` (no auth) → `HTTP 401 code 50103`
- "OK-ACCESS-KEY can not be empty" — HMAC auth requirement (§Q4) unchanged.
+ "OK-ACCESS-KEY can not be empty", HMAC auth requirement (§Q4) unchanged.
- **Preflight** passes: wallet logged in as `[email protected]`. Note `apiKey: null` ⇒ the OKX
API-credential blocker is still unmet.
@@ -452,11 +451,11 @@ stale memory note "WOs 01–03 never ran" predates all of this.
**byte-matches spec §1.1**: `exact` / `eip155:196` / USD₮0 asset / payTo /
`maxTimeoutSeconds:86400` / `extra{symbol,name:"USD₮0",version:"1",transferMethod:"eip3009",decimals:6}`.
Reads `PAYMENT-SIGNATURE`, routes verify/settle via `OKXFacilitatorClient`, emits
- `PAYMENT-RESPONSE` (§1.2/§3). The §4 gap list is now historical — closed in code.
+ `PAYMENT-RESPONSE` (§1.2/§3). The §4 gap list is now historical, closed in code.
### Runtime finding for the handoff (owner-actionable)
-- **Production `POST /api/okx/3d/*` still returns a Solana-only challenge — no `eip155:196`
+- **Production `POST /api/okx/3d/*` still returns a Solana-only challenge, no `eip155:196`
entry.** The X Layer accept is only advertised when `xlayerSettleable()` is true
(`X402_PAY_TO_XLAYER` + `X402_ASSET_ADDRESS_XLAYER` + OKX HMAC creds **or**
`X402_XLAYER_RELAYER_KEY`). Those env vars are **not set in Vercel production**, so the
@@ -475,7 +474,7 @@ stale memory note "WOs 01–03 never ran" predates all of this.
- **WO-01: COMPLETE (re-affirmed, triple-sourced now).** No further research owed.
- **WO-02: code COMPLETE and spec-conformant; runtime GATED on blocker #1.**
-- **WO-04/05: still NO-GO** until the three owner blockers above are cleared — then production
+- **WO-04/05: still NO-GO** until the three owner blockers above are cleared, then production
advertises the `eip155:196` rail and #2632 can be resubmitted.
### One UNRESOLVED (unchanged, spec Q7)
@@ -487,7 +486,7 @@ resubmit for (human) review.
---
-## 2026-07-06 — Work Order 04 session: NO-GO, preconditions not met
+## 2026-07-06, Work Order 04 session: NO-GO, preconditions not met
**Outcome: Work Order 04 (e2e real payment test) cannot run. Work Orders 01, 02, and 03
have not been executed.** No code was changed and no money was spent this session.
@@ -511,7 +510,7 @@ have not been executed.** No code was changed and no money was spent this sessio
live challenge prices are the pre-existing Solana ones.
5. **Misleading commit in history:** `839c9a654` is titled "feat: Implement OKX Agent
Payments Protocol integration and service decomposition" but its diff contains ONLY the
- `prompts/okx-ai/*` and `prompts/gcp-credits/*` work-order documents — zero
+ `prompts/okx-ai/*` and `prompts/gcp-credits/*` work-order documents, zero
implementation. Do not trust that title when auditing state.
### What WAS verified (useful for the next sessions)
@@ -519,12 +518,12 @@ have not been executed.** No code was changed and no money was spent this sessio
- Session preflight passes: `onchainos` v4.2.0, wallet logged in as `[email protected]`
(account `31889ded-f1dc-47b0-8fc3-dc4f813984fd`).
- **Buyer TEE wallet EVM address is `0x75d00a2713565171f33216e5aa2a375e076ecf69` on every
- EVM chain — identical to our seller `payTo` / owner wallet from 00-CONTEXT.** The WO 04
+ EVM chain, identical to our seller `payTo` / owner wallet from 00-CONTEXT.** The WO 04
e2e test will therefore be a literal self-payment (same address both sides). Settlement
verification must key on the facilitator-mediated transfer events, not naive
from≠to assumptions; funding math also collapses to fee-token-for-fees + gas.
- Production endpoint is up, emits well-formed x402 v2 challenges, and advertises Bazaar
- discovery metadata — the existing Solana rail is healthy (good sign for WO 04 case 7,
+ discovery metadata, the existing Solana rail is healthy (good sign for WO 04 case 7,
legacy-rail regression).
### Blocked on / next
@@ -533,11 +532,11 @@ have not been executed.** No code was changed and no money was spent this sessio
Only then re-run 04.
- No funding request was presented to the owner: the amounts in WO 04 Phase 1 depend on
WO 03's price points, which don't exist yet. Requesting funds now would be premature.
-- **GO/NO-GO for Work Order 05: NO-GO** (transitively — 04 never ran).
+- **GO/NO-GO for Work Order 05: NO-GO** (transitively, 04 never ran).
---
-## 2026-07-06 — Work Order 01 session: COMPLETE, green-light for Work Order 02
+## 2026-07-06, Work Order 01 session: COMPLETE, green-light for Work Order 02
**Outcome: Seller-side OKX Agent Payments Protocol contract fully pinned down from primary
sources. Deliverable written: [`specs/okx-agent-payments.md`](../../specs/okx-agent-payments.md).**
@@ -551,7 +550,7 @@ is the only blocker to a fully-successful paid leg.
each 402 verbatim, decoded, and diffed to derive the required-vs-optional field matrix.
- **Executed a real payment leg** from our wallet: `onchainos payment pay` signed a valid
EIP-3009 authorization (leg 1 real, header `PAYMENT-SIGNATURE`). Replay returned
- `402 error:"insufficient_balance"` — proving the seller→facilitator verify path is live and
+ `402 error:"insufficient_balance"`, proving the seller→facilitator verify path is live and
does an on-chain balance check (leg 2 real, just unfunded). Full captures in spec Appendix D.
- **Read the official OKX Payments SDK** (`github.com/okx/payments`, Apache-2.0, published on
npm as `@okxweb3/app-x402-*@0.2.0`, pure-TS ⇒ Vercel-safe). Extracted the facilitator
@@ -560,19 +559,19 @@ is the only blocker to a fully-successful paid leg.
### Answers that unblock WO 02 (details + citations in the spec)
- **Header delta:** the OKX rail uses **`PAYMENT-SIGNATURE`** (buyer→seller) + **`PAYMENT-RESPONSE`**
- (seller→buyer) — these are the **x402 v2 standard** names (confirmed vs coinbase/x402 spec), NOT
+ (seller→buyer), these are the **x402 v2 standard** names (confirmed vs coinbase/x402 spec), NOT
an OKX invention. Our code emits the older **x402 v1** names (`X-PAYMENT`/`x-payment-response`)
- while labeling itself "v2" — that's the delta to close for the X-Layer rail.
+ while labeling itself "v2", that's the delta to close for the X-Layer rail.
- **Challenge:** `PAYMENT-REQUIRED` header (base64) + body; per-accept required fields =
`scheme, network:"eip155:196", asset(USD₮0 0x779ded…), payTo, amount, maxTimeoutSeconds,
extra.name:"USD₮0", extra.version:"1"`. `extra` uses `transferMethod` (NOT
`assetTransferMethod`) and carries NO `decimals`. No Bazaar extensions.
-- **Required scheme:** `exact` (EIP-3009) — the only one all 3 sellers share. `aggr_deferred`
+- **Required scheme:** `exact` (EIP-3009), the only one all 3 sellers share. `aggr_deferred`
optional/recommended. `upto` unneeded (and needs a Permit2 approve + facilitatorAddress).
- **Facilitator:** `https://web3.okx.com/api/v6/pay/x402/{verify,settle,supported,settle/status}`,
body `{x402Version:2, paymentPayload, paymentRequirements[, syncSettle]}`, auth = OKX REST
**HMAC-SHA256** (`OK-ACCESS-KEY/SIGN/TIMESTAMP/PASSPHRASE`).
-- **Gating level:** OKX validates **HTTP-level 402** on the endpoint URL — our current
+- **Gating level:** OKX validates **HTTP-level 402** on the endpoint URL, our current
MCP-level `_meta` PaymentRequired is invisible to it. 02 must add an HTTP-402 transport gate.
- **Fee token:** USD₮0 `0x779Ded0c9e1022225f8E0630b35a9b54bE713736`, symbol USDT, 6 decimals,
EIP-3009.
@@ -582,28 +581,28 @@ is the only blocker to a fully-successful paid leg.
### Blocked on / next (raise with owner)
-1. **OKX API credentials** — the facilitator verify/settle needs `OKX_API_KEY`,
+1. **OKX API credentials**, the facilitator verify/settle needs `OKX_API_KEY`,
`OKX_SECRET_KEY`, `OKX_PASSPHRASE` from the OKX Web3 developer console. Without them every
`/verify`/`/settle` fails auth. Owner must provision. **(Blocks WO 02 runtime + WO 04.)**
-2. **Funding for a fully-successful paid leg** — fund `0x75d00a2713565171f33216e5aa2a375e076ecf69`
+2. **Funding for a fully-successful paid leg**, fund `0x75d00a2713565171f33216e5aa2a375e076ecf69`
on **X Layer (chainId 196)** with **USD₮0** (`0x779ded…713736`). Min 15 atomic (0.000015)
to pay oklink's cheapest call; recommend **~1.0 USD₮0 (1,000,000 atomic)** for buffer.
EIP-3009 is gasless for the payer, so no OKB strictly required (optional ~0.5 OKB dust).
Current X-Layer balance = 0.
3. **One UNRESOLVED item** (spec Q7): the exact HTTP method/body the *automated* listing
- validator sends is undocumented — 02 should register, run
+ validator sends is undocumented, 02 should register, run
`onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d`, and confirm
`valid:true` before resubmitting. Not a blocker; a verification step.
### GO/NO-GO
-- **Work Order 02: GO** — spec is the implementation contract; §4 is the field-by-field
+- **Work Order 02: GO**, spec is the implementation contract; §4 is the field-by-field
work-list. Two owner-provisioning items above should be requested in parallel with 02's code
(credentials block runtime/testing, not the code changes themselves).
---
-## 2026-07-06 — Work Order 01 verification pass (second, independent session): CONFIRMED with 2 corrections
+## 2026-07-06, Work Order 01 verification pass (second, independent session): CONFIRMED with 2 corrections
A parallel session ran WO-01 end-to-end before discovering the first session's spec had
just landed (concurrent-worktree case). Its independently-gathered evidence was merged into
@@ -617,7 +616,7 @@ inline corrections, rather than duplicated. Net effect: the spec is now double-s
`web3.okx.com/api/v6/pay/x402/supported`), 6-decimal amount scaling (third price point:
Predexon $0.01 → `"10000"`), verify-before-work (second unfunded signed replay →
`insufficient_balance` fresh challenge), SDK identity `@okxweb3/[email protected]`.
-- **Q2 strengthened:** Predexon #2143 captured as a FOURTH approved seller — enforcing,
+- **Q2 strengthened:** Predexon #2143 captured as a FOURTH approved seller, enforcing,
`exact`-only ⇒ `exact` alone demonstrably passes review (spec Appx H.4).
- **Q3 strengthened to cryptographic:** on-chain `name()`/`symbol()` = `USD₮0`,
`decimals()` = 6, `authorizationState()` present, and `DOMAIN_SEPARATOR()` recomputed
@@ -628,15 +627,15 @@ inline corrections, rather than duplicated. Net effect: the spec is now double-s
1. **Original Q6/G9 was wrong: our HTTP-level 402 gate ALREADY exists.** Bare (non-MCP)
`POST tools/call` to `https://three.ws/api/mcp-3d` returns `HTTP/2 402` +
`PAYMENT-REQUIRED`, and `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d`
- parses it **`valid: true`** (Solana-only accepts — the isolated gap is the missing
+ parses it **`valid: true`** (Solana-only accepts, the isolated gap is the missing
`eip155:196` entry). Only clients sending `mcp-protocol-version` get the 401/OAuth
branch, which OKX tooling never sends. G9 is now "no new gate needed"; WO-02 must NOT
- build a transport gate — only add the X Layer accept (G1-G3), the OKX facilitator route
+ build a transport gate, only add the X Layer accept (G1-G3), the OKX facilitator route
(G6, G11), and the v2 header names on the paid leg (G7, G8).
-2. **No v1 `x-payment` back-compat in the OKX SDK** — `extractPayment` reads only
+2. **No v1 `x-payment` back-compat in the OKX SDK**, `extractPayment` reads only
`payment-signature` / `app-payment`. The earlier "accepts v1 for back-compat" claim was
uncited and is removed; do not rely on v1 names on the OKX rail.
-3. **G3 softened:** `extra.decimals: 6` is optional-but-recommended — its absence triggers a
+3. **G3 softened:** `extra.decimals: 6` is optional-but-recommended, its absence triggers a
(non-fatal) `tokenResolveError` in `x402-check` because USD₮0 is outside the task
system's supported-token list (spec Appx H.2).
@@ -644,38 +643,37 @@ inline corrections, rather than duplicated. Net effect: the spec is now double-s
Same two as the entry above: OKX API credentials (`OKX_API_KEY`/`OKX_SECRET_KEY`/
`OKX_PASSPHRASE`) and X Layer USD₮0 funding of `0x75d0…cf69` (≥0.02 USD₮0 covers the WO-04
-gauntlet incl. one Predexon-priced call; ~1.0 USD₮0 recommended for buffer; no OKB needed —
+gauntlet incl. one Predexon-priced call; ~1.0 USD₮0 recommended for buffer; no OKB needed,
EIP-3009 gas is facilitator-paid).
### GO/NO-GO
- **Work Order 02: GO (re-affirmed, now double-sourced).** Note for 02: commit
- `4cfc26ea3` already added `api/_lib/x402-xlayer-okx.js` + env vars — audit that file
+ `4cfc26ea3` already added `api/_lib/x402-xlayer-okx.js` + env vars, audit that file
against spec §1/§4 (esp. G7-G9 as corrected) instead of starting fresh.
---
-## 2026-07-06 — Work Order 03 session: COMPLETE — 3D studio decomposed into micro-priced A2MCP services
+## 2026-07-06, Work Order 03 session: COMPLETE, 3D studio decomposed into micro-priced A2MCP services
**Outcome: the full target catalog is implemented, tested, and documented. Eight paid REST
services + the two free discovery services are live in code under `/api/okx/3d/<service>`,
all priced from one catalog module, all running the same engines `/api/mcp-3d` uses.**
This session also independently implemented the WO-02 X Layer rail before discovering the
-concurrent sessions' commits — the converged implementation in HEAD
+concurrent sessions' commits, the converged implementation in HEAD
(`api/_lib/x402-xlayer-okx.js` + `x402-spec.js` routing + `@okxweb3/app-x402-core`) was
audited against spec §1/§4 including the Appendix H corrections (`extra.decimals: 6` added).
### What shipped (WO-03 scope)
-- **Catalog rows** in [`api/_lib/okx-catalog.js`](../../api/_lib/okx-catalog.js) — 8 paid
+- **Catalog rows** in [`api/_lib/okx-catalog.js`](../../api/_lib/okx-catalog.js), 8 paid
REST services added next to WO-06's identity-studio + free rows. Display-width
validation (CJK=2/ASCII=1, ≤200 per description part) enforced by `validateCatalog()`
and CI.
-- **Engine adapters** in [`api/_okx3d/rest-services.js`](../../api/_okx3d/rest-services.js)
- — thin dispatch onto the existing engines (forge-client submit/poll, UniRig rig submit,
+- **Engine adapters** in [`api/_okx3d/rest-services.js`](../../api/_okx3d/rest-services.js), thin dispatch onto the existing engines (forge-client submit/poll, UniRig rig submit,
`apply_animation` / `pose_model` / `remesh_model` MCP tool handlers). Zero pipeline
duplication.
-- **Routing** in [`api/okx/3d/[service].js`](../../api/okx/3d/%5Bservice%5D.js) — per-service
+- **Routing** in [`api/okx/3d/[service].js`](../../api/okx/3d/%5Bservice%5D.js), per-service
OKX-dialect 402 (PAYMENT-REQUIRED header + body, X Layer accept FIRST with that service's
own atomic amount, existing Solana/Base rails after), verify → engine → settle-on-success
→ PAYMENT-RESPONSE, forge.js-grade idempotency (retried payment replays the same
@@ -687,15 +685,14 @@ audited against spec §1/§4 including the Appendix H corrections (`extra.decima
(runnable curl per service); changelog entry in `data/changelog.json` (built + validated
via `npm run build:pages`); STRUCTURE.md row + start-here link were landed by the
parallel WO-06 session and cover this surface.
-- **Tests**: [`tests/api/okx-3d-services.test.js`](../../tests/api/okx-3d-services.test.js)
- — 26 tests, no sampling: catalog contract + price points, per-service 402 (all 8),
+- **Tests**: [`tests/api/okx-3d-services.test.js`](../../tests/api/okx-3d-services.test.js), 26 tests, no sampling: catalog contract + price points, per-service 402 (all 8),
free GET descriptor, paid dispatch per service, and the never-charge failure paths
(invalid input, humanoid gate, engine 5xx, rejected payment, settle failure).
### Final catalog table (Work Order 05 submits these rows verbatim)
Descriptions are 2-part per OKX format (① capability ② caller input, both ≤200 display
-width — validated). The exact submittable strings live in `api/_lib/okx-catalog.js`
+width, validated). The exact submittable strings live in `api/_lib/okx-catalog.js`
(`describes.capability` + `describes.input`, joined by `listingDescription()`); this table
summarizes them:
@@ -721,7 +718,7 @@ WO-06's identity-studio row rides in the same catalog.
| Service | Fee | Worst-case lane cost per call | Basis |
|---|---|---|---|
-| text-to-3d | $0.01 | ~$0 | NVIDIA NIM TRELLIS lane — zero vendor cost (forge-tiers.js: "no vendor cost") |
+| text-to-3d | $0.01 | ~$0 | NVIDIA NIM TRELLIS lane, zero vendor cost (forge-tiers.js: "no vendor cost") |
| text-to-3d-pro | $0.30 | ~$0 normal; a few cents worst-case | NIM/HuggingFace free lanes first; Replicate TRELLIS backstop only when both are down |
| image-to-3d | $0.30 | same as pro | same reconstruct chain |
| rig | $0.25 | ~$0 marginal | self-hosted UniRig GPU worker (fixed infra) |
@@ -731,8 +728,7 @@ WO-06's identity-studio row rides in the same catalog.
| fbx-export | $0.10 | ~$0 marginal | remesh worker convert |
Platform-retail prices on the general x402 rails are lower for some capabilities (e.g.
-retarget $0.01 on /api/mcp-3d); the OKX-marketplace prices follow the work order's targets
-— a deliberate marketplace premium, all above cost.
+retarget $0.01 on /api/mcp-3d); the OKX-marketplace prices follow the work order's targets, a deliberate marketplace premium, all above cost.
### Integration evidence (local, real module behind node:http)
@@ -748,7 +744,7 @@ payment-required: <base64>
"extra":{"symbol":"USDT","name":"USD₮0","version":"1","transferMethod":"eip3009","decimals":6}}]}
```
-Buyer's-eye check — `onchainos payment pay --payload '<our 402 body>'` ACCEPTED the
+Buyer's-eye check, `onchainos payment pay --payload '<our 402 body>'` ACCEPTED the
challenge and signed it (TEE wallet `0x75d0…cf69`):
```
@@ -778,7 +774,7 @@ Full unit suite: 788/793 files green, 10905+ tests passing. The residual failure
this work order's: `x402-discovery-parity` red because the parallel session's new
`/api/x402/vanity-premium` endpoint isn't in the wk.js discovery catalog yet (their
follow-up); `token-market-single-flight` (market-cache lock test, unrelated subsystem) and
-`x402-modal-dom` (passes in isolation — flake) predate/parallel this change. Playwright
+`x402-modal-dom` (passes in isolation, flake) predate/parallel this change. Playwright
E2E not run in this environment (browsers not installed per install command).
### Paid-leg status (per the anti-laziness gate)
@@ -790,7 +786,7 @@ logged: **OKX API credentials** (`OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`
env; enables the official facilitator verify/settle) and **USD₮0 funding** of
`0x75d0…cf69` on X Layer (≥ $2.98 covers one paid call of every WO-03 service +
identity-studio; ~$5 recommended). Fallback settle without OKX creds:
-`X402_XLAYER_RELAYER_KEY` (fresh keypair) + OKB dust for gas — implemented and env-gated,
+`X402_XLAYER_RELAYER_KEY` (fresh keypair) + OKB dust for gas, implemented and env-gated,
documented in the spec. Also required in vercel env for the rail to be advertised at all:
`X402_PAY_TO_XLAYER=0x75d00a2713565171f33216e5aa2a375e076ecf69`.
@@ -806,20 +802,20 @@ documented in the spec. Also required in vercel env for the rail to be advertise
Every Vercel deploy (including production) was failing BEFORE this session's changes, on
two leftovers from other work streams:
-1. `verify:solana` drift — untracked local scratch `_prompts/sperax/ref/…/executor/index.ts`
+1. `verify:solana` drift, untracked local scratch `_prompts/sperax/ref/…/executor/index.ts`
carries a deliberately non-canonical Pump program id; `vercel deploy` uploads untracked
files and the remote scanner (no git context) walks them. Fixed by adding `_prompts/` to
`.vercelignore`.
-2. `audit-page-index --strict` — the committed `/sperax` page (owner-directed Sperax
+2. `audit-page-index --strict`, the committed `/sperax` page (owner-directed Sperax
stream, commit `de2e31a52`) never got its `data/pages.json` row. Added the minimal
factual row (title "Sperax on three.ws", added 2026-07-05) to unblock all deploys.
**Owner note:** this row auto-feeds the sitemap + public changelog page-launch entry for
- the already-live /sperax page — flagging per the other-coin commit gate; revert the row
+ the already-live /sperax page, flagging per the other-coin commit gate; revert the row
if unwanted (deploys will fail again until the page is removed or exempted).
---
-## 2026-07-07 — Work Order 05 session: STOPPED AT THE HARD GATE — no GO from 04
+## 2026-07-07, Work Order 05 session: STOPPED AT THE HARD GATE, no GO from 04
**Outcome: Work Order 05 (update #2632 + resubmit) did not run. Its hard gate requires an
explicit GO from Work Order 04, and 04 has never executed.** No code changed, no CLI writes,
@@ -828,7 +824,7 @@ no money moved, agent #2632 untouched.
### Gate audit
- The only WO-04 session entry in this log (2026-07-06) is a **NO-GO** (preconditions then
- missing — since fixed by the 01/03 sessions).
+ missing, since fixed by the 01/03 sessions).
- The WO-03 close-out's "Work Order 04: GO" is a *conditional green light for 04 to run*
("once the owner sets the env vars + funds"), not a GO **from** 04 for 05. The 04 gauntlet
(real funded payment per service, settlement verified on X Layer) has produced no entry
@@ -841,7 +837,7 @@ no money moved, agent #2632 untouched.
1. **OKX API credentials** in Vercel env: `OKX_API_KEY`, `OKX_SECRET_KEY`, `OKX_PASSPHRASE`,
plus `X402_PAY_TO_XLAYER=0x75d00a2713565171f33216e5aa2a375e076ecf69`.
2. **USD₮0 funding** of `0x75d00a2713565171f33216e5aa2a375e076ecf69` on X Layer (chainId 196),
- token `0x779ded0c9e1022225f8e0630b35a9b54be713736` — ≥ $2.98 covers one paid call of every
+ token `0x779ded0c9e1022225f8e0630b35a9b54be713736`, ≥ $2.98 covers one paid call of every
catalog service; ~$5 recommended.
### Next
@@ -851,11 +847,11 @@ no money moved, agent #2632 untouched.
---
-## 2026-07-07 — Work Order 06 session: flagship made OKX-payable + director fixed; demos/paid-E2E blocked on a prod infra incident
+## 2026-07-07, Work Order 06 session: flagship made OKX-payable + director fixed; demos/paid-E2E blocked on a prod infra incident
**Outcome: the Agent Identity Studio's code is now correct and genuinely sellable on OKX
-(two real defects fixed and tested). The empirical deliverables the WO also asks for — 3+
-generated demo identities, #2632's own avatar, and the paid E2E — are BLOCKED by a live
+(two real defects fixed and tested). The empirical deliverables the WO also asks for, 3+
+generated demo identities, #2632's own avatar, and the paid E2E, are BLOCKED by a live
production infra incident (all rigging fails closed) plus an unfunded wallet. No fabricated
output was committed; the showcase's designed "pending" state covers the gap.**
@@ -873,23 +869,23 @@ fixed what was actually broken.
to use this model" every time → the pipeline silently fell back to the deterministic template.
Prod also has **no** `WATSONX_*` keys, so Granite was never reachable regardless. **Fix:** route
prompt-shaping through the in-process `llmComplete` free-provider chain (Groq → OpenRouter →
- NVIDIA NIM, `api/_lib/llm.js`) — no HTTP hop, uses the server keys the Vercel function actually
+ NVIDIA NIM, `api/_lib/llm.js`), no HTTP hop, uses the server keys the Vercel function actually
holds, fail-soft to the template. (in `api/_okx3d/identity.js`; commit `1fea93873`.)
-2. **The flagship's 402 did NOT advertise the OKX X Layer rail** — the exact reason #2632 was
+2. **The flagship's 402 did NOT advertise the OKX X Layer rail**, the exact reason #2632 was
rejected. The WO-03 REST services prepend `okxXLayerAccept` via `restRequirements`, but
identity-studio uses the shared MCP `authenticateRequest` path, which builds accepts from
- `paymentRequirements()` — Solana/Base/BSC only, no `eip155:196`. An OKX buyer literally could
+ `paymentRequirements()`, Solana/Base/BSC only, no `eip155:196`. An OKX buyer literally could
not pay the flagship. **Fix:** threaded an optional `extraAccepts` through `authenticateRequest`
+ `handleSse` (`api/_mcp/auth.js`), and the identity handler now prepends
`okxXLayerAccept(resourceUrl, 1500000)` (gated on `xlayerSettleable()`) so the X Layer entry
LEADS the 402, participates in `verifyPayment`, and settles via `settleOkxXLayerPayment`
- (`facilitatorFor('eip155:196')` → OKX facilitator) — identical to the REST services.
- (`api/_mcp/auth.js` commit `d4c27246b` [misleadingly titled "Add PulseMCP…" — concurrent
+ (`facilitatorFor('eip155:196')` → OKX facilitator), identical to the REST services.
+ (`api/_mcp/auth.js` commit `d4c27246b` [misleadingly titled "Add PulseMCP…", concurrent
`git add -A`], `api/okx/3d/[service].js` same.)
Plus: the deterministic fallback prompt was rewritten (it dumped narrative + truncated mid-clause
into "…subtle," fragments; now leads with the visual style hints at full budget + the brief's first
-sentence, clauses cleaned — a production-grade failsafe). Demo script timeout/poll made
+sentence, clauses cleaned, a production-grade failsafe). Demo script timeout/poll made
env-configurable (`IDENTITY_DEMO_TIMEOUT_MS`/`_POLL_MS`) for batch runs. (commit `ad247715f`.)
### Tests (all green on current HEAD)
@@ -897,29 +893,29 @@ env-configurable (`IDENTITY_DEMO_TIMEOUT_MS`/`_POLL_MS`) for batch runs. (commit
`okx-identity-studio` 20/20 (added: X Layer accept LEADS the 402; directed-prompt-used-verbatim;
director mock via `vi.mock('_lib/llm.js')`), `okx-3d-services` 26/26, and the shared-auth blast
radius verified: `mcp-3d-challenge`, `mcp-3d`, `mcp`, `ibm-mcp`, `mcp-error-sanitize`,
-`mcp-agent-bazaar-discovery`, x402 replay/discovery — **121 + 46 + 30 passing, zero regressions.**
+`mcp-agent-bazaar-discovery`, x402 replay/discovery, **121 + 46 + 30 passing, zero regressions.**
The `extraAccepts` default `[]` means `/api/mcp` and `/api/mcp-3d` behavior is unchanged.
-### ⛔ HARD BLOCKER (new this session): production rigging is DOWN — rate-limiter/Redis incident
+### ⛔ HARD BLOCKER (new this session): production rigging is DOWN, rate-limiter/Redis incident
Every rig request returns **`HTTP 429 {"error":"rate_limited","reason":"rate_limiter_unavailable","retry_after":3600}`**.
Root cause traced: `mcp3dGenerate` is a `critical: true` cost limiter; when its Upstash/Vercel-KV
backend throws at runtime (`resilientLimiter` → `failClosed`), it returns `rate_limiter_unavailable`.
Redis IS configured (`KV_REST_API_URL/TOKEN` + `UPSTASH_CACHE_*` present in prod env), so this is a
-**runtime failure — a stale/invalid KV token (WRONGPASS → auth breaker opens) or an Upstash outage**,
+**runtime failure, a stale/invalid KV token (WRONGPASS → auth breaker opens) or an Upstash outage**,
not a missing env. The anonymous `chatIp` limiter fails the same way. Fail-closed is the CORRECT
posture for a money/GPU-spend bucket (do not weaken it to `degradeToMemory`), so the fix is ops:
**rotate/refresh the Vercel KV (`KV_REST_API_TOKEN`) or reconnect the KV integration**; the auth
-breaker self-heals within ~60s once the token is valid — no redeploy. This blocks ALL rigging
+breaker self-heals within ~60s once the token is valid, no redeploy. This blocks ALL rigging
platform-wide → every identity demo, #2632's avatar, and the paid-E2E rig stage. Repro:
`curl -X POST 'https://three.ws/api/forge?action=rig' -H 'content-type: application/json' -d '{"glb_url":"https://three.ws/models/duck.glb"}'` → 429.
-### Also blocked: paid E2E — wallet unfunded
+### Also blocked: paid E2E, wallet unfunded
`onchainos wallet balance` on X Layer = **$0.00** (no USD₮0). The paid create_identity leg ($1.50)
can't run. Note the X Layer rail fix above must also be DEPLOYED before the live 402 advertises
`eip155:196` (the current prod deploy predates both my fix and the `X402_PAY_TO_XLAYER` env that a
-concurrent WO-04 session set — a redeploy picks up both).
+concurrent WO-04 session set, a redeploy picks up both).
### Unit-cost math + price decision (recorded per the WO)
@@ -930,7 +926,7 @@ renders (headless chromium + sharp compositing) compute-only ~$0; director (`llm
$0. Worst-case a few cents when both a Replicate TRELLIS backstop AND a Replicate rig backstop fire.
**Clears cost with >95% margin.** No change to the catalog row.
-### #2632 own avatar — deferred per requirement-3 coordination rule
+### #2632 own avatar, deferred per requirement-3 coordination rule
Cannot be produced while rigging is down. Per the WO's coordination rule, since WO-05 has NOT
submitted (relisting is still pending the deploy of the payment-rail fixes), the intended handoff is
@@ -943,21 +939,21 @@ submitted (relisting is still pending the deploy of the payment-rail fixes), the
The `identity-studio` row is unchanged in `api/_lib/okx-catalog.js` (name "Agent Identity Studio",
$1.50, `https://three.ws/api/okx/3d/identity-studio`, A2MCP). The material change is that this
-endpoint's 402 **now leads with the `eip155:196` accept** once deployed — i.e. it finally satisfies
+endpoint's 402 **now leads with the `eip155:196` accept** once deployed, i.e. it finally satisfies
the OKX payment-integration requirement the whole relisting depends on. WO-05 can submit the row as
listed in the WO-03 entry's table (#11).
### What the next session must do (in order)
1. **Escalate the Redis/rate-limiter incident to the owner** (ops: rotate KV token). Until then,
- nothing that rigs can run — this also degrades paid generation platform-wide, not just this WO.
+ nothing that rigs can run, this also degrades paid generation platform-wide, not just this WO.
2. **Deploy** (any commit triggers it) so the flagship 402 advertises the X Layer rail live; re-probe
`curl -sS -X POST https://three.ws/api/okx/3d/identity-studio …` and confirm `accepts[0].network
== "eip155:196"`.
3. Once rigging is back: run the 3 demo briefs (`ledgerlynx`, `museweaver`, `momentum-9`) +
`three-ws-3d-studio` through `scripts/okx-identity-demo.mjs` with **real LLM keys** (the demo runs
the director in-process; prod `vercel env pull` returns the keys EMPTY because they're marked
- sensitive — get them from the owner or run the paid job through the deployed endpoint instead).
+ sensitive, get them from the owner or run the paid job through the deployed endpoint instead).
Inspect every deliverable (PFP legible at 128×128, full-body coherent, `verifyRiggedGlb` ≥10
joints + JOINTS_0/WEIGHTS_0), iterate if mediocre, commit `data/agent-identities.json`.
4. **Fund** `0x75d0…cf69` with USD₮0 on X Layer, then run the paid identity-studio E2E (unpaid 402 →
@@ -971,25 +967,25 @@ commits actually contain.
---
-## 2026-07-08 — Verification-only pass: re-audited both blockers against LIVE production; one root
+## 2026-07-08, Verification-only pass: re-audited both blockers against LIVE production; one root
cause corrected, one new same-day incident found (fixed mid-session, not by this agent), core
blockers CONFIRMED STILL OPEN with precise unblock instructions
**No code was shipped in this session beyond a documentation fix.** Scope was explicitly
-verify-only per the dispatching instruction — do not touch credentials/funding, re-establish
+verify-only per the dispatching instruction, do not touch credentials/funding, re-establish
ground truth since the two 2026-07-07 blockers might have resolved on their own.
### Important context shift since the last entries: production moved off Vercel
Commit `d7f69ada9` ("feat(infra): migrate production to Google Cloud Run") landed 2026-07-07,
same day as the WO-06 entry above that told the next session to "rotate the Vercel KV token."
-**That instruction is now stale** — there is no Vercel KV in the production path anymore.
+**That instruction is now stale**, there is no Vercel KV in the production path anymore.
Production env lives on Cloud Run service `three-ws-api` (`gcloud run services describe
three-ws-api --region us-central1`), and `docs/ops/gcp-production.md` is the authoritative ops
doc for this (per `CLAUDE.md`'s stack notes). All findings below were re-derived from that
service's actual env vars and live HTTP probes, not from old assumptions.
-### 1. Rigging repro — STILL 429, root cause refined
+### 1. Rigging repro, STILL 429, root cause refined
```
curl -X POST 'https://three.ws/api/forge?action=rig' -H 'content-type: application/json' \
@@ -997,41 +993,41 @@ curl -X POST 'https://three.ws/api/forge?action=rig' -H 'content-type: applicati
→ HTTP 429 {"error":"rate_limited","error_description":"Rigging limit reached. Try again shortly.",
"retry_after":3600,"reason":"rate_limiter_unavailable"}
```
-Unchanged from the 2026-07-07 entry. Root cause is **not** a stale/rotatable token — `gcloud run
+Unchanged from the 2026-07-07 entry. Root cause is **not** a stale/rotatable token, `gcloud run
services describe three-ws-api --region us-central1` shows the Cloud Run service has **no**
`UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` env vars at all (grepped the full env list;
zero matches). `/api/healthz` confirms: `subsystems.cache = {"status":"ok","detail":"in-memory (no
Redis configured)","backend":"memory"}`. `api/_lib/rate-limit.js` fails the `critical:true`
cost-limiter bucket closed by design when Redis is absent (correct posture for a money/GPU-spend
-gate — do not weaken it). **This blocks all rigging platform-wide, unchanged from 2026-07-07.**
+gate, do not weaken it). **This blocks all rigging platform-wide, unchanged from 2026-07-07.**
-### 2. NEW same-day incident (found mid-session, already fixed by the time I finished — not my fix)
+### 2. NEW same-day incident (found mid-session, already fixed by the time I finished, not my fix)
While probing, `/api/mcp-3d`, `/api/mcp`, and every `/api/okx/3d/*` route returned **HTTP 500
-`{"error":"internal_error","message":"The request failed unexpectedly."}`** — not 429, an outright
+`{"error":"internal_error","message":"The request failed unexpectedly."}`**, not 429, an outright
crash. Cloud Run stderr logs (`gcloud logging read ... run.googleapis.com%2Fstderr`) showed the
cause: `api/_lib/x402/idempotency-cache.js` **hard-throws at module import** in production when
-Redis is unset and `X402_ALLOW_MEMORY_FALLBACK` isn't `1` — `Error: [x402-idempotency] refusing to
+Redis is unset and `X402_ALLOW_MEMORY_FALLBACK` isn't `1`, `Error: [x402-idempotency] refusing to
boot in production without Upstash...`. Because every paid route imports this module, the entire
paid API surface (not just rigging) was down. Revision `three-ws-api-00007-trd` had this crash;
revision `three-ws-api-00008-5dg` (created `2026-07-08T00:38:49Z`, ~seconds after I first hit the
-500s) has `X402_ALLOW_MEMORY_FALLBACK=1` set and boots clean — **someone (owner or a concurrent
+500s) has `X402_ALLOW_MEMORY_FALLBACK=1` set and boots clean, **someone (owner or a concurrent
agent) fixed this live while I was mid-probe.** Re-tested after the rollout: `/api/mcp-3d` GET,
`/api/okx/3d/health`, `/api/okx/3d/catalog`, `/api/okx/3d/identity-studio` GET/POST-unpaid all
return correctly now (402 or 200, no more 500s). I found `docs/ops/gcp-production.md` already had
-a row documenting this exact incident + fix by the time I went to write one — so no doc gap there;
+a row documenting this exact incident + fix by the time I went to write one, so no doc gap there;
I left it as found. **This incident and its fix are unrelated to the OKX/rigging blockers below
and are already resolved; flagging only so the next session doesn't waste time re-diagnosing it.**
One residual oddity: `POST /api/mcp` and `POST /api/mcp-3d` with a `tools/call` or `tools/list`
JSON-RPC body now hang (curl times out at 30-60s, 0 bytes) even though `GET` on the same URL
-returns instantly. Not investigated further (out of this session's scope) — note for whoever picks
+returns instantly. Not investigated further (out of this session's scope), note for whoever picks
up MCP-surface work next; `GET`-based 402 probes (used throughout this campaign) are unaffected.
-### 3. X Layer rail in the 402 challenge — STILL NOT ADVERTISED, but for a different, now-precise
+### 3. X Layer rail in the 402 challenge, STILL NOT ADVERTISED, but for a different, now-precise
reason than "needs a deploy"
The 2026-07-07 WO-06 entry said a deploy was needed to pick up `X402_PAY_TO_XLAYER`. **That deploy
-has since happened** — `gcloud run services describe three-ws-api` confirms both
+has since happened**, `gcloud run services describe three-ws-api` confirms both
`X402_PAY_TO_XLAYER=0x75d00a2713565171f33216e5aa2a375e076ecf69` and
`X402_ASSET_ADDRESS_XLAYER=0x779ded0c9e1022225f8e0630b35a9b54be713736` are live in prod env. But
the X Layer accept still does not appear:
@@ -1041,7 +1037,7 @@ curl -i -X POST https://three.ws/api/okx/3d/identity-studio # unpaid probe
curl -i -X POST https://three.ws/api/okx/3d/pose-seed # unpaid probe
```
Both return a valid 402 with `accepts[]` containing Solana (USDC + THREE) and Base (USDC) entries
-only — **no `eip155:196` entry, on any endpoint, confirmed across identity-studio (the flagship)
+only, **no `eip155:196` entry, on any endpoint, confirmed across identity-studio (the flagship)
and pose-seed (cheapest paid service)**. `curl https://three.ws/api/okx/3d/health` makes the exact
gap explicit:
```
@@ -1057,43 +1053,43 @@ export function xlayerSettleable() {
);
}
```
-The first two conditions are now true (confirmed above); the third is **not** —
+The first two conditions are now true (confirmed above); the third is **not**,
`gcloud run services describe three-ws-api` has no `OKX_API_KEY`, `OKX_SECRET_KEY`,
`OKX_PASSPHRASE`, or `X402_XLAYER_RELAYER_KEY` among its env vars. **This, not a missing deploy, is
-now the sole blocker for the X Layer rail appearing at all** — the exact rail OKX's review flagged
+now the sole blocker for the X Layer rail appearing at all**, the exact rail OKX's review flagged
as missing when it rejected agent #2632. Documented as a new row in
`docs/ops/gcp-production.md`'s "Known-missing (blocked on owner)" table (commit in this session).
-### 4. Wallet funding — STILL $0.00, unchanged
+### 4. Wallet funding, STILL $0.00, unchanged
```
onchainos wallet balance --chain xlayer
→ {"ok":true,"data":{"details":[{"tokenAssets":[]}],"totalValueUsd":"0.00"}}
```
No USD₮0, no OKB, on `0x75d00a2713565171f33216e5aa2a375e076ecf69` on X Layer (chainId 196). Did
-not attempt to fund — requires the owner's real money, out of scope for this session per the
+not attempt to fund, requires the owner's real money, out of scope for this session per the
dispatching instruction.
-### 5. Agent #2632 status — unchanged
+### 5. Agent #2632 status, unchanged
`onchainos agent get-agents --agent-ids 2632` still shows `approvalDisplayStatus: 5` ("Listing
-rejected"), `status: "not listed"`, `serviceList: []`. WO-05 has correctly not run — its hard gate
+rejected"), `status: "not listed"`, `serviceList: []`. WO-05 has correctly not run, its hard gate
(explicit GO from WO-04) is still unmet, and WO-04 still cannot run for real (needs both the OKX
-rail live — item 3 — and wallet funding — item 4).
+rail live, item 3, and wallet funding, item 4).
### WO-05/06/07 precondition check (per the dispatching instruction)
- **WO-05**: hard-gated on WO-04's GO. WO-04 requires a funded wallet + a working settlement rail
- (items 3+4 above) to run for real. Still NO-GO. Did not run it (correctly stays untouched — its
+ (items 3+4 above) to run for real. Still NO-GO. Did not run it (correctly stays untouched, its
own file says "stop and say so" with no gate).
-- **WO-06**: requirement 2 (3+ demo identities, inspected) is still blocked — needs rigging, which
+- **WO-06**: requirement 2 (3+ demo identities, inspected) is still blocked, needs rigging, which
is still 429 (item 1). Requirement 3 (#2632's own avatar) is downstream of requirement 2. Neither
requires money by itself, but both require the rigging pipeline which fails closed on the same
Redis gap. No code-only work available here beyond what WO-06 already shipped.
- **WO-07**: explicitly requires "01–05 must be complete" before it runs; 05 hasn't run. Not
started, correctly.
- No piece of remaining work in 05/06/07 is code-only and non-financial/non-signature at this
- time — everything left is genuinely gated on the two owner items below.
+ time, everything left is genuinely gated on the two owner items below.
### Precise unblock list for the owner (both required; independent of each other)
@@ -1102,7 +1098,7 @@ rail live — item 3 — and wallet funding — item 4).
set `UPSTASH_REDIS_REST_URL` + `UPSTASH_REDIS_REST_TOKEN`:
`gcloud run services update three-ws-api --region us-central1 --set-env-vars
UPSTASH_REDIS_REST_URL=...,UPSTASH_REDIS_REST_TOKEN=...`. (The idempotency-crash half of this
- gap is already patched around via `X402_ALLOW_MEMORY_FALLBACK=1` — this step is specifically to
+ gap is already patched around via `X402_ALLOW_MEMORY_FALLBACK=1`, this step is specifically to
restore real cross-replica rate limiting so rigging stops failing closed.)
2. **OKX facilitator credentials OR a relayer key** (unblocks the X Layer rail appearing in any
402 → unblocks WO-04's real paid E2E → unblocks WO-05's resubmission): either
@@ -1112,7 +1108,7 @@ rail live — item 3 — and wallet funding — item 4).
`gcloud run services update three-ws-api --region us-central1 --set-env-vars
OKX_API_KEY=...,OKX_SECRET_KEY=...,OKX_PASSPHRASE=...` (or `X402_XLAYER_RELAYER_KEY=...`).
3. **Fund `0x75d00a2713565171f33216e5aa2a375e076ecf69` on X Layer (chainId 196) with USD₮0**
- (`0x779ded0c9e1022225f8e0630b35a9b54be713736`) — ~$5 recommended (covers one paid call of every
+ (`0x779ded0c9e1022225f8e0630b35a9b54be713736`), ~$5 recommended (covers one paid call of every
catalog service with buffer, per the WO-03 close-out's cost table). No OKB strictly required
for the payer (EIP-3009 gas is facilitator/relayer-paid), but a small OKB balance is worth
adding as a safety margin regardless of which settlement path (1) uses.
@@ -1122,17 +1118,17 @@ dispatch WO-05 (resubmission) and finish WO-06's demo/avatar requirements, then
### Files touched this session
-- `docs/ops/gcp-production.md` — added the "OKX X Layer facilitator creds" row to the
+- `docs/ops/gcp-production.md`, added the "OKX X Layer facilitator creds" row to the
known-missing table (item 3 above, in doc form for future ops sessions).
- This entry.
-## 2026-07-10 — Rig lane restored end-to-end; WO-06 demo identities COMPLETE (4/4)
+## 2026-07-10, Rig lane restored end-to-end; WO-06 demo identities COMPLETE (4/4)
The blocker that froze WO-06's demo requirement (rigging failing closed) is fully root-caused
-and fixed — two independent faults stacked:
+and fixed, two independent faults stacked:
1. **Routing:** `api/_providers/gcp.js` sent `rerig` to `GCP_RECONSTRUCTION_URL`
- (avatar-reconstruction — no `/rig` endpoint → provider 404 "Not Found" on every rig).
+ (avatar-reconstruction, no `/rig` endpoint → provider 404 "Not Found" on every rig).
Fixed: provider prefers `GCP_UNIRIG_URL` (set on three-ws-api) and speaks the standalone
unirig worker's native schema (`mesh_gcs_url` in, `rigged_gcs_url` out, `/tasks/:id` poll).
2. **Worker:** upstream UniRig hardcodes `PYOPENGL_PLATFORM='egl'` for its voxelization render;
@@ -1140,9 +1136,9 @@ and fixed — two independent faults stacked:
Fixed with image `unirig/server:dc9ce4063-r7-osmesa` (revision unirig-00007-gpz): libosmesa6
+ sed egl→osmesa in /opt/unirig + mmatl's PyOpenGL fork (stock PyOpenGL lacks
`OSMesaCreateContextAttribs`). NOTE: the deployed unirig image is NOT built from
- workers/unirig/ — its true Dockerfile was never committed; r6/r7 are patch layers on r5.
+ workers/unirig/, its true Dockerfile was never committed; r6/r7 are patch layers on r5.
-**WO-06 requirement 2 (3+ demo identities) — DONE.** All four briefs ran the full production
+**WO-06 requirement 2 (3+ demo identities), DONE.** All four briefs ran the full production
pipeline (generate → UniRig rig → posed renders), programmatically rig-verified
(skins + JOINTS_0/WEIGHTS_0), results written to `data/agent-identities.json` by
`scripts/okx-identity-demo.mjs`:
@@ -1156,12 +1152,12 @@ pipeline (generate → UniRig rig → posed renders), programmatically rig-verif
**WO-06 requirement 3 (#2632's avatar):** the asset exists (three-ws-3d-studio's PFP set +
rigged GLB, URLs in data/agent-identities.json). Per the coordination rule, NOT uploaded
-on-chain — WO-05 hasn't submitted, so the asset is handed off here for WO-05/the owner to
+on-chain, WO-05 hasn't submitted, so the asset is handed off here for WO-05/the owner to
set with the identity-update flow (on-chain write needs human confirmation).
**Still owner-blocked:** WO-04/05/07 remain gated on funding the payer wallet
(`0x75d00a2713565171f33216e5aa2a375e076ecf69`, X Layer 196: ~$5 USD₮0 + OKB dust).
-Redis is live and the X Layer rail reports settleable:true — funding is the only gap.
+Redis is live and the X Layer rail reports settleable:true, funding is the only gap.
## 2026-07-17: Listing rejected again, avatar-only reasons; compliant 440x440 avatar produced
@@ -1276,7 +1272,7 @@ draw their reflections almost entirely from the environment map, so with none se
leather, and fabric collapse to near-black. Compounded by ACESFilmic tone mapping at
exposure 1.0 (crushes shadows) and a dark backdrop gradient behind the PFP.
-Fix (no new dependencies — three's built-in procedural `RoomEnvironment`):
+Fix (no new dependencies, three's built-in procedural `RoomEnvironment`):
- `api/_lib/render-clip.js` (the Identity Studio render path via `/api/render/avatar-clip`)
and `api/_lib/avatar-render.js` (public avatar render + MCP tool): added PMREM
`RoomEnvironment` image-based lighting (`scene.environment`, `environmentIntensity` 1.15),
diff --git a/prompts/okx-ai/README.md b/prompts/okx-ai/README.md
index 1e7094b91..2c5dff87f 100644
--- a/prompts/okx-ai/README.md
+++ b/prompts/okx-ai/README.md
@@ -1,4 +1,4 @@
-# OKX.AI Launch — Work Orders
+# OKX.AI Launch: Work Orders
Sequenced, self-contained prompts to take "three.ws 3D Studio" (agent #2632) from
**rejected listing** to **approved, selling, best-in-category ASP** on OKX.AI. Each file is
@@ -19,10 +19,10 @@ facts) and ends by appending to `PROGRESS.md` (the cross-chat handoff log).
|---|---|---|---|
| 1 | `01-protocol-research.md` | Pin the seller-side payments spec from primary sources + live captures | OTP login; maybe dust funding |
| 2 | `02-payments-integration.md` | Implement the OKX rail on our endpoint, tested | possibly `vercel env` values |
-| 3 | `03-service-decomposition.md` | Split into micro-priced services + free catalog | — |
+| 3 | `03-service-decomposition.md` | Split into micro-priced services + free catalog |, |
| 4 | `04-e2e-real-payment-test.md` | Pay ourselves for real; settlement + adversarial gauntlet | **wallet funding**, OTP |
| 5 | `05-relisting-resubmission.md` | Update #2632 + resubmit for review | OTP; confirm on-chain writes |
-| 6 | `06-agent-pfp-wedge.md` | "Agent Identity Studio" — avatars for OKX agents (parallel after 02) | funding for test buys |
+| 6 | `06-agent-pfp-wedge.md` | "Agent Identity Studio", avatars for OKX agents (parallel after 02) | funding for test buys |
| 7 | `07-final-audit-and-watch.md` | Adversarial re-audit, docs closure, approval watch, launch runbook | OTP |
Strict chain: 01 → 02 → 03 → 04 → 05 → 07. 06 can run any time after 02.
@@ -34,5 +34,5 @@ Strict chain: 01 → 02 → 03 → 04 → 05 → 07. 06 can run any time after 0
- Owner has pre-authorized OKX/X Layer/fee-token references for commits in this stream
(details in `00-CONTEXT.md` rule 2).
- Real money on request: work orders compute exact funding needs and pause for the owner.
-- Never deactivate/delete agent #2632 — all changes via update + re-activate.
+- Never deactivate/delete agent #2632, all changes via update + re-activate.
- `PROGRESS.md` is the only memory between chats. Write it like the next agent knows nothing.
diff --git a/prompts/okx-ai/RUNBOOK.md b/prompts/okx-ai/RUNBOOK.md
index 41b414415..a47c41d08 100644
--- a/prompts/okx-ai/RUNBOOK.md
+++ b/prompts/okx-ai/RUNBOOK.md
@@ -1,4 +1,4 @@
-# OKX.AI Operator Runbook — agent #2632 "three.ws 3D Studio"
+# OKX.AI Operator Runbook: agent #2632 "three.ws 3D Studio"
The operator's guide for launch day and the days before it. Written for a zero-context
human or agent: every command below was run from this repo and its real output recorded.
@@ -7,10 +7,30 @@ human or agent: every command below was run from this repo and its real output r
- **Full history:** [`PROGRESS.md`](PROGRESS.md).
- **Public docs:** [`docs/okx-marketplace.md`](../../docs/okx-marketplace.md), [`specs/okx-agent-payments.md`](../../specs/okx-agent-payments.md).
-**CLI:** `onchainos` v4.2.0+ at `~/.local/bin/onchainos`. The read commands below need no
-login. Every **write** (update, activate, resubmit) requires an email-OTP login as
-`[email protected]` — a human must read the code from that inbox. Agents cannot complete a
-write on their own.
+**CLI:** `onchainos` at `~/.local/bin/onchainos` (v4.3.0 as of 2026-07-23; check drift with
+`onchainos --version`). The read commands below need no login. Every **write** (update,
+activate, resubmit) needs an authenticated session as `[email protected]`. **Login mechanics
+changed as of v4.3.0** (older sessions in `PROGRESS.md` describe a direct `wallet login
+<email>` + OTP-typed flow; that no longer exists):
+
+```bash
+onchainos wallet login --phase init
+# -> {"authSessionId": "...", "loginUrl": "https://web3.okx.com/account/sociallogin?...", "opened": true}
+```
+
+A human must open `loginUrl` in a browser, choose email, enter `[email protected]`, and complete
+the emailed OTP there (agents cannot type OTP into this flow directly, it never surfaces as a
+CLI prompt). Then poll for completion (long-running, times out at 120s per call, re-issue as
+needed while the human finishes the browser step):
+
+```bash
+onchainos wallet login --phase poll --session-id <authSessionId>
+onchainos wallet status # loggedIn: true once done
+```
+
+`onchainos agent get-agents` / `service-list` / `search` need this session even though they
+are reads (they 401 with "session expired" when logged out). Only `curl` against our own
+`/api/okx/3d/*` endpoints (§7) and public RPC reads are truly login-free.
---
@@ -33,9 +53,9 @@ Verified output (2026-07-10):
| Field | Meaning |
| --- | --- |
-| `approvalDisplayStatus` | Review state. `5` = **Listing rejected** (our current state). The CLI also returns `approvalLabel`, the human string — **trust `approvalLabel` over memorising numbers**; the numeric map is OKX's and is not documented publicly. |
+| `approvalDisplayStatus` | Review state. `5` = **Listing rejected** (our current state). The CLI also returns `approvalLabel`, the human string, **trust `approvalLabel` over memorising numbers**; the numeric map is OKX's and is not documented publicly. |
| `approvalLabel` | Same state as text: `"Listing rejected"`, `"Listing approved"`, `"Under review"`. |
-| `approvalRemark` | The reviewer's stated reason. **Currently empty** — the 2026-07-04 rejection reason arrived only by email, not through this field. Do not assume a rejection reason will appear here. |
+| `approvalRemark` | The reviewer's stated reason. **Currently empty**, the 2026-07-04 rejection reason arrived only by email, not through this field. Do not assume a rejection reason will appear here. |
| `status` | Listing state. `2` = **not listed**. |
| `soldCount` | Lifetime sales. `0` today. First non-zero value is our first revenue. |
| `role` | `2` = ASP (Agent Service Provider). |
@@ -51,15 +71,16 @@ onchainos agent get-agents --agent-ids 2632 \
## 2. Known drift: the live listing is NOT our current catalog
-Verified 2026-07-10. The listing still carries the **old, rejected** service set. It has
-**7** services; our catalog module [`api/_lib/okx-catalog.js`](../../api/_lib/okx-catalog.js)
-defines **11**, and **not one name matches**.
+Last confirmed 2026-07-10 (service-list read needs the login session in §0 above; re-run once
+logged in to refresh this). The listing carried the **old, rejected** service set: **7**
+services vs. our catalog module [`api/_lib/okx-catalog.js`](../../api/_lib/okx-catalog.js)'s
+**11**, not one name matching.
```bash
-onchainos agent service-list --agent-id 2632 # → data[0].total = 7
+onchainos agent service-list --agent-id 2632 # → data[0].total = 7 (as of 2026-07-10)
```
-| Live on the listing (7) | Our catalog module (11) |
+| Live on the listing (7, as of 2026-07-10) | Our catalog module (11) |
| --- | --- |
| Text & Image to 3D Model | Agent Identity Studio |
| Video to 3D Scene Capture | Text to 3D Model (GLB) |
@@ -74,33 +95,64 @@ onchainos agent service-list --agent-id 2632 # → data[0].total = 7
| | 3D Studio Health (free) |
This is expected: **WO-05 (relisting) has never run**, because it is hard-gated on WO-04.
-Nothing is broken — but do not read the live listing as a description of what we sell today.
-The catalog module is the source of truth; the listing is stale until WO-05 executes.
+Nothing is broken, but do not read the live listing as a description of what we sell today.
+The catalog module is the source of truth; the listing is stale until WO-05 executes. Note
+also that the catalog's listing strings were rewritten 2026-07-17 (`f68ce55bb`) to match OKX's
+documented description format (numbered "Provide: 1. ... 2. ..." lists, no tech jargon, no
+price-in-name), verify against the CURRENT `api/_lib/okx-catalog.js`, not the table above,
+which mirrors the module as of 2026-07-10.
---
## 3. The one blocker: settlement funding
Everything else is code-complete. The rail reports `settleable: true` in production, but no
-funded call has ever settled on-chain — the payer wallet is empty, so real attempts return
-`insufficient_balance`.
-
-**To unblock, the owner funds one wallet:**
+funded call has ever settled on-chain.
+
+**⚠️ Correction (2026-07-23, WO-07 audit): the seller/payTo address has moved.** Every earlier
+session in `PROGRESS.md` (and the pre-2026-07-23 text below in this file) names
+`0x75d00a2713565171f33216e5aa2a375e076ecf69` as "the payTo wallet". Live-probed today, the
+X Layer accept's `payTo` is **`0x4022de2D36C334E73C7a108805Cea11C0564f402`**, the platform's
+standard EVM merchant/deployer wallet (already the Base rail's `payTo`, see
+`contracts/DEPLOYMENTS.md`), evidently consolidated onto X Layer sometime between 2026-07-07
+and 2026-07-23 with no PROGRESS.md entry recording it. Confirmed against the live Cloud Run
+env var (`X402_PAY_TO_XLAYER`), not just the HTTP challenge, so this is the real seller address,
+not a caching artifact. `0x75d0…cf69` still has two other real roles that are unaffected: it is
+agent #2632's **on-chain identity owner wallet**, and it is the **onchainos buyer/TEE wallet**
+this session's `payment pay` command signs from, so a "self-payment" test is no longer
+self-payment (buyer `0x75d0…cf69` → seller `0x4022de2D…f402`), which is arguably a more
+realistic E2E test, not a problem, but the funding target below is what actually needs money.
+
+**Wallet balances checked live 2026-07-23 (X Layer RPC `rpc.xlayer.tech`, direct `eth_call`):**
+
+| Wallet | Role | Token | Balance |
+| --- | --- | --- | --- |
+| `0x75d00a2713565171f33216e5aa2a375e076ecf69` | Buyer (onchainos TEE wallet) + agent identity owner | USD₮0 | **0** |
+| `0x4022de2D36C334E73C7a108805Cea11C0564f402` | Seller / payTo (current) | USD₮0 | 2.427731 (irrelevant to the buyer-side test, it's the recipient not the payer) |
+| `0xe81DE501Dd5D9299E2bA8964498858d3fAD0415B` | Relayer (`X402_XLAYER_RELAYER_KEY`, Secret Manager `x402-xlayer-relayer-key` v3, rotated 2026-07-12; superseded the `0x1F4a…bb74` address `PROGRESS.md` names from 2026-07-08) | OKB (gas) | 0.02 |
+
+**To unblock, the owner funds the BUYER wallet** (the seller already has funds; gas at the
+relayer is thin but present):
| | |
| --- | --- |
-| Wallet (payer + seller) | `0x75d00a2713565171f33216e5aa2a375e076ecf69` |
+| Wallet to fund | `0x75d00a2713565171f33216e5aa2a375e076ecf69` (buyer) |
| Chain | X Layer, chainId **196** (`eip155:196`) |
-| Token | `0x779ded0c9e1022225f8e0630b35a9b54be713736` |
-| Amount | ~$5 of the fee token, plus OKB dust for gas |
+| Token | `0x779ded0c9e1022225f8e0630b35a9b54be713736` (USD₮0) |
+| Amount | ≥$3 to cover one paid call of every catalog service once each; ~$5 for buffer |
+
+Re-verify the relayer's OKB balance is still enough for ≥3 settlement tx before relying on
+0.02 OKB, top up a few cents' worth if a dry run shows `broadcast_failed`/out-of-gas.
Once funded, run [`04-e2e-real-payment-test.md`](04-e2e-real-payment-test.md). It needs ≥3
real settlements with transaction hashes. **Only then** does WO-05 (resubmission) unlock.
Until a real settlement exists, `docs/okx-marketplace.md` must not claim observed on-chain
-settlement — its "Payment semantics" section states the contract as implemented and
+settlement, its "Payment semantics" section states the contract as implemented and
unit-tested, with an explicit note that no funded settlement has occurred. Keep that note
-until the first tx hash lands, then update both that section and `PROGRESS.md`.
+until the first tx hash lands, then update both that section and `PROGRESS.md`. Also re-probe
+`payTo` live before trusting any address in this file, the mid-stream address change above
+went unrecorded once; it can happen again silently on a future deploy.
---
@@ -113,14 +165,14 @@ This is the holder-visible moment. Work the list top to bottom.
onchainos agent get-agents --agent-ids 2632 # status should leave 2 ("not listed")
onchainos agent service-list --agent-id 2632 # services present, prices correct
```
- Reconcile the service names against `api/_lib/okx-catalog.js` — see §2. If they still
+ Reconcile the service names against `api/_lib/okx-catalog.js`, see §2. If they still
differ, WO-05 did not take; re-run it before announcing.
2. **Search as a buyer would.** We must actually appear:
```bash
onchainos agent search --query "3D avatar rigging GLB"
```
- Verified 2026-07-10: returns 2 results, **agent 2632 absent** (correct — we are not
+ Verified 2026-07-10: returns 2 results, **agent 2632 absent** (correct, we are not
listed). After approval this must return us. Check the card copy reads well and the
prices are right.
@@ -133,7 +185,7 @@ This is the holder-visible moment. Work the list top to bottom.
`/api/cron/changelog-push` cron posts the entry once the deploy that ships
it is live. No manual push step.
-4. **Set the agent's own avatar live** if WO-06's dogfood upload was deferred (it was — the
+4. **Set the agent's own avatar live** if WO-06's dogfood upload was deferred (it was, the
asset is generated but never written on-chain). This is an on-chain write: OTP required.
5. **Record it.** Append the approval, the date, and the first listing screenshot/output to
@@ -144,7 +196,7 @@ This is the holder-visible moment. Work the list top to bottom.
## 5. Branch: **REJECTED AGAIN** (`approvalDisplayStatus: 5`)
1. **Capture the exact reason.** Check `approvalRemark` first, then the `[email protected]`
- inbox — the 2026-07-04 rejection came by email with `approvalRemark` empty, so assume the
+ inbox, the 2026-07-04 rejection came by email with `approvalRemark` empty, so assume the
email is authoritative.
```bash
onchainos agent get-agents --agent-ids 2632 \
@@ -153,10 +205,20 @@ This is the holder-visible moment. Work the list top to bottom.
2. **Append the verbatim remark to `PROGRESS.md`** with the date. Never paraphrase a
reviewer.
3. **Map the reason to the work order that owns it**, fix there, and re-run
- [`05-relisting-resubmission.md`](05-relisting-resubmission.md). For reference, the
- 2026-07-04 rejection ("your A2MCP service has not been integrated with the OKX Agent
- Payments Protocol standard") was owned by the payment rail, now implemented in
- [`api/_lib/x402-xlayer-okx.js`](../../api/_lib/x402-xlayer-okx.js).
+ [`05-relisting-resubmission.md`](05-relisting-resubmission.md). Precedent:
+ - 2026-07-04 rejection ("your A2MCP service has not been integrated with the OKX Agent
+ Payments Protocol standard") was owned by the payment rail, implemented in
+ [`api/_lib/x402-xlayer-okx.js`](../../api/_lib/x402-xlayer-okx.js).
+ - 2026-07-17 rejection (avatar not aligned with agent positioning / not polished; wrong
+ dimensions/corners) was owned by the listing avatar. Fixed: a logo-style 440x440 square
+ avatar at [`prompts/okx-ai/assets/okx-avatar-440.png`](assets/okx-avatar-440.png)
+ (reproducible via `node prompts/okx-ai/assets/render-avatar.mjs`), plus a root-cause fix
+ to the render pipeline itself (missing IBL environment made every avatar/PFP render dark
+ and murky, see `api/_lib/render-clip.js` / `api/_lib/avatar-render.js`, shipped
+ 2026-07-17). **As of this audit (2026-07-23) the fixed avatar has not yet been uploaded
+ on-chain** (`agent upload` + `agent update` need the login session from §0, then a human
+ confirms the write), that upload plus the catalog-string resubmission (§2) is the next
+ concrete action once login completes.
---
@@ -166,7 +228,7 @@ This is the holder-visible moment. Work the list top to bottom.
| --- | --- |
| Did we sell? | `onchainos agent get-agents --agent-ids 2632` → `soldCount` |
| What did buyers say? | `onchainos agent feedback-list` (verified present: "Query Agent reviews") |
-| Where does revenue land? | The agent wallet `0x75d0…cf69` on X Layer (196) — the same wallet that pays. Confirm the first payout against the settlement tx hash from WO-04. |
+| Where does revenue land? | The seller/payTo wallet on X Layer (196), **verify live**, it has moved before (see §3); as of 2026-07-23 it is `0x4022de2D36C334E73C7a108805Cea11C0564f402`, the platform's standard EVM merchant wallet, not the buyer wallet. Confirm the first payout against the settlement tx hash from WO-04. |
| Where do errors surface? | The existing error-reporting path in [`api/_mcp/payments.js`](../../api/_mcp/payments.js); paid-endpoint failures answer **before** settlement, so a failed job never charges a buyer. |
| Daily watch | `soldCount`, `approvalLabel`, and the paid-endpoint health/catalog free routes (§7). |
@@ -174,7 +236,7 @@ This is the holder-visible moment. Work the list top to bottom.
## 7. Free routes worth probing any day
-These need no payment, no key, and no login — they are the fastest signal that the surface
+These need no payment, no key, and no login, they are the fastest signal that the surface
is healthy:
```bash
diff --git a/public/changelog.json b/public/changelog.json
index 7cbb8e1d0..c2416d585 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-23T13:34:39.256Z",
+ "generated_at": "2026-07-23T13:42:42.342Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -36,6 +36,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-23",
+ "type": "update",
+ "title": "A full notification center, plus two new things it tells you about",
+ "summary": "The bell in the nav now links to a dedicated /notifications page: your full history, filterable by category (sales, purchases, social, in person, market alerts, creations, account), with load-more paging so nothing gets lost past the dropdown's last 20. We also closed two gaps in what triggers a notification. Fork royalty streams (an avatar you created earning a slice of income from everyone who forked it) now notify the upstream creator the moment a payout confirms on-chain, with the SOL/USD amount and which fork paid it. And finishing a mission or co-op heist in /play now lands in your inbox too, not just the site-wide activity ticker. Both respect your existing per-category mute preferences in notification settings.",
+ "link": "/notifications",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-23",
"type": "update",
@@ -88,6 +98,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-23",
+ "type": "update",
+ "title": "Real materials: skin, glass, and car paint that actually behave like the real thing",
+ "summary": "Avatars now get a subtle skin sheen, wet-looking corneas, and double-sided hair automatically the moment a humanoid model loads in any three.ws viewer, no extra step needed. Restyle Studio's material presets grew a real-physics tier alongside the classic looks: skin, car paint with a genuine clearcoat layer, brushed steel with directional anisotropic highlights, and a real-glass preset that actually refracts (KHR_materials_transmission) instead of faking transparency. The AI restyle tool (\"make it chrome\", \"cyberpunk neon\") can now propose clearcoat, transmission, and sheen too when an instruction calls for it. The text-guided texture worker also gained an optional material_class hint (person/metal/wood/fabric/plastic/glass) that bakes measured real-world roughness values instead of one flat guess for every material.",
+ "link": "/restyle",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-23",
"type": "update",
@@ -3040,6 +3061,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-12",
+ "type": "launch",
+ "title": "Notifications",
+ "summary": "Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.",
+ "link": "/notifications",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-12",
"type": "launch",
@@ -5817,7 +5848,7 @@
{
"date": "2026-07-06",
"type": "launch",
- "title": "Agent Identity Studio — 3D avatars for AI agents",
+ "title": "Agent Identity Studio: 3D avatars for AI agents",
"summary": "Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.",
"link": "/agent-identities",
"tags": [
diff --git a/public/changelog.xml b/public/changelog.xml
index c22ace87f..b6300dda5 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>launch</category>
<description>Two weeks of fully autonomous pump.fun trading on Solana: 11 armed strategies, 90 closed real-money trades, every entry thesis, every exit, every mistake. Plus the 83,000 coins the fleet did not buy, the winners it missed, and a paperhands audit of every sell. Complete dataset included.</description>
</item>
+ <item>
+ <title>A full notification center, plus two new things it tells you about</title>
+ <link>https://three.ws/notifications</link>
+ <guid isPermaLink="false">2026-07-23:A full notification center, plus two new things it tells you about</guid>
+ <pubDate>Thu, 23 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The bell in the nav now links to a dedicated /notifications page: your full history, filterable by category (sales, purchases, social, in person, market alerts, creations, account), with load-more paging so nothing gets lost past the dropdown's last 20. We also closed two gaps in what triggers a notification. Fork royalty streams (an avatar you created earning a slice of income from everyone who forked it) now notify the upstream creator the moment a payout confirms on-chain, with the SOL/USD amount and which fork paid it. And finishing a mission or co-op heist in /play now lands in your inbox too, not just the site-wide activity ticker. Both respect your existing per-category mute preferences in notification settings.</description>
+ </item>
<item>
<title>Agent wallet and portfolio views stay reliable when an RPC provider is capped</title>
<link>https://three.ws/changelog</link>
@@ -70,6 +78,14 @@
<category>improvement</category>
<description>Previewing a prop from the CC0 object library (a wrench, a vase, an ammo box) used to drop you into the embodied-agent surface, complete with an &quot;Ask the agent&quot; box and prompts like &quot;Why are you embodied?&quot; that make no sense for an inanimate object. Objects now open in a dedicated viewer mode: the agent chat and avatar controls are gone, replaced by the things you actually want for a 3D thing — Restyle to recolor or AI-restyle its materials, View in AR to place it in your room, and Download the CC0 GLB. Avatars are untouched and still open with the full agent experience.</description>
</item>
+ <item>
+ <title>Real materials: skin, glass, and car paint that actually behave like the real thing</title>
+ <link>https://three.ws/restyle</link>
+ <guid isPermaLink="false">2026-07-23:Real materials: skin, glass, and car paint that actually behave like the real thing</guid>
+ <pubDate>Thu, 23 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Avatars now get a subtle skin sheen, wet-looking corneas, and double-sided hair automatically the moment a humanoid model loads in any three.ws viewer, no extra step needed. Restyle Studio's material presets grew a real-physics tier alongside the classic looks: skin, car paint with a genuine clearcoat layer, brushed steel with directional anisotropic highlights, and a real-glass preset that actually refracts (KHR_materials_transmission) instead of faking transparency. The AI restyle tool (&quot;make it chrome&quot;, &quot;cyberpunk neon&quot;) can now propose clearcoat, transmission, and sheen too when an instruction calls for it. The text-guided texture worker also gained an optional material_class hint (person/metal/wood/fabric/plastic/glass) that bakes measured real-world roughness values instead of one flat guess for every material.</description>
+ </item>
<item>
<title>Restyled models now show up on your creator portfolio</title>
<link>https://three.ws/profile</link>
@@ -2334,6 +2350,14 @@
<category>launch</category>
<description>How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.</description>
</item>
+ <item>
+ <title>Notifications</title>
+ <link>https://three.ws/notifications</link>
+ <guid isPermaLink="false">2026-07-12:Notifications</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.</description>
+ </item>
<item>
<title>Rankings</title>
<link>https://three.ws/rankings</link>
@@ -4463,9 +4487,9 @@
<description>Our Solana vanity grinder, grind a brand-new address that starts with your ticker for a branded token mint or agent/treasury wallet, now reads like the flagship it is on the x402 agent marketplaces. The listing leads with what agents actually use it for, spells out both output formats (a raw keypair or an importable BIP-39 seed phrase), the character caps and the full price ladder ($0.01-$0.25 for a keypair, $0.05-$0.50 for a mnemonic), and the security model: nothing is ever stored, the secret is served once over TLS and stripped from the replay cache, and an optional sealed-delivery key means the plaintext never appears in the response or any log. The discovery schema is now complete enough for an agent to grind an address blind, and the premium pre-ground inventory tier is now indexable too, so all three vanity tiers surface on the marketplaces and can never drift from what the live payment charges. New reference doc at /docs/vanity.</description>
</item>
<item>
- <title>Agent Identity Studio — 3D avatars for AI agents</title>
+ <title>Agent Identity Studio: 3D avatars for AI agents</title>
<link>https://three.ws/agent-identities</link>
- <guid isPermaLink="false">2026-07-06:Agent Identity Studio — 3D avatars for AI agents</guid>
+ <guid isPermaLink="false">2026-07-06:Agent Identity Studio: 3D avatars for AI agents</guid>
<pubDate>Mon, 06 Jul 2026 12:00:00 GMT</pubDate>
<category>launch</category>
<description>Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.</description>
diff --git a/public/features.json b/public/features.json
index 4395a5082..084030b9c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-23T13:34:39.248Z",
+ "generated_at": "2026-07-23T13:42:42.333Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -225,6 +225,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/notifications",
+ "title": "Notifications",
+ "description": "Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.",
+ "added": "2026-07-12",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/skills",
"title": "Skills Marketplace",
@@ -2325,7 +2335,7 @@
},
{
"path": "/agent-identities",
- "title": "Agent Identity Studio — 3D avatars for AI agents",
+ "title": "Agent Identity Studio: 3D avatars for AI agents",
"description": "Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.",
"added": "2026-07-06",
"auth": null,
diff --git a/public/hdri/outdoor.hdr b/public/hdri/outdoor.hdr
new file mode 100644
index 000000000..cb2eb4653
Binary files /dev/null and b/public/hdri/outdoor.hdr differ
diff --git a/public/hdri/studio.hdr b/public/hdri/studio.hdr
new file mode 100644
index 000000000..fd9f69afe
Binary files /dev/null and b/public/hdri/studio.hdr differ
diff --git a/public/hdri/sunset.hdr b/public/hdri/sunset.hdr
new file mode 100644
index 000000000..0e33781ba
Binary files /dev/null and b/public/hdri/sunset.hdr differ
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 4a5dec897..9ef0975e8 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -139,6 +139,12 @@ URL: https://three.ws/collection
View all the skills and subscriptions you've unlocked on three.ws.
+### Notifications
+
+URL: https://three.ws/notifications
+
+Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.
+
### Skills Marketplace
URL: https://three.ws/skills
@@ -793,6 +799,12 @@ URL: https://three.ws/leaderboard
Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
+### KOL Tracker
+
+URL: https://three.ws/tracker
+
+Solana crypto KOLs ranked by realized P&L computed from their own wallet's on-chain trade history, with win rate, volume, trade count, and X follower counts for verified handles.
+
### Custody Integrity
URL: https://three.ws/integrity
@@ -1400,7 +1412,7 @@ URL: https://three.ws/chat
Talk to your agent. Voice, text, and tool-use in one interface.
-### Agent Identity Studio — 3D avatars for AI agents
+### Agent Identity Studio: 3D avatars for AI agents
URL: https://three.ws/agent-identities
diff --git a/public/llms.txt b/public/llms.txt
index b5c53f2f8..a0ade1a98 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -32,6 +32,7 @@ Entry points into the product.
- [Marketplace](https://three.ws/marketplace): Buy access to agents, skills, and avatars from other creators.
- [Marketplace Analytics](https://three.ws/marketplace/analytics): Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.
- [My Collection](https://three.ws/collection): View all the skills and subscriptions you've unlocked on three.ws.
+- [Notifications](https://three.ws/notifications): Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.
- [Skills Marketplace](https://three.ws/skills): Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter.
- [Community](https://three.ws/community): Live platform activity plus where to follow, contribute, and connect with three.ws creators.
- [Search](https://three.ws/search): One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.
@@ -149,6 +150,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Memetic Launcher](https://three.ws/launcher): Your personal autonomous coin launcher — set your mode (trend, meme, hybrid, random), pick trend sources, tune your cadence, preview what your agents would mint, then go live: real pump.fun launches on your schedule, self-funded from your own agents' wallets under a hard daily SOL cap.
- [Coin Clash](https://three.ws/clash): Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
- [Trader Leaderboard](https://three.ws/leaderboard): Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
+- [KOL Tracker](https://three.ws/tracker): Solana crypto KOLs ranked by realized P&L computed from their own wallet's on-chain trade history, with win rate, volume, trade count, and X follower counts for verified handles.
- [Custody Integrity](https://three.ws/integrity): Provable, on-chain-anchored custody for every three.ws agent wallet. The platform commits a Merkle root over every wallet's on-chain state to Solana — verify the latest root yourself, no account required.
- [Agent Labor Market](https://three.ws/labor-market): A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.
- [Back-an-Agent Vaults](https://three.ws/vaults): Copy-trade a 3D agent with a verifiable on-chain reputation: stake into a verified trader, share its real P&L pro-rata, and watch it trade your capital live — segregated custody, hard spend limits, and a drawdown circuit breaker.
@@ -253,7 +255,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
Manage, talk to, and deploy individual agents.
- [Chat](https://three.ws/chat): Talk to your agent. Voice, text, and tool-use in one interface.
-- [Agent Identity Studio — 3D avatars for AI agents](https://three.ws/agent-identities): Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.
+- [Agent Identity Studio: 3D avatars for AI agents](https://three.ws/agent-identities): Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.
- [Agents Index](https://three.ws/agents): Browse every registered agent on three.ws.
- [Reasoning Ledger](https://three.ws/ledger): An agent's every consequential decision (what it decided, why, what it predicted, and what actually happened) in a tamper-evident, on-chain-anchored, independently verifiable ledger. Open any agent's at /ledger/<agentId>. Being wrong is visible; honesty is the trust signal.
- [Reputation Explorer](https://three.ws/reputation): Inspect on-chain reputation scores and attestations for any agent.
diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.json
index f4d6f6bdb..2614d3d37 100644
--- a/public/locales/localized-pages.json
+++ b/public/locales/localized-pages.json
@@ -1,6 +1,6 @@
{
"generated": true,
- "count": 183,
+ "count": 184,
"paths": [
"/",
"/activity",
@@ -171,6 +171,7 @@
"/three-token",
"/tour",
"/tour-builder",
+ "/tracker",
"/trades",
"/trending",
"/tutorials",
diff --git a/public/nav.css b/public/nav.css
index e91e6da73..1777c6348 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -251,6 +251,16 @@
.notif-panel-body::-webkit-scrollbar { width: 4px; }
.notif-panel-body::-webkit-scrollbar-track { background: transparent; }
.notif-panel-body::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 2px; }
+.notif-panel-viewall {
+ display: block; text-align: center;
+ padding: 10px; flex-shrink: 0;
+ font-size: var(--text-sm); font-weight: 500; color: rgba(255,255,255,0.5);
+ border-top: 1px solid rgba(255,255,255,0.08);
+ text-decoration: none;
+ transition: color 0.12s, background 0.12s;
+}
+.notif-panel-viewall:hover { color: rgba(255,255,255,0.85); background: rgba(255,255,255,0.04); }
+.notif-panel-viewall:focus-visible { outline: 2px solid rgba(255,255,255,0.3); outline-offset: -2px; }
/* notification rows */
.notif-row {
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index fb4320415..9c4445e2f 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -84,7 +84,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 526 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 528 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -96,7 +96,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 526 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 528 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -104,6 +104,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/tracker">
+ <span class="sm-new-date">Jul 23, 2026</span>
+ <span class="sm-title">KOL Tracker</span>
+ <span class="sm-path">/tracker</span>
+ <span class="sm-desc">Solana crypto KOLs ranked by realized P&amp;L computed from their own wallet's on-chain trade history, with win rate, volume, trade count, and X follower counts for verified handles.</span>
+ </a>
+ </li>
<li>
<a href="/tutorials/shopify-shopping-assistant">
<span class="sm-new-date">Jul 23, 2026</span>
@@ -168,14 +176,6 @@
<span class="sm-desc">Every three.ws policy in one place, plus which address to use to report copyright, abuse, or privacy issues.</span>
</a>
</li>
- <li>
- <a href="/character-library">
- <span class="sm-new-date">Jul 19, 2026</span>
- <span class="sm-title">Character Library</span>
- <span class="sm-path">/character-library</span>
- <span class="sm-desc">106 professionally rigged 3D characters, free to use. Every one drives the full animation library and drops into the Studio, Animation Studio, and embed viewer in one click.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -193,7 +193,7 @@
</nav>
<section class="sm-section" id="main">
<header>
- <h2>Main<span class="sm-count" data-count>36</span></h2>
+ <h2>Main<span class="sm-count" data-count>37</span></h2>
<p class="sm-section-desc">Entry points into the product.</p>
</header>
<ul class="sm-list">
@@ -344,6 +344,13 @@
<span class="sm-desc">View all the skills and subscriptions you've unlocked on three.ws.</span>
</a>
</li>
+ <li>
+ <a href="/notifications">
+ <span class="sm-title">Notifications</span>
+ <span class="sm-path">/notifications</span>
+ <span class="sm-desc">Every payment, sale, remix, follow, quest, and royalty notification on three.ws — all in one place, filterable by category.</span>
+ </a>
+ </li>
<li>
<a href="/skills">
<span class="sm-title">Skills Marketplace</span>
@@ -955,7 +962,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>121</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>122</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -1113,6 +1120,13 @@
<span class="sm-desc">Pump.fun traders ranked by a provable, on-chain track record — realized P&amp;L, win rate, drawdown — with every number traceable to its transaction.</span>
</a>
</li>
+ <li>
+ <a href="/tracker">
+ <span class="sm-title">KOL Tracker</span>
+ <span class="sm-path">/tracker</span>
+ <span class="sm-desc">Solana crypto KOLs ranked by realized P&amp;L computed from their own wallet's on-chain trade history, with win rate, volume, trade count, and X follower counts for verified handles.</span>
+ </a>
+ </li>
<li>
<a href="/integrity">
<span class="sm-title">Custody Integrity</span>
@@ -1824,7 +1838,7 @@
</li>
<li>
<a href="/agent-identities">
- <span class="sm-title">Agent Identity Studio — 3D avatars for AI agents</span>
+ <span class="sm-title">Agent Identity Studio: 3D avatars for AI agents</span>
<span class="sm-path">/agent-identities</span>
<span class="sm-desc">Every AI agent deserves a face. A brand brief becomes a rigged 3D avatar plus posed studio renders — see the demo identities generated end-to-end by the pipeline.</span>
</a>
diff --git a/scripts/README.md b/scripts/README.md
index 13e6df27e..3dc60b3b1 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -34,6 +34,20 @@ repeated signatures, classifies each against the runbook
owner / env-action / investigate / self-healing, and prints the concrete action
per finding. Agents drive the fix loop via the `/gcp-triage` skill.
+### `inspect-pbr-channels.mjs` — PBR channel matrix for any GLB
+
+```sh
+node scripts/inspect-pbr-channels.mjs public/avatars/fox.glb
+node scripts/inspect-pbr-channels.mjs --json https://storage.googleapis.com/three-ws-avatar-reconstructions/mesh.glb
+```
+
+Loads a local file or public https GLB with `@gltf-transform/core` and reports,
+per material, whether baseColor/normal/metallicRoughness/occlusion/emissive
+are a real texture, a flat factor, or missing, plus which `KHR_materials_*`
+extensions (clearcoat, transmission, sheen, ior, anisotropy, volume) are
+present. This is the ground truth for auditing whether a forge lane emits a
+full PBR set or just albedo, without opening the GLB in a 3D editor by hand.
+
### `set-r2-cors.mjs` — apply the bucket CORS policy
Runs the canonical CORS policy against the R2 bucket holding all media
diff --git a/scripts/inspect-pbr-channels.mjs b/scripts/inspect-pbr-channels.mjs
new file mode 100644
index 000000000..14b4d8eeb
--- /dev/null
+++ b/scripts/inspect-pbr-channels.mjs
@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+/**
+ * PBR channel matrix — audits which physically-based material channels a GLB
+ * actually carries: baseColor/albedo, normal, metallicRoughness, occlusion
+ * (packed or standalone), emissive, and the real-material KHR extensions
+ * (clearcoat, transmission, sheen, IOR, anisotropy, volume).
+ *
+ * This is prompt 04's audit tool ("build a small scripts/ inspection tool"):
+ * point it at any local file or public https URL and it prints, per material,
+ * which channels exist as textures vs. flat factors vs. missing entirely —
+ * the ground truth for "does this forge lane emit a full PBR set or just
+ * albedo" without opening the GLB in a 3D editor by hand.
+ *
+ * Usage:
+ * node scripts/inspect-pbr-channels.mjs <path-or-url> [<path-or-url> ...]
+ * node scripts/inspect-pbr-channels.mjs --json <path-or-url> # machine-readable
+ *
+ * Examples:
+ * node scripts/inspect-pbr-channels.mjs public/avatars/fox.glb
+ * node scripts/inspect-pbr-channels.mjs https://storage.googleapis.com/three-ws-avatar-reconstructions/mesh.glb
+ */
+import { readFileSync } from 'node:fs';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { MeshoptDecoder } from 'meshoptimizer';
+
+async function makeIO() {
+ await MeshoptDecoder.ready;
+ return new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+}
+
+const KHR_EXTENSION_LABELS = {
+ KHR_materials_clearcoat: 'clearcoat',
+ KHR_materials_transmission: 'transmission',
+ KHR_materials_sheen: 'sheen',
+ KHR_materials_ior: 'ior',
+ KHR_materials_anisotropy: 'anisotropy',
+ KHR_materials_volume: 'volume',
+ KHR_materials_specular: 'specular',
+ KHR_materials_emissive_strength: 'emissiveStrength',
+ KHR_materials_unlit: 'unlit',
+};
+
+async function loadBytes(source) {
+ if (/^https?:\/\//i.test(source)) {
+ const resp = await fetch(source);
+ if (!resp.ok) throw new Error(`fetch ${source} failed: ${resp.status}`);
+ return new Uint8Array(await resp.arrayBuffer());
+ }
+ return new Uint8Array(readFileSync(source));
+}
+
+function textureLabel(tex) {
+ if (!tex) return null;
+ const size = tex.getSize();
+ const mime = tex.getMimeType();
+ return `${size ? `${size[0]}x${size[1]}` : '?'} ${mime || ''}`.trim();
+}
+
+async function inspect(source) {
+ const bytes = await loadBytes(source);
+ const io = await makeIO();
+ const doc = await io.readBinary(bytes);
+ const root = doc.getRoot();
+ const materials = root.listMaterials();
+
+ const report = {
+ source,
+ bytes: bytes.byteLength,
+ materialCount: materials.length,
+ textureCount: root.listTextures().length,
+ materials: [],
+ };
+
+ for (const mat of materials) {
+ const channels = {
+ baseColor: mat.getBaseColorTexture()
+ ? { kind: 'texture', detail: textureLabel(mat.getBaseColorTexture()) }
+ : { kind: 'factor', detail: mat.getBaseColorFactor() },
+ metallicRoughness: mat.getMetallicRoughnessTexture()
+ ? { kind: 'texture', detail: textureLabel(mat.getMetallicRoughnessTexture()) }
+ : { kind: 'factor', detail: { metallic: mat.getMetallicFactor(), roughness: mat.getRoughnessFactor() } },
+ normal: mat.getNormalTexture() ? { kind: 'texture', detail: textureLabel(mat.getNormalTexture()) } : { kind: 'missing' },
+ occlusion: mat.getOcclusionTexture()
+ ? {
+ kind: 'texture',
+ // glTF packs AO in the metallicRoughness texture's R channel by
+ // convention when the two textures are the same image.
+ packed: mat.getOcclusionTexture() === mat.getMetallicRoughnessTexture(),
+ detail: textureLabel(mat.getOcclusionTexture()),
+ }
+ : { kind: 'missing' },
+ emissive: mat.getEmissiveTexture()
+ ? { kind: 'texture', detail: textureLabel(mat.getEmissiveTexture()) }
+ : { kind: 'factor', detail: mat.getEmissiveFactor() },
+ };
+
+ const extensions = {};
+ for (const [name, label] of Object.entries(KHR_EXTENSION_LABELS)) {
+ const ext = mat.getExtension(name);
+ if (ext) extensions[label] = true;
+ }
+
+ report.materials.push({
+ name: mat.getName() || '(unnamed)',
+ channels,
+ extensions,
+ });
+ }
+
+ return report;
+}
+
+function fmtChannel(ch) {
+ if (ch.kind === 'missing') return 'MISSING';
+ if (ch.kind === 'texture') return `tex(${ch.detail})${ch.packed ? ' [packed w/ metallicRoughness]' : ''}`;
+ return `factor(${JSON.stringify(ch.detail)})`;
+}
+
+function printHuman(report) {
+ console.log(`\n${report.source}`);
+ console.log(` ${report.bytes.toLocaleString()} bytes, ${report.materialCount} material(s), ${report.textureCount} texture(s)`);
+ for (const mat of report.materials) {
+ console.log(` material "${mat.name}"`);
+ for (const [ch, val] of Object.entries(mat.channels)) {
+ console.log(` ${ch.padEnd(18)} ${fmtChannel(val)}`);
+ }
+ const extNames = Object.keys(mat.extensions);
+ console.log(` ${'extensions'.padEnd(18)} ${extNames.length ? extNames.join(', ') : 'none'}`);
+ }
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const jsonMode = args.includes('--json');
+ const sources = args.filter((a) => a !== '--json');
+ if (!sources.length) {
+ console.error('usage: node scripts/inspect-pbr-channels.mjs [--json] <path-or-url> [...]');
+ process.exit(1);
+ }
+
+ const reports = [];
+ for (const source of sources) {
+ try {
+ reports.push(await inspect(source));
+ } catch (err) {
+ reports.push({ source, error: err.message });
+ }
+ }
+
+ if (jsonMode) {
+ console.log(JSON.stringify(reports, null, 2));
+ return;
+ }
+ for (const report of reports) {
+ if (report.error) {
+ console.error(`\n${report.source}\n ERROR: ${report.error}`);
+ continue;
+ }
+ printHuman(report);
+ }
+}
+
+main();
diff --git a/scripts/okx-identity-demo.mjs b/scripts/okx-identity-demo.mjs
index a6c8a9598..93b9853eb 100644
--- a/scripts/okx-identity-demo.mjs
+++ b/scripts/okx-identity-demo.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
// Run the Agent Identity Studio pipeline for the demo identities in
-// data/agent-identities.json — REAL runs of the production pipeline (the same
+// data/agent-identities.json, REAL runs of the production pipeline (the same
// module the /api/okx/3d/identity-studio endpoint executes), driven locally:
//
// node --env-file=.env.local scripts/okx-identity-demo.mjs [slug] [--force]
@@ -80,7 +80,7 @@ async function runIdentity(entry) {
}
const rig = await verifyRiggedGlb(desc.deliverables.rigged_glb_url);
console.log(
- ` ✓ done in ${Math.round((Date.now() - started) / 1000)}s — rig verified: ` +
+ ` ✓ done in ${Math.round((Date.now() - started) / 1000)}s, rig verified: ` +
`${rig.joints} joints, ${rig.skinnedPrimitives} skinned primitives, ${Math.round(rig.bytes / 1024)}KB`,
);
return {
diff --git a/scripts/quality-bench.mjs b/scripts/quality-bench.mjs
new file mode 100644
index 000000000..89245fc15
--- /dev/null
+++ b/scripts/quality-bench.mjs
@@ -0,0 +1,235 @@
+#!/usr/bin/env node
+// Realism eval harness: fires the fixed prompt set in data/quality-bench/prompts.json
+// through the REAL /api/forge path on a live deployment, renders 3 canonical views of
+// the resulting GLB with the same headless three.js renderer that powers the avatar
+// clip/OG-card renders (api/_lib/render-clip.js), and scores every view with Vertex
+// Gemini vision (gemini-2.5-pro), twice per view, averaged. Core generate/render/judge
+// logic lives in api/_lib/quality-bench.js, shared with the weekly cron sweep
+// (api/cron/quality-bench.js) so the two callers can never disagree on what a
+// "scored view" means.
+//
+// Usage:
+// node scripts/quality-bench.mjs [--lane=<id|id,id|all>] [--tier=<draft|standard|high|all>]
+// [--prompts=qb01,qb02,...] [--base-url=https://three.ws] [--resume=<run-file>]
+// [--dry-run]
+// node scripts/quality-bench.mjs --compare=latest,previous
+//
+// Requires GOOGLE_CLOUD_PROJECT + GCP credentials (GCP_SERVICE_ACCOUNT_JSON, or the
+// ambient Cloud Run/GCE metadata server) to score with Vertex Gemini — the same
+// anchor api/_lib/vertex-gemini.js uses everywhere else. Forge generation itself
+// needs no local credentials: the script calls the live /api/forge HTTP path on
+// --base-url, which runs against that deployment's own configured lanes.
+//
+// Idempotent/resumable: every completed (promptId, lane, tier) result is written to
+// the run file immediately, so a crash or Ctrl-C loses at most the one in-flight
+// generation. Re-running with --resume=<same file> skips everything already recorded
+// and never re-submits or re-spends on a completed combo.
+
+import { readFile, writeFile, mkdir, readdir } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { JUDGE_MODEL, JUDGE_PROMPT_VERSION, loadCatalog, runOne } from '../api/_lib/quality-bench.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '..');
+const BENCH_DIR = path.join(ROOT, 'data', 'quality-bench');
+const RUNS_DIR = path.join(BENCH_DIR, 'runs');
+const PROMPTS_FILE = path.join(BENCH_DIR, 'prompts.json');
+
+function parseArgs(argv) {
+ const args = { lane: 'all', tier: 'standard,high', prompts: 'all', baseUrl: 'https://three.ws', dryRun: false };
+ for (const raw of argv) {
+ const [k, ...rest] = raw.replace(/^--/, '').split('=');
+ const v = rest.join('=');
+ if (k === 'lane') args.lane = v;
+ else if (k === 'tier') args.tier = v;
+ else if (k === 'prompts') args.prompts = v;
+ else if (k === 'base-url') args.baseUrl = v;
+ else if (k === 'resume') args.resume = v;
+ else if (k === 'compare') args.compare = v;
+ else if (k === 'dry-run') args.dryRun = true;
+ }
+ return args;
+}
+
+async function loadPrompts() {
+ const raw = JSON.parse(await readFile(PROMPTS_FILE, 'utf8'));
+ return raw.prompts;
+}
+
+function liveImageBackends(catalog, requestedLane) {
+ const imageBackends = catalog.backends.filter((b) => b.paths.includes('image'));
+ if (requestedLane && requestedLane !== 'all') {
+ const ids = requestedLane.split(',').map((s) => s.trim());
+ return imageBackends.filter((b) => ids.includes(b.id));
+ }
+ return imageBackends.filter((b) => b.configured);
+}
+
+function resultKey(r) {
+ return `${r.promptId}::${r.lane}::${r.tier}`;
+}
+
+function runFilePath(name) {
+ return path.join(RUNS_DIR, name.endsWith('.json') ? name : `${name}.json`);
+}
+
+async function listRunFiles() {
+ if (!existsSync(RUNS_DIR)) return [];
+ const files = await readdir(RUNS_DIR);
+ return files.filter((f) => f.endsWith('.json')).sort();
+}
+
+async function newRunFileName() {
+ const files = await listRunFiles();
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ let n = 1;
+ let name = `run-${stamp}.json`;
+ while (files.includes(name)) {
+ n += 1;
+ name = `run-${stamp}-${n}.json`;
+ }
+ return name;
+}
+
+async function saveRun(runPath, run) {
+ await mkdir(RUNS_DIR, { recursive: true });
+ await writeFile(runPath, JSON.stringify(run, null, '\t') + '\n', 'utf8');
+}
+
+async function runBench(args) {
+ const prompts = await loadPrompts();
+ const wantedPromptIds = args.prompts === 'all' ? null : new Set(args.prompts.split(',').map((s) => s.trim()));
+ const selectedPrompts = wantedPromptIds ? prompts.filter((p) => wantedPromptIds.has(p.id)) : prompts;
+ const tiers = args.tier === 'all' ? ['draft', 'standard', 'high'] : args.tier.split(',').map((s) => s.trim());
+
+ const catalog = await loadCatalog(args.baseUrl);
+ const lanes = liveImageBackends(catalog, args.lane);
+ if (!lanes.length) {
+ throw new Error('no live image-capable forge lanes matched --lane on this deployment (check /api/forge?catalog)');
+ }
+
+ console.log(`quality-bench: ${selectedPrompts.length} prompts x ${lanes.length} lanes (${lanes.map((l) => l.id).join(', ')}) x ${tiers.length} tiers (${tiers.join(', ')}) against ${args.baseUrl}`);
+
+ let runPath;
+ let run;
+ if (args.resume) {
+ runPath = runFilePath(args.resume);
+ run = JSON.parse(await readFile(runPath, 'utf8'));
+ } else {
+ runPath = path.join(RUNS_DIR, await newRunFileName());
+ run = {
+ runId: path.basename(runPath, '.json'),
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ baseUrl: args.baseUrl,
+ judgeModel: JUDGE_MODEL,
+ judgePromptVersion: JUDGE_PROMPT_VERSION,
+ lanes: lanes.map((l) => l.id),
+ tiers,
+ results: [],
+ };
+ }
+ const done = new Set(run.results.map(resultKey));
+
+ if (args.dryRun) {
+ let planned = 0;
+ for (const p of selectedPrompts) for (const lane of lanes) for (const tier of tiers) {
+ if (!done.has(`${p.id}::${lane.id}::${tier}`)) planned += 1;
+ }
+ console.log(`dry-run: ${planned} (prompt, lane, tier) combos would run; ${done.size} already recorded in ${runPath}`);
+ return;
+ }
+
+ for (const p of selectedPrompts) {
+ for (const lane of lanes) {
+ for (const tier of tiers) {
+ const key = `${p.id}::${lane.id}::${tier}`;
+ if (done.has(key)) continue;
+ console.log(`-> ${p.id} [${p.subjectClass}] lane=${lane.id} tier=${tier}`);
+ const result = await runOne(args.baseUrl, p, lane.id, tier);
+ run.results.push(result);
+ await saveRun(runPath, run);
+ }
+ }
+ }
+
+ run.finishedAt = new Date().toISOString();
+ await saveRun(runPath, run);
+ console.log(`quality-bench: run complete -> ${runPath}`);
+ printSummary(run);
+}
+
+function printSummary(run) {
+ const byLaneTier = new Map();
+ for (const r of run.results) {
+ const key = `${r.lane}/${r.tier}`;
+ if (!byLaneTier.has(key)) byLaneTier.set(key, []);
+ if (typeof r.meanScore === 'number') byLaneTier.get(key).push(r.meanScore);
+ }
+ console.log('\nlane/tier mean n');
+ for (const [key, scores] of [...byLaneTier.entries()].sort()) {
+ const mean = scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : NaN;
+ console.log(`${key.padEnd(18)} ${mean.toFixed(2).padStart(5)} ${scores.length}`);
+ }
+}
+
+async function resolveCompareFile(token) {
+ const files = await listRunFiles();
+ if (!files.length) throw new Error('no run files found in data/quality-bench/runs/');
+ if (token === 'latest') return runFilePath(files[files.length - 1]);
+ if (token === 'previous') {
+ if (files.length < 2) throw new Error('need at least 2 runs to resolve "previous"');
+ return runFilePath(files[files.length - 2]);
+ }
+ return runFilePath(token);
+}
+
+function overallMean(run) {
+ const scores = run.results.map((r) => r.meanScore).filter((n) => typeof n === 'number');
+ if (!scores.length) return null;
+ return scores.reduce((a, b) => a + b, 0) / scores.length;
+}
+
+async function compareRuns(spec) {
+ const [aTok, bTok] = spec.split(',').map((s) => s.trim());
+ if (!aTok || !bTok) throw new Error('--compare requires two run identifiers, e.g. --compare=latest,previous');
+ const [aPath, bPath] = await Promise.all([resolveCompareFile(aTok), resolveCompareFile(bTok)]);
+ const [a, b] = await Promise.all([
+ JSON.parse(await readFile(aPath, 'utf8')),
+ JSON.parse(await readFile(bPath, 'utf8')),
+ ]);
+ const meanA = overallMean(a);
+ const meanB = overallMean(b);
+ console.log(`${aTok} (${path.basename(aPath)}): mean ${meanA?.toFixed(3)}`);
+ console.log(`${bTok} (${path.basename(bPath)}): mean ${meanB?.toFixed(3)}`);
+ if (meanA == null || meanB == null) {
+ console.error('one of the runs has no scored results; cannot compare');
+ process.exitCode = 1;
+ return;
+ }
+ const drop = meanB - meanA; // positive = "a" regressed vs "b"
+ console.log(`delta (${aTok} - ${bTok}): ${drop.toFixed(3)}`);
+ if (drop < -1.0) {
+ console.error(`REGRESSION: ${aTok} mean dropped ${Math.abs(drop).toFixed(3)} points vs ${bTok} (threshold 1.0)`);
+ process.exitCode = 1;
+ } else {
+ console.log('no regression beyond threshold (1.0)');
+ }
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.compare) {
+ await compareRuns(args.compare);
+ return;
+ }
+ await runBench(args);
+}
+
+main().catch((err) => {
+ console.error('quality-bench failed:', err.stack || err.message);
+ process.exitCode = 1;
+});
diff --git a/specs/okx-agent-payments.md b/specs/okx-agent-payments.md
index 581e94f38..8893e986a 100644
--- a/specs/okx-agent-payments.md
+++ b/specs/okx-agent-payments.md
@@ -1,42 +1,44 @@
-# OKX Agent Payments Protocol — Seller-Side Contract (three.ws A2MCP)
+# OKX Agent Payments Protocol: Seller-Side Contract (three.ws A2MCP)
-*Historical record — this Work Order research contract was captured 2026-07-06 and reconciled 2026-07-07, the day three.ws production migrated from Vercel to Google Cloud Run. Its "Set in Vercel" / "not set in Vercel production" notes describe that point-in-time state; production env vars now live on the Cloud Run service `three-ws-api` (`gcloud run services describe/update three-ws-api --region us-central1` — see [docs/ops/gcp-production.md](../docs/ops/gcp-production.md)). The seller-side wire contract (§1) and the spec→code map (§5) remain current.*
+*Historical record, this Work Order research contract was captured 2026-07-06 and reconciled 2026-07-07, the day three.ws production migrated from Vercel to Google Cloud Run. Its "Set in Vercel" / "not set in Vercel production" notes describe that point-in-time state; production env vars now live on the Cloud Run service `three-ws-api` (`gcloud run services describe/update three-ws-api --region us-central1`, see [docs/ops/gcp-production.md](../docs/ops/gcp-production.md)). The seller-side wire contract (§1) and the spec→code map (§5) remain current.*
> **Status:** Research complete. Green-light for Work Order 02.
> **Chain:** X Layer mainnet, `eip155:196` (chainId 196).
> **Our payTo:** `0x75d00a2713565171f33216e5aa2a375e076ecf69` (agent #2632 owner wallet).
> **Fee token:** USD₮0 `0x779Ded0c9e1022225f8E0630b35a9b54bE713736` (6 decimals, EIP-3009).
-> **Why this exists:** Our A2MCP endpoint ([api/mcp-3d.js](../api/mcp-3d.js)) emits x402 accepts for Solana/Base/BSC/Arbitrum only — never `eip155:196`, never the OKX fee token — and on the paid leg it reads/emits **x402 v1 header names** (`X-PAYMENT`/`x-payment-response`) rather than the **x402 v2** names OKX uses (`PAYMENT-SIGNATURE`/`PAYMENT-RESPONSE`). That is the exact reason agent #2632 was rejected on 2026-07-04. (The HTTP-level 402 gate itself ALREADY exists — see the verification note below.) This spec pins the seller-side contract from **primary sources** so 02 can implement it without opening a browser.
+> **Why this exists:** Our A2MCP endpoint ([api/mcp-3d.js](../api/mcp-3d.js)) emits x402 accepts for Solana/Base/BSC/Arbitrum only, never `eip155:196`, never the OKX fee token, and on the paid leg it reads/emits **x402 v1 header names** (`X-PAYMENT`/`x-payment-response`) rather than the **x402 v2** names OKX uses (`PAYMENT-SIGNATURE`/`PAYMENT-RESPONSE`). That is the exact reason agent #2632 was rejected on 2026-07-04. (The HTTP-level 402 gate itself ALREADY exists, see the verification note below.) This spec pins the seller-side contract from **primary sources** so 02 can implement it without opening a browser.
>
-> **Header-naming premise correction (important):** `PAYMENT-SIGNATURE` (buyer→seller) and `PAYMENT-RESPONSE` (seller→buyer) are the **vanilla x402 _v2_ standard** header names (Coinbase `x402` `specs/transports-v2/http.md`; `specs/x402-specification-v2.md:77` literally errors `"PAYMENT-SIGNATURE header is required"`). `X-PAYMENT`/`X-PAYMENT-RESPONSE` are **x402 _v1_**. OKX matches x402 v2 exactly on header naming. (The OKX SDK's `extractPayment` reads ONLY `payment-signature` and the subscription `app-payment` — there is NO v1 `x-payment` fallback in it; SDK-REPO `x402HTTPResourceServer.ts:1558-1580`. Do not rely on v1 names on the OKX rail.) The genuine OKX extensions are only: the `aggr_deferred`/`upto` schemes, the HMAC-signed OKX-hosted facilitator, `syncSettle`, `settle/status`, subscriptions, and the parallel `WWW-Authenticate: Payment` MPP rail. **Our own code labels itself "v2" but uses the v1 payment-header names — that is the delta to close for the X-Layer rail.**
+> **Header-naming premise correction (important):** `PAYMENT-SIGNATURE` (buyer→seller) and `PAYMENT-RESPONSE` (seller→buyer) are the **vanilla x402 _v2_ standard** header names (Coinbase `x402` `specs/transports-v2/http.md`; `specs/x402-specification-v2.md:77` literally errors `"PAYMENT-SIGNATURE header is required"`). `X-PAYMENT`/`X-PAYMENT-RESPONSE` are **x402 _v1_**. OKX matches x402 v2 exactly on header naming. (The OKX SDK's `extractPayment` reads ONLY `payment-signature` and the subscription `app-payment`, there is NO v1 `x-payment` fallback in it; SDK-REPO `x402HTTPResourceServer.ts:1558-1580`. Do not rely on v1 names on the OKX rail.) The genuine OKX extensions are only: the `aggr_deferred`/`upto` schemes, the HMAC-signed OKX-hosted facilitator, `syncSettle`, `settle/status`, subscriptions, and the parallel `WWW-Authenticate: Payment` MPP rail. **Our own code labels itself "v2" but uses the v1 payment-header names, that is the delta to close for the X-Layer rail.**
>
-> **Verification pass (2026-07-06, second session, independent captures — Appendix H):** a parallel WO-01 run re-derived this contract from its own wire captures (Predexon #2143 as a fourth approved seller, a second signed payment leg, on-chain RPC reads, live `x402-check` runs). It CONFIRMS every §2 answer with two corrections, applied inline below: (1) our endpoint's **HTTP-level 402 gate already exists** for non-MCP clients — bare `POST tools/call` returns `HTTP/2 402` + `PAYMENT-REQUIRED`, and `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d` parses it `valid: true` (Solana-only accepts — the gap is the missing `eip155:196` entry, not a missing gate; original Q6/G9 overstated this); (2) the SDK has no v1 `x-payment` fallback (above). It also STRENGTHENS Q3: `extra.name`/`extra.version` are now cryptographically pinned against the token's on-chain `DOMAIN_SEPARATOR()` (Appendix H.3).
+> **Verification pass (2026-07-06, second session, independent captures, Appendix H):** a parallel WO-01 run re-derived this contract from its own wire captures (Predexon #2143 as a fourth approved seller, a second signed payment leg, on-chain RPC reads, live `x402-check` runs). It CONFIRMS every §2 answer with two corrections, applied inline below: (1) our endpoint's **HTTP-level 402 gate already exists** for non-MCP clients, bare `POST tools/call` returns `HTTP/2 402` + `PAYMENT-REQUIRED`, and `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d` parses it `valid: true` (Solana-only accepts, the gap is the missing `eip155:196` entry, not a missing gate; original Q6/G9 overstated this); (2) the SDK has no v1 `x-payment` fallback (above). It also STRENGTHENS Q3: `extra.name`/`extra.version` are now cryptographically pinned against the token's on-chain `DOMAIN_SEPARATOR()` (Appendix H.3).
-> **Post-implementation reconciliation (2026-07-07, WO-01 close-out session):** the contract below has since been **implemented** by WO-02/03 and **re-validated against still-live primary sources today** — the approved-seller 402 (oklink `get_chain_info`) is byte-identical to Appendix A, the OKX facilitator still returns `HTTP 401 code 50103` requiring `OK-ACCESS-KEY`, and USD₮0 is unchanged. Spec-vs-shipped conformance was checked: [`api/_lib/x402-xlayer-okx.js`](../api/_lib/x402-xlayer-okx.js) `okxXLayerAccept()` byte-matches §1.1 (scheme `exact`, `eip155:196`, USD₮0 asset, `extra{name:"USD₮0",version:"1",transferMethod:"eip3009",decimals:6}`, `maxTimeoutSeconds:86400`), reads `PAYMENT-SIGNATURE`, routes verify/settle through `OKXFacilitatorClient`, and emits `PAYMENT-RESPONSE` per §1.2. **The §4 gap list below is therefore historical — it was 02's work list and is now closed in code**, EXCEPT the runtime is still gated: the X Layer accept is only advertised when `xlayerSettleable()` is true (`X402_PAY_TO_XLAYER` + `X402_ASSET_ADDRESS_XLAYER` + OKX HMAC creds **or** `X402_XLAYER_RELAYER_KEY`). Those env vars are **not set in Vercel production**, so `POST /api/okx/3d/*` still returns a **Solana-only** challenge with no `eip155:196` entry — i.e. the 2026-07-04 rejection cause persists *at runtime* despite the merged code. Unblocking is entirely owner-provisioning (see PROGRESS): set the X Layer env vars + OKX API credentials, fund `0x75d0…cf69` with USD₮0. No further code or research is required from this spec.
+> **Post-implementation reconciliation (2026-07-07, WO-01 close-out session):** the contract below has since been **implemented** by WO-02/03 and **re-validated against still-live primary sources today**, the approved-seller 402 (oklink `get_chain_info`) is byte-identical to Appendix A, the OKX facilitator still returns `HTTP 401 code 50103` requiring `OK-ACCESS-KEY`, and USD₮0 is unchanged. Spec-vs-shipped conformance was checked: [`api/_lib/x402-xlayer-okx.js`](../api/_lib/x402-xlayer-okx.js) `okxXLayerAccept()` byte-matches §1.1 (scheme `exact`, `eip155:196`, USD₮0 asset, `extra{name:"USD₮0",version:"1",transferMethod:"eip3009",decimals:6}`, `maxTimeoutSeconds:86400`), reads `PAYMENT-SIGNATURE`, routes verify/settle through `OKXFacilitatorClient`, and emits `PAYMENT-RESPONSE` per §1.2. **The §4 gap list below is therefore historical, it was 02's work list and is now closed in code**, EXCEPT the runtime is still gated: the X Layer accept is only advertised when `xlayerSettleable()` is true (`X402_PAY_TO_XLAYER` + `X402_ASSET_ADDRESS_XLAYER` + OKX HMAC creds **or** `X402_XLAYER_RELAYER_KEY`). Those env vars are **not set in Vercel production**, so `POST /api/okx/3d/*` still returns a **Solana-only** challenge with no `eip155:196` entry, i.e. the 2026-07-04 rejection cause persists *at runtime* despite the merged code. Unblocking is entirely owner-provisioning (see PROGRESS): set the X Layer env vars + OKX API credentials, fund `0x75d0…cf69` with USD₮0. No further code or research is required from this spec.
+
+> **Correction (2026-07-23, Work Order 07 final audit):** the "our payTo" address stated throughout this spec, `0x75d00a2713565171f33216e5aa2a375e076ecf69`, is **no longer what production advertises**. Live probe of `POST /api/okx/3d/text-to-3d` today returns `accepts[0].payTo = 0x4022de2D36C334E73C7a108805Cea11C0564f402` on `eip155:196` (confirmed against the Cloud Run service's live `X402_PAY_TO_XLAYER` env var). That address is the platform's standing EVM merchant/deployer wallet, already the `payTo` for the Base rail (see `contracts/DEPLOYMENTS.md`) and now consolidated onto X Layer too, sometime between 2026-07-07 and 2026-07-23 (no PROGRESS.md entry recorded the change; not a WO-07 regression). `0x75d0…cf69` remains agent #2632's **on-chain identity owner wallet** (the ERC-8004 registration) and the **onchainos buyer/TEE wallet** used to sign test payments, those roles are unaffected, only the payment-recipient address changed. Funding instructions in [`prompts/okx-ai/RUNBOOK.md`](../prompts/okx-ai/RUNBOOK.md) have been corrected to the live address; every `0x75d0…cf69`-as-payTo reference below (§1 examples, Appendix D, the table in §5) is now historical evidence of what was true on the date it was captured, not the current live value. Re-verify `payTo` live before any future funding request.
This is a load-bearing contract in the sense of `specs/README.md`: 02's implementation is validated against §1 (the challenge shape) and §4 (the gap list). Every claim carries a citation. Anything not verifiable from a primary source is marked **UNRESOLVED**.
**Primary sources used (all cited inline below):**
-- **SDK-REPO** — `github.com/okx/payments`, the official **OKX Payments SDK** (Apache-2.0, cloned & read 2026-07-06). Paths below are relative to `typescript/bu-payments/`.
-- **WIRE-OKLINK** — live 402 + paid replay from **Onchain Data Explorer** (agent #2023, 174 sales, approvalStatus 4), endpoint `https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info`. Captured 2026-07-06 (Appendix A).
-- **WIRE-COINANK** — live 402 from **CoinAnk OpenAPI** (agent #2013, 818 sales, approvalStatus 4), `https://open-api.coinank.com/api/etf/getUsBtcEtf` (Appendix B).
-- **WIRE-OKB** — live 402 from **OKB Monitoring** (agent #3837, approvalStatus 4), `https://okb.swaper.money/x402/digest` (Appendix C).
-- **PAY-LEG1/2** — real `onchainos payment pay` signing + paid replay from our own wallet (Appendix D).
-- **SKILL** — repo client-side skill `.claude/skills/okx-agent-payments-protocol/` (buyer constraints).
-- **SKILLS-REPO** — `github.com/okx/onchainos-skills` (the `onchainos` CLI + listing validator `cli/…/identity/validate.rs`).
-- **X402-SPEC** — `github.com/coinbase/x402` (`specs/x402-specification-v2.md`, `specs/transports-v2/http.md`) — establishes that `PAYMENT-SIGNATURE`/`PAYMENT-RESPONSE` are the x402 v2 standard, not an OKX invention.
+- **SDK-REPO**, `github.com/okx/payments`, the official **OKX Payments SDK** (Apache-2.0, cloned & read 2026-07-06). Paths below are relative to `typescript/bu-payments/`.
+- **WIRE-OKLINK**, live 402 + paid replay from **Onchain Data Explorer** (agent #2023, 174 sales, approvalStatus 4), endpoint `https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info`. Captured 2026-07-06 (Appendix A).
+- **WIRE-COINANK**, live 402 from **CoinAnk OpenAPI** (agent #2013, 818 sales, approvalStatus 4), `https://open-api.coinank.com/api/etf/getUsBtcEtf` (Appendix B).
+- **WIRE-OKB**, live 402 from **OKB Monitoring** (agent #3837, approvalStatus 4), `https://okb.swaper.money/x402/digest` (Appendix C).
+- **PAY-LEG1/2**, real `onchainos payment pay` signing + paid replay from our own wallet (Appendix D).
+- **SKILL**, repo client-side skill `.claude/skills/okx-agent-payments-protocol/` (buyer constraints).
+- **SKILLS-REPO**, `github.com/okx/onchainos-skills` (the `onchainos` CLI + listing validator `cli/…/identity/validate.rs`).
+- **X402-SPEC**, `github.com/coinbase/x402` (`specs/x402-specification-v2.md`, `specs/transports-v2/http.md`), establishes that `PAYMENT-SIGNATURE`/`PAYMENT-RESPONSE` are the x402 v2 standard, not an OKX invention.
---
-## 1. Seller contract — what OUR endpoint must emit
+## 1. Seller contract, what OUR endpoint must emit
### 1.1 The 402 challenge (concrete, with our values)
On an unpaid request to a paid A2MCP resource, respond `HTTP 402` with:
- Header **`PAYMENT-REQUIRED`**: base64 of the JSON body below.
-- Header **`Access-Control-Expose-Headers: PAYMENT-REQUIRED`** (so browser/agent clients behind CORS can read it — WIRE-OKLINK sets this).
+- Header **`Access-Control-Expose-Headers: PAYMENT-REQUIRED`** (so browser/agent clients behind CORS can read it, WIRE-OKLINK sets this).
- Body: the same JSON (SDK emits the challenge in both the header and, on the resource server, the body).
```json
@@ -75,15 +77,15 @@ On an unpaid request to a paid A2MCP resource, respond `HTTP 402` with:
| Field | Required? | Value / notes |
|---|---|---|
-| `x402Version` | ✅ required | `2` (OKB uses `1` — legacy still accepted, but emit `2`; SDK hardcodes `2`, SDK-REPO `facilitator/OKXFacilitatorClient.ts:98`). |
+| `x402Version` | ✅ required | `2` (OKB uses `1`, legacy still accepted, but emit `2`; SDK hardcodes `2`, SDK-REPO `facilitator/OKXFacilitatorClient.ts:98`). |
| `accepts[].scheme` | ✅ required | `"exact"` present in all three. `"aggr_deferred"` in 2/3 (optional). `"upto"` in **none**. |
-| `accepts[].network` | ✅ required | `"eip155:196"` in all three. **This is the field we don't emit — root cause of rejection.** |
+| `accepts[].network` | ✅ required | `"eip155:196"` in all three. **This is the field we don't emit, root cause of rejection.** |
| `accepts[].asset` | ✅ required | `0x779ded…713736` (USD₮0) in all three. |
| `accepts[].payTo` | ✅ required | Seller receiving address. Ours: `0x75d00a2713565171f33216e5aa2a375e076ecf69`. |
| `accepts[].amount` (v2) / `maxAmountRequired` (v1) | ✅ required | Atomic USD₮0 string. |
| `accepts[].maxTimeoutSeconds` | ✅ required | Seen `86400` / `300` / `300`. Use `86400` (oklink) or any ≥ a few minutes; it bounds `validBefore`. |
-| `accepts[].extra.name` | ✅ required (EIP-3009) | `"USD₮0"` — the token's **EIP-712 domain name**. Must byte-match the on-chain domain separator or the facilitator computes the wrong hash and rejects the signature. |
-| `accepts[].extra.version` | ✅ required (EIP-3009) | `"1"` — EIP-712 domain version. |
+| `accepts[].extra.name` | ✅ required (EIP-3009) | `"USD₮0"`, the token's **EIP-712 domain name**. Must byte-match the on-chain domain separator or the facilitator computes the wrong hash and rejects the signature. |
+| `accepts[].extra.version` | ✅ required (EIP-3009) | `"1"`, EIP-712 domain version. |
| `accepts[].extra.symbol` | ⬜ optional | `"USDT"`. Only WIRE-OKLINK emits it. Display hint. |
| `accepts[].extra.transferMethod` | ⬜ optional | `"eip3009"`. Only WIRE-OKLINK emits it. Default is EIP-3009 when absent (SDK `assetTransferMethod` only set for permit2 tokens; `defaultAssets.ts`). |
| `accepts[].extra.decimals` | ⬜ optional | `6`. Only WIRE-OKB (v1) puts it in `extra`; v2 sellers omit it (decimals come from the default-asset registry). |
@@ -141,7 +143,7 @@ The buyer replays the original request adding **`PAYMENT-SIGNATURE: <base64 Paym
}
```
-The seller passes `payload` + the matching `accepted` (as `paymentRequirements`) straight to the facilitator — it does not re-derive the EIP-712 hash itself. Header name is read case-insensitively (`payment-signature` OR `PAYMENT-SIGNATURE`; SDK `x402HTTPResourceServer.ts:1560`).
+The seller passes `payload` + the matching `accepted` (as `paymentRequirements`) straight to the facilitator, it does not re-derive the EIP-712 hash itself. Header name is read case-insensitively (`payment-signature` OR `PAYMENT-SIGNATURE`; SDK `x402HTTPResourceServer.ts:1560`).
### 1.4 Settlement receipt (seller → buyer)
@@ -152,27 +154,27 @@ On success attach `PAYMENT-RESPONSE` (base64 of the `SettleResponse`). Shape (SD
```
- `status: "success"` when settled with `syncSettle:true` (facilitator waited for on-chain confirmation).
-- `status: "pending"` (default, `syncSettle` unset/false) — facilitator accepted, tx settles async; seller may confirm later via `GET /api/v6/pay/x402/settle/status?txHash=…`.
-- `status: "timeout"` — on-chain confirmation timed out.
+- `status: "pending"` (default, `syncSettle` unset/false), facilitator accepted, tx settles async; seller may confirm later via `GET /api/v6/pay/x402/settle/status?txHash=…`.
+- `status: "timeout"`, on-chain confirmation timed out.
---
-## 2. Answer table — the 8 questions
+## 2. Answer table, the 8 questions
| # | Question | Answer | Citation |
|---|---|---|---|
| 1 | Exact 402 challenge shape the validator accepts | Header **`PAYMENT-REQUIRED`** = base64 JSON `{x402Version:2, resource:{url,mimeType?}, accepts:[…]}`. Per-`accepts` **required**: `scheme, network:"eip155:196", asset(USD₮0), payTo, amount, maxTimeoutSeconds, extra.name, extra.version`. `extra.symbol`/`extra.transferMethod`/`resource.mimeType` optional. No Bazaar/extensions needed. Full matrix §1.1. | WIRE-OKLINK/COINANK/OKB (Appx A-C); SDK `http/index.ts:40`, `x402HTTPResourceServer.ts:1101` |
-| 2 | Which scheme(s) mandatory for listing | **`exact` (EIP-3009) is the one required scheme** — present in all 3 approved sellers, and the verification pass adds a fourth: **Predexon #2143 is approved and payment-enforcing with ONLY `exact`** (Appx H.4), so `exact` alone demonstrably passes review. `aggr_deferred` is offered by 2/4 (optional, recommended as a second accept). **`upto` is offered by none** and is NOT needed for approval. `upto` (if ever added) requires `extra.facilitatorAddress`, which the seller must fetch from the facilitator's `/supported.signers` — it cannot be hardcoded. | WIRE-* diff; Appx H.4 (Predexon, exact-only); SDK `upto/facilitator/scheme.ts:29-39`, `upto/client/permit2.ts:32-38`; SKILL `accepts-schemes.md` |
-| 3 | Fee token `0x779Ded…713736` on X Layer | **Symbol `USDT`, name `USD₮0`, decimals `6`, EIP-3009 capable** (supports `transferWithAuthorization`). Community-recognized. Not permit2-only — the whole rail uses EIP-3009. **Cryptographically pinned (verification pass):** on-chain `name()` = `symbol()` = `"USD₮0"` (₮ = U+20AE), `decimals()` = 6; `authorizationState(address,bytes32)` answers (EIP-3009 present); and `DOMAIN_SEPARATOR()` == `keccak(EIP712Domain{name:"USD₮0",version:"1",chainId:196,verifyingContract:0x779d…})` — byte-exact, so `extra.name`/`extra.version` are proven, not inferred (Appx H.3). | `onchainos token info` (Appx E); X Layer RPC `eth_call` + domain-separator recomputation (Appx H.3); SDK `defaultAssets.ts` `DEFAULT_STABLECOINS["eip155:196"]` comment "(EIP-3009)"; live EIP-3009 sign accepted structurally by facilitator (PAY-LEG1/2) |
+| 2 | Which scheme(s) mandatory for listing | **`exact` (EIP-3009) is the one required scheme**, present in all 3 approved sellers, and the verification pass adds a fourth: **Predexon #2143 is approved and payment-enforcing with ONLY `exact`** (Appx H.4), so `exact` alone demonstrably passes review. `aggr_deferred` is offered by 2/4 (optional, recommended as a second accept). **`upto` is offered by none** and is NOT needed for approval. `upto` (if ever added) requires `extra.facilitatorAddress`, which the seller must fetch from the facilitator's `/supported.signers`, it cannot be hardcoded. | WIRE-* diff; Appx H.4 (Predexon, exact-only); SDK `upto/facilitator/scheme.ts:29-39`, `upto/client/permit2.ts:32-38`; SKILL `accepts-schemes.md` |
+| 3 | Fee token `0x779Ded…713736` on X Layer | **Symbol `USDT`, name `USD₮0`, decimals `6`, EIP-3009 capable** (supports `transferWithAuthorization`). Community-recognized. Not permit2-only, the whole rail uses EIP-3009. **Cryptographically pinned (verification pass):** on-chain `name()` = `symbol()` = `"USD₮0"` (₮ = U+20AE), `decimals()` = 6; `authorizationState(address,bytes32)` answers (EIP-3009 present); and `DOMAIN_SEPARATOR()` == `keccak(EIP712Domain{name:"USD₮0",version:"1",chainId:196,verifyingContract:0x779d…})`, byte-exact, so `extra.name`/`extra.version` are proven, not inferred (Appx H.3). | `onchainos token info` (Appx E); X Layer RPC `eth_call` + domain-separator recomputation (Appx H.3); SDK `defaultAssets.ts` `DEFAULT_STABLECOINS["eip155:196"]` comment "(EIP-3009)"; live EIP-3009 sign accepted structurally by facilitator (PAY-LEG1/2) |
| 4 | OKX facilitator verify/settle URLs, shapes, auth | Base `https://web3.okx.com`. **`POST /api/v6/pay/x402/verify`**, **`POST /api/v6/pay/x402/settle`**, `GET /api/v6/pay/x402/supported`, `GET /api/v6/pay/x402/settle/status?txHash=`. Body `{x402Version:2, paymentPayload, paymentRequirements[, syncSettle]}`. Responses wrapped `{code,msg,data}`. **Auth = OKX REST HMAC-SHA256**: headers `OK-ACCESS-KEY`, `OK-ACCESS-SIGN`(=base64(HMAC-SHA256(secret, timestamp+method+path+body))), `OK-ACCESS-TIMESTAMP`(ISO-8601), `OK-ACCESS-PASSPHRASE`. **⇒ We need an OKX API key/secret/passphrase.** `upto`'s `extra.facilitatorAddress` = `supported.signers[family][0]` via `getExtra()`. | SDK `facilitator/OKXFacilitatorClient.ts` (all endpoints + `createHeaders` L60-76); `upto/facilitator/scheme.ts:39` |
-| 5 | The official OKX Payment SDK | **`github.com/okx/payments` = "OKX Payments SDK", Apache-2.0** (monorepo `@okxweb3/payments-sdk-monorepo`; Go/Python/Rust/TS/Java). **Use the `@okxweb3/app-x402-*` family @ v0.2.0** (`-core`, `-evm`, `-express`/`-next`/`-hono`/`-fastify`, `-mpp`) — that's what the runnable demo imports (published 2026-07-03). **⚠️ Avoid the stale `@okxweb3/x402-*` @ v0.1.0** (`x402-core`/`x402-evm`/`mpp`) that the repo's `SELLER.md` still names — last touched 2026-06-08. Pure TypeScript (deps `viem`/`zod`/`axios`/`mppx` — pure JS, `@noble` crypto, `node:crypto` HMAC, no native bindings) ⇒ **runs in Vercel functions**. Seller-side it builds the 402 challenge, reads `PAYMENT-SIGNATURE`, calls facilitator verify/settle, emits `PAYMENT-RESPONSE`, plus lifecycle hooks + metered `setSettlementOverrides`. Weekly downloads low (new pkg): app-x402-core ≈267, -evm ≈204, -express ≈188. | SDK-REPO README + `package.json`; `npm view @okxweb3/app-x402-*`; `api.npmjs.org/downloads/point/last-week`; `app-x402-next/README.md` |
-| 6 | HTTP-level 402 vs MCP-level PaymentRequired | OKX expects **HTTP-level 402** on the endpoint URL: real `HTTP/2 402` status + `PAYMENT-REQUIRED` header, paid replay via `PAYMENT-SIGNATURE` header. All approved sellers do HTTP-level; the validator/buyer never inspects JSON-RPC `_meta`. **CORRECTED (verification pass): our endpoint ALREADY has this HTTP-level gate** — a bare (non-MCP) `POST tools/call` gets `HTTP/2 402` + `PAYMENT-REQUIRED`, live-verified for `text_to_3d` and `auto_rig_model`, and `x402-check` parses it `valid: true` (Appx H.1). Only MCP-protocol clients (`mcp-protocol-version` header) are routed to 401/OAuth, which OKX tooling never sends. 02's work on this axis is ONLY: the paid-replay leg must also accept `PAYMENT-SIGNATURE` (G7) and emit `PAYMENT-RESPONSE` (G8); the MCP-level `_meta` flow stays for MCP-native clients. | WIRE-OKLINK (POST→402, GET→405); Appx H.1 (live status matrix + x402-check `valid:true`); [api/mcp-3d.js](../api/mcp-3d.js), [api/_mcp/auth.js](../api/_mcp/auth.js); SDK is HTTP-transport only |
-| 7 | How listing review validates the endpoint | Two layers. **(a) Registration-time `validate-listing` is PURE-LOCAL — no HTTP probe** (`onchainos-skills` `cli/…/identity/validate.rs`): it only checks A2MCP has an `endpoint`, the URL is `https://` + publicly reachable (rejects `http`, `localhost`, `127.0.0.1`, RFC-1918, `*.local/.internal`, mock/placeholder, >512 chars), fee is a plain number (USDT implicit), description has no URLs/addresses. It writes the endpoint URL on-chain (ERC-8004). Service-type → rail: **`A2MCP → x402`**. **(b) Approval / rejection** ("A2MCP service has not been integrated with the OKX Agent Payments Protocol") is a **human/off-repo review** — no codified automated probe that asserts the 402 shape exists in `okx/payments` or `onchainos-skills`. To pass it, the live endpoint must emit a v2 `402` whose `accepts` advertise **`eip155:196` + USD₮0** at the registered price. **Self-check tool (manual, not the gate):** `onchainos agent x402-check --endpoint <url>` flags `"Endpoint returned HTTP 200 (not 402); not a valid x402 service"` when the gate is absent (Appx E). **UNRESOLVED:** the exact method/body of any OKX-side automated probe, and whether one exists, are undocumented (dev-portal pages are JS-rendered / 404 to fetch). 02 should register, run `x402-check` against `https://three.ws/api/mcp-3d`, confirm `valid:true`, then resubmit for (human) review. | `onchainos-skills` `identity/validate.rs`, `task-cli-reference.md:396`; `onchainos agent x402-check` (Appx E); rejection email (00-CONTEXT) |
-| 8 | Settlement finality — how seller confirms payment | Seller trusts the facilitator's responses, not its own chain read. `/verify` → `isValid:true` gates doing the work (proves the signed authorization is valid + payer funded — a broke payer gets `isValid:false` / `insufficient_balance`, proven by PAY-LEG2). `/settle` → `{success, status}`: `syncSettle:true` ⇒ `status:"success"` (on-chain confirmed before responding); default async ⇒ `status:"pending"` (safe to release; poll `/settle/status?txHash` for finality). The `PAYMENT-RESPONSE` header carries `{success,status,transaction,payer,amount}` to the buyer. | SDK `OKXFacilitatorClient.ts` settle L124-150 + `syncSettle` docstring; `types/facilitator.ts:26-38`; PAY-LEG2 |
+| 5 | The official OKX Payment SDK | **`github.com/okx/payments` = "OKX Payments SDK", Apache-2.0** (monorepo `@okxweb3/payments-sdk-monorepo`; Go/Python/Rust/TS/Java). **Use the `@okxweb3/app-x402-*` family @ v0.2.0** (`-core`, `-evm`, `-express`/`-next`/`-hono`/`-fastify`, `-mpp`), that's what the runnable demo imports (published 2026-07-03). **⚠️ Avoid the stale `@okxweb3/x402-*` @ v0.1.0** (`x402-core`/`x402-evm`/`mpp`) that the repo's `SELLER.md` still names, last touched 2026-06-08. Pure TypeScript (deps `viem`/`zod`/`axios`/`mppx`, pure JS, `@noble` crypto, `node:crypto` HMAC, no native bindings) ⇒ **runs in Vercel functions**. Seller-side it builds the 402 challenge, reads `PAYMENT-SIGNATURE`, calls facilitator verify/settle, emits `PAYMENT-RESPONSE`, plus lifecycle hooks + metered `setSettlementOverrides`. Weekly downloads low (new pkg): app-x402-core ≈267, -evm ≈204, -express ≈188. | SDK-REPO README + `package.json`; `npm view @okxweb3/app-x402-*`; `api.npmjs.org/downloads/point/last-week`; `app-x402-next/README.md` |
+| 6 | HTTP-level 402 vs MCP-level PaymentRequired | OKX expects **HTTP-level 402** on the endpoint URL: real `HTTP/2 402` status + `PAYMENT-REQUIRED` header, paid replay via `PAYMENT-SIGNATURE` header. All approved sellers do HTTP-level; the validator/buyer never inspects JSON-RPC `_meta`. **CORRECTED (verification pass): our endpoint ALREADY has this HTTP-level gate**, a bare (non-MCP) `POST tools/call` gets `HTTP/2 402` + `PAYMENT-REQUIRED`, live-verified for `text_to_3d` and `auto_rig_model`, and `x402-check` parses it `valid: true` (Appx H.1). Only MCP-protocol clients (`mcp-protocol-version` header) are routed to 401/OAuth, which OKX tooling never sends. 02's work on this axis is ONLY: the paid-replay leg must also accept `PAYMENT-SIGNATURE` (G7) and emit `PAYMENT-RESPONSE` (G8); the MCP-level `_meta` flow stays for MCP-native clients. | WIRE-OKLINK (POST→402, GET→405); Appx H.1 (live status matrix + x402-check `valid:true`); [api/mcp-3d.js](../api/mcp-3d.js), [api/_mcp/auth.js](../api/_mcp/auth.js); SDK is HTTP-transport only |
+| 7 | How listing review validates the endpoint | Two layers. **(a) Registration-time `validate-listing` is PURE-LOCAL, no HTTP probe** (`onchainos-skills` `cli/…/identity/validate.rs`): it only checks A2MCP has an `endpoint`, the URL is `https://` + publicly reachable (rejects `http`, `localhost`, `127.0.0.1`, RFC-1918, `*.local/.internal`, mock/placeholder, >512 chars), fee is a plain number (USDT implicit), description has no URLs/addresses. It writes the endpoint URL on-chain (ERC-8004). Service-type → rail: **`A2MCP → x402`**. **(b) Approval / rejection** ("A2MCP service has not been integrated with the OKX Agent Payments Protocol") is a **human/off-repo review**, no codified automated probe that asserts the 402 shape exists in `okx/payments` or `onchainos-skills`. To pass it, the live endpoint must emit a v2 `402` whose `accepts` advertise **`eip155:196` + USD₮0** at the registered price. **Self-check tool (manual, not the gate):** `onchainos agent x402-check --endpoint <url>` flags `"Endpoint returned HTTP 200 (not 402); not a valid x402 service"` when the gate is absent (Appx E). **UNRESOLVED:** the exact method/body of any OKX-side automated probe, and whether one exists, are undocumented (dev-portal pages are JS-rendered / 404 to fetch). 02 should register, run `x402-check` against `https://three.ws/api/mcp-3d`, confirm `valid:true`, then resubmit for (human) review. | `onchainos-skills` `identity/validate.rs`, `task-cli-reference.md:396`; `onchainos agent x402-check` (Appx E); rejection email (00-CONTEXT) |
+| 8 | Settlement finality, how seller confirms payment | Seller trusts the facilitator's responses, not its own chain read. `/verify` → `isValid:true` gates doing the work (proves the signed authorization is valid + payer funded, a broke payer gets `isValid:false` / `insufficient_balance`, proven by PAY-LEG2). `/settle` → `{success, status}`: `syncSettle:true` ⇒ `status:"success"` (on-chain confirmed before responding); default async ⇒ `status:"pending"` (safe to release; poll `/settle/status?txHash` for finality). The `PAYMENT-RESPONSE` header carries `{success,status,transaction,payer,amount}` to the buyer. | SDK `OKXFacilitatorClient.ts` settle L124-150 + `syncSettle` docstring; `types/facilitator.ts:26-38`; PAY-LEG2 |
---
-## 3. SDK decision — adopt `@okxweb3/app-x402-*` (with a thin adapter)
+## 3. SDK decision, adopt `@okxweb3/app-x402-*` (with a thin adapter)
**Decision: ADOPT the OKX Payments SDK for the OKX/X-Layer rail; keep our existing `api/_lib/x402-spec.js` for the Solana/Base/BSC rails.** Do not hand-roll the OKX dialect.
@@ -180,21 +182,21 @@ Per CLAUDE.md "Open-source first" checklist:
| Criterion | Finding | Verdict |
|---|---|---|
-| Solves the problem | Yes — builds the exact `eip155:196` challenge, HMAC-signs facilitator calls, handles `exact`/`aggr_deferred`/`upto`/`period`, emits `PAYMENT-RESPONSE`. First-party, so it tracks the spec the validator enforces. | ✅ |
+| Solves the problem | Yes, builds the exact `eip155:196` challenge, HMAC-signs facilitator calls, handles `exact`/`aggr_deferred`/`upto`/`period`, emits `PAYMENT-RESPONSE`. First-party, so it tracks the spec the validator enforces. | ✅ |
| Maintenance / provenance | Official OKX org (`okx/payments`), the SDK the rejection email points to. Multi-language, actively structured. v0.2.0 (early but first-party). | ✅ |
| License | **Apache-2.0** (`@okxweb3/app-mpp` is MIT). Compatible with our commercial use. | ✅ |
| Vercel compatibility | Pure TS, deps are `fetch` + `node:crypto` + `viem`-class EVM libs; no native addons. `@okxweb3/app-x402-next` targets Next/serverless directly. | ✅ |
-| Weekly downloads | Low — app-x402-core ≈267/wk, -evm ≈204, -express ≈188 (v0.2.0, published 2026-07-03). Mitigated by first-party status + our own tests. | ⚠️ acceptable |
+| Weekly downloads | Low, app-x402-core ≈267/wk, -evm ≈204, -express ≈188 (v0.2.0, published 2026-07-03). Mitigated by first-party status + our own tests. | ⚠️ acceptable |
**⚠️ Package trap:** install the **`@okxweb3/app-x402-*` v0.2.0** family (what the demo imports), NOT the stale **`@okxweb3/x402-*` v0.1.0** family the repo's `SELLER.md` documents (last touched 2026-06-08).
-**Adoption shape for 02:** our endpoint is a bare Vercel function (`api/mcp-3d.js`, Node `req/res`), not a Next.js app-router route, so `withX402` (needs `NextRequest`/`NextResponse`) is not a drop-in. Use the framework-agnostic core: `@okxweb3/app-x402-core` (`x402ResourceServer`, `OKXFacilitatorClient`, the `HTTPAdapter` interface, header codecs) + `@okxweb3/app-x402-evm` (`ExactEvmScheme`). Write a ~30-line `HTTPAdapter` over our Node `req`. This gives the OKX 402/verify/settle for `eip155:196` alongside our current multi-chain `paymentRequirements()` for the other rails. Reference seller wiring: SDK `demo/x402/src/index.ts` (Express) and `app-x402-next/README.md` (`withX402`). **Serverless caveat:** `await resourceServer.initialize()` calls the facilitator `/supported` and must run once per cold start (lazily) before the first paid request — it is what populates `upto`'s `facilitatorAddress` and validates scheme support.
+**Adoption shape for 02:** our endpoint is a bare Vercel function (`api/mcp-3d.js`, Node `req/res`), not a Next.js app-router route, so `withX402` (needs `NextRequest`/`NextResponse`) is not a drop-in. Use the framework-agnostic core: `@okxweb3/app-x402-core` (`x402ResourceServer`, `OKXFacilitatorClient`, the `HTTPAdapter` interface, header codecs) + `@okxweb3/app-x402-evm` (`ExactEvmScheme`). Write a ~30-line `HTTPAdapter` over our Node `req`. This gives the OKX 402/verify/settle for `eip155:196` alongside our current multi-chain `paymentRequirements()` for the other rails. Reference seller wiring: SDK `demo/x402/src/index.ts` (Express) and `app-x402-next/README.md` (`withX402`). **Serverless caveat:** `await resourceServer.initialize()` calls the facilitator `/supported` and must run once per cold start (lazily) before the first paid request, it is what populates `upto`'s `facilitatorAddress` and validates scheme support.
**Env we must add:** `OKX_API_KEY`, `OKX_SECRET_KEY`, `OKX_PASSPHRASE` (facilitator HMAC), plus the payTo already known. **Blocker for 02:** these OKX API credentials must be provisioned by the owner from the OKX Web3 developer console. Without them every `/verify` and `/settle` fails auth. → raised in PROGRESS.
---
-## 4. Gap analysis — `paymentRequirements()` today vs. what OKX requires (02's work list)
+## 4. Gap analysis, `paymentRequirements()` today vs. what OKX requires (02's work list)
Reference: [api/_lib/x402-spec.js](../api/_lib/x402-spec.js) `paymentRequirements()` (L162-232) and `buildExactRequirements()` (L362-398).
@@ -202,13 +204,13 @@ Reference: [api/_lib/x402-spec.js](../api/_lib/x402-spec.js) `paymentRequirement
|---|---|---|---|
| G1 | Accepts for `NETWORK_SOLANA_MAINNET`, `NETWORK_BASE_MAINNET`, `NETWORK_BSC_MAINNET`, `NETWORK_ARBITRUM_MAINNET`. **No `eip155:196`.** | An `accepts` entry with `network:"eip155:196"`. | Add `NETWORK_XLAYER_MAINNET = "eip155:196"` and an X-Layer branch (behind an env like `X402_PAY_TO_XLAYER`). |
| G2 | `asset` = USDC on Solana/Base; `X402_ASSET_ADDRESS_BASE`. | `asset` = `0x779ded0c9e1022225f8e0630b35a9b54be713736` (USD₮0). | Hardcode/env the USD₮0 mint for the X-Layer accept. |
-| G3 | `extra: { name, decimals }` (Base) / `{ name, decimals, feePayer }` (Solana). | `extra: { name:"USD₮0", version:"1" }` (+ optional `symbol`,`transferMethod`,`decimals`). **`version` is required.** | New `extra` builder for the X-Layer accept: `name`+`version` mandatory. `decimals: 6` is optional (v2 sellers omit it) but RECOMMENDED: without it `x402-check` emits a `tokenResolveError` ("cannot determine token decimals … does not provide a `decimals` field", Appx H.2) because USD₮0 is outside the task system's supported-token list — harmless for oklink but free to avoid. |
-| G4 | Field name `extra.assetTransferMethod` (permit2 path). | OKX exact uses `extra.transferMethod:"eip3009"` (or omit → EIP-3009 default). | Emit `transferMethod` (optional) — do NOT emit `assetTransferMethod` on the X-Layer accept. |
+| G3 | `extra: { name, decimals }` (Base) / `{ name, decimals, feePayer }` (Solana). | `extra: { name:"USD₮0", version:"1" }` (+ optional `symbol`,`transferMethod`,`decimals`). **`version` is required.** | New `extra` builder for the X-Layer accept: `name`+`version` mandatory. `decimals: 6` is optional (v2 sellers omit it) but RECOMMENDED: without it `x402-check` emits a `tokenResolveError` ("cannot determine token decimals … does not provide a `decimals` field", Appx H.2) because USD₮0 is outside the task system's supported-token list, harmless for oklink but free to avoid. |
+| G4 | Field name `extra.assetTransferMethod` (permit2 path). | OKX exact uses `extra.transferMethod:"eip3009"` (or omit → EIP-3009 default). | Emit `transferMethod` (optional), do NOT emit `assetTransferMethod` on the X-Layer accept. |
| G5 | Schemes `exact` (EIP-3009/permit2) + `direct` (BSC). **No `aggr_deferred`.** | `exact` mandatory; `aggr_deferred` recommended 2nd accept. | Emit `exact` for X-Layer; optionally add `aggr_deferred` accept (SDK `ExactEvmScheme`/aggr scheme). |
| G6 | Facilitator routing = CDP / PayAI / self / BSC-direct (`facilitatorFor()`). **No OKX facilitator.** | verify/settle at `https://web3.okx.com/api/v6/pay/x402/{verify,settle}` with HMAC auth. | Add an `OKXFacilitatorClient` route for `eip155:196` (adopt SDK, §3). |
-| G7 | Payment header read = **`X-PAYMENT`** (x402 v1 name; `decodePaymentHeader`, `verifyPayment`) — despite the file labeling itself "v2". | Buyer sends **`PAYMENT-SIGNATURE`** (the x402 **v2** standard name). | On the X-Layer path read `PAYMENT-SIGNATURE` (case-insensitive; also accept `x-payment` for v1 back-compat). Keep `X-PAYMENT` for the other rails. |
+| G7 | Payment header read = **`X-PAYMENT`** (x402 v1 name; `decodePaymentHeader`, `verifyPayment`), despite the file labeling itself "v2". | Buyer sends **`PAYMENT-SIGNATURE`** (the x402 **v2** standard name). | On the X-Layer path read `PAYMENT-SIGNATURE` (case-insensitive; also accept `x-payment` for v1 back-compat). Keep `X-PAYMENT` for the other rails. |
| G8 | Success receipt = **`x-payment-response`** (x402 v1 name; set in `api/mcp-3d.js:107` etc.). | **`PAYMENT-RESPONSE`** (x402 v2 name). | Emit `PAYMENT-RESPONSE` on the X-Layer success reply. |
-| G9 | ~~Gating is MCP-level only~~ **CORRECTED:** HTTP-level 402 + `PAYMENT-REQUIRED` already emitted to non-MCP clients ([api/_mcp/auth.js](../api/_mcp/auth.js) `send402` path; live-verified `HTTP/2 402` on bare `tools/call`, Appx H.1). MCP-protocol clients get 401/OAuth — fine, OKX tooling never sends `mcp-protocol-version`. | **HTTP-level 402** on the endpoint URL — already satisfied. | No new gate. Verify with `x402-check` after G1-G8 land; keep the 401/OAuth branch for MCP clients as-is. |
+| G9 | ~~Gating is MCP-level only~~ **CORRECTED:** HTTP-level 402 + `PAYMENT-REQUIRED` already emitted to non-MCP clients ([api/_mcp/auth.js](../api/_mcp/auth.js) `send402` path; live-verified `HTTP/2 402` on bare `tools/call`, Appx H.1). MCP-protocol clients get 401/OAuth, fine, OKX tooling never sends `mcp-protocol-version`. | **HTTP-level 402** on the endpoint URL, already satisfied. | No new gate. Verify with `x402-check` after G1-G8 land; keep the 401/OAuth branch for MCP clients as-is. |
| G10 | Body carries `extensions.bazaar` + `builder-code` + `offer-receipt`. | OKX sellers emit none of these on the `eip155:196` accepts. | Keep the OKX accept body minimal (`x402Version/resource/accepts`); don't attach Bazaar extensions to it. |
| G11 | Facilitator auth = CDP JWT / bearer token. | OKX HMAC needs `OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`. | Provision + wire the three env vars (owner blocker). |
| G12 | `maxTimeoutSeconds: 60`. | Approved sellers use `86400`/`300`. | Use ≥ ~300 on X-Layer (bounds `validBefore`); `86400` matches oklink. |
@@ -217,10 +219,10 @@ Reference: [api/_lib/x402-spec.js](../api/_lib/x402-spec.js) `paymentRequirement
---
-## 5. Implementation (Work Order 02 — landed 2026-07-07)
+## 5. Implementation (Work Order 02, landed 2026-07-07)
The OKX/X Layer rail was implemented as an **addition** to the existing multi-rail
-`x402-spec.js` seams — not a parallel payment stack. The `eip155:196` accept, the OKX
+`x402-spec.js` seams, not a parallel payment stack. The `eip155:196` accept, the OKX
facilitator verify/settle route, and the x402-v2 receipt header names all flow through
the same `paymentRequirements()` / `verifyPayment()` / `settlePayment()` /
`encodePaymentResponseHeader()` functions every other rail uses, selected by the network
@@ -228,15 +230,15 @@ of the presented payment. Spec → code map (file:line at landing commit `05de05
| Spec / Gap | Requirement | Code |
|---|---|---|
-| §1.1, G1–G5, G12 | The `eip155:196` accept, byte-shaped to the approved-seller wire (`scheme:exact`, USD₮0 asset, `extra.{name,version,symbol,transferMethod,decimals}`, `maxTimeoutSeconds:86400`) | [`okxXLayerAccept()`](../api/_lib/x402-xlayer-okx.js#L190-L210) — the domain constants `USDT0_DOMAIN_NAME='USD₮0'` (₮ = U+20AE) / `USDT0_DOMAIN_VERSION='1'` are [pinned + commented](../api/_lib/x402-xlayer-okx.js#L59-L65) against Appx H.3 |
+| §1.1, G1–G5, G12 | The `eip155:196` accept, byte-shaped to the approved-seller wire (`scheme:exact`, USD₮0 asset, `extra.{name,version,symbol,transferMethod,decimals}`, `maxTimeoutSeconds:86400`) | [`okxXLayerAccept()`](../api/_lib/x402-xlayer-okx.js#L190-L210), the domain constants `USDT0_DOMAIN_NAME='USD₮0'` (₮ = U+20AE) / `USDT0_DOMAIN_VERSION='1'` are [pinned + commented](../api/_lib/x402-xlayer-okx.js#L59-L65) against Appx H.3 |
| §1.1 | Advertise the accept only when settlement is actually possible (never 402-then-502) | [`xlayerSettleable()`](../api/_lib/x402-xlayer-okx.js#L179-L185); wired into [`paymentRequirements()`](../api/_lib/x402-spec.js#L239-L246) after the Solana/Base/BSC accepts (multi-rail coexistence, requirement 4) |
-| §1.1 amount | Advertised == verified == settled, all from `priceBatch`/`studioX402Amount` (requirement 6) | The X Layer accept takes `common.amount` (the per-tool price) unchanged — USD₮0 shares USDC's 6-decimal atomic scale, so `150000` = $0.15 across every rail. [x402-spec.js#L245](../api/_lib/x402-spec.js#L245) |
+| §1.1 amount | Advertised == verified == settled, all from `priceBatch`/`studioX402Amount` (requirement 6) | The X Layer accept takes `common.amount` (the per-tool price) unchanged, USD₮0 shares USDC's 6-decimal atomic scale, so `150000` = $0.15 across every rail. [x402-spec.js#L245](../api/_lib/x402-spec.js#L245) |
| §1.2 step 3, G6 | Route verify/settle to the OKX rail by network | [`facilitatorFor()` → `{okxXLayer:true}`](../api/_lib/x402-spec.js#L287-L292) for `eip155:196` |
-| §1.2 step 4, requirement 2 | Verify BEFORE work — real EIP-712 recovery (ERC-1271-aware for smart-account wallets), recipient/amount/time-window checks, unused-nonce + `balanceOf` on-chain, then the OKX facilitator `/verify` when credentialed | [`verifyOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L272-L416); dispatched from [`verifyPayment()`](../api/_lib/x402-spec.js#L1014-L1022). Invalid/underpaid/expired throws `X402Error` 402 → fresh challenge, tool does not run |
+| §1.2 step 4, requirement 2 | Verify BEFORE work, real EIP-712 recovery (ERC-1271-aware for smart-account wallets), recipient/amount/time-window checks, unused-nonce + `balanceOf` on-chain, then the OKX facilitator `/verify` when credentialed | [`verifyOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L272-L416); dispatched from [`verifyPayment()`](../api/_lib/x402-spec.js#L1014-L1022). Invalid/underpaid/expired throws `X402Error` 402 → fresh challenge, tool does not run |
| §1.2 step 6, §1.4, requirement 3 | Settle only after tool success; OKX facilitator `/settle` (`syncSettle:true`) primary, direct EIP-3009 redemption fallback; return `{success,status,transaction,payer,amount}` | [`settleOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L442-L530); dispatched from [`settlePayment()`](../api/_lib/x402-spec.js#L1110-L1120). Called only after `anySuccess` in [mcp-3d.js](../api/mcp-3d.js#L103-L119) and [okx/3d/[service].js](../api/okx/3d/%5Bservice%5D.js#L377-L392) |
| §1.3, G7 | Read the buyer's `PAYMENT-SIGNATURE` (x402 v2) header; parse the OKX `{accepted, payload:{authorization,signature}}` dialect | [auth.js reads `payment-signature`](../api/_mcp/auth.js#L94-L97); [`selectRequirement()` matches `paymentPayload.accepted.network`](../api/_lib/x402-spec.js#L786-L792); [`extractAuthorization()`](../api/_lib/x402-xlayer-okx.js#L237-L249) |
| §1.4, G8 | Emit `PAYMENT-RESPONSE` (x402 v2) receipt with `status`+`amount`; keep `x-payment-response` (v1) as an alias | [`encodePaymentResponseHeader()`](../api/_lib/x402-spec.js#L1169-L1186) now passes through `status`/`amount`; both header names set in [mcp-3d.js#L108-L116](../api/mcp-3d.js#L108-L116) and [service].js; both added to the [CORS expose list](../api/_lib/http.js#L383-L386) |
-| §Q4/§Q5, G6/G11 | OKX facilitator client (HMAC-SHA256 auth) | Adopt the official SDK [`OKXFacilitatorClient` from `@okxweb3/app-x402-core@^0.2.0`](../api/_lib/x402-xlayer-okx.js#L51) behind our seams (SDK decision §3) — no hand-rolled dialect |
+| §Q4/§Q5, G6/G11 | OKX facilitator client (HMAC-SHA256 auth) | Adopt the official SDK [`OKXFacilitatorClient` from `@okxweb3/app-x402-core@^0.2.0`](../api/_lib/x402-xlayer-okx.js#L51) behind our seams (SDK decision §3), no hand-rolled dialect |
| G9 | HTTP-level 402 gate | Already present (Appx H.1); unchanged. The `send402`/`sendAuthChallenge` non-MCP branch emits the challenge to bare `tools/call` |
| G10 | Keep the OKX accept minimal | The X Layer accept carries no per-accept Bazaar extension; `sendOkx402()` ([x402-xlayer-okx.js#L218-L232](../api/_lib/x402-xlayer-okx.js#L218-L232)) emits the minimal `{x402Version,resource,accepts}` for the decomposed `/api/okx/3d/*` services. (The `/api/mcp-3d` MCP endpoint keeps its Bazaar body for its non-OKX discovery role; the X Layer accept inside it is still minimal.) |
@@ -244,20 +246,20 @@ of the presented payment. Spec → code map (file:line at landing commit `05de05
| Var | Purpose | Set in Vercel? |
|---|---|---|
-| `X402_PAY_TO_XLAYER` | Seller receiving address on X Layer (owner wallet `0x75d0…cf69`) | ✅ Preview + Production (owner set 2026-07-07) |
+| `X402_PAY_TO_XLAYER` | Seller receiving address on X Layer | ✅ set in production. Value as of 2026-07-07: `0x75d0…cf69`. **Value live 2026-07-23 (WO-07 audit): `0x4022de2D…f402`, the platform's standard EVM merchant wallet**, see the 2026-07-23 correction note above. |
| `X402_ASSET_ADDRESS_XLAYER` | USD₮0 mint; defaults to `0x779ded…713736` in [env.js](../api/_lib/env.js#L752-L754) so it needs no explicit set | default |
| `X402_XLAYER_RELAYER_KEY` | Relayer key for the direct-redemption settle fallback (no OKX creds) | ✅ Preview + Production |
-| `OKX_API_KEY` / `OKX_SECRET_KEY` / `OKX_PASSPHRASE` | OKX facilitator HMAC — enables the official `/verify`+`/settle` route | ❌ **owner action** (see PROGRESS) |
+| `OKX_API_KEY` / `OKX_SECRET_KEY` / `OKX_PASSPHRASE` | OKX facilitator HMAC, enables the official `/verify`+`/settle` route | ❌ **owner action** (see PROGRESS) |
With `X402_PAY_TO_XLAYER` + `X402_XLAYER_RELAYER_KEY` set, `xlayerSettleable()` is true and the rail is advertised and settleable via direct redemption today. The OKX facilitator creds are the preferred settle route (gasless, first-party) and remain the one owner blocker for WO-04's funded run.
-**Verification captured this session (local, real module over `node:http`):** unpaid `POST tools/call text_to_3d` → `HTTP/1.1 402` whose `accepts[1]` is the `eip155:196` USD₮0 entry with every §1.1 field byte-exact (`extra.name` bytes = `555344e282ae30`, confirmed). `onchainos payment pay --selected-index 1` ACCEPTED it and returned a `PAYMENT-SIGNATURE` header signing `value:"150000"` to our payTo on `eip155:196`. Replaying that header against our endpoint (wallet holds 0 USD₮0) ran the real on-chain verify and returned `402 error:"insufficient_balance"` with a fresh full challenge — the tool did not run. Field-validated captures in `prompts/okx-ai/e2e-evidence/`.
+**Verification captured this session (local, real module over `node:http`):** unpaid `POST tools/call text_to_3d` → `HTTP/1.1 402` whose `accepts[1]` is the `eip155:196` USD₮0 entry with every §1.1 field byte-exact (`extra.name` bytes = `555344e282ae30`, confirmed). `onchainos payment pay --selected-index 1` ACCEPTED it and returned a `PAYMENT-SIGNATURE` header signing `value:"150000"` to our payTo on `eip155:196`. Replaying that header against our endpoint (wallet holds 0 USD₮0) ran the real on-chain verify and returned `402 error:"insufficient_balance"` with a fresh full challenge, the tool did not run. Field-validated captures in `prompts/okx-ai/e2e-evidence/`.
---
-## Appendix — raw captures (verbatim, dated 2026-07-06)
+## Appendix, raw captures (verbatim, dated 2026-07-06)
-### A. WIRE-OKLINK — Onchain Data Explorer #2023 (174 sales), `get_chain_info`
+### A. WIRE-OKLINK, Onchain Data Explorer #2023 (174 sales), `get_chain_info`
`GET` → `HTTP/2 405 {"code":"405","msg":"Method Not Allowed"}`. `POST {}` → `HTTP/2 402`:
@@ -272,15 +274,15 @@ Decoded body:
{"x402Version":2,"resource":{"url":"https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info","mimeType":"application/json"},"accepts":[{"scheme":"exact","network":"eip155:196","amount":"15","payTo":"0xa7e37604ebab94408159e405033a455f820fd987","maxTimeoutSeconds":86400,"asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","extra":{"symbol":"USDT","version":"1","transferMethod":"eip3009","name":"USD₮0"}},{"scheme":"aggr_deferred","network":"eip155:196","amount":"15","payTo":"0xa7e37604ebab94408159e405033a455f820fd987","maxTimeoutSeconds":86400,"asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","extra":{"symbol":"USDT","version":"1","transferMethod":"eip3009","name":"USD₮0"}}]}
```
-### B. WIRE-COINANK — CoinAnk OpenAPI #2013 (818 sales), `getUsBtcEtf`
+### B. WIRE-COINANK, CoinAnk OpenAPI #2013 (818 sales), `getUsBtcEtf`
`GET` → `HTTP/2 402`. Emits BOTH `payment-required` (v2, 4 accepts) AND four `WWW-Authenticate: Payment` headers (MPP charge+session). The seller offers each scheme in TWO currencies: the USD₮0 fee token AND a second X-Layer stablecoin. Only the **USD₮0** accepts matter for our contract; the second currency's mint/name are omitted here (not load-bearing, out of our USD₮0-only scope). USD₮0 accepts, decoded verbatim:
```json
{"x402Version":2,"accepts":[
- { "…second-stablecoin exact accept — identifiers omitted…" },
+ { "…second-stablecoin exact accept, identifiers omitted…" },
{"x402Version":2,"scheme":"exact","network":"eip155:196","amount":"1000","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}},
- { "…second-stablecoin aggr_deferred accept — identifiers omitted…" },
+ { "…second-stablecoin aggr_deferred accept, identifiers omitted…" },
{"x402Version":2,"scheme":"aggr_deferred","network":"eip155:196","amount":"1000","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}}],
"resource":{"url":"https://open-api.coinank.com/api/etf/getUsBtcEtf"}}
```
@@ -288,28 +290,28 @@ Decoded body:
Structural takeaways (same across both currencies): each accept nests its own `x402Version:2`; `extra` is `{name, version}` only (no `symbol`/`transferMethod`/`decimals`); `resource` is `{url}` with no `mimeType`.
`WWW-Authenticate` charge `request` (USD₮0) decoded: `{"amount":"1000","currency":"0x779ded…713736","recipient":"0xb1257e…d0b7","methodDetails":{"chainId":196,"feePayer":true}}`.
-Session `request` decoded: adds `"escrowContract":"0x5E550002e64FaF79B41D89fE8439eEb1be66CE3b","minVoucherDelta":"10000"` and `"suggestedDeposit":"100000"`. (MPP rail — out of scope for 02.)
+Session `request` decoded: adds `"escrowContract":"0x5E550002e64FaF79B41D89fE8439eEb1be66CE3b","minVoucherDelta":"10000"` and `"suggestedDeposit":"100000"`. (MPP rail, out of scope for 02.)
-### C. WIRE-OKB — OKB Monitoring #3837, `/x402/digest`
+### C. WIRE-OKB, OKB Monitoring #3837, `/x402/digest`
Both `GET` and `POST` → `HTTP/2 402`, body (note **`x402Version:1`**, `maxAmountRequired`, per-accept `decimals`/`description`):
```json
-{"x402Version":1,"accepts":[{"scheme":"exact","network":"eip155:196","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","decimals":6,"maxAmountRequired":"10000","payTo":"0x0921f7fcbc93984c2a4d29b4079f97840184365b","resource":"https://okb.swaper.money/x402/digest","description":"OKB X Layer monitor — OKB X Layer daily anomaly digest (alerts + metrics + report)","mimeType":"application/json","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}}]}
+{"x402Version":1,"accepts":[{"scheme":"exact","network":"eip155:196","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","decimals":6,"maxAmountRequired":"10000","payTo":"0x0921f7fcbc93984c2a4d29b4079f97840184365b","resource":"https://okb.swaper.money/x402/digest","description":"OKB X Layer monitor, OKB X Layer daily anomaly digest (alerts + metrics + report)","mimeType":"application/json","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}}]}
```
-### D. PAY-LEG1/2 — real payment from our wallet `0x75d0…cf69`
+### D. PAY-LEG1/2, real payment from our wallet `0x75d0…cf69`
-**Leg 1** — `onchainos payment pay --payload <oklink 402> --selected-index 0` →
+**Leg 1**, `onchainos payment pay --payload <oklink 402> --selected-index 0` →
`{ok:true, data:{ header_name:"PAYMENT-SIGNATURE", scheme:"exact", wallet:"0x75d00a2713565171f33216e5aa2a375e076ecf69", authorization_header:"<base64>" }}`. Decoded payload in §1.3 (EIP-3009 `transferWithAuthorization`, value "15", from our wallet, to oklink's payTo, signed).
-**Leg 2** — replay `POST get_chain_info` with `PAYMENT-SIGNATURE: <header>` → `HTTP/2 402`, body:
+**Leg 2**, replay `POST get_chain_info` with `PAYMENT-SIGNATURE: <header>` → `HTTP/2 402`, body:
```json
{"x402Version":2,"error":"insufficient_balance","resource":{"url":"https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info","mimeType":"application/json"},"accepts":[ …same two accepts as Appx A… ]}
```
-**Interpretation:** signing succeeded (leg 1 real), and the seller's facilitator did an on-chain balance check and rejected because our X-Layer wallet holds **0 USD₮0** — proving (a) the seller→facilitator verify path is live, (b) rejection re-emits the full 402 with a top-level `error`. **Funding blocker (DoD):** to capture a fully-successful paid leg the owner must fund `0x75d00a2713565171f33216e5aa2a375e076ecf69` on **X Layer (chainId 196)** with **USD₮0** (`0x779ded…713736`). Minimum to pay oklink `get_chain_info` = **15 atomic (0.000015 USD₮0)**; recommend **~1.0 USD₮0 (1,000,000 atomic)** for buffer across test calls + the pfp-wedge work. `exact`+EIP-3009 is gasless for the payer (facilitator broadcasts, `feePayer:true`), so no OKB gas is strictly required; a small OKB dust (~0.5 OKB) is optional insurance for any self-broadcast path. `onchainos portfolio all-balances --chain xlayer --chains 196 --address 0x75d0…cf69` currently returns `data:[]`.
+**Interpretation:** signing succeeded (leg 1 real), and the seller's facilitator did an on-chain balance check and rejected because our X-Layer wallet holds **0 USD₮0**, proving (a) the seller→facilitator verify path is live, (b) rejection re-emits the full 402 with a top-level `error`. **Funding blocker (DoD):** to capture a fully-successful paid leg the owner must fund `0x75d00a2713565171f33216e5aa2a375e076ecf69` on **X Layer (chainId 196)** with **USD₮0** (`0x779ded…713736`). Minimum to pay oklink `get_chain_info` = **15 atomic (0.000015 USD₮0)**; recommend **~1.0 USD₮0 (1,000,000 atomic)** for buffer across test calls + the pfp-wedge work. `exact`+EIP-3009 is gasless for the payer (facilitator broadcasts, `feePayer:true`), so no OKB gas is strictly required; a small OKB dust (~0.5 OKB) is optional insurance for any self-broadcast path. `onchainos portfolio all-balances --chain xlayer --chains 196 --address 0x75d0…cf69` currently returns `data:[]`.
### E. CLI validator + token info
@@ -322,11 +324,11 @@ $ onchainos token info --chain xlayer --address 0x779ded0c9e1022225f8e0630b35a9b
"tokenContractAddress":"0x779ded0c9e1022225f8e0630b35a9b54be713736"}
```
-### F. `onchainos agent service-list` — how a service is registered (shape)
+### F. `onchainos agent service-list`, how a service is registered (shape)
Each A2MCP service row (from Onchain Data Explorer #2023): `{ serviceType:"A2MCP", serviceName, endpoint:"https://…", fee:"0.000015", contractAddress:"0x779ded…713736", chainIndex:196 }`. The registered `endpoint` + `fee` + fee-token `contractAddress` + `chainIndex` are what the buyer/validator matches the live 402 against.
-### G. OKX Payments SDK — seller wiring (SDK-REPO `demo/x402/src/index.ts`, trimmed)
+### G. OKX Payments SDK, seller wiring (SDK-REPO `demo/x402/src/index.ts`, trimmed)
```ts
import { OKXFacilitatorClient } from "@okxweb3/app-x402-core";
@@ -345,7 +347,7 @@ const routes = { "POST /api/mcp-3d": {
// USD price → USD₮0 atomic auto-converted via DEFAULT_STABLECOINS["eip155:196"] (6 dp).
```
-### H. Verification-pass captures (second WO-01 session, 2026-07-06 — independent evidence)
+### H. Verification-pass captures (second WO-01 session, 2026-07-06, independent evidence)
#### H.1 Our endpoint's live HTTP-level gate (disproves original G9)
@@ -362,19 +364,19 @@ url/description/mimeType/serviceName/tags/iconUrl, Solana USDC `amount "1000"` +
THREE `amount "10000000"` accepts, `bazaar` extension) and
`access-control-allow-headers` ALREADY includes `payment-signature`;
`access-control-expose-headers: PAYMENT-REQUIRED, x-payment-response, …` (needs
-`PAYMENT-RESPONSE` added — G8).
+`PAYMENT-RESPONSE` added, G8).
#### H.2 `x402-check` against our endpoint and oklink
Ours: `{"valid": true, "x402Version": 2, "scheme": "exact", "network":
"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "asset": "EPjFWdd5…TDt1v", "amountMinimal":
-"1000", "amountHuman": 0.001, "decimals": 6, "tokenSymbol": "UNKNOWN", …}` — parses clean;
+"1000", "amountHuman": 0.001, "decimals": 6, "tokenSymbol": "UNKNOWN", …}`, parses clean;
**no `eip155:196` entry to select** (the rejection, isolated).
oklink (`--body '{"chainIndex":"196"}'`): `"valid": true` plus
`"tokenResolveError": "cannot determine token decimals: token-info lookup failed (asset
0x779ded0c…3736 is not in the task system's supported token list (checked: USDT, USDG)) and
-the accepts entry does not provide a 'decimals' field"` — non-fatal; basis for the G3
+the accepts entry does not provide a 'decimals' field"`, non-fatal; basis for the G3
`extra.decimals` recommendation.
#### H.3 Fee-token on-chain reads (X Layer RPC `https://rpc.xlayer.tech`)
@@ -391,11 +393,11 @@ eip712Domain() → empty (no ERC-5267; domain params
Recomputation (ethers v6): `keccak256(abiEncode(keccak256("EIP712Domain(string name,string
version,uint256 chainId,address verifyingContract)"), keccak256("USD₮0"), keccak256("1"),
196, 0x779ded0c9e1022225f8e0630b35a9b54be713736))` =
-`0xd591d9ba…599d` — **byte-exact match** with the on-chain `DOMAIN_SEPARATOR()`.
+`0xd591d9ba…599d`, **byte-exact match** with the on-chain `DOMAIN_SEPARATOR()`.
`extra.name = "USD₮0"` / `extra.version = "1"` are therefore cryptographically proven.
-A mis-transcribed ₮ (U+20AE) produces invalid signatures — copy the string from this spec.
+A mis-transcribed ₮ (U+20AE) produces invalid signatures, copy the string from this spec.
-#### H.4 WIRE-PREDEXON — Predexon #2143 (approved, enforcing, `exact`-only)
+#### H.4 WIRE-PREDEXON, Predexon #2143 (approved, enforcing, `exact`-only)
`curl -si "https://a2mcp.predexon.com/v1/markets/search?query=btc"` → `HTTP/2 402`, body
`{"error":"payment_required","service":"Predexon Market Search","price":"0.01 USDT0",…}`,
@@ -411,7 +413,7 @@ $0.01 → `"10000"` re-confirms 6-decimal scaling on a third price point. Note
#### H.5 Facilitator auth requirement (live) + second signed leg
`curl -si https://web3.okx.com/api/v6/pay/x402/supported` (no auth) → `HTTP/2 401`
-`{"msg":"Request header OK-ACCESS-KEY can not be empty.","code":"50103"}` — HMAC credentials
+`{"msg":"Request header OK-ACCESS-KEY can not be empty.","code":"50103"}`, HMAC credentials
are required in practice, not just per SDK source.
A second independent `payment pay` + unfunded replay against oklink reproduced PAY-LEG1/2
@@ -419,10 +421,10 @@ exactly (`header_name: "PAYMENT-SIGNATURE"`, fresh nonce, `validBefore` = now +
replay → 402 `"error":"insufficient_balance"` with full fresh challenge). The flow is
deterministic, not a one-off.
-#### H.6 XBubbleAI #2087 — cautionary non-example
+#### H.6 XBubbleAI #2087, cautionary non-example
Both `https://x402.dappos.com/healthz` AND the priced
`/okx/a2mcp/bubble-image` answer `HTTP/2 200` to unpaid requests (the latter generated and
-returned a real image URL, unpaid). Approved but non-enforcing, 0 sales — approval evidently
+returned a real image URL, unpaid). Approved but non-enforcing, 0 sales, approval evidently
predates or ignores runtime enforcement; do NOT copy its behavior, and it explains why
`x402-check` against its healthz returns `valid:false` (Appx E).
diff --git a/src/agent-screen-world.js b/src/agent-screen-world.js
index a3b21e77b..2161be17d 100644
--- a/src/agent-screen-world.js
+++ b/src/agent-screen-world.js
@@ -20,6 +20,7 @@ import { createDayNightCycle } from './game/day-night.js';
import {
worldClock, phaseLabel, daylightAmount, DEFAULT_CYCLE_MS,
} from './shared/world-clock.js';
+import { applyCinematicDefaults, detectQualityTier } from './shared/cinematic-render.js';
export { worldClock, phaseLabel, daylightAmount, DEFAULT_CYCLE_MS };
@@ -69,7 +70,13 @@ export function createAmbientWorld({ agentId, seed, container, cycleMs = DEFAULT
const renderer = new WebGLRenderer({ antialias: true, alpha: false, powerPreference: 'low-power' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
- renderer.shadowMap.enabled = true;
+ // ACES + sRGB + soft shadows only (src/shared/cinematic-render.js). No HDRI
+ // preset and no ground-contact shadow catcher here: this world already has
+ // its own real environment (createWorldEnvironment's biome sky + the
+ // deterministic day-night cycle) and its own ground plane with real NPCs
+ // casting real shadows on it (AmbientLife) — a static studio HDRI would
+ // fight the dynamic sky instead of complementing it.
+ applyCinematicDefaults(renderer, { tier: detectQualityTier() });
const canvas = renderer.domElement;
canvas.style.cssText = 'width:100%;height:100%;display:block;';
container.appendChild(canvas);
diff --git a/src/agent-screen.js b/src/agent-screen.js
index 9c5df025a..1ab34f3ee 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -38,6 +38,7 @@ import { createAgentScreenClient } from './shared/agent-screen-client.js';
import { mountAgentReactions } from './agent-reactions.js';
import { handleTourFrame } from './agent-screen-tour.js';
import { buildRunCommand, buildRunCommandHtml, RUNTIME_LABELS } from './agent-screen-runcmd.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
import { createNewsroomAnchor } from './agent-screen-anchor.js';
import { createTreasuryCockpit } from './agent-screen-treasury.js';
import { MirrorPanel } from './agent-screen-mirror.js';
@@ -965,8 +966,15 @@ async function boot(id) {
const webcamRenderer = new WebGLRenderer({ antialias: true, alpha: true });
webcamRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
webcamRenderer.setClearColor(0x0a0d1a, 1);
+ // ACES + sRGB + soft shadows, shared bar (src/shared/cinematic-render.js).
+ const webcamQualityTier = detectQualityTier();
+ applyCinematicDefaults(webcamRenderer, { tier: webcamQualityTier });
const webcamScene = new Scene();
+ // Real HDRI IBL for specular/rim detail on the avatar bust. No ground-contact
+ // shadow here: this is a tight head-and-shoulders webcam crop with no floor
+ // in frame, so a shadow catcher plane would never be visible.
+ loadEnvironment(webcamRenderer, webcamScene, webcamQualityTier === 'mobile' ? null : 'studio');
webcamScene.add(new AmbientLight(0xffffff, 0.7));
const sun = new DirectionalLight(0xffffff, 1.2);
sun.position.set(1.5, 2.5, 2);
diff --git a/src/ar-studio.js b/src/ar-studio.js
index f752eec3b..5ec1293b7 100644
--- a/src/ar-studio.js
+++ b/src/ar-studio.js
@@ -26,10 +26,10 @@
import {
AnimationMixer, Box3, CanvasTexture, Color, DirectionalLight, GridHelper, Group,
HemisphereLight, Mesh, MeshBasicMaterial, PerspectiveCamera, PlaneGeometry,
- PMREMGenerator, Raycaster, RingGeometry, Scene, Vector2, Vector3, WebGLRenderer,
+ Raycaster, RingGeometry, Scene, Vector2, Vector3, WebGLRenderer,
} from 'three';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
import { EstimatedLighting } from './ar/estimated-lighting.js';
import {
@@ -122,23 +122,23 @@ if (!canvas || !hud) {
const renderer = new WebGLRenderer({
canvas, alpha: true, antialias: true, preserveDrawingBuffer: true,
});
-renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
+// Filmic tone mapping + correct sRGB output + soft shadows: the shared bar
+// every viewer on the platform now matches (src/shared/cinematic-render.js).
+const qualityTier = detectQualityTier();
+applyCinematicDefaults(renderer, { tier: qualityTier });
const scene = new Scene();
const camera = new PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.02, 200);
camera.position.set(0, EYE_HEIGHT_M, 0);
-// PBR environment so forge materials (metal, glass, emissive) read correctly
-// against a real room — same RoomEnvironment the main viewer uses.
-try {
- const pmrem = new PMREMGenerator(renderer);
- scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
- pmrem.dispose();
-} catch (err) {
+// Real HDRI IBL (studio preset) so forge materials (metal, glass, emissive)
+// read correctly against a real room; falls back to the procedural
+// RoomEnvironment on fetch failure or mobile tier.
+loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio').catch((err) => {
log.warn('environment map failed', err);
-}
+});
const HEMI_BASE = 1.0;
const SUN_BASE = 1.15;
diff --git a/src/avatar-drop.js b/src/avatar-drop.js
index 0071cdcb0..4a481ec57 100644
--- a/src/avatar-drop.js
+++ b/src/avatar-drop.js
@@ -18,6 +18,7 @@ import { getMeshoptDecoder } from './viewer/internal.js';
import { reserveWebGLContext } from './webgl-budget.js';
import { log } from './shared/log.js';
import { resolveDevR2Url } from './shared/dev-r2-proxy.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
export function initAvatarDrop(sectionEl) {
const canvas = sectionEl.querySelector('#drop-canvas');
@@ -45,6 +46,10 @@ export function initAvatarDrop(sectionEl) {
reserveWebGLContext();
const scene = new Scene();
+ // Real HDRI image-based lighting so the dropped avatar's PBR skin/materials
+ // pick up believable reflections instead of flat directional-only shading.
+ // Falls back to a procedural room environment internally on fetch failure.
+ loadEnvironment(renderer, scene, 'studio');
let PX_PER_UNIT = 120;
const camera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
diff --git a/src/avatar-picker.js b/src/avatar-picker.js
index 759f00ef8..28b7eb0ff 100644
--- a/src/avatar-picker.js
+++ b/src/avatar-picker.js
@@ -137,14 +137,19 @@ const _thumbCache = new Map(); // glbUrl → data:image/png
async function getOffscreenCtx() {
if (_offscreenCtx) return _offscreenCtx;
const [{ WebGLRenderer, Scene, PerspectiveCamera, AmbientLight, DirectionalLight, Box3, Vector3 },
- { GLTFLoader }, { getMeshoptDecoder }] = await Promise.all([
+ { GLTFLoader }, { getMeshoptDecoder },
+ { applyCinematicDefaults, loadEnvironment }] = await Promise.all([
import('three'),
import('three/addons/loaders/GLTFLoader.js'),
import('./viewer/internal.js'),
+ import('./shared/cinematic-render.js'),
]);
const cvs = document.createElement('canvas');
cvs.width = 256; cvs.height = 256;
const renderer = new WebGLRenderer({ canvas: cvs, antialias: true, alpha: true });
+ // Cinematic defaults (ACES tone mapping, sRGB output) shared with every other
+ // viewer on the platform; product-shot studio HDRI for the picker thumbnails.
+ applyCinematicDefaults(renderer, { exposure: 1.1, tier: 'medium' });
renderer.setPixelRatio(1);
renderer.setSize(256, 256);
renderer.setClearColor(0x000000, 0);
@@ -152,6 +157,7 @@ async function getOffscreenCtx() {
camera.position.set(0, 1.3, 2.2);
camera.lookAt(0, 1.0, 0);
const scene = new Scene();
+ loadEnvironment(renderer, scene, 'studio');
scene.add(new AmbientLight(0xffffff, 1.0));
const sun = new DirectionalLight(0xffffff, 1.4);
sun.position.set(2, 4, 3);
diff --git a/src/club-entrance.js b/src/club-entrance.js
index 9547d6db6..cbcd7849f 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -59,6 +59,7 @@ import { detectProfile, PROFILES, createFrameWatchdog } from './club-perf.js';
import { getPowerSaver } from './shared/frame-governor.js';
import { log } from './shared/log.js';
import { isExpressEntry } from './shared/club-express.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
const TOUR_URL = '/club/venue/tour.glb';
const ALLEYWAY_URL = '/club/venue/alleyway.glb';
@@ -235,6 +236,17 @@ async function start(canvasEl) {
fill.position.set(0, 2.4, 0);
scene.add(fill);
+ // Real HDRI image-based lighting on top of the hand-placed rig above, so
+ // reflective surfaces (chrome trim, wet asphalt, the avatar's own skin/eyes)
+ // pick up believable environment light instead of flat ambient-only shading.
+ // Reuses the same profile.tier the render-budget system already computed
+ // (src/club-perf.js) rather than re-detecting capability — on the 'low'
+ // tier we skip the network HDRI fetch entirely (procedural fallback via
+ // `preset: null`) since a struggling device shouldn't spend bandwidth/GPU
+ // on IBL it can't afford to render anyway. 'sunset' fits the neon
+ // evening-alley mood better than the neutral studio/outdoor presets.
+ loadEnvironment(renderer, scene, profile.tier === 'low' ? null : 'sunset').catch(() => {});
+
// ── Postprocessing — the same cinematic stack as the pole stage ──────────
// Bloom makes the neon door/sign actually glow, ACES gives filmic colour,
// the vignette pulls focus to the path ahead, SMAA cleans the edges. We
diff --git a/src/coin3d/main.js b/src/coin3d/main.js
index 1690ffaa3..d531d2f89 100644
--- a/src/coin3d/main.js
+++ b/src/coin3d/main.js
@@ -53,6 +53,7 @@ import {
} from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { fetchFirstOrNull } from '../shared/failover-fetch.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from '../shared/cinematic-render.js';
const MCP_ENDPOINT = '/api/pump-fun-mcp';
// The one and only coin — featured on the no-mint landing.
@@ -306,10 +307,17 @@ let coinGlowColor = new Color(0x6ea8ff);
function initScene() {
renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
- renderer.outputColorSpace = SRGBColorSpace;
+ // Shared cinematic bar: ACES tone mapping + sRGB output color space +
+ // tiered pixel ratio cap (replaces the old sRGB-only line). The medallion
+ // is a real textured/metallic MeshStandardMaterial product shot, so it
+ // gets a real HDRI for genuine reflections too. No ground-contact shadow:
+ // the coin and holder galaxy spin freely in starfield space with no
+ // floor/pedestal for a shadow to land on.
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
scene = new Scene();
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'studio');
camera = new PerspectiveCamera(45, 1, 0.1, 200);
camera.position.set(0, 1.6, 6.2);
diff --git a/src/constellation/main.js b/src/constellation/main.js
index 6b0df0e70..ae1b044f5 100644
--- a/src/constellation/main.js
+++ b/src/constellation/main.js
@@ -24,6 +24,7 @@ import {
} from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { tokenText, pca3, normalizeCoordsToRadius, cosineNeighbors } from './embedding.js';
+import { applyCinematicDefaults, detectQualityTier } from '../shared/cinematic-render.js';
// ---- DOM ------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
@@ -422,7 +423,12 @@ function boot() {
fatalOverlay('<strong>This experience needs WebGL.</strong><br/>Your browser could not create a WebGL context.');
return false;
}
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ // Shared cinematic bar (ACES tone mapping, sRGB output, tiered pixel ratio
+ // cap). No HDRI/IBL here: every material in this scene is MeshBasicMaterial
+ // or PointsMaterial (unlit/emissive-style stars + additive glow sprites),
+ // so environment reflections would never be visible - only the tone
+ // mapping's highlight rolloff matters for this surface.
+ applyCinematicDefaults(renderer, { tier: detectQualityTier() });
renderer.setSize(window.innerWidth, window.innerHeight);
scene = new Scene();
diff --git a/src/demo/os-combined.js b/src/demo/os-combined.js
index 44b16a917..d8f64e719 100644
--- a/src/demo/os-combined.js
+++ b/src/demo/os-combined.js
@@ -32,6 +32,7 @@ import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { FilesetResolver, FaceLandmarker } from '@mediapipe/tasks-vision';
import { TRIANGULATION } from './triangulation.js';
import { log } from '../shared/log.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment, updateGroundContactShadow } from '../shared/cinematic-render.js';
const MODEL_URL =
'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
@@ -64,6 +65,7 @@ let landmarker = null;
let landmarkerLoading = null;
let viewer = null;
let bodyRoot = null;
+let groundShadow = null;
let faceMesh = null;
let selfieImg = null;
let lastGlbBlob = null;
@@ -103,8 +105,10 @@ async function loadBody(url, label) {
}
bodyRoot = gltf.scene;
bodyRoot.name = 'body-root';
+ bodyRoot.traverse((n) => { if (n.isMesh) n.castShadow = true; });
viewer.scene.add(bodyRoot);
fitToObject(viewer, bodyRoot);
+ groundShadow = updateGroundContactShadow(viewer.scene, bodyRoot, groundShadow);
viewerOverlay.style.display = 'none';
const headBone = findHeadBone(bodyRoot);
const bones = countBones(bodyRoot);
@@ -304,12 +308,17 @@ function ensureViewer() {
const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
- renderer.outputColorSpace = SRGBColorSpace;
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
viewerHost.appendChild(renderer.domElement);
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'studio');
+
scene.add(new HemisphereLight(0xffffff, 0x333333, 1.2));
const dir = new DirectionalLight(0xffffff, 1.5);
dir.position.set(2, 4, 3);
+ dir.castShadow = true;
+ dir.shadow.mapSize.set(1024, 1024);
scene.add(dir);
const grid = new GridHelper(4, 8, 0x222222, 0x111111);
diff --git a/src/demo/os-selfie.js b/src/demo/os-selfie.js
index bc0bed57e..5515a78d8 100644
--- a/src/demo/os-selfie.js
+++ b/src/demo/os-selfie.js
@@ -36,6 +36,7 @@ import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { FilesetResolver, FaceLandmarker } from '@mediapipe/tasks-vision';
import { TRIANGULATION } from './triangulation.js';
import { log } from '../shared/log.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from '../shared/cinematic-render.js';
const MODEL_URL =
'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
@@ -306,9 +307,12 @@ function ensureViewer() {
const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
- renderer.outputColorSpace = SRGBColorSpace;
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
viewerHost.appendChild(renderer.domElement);
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'studio');
+
scene.add(new HemisphereLight(0xffffff, 0x333333, 1.2));
const dir = new DirectionalLight(0xffffff, 1.4);
dir.position.set(1, 2, 3);
diff --git a/src/demo/os-studio.js b/src/demo/os-studio.js
index 2b7b75b00..40772e59b 100644
--- a/src/demo/os-studio.js
+++ b/src/demo/os-studio.js
@@ -12,7 +12,6 @@ import {
Color,
PerspectiveCamera,
WebGLRenderer,
- SRGBColorSpace,
HemisphereLight,
DirectionalLight,
GridHelper,
@@ -22,6 +21,7 @@ import {
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from '../viewer/internal.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment, updateGroundContactShadow } from '../shared/cinematic-render.js';
const PUBLIC_STUDIO = 'https://m3-org.github.io/CharacterStudio';
@@ -117,6 +117,7 @@ window.addEventListener('message', async (event) => {
// ── Preview viewer ─────────────────────────────────────────────────────────
let previewState = null;
+let previewGroundShadow = null;
async function renderPreview(blob) {
previewViewer.style.display = 'block';
@@ -133,8 +134,10 @@ async function renderPreview(blob) {
loader.setMeshoptDecoder(await getMeshoptDecoder());
const gltf = await loader.loadAsync(url);
gltf.scene.userData.kind = 'avatar';
+ gltf.scene.traverse((n) => { if (n.isMesh) n.castShadow = true; });
scene.add(gltf.scene);
fitToObject(previewState, gltf.scene);
+ previewGroundShadow = updateGroundContactShadow(scene, gltf.scene, previewGroundShadow);
const box = new Box3().setFromObject(gltf.scene);
const size = new Vector3();
box.getSize(size);
@@ -162,12 +165,17 @@ function initViewer(host) {
const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
- renderer.outputColorSpace = SRGBColorSpace;
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
host.appendChild(renderer.domElement);
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'studio');
+
scene.add(new HemisphereLight(0xffffff, 0x444444, 1.2));
const dir = new DirectionalLight(0xffffff, 1.5);
dir.position.set(2, 4, 3);
+ dir.castShadow = true;
+ dir.shadow.mapSize.set(1024, 1024);
scene.add(dir);
const grid = new GridHelper(4, 8, 0x222222, 0x111111);
diff --git a/src/footer-bot.js b/src/footer-bot.js
index d50d7cc1e..ca39c785b 100644
--- a/src/footer-bot.js
+++ b/src/footer-bot.js
@@ -13,6 +13,7 @@ import {
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { reserveWebGLContext } from './webgl-budget.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
// The footer bot is purely decorative. Every failure mode here — no mount
// point, a browser that refuses a WebGL context (context budget exhausted, GPU
@@ -46,6 +47,13 @@ import { reserveWebGLContext } from './webgl-budget.js';
reserveWebGLContext();
const scene = new Scene();
+ // This widget mounts on every page load, site-wide. A real HDRI fetch would
+ // add a network request (and PMREM compile cost) to every page for a small,
+ // purely decorative mascot that most users never look at directly — not
+ // worth the tradeoff. Pass `null` so loadEnvironment installs the
+ // procedural RoomEnvironment instead: still correct PBR image-based
+ // lighting (soft, neutral, no washed-out flat shading), zero network cost.
+ loadEnvironment(renderer, scene, null);
// Match model-viewer camera-orbit="0deg 80deg 9m" field-of-view="35deg"
const camera = new PerspectiveCamera(35, w / h, 0.1, 100);
diff --git a/src/forge-conversational-refine.js b/src/forge-conversational-refine.js
new file mode 100644
index 000000000..428fff97d
--- /dev/null
+++ b/src/forge-conversational-refine.js
@@ -0,0 +1,286 @@
+// Forge — Conversational iteration (browser client).
+//
+// "Make the helmet red", "add a cape", "give it bigger ears" — a free-text
+// instruction against the model on screen, via POST /api/forge-iterate. That
+// endpoint shares its core (composeRefinement + version lineage) with the
+// MCP `refine_model` tool, so this is the exact same free iteration path
+// agents get, wired to the plain /forge page (previously Studio-only).
+//
+// Distinct from:
+// - #refine (forge.js) → re-runs the SAME prompt at a HIGHER quality tier
+// - #refine-locally / forge-refine.js → local deterministic geometry ops
+// (weld/smooth/decimate), no network call
+// - forge-stylize.js → geometric filters (voxel/brick/voronoi)
+// - forge-materials.js → PBR material re-skin only
+// This module is the only one that changes the SHAPE of the model based on a
+// natural-language instruction.
+//
+// Self-contained: builds its own button + panel off `forge:model-ready`, and
+// forwards the same x-forge-client identity forge.js uses so an iteration
+// lands in the same anonymous gallery/lineage as its parent.
+
+const POLL_INTERVAL_MS = 2500;
+const MAX_POLL_MS = 5 * 60 * 1000;
+
+const actions = document.querySelector('#state-result .result-bar .actions');
+const resultBar = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+
+if (actions && resultBar && viewer) {
+ injectStyles();
+
+ const CLIENT_ID = (() => {
+ const KEY = 'forge:cid';
+ try {
+ let id = localStorage.getItem(KEY);
+ if (!id) {
+ id =
+ crypto?.randomUUID?.() ||
+ `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ localStorage.setItem(KEY, id);
+ }
+ return id;
+ } catch {
+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ }
+ })();
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn btn-ghost';
+ btn.id = 'forge-iterate-btn';
+ btn.setAttribute('aria-expanded', 'false');
+ btn.title = 'Describe a change to iterate on this exact model ("make it metallic", "add a hat")';
+ btn.innerHTML = `
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
+ </svg>
+ Iterate`;
+
+ const materialsBtn = document.getElementById('forge-materials-btn');
+ const rigBtn = document.getElementById('forge-rig-btn');
+ const anchorAfter = materialsBtn || rigBtn || document.getElementById('forge-ar-btn');
+ if (anchorAfter && anchorAfter.parentNode === actions) {
+ anchorAfter.after(btn);
+ } else {
+ actions.appendChild(btn);
+ }
+
+ const panel = document.createElement('div');
+ panel.className = 'iterate-panel is-hidden';
+ panel.id = 'iterate-panel';
+ panel.innerHTML = `
+ <div class="iterate-head">
+ <h3>Iterate on this model</h3>
+ <p class="iterate-sub">Describe a change. Each iteration is a new version you can keep going from — nothing overwrites the model you have now.</p>
+ </div>
+ <div class="iterate-lineage is-hidden" id="iterate-lineage" role="group" aria-label="Version history"></div>
+ <form class="iterate-form" id="iterate-form">
+ <input
+ type="text"
+ id="iterate-instruction"
+ maxlength="300"
+ placeholder="e.g. &quot;make the helmet red&quot;, &quot;add a small backpack&quot;"
+ aria-label="Describe a change"
+ />
+ <button type="submit" class="btn" id="iterate-apply">Iterate</button>
+ </form>
+ <div class="iterate-status" id="iterate-status" role="status" aria-live="polite"></div>
+ `;
+ resultBar.after(panel);
+
+ const form = panel.querySelector('#iterate-form');
+ const input = panel.querySelector('#iterate-instruction');
+ const status = panel.querySelector('#iterate-status');
+ const applyBtn = panel.querySelector('#iterate-apply');
+ const lineageHost = panel.querySelector('#iterate-lineage');
+
+ let originalGlbUrl = '';
+ let originalLabel = '';
+ let originalPrompt = '';
+ let currentGlbUrl = '';
+ let lineage = null; // [{glbUrl, instruction?, ...}] from the last response
+ let activeIndex = -1;
+ let busy = false;
+ let runToken = 0;
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ function setStatus(text, kind = '') {
+ status.textContent = text || '';
+ status.dataset.kind = kind;
+ }
+
+ function setBusy(next) {
+ busy = next;
+ applyBtn.disabled = next;
+ input.disabled = next;
+ }
+
+ function renderLineage() {
+ if (!Array.isArray(lineage) || lineage.length < 2) {
+ lineageHost.classList.add('is-hidden');
+ lineageHost.innerHTML = '';
+ return;
+ }
+ lineageHost.classList.remove('is-hidden');
+ lineageHost.innerHTML = lineage
+ .map((v, i) => {
+ const label = i === 0 ? 'Original' : v.instruction || `v${i + 1}`;
+ return `<button type="button" class="iterate-version${i === activeIndex ? ' is-active' : ''}" data-index="${i}" title="${label}">${i === 0 ? 'v0' : `v${i}`}</button>`;
+ })
+ .join('');
+ lineageHost.querySelectorAll('.iterate-version').forEach((b) => {
+ b.addEventListener('click', () => jumpTo(Number(b.dataset.index)));
+ });
+ }
+
+ function jumpTo(index) {
+ if (!Array.isArray(lineage) || !lineage[index]) return;
+ activeIndex = index;
+ const v = lineage[index];
+ currentGlbUrl = v.glbUrl;
+ viewer.setAttribute('src', v.glbUrl);
+ viewer.setAttribute('alt', `${originalLabel} — ${index === 0 ? 'original' : v.instruction}`);
+ renderLineage();
+ setStatus(index === 0 ? 'Showing the original.' : `Showing: "${v.instruction}"`, '');
+ }
+
+ async function runIterate(instruction) {
+ const text = (instruction || '').trim();
+ if (!text || busy || !currentGlbUrl) return;
+ const token = ++runToken;
+ setBusy(true);
+ setStatus('Iterating…', 'busy');
+ try {
+ const res = await fetch('/api/forge-iterate', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-forge-client': CLIENT_ID },
+ body: JSON.stringify({
+ glb_url: currentGlbUrl,
+ instruction: text,
+ parent_prompt: originalPrompt || originalLabel,
+ parent_lineage: Array.isArray(lineage) ? lineage : undefined,
+ parent_index: activeIndex >= 0 ? activeIndex : undefined,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (token !== runToken) return;
+ if (res.status === 429) {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
+ setStatus(`Iteration is busy right now. Try again in about ${secs}s.`, 'error');
+ return;
+ }
+ if (!res.ok || !data.glbUrl) {
+ setStatus(data.message || `Iteration failed (${res.status}). Try a smaller, clearer change.`, 'error');
+ return;
+ }
+ currentGlbUrl = data.glbUrl;
+ lineage = Array.isArray(data.lineage) ? data.lineage : lineage;
+ activeIndex = Number.isInteger(data.activeIndex) ? data.activeIndex : (lineage?.length || 1) - 1;
+ viewer.setAttribute('src', data.glbUrl);
+ viewer.setAttribute('alt', `${originalLabel} — ${text}`);
+ renderLineage();
+ input.value = '';
+ setStatus(`Applied: "${text}". Keep iterating, or jump back to an earlier version above.`, 'done');
+ } catch {
+ if (token !== runToken) return;
+ setStatus('Network hiccup — the model is unchanged. Try again.', 'error');
+ } finally {
+ if (token === runToken) setBusy(false);
+ }
+ }
+
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ runIterate(input.value);
+ });
+
+ btn.addEventListener('click', () => {
+ const willShow = panel.classList.contains('is-hidden');
+ panel.classList.toggle('is-hidden', !willShow);
+ btn.setAttribute('aria-expanded', String(willShow));
+ if (willShow) input.focus();
+ });
+
+ function onNewSource(glbUrl, label) {
+ if (!glbUrl || glbUrl === originalGlbUrl) return;
+ originalGlbUrl = glbUrl;
+ originalLabel = label || '';
+ originalPrompt = label || '';
+ currentGlbUrl = glbUrl;
+ lineage = null;
+ activeIndex = -1;
+ runToken++;
+ setStatus('', '');
+ input.value = '';
+ renderLineage();
+ panel.classList.add('is-hidden');
+ btn.setAttribute('aria-expanded', 'false');
+ setBusy(false);
+ }
+
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ // Ignore our own lineage-jump / iterate swaps; only a genuinely new source
+ // model (fresh generation, gallery open) should reset the panel.
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === originalGlbUrl || url === currentGlbUrl) return;
+ if (Array.isArray(lineage) && lineage.some((v) => v.glbUrl === url)) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+}
+
+function injectStyles() {
+ if (document.getElementById('forge-iterate-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'forge-iterate-styles';
+ style.textContent = `
+ .iterate-panel {
+ margin: 0 var(--space-md, 1rem) var(--space-md, 1rem);
+ padding: 0.9rem 1rem;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm, 8px);
+ background: var(--surface, rgba(255,255,255,0.03));
+ }
+ .iterate-panel.is-hidden { display: none; }
+ .iterate-head h3 { margin: 0 0 0.15rem; font-size: var(--text-md, 1rem); }
+ .iterate-sub { margin: 0 0 0.7rem; font-size: var(--text-sm, 0.85rem); color: var(--ink-dim); }
+ .iterate-lineage { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-bottom: 0.7rem; }
+ .iterate-lineage.is-hidden { display: none; }
+ .iterate-version {
+ padding: 0.25rem 0.6rem;
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--ink-dim);
+ font-size: var(--text-xs, 0.75rem);
+ cursor: pointer;
+ }
+ .iterate-version.is-active { border-color: var(--accent); color: var(--accent); }
+ .iterate-version:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .iterate-form { display: flex; gap: 0.5rem; }
+ .iterate-form input {
+ flex: 1;
+ padding: 0.5rem 0.7rem;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm, 8px);
+ background: transparent;
+ color: var(--ink);
+ font-size: var(--text-sm, 0.85rem);
+ }
+ .iterate-form input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .iterate-status { margin-top: 0.5rem; font-size: var(--text-xs, 0.8rem); color: var(--ink-dim); min-height: 1em; }
+ .iterate-status[data-kind='error'] { color: var(--danger); }
+ .iterate-status[data-kind='done'] { color: var(--success); }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/src/forge-materials.js b/src/forge-materials.js
new file mode 100644
index 000000000..957f9e71c
--- /dev/null
+++ b/src/forge-materials.js
@@ -0,0 +1,247 @@
+// Forge — Material restyle panel (browser client).
+//
+// Re-skins the current model's PBR materials without touching its geometry:
+// "make it chrome", "wooden", "cyberpunk neon" — a free-text instruction goes
+// to POST /api/material-studio?action=restyle, which has IBM Granite propose
+// PBR factors and re-exports the GLB server-side. Same backing endpoint the
+// paid `restyle_material` MCP tool calls, so results here are the exact same
+// pipeline agents get. Synchronous (no poll loop needed).
+//
+// Self-contained: builds its own button + panel off `forge:model-ready`, same
+// pattern as forge-stylize.js and forge-rig.js.
+
+const PRESET_CHIPS = [
+ { label: 'Chrome', instruction: 'make it polished chrome' },
+ { label: 'Brushed gold', instruction: 'make it brushed gold metal' },
+ { label: 'Weathered wood', instruction: 'make it weathered natural wood' },
+ { label: 'Cyberpunk neon', instruction: 'make it glossy black with cyberpunk neon accent trim' },
+ { label: 'Marble', instruction: 'make it polished white marble' },
+ { label: 'Rusted metal', instruction: 'make it rusted, worn metal' },
+];
+
+const actions = document.querySelector('#state-result .result-bar .actions');
+const resultBar = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+
+if (actions && resultBar && viewer) {
+ injectStyles();
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn btn-ghost';
+ btn.id = 'forge-materials-btn';
+ btn.setAttribute('aria-expanded', 'false');
+ btn.title = 'Restyle this model’s materials (AI PBR re-skin, keeps the same shape)';
+ btn.innerHTML = `
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M12 19l7-7 3 3-7 7-3-3z" />
+ <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z" />
+ <path d="M2 2l7.586 7.586" />
+ <circle cx="11" cy="11" r="2" />
+ </svg>
+ Restyle materials`;
+
+ const rigBtn = document.getElementById('forge-rig-btn');
+ const arBtn = document.getElementById('forge-irl-btn') || document.getElementById('forge-ar-btn');
+ const anchorAfter = rigBtn || arBtn;
+ if (anchorAfter && anchorAfter.parentNode === actions) {
+ anchorAfter.after(btn);
+ } else {
+ actions.appendChild(btn);
+ }
+
+ const panel = document.createElement('div');
+ panel.className = 'materials-panel is-hidden';
+ panel.id = 'materials-panel';
+ panel.innerHTML = `
+ <div class="materials-head">
+ <h3>Restyle materials</h3>
+ <p class="materials-sub">Keeps the same mesh, re-skins the surface. Pick a preset or describe your own.</p>
+ </div>
+ <div class="materials-chips" id="materials-chips" role="group" aria-label="Material presets"></div>
+ <form class="materials-form" id="materials-form">
+ <input
+ type="text"
+ id="materials-instruction"
+ maxlength="300"
+ placeholder="Describe a material, e.g. &quot;make it iridescent soap-bubble glass&quot;"
+ aria-label="Describe a material"
+ />
+ <button type="submit" class="btn" id="materials-apply">Apply</button>
+ </form>
+ <div class="materials-actions is-hidden" id="materials-result-actions">
+ <a class="btn btn-ghost" id="materials-download" download>Download restyled GLB</a>
+ <button type="button" class="btn btn-ghost" id="materials-revert">Revert to original</button>
+ </div>
+ <div class="materials-status" id="materials-status" role="status" aria-live="polite"></div>
+ `;
+ resultBar.after(panel);
+
+ const chipsHost = panel.querySelector('#materials-chips');
+ for (const p of PRESET_CHIPS) {
+ const chip = document.createElement('button');
+ chip.type = 'button';
+ chip.className = 'materials-chip';
+ chip.textContent = p.label;
+ chip.addEventListener('click', () => {
+ panel.querySelector('#materials-instruction').value = p.instruction;
+ runRestyle(p.instruction);
+ });
+ chipsHost.appendChild(chip);
+ }
+
+ const form = panel.querySelector('#materials-form');
+ const input = panel.querySelector('#materials-instruction');
+ const status = panel.querySelector('#materials-status');
+ const resultActions = panel.querySelector('#materials-result-actions');
+ const downloadLink = panel.querySelector('#materials-download');
+ const revertBtn = panel.querySelector('#materials-revert');
+ const applyBtn = panel.querySelector('#materials-apply');
+
+ let originalGlbUrl = '';
+ let originalLabel = '';
+ let lastRestyledUrl = '';
+ let busy = false;
+
+ function setStatus(text, kind = '') {
+ status.textContent = text || '';
+ status.dataset.kind = kind;
+ }
+
+ function setBusy(next) {
+ busy = next;
+ applyBtn.disabled = next;
+ input.disabled = next;
+ for (const chip of chipsHost.querySelectorAll('.materials-chip')) chip.disabled = next;
+ }
+
+ async function runRestyle(instruction) {
+ const text = (instruction || '').trim();
+ if (!text || busy || !originalGlbUrl) return;
+ setBusy(true);
+ setStatus('Restyling materials…', 'busy');
+ try {
+ const res = await fetch('/api/material-studio?action=restyle', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ glb_url: lastRestyledUrl || originalGlbUrl, instruction: text }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 429) {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ setStatus(`Restyle is busy right now. Try again in about ${secs}s.`, 'error');
+ return;
+ }
+ if (!res.ok || !data.glbUrl) {
+ setStatus(data.message || `Restyle failed (${res.status}). Try a shorter, clearer description.`, 'error');
+ return;
+ }
+ lastRestyledUrl = data.glbUrl;
+ viewer.setAttribute('src', data.glbUrl);
+ viewer.setAttribute('alt', `${originalLabel} — restyled: ${text}`);
+ const safeLabel = (originalLabel || 'forge').replace(/[^a-z0-9]+/gi, '-').slice(0, 40).replace(/^-|-$/g, '') || 'forge';
+ downloadLink.href = data.glbUrl;
+ downloadLink.setAttribute('download', `${safeLabel}-restyled.glb`);
+ resultActions.classList.remove('is-hidden');
+ setStatus(`Applied: "${text}". Try another description, or revert.`, 'done');
+ } catch {
+ setStatus('Network hiccup — the model is unchanged. Try again.', 'error');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ runRestyle(input.value);
+ });
+
+ revertBtn.addEventListener('click', () => {
+ lastRestyledUrl = '';
+ viewer.setAttribute('src', originalGlbUrl);
+ viewer.setAttribute('alt', originalLabel || '3D model');
+ resultActions.classList.add('is-hidden');
+ setStatus('Showing the original materials.', '');
+ });
+
+ btn.addEventListener('click', () => {
+ const willShow = panel.classList.contains('is-hidden');
+ panel.classList.toggle('is-hidden', !willShow);
+ btn.setAttribute('aria-expanded', String(willShow));
+ if (willShow) input.focus();
+ });
+
+ function onNewSource(glbUrl, label) {
+ if (!glbUrl || glbUrl === originalGlbUrl) return;
+ originalGlbUrl = glbUrl;
+ originalLabel = label || '';
+ lastRestyledUrl = '';
+ resultActions.classList.add('is-hidden');
+ setStatus('', '');
+ input.value = '';
+ panel.classList.add('is-hidden');
+ btn.setAttribute('aria-expanded', 'false');
+ }
+
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === originalGlbUrl || url === lastRestyledUrl) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+}
+
+function injectStyles() {
+ if (document.getElementById('forge-materials-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'forge-materials-styles';
+ style.textContent = `
+ .materials-panel {
+ margin: 0 var(--space-md, 1rem) var(--space-md, 1rem);
+ padding: 0.9rem 1rem;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm, 8px);
+ background: var(--surface, rgba(255,255,255,0.03));
+ }
+ .materials-panel.is-hidden { display: none; }
+ .materials-head h3 { margin: 0 0 0.15rem; font-size: var(--text-md, 1rem); }
+ .materials-sub { margin: 0 0 0.7rem; font-size: var(--text-sm, 0.85rem); color: var(--ink-dim); }
+ .materials-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-bottom: 0.7rem; }
+ .materials-chip {
+ padding: 0.35rem 0.7rem;
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--ink);
+ font-size: var(--text-xs, 0.78rem);
+ cursor: pointer;
+ }
+ .materials-chip:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
+ .materials-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .materials-chip:disabled { opacity: 0.5; cursor: progress; }
+ .materials-form { display: flex; gap: 0.5rem; }
+ .materials-form input {
+ flex: 1;
+ padding: 0.5rem 0.7rem;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm, 8px);
+ background: transparent;
+ color: var(--ink);
+ font-size: var(--text-sm, 0.85rem);
+ }
+ .materials-form input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .materials-actions { display: flex; gap: 0.5rem; margin-top: 0.6rem; }
+ .materials-status { margin-top: 0.5rem; font-size: var(--text-xs, 0.8rem); color: var(--ink-dim); min-height: 1em; }
+ .materials-status[data-kind='error'] { color: var(--danger); }
+ .materials-status[data-kind='done'] { color: var(--success); }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/src/forge-rig.js b/src/forge-rig.js
new file mode 100644
index 000000000..ea84bd1de
--- /dev/null
+++ b/src/forge-rig.js
@@ -0,0 +1,257 @@
+// Forge — Auto-rig action (browser client).
+//
+// Adds a "Rig for animation" button to the result action bar. Click it and the
+// current GLB goes through the same auto-rig lane the MCP `rig_mesh` tool and
+// avatar pipeline use (POST /api/forge?action=rig → self-hosted GCP UniRig,
+// falling back to the configured Replicate rerig model), polling through the
+// same GET /api/forge?job=<id> contract every other forge job uses. Nothing
+// here is a separate mesh-generation lane — it is a skeleton + skin-weight
+// pass over the mesh already on screen.
+//
+// Self-contained on purpose, same pattern as forge-stylize.js: builds its own
+// DOM off `forge:model-ready`, owns its own styles, degrades to nothing on a
+// page that doesn't have the result actions bar.
+
+const POLL_INTERVAL_MS = 2500;
+const MAX_POLL_MS = 4 * 60 * 1000;
+
+const actions = document.querySelector('#state-result .result-bar .actions');
+const resultBar = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+
+if (actions && resultBar && viewer) {
+ injectStyles();
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn btn-ghost';
+ btn.id = 'forge-rig-btn';
+ btn.title = 'Add a humanoid skeleton so this model can be posed and animated';
+ btn.innerHTML = `
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="12" cy="5" r="2" />
+ <path d="M12 7v6" />
+ <path d="M12 13l-4 7" />
+ <path d="M12 13l4 7" />
+ <path d="M7 10h10" />
+ </svg>
+ <span id="forge-rig-label">Rig for animation</span>`;
+
+ // Insert right after the AR button (or IRL button if present) so the
+ // "make it move" actions cluster together before Refine/Compose/Download.
+ const anchorAfter = document.getElementById('forge-irl-btn') || document.getElementById('forge-ar-btn');
+ if (anchorAfter && anchorAfter.parentNode === actions) {
+ anchorAfter.after(btn);
+ } else {
+ actions.appendChild(btn);
+ }
+
+ const panel = document.createElement('div');
+ panel.className = 'rig-panel is-hidden';
+ panel.id = 'rig-panel';
+ panel.setAttribute('role', 'status');
+ panel.setAttribute('aria-live', 'polite');
+ resultBar.after(panel);
+
+ let originalGlbUrl = '';
+ let originalLabel = '';
+ let runToken = 0;
+ let elapsedTimer = null;
+ let unconfigured = false;
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ function setPanel(html) {
+ panel.innerHTML = html;
+ panel.classList.remove('is-hidden');
+ }
+
+ function hidePanel() {
+ panel.classList.add('is-hidden');
+ panel.innerHTML = '';
+ }
+
+ function stopElapsed() {
+ if (elapsedTimer) {
+ clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+ }
+
+ function setBusy(busy) {
+ btn.disabled = busy;
+ btn.classList.toggle('is-working', busy);
+ }
+
+ function renderBusy(label) {
+ setPanel(
+ `<span class="rig-spinner" aria-hidden="true"></span><span id="rig-status-text">${label}</span>`,
+ );
+ }
+
+ function startElapsed(seed = 'Rigging') {
+ stopElapsed();
+ const t0 = performance.now();
+ const tick = () => {
+ const s = Math.floor((performance.now() - t0) / 1000);
+ const node = document.getElementById('rig-status-text');
+ if (node) node.textContent = `${seed} — ${s}s`;
+ };
+ tick();
+ elapsedTimer = setInterval(tick, 1000);
+ }
+
+ async function startJob(glbUrl) {
+ const res = await fetch('/api/forge?action=rig', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ glb_url: glbUrl }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 501 || data.error === 'rig_unconfigured') {
+ const e = new Error(
+ data.message || 'Auto-rigging is not configured on this deployment.',
+ );
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ const e = new Error(`The rigger is busy. Try again in about ${secs}s.`);
+ e.kind = 'busy';
+ throw e;
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `The rigger returned ${res.status}.`);
+ }
+ return data;
+ }
+
+ async function pollUntilDone(jobId, token) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (token === runToken && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (token !== runToken) return null;
+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') {
+ throw new Error(data.error || 'Rigging failed.');
+ }
+ }
+ if (token !== runToken) return null;
+ throw new Error('Rigging timed out. Try again — self-host GPUs occasionally cold-start slowly.');
+ }
+
+ function renderDone(riggedUrl) {
+ stopElapsed();
+ const safeLabel = (originalLabel || 'forge').replace(/[^a-z0-9]+/gi, '-').slice(0, 40).replace(/^-|-$/g, '') || 'forge';
+ setPanel(`
+ <span class="rig-check" aria-hidden="true">✓</span>
+ <span>Rigged — ready to pose and animate.</span>
+ <div class="rig-actions">
+ <a class="btn btn-ghost" href="${riggedUrl}" download="${safeLabel}-rigged.glb">Download rigged GLB</a>
+ <a class="btn btn-ghost" href="/pose?src=${encodeURIComponent(riggedUrl)}">Animate in Pose Studio</a>
+ <a class="btn btn-ghost" href="/irl?avatar=${encodeURIComponent(riggedUrl)}">Place IRL</a>
+ </div>
+ `);
+ }
+
+ async function runRig() {
+ if (!originalGlbUrl || unconfigured) return;
+ const token = ++runToken;
+ setBusy(true);
+ renderBusy('Adding a skeleton');
+ startElapsed('Rigging');
+ try {
+ const job = await startJob(originalGlbUrl);
+ const done = await pollUntilDone(job.job_id, token);
+ if (token !== runToken || !done) return;
+ renderDone(done.glb_url);
+ } catch (err) {
+ if (token !== runToken) return;
+ stopElapsed();
+ if (err.kind === 'unconfigured') {
+ unconfigured = true;
+ btn.disabled = true;
+ btn.title = 'Auto-rigging is not configured on this deployment yet.';
+ setPanel(
+ `<span class="rig-warn" aria-hidden="true">◌</span><span>${err.message}</span>`,
+ );
+ setTimeout(hidePanel, 6000);
+ return;
+ }
+ setPanel(
+ `<span class="rig-warn" aria-hidden="true">⚠</span><span>${err.message}</span> ` +
+ `<button type="button" class="btn btn-ghost btn-sm" id="rig-retry">Retry</button>`,
+ );
+ document.getElementById('rig-retry')?.addEventListener('click', runRig);
+ } finally {
+ if (token === runToken) setBusy(false);
+ }
+ }
+
+ btn.addEventListener('click', runRig);
+
+ function onNewSource(glbUrl, label) {
+ if (!glbUrl || glbUrl === originalGlbUrl) return;
+ originalGlbUrl = glbUrl;
+ originalLabel = label || '';
+ runToken++;
+ stopElapsed();
+ if (!unconfigured) {
+ hidePanel();
+ setBusy(false);
+ }
+ }
+
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === originalGlbUrl) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+}
+
+function injectStyles() {
+ if (document.getElementById('forge-rig-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'forge-rig-styles';
+ style.textContent = `
+ #forge-rig-btn.is-working { cursor: progress; opacity: 0.75; }
+ .rig-panel {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.6rem;
+ margin: 0 var(--space-md, 1rem) var(--space-sm, 0.75rem);
+ padding: 0.6rem 0.85rem;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm, 8px);
+ background: color-mix(in srgb, var(--accent) 6%, transparent);
+ font-size: var(--text-sm, 0.85rem);
+ color: var(--ink-dim);
+ }
+ .rig-panel.is-hidden { display: none; }
+ .rig-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-left: auto; }
+ .rig-spinner {
+ width: 12px; height: 12px; border-radius: 50%; flex: none;
+ border: 2px solid color-mix(in srgb, var(--accent) 35%, transparent);
+ border-top-color: var(--accent);
+ animation: rig-spin 0.8s linear infinite;
+ }
+ .rig-check { color: var(--success); font-weight: 700; }
+ .rig-warn { color: var(--danger); }
+ @keyframes rig-spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) { .rig-spinner { animation: none; } }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/src/forge.js b/src/forge.js
index a302e0b5b..d4220dd71 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -106,6 +106,7 @@ const els = {
forgeShareBtn: document.getElementById('forge-share-btn'),
segmentBtn: document.getElementById('forge-segment-btn'),
openInComposer: document.getElementById('open-in-composer'),
+ irlBtn: document.getElementById('forge-irl-btn'),
categoryPicker: document.getElementById('forge-category-picker'),
savedChip: document.getElementById('result-saved'),
creations: document.getElementById('creations'),
@@ -1887,6 +1888,7 @@ function showResult(glbUrl, label, meta, { autoSaved = false } = {}) {
// Cross-link into Parts Studio with this exact model pre-loaded.
if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;
if (els.openInComposer) els.openInComposer.href = `/compose?glb=${encodeURIComponent(glbUrl)}`;
+ if (els.irlBtn) els.irlBtn.href = `/irl?avatar=${encodeURIComponent(glbUrl)}`;
// Offer "Refine" when a higher tier exists and this job can be re-run. Use the
// tier the result was actually produced at (meta), falling back to the current
// selection for re-opened gallery models that don't carry tier metadata.
diff --git a/src/game/avatar-thumb.js b/src/game/avatar-thumb.js
index 6640644bc..253076bb0 100644
--- a/src/game/avatar-thumb.js
+++ b/src/game/avatar-thumb.js
@@ -8,12 +8,13 @@
import {
Scene, PerspectiveCamera, WebGLRenderer, Group, Box3, Vector3,
- HemisphereLight, DirectionalLight, AmbientLight, SRGBColorSpace,
+ HemisphereLight, DirectionalLight, AmbientLight,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { AnimationManager } from '../animation-manager.js';
import { loadManifest, getLocomotionDefs, CLIP_IDLE, dracoLoader, meshoptReady } from './avatar-rig.js';
import { log } from '../shared/log.js';
+import { applyCinematicDefaults, loadEnvironment } from '../shared/cinematic-render.js';
const SIZE = 160; // square render target, downscaled by the chip's CSS box
@@ -34,10 +35,15 @@ function ensureRenderer() {
if (_failed) return false;
try {
_renderer = new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true });
- _renderer.setPixelRatio(1);
+ // Cinematic defaults (ACES tone mapping, sRGB output) shared with every
+ // other viewer on the platform. Product-shot style HDRI, loaded once for
+ // this shared offscreen renderer (not per-thumbnail) and fire-and-forget
+ // so it never blocks the first render.
+ applyCinematicDefaults(_renderer, { exposure: 1.1, tier: 'medium' });
+ _renderer.setPixelRatio(1); // fixed thumbnail resolution, independent of quality tier
_renderer.setSize(SIZE, SIZE, false);
- _renderer.outputColorSpace = SRGBColorSpace;
_scene = new Scene();
+ loadEnvironment(_renderer, _scene, 'studio');
_scene.add(new HemisphereLight(0xffffff, 0x404a5a, 1.15));
const key = new DirectionalLight(0xffffff, 1.7);
key.position.set(1.6, 2.4, 2.0);
diff --git a/src/game/boot-avatar.js b/src/game/boot-avatar.js
index c769e6a5a..d1be6ce71 100644
--- a/src/game/boot-avatar.js
+++ b/src/game/boot-avatar.js
@@ -17,7 +17,7 @@
import {
Scene, PerspectiveCamera, WebGLRenderer, Box3, Vector3,
- HemisphereLight, DirectionalLight, AmbientLight, SRGBColorSpace,
+ HemisphereLight, DirectionalLight, AmbientLight,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { AnimationManager } from '../animation-manager.js';
@@ -27,6 +27,7 @@ import {
} from './avatar-rig.js';
import { getRequestedAvatar } from './play-handoff.js';
import { log } from '../shared/log.js';
+import { applyCinematicDefaults, loadEnvironment } from '../shared/cinematic-render.js';
const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
const TURN_SPEED = 0.5; // radians/sec — a slow, premium turntable
@@ -42,11 +43,15 @@ function boot() {
try {
renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
- renderer.outputColorSpace = SRGBColorSpace;
+ // Cinematic defaults (ACES tone mapping, sRGB output). This view is on
+ // screen for well under 6s (the loader's own safety net), so the
+ // environment uses the procedural fallback (no HDRI network fetch) to
+ // never compete with the real scene bundle's download.
+ applyCinematicDefaults(renderer, { exposure: 1.1, tier: 'medium' });
sizeToBox();
scene = new Scene();
+ loadEnvironment(renderer, scene, null);
scene.add(new HemisphereLight(0xffffff, 0x202028, 1.1));
const key = new DirectionalLight(0xffffff, 1.9);
key.position.set(1.4, 2.6, 2.2);
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 858a2b28b..28c5931b5 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -11,8 +11,7 @@
// Colyseus), reused here so a coin community is a first-class 3D space.
import {
- Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, PCFShadowMap, SRGBColorSpace,
- ACESFilmicToneMapping,
+ Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, SRGBColorSpace,
Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry, RingGeometry,
CylinderGeometry, PlaneGeometry,
TextureLoader, DoubleSide,
@@ -28,6 +27,7 @@ import { createDistrict } from './district.js';
import { DISTRICT, clampToBounds } from './world-zones.js';
import { PhysicsWorld } from '../physics/physics-world.js';
import { detectProfile, createFrameWatchdog } from '../club-perf.js';
+import { applyCinematicDefaults, loadEnvironment } from '../shared/cinematic-render.js';
import {
createFrameGovernor, trackWindowFocus, getPowerSaver, onPowerSaverChange,
FPS_ACTIVE, FPS_IDLE, FPS_SAVER,
@@ -683,13 +683,13 @@ export class CoinCommunities {
}
r.setSize(window.innerWidth, window.innerHeight);
if (this._transparentBg) r.setClearColor(0x000000, 0);
- r.shadowMap.type = PCFShadowMap;
- r.outputColorSpace = SRGBColorSpace;
- // ACES keeps the cool moonlight key and the bright avatars from clipping;
- // exposure is tuned for the dark monochrome arena (the LDR gradient backdrop
- // doesn't need the heavy pull the old HDR daylight sky did).
- r.toneMapping = ACESFilmicToneMapping;
- r.toneMappingExposure = 1.0;
+ // Cinematic defaults (ACES tone mapping, sRGB output, VSM soft shadows,
+ // pixel-ratio cap) shared with every other viewer on the platform. Exposure
+ // is tuned for the dark monochrome arena (the LDR gradient backdrop doesn't
+ // need the heavy pull the old HDR daylight sky did). _applyPerfTier() below
+ // still owns the final pixel-ratio/shadow-enabled call so power-saver mode
+ // and the 'low' tier keep degrading exactly as before.
+ applyCinematicDefaults(r, { exposure: 1.0, tier: this._perfTier === 'low' ? 'mobile' : this._perfTier });
this.renderer = r;
this._applyPerfTier();
window.addEventListener('resize', () => this._onResize());
@@ -740,6 +740,11 @@ export class CoinCommunities {
const scene = new Scene();
this.scene = scene;
+ // Real HDRI image-based lighting for the plaza (falls back to procedural
+ // RoomEnvironment on the 'low' tier or fetch failure). 'outdoor' fits the
+ // open-air metaverse plaza better than a studio backdrop.
+ loadEnvironment(this.renderer, scene, this._perfTier === 'low' ? null : 'outdoor');
+
// Far plane reaches the sky dome; near stays tight for close avatars.
// Initial FOV matches the follow mode's (camera-modes.js) so the first
// rendered frame doesn't pop before _updateCamera applies the mode.
diff --git a/src/hero-stage.js b/src/hero-stage.js
index 16b1769ea..d589d5a51 100644
--- a/src/hero-stage.js
+++ b/src/hero-stage.js
@@ -37,6 +37,7 @@ import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
const REDUCED_MOTION = () =>
typeof window !== 'undefined' &&
@@ -93,6 +94,11 @@ export class HeroStage {
this.renderer.toneMapping = ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.05;
+ // Real HDRI image-based lighting so the rings/stars pick up subtle
+ // reflected colour instead of relying on emissive materials alone.
+ // Falls back to a procedural room environment internally on fetch failure.
+ loadEnvironment(this.renderer, this.scene, 'studio');
+
this._buildRings();
this._buildStars();
diff --git a/src/irl.js b/src/irl.js
index 696357f67..97dc33fb0 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -5,7 +5,6 @@
// Walking + joystick from walk-embed. Camera mode makes the real floor the stage.
import {
- ACESFilmicToneMapping,
AmbientLight,
Box3,
BoxGeometry,
@@ -22,7 +21,6 @@ import {
OrthographicCamera,
PerspectiveCamera,
PlaneGeometry,
- PMREMGenerator,
Quaternion,
Raycaster,
Scene,
@@ -35,11 +33,10 @@ import {
TorusGeometry,
Vector2,
Vector3,
- VSMShadowMap,
WebGLRenderer,
WebGLRenderTarget,
} from 'three';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { applyCinematicDefaults, loadEnvironment, detectQualityTier } from './shared/cinematic-render.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
@@ -202,24 +199,15 @@ function setStatus(msg, { error = false, warn = false, loading = false, sticky =
// ── Renderer / scene ──────────────────────────────────────────────────────
const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
-renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.setClearColor(0x000000, 0);
-renderer.shadowMap.enabled = true;
-// PCFSoftShadowMap is deprecated in three.js and silently downgrades to hard
-// PCFShadowMap at runtime (console warning, worse shadow edges). VSMShadowMap
-// is the still-supported soft-shadow type — same intent, actually honored.
-renderer.shadowMap.type = VSMShadowMap;
-// Filmic tone mapping is what separates "sticker pasted on the camera feed"
-// from "object standing in the room" — highlight rolloff + midtone contrast,
-// the same treatment Quick Look applies to a USDZ. Exposure compensates for
-// ACES's overall darkening at these light levels.
-renderer.toneMapping = ACESFilmicToneMapping;
-renderer.toneMappingExposure = 1.15;
+// Filmic tone mapping + VSM soft shadows + IBL from a real HDRI: the shared
+// bar every viewer on the platform now matches (src/shared/cinematic-render.js).
+const qualityTier = detectQualityTier();
+applyCinematicDefaults(renderer, { exposure: 1.15, tier: qualityTier });
const scene = new Scene();
-const pmrem = new PMREMGenerator(renderer);
-scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio');
// Keyed like a studio portrait, not a flood: the IBL carries the specular/rim
// detail, the sun carries shape + shadow. The old 0.55 ambient + 0.6 hemi fill
@@ -2927,8 +2915,7 @@ function setCameraQuiet(quiet) {
function rebuildAfterContextRestore() {
try {
const prevEnv = scene.environment;
- scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
- prevEnv?.dispose?.();
+ loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio').then(() => prevEnv?.dispose?.());
} catch (e) {
log.warn('[irl] environment rebuild after context restore failed:', e);
}
diff --git a/src/irl/world-line-ar.js b/src/irl/world-line-ar.js
index 8b4126e44..8afe18bc9 100644
--- a/src/irl/world-line-ar.js
+++ b/src/irl/world-line-ar.js
@@ -18,6 +18,7 @@ import {
} from 'three';
import { getMeshoptDecoder } from '../viewer/internal.js';
import { mountPinIdle } from './pin-idle.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from '../shared/cinematic-render.js';
// ── Agent voice (TTS) ────────────────────────────────────────────────────────
let _voiceAudio = null;
@@ -286,10 +287,12 @@ export class WorldLineCeremony {
try {
const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
const renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
- renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
+ const qualityTier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier: qualityTier });
const size = 160;
renderer.setSize(size, size, false);
const scene = new Scene();
+ loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio');
scene.add(new AmbientLight(0xffffff, 1.1));
const key = new DirectionalLight(0xffffff, 1.2); key.position.set(1, 2, 2); scene.add(key);
const cam = new PerspectiveCamera(35, 1, 0.1, 100);
@@ -334,9 +337,12 @@ export class WorldLineCeremony {
try {
const renderer = new WebGLRenderer({ alpha: true, antialias: true });
renderer.xr.enabled = true;
+ const arQualityTier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier: arQualityTier });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new Scene();
+ loadEnvironment(renderer, scene, arQualityTier === 'mobile' ? null : 'studio');
scene.add(new AmbientLight(0xffffff, 1.2));
const cam = new PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 40);
const reticle = new Mesh(
diff --git a/src/notifications-page.js b/src/notifications-page.js
new file mode 100644
index 000000000..9f9944c52
--- /dev/null
+++ b/src/notifications-page.js
@@ -0,0 +1,230 @@
+// Dedicated notification-center page (pages/notifications.html) — the full
+// history view the nav bell dropdown (src/notifications.js) can't hold. Reuses
+// the dropdown's icon/label/link/escaping helpers so the two surfaces always
+// read identically; adds category tabs, delete, and cursor pagination for the
+// "hundreds of items" overflow case the dropdown never has to handle.
+
+import { TYPE_ICON, notifLabel, notifLink, escNotif, relTime, trackInApp } from './notifications.js';
+
+const AUTH_HINT_KEY = '3dagent:auth-hint';
+const PAGE_SIZE = 30;
+
+// Mirrors api/_lib/notify-prefs.js TYPE_CATEGORY — kept small and in sync by
+// hand since it only drives client-side tab filtering, not delivery gating.
+const TYPE_CATEGORY = {
+ skill_purchased: 'sales', asset_purchased: 'sales', sale: 'sales', 'payment-earned': 'sales',
+ payment_received: 'sales', referral_earned: 'sales', referral_signup: 'sales', referral_reward: 'sales',
+ pump_launch_filled: 'sales', royalty_paid: 'sales',
+ skill_purchase_confirmed: 'purchases', asset_purchase_confirmed: 'purchases',
+ skill_gift_received: 'purchases', skill_gift_sent: 'purchases',
+ remix: 'social', reply: 'social', embed: 'social', mention: 'social', fork: 'social',
+ follow: 'social', dm_received: 'social', agent_review: 'social', quest_complete: 'social',
+ irl_interaction: 'irl', irl_reply: 'irl',
+ pump_alert: 'alerts',
+ forge_complete: 'creations', forge_failed: 'creations',
+ withdrawal_completed: 'account', withdrawal_failed: 'account', payment_mismatch: 'account',
+ asset_payment_mismatch: 'account', skill_payment_mismatch: 'account', security_alert: 'account',
+ wallet_anomaly_frozen: 'account',
+};
+function categoryOf(type) { return TYPE_CATEGORY[type] || 'account'; }
+
+function isAuthed() {
+ try {
+ const raw = localStorage.getItem(AUTH_HINT_KEY);
+ return raw ? JSON.parse(raw)?.authed === true : false;
+ } catch { return false; }
+}
+
+const els = {};
+let all = []; // every notification fetched so far, newest-first
+let activeTab = ''; // '' = all
+let unread = 0;
+let hasMore = true;
+let loading = false;
+
+function q(id) { return document.getElementById(id); }
+
+function renderSkeleton() {
+ els.list.innerHTML = Array.from({ length: 6 }).map(() => `
+ <div class="n-skel-row">
+ <div class="skeleton"></div>
+ <div class="n-skel-body">
+ <div class="skeleton skeleton-row" style="height:14px;width:70%"></div>
+ <div class="skeleton skeleton-row" style="height:11px;width:30%"></div>
+ </div>
+ </div>
+ `).join('');
+}
+
+function renderEmpty() {
+ els.list.innerHTML = `
+ <div class="n-empty">
+ <div class="n-empty-icon" aria-hidden="true">🔔</div>
+ <h3>No notifications ${activeTab ? 'in this category ' : ''}yet</h3>
+ <p>When your agent earns, sells, gets remixed, followed, or finishes a quest, you'll see it here.</p>
+ </div>
+ `;
+}
+
+function filtered() {
+ return activeTab ? all.filter((n) => categoryOf(n.type) === activeTab) : all;
+}
+
+function render() {
+ const list = filtered();
+ if (!list.length) return renderEmpty();
+
+ els.list.innerHTML = list.map((n) => {
+ const icon = TYPE_ICON[n.type] || '📣';
+ const msg = notifLabel(n);
+ const link = notifLink(n);
+ const time = relTime(n.created_at);
+ const rowUnread = !n.read_at;
+ return `
+ <div class="n-row${rowUnread ? ' is-unread' : ''}"
+ data-id="${escNotif(n.id)}"
+ data-link="${escNotif(link || '')}"
+ tabindex="0" role="button"
+ aria-label="${escNotif(msg)}${rowUnread ? ' (unread)' : ''}">
+ <span class="n-icon" aria-hidden="true">${icon}</span>
+ <div class="n-body">
+ <div class="n-msg">${escNotif(msg)}</div>
+ <div class="n-time">${escNotif(time)}</div>
+ </div>
+ ${rowUnread ? '<span class="n-dot" aria-hidden="true"></span>' : ''}
+ <button type="button" class="n-del" data-id="${escNotif(n.id)}" aria-label="Delete notification" title="Delete">✕</button>
+ </div>
+ `;
+ }).join('');
+
+ els.list.querySelectorAll('.n-row').forEach((row) => {
+ const activate = (e) => {
+ if (e.target.closest('.n-del')) return;
+ const id = row.dataset.id;
+ const link = row.dataset.link;
+ if (id) trackInApp(id, 'opened');
+ if (id && row.classList.contains('is-unread')) markOneRead(id, row);
+ if (link) {
+ if (link.startsWith('http')) window.open(link, '_blank', 'noopener');
+ else window.location.href = link;
+ }
+ };
+ row.addEventListener('click', activate);
+ row.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activate(e); } });
+ });
+ els.list.querySelectorAll('.n-del').forEach((btn) => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ deleteOne(btn.dataset.id);
+ });
+ });
+
+ els.loadMoreWrap.hidden = !hasMore;
+}
+
+function markOneRead(id, rowEl) {
+ const n = all.find((x) => x.id === id);
+ if (!n || n.read_at) return;
+ n.read_at = new Date().toISOString();
+ unread = Math.max(0, unread - 1);
+ rowEl?.classList.remove('is-unread');
+ rowEl?.querySelector('.n-dot')?.remove();
+ fetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include' }).catch(() => {});
+}
+
+async function markAllRead() {
+ els.markAll.disabled = true;
+ els.markAll.textContent = 'Done ✓';
+ all.forEach((n) => { n.read_at = n.read_at || new Date().toISOString(); });
+ unread = 0;
+ render();
+ try {
+ await fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include' });
+ } catch { /* fire-and-forget */ }
+}
+
+function deleteOne(id) {
+ const row = els.list.querySelector(`.n-row[data-id="${CSS.escape(id)}"]`);
+ row?.remove();
+ const wasUnread = all.find((n) => n.id === id && !n.read_at);
+ all = all.filter((n) => n.id !== id);
+ if (wasUnread) unread = Math.max(0, unread - 1);
+ if (!filtered().length) renderEmpty();
+ fetch(`/api/notifications/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' }).catch(() => {});
+}
+
+async function loadPage(before) {
+ if (loading) return;
+ loading = true;
+ els.loadMoreBtn.disabled = true;
+ els.loadMoreBtn.textContent = 'Loading…';
+ try {
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE) });
+ if (before) params.set('before', before);
+ const resp = await fetch(`/api/notifications?${params}`, { credentials: 'include' });
+ if (resp.status === 401) {
+ els.authWall.hidden = false;
+ els.main.hidden = true;
+ return;
+ }
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const data = await resp.json();
+ const fresh = data.notifications || [];
+ all = before ? [...all, ...fresh] : fresh;
+ unread = data.unread_count ?? unread;
+ hasMore = !!data.has_more;
+ render();
+ } catch (err) {
+ els.error.textContent = 'Could not load notifications. Try refreshing the page.';
+ els.error.hidden = false;
+ } finally {
+ loading = false;
+ els.loadMoreBtn.disabled = false;
+ els.loadMoreBtn.textContent = 'Load more';
+ }
+}
+
+function wireTabs() {
+ els.tabs.querySelectorAll('.n-tab').forEach((tab) => {
+ tab.addEventListener('click', () => {
+ els.tabs.querySelectorAll('.n-tab').forEach((t) => { t.classList.remove('active'); t.setAttribute('aria-selected', 'false'); });
+ tab.classList.add('active');
+ tab.setAttribute('aria-selected', 'true');
+ activeTab = tab.dataset.type || '';
+ render();
+ });
+ });
+}
+
+async function init() {
+ els.authWall = q('n-auth-wall');
+ els.error = q('n-error');
+ els.main = q('n-main');
+ els.tabs = q('n-tabs');
+ els.list = q('n-list');
+ els.markAll = q('n-mark-all');
+ els.loadMoreWrap = q('n-load-more');
+ els.loadMoreBtn = q('n-load-more-btn');
+
+ if (!isAuthed()) {
+ els.authWall.hidden = false;
+ return;
+ }
+
+ els.main.hidden = false;
+ renderSkeleton();
+ wireTabs();
+ els.markAll.addEventListener('click', markAllRead);
+ els.loadMoreBtn.addEventListener('click', () => {
+ const last = all[all.length - 1];
+ if (last) loadPage(last.created_at);
+ });
+
+ await loadPage(null);
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+} else {
+ init();
+}
diff --git a/src/notifications.js b/src/notifications.js
index 65f9980de..b12afbb22 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -64,7 +64,7 @@ function tryAcquireFetchLock() {
} catch { return true; }
}
-const TYPE_ICON = {
+export const TYPE_ICON = {
skill_purchased: '💵',
skill_purchase_confirmed: '✅',
skill_gift_received: '🎁',
@@ -87,9 +87,11 @@ const TYPE_ICON = {
agent_review: '⭐',
forge_complete: '✨',
forge_failed: '⚠️',
+ quest_complete: '🏆',
+ royalty_paid: '💰',
};
-function notifLabel(n) {
+export function notifLabel(n) {
const p = n.payload || {};
switch (n.type) {
case 'skill_purchased':
@@ -151,6 +153,16 @@ function notifLabel(n) {
return p.prompt
? `Your generation "${String(p.prompt).slice(0, 60)}" failed. Tap to retry`
: `A 3D generation failed. Tap to retry`;
+ case 'quest_complete':
+ return p.mission
+ ? `You finished "${p.mission}"${p.gold ? ` — earned ${p.gold} gold` : ''}`
+ : `You finished a quest`;
+ case 'royalty_paid':
+ return p.usd
+ ? `${p.actor || 'A fork of your avatar'} paid you $${Number(p.usd).toFixed(3)} in royalties`
+ : p.sol
+ ? `${p.actor || 'A fork of your avatar'} paid you ${Number(p.sol).toFixed(4)} SOL in royalties`
+ : `${p.actor || 'A fork of your avatar'} paid you a royalty`;
default:
return n.type.replace(/_/g, ' ');
}
@@ -170,7 +182,7 @@ function irlPayLabel(amount, mint) {
return label ? `${human} ${label}` : human;
}
-function notifLink(n) {
+export function notifLink(n) {
const p = n.payload || {};
const raw = p.link
|| (p.tx_signature ? `https://solscan.io/tx/${encodeURIComponent(p.tx_signature)}` : null)
@@ -193,7 +205,7 @@ function safeNavUrl(raw) {
// HTML-escape untrusted notification text before it goes into innerHTML/attrs.
// Notification payloads carry other users' actor/skill/item names, so every
// interpolated value is treated as hostile.
-function escNotif(s) {
+export function escNotif(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
@@ -201,7 +213,7 @@ function escNotif(s) {
.replace(/"/g, '&quot;');
}
-function relTime(dateStr) {
+export function relTime(dateStr) {
const diff = Date.now() - new Date(dateStr).getTime();
const m = Math.floor(diff / 60_000);
if (m < 1) return 'just now';
@@ -213,7 +225,7 @@ function relTime(dateStr) {
// Fire-and-forget funnel beacon for the in-app channel. The push channel is
// instrumented from the service worker; this closes the loop for inbox opens.
-function trackInApp(notificationId, event) {
+export function trackInApp(notificationId, event) {
fetch('/api/notifications/track', {
method: 'POST',
credentials: 'include',
@@ -405,6 +417,7 @@ class NotificationInbox {
</div>
</div>
<div class="notif-panel-body" aria-live="polite" aria-atomic="false"></div>
+ <a href="/notifications" class="notif-panel-viewall">See all notifications</a>
`;
el.querySelector('.notif-mark-all').addEventListener('click', (e) => {
e.stopPropagation();
diff --git a/src/oracle-graph.js b/src/oracle-graph.js
index a801fcd0e..c9e84604d 100644
--- a/src/oracle-graph.js
+++ b/src/oracle-graph.js
@@ -34,6 +34,7 @@ import {
ToneMappingMode,
} from 'postprocessing';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
// Tier → hex color
const TIER_COLOR = {
@@ -77,14 +78,24 @@ export function mountOracleGraph(canvas, labelContainer) {
const H = () => canvas.clientHeight || 520;
const renderer = new WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: 'high-performance' });
- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
- renderer.setSize(W(), H(), false);
- renderer.outputColorSpace = 'srgb';
+ // Shared cinematic bar for sRGB output + tiered pixel ratio cap. Tone
+ // mapping stays NoToneMapping on the renderer itself: this scene already
+ // runs ACES filmic through the postprocessing ToneMappingEffect below
+ // (composed alongside bloom), so setting it on the renderer too would
+ // double-apply the curve.
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
renderer.toneMapping = NoToneMapping;
+ renderer.setSize(W(), H(), false);
const scene = new Scene();
scene.background = new Color(0x05060c);
scene.fog = new FogExp2(0x05060c, 0.012);
+ // Conviction spheres use MeshStandardMaterial (real PBR, reacts to light),
+ // so a real HDRI gives them genuine specular highlights beyond the flat
+ // key/rim/ambient rig below. No ground-contact shadow: the graph floats
+ // in open space with no floor/pedestal for a shadow to land on.
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'sunset');
// Fill + key + rim so the metallic spheres read as 3D from every orbit
// angle. The emissive glow (below) carries the tier color and feeds bloom;
// these lights give the spheres form so they don't look like flat discs.
diff --git a/src/play-agent-wallet.js b/src/play-agent-wallet.js
index 94b561594..f08a54101 100644
--- a/src/play-agent-wallet.js
+++ b/src/play-agent-wallet.js
@@ -15,7 +15,6 @@ import {
HemisphereLight, DirectionalLight, Mesh, MeshStandardMaterial, MeshBasicMaterial,
CircleGeometry, BoxGeometry, PlaneGeometry, RingGeometry, CylinderGeometry,
CanvasTexture, SRGBColorSpace, DoubleSide, GridHelper, Vector3, MathUtils,
- ACESFilmicToneMapping, PCFShadowMap,
} from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import {
@@ -23,6 +22,7 @@ import {
newAnim, CLIP_IDLE, CLIP_WALK,
} from './game/avatar-rig.js';
import { CC_AVATAR_KEY } from './game/play-handoff.js';
+import { applyCinematicDefaults, loadEnvironment, detectQualityTier } from './shared/cinematic-render.js';
// ── config ──────────────────────────────────────────────────────────────────
@@ -103,10 +103,11 @@ const camera = new PerspectiveCamera(46, 1, 0.1, 80);
camera.position.set(-1.6, 2.5, 6.4);
const renderer = new WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
-renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
-renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFShadowMap;
-renderer.toneMapping = ACESFilmicToneMapping;
+// Cinematic defaults (ACES tone mapping, sRGB output, VSM soft shadows,
+// pixel-ratio cap) shared with every other viewer on the platform.
+const qualityTier = detectQualityTier();
+applyCinematicDefaults(renderer, { exposure: 1.15, tier: qualityTier });
+loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio');
stageEl.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
diff --git a/src/pointcloud-viewer.js b/src/pointcloud-viewer.js
index 94baaddf4..54cdcdba6 100644
--- a/src/pointcloud-viewer.js
+++ b/src/pointcloud-viewer.js
@@ -21,6 +21,7 @@ import {
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js';
+import { applyCinematicDefaults, detectQualityTier } from './shared/cinematic-render.js';
export const COLOR_MODES = ['rgb', 'mono', 'height', 'depth'];
@@ -45,7 +46,12 @@ export class PointCloudViewer {
// preserveDrawingBuffer so screenshot()/toDataURL reliably capture the frame.
this.renderer = new WebGLRenderer({ antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true });
- this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ // Shared cinematic bar for ACES tone mapping + sRGB output + tiered
+ // pixel ratio cap - this still improves the color reproduction of
+ // vertex-coloured points. No HDRI/IBL and no ground-contact shadow:
+ // a point cloud has no surface materials for an environment map to
+ // reflect off of and no shadow-catching mesh to receive on.
+ applyCinematicDefaults(this.renderer, { tier: detectQualityTier() });
host.appendChild(this.renderer.domElement);
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
diff --git a/src/sentiment-heatmap-3d.js b/src/sentiment-heatmap-3d.js
index 3f6f6f50a..7741cb9fd 100644
--- a/src/sentiment-heatmap-3d.js
+++ b/src/sentiment-heatmap-3d.js
@@ -37,6 +37,7 @@ import {
CanvasTexture,
} from 'three';
import { momentumColor, glowIntensity } from './sentiment-heatmap-data.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
const SPACING = 1.55; // grid cell spacing
const BASE_H = 0.18; // minimum pillar height (so a flat token still has presence)
@@ -109,12 +110,18 @@ export class SentimentHeatmap3D {
alpha: true,
preserveDrawingBuffer: true, // required for toDataURL frame capture
});
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ // Shared cinematic bar: ACES tone mapping + sRGB output + tiered pixel
+ // ratio cap. Pillars use MeshStandardMaterial (roughness/metalness),
+ // so a real HDRI below gives them genuine specular reflections, not
+ // just flat emissive glow.
+ const tier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier });
renderer.setClearColor(0x05060a, 1);
this.renderer = renderer;
const scene = new Scene();
this.scene = scene;
+ loadEnvironment(renderer, scene, tier === 'mobile' ? null : 'sunset');
const camera = new PerspectiveCamera(46, 1, 0.1, 100);
camera.position.set(0, 7, 11);
diff --git a/src/shared/agent-watch-panel.js b/src/shared/agent-watch-panel.js
index 0433dc5e0..f9d448820 100644
--- a/src/shared/agent-watch-panel.js
+++ b/src/shared/agent-watch-panel.js
@@ -22,6 +22,7 @@ import {
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from '../viewer/internal.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './cinematic-render.js';
// Top-level endpoint — this is the real-time frame+log SSE stream.
const STREAM_URL = (id) => `/api/agent-screen-stream?agentId=${encodeURIComponent(id)}`;
@@ -1231,6 +1232,12 @@ class WatchPanel {
renderer.setClearColor(0x0a0a0d, 1);
renderer.setSize(360, 480);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ // ACES + sRGB + real HDRI IBL, shared bar (src/shared/cinematic-render.js).
+ // No ground-contact shadow here: this is a tight face-crop headshot with
+ // no floor in frame, so a shadow catcher plane would never be visible.
+ const watchQualityTier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier: watchQualityTier });
+ loadEnvironment(renderer, webcamScene, watchQualityTier === 'mobile' ? null : 'studio');
this._webcamRenderer = renderer;
this._webcamScene = webcamScene;
diff --git a/src/shared/avatar-material-realism.js b/src/shared/avatar-material-realism.js
new file mode 100644
index 000000000..7c1ed7bec
--- /dev/null
+++ b/src/shared/avatar-material-realism.js
@@ -0,0 +1,178 @@
+/**
+ * Avatar material realism — upgrades a loaded avatar's skin, eye, and hair
+ * materials from flat glTF PBR (whatever the forge lane exported) to a
+ * physically-tuned look, so avatars read as people instead of mannequins.
+ *
+ * Applied automatically by the viewer right after a humanoid GLB loads (see
+ * viewer.js setContent()) — this is not a separate opt-in step. Mesh/material
+ * classification is name-based (the same convention glb-canonicalize.js
+ * already relies on for bone mapping): Ready Player Me / Avaturn / Mixamo /
+ * VRM / VRoid exports all name skin, eye, and hair primitives predictably.
+ * A rig with none of these names is left untouched — no guessing on props.
+ *
+ * Values are measured-real, not stylized:
+ * - skin: roughness 0.45-0.6 (matte-to-slightly-oily human skin), a warm
+ * sheen layer standing in for subsurface scattering (three.js's
+ * MeshPhysicalMaterial has no true SSS term for opaque geometry — sheen
+ * is the closest physically-based approximation to the soft, warm
+ * falloff skin shows at grazing angles), 0 metalness, low specular F0.
+ * - eyes: high clearcoat (wet cornea) over a low-roughness iris/sclera,
+ * IOR 1.376 (real corneal index).
+ * - hair: alpha-cutout, double-sided, low sheen, mid roughness (individual
+ * strands are not resolved so anisotropy would be misleading here).
+ */
+
+import { Color, DoubleSide } from 'three';
+import { MeshPhysicalMaterial } from 'three';
+
+// Boundary is "start/underscore/hyphen/whitespace" on one side and
+// "underscore/hyphen/whitespace/end/(optional left|right suffix)" on the
+// other — mesh names glue words together with no separator before a L/R
+// suffix ("EyeLeft", "HairBack"), so the trailing boundary can't require a
+// hard separator the way the leading one can.
+const SKIN_NAME_RE = /(^|[_\s-])(skin|body|face|head|torso|arm|leg|hand|feet|foot)(?=[_\s-]|$)/i;
+const WOLF3D_SKIN_RE = /wolf3d_skin|wolf3d_body|wolf3d_head/i;
+const EYE_NAME_RE = /(^|[_\s-])(eye|cornea|iris|sclera)(left|right)?(?=[_\s-]|$)/i;
+const HAIR_NAME_RE = /(^|[_\s-])(hair|eyebrow|eyelash|beard|fur)(left|right|back|front)?(?=[_\s-]|$)/i;
+const TEETH_NAME_RE = /(^|[_\s-])(teeth|tongue|mouth)(?=[_\s-]|$)/i;
+
+function nameOf(node) {
+ return `${node?.name || ''} ${node?.material?.name || ''}`;
+}
+
+function classify(node) {
+ const n = nameOf(node);
+ if (WOLF3D_SKIN_RE.test(n) || SKIN_NAME_RE.test(n)) return 'skin';
+ if (EYE_NAME_RE.test(n)) return 'eye';
+ if (HAIR_NAME_RE.test(n)) return 'hair';
+ if (TEETH_NAME_RE.test(n)) return 'teeth';
+ return null;
+}
+
+// Fields worth carrying over from a plain MeshStandardMaterial onto its
+// MeshPhysicalMaterial upgrade. Deliberately NOT using MeshPhysicalMaterial's
+// own .copy() — it assumes the source is already a MeshPhysicalMaterial and
+// unconditionally copies physical-only sub-objects (e.g. clearcoatNormalScale)
+// straight off the source, which is undefined on a plain Standard material
+// and throws. Copying field-by-field is the correct, source-type-agnostic way.
+const CARRY_OVER_FIELDS = [
+ 'map', 'normalMap', 'normalScale', 'roughnessMap', 'metalnessMap', 'aoMap', 'aoMapIntensity',
+ 'emissiveMap', 'emissiveIntensity', 'alphaMap', 'envMap', 'envMapIntensity', 'side', 'transparent',
+ 'opacity', 'alphaTest', 'flatShading', 'wireframe', 'vertexColors', 'name', 'metalness', 'roughness',
+];
+
+function upgradeToPhysical(material) {
+ if (material.isMeshPhysicalMaterial) return material;
+ const physical = new MeshPhysicalMaterial();
+ for (const f of CARRY_OVER_FIELDS) {
+ if (material[f] !== undefined) physical[f] = material[f];
+ }
+ physical.color.copy(material.color);
+ if (material.emissive) physical.emissive.copy(material.emissive);
+ return physical;
+}
+
+function applySkin(material) {
+ const m = upgradeToPhysical(material);
+ m.roughness = Math.min(0.6, Math.max(0.45, m.roughness || 0.5));
+ m.metalness = 0;
+ // Warm sheen approximates the soft subsurface falloff of skin without a
+ // true SSS term — sheenColor picks up the skin's own hue automatically.
+ m.sheen = 0.35;
+ m.sheenColor = new Color(0xffe0c2).multiply(m.color || new Color(0xffffff));
+ m.sheenRoughness = 0.6;
+ // Human skin's specular reflectance (F0) is ~0.028, well below the
+ // MeshStandardMaterial default (~0.04, i.e. specularIntensity=1) — this
+ // softens the plasticky highlight non-metals get by default.
+ m.specularIntensity = 0.6;
+ m.specularColor = new Color(0xffffff);
+ m.envMapIntensity = Math.min(m.envMapIntensity ?? 1, 0.7);
+ m.needsUpdate = true;
+ return m;
+}
+
+function applyEye(material) {
+ const m = upgradeToPhysical(material);
+ m.roughness = 0.08;
+ m.metalness = 0;
+ m.clearcoat = 1;
+ m.clearcoatRoughness = 0.03;
+ m.ior = 1.376; // real corneal index of refraction
+ m.envMapIntensity = Math.max(m.envMapIntensity ?? 1, 1.1);
+ m.needsUpdate = true;
+ return m;
+}
+
+function applyHair(material) {
+ const m = upgradeToPhysical(material);
+ m.roughness = Math.min(0.55, Math.max(0.3, m.roughness || 0.4));
+ m.metalness = 0;
+ m.sheen = 0.5;
+ m.sheenColor = (m.color || new Color(0x2a1f1a)).clone();
+ m.sheenRoughness = 0.4;
+ m.side = DoubleSide;
+ if (m.map && 'alphaTest' in m) m.alphaTest = Math.max(m.alphaTest || 0, 0.35);
+ m.needsUpdate = true;
+ return m;
+}
+
+function applyTeeth(material) {
+ const m = upgradeToPhysical(material);
+ m.roughness = 0.25;
+ m.metalness = 0;
+ m.clearcoat = 0.4;
+ m.clearcoatRoughness = 0.15;
+ m.needsUpdate = true;
+ return m;
+}
+
+const APPLIERS = { skin: applySkin, eye: applyEye, hair: applyHair, teeth: applyTeeth };
+
+/**
+ * Traverse `root` and upgrade any skin/eye/hair/teeth mesh materials in
+ * place. Idempotent — re-running on an already-upgraded material is a no-op
+ * beyond reassigning the same tuned values. Returns a count per class so
+ * callers (and tests) can assert coverage on a given rig.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {{skin:number, eye:number, hair:number, teeth:number}}
+ */
+export function applyAvatarMaterialRealism(root) {
+ const counts = { skin: 0, eye: 0, hair: 0, teeth: 0 };
+ if (!root || typeof root.traverse !== 'function') return counts;
+
+ root.traverse((node) => {
+ if (!node.isMesh || !node.material) return;
+ const cls = classify(node);
+ if (!cls) return;
+ const applier = APPLIERS[cls];
+ const mats = Array.isArray(node.material) ? node.material : [node.material];
+ const upgraded = mats.map((mat) => {
+ if (!mat || !('roughness' in mat)) return mat; // skip Basic/line/sprite materials
+ counts[cls]++;
+ return applier(mat);
+ });
+ node.material = Array.isArray(node.material) ? upgraded : upgraded[0];
+ });
+
+ return counts;
+}
+
+/**
+ * True if `root` contains at least one skin or eye mesh by name — the
+ * signal viewer.js uses to decide whether a loaded GLB is an avatar worth
+ * running the realism pass on (props/vehicles/etc. never match).
+ *
+ * @param {import('three').Object3D} root
+ * @returns {boolean}
+ */
+export function looksLikeAvatarMesh(root) {
+ if (!root || typeof root.traverse !== 'function') return false;
+ let found = false;
+ root.traverse((node) => {
+ if (found || !node.isMesh) return;
+ const cls = classify(node);
+ if (cls === 'skin' || cls === 'eye') found = true;
+ });
+ return found;
+}
diff --git a/src/shared/cinematic-render.js b/src/shared/cinematic-render.js
new file mode 100644
index 000000000..d9ec49705
--- /dev/null
+++ b/src/shared/cinematic-render.js
@@ -0,0 +1,142 @@
+// Cinematic rendering defaults shared by every 3D viewer on the platform.
+//
+// Extracted from the pattern proven in /irl (src/irl.js) and the avatar
+// result viewers (TalkScene, src/voice/talk-scene.js): ACES filmic tone
+// mapping, correct sRGB output color space, image-based lighting from a
+// real HDRI (falling back to a procedural room environment when the
+// network asset hasn't loaded yet or a surface opts out for size), and a
+// ground contact shadow that catches without requiring a visible floor.
+//
+// Any surface constructing its own WebGLRenderer should call
+// `applyCinematicDefaults(renderer)` right after construction and
+// `loadEnvironment(renderer, scene, preset)` once the scene exists, instead
+// of re-deriving these values per file.
+
+import {
+ ACESFilmicToneMapping,
+ SRGBColorSpace,
+ VSMShadowMap,
+ PMREMGenerator,
+ Box3,
+ PlaneGeometry,
+ ShadowMaterial,
+ Mesh,
+} from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+
+/** Curated HDRI set, served from our own static assets (CC0, Poly Haven origin). */
+export const HDRI_PRESETS = {
+ studio: '/hdri/studio.hdr',
+ outdoor: '/hdri/outdoor.hdr',
+ sunset: '/hdri/sunset.hdr',
+};
+
+/** Render quality tiers a viewer can request. 'mobile' matches the low-end /club profile. */
+export const QUALITY_TIERS = {
+ high: { pixelRatioCap: 2, shadows: true, hdri: true },
+ medium: { pixelRatioCap: 1.5, shadows: true, hdri: true },
+ mobile: { pixelRatioCap: 1, shadows: false, hdri: false },
+};
+
+/**
+ * Pick a quality tier from real capability signals, matching src/club-perf.js.
+ * @param {object} [env]
+ * @returns {'high'|'medium'|'mobile'}
+ */
+export function detectQualityTier(env = {}) {
+ const nav = env.navigator ?? (typeof navigator !== 'undefined' ? navigator : {});
+ const win = env.window ?? (typeof window !== 'undefined' ? window : {});
+ const ua = String(nav.userAgent || '');
+ const isMobile = /(iPhone|iPad|Android|Mobi)/i.test(ua);
+ const lowMem = (nav.deviceMemory ?? 8) < 4;
+ const lowCores = (nav.hardwareConcurrency ?? 8) < 4;
+ const coarse = !!(win.matchMedia && win.matchMedia('(any-pointer: coarse)').matches);
+ if (isMobile && (lowMem || lowCores)) return 'mobile';
+ if (coarse || lowMem || lowCores) return 'medium';
+ return 'high';
+}
+
+/**
+ * Apply ACES tone mapping + correct color management + soft shadow type to
+ * a renderer. Call once, right after construction.
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {object} [opts]
+ * @param {number} [opts.exposure] - toneMappingExposure, default 1.15 (matches /irl)
+ * @param {'high'|'medium'|'mobile'} [opts.tier]
+ */
+export function applyCinematicDefaults(renderer, opts = {}) {
+ const tier = QUALITY_TIERS[opts.tier] ? opts.tier : 'high';
+ const budget = QUALITY_TIERS[tier];
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = opts.exposure ?? 1.15;
+ renderer.setPixelRatio(Math.min(typeof window !== 'undefined' ? window.devicePixelRatio : 1, budget.pixelRatioCap));
+ if (budget.shadows) {
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = VSMShadowMap;
+ } else {
+ renderer.shadowMap.enabled = false;
+ }
+ return budget;
+}
+
+const _envCache = new Map();
+
+/**
+ * Load a curated HDRI as the scene's IBL environment, PMREM-prefiltered.
+ * Falls back to the procedural RoomEnvironment (still correct, just not a
+ * real photograph) on fetch failure or when `preset` is null/'mobile' tier.
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {import('three').Scene} scene
+ * @param {'studio'|'outdoor'|'sunset'|null} preset
+ */
+export async function loadEnvironment(renderer, scene, preset = 'studio') {
+ const pmrem = new PMREMGenerator(renderer);
+ pmrem.compileEquirectangularShader();
+ if (!preset || !HDRI_PRESETS[preset]) {
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ return scene.environment;
+ }
+ try {
+ let hdrTexture = _envCache.get(preset);
+ if (!hdrTexture) {
+ const { RGBELoader } = await import('three/addons/loaders/RGBELoader.js');
+ hdrTexture = await new RGBELoader().loadAsync(HDRI_PRESETS[preset]);
+ _envCache.set(preset, hdrTexture);
+ }
+ const envMap = pmrem.fromEquirectangular(hdrTexture).texture;
+ scene.environment = envMap;
+ scene.environmentIntensity ??= 1;
+ return envMap;
+ } catch (err) {
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ return scene.environment;
+ }
+}
+
+/**
+ * A ShadowMaterial plane that renders invisible except where a shadow
+ * falls on it, giving a soft ground-contact shadow without a visible
+ * floor. Sized/positioned from the target object's bounding box, so it
+ * works for any model scale. Call again after the model changes size.
+ * @param {import('three').Scene} scene
+ * @param {import('three').Object3D} target
+ * @param {import('three').Mesh} [existing] - reuse a prior catcher plane
+ * @param {number} [opacity]
+ */
+export function updateGroundContactShadow(scene, target, existing, opacity = 0.35) {
+ const b = new Box3().setFromObject(target);
+ if (!Number.isFinite(b.min.y)) return existing ?? null;
+ const footprint = Math.max(b.max.x - b.min.x, b.max.z - b.min.z, 1);
+ const size = footprint * 6;
+ let plane = existing;
+ if (!plane) {
+ plane = new Mesh(new PlaneGeometry(1, 1), new ShadowMaterial({ opacity }));
+ plane.rotation.x = -Math.PI / 2;
+ plane.receiveShadow = true;
+ scene.add(plane);
+ }
+ plane.scale.set(size, size, 1);
+ plane.position.set((b.min.x + b.max.x) / 2, b.min.y, (b.min.z + b.max.z) / 2);
+ return plane;
+}
diff --git a/src/stage.js b/src/stage.js
index 0b1a6a4c3..c710918c7 100644
--- a/src/stage.js
+++ b/src/stage.js
@@ -29,6 +29,7 @@ import { apiFetch } from './api.js';
import { StageNet } from './stage-net.js';
import { tipAgent, TipError } from './shared/agent-tip.js';
import { LipsyncDriver } from './voice/lipsync-driver.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const THREE_DECIMALS = 6;
@@ -533,6 +534,11 @@ class StageScene {
this.renderer.toneMapping = ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.1;
+ // Real HDRI image-based lighting so the host/audience avatars' PBR
+ // materials pick up believable reflections. Falls back to a procedural
+ // room environment internally on fetch failure.
+ loadEnvironment(this.renderer, this.scene, 'studio');
+
this._buildVenue();
this.hostGroup = new Group();
this.hostGroup.position.set(0, 0, 0);
diff --git a/src/theater-stage.js b/src/theater-stage.js
index a9299bf5d..6425cdded 100644
--- a/src/theater-stage.js
+++ b/src/theater-stage.js
@@ -56,6 +56,7 @@ import { gltfLoader, disposeGltfLoader } from './loaders/gltf.js';
import { AnimationManager } from './animation-manager.js';
import { agentAvatarGlb, MANNEQUIN_GLB } from './shared/agent-3d.js';
import { log } from './shared/log.js';
+import { loadEnvironment } from './shared/cinematic-render.js';
// Reaction vocabulary mapped onto the real pre-baked clip library
// (public/animations/manifest.json). Each kind picks deterministically from its
@@ -177,6 +178,12 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false,
const scene = new Scene();
scene.fog = new Fog(0x05050a, 16, 46);
+ // Real HDRI image-based lighting so the desks' PBR materials (screens,
+ // metal trim, avatar skin) pick up believable reflections instead of
+ // flat directional-light-only shading. Falls back to a procedural room
+ // environment internally on fetch failure, so this never blocks the stage.
+ loadEnvironment(renderer, scene, 'studio');
+
// A dealing-room vantage: raised and pulled back so several rows of desks read
// as a room, not a line-up. Looks slightly down into the pit.
const CAM_BASE_Z = 10.4;
diff --git a/src/viewer.js b/src/viewer.js
index 4a276a0bb..f22ac7932 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -56,6 +56,7 @@ import { setClips, playAllClips } from './viewer/animation.js';
import { computeFramingExtent, computeFramingWidth } from './viewer/framing.js';
import { LightProbeGrid } from './light-probe-grid.js';
import { AnimationManager } from './animation-manager.js';
+import { applyAvatarMaterialRealism, looksLikeAvatarMesh } from './shared/avatar-material-realism.js';
import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
import {
CinematicPipeline,
@@ -1251,6 +1252,12 @@ export class Viewer {
}
});
+ // Skin/eye/hair realism pass — name-matched, so props and non-humanoid
+ // meshes are never touched. See src/shared/avatar-material-realism.js.
+ if (looksLikeAvatarMesh(object)) {
+ applyAvatarMaterialRealism(object);
+ }
+
this.state.punctualLights = true;
this.content.traverse((node) => {
if (node.isLight) {
diff --git a/src/voice/talk-scene.js b/src/voice/talk-scene.js
index 740e4d509..afabdfcee 100644
--- a/src/voice/talk-scene.js
+++ b/src/voice/talk-scene.js
@@ -18,23 +18,16 @@
import {
Timer,
WebGLRenderer,
- SRGBColorSpace,
- ACESFilmicToneMapping,
- PCFSoftShadowMap,
Scene,
- PMREMGenerator,
AmbientLight,
DirectionalLight,
PerspectiveCamera,
AnimationMixer,
Box3,
- PlaneGeometry,
- ShadowMaterial,
- Mesh,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { applyCinematicDefaults, loadEnvironment, detectQualityTier, updateGroundContactShadow } from '../shared/cinematic-render.js';
import { computeFraming, CAMERA_PRESETS } from './camera-presets.js';
import { TalkEmotes } from './talk-emotes.js';
import { getMeshoptDecoder } from '../viewer/internal.js';
@@ -99,17 +92,10 @@ export class TalkScene {
alpha: true,
preserveDrawingBuffer: true,
});
- this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- this.renderer.outputColorSpace = SRGBColorSpace;
- this.renderer.toneMapping = ACESFilmicToneMapping;
- this.renderer.toneMappingExposure = 1.0;
- // Soft ground-contact shadow, matching the IRL placement viewer's
- // PCFSoftShadowMap upgrade — a ShadowMaterial catcher (added once the
- // avatar loads, see _setupGroundShadow) renders invisible except where
- // the key light casts a shadow, so it doesn't break this scene's
- // transparent background.
- this.renderer.shadowMap.enabled = true;
- this.renderer.shadowMap.type = PCFSoftShadowMap;
+ // Cinematic defaults (ACES tone mapping, sRGB output, soft shadows,
+ // pixel-ratio cap) shared with every other viewer on the platform.
+ const qualityTier = detectQualityTier();
+ applyCinematicDefaults(this.renderer, { exposure: 1.0, tier: qualityTier });
const { width, height } = sizeOf(container);
this.renderer.setSize(width, height, false);
@@ -119,10 +105,9 @@ export class TalkScene {
this.scene = new Scene();
this.scene.background = null; // transparent so the page bg shows through
- // Image-based lighting via RoomEnvironment — same look-and-feel choice
- // model-viewer uses when no environment-image is set.
- const pmrem = new PMREMGenerator(this.renderer);
- this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ // Real HDRI image-based lighting (falls back to procedural RoomEnvironment
+ // on mobile tier or fetch failure).
+ loadEnvironment(this.renderer, this.scene, qualityTier === 'mobile' ? null : 'studio');
// Fill + key + rim for visual depth.
this.scene.add(new AmbientLight(0xffffff, 0.4));
@@ -336,18 +321,7 @@ export class TalkScene {
// the loaded model's own bounding box, so it works for any avatar height.
_setupGroundShadow() {
if (!this.root) return;
- const b = new Box3().setFromObject(this.root);
- if (!Number.isFinite(b.min.y)) return; // empty/degenerate bounds — nothing to catch a shadow
- const footprint = Math.max(b.max.x - b.min.x, b.max.z - b.min.z, 1);
- const size = footprint * 6;
- if (!this._groundShadow) {
- this._groundShadow = new Mesh(new PlaneGeometry(1, 1), new ShadowMaterial({ opacity: 0.35 }));
- this._groundShadow.rotation.x = -Math.PI / 2;
- this._groundShadow.receiveShadow = true;
- this.scene.add(this._groundShadow);
- }
- this._groundShadow.scale.set(size, size, 1);
- this._groundShadow.position.set((b.min.x + b.max.x) / 2, b.min.y, (b.min.z + b.max.z) / 2);
+ this._groundShadow = updateGroundContactShadow(this.scene, this.root, this._groundShadow);
}
_frameAvatar() {
diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.js
index 2fa7bdb13..aaf00a2f3 100644
--- a/src/walk-embed-preview.js
+++ b/src/walk-embed-preview.js
@@ -14,10 +14,8 @@ import {
MeshBasicMaterial,
MeshStandardMaterial,
CanvasTexture,
- PCFShadowMap,
PerspectiveCamera,
PlaneGeometry,
- PMREMGenerator,
Quaternion,
Scene,
ShadowMaterial,
@@ -26,11 +24,11 @@ import {
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from './viewer/internal.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { reserveWebGLContext } from './webgl-budget.js';
import { log } from './shared/log.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
const AVATAR_URL = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -79,16 +77,17 @@ export function initWalkPreview(container) {
joystickEl.remove();
return;
}
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = PCFShadowMap;
+ // Filmic tone mapping + correct sRGB output + soft VSM shadows: the shared
+ // bar every viewer on the platform now matches (src/shared/cinematic-render.js).
+ const qualityTier = detectQualityTier();
+ applyCinematicDefaults(renderer, { tier: qualityTier });
// Count this context against the shared budget so <agent-3d> grids on the
// same page leave room for it (see webgl-budget.js / element.js).
reserveWebGLContext();
const scene = new Scene();
- const pmrem = new PMREMGenerator(renderer);
- scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ // Real outdoor-sky HDRI IBL, matching its sibling /walk-embed.
+ loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'outdoor');
// Lights
const ambient = new AmbientLight(0xffffff, 0.55);
diff --git a/src/walk-embed.js b/src/walk-embed.js
index 71a30c9e4..5ffa45822 100644
--- a/src/walk-embed.js
+++ b/src/walk-embed.js
@@ -24,11 +24,9 @@ import {
HemisphereLight,
Mesh,
MeshStandardMaterial,
- PCFShadowMap,
PerspectiveCamera,
Plane,
AnimationMixer,
- PMREMGenerator,
Raycaster,
Scene,
ShadowMaterial,
@@ -37,12 +35,12 @@ import {
WebGLRenderer,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { getMeshoptDecoder } from './viewer/internal.js';
import { AnimationManager } from './animation-manager.js';
import { log } from './shared/log.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
import {
OUTBOUND,
installEmbedBridge,
@@ -313,19 +311,22 @@ function emit(type, payload = {}) {
// ── Renderer / scene ──────────────────────────────────────────────────────
const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
-renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
const HAS_SOLID_BG = !!(BG_PARAM && BG_PARAM !== 'transparent');
// Paint the actual bg color (not opaque black) so ?bg=#101820 renders the
// requested color. Transparent embeds keep alpha 0 so the host shows through.
renderer.setClearColor(HAS_SOLID_BG ? new Color(BG_PARAM) : 0x000000, HAS_SOLID_BG ? 1 : 0);
-renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFShadowMap;
+// Filmic tone mapping + correct sRGB output + soft VSM shadows: the shared bar
+// every viewer on the platform now matches (src/shared/cinematic-render.js).
+const qualityTier = detectQualityTier();
+applyCinematicDefaults(renderer, { tier: qualityTier });
const scene = new Scene();
-const pmrem = new PMREMGenerator(renderer);
-scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+// Real outdoor-sky HDRI IBL: walking scenes read better under an outdoor
+// preset than the studio default. Falls back to a procedural environment on
+// fetch failure or mobile tier.
+loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'outdoor');
scene.add(new AmbientLight(0xffffff, 0.55));
const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.6);
diff --git a/src/walk.js b/src/walk.js
index 669a51e70..8ce67b0b2 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -26,7 +26,7 @@ import {
MeshStandardMaterial,
OrthographicCamera,
ACESFilmicToneMapping,
- PCFSoftShadowMap,
+ VSMShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
@@ -455,7 +455,9 @@ const renderer = new WebGLRenderer({
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFSoftShadowMap;
+// PCFSoftShadowMap is deprecated in three.js and silently downgrades to hard
+// PCFShadowMap at runtime; VSMShadowMap is the supported soft-shadow type.
+renderer.shadowMap.type = VSMShadowMap;
// Filmic response to match the IRL/avatar-sdk render stack — the IBL below
// already supplies real ambient light; ACES keeps its highlights from clipping.
renderer.toneMapping = ACESFilmicToneMapping;
diff --git a/src/xr.js b/src/xr.js
index 7c070f478..7096fcd2b 100644
--- a/src/xr.js
+++ b/src/xr.js
@@ -11,9 +11,7 @@ import {
HemisphereLight,
Mesh,
MeshStandardMaterial,
- PCFShadowMap,
PerspectiveCamera,
- PMREMGenerator,
Scene,
ShadowMaterial,
WebGLRenderer,
@@ -21,7 +19,6 @@ import {
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
import { wireShareButton } from './irl/share-frame.js';
@@ -29,6 +26,7 @@ import { canUseQuickLook } from './ar/quick-look.js';
import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';
import { log } from './shared/log.js';
import { createAvatarPicker } from './avatar-picker.js';
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
// ── DOM ──────────────────────────────────────────────────────────────────────
@@ -57,15 +55,14 @@ function setStatus(msg, type = 'idle') {
// ── Three.js setup ───────────────────────────────────────────────────────────
const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
-renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
-renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFShadowMap;
-renderer.outputColorSpace = 'srgb';
+// Filmic tone mapping + correct sRGB output + soft VSM shadows: the shared bar
+// every viewer on the platform now matches (src/shared/cinematic-render.js).
+const qualityTier = detectQualityTier();
+applyCinematicDefaults(renderer, { tier: qualityTier });
const scene = new Scene();
-const pmrem = new PMREMGenerator(renderer);
-scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+loadEnvironment(renderer, scene, qualityTier === 'mobile' ? null : 'studio');
const camera = new PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.01, 100);
camera.position.set(0, 1.4, 2.6);
diff --git a/tests/api-internal-quest-notify.test.js b/tests/api-internal-quest-notify.test.js
new file mode 100644
index 000000000..f67da954f
--- /dev/null
+++ b/tests/api-internal-quest-notify.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const verifyWorldServiceTokenMock = vi.fn();
+vi.mock('../api/_lib/world-service-auth.js', () => ({
+ verifyWorldServiceToken: (...a) => verifyWorldServiceTokenMock(...a),
+}));
+
+const insertNotificationMock = vi.fn();
+vi.mock('../api/_lib/notify.js', () => ({
+ insertNotification: (...a) => insertNotificationMock(...a),
+}));
+
+const { default: handler } = await import('../api/internal/quest-notify.js');
+
+function mkReq({ method = 'POST', url = '/api/internal/quest-notify', headers = {}, body = null } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method, url, headers: hdrs,
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') this._endCb = cb;
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+const ACCOUNT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+beforeEach(() => {
+ verifyWorldServiceTokenMock.mockReset().mockResolvedValue(null);
+ insertNotificationMock.mockReset();
+});
+
+describe('POST /api/internal/quest-notify', () => {
+ it('rejects a request with no valid world-service token', async () => {
+ const req = mkReq({ body: { accountUid: ACCOUNT, mission: 'Heist' } });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(401);
+ expect(insertNotificationMock).not.toHaveBeenCalled();
+ });
+
+ it('inserts a quest_complete notification for a valid service-signed request', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const req = mkReq({
+ headers: { authorization: 'Bearer faketoken' },
+ body: { accountUid: ACCOUNT, mission: 'Vault heist', gold: 250, coop: true, coin: 'THREE' },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: true });
+ expect(insertNotificationMock).toHaveBeenCalledWith(ACCOUNT, 'quest_complete', {
+ mission: 'Vault heist',
+ gold: 250,
+ coop: true,
+ coin: 'THREE',
+ link: '/play',
+ });
+ });
+
+ it('rejects a malformed accountUid even with a valid service token', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const req = mkReq({
+ headers: { authorization: 'Bearer faketoken' },
+ body: { accountUid: 'not-a-uuid', mission: 'Heist' },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(insertNotificationMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/forge-free-first.test.js b/tests/api/forge-free-first.test.js
index 5b95a8fc3..ba2c9aecf 100644
--- a/tests/api/forge-free-first.test.js
+++ b/tests/api/forge-free-first.test.js
@@ -158,9 +158,12 @@ describe('forge free-first reconstruct ordering', () => {
expect(res.body.backend).toBe('huggingface');
expect(res.body.mode).toBe('text_to_3d');
expect(res.body.glb_url).toBe('https://cdn.example/hf.glb');
- // NVIDIA NIM was attempted first (and failed), then the FREE HF lane served
- // it — the paid Replicate reconstruct was NEVER invoked.
- expect(nvidiaTextTo3d).toHaveBeenCalled();
+ // The default resolver now leads with the image-intermediate reference
+ // pipeline: with HF configured (and no self-host worker), it resolves
+ // straight to the FREE HuggingFace lane — NVIDIA's native text→mesh
+ // preview (which skips the photoreal reference image) is never even
+ // attempted, and the paid Replicate reconstruct is NEVER invoked either.
+ expect(nvidiaTextTo3d).not.toHaveBeenCalled();
expect(hfSubmit).toHaveBeenCalled();
expect(replicateSubmit).not.toHaveBeenCalled();
} finally {
@@ -261,12 +264,17 @@ describe('forge free-first reconstruct ordering', () => {
// The flag flips ORDER, not availability. With free-first OFF the paid
// Replicate default is attempted FIRST; HF still serves as the post-failure
// fallback (so the request doesn't dead-end), but only after Replicate is hit.
+ // The tier-default resolver now resolves straight to 'huggingface' when it's
+ // configured (the photoreal-reference-by-default fix), so this legacy
+ // paid-vs-free ordering — internal to the 'trellis' backend's own reconstruct
+ // fallback — is exercised via an EXPLICIT backend pick rather than the
+ // implicit default.
process.env.HF_TOKEN = 'test-hf-token';
process.env.FORGE_PREFER_FREE = 'false';
replicateSubmit.mockClear();
hfSubmit.mockClear();
try {
- const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });
+ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image', backend: 'trellis' });
const res = makeRes();
await handler(req, res);
diff --git a/tests/api/forge-lane-routing.test.js b/tests/api/forge-lane-routing.test.js
index e1e873452..40aa0fee4 100644
--- a/tests/api/forge-lane-routing.test.js
+++ b/tests/api/forge-lane-routing.test.js
@@ -67,14 +67,16 @@ describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {
]);
});
- it('keeps the native NVIDIA text→3D default first for text prompts', () => {
+ it('leads text prompts with the self-host photoreal reference pipeline; native NVIDIA text lane trails', () => {
configureAllLanes();
- // Text (userImages=false): the tier-named native lane leads, then self-host.
+ // Text (userImages=false): the tier-named image-intermediate lane leads (the
+ // reference-image pipeline), NVIDIA's native text→mesh preview is the last
+ // free-lane resort since it skips the photoreal reference image entirely.
expect(freeLaneCandidates('image', 'draft', false)).toEqual([
- 'nvidia',
'trellis_selfhost',
'hunyuan3d',
'huggingface',
+ 'nvidia',
]);
});
@@ -101,27 +103,28 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted fre
}
});
- it('off (default) keeps the native NVIDIA text lane leading', () => {
+ it('off (default) already leads with self-host TRELLIS — the photoreal reference default', () => {
configureAllLanes();
delete process.env.FORGE_SELFHOST_PRIMARY;
expect(freeLaneCandidates('image', 'draft', false)).toEqual([
- 'nvidia',
'trellis_selfhost',
'hunyuan3d',
'huggingface',
+ 'nvidia',
]);
});
- it('on: self-host workers lead for text, hosted lanes remain as fallthrough', () => {
+ it('on: self-host workers lead for text, hosted lanes remain as fallthrough (no-op vs. off)', () => {
configureAllLanes();
process.env.FORGE_SELFHOST_PRIMARY = '1';
- // nvidia (tier-named) is demoted below our own fleet; order within each group
- // is preserved, so hosted nvidia/huggingface stay in place as fallthrough.
+ // The named draft/standard default is now itself a self-host lane
+ // (trellis_selfhost), so hoisting self-host ahead of hosted lanes is a
+ // no-op here — the order matches the flag-off case exactly.
expect(freeLaneCandidates('image', 'draft', false)).toEqual([
'trellis_selfhost',
'hunyuan3d',
- 'nvidia',
'huggingface',
+ 'nvidia',
]);
});
@@ -140,7 +143,7 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted fre
process.env.NVIDIA_API_KEY = 'nvapi-test';
process.env.HF_TOKEN = 'hf_test';
process.env.FORGE_SELFHOST_PRIMARY = '1';
- expect(freeLaneCandidates('image', 'draft', false)).toEqual(['nvidia', 'huggingface']);
+ expect(freeLaneCandidates('image', 'draft', false)).toEqual(['huggingface', 'nvidia']);
});
it('on: routes an unnamed text prompt to self-host TRELLIS via the resolver', () => {
@@ -204,18 +207,20 @@ describe('resolveBackendIdWithHealth — prefer healthy self-host → other free
);
});
- it('prefers the native NVIDIA lane for healthy text, then self-host when it is down', () => {
+ it('leads text with self-host TRELLIS regardless of NVIDIA health; falls to the next lane when self-host is down', () => {
+ // trellis_selfhost has no health entry (unknown) — missing telemetry never
+ // demotes the preferred lane, so it wins even though nvidia reports 'ok'.
expect(
resolveBackendIdWithHealth({ path: 'image', tier: 'draft', userImages: false, health: { nvidia: 'ok' } }),
- ).toBe('nvidia');
+ ).toBe('trellis_selfhost');
expect(
resolveBackendIdWithHealth({
path: 'image',
tier: 'draft',
userImages: false,
- health: { nvidia: 'down', trellis_selfhost: 'ok' },
+ health: { trellis_selfhost: 'down', hunyuan3d: 'ok' },
}),
- ).toBe('trellis_selfhost');
+ ).toBe('hunyuan3d');
});
it('honors an explicitly named backend regardless of health', () => {
diff --git a/tests/api/forge-realism-routing.test.js b/tests/api/forge-realism-routing.test.js
index 28cd574ae..6dd522073 100644
--- a/tests/api/forge-realism-routing.test.js
+++ b/tests/api/forge-realism-routing.test.js
@@ -170,14 +170,19 @@ describe('Self-host lane health + cold-start coverage (triposg + hunyuan3d)', ()
});
});
-describe('Free/default tier is unchanged (no regression)', () => {
- it('draft text prompt still leads with native NVIDIA NIM', () => {
+describe('Free/default tier now leads with the photoreal reference-image pipeline', () => {
+ // Owner directive: every tier defaults to the image-intermediate (reference
+ // photo → mesh) lane, never NVIDIA's native text→mesh preview, because that
+ // reference image is the single highest-leverage lever on realism. NVIDIA
+ // stays free and explicitly selectable, and remains the final fallthrough so
+ // a text prompt never dead-ends on a deployment with no self-host/HF lane.
+ it('draft text prompt leads with self-host TRELLIS; native NVIDIA NIM is the last resort', () => {
configureAllLanes();
expect(freeLaneCandidates('image', 'draft', false)).toEqual([
- 'nvidia',
'trellis_selfhost',
'hunyuan3d',
'huggingface',
+ 'nvidia',
]);
});
@@ -186,6 +191,6 @@ describe('Free/default tier is unchanged (no regression)', () => {
const plain = freeLaneCandidates('image', 'standard', false);
expect(freeLaneCandidates('image', 'standard', false, 'hardsurface')).toEqual(plain);
expect(freeLaneCandidates('image', 'standard', false, 'organic')).toEqual(plain);
- expect(plain[0]).toBe('nvidia');
+ expect(plain[0]).toBe('trellis_selfhost');
});
});
diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.js
index 743e5ba36..a0d346f94 100644
--- a/tests/api/forge-tiers.test.js
+++ b/tests/api/forge-tiers.test.js
@@ -98,9 +98,13 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
const draftEst = nv.estimates.image.find((e) => e.tier === 'draft');
expect(draftEst.eta_seconds).toBeGreaterThan(0);
expect(draftEst.credits).toBeNull();
- // The tier-aware default map advertises a free engine for every tier.
- expect(cat.default_backend_for_tier.draft.image).toBe('nvidia');
- expect(cat.default_backend_for_tier.standard.image).toBe('nvidia');
+ // The tier-aware default map advertises a free engine for every tier. With
+ // only NVIDIA + HuggingFace configured (no self-host worker) in this test,
+ // HuggingFace — an image-intermediate, reference-capable lane — outranks
+ // NVIDIA's native text-only preview at every tier, matching the
+ // photoreal-reference-by-default policy.
+ expect(cat.default_backend_for_tier.draft.image).toBe('huggingface');
+ expect(cat.default_backend_for_tier.standard.image).toBe('huggingface');
expect(cat.default_backend_for_tier.high.image).toBe('huggingface');
});
diff --git a/tests/api/forge-trellis-selfhost.test.js b/tests/api/forge-trellis-selfhost.test.js
index 90099d7b4..33f671783 100644
--- a/tests/api/forge-trellis-selfhost.test.js
+++ b/tests/api/forge-trellis-selfhost.test.js
@@ -90,14 +90,17 @@ describe('forge-tiers — self-hosted TRELLIS routing precedence', () => {
expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis_selfhost');
});
- it('does not disturb the native text→3D default (NVIDIA) or the high-tier textured engine', () => {
+ it('leads text prompts with the self-host photoreal reference pipeline too; high stays on self-host TRELLIS', () => {
process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';
process.env.GCP_RECONSTRUCTION_KEY = 'secret';
process.env.HF_TOKEN = 'hf_test';
process.env.NVIDIA_API_KEY = 'nvapi-test';
- // Text prompts at draft/standard still get NVIDIA's native single-hop lane.
- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('nvidia');
- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false })).toBe('nvidia');
+ // Text prompts at draft/standard now default to the self-host TRELLIS
+ // image-intermediate lane too — NVIDIA's native single-hop text→mesh
+ // preview skips the photoreal reference image, so it is no longer a
+ // named tier default anywhere (see forge-tiers.js FREE_DEFAULT_FOR_TIERS).
+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('trellis_selfhost');
+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false })).toBe('trellis_selfhost');
// High names our self-host Hunyuan3D engine; unconfigured here, so the
// candidate walk falls to the self-host TRELLIS lane.
expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis_selfhost');
diff --git a/tests/api/material-studio-store.test.js b/tests/api/material-studio-store.test.js
index 4666b73ea..93db1c20c 100644
--- a/tests/api/material-studio-store.test.js
+++ b/tests/api/material-studio-store.test.js
@@ -23,7 +23,7 @@ let watsonxReply;
vi.mock('../../api/_lib/r2.js', () => ({
putObject: vi.fn(async ({ key, body }) => {
- uploadedObjects.push({ key, bytes: body.length ?? body.byteLength });
+ uploadedObjects.push({ key, bytes: body.length ?? body.byteLength, body: Buffer.from(body) });
}),
publicUrl: vi.fn((key) => `https://cdn.three.ws/${key}`),
}));
@@ -156,6 +156,50 @@ describe('restyleMaterialFromInstruction', () => {
});
expect(uploadedObjects).toHaveLength(0);
});
+
+ it('applies clearcoat + transmission + sheen as real KHR material extensions and the output still validates', async () => {
+ watsonxReply = {
+ name: 'Wet car paint over frosted glass trim',
+ baseColorFactor: [0.55, 0.05, 0.08],
+ metallicFactor: 0.6,
+ roughnessFactor: 0.35,
+ emissiveFactor: [0, 0, 0],
+ clearcoatFactor: 1,
+ clearcoatRoughnessFactor: 0.03,
+ transmissionFactor: 0.9,
+ ior: 1.45,
+ sheenColorFactor: [0.9, 0.9, 0.95],
+ sheenRoughnessFactor: 0.5,
+ notes: 'glossy lacquered paint with a frosted glass accent',
+ };
+ const { restyleMaterialFromInstruction } = await import('../../api/_lib/material-studio-store.js');
+ const result = await restyleMaterialFromInstruction({
+ glbUrl: FIXTURE_URL,
+ instruction: 'car paint with a frosted glass trim',
+ });
+
+ expect(result.factors.clearcoatFactor).toBe(1);
+ expect(result.factors.transmissionFactor).toBe(0.9);
+ expect(result.factors.ior).toBe(1.45);
+ expect(uploadedObjects).toHaveLength(1); // gltf-validator (writeAndValidate) passed
+
+ // Re-parse the persisted bytes and confirm the extensions actually landed
+ // on the material, not just in the returned `factors` echo.
+ const { NodeIO } = await import('@gltf-transform/core');
+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const doc = await io.readBinary(new Uint8Array(uploadedObjects[0].body));
+ const mat = doc.getRoot().listMaterials()[0];
+ const clearcoat = mat.getExtension('KHR_materials_clearcoat');
+ const transmission = mat.getExtension('KHR_materials_transmission');
+ const ior = mat.getExtension('KHR_materials_ior');
+ const sheen = mat.getExtension('KHR_materials_sheen');
+ expect(clearcoat?.getClearcoatFactor()).toBeCloseTo(1);
+ expect(clearcoat?.getClearcoatRoughnessFactor()).toBeCloseTo(0.03);
+ expect(transmission?.getTransmissionFactor()).toBeCloseTo(0.9);
+ expect(ior?.getIOR()).toBeCloseTo(1.45);
+ expect(sheen?.getSheenRoughnessFactor()).toBeCloseTo(0.5);
+ });
});
describe('generateSeededVariants', () => {
@@ -188,6 +232,20 @@ describe('generateSeededVariants', () => {
});
});
+ it('carries the carPaint preset clearcoat through to the persisted GLB as a real extension', async () => {
+ const { generateSeededVariants } = await import('../../api/_lib/material-studio-store.js');
+ const result = await generateSeededVariants({ glbUrl: FIXTURE_URL, preset: 'carPaint', seed: 3, count: 1 });
+ expect(uploadedObjects).toHaveLength(1);
+
+ const { NodeIO } = await import('@gltf-transform/core');
+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const doc = await io.readBinary(new Uint8Array(uploadedObjects[0].body));
+ const clearcoat = doc.getRoot().listMaterials()[0].getExtension('KHR_materials_clearcoat');
+ expect(clearcoat?.getClearcoatFactor()).toBeCloseTo(1);
+ expect(result.variants[0].config.clearcoat).toBe(1);
+ });
+
it('clamps an out-of-range count into [1, 12]', async () => {
const { generateSeededVariants } = await import('../../api/_lib/material-studio-store.js');
const result = await generateSeededVariants({ glbUrl: FIXTURE_URL, preset: 'wood', seed: 2, count: 999 });
diff --git a/tests/avatar-material-realism.test.js b/tests/avatar-material-realism.test.js
new file mode 100644
index 000000000..47233c51c
--- /dev/null
+++ b/tests/avatar-material-realism.test.js
@@ -0,0 +1,95 @@
+import { describe, it, expect } from 'vitest';
+import { Group, Mesh, BoxGeometry, MeshStandardMaterial, Color } from 'three';
+import { applyAvatarMaterialRealism, looksLikeAvatarMesh } from '../src/shared/avatar-material-realism.js';
+
+// Real three.js objects (no WebGL context needed for Material/Object3D
+// construction) — exercises the actual classification + upgrade path the
+// viewer runs after loading a GLB, not a mocked stand-in.
+
+function meshNamed(name) {
+ const m = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: 0xe8b892 }));
+ m.name = name;
+ return m;
+}
+
+function buildAvatarRoot() {
+ const root = new Group();
+ root.add(meshNamed('Wolf3D_Skin'));
+ root.add(meshNamed('Wolf3D_Head'));
+ root.add(meshNamed('EyeLeft'));
+ root.add(meshNamed('EyeRight'));
+ root.add(meshNamed('Wolf3D_Hair'));
+ root.add(meshNamed('Wolf3D_Teeth'));
+ root.add(meshNamed('sword_prop')); // untouched — not a body-part name
+ return root;
+}
+
+describe('looksLikeAvatarMesh', () => {
+ it('detects a rig with skin/eye meshes', () => {
+ expect(looksLikeAvatarMesh(buildAvatarRoot())).toBe(true);
+ });
+
+ it('returns false for a prop-only root', () => {
+ const root = new Group();
+ root.add(meshNamed('sword_prop'));
+ root.add(meshNamed('shield'));
+ expect(looksLikeAvatarMesh(root)).toBe(false);
+ });
+
+ it('is false for a non-Object3D input', () => {
+ expect(looksLikeAvatarMesh(null)).toBe(false);
+ expect(looksLikeAvatarMesh({})).toBe(false);
+ });
+});
+
+describe('applyAvatarMaterialRealism', () => {
+ it('upgrades skin/eye/hair/teeth materials and leaves props untouched', () => {
+ const root = buildAvatarRoot();
+ const counts = applyAvatarMaterialRealism(root);
+ expect(counts).toEqual({ skin: 2, eye: 2, hair: 1, teeth: 1 });
+
+ const skin = root.getObjectByName('Wolf3D_Skin').material;
+ expect(skin.isMeshPhysicalMaterial).toBe(true);
+ expect(skin.metalness).toBe(0);
+ expect(skin.roughness).toBeGreaterThanOrEqual(0.45);
+ expect(skin.roughness).toBeLessThanOrEqual(0.6);
+ expect(skin.sheen).toBeGreaterThan(0);
+
+ const eye = root.getObjectByName('EyeLeft').material;
+ expect(eye.isMeshPhysicalMaterial).toBe(true);
+ expect(eye.clearcoat).toBe(1);
+ expect(eye.ior).toBeCloseTo(1.376);
+
+ const hair = root.getObjectByName('Wolf3D_Hair').material;
+ expect(hair.isMeshPhysicalMaterial).toBe(true);
+ expect(hair.side).toBe(2); // THREE.DoubleSide
+
+ const prop = root.getObjectByName('sword_prop').material;
+ expect(prop.isMeshPhysicalMaterial).toBeUndefined();
+ });
+
+ it('is idempotent — running twice keeps the same tuned values', () => {
+ const root = buildAvatarRoot();
+ applyAvatarMaterialRealism(root);
+ const skinBefore = root.getObjectByName('Wolf3D_Skin').material.roughness;
+ applyAvatarMaterialRealism(root);
+ const skinAfter = root.getObjectByName('Wolf3D_Skin').material.roughness;
+ expect(skinAfter).toBe(skinBefore);
+ });
+
+ it('preserves the original albedo color while adding the sheen layer', () => {
+ const root = new Group();
+ const mesh = meshNamed('Wolf3D_Body');
+ mesh.material.color = new Color(0.7, 0.3, 0.2);
+ root.add(mesh);
+ applyAvatarMaterialRealism(root);
+ const mat = mesh.material;
+ expect(mat.color.r).toBeCloseTo(0.7);
+ expect(mat.color.g).toBeCloseTo(0.3);
+ expect(mat.color.b).toBeCloseTo(0.2);
+ });
+
+ it('returns all-zero counts for a non-Object3D root', () => {
+ expect(applyAvatarMaterialRealism(null)).toEqual({ skin: 0, eye: 0, hair: 0, teeth: 0 });
+ });
+});
diff --git a/tests/e2e/a11y-top-pages.spec.js b/tests/e2e/a11y-top-pages.spec.js
new file mode 100644
index 000000000..9c41c9f25
--- /dev/null
+++ b/tests/e2e/a11y-top-pages.spec.js
@@ -0,0 +1,46 @@
+// Task 07 — automated accessibility floor. Runs axe-core against the top 30
+// pages by data/pages.json priority (the same ranking that drives the
+// sitemap/llms.txt), catching contrast-below-AA, missing labels, and
+// keyboard traps before they ship. `wcag2a`/`wcag2aa`/`wcag21aa` rule sets
+// only — no experimental/best-practice rules, so this stays a hard gate and
+// not a taste argument.
+
+import { test, expect } from '@playwright/test';
+import AxeBuilder from '@axe-core/playwright';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { join, dirname } from 'node:path';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const pagesData = JSON.parse(readFileSync(join(ROOT, 'data', 'pages.json'), 'utf8'));
+
+const allPages = pagesData.sections.flatMap((s) => s.pages);
+const top30 = [...allPages]
+ .sort((a, b) => (b.priority ?? 0.5) - (a.priority ?? 0.5))
+ .slice(0, 30);
+
+// Known, accepted contrast exceptions: third-party embeds we don't control
+// the markup of, or pages that intentionally render user-generated content.
+// Keep this list short and named — it is an exception ledger, not a bypass.
+const KNOWN_EXCEPTIONS = new Set([]);
+
+for (const { path } of top30) {
+ test(`a11y floor: ${path}`, async ({ page }) => {
+ if (KNOWN_EXCEPTIONS.has(path)) test.skip();
+ await page.goto(path, { waitUntil: 'domcontentloaded', timeout: 60_000 });
+ await page.waitForTimeout(500); // let above-the-fold async content settle
+
+ const results = await new AxeBuilder({ page })
+ .withTags(['wcag2a', 'wcag2aa', 'wcag21aa'])
+ .analyze();
+
+ if (results.violations.length > 0) {
+ const summary = results.violations
+ .map((v) => `[${v.impact}] ${v.id}: ${v.help} (${v.nodes.length} node(s))\n ${v.nodes.map((n) => n.target.join(' ')).join('\n ')}`)
+ .join('\n\n');
+ throw new Error(`axe found ${results.violations.length} violation(s) on ${path}:\n\n${summary}`);
+ }
+
+ expect(results.violations).toEqual([]);
+ });
+}
diff --git a/vercel.json b/vercel.json
index f429f61a1..c3182ccd9 100644
--- a/vercel.json
+++ b/vercel.json
@@ -15,7 +15,7 @@
"api/cron/treasury-topup.js": {
"maxDuration": 120
},
- "{api/cron/economy-reconcile,api/cron/x402-ring-leak-scan}.js": {
+ "{api/cron/economy-reconcile,api/cron/x402-ring-leak-scan,api/cron/quality-bench}.js": {
"maxDuration": 300
},
"{api/strategies,api/cron/payment-session-sweep,api/cron/three-market-refresh}.js": {
@@ -218,6 +218,14 @@
},
"continue": true
},
+ {
+ "src": "/hdri/(.*)\\.hdr",
+ "headers": {
+ "access-control-allow-origin": "*",
+ "cache-control": "public, max-age=31536000, immutable"
+ },
+ "continue": true
+ },
{
"src": "/cdn/(.+)",
"dest": "/api/cdn-object?key=$1"
@@ -2390,6 +2398,14 @@
"src": "/collection/",
"dest": "/collection.html"
},
+ {
+ "src": "/notifications",
+ "dest": "/notifications.html"
+ },
+ {
+ "src": "/notifications/",
+ "dest": "/notifications.html"
+ },
{
"src": "/marketplace/analytics",
"dest": "/marketplace-analytics.html"
@@ -5557,6 +5573,10 @@
{
"path": "/api/cron/forge-off-crown",
"schedule": "7 0 * * 1"
+ },
+ {
+ "path": "/api/cron/quality-bench",
+ "schedule": "23 3 * * 1"
}
]
}
diff --git a/vite.config.js b/vite.config.js
index eee1e6910..539bff2b2 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -399,6 +399,7 @@ const appConfig = {
'marketplace-walk': resolve(__dirname, 'pages/marketplace-walk.html'),
'marketplace-analytics': resolve(__dirname, 'pages/marketplace-analytics.html'),
collection: resolve(__dirname, 'pages/collection.html'),
+ notifications: resolve(__dirname, 'pages/notifications.html'),
'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),
'agent-mind': resolve(__dirname, 'pages/agent-mind.html'),
'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),
@@ -462,6 +463,7 @@ const appConfig = {
'a-edit': resolve(__dirname, 'pages/a-edit.html'),
'a-me': resolve(__dirname, 'pages/a-me.html'),
labs: resolve(__dirname, 'pages/labs.html'),
+ 'quality-bench': resolve(__dirname, 'pages/quality-bench.html'),
search: resolve(__dirname, 'pages/search.html'),
rankings: resolve(__dirname, 'pages/rankings.html'),
'daily-match': resolve(__dirname, 'pages/daily-match.html'),
@@ -1332,6 +1334,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/bazaar/': resolve(root, 'public/bazaar.html'),
'/labs': resolve(root, 'pages/labs.html'),
'/labs/': resolve(root, 'pages/labs.html'),
+ '/quality-bench': resolve(root, 'pages/quality-bench.html'),
+ '/quality-bench/': resolve(root, 'pages/quality-bench.html'),
'/search': resolve(root, 'pages/search.html'),
'/search/': resolve(root, 'pages/search.html'),
'/rankings': resolve(root, 'pages/rankings.html'),
diff --git a/workers/model-text2motion/cloudbuild.yaml b/workers/model-text2motion/cloudbuild.yaml
index 488d6dcfd..b2138083f 100644
--- a/workers/model-text2motion/cloudbuild.yaml
+++ b/workers/model-text2motion/cloudbuild.yaml
@@ -64,5 +64,7 @@ options:
machineType: E2_HIGHCPU_32
logging: CLOUD_LOGGING_ONLY
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
# Model download + CUDA deps push the build past the 10-minute default.
timeout: 3600s
diff --git a/workers/model-text2motion/main.py b/workers/model-text2motion/main.py
index c14fc4f09..0609e5b4b 100644
--- a/workers/model-text2motion/main.py
+++ b/workers/model-text2motion/main.py
@@ -58,18 +58,39 @@ DEFAULT_FPS = 30
_bucket: Optional[storage.Bucket] = None
_sem: Optional[asyncio.Semaphore] = None
+_ready: Optional[asyncio.Event] = None
+_load_error: Optional[str] = None
_tasks: dict[str, dict] = {}
_model = None # lazily-loaded MDM sampler
+async def _load_model_bg() -> None:
+ global _load_error
+ loop = asyncio.get_event_loop()
+ try:
+ await loop.run_in_executor(None, _load_model)
+ _ready.set()
+ log.info("text2motion ready — max_concurrent=%d", MAX_CONCURRENT)
+ except Exception as exc: # noqa: BLE001
+ _load_error = safe_error(exc, context="MDM checkpoint load")
+ log.error("MDM model load FAILED: %s", exc)
+
+
@asynccontextmanager
async def lifespan(app: FastAPI):
- global _bucket, _sem
+ global _bucket, _sem, _ready
_bucket = storage.Client().bucket(GCS_BUCKET)
_sem = asyncio.Semaphore(MAX_CONCURRENT)
- loop = asyncio.get_event_loop()
- await loop.run_in_executor(None, _load_model)
- log.info("text2motion ready — max_concurrent=%d", MAX_CONCURRENT)
+ _ready = asyncio.Event()
+ # Load the checkpoint in the BACKGROUND and yield immediately — uvicorn
+ # runs the ASGI lifespan before binding the socket, and the full load
+ # (MDM transformer + CUDA transfer from the GCS FUSE-mounted weights dir)
+ # can run past Cloud Run's startup TCP-probe window on a cold instance.
+ # Backgrounding opens the port at once; requests that arrive before the
+ # load completes wait on `_ready` in `_run_inference`. Same pattern as
+ # model-trellis / model-triposg.
+ asyncio.create_task(_load_model_bg())
+ log.info("text2motion starting, model loading in background (max_concurrent=%d)", MAX_CONCURRENT)
yield
@@ -134,16 +155,25 @@ async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
@app.get("/health")
async def health() -> dict:
- return {"ok": True, "model_loaded": _model is not None}
+ return {
+ "ok": True,
+ "model_loaded": _model is not None,
+ "status": "ready" if _model is not None else ("failed" if _load_error else "loading"),
+ "load_error": _load_error,
+ }
async def _run_inference(task_id: str, prompt: str, n_frames: int, fps: int) -> None:
- assert _sem is not None and _bucket is not None
+ assert _sem is not None and _bucket is not None and _ready is not None
async with _sem:
_tasks[task_id]["status"] = "running"
started = time.time()
loop = asyncio.get_event_loop()
try:
+ try:
+ await asyncio.wait_for(_ready.wait(), timeout=600)
+ except asyncio.TimeoutError:
+ raise RuntimeError(_load_error or "model load timed out")
poses, trans = await loop.run_in_executor(None, _generate_motion, prompt, n_frames)
clip = smpl_motion_to_clip(poses, trans, fps=fps, name=_safe_name(prompt))
payload = json.dumps(clip).encode("utf-8")
diff --git a/workers/model-text2motion/mdm_sampler.py b/workers/model-text2motion/mdm_sampler.py
index 090b59318..030a7a3d8 100644
--- a/workers/model-text2motion/mdm_sampler.py
+++ b/workers/model-text2motion/mdm_sampler.py
@@ -35,22 +35,45 @@ class MdmSampler:
def _load(self) -> None:
# Imports are GPU-only — kept here so the module imports without torch.
+ import json
import os
+ from types import SimpleNamespace
import torch
+ from model.cfg_sampler import ClassifierFreeSampleModel
from utils.model_util import create_model_and_diffusion, load_model_wo_clip
- from utils.parser_util import generate_args
- args = generate_args(model_path=os.path.join(self.model_dir, "model.pt"))
- args.dataset = "humanml"
+ # utils.parser_util.generate_args() takes no parameters and parses
+ # sys.argv (a CLI-only entry point, not usable from a server process —
+ # a prior version of this file called it as `generate_args(model_path=...)`,
+ # which doesn't match its signature at all). The released checkpoints
+ # ship an `args.json` sibling to the `.pt` file with every field the
+ # model/diffusion constructors need (see MDM's own
+ # `load_args_from_model`); load that directly into a plain namespace.
+ with open(os.path.join(self.model_dir, "args.json")) as fh:
+ args = SimpleNamespace(**json.load(fh))
self._args = args
- model, diffusion = create_model_and_diffusion(args, data=None)
+ self._guidance_param = getattr(args, "guidance_param", 2.5)
+
+ # create_model_and_diffusion()'s `data` param is only consulted for
+ # `data.dataset.num_actions` (action-conditioned datasets); passing
+ # None crashes on that attribute access before the humanml/text-cond
+ # branch (which doesn't need it) is ever reached.
+ dummy_data = SimpleNamespace(dataset=SimpleNamespace())
+ model, diffusion = create_model_and_diffusion(args, dummy_data)
state = torch.load(os.path.join(self.model_dir, "model.pt"), map_location="cpu")
load_model_wo_clip(model, state)
model.to(self.device).eval()
+ # Classifier-free guidance sampling wrapper — matches sample/generate.py's
+ # own gating (skip the wrapper entirely when guidance_param == 1).
+ if self._guidance_param != 1:
+ model = ClassifierFreeSampleModel(model)
self._model = model
self._diffusion = diffusion
- log.info("MDM model + diffusion ready on %s", self.device)
+ log.info(
+ "MDM model + diffusion ready on %s (arch=%s, diffusion_steps=%s, guidance=%s)",
+ self.device, args.arch, args.diffusion_steps, self._guidance_param,
+ )
def sample(self, prompt: str, n_frames: int):
"""Text → (poses (T,24,3) axis-angle, trans (T,3)).
@@ -59,12 +82,13 @@ class MdmSampler:
root translation, and resamples to `n_frames`.
"""
import torch
- from data_loaders.humanml.scripts.motion_process import recover_from_ric
horizon = min(MAX_MOTION_LEN, max(2, int(round(n_frames * HUMANML_FPS / max(n_frames, 1))) or n_frames))
horizon = min(MAX_MOTION_LEN, max(2, n_frames))
model_kwargs = {"y": {"text": [prompt], "lengths": torch.tensor([horizon], device=self.device)}}
+ if self._guidance_param != 1:
+ model_kwargs["y"]["scale"] = torch.ones(1, device=self.device) * self._guidance_param
sample_fn = self._diffusion.p_sample_loop
with torch.no_grad():
sample = sample_fn(
@@ -76,40 +100,190 @@ class MdmSampler:
)
# Decode the HumanML3D vector representation back to joint rotations +
- # root translation, then to SMPL axis-angle. recover_smpl_from_sample is
- # provided by the MDM repo's rotation utilities.
- poses, trans = _decode_to_smpl(sample, self._args)
+ # root translation, then to SMPL-indexed axis-angle.
+ poses, trans = _decode_to_smpl(sample)
poses = np.asarray(poses, dtype=np.float64)
trans = np.asarray(trans, dtype=np.float64)
poses, trans = _resample(poses, trans, n_frames)
return poses, trans
-def _decode_to_smpl(sample, args):
- """Decode an MDM sample tensor to (poses (T,24,3), trans (T,3)).
+def _decode_to_smpl(sample):
+ """Decode an MDM sample tensor to (poses (T,22,3) axis-angle, trans (T,3)).
+
+ MDM's HumanML3D checkpoint emits a 263-dim feature vector per frame.
+ `recover_from_ric` (upstream, real) turns that back into global joint
+ *positions* on the 22-joint HumanML3D skeleton — the SMPL body joints 0-21
+ under the same kinematic tree (paramUtil.t2m_kinematic_chain).
- MDM's HumanML3D checkpoint emits a 263-dim feature vector per frame; the
- repo's `recover_from_ric` + rotation conversion recover joint positions and
- rotations. This isolates that decode so a different MDM variant only touches
- here.
+ There is no upstream `positions_to_smpl_poses` in the MDM repo (a prior
+ version of this file imported one that does not exist — verified against
+ github.com/GuyTevet/motion-diffusion-model). Converting positions to local
+ joint *rotations* is done here directly by `_positions_to_local_quats`: a
+ joint's local rotation is recovered from where ITS OWN children ended up
+ (not its own position, which under standard FK only depends on ancestor
+ rotations), via a best-fit (Kabsch) rotation from each child's rest
+ direction (`paramUtil.t2m_raw_offsets`, upstream data) to its measured
+ direction. This carries no twist signal (same limitation HumanML3D's
+ output has generally) — `smpl_to_clip`'s `rest_offsets` param is the
+ intended place to calibrate the residual SMPL-rest vs. Wolf3D-rest
+ orientation offset.
"""
- import torch
from data_loaders.humanml.scripts.motion_process import recover_from_ric
- from data_loaders.humanml.utils import paramUtil # noqa: F401 (ensures skeleton tables load)
+ from data_loaders.humanml.utils import paramUtil
# sample: (1, njoints, nfeats, T) → (T, features)
feats = sample.squeeze(0).permute(2, 0, 1).contiguous() # (T, njoints, nfeats)
n_joints = 22
positions = recover_from_ric(feats.float(), n_joints) # (T, 22, 3)
- positions = positions.cpu().numpy()
+ positions = positions.cpu().numpy().astype(np.float64)
- # Joint positions → SMPL axis-angle via the repo's inverse-kinematics helper.
- from data_loaders.humanml.scripts.motion_process import positions_to_smpl_poses
+ parents = _parents_from_kinematic_chain(paramUtil.t2m_kinematic_chain, n_joints)
+ rest_dirs = paramUtil.t2m_raw_offsets.astype(np.float64) # (22, 3), joint 0 unused
- poses, trans = positions_to_smpl_poses(positions)
+ local_quat = _positions_to_local_quats(positions, parents, rest_dirs) # (T, 22, 4) xyzw
+ poses = _quat_to_axis_angle(local_quat) # (T, 22, 3)
+ trans = positions[:, 0, :] # root joint IS the world root position
return poses, trans
+def _parents_from_kinematic_chain(kinematic_chain, n_joints: int) -> np.ndarray:
+ """Flatten paramUtil's per-limb chains (each starting at the root, joint 0)
+ into a single parent-index array, e.g. [-1, 2, 5, 8, ...] for a 22-joint
+ skeleton. Every joint in the topology appears in exactly one chain."""
+ parents = np.full(n_joints, -1, dtype=np.int64)
+ for chain in kinematic_chain:
+ for i in range(1, len(chain)):
+ parents[chain[i]] = chain[i - 1]
+ return parents
+
+
+def _quat_conjugate(q: np.ndarray) -> np.ndarray:
+ return np.concatenate([-q[..., :3], q[..., 3:4]], axis=-1)
+
+
+def _quat_multiply(a: np.ndarray, b: np.ndarray) -> np.ndarray:
+ ax, ay, az, aw = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
+ bx, by, bz, bw = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
+ return np.stack(
+ [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ],
+ axis=-1,
+ )
+
+
+def _quat_rotate(q: np.ndarray, v: np.ndarray) -> np.ndarray:
+ qv = np.concatenate([v, np.zeros_like(v[..., :1])], axis=-1)
+ return _quat_multiply(_quat_multiply(q, qv), _quat_conjugate(q))[..., :3]
+
+
+def _rotation_matrix_to_quat(r: np.ndarray) -> np.ndarray:
+ """(...,3,3) proper rotation matrices → (...,4) xyzw quaternions."""
+ m00, m01, m02 = r[..., 0, 0], r[..., 0, 1], r[..., 0, 2]
+ m10, m11, m12 = r[..., 1, 0], r[..., 1, 1], r[..., 1, 2]
+ m20, m21, m22 = r[..., 2, 0], r[..., 2, 1], r[..., 2, 2]
+ trace = m00 + m11 + m22
+ w = 0.5 * np.sqrt(np.maximum(1.0 + trace, 1e-12))
+ safe_w = np.where(w < 1e-6, 1.0, w)
+ x = (m21 - m12) / (4.0 * safe_w)
+ y = (m02 - m20) / (4.0 * safe_w)
+ z = (m10 - m01) / (4.0 * safe_w)
+ quat = np.stack([x, y, z, w], axis=-1)
+ norm = np.linalg.norm(quat, axis=-1, keepdims=True)
+ return quat / np.where(norm < 1e-8, 1.0, norm)
+
+
+def _kabsch_quat(sources: np.ndarray, targets: np.ndarray) -> np.ndarray:
+ """Best-fit rotation quaternion mapping unit-vector set `sources` onto
+ `targets`, batched over frames. `sources`/`targets`: (T, K, 3). Minimizes
+ sum_k |R @ sources[k] - targets[k]|^2 (Kabsch/Procrustes, reflection-
+ corrected so R is always a proper rotation). K == 1 degenerates to a
+ shortest-arc rotation with an unconstrained twist about that one axis —
+ the same ambiguity single-child joints have regardless of method, since
+ HumanML3D position data carries no twist signal for any joint."""
+ h = np.einsum("tka,tkb->tab", sources, targets) # (T,3,3)
+ u, _, vt = np.linalg.svd(h)
+ d = np.sign(np.linalg.det(np.einsum("tab,tbc->tac", vt.transpose(0, 2, 1), u.transpose(0, 2, 1))))
+ diag = np.tile(np.eye(3), (h.shape[0], 1, 1))
+ diag[:, 2, 2] = d
+ r = np.einsum("tab,tbc,tcd->tad", vt.transpose(0, 2, 1), diag, u.transpose(0, 2, 1))
+ return _rotation_matrix_to_quat(r)
+
+
+def _positions_to_local_quats(
+ positions: np.ndarray, parents: np.ndarray, rest_dirs: np.ndarray
+) -> np.ndarray:
+ """(T,J,3) global positions → (T,J,4) local xyzw quaternions per the
+ `parents`/`rest_dirs` topology.
+
+ A joint's local rotation `R_j` is NOT observable from its own position —
+ under standard skeletal FK (global_j = global_parent(j) * R_j, and the
+ *fixed* rest offset rotates with the PARENT's global orientation only:
+ pos[j] - pos[parent(j)] = rotate(global_parent(j), rest_dirs[j])) that
+ offset doesn't involve R_j at all. R_j only shows up in where j's OWN
+ children end up. So this recovers R_j, per joint, from the directions to
+ j's children: best-fit (Kabsch) rotation mapping each child's rest
+ direction (in j's parent-relative frame) onto its measured direction,
+ across however many children j has (root and the chest joint branch into
+ 3; most joints have exactly 1, where Kabsch degenerates to a shortest-arc
+ solve). Leaf joints (hands, feet, head) have no children and no positional
+ evidence for their own twist, so they get an identity local rotation.
+ """
+ n_frames, n_joints, _ = positions.shape
+ local_quat = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (n_frames, n_joints, 1))
+ global_quat = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (n_frames, n_joints, 1))
+
+ children_of = [[] for _ in range(n_joints)]
+ for j in range(1, n_joints):
+ children_of[parents[j]].append(j)
+
+ # Single top-down pass: `parents[j] < j` for this topology (verified — the
+ # kinematic chains are built root-outward), so global_quat[parents[j]] is
+ # always already resolved by the time joint j is processed.
+ for j in range(n_joints):
+ kids = children_of[j]
+ if kids:
+ rest = rest_dirs[np.array(kids)] # (K,3)
+ rest = rest / np.linalg.norm(rest, axis=-1, keepdims=True)
+ rest = np.broadcast_to(rest, (n_frames,) + rest.shape).copy() # (T,K,3)
+
+ measured = positions[:, kids, :] - positions[:, j : j + 1, :] # (T,K,3)
+ measured = measured / np.linalg.norm(measured, axis=-1, keepdims=True)
+
+ if j == 0:
+ targets_in_parent_frame = measured # root: parent frame == world
+ else:
+ p = parents[j]
+ k = measured.shape[1]
+ parent_conj = np.broadcast_to(_quat_conjugate(global_quat[:, p])[:, None, :], (n_frames, k, 4))
+ targets_in_parent_frame = _quat_rotate(parent_conj, measured)
+
+ local_quat[:, j] = _kabsch_quat(rest, targets_in_parent_frame)
+ # else: leaf joint, no positional evidence for its own twist — identity.
+
+ global_quat[:, j] = (
+ local_quat[:, j] if j == 0 else _quat_multiply(global_quat[:, parents[j]], local_quat[:, j])
+ )
+
+ return local_quat
+
+
+def _quat_to_axis_angle(q: np.ndarray) -> np.ndarray:
+ """(...,4) xyzw quaternion → (...,3) axis-angle."""
+ q = q / np.where(np.linalg.norm(q, axis=-1, keepdims=True) < 1e-8, 1.0, np.linalg.norm(q, axis=-1, keepdims=True))
+ w = np.clip(q[..., 3], -1.0, 1.0)
+ angle = 2.0 * np.arccos(w)
+ sin_half = np.sqrt(np.maximum(1.0 - w * w, 0.0))
+ safe_sin = np.where(sin_half < 1e-8, 1.0, sin_half)
+ axis = q[..., :3] / safe_sin[..., None]
+ aa = axis * angle[..., None]
+ return np.where(sin_half[..., None] < 1e-8, 0.0, aa)
+
+
def _resample(poses: np.ndarray, trans: np.ndarray, n_frames: int):
"""Linear-resample motion to exactly `n_frames` frames."""
src = poses.shape[0]
diff --git a/workers/texture/README.md b/workers/texture/README.md
index 47636b092..4ed254730 100644
--- a/workers/texture/README.md
+++ b/workers/texture/README.md
@@ -19,6 +19,14 @@ Geometry comes from the generation lanes ([model-triposg](../model-triposg/),
[model-trellis](../model-trellis/), etc.); this worker is the *surface* stage that
turns bare geometry into a finished, material-clad GLB.
+The viewer applies one more realism layer on top at load time, for free: any
+GLB with recognizable skin/eye/hair mesh names gets its materials upgraded to
+`MeshPhysicalMaterial` with measured-value skin sheen, wet-cornea clearcoat
+eyes, and double-sided hair (`src/shared/avatar-material-realism.js`, wired
+into `src/viewer.js`'s `setContent()`) — this runs regardless of which lane or
+worker produced the mesh, so it is not a texture-worker concern, but it is the
+other half of "the surface reads as real" this campaign targets.
+
## How it runs
Ships as the Cloud Run service **`texture-service`** in **`us-central1`**, built
@@ -88,6 +96,7 @@ curl -X POST https://$SERVICE_URL/texture \
| `negative_prompt` | no | `blurry, low quality, distorted, watermark` | |
| `num_views` | no | `8` | `4` or `8` render viewpoints |
| `texture_size` | no | `1024` | `512`, `1024`, or `2048` |
+| `material_class` | no | — | `person`, `metal`, `wood`, `fabric`, `plastic`, or `glass` — bakes measured real-world roughness/metallic factors for that class instead of a flat guess, and appends material-appropriate descriptors to the SDXL prompt (see `MATERIAL_CLASS_PBR` in `main.py`) |
### `POST /retexture_region` → `202`
diff --git a/workers/texture/main.py b/workers/texture/main.py
index 153797598..672a9243f 100644
--- a/workers/texture/main.py
+++ b/workers/texture/main.py
@@ -40,7 +40,12 @@ API contract:
prompt: str, # texture description, e.g. "worn leather, dark brown"
negative_prompt?: str,
num_views?: int, # 4 or 8 (default: 8)
- texture_size?: int # 512|1024|2048 (default: 1024)
+ texture_size?: int, # 512|1024|2048 (default: 1024)
+ material_class?: str # person|metal|wood|fabric|plastic|glass — sets the
+ # baked roughness/metallic factors to measured
+ # real-world values instead of a flat guess, and
+ # nudges the SDXL prompt with material-appropriate
+ # descriptors (see MATERIAL_CLASS_PBR below).
} → 202 { task_id, status }
POST /retexture_region {
@@ -145,6 +150,28 @@ VIEWPOINTS_8 = [
]
VIEWPOINTS_4 = [(0, 0), (90, 0), (180, 0), (270, 0)]
+# Measured-value PBR defaults per material class (see prompt 04's "material
+# presets that match reality"). Keyed by the director's material
+# classification (api/_lib/forge-director-prompts.js) — these are the same
+# real-world roughness/metallic ranges @three-ws/viewer-presets uses for its
+# skin/carPaint/brushedSteel/realGlass presets, applied here to the BAKED
+# texture atlas so a lane that never runs Material Studio still ships a
+# physically-plausible material out of the box instead of the flat
+# metallic=0/roughness=0.8 guess every class used to get.
+MATERIAL_CLASS_PBR = {
+ "person": {"metallic": 0.0, "roughness": 0.52, "prompt_suffix": "realistic human skin texture, subtle pores, soft even lighting"},
+ "metal": {"metallic": 0.9, "roughness": 0.35, "prompt_suffix": "brushed metal, subtle micro-scratches, realistic metallic reflections"},
+ "wood": {"metallic": 0.0, "roughness": 0.72, "prompt_suffix": "natural wood grain, matte varnish, realistic wood texture"},
+ "fabric": {"metallic": 0.0, "roughness": 0.88, "prompt_suffix": "woven fabric texture, soft matte cloth, visible weave"},
+ "plastic": {"metallic": 0.0, "roughness": 0.35, "prompt_suffix": "smooth injection-molded plastic, slight glossy sheen"},
+ "glass": {"metallic": 0.0, "roughness": 0.05, "prompt_suffix": "clear glass, subtle reflections, glossy transparent surface"},
+}
+DEFAULT_MATERIAL_PBR = {"metallic": 0.0, "roughness": 0.8, "prompt_suffix": ""}
+
+
+def _resolve_material_pbr(material_class: Optional[str]) -> dict:
+ return MATERIAL_CLASS_PBR.get((material_class or "").strip().lower(), DEFAULT_MATERIAL_PBR)
+
def _load_pipeline() -> None:
global _pipe
@@ -413,9 +440,13 @@ def _run_texturing(
negative_prompt: str,
num_views: int,
texture_size: int,
+ material_class: Optional[str] = None,
) -> bytes:
import trimesh
+ pbr = _resolve_material_pbr(material_class)
+ effective_prompt = f"{prompt}, {pbr['prompt_suffix']}" if pbr["prompt_suffix"] else prompt
+
mesh = _load_mesh(mesh_url)
viewpoints = VIEWPOINTS_8 if num_views >= 8 else VIEWPOINTS_4
@@ -425,20 +456,20 @@ def _run_texturing(
for az, el in viewpoints
]
- log.info("Generating texture views with SDXL+ControlNet")
+ log.info("Generating texture views with SDXL+ControlNet (material_class=%s)", material_class or "default")
view_images = [
- _generate_view_texture(d, prompt, negative_prompt, texture_size, seed=i * 42)
+ _generate_view_texture(d, effective_prompt, negative_prompt, texture_size, seed=i * 42)
for i, d in enumerate(depth_maps)
]
log.info("Projecting views onto UV atlas (%dpx)", texture_size)
texture_atlas = _project_texture_onto_uv(mesh, view_images, viewpoints, texture_size)
- log.info("Baking textured GLB")
+ log.info("Baking textured GLB with metallic=%.2f roughness=%.2f", pbr["metallic"], pbr["roughness"])
material = trimesh.visual.material.PBRMaterial(
baseColorTexture=texture_atlas,
- metallicFactor=0.0,
- roughnessFactor=0.8,
+ metallicFactor=pbr["metallic"],
+ roughnessFactor=pbr["roughness"],
)
mesh.visual = trimesh.visual.TextureVisuals(uv=mesh.visual.uv, material=material)
@@ -730,10 +761,11 @@ async def _process(
negative_prompt: str,
num_views: int,
texture_size: int,
+ material_class: Optional[str] = None,
) -> None:
await _run_task(
task_id,
- lambda: _run_texturing(mesh_url, prompt, negative_prompt, num_views, texture_size),
+ lambda: _run_texturing(mesh_url, prompt, negative_prompt, num_views, texture_size, material_class),
label="texture",
)
@@ -776,6 +808,10 @@ class TextureRequest(BaseModel):
# trained at, risking both L4 VRAM headroom and per-view coherence, so it
# is deliberately left off the accepted set below.
texture_size: int = Field(default=2048)
+ material_class: Optional[str] = Field(
+ default=None,
+ description="person|metal|wood|fabric|plastic|glass — measured-value roughness/metallic bake + prompt hint",
+ )
@field_validator("texture_size")
@classmethod
@@ -784,6 +820,13 @@ class TextureRequest(BaseModel):
raise ValueError("texture_size must be 512, 1024, or 2048")
return v
+ @field_validator("material_class")
+ @classmethod
+ def validate_material_class(cls, v: Optional[str]) -> Optional[str]:
+ if v is not None and v.strip().lower() not in MATERIAL_CLASS_PBR:
+ raise ValueError(f"material_class must be one of {sorted(MATERIAL_CLASS_PBR)}")
+ return v
+
@app.post("/texture", status_code=202)
async def texture_mesh(
@@ -806,6 +849,7 @@ async def texture_mesh(
body.negative_prompt,
body.num_views,
body.texture_size,
+ body.material_class,
)
return {"task_id": task_id, "status": "queued"}