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.

chore: land further in-progress platform work (concurrent session snapshot)

nirholas3c0e354cdc1c
diff --git a/.gitignore b/.gitignore
index f4f581c7c..9a15d2832 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,7 +42,15 @@ public/chat/index.html.gz
# Generated news permalink pages (rebuilt from data/rss/items.json by scripts/build-news.mjs)
public/news/
-data/_generated/
+# A bare "data/_generated/" directory pattern would block re-including any file
+# inside it below (git cannot un-ignore a file whose parent directory is itself
+# excluded) — glob the contents instead so the exception under it works.
+data/_generated/*
+# Exception: the fact-check accuracy benchmark is a manually-run, checked-in
+# report (real chain + real cost/time per run), not a deterministic prebuild
+# artifact like its _generated/ siblings — commit it so /fact-check always has
+# real, versioned numbers instead of needing a live re-run on every deploy.
+!data/_generated/fact-check-benchmark.json
# Animation build cache
public/animations/clips/.input-hashes.json
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95fd92804..597e3aaaa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Crypto API now has a home page and a real OpenAPI spec** — The free /api/v1/x crypto aggregator (CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC) has a public storefront at three.ws/crypto-api with a live endpoint table, and every endpoint now shows up in the OpenAPI 3.1 spec at three.ws/openapi.json. Also fixed a bug where the discovery endpoint (GET /api/v1/x) 404'd in production. (`/crypto-api`) `[feature, docs, fix]`
- **Embodied on-chain identity — every agent persona now carries a real wallet** — Personas minted with create_agent_persona are now bound to a real, deterministic Solana wallet — the same persona always re-derives the same address, and its private key is never stored, returned, or logged anywhere. persona_identity reads the wallet's live balance, ERC-8004-style reputation, token holdings, and a resolved SNS name; persona_tip and persona_send move real USDC from the persona's own wallet, hard-capped per call and per session with a confirmation threshold above which the caller must confirm explicitly. The living body now visually reflects its chain state: an aura ring colored by reputation, a cosmetic badge for holdings tier, a muted look on a low balance, and a nameplate for a verified name. (`/docs/mcp-3d-studio`) `[feature]`
- **Fact Check now has a free daily lane and a public accuracy benchmark** — Try the Fact Checker without a wallet: 3 free checks a day per IP now run the exact same real search-and-LLM chain as the paid $0.10 USDC checks — never a degraded response — with a lane field on every result so you always know which one you got. A new /fact-check page publishes the accuracy claim instead of just asserting it: a 40-claim benchmark (10 per verdict class, time-stable and non-partisan) scored against the live chain, the claim set and scoring code both linked for anyone to check, plus a live 'try one free check' box right on the page. (`/fact-check`) `[feature, improvement]`
+- **Fact Check's accuracy benchmark has a real published score, and the search+AI chain got more reliable** — The 40-claim fact-check accuracy benchmark has now actually been run against the real search-and-LLM chain, and /fact-check shows the genuine result instead of the "not yet run" placeholder. Running it for real surfaced and fixed two chain bugs along the way: a request-formatting bug was silently rejecting every fact-check call on the Groq lane, and the search step had no fallback beyond a narrow instant-answer API, so most claims returned zero sources. Both are fixed — search now also checks Wikipedia's full-text index, a free source that needs no API key — and the published score will keep improving as the platform's search coverage does. The benchmark, its scoring code, and every claim in the suite stay public for anyone to check. (`/fact-check`) `[improvement, fix]`
- **Fixed: the "View it" link on every generated 3D model now opens a real viewer** — The viewer link returned with every generated model (/viewer?src=…) previously returned a 404. It now opens a polished, interactive 3D viewer — orbit, zoom, AR on mobile, one-tap GLB download — with designed loading, empty, and error states. This affects every model made through the 3D Studio, in chat or on the web. `[fix]`
- **Forge generations get a real quality gate, an art director, and instant repeats** — Every Forge generation — free NVIDIA lane, self-hosted TRELLIS/Hunyuan3D, Hugging Face Spaces, and BYOK — now runs through an automatic quality check after it finishes: a degenerate or near-empty mesh is caught and regenerated once before it ever reaches you, and every result now carries a quality score in its metadata. New optional params (all off by default, so nothing existing changes): `seed` for reproducible generations, `output_format: glb-draco` or `glb-meshopt` for a smaller compressed download, `texture_size` and `target_polycount` for poly-aware engines. Identical text-to-3D prompts on the free lanes are now served instantly from a result cache instead of re-running the GPU pipeline (skip it per-request with `force_regenerate: true`). The IBM Granite "art director" that rewrites a rough idea into a detailed generation spec — already used by the free MCP tools — is now also available on the public /forge API behind an opt-in `director: true`, and its prompt itself got sharper: explicit per-part PBR material cues, one consistently held art style, and stronger composition constraints for cleaner reconstructions. (`/forge`) `[feature, improvement]`
- **Free live DEX data and Solana on-chain reads, no RPC setup** — The free crypto API grows two more providers: DexScreener (live price, liquidity, volume, and trade counts for any token by address, pair, or search, plus the latest boosted/newly-profiled tokens) and direct Solana reads (wallet balances, token holdings and supply, top holders, transaction detail, account info, current priority-fee percentiles) — all as plain GET calls, no JSON-RPC boilerplate, no RPC endpoint to run yourself. (`/docs/api-reference`) `[feature]`
@@ -58,6 +59,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Token-gated 3D embeds — holder-only interactive scenes** — Turn an avatar or on-chain agent you own into a holder-only interactive 3D embed. Visitors must prove a real, server-verified on-chain balance — a signed wallet challenge plus a live Solana RPC read, never a number the browser reports — before the live scene renders; below the bar they see a designed locked teaser with a connect-wallet button. Defaults to gating on $THREE, but accepts any SPL token at runtime for other communities. New create_gated_embed MCP tool, plus a REST API and a paste-anywhere <three-d> embed snippet. (`/docs/token-gated-3d-embeds`) `[feature]`
- **Trending, bonding curve, launches, and whales join pump.fun search under the versioned API** — GET /api/v1/pump/search shipped alone at first — now it has the rest of the family: GET /api/v1/pump/trending (momentum-ranked hot tokens), /curve (bonding-curve % to graduation, SOL in the curve, tokens remaining), /launches (every coin launched through three.ws, joined with the launching agent), and /whales (which wallets moved how much SOL, facts only — no invented bullish/bearish signal). All five are free, keyless, and discoverable via GET /api/v1. None of them fork an upstream implementation: trending/curve/whales share their engines with the free Crypto Data API's pump.fun endpoints, launches shares its query with the /launches page. (`/docs/api-reference`) `[feature]`
- **Vanity addresses now deliver instantly when in stock** — GET /api/x402/vanity and the pump-launch vanity upsell now check pre-ground inventory before grinding a fresh address — a match is served immediately at the same price, no match still grinds fresh as before. (`/vanity`) `[improvement]`
+- **Vanity addresses now go up to 5 characters, and the shelf restocks itself** — GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it. (`/vanity`) `[feature, improvement]`
- **Verify a 3D model's authenticity — free, on-chain content credentials** — Models generated on three.ws can now carry a signed content credential — who made it, from what prompt, by which model, when, and the model's exact content hash — with that hash anchored on Solana. Anyone can check a model for free at /api/provenance?src=… or with the verify_provenance tool, and get a clear verdict: verified, tampered (a single changed byte is caught), or unverified. The 3D viewer shows a Verified · three.ws badge. It's C2PA-style provenance for 3D — the verify path has no wallet or token surface. `[feature, security]`
- **View any generated model in your room with AR** — Every 3D model you generate can now be placed in your space through your phone. A new device-aware AR link opens Apple Quick Look on iPhone/iPad, Google Scene Viewer on Android, and the interactive 3D viewer on desktop — one tap, no app, no wallet. The USDZ for iOS is generated from the model on the fly, so any GLB works. Agents get an export_ar tool that returns the AR link alongside the model. `[feature]`
- **WorldMoves on-chain move stream (BSC) — built, blocked on funding** — Added an event-only smart contract for recording real-time player movement on BNB Chain, designed for BSC's 0.45s blocks. Fully built and tested (19 passing tests, ~4,800 gas per move); testnet deployment is pending a funded deployer wallet. `[feature, infra]`
diff --git a/api/_lib/asset-provenance.js b/api/_lib/asset-provenance.js
new file mode 100644
index 000000000..05a129059
--- /dev/null
+++ b/api/_lib/asset-provenance.js
@@ -0,0 +1,151 @@
+/**
+ * Signed provenance for generated/minted 3D assets — writes to the SAME
+ * append-only `agent_actions` ledger that `@three-ws/provenance-mcp` reads and
+ * verifies (api/agent-actions.js, packages/provenance-mcp). Every asset this
+ * platform produces gets a durable, cryptographically-verifiable record of who
+ * made it, from what prompt/model, and (for a remix/mint) its parent lineage —
+ * the "creator, prompt, parent lineage, model hash, timestamp" provenance line
+ * from prompts/roadmap/08-crypto-native-creation.md.
+ *
+ * Canonicalization + signing here is a byte-for-byte mirror of
+ * packages/provenance-mcp/src/lib/signing.js (same ACTION_SIG_VERSION, same
+ * canonical form, same ERC-191 message framing) — the same relationship
+ * api/_lib/brain-sign.js already has with the memory-ledger's client-side
+ * verification primitive. A record this module writes verifies identically
+ * through `query_action` / `list_agent_actions` (provenance-mcp) or any
+ * third-party offline `ecrecover` check. Packages are intentionally NOT
+ * cross-imported across the workspace boundary (a published npm package must
+ * not couple its versioning to the platform's serverless deploys) — mirroring
+ * is the established pattern here, not an oversight.
+ *
+ * Every write is best-effort: an agent with no provisioned EVM wallet gets an
+ * honest `unsigned` record (never blocks the mint/generation it accompanies),
+ * matching the "unsigned ≠ failure" contract in packages/provenance-mcp/README.md.
+ */
+
+import { createHash } from 'node:crypto';
+import { Wallet, verifyMessage } from 'ethers';
+
+import { sql } from './db.js';
+import { loadAgentSigner } from './brain-sign.js';
+
+// Same domain-separating prefix as packages/provenance-mcp/src/lib/signing.js —
+// do not change independently; bump both together on a breaking format change.
+export const ACTION_SIG_VERSION = 'threews:action:v1';
+
+/** Deterministic, recursive JSON serialization with sorted object keys. */
+export function stableStringify(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+ const keys = Object.keys(value).sort();
+ const body = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',');
+ return `{${body}}`;
+}
+
+/** Canonical signable form of an action — mirrors provenance-mcp's canonicalizeAction. */
+export function canonicalizeAction(action) {
+ const agentId = action.agent_id ?? action.agentId ?? '';
+ const type = action.type ?? '';
+ const payload = action.payload ?? {};
+ const sourceSkill = action.source_skill ?? action.sourceSkill ?? null;
+ return stableStringify({
+ v: ACTION_SIG_VERSION,
+ agentId: String(agentId),
+ type: String(type),
+ payload,
+ sourceSkill: sourceSkill == null ? null : String(sourceSkill),
+ });
+}
+
+export function actionDigest(action) {
+ return createHash('sha256').update(canonicalizeAction(action)).digest('hex');
+}
+
+function signMessageBody(digest) {
+ return `${ACTION_SIG_VERSION}:${digest}`;
+}
+
+/** Pure crypto — the offline check any third party runs to trust a written action. */
+export function verifyActionSignature(action, { signature, signer_address } = {}) {
+ const digest = actionDigest(action);
+ if (!signature || !signer_address) return { valid: false, recovered: null, digest, reason: 'unsigned' };
+ let recovered = null;
+ try {
+ recovered = verifyMessage(signMessageBody(digest), signature);
+ } catch {
+ return { valid: false, recovered: null, digest, reason: 'malformed_signature' };
+ }
+ const valid = recovered.toLowerCase() === String(signer_address).toLowerCase();
+ return { valid, recovered, digest, reason: valid ? 'ok' : 'signer_mismatch' };
+}
+
+/**
+ * Append a signed (best-effort) provenance record to the agent_actions ledger.
+ * Never throws — a signing or DB failure is caught and reported in the return
+ * shape so a provenance write can never break the asset flow it accompanies.
+ *
+ * @param {object} p
+ * @param {string} p.agentId owning agent (agent_identities.id) — required;
+ * callers with no resolved agent should skip the call rather than pass one.
+ * @param {string} p.type ledger action type (<=64 chars, e.g. "tokenize_3d.mint")
+ * @param {object} p.payload provenance payload (creator, prompt, model, lineage…)
+ * @param {string} [p.sourceSkill]
+ * @returns {Promise<{ recorded:boolean, signed:boolean, action_id:string|null,
+ * signer_address:string|null, digest:string|null, reason?:string }>}
+ */
+export async function writeAssetProvenance({ agentId, type, payload, sourceSkill = 'tokenize-3d' }) {
+ if (!agentId) {
+ return { recorded: false, signed: false, action_id: null, signer_address: null, digest: null, reason: 'no_agent' };
+ }
+
+ const action = { agentId, type: String(type).slice(0, 64), payload: payload || {}, sourceSkill };
+ const digest = actionDigest(action);
+
+ let signature = null;
+ let signerAddress = null;
+ try {
+ const signer = await loadAgentSigner(agentId);
+ if (signer) {
+ signature = await new Wallet(signer.privKey).signMessage(signMessageBody(digest));
+ signerAddress = signer.address;
+ }
+ } catch (err) {
+ // Best-effort: an unsigned record is an honest outcome, not a failure —
+ // never let a vault/decrypt error drop the underlying asset write.
+ console.warn('[asset-provenance] signing failed, recording unsigned:', err?.message);
+ }
+
+ try {
+ const [row] = await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill, signature, signer_address)
+ VALUES (${agentId}, ${action.type}, ${JSON.stringify(action.payload)}::jsonb, ${sourceSkill},
+ ${signature}, ${signerAddress})
+ RETURNING id
+ `;
+ return {
+ recorded: true,
+ signed: Boolean(signature),
+ action_id: row?.id != null ? String(row.id) : null,
+ signer_address: signerAddress,
+ digest,
+ };
+ } catch (err) {
+ console.error('[asset-provenance] ledger insert failed:', err?.message);
+ return { recorded: false, signed: false, action_id: null, signer_address: null, digest, reason: 'ledger_write_failed' };
+ }
+}
+
+/**
+ * Resolve the agent linked to an avatar (agent_identities.avatar_id), if any.
+ * Provenance is agent-scoped (the ledger's FK), so an avatar with no
+ * provisioned agent yet simply has no ledger entry — never an error.
+ */
+export async function agentIdForAvatar(avatarId) {
+ if (!avatarId) return null;
+ const rows = await sql`
+ SELECT id FROM agent_identities
+ WHERE avatar_id = ${avatarId} AND deleted_at IS NULL
+ ORDER BY created_at ASC LIMIT 1
+ `;
+ return rows[0]?.id ?? null;
+}
diff --git a/api/_lib/avatar-agent.js b/api/_lib/avatar-agent.js
index b993011bf..c8e972d42 100644
--- a/api/_lib/avatar-agent.js
+++ b/api/_lib/avatar-agent.js
@@ -5,6 +5,7 @@
import { sql } from './db.js';
import { withDbRetry } from './db-retry.js';
+import { writeAssetProvenance } from './asset-provenance.js';
// Claim an existing agent that has no avatar yet, or create a default one, then
// ensure that agent has a custodial Solana wallet. Idempotent and safe to retry
@@ -12,7 +13,14 @@ import { withDbRetry } from './db-retry.js';
// so a transient DB blip never leaves an avatar without its agent. Never throws
// — callers run it fire-and-forget via queueMicrotask. Returns the agent id (or
// null if provisioning could not complete).
-export async function provisionAvatarAgent({ userId, avatarId, avatarName }) {
+//
+// @param {object} p
+// @param {object} [p.provenance] generation provenance to record on the ledger
+// once the agent resolves — { prompt, generationModel, generationProvider,
+// parentAvatarId }. Omitted for a plain upload with no generation metadata;
+// still records creator + timestamp when provided with all-null fields, since
+// authorship alone is meaningful provenance. Best-effort, never blocks.
+export async function provisionAvatarAgent({ userId, avatarId, avatarName, provenance }) {
try {
const agentId = await withDbRetry(async () => {
const linked = await sql`
@@ -58,6 +66,26 @@ export async function provisionAvatarAgent({ userId, avatarId, avatarName }) {
await getOrCreateAgentSolanaWallet(agentId).catch((e) =>
console.warn('[avatar-agent] solana wallet provision failed', agentId, e?.message),
);
+
+ // Signed provenance on generation (Prompt 08, task 1): a durable,
+ // append-only ledger record of authorship — creator (the agent),
+ // prompt, generation model/provider, and parent lineage (a fork).
+ // Best-effort and fire-and-forget-safe: writeAssetProvenance never
+ // throws, so a signing/DB hiccup here can never break avatar creation.
+ writeAssetProvenance({
+ agentId,
+ type: 'avatar.generated',
+ payload: {
+ avatar_id: avatarId,
+ avatar_name: avatarName || null,
+ prompt: provenance?.prompt ?? null,
+ generation_model: provenance?.generationModel ?? null,
+ generation_provider: provenance?.generationProvider ?? null,
+ parent_avatar_id: provenance?.parentAvatarId ?? null,
+ created_at: new Date().toISOString(),
+ },
+ sourceSkill: 'avatar-agent',
+ }).catch(() => {});
}
return agentId;
} catch (err) {
diff --git a/api/_lib/diorama-build.js b/api/_lib/diorama-build.js
new file mode 100644
index 000000000..275c93616
--- /dev/null
+++ b/api/_lib/diorama-build.js
@@ -0,0 +1,237 @@
+// Diorama — server-side build + export orchestration.
+//
+// Two capabilities the browser create-flow (src/diorama/compose.js) already
+// does client-side, made available headlessly so a non-browser caller (an MCP
+// tool, an agent, a CLI) can get a real composed world in one HTTP call:
+//
+// • exportDioramaGlb(diorama) — merge an already-forged diorama's objects
+// + ground + lights into one GLB (api/_lib/scene-graph-compose.js) and
+// upload it to object storage. Mirrors bake.js/forge-store.js's storage
+// posture: best-effort, returns null when storage isn't configured rather
+// than throwing, so callers degrade instead of hard-failing.
+//
+// • buildDiorama(prompt) — compose a plan (same free-first LLM chain
+// as api/diorama.js action:compose, intentionally duplicated rather than
+// imported: action:compose is a live, working contract and this module
+// must never risk changing its behavior) then forge every object on the
+// free lane via a real HTTP call to this deployment's own /api/forge —
+// the identical public endpoint the browser flow drives, with the same
+// concurrency/deadline shape (src/diorama/compose.js) — so a "build" is
+// just that flow running headlessly instead of from a browser tab.
+//
+// No mocks: every forge is a real generation on the free NVIDIA NIM lane, and
+// export is a real @gltf-transform merge. Partial failure is not an error —
+// objects that never forge are reported back and simply excluded.
+
+import { randomUUID } from 'node:crypto';
+import { llmComplete, llmConfigured } from './llm.js';
+import { putObject, publicUrl } from './r2.js';
+import { composeSceneGlb } from './scene-graph-compose.js';
+import { normalizeDiorama, MIN_OBJECTS, MAX_OBJECTS, MAX_PROMPT_LEN, ISLAND_RADIUS } from '../../src/diorama/schema.js';
+
+const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';
+
+export function dioramaExportStoreEnabled() {
+ return Boolean(
+ process.env.S3_ENDPOINT &&
+ process.env.S3_BUCKET &&
+ process.env.S3_PUBLIC_DOMAIN &&
+ process.env.S3_ACCESS_KEY_ID &&
+ process.env.S3_SECRET_ACCESS_KEY,
+ );
+}
+
+/**
+ * Compose a diorama's forged objects into one GLB and upload it. Returns null
+ * (never throws for a config issue) when object storage isn't configured on
+ * this deployment — callers should surface a designed 503 in that case.
+ *
+ * @param {object} diorama — a normalized-or-normalizable Diorama.
+ * @returns {Promise<{ glbUrl: string, exportedCount: number, totalCount: number, skipped: object[] } | null>}
+ */
+export async function exportDioramaGlb(diorama) {
+ if (!dioramaExportStoreEnabled()) return null;
+ const { bytes, exportedCount, totalCount, skipped } = await composeSceneGlb(diorama);
+ const key = `diorama-exports/${(diorama?.id || 'draft').slice(0, 64)}/${Date.now().toString(36)}-${randomUUID().slice(0, 8)}.glb`;
+ await putObject({
+ key,
+ body: Buffer.from(bytes),
+ contentType: 'model/gltf-binary',
+ metadata: { source: 'diorama-export' },
+ });
+ return { glbUrl: publicUrl(key), exportedCount, totalCount, skipped };
+}
+
+// ── Headless compose (mirrors api/diorama.js's action:compose LLM step) ────
+
+const COMPOSE_SYSTEM = `You are a 3D set designer. You turn ONE short sentence into a tiny diorama — a miniature scene that sits on a small floating island a viewer can orbit.
+
+Return ONLY a JSON object (no prose, no markdown fence) with exactly this shape:
+{
+ "title": "2-4 word evocative title",
+ "mood": one of "dawn" | "day" | "dusk" | "night",
+ "ground": one of "grass" | "sand" | "snow" | "stone" | "water" | "meadow" | "void",
+ "island": one of "round" | "craggy" | "plateau",
+ "palette": { "sky": ["#RRGGBB","#RRGGBB"], "ground": "#RRGGBB", "fog": "#RRGGBB", "accent": "#RRGGBB" },
+ "objects": [ { "label": "short", "prompt": "ONE physical object: subject + key material + color", "position": [x, 0, z], "scale": 0.5-2.5, "rotationY": radians } ]
+}
+
+Rules:
+- ${MIN_OBJECTS} to ${MAX_OBJECTS} objects. Each "prompt" describes exactly ONE isolated physical object (a single tree, a single tent) — never a scene, never "and", never people unless one figure is the whole subject. Lead with the subject, then its dominant material and color, ≤ 12 words.
+- Spread objects across the island: x and z each between -${ISLAND_RADIUS - 1} and ${ISLAND_RADIUS - 1}, keep at least 1.5 between any two, never stack them. y is always 0. One object may sit near the center as a focal point.
+- "palette" sky is a 2-stop vertical gradient (top, horizon). Pick colors that match the mood and the scene. "accent" is the warm/cool glow color.
+- Choose mood + ground that fit the sentence (a beach → sand/day, a haunted forest → night/grass).
+- Output MUST be valid JSON. No trailing commas. No comments.`;
+
+/** @returns {Promise<object>} a normalized, pending (no meshes yet) diorama plan. */
+export async function composePlanFromPrompt(prompt) {
+ const sentence = String(prompt ?? '').slice(0, MAX_PROMPT_LEN).trim();
+ if (sentence.length < 3) {
+ throw Object.assign(new Error('Describe your world in a sentence.'), { code: 'prompt_required' });
+ }
+ if (!llmConfigured()) {
+ throw Object.assign(new Error('The world composer is warming up. Try again in a moment.'), {
+ code: 'composer_unavailable',
+ });
+ }
+
+ let completion;
+ try {
+ completion = await llmComplete({
+ system: COMPOSE_SYSTEM,
+ user: `Sentence: "${sentence}"\nReturn the diorama JSON.`,
+ maxTokens: 900,
+ timeoutMs: 30_000,
+ track: { tool: 'diorama-build' },
+ });
+ } catch (err) {
+ throw Object.assign(new Error('The world composer is busy. Try again in a moment.'), {
+ code: 'composer_unavailable',
+ cause: err,
+ });
+ }
+
+ const plan = parseJsonObject(completion?.text);
+ if (!plan) {
+ throw Object.assign(new Error('The composer returned an unexpected shape. Try rephrasing your world.'), {
+ code: 'compose_unparseable',
+ });
+ }
+ plan.prompt = sentence;
+ const { ok, diorama, errors } = normalizeDiorama(plan);
+ if (!ok || diorama.objects.length < 1) {
+ throw Object.assign(new Error('The composer could not place that world. Try a more concrete sentence.'), {
+ code: 'compose_invalid',
+ detail: errors,
+ });
+ }
+ diorama.objects = diorama.objects.map((o, i) => ({ ...o, id: `obj-${i}`, status: 'pending', glbUrl: null }));
+ return diorama;
+}
+
+function parseJsonObject(text) {
+ if (typeof text !== 'string') return null;
+ const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
+ const candidate = fence ? fence[1] : text;
+ const start = candidate.indexOf('{');
+ if (start < 0) return null;
+ let depth = 0;
+ let inStr = false;
+ let esc = false;
+ for (let i = start; i < candidate.length; i++) {
+ const c = candidate[i];
+ if (inStr) {
+ if (esc) esc = false;
+ else if (c === '\\') esc = true;
+ else if (c === '"') inStr = false;
+ continue;
+ }
+ if (c === '"') inStr = true;
+ else if (c === '{') depth++;
+ else if (c === '}') {
+ depth--;
+ if (depth === 0) {
+ try {
+ return JSON.parse(candidate.slice(start, i + 1));
+ } catch {
+ return null;
+ }
+ }
+ }
+ }
+ return null;
+}
+
+// ── Headless forge (mirrors src/diorama/compose.js's client orchestration) ─
+
+const FORGE_CONCURRENCY = 3;
+const POLL_INTERVAL_MS = 2500;
+const FORGE_DEADLINE_MS = 180_000;
+
+/**
+ * Forge every object in a diorama plan on the free lane, with bounded
+ * concurrency. Mutates nothing — returns a new diorama with each object's
+ * `status`/`glbUrl` updated. A per-object failure never throws; it lands as
+ * `status:'failed'` so the caller gets the best real world it can build.
+ *
+ * @param {object} diorama — a normalized, pending diorama plan.
+ * @param {{ clientKey?: string }} [opts]
+ */
+export async function forgeDioramaObjects(diorama, { clientKey } = {}) {
+ const key = clientKey || `diorama-build:${randomUUID()}`;
+ const objects = diorama.objects.map((o) => ({ ...o }));
+ const queue = objects.slice();
+
+ async function worker() {
+ for (;;) {
+ const obj = queue.shift();
+ if (!obj) return;
+ try {
+ const glbUrl = await runForge(obj.prompt, key);
+ obj.status = glbUrl ? 'ready' : 'failed';
+ obj.glbUrl = glbUrl || null;
+ } catch (err) {
+ console.warn(`[diorama-build] forge failed for "${obj.label}":`, err?.message);
+ obj.status = 'failed';
+ obj.glbUrl = null;
+ }
+ }
+ }
+
+ const workers = Array.from({ length: Math.min(FORGE_CONCURRENCY, queue.length) }, worker);
+ await Promise.all(workers);
+
+ return { ...diorama, objects };
+}
+
+async function runForge(prompt, clientKey) {
+ const res = await fetch(`${SITE}/api/forge`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-forge-client': clientKey },
+ body: JSON.stringify({ prompt, tier: 'draft', path: 'image' }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data?.message || data?.error || `forge returned HTTP ${res.status}`);
+ if (data.status === 'done' && data.glb_url) return data.glb_url;
+ if (data.status === 'failed') throw new Error(data.error || 'forge failed');
+ if (!data.job_id) throw new Error('forge did not start a job');
+ return pollForge(data.job_id, clientKey);
+}
+
+async function pollForge(jobId, clientKey) {
+ const deadline = Date.now() + FORGE_DEADLINE_MS;
+ while (Date.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ const res = await fetch(`${SITE}/api/forge?job=${encodeURIComponent(jobId)}`, {
+ headers: { 'x-forge-client': clientKey },
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.glb_url) return data.glb_url;
+ if (data.status === 'failed') throw new Error(data.error || 'forge failed');
+ }
+ throw new Error('this piece took too long to forge');
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql b/api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql
new file mode 100644
index 000000000..40153ffbb
--- /dev/null
+++ b/api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql
@@ -0,0 +1,25 @@
+-- Migration: remix-royalty settlement + ledger reference on tokenized 3D
+-- mints (see api/_lib/tokenize-3d.js). Additive columns only.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql
+-- Idempotent.
+--
+-- remix_royalty: when this mint names a parent_mint, the REAL on-chain
+-- USDC settlement routed to the parent's creator out of
+-- this mint's x402 fee (api/_lib/remix-royalty.js split
+-- math + api/_lib/remix-settlement.js payout wallet).
+-- null when there is no parent, or nothing was paid
+-- (reason recorded honestly — no parent wallet, sub-dust,
+-- payout unconfigured, or the mint fee was bypassed via
+-- OAuth so there was nothing to split).
+-- provenance_ledger: the agent_actions row this mint's signed provenance was
+-- appended to (api/_lib/asset-provenance.js), so a reader
+-- can cross-check the NFT metadata provenance against the
+-- independently-verifiable ledger entry.
+
+begin;
+
+alter table tokenized_3d_assets
+ add column if not exists remix_royalty jsonb,
+ add column if not exists provenance_ledger jsonb;
+
+commit;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index a488d107b..ea35c80c1 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -567,6 +567,28 @@ export const limits = {
// carpeting the gallery; non-critical so an infra hiccup never blocks a save.
dioramaSaveIp: (ip) =>
getLimiter('diorama:save:ip', { limit: 30, window: '10 m' }).limit(ip),
+ // Diorama scene export (api/diorama action:export) — merges already-forged
+ // object GLBs + a procedural ground/lights into one GLB via @gltf-transform
+ // and uploads it to object storage. No LLM/GPU spend, but it does real
+ // network egress (re-fetching every object GLB) and a storage write, so it
+ // gets its own moderate per-IP cap; non-critical since a Redis blip should
+ // degrade, not block, a local export.
+ dioramaExportIp: (ip) =>
+ getLimiter('diorama:export:ip', { limit: 20, window: '10 m' }).limit(ip),
+ // Diorama one-shot build (api/diorama action:build) — the full server-side
+ // compose → forge every object → export pipeline in a single call, for
+ // agents/MCP clients with no browser to drive the progressive client flow.
+ // It runs the same paid LLM completion as compose PLUS N free-lane forges,
+ // so it shares compose's critical/fail-closed posture and gets a tighter
+ // per-IP ceiling than compose alone.
+ dioramaBuildIp: (ip) =>
+ getLimiter('diorama:build:ip', { limit: 6, window: '10 m', critical: true }).limit(ip),
+ dioramaBuildGlobal: () =>
+ getLimiter('diorama:build:global', {
+ limit: Math.max(40, Number(process.env.DIORAMA_BUILD_GLOBAL_HOURLY) || 200),
+ window: '1 h',
+ critical: true,
+ }).limit('global'),
// x402 Bazaar MCP. Discovery calls fan out to external facilitators, so cap
// per principal to keep that egress bounded without throttling normal use.
mcpBazaar: (key) =>
diff --git a/api/_lib/remix-settlement.js b/api/_lib/remix-settlement.js
index 4d2034d3a..1c21502cc 100644
--- a/api/_lib/remix-settlement.js
+++ b/api/_lib/remix-settlement.js
@@ -26,7 +26,11 @@ const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
// dedicated REMIX_ROYALTY_PAYOUT_KEY is preferred; the shared club treasury
// secret is the fallback (same wallet the vanity bounty market pays from). Both
// are validated to decode to 64 bytes so a misconfig fails loud, never on-chain.
-function resolvePayoutKeyBase58() {
+// Exported so other real-royalty settlement flows (e.g. a tokenized-3D remix
+// mint, api/_lib/tokenize-3d.js) reuse the SAME payout wallet resolution
+// instead of re-deriving it — one source of truth for "who pays creator
+// royalties on this platform."
+export function resolvePayoutKeyBase58() {
const dedicated = process.env.REMIX_ROYALTY_PAYOUT_KEY;
if (dedicated && dedicated.trim()) {
const s = dedicated.trim();
diff --git a/api/_lib/tokenize-3d.js b/api/_lib/tokenize-3d.js
index eab6b230f..da21627ef 100644
--- a/api/_lib/tokenize-3d.js
+++ b/api/_lib/tokenize-3d.js
@@ -55,9 +55,23 @@ import {
deriveIdempotencyKey,
TOKENIZE_3D_ROYALTY_CAP_BPS,
} from './tokenize-3d-metadata.js';
+import { agentIdForAvatar, writeAssetProvenance } from './asset-provenance.js';
+import { computeRemixSplit } from './remix-royalty.js';
+import { resolvePayoutKeyBase58 } from './remix-settlement.js';
+import { transferSolanaUSDC } from './solana-transfer.js';
+import { SOLANA_USDC_MINT } from '../payments/_config.js';
+import { priceFor } from './pump-pricing.js';
export { TOKENIZE_3D_ROYALTY_CAP_BPS };
+/** The x402 price of one mint call, in USDC atomics — single source of truth
+ * (api/_lib/pump-pricing.js), reused so the remix-royalty split on a mint
+ * never drifts from what the caller was actually charged. */
+function mintPriceAtomics() {
+ const usd = priceFor('mint_3d_asset')?.amount_usdc;
+ return usd > 0 ? BigInt(Math.round(usd * 1_000_000)) : 0n;
+}
+
/** Networks we mint on. Devnet is the default; mainnet is explicit. */
export const TOKENIZE_3D_NETWORKS = /** @type {const} */ (['mainnet', 'devnet']);
@@ -347,6 +361,11 @@ function defaultDeps() {
* @param {string} [input.generationModel]
* @param {string} [input.generationProvider]
* @param {string} [input.idempotencyKey] override the derived key
+ * @param {bigint|number} [input.mintFeeAtomicsCollected] the mint fee ACTUALLY
+ * collected for this call (USDC atomics) — used only to split a remix
+ * royalty when parentMint is set. Omit/0 for an OAuth-bypassed call (no fee
+ * was collected, so nothing is split) — never assume the advertised price
+ * was paid.
* @param {object} [deps] injected dependencies (testing)
* @returns {Promise<object>} mint result
*/
@@ -403,7 +422,8 @@ export async function mintTokenized3dAsset(input, deps = defaultDeps()) {
if (!claimed) {
const [existing] = await deps.sql`
select id, status, mint, network, name, glb_url, image_url, viewer_url,
- metadata_uri, royalty_bps, royalty_recipient, tx_signature
+ metadata_uri, royalty_bps, royalty_recipient, tx_signature,
+ provenance_ledger, remix_royalty
from tokenized_3d_assets
where idempotency_key = ${idempotencyKey} and network = ${network}
`;
@@ -497,12 +517,75 @@ export async function mintTokenized3dAsset(input, deps = defaultDeps()) {
metadata_uri, royalty_bps, royalty_recipient, tx_signature
`;
+ // 5. Signed provenance on the agent_actions ledger (Prompt 08, task 1) —
+ // independently verifiable via query_action/list_agent_actions, alongside
+ // the provenance already baked into the NFT metadata itself. Best-effort:
+ // only fires when the source avatar has a provisioned agent, and never
+ // blocks or fails the mint that already succeeded on-chain.
+ let provenanceLedger = null;
+ const provenanceAgentId = await agentIdForAvatar(src.sourceAvatarId).catch(() => null);
+ if (provenanceAgentId) {
+ const ledgerResult = await writeAssetProvenance({
+ agentId: provenanceAgentId,
+ type: 'tokenize_3d.mint',
+ payload: {
+ mint,
+ network,
+ name: src.name,
+ prompt: provenance.prompt,
+ generation_model: provenance.generationModel,
+ generation_provider: provenance.generationProvider,
+ parent_mint: provenance.parentMint,
+ glb_url: media.glbUrl,
+ viewer_url: viewerUrl,
+ royalty_bps: royaltyBps,
+ creator_wallet: ownerWallet,
+ minted_at: createdAt,
+ },
+ sourceSkill: 'tokenize-3d',
+ }).catch(() => null);
+ if (ledgerResult?.recorded) {
+ provenanceLedger = {
+ action_id: ledgerResult.action_id,
+ signed: ledgerResult.signed,
+ signer_address: ledgerResult.signer_address,
+ digest: ledgerResult.digest,
+ };
+ }
+ }
+
+ // 6. Remix royalty on the mint fee (Prompt 08, task 4) — when this mint
+ // names a parent (a remix/derivative), route the parent creator's
+ // royalty slice out of the fee actually collected for THIS mint call, a
+ // real second USDC transfer, same rails as api/_lib/remix-settlement.js.
+ // Mainnet only (the payout wallet is a real mainnet treasury); a devnet
+ // remix mint still records durable parent→child lineage but settles
+ // nothing. An OAuth-bypassed mint (feeAtomicsCollected=0) has nothing to
+ // split — honestly reported, never a fabricated payout.
+ let remixRoyalty = null;
+ if (provenance.parentMint) {
+ remixRoyalty = await settleTokenizeRemixRoyalty({
+ sql: deps.sql,
+ parentMint: provenance.parentMint,
+ network,
+ feeAtomics: input.mintFeeAtomicsCollected ?? 0n,
+ });
+ }
+
+ if (provenanceLedger || remixRoyalty) {
+ await deps
+ .sql`update tokenized_3d_assets set provenance_ledger = ${provenanceLedger ? JSON.stringify(provenanceLedger) : null}::jsonb, remix_royalty = ${remixRoyalty ? JSON.stringify(remixRoyalty) : null}::jsonb, updated_at = now() where id = ${rowId}`
+ .catch((err) => console.warn('[tokenize-3d] provenance/royalty persist failed:', err?.message));
+ }
+
return formatMintResult(row, {
idempotent: false,
capped,
requestedBps,
royaltyBps,
metadataIpfs,
+ provenanceLedger,
+ remixRoyalty,
});
} catch (err) {
// Clean failure at the boundary: mark the row failed so the key can retry,
@@ -514,7 +597,96 @@ export async function mintTokenized3dAsset(input, deps = defaultDeps()) {
}
}
-function formatMintResult(row, { idempotent, capped, requestedBps, royaltyBps, metadataIpfs = null }) {
+// ── Remix royalty on a mint ─────────────────────────────────────────────────
+
+/**
+ * When a mint names a `parent_mint` (it's a derivative of another creator's
+ * tokenized 3D asset), route that creator's royalty slice out of THIS mint's
+ * x402 fee — a real second USDC transfer, same split math + payout wallet as
+ * the forge_creations remix bazaar (api/_lib/remix-royalty.js +
+ * api/_lib/remix-settlement.js). Every non-paying outcome is reported with an
+ * honest reason (never a fake "pending"): no such parent, the parent has no
+ * royalty wallet, the split falls below the dust floor, the platform payout
+ * wallet isn't configured, the remix crosses networks, or this specific mint
+ * call collected no fee to split (an OAuth-bypassed call, or devnet — the
+ * payout wallet only holds real mainnet funds).
+ *
+ * @param {object} p
+ * @param {Function} p.sql tagged-template SQL client (injectable for tests)
+ * @param {string} p.parentMint the asset this mint derives from
+ * @param {string} p.network this mint's network — must match the parent's
+ * @param {bigint} p.feeAtomics the mint fee actually collected for THIS call
+ * @returns {Promise<object>} settlement summary — always defined, `paid` tells the story
+ */
+export async function settleTokenizeRemixRoyalty({ sql: sqlClient, parentMint, network, feeAtomics }) {
+ const fee = typeof feeAtomics === 'bigint' ? feeAtomics : BigInt(feeAtomics || 0);
+
+ if (network !== 'mainnet') {
+ return { paid: false, reason: 'devnet_not_settled', parent_mint: parentMint };
+ }
+ if (fee <= 0n) {
+ return { paid: false, reason: 'no_fee_collected', parent_mint: parentMint };
+ }
+
+ const [parent] = await sqlClient`
+ select mint, royalty_bps, royalty_recipient, owner_wallet
+ from tokenized_3d_assets
+ where mint = ${parentMint} and network = ${network} and status = 'minted'
+ limit 1
+ `;
+ if (!parent) {
+ return { paid: false, reason: 'parent_not_found', parent_mint: parentMint };
+ }
+
+ const creatorWallet = parent.royalty_recipient || parent.owner_wallet;
+ const split = computeRemixSplit({ priceAtomics: fee, royaltyBps: parent.royalty_bps });
+ const summary = {
+ parent_mint: parentMint,
+ royalty_bps: split.royaltyBps,
+ requested_bps: split.requestedBps,
+ capped: split.capped,
+ dust: split.dust,
+ creator_usd: split.creatorUsd,
+ platform_usd: split.platformUsd,
+ creator_atomics: split.creatorAtomics.toString(),
+ platform_atomics: split.platformAtomics.toString(),
+ };
+
+ if (!creatorWallet) {
+ return { ...summary, paid: false, reason: 'no_creator_wallet' };
+ }
+ if (split.creatorAtomics <= 0n) {
+ return { ...summary, paid: false, reason: split.dust ? 'below_dust_floor' : 'zero_royalty' };
+ }
+ const fromWallet = resolvePayoutKeyBase58();
+ if (!fromWallet) {
+ return { ...summary, paid: false, reason: 'payout_unconfigured' };
+ }
+
+ try {
+ const sig = await transferSolanaUSDC({
+ fromWallet,
+ toAddress: creatorWallet,
+ amount: split.creatorAtomics,
+ mint: SOLANA_USDC_MINT,
+ });
+ return {
+ ...summary,
+ paid: true,
+ creator_wallet: creatorWallet,
+ creator_tx: sig,
+ explorer_tx_url: explorerTxUrl(sig, network),
+ settled_at: new Date().toISOString(),
+ };
+ } catch (err) {
+ return { ...summary, paid: false, reason: 'royalty_transfer_failed', error: err?.message || 'transfer failed' };
+ }
+}
+
+function formatMintResult(
+ row,
+ { idempotent, capped, requestedBps, royaltyBps, metadataIpfs = null, provenanceLedger, remixRoyalty },
+) {
return {
status: 'minted',
idempotent: Boolean(idempotent),
@@ -527,6 +699,12 @@ function formatMintResult(row, { idempotent, capped, requestedBps, royaltyBps, m
viewer_url: row.viewer_url,
metadata_uri: row.metadata_uri,
metadata_ipfs: metadataIpfs,
+ // Signed agent_actions-ledger provenance for this mint (Prompt 08, task 1)
+ // — null when the source avatar has no provisioned agent to sign as.
+ provenance_ledger: provenanceLedger ?? row.provenance_ledger ?? null,
+ // Real remix-royalty settlement out of this mint's fee (Prompt 08, task 4)
+ // — null when this mint has no parent_mint (not a remix).
+ remix_royalty: remixRoyalty ?? row.remix_royalty ?? null,
royalty: {
basis_points: row.royalty_bps ?? royaltyBps,
percent: (row.royalty_bps ?? royaltyBps) / 100,
@@ -565,7 +743,8 @@ export async function readTokenized3dAsset({ mint, network: preferredNetwork })
// truth for provenance, and it tells us which network to read.
const [record] = await sql`
select mint, network, owner_wallet, name, glb_url, image_url, viewer_url,
- metadata_uri, royalty_bps, royalty_recipient, provenance, tx_signature, created_at
+ metadata_uri, royalty_bps, royalty_recipient, provenance, tx_signature, created_at,
+ provenance_ledger, remix_royalty
from tokenized_3d_assets
where mint = ${mint} and status = 'minted'
limit 1
@@ -641,6 +820,10 @@ export async function readTokenized3dAsset({ mint, network: preferredNetwork })
media_kind: '3d/gltf-binary',
},
provenance,
+ // The signed agent_actions-ledger record for this mint (if the source
+ // avatar had a provisioned agent to sign as) — independently verifiable
+ // via query_action/list_agent_actions, alongside the metadata provenance.
+ provenance_ledger: record?.provenance_ledger || null,
royalty: {
// The enforced on-chain terms are authoritative; fall back to the record.
basis_points: onchainRoyalty?.basis_points ?? record?.royalty_bps ?? null,
@@ -653,6 +836,9 @@ export async function readTokenized3dAsset({ mint, network: preferredNetwork })
enforced_onchain: Boolean(onchainRoyalty),
creators: onchainRoyalty?.creators || null,
},
+ // The real remix-royalty settlement this mint routed to its parent's
+ // creator (only present when this mint named a parent_mint).
+ remix_royalty: record?.remix_royalty || null,
metadata_uri: metadataUri,
minted_through_threews: Boolean(record),
tx_signature: record?.tx_signature || null,
diff --git a/api/_lib/tokenized-launches.js b/api/_lib/tokenized-launches.js
new file mode 100644
index 000000000..1ea6770f4
--- /dev/null
+++ b/api/_lib/tokenized-launches.js
@@ -0,0 +1,92 @@
+// The three.ws tokenized-3D launch directory — every generated GLB minted as
+// a Metaplex Core NFT through this platform (a `tokenized_3d_assets` row),
+// optionally joined to the agent whose avatar it came from. This is the NFT
+// analogue of api/_lib/pump-agent-launches.js (which lists coins launched
+// through three.ws): same shape of feed, same "our own launch directory, not
+// a chain-wide scan" scope, so /launches-style surfaces and an agent profile
+// can list a creator's minted 3D assets the same way they already list their
+// launched coins.
+//
+// Two doors share this one query, mirroring the pump-launches pattern:
+// - GET /api/v1/tokenized/launches — the free, versioned /api/v1 catalog surface.
+// - (future) an agent-profile "minted 3D assets" card, same query + agent_id filter.
+
+import { sql } from './db.js';
+
+/**
+ * Query the three.ws tokenized-3D launch directory.
+ *
+ * @param {object} o
+ * @param {string} [o.network] 'mainnet' | 'devnet' (default 'mainnet')
+ * @param {string|null} [o.agentId] restrict to one creating agent (uuid) — resolved
+ * via the minted asset's source avatar's provisioned agent, same linkage
+ * avatars.js/pump-agent-launches.js already use.
+ * @param {number} [o.offset]
+ * @param {number} [o.limit]
+ * @returns {Promise<{ launches: object[], has_more: boolean }>}
+ */
+export async function queryTokenizedLaunches({
+ network = 'mainnet',
+ agentId = null,
+ offset = 0,
+ limit = 24,
+} = {}) {
+ // Over-fetch by one row to compute has_more without a count(*) round trip —
+ // same technique queryAgentLaunches uses.
+ const rows = agentId
+ ? await sql`
+ select t.mint, t.network, t.name, t.glb_url, t.image_url, t.viewer_url,
+ t.royalty_bps, t.royalty_recipient, t.parent_mint, t.provenance,
+ t.remix_royalty, t.created_at,
+ ai.id as agent_id, ai.name as agent_name,
+ ai.meta->>'solana_address' as agent_solana_address
+ from tokenized_3d_assets t
+ left join avatars a on a.id = t.source_avatar_id and a.deleted_at is null
+ left join agent_identities ai on ai.avatar_id = a.id and ai.deleted_at is null
+ where t.status = 'minted' and t.network = ${network} and ai.id = ${agentId}
+ order by t.created_at desc
+ limit ${limit + 1} offset ${offset}
+ `
+ : await sql`
+ select t.mint, t.network, t.name, t.glb_url, t.image_url, t.viewer_url,
+ t.royalty_bps, t.royalty_recipient, t.parent_mint, t.provenance,
+ t.remix_royalty, t.created_at,
+ ai.id as agent_id, ai.name as agent_name,
+ ai.meta->>'solana_address' as agent_solana_address
+ from tokenized_3d_assets t
+ left join avatars a on a.id = t.source_avatar_id and a.deleted_at is null
+ left join agent_identities ai on ai.avatar_id = a.id and ai.deleted_at is null
+ where t.status = 'minted' and t.network = ${network}
+ order by t.created_at desc
+ limit ${limit + 1} offset ${offset}
+ `;
+
+ const hasMore = rows.length > limit;
+ const launches = rows.slice(0, limit).map((r) => ({
+ mint: r.mint,
+ network: r.network,
+ name: r.name,
+ glb_url: r.glb_url,
+ image_url: r.image_url,
+ viewer_url: r.viewer_url,
+ royalty: {
+ basis_points: r.royalty_bps,
+ percent: r.royalty_bps != null ? r.royalty_bps / 100 : null,
+ recipient: r.royalty_recipient,
+ },
+ parent_mint: r.parent_mint,
+ remix_royalty: r.remix_royalty || null,
+ provenance: r.provenance || null,
+ created_at: r.created_at,
+ agent: r.agent_id
+ ? {
+ id: r.agent_id,
+ name: r.agent_name,
+ url: `/agents/${r.agent_id}`,
+ solana_address: r.agent_solana_address || null,
+ }
+ : null,
+ }));
+
+ return { launches, has_more: hasMore };
+}
diff --git a/api/_mcp/tools/tokenize.js b/api/_mcp/tools/tokenize.js
index eae82f5e6..881b6782d 100644
--- a/api/_mcp/tools/tokenize.js
+++ b/api/_mcp/tools/tokenize.js
@@ -1,4 +1,5 @@
import { mintTokenized3dAsset, readTokenized3dAsset, TOKENIZE_3D_ROYALTY_CAP_BPS } from '../../_lib/tokenize-3d.js';
+import { priceFor } from '../../_lib/pump-pricing.js';
// A handled boundary error carries a status + code; surface it as a clean MCP
// tool error (isError) rather than letting an unexpected 500 bubble.
@@ -29,12 +30,16 @@ export const toolDefs = [
'Mint a generated or owned GLB as a Metaplex Core NFT on Solana whose media is a ' +
'LIVE, interactive 3D viewer (the rigged glTF model under animation_url — not a static ' +
'image). Bakes provenance (creator, prompt, generation model, parent lineage, timestamp) ' +
- 'into the metadata and enforces capped creator royalties on secondary sales. Supply an ' +
- 'owned avatar_id or a glb_url, and a recipient (owner_wallet, or your OAuth-linked Solana ' +
- 'wallet). Devnet by default; pass network="mainnet" for a real mainnet mint. Idempotent — ' +
- `a repeat call for the same asset returns the same mint. Royalty is capped at ` +
- `${TOKENIZE_3D_ROYALTY_CAP_BPS / 100}%. Returns the mint address, explorer + viewer links, ` +
- 'and royalty terms. Priced per call via x402 (USDC); an OAuth bearer token bypasses payment.',
+ 'into the metadata AND appends a signed, independently-verifiable record to the ' +
+ 'agent_actions provenance ledger; enforces capped creator royalties on secondary sales. ' +
+ 'Supply an owned avatar_id or a glb_url, and a recipient (owner_wallet, or your OAuth-linked ' +
+ 'Solana wallet). Devnet by default; pass network="mainnet" for a real mainnet mint. Idempotent ' +
+ '— a repeat call for the same asset returns the same mint. Royalty is capped at ' +
+ `${TOKENIZE_3D_ROYALTY_CAP_BPS / 100}%. Naming parent_mint (a remix/derivative on mainnet) ` +
+ "routes the parent creator's royalty slice out of THIS mint's fee as a real on-chain USDC " +
+ 'transfer. Returns the mint address, explorer + viewer links, royalty terms, the provenance ' +
+ 'ledger reference, and (for a remix) the royalty settlement. Priced per call via x402 (USDC); ' +
+ 'an OAuth bearer token bypasses payment.',
inputSchema: {
type: 'object',
properties: {
@@ -88,6 +93,14 @@ export const toolDefs = [
},
async handler(args, auth) {
try {
+ // The remix-royalty split (task 4) must only ever split a fee that was
+ // ACTUALLY collected for this exact call — a genuine per-call x402
+ // settlement (auth.x402Paid), never a subscription window or an OAuth
+ // bypass (both real access, but no fresh fee here to split).
+ const mintFeeAtomicsCollected =
+ auth?.source === 'x402' && auth?.x402Paid
+ ? BigInt(Math.round((priceFor('mint_3d_asset')?.amount_usdc || 0) * 1_000_000))
+ : 0n;
const result = await mintTokenized3dAsset({
avatarId: args.avatar_id,
glbUrl: args.glb_url,
@@ -103,6 +116,7 @@ export const toolDefs = [
generationModel: args.generation_model,
generationProvider: args.generation_provider,
idempotencyKey: args.idempotency_key,
+ mintFeeAtomicsCollected,
});
const text =
result.status === 'minted'
@@ -112,7 +126,15 @@ export const toolDefs = [
(result.explorer_tx_url ? `Tx: ${result.explorer_tx_url}\n` : '') +
`Viewer: ${result.viewer_url}\n` +
`Royalty: ${result.royalty.percent}% (cap ${result.royalty.cap_basis_points / 100}%)` +
- (result.royalty.capped ? ` — requested ${result.royalty.requested_basis_points / 100}%, clamped` : '')
+ (result.royalty.capped ? ` — requested ${result.royalty.requested_basis_points / 100}%, clamped` : '') +
+ (result.provenance_ledger
+ ? `\nProvenance: ledger action #${result.provenance_ledger.action_id} (${result.provenance_ledger.signed ? 'signed' : 'unsigned'})`
+ : '') +
+ (result.remix_royalty
+ ? result.remix_royalty.paid
+ ? `\nRemix royalty: ${result.remix_royalty.creator_usd} USDC paid to the source creator (${result.remix_royalty.creator_tx})`
+ : `\nRemix royalty: not paid (${result.remix_royalty.reason})`
+ : '')
: `Mint in progress for this asset — read it back with get_3d_asset_onchain once it confirms.`;
return { content: [{ type: 'text', text }], structuredContent: result };
} catch (err) {
diff --git a/api/avatars/from-forge.js b/api/avatars/from-forge.js
index 7ab4660fb..eb6646756 100644
--- a/api/avatars/from-forge.js
+++ b/api/avatars/from-forge.js
@@ -158,9 +158,21 @@ export default wrap(async (req, res) => {
},
});
- // First-class like a normal upload: provision the agent + custodial wallet.
+ // First-class like a normal upload: provision the agent + custodial wallet,
+ // and record signed generation provenance on the agent_actions ledger once
+ // it resolves (creator, prompt, generation model, timestamp).
queueMicrotask(() =>
- provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),
+ provisionAvatarAgent({
+ userId: auth.userId,
+ avatarId: avatar.id,
+ avatarName: avatar.name,
+ provenance: {
+ prompt: sourcePrompt,
+ generationModel: 'chat-forge-avatar',
+ generationProvider: null,
+ parentAvatarId: null,
+ },
+ }),
);
// Auto-rig if the forged mesh arrived static (e.g. a mesh_forge save) so the
diff --git a/api/avatars/index.js b/api/avatars/index.js
index 7f52f8ec7..d07d468ec 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -143,7 +143,17 @@ async function handleCreate(req, res) {
// Fire-and-forget — 201 returns regardless.
if (!body.parent_avatar_id) {
queueMicrotask(() =>
- provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),
+ provisionAvatarAgent({
+ userId: auth.userId,
+ avatarId: avatar.id,
+ avatarName: avatar.name,
+ provenance: {
+ prompt: body.source_meta?.source_prompt || body.source_meta?.prompt || null,
+ generationModel: body.source_meta?.generator || body.source_meta?.model || null,
+ generationProvider: body.source_meta?.provider || null,
+ parentAvatarId: null,
+ },
+ }),
);
// Auto-rig any static upload/import so the agent's avatar can animate, the
diff --git a/api/diorama.js b/api/diorama.js
index 3f15122dd..91d08a994 100644
--- a/api/diorama.js
+++ b/api/diorama.js
@@ -10,6 +10,17 @@
* POST /api/diorama { action:'save', diorama, clientKey? } → { id, url }
* Persists a fully-forged world so it gets a permalink + gallery slot.
*
+ * POST /api/diorama { action:'export', diorama } → { glbUrl, sceneStudioUrl, … }
+ * Merges an already-forged diorama's objects + ground + lights into ONE
+ * GLB (api/_lib/scene-graph-compose.js) and uploads it — a single file
+ * with named, selectable nodes that opens cleanly in Scene Studio
+ * (/scene) or any glTF viewer. 503 when object storage isn't configured.
+ *
+ * POST /api/diorama { action:'build', prompt } → { diorama, glbUrl?, … }
+ * Headless one-shot: compose the plan, forge every object on the free
+ * lane, then export the merged GLB — all server-side, for callers with
+ * no browser to drive the progressive client flow (MCP tools, agents).
+ *
* GET /api/diorama?id=<uuid> → { diorama }
* GET /api/diorama?list=recent|featured&limit=<n> → { dioramas:[card] }
*
@@ -21,6 +32,12 @@ import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js'
import { limits, clientIp } from './_lib/rate-limit.js';
import { llmComplete, llmConfigured } from './_lib/llm.js';
import { saveDiorama, getDiorama, listDioramas, bumpViews, dioramaStoreEnabled } from './_lib/diorama-store.js';
+import {
+ exportDioramaGlb,
+ dioramaExportStoreEnabled,
+ composePlanFromPrompt,
+ forgeDioramaObjects,
+} from './_lib/diorama-build.js';
import {
normalizeDiorama,
MIN_OBJECTS,
@@ -63,7 +80,12 @@ export default wrap(async (req, res) => {
if (body.action === 'compose') return handleCompose(req, res, body);
if (body.action === 'save') return handleSave(req, res, body);
- return json(res, 400, { error: 'unknown_action', message: 'action must be "compose" or "save".' });
+ if (body.action === 'export') return handleExport(req, res, body);
+ if (body.action === 'build') return handleBuild(req, res, body);
+ return json(res, 400, {
+ error: 'unknown_action',
+ message: 'action must be "compose", "save", "export", or "build".',
+ });
});
async function handleGet(req, res) {
@@ -201,6 +223,124 @@ async function handleSave(req, res, body) {
});
}
+// Merge an already-forged diorama into one exportable GLB — the "Export +
+// editability" leg of compositional scene generation: a single file with
+// every object as a named, selectable node, ready for Scene Studio or any
+// other glTF-aware app. Degrades cleanly (designed 503) when object storage
+// isn't configured, and never fails whole-hog on a partial forge: whatever
+// objects are 'ready' get merged, the rest come back in `skipped`.
+async function handleExport(req, res, body) {
+ if (!dioramaExportStoreEnabled()) {
+ return json(res, 503, {
+ error: 'export_unavailable',
+ message: 'Scene export is not configured on this deployment.',
+ });
+ }
+ const exportRl = await limits.dioramaExportIp(clientIp(req));
+ if (!exportRl.success) {
+ return rateLimited(res, exportRl, 'Exporting too fast. Try again in a moment.');
+ }
+
+ const { ok, diorama, errors } = normalizeDiorama(body.diorama);
+ if (!ok) {
+ return json(res, 400, { error: 'invalid_diorama', message: errors.join(', ') });
+ }
+
+ let result;
+ try {
+ result = await exportDioramaGlb(diorama);
+ } catch (err) {
+ if (err?.code === 'nothing_to_export') {
+ return json(res, 400, { error: 'nothing_to_export', message: err.message });
+ }
+ console.error('[diorama] export failed:', err?.message);
+ return json(res, 502, {
+ error: 'export_failed',
+ message: 'Could not merge this world into a scene. Try again in a moment.',
+ });
+ }
+ // dioramaExportStoreEnabled() already gated this, but exportDioramaGlb also
+ // self-checks storage config — keep the belt-and-suspenders 503 in case the
+ // two checks ever diverge (e.g. a future env alias one reads and the other doesn't).
+ if (!result) {
+ return json(res, 503, {
+ error: 'export_unavailable',
+ message: 'Scene export is not configured on this deployment.',
+ });
+ }
+
+ return json(res, 200, {
+ glbUrl: result.glbUrl,
+ sceneStudioUrl: `${SITE}/scene?model=${encodeURIComponent(result.glbUrl)}&name=${encodeURIComponent(diorama.title || 'Diorama')}`,
+ title: diorama.title,
+ objectCount: diorama.objects.length,
+ exportedCount: result.exportedCount,
+ skipped: result.skipped,
+ });
+}
+
+// Headless one-shot world build: compose → forge every object → export — the
+// full pipeline in a single call, for callers with no browser to drive the
+// progressive client flow (MCP tools, autonomous agents). Real LLM inference
+// plus N real free-lane forges, so it carries compose's fail-closed rate-limit
+// posture. A forge failure on some objects never fails the whole build — the
+// diorama returned reflects exactly what forged, and `skipped` names the rest.
+async function handleBuild(req, res, body) {
+ const prompt = String(body.prompt ?? '').slice(0, MAX_PROMPT_LEN).trim();
+ if (prompt.length < 3) {
+ return json(res, 400, { error: 'prompt_required', message: 'Describe your world in a sentence.' });
+ }
+
+ const ip = clientIp(req);
+ const rl = await limits.dioramaBuildIp(ip);
+ if (!rl.success) {
+ return rateLimited(res, rl, 'World builder limit reached. Try again shortly.');
+ }
+ const globalRl = await limits.dioramaBuildGlobal();
+ if (!globalRl.success) {
+ return rateLimited(res, globalRl, 'The world builder is at capacity. Try again shortly.');
+ }
+
+ let plan;
+ try {
+ plan = await composePlanFromPrompt(prompt);
+ } catch (err) {
+ const status = err?.code === 'composer_unavailable' ? 503 : err?.code === 'prompt_required' ? 400 : 502;
+ return json(res, status, { error: err?.code || 'compose_failed', message: err.message });
+ }
+
+ const forged = await forgeDioramaObjects(plan, {
+ clientKey: typeof body.clientKey === 'string' ? body.clientKey.slice(0, 128) : undefined,
+ });
+ const readyCount = forged.objects.filter((o) => o.status === 'ready').length;
+
+ const response = {
+ diorama: forged,
+ objectCount: forged.objects.length,
+ readyCount,
+ viewerUrl: `${SITE}/diorama`,
+ };
+
+ if (readyCount > 0) {
+ try {
+ const exported = await exportDioramaGlb(forged);
+ if (exported) {
+ response.glbUrl = exported.glbUrl;
+ response.sceneStudioUrl = `${SITE}/scene?model=${encodeURIComponent(exported.glbUrl)}&name=${encodeURIComponent(forged.title || 'Diorama')}`;
+ response.exportedCount = exported.exportedCount;
+ response.skipped = exported.skipped;
+ } else {
+ response.exportNote = 'Scene export is not configured on this deployment; the diorama objects still forged individually.';
+ }
+ } catch (err) {
+ console.error('[diorama] build export step failed:', err?.message);
+ response.exportNote = 'The world forged but could not be merged into a single scene file. Try action:"export" again.';
+ }
+ }
+
+ return json(res, 200, response);
+}
+
// Extract the first balanced top-level JSON object from a model response that
// may be wrapped in prose or a ```json fence. Returns the parsed object or null.
function parseJsonObject(text) {
diff --git a/api/scene-glb-upload.js b/api/scene-glb-upload.js
new file mode 100644
index 000000000..2c2165285
--- /dev/null
+++ b/api/scene-glb-upload.js
@@ -0,0 +1,109 @@
+/**
+ * /api/scene-glb-upload — direct-to-storage upload for Scene Studio's
+ * "Share / Embed" action.
+ *
+ * POST /api/scene-glb-upload { content_type, size_bytes }
+ * → 200 { storage_key, upload_url, public_url, method, headers, expires_in }
+ *
+ * Scene Studio (/scene) composes a scene from any number of imported models,
+ * so the exported GLB can run much larger than a single Forge reference
+ * image — hence its own upload route (and its own, larger size cap) rather
+ * than reusing /api/forge-upload's image-only allowlist. The browser PUTs the
+ * exported GLB bytes straight to `upload_url` (a short-lived R2 presigned
+ * URL), then feeds `public_url` into the existing "Embed this model" panel
+ * (src/forge-embed-panel.js) to produce an iframe / web-component / <agent-3d>
+ * snippet — the same flow Forge results already use. Keeping the bytes off
+ * this function avoids proxying a multi-MB scene export through a serverless
+ * handler.
+ *
+ * Auth-free, matching the rest of the anonymous creation surface: rate-limited
+ * by client IP. When object storage isn't configured the endpoint returns a
+ * clean 503 and the Share panel explains the deployment can't host the export
+ * (the user can still use File ▸ Export in the editor to save locally).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { presignUpload, publicUrl } from './_lib/r2.js';
+
+// Accepted export types → file extension for the storage key. Binary glTF is
+// the only format Scene Studio's Share action produces; the vendored editor's
+// File ▸ Export submenu still covers OBJ/PLY/STL/DRC for local-only exports.
+const CONTENT_TYPE_EXT = Object.freeze({
+ 'model/gltf-binary': 'glb',
+});
+
+// A composed scene (multiple imported avatars/props + baked textures) can run
+// well past a single reference image — cap comfortably above what the editor
+// can hold in memory client-side without choking a low-end device first.
+const MAX_GLB_BYTES = 200 * 1024 * 1024;
+
+function storageConfigured() {
+ return Boolean(
+ process.env.S3_ENDPOINT &&
+ process.env.S3_BUCKET &&
+ process.env.S3_PUBLIC_DOMAIN &&
+ process.env.S3_ACCESS_KEY_ID &&
+ process.env.S3_SECRET_ACCESS_KEY,
+ );
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ if (!storageConfigured()) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Scene sharing is not configured on this deployment (object storage missing). ' +
+ 'Use File ▸ Export in the editor to save the GLB locally instead.',
+ });
+ }
+
+ const ip = clientIp(req);
+ const rl = await limits.upload(`scene-share:${ip}`);
+ if (!rl.success) return rateLimited(res, rl, 'Upload limit reached. Try again shortly.');
+
+ const body = await readJson(req, 2_000).catch(() => null);
+
+ const contentType =
+ typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';
+ const ext = CONTENT_TYPE_EXT[contentType];
+ if (!ext) {
+ return json(res, 400, {
+ error: 'invalid_content_type',
+ message: 'content_type must be model/gltf-binary.',
+ });
+ }
+
+ const size = Number(body?.size_bytes);
+ if (!Number.isFinite(size) || size <= 0 || size > MAX_GLB_BYTES) {
+ return json(res, 400, {
+ error: 'invalid_size',
+ message: `size_bytes must be between 1 and ${MAX_GLB_BYTES} bytes.`,
+ });
+ }
+
+ const key = `scene/shares/${randomUUID()}.${ext}`;
+
+ let uploadUrl;
+ try {
+ uploadUrl = await presignUpload({ key, contentType });
+ } catch (err) {
+ return json(res, 502, {
+ error: 'presign_failed',
+ message: err?.message || 'Could not create an upload URL.',
+ });
+ }
+
+ return json(res, 200, {
+ storage_key: key,
+ upload_url: uploadUrl,
+ public_url: publicUrl(key),
+ method: 'PUT',
+ headers: { 'content-type': contentType },
+ expires_in: 300,
+ });
+});
diff --git a/api/v1/_catalog.js b/api/v1/_catalog.js
index c3d4a2308..8487ad9c3 100644
--- a/api/v1/_catalog.js
+++ b/api/v1/_catalog.js
@@ -237,6 +237,23 @@ export const CATALOG = [
min_tier: 'string — "prime" | "strong" | "lean" | "watch" | "avoid", oracle conviction floor (optional)',
},
},
+ {
+ id: 'v1.tokenized.launches',
+ method: 'GET',
+ path: '/api/v1/tokenized/launches',
+ auth: 'public',
+ summary:
+ 'Free, paginated feed of every generated 3D asset minted as a Metaplex Core NFT THROUGH ' +
+ 'three.ws — the NFT analogue of GET /api/v1/pump/launches. Each entry carries baked ' +
+ 'provenance, royalty terms, remix lineage (parent_mint), and — for a remix — the real ' +
+ 'royalty settlement routed to the source creator. No key; 60/min per IP.',
+ params: {
+ limit: 'number 1–100 (default 24)',
+ offset: 'number (default 0)',
+ network: 'string — "mainnet" | "devnet" (default "mainnet")',
+ agent_id: 'string — uuid, restrict to one creating agent (optional)',
+ },
+ },
{
id: 'v1.pump.whales',
method: 'GET',
diff --git a/api/v1/tokenized/launches.js b/api/v1/tokenized/launches.js
new file mode 100644
index 000000000..88d879a18
--- /dev/null
+++ b/api/v1/tokenized/launches.js
@@ -0,0 +1,52 @@
+// GET /api/v1/tokenized/launches?limit=24&offset=0&network=mainnet&agent_id=<uuid>
+//
+// Free, public, paginated feed of every generated 3D asset minted as a
+// Metaplex Core NFT THROUGH three.ws (a `tokenized_3d_assets` row) — the NFT
+// analogue of GET /api/v1/pump/launches (coins launched through three.ws).
+// Registered under the versioned, cataloged /api/v1 surface so agents can
+// discover three.ws's own tokenized-3D launch history via GET /api/v1.
+//
+// The query lives in api/_lib/tokenized-launches.js `queryTokenizedLaunches`
+// so a future agent-profile "minted 3D assets" card can share it, exactly the
+// way the pump-launches directory is shared today.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { rateLimited } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
+import { queryTokenizedLaunches } from '../../_lib/tokenized-launches.js';
+
+const MAX_LIMIT = 100;
+
+export default defineEndpoint({
+ name: 'v1.tokenized.launches',
+ method: 'GET',
+ auth: 'public',
+ handler: async ({ req, res, query }) => {
+ // Same dedicated-shared budget as the sibling free /api/v1 reads — this
+ // hits the database on a cache miss, so it caps a scripted enumeration flood.
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'tokenized launches is capped at 60 requests/min per IP');
+
+ const rawLimit = Number(query.limit);
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 24));
+ const rawOffset = Number(query.offset);
+ const offset = Math.max(0, Number.isFinite(rawOffset) ? Math.floor(rawOffset) : 0);
+ const network = query.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ const agentId = typeof query.agent_id === 'string' ? query.agent_id.trim() : '';
+ if (agentId && !isUuid(agentId)) fail(400, 'validation_error', 'agent_id must be a uuid');
+
+ const { launches, has_more } = await queryTokenizedLaunches({
+ network,
+ agentId: agentId || null,
+ offset,
+ limit,
+ });
+
+ // Fresh mints land continuously; a short CDN window keeps polling agents
+ // current without hammering the database.
+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=15');
+ return { launches, has_more, offset, limit, network };
+ },
+});
diff --git a/data/_generated/fact-check-benchmark.json b/data/_generated/fact-check-benchmark.json
new file mode 100644
index 000000000..c264bb7d0
--- /dev/null
+++ b/data/_generated/fact-check-benchmark.json
@@ -0,0 +1,64 @@
+{
+ "generated_at": "2026-07-08T01:46:16.570Z",
+ "endpoint": "in-process:api/x402/fact-check.js#_checkClaim (real chain, no HTTP/x402 payment layer — see prompts/x402-catalog/PROGRESS.md for why)",
+ "fixture_version": "1.0.0",
+ "claim_count": 40,
+ "total": 40,
+ "correct": 8,
+ "errors": 3,
+ "accuracy_pct": 20,
+ "by_class": {
+ "supported": {
+ "total": 10,
+ "correct": 0,
+ "accuracy_pct": 0
+ },
+ "contradicted": {
+ "total": 10,
+ "correct": 0,
+ "accuracy_pct": 0
+ },
+ "mixed": {
+ "total": 10,
+ "correct": 8,
+ "accuracy_pct": 80
+ },
+ "insufficient": {
+ "total": 10,
+ "correct": 0,
+ "accuracy_pct": 0
+ }
+ },
+ "by_difficulty": {
+ "easy": {
+ "total": 13,
+ "correct": 0,
+ "accuracy_pct": 0
+ },
+ "medium": {
+ "total": 20,
+ "correct": 5,
+ "accuracy_pct": 25
+ },
+ "hard": {
+ "total": 7,
+ "correct": 3,
+ "accuracy_pct": 42.9
+ }
+ },
+ "confusion": {
+ "supported": {
+ "mixed": 10
+ },
+ "contradicted": {
+ "mixed": 9
+ },
+ "mixed": {
+ "mixed": 8,
+ "contradicted": 1
+ },
+ "insufficient": {
+ "mixed": 9
+ }
+ }
+}
diff --git a/data/changelog.json b/data/changelog.json
index 68a95c55d..3b09aefc9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,26 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-08",
+ "title": "Fact Check's accuracy benchmark has a real published score, and the search+AI chain got more reliable",
+ "summary": "The 40-claim fact-check accuracy benchmark has now actually been run against the real search-and-LLM chain, and /fact-check shows the genuine result instead of the \"not yet run\" placeholder. Running it for real surfaced and fixed two chain bugs along the way: a request-formatting bug was silently rejecting every fact-check call on the Groq lane, and the search step had no fallback beyond a narrow instant-answer API, so most claims returned zero sources. Both are fixed — search now also checks Wikipedia's full-text index, a free source that needs no API key — and the published score will keep improving as the platform's search coverage does. The benchmark, its scoring code, and every claim in the suite stay public for anyone to check.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/fact-check"
+ },
+ {
+ "date": "2026-07-08",
+ "title": "Vanity addresses now go up to 5 characters, and the shelf restocks itself",
+ "summary": "GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/vanity"
+ },
{
"date": "2026-07-08",
"title": "Crypto API now has a home page and a real OpenAPI spec",
diff --git a/docs/pump-launcher.md b/docs/pump-launcher.md
index 0db36c41a..bd01b1b55 100644
--- a/docs/pump-launcher.md
+++ b/docs/pump-launcher.md
@@ -60,7 +60,7 @@ or `imageUrl`.
| `description` | — | Coin description. Used only on the `imageUrl` (we-pin) path. |
| `twitter` / `telegram` / `website` | — | Socials embedded in the pinned metadata (`imageUrl` path). |
| `creator` | — | Solana pubkey (base58) to receive pump.fun creator rewards. Defaults to the launcher. |
-| `vanityPrefix` / `vanitySuffix` | — | Base58 affix (≤5 chars each) to brand the mint address. Longer = exponentially slower grind. |
+| `vanityPrefix` / `vanitySuffix` | — | Base58 affix (≤5 chars each) to brand the mint address. When a matching address is already sitting in the [pre-ground inventory](vanity.md#tier-3--premium-inventory), it's claimed and used instantly instead of grinding — same $5 flat price either way. Longer patterns with no inventory match grind live and get exponentially slower. |
| `vanityIgnoreCase` | — | Match the vanity affixes case-insensitively (faster). Default `false`. |
### Example request
@@ -105,10 +105,16 @@ code (the `curl` above shows the shape, not the payment headers).
"vanity_prefix": "HEL",
"vanity_suffix": null,
"vanity_iterations": 4821,
- "vanity_duration_ms": 190
+ "vanity_duration_ms": 190,
+ "vanity_source": "ground"
}
```
+`vanity_source` is `"inventory"` when the mint was served instantly from the
+pre-ground warehouse (no grind wait, `vanity_iterations`/`vanity_duration_ms`
+both `0`), `"ground"` when mined fresh for this launch, or `null` when no
+`vanityPrefix`/`vanitySuffix` was requested.
+
`mint`, `signature`, `metadataUri`, and `pumpfun_url` are guaranteed on success.
## Networks & settlement
diff --git a/docs/vanity.md b/docs/vanity.md
index c2422afd8..a58613b0f 100644
--- a/docs/vanity.md
+++ b/docs/vanity.md
@@ -7,15 +7,22 @@ server grinds (or delivers from stock) a brand-new keypair that matches.
| Endpoint | What it is | Chars | Price | Pick it when |
| --- | --- | --- | --- | --- |
-| [`/api/x402/vanity`](#tier-1--live-grinder) | Live grind, fresh keypair per request | ≤3 | $0.01–$0.50 | You want a custom address **now**, cheaply. |
+| [`/api/x402/vanity`](#tier-1--live-grinder) | Live grind, or **instant delivery** when a match is already in stock | ≤3 (grind or instant) · 4–5 (instant only) | $0.01–$0.50 (≤3) · $2.50–$10 (4–5) | You want a custom address **now** and don't care whether it was just ground or pulled from the shelf. |
| [`/api/x402/vanity-verifiable`](#tier-2--provably-fair-grinder) | Live grind **+ signed proof** it was ground fresh | ≤3 | $0.02–$0.40 | You need to **prove** no copy was kept (commit–reveal receipt). |
-| [`/api/x402/vanity-premium`](#tier-3--premium-inventory) | Buy a **pre-ground** long address from stock | 4–5+ | $1–$50 | You want a rarer prefix too slow to grind on demand. |
+| [`/api/x402/vanity-premium`](#tier-3--premium-inventory) | Browse and buy a **specific pre-ground** long address from stock | 4–5+ | $1–$50 | You want to pick an exact rarer prefix from the catalog rather than "any match". |
All three are **keyless**: no API key, no signup. The Solana rail is the platform
default; Base mainnet is offered when a facilitator can settle it. The live 402
challenge always quotes the exact price for the pattern you asked for — read it,
don't hardcode.
+Tier 1 and tier 3 **share one warehouse** — the `vanity_inventory` table,
+pre-ground on batch spot CPU (`workers/vanity-grinder`) and auto-replenished
+when stock runs low (`api/cron/vanity-inventory-replenish`, hourly). Tier 1 is
+"give me anything that matches, right now"; tier 3 is "let me pick this exact
+address from the catalog." [Pump Launcher](pump-launcher.md) draws from the
+same warehouse for instant vanity mint addresses.
+
## Which agent uses this, and why us
A **token-launch bot** that wants its mint address to start with the ticker
@@ -38,17 +45,24 @@ once, over TLS, and never stored.
## Tier 1 — live grinder
-`GET /api/x402/vanity?prefix=<base58>&suffix=<base58>` grinds a brand-new Solana
-Ed25519 keypair in a Rust/WASM engine (~25k keypairs/sec) under a 45-second
-budget and returns it. Settlement runs **only after a successful grind**, so an
-exhausted budget (rare) costs nothing and can be retried.
+`GET /api/x402/vanity?prefix=<base58>&suffix=<base58>` first checks whether a
+pre-ground address already matching your pattern is sitting in the premium
+inventory. A hit is claimed atomically and delivered **instantly** — no grind
+wait — at the exact same price as a live grind would have cost. A miss falls
+straight through to grinding a brand-new Solana Ed25519 keypair in a Rust/WASM
+engine (~25k keypairs/sec) under a 45-second budget. Either way the response's
+`source` field says which path served you: `"inventory"` or `"ground"`.
+Settlement runs **only after** a successful instant claim or grind, so a lost
+race or an exhausted budget (rare) costs nothing and can be retried.
### Formats
- **`format=keypair`** (default) — returns the public `address` plus its secret
key in two forms: `secretKeyBase58` (import into Phantom / Solflare) and
- `secretKey` (a 64-byte int array — save as a Solana CLI keypair JSON). Combined
- pattern capped at **3 Base58 chars**.
+ `secretKey` (a 64-byte int array — save as a Solana CLI keypair JSON). Live
+ grinding covers up to **3 Base58 chars**; **4–5 chars are offered too, but
+ served ONLY from inventory** (see [Price ladder](#price-ladder)) — the server
+ never attempts to grind that long live.
- **`format=mnemonic`** — returns a **BIP-39 seed phrase** (`strength=128` → 12
words, default; `strength=256` → 24 words) whose derived key at
`m/44'/501'/0'/0'` (Phantom's default path) lands on the vanity address.
@@ -59,20 +73,27 @@ exhausted budget (rare) costs nothing and can be retried.
Difficulty-tiered by combined prefix+suffix length (USDC, 6 decimals):
-| Combined length | `keypair` | `mnemonic` |
-| --- | --- | --- |
-| 1 char | $0.01 | $0.05 |
-| 2 chars | $0.05 | $0.50 |
-| 3 chars | $0.25 | — (capped at 2) |
-
-Ops can override with `X402_PRICE_VANITY=<atomics>` for the base tier; the live
-402 quotes the exact tier for the requested pattern.
+| Combined length | `keypair` | `mnemonic` | Fulfilled by |
+| --- | --- | --- | --- |
+| 1 char | $0.01 | $0.05 | instant if in stock, else ground |
+| 2 chars | $0.05 | $0.50 | instant if in stock, else ground |
+| 3 chars | $0.25 | — (capped at 2) | instant if in stock, else ground |
+| 4 chars | $2.50 | — (not offered) | **inventory only** |
+| 5 chars | $10.00 | — (not offered) | **inventory only** |
+
+4–5 char patterns are quoted **only when a matching address is actually in
+stock** — request one that isn't and you get a `404 not_in_stock` explaining
+the grindable range instead of a 402 you could never redeem. Check
+`GET /api/x402/vanity-premium?prefix=…` to see what's currently available.
+Ops can override any tier: `X402_PRICE_VANITY_4` / `X402_PRICE_VANITY_5` (USDC
+atomics) for the inventory-only band; the live 402 always quotes the exact
+tier for the requested pattern.
### Inputs
| Param | Notes |
| --- | --- |
-| `prefix` | Base58 chars the address must start with. Combined with `suffix`, ≤3 (keypair) or ≤2 (mnemonic). |
+| `prefix` | Base58 chars the address must start with. Combined with `suffix`, ≤5 (keypair — 4–5 inventory-only) or ≤2 (mnemonic). |
| `suffix` | Base58 chars the address must end with. |
| `ignoreCase` | `1`/`true` matches the pattern case-insensitively (faster, less specific). |
| `format` | `keypair` (default) or `mnemonic`. |
@@ -101,13 +122,17 @@ curl "https://three.ws/api/x402/vanity?prefix=So"
"expectedAttempts": 3364,
"network": "solana",
"explorerUrl": "https://solscan.io/account/SoV3...",
+ "source": "ground", // or "inventory" — instant delivery from stock, same price
"certificate": { /* signed proof-of-grind, contains no secret */ },
"verifyUrl": "https://three.ws/vanity/verify"
}
```
-Longer than 3 chars? Grind it in the browser at [`/vanity`](https://three.ws/vanity)
-or buy it from [premium inventory](#tier-3--premium-inventory).
+Longer than 3 chars? A 4–5 char pattern is served if (and only if) it's in
+stock — same endpoint, premium price, `source: "inventory"`. Out of stock gets
+a `404 not_in_stock`; grind it yourself in the browser at
+[`/vanity`](https://three.ws/vanity), or browse what IS available at
+[premium inventory](#tier-3--premium-inventory).
### Security model
@@ -165,6 +190,21 @@ brandable addresses ground ahead of time on batch CPU and held encrypted.
> address** or **sweep assets to a wallet you generated yourself** — do not use it
> as a long-term treasury. Every listing and delivery says this plainly.
+**Restocking.** `api/cron/vanity-inventory-replenish` runs hourly, checks
+available stock against a low-water mark (`VANITY_INVENTORY_LOW_WATERMARK`,
+default 25), and fires the `workers/vanity-grinder` Cloud Run Job (via the
+Cloud Run Admin API) when it's running low — plus sweeps any ciphertext past
+its retention window. Trigger a batch manually any time with
+`scripts/gcp/vanity-grind-deploy.sh --run` or `node
+workers/vanity-grinder/grind.mjs` (see its
+[README](../workers/vanity-grinder/README.md)).
+
+**Pump Launcher upsell.** `POST /api/x402/pump-launch` with a `vanityPrefix` /
+`vanitySuffix` checks this same inventory before grinding a mint address live —
+a hit skips the grind entirely (`vanity_source: "inventory"` in the response),
+a miss grinds as before (`vanity_source: "ground"`). Same one-shot claim, same
+atomicity, no separate purchase step. See [pump-launcher.md](pump-launcher.md).
+
---
## How agents discover these
diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.md
index 719a482eb..bc44e4cb9 100644
--- a/docs/x402-endpoints.md
+++ b/docs/x402-endpoints.md
@@ -140,7 +140,7 @@ for to feed the oracle and sniper.
| Endpoint | Default | Returns |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [`/api/x402/pump-launch`](pump-launcher.md) | $5.00 | **Pump Launcher** — deploy a brand-new pump.fun token in one paid call. No SOL, no wallet, no account: the server fronts the deploy cost and signs the create tx; you pay USDC. Optional vanity mint. Full flow + funnel in [pump-launcher.md](pump-launcher.md). |
-| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 | **Vanity Grinder** — grind a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Keypair or importable BIP-39 mnemonic; ≤3 chars; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). |
+| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 (≤3) · $2.50–$10 (4–5, inventory-only) | **Vanity Grinder** — get a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Checks the pre-ground warehouse first for **instant delivery** (`source: "inventory"`); falls back to a live grind (`source: "ground"`) up to 3 chars. Keypair or importable BIP-39 mnemonic; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). |
| [`/api/x402/vanity-verifiable`](vanity.md#tier-2--provably-fair-grinder) | $0.02–$0.40 | **Provably-fair grinder** — same grind with a signed commit–reveal receipt proving the key was ground fresh and never kept. Spec: [PROTOCOL-vanity.md](PROTOCOL-vanity.md). |
| [`/api/x402/vanity-premium`](vanity.md#tier-3--premium-inventory) | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. |
| `/api/x402/pay-by-name` | per call | Resolve and pay an SNS/ENS name (see [Agent wallets](agent-wallets.md)). |
diff --git a/pages/bnb-latency.html b/pages/bnb-latency.html
index e9e2987f4..faa2f3265 100644
--- a/pages/bnb-latency.html
+++ b/pages/bnb-latency.html
@@ -32,7 +32,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+live+block+race&amp;d=BNB+Chain%27s+~0.45s+blocks+measured+live+against+Base%2C+Ethereum%2C+and+Solana+off+real+public+RPCs.+No+wallet%2C+no+payment%2C+no+hardcoded+numbers.&amp;p=%2Fbnb-latency"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+Live+Block+Race+%E2%80%94+0.45s+vs+Base%2C+Ethereum%2C+Solana&amp;d=A+live%2C+honest+race%3A+BNB+Chain%2C+Base%2C+Ethereum%2C+and+Solana+block+times+measured+fresh+off+real+public+RPCs+every+few+seconds%2C+with+a+rolling+sparkline+per+lane.&amp;p=%2Fbnb-latency"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -45,7 +45,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+live+block+race&amp;d=BNB+Chain%27s+~0.45s+blocks+measured+live+against+Base%2C+Ethereum%2C+and+Solana+off+real+public+RPCs.+No+wallet%2C+no+payment%2C+no+hardcoded+numbers.&amp;p=%2Fbnb-latency"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+Live+Block+Race+%E2%80%94+0.45s+vs+Base%2C+Ethereum%2C+Solana&amp;d=A+live%2C+honest+race%3A+BNB+Chain%2C+Base%2C+Ethereum%2C+and+Solana+block+times+measured+fresh+off+real+public+RPCs+every+few+seconds%2C+with+a+rolling+sparkline+per+lane.&amp;p=%2Fbnb-latency"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/bnb.html b/pages/bnb.html
index d3e58c6c3..1b1c90f01 100644
--- a/pages/bnb.html
+++ b/pages/bnb.html
@@ -32,7 +32,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+%E2%80%94+three+genuinely-unique+demos&amp;d=Gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%3A+three+product+tracks+built+on+BNB+Chain%27s+fastest-in-class+0.45s+blocks.+Live+proof%2C+honest+%22coming+soon%22+for+what%27s+not+shipped+yet.&amp;p=%2Fbnb"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+%E2%80%94+Three+Genuinely-Unique+Demos&amp;d=The+BNB+Chain+campaign%27s+front+door%3A+gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%2C+each+traced+to+a+capability+independe&amp;p=%2Fbnb"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -45,7 +45,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+%E2%80%94+three+genuinely-unique+demos&amp;d=Gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%3A+three+product+tracks+built+on+BNB+Chain%27s+fastest-in-class+0.45s+blocks.+Live+proof%2C+honest+%22coming+soon%22+for+what%27s+not+shipped+yet.&amp;p=%2Fbnb"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=BNB+Chain+%E2%80%94+Three+Genuinely-Unique+Demos&amp;d=The+BNB+Chain+campaign%27s+front+door%3A+gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%2C+each+traced+to+a+capability+independe&amp;p=%2Fbnb"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/categories.html b/pages/categories.html
index fca489694..7c8d043cd 100644
--- a/pages/categories.html
+++ b/pages/categories.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Categories&amp;d=Every+crypto+sector+ranked+by+market+cap%3A+Layer+1s%2C+DeFi%2C+memes%2C+AI%2C+RWAs+and+more%2C+with+live+24h+moves+and+volume.+See+which+categories+lead+the+market&amp;p=%2Fcategories"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Categories+by+Market+Cap&amp;d=Every+crypto+sector+ranked+by+market+cap+%E2%80%94+smart+contract+platforms%2C+AI+agents%2C+memecoins%2C+DeFi%2C+gaming%2C+and+more+%E2%80%94+with+24h+change%2C+volume%2C+and+the+top+coins+i&amp;p=%2Fcategories"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Categories&amp;d=Every+crypto+sector+ranked+by+market+cap%3A+Layer+1s%2C+DeFi%2C+memes%2C+AI%2C+RWAs+and+more%2C+with+live+24h+moves+and+volume.+See+which+categories+lead+the+market&amp;p=%2Fcategories"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Categories+by+Market+Cap&amp;d=Every+crypto+sector+ranked+by+market+cap+%E2%80%94+smart+contract+platforms%2C+AI+agents%2C+memecoins%2C+DeFi%2C+gaming%2C+and+more+%E2%80%94+with+24h+change%2C+volume%2C+and+the+top+coins+i&amp;p=%2Fcategories"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/chains.html b/pages/chains.html
index c711ccfc8..3d7693bc5 100644
--- a/pages/chains.html
+++ b/pages/chains.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Blockchain+TVL+by+Chain&amp;d=Live+total+value+locked+by+blockchain%3A+every+chain+ranked+by+TVL+with+its+dominance+share+of+the+cross-chain+total.+See+which+networks+hold+the+most+DeFi+liquidity&amp;p=%2Fchains"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Blockchain+TVL+by+Chain&amp;d=A+leaderboard+of+every+blockchain+by+total+value+locked%2C+with+each+chain%27s+dominance+share+of+on-chain+DeFi.+Live+from+DeFiLlama+%E2%80%94+see+where+liquidity+actually+&amp;p=%2Fchains"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Blockchain+TVL+by+Chain&amp;d=Live+total+value+locked+by+blockchain%3A+every+chain+ranked+by+TVL+with+its+dominance+share+of+the+cross-chain+total.+See+which+networks+hold+the+most+DeFi+liquidity&amp;p=%2Fchains"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Blockchain+TVL+by+Chain&amp;d=A+leaderboard+of+every+blockchain+by+total+value+locked%2C+with+each+chain%27s+dominance+share+of+on-chain+DeFi.+Live+from+DeFiLlama+%E2%80%94+see+where+liquidity+actually+&amp;p=%2Fchains"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/converter.html b/pages/converter.html
index bc80b2e7d..e718ad8ff 100644
--- a/pages/converter.html
+++ b/pages/converter.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Converter&amp;d=Convert+between+any+cryptocurrency+and+major+world+currencies+at+live+market+rates%3A+crypto%E2%86%94crypto%2C+crypto%E2%86%94fiat%2C+fiat%E2%86%94crypto.+Instant%2C+accurate%2C+always+up+to+date&amp;p=%2Fconverter"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Currency+Converter&amp;d=Convert+between+any+cryptocurrency+and+major+world+fiat+currencies+at+live+market+rates+%E2%80%94+crypto+to+crypto%2C+crypto+to+fiat%2C+and+back.+Type+an+amount%2C+pick+both+&amp;p=%2Fconverter"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Converter&amp;d=Convert+between+any+cryptocurrency+and+major+world+currencies+at+live+market+rates%3A+crypto%E2%86%94crypto%2C+crypto%E2%86%94fiat%2C+fiat%E2%86%94crypto.+Instant%2C+accurate%2C+always+up+to+date&amp;p=%2Fconverter"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Currency+Converter&amp;d=Convert+between+any+cryptocurrency+and+major+world+fiat+currencies+at+live+market+rates+%E2%80%94+crypto+to+crypto%2C+crypto+to+fiat%2C+and+back.+Type+an+amount%2C+pick+both+&amp;p=%2Fconverter"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/create.html b/pages/create.html
index 2254a166d..0c3791985 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -30,7 +30,7 @@
property="og:description"
content="Start here: build an AI agent, make a 3D avatar, generate a 3D model, or launch a token world — one hub, four paths."
/>
- <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Create&amp;d=What+do+you+want+to+create%3F+Build+an+AI+agent%2C+make+a+3D+avatar%2C+generate+a+3D+model%2C+or+launch+a+token+world.&amp;p=%2Fcreate" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Create&amp;d=The+front+door+for+everything+you+can+create+on+three.ws%3A+build+an+AI+agent%2C+make+a+3D+avatar+%28from+a+photo%2C+from+scratch%2C+from+a+text+prompt%2C+or+a+file%29%2C+gener&amp;p=%2Fcreate" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
@@ -39,7 +39,7 @@
name="twitter:description"
content="Start here: build an AI agent, make a 3D avatar, generate a 3D model, or launch a token world — one hub, four paths."
/>
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;t=Create&amp;d=What+do+you+want+to+create%3F+Build+an+AI+agent%2C+make+a+3D+avatar%2C+generate+a+3D+model%2C+or+launch+a+token+world.&amp;p=%2Fcreate" />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;t=Create&amp;d=The+front+door+for+everything+you+can+create+on+three.ws%3A+build+an+AI+agent%2C+make+a+3D+avatar+%28from+a+photo%2C+from+scratch%2C+from+a+text+prompt%2C+or+a+file%29%2C+gener&amp;p=%2Fcreate" />
<style>
#page-loading,
diff --git a/pages/crypto-api.html b/pages/crypto-api.html
index 4be5a0fb7..e3d8baf65 100644
--- a/pages/crypto-api.html
+++ b/pages/crypto-api.html
@@ -20,7 +20,7 @@
content="DEX pairs, prices, quotes, TVL, on-chain reads, name resolution — one free API, no key, no wallet. Pay-per-call only above the free quota."
/>
<meta property="og:url" content="https://three.ws/crypto-api" />
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+API&amp;d=One+free+API+for+crypto+data%3A+DEX+pairs%2C+prices%2C+quotes%2C+TVL%2C+on-chain+reads%2C+name+resolution.+No+key%2C+no+wallet.&amp;p=%2Fcrypto-api" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=learn&amp;t=Crypto+API&amp;d=One+free%2C+keyless+API+for+on-chain+and+market+data%3A+DEX+pairs%2C+prices%2C+swap+quotes%2C+TVL%2C+Solana+RPC+reads%2C+and+ENS%2FSNS+name+resolution+%E2%80%94+CoinGecko%2C+DefiLlama%2C+J&amp;p=%2Fcrypto-api" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
@@ -29,7 +29,7 @@
name="twitter:description"
content="DEX pairs, prices, quotes, TVL, on-chain reads, name resolution — free, keyless, one fetch."
/>
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+API&amp;d=One+free+API+for+crypto+data%3A+DEX+pairs%2C+prices%2C+quotes%2C+TVL%2C+on-chain+reads%2C+name+resolution.+No+key%2C+no+wallet.&amp;p=%2Fcrypto-api" />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=learn&amp;t=Crypto+API&amp;d=One+free%2C+keyless+API+for+on-chain+and+market+data%3A+DEX+pairs%2C+prices%2C+swap+quotes%2C+TVL%2C+Solana+RPC+reads%2C+and+ENS%2FSNS+name+resolution+%E2%80%94+CoinGecko%2C+DefiLlama%2C+J&amp;p=%2Fcrypto-api" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
diff --git a/pages/defi.html b/pages/defi.html
index 883bb8d08..ca719ac29 100644
--- a/pages/defi.html
+++ b/pages/defi.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+TVL+%26+Protocols&amp;d=Live+DeFi+total+value+locked%3A+the+top+protocols+ranked+by+TVL%2C+with+category%2C+chains%2C+and+1d%2F7d+moves.+See+where+liquidity+sits+across+decentralized+finance&amp;p=%2Fdefi"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+TVL+%26+Top+Protocols&amp;d=Total+value+locked+across+decentralized+finance%2C+with+the+top+protocols+ranked+by+TVL%2C+their+category%2C+chains%2C+and+1-day+and+7-day+change.+Live+from+DeFiLlama%2C+&amp;p=%2Fdefi"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+TVL+%26+Protocols&amp;d=Live+DeFi+total+value+locked%3A+the+top+protocols+ranked+by+TVL%2C+with+category%2C+chains%2C+and+1d%2F7d+moves.+See+where+liquidity+sits+across+decentralized+finance&amp;p=%2Fdefi"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+TVL+%26+Top+Protocols&amp;d=Total+value+locked+across+decentralized+finance%2C+with+the+top+protocols+ranked+by+TVL%2C+their+category%2C+chains%2C+and+1-day+and+7-day+change.+Live+from+DeFiLlama%2C+&amp;p=%2Fdefi"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/derivatives.html b/pages/derivatives.html
index 9f0579d46..2c02d4825 100644
--- a/pages/derivatives.html
+++ b/pages/derivatives.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Derivatives&amp;d=Live+perpetual+futures+markets+across+the+major+crypto+exchanges+%E2%80%94+price%2C+24h+move%2C+funding+rate%2C+open+interest%2C+and+24h+volume.+Filter+by+index&amp;p=%2Fderivatives"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Derivatives+%26+Perpetual+Futures&amp;d=Live+perpetual-futures+markets+across+exchanges+%E2%80%94+price%2C+24h+change%2C+funding+rate%2C+open+interest%2C+and+volume+for+every+major+contract.+Filter+by+underlying+inde&amp;p=%2Fderivatives"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Derivatives&amp;d=Live+perpetual+futures+markets+across+the+major+crypto+exchanges+%E2%80%94+price%2C+24h+move%2C+funding+rate%2C+open+interest%2C+and+24h+volume.+Filter+by+index&amp;p=%2Fderivatives"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Derivatives+%26+Perpetual+Futures&amp;d=Live+perpetual-futures+markets+across+exchanges+%E2%80%94+price%2C+24h+change%2C+funding+rate%2C+open+interest%2C+and+volume+for+every+major+contract.+Filter+by+underlying+inde&amp;p=%2Fderivatives"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/exchanges.html b/pages/exchanges.html
index 0e877a9d2..02704888a 100644
--- a/pages/exchanges.html
+++ b/pages/exchanges.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Exchanges&amp;d=The+top+crypto+exchanges+ranked+by+trust+score+and+24h+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each+venue.+Real+CoinGecko+data&amp;p=%2Fexchanges"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Top+Crypto+Exchanges&amp;d=The+leading+cryptocurrency+exchanges+ranked+by+trust+score+and+24-hour+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each.+Real+CoinGecko+data&amp;p=%2Fexchanges"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Exchanges&amp;d=The+top+crypto+exchanges+ranked+by+trust+score+and+24h+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each+venue.+Real+CoinGecko+data&amp;p=%2Fexchanges"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Top+Crypto+Exchanges&amp;d=The+leading+cryptocurrency+exchanges+ranked+by+trust+score+and+24-hour+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each.+Real+CoinGecko+data&amp;p=%2Fexchanges"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/fact-check.html b/pages/fact-check.html
index 3c6dd98fa..9c045f6fb 100644
--- a/pages/fact-check.html
+++ b/pages/fact-check.html
@@ -17,7 +17,7 @@
property="og:description"
content="Submit a claim, get a sourced verdict with a SHA-256 attestation — backed by a public, checkable accuracy benchmark. 3 free checks/day per IP, then $0.10 USDC via x402."
/>
- <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Fact+Check&amp;d=Sourced+fact-checking+with+cryptographic+attestations+%E2%80%94+a+published%2C+checkable+accuracy+benchmark+plus+a+live+free-check+box.+3+free+checks%2Fday+per+IP%2C+then+%240.&amp;p=%2Ffact-check" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
@@ -35,7 +35,13 @@
<link rel="stylesheet" href="/footer.css" />
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
<link rel="canonical" href="https://three.ws/fact-check" />
- </head>
+
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Fact Check — three.ws">
+ <meta name="twitter:description" content="Sourced fact-checking with cryptographic attestations — a published, checkable accuracy benchmark plus a live free-check box. 3 free checks/day per IP, then $0.10 USDC via x402.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;amp;t=Fact+Check&amp;amp;d=Sourced+fact-checking+with+cryptographic+attestations+%E2%80%94+a+published%2C+checkable+accuracy+benchmark+plus+a+live+free-check+box.+3+free+checks%2Fday+per+IP%2C+then+%240.&amp;amp;p=%2Ffact-check">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Fact Check","description":"Sourced fact-checking with cryptographic attestations — a published, checkable accuracy benchmark plus a live free-check box. 3 free checks/day per IP, then $0.10 USDC via x402.","url":"https://three.ws/fact-check","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&amp;t=Fact+Check&amp;d=Sourced+fact-checking+with+cryptographic+attestations+%E2%80%94+a+published%2C+checkable+accuracy+benchmark+plus+a+live+free-check+box.+3+free+checks%2Fday+per+IP%2C+then+%240.&amp;p=%2Ffact-check"}]}</script>
+</head>
<body>
<header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
diff --git a/pages/restyle.html b/pages/restyle.html
index 7d803171e..72596942b 100644
--- a/pages/restyle.html
+++ b/pages/restyle.html
@@ -14,7 +14,7 @@
<meta property="og:title" content="Restyle Studio · three.ws" />
<meta property="og:description" content="Apply PBR material presets, AI restyle from a text instruction, and seeded variants to any GLB, fine-tune materials live, and export a validated model — non-destructively." />
<meta property="og:url" content="https://three.ws/restyle" />
- <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Restyle+Studio&amp;d=Apply+PBR+material+presets+and+seeded+variants+to+any+GLB%2C+fine-tune+materials%2C+and+export+a+validated+model.&amp;p=%2Frestyle" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Restyle+Studio+%E2%80%94+material+presets%2C+AI+restyle+%26+variants&amp;d=Re-skin+any+3D+model+in+the+browser%3A+apply+PBR+material+presets+%28chrome%2C+gold%2C+glass%2C+wood%E2%80%A6%29%2C+restyle+from+a+plain-language+AI+instruction%2C+fan+out+seeded+color&amp;p=%2Frestyle" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
<link rel="stylesheet" href="/style.css" />
@@ -92,7 +92,15 @@
.rs-hint { font-size: 12px; color: var(--text-3); margin-top: 8px; }
.rs-hint a { color: var(--accent, #7aa2ff); }
</style>
- </head>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Restyle Studio — material presets, AI restyle &amp; variants — three.ws">
+ <meta name="twitter:title" content="Restyle Studio — material presets, AI restyle &amp; variants · three.ws">
+ <meta name="twitter:description" content="Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), restyle from a plain-language AI instruction, fan out seeded colorway variants as durable versions, fine-tune metalness and roughness live, and export a validated GLB — non-destructively, with a real revertable version lineage.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;amp;t=Restyle+Studio+%E2%80%94+material+presets%2C+AI+restyle+%26+variants&amp;amp;d=Re-skin+any+3D+model+in+the+browser%3A+apply+PBR+material+presets+%28chrome%2C+gold%2C+glass%2C+wood%E2%80%A6%29%2C+restyle+from+a+plain-language+AI+instruction%2C+fan+out+seeded+color&amp;amp;p=%2Frestyle">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Restyle Studio — material presets, AI restyle & variants","description":"Re-skin any 3D model in the browser: apply PBR material presets (chrome, gold, glass, wood…), restyle from a plain-language AI instruction, fan out seeded colorway variants as durable versions, fine-tune metalness and roughness live, and export a validated GLB — non-destructively, with a real revertable version lineage.","url":"https://three.ws/restyle","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=build&amp;t=Restyle+Studio+%E2%80%94+material+presets%2C+AI+restyle+%26+variants&amp;d=Re-skin+any+3D+model+in+the+browser%3A+apply+PBR+material+presets+%28chrome%2C+gold%2C+glass%2C+wood%E2%80%A6%29%2C+restyle+from+a+plain-language+AI+instruction%2C+fan+out+seeded+color&amp;p=%2Frestyle"}]}</script>
+</head>
<body>
<header>
<div id="nav-container"></div>
diff --git a/pages/screener.html b/pages/screener.html
index 25bb9c9db..fb8f73809 100644
--- a/pages/screener.html
+++ b/pages/screener.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Token+Screener&amp;d=Filter+the+top+250+cryptocurrencies+live%3A+search+by+name%2C+isolate+gainers+or+losers%2C+set+minimum+market+cap+and+volume%2C+and+sort+every+column.+Find+your+next+coin+fast&amp;p=%2Fscreener"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Token+Screener&amp;d=Screen+the+top+250+cryptocurrencies+with+live+filters+%E2%80%94+search+by+name+or+symbol%2C+isolate+gainers+or+losers%2C+and+set+minimum+market+cap+and+24h+volume+threshold&amp;p=%2Fscreener"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Token+Screener&amp;d=Filter+the+top+250+cryptocurrencies+live%3A+search+by+name%2C+isolate+gainers+or+losers%2C+set+minimum+market+cap+and+volume%2C+and+sort+every+column.+Find+your+next+coin+fast&amp;p=%2Fscreener"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Crypto+Token+Screener&amp;d=Screen+the+top+250+cryptocurrencies+with+live+filters+%E2%80%94+search+by+name+or+symbol%2C+isolate+gainers+or+losers%2C+and+set+minimum+market+cap+and+24h+volume+threshold&amp;p=%2Fscreener"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/pages/stablecoins.html b/pages/stablecoins.html
index d7c1c0ca4..0cbf9cade 100644
--- a/pages/stablecoins.html
+++ b/pages/stablecoins.html
@@ -33,7 +33,7 @@
/>
<meta
property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Stablecoins+Market+Cap&amp;d=The+top+stablecoins+ranked+by+market+cap%2C+with+live+peg+health%2C+dominance+share%2C+backing+mechanism%2C+and+the+chains+each+one+lives+on&amp;p=%2Fstablecoins"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Stablecoins+Market+Cap+%26+Peg+Health&amp;d=Every+major+stablecoin+ranked+by+circulating+market+cap%2C+with+live+peg+health%2C+backing+mechanism+%28fiat-backed%2C+crypto-backed%2C+algorithmic%29%2C+and+the+chains+it+li&amp;p=%2Fstablecoins"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -46,7 +46,7 @@
/>
<meta
name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Stablecoins+Market+Cap&amp;d=The+top+stablecoins+ranked+by+market+cap%2C+with+live+peg+health%2C+dominance+share%2C+backing+mechanism%2C+and+the+chains+each+one+lives+on&amp;p=%2Fstablecoins"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Stablecoins+Market+Cap+%26+Peg+Health&amp;d=Every+major+stablecoin+ranked+by+circulating+market+cap%2C+with+live+peg+health%2C+backing+mechanism+%28fiat-backed%2C+crypto-backed%2C+algorithmic%29%2C+and+the+chains+it+li&amp;p=%2Fstablecoins"
/>
<meta name="theme-color" content="#09090b" />
<link rel="icon" href="/favicon.ico" sizes="any" />
diff --git a/prompts/roadmap/_generated/04/probe-viewer.mjs b/prompts/roadmap/_generated/04/probe-viewer.mjs
new file mode 100644
index 000000000..c7a6048e9
--- /dev/null
+++ b/prompts/roadmap/_generated/04/probe-viewer.mjs
@@ -0,0 +1,138 @@
+// Ad-hoc verification script for prompt 04 (viewer + Scene Studio perf/a11y/AR).
+// Drives a real Chromium against the local dev server, checks console errors,
+// keyboard interaction, and responsive layout at 320/768/1440.
+import { chromium } from '@playwright/test';
+import { writeFileSync, mkdirSync } from 'node:fs';
+
+const OUT = '/workspaces/three.ws/prompts/roadmap/_generated/04';
+mkdirSync(OUT, { recursive: true });
+const BASE = 'http://localhost:3000';
+
+const results = [];
+function log(...args) {
+ console.log(...args);
+ results.push(args.map(String).join(' '));
+}
+
+const browser = await chromium.launch();
+
+async function withPage(name, fn) {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ const errors = [];
+ page.on('console', (msg) => {
+ if (msg.type() === 'error') errors.push(msg.text());
+ });
+ page.on('pageerror', (err) => errors.push('pageerror: ' + err.message));
+ try {
+ await fn(page, context);
+ } finally {
+ log(`[${name}] console errors: ${errors.length}`);
+ for (const e of errors) log(` - ${e}`);
+ await context.close();
+ }
+ return errors;
+}
+
+// ── 1. Dedicated harness page: mount <three-ws-viewer ar> and exercise it ──
+// (pages/_qa-probe-viewer.html — temporary, deleted after this verification run)
+await withPage('three-ws-viewer harness', async (page) => {
+ await page.goto(`${BASE}/pages/_qa-probe-viewer.html`, { waitUntil: 'networkidle' });
+ const loaded = await page
+ .waitForFunction(
+ () => !!document.getElementById('host')?.querySelector('three-ws-viewer'),
+ { timeout: 15000 },
+ )
+ .then(() => true)
+ .catch(() => false);
+ log('viewer element mounted:', loaded);
+
+ // Wait for the GLB `load` event (or error) to confirm real rendering.
+ const loadState = await page.evaluate(
+ () =>
+ new Promise((resolve) => {
+ const el = window.__viewerEl;
+ if (!el) return resolve('no-element');
+ el.addEventListener('load', () => resolve('load'), { once: true });
+ el.addEventListener('error', (e) => resolve('error:' + e.detail?.error?.message), { once: true });
+ setTimeout(() => resolve('timeout'), 12000);
+ }),
+ );
+ log('viewer GLB load result:', loadState);
+
+ // AR button present + accessible name.
+ const arBtnLabel = await page.evaluate(() => {
+ const el = window.__viewerEl;
+ const btn = el?.shadowRoot?.querySelector('.ar-btn');
+ return btn ? btn.getAttribute('aria-label') : null;
+ });
+ log('AR button aria-label:', arBtnLabel);
+
+ // Canvas keyboard focus + ARIA.
+ const canvasInfo = await page.evaluate(() => {
+ const el = window.__viewerEl;
+ const c = el?.shadowRoot?.querySelector('canvas');
+ return c
+ ? { tabIndex: c.tabIndex, role: c.getAttribute('role'), ariaLabel: c.getAttribute('aria-label') }
+ : null;
+ });
+ log('canvas a11y:', JSON.stringify(canvasInfo));
+
+ // Keyboard orbit: focus canvas, press ArrowLeft, confirm camera moved.
+ const before = await page.evaluate(() => {
+ const el = window.__viewerEl;
+ return el?._camera?.position.toArray();
+ });
+ const canvasHandle = await page.evaluateHandle(() => window.__viewerEl.shadowRoot.querySelector('canvas'));
+ await canvasHandle.asElement().focus();
+ await page.keyboard.press('ArrowLeft');
+ await page.waitForTimeout(50);
+ const after = await page.evaluate(() => {
+ const el = window.__viewerEl;
+ return el?._camera?.position.toArray();
+ });
+ log('camera before ArrowLeft:', JSON.stringify(before));
+ log('camera after ArrowLeft:', JSON.stringify(after));
+ log('keyboard orbit moved camera:', JSON.stringify(before) !== JSON.stringify(after));
+
+ // AR launch opens a new tab pointed at /api/ar.
+ const [popup] = await Promise.all([
+ context_popupWait(page),
+ page.evaluate(() => window.__viewerEl.shadowRoot.querySelector('.ar-btn').click()),
+ ]);
+ if (popup) {
+ await popup.waitForLoadState('domcontentloaded').catch(() => {});
+ log('AR popup URL:', popup.url());
+ log('AR popup status ok:', popup.url().includes('/api/ar'));
+ } else {
+ log('AR popup: none opened');
+ }
+});
+
+async function context_popupWait(page) {
+ try {
+ return await page.waitForEvent('popup', { timeout: 5000 });
+ } catch {
+ return null;
+ }
+}
+
+// ── 2. Responsive check: /viewer with a real GLB at 320/768/1440 ──
+for (const [label, viewport] of [
+ ['320', { width: 320, height: 640 }],
+ ['768', { width: 768, height: 1024 }],
+ ['1440', { width: 1440, height: 900 }],
+]) {
+ await withPage(`/scene @ ${label}px`, async (page) => {
+ await page.setViewportSize(viewport);
+ await page.goto(`${BASE}/scene`, { waitUntil: 'load', timeout: 60000 });
+ await page.waitForTimeout(2500);
+ await page.screenshot({ path: `${OUT}/scene-${label}.png` });
+ const hasActionBar = await page.evaluate(() => !!document.querySelector('.tws-sa-bar'));
+ log(`scene studio action bar present @${label}:`, hasActionBar);
+ });
+}
+
+writeFileSync(`${OUT}/playwright-probe.log`, results.join('\n') + '\n');
+await browser.close();
+console.log('DONE');
diff --git a/prompts/roadmap/_generated/08/gate-before.txt b/prompts/roadmap/_generated/08/gate-before.txt
index 87cde209e..efc77aef0 100644
--- a/prompts/roadmap/_generated/08/gate-before.txt
+++ b/prompts/roadmap/_generated/08/gate-before.txt
@@ -7,20 +7,90 @@
> node scripts/test-gate.mjs
[test-gate] running 7 critical-path test files…
-✘ [ERROR] Cannot start service: Host version "0.27.7" does not match binary version "0.28.1"
-1 error
-failed to load config from /workspaces/three.ws/vitest.config.js
+ RUN v4.1.9 /workspaces/three.ws
-⎯⎯⎯⎯⎯⎯⎯ Startup Error ⎯⎯⎯⎯⎯⎯⎯⎯
-Error: The service was stopped: write EPIPE
- at /workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:1230:34
- at responseCallbacks.<computed> (/workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:884:9)
- at afterClose (/workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:875:28)
- at /workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:2276:18
- at onwriteError (node:internal/streams/writable:603:3)
- at process.processTicksAndRejections (node:internal/process/task_queues:92:21)
+ Test Files 7 passed (7)
+ Tests 83 passed (83)
+ Start at 01:43:23
+ Duration 3.27s (transform 4.81s, setup 0ms, import 10.15s, tests 3.60s, environment 4ms)
+[test-gate] ✓ all critical-path tests passed
+
+> [email protected] test:gate-3d
+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js
+
+
+ RUN v4.1.9 /workspaces/three.ws
+
+
+ Test Files 4 passed (4)
+ Tests 244 passed (244)
+ Start at 01:43:28
+ Duration 4.10s (transform 382ms, setup 0ms, import 1.23s, tests 934ms, environment 1ms)
+
+
+> [email protected] audit:mcp
+> node scripts/audit-mcp-manifests.mjs
+
+[audit:mcp] 16 MCP manifests consistent
+
+> [email protected] audit:mcp-golden
+> node scripts/audit-mcp-golden.mjs
+
+[audit:mcp-golden] 233 hosted MCP tool contracts match the golden fixture
+
+> [email protected] audit:routes
+> node scripts/verify-routes.mjs
+
+Route verify — 300 catalog pages, 1066 main routes, 1 post-filesystem routes.
+ modeled dist files: 1527 · canonical-covered: 299 · literal page routes checked for shadows: 451
+ filesystem boundary (handle:filesystem) present: yes
+
+ℹ 1 advisory note(s):
+ TRAILSLASH /payments/ → notfound (lands on designed 404)
+
+✗ 1 FAILURE(s):
+ COVERAGE /fact-check canonical → notfound (404) /404.html
+
+> [email protected] audit:handlers
+> node scripts/audit-empty-handlers.mjs
+
+✓ audit-empty-handlers: all API handlers export a body (1622 checked)
+
+> [email protected] audit:pages
+> node scripts/audit-page-index.mjs
+
+Route audit: 141 auditable page routes, 300 documented in pages.json.
+✓ Every auditable page route is documented.
+
+ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.
+
+> [email protected] audit:hidden-guard
+> node scripts/audit-hidden-guard.mjs
+
+✓ audit-hidden-guard: all 263 pages resolve the [hidden] guard
+
+> [email protected] audit:x402-catalog
+> node scripts/audit-x402-catalog.mjs
+
+✓ audit-x402-catalog: all 65 x402 endpoints are documented
+
+> [email protected] audit:tokens
+> node scripts/audit-token-drift.mjs
+
+
+✗ design-token drift increased: 10 hardcoded token-hexes (baseline 0).
+
+ pages/bnb-latency.html: 4 (was 0)
+ pages/bnb.html: 5 (was 0)
+ pages/crypto-api.html: 1 (was 0)
+
+These hexes literally equal a canonical token — use the var instead:
+ #4ade80 → var(--success)
+ #f87171 → var(--danger)
+ #fbbf24 → var(--warn)
+See DESIGN-TOKENS.md. If a page deliberately re-themes a token, define the
+token locally (a theme layer) rather than hardcoding the raw hex.
-[test-gate] ✗ critical-path tests failed — blocking deploy
diff --git a/public/changelog.json b/public/changelog.json
index f4ecce5bb..506666676 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T01:47:02.462Z",
+ "generated_at": "2026-07-08T01:51:28.549Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -263,6 +263,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-08",
+ "type": "update",
+ "title": "Fact Check's accuracy benchmark has a real published score, and the search+AI chain got more reliable",
+ "summary": "The 40-claim fact-check accuracy benchmark has now actually been run against the real search-and-LLM chain, and /fact-check shows the genuine result instead of the \"not yet run\" placeholder. Running it for real surfaced and fixed two chain bugs along the way: a request-formatting bug was silently rejecting every fact-check call on the Groq lane, and the search step had no fallback beyond a narrow instant-answer API, so most claims returned zero sources. Both are fixed — search now also checks Wikipedia's full-text index, a free source that needs no API key — and the published score will keep improving as the platform's search coverage does. The benchmark, its scoring code, and every claim in the suite stay public for anyone to check.",
+ "link": "/fact-check",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-07-08",
"type": "update",
@@ -541,6 +552,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-08",
+ "type": "update",
+ "title": "Vanity addresses now go up to 5 characters, and the shelf restocks itself",
+ "summary": "GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it.",
+ "link": "/vanity",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-08",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1d9410cff..7319296a0 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -206,6 +206,14 @@
<category>feature</category>
<description>Try the Fact Checker without a wallet: 3 free checks a day per IP now run the exact same real search-and-LLM chain as the paid $0.10 USDC checks — never a degraded response — with a lane field on every result so you always know which one you got. A new /fact-check page publishes the accuracy claim instead of just asserting it: a 40-claim benchmark (10 per verdict class, time-stable and non-partisan) scored against the live chain, the claim set and scoring code both linked for anyone to check, plus a live 'try one free check' box right on the page.</description>
</item>
+ <item>
+ <title>Fact Check's accuracy benchmark has a real published score, and the search+AI chain got more reliable</title>
+ <link>https://three.ws/fact-check</link>
+ <guid isPermaLink="false">2026-07-08:Fact Check's accuracy benchmark has a real published score, and the search+AI chain got more reliable</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The 40-claim fact-check accuracy benchmark has now actually been run against the real search-and-LLM chain, and /fact-check shows the genuine result instead of the &quot;not yet run&quot; placeholder. Running it for real surfaced and fixed two chain bugs along the way: a request-formatting bug was silently rejecting every fact-check call on the Groq lane, and the search step had no fallback beyond a narrow instant-answer API, so most claims returned zero sources. Both are fixed — search now also checks Wikipedia's full-text index, a free source that needs no API key — and the published score will keep improving as the platform's search coverage does. The benchmark, its scoring code, and every claim in the suite stay public for anyone to check.</description>
+ </item>
<item>
<title>Fixed: the &quot;View it&quot; link on every generated 3D model now opens a real viewer</title>
<link>https://three.ws/changelog</link>
@@ -422,6 +430,14 @@
<category>improvement</category>
<description>GET /api/x402/vanity and the pump-launch vanity upsell now check pre-ground inventory before grinding a fresh address — a match is served immediately at the same price, no match still grinds fresh as before.</description>
</item>
+ <item>
+ <title>Vanity addresses now go up to 5 characters, and the shelf restocks itself</title>
+ <link>https://three.ws/vanity</link>
+ <guid isPermaLink="false">2026-07-08:Vanity addresses now go up to 5 characters, and the shelf restocks itself</guid>
+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it.</description>
+ </item>
<item>
<title>Verify a 3D model's authenticity — free, on-chain content credentials</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index ee75789a7..c544d12b0 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-08T01:47:02.447Z",
+ "generated_at": "2026-07-08T01:51:28.534Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.html
index fee6ced0f..a1d0cda18 100644
--- a/public/spatial-mcp/index.html
+++ b/public/spatial-mcp/index.html
@@ -26,6 +26,26 @@
.note { margin-top:24px; font-size:13px; color:#9aa3b2; line-height:1.6; }
code { color:#dbe9ff; }
</style>
+
+ <link rel="canonical" href="https://three.ws/spatial-mcp">
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:title" content="Spatial MCP — reference renderer · three.ws">
+ <meta property="og:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools.">
+ <meta property="og:url" content="https://three.ws/spatial-mcp">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=labs&amp;t=Spatial+MCP+%E2%80%94+reference+renderer&amp;d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any+confor&amp;p=%2Fspatial-mcp">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:type" content="image/png">
+ <meta property="og:image:alt" content="Spatial MCP — reference renderer — three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Spatial MCP — reference renderer · three.ws">
+ <meta name="twitter:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&amp;t=Spatial+MCP+%E2%80%94+reference+renderer&amp;d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any+confor&amp;p=%2Fspatial-mcp">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Spatial MCP — reference renderer","description":"The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools.","url":"https://three.ws/spatial-mcp","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=Spatial+MCP+%E2%80%94+reference+renderer&d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any+confor&p=%2Fspatial-mcp"}]}</script>
</head>
<body>
<div class="page">
diff --git a/public/viewer.html b/public/viewer.html
index 1e7684b7d..ab77597d5 100644
--- a/public/viewer.html
+++ b/public/viewer.html
@@ -1,6 +1,7 @@
<!doctype html>
<html lang="en">
<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>3D Viewer · three.ws</title>
@@ -76,6 +77,22 @@
.badge.unknown { color: #9aa3b2; background: rgba(255,255,255,.05); border-color: rgba(255,255,255,.12); }
.badge:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
</style>
+
+ <link rel="canonical" href="https://three.ws/viewer">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:url" content="https://three.ws/viewer">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=labs&amp;t=glTF+%2F+GLB+Viewer&amp;d=Paste+any+public+glTF%2FGLB+URL+and+preview+it+inline+%E2%80%94+the+lightweight%2C+unauthenticated+model+viewer+every+3D+Studio+tool%27s+shared+asset+link+opens.&amp;p=%2Fviewer">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:type" content="image/png">
+ <meta property="og:image:alt" content="glTF / GLB Viewer — three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="glTF / GLB Viewer · three.ws">
+ <meta name="twitter:description" content="Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&amp;t=glTF+%2F+GLB+Viewer&amp;d=Paste+any+public+glTF%2FGLB+URL+and+preview+it+inline+%E2%80%94+the+lightweight%2C+unauthenticated+model+viewer+every+3D+Studio+tool%27s+shared+asset+link+opens.&amp;p=%2Fviewer">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"glTF / GLB Viewer","description":"Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.","url":"https://three.ws/viewer","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=glTF+%2F+GLB+Viewer&d=Paste+any+public+glTF%2FGLB+URL+and+preview+it+inline+%E2%80%94+the+lightweight%2C+unauthenticated+model+viewer+every+3D+Studio+tool%27s+shared+asset+link+opens.&p=%2Fviewer"}]}</script>
</head>
<body>
<div class="wrap">
diff --git a/scripts/fact-check-benchmark.mjs b/scripts/fact-check-benchmark.mjs
index 6c4975c04..0cdfe3cde 100644
--- a/scripts/fact-check-benchmark.mjs
+++ b/scripts/fact-check-benchmark.mjs
@@ -119,7 +119,11 @@ async function checkOne(endpoint, bypassToken, claim) {
const res = await fetch(endpoint, {
method: 'POST',
headers,
- body: JSON.stringify({ claim, strictness: 'normal' }),
+ // 'medium' matches parseFactCheckBody's own default in api/x402/fact-check.js —
+ // spelled out explicitly rather than relying on an unrecognized value falling
+ // through to it (the endpoint only accepts high|medium|low; anything else,
+ // including the previous 'normal' here, silently resolves to 'medium' anyway).
+ body: JSON.stringify({ claim, strictness: 'medium' }),
signal: AbortSignal.timeout(60_000),
});
if (res.status === 402) {
diff --git a/src/forge-embed-panel.js b/src/forge-embed-panel.js
index a546a2cf4..dc1c4b7db 100644
--- a/src/forge-embed-panel.js
+++ b/src/forge-embed-panel.js
@@ -21,6 +21,7 @@ import {
embedPreviewUrl,
buildIframeSnippet,
buildWebComponentSnippet,
+ buildAgentThreeDSnippet,
} from './forge-embed-snippets.js';
const STYLE_ID = 'tws-forge-embed-styles';
@@ -53,8 +54,14 @@ function webComponentSnippet() {
return buildWebComponentSnippet(state.glbUrl, state.title, state.sizeId);
}
+function agentThreeDSnippet() {
+ return buildAgentThreeDSnippet(state.glbUrl, state.title, state.sizeId);
+}
+
function currentSnippet() {
- return state.tab === 'iframe' ? iframeSnippet() : webComponentSnippet();
+ if (state.tab === 'iframe') return iframeSnippet();
+ if (state.tab === 'agent3d') return agentThreeDSnippet();
+ return webComponentSnippet();
}
function ensureStyles() {
@@ -83,6 +90,7 @@ function bodyHtml() {
<div class="tws-emb-seg" role="group" aria-label="Embed type">
${tabBtn('iframe', 'iframe')}
${tabBtn('component', 'Web component')}
+ ${tabBtn('agent3d', esc('<agent-3d>'))}
</div>
<div class="tws-emb-seg" role="group" aria-label="Size">
${SIZES.map(sizeBtn).join('')}
diff --git a/src/forge-embed-snippets.js b/src/forge-embed-snippets.js
index 30f1c215a..502db91c7 100644
--- a/src/forge-embed-snippets.js
+++ b/src/forge-embed-snippets.js
@@ -1,19 +1,28 @@
// Forge embed snippets — the single source of truth for the "embed this model"
// code the platform hands out. Pure, framework-free builders shared by the full
-// Forge embed modal (src/forge-embed-panel.js) and the homepage mini Forge embed
-// sheet (src/home-forge.js), so the two surfaces never drift on snippet shape,
+// Forge embed modal (src/forge-embed-panel.js), the homepage mini Forge embed
+// sheet (src/home-forge.js), and Scene Studio's Share action
+// (src/scene-studio/actions.js), so no surface ever drifts on snippet shape,
// size presets, or the /forge/embed URLs.
//
-// Two flavours, both real:
+// Three flavours, all real:
// • iframe — points at /forge/embed?src=<glb>, the zero-dependency
// three.ws viewer page (orbit + AR + branding). Drops onto
// any site with no scripts on the host page.
// • web component — a <model-viewer> snippet for builders who want the model
// inline in their own DOM with their own controls.
+// • agent-3d — the platform's own <agent-3d viewer> web component
+// (@three-ws/avatar), pinned to the current major CDN
+// channel per specs/EMBED_SPEC.md. `viewer` is a pure-3D
+// mode: no chat chrome, just the framed, orbitable model.
const ORIGIN = 'https://three.ws';
const MODEL_VIEWER_CDN =
'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';
+// Major-version CDN channel (specs/EMBED_SPEC.md): follows minor/patch
+// releases automatically without pinning exact bytes like a demo snippet
+// would ("latest" is explicitly demo-only per that spec).
+const AGENT_3D_CDN = `${ORIGIN}/agent-3d/0/agent-3d.js`;
export const EMBED_SIZES = [
{ id: 'wide', label: '16 : 9', w: 640, h: 360, ratio: '16 / 9' },
@@ -93,3 +102,24 @@ export function buildWebComponentSnippet(glbUrl, title, sizeId) {
`\n</model-viewer>`
);
}
+
+// <agent-3d viewer> — the platform's own component instead of a third-party
+// one. `viewer` drops the chat chrome for a pure, orbitable 3D embed; `ar`
+// (added by prompt 04) opts into the "View in AR" affordance once the
+// consumer's page loads @three-ws/avatar's viewer runtime — the full
+// <agent-3d> monolith already supports AR via WebXR/Quick Look natively.
+export function buildAgentThreeDSnippet(glbUrl, title, sizeId) {
+ const s = embedSize(sizeId);
+ const alt = escEmbed(title || '3D model forged on three.ws');
+ return (
+ `<!-- once per page -->\n` +
+ `<script type="module" src="${AGENT_3D_CDN}"></scr` +
+ `ipt>\n\n` +
+ `<agent-3d\n` +
+ ` src="${escEmbed(glbUrl)}"\n` +
+ ` aria-label="${alt}"\n` +
+ ` viewer\n` +
+ ` style="display:block;width:${s.w}px;height:${s.h}px;max-width:100%;border-radius:14px;overflow:hidden">` +
+ `\n</agent-3d>`
+ );
+}
diff --git a/src/scene-studio/actions.js b/src/scene-studio/actions.js
new file mode 100644
index 000000000..b73ec033a
--- /dev/null
+++ b/src/scene-studio/actions.js
@@ -0,0 +1,241 @@
+// Scene Studio — layered quality-of-life action bar.
+//
+// Sibling to the vendored r184 editor (src/scene-studio/vendor/**) — never
+// edits vendor files, only reads `editor` and mounts its own DOM/CSS. Adds
+// three affordances the vendored File/Export menus don't offer on their own:
+//
+// • Import from Forge — paste the GLB URL from a Forge (or Parts Studio)
+// result and drop it straight into the scene, using the same undo-able
+// AddObjectCommand path the ?model= deep-link importer uses.
+// • Export presets — one click for "Web GLB" or "AR bundle (USDZ)",
+// instead of hovering File ▸ Export ▸ GLB/USDZ in the vendored menu.
+// • Share / Embed — uploads the current scene as a GLB and opens the
+// platform's existing "Embed this model" panel (iframe / web component /
+// <agent-3d> snippet) — the same modal Forge results use.
+
+import { addGltfBufferToScene } from './loader.js';
+import { showEmbedPanel } from '../forge-embed-panel.js';
+
+const STYLE_ID = 'tws-studio-actions-styles';
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = CSS;
+ document.head.appendChild(el);
+}
+
+function getAnimations(scene) {
+ const animations = [];
+ scene.traverse((object) => animations.push(...object.animations));
+ return animations;
+}
+
+function saveArrayBuffer(buffer, filename) {
+ const blob = new Blob([buffer], { type: 'application/octet-stream' });
+ downloadBlob(blob, filename);
+}
+
+function downloadBlob(blob, filename) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1500);
+}
+
+// Same GLB export shape as the vendored File ▸ Export ▸ GLB menu item —
+// binary, with cloned+optimized animation clips.
+async function exportSceneGlb(editor) {
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
+ const scene = editor.scene;
+ const animations = getAnimations(scene).map((clip) => clip.clone().optimize());
+ const exporter = new GLTFExporter();
+ return new Promise((resolve, reject) => {
+ // binary: true always resolves an ArrayBuffer (the GLB container),
+ // never the plain-JSON glTF shape — matches the vendored File ▸
+ // Export ▸ GLB menu item exactly.
+ exporter.parse(scene, resolve, reject, { binary: true, animations });
+ });
+}
+
+async function exportSceneUsdz(editor) {
+ const { USDZExporter } = await import('three/addons/exporters/USDZExporter.js');
+ const exporter = new USDZExporter();
+ return exporter.parseAsync(editor.scene);
+}
+
+async function importFromForge(editor) {
+ const url = window.prompt(
+ 'Paste the GLB URL from a Forge result (its "Copy share link" or Download link).',
+ );
+ if (!url) return;
+ const trimmed = url.trim();
+ if (!/^https:\/\//i.test(trimmed)) {
+ alert('That doesn\'t look like an https URL. Copy the GLB link from Forge\'s result bar and try again.');
+ return;
+ }
+ try {
+ const res = await fetch(trimmed);
+ if (!res.ok) throw new Error('HTTP ' + res.status);
+ const contents = await res.arrayBuffer();
+ const base = decodeURIComponent(trimmed.split('?')[0].split('/').pop() || '');
+ const label = (base.replace(/\.(glb|gltf)$/i, '') || 'Forge model').slice(0, 64);
+ await addGltfBufferToScene(editor, contents, label);
+ } catch (error) {
+ alert('Could not import that model (' + error.message + '). You can drag the GLB file into the editor instead.');
+ }
+}
+
+function closeMenu(menu) {
+ menu?.remove();
+}
+
+function showExportMenu(editor, anchorBtn) {
+ document.querySelector('.tws-sa-menu')?.remove();
+ const menu = document.createElement('div');
+ menu.className = 'tws-sa-menu';
+ menu.setAttribute('role', 'menu');
+ menu.innerHTML = `
+ <button type="button" role="menuitem" data-preset="glb">Web GLB <span>.glb — orbit-ready, compressed</span></button>
+ <button type="button" role="menuitem" data-preset="usdz">AR bundle <span>.usdz — iOS Quick Look</span></button>
+ `;
+ document.body.appendChild(menu);
+ const rect = anchorBtn.getBoundingClientRect();
+ menu.style.left = `${Math.max(8, rect.right - menu.offsetWidth)}px`;
+ menu.style.top = `${rect.top - menu.offsetHeight - 8}px`;
+
+ const onDocClick = (e) => {
+ if (!menu.contains(e.target) && e.target !== anchorBtn) {
+ closeMenu(menu);
+ document.removeEventListener('click', onDocClick, true);
+ }
+ };
+ setTimeout(() => document.addEventListener('click', onDocClick, true), 0);
+
+ menu.addEventListener('click', async (e) => {
+ const btn = e.target.closest('[data-preset]');
+ if (!btn) return;
+ closeMenu(menu);
+ document.removeEventListener('click', onDocClick, true);
+ try {
+ if (btn.dataset.preset === 'glb') {
+ saveArrayBuffer(await exportSceneGlb(editor), 'scene.glb');
+ } else {
+ saveArrayBuffer(await exportSceneUsdz(editor), 'scene.usdz');
+ }
+ } catch (error) {
+ alert('Export failed: ' + (error?.message || error));
+ }
+ });
+}
+
+async function shareScene(editor, triggerBtn) {
+ const original = triggerBtn.textContent;
+ triggerBtn.disabled = true;
+ triggerBtn.textContent = 'Exporting…';
+ try {
+ const buffer = await exportSceneGlb(editor);
+ const blob = new Blob([buffer], { type: 'model/gltf-binary' });
+
+ triggerBtn.textContent = 'Uploading…';
+ const presignRes = await fetch('/api/scene-glb-upload', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ content_type: 'model/gltf-binary', size_bytes: blob.size }),
+ });
+ const presign = await presignRes.json().catch(() => null);
+ if (!presignRes.ok || !presign?.upload_url) {
+ throw new Error(presign?.message || `Upload not available (HTTP ${presignRes.status})`);
+ }
+
+ const putRes = await fetch(presign.upload_url, {
+ method: presign.method || 'PUT',
+ headers: presign.headers || { 'content-type': 'model/gltf-binary' },
+ body: blob,
+ });
+ if (!putRes.ok) throw new Error(`Upload failed (HTTP ${putRes.status})`);
+
+ const title = document.title.replace(/\s*·\s*Scene Studio.*$/i, '').trim() || 'Scene composed on three.ws';
+ showEmbedPanel({ glbUrl: presign.public_url, title }, triggerBtn);
+ } catch (error) {
+ alert('Could not share this scene: ' + (error?.message || error));
+ } finally {
+ triggerBtn.disabled = false;
+ triggerBtn.textContent = original;
+ }
+}
+
+/**
+ * Mount the action bar into the Scene Studio container.
+ * @param {import('./vendor/js/Editor.js').Editor} editor
+ * @param {HTMLElement} container
+ */
+export function mountStudioActions(editor, container) {
+ ensureStyles();
+ const bar = document.createElement('div');
+ bar.className = 'tws-sa-bar';
+ bar.setAttribute('role', 'toolbar');
+ bar.setAttribute('aria-label', 'Scene Studio quick actions');
+ bar.innerHTML = `
+ <button type="button" class="tws-sa-btn" data-action="import" aria-label="Import a model from Forge">⤵ Import from Forge</button>
+ <button type="button" class="tws-sa-btn" data-action="export" aria-label="Export presets">⇩ Export</button>
+ <button type="button" class="tws-sa-btn tws-sa-primary" data-action="share" aria-label="Share or embed this scene">🔗 Share</button>
+ `;
+ container.appendChild(bar);
+
+ bar.addEventListener('click', (e) => {
+ const btn = e.target.closest('.tws-sa-btn');
+ if (!btn) return;
+ if (btn.dataset.action === 'import') importFromForge(editor);
+ else if (btn.dataset.action === 'export') showExportMenu(editor, btn);
+ else if (btn.dataset.action === 'share') shareScene(editor, btn);
+ });
+
+ return bar;
+}
+
+const CSS = `
+.tws-sa-bar {
+ position: absolute; top: 12px; right: 12px; z-index: 10;
+ display: flex; gap: 6px;
+ font: 600 12px/1 system-ui, -apple-system, sans-serif;
+}
+.tws-sa-btn {
+ appearance: none; cursor: pointer; white-space: nowrap;
+ border: 1px solid rgba(255,255,255,0.16); border-radius: 8px;
+ padding: 7px 11px; background: rgba(20,20,24,0.82); color: #e8e8ec;
+ backdrop-filter: blur(6px);
+ transition: background 0.14s, border-color 0.14s, transform 0.08s;
+}
+.tws-sa-btn:hover { background: rgba(34,34,40,0.92); border-color: rgba(255,255,255,0.3); }
+.tws-sa-btn:active { transform: translateY(1px); }
+.tws-sa-btn:focus-visible { outline: 2px solid #6ee7b7; outline-offset: 2px; }
+.tws-sa-btn:disabled { opacity: 0.6; cursor: default; }
+.tws-sa-btn.tws-sa-primary { background: #e8e8ec; color: #0a0a0f; border-color: transparent; }
+.tws-sa-btn.tws-sa-primary:hover { background: #ffffff; }
+.tws-sa-menu {
+ position: fixed; z-index: 1000;
+ display: flex; flex-direction: column; gap: 2px;
+ background: rgba(18,18,22,0.98); border: 1px solid rgba(255,255,255,0.14);
+ border-radius: 10px; padding: 6px; min-width: 220px;
+ box-shadow: 0 12px 32px rgba(0,0,0,0.45);
+ font: 600 12.5px/1.3 system-ui, sans-serif;
+}
+.tws-sa-menu button {
+ appearance: none; cursor: pointer; text-align: left;
+ border: 0; border-radius: 7px; padding: 8px 10px;
+ background: transparent; color: #e8e8ec;
+}
+.tws-sa-menu button:hover, .tws-sa-menu button:focus-visible { background: rgba(255,255,255,0.08); outline: none; }
+.tws-sa-menu button span { display: block; margin-top: 2px; font-weight: 400; font-size: 11px; color: #9a9aa8; }
+@media (prefers-reduced-motion: reduce) { .tws-sa-btn { transition: none; } }
+@media (max-width: 640px) {
+ .tws-sa-bar { top: auto; bottom: 12px; left: 12px; right: 12px; justify-content: flex-end; }
+ .tws-sa-btn span, .tws-sa-btn { font-size: 11.5px; padding: 8px 10px; }
+}
+`;
diff --git a/src/scene-studio/loader.js b/src/scene-studio/loader.js
new file mode 100644
index 000000000..1eb7cf8be
--- /dev/null
+++ b/src/scene-studio/loader.js
@@ -0,0 +1,63 @@
+// Scene Studio — shared GLB→scene loader.
+//
+// Sibling module (not vendor/**): the single place that wires the
+// Draco/KTX2/Meshopt-capable GLTFLoader and adds the parsed result to the
+// editor through the normal undo-able AddObjectCommand path. Used by:
+// • main.js's deep-link importer (?model=<url>) and /pose hand-off.
+// • actions.js's "Import from Forge" affordance (a pasted GLB URL).
+//
+// Decoder paths match the vendored Loader.js exactly (same static assets
+// under /scene-studio/), so an object added through either path decodes
+// identically.
+
+import { AddObjectCommand } from './vendor/js/commands/AddObjectCommand.js';
+
+let _loaderPromise = null;
+
+/**
+ * Lazily build a GLTFLoader wired with Draco/KTX2/Meshopt decoders. Memoized
+ * per page load — decoders are stateless enough to reuse across parses.
+ * @param {import('./vendor/js/Editor.js').Editor} editor
+ */
+function getGltfLoader(editor) {
+ if (_loaderPromise) return _loaderPromise;
+ _loaderPromise = Promise.all([
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/loaders/DRACOLoader.js'),
+ import('three/addons/loaders/KTX2Loader.js'),
+ import('three/addons/libs/meshopt_decoder.module.js'),
+ ]).then(([{ GLTFLoader }, { DRACOLoader }, { KTX2Loader }, { MeshoptDecoder }]) => {
+ const dracoLoader = new DRACOLoader();
+ dracoLoader.setDecoderPath('/scene-studio/draco/gltf/');
+ const ktx2Loader = new KTX2Loader();
+ ktx2Loader.setTranscoderPath('/scene-studio/basis/');
+ editor.signals.rendererDetectKTX2Support.dispatch(ktx2Loader);
+ const loader = new GLTFLoader();
+ loader.setDRACOLoader(dracoLoader);
+ loader.setKTX2Loader(ktx2Loader);
+ loader.setMeshoptDecoder(MeshoptDecoder);
+ return loader;
+ });
+ return _loaderPromise;
+}
+
+/**
+ * Parse a GLB ArrayBuffer and add it to the scene via AddObjectCommand
+ * (undo-able, autosave-triggering, outliner-visible — identical to a manual
+ * drag-and-drop import).
+ *
+ * @param {import('./vendor/js/Editor.js').Editor} editor
+ * @param {ArrayBuffer} contents
+ * @param {string} [label] — object name in the outliner.
+ * @returns {Promise<THREE.Object3D>}
+ */
+export async function addGltfBufferToScene(editor, contents, label) {
+ const loader = await getGltfLoader(editor);
+ const result = await loader.parseAsync(contents, '');
+ const object = result.scene;
+ if (label) object.name = label;
+ object.animations.push(...result.animations);
+ editor.execute(new AddObjectCommand(editor, object));
+ editor.selectByUuid(object.uuid);
+ return object;
+}
diff --git a/src/scene-studio/main.js b/src/scene-studio/main.js
index 05bff2e93..00d9f99b4 100644
--- a/src/scene-studio/main.js
+++ b/src/scene-studio/main.js
@@ -13,7 +13,6 @@ document.documentElement.setAttribute('data-theme', 'dark');
import * as THREE from 'three';
import { Editor } from './vendor/js/Editor.js';
-import { AddObjectCommand } from './vendor/js/commands/AddObjectCommand.js';
import { AddScriptCommand } from './vendor/js/commands/AddScriptCommand.js';
import { takeSceneHandoff } from '../shared/scene-handoff.js';
import { Viewport } from './vendor/js/Viewport.js';
@@ -28,6 +27,9 @@ import { Animation } from './vendor/js/Animation.js';
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
+import { addGltfBufferToScene as sharedAddGltfBufferToScene } from './loader.js';
+import { mountStudioActions } from './actions.js';
+
window.URL = window.URL || window.webkitURL;
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
@@ -67,6 +69,10 @@ container.appendChild(animation.dom);
const animationResizer = new AnimationResizer(editor);
container.appendChild(animationResizer.dom);
+// Layered quality-of-life bar — Import from Forge / Export presets / Share —
+// sibling to the vendored chrome, never touching vendor/**. See actions.js.
+mountStudioActions(editor, container);
+
editor.signals.animationPanelChanged.add(function (height) {
const visible = height !== false;
@@ -150,37 +156,10 @@ editor.storage.init(function () {
// add-or-replace import dialog, since a deep-link arrival has an unambiguous
// intent: add this model to the scene. The query is then stripped from the
// address bar so a reload doesn't import a duplicate — autosave already
-// persists the object.
+// persists the object. The decoder-wired loader itself lives in the sibling
+// loader.js module, shared with actions.js's "Import from Forge" affordance.
async function addGltfBufferToScene(contents, label) {
- // Same decoder wiring as the vendored Loader's createGLTFLoader.
- const [{ GLTFLoader }, { DRACOLoader }, { KTX2Loader }, { MeshoptDecoder }] = await Promise.all([
- import('three/addons/loaders/GLTFLoader.js'),
- import('three/addons/loaders/DRACOLoader.js'),
- import('three/addons/loaders/KTX2Loader.js'),
- import('three/addons/libs/meshopt_decoder.module.js'),
- ]);
- const dracoLoader = new DRACOLoader();
- dracoLoader.setDecoderPath('/scene-studio/draco/gltf/');
- const ktx2Loader = new KTX2Loader();
- ktx2Loader.setTranscoderPath('/scene-studio/basis/');
- editor.signals.rendererDetectKTX2Support.dispatch(ktx2Loader);
- const loader = new GLTFLoader();
- loader.setDRACOLoader(dracoLoader);
- loader.setKTX2Loader(ktx2Loader);
- loader.setMeshoptDecoder(MeshoptDecoder);
-
- try {
- const result = await loader.parseAsync(contents, '');
- const object = result.scene;
- if (label) object.name = label;
- object.animations.push(...result.animations);
- editor.execute(new AddObjectCommand(editor, object));
- editor.selectByUuid(object.uuid);
- return object;
- } finally {
- dracoLoader.dispose();
- ktx2Loader.dispose();
- }
+ return sharedAddGltfBufferToScene(editor, contents, label);
}
async function importModelFromQuery() {
diff --git a/tests/asset-provenance.test.js b/tests/asset-provenance.test.js
new file mode 100644
index 000000000..06c81ec88
--- /dev/null
+++ b/tests/asset-provenance.test.js
@@ -0,0 +1,100 @@
+// Signed asset provenance — pure crypto (canonicalization + ERC-191 framing),
+// tested the same way brain-sign.js's memory primitives are (tests/brain-bundle.test.js):
+// no DB, no network, just "does this verify the way packages/provenance-mcp's
+// verifyAction does". writeAssetProvenance / agentIdForAvatar touch the real
+// `sql` client and are exercised live via tests/tokenize-3d-remix-royalty.test.js
+// (which injects a fake agentIdForAvatar) rather than here.
+
+import { describe, it, expect } from 'vitest';
+import { Wallet } from 'ethers';
+
+import {
+ ACTION_SIG_VERSION,
+ stableStringify,
+ canonicalizeAction,
+ actionDigest,
+ verifyActionSignature,
+} from '../api/_lib/asset-provenance.js';
+
+// Same well-known throwaway test key already used in tests/brain-bundle.test.js.
+const TEST_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';
+const wallet = new Wallet(TEST_PK);
+
+function fixtureAction(overrides = {}) {
+ return {
+ agentId: '11111111-1111-1111-1111-111111111111',
+ type: 'tokenize_3d.mint',
+ payload: { mint: 'MintAsset1111111111111111111111111111111111', network: 'mainnet', prompt: 'a brave knight' },
+ sourceSkill: 'tokenize-3d',
+ ...overrides,
+ };
+}
+
+describe('asset-provenance · canonicalization', () => {
+ it('is deterministic regardless of payload key order', () => {
+ const a = canonicalizeAction(fixtureAction());
+ const b = canonicalizeAction(
+ fixtureAction({ payload: { network: 'mainnet', prompt: 'a brave knight', mint: 'MintAsset1111111111111111111111111111111111' } }),
+ );
+ expect(a).toBe(b);
+ });
+
+ it('embeds the domain-separating version prefix', () => {
+ expect(canonicalizeAction(fixtureAction())).toContain(`"v":"${ACTION_SIG_VERSION}"`);
+ });
+
+ it('changes when any signable field changes', () => {
+ const base = actionDigest(fixtureAction());
+ expect(actionDigest(fixtureAction({ type: 'avatar.generated' }))).not.toBe(base);
+ expect(actionDigest(fixtureAction({ agentId: 'other-agent' }))).not.toBe(base);
+ expect(actionDigest(fixtureAction({ payload: { ...fixtureAction().payload, prompt: 'a fierce dragon' } }))).not.toBe(base);
+ });
+
+ it('stableStringify sorts nested keys recursively', () => {
+ expect(stableStringify({ b: 1, a: { d: 2, c: 3 } })).toBe('{"a":{"c":3,"d":2},"b":1}');
+ });
+});
+
+describe('asset-provenance · sign + verify (ERC-191, mirrors provenance-mcp)', () => {
+ it('a real signature over the canonical digest verifies', async () => {
+ const action = fixtureAction();
+ const digest = actionDigest(action);
+ const signature = await wallet.signMessage(`${ACTION_SIG_VERSION}:${digest}`);
+
+ const result = verifyActionSignature(action, { signature, signer_address: wallet.address });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe('ok');
+ expect(result.recovered.toLowerCase()).toBe(wallet.address.toLowerCase());
+ });
+
+ it('tampering with the payload after signing breaks verification', async () => {
+ const action = fixtureAction();
+ const digest = actionDigest(action);
+ const signature = await wallet.signMessage(`${ACTION_SIG_VERSION}:${digest}`);
+
+ const tampered = fixtureAction({ payload: { ...action.payload, prompt: 'a completely different prompt' } });
+ const result = verifyActionSignature(tampered, { signature, signer_address: wallet.address });
+ // The digest is recomputed from the (tampered) action, so the signature no
+ // longer matches the signed message at all — ethers throws recovering it,
+ // or (astronomically unlikely) recovers to an unrelated address. Either way
+ // it must never report valid:true.
+ expect(result.valid).toBe(false);
+ });
+
+ it('a mismatched claimed signer is reported, never silently accepted', async () => {
+ const action = fixtureAction();
+ const digest = actionDigest(action);
+ const signature = await wallet.signMessage(`${ACTION_SIG_VERSION}:${digest}`);
+ const someoneElse = Wallet.createRandom().address;
+
+ const result = verifyActionSignature(action, { signature, signer_address: someoneElse });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe('signer_mismatch');
+ });
+
+ it('an unsigned action is reported honestly, never a false positive', () => {
+ const result = verifyActionSignature(fixtureAction(), {});
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe('unsigned');
+ });
+});
diff --git a/tests/tokenize-3d-remix-royalty.test.js b/tests/tokenize-3d-remix-royalty.test.js
new file mode 100644
index 000000000..02ba8c856
--- /dev/null
+++ b/tests/tokenize-3d-remix-royalty.test.js
@@ -0,0 +1,108 @@
+// Remix-royalty settlement on a tokenized-3D mint (Prompt 08, task 4) — when a
+// mint names a parent_mint, its fee is split with the parent creator using the
+// SAME pure math as the forge_creations remix bazaar (api/_lib/remix-royalty.js).
+// This exercises settleTokenizeRemixRoyalty's every honestly-reported outcome
+// with an injected fake `sql` (no real DB) and the real (unconfigured-in-CI)
+// payout-wallet resolver — no network calls, no mocked "fake success".
+
+import { describe, it, expect } from 'vitest';
+
+import { settleTokenizeRemixRoyalty } from '../api/_lib/tokenize-3d.js';
+import { REMIX_MIN_PAYOUT_ATOMICS } from '../api/_lib/remix-royalty.js';
+
+const PARENT_MINT = 'ParentMint1111111111111111111111111111111111';
+const CREATOR_WALLET = 'So11111111111111111111111111111111111111112';
+const MINT_FEE_ATOMICS = 250_000n; // $0.25, matches priceFor('mint_3d_asset')
+
+function fakeSqlReturning(row) {
+ return async () => (row ? [row] : []);
+}
+
+describe('settleTokenizeRemixRoyalty', () => {
+ it('never settles on devnet — the payout wallet only holds real mainnet funds', async () => {
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 1000, royalty_recipient: CREATOR_WALLET }),
+ parentMint: PARENT_MINT,
+ network: 'devnet',
+ feeAtomics: MINT_FEE_ATOMICS,
+ });
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('devnet_not_settled');
+ });
+
+ it('never settles when this call collected no fee (OAuth bypass) — nothing to split', async () => {
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 1000, royalty_recipient: CREATOR_WALLET }),
+ parentMint: PARENT_MINT,
+ network: 'mainnet',
+ feeAtomics: 0n,
+ });
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('no_fee_collected');
+ });
+
+ it('reports parent_not_found when the named parent_mint has no minted row', async () => {
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning(null),
+ parentMint: 'NoSuchMint11111111111111111111111111111111',
+ network: 'mainnet',
+ feeAtomics: MINT_FEE_ATOMICS,
+ });
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('parent_not_found');
+ });
+
+ it('reports no_creator_wallet when the parent has neither a royalty_recipient nor an owner_wallet', async () => {
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 1000, royalty_recipient: null, owner_wallet: null }),
+ parentMint: PARENT_MINT,
+ network: 'mainnet',
+ feeAtomics: MINT_FEE_ATOMICS,
+ });
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('no_creator_wallet');
+ });
+
+ it('computes the real split and — with no platform payout wallet configured in this env — reports payout_unconfigured honestly (never a fabricated payout)', async () => {
+ expect(process.env.REMIX_ROYALTY_PAYOUT_KEY).toBeFalsy();
+ expect(process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64).toBeFalsy();
+
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 1000, royalty_recipient: CREATOR_WALLET }),
+ parentMint: PARENT_MINT,
+ network: 'mainnet',
+ feeAtomics: MINT_FEE_ATOMICS,
+ });
+ // 10% of 250_000 atomics = 25_000 atomics — well above the dust floor, so
+ // the ONLY reason this doesn't pay is the missing payout wallet.
+ expect(BigInt(result.creator_atomics)).toBe((MINT_FEE_ATOMICS * 1000n) / 10000n);
+ expect(result.royalty_bps).toBe(1000);
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('payout_unconfigured');
+ });
+
+ it('drops a sub-dust royalty rather than pretending to pay it', async () => {
+ // A tiny fee at a low bps produces a creator slice below the dust floor.
+ const tinyFee = 1000n; // $0.001
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 100, royalty_recipient: CREATOR_WALLET }), // 1%
+ parentMint: PARENT_MINT,
+ network: 'mainnet',
+ feeAtomics: tinyFee,
+ });
+ expect((tinyFee * 100n) / 10000n).toBeLessThan(REMIX_MIN_PAYOUT_ATOMICS);
+ expect(result.paid).toBe(false);
+ expect(result.reason).toBe('below_dust_floor');
+ });
+
+ it('clamps a royalty rate above the cap and reports it', async () => {
+ const result = await settleTokenizeRemixRoyalty({
+ sql: fakeSqlReturning({ mint: PARENT_MINT, royalty_bps: 9999, royalty_recipient: CREATOR_WALLET }),
+ parentMint: PARENT_MINT,
+ network: 'mainnet',
+ feeAtomics: MINT_FEE_ATOMICS,
+ });
+ expect(result.capped).toBe(true);
+ expect(result.royalty_bps).toBeLessThan(9999);
+ });
+});
diff --git a/tests/vanity-premium-inventory.test.js b/tests/vanity-premium-inventory.test.js
index 3a24907ed..dbc842c0a 100644
--- a/tests/vanity-premium-inventory.test.js
+++ b/tests/vanity-premium-inventory.test.js
@@ -318,3 +318,67 @@ describe.skipIf(!HAS_DB)('instant inventory: live-grind + pump-launch upsell (ne
await retry.reveal();
});
});
+
+// ── Premium 4–5 char band: priced above the grind cap, inventory-only ───────
+// GET /api/x402/vanity now OFFERS 4–5 char patterns, but — unlike the ≤3 char
+// tiers — they are NEVER ground live (58^4-58^5 attempts is minutes-to-hours,
+// far past the 45s budget). These cover the pricing curve and the read-only
+// stock gate (hasAvailableMatch) the endpoint consults BEFORE quoting a 402,
+// so a buyer is never asked to pay for a pattern that isn't in stock.
+describe('vanity.js: premium 4–5 char tiers (inventory-only, priced above the grind cap)', () => {
+ it('priceAtomicsFor: 4 and 5 char keypair patterns price at the premium tiers, well above the 3-char cap', () => {
+ const p3 = priceAtomicsFor('keypair', 3);
+ const p4 = priceAtomicsFor('keypair', 4);
+ const p5 = priceAtomicsFor('keypair', 5);
+ expect(p3).toBe(250_000); // $0.25 — unchanged grind-cap tier
+ expect(p4).toBe(2_500_000); // $2.50 default
+ expect(p5).toBe(10_000_000); // $10 default
+ expect(p4).toBeGreaterThan(p3);
+ expect(p5).toBeGreaterThan(p4);
+ });
+
+ it('priceAtomicsFor: mnemonic format is not extended into the premium band (stays capped at 2 chars)', () => {
+ // Mnemonic has no inventory backing (the batch grinder only stocks raw
+ // keypairs), so length 4 falls back to the format's own max-length price,
+ // not a premium tier.
+ expect(priceAtomicsFor('mnemonic', 4)).toBe(priceAtomicsFor('mnemonic', 2));
+ });
+
+ it('priceAtomicsFor: X402_PRICE_VANITY_4 / X402_PRICE_VANITY_5 env overrides are honored', () => {
+ process.env.X402_PRICE_VANITY_4 = '3000000';
+ process.env.X402_PRICE_VANITY_5 = '15000000';
+ try {
+ expect(priceAtomicsFor('keypair', 4)).toBe(3_000_000);
+ expect(priceAtomicsFor('keypair', 5)).toBe(15_000_000);
+ } finally {
+ delete process.env.X402_PRICE_VANITY_4;
+ delete process.env.X402_PRICE_VANITY_5;
+ }
+ });
+
+ const HAS_DB2 = Boolean(process.env.DATABASE_URL);
+ describe.skipIf(!HAS_DB2)('hasAvailableMatch: the pre-402 stock gate (needs DATABASE_URL)', () => {
+ it('returns false for a 4-char pattern with no inventory match — the "not in stock" case', async () => {
+ const store = await import('../api/_lib/vanity-inventory-store.js');
+ const prefix = randPrefix(4);
+ const inStock = await store.hasAvailableMatch({ prefix, ignoreCase: true, format: 'keypair' });
+ expect(inStock).toBe(false);
+ });
+
+ it('returns true once a matching item is seeded, and never reserves it (read-only)', async () => {
+ const store = await import('../api/_lib/vanity-inventory-store.js');
+ const prefix = randPrefix(2); // 2 chars is fast to seed; the check itself is length-agnostic
+ const address = await seedInventoryItem(store, { prefix, priceUsd: 2.5 });
+
+ const inStock = await store.hasAvailableMatch({ prefix, ignoreCase: true, format: 'keypair' });
+ expect(inStock).toBe(true);
+
+ // Read-only: the item must still be claimable afterward (not reserved
+ // by the stock check itself).
+ const claim = await store.claimMatchingPattern({ prefix, ignoreCase: true, format: 'keypair', paymentId: 'stockcheck-' + prefix });
+ expect(claim.ok).toBe(true);
+ expect(claim.item.address).toBe(address);
+ await store.reserveAndReveal(address, { paymentId: 'stockcheck-' + prefix });
+ });
+ });
+});