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(x402): add mint-to-mesh endpoint, refactor x402-spec, expand discovery

nirholasa31543abf682
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 821ab64cd..5e431df98 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -198,33 +198,14 @@ export const env = {
return opt('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
},
- // Coinbase Developer Platform (CDP) facilitator. Required to be indexed by
- // agentic.market / the CDP Bazaar — only endpoints whose first verify+settle
- // is processed by CDP get cataloged. PayAI is not Bazaar-cataloged.
- // Auth uses ES256 JWT signed with the CDP API key (per Coinbase Cloud auth).
- get X402_CDP_FACILITATOR_URL() {
- return trimSlash(
- opt(
- 'X402_CDP_FACILITATOR_URL',
- 'https://api.cdp.coinbase.com/platform/v2/x402/facilitator',
- ),
- );
- },
- get CDP_API_KEY_ID() {
- return opt('CDP_API_KEY_ID');
- },
- // PEM-encoded ECDSA P-256 private key (BEGIN EC PRIVATE KEY ... END EC PRIVATE KEY).
- // In Vercel, paste the full multi-line PEM as the value (newlines preserved).
- get CDP_API_KEY_SECRET() {
- return opt('CDP_API_KEY_SECRET');
- },
-
// EVM mainnet chains accepted by /api/x402/* paid endpoints — defaults to
// Base + Arbitrum because those are the two CDP-Bazaar-supported networks
// the seller wizard currently exposes. Comma-separated CAIP-2 IDs.
get X402_EVM_NETWORKS() {
return opt('X402_EVM_NETWORKS', 'eip155:8453,eip155:42161')
- .split(',').map((s) => s.trim()).filter(Boolean);
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
},
// Native (non-bridged) USDC on Arbitrum One mainnet.
get X402_ASSET_ADDRESS_ARBITRUM() {
diff --git a/api/_lib/glb-themer.js b/api/_lib/glb-themer.js
new file mode 100644
index 000000000..ce301ed53
--- /dev/null
+++ b/api/_lib/glb-themer.js
@@ -0,0 +1,164 @@
+// Procedural GLB synthesis — "mint to mesh".
+//
+// Builds a unit-cube glTF 2.0 binary with a single PBR material, an optional
+// baseColor texture (typically the token's off-chain image), and a hashed
+// baseColorFactor derived from the mint address. The resulting GLB is small
+// (typically 1–60 KB) and a fully-conformant glTF 2.0 file — any Three.js,
+// Babylon.js, or model-viewer instance renders it directly.
+//
+// Used by /api/x402/mint-to-mesh to produce a 3D representation of a Solana
+// fungible token on demand.
+
+import { Document, NodeIO } from '@gltf-transform/core';
+
+// Cube centered at origin with side 1. 24 verts (6 faces × 4 corners) so each
+// face has its own face normal and UV island. 36 indices (6 × 2 triangles).
+//
+// UV layout: each face occupies the full [0,1]² square, so a single 2D image
+// shows on every face. Wound CCW when viewed from outside.
+const CUBE = {
+ positions: new Float32Array([
+ // +X
+ 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
+ // -X
+ -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5,
+ // +Y
+ -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
+ // -Y
+ -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5,
+ // +Z
+ -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
+ // -Z
+ 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5,
+ ]),
+ normals: new Float32Array([
+ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
+ -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0,
+ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
+ 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
+ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
+ 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,
+ ]),
+ uvs: new Float32Array([
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ ]),
+ indices: new Uint16Array([
+ 0, 1, 2, 0, 2, 3,
+ 4, 5, 6, 4, 6, 7,
+ 8, 9, 10, 8, 10, 11,
+ 12, 13, 14, 12, 14, 15,
+ 16, 17, 18, 16, 18, 19,
+ 20, 21, 22, 20, 22, 23,
+ ]),
+};
+
+// Stable color-from-string. Returns [r, g, b] in [0,1] — saturated, mid-light.
+// Built so visually-similar mints (shared prefix, same script) still get
+// distinct hues; tiny edits to the input change the hash a lot.
+export function colorFromMint(mint) {
+ let h = 2166136261 >>> 0;
+ for (let i = 0; i < mint.length; i++) {
+ h ^= mint.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ const hue = (h >>> 0) % 360;
+ return hslToRgb(hue / 360, 0.7, 0.55);
+}
+
+function hslToRgb(h, s, l) {
+ if (s === 0) return [l, l, l];
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ return [hueToRgb(p, q, h + 1 / 3), hueToRgb(p, q, h), hueToRgb(p, q, h - 1 / 3)];
+}
+
+function hueToRgb(p, q, t) {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+}
+
+/**
+ * Build a binary glTF 2.0 (GLB) cube themed for a Solana token.
+ *
+ * @param {object} opts
+ * @param {string} opts.mint Solana mint address (used as fallback name + color seed)
+ * @param {string|null} [opts.name] Token name from on-chain Metaplex metadata
+ * @param {string|null} [opts.symbol] Token symbol from on-chain Metaplex metadata
+ * @param {Uint8Array|null} [opts.image] Image bytes (PNG/JPEG). When omitted, the cube is color-only.
+ * @param {string|null} [opts.imageMimeType] Image MIME type (image/png or image/jpeg). Required iff `image` is set.
+ * @param {[number,number,number]} [opts.color] RGB in [0,1]. Defaults to colorFromMint(mint).
+ * @param {object} [opts.extras] Additional asset.extras key/values to include.
+ * @returns {Promise<Uint8Array>} GLB bytes.
+ */
+export async function createThemedGLB({
+ mint,
+ name = null,
+ symbol = null,
+ image = null,
+ imageMimeType = null,
+ color = null,
+ extras = {},
+}) {
+ if (!mint) throw new Error('createThemedGLB: mint is required');
+ const rgb = color || colorFromMint(mint);
+ const safeName = (name || symbol || mint.slice(0, 8)).toString().trim().slice(0, 64);
+ const safeSymbol = (symbol || mint.slice(0, 6)).toString().trim().slice(0, 16);
+
+ const doc = new Document();
+ doc.createBuffer();
+
+ doc.getRoot().getAsset().generator = 'three.ws mint-to-mesh / @gltf-transform';
+ doc.getRoot().getAsset().extras = {
+ mint,
+ name: safeName,
+ symbol: safeSymbol,
+ generatedAt: new Date().toISOString(),
+ generator: 'https://three.ws/api/x402/mint-to-mesh',
+ ...extras,
+ };
+
+ const positions = doc
+ .createAccessor('cube_positions')
+ .setType('VEC3')
+ .setArray(CUBE.positions);
+ const normals = doc.createAccessor('cube_normals').setType('VEC3').setArray(CUBE.normals);
+ const uvs = doc.createAccessor('cube_uvs').setType('VEC2').setArray(CUBE.uvs);
+ const indices = doc.createAccessor('cube_indices').setType('SCALAR').setArray(CUBE.indices);
+
+ const material = doc
+ .createMaterial(safeSymbol)
+ .setBaseColorFactor([rgb[0], rgb[1], rgb[2], 1])
+ .setMetallicFactor(0.05)
+ .setRoughnessFactor(0.6)
+ .setDoubleSided(false);
+
+ if (image && imageMimeType) {
+ const tex = doc.createTexture(safeSymbol).setImage(image).setMimeType(imageMimeType);
+ material.setBaseColorTexture(tex);
+ }
+
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', positions)
+ .setAttribute('NORMAL', normals)
+ .setAttribute('TEXCOORD_0', uvs)
+ .setIndices(indices)
+ .setMaterial(material);
+
+ const mesh = doc.createMesh(safeSymbol).addPrimitive(prim);
+ const node = doc.createNode(safeSymbol).setMesh(mesh);
+ const scene = doc.createScene(safeName).addChild(node);
+ doc.getRoot().setDefaultScene(scene);
+
+ const io = new NodeIO();
+ return io.writeBinary(doc);
+}
diff --git a/api/_lib/solana-token-meta.js b/api/_lib/solana-token-meta.js
new file mode 100644
index 000000000..a59d92946
Binary files /dev/null and b/api/_lib/solana-token-meta.js differ
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 00bbc05c0..55ae0ca98 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -31,7 +31,6 @@
// 5. Server POSTs facilitator /settle (same body) → { success, transaction, network, payer }
// Server attaches a base64 settlement object as `X-PAYMENT-RESPONSE` on the success reply.
-import { createPrivateKey, createSign, randomBytes, sign } from 'crypto';
import { env } from './env.js';
export const X402_VERSION = 2;
@@ -94,154 +93,12 @@ function facilitatorFor(network) {
network === NETWORK_SOLANA_DEVNET ||
network === 'solana'
)
- return {
- url: env.X402_FACILITATOR_URL_SOLANA,
- token: env.X402_FACILITATOR_TOKEN_SOLANA,
- kind: 'bearer',
- };
- if (
- network === NETWORK_BASE_MAINNET ||
- network === NETWORK_BASE_SEPOLIA ||
- network === 'base'
- ) {
- // Prefer CDP when keys are configured — required for agentic.market /
- // CDP Bazaar indexing. PayAI is a fine fallback for anyone running outside
- // the Bazaar ecosystem.
- if (env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET) {
- return { url: env.X402_CDP_FACILITATOR_URL, kind: 'cdp' };
- }
- return {
- url: env.X402_FACILITATOR_URL_BASE,
- token: env.X402_FACILITATOR_TOKEN_BASE,
- kind: 'bearer',
- };
- }
+ return { url: env.X402_FACILITATOR_URL_SOLANA, token: env.X402_FACILITATOR_TOKEN_SOLANA };
+ if (network === NETWORK_BASE_MAINNET || network === NETWORK_BASE_SEPOLIA || network === 'base')
+ return { url: env.X402_FACILITATOR_URL_BASE, token: env.X402_FACILITATOR_TOKEN_BASE };
throw new X402Error('unsupported_network', `unsupported network: ${network}`, 400);
}
-// Coinbase Cloud / CDP API auth: per-request JWT signed with the account's
-// API secret. CDP issues two key formats today:
-// * Ed25519 — secret is base64-encoded 32-byte seed or 64-byte (seed||pub).
-// Newer CDP keys default to this. Signed with EdDSA.
-// * ECDSA P-256 — secret is a PEM-encoded EC private key. Signed with ES256.
-// The `uri` claim binds the JWT to the exact request, so we mint per-request.
-//
-// Spec: https://docs.cdp.coinbase.com/api-reference/v2/authentication
-function loadCdpKey() {
- const secret = env.CDP_API_KEY_SECRET;
- if (!secret) throw new X402Error('cdp_not_configured', 'CDP_API_KEY_SECRET not set', 500);
- if (secret.includes('-----BEGIN')) {
- let key;
- try {
- key = createPrivateKey({ key: secret, format: 'pem' });
- } catch (err) {
- throw new X402Error(
- 'cdp_bad_key',
- `CDP_API_KEY_SECRET PEM parse failed: ${err.message}`,
- 500,
- );
- }
- if (key.asymmetricKeyType !== 'ec') {
- throw new X402Error('cdp_bad_key', 'CDP PEM secret must be an ECDSA P-256 key', 500);
- }
- return { alg: 'ES256', key };
- }
- // Base64-encoded raw Ed25519: 32-byte seed or 64-byte seed||pub.
- let raw;
- try {
- raw = Buffer.from(secret, 'base64');
- } catch (err) {
- throw new X402Error(
- 'cdp_bad_key',
- `CDP_API_KEY_SECRET base64 decode failed: ${err.message}`,
- 500,
- );
- }
- const seed = raw.length === 64 ? raw.subarray(0, 32) : raw.length === 32 ? raw : null;
- if (!seed) {
- throw new X402Error(
- 'cdp_bad_key',
- `CDP_API_KEY_SECRET: expected PEM EC key or 32/64-byte base64 Ed25519 (got ${raw.length} bytes)`,
- 500,
- );
- }
- // Wrap raw seed in PKCS#8 DER so node:crypto accepts it.
- const pkcs8 = Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]);
- let key;
- try {
- key = createPrivateKey({ key: pkcs8, format: 'der', type: 'pkcs8' });
- } catch (err) {
- throw new X402Error('cdp_bad_key', `CDP Ed25519 key import failed: ${err.message}`, 500);
- }
- return { alg: 'EdDSA', key };
-}
-
-let cdpKeyCache = null;
-function cdpKey() {
- if (!cdpKeyCache) cdpKeyCache = loadCdpKey();
- return cdpKeyCache;
-}
-
-function b64url(input) {
- return Buffer.from(input)
- .toString('base64')
- .replace(/=+$/, '')
- .replace(/\+/g, '-')
- .replace(/\//g, '_');
-}
-
-function cdpAuthHeader(method, urlString) {
- if (!env.CDP_API_KEY_ID) {
- throw new X402Error('cdp_not_configured', 'CDP_API_KEY_ID not set', 500);
- }
- const { alg, key } = cdpKey();
- const u = new URL(urlString);
- const uri = `${method.toUpperCase()} ${u.host}${u.pathname}`;
- const now = Math.floor(Date.now() / 1000);
- const header = {
- alg,
- kid: env.CDP_API_KEY_ID,
- typ: 'JWT',
- nonce: randomBytes(16).toString('hex'),
- };
- const payload = { iss: 'cdp', nbf: now, exp: now + 120, sub: env.CDP_API_KEY_ID, uri };
- const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
-
- let sigBuf;
- if (alg === 'ES256') {
- // Node returns DER-encoded ECDSA; JOSE wants raw r||s.
- const der = createSign('SHA256').update(signingInput).sign({ key, dsaEncoding: 'der' });
- sigBuf = derToJoseEcdsa(der, 32);
- } else {
- // EdDSA: crypto.sign(null, msg, key) returns the raw 64-byte signature.
- sigBuf = sign(null, Buffer.from(signingInput, 'utf8'), key);
- }
- return `Bearer ${signingInput}.${b64url(sigBuf)}`;
-}
-
-// Convert DER-encoded ECDSA signature (SEQUENCE { INTEGER r, INTEGER s })
-// into the JOSE r||s form. Each integer is padded/truncated to `keyBytes`.
-function derToJoseEcdsa(der, keyBytes) {
- let offset = 2; // skip SEQUENCE tag + length (length always 1 byte for P-256: r,s ≤ 33 each)
- if (der[1] & 0x80) offset = 2 + (der[1] & 0x7f); // long-form length, rare for P-256 but handle it
- if (der[offset] !== 0x02)
- throw new X402Error('cdp_bad_signature', 'malformed ECDSA r tag', 500);
- const rLen = der[offset + 1];
- let r = der.slice(offset + 2, offset + 2 + rLen);
- offset = offset + 2 + rLen;
- if (der[offset] !== 0x02)
- throw new X402Error('cdp_bad_signature', 'malformed ECDSA s tag', 500);
- const sLen = der[offset + 1];
- let s = der.slice(offset + 2, offset + 2 + sLen);
- // Strip leading zero padding inserted by DER to keep INTEGERs positive.
- while (r.length > keyBytes && r[0] === 0x00) r = r.slice(1);
- while (s.length > keyBytes && s[0] === 0x00) s = s.slice(1);
- const out = Buffer.alloc(keyBytes * 2);
- r.copy(out, keyBytes - r.length);
- s.copy(out, keyBytes * 2 - s.length);
- return out;
-}
-
function decodePaymentHeader(header) {
if (!header) throw new X402Error('payment_required', 'X-PAYMENT header required', 402);
let json;
@@ -275,15 +132,11 @@ function hostOf(url) {
}
async function callFacilitator(network, path, body) {
- const { url: base, token, kind } = facilitatorFor(network);
+ const { url: base, token } = facilitatorFor(network);
const url = `${base}${path}`;
const host = hostOf(base);
const headers = { 'content-type': 'application/json', accept: 'application/json' };
- if (kind === 'cdp') {
- headers.authorization = cdpAuthHeader('POST', url);
- } else if (token) {
- headers.authorization = `Bearer ${token}`;
- }
+ if (token) headers.authorization = `Bearer ${token}`;
let res;
try {
res = await fetch(url, {
diff --git a/api/agents.js b/api/agents.js
index 156310396..1a99400fe 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -199,13 +199,21 @@ export async function handleGetOne(req, res, id) {
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
- const prices = await sql`
- SELECT skill_name, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}
- `;
- row.skill_prices = prices.reduce((acc, p) => {
- acc[p.skill_name] = { amount: p.amount, currency_mint: p.currency_mint };
- return acc;
- }, {});
+ // Pricing is non-critical for the detail view; the agent_skill_prices
+ // schema has churned across migrations (skill / skill_name / skill_id),
+ // so a column mismatch must never 500 the agent page.
+ row.skill_prices = {};
+ try {
+ const prices = await sql`
+ SELECT skill_name, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}
+ `;
+ row.skill_prices = prices.reduce((acc, p) => {
+ acc[p.skill_name] = { amount: p.amount, currency_mint: p.currency_mint };
+ return acc;
+ }, {});
+ } catch (e) {
+ console.error('[agents] skill_prices lookup failed', e?.message || e);
+ }
await healStaleAvatarId(row);
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index b10a617ca..7c657c838 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -1,45 +1,75 @@
-// GET /api/insights/revenue-vision — paid endpoint listed on agentic.market.
+// GET /api/insights/revenue-vision
//
-// x402 v2 + CDP facilitator. Charges $0.001 USDC on Base mainnet per call.
-// On a valid payment, hands the caller's mission_brief to Claude and returns
-// a structured { power_mode, insight, recommended_move, confidence } object.
+// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market). For $0.001
+// USDC on Base or Arbitrum mainnet the server hands the caller's mission_brief
+// to Claude and returns a structured { power_mode, insight, recommended_move,
+// confidence } object. Buyers pay programmatically with @x402/fetch — no API keys.
//
-// First successful settle through the CDP facilitator is what triggers Bazaar
-// indexing — see api/x402-status for facilitator wiring health.
+// Wire stack (mirrors api/x402/model-check.js for consistency):
+// • @x402/express paymentMiddleware → Express adapter
+// • @x402/core x402ResourceServer + HTTPFacilitatorClient
+// • @x402/evm ExactEvmScheme (eip155:* networks)
+// • @x402/extensions declareDiscoveryExtension → bazaar discovery shape
+// • @coinbase/x402 facilitator config with ES256 JWT auth (CDP)
+//
+// Bazaar listing requires settlement through the CDP facilitator — that's the
+// only one whose verify+settle log feeds the catalog. CDP_API_KEY_ID and
+// CDP_API_KEY_SECRET must be set in Vercel.
+
+import express from 'express';
+import { paymentMiddleware, x402ResourceServer } from '@x402/express';
+import { ExactEvmScheme } from '@x402/evm/exact/server';
+import { HTTPFacilitatorClient } from '@x402/core/server';
+import { declareDiscoveryExtension } from '@x402/extensions/bazaar';
+import { facilitator as cdpFacilitator } from '@coinbase/x402';
-import { z } from 'zod';
-import { cors, error, json, method, wrap } from '../_lib/http.js';
import { env } from '../_lib/env.js';
-import {
- NETWORK_BASE_MAINNET,
- X402Error,
- encodePaymentResponseHeader,
- paymentRequirements,
- resolveResourceUrl,
- send402,
- settlePayment,
- verifyPayment,
-} from '../_lib/x402-spec.js';
-
-const RESOURCE_DESCRIPTION =
- 'Revenue Vision — agentic growth analysis for AI buyers. Pay $0.001 USDC on Base mainnet, hand over a mission_brief, and get back a prioritized next-best growth move with a structured confidence rating. Powered by Claude.';
-
-const inputExample = {
+
+const NETWORK_BASE = 'eip155:8453';
+const NETWORK_ARBITRUM = 'eip155:42161';
+const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+const ASSET_FOR_NETWORK = {
+ [NETWORK_BASE]: USDC_BASE,
+ [NETWORK_ARBITRUM]: env.X402_ASSET_ADDRESS_ARBITRUM,
+};
+
+const PAY_TO = env.X402_PAY_TO_BASE;
+const PRICE = '$0.001';
+const ROUTE = '/api/insights/revenue-vision';
+
+function buildAccepts() {
+ return env.X402_EVM_NETWORKS.filter((n) => ASSET_FOR_NETWORK[n]).map((network) => ({
+ scheme: 'exact',
+ network,
+ price: PRICE,
+ payTo: PAY_TO,
+ asset: ASSET_FOR_NETWORK[network],
+ extra: { name: 'USDC', version: '2', decimals: 6 },
+ }));
+}
+
+const facilitatorClient = new HTTPFacilitatorClient(cdpFacilitator);
+
+let resourceServer = new x402ResourceServer(facilitatorClient);
+for (const network of env.X402_EVM_NETWORKS) {
+ if (!ASSET_FOR_NETWORK[network]) continue;
+ resourceServer = resourceServer.register(network, new ExactEvmScheme());
+}
+
+const ROUTE_DESCRIPTION =
+ 'Revenue Vision — agentic growth analysis for AI buyers. Hand over a mission_brief ' +
+ '(a free-text growth question or hypothesis) and get back a single prioritized next-best ' +
+ 'tactical move, a specific data-grounded insight, and an honestly-calibrated confidence ' +
+ 'rating. Powered by Claude. Pay-per-call in USDC on Base or Arbitrum mainnet.';
+
+const DISCOVERY_INPUT_EXAMPLE = {
agent_codename: 'ledger-bot',
power_request: 'revenue-vision',
mission_brief: 'Find the highest-converting buyer segment this week.',
};
-const outputExample = {
- power_mode: 'revenue-vision',
- insight:
- 'Developer teams at 10–50 employees convert 2.4x better than enterprise prospects on the current funnel.',
- recommended_move:
- 'Shift 30% of the paid-acquisition budget to builder-focused onboarding campaigns this sprint.',
- confidence: 'high',
-};
-
-const inputSchema = {
+const DISCOVERY_INPUT_SCHEMA = {
type: 'object',
required: ['agent_codename', 'power_request', 'mission_brief'],
properties: {
@@ -61,7 +91,16 @@ const inputSchema = {
},
};
-const outputSchema = {
+const DISCOVERY_OUTPUT_EXAMPLE = {
+ power_mode: 'revenue-vision',
+ insight:
+ 'Developer teams at 10–50 employees convert 2.4x better than enterprise prospects on the current funnel.',
+ recommended_move:
+ 'Shift 30% of the paid-acquisition budget to builder-focused onboarding campaigns this sprint.',
+ confidence: 'high',
+};
+
+const DISCOVERY_OUTPUT_SCHEMA = {
type: 'object',
required: ['power_mode', 'insight', 'recommended_move', 'confidence'],
properties: {
@@ -78,34 +117,37 @@ const outputSchema = {
},
};
-function bazaarRevenueVision() {
- return {
- method: 'GET',
- discoverable: true,
- input: inputExample,
- inputSchema,
- output: { example: outputExample, schema: outputSchema },
- };
-}
+const routeConfig = {
+ [`GET ${ROUTE}`]: {
+ accepts: buildAccepts(),
+ description: ROUTE_DESCRIPTION,
+ mimeType: 'application/json',
+ extensions: {
+ ...declareDiscoveryExtension({
+ input: DISCOVERY_INPUT_EXAMPLE,
+ inputSchema: DISCOVERY_INPUT_SCHEMA,
+ output: {
+ example: DISCOVERY_OUTPUT_EXAMPLE,
+ schema: DISCOVERY_OUTPUT_SCHEMA,
+ },
+ }),
+ },
+ },
+};
-const querySchema = z.object({
- agent_codename: z.string().min(1).max(120),
- power_request: z.literal('revenue-vision'),
- mission_brief: z.string().min(4).max(4000),
-});
+const app = express();
-function baseAccepts() {
- const all = paymentRequirements();
- const base = all.filter((a) => a.network === NETWORK_BASE_MAINNET);
- if (!base.length) {
- throw new X402Error(
- 'misconfigured',
- 'X402_PAY_TO_BASE / X402_ASSET_ADDRESS_BASE must be set to advertise Base mainnet payments',
- 500,
- );
- }
- return base;
-}
+// Initializes by hitting the CDP facilitator's /supported endpoint to discover
+// advertised scheme/network pairs. Requires CDP_API_KEY_ID and CDP_API_KEY_SECRET
+// — without them the first request returns 500.
+app.use(paymentMiddleware(routeConfig, resourceServer));
+
+const SYSTEM_PROMPT =
+ 'You are Revenue Vision, an agentic growth analyst. Reply with a single JSON object ' +
+ 'exactly matching the schema {"power_mode":"revenue-vision","insight":string,"recommended_move":string,"confidence":"high"|"medium"|"low"}. ' +
+ 'The insight should be specific and quantitative when possible. The recommended_move should be one concrete tactical action. ' +
+ 'Calibrate confidence honestly: "high" only when you can defend the claim, otherwise "medium" or "low". ' +
+ 'No prose, no markdown, no preamble.';
async function callClaude(missionBrief, agentCodename) {
const upstream = await fetch('https://api.anthropic.com/v1/messages', {
@@ -118,7 +160,7 @@ async function callClaude(missionBrief, agentCodename) {
body: JSON.stringify({
model: 'claude-sonnet-4-6',
max_tokens: 800,
- system: 'You are Revenue Vision, an agentic growth analyst. Reply with a single JSON object exactly matching the schema {"power_mode":"revenue-vision","insight":string,"recommended_move":string,"confidence":"high"|"medium"|"low"}. The insight should be specific and quantitative when possible. The recommended_move should be one concrete tactical action. Calibrate confidence honestly: "high" only when you can defend the claim, otherwise "medium" or "low". No prose, no markdown, no preamble.',
+ system: SYSTEM_PROMPT,
messages: [
{
role: 'user',
@@ -130,21 +172,14 @@ async function callClaude(missionBrief, agentCodename) {
});
if (!upstream.ok) {
const errText = await upstream.text();
- throw new X402Error(
- 'upstream_error',
- `Claude returned ${upstream.status}: ${errText.slice(0, 300)}`,
- 502,
- );
+ const err = new Error(`Claude returned ${upstream.status}: ${errText.slice(0, 300)}`);
+ err.status = 502;
+ throw err;
}
const data = await upstream.json();
const text = data?.content?.find?.((b) => b.type === 'text')?.text || '';
- let parsed;
- try {
- const match = text.match(/\{[\s\S]*\}/);
- parsed = JSON.parse(match ? match[0] : text);
- } catch (err) {
- throw new X402Error('upstream_error', `Claude returned non-JSON: ${err.message}`, 502);
- }
+ const match = text.match(/\{[\s\S]*\}/);
+ const parsed = JSON.parse(match ? match[0] : text);
const allowedConfidence = new Set(['high', 'medium', 'low']);
return {
power_mode: 'revenue-vision',
@@ -154,57 +189,53 @@ async function callClaude(missionBrief, agentCodename) {
};
}
-export default wrap(async (req, res) => {
- if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const accepts = baseAccepts();
- const resourceUrl = resolveResourceUrl(req, '/api/insights/revenue-vision');
- const send402Here = (message) =>
- send402(res, {
- resourceUrl,
- accepts,
- error: message || 'X-PAYMENT header is required',
- description: RESOURCE_DESCRIPTION,
- bazaar: bazaarRevenueVision(),
- });
-
- // Always return 402 for unauthenticated requests BEFORE any query validation —
- // agentic.market's Bazaar crawler explicitly de-indexes endpoints that 400 on
- // its discovery probes, so payment-gating must come first.
- const paymentHeader = req.headers['x-payment'] || req.headers['X-PAYMENT'];
- if (!paymentHeader) return send402Here();
-
- const url = new URL(req.url, 'http://x');
- const query = {
- agent_codename: url.searchParams.get('agent_codename') || '',
- power_request: url.searchParams.get('power_request') || '',
- mission_brief: url.searchParams.get('mission_brief') || '',
- };
- const parsed = querySchema.safeParse(query);
- if (!parsed.success) {
- return error(
- res,
- 400,
- 'validation_error',
- parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '),
- );
+app.get(ROUTE, async (req, res) => {
+ const agentCodename = String(req.query?.agent_codename || '').trim();
+ const powerRequest = String(req.query?.power_request || '').trim();
+ const missionBrief = String(req.query?.mission_brief || '').trim();
+
+ if (!agentCodename || agentCodename.length > 120) {
+ return res
+ .status(400)
+ .json({
+ error: 'invalid_agent_codename',
+ message: 'agent_codename is required (≤120 chars)',
+ });
+ }
+ if (powerRequest !== 'revenue-vision') {
+ return res
+ .status(400)
+ .json({
+ error: 'invalid_power_request',
+ message: 'power_request must be "revenue-vision"',
+ });
+ }
+ if (missionBrief.length < 4 || missionBrief.length > 4000) {
+ return res
+ .status(400)
+ .json({
+ error: 'invalid_mission_brief',
+ message: 'mission_brief must be 4–4000 chars',
+ });
}
- let verified;
+ let result;
try {
- verified = await verifyPayment({ paymentHeader, requirements: accepts });
+ result = await callClaude(missionBrief, agentCodename);
} catch (err) {
- if (err instanceof X402Error && err.status === 402) return send402Here(err.message);
- throw err;
+ const status = err.status || 502;
+ return res
+ .status(status)
+ .json({ error: 'upstream_error', message: err.message || 'Claude call failed' });
}
- const result = await callClaude(parsed.data.mission_brief, parsed.data.agent_codename);
- const settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ res.setHeader('cache-control', 'no-store');
+ res.json(result);
+});
- res.setHeader('payment-response', encodePaymentResponseHeader(settled));
- return json(res, 200, result);
+app.use((err, req, res, _next) => {
+ console.error('[insights/revenue-vision] unhandled', err);
+ res.status(500).json({ error: 'internal_error', message: err?.message || 'unknown error' });
});
+
+export default app;
diff --git a/api/wk.js b/api/wk.js
index d18a45c04..af9d1c330 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -14,61 +14,137 @@ import {
// ── agent-attestation-schemas ─────────────────────────────────────────────────
const COMMON = {
- v: { type: 'integer', const: 1 },
- kind: { type: 'string' },
+ v: { type: 'integer', const: 1 },
+ kind: { type: 'string' },
agent: { type: 'string', description: 'Metaplex Core asset pubkey (base58)' },
- ts: { type: 'integer', description: 'Unix seconds when attestation was created' },
+ ts: { type: 'integer', description: 'Unix seconds when attestation was created' },
};
const SCHEMAS = {
- 'threews.feedback.v1': { description: 'Client → agent feedback.', required: ['v', 'kind', 'agent', 'score'], properties: { ...COMMON, score: { type: 'integer', minimum: 1, maximum: 5 }, task_id: { type: 'string' }, uri: { type: 'string', format: 'uri' } } },
- 'threews.validation.v1': { description: 'Validator attestation about an agent task result.', required: ['v', 'kind', 'agent', 'task_hash', 'passed'], properties: { ...COMMON, task_hash: { type: 'string' }, passed: { type: 'boolean' }, uri: { type: 'string', format: 'uri' } } },
- 'threews.task.v1': { description: 'Client posts a task offer to an agent.', required: ['v', 'kind', 'agent', 'task_id', 'scope_hash'], properties: { ...COMMON, task_id: { type: 'string' }, scope_hash: { type: 'string' }, uri: { type: 'string', format: 'uri' } } },
- 'threews.accept.v1': { description: 'Agent accepts a task.', required: ['v', 'kind', 'agent', 'task_id'], properties: { ...COMMON, task_id: { type: 'string' } } },
- 'threews.revoke.v1': { description: 'Revoke a previous attestation.', required: ['v', 'kind', 'agent', 'target_signature'], properties: { ...COMMON, target_signature: { type: 'string' }, reason: { type: 'string' } } },
- 'threews.dispute.v1': { description: 'Agent owner disputes a feedback or validation.', required: ['v', 'kind', 'agent', 'target_signature'], properties: { ...COMMON, target_signature: { type: 'string' }, reason: { type: 'string' }, uri: { type: 'string', format: 'uri' } } },
+ 'threews.feedback.v1': {
+ description: 'Client → agent feedback.',
+ required: ['v', 'kind', 'agent', 'score'],
+ properties: {
+ ...COMMON,
+ score: { type: 'integer', minimum: 1, maximum: 5 },
+ task_id: { type: 'string' },
+ uri: { type: 'string', format: 'uri' },
+ },
+ },
+ 'threews.validation.v1': {
+ description: 'Validator attestation about an agent task result.',
+ required: ['v', 'kind', 'agent', 'task_hash', 'passed'],
+ properties: {
+ ...COMMON,
+ task_hash: { type: 'string' },
+ passed: { type: 'boolean' },
+ uri: { type: 'string', format: 'uri' },
+ },
+ },
+ 'threews.task.v1': {
+ description: 'Client posts a task offer to an agent.',
+ required: ['v', 'kind', 'agent', 'task_id', 'scope_hash'],
+ properties: {
+ ...COMMON,
+ task_id: { type: 'string' },
+ scope_hash: { type: 'string' },
+ uri: { type: 'string', format: 'uri' },
+ },
+ },
+ 'threews.accept.v1': {
+ description: 'Agent accepts a task.',
+ required: ['v', 'kind', 'agent', 'task_id'],
+ properties: { ...COMMON, task_id: { type: 'string' } },
+ },
+ 'threews.revoke.v1': {
+ description: 'Revoke a previous attestation.',
+ required: ['v', 'kind', 'agent', 'target_signature'],
+ properties: { ...COMMON, target_signature: { type: 'string' }, reason: { type: 'string' } },
+ },
+ 'threews.dispute.v1': {
+ description: 'Agent owner disputes a feedback or validation.',
+ required: ['v', 'kind', 'agent', 'target_signature'],
+ properties: {
+ ...COMMON,
+ target_signature: { type: 'string' },
+ reason: { type: 'string' },
+ uri: { type: 'string', format: 'uri' },
+ },
+ },
};
function handleAttestationSchemas(req, res) {
- return json(res, 200, {
- version: 1,
- transport: { type: 'spl-memo', program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', note: 'Each attestation is a signed memo tx with the agent asset pubkey as a non-signer key.' },
- schemas: SCHEMAS,
- discovery: { list_endpoint: '/api/agents/solana-attestations?asset=<pubkey>&kind=...', reputation_endpoint: '/api/agents/solana-reputation?asset=<pubkey>' },
- }, { 'cache-control': 'public, max-age=300' });
+ return json(
+ res,
+ 200,
+ {
+ version: 1,
+ transport: {
+ type: 'spl-memo',
+ program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',
+ note: 'Each attestation is a signed memo tx with the agent asset pubkey as a non-signer key.',
+ },
+ schemas: SCHEMAS,
+ discovery: {
+ list_endpoint: '/api/agents/solana-attestations?asset=<pubkey>&kind=...',
+ reputation_endpoint: '/api/agents/solana-reputation?asset=<pubkey>',
+ },
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
}
// ── oauth-authorization-server ────────────────────────────────────────────────
function handleOauthAuthServer(req, res) {
const base = env.APP_ORIGIN;
- return json(res, 200, {
- issuer: base,
- authorization_endpoint: `${base}/oauth/authorize`,
- token_endpoint: `${base}/api/oauth/token`,
- registration_endpoint: `${base}/api/oauth/register`,
- revocation_endpoint: `${base}/api/oauth/revoke`,
- introspection_endpoint: `${base}/api/oauth/introspect`,
- response_types_supported: ['code'],
- grant_types_supported: ['authorization_code', 'refresh_token'],
- code_challenge_methods_supported: ['S256'],
- token_endpoint_auth_methods_supported: ['none', 'client_secret_basic', 'client_secret_post'],
- scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'offline_access'],
- service_documentation: `${base}/docs/mcp`,
- ui_locales_supported: ['en'],
- }, { 'cache-control': 'public, max-age=300' });
+ return json(
+ res,
+ 200,
+ {
+ issuer: base,
+ authorization_endpoint: `${base}/oauth/authorize`,
+ token_endpoint: `${base}/api/oauth/token`,
+ registration_endpoint: `${base}/api/oauth/register`,
+ revocation_endpoint: `${base}/api/oauth/revoke`,
+ introspection_endpoint: `${base}/api/oauth/introspect`,
+ response_types_supported: ['code'],
+ grant_types_supported: ['authorization_code', 'refresh_token'],
+ code_challenge_methods_supported: ['S256'],
+ token_endpoint_auth_methods_supported: [
+ 'none',
+ 'client_secret_basic',
+ 'client_secret_post',
+ ],
+ scopes_supported: [
+ 'avatars:read',
+ 'avatars:write',
+ 'avatars:delete',
+ 'profile',
+ 'offline_access',
+ ],
+ service_documentation: `${base}/docs/mcp`,
+ ui_locales_supported: ['en'],
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
}
// ── oauth-protected-resource ──────────────────────────────────────────────────
function handleOauthProtectedResource(req, res) {
- return json(res, 200, {
- resource: env.MCP_RESOURCE,
- authorization_servers: [env.APP_ORIGIN],
- bearer_methods_supported: ['header'],
- resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,
- scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile'],
- }, { 'cache-control': 'public, max-age=300' });
+ return json(
+ res,
+ 200,
+ {
+ resource: env.MCP_RESOURCE,
+ authorization_servers: [env.APP_ORIGIN],
+ bearer_methods_supported: ['header'],
+ resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,
+ scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile'],
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
}
// ── x402 ─────────────────────────────────────────────────────────────────────
@@ -107,6 +183,8 @@ function handleX402Discovery(req, res) {
const origin = env.APP_ORIGIN;
const mcpUrl = `${origin}/api/mcp`;
const modelCheckUrl = `${origin}/api/x402/model-check`;
+ const mintToMeshUrl = `${origin}/api/x402/mint-to-mesh`;
+ const revenueVisionUrl = `${origin}/api/insights/revenue-vision`;
const price = RAW_AMOUNT_TO_USDC(env.X402_MAX_AMOUNT_REQUIRED);
const mcpAccepts = [];
@@ -170,94 +248,190 @@ function handleX402Discovery(req, res) {
},
];
- return json(res, 200, {
- $schema: 'https://x402.org/schemas/discovery.json',
- service: {
- name: 'three.ws',
- legal_name: 'three.ws',
- tagline: 'AI-powered 3D model viewer and validation agent.',
- description: 'three.ws is an agent-first 3D model platform. Drag-and-drop glTF/GLB preview, model validation/inspection/optimization, plus Solana agent data — reachable both as MCP tool calls and as paid REST endpoints (x402 v2). USDC on Base, Arbitrum, and Solana mainnet.',
- operator: 'three.ws',
- mission: 'Make 3D model tooling and Solana agent data machine-native so any AI agent can transact with the HTTP 402 protocol.',
- website: origin,
- docs: `${origin}/docs/mcp`,
- repository: 'https://github.com/nirholas/three.ws',
- contact: `${origin}/`,
- tags: ['x402', 'x402-v2', 'mcp', 'agent-first', '3d', 'gltf', 'glb', 'three-js', 'solana', 'base', 'arbitrum', 'usdc'],
- environment: 'apex',
- origin,
- },
- resources: [
- {
- path: '/api/x402/model-check',
- url: modelCheckUrl,
- method: 'GET',
+ return json(
+ res,
+ 200,
+ {
+ $schema: 'https://x402.org/schemas/discovery.json',
+ service: {
+ name: 'three.ws',
+ legal_name: 'three.ws',
+ tagline: 'AI-powered 3D model viewer and validation agent.',
description:
- 'Fetches a glTF/GLB model from a URL and returns structural stats (vertex/triangle counts, materials, textures, animations, extensions) plus a prioritized list of optimization recommendations. Single GET, ?url=…. CDP-Bazaar-cataloged.',
- mimeType: 'application/json',
- accepts: modelCheckAccepts,
- extensions: {
- bazaar: {
- method: 'GET',
- discoverable: true,
- input: { url: 'https://three.ws/avatar/character-studio/sample.glb' },
- inputSchema: {
- type: 'object',
- required: ['url'],
- properties: {
- url: { type: 'string', format: 'uri', description: 'Public HTTPS URL of a glTF/GLB model.' },
+ 'three.ws is an agent-first 3D model platform. Drag-and-drop glTF/GLB preview, model validation/inspection/optimization, plus Solana agent data — reachable both as MCP tool calls and as paid REST endpoints (x402 v2). USDC on Base, Arbitrum, and Solana mainnet.',
+ operator: 'three.ws',
+ mission:
+ 'Make 3D model tooling and Solana agent data machine-native so any AI agent can transact with the HTTP 402 protocol.',
+ website: origin,
+ docs: `${origin}/docs/mcp`,
+ repository: 'https://github.com/nirholas/three.ws',
+ contact: `${origin}/`,
+ tags: [
+ 'x402',
+ 'x402-v2',
+ 'mcp',
+ 'agent-first',
+ '3d',
+ 'gltf',
+ 'glb',
+ 'three-js',
+ 'solana',
+ 'base',
+ 'arbitrum',
+ 'usdc',
+ ],
+ environment: 'apex',
+ origin,
+ },
+ resources: [
+ {
+ path: '/api/x402/model-check',
+ url: modelCheckUrl,
+ method: 'GET',
+ description:
+ 'Fetches a glTF/GLB model from a URL and returns structural stats (vertex/triangle counts, materials, textures, animations, extensions) plus a prioritized list of optimization recommendations. Single GET, ?url=…. CDP-Bazaar-cataloged.',
+ mimeType: 'application/json',
+ accepts: modelCheckAccepts,
+ extensions: {
+ bazaar: {
+ method: 'GET',
+ discoverable: true,
+ input: { url: 'https://three.ws/avatar/character-studio/sample.glb' },
+ inputSchema: {
+ type: 'object',
+ required: ['url'],
+ properties: {
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public HTTPS URL of a glTF/GLB model.',
+ },
+ },
},
},
},
},
- },
- {
- path: '/api/mcp',
- url: mcpUrl,
- method: 'POST',
- description:
- 'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',
- mimeType: 'application/json',
- accepts: mcpAccepts,
- extensions: { bazaar: bazaarExtension() },
- links: {
- openapi: `${origin}/openapi.json`,
- docs: `${origin}/docs/mcp`,
- agent_card: `${origin}/.well-known/agent-card.json`,
- payment_config: `${origin}/.well-known/x402`,
+ {
+ path: '/api/x402/mint-to-mesh',
+ url: mintToMeshUrl,
+ method: 'GET',
+ description:
+ 'Mint to Mesh — pass a Solana fungible-token mint, get back a binary glTF (GLB) cube themed for that token. Color is derived from a stable hash of the mint; when the off-chain Metaplex JSON exposes a PNG/JPEG, that image is embedded as a baseColor texture on every face. Asset.extras carry mint, name, symbol, and timestamp. Useful for any agent that needs an instantly renderable 3D representation of a token. CDP-Bazaar-cataloged.',
+ mimeType: 'application/json',
+ accepts: modelCheckAccepts,
+ extensions: {
+ bazaar: {
+ method: 'GET',
+ discoverable: true,
+ input: { mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263' },
+ inputSchema: {
+ type: 'object',
+ required: ['mint'],
+ properties: {
+ mint: {
+ type: 'string',
+ minLength: 32,
+ maxLength: 64,
+ description: 'Base58 SPL mint address on Solana mainnet.',
+ },
+ },
+ },
+ },
+ },
},
- },
- ],
- }, { 'cache-control': 'public, max-age=300' });
+ {
+ path: '/api/insights/revenue-vision',
+ url: revenueVisionUrl,
+ method: 'GET',
+ description:
+ 'Revenue Vision — agentic growth analysis powered by Claude. Hand over a mission_brief and get back a single prioritized next-best move, a data-grounded insight, and an honestly-calibrated confidence rating. CDP-Bazaar-cataloged.',
+ mimeType: 'application/json',
+ accepts: modelCheckAccepts,
+ extensions: {
+ bazaar: {
+ method: 'GET',
+ discoverable: true,
+ input: {
+ agent_codename: 'ledger-bot',
+ power_request: 'revenue-vision',
+ mission_brief:
+ 'Find the highest-converting buyer segment this week.',
+ },
+ inputSchema: {
+ type: 'object',
+ required: ['agent_codename', 'power_request', 'mission_brief'],
+ properties: {
+ agent_codename: { type: 'string' },
+ power_request: { type: 'string', enum: ['revenue-vision'] },
+ mission_brief: {
+ type: 'string',
+ minLength: 4,
+ maxLength: 4000,
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ path: '/api/mcp',
+ url: mcpUrl,
+ method: 'POST',
+ description:
+ 'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',
+ mimeType: 'application/json',
+ accepts: mcpAccepts,
+ extensions: { bazaar: bazaarExtension() },
+ links: {
+ openapi: `${origin}/openapi.json`,
+ docs: `${origin}/docs/mcp`,
+ agent_card: `${origin}/.well-known/agent-card.json`,
+ payment_config: `${origin}/.well-known/x402`,
+ },
+ },
+ ],
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
}
// ── dispatcher ────────────────────────────────────────────────────────────────
function handleChatPlugin(req, res) {
- return json(res, 200, {
- identifier: '3dagent',
- schemaVersion: 1,
- meta: {
- title: 'three.ws',
- description: 'Render a 3D avatar that reacts to the chat.',
- avatar: 'https://three.ws/favicon.ico',
- tags: ['avatar', '3d', 'agent'],
+ return json(
+ res,
+ 200,
+ {
+ identifier: '3dagent',
+ schemaVersion: 1,
+ meta: {
+ title: 'three.ws',
+ description: 'Render a 3D avatar that reacts to the chat.',
+ avatar: 'https://three.ws/favicon.ico',
+ tags: ['avatar', '3d', 'agent'],
+ },
+ ui: { position: 'right', size: { width: 320, height: 420 } },
+ settings: [
+ { name: 'agentId', type: 'string', required: true, title: 'Agent ID' },
+ {
+ name: 'apiOrigin',
+ type: 'string',
+ default: 'https://three.ws/',
+ title: 'API Origin',
+ },
+ ],
},
- ui: { position: 'right', size: { width: 320, height: 420 } },
- settings: [
- { name: 'agentId', type: 'string', required: true, title: 'Agent ID' },
- { name: 'apiOrigin', type: 'string', default: 'https://three.ws/', title: 'API Origin' },
- ],
- }, { 'cache-control': 'public, max-age=3600' });
+ { 'cache-control': 'public, max-age=3600' },
+ );
}
const DISPATCH = {
- 'agent-attestation-schemas': handleAttestationSchemas,
- 'chat-plugin': handleChatPlugin,
+ 'agent-attestation-schemas': handleAttestationSchemas,
+ 'chat-plugin': handleChatPlugin,
'oauth-authorization-server': handleOauthAuthServer,
- 'oauth-protected-resource': handleOauthProtectedResource,
- 'x402': handleX402,
- 'x402-discovery': handleX402Discovery,
+ 'oauth-protected-resource': handleOauthProtectedResource,
+ x402: handleX402,
+ 'x402-discovery': handleX402Discovery,
};
// Public discovery docs (x402, x402-discovery, chat-plugin, agent-attestation-schemas)
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
new file mode 100644
index 000000000..bf474c4d2
--- /dev/null
+++ b/api/x402/mint-to-mesh.js
@@ -0,0 +1,243 @@
+// GET /api/x402/mint-to-mesh?mint=<solana-mint>
+//
+// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market). For $0.01
+// USDC on Base or Arbitrum mainnet the server reads the token's on-chain
+// Metaplex metadata, resolves the off-chain JSON, fetches the image (when one
+// is exposed), and returns a themed binary glTF cube ready for any Three.js /
+// Babylon.js / model-viewer instance to render.
+//
+// The cube is procedurally synthesized per request via @gltf-transform — no
+// templated asset, no headless WebGL, no S3. Output ships as base64 inside a
+// JSON envelope so x402 facilitators that struggle with binary bodies still
+// receive a clean response.
+//
+// Wire stack (matches /api/x402/model-check):
+// • @x402/express paymentMiddleware → Express adapter
+// • @x402/core x402ResourceServer + HTTPFacilitatorClient
+// • @x402/evm ExactEvmScheme (eip155:* networks)
+// • @x402/extensions declareDiscoveryExtension → bazaar discovery shape
+// • @coinbase/x402 facilitator config with ES256 JWT auth (CDP)
+
+import express from 'express';
+import { paymentMiddleware, x402ResourceServer } from '@x402/express';
+import { ExactEvmScheme } from '@x402/evm/exact/server';
+import { HTTPFacilitatorClient } from '@x402/core/server';
+import { declareDiscoveryExtension } from '@x402/extensions/bazaar';
+import { facilitator as cdpFacilitator } from '@coinbase/x402';
+
+import { env } from '../_lib/env.js';
+import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
+import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
+
+const NETWORK_BASE = 'eip155:8453';
+const NETWORK_ARBITRUM = 'eip155:42161';
+const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+const ASSET_FOR_NETWORK = {
+ [NETWORK_BASE]: USDC_BASE,
+ [NETWORK_ARBITRUM]: env.X402_ASSET_ADDRESS_ARBITRUM,
+};
+
+const PAY_TO = env.X402_PAY_TO_BASE;
+const PRICE = '$0.01';
+const ROUTE = '/api/x402/mint-to-mesh';
+
+function buildAccepts() {
+ return env.X402_EVM_NETWORKS
+ .filter((n) => ASSET_FOR_NETWORK[n])
+ .map((network) => ({
+ scheme: 'exact',
+ network,
+ price: PRICE,
+ payTo: PAY_TO,
+ asset: ASSET_FOR_NETWORK[network],
+ extra: { name: 'USDC', version: '2', decimals: 6 },
+ }));
+}
+
+const facilitatorClient = new HTTPFacilitatorClient(cdpFacilitator);
+
+let resourceServer = new x402ResourceServer(facilitatorClient);
+for (const network of env.X402_EVM_NETWORKS) {
+ if (!ASSET_FOR_NETWORK[network]) continue;
+ resourceServer = resourceServer.register(network, new ExactEvmScheme());
+}
+
+const ROUTE_DESCRIPTION =
+ 'three.ws Mint to Mesh — pass a Solana fungible-token mint, get back a binary ' +
+ 'glTF (GLB) cube themed for that token. The cube is colored from a stable hash ' +
+ 'of the mint and (when the off-chain metadata exposes a PNG/JPEG) carries the ' +
+ 'token image as a baseColor texture on every face. Asset.extras carry the full ' +
+ 'on-chain Metaplex metadata so downstream agents can introspect mint, name, ' +
+ 'symbol, and timestamp. Useful for any agent that needs an instantly renderable ' +
+ '3D representation of a token (in-game items, leaderboards, NFT-of-token, AR ' +
+ 'previews). Pay-per-call in USDC on Base or Arbitrum mainnet.';
+
+const DISCOVERY_INPUT_EXAMPLE = {
+ mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263',
+};
+
+const DISCOVERY_INPUT_SCHEMA = {
+ type: 'object',
+ required: ['mint'],
+ properties: {
+ mint: {
+ type: 'string',
+ minLength: 32,
+ maxLength: 64,
+ description: 'Base58 SPL mint address on Solana mainnet.',
+ },
+ },
+};
+
+const DISCOVERY_OUTPUT_EXAMPLE = {
+ mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263',
+ theme: {
+ name: 'Bonk',
+ symbol: 'Bonk',
+ color: [0.92, 0.45, 0.18],
+ imageUrl: 'https://arweave.net/hQiPZOsRZXGXBJd_82PhVdlM_hACsT_q6wqwf5cSY7I',
+ hasImage: true,
+ },
+ glb: {
+ mimeType: 'model/gltf-binary',
+ bytes: 50768,
+ base64:
+ 'Z2xURgIAAADQxAAA…(truncated; full GLB bytes are returned on a real call)',
+ },
+};
+
+const DISCOVERY_OUTPUT_SCHEMA = {
+ type: 'object',
+ required: ['mint', 'theme', 'glb'],
+ properties: {
+ mint: { type: 'string' },
+ theme: {
+ type: 'object',
+ required: ['name', 'symbol', 'color', 'hasImage'],
+ properties: {
+ name: { type: ['string', 'null'] },
+ symbol: { type: ['string', 'null'] },
+ color: {
+ type: 'array',
+ minItems: 3,
+ maxItems: 3,
+ items: { type: 'number', minimum: 0, maximum: 1 },
+ description: 'RGB triplet in [0,1] used as baseColorFactor.',
+ },
+ imageUrl: { type: ['string', 'null'], format: 'uri' },
+ hasImage: {
+ type: 'boolean',
+ description:
+ 'True when a PNG/JPEG image was fetched and embedded as a baseColor texture.',
+ },
+ },
+ },
+ glb: {
+ type: 'object',
+ required: ['mimeType', 'bytes', 'base64'],
+ properties: {
+ mimeType: { type: 'string', const: 'model/gltf-binary' },
+ bytes: { type: 'integer', minimum: 1 },
+ base64: {
+ type: 'string',
+ description: 'Base64-encoded binary glTF (GLB). Decode for the raw .glb file.',
+ },
+ },
+ },
+ },
+};
+
+const routeConfig = {
+ [`GET ${ROUTE}`]: {
+ accepts: buildAccepts(),
+ description: ROUTE_DESCRIPTION,
+ mimeType: 'application/json',
+ extensions: {
+ ...declareDiscoveryExtension({
+ input: DISCOVERY_INPUT_EXAMPLE,
+ inputSchema: DISCOVERY_INPUT_SCHEMA,
+ output: {
+ example: DISCOVERY_OUTPUT_EXAMPLE,
+ schema: DISCOVERY_OUTPUT_SCHEMA,
+ },
+ }),
+ },
+ },
+};
+
+const app = express();
+
+// Middleware initializes by hitting the CDP facilitator's /supported endpoint
+// to discover advertised scheme/network pairs. Requires CDP_API_KEY_ID and
+// CDP_API_KEY_SECRET to be set — without them the first request returns 500
+// with "Failed to initialize: no supported payment kinds loaded".
+app.use(paymentMiddleware(routeConfig, resourceServer));
+
+// Loose Solana base58 sanity check. Real validation happens in solanaPubkey()
+// inside fetchTokenMeta — this just rejects obvious garbage early so we don't
+// pay for an RPC round trip on it.
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+app.get(ROUTE, async (req, res) => {
+ const mint = String(req.query?.mint || '').trim();
+ if (!mint) {
+ return res.status(400).json({ error: 'missing_mint', message: 'query param "mint" is required' });
+ }
+ if (!BASE58_RE.test(mint)) {
+ return res
+ .status(400)
+ .json({ error: 'invalid_mint', message: 'mint must be a base58 SPL address (32–44 chars)' });
+ }
+
+ let meta;
+ try {
+ meta = await fetchTokenMeta(mint);
+ } catch (err) {
+ const status = err.status || 502;
+ return res.status(status).json({
+ error: err.code || 'meta_fetch_failed',
+ message: err.message || 'failed to read on-chain metadata',
+ });
+ }
+
+ const color = colorFromMint(mint);
+ const glb = await createThemedGLB({
+ mint: meta.mint,
+ name: meta.name,
+ symbol: meta.symbol,
+ image: meta.image?.bytes || null,
+ imageMimeType: meta.image?.mimeType || null,
+ color,
+ extras: {
+ description: meta.description || undefined,
+ imageUrl: meta.imageUrl || undefined,
+ externalUrl: meta.externalUrl || undefined,
+ offchainUri: meta.uri || undefined,
+ },
+ });
+
+ res.setHeader('cache-control', 'no-store');
+ res.json({
+ mint: meta.mint,
+ theme: {
+ name: meta.name,
+ symbol: meta.symbol,
+ color,
+ imageUrl: meta.imageUrl,
+ hasImage: !!meta.image,
+ },
+ glb: {
+ mimeType: 'model/gltf-binary',
+ bytes: glb.byteLength,
+ base64: Buffer.from(glb).toString('base64'),
+ },
+ });
+});
+
+app.use((err, req, res, _next) => {
+ console.error('[x402/mint-to-mesh] unhandled', err);
+ res.status(500).json({ error: 'internal_error', message: err?.message || 'unknown error' });
+});
+
+export default app;
diff --git a/home.html b/home.html
index e5110df0f..e21d0d7ba 100644
--- a/home.html
+++ b/home.html
@@ -394,36 +394,6 @@
</div>
</section>
- <!-- ── Trust strip ── -->
- <div class="h-trust-strip">
- <div class="h-trust-inner">
- <div class="h-trust-item">
- <span class="h-trust-num">20+</span>
- <span class="h-trust-label">EVM chains</span>
- </div>
- <span class="h-trust-sep" aria-hidden="true">·</span>
- <div class="h-trust-item">
- <span class="h-trust-num">ERC-8004</span>
- <span class="h-trust-label">on-chain standard</span>
- </div>
- <span class="h-trust-sep" aria-hidden="true">·</span>
- <div class="h-trust-item">
- <span class="h-trust-num">5</span>
- <span class="h-trust-label">widget types</span>
- </div>
- <span class="h-trust-sep" aria-hidden="true">·</span>
- <div class="h-trust-item">
- <span class="h-trust-num">A2A + MCP</span>
- <span class="h-trust-label">interoperability</span>
- </div>
- <span class="h-trust-sep" aria-hidden="true">·</span>
- <div class="h-trust-item">
- <span class="h-trust-num">MIT</span>
- <span class="h-trust-label">open source</span>
- </div>
- </div>
- </div>
-
<!-- ── Bento feature grid ── -->
<section class="h-bento-section">
<div class="h-bento-header h-reveal">
diff --git a/scripts/x402-pay.mjs b/scripts/x402-pay.mjs
new file mode 100644
index 000000000..2d0df655e
--- /dev/null
+++ b/scripts/x402-pay.mjs
@@ -0,0 +1,115 @@
+// x402 buyer client — fires a real paid request against an x402 endpoint and
+// prints the response + settlement details.
+//
+// USAGE
+// BUYER_PRIVATE_KEY=0x... node scripts/x402-pay.mjs <url> [field=value ...]
+//
+// EXAMPLES
+// # Smoke-test our own revenue-vision endpoint after deploy:
+// BUYER_PRIVATE_KEY=0xabc... node scripts/x402-pay.mjs \
+// https://three.ws/api/insights/revenue-vision \
+// agent_codename=ledger-bot \
+// power_request=revenue-vision \
+// mission_brief="Find the highest-converting buyer segment this week."
+//
+// # Hit the model-check endpoint:
+// BUYER_PRIVATE_KEY=0xabc... node scripts/x402-pay.mjs \
+// https://three.ws/api/x402/model-check \
+// url=https://three.ws/avatar/character-studio/sample.glb
+//
+// REQUIREMENTS
+// * BUYER_PRIVATE_KEY — hex EVM private key (0x...). Wallet must hold USDC on
+// Base mainnet (or Arbitrum One — script auto-selects whichever the endpoint
+// accepts that's listed first). $0.001 USDC + a tiny amount of ETH for gas.
+// * Node 20+ (uses native fetch).
+//
+// BAZAAR INDEXING
+// The first successful settle through the CDP facilitator is what triggers
+// agentic.market to index your endpoint. Run this script once with a real
+// buyer wallet and you're listed.
+
+import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from '@x402/fetch';
+import { ExactEvmScheme } from '@x402/evm/exact/client';
+import { privateKeyToAccount } from 'viem/accounts';
+
+const BUYER_PRIVATE_KEY = process.env.BUYER_PRIVATE_KEY;
+if (!BUYER_PRIVATE_KEY) {
+ console.error('error: BUYER_PRIVATE_KEY env var is required (0x-prefixed hex)');
+ process.exit(2);
+}
+if (!/^0x[0-9a-fA-F]{64}$/.test(BUYER_PRIVATE_KEY)) {
+ console.error(
+ 'error: BUYER_PRIVATE_KEY must be 0x + 64 hex chars (32-byte ECDSA secp256k1 key)',
+ );
+ process.exit(2);
+}
+
+const args = process.argv.slice(2);
+if (!args.length) {
+ console.error(
+ 'usage: BUYER_PRIVATE_KEY=0x... node scripts/x402-pay.mjs <url> [field=value ...]',
+ );
+ process.exit(2);
+}
+
+const targetUrl = args[0];
+const params = new URLSearchParams();
+for (const pair of args.slice(1)) {
+ const eq = pair.indexOf('=');
+ if (eq === -1) {
+ console.error(`error: argument "${pair}" must be in field=value form`);
+ process.exit(2);
+ }
+ params.set(pair.slice(0, eq), pair.slice(eq + 1));
+}
+
+const url = new URL(targetUrl);
+for (const [k, v] of params) url.searchParams.set(k, v);
+
+const account = privateKeyToAccount(BUYER_PRIVATE_KEY);
+console.log(`buyer wallet: ${account.address}`);
+console.log(`target: ${url.toString()}`);
+console.log();
+
+// `eip155:*` registers the same scheme for any EVM chain — the facilitator's
+// first-listed accepts entry decides which one we actually pay on.
+const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
+ schemes: [{ network: 'eip155:*', client: new ExactEvmScheme(account) }],
+});
+
+const t0 = Date.now();
+let res;
+try {
+ res = await fetchWithPayment(url.toString(), { method: 'GET' });
+} catch (err) {
+ console.error('request failed:', err?.message || err);
+ if (err?.cause) console.error('cause:', err.cause);
+ process.exit(1);
+}
+const elapsed = Date.now() - t0;
+
+console.log(`HTTP ${res.status} (${elapsed}ms)`);
+
+const paymentResponseHeader =
+ res.headers.get('payment-response') || res.headers.get('PAYMENT-RESPONSE');
+if (paymentResponseHeader) {
+ try {
+ const decoded = decodePaymentResponseHeader(paymentResponseHeader);
+ console.log('settlement:');
+ console.log(` network: ${decoded.network}`);
+ console.log(` payer: ${decoded.payer}`);
+ console.log(` transaction: ${decoded.transaction}`);
+ } catch (err) {
+ console.warn('could not decode payment-response header:', err?.message);
+ }
+}
+
+const text = await res.text();
+console.log('body:');
+try {
+ console.log(JSON.stringify(JSON.parse(text), null, 2));
+} catch {
+ console.log(text);
+}
+
+if (!res.ok) process.exit(1);