Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add follow mode functionality and enhance avatar controls; update schema for agent identities
swarmsyy855943e2e4d4
diff --git a/.gitignore b/.gitignoreindex 8ad90797f..354a343c6 100644--- a/.gitignore+++ b/.gitignore@@ -8,3 +8,4 @@ npm-debug.log*.env.local.env.*.local+.env*.localdiff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex cb7301487..9ff5a22e8 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -198,10 +198,10 @@ create table if not exists plan_quotas ();insert into plan_quotas (plan, max_avatars, max_bytes_per_avatar, max_total_bytes, mcp_calls_per_day) values- ('free', 10, 25 * 1024 * 1024, 250 * 1024 * 1024, 1000),- ('pro', 500, 50 * 1024 * 1024, 25 * 1024 * 1024 * 1024, 50000),- ('team', 5000, 100 * 1024 * 1024, 500 * 1024 * 1024 * 1024, 500000),- ('enterprise', 100000, 500 * 1024 * 1024, 10 * 1024 * 1024 * 1024 * 1024, 10000000)+ ('free', 10, 26214400, 262144000, 1000),+ ('pro', 500, 52428800, 26843545600, 50000),+ ('team', 5000, 104857600, 536870912000, 500000),+ ('enterprise', 100000, 524288000, 10995116277760, 10000000)on conflict (plan) do update setmax_avatars = excluded.max_avatars,max_bytes_per_avatar = excluded.max_bytes_per_avatar,@@ -257,6 +257,14 @@ create index if not exists agent_identities_usercreate index if not exists agent_identities_walleton agent_identities(wallet_address) where wallet_address is not null;+-- Additive migrations for agent_identities columns added after initial deployment.+alter table agent_identities add column if not exists wallet_address text;+alter table agent_identities add column if not exists chain_id int;+alter table agent_identities add column if not exists erc8004_agent_id bigint;+alter table agent_identities add column if not exists erc8004_registry text;+alter table agent_identities add column if not exists registration_cid text;+alter table agent_identities add column if not exists home_url text;+-- ── agent_memories — the agent's persistent context ──────────────────────────create table if not exists agent_memories (id uuid primary key default gen_random_uuid(),@@ -272,7 +280,7 @@ create table if not exists agent_memories (create index if not exists agent_memories_agent_typeon agent_memories(agent_id, type, created_at desc)- where expires_at is null or expires_at > now();+ where expires_at is null;-- ── agent_actions — append-only signed history ───────────────────────────────create table if not exists agent_actions (diff --git a/api/agents/[id].js b/api/agents/[id].jsindex e0fda6292..bf09b96a4 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -3,9 +3,9 @@* Routes to the appropriate handler in api/agents.js*/import { handleGetOne, handleWallet } from '../agents.js';-import { cors, error } from '../_lib/http.js';+import { cors, error, wrap } from '../_lib/http.js';-export default async function handler(req, res) {+export default wrap(async function handler(req, res) {const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean);// parts: ['api', 'agents', ':id'] or ['api', 'agents', ':id', 'wallet']@@ -19,4 +19,4 @@ export default async function handler(req, res) {if (sub === 'wallet') return handleWallet(req, res, id);return handleGetOne(req, res, id);-}+})diff --git a/api/agents/by-wallet.js b/api/agents/by-wallet.jsnew file mode 100644index 000000000..51569a277--- /dev/null+++ b/api/agents/by-wallet.js@@ -0,0 +1,62 @@+/**+ * GET /api/agents/by-wallet?address=0x...&chain_id=84532+ *+ * Lists agents registered in our DB whose wallet_address matches the query.+ * Unauthenticated; returns only public fields (no user_id, no raw meta).+ * Pair with on-chain enumeration (balanceOf + tokenOfOwnerByIndex) on the+ * client to also surface agents minted outside this app.+ */++import { sql } from '../_lib/db.js';+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const raw = (url.searchParams.get('address') || '').trim();+ if (!/^0x[a-fA-F0-9]{40}$/.test(raw)) {+ return error(res, 400, 'validation_error', 'invalid wallet address');+ }+ const address = raw.toLowerCase();+ const chainId = Number(url.searchParams.get('chain_id')) || null;++ const rows = chainId+ ? await sql`+ SELECT id, name, description, avatar_id, home_url,+ erc8004_agent_id, erc8004_registry, chain_id,+ wallet_address, created_at+ FROM agent_identities+ WHERE lower(wallet_address) = ${address}+ AND chain_id = ${chainId}+ AND deleted_at IS NULL+ ORDER BY created_at ASC`+ : await sql`+ SELECT id, name, description, avatar_id, home_url,+ erc8004_agent_id, erc8004_registry, chain_id,+ wallet_address, created_at+ FROM agent_identities+ WHERE lower(wallet_address) = ${address}+ AND deleted_at IS NULL+ ORDER BY created_at ASC`;++ return json(res, 200, {+ agents: rows.map((r) => ({+ id: r.id,+ name: r.name,+ description: r.description,+ avatar_id: r.avatar_id,+ home_url: r.home_url || `/agent/${r.id}`,+ erc8004_agent_id: r.erc8004_agent_id != null ? String(r.erc8004_agent_id) : null,+ erc8004_registry: r.erc8004_registry,+ chain_id: r.chain_id,+ wallet_address: r.wallet_address,+ created_at: r.created_at,+ })),+ });+});diff --git a/api/config.js b/api/config.jsnew file mode 100644index 000000000..760da56b4--- /dev/null+++ b/api/config.js@@ -0,0 +1,14 @@+// Public client-config. Returns non-secret config values the browser needs+// (Privy app id, etc.). Lets us keep values in env vars instead of hardcoded+// in static HTML in public/.++import { cors, json, method, wrap } from './_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['GET'])) return;++ return json(res, 200, {+ privyAppId: process.env.PRIVY_APP_ID || '',+ });+});diff --git a/api/erc8004/pin.js b/api/erc8004/pin.jsnew file mode 100644index 000000000..dc14bc20d--- /dev/null+++ b/api/erc8004/pin.js@@ -0,0 +1,60 @@+import { PutObjectCommand } from '@aws-sdk/client-s3';+import { r2, publicUrl } from '../_lib/r2.js';+import { cors, error, json, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';++const ALLOWED = new Set([+ 'model/gltf-binary',+ 'model/gltf+json',+ 'application/json',+ 'application/octet-stream',+]);++const MAX_GLB = 100 * 1024 * 1024; // 100 MB+const MAX_JSON = 1024 * 1024; // 1 MB++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads');++ const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();+ if (!ALLOWED.has(ct)) return error(res, 415, 'unsupported_type', 'unsupported content-type');++ const isJson = ct === 'application/json';+ const ext = isJson ? 'json' : 'glb';+ const body = await readRaw(req, isJson ? MAX_JSON : MAX_GLB);++ const key = `erc8004/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;++ await r2.send(new PutObjectCommand({+ Bucket: env.R2_BUCKET,+ Key: key,+ Body: body,+ ContentType: ct,+ }));++ return json(res, 200, { url: publicUrl(key) });+});++function readRaw(req, limit) {+ return new Promise((resolve, reject) => {+ const chunks = [];+ let total = 0;+ req.on('data', (chunk) => {+ total += chunk.length;+ if (total > limit) {+ reject(Object.assign(new Error('payload too large'), { status: 413 }));+ req.destroy();+ return;+ }+ chunks.push(chunk);+ });+ req.on('end', () => resolve(Buffer.concat(chunks)));+ req.on('error', reject);+ });+}diff --git a/index.html b/index.htmlindex 6a435561f..904d74d7d 100644--- a/index.html+++ b/index.html@@ -58,6 +58,30 @@<div id="agent-home-container"></div></div>+ <!-- Auth gate — shown only to anonymous visitors on the main viewer -->+ <aside class="auth-gate" id="auth-gate">+ <div class="auth-gate__inner">+ <div class="auth-gate__eyebrow">+ <span class="auth-gate__lock" aria-hidden="true">◎</span>+ <span>Unlock the agent</span>+ </div>+ <h2 class="auth-gate__title">Your agent lives here</h2>+ <p class="auth-gate__desc">+ Sign in to access animations, scene controls, and your agent's on-chain identity, memory, and skills.+ </p>+ <div class="auth-gate__actions">+ <a class="auth-gate__btn auth-gate__btn--primary" href="/login">Sign in</a>+ <a class="auth-gate__btn" href="/register">Create account</a>+ </div>+ <ul class="auth-gate__perks">+ <li>Animations & presence controls</li>+ <li>Save avatars to your account</li>+ <li>Register on-chain agent identity</li>+ <li>Scene, lighting & material editor</li>+ </ul>+ </div>+ </aside>+<!-- 3D Viewer --><div class="viewer-container" id="viewer-container"></div>diff --git a/package-lock.json b/package-lock.jsonindex 3005f5828..44cada3a4 100644--- a/package-lock.json+++ b/package-lock.json@@ -27,6 +27,7 @@"query-string": "^8.1.0","simple-dropzone": "^0.8.3","three": "^0.176.0",+ "tweakpane": "^4.0.5","vhtml": "^2.2.0","zod": "^3.23.8"},@@ -7743,6 +7744,15 @@"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==","license": "0BSD"},+ "node_modules/tweakpane": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/tweakpane/-/tweakpane-4.0.5.tgz",+ "integrity": "sha512-rxEXdSI+ArlG1RyO6FghC4ZUX8JkEfz8F3v1JuteXSV0pEtHJzyo07fcDG+NsJfN5L39kSbCYbB9cBGHyuI/tQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/cocopon"+ }+ },"node_modules/type-fest": {"version": "0.16.0","resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz",diff --git a/package.json b/package.jsonindex e2798906b..8e2127a96 100644--- a/package.json+++ b/package.json@@ -64,6 +64,7 @@"query-string": "^8.1.0","simple-dropzone": "^0.8.3","three": "^0.176.0",+ "tweakpane": "^4.0.5","vhtml": "^2.2.0","zod": "^3.23.8"},diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 063702d9d..cbfbad9d5 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -650,6 +650,7 @@ async function renderEmbed(root) {<p class="muted" style="margin:0 0 10px">By default anyone. Lock it down to specific hosts (your Lobehub deploy, your Substack…) on the <a href="/dashboard/embed-policy?agent=${encodeURIComponent(agent.id)}">embed-policy page</a>.</p></div>${onchainCard(agent)}+ ${myAgentsCard()}</div></div>`;@@ -670,6 +671,7 @@ async function renderEmbed(root) {}bindOnchainDeploy(body, agent);+ bindMyAgents(body);}function snippetBlock(title, code, _lang) {@@ -777,6 +779,194 @@ function bindOnchainDeploy(body, agent) {});}+// ── My on-chain agents card ─────────────────────────────────────────────────+// Lists every ERC-8004 agent owned by the connected wallet — minted here or+// elsewhere. Enumerates via ERC-721: balanceOf + tokenOfOwnerByIndex, falling+// back to a Transfer-event scan if the registry isn't ERC-721-Enumerable.+// Merges in DB-registered agents from /api/agents/by-wallet so "home" links+// work for agents minted through this app.+function myAgentsCard() {+ return `+ <div class="card" id="my-agents-card" style="margin-top:14px">+ <h3 style="margin:0 0 6px">Your on-chain agents</h3>+ <p class="muted" style="margin:0 0 10px">All ERC-8004 agents owned by your connected wallet — minted here or anywhere else.</p>+ <div class="row" style="gap:8px; flex-wrap:wrap; align-items:center">+ <button class="btn sec" id="my-agents-load" type="button">Load from wallet</button>+ <span id="my-agents-status" class="muted" style="font-size:12px"></span>+ </div>+ <div id="my-agents-list" style="margin-top:12px; display:grid; gap:10px"></div>+ </div>+ `;+}++function bindMyAgents(body) {+ const btn = body.querySelector('#my-agents-load');+ const status = body.querySelector('#my-agents-status');+ const list = body.querySelector('#my-agents-list');+ if (!btn) return;++ btn.addEventListener('click', async () => {+ btn.disabled = true;+ status.textContent = 'Connecting wallet…';+ list.innerHTML = '';++ try {+ const [{ connectWallet, getIdentityRegistry }, { REGISTRY_DEPLOYMENTS }] = await Promise.all([+ import('/src/erc8004/agent-registry.js'),+ import('/src/erc8004/abi.js'),+ ]);++ const { signer, address, chainId } = await connectWallet();+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment?.identityRegistry) {+ status.textContent = `No ERC-8004 registry on chain ${chainId}. Switch networks and retry.`;+ return;+ }++ status.textContent = 'Reading registry…';+ const registry = getIdentityRegistry(chainId, signer);+ const balance = Number(await registry.balanceOf(address));++ // Fire the DB lookup in parallel with on-chain work.+ const dbPromise = fetch(+ `/api/agents/by-wallet?address=${encodeURIComponent(address)}&chain_id=${chainId}`,+ { credentials: 'include' },+ ).then((r) => (r.ok ? r.json() : { agents: [] })).catch(() => ({ agents: [] }));++ if (balance === 0) {+ const { agents: dbAgents = [] } = await dbPromise;+ if (dbAgents.length === 0) {+ status.textContent = `No agents owned on chain ${chainId}.`;+ return;+ }+ renderAgentRows(list, [], dbAgents);+ status.textContent = `${dbAgents.length} DB record${dbAgents.length === 1 ? '' : 's'} (not on-chain yet).`;+ return;+ }++ status.textContent = `${balance} agent${balance === 1 ? '' : 's'} owned. Enumerating…`;++ // Try ERC-721 Enumerable; fall back to event scan.+ let tokenIds = [];+ try {+ for (let i = 0; i < balance; i++) {+ tokenIds.push(Number(await registry.tokenOfOwnerByIndex(address, i)));+ }+ } catch {+ status.textContent = 'Registry is not Enumerable — scanning Transfer events…';+ const events = await registry.queryFilter(registry.filters.Transfer(null, address));+ const seen = new Set();+ for (const e of events) {+ const id = Number(e.args.tokenId);+ if (seen.has(id)) continue;+ seen.add(id);+ try {+ const owner = await registry.ownerOf(id);+ if (owner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);+ } catch { /* token burned/transferred — skip */ }+ }+ }++ status.textContent = `Fetching metadata for ${tokenIds.length} agent${tokenIds.length === 1 ? '' : 's'}…`;+ const onchain = await Promise.all(tokenIds.map((id) => fetchTokenMeta(registry, id)));+ const { agents: dbAgents = [] } = await dbPromise;++ renderAgentRows(list, onchain, dbAgents);+ status.textContent = `${onchain.length} on-chain agent${onchain.length === 1 ? '' : 's'} on chain ${chainId}.`;+ } catch (err) {+ status.textContent = `Error: ${err.message || String(err)}`;+ } finally {+ btn.disabled = false;+ }+ });+}++async function fetchTokenMeta(registry, tokenId) {+ let uri = '';+ let meta = null;+ try { uri = await registry.tokenURI(tokenId); } catch { /* no URI set */ }+ if (uri) {+ const httpUrl = uriToHttp(uri);+ try {+ const r = await fetch(httpUrl);+ const ct = r.headers.get('content-type') || '';+ if (r.ok && ct.includes('json')) meta = await r.json();+ } catch { /* metadata unreachable */ }+ }+ return { id: tokenId, uri, meta };+}++function uriToHttp(uri) {+ if (!uri) return '';+ if (uri.startsWith('ipfs://')) return `https://ipfs.io/ipfs/${uri.slice(7)}`;+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;+ return uri;+}++function renderAgentRows(list, onchainAgents, dbAgents) {+ const dbByAgentId = new Map();+ for (const a of dbAgents) {+ if (a.erc8004_agent_id != null) dbByAgentId.set(String(a.erc8004_agent_id), a);+ }++ list.innerHTML = '';+ for (const { id, uri, meta } of onchainAgents) {+ const dbRow = dbByAgentId.get(String(id));+ const name = meta?.name || dbRow?.name || `Agent #${id}`;+ const desc = meta?.description || dbRow?.description || '';+ const img = uriToHttp(meta?.image || '');+ const homeLink = dbRow ? `/agent/${encodeURIComponent(dbRow.id)}` : '';+ const metaLink = uri ? uriToHttp(uri) : '';++ const el = document.createElement('div');+ el.className = 'row';+ el.style.cssText = 'gap:12px; padding:10px; border:1px solid #2a2a34; border-radius:10px; align-items:flex-start';+ el.innerHTML = `+ <div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; overflow:hidden; display:flex; align-items:center; justify-content:center">+ ${img ? `<img src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" onerror="this.remove()">` : '<span class="muted" style="font-size:10px">no image</span>'}+ </div>+ <div style="flex:1 1 auto; min-width:0">+ <div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">+ <strong style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0">${esc(name)}</strong>+ <span class="muted" style="font-size:12px">#${esc(String(id))}</span>+ </div>+ ${desc ? `<p class="muted" style="margin:4px 0 0; font-size:12px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden">${esc(desc)}</p>` : ''}+ <div class="row" style="gap:10px; margin-top:6px; font-size:12px">+ ${metaLink ? `<a href="${attr(metaLink)}" target="_blank" rel="noopener" class="muted">Metadata</a>` : ''}+ ${homeLink ? `<a href="${attr(homeLink)}" target="_blank" rel="noopener">Open home</a>` : ''}+ </div>+ </div>+ `;+ list.appendChild(el);+ }++ // Surface DB rows that aren't on-chain yet (e.g. registration failed).+ for (const a of dbAgents) {+ const hasOnchain = a.erc8004_agent_id != null && onchainAgents.some((o) => String(o.id) === String(a.erc8004_agent_id));+ if (hasOnchain) continue;++ const el = document.createElement('div');+ el.className = 'row';+ el.style.cssText = 'gap:12px; padding:10px; border:1px dashed #2a2a34; border-radius:10px; align-items:flex-start; opacity:.85';+ el.innerHTML = `+ <div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; display:flex; align-items:center; justify-content:center">+ <span class="muted" style="font-size:10px">db only</span>+ </div>+ <div style="flex:1 1 auto; min-width:0">+ <div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">+ <strong style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0">${esc(a.name || 'Agent')}</strong>+ <span class="muted" style="font-size:12px">not on-chain</span>+ </div>+ ${a.description ? `<p class="muted" style="margin:4px 0 0; font-size:12px">${esc(a.description)}</p>` : ''}+ <div class="row" style="gap:10px; margin-top:6px; font-size:12px">+ <a href="/agent/${encodeURIComponent(a.id)}" target="_blank" rel="noopener">Open home</a>+ </div>+ </div>+ `;+ list.appendChild(el);+ }+}+// ── Billing placeholder ─────────────────────────────────────────────────────function renderBilling(root) {root.innerHTML = `<h1>Plan & usage</h1><p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p><div class="card muted">Detailed usage analytics coming soon.</div>`;diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.htmlindex 09e3bb0e6..7667d2e3b 100644--- a/public/dashboard/embed-policy.html+++ b/public/dashboard/embed-policy.html@@ -106,7 +106,7 @@ async function loadMe() {try {await api('GET', '/api/auth/me');} catch {- location.href = '/login.html?next=' + encodeURIComponent(location.pathname + location.search);+ location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search);throw new Error('redirecting');}}diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 29e51c799..8e0411b4d 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -150,7 +150,7 @@ window.signOut = signOut;state.user = me.user;document.getElementById('user-email').textContent = me.user.email;} catch {- location.href = '/login.html?next=' + encodeURIComponent(location.pathname + location.hash);+ location.href = '/login?next=' + encodeURIComponent(location.pathname + location.hash);return;}navigate(location.hash.slice(1) || 'avatars');diff --git a/public/studio/studio.js b/public/studio/studio.jsindex e796c48da..05c4e98b6 100644--- a/public/studio/studio.js+++ b/public/studio/studio.js@@ -229,9 +229,13 @@ function selectAvatar(id) {}function selectByModelUrl(url) {- const found = state.avatars.find((a) => a.model_url === url);+ const urlPath = (() => { try { return new URL(url, location.origin).pathname; } catch { return url; } })();+ const found = state.avatars.find((a) => {+ if (!a.model_url) return false;+ if (a.model_url === url) return true;+ try { return new URL(a.model_url).pathname === urlPath; } catch { return false; }+ });if (found) selectAvatar(found.id);- else previewSt.textContent = 'Pick an avatar from your library';}function selectType(key) {@@ -313,7 +317,7 @@ function schedulePreview() {}function updatePreview(forceReload) {- if (!state.avatarId) {+ if (!state.avatarId && !state.preselectedModel) {previewSt.textContent = 'Pick an avatar to preview';return;}@@ -323,7 +327,8 @@ function updatePreview(forceReload) {previewSt.textContent = 'Avatar has no public URL — make it public/unlisted to preview';return;}- previewSt.textContent = 'Live preview';+ previewSt.textContent = state.avatarId ? 'Live preview' : 'Preview only — pick an avatar from your library to save';+ if (!state.avatarId) captureBtn.disabled = false;const camStr = Array.isArray(state.config.cameraPosition)? `&cameraPosition=${state.config.cameraPosition.map((n) => n.toFixed(3)).join(',')}`diff --git a/public/wallet-login.js b/public/wallet-login.jsindex 6afa64890..ffca05d1c 100644--- a/public/wallet-login.js+++ b/public/wallet-login.js@@ -7,10 +7,17 @@import { BrowserProvider } from 'https://esm.sh/[email protected]';-const PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';const params = new URLSearchParams(location.search);const next = params.get('next') || '/dashboard/';+// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var). The+// meta tag is a local-dev fallback — prod should rely on the fetched config.+let PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';+const configReady = fetch('/api/config', { credentials: 'omit' })+ .then((r) => r.ok ? r.json() : null)+ .then((cfg) => { if (cfg?.privyAppId) PRIVY_APP_ID = cfg.privyAppId; })+ .catch(() => {});+// ── UI helpers ──────────────────────────────────────────────────────────────function ui() {@@ -31,6 +38,7 @@ function ui() {async function signInWithPrivy() {const { privyBtn, setErr, clearErr } = ui();+ await configReady;if (!PRIVY_APP_ID) { setErr('Privy not configured.'); return; }clearErr();diff --git a/scripts/apply-schema.mjs b/scripts/apply-schema.mjsnew file mode 100644index 000000000..62c5da449--- /dev/null+++ b/scripts/apply-schema.mjs@@ -0,0 +1,50 @@+#!/usr/bin/env node+// One-shot schema applier. Idempotent — safe to re-run.+// Usage: node scripts/apply-schema.mjs (reads DATABASE_URL from .env.local → .env → environment)++import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { Pool, neonConfig } from '@neondatabase/serverless';+import ws from 'ws';++const __dirname = dirname(fileURLToPath(import.meta.url));+const root = resolve(__dirname, '..');++function loadEnvFile(path) {+ let raw;+ try { raw = readFileSync(path, 'utf8'); } catch { return; }+ for (const line of raw.split('\n')) {+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);+ if (!m) continue;+ const [, k, v] = m;+ if (process.env[k]) continue;+ process.env[k] = v.replace(/^["']|["']$/g, '');+ }+}+loadEnvFile(resolve(root, '.env.local'));+loadEnvFile(resolve(root, '.env'));++const url = process.env.DATABASE_URL;+if (!url) {+ console.error('DATABASE_URL not set');+ process.exit(1);+}++neonConfig.webSocketConstructor = ws;++const schema = readFileSync(resolve(root, 'api/_lib/schema.sql'), 'utf8');+const host = new URL(url).host;++console.log(`Applying schema to ${host} …`);++const pool = new Pool({ connectionString: url });+try {+ await pool.query(schema);+ console.log('✓ schema applied');+} catch (err) {+ console.error('✗ schema failed:', err.message);+ process.exitCode = 1;+} finally {+ await pool.end();+}diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex b6c74cd4a..4e67c99ff 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -75,6 +75,12 @@ export class AgentAvatar {this._targetTilt = 0; // radiansthis._currentLean = 0; // slight forward leanthis._targetLean = 0;+ this._currentYaw = 0; // horizontal gaze (follow mode)++ // Follow mode state+ this._mouseGaze = { x: 0, y: 0 }; // normalised -1..1+ this._keystrokePitch = 0; // look-down impulse (radians, decays)+ this._keystrokeYaw = 0; // lateral drift impulse (radians, decays)// One-shot gesture trackingthis._oneShotAction = null;@@ -93,7 +99,9 @@ export class AgentAvatar {// Listeners stored so we can detach laterthis._listeners = [];- this._tickBound = this._tickEmotion.bind(this);+ this._tickBound = this._tickEmotion.bind(this);+ this._onMouseMove = this._handleMouseMove.bind(this);+ this._onKeyFollowDown = this._handleKeyPress.bind(this);}// ── Lifecycle ─────────────────────────────────────────────────────────────@@ -104,6 +112,10 @@ export class AgentAvatar {if (!this.viewer._afterAnimateHooks) this.viewer._afterAnimateHooks = [];this.viewer._afterAnimateHooks.push(this._tickBound);+ // Follow mode input listeners+ this.viewer.el.addEventListener('mousemove', this._onMouseMove);+ window.addEventListener('keydown', this._onKeyFollowDown);+// Subscribe to protocol eventsthis._sub(ACTION_TYPES.SPEAK, this._onSpeak.bind(this));this._sub(ACTION_TYPES.GESTURE, this._onGesture.bind(this));@@ -132,6 +144,8 @@ export class AgentAvatar {const idx = this.viewer._afterAnimateHooks.indexOf(this._tickBound);if (idx !== -1) this.viewer._afterAnimateHooks.splice(idx, 1);}+ this.viewer.el.removeEventListener('mousemove', this._onMouseMove);+ window.removeEventListener('keydown', this._onKeyFollowDown);for (const [type, handler] of this._listeners) {this.protocol.off(type, handler);}@@ -331,7 +345,20 @@ export class AgentAvatar {this._currentTilt = _lerp(this._currentTilt, this._targetTilt, dt * 3.0);// ── Forward lean (curiosity leans in, patience leans back) ────────- this._targetLean = w.curiosity * 0.03 - w.patience * 0.02;+ this._targetLean = w.curiosity * 0.03 - w.patience * 0.02;+ const _followMode = this.viewer.state?.followMode;+ if (_followMode === 'mouse') {+ // Mouse Y: -1 = top of canvas (look up), +1 = bottom (look down)+ this._targetLean += this._mouseGaze.y * (12 * DEG2RAD);+ } else if (_followMode === 'keystrokes') {+ this._targetLean += this._keystrokePitch;+ this._keystrokePitch = Math.max(0, this._keystrokePitch - dt * 0.9);+ this._keystrokeYaw = _lerp(this._keystrokeYaw, 0, dt * 0.6);+ } else {+ // Decay any residual follow-mode values if mode was switched off+ this._keystrokePitch = 0;+ this._keystrokeYaw = _lerp(this._keystrokeYaw, 0, dt * 2.0);+ }this._currentLean = _lerp(this._currentLean, this._targetLean, dt * 2.0);this._applyHeadTransform();@@ -371,18 +398,52 @@ export class AgentAvatar {_applyHeadTransform() {if (!this.viewer?.content) return;- // Find a head/neck bone or the root bone to tilt+ // Compute yaw target from follow mode+ const followMode = this.viewer.state?.followMode;+ let targetYaw = 0;+ if (followMode === 'mouse') {+ targetYaw = this._mouseGaze.x * (25 * DEG2RAD);+ } else if (followMode === 'keystrokes') {+ targetYaw = this._keystrokeYaw;+ }+ this._currentYaw = _lerp(this._currentYaw, targetYaw, 0.08);+this.viewer.content.traverse(node => {if (!node.isBone) return;const n = node.name.toLowerCase();if (n.includes('head') || n.includes('neck')) {- // Apply tilt (Z rotation) and lean (X rotation)- node.rotation.z = _lerp(node.rotation.z, this._currentTilt, 0.1);- node.rotation.x = _lerp(node.rotation.x, this._currentLean, 0.1);+ node.rotation.z = _lerp(node.rotation.z, this._currentTilt, 0.1);+ node.rotation.x = _lerp(node.rotation.x, this._currentLean, 0.1);+ node.rotation.y = _lerp(node.rotation.y, this._currentYaw, 0.1);}});}+ // ── Follow Mode Handlers ──────────────────────────────────────────────────++ _handleMouseMove(e) {+ const rect = this.viewer.el.getBoundingClientRect();+ this._mouseGaze.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;+ this._mouseGaze.y = ((e.clientY - rect.top) / rect.height) * 2 - 1;+ }++ _handleKeyPress(e) {+ if (this.viewer.state?.followMode !== 'keystrokes') return;+ if (['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'Tab', 'Escape'].includes(e.key)) return;++ // Look down toward keyboard+ this._keystrokePitch = 0.18;++ // Lateral drift based on rough key column: left side → look left, right side → look right+ const leftKeys = 'qweasdzxc123`~!@#';+ const rightKeys = 'yuiophjklnm7890-=';+ const k = e.key.toLowerCase();+ if (leftKeys.includes(k)) this._keystrokeYaw = -0.12;+ else if (rightKeys.includes(k)) this._keystrokeYaw = 0.12;++ this._injectStimulus('curiosity', 0.07);+ }+// ── Gesture / One-shot Animations ────────────────────────────────────────/**diff --git a/src/agent-identity.js b/src/agent-identity.jsindex 24a919cff..2eb265890 100644--- a/src/agent-identity.js+++ b/src/agent-identity.js@@ -165,12 +165,17 @@ export class AgentIdentity {/*** Register this agent on-chain via the ERC-8004 registry.- * @param {File} glbFile- * @param {string} apiToken+ * @param {{ glbFile: File, name?: string, description?: string, apiToken?: string, onStatus?: Function }} [opts]*/- async register(glbFile, apiToken) {+ async register({ glbFile, name, description, apiToken, onStatus } = {}) {const { registerAgent } = await import('./erc8004/agent-registry.js');- const result = await registerAgent(glbFile, apiToken);+ const result = await registerAgent({+ glbFile,+ name: name || this.name,+ description: description || this.description,+ apiToken,+ onStatus,+ });await this.update({ isRegistered: true, meta: { ...this.meta, erc8004: result } });return result;}diff --git a/src/app.js b/src/app.jsindex 77bb97e4b..5f0ffcea4 100644--- a/src/app.js+++ b/src/app.js@@ -50,6 +50,7 @@ class App {proxyURL: hash.proxyURL || '',agent: hash.agent || '',widget: hash.widget || '',+ register: hash.register !== undefined,};this.el = el;@@ -78,6 +79,7 @@ class App {this.createDropzone();this.setupAvatarCreator();this.hideSpinner();+ this._applyViewerMode();this._updateSignInLink();const options = this.options;@@ -212,13 +214,28 @@ class App {}}+ _applyViewerMode() {+ const { kiosk, widget, agent, register } = this.options;+ let mode = 'main';+ if (kiosk || widget || agent) mode = 'embed';+ else if (register) mode = 'register';+ document.body.dataset.viewerMode = mode;+ if (mode === 'main') document.body.dataset.authed = 'pending';+ }+async _updateSignInLink() {const link = document.getElementById('nav-sign-in');- if (!link) return;try {const user = await getMe();- if (user) link.classList.add('signed-in');- } catch { /* leave sign-in visible */ }+ if (link && user) link.classList.add('signed-in');+ if (document.body.dataset.viewerMode === 'main') {+ document.body.dataset.authed = user ? 'true' : 'false';+ }+ } catch {+ if (document.body.dataset.viewerMode === 'main') {+ document.body.dataset.authed = 'false';+ }+ }}_refreshMakeWidgetButton() {diff --git a/src/erc8004/abi.js b/src/erc8004/abi.jsindex fb170db42..a384b66d3 100644--- a/src/erc8004/abi.js+++ b/src/erc8004/abi.js@@ -28,6 +28,8 @@ export const IDENTITY_REGISTRY_ABI = [// --- ERC-721 basics ---'function ownerOf(uint256 tokenId) external view returns (address)','function balanceOf(address owner) external view returns (uint256)',+ 'function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)',+ 'function totalSupply() external view returns (uint256)','function name() external view returns (string)','function symbol() external view returns (string)','function getVersion() external pure returns (string)',diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.jsindex c1c580d0c..9ab3786a1 100644--- a/src/erc8004/agent-registry.js+++ b/src/erc8004/agent-registry.js@@ -64,42 +64,45 @@ export function getSigner() {}// ----------------------------------------------------------------------------// IPFS upload (via public pinning gateway — swap for Filebase / web3.storage)+// File upload — backend R2 (default) or Pinata (if token supplied)// ----------------------------------------------------------------------------const IPFS_UPLOAD_URL = 'https://api.web3.storage/upload';-/**- * Pin a blob to IPFS. Returns the CID.+ * Upload a file blob. Returns the public URL.*- * Uses web3.storage free tier by default.- * Set `window.__W3S_TOKEN` or pass `apiToken` for auth.+ * Without a token: POSTs to /api/erc8004/pin which stores to R2.+ * With a Pinata JWT token: POSTs to Pinata and returns an ipfs:// URL.** @param {Blob|File} blob- * @param {string} [apiToken]- * @returns {Promise<string>} The IPFS CID.+ * @param {string} [apiToken] Pinata JWT (optional)+ * @returns {Promise<string>} Public URL for the uploaded file.*/-export async function pinToIPFS(blob, apiToken) {- const token = apiToken || window.__W3S_TOKEN;- if (!token) {- throw new Error(- 'IPFS upload requires an API token. Set window.__W3S_TOKEN or pass one to pinToIPFS().',- );+export async function pinFile(blob, apiToken) {+ if (apiToken) {+ const form = new FormData();+ form.append('file', blob, blob.name || 'upload');+ const res = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {+ method: 'POST',+ headers: { Authorization: `Bearer ${apiToken}` },+ body: form,+ });+ if (!res.ok) throw new Error(`Pinata upload failed (${res.status})`);+ const data = await res.json();+ return `ipfs://${data.IpfsHash}`;}- const res = await fetch(IPFS_UPLOAD_URL, {+ const res = await fetch('/api/erc8004/pin', {method: 'POST',- headers: { Authorization: `Bearer ${token}` },+ headers: { 'content-type': blob.type || 'application/octet-stream' },body: blob,+ credentials: 'include',});-if (!res.ok) {- const text = await res.text();- throw new Error(`IPFS upload failed (${res.status}): ${text}`);+ const text = await res.text().catch(() => res.status);+ throw new Error(`Upload failed (${res.status}): ${text}`);}-const data = await res.json();- return data.cid;+ return data.url;}// ---------------------------------------------------------------------------@@ -112,7 +115,7 @@ export async function pinToIPFS(blob, apiToken) {* @param {object} opts* @param {string} opts.name Agent display name* @param {string} opts.description Natural-language description- * @param {string} opts.imageCID IPFS CID of the 3D GLB model+ * @param {string} opts.imageUrl URL of the 3D GLB model (HTTPS or ipfs://)* @param {number} opts.agentId Token ID from the registry (filled after mint)* @param {number} opts.chainId Chain ID where registered* @param {string} opts.registryAddr Identity Registry contract address@@ -122,7 +125,7 @@ export async function pinToIPFS(blob, apiToken) {export function buildRegistrationJSON({name,description,- imageCID,+ imageUrl,agentId,chainId,registryAddr,@@ -132,12 +135,12 @@ export function buildRegistrationJSON({type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',name,description,- image: `ipfs://${imageCID}`,+ image: imageUrl,active: true,services: [{name: '3D',- endpoint: `https://3dagent.vercel.app/#model=ipfs://${imageCID}`,+ endpoint: `https://3dagent.vercel.app/#model=${encodeURIComponent(imageUrl)}`,version: '1.0',},...services,@@ -172,38 +175,38 @@ export function getIdentityRegistry(chainId, signer) {/*** Full registration flow:- * 1. Upload GLB to IPFS+ * 1. Upload GLB to storage (R2 or Pinata)* 2. Build registration JSON- * 3. Upload registration JSON to IPFS+ * 3. Upload registration JSON to storage* 4. Call register(agentURI) on-chain- * 5. Update registration JSON with agentId, re-pin, call setAgentURI+ * 5. Update agentURI to the final registration JSON** @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] IPFS pinning API token+ * @param {string} [opts.apiToken] Optional Pinata JWT (omit to use built-in storage)* @param {function} [opts.onStatus] Callback for progress updates- * @returns {Promise<{agentId: number, registrationCID: string, txHash: string}>}+ * @returns {Promise<{agentId: number, registrationUrl: string, txHash: string}>}*/export async function registerAgent({ glbFile, name, description, apiToken, onStatus }) {const log = onStatus || (() => {});// 1. Connect walletlog('Connecting wallet...');- const { signer, address, chainId } = await connectWallet();+ const { signer, chainId } = await connectWallet();- // 2. Upload GLB to IPFS- log('Uploading 3D model to IPFS...');- const glbCID = await pinToIPFS(glbFile, apiToken);- log(`Model pinned: ipfs://${glbCID}`);+ // 2. Upload GLB+ log('Uploading 3D model...');+ const glbUrl = await pinFile(glbFile, apiToken);+ log(`Model uploaded: ${glbUrl}`);// 3. Get contractconst registry = getIdentityRegistry(chainId, signer);- // 4. Register with a placeholder URI first to get the agentId+ // 4. Register with GLB URL first to get the agentIdlog('Registering agent on-chain...');- const tx = await registry['register(string)'](`ipfs://${glbCID}`);+ const tx = await registry['register(string)'](glbUrl);log(`Transaction submitted: ${tx.hash}`);const receipt = await tx.wait();@@ -223,29 +226,29 @@ export async function registerAgent({ glbFile, name, description, apiToken, onStconst registrationJSON = buildRegistrationJSON({name,description,- imageCID: glbCID,+ imageUrl: glbUrl,agentId,chainId,registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,});- // 6. Pin registration JSON to IPFS- log('Pinning registration metadata to IPFS...');+ // 6. Upload registration JSON+ log('Uploading registration metadata...');const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {type: 'application/json',});- const registrationCID = await pinToIPFS(jsonBlob, apiToken);- log(`Registration JSON pinned: ipfs://${registrationCID}`);+ const registrationUrl = await pinFile(jsonBlob, apiToken);+ log(`Registration metadata uploaded: ${registrationUrl}`);// 7. Update agentURI on-chain to point at the full registration JSONlog('Updating agentURI on-chain...');- const updateTx = await registry.setAgentURI(agentId, `ipfs://${registrationCID}`);+ const updateTx = await registry.setAgentURI(agentId, registrationUrl);await updateTx.wait();log('Agent URI updated on-chain.');return {agentId,- registrationCID,+ registrationUrl,txHash: tx.hash,};}diff --git a/src/erc8004/chain-meta.js b/src/erc8004/chain-meta.jsnew file mode 100644index 000000000..7a6acf7cd--- /dev/null+++ b/src/erc8004/chain-meta.js@@ -0,0 +1,112 @@+/**+ * Human-readable metadata for every chain in REGISTRY_DEPLOYMENTS.+ *+ * Used by:+ * - Chain switcher (wallet_switchEthereumChain + wallet_addEthereumChain fallback)+ * - Agent card "View on explorer" links+ * - Chain dropdown labels+ *+ * Public RPCs below are safe defaults. They work out-of-the-box for+ * wallet_addEthereumChain but may rate-limit on heavy reads — use user-supplied+ * wallet provider for production reads.+ */++import { REGISTRY_DEPLOYMENTS } from './abi.js';++/** @type {Record<number, { name: string, shortName: string, currency: { name: string, symbol: string, decimals: number }, rpcUrl: string, explorer: string, testnet: boolean }>} */+export const CHAIN_META = {+ // ── Mainnets ──────────────────────────────────────────────────────────+ 1: { name: 'Ethereum', shortName: 'ETH', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://ethereum-rpc.publicnode.com', explorer: 'https://etherscan.io', testnet: false },+ 10: { name: 'Optimism', shortName: 'OP', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.optimism.io', explorer: 'https://optimistic.etherscan.io', testnet: false },+ 56: { name: 'BNB Chain', shortName: 'BSC', currency: { name: 'BNB', symbol: 'BNB', decimals: 18 }, rpcUrl: 'https://bsc-dataseed.bnbchain.org', explorer: 'https://bscscan.com', testnet: false },+ 100: { name: 'Gnosis', shortName: 'GNO', currency: { name: 'xDAI', symbol: 'xDAI', decimals: 18 }, rpcUrl: 'https://rpc.gnosischain.com', explorer: 'https://gnosisscan.io', testnet: false },+ 137: { name: 'Polygon', shortName: 'POL', currency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrl: 'https://polygon-rpc.com', explorer: 'https://polygonscan.com', testnet: false },+ 250: { name: 'Fantom', shortName: 'FTM', currency: { name: 'Fantom', symbol: 'FTM', decimals: 18 }, rpcUrl: 'https://rpc.ftm.tools', explorer: 'https://ftmscan.com', testnet: false },+ 324: { name: 'zkSync Era', shortName: 'zkSync', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.era.zksync.io', explorer: 'https://explorer.zksync.io', testnet: false },+ 1284: { name: 'Moonbeam', shortName: 'GLMR', currency: { name: 'Glimmer', symbol: 'GLMR', decimals: 18 }, rpcUrl: 'https://rpc.api.moonbeam.network', explorer: 'https://moonbeam.moonscan.io', testnet: false },+ 5000: { name: 'Mantle', shortName: 'MNT', currency: { name: 'Mantle', symbol: 'MNT', decimals: 18 }, rpcUrl: 'https://rpc.mantle.xyz', explorer: 'https://explorer.mantle.xyz', testnet: false },+ 8453: { name: 'Base', shortName: 'Base', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.base.org', explorer: 'https://basescan.org', testnet: false },+ 42161: { name: 'Arbitrum One', shortName: 'ARB', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://arb1.arbitrum.io/rpc', explorer: 'https://arbiscan.io', testnet: false },+ 42220: { name: 'Celo', shortName: 'CELO', currency: { name: 'Celo', symbol: 'CELO', decimals: 18 }, rpcUrl: 'https://forno.celo.org', explorer: 'https://celoscan.io', testnet: false },+ 43114: { name: 'Avalanche', shortName: 'AVAX', currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 }, rpcUrl: 'https://api.avax.network/ext/bc/C/rpc', explorer: 'https://snowtrace.io', testnet: false },+ 59144: { name: 'Linea', shortName: 'Linea', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://rpc.linea.build', explorer: 'https://lineascan.build', testnet: false },+ 534352: { name: 'Scroll', shortName: 'Scroll', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://rpc.scroll.io', explorer: 'https://scrollscan.com', testnet: false },++ // ── Testnets ──────────────────────────────────────────────────────────+ 97: { name: 'BSC Testnet', shortName: 'BSCt', currency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 }, rpcUrl: 'https://bsc-testnet-rpc.publicnode.com', explorer: 'https://testnet.bscscan.com', testnet: true },+ 11155111: { name: 'Ethereum Sepolia', shortName: 'Sep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://ethereum-sepolia-rpc.publicnode.com', explorer: 'https://sepolia.etherscan.io', testnet: true },+ 84532: { name: 'Base Sepolia', shortName: 'BaseSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org', testnet: true },+ 421614: { name: 'Arbitrum Sepolia', shortName: 'ArbSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc', explorer: 'https://sepolia.arbiscan.io', testnet: true },+ 11155420: { name: 'Optimism Sepolia', shortName: 'OpSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia.optimism.io', explorer: 'https://sepolia-optimism.etherscan.io', testnet: true },+ 80002: { name: 'Polygon Amoy', shortName: 'Amoy', currency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrl: 'https://rpc-amoy.polygon.technology', explorer: 'https://amoy.polygonscan.com', testnet: true },+ 43113: { name: 'Avalanche Fuji', shortName: 'Fuji', currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 }, rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc', explorer: 'https://testnet.snowtrace.io', testnet: true },+};++export const DEFAULT_CHAIN_ID = 97; // BSC Testnet++/** @returns {number[]} All chain IDs where both CHAIN_META and REGISTRY_DEPLOYMENTS exist. */+export function supportedChainIds() {+ return Object.keys(CHAIN_META)+ .map(Number)+ .filter((id) => REGISTRY_DEPLOYMENTS[id]);+}++/** @param {number} chainId */+export function chainIdHex(chainId) {+ return '0x' + chainId.toString(16);+}++/**+ * Switch the injected wallet to `chainId`. If the chain isn't known to the+ * wallet (error 4902), add it via wallet_addEthereumChain then retry switch.+ *+ * @param {number} chainId+ * @param {any} [provider] Optional EIP-1193 provider (defaults to window.ethereum)+ */+export async function switchChain(chainId, provider) {+ const eth = provider || window.ethereum;+ if (!eth) throw new Error('No wallet provider available');++ const meta = CHAIN_META[chainId];+ if (!meta) throw new Error(`Unknown chainId ${chainId}`);+ const hex = chainIdHex(chainId);++ try {+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });+ } catch (err) {+ if (err && (err.code === 4902 || /Unrecognized chain|not added|add.*chain/i.test(err.message || ''))) {+ await eth.request({+ method: 'wallet_addEthereumChain',+ params: [{+ chainId: hex,+ chainName: meta.name,+ nativeCurrency: meta.currency,+ rpcUrls: [meta.rpcUrl],+ blockExplorerUrls: [meta.explorer],+ }],+ });+ // wallet_addEthereumChain usually auto-switches, but force it to be safe.+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });+ } else {+ throw err;+ }+ }+}++/** @param {number} chainId @param {string} txHash */+export function txExplorerUrl(chainId, txHash) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/tx/${txHash}` : '';+}++/** @param {number} chainId @param {string} address */+export function addressExplorerUrl(chainId, address) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/address/${address}` : '';+}++/** @param {number} chainId @param {string} contract @param {string|number} tokenId */+export function tokenExplorerUrl(chainId, contract, tokenId) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/token/${contract}?a=${tokenId}` : '';+}diff --git a/src/erc8004/privy.js b/src/erc8004/privy.jsindex befed34da..26940d9a8 100644--- a/src/erc8004/privy.js+++ b/src/erc8004/privy.js@@ -16,8 +16,36 @@ import { BrowserProvider } from 'ethers';let _privy = null;let _initPromise = null;+let _resolvedAppId = null;+let _appIdPromise = null;-const APP_ID = import.meta.env.VITE_PRIVY_APP_ID || '';+const BUILD_APP_ID = import.meta.env.VITE_PRIVY_APP_ID || '';++/**+ * Resolve the Privy app ID. Prefers build-time VITE_PRIVY_APP_ID; otherwise+ * fetches /api/config at runtime so ops can rotate the ID without a rebuild.+ */+async function resolveAppId() {+ if (_resolvedAppId !== null) return _resolvedAppId;+ if (BUILD_APP_ID) { _resolvedAppId = BUILD_APP_ID; return _resolvedAppId; }+ if (_appIdPromise) return _appIdPromise;++ _appIdPromise = (async () => {+ try {+ const res = await fetch('/api/config', { credentials: 'include' });+ if (!res.ok) return '';+ const data = await res.json();+ return data.privyAppId || '';+ } catch {+ return '';+ }+ })().then((id) => {+ _resolvedAppId = id;+ return id;+ });++ return _appIdPromise;+}// ---------------------------------------------------------------------------// Init@@ -29,13 +57,15 @@ const APP_ID = import.meta.env.VITE_PRIVY_APP_ID || '';export async function initPrivy() {if (_privy) return _privy;if (_initPromise) return _initPromise;- if (!APP_ID) return null;++ const appId = await resolveAppId();+ if (!appId) return null;_initPromise = (async () => {try {const mod = await import('@privy-io/js-sdk-core');const PrivyClient = mod.PrivyClient || mod.default;- _privy = new PrivyClient({ appId: APP_ID });+ _privy = new PrivyClient({ appId });return _privy;} catch (err) {console.warn('[privy] Failed to load — falling back to injected wallet.', err.message);diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.jsindex e1078c3a4..0792b9395 100644--- a/src/erc8004/register-ui.js+++ b/src/erc8004/register-ui.js@@ -5,7 +5,7 @@* Uses plain DOM (consistent with the rest of the project).*/-import { registerAgent, connectWallet } from './agent-registry.js';+import { registerAgent, connectWallet, pinFile } from './agent-registry.js';import { isPrivyConfigured } from './privy.js';export class RegisterUI {@@ -65,10 +65,6 @@ export class RegisterUI {</div></label>- <label class="erc8004-label">- IPFS API Token- <input type="password" class="erc8004-input" name="ipfsToken" placeholder="web3.storage or Filebase token" />- </label></div><!-- Step 3: Register -->@@ -88,7 +84,7 @@ export class RegisterUI {<h3>Agent Registered!</h3><dl class="erc8004-result-dl"><dt>Agent ID</dt> <dd class="erc8004-res-id"></dd>- <dt>IPFS CID</dt> <dd class="erc8004-res-cid"></dd>+ <dt>Metadata</dt> <dd class="erc8004-res-cid"></dd><dt>Tx Hash</dt> <dd class="erc8004-res-tx"></dd></dl><button class="erc8004-btn erc8004-btn--view" type="button">View in 3D</button>@@ -146,10 +142,10 @@ export class RegisterUI {// Register$('.erc8004-btn--register').addEventListener('click', () => this._doRegister());- // View result+ // View result — jump to viewer with the registered model$('.erc8004-btn--view').addEventListener('click', () => {- const cid = $('.erc8004-res-cid').textContent;- window.location.hash = `model=ipfs://${cid}`;+ const id = $('.erc8004-res-id').textContent;+ window.location.hash = id ? `agent=${id}` : '';window.location.reload();});}@@ -179,7 +175,6 @@ export class RegisterUI {const $ = (sel) => this.el.querySelector(sel);const name = $('[name="agentName"]').value.trim();const description = $('[name="agentDesc"]').value.trim();- const apiToken = $('[name="ipfsToken"]').value.trim();const registerBtn = $('.erc8004-btn--register');registerBtn.disabled = true;@@ -190,13 +185,12 @@ export class RegisterUI {glbFile: this.selectedFile,name,description,- apiToken: apiToken || undefined,onStatus: (msg) => this._log(msg),});// Show result$('.erc8004-res-id').textContent = result.agentId;- $('.erc8004-res-cid').textContent = result.registrationCID;+ $('.erc8004-res-cid').textContent = result.registrationUrl;$('.erc8004-res-tx').textContent = result.txHash;$('.erc8004-result').style.display = '';this._log('Registration complete!');diff --git a/src/viewer.js b/src/viewer.jsindex 63d2df7b1..7d7eddab8 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -87,6 +87,9 @@ export class Viewer {// Info overlayshowInfo: true,showLabels: false,++ // Avatar follow mode+ followMode: 'mouse',};this.prevTime = 0;@@ -709,6 +712,10 @@ export class Viewer {this.cameraFolder = gui.addFolder('Cameras');this.cameraFolder.domElement.style.display = 'none';+ // Agent controls.+ const agentFolder = gui.addFolder('Agent');+ agentFolder.add(this.state, 'followMode', { 'None': 'none', 'Follow Mouse': 'mouse', 'Follow Keystrokes': 'keystrokes' }).name('follow mode');+// Stats.const perfFolder = gui.addFolder('Performance');const perfLi = document.createElement('li');diff --git a/style.css b/style.cssindex bf4505a3b..f4743d59e 100644--- a/style.css+++ b/style.css@@ -2565,3 +2565,155 @@ footer .separator {}.texture-lightbox__bar { padding: var(--space-xs); gap: var(--space-xs); }}++/* ============================================================================+ AUTH GATE — hides power tools from anonymous visitors on the main viewer+ ============================================================================ */++.auth-gate { display: none; }++body[data-viewer-mode="main"][data-authed="pending"] .anim-panel,+body[data-viewer-mode="main"][data-authed="pending"] #agent-presence-sidebar,+body[data-viewer-mode="main"][data-authed="pending"] .dg.main,+body[data-viewer-mode="main"][data-authed="pending"] #make-widget-btn {+ visibility: hidden !important;+}++body[data-viewer-mode="main"][data-authed="false"] .anim-panel,+body[data-viewer-mode="main"][data-authed="false"] #agent-presence-sidebar,+body[data-viewer-mode="main"][data-authed="false"] .dg.main,+body[data-viewer-mode="main"][data-authed="false"] #make-widget-btn {+ display: none !important;+}++body[data-viewer-mode="main"][data-authed="false"] .auth-gate {+ display: block;+ animation: auth-gate-in 0.4s ease;+}++@keyframes auth-gate-in {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}++.auth-gate {+ position: fixed;+ top: calc(var(--header-h) + var(--space-md));+ left: var(--space-md);+ width: 280px;+ z-index: 50;+}++.auth-gate__inner {+ background: linear-gradient(180deg, rgba(18, 18, 26, 0.94) 0%, rgba(10, 10, 16, 0.94) 100%);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: var(--radius-lg);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ padding: var(--space-md);+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05);+}++.auth-gate__eyebrow {+ display: flex;+ align-items: center;+ gap: var(--space-xs);+ font-size: var(--text-xs);+ color: rgba(255, 255, 255, 0.5);+ font-weight: 500;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ margin-bottom: var(--space-xs);+}++.auth-gate__lock {+ font-size: 1rem;+ opacity: 0.7;+}++.auth-gate__title {+ font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-size: 1.15rem;+ font-weight: 600;+ color: #fff;+ margin: 0 0 var(--space-2xs);+ letter-spacing: -0.01em;+}++.auth-gate__desc {+ font-size: var(--text-sm);+ line-height: 1.5;+ color: rgba(255, 255, 255, 0.65);+ margin: 0 0 var(--space-sm);+}++.auth-gate__actions {+ display: flex;+ flex-direction: column;+ gap: var(--space-2xs);+ margin-bottom: var(--space-sm);+}++.auth-gate__btn {+ display: flex;+ align-items: center;+ justify-content: center;+ padding: var(--space-xs) var(--space-sm);+ border-radius: var(--radius-md);+ font-size: var(--text-sm);+ font-weight: 500;+ text-decoration: none;+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.85);+ background: rgba(255, 255, 255, 0.03);+ transition: background 0.15s, border-color 0.15s, color 0.15s;+}++.auth-gate__btn:hover {+ background: rgba(255, 255, 255, 0.08);+ border-color: rgba(255, 255, 255, 0.2);+ color: #fff;+}++.auth-gate__btn--primary {+ background: #fff;+ color: #0a0a10;+ border-color: #fff;+}++.auth-gate__btn--primary:hover {+ background: rgba(255, 255, 255, 0.9);+ color: #0a0a10;+}++.auth-gate__perks {+ list-style: none;+ padding: 0;+ margin: 0;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ padding-top: var(--space-sm);+}++.auth-gate__perks li {+ font-size: var(--text-xs);+ color: rgba(255, 255, 255, 0.55);+ padding: var(--space-3xs) 0;+ display: flex;+ align-items: center;+}++.auth-gate__perks li::before {+ content: '→';+ margin-right: var(--space-xs);+ color: rgba(255, 255, 255, 0.4);+}++@media screen and (max-width: 700px) {+ .auth-gate {+ top: auto;+ bottom: var(--space-md);+ left: var(--space-sm);+ right: var(--space-sm);+ width: auto;+ }+}diff --git a/vercel.json b/vercel.jsonindex e813219e0..d5e05fbcd 100644--- a/vercel.json+++ b/vercel.json@@ -22,6 +22,7 @@{ "src": "/studio/(.*)", "dest": "/public/studio/$1" },{ "src": "/api/agents/me", "dest": "/api/agents" },+ { "src": "/api/agents/by-wallet", "dest": "/api/agents/by-wallet" },{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },{ "src": "/api/agents/([^/]+)/embed-policy", "dest": "/api/agents/[id]/embed-policy?id=$1" },{ "src": "/api/agents/([^/]+)/sign", "dest": "/api/agents/[id]/sign?id=$1" },diff --git a/yarn.lock b/yarn.lockindex 1c1dd1d4c..952d849b4 100644--- a/yarn.lock+++ b/yarn.lock@@ -3881,6 +3881,11 @@ [email protected]:resolved "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz"integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==+tweakpane@^4.0.5:+ version "4.0.5"+ resolved "https://registry.npmjs.org/tweakpane/-/tweakpane-4.0.5.tgz"+ integrity sha512-rxEXdSI+ArlG1RyO6FghC4ZUX8JkEfz8F3v1JuteXSV0pEtHJzyo07fcDG+NsJfN5L39kSbCYbB9cBGHyuI/tQ==+type-fest@^0.16.0:version "0.16.0"resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz"