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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(mcp): agent registration, memory, embed, paid-services + avatar render
nirholasd5ba139e9d12
diff --git a/api/_lib/agent-paid-services.js b/api/_lib/agent-paid-services.jsnew file mode 100644index 000000000..e44e09dae--- /dev/null+++ b/api/_lib/agent-paid-services.js@@ -0,0 +1,175 @@+// Registry for agent-published paid x402 services (the `monetize_endpoint` tool).+//+// An agent points `monetize_endpoint` at an upstream it already serves and a+// price; we persist a row here and three.ws hosts the paywall at+// /api/x402/service/<slug>. The hosted endpoint (api/x402/service.js) reads the+// row per request to build the 402 challenge, settle the buyer's USDC to the+// agent's own payout wallet, and proxy the call to `target_url`. The same rows+// feed the /.well-known/x402.json discovery doc so facilitators — and therefore+// find_services / the bazaar — index the listing.++import { randomUUID } from 'node:crypto';+import { sql } from './db.js';+import { env } from './env.js';+import { assertPublicHttpsUrl, SsrfError } from './ssrf.js';++export class MonetizeError extends Error {+ constructor(message, code = 'monetize_error', status = 400) {+ super(message);+ this.name = 'MonetizeError';+ this.code = code;+ this.status = status;+ }+}++// USDC has 6 decimals. Convert a human dollar price to atomic units (string).+export function usdcToAtomics(priceUsdc) {+ const n = Number(priceUsdc);+ if (!Number.isFinite(n) || n <= 0) {+ throw new MonetizeError('price_usdc must be a number greater than 0', 'invalid_price');+ }+ const atomics = Math.round(n * 1_000_000);+ if (atomics < 1) {+ throw new MonetizeError('price_usdc is below the $0.000001 minimum', 'invalid_price');+ }+ return String(atomics);+}++export function atomicsToUsdc(atomics) {+ return Number(atomics || 0) / 1_000_000;+}++// The hosted resource URL a buyer (and pay_and_call) hits for this service.+export function serviceResourceUrl(slug) {+ return `${env.APP_ORIGIN}/api/x402/service/${slug}`;+}++// Build a slug from the service name plus a short unique suffix so two agents+// can both publish a "Weather API" without colliding. Always satisfies the+// table's CHECK: starts/ends alphanumeric, kebab middle, length 3–64.+function buildSlug(name) {+ const base = String(name || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 40)+ .replace(/-+$/g, '');+ const suffix = randomUUID().replace(/-/g, '').slice(0, 8);+ const stem = base.length >= 1 ? base : 'service';+ return `${stem}-${suffix}`;+}++// SSRF-validate the upstream URL. Public https only (the resolver rejects+// private / loopback / cloud-metadata targets). Throws MonetizeError so the MCP+// boundary can render a clean message.+export async function validateTargetUrl(rawUrl) {+ try {+ return await assertPublicHttpsUrl(rawUrl);+ } catch (err) {+ if (err instanceof SsrfError) {+ throw new MonetizeError(+ `target_url rejected: ${err.message}`,+ 'invalid_target_url',+ 400,+ );+ }+ throw err;+ }+}++// Resolve the agent's own payout wallet for the requested settlement network.+// solana → meta.solana_address (provisioned by provision_wallet); base → the+// agent's EVM wallet_address. Returns null when the prerequisite wallet is+// missing so the caller can tell the agent to provision_wallet first.+export function resolvePayoutAddress({ network, agentRow }) {+ if (network === 'solana') return agentRow?.meta?.solana_address || null;+ return agentRow?.wallet_address || null;+}++/**+ * Create (and list) a priced x402 wrapper for one of the caller's agents.+ *+ * @param {{+ * ownerUserId: string, agentId: string, name: string, description: string,+ * priceUsdc: number, targetUrl: string, method?: 'GET'|'POST',+ * inputSchema?: object|null, network?: 'base'|'solana', payoutAddress: string,+ * }} input+ * @returns {Promise<object>} the persisted service row (camel fields preserved as-is)+ */+export async function createPaidService(input) {+ const {+ ownerUserId,+ agentId,+ name,+ description,+ priceUsdc,+ targetUrl,+ method = 'POST',+ inputSchema = null,+ network = 'base',+ payoutAddress,+ } = input;++ const priceAtomics = usdcToAtomics(priceUsdc);+ const upperMethod = String(method).toUpperCase() === 'GET' ? 'GET' : 'POST';+ const net = network === 'solana' ? 'solana' : 'base';+ const schemaJson = inputSchema ? JSON.stringify(inputSchema) : null;++ // Retry on the (extremely unlikely) slug collision rather than failing the+ // agent's publish on a random 8-char suffix clash.+ let lastErr = null;+ for (let attempt = 0; attempt < 4; attempt++) {+ const slug = buildSlug(name);+ try {+ const [row] = await sql`+ INSERT INTO agent_paid_services+ (owner_user_id, agent_id, slug, name, description, price_atomics,+ target_url, target_method, input_schema, network, payout_address)+ VALUES (+ ${ownerUserId}, ${agentId}, ${slug}, ${name}, ${description}, ${priceAtomics},+ ${targetUrl}, ${upperMethod}, ${schemaJson}::jsonb, ${net}, ${payoutAddress}+ )+ RETURNING id, slug, name, description, price_atomics, target_url, target_method,+ input_schema, network, payout_address, bazaar_listed, created_at+ `;+ return row;+ } catch (err) {+ // 23505 = unique_violation on slug; regenerate and retry.+ if (err?.code === '23505' || /duplicate key|unique/i.test(err?.message || '')) {+ lastErr = err;+ continue;+ }+ throw err;+ }+ }+ throw lastErr || new MonetizeError('failed to allocate a unique slug', 'slug_alloc_failed', 500);+}++// Fetch one active service by slug for the hosted paywall to serve.+export async function getActiveServiceBySlug(slug) {+ if (!slug || typeof slug !== 'string') return null;+ const [row] = await sql`+ SELECT id, owner_user_id, agent_id, slug, name, description, price_atomics,+ target_url, target_method, input_schema, network, payout_address,+ bazaar_listed, created_at+ FROM agent_paid_services+ WHERE slug = ${slug} AND archived_at IS NULL+ LIMIT 1+ `;+ return row || null;+}++// Active, bazaar-listed services for the discovery doc. Capped so a flood of+// listings can't bloat the heavily-crawled /.well-known/x402.json payload.+export async function listBazaarServices({ limit = 200 } = {}) {+ const capped = Math.min(Math.max(1, limit | 0 || 200), 500);+ const rows = await sql`+ SELECT slug, name, description, price_atomics, target_method,+ input_schema, network+ FROM agent_paid_services+ WHERE archived_at IS NULL AND bazaar_listed = true+ ORDER BY created_at DESC+ LIMIT ${capped}+ `;+ return rows;+}diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.jsindex 99bc54fa2..a65dbc7c7 100644--- a/api/_lib/agent-wallet.js+++ b/api/_lib/agent-wallet.js@@ -282,6 +282,84 @@ export async function generateSolanaAgentWallet() {return { address: kp.publicKey.toBase58(), encrypted_secret };}+// Circle USDC mints — the x402 settlement asset, per cluster. Used for the+// USDC balance readout on a freshly provisioned wallet (not a coin token; $THREE+// is the only coin, USDC is the payment rail).+const USDC_MINT_BY_CLUSTER = {+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',+};++/**+ * Idempotently provision a custodial Solana wallet for an agent.+ *+ * Mirrors the POST branch of api/agents/solana-wallet.js: generate a keypair via+ * generateSolanaAgentWallet(), store the address + encrypted secret in agent+ * meta, and never re-create if one already exists. Returns { address, created }.+ */+export async function getOrCreateAgentSolanaWallet(agentId) {+ const { sql } = await import('./db.js');+ const [row] = await sql`+ select id, meta from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!row) throw new Error('agent not found');++ let meta = { ...(row.meta || {}) };+ if (meta.solana_address) {+ return { address: meta.solana_address, created: false };+ }++ const sol = await generateSolanaAgentWallet();+ meta = {+ ...meta,+ solana_address: sol.address,+ encrypted_solana_secret: sol.encrypted_secret,+ solana_wallet_source: 'generated',+ };+ await sql`update agent_identities set meta = ${JSON.stringify(meta)}::jsonb where id = ${agentId}`;+ return { address: sol.address, created: true };+}++/**+ * Read the live SOL + USDC balances for a Solana address on the given cluster.+ * Never throws — an RPC failure returns nulls so a provision call still succeeds+ * with the wallet address (balances can be re-read later via wallet_status).+ * @returns {Promise<{ sol: number|null, usdc: number|null }>}+ */+export async function getSolanaAddressBalances(address, cluster = 'mainnet') {+ const net = cluster === 'devnet' ? 'devnet' : 'mainnet';+ let sol = null;+ let usdc = null;+ try {+ const { PublicKey } = await import('@solana/web3.js');+ const { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } =+ await import('@solana/spl-token');+ const { solanaConnection } = await import('./agent-pumpfun.js');+ const conn = solanaConnection(net);+ const owner = new PublicKey(address);+ const lamports = await conn.getBalance(owner);+ sol = lamports / 1e9;+ try {+ const ata = getAssociatedTokenAddressSync(+ new PublicKey(USDC_MINT_BY_CLUSTER[net]),+ owner,+ false,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const bal = await conn.getTokenAccountBalance(ata);+ usdc = bal?.value?.uiAmount ?? 0;+ } catch {+ usdc = 0; // no ATA yet → zero USDC+ }+ } catch {+ // RPC failure — report nulls rather than throw.+ }+ return { sol, usdc };+}+/*** Recover a Solana Keypair from its encrypted form.* Only call this when the agent needs to sign a transaction.diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.jsnew file mode 100644index 000000000..2c4c8111e--- /dev/null+++ b/api/_lib/avatar-render.js@@ -0,0 +1,416 @@+// Avatar render core — the headless-chromium + three.js pipeline that turns a+// stored GLB into a PNG/JPEG/WebP, plus the param-resolution and R2 cache layer+// around it. Extracted so BOTH the public HTTP endpoint (api/avatar/render.js)+// and the render_avatar_image MCP tool share one implementation — there is no+// duplicated chromium code anywhere else.++import { createHash } from 'node:crypto';+// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()+// so Vercel's NFT does not statically trace the chromium binary tree on every+// route in a function package — that trace was the 45-min build timeout.+import { env } from './env.js';+import { publicUrl, putObject, headObject } from './r2.js';+import { PRESETS } from '../../src/pose-presets.js';++export const MIN_DIM = 64;+export const MAX_DIM = 2048;+export const DEFAULT_SIZE = 512;++export const SCENE_PRESETS = {+ 'full-body': { phi: 80, theta: 0, radiusMult: 1.0, lookAtY: 0.0 },+ 'upper-body': { phi: 82, theta: 5, radiusMult: 0.55, lookAtY: 0.15 },+ 'portrait': { phi: 84, theta: 8, radiusMult: 0.38, lookAtY: 0.30 },+ 'headshot': { phi: 86, theta: 5, radiusMult: 0.28, lookAtY: 0.38 },+};++export const FORMAT_TYPES = {+ png: 'image/png',+ jpeg: 'image/jpeg',+ webp: 'image/webp',+};++export function clamp(v, min, max) {+ return Math.max(min, Math.min(max, v));+}++function toInt(v, fallback) {+ const n = typeof v === 'number' ? Math.trunc(v) : parseInt(v, 10);+ return Number.isFinite(n) ? n : fallback;+}++// Normalize loose render inputs (HTTP query strings or MCP-typed values) into a+// validated param set, or an { error } the caller maps to its own error shape.+// Validates scene / pose / expression exactly as the public endpoint always has.+export function resolveRenderParams(input = {}) {+ const sceneName = input.scene || 'upper-body';+ const scenePreset = SCENE_PRESETS[sceneName];+ if (!scenePreset) {+ return {+ error: {+ code: 'invalid_scene',+ message: `Unknown scene "${sceneName}". Valid: ${Object.keys(SCENE_PRESETS).join(', ')}`,+ },+ };+ }++ const size = clamp(toInt(input.size, DEFAULT_SIZE), MIN_DIM, MAX_DIM);+ const width = clamp(toInt(input.width, size), MIN_DIM, MAX_DIM);+ const height = clamp(toInt(input.height, size), MIN_DIM, MAX_DIM);+ const bg = input.bg || 'transparent';+ const format = FORMAT_TYPES[input.format] ? input.format : 'png';+ const quality = clamp(toInt(input.quality, 90), 1, 100);++ let posePresetId = null;+ if (input.pose) {+ const found = PRESETS.find((p) => p.id === input.pose);+ if (!found) {+ return {+ error: {+ code: 'unknown_pose',+ message: `Unknown pose "${input.pose}". GET /api/avatar/render for the catalog.`,+ },+ };+ }+ posePresetId = found.id;+ }++ let expression = null;+ if (input.expression != null) {+ let exp = input.expression;+ if (typeof exp === 'string') {+ try {+ exp = JSON.parse(exp);+ } catch {+ return {+ error: {+ code: 'invalid_expression',+ message: 'expression must be a JSON object of morph targets',+ },+ };+ }+ }+ if (typeof exp !== 'object' || exp === null || Array.isArray(exp)) {+ return {+ error: {+ code: 'invalid_expression',+ message: 'expression must be a JSON object of morph targets',+ },+ };+ }+ expression = exp;+ }++ return { params: { scene: sceneName, scenePreset, size, width, height, bg, format, quality, posePresetId, expression } };+}++function cacheKey(avatarId, paramsHash, format) {+ return `renders/${avatarId}/${paramsHash}.${format}`;+}++function hashParams(obj) {+ return createHash('sha256').update(JSON.stringify(obj)).digest('hex').slice(0, 16);+}++// Deterministic cache fingerprint. Includes avatar.updated_at so any change to+// the avatar (appearance, GLB, etc.) automatically busts every cached render.+function renderFingerprint(updatedAt, params) {+ return hashParams({+ scene: params.scene,+ w: params.width,+ h: params.height,+ bg: params.bg,+ format: params.format,+ quality: params.quality,+ pose: params.posePresetId,+ expression: params.expression,+ updated: updatedAt,+ });+}++// Resolve the render from cache, or render fresh + persist to R2 and return it.+// avatar the avatar row (needs id + updated_at for the cache key)+// glbUrl fetchable GLB URL (public CDN for public/unlisted, signed for private)+// params a resolveRenderParams() result.params+// awaitUpload true → await the R2 write so the returned imageUrl is live+// (MCP callers that only get a URL back)+// false → fire the write in the background and hand back the+// buffer the caller already holds (the HTTP endpoint)+// Returns { cached, key, imageUrl, buffer, contentType }. buffer is null on a hit.+export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload = false }) {+ const contentType = FORMAT_TYPES[params.format];+ const fingerprint = renderFingerprint(avatar.updated_at, params);+ const key = cacheKey(avatar.id, fingerprint, params.format);++ try {+ const head = await headObject(key);+ if (head) {+ return { cached: true, key, imageUrl: publicUrl(key), buffer: null, contentType };+ }+ } catch {+ // Cache miss — render fresh.+ }++ const cameraOrbit = { theta: params.scenePreset.theta, phi: params.scenePreset.phi, radius: null };+ const { png } = await renderAvatarScene({+ glbUrl,+ width: params.width,+ height: params.height,+ background: params.bg,+ posePresetId: params.posePresetId,+ cameraOrbit,+ expression: params.expression,+ scenePreset: params.scenePreset,+ });++ const put = putObject({+ key,+ body: png,+ contentType,+ metadata: { avatar_id: avatar.id, scene: params.scene, params: fingerprint },+ });+ if (awaitUpload) {+ await put;+ } else {+ put.catch((err) => console.warn('[avatar-render] cache write failed:', err?.message));+ }++ return { cached: false, key, imageUrl: publicUrl(key), buffer: png, contentType };+}++const DEFAULT_CHROMIUM_PACK =+ 'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';+const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;+const THREE_VERSION = '0.176.0';++let _browserPromise = null;+async function getBrowser() {+ if (_browserPromise) return _browserPromise;+ _browserPromise = (async () => {+ const [{ default: puppeteer }, { default: chromium }] = await Promise.all([+ import('puppeteer-core'),+ import('@sparticuz/chromium-min'),+ ]);+ const executablePath = await chromium.executablePath(CHROMIUM_PACK);+ return puppeteer.launch({+ args: chromium.args,+ defaultViewport: { width: 1024, height: 1024, deviceScaleFactor: 1 },+ executablePath,+ headless: chromium.headless,+ });+ })().catch((err) => {+ _browserPromise = null;+ throw err;+ });+ return _browserPromise;+}++function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {+ const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');+ const poseJson = pose ? JSON.stringify(pose) : 'null';+ const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });+ const expressionJson = JSON.stringify(expression || null);+ const presetJson = JSON.stringify(scenePreset);++ return `<!doctype html>+<html><head><meta charset="utf-8" />+<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>+</head><body>+<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>+<script type="importmap">{ "imports": {+ "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",+ "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"+}}</script>+<script type="module">+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';++window.__renderDone = false;+window.__renderError = null;++const canvas = document.getElementById('c');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });+renderer.setSize(${width}, ${height}, false);+renderer.setPixelRatio(1);+renderer.outputColorSpace = THREE.SRGBColorSpace;+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.0;++const scene = new THREE.Scene();+const bgColor = ${bg};+if (bgColor !== null) scene.background = new THREE.Color(bgColor);++const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);++scene.add(new THREE.AmbientLight(0xffffff, 0.6));+const key = new THREE.DirectionalLight(0xffffff, 1.5);+key.position.set(2, 3, 4); scene.add(key);+const fill = new THREE.DirectionalLight(0xbfd6ff, 0.65);+fill.position.set(-3, 1, 2); scene.add(fill);+const rim = new THREE.DirectionalLight(0xc7a8ff, 0.55);+rim.position.set(0, 2, -4); scene.add(rim);+const bottom = new THREE.DirectionalLight(0xffffff, 0.15);+bottom.position.set(0, -2, 1); scene.add(bottom);++const aliases = {+ shoulderl: ['leftshoulder','shoulder_l','l_shoulder','mixamorig:leftshoulder'],+ shoulderr: ['rightshoulder','shoulder_r','r_shoulder','mixamorig:rightshoulder'],+ elbowl: ['leftforearm','leftelbow','elbow_l','mixamorig:leftforearm','mixamorig:leftelbow'],+ elbowr: ['rightforearm','rightelbow','elbow_r','mixamorig:rightforearm','mixamorig:rightelbow'],+ wristl: ['lefthand','wrist_l','mixamorig:lefthand'],+ wristr: ['righthand','wrist_r','mixamorig:righthand'],+ hipl: ['leftupleg','hip_l','mixamorig:leftupleg'],+ hipr: ['rightupleg','hip_r','mixamorig:rightupleg'],+ kneel: ['leftleg','knee_l','mixamorig:leftleg'],+ kneer: ['rightleg','knee_r','mixamorig:rightleg'],+ anklel: ['leftfoot','ankle_l','mixamorig:leftfoot'],+ ankler: ['rightfoot','ankle_r','mixamorig:rightfoot'],+ head: ['head','mixamorig:head'],+ neck: ['neck','mixamorig:neck'],+ spine: ['spine','spine1','mixamorig:spine','mixamorig:spine1'],+ hips: ['hips','mixamorig:hips'],+};++function applyPose(root, poseMap) {+ if (!poseMap) return;+ const byName = new Map();+ root.traverse((o) => { if (o.name) byName.set(o.name.toLowerCase(), o); });+ function findJoint(k) {+ const key = k.toLowerCase();+ const direct = byName.get(key);+ if (direct) return direct;+ const list = aliases[key] || [];+ for (const a of list) { const j = byName.get(a); if (j) return j; }+ return null;+ }+ for (const [key, rot] of Object.entries(poseMap)) {+ const joint = findJoint(key);+ if (!joint) continue;+ joint.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);+ }+}++function applyExpression(root, expression) {+ if (!expression || typeof expression !== 'object') return;+ root.traverse((o) => {+ if (!o.isMesh || !o.morphTargetDictionary || !o.morphTargetInfluences) return;+ for (const [name, value] of Object.entries(expression)) {+ const idx = o.morphTargetDictionary[name] ?? o.morphTargetDictionary[name.toLowerCase()];+ if (typeof idx === 'number') o.morphTargetInfluences[idx] = Number(value) || 0;+ }+ });+}++function frameCameraForScene(root, orbit, preset) {+ const box = new THREE.Box3().setFromObject(root);+ const size = new THREE.Vector3(); box.getSize(size);+ const center = new THREE.Vector3(); box.getCenter(center);++ root.position.sub(center);++ const halfH = size.y * 0.5;+ const lookAtY = halfH * (preset.lookAtY || 0);++ root.position.y += size.y * 0.05;++ const maxDim = Math.max(size.x, size.y, size.z);+ const fov = THREE.MathUtils.degToRad(camera.fov);+ const defaultDist = (maxDim / 2) / Math.tan(fov / 2) * 1.45;+ const radius = defaultDist * (preset.radiusMult || 1.0);++ const theta = THREE.MathUtils.degToRad(Number(orbit.theta) || 0);+ const phi = THREE.MathUtils.degToRad(Number(orbit.phi) || 80);+ const x = radius * Math.sin(phi) * Math.sin(theta);+ const y = radius * Math.cos(phi) + lookAtY;+ const z = radius * Math.sin(phi) * Math.cos(theta);+ camera.position.set(x, y, z);+ camera.lookAt(0, lookAtY, 0);+}++const orbit = ${orbitJson};+const poseMap = ${poseJson};+const expression = ${expressionJson};+const preset = ${presetJson};++// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;+// a bare GLTFLoader throws "No DRACOLoader instance provided". Register+// every standard compression decoder from the pinned three.js release.+const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';+const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');+const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);++const loader = new GLTFLoader();+loader.setDRACOLoader(dracoLoader);+loader.setKTX2Loader(ktx2Loader);+loader.setMeshoptDecoder(MeshoptDecoder);++loader.load(${JSON.stringify(glbUrl)}, (gltf) => {+ try {+ const root = gltf.scene;+ scene.add(root);+ applyPose(root, poseMap);+ applyExpression(root, expression);+ frameCameraForScene(root, orbit, preset);+ renderer.render(scene, camera);+ requestAnimationFrame(() => {+ renderer.render(scene, camera);+ window.__renderDone = true;+ });+ } catch (err) {+ window.__renderError = err.message || String(err);+ }+}, undefined, (err) => {+ window.__renderError = 'glb load failed: ' + (err?.message || err);+});+</script></body></html>`;+}++export async function renderAvatarScene({+ glbUrl,+ width = 512,+ height = 512,+ background = 'transparent',+ posePresetId = null,+ cameraOrbit = null,+ expression = null,+ scenePreset = SCENE_PRESETS['upper-body'],+} = {}) {+ const W = clamp(Number(width) || 512, MIN_DIM, MAX_DIM);+ const H = clamp(Number(height) || 512, MIN_DIM, MAX_DIM);++ let pose = null;+ if (posePresetId) {+ const found = PRESETS.find((p) => p.id === posePresetId);+ if (found) pose = found.pose;+ }++ const browser = await getBrowser();+ const page = await browser.newPage();+ try {+ await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });+ const html = sceneViewerHtml({+ glbUrl, width: W, height: H, background,+ pose, cameraOrbit: cameraOrbit || { theta: 0, phi: 80, radius: null },+ expression, scenePreset,+ });+ await page.setContent(html, { waitUntil: 'domcontentloaded' });+ await page.waitForFunction(+ 'window.__renderDone === true || window.__renderError !== null',+ { timeout: 20_000 },+ );+ const err = await page.evaluate(() => window.__renderError);+ if (err) {+ throw Object.assign(new Error(`render failed: ${err}`), { status: 502, code: 'render_failed' });+ }+ const png = await page.screenshot({+ type: 'png',+ omitBackground: background === 'transparent',+ clip: { x: 0, y: 0, width: W, height: H },+ });+ return { png };+ } finally {+ await page.close().catch(() => {});+ }+}diff --git a/api/_lib/embed.js b/api/_lib/embed.jsnew file mode 100644index 000000000..f6219adb7--- /dev/null+++ b/api/_lib/embed.js@@ -0,0 +1,84 @@+// Shared embed-snippet builders.+//+// Both the oEmbed provider (api/agent-oembed.js) and the get_embed_code MCP tool+// hand callers a copy-paste <iframe> that unfurls a three.ws 3D viewer inline in+// Notion / Webflow / Framer / a blog. They render that iframe through THESE+// helpers so the markup and the canonical URL shapes never drift between the two+// surfaces. Nothing here touches the database or the network — pure URL/string+// assembly — so it's cheap to import from a serverless handler.++// Social-card dimensions every three.ws OG endpoint emits (agent/og, a-og,+// forge-og). Exposed so oEmbed payloads can advertise a correct thumbnail size.+export const EMBED_THUMB = { width: 1200, height: 630 };++// Clamp a caller-supplied width/height to sane bounds, falling back to a default+// for missing or nonsensical input. Embeds clamp rather than error so a too-big+// number still yields a usable snippet (see the get_embed_code contract).+export function clampEmbedDim(raw, fallback, min, max) {+ const n = raw === null || raw === undefined || raw === '' ? NaN : parseInt(raw, 10);+ if (!Number.isFinite(n) || n <= 0) return fallback;+ return Math.max(min, Math.min(max, n));+}++function escapeAttr(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++// The single canonical embed iframe used everywhere three.ws hands out a snippet:+// sandboxed, lazy-loaded, responsive (max-width:100%), AR/XR + fullscreen capable.+// autorotate/ar default on; when either is turned off it's appended as a query+// hint the embed page can honor (and which is harmless to pages that don't).+export function buildEmbedIframe({ src, width, height, title, autorotate = true, ar = true }) {+ const hints = [];+ if (autorotate === false) hints.push('autorotate=0');+ if (ar === false) hints.push('ar=0');+ const url = hints.length ? `${src}${src.includes('?') ? '&' : '?'}${hints.join('&')}` : src;+ const titleAttr = title ? ` title="${escapeAttr(title)}"` : '';+ return (+ `<iframe src="${escapeAttr(url)}" width="${width}" height="${height}"${titleAttr} ` ++ `loading="lazy" style="border:0;border-radius:12px;max-width:100%" ` ++ `allow="autoplay; fullscreen; xr-spatial-tracking" allowfullscreen ` ++ `sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`+ );+}++// ── Canonical URL shapes per target ──────────────────────────────────────────+// embedUrl → the iframe src (renders the 3D viewer standalone)+// shareUrl → the human-facing page to link/share+// thumbnailUrl→ the Open Graph social card++export function agentEmbedTarget(origin, id) {+ return {+ embedUrl: `${origin}/agent/${id}/embed`,+ shareUrl: `${origin}/agent/${id}`,+ thumbnailUrl: `${origin}/api/agent/${id}/og`,+ };+}++export function onchainEmbedTarget(origin, chainId, agentId) {+ const enc = encodeURIComponent(String(agentId));+ return {+ embedUrl: `${origin}/a/${chainId}/${enc}/embed`,+ shareUrl: `${origin}/a/${chainId}/${enc}`,+ thumbnailUrl: `${origin}/api/a-og?chain=${chainId}&id=${enc}`,+ };+}++export function forgeEmbedTarget(origin, id) {+ const enc = encodeURIComponent(String(id));+ return {+ embedUrl: `${origin}/forge?share=${enc}`,+ shareUrl: `${origin}/forge/share/${id}`,+ thumbnailUrl: `${origin}/api/forge/${id}/og`,+ };+}++// oEmbed discovery URL for a target the /api/oembed provider resolves (agents and+// on-chain agents). Returns the endpoint that yields the oEmbed JSON for shareUrl.+export function oembedUrl(origin, shareUrl) {+ return `${origin}/api/oembed?url=${encodeURIComponent(shareUrl)}`;+}diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.jsindex 3a3abcfef..0a010cacb 100644--- a/api/_lib/fetch-model.js+++ b/api/_lib/fetch-model.js@@ -3,23 +3,18 @@// Arbitrary URL fetching from a server reachable by the internet is a classic// SSRF vector: an attacker can point "url" at internal metadata endpoints// (169.254.169.254 on AWS/GCP), private RFC1918 ranges, or loopback and we'd-// happily proxy the response back to them. Defenses here:-// 1. Scheme allowlist — only https by default (http permitted in dev).-// 2. DNS resolution happens on OUR side, and the resolved address is-// checked against an IP blocklist before the connection is opened.-// 3. Follow redirects manually, re-validating the target host each hop.-// 4. Size limit — we stop reading after N bytes.-// 5. Timeout — total request + streaming is bounded.+// happily proxy the response back to them. The SSRF policy (scheme allowlist,+// our-side DNS resolution + IP blocklist, connection pinning, per-hop redirect+// re-validation) lives in api/_lib/ssrf.js and is shared with the x402 monetize+// proxy. This fetcher adds the model-specific concerns on top: a byte size cap+// and a total request/streaming timeout.-import { lookup } from 'node:dns/promises';-import { Agent } from 'undici';+import { SsrfError, pinnedAgent, resolvePublicHost, validatePublicUrl } from './ssrf.js';const DEFAULT_MAX_BYTES = 50 * 1024 * 1024; // 50 MBconst DEFAULT_TIMEOUT_MS = 20_000;const MAX_REDIRECTS = 3;-const IS_DEV = process.env.NODE_ENV !== 'production';-export class FetchModelError extends Error {constructor(message, code = 'fetch_failed') {super(message);@@ -27,107 +22,19 @@ export class FetchModelError extends Error {}}-function isPrivateIPv4(ip) {- const p = ip.split('.').map(Number);- if (p.length !== 4 || p.some((n) => Number.isNaN(n))) return true;- if (p[0] === 10) return true;- if (p[0] === 127) return true;- if (p[0] === 0) return true;- if (p[0] === 169 && p[1] === 254) return true; // link-local, cloud metadata- if (p[0] === 172 && p[1] >= 16 && p[1] <= 31) return true;- if (p[0] === 192 && p[1] === 168) return true;- if (p[0] === 192 && p[1] === 0 && p[2] === 0) return true; // IETF- if (p[0] === 192 && p[1] === 0 && p[2] === 2) return true; // docs- if (p[0] === 198 && (p[1] === 18 || p[1] === 19)) return true; // benchmark- if (p[0] === 198 && p[1] === 51 && p[2] === 100) return true; // docs- if (p[0] === 203 && p[1] === 0 && p[2] === 113) return true; // docs- if (p[0] >= 224) return true; // multicast + reserved- return false;-}--function isPrivateIPv6(ip) {- const lower = ip.toLowerCase();- if (lower === '::' || lower === '::1') return true;- if (lower.startsWith('fe80:') || lower.startsWith('fe80::')) return true; // link-local- if (lower.startsWith('fc') || lower.startsWith('fd')) return true; // ULA fc00::/7- if (lower.startsWith('::ffff:')) {- const mapped = lower.replace(/^::ffff:/, '');- if (/^\d+\.\d+\.\d+\.\d+$/.test(mapped)) return isPrivateIPv4(mapped);- }- if (lower.startsWith('2001:db8:')) return true; // docs- return false;-}--function isPrivateAddress(address, family) {- if (family === 4) return isPrivateIPv4(address);- if (family === 6) return isPrivateIPv6(address);- // Unknown family — treat as unsafe.- return true;-}--// Resolve `host` once, reject if ANY resolved address is private, and return the-// validated address list. The caller pins the connection to exactly these-// addresses (via a custom undici `lookup`) so a DNS-rebinding attacker who-// returns a public IP at validation time and a private IP at connect time-// cannot reach internal services — we never re-resolve through the OS.-async function resolvePublicHost(host) {- if (!host) throw new FetchModelError('missing host', 'invalid_url');- let resolved;- try {- resolved = await lookup(host, { all: true });- } catch (e) {- throw new FetchModelError(`DNS lookup failed for ${host}`, 'dns_failed');- }- const addrs = Array.isArray(resolved) ? resolved : [resolved];- if (!addrs.length) throw new FetchModelError(`DNS lookup failed for ${host}`, 'dns_failed');- for (const { address, family } of addrs) {- if (isPrivateAddress(address, family)) {- throw new FetchModelError(- `host resolves to private address: ${address}`,- 'private_address',- );- }- }- return addrs;-}--// Build an undici Agent whose DNS `lookup` only ever yields the pre-validated-// addresses for `expectedHost`. Any connect attempt to a different host (e.g.-// after an internal redirect we didn't re-pin) or with no validated address is-// refused. This closes the check-then-connect TOCTOU: the address the socket-// connects to is byte-for-byte one we already asserted is public.-function pinnedAgent(expectedHost, addrs) {- return new Agent({- connect: {- lookup(hostname, _opts, cb) {- if (hostname !== expectedHost) {- cb(new FetchModelError(`unexpected connect host: ${hostname}`, 'host_pin_mismatch'));- return;- }- // undici accepts an array of { address, family } entries. Re-assert- // here as defense-in-depth in case a resolver returned mixed records.- const safe = addrs.filter((a) => !isPrivateAddress(a.address, a.family));- if (!safe.length) {- cb(new FetchModelError('no public address to connect to', 'private_address'));- return;- }- cb(null, safe.map((a) => ({ address: a.address, family: a.family })));- },- },- });+// Map a shared SsrfError to the FetchModelError shape callers already expect, so+// existing { code: 'private_address' } / 'scheme_not_allowed' assertions hold.+function asFetchModelError(err) {+ if (err instanceof SsrfError) return new FetchModelError(err.message, err.code);+ return err;}function validateUrl(rawUrl) {- let url;try {- url = new URL(rawUrl);- } catch {- throw new FetchModelError('invalid URL', 'invalid_url');- }- if (url.protocol !== 'https:' && !(IS_DEV && url.protocol === 'http:')) {- throw new FetchModelError(`scheme not allowed: ${url.protocol}`, 'scheme_not_allowed');+ return validatePublicUrl(rawUrl);+ } catch (err) {+ throw asFetchModelError(err);}- return url;}/**diff --git a/api/_lib/migrations/2026-06-08-agent-paid-services.sql b/api/_lib/migrations/2026-06-08-agent-paid-services.sqlnew file mode 100644index 000000000..ccade53e2--- /dev/null+++ b/api/_lib/migrations/2026-06-08-agent-paid-services.sql@@ -0,0 +1,58 @@+-- Agent-published paid x402 services.+--+-- The `monetize_endpoint` MCP tool lets an agent put a price on an upstream it+-- already serves and earn USDC when other agents pay to call it. Each row is a+-- priced wrapper: three.ws hosts the x402 paywall at /api/x402/service/<slug>,+-- settles the buyer's USDC to the agent's own payout wallet, then proxies the+-- request through to `target_url`. The row is the source of truth the hosted+-- endpoint reads per request AND the entry the /.well-known/x402.json discovery+-- doc surfaces so facilitators (and therefore find_services / the bazaar) index+-- it.+--+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-08-agent-paid-services.sql+-- Idempotent.++CREATE TABLE IF NOT EXISTS agent_paid_services (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,++ -- public-facing identifier; the hosted resource URL is /api/x402/service/<slug>+ slug text NOT NULL UNIQUE+ CONSTRAINT agent_paid_services_slug_format+ CHECK (slug ~ '^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$'),++ name text NOT NULL,+ description text NOT NULL,++ -- USDC atomic units (6 decimals); stored as text so it round-trips as bigint+ price_atomics text NOT NULL+ CONSTRAINT agent_paid_services_price_format+ CHECK (price_atomics ~ '^[1-9][0-9]*$'),++ -- the upstream the agent already serves; SSRF-validated before insert+ target_url text NOT NULL,+ target_method text NOT NULL DEFAULT 'POST'+ CHECK (target_method IN ('GET', 'POST')),+ input_schema jsonb,++ -- settlement network + the agent's own wallet that receives the USDC+ network text NOT NULL DEFAULT 'base'+ CHECK (network IN ('base', 'solana')),+ payout_address text NOT NULL,++ bazaar_listed boolean NOT NULL DEFAULT true,++ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ archived_at timestamptz+);++CREATE INDEX IF NOT EXISTS idx_agent_paid_services_owner+ ON agent_paid_services (owner_user_id, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_agent_paid_services_agent+ ON agent_paid_services (agent_id, created_at DESC);+-- Discovery doc + bazaar listing pull the active, listed rows.+CREATE INDEX IF NOT EXISTS idx_agent_paid_services_listed+ ON agent_paid_services (created_at DESC)+ WHERE archived_at IS NULL AND bazaar_listed = true;diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 4299fd63d..521d5548c 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -314,6 +314,10 @@ export const limits = {// Agent wallet read endpoints (GET balance, activity). Per authenticated user.walletRead: (userId) => getLimiter('wallet:read', { limit: 60, window: '1 m' }).limit(userId),agentSuggest: (ip) => getLimiter('agents:suggest', { limit: 120, window: '1 m' }).limit(ip),+ // On-chain agent registration (register_agent MCP tool). Each call may mint a+ // Core asset + Agent Identity PDA — real SOL spend — so this is deliberately+ // tight, keyed per authenticated user.+ agentRegister: (userId) => getLimiter('agent:register', { limit: 12, window: '1 h' }).limit(userId),read: (ip) => getLimiter('permissions:read', { limit: 300, window: '1 m' }).limit(ip),permissionsGrant: (userId) =>getLimiter('permissions:grant', { limit: 10, window: '1 h' }).limit(userId),diff --git a/api/_lib/ssrf.js b/api/_lib/ssrf.jsnew file mode 100644index 000000000..dbe1f69c1--- /dev/null+++ b/api/_lib/ssrf.js@@ -0,0 +1,187 @@+// SSRF guard primitives, shared by every server-side fetcher of untrusted URLs.+//+// Fetching an attacker-supplied URL from a server reachable by the internet is a+// classic SSRF vector: the URL can point at cloud metadata (169.254.169.254),+// RFC1918 ranges, or loopback, and we'd happily proxy the response back. The+// defenses here are the ones api/_lib/fetch-model.js pioneered, factored out so+// the x402 monetize proxy (and anything else) enforces the exact same policy:+// 1. Scheme allowlist — https only (http permitted in dev).+// 2. DNS resolution on OUR side; every resolved address checked against an IP+// blocklist before a socket opens.+// 3. Connections pinned to the validated addresses (custom undici lookup) so a+// DNS-rebinding host can't swap in a private IP at connect time.+// 4. Redirects followed manually, re-validating the target host each hop.++import { lookup } from 'node:dns/promises';+import { Agent } from 'undici';++const IS_DEV = process.env.NODE_ENV !== 'production';++export class SsrfError extends Error {+ constructor(message, code = 'blocked') {+ super(message);+ this.name = 'SsrfError';+ this.code = code;+ }+}++export function isPrivateIPv4(ip) {+ const p = ip.split('.').map(Number);+ if (p.length !== 4 || p.some((n) => Number.isNaN(n))) return true;+ if (p[0] === 10) return true;+ if (p[0] === 127) return true;+ if (p[0] === 0) return true;+ if (p[0] === 169 && p[1] === 254) return true; // link-local, cloud metadata+ if (p[0] === 172 && p[1] >= 16 && p[1] <= 31) return true;+ if (p[0] === 192 && p[1] === 168) return true;+ if (p[0] === 192 && p[1] === 0 && p[2] === 0) return true; // IETF+ if (p[0] === 192 && p[1] === 0 && p[2] === 2) return true; // docs+ if (p[0] === 198 && (p[1] === 18 || p[1] === 19)) return true; // benchmark+ if (p[0] === 198 && p[1] === 51 && p[2] === 100) return true; // docs+ if (p[0] === 203 && p[1] === 0 && p[2] === 113) return true; // docs+ if (p[0] >= 224) return true; // multicast + reserved+ return false;+}++export function isPrivateIPv6(ip) {+ const lower = ip.toLowerCase();+ if (lower === '::' || lower === '::1') return true;+ if (lower.startsWith('fe80:') || lower.startsWith('fe80::')) return true; // link-local+ if (lower.startsWith('fc') || lower.startsWith('fd')) return true; // ULA fc00::/7+ if (lower.startsWith('::ffff:')) {+ const mapped = lower.replace(/^::ffff:/, '');+ if (/^\d+\.\d+\.\d+\.\d+$/.test(mapped)) return isPrivateIPv4(mapped);+ }+ if (lower.startsWith('2001:db8:')) return true; // docs+ return false;+}++export function isPrivateAddress(address, family) {+ if (family === 4) return isPrivateIPv4(address);+ if (family === 6) return isPrivateIPv6(address);+ return true; // unknown family → unsafe+}++// Resolve `host` once, reject if ANY resolved address is private, and return the+// validated address list to pin the connection to.+export async function resolvePublicHost(host) {+ if (!host) throw new SsrfError('missing host', 'invalid_url');+ let resolved;+ try {+ resolved = await lookup(host, { all: true });+ } catch {+ throw new SsrfError(`DNS lookup failed for ${host}`, 'dns_failed');+ }+ const addrs = Array.isArray(resolved) ? resolved : [resolved];+ if (!addrs.length) throw new SsrfError(`DNS lookup failed for ${host}`, 'dns_failed');+ for (const { address, family } of addrs) {+ if (isPrivateAddress(address, family)) {+ throw new SsrfError(`host resolves to private address: ${address}`, 'private_address');+ }+ }+ return addrs;+}++// undici Agent whose DNS lookup only yields the pre-validated addresses for+// `expectedHost`, closing the check-then-connect TOCTOU.+export function pinnedAgent(expectedHost, addrs) {+ return new Agent({+ connect: {+ lookup(hostname, _opts, cb) {+ if (hostname !== expectedHost) {+ cb(new SsrfError(`unexpected connect host: ${hostname}`, 'host_pin_mismatch'));+ return;+ }+ const safe = addrs.filter((a) => !isPrivateAddress(a.address, a.family));+ if (!safe.length) {+ cb(new SsrfError('no public address to connect to', 'private_address'));+ return;+ }+ cb(null, safe.map((a) => ({ address: a.address, family: a.family })));+ },+ },+ });+}++// Parse + scheme-check a URL. https only (http allowed in dev). Returns the URL.+export function validatePublicUrl(rawUrl, { allowHttp = IS_DEV } = {}) {+ let url;+ try {+ url = new URL(rawUrl);+ } catch {+ throw new SsrfError('invalid URL', 'invalid_url');+ }+ if (url.protocol !== 'https:' && !(allowHttp && url.protocol === 'http:')) {+ throw new SsrfError(`scheme not allowed: ${url.protocol}`, 'scheme_not_allowed');+ }+ return url;+}++// Static + DNS validation for a user-supplied target URL at registration time.+// Resolves the host so a URL pointing at a private IP is rejected before we ever+// store it. Returns the normalized href.+export async function assertPublicHttpsUrl(rawUrl, opts = {}) {+ const url = validatePublicUrl(rawUrl, opts);+ await resolvePublicHost(url.hostname);+ return url.href;+}++// SSRF-guarded fetch of an untrusted URL, re-validating each redirect hop and+// returning the parsed JSON (or raw text when not JSON). Used by the x402 paid+// proxy to relay a buyer's call to the agent's upstream `target_url`.+export async function safeFetchJson(+ rawUrl,+ { method = 'GET', headers = {}, body, timeoutMs = 25_000, maxRedirects = 3, allowHttp } = {},+) {+ let currentUrl = validatePublicUrl(rawUrl, { allowHttp });+ let redirects = 0;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ let agent = null;+ try {+ while (true) {+ const addrs = await resolvePublicHost(currentUrl.hostname);+ if (agent) await agent.close().catch(() => {});+ agent = pinnedAgent(currentUrl.hostname, addrs);++ const res = await fetch(currentUrl, {+ method,+ redirect: 'manual',+ signal: controller.signal,+ dispatcher: agent,+ headers: {+ 'user-agent': '3d-agent-x402/1.0 (+https://three.ws/)',+ accept: 'application/json, text/plain;q=0.8, */*;q=0.5',+ ...(body != null ? { 'content-type': 'application/json' } : {}),+ ...headers,+ },+ ...(body != null ? { body: typeof body === 'string' ? body : JSON.stringify(body) } : {}),+ });++ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {+ if (++redirects > maxRedirects) {+ throw new SsrfError('too many redirects', 'too_many_redirects');+ }+ currentUrl = validatePublicUrl(new URL(res.headers.get('location'), currentUrl).toString(), {+ allowHttp,+ });+ continue;+ }++ const text = await res.text();+ let data = text;+ const ct = res.headers.get('content-type') || '';+ if (ct.includes('application/json') || ct.includes('+json')) {+ try {+ data = text ? JSON.parse(text) : null;+ } catch {+ data = text;+ }+ }+ return { status: res.status, ok: res.ok, contentType: ct, data };+ }+ } finally {+ clearTimeout(timer);+ if (agent) await agent.close().catch(() => {});+ }+}diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex ac673b1bc..6ebaf800e 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -7,14 +7,18 @@ import { toolDefs as solanaDefs } from './tools/solana.js';import { toolDefs as pumpfunDefs } from './tools/pumpfun.js';import { toolDefs as agentDefs } from './tools/agents.js';import { toolDefs as animationDefs } from './tools/animations.js';+import { toolDefs as memoryDefs } from './tools/memory.js';+import { toolDefs as embedDefs } from './tools/embed.js';const allDefs = [...avatarDefs,+ ...embedDefs,...modelDefs,...animationDefs,...solanaDefs,...pumpfunDefs,...agentDefs,+ ...memoryDefs,];// Schema objects for tools/list — strip internal fields (scope, handler).diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.jsindex 669b66094..8d139d5bb 100644--- a/api/_mcp/dispatch.js+++ b/api/_mcp/dispatch.js@@ -108,6 +108,7 @@ async function onInitialize(_params, _auth) {'Render 3D avatars stored on three.ws as <model-viewer> HTML artifacts.',"Use list_my_avatars to see the user's avatars and render_avatar to get embeddable viewer HTML.",'Public avatars can be discovered via search_public_avatars.',+ 'Give an agent persistent memory: remember stores a memory for an agent you own, recall retrieves the most relevant memories for a query, and forget deletes one.',].join(' '),};}diff --git a/api/_mcp/origin.js b/api/_mcp/origin.jsnew file mode 100644index 000000000..4f859f9e8--- /dev/null+++ b/api/_mcp/origin.js@@ -0,0 +1,15 @@+// Resolve the public site origin for building absolute URLs in MCP tool output.+//+// Prefers explicit env (stable across preview deploys); falls back to the+// request Host header, then VERCEL_URL. Shared by every tool that emits links+// (animation catalogue fetches, embed snippets) so origin resolution lives in+// exactly one place.+export function resolveOrigin(req) {+ const env =+ process.env.APP_ORIGIN || process.env.PUBLIC_ORIGIN || process.env.PUBLIC_APP_ORIGIN;+ if (env) return env.replace(/\/$/, '');+ const host = req?.headers?.host;+ if (host) return `${/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https'}://${host}`;+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;+ throw new Error('cannot resolve site origin');+}diff --git a/api/_mcp/tools/agents.js b/api/_mcp/tools/agents.jsindex 5b4132b61..7e3d5c976 100644--- a/api/_mcp/tools/agents.js+++ b/api/_mcp/tools/agents.js@@ -1,5 +1,24 @@+import { sql } from '../../_lib/db.js';import { limits } from '../../_lib/rate-limit.js';import { runAgentDelegation, AgentNotFoundError } from '../../_lib/agent-delegate.js';+import { checkIdentityIntegrity } from '../../_lib/identity-integrity.js';+import { agentHomeUrl } from '../../_lib/three-brand.js';+import { getAgentCollection } from '../../_lib/solana-collection.js';+import {+ authoritySecret,+ buildAuthorityUmi,+ loadCollectionAsset,+ deployAgentOnce,+ registerAgentOnce,+ explorerUrl,+} from '../../_lib/onchain-deploy.js';+import { buildRegistrationJSON } from '../../../src/erc8004/registration-json.js';+import { REGISTRY_DEPLOYMENTS } from '../../../src/erc8004/abi.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// Base mainnet — the EVM chain we expose for ERC-8004 self-registration.+const BASE_CHAIN_ID = 8453;function rpcError(code, message, data) {const e = new Error(message);@@ -8,6 +27,160 @@ function rpcError(code, message, data) {return e;}+// A tool result that carries both human-readable text and the structured+// payload. `isError` marks designed *error* states (sign-in required, unknown+// agent, unconfigured registry) — distinct from designed *non-error* states+// (registered, already_registered, needs_wallet_signature) which return ok.+function toolResult(structured, { isError = false } = {}) {+ return {+ content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],+ structuredContent: structured,+ ...(isError ? { isError: true } : {}),+ };+}++function designedError(status, message, extra = {}) {+ return toolResult({ status, error: status, message, ...extra }, { isError: true });+}++// Resolve which Solana network to register on. An explicit `network` wins;+// otherwise follow where the agent already lives on-chain; otherwise prefer the+// network that has a configured collection. Keeps register/read paths aligned.+function resolveSolanaNetwork(meta, requested) {+ if (requested === 'mainnet' || requested === 'devnet') return requested;+ if (meta?.sol_mint_address) return 'mainnet';+ if (meta?.devnet?.sol_mint_address) return 'devnet';+ if (getAgentCollection('mainnet')) return 'mainnet';+ if (getAgentCollection('devnet')) return 'devnet';+ return 'mainnet';+}++// Build the prepared ERC-8004 "continue in browser" payload for the EVM path.+// The Base register() call needs the user's own wallet to sign, so we never+// fabricate a tx — we return the exact registration JSON plus a deep link to+// the web deploy flow with everything pre-filled.+function prepareBaseRegistration(agent) {+ const deployment = REGISTRY_DEPLOYMENTS[BASE_CHAIN_ID];+ const registrationJson = buildRegistrationJSON({+ name: agent.name,+ description: agent.description || '',+ // agentId is assigned on-chain by register() — unknown until the user signs.+ agentId: null,+ chainId: BASE_CHAIN_ID,+ registryAddr: deployment.identityRegistry,+ x402Support: true,+ });+ return toolResult({+ status: 'needs_wallet_signature',+ chain: 'base',+ chain_id: BASE_CHAIN_ID,+ agent_id: agent.id,+ identity_registry: deployment.identityRegistry,+ registration_json: registrationJson,+ continue_url: `${agentHomeUrl(agent.id)}?deploy=base`,+ message:+ 'ERC-8004 registration on Base requires your browser wallet to sign the ' ++ 'on-chain register() call — headless agents cannot do this. Open continue_url ' ++ 'to finish in three.ws with the registration metadata pre-filled.',+ });+}++// Server-custodial Solana registration: mint the Core asset if needed, then+// enrol it in the Metaplex Agent Registry. The collection authority signs and+// pays — the agent's owner wallet never signs — so this runs headless.+async function registerOnSolana({ agent, network, force }) {+ const secret = authoritySecret();+ if (!secret) {+ return designedError(+ 'registration_not_configured',+ 'On-chain agent registration is not configured on this deployment. Set ' ++ 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (the funded collection authority) to ' ++ 'enable server-custodial Solana registration.',+ { chain: 'solana', network },+ );+ }++ let umi, authoritySigner;+ try {+ ({ umi, authoritySigner } = buildAuthorityUmi(network, secret));+ } catch (e) {+ return designedError('registration_not_configured', e.message, { chain: 'solana', network });+ }++ const meta = agent.meta || {};+ const net = network === 'mainnet' ? meta : meta.devnet || {};+ const existing = net.agent_registry;++ // Idempotent: already enrolled and not forcing → return the existing identity,+ // never a second mint.+ if (existing?.identity_pda && !force) {+ return toolResult({+ status: 'already_registered',+ chain: 'solana',+ network,+ agent_id: agent.id,+ agent_pda: existing.identity_pda,+ asset: existing.asset || net.sol_mint_address || null,+ registration_uri: existing.registration_uri || null,+ tx_hash: existing.tx_hash || null,+ explorer_url: explorerUrl(existing.identity_pda, network),+ });+ }++ const collectionAddr = getAgentCollection(network);+ let registry;++ if (!net.sol_mint_address) {+ // No Core asset on this network yet — mint it (deployAgentOnce mints AND+ // enrols in the registry as its final step).+ const collectionAsset = await loadCollectionAsset(umi, collectionAddr);+ const out = await deployAgentOnce({+ umi,+ authoritySigner,+ collectionAddr,+ collectionAsset,+ agent,+ network,+ });+ registry = out.registry;+ if (!registry) {+ // The asset minted but the registry step failed mid-flow — report it+ // honestly; a retry of register_agent finishes the enrolment.+ return designedError(+ 'registration_incomplete',+ 'The on-chain asset was minted but Agent Registry enrolment did not complete. ' ++ 'Retry register_agent to finish enrolling the existing asset.',+ { chain: 'solana', network, agent_id: agent.id, asset: out.asset },+ );+ }+ } else {+ // Asset already minted — enrol (or re-confirm) it. registerAgentOnce is+ // idempotent on-chain: an existing PDA short-circuits without a new tx.+ registry = await registerAgentOnce({+ umi,+ authoritySigner,+ agent,+ asset: net.sol_mint_address,+ collectionAddr,+ network,+ });+ }++ return toolResult({+ status: 'registered',+ chain: 'solana',+ network,+ agent_id: agent.id,+ agent_pda: registry.identityPda,+ asset: registry.asset,+ registration_uri: registry.registrationUri,+ tx_hash: registry.signature || null,+ already_registered: registry.alreadyRegistered,+ explorer_url: explorerUrl(registry.identityPda, network),+ asset_explorer_url: explorerUrl(registry.asset, network),+ });+}+export const toolDefs = [{name: 'call_agent',@@ -47,4 +220,193 @@ export const toolDefs = [}},},+ {+ name: 'register_agent',+ title: 'Register an agent on-chain',+ description:+ "Mint one of your agents' on-chain digital identity. On Solana (chain:solana) " ++ 'this enrols the agent in the Metaplex Agent Registry server-custodially — ' ++ 'three.ws signs and pays, your wallet never has to — and returns the Agent ' ++ 'Identity PDA, registration URI, and explorer link. On Base (chain:base) ' ++ 'ERC-8004 registration needs your browser wallet to sign, so this returns a ' ++ 'prepared registration_json plus a continue_url to finish in the browser. ' ++ 'Idempotent: an already-registered agent is returned as-is unless force:true. ' ++ 'Requires a signed-in three.ws account.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'Your agent identity id (uuid).' },+ chain: {+ type: 'string',+ enum: ['solana', 'base'],+ default: 'solana',+ description: 'Which chain to register on. solana = headless; base = ERC-8004 (needs your wallet).',+ },+ network: {+ type: 'string',+ enum: ['mainnet', 'devnet'],+ description: 'Solana cluster (chain:solana only). Defaults to where the agent already lives, else the configured collection network.',+ },+ force: {+ type: 'boolean',+ default: false,+ description: 'Re-run registration even if the agent is already registered (never double-mints).',+ },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ // Account-scoped write: x402 pay-per-call principals have no user, so they+ // cannot register an agent. Surface a designed, actionable sign-in state.+ if (!auth.userId) {+ return designedError(+ 'sign_in_required',+ 'register_agent writes to your three.ws account and requires a signed-in ' ++ 'user. Pay-per-call (x402) callers cannot register agents — authenticate ' ++ 'with your three.ws account (OAuth) and retry.',+ { chain: args.chain || 'solana' },+ );+ }++ const rl = await limits.agentRegister(auth.userId);+ if (!rl.success)+ throw rpcError(-32000, 'rate_limited', {+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });++ if (!UUID_RE.test(args.agent_id || '')) {+ return designedError('validation_error', 'agent_id must be a valid uuid.', {});+ }++ const [agent] = await sql`+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,+ av.thumbnail_key, av.storage_key+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.id = ${args.agent_id} AND ai.deleted_at IS NULL+ LIMIT 1+ `;+ if (!agent) {+ return designedError('not_found', 'No agent with that id.', { agent_id: args.agent_id });+ }+ if (agent.user_id !== auth.userId) {+ return designedError(+ 'forbidden',+ 'That agent belongs to another account — you can only register your own agents.',+ { agent_id: args.agent_id },+ );+ }++ const chain = args.chain || 'solana';+ if (chain === 'base') return prepareBaseRegistration(agent);++ const network = resolveSolanaNetwork(agent.meta, args.network);+ return registerOnSolana({ agent, network, force: !!args.force });+ },+ },+ {+ name: 'identity_check',+ title: 'Screen an agent identity for impersonation',+ description:+ 'Screen an agent identity (an existing agent_id, or a proposed name + description) ' ++ 'for impersonation and policy violations before it goes public. Uses IBM Granite ' ++ 'embeddings to find look-alike agents a name match would miss, and Granite Guardian ' ++ 'to screen the identity text. Returns a clear | review | block verdict with the ' ++ 'nearest neighbours and human-readable reasons.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'Screen one of your existing agents by id.' },+ name: { type: 'string', description: 'Proposed agent name (use with description instead of agent_id).' },+ description: { type: 'string', description: 'Proposed agent description.' },+ persona_tone_tags: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional persona/tone tags to include in the embedded identity.',+ },+ },+ additionalProperties: false,+ },+ scope: 'agents:read',+ async handler(args, auth) {+ const rl = await limits.identityCheckIp(auth.userId || auth.rateKey || 'anon');+ if (!rl.success)+ throw rpcError(-32000, 'rate_limited', {+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });++ let name = typeof args.name === 'string' ? args.name.trim().slice(0, 100) : '';+ let description =+ typeof args.description === 'string' ? args.description.trim().slice(0, 500) : '';+ let tags = Array.isArray(args.persona_tone_tags)+ ? args.persona_tone_tags.map((t) => String(t).trim()).filter(Boolean).slice(0, 12)+ : [];+ let excludeAgentId = null;++ // When an agent_id is given, screen that agent's stored identity. Ownership+ // isn't required to *read* a public identity, but we only resolve the row+ // for the caller (own or public) and exclude it from its own comparison.+ if (args.agent_id) {+ if (!UUID_RE.test(args.agent_id)) {+ return designedError('validation_error', 'agent_id must be a valid uuid.', {});+ }+ const [row] = await sql`+ SELECT id, name, description, persona_tone_tags, user_id, is_public+ FROM agent_identities+ WHERE id = ${args.agent_id} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!row) {+ return designedError('not_found', 'No agent with that id.', { agent_id: args.agent_id });+ }+ if (!row.is_public && row.user_id !== auth.userId) {+ return designedError(+ 'forbidden',+ 'That agent is private and belongs to another account.',+ { agent_id: args.agent_id },+ );+ }+ name = row.name || '';+ description = row.description || '';+ tags = Array.isArray(row.persona_tone_tags) ? row.persona_tone_tags : [];+ excludeAgentId = row.id;+ }++ if (!name && !description) {+ return designedError(+ 'validation_error',+ 'Provide an agent_id, or a name and/or description to screen.',+ {},+ );+ }++ const result = await checkIdentityIntegrity(+ { name, description, persona_tone_tags: tags },+ { userId: auth.userId, excludeAgentId },+ );++ // Project the integrity report onto the task's contract shape while keeping+ // the full detail (uniqueness, guardian, model) alongside.+ const structured = {+ verdict: result.status, // clear | review | block | unavailable+ configured: result.configured,+ agent_id: excludeAgentId,+ similar_agents: (result.similar || []).map((s) => ({+ id: s.id,+ name: s.name,+ score: s.score,+ owned: s.owned,+ public: s.public,+ })),+ reasons: result.reasons || [],+ duplicate_of: result.duplicateOf || null,+ uniqueness: result.uniqueness,+ guardian: result.guardian,+ model: result.model,+ };+ return toolResult(structured);+ },+ },];diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.jsindex 2f158a41e..f7b6f1b85 100644--- a/api/_mcp/tools/animations.js+++ b/api/_mcp/tools/animations.js@@ -13,6 +13,7 @@// addon is dynamically imported inside the handler.import { limits } from '../../_lib/rate-limit.js';+import { resolveOrigin } from '../origin.js';import { fetchModel, FetchModelError } from '../../_lib/fetch-model.js';import {canonicalNodeMapFromObject,@@ -34,17 +35,7 @@ function rpcError(code, message, data) {return e;}-// ── Origin + catalogue helpers ────────────────────────────────────────────-function resolveOrigin(req) {- const env =- process.env.APP_ORIGIN || process.env.PUBLIC_ORIGIN || process.env.PUBLIC_APP_ORIGIN;- if (env) return env.replace(/\/$/, '');- const host = req?.headers?.host;- if (host) return `${/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https'}://${host}`;- if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;- throw new Error('cannot resolve site origin to load the animation catalogue');-}-+// ── Catalogue helpers ────────────────────────────────────────────────────────async function loadManifest(origin) {const res = await fetch(`${origin}/animations/manifest.json`, { cache: 'no-store' });if (!res.ok) throw new Error(`manifest fetch failed (HTTP ${res.status})`);diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.jsindex fd7414bdd..be3d57631 100644--- a/api/_mcp/tools/avatars.js+++ b/api/_mcp/tools/avatars.js@@ -14,6 +14,7 @@ import {safeHttpsUrl,} from '../render.js';import { readMcpPolicyByAvatar } from '../embed-policy.js';+import { resolveRenderParams, renderAvatarImage } from '../../_lib/avatar-render.js';import { logAudit } from '../../_lib/audit.js';function rpcError(code, message, data) {@@ -206,6 +207,122 @@ export const toolDefs = [};},},+ {+ name: 'render_avatar_image',+ title: 'Render an avatar to an image',+ description:+ 'Render a stored avatar to a real PNG/JPEG/WebP image (headless three.js) and ' ++ 'return its URL — ready for an <img> tag, social card, or game loader. Choose a ' ++ 'camera framing (scene), an optional pose preset and ARKit-52 expression. Renders ' ++ 'are cached, so repeat calls with the same parameters return instantly. Works on ' ++ 'your own avatars (any visibility) and on public avatars.',+ inputSchema: {+ type: 'object',+ properties: {+ avatar_id: { type: 'string', format: 'uuid', description: 'The avatar to render.' },+ scene: {+ type: 'string',+ enum: ['full-body', 'upper-body', 'portrait', 'headshot'],+ default: 'upper-body',+ description: 'Camera framing preset.',+ },+ pose: {+ type: 'string',+ description: 'Optional pose preset id (see pose_model / the render catalog).',+ },+ expression: {+ type: 'object',+ description: 'Optional ARKit-52 morph map, e.g. {"mouthSmile":0.6}.',+ additionalProperties: { type: 'number' },+ },+ size: {+ type: 'integer',+ minimum: 64,+ maximum: 2048,+ default: 512,+ description: 'Square pixel dimension.',+ },+ bg: {+ type: 'string',+ default: 'transparent',+ description: 'Background: a CSS color or "transparent".',+ },+ format: {+ type: 'string',+ enum: ['png', 'jpeg', 'webp'],+ default: 'png',+ },+ },+ required: ['avatar_id'],+ additionalProperties: false,+ },+ scope: 'avatars:read',+ async handler(args, auth) {+ // Same visibility gate as get_avatar: an owner sees any visibility; a+ // non-owner sees only public/unlisted; private-not-yours reads as missing.+ const avatar = await getAvatar({ id: args.avatar_id, requesterId: auth.userId });+ if (!avatar) throw new Error('avatar not found');++ const urlInfo = await resolveAvatarUrl(avatar);+ if (!urlInfo?.url) {+ return {+ content: [+ { type: 'text', text: 'Error: this avatar has no model to render yet.' },+ ],+ isError: true,+ };+ }++ const resolved = resolveRenderParams({+ scene: args.scene,+ size: args.size,+ bg: args.bg,+ format: args.format,+ pose: args.pose,+ expression: args.expression,+ });+ if (resolved.error) {+ return {+ content: [{ type: 'text', text: `Error: ${resolved.error.message}` }],+ isError: true,+ };+ }++ let out;+ try {+ out = await renderAvatarImage({+ avatar,+ glbUrl: urlInfo.url,+ params: resolved.params,+ awaitUpload: true,+ });+ } catch (err) {+ return {+ content: [+ {+ type: 'text',+ text: `Render failed: ${err?.message || 'the avatar could not be rendered'}.`,+ },+ ],+ isError: true,+ };+ }++ return {+ content: [+ {+ type: 'text',+ text: `Rendered "${avatar.name}" (${resolved.params.scene}).\n${out.imageUrl}`,+ },+ ],+ structuredContent: {+ image_url: out.imageUrl,+ scene: resolved.params.scene,+ cached: out.cached,+ },+ };+ },+ },{name: 'delete_avatar',title: 'Delete avatar',diff --git a/api/_mcp/tools/embed.js b/api/_mcp/tools/embed.jsnew file mode 100644index 000000000..de93e9261--- /dev/null+++ b/api/_mcp/tools/embed.js@@ -0,0 +1,214 @@+// MCP tool: get_embed_code — hand an agent a copy-paste embed snippet for a+// three.ws 3D avatar, on-chain agent, or Forge creation. "As easy as embedding a+// YouTube video": one call returns the <iframe> HTML, the shareable URL, the+// oEmbed discovery URL, and a social-card thumbnail.+//+// The iframe markup + canonical URL shapes come from the shared builder in+// api/_lib/embed.js — the same one the /api/oembed provider uses — so embed+// output never drifts between the oEmbed surface and this tool.++import { sql } from '../../_lib/db.js';+import { isUuid } from '../../_lib/validate.js';+import { resolveOrigin } from '../origin.js';+import { resolveOnChainAgent, SERVER_CHAIN_META } from '../../_lib/onchain.js';+import { readEmbedPolicy } from '../../_lib/embed-policy.js';+import {+ buildEmbedIframe,+ clampEmbedDim,+ agentEmbedTarget,+ onchainEmbedTarget,+ forgeEmbedTarget,+ oembedUrl,+} from '../../_lib/embed.js';++function rpcError(code, message, data) {+ const e = new Error(message);+ e.code = code;+ e.data = data;+ return e;+}++// A designed, actionable error a chat client renders as text (not a thrown+// JSON-RPC fault) — used for "make it public first" style guidance.+function designedError(text, structured) {+ return {+ content: [{ type: 'text', text }],+ isError: true,+ structuredContent: { ok: false, ...structured },+ };+}++// Resolve the embed target (one of agent / on-chain agent / forge creation),+// enforcing visibility/ownership. Returns { target, title, oembed } on success,+// or a `{ error }` envelope (a designed isError result) the handler returns as-is.+async function resolveTarget({ kind, args, auth, origin }) {+ if (kind === 'agent') {+ if (!isUuid(args.agent_id)) throw rpcError(-32602, 'agent_id must be a uuid');+ const [agent] = await sql`+ SELECT id, user_id, name, is_public+ FROM agent_identities+ WHERE id = ${args.agent_id} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!agent) throw new Error('agent not found');+ // Mirror get_avatar's visibility check: a private item is embeddable only+ // by its owner — everyone else must publish (public/unlisted) it first.+ if (agent.is_public === false && agent.user_id !== auth.userId) {+ return {+ error: designedError(+ 'This agent is private, so its embed can\'t be shared publicly yet. ' ++ 'Make it public (or unlisted) in your three.ws dashboard, then call get_embed_code again.',+ { reason: 'private', share_url: agentEmbedTarget(origin, agent.id).shareUrl },+ ),+ };+ }+ // Honor an explicit iframe-surface opt-out in the agent's embed policy.+ const policy = await readEmbedPolicy(agent.id);+ if (policy && policy.surfaces?.iframe === false) {+ return {+ error: designedError(+ 'This agent has disabled iframe embedding in its embed policy. ' ++ 'Re-enable the iframe surface in the dashboard to share an embed snippet.',+ { reason: 'iframe_disabled' },+ ),+ };+ }+ const target = agentEmbedTarget(origin, agent.id);+ return { target, title: agent.name || 'three.ws avatar', oembed: oembedUrl(origin, target.shareUrl) };+ }++ if (kind === 'onchain') {+ const chainId = Number(args.chain_id);+ if (!Number.isInteger(chainId) || !SERVER_CHAIN_META[chainId]) {+ throw rpcError(-32602, `unsupported chain_id: ${args.chain_id}`);+ }+ const agentId = String(args.onchain_agent_id);+ if (!/^\d+$/.test(agentId)) {+ throw rpcError(-32602, 'onchain_agent_id must be a numeric token id');+ }+ const resolved = await resolveOnChainAgent({ chainId, agentId });+ if (resolved.error && resolved.error.startsWith('chain_read')) {+ throw new Error(`on-chain agent #${agentId} not found on chain ${chainId}`);+ }+ const target = onchainEmbedTarget(origin, chainId, agentId);+ return {+ target,+ title: resolved.name || `Agent #${agentId}`,+ oembed: oembedUrl(origin, target.shareUrl),+ };+ }++ // Forge creation — Forge share pages are public by id (no per-user+ // visibility), so the only gate is that the mesh actually finished rendering.+ if (!isUuid(args.creation_id)) throw rpcError(-32602, 'creation_id must be a uuid');+ const [creation] = await sql`+ SELECT id, status, glb_url FROM forge_creations+ WHERE id = ${args.creation_id} LIMIT 1+ `;+ if (!creation) throw new Error('forge creation not found');+ if (creation.status !== 'done' || !creation.glb_url) {+ return {+ error: designedError(+ 'This Forge creation hasn\'t finished generating yet, so there\'s nothing to embed. ' ++ 'Wait for it to complete, then call get_embed_code again.',+ { reason: 'not_ready', status: creation.status },+ ),+ };+ }+ // Forge has no oEmbed provider wired (the share page handles unfurling), so+ // oembed_url is null rather than a link that wouldn't resolve.+ return { target: forgeEmbedTarget(origin, creation.id), title: 'three.ws Forge creation', oembed: null };+}++export const toolDefs = [+ {+ name: 'get_embed_code',+ title: 'Get embed code',+ description:+ 'Return a ready-to-paste <iframe> embed snippet (plus shareable URL, oEmbed URL, and OG thumbnail) for a three.ws avatar, on-chain agent, or Forge creation. Embed a persistent 3D avatar into Notion, Webflow, Framer, a blog, or any site as easily as a YouTube video. Provide exactly one target: agent_id, OR chain_id + onchain_agent_id, OR creation_id.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'Embed a regular three.ws agent.' },+ chain_id: { type: 'integer', description: 'EVM chain id of an on-chain (ERC-8004) agent.' },+ onchain_agent_id: {+ type: 'string',+ description: 'Token id of the on-chain agent (pair with chain_id).',+ },+ creation_id: { type: 'string', format: 'uuid', description: 'Embed a Forge 3D creation.' },+ // Bounds are clamped in the handler, not enforced by the schema, so an+ // out-of-range number yields a usable snippet instead of a hard error.+ width: { type: 'integer', default: 480, description: 'Iframe width in px (clamped 240–1920).' },+ height: { type: 'integer', default: 360, description: 'Iframe height in px (clamped 180–1080).' },+ autorotate: { type: 'boolean', default: true, description: 'Slowly auto-rotate the avatar.' },+ ar: { type: 'boolean', default: true, description: 'Offer an AR / view-in-room button on mobile.' },+ },+ additionalProperties: false,+ },+ scope: 'avatars:read',+ async handler(args, auth, req) {+ const origin = resolveOrigin(req);++ // Exactly one target must be supplied.+ const hasAgent = Boolean(args.agent_id);+ const hasOnchain = args.chain_id != null && args.onchain_agent_id != null;+ const hasCreation = Boolean(args.creation_id);+ const supplied = [hasAgent, hasOnchain, hasCreation].filter(Boolean).length;+ if (supplied !== 1) {+ throw rpcError(+ -32602,+ 'provide exactly one target: agent_id, OR chain_id + onchain_agent_id, OR creation_id',+ );+ }++ const width = clampEmbedDim(args.width, 480, 240, 1920);+ const height = clampEmbedDim(args.height, 360, 180, 1080);+ const autorotate = args.autorotate !== false;+ const ar = args.ar !== false;++ const kind = hasAgent ? 'agent' : hasOnchain ? 'onchain' : 'forge';+ const resolved = await resolveTarget({ kind, args, auth, origin });+ if (resolved.error) return resolved.error;+ const { target, title, oembed } = resolved;++ const embedHtml = buildEmbedIframe({+ src: target.embedUrl,+ width,+ height,+ title,+ autorotate,+ ar,+ });++ const structuredContent = {+ ok: true,+ embed_html: embedHtml,+ share_url: target.shareUrl,+ oembed_url: oembed,+ thumbnail_url: target.thumbnailUrl,+ width,+ height,+ };++ return {+ content: [+ {+ type: 'text',+ text: `Embed snippet for "${title}" — paste it anywhere HTML is allowed:\n\n${embedHtml}\n\nShare URL: ${target.shareUrl}`,+ },+ // A self-contained text/html artifact so MCP clients that render HTML+ // show a live preview of the embed (mirrors render_avatar / preview_3d).+ {+ type: 'resource',+ resource: {+ uri: target.shareUrl,+ mimeType: 'text/html',+ text: `<!doctype html><meta charset="utf-8"><body style="margin:0;background:transparent">${embedHtml}</body>`,+ },+ },+ ],+ structuredContent,+ };+ },+ },+];diff --git a/api/_mcp/tools/memory.js b/api/_mcp/tools/memory.jsnew file mode 100644index 000000000..eb83a83d6--- /dev/null+++ b/api/_mcp/tools/memory.js@@ -0,0 +1,269 @@+// MCP memory tools — remember / recall / forget.+//+// Exposes the agent-memory backend (api/agent-memory.js, table agent_memories)+// as MCP tools so an agent connected to /api/mcp can persist, retrieve, and+// delete its own long-term memories. Ownership is enforced on every tool by+// the same query the REST endpoint uses: a memory belongs to an agent, and an+// agent belongs to a user (agent_identities.user_id). A caller may only touch+// agents they own; pay-per-call x402 principals (auth.userId === null) have no+// account and are refused with a designed, actionable message.++import { sql } from '../../_lib/db.js';++const VALID_TYPES = ['user', 'feedback', 'project', 'reference'];++// 7-day half-life recency decay, mirroring src/agent-memory.js so server-side+// recall ranks memories the same way the client store does.+const RECENCY_HALF_LIFE_MS = 7 * 24 * 60 * 60 * 1000;++// Designed "not your agent / not signed in" result. The task requires a helpful+// message, not a throw — anonymous x402 callers have no account at all, owners+// of a different agent get the same opaque answer so we don't leak existence.+function ownershipError() {+ return {+ content: [+ {+ type: 'text',+ text: 'Memory is account-scoped. Sign in with three.ws OAuth (scope memory:read / memory:write) and pass an agent_id you own.',+ },+ ],+ isError: true,+ };+}++// Returns true when auth.userId owns the agent. Reuses the REST endpoint's+// ownership query verbatim so the trust boundary stays identical.+async function ownsAgent(agentId, auth) {+ if (!auth?.userId) return false;+ const [row] = await sql`+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ return !!row && row.user_id === auth.userId;+}++function decorate(row) {+ return {+ id: row.id,+ agent_id: row.agent_id,+ type: row.type,+ content: row.content,+ tags: row.tags || [],+ context: row.context || {},+ salience: row.salience,+ created_at: row.created_at,+ expires_at: row.expires_at || null,+ };+}++function tokenize(text) {+ return String(text || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((t) => t.length > 1);+}++// Blend lexical relevance to the query with salience and recency. With no+// per-memory embeddings stored server-side, lexical overlap stands in for+// semantic similarity; when a query matches nothing, lexical=0 and the order+// degrades cleanly to the salience+recency ranking the REST endpoint uses —+// never a failure mode. Returns a score in roughly [0,1].+function scoreMemory(row, queryTokens, nowMs) {+ const haystack = new Set(tokenize(`${row.content} ${(row.tags || []).join(' ')}`));+ let hits = 0;+ for (const t of queryTokens) if (haystack.has(t)) hits++;+ const lexical = queryTokens.length ? hits / queryTokens.length : 0;++ const createdMs = row.created_at ? new Date(row.created_at).getTime() : nowMs;+ const ageMs = Math.max(0, nowMs - createdMs);+ const recency = Math.exp((-0.693 * ageMs) / RECENCY_HALF_LIFE_MS);++ const salience = typeof row.salience === 'number' ? row.salience : 0.5;++ return 0.5 * lexical + 0.35 * salience + 0.15 * recency;+}++export const toolDefs = [+ {+ name: 'remember',+ title: 'Remember',+ description:+ 'Store a long-term memory for one of your agents. Use for durable facts: who the user is (type=user), guidance/corrections (feedback), ongoing work (project), or external pointers (reference). Returns the stored memory.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid' },+ content: { type: 'string', minLength: 1, maxLength: 4000 },+ type: { type: 'string', enum: VALID_TYPES, default: 'reference' },+ tags: {+ type: 'array',+ items: { type: 'string', maxLength: 100 },+ maxItems: 20,+ },+ context: {+ type: 'string',+ maxLength: 2000,+ description: 'Optional freeform metadata about where this memory came from.',+ },+ salience: { type: 'number', minimum: 0, maximum: 1, default: 0.5 },+ expires_at: {+ type: 'string',+ format: 'date-time',+ description:+ 'Optional ISO-8601 expiry; the memory is excluded from recall after this time.',+ },+ },+ required: ['agent_id', 'content'],+ additionalProperties: false,+ },+ scope: 'memory:write',+ async handler(args, auth) {+ if (!(await ownsAgent(args.agent_id, auth))) return ownershipError();++ const type = VALID_TYPES.includes(args.type) ? args.type : 'reference';+ const tags = Array.isArray(args.tags) ? args.tags : [];+ const context = args.context ? { note: args.context } : {};+ const salience = typeof args.salience === 'number' ? args.salience : 0.5;+ const expiresAt = args.expires_at ? new Date(args.expires_at).toISOString() : null;++ const [row] = await sql`+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, expires_at)+ VALUES (+ gen_random_uuid(),+ ${args.agent_id},+ ${type},+ ${args.content.trim()},+ ${tags},+ ${JSON.stringify(context)}::jsonb,+ ${salience},+ ${expiresAt}+ )+ RETURNING *+ `;++ const mem = decorate(row);+ return {+ content: [{ type: 'text', text: `Remembered (${mem.type}): ${mem.content}` }],+ structuredContent: { memory: mem },+ };+ },+ },+ {+ name: 'recall',+ title: 'Recall',+ description:+ 'Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid' },+ query: { type: 'string', minLength: 1, maxLength: 1000 },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 8 },+ type: { type: 'string', enum: VALID_TYPES },+ },+ required: ['agent_id', 'query'],+ additionalProperties: false,+ },+ scope: 'memory:read',+ async handler(args, auth) {+ if (!(await ownsAgent(args.agent_id, auth))) return ownershipError();++ const limit = Math.min(Math.max(Number(args.limit) || 8, 1), 50);+ // Pull a bounded candidate pool ordered the way the REST list endpoint+ // does, then re-rank in memory against the query. The pool cap keeps the+ // query cheap while covering far more than any limit a caller will ask for.+ const candidates = args.type+ ? await sql`+ SELECT * FROM agent_memories+ WHERE agent_id = ${args.agent_id}+ AND type = ${args.type}+ AND (expires_at IS NULL OR expires_at > now())+ ORDER BY salience DESC, created_at DESC+ LIMIT 200+ `+ : await sql`+ SELECT * FROM agent_memories+ WHERE agent_id = ${args.agent_id}+ AND (expires_at IS NULL OR expires_at > now())+ ORDER BY salience DESC, created_at DESC+ LIMIT 200+ `;++ if (!candidates.length) {+ return {+ content: [+ {+ type: 'text',+ text: 'No memories stored for this agent yet. Use the remember tool to add some.',+ },+ ],+ structuredContent: { memories: [] },+ };+ }++ const nowMs = Date.now();+ const queryTokens = tokenize(args.query);+ const ranked = candidates+ .map((row) => ({ row, score: scoreMemory(row, queryTokens, nowMs) }))+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map(({ row, score }) => {+ const mem = decorate(row);+ return {+ id: mem.id,+ type: mem.type,+ content: mem.content,+ tags: mem.tags,+ salience: mem.salience,+ score: Math.round(score * 1000) / 1000,+ };+ });++ const summary = ranked.map((m, i) => `${i + 1}. [${m.type}] ${m.content}`).join('\n');+ return {+ content: [{ type: 'text', text: summary }],+ structuredContent: { memories: ranked },+ };+ },+ },+ {+ name: 'forget',+ title: 'Forget',+ description: 'Delete a memory you own by its id.',+ inputSchema: {+ type: 'object',+ properties: {+ memory_id: { type: 'string', format: 'uuid' },+ agent_id: { type: 'string', format: 'uuid' },+ },+ required: ['memory_id'],+ additionalProperties: false,+ },+ scope: 'memory:write',+ async handler(args, auth) {+ if (!auth?.userId) return ownershipError();++ // Ownership via the same join handleDelete uses: memory → agent → user.+ const [row] = await sql`+ SELECT m.id, a.user_id+ FROM agent_memories m+ JOIN agent_identities a ON a.id = m.agent_id+ WHERE m.id = ${args.memory_id}+ `;++ if (!row || row.user_id !== auth.userId) {+ return {+ content: [+ { type: 'text', text: 'No such memory, or it does not belong to you.' },+ ],+ isError: true,+ };+ }++ await sql`DELETE FROM agent_memories WHERE id = ${args.memory_id}`;+ return {+ content: [{ type: 'text', text: `Forgot memory ${args.memory_id}.` }],+ structuredContent: { ok: true, id: args.memory_id },+ };+ },+ },+];diff --git a/api/_mcp3d/dispatch.js b/api/_mcp3d/dispatch.jsindex 128c6c630..47fc8fc71 100644--- a/api/_mcp3d/dispatch.js+++ b/api/_mcp3d/dispatch.js@@ -13,7 +13,9 @@ const INSTRUCTIONS = ['auto_rig_model(glb_url) adds a skeleton; apply_animation(model_url, animation) and pose_model(prompt)','drive the rigged result; list_animations enumerates clips. Mesh ops: remesh_model, stylize_model,','segment_model, retexture_model, retexture_region, generate_material. preview_3d(glb_url) renders any',- 'GLB; inspect_model / optimize_model analyze one. Always display returned text/html resources as inline 3D artifacts.',+ 'GLB; inspect_model / optimize_model analyze one. save_avatar(glb_url, name) persists a generated GLB as a',+ 'durable, named avatar you own (then render_avatar_image / get_avatar on the main server work on it).',+ 'Always display returned text/html resources as inline 3D artifacts.',].join(' ');export const dispatch = makeDispatcher({diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 8033c8a59..f2eef0d4d 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -37,6 +37,10 @@ import {import { resolveProviderKey } from '../../_lib/forge-provider-key.js';import { encodeJobToken, decodeJobToken } from '../../_lib/forge-job-token.js';import { watsonxConfig, watsonxChatComplete } from '../../_lib/watsonx.js';+import { createAvatar, storageKeyFor } from '../../_lib/avatars.js';+import { putObject } from '../../_lib/r2.js';+import { isValidGlbHeader, inspectGlb } from '../../_lib/glb-inspect.js';+import { env } from '../../_lib/env.js';import { PRESETS, PRESET_GROUPS } from '../../../src/pose-presets.js';import {renderModelViewerHtml,@@ -121,6 +125,26 @@ const POLL_HINT ='Call generation_status with this job_id to check progress. ' +'Reconstruction typically finishes in 30–90 seconds.';+// Ceiling on a GLB copied into durable storage by save_avatar. Matches the+// reconstruct + forge pipelines so a runaway model can't ingest an unbounded blob.+const MAX_GLB_BYTES = 64 * 1024 * 1024;++// Fetch a provider GLB into a Buffer with a hard size cap, so save_avatar can+// persist its own durable copy before the provider's delivery URL expires.+async function fetchGlbBuffer(url) {+ const resp = await fetch(url);+ if (!resp.ok) throw rpcError(-32000, `Could not fetch the GLB (${resp.status}).`);+ const declared = Number(resp.headers.get('content-length') || 0);+ if (declared && declared > MAX_GLB_BYTES) {+ throw rpcError(-32000, `GLB too large to save (${declared} bytes; max ${MAX_GLB_BYTES}).`);+ }+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > MAX_GLB_BYTES) {+ throw rpcError(-32000, `GLB too large to save (${buf.length} bytes; max ${MAX_GLB_BYTES}).`);+ }+ return buf;+}+function viewerArtifact({ glbUrl, name, options = {} }) {const html = renderModelViewerHtml({src: glbUrl,@@ -1503,4 +1527,152 @@ export const toolDefs = [};},},+ {+ name: 'save_avatar',+ title: 'Save a generated GLB as a durable, named avatar',+ description:+ 'Persist a generated GLB (e.g. the glb_url returned by generation_status) as a durable avatar in your three.ws library. The mesh is copied into our own storage so it survives the provider URL expiring, then registered as a named avatar you own. Returns avatar_id, slug, model_url, and a view_url. This is the bridge from the studio to the avatar system: after saving, get_avatar, render_avatar_image, embeds, and on-chain identity all work on the result. Requires you to be signed in.',+ inputSchema: {+ type: 'object',+ properties: {+ glb_url: {+ type: 'string',+ format: 'uri',+ description: 'Public https URL of the GLB to save (e.g. from generation_status).',+ },+ name: {+ type: 'string',+ minLength: 1,+ maxLength: 80,+ description: 'A name for the avatar, 1–80 characters.',+ },+ visibility: {+ type: 'string',+ enum: ['public', 'unlisted', 'private'],+ default: 'unlisted',+ description:+ 'public = listed in the gallery; unlisted = anyone with the link; private = only you.',+ },+ source_prompt: {+ type: 'string',+ maxLength: 1000,+ description: 'Optional: the prompt that generated this model, kept as provenance.',+ },+ tags: {+ type: 'array',+ items: { type: 'string', minLength: 1, maxLength: 40 },+ maxItems: 20,+ description: 'Optional tags for organizing and searching your library.',+ },+ },+ required: ['glb_url', 'name'],+ additionalProperties: false,+ },+ scope: 'avatars:write',+ async handler(args, auth) {+ await enforce(limits.mcp3dGenerate, auth);++ if (!auth.userId) {+ return {+ content: [+ {+ type: 'text',+ text:+ 'Sign in to save an avatar. Saving writes to your three.ws library, ' ++ 'so it needs a signed-in account (an OAuth bearer token), not an ' ++ 'anonymous pay-per-call session.',+ },+ ],+ structuredContent: { status: 'sign_in_required' },+ isError: true,+ };+ }++ if (!(await isPublicHttpsUrl(args.glb_url))) {+ return {+ content: [{ type: 'text', text: 'Error: glb_url must be a public https URL.' }],+ isError: true,+ };+ }++ const buf = await fetchGlbBuffer(args.glb_url);+ const info = isValidGlbHeader(buf) ? inspectGlb(buf) : null;+ if (!info) {+ return {+ content: [+ {+ type: 'text',+ text: 'Error: that URL did not return a valid GLB (binary glTF). Pass a .glb model URL.',+ },+ ],+ isError: true,+ };+ }++ const visibility = ['public', 'unlisted', 'private'].includes(args.visibility)+ ? args.visibility+ : 'unlisted';+ const name = String(args.name).trim().slice(0, 80);+ const slug = `studio-${createHash('sha256')+ .update(`${auth.userId}|${name}|${args.glb_url}`)+ .digest('hex')+ .slice(0, 8)}`;+ const storageKey = storageKeyFor({ userId: auth.userId, slug });++ await putObject({+ key: storageKey,+ body: buf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'studio', user_id: auth.userId },+ });++ const tags = Array.isArray(args.tags)+ ? args.tags.map((t) => String(t).trim()).filter(Boolean).slice(0, 20)+ : [];++ const avatar = await createAvatar({+ userId: auth.userId,+ storageKey,+ input: {+ slug,+ name,+ description: null,+ size_bytes: buf.length,+ content_type: 'model/gltf-binary',+ source: 'studio',+ source_meta: {+ source_glb_url: args.glb_url,+ source_prompt: args.source_prompt ?? null,+ is_rigged: info.isRigged ?? null,+ mesh_count: info.meshCount ?? null,+ animation_count: info.animationCount ?? null,+ },+ visibility,+ tags,+ checksum_sha256: null,+ parent_avatar_id: null,+ },+ });++ const viewUrl = `${env.APP_ORIGIN}/discover/avatar/${avatar.id}`;+ return {+ content: [+ {+ type: 'text',+ text:+ `Saved "${avatar.name}" to your library (${visibility}).\n` ++ `Avatar ID: ${avatar.id}\nView: ${viewUrl}\n` ++ 'Render it with render_avatar_image, or fetch it with get_avatar.',+ },+ ],+ structuredContent: {+ avatar_id: avatar.id,+ slug: avatar.slug,+ model_url: avatar.model_url,+ view_url: viewUrl,+ visibility,+ },+ };+ },+ },];diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.jsindex c447b1a1d..5f6075ad0 100644--- a/api/_mcpagent/tools.js+++ b/api/_mcpagent/tools.js@@ -13,12 +13,26 @@// to returning the exact payment requirements + a pay link rather than failing.import { limits } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';+import { sql } from '../_lib/db.js';import { Bazaar, filterByMaxPrice, filterByNetwork } from '../_lib/x402/bazaar-client.js';import {getUserWalletStatus,payExternalX402,resolveSpendEnabled,} from '../_lib/x402-user-payer.js';+import {+ getOrCreateAgentSolanaWallet,+ getSolanaAddressBalances,+} from '../_lib/agent-wallet.js';+import {+ createPaidService,+ validateTargetUrl,+ resolvePayoutAddress,+ serviceResourceUrl,+ atomicsToUsdc,+ usdcToAtomics,+ MonetizeError,+} from '../_lib/agent-paid-services.js';function rpcError(code, message, data) {const e = new Error(message);diff --git a/api/agent-oembed.js b/api/agent-oembed.jsindex 0c9f4e843..8c79f6513 100644--- a/api/agent-oembed.js+++ b/api/agent-oembed.js@@ -12,11 +12,16 @@ import { sql } from './_lib/db.js';import { env } from './_lib/env.js';import { cors, wrap, error } from './_lib/http.js';import { resolveOnChainAgent, SERVER_CHAIN_META } from './_lib/onchain.js';+import {+ buildEmbedIframe,+ clampEmbedDim,+ agentEmbedTarget,+ onchainEmbedTarget,+ EMBED_THUMB,+} from './_lib/embed.js';const DEFAULT_WIDTH = 420;const DEFAULT_HEIGHT = 520;-const THUMB_WIDTH = 1200;-const THUMB_HEIGHT = 630;export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;@@ -25,13 +30,13 @@ export default wrap(async (req, res) => {const target = url.searchParams.get('url');const format = (url.searchParams.get('format') || 'json').toLowerCase();- const WIDTH = clampDim(url.searchParams.get('maxwidth'), DEFAULT_WIDTH, 100, 2000);- const HEIGHT = clampDim(url.searchParams.get('maxheight'), DEFAULT_HEIGHT, 100, 2000);+ const width = clampEmbedDim(url.searchParams.get('maxwidth'), DEFAULT_WIDTH, 100, 2000);+ const height = clampEmbedDim(url.searchParams.get('maxheight'), DEFAULT_HEIGHT, 100, 2000);if (!target) return error(res, 400, 'invalid_request', 'url parameter required');const onchain = extractOnChain(target);- if (onchain) return sendOnChain(res, format, onchain);+ if (onchain) return sendOnChain(res, format, { ...onchain, width, height });const agentId = extractAgentId(target);if (!agentId) return error(res, 404, 'not_found', 'url is not a recognised agent url');@@ -45,13 +50,9 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');const origin = env.APP_ORIGIN;- const embedUrl = `${origin}/agent/${agent.id}/embed`;- const agentUrl = `${origin}/agent/${agent.id}`;- const thumbUrl = `${origin}/api/agent/${agent.id}/og`;+ const { embedUrl, shareUrl, thumbnailUrl } = agentEmbedTarget(origin, agent.id);const title = agent.name || 'Agent';- const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${WIDTH}" height="${HEIGHT}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;-const payload = {type: 'rich',version: '1.0',@@ -59,13 +60,13 @@ export default wrap(async (req, res) => {provider_url: origin,title,author_name: title,- author_url: agentUrl,- html: iframe,- width: WIDTH,- height: HEIGHT,- thumbnail_url: thumbUrl,- thumbnail_width: THUMB_WIDTH,- thumbnail_height: THUMB_HEIGHT,+ author_url: shareUrl,+ html: buildEmbedIframe({ src: embedUrl, width, height, title }),+ width,+ height,+ thumbnail_url: thumbnailUrl,+ thumbnail_width: EMBED_THUMB.width,+ thumbnail_height: EMBED_THUMB.height,};res.setHeader('cache-control', 'public, max-age=900');@@ -120,20 +121,16 @@ function extractOnChain(target) {return { chainId, agentId };}-async function sendOnChain(res, format, { chainId, agentId }) {+async function sendOnChain(res, format, { chainId, agentId, width, height }) {const agent = await resolveOnChainAgent({ chainId, agentId });if (agent.error && agent.error.startsWith('chain_read')) {return error(res, 404, 'not_found', `agent #${agentId} not found on chain ${chainId}`);}const origin = env.APP_ORIGIN;- const pageUrl = `${origin}/a/${chainId}/${agentId}`;- const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;- const thumbUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(agentId)}`;+ const { embedUrl, shareUrl, thumbnailUrl } = onchainEmbedTarget(origin, chainId, agentId);const title = agent.name || `Agent #${agentId}`;- const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${WIDTH}" height="${HEIGHT}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;-const payload = {type: 'rich',version: '1.0',@@ -141,13 +138,13 @@ async function sendOnChain(res, format, { chainId, agentId }) {provider_url: origin,title,author_name: title,- author_url: pageUrl,- html: iframe,- width: WIDTH,- height: HEIGHT,- thumbnail_url: thumbUrl,- thumbnail_width: THUMB_WIDTH,- thumbnail_height: THUMB_HEIGHT,+ author_url: shareUrl,+ html: buildEmbedIframe({ src: embedUrl, width, height, title }),+ width,+ height,+ thumbnail_url: thumbnailUrl,+ thumbnail_width: EMBED_THUMB.width,+ thumbnail_height: EMBED_THUMB.height,};res.setHeader('cache-control', 'public, max-age=900');@@ -176,17 +173,3 @@ function escapeXml(s) {.replace(/"/g, '"').replace(/'/g, ''');}--function escapeAttr(s) {- return String(s)- .replace(/&/g, '&')- .replace(/"/g, '"')- .replace(/</g, '<')- .replace(/>/g, '>');-}--function clampDim(raw, def, min, max) {- const n = raw != null ? parseInt(raw, 10) : NaN;- if (!Number.isFinite(n) || n <= 0) return def;- return Math.max(min, Math.min(max, n));-}diff --git a/api/api-keys.js b/api/api-keys.jsindex 4b56b47df..f5a3fd3db 100644--- a/api/api-keys.js+++ b/api/api-keys.js@@ -7,7 +7,7 @@ import { requireCsrf } from './_lib/csrf.js';import { parse } from './_lib/validate.js';import { z } from 'zod';-const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile']);+const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write']);const createSchema = z.object({name: z.string().trim().min(1).max(80),diff --git a/api/avatar/render.js b/api/avatar/render.jsindex 6f6f729df..8229209c8 100644--- a/api/avatar/render.js+++ b/api/avatar/render.js@@ -20,38 +20,29 @@// and caches the result in R2. Subsequent requests 302 to the CDN URL.// Cache is keyed on avatar_id + param hash + avatar updated_at, so updates// to the avatar (appearance, GLB, etc.) automatically bust the cache.+//+// The chromium + three.js pipeline and the param/cache layer live in+// api/_lib/avatar-render.js so the render_avatar_image MCP tool shares the exact+// same code path — this route is the public, unauthenticated surface on top.-import { createHash } from 'node:crypto';-// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()-// so Vercel's NFT does not statically trace the chromium binary tree on every-// route in this function package — that trace was the 45-min build timeout.import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { getAvatar } from '../_lib/avatars.js';-import { publicUrl, putObject, headObject } from '../_lib/r2.js';+import {+ SCENE_PRESETS,+ FORMAT_TYPES,+ MIN_DIM,+ MAX_DIM,+ DEFAULT_SIZE,+ resolveRenderParams,+ renderAvatarImage,+} from '../_lib/avatar-render.js';import { PRESETS } from '../../src/pose-presets.js';export const maxDuration = 30;-const MIN_DIM = 64;-const MAX_DIM = 2048;-const DEFAULT_SIZE = 512;const RATE_LIMIT_WINDOW_MS = 10 * 60 * 1000;const RATE_LIMIT_MAX = 120;-const SCENE_PRESETS = {- 'full-body': { phi: 80, theta: 0, radiusMult: 1.0, lookAtY: 0.0 },- 'upper-body': { phi: 82, theta: 5, radiusMult: 0.55, lookAtY: 0.15 },- 'portrait': { phi: 84, theta: 8, radiusMult: 0.38, lookAtY: 0.30 },- 'headshot': { phi: 86, theta: 5, radiusMult: 0.28, lookAtY: 0.38 },-};--const FORMAT_TYPES = {- png: 'image/png',- jpeg: 'image/jpeg',- webp: 'image/webp',-};-const rateMap = new Map();function rateCheck(ip) {const now = Date.now();@@ -72,14 +63,6 @@ function rateCheck(ip) {return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };}-function cacheKey(avatarId, paramsHash, format) {- return `renders/${avatarId}/${paramsHash}.${format}`;-}--function hashParams(obj) {- return createHash('sha256').update(JSON.stringify(obj)).digest('hex').slice(0, 16);-}-export default wrap(async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;@@ -130,351 +113,47 @@ export default wrap(async function handler(req, res) {return error(res, 403, 'private', 'Avatar is private — only public or unlisted avatars can be rendered');}- const sceneName = q.get('scene') || 'upper-body';- const scenePreset = SCENE_PRESETS[sceneName];- if (!scenePreset) {- return error(res, 400, 'invalid_scene', `Unknown scene "${sceneName}". Valid: ${Object.keys(SCENE_PRESETS).join(', ')}`);- }-- const size = clamp(parseInt(q.get('size'), 10) || DEFAULT_SIZE, MIN_DIM, MAX_DIM);- const width = clamp(parseInt(q.get('width'), 10) || size, MIN_DIM, MAX_DIM);- const height = clamp(parseInt(q.get('height'), 10) || size, MIN_DIM, MAX_DIM);-- const bg = q.get('bg') || 'transparent';- const format = FORMAT_TYPES[q.get('format')] ? q.get('format') : 'png';- const quality = clamp(parseInt(q.get('quality'), 10) || 90, 1, 100);-- let posePresetId = null;- if (q.get('pose')) {- const found = PRESETS.find((p) => p.id === q.get('pose'));- if (!found) {- return error(res, 400, 'unknown_pose', `Unknown pose "${q.get('pose')}". GET this endpoint without params for the catalog.`);- }- posePresetId = found.id;- }-- let expression = null;- if (q.get('expression')) {- try {- expression = JSON.parse(q.get('expression'));- if (typeof expression !== 'object' || expression === null || Array.isArray(expression)) throw new Error();- } catch {- return error(res, 400, 'invalid_expression', 'expression must be a JSON object of morph targets');- }- }-- const paramFingerprint = hashParams({- scene: sceneName,- w: width,- h: height,- bg,- format,- quality,- pose: posePresetId,- expression,- updated: avatar.updated_at,+ const resolved = resolveRenderParams({+ scene: q.get('scene'),+ size: q.get('size'),+ width: q.get('width'),+ height: q.get('height'),+ bg: q.get('bg'),+ format: q.get('format'),+ quality: q.get('quality'),+ pose: q.get('pose'),+ expression: q.get('expression'),});-- const key = cacheKey(avatar.id, paramFingerprint, format);-- try {- const head = await headObject(key);- if (head) {- const cdnUrl = publicUrl(key);- res.statusCode = 302;- res.setHeader('location', cdnUrl);- res.setHeader('cache-control', 'public, max-age=300, s-maxage=86400');- res.setHeader('x-render-cache', 'hit');- res.end();- return;- }- } catch {- // Cache miss — render fresh+ if (resolved.error) {+ return error(res, 400, resolved.error.code, resolved.error.message);}+ const params = resolved.params;- const cameraOrbit = {- theta: scenePreset.theta,- phi: scenePreset.phi,- radius: null,- };-- let result;+ let out;try {- result = await renderAvatarScene({- glbUrl: avatar.model_url,- width,- height,- background: bg,- posePresetId,- cameraOrbit,- expression,- scenePreset,- });+ out = await renderAvatarImage({ avatar, glbUrl: avatar.model_url, params, awaitUpload: false });} catch (err) {const status = err?.status || 502;return error(res, status, err?.code || 'render_failed', err?.message || 'Render failed');}- const imageBuffer = result.png;-- putObject({- key,- body: imageBuffer,- contentType: FORMAT_TYPES[format],- metadata: { avatar_id: avatar.id, scene: sceneName, params: paramFingerprint },- }).catch((err) => {- console.warn('[avatar/render] cache write failed:', err?.message);- });+ if (out.cached) {+ res.statusCode = 302;+ res.setHeader('location', out.imageUrl);+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=86400');+ res.setHeader('x-render-cache', 'hit');+ res.end();+ return;+ }+ const imageBuffer = out.buffer;res.statusCode = 200;- res.setHeader('content-type', FORMAT_TYPES[format]);+ res.setHeader('content-type', out.contentType);res.setHeader('content-length', String(imageBuffer.length));res.setHeader('cache-control', 'public, max-age=300, s-maxage=86400');res.setHeader('x-render-cache', 'miss');- res.setHeader('x-render-scene', sceneName);- res.setHeader('x-render-size', `${width}x${height}`);+ res.setHeader('x-render-scene', params.scene);+ res.setHeader('x-render-size', `${params.width}x${params.height}`);res.setHeader('access-control-expose-headers', 'x-render-cache, x-render-scene, x-render-size');res.end(imageBuffer);});--function clamp(v, min, max) {- return Math.max(min, Math.min(max, v));-}--const DEFAULT_CHROMIUM_PACK =- 'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';-const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;-const THREE_VERSION = '0.176.0';--let _browserPromise = null;-async function getBrowser() {- if (_browserPromise) return _browserPromise;- _browserPromise = (async () => {- const [{ default: puppeteer }, { default: chromium }] = await Promise.all([- import('puppeteer-core'),- import('@sparticuz/chromium-min'),- ]);- const executablePath = await chromium.executablePath(CHROMIUM_PACK);- return puppeteer.launch({- args: chromium.args,- defaultViewport: { width: 1024, height: 1024, deviceScaleFactor: 1 },- executablePath,- headless: chromium.headless,- });- })().catch((err) => {- _browserPromise = null;- throw err;- });- return _browserPromise;-}--function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {- const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');- const poseJson = pose ? JSON.stringify(pose) : 'null';- const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });- const expressionJson = JSON.stringify(expression || null);- const presetJson = JSON.stringify(scenePreset);-- return `<!doctype html>-<html><head><meta charset="utf-8" />-<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>-</head><body>-<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>-<script type="importmap">{ "imports": {- "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"-}}</script>-<script type="module">-import * as THREE from 'three';-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';-import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';-import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';-import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';--window.__renderDone = false;-window.__renderError = null;--const canvas = document.getElementById('c');-const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });-renderer.setSize(${width}, ${height}, false);-renderer.setPixelRatio(1);-renderer.outputColorSpace = THREE.SRGBColorSpace;-renderer.toneMapping = THREE.ACESFilmicToneMapping;-renderer.toneMappingExposure = 1.0;--const scene = new THREE.Scene();-const bgColor = ${bg};-if (bgColor !== null) scene.background = new THREE.Color(bgColor);--const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);--scene.add(new THREE.AmbientLight(0xffffff, 0.6));-const key = new THREE.DirectionalLight(0xffffff, 1.5);-key.position.set(2, 3, 4); scene.add(key);-const fill = new THREE.DirectionalLight(0xbfd6ff, 0.65);-fill.position.set(-3, 1, 2); scene.add(fill);-const rim = new THREE.DirectionalLight(0xc7a8ff, 0.55);-rim.position.set(0, 2, -4); scene.add(rim);-const bottom = new THREE.DirectionalLight(0xffffff, 0.15);-bottom.position.set(0, -2, 1); scene.add(bottom);--const aliases = {- shoulderl: ['leftshoulder','shoulder_l','l_shoulder','mixamorig:leftshoulder'],- shoulderr: ['rightshoulder','shoulder_r','r_shoulder','mixamorig:rightshoulder'],- elbowl: ['leftforearm','leftelbow','elbow_l','mixamorig:leftforearm','mixamorig:leftelbow'],- elbowr: ['rightforearm','rightelbow','elbow_r','mixamorig:rightforearm','mixamorig:rightelbow'],- wristl: ['lefthand','wrist_l','mixamorig:lefthand'],- wristr: ['righthand','wrist_r','mixamorig:righthand'],- hipl: ['leftupleg','hip_l','mixamorig:leftupleg'],- hipr: ['rightupleg','hip_r','mixamorig:rightupleg'],- kneel: ['leftleg','knee_l','mixamorig:leftleg'],- kneer: ['rightleg','knee_r','mixamorig:rightleg'],- anklel: ['leftfoot','ankle_l','mixamorig:leftfoot'],- ankler: ['rightfoot','ankle_r','mixamorig:rightfoot'],- head: ['head','mixamorig:head'],- neck: ['neck','mixamorig:neck'],- spine: ['spine','spine1','mixamorig:spine','mixamorig:spine1'],- hips: ['hips','mixamorig:hips'],-};--function applyPose(root, poseMap) {- if (!poseMap) return;- const byName = new Map();- root.traverse((o) => { if (o.name) byName.set(o.name.toLowerCase(), o); });- function findJoint(k) {- const key = k.toLowerCase();- const direct = byName.get(key);- if (direct) return direct;- const list = aliases[key] || [];- for (const a of list) { const j = byName.get(a); if (j) return j; }- return null;- }- for (const [key, rot] of Object.entries(poseMap)) {- const joint = findJoint(key);- if (!joint) continue;- joint.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);- }-}--function applyExpression(root, expression) {- if (!expression || typeof expression !== 'object') return;- root.traverse((o) => {- if (!o.isMesh || !o.morphTargetDictionary || !o.morphTargetInfluences) return;- for (const [name, value] of Object.entries(expression)) {- const idx = o.morphTargetDictionary[name] ?? o.morphTargetDictionary[name.toLowerCase()];- if (typeof idx === 'number') o.morphTargetInfluences[idx] = Number(value) || 0;- }- });-}--function frameCameraForScene(root, orbit, preset) {- const box = new THREE.Box3().setFromObject(root);- const size = new THREE.Vector3(); box.getSize(size);- const center = new THREE.Vector3(); box.getCenter(center);-- root.position.sub(center);-- const halfH = size.y * 0.5;- const lookAtY = halfH * (preset.lookAtY || 0);-- root.position.y += size.y * 0.05;-- const maxDim = Math.max(size.x, size.y, size.z);- const fov = THREE.MathUtils.degToRad(camera.fov);- const defaultDist = (maxDim / 2) / Math.tan(fov / 2) * 1.45;- const radius = defaultDist * (preset.radiusMult || 1.0);-- const theta = THREE.MathUtils.degToRad(Number(orbit.theta) || 0);- const phi = THREE.MathUtils.degToRad(Number(orbit.phi) || 80);- const x = radius * Math.sin(phi) * Math.sin(theta);- const y = radius * Math.cos(phi) + lookAtY;- const z = radius * Math.sin(phi) * Math.cos(theta);- camera.position.set(x, y, z);- camera.lookAt(0, lookAtY, 0);-}--const orbit = ${orbitJson};-const poseMap = ${poseJson};-const expression = ${expressionJson};-const preset = ${presetJson};--// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;-// a bare GLTFLoader throws "No DRACOLoader instance provided". Register-// every standard compression decoder from the pinned three.js release.-const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';-const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');-const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);--const loader = new GLTFLoader();-loader.setDRACOLoader(dracoLoader);-loader.setKTX2Loader(ktx2Loader);-loader.setMeshoptDecoder(MeshoptDecoder);--loader.load(${JSON.stringify(glbUrl)}, (gltf) => {- try {- const root = gltf.scene;- scene.add(root);- applyPose(root, poseMap);- applyExpression(root, expression);- frameCameraForScene(root, orbit, preset);- renderer.render(scene, camera);- requestAnimationFrame(() => {- renderer.render(scene, camera);- window.__renderDone = true;- });- } catch (err) {- window.__renderError = err.message || String(err);- }-}, undefined, (err) => {- window.__renderError = 'glb load failed: ' + (err?.message || err);-});-</script></body></html>`;-}--async function renderAvatarScene({- glbUrl,- width = 512,- height = 512,- background = 'transparent',- posePresetId = null,- cameraOrbit = null,- expression = null,- scenePreset = SCENE_PRESETS['upper-body'],-} = {}) {- const W = clamp(Number(width) || 512, MIN_DIM, MAX_DIM);- const H = clamp(Number(height) || 512, MIN_DIM, MAX_DIM);-- let pose = null;- if (posePresetId) {- const found = PRESETS.find((p) => p.id === posePresetId);- if (found) pose = found.pose;- }-- const browser = await getBrowser();- const page = await browser.newPage();- try {- await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });- const html = sceneViewerHtml({- glbUrl, width: W, height: H, background,- pose, cameraOrbit: cameraOrbit || { theta: 0, phi: 80, radius: null },- expression, scenePreset,- });- await page.setContent(html, { waitUntil: 'domcontentloaded' });- await page.waitForFunction(- 'window.__renderDone === true || window.__renderError !== null',- { timeout: 20_000 },- );- const err = await page.evaluate(() => window.__renderError);- if (err) {- throw Object.assign(new Error(`render failed: ${err}`), { status: 502, code: 'render_failed' });- }- const png = await page.screenshot({- type: 'png',- omitBackground: background === 'transparent',- clip: { x: 0, y: 0, width: W, height: H },- });- return { png };- } finally {- await page.close().catch(() => {});- }-}diff --git a/api/keys/index.js b/api/keys/index.jsindex c870b654b..96558fe5c 100644--- a/api/keys/index.js+++ b/api/keys/index.js@@ -11,7 +11,7 @@ import { limits } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { z } from 'zod';-const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile']);+const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write']);const createSchema = z.object({name: z.string().trim().min(1).max(80),diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex e223bc4d9..fb86fade2 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -38,7 +38,7 @@ function intersectScopes(requested, allowed) {}function scopeLabel(s) {- const labels = { 'avatars:read': 'Read your avatars', 'avatars:write': 'Create and update avatars', 'avatars:delete': 'Delete your avatars', profile: 'See your name and email', offline_access: 'Stay signed in across sessions' };+ const labels = { 'avatars:read': 'Read your avatars', 'avatars:write': 'Create and update avatars', 'avatars:delete': 'Delete your avatars', profile: 'See your name and email', offline_access: 'Stay signed in across sessions', 'memory:read': 'Recall your agents’ memories', 'memory:write': 'Store and forget your agents’ memories', 'agents:read': 'Screen your agents’ identities', 'agents:write': 'Register your agents on-chain' };return labels[s] || esc(s);}diff --git a/api/wk.js b/api/wk.jsindex b89fd1045..782bc1cbd 100644--- a/api/wk.js+++ b/api/wk.js@@ -130,6 +130,12 @@ function handleOauthAuthServer(req, res) {'avatars:delete','profile','offline_access',+ // Agent memory MCP tools (remember / recall / forget).+ 'memory:read',+ 'memory:write',+ // On-chain agent identity MCP tools (register_agent / identity_check).+ 'agents:read',+ 'agents:write',// USE-21 auth-hints: paid endpoints advertise these scopes for// Bearer-token bypass via the auth-hints extension.'read:agent-reputation',@@ -153,7 +159,16 @@ function handleOauthProtectedResource(req, res) {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'],+ scopes_supported: [+ 'avatars:read',+ 'avatars:write',+ 'avatars:delete',+ 'profile',+ 'memory:read',+ 'memory:write',+ 'agents:read',+ 'agents:write',+ ],},{ 'cache-control': 'public, max-age=300' },);diff --git a/api/x402/service.js b/api/x402/service.jsnew file mode 100644index 000000000..0dee2787d--- /dev/null+++ b/api/x402/service.js@@ -0,0 +1,159 @@+// Hosted x402 paywall for agent-published services (the `monetize_endpoint` tool).+//+// GET|POST /api/x402/service/<slug>+//+// Each agent that runs `monetize_endpoint` gets a row in agent_paid_services and+// a stable resource URL here. This handler loads the row per request, wraps it+// in the shared paidEndpoint() x402 dance with the price the agent set and the+// agent's OWN wallet as the payee, and — only after the buyer's USDC settles —+// proxies the call through to the agent's upstream `target_url` (SSRF-guarded)+// and returns its response. That is the agent earning USDC: the buyer pays the+// agent, the agent's API does the work.+//+// The slug arrives as ?slug=<slug> via the vercel rewrite for+// /api/x402/service/(.*). Unknown / archived slugs 404 before any 402 challenge.++import { error, cors } from '../_lib/http.js';+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { safeFetchJson, SsrfError } from '../_lib/ssrf.js';+import {+ getActiveServiceBySlug,+ serviceResourceUrl,+ atomicsToUsdc,+} from '../_lib/agent-paid-services.js';++function slugFromReq(req) {+ const fromQuery = req.query?.slug;+ if (fromQuery) return String(Array.isArray(fromQuery) ? fromQuery[0] : fromQuery);+ const path = new URL(req.url, 'http://x').pathname;+ const m = path.match(/\/api\/x402\/service\/([^/?]+)/);+ return m ? decodeURIComponent(m[1]) : null;+}++// Read the buyer's JSON body for a POST proxy. paidEndpoint hands us the raw+// req; we drain it once here (the payment header is already verified by then).+async function readBody(req) {+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ return raw ? JSON.parse(raw) : null;+ } catch {+ return null;+ }+}++// Build the bazaar discovery extension for a service row so the live 402 mirrors+// what /.well-known/x402.json advertises.+function bazaarFor(row, resourceUrl) {+ const inputSchema = row.input_schema || { type: 'object', additionalProperties: true };+ return {+ description: row.description,+ useCases: ['agent service', 'x402 paid api'],+ input: {+ type: 'json',+ example: {},+ schema: inputSchema,+ },+ output: {+ type: 'json',+ example: {},+ },+ schema: buildBazaarSchema({+ method: row.target_method,+ bodySchema: row.target_method === 'POST' ? inputSchema : undefined,+ }),+ resource: resourceUrl,+ };+}++export default async function handler(req, res) {+ // OPTIONS preflight is handled by paidEndpoint too, but we may 404 before we+ // build it, so answer CORS up front for the not-found path.+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;++ const slug = slugFromReq(req);+ if (!slug) return error(res, 400, 'bad_request', 'missing service slug');++ let row;+ try {+ row = await getActiveServiceBySlug(slug);+ } catch (err) {+ console.error('[x402/service] lookup failed', err?.message || err);+ return error(res, 502, 'lookup_failed', 'could not load service');+ }+ if (!row) return error(res, 404, 'not_found', `no paid service at /api/x402/service/${slug}`);++ const method = row.target_method === 'POST' ? 'POST' : 'GET';+ const resourceUrl = serviceResourceUrl(slug);+ const network = row.network === 'solana' ? 'solana' : 'base';+ const payTo = network === 'solana' ? { solana: row.payout_address } : { base: row.payout_address };++ const paid = paidEndpoint({+ route: `/api/x402/service/${slug}`,+ method,+ priceAtomics: row.price_atomics,+ networks: [network],+ description: row.description,+ bazaar: bazaarFor(row, resourceUrl),+ service: withService({+ serviceName: row.name,+ tags: ['agent', 'monetized', network],+ }),+ // Settle the buyer's USDC to the AGENT's own wallet, not the platform's.+ payTo,+ resourceUrlBuilder: () => resourceUrl,++ async handler({ req: pReq }) {+ const body = method === 'POST' ? await readBody(pReq) : undefined;+ // Forward the buyer's query params (minus our routing slug) on GET.+ let targetUrl = row.target_url;+ if (method === 'GET') {+ try {+ const incoming = new URL(pReq.url, 'http://x').searchParams;+ incoming.delete('slug');+ const qs = incoming.toString();+ if (qs) {+ const u = new URL(row.target_url);+ for (const [k, v] of incoming) u.searchParams.set(k, v);+ targetUrl = u.href;+ }+ } catch {+ /* fall back to the bare target_url */+ }+ }++ let upstream;+ try {+ upstream = await safeFetchJson(targetUrl, { method, body });+ } catch (err) {+ if (err instanceof SsrfError) {+ throw Object.assign(new Error(`upstream blocked: ${err.message}`), {+ status: 502,+ code: 'upstream_blocked',+ });+ }+ throw Object.assign(new Error(`upstream request failed: ${err?.message || err}`), {+ status: 502,+ code: 'upstream_failed',+ });+ }+ if (!upstream.ok) {+ throw Object.assign(new Error(`upstream returned ${upstream.status}`), {+ status: 502,+ code: 'upstream_error',+ });+ }+ return {+ service: row.name,+ price_usdc: atomicsToUsdc(row.price_atomics),+ network,+ result: upstream.data,+ };+ },+ });++ return paid(req, res);+}diff --git a/server-3d.json b/server-3d.jsonindex fd05ca4d1..105ba95fe 100644--- a/server-3d.json+++ b/server-3d.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/threews-3d-studio",- "description": "Turn text or an image into an interactive, animation-ready 3D model (GLB): generate (text/image→3D, quality tiers + geometry backends), auto-rig, animate, pose, remesh, segment, retexture, and IBM Granite prompt-direction + material generation. By three.ws.",+ "description": "Turn text or an image into an interactive, animation-ready 3D model (GLB): generate (text/image→3D, quality tiers + geometry backends), auto-rig, animate, pose, remesh, segment, retexture, save generated models as durable named avatars, and IBM Granite prompt-direction + material generation. By three.ws.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/server.json b/server.jsonindex d78167199..957ce64f8 100644--- a/server.json+++ b/server.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/three.ws",- "description": "Render 3D avatars from three.ws and validate, inspect, and optimize glTF/GLB models.",+ "description": "Render 3D avatars from three.ws as interactive embeds or real PNG/JPEG/WebP images, get copy-paste <iframe> embed code for any avatar, on-chain agent, or Forge creation to drop into Notion/Webflow/a blog, persist and manage your avatar library, validate, inspect, and optimize glTF/GLB models, give agents persistent memory (remember, recall, forget), and mint an agent's on-chain identity — register_agent (server-custodial Metaplex Agent Registry on Solana, or a prepared ERC-8004 payload for Base) and identity_check (Granite impersonation + policy screening).","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.jsindex 1fcfbbc6e..4636127bf 100644--- a/src/erc8004/agent-registry.js+++ b/src/erc8004/agent-registry.js@@ -9,8 +9,14 @@*/import { BrowserProvider, Contract } from 'ethers';-import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';import { glbFileToThumbnail } from './thumbnail.js';+import { buildRegistrationJSON } from './registration-json.js';++// Re-exported so existing browser callers (src/mint/index.js) keep their import+// path. The builder itself lives in registration-json.js — a dependency-light+// module server-side code can import without the ethers/Three.js stack.+export { buildRegistrationJSON };// ---------------------------------------------------------------------------// Wallet@@ -275,104 +281,6 @@ export async function pinFile(blob, apiToken) {return data.url;}-// ----------------------------------------------------------------------------// Registration JSON builder-// -----------------------------------------------------------------------------/**- * Build an ERC-8004 agent registration JSON.- *- * @param {object} opts- * @param {string} opts.name Agent display name- * @param {string} opts.description Natural-language description- * @param {string} opts.imageUrl URL of the 3D GLB model (HTTPS or ipfs://)- * @param {number} opts.agentId Token ID from the registry (filled after mint)- * @param {number} opts.chainId Chain ID where registered- * @param {string} opts.registryAddr Identity Registry contract address- * @param {string[]} [opts.services] Additional service objects- * @returns {object}- */-/**- * Build a spec-compliant ERC-8004 registration JSON.- *- * `imageUrl` is the 2D thumbnail (per NFT convention). `glbUrl` is optional —- * when present, the GLB is surfaced as a dedicated `avatar` service entry and- * a companion `3D` renderer service pointing at 3dagent so other apps can load- * the body in-browser without coupling to our domain.- *- * @param {object} opts- * @param {string} opts.name- * @param {string} opts.description- * @param {string} [opts.imageUrl] 2D thumbnail URL (PNG/JPG) — used for `image`- * @param {string} [opts.glbUrl] Optional GLB URL — emitted as an `avatar` service- * @param {number} opts.agentId- * @param {number} opts.chainId- * @param {string} opts.registryAddr- * @param {Array} [opts.services] Extra service entries- * @param {boolean}[opts.x402Support]- * @param {Array<{name:string,url:string,loop?:boolean,clipName?:string,source?:string}>} [opts.animations]- * Optional animation clip list — emitted as a top-level `animations` extension- * field (ERC-8004 permits extensions). Viewers that understand the field can- * attach extra clips; others ignore it harmlessly.- */-export function buildRegistrationJSON({- name,- description,- imageUrl,- glbUrl,- agentId,- chainId,- registryAddr,- services = [],- x402Support = false,- animations,-}) {- const baseServices = [];- if (glbUrl) {- baseServices.push({- name: 'avatar',- endpoint: glbUrl,- version: 'gltf-2.0',- });- baseServices.push({- name: '3D',- endpoint: `https://three.ws/app#model=${encodeURIComponent(glbUrl)}`,- version: '1.0',- });- }-- const json = {- type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',- name,- description,- image: imageUrl || '',- active: true,- x402Support,- services: [...baseServices, ...services],- registrations: [- {- agentId,- agentRegistry: agentRegistryId(chainId, registryAddr),- },- ],- supportedTrust: ['reputation'],- };-- // Top-level `body` field follows specs/AGENT_MANIFEST.md convention and is- // read directly by src/manifest.js → normalize(). Spec-permitted (extension- // fields MAY be added). Redundant with the `avatar` service entry above but- // keeps this repo's manifest resolver happy without forcing it to grep services.- if (glbUrl) {- json.body = { uri: glbUrl, format: 'gltf-binary' };- }-- if (Array.isArray(animations) && animations.length > 0) {- json.animations = animations;- }-- return json;-}-// ---------------------------------------------------------------------------// On-chain registration// ---------------------------------------------------------------------------diff --git a/src/erc8004/registration-json.js b/src/erc8004/registration-json.jsnew file mode 100644index 000000000..af0d86e38--- /dev/null+++ b/src/erc8004/registration-json.js@@ -0,0 +1,93 @@+/**+ * ERC-8004 registration JSON builder — pure, dependency-light.+ *+ * Split out of agent-registry.js (which pulls in ethers + a Three.js thumbnail+ * renderer for the browser deploy flow) so server-side callers — e.g. the MCP+ * `register_agent` tool that returns a prepared "continue in browser" payload —+ * can build the exact same document without dragging the wallet/renderer stack+ * into a serverless function. agent-registry.js re-exports this so the browser+ * import path is unchanged.+ */++import { agentRegistryId } from './abi.js';++/**+ * Build a spec-compliant ERC-8004 registration JSON.+ *+ * `imageUrl` is the 2D thumbnail (per NFT convention). `glbUrl` is optional —+ * when present, the GLB is surfaced as a dedicated `avatar` service entry and+ * a companion `3D` renderer service pointing at 3dagent so other apps can load+ * the body in-browser without coupling to our domain.+ *+ * @param {object} opts+ * @param {string} opts.name+ * @param {string} opts.description+ * @param {string} [opts.imageUrl] 2D thumbnail URL (PNG/JPG) — used for `image`+ * @param {string} [opts.glbUrl] Optional GLB URL — emitted as an `avatar` service+ * @param {number} opts.agentId+ * @param {number} opts.chainId+ * @param {string} opts.registryAddr+ * @param {Array} [opts.services] Extra service entries+ * @param {boolean}[opts.x402Support]+ * @param {Array<{name:string,url:string,loop?:boolean,clipName?:string,source?:string}>} [opts.animations]+ * Optional animation clip list — emitted as a top-level `animations` extension+ * field (ERC-8004 permits extensions). Viewers that understand the field can+ * attach extra clips; others ignore it harmlessly.+ */+export function buildRegistrationJSON({+ name,+ description,+ imageUrl,+ glbUrl,+ agentId,+ chainId,+ registryAddr,+ services = [],+ x402Support = false,+ animations,+}) {+ const baseServices = [];+ if (glbUrl) {+ baseServices.push({+ name: 'avatar',+ endpoint: glbUrl,+ version: 'gltf-2.0',+ });+ baseServices.push({+ name: '3D',+ endpoint: `https://three.ws/app#model=${encodeURIComponent(glbUrl)}`,+ version: '1.0',+ });+ }++ const json = {+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',+ name,+ description,+ image: imageUrl || '',+ active: true,+ x402Support,+ services: [...baseServices, ...services],+ registrations: [+ {+ agentId,+ agentRegistry: agentRegistryId(chainId, registryAddr),+ },+ ],+ supportedTrust: ['reputation'],+ };++ // Top-level `body` field follows specs/AGENT_MANIFEST.md convention and is+ // read directly by src/manifest.js → normalize(). Spec-permitted (extension+ // fields MAY be added). Redundant with the `avatar` service entry above but+ // keeps this repo's manifest resolver happy without forcing it to grep services.+ if (glbUrl) {+ json.body = { uri: glbUrl, format: 'gltf-binary' };+ }++ if (Array.isArray(animations) && animations.length > 0) {+ json.animations = animations;+ }++ return json;+}diff --git a/src/game/npc/npc-aixbt.js b/src/game/npc/npc-aixbt.jsindex 92b5d9bb1..9201f86c6 100644--- a/src/game/npc/npc-aixbt.js+++ b/src/game/npc/npc-aixbt.js@@ -1,11 +1,10 @@// AIXBT — the town's intelligence terminal.//-// Unlike the vendor counters (npc-services.js), aixbt doesn't sell a one-shot-// paid call: he's the wired-in oracle. Walk up, press E, and he immediately-// pulls the live aixbt feed — narrative intel + momentum-ranked movers — and-// reads it back in a terminal panel. A query bar re-runs the feed for a token-// or chain. Data is the three.ws ⇄ aixbt bridge (/api/aixbt/*); the upstream-// aixbt key stays server-side.+// Walk up, press E, and aixbt asks what you want to see — a game-style dialogue+// wheel with four reads. You pick one (and, for a scan, type the token), and the+// terminal runs the live aixbt feed for exactly that: momentum movers, narrative+// intel, a macro read, or a single-token scan. Data is the three.ws ⇄ aixbt+// bridge (/api/aixbt/*); the upstream aixbt key stays server-side.//// Free at the counter because three.ws already pays aixbt upstream; the paid// layer lives on the MCP tools (aixbt_intel / aixbt_projects) for other agents.@@ -62,6 +61,39 @@ const CHAINS = [{ value: 'ethereum', label: 'Ethereum' },];+// The dialogue wheel. Each choice maps to a live aixbt read. `say` is the+// in-world line aixbt speaks the moment you pick it.+const CHOICES = [+ {+ id: 'movers',+ icon: '📈',+ title: "What's moving?",+ desc: 'Momentum-ranked movers, live',+ say: 'Pulling the movers — highest momentum first.',+ },+ {+ id: 'narratives',+ icon: '📰',+ title: "What's the story?",+ desc: 'Narrative intel forming now',+ say: 'Reading the narratives forming right now.',+ },+ {+ id: 'macro',+ icon: '🌐',+ title: 'Read the market',+ desc: 'Hourly macro context',+ say: 'Here is the macro read — crypto and tradfi.',+ },+ {+ id: 'scan',+ icon: '🔍',+ title: 'Scan a token',+ desc: 'Type a ticker, I dig in',+ say: 'Name the token and I will scan it.',+ },+];+function injectStyles() {if (document.getElementById('aixbt-term-styles')) return;const s = document.createElement('style');@@ -72,14 +104,36 @@ function injectStyles() {.aixbt-live { display:inline-flex; align-items:center; gap:5px; font-size:10px; font-weight:800; letter-spacing:0.08em; color:#27e0c4; }.aixbt-live::before { content:''; width:7px; height:7px; border-radius:50%; background:#27e0c4; box-shadow:0 0 8px #27e0c4; animation:aixbt-pulse 1.6s ease-in-out infinite; }@keyframes aixbt-pulse { 0%,100%{opacity:1} 50%{opacity:0.35} }- .aixbt-bar { display:flex; gap:8px; margin:4px 0 14px; }- .aixbt-bar .npc-svc-input { margin:0; }- .aixbt-bar .aixbt-token { flex:1 1 auto; }- .aixbt-bar .aixbt-chain { flex:0 0 130px; }- .aixbt-refresh { flex:0 0 auto; border:1px solid var(--cc-edge, rgba(255,255,255,0.14)); background:rgba(39,224,196,0.12); color:#9ff4e6; font-weight:700; border-radius:var(--cc-radius,4px); padding:0 14px; cursor:pointer; transition:background .15s ease; }- .aixbt-refresh:hover { background:rgba(39,224,196,0.22); }- .aixbt-refresh:disabled { opacity:0.5; cursor:default; }+ /* dialogue wheel */+ .aixbt-ask { font-size:13px; color:var(--cc-text,#e9e9ec); margin:2px 0 12px; }+ .aixbt-menu { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:4px; }+ .aixbt-choice { display:flex; align-items:flex-start; gap:11px; text-align:left; padding:13px 14px; border:1px solid var(--cc-edge, rgba(255,255,255,0.14)); border-radius:var(--cc-radius,6px); background:rgba(255,255,255,0.03); color:var(--cc-text,#e9e9ec); cursor:pointer; transition:border-color .15s ease, background .15s ease, transform .12s ease; }+ .aixbt-choice:hover { border-color:rgba(39,224,196,0.55); background:rgba(39,224,196,0.08); transform:translateY(-1px); }+ .aixbt-choice:active { transform:translateY(0); }+ .aixbt-choice:focus-visible { outline:2px solid #27e0c4; outline-offset:2px; }+ .aixbt-choice-ic { font-size:20px; line-height:1; margin-top:1px; }+ .aixbt-choice-key { position:absolute; }+ .aixbt-choice-t { font-weight:800; font-size:14px; letter-spacing:0.01em; }+ .aixbt-choice-d { font-size:11.5px; color:var(--cc-muted,#9a9aa2); margin-top:3px; line-height:1.35; }+ .aixbt-num { display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px; border-radius:3px; font-size:10px; font-weight:800; color:#9ff4e6; background:rgba(39,224,196,0.16); margin-right:6px; vertical-align:1px; }+ /* chips + back + scan form */+ .aixbt-toolbar { display:flex; align-items:center; gap:10px; margin:2px 0 14px; flex-wrap:wrap; }+ .aixbt-back { flex:0 0 auto; border:1px solid var(--cc-edge, rgba(255,255,255,0.14)); background:rgba(255,255,255,0.04); color:var(--cc-text,#e9e9ec); font-weight:700; font-size:12px; border-radius:var(--cc-radius,4px); padding:5px 11px; cursor:pointer; transition:background .15s ease; }+ .aixbt-back:hover { background:rgba(255,255,255,0.09); }+ .aixbt-chips { display:flex; gap:6px; flex-wrap:wrap; }+ .aixbt-chip { border:1px solid var(--cc-edge, rgba(255,255,255,0.14)); background:transparent; color:var(--cc-muted,#9a9aa2); font-size:11.5px; font-weight:700; border-radius:999px; padding:4px 11px; cursor:pointer; transition:all .15s ease; }+ .aixbt-chip:hover { color:var(--cc-text,#e9e9ec); border-color:rgba(255,255,255,0.3); }+ .aixbt-chip.is-on { color:#06201c; background:#27e0c4; border-color:#27e0c4; }+ .aixbt-scan-form { display:flex; gap:8px; margin:2px 0 14px; }+ .aixbt-scan-form .npc-svc-input { margin:0; }+ .aixbt-scan-form .aixbt-token { flex:1 1 auto; }+ .aixbt-scan-form .aixbt-chain { flex:0 0 130px; }+ .aixbt-go { flex:0 0 auto; border:1px solid var(--cc-edge, rgba(255,255,255,0.14)); background:rgba(39,224,196,0.14); color:#9ff4e6; font-weight:800; border-radius:var(--cc-radius,4px); padding:0 16px; cursor:pointer; transition:background .15s ease; }+ .aixbt-go:hover { background:rgba(39,224,196,0.24); }+ .aixbt-go:disabled { opacity:0.5; cursor:default; }+ /* result rows */.aixbt-section-h { font-size:11px; font-weight:800; letter-spacing:0.07em; text-transform:uppercase; color:var(--cc-muted,#9a9aa2); margin:16px 0 8px; }+ .aixbt-section-h:first-child { margin-top:4px; }.aixbt-row { padding:10px 0; border-top:1px solid var(--cc-edge, rgba(255,255,255,0.08)); }.aixbt-row:first-of-type { border-top:0; }.aixbt-row-top { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }@@ -96,6 +150,13 @@ function injectStyles() {.aixbt-score-track { height:5px; border-radius:3px; background:rgba(255,255,255,0.08); overflow:hidden; }.aixbt-score-fill { display:block; height:100%; background:linear-gradient(90deg,#27e0c4,#7aa8ff); border-radius:3px; transition:width .4s ease; }.aixbt-score-v { font-size:11px; text-align:right; color:var(--cc-text,#e9e9ec); font-variant-numeric:tabular-nums; }+ /* macro grounding */+ .aixbt-ground-sec { margin-top:14px; }+ .aixbt-ground-sec:first-child { margin-top:4px; }+ .aixbt-ground-k { font-size:11px; font-weight:800; letter-spacing:0.06em; text-transform:uppercase; color:#9ff4e6; margin-bottom:6px; }+ .aixbt-ground-p { font-size:13px; line-height:1.5; color:var(--cc-text,#e9e9ec); margin:0 0 6px; }+ .aixbt-ground-list { margin:0; padding-left:18px; }+ .aixbt-ground-list li { font-size:13px; line-height:1.5; color:var(--cc-text,#e9e9ec); margin-bottom:4px; }.aixbt-skel { height:54px; border-radius:6px; background:linear-gradient(90deg,rgba(255,255,255,0.05),rgba(255,255,255,0.11),rgba(255,255,255,0.05)); background-size:200% 100%; animation:aixbt-shimmer 1.2s linear infinite; margin-bottom:8px; }@keyframes aixbt-shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} }.aixbt-empty, .aixbt-error { color:var(--cc-muted,#9a9aa2); font-size:13px; padding:14px 0; }@@ -168,8 +229,75 @@ function renderProjects(items) {}));}-// Open aixbt's intelligence terminal. Auto-loads the live feed; the query bar-// re-runs it. Manages its own lifecycle (no return value).+// Grounding comes back as aixbt-shaped structured context. We render it+// defensively: strings become paragraphs, arrays become bullet lists, nested+// objects become titled sections — never fabricating a field that isn't there.+function humanizeKey(k) {+ return String(k)+ .replace(/[_-]+/g, ' ')+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/\b\w/g, (c) => c.toUpperCase());+}++function groundingItemText(v) {+ if (v == null) return null;+ if (typeof v === 'string' || typeof v === 'number') return String(v);+ if (typeof v === 'object') {+ return v.description || v.summary || v.text || v.title || v.name || v.headline || null;+ }+ return null;+}++function renderGroundingValue(value) {+ if (value == null) return null;+ if (typeof value === 'string' || typeof value === 'number') {+ return el('p', { class: 'aixbt-ground-p', text: String(value) });+ }+ if (Array.isArray(value)) {+ const texts = value.map(groundingItemText).filter(Boolean);+ if (!texts.length) return null;+ return el('ul', { class: 'aixbt-ground-list' }, texts.slice(0, 12).map((t) => el('li', { text: t })));+ }+ if (typeof value === 'object') {+ // One level of nesting: render child keys as paragraphs/lists.+ const kids = Object.entries(value)+ .map(([k, v]) => {+ const inner = Array.isArray(v)+ ? renderGroundingValue(v)+ : (typeof v === 'string' || typeof v === 'number')+ ? el('p', { class: 'aixbt-ground-p' }, [el('strong', { text: `${humanizeKey(k)}: ` }), String(v)])+ : null;+ return inner;+ })+ .filter(Boolean);+ return kids.length ? el('div', {}, kids) : null;+ }+ return null;+}++function renderGrounding(grounding) {+ if (grounding == null || (typeof grounding === 'object' && !Object.keys(grounding).length)) {+ return el('div', { class: 'aixbt-empty', text: 'No macro read available right now.' });+ }+ if (typeof grounding === 'string') {+ return el('p', { class: 'aixbt-ground-p', text: grounding });+ }+ const sections = Object.entries(grounding)+ .map(([k, v]) => {+ const rendered = renderGroundingValue(v);+ if (!rendered) return null;+ return el('div', { class: 'aixbt-ground-sec' }, [+ el('div', { class: 'aixbt-ground-k', text: humanizeKey(k) }),+ rendered,+ ]);+ })+ .filter(Boolean);+ if (!sections.length) return el('div', { class: 'aixbt-empty', text: 'No macro read available right now.' });+ return el('div', {}, sections);+}++// Open aixbt's intelligence terminal. Opens to the dialogue wheel; each choice+// runs the matching live read. Manages its own lifecycle (no return value).export function openAixbtTerminal(npc, { ui } = {}) {injectStyles();closePanel();@@ -187,86 +315,200 @@ export function openAixbtTerminal(npc, { ui } = {}) {]),close,]));- card.appendChild(el('p', { class: 'npc-svc-intro', text: 'Live aixbt feed — narrative intel and momentum movers. Filter by token or chain.' }));-- // Query bar.- const tokenInput = el('input', { class: 'npc-svc-input aixbt-token', type: 'text', placeholder: 'Token or ticker (optional)' });- const chainSelect = el('select', { class: 'npc-svc-input aixbt-chain' }, CHAINS.map((c) =>- el('option', { value: c.value }, [c.label])));- const refreshBtn = el('button', { class: 'aixbt-refresh', type: 'button', text: 'Refresh' });- // Keep typing out of the world's movement handlers (window-level keydown).- for (const node of [tokenInput, chainSelect]) {- node.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); run(); } });- node.addEventListener('keyup', (e) => e.stopPropagation());- }- card.appendChild(el('div', { class: 'aixbt-bar' }, [tokenInput, chainSelect, refreshBtn]));const body = el('div', { class: 'npc-svc-result', style: 'display:block' });card.appendChild(body);- function skeleton() {+ let busy = false;++ function skeleton(label) {body.textContent = '';- body.appendChild(el('div', { class: 'aixbt-section-h', text: 'Narratives' }));+ body.appendChild(el('div', { class: 'aixbt-section-h', text: label }));for (let i = 0; i < 3; i++) body.appendChild(el('div', { class: 'aixbt-skel' }));}- let busy = false;- async function run() {+ function backBar(extra) {+ return el('div', { class: 'aixbt-toolbar' }, [+ el('button', { class: 'aixbt-back', type: 'button', text: '← Ask again', onclick: showMenu }),+ extra || null,+ ]);+ }++ function chainChips(active, onPick) {+ return el('div', { class: 'aixbt-chips' }, CHAINS.map((c) =>+ el('button', {+ class: `aixbt-chip${c.value === active ? ' is-on' : ''}`,+ type: 'button',+ text: c.label,+ onclick: () => { if (c.value !== active && !busy) onPick(c.value); },+ })));+ }++ function showError(err, retry) {+ body.textContent = '';+ body.appendChild(backBar());+ if (err?.code === 'aixbt_not_configured') {+ body.appendChild(el('div', { class: 'aixbt-error', text: "aixbt isn't connected on this deployment yet." }));+ if (err.setup) body.appendChild(el('div', { class: 'aixbt-setup', text: err.setup }));+ npc?.say?.('My feed isn\'t wired up here yet.');+ } else if (err?.code === 'aixbt_unauthorized') {+ body.appendChild(el('div', { class: 'aixbt-error', text: 'That read needs a higher aixbt plan than this key has.' }));+ npc?.say?.('My key can\'t reach that one.');+ } else {+ body.appendChild(el('div', { class: 'aixbt-error', text: `Couldn't reach the aixbt feed: ${err.message}` }));+ if (retry) body.appendChild(el('button', { class: 'aixbt-go', type: 'button', text: 'Retry', style: 'margin-top:10px', onclick: retry }));+ ui?.toast?.('aixbt feed unavailable', 'warn');+ }+ }++ // ── reads ─────────────────────────────────────────────────────────────────+ async function runMovers(chain) {if (busy) return;busy = true;- refreshBtn.disabled = true;- refreshBtn.textContent = 'Loading…';- skeleton();- const token = tokenInput.value.trim();- const chain = chainSelect.value;- const intelQs = new URLSearchParams({ limit: '6' });- if (chain) intelQs.set('chain', chain);- const projQs = new URLSearchParams({ limit: '6' });- if (chain) projQs.set('chain', chain);- if (token) projQs.set('names', token);+ skeleton('Momentum');+ const qs = new URLSearchParams({ limit: '8' });+ if (chain) qs.set('chain', chain);+ try {+ const { projects = [] } = await fetchJson(`/api/aixbt/projects?${qs}`);+ body.textContent = '';+ body.appendChild(backBar(chainChips(chain, runMovers)));+ body.appendChild(el('div', { class: 'aixbt-section-h', text: chain ? `Momentum · ${chain}` : 'Momentum' }));+ body.appendChild(renderProjects(projects));+ npc?.say?.(projects.length ? `Top mover is ${projects[0].ticker ? '$' + projects[0].ticker : projects[0].name}.` : 'Quiet on that chain — try another.');+ } catch (err) {+ showError(err, () => runMovers(chain));+ } finally { busy = false; }+ }+ async function runNarratives(chain) {+ if (busy) return;+ busy = true;+ skeleton('Narratives');+ const qs = new URLSearchParams({ limit: '8' });+ if (chain) qs.set('chain', chain);try {- const [intelRes, projRes] = await Promise.all([- fetchJson(`/api/aixbt/intel?${intelQs}`),+ const { intel = [] } = await fetchJson(`/api/aixbt/intel?${qs}`);+ body.textContent = '';+ body.appendChild(backBar(chainChips(chain, runNarratives)));+ body.appendChild(el('div', { class: 'aixbt-section-h', text: chain ? `Narratives · ${chain}` : 'Narratives' }));+ body.appendChild(renderIntel(intel));+ npc?.say?.(intel.length ? `Tracking ${intel.length} narrative${intel.length === 1 ? '' : 's'} right now.` : 'No fresh narratives on that filter.');+ } catch (err) {+ showError(err, () => runNarratives(chain));+ } finally { busy = false; }+ }++ async function runMacro() {+ if (busy) return;+ busy = true;+ skeleton('Macro');+ try {+ const { grounding } = await fetchJson('/api/aixbt/grounding');+ body.textContent = '';+ body.appendChild(backBar());+ body.appendChild(el('div', { class: 'aixbt-section-h', text: 'Market context' }));+ body.appendChild(renderGrounding(grounding));+ npc?.say?.('That\'s the read across crypto and tradfi.');+ } catch (err) {+ showError(err, runMacro);+ } finally { busy = false; }+ }++ async function runScan(token, chain) {+ if (busy) return;+ const q = (token || '').trim();+ if (!q) { showScan(token, chain); return; }+ busy = true;+ skeleton(`Scanning ${q.toUpperCase()}`);+ const projQs = new URLSearchParams({ limit: '6', names: q });+ const intelQs = new URLSearchParams({ limit: '6' });+ if (chain) { projQs.set('chain', chain); intelQs.set('chain', chain); }+ try {+ const [projRes, intelRes] = await Promise.all([fetchJson(`/api/aixbt/projects?${projQs}`),+ fetchJson(`/api/aixbt/intel?${intelQs}`),]);+ const projects = projRes.projects || [];+ // Intel isn't name-filterable upstream; keep items that mention the token.+ const ql = q.toLowerCase();+ const intel = (intelRes.intel || []).filter((i) =>+ (i.ticker && i.ticker.toLowerCase() === ql) ||+ (i.project && i.project.toLowerCase().includes(ql)) ||+ (i.description && i.description.toLowerCase().includes(ql)));body.textContent = '';- body.appendChild(el('div', { class: 'aixbt-section-h', text: token ? `Momentum · ${token.toUpperCase()}` : 'Momentum' }));- body.appendChild(renderProjects(projRes.projects || []));- body.appendChild(el('div', { class: 'aixbt-section-h', text: 'Narratives' }));- body.appendChild(renderIntel(intelRes.intel || []));- npc?.say?.(- (projRes.projects || []).length || (intelRes.intel || []).length- ? 'Here\'s what the feed is showing right now.'- : 'Quiet on that filter — try a broader chain.',- );+ body.appendChild(backBar());+ body.appendChild(el('div', { class: 'aixbt-section-h', text: `Momentum · ${q.toUpperCase()}` }));+ body.appendChild(renderProjects(projects));+ body.appendChild(el('div', { class: 'aixbt-section-h', text: `Narratives · ${q.toUpperCase()}` }));+ body.appendChild(renderIntel(intel));+ npc?.say?.(projects.length || intel.length ? `Here's what I have on ${q.toUpperCase()}.` : `Nothing surfacing on ${q.toUpperCase()} yet.`);} catch (err) {- body.textContent = '';- if (err?.code === 'aixbt_not_configured') {- body.appendChild(el('div', { class: 'aixbt-error', text: 'aixbt isn\'t connected on this deployment yet.' }));- if (err.setup) body.appendChild(el('div', { class: 'aixbt-setup', text: err.setup }));- npc?.say?.('My feed isn\'t wired up here yet.');- } else {- body.appendChild(el('div', { class: 'aixbt-error', text: `Couldn't reach the aixbt feed: ${err.message}` }));- body.appendChild(el('button', { class: 'aixbt-refresh', type: 'button', text: 'Retry', style: 'margin-top:10px', onclick: run }));- ui?.toast?.('aixbt feed unavailable', 'warn');- }- } finally {- busy = false;- refreshBtn.disabled = false;- refreshBtn.textContent = 'Refresh';+ showError(err, () => runScan(q, chain));+ } finally { busy = false; }+ }++ // ── scan sub-form (the "type what you want" step) ──────────────────────────+ function showScan(prevToken, prevChain) {+ body.textContent = '';+ body.appendChild(backBar());+ body.appendChild(el('p', { class: 'aixbt-ask', text: 'Which token should I scan?' }));+ const tokenInput = el('input', { class: 'npc-svc-input aixbt-token', type: 'text', placeholder: 'Token or ticker (e.g. SOL)', value: prevToken || '' });+ const chainSelect = el('select', { class: 'npc-svc-input aixbt-chain' }, CHAINS.map((c) =>+ el('option', { value: c.value, selected: c.value === (prevChain || '') ? true : null }, [c.label])));+ const goBtn = el('button', { class: 'aixbt-go', type: 'button', text: 'Scan' });+ // Keep typing out of the world's movement handlers (window-level keydown).+ for (const node of [tokenInput, chainSelect]) {+ node.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); runScan(tokenInput.value, chainSelect.value); } });+ node.addEventListener('keyup', (e) => e.stopPropagation());}+ goBtn.addEventListener('click', () => runScan(tokenInput.value, chainSelect.value));+ body.appendChild(el('div', { class: 'aixbt-scan-form' }, [tokenInput, chainSelect, goBtn]));+ requestAnimationFrame(() => tokenInput.focus());+ }++ // ── the dialogue wheel ─────────────────────────────────────────────────────+ function pick(choice) {+ if (busy) return;+ npc?.say?.(choice.say);+ if (choice.id === 'movers') runMovers('');+ else if (choice.id === 'narratives') runNarratives('');+ else if (choice.id === 'macro') runMacro();+ else if (choice.id === 'scan') showScan('', '');+ }++ function showMenu() {+ body.textContent = '';+ body.appendChild(el('p', { class: 'aixbt-ask', text: 'What do you want to see? Pick a read — or press 1–4.' }));+ const menu = el('div', { class: 'aixbt-menu' }, CHOICES.map((c, idx) =>+ el('button', { class: 'aixbt-choice', type: 'button', onclick: () => pick(c), 'aria-label': c.title }, [+ el('span', { class: 'aixbt-choice-ic', text: c.icon }),+ el('span', {}, [+ el('span', { class: 'aixbt-choice-t' }, [el('span', { class: 'aixbt-num', text: String(idx + 1) }), c.title]),+ el('span', { class: 'aixbt-choice-d', text: c.desc }),+ ]),+ ])));+ body.appendChild(menu);+ requestAnimationFrame(() => { const first = menu.querySelector('.aixbt-choice'); if (first) first.focus(); });}- refreshBtn.addEventListener('click', run);- // Mount + ESC + autoload.+ // Number-key shortcuts (1–4) while the menu is the active view.+ const onKey = (e) => {+ if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); closePanel(); return; }+ if (busy) return;+ const onMenu = body.querySelector('.aixbt-menu');+ if (onMenu && e.key >= '1' && e.key <= String(CHOICES.length)) {+ e.stopPropagation(); e.preventDefault();+ pick(CHOICES[Number(e.key) - 1]);+ }+ };++ // Mount + ESC + open to the dialogue wheel.const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;- const onKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); closePanel(); } };document.addEventListener('keydown', onKey, true);document.body.appendChild(overlay);openPanel = { overlay, onKey, opener };requestAnimationFrame(() => {overlay.classList.add('is-in');- run();+ showMenu();});}diff --git a/tests/api/mcp-avatar-persist.test.js b/tests/api/mcp-avatar-persist.test.jsnew file mode 100644index 000000000..baa0c9b0d--- /dev/null+++ b/tests/api/mcp-avatar-persist.test.js@@ -0,0 +1,263 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// ── Env (lazy env.* access in shared helpers) ───────────────────────────────+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';+process.env.JWT_SECRET ||= 'test-secret-persist';+process.env.UPSTASH_REDIS_REST_URL ||= 'https://redis.test';+process.env.UPSTASH_REDIS_REST_TOKEN ||= 'redis-token';+process.env.S3_PUBLIC_DOMAIN ||= 'https://cdn.test';+process.env.S3_BUCKET ||= 'test-bucket';++// ── SSRF guard (DNS resolution breaks on fake test hostnames) ───────────────+vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => {+ const mod = await importOriginal();+ const { SsrfBlockedError } = mod;+ return {+ ...mod,+ assertSafePublicUrl: vi.fn(async (url, opts = {}) => {+ const parsed = new URL(url);+ if (parsed.protocol === 'http:' && !opts.allowHttp)+ throw new SsrfBlockedError('http:// not allowed — use https://');+ if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')+ throw new SsrfBlockedError('host resolves to a blocked range');+ return parsed;+ }),+ };+});++// ── DB (no Postgres in unit tests) ──────────────────────────────────────────+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));++// ── Rate limits ─────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 3600000 })),+ mcp3dStatus: vi.fn(async () => ({ success: true })),+ mcpInspect: vi.fn(async () => ({ success: true })),+ mcpOptimize: vi.fn(async () => ({ success: true })),+ mcpIp: vi.fn(async () => ({ success: true })),+ mcpUser: vi.fn(async () => ({ success: true })),+ mcpValidate: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '203.0.113.9'),+}));++// ── Usage (no DB) ───────────────────────────────────────────────────────────+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++// ── Object storage ──────────────────────────────────────────────────────────+const r2State = { put: vi.fn(async () => {}) };+vi.mock('../../api/_lib/r2.js', () => ({+ putObject: (...a) => r2State.put(...a),+ headObject: vi.fn(async () => null),+ publicUrl: (key) => `https://cdn.test/${key}`,+ presignGet: vi.fn(async ({ key }) => `https://cdn.test/signed/${key}`),+}));++// ── GLB inspection (avoid parsing a real binary in unit tests) ──────────────+const glbState = { valid: true };+vi.mock('../../api/_lib/glb-inspect.js', () => ({+ isValidGlbHeader: () => glbState.valid,+ inspectGlb: () => ({+ isRigged: false,+ meshCount: 1,+ animationCount: 0,+ skinCount: 0,+ skeletonJointCount: 0,+ nodeCount: 1,+ generator: 'test',+ }),+}));++// ── Avatar service (DB-backed CRUD) ─────────────────────────────────────────+const avState = { avatar: null };+const createAvatar = vi.fn(async ({ input }) => ({+ id: 'avatar-uuid-0001',+ slug: input.slug,+ name: input.name,+ visibility: input.visibility,+ size_bytes: input.size_bytes,+ source: input.source,+ model_url: input.visibility === 'private' ? null : `https://cdn.test/u/user-1/${input.slug}.glb`,+}));+vi.mock('../../api/_lib/avatars.js', () => ({+ createAvatar,+ storageKeyFor: ({ userId, slug }) => `u/${userId}/${slug}/x.glb`,+ getAvatar: vi.fn(async () => avState.avatar),+ getAvatarBySlug: vi.fn(async () => avState.avatar),+ searchPublicAvatars: vi.fn(async () => ({ avatars: [] })),+ listAvatars: vi.fn(async () => ({ avatars: [] })),+ resolveAvatarUrl: vi.fn(async () => ({ url: 'https://cdn.test/m.glb', cdn: true })),+ deleteAvatar: vi.fn(async () => true),+}));++// ── Render layer (mock the chromium pipeline; keep resolveRenderParams real) ─+const renderState = {+ fn: vi.fn(async ({ params }) => ({+ cached: false,+ key: 'renders/avatar-uuid-0001/abc.png',+ imageUrl: 'https://cdn.test/renders/avatar-uuid-0001/abc.png',+ buffer: Buffer.from([0x89]),+ contentType: `image/${params.format}`,+ })),+};+vi.mock('../../api/_lib/avatar-render.js', async (importOriginal) => {+ const mod = await importOriginal();+ return { ...mod, renderAvatarImage: (...a) => renderState.fn(...a) };+});++// ── Global fetch (save_avatar copies the provider GLB) ──────────────────────+vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ ok: true,+ status: 200,+ headers: { get: () => '512' },+ arrayBuffer: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]).buffer,+ })),+);++const { toolDefs: studioDefs } = await import('../../api/_mcp3d/tools/studio.js');+const { toolDefs: avatarDefs } = await import('../../api/_mcp/tools/avatars.js');+const { TOOL_CATALOG: studioCatalog } = await import('../../api/_mcp3d/catalog.js');+const { TOOL_CATALOG: mainCatalog } = await import('../../api/_mcp/catalog.js');++const studioTool = (name) => studioDefs.find((d) => d.name === name);+const avatarTool = (name) => avatarDefs.find((d) => d.name === name);++beforeEach(() => {+ r2State.put.mockClear();+ createAvatar.mockClear();+ renderState.fn.mockClear();+ glbState.valid = true;+ avState.avatar = null;+});++describe('catalog assembly', () => {+ it('lists save_avatar on the 3D Studio server', () => {+ expect(studioCatalog.map((t) => t.name)).toContain('save_avatar');+ });+ it('lists render_avatar_image on the main server', () => {+ expect(mainCatalog.map((t) => t.name)).toContain('render_avatar_image');+ });+ it('keeps each tool on its own server (save on 3D Studio, render on main)', () => {+ expect(mainCatalog.map((t) => t.name)).not.toContain('save_avatar');+ expect(studioCatalog.map((t) => t.name)).not.toContain('render_avatar_image');+ });+});++describe('save_avatar', () => {+ const AUTH = { userId: 'user-1', scope: 'avatars:write', source: 'session' };++ it('persists a public GLB as a durable avatar (happy path)', async () => {+ const r = await studioTool('save_avatar').handler(+ { glb_url: 'https://cdn.test/gen.glb', name: 'My Hero', visibility: 'unlisted' },+ AUTH,+ );+ // Copied into our own storage under the caller's namespace.+ expect(r2State.put).toHaveBeenCalledTimes(1);+ expect(r2State.put.mock.calls[0][0].key).toMatch(/^u\/user-1\//);+ // Registered as a studio-sourced avatar owned by the caller.+ expect(createAvatar).toHaveBeenCalledTimes(1);+ expect(createAvatar.mock.calls[0][0].userId).toBe('user-1');+ expect(createAvatar.mock.calls[0][0].input.source).toBe('studio');+ expect(createAvatar.mock.calls[0][0].input.visibility).toBe('unlisted');+ // Returns the bridge fields.+ expect(r.structuredContent).toMatchObject({+ avatar_id: 'avatar-uuid-0001',+ slug: expect.stringMatching(/^studio-/),+ model_url: expect.stringContaining('https://cdn.test/'),+ view_url: 'https://three.ws/discover/avatar/avatar-uuid-0001',+ });+ expect(r.isError).toBeUndefined();+ });++ it('rejects an unauthenticated (pay-per-call) caller with a sign-in error', async () => {+ const r = await studioTool('save_avatar').handler(+ { glb_url: 'https://cdn.test/gen.glb', name: 'My Hero' },+ { userId: null, scope: '', source: 'x402' },+ );+ expect(r.isError).toBe(true);+ expect(r.structuredContent.status).toBe('sign_in_required');+ expect(r2State.put).not.toHaveBeenCalled();+ expect(createAvatar).not.toHaveBeenCalled();+ });++ it('rejects a non-public glb_url (SSRF guard)', async () => {+ const r = await studioTool('save_avatar').handler(+ { glb_url: 'http://localhost/secret.glb', name: 'Hero' },+ AUTH,+ );+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/public https url/i);+ expect(r2State.put).not.toHaveBeenCalled();+ expect(createAvatar).not.toHaveBeenCalled();+ });++ it('rejects a URL that is not a valid GLB', async () => {+ glbState.valid = false;+ const r = await studioTool('save_avatar').handler(+ { glb_url: 'https://cdn.test/not-a-model.glb', name: 'Hero' },+ AUTH,+ );+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/valid GLB/i);+ expect(createAvatar).not.toHaveBeenCalled();+ });+});++describe('render_avatar_image', () => {+ const AUTH = { userId: 'user-1', scope: 'avatars:read', source: 'session' };++ it('renders a stored avatar and returns the image URL (happy path)', async () => {+ avState.avatar = {+ id: 'avatar-uuid-0001',+ name: 'Hero',+ visibility: 'public',+ updated_at: '2026-01-01T00:00:00Z',+ model_url: 'https://cdn.test/m.glb',+ };+ const r = await avatarTool('render_avatar_image').handler(+ { avatar_id: 'avatar-uuid-0001', scene: 'portrait' },+ AUTH,+ );+ expect(renderState.fn).toHaveBeenCalledTimes(1);+ // Renders from the resolved (signed/public) URL, awaiting the upload so the URL is live.+ expect(renderState.fn.mock.calls[0][0].awaitUpload).toBe(true);+ expect(renderState.fn.mock.calls[0][0].params.scene).toBe('portrait');+ expect(r.structuredContent).toEqual({+ image_url: 'https://cdn.test/renders/avatar-uuid-0001/abc.png',+ scene: 'portrait',+ cached: false,+ });+ expect(r.isError).toBeUndefined();+ });++ it('rejects an unknown pose without invoking the render pipeline', async () => {+ avState.avatar = {+ id: 'avatar-uuid-0001',+ name: 'Hero',+ visibility: 'public',+ updated_at: '2026-01-01T00:00:00Z',+ model_url: 'https://cdn.test/m.glb',+ };+ const r = await avatarTool('render_avatar_image').handler(+ { avatar_id: 'avatar-uuid-0001', pose: 'definitely-not-a-pose' },+ AUTH,+ );+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/unknown pose/i);+ expect(renderState.fn).not.toHaveBeenCalled();+ });++ it('reports a missing / inaccessible avatar as not found', async () => {+ avState.avatar = null;+ await expect(+ avatarTool('render_avatar_image').handler({ avatar_id: 'avatar-uuid-9999' }, AUTH),+ ).rejects.toThrow(/not found/i);+ expect(renderState.fn).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/mcp-embed.test.js b/tests/api/mcp-embed.test.jsnew file mode 100644index 000000000..25879e1df--- /dev/null+++ b/tests/api/mcp-embed.test.js@@ -0,0 +1,232 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++// ── Env (before any lazy env.* access) ──────────────────────────────────────+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';+process.env.JWT_SECRET ||= 'test-secret-embed';+process.env.UPSTASH_REDIS_REST_URL ||= 'https://redis.test';+process.env.UPSTASH_REDIS_REST_TOKEN ||= 'redis-token';++// ── Auth ────────────────────────────────────────────────────────────────────+const authState = { extracted: null, bearer: null };+vi.mock('../../api/_lib/auth.js', () => ({+ extractBearer: vi.fn(() => authState.extracted),+ authenticateBearer: vi.fn(async () => authState.bearer),+ hasScope: vi.fn((granted, required) => {+ const g = new Set((granted || '').split(/\s+/).filter(Boolean));+ return required.split(/\s+/).every((s) => g.has(s));+ }),+}));++// ── DB — the embed tool issues one SELECT per call; queue the row(s). ────────+const sqlState = { queue: [], calls: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: Array.isArray(strings) ? strings.join('?') : String(strings), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++// ── Rate limits ──────────────────────────────────────────────────────────────+const ok = { success: true, reset: Date.now() + 60000 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpIp: vi.fn(async () => ok),+ mcpUser: vi.fn(async () => ok),+ mcpValidate: vi.fn(async () => ok),+ mcpInspect: vi.fn(async () => ({ success: true })),+ mcpOptimize: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '203.0.113.7'),+}));++// ── Usage ─────────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++// ── Pump pricing (embed tool is free → null price) ──────────────────────────+vi.mock('../../api/_lib/pump-pricing.js', () => ({+ priceFor: vi.fn(() => null),+ findActiveSubscription: vi.fn(async () => null),+ resolveBillingMint: vi.fn(() => null),+ x402AmountForTool: vi.fn(() => null),+}));++// ── On-chain resolver ────────────────────────────────────────────────────────+const onchainState = { result: { name: 'Onchain Hero' } };+vi.mock('../../api/_lib/onchain.js', () => ({+ resolveOnChainAgent: vi.fn(async () => onchainState.result),+ // Minimal chain table: only Base (8453) is needed by the tests.+ SERVER_CHAIN_META: { 8453: { name: 'Base', short: 'BASE', testnet: false } },+}));++// ── Embed policy (iframe surface enabled by default) ─────────────────────────+const policyState = { policy: null };+vi.mock('../../api/_lib/embed-policy.js', () => ({+ readEmbedPolicy: vi.fn(async () => policyState.policy),+}));++// ── Infra ────────────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));++// ── Import handler AFTER mocks ───────────────────────────────────────────────+const { default: handler } = await import('../../api/mcp.js');++// ── HTTP harness ─────────────────────────────────────────────────────────────+function makeReq({ method = 'POST', url = '/api/mcp', headers = {}, body = null } = {}) {+ const base = body !== null ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = { host: 'three.ws', ...(body !== null ? { 'content-type': 'application/json' } : {}), ...headers };+ return base;+}+function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { if (chunk !== undefined) this.body += String(chunk); this.writableEnded = true; },+ };+}+async function invoke(reqOpts = {}) {+ const res = makeRes();+ await handler(makeReq(reqOpts), res);+ let parsed = null;+ try { parsed = res.body ? JSON.parse(res.body) : null; } catch { parsed = res.body; }+ return { res, status: res.statusCode, body: parsed };+}+function call(args, extraHeaders = {}) {+ return {+ body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_embed_code', arguments: args } },+ headers: { authorization: 'Bearer valid-token', ...extraHeaders },+ };+}++const FULL_AUTH = { userId: 'user-1', scope: 'avatars:read', source: 'oauth' };+const AGENT_ID = '11111111-1111-4111-8111-111111111111';+const CREATION_ID = '22222222-2222-4222-8222-222222222222';++beforeEach(() => {+ authState.extracted = 'valid-token';+ authState.bearer = FULL_AUTH;+ sqlState.queue = [];+ sqlState.calls = [];+ onchainState.result = { name: 'Onchain Hero' };+ policyState.policy = null;+});++// ── Catalog assembly ─────────────────────────────────────────────────────────+describe('catalog', () => {+ it('tools/list advertises get_embed_code', async () => {+ const { body } = await invoke({+ body: { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} },+ headers: { authorization: 'Bearer valid-token' },+ });+ const names = body.result.tools.map((t) => t.name);+ expect(names).toContain('get_embed_code');+ });+});++// ── Agent embed ──────────────────────────────────────────────────────────────+describe('agent embed', () => {+ it('returns a public agent embed snippet with the /embed URL and dimensions', async () => {+ sqlState.queue = [[{ id: AGENT_ID, user_id: 'someone-else', name: 'Nova', is_public: true }]];++ const { body } = await invoke(call({ agent_id: AGENT_ID, width: 640, height: 480 }));++ expect(body.error).toBeUndefined();+ const sc = body.result.structuredContent;+ expect(sc.ok).toBe(true);+ expect(sc.embed_html).toContain(`https://three.ws/agent/${AGENT_ID}/embed`);+ expect(sc.embed_html).toContain('width="640"');+ expect(sc.embed_html).toContain('height="480"');+ expect(sc.share_url).toBe(`https://three.ws/agent/${AGENT_ID}`);+ expect(sc.oembed_url).toContain('/api/oembed?url=');+ expect(sc.thumbnail_url).toBe(`https://three.ws/api/agent/${AGENT_ID}/og`);+ // Live-preview artifact for HTML-rendering clients.+ const resource = body.result.content.find((c) => c.type === 'resource');+ expect(resource.resource.mimeType).toBe('text/html');+ expect(resource.resource.text).toContain('<iframe');+ });++ it('clamps an out-of-range width instead of erroring', async () => {+ sqlState.queue = [[{ id: AGENT_ID, user_id: 'user-1', name: 'Nova', is_public: true }]];+ const { body } = await invoke(call({ agent_id: AGENT_ID, width: 99999 }));+ expect(body.error).toBeUndefined();+ expect(body.result.structuredContent.width).toBe(1920);+ expect(body.result.structuredContent.embed_html).toContain('width="1920"');+ });++ it('rejects a private agent embed for a non-owner with a designed error', async () => {+ sqlState.queue = [[{ id: AGENT_ID, user_id: 'owner-9', name: 'Secret', is_public: false }]];++ const { body } = await invoke(call({ agent_id: AGENT_ID }));++ expect(body.error).toBeUndefined(); // designed isError result, not a JSON-RPC fault+ expect(body.result.isError).toBe(true);+ expect(body.result.structuredContent.ok).toBe(false);+ expect(body.result.structuredContent.reason).toBe('private');+ expect(body.result.content[0].text).toMatch(/public|unlisted/i);+ });++ it('lets the owner embed their own private agent', async () => {+ sqlState.queue = [[{ id: AGENT_ID, user_id: 'user-1', name: 'Mine', is_public: false }]];+ const { body } = await invoke(call({ agent_id: AGENT_ID }));+ expect(body.result.structuredContent.ok).toBe(true);+ expect(body.result.structuredContent.embed_html).toContain('/embed');+ });+});++// ── On-chain agent embed ─────────────────────────────────────────────────────+describe('on-chain agent embed', () => {+ it('returns an on-chain agent embed with the /a/<chain>/<id>/embed URL', async () => {+ const { body } = await invoke(call({ chain_id: 8453, onchain_agent_id: '42' }));+ const sc = body.result.structuredContent;+ expect(sc.ok).toBe(true);+ expect(sc.embed_html).toContain('https://three.ws/a/8453/42/embed');+ expect(sc.share_url).toBe('https://three.ws/a/8453/42');+ expect(sc.thumbnail_url).toBe('https://three.ws/api/a-og?chain=8453&id=42');+ });+});++// ── Forge creation embed ─────────────────────────────────────────────────────+describe('forge creation embed', () => {+ it('returns a forge embed snippet for a finished creation', async () => {+ sqlState.queue = [[{ id: CREATION_ID, status: 'done', glb_url: 'https://cdn.test/m.glb' }]];+ const { body } = await invoke(call({ creation_id: CREATION_ID, height: 540 }));+ const sc = body.result.structuredContent;+ expect(sc.ok).toBe(true);+ expect(sc.embed_html).toContain(`https://three.ws/forge?share=${CREATION_ID}`);+ expect(sc.embed_html).toContain('height="540"');+ expect(sc.share_url).toBe(`https://three.ws/forge/share/${CREATION_ID}`);+ expect(sc.oembed_url).toBeNull();+ });++ it('rejects a still-generating creation with a designed error', async () => {+ sqlState.queue = [[{ id: CREATION_ID, status: 'generating', glb_url: null }]];+ const { body } = await invoke(call({ creation_id: CREATION_ID }));+ expect(body.result.isError).toBe(true);+ expect(body.result.structuredContent.reason).toBe('not_ready');+ });+});++// ── Target validation ────────────────────────────────────────────────────────+describe('target validation', () => {+ it('rejects when no target is provided', async () => {+ const { body } = await invoke(call({}));+ expect(body.error.code).toBe(-32602);+ expect(body.error.message).toMatch(/exactly one target/i);+ });++ it('rejects when more than one target is provided', async () => {+ const { body } = await invoke(call({ agent_id: AGENT_ID, creation_id: CREATION_ID }));+ expect(body.error.code).toBe(-32602);+ expect(body.error.message).toMatch(/exactly one target/i);+ });+});diff --git a/tests/api/mcp-memory.test.js b/tests/api/mcp-memory.test.jsnew file mode 100644index 000000000..9e76a01e5--- /dev/null+++ b/tests/api/mcp-memory.test.js@@ -0,0 +1,346 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++// ── Env vars (must be set before any lazy env.* access) ──────────────────+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';+process.env.JWT_SECRET ||= 'test-secret-mcp-memory';+process.env.UPSTASH_REDIS_REST_URL ||= 'https://redis.test';+process.env.UPSTASH_REDIS_REST_TOKEN ||= 'redis-token';++// ── Auth ──────────────────────────────────────────────────────────────────+const authState = { extracted: null, bearer: null };++vi.mock('../../api/_lib/auth.js', () => ({+ extractBearer: vi.fn(() => authState.extracted),+ authenticateBearer: vi.fn(async () => authState.bearer),+ hasScope: vi.fn((granted, required) => {+ const g = new Set((granted || '').split(/\s+/).filter(Boolean));+ return required.split(/\s+/).every((s) => g.has(s));+ }),+}));++// ── DB ────────────────────────────────────────────────────────────────────+// Each sql`...` call shifts the next queued result, so a test queues one result+// per query the handler will run, in order.+const sqlState = { queue: [], calls: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++// ── Rate limits ───────────────────────────────────────────────────────────+const rlState = {+ mcpIp: { success: true, reset: Date.now() + 60000 },+ mcpUser: { success: true, reset: Date.now() + 60000 },+};+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpIp: vi.fn(async () => rlState.mcpIp),+ mcpUser: vi.fn(async () => rlState.mcpUser),+ mcpValidate: vi.fn(async () => ({ success: true })),+ mcpInspect: vi.fn(async () => ({ success: true })),+ mcpOptimize: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '203.0.113.1'),+}));++// ── Usage ─────────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++// ── x402 (memory tools are free; keep the surface inert) ────────────────────+class MockX402Error extends Error {+ constructor(code, message, status = 402) {+ super(message);+ this.code = code;+ this.status = status;+ }+}+vi.mock('../../api/_lib/x402-spec.js', () => ({+ X402Error: MockX402Error,+ X402_VERSION: 2,+ paymentRequirements: vi.fn(() => [{ scheme: 'exact', network: 'eip155:8453', amount: '1000' }]),+ bazaarExtension: vi.fn(() => ({})),+ verifyPayment: vi.fn(async () => {+ throw new MockX402Error('invalid_payment', 'payment rejected', 402);+ }),+ settlePayment: vi.fn(async () => ({ success: true })),+ encodePaymentResponseHeader: vi.fn(() => 'settlement-b64'),+ send402: vi.fn(),+ build402Body: vi.fn(({ resourceUrl, accepts } = {}) => ({+ x402Version: 2,+ resource: { url: resourceUrl },+ accepts: Array.isArray(accepts) ? accepts : [accepts],+ })),+ resolveResourceUrl: vi.fn((req, path) => `https://app.test${path}`),+}));++// ── Pump pricing (memory tools are unpriced → free) ─────────────────────────+vi.mock('../../api/_lib/pump-pricing.js', () => ({+ priceFor: vi.fn(() => null),+ findActiveSubscription: vi.fn(async () => null),+ resolveBillingMint: vi.fn(() => null),+ x402AmountForTool: vi.fn(() => null),+}));++// ── Sibling tool deps (only needed so the catalog's imports resolve) ─────────+vi.mock('../../api/_lib/avatars.js', () => ({+ listAvatars: vi.fn(async () => ({ avatars: [] })),+ getAvatar: vi.fn(async () => null),+ getAvatarBySlug: vi.fn(async () => null),+ searchPublicAvatars: vi.fn(async () => ({ avatars: [] })),+ resolveAvatarUrl: vi.fn(async () => ({ url: 'https://cdn.test/model.glb' })),+ deleteAvatar: vi.fn(async () => true),+}));+class MockFetchModelError extends Error {}+vi.mock('../../api/_lib/fetch-model.js', () => ({+ FetchModelError: MockFetchModelError,+ fetchModel: vi.fn(async () => ({ bytes: new Uint8Array(4), url: 'x', filename: 'm.glb' })),+}));+vi.mock('gltf-validator', () => ({ validateBytes: vi.fn(async () => ({ issues: {} })) }));+vi.mock('../../api/_lib/solana-attestations.js', () => ({+ crawlAgentAttestations: vi.fn(async () => {}),+ KIND_MAP: {},+}));+vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({+ pumpfunMcp: {+ recentClaims: vi.fn(async () => ({ ok: true, data: [] })),+ tokenIntel: vi.fn(async () => ({ ok: true, data: {} })),+ creatorIntel: vi.fn(async () => ({ ok: true, data: {} })),+ graduations: vi.fn(async () => ({ ok: true, data: [] })),+ },+ pumpfunBotEnabled: vi.fn(() => false),+}));+vi.mock('../../api/_lib/model-inspect.js', () => ({+ inspectModel: vi.fn(async () => ({ counts: {}, textures: [], extensionsUsed: [] })),+ suggestOptimizations: vi.fn(() => []),+}));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));++// ── Import handler AFTER mocks ─────────────────────────────────────────────+const { default: handler } = await import('../../api/mcp.js');++// ── Test helpers ───────────────────────────────────────────────────────────+function makeReq({ method = 'POST', url = '/api/mcp', headers = {}, body = null } = {}) {+ const base =+ body !== null ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = {+ host: 'app.test',+ ...(body !== null ? { 'content-type': 'application/json' } : {}),+ ...headers,+ };+ return base;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += String(chunk);+ this.writableEnded = true;+ },+ };+}++async function call(name, args, { scope = 'memory:read memory:write' } = {}) {+ authState.extracted = 'valid-token';+ authState.bearer = { userId: 'user-1', scope, source: 'oauth' };+ const req = makeReq({+ body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },+ headers: { authorization: 'Bearer valid-token' },+ });+ const res = makeRes();+ await handler(req, res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++const AGENT_ID = '11111111-1111-4111-8111-111111111111';+const MEM_ID = '22222222-2222-4222-8222-222222222222';++beforeEach(() => {+ authState.extracted = null;+ authState.bearer = null;+ sqlState.queue = [];+ sqlState.calls = [];+ rlState.mcpIp = { success: true, reset: Date.now() + 60000 };+ rlState.mcpUser = { success: true, reset: Date.now() + 60000 };+});++// ── Catalog wiring ──────────────────────────────────────────────────────────+describe('catalog', () => {+ it('exposes remember, recall, and forget', async () => {+ const m = await import('../../api/_mcp/catalog.js');+ const names = m.TOOL_CATALOG.map((t) => t.name);+ expect(names).toContain('remember');+ expect(names).toContain('recall');+ expect(names).toContain('forget');+ });+});++// ── Scope enforcement ───────────────────────────────────────────────────────+describe('scope enforcement', () => {+ it('remember without memory:write returns -32002', async () => {+ const { body } = await call(+ 'remember',+ { agent_id: AGENT_ID, content: 'hi' },+ { scope: '' },+ );+ expect(body.error.code).toBe(-32002);+ expect(body.error.message).toMatch(/memory:write/);+ });++ it('recall without memory:read returns -32002', async () => {+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'hi' }, { scope: '' });+ expect(body.error.code).toBe(-32002);+ expect(body.error.message).toMatch(/memory:read/);+ });+});++// ── Schema validation ───────────────────────────────────────────────────────+describe('schema validation', () => {+ it('remember rejects a non-uuid agent_id with -32602', async () => {+ const { body } = await call('remember', { agent_id: 'not-a-uuid', content: 'hi' });+ expect(body.error.code).toBe(-32602);+ });++ it('remember rejects missing content with -32602', async () => {+ const { body } = await call('remember', { agent_id: AGENT_ID });+ expect(body.error.code).toBe(-32602);+ });++ it('recall rejects an over-long query with -32602', async () => {+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'x'.repeat(1001) });+ expect(body.error.code).toBe(-32602);+ });+});++// ── Ownership ────────────────────────────────────────────────────────────────+describe('ownership', () => {+ it('remember on an agent the caller does not own returns a designed error', async () => {+ sqlState.queue = [[]]; // ownsAgent → no matching row+ const { body } = await call('remember', { agent_id: AGENT_ID, content: 'secret' });+ expect(body.error).toBeUndefined();+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toMatch(/sign in with three\.ws oauth/i);+ });++ it('recall on a foreign agent returns a designed error, not stored rows', async () => {+ sqlState.queue = [[{ user_id: 'someone-else' }]];+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'anything' });+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toMatch(/account-scoped/i);+ });++ it('forget refuses a memory owned by another user', async () => {+ sqlState.queue = [[{ id: MEM_ID, user_id: 'someone-else' }]];+ const { body } = await call('forget', { memory_id: MEM_ID });+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toMatch(/does not belong to you/i);+ });+});++// ── Empty recall ─────────────────────────────────────────────────────────────+describe('empty recall', () => {+ it('returns an empty list with a helpful message when nothing is stored', async () => {+ sqlState.queue = [+ [{ user_id: 'user-1' }], // ownsAgent+ [], // candidates+ ];+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'pumpfun' });+ expect(body.result.isError).toBeUndefined();+ expect(body.result.structuredContent.memories).toEqual([]);+ expect(body.result.content[0].text).toMatch(/no memories stored/i);+ });+});++// ── Happy-path round trip: remember → recall → forget ───────────────────────+describe('round trip', () => {+ it('remembers a memory and echoes the stored row', async () => {+ const stored = {+ id: MEM_ID,+ agent_id: AGENT_ID,+ type: 'project',+ content: 'Ship the memory MCP tools',+ tags: ['mcp'],+ context: {},+ salience: 0.7,+ created_at: '2026-06-08T00:00:00.000Z',+ expires_at: null,+ };+ sqlState.queue = [+ [{ user_id: 'user-1' }], // ownsAgent+ [stored], // INSERT ... RETURNING *+ ];+ const { body } = await call('remember', {+ agent_id: AGENT_ID,+ content: 'Ship the memory MCP tools',+ type: 'project',+ tags: ['mcp'],+ salience: 0.7,+ });+ expect(body.error).toBeUndefined();+ expect(body.result.structuredContent.memory.id).toBe(MEM_ID);+ expect(body.result.structuredContent.memory.type).toBe('project');+ expect(body.result.content[0].text).toContain('Ship the memory MCP tools');+ });++ it('recalls the stored memory ranked first by query relevance', async () => {+ const rows = [+ {+ id: 'mem-unrelated',+ agent_id: AGENT_ID,+ type: 'reference',+ content: 'A note about something else entirely',+ tags: [],+ salience: 0.9,+ created_at: '2026-06-08T00:00:00.000Z',+ expires_at: null,+ },+ {+ id: MEM_ID,+ agent_id: AGENT_ID,+ type: 'project',+ content: 'Ship the memory MCP tools for pumpfun',+ tags: ['mcp', 'pumpfun'],+ salience: 0.5,+ created_at: '2026-06-08T00:00:00.000Z',+ expires_at: null,+ },+ ];+ sqlState.queue = [+ [{ user_id: 'user-1' }], // ownsAgent+ rows, // candidates+ ];+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'pumpfun mcp tools' });+ const mems = body.result.structuredContent.memories;+ expect(mems[0].id).toBe(MEM_ID); // lexical relevance beats the higher-salience unrelated note+ expect(mems[0].score).toBeGreaterThan(mems[1].score);+ });++ it('forgets a memory the caller owns', async () => {+ sqlState.queue = [+ [{ id: MEM_ID, user_id: 'user-1' }], // ownership join+ [], // DELETE+ ];+ const { body } = await call('forget', { memory_id: MEM_ID });+ expect(body.error).toBeUndefined();+ expect(body.result.structuredContent).toEqual({ ok: true, id: MEM_ID });+ expect(body.result.content[0].text).toContain(MEM_ID);+ });+});diff --git a/tests/api/mcp-register-agent.test.js b/tests/api/mcp-register-agent.test.jsnew file mode 100644index 000000000..a124c9cf2--- /dev/null+++ b/tests/api/mcp-register-agent.test.js@@ -0,0 +1,299 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// register_agent / identity_check — the on-chain identity MCP tools. We exercise+// the tool handlers directly (importing toolDefs) with the registry + Granite+// layers mocked, so the test asserts orchestration/contract shape without any+// real Solana RPC, watsonx call, or DB.++// ── DB ──────────────────────────────────────────────────────────────────────+const sqlState = { queue: [], calls: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++// ── Rate limits ───────────────────────────────────────────────────────────────+const rl = { success: true, reset: Date.now() + 60000 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ agentRegister: vi.fn(async () => rl),+ identityCheckIp: vi.fn(async () => rl),+ agentDelegate: vi.fn(async () => rl),+ },+ clientIp: vi.fn(() => '203.0.113.1'),+}));++// ── Agent delegate (call_agent, unused here) ──────────────────────────────────+vi.mock('../../api/_lib/agent-delegate.js', () => ({+ runAgentDelegation: vi.fn(async () => ({ response: 'ok' })),+ AgentNotFoundError: class extends Error {},+}));++// ── three-brand (agentHomeUrl) ────────────────────────────────────────────────+vi.mock('../../api/_lib/three-brand.js', () => ({+ agentHomeUrl: (id) => `https://app.test/agent/${id}`,+}));++// ── Solana collection ─────────────────────────────────────────────────────────+const collectionState = { mainnet: null, devnet: null };+vi.mock('../../api/_lib/solana-collection.js', () => ({+ getAgentCollection: vi.fn((net) => collectionState[net] || null),+}));++// ── On-chain deploy / registry ────────────────────────────────────────────────+const chainState = {+ secret: 'AUTHORITY_SECRET',+ deploy: null,+ register: null,+ buildThrows: false,+};+vi.mock('../../api/_lib/onchain-deploy.js', () => ({+ authoritySecret: vi.fn(() => chainState.secret),+ buildAuthorityUmi: vi.fn(() => {+ if (chainState.buildThrows) throw new Error('authority/funder secret is not a valid base58 keypair');+ return { umi: {}, authoritySigner: { publicKey: { toString: () => 'AUTH_PUBKEY' } } };+ }),+ loadCollectionAsset: vi.fn(async () => null),+ deployAgentOnce: vi.fn(async () => chainState.deploy),+ registerAgentOnce: vi.fn(async () => chainState.register),+ explorerUrl: vi.fn((addr, net) => `https://solscan.io/account/${addr}${net === 'devnet' ? '?cluster=devnet' : ''}`),+}));++// ── Identity integrity (Granite) ──────────────────────────────────────────────+const identityState = { result: null };+vi.mock('../../api/_lib/identity-integrity.js', () => ({+ checkIdentityIntegrity: vi.fn(async () => identityState.result),+}));++// ── Import AFTER mocks ────────────────────────────────────────────────────────+const { toolDefs } = await import('../../api/_mcp/tools/agents.js');+const onchain = await import('../../api/_lib/onchain-deploy.js');++const TOOLS = Object.fromEntries(toolDefs.map((t) => [t.name, t]));+const UID = 'user-1';+const AGENT_ID = '11111111-1111-4111-8111-111111111111';++function ownerAuth(scope) {+ return { userId: UID, scope: scope ?? 'agents:read agents:write', source: 'oauth' };+}++// Parse a tool result's structuredContent (the contract payload).+function out(result) {+ return result.structuredContent;+}++beforeEach(() => {+ sqlState.queue = [];+ sqlState.calls = [];+ collectionState.mainnet = null;+ collectionState.devnet = null;+ chainState.secret = 'AUTHORITY_SECRET';+ chainState.deploy = null;+ chainState.register = null;+ chainState.buildThrows = false;+ identityState.result = null;+ vi.clearAllMocks();+});++// ── Catalog assembly ──────────────────────────────────────────────────────────+describe('catalog assembly', () => {+ it('exposes register_agent (agents:write) and identity_check (agents:read)', () => {+ expect(TOOLS.register_agent).toBeDefined();+ expect(TOOLS.register_agent.scope).toBe('agents:write');+ expect(TOOLS.identity_check).toBeDefined();+ expect(TOOLS.identity_check.scope).toBe('agents:read');+ });+});++// ── register_agent ────────────────────────────────────────────────────────────+describe('register_agent', () => {+ it('rejects an x402/null-user caller with a designed sign-in state', async () => {+ const res = await TOOLS.register_agent.handler(+ { agent_id: AGENT_ID, chain: 'solana' },+ { userId: null, rateKey: 'x402:wallet', scope: '', source: 'x402' },+ );+ expect(res.isError).toBe(true);+ expect(out(res).status).toBe('sign_in_required');+ // Never touched the DB or the chain.+ expect(sqlState.calls.length).toBe(0);+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ });++ it('rejects registering another account’s agent (ownership check)', async () => {+ sqlState.queue.push([{ id: AGENT_ID, user_id: 'someone-else', name: 'X', meta: {} }]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID }, ownerAuth());+ expect(res.isError).toBe(true);+ expect(out(res).status).toBe('forbidden');+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ expect(onchain.registerAgentOnce).not.toHaveBeenCalled();+ });++ it('is idempotent: already-registered agent returns existing identity, no re-mint', async () => {+ sqlState.queue.push([+ {+ id: AGENT_ID,+ user_id: UID,+ name: 'Granite Oracle',+ meta: {+ sol_mint_address: 'ASSET1',+ agent_registry: {+ identity_pda: 'PDA1',+ asset: 'ASSET1',+ registration_uri: 'https://ipfs/reg.json',+ tx_hash: 'SIG1',+ },+ },+ },+ ]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID, chain: 'solana' }, ownerAuth());+ const o = out(res);+ expect(res.isError).toBeUndefined();+ expect(o.status).toBe('already_registered');+ expect(o.agent_pda).toBe('PDA1');+ expect(o.network).toBe('mainnet');+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ expect(onchain.registerAgentOnce).not.toHaveBeenCalled();+ });++ it('chain:base returns a designed needs_wallet_signature payload (no fabricated tx)', async () => {+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Base Bot', description: 'on base', meta: {} }]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID, chain: 'base' }, ownerAuth());+ const o = out(res);+ expect(res.isError).toBeUndefined();+ expect(o.status).toBe('needs_wallet_signature');+ expect(o.chain).toBe('base');+ expect(o.chain_id).toBe(8453);+ expect(o.continue_url).toBe(`https://app.test/agent/${AGENT_ID}?deploy=base`);+ // Prepared ERC-8004 registration JSON, fully formed.+ expect(o.registration_json.name).toBe('Base Bot');+ expect(o.registration_json.type).toMatch(/eip-8004/);+ expect(o.registration_json.registrations[0].agentRegistry).toMatch(/^eip155:8453:/);+ // No on-chain side effects.+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ });++ it('returns a designed not-configured error when the Solana authority is unset', async () => {+ chainState.secret = null;+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Solo', meta: {} }]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID, chain: 'solana' }, ownerAuth());+ const o = out(res);+ expect(res.isError).toBe(true);+ expect(o.status).toBe('registration_not_configured');+ // Crucially, no fabricated PDA.+ expect(o.agent_pda).toBeUndefined();+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ });++ it('mints + registers a fresh agent on Solana and returns the real PDA', async () => {+ chainState.deploy = {+ asset: 'ASSETX',+ registry: {+ asset: 'ASSETX',+ identityPda: 'PDAX',+ registrationUri: 'https://ipfs/regx.json',+ signature: 'SIGX',+ alreadyRegistered: false,+ },+ };+ sqlState.queue.push([{ id: AGENT_ID, user_id: UID, name: 'Fresh', description: 'new', meta: {} }]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID, chain: 'solana' }, ownerAuth());+ const o = out(res);+ expect(res.isError).toBeUndefined();+ expect(o.status).toBe('registered');+ expect(o.agent_pda).toBe('PDAX');+ expect(o.asset).toBe('ASSETX');+ expect(o.registration_uri).toBe('https://ipfs/regx.json');+ expect(o.tx_hash).toBe('SIGX');+ expect(o.explorer_url).toContain('PDAX');+ expect(onchain.deployAgentOnce).toHaveBeenCalledOnce();+ expect(onchain.registerAgentOnce).not.toHaveBeenCalled();+ });++ it('enrols an already-minted (but unregistered) agent without re-minting', async () => {+ chainState.register = {+ asset: 'ASSETM',+ identityPda: 'PDAM',+ registrationUri: 'https://ipfs/regm.json',+ signature: 'SIGM',+ alreadyRegistered: false,+ };+ sqlState.queue.push([+ { id: AGENT_ID, user_id: UID, name: 'Minted', meta: { sol_mint_address: 'ASSETM' } },+ ]);+ const res = await TOOLS.register_agent.handler({ agent_id: AGENT_ID, chain: 'solana' }, ownerAuth());+ const o = out(res);+ expect(o.status).toBe('registered');+ expect(o.agent_pda).toBe('PDAM');+ expect(onchain.deployAgentOnce).not.toHaveBeenCalled();+ expect(onchain.registerAgentOnce).toHaveBeenCalledOnce();+ });++ it('rejects a non-uuid agent_id with a validation error', async () => {+ const res = await TOOLS.register_agent.handler({ agent_id: 'not-a-uuid' }, ownerAuth());+ expect(res.isError).toBe(true);+ expect(out(res).status).toBe('validation_error');+ });+});++// ── identity_check ────────────────────────────────────────────────────────────+describe('identity_check', () => {+ it('returns a block verdict with similar agents and reasons (name + description)', async () => {+ identityState.result = {+ configured: true,+ status: 'block',+ uniqueness: 0.02,+ reasons: ['This identity is 98% similar to an existing public agent ("Granite Oracle").'],+ similar: [{ id: 'a2', name: 'Granite Oracle', score: 0.98, owned: false, public: true }],+ duplicateOf: { id: 'a2', name: 'Granite Oracle', score: 0.98 },+ guardian: null,+ model: { embed: 'granite-embed', guardian: null },+ };+ const res = await TOOLS.identity_check.handler(+ { name: 'The Granite Oracle 🔮', description: 'A wise on-chain oracle.' },+ ownerAuth(),+ );+ const o = out(res);+ expect(o.verdict).toBe('block');+ expect(o.similar_agents).toHaveLength(1);+ expect(o.similar_agents[0].name).toBe('Granite Oracle');+ expect(o.reasons[0]).toMatch(/similar/);+ expect(o.duplicate_of.id).toBe('a2');+ });++ it('screens an existing agent by id (resolves its stored identity)', async () => {+ sqlState.queue.push([+ { id: AGENT_ID, name: 'My Agent', description: 'mine', persona_tone_tags: ['calm'], user_id: UID, is_public: false },+ ]);+ identityState.result = {+ configured: true,+ status: 'clear',+ uniqueness: 0.6,+ reasons: ['Identity is distinct.'],+ similar: [],+ duplicateOf: null,+ guardian: null,+ model: { embed: 'granite-embed', guardian: null },+ };+ const res = await TOOLS.identity_check.handler({ agent_id: AGENT_ID }, ownerAuth());+ const o = out(res);+ expect(o.verdict).toBe('clear');+ expect(o.agent_id).toBe(AGENT_ID);+ });++ it('rejects screening another account’s private agent', async () => {+ sqlState.queue.push([+ { id: AGENT_ID, name: 'Secret', description: 'hidden', persona_tone_tags: [], user_id: 'other', is_public: false },+ ]);+ const res = await TOOLS.identity_check.handler({ agent_id: AGENT_ID }, ownerAuth());+ expect(res.isError).toBe(true);+ expect(out(res).status).toBe('forbidden');+ });++ it('requires a name/description or agent_id', async () => {+ const res = await TOOLS.identity_check.handler({}, ownerAuth());+ expect(res.isError).toBe(true);+ expect(out(res).status).toBe('validation_error');+ });+});