Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add new 3D modeling services to OKX catalog and enhance identity demo script

fudjia82a3b1a26ec3
diff --git a/api/_lib/okx-catalog.js b/api/_lib/okx-catalog.js
index 011548ede..2fc4d12b2 100644
--- a/api/_lib/okx-catalog.js
+++ b/api/_lib/okx-catalog.js
@@ -113,6 +113,227 @@ export const OKX_CATALOG = Object.freeze([
},
},
},
+ // ── Work order 03: the decomposed 3D studio ────────────────────────────
+ // Micro-priced REST services, one capability per endpoint, all backed by
+ // the same engines /api/mcp-3d runs on (api/_okx3d/rest-services.js maps
+ // each id to its engine — no logic duplicated). Prices clear worst-case
+ // lane cost; the math is recorded in prompts/okx-ai/PROGRESS.md.
+ {
+ id: 'text-to-3d',
+ name: 'Text to 3D Model (GLB)',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Generates a textured, downloadable 3D model (GLB) from a text prompt on the fast draft ' +
+ 'lane. Returns the finished GLB URL inline or a job to poll for free. Paid only when the ' +
+ 'job is accepted.',
+ input:
+ 'POST JSON with prompt (3-1000 chars) describing one object or character; optional ' +
+ 'aspect_ratio. Poll poll_url free until status is done.',
+ },
+ priceUsd: '0.01',
+ amountAtomics: usdToAtomics(0.01),
+ endpoint: `${BASE}/api/okx/3d/text-to-3d`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['prompt'],
+ additionalProperties: false,
+ properties: {
+ prompt: { type: 'string', minLength: 3, maxLength: 1000 },
+ aspect_ratio: { type: 'string', enum: ['1:1', '4:3', '3:4', '16:9', '9:16'] },
+ },
+ },
+ },
+ {
+ id: 'text-to-3d-pro',
+ name: 'Text to 3D Model (Pro)',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Art-directed text to 3D: an LLM art director refines the prompt, then a higher-quality ' +
+ 'lane generates the textured GLB — standard tier by default, high for maximum detail ' +
+ 'plus PBR textures.',
+ input:
+ 'POST JSON with prompt (3-1000 chars); optional tier standard|high and aspect_ratio. ' +
+ 'Returns the GLB URL inline or job_id + poll_url; polling is free.',
+ },
+ priceUsd: '0.30',
+ amountAtomics: usdToAtomics(0.3),
+ endpoint: `${BASE}/api/okx/3d/text-to-3d-pro`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['prompt'],
+ additionalProperties: false,
+ properties: {
+ prompt: { type: 'string', minLength: 3, maxLength: 1000 },
+ tier: { type: 'string', enum: ['standard', 'high'] },
+ aspect_ratio: { type: 'string', enum: ['1:1', '4:3', '3:4', '16:9', '9:16'] },
+ },
+ },
+ },
+ {
+ id: 'image-to-3d',
+ name: 'Image to 3D Model',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Reconstructs a textured 3D model (GLB) from one to four reference photos of a single ' +
+ 'object. Paid per call; the job is polled for free until done.',
+ input:
+ 'POST JSON with image_urls: 1-4 public https photos of the same object; optional prompt ' +
+ 'hint. Returns the GLB URL or job_id + poll_url.',
+ },
+ priceUsd: '0.30',
+ amountAtomics: usdToAtomics(0.3),
+ endpoint: `${BASE}/api/okx/3d/image-to-3d`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['image_urls'],
+ additionalProperties: false,
+ properties: {
+ image_urls: {
+ type: 'array',
+ items: { type: 'string', format: 'uri' },
+ minItems: 1,
+ maxItems: 4,
+ },
+ prompt: { type: 'string', maxLength: 1000 },
+ },
+ },
+ },
+ {
+ id: 'rig',
+ name: 'Auto-Rig a GLB',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Auto-rigs a static humanoid GLB into an animation-ready model: adds a skeleton and skin ' +
+ 'weights so it can be posed and animated in any engine. Paid per call; job polling is ' +
+ 'free.',
+ input:
+ 'POST JSON with glb_url: public https URL of the static GLB to rig. Humanoid models rig ' +
+ 'best. Returns job_id + poll_url; poll free until done.',
+ },
+ priceUsd: '0.25',
+ amountAtomics: usdToAtomics(0.25),
+ endpoint: `${BASE}/api/okx/3d/rig`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['glb_url'],
+ additionalProperties: false,
+ properties: { glb_url: { type: 'string', format: 'uri' } },
+ },
+ },
+ {
+ id: 'avatar',
+ name: 'Text to Rigged Avatar',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'One call from text to an animation-ready character: generates the mesh, then auto-rigs a ' +
+ 'humanoid skeleton. Non-humanoid prompts are steered to plain mesh generation instead of ' +
+ 'a wasted rig pass.',
+ input:
+ 'POST JSON with prompt describing a full-body character, or image_url reference; optional ' +
+ 'allow_non_humanoid. Returns the mesh GLB plus a rig job to poll free.',
+ },
+ priceUsd: '0.50',
+ amountAtomics: usdToAtomics(0.5),
+ endpoint: `${BASE}/api/okx/3d/avatar`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ prompt: { type: 'string', maxLength: 1000 },
+ image_url: { type: 'string', format: 'uri' },
+ allow_non_humanoid: { type: 'boolean' },
+ },
+ },
+ },
+ {
+ id: 'retarget',
+ name: 'Animation Retarget',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Retargets a curated animation clip (idle, walk, dance and more) onto any rigged humanoid ' +
+ 'GLB. Returns the clip keyed to the rig plus a bone-coverage report. Completes in-request.',
+ input:
+ 'POST JSON with model_url (rigged GLB https URL) and animation (preset name); optional ' +
+ 'format glb|clip and speed 0.25-2.5.',
+ },
+ priceUsd: '0.10',
+ amountAtomics: usdToAtomics(0.1),
+ endpoint: `${BASE}/api/okx/3d/retarget`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['model_url', 'animation'],
+ additionalProperties: false,
+ properties: {
+ model_url: { type: 'string', format: 'uri' },
+ animation: { type: 'string' },
+ format: { type: 'string', enum: ['glb', 'clip'] },
+ speed: { type: 'number', minimum: 0.25, maximum: 2.5 },
+ },
+ },
+ },
+ {
+ id: 'pose-seed',
+ name: 'Pose Seed',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Resolves a natural-language pose description to a deterministic pose seed and a full ' +
+ 'joint-rotation map for humanoid rigs. The same prompt always returns the same pose. ' +
+ 'Completes in-request.',
+ input:
+ 'POST JSON with prompt (pose description, 1-500 chars). Returns the seed, per-joint ' +
+ 'rotations, and a preview link.',
+ },
+ priceUsd: '0.02',
+ amountAtomics: usdToAtomics(0.02),
+ endpoint: `${BASE}/api/okx/3d/pose-seed`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['prompt'],
+ additionalProperties: false,
+ properties: { prompt: { type: 'string', minLength: 1, maxLength: 500 } },
+ },
+ },
+ {
+ id: 'fbx-export',
+ name: 'FBX Export (rig-preserving)',
+ kind: 'rest',
+ describes: {
+ capability:
+ 'Converts a GLB to FBX for Unity/Unreal — a rigged GLB keeps its skeleton, skin weights, ' +
+ 'and blendshapes. Also exports obj, stl, ply, usdz, and 3mf. Paid per call; job polling ' +
+ 'is free.',
+ input:
+ 'POST JSON with model_url (GLB https URL); optional format (default fbx). Returns ' +
+ 'job_id + poll_url; poll free until done.',
+ },
+ priceUsd: '0.10',
+ amountAtomics: usdToAtomics(0.1),
+ endpoint: `${BASE}/api/okx/3d/fbx-export`,
+ tool: null,
+ inputSchema: {
+ type: 'object',
+ required: ['model_url'],
+ additionalProperties: false,
+ properties: {
+ model_url: { type: 'string', format: 'uri' },
+ format: { type: 'string', enum: ['fbx', 'obj', 'stl', 'ply', 'usdz', '3mf'] },
+ },
+ },
+ },
{
id: 'catalog',
name: '3D Studio Catalog (free)',
@@ -152,6 +373,12 @@ export function catalogEntry(id) {
return OKX_CATALOG.find((e) => e.id === id) || null;
}
+// The OKX listing description string: part ① and part ② joined on a newline —
+// the layout the approved sellers use. Work order 05 submits this verbatim.
+export function listingDescription(entry) {
+ return `${entry.describes.capability}\n${entry.describes.input}`;
+}
+
// The machine-readable index the free catalog service returns — the exact
// payload OKX buyers (and work order 05's listing update) consume.
export function catalogIndex() {
@@ -208,6 +435,11 @@ export function validateCatalog(catalog = OKX_CATALOG) {
if (e.kind === 'a2mcp' && (!e.tool || !e.inputSchema)) {
throw new Error(`${ctx}: a2mcp row needs tool + inputSchema`);
}
+ // Paid REST rows must document their POST body — the catalog service and
+ // the listing both surface the schema, and buyers have nothing else.
+ if (e.kind === 'rest' && !free && !e.inputSchema) {
+ throw new Error(`${ctx}: paid rest row needs inputSchema`);
+ }
}
return true;
}
diff --git a/api/_lib/x402-xlayer-okx.js b/api/_lib/x402-xlayer-okx.js
index 489c27491..bbacebca2 100644
--- a/api/_lib/x402-xlayer-okx.js
+++ b/api/_lib/x402-xlayer-okx.js
@@ -201,6 +201,10 @@ export function okxXLayerAccept(resourceUrl, amount) {
name: USDT0_DOMAIN_NAME,
version: USDT0_DOMAIN_VERSION,
transferMethod: 'eip3009',
+ // Optional-but-recommended (spec Appx H.2): USD₮0 is outside the OKX
+ // task system's supported-token list, so omitting decimals triggers a
+ // non-fatal tokenResolveError in `onchainos agent x402-check`.
+ decimals: 6,
},
};
}
diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.js
index fb46844bc..5287843d1 100644
--- a/api/_okx3d/identity.js
+++ b/api/_okx3d/identity.js
@@ -193,11 +193,15 @@ export async function shapeIdentityPrompt({ base = BASE, agentName, brief, style
async function submitForge(base, payload) {
let res;
try {
+ // The default free lane (NVIDIA NIM TRELLIS) completes SYNCHRONOUSLY —
+ // the submit response can take minutes and already carry the finished
+ // GLB, so the submit timeout must cover a full generation, not just an
+ // enqueue ack. Async backends still return a job_id quickly.
res = await fetch(`${base}/api/forge`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
- signal: AbortSignal.timeout(30_000),
+ signal: AbortSignal.timeout(150_000),
});
} catch (err) {
throw pipelineError('provider_error', `forge unreachable: ${err?.message || err}`);
@@ -484,42 +488,21 @@ async function beginRig(base, state) {
return saveState(state);
}
-// A generate/rig failure retries free while attempts remain — the buyer paid
-// for deliverables, not for our transient upstream weather. Exhausted retries
-// mark the job failed with the last actionable error.
-async function failStage(base, state, stage, err) {
+// A generate/rig/render failure retries free while attempts remain — the
+// buyer paid for deliverables, not for our transient upstream weather. The
+// retry itself happens on the NEXT status poll (the failed stage's job handle
+// is cleared, and advance re-submits), so one bad resubmission can never go
+// terminal while attempts remain. Exhausted retries mark the job failed with
+// the last actionable error.
+async function failStage(state, stage, err) {
const attempts = state.attempts[stage] ?? 0;
if (attempts < MAX_STAGE_ATTEMPTS && err?.code !== 'not_configured') {
state.error = { stage, code: err?.code || 'provider_error', message: String(err?.message || err), retrying: true };
- if (stage === 'generate') {
- try {
- const gen = await submitForge(
- base,
- state.input.referenceImageUrl
- ? { image_urls: [state.input.referenceImageUrl], prompt: state.prompt.effective, aspect_ratio: '3:4' }
- : { prompt: state.prompt.effective, aspect_ratio: '3:4' },
- );
- state.attempts.generate += 1;
- state.gen.jobId = gen.job_id ?? null;
- if (gen.status === 'done' && gen.glb_url) state.gen.glbUrl = gen.glb_url;
- return saveState(state);
- } catch (resubmitErr) {
- err = resubmitErr;
- }
- } else if (stage === 'rig') {
- try {
- const rig = await startRig(base, state.gen.glbUrl);
- state.attempts.rig += 1;
- state.rig.jobId = rig.job_id;
- return saveState(state);
- } catch (resubmitErr) {
- err = resubmitErr;
- }
- } else if (stage === 'render') {
- // Leave the cursor in place — the next status poll re-runs this render.
- state.attempts.render = attempts + 1;
- return saveState(state);
- }
+ if (stage === 'generate') state.gen.jobId = null;
+ else if (stage === 'rig') state.rig.jobId = null;
+ // render: cursor stays put — the next poll re-runs the same render.
+ state.attempts[stage] = attempts + 1;
+ return saveState(state);
}
state.stage = 'failed';
state.error = { stage, code: err?.code || 'provider_error', message: String(err?.message || err), retrying: false };
diff --git a/api/_okx3d/rest-services.js b/api/_okx3d/rest-services.js
new file mode 100644
index 000000000..0245b611b
--- /dev/null
+++ b/api/_okx3d/rest-services.js
@@ -0,0 +1,260 @@
+// OKX.AI REST services — engine adapters for the decomposed 3D studio.
+//
+// One exported invoke() per catalog row (api/_lib/okx-catalog.js), each a thin
+// wrapper over an engine the platform already runs — NO duplicated pipeline
+// logic:
+//
+// text-to-3d → /api/forge submit on the free NVIDIA NIM TRELLIS lane
+// (draft tier) via _mcp-studio/forge-client.js
+// text-to-3d-pro → Granite art director (fail-soft) + /api/forge submit at
+// standard/high tier — the mesh_forge chain
+// image-to-3d → /api/forge submit, image lane (TRELLIS reconstruct)
+// rig → /api/forge?action=rig submit (UniRig worker)
+// avatar → the forge_avatar chain: generate to completion, then
+// submit the rig job (humanoid gate included)
+// retarget → apply_animation MCP tool handler (in-process retarget)
+// pose-seed → pose_model MCP tool handler (deterministic presets)
+// fbx-export → remesh_model MCP tool handler, operation=convert
+//
+// Contract with the route (api/okx/3d/[service].js): invoke AFTER payment
+// verification and BEFORE settlement — a thrown error means the buyer is not
+// charged. Async lanes return { status:'queued', job_id, poll_url } (polling
+// GET /api/forge?job=<id> is free, no payment or account); fast lanes return
+// their result inline with status:'done'.
+
+import Ajv from 'ajv';
+import addFormats from 'ajv-formats';
+
+import { catalogEntry } from '../_lib/okx-catalog.js';
+import {
+ originFromReq,
+ viewerUrl,
+ startForge,
+ startRig,
+ generate,
+ directPrompt,
+} from '../_mcp-studio/forge-client.js';
+import { TOOLS as STUDIO_TOOLS } from '../_mcp3d/catalog.js';
+
+const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
+addFormats(ajv);
+
+// Compile each paid REST row's inputSchema once; invoke() validates before any
+// engine call so malformed input fails fast and free of charge.
+const validators = new Map();
+function validatorFor(entry) {
+ let v = validators.get(entry.id);
+ if (!v) {
+ v = ajv.compile(entry.inputSchema);
+ validators.set(entry.id, v);
+ }
+ return v;
+}
+
+function inputError(message) {
+ const e = new Error(message);
+ e.status = 400;
+ e.code = 'invalid_input';
+ return e;
+}
+
+// Errors from the studio MCP tool handlers carry JSON-RPC codes; normalize to
+// HTTP-shaped errors the route can map without leaking internals.
+function normalizeToolError(err, service) {
+ if (err?.status) return err;
+ const e = new Error(err?.message || `${service} failed`);
+ e.status = typeof err?.code === 'number' && err.code === -32602 ? 400 : 502;
+ e.code = e.status === 400 ? 'invalid_input' : 'service_failed';
+ return e;
+}
+
+// The synthetic principal MCP tool handlers see for a paid OKX call: no
+// account scope (payer-keyed rate limits), same shape mcp-3d.js synthesizes.
+function okxAuth(payer) {
+ return { userId: null, rateKey: `okx:${payer || 'anon'}`, scope: '', source: 'x402', payer };
+}
+
+function queuedResponse(job, extra = {}) {
+ if (job.status === 'done' && job.glb_url) {
+ return { status: 'done', glb_url: job.glb_url, ...extra };
+ }
+ return {
+ status: 'queued',
+ job_id: job.job_id,
+ poll_url: job.poll_url || `/api/forge?job=${encodeURIComponent(job.job_id)}`,
+ ...extra,
+ };
+}
+
+// Prompt used by text-to-3d-pro — the same single-subject art-director spec
+// mesh_forge uses (kept in sync with api/_mcp-studio/tools.js).
+const MESH_DIRECTOR =
+ "You are a 3D asset art director. Rewrite the user's idea into ONE concise prompt for a text-to-3D " +
+ 'generator. Describe a SINGLE isolated subject on a plain background, naming form, materials, color, and ' +
+ 'surface detail. No scenes, no multiple objects, no text or logos, no background. Output ONLY the rewritten ' +
+ 'prompt as a single line.';
+
+// Humanoid gate for the avatar chain — mirror of the forge_avatar steer in
+// api/_mcp-studio/tools.js so both surfaces refuse the same obvious objects.
+const NON_HUMANOID = /\b(chair|sofa|couch|table|desk|lamp|car|truck|vehicle|building|house|tree|plant|sword|gun|bottle|cup|mug|phone|laptop|rock|stone|food|fruit|flower|dog|cat|horse|cow|fish|bird|dragon|snake|spider|dinosaur)\b/i;
+const HUMANOID = /\b(human|person|man|woman|boy|girl|character|avatar|hero|warrior|knight|robot|android|figure|mascot|humanoid|biped|wizard|elf|orc|zombie|ninja|soldier|astronaut)\b/i;
+function looksNonHumanoid(prompt) {
+ const t = String(prompt || '');
+ return NON_HUMANOID.test(t) && !HUMANOID.test(t);
+}
+
+async function callStudioTool(name, args, { req, payer }) {
+ const tool = STUDIO_TOOLS[name];
+ if (!tool) {
+ const e = new Error(`engine tool ${name} is not available`);
+ e.status = 500;
+ e.code = 'engine_missing';
+ throw e;
+ }
+ let result;
+ try {
+ result = await tool.handler(args, okxAuth(payer), req);
+ } catch (err) {
+ throw normalizeToolError(err, name);
+ }
+ if (result?.isError) {
+ const message = result.content?.find((c) => c.type === 'text')?.text || `${name} failed`;
+ throw inputError(message);
+ }
+ return result;
+}
+
+const HANDLERS = {
+ // $0.01 — the free NVIDIA NIM TRELLIS lane, draft tier, submit-then-poll.
+ async 'text-to-3d'(args, ctx) {
+ const job = await startForge(ctx.base, {
+ prompt: args.prompt,
+ aspect: args.aspect_ratio,
+ backend: 'nvidia',
+ path: 'image',
+ });
+ return queuedResponse(job, { mode: 'text_to_3d', tier: 'draft' });
+ },
+
+ // $0.30 — Granite director (fail-soft) + the standard/high generation lane.
+ async 'text-to-3d-pro'(args, ctx) {
+ const tier = args.tier === 'high' ? 'high' : 'standard';
+ let effective = args.prompt;
+ const directed = await directPrompt(ctx.base, MESH_DIRECTOR, args.prompt);
+ if (directed) effective = directed;
+ const job = await startForge(ctx.base, { prompt: effective, aspect: args.aspect_ratio });
+ return queuedResponse(job, { mode: 'text_to_3d', tier });
+ },
+
+ // $0.30 — image lane (TRELLIS reconstruct of caller-supplied views).
+ async 'image-to-3d'(args, ctx) {
+ const job = await startForge(ctx.base, {
+ prompt: args.prompt || undefined,
+ imageUrls: args.image_urls,
+ aspect: '1:1',
+ });
+ return queuedResponse(job, { mode: 'image_to_3d' });
+ },
+
+ // $0.25 — UniRig auto-rigging, submit-then-poll.
+ async rig(args, ctx) {
+ const job = await startRig(ctx.base, args.glb_url);
+ return queuedResponse(job, { mode: 'rig' });
+ },
+
+ // $0.50 — the forge_avatar chain: mesh to completion, then the rig job.
+ // The mesh GLB is returned even while the rig is still polling, so a rig
+ // failure never loses the paid generation.
+ async avatar(args, ctx) {
+ if (!args.prompt && !args.image_url) {
+ throw inputError('Provide a prompt or an image_url.');
+ }
+ if (args.prompt && !args.image_url && args.allow_non_humanoid !== true && looksNonHumanoid(args.prompt)) {
+ throw inputError(
+ 'That looks like an object rather than a character. Auto-rigging needs a humanoid figure — use text-to-3d for objects, or set allow_non_humanoid to override.',
+ );
+ }
+ const gen = await generate(
+ ctx.base,
+ {
+ prompt: args.prompt || undefined,
+ imageUrls: args.image_url ? [args.image_url] : undefined,
+ aspect: '1:1',
+ },
+ { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS' },
+ );
+ if (gen._timedOut || !gen.glb_url) {
+ const e = new Error('Generation took too long — you were not charged; try again.');
+ e.status = 504;
+ e.code = 'generation_timeout';
+ throw e;
+ }
+ const rigJob = await startRig(ctx.base, gen.glb_url);
+ return queuedResponse(rigJob, {
+ mode: 'avatar',
+ mesh_glb_url: gen.glb_url,
+ mesh_viewer_url: viewerUrl(ctx.base, gen.glb_url),
+ });
+ },
+
+ // $0.10 — in-process clip retargeting; completes inside the request.
+ async retarget(args, ctx) {
+ const result = await callStudioTool('apply_animation', args, ctx);
+ return { status: 'done', ...(result.structuredContent || {}) };
+ },
+
+ // $0.02 — deterministic pose-seed resolution; completes inside the request.
+ async 'pose-seed'(args, ctx) {
+ const result = await callStudioTool('pose_model', { prompt: args.prompt }, ctx);
+ return { status: 'done', ...(result.structuredContent || {}) };
+ },
+
+ // $0.10 — remesh convert (rig-preserving FBX by default), submit-then-poll.
+ async 'fbx-export'(args, ctx) {
+ const result = await callStudioTool(
+ 'remesh_model',
+ { model_url: args.model_url, operation: 'convert', format: args.format || 'fbx' },
+ ctx,
+ );
+ const sc = result.structuredContent || {};
+ if (sc.job_id) {
+ return {
+ status: 'queued',
+ job_id: sc.job_id,
+ poll_url: `/api/forge?job=${encodeURIComponent(sc.job_id)}`,
+ mode: 'convert',
+ format: args.format || 'fbx',
+ };
+ }
+ return { status: 'done', ...sc };
+ },
+};
+
+export function isRestPaidService(id) {
+ const entry = catalogEntry(id);
+ return Boolean(entry && entry.kind === 'rest' && entry.priceUsd !== '0' && HANDLERS[id]);
+}
+
+// Run one paid REST service. Validates input against the catalog schema, then
+// dispatches to the engine adapter. Throws HTTP-shaped errors ({status, code,
+// message}); the route maps them and skips settlement.
+export async function invokeRestService(id, args, { req, payer }) {
+ const entry = catalogEntry(id);
+ const handler = HANDLERS[id];
+ if (!entry || !handler) {
+ const e = new Error(`no such service "${id}"`);
+ e.status = 404;
+ e.code = 'unknown_service';
+ throw e;
+ }
+ const validate = validatorFor(entry);
+ const body = args && typeof args === 'object' ? args : {};
+ if (!validate(body)) {
+ const first = validate.errors?.[0];
+ throw inputError(
+ `invalid input${first ? `: ${first.instancePath || '(root)'} ${first.message}` : ''}`,
+ );
+ }
+ const base = originFromReq(req);
+ return handler(body, { req, base, payer });
+}
diff --git a/api/okx/3d/[service].js b/api/okx/3d/[service].js
index 657ddc6b4..28c62c237 100644
--- a/api/okx/3d/[service].js
+++ b/api/okx/3d/[service].js
@@ -8,12 +8,42 @@
// x402-priced; identity_status + getting_started
// are free. Transport mirrors api/mcp-3d.js —
// verify → dispatch → settle-on-success.
-import { cors, json, readJson, wrap } from '../../_lib/http.js';
+// /api/okx/3d/<paid service> REST (work order 03): plain JSON POST, one
+// capability + one price per endpoint. Unpaid
+// POST → OKX-dialect 402 (PAYMENT-REQUIRED
+// header + body); paid replay → verify →
+// engine → settle → PAYMENT-RESPONSE. GET is
+// the free per-service descriptor. Engines in
+// api/_okx3d/rest-services.js.
+import { cors, error, json, readJson, wrap } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { settlePayment, encodePaymentResponseHeader } from '../../_lib/x402-spec.js';
+import {
+ buildExactRequirements,
+ encodePaymentResponseHeader,
+ resolveResourceUrl,
+ settlePayment,
+ verifyPayment,
+ X402Error,
+} from '../../_lib/x402-spec.js';
+import {
+ okxXLayerAccept,
+ sendOkx402,
+ xlayerRailHealth,
+ xlayerSettleable,
+} from '../../_lib/x402-xlayer-okx.js';
import { priceBatch, isDiscoveryOnlyBatch } from '../../_lib/mcp-batch-price.js';
-import { OKX_CATALOG, catalogIndex, catalogEntry } from '../../_lib/okx-catalog.js';
+import { OKX_CATALOG, catalogIndex, catalogEntry, listingDescription } from '../../_lib/okx-catalog.js';
import { headObject, putObject } from '../../_lib/r2.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ extractIdFromHeader,
+ hashPaymentProof,
+ hashRequestPayload,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from '../../_lib/x402/payment-identifier-server.js';
import {
send401,
sendJsonRpcError,
@@ -30,6 +60,7 @@ import {
isPublicIdentityTool,
IDENTITY_CHALLENGE,
} from '../../_okx3d/tools.js';
+import { invokeRestService, isRestPaidService } from '../../_okx3d/rest-services.js';
const BASE = 'https://three.ws';
const HEALTH_PROBE_KEY = 'okx-identity/health-probe.txt';
@@ -85,10 +116,201 @@ async function healthReport() {
await headObject(HEALTH_PROBE_KEY);
}
}),
+ probe('retarget', async () => {
+ // The animation library the retarget service reads clips from — a
+ // reachable, non-empty manifest proves the clip lane is servable.
+ const res = await fetch(`${BASE}/animations/manifest.json`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) throw new Error(`animation manifest returned ${res.status}`);
+ const manifest = await res.json();
+ const clips = Array.isArray(manifest) ? manifest.length : Array.isArray(manifest?.animations) ? manifest.animations.length : 0;
+ if (!clips) throw new Error('animation manifest empty');
+ return { clips };
+ }),
+ probe('payment-rail', async () => {
+ // Real X Layer probe: RPC block height, fee-token symbol read, and
+ // settlement-route configuration (OKX facilitator creds / relayer).
+ const rail = await xlayerRailHealth();
+ if (rail.rpc && !rail.rpc.ok) throw new Error(rail.rpc.error || 'X Layer RPC unreachable');
+ return {
+ settleable: rail.settleable,
+ block: rail.rpc?.block,
+ token: rail.token?.symbol,
+ facilitator_configured: rail.facilitator?.configured ?? false,
+ };
+ }),
]);
return { ok: subsystems.every((s) => s.ok), subsystems, checkedAt: new Date().toISOString() };
}
+// Per-service accepts: the OKX X Layer entry leads (that is the rail this
+// surface exists for — the buyer CLI auto-selects the first `exact` entry),
+// followed by the platform's existing rails so non-OKX agents can pay too.
+// One service, one price: every entry carries the same catalog amount.
+function restRequirements(resourceUrl, entry) {
+ const out = [];
+ if (xlayerSettleable()) out.push(okxXLayerAccept(resourceUrl, entry.amountAtomics));
+ out.push(...buildExactRequirements(resourceUrl, entry.amountAtomics));
+ return out;
+}
+
+// Free GET descriptor — per-service discovery, mirroring GET /api/x402/forge:
+// what it does, what it costs, how to call it. No payment, no account.
+function restDescriptor(res, entry) {
+ return json(
+ res,
+ 200,
+ {
+ service: entry.id,
+ name: entry.name,
+ endpoint: entry.endpoint,
+ method: 'POST',
+ price_usd: entry.priceUsd,
+ description: listingDescription(entry),
+ input_schema: entry.inputSchema,
+ poll: 'GET /api/forge?job=<job_id> — free',
+ catalog: `${BASE}/api/okx/3d/catalog`,
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
+}
+
+// Plain-JSON paid service (work order 03). Wire flow per
+// specs/okx-agent-payments.md and the api/x402/forge.js seller pattern:
+// unpaid POST → OKX-dialect 402; paid replay → idempotency check → verify →
+// engine (submit/complete) → settle → 200 + PAYMENT-RESPONSE. Engine errors
+// are answered BEFORE settlement, so a failed job never charges the buyer.
+async function handleRestService(req, res, entry) {
+ if (req.method === 'GET' || req.method === 'HEAD') return restDescriptor(res, entry);
+ if (req.method !== 'POST') {
+ res.setHeader('allow', 'GET, POST');
+ return error(res, 405, 'method_not_allowed', 'POST to run the service, GET for its descriptor');
+ }
+
+ // Pre-payment surface (402 challenges, validation) is rate-limited; the
+ // work itself is paywalled.
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success)
+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const rawBody = Buffer.concat(chunks).toString('utf8');
+ let body;
+ try {
+ body = rawBody ? JSON.parse(rawBody) : {};
+ } catch {
+ return error(res, 400, 'invalid_json', 'Request body must be valid JSON.');
+ }
+
+ const resourcePath = `/api/okx/3d/${entry.id}`;
+ const resourceUrl = resolveResourceUrl(req, resourcePath);
+ const requirements = restRequirements(resourceUrl, entry);
+ if (!requirements.length) {
+ return error(
+ res,
+ 503,
+ 'rail_unconfigured',
+ 'No payment rail is configured on this deployment — set the X Layer envs per specs/okx-agent-payments.md.',
+ );
+ }
+
+ const paymentHeader = req.headers['payment-signature'] || req.headers['x-payment'];
+ if (!paymentHeader) {
+ return sendOkx402(res, { resourceUrl, accepts: requirements });
+ }
+
+ // Idempotency + replay: a retried payment (same proof, same body) replays
+ // the SAME response instead of submitting a second job; a concurrent replay
+ // of an in-flight proof is refused. Identical plumbing to api/x402/forge.js.
+ const clientPaymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({ method: 'POST', url: resourcePath, body: rawBody });
+ const paymentHash = hashPaymentProof(paymentHeader);
+ const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ if (paymentId) {
+ const lookup = await checkCache({ route: resourcePath, paymentId, payloadHash, paymentHash });
+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route: resourcePath,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ reason: lookup.reason,
+ });
+ }
+ }
+ let releaseProof = async () => {};
+ const guard = await reservePaymentProof(resourcePath, paymentHeader);
+ if (!guard.ok) {
+ return json(res, 409, { error: 'payment_in_flight', retry_after: 1 });
+ }
+ releaseProof = guard.release;
+
+ try {
+ let verified;
+ try {
+ verified = await verifyPayment({ paymentHeader, requirements });
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return sendOkx402(res, { resourceUrl, accepts: requirements, error: err.message });
+ }
+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);
+ }
+
+ // Engine runs AFTER verify, BEFORE settle — a thrown engine error means
+ // the buyer was not charged, and we say so.
+ let result;
+ try {
+ result = await invokeRestService(entry.id, body, { req, payer: verified.payer });
+ } catch (err) {
+ const status = err.status || 502;
+ const message =
+ status >= 500
+ ? 'The service could not complete and your payment was not taken — please retry shortly.'
+ : err.message;
+ if (status >= 500) console.warn(`[okx/3d/${entry.id}] engine failed (${status}): ${err?.message || err}`);
+ return error(res, status, err.code || 'service_failed', message);
+ }
+
+ let settled;
+ try {
+ settled = await settlePayment({ verified });
+ } catch (err) {
+ return sendX402Error(res, { resourceUrl, accepts: requirements }, err);
+ }
+
+ const paymentResponse = encodePaymentResponseHeader(settled);
+ const contentType = 'application/json; charset=utf-8';
+ const responseBody = JSON.stringify({ service: entry.id, price_usd: entry.priceUsd, ...result });
+ res.statusCode = 200;
+ // v2 header name (OKX buyers decode PAYMENT-RESPONSE) + the legacy name
+ // for x402 SDK clients paying over the platform rails.
+ res.setHeader('PAYMENT-RESPONSE', paymentResponse);
+ res.setHeader('x-payment-response', paymentResponse);
+ res.setHeader('access-control-expose-headers', 'PAYMENT-REQUIRED, PAYMENT-RESPONSE');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', contentType);
+ res.end(responseBody);
+
+ if (paymentId) {
+ await storeResponse({
+ route: resourcePath,
+ paymentId,
+ payloadHash,
+ paymentHash,
+ status: 200,
+ body: responseBody,
+ contentType,
+ paymentResponseHeader: paymentResponse,
+ });
+ }
+ } finally {
+ await releaseProof();
+ }
+}
+
async function handleIdentityStudio(req, res) {
const resourcePath = '/api/okx/3d/identity-studio';
@@ -132,7 +354,10 @@ async function handleIdentityStudio(req, res) {
// first settle lands.
let releaseProof = async () => {};
if (x402Ctx) {
- const guard = await reservePaymentProof(resourcePath, req.headers['x-payment']);
+ const guard = await reservePaymentProof(
+ resourcePath,
+ req.headers['x-payment'] || req.headers['payment-signature'],
+ );
if (!guard.ok) {
return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });
}
@@ -195,6 +420,8 @@ export default wrap(async (req, res) => {
if (service === 'identity-studio') return handleIdentityStudio(req, res);
+ if (isRestPaidService(service)) return handleRestService(req, res, catalogEntry(service));
+
const known = catalogEntry(service);
return json(res, 404, {
error: 'unknown_service',
diff --git a/data/agent-identities.json b/data/agent-identities.json
new file mode 100644
index 000000000..cca3793f0
--- /dev/null
+++ b/data/agent-identities.json
@@ -0,0 +1,37 @@
+{
+ "$comment": "Agent Identity Studio demo identities — the saved inputs and pipeline outputs behind three.ws/agent-identities. Each entry is a REAL run of the production pipeline (scripts/okx-identity-demo.mjs); results are written back here by the script, never by hand.",
+ "identities": [
+ {
+ "slug": "ledgerlynx",
+ "kind": "finance data agent",
+ "agentName": "LedgerLynx",
+ "brief": "A meticulous on-chain accounting agent that reconciles wallets and flags anomalies in real time. Calm, precise, incorruptible — dresses like a sharp auditor from the future.",
+ "styleHints": "deep navy and silver palette, brushed-metal accents, subtle circuit-trace pinstripes",
+ "result": null
+ },
+ {
+ "slug": "museweaver",
+ "kind": "creative / art agent",
+ "agentName": "MuseWeaver",
+ "brief": "A flamboyant generative-art muse that turns raw ideas into finished galleries. Playful, extravagant, a walking canvas with paint still drying.",
+ "styleHints": "iridescent fabrics, paint-splash gradients, asymmetric couture silhouette",
+ "result": null
+ },
+ {
+ "slug": "momentum-9",
+ "kind": "trading bot",
+ "agentName": "Momentum-9",
+ "brief": "A high-frequency momentum trading bot built for speed and discipline. Aggressive but never reckless; reads order books like sheet music.",
+ "styleHints": "matte-black exoskeleton with ember-orange telemetry lines and a narrow visor",
+ "result": null
+ },
+ {
+ "slug": "three-ws-3d-studio",
+ "kind": "our own listing — OKX.AI agent #2632",
+ "agentName": "three.ws 3D Studio",
+ "brief": "The 3D identity studio of three.ws: an artisan engineer agent that forges avatars, rigs skeletons, and lights studio renders for other AI agents. Equal parts craftsman and machine.",
+ "styleHints": "charcoal work jacket with violet and cyan accents, holographic measuring tools, craftsman apron",
+ "result": null
+ }
+ ]
+}
diff --git a/data/pages.json b/data/pages.json
index b05ce34a1..04a85e5a3 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1074,6 +1074,14 @@
"changefreq": "weekly",
"added": "2026-06-20"
},
+ {
+ "path": "/vanity/premium",
+ "title": "Premium Vanity Inventory",
+ "description": "Buy a long, brandable Solana vanity address delivered instantly from stock — 4–5+ character prefixes the live grinder can't reach, ground ahead of time on batch CPU and sold via x402. Keys are encrypted at rest, priced by rarity, and delivered exactly once.",
+ "priority": 0.6,
+ "changefreq": "weekly",
+ "added": "2026-07-06"
+ },
{
"path": "/vanity/bounties",
"title": "Grind-Bounty Market",
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
index df6ab3db3..cd9bc2731 100755
--- a/mcp-server/src/index.js
+++ b/mcp-server/src/index.js
@@ -31,6 +31,7 @@ import { buildPoseSeedTool } from './tools/pose-seed.js';
import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';
import { buildAgentReputationTool } from './tools/agent-reputation.js';
import { buildVanityGrinderTool } from './tools/vanity-grinder.js';
+import { buildVanityPremiumTool } from './tools/vanity-premium.js';
import { buildTextToAvatarTool } from './tools/text-to-avatar.js';
import { buildMeshForgeTool } from './tools/mesh-forge.js';
import { buildForgeFreeTool } from './tools/forge-free.js';
@@ -68,7 +69,8 @@ const SERVER_INSTRUCTIONS =
'(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' +
'(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' +
'ERC-8004 agent reputation (agent_reputation), Solana vanity address mining ' +
- '(vanity_grinder), and AgenC coordination protocol reads — ' +
+ '(vanity_grinder) plus a free browse of the premium pre-ground vanity inventory ' +
+ '(vanity_premium), and AgenC coordination protocol reads — ' +
'task discovery, task status + lifecycle, and agent registry lookup ' +
'(agenc_list_tasks, agenc_get_task, agenc_get_agent), aixbt market ' +
'intelligence — narrative intel feed and momentum-ranked project scans ' +
@@ -101,6 +103,7 @@ const TOOL_BUILDERS = [
buildPumpSnapshotTool,
buildAgentReputationTool,
buildVanityGrinderTool,
+ buildVanityPremiumTool,
buildAgenCListTasksTool,
buildAgenCGetTaskTool,
buildAgenCGetAgentTool,
diff --git a/mcp-server/src/tools/vanity-premium.js b/mcp-server/src/tools/vanity-premium.js
new file mode 100644
index 000000000..c730c2fcd
--- /dev/null
+++ b/mcp-server/src/tools/vanity-premium.js
@@ -0,0 +1,115 @@
+// `vanity_premium` — FREE MCP tool: browse the premium vanity-address INVENTORY
+// (long 4–5+ char brandable addresses ground ahead of time on batch CPU) and get
+// difficulty-scaled prices + a ready-to-pay purchase link.
+//
+// This is the discovery half of the sell-from-stock tier. It is intentionally
+// FREE and read-only: it lists what's in stock and each item's price, then hands
+// back an x402 buy URL (/api/x402/vanity-premium?address=…) that the caller (or a
+// pay-capable agent) settles to receive the key ONCE. The existing paid
+// `vanity_grinder` tool — which grinds a fresh ≤3-char keypair per call — is
+// untouched and remains the live-grind tier.
+//
+// CUSTODY HONESTY: every response carries the same disclosure the endpoint and UI
+// show — these keys are platform-generated; use as a token mint or sweep to
+// self-generated custody, not as a treasury.
+
+import { z } from 'zod';
+
+import { free } from '../payments.js';
+import { jsonSchemaFromZod } from './_shared.js';
+
+const TOOL_NAME = 'vanity_premium';
+
+const APP_ORIGIN = (process.env.APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');
+
+const CUSTODY_NOTICE =
+ 'These keys were generated by three.ws, not by you. For high-value use, treat a purchased address ' +
+ 'as a token MINT or sweep assets to a self-generated wallet — do not use it as a treasury. The key ' +
+ 'is delivered once and its ciphertext is destroyed on delivery.';
+
+const TOOL_DESCRIPTION =
+ 'Browse the three.ws PREMIUM vanity-address inventory — long (4–5+ character) brandable Solana ' +
+ 'addresses ground ahead of time on batch CPU and sold from stock, which the live grinder cannot reach. ' +
+ 'FREE and read-only: returns the available patterns, each address, its rarity tier, and a difficulty-' +
+ 'scaled price ($1–$50), plus a ready-to-pay x402 buyUrl. Pay that URL (USDC on Base or Solana) to ' +
+ 'receive the private key exactly once; the ciphertext is destroyed on delivery (delete-after-reveal). ' +
+ 'Filter by prefix or rarity tier and sort by rarity/price/newest. For a fresh ≤3-char grind instead of ' +
+ 'buying from stock, use the vanity_grinder tool. CUSTODY: keys are platform-generated — use as a token ' +
+ 'mint or sweep to self-generated custody, not a treasury. Free — no payment required to browse.';
+
+const inputZodShape = {
+ prefix: z.string().max(8).describe('Filter to addresses whose prefix starts with these Base58 chars.').optional(),
+ tier: z
+ .enum(['common', 'uncommon', 'rare', 'epic', 'legendary', 'mythic'])
+ .describe('Filter to a rarity tier.')
+ .optional(),
+ sort: z.enum(['rarity', 'price', 'new']).describe('Order results — rarity (default), price (cheapest first), or new.').optional(),
+ limit: z.number().int().min(1).max(100).describe('Max results (default 40).').optional(),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+async function runVanityPremium({ prefix, tier, sort = 'rarity', limit = 40 } = {}) {
+ // Lazy-import the store so tool enumeration never needs a DB connection.
+ let store;
+ try {
+ store = await import('../../../api/_lib/vanity-inventory-store.js');
+ } catch (err) {
+ return degraded(`inventory store unavailable (${err.message})`);
+ }
+ try {
+ const [items, stats] = await Promise.all([
+ store.listAvailable({ prefix, tier, sort, limit }),
+ store.inventoryStats(),
+ ]);
+ return {
+ custodyNotice: CUSTODY_NOTICE,
+ stats,
+ priceRange: { minUsd: stats.minPrice, maxUsd: stats.maxPrice },
+ count: items.length,
+ items: items.map((it) => ({
+ address: it.address,
+ pattern: it.patternLabel,
+ rarityTier: it.rarityTier,
+ rarityScore: it.rarityScore,
+ priceUsd: it.priceUsd,
+ buyUrl: `${APP_ORIGIN}/api/x402/vanity-premium?address=${encodeURIComponent(it.address)}`,
+ explorerUrl: `https://solscan.io/account/${it.address}`,
+ })),
+ browseUrl: `${APP_ORIGIN}/vanity/premium`,
+ howToBuy: 'Pay the item buyUrl with x402 (USDC on Base or Solana). The key is delivered once; add &sealTo=<X25519 pubkey> to receive it sealed.',
+ };
+ } catch (err) {
+ return degraded(`could not read inventory (${err.message})`);
+ }
+}
+
+// Degrade gracefully: still hand back the browse + purchase surface so the caller
+// isn't dead-ended when the store read fails.
+function degraded(reason) {
+ return {
+ custodyNotice: CUSTODY_NOTICE,
+ count: 0,
+ items: [],
+ note: `${reason}. Browse and buy directly at the listing endpoint.`,
+ browseUrl: `${APP_ORIGIN}/vanity/premium`,
+ listingApi: `${APP_ORIGIN}/api/x402/vanity-premium`,
+ };
+}
+
+export function buildVanityPremiumTool() {
+ const handler = free({ toolName: TOOL_NAME, inputSchema: inputJsonSchema }, (args) => runVanityPremium(args));
+ return {
+ name: TOOL_NAME,
+ title: 'Premium vanity inventory (browse)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
+ handler,
+ };
+}
diff --git a/pages/agent-identities.html b/pages/agent-identities.html
new file mode 100644
index 000000000..32e977aaa
--- /dev/null
+++ b/pages/agent-identities.html
@@ -0,0 +1,310 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <title>Agent Identity Studio — 3D avatars for AI agents · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta
+ name="description"
+ content="Every AI agent deserves a face. The Agent Identity Studio turns a brand brief into a rigged 3D avatar plus posed studio renders — see the demo identities, then mint your agent's own."
+ />
+ <link rel="canonical" href="https://three.ws/agent-identities" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Agent Identity Studio — 3D avatars for AI agents" />
+ <meta
+ property="og:description"
+ content="Brand brief in, rigged 3D avatar + studio renders out. Demo identities generated end-to-end by the pipeline."
+ />
+ <meta property="og:url" content="https://three.ws/agent-identities" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/style.css" />
+ <style>
+ .ai-wrap {
+ max-width: 1160px;
+ margin: 0 auto;
+ padding: calc(var(--header-h, 64px) + var(--space-xl)) var(--space-lg) var(--space-2xl);
+ }
+ .ai-hero {
+ max-width: 720px;
+ margin-bottom: var(--space-2xl);
+ }
+ .ai-hero h1 {
+ font-family: var(--font-display);
+ font-size: var(--text-3xl);
+ line-height: var(--leading-tight);
+ margin: 0 0 var(--space-sm);
+ }
+ .ai-hero p {
+ color: var(--ink-dim);
+ font-size: var(--text-md);
+ line-height: var(--leading-normal);
+ margin: 0 0 var(--space-md);
+ }
+ .ai-hero .ai-cta {
+ display: flex;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ }
+ .ai-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5ch;
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 2px 10px;
+ margin-bottom: var(--space-sm);
+ }
+ .ai-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: var(--space-lg);
+ }
+ .ai-card {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;
+ }
+ .ai-card:hover {
+ transform: translateY(-3px);
+ border-color: var(--stroke-strong);
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
+ }
+ .ai-card:focus-within {
+ border-color: var(--accent);
+ }
+ .ai-stage {
+ position: relative;
+ aspect-ratio: 4 / 5;
+ background: radial-gradient(120% 90% at 50% 40%, #1a2030 0%, #10141d 55%, #0a0c10 100%);
+ }
+ .ai-stage img,
+ .ai-stage model-viewer,
+ .ai-stage .ai-pending {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ .ai-stage img {
+ object-fit: contain;
+ transition: opacity 0.25s ease;
+ }
+ .ai-stage model-viewer {
+ --poster-color: transparent;
+ background: transparent;
+ }
+ .ai-pending {
+ display: grid;
+ place-items: center;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ text-align: center;
+ padding: var(--space-lg);
+ }
+ .ai-pfp {
+ position: absolute;
+ left: var(--space-sm);
+ bottom: var(--space-sm);
+ width: 72px;
+ height: 72px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke-strong);
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.5);
+ background: #10141d;
+ overflow: hidden;
+ }
+ .ai-pfp img {
+ position: static;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .ai-body {
+ padding: var(--space-md);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-xs);
+ flex: 1;
+ }
+ .ai-kind {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--accent);
+ }
+ .ai-name {
+ font-family: var(--font-display);
+ font-size: var(--text-lg);
+ margin: 0;
+ }
+ .ai-brief {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ margin: 0;
+ flex: 1;
+ }
+ .ai-shots {
+ display: flex;
+ gap: var(--space-2xs);
+ }
+ .ai-shots button {
+ flex: 1;
+ aspect-ratio: 4 / 5;
+ padding: 0;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ background: #10141d;
+ overflow: hidden;
+ cursor: pointer;
+ transition: border-color 0.15s ease, transform 0.15s ease;
+ }
+ .ai-shots button:hover,
+ .ai-shots button:focus-visible {
+ border-color: var(--accent);
+ transform: translateY(-1px);
+ }
+ .ai-shots button[aria-pressed='true'] {
+ border-color: var(--accent);
+ }
+ .ai-shots img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .ai-actions {
+ display: flex;
+ gap: var(--space-xs);
+ margin-top: var(--space-2xs);
+ }
+ .ai-actions a,
+ .ai-actions button {
+ flex: 1;
+ text-align: center;
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ padding: 8px 10px;
+ border-radius: var(--radius-control);
+ border: 1px solid var(--stroke);
+ color: var(--ink);
+ background: var(--surface-2);
+ text-decoration: none;
+ cursor: pointer;
+ transition: border-color 0.15s ease, background 0.15s ease;
+ }
+ .ai-actions a:hover,
+ .ai-actions button:hover,
+ .ai-actions a:focus-visible,
+ .ai-actions button:focus-visible {
+ border-color: var(--accent);
+ background: var(--surface-3);
+ }
+ .ai-how {
+ margin-top: var(--space-2xl);
+ border-top: 1px solid var(--hairline);
+ padding-top: var(--space-xl);
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: var(--space-lg);
+ }
+ .ai-how h2 {
+ grid-column: 1 / -1;
+ font-family: var(--font-display);
+ font-size: var(--text-xl);
+ margin: 0;
+ }
+ .ai-step {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ padding: var(--space-md);
+ }
+ .ai-step h3 {
+ font-size: var(--text-md);
+ margin: 0 0 var(--space-2xs);
+ }
+ .ai-step p {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ margin: 0;
+ }
+ .ai-step code {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--accent);
+ word-break: break-all;
+ }
+ @media (max-width: 480px) {
+ .ai-wrap {
+ padding-left: var(--space-md);
+ padding-right: var(--space-md);
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <main class="ai-wrap">
+ <header class="ai-hero">
+ <span class="ai-badge">A2MCP service · $1.50 per identity · live on OKX.AI rails</span>
+ <h1>Every AI agent deserves a face.</h1>
+ <p>
+ The Agent Identity Studio turns a brand brief into a complete 3D identity: a rigged,
+ animation-ready GLB avatar plus posed, studio-lit renders — including a profile picture
+ that stays sharp at marketplace thumbnail size. The identities below were generated
+ end-to-end by the pipeline from the briefs shown, no manual touch-ups.
+ </p>
+ <div class="ai-cta">
+ <a class="btn btn-primary" href="/docs/okx-marketplace">Read the service docs</a>
+ <a class="btn" href="/api/okx/3d/catalog">Service catalog (JSON)</a>
+ </div>
+ </header>
+
+ <section class="ai-grid" id="identity-grid" aria-label="Demo agent identities">
+ <!-- cards rendered by src/agent-identities.js -->
+ </section>
+
+ <section class="ai-how">
+ <h2>How agents buy it</h2>
+ <div class="ai-step">
+ <h3>1 · Call create_identity</h3>
+ <p>
+ POST an MCP <code>tools/call</code> to
+ <code>https://three.ws/api/okx/3d/identity-studio</code> with an agent name and brief.
+ The 402 challenge quotes $1.50 in USDC; pay it and replay.
+ </p>
+ </div>
+ <div class="ai-step">
+ <h3>2 · Poll for free</h3>
+ <p>
+ <code>identity_status</code> costs nothing and drives the job: generation, humanoid
+ auto-rig, then each studio render. Typical time to done: 3–6 minutes.
+ </p>
+ </div>
+ <div class="ai-step">
+ <h3>3 · Own the identity</h3>
+ <p>
+ Deliverables: square PFP (1024 + 128 preview), full-body render set, and the rigged
+ GLB — usable in three.ws scenes, games, and any glTF runtime.
+ </p>
+ </div>
+ </section>
+ </main>
+
+ <script src="/nav.js"></script>
+ <script type="module" src="/src/agent-identities.js"></script>
+ <script src="/footer.js" defer></script>
+ </body>
+</html>
diff --git a/public/vanity/premium/index.html b/public/vanity/premium/index.html
new file mode 100644
index 000000000..0e64d4e02
--- /dev/null
+++ b/public/vanity/premium/index.html
@@ -0,0 +1,262 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8">
+ <title>Premium Vanity Inventory · Pre-ground Solana addresses · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="description" content="Buy a long, brandable Solana vanity address delivered instantly from stock — 4–5+ character prefixes the live grinder can't reach, ground ahead of time on batch CPU and sold via x402. Price scales with rarity.">
+ <link rel="icon" href="/favicon.ico">
+ <link rel="stylesheet" href="/footer.css">
+ <link rel="stylesheet" href="/nav.css">
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <meta property="og:title" content="Premium Vanity Inventory · three.ws">
+ <meta property="og:description" content="Long, brandable Solana vanity addresses, ground ahead of time and sold from stock. Delivered once, encrypted at rest, priced by rarity.">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Premium+Vanity+Inventory&amp;d=Buy+a+long+brandable+Solana+vanity+address+delivered+instantly+from+stock&amp;p=%2Fvanity%2Fpremium">
+ <meta name="twitter:card" content="summary_large_image">
+ <style>
+ * { box-sizing: border-box; }
+ :root {
+ --fg: #f0f0f0; --muted: #888; --dim: #666; --border: rgba(255,255,255,0.08);
+ --bg: #000; --card-bg: #0e0e10;
+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;
+ --radius: 12px;
+ --common:#94a3b8; --uncommon:#4ade80; --rare:#38bdf8; --epic:#a855f7; --legendary:#ffb020; --mythic:#ff5db1;
+ }
+ body { font: 15px/1.5 'Inter', system-ui, -apple-system, sans-serif; background:#000; color:var(--fg); margin:0; min-height:100vh; display:flex; flex-direction:column; }
+ main { flex:1; max-width:1100px; width:100%; margin:0 auto; padding:2.2rem 1rem 4rem; }
+ a { color:inherit; }
+ .hero { margin-bottom:1.4rem; }
+ h1 { font-size:2rem; margin:0 0 .4rem; font-family:var(--font-display); letter-spacing:-0.02em; line-height:1.05; }
+ .lede { color:var(--muted); margin:0; max-width:66ch; }
+ .lede a { color:#ffd54f; text-decoration:none; border-bottom:1px solid rgba(255,213,79,.4); }
+ .lede a:hover { border-bottom-color:#ffd54f; }
+
+ /* custody notice — required, prominent */
+ .custody { display:flex; gap:.7rem; align-items:flex-start; margin:1.3rem 0 0; padding:.9rem 1.1rem; border:1px solid rgba(255,176,32,.28); background:rgba(255,176,32,.06); border-radius:var(--radius); }
+ .custody .ic { font-size:1.1rem; line-height:1.3; }
+ .custody p { margin:0; font-size:.82rem; color:#e8d8b0; }
+ .custody b { color:#ffcf6b; }
+
+ /* stat strip */
+ .statstrip { display:flex; gap:.6rem; flex-wrap:wrap; margin:1.4rem 0 0; }
+ .stat { flex:1; min-width:130px; border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:.85rem 1rem; }
+ .stat .k { font-size:.72rem; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); }
+ .stat .v { font-size:1.5rem; font-weight:800; font-family:var(--font-display); margin-top:.15rem; }
+
+ /* controls */
+ .controls { display:flex; gap:.6rem; flex-wrap:wrap; align-items:center; margin:1.8rem 0 1.1rem; }
+ .controls select, .controls input[type=text] { font:inherit; font-size:.85rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.5rem .7rem; }
+ .controls input[type=text] { flex:1; min-width:140px; }
+ .controls select:focus, .controls input:focus { outline:none; border-color:rgba(255,255,255,.32); }
+ .controls label { font-size:.72rem; color:var(--dim); text-transform:uppercase; letter-spacing:.04em; }
+
+ /* grid */
+ .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:.9rem; }
+ .gcard { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1.1rem; position:relative; overflow:hidden; transition:transform .14s ease, border-color .15s ease; opacity:0; animation:fadein .4s ease forwards; }
+ .gcard:hover { transform:translateY(-2px); border-color:rgba(255,255,255,.16); }
+ .gcard::before { content:''; position:absolute; inset:0 auto 0 0; width:4px; background:var(--accent,#888); }
+ .gcard .badge { display:inline-flex; align-items:center; gap:.35rem; font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.06em; padding:.25rem .6rem; border-radius:999px; color:#000; }
+ .gcard .addr { font-family:ui-monospace,monospace; font-size:.92rem; margin:.7rem 0 .2rem; word-break:break-all; line-height:1.35; color:rgba(240,240,240,.55); }
+ .gcard .addr .hi { color:#fff; font-weight:700; }
+ .gcard .meta { display:flex; gap:1.2rem; margin-top:.7rem; font-size:.74rem; color:var(--dim); }
+ .gcard .meta b { color:#bbb; font-weight:700; display:block; font-size:.95rem; font-family:var(--font-display); }
+ .gcard .price { font-family:var(--font-display); font-size:1.5rem; font-weight:900; }
+ .gcard .acts { display:flex; gap:.5rem; margin-top:.95rem; }
+ .gcard .acts a, .gcard .acts button { font:inherit; font-size:.76rem; font-weight:600; text-decoration:none; color:var(--muted); background:none; border:1px solid var(--border); border-radius:7px; padding:.4rem .65rem; cursor:pointer; transition:color .15s, border-color .15s, transform .12s; }
+ .gcard .acts .buy { color:#000; background:#fff; border-color:#fff; font-weight:700; }
+ .gcard .acts a:hover, .gcard .acts button:hover { transform:translateY(-1px); }
+ .gcard .acts a:focus-visible, .gcard .acts button:focus-visible { outline:2px solid rgba(139,92,246,.7); outline-offset:2px; }
+ @keyframes fadein { to { opacity:1; } }
+
+ /* states */
+ .state { border:1px dashed var(--border); border-radius:var(--radius); padding:2.6rem 1.4rem; text-align:center; color:var(--muted); }
+ .state h3 { margin:0 0 .5rem; font-family:var(--font-display); color:#ccc; }
+ .state a.cta { display:inline-block; margin-top:.9rem; color:#000; background:#fff; text-decoration:none; font-weight:700; border-radius:8px; padding:.55rem 1.1rem; }
+ .skel { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); height:190px; position:relative; overflow:hidden; }
+ .skel::after { content:''; position:absolute; inset:0; background:linear-gradient(90deg,transparent,rgba(255,255,255,.05),transparent); transform:translateX(-100%); animation:shimmer 1.3s infinite; }
+ @keyframes shimmer { to { transform:translateX(100%); } }
+
+ /* buy dialog */
+ dialog.buy { border:1px solid var(--border); border-radius:14px; background:#0c0c0e; color:var(--fg); max-width:520px; width:92%; padding:0; }
+ dialog.buy::backdrop { background:rgba(0,0,0,.6); backdrop-filter:blur(3px); }
+ dialog.buy .inner { padding:1.5rem 1.6rem; }
+ dialog.buy h3 { margin:0 0 .3rem; font-family:var(--font-display); }
+ dialog.buy .addr { font-family:ui-monospace,monospace; font-size:.86rem; word-break:break-all; color:#cbd5e1; margin:.5rem 0 1rem; }
+ dialog.buy ol { margin:.4rem 0 1rem; padding-left:1.2rem; font-size:.85rem; color:var(--muted); }
+ dialog.buy code { background:#161616; border:1px solid var(--border); border-radius:6px; padding:.12rem .35rem; font-size:.8rem; word-break:break-all; }
+ dialog.buy .row { display:flex; gap:.6rem; margin-top:.4rem; }
+ dialog.buy .row button, dialog.buy .row a { font:inherit; font-weight:700; border-radius:8px; padding:.55rem 1rem; cursor:pointer; text-decoration:none; text-align:center; }
+ dialog.buy .copy { background:#fff; color:#000; border:none; }
+ dialog.buy .close { background:transparent; color:var(--muted); border:1px solid var(--border); }
+
+ [data-theme="light"] body { background:#fff; color:#111; }
+ [data-theme="light"] .gcard, [data-theme="light"] .stat, [data-theme="light"] dialog.buy { background:#fafafa; }
+ </style>
+</head>
+<body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main id="main">
+ <div class="hero">
+ <h1>Premium Vanity Inventory</h1>
+ <p class="lede">Long, brandable Solana addresses — 4–5+ character prefixes the live grinder can't reach — ground ahead of time on batch CPU and sold from stock. Buy one and the private key is delivered <strong>once</strong> over the <a href="/vanity/gallery">x402</a> rail, then its stored copy is destroyed. Need a fresh ≤3-char grind instead? Use the <a href="/vanity-wallet">live grinder</a>.</p>
+ </div>
+
+ <div class="custody" role="note">
+ <span class="ic">🔑</span>
+ <p id="custody-copy"><b>Custody:</b> these keys were generated by three.ws, not by you. For high-value use, treat a purchased address as a <b>token mint address</b> or sweep assets to a wallet you generated yourself — do not use it as a treasury. The key is delivered once and its ciphertext is destroyed on delivery, so three.ws cannot recover or re-send it.</p>
+ </div>
+
+ <div class="statstrip" id="stats" hidden>
+ <div class="stat"><div class="k">Available</div><div class="v" id="s-available">—</div></div>
+ <div class="stat"><div class="k">Price range</div><div class="v" id="s-price">—</div></div>
+ <div class="stat"><div class="k">Rarity tiers</div><div class="v" id="s-tiers">—</div></div>
+ <div class="stat"><div class="k">Sold</div><div class="v" id="s-sold">—</div></div>
+ </div>
+
+ <div class="controls">
+ <input type="text" id="q" placeholder="Filter by prefix (e.g. PUMP)" aria-label="Filter by prefix" autocomplete="off">
+ <label for="tier">Tier</label>
+ <select id="tier" aria-label="Rarity tier">
+ <option value="">All</option>
+ <option value="mythic">Mythic</option>
+ <option value="legendary">Legendary</option>
+ <option value="epic">Epic</option>
+ <option value="rare">Rare</option>
+ <option value="uncommon">Uncommon</option>
+ <option value="common">Common</option>
+ </select>
+ <label for="sort">Sort</label>
+ <select id="sort" aria-label="Sort">
+ <option value="rarity">Rarity</option>
+ <option value="price">Price ↑</option>
+ <option value="new">Newest</option>
+ </select>
+ </div>
+
+ <div id="list" aria-live="polite"></div>
+ </main>
+
+ <footer class="h-footer-horizon"><div class="h-footer-inner" style="text-align:center;padding:2rem 1rem;color:#555;font-size:.8rem">three.ws — premium vanity inventory · keys encrypted at rest · delivered once</div></footer>
+
+ <dialog class="buy" id="buy">
+ <div class="inner">
+ <h3>Buy this address</h3>
+ <div class="addr" id="buy-addr"></div>
+ <p style="font-size:.85rem;color:var(--muted);margin:.2rem 0 .6rem">Pay this x402 endpoint in USDC (Base or Solana) with any x402 client. The private key is returned once in the response, then destroyed server-side.</p>
+ <ol>
+ <li>Point an x402 client (<code>@x402/fetch</code>, a pay-capable agent, or the <code>vanity_premium</code> MCP tool) at the buy URL.</li>
+ <li>It pays the quoted price and receives the key <b>once</b>. Import it immediately.</li>
+ <li>Optional: append <code>&amp;sealTo=&lt;X25519 pubkey&gt;</code> to receive the key sealed to you (plaintext never in the response).</li>
+ </ol>
+ <div style="margin:.3rem 0 .2rem;font-size:.72rem;color:var(--dim);text-transform:uppercase;letter-spacing:.04em">Buy URL</div>
+ <code id="buy-url" style="display:block;padding:.55rem .6rem"></code>
+ <div class="row">
+ <button class="copy" id="buy-copy" type="button">Copy buy URL</button>
+ <a class="close" id="buy-explorer" target="_blank" rel="noopener">View on Solscan</a>
+ <button class="close" id="buy-close" type="button">Close</button>
+ </div>
+ </div>
+ </dialog>
+
+ <script type="module">
+ const API = '/api/x402/vanity-premium';
+ const listEl = document.getElementById('list');
+ const qEl = document.getElementById('q');
+ const tierEl = document.getElementById('tier');
+ const sortEl = document.getElementById('sort');
+ const TIER_COLOR = { common:'#94a3b8', uncommon:'#4ade80', rare:'#38bdf8', epic:'#a855f7', legendary:'#ffb020', mythic:'#ff5db1' };
+ let debounce;
+
+ function skeletons() {
+ listEl.innerHTML = '<div class="grid">' + Array.from({length:6}).map(()=>'<div class="skel"></div>').join('') + '</div>';
+ }
+ function esc(s){ return String(s).replace(/[&<>"]/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
+
+ function highlightAddr(addr, prefix, suffix) {
+ let out = esc(addr);
+ if (prefix) out = '<span class="hi">'+esc(addr.slice(0,prefix.length))+'</span>'+esc(addr.slice(prefix.length));
+ else if (suffix) out = esc(addr.slice(0,addr.length-suffix.length))+'<span class="hi">'+esc(addr.slice(addr.length-suffix.length))+'</span>';
+ return out;
+ }
+
+ function card(it) {
+ const color = TIER_COLOR[it.rarityTier] || '#888';
+ const el = document.createElement('div');
+ el.className = 'gcard';
+ el.style.setProperty('--accent', color);
+ el.innerHTML = `
+ <span class="badge" style="background:${color}">${esc(it.rarityTier)}</span>
+ <div class="addr">${highlightAddr(it.address, it.prefix, it.suffix)}</div>
+ <div class="meta">
+ <div><b>${esc(it.patternLabel)}</b>pattern</div>
+ <div><b>${it.rarityScore}</b>rarity</div>
+ <div><span class="price">$${it.priceUsd}</span></div>
+ </div>
+ <div class="acts">
+ <button class="buy" data-buy>Buy — $${it.priceUsd}</button>
+ <a href="https://solscan.io/account/${encodeURIComponent(it.address)}" target="_blank" rel="noopener">Explorer</a>
+ </div>`;
+ el.querySelector('[data-buy]').addEventListener('click', ()=>openBuy(it));
+ return el;
+ }
+
+ function openBuy(it) {
+ const url = new URL(it.buyUrl || (location.origin + API + '?address=' + encodeURIComponent(it.address)), location.origin);
+ document.getElementById('buy-addr').textContent = it.address;
+ document.getElementById('buy-url').textContent = url.href;
+ document.getElementById('buy-explorer').href = 'https://solscan.io/account/' + it.address;
+ const dlg = document.getElementById('buy');
+ document.getElementById('buy-copy').onclick = async () => {
+ try { await navigator.clipboard.writeText(url.href); document.getElementById('buy-copy').textContent = 'Copied ✓'; setTimeout(()=>document.getElementById('buy-copy').textContent='Copy buy URL',1500); } catch {}
+ };
+ document.getElementById('buy-close').onclick = () => dlg.close();
+ dlg.showModal();
+ }
+
+ async function load() {
+ skeletons();
+ const params = new URLSearchParams();
+ if (qEl.value.trim()) params.set('prefix', qEl.value.trim());
+ if (tierEl.value) params.set('tier', tierEl.value);
+ params.set('sort', sortEl.value);
+ params.set('limit', '100');
+ let data;
+ try {
+ const res = await fetch(API + '?' + params.toString(), { headers: { accept:'application/json' } });
+ if (!res.ok) throw new Error('HTTP ' + res.status);
+ data = await res.json();
+ } catch (err) {
+ listEl.innerHTML = `<div class="state"><h3>Couldn't load inventory</h3><p>${esc(err.message)}. The store may be warming up — try again.</p><a class="cta" href="#" onclick="location.reload();return false">Retry</a></div>`;
+ return;
+ }
+ if (data.custodyNotice) document.getElementById('custody-copy').innerHTML = '<b>Custody:</b> ' + esc(data.custodyNotice);
+ const s = data.stats || {};
+ document.getElementById('stats').hidden = false;
+ document.getElementById('s-available').textContent = s.available ?? 0;
+ document.getElementById('s-price').textContent = (s.available ? `$${s.minPrice}–$${s.maxPrice}` : '—');
+ document.getElementById('s-tiers').textContent = s.tiers ?? 0;
+ document.getElementById('s-sold').textContent = s.sold ?? 0;
+
+ const items = data.items || [];
+ if (!items.length) {
+ listEl.innerHTML = `<div class="state"><h3>${qEl.value||tierEl.value?'No matches':'Inventory is being ground'}</h3><p>${qEl.value||tierEl.value?'No available addresses match this filter — clear it to see everything in stock.':'New premium addresses are ground on batch CPU and land here as they finish. Check back shortly, or grind a fresh one now.'}</p><a class="cta" href="/vanity-wallet">Grind one live →</a></div>`;
+ return;
+ }
+ const grid = document.createElement('div');
+ grid.className = 'grid';
+ items.forEach((it, i) => { const c = card(it); c.style.animationDelay = (i*22) + 'ms'; grid.appendChild(c); });
+ listEl.innerHTML = '';
+ listEl.appendChild(grid);
+ }
+
+ qEl.addEventListener('input', () => { clearTimeout(debounce); debounce = setTimeout(load, 280); });
+ tierEl.addEventListener('change', load);
+ sortEl.addEventListener('change', load);
+ load();
+ </script>
+</body>
+</html>
diff --git a/scripts/okx-identity-demo.mjs b/scripts/okx-identity-demo.mjs
new file mode 100644
index 000000000..3575a2cb4
--- /dev/null
+++ b/scripts/okx-identity-demo.mjs
@@ -0,0 +1,121 @@
+#!/usr/bin/env node
+// Run the Agent Identity Studio pipeline for the demo identities in
+// data/agent-identities.json — REAL runs of the production pipeline (the same
+// module the /api/okx/3d/identity-studio endpoint executes), driven locally:
+//
+// node --env-file=.env.local scripts/okx-identity-demo.mjs [slug] [--force]
+//
+// Needs the S3_* (R2) vars from .env.local; generation/rig/render all run on
+// the deployed three.ws surfaces. Results (render URLs, GLB URLs, rig
+// verification) are written back into data/agent-identities.json, which powers
+// the /agent-identities showcase page. Rigging is VERIFIED programmatically:
+// the rigged GLB must contain a skin with joints and skinned primitives with
+// JOINTS_0 + WEIGHTS_0 attributes, or the run is recorded as failed.
+
+process.env.JWT_SECRET ||= 'okx-identity-local-demo'; // job tokens are local-only here
+
+import { readFileSync, writeFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const DATA_PATH = resolve(import.meta.dirname, '../data/agent-identities.json');
+const POLL_MS = 5000;
+const TIMEOUT_MS = 15 * 60 * 1000;
+
+const { createIdentityJob, advanceIdentityJob, describeIdentityJob } = await import(
+ '../api/_okx3d/identity.js'
+);
+
+// Parse a GLB's JSON chunk and assert real rigging: bones AND skin weights.
+async function verifyRiggedGlb(url) {
+ const res = await fetch(url, { signal: AbortSignal.timeout(60_000) });
+ if (!res.ok) throw new Error(`GLB fetch ${res.status}`);
+ const buf = Buffer.from(await res.arrayBuffer());
+ if (buf.length < 20 || buf.readUInt32LE(0) !== 0x46546c67) throw new Error('not a GLB');
+ const jsonLen = buf.readUInt32LE(12);
+ if (buf.readUInt32LE(16) !== 0x4e4f534a) throw new Error('first chunk is not JSON');
+ const doc = JSON.parse(buf.subarray(20, 20 + jsonLen).toString('utf8'));
+ const joints = (doc.skins || []).reduce((n, s) => n + (s.joints?.length || 0), 0);
+ const skinnedPrims = (doc.meshes || [])
+ .flatMap((m) => m.primitives || [])
+ .filter((p) => p.attributes && 'JOINTS_0' in p.attributes && 'WEIGHTS_0' in p.attributes);
+ if (!doc.skins?.length) throw new Error('no skins in GLB');
+ if (joints < 10) throw new Error(`only ${joints} joints`);
+ if (!skinnedPrims.length) throw new Error('no primitives carry JOINTS_0/WEIGHTS_0');
+ return {
+ bytes: buf.length,
+ skins: doc.skins.length,
+ joints,
+ skinnedPrimitives: skinnedPrims.length,
+ generator: doc.asset?.generator || null,
+ };
+}
+
+async function runIdentity(entry) {
+ console.log(`\n━━ ${entry.agentName} (${entry.kind}) ━━`);
+ const started = Date.now();
+ const { jobId, state: initial } = await createIdentityJob({
+ agentName: entry.agentName,
+ brief: entry.brief,
+ styleHints: entry.styleHints,
+ });
+ console.log(`job ${jobId.slice(0, 24)}… | prompt: ${initial.prompt.effective}`);
+
+ let state = initial;
+ while (Date.now() - started < TIMEOUT_MS) {
+ await new Promise((r) => setTimeout(r, POLL_MS));
+ state = await advanceIdentityJob(state.id);
+ const desc = describeIdentityJob(state);
+ process.stdout.write(
+ `\r ${desc.stage} (${desc.progress.renders_done}/${desc.progress.renders_total} renders) `,
+ );
+ if (desc.status === 'done' || desc.status === 'failed') break;
+ }
+ console.log('');
+ const desc = describeIdentityJob(state);
+ if (desc.status !== 'done') {
+ throw new Error(`run ended ${desc.status}: ${JSON.stringify(desc.last_error || 'timeout')}`);
+ }
+ const rig = await verifyRiggedGlb(desc.deliverables.rigged_glb_url);
+ console.log(
+ ` ✓ done in ${Math.round((Date.now() - started) / 1000)}s — rig verified: ` +
+ `${rig.joints} joints, ${rig.skinnedPrimitives} skinned primitives, ${Math.round(rig.bytes / 1024)}KB`,
+ );
+ return {
+ jobIdPrefix: jobId.slice(0, 16),
+ prompt: state.prompt.effective,
+ directed: Boolean(state.prompt.directed),
+ backend: state.gen.backend,
+ pfp: desc.deliverables.pfp,
+ fullBody: desc.deliverables.full_body,
+ riggedGlbUrl: desc.deliverables.rigged_glb_url,
+ meshGlbUrl: desc.deliverables.mesh_glb_url,
+ viewerUrl: desc.deliverables.viewer_url,
+ poseStudioUrl: desc.deliverables.pose_studio_url,
+ rigVerification: rig,
+ durationSeconds: Math.round((Date.now() - started) / 1000),
+ completedAt: new Date().toISOString(),
+ };
+}
+
+const args = process.argv.slice(2);
+const force = args.includes('--force');
+const only = args.find((a) => !a.startsWith('--'));
+
+const data = JSON.parse(readFileSync(DATA_PATH, 'utf8'));
+let failures = 0;
+for (const entry of data.identities) {
+ if (only && entry.slug !== only) continue;
+ if (entry.result && !force) {
+ console.log(`skip ${entry.slug} (already has a result; --force to rerun)`);
+ continue;
+ }
+ try {
+ entry.result = await runIdentity(entry);
+ writeFileSync(DATA_PATH, JSON.stringify(data, null, '\t') + '\n');
+ } catch (err) {
+ failures += 1;
+ console.error(` ✗ ${entry.slug} failed: ${err.message}`);
+ }
+}
+console.log(`\n${data.identities.filter((e) => e.result).length}/${data.identities.length} identities complete`);
+process.exit(failures ? 1 : 0);
diff --git a/scripts/vanity-inventory-load.mjs b/scripts/vanity-inventory-load.mjs
new file mode 100644
index 000000000..b14925b7b
--- /dev/null
+++ b/scripts/vanity-inventory-load.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+/**
+ * Load a batch grinder's ENCRYPTED inventory JSONL into the vanity_inventory
+ * table, and housekeeping for the store.
+ *
+ * The JSONL is produced by workers/vanity-grinder/grind.mjs. Each line already
+ * holds a SEALED secret (secret_ciphertext) — this loader never sees or writes a
+ * plaintext key; it just upserts records. Run it wherever DATABASE_URL points at
+ * the target DB (locally against a Neon branch, or in CI/prod).
+ *
+ * Usage:
+ * node scripts/vanity-inventory-load.mjs --file workers/vanity-grinder/out/inventory.jsonl
+ * node scripts/vanity-inventory-load.mjs --file <f> --dry-run
+ * node scripts/vanity-inventory-load.mjs --stats
+ * node scripts/vanity-inventory-load.mjs --sweep # destroy expired ciphertext
+ *
+ * Auth: reads DATABASE_URL from .env / .env.local / env. No interactive prompts.
+ * The vault key (WALLET_ENCRYPTION_KEY / VANITY_KMS_KEY) is NOT needed here — the
+ * loader stores ciphertext as-is; only the delivery endpoint ever decrypts.
+ */
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '..');
+
+// Load .env.local / .env like scripts/apply-migrations.mjs.
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1);
+ process.env[m[1]] = val;
+ }
+ break;
+ } catch { /* not present */ }
+}
+
+const args = process.argv.slice(2);
+const has = (f) => args.includes(f);
+const val = (f) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : null; };
+const DRY = has('--dry-run');
+
+if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is not set. Add it to .env.local or export it.');
+ process.exit(2);
+}
+
+const store = await import('../api/_lib/vanity-inventory-store.js');
+
+if (has('--stats')) {
+ const s = await store.inventoryStats();
+ console.log(JSON.stringify(s, null, 2));
+ process.exit(0);
+}
+
+if (has('--sweep')) {
+ const r = await store.sweepExpiredSecrets();
+ console.log(`Swept ${r.destroyed} expired ciphertext(s).`);
+ process.exit(0);
+}
+
+const file = val('--file');
+if (!file) {
+ console.error('Usage: --file <inventory.jsonl> | --stats | --sweep');
+ process.exit(2);
+}
+
+const lines = readFileSync(path.resolve(file), 'utf8').trim().split('\n').filter(Boolean);
+console.log(`Loading ${lines.length} record(s) from ${file}${DRY ? ' (dry-run)' : ''}…`);
+
+let inserted = 0, skipped = 0, bad = 0;
+for (const line of lines) {
+ let r;
+ try {
+ r = JSON.parse(line);
+ } catch {
+ bad++;
+ continue;
+ }
+ if (!r.address || !r.secretCiphertext) { bad++; continue; }
+ if (DRY) { inserted++; continue; }
+ try {
+ const res = await store.upsertInventoryItem({
+ address: r.address,
+ prefix: r.prefix,
+ suffix: r.suffix,
+ ignoreCase: r.ignoreCase,
+ patternLabel: r.patternLabel,
+ format: r.format,
+ difficultyAttempts: r.difficultyAttempts,
+ rarityBits: r.rarityBits,
+ rarityTier: r.rarityTier,
+ rarityScore: r.rarityScore,
+ secretCiphertext: r.secretCiphertext,
+ secretScheme: r.secretScheme,
+ priceUsd: r.priceUsd,
+ retentionDays: r.retentionDays ?? 0,
+ });
+ res.inserted ? inserted++ : skipped++;
+ } catch (err) {
+ console.error(` ! ${r.address}: ${err.message}`);
+ bad++;
+ }
+}
+
+console.log(`Done. inserted=${inserted} skipped(existing)=${skipped} bad=${bad}`);
+if (!DRY) {
+ const s = await store.inventoryStats();
+ console.log(`Inventory now: ${s.available} available, ${s.sold} sold, price $${s.minPrice}–$${s.maxPrice}.`);
+}
+process.exit(0);
diff --git a/src/agent-identities.js b/src/agent-identities.js
new file mode 100644
index 000000000..836684379
--- /dev/null
+++ b/src/agent-identities.js
@@ -0,0 +1,121 @@
+// /agent-identities — Agent Identity Studio showcase grid.
+//
+// Renders the demo identities from data/agent-identities.json (real pipeline
+// runs, written by scripts/okx-identity-demo.mjs). Each card: the full-body
+// hero shot with the PFP crop pinned on top, thumbnails to switch poses, and
+// a lazy "View in 3D" that swaps the image for a <model-viewer> of the rigged
+// GLB — heavy 3D loads only on request, never on page load.
+
+import data from '../data/agent-identities.json';
+
+const grid = document.getElementById('identity-grid');
+
+let modelViewerLoaded = false;
+function ensureModelViewer() {
+ if (modelViewerLoaded) return;
+ modelViewerLoaded = true;
+ const s = document.createElement('script');
+ s.type = 'module';
+ s.src = '/model-viewer-meshopt.js';
+ document.head.appendChild(s);
+}
+
+function el(tag, attrs = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of children) node.appendChild(c);
+ return node;
+}
+
+function card(identity) {
+ const { agentName, kind, brief, result } = identity;
+
+ const stage = el('div', { class: 'ai-stage' });
+ if (!result) {
+ // Every state designed: an entry without a completed run says so instead
+ // of rendering a broken card.
+ stage.appendChild(
+ el('div', { class: 'ai-pending', text: `${agentName} is still in the studio — check back soon.` }),
+ );
+ }
+
+ const bodyChildren = [
+ el('span', { class: 'ai-kind', text: kind }),
+ el('h2', { class: 'ai-name', text: agentName }),
+ el('p', { class: 'ai-brief', text: brief }),
+ ];
+
+ if (result) {
+ const hero = el('img', {
+ src: result.fullBody[0]?.url || result.pfp.url,
+ alt: `${agentName} — full-body 3D render`,
+ loading: 'lazy',
+ });
+ stage.appendChild(hero);
+ stage.appendChild(
+ el('div', { class: 'ai-pfp' }, [
+ el('img', { src: result.pfp.url, alt: `${agentName} profile picture crop`, loading: 'lazy' }),
+ ]),
+ );
+
+ const shots = el('div', { class: 'ai-shots', role: 'group', 'aria-label': `${agentName} poses` });
+ for (const shot of result.fullBody) {
+ const btn = el(
+ 'button',
+ {
+ type: 'button',
+ 'aria-label': `Show ${shot.pose} pose`,
+ 'aria-pressed': shot === result.fullBody[0] ? 'true' : 'false',
+ onclick: () => {
+ hero.src = shot.url;
+ const viewer = stage.querySelector('model-viewer');
+ if (viewer) {
+ viewer.remove();
+ hero.style.opacity = '1';
+ }
+ shots.querySelectorAll('button').forEach((b) => b.setAttribute('aria-pressed', 'false'));
+ btn.setAttribute('aria-pressed', 'true');
+ },
+ },
+ [el('img', { src: shot.url, alt: '', loading: 'lazy' })],
+ );
+ shots.appendChild(btn);
+ }
+ bodyChildren.push(shots);
+
+ const view3d = el('button', {
+ type: 'button',
+ text: 'View in 3D',
+ onclick: () => {
+ ensureModelViewer();
+ if (stage.querySelector('model-viewer')) return;
+ const viewer = el('model-viewer', {
+ src: result.riggedGlbUrl,
+ 'camera-controls': '',
+ 'touch-action': 'pan-y',
+ 'shadow-intensity': '0.6',
+ exposure: '1.05',
+ alt: `${agentName} rigged 3D avatar`,
+ });
+ hero.style.opacity = '0';
+ stage.appendChild(viewer);
+ view3d.textContent = 'Rotate · drag to orbit';
+ },
+ });
+ bodyChildren.push(
+ el('div', { class: 'ai-actions' }, [
+ view3d,
+ el('a', { href: result.viewerUrl, target: '_blank', rel: 'noopener', text: 'Open in viewer' }),
+ el('a', { href: result.poseStudioUrl, target: '_blank', rel: 'noopener', text: 'Pose studio' }),
+ ]),
+ );
+ }
+
+ return el('article', { class: 'ai-card' }, [stage, el('div', { class: 'ai-body' }, bodyChildren)]);
+}
+
+for (const identity of data.identities) grid.appendChild(card(identity));
diff --git a/tests/api/okx-3d-services.test.js b/tests/api/okx-3d-services.test.js
new file mode 100644
index 000000000..89c26f498
--- /dev/null
+++ b/tests/api/okx-3d-services.test.js
@@ -0,0 +1,422 @@
+/**
+ * Work order 03 — the decomposed 3D studio on OKX.AI
+ * (/api/okx/3d/<service>, catalog rows in api/_lib/okx-catalog.js, engines in
+ * api/_okx3d/rest-services.js).
+ *
+ * Covers, for EVERY paid REST service (no sampling): the catalog contract and
+ * price points, the per-service 402 (OKX dialect, X Layer accept first, the
+ * service's own amount), the free GET descriptor, the paid dispatch to the
+ * real engine seam, settle-only-after-success, and the failure paths that
+ * must never charge (invalid input, humanoid gate, engine 5xx, rejected
+ * payment).
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.X402_PAY_TO_XLAYER ||= '0x75d00a2713565171f33216e5aa2a375e076ecf69';
+process.env.X402_XLAYER_RELAYER_KEY ||=
+ '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';
+process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';
+process.env.JWT_SECRET ||= 'okx-3d-test-secret';
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcpIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcpUser: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcpOptimize: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ clientIp: vi.fn(() => '203.0.113.9'),
+}));
+
+vi.mock('../../api/_lib/usage.js', () => ({
+ recordEvent: vi.fn(),
+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+// Idempotency plumbing is DB-backed in prod; stub it to always-miss so the
+// paid path runs the engine (replay caching has its own suite).
+vi.mock('../../api/_lib/x402/payment-identifier-server.js', () => ({
+ PAYMENT_IDENTIFIER: 'payment-identifier',
+ extractIdFromHeader: vi.fn(() => null),
+ hashPaymentProof: vi.fn(() => null),
+ hashRequestPayload: vi.fn(() => 'payload-hash'),
+ paymentIdentifierExtension: vi.fn(() => ({})),
+ checkCache: vi.fn(async () => ({ kind: 'miss' })),
+ storeResponse: vi.fn(async () => {}),
+ writeCachedResponse: vi.fn(),
+ writeConflict: vi.fn(),
+ reservePaymentProof: vi.fn(async () => ({ ok: true, release: async () => {} })),
+}));
+
+// Payment verification/settlement are exercised against the live rail in the
+// WO-04 gauntlet; here they are seams — the suite asserts WHEN they run
+// (verify before engine, settle only after success), not chain mechanics.
+const verifyPaymentMock = vi.fn();
+const settlePaymentMock = vi.fn();
+vi.mock('../../api/_lib/x402-spec.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return {
+ ...real,
+ verifyPayment: (...args) => verifyPaymentMock(...args),
+ settlePayment: (...args) => settlePaymentMock(...args),
+ };
+});
+
+vi.mock('../../api/_lib/r2.js', () => ({
+ putObject: vi.fn(async () => {}),
+ getObjectBuffer: vi.fn(async () => Buffer.alloc(0)),
+ headObject: vi.fn(async () => ({ ContentLength: 1 })),
+ publicUrl: (key) => `https://cdn.test/${key}`,
+}));
+
+// Programmable fetch router over the engine's HTTP surfaces (/api/forge).
+const fetchRoutes = {};
+function jsonResponse(status, body) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+const realFetch = globalThis.fetch;
+beforeEach(() => {
+ verifyPaymentMock.mockReset();
+ settlePaymentMock.mockReset();
+ verifyPaymentMock.mockImplementation(async ({ requirements }) => ({
+ paymentPayload: { x402Version: 2 },
+ requirement: Array.isArray(requirements) ? requirements[0] : requirements,
+ payer: '0x75d00a2713565171f33216e5aa2a375e076ecf69',
+ }));
+ settlePaymentMock.mockResolvedValue({
+ success: true,
+ transaction: '0xsettled',
+ network: 'eip155:196',
+ payer: '0x75d00a2713565171f33216e5aa2a375e076ecf69',
+ });
+ fetchRoutes.forgeSubmit = () => jsonResponse(200, { job_id: 'forge-gen-1', status: 'queued' });
+ fetchRoutes.rig = () => jsonResponse(200, { job_id: 'forge-rig-1', status: 'queued' });
+ fetchRoutes.forgePoll = () => jsonResponse(200, { status: 'running' });
+ fetchRoutes.chat = () => new Response(null, { status: 503 }); // director down → fail-soft
+ fetchRoutes.other = () => new Response('not found', { status: 404 });
+ globalThis.fetch = vi.fn(async (url, init = {}) => {
+ const u = String(url);
+ if (u.includes('/api/chat')) return fetchRoutes.chat(u, init);
+ if (u.includes('/api/forge?action=rig')) return fetchRoutes.rig(u, init);
+ if (u.includes('/api/forge?job=')) return fetchRoutes.forgePoll(u, init);
+ if (u.includes('/api/forge')) return fetchRoutes.forgeSubmit(u, init);
+ return fetchRoutes.other(u, init);
+ });
+ return () => {
+ globalThis.fetch = realFetch;
+ };
+});
+
+const {
+ OKX_CATALOG,
+ catalogEntry,
+ catalogIndex,
+ listingDescription,
+ validateCatalog,
+} = await import('../../api/_lib/okx-catalog.js');
+const studioCatalog = await import('../../api/_mcp3d/catalog.js');
+const { default: handler } = await import('../../api/okx/3d/[service].js');
+
+const PAID_REST_IDS = [
+ 'text-to-3d',
+ 'text-to-3d-pro',
+ 'image-to-3d',
+ 'rig',
+ 'avatar',
+ 'retarget',
+ 'pose-seed',
+ 'fbx-export',
+];
+
+// Valid POST bodies per service, used by both the 402 and the paid tests.
+const VALID_INPUT = {
+ 'text-to-3d': { prompt: 'a brass steampunk owl' },
+ 'text-to-3d-pro': { prompt: 'a brass steampunk owl', tier: 'high' },
+ 'image-to-3d': { image_urls: ['https://example.com/owl-front.jpg'] },
+ rig: { glb_url: 'https://cdn.test/owl.glb' },
+ avatar: { prompt: 'a heroic knight character, full body' },
+ retarget: { model_url: 'https://cdn.test/knight-rigged.glb', animation: 'idle' },
+ 'pose-seed': { prompt: 'confident standing pose, arms crossed' },
+ 'fbx-export': { model_url: 'https://cdn.test/knight-rigged.glb' },
+};
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', service, headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : JSON.stringify(body);
+ const req = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ req.method = method;
+ req.url = `/api/okx/3d/${service}`;
+ req.query = { service };
+ req.headers = {
+ 'content-type': 'application/json',
+ host: 'three.ws',
+ 'x-forwarded-proto': 'https',
+ ...headers,
+ };
+ return req;
+}
+
+const decode402Header = (res) =>
+ JSON.parse(Buffer.from(res.headers['payment-required'], 'base64').toString('utf8'));
+
+describe('okx catalog — work order 03 rows', () => {
+ it('all eight decomposed services exist at the work-order price points', () => {
+ expect(validateCatalog()).toBe(true);
+ const prices = Object.fromEntries(
+ OKX_CATALOG.map((e) => [e.id, [e.priceUsd, e.amountAtomics]]),
+ );
+ expect(prices['text-to-3d']).toEqual(['0.01', '10000']);
+ expect(prices['text-to-3d-pro']).toEqual(['0.30', '300000']);
+ expect(prices['image-to-3d']).toEqual(['0.30', '300000']);
+ expect(prices.rig).toEqual(['0.25', '250000']);
+ expect(prices.avatar).toEqual(['0.50', '500000']);
+ expect(prices.retarget).toEqual(['0.10', '100000']);
+ expect(prices['pose-seed']).toEqual(['0.02', '20000']);
+ expect(prices['fbx-export']).toEqual(['0.10', '100000']);
+ });
+
+ it('every paid row routes /api/okx/3d/<id>, is POST-documented, and its listing description joins the two parts', () => {
+ for (const id of PAID_REST_IDS) {
+ const e = catalogEntry(id);
+ expect(e.endpoint).toBe(`https://three.ws/api/okx/3d/${id}`);
+ expect(e.inputSchema).toBeTruthy();
+ expect(listingDescription(e)).toBe(`${e.describes.capability}\n${e.describes.input}`);
+ }
+ });
+
+ it('the free catalog index carries every service 1:1', () => {
+ const ids = catalogIndex().services.map((s) => s.id);
+ for (const id of PAID_REST_IDS) expect(ids).toContain(id);
+ });
+
+ it('the paid MCP tools each service maps to exist on the studio engine', () => {
+ for (const tool of ['apply_animation', 'pose_model', 'remesh_model']) {
+ expect(studioCatalog.TOOLS[tool]?.handler).toBeTypeOf('function');
+ }
+ });
+});
+
+describe('per-service 402 (unpaid POST)', () => {
+ for (const id of PAID_REST_IDS) {
+ it(`${id}: OKX-dialect 402, X Layer accept first, its own amount`, async () => {
+ const res = makeRes();
+ await handler(makeReq({ service: id, body: VALID_INPUT[id] }), res);
+ expect(res.statusCode).toBe(402);
+ const entry = catalogEntry(id);
+ const header = decode402Header(res);
+ const body = JSON.parse(res.body);
+ expect(body).toEqual(header); // header and body carry the same envelope
+ expect(body.x402Version).toBe(2);
+ expect(body.resource.url).toBe(`https://three.ws/api/okx/3d/${id}`);
+ expect(body.resource.mimeType).toBe('application/json');
+ const first = body.accepts[0];
+ expect(first.scheme).toBe('exact');
+ expect(first.network).toBe('eip155:196');
+ expect(first.amount).toBe(entry.amountAtomics);
+ expect(first.payTo.toLowerCase()).toBe('0x75d00a2713565171f33216e5aa2a375e076ecf69');
+ expect(first.asset.toLowerCase()).toBe('0x779ded0c9e1022225f8e0630b35a9b54be713736');
+ expect(first.maxTimeoutSeconds).toBe(86400);
+ expect(first.extra).toMatchObject({
+ symbol: 'USDT',
+ name: 'USD₮0',
+ version: '1',
+ transferMethod: 'eip3009',
+ });
+ // One service, one price: every advertised rail quotes the same amount.
+ for (const a of body.accepts) expect(a.amount).toBe(entry.amountAtomics);
+ expect(settlePaymentMock).not.toHaveBeenCalled();
+ });
+ }
+
+ it('GET is the free per-service descriptor (price + schema, no payment)', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', service: 'rig' }), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.price_usd).toBe('0.25');
+ expect(body.input_schema.required).toEqual(['glb_url']);
+ expect(body.method).toBe('POST');
+ });
+});
+
+describe('paid dispatch — verify → engine → settle', () => {
+ function paidReq(service, body) {
+ return makeReq({ service, body, headers: { 'payment-signature': 'c2ln' } });
+ }
+
+ it('text-to-3d runs the free NVIDIA NIM lane (draft) and returns a pollable job', async () => {
+ const res = makeRes();
+ await handler(paidReq('text-to-3d', VALID_INPUT['text-to-3d']), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body).toMatchObject({ service: 'text-to-3d', price_usd: '0.01', status: 'queued', job_id: 'forge-gen-1' });
+ expect(body.poll_url).toContain('/api/forge?job=');
+ const submit = globalThis.fetch.mock.calls.find(([u]) => String(u).endsWith('/api/forge'));
+ expect(JSON.parse(submit[1].body)).toMatchObject({ backend: 'nvidia', path: 'image' });
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ expect(res.headers['payment-response']).toBeTruthy();
+ expect(res.headers['x-payment-response']).toBe(res.headers['payment-response']);
+ });
+
+ it('text-to-3d-pro survives a downed art director (fail-soft) and submits the original prompt', async () => {
+ const res = makeRes();
+ await handler(paidReq('text-to-3d-pro', VALID_INPUT['text-to-3d-pro']), res);
+ expect(res.statusCode).toBe(200);
+ const submit = globalThis.fetch.mock.calls.find(([u]) => String(u).endsWith('/api/forge'));
+ expect(JSON.parse(submit[1].body).prompt).toBe('a brass steampunk owl');
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('image-to-3d forwards the reference views to the reconstruct lane', async () => {
+ const res = makeRes();
+ await handler(paidReq('image-to-3d', VALID_INPUT['image-to-3d']), res);
+ expect(res.statusCode).toBe(200);
+ const submit = globalThis.fetch.mock.calls.find(([u]) => String(u).endsWith('/api/forge'));
+ expect(JSON.parse(submit[1].body).image_urls).toEqual(VALID_INPUT['image-to-3d'].image_urls);
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('rig submits the UniRig job and returns it pollable', async () => {
+ const res = makeRes();
+ await handler(paidReq('rig', VALID_INPUT.rig), res);
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body)).toMatchObject({ status: 'queued', job_id: 'forge-rig-1', mode: 'rig' });
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('avatar chains generate → rig and returns the mesh even while the rig job polls', async () => {
+ fetchRoutes.forgeSubmit = () =>
+ jsonResponse(200, { status: 'done', glb_url: 'https://cdn.test/knight.glb' });
+ const res = makeRes();
+ await handler(paidReq('avatar', VALID_INPUT.avatar), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body).toMatchObject({
+ service: 'avatar',
+ status: 'queued',
+ job_id: 'forge-rig-1',
+ mode: 'avatar',
+ mesh_glb_url: 'https://cdn.test/knight.glb',
+ });
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('pose-seed resolves deterministically in-process — same prompt, same seed, real engine', async () => {
+ const res1 = makeRes();
+ await handler(paidReq('pose-seed', VALID_INPUT['pose-seed']), res1);
+ expect(res1.statusCode).toBe(200);
+ const first = JSON.parse(res1.body);
+ expect(first.status).toBe('done');
+ expect(first.seed ?? first.pose ?? first.rotations ?? first.preset).toBeDefined();
+ const res2 = makeRes();
+ await handler(paidReq('pose-seed', VALID_INPUT['pose-seed']), res2);
+ expect(JSON.parse(res2.body)).toEqual(first);
+ expect(settlePaymentMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('retarget routes to the apply_animation engine and settles only on success', async () => {
+ const original = studioCatalog.TOOLS.apply_animation.handler;
+ studioCatalog.TOOLS.apply_animation.handler = vi.fn(async (args) => ({
+ content: [{ type: 'text', text: 'ok' }],
+ structuredContent: { animation: args.animation, coverage: 0.97, clip: { tracks: 12 } },
+ }));
+ try {
+ const res = makeRes();
+ await handler(paidReq('retarget', VALID_INPUT.retarget), res);
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body)).toMatchObject({ status: 'done', animation: 'idle', coverage: 0.97 });
+ expect(studioCatalog.TOOLS.apply_animation.handler).toHaveBeenCalledTimes(1);
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ } finally {
+ studioCatalog.TOOLS.apply_animation.handler = original;
+ }
+ });
+
+ it('fbx-export routes to remesh_model convert with rig-preserving fbx default', async () => {
+ const original = studioCatalog.TOOLS.remesh_model.handler;
+ studioCatalog.TOOLS.remesh_model.handler = vi.fn(async (args) => {
+ expect(args).toMatchObject({ operation: 'convert', format: 'fbx' });
+ return { content: [{ type: 'text', text: 'ok' }], structuredContent: { job_id: 'remesh-1' } };
+ });
+ try {
+ const res = makeRes();
+ await handler(paidReq('fbx-export', VALID_INPUT['fbx-export']), res);
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body)).toMatchObject({ status: 'queued', job_id: 'remesh-1', format: 'fbx' });
+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);
+ } finally {
+ studioCatalog.TOOLS.remesh_model.handler = original;
+ }
+ });
+});
+
+describe('failure paths never charge', () => {
+ function paidReq(service, body) {
+ return makeReq({ service, body, headers: { 'payment-signature': 'c2ln' } });
+ }
+
+ it('invalid input → 400 before any engine call, no settle', async () => {
+ const res = makeRes();
+ await handler(paidReq('text-to-3d', { prompt: 'x' }), res); // below minLength 3
+ expect(res.statusCode).toBe(400);
+ expect(settlePaymentMock).not.toHaveBeenCalled();
+ expect(globalThis.fetch.mock.calls.find(([u]) => String(u).includes('/api/forge'))).toBeUndefined();
+ });
+
+ it('avatar humanoid gate steers objects away without charging', async () => {
+ const res = makeRes();
+ await handler(paidReq('avatar', { prompt: 'a wooden chair' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error_description || JSON.parse(res.body).message).toMatch(/humanoid/i);
+ expect(settlePaymentMock).not.toHaveBeenCalled();
+ });
+
+ it('engine 5xx → 502, explicit "payment was not taken", no settle', async () => {
+ fetchRoutes.forgeSubmit = () => jsonResponse(500, { message: 'kaboom' });
+ const res = makeRes();
+ await handler(paidReq('text-to-3d', VALID_INPUT['text-to-3d']), res);
+ expect(res.statusCode).toBeGreaterThanOrEqual(500);
+ expect(res.body).toMatch(/payment was not taken/);
+ expect(settlePaymentMock).not.toHaveBeenCalled();
+ });
+
+ it('rejected payment → fresh OKX 402 with the error surfaced, engine never runs', async () => {
+ const { X402Error } = await import('../../api/_lib/x402-errors.js');
+ verifyPaymentMock.mockRejectedValueOnce(new X402Error('invalid_payment', 'insufficient_balance', 402));
+ const res = makeRes();
+ await handler(paidReq('rig', VALID_INPUT.rig), res);
+ expect(res.statusCode).toBe(402);
+ const body = JSON.parse(res.body);
+ expect(body.error).toBe('insufficient_balance');
+ expect(body.accepts[0].network).toBe('eip155:196');
+ expect(globalThis.fetch.mock.calls.find(([u]) => String(u).includes('action=rig'))).toBeUndefined();
+ expect(settlePaymentMock).not.toHaveBeenCalled();
+ });
+
+ it('settle failure after delivered work surfaces the x402 error path', async () => {
+ const { X402Error } = await import('../../api/_lib/x402-errors.js');
+ settlePaymentMock.mockRejectedValueOnce(new X402Error('settle_failed', 'facilitator down', 502));
+ const res = makeRes();
+ await handler(paidReq('text-to-3d', VALID_INPUT['text-to-3d']), res);
+ expect(res.statusCode).toBe(502);
+ expect(res.body).toMatch(/settle|facilitator/i);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 6a5119005..60de9cc52 100644
--- a/vercel.json
+++ b/vercel.json
@@ -43,7 +43,7 @@
},
"api/okx/3d/[service].js": {
"includeFiles": "{node_modules/@img/sharp-libvips-linux-x64/**,node_modules/@img/sharp-linux-x64/**}",
- "maxDuration": 120
+ "maxDuration": 300
},
"api/widgets/[id]/knowledge-process.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
diff --git a/vite.config.js b/vite.config.js
index 572cbe2d4..9266d2e4e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -537,6 +537,7 @@ const appConfig = {
'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),
'vanity-verify': resolve(__dirname, 'public/vanity/verify/index.html'),
'vanity-gallery': resolve(__dirname, 'public/vanity/gallery/index.html'),
+ 'vanity-premium': resolve(__dirname, 'public/vanity/premium/index.html'),
'vanity-bounties': resolve(__dirname, 'public/vanity/bounties/index.html'),
'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),
'evm-wallet': resolve(__dirname, 'public/evm-wallet.html'),
@@ -1052,6 +1053,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/vanity/verify/': resolve(root, 'public/vanity/verify/index.html'),
'/vanity/gallery': resolve(root, 'public/vanity/gallery/index.html'),
'/vanity/gallery/': resolve(root, 'public/vanity/gallery/index.html'),
+ '/vanity/premium': resolve(root, 'public/vanity/premium/index.html'),
+ '/vanity/premium/': resolve(root, 'public/vanity/premium/index.html'),
'/vanity/bounties': resolve(root, 'public/vanity/bounties/index.html'),
'/vanity/bounties/': resolve(root, 'public/vanity/bounties/index.html'),
'/evm-wallet': resolve(root, 'public/evm-wallet.html'),