Skip to content

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

embedd

nirholas110d1637840a
diff --git a/a-embed.html b/a-embed.html
new file mode 100644
index 000000000..e309fa72b
--- /dev/null
+++ b/a-embed.html
@@ -0,0 +1,284 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Embedded 3D agent avatar — on-chain." />
+ <meta name="robots" content="noindex" />
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ width: 100%;
+ background: transparent;
+ overflow: hidden;
+ font-family: system-ui, sans-serif;
+ }
+ #stage {
+ position: absolute;
+ inset: 0;
+ }
+ #stage canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #stage .gui-wrap,
+ #stage .gui-toggle,
+ #stage .annotation-canvas {
+ display: none !important;
+ }
+ #stage .model-info {
+ display: none !important;
+ }
+ #name-plate {
+ position: absolute;
+ left: 12px;
+ bottom: 10px;
+ z-index: 2;
+ pointer-events: none;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.04em;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+ }
+ #chain-plate {
+ position: absolute;
+ right: 12px;
+ bottom: 10px;
+ z-index: 2;
+ pointer-events: none;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.4);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+ }
+ #open-link {
+ position: absolute;
+ right: 12px;
+ top: 10px;
+ z-index: 3;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.05em;
+ text-decoration: none;
+ padding: 4px 8px;
+ border-radius: 4px;
+ background: rgba(0, 0, 0, 0.35);
+ backdrop-filter: blur(4px);
+ }
+ #open-link:hover {
+ color: rgba(255, 255, 255, 0.9);
+ background: rgba(0, 0, 0, 0.5);
+ }
+ #loading {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 12px;
+ }
+ #loading::after {
+ content: '';
+ width: 18px;
+ height: 18px;
+ margin-left: 8px;
+ border: 2px solid rgba(255, 255, 255, 0.15);
+ border-top-color: rgba(255, 255, 255, 0.5);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ #error,
+ #blocked {
+ position: absolute;
+ inset: 0;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 12px;
+ padding: 1rem;
+ text-align: center;
+ flex-direction: column;
+ gap: 6px;
+ }
+ #blocked a {
+ color: rgba(180, 200, 255, 0.9);
+ text-decoration: none;
+ }
+ body.bg-dark {
+ background: #0b0d10;
+ }
+ body.bg-light {
+ background: #f5f5f5;
+ }
+ body.bg-light #name-plate {
+ color: rgba(0, 0, 0, 0.65);
+ text-shadow: none;
+ }
+ body.bg-light #chain-plate {
+ color: rgba(0, 0, 0, 0.45);
+ text-shadow: none;
+ }
+ body.bg-light #open-link {
+ color: rgba(0, 0, 0, 0.65);
+ background: rgba(255, 255, 255, 0.6);
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage"></div>
+ <div id="name-plate"></div>
+ <div id="chain-plate"></div>
+ <a id="open-link" target="_blank" rel="noopener" style="display: none">Open ↗</a>
+ <div id="loading">Loading agent</div>
+ <div id="error"></div>
+ <div id="blocked"></div>
+
+ <script type="module">
+ import { Viewer } from './src/viewer.js';
+ import {
+ parseAgentRef,
+ resolveOnchainAgent,
+ toManifest,
+ resolveUrlCandidates,
+ isEmbedAllowed,
+ toPublicUrl,
+ } from './src/erc8004/resolver.js';
+
+ const params = new URL(location.href).searchParams;
+ const bg = params.get('bg') || 'transparent';
+ if (bg === 'dark') document.body.classList.add('bg-dark');
+ if (bg === 'light') document.body.classList.add('bg-light');
+
+ const plateOn = params.get('name') !== '0';
+ const chainOn = params.get('chain-plate') !== '0';
+ const openLinkOn = params.get('open-link') !== '0';
+
+ // URL: /a/:chainId/:agentId/embed
+ const ref = parseAgentRef(location.pathname);
+
+ function showError(msg) {
+ document.getElementById('loading').style.display = 'none';
+ const el = document.getElementById('error');
+ el.textContent = msg || 'Could not load agent';
+ el.style.display = 'flex';
+ try {
+ parent?.postMessage({ __agent: true, type: 'error', message: msg }, '*');
+ } catch {}
+ }
+
+ function showBlocked(host) {
+ document.getElementById('loading').style.display = 'none';
+ const el = document.getElementById('blocked');
+ const link = ref ? toPublicUrl(ref) : '/';
+ el.innerHTML = `
+ <div>This agent does not allow embedding on <b>${host || 'this site'}</b>.</div>
+ <a href="${link}" target="_blank" rel="noopener">Open on 3dagent.vercel.app ↗</a>
+ `;
+ el.style.display = 'flex';
+ try {
+ parent?.postMessage({ __agent: true, type: 'blocked', host }, '*');
+ } catch {}
+ }
+
+ // Best-effort parent hostname — referrer is the only cross-origin signal.
+ function getParentHost() {
+ try {
+ if (window.parent === window) return location.hostname;
+ if (document.referrer) return new URL(document.referrer).hostname;
+ } catch {}
+ return '';
+ }
+
+ // Try a list of candidate URLs; resolve with the first that succeeds.
+ async function loadWithFallback(viewer, uris) {
+ let lastErr;
+ for (const u of uris) {
+ try {
+ await viewer.load(u, '', new Map());
+ return u;
+ } catch (err) {
+ lastErr = err;
+ console.warn('[a-embed] load failed, trying next:', u, err?.message);
+ }
+ }
+ throw lastErr || new Error('All candidate URLs failed');
+ }
+
+ async function main() {
+ if (!ref) return showError('Invalid agent URL');
+
+ const resolved = await resolveOnchainAgent(ref);
+ if (resolved.error && !resolved.glbUrl && !resolved.image) {
+ return showError(`On-chain resolve failed: ${resolved.error}`);
+ }
+
+ // Embed-policy gate
+ const parentHost = getParentHost();
+ const policy = resolved.metadata?.embedPolicy;
+ if (policy && !isEmbedAllowed(policy, parentHost)) {
+ return showBlocked(parentHost);
+ }
+
+ if (plateOn) {
+ document.getElementById('name-plate').textContent = resolved.name;
+ }
+ if (chainOn) {
+ const chainName = resolved.chain?.name || `chain ${ref.chainId}`;
+ document.getElementById('chain-plate').textContent =
+ `${chainName} · #${ref.agentId}`;
+ }
+ if (openLinkOn) {
+ const ol = document.getElementById('open-link');
+ ol.href = toPublicUrl(ref);
+ ol.style.display = 'inline-block';
+ }
+
+ const bodyURI = resolved.glbUrl || resolved.image;
+ if (!bodyURI) return showError('Agent has no 3D body');
+
+ const stage = document.getElementById('stage');
+ const viewer = new Viewer(stage, { kiosk: true });
+ if (bg === 'transparent') {
+ viewer.renderer?.setClearAlpha(0);
+ if (viewer.scene) viewer.scene.background = null;
+ }
+
+ const candidates = resolveUrlCandidates(bodyURI);
+ await loadWithFallback(viewer, candidates);
+
+ document.getElementById('loading').style.display = 'none';
+
+ parent?.postMessage(
+ {
+ __agent: true,
+ type: 'ready',
+ caip: resolved.caip,
+ chainId: ref.chainId,
+ agentId: ref.agentId,
+ name: resolved.name,
+ owner: resolved.onchain.owner,
+ },
+ '*',
+ );
+ }
+
+ main().catch((err) => {
+ console.error('[a-embed]', err);
+ showError(err.message || 'Could not load agent');
+ });
+ </script>
+ </body>
+</html>
diff --git a/api/_lib/env.js b/api/_lib/env.js
index dff452095..c6052e9a9 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -42,4 +42,11 @@ export const env = {
// is hit; keeping these optional so unrelated endpoints still respond when unset.
get AVATURN_API_KEY() { return opt('AVATURN_API_KEY'); },
get AVATURN_API_URL() { return trimSlash(opt('AVATURN_API_URL', 'https://api.avaturn.me')); },
+
+ // Etherscan V2 — unified multichain explorer API (one key, all chains).
+ // Used by api/cron/erc8004-crawl.js to index ERC-8004 Registered events.
+ get ETHERSCAN_API_KEY() { return opt('ETHERSCAN_API_KEY'); },
+
+ // Secret for Vercel Cron Authorization header (crons call with `Bearer $CRON_SECRET`).
+ get CRON_SECRET() { return opt('CRON_SECRET'); },
};
diff --git a/api/_lib/erc8004-chains.js b/api/_lib/erc8004-chains.js
new file mode 100644
index 000000000..6a4481afe
--- /dev/null
+++ b/api/_lib/erc8004-chains.js
@@ -0,0 +1,54 @@
+/**
+ * Server-side mirror of src/erc8004/abi.js REGISTRY_DEPLOYMENTS + chain metadata.
+ * Duplicated (rather than importing from src/) so the serverless bundle stays
+ * lean and the crawler is insulated from client-only imports in src/erc8004/.
+ *
+ * Identity Registry deployment: CREATE2-deterministic, same address on every
+ * chain — one address per network class (mainnet vs. testnet).
+ */
+
+export const IDENTITY_REGISTRY_MAINNET = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
+export const IDENTITY_REGISTRY_TESTNET = '0x8004A818BFB912233c491871b3d84c89A494BD9e';
+
+/**
+ * Chains where the ERC-8004 Identity Registry is deployed. Ordered so the most
+ * active chains are crawled first when the cron has a time budget.
+ */
+export const CHAINS = [
+ { id: 8453, name: 'Base', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://basescan.org' },
+ { id: 42161, name: 'Arbitrum One', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://arbiscan.io' },
+ { id: 56, name: 'BNB Chain', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://bscscan.com' },
+ { id: 1, name: 'Ethereum', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://etherscan.io' },
+ { id: 10, name: 'Optimism', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://optimistic.etherscan.io' },
+ { id: 137, name: 'Polygon', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://polygonscan.com' },
+ { id: 43114, name: 'Avalanche', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://snowtrace.io' },
+ { id: 100, name: 'Gnosis', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://gnosisscan.io' },
+ { id: 250, name: 'Fantom', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://ftmscan.com' },
+ { id: 42220, name: 'Celo', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://celoscan.io' },
+ { id: 59144, name: 'Linea', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://lineascan.build' },
+ { id: 534352, name: 'Scroll', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://scrollscan.com' },
+ { id: 5000, name: 'Mantle', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://explorer.mantle.xyz' },
+ { id: 324, name: 'zkSync Era', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://explorer.zksync.io' },
+ { id: 1284, name: 'Moonbeam', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://moonbeam.moonscan.io' },
+ { id: 97, name: 'BSC Testnet', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://testnet.bscscan.com' },
+ { id: 84532, name: 'Base Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.basescan.org' },
+ { id: 421614, name: 'Arbitrum Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.arbiscan.io' },
+ { id: 11155111, name: 'Ethereum Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.etherscan.io' },
+ { id: 11155420, name: 'Optimism Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia-optimism.etherscan.io' },
+ { id: 80002, name: 'Polygon Amoy', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://amoy.polygonscan.com' },
+ { id: 43113, name: 'Avalanche Fuji', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://testnet.snowtrace.io' },
+];
+
+export const CHAIN_BY_ID = Object.fromEntries(CHAINS.map((c) => [c.id, c]));
+
+export function tokenExplorerUrl(chainId, agentId) {
+ const c = CHAIN_BY_ID[chainId];
+ if (!c) return null;
+ return `${c.explorer}/token/${c.registry}?a=${agentId}`;
+}
+
+export function addressExplorerUrl(chainId, address) {
+ const c = CHAIN_BY_ID[chainId];
+ if (!c) return null;
+ return `${c.explorer}/address/${address}`;
+}
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
new file mode 100644
index 000000000..b79937fa4
--- /dev/null
+++ b/api/_lib/onchain.js
@@ -0,0 +1,262 @@
+/**
+ * Server-side on-chain agent resolver.
+ *
+ * Mirrors the client-side resolver in src/erc8004/resolve-avatar.js but keeps
+ * its own lightweight chain-meta table so serverless cold-starts stay cheap.
+ * Only identity-registry `tokenURI` + `ownerOf` reads happen here; manifest
+ * bodies (GLB, images) are pointed to, never fetched.
+ *
+ * Canonical deployment addresses are the CREATE2-deterministic ones from
+ * src/erc8004/abi.js — kept in sync by hand.
+ */
+
+import { JsonRpcProvider, Contract, getAddress } from 'ethers';
+
+const IDENTITY_ABI = [
+ 'function tokenURI(uint256 tokenId) external view returns (string)',
+ 'function ownerOf(uint256 tokenId) external view returns (address)',
+ 'function getAgentWallet(uint256 agentId) external view returns (address)',
+];
+
+const MAINNET = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
+const TESTNET = '0x8004A818BFB912233c491871b3d84c89A494BD9e';
+
+// Tight table — only what the server needs. Public RPCs with low-latency
+// global edges; no API keys required.
+export const SERVER_CHAIN_META = {
+ // Mainnets
+ 1: { name: 'Ethereum', short: 'ETH', rpc: 'https://eth.llamarpc.com', explorer: 'https://etherscan.io', registry: MAINNET, testnet: false },
+ 10: { name: 'Optimism', short: 'OP', rpc: 'https://mainnet.optimism.io', explorer: 'https://optimistic.etherscan.io', registry: MAINNET, testnet: false },
+ 56: { name: 'BNB Chain', short: 'BSC', rpc: 'https://bsc-dataseed.bnbchain.org', explorer: 'https://bscscan.com', registry: MAINNET, testnet: false },
+ 100: { name: 'Gnosis', short: 'GNO', rpc: 'https://rpc.gnosischain.com', explorer: 'https://gnosisscan.io', registry: MAINNET, testnet: false },
+ 137: { name: 'Polygon', short: 'MATIC', rpc: 'https://polygon-rpc.com', explorer: 'https://polygonscan.com', registry: MAINNET, testnet: false },
+ 250: { name: 'Fantom', short: 'FTM', rpc: 'https://rpc.ftm.tools', explorer: 'https://ftmscan.com', registry: MAINNET, testnet: false },
+ 324: { name: 'zkSync Era', short: 'zkSync', rpc: 'https://mainnet.era.zksync.io', explorer: 'https://explorer.zksync.io', registry: MAINNET, testnet: false },
+ 1284: { name: 'Moonbeam', short: 'GLMR', rpc: 'https://rpc.api.moonbeam.network', explorer: 'https://moonscan.io', registry: MAINNET, testnet: false },
+ 5000: { name: 'Mantle', short: 'MNT', rpc: 'https://rpc.mantle.xyz', explorer: 'https://explorer.mantle.xyz', registry: MAINNET, testnet: false },
+ 8453: { name: 'Base', short: 'BASE', rpc: 'https://mainnet.base.org', explorer: 'https://basescan.org', registry: MAINNET, testnet: false },
+ 42161: { name: 'Arbitrum One', short: 'ARB', rpc: 'https://arb1.arbitrum.io/rpc', explorer: 'https://arbiscan.io', registry: MAINNET, testnet: false },
+ 42220: { name: 'Celo', short: 'CELO', rpc: 'https://forno.celo.org', explorer: 'https://celoscan.io', registry: MAINNET, testnet: false },
+ 43114: { name: 'Avalanche', short: 'AVAX', rpc: 'https://api.avax.network/ext/bc/C/rpc', explorer: 'https://snowtrace.io', registry: MAINNET, testnet: false },
+ 59144: { name: 'Linea', short: 'LINEA', rpc: 'https://rpc.linea.build', explorer: 'https://lineascan.build', registry: MAINNET, testnet: false },
+ 534352: { name: 'Scroll', short: 'SCR', rpc: 'https://rpc.scroll.io', explorer: 'https://scrollscan.com', registry: MAINNET, testnet: false },
+
+ // Testnets
+ 97: { name: 'BSC Testnet', short: 'tBSC', rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545', explorer: 'https://testnet.bscscan.com', registry: TESTNET, testnet: true },
+ 11155111: { name: 'Ethereum Sepolia', short: 'SEP', rpc: 'https://rpc.sepolia.org', explorer: 'https://sepolia.etherscan.io', registry: TESTNET, testnet: true },
+ 84532: { name: 'Base Sepolia', short: 'baseSep', rpc: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org', registry: TESTNET, testnet: true },
+ 421614: { name: 'Arbitrum Sepolia', short: 'arbSep', rpc: 'https://sepolia-rollup.arbitrum.io/rpc', explorer: 'https://sepolia.arbiscan.io', registry: TESTNET, testnet: true },
+ 11155420: { name: 'Optimism Sepolia', short: 'opSep', rpc: 'https://sepolia.optimism.io', explorer: 'https://sepolia-optimism.etherscan.io', registry: TESTNET, testnet: true },
+ 80002: { name: 'Polygon Amoy', short: 'Amoy', rpc: 'https://rpc-amoy.polygon.technology', explorer: 'https://amoy.polygonscan.com', registry: TESTNET, testnet: true },
+ 43113: { name: 'Avalanche Fuji', short: 'Fuji', rpc: 'https://api.avax-test.network/ext/bc/C/rpc', explorer: 'https://testnet.snowtrace.io', registry: TESTNET, testnet: true },
+};
+
+const IPFS_GATEWAY = 'https://ipfs.io/ipfs/';
+const AR_GATEWAY = 'https://arweave.net/';
+
+/** @param {string} uri */
+export function resolveURI(uri) {
+ if (!uri) return '';
+ if (uri.startsWith('ipfs://')) return IPFS_GATEWAY + uri.slice(7);
+ if (uri.startsWith('ar://')) return AR_GATEWAY + uri.slice(5);
+ return uri;
+}
+
+/**
+ * Resolve an on-chain agent.
+ * @param {{ chainId: number, agentId: string|number, fetchManifest?: boolean, timeoutMs?: number }} p
+ * @returns {Promise<{
+ * chainId: number,
+ * chainName: string,
+ * chainShort: string,
+ * testnet: boolean,
+ * explorer: string,
+ * registry: string,
+ * agentId: string,
+ * owner: string|null,
+ * wallet: string|null,
+ * tokenURI: string|null,
+ * tokenURIResolved: string|null,
+ * manifest: object|null,
+ * name: string|null,
+ * description: string|null,
+ * image: string|null,
+ * bodyURI: string|null,
+ * error?: string,
+ * }>}
+ */
+export async function resolveOnChainAgent({
+ chainId,
+ agentId,
+ fetchManifest = true,
+ timeoutMs = 4000,
+}) {
+ const meta = SERVER_CHAIN_META[chainId];
+ if (!meta) {
+ return _emptyResult(chainId, agentId, 'unsupported_chain');
+ }
+
+ const base = {
+ chainId,
+ chainName: meta.name,
+ chainShort: meta.short,
+ testnet: meta.testnet,
+ explorer: meta.explorer,
+ registry: meta.registry,
+ agentId: String(agentId),
+ owner: null,
+ wallet: null,
+ tokenURI: null,
+ tokenURIResolved: null,
+ manifest: null,
+ name: null,
+ description: null,
+ image: null,
+ bodyURI: null,
+ };
+
+ let provider;
+ try {
+ provider = new JsonRpcProvider(meta.rpc, chainId, { staticNetwork: true });
+ } catch (err) {
+ return { ...base, error: `rpc_init: ${err.message}` };
+ }
+
+ const registry = new Contract(meta.registry, IDENTITY_ABI, provider);
+ const idBig = BigInt(agentId);
+
+ try {
+ const [uri, owner] = await Promise.all([
+ _withTimeout(registry.tokenURI(idBig), timeoutMs),
+ _withTimeout(registry.ownerOf(idBig).catch(() => null), timeoutMs),
+ ]);
+ base.tokenURI = uri || null;
+ base.tokenURIResolved = uri ? resolveURI(uri) : null;
+ base.owner = owner ? _safeAddress(owner) : null;
+ } catch (err) {
+ return { ...base, error: `chain_read: ${err.message}` };
+ }
+
+ if (fetchManifest && base.tokenURIResolved) {
+ try {
+ const res = await _withTimeout(fetch(base.tokenURIResolved), timeoutMs);
+ if (res.ok) {
+ const json = await res.json();
+ base.manifest = json;
+ base.name = _pickName(json, agentId);
+ base.description = _pickDescription(json);
+ base.image = _pickImage(json);
+ base.bodyURI = _pickBody(json);
+ }
+ } catch (err) {
+ base.error = `manifest_fetch: ${err.message}`;
+ }
+ }
+
+ return base;
+}
+
+function _emptyResult(chainId, agentId, error) {
+ return {
+ chainId,
+ chainName: `Chain ${chainId}`,
+ chainShort: String(chainId),
+ testnet: false,
+ explorer: '',
+ registry: '',
+ agentId: String(agentId),
+ owner: null,
+ wallet: null,
+ tokenURI: null,
+ tokenURIResolved: null,
+ manifest: null,
+ name: null,
+ description: null,
+ image: null,
+ bodyURI: null,
+ error,
+ };
+}
+
+function _safeAddress(addr) {
+ try {
+ return getAddress(addr);
+ } catch {
+ return null;
+ }
+}
+
+function _pickName(json, agentId) {
+ if (json?.name) return String(json.name);
+ const reg = json?.registrations?.[0];
+ if (reg?.agentId) return `Agent #${reg.agentId}`;
+ return `Agent #${agentId}`;
+}
+
+function _pickDescription(json) {
+ if (typeof json?.description === 'string') return json.description;
+ if (typeof json?.summary === 'string') return json.summary;
+ return null;
+}
+
+function _pickImage(json) {
+ const candidates = [json?.image, json?.thumbnail, json?.body?.thumbnail, json?.avatar];
+ for (const c of candidates) {
+ if (typeof c === 'string' && c) return resolveURI(c);
+ }
+ return null;
+}
+
+function _pickBody(json) {
+ const candidates = [
+ json?.body?.uri,
+ json?.body?.url,
+ json?.body,
+ json?.avatar,
+ json?.model,
+ json?.image,
+ ];
+ for (const c of candidates) {
+ if (typeof c === 'string' && c) return resolveURI(c);
+ }
+ return null;
+}
+
+function _withTimeout(promise, ms) {
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error(`timeout ${ms}ms`)), ms);
+ Promise.resolve(promise).then(
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
+ );
+ });
+}
+
+/** Short address form 0xabc…def */
+export function shortenAddr(addr) {
+ if (!addr || typeof addr !== 'string') return '';
+ if (addr.length <= 10) return addr;
+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
+}
+
+/** Build explorer deep link. */
+export function explorerLink(chainId, kind, value) {
+ const meta = SERVER_CHAIN_META[chainId];
+ if (!meta?.explorer || !value) return '';
+ switch (kind) {
+ case 'tx':
+ return `${meta.explorer}/tx/${value}`;
+ case 'address':
+ return `${meta.explorer}/address/${value}`;
+ case 'token':
+ return `${meta.explorer}/token/${value}`;
+ default:
+ return meta.explorer;
+ }
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 9ff5a22e8..2bd0b7937 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -341,3 +341,45 @@ create table if not exists widget_views (
create index if not exists widget_views_widget_time
on widget_views(widget_id, created_at desc);
+
+-- ── erc8004_agents_index — crawled directory of every on-chain agent ───────
+-- Populated by api/cron/erc8004-crawl.js from Etherscan V2 getLogs across every
+-- chain in REGISTRY_DEPLOYMENTS. Metadata fields are lazily filled from each
+-- agent's agentURI JSON. `has_3d` = true when services[name=avatar] is set.
+create table if not exists erc8004_agents_index (
+ chain_id integer not null,
+ agent_id text not null, -- uint256 as decimal string
+ owner text not null, -- 0x-lowercase
+ registry text not null, -- 0x-lowercase contract addr
+ agent_uri text,
+ name text,
+ description text,
+ image text, -- 2D thumbnail URL
+ glb_url text, -- services[name=avatar] endpoint
+ services jsonb not null default '[]'::jsonb,
+ x402_support boolean not null default false,
+ has_3d boolean not null default false,
+ active boolean not null default true,
+ registered_block bigint,
+ registered_tx text,
+ registered_at timestamptz,
+ last_metadata_at timestamptz,
+ metadata_error text,
+ last_seen_at timestamptz not null default now(),
+ primary key (chain_id, agent_id)
+);
+
+create index if not exists erc8004_agents_has3d_time
+ on erc8004_agents_index(has_3d, registered_at desc) where active;
+create index if not exists erc8004_agents_chain_time
+ on erc8004_agents_index(chain_id, registered_at desc) where active;
+create index if not exists erc8004_agents_owner
+ on erc8004_agents_index(owner) where active;
+create index if not exists erc8004_agents_metadata_stale
+ on erc8004_agents_index(last_metadata_at nulls first);
+
+create table if not exists erc8004_crawl_cursor (
+ chain_id integer primary key,
+ last_block bigint not null default 0,
+ updated_at timestamptz not null default now()
+);
diff --git a/api/a-og.js b/api/a-og.js
new file mode 100644
index 000000000..5ed7713b9
--- /dev/null
+++ b/api/a-og.js
@@ -0,0 +1,120 @@
+/**
+ * On-chain agent OG image
+ * -----------------------
+ * GET /api/a-og?chain=<chainId>&id=<agentId>
+ *
+ * Happy path: 302 to the manifest's image (IPFS/HTTPS thumbnail).
+ * Fallback: server-rendered SVG card — Slack, X, Discord, Farcaster all
+ * accept image/svg+xml for OG images, so we avoid canvas/sharp at edge.
+ */
+
+import { cors, wrap, error } from './_lib/http.js';
+import { resolveOnChainAgent, shortenAddr } from './_lib/onchain.js';
+
+const CACHE_CARD = 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400';
+const CACHE_REDIR = 'public, max-age=600, s-maxage=3600';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const chainId = Number(url.searchParams.get('chain'));
+ const agentId = url.searchParams.get('id');
+
+ if (!Number.isFinite(chainId) || !agentId) {
+ return error(res, 400, 'invalid_request', 'chain and id required');
+ }
+
+ const agent = await resolveOnChainAgent({ chainId, agentId });
+
+ // If the manifest has a raw image URL, redirect so the crawler caches
+ // an actual PNG/JPG (better social preview than SVG text card).
+ // Only redirect for http(s) URLs — crawlers won't follow ipfs:// or
+ // gateway URLs from random hosts reliably.
+ if (agent.image && /^https?:\/\//i.test(agent.image)) {
+ res.statusCode = 302;
+ res.setHeader('location', agent.image);
+ res.setHeader('cache-control', CACHE_REDIR);
+ res.end();
+ return;
+ }
+
+ const status = agent.error && !agent.name ? 404 : 200;
+ res.statusCode = status;
+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
+ res.setHeader('cache-control', status === 200 ? CACHE_CARD : 'public, max-age=60');
+ res.end(renderCard(agent));
+});
+
+function renderCard(agent) {
+ const name = agent.name || `Agent #${agent.agentId}`;
+ const desc = agent.description || 'An embodied 3D agent on-chain.';
+ const chain = agent.chainName || `Chain ${agent.chainId}`;
+ const short = agent.chainShort || '';
+ const owner = agent.owner ? shortenAddr(agent.owner) : '';
+ const testnet = agent.testnet;
+ const accent = testnet ? '#f59e0b' : '#8b5cf6';
+
+ const safeName = escapeXml(truncate(name, 48));
+ const safeDesc = escapeXml(truncate(desc, 160));
+ const safeChain = escapeXml(truncate(chain, 20));
+ const safeShort = escapeXml(truncate(short, 12));
+ const safeOwner = escapeXml(owner);
+ const safeId = escapeXml(agent.agentId);
+
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${safeName} on ${safeChain}">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0" stop-color="#0b0d10"/>
+ <stop offset="1" stop-color="#141722"/>
+ </linearGradient>
+ <radialGradient id="glow" cx="0.85" cy="0.15" r="0.6">
+ <stop offset="0" stop-color="${accent}" stop-opacity="0.35"/>
+ <stop offset="1" stop-color="${accent}" stop-opacity="0"/>
+ </radialGradient>
+ </defs>
+ <rect width="1200" height="630" fill="url(#bg)"/>
+ <rect width="1200" height="630" fill="url(#glow)"/>
+
+ <!-- Chain badge top-left -->
+ <g transform="translate(80, 70)">
+ <rect x="0" y="0" rx="18" ry="18" width="${Math.max(140, safeChain.length * 13 + 40)}" height="40" fill="rgba(255,255,255,0.06)" stroke="${accent}" stroke-opacity="0.5" stroke-width="1"/>
+ <circle cx="24" cy="20" r="6" fill="${accent}"/>
+ <text x="42" y="27" fill="#e5e5e5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="16" font-weight="500" letter-spacing="0.5">${safeChain}${testnet ? ' · TESTNET' : ''}</text>
+ </g>
+
+ <!-- Agent # top-right -->
+ <text x="1120" y="95" text-anchor="end" fill="rgba(229,229,229,0.4)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="22" font-weight="400" letter-spacing="2">#${safeId}</text>
+
+ <!-- Main title -->
+ <text x="80" y="340" fill="#f5f5f5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="84" font-weight="300" letter-spacing="-3">${safeName}</text>
+
+ <!-- Description -->
+ <text x="80" y="410" fill="rgba(229,229,229,0.6)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="28" font-weight="400">${safeDesc}</text>
+
+ <!-- Owner footer -->
+ ${safeOwner ? `<text x="80" y="495" fill="rgba(229,229,229,0.35)" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="20">owner ${safeOwner}</text>` : ''}
+
+ <!-- Brand footer -->
+ <g transform="translate(80, 550)">
+ <circle cx="12" cy="12" r="10" fill="none" stroke="${accent}" stroke-width="2"/>
+ <text x="34" y="19" fill="rgba(229,229,229,0.45)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="18" font-weight="500" letter-spacing="3">3D AGENT</text>
+ </g>
+ <text x="1120" y="569" text-anchor="end" fill="rgba(229,229,229,0.3)" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="16">eip155:${agent.chainId}${safeShort ? ` · ${safeShort}` : ''}</text>
+</svg>`;
+}
+
+function truncate(s, n) {
+ s = String(s || '');
+ return s.length <= n ? s : s.slice(0, n - 1) + '…';
+}
+
+function escapeXml(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
+}
diff --git a/api/a-page.js b/api/a-page.js
new file mode 100644
index 000000000..4b3e251ae
--- /dev/null
+++ b/api/a-page.js
@@ -0,0 +1,193 @@
+/**
+ * Server-rendered metadata page for on-chain agents
+ * -------------------------------------------------
+ * GET /api/a-page?chain=<chainId>&id=<agentId>
+ *
+ * Wired to /a/:chainId/:agentId via vercel.json. Returns an HTML page with
+ * Open Graph + Twitter Player Card + oEmbed discovery + Farcaster Frame tags
+ * so social crawlers get a rich preview. Real browsers run the inline script
+ * and navigate to the SPA viewer.
+ */
+
+import { env } from './_lib/env.js';
+import { cors, wrap } from './_lib/http.js';
+import { resolveOnChainAgent, shortenAddr, SERVER_CHAIN_META } from './_lib/onchain.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const chainId = Number(url.searchParams.get('chain'));
+ const agentId = url.searchParams.get('id');
+
+ if (!Number.isFinite(chainId) || !agentId) {
+ return notFound(res, 'Invalid agent URL');
+ }
+ if (!SERVER_CHAIN_META[chainId]) {
+ return notFound(res, `Chain ${chainId} is not supported`);
+ }
+
+ const agent = await resolveOnChainAgent({ chainId, agentId });
+
+ // Hard 404 only when the on-chain read itself failed (token likely doesn't
+ // exist). Manifest fetch failures still render a card so the link shares.
+ if (agent.error && agent.error.startsWith('chain_read')) {
+ return notFound(res, `Agent #${agentId} not found on ${agent.chainName}`);
+ }
+
+ const origin = env.APP_ORIGIN;
+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;
+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;
+ const viewerUrl = `${origin}/?agent=agent://${chainId}/${agentId}`;
+ const ogUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(agentId)}`;
+ const oembedJs = `${origin}/api/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;
+
+ const title = agent.name || `Agent #${agentId}`;
+ const chainLabel = agent.chainName || `Chain ${chainId}`;
+ const ownerShort = agent.owner ? shortenAddr(agent.owner) : '';
+ const desc =
+ agent.description ||
+ `An embodied 3D agent on ${chainLabel}${ownerShort ? ` · owned by ${ownerShort}` : ''}.`;
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');
+ res.end(
+ renderHtml({
+ title,
+ desc,
+ chainLabel,
+ chainId,
+ agentId,
+ ownerShort,
+ pageUrl,
+ embedUrl,
+ viewerUrl,
+ ogUrl,
+ oembedJs,
+ origin,
+ manifestURI: agent.tokenURI || '',
+ }),
+ );
+});
+
+function notFound(res, reason) {
+ res.statusCode = 404;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60');
+ res.end(
+ `<!doctype html><meta charset="utf-8"><title>Agent not found — 3D Agent</title>
+<style>body{font-family:Inter,system-ui,sans-serif;background:#0a0a0a;color:#e0e0e0;display:grid;place-items:center;min-height:100vh;margin:0}main{text-align:center;padding:2rem;max-width:520px}a{color:#8b5cf6}</style>
+<main><h1>Agent not found</h1><p>${escapeHtml(reason)}</p><p><a href="/explore">Browse all on-chain agents</a> · <a href="/">Open viewer</a></p></main>`,
+ );
+}
+
+function renderHtml(p) {
+ const t = escapeHtml(p.title);
+ const d = escapeHtml(p.desc);
+ const chainL = escapeHtml(p.chainLabel);
+ return `<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <title>${t} · ${chainL} — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
+ <meta name="description" content="${d}">
+ <meta name="theme-color" content="#0a0a0a">
+
+ <meta property="og:type" content="profile">
+ <meta property="og:site_name" content="3D Agent">
+ <meta property="og:title" content="${t}">
+ <meta property="og:description" content="${d}">
+ <meta property="og:url" content="${escapeAttr(p.pageUrl)}">
+ <meta property="og:image" content="${escapeAttr(p.ogUrl)}">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:alt" content="${t} on ${chainL}">
+
+ <meta name="twitter:card" content="player">
+ <meta name="twitter:title" content="${t}">
+ <meta name="twitter:description" content="${d}">
+ <meta name="twitter:image" content="${escapeAttr(p.ogUrl)}">
+ <meta name="twitter:player" content="${escapeAttr(p.embedUrl)}">
+ <meta name="twitter:player:width" content="480">
+ <meta name="twitter:player:height" content="600">
+
+ <!-- Farcaster Frame (vNext) -->
+ <meta property="fc:frame" content="vNext">
+ <meta property="fc:frame:image" content="${escapeAttr(p.ogUrl)}">
+ <meta property="fc:frame:image:aspect_ratio" content="1.91:1">
+ <meta property="fc:frame:button:1" content="View 3D">
+ <meta property="fc:frame:button:1:action" content="link">
+ <meta property="fc:frame:button:1:target" content="${escapeAttr(p.viewerUrl)}">
+ <meta property="fc:frame:button:2" content="Explore">
+ <meta property="fc:frame:button:2:action" content="link">
+ <meta property="fc:frame:button:2:target" content="${escapeAttr(p.origin)}/explore">
+
+ <link rel="canonical" href="${escapeAttr(p.pageUrl)}">
+ <link rel="alternate" type="application/json+oembed" href="${escapeAttr(p.oembedJs)}" title="${t}">
+ <link rel="shortcut icon" href="/favicon.ico">
+
+ <style>
+ html,body{margin:0;padding:0;background:#0a0a0a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%;overflow:hidden}
+ .shell{display:grid;place-items:center;height:100vh;text-align:center;padding:2rem;gap:1rem}
+ .shell a{color:#8b5cf6;text-decoration:none}
+ .shell a:hover{text-decoration:underline}
+ .spinner{width:32px;height:32px;border:2px solid rgba(255,255,255,0.1);border-top-color:#8b5cf6;border-radius:50%;animation:spin 1s linear infinite}
+ @keyframes spin{to{transform:rotate(360deg)}}
+ @media(prefers-reduced-motion:reduce){.spinner{animation:none}}
+ </style>
+</head>
+<body>
+ <noscript>
+ <div class="shell">
+ <h1>${t}</h1>
+ <p>${d}</p>
+ <p><a href="${escapeAttr(p.embedUrl)}">Open 3D viewer</a> · <a href="/explore">Browse agents</a></p>
+ </div>
+ </noscript>
+ <div class="shell" id="loading" aria-live="polite">
+ <div class="spinner" aria-hidden="true"></div>
+ <p>Loading ${t}…</p>
+ </div>
+ <script>
+ (function () {
+ var target = ${JSON.stringify(p.viewerUrl)};
+ try {
+ var u = new URL(window.location.href);
+ if (u.searchParams.get('embed') === '0') return;
+ } catch (e) {}
+ window.location.replace(target);
+ })();
+ </script>
+ <script type="application/ld+json">
+${escapeJsonLd({
+ '@context': 'https://schema.org',
+ '@type': 'Person',
+ name: p.title,
+ description: p.desc,
+ url: p.pageUrl,
+ image: p.ogUrl,
+ identifier: `eip155:${p.chainId}:${p.agentId}`,
+ sameAs: p.manifestURI ? [p.manifestURI] : undefined,
+ provider: { '@type': 'Organization', name: '3D Agent', url: 'https://3dagent.vercel.app' },
+})}
+ </script>
+</body>
+</html>`;
+}
+
+function escapeHtml(s) {
+ return String(s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+function escapeAttr(s) {
+ return escapeHtml(s);
+}
+function escapeJsonLd(obj) {
+ const clean = JSON.parse(JSON.stringify(obj));
+ return JSON.stringify(clean, null, 2).replace(/</g, '\\u003c');
+}
diff --git a/api/agent-oembed.js b/api/agent-oembed.js
index fe52b9ff0..13635783b 100644
--- a/api/agent-oembed.js
+++ b/api/agent-oembed.js
@@ -11,6 +11,7 @@
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';
const WIDTH = 420;
const HEIGHT = 520;
@@ -26,6 +27,9 @@ export default wrap(async (req, res) => {
if (!target) return error(res, 400, 'invalid_request', 'url parameter required');
+ const onchain = extractOnChain(target);
+ if (onchain) return sendOnChain(res, format, onchain);
+
const agentId = extractAgentId(target);
if (!agentId) return error(res, 404, 'not_found', 'url is not a recognised agent url');
@@ -88,6 +92,66 @@ function extractAgentId(target) {
return match ? match[1] : null;
}
+function extractOnChain(target) {
+ let parsed;
+ try { parsed = new URL(target); } catch { return null; }
+
+ const originStr = `${parsed.protocol}//${parsed.host}`;
+ const okOrigin = originStr === env.APP_ORIGIN
+ || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
+ if (!okOrigin) return null;
+
+ const match = parsed.pathname.match(/^\/a\/(\d+)\/(\d+)\/?$/);
+ if (!match) return null;
+ const chainId = Number(match[1]);
+ const agentId = match[2];
+ if (!SERVER_CHAIN_META[chainId]) return null;
+ return { chainId, agentId };
+}
+
+async function sendOnChain(res, format, { chainId, agentId }) {
+ 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 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',
+ provider_name: '3D Agent',
+ 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,
+ };
+
+ res.setHeader('cache-control', 'public, max-age=900');
+
+ if (format === 'xml') {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/xml; charset=utf-8');
+ res.end(toXml(payload));
+ return;
+ }
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json+oembed; charset=utf-8');
+ res.end(JSON.stringify(payload));
+}
+
function toXml(payload) {
const lines = Object.entries(payload).map(([k, v]) =>
` <${k}>${escapeXml(String(v))}</${k}>`
diff --git a/api/cron/erc8004-crawl.js b/api/cron/erc8004-crawl.js
new file mode 100644
index 000000000..d21dc4aef
--- /dev/null
+++ b/api/cron/erc8004-crawl.js
@@ -0,0 +1,255 @@
+/**
+ * ERC-8004 directory crawler — indexes every `Registered` event from every
+ * chain in CHAINS into the `erc8004_agents_index` table, then enriches a
+ * batch of rows with their agentURI metadata (name, image, GLB, services).
+ *
+ * Runs on Vercel Cron every 15 minutes (see vercel.json crons). Also callable
+ * manually via `POST /api/cron/erc8004-crawl` with `Authorization: Bearer
+ * $CRON_SECRET` for on-demand refreshes.
+ *
+ * Flow per chain:
+ * 1. Read last scanned block from erc8004_crawl_cursor.
+ * 2. Etherscan V2 getLogs → Registered events since that block.
+ * 3. Decode agentId (topic1), owner (topic2), agentURI (data) and upsert.
+ * 4. Advance cursor.
+ *
+ * Metadata pass: pick the 20 oldest-metadata rows, fetch JSON, extract
+ * name/description/image/services/has_3d, write back.
+ */
+
+import { id as keccakId, AbiCoder, getAddress } from 'ethers';
+import { sql } from '../_lib/db.js';
+import { cors, error, json, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { CHAINS } from '../_lib/erc8004-chains.js';
+
+const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');
+const ETHERSCAN_BASE = 'https://api.etherscan.io/v2/api';
+const ABI_CODER = AbiCoder.defaultAbiCoder();
+
+// Per-chain log page size. Etherscan V2 caps `offset` at 1000.
+const LOG_PAGE_SIZE = 1000;
+
+// Metadata enrichment per invocation. Keep modest — each fetch hits IPFS/R2.
+const METADATA_BATCH = 25;
+
+// Per-request timeout so one stuck chain can't eat the whole cron budget.
+const FETCH_TIMEOUT_MS = 8_000;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ // Vercel Cron sends `Authorization: Bearer $CRON_SECRET`. Allow GET/POST
+ // from the Vercel cron runner and from a manually-authorized caller.
+ const auth = req.headers['authorization'] || '';
+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+ if (!env.ETHERSCAN_API_KEY) {
+ return error(res, 500, 'missing_env', 'ETHERSCAN_API_KEY not configured');
+ }
+
+ const report = { chains: [], enriched: 0, errors: [] };
+
+ // 1. Crawl logs chain-by-chain.
+ for (const chain of CHAINS) {
+ try {
+ const r = await crawlChain(chain);
+ report.chains.push({ chainId: chain.id, name: chain.name, ...r });
+ } catch (err) {
+ report.errors.push({ chainId: chain.id, error: err.message || String(err) });
+ }
+ }
+
+ // 2. Enrich metadata for the oldest-seen rows.
+ try {
+ report.enriched = await enrichMetadata(METADATA_BATCH);
+ } catch (err) {
+ report.errors.push({ stage: 'metadata', error: err.message || String(err) });
+ }
+
+ return json(res, 200, report);
+});
+
+// ─── Log crawl ───────────────────────────────────────────────────────────
+
+async function crawlChain(chain) {
+ const [cursor] = await sql`
+ SELECT last_block FROM erc8004_crawl_cursor WHERE chain_id = ${chain.id}
+ `;
+ const fromBlock = cursor ? Number(cursor.last_block) + 1 : 0;
+
+ const url = new URL(ETHERSCAN_BASE);
+ url.searchParams.set('chainid', String(chain.id));
+ url.searchParams.set('module', 'logs');
+ url.searchParams.set('action', 'getLogs');
+ url.searchParams.set('address', chain.registry);
+ url.searchParams.set('topic0', REGISTERED_TOPIC);
+ url.searchParams.set('fromBlock', String(fromBlock));
+ url.searchParams.set('toBlock', 'latest');
+ url.searchParams.set('page', '1');
+ url.searchParams.set('offset', String(LOG_PAGE_SIZE));
+ url.searchParams.set('apikey', env.ETHERSCAN_API_KEY);
+
+ const body = await fetchJson(url.toString());
+ // Etherscan returns `status:"1"` with `result:[...]` OR `status:"0"` with
+ // `message:"No records found"` when empty. Anything else is an error.
+ if (body.status === '0' && /no records/i.test(body.message || '')) {
+ return { inserted: 0, lastBlock: fromBlock - 1, fromBlock };
+ }
+ if (body.status !== '1' || !Array.isArray(body.result)) {
+ throw new Error(`etherscan ${chain.id}: ${body.message || 'unknown'} — ${String(body.result).slice(0, 120)}`);
+ }
+
+ let lastBlock = fromBlock - 1;
+ let inserted = 0;
+
+ for (const log of body.result) {
+ try {
+ const agentId = BigInt(log.topics[1]).toString();
+ const ownerHex = '0x' + log.topics[2].slice(-40);
+ const owner = getAddress(ownerHex).toLowerCase();
+ const [agentURI] = ABI_CODER.decode(['string'], log.data);
+ const blockNumber = Number.parseInt(log.blockNumber, 16);
+ const timestamp = Number.parseInt(log.timeStamp, 16);
+ const registeredAt = new Date(timestamp * 1000).toISOString();
+
+ await sql`
+ INSERT INTO erc8004_agents_index
+ (chain_id, agent_id, owner, registry, agent_uri,
+ registered_block, registered_tx, registered_at, last_seen_at)
+ VALUES
+ (${chain.id}, ${agentId}, ${owner}, ${chain.registry.toLowerCase()},
+ ${agentURI || null}, ${blockNumber}, ${log.transactionHash},
+ ${registeredAt}, now())
+ ON CONFLICT (chain_id, agent_id) DO UPDATE SET
+ owner = excluded.owner,
+ agent_uri = COALESCE(excluded.agent_uri, erc8004_agents_index.agent_uri),
+ last_seen_at = now()
+ `;
+ inserted += 1;
+ if (blockNumber > lastBlock) lastBlock = blockNumber;
+ } catch (decodeErr) {
+ // Skip malformed log; continue.
+ console.warn('[crawl] decode failed', chain.id, log.transactionHash, decodeErr.message);
+ }
+ }
+
+ // Update cursor (even on zero inserts — keeps fromBlock monotonic).
+ const newCursor = Math.max(lastBlock, fromBlock - 1);
+ await sql`
+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at)
+ VALUES (${chain.id}, ${newCursor}, now())
+ ON CONFLICT (chain_id) DO UPDATE SET
+ last_block = GREATEST(erc8004_crawl_cursor.last_block, excluded.last_block),
+ updated_at = now()
+ `;
+
+ return { inserted, lastBlock: newCursor, fromBlock };
+}
+
+// ─── Metadata enrichment ─────────────────────────────────────────────────
+
+async function enrichMetadata(limit) {
+ // Rows with no metadata yet, or metadata older than 7d.
+ const rows = await sql`
+ SELECT chain_id, agent_id, agent_uri
+ FROM erc8004_agents_index
+ WHERE agent_uri IS NOT NULL
+ AND (last_metadata_at IS NULL OR last_metadata_at < now() - interval '7 days')
+ ORDER BY last_metadata_at NULLS FIRST, registered_at DESC NULLS LAST
+ LIMIT ${limit}
+ `;
+
+ let done = 0;
+ for (const row of rows) {
+ try {
+ const meta = await fetchAgentMetadata(row.agent_uri);
+ if (!meta) {
+ await sql`
+ UPDATE erc8004_agents_index
+ SET metadata_error = 'fetch failed',
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ continue;
+ }
+ const name = truncate(meta.name || '', 200);
+ const description = truncate(meta.description || '', 1000);
+ const image = resolveGateway(meta.image || '');
+ const services = Array.isArray(meta.services) ? meta.services : [];
+ const avatarSvc = services.find(
+ (s) => String(s?.name || '').toLowerCase() === 'avatar' && s?.endpoint,
+ );
+ const glbUrl = avatarSvc ? resolveGateway(avatarSvc.endpoint) : null;
+ const has3d = !!glbUrl;
+ const active = meta.active !== false;
+ const x402 = !!(meta.x402Support || meta.x402);
+
+ await sql`
+ UPDATE erc8004_agents_index
+ SET name = ${name || null},
+ description = ${description || null},
+ image = ${image || null},
+ glb_url = ${glbUrl},
+ services = ${JSON.stringify(services)}::jsonb,
+ has_3d = ${has3d},
+ active = ${active},
+ x402_support = ${x402},
+ metadata_error = null,
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ done += 1;
+ } catch (err) {
+ await sql`
+ UPDATE erc8004_agents_index
+ SET metadata_error = ${truncate(err.message || String(err), 500)},
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ }
+ }
+ return done;
+}
+
+// ─── Helpers ─────────────────────────────────────────────────────────────
+
+async function fetchJson(url) {
+ const ac = new AbortController();
+ const t = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, { signal: ac.signal });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return await res.json();
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+async function fetchAgentMetadata(uri) {
+ const url = resolveGateway(uri);
+ if (!url) return null;
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+function resolveGateway(uri) {
+ if (!uri || typeof uri !== 'string') return '';
+ if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);
+ if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);
+ if (uri.startsWith('http://') || uri.startsWith('https://')) return uri;
+ return '';
+}
+
+function truncate(s, max) {
+ if (!s) return '';
+ return s.length > max ? s.slice(0, max) : s;
+}
diff --git a/api/explore.js b/api/explore.js
new file mode 100644
index 000000000..5d7ebe697
--- /dev/null
+++ b/api/explore.js
@@ -0,0 +1,104 @@
+/**
+ * GET /api/explore — paginated directory of every ERC-8004 agent we've indexed.
+ *
+ * Query params:
+ * only3d=1 — only rows where has_3d = true
+ * chain=<id> — filter by chainId
+ * q=<text> — name/description substring
+ * cursor=<iso> — registered_at ISO string for pagination (older rows)
+ * limit=<int> — page size, default 24, max 60
+ */
+
+import { sql } from './_lib/db.js';
+import { cors, json, method, wrap, error } from './_lib/http.js';
+import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const only3d = url.searchParams.get('only3d') === '1';
+ const chainId = parseInt(url.searchParams.get('chain') || '', 10);
+ const q = (url.searchParams.get('q') || '').trim().slice(0, 80);
+ const cursor = url.searchParams.get('cursor');
+ const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 60);
+
+ const cursorDate = cursor ? new Date(cursor) : null;
+ if (cursor && isNaN(cursorDate?.getTime())) {
+ return error(res, 400, 'validation_error', 'cursor must be an ISO date');
+ }
+
+ // Filter construction via template fragments kept inline because Neon's
+ // tagged-template driver doesn't compose them the way pg.Client does; a
+ // single query with optional predicates guarded by nulls is clearer.
+ const rows = await sql`
+ SELECT chain_id, agent_id, owner, name, description, image, glb_url,
+ has_3d, x402_support, registered_at, registered_tx,
+ services, agent_uri
+ FROM erc8004_agents_index
+ WHERE active = true
+ AND (${only3d ? true : null}::boolean IS NULL OR has_3d = true)
+ AND (${Number.isFinite(chainId) ? chainId : null}::integer IS NULL OR chain_id = ${Number.isFinite(chainId) ? chainId : null})
+ AND (${q || null}::text IS NULL OR (
+ coalesce(name,'') ILIKE ${'%' + q + '%'}
+ OR coalesce(description,'') ILIKE ${'%' + q + '%'}
+ ))
+ AND (${cursorDate ? cursorDate.toISOString() : null}::timestamptz IS NULL OR registered_at < ${cursorDate ? cursorDate.toISOString() : null}::timestamptz)
+ ORDER BY registered_at DESC NULLS LAST
+ LIMIT ${limit + 1}
+ `;
+
+ const hasMore = rows.length > limit;
+ const page = rows.slice(0, limit);
+
+ const items = page.map((r) => {
+ const chain = CHAIN_BY_ID[r.chain_id];
+ return {
+ chainId: r.chain_id,
+ chainName: chain?.name || `Chain ${r.chain_id}`,
+ chainShortName: chain?.name || `#${r.chain_id}`,
+ agentId: r.agent_id,
+ owner: r.owner,
+ ownerShort: shortAddr(r.owner),
+ name: r.name || `Agent #${r.agent_id}`,
+ description: r.description || '',
+ image: r.image || null,
+ glbUrl: r.glb_url || null,
+ has3d: r.has_3d,
+ x402Support: r.x402_support,
+ registeredAt: r.registered_at,
+ tokenExplorerUrl: tokenExplorerUrl(r.chain_id, r.agent_id),
+ ownerExplorerUrl: addressExplorerUrl(r.chain_id, r.owner),
+ viewerUrl: r.glb_url
+ ? `/#model=${encodeURIComponent(r.glb_url)}`
+ : null,
+ services: (r.services || []).map((s) => ({
+ name: s?.name || null,
+ endpoint: s?.endpoint || null,
+ version: s?.version || null,
+ })),
+ };
+ });
+
+ const nextCursor = hasMore && page.length > 0 ? page[page.length - 1].registered_at : null;
+
+ // Totals (cheap: single bool-filtered count).
+ const [{ total }] = await sql`
+ SELECT count(*)::text as total FROM erc8004_agents_index WHERE active = true
+ `;
+ const [{ total3d }] = await sql`
+ SELECT count(*)::text as total3d FROM erc8004_agents_index WHERE active = true AND has_3d = true
+ `;
+
+ return json(res, 200, {
+ items,
+ nextCursor,
+ totals: { all: Number(total), threeD: Number(total3d) },
+ });
+});
+
+function shortAddr(a) {
+ if (!a || a.length < 10) return a || '';
+ return `${a.slice(0, 6)}…${a.slice(-4)}`;
+}
diff --git a/api/showcase.js b/api/showcase.js
new file mode 100644
index 000000000..f78ec0b38
--- /dev/null
+++ b/api/showcase.js
@@ -0,0 +1,170 @@
+// GET /api/showcase — public directory of ERC-8004 agents with 3D avatars.
+//
+// Reads from `erc8004_agents_index` (populated by api/cron/erc8004-crawl.js).
+// Keyset pagination on (registered_at, chain_id, agent_id) — stable under
+// concurrent inserts and backed by the `erc8004_agents_has3d_time` index.
+
+import { sql } from './_lib/db.js';
+import { cors, error, json, method, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
+
+const MAX_LIMIT = 60;
+const DEFAULT_LIMIT = 24;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const params = parseParams(url.searchParams);
+ if (params.error) return error(res, 400, 'validation_error', params.error);
+
+ const { chainIds, sort, limit, cursor } = params;
+ const decoded = cursor ? decodeCursor(cursor) : null;
+ if (cursor && !decoded) return error(res, 400, 'validation_error', 'invalid cursor');
+
+ const cursorAt = decoded?.registeredAt || null;
+ const cursorChain = decoded?.chainId ?? null;
+ const cursorAgent = decoded?.agentId || null;
+
+ const rows =
+ sort === 'newest'
+ ? await sql`
+ SELECT chain_id, agent_id, owner, registry, agent_uri,
+ name, description, image, glb_url, services, x402_support,
+ registered_block, registered_tx, registered_at
+ FROM erc8004_agents_index
+ WHERE active = true
+ AND has_3d = true
+ AND chain_id = ANY(${chainIds}::int[])
+ AND (
+ ${cursorAt}::timestamptz IS NULL
+ OR (registered_at, chain_id, agent_id) <
+ (${cursorAt}::timestamptz, ${cursorChain}::int, ${cursorAgent}::text)
+ )
+ ORDER BY registered_at DESC NULLS LAST, chain_id DESC, agent_id DESC
+ LIMIT ${limit + 1}
+ `
+ : await sql`
+ SELECT chain_id, agent_id, owner, registry, agent_uri,
+ name, description, image, glb_url, services, x402_support,
+ registered_block, registered_tx, registered_at
+ FROM erc8004_agents_index
+ WHERE active = true
+ AND has_3d = true
+ AND chain_id = ANY(${chainIds}::int[])
+ AND (
+ ${cursorAt}::timestamptz IS NULL
+ OR (registered_at, chain_id, agent_id) >
+ (${cursorAt}::timestamptz, ${cursorChain}::int, ${cursorAgent}::text)
+ )
+ ORDER BY registered_at ASC NULLS FIRST, chain_id ASC, agent_id ASC
+ LIMIT ${limit + 1}
+ `;
+
+ const hasMore = rows.length > limit;
+ const pageRows = hasMore ? rows.slice(0, limit) : rows;
+ const nextCursor = hasMore ? encodeCursor(pageRows[pageRows.length - 1]) : null;
+ const agents = pageRows.map(shapeAgent);
+
+ // Filtered total, for the "N agents" headline. Cached at the edge so hot
+ // pages don't re-count.
+ const [{ count }] = await sql`
+ SELECT COUNT(*)::int AS count
+ FROM erc8004_agents_index
+ WHERE active = true
+ AND has_3d = true
+ AND chain_id = ANY(${chainIds}::int[])
+ `;
+
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=60, stale-while-revalidate=300');
+ return json(res, 200, { agents, total: count, next_cursor: nextCursor });
+});
+
+// ─── Params ──────────────────────────────────────────────────────────────────
+
+function parseParams(sp) {
+ const net = (sp.get('net') || 'mainnet').toLowerCase();
+ if (!['mainnet', 'testnet', 'all'].includes(net)) {
+ return { error: 'net must be mainnet | testnet | all' };
+ }
+
+ const sort = (sp.get('sort') || 'newest').toLowerCase();
+ if (!['newest', 'oldest'].includes(sort)) {
+ return { error: 'sort must be newest | oldest' };
+ }
+
+ let limit = Number(sp.get('limit')) || DEFAULT_LIMIT;
+ if (!Number.isFinite(limit) || limit < 1) limit = DEFAULT_LIMIT;
+ if (limit > MAX_LIMIT) limit = MAX_LIMIT;
+
+ const chainParam = sp.get('chain') || '';
+ const explicitChains = [];
+ if (chainParam) {
+ for (const p of chainParam.split(',').map((s) => s.trim()).filter(Boolean)) {
+ const n = Number(p);
+ if (!Number.isInteger(n) || !CHAIN_BY_ID[n]) {
+ return { error: `unknown chain: ${p}` };
+ }
+ explicitChains.push(n);
+ }
+ }
+
+ const candidates = explicitChains.length
+ ? explicitChains
+ : Object.values(CHAIN_BY_ID)
+ .filter((c) => (net === 'all' ? true : net === 'mainnet' ? !c.testnet : c.testnet))
+ .map((c) => c.id);
+
+ const cursor = sp.get('cursor') || '';
+ return { chainIds: candidates, sort, limit, cursor };
+}
+
+// ─── Shape & cursor ──────────────────────────────────────────────────────────
+
+function shapeAgent(row) {
+ const chainMeta = CHAIN_BY_ID[row.chain_id];
+ return {
+ chainId: row.chain_id,
+ chainName: chainMeta?.name || `Chain ${row.chain_id}`,
+ chainTestnet: !!chainMeta?.testnet,
+ agentId: row.agent_id,
+ owner: row.owner,
+ registry: row.registry,
+ agentURI: row.agent_uri,
+ name: row.name,
+ description: row.description,
+ image: row.image,
+ glbUrl: row.glb_url,
+ services: Array.isArray(row.services) ? row.services : [],
+ x402Support: !!row.x402_support,
+ registeredBlock: row.registered_block ? Number(row.registered_block) : null,
+ registeredTx: row.registered_tx,
+ registeredAt: row.registered_at ? new Date(row.registered_at).toISOString() : null,
+ viewerUrl: `/a/${row.chain_id}/${row.agent_id}`,
+ tokenExplorerUrl: tokenExplorerUrl(row.chain_id, row.agent_id),
+ ownerExplorerUrl: row.owner ? addressExplorerUrl(row.chain_id, row.owner) : null,
+ };
+}
+
+function encodeCursor(row) {
+ const at = row.registered_at ? new Date(row.registered_at).toISOString() : '';
+ const payload = `${at}|${row.chain_id}|${row.agent_id}`;
+ return Buffer.from(payload, 'utf8').toString('base64url');
+}
+
+function decodeCursor(cursor) {
+ try {
+ const payload = Buffer.from(cursor, 'base64url').toString('utf8');
+ const [registeredAt, chainIdStr, agentId] = payload.split('|');
+ const chainId = Number(chainIdStr);
+ if (!registeredAt || !Number.isInteger(chainId) || !agentId) return null;
+ return { registeredAt, chainId, agentId };
+ } catch {
+ return null;
+ }
+}
diff --git a/features.html b/features.html
index 4866aeaac..32378e484 100644
--- a/features.html
+++ b/features.html
@@ -28,6 +28,7 @@
<h1><a href="/">3D Agent</a></h1>
<nav class="features-nav">
<a href="/app">Viewer</a>
+ <a href="/explore">Explore</a>
<a href="/features" class="active">Features</a>
</nav>
</header>
diff --git a/index.html b/index.html
index 5c129b8d8..e48e6f905 100644
--- a/index.html
+++ b/index.html
@@ -495,6 +495,7 @@
</h1>
<nav class="features-nav">
<a href="/app">Viewer</a>
+ <a href="/explore">Explore</a>
<a href="/features">Features</a>
<a href="/widgets">Widgets</a>
<a href="/dashboard" class="nav-dashboard">Dashboard</a>
diff --git a/prompts/embed-hardening/00-README.md b/prompts/embed-hardening/00-README.md
new file mode 100644
index 000000000..e8303dda8
--- /dev/null
+++ b/prompts/embed-hardening/00-README.md
@@ -0,0 +1,87 @@
+# Embed Hardening — Make the embed system production-safe before users flood in
+
+This band makes the existing embed surfaces safe to drop on third-party sites at scale. It's a follow-up to the CDN versioning work that landed in [scripts/publish-lib.mjs](../../scripts/publish-lib.mjs) + [vercel.json](../../vercel.json) `/agent-3d/*` routes — the script ships fine, but the *runtime* (per-agent policy, surface enforcement, LLM payment routing) has gaps that will bite the moment the snippet gets pasted somewhere real.
+
+---
+
+## The audit that drove these prompts
+
+Investigation of the current state ([api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js), [api/_lib/schema.sql](../../api/_lib/schema.sql), [src/runtime/providers.js](../../src/runtime/providers.js), [src/element.js](../../src/element.js), [agent-embed.html](../../agent-embed.html)) found:
+
+- **Embed-policy endpoint exists** with GET/PUT/DELETE and a JSONB `embed_policy` column on `agent_identities`. Owner UI exists at [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html). Origin allowlist is enforced in [agent-embed.html:49-88](../../agent-embed.html#L49-L88).
+- **Schema migration was never merged** — the `ADD COLUMN` lives in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) but not in [api/_lib/schema.sql](../../api/_lib/schema.sql). Fresh deploys won't have the column.
+- **`<agent-3d>` web component is broken on third-party sites** — [src/runtime/providers.js:30](../../src/runtime/providers.js#L30) defaults to `https://api.anthropic.com/v1/messages` with no key. No `we-pay`, no quota, no wallet-gating. A pasted snippet either fails silently or, if a key is somehow present, is uncapped.
+- **Only one surface checks embed-policy** — the iframe page. The `<agent-3d>` script doesn't, widgets at `/w/:id` have a separate `visibility` flag, MCP at `/api/mcp/*` has no embedding checks at all.
+- **No storage-mode tracking** — `avatars.storage_key` says "it's in R2." Nothing tracks "also pinned to IPFS" or "hash attested on-chain."
+
+## The unifying design — one JSONB, three axes
+
+Extend the existing `embed_policy` column from `{ mode, hosts }` to:
+
+```jsonc
+{
+ "origins": { "mode": "allowlist|denylist", "hosts": [...] }, // exists today (renamed nest)
+ "surfaces": { "script": true, "iframe": true, "widget": true, "mcp": false },
+ "brain": {
+ "mode": "none|key-proxy|we-pay|wallet-gated",
+ "proxy_url": "https://owner.example/llm",
+ "monthly_quota": 10000,
+ "rate_limit_per_min": 20
+ },
+ "storage": { "primary": "r2", "pinned_ipfs": false, "onchain_attested": false }
+}
+```
+
+Backwards-compat: existing `{ mode, hosts }` shape is read as `policy.origins`.
+
+---
+
+## The five prompts
+
+| # | Prompt | What it ships |
+|---|---|---|
+| 01 | [01-schema-merge.md](01-schema-merge.md) | Move the `embed_policy` ALTER into [api/_lib/schema.sql](../../api/_lib/schema.sql) so fresh deploys have the column. Apply via [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs). |
+| 02 | [02-extended-policy.md](02-extended-policy.md) | Define the extended JSONB shape. Write [api/_lib/embed-policy.js](../../api/_lib/embed-policy.js) helper. Extend [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) GET/PUT to accept the new shape (backwards-compat). Extend the dashboard UI with new sections. |
+| 03 | [03-surface-enforcement.md](03-surface-enforcement.md) | Wire policy reads into the `<agent-3d>` element, the widget page, the MCP endpoint, and CSP `frame-ancestors`. Fail-closed where denied. |
+| 04 | [04-llm-proxy-quotas.md](04-llm-proxy-quotas.md) | Build `/api/llm/anthropic` with per-agent monthly quota + per-IP rate limit. Default [src/runtime/providers.js](../../src/runtime/providers.js) to it when no key/proxy is set. Track usage in `usage_events`. **This is the spend-protection work — without it, no flood is safe.** |
+| 05 | [05-storage-flags.md](05-storage-flags.md) | Add `storage_mode` JSONB to `avatars`. Pin-to-IPFS UI in dashboard. Record content hash (no on-chain tx yet). |
+
+---
+
+## Independence guarantees — read before running in parallel
+
+These prompts are designed to run **in any order**, **in parallel**, in **separate Claude Code sessions**. The rules that make that safe:
+
+1. **Schema changes are additive `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`**, appended to the existing migration block at [api/_lib/schema.sql:260](../../api/_lib/schema.sql#L260)+. Three of the five prompts (01, 02, 05) may add their own `ALTER` lines. They're idempotent — re-running is a no-op.
+2. **`api/_lib/embed-policy.js` is owned by prompt 02.** Prompts 03 and 04 import it *if it exists* and otherwise inline a minimal local copy of `defaultEmbedPolicy()` and `readEmbedPolicy(agentId)` (the inlined versions are spelled out in each prompt). Whichever ships first wins; later-shipping prompts can switch to the imported version in a follow-up.
+3. **No two prompts touch the same source file's same lines.** Each prompt declares its **Files you own** (create/edit) and **Files off-limits** (other prompts are editing). If you find yourself wanting to edit an off-limits file, stop and report it instead.
+4. **No prompt depends on another's runtime artifact.** Prompt 04 (LLM proxy) reads quotas from `embed_policy.brain.*` if present, falls back to a hard-coded global cap if absent. Prompt 03 (surface enforcement) reads `embed_policy.surfaces.*` if present, falls back to "all surfaces allowed" if absent.
+5. **Prettier + `node --check` + `npx vite build`** are the verification floor for every prompt. SQL changes must be applied via `node scripts/apply-schema.mjs` against your local `DATABASE_URL` and re-run to prove idempotency.
+
+## Conflict resolution if two prompts ship at once
+
+- **`api/_lib/schema.sql`** — merge by accepting both `ALTER` lines. Order doesn't matter.
+- **`api/agents/[id]/embed-policy.js`** — only prompt 02 should edit this. If another prompt's PR shows changes here, that's a bug in the prompt; reject and re-scope.
+- **`public/dashboard/embed-policy.html`** — only prompt 02 should edit this; same as above.
+- **`api/_lib/embed-policy.js`** — if both 02 and a later prompt try to create it, accept 02's version (it's the source of truth) and have the later prompt's PR import from it instead.
+
+## Acceptance for the band as a whole
+
+When all five have shipped:
+
+1. Drop `<script src="/agent-3d/1.5.1/agent-3d.js"></script><agent-3d src="agent://base/42">` on a third-party origin → it loads, the LLM call goes through `/api/llm/anthropic`, the per-agent quota is enforced, the embed-policy origin allowlist is checked.
+2. The dashboard at `/dashboard/embed-policy.html?id=...` exposes all four sections (origins, surfaces, brain, storage) and persists them.
+3. `select embed_policy from agent_identities` returns the extended JSONB. Existing `{ mode, hosts }` rows still parse (backwards-compat).
+4. Owner can pin an avatar to IPFS from the storage UI; resulting `storage_mode.pinned_ipfs` flips to `true`.
+5. A loop of `<agent-3d>` calls beyond the per-agent monthly quota returns HTTP 429 from the proxy, not a successful Anthropic call.
+
+If any of those don't hold, the band isn't done.
+
+---
+
+## House rules (also in [/CLAUDE.md](../../CLAUDE.md) and [/api/CLAUDE.md](../../api/CLAUDE.md))
+
+- ESM only. Prettier: tabs, 4-wide, single quotes, 100 cols. Run `npx prettier --write` on every file you touch.
+- Use [api/_lib/http.js](../../api/_lib/http.js) (`json`/`error`/`wrap`/`cors`/`method`), [api/_lib/db.js](../../api/_lib/db.js) (`sql` tagged template), [api/_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`/`authenticateBearer`), [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) (`limits.*`/`clientIp`), [api/_lib/usage.js](../../api/_lib/usage.js) (`recordEvent`).
+- Never `res.end(JSON.stringify(...))`. Never instantiate a new Pool. Never hand-roll JWT.
+- One PR per prompt. End every PR with a Reporting block (files changed, commands run + output, what was skipped, unrelated bugs noticed).
diff --git a/prompts/embed-hardening/01-schema-merge.md b/prompts/embed-hardening/01-schema-merge.md
new file mode 100644
index 000000000..4c4150879
--- /dev/null
+++ b/prompts/embed-hardening/01-schema-merge.md
@@ -0,0 +1,98 @@
+# Task 01 — Merge `embed_policy` schema migration into the canonical schema
+
+## Why this exists
+
+The `/api/agents/:id/embed-policy` endpoint (see [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js)) reads and writes a JSONB column `embed_policy` on the `agent_identities` table. The endpoint and the dashboard UI ship today, but the column itself was never merged into the canonical schema at [api/_lib/schema.sql](../../api/_lib/schema.sql) — it lives in a stranded one-off file at [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql).
+
+Consequence: any fresh database (CI, local dev, a new Vercel preview branch with a fresh Neon DB) that runs `node scripts/apply-schema.mjs` does **not** get the column. The endpoint then 500s on its first read. This is the boring foundational fix that unblocks the other four prompts in [00-README.md](00-README.md).
+
+## What you're building
+
+A two-line `ALTER TABLE` added to [api/_lib/schema.sql](../../api/_lib/schema.sql)'s additive-migrations block (currently lines 260–266), plus a header note in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) marking it merged. Then run [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs) against your local DB to confirm idempotency.
+
+## Read first (in this order)
+
+1. [api/_lib/schema.sql](../../api/_lib/schema.sql) — focus on the `agent_identities` block at lines 235–266. Note the existing pattern for additive migrations (`alter table agent_identities add column if not exists ...`).
+2. [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) — 19 lines, the source of truth for the migration that needs merging.
+3. [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs) — the one-shot applier; reads `DATABASE_URL` from `.env.local` → `.env` → environment.
+4. [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — confirms the column name (`embed_policy`) and type (`jsonb`).
+
+## What to change
+
+### 1. Append the migration to `api/_lib/schema.sql`
+
+Find the additive-migrations block under the `agent_identities` table (currently lines 260–266 — the run of `alter table agent_identities add column if not exists ...` lines). At the end of that block, add **one** new line:
+
+```sql
+alter table agent_identities add column if not exists embed_policy jsonb;
+```
+
+Match the surrounding indentation (spaces vs tabs, column alignment). Do not modify any other line. Do not reorder existing lines.
+
+### 2. Mark the stranded migration file as merged
+
+Edit [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql). Replace the existing header comment (lines 1–16) with:
+
+```sql
+-- Task 03 — Per-agent embed referrer allowlist
+--
+-- MERGED into api/_lib/schema.sql on <YYYY-MM-DD>. This file is kept for
+-- historical reference and as a one-shot ALTER for any database that was
+-- provisioned before the canonical schema picked up this column.
+--
+-- Adds an `embed_policy` JSONB column to `agent_identities`. NULL means
+-- "no policy" — preserves the legacy "embed anywhere" behaviour.
+--
+-- Apply once against any pre-existing database that wasn't reset:
+-- psql "$DATABASE_URL" -f specs/schema/embed-policy.sql
+-- Or just re-run `node scripts/apply-schema.mjs` (idempotent).
+```
+
+Leave the `ALTER TABLE` itself (lines 17–18 in the original) unchanged. Replace `<YYYY-MM-DD>` with today's date in ISO form.
+
+### 3. Verify idempotency by applying
+
+Run `node scripts/apply-schema.mjs` against your local `DATABASE_URL`. It should print no errors. Run it a second time. It should still print no errors. Capture both outputs for the reporting block.
+
+If you don't have a local Postgres / Neon connection, say so explicitly in your report — do not skip the run. The script reads `.env.local` automatically; check `cat .env.example` if you need to know what env vars are expected (you do not need to populate them — just confirm the script's check for `DATABASE_URL` fails cleanly).
+
+## Files you own (create / edit)
+
+- Edit: [api/_lib/schema.sql](../../api/_lib/schema.sql) — one line added under the `agent_identities` additive-migrations block.
+- Edit: [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) — header comment replaced; ALTER unchanged.
+
+## Files off-limits (other prompts edit these)
+
+- [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — owned by prompt 02
+- [api/_lib/embed-policy.js](../../api/_lib/embed-policy.js) (if it exists) — owned by prompt 02
+- [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — owned by prompt 02
+- Anything under [src/](../../src/) — owned by prompt 03
+- [src/runtime/providers.js](../../src/runtime/providers.js) and any new `api/llm/*` — owned by prompt 04
+- The `avatars` table schema and any new `storage_mode` column — owned by prompt 05
+
+## Idempotency / parallel-safety notes
+
+- Prompts 02 and 05 may also append `ALTER TABLE` lines to the same migration block. That's fine — `add column if not exists` is idempotent. Resolve any merge conflict by keeping all three lines in any order.
+- Do not attempt to coalesce multiple ALTERs into one; keep them as separate lines for git-blame readability.
+
+## Acceptance test
+
+1. `git diff api/_lib/schema.sql` shows exactly one added line in the additive-migrations block, no other changes.
+2. `git diff specs/schema/embed-policy.sql` shows only the header comment replaced; the `ALTER TABLE` body unchanged.
+3. `npx prettier --check api/_lib/schema.sql specs/schema/embed-policy.sql` passes (or write `--write` and commit the formatted version).
+4. `node scripts/apply-schema.mjs` runs without error against your local DB. Run it twice. Capture both outputs.
+5. `node --check` is N/A (only SQL changed) — note this in the report.
+6. `npx vite build` passes — confirms nothing in the JS world broke.
+
+## Reporting
+
+Output at the end of your PR / commit:
+
+- **Files changed:** with line counts.
+- **Commands run + output:**
+ - `node scripts/apply-schema.mjs` (first run + second run, full output).
+ - `npx prettier --check ...` result.
+ - `npx vite build` result (just last 5 lines + total time).
+- **Skipped:** anything you couldn't run (e.g. no local DB), with reason.
+- **Unrelated bugs noticed:** list anything off in nearby code that you did NOT fix.
+- **Confirmation of scope:** that you did not edit any file in the off-limits list above.
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index 6e3c3ebaa..97433b165 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -87,7 +87,7 @@ async function renderAvatars(root) {
try {
const { avatars } = await api.listAvatars();
if (!avatars.length) {
- list.innerHTML = `<div class="empty">No avatars yet. <a href="#create">Take a selfie</a> or <a href="#upload">upload a .glb</a>.</div>`;
+ list.innerHTML = `<div class="empty">No avatars yet. <a href="#create">Take a selfie</a>, <a href="#upload">upload a .glb</a>, or <a href="/deploy">deploy a metadata-only agent on-chain</a>.</div>`;
return;
}
list.innerHTML = '';
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 82b3b3f93..3299709d8 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1,161 +1,695 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Dashboard · 3D Agent</title>
-<link rel="icon" href="/favicon.ico">
-<style>
- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }
- * { box-sizing: border-box; }
- body { font:15px/1.55 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }
- a { color:#9a8cff; text-decoration:none; }
- header { display:flex; align-items:center; justify-content:space-between; padding:16px 24px; border-bottom:1px solid var(--border); position:sticky; top:0; background:var(--bg); z-index:5; }
- .brand { font-weight:600; letter-spacing:-.01em; }
- nav a { margin-right:14px; color:#aaa; font-size:14px; }
- nav a.active { color:#fff; }
- .layout { display:grid; grid-template-columns:220px 1fr; min-height:calc(100vh - 57px); }
- aside { border-right:1px solid var(--border); padding:20px 0; }
- aside a { display:block; padding:9px 20px; color:#aaa; font-size:14px; border-left:2px solid transparent; }
- aside a.active { color:#fff; background:rgba(106,92,255,.08); border-left-color:var(--accent); }
- main { padding:28px; max-width:1100px; }
- h1 { font-size:22px; margin:0 0 6px; letter-spacing:-.01em; }
- .sub { color:#888; margin:0 0 22px; font-size:14px; }
- .cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); gap:14px; }
- .card { background:var(--panel); border:1px solid var(--border); border-radius:14px; padding:16px; }
- .card h3 { margin:0 0 4px; font-size:15px; }
- .card .meta { font-size:12px; color:#888; margin:0 0 10px; }
- .preview { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; margin-bottom:10px; overflow:hidden; display:grid; place-items:center; color:#555; font-size:12px; }
- .preview model-viewer { width:100%; height:100%; }
- .row { display:flex; align-items:center; gap:8px; }
- .tag { font-size:11px; padding:2px 7px; border-radius:99px; background:#20202c; color:#ccc; }
- .btn { padding:9px 14px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; }
- .btn.sec { background:#222230; color:#ddd; }
- .empty { text-align:center; padding:60px 20px; border:1px dashed var(--border); border-radius:14px; color:#888; }
- .toolbar { display:flex; justify-content:space-between; align-items:center; margin-bottom:18px; }
- .err { padding:12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; margin-bottom:14px; }
- pre { background:#0f0f17; border:1px solid var(--border); border-radius:8px; padding:10px 12px; overflow:auto; font-size:12px; }
- code { font-family: ui-monospace, SF Mono, Menlo, monospace; }
- .key-row { display:flex; justify-content:space-between; align-items:center; padding:10px 0; border-bottom:1px solid var(--border); }
- .key-row:last-child { border:0; }
- .muted { color:#888; font-size:13px; }
- .section { margin-top:34px; }
- input, textarea, select { background:#0f0f17; border:1px solid var(--border); color:#eee; padding:9px 11px; border-radius:8px; font-size:14px; font-family:inherit; }
- input:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Dashboard · 3D Agent</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ --border: #22222e;
+ --bg: #0b0b10;
+ --panel: #14141c;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.55 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
+ color: #eee;
+ margin: 0;
+ background: var(--bg);
+ min-height: 100vh;
+ }
+ a {
+ color: #9a8cff;
+ text-decoration: none;
+ }
+ header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 24px;
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ background: var(--bg);
+ z-index: 5;
+ }
+ .brand {
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ }
+ nav a {
+ margin-right: 14px;
+ color: #aaa;
+ font-size: 14px;
+ }
+ nav a.active {
+ color: #fff;
+ }
+ .layout {
+ display: grid;
+ grid-template-columns: 220px 1fr;
+ min-height: calc(100vh - 57px);
+ }
+ aside {
+ border-right: 1px solid var(--border);
+ padding: 20px 0;
+ }
+ aside a {
+ display: block;
+ padding: 9px 20px;
+ color: #aaa;
+ font-size: 14px;
+ border-left: 2px solid transparent;
+ }
+ aside a.active {
+ color: #fff;
+ background: rgba(106, 92, 255, 0.08);
+ border-left-color: var(--accent);
+ }
+ main {
+ padding: 28px;
+ max-width: 1100px;
+ }
+ h1 {
+ font-size: 22px;
+ margin: 0 0 6px;
+ letter-spacing: -0.01em;
+ }
+ .sub {
+ color: #888;
+ margin: 0 0 22px;
+ font-size: 14px;
+ }
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: 14px;
+ }
+ .card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 16px;
+ }
+ .card h3 {
+ margin: 0 0 4px;
+ font-size: 15px;
+ }
+ .card .meta {
+ font-size: 12px;
+ color: #888;
+ margin: 0 0 10px;
+ }
+ .preview {
+ aspect-ratio: 1/1;
+ background: #0f0f17;
+ border-radius: 10px;
+ margin-bottom: 10px;
+ overflow: hidden;
+ display: grid;
+ place-items: center;
+ color: #555;
+ font-size: 12px;
+ }
+ .preview model-viewer {
+ width: 100%;
+ height: 100%;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .tag {
+ font-size: 11px;
+ padding: 2px 7px;
+ border-radius: 99px;
+ background: #20202c;
+ color: #ccc;
+ }
+ .btn {
+ padding: 9px 14px;
+ border-radius: 9px;
+ border: 0;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #fff;
+ }
+ .btn.sec {
+ background: #222230;
+ color: #ddd;
+ }
+ .empty {
+ text-align: center;
+ padding: 60px 20px;
+ border: 1px dashed var(--border);
+ border-radius: 14px;
+ color: #888;
+ }
+ .toolbar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 18px;
+ }
+ .err {
+ padding: 12px;
+ background: rgba(255, 92, 92, 0.1);
+ border: 1px solid rgba(255, 92, 92, 0.3);
+ border-radius: 8px;
+ color: #ffb3b3;
+ margin-bottom: 14px;
+ }
+ pre {
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 10px 12px;
+ overflow: auto;
+ font-size: 12px;
+ }
+ code {
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ }
+ .key-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--border);
+ }
+ .key-row:last-child {
+ border: 0;
+ }
+ .muted {
+ color: #888;
+ font-size: 13px;
+ }
+ .section {
+ margin-top: 34px;
+ }
+ input,
+ textarea,
+ select {
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ color: #eee;
+ padding: 9px 11px;
+ border-radius: 8px;
+ font-size: 14px;
+ font-family: inherit;
+ }
+ input:focus,
+ textarea:focus,
+ select:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
- /* ── Widgets tab ─────────────────────────────────────────────────────── */
- .btn-primary { display:inline-block; padding:9px 14px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; text-decoration:none; }
- .btn-primary:hover { filter:brightness(1.08); }
- .btn-danger { background:#cc4040; }
- .widgets-header { display:flex; justify-content:space-between; align-items:flex-start; gap:14px; margin-bottom:18px; flex-wrap:wrap; }
- .widgets-header h1 { margin-bottom:6px; }
- .widget-toolbar { display:flex; gap:10px; align-items:center; margin-bottom:18px; flex-wrap:wrap; }
- .widget-toolbar input, .widget-toolbar select { padding:7px 10px; font-size:13px; }
- .widget-toolbar input[type="search"] { min-width:200px; }
- .widget-card { background:var(--panel); border:1px solid var(--border); border-radius:14px; padding:14px; display:flex; flex-direction:column; gap:10px; position:relative; transition:border-color .15s; }
- .widget-card:hover { border-color:#2c2c40; }
- .widget-card .frame { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; overflow:hidden; position:relative; }
- .widget-card .frame iframe { width:100%; height:100%; border:0; display:block; }
- .widget-card .frame .placeholder { display:grid; place-items:center; height:100%; color:#555; font-size:12px; padding:10px; text-align:center; }
- .widget-card .title { display:flex; align-items:baseline; gap:8px; min-height:22px; }
- .widget-card .title h3 { margin:0; font-size:14px; cursor:text; flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
- .widget-card .title input { flex:1; padding:3px 6px; font-size:14px; font-weight:600; }
- .widget-card .pill { display:inline-flex; align-items:center; gap:6px; font-size:11px; padding:2px 8px; border-radius:99px; background:#20202c; color:#ccc; white-space:nowrap; }
- .widget-card .pill .dot { width:7px; height:7px; border-radius:50%; }
- .widget-card .meta { font-size:12px; color:#888; }
- .widget-card .actions { display:flex; gap:6px; flex-wrap:wrap; margin-top:auto; }
- .widget-card .actions button, .widget-card .actions a { padding:6px 10px; border-radius:7px; border:1px solid var(--border); background:#1a1a24; color:#ddd; font-size:12px; cursor:pointer; text-decoration:none; }
- .widget-card .actions button:hover, .widget-card .actions a:hover { background:#22222e; }
- .widget-card .actions .danger:hover { background:rgba(204,64,64,.18); border-color:rgba(204,64,64,.5); color:#ffb3b3; }
- .toggle { position:relative; display:inline-flex; align-items:center; gap:6px; cursor:pointer; user-select:none; }
- .toggle input { position:absolute; opacity:0; width:0; height:0; }
- .toggle .track { width:30px; height:17px; background:#2a2a36; border-radius:99px; position:relative; transition:background .15s; }
- .toggle .track::after { content:''; position:absolute; top:2px; left:2px; width:13px; height:13px; background:#aaa; border-radius:50%; transition:transform .15s, background .15s; }
- .toggle input:checked + .track { background:rgba(106,92,255,.55); }
- .toggle input:checked + .track::after { transform:translateX(13px); background:#fff; }
- .toggle input:focus-visible + .track { outline:2px solid var(--accent); outline-offset:2px; }
- .toggle .label { font-size:11px; color:#888; }
+ /* ── Widgets tab ─────────────────────────────────────────────────────── */
+ .btn-primary {
+ display: inline-block;
+ padding: 9px 14px;
+ border-radius: 9px;
+ border: 0;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #fff;
+ text-decoration: none;
+ }
+ .btn-primary:hover {
+ filter: brightness(1.08);
+ }
+ .btn-danger {
+ background: #cc4040;
+ }
+ .widgets-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ gap: 14px;
+ margin-bottom: 18px;
+ flex-wrap: wrap;
+ }
+ .widgets-header h1 {
+ margin-bottom: 6px;
+ }
+ .widget-toolbar {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ margin-bottom: 18px;
+ flex-wrap: wrap;
+ }
+ .widget-toolbar input,
+ .widget-toolbar select {
+ padding: 7px 10px;
+ font-size: 13px;
+ }
+ .widget-toolbar input[type='search'] {
+ min-width: 200px;
+ }
+ .widget-card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ position: relative;
+ transition: border-color 0.15s;
+ }
+ .widget-card:hover {
+ border-color: #2c2c40;
+ }
+ .widget-card .frame {
+ aspect-ratio: 1/1;
+ background: #0f0f17;
+ border-radius: 10px;
+ overflow: hidden;
+ position: relative;
+ }
+ .widget-card .frame iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: block;
+ }
+ .widget-card .frame .placeholder {
+ display: grid;
+ place-items: center;
+ height: 100%;
+ color: #555;
+ font-size: 12px;
+ padding: 10px;
+ text-align: center;
+ }
+ .widget-card .title {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ min-height: 22px;
+ }
+ .widget-card .title h3 {
+ margin: 0;
+ font-size: 14px;
+ cursor: text;
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .widget-card .title input {
+ flex: 1;
+ padding: 3px 6px;
+ font-size: 14px;
+ font-weight: 600;
+ }
+ .widget-card .pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ padding: 2px 8px;
+ border-radius: 99px;
+ background: #20202c;
+ color: #ccc;
+ white-space: nowrap;
+ }
+ .widget-card .pill .dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ }
+ .widget-card .meta {
+ font-size: 12px;
+ color: #888;
+ }
+ .widget-card .actions {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-top: auto;
+ }
+ .widget-card .actions button,
+ .widget-card .actions a {
+ padding: 6px 10px;
+ border-radius: 7px;
+ border: 1px solid var(--border);
+ background: #1a1a24;
+ color: #ddd;
+ font-size: 12px;
+ cursor: pointer;
+ text-decoration: none;
+ }
+ .widget-card .actions button:hover,
+ .widget-card .actions a:hover {
+ background: #22222e;
+ }
+ .widget-card .actions .danger:hover {
+ background: rgba(204, 64, 64, 0.18);
+ border-color: rgba(204, 64, 64, 0.5);
+ color: #ffb3b3;
+ }
+ .toggle {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ cursor: pointer;
+ user-select: none;
+ }
+ .toggle input {
+ position: absolute;
+ opacity: 0;
+ width: 0;
+ height: 0;
+ }
+ .toggle .track {
+ width: 30px;
+ height: 17px;
+ background: #2a2a36;
+ border-radius: 99px;
+ position: relative;
+ transition: background 0.15s;
+ }
+ .toggle .track::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 13px;
+ height: 13px;
+ background: #aaa;
+ border-radius: 50%;
+ transition:
+ transform 0.15s,
+ background 0.15s;
+ }
+ .toggle input:checked + .track {
+ background: rgba(106, 92, 255, 0.55);
+ }
+ .toggle input:checked + .track::after {
+ transform: translateX(13px);
+ background: #fff;
+ }
+ .toggle input:focus-visible + .track {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .toggle .label {
+ font-size: 11px;
+ color: #888;
+ }
- /* Drawer */
- .drawer-overlay { position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:50; opacity:0; pointer-events:none; transition:opacity .18s; }
- .drawer-overlay.open { opacity:1; pointer-events:auto; }
- .drawer { position:fixed; right:0; top:0; bottom:0; width:min(560px, 100vw); background:#0e0e16; border-left:1px solid var(--border); transform:translateX(100%); transition:transform .22s cubic-bezier(.2,.8,.2,1); z-index:51; overflow-y:auto; }
- .drawer.open { transform:none; }
- .drawer header { display:flex; align-items:center; justify-content:space-between; padding:16px 20px; border-bottom:1px solid var(--border); position:sticky; top:0; background:#0e0e16; z-index:1; }
- .drawer header h2 { margin:0; font-size:16px; }
- .drawer .body { padding:20px; display:flex; flex-direction:column; gap:18px; }
- .drawer .frame-lg { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; overflow:hidden; }
- .drawer .frame-lg iframe { width:100%; height:100%; border:0; }
- .drawer .stat-grid { display:grid; grid-template-columns:repeat(2, 1fr); gap:10px; }
- .drawer .stat { background:#13131c; border:1px solid var(--border); border-radius:10px; padding:12px 14px; }
- .drawer .stat .n { font-size:22px; font-weight:600; }
- .drawer .stat .l { font-size:11px; color:#888; text-transform:uppercase; letter-spacing:.5px; }
- .spark { width:100%; height:60px; }
- .spark path.area { fill:rgba(106,92,255,.18); }
- .spark path.line { fill:none; stroke:var(--accent); stroke-width:2; }
- .spark .axis { stroke:#22222e; stroke-width:1; }
- details summary { cursor:pointer; padding:6px 0; color:#aaa; font-size:13px; }
- details[open] summary { color:#eee; }
- .danger-zone { border:1px solid rgba(204,64,64,.4); border-radius:10px; padding:14px; background:rgba(204,64,64,.05); }
- .danger-zone h3 { margin:0 0 6px; color:#ffb3b3; font-size:13px; }
+ /* Drawer */
+ .drawer-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.55);
+ z-index: 50;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.18s;
+ }
+ .drawer-overlay.open {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ .drawer {
+ position: fixed;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ width: min(560px, 100vw);
+ background: #0e0e16;
+ border-left: 1px solid var(--border);
+ transform: translateX(100%);
+ transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1);
+ z-index: 51;
+ overflow-y: auto;
+ }
+ .drawer.open {
+ transform: none;
+ }
+ .drawer header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 20px;
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ background: #0e0e16;
+ z-index: 1;
+ }
+ .drawer header h2 {
+ margin: 0;
+ font-size: 16px;
+ }
+ .drawer .body {
+ padding: 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ }
+ .drawer .frame-lg {
+ aspect-ratio: 1/1;
+ background: #0f0f17;
+ border-radius: 10px;
+ overflow: hidden;
+ }
+ .drawer .frame-lg iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ .drawer .stat-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 10px;
+ }
+ .drawer .stat {
+ background: #13131c;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 12px 14px;
+ }
+ .drawer .stat .n {
+ font-size: 22px;
+ font-weight: 600;
+ }
+ .drawer .stat .l {
+ font-size: 11px;
+ color: #888;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+ .spark {
+ width: 100%;
+ height: 60px;
+ }
+ .spark path.area {
+ fill: rgba(106, 92, 255, 0.18);
+ }
+ .spark path.line {
+ fill: none;
+ stroke: var(--accent);
+ stroke-width: 2;
+ }
+ .spark .axis {
+ stroke: #22222e;
+ stroke-width: 1;
+ }
+ details summary {
+ cursor: pointer;
+ padding: 6px 0;
+ color: #aaa;
+ font-size: 13px;
+ }
+ details[open] summary {
+ color: #eee;
+ }
+ .danger-zone {
+ border: 1px solid rgba(204, 64, 64, 0.4);
+ border-radius: 10px;
+ padding: 14px;
+ background: rgba(204, 64, 64, 0.05);
+ }
+ .danger-zone h3 {
+ margin: 0 0 6px;
+ color: #ffb3b3;
+ font-size: 13px;
+ }
- /* Modal */
- .modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.6); z-index:60; display:grid; place-items:center; opacity:0; pointer-events:none; transition:opacity .15s; }
- .modal-overlay.open { opacity:1; pointer-events:auto; }
- .modal { background:#0e0e16; border:1px solid var(--border); border-radius:14px; padding:22px; width:min(560px, calc(100vw - 32px)); max-height:calc(100vh - 32px); overflow-y:auto; }
- .modal h2 { margin:0 0 4px; font-size:17px; }
- .modal .sub { margin:0 0 18px; }
- .size-presets { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
- .size-presets button { padding:6px 12px; border-radius:99px; border:1px solid var(--border); background:#13131c; color:#ccc; font-size:12px; cursor:pointer; }
- .size-presets button.active { border-color:var(--accent); color:#fff; background:rgba(106,92,255,.15); }
- .size-inputs { display:flex; gap:8px; align-items:center; margin-bottom:14px; }
- .size-inputs input { width:90px; }
+ /* Modal */
+ .modal-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ z-index: 60;
+ display: grid;
+ place-items: center;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s;
+ }
+ .modal-overlay.open {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ .modal {
+ background: #0e0e16;
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 22px;
+ width: min(560px, calc(100vw - 32px));
+ max-height: calc(100vh - 32px);
+ overflow-y: auto;
+ }
+ .modal h2 {
+ margin: 0 0 4px;
+ font-size: 17px;
+ }
+ .modal .sub {
+ margin: 0 0 18px;
+ }
+ .size-presets {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-bottom: 14px;
+ }
+ .size-presets button {
+ padding: 6px 12px;
+ border-radius: 99px;
+ border: 1px solid var(--border);
+ background: #13131c;
+ color: #ccc;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .size-presets button.active {
+ border-color: var(--accent);
+ color: #fff;
+ background: rgba(106, 92, 255, 0.15);
+ }
+ .size-inputs {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ margin-bottom: 14px;
+ }
+ .size-inputs input {
+ width: 90px;
+ }
- .toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); background:#1a1a24; border:1px solid var(--border); padding:10px 18px; border-radius:99px; font-size:13px; color:#ddd; z-index:70; box-shadow:0 4px 18px rgba(0,0,0,.4); animation:toast-in .2s; }
- @keyframes toast-in { from { opacity:0; transform:translate(-50%, 8px); } to { opacity:1; transform:translateX(-50%); } }
+ .toast {
+ position: fixed;
+ bottom: 24px;
+ left: 50%;
+ transform: translateX(-50%);
+ background: #1a1a24;
+ border: 1px solid var(--border);
+ padding: 10px 18px;
+ border-radius: 99px;
+ font-size: 13px;
+ color: #ddd;
+ z-index: 70;
+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);
+ animation: toast-in 0.2s;
+ }
+ @keyframes toast-in {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateX(-50%);
+ }
+ }
- /* visually-hidden utility for screen-reader-only labels */
- .sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); border:0; }
-</style>
-<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
-</head>
-<body>
-<header>
- <div class="brand"><a href="/">3D Agent</a></div>
- <div class="row">
- <span id="user-email" class="muted"></span>
- <button class="btn sec" onclick="signOut()">Sign out</button>
- </div>
-</header>
-<div class="layout">
- <aside>
- <a href="#avatars" class="active" data-tab="avatars">Avatars</a>
- <a href="#create" data-tab="create">Create from selfie</a>
- <a href="#upload" data-tab="upload">Upload</a>
- <a href="#widgets" data-tab="widgets">Widgets</a>
- <a href="#embed" data-tab="embed">Embed</a>
- <a href="#keys" data-tab="keys">API keys</a>
- <a href="#mcp" data-tab="mcp">MCP</a>
- <a href="#billing" data-tab="billing">Plan &amp; usage</a>
- </aside>
- <main id="main"></main>
-</div>
-<script type="module">
-import { state, api, navigate, signOut } from '/dashboard/dashboard.js';
-window.signOut = signOut;
+ /* visually-hidden utility for screen-reader-only labels */
+ .sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ border: 0;
+ }
+ </style>
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ </head>
+ <body>
+ <header>
+ <div class="brand"><a href="/">3D Agent</a></div>
+ <div class="row">
+ <span id="user-email" class="muted"></span>
+ <button class="btn sec" onclick="signOut()">Sign out</button>
+ </div>
+ </header>
+ <div class="layout">
+ <aside>
+ <a href="#avatars" class="active" data-tab="avatars">Avatars</a>
+ <a href="#create" data-tab="create">Create from selfie</a>
+ <a href="#upload" data-tab="upload">Upload</a>
+ <a href="#widgets" data-tab="widgets">Widgets</a>
+ <a href="#embed" data-tab="embed">Embed</a>
+ <a href="#keys" data-tab="keys">API keys</a>
+ <a href="#mcp" data-tab="mcp">MCP</a>
+ <a href="#billing" data-tab="billing">Plan &amp; usage</a>
+ <a href="/explore" title="Browse on-chain agents across every supported chain"
+ >Explore on-chain ↗</a
+ >
+ </aside>
+ <main id="main"></main>
+ </div>
+ <script type="module">
+ import { state, api, navigate, signOut } from '/dashboard/dashboard.js';
+ window.signOut = signOut;
-(async () => {
- try {
- const me = await api.me();
- state.user = me.user;
- document.getElementById('user-email').textContent = me.user.email;
- } catch {
- location.href = '/login?next=' + encodeURIComponent(location.pathname + location.hash);
- return;
- }
- navigate(location.hash.slice(1) || 'avatars');
- window.addEventListener('hashchange', () => navigate(location.hash.slice(1) || 'avatars'));
-})();
-</script>
-</body>
+ (async () => {
+ try {
+ const me = await api.me();
+ state.user = me.user;
+ document.getElementById('user-email').textContent = me.user.email;
+ } catch {
+ location.href =
+ '/login?next=' + encodeURIComponent(location.pathname + location.hash);
+ return;
+ }
+ navigate(location.hash.slice(1) || 'avatars');
+ window.addEventListener('hashchange', () =>
+ navigate(location.hash.slice(1) || 'avatars'),
+ );
+ })();
+ </script>
+ </body>
</html>
diff --git a/public/explore/explore.js b/public/explore/explore.js
new file mode 100644
index 000000000..0b8556578
--- /dev/null
+++ b/public/explore/explore.js
@@ -0,0 +1,348 @@
+/**
+ * /explore — ERC-8004 agent marketplace grid.
+ *
+ * Pulls from GET /api/explore. Filters + infinite pagination via cursor.
+ * Clicking a card opens the on-chain token page on the source chain's
+ * explorer; clicking the 3D preview (when present) loads the GLB in the
+ * main viewer via /#model=<url>.
+ */
+
+const CHAINS = [
+ { id: 8453, name: 'Base' },
+ { id: 42161, name: 'Arbitrum One' },
+ { id: 56, name: 'BNB Chain' },
+ { id: 1, name: 'Ethereum' },
+ { id: 10, name: 'Optimism' },
+ { id: 137, name: 'Polygon' },
+ { id: 43114, name: 'Avalanche' },
+ { id: 100, name: 'Gnosis' },
+ { id: 250, name: 'Fantom' },
+ { id: 42220, name: 'Celo' },
+ { id: 59144, name: 'Linea' },
+ { id: 534352, name: 'Scroll' },
+ { id: 5000, name: 'Mantle' },
+ { id: 324, name: 'zkSync Era' },
+ { id: 1284, name: 'Moonbeam' },
+ { id: 97, name: 'BSC Testnet' },
+ { id: 84532, name: 'Base Sepolia' },
+ { id: 421614, name: 'Arbitrum Sepolia' },
+ { id: 11155111, name: 'Ethereum Sepolia' },
+ { id: 11155420, name: 'Optimism Sepolia' },
+ { id: 80002, name: 'Polygon Amoy' },
+ { id: 43113, name: 'Avalanche Fuji' },
+];
+
+const els = {
+ search: document.querySelector('[data-role="search"]'),
+ filters: document.querySelector('[data-role="filters"]'),
+ chain: document.querySelector('[data-role="chain"]'),
+ grid: document.querySelector('[data-role="grid"]'),
+ status: document.querySelector('[data-role="status"]'),
+ loadMore: document.querySelector('[data-role="load-more"]'),
+ statAll: document.querySelector('[data-role="stat-all"]'),
+ stat3d: document.querySelector('[data-role="stat-3d"]'),
+};
+
+// Populate chain dropdown.
+for (const c of CHAINS) {
+ const opt = document.createElement('option');
+ opt.value = String(c.id);
+ opt.textContent = c.name;
+ els.chain.appendChild(opt);
+}
+
+const state = {
+ filter: 'all', // 'all' | '3d'
+ chainId: '',
+ query: '',
+ cursor: null,
+ loading: false,
+};
+
+let searchDebounce;
+
+els.filters.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-filter]');
+ if (!btn) return;
+ state.filter = btn.dataset.filter;
+ for (const b of els.filters.querySelectorAll('[data-filter]')) {
+ b.classList.toggle('active', b.dataset.filter === state.filter);
+ }
+ resetAndLoad();
+});
+
+els.chain.addEventListener('change', () => {
+ state.chainId = els.chain.value;
+ resetAndLoad();
+});
+
+els.search.addEventListener('input', () => {
+ clearTimeout(searchDebounce);
+ searchDebounce = setTimeout(() => {
+ state.query = els.search.value.trim();
+ resetAndLoad();
+ }, 250);
+});
+
+els.loadMore.addEventListener('click', () => loadPage());
+
+// Delegated embed-button click — cards can be re-rendered freely
+els.grid.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-role="card-embed"]');
+ if (!btn) return;
+ e.preventDefault();
+ e.stopPropagation();
+ openEmbedModal({
+ chainId: Number(btn.dataset.chainId),
+ agentId: btn.dataset.agentId,
+ name: btn.dataset.name,
+ });
+});
+
+function resetAndLoad() {
+ state.cursor = null;
+ els.grid.innerHTML = '';
+ loadPage();
+}
+
+async function loadPage() {
+ if (state.loading) return;
+ state.loading = true;
+ els.loadMore.hidden = true;
+ els.status.textContent = state.cursor ? 'Loading more…' : 'Loading agents…';
+
+ const params = new URLSearchParams();
+ if (state.filter === '3d') params.set('only3d', '1');
+ if (state.chainId) params.set('chain', state.chainId);
+ if (state.query) params.set('q', state.query);
+ if (state.cursor) params.set('cursor', state.cursor);
+ params.set('limit', '24');
+
+ try {
+ const res = await fetch(`/api/explore?${params.toString()}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+
+ if (data.totals) {
+ els.statAll.textContent = data.totals.all.toLocaleString();
+ els.stat3d.textContent = data.totals.threeD.toLocaleString();
+ }
+
+ for (const item of data.items) {
+ els.grid.appendChild(renderCard(item));
+ }
+ state.cursor = data.nextCursor;
+ els.loadMore.hidden = !state.cursor;
+
+ if (els.grid.children.length === 0) {
+ els.status.innerHTML =
+ '<div class="explore-empty">No agents match these filters yet.</div>';
+ } else {
+ els.status.textContent = '';
+ }
+ } catch (err) {
+ els.status.innerHTML = `<div class="explore-error">Failed to load: ${escapeHtml(err.message)}</div>`;
+ } finally {
+ state.loading = false;
+ }
+}
+
+function renderCard(item) {
+ const card = document.createElement('article');
+ card.className = 'explore-card' + (item.has3d ? ' explore-card--3d' : '');
+
+ const thumb = item.image
+ ? `<img src="${escapeAttr(item.image)}" alt="" loading="lazy" />`
+ : `<div class="explore-card-ph">${item.has3d ? '🎭' : '🤖'}</div>`;
+
+ const badges = [];
+ badges.push(
+ `<span class="explore-badge explore-badge--chain">${escapeHtml(item.chainName)}</span>`,
+ );
+ if (item.has3d)
+ badges.push(`<span class="explore-badge explore-badge--3d">3D</span>`);
+ if (item.x402Support)
+ badges.push(`<span class="explore-badge explore-badge--x402">x402</span>`);
+
+ const serviceChips = (item.services || [])
+ .filter((s) => s.name && !['avatar', '3d'].includes(String(s.name).toLowerCase()))
+ .slice(0, 3)
+ .map((s) => `<span class="explore-svc">${escapeHtml(s.name)}</span>`)
+ .join('');
+
+ const primaryHref = item.viewerUrl || item.tokenExplorerUrl || '#';
+ const primaryLabel = item.viewerUrl ? 'Load in viewer' : 'View on explorer';
+ const primaryTarget = item.viewerUrl ? '_self' : '_blank';
+
+ card.innerHTML = `
+ <a class="explore-card-thumb" href="${escapeAttr(primaryHref)}" target="${primaryTarget}" rel="noopener">
+ ${thumb}
+ ${item.has3d ? '<span class="explore-card-play">▶</span>' : ''}
+ </a>
+ <div class="explore-card-body">
+ <div class="explore-card-head">
+ <h3 class="explore-card-name">${escapeHtml(item.name)}</h3>
+ <span class="explore-card-id">#${escapeHtml(item.agentId)}</span>
+ </div>
+ <div class="explore-card-badges">${badges.join('')}</div>
+ ${item.description ? `<p class="explore-card-desc">${escapeHtml(item.description)}</p>` : ''}
+ ${serviceChips ? `<div class="explore-card-svcs">${serviceChips}</div>` : ''}
+ <div class="explore-card-foot">
+ <a class="explore-card-owner" href="${escapeAttr(item.ownerExplorerUrl || '#')}" target="_blank" rel="noopener" title="${escapeAttr(item.owner)}">
+ ${escapeHtml(item.ownerShort)}
+ </a>
+ <div class="explore-card-actions">
+ ${item.viewerUrl ? `<a class="explore-card-link" href="${escapeAttr(item.viewerUrl)}">View 3D</a>` : ''}
+ <a class="explore-card-link" href="${escapeAttr(item.tokenExplorerUrl || '#')}" target="_blank" rel="noopener">On-chain ↗</a>
+ <button type="button" class="explore-card-link explore-card-link--ghost" data-role="card-embed"
+ data-chain-id="${escapeAttr(String(item.chainId))}"
+ data-agent-id="${escapeAttr(String(item.agentId))}"
+ data-name="${escapeAttr(item.name || `Agent #${item.agentId}`)}">Embed</button>
+ </div>
+ </div>
+ </div>
+ `;
+ return card;
+}
+
+function escapeHtml(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+function escapeAttr(s) {
+ return escapeHtml(s).replace(/'/g, '&#39;');
+}
+
+// ─── Embed modal ──────────────────────────────────────────────────────────
+const LIB_CDN_URL = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';
+
+function openEmbedModal({ chainId, agentId, name }) {
+ document.querySelector('.embed-modal')?.remove();
+
+ const origin = location.origin;
+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;
+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;
+ const agentUri = `agent://${chainId}/${agentId}`;
+ const displayName = name || `Agent #${agentId}`;
+
+ const snippets = {
+ webComponent: `<script type="module" src="${LIB_CDN_URL}"></script>\n<agent-3d src="${agentUri}" mode="inline" width="480px" responsive></agent-3d>`,
+ iframe: `<iframe src="${embedUrl}" width="480" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${displayName}"></iframe>`,
+ link: pageUrl,
+ markdown: `[![${displayName}](${origin}/api/a-og?chain=${chainId}&id=${agentId})](${pageUrl})`,
+ farcaster: pageUrl,
+ };
+
+ const modal = document.createElement('div');
+ modal.className = 'embed-modal';
+ modal.setAttribute('role', 'dialog');
+ modal.setAttribute('aria-modal', 'true');
+ modal.innerHTML = `
+ <div class="embed-modal__backdrop" data-role="close"></div>
+ <div class="embed-modal__panel" role="document">
+ <header class="embed-modal__head">
+ <div>
+ <h2 class="embed-modal__title">Embed ${escapeHtml(displayName)}</h2>
+ <p class="embed-modal__sub">Drop this anywhere — any site, any doc, any chat.</p>
+ </div>
+ <button type="button" class="embed-modal__close" data-role="close" aria-label="Close">×</button>
+ </header>
+ <div class="embed-modal__tabs" role="tablist">
+ <button type="button" class="embed-tab is-active" data-tab="webComponent" role="tab" aria-selected="true">Web component</button>
+ <button type="button" class="embed-tab" data-tab="iframe" role="tab" aria-selected="false">iframe</button>
+ <button type="button" class="embed-tab" data-tab="link" role="tab" aria-selected="false">Link</button>
+ <button type="button" class="embed-tab" data-tab="markdown" role="tab" aria-selected="false">Markdown</button>
+ <button type="button" class="embed-tab" data-tab="farcaster" role="tab" aria-selected="false">Farcaster</button>
+ </div>
+ <div class="embed-modal__body">
+ <div class="embed-pane is-active" data-pane="webComponent">
+ <p class="embed-pane__hint">Full fidelity — avatar, animations, voice, memory. Requires script module.</p>
+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.webComponent)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="webComponent">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="iframe">
+ <p class="embed-pane__hint">Works anywhere that allows iframes: Notion, Substack, Ghost, blogs.</p>
+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.iframe)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="iframe">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="link">
+ <p class="embed-pane__hint">Unfurls in Slack, X, Discord, iMessage with a rich preview card.</p>
+ <input class="embed-snippet embed-snippet--input" readonly value="${escapeAttr(snippets.link)}" />
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="link">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="markdown">
+ <p class="embed-pane__hint">GitHub README, Markdown blog — renders a preview card that links to the viewer.</p>
+ <textarea class="embed-snippet" readonly rows="2">${escapeHtml(snippets.markdown)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="markdown">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="farcaster">
+ <p class="embed-pane__hint">Cast this link — Warpcast and compatible clients render an interactive Frame with View 3D + Explore buttons.</p>
+ <input class="embed-snippet embed-snippet--input" readonly value="${escapeAttr(snippets.farcaster)}" />
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="farcaster">Copy</button>
+ </div>
+ </div>
+ <footer class="embed-modal__foot">
+ <a href="${escapeAttr(pageUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Open standalone page ↗</a>
+ <a href="${escapeAttr(embedUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Preview iframe ↗</a>
+ </footer>
+ </div>
+ `;
+ document.body.appendChild(modal);
+
+ const close = () => {
+ modal.remove();
+ document.removeEventListener('keydown', onEsc);
+ };
+ const onEsc = (e) => {
+ if (e.key === 'Escape') close();
+ };
+ document.addEventListener('keydown', onEsc);
+ modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));
+
+ modal.querySelectorAll('.embed-tab').forEach((tab) => {
+ tab.addEventListener('click', () => {
+ modal.querySelectorAll('.embed-tab').forEach((t) => {
+ t.classList.toggle('is-active', t === tab);
+ t.setAttribute('aria-selected', t === tab ? 'true' : 'false');
+ });
+ modal.querySelectorAll('.embed-pane').forEach((p) => {
+ p.classList.toggle('is-active', p.dataset.pane === tab.dataset.tab);
+ });
+ });
+ });
+
+ modal.querySelectorAll('[data-role="copy"]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const key = btn.dataset.key;
+ const text = snippets[key];
+ if (!text) return;
+ const done = (ok) => {
+ btn.textContent = ok ? 'Copied ✓' : 'Copy failed';
+ setTimeout(() => (btn.textContent = 'Copy'), 1400);
+ };
+ if (navigator.clipboard?.writeText) {
+ navigator.clipboard.writeText(text).then(() => done(true), () => done(false));
+ } else {
+ const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);
+ ta?.select();
+ try {
+ document.execCommand('copy');
+ done(true);
+ } catch {
+ done(false);
+ }
+ }
+ });
+ });
+
+ setTimeout(() => {
+ const first = modal.querySelector('.embed-pane.is-active .embed-snippet');
+ first?.focus();
+ first?.select?.();
+ }, 50);
+}
+
+loadPage();
diff --git a/public/explore/index.html b/public/explore/index.html
new file mode 100644
index 000000000..5d38da558
--- /dev/null
+++ b/public/explore/index.html
@@ -0,0 +1,103 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Explore · 3D Agent</title>
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1.0, viewport-fit=cover"
+ />
+ <meta
+ name="description"
+ content="Browse every ERC-8004 agent registered on-chain across 20+ EVM networks. Filter by 3D avatar, chain, and keywords."
+ />
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://3dagent.vercel.app/explore" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
+ </head>
+ <body class="features-page explore-page">
+ <header>
+ <h1>
+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ </h1>
+ <nav class="features-nav">
+ <a href="/app">Viewer</a>
+ <a href="/explore" class="active">Explore</a>
+ <a href="/features">Features</a>
+ <a href="/widgets">Widgets</a>
+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>
+ <a href="/login" class="nav-sign-in" id="nav-sign-in">Sign in</a>
+ </nav>
+ </header>
+
+ <main class="features-main explore-main">
+ <section class="explore-hero">
+ <div class="explore-hero-chip">
+ <span class="explore-hero-dot"></span>
+ <span>ERC-8004 Agent Directory</span>
+ </div>
+ <h2>Every agent, every chain.</h2>
+ <p class="explore-sub">
+ The complete on-chain index of ERC-8004 agents. Click a 3D avatar to load
+ it in the viewer. Click any card for its on-chain passport.
+ </p>
+
+ <div class="explore-stats" data-role="stats">
+ <div class="explore-stat">
+ <div class="explore-stat-value" data-role="stat-all">—</div>
+ <div class="explore-stat-label">Agents indexed</div>
+ </div>
+ <div class="explore-stat">
+ <div class="explore-stat-value" data-role="stat-3d">—</div>
+ <div class="explore-stat-label">With 3D avatars</div>
+ </div>
+ <div class="explore-stat">
+ <div class="explore-stat-value" data-role="stat-chains">22</div>
+ <div class="explore-stat-label">Chains crawled</div>
+ </div>
+ </div>
+ </section>
+
+ <section class="explore-controls">
+ <div class="explore-search">
+ <input
+ type="search"
+ placeholder="Search by name or description…"
+ data-role="search"
+ aria-label="Search agents"
+ />
+ </div>
+ <div class="explore-chips" data-role="filters">
+ <button class="explore-chip active" data-filter="all">All agents</button>
+ <button class="explore-chip" data-filter="3d">3D only</button>
+ </div>
+ <div class="explore-chain-select">
+ <label for="explore-chain">Chain:</label>
+ <select id="explore-chain" data-role="chain">
+ <option value="">All chains</option>
+ </select>
+ </div>
+ </section>
+
+ <section class="explore-grid-wrap">
+ <div class="explore-grid" data-role="grid"></div>
+ <div class="explore-status" data-role="status"></div>
+ <div class="explore-load-more-wrap">
+ <button class="explore-load-more" data-role="load-more" hidden>
+ Load more
+ </button>
+ </div>
+ </section>
+ </main>
+
+ <script type="module" src="./explore.js"></script>
+ </body>
+</html>
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index ae4e7cae3..577645f1d 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -16,13 +16,18 @@ That's the full install for 95% of users. Everything below is optional.
### Source (pick one)
-| Attribute | Form | Example |
-| ---------- | -------------------------- | ------------------------------------- |
-| `src` | on-chain URI | `agent://base/42` |
-| `manifest` | IPFS or HTTPS manifest URL | `ipfs://bafy.../manifest.json` |
-| `body` | bare GLB (ad-hoc agent) | `ipfs://bafy.../cz.glb` or `./cz.glb` |
-
-When multiple are set, priority is `src` > `manifest` > `body`.
+| Attribute | Form | Example |
+| ---------- | --------------------------------- | ------------------------------------- |
+| `src` | on-chain URI | `agent://base/42` |
+| `agent-id` | numeric id (pair with `chain-id`) | `agent-id="42" chain-id="8453"` |
+| `agent-id` | CAIP-10 + tokenId | `agent-id="eip155:8453:0xReg…:42"` |
+| `agent-id` | shorthand onchain: | `agent-id="onchain:8453:42"` |
+| `agent-id` | backend account id (legacy) | `agent-id="a_abc123"` |
+| `manifest` | IPFS or HTTPS manifest URL | `ipfs://bafy.../manifest.json` |
+| `body` | bare GLB (ad-hoc agent) | `ipfs://bafy.../cz.glb` or `./cz.glb` |
+
+When multiple are set, priority is `src` > `agent-id` > `manifest` > `body`.
+All on-chain forms resolve through [`src/erc8004/resolver.js`](../src/erc8004/resolver.js).
### Body / scene
@@ -86,11 +91,14 @@ When multiple are set, priority is `src` > `manifest` > `body`.
### Identity / chain
-| Attribute | Type | Notes |
-| ---------- | ------------------------------------------- | ----------------------------------------------- |
-| `chain` | `base`\|`base-sepolia`\|`ethereum` | override the chain in `src="agent://..."` |
-| `registry` | 0x address | override deployed registry |
-| `wallet` | `auto`\|`metamask`\|`walletconnect`\|`none` | wallet connection policy for registration flows |
+| Attribute | Type | Notes |
+| ---------- | ------------------------------------------- | -------------------------------------------------- |
+| `chain` | `base`\|`base-sepolia`\|`ethereum` | override the chain in `src="agent://..."` |
+| `chain-id` | numeric chain id (e.g. `8453`, `84532`) | pair with numeric `agent-id` for the common case |
+| `registry` | 0x address | override deployed registry (for CAIP-10 precision) |
+| `wallet` | `auto`\|`metamask`\|`walletconnect`\|`none` | wallet connection policy for registration flows |
+
+The canonical embed shape is `<agent-3d chain-id="8453" agent-id="42">` — the element reads both attributes, resolves the on-chain registry via `REGISTRY_DEPLOYMENTS` (CREATE2-deterministic), and boots. Any of the `agent-id` forms in the Source table are accepted; the explicit `chain-id` attribute is only needed when `agent-id` is a bare number.
### Dev / debug
@@ -339,6 +347,52 @@ All bundle responses ship `access-control-allow-origin: *` and `cross-origin-res
- Element spec: `embed/0.1` — breaking changes bump minor until 1.0.
- Bundle version: tracks `package.json` `version` of the main repo. Pinning a `<MAJOR>.<MINOR>.<PATCH>` URL is the only forever-stable option — moving channels can ship security fixes that may include behavior changes within their semver range.
+## Share routes (on-chain agents)
+
+Every on-chain agent has a canonical URL triad, plus companion endpoints for previews and oEmbed.
+
+| Route | Purpose | Served by |
+| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------- |
+| `/a/:chainId/:agentId` | Canonical page — Open Graph + Twitter Player Card + Farcaster Frame + oEmbed discovery. Redirects real browsers into the SPA viewer. | `api/a-page.js` |
+| `/a/:chainId/:agentId/embed` | Chromeless iframe viewer (kiosk mode) — meant to be embedded in iframes, web-component previews, and Twitter Player Card. | `a-embed.html` |
+| `/api/a-og?chain=<id>&id=<agentId>` | 1200×630 OG image. Redirects to the manifest image if present; otherwise renders an SVG card with chain badge + owner. | `api/a-og.js` |
+| `/api/oembed?url=...` | oEmbed v1.0 JSON/XML. Recognizes `/a/:chain/:id` URLs; returns `type: rich` with an iframe html payload. | `api/agent-oembed.js` |
+
+### Surface matrix
+
+Pick the right embed for each surface:
+
+| Surface | Recommended embed | Why |
+| ----------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------ |
+| Your own site / partner site | `<agent-3d src="agent://:chain/:id">` | Full fidelity — voice, memory, skills, animations. |
+| Notion, Substack, Ghost, Medium | `<iframe src="/a/:chain/:id/embed">` | iframe-only platforms — universal compatibility. |
+| GitHub README / markdown blog | `![alt](/api/a-og?chain=...&id=...)` linking to `/a/:chain/:id` | Markdown platforms don't run JS — use the OG image as a preview card. |
+| X / Twitter post | Paste `/a/:chain/:id` | Twitter unfurls via `twitter:player` → iframe. |
+| Slack / Discord / iMessage | Paste `/a/:chain/:id` | OG tags + oEmbed give a rich preview. |
+| Farcaster cast | Paste `/a/:chain/:id` | Frame meta tags render an interactive card with "View 3D" + "Explore" buttons. |
+| Claude.ai artifact / LobeHub plugin | `<iframe src="/a/:chain/:id/embed">` (band 5) | Sandboxed embed — works inside AI artifact runtimes. |
+
+### Embed policy
+
+The iframe at `/a/:chain/:id/embed` reads an optional `embedPolicy` from the agent's on-chain manifest metadata. Shape:
+
+```json
+{
+ "embedPolicy": {
+ "mode": "allowlist" | "denylist" | "open",
+ "hosts": ["partner.example", "*.example.com"]
+ }
+}
+```
+
+- `mode: "open"` (or missing policy): permissionless — embed anywhere. This is the default.
+- `mode: "allowlist"`: iframe refuses to render unless the parent host matches at least one entry.
+- `mode: "denylist"`: iframe refuses to render if the parent host matches any entry.
+
+Parent host is determined from `window.location.ancestorOrigins` (Chromium) or `document.referrer`. When the iframe refuses, it posts `{ __agent, type: 'blocked', host }` to its parent and shows a link to open the agent on `3dagent.vercel.app`.
+
+**We ship permissionless by default.** On-chain identity is public — any embedder can show any agent unless the owner has explicitly set a policy. The policy path exists so owners _can_ restrict later; it doesn't gate the default experience.
+
## See also
- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md)
diff --git a/src/agent-hub-actions.js b/src/agent-hub-actions.js
index 8b86a2565..23376d608 100644
--- a/src/agent-hub-actions.js
+++ b/src/agent-hub-actions.js
@@ -68,14 +68,19 @@ export function renderHubActions(panel, identity, rawAgent) {
deployBtn.disabled = true;
deployBtn.querySelector('span').textContent = 'Opening…';
try {
+ const initial = await _resolveAgentPrefill(rawAgent);
const { RegisterUI } = await import('./erc8004/register-ui.js');
const wrap = document.createElement('div');
wrap.className = 'agent-register-overlay';
document.body.appendChild(wrap);
- new RegisterUI(wrap, () => {
- wrap.remove();
- location.reload();
- });
+ new RegisterUI(
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ { initial },
+ );
} catch (err) {
console.error('[hub] register-ui load failed', err);
deployBtn.disabled = false;
@@ -98,6 +103,35 @@ export function renderHubActions(panel, identity, rawAgent) {
}
}
+/**
+ * Build the `opts.initial` payload for RegisterUI from a backend agent.
+ * Pulls name + description directly; if the agent has a linked avatar_id,
+ * resolves that avatar's GLB + thumbnail so the wizard opens with the
+ * embodied version pre-selected. Falls back silently on any fetch failure.
+ *
+ * @param {Object} rawAgent
+ */
+async function _resolveAgentPrefill(rawAgent) {
+ const initial = {
+ name: rawAgent.name || '',
+ description: rawAgent.description || '',
+ };
+ if (!rawAgent.avatar_id) return initial;
+ try {
+ const res = await fetch(`/api/avatars/${encodeURIComponent(rawAgent.avatar_id)}`, {
+ credentials: 'include',
+ });
+ if (!res.ok) return initial;
+ const { avatar } = await res.json();
+ if (!avatar) return initial;
+ initial.glbUrl = avatar.url || avatar.model_url || '';
+ initial.imageUrl = avatar.thumbnail_url || '';
+ } catch (err) {
+ console.warn('[hub] avatar prefill failed; opening wizard without it', err);
+ }
+ return initial;
+}
+
// ── Icon helpers (inline SVG, consistent with existing nav icons) ─────────────
function _iconGear() {
diff --git a/src/app.js b/src/app.js
index 2b322bf63..715fb48e5 100644
--- a/src/app.js
+++ b/src/app.js
@@ -51,28 +51,34 @@ function _base64ToFile(b64, name, type) {
/**
* Parse an on-chain agent URL path. Accepts:
* /a/<chainId>/<agentId> (canonical — registry inferred)
+ * /a/<chainId>/<agentId>/embed (chromeless iframe variant)
* /a/<chainId>/<registry>/<agentId> (explicit registry, for non-canonical deployments)
+ * /a/<chainId>/<registry>/<agentId>/embed
* /a/eip155:<chainId>:<registry>/<agentId> (full CAIP)
*/
function parseOnchainPath(pathname) {
- const m = pathname.match(/^\/a\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?\/?$/);
+ // Strip trailing /embed (capturing) then peel remaining segments.
+ const embedMatch = pathname.match(/^(\/a\/.+?)\/embed\/?$/);
+ const embed = !!embedMatch;
+ const base = embed ? embedMatch[1] : pathname;
+ const m = base.match(/^\/a\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?\/?$/);
if (!m) return null;
const [, a, b, c] = m;
// /a/eip155:chainId:registry/<agentId>
const caipMatch = a.match(/^eip155:(\d+):(0x[a-fA-F0-9]{40})$/);
if (caipMatch && b && /^\d+$/.test(b) && !c) {
- return { chainId: Number(caipMatch[1]), registry: caipMatch[2], agentId: b };
+ return { chainId: Number(caipMatch[1]), registry: caipMatch[2], agentId: b, embed };
}
// /a/<chainId>/<registry>/<agentId>
if (b && c && /^\d+$/.test(a) && /^0x[a-fA-F0-9]{40}$/.test(b) && /^\d+$/.test(c)) {
- return { chainId: Number(a), registry: b, agentId: c };
+ return { chainId: Number(a), registry: b, agentId: c, embed };
}
// /a/<chainId>/<agentId> (canonical: registry inferred from REGISTRY_DEPLOYMENTS)
if (b && !c && /^\d+$/.test(a) && /^\d+$/.test(b)) {
- return { chainId: Number(a), agentId: b };
+ return { chainId: Number(a), agentId: b, embed };
}
return null;
@@ -118,7 +124,7 @@ class App {
const onchain = parseOnchainPath(location.pathname) || parseOnchainHash(hash.onchain);
this.options = {
- kiosk: Boolean(hash.kiosk),
+ kiosk: Boolean(hash.kiosk) || !!(onchain && onchain.embed),
model: hash.model || '',
preset: hash.preset || '',
cameraPosition: hash.cameraPosition ? hash.cameraPosition.split(',').map(Number) : null,
@@ -130,6 +136,7 @@ class App {
deploy: hash.deploy !== undefined || location.pathname === '/deploy',
onchain, // { chainId, agentId, registry? } | null
explore: location.pathname === '/explore',
+ showcase: location.pathname === '/showcase' || location.pathname === '/showcase/',
// pending=1 signals a post-login save round-trip
pending: qp.get('pending') === '1',
};
@@ -193,6 +200,13 @@ class App {
return;
}
+ // /showcase — browsable marketplace of every indexed 3D agent.
+ if (options.showcase) {
+ this._showShowcasePage();
+ this._initAgentSystem();
+ return;
+ }
+
// /a/<chainId>/<agentId> — resolve an on-chain agent to its 3D avatar.
if (options.onchain) {
this._loadOnChainAgent(options.onchain);
@@ -1104,8 +1118,10 @@ class App {
*/
async _loadOnChainAgent(onchain) {
try {
- const [{ getAgentOnchain, fetchAgentMetadata, findAvatar3D }, { REGISTRY_DEPLOYMENTS }] =
- await Promise.all([import('./erc8004/queries.js'), import('./erc8004/abi.js')]);
+ const [
+ { getAgentOnchain, fetchAgentMetadata, findAvatar3D },
+ { REGISTRY_DEPLOYMENTS },
+ ] = await Promise.all([import('./erc8004/queries.js'), import('./erc8004/abi.js')]);
if (!REGISTRY_DEPLOYMENTS[onchain.chainId]) {
this._showOnChainError(`Unsupported chain: ${onchain.chainId}`);
@@ -1202,6 +1218,29 @@ class App {
}
}
+ async _showShowcasePage() {
+ try {
+ const main = this.el.querySelector('main.wrap') || this.el;
+ this.dropEl?.classList.add('hidden');
+ const dropzone = this.el.querySelector('.dropzone');
+ if (dropzone) dropzone.style.display = 'none';
+ if (this.viewerContainerEl) this.viewerContainerEl.style.display = 'none';
+ const authGate = this.el.querySelector('#auth-gate');
+ if (authGate) authGate.style.display = 'none';
+ const presence = this.el.querySelector('.agent-presence-sidebar');
+ if (presence) presence.style.display = 'none';
+
+ const page = document.createElement('section');
+ page.className = 'showcase-page';
+ main.appendChild(page);
+
+ const { renderShowcasePage } = await import('./erc8004/showcase.js');
+ renderShowcasePage(page);
+ } catch (err) {
+ console.error('[3d-agent] showcase page load failed', err);
+ }
+ }
+
async _showDeployPage() {
// Render /deploy as a normal page inside the app.html shell (header +
// footer stay visible). We hide the viewer + dropzone + auth gate and
diff --git a/src/element.js b/src/element.js
index 43c1103ac..5a70a3cb5 100644
--- a/src/element.js
+++ b/src/element.js
@@ -9,6 +9,7 @@ import { Memory } from './memory/index.js';
import { loadManifest, fetchRelative } from './manifest.js';
import { resolveURI } from './ipfs.js';
import { resolveAgentById, AgentResolveError } from './agent-resolver.js';
+import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -180,7 +181,20 @@ const BASE_STYLE = `
class Agent3DElement extends HTMLElement {
static get observedAttributes() {
- return ['src', 'manifest', 'body', 'agent-id', 'mode', 'position', 'width', 'height', 'voice', 'api-key', 'key-proxy', 'responsive'];
+ return [
+ 'src',
+ 'manifest',
+ 'body',
+ 'agent-id',
+ 'mode',
+ 'position',
+ 'width',
+ 'height',
+ 'voice',
+ 'api-key',
+ 'key-proxy',
+ 'responsive',
+ ];
}
constructor() {
@@ -217,7 +231,8 @@ class Agent3DElement extends HTMLElement {
attributeChangedCallback(name, oldVal, newVal) {
if (!this._mounted) return;
- if (['mode', 'position', 'width', 'height', 'responsive'].includes(name)) this._applyLayout();
+ if (['mode', 'position', 'width', 'height', 'responsive'].includes(name))
+ this._applyLayout();
if (['src', 'manifest', 'body', 'agent-id'].includes(name)) {
// Source change — reboot
this._teardown();
@@ -257,7 +272,10 @@ class Agent3DElement extends HTMLElement {
pillBtn.setAttribute('aria-label', 'Open agent');
pillBtn.addEventListener('click', () => this._expandPill());
pillBtn.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._expandPill(); }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ this._expandPill();
+ }
});
this.shadowRoot.appendChild(pillBtn);
this._pillBtn = pillBtn;
@@ -352,9 +370,17 @@ class Agent3DElement extends HTMLElement {
const width = this.getAttribute('width') || '320px';
const height = this.getAttribute('height') || '420px';
this.style.setProperty('--agent-width', responsive ? this._clampWidth(width) : width);
- this.style.setProperty('--agent-height', responsive ? this._clampHeight(height) : height);
+ this.style.setProperty(
+ '--agent-height',
+ responsive ? this._clampHeight(height) : height,
+ );
} else {
- this.style.top = this.style.bottom = this.style.left = this.style.right = this.style.transform = '';
+ this.style.top =
+ this.style.bottom =
+ this.style.left =
+ this.style.right =
+ this.style.transform =
+ '';
const width = this.getAttribute('width');
const height = this.getAttribute('height');
@@ -371,8 +397,16 @@ class Agent3DElement extends HTMLElement {
}
}
- if (width) this.style.setProperty('--agent-width', responsive ? this._clampWidth(width) : width);
- if (height) this.style.setProperty('--agent-height', responsive ? this._clampHeight(height) : height);
+ if (width)
+ this.style.setProperty(
+ '--agent-width',
+ responsive ? this._clampWidth(width) : width,
+ );
+ if (height)
+ this.style.setProperty(
+ '--agent-height',
+ responsive ? this._clampHeight(height) : height,
+ );
}
}
@@ -395,15 +429,23 @@ class Agent3DElement extends HTMLElement {
// Swipe-down to close the bottom-sheet (CSS transitions handle the animation)
let touchStartY = 0;
- this.shadowRoot.addEventListener('touchstart', (e) => {
- touchStartY = e.touches[0].clientY;
- }, { passive: true });
- this.shadowRoot.addEventListener('touchend', (e) => {
- const dy = e.changedTouches[0].clientY - touchStartY;
- if (dy > 60 && this._pillActive && this.getAttribute('aria-expanded') === 'true') {
- this._collapsePill();
- }
- }, { passive: true });
+ this.shadowRoot.addEventListener(
+ 'touchstart',
+ (e) => {
+ touchStartY = e.touches[0].clientY;
+ },
+ { passive: true },
+ );
+ this.shadowRoot.addEventListener(
+ 'touchend',
+ (e) => {
+ const dy = e.changedTouches[0].clientY - touchStartY;
+ if (dy > 60 && this._pillActive && this.getAttribute('aria-expanded') === 'true') {
+ this._collapsePill();
+ }
+ },
+ { passive: true },
+ );
}
_updatePillState(narrow) {
@@ -465,7 +507,12 @@ class Agent3DElement extends HTMLElement {
this._stageEl.style.display = '';
// Clear pill inline overrides, re-apply proper floating layout
this.style.width = this.style.height = this.style.borderRadius = '';
- this.style.bottom = this.style.top = this.style.left = this.style.right = this.style.transform = '';
+ this.style.bottom =
+ this.style.top =
+ this.style.left =
+ this.style.right =
+ this.style.transform =
+ '';
this._applyLayout();
if (this._outsideTapHandler) {
document.removeEventListener('pointerdown', this._outsideTapHandler);
@@ -475,7 +522,10 @@ class Agent3DElement extends HTMLElement {
_observeViewport() {
if (this.hasAttribute('eager')) return;
- if (typeof IntersectionObserver === 'undefined') { this._boot(); return; }
+ if (typeof IntersectionObserver === 'undefined') {
+ this._boot();
+ return;
+ }
this._io = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) {
this._io.disconnect();
@@ -490,14 +540,21 @@ class Agent3DElement extends HTMLElement {
this._booting = true;
try {
this._loadingEl.hidden = false;
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.1 } }));
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.1 } }),
+ );
const manifest = await this._resolveManifest();
this._manifest = manifest;
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.3 } }));
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.3 } }),
+ );
// Hydrate instructions.md if referenced
- if (typeof manifest.brain?.instructions === 'string' && manifest.brain.instructions.endsWith('.md')) {
+ if (
+ typeof manifest.brain?.instructions === 'string' &&
+ manifest.brain.instructions.endsWith('.md')
+ ) {
const text = await fetchRelative(manifest, manifest.brain.instructions);
if (text) manifest.instructions = stripFrontmatter(text);
} else if (manifest.brain?.instructions) {
@@ -505,7 +562,9 @@ class Agent3DElement extends HTMLElement {
}
// Build Viewer
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'body', pct: 0.45 } }));
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'body', pct: 0.45 } }),
+ );
const viewer = new Viewer(this._stageEl, { kiosk: this.hasAttribute('kiosk') });
this._viewer = viewer;
const bodyURI = resolveURI(manifest.body?.uri);
@@ -515,8 +574,11 @@ class Agent3DElement extends HTMLElement {
this._scene = new SceneController(viewer);
// Memory
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'memory', pct: 0.6 } }));
- const memoryNamespace = manifest.id?.agentId || this.getAttribute('memory-key') || manifest.name || 'anon';
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'memory', pct: 0.6 } }),
+ );
+ const memoryNamespace =
+ manifest.id?.agentId || this.getAttribute('memory-key') || manifest.name || 'anon';
this._memory = await Memory.load({
mode: this.getAttribute('memory') || manifest.memory?.mode || 'local',
namespace: memoryNamespace,
@@ -525,7 +587,9 @@ class Agent3DElement extends HTMLElement {
});
// Skills
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'skills', pct: 0.75 } }));
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'skills', pct: 0.75 } }),
+ );
this._skills = new SkillRegistry({
trust: this.getAttribute('skill-trust') || 'owned-only',
ownerAddress: manifest.id?.owner,
@@ -533,15 +597,23 @@ class Agent3DElement extends HTMLElement {
const skillList = manifest.skills || [];
for (const spec of skillList) {
try {
- const skill = await this._skills.install(spec, { bundleBase: manifest._baseURI });
- this.dispatchEvent(new CustomEvent('skill:loaded', { detail: { name: skill.name, uri: skill.uri } }));
+ const skill = await this._skills.install(spec, {
+ bundleBase: manifest._baseURI,
+ });
+ this.dispatchEvent(
+ new CustomEvent('skill:loaded', {
+ detail: { name: skill.name, uri: skill.uri },
+ }),
+ );
} catch (e) {
console.warn('[agent-3d] skill load failed', spec, e);
}
}
// Runtime
- this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'brain', pct: 0.9 } }));
+ this.dispatchEvent(
+ new CustomEvent('agent:load-progress', { detail: { phase: 'brain', pct: 0.9 } }),
+ );
const providerConfig = {
apiKey: this.getAttribute('api-key') || undefined,
proxyURL: this.getAttribute('key-proxy') || undefined,
@@ -560,9 +632,20 @@ class Agent3DElement extends HTMLElement {
providerConfig,
});
// Re-dispatch runtime events on the host
- for (const ev of ['brain:thinking', 'brain:message', 'skill:tool-called', 'voice:speech-start', 'voice:speech-end', 'voice:transcript', 'voice:listen-start', 'memory:write']) {
+ for (const ev of [
+ 'brain:thinking',
+ 'brain:message',
+ 'skill:tool-called',
+ 'voice:speech-start',
+ 'voice:speech-end',
+ 'voice:transcript',
+ 'voice:listen-start',
+ 'memory:write',
+ ]) {
this._runtime.addEventListener(ev, (e) => {
- this.dispatchEvent(new CustomEvent(ev, { detail: e.detail, bubbles: true, composed: true }));
+ this.dispatchEvent(
+ new CustomEvent(ev, { detail: e.detail, bubbles: true, composed: true }),
+ );
if (ev === 'brain:message' && this._chatEl) this._renderMessage(e.detail);
});
}
@@ -570,20 +653,24 @@ class Agent3DElement extends HTMLElement {
this._mounted = true;
this._loadingEl.hidden = true;
if (!this._pillActive) this._posterEl.style.opacity = '0';
- this.dispatchEvent(new CustomEvent('agent:ready', {
- detail: { agent: this, manifest },
- bubbles: true,
- composed: true,
- }));
+ this.dispatchEvent(
+ new CustomEvent('agent:ready', {
+ detail: { agent: this, manifest },
+ bubbles: true,
+ composed: true,
+ }),
+ );
} catch (err) {
console.error('[agent-3d] boot failed', err);
this._loadingEl.hidden = true;
this._showError(err);
- this.dispatchEvent(new CustomEvent('agent:error', {
- detail: { phase: 'boot', error: err },
- bubbles: true,
- composed: true,
- }));
+ this.dispatchEvent(
+ new CustomEvent('agent:error', {
+ detail: { phase: 'boot', error: err },
+ bubbles: true,
+ composed: true,
+ }),
+ );
} finally {
this._booting = false;
}
@@ -594,11 +681,37 @@ class Agent3DElement extends HTMLElement {
const manifestAttr = this.getAttribute('manifest');
const body = this.getAttribute('body');
const agentIdAttr = this.getAttribute('agent-id');
+ const chainIdAttr = this.getAttribute('chain-id');
if (src) {
if (agentIdAttr) console.warn('[agent-3d] both src and agent-id provided; using src');
- return loadManifest(src, { rpcURL: this.getAttribute('rpc-url'), registry: this.getAttribute('registry') });
+ return loadManifest(src, {
+ rpcURL: this.getAttribute('rpc-url'),
+ registry: this.getAttribute('registry'),
+ });
+ }
+ if (agentIdAttr) {
+ // On-chain reference? Supported forms:
+ // agent-id="eip155:8453:0xabc...:42" full CAIP-10 + token
+ // agent-id="onchain:8453:42" shorthand, canonical registry
+ // agent-id="42" chain-id="8453" numeric id + explicit chain
+ // agent-id="agent://8453/42" agent URI
+ const caipInput = chainIdAttr
+ ? {
+ chainId: Number(chainIdAttr),
+ agentId: agentIdAttr,
+ registry: this.getAttribute('registry') || undefined,
+ }
+ : agentIdAttr;
+ const ref = parseAgentRef(caipInput);
+ if (ref) {
+ const resolved = await resolveOnchainAgent(ref);
+ if (resolved.error && !resolved.glbUrl)
+ throw new Error(`On-chain resolve failed: ${resolved.error}`);
+ return toManifest(resolved);
+ }
+ // Fall back to backend agent by UUID
+ return resolveAgentById(agentIdAttr);
}
- if (agentIdAttr) return resolveAgentById(agentIdAttr);
if (manifestAttr) return loadManifest(manifestAttr);
if (body) {
// Ad-hoc agent from a bare GLB
@@ -615,7 +728,11 @@ class Agent3DElement extends HTMLElement {
},
instructions: instructionsAttr || 'You are an embodied 3D agent.',
voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
- skills: (this.getAttribute('skills') || '').split(',').map((s) => s.trim()).filter(Boolean).map((uri) => ({ uri })),
+ skills: (this.getAttribute('skills') || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ .map((uri) => ({ uri })),
memory: { mode: this.getAttribute('memory') || 'local' },
tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
version: '0.1.0',
@@ -664,8 +781,12 @@ class Agent3DElement extends HTMLElement {
}
_teardown() {
- try { this._io?.disconnect(); } catch {}
- try { this._ro?.disconnect(); } catch {}
+ try {
+ this._io?.disconnect();
+ } catch {}
+ try {
+ this._ro?.disconnect();
+ } catch {}
try {
if (this._mqNarrow && this._mqNarrowHandler) {
this._mqNarrow.removeEventListener('change', this._mqNarrowHandler);
@@ -675,8 +796,12 @@ class Agent3DElement extends HTMLElement {
document.removeEventListener('pointerdown', this._outsideTapHandler);
this._outsideTapHandler = null;
}
- try { this._runtime?.destroy(); } catch {}
- try { this._viewer?.dispose?.(); } catch {}
+ try {
+ this._runtime?.destroy();
+ } catch {}
+ try {
+ this._viewer?.dispose?.();
+ } catch {}
this._mounted = false;
this._pillActive = false;
this._runtime = this._viewer = this._scene = this._memory = this._skills = null;
@@ -694,23 +819,43 @@ class Agent3DElement extends HTMLElement {
return reply?.text || '';
}
- clearConversation() { this._runtime?.clearConversation(); }
+ clearConversation() {
+ this._runtime?.clearConversation();
+ }
- async wave(opts) { return this._scene?.playAnimationByHint('wave', opts); }
- async lookAt(target) { return this._scene?.lookAt(target); }
- async play(name, opts) { return this._scene?.playClipByName(name, opts); }
+ async wave(opts) {
+ return this._scene?.playAnimationByHint('wave', opts);
+ }
+ async lookAt(target) {
+ return this._scene?.lookAt(target);
+ }
+ async play(name, opts) {
+ return this._scene?.playClipByName(name, opts);
+ }
async installSkill(uri) {
if (!this._skills) throw new Error('Agent not mounted');
return this._skills.install({ uri });
}
- uninstallSkill(name) { return this._skills?.uninstall(name); }
- get skills() { return this._skills?.all() || []; }
- get memory() { return this._memory; }
- get manifest() { return this._manifest; }
- get runtime() { return this._runtime; }
+ uninstallSkill(name) {
+ return this._skills?.uninstall(name);
+ }
+ get skills() {
+ return this._skills?.all() || [];
+ }
+ get memory() {
+ return this._memory;
+ }
+ get manifest() {
+ return this._manifest;
+ }
+ get runtime() {
+ return this._runtime;
+ }
- setMode(mode) { this.setAttribute('mode', mode); }
+ setMode(mode) {
+ this.setAttribute('mode', mode);
+ }
setPosition(pos, offset) {
this.setAttribute('position', pos);
if (offset) this.setAttribute('offset', offset);
@@ -720,14 +865,23 @@ class Agent3DElement extends HTMLElement {
this.setAttribute('height', h);
}
- pause() { this._runtime?.pause(); }
- resume() { /* viewer resumes via IntersectionObserver */ }
- destroy() { this._teardown(); }
+ pause() {
+ this._runtime?.pause();
+ }
+ resume() {
+ /* viewer resumes via IntersectionObserver */
+ }
+ destroy() {
+ this._teardown();
+ }
_waitForReady() {
if (this._mounted) return Promise.resolve();
return new Promise((resolve) => {
- const on = () => { this.removeEventListener('agent:ready', on); resolve(); };
+ const on = () => {
+ this.removeEventListener('agent:ready', on);
+ resolve();
+ };
this.addEventListener('agent:ready', on);
if (!this._booting) this._boot();
});
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index e2a35ce14..cd11455e4 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -11,6 +11,7 @@
import { BrowserProvider, Contract } from 'ethers';
import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';
import { isPrivyConfigured, connectWithPrivy } from './privy.js';
+import { glbFileToThumbnail } from './thumbnail.js';
// ---------------------------------------------------------------------------
// Wallet
@@ -44,7 +45,9 @@ export async function connectWallet() {
// Fallback: raw injected provider (MetaMask, etc.)
if (!window.ethereum) {
- throw new Error('No wallet detected. Install MetaMask or configure Privy (VITE_PRIVY_APP_ID).');
+ throw new Error(
+ 'No wallet detected. Install MetaMask or configure Privy (VITE_PRIVY_APP_ID).',
+ );
}
_provider = new BrowserProvider(window.ethereum);
@@ -166,7 +169,7 @@ export function buildRegistrationJSON({
});
}
- return {
+ const json = {
type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
name,
description,
@@ -182,6 +185,16 @@ export function buildRegistrationJSON({
],
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' };
+ }
+
+ return json;
}
// ---------------------------------------------------------------------------
@@ -203,46 +216,98 @@ export function getIdentityRegistry(chainId, signer) {
}
/**
- * Full registration flow:
- * 1. Upload GLB to storage (R2 or Pinata)
- * 2. Build registration JSON
- * 3. Upload registration JSON to storage
- * 4. Call register(agentURI) on-chain
- * 5. Update agentURI to the final registration JSON
+ * Full ERC-8004 registration flow.
*
- * @param {object} opts
- * @param {File} opts.glbFile The GLB avatar file
- * @param {string} opts.name Agent name
- * @param {string} opts.description Agent description
- * @param {string} [opts.apiToken] Optional Pinata JWT (omit to use built-in storage)
- * @param {Array<{name?:string,type?:string,endpoint:string,version?:string}>} [opts.services] Extra services to include in registration JSON
- * @param {function} [opts.onStatus] Callback for progress updates
- * @returns {Promise<{agentId: number, registrationUrl: string, txHash: string}>}
+ * Resolution order for each asset:
+ * - GLB: `glbUrl` (already-stable URL, skips re-pinning) → `glbFile` (pinned) → none
+ * - 2D image: `imageUrl` → `imageFile` (pinned) → auto-render from `glbFile`
+ * (unless `autoThumbnail: false`) → empty string
+ *
+ * On-chain sequence:
+ * 1. Pin any files that aren't already URLs
+ * 2. (Optional) auto-render a 2D thumbnail from the GLB for ERC-721 marketplace compat
+ * 3. Connect wallet + get Identity Registry contract
+ * 4. `register(seedURI)` — seeds the mint with whichever URL resolves first
+ * 5. Build full registration JSON with the minted agentId
+ * 6. Pin the JSON
+ * 7. `setAgentURI(agentId, registrationUrl)` — point on-chain pointer at final JSON
+ *
+ * @param {object} opts
+ * @param {string} opts.name
+ * @param {string} opts.description
+ * @param {File} [opts.glbFile] GLB to pin (skipped if `glbUrl` provided)
+ * @param {string} [opts.glbUrl] Pre-resolved GLB URL — pass instead of `glbFile` to skip re-pin
+ * @param {string} [opts.imageUrl] Pre-resolved 2D image URL (PNG/JPG)
+ * @param {File|Blob} [opts.imageFile] 2D image to pin when `imageUrl` absent
+ * @param {boolean} [opts.autoThumbnail=true] Auto-render thumbnail from GLB if no image provided
+ * @param {string} [opts.apiToken] Optional Pinata JWT — omit to use built-in R2 backend
+ * @param {Array<{name?:string,type?:string,endpoint:string,version?:string}>} [opts.services]
+ * @param {boolean} [opts.x402Support=false]
+ * @param {(msg: string) => void} [opts.onStatus] Progress callback
+ * @returns {Promise<{agentId: number, registrationUrl: string, txHash: string, chainId: number}>}
*/
-export async function registerAgent({ glbFile, name, description, imageUrl, apiToken, services = [], x402Support = false, onStatus }) {
+export async function registerAgent({
+ name,
+ description,
+ glbFile,
+ glbUrl,
+ imageUrl,
+ imageFile,
+ autoThumbnail = true,
+ apiToken,
+ services = [],
+ x402Support = false,
+ onStatus,
+}) {
const log = onStatus || (() => {});
- // 1. Connect wallet
- log('Connecting wallet...');
- const { signer, chainId } = await connectWallet();
+ // ── 1. Resolve GLB: pin file if we don't already have a URL.
+ if (glbFile && !glbUrl) {
+ log('Uploading 3D model...');
+ glbUrl = await pinFile(glbFile, apiToken);
+ log(`Model uploaded: ${glbUrl}`);
+ }
- // 2. Upload GLB
- log('Uploading 3D model...');
- const glbUrl = await pinFile(glbFile, apiToken);
- log(`Model uploaded: ${glbUrl}`);
+ // ── 2. Resolve 2D image. Priority: URL → File → auto-thumbnail from GLB.
+ if (!imageUrl && imageFile) {
+ log('Uploading 2D image...');
+ imageUrl = await pinFile(imageFile, apiToken);
+ log(`Image uploaded: ${imageUrl}`);
+ } else if (!imageUrl && autoThumbnail && glbFile) {
+ try {
+ log('Rendering 2D thumbnail from GLB...');
+ const thumb = await glbFileToThumbnail(glbFile);
+ imageUrl = await pinFile(thumb, apiToken);
+ log(`Thumbnail uploaded: ${imageUrl}`);
+ } catch (err) {
+ log(`Thumbnail render failed (${err.message}) — continuing without 2D image.`);
+ }
+ }
+ imageUrl = imageUrl || '';
- // 3. Get contract
+ // ── 3. Wallet + contract.
+ log('Connecting wallet...');
+ const { signer, chainId } = await connectWallet();
const registry = getIdentityRegistry(chainId, signer);
- // 4. Register with GLB URL first to get the agentId
+ // ── 4. Mint with seed URI (useful metadata in the Registered event even if
+ // setAgentURI fails before step 7 completes).
log('Registering agent on-chain...');
- const tx = await registry['register(string)'](glbUrl);
+ const seedURI = glbUrl || imageUrl || '';
+ const tx = seedURI
+ ? await registry['register(string)'](seedURI)
+ : await registry['register()']();
log(`Transaction submitted: ${tx.hash}`);
const receipt = await tx.wait();
- // Parse agentId from the Registered event
const registeredEvent = receipt.logs
- .map((l) => { try { return registry.interface.parseLog(l); } catch { return null; } })
+ .map((l) => {
+ try {
+ return registry.interface.parseLog(l);
+ } catch {
+ return null;
+ }
+ })
.find((e) => e && e.name === 'Registered');
if (!registeredEvent) {
@@ -252,13 +317,11 @@ export async function registerAgent({ glbFile, name, description, imageUrl, apiT
const agentId = Number(registeredEvent.args.agentId);
log(`Agent minted! agentId = ${agentId}`);
- // 5. Build final registration JSON with the agentId. `imageUrl` is left as
- // whatever the caller passed — NFT-marketplace thumbnails want a PNG/JPG,
- // not a GLB. The GLB is surfaced via the `avatar` service entry below.
+ // ── 5 + 6. Build + pin the full registration JSON.
const registrationJSON = buildRegistrationJSON({
name,
description,
- imageUrl: imageUrl || '',
+ imageUrl,
glbUrl,
agentId,
chainId,
@@ -267,7 +330,6 @@ export async function registerAgent({ glbFile, name, description, imageUrl, apiT
x402Support,
});
- // 6. Upload registration JSON
log('Uploading registration metadata...');
const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {
type: 'application/json',
@@ -275,15 +337,11 @@ export async function registerAgent({ glbFile, name, description, imageUrl, apiT
const registrationUrl = await pinFile(jsonBlob, apiToken);
log(`Registration metadata uploaded: ${registrationUrl}`);
- // 7. Update agentURI on-chain to point at the full registration JSON
+ // ── 7. Point agentURI at the final JSON.
log('Updating agentURI on-chain...');
const updateTx = await registry.setAgentURI(agentId, registrationUrl);
await updateTx.wait();
log('Agent URI updated on-chain.');
- return {
- agentId,
- registrationUrl,
- txHash: tx.hash,
- };
+ return { agentId, registrationUrl, txHash: tx.hash, chainId };
}
diff --git a/src/erc8004/default-avatars.js b/src/erc8004/default-avatars.js
new file mode 100644
index 000000000..af17897f8
--- /dev/null
+++ b/src/erc8004/default-avatars.js
@@ -0,0 +1,37 @@
+/**
+ * Pre-pinned default avatars for ERC-8004 deploy flow.
+ *
+ * Populated entries here become selectable in the "Default avatar" option of
+ * the register-ui Step 3 wizard. Each entry:
+ * - id stable key (used for radio selection + analytics)
+ * - name display label
+ * - description short hint under the card
+ * - url stable GLB URL (ipfs:// preferred — CID-addressable + free)
+ * - thumbnailUrl 2D poster URL used both as the card preview AND the
+ * ERC-721 `image` field, skipping client-side re-render
+ *
+ * Leave the array empty until we've pinned real assets — the wizard gracefully
+ * hides the option when `DEFAULT_AVATARS.length === 0`.
+ *
+ * To add one:
+ * 1. Pin the GLB + a 512x512 PNG thumbnail to IPFS (Pinata / R2 / nft.storage).
+ * 2. Append an entry below with both `ipfs://<cid>` URLs.
+ * 3. Verify the CIDs resolve via https://ipfs.io/ipfs/<cid>.
+ * 4. Prettier + `npm run build` — done.
+ */
+
+/**
+ * @typedef {object} DefaultAvatar
+ * @property {string} id
+ * @property {string} name
+ * @property {string} description
+ * @property {string} url GLB URL (ipfs:// or https://)
+ * @property {string} thumbnailUrl PNG URL (ipfs:// or https://)
+ */
+
+/** @type {DefaultAvatar[]} */
+export const DEFAULT_AVATARS = [];
+
+export function getDefaultAvatar(id) {
+ return DEFAULT_AVATARS.find((a) => a.id === id) || null;
+}
diff --git a/src/erc8004/explore.js b/src/erc8004/explore.js
index 10b8ef758..5d06328b7 100644
--- a/src/erc8004/explore.js
+++ b/src/erc8004/explore.js
@@ -519,6 +519,17 @@ class ExplorePage {
}
});
});
+ root.querySelectorAll('[data-role="card-embed"]').forEach((btn) => {
+ btn.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ openEmbedModal({
+ chainId: Number(btn.dataset.chainId),
+ agentId: btn.dataset.agentId,
+ name: btn.dataset.name,
+ });
+ });
+ });
}
_wireExampleClicks(root) {
@@ -650,6 +661,12 @@ function renderCard(r) {
<div class="explore-card-actions">
<a class="explore-btn explore-btn--sm explore-btn--primary" href="${esc(viewerUrl)}">Open 3D ↗</a>
${explorerUrl ? `<a class="explore-btn explore-btn--sm" href="${esc(explorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--ghost"
+ data-role="card-embed"
+ data-chain-id="${esc(String(r.chainId))}"
+ data-agent-id="${esc(String(r.agentId))}"
+ data-name="${esc(r.name || `Agent #${r.agentId}`)}"
+ title="Get embed snippets">Embed</button>
<button type="button" class="explore-btn explore-btn--sm explore-btn--ghost"
data-role="card-copy" data-share="${esc(viewerUrl)}" title="Copy shareable link">Share</button>
</div>
@@ -678,6 +695,149 @@ function renderNoMatchCopy(type, query) {
}
}
+// ───────────────────────────────────────────────────────────────────────────
+// Embed modal
+// ───────────────────────────────────────────────────────────────────────────
+
+const LIB_CDN_URL = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';
+
+/**
+ * Open a modal with copy-paste embed snippets for an on-chain agent.
+ * @param {{ chainId: number, agentId: string, name: string }} p
+ */
+function openEmbedModal({ chainId, agentId, name }) {
+ // Remove any existing
+ document.querySelector('.embed-modal')?.remove();
+
+ const origin = location.origin;
+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;
+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;
+ const agentUri = `agent://${chainId}/${agentId}`;
+ const displayName = name || `Agent #${agentId}`;
+
+ const snippets = {
+ iframe: `<iframe src="${embedUrl}" width="480" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${displayName}"></iframe>`,
+ webComponent: `<script type="module" src="${LIB_CDN_URL}"></script>
+<agent-3d src="${agentUri}" mode="inline" width="480px" responsive></agent-3d>`,
+ markdown: `[![${displayName}](${origin}/api/a-og?chain=${chainId}&id=${agentId})](${pageUrl})`,
+ link: pageUrl,
+ farcaster: pageUrl,
+ };
+
+ const modal = document.createElement('div');
+ modal.className = 'embed-modal';
+ modal.setAttribute('role', 'dialog');
+ modal.setAttribute('aria-modal', 'true');
+ modal.setAttribute('aria-label', `Embed ${displayName}`);
+ modal.innerHTML = `
+ <div class="embed-modal__backdrop" data-role="close"></div>
+ <div class="embed-modal__panel" role="document">
+ <header class="embed-modal__head">
+ <div>
+ <h2 class="embed-modal__title">Embed ${esc(displayName)}</h2>
+ <p class="embed-modal__sub">Drop this anywhere — any site, any doc, any chat.</p>
+ </div>
+ <button type="button" class="embed-modal__close" data-role="close" aria-label="Close">×</button>
+ </header>
+ <div class="embed-modal__tabs" role="tablist">
+ <button type="button" class="embed-tab is-active" data-tab="webComponent" role="tab" aria-selected="true">Web component</button>
+ <button type="button" class="embed-tab" data-tab="iframe" role="tab" aria-selected="false">iframe</button>
+ <button type="button" class="embed-tab" data-tab="link" role="tab" aria-selected="false">Link</button>
+ <button type="button" class="embed-tab" data-tab="markdown" role="tab" aria-selected="false">Markdown</button>
+ <button type="button" class="embed-tab" data-tab="farcaster" role="tab" aria-selected="false">Farcaster</button>
+ </div>
+ <div class="embed-modal__body">
+ <div class="embed-pane is-active" data-pane="webComponent">
+ <p class="embed-pane__hint">Full fidelity — loads the avatar + runtime. Requires modules.</p>
+ <textarea class="embed-snippet" readonly rows="3">${esc(snippets.webComponent)}</textarea>
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="webComponent">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="iframe">
+ <p class="embed-pane__hint">Works everywhere that allows iframes — Notion, Substack, Ghost, your own site.</p>
+ <textarea class="embed-snippet" readonly rows="3">${esc(snippets.iframe)}</textarea>
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="iframe">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="link">
+ <p class="embed-pane__hint">Share anywhere — unfurls in Slack, X, Discord, iMessage with a preview card.</p>
+ <input class="embed-snippet embed-snippet--input" readonly value="${esc(snippets.link)}" />
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="link">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="markdown">
+ <p class="embed-pane__hint">Drop into a README or blog that renders markdown — shows a preview card that links to the 3D viewer.</p>
+ <textarea class="embed-snippet" readonly rows="2">${esc(snippets.markdown)}</textarea>
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="markdown">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="farcaster">
+ <p class="embed-pane__hint">Cast this link. The page has Frame meta tags — Warpcast and compatible clients render an interactive card with View 3D + Explore buttons.</p>
+ <input class="embed-snippet embed-snippet--input" readonly value="${esc(snippets.farcaster)}" />
+ <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="farcaster">Copy</button>
+ </div>
+ </div>
+ <footer class="embed-modal__foot">
+ <a href="${esc(pageUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Open standalone page ↗</a>
+ <a href="${esc(embedUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Preview iframe ↗</a>
+ </footer>
+ </div>
+ `;
+ document.body.appendChild(modal);
+
+ const close = () => {
+ modal.remove();
+ document.removeEventListener('keydown', onEsc);
+ };
+ const onEsc = (e) => {
+ if (e.key === 'Escape') close();
+ };
+ document.addEventListener('keydown', onEsc);
+ modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));
+
+ modal.querySelectorAll('.embed-tab').forEach((tab) => {
+ tab.addEventListener('click', () => {
+ modal.querySelectorAll('.embed-tab').forEach((t) => {
+ t.classList.toggle('is-active', t === tab);
+ t.setAttribute('aria-selected', t === tab ? 'true' : 'false');
+ });
+ modal.querySelectorAll('.embed-pane').forEach((p) => {
+ p.classList.toggle('is-active', p.dataset.pane === tab.dataset.tab);
+ });
+ });
+ });
+
+ modal.querySelectorAll('[data-role="copy"]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const key = btn.dataset.key;
+ const text = snippets[key];
+ if (!text) return;
+ const done = (ok) => {
+ btn.textContent = ok ? 'Copied ✓' : 'Copy failed';
+ setTimeout(() => (btn.textContent = 'Copy'), 1400);
+ };
+ if (navigator.clipboard?.writeText) {
+ navigator.clipboard.writeText(text).then(
+ () => done(true),
+ () => done(false),
+ );
+ } else {
+ const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);
+ ta?.select();
+ try {
+ document.execCommand('copy');
+ done(true);
+ } catch {
+ done(false);
+ }
+ }
+ });
+ });
+
+ // Focus first field for quick copy
+ setTimeout(() => {
+ const first = modal.querySelector('.embed-pane.is-active .embed-snippet');
+ first?.focus();
+ first?.select?.();
+ }, 50);
+}
+
// ───────────────────────────────────────────────────────────────────────────
// Toast
// ───────────────────────────────────────────────────────────────────────────
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 04bd3ae79..7bbaba118 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -23,6 +23,7 @@ import {
buildRegistrationJSON,
} from './agent-registry.js';
import { glbFileToThumbnail } from './thumbnail.js';
+import { DEFAULT_AVATARS, getDefaultAvatar } from './default-avatars.js';
import { isPrivyConfigured } from './privy.js';
import { REGISTRY_DEPLOYMENTS } from './abi.js';
import { renderBatchTab } from './batch-tab.js';
@@ -58,6 +59,15 @@ import {
// Templates (for the Templates tab → prefills Create)
// ───────────────────────────────────────────────────────────────────────────
+// Service presets per template. Types match SERVICE_TYPES; endpoints are blank
+// so the wizard shows empty rows the user fills in with their own URLs.
+const S = {
+ a2a: { type: 'A2A', name: 'A2A', endpoint: '' },
+ mcp: { type: 'MCP', name: 'MCP', endpoint: '' },
+ web: { type: 'web', name: 'Website', endpoint: '' },
+ x402: { type: 'x402', name: 'x402', endpoint: '' },
+};
+
const TEMPLATES = [
{
id: 'companion',
@@ -65,6 +75,7 @@ const TEMPLATES = [
name: 'Virtual Companion',
description:
'Always-on digital friend with persistent memory and empathy for daily check-ins and emotional support.',
+ services: [S.a2a],
},
{
id: 'influencer',
@@ -72,6 +83,7 @@ const TEMPLATES = [
name: 'Virtual Influencer',
description:
'On-brand 3D persona for social posts, livestreams, and AMAs with a consistent face and voice.',
+ services: [S.a2a, S.web],
},
{
id: 'vtuber',
@@ -79,6 +91,7 @@ const TEMPLATES = [
name: 'VTuber Co-Host',
description:
'Livestream co-host with reactive expressions, chat moderation, superchat shoutouts, and lore memory.',
+ services: [S.a2a],
},
{
id: 'tutor',
@@ -86,6 +99,7 @@ const TEMPLATES = [
name: 'Language Tutor',
description:
'One-on-one conversation practice with pronunciation feedback, spaced repetition, and adaptive lessons.',
+ services: [S.a2a, S.mcp],
},
{
id: 'gallery',
@@ -93,6 +107,7 @@ const TEMPLATES = [
name: 'Gallery Guide',
description:
'Embodied docent for 3D galleries, NFT exhibitions, and metaverse rooms with scripted tours and Q&A.',
+ services: [S.a2a, S.web],
},
{
id: 'npc',
@@ -100,6 +115,7 @@ const TEMPLATES = [
name: 'Game NPC',
description:
'Questgiver and dialog partner for game worlds with persistent lore, per-player memory, and branching scripts.',
+ services: [S.a2a],
},
{
id: 'wellness',
@@ -107,6 +123,7 @@ const TEMPLATES = [
name: 'Wellness Coach',
description:
'Breathwork, meditation, and daily mood check-ins with a calm, empathetic embodied presence.',
+ services: [S.a2a],
},
{
id: 'concierge',
@@ -114,6 +131,7 @@ const TEMPLATES = [
name: 'NFT Concierge',
description:
'Token-gated holder assistant — perks, drops, private channel access, and holder-specific analytics.',
+ services: [S.a2a, S.mcp],
},
{
id: 'dao',
@@ -121,6 +139,7 @@ const TEMPLATES = [
name: 'DAO Delegate',
description:
'Reads governance proposals, summarizes sentiment, and votes on behalf of delegators within a mandate.',
+ services: [S.a2a, S.mcp],
},
{
id: 'portfolio',
@@ -128,6 +147,7 @@ const TEMPLATES = [
name: 'Portfolio Manager',
description:
'Tracks wallet positions across chains, alerts on drawdown and risk, and rebalances on schedule.',
+ services: [S.a2a, S.mcp],
},
{
id: 'defi',
@@ -135,6 +155,7 @@ const TEMPLATES = [
name: 'DeFi Trading Agent',
description:
'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',
+ services: [S.a2a, S.mcp, S.x402],
},
{
id: 'support',
@@ -142,6 +163,7 @@ const TEMPLATES = [
name: 'Avatar Support Agent',
description:
'Face-of-the-brand support — tickets, FAQ, and multi-language help with a consistent embodied persona.',
+ services: [S.a2a, S.web],
},
{
id: 'code',
@@ -149,6 +171,7 @@ const TEMPLATES = [
name: 'Code Review Agent',
description:
'Automated code analysis, security auditing, gas optimization, and best-practice enforcement.',
+ services: [S.a2a, S.mcp, S.x402],
},
{
id: 'data',
@@ -156,6 +179,7 @@ const TEMPLATES = [
name: 'Data Analysis Agent',
description:
'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.',
+ services: [S.a2a, S.mcp],
},
{
id: 'content',
@@ -163,12 +187,14 @@ const TEMPLATES = [
name: 'Content Creator',
description:
'AI content generation for social posts, documentation, technical writing, and marketing copy.',
+ services: [S.a2a, S.x402],
},
{
id: 'research',
emoji: '🔬',
name: 'Research Assistant',
description: 'Deep research on protocols, tokens, governance proposals, and market trends.',
+ services: [S.a2a, S.mcp],
},
];
@@ -245,8 +271,10 @@ export class RegisterUI {
glbUrl: initial.glbUrl || '',
glbFile: null,
savedAvatar: null, // { id, name, url, thumbnailUrl }
+ defaultAvatarId: null, // id of a pre-pinned DEFAULT_AVATARS entry
avatarSource: initial.glbUrl ? 'current' : 'upload',
services: [], // [{ name, type, endpoint }]
+ x402Support: false,
apiToken: '', // optional Pinata JWT
};
@@ -649,6 +677,7 @@ export class RegisterUI {
savedAvatar: null,
avatarSource: 'skip',
services: [],
+ x402Support: false,
apiToken: this.form.apiToken || '',
};
this.wizardStep = 1;
@@ -742,6 +771,11 @@ export class RegisterUI {
<button class="erc8004-btn erc8004-btn--ghost" data-role="add">+ Add endpoint</button>
+ <label class="erc8004-checkbox" style="margin-top:12px">
+ <input type="checkbox" data-role="x402" ${this.form.x402Support ? 'checked' : ''} />
+ Accept x402 payments (HTTP-native micropayments)
+ </label>
+
<div class="erc8004-wizard-nav">
<button class="erc8004-btn" data-role="back">← Back</button>
<button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Configuration →</button>
@@ -783,6 +817,9 @@ export class RegisterUI {
this.form.services.push({ type: 'A2A', name: '', endpoint: '' });
renderList();
});
+ body.querySelector('[data-role="x402"]').addEventListener('change', (e) => {
+ this.form.x402Support = e.target.checked;
+ });
body.querySelector('[data-role="back"]').addEventListener('click', () => {
this.wizardStep = 1;
this._renderActiveTab();
@@ -814,6 +851,7 @@ export class RegisterUI {
<div class="erc8004-avatar-sources" data-role="sources">
${hasCurrent ? radio('current', 'Use current avatar', `From your active session — <code>${esc(this.form.glbUrl)}</code>`) : ''}
${radio('saved', 'Use a saved avatar', canPickSaved ? 'Pick one from your account library.' : 'Sign in to pick from your saved avatars.', !canPickSaved)}
+ ${DEFAULT_AVATARS.length ? radio('default', 'Use a default avatar', 'Pick a pre-pinned starter avatar — no upload needed.') : ''}
${radio('upload', 'Upload a new GLB', 'Drop or browse a .glb / .gltf file from your machine.')}
${radio('skip', 'Skip — no 3D body', 'Deploy as a metadata-only agent. You can attach an avatar later via setAgentURI.')}
</div>
@@ -905,6 +943,27 @@ export class RegisterUI {
drop.classList.remove('erc8004-file-drop--active');
setFile(e.dataTransfer.files[0]);
});
+ } else if (s === 'default') {
+ panel.innerHTML = `<div class="erc8004-saved-grid" data-role="grid"></div>`;
+ const grid = panel.querySelector('[data-role="grid"]');
+ if (!DEFAULT_AVATARS.length) {
+ grid.innerHTML = `<div class="erc8004-muted">No default avatars available yet.</div>`;
+ } else {
+ grid.innerHTML = DEFAULT_AVATARS.map(
+ (a) => `
+ <button type="button" class="erc8004-saved-card ${this.form.defaultAvatarId === a.id ? 'erc8004-saved-card--active' : ''}" data-id="${esc(a.id)}">
+ ${a.thumbnailUrl ? `<img src="${esc(a.thumbnailUrl)}" alt="" loading="lazy" />` : `<div class="erc8004-saved-card-ph">GLB</div>`}
+ <div class="erc8004-saved-card-name">${esc(a.name)}</div>
+ </button>
+ `,
+ ).join('');
+ grid.querySelectorAll('.erc8004-saved-card').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ this.form.defaultAvatarId = btn.dataset.id;
+ renderPanel();
+ });
+ });
+ }
} else if (s === 'skip') {
panel.innerHTML = `
<div class="erc8004-avatar-summary">
@@ -946,6 +1005,10 @@ export class RegisterUI {
this._toast('Drop a .glb file, or choose another option.', true);
return;
}
+ if (s === 'default' && !this.form.defaultAvatarId) {
+ this._toast('Pick a default avatar, or choose another option.', true);
+ return;
+ }
this.wizardStep = 4;
this._renderActiveTab();
});
@@ -1060,6 +1123,10 @@ export class RegisterUI {
if (s === 'upload' && this.form.glbFile) {
return `Uploaded: ${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)`;
}
+ if (s === 'default' && this.form.defaultAvatarId) {
+ const def = getDefaultAvatar(this.form.defaultAvatarId);
+ return def ? `Default: ${esc(def.name)}` : `Default avatar`;
+ }
if (s === 'skip') return `<span class="erc8004-muted">None — metadata-only</span>`;
return `<span class="erc8004-muted">Not selected</span>`;
}
@@ -1078,12 +1145,14 @@ export class RegisterUI {
version: '1.0',
}));
// Best-effort glbUrl preview: 'current' uses pre-fill; 'saved' uses the
- // picked avatar's known URL; 'upload' is unknown until pin; 'skip' is
- // omitted entirely.
+ // picked avatar's known URL; 'default' uses the picked default's known
+ // URL; 'upload' is unknown until pin; 'skip' is omitted entirely.
let glbUrl = null;
if (this.form.avatarSource === 'current') glbUrl = this.form.glbUrl || null;
else if (this.form.avatarSource === 'saved')
glbUrl = this.form.savedAvatar?.modelUrl || null;
+ else if (this.form.avatarSource === 'default' && this.form.defaultAvatarId)
+ glbUrl = getDefaultAvatar(this.form.defaultAvatarId)?.url || null;
else if (this.form.avatarSource === 'upload' && this.form.glbFile)
glbUrl = `<pending-upload:${this.form.glbFile.name}>`;
@@ -1229,12 +1298,23 @@ export class RegisterUI {
version: '1.0',
}));
- // ── 1. Resolve GLB source: File to pin, or stable URL to reference as-is.
+ // Resolve avatarSource → { glbFile?, glbUrl?, imageUrl? }. Stable URLs skip
+ // re-pinning; everything else is fetched into a File so `registerAgent` can
+ // pin it (and render a 2D thumbnail) uniformly. Defaults ship their own
+ // thumbnail, so we pre-seed `imageUrl` to skip client-side re-rendering.
let glbFile = null;
let glbUrl = null;
+ let imageUrl = userImageUrl;
if (avatarSource === 'upload') {
glbFile = this.form.glbFile;
+ } else if (avatarSource === 'default' && this.form.defaultAvatarId) {
+ const def = getDefaultAvatar(this.form.defaultAvatarId);
+ if (def) {
+ glbUrl = def.url;
+ if (!imageUrl && def.thumbnailUrl) imageUrl = def.thumbnailUrl;
+ say(`Using default avatar: ${def.name}`);
+ }
} else if (avatarSource === 'current' && this.form.glbUrl) {
if (_isStableUrl(this.form.glbUrl)) {
glbUrl = this.form.glbUrl;
@@ -1261,78 +1341,16 @@ export class RegisterUI {
}
}
- // ── 2. Pin GLB if we have a File (stable URLs skip this step).
- if (glbFile && !glbUrl) {
- say('Uploading 3D model…');
- glbUrl = await pinFile(glbFile, apiToken || undefined);
- say(`Model uploaded: ${glbUrl}`);
- }
-
- // ── 3. Auto-generate 2D thumbnail when user has a GLB but no 2D poster.
- // Spec `image` must be PNG/JPG for ERC-721 marketplace compat.
- let imageUrl = userImageUrl || '';
- if (!imageUrl && glbFile) {
- try {
- say('Rendering 2D thumbnail from GLB…');
- const thumb = await glbFileToThumbnail(glbFile);
- imageUrl = await pinFile(thumb, apiToken || undefined);
- say(`Thumbnail uploaded: ${imageUrl}`);
- } catch (err) {
- say(`Thumbnail render failed (${err.message}) — continuing without 2D image.`);
- }
- }
-
- // ── 4. Mint on-chain. Seed URI carries useful metadata in the Registered
- // event in case setAgentURI fails later.
- say('Connecting wallet…');
- const { signer, chainId } = await connectWallet();
- const registry = getIdentityRegistry(chainId, signer);
-
- say('Registering agent on-chain…');
- const seedURI = glbUrl || imageUrl || '';
- const tx = seedURI
- ? await registry['register(string)'](seedURI)
- : await registry['register()']();
- say(`Transaction submitted: ${tx.hash}`);
- const receipt = await tx.wait();
-
- const registeredEvent = receipt.logs
- .map((l) => {
- try {
- return registry.interface.parseLog(l);
- } catch {
- return null;
- }
- })
- .find((e) => e && e.name === 'Registered');
- if (!registeredEvent) throw new Error('Registered event not found in receipt');
- const agentId = Number(registeredEvent.args.agentId);
- say(`Agent minted! agentId = ${agentId}`);
-
- // ── 5. Build + pin the full registration JSON, then setAgentURI.
- const registrationJSON = buildRegistrationJSON({
+ return await registerAgent({
name,
description,
- imageUrl,
+ glbFile: glbFile || undefined,
glbUrl: glbUrl || undefined,
- agentId,
- chainId,
- registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
+ imageUrl: imageUrl || undefined,
+ apiToken: apiToken || undefined,
services: extraServices,
+ onStatus: say,
});
-
- say('Uploading registration metadata…');
- const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {
- type: 'application/json',
- });
- const registrationUrl = await pinFile(jsonBlob, apiToken || undefined);
- say(`Registration metadata: ${registrationUrl}`);
-
- say('Updating agentURI on-chain…');
- const updateTx = await registry.setAgentURI(agentId, registrationUrl);
- await updateTx.wait();
-
- return { agentId, registrationUrl, txHash: tx.hash };
}
/**
@@ -1379,7 +1397,7 @@ export class RegisterUI {
})
.then(async (res) => {
if (res.count === 0) {
- list.innerHTML = `<div class="erc8004-muted">No agents registered on this chain yet. <a class="erc8004-link" data-role="goto-create">Create one →</a></div>`;
+ list.innerHTML = `<div class="erc8004-muted">No agents registered on this chain yet. <a class="erc8004-link" data-role="goto-create">Create one →</a> or <a class="erc8004-link" href="/explore" target="_blank" rel="noopener">browse other on-chain agents ↗</a>.</div>`;
list.querySelector('[data-role="goto-create"]').addEventListener(
'click',
(e) => {
@@ -1459,6 +1477,7 @@ export class RegisterUI {
<div class="erc8004-agent-card-actions">
${tokenUrl ? `<a class="erc8004-link" href="${esc(tokenUrl)}" target="_blank" rel="noopener">Details ↗</a>` : ''}
${glbUrl ? `<a class="erc8004-link" href="${esc(publicUrl)}">Open in 3D ↗</a>` : `<a class="erc8004-link" href="#agent=${agentId}">Open in viewer</a>`}
+ <button type="button" class="erc8004-link" data-role="embed">Embed &lt;/&gt;</button>
${opts.withQR && tokenUrl ? `<button type="button" class="erc8004-link" data-role="qr">QR</button>` : ''}
${opts.withEdit ? `<button type="button" class="erc8004-link" data-role="edit">Edit on-chain ✏️</button>` : ''}
${isOwner ? `<button type="button" class="erc8004-link" data-role="redeploy">Deploy on another chain 🌐</button>` : ''}
@@ -1469,6 +1488,11 @@ export class RegisterUI {
</div>
`;
+ const embedBtn = card.querySelector('[data-role="embed"]');
+ if (embedBtn)
+ embedBtn.addEventListener('click', () =>
+ this._openEmbedModal({ agentId, name, glbUrl }),
+ );
if (opts.withQR && tokenUrl) {
const qrBtn = card.querySelector('[data-role="qr"]');
if (qrBtn)
@@ -1569,6 +1593,127 @@ export class RegisterUI {
});
}
+ /**
+ * Embed-snippet modal. Gives the owner four ready-to-paste surfaces for
+ * their on-chain agent: a web-component tag, a plain iframe, a share URL,
+ * and the oEmbed discovery URL. Any page that discovers this agent can
+ * render it the same way — chain is the source of truth.
+ */
+ _openEmbedModal({ agentId, name, glbUrl }) {
+ const chainId = this.selectedChainId;
+ const origin = location.origin;
+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;
+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;
+ const oembedUrl = `${origin}/api/oembed?url=${encodeURIComponent(pageUrl)}`;
+ const cdnBase = `${origin}/agent-3d/latest/agent-3d.js`;
+
+ const snippetWC =
+ `<script type="module" src="${cdnBase}"></script>\n` +
+ `<agent-3d chain-id="${chainId}" agent-id="${agentId}" style="width:420px;height:520px"></agent-3d>`;
+ const snippetIframe =
+ `<iframe src="${embedUrl}" width="420" height="520" ` +
+ `style="border:0;border-radius:12px" ` +
+ `allow="autoplay; xr-spatial-tracking" ` +
+ `sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;
+
+ const modal = document.createElement('div');
+ modal.className = 'erc8004-modal';
+ modal.innerHTML = `
+ <div class="erc8004-modal-card" style="max-width:640px">
+ <div class="erc8004-modal-head">
+ <div class="erc8004-h4" style="margin:0">Embed ${esc(name || 'agent')}</div>
+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>
+ </div>
+ <p class="erc8004-muted erc8004-small">
+ Any surface can render this agent from chain data alone — no backend account needed.
+ ${glbUrl ? '' : '<br><b>Note:</b> this agent has no 3D body registered yet. Add one via Edit on-chain.'}
+ </p>
+ <div class="erc8004-embed-tabs" role="tablist">
+ <button type="button" data-tab="wc" class="erc8004-tab is-active">Web component</button>
+ <button type="button" data-tab="if" class="erc8004-tab">iframe</button>
+ <button type="button" data-tab="sh" class="erc8004-tab">Share URL</button>
+ <button type="button" data-tab="oe" class="erc8004-tab">oEmbed</button>
+ </div>
+ <div class="erc8004-embed-panels">
+ <div data-panel="wc" class="is-active">
+ <p class="erc8004-muted erc8004-small">Drop into any HTML page. Self-contained, no build step.</p>
+ <textarea class="erc8004-code" data-role="code-wc" readonly rows="4">${esc(snippetWC)}</textarea>
+ <button class="erc8004-btn erc8004-btn--primary" data-copy="wc">Copy</button>
+ </div>
+ <div data-panel="if" hidden>
+ <p class="erc8004-muted erc8004-small">Works everywhere iframes do — Notion, Ghost, WordPress, Substack.</p>
+ <textarea class="erc8004-code" data-role="code-if" readonly rows="4">${esc(snippetIframe)}</textarea>
+ <button class="erc8004-btn erc8004-btn--primary" data-copy="if">Copy</button>
+ </div>
+ <div data-panel="sh" hidden>
+ <p class="erc8004-muted erc8004-small">Paste anywhere (Discord, Slack, X, Farcaster) — OG preview + Twitter Player Card auto-render.</p>
+ <textarea class="erc8004-code" data-role="code-sh" readonly rows="2">${esc(pageUrl)}</textarea>
+ <button class="erc8004-btn erc8004-btn--primary" data-copy="sh">Copy</button>
+ </div>
+ <div data-panel="oe" hidden>
+ <p class="erc8004-muted erc8004-small">For apps that consume <a href="https://oembed.com" target="_blank" rel="noopener">oEmbed</a> directly (Notion, some CMSes).</p>
+ <textarea class="erc8004-code" data-role="code-oe" readonly rows="2">${esc(oembedUrl)}</textarea>
+ <button class="erc8004-btn erc8004-btn--primary" data-copy="oe">Copy</button>
+ </div>
+ </div>
+ <details class="erc8004-embed-policy">
+ <summary>Restrict where this agent can be embedded</summary>
+ <p class="erc8004-muted erc8004-small">
+ Add <code>embedPolicy</code> to your registration JSON (via Edit on-chain):
+ </p>
+ <pre class="erc8004-code" style="user-select:text">{
+ "embedPolicy": {
+ "mode": "allowlist",
+ "hosts": ["example.com", "*.mysite.xyz"]
+ }
+}</pre>
+ <p class="erc8004-muted erc8004-small">
+ Chain is the source of truth — policy is enforced by every embed surface.
+ </p>
+ </details>
+ </div>
+ `;
+ this.el.appendChild(modal);
+
+ const close = () => modal.remove();
+ modal.addEventListener('click', (e) => {
+ if (e.target === modal) close();
+ });
+ modal.querySelector('[data-role="close"]').addEventListener('click', close);
+
+ modal.querySelectorAll('.erc8004-tab').forEach((tab) => {
+ tab.addEventListener('click', () => {
+ const id = tab.getAttribute('data-tab');
+ modal
+ .querySelectorAll('.erc8004-tab')
+ .forEach((t) => t.classList.toggle('is-active', t === tab));
+ modal.querySelectorAll('[data-panel]').forEach((p) => {
+ const match = p.getAttribute('data-panel') === id;
+ p.hidden = !match;
+ p.classList.toggle('is-active', match);
+ });
+ });
+ });
+
+ modal.querySelectorAll('[data-copy]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const which = btn.getAttribute('data-copy');
+ const ta = modal.querySelector(`[data-role="code-${which}"]`);
+ if (!ta) return;
+ try {
+ await navigator.clipboard.writeText(ta.value);
+ const prev = btn.textContent;
+ btn.textContent = 'Copied ✓';
+ setTimeout(() => (btn.textContent = prev), 1400);
+ } catch {
+ ta.select();
+ document.execCommand('copy');
+ this._toast('Copied');
+ }
+ });
+ });
+ }
+
/**
* Edit modal for an existing on-chain agent. Lets the owner update
* name / description / 2D image / 3D body, then pins a new registration
@@ -1599,6 +1744,15 @@ export class RegisterUI {
<label class="erc8004-label">3D Avatar (GLB) — optional, replaces existing body
<input type="file" accept=".glb,.gltf" class="erc8004-file-input" name="glb" />
</label>
+ ${
+ currentMeta?.body?.uri ||
+ (currentMeta?.services || []).some((s) => s?.name === 'avatar')
+ ? `<label class="erc8004-checkbox">
+ <input type="checkbox" name="removeAvatar" />
+ Remove 3D avatar from this agent (clears body + avatar service)
+ </label>`
+ : ''
+ }
<label class="erc8004-label">Pinata JWT (optional)
<input class="erc8004-input" name="apiToken" placeholder="leave blank for R2 backend" />
</label>
@@ -1638,6 +1792,7 @@ export class RegisterUI {
const apiToken = modal.querySelector('[name="apiToken"]').value.trim() || undefined;
const fileInput = modal.querySelector('[name="glb"]');
const glbFile = fileInput.files?.[0] || null;
+ const removeAvatar = !!modal.querySelector('[name="removeAvatar"]')?.checked;
await this._doUpdateAgent({
agentId,
@@ -1645,6 +1800,7 @@ export class RegisterUI {
description,
imageUrl: imageUrlInput,
glbFile,
+ removeAvatar,
apiToken,
currentMeta: meta,
say,
@@ -1671,19 +1827,28 @@ export class RegisterUI {
description,
imageUrl,
glbFile,
+ removeAvatar = false,
apiToken,
currentMeta,
say,
}) {
- // Find the current GLB URL from the metadata (it lives in services[name=avatar]).
- const existingGlbUrl = (currentMeta?.services || []).find(
- (s) => s?.name === 'avatar' && s?.endpoint,
- )?.endpoint;
-
- let glbUrl = existingGlbUrl || undefined;
+ // Find the current GLB URL from the metadata (it lives in services[name=avatar]
+ // or the top-level body field — check both).
+ const existingGlbUrl =
+ currentMeta?.body?.uri ||
+ (currentMeta?.services || []).find((s) => s?.name === 'avatar' && s?.endpoint)
+ ?.endpoint;
+
+ let glbUrl = removeAvatar ? undefined : existingGlbUrl || undefined;
let newImageUrl = imageUrl;
+ if (removeAvatar) {
+ say('Avatar will be removed from this agent.');
+ }
+
// If user uploaded a new GLB, pin it and re-render thumbnail when image is empty.
+ // Uploading a new GLB overrides a `removeAvatar` checkbox — user likely meant to
+ // replace rather than delete.
if (glbFile) {
say('Uploading new 3D model…');
glbUrl = await pinFile(glbFile, apiToken);
@@ -1708,6 +1873,11 @@ export class RegisterUI {
say('Connecting wallet…');
const { signer, chainId } = await connectWallet();
+ if (chainId !== this.selectedChainId) {
+ throw new Error(
+ `Wallet is on chain ${chainId} but this agent lives on ${this.selectedChainId} (${CHAIN_META[this.selectedChainId]?.name || 'unknown'}). Switch chains in your wallet and try again.`,
+ );
+ }
const registry = getIdentityRegistry(chainId, signer);
const registryAddr = REGISTRY_DEPLOYMENTS[chainId].identityRegistry;
@@ -2081,6 +2251,9 @@ export class RegisterUI {
if (!t) return;
this.form.name = t.name;
this.form.description = t.description;
+ if (Array.isArray(t.services)) {
+ this.form.services = t.services.map((s) => ({ ...s }));
+ }
this.wizardStep = 1;
this._setTab('create');
});
diff --git a/src/erc8004/resolver.js b/src/erc8004/resolver.js
new file mode 100644
index 000000000..2728ef78f
--- /dev/null
+++ b/src/erc8004/resolver.js
@@ -0,0 +1,323 @@
+/**
+ * Universal on-chain agent resolver.
+ *
+ * One import point for every surface that needs to turn "an on-chain agent"
+ * into something renderable: the web component, oEmbed, OG image, explore
+ * page, Claude.ai artifact, LobeHub plugin, SDK.
+ *
+ * Inputs it understands:
+ *
+ * parseAgentRef('eip155:8453:0xabc...:42') — full CAIP-10 + tokenId
+ * parseAgentRef('onchain:8453:42') — shorthand (canonical registry)
+ * parseAgentRef('agent://8453/42') — agent URI
+ * parseAgentRef({ chainId: 8453, agentId: 42 }) — already parsed
+ * parseAgentRef('/a/8453/42') — URL path
+ *
+ * Output of resolveOnchainAgent: a normalized record with on-chain facts
+ * (owner, URI) + off-chain metadata + a resolved GLB URL.
+ */
+
+import { getAgentOnchain, fetchAgentMetadata, findAvatar3D } from './queries.js';
+import { REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';
+import { CHAIN_META } from './chain-meta.js';
+
+// ---------------------------------------------------------------------------
+// Parsing
+// ---------------------------------------------------------------------------
+
+/**
+ * Parse any supported agent reference into `{ chainId, agentId, registry? }`.
+ * Returns `null` if the input doesn't look like an on-chain reference.
+ *
+ * @param {string|object} input
+ * @returns {{ chainId: number, agentId: string, registry?: string }|null}
+ */
+export function parseAgentRef(input) {
+ if (!input) return null;
+
+ if (typeof input === 'object') {
+ if (input.chainId && input.agentId !== undefined) {
+ return {
+ chainId: Number(input.chainId),
+ agentId: String(input.agentId),
+ registry: input.registry || undefined,
+ };
+ }
+ return null;
+ }
+
+ const s = String(input).trim();
+ if (!s) return null;
+
+ // Full CAIP-10 + token: "eip155:<chainId>:<registry>:<agentId>"
+ let m = s.match(/^eip155:(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/);
+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };
+
+ // CAIP-10 assetType form: "eip155:<chainId>/erc721:<registry>/<agentId>"
+ m = s.match(/^eip155:(\d+)\/erc721:(0x[0-9a-fA-F]{40})\/(\d+)$/);
+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };
+
+ // Shorthand: "onchain:<chainId>:<agentId>"
+ m = s.match(/^onchain:(\d+):(\d+)$/);
+ if (m) return { chainId: Number(m[1]), agentId: m[2] };
+
+ // agent:// scheme
+ m = s.match(/^agent:\/\/(\d+)\/(\d+)$/);
+ if (m) return { chainId: Number(m[1]), agentId: m[2] };
+
+ // URL path: "/a/<chainId>/<agentId>" or with explicit registry
+ m = s.match(/^\/?a\/(\d+)\/(\d+)(?:\/(embed))?\/?$/);
+ if (m) return { chainId: Number(m[1]), agentId: m[2] };
+ m = s.match(/^\/?a\/(\d+)\/(0x[0-9a-fA-F]{40})\/(\d+)\/?$/);
+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };
+
+ return null;
+}
+
+/**
+ * Return the canonical CAIP-10 identifier string for an agent.
+ * @param {{ chainId: number, agentId: string|number, registry?: string }} ref
+ */
+export function toCAIP10(ref) {
+ const registry = ref.registry || REGISTRY_DEPLOYMENTS[ref.chainId]?.identityRegistry;
+ if (!registry) return `onchain:${ref.chainId}:${ref.agentId}`;
+ return `eip155:${ref.chainId}:${registry}:${ref.agentId}`;
+}
+
+/**
+ * Return the public `/a/<chainId>/<agentId>` URL for an agent.
+ * @param {{ chainId: number, agentId: string|number }} ref
+ * @param {object} [opts]
+ * @param {boolean} [opts.embed] Append `/embed` for chromeless iframe mode
+ * @param {string} [opts.origin] Override origin (defaults to location.origin)
+ */
+export function toPublicUrl(ref, { embed = false, origin } = {}) {
+ const o = origin || (typeof location !== 'undefined' ? location.origin : '');
+ return `${o}/a/${ref.chainId}/${ref.agentId}${embed ? '/embed' : ''}`;
+}
+
+// ---------------------------------------------------------------------------
+// URL fallback — tries direct, then rotates IPFS gateways, then Arweave
+// ---------------------------------------------------------------------------
+
+const IPFS_GATEWAYS = [
+ 'https://ipfs.io/ipfs/',
+ 'https://dweb.link/ipfs/',
+ 'https://cloudflare-ipfs.com/ipfs/',
+ 'https://gateway.pinata.cloud/ipfs/',
+];
+const AR_GATEWAY = 'https://arweave.net/';
+
+/**
+ * Convert any of `https://…`, `ipfs://<cid>[/path]`, `ar://<tx>` into a plain
+ * HTTPS URL. For ipfs, returns the first gateway — use `resolveUrlCandidates`
+ * when you need fallbacks.
+ *
+ * @param {string} uri
+ * @returns {string}
+ */
+export function resolveUrl(uri) {
+ if (!uri) return '';
+ if (uri.startsWith('ipfs://')) return IPFS_GATEWAYS[0] + uri.slice(7);
+ if (uri.startsWith('ar://')) return AR_GATEWAY + uri.slice(5);
+ return uri;
+}
+
+/**
+ * All HTTPS forms of an off-chain URI, in preference order. Use when you
+ * want to try each in sequence — e.g. the `<img>` fallback chain or a
+ * `fetch` retry loop.
+ *
+ * @param {string} uri
+ * @returns {string[]}
+ */
+export function resolveUrlCandidates(uri) {
+ if (!uri) return [];
+ if (uri.startsWith('ipfs://')) {
+ const rest = uri.slice(7);
+ return IPFS_GATEWAYS.map((gw) => gw + rest);
+ }
+ if (uri.startsWith('ar://')) return [AR_GATEWAY + uri.slice(5)];
+ return [uri];
+}
+
+// ---------------------------------------------------------------------------
+// Resolution
+// ---------------------------------------------------------------------------
+
+// Lightweight in-memory cache keyed by canonical ref string. The resolver is
+// a hot path on /explore and in consumer embeds; don't hit the chain twice
+// for the same agent within a page session.
+const _cache = new Map();
+function cacheKey(ref) {
+ return `${ref.chainId}:${ref.agentId}`;
+}
+
+/**
+ * Full resolution of an on-chain ERC-8004 agent.
+ *
+ * @param {string|object} input Anything `parseAgentRef` accepts
+ * @param {object} [opts]
+ * @param {any} [opts.ethProvider] EIP-1193 provider for chain reads
+ * @param {boolean} [opts.fresh] Bypass the session cache
+ * @returns {Promise<{
+ * ref: { chainId: number, agentId: string, registry: string },
+ * caip: string,
+ * publicUrl: string,
+ * chain: { name: string, testnet: boolean, explorer: string }|null,
+ * onchain: { owner: string|null, uri: string|null },
+ * metadata: any|null,
+ * metadataUrl: string|null,
+ * image: string|null,
+ * glbUrl: string|null,
+ * name: string,
+ * description: string,
+ * services: any[],
+ * error?: string,
+ * }>}
+ */
+export async function resolveOnchainAgent(input, { ethProvider, fresh = false } = {}) {
+ const parsed = parseAgentRef(input);
+ if (!parsed) throw new Error(`Unrecognised agent reference: ${input}`);
+
+ const ref = {
+ chainId: parsed.chainId,
+ agentId: String(parsed.agentId),
+ registry: parsed.registry || REGISTRY_DEPLOYMENTS[parsed.chainId]?.identityRegistry || null,
+ };
+ if (!ref.registry) throw new Error(`No registry deployed on chain ${ref.chainId}`);
+
+ const key = cacheKey(ref);
+ if (!fresh && _cache.has(key)) return _cache.get(key);
+
+ const chainMeta = CHAIN_META[ref.chainId] || null;
+ const base = {
+ ref,
+ caip: toCAIP10(ref),
+ publicUrl:
+ typeof location !== 'undefined' ? toPublicUrl(ref) : `/a/${ref.chainId}/${ref.agentId}`,
+ chain: chainMeta
+ ? { name: chainMeta.name, testnet: !!chainMeta.testnet, explorer: chainMeta.explorer }
+ : null,
+ onchain: { owner: null, uri: null },
+ metadata: null,
+ metadataUrl: null,
+ image: null,
+ glbUrl: null,
+ name: `Agent #${ref.agentId}`,
+ description: '',
+ services: [],
+ };
+
+ try {
+ const { owner, uri } = await getAgentOnchain({
+ chainId: ref.chainId,
+ agentId: ref.agentId,
+ ethProvider,
+ });
+ base.onchain = { owner, uri };
+
+ if (!uri) {
+ base.error = 'agentURI not set';
+ _cache.set(key, base);
+ return base;
+ }
+
+ const metaRes = await fetchAgentMetadata(uri);
+ if (!metaRes.ok) {
+ base.error = metaRes.error;
+ base.metadataUrl = metaRes.resolvedUrl || null;
+ _cache.set(key, base);
+ return base;
+ }
+ const md = metaRes.data;
+ base.metadata = md;
+ base.metadataUrl = metaRes.resolvedUrl || null;
+ base.name = (md?.name && String(md.name)) || base.name;
+ base.description = (md?.description && String(md.description)) || '';
+ base.image = md?.image ? String(md.image) : null;
+ base.services = Array.isArray(md?.services) ? md.services : [];
+ base.glbUrl = findAvatar3D(md);
+ } catch (err) {
+ base.error = err.message || String(err);
+ }
+
+ _cache.set(key, base);
+ return base;
+}
+
+/**
+ * Build a full agent-manifest/0.1 object from a resolved on-chain agent.
+ * Mirrors the shape `resolveAgentById` returns so the rest of the boot path
+ * (memory, skills, runtime) works unchanged.
+ *
+ * @param {Awaited<ReturnType<typeof resolveOnchainAgent>>} resolved
+ * @returns {object}
+ */
+export function toManifest(resolved) {
+ const services = Array.isArray(resolved.services) ? resolved.services : [];
+ const brainSvc = services.find((s) => /brain|llm|chat/i.test(s?.name || s?.type || ''));
+ const skillSvcs = services.filter((s) => /skill/i.test(s?.name || s?.type || ''));
+
+ const glb = resolved.glbUrl ? resolveUrl(resolved.glbUrl) : '';
+ const img = resolved.image ? resolveUrl(resolved.image) : '';
+
+ return {
+ spec: 'agent-manifest/0.1',
+ _baseURI: resolved.metadataUrl ? trimToDir(resolved.metadataUrl) : '',
+ _source: 'erc8004-resolver',
+ id: {
+ agentId: resolved.ref.agentId,
+ chainId: resolved.ref.chainId,
+ registry: resolved.ref.registry,
+ owner: resolved.onchain.owner || undefined,
+ walletAddress: resolved.onchain.owner || undefined,
+ caip: resolved.caip,
+ agentRegistry: agentRegistryId(resolved.ref.chainId, resolved.ref.registry),
+ },
+ name: resolved.name,
+ description: resolved.description,
+ image: img,
+ body: { uri: glb || img, format: 'gltf-binary' },
+ brain: brainSvc
+ ? { provider: 'remote', endpoint: brainSvc.endpoint }
+ : { provider: 'none' },
+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ skills: skillSvcs.map((s) => ({ name: s.name, uri: s.endpoint })),
+ memory: { mode: 'local', namespace: resolved.caip },
+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression'],
+ version: '0.1.0',
+ services,
+ x402Support: !!(resolved.metadata?.x402Support || resolved.metadata?.x402),
+ embedPolicy: resolved.metadata?.embedPolicy || null,
+ };
+}
+
+function trimToDir(url) {
+ const i = url.lastIndexOf('/');
+ return i >= 0 ? url.slice(0, i + 1) : url;
+}
+
+/**
+ * Should a given parent origin be allowed to embed this agent?
+ * Respects an `embedPolicy` field in the registration JSON:
+ *
+ * { mode: 'allowlist'|'denylist', hosts: ['example.com', '*.foo.com'] }
+ *
+ * No policy = public. Rules match hostname suffix; `*.` wildcards supported.
+ *
+ * @param {object|null} policy
+ * @param {string} host
+ * @returns {boolean}
+ */
+export function isEmbedAllowed(policy, host) {
+ if (!policy || !policy.mode || !Array.isArray(policy.hosts)) return true;
+ const match = policy.hosts.some((rule) => {
+ if (!rule) return false;
+ const r = String(rule).toLowerCase();
+ const h = String(host || '').toLowerCase();
+ if (r.startsWith('*.')) return h === r.slice(2) || h.endsWith('.' + r.slice(2));
+ return h === r;
+ });
+ return policy.mode === 'allowlist' ? match : !match;
+}
diff --git a/src/erc8004/showcase.js b/src/erc8004/showcase.js
new file mode 100644
index 000000000..a2f19cd59
--- /dev/null
+++ b/src/erc8004/showcase.js
@@ -0,0 +1,528 @@
+/**
+ * /showcase — browsable directory of every ERC-8004 agent with a 3D avatar.
+ *
+ * Reads from GET /api/showcase (backed by erc8004_agents_index, populated by
+ * api/cron/erc8004-crawl.js). Unlike /explore (search-by-input), this page is
+ * pure browse: pick a net + chains, scroll a grid of newest-minted agents,
+ * click a card to open its 3D viewer at /a/<chainId>/<agentId>.
+ *
+ * Lazy-loaded by src/app.js `_showShowcasePage`.
+ */
+
+import { CHAIN_META, supportedChainIds } from './chain-meta.js';
+import { resolveURI } from '../ipfs.js';
+
+const PAGE_SIZE = 24;
+const NET_KEY = '3dagent.showcase.net';
+const CHAINS_KEY = '3dagent.showcase.chains';
+const SORT_KEY = '3dagent.showcase.sort';
+
+const esc = (s) =>
+ String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+
+const shortAddr = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '');
+
+function loadNet() {
+ try {
+ const v = localStorage.getItem(NET_KEY);
+ if (v === 'mainnet' || v === 'testnet' || v === 'all') return v;
+ } catch {}
+ return 'mainnet';
+}
+function saveNet(v) {
+ try { localStorage.setItem(NET_KEY, v); } catch {}
+}
+
+function loadSort() {
+ try {
+ const v = localStorage.getItem(SORT_KEY);
+ if (v === 'newest' || v === 'oldest') return v;
+ } catch {}
+ return 'newest';
+}
+function saveSort(v) {
+ try { localStorage.setItem(SORT_KEY, v); } catch {}
+}
+
+function loadChains() {
+ try {
+ const raw = localStorage.getItem(CHAINS_KEY);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((n) => Number.isInteger(n));
+ } catch {
+ return [];
+ }
+}
+function saveChains(ids) {
+ try { localStorage.setItem(CHAINS_KEY, JSON.stringify(ids)); } catch {}
+}
+
+function splitChains() {
+ const ids = supportedChainIds();
+ const mainnet = [];
+ const testnet = [];
+ for (const id of ids) {
+ const m = CHAIN_META[id];
+ if (!m) continue;
+ (m.testnet ? testnet : mainnet).push(id);
+ }
+ return { mainnet, testnet };
+}
+
+/**
+ * Entry point called by app.js `_showShowcasePage`.
+ * @param {HTMLElement} container
+ */
+export function renderShowcasePage(container) {
+ const page = new ShowcasePage(container);
+ page.mount();
+ return page;
+}
+
+class ShowcasePage {
+ /** @param {HTMLElement} container */
+ constructor(container) {
+ this.container = container;
+ this._net = loadNet();
+ this._sort = loadSort();
+ this._chains = loadChains(); // empty = all of `_net`
+ this._items = [];
+ this._nextCursor = null;
+ this._total = 0;
+ this._loading = false;
+ this._reqSeq = 0;
+ this._onHashChange = () => this._readURL({ replace: true });
+ this._onScroll = () => this._maybeAutoLoad();
+ }
+
+ mount() {
+ this.container.innerHTML = `
+ <div class="showcase-shell">
+ <header class="showcase-hero">
+ <div class="showcase-hero-inner">
+ <div class="showcase-eyebrow">ERC-8004 · Directory</div>
+ <h1 class="showcase-title">Every 3D agent on-chain.</h1>
+ <p class="showcase-subtitle">
+ Browse every ERC-8004 agent with a <code>gltf</code> body — discovered across
+ ${supportedChainIds().length} chains and indexed from canonical registries. Click any
+ card to open it in the 3D viewer.
+ </p>
+ <div class="showcase-stats" data-role="stats">
+ <div class="showcase-stat">
+ <span class="showcase-stat-value" data-role="statTotal">—</span>
+ <span class="showcase-stat-label">3D agents</span>
+ </div>
+ <div class="showcase-stat">
+ <span class="showcase-stat-value">${splitChains().mainnet.length}+${splitChains().testnet.length}</span>
+ <span class="showcase-stat-label">chains</span>
+ </div>
+ <div class="showcase-stat">
+ <span class="showcase-stat-value">v2.0</span>
+ <span class="showcase-stat-label">registry</span>
+ </div>
+ </div>
+ </div>
+ </header>
+
+ <section class="showcase-controls">
+ <div class="showcase-controls-row">
+ <div class="showcase-segmented" role="tablist" data-role="netGroup">
+ <button type="button" role="tab" class="showcase-seg" data-net="mainnet">Mainnet</button>
+ <button type="button" role="tab" class="showcase-seg" data-net="testnet">Testnet</button>
+ <button type="button" role="tab" class="showcase-seg" data-net="all">All</button>
+ </div>
+ <div class="showcase-controls-spacer"></div>
+ <div class="showcase-sort">
+ <label class="showcase-sort-lbl" for="showcase-sort-sel">Sort</label>
+ <select id="showcase-sort-sel" class="showcase-sort-sel" data-role="sortSel">
+ <option value="newest">Newest</option>
+ <option value="oldest">Oldest</option>
+ </select>
+ </div>
+ </div>
+ <div class="showcase-controls-row showcase-controls-row--chains">
+ <strong class="showcase-controls-lbl">Chains</strong>
+ <div class="showcase-chain-chips" data-role="chainChips"></div>
+ <button type="button" class="showcase-chip-reset" data-role="chainReset" hidden>Clear</button>
+ </div>
+ </section>
+
+ <section class="showcase-results" data-role="results" aria-live="polite"></section>
+
+ <div class="showcase-loadmore" data-role="loadMore" hidden>
+ <button type="button" class="showcase-btn" data-role="loadMoreBtn">Load more</button>
+ </div>
+ </div>
+ `;
+
+ this._bindControls();
+ this._renderNetSegmented();
+ this._renderSortSelect();
+ this._renderChainChips();
+
+ window.addEventListener('hashchange', this._onHashChange);
+ window.addEventListener('popstate', this._onHashChange);
+ window.addEventListener('scroll', this._onScroll, { passive: true });
+
+ this._readURL({ replace: true });
+ }
+
+ destroy() {
+ window.removeEventListener('hashchange', this._onHashChange);
+ window.removeEventListener('popstate', this._onHashChange);
+ window.removeEventListener('scroll', this._onScroll);
+ }
+
+ // ── URL ↔ state ───────────────────────────────────────────────────────
+
+ _readURL({ replace }) {
+ const url = new URL(location.href);
+ const net = url.searchParams.get('net');
+ const sort = url.searchParams.get('sort');
+ const chains = url.searchParams.get('chain');
+ if (net && ['mainnet', 'testnet', 'all'].includes(net)) {
+ this._net = net;
+ saveNet(net);
+ }
+ if (sort && ['newest', 'oldest'].includes(sort)) {
+ this._sort = sort;
+ saveSort(sort);
+ }
+ if (chains !== null) {
+ const parsed = chains
+ .split(',')
+ .map((s) => Number(s.trim()))
+ .filter((n) => Number.isInteger(n) && CHAIN_META[n]);
+ this._chains = parsed;
+ saveChains(parsed);
+ }
+
+ this._renderNetSegmented();
+ this._renderSortSelect();
+ this._renderChainChips();
+ this._resetAndLoad();
+ }
+
+ _pushURL() {
+ const url = new URL(location.href);
+ if (this._net !== 'mainnet') url.searchParams.set('net', this._net);
+ else url.searchParams.delete('net');
+ if (this._sort !== 'newest') url.searchParams.set('sort', this._sort);
+ else url.searchParams.delete('sort');
+ if (this._chains.length) url.searchParams.set('chain', this._chains.join(','));
+ else url.searchParams.delete('chain');
+ history.replaceState({}, '', url.toString());
+ }
+
+ // ── Controls ──────────────────────────────────────────────────────────
+
+ _bindControls() {
+ this.container.querySelector('[data-role="netGroup"]').addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-net]');
+ if (!btn) return;
+ const next = btn.dataset.net;
+ if (next === this._net) return;
+ this._net = next;
+ saveNet(next);
+ // Clearing chain filter makes sense when flipping net (chips re-render anyway).
+ this._chains = [];
+ saveChains([]);
+ this._renderNetSegmented();
+ this._renderChainChips();
+ this._pushURL();
+ this._resetAndLoad();
+ });
+
+ this.container.querySelector('[data-role="sortSel"]').addEventListener('change', (e) => {
+ const v = e.target.value;
+ if (v !== 'newest' && v !== 'oldest') return;
+ this._sort = v;
+ saveSort(v);
+ this._pushURL();
+ this._resetAndLoad();
+ });
+
+ this.container.querySelector('[data-role="chainReset"]').addEventListener('click', () => {
+ this._chains = [];
+ saveChains([]);
+ this._renderChainChips();
+ this._pushURL();
+ this._resetAndLoad();
+ });
+
+ this.container.querySelector('[data-role="loadMoreBtn"]').addEventListener('click', () => {
+ this._loadMore();
+ });
+ }
+
+ _renderNetSegmented() {
+ const group = this.container.querySelector('[data-role="netGroup"]');
+ group.querySelectorAll('button[data-net]').forEach((btn) => {
+ const active = btn.dataset.net === this._net;
+ btn.classList.toggle('showcase-seg--active', active);
+ btn.setAttribute('aria-selected', active ? 'true' : 'false');
+ });
+ }
+
+ _renderSortSelect() {
+ const sel = this.container.querySelector('[data-role="sortSel"]');
+ sel.value = this._sort;
+ }
+
+ _renderChainChips() {
+ const root = this.container.querySelector('[data-role="chainChips"]');
+ const { mainnet, testnet } = splitChains();
+ const pool = this._net === 'mainnet' ? mainnet : this._net === 'testnet' ? testnet : [...mainnet, ...testnet];
+
+ const chip = (id) => {
+ const m = CHAIN_META[id];
+ if (!m) return '';
+ const active = this._chains.includes(id);
+ return `
+ <button type="button"
+ class="showcase-chip ${active ? 'showcase-chip--active' : ''} ${m.testnet ? 'showcase-chip--testnet' : ''}"
+ data-chain="${id}"
+ title="${esc(m.name)}"
+ aria-pressed="${active ? 'true' : 'false'}"
+ >
+ <span class="showcase-chip-dot"></span>
+ ${esc(m.shortName || m.name)}
+ </button>
+ `;
+ };
+
+ root.innerHTML = pool.map(chip).join('');
+ root.querySelectorAll('.showcase-chip').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const id = Number(btn.dataset.chain);
+ const idx = this._chains.indexOf(id);
+ if (idx >= 0) this._chains.splice(idx, 1);
+ else this._chains.push(id);
+ saveChains(this._chains);
+ this._renderChainChips();
+ this._pushURL();
+ this._resetAndLoad();
+ });
+ });
+
+ const reset = this.container.querySelector('[data-role="chainReset"]');
+ reset.hidden = this._chains.length === 0;
+ }
+
+ // ── Data ──────────────────────────────────────────────────────────────
+
+ _resetAndLoad() {
+ this._items = [];
+ this._nextCursor = null;
+ this._reqSeq++;
+ this._renderResults({ skeleton: true });
+ this._loadMore({ first: true });
+ }
+
+ async _loadMore({ first = false } = {}) {
+ if (this._loading) return;
+ if (!first && !this._nextCursor) return;
+ this._loading = true;
+ const seq = this._reqSeq;
+ this._setLoadMoreState();
+
+ const params = new URLSearchParams();
+ params.set('net', this._net);
+ params.set('sort', this._sort);
+ params.set('limit', String(PAGE_SIZE));
+ if (this._chains.length) params.set('chain', this._chains.join(','));
+ if (this._nextCursor) params.set('cursor', this._nextCursor);
+
+ try {
+ const res = await fetch('/api/showcase?' + params.toString(), {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw new Error(`HTTP ${res.status}${text ? ': ' + text.slice(0, 200) : ''}`);
+ }
+ const data = await res.json();
+ if (seq !== this._reqSeq) return; // superseded
+ const agents = Array.isArray(data.agents) ? data.agents : [];
+ this._items = this._items.concat(agents);
+ this._nextCursor = data.next_cursor || null;
+ this._total = Number(data.total) || this._total;
+ this._renderStats();
+ this._renderResults();
+ } catch (err) {
+ if (seq !== this._reqSeq) return;
+ this._renderError(err.message || String(err));
+ } finally {
+ if (seq === this._reqSeq) this._loading = false;
+ this._setLoadMoreState();
+ }
+ }
+
+ _maybeAutoLoad() {
+ if (this._loading || !this._nextCursor) return;
+ const more = this.container.querySelector('[data-role="loadMore"]');
+ if (!more || more.hidden) return;
+ const rect = more.getBoundingClientRect();
+ if (rect.top < window.innerHeight + 400) this._loadMore();
+ }
+
+ // ── Render ────────────────────────────────────────────────────────────
+
+ _renderStats() {
+ const el = this.container.querySelector('[data-role="statTotal"]');
+ if (el) el.textContent = formatCount(this._total);
+ }
+
+ _setLoadMoreState() {
+ const wrap = this.container.querySelector('[data-role="loadMore"]');
+ const btn = this.container.querySelector('[data-role="loadMoreBtn"]');
+ if (!wrap || !btn) return;
+ wrap.hidden = !this._nextCursor;
+ btn.disabled = !!this._loading;
+ btn.textContent = this._loading ? 'Loading…' : 'Load more';
+ }
+
+ _renderResults({ skeleton = false } = {}) {
+ const out = this.container.querySelector('[data-role="results"]');
+ if (skeleton) {
+ out.innerHTML = `
+ <div class="showcase-grid" aria-busy="true">
+ ${Array.from({ length: 8 }, () => `
+ <div class="showcase-card showcase-card--skel">
+ <div class="showcase-skel-img"></div>
+ <div class="showcase-skel-line"></div>
+ <div class="showcase-skel-line showcase-skel-line--short"></div>
+ </div>
+ `).join('')}
+ </div>
+ `;
+ return;
+ }
+
+ if (!this._items.length) {
+ out.innerHTML = `
+ <div class="showcase-empty">
+ <div class="showcase-empty-art">✨</div>
+ <h3>No 3D agents found.</h3>
+ <p class="showcase-muted">
+ Try a different chain filter, flip to ${this._net === 'mainnet' ? 'Testnet' : 'Mainnet'}, or
+ <a href="/deploy">deploy your own</a>.
+ </p>
+ </div>
+ `;
+ return;
+ }
+
+ out.innerHTML = `
+ <div class="showcase-grid">
+ ${this._items.map((a) => renderCard(a)).join('')}
+ </div>
+ `;
+ this._wireCardShare(out);
+ }
+
+ _renderError(message) {
+ const out = this.container.querySelector('[data-role="results"]');
+ out.innerHTML = `
+ <div class="showcase-empty showcase-empty--error">
+ <div class="showcase-empty-art">⚠️</div>
+ <h3>Couldn't load the directory.</h3>
+ <p class="showcase-muted">${esc(message)}</p>
+ <button type="button" class="showcase-btn" data-role="retry">Retry</button>
+ </div>
+ `;
+ out.querySelector('[data-role="retry"]').addEventListener('click', () => this._resetAndLoad());
+ }
+
+ _wireCardShare(root) {
+ root.querySelectorAll('[data-role="card-share"]').forEach((btn) => {
+ btn.addEventListener('click', async (e) => {
+ e.preventDefault();
+ const href = btn.dataset.share;
+ if (!href) return;
+ const url = new URL(href, location.origin).toString();
+ try {
+ await navigator.clipboard.writeText(url);
+ btn.textContent = 'Copied ✓';
+ setTimeout(() => (btn.textContent = 'Share'), 1400);
+ } catch {
+ window.prompt('Copy link:', url);
+ }
+ });
+ });
+ }
+}
+
+// ─── Card ──────────────────────────────────────────────────────────────────
+
+/**
+ * @param {object} a Shaped agent from /api/showcase
+ */
+function renderCard(a) {
+ const chainMeta = CHAIN_META[a.chainId];
+ const chainShort = chainMeta?.shortName || a.chainName || `#${a.chainId}`;
+ const img = a.image ? resolveURI(a.image) : '';
+ const title = esc(a.name || `Agent #${a.agentId}`);
+ const descLine = a.description
+ ? `<p class="showcase-card-desc">${esc(truncate(a.description, 140))}</p>`
+ : '';
+ const ownerLine = a.owner
+ ? `<a class="showcase-card-owner" href="${esc(a.ownerExplorerUrl || '#')}" target="_blank" rel="noopener" title="${esc(a.owner)}">Owner ${esc(shortAddr(a.owner))} ↗</a>`
+ : '';
+
+ const tags = [];
+ tags.push(`<span class="showcase-tag showcase-tag--3d">3D</span>`);
+ if (a.x402Support) tags.push(`<span class="showcase-tag showcase-tag--x402">x402 💳</span>`);
+ const serviceTypes = new Set();
+ for (const s of a.services || []) {
+ const name = String(s?.name || '').toLowerCase();
+ if (name === 'a2a' || name.startsWith('a2a')) serviceTypes.add('A2A');
+ else if (name === 'mcp' || name.startsWith('mcp')) serviceTypes.add('MCP');
+ else if (name === 'oasf') serviceTypes.add('OASF');
+ }
+ for (const t of serviceTypes) tags.push(`<span class="showcase-tag">${t}</span>`);
+
+ return `
+ <article class="showcase-card">
+ <a class="showcase-card-thumb" href="${esc(a.viewerUrl)}" aria-label="Open Agent #${esc(a.agentId)} in 3D viewer">
+ ${img ? `<img src="${esc(img)}" alt="" loading="lazy" />` : `<div class="showcase-card-ph">🤖</div>`}
+ <span class="showcase-chain-badge ${chainMeta?.testnet ? 'showcase-chain-badge--testnet' : ''}" title="${esc(chainMeta?.name || '')}">
+ ${esc(chainShort)}
+ </span>
+ <span class="showcase-card-3dpill">▶ 3D</span>
+ </a>
+ <div class="showcase-card-body">
+ <div class="showcase-card-head">
+ <a class="showcase-card-title" href="${esc(a.viewerUrl)}">${title}</a>
+ <span class="showcase-card-id">#${esc(a.agentId)}</span>
+ </div>
+ ${descLine}
+ <div class="showcase-card-tags">${tags.join('')}</div>
+ ${ownerLine}
+ <div class="showcase-card-actions">
+ <a class="showcase-btn showcase-btn--sm showcase-btn--primary" href="${esc(a.viewerUrl)}">Open 3D ↗</a>
+ ${a.tokenExplorerUrl ? `<a class="showcase-btn showcase-btn--sm" href="${esc(a.tokenExplorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}
+ <button type="button" class="showcase-btn showcase-btn--sm showcase-btn--ghost"
+ data-role="card-share" data-share="${esc(a.viewerUrl)}" title="Copy shareable link">Share</button>
+ </div>
+ </div>
+ </article>
+ `;
+}
+
+function truncate(s, n) {
+ s = String(s || '');
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
+}
+
+function formatCount(n) {
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
+ if (n >= 1_000) return (n / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';
+ return String(n);
+}
diff --git a/src/erc8004/templates.js b/src/erc8004/templates.js
deleted file mode 100644
index a820af4bb..000000000
--- a/src/erc8004/templates.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Pre-filled agent templates — seed the Create wizard with one click.
- *
- * Each template populates Identity (name, description) + Services. Users can
- * still edit everything before deploying.
- */
-
-/**
- * @typedef {Object} AgentTemplate
- * @property {string} id Unique key.
- * @property {string} emoji Display icon.
- * @property {string} name Card title & default agent name.
- * @property {string} description Card copy & default agent description.
- * @property {Array<{name: string, endpoint: string, version?: string}>} services
- * @property {{trust?: string[], x402?: boolean}} [config]
- */
-
-/** @type {AgentTemplate[]} */
-export const TEMPLATES = [
- {
- id: 'defi-trading',
- emoji: '📈',
- name: 'DeFi Trading Agent',
- description: 'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
- ],
- config: { trust: ['reputation'], x402: true },
- },
- {
- id: 'support-bot',
- emoji: '🎧',
- name: 'Customer Support Bot',
- description: 'AI-powered support agent for handling tickets, FAQ queries, and multi-language communication.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- ],
- config: { trust: ['reputation'], x402: false },
- },
- {
- id: 'code-review',
- emoji: '🔍',
- name: 'Code Review Agent',
- description: 'Automated code analysis, security auditing, gas optimization, and best practice enforcement.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
- ],
- config: { trust: ['reputation', 'validation'], x402: true },
- },
- {
- id: 'data-analysis',
- emoji: '📊',
- name: 'Data Analysis Agent',
- description: 'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- { name: 'OASF', endpoint: 'https://your-agent.example/oasf', version: '1.0' },
- ],
- config: { trust: ['reputation'], x402: true },
- },
- {
- id: 'content-creator',
- emoji: '✍️',
- name: 'Content Creator',
- description: 'AI content generation for social media, documentation, technical writing, and marketing.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- ],
- config: { trust: ['reputation'], x402: true },
- },
- {
- id: 'research-assistant',
- emoji: '🔬',
- name: 'Research Assistant',
- description: 'Deep research on protocols, tokens, governance proposals, and market trends.',
- services: [
- { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
- { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
- ],
- config: { trust: ['reputation'], x402: true },
- },
-];
-
-/**
- * @param {string} id
- * @returns {AgentTemplate|null}
- */
-export function getTemplate(id) {
- return TEMPLATES.find((t) => t.id === id) || null;
-}
diff --git a/src/manifest.js b/src/manifest.js
index ba110fc2c..b3d4081e3 100644
--- a/src/manifest.js
+++ b/src/manifest.js
@@ -3,6 +3,7 @@
import { JsonRpcProvider, Contract } from 'ethers';
import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
+import { findAvatar3D } from './erc8004/queries.js';
import { resolveURI, fetchWithFallback } from './ipfs.js';
const CHAIN_ALIASES = {
@@ -99,6 +100,10 @@ export function normalize(json, { baseURI = '' } = {}) {
// ERC-8004 registration JSON — adapt to manifest shape
if (json.type && json.type.includes('eip-8004')) {
const registration = json.registrations?.[0] || {};
+ // The GLB lives in services[{name:'avatar'}] per our convention. The
+ // top-level `image` field is a 2D thumbnail (NFT-marketplace compat) —
+ // only fall back to it when no 3D body was declared.
+ const glbUri = findAvatar3D(json);
return {
spec: 'agent-manifest/0.1',
_baseURI: baseURI,
@@ -107,13 +112,16 @@ export function normalize(json, { baseURI = '' } = {}) {
name: json.name,
description: json.description,
image: json.image,
- body: { uri: json.image, format: 'gltf-binary' },
+ body: { uri: resolveURI(glbUri || json.image || ''), format: 'gltf-binary' },
brain: { provider: 'none' },
voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
skills: [],
memory: { mode: 'local' },
tools: ['wave', 'lookAt', 'play_clip', 'setExpression'],
version: '0.1.0',
+ services: Array.isArray(json.services) ? json.services : [],
+ x402Support: !!json.x402Support,
+ embedPolicy: json.embedPolicy || null,
};
}
diff --git a/style.css b/style.css
index 59dfff1d5..477a7272a 100644
--- a/style.css
+++ b/style.css
@@ -4993,6 +4993,24 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {
margin-bottom: var(--space-sm);
}
+.erc8004-checkbox {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-md);
+ font-size: var(--text-sm);
+ color: rgba(255, 255, 255, 0.75);
+ cursor: pointer;
+ user-select: none;
+}
+
+.erc8004-checkbox input[type='checkbox'] {
+ width: 16px;
+ height: 16px;
+ accent-color: #b15bff;
+ cursor: pointer;
+}
+
.erc8004-qr-canvas-wrap {
display: flex;
justify-content: center;
@@ -5013,6 +5031,79 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {
margin: 0 0 var(--space-sm);
}
+/* Embed snippet modal */
+.erc8004-embed-tabs {
+ display: flex;
+ gap: 2px;
+ margin: var(--space-md) 0 0;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
+ padding: 0;
+ flex-wrap: wrap;
+}
+.erc8004-embed-tabs .erc8004-tab {
+ padding: 8px 14px;
+ background: transparent;
+ border: 0;
+ border-bottom: 2px solid transparent;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: var(--text-sm);
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s;
+}
+.erc8004-embed-tabs .erc8004-tab:hover {
+ color: rgba(255, 255, 255, 0.9);
+}
+.erc8004-embed-tabs .erc8004-tab.is-active {
+ color: #fff;
+ border-bottom-color: var(--accent, #8b5cf6);
+}
+.erc8004-embed-panels {
+ padding: var(--space-md) 0;
+}
+.erc8004-embed-panels > [data-panel] {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+}
+.erc8004-embed-panels > [data-panel][hidden] {
+ display: none;
+}
+.erc8004-code {
+ width: 100%;
+ box-sizing: border-box;
+ background: rgba(0, 0, 0, 0.4);
+ color: #e5e7eb;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: var(--radius-sm);
+ padding: 10px 12px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ resize: vertical;
+ user-select: all;
+ white-space: pre;
+ overflow-x: auto;
+}
+textarea.erc8004-code {
+ min-height: 48px;
+}
+.erc8004-embed-policy {
+ margin-top: var(--space-md);
+ padding-top: var(--space-md);
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+}
+.erc8004-embed-policy summary {
+ cursor: pointer;
+ color: rgba(255, 255, 255, 0.65);
+ font-size: var(--text-sm);
+ margin-bottom: var(--space-sm);
+}
+.erc8004-embed-policy summary:hover {
+ color: #fff;
+}
+
/* Footer */
.erc8004-footer {
margin-top: var(--space-lg);
@@ -5085,3 +5176,591 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {
.erc8004-footer-credit a {
color: rgba(255, 255, 255, 0.55);
}
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * /explore — ERC-8004 agent marketplace
+ * Lobehub-plugin-grid × etherscan-NFT-detail hybrid. Uses site tokens.
+ * ───────────────────────────────────────────────────────────────────────── */
+
+.explore-main {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-lg);
+}
+
+.explore-hero {
+ text-align: center;
+ padding: var(--space-2xl) 0 var(--space-xl);
+}
+.explore-hero h2 {
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: clamp(2rem, 4vw, 3.2rem);
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: var(--space-md) 0 var(--space-sm);
+ color: #fff;
+}
+.explore-sub {
+ max-width: 560px;
+ margin: 0 auto;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 15px;
+ line-height: 1.55;
+}
+.explore-hero-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 14px;
+ background: var(--accent-soft);
+ border: 1px solid var(--accent);
+ border-radius: 99px;
+ color: var(--accent);
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+}
+.explore-hero-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 10px var(--accent);
+}
+
+.explore-stats {
+ display: flex;
+ justify-content: center;
+ gap: var(--space-xl);
+ margin-top: var(--space-xl);
+ flex-wrap: wrap;
+}
+.explore-stat {
+ text-align: center;
+}
+.explore-stat-value {
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: var(--accent);
+}
+.explore-stat-label {
+ font-size: 11px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.45);
+ margin-top: 2px;
+}
+
+.explore-controls {
+ display: flex;
+ gap: var(--space-md);
+ align-items: center;
+ flex-wrap: wrap;
+ margin: var(--space-xl) 0 var(--space-lg);
+ padding: var(--space-md);
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-md);
+}
+.explore-search {
+ flex: 1 1 260px;
+}
+.explore-search input {
+ width: 100%;
+ padding: 10px 14px;
+ background: rgba(0, 0, 0, 0.4);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-sm);
+ color: #fff;
+ font: inherit;
+ font-size: 14px;
+}
+.explore-search input:focus {
+ outline: none;
+ border-color: var(--accent);
+ background: rgba(0, 0, 0, 0.6);
+}
+.explore-chips {
+ display: flex;
+ gap: 6px;
+}
+.explore-chip {
+ padding: 8px 14px;
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: var(--radius-sm);
+ color: rgba(255, 255, 255, 0.6);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.15s;
+}
+.explore-chip:hover {
+ border-color: rgba(255, 255, 255, 0.25);
+ color: #fff;
+}
+.explore-chip.active {
+ background: var(--accent-soft);
+ border-color: var(--accent);
+ color: var(--accent);
+}
+.explore-chain-select {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 13px;
+}
+.explore-chain-select select {
+ padding: 8px 10px;
+ background: rgba(0, 0, 0, 0.4);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: var(--radius-sm);
+ color: #fff;
+ font: inherit;
+ font-size: 13px;
+}
+
+.explore-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: var(--space-md);
+}
+
+.explore-card {
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ transition:
+ border-color 0.15s,
+ transform 0.15s,
+ background 0.15s;
+ display: flex;
+ flex-direction: column;
+}
+.explore-card:hover {
+ border-color: rgba(255, 255, 255, 0.18);
+ transform: translateY(-2px);
+ background: rgba(255, 255, 255, 0.04);
+}
+.explore-card--3d:hover {
+ border-color: var(--accent);
+}
+
+.explore-card-thumb {
+ position: relative;
+ display: block;
+ aspect-ratio: 1 / 1;
+ background: linear-gradient(135deg, #111 0%, #1a1a1f 100%);
+ overflow: hidden;
+ text-decoration: none;
+}
+.explore-card-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+.explore-card-ph {
+ display: grid;
+ place-items: center;
+ height: 100%;
+ font-size: 48px;
+ opacity: 0.4;
+}
+.explore-card-play {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ font-size: 34px;
+ color: #fff;
+ text-shadow: 0 2px 14px rgba(0, 0, 0, 0.6);
+ opacity: 0;
+ background: rgba(0, 0, 0, 0.35);
+ transition: opacity 0.2s;
+}
+.explore-card--3d:hover .explore-card-play {
+ opacity: 1;
+}
+
+.explore-card-body {
+ padding: var(--space-md);
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ flex: 1;
+}
+.explore-card-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+}
+.explore-card-name {
+ margin: 0;
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 15px;
+ font-weight: 600;
+ color: #fff;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.explore-card-id {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.35);
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ flex-shrink: 0;
+}
+.explore-card-badges {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+}
+.explore-badge {
+ font-size: 10px;
+ padding: 2px 7px;
+ border-radius: 99px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ background: rgba(255, 255, 255, 0.06);
+ color: rgba(255, 255, 255, 0.7);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+}
+.explore-badge--3d {
+ background: var(--accent-soft);
+ color: var(--accent);
+ border-color: var(--accent);
+}
+.explore-badge--x402 {
+ background: rgba(124, 58, 237, 0.2);
+ color: #c4b5fd;
+ border-color: rgba(124, 58, 237, 0.4);
+}
+.explore-card-desc {
+ margin: 0;
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.55);
+ line-height: 1.45;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.explore-card-svcs {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+}
+.explore-svc {
+ font-size: 10px;
+ padding: 2px 6px;
+ background: rgba(255, 255, 255, 0.04);
+ color: rgba(255, 255, 255, 0.55);
+ border-radius: 4px;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+}
+.explore-card-foot {
+ margin-top: auto;
+ padding-top: 8px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ border-top: 1px solid rgba(255, 255, 255, 0.05);
+ gap: 8px;
+}
+.explore-card-owner {
+ font-size: 11px;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+}
+.explore-card-owner:hover {
+ color: var(--accent);
+}
+.explore-card-actions {
+ display: flex;
+ gap: 10px;
+}
+.explore-card-link {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.7);
+ text-decoration: none;
+ font-weight: 500;
+}
+.explore-card-link:hover {
+ color: var(--accent);
+}
+
+.explore-status {
+ text-align: center;
+ padding: var(--space-lg) 0;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 13px;
+}
+.explore-empty {
+ padding: var(--space-xl);
+ border: 1px dashed rgba(255, 255, 255, 0.1);
+ border-radius: var(--radius-md);
+ color: rgba(255, 255, 255, 0.5);
+}
+.explore-error {
+ padding: var(--space-md);
+ background: rgba(239, 68, 68, 0.08);
+ border: 1px solid rgba(239, 68, 68, 0.3);
+ border-radius: var(--radius-sm);
+ color: #fca5a5;
+}
+
+.explore-load-more-wrap {
+ display: flex;
+ justify-content: center;
+ padding: var(--space-lg) 0;
+}
+.explore-load-more {
+ padding: 10px 24px;
+ background: var(--accent-soft);
+ border: 1px solid var(--accent);
+ border-radius: var(--radius-sm);
+ color: var(--accent);
+ font: inherit;
+ font-weight: 600;
+ font-size: 14px;
+ cursor: pointer;
+ transition: all 0.15s;
+}
+.explore-load-more:hover {
+ background: var(--accent);
+ color: #fff;
+}
+
+/* ─────────────────────────────────────────────────────────────────────────
+ Embed modal — shared by /explore + Search tab
+ ─────────────────────────────────────────────────────────────────────── */
+.embed-modal {
+ position: fixed;
+ inset: 0;
+ z-index: 9999;
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ animation: embed-modal-in 0.18s ease-out;
+}
+@keyframes embed-modal-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+.embed-modal__backdrop {
+ position: absolute;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ backdrop-filter: blur(6px);
+}
+.embed-modal__panel {
+ position: relative;
+ width: min(640px, 100%);
+ max-height: calc(100vh - 32px);
+ background: #0f1115;
+ color: #e5e5e5;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 16px;
+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+.embed-modal__head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 20px 20px 12px;
+}
+.embed-modal__title {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ letter-spacing: -0.3px;
+}
+.embed-modal__sub {
+ margin: 4px 0 0;
+ font-size: 13px;
+ color: rgba(229, 229, 229, 0.55);
+}
+.embed-modal__close {
+ background: transparent;
+ border: 0;
+ color: rgba(229, 229, 229, 0.6);
+ font-size: 28px;
+ line-height: 1;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all 0.15s;
+}
+.embed-modal__close:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+}
+.embed-modal__tabs {
+ display: flex;
+ gap: 2px;
+ padding: 0 20px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+.embed-modal__tabs::-webkit-scrollbar {
+ display: none;
+}
+.embed-tab {
+ background: transparent;
+ border: 0;
+ color: rgba(229, 229, 229, 0.55);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ padding: 10px 14px;
+ cursor: pointer;
+ border-bottom: 2px solid transparent;
+ margin-bottom: -1px;
+ white-space: nowrap;
+ transition: all 0.15s;
+}
+.embed-tab:hover {
+ color: #e5e5e5;
+}
+.embed-tab.is-active {
+ color: #fff;
+ border-bottom-color: #8b5cf6;
+}
+.embed-modal__body {
+ padding: 20px;
+ overflow-y: auto;
+ flex: 1;
+}
+.embed-pane {
+ display: none;
+}
+.embed-pane.is-active {
+ display: block;
+}
+.embed-pane__hint {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: rgba(229, 229, 229, 0.6);
+ line-height: 1.5;
+}
+.embed-snippet {
+ display: block;
+ width: 100%;
+ background: #05070a;
+ color: #d4d4d4;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ padding: 12px 14px;
+ font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
+ font-size: 12px;
+ line-height: 1.55;
+ resize: vertical;
+ box-sizing: border-box;
+ outline: none;
+}
+.embed-snippet:focus {
+ border-color: rgba(139, 92, 246, 0.5);
+ box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.15);
+}
+.embed-snippet--input {
+ resize: none;
+}
+.embed-copy-btn {
+ margin-top: 10px;
+ background: linear-gradient(135deg, #8b5cf6, #6d28d9);
+ color: #fff;
+ border: 0;
+ border-radius: 8px;
+ padding: 8px 16px;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition:
+ transform 0.1s,
+ box-shadow 0.15s;
+}
+.embed-copy-btn:hover {
+ box-shadow: 0 4px 14px rgba(139, 92, 246, 0.4);
+}
+.embed-copy-btn:active {
+ transform: translateY(1px);
+}
+.embed-modal__foot {
+ padding: 12px 20px;
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+ display: flex;
+ gap: 16px;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+}
+.embed-foot-link {
+ font-size: 12px;
+ color: rgba(229, 229, 229, 0.55);
+ text-decoration: none;
+}
+.embed-foot-link:hover {
+ color: #8b5cf6;
+}
+.explore-card-link--ghost {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ color: rgba(229, 229, 229, 0.75);
+ cursor: pointer;
+ font: inherit;
+ font-size: 12px;
+ padding: 4px 10px;
+ border-radius: 6px;
+}
+.explore-card-link--ghost:hover {
+ border-color: rgba(139, 92, 246, 0.5);
+ color: #fff;
+}
+@media (max-width: 560px) {
+ .embed-modal__panel {
+ max-height: calc(100vh - 16px);
+ }
+ .embed-modal__head,
+ .embed-modal__body,
+ .embed-modal__foot {
+ padding-left: 14px;
+ padding-right: 14px;
+ }
+ .embed-modal__tabs {
+ padding-left: 14px;
+ padding-right: 14px;
+ }
+}
diff --git a/vercel.json b/vercel.json
index 92fb46414..67060603b 100644
--- a/vercel.json
+++ b/vercel.json
@@ -44,6 +44,7 @@
{ "src": "/api/agent-memory/([^/]+)", "dest": "/api/agent-memory" },
{ "src": "/api/agent-memory", "dest": "/api/agent-memory" },
{ "src": "/api/agent/([^/]+)/og", "dest": "/api/agent-og?id=$1" },
+ { "src": "/api/a/(\\d+)/(\\d+)/og", "dest": "/api/a-og?chain=$1&id=$2" },
{ "src": "/api/oembed", "dest": "/api/agent-oembed" },
{ "src": "/agent/([^/]+)/edit", "dest": "/agent-edit.html" },
{ "src": "/agent/([^/]+)/embed", "dest": "/agent-embed.html" },
@@ -117,8 +118,13 @@
{ "src": "/create", "dest": "/create.html" },
{ "src": "/create/", "dest": "/create.html" },
{ "src": "/home", "dest": "/home.html" },
- { "src": "/explore", "dest": "/app.html" },
+ { "src": "/explore", "dest": "/public/explore/index.html" },
+ { "src": "/explore/", "dest": "/public/explore/index.html" },
+ { "src": "/explore/(.*)", "dest": "/public/explore/$1" },
+ { "src": "/a/(\\d+)/(\\d+)/embed", "dest": "/a-embed.html" },
+ { "src": "/a/(\\d+)/(\\d+)", "dest": "/api/a-page?chain=$1&id=$2" },
{ "src": "/a/(.*)", "dest": "/app.html" },
{ "src": "/(.*)", "dest": "/public/$1" }
- ]
+ ],
+ "crons": [{ "path": "/api/cron/erc8004-crawl", "schedule": "*/15 * * * *" }]
}
diff --git a/vite.config.js b/vite.config.js
index 5915f1587..f324f5d58 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -32,6 +32,7 @@ const appConfig = {
'agent-home': resolve(__dirname, 'agent-home.html'),
'agent-edit': resolve(__dirname, 'agent-edit.html'),
'agent-embed': resolve(__dirname, 'agent-embed.html'),
+ 'a-embed': resolve(__dirname, 'a-embed.html'),
},
},
},
@@ -44,7 +45,8 @@ const appConfig = {
'/app': resolve(root, 'app.html'),
'/login': resolve(root, 'public/login.html'),
'/deploy': resolve(root, 'app.html'),
- '/explore': resolve(root, 'app.html'),
+ '/explore': resolve(root, 'public/explore/index.html'),
+ '/explore/': resolve(root, 'public/explore/index.html'),
'/features': resolve(root, 'features.html'),
'/create': resolve(root, 'create.html'),
'/dashboard': resolve(root, 'public/dashboard/index.html'),
@@ -62,8 +64,11 @@ const appConfig = {
filePath = resolve(root, 'agent-embed.html');
else if (!filePath && /^\/agent\/[^/]+$/.test(path))
filePath = resolve(root, 'agent-home.html');
- // /a/<chainId>/<agentId> — public on-chain agent viewer.
- else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}$/.test(path))
+ // /a/<chainId>/<agentId>/embed or /a/<chainId>/<registry>/<agentId>/embed → iframe viewer
+ else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/embed\/?$/.test(path))
+ filePath = resolve(root, 'a-embed.html');
+ // /a/<chainId>/<agentId> or /a/<chainId>/<registry>/<agentId>
+ else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/?$/.test(path))
filePath = resolve(root, 'app.html');
if (!filePath) return next();
try {