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.

milady

nirholas9435ccedcb2b
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index fbaa32cc8..6e3c3ebaa 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -36,13 +36,21 @@ async function j(method, path, body) {
const data = res.headers.get('content-type')?.includes('application/json')
? await res.json()
: null;
- if (!res.ok) throw Object.assign(new Error((data && data.error_description) || res.statusText), { status: res.status, data });
+ if (!res.ok)
+ throw Object.assign(new Error((data && data.error_description) || res.statusText), {
+ status: res.status,
+ data,
+ });
return data;
}
export function signOut() {
fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(() => {
- try { localStorage.removeItem('3dagent:auth-hint'); } catch { /* ignore */ }
+ try {
+ localStorage.removeItem('3dagent:auth-hint');
+ } catch {
+ /* ignore */
+ }
location.href = '/';
});
}
@@ -50,7 +58,9 @@ export function signOut() {
export function navigate(tab) {
// Support #edit/<id> sub-routes for per-avatar edit screens.
const [base, ...rest] = (tab || 'avatars').split('/');
- document.querySelectorAll('aside a').forEach((a) => a.classList.toggle('active', a.dataset.tab === base));
+ document
+ .querySelectorAll('aside a')
+ .forEach((a) => a.classList.toggle('active', a.dataset.tab === base));
const main = document.getElementById('main');
main.innerHTML = '';
const renderer = tabs[base] || tabs.avatars;
@@ -99,10 +109,11 @@ function avatarCard(a) {
<p class="meta">${a.size_bytes ? fmtSize(a.size_bytes) : ''} · ${esc(a.visibility)} · ${new Date(a.created_at).toLocaleDateString()}</p>
<div class="row" style="gap:6px; margin-bottom:10px">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>
<div class="row" style="justify-content:space-between">
- <select data-vis>${['private','unlisted','public'].map((v) => `<option ${v===a.visibility?'selected':''} value="${v}">${v}</option>`).join('')}</select>
+ <select data-vis>${['private', 'unlisted', 'public'].map((v) => `<option ${v === a.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}</select>
<div class="row" style="gap:6px">
<a class="btn sec" href="#edit/${encodeURIComponent(a.id)}">Edit</a>
<button class="btn sec" data-replace>Replace GLB</button>
+ <a class="btn sec" href="/deploy?avatar=${encodeURIComponent(a.id)}" title="Mint as ERC-8004 agent">Deploy on-chain</a>
<button class="btn sec" data-del>Delete</button>
</div>
</div>
@@ -110,14 +121,18 @@ function avatarCard(a) {
el.querySelector('[data-vis]').addEventListener('change', async (e) => {
try {
await api.patchAvatar(a.id, { visibility: e.target.value });
- } catch (err) { alert(err.message); }
+ } catch (err) {
+ alert(err.message);
+ }
});
el.querySelector('[data-del]').addEventListener('click', async () => {
if (!confirm(`Delete "${a.name}"?`)) return;
try {
await api.deleteAvatar(a.id);
el.remove();
- } catch (err) { alert(err.message); }
+ } catch (err) {
+ alert(err.message);
+ }
});
el.querySelector('[data-replace]').addEventListener('click', () => replaceGlbFlow(a, el));
return el;
@@ -132,7 +147,8 @@ function replaceGlbFlow(a, cardEl) {
const warn = document.createElement('div');
warn.setAttribute('data-glb-warn', '');
- warn.style.cssText = 'margin:8px 0; padding:10px; background:rgba(255,165,0,.08); border:1px solid rgba(255,165,0,.25); border-radius:8px; font-size:12px; color:#d4aa44';
+ warn.style.cssText =
+ 'margin:8px 0; padding:10px; background:rgba(255,165,0,.08); border:1px solid rgba(255,165,0,.25); border-radius:8px; font-size:12px; color:#d4aa44';
warn.innerHTML = `
<p style="margin:0 0 8px">&#9888; This bypasses Avaturn &#8212; your avatar may not animate correctly if not rigged to the Mixamo skeleton.</p>
<div class="row" style="gap:6px">
@@ -175,14 +191,18 @@ async function doReplaceUpload(a, file, warnEl, cardEl) {
}
// MIME type check
- if (file.type && file.type !== 'model/gltf-binary' && file.type !== 'application/octet-stream') {
+ if (
+ file.type &&
+ file.type !== 'model/gltf-binary' &&
+ file.type !== 'application/octet-stream'
+ ) {
say(`Unexpected file type "${file.type}". Expected model/gltf-binary.`, true);
return;
}
// Magic number check: first 4 bytes must be 'glTF' (0x46546C67 little-endian)
const header = await file.slice(0, 4).arrayBuffer();
- if (new DataView(header).getUint32(0, true) !== 0x46546C67) {
+ if (new DataView(header).getUint32(0, true) !== 0x46546c67) {
say('Not a valid GLB \u2014 magic number check failed. Renamed files are rejected.', true);
return;
}
@@ -220,7 +240,9 @@ async function doReplaceUpload(a, file, warnEl, cardEl) {
}
if (boneMatch !== null && boneMatch < 0.5) {
- say(`Uploaded. \u26a0 Animations may not play \u2014 skeleton mismatch (${Math.round(boneMatch * 100)}% Mixamo bone match).`);
+ say(
+ `Uploaded. \u26a0 Animations may not play \u2014 skeleton mismatch (${Math.round(boneMatch * 100)}% Mixamo bone match).`,
+ );
} else {
say('Replaced! Your agent now uses the new GLB.');
}
@@ -234,16 +256,33 @@ async function doReplaceUpload(a, file, warnEl, cardEl) {
// Returns a ratio 0..1, or null if the file has no parseable node names.
function checkMixamoSkeleton(buffer) {
const MIXAMO_BONES = new Set([
- 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
- 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',
- 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
- 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
- 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+ 'Hips',
+ 'Spine',
+ 'Spine1',
+ 'Spine2',
+ 'Neck',
+ 'Head',
+ 'LeftShoulder',
+ 'LeftArm',
+ 'LeftForeArm',
+ 'LeftHand',
+ 'RightShoulder',
+ 'RightArm',
+ 'RightForeArm',
+ 'RightHand',
+ 'LeftUpLeg',
+ 'LeftLeg',
+ 'LeftFoot',
+ 'LeftToeBase',
+ 'RightUpLeg',
+ 'RightLeg',
+ 'RightFoot',
+ 'RightToeBase',
]);
try {
const view = new DataView(buffer);
const chunkLen = view.getUint32(12, true);
- if (view.getUint32(16, true) !== 0x4E4F534A) return null; // chunk 0 is not JSON
+ if (view.getUint32(16, true) !== 0x4e4f534a) return null; // chunk 0 is not JSON
const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, chunkLen)));
const nodes = (json.nodes || []).filter((n) => n.name);
if (!nodes.length) return null;
@@ -287,9 +326,16 @@ function renderUpload(root) {
content_type: file.type || 'model/gltf-binary',
});
progress.textContent = `Uploading ${fmtSize(file.size)}…`;
- await uploadToR2(upload_url, file, (pct) => (progress.textContent = `Uploading ${pct}%…`));
+ await uploadToR2(
+ upload_url,
+ file,
+ (pct) => (progress.textContent = `Uploading ${pct}%…`),
+ );
progress.textContent = 'Finalizing…';
- const tags = (root.querySelector('#tags').value || '').split(',').map((s) => s.trim()).filter(Boolean);
+ const tags = (root.querySelector('#tags').value || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
const { avatar } = await api.createAvatar({
storage_key,
name: root.querySelector('#name').value,
@@ -315,8 +361,12 @@ function uploadToR2(url, file, onProgress) {
const xhr = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.setRequestHeader('content-type', file.type || 'model/gltf-binary');
- xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));
- xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));
+ xhr.upload.onprogress = (e) =>
+ e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));
+ xhr.onload = () =>
+ xhr.status >= 200 && xhr.status < 300
+ ? resolve()
+ : reject(new Error(`Upload failed (${xhr.status})`));
xhr.onerror = () => reject(new Error('Network error during upload'));
xhr.send(file);
});
@@ -327,8 +377,8 @@ function uploadToR2(url, file, onProgress) {
// camera capture, selfie-to-mesh, and returns a GLB URL via postMessage.
// We fetch that GLB and run it through the same R2 upload path as manual uploads.
const RPM_SUBDOMAIN = 'demo'; // any public RPM subdomain works for self-serve
-const RPM_ORIGIN = `https://${RPM_SUBDOMAIN}.readyplayer.me`;
-const RPM_SRC = `${RPM_ORIGIN}/avatar?frameApi&bodyType=fullbody&clearCache=true`;
+const RPM_ORIGIN = `https://${RPM_SUBDOMAIN}.readyplayer.me`;
+const RPM_SRC = `${RPM_ORIGIN}/avatar?frameApi&bodyType=fullbody&clearCache=true`;
function renderCreate(root) {
root.innerHTML = `
@@ -353,11 +403,11 @@ function renderCreate(root) {
</div>
`;
- const launchBtn = root.querySelector('#rpm-launch');
+ const launchBtn = root.querySelector('#rpm-launch');
const restartBtn = root.querySelector('#rpm-restart');
- const intro = root.querySelector('#rpm-intro');
- const iframe = root.querySelector('#rpm-iframe');
- const progress = root.querySelector('#rpm-progress');
+ const intro = root.querySelector('#rpm-intro');
+ const iframe = root.querySelector('#rpm-iframe');
+ const progress = root.querySelector('#rpm-progress');
const say = (msg, isError = false) => {
progress.style.display = 'block';
@@ -382,7 +432,11 @@ function renderCreate(root) {
// Ready Player Me → subscribe to all events once its frame is ready.
if (data.eventName === 'v1.frame.ready') {
iframe.contentWindow?.postMessage(
- JSON.stringify({ target: 'readyplayerme', type: 'subscribe', eventName: 'v1.**' }),
+ JSON.stringify({
+ target: 'readyplayerme',
+ type: 'subscribe',
+ eventName: 'v1.**',
+ }),
RPM_ORIGIN,
);
return;
@@ -390,12 +444,17 @@ function renderCreate(root) {
if (data.eventName === 'v1.avatar.exported') {
const glbUrl = data.data?.url;
- if (!glbUrl) { say('No avatar URL returned', true); return; }
+ if (!glbUrl) {
+ say('No avatar URL returned', true);
+ return;
+ }
say('Fetching avatar…');
try {
const avatar = await saveRpmAvatar(glbUrl);
say(`Saved "${avatar.name}". Redirecting…`);
- setTimeout(() => { location.hash = 'avatars'; }, 600);
+ setTimeout(() => {
+ location.hash = 'avatars';
+ }, 600);
} catch (err) {
say(err.message || 'Failed to save avatar', true);
}
@@ -421,7 +480,11 @@ function renderCreate(root) {
function parseRpmMessage(raw) {
if (!raw) return null;
if (typeof raw === 'object') return raw;
- try { return JSON.parse(raw); } catch { return null; }
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
}
async function saveRpmAvatar(sourceUrl) {
@@ -442,7 +505,10 @@ async function saveRpmAvatar(sourceUrl) {
const xhr = new XMLHttpRequest();
xhr.open('PUT', upload_url);
xhr.setRequestHeader('content-type', contentType);
- xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));
+ xhr.onload = () =>
+ xhr.status >= 200 && xhr.status < 300
+ ? resolve()
+ : reject(new Error(`Upload failed (${xhr.status})`));
xhr.onerror = () => reject(new Error('Network error during upload'));
xhr.send(blob);
});
@@ -461,7 +527,9 @@ async function saveRpmAvatar(sourceUrl) {
// Wire the new avatar straight into the caller's default agent identity so
// the selfie immediately becomes the agent's body across the site.
- await attachAvatarToDefaultAgent(avatar.id).catch((e) => console.warn('attach to agent skipped:', e.message));
+ await attachAvatarToDefaultAgent(avatar.id).catch((e) =>
+ console.warn('attach to agent skipped:', e.message),
+ );
return avatar;
}
@@ -481,7 +549,10 @@ async function attachAvatarToDefaultAgent(avatarId) {
// ── Edit avatar ─────────────────────────────────────────────────────────────
async function renderEdit(root, params = []) {
const id = params[0];
- if (!id) { location.hash = 'avatars'; return; }
+ if (!id) {
+ location.hash = 'avatars';
+ return;
+ }
root.innerHTML = `
<div class="toolbar">
@@ -499,7 +570,9 @@ async function renderEdit(root, params = []) {
const body = root.querySelector('#edit-body');
let avatar;
try {
- const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });
+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, {
+ credentials: 'include',
+ });
if (!res.ok) throw new Error((await res.json()).error_description || res.statusText);
avatar = (await res.json()).avatar;
} catch (err) {
@@ -512,9 +585,11 @@ async function renderEdit(root, params = []) {
<div style="display:grid; grid-template-columns:minmax(260px,1fr) minmax(260px,2fr); gap:20px; align-items:start">
<div class="card" style="padding:10px">
<div class="preview" style="aspect-ratio:1/1; margin:0; background:#0f0f17; border-radius:10px; overflow:hidden">
- ${previewUrl
- ? `<model-viewer src="${attr(previewUrl)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" style="width:100%;height:100%"></model-viewer>`
- : `<div style="display:grid;place-items:center;height:100%;color:#555;font-size:12px">Preview unavailable</div>`}
+ ${
+ previewUrl
+ ? `<model-viewer src="${attr(previewUrl)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" style="width:100%;height:100%"></model-viewer>`
+ : `<div style="display:grid;place-items:center;height:100%;color:#555;font-size:12px">Preview unavailable</div>`
+ }
</div>
<p class="muted" style="margin:10px 4px 0">${fmtSize(avatar.size_bytes || 0)} · ${esc(avatar.source || 'upload')}</p>
</div>
@@ -523,7 +598,7 @@ async function renderEdit(root, params = []) {
<label style="display:block;margin-top:12px">Description<textarea id="edesc" rows="3" style="width:100%">${esc(avatar.description || '')}</textarea></label>
<label style="display:block;margin-top:12px">Visibility
<select id="evis" style="width:100%">
- ${['private','unlisted','public'].map((v) => `<option ${v===avatar.visibility?'selected':''} value="${v}">${v}</option>`).join('')}
+ ${['private', 'unlisted', 'public'].map((v) => `<option ${v === avatar.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}
</select>
</label>
<label style="display:block;margin-top:12px">Tags (comma separated)<input id="etags" value="${attr((avatar.tags || []).join(', '))}" style="width:100%"></label>
@@ -542,7 +617,10 @@ async function renderEdit(root, params = []) {
msg.style.color = '#888';
msg.textContent = 'Saving…';
try {
- const tags = (body.querySelector('#etags').value || '').split(',').map((s) => s.trim()).filter(Boolean);
+ const tags = (body.querySelector('#etags').value || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
await api.patchAvatar(id, {
name: body.querySelector('#ename').value.trim(),
description: body.querySelector('#edesc').value.trim() || undefined,
@@ -595,21 +673,37 @@ async function renderKeys(root) {
async function refresh() {
try {
const { keys } = await api.listKeys();
- if (!keys.length) { klist.innerHTML = '<div class="muted">No keys yet.</div>'; return; }
- klist.innerHTML = keys.map((k) => `
+ if (!keys.length) {
+ klist.innerHTML = '<div class="muted">No keys yet.</div>';
+ return;
+ }
+ klist.innerHTML = keys
+ .map(
+ (k) => `
<div class="key-row">
<div>
<div><code>${esc(k.prefix)}…</code> — ${esc(k.name)}</div>
- <div class="muted">scope: ${esc(k.scope)} · created ${new Date(k.created_at).toLocaleDateString()}${k.revoked_at?` · <b style="color:#f88">revoked</b>`:''}</div>
+ <div class="muted">scope: ${esc(k.scope)} · created ${new Date(k.created_at).toLocaleDateString()}${k.revoked_at ? ` · <b style="color:#f88">revoked</b>` : ''}</div>
</div>
${k.revoked_at ? '' : `<button class="btn sec" data-id="${esc(k.id)}">Revoke</button>`}
</div>
- `).join('');
- klist.querySelectorAll('button[data-id]').forEach((b) => b.addEventListener('click', async () => {
- if (!confirm('Revoke this key?')) return;
- try { await api.revokeKey(b.dataset.id); refresh(); } catch (e) { alert(e.message); }
- }));
- } catch (e) { klist.innerHTML = `<div class="err">${esc(e.message)}</div>`; }
+ `,
+ )
+ .join('');
+ klist.querySelectorAll('button[data-id]').forEach((b) =>
+ b.addEventListener('click', async () => {
+ if (!confirm('Revoke this key?')) return;
+ try {
+ await api.revokeKey(b.dataset.id);
+ refresh();
+ } catch (e) {
+ alert(e.message);
+ }
+ }),
+ );
+ } catch (e) {
+ klist.innerHTML = `<div class="err">${esc(e.message)}</div>`;
+ }
}
root.querySelector('#new').addEventListener('submit', async (e) => {
e.preventDefault();
@@ -626,7 +720,9 @@ async function renderKeys(root) {
`;
root.querySelector('#kname').value = '';
refresh();
- } catch (err) { alert(err.message); }
+ } catch (err) {
+ alert(err.message);
+ }
});
refresh();
}
@@ -643,11 +739,17 @@ function renderMcp(root) {
<h3 class="section">Claude Desktop / Claude Code (remote)</h3>
<p class="muted">Add a Custom Connector in Claude. When prompted, sign in with your 3D Agent account.</p>
- <pre><code>${esc(JSON.stringify({
- mcpServers: {
- '3d-agent': { url: `${origin}/api/mcp` }
- }
- }, null, 2))}</code></pre>
+ <pre><code>${esc(
+ JSON.stringify(
+ {
+ mcpServers: {
+ '3d-agent': { url: `${origin}/api/mcp` },
+ },
+ },
+ null,
+ 2,
+ ),
+ )}</code></pre>
<h3 class="section">Programmatic (API key)</h3>
<p class="muted">Bypass OAuth for server-to-server usage. Pass key as a bearer token.</p>
@@ -696,69 +798,69 @@ async function renderEmbed(root) {
const origin = location.origin;
const embedUrl = `${origin}/agent/${encodeURIComponent(agent.id)}/embed`;
- const homeUrl = `${origin}/agent/${encodeURIComponent(agent.id)}`;
+ const homeUrl = `${origin}/agent/${encodeURIComponent(agent.id)}`;
const iframeSnippet = `<iframe src="${embedUrl}" allow="camera; microphone" style="width:320px;height:420px;border:0;border-radius:16px;overflow:hidden" title="${esc(agent.name || 'Agent')}"></iframe>`;
const lobehubSnippet = [
- "// Drop into a Lobehub fork — renders the agent alongside the chat panel",
- "// and forwards assistant messages to it so the avatar speaks/emotes.",
+ '// Drop into a Lobehub fork — renders the agent alongside the chat panel',
+ '// and forwards assistant messages to it so the avatar speaks/emotes.',
"import { useEffect, useRef } from 'react';",
- "",
- "export function AgentSidecar({ latestAssistantMessage }) {",
+ '',
+ 'export function AgentSidecar({ latestAssistantMessage }) {',
` const AGENT_ID = ${JSON.stringify(agent.id)};`,
` const EMBED_URL = ${JSON.stringify(embedUrl)};`,
- " const ref = useRef(null);",
- "",
- " useEffect(() => {",
- " if (!ref.current || !latestAssistantMessage) return;",
- " ref.current.contentWindow?.postMessage({",
- " __agent: AGENT_ID,",
+ ' const ref = useRef(null);',
+ '',
+ ' useEffect(() => {',
+ ' if (!ref.current || !latestAssistantMessage) return;',
+ ' ref.current.contentWindow?.postMessage({',
+ ' __agent: AGENT_ID,',
" type: 'action',",
" action: { type: 'speak', payload: { text: latestAssistantMessage.text } },",
" }, '*');",
- " }, [latestAssistantMessage]);",
- "",
- " return <iframe ref={ref} src={EMBED_URL} allow=\"camera; microphone\"",
- " style={{ width: 320, height: 420, border: 0, borderRadius: 16 }} />;",
- "}",
+ ' }, [latestAssistantMessage]);',
+ '',
+ ' return <iframe ref={ref} src={EMBED_URL} allow="camera; microphone"',
+ ' style={{ width: 320, height: 420, border: 0, borderRadius: 16 }} />;',
+ '}',
].join('\n');
const claudeSnippet = [
- "<!-- Paste into Claude as an HTML Artifact. The avatar renders live. -->",
+ '<!-- Paste into Claude as an HTML Artifact. The avatar renders live. -->',
`<iframe src="${embedUrl}"`,
- " style=\"width:100%;height:480px;border:0;border-radius:16px\"",
- " allow=\"camera; microphone\"></iframe>",
+ ' style="width:100%;height:480px;border:0;border-radius:16px"',
+ ' allow="camera; microphone"></iframe>',
].join('\n');
const postMessageSnippet = [
- "// From any host page, make the avatar speak + emote:",
+ '// From any host page, make the avatar speak + emote:',
"const frame = document.querySelector('iframe');",
- "frame.contentWindow.postMessage({",
+ 'frame.contentWindow.postMessage({',
` __agent: ${JSON.stringify(agent.id)},`,
" type: 'action',",
" action: { type: 'speak', payload: { text: 'Hello from the host app' } },",
"}, '*');",
- "",
- "// Listen for agent readiness:",
+ '',
+ '// Listen for agent readiness:',
"window.addEventListener('message', (e) => {",
` if (e.data?.__agent === ${JSON.stringify(agent.id)} && e.data.type === 'ready') {`,
" console.log('agent online:', e.data.name);",
- " }",
- "});",
+ ' }',
+ '});',
].join('\n');
const sdkSnippet = [
- "<!-- Drop-in SDK around the postMessage Bridge v1. -->",
- "<!-- See /agent/" + agent.id + "/embed for the wire contract. -->",
+ '<!-- Drop-in SDK around the postMessage Bridge v1. -->',
+ '<!-- See /agent/' + agent.id + '/embed for the wire contract. -->',
`<iframe id="agent" src="${embedUrl}" allow="camera; microphone"`,
- " style=\"width:320px;height:420px;border:0;border-radius:16px\"></iframe>",
+ ' style="width:320px;height:420px;border:0;border-radius:16px"></iframe>',
`<script src="${origin}/embed-sdk.js"></script>`,
- "<script>",
+ '<script>',
" const bridge = Agent3D.connect(document.getElementById('agent'), {",
` agentId: ${JSON.stringify(agent.id)},`,
" onReady: ({ version, capabilities }) => console.log('ready', version, capabilities),",
" onAction: (action) => console.log('iframe emitted', action),",
" onResize: (h) => console.log('preferred height', h),",
" onError: (err) => console.warn('bridge error', err.message),",
- " });",
+ ' });',
" bridge.ready.then(() => bridge.send({ type: 'speak', payload: { text: 'Hi from host' } }));",
- "</script>",
+ '</script>',
].join('\n');
body.innerHTML = `
@@ -770,13 +872,17 @@ async function renderEmbed(root) {
<a href="${attr(homeUrl)}" target="_blank" class="muted">Home page →</a>
</div>
<p class="muted" style="padding:0 6px">Agent ID <code>${esc(agent.id)}</code></p>
- ${agent.wallet_address ? `
+ ${
+ agent.wallet_address
+ ? `
<p class="muted" style="padding:0 6px; margin-top:6px; line-height:1.4">
Agent wallet<br>
<code style="font-size:11px; word-break:break-all">${esc(agent.wallet_address)}</code><br>
<span style="font-size:11px">Server-held. Agents sign autonomously via <code style="font-size:11px">POST /api/agents/${esc(agent.id)}/sign</code>.</span>
</p>
- ` : ''}
+ `
+ : ''
+ }
</div>
<div>
${snippetBlock('Universal iframe (any site)', iframeSnippet, 'html')}
@@ -802,7 +908,9 @@ async function renderEmbed(root) {
await navigator.clipboard.writeText(target.textContent);
const original = btn.textContent;
btn.textContent = 'Copied';
- setTimeout(() => { btn.textContent = original; }, 1200);
+ setTimeout(() => {
+ btn.textContent = original;
+ }, 1200);
} catch {
btn.textContent = 'Copy failed';
}
@@ -855,8 +963,8 @@ function onchainCard(agent) {
// Attach the click handler after the embed DOM has been rendered. Called from
// renderEmbed below via a mutation after body.innerHTML is set.
function bindOnchainDeploy(body, agent) {
- const btn = body.querySelector('#onchain-deploy');
- const log = body.querySelector('#onchain-log');
+ const btn = body.querySelector('#onchain-deploy');
+ const log = body.querySelector('#onchain-log');
const token = body.querySelector('#onchain-ipfs-token');
if (!btn) return;
@@ -876,8 +984,11 @@ function bindOnchainDeploy(body, agent) {
try {
say('Fetching avatar GLB…');
- const avRes = await fetch(`/api/avatars/${encodeURIComponent(agent.avatar_id)}`, { credentials: 'include' });
- if (!avRes.ok) throw new Error((await avRes.json()).error_description || 'avatar fetch failed');
+ const avRes = await fetch(`/api/avatars/${encodeURIComponent(agent.avatar_id)}`, {
+ credentials: 'include',
+ });
+ if (!avRes.ok)
+ throw new Error((await avRes.json()).error_description || 'avatar fetch failed');
const avatarRow = (await avRes.json()).avatar;
const glbUrl = avatarRow.url || avatarRow.model_url;
if (!glbUrl) throw new Error('avatar has no URL');
@@ -897,19 +1008,30 @@ function bindOnchainDeploy(body, agent) {
say(`Persisting onchain IDs to your account…`);
const wallet = window.ethereum?.selectedAddress || '';
- const chainId = Number((await window.ethereum?.request?.({ method: 'eth_chainId' })) || 0) || undefined;
+ const chainId =
+ Number((await window.ethereum?.request?.({ method: 'eth_chainId' })) || 0) ||
+ undefined;
await fetch(`/api/agents/${encodeURIComponent(agent.id)}/wallet`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
wallet_address: wallet,
- chain_id: chainId ? parseInt(chainId.toString(16) === chainId.toString() ? chainId : String(chainId), 10) || null : null,
+ chain_id: chainId
+ ? parseInt(
+ chainId.toString(16) === chainId.toString()
+ ? chainId
+ : String(chainId),
+ 10,
+ ) || null
+ : null,
erc8004_agent_id: result.agentId,
}),
});
- say(`✓ Done. agentId=${result.agentId}, registration=ipfs://${result.registrationCID}, tx=${result.txHash}`);
+ say(
+ `✓ Done. agentId=${result.agentId}, registration=ipfs://${result.registrationCID}, tx=${result.txHash}`,
+ );
} catch (err) {
say(err.message || String(err), true);
} finally {
@@ -950,10 +1072,11 @@ function bindMyAgents(body) {
list.innerHTML = '';
try {
- const [{ connectWallet, getIdentityRegistry }, { REGISTRY_DEPLOYMENTS }] = await Promise.all([
- import('/src/erc8004/agent-registry.js'),
- import('/src/erc8004/abi.js'),
- ]);
+ 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];
@@ -970,7 +1093,9 @@ function bindMyAgents(body) {
const dbPromise = fetch(
`/api/agents/by-wallet?address=${encodeURIComponent(address)}&chain_id=${chainId}`,
{ credentials: 'include' },
- ).then((r) => (r.ok ? r.json() : { agents: [] })).catch(() => ({ agents: [] }));
+ )
+ .then((r) => (r.ok ? r.json() : { agents: [] }))
+ .catch(() => ({ agents: [] }));
if (balance === 0) {
const { agents: dbAgents = [] } = await dbPromise;
@@ -1002,7 +1127,9 @@ function bindMyAgents(body) {
try {
const owner = await registry.ownerOf(id);
if (owner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);
- } catch { /* token burned/transferred — skip */ }
+ } catch {
+ /* token burned/transferred — skip */
+ }
}
}
@@ -1023,14 +1150,20 @@ function bindMyAgents(body) {
async function fetchTokenMeta(registry, tokenId) {
let uri = '';
let meta = null;
- try { uri = await registry.tokenURI(tokenId); } catch { /* no URI set */ }
+ 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 */ }
+ } catch {
+ /* metadata unreachable */
+ }
}
return { id: tokenId, uri, meta };
}
@@ -1038,7 +1171,7 @@ async function fetchTokenMeta(registry, tokenId) {
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)}`;
+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;
return uri;
}
@@ -1059,7 +1192,8 @@ function renderAgentRows(list, onchainAgents, dbAgents) {
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.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>'}
@@ -1081,12 +1215,15 @@ function renderAgentRows(list, onchainAgents, dbAgents) {
// 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));
+ 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.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>
@@ -1117,22 +1254,30 @@ function renderBilling(root) {
// the dashboard is for managing what already exists.
const WIDGET_TYPE_META = {
- 'turntable': { label: 'Turntable', color: '#6a5cff' },
- 'animation-gallery': { label: 'Animations', color: '#ff5ca8' },
- 'talking-agent': { label: 'Talking Agent', color: '#00e5a0' },
- 'passport': { label: 'Passport', color: '#f0c14b' },
- 'hotspot-tour': { label: 'Hotspot Tour', color: '#5cc8ff' },
+ turntable: { label: 'Turntable', color: '#6a5cff' },
+ 'animation-gallery': { label: 'Animations', color: '#ff5ca8' },
+ 'talking-agent': { label: 'Talking Agent', color: '#00e5a0' },
+ passport: { label: 'Passport', color: '#f0c14b' },
+ 'hotspot-tour': { label: 'Hotspot Tour', color: '#5cc8ff' },
};
const WIDGET_PREFS_KEY = 'dashboard.widgets.prefs';
const DEFAULT_WIDGET_PREFS = { sort: 'updated', type: '', q: '' };
function loadWidgetPrefs() {
- try { return { ...DEFAULT_WIDGET_PREFS, ...JSON.parse(localStorage.getItem(WIDGET_PREFS_KEY) || '{}') }; }
- catch { return { ...DEFAULT_WIDGET_PREFS }; }
+ try {
+ return {
+ ...DEFAULT_WIDGET_PREFS,
+ ...JSON.parse(localStorage.getItem(WIDGET_PREFS_KEY) || '{}'),
+ };
+ } catch {
+ return { ...DEFAULT_WIDGET_PREFS };
+ }
}
function saveWidgetPrefs(prefs) {
- try { localStorage.setItem(WIDGET_PREFS_KEY, JSON.stringify(prefs)); } catch {}
+ try {
+ localStorage.setItem(WIDGET_PREFS_KEY, JSON.stringify(prefs));
+ } catch {}
}
async function renderWidgets(root) {
@@ -1151,14 +1296,18 @@ async function renderWidgets(root) {
<label class="sr-only" for="w-type">Filter by type</label>
<select id="w-type" aria-label="Filter by widget type">
<option value="">All types</option>
- ${Object.entries(WIDGET_TYPE_META).map(([t, m]) =>
- `<option value="${attr(t)}" ${prefs.type===t?'selected':''}>${esc(m.label)}</option>`).join('')}
+ ${Object.entries(WIDGET_TYPE_META)
+ .map(
+ ([t, m]) =>
+ `<option value="${attr(t)}" ${prefs.type === t ? 'selected' : ''}>${esc(m.label)}</option>`,
+ )
+ .join('')}
</select>
<label class="sr-only" for="w-sort">Sort widgets</label>
<select id="w-sort" aria-label="Sort widgets">
- <option value="updated" ${prefs.sort==='updated'?'selected':''}>Recently updated</option>
- <option value="views" ${prefs.sort==='views' ?'selected':''}>Most viewed</option>
- <option value="name" ${prefs.sort==='name' ?'selected':''}>Name (A–Z)</option>
+ <option value="updated" ${prefs.sort === 'updated' ? 'selected' : ''}>Recently updated</option>
+ <option value="views" ${prefs.sort === 'views' ? 'selected' : ''}>Most viewed</option>
+ <option value="name" ${prefs.sort === 'name' ? 'selected' : ''}>Name (A–Z)</option>
</select>
<span id="w-count" class="muted" aria-live="polite"></span>
</div>
@@ -1194,25 +1343,45 @@ async function renderWidgets(root) {
return;
}
const filtered = applyWidgetFilters(widgets, prefs);
- countEl.textContent = filtered.length === widgets.length
- ? `${widgets.length} widget${widgets.length===1?'':'s'}`
- : `${filtered.length} of ${widgets.length}`;
+ countEl.textContent =
+ filtered.length === widgets.length
+ ? `${widgets.length} widget${widgets.length === 1 ? '' : 's'}`
+ : `${filtered.length} of ${widgets.length}`;
list.innerHTML = '';
if (!filtered.length) {
list.innerHTML = `<div class="empty" style="grid-column:1/-1">No widgets match the current filters.</div>`;
return;
}
for (const w of filtered) {
- const card = widgetCard(w, { reload: rerender, mutate: (next) => mutateLocal(widgets, w.id, next), remove: () => { widgets = widgets.filter((x) => x.id !== w.id); rerender(); } });
+ const card = widgetCard(w, {
+ reload: rerender,
+ mutate: (next) => mutateLocal(widgets, w.id, next),
+ remove: () => {
+ widgets = widgets.filter((x) => x.id !== w.id);
+ rerender();
+ },
+ });
list.appendChild(card);
const ifr = card.querySelector('iframe[data-src]');
if (ifr) observer.observe(ifr);
}
}
- root.querySelector('#w-search').addEventListener('input', (e) => { prefs.q = e.target.value; saveWidgetPrefs(prefs); rerender(); });
- root.querySelector('#w-type').addEventListener('change', (e) => { prefs.type = e.target.value; saveWidgetPrefs(prefs); rerender(); });
- root.querySelector('#w-sort').addEventListener('change', (e) => { prefs.sort = e.target.value; saveWidgetPrefs(prefs); rerender(); });
+ root.querySelector('#w-search').addEventListener('input', (e) => {
+ prefs.q = e.target.value;
+ saveWidgetPrefs(prefs);
+ rerender();
+ });
+ root.querySelector('#w-type').addEventListener('change', (e) => {
+ prefs.type = e.target.value;
+ saveWidgetPrefs(prefs);
+ rerender();
+ });
+ root.querySelector('#w-sort').addEventListener('change', (e) => {
+ prefs.sort = e.target.value;
+ saveWidgetPrefs(prefs);
+ rerender();
+ });
rerender();
}
@@ -1230,8 +1399,8 @@ function applyWidgetFilters(widgets, prefs) {
if (q) out = out.filter((w) => (w.name || '').toLowerCase().includes(q));
}
out = [...out];
- if (prefs.sort === 'name') out.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
- if (prefs.sort === 'views') out.sort((a, b) => (b.view_count || 0) - (a.view_count || 0));
+ if (prefs.sort === 'name') out.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ if (prefs.sort === 'views') out.sort((a, b) => (b.view_count || 0) - (a.view_count || 0));
if (prefs.sort === 'updated' || !prefs.sort) {
out.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
}
@@ -1258,7 +1427,7 @@ function widgetCard(w, ctx) {
<div class="row" style="justify-content:space-between; gap:8px">
<span class="meta">${formatViewCount(w.view_count)} · updated ${timeAgo(w.updated_at)}</span>
<label class="toggle" title="${w.is_public ? 'Public — anyone with the URL can view' : 'Private — only you can view'}">
- <input type="checkbox" data-public ${w.is_public?'checked':''}>
+ <input type="checkbox" data-public ${w.is_public ? 'checked' : ''}>
<span class="track"></span>
<span class="label">${w.is_public ? 'Public' : 'Private'}</span>
</label>
@@ -1280,7 +1449,12 @@ function widgetCard(w, ctx) {
const toggleInput = card.querySelector('input[data-public]');
toggleInput.addEventListener('change', async () => {
const next = toggleInput.checked;
- if (!next && !confirm('Making this widget private will break any existing embeds on other sites. Continue?')) {
+ if (
+ !next &&
+ !confirm(
+ 'Making this widget private will break any existing embeds on other sites. Continue?',
+ )
+ ) {
toggleInput.checked = true;
return;
}
@@ -1303,7 +1477,9 @@ function widgetCard(w, ctx) {
toast('Duplicated');
// Re-fetch via navigate so the new row's avatar join is populated.
navigate('widgets');
- } catch (err) { toast(err.message || 'Duplicate failed', true); }
+ } catch (err) {
+ toast(err.message || 'Duplicate failed', true);
+ }
});
card.querySelector('[data-delete]').addEventListener('click', async () => {
if (!confirm(`Delete "${w.name || 'this widget'}"? This cannot be undone.`)) return;
@@ -1313,7 +1489,9 @@ function widgetCard(w, ctx) {
card.style.opacity = '0';
setTimeout(() => ctx.remove(), 220);
toast('Deleted');
- } catch (err) { toast(err.message || 'Delete failed', true); }
+ } catch (err) {
+ toast(err.message || 'Delete failed', true);
+ }
});
return card;
@@ -1334,7 +1512,8 @@ function beginRename(card, w, ctx) {
let settled = false;
const restore = (text) => {
- if (settled) return; settled = true;
+ if (settled) return;
+ settled = true;
const h = document.createElement('h3');
h.textContent = text;
h.title = 'Double-click to rename';
@@ -1343,14 +1522,22 @@ function beginRename(card, w, ctx) {
};
input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); commit(); }
- else if (e.key === 'Escape') { e.preventDefault(); restore(original); }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ commit();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ restore(original);
+ }
});
input.addEventListener('blur', commit);
async function commit() {
const next = input.value.trim();
- if (!next || next === original) { restore(original); return; }
+ if (!next || next === original) {
+ restore(original);
+ return;
+ }
try {
await api.patchWidget(w.id, { name: next });
ctx.mutate({ name: next });
@@ -1366,16 +1553,23 @@ function beginRename(card, w, ctx) {
function lazyIframeObserver() {
if (typeof IntersectionObserver === 'undefined') {
// Fallback — eagerly hydrate. Old browsers shouldn't pay this a/b cost.
- return { observe(el) { hydrate(el); } };
+ return {
+ observe(el) {
+ hydrate(el);
+ },
+ };
}
- const io = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (entry.isIntersecting) {
- hydrate(entry.target);
- io.unobserve(entry.target);
+ const io = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) {
+ hydrate(entry.target);
+ io.unobserve(entry.target);
+ }
}
- }
- }, { rootMargin: '120px' });
+ },
+ { rootMargin: '120px' },
+ );
return io;
function hydrate(el) {
const src = el.getAttribute('data-src');
@@ -1394,7 +1588,7 @@ async function openWidgetDrawer(w, ctx) {
drawer.tabIndex = -1;
const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
- const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;
+ const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;
const iframeSnippet = makeIframeSnippet(w, pageUrl, 600, 600);
const scriptSnippet = `<script async src="${location.origin}/embed.js" data-widget="${esc(w.id)}"></script>`;
const meta = WIDGET_TYPE_META[w.type] || { label: w.type, color: '#888' };
@@ -1442,15 +1636,24 @@ async function openWidgetDrawer(w, ctx) {
document.body.appendChild(overlay);
document.body.appendChild(drawer);
- requestAnimationFrame(() => { overlay.classList.add('open'); drawer.classList.add('open'); });
+ requestAnimationFrame(() => {
+ overlay.classList.add('open');
+ drawer.classList.add('open');
+ });
drawer.focus();
const close = () => {
overlay.classList.remove('open');
drawer.classList.remove('open');
- setTimeout(() => { overlay.remove(); drawer.remove(); document.removeEventListener('keydown', onKey); }, 220);
+ setTimeout(() => {
+ overlay.remove();
+ drawer.remove();
+ document.removeEventListener('keydown', onKey);
+ }, 220);
+ };
+ const onKey = (e) => {
+ if (e.key === 'Escape') close();
};
- const onKey = (e) => { if (e.key === 'Escape') close(); };
document.addEventListener('keydown', onKey);
overlay.addEventListener('click', close);
drawer.querySelector('[data-close]').addEventListener('click', close);
@@ -1469,7 +1672,9 @@ async function openWidgetDrawer(w, ctx) {
toast('Deleted');
close();
ctx?.remove?.();
- } catch (err) { toast(err.message || 'Delete failed', true); }
+ } catch (err) {
+ toast(err.message || 'Delete failed', true);
+ }
});
// Stats — load async, render sparkline.
@@ -1477,15 +1682,17 @@ async function openWidgetDrawer(w, ctx) {
const { stats } = await api.widgetStats(w.id);
drawer.querySelector('#stats-region').innerHTML = renderStatsPanel(w, stats);
} catch (err) {
- drawer.querySelector('#stats-region').innerHTML = `<div class="err">${esc(err.message || 'Failed to load stats')}</div>`;
+ drawer.querySelector('#stats-region').innerHTML =
+ `<div class="err">${esc(err.message || 'Failed to load stats')}</div>`;
}
}
function renderStatsPanel(w, stats) {
const total7d = (stats.recent_views_7d || []).reduce((s, d) => s + (d.count || 0), 0);
- const chatLine = stats.chat_count !== null && stats.chat_count !== undefined
- ? `<div class="stat"><div class="n">${formatNum(stats.chat_count)}</div><div class="l">Chats (lifetime)</div></div>`
- : '';
+ const chatLine =
+ stats.chat_count !== null && stats.chat_count !== undefined
+ ? `<div class="stat"><div class="n">${formatNum(stats.chat_count)}</div><div class="l">Chats (lifetime)</div></div>`
+ : '';
const lastSeen = stats.last_viewed_at
? `<div class="muted" style="margin-top:4px; font-size:12px">Last viewed ${timeAgo(stats.last_viewed_at)}</div>`
: '';
@@ -1509,7 +1716,9 @@ function renderStatsPanel(w, stats) {
function sparkline(days) {
if (!days.length) return '<div class="muted" style="font-size:12px">No views yet</div>';
- const W = 480, H = 60, P = 4;
+ const W = 480,
+ H = 60,
+ P = 4;
const max = Math.max(1, ...days.map((d) => d.count || 0));
const stepX = (W - 2 * P) / Math.max(1, days.length - 1);
const pts = days.map((d, i) => {
@@ -1517,13 +1726,19 @@ function sparkline(days) {
const y = H - P - ((d.count || 0) / max) * (H - 2 * P);
return [x, y];
});
- const linePath = pts.map((p, i) => (i === 0 ? `M${p[0].toFixed(1)},${p[1].toFixed(1)}` : `L${p[0].toFixed(1)},${p[1].toFixed(1)}`)).join(' ');
- const areaPath = `${linePath} L${pts[pts.length-1][0].toFixed(1)},${H-P} L${pts[0][0].toFixed(1)},${H-P} Z`;
+ const linePath = pts
+ .map((p, i) =>
+ i === 0
+ ? `M${p[0].toFixed(1)},${p[1].toFixed(1)}`
+ : `L${p[0].toFixed(1)},${p[1].toFixed(1)}`,
+ )
+ .join(' ');
+ const areaPath = `${linePath} L${pts[pts.length - 1][0].toFixed(1)},${H - P} L${pts[0][0].toFixed(1)},${H - P} Z`;
const allZero = days.every((d) => !d.count);
- const labels = `${esc(days[0].day)} → ${esc(days[days.length-1].day)}`;
+ const labels = `${esc(days[0].day)} → ${esc(days[days.length - 1].day)}`;
return `
<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Views over the last 7 days, ${days.map((d) => `${d.day}: ${d.count}`).join(', ')}">
- <line class="axis" x1="${P}" y1="${H-P}" x2="${W-P}" y2="${H-P}"></line>
+ <line class="axis" x1="${P}" y1="${H - P}" x2="${W - P}" y2="${H - P}"></line>
${allZero ? '' : `<path class="area" d="${areaPath}"></path><path class="line" d="${linePath}"></path>`}
</svg>
<div class="muted" style="font-size:11px; display:flex; justify-content:space-between; padding:0 4px">
@@ -1536,10 +1751,10 @@ function sparkline(days) {
// ── Share modal ─────────────────────────────────────────────────────────────
function openShareModal(w) {
const SIZES = [
- { label: 'Small', width: 320, height: 320 },
- { label: 'Medium', width: 600, height: 600 },
+ { label: 'Small', width: 320, height: 320 },
+ { label: 'Medium', width: 600, height: 600 },
{ label: 'Banner', width: 1200, height: 400 },
- { label: 'Custom', width: 0, height: 0 },
+ { label: 'Custom', width: 0, height: 0 },
];
let active = 1;
let dim = { ...SIZES[active] };
@@ -1552,11 +1767,11 @@ function openShareModal(w) {
<h2>Share "${esc(w.name || 'widget')}"</h2>
<p class="sub">Pick a size, copy the iframe, and you're done.</p>
<div class="size-presets" role="tablist">
- ${SIZES.map((s, i) => `<button type="button" data-i="${i}" class="${i===active?'active':''}" role="tab" aria-selected="${i===active}">${esc(s.label)}${s.width?` (${s.width}×${s.height})`:''}</button>`).join('')}
+ ${SIZES.map((s, i) => `<button type="button" data-i="${i}" class="${i === active ? 'active' : ''}" role="tab" aria-selected="${i === active}">${esc(s.label)}${s.width ? ` (${s.width}×${s.height})` : ''}</button>`).join('')}
</div>
<div class="size-inputs">
- <label class="muted" style="font-size:12px">W <input id="m-w" type="number" min="120" max="2000" value="${dim.width||600}"></label>
- <label class="muted" style="font-size:12px">H <input id="m-h" type="number" min="120" max="2000" value="${dim.height||600}"></label>
+ <label class="muted" style="font-size:12px">W <input id="m-w" type="number" min="120" max="2000" value="${dim.width || 600}"></label>
+ <label class="muted" style="font-size:12px">H <input id="m-h" type="number" min="120" max="2000" value="${dim.height || 600}"></label>
</div>
<div style="background:#0f0f17; border:1px solid var(--border); border-radius:10px; padding:12px; margin-bottom:12px">
<div class="muted" style="font-size:11px; margin-bottom:8px">Live preview (scaled to fit)</div>
@@ -1584,7 +1799,8 @@ function openShareModal(w) {
const snippet = makeIframeSnippet(w, pageUrl, dim.width, dim.height);
snipEl.textContent = snippet;
// Live preview at scaled size — fit within 320×320 while preserving ratio.
- const maxW = 320, maxH = 320;
+ const maxW = 320,
+ maxH = 320;
const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);
previewEl.innerHTML = `<iframe src="/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;
previewEl.style.width = `${dim.width * scale}px`;
@@ -1598,7 +1814,8 @@ function openShareModal(w) {
});
if (SIZES[i].width) {
dim = { width: SIZES[i].width, height: SIZES[i].height };
- wInput.value = dim.width; hInput.value = dim.height;
+ wInput.value = dim.width;
+ hInput.value = dim.height;
}
refresh();
}
@@ -1606,7 +1823,10 @@ function openShareModal(w) {
b.addEventListener('click', () => setPreset(Number(b.dataset.i)));
});
const onDimChange = () => {
- dim = { width: clampInt(wInput.value, 120, 2000, 600), height: clampInt(hInput.value, 120, 2000, 600) };
+ dim = {
+ width: clampInt(wInput.value, 120, 2000, 600),
+ height: clampInt(hInput.value, 120, 2000, 600),
+ };
// Switch to "Custom" preset when typing.
setPresetSilent(SIZES.length - 1);
refresh();
@@ -1623,13 +1843,22 @@ function openShareModal(w) {
const close = () => {
overlay.classList.remove('open');
- setTimeout(() => { overlay.remove(); document.removeEventListener('keydown', onKey); }, 200);
+ setTimeout(() => {
+ overlay.remove();
+ document.removeEventListener('keydown', onKey);
+ }, 200);
+ };
+ const onKey = (e) => {
+ if (e.key === 'Escape') close();
};
- const onKey = (e) => { if (e.key === 'Escape') close(); };
document.addEventListener('keydown', onKey);
- overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) close();
+ });
overlay.querySelector('#m-close').addEventListener('click', close);
- overlay.querySelector('#m-copy').addEventListener('click', (e) => copyToClipboard(snipEl.textContent, e.currentTarget));
+ overlay
+ .querySelector('#m-copy')
+ .addEventListener('click', (e) => copyToClipboard(snipEl.textContent, e.currentTarget));
refresh();
}
@@ -1653,7 +1882,9 @@ async function copyToClipboard(text, btn) {
if (btn) {
const orig = btn.textContent;
btn.textContent = 'Copied';
- setTimeout(() => { btn.textContent = orig; }, 1100);
+ setTimeout(() => {
+ btn.textContent = orig;
+ }, 1100);
}
} catch {
toast('Copy failed — select and ⌘C manually', true);
@@ -1667,11 +1898,18 @@ function toast(message, isError = false) {
clearTimeout(_toastTimer);
const el = document.createElement('div');
el.className = 'toast';
- if (isError) { el.style.color = '#ffb3b3'; el.style.borderColor = 'rgba(255,92,92,.4)'; }
+ if (isError) {
+ el.style.color = '#ffb3b3';
+ el.style.borderColor = 'rgba(255,92,92,.4)';
+ }
el.setAttribute('role', isError ? 'alert' : 'status');
el.textContent = message;
document.body.appendChild(el);
- _toastTimer = setTimeout(() => { el.style.opacity = '0'; el.style.transition = 'opacity .25s'; setTimeout(() => el.remove(), 260); }, 2200);
+ _toastTimer = setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transition = 'opacity .25s';
+ setTimeout(() => el.remove(), 260);
+ }, 2200);
}
function timeAgo(ts) {
@@ -1679,22 +1917,22 @@ function timeAgo(ts) {
const then = new Date(ts).getTime();
const now = Date.now();
const sec = Math.max(1, Math.round((now - then) / 1000));
- if (sec < 60) return `${sec}s ago`;
+ if (sec < 60) return `${sec}s ago`;
const min = Math.round(sec / 60);
- if (min < 60) return `${min}m ago`;
- const hr = Math.round(min / 60);
- if (hr < 24) return `${hr}h ago`;
+ if (min < 60) return `${min}m ago`;
+ const hr = Math.round(min / 60);
+ if (hr < 24) return `${hr}h ago`;
const day = Math.round(hr / 24);
- if (day < 30) return `${day}d ago`;
- const mo = Math.round(day / 30);
- if (mo < 12) return `${mo}mo ago`;
+ if (day < 30) return `${day}d ago`;
+ const mo = Math.round(day / 30);
+ if (mo < 12) return `${mo}mo ago`;
return `${Math.round(mo / 12)}y ago`;
}
function formatNum(n) {
const v = Number(n || 0);
- if (v < 1000) return String(v);
- if (v < 10000) return (v / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
+ if (v < 1000) return String(v);
+ if (v < 10000) return (v / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
if (v < 1_000_000) return Math.round(v / 1000) + 'k';
return (v / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
}
@@ -1723,20 +1961,30 @@ async function renderAnimations(root) {
try {
const res = await api.getAgentMe();
agent = res?.agent;
- if (!agent) { body.innerHTML = `<div class="empty">No agent found. <a href="#create">Create one first.</a></div>`; return; }
+ if (!agent) {
+ body.innerHTML = `<div class="empty">No agent found. <a href="#create">Create one first.</a></div>`;
+ return;
+ }
if (agent.avatar_id) {
try {
const av = await api.getAvatar(agent.avatar_id);
avatarUrl = av?.avatar?.url || av?.avatar?.model_url;
- } catch { /* no avatar URL */ }
+ } catch {
+ /* no avatar URL */
+ }
}
} catch (e) {
- body.innerHTML = `<div class="err">${esc(e.message)}</div>`; return;
+ body.innerHTML = `<div class="err">${esc(e.message)}</div>`;
+ return;
}
let animations = Array.isArray(agent.meta?.animations) ? [...agent.meta.animations] : [];
let presets = [];
- try { presets = await fetch('/animations/presets.json').then((r) => r.json()); } catch { /* presets unavailable */ }
+ try {
+ presets = await fetch('/animations/presets.json').then((r) => r.json());
+ } catch {
+ /* presets unavailable */
+ }
let saveTimer;
const statusEl = document.createElement('p');
@@ -1752,7 +2000,9 @@ async function renderAnimations(root) {
await api.patchAgentAnimations(agent.id, animations);
statusEl.style.color = '#9a8cff';
statusEl.textContent = 'Saved.';
- setTimeout(() => { if (statusEl.textContent === 'Saved.') statusEl.textContent = ''; }, 2000);
+ setTimeout(() => {
+ if (statusEl.textContent === 'Saved.') statusEl.textContent = '';
+ }, 2000);
} catch (err) {
statusEl.style.color = '#ffb3b3';
statusEl.textContent = err.message || 'Save failed.';
@@ -1760,14 +2010,17 @@ async function renderAnimations(root) {
}, 500);
}
- function isAttached(name) { return animations.some((a) => a.name.toLowerCase() === name.toLowerCase()); }
+ function isAttached(name) {
+ return animations.some((a) => a.name.toLowerCase() === name.toLowerCase());
+ }
let listEl, presetGridEl;
function renderClipList() {
listEl.innerHTML = '';
if (!animations.length) {
- listEl.innerHTML = '<div class="muted" style="padding:12px 0">No clips attached yet.</div>';
+ listEl.innerHTML =
+ '<div class="muted" style="padding:12px 0">No clips attached yet.</div>';
return;
}
for (const clip of animations) {
@@ -1795,7 +2048,9 @@ async function renderAnimations(root) {
renderPresetGrid();
debounceSync();
});
- row.querySelector('.preview-btn').addEventListener('click', () => openAnimPreview(clip, avatarUrl));
+ row.querySelector('.preview-btn').addEventListener('click', () =>
+ openAnimPreview(clip, avatarUrl),
+ );
listEl.appendChild(row);
}
}
@@ -1810,8 +2065,18 @@ async function renderAnimations(root) {
tile.innerHTML = `<div class="icon">${esc(p.icon || '🎬')}</div><div class="label">${esc(p.label || p.name)}</div>`;
tile.title = attached ? 'Already attached' : `Add "${p.name}"`;
tile.addEventListener('click', () => {
- if (isAttached(p.name)) { toast('Already attached'); return; }
- animations.push({ name: p.name, url: p.url, loop: p.loop !== false, clipName: p.clipName || undefined, source: 'preset', addedAt: new Date().toISOString() });
+ if (isAttached(p.name)) {
+ toast('Already attached');
+ return;
+ }
+ animations.push({
+ name: p.name,
+ url: p.url,
+ loop: p.loop !== false,
+ clipName: p.clipName || undefined,
+ source: 'preset',
+ addedAt: new Date().toISOString(),
+ });
renderClipList();
renderPresetGrid();
debounceSync();
@@ -1884,18 +2149,46 @@ async function renderAnimations(root) {
const name = nameEl.value.trim();
const file = fileEl.files?.[0];
uploadErr.textContent = '';
- if (!name) { uploadErr.textContent = 'Name is required.'; return; }
- if (name.length > 60) { uploadErr.textContent = 'Name too long (max 60 chars).'; return; }
- if (isAttached(name)) { uploadErr.textContent = `"${name}" is already attached.`; return; }
- if (!file) { uploadErr.textContent = 'Select a .glb file.'; return; }
+ if (!name) {
+ uploadErr.textContent = 'Name is required.';
+ return;
+ }
+ if (name.length > 60) {
+ uploadErr.textContent = 'Name too long (max 60 chars).';
+ return;
+ }
+ if (isAttached(name)) {
+ uploadErr.textContent = `"${name}" is already attached.`;
+ return;
+ }
+ if (!file) {
+ uploadErr.textContent = 'Select a .glb file.';
+ return;
+ }
uploadBtn.disabled = true;
uploadProgress.textContent = 'Requesting upload URL…';
try {
- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'anim';
- const { upload_url, storage_key } = await api.presignAnimation({ size_bytes: file.size, content_type: 'model/gltf-binary', slug });
+ const slug =
+ name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '') || 'anim';
+ const { upload_url, storage_key } = await api.presignAnimation({
+ size_bytes: file.size,
+ content_type: 'model/gltf-binary',
+ slug,
+ });
uploadProgress.textContent = `Uploading ${fmtSize(file.size)}…`;
- await _uploadXHR(upload_url, file, (pct) => { uploadProgress.textContent = `Uploading ${pct}%…`; });
- animations.push({ name, url: storage_key, loop: true, source: 'custom', addedAt: new Date().toISOString() });
+ await _uploadXHR(upload_url, file, (pct) => {
+ uploadProgress.textContent = `Uploading ${pct}%…`;
+ });
+ animations.push({
+ name,
+ url: storage_key,
+ loop: true,
+ source: 'custom',
+ addedAt: new Date().toISOString(),
+ });
renderClipList();
renderPresetGrid();
debounceSync();
@@ -1916,8 +2209,12 @@ function _uploadXHR(url, file, onProgress) {
const xhr = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.setRequestHeader('content-type', 'model/gltf-binary');
- xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));
- xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));
+ xhr.upload.onprogress = (e) =>
+ e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));
+ xhr.onload = () =>
+ xhr.status >= 200 && xhr.status < 300
+ ? resolve()
+ : reject(new Error(`Upload failed (${xhr.status})`));
xhr.onerror = () => reject(new Error('Network error'));
xhr.send(file);
});
@@ -1927,11 +2224,19 @@ let _animPreviewEl = null;
async function _ensureAgent3DLib() {
if (customElements.get('agent-3d')) return true;
- try { await import('/dist-lib/agent-3d.js'); return true; } catch { return false; }
+ try {
+ await import('/dist-lib/agent-3d.js');
+ return true;
+ } catch {
+ return false;
+ }
}
async function openAnimPreview(clip, avatarUrl) {
- if (!avatarUrl) { toast('No avatar URL available for preview', true); return; }
+ if (!avatarUrl) {
+ toast('No avatar URL available for preview', true);
+ return;
+ }
let overlay = document.getElementById('anim-preview-overlay');
if (!overlay) {
@@ -1950,7 +2255,9 @@ async function openAnimPreview(clip, avatarUrl) {
`;
document.body.appendChild(overlay);
overlay.querySelector('#ap-close').addEventListener('click', closeAnimPreview);
- overlay.addEventListener('click', (e) => { if (e.target === overlay) closeAnimPreview(); });
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) closeAnimPreview();
+ });
}
closeAnimPreview();
@@ -1962,7 +2269,10 @@ async function openAnimPreview(clip, avatarUrl) {
status.textContent = 'Loading library…';
const ok = await _ensureAgent3DLib();
- if (!ok) { status.textContent = 'Could not load 3D viewer.'; return; }
+ if (!ok) {
+ status.textContent = 'Could not load 3D viewer.';
+ return;
+ }
const el = document.createElement('agent-3d');
el.setAttribute('body', avatarUrl);
@@ -1975,23 +2285,44 @@ async function openAnimPreview(clip, avatarUrl) {
status.textContent = 'Loading avatar…';
try {
await new Promise((resolve, reject) => {
- const onReady = () => { el.removeEventListener('agent:ready', onReady); el.removeEventListener('agent:error', onErr); resolve(); };
- const onErr = (e) => { el.removeEventListener('agent:ready', onReady); el.removeEventListener('agent:error', onErr); reject(new Error(e.detail?.error?.message || 'load failed')); };
+ const onReady = () => {
+ el.removeEventListener('agent:ready', onReady);
+ el.removeEventListener('agent:error', onErr);
+ resolve();
+ };
+ const onErr = (e) => {
+ el.removeEventListener('agent:ready', onReady);
+ el.removeEventListener('agent:error', onErr);
+ reject(new Error(e.detail?.error?.message || 'load failed'));
+ };
el.addEventListener('agent:ready', onReady);
el.addEventListener('agent:error', onErr);
});
- } catch (e) { status.textContent = `Error: ${e.message}`; return; }
+ } catch (e) {
+ status.textContent = `Error: ${e.message}`;
+ return;
+ }
let hasBones = false;
- el._scene?.content?.traverse?.((n) => { if (n.isBone) hasBones = true; });
- if (!hasBones) { status.textContent = 'This avatar has no skeleton — clips cannot be previewed.'; return; }
+ el._scene?.content?.traverse?.((n) => {
+ if (n.isBone) hasBones = true;
+ });
+ if (!hasBones) {
+ status.textContent = 'This avatar has no skeleton — clips cannot be previewed.';
+ return;
+ }
status.textContent = `Loading clip "${clip.name}"…`;
try {
const gltf = await el._scene.loadGLB(clip.url);
const clips = gltf?.animations || [];
- const target = clip.clipName ? (clips.find((c) => c.name === clip.clipName) || clips[0]) : clips[0];
- if (!target) { status.textContent = 'No animation found in clip file.'; return; }
+ const target = clip.clipName
+ ? clips.find((c) => c.name === clip.clipName) || clips[0]
+ : clips[0];
+ if (!target) {
+ status.textContent = 'No animation found in clip file.';
+ return;
+ }
await el._scene.play(target, { blend: 0.35 });
status.textContent = `Playing "${clip.name}"`;
} catch (e) {
@@ -2001,8 +2332,12 @@ async function openAnimPreview(clip, avatarUrl) {
function closeAnimPreview() {
if (_animPreviewEl) {
- try { _animPreviewEl.destroy?.(); } catch {}
- try { _animPreviewEl.remove(); } catch {}
+ try {
+ _animPreviewEl.destroy?.();
+ } catch {}
+ try {
+ _animPreviewEl.remove();
+ } catch {}
_animPreviewEl = null;
}
const stage = document.getElementById('ap-stage');
@@ -2012,6 +2347,17 @@ function closeAnimPreview() {
}
// ── utils ───────────────────────────────────────────────────────────────────
-function fmtSize(b) { if (b < 1024) return b + ' B'; if (b < 1024*1024) return (b/1024).toFixed(1) + ' KB'; return (b/1024/1024).toFixed(1) + ' MB'; }
-function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
-function attr(s) { return esc(s); }
+function fmtSize(b) {
+ if (b < 1024) return b + ' B';
+ if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
+ return (b / 1024 / 1024).toFixed(1) + ' MB';
+}
+function esc(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+function attr(s) {
+ return esc(s);
+}
diff --git a/src/app.js b/src/app.js
index 8ee318121..2b322bf63 100644
--- a/src/app.js
+++ b/src/app.js
@@ -48,6 +48,51 @@ function _base64ToFile(b64, name, type) {
return new File([bytes], name, { type });
}
+/**
+ * Parse an on-chain agent URL path. Accepts:
+ * /a/<chainId>/<agentId> (canonical — registry inferred)
+ * /a/<chainId>/<registry>/<agentId> (explicit registry, for non-canonical deployments)
+ * /a/eip155:<chainId>:<registry>/<agentId> (full CAIP)
+ */
+function parseOnchainPath(pathname) {
+ const m = pathname.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 };
+ }
+
+ // /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 };
+ }
+
+ // /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 null;
+}
+
+function escHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/** Parse #onchain=<chainId>:<agentId> for embed mode. */
+function parseOnchainHash(value) {
+ if (!value) return null;
+ const m = String(value).match(/^(\d+):(\d+)$/);
+ if (!m) return null;
+ return { chainId: Number(m[1]), agentId: m[2] };
+}
+
if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
console.error('The File APIs are not fully supported in this browser.');
} else if (!WebGL.isWebGL2Available()) {
@@ -66,6 +111,12 @@ class App {
// agentHash: from #agent= hash → legacy embed mode
const agentQuery = qp.get('agent') || '';
const agentHash = hash.agent || '';
+
+ // On-chain CAIP-style route: /a/<chainId>/<agentId> [ /<registry> optional ]
+ // Parses to { chainId, agentId, registry? } when matched. Renders the agent's
+ // 3D avatar by resolving its registration file → `avatar` service endpoint.
+ const onchain = parseOnchainPath(location.pathname) || parseOnchainHash(hash.onchain);
+
this.options = {
kiosk: Boolean(hash.kiosk),
model: hash.model || '',
@@ -77,6 +128,8 @@ class App {
agentEdit: agentQuery, // query-param agent → editing surface
widget: hash.widget || '',
deploy: hash.deploy !== undefined || location.pathname === '/deploy',
+ onchain, // { chainId, agentId, registry? } | null
+ explore: location.pathname === '/explore',
// pending=1 signals a post-login save round-trip
pending: qp.get('pending') === '1',
};
@@ -133,6 +186,20 @@ class App {
return;
}
+ // /explore — gallery of on-chain agents with 3D avatars.
+ if (options.explore) {
+ this._showExplorePage();
+ this._initAgentSystem();
+ return;
+ }
+
+ // /a/<chainId>/<agentId> — resolve an on-chain agent to its 3D avatar.
+ if (options.onchain) {
+ this._loadOnChainAgent(options.onchain);
+ this._initAgentSystem();
+ return;
+ }
+
// Load a specific agent by ID: /#agent=<uuid> (embed mode)
if (options.agent) {
this._loadAgent(options.agent);
@@ -1029,11 +1096,121 @@ class App {
console.error(error);
}
+ /**
+ * Resolve an on-chain ERC-8004 agent to its 3D avatar and render it.
+ * Public — works for anyone, no wallet required.
+ *
+ * @param {{ chainId: number, agentId: string, registry?: string }} onchain
+ */
+ async _loadOnChainAgent(onchain) {
+ try {
+ 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}`);
+ return;
+ }
+
+ const { uri } = await getAgentOnchain({
+ chainId: onchain.chainId,
+ agentId: onchain.agentId,
+ ethProvider: window.ethereum,
+ });
+ if (!uri) {
+ this._showOnChainError(`Agent #${onchain.agentId} has no agentURI set.`);
+ return;
+ }
+
+ const meta = await fetchAgentMetadata(uri);
+ if (!meta.ok) {
+ this._showOnChainError(`Could not fetch registration JSON: ${meta.error}`);
+ return;
+ }
+
+ this._onchainMetadata = meta.data;
+ this._updateOnChainCard(onchain, meta.data);
+
+ const glbUri = findAvatar3D(meta.data);
+ if (!glbUri) {
+ this._showOnChainError(
+ `Agent #${onchain.agentId} has no 3D avatar — no <code>avatar</code> service entry and <code>image</code> is not a GLB.`,
+ );
+ return;
+ }
+
+ const resolvedGlb = isDecentralizedURI(glbUri) ? resolveURI(glbUri) : glbUri;
+ await this.view(resolvedGlb, '', new Map());
+ } catch (err) {
+ console.warn('[3d-agent] on-chain load failed:', err);
+ this._showOnChainError(err.message || String(err));
+ }
+ }
+
+ _showOnChainError(msg) {
+ this._updateOnChainCard(this.options.onchain, null, msg);
+ this.dropEl?.classList.add('hidden');
+ }
+
+ /**
+ * Render a small info card overlaying the viewer so users know whose agent
+ * they're looking at. Hidden in kiosk mode.
+ */
+ _updateOnChainCard(onchain, metadata, errorMsg = '') {
+ if (this.options.kiosk) return;
+ let card = this.el.querySelector('.onchain-card');
+ if (!card) {
+ card = document.createElement('div');
+ card.className = 'onchain-card';
+ this.el.appendChild(card);
+ }
+ const chainLabel = `chainId ${onchain.chainId}`;
+ if (errorMsg) {
+ card.innerHTML = `<div class="onchain-card__err">⚠ ${escHtml(errorMsg)}</div>
+ <div class="onchain-card__sub">Agent #${escHtml(onchain.agentId)} · ${escHtml(chainLabel)}</div>`;
+ return;
+ }
+ const name = metadata?.name ? String(metadata.name) : `Agent #${onchain.agentId}`;
+ const desc = metadata?.description ? String(metadata.description) : '';
+ card.innerHTML = `
+ <div class="onchain-card__name">${escHtml(name)}</div>
+ <div class="onchain-card__sub">#${escHtml(onchain.agentId)} · ${escHtml(chainLabel)}</div>
+ ${desc ? `<div class="onchain-card__desc">${escHtml(desc)}</div>` : ''}
+ `;
+ }
+
+ async _showExplorePage() {
+ 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 = 'explore-page';
+ main.appendChild(page);
+
+ const { renderExplorePage } = await import('./erc8004/explore.js');
+ renderExplorePage(page);
+ } catch (err) {
+ console.error('[3d-agent] explore 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
// replace them with the ERC-8004 wizard, pre-filled from the user's
// current avatar so Step 5 flows from Steps 1–4.
+ //
+ // Deep-link support: `/deploy?avatar=<id>` pre-fills from a previously
+ // saved avatar (dashboard "Deploy on-chain" per row). That prefill
+ // overrides the viewer's current model.
try {
const main = this.el.querySelector('main.wrap') || this.el;
this.dropEl?.classList.add('hidden');
@@ -1049,22 +1226,51 @@ class App {
page.className = 'deploy-page';
main.appendChild(page);
+ const initial = await this._resolveDeployInitial();
+
const { RegisterUI } = await import('./erc8004/register-ui.js');
new RegisterUI(
page,
(result) => {
console.info('[ERC-8004] Agent registered:', result);
},
- {
- mode: 'page',
- initial: { glbUrl: this._currentModelUrl || '' },
- },
+ { mode: 'page', initial },
);
} catch (err) {
console.error('[3d-agent] deploy page load failed', err);
}
}
+ /**
+ * Resolve the initial state passed to RegisterUI. If `?avatar=<id>` is
+ * present, fetch that avatar from the backend and pre-fill name /
+ * description / image / GLB. Otherwise fall back to the current viewer
+ * model.
+ */
+ async _resolveDeployInitial() {
+ const qp = new URLSearchParams(location.search);
+ const avatarId = qp.get('avatar');
+ const fallback = { glbUrl: this._currentModelUrl || '' };
+ if (!avatarId) return fallback;
+ try {
+ const res = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
+ credentials: 'include',
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const { avatar } = await res.json();
+ if (!avatar) throw new Error('empty avatar payload');
+ return {
+ name: avatar.name || '',
+ description: avatar.description || '',
+ imageUrl: avatar.thumbnail_url || '',
+ glbUrl: avatar.url || avatar.model_url || '',
+ };
+ } catch (err) {
+ console.warn('[deploy] avatar prefill failed; falling back to viewer model', err);
+ return fallback;
+ }
+ }
+
showSpinner() {
this.spinnerEl.style.display = '';
}
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index bf11f0d34..e2a35ce14 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -122,29 +122,58 @@ export async function pinFile(blob, apiToken) {
* @param {string[]} [opts.services] Additional service objects
* @returns {object}
*/
+/**
+ * Build a spec-compliant ERC-8004 registration JSON.
+ *
+ * `imageUrl` is the 2D thumbnail (per NFT convention). `glbUrl` is optional —
+ * when present, the GLB is surfaced as a dedicated `avatar` service entry and
+ * a companion `3D` renderer service pointing at 3dagent so other apps can load
+ * the body in-browser without coupling to our domain.
+ *
+ * @param {object} opts
+ * @param {string} opts.name
+ * @param {string} opts.description
+ * @param {string} [opts.imageUrl] 2D thumbnail URL (PNG/JPG) — used for `image`
+ * @param {string} [opts.glbUrl] Optional GLB URL — emitted as an `avatar` service
+ * @param {number} opts.agentId
+ * @param {number} opts.chainId
+ * @param {string} opts.registryAddr
+ * @param {Array} [opts.services] Extra service entries
+ * @param {boolean}[opts.x402Support]
+ */
export function buildRegistrationJSON({
name,
description,
imageUrl,
+ glbUrl,
agentId,
chainId,
registryAddr,
services = [],
+ x402Support = false,
}) {
+ const baseServices = [];
+ if (glbUrl) {
+ baseServices.push({
+ name: 'avatar',
+ endpoint: glbUrl,
+ version: 'gltf-2.0',
+ });
+ baseServices.push({
+ name: '3D',
+ endpoint: `https://3dagent.vercel.app/#model=${encodeURIComponent(glbUrl)}`,
+ version: '1.0',
+ });
+ }
+
return {
type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
name,
description,
- image: imageUrl,
+ image: imageUrl || '',
active: true,
- services: [
- {
- name: '3D',
- endpoint: `https://3dagent.vercel.app/#model=${encodeURIComponent(imageUrl)}`,
- version: '1.0',
- },
- ...services,
- ],
+ x402Support,
+ services: [...baseServices, ...services],
registrations: [
{
agentId,
@@ -190,7 +219,7 @@ export function getIdentityRegistry(chainId, signer) {
* @param {function} [opts.onStatus] Callback for progress updates
* @returns {Promise<{agentId: number, registrationUrl: string, txHash: string}>}
*/
-export async function registerAgent({ glbFile, name, description, apiToken, services = [], onStatus }) {
+export async function registerAgent({ glbFile, name, description, imageUrl, apiToken, services = [], x402Support = false, onStatus }) {
const log = onStatus || (() => {});
// 1. Connect wallet
@@ -223,15 +252,19 @@ export async function registerAgent({ glbFile, name, description, apiToken, serv
const agentId = Number(registeredEvent.args.agentId);
log(`Agent minted! agentId = ${agentId}`);
- // 5. Build final registration JSON with the 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.
const registrationJSON = buildRegistrationJSON({
name,
description,
- imageUrl: glbUrl,
+ imageUrl: imageUrl || '',
+ glbUrl,
agentId,
chainId,
registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
services,
+ x402Support,
});
// 6. Upload registration JSON
diff --git a/src/erc8004/explore.js b/src/erc8004/explore.js
new file mode 100644
index 000000000..bdeb09a50
--- /dev/null
+++ b/src/erc8004/explore.js
@@ -0,0 +1,138 @@
+/**
+ * Public explore page — a cross-chain gallery of ERC-8004 agents that resolve
+ * to a 3D avatar. Entry point is `/explore`.
+ *
+ * Flow:
+ * 1. For each supported chain, scan recent `Registered` events.
+ * 2. Fetch the registration JSON behind each agent's URI.
+ * 3. Keep only entries where `findAvatar3D(metadata)` returns a URL.
+ * 4. Render a grid of cards linking to `/a/<chainId>/<agentId>`.
+ *
+ * No wallet required — uses public RPCs from CHAIN_META. Scans are bounded
+ * (`blocks`, `limitPerChain`) so a single open of the page doesn't blow up
+ * public endpoints. Metadata fetches run concurrently with a cap.
+ */
+
+import { supportedChainIds, CHAIN_META } from './chain-meta.js';
+import { listRegisteredEvents, fetchAgentMetadata, findAvatar3D } from './queries.js';
+
+const SCAN_BLOCKS = 250000;
+const LIMIT_PER_CHAIN = 25;
+const METADATA_CONCURRENCY = 6;
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ }[c]));
+}
+
+/**
+ * Render the explore page into `container`. Takes over that element.
+ * @param {HTMLElement} container
+ */
+export async function renderExplorePage(container) {
+ container.innerHTML = `
+ <div class="explore-head">
+ <h1>Explore on-chain 3D agents</h1>
+ <p class="explore-sub">Every card below is an ERC-8004 agent whose registration metadata points at a 3D avatar. Click to load it in the viewer.</p>
+ <div class="explore-meta" id="explore-meta">Scanning chains…</div>
+ </div>
+ <div class="explore-grid" id="explore-grid"></div>
+ <div class="explore-foot" id="explore-foot"></div>
+ `;
+
+ const grid = container.querySelector('#explore-grid');
+ const meta = container.querySelector('#explore-meta');
+ const foot = container.querySelector('#explore-foot');
+
+ const chains = supportedChainIds();
+ let scanned = 0;
+ let found = 0;
+
+ const updateStatus = () => {
+ meta.textContent = `Scanned ${scanned}/${chains.length} chains · ${found} live 3D agents`;
+ };
+ updateStatus();
+
+ // Run chains in parallel — event queries on different RPCs are independent.
+ await Promise.all(chains.map(async (chainId) => {
+ const chainMeta = CHAIN_META[chainId];
+ try {
+ const events = await listRegisteredEvents({
+ chainId,
+ blocks: SCAN_BLOCKS,
+ limit: LIMIT_PER_CHAIN,
+ });
+ await runWithConcurrency(events, METADATA_CONCURRENCY, async (ev) => {
+ const meta = await fetchAgentMetadata(ev.agentURI);
+ if (!meta.ok) return;
+ const glb = findAvatar3D(meta.data);
+ if (!glb) return;
+ found += 1;
+ renderCard(grid, {
+ chainId,
+ chainName: chainMeta?.shortName || chainMeta?.name || String(chainId),
+ agentId: ev.agentId.toString(),
+ owner: ev.owner,
+ metadata: meta.data,
+ glb,
+ });
+ updateStatus();
+ });
+ } catch (err) {
+ console.warn(`[explore] chain ${chainId} scan failed:`, err.message);
+ } finally {
+ scanned += 1;
+ updateStatus();
+ }
+ }));
+
+ if (found === 0) {
+ foot.innerHTML = `
+ <p>No 3D agents indexed yet on the scanned window.</p>
+ <p><a href="/deploy" class="explore-cta">Deploy yours →</a></p>
+ `;
+ } else {
+ foot.innerHTML = `<p><a href="/deploy" class="explore-cta">Deploy your agent on-chain →</a></p>`;
+ }
+}
+
+function renderCard(grid, { chainId, chainName, agentId, owner, metadata, glb }) {
+ const card = document.createElement('a');
+ card.className = 'explore-card';
+ card.href = `/a/${chainId}/${agentId}`;
+
+ const name = metadata.name ? String(metadata.name) : `Agent #${agentId}`;
+ const desc = metadata.description ? String(metadata.description).slice(0, 140) : '';
+ const img = typeof metadata.image === 'string' ? metadata.image : '';
+ const thumbHtml = img
+ ? `<div class="explore-card__thumb" style="background-image:url('${esc(resolveUri(img))}')"></div>`
+ : `<div class="explore-card__thumb explore-card__thumb--none">3D</div>`;
+
+ card.innerHTML = `
+ ${thumbHtml}
+ <div class="explore-card__body">
+ <div class="explore-card__name">${esc(name)}</div>
+ <div class="explore-card__chain">${esc(chainName)} · #${esc(agentId)}</div>
+ ${desc ? `<div class="explore-card__desc">${esc(desc)}</div>` : ''}
+ </div>
+ `;
+ grid.appendChild(card);
+}
+
+function resolveUri(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;
+}
+
+async function runWithConcurrency(items, limit, fn) {
+ const iterator = items[Symbol.iterator]();
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
+ for (const item of iterator) {
+ try { await fn(item); } catch { /* swallow per-item */ }
+ }
+ });
+ await Promise.all(workers);
+}
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
index 30d5faabf..96eab6f19 100644
--- a/src/erc8004/queries.js
+++ b/src/erc8004/queries.js
@@ -175,6 +175,38 @@ export async function getAgentOnchain({ chainId, agentId, ethProvider }) {
return { agentId: BigInt(agentId), owner, uri };
}
+/**
+ * Extract a 3D avatar URL (GLB/GLTF) from an ERC-8004 registration payload.
+ *
+ * Canonical location is a service entry named `avatar` / `avatar-3d` with a
+ * `version` that starts with `gltf`. Falls back to the top-level `image` field
+ * when it ends in `.glb` or `.gltf` — older files we wrote before the service
+ * convention pollute `image` with the GLB URL.
+ *
+ * @param {any} metadata Parsed registration JSON
+ * @returns {string|null} GLB/GLTF URL (still in raw ipfs://, ar://, https:// form)
+ */
+export function findAvatar3D(metadata) {
+ if (!metadata || typeof metadata !== 'object') return null;
+
+ const services = Array.isArray(metadata.services) ? metadata.services : [];
+ for (const svc of services) {
+ if (!svc || typeof svc !== 'object') continue;
+ const endpoint = String(svc.endpoint || '').trim();
+ if (!endpoint) continue;
+ const name = String(svc.name || '').toLowerCase();
+ const version = String(svc.version || '').toLowerCase();
+ if (name === 'avatar' || name === 'avatar-3d') return endpoint;
+ if (version.startsWith('gltf')) return endpoint;
+ if (/\.(glb|gltf)(\?|#|$)/i.test(endpoint)) return endpoint;
+ }
+
+ const img = String(metadata.image || '').trim();
+ if (/\.(glb|gltf)(\?|#|$)/i.test(img)) return img;
+
+ return null;
+}
+
/**
* Resolve any IPFS/Arweave/data/https URI to a fetchable URL and parse JSON.
*
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 90e7f9f57..499d4fba4 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -22,6 +22,7 @@ import {
getIdentityRegistry,
buildRegistrationJSON,
} from './agent-registry.js';
+import { glbFileToThumbnail } from './thumbnail.js';
import { isPrivyConfigured } from './privy.js';
import { REGISTRY_DEPLOYMENTS } from './abi.js';
import { renderBatchTab } from './batch-tab.js';
@@ -176,6 +177,24 @@ const esc = (s) =>
);
const shortAddr = (a) => (a ? a.slice(0, 6) + '…' + a.slice(-4) : '');
+/**
+ * True if `url` is already a content-addressed or durable public URL that
+ * doesn't need to be fetched and re-pinned before referencing in a
+ * registration JSON. Avoids wasted uploads for avatars users created
+ * earlier (or default avatars shipped on the same domain).
+ */
+const _isStableUrl = (url) => {
+ if (!url || typeof url !== 'string') return false;
+ const u = url.trim();
+ return (
+ u.startsWith('ipfs://') ||
+ u.startsWith('ar://') ||
+ u.startsWith('https://') ||
+ u.startsWith('http://') ||
+ u.startsWith('/') // same-origin public asset (e.g. /avatars/cz.glb)
+ );
+};
+
// ───────────────────────────────────────────────────────────────────────────
// RegisterUI
// ───────────────────────────────────────────────────────────────────────────
@@ -205,6 +224,11 @@ export class RegisterUI {
// Wizard state — pre-populate from the user's current avatar/session so
// the on-chain JSON points to the GLB they just uploaded/created.
+ // `avatarSource` drives Step 3 behaviour:
+ // 'current' → use `glbUrl` pre-filled from the live SPA viewer
+ // 'saved' → pick one from the signed-in user's saved avatars
+ // 'upload' → user drops a new .glb in the wizard
+ // 'skip' → deploy as a metadata-only agent (no 3D body)
this.wizardStep = 1;
this.form = {
name: initial.name || '',
@@ -212,12 +236,16 @@ export class RegisterUI {
imageUrl: initial.imageUrl || '',
glbUrl: initial.glbUrl || '',
glbFile: null,
+ savedAvatar: null, // { id, name, url, thumbnailUrl }
+ avatarSource: initial.glbUrl ? 'current' : 'upload',
services: [], // [{ name, type, endpoint }]
apiToken: '', // optional Pinata JWT
};
// Cache of signed-in user's backend agent id (if any) — linked after deploy
this._backendAgentId = null;
+ this._signedIn = false;
+ this._savedAvatars = null; // loaded lazily when user switches source to 'saved'
this._build();
this._bind();
@@ -402,13 +430,59 @@ export class RegisterUI {
try {
const res = await fetch('/api/agents/me', { credentials: 'include' });
if (!res.ok) return;
+ this._signedIn = true;
const { agent } = await res.json();
if (agent && agent.id) this._backendAgentId = agent.id;
+ // If Step 3 is already rendered (signed-in detection raced with UI),
+ // re-render so the "Use a saved avatar" option appears.
+ if (this.wizardStep === 3 && this.activeTab === 'create') this._renderActiveTab();
} catch {
/* anon user or endpoint unavailable — fine */
}
}
+ /**
+ * Lazily fetch the signed-in user's saved avatars for the Step 3 picker.
+ * Returns [] on any failure (anonymous, endpoint down, etc) so the UI can
+ * silently fall back to the upload/skip options.
+ */
+ async _loadSavedAvatars() {
+ if (this._savedAvatars) return this._savedAvatars;
+ try {
+ const res = await fetch('/api/avatars?limit=50', { credentials: 'include' });
+ if (!res.ok) {
+ this._savedAvatars = [];
+ return this._savedAvatars;
+ }
+ const payload = await res.json();
+ const rows = payload.avatars || payload.data || [];
+ this._savedAvatars = rows.map((r) => ({
+ id: r.id,
+ name: r.name || 'Untitled',
+ modelUrl: r.model_url || null, // null for private — resolved on select
+ thumbnailUrl: r.thumbnail_url || null,
+ visibility: r.visibility,
+ }));
+ } catch {
+ this._savedAvatars = [];
+ }
+ return this._savedAvatars;
+ }
+
+ /**
+ * Resolve a saved avatar's download URL. Public/unlisted expose `model_url`
+ * directly; private avatars require a per-object signed-URL fetch.
+ */
+ async _resolveSavedAvatarUrl(avatar) {
+ if (avatar.modelUrl) return avatar.modelUrl;
+ const res = await fetch(`/api/avatars/${encodeURIComponent(avatar.id)}`, {
+ credentials: 'include',
+ });
+ if (!res.ok) throw new Error(`avatar fetch failed (${res.status})`);
+ const { avatar: detail } = await res.json();
+ return detail?.url || null;
+ }
+
async _linkAgentToAccount({ agentId, chainId, txHash }) {
if (!this._backendAgentId || !this.wallet) return;
try {
@@ -611,22 +685,31 @@ export class RegisterUI {
}
_renderStepConfig(body) {
- body.innerHTML = `
- <h3 class="erc8004-h3">Configuration</h3>
- <p class="erc8004-p">Optional: attach a 3D avatar (GLB) so anyone can render your agent in a browser. If provided, it becomes the agent's primary image.</p>
-
- <label class="erc8004-label">3D Avatar (GLB)
- <div class="erc8004-file-drop" data-role="drop">
- <input type="file" accept=".glb,.gltf" class="erc8004-file-input" />
- <span class="erc8004-file-text">${
- this.form.glbFile
- ? esc(this.form.glbFile.name)
- : this.form.glbUrl
- ? `Using current avatar: ${esc(this.form.glbUrl)} (click to replace)`
- : 'Drop .glb file or click to browse'
- }</span>
+ const hasCurrent = !!this.form.glbUrl;
+ const canPickSaved = this._signedIn;
+ const src = this.form.avatarSource;
+ const radio = (value, label, hint, disabled = false) => `
+ <label class="erc8004-avatar-source ${src === value ? 'erc8004-avatar-source--active' : ''} ${disabled ? 'erc8004-avatar-source--disabled' : ''}">
+ <input type="radio" name="avatarSource" value="${value}" ${src === value ? 'checked' : ''} ${disabled ? 'disabled' : ''} />
+ <div>
+ <div class="erc8004-avatar-source-title">${label}</div>
+ <div class="erc8004-avatar-source-hint">${hint}</div>
</div>
</label>
+ `;
+
+ body.innerHTML = `
+ <h3 class="erc8004-h3">3D Avatar</h3>
+ <p class="erc8004-p">Attach a GLB so any 3D-aware client can render your agent's body, or deploy as metadata-only. ERC-8004 doesn't require a 3D avatar — a 2D <code>image</code> works too.</p>
+
+ <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)}
+ ${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>
+
+ <div class="erc8004-avatar-panel" data-role="panel"></div>
<label class="erc8004-label">IPFS Pinning Token (optional)
<input class="erc8004-input" type="password" name="apiToken" placeholder="Pinata JWT — leave blank to use built-in R2 storage" value="${esc(this.form.apiToken)}" />
@@ -638,32 +721,101 @@ export class RegisterUI {
<button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Deploy →</button>
</div>
`;
- const drop = body.querySelector('[data-role="drop"]');
- const input = drop.querySelector('.erc8004-file-input');
- const label = drop.querySelector('.erc8004-file-text');
-
- const setFile = (f) => {
- if (!f) return;
- if (!/\.(glb|gltf)$/i.test(f.name)) {
- this._toast('Must be a .glb or .gltf file', true);
- return;
+
+ const panel = body.querySelector('[data-role="panel"]');
+
+ const renderPanel = () => {
+ const s = this.form.avatarSource;
+ if (s === 'current') {
+ panel.innerHTML = `
+ <div class="erc8004-avatar-summary">
+ <span class="erc8004-avatar-summary-badge">✓</span>
+ <div>
+ <div>Using your current avatar.</div>
+ <div class="erc8004-hint"><code>${esc(this.form.glbUrl)}</code></div>
+ </div>
+ </div>
+ `;
+ } else if (s === 'saved') {
+ panel.innerHTML = `<div class="erc8004-saved-grid" data-role="grid"><div class="erc8004-muted">Loading your avatars…</div></div>`;
+ this._loadSavedAvatars().then((list) => {
+ const grid = panel.querySelector('[data-role="grid"]');
+ if (!grid) return;
+ if (!list.length) {
+ grid.innerHTML = `<div class="erc8004-muted">No saved avatars yet. <a href="/create" class="erc8004-link">Create one</a> or choose another option above.</div>`;
+ return;
+ }
+ grid.innerHTML = list
+ .map(
+ (a) => `
+ <button type="button" class="erc8004-saved-card ${this.form.savedAvatar?.id === 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', () => {
+ const id = btn.dataset.id;
+ const picked = list.find((x) => x.id === id);
+ this.form.savedAvatar = picked || null;
+ renderPanel();
+ });
+ });
+ });
+ } else if (s === 'upload') {
+ panel.innerHTML = `
+ <div class="erc8004-file-drop" data-role="drop">
+ <input type="file" accept=".glb,.gltf" class="erc8004-file-input" />
+ <span class="erc8004-file-text">${this.form.glbFile ? esc(this.form.glbFile.name) : 'Drop .glb file or click to browse'}</span>
+ </div>
+ `;
+ const drop = panel.querySelector('[data-role="drop"]');
+ const input = drop.querySelector('.erc8004-file-input');
+ const label = drop.querySelector('.erc8004-file-text');
+ const setFile = (f) => {
+ if (!f) return;
+ if (!/\.(glb|gltf)$/i.test(f.name)) {
+ this._toast('Must be a .glb or .gltf file', true);
+ return;
+ }
+ this.form.glbFile = f;
+ label.textContent = f.name;
+ };
+ input.addEventListener('change', (e) => setFile(e.target.files[0]));
+ drop.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ drop.classList.add('erc8004-file-drop--active');
+ });
+ drop.addEventListener('dragleave', () =>
+ drop.classList.remove('erc8004-file-drop--active'),
+ );
+ drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ drop.classList.remove('erc8004-file-drop--active');
+ setFile(e.dataTransfer.files[0]);
+ });
+ } else if (s === 'skip') {
+ panel.innerHTML = `
+ <div class="erc8004-avatar-summary">
+ <span class="erc8004-avatar-summary-badge erc8004-avatar-summary-badge--muted">∅</span>
+ <div>
+ <div>Deploying as a metadata-only agent.</div>
+ <div class="erc8004-hint">Your registration JSON will include <code>image</code> (from Step 1) and services but no GLB. You can attach an avatar later from My Agents → Edit.</div>
+ </div>
+ </div>
+ `;
}
- this.form.glbFile = f;
- label.textContent = f.name;
};
- input.addEventListener('change', (e) => setFile(e.target.files[0]));
- drop.addEventListener('dragover', (e) => {
- e.preventDefault();
- drop.classList.add('erc8004-file-drop--active');
- });
- drop.addEventListener('dragleave', () =>
- drop.classList.remove('erc8004-file-drop--active'),
- );
- drop.addEventListener('drop', (e) => {
- e.preventDefault();
- drop.classList.remove('erc8004-file-drop--active');
- setFile(e.dataTransfer.files[0]);
+ renderPanel();
+
+ body.querySelectorAll('input[name="avatarSource"]').forEach((r) => {
+ r.addEventListener('change', (e) => {
+ this.form.avatarSource = e.target.value;
+ this._renderActiveTab(); // re-render to update active-class + panel
+ });
});
body.querySelector('[name="apiToken"]').addEventListener(
@@ -675,6 +827,16 @@ export class RegisterUI {
this._renderActiveTab();
});
body.querySelector('[data-role="next"]').addEventListener('click', () => {
+ // Validate the selected source before advancing.
+ const s = this.form.avatarSource;
+ if (s === 'saved' && !this.form.savedAvatar) {
+ this._toast('Pick one of your saved avatars, or choose another option.', true);
+ return;
+ }
+ if (s === 'upload' && !this.form.glbFile) {
+ this._toast('Drop a .glb file, or choose another option.', true);
+ return;
+ }
this.wizardStep = 4;
this._renderActiveTab();
});
@@ -692,7 +854,7 @@ export class RegisterUI {
<dt>Name</dt> <dd>${esc(this.form.name)}</dd>
<dt>Description</dt> <dd>${esc(this.form.description)}</dd>
${this.form.imageUrl ? `<dt>Image</dt> <dd>${esc(this.form.imageUrl)}</dd>` : ''}
- ${this.form.glbFile ? `<dt>GLB File</dt> <dd>${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)</dd>` : this.form.glbUrl ? `<dt>GLB URL</dt> <dd>${esc(this.form.glbUrl)}</dd>` : ''}
+ <dt>Avatar</dt> <dd>${this._avatarSummary()}</dd>
<dt>Services</dt> <dd>${this.form.services.length ? this.form.services.map((s) => `${esc(s.type)}: ${esc(s.endpoint || '—')}`).join('<br>') : '<span class="erc8004-muted">none</span>'}</dd>
<dt>Chain</dt> <dd>${esc(meta.name)} (chainId ${this.selectedChainId})</dd>
<dt>Registry</dt> <dd><code>${esc(REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry)}</code></dd>
@@ -774,23 +936,58 @@ export class RegisterUI {
this._wireExportOptions(body);
}
+ /**
+ * One-line summary of the user's Step 3 avatar choice, shown on the Deploy
+ * review screen.
+ */
+ _avatarSummary() {
+ const s = this.form.avatarSource;
+ if (s === 'current' && this.form.glbUrl) {
+ return `Current session avatar — <code>${esc(this.form.glbUrl)}</code>`;
+ }
+ if (s === 'saved' && this.form.savedAvatar) {
+ return `Saved: ${esc(this.form.savedAvatar.name)}`;
+ }
+ if (s === 'upload' && this.form.glbFile) {
+ return `Uploaded: ${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)`;
+ }
+ if (s === 'skip') return `<span class="erc8004-muted">None — metadata-only</span>`;
+ return `<span class="erc8004-muted">Not selected</span>`;
+ }
+
_wireExportOptions(body) {
const buildJSON = () => {
const identityAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;
- return {
- type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
+ // Preview JSON should match the shape `_doRegister` actually mints so
+ // users export what they're about to deploy.
+ const extra = (this.form.services || [])
+ .filter((s) => s.endpoint?.trim())
+ .map((s) => ({
+ name: s.name || s.type,
+ type: s.type,
+ endpoint: s.endpoint,
+ 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.
+ 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 === 'upload' && this.form.glbFile)
+ glbUrl = `<pending-upload:${this.form.glbFile.name}>`;
+
+ return buildRegistrationJSON({
name: this.form.name,
description: this.form.description,
- image: this.form.imageUrl || '',
- services: (this.form.services || []).filter((s) => s.endpoint?.trim()),
- active: true,
- registrations: [
- {
- agentId: 'PENDING',
- agentRegistry: `eip155:${this.selectedChainId}:${identityAddr}`,
- },
- ],
- };
+ imageUrl: this.form.imageUrl || glbUrl || '',
+ glbUrl: glbUrl || undefined,
+ agentId: 'PENDING',
+ chainId: this.selectedChainId,
+ registryAddr: identityAddr,
+ services: extra,
+ });
};
const download = (text, filename, mime = 'application/json') => {
const blob = new Blob([text], { type: mime });
@@ -894,57 +1091,96 @@ export class RegisterUI {
}
/**
- * Wraps agent-registry.registerAgent() with GLB-optional behavior: if the
- * user uploaded a GLB we use the existing flow; otherwise we go straight
- * to metadata-JSON pinning + on-chain mint.
+ * Unified deploy flow covering all avatar scenarios:
+ * - 'upload' → pin the dropped File
+ * - 'current' → reference existing stable URL (ipfs/https) without re-pinning,
+ * or fetch+pin if it's a blob:/data: URL
+ * - 'saved' → same bypass logic for stable saved-avatar URLs
+ * - 'skip' → no GLB, metadata-only agent
+ *
+ * If a GLB is present but no 2D `imageUrl` was supplied, auto-render a
+ * 512×512 PNG thumbnail from the GLB and pin it so ERC-721 marketplaces
+ * have a valid value for the `image` field.
*/
async _doRegister(say) {
- const { name, description, imageUrl, services, apiToken, glbUrl } = this.form;
- let { glbFile } = this.form;
-
- // If no file was uploaded but the SPA pre-populated a glbUrl (the avatar
- // the user just uploaded/created), fetch it as a File so the normal
- // GLB-pinning pipeline applies.
- if (!glbFile && glbUrl) {
+ const {
+ name,
+ description,
+ imageUrl: userImageUrl,
+ services,
+ apiToken,
+ avatarSource,
+ } = this.form;
+ const extraServices = services
+ .filter((s) => s.endpoint.trim())
+ .map((s) => ({
+ name: s.name || s.type,
+ type: s.type,
+ endpoint: s.endpoint,
+ version: '1.0',
+ }));
+
+ // ── 1. Resolve GLB source: File to pin, or stable URL to reference as-is.
+ let glbFile = null;
+ let glbUrl = null;
+
+ if (avatarSource === 'upload') {
+ glbFile = this.form.glbFile;
+ } else if (avatarSource === 'current' && this.form.glbUrl) {
+ if (_isStableUrl(this.form.glbUrl)) {
+ glbUrl = this.form.glbUrl;
+ say(`Reusing existing avatar URL (no re-upload): ${glbUrl}`);
+ } else {
+ glbFile = await this._fetchUrlAsFile(this.form.glbUrl, say, 'current avatar');
+ }
+ } else if (avatarSource === 'saved' && this.form.savedAvatar) {
try {
- say(`Fetching current avatar from ${glbUrl}…`);
- const res = await fetch(glbUrl);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const blob = await res.blob();
- const fileName = glbUrl.split('/').pop()?.split('?')[0] || 'avatar.glb';
- glbFile = new File([blob], fileName, { type: blob.type || 'model/gltf-binary' });
+ say(`Resolving saved avatar: ${this.form.savedAvatar.name}…`);
+ const url = await this._resolveSavedAvatarUrl(this.form.savedAvatar);
+ if (!url) throw new Error('no download URL');
+ if (_isStableUrl(url)) {
+ glbUrl = url;
+ say(`Reusing saved avatar URL (no re-upload): ${url}`);
+ } else {
+ glbFile = await this._fetchUrlAsFile(url, say, this.form.savedAvatar.name);
+ }
} catch (err) {
- say(`Could not fetch current avatar (${err.message}) — continuing without GLB.`);
+ say(
+ `Could not load saved avatar (${err.message}) — deploying metadata-only.`,
+ true,
+ );
}
}
- // GLB path — use the existing registerAgent flow (pins GLB, mints, updates URI).
- // We extend it by appending user-supplied services to the registration JSON.
- if (glbFile) {
- return await registerAgent({
- glbFile,
- name,
- description,
- apiToken: apiToken || undefined,
- onStatus: say,
- services: services
- .filter((s) => s.endpoint.trim())
- .map((s) => ({
- name: s.name || s.type,
- type: s.type,
- endpoint: s.endpoint,
- version: '1.0',
- })),
- });
+ // ── 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}`);
}
- // URI-only path: mirror agent-registry.registerAgent() but without the GLB upload.
+ // ── 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 = imageUrl || '';
+ const seedURI = glbUrl || imageUrl || '';
const tx = seedURI
? await registry['register(string)'](seedURI)
: await registry['register()']();
@@ -964,21 +1200,16 @@ export class RegisterUI {
const agentId = Number(registeredEvent.args.agentId);
say(`Agent minted! agentId = ${agentId}`);
+ // ── 5. Build + pin the full registration JSON, then setAgentURI.
const registrationJSON = buildRegistrationJSON({
name,
description,
- imageUrl: imageUrl || '',
+ imageUrl,
+ glbUrl: glbUrl || undefined,
agentId,
chainId,
registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
- services: services
- .filter((s) => s.endpoint.trim())
- .map((s) => ({
- name: s.name || s.type,
- type: s.type,
- endpoint: s.endpoint,
- version: '1.0',
- })),
+ services: extraServices,
});
say('Uploading registration metadata…');
@@ -995,6 +1226,24 @@ export class RegisterUI {
return { agentId, registrationUrl, txHash: tx.hash };
}
+ /**
+ * Fetch a URL and wrap the response as a File for the pinning pipeline.
+ * Returns null on failure (after logging via `say`).
+ */
+ async _fetchUrlAsFile(url, say, label = 'avatar') {
+ try {
+ say(`Fetching ${label}…`);
+ const res = await fetch(url, { credentials: 'include' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const blob = await res.blob();
+ const fileName = url.split('/').pop()?.split('?')[0] || 'avatar.glb';
+ return new File([blob], fileName, { type: blob.type || 'model/gltf-binary' });
+ } catch (err) {
+ say(`Could not fetch ${label} (${err.message}) — continuing without GLB.`, true);
+ return null;
+ }
+ }
+
// -----------------------------------------------------------------------
// Tab: My Agents
// -----------------------------------------------------------------------
@@ -1046,7 +1295,7 @@ export class RegisterUI {
card.className = 'erc8004-agent-card';
card.innerHTML = `<div class="erc8004-muted">Loading #${id}…</div>`;
list.appendChild(card);
- this._fillAgentCard(card, id, { withQR: true });
+ this._fillAgentCard(card, id, { withQR: true, withEdit: true });
}
if (res.partial) {
const note = document.createElement('div');
@@ -1076,6 +1325,11 @@ export class RegisterUI {
const image = meta.ok ? meta.data.image : '';
const hasX402 = meta.ok && (meta.data.x402Support || meta.data.x402);
card._meta = meta.ok ? meta.data : null;
+ card._owner = owner;
+
+ const isOwner =
+ this.wallet && owner && this.wallet.address.toLowerCase() === owner.toLowerCase();
+ const showLink = isOwner && this._signedIn && this._backendAgentId;
card.innerHTML = `
<div class="erc8004-agent-card-inner">
@@ -1087,12 +1341,15 @@ export class RegisterUI {
<strong>${esc(name)}</strong>
<span class="erc8004-tag">#${agentId}</span>
${hasX402 ? `<span class="erc8004-tag erc8004-tag--x402">x402 💳</span>` : ''}
+ ${isOwner ? `<span class="erc8004-tag erc8004-tag--owner">You own this</span>` : ''}
</div>
${description ? `<p class="erc8004-p erc8004-clip">${esc(description)}</p>` : ''}
<div class="erc8004-agent-card-actions">
${tokenUrl ? `<a class="erc8004-link" href="${esc(tokenUrl)}" target="_blank" rel="noopener">Details ↗</a>` : ''}
<a class="erc8004-link" href="#agent=${agentId}">Open in viewer</a>
${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>` : ''}
+ ${showLink ? `<button type="button" class="erc8004-link" data-role="link">Link to my account 🔗</button>` : ''}
</div>
</div>
</div>
@@ -1105,6 +1362,31 @@ export class RegisterUI {
this._openQRModal({ agentId, url: tokenUrl }),
);
}
+ if (opts.withEdit) {
+ const editBtn = card.querySelector('[data-role="edit"]');
+ if (editBtn)
+ editBtn.addEventListener('click', () =>
+ this._openEditModal({ agentId, currentMeta: card._meta, card }),
+ );
+ }
+ const linkBtn = card.querySelector('[data-role="link"]');
+ if (linkBtn)
+ linkBtn.addEventListener('click', async () => {
+ linkBtn.disabled = true;
+ linkBtn.textContent = 'Linking…';
+ try {
+ await this._linkAgentToAccount({
+ agentId: Number(agentId),
+ chainId: this.selectedChainId,
+ });
+ linkBtn.textContent = 'Linked ✓';
+ this._toast('Agent linked to your account');
+ } catch (err) {
+ linkBtn.disabled = false;
+ linkBtn.textContent = 'Link to my account 🔗';
+ this._toast(`Link failed: ${err.message}`, true);
+ }
+ });
} catch (err) {
card.innerHTML = `<div class="erc8004-log-error">Agent #${agentId}: ${esc(err.message)}</div>`;
}
@@ -1162,6 +1444,174 @@ export class RegisterUI {
});
}
+ /**
+ * Edit modal for an existing on-chain agent. Lets the owner update
+ * name / description / 2D image / 3D body, then pins a new registration
+ * JSON and calls setAgentURI(agentId, newURI). Preserves unrelated
+ * fields from the current metadata (services, registrations, trust, etc.).
+ */
+ _openEditModal({ agentId, currentMeta, card }) {
+ const meta = currentMeta || {};
+ const modal = document.createElement('div');
+ modal.className = 'erc8004-modal';
+ modal.innerHTML = `
+ <div class="erc8004-modal-card">
+ <div class="erc8004-modal-head">
+ <div class="erc8004-h4" style="margin:0">Edit Agent #${String(agentId)}</div>
+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>
+ </div>
+ <p class="erc8004-muted erc8004-small">Updates are written on-chain via <code>setAgentURI()</code>. Re-pins the registration JSON and points <code>agentURI</code> at the new CID.</p>
+
+ <label class="erc8004-label">Name
+ <input class="erc8004-input" name="name" value="${esc(meta.name || '')}" />
+ </label>
+ <label class="erc8004-label">Description
+ <textarea class="erc8004-input" name="description" rows="3">${esc(meta.description || '')}</textarea>
+ </label>
+ <label class="erc8004-label">Image URL (2D — for marketplaces)
+ <input class="erc8004-input" name="imageUrl" value="${esc(meta.image || '')}" placeholder="https://… or ipfs://…" />
+ </label>
+ <label class="erc8004-label">3D Avatar (GLB) — optional, replaces existing body
+ <input type="file" accept=".glb,.gltf" class="erc8004-file-input" name="glb" />
+ </label>
+ <label class="erc8004-label">Pinata JWT (optional)
+ <input class="erc8004-input" name="apiToken" placeholder="leave blank for R2 backend" />
+ </label>
+
+ <div class="erc8004-log" data-role="log"></div>
+
+ <div class="erc8004-row" style="justify-content:flex-end">
+ <button class="erc8004-btn" data-role="cancel">Cancel</button>
+ <button class="erc8004-btn erc8004-btn--primary" data-role="save">Save on-chain</button>
+ </div>
+ </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.querySelector('[data-role="cancel"]').addEventListener('click', close);
+
+ modal.querySelector('[data-role="save"]').addEventListener('click', async () => {
+ const saveBtn = modal.querySelector('[data-role="save"]');
+ const log = modal.querySelector('[data-role="log"]');
+ const say = (msg, err = false) => {
+ const line = document.createElement('div');
+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');
+ line.textContent = msg;
+ log.appendChild(line);
+ log.scrollTop = log.scrollHeight;
+ };
+ saveBtn.disabled = true;
+ try {
+ const name = modal.querySelector('[name="name"]').value.trim();
+ const description = modal.querySelector('[name="description"]').value.trim();
+ const imageUrlInput = modal.querySelector('[name="imageUrl"]').value.trim();
+ const apiToken = modal.querySelector('[name="apiToken"]').value.trim() || undefined;
+ const fileInput = modal.querySelector('[name="glb"]');
+ const glbFile = fileInput.files?.[0] || null;
+
+ await this._doUpdateAgent({
+ agentId,
+ name,
+ description,
+ imageUrl: imageUrlInput,
+ glbFile,
+ apiToken,
+ currentMeta: meta,
+ say,
+ });
+
+ this._toast('Agent updated on-chain');
+ close();
+ if (card) this._fillAgentCard(card, agentId, { withQR: true, withEdit: true });
+ } catch (err) {
+ say('Update failed: ' + (err.shortMessage || err.message || String(err)), true);
+ saveBtn.disabled = false;
+ }
+ });
+ }
+
+ /**
+ * Build + pin a new registration JSON and call setAgentURI on-chain.
+ * Preserves `services`, `registrations`, `supportedTrust`, `x402Support`
+ * from the existing metadata; only touches the fields the user edited.
+ */
+ async _doUpdateAgent({
+ agentId,
+ name,
+ description,
+ imageUrl,
+ glbFile,
+ 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;
+ let newImageUrl = imageUrl;
+
+ // If user uploaded a new GLB, pin it and re-render thumbnail when image is empty.
+ if (glbFile) {
+ say('Uploading new 3D model…');
+ glbUrl = await pinFile(glbFile, apiToken);
+ say(`Model uploaded: ${glbUrl}`);
+ if (!newImageUrl) {
+ try {
+ say('Rendering 2D thumbnail from new GLB…');
+ const thumb = await glbFileToThumbnail(glbFile);
+ newImageUrl = await pinFile(thumb, apiToken);
+ say(`Thumbnail uploaded: ${newImageUrl}`);
+ } catch (err) {
+ say(`Thumbnail render failed (${err.message}) — keeping existing image.`);
+ newImageUrl = currentMeta?.image || '';
+ }
+ }
+ }
+
+ // Preserve non-avatar services (user-added A2A/MCP/etc.) and other fields.
+ const preservedServices = (currentMeta?.services || []).filter(
+ (s) => s?.name !== 'avatar' && s?.name !== '3D',
+ );
+
+ say('Connecting wallet…');
+ const { signer, chainId } = await connectWallet();
+ const registry = getIdentityRegistry(chainId, signer);
+ const registryAddr = REGISTRY_DEPLOYMENTS[chainId].identityRegistry;
+
+ const registrationJSON = buildRegistrationJSON({
+ name,
+ description,
+ imageUrl: newImageUrl || '',
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services: preservedServices,
+ x402Support: !!(currentMeta?.x402Support || currentMeta?.x402),
+ });
+
+ say('Uploading new registration metadata…');
+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {
+ type: 'application/json',
+ });
+ const newUri = await pinFile(jsonBlob, apiToken);
+ say(`New metadata: ${newUri}`);
+
+ say('Calling setAgentURI on-chain…');
+ const tx = await registry.setAgentURI(agentId, newUri);
+ say(`Transaction submitted: ${tx.hash}`);
+ await tx.wait();
+ say('Agent URI updated ✓');
+ }
+
// -----------------------------------------------------------------------
// Tab: Search
// -----------------------------------------------------------------------
diff --git a/src/erc8004/resolve-avatar.js b/src/erc8004/resolve-avatar.js
new file mode 100644
index 000000000..924ecd537
--- /dev/null
+++ b/src/erc8004/resolve-avatar.js
@@ -0,0 +1,460 @@
+/**
+ * Avatar resolver — the "paste anything, see their 3D avatar" primitive.
+ *
+ * Given free-form input (address, ENS name, tx hash, agent ID, agent:// URI)
+ * this module fans out across configured chains, discovers matching ERC-8004
+ * agent registrations, hydrates their metadata, and returns a flat list of
+ * results ready to render as a gallery.
+ *
+ * Used by:
+ * - src/erc8004/explore.js (the public /explore gallery page)
+ * - src/erc8004/register-ui.js ("Find Avatar" tab for creators)
+ *
+ * Chain reads happen through public RPCs (CHAIN_META) so no wallet required.
+ */
+
+import { JsonRpcProvider, Contract, Interface, isAddress, getAddress } from 'ethers';
+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';
+import { CHAIN_META, supportedChainIds } from './chain-meta.js';
+import {
+ getReadProvider,
+ getReadRegistry,
+ getAgentOnchain,
+ fetchAgentMetadata,
+ findAvatar3D,
+ listAgentsByOwner,
+} from './queries.js';
+
+// ───────────────────────────────────────────────────────────────────────────
+// Input detection
+// ───────────────────────────────────────────────────────────────────────────
+
+export const INPUT_TYPES = {
+ AGENT_ID: 'agentId',
+ ADDRESS: 'address',
+ TX_HASH: 'txHash',
+ ENS: 'ens',
+ AGENT_URI: 'agentURI',
+ UNKNOWN: 'unknown',
+};
+
+/** @param {string} input */
+export function detectInputType(input) {
+ const v = String(input ?? '').trim();
+ if (!v) return INPUT_TYPES.UNKNOWN;
+ if (/^agent:\/\/[^/]+\/\d+$/i.test(v)) return INPUT_TYPES.AGENT_URI;
+ if (/^0x[a-fA-F0-9]{64}$/.test(v)) return INPUT_TYPES.TX_HASH;
+ if (/^0x[a-fA-F0-9]{40}$/.test(v)) return INPUT_TYPES.ADDRESS;
+ if (/^\d{1,10}$/.test(v)) return INPUT_TYPES.AGENT_ID;
+ // ENS-style: any string with at least one dot and an alpha TLD-ish tail
+ if (/^[a-z0-9][a-z0-9-]*(\.[a-z0-9-]+)+$/i.test(v)) return INPUT_TYPES.ENS;
+ return INPUT_TYPES.UNKNOWN;
+}
+
+/** Default fan-out set — active ERC-8004 chains. Small enough that 9 parallel reads is cheap. */
+export const DEFAULT_FAN_OUT_CHAINS = [
+ 8453, // Base
+ 1, // Ethereum
+ 10, // Optimism
+ 42161, // Arbitrum One
+ 137, // Polygon
+ 56, // BNB Chain
+ 84532, // Base Sepolia
+ 11155111, // Ethereum Sepolia
+ 97, // BSC Testnet
+];
+
+// ───────────────────────────────────────────────────────────────────────────
+// Shared result shape
+// ───────────────────────────────────────────────────────────────────────────
+
+/**
+ * A single resolved on-chain agent.
+ *
+ * @typedef {object} AvatarResult
+ * @property {number} chainId
+ * @property {string} chainName
+ * @property {boolean} testnet
+ * @property {string} agentId Stringified (bigint-safe)
+ * @property {string} owner Checksummed
+ * @property {string} [uri] Raw tokenURI (ipfs://, ar://, data:, https://)
+ * @property {any} [meta] Parsed registration JSON (when available)
+ * @property {string|null} avatarUri Raw GLB/GLTF URI (ipfs://, ar://, https://) or null
+ * @property {string} [image] Poster image URL
+ * @property {string} [name]
+ * @property {string} [description]
+ * @property {boolean} [x402]
+ * @property {string[]} [serviceTypes] Uppercased service.type/name list for filtering
+ * @property {string} viewerUrl Canonical `/a/<chainId>/<agentId>` link
+ * @property {string} tokenExplorerUrl
+ * @property {string} ownerExplorerUrl
+ * @property {string} registry
+ * @property {string} [error] Per-agent non-fatal error message
+ */
+
+// ───────────────────────────────────────────────────────────────────────────
+// Single-agent resolution helpers
+// ───────────────────────────────────────────────────────────────────────────
+
+function _extractX402(meta) {
+ if (!meta || typeof meta !== 'object') return false;
+ if (meta.x402Support || meta.x402) return true;
+ const services = Array.isArray(meta.services) ? meta.services : [];
+ return services.some((s) => {
+ const t = String(s?.type || s?.name || '').toUpperCase();
+ return t === 'X402' || t.includes('X402');
+ });
+}
+
+function _extractServiceTypes(meta) {
+ if (!meta || typeof meta !== 'object') return [];
+ const services = Array.isArray(meta.services) ? meta.services : [];
+ return services.map((s) => String(s?.type || s?.name || '').toUpperCase()).filter(Boolean);
+}
+
+function _chainName(chainId) {
+ return CHAIN_META[chainId]?.name || `Chain ${chainId}`;
+}
+
+/**
+ * Hydrate a single (chainId, agentId) pair into a full AvatarResult.
+ * Uses the read-only public RPC — no wallet required.
+ *
+ * @param {object} opts
+ * @param {number} opts.chainId
+ * @param {bigint|string|number} opts.agentId
+ * @param {any} [opts.ethProvider]
+ * @returns {Promise<AvatarResult>}
+ */
+export async function hydrateAgent({ chainId, agentId, ethProvider }) {
+ const meta = CHAIN_META[chainId];
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ const registry = deployment?.identityRegistry || '';
+
+ const base = {
+ chainId,
+ chainName: meta?.name || `Chain ${chainId}`,
+ testnet: !!meta?.testnet,
+ agentId: String(agentId),
+ owner: '',
+ uri: '',
+ meta: null,
+ avatarUri: null,
+ image: '',
+ name: '',
+ description: '',
+ x402: false,
+ serviceTypes: [],
+ viewerUrl: `/a/${chainId}/${String(agentId)}`,
+ tokenExplorerUrl: registry && meta ? `${meta.explorer}/token/${registry}?a=${String(agentId)}` : '',
+ ownerExplorerUrl: '',
+ registry,
+ };
+
+ try {
+ const { owner, uri } = await getAgentOnchain({ chainId, agentId, ethProvider });
+ base.owner = owner ? getAddress(owner) : '';
+ base.uri = uri || '';
+ base.ownerExplorerUrl = base.owner && meta ? `${meta.explorer}/address/${base.owner}` : '';
+
+ if (!uri) {
+ base.error = 'no agentURI';
+ return base;
+ }
+
+ const fetched = await fetchAgentMetadata(uri);
+ if (!fetched.ok) {
+ base.error = fetched.error || 'metadata fetch failed';
+ return base;
+ }
+ const data = fetched.data || {};
+ base.meta = data;
+ base.name = String(data.name || '').trim();
+ base.description = String(data.description || '').trim();
+ base.image = String(data.image || '').trim();
+ base.avatarUri = findAvatar3D(data);
+ base.x402 = _extractX402(data);
+ base.serviceTypes = _extractServiceTypes(data);
+ } catch (err) {
+ base.error = err?.message || String(err);
+ }
+ return base;
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Resolvers — each takes shape-preserving opts and returns AvatarResult[]
+// ───────────────────────────────────────────────────────────────────────────
+
+/**
+ * @param {{ chainId: number, agentId: string|number|bigint, ethProvider?: any }} opts
+ * @returns {Promise<AvatarResult[]>}
+ */
+export async function resolveByAgentId(opts) {
+ const result = await hydrateAgent(opts);
+ return [result];
+}
+
+/**
+ * Fan-out: given (chainIds, agentId) try the same id on every chain and return
+ * every hit. Useful when the user pastes "6443" and we don't know the chain.
+ *
+ * @param {object} opts
+ * @param {string|number|bigint} opts.agentId
+ * @param {number[]} [opts.chainIds]
+ * @param {any} [opts.ethProvider]
+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]
+ * @returns {Promise<AvatarResult[]>}
+ */
+export async function resolveByAgentIdFanOut({
+ agentId,
+ chainIds = DEFAULT_FAN_OUT_CHAINS,
+ ethProvider,
+ onProgress = () => {},
+}) {
+ const jobs = chainIds.map(async (chainId) => {
+ onProgress(chainId, 'start');
+ try {
+ const r = await hydrateAgent({ chainId, agentId, ethProvider });
+ // Filter out "doesn't exist" (no owner AND no uri). Those are empty slots, not agents.
+ if (!r.owner && !r.uri) {
+ onProgress(chainId, 'done', 0);
+ return null;
+ }
+ onProgress(chainId, 'done', 1);
+ return r;
+ } catch (err) {
+ onProgress(chainId, 'error', err);
+ return null;
+ }
+ });
+ const out = (await Promise.all(jobs)).filter(Boolean);
+ return out;
+}
+
+/**
+ * Resolve every agent owned by `address` across `chainIds`.
+ *
+ * @param {object} opts
+ * @param {string} opts.address
+ * @param {number[]} [opts.chainIds]
+ * @param {any} [opts.ethProvider]
+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]
+ * @returns {Promise<AvatarResult[]>}
+ */
+export async function resolveByAddress({
+ address,
+ chainIds = DEFAULT_FAN_OUT_CHAINS,
+ ethProvider,
+ onProgress = () => {},
+}) {
+ if (!isAddress(address)) throw new Error('Not a valid EVM address');
+ const checksummed = getAddress(address);
+
+ const chainJobs = chainIds.map(async (chainId) => {
+ onProgress(chainId, 'start');
+ try {
+ const { ids } = await listAgentsByOwner({
+ chainId,
+ owner: checksummed,
+ ethProvider,
+ });
+ if (!ids || ids.length === 0) {
+ onProgress(chainId, 'done', 0);
+ return [];
+ }
+ // Hydrate each in parallel, but cap concurrency on chains with big balances.
+ const hydrated = await Promise.all(
+ ids.map((id) => hydrateAgent({ chainId, agentId: id, ethProvider })),
+ );
+ onProgress(chainId, 'done', hydrated.length);
+ return hydrated;
+ } catch (err) {
+ onProgress(chainId, 'error', err);
+ return [];
+ }
+ });
+
+ const nested = await Promise.all(chainJobs);
+ return nested.flat();
+}
+
+/**
+ * Resolve every `Registered` event in a given tx hash — yields one result per
+ * agent minted in that transaction.
+ *
+ * @param {object} opts
+ * @param {string} opts.txHash
+ * @param {number} [opts.chainId] If omitted, we fan-out across chainIds.
+ * @param {number[]} [opts.chainIds]
+ * @param {any} [opts.ethProvider]
+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]
+ * @returns {Promise<AvatarResult[]>}
+ */
+export async function resolveByTxHash({
+ txHash,
+ chainId,
+ chainIds = DEFAULT_FAN_OUT_CHAINS,
+ ethProvider,
+ onProgress = () => {},
+}) {
+ if (!/^0x[a-fA-F0-9]{64}$/.test(txHash)) throw new Error('Not a valid tx hash');
+ const candidates = chainId ? [chainId] : chainIds;
+
+ const iface = new Interface(IDENTITY_REGISTRY_ABI);
+ const registeredTopic = iface.getEvent('Registered').topicHash;
+
+ const chainJobs = candidates.map(async (cid) => {
+ onProgress(cid, 'start');
+ try {
+ const deployment = REGISTRY_DEPLOYMENTS[cid];
+ if (!deployment?.identityRegistry) {
+ onProgress(cid, 'done', 0);
+ return [];
+ }
+ const provider = getReadProvider(cid, ethProvider);
+ const receipt = await provider.getTransactionReceipt(txHash);
+ if (!receipt) {
+ onProgress(cid, 'done', 0);
+ return [];
+ }
+ const registryAddr = deployment.identityRegistry.toLowerCase();
+ const hits = [];
+ for (const log of receipt.logs) {
+ if (!log.address || log.address.toLowerCase() !== registryAddr) continue;
+ if (!log.topics || log.topics[0] !== registeredTopic) continue;
+ try {
+ const parsed = iface.parseLog(log);
+ const agentId = parsed.args.agentId;
+ hits.push(await hydrateAgent({ chainId: cid, agentId, ethProvider }));
+ } catch {
+ // malformed log — skip
+ }
+ }
+ onProgress(cid, 'done', hits.length);
+ return hits;
+ } catch (err) {
+ onProgress(cid, 'error', err);
+ return [];
+ }
+ });
+
+ const nested = await Promise.all(chainJobs);
+ return nested.flat();
+}
+
+/**
+ * Resolve an agent://<chain>/<id> URI.
+ *
+ * @param {string} uri
+ * @param {any} [ethProvider]
+ * @returns {Promise<AvatarResult[]>}
+ */
+export async function resolveByAgentURI(uri, ethProvider) {
+ const m = String(uri).match(/^agent:\/\/([^/]+)\/(\d+)$/i);
+ if (!m) throw new Error('Malformed agent URI');
+ const [, chainToken, idStr] = m;
+ const CHAIN_ALIASES = {
+ base: 8453,
+ 'base-mainnet': 8453,
+ 'base-sepolia': 84532,
+ ethereum: 1,
+ mainnet: 1,
+ optimism: 10,
+ arbitrum: 42161,
+ polygon: 137,
+ bsc: 56,
+ };
+ const chainId = CHAIN_ALIASES[chainToken.toLowerCase()] || Number(chainToken);
+ if (!chainId || !REGISTRY_DEPLOYMENTS[chainId]) {
+ throw new Error(`Unknown chain in URI: ${chainToken}`);
+ }
+ const r = await hydrateAgent({ chainId, agentId: idStr, ethProvider });
+ return [r];
+}
+
+/**
+ * Resolve an ENS name to an address using Ethereum mainnet public RPC, then
+ * delegate to resolveByAddress. Names that don't resolve throw.
+ *
+ * @param {string} name
+ */
+export async function resolveENSAddress(name) {
+ const provider = new JsonRpcProvider(CHAIN_META[1].rpcUrl, 1);
+ const addr = await provider.resolveName(name);
+ if (!addr) throw new Error(`ENS name does not resolve: ${name}`);
+ return getAddress(addr);
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Auto-resolve — single entry point
+// ───────────────────────────────────────────────────────────────────────────
+
+/**
+ * @param {object} opts
+ * @param {string} opts.input
+ * @param {number[]} [opts.chainIds] Fan-out set
+ * @param {any} [opts.ethProvider]
+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]
+ * @returns {Promise<{ type: string, resolvedAddress?: string, results: AvatarResult[] }>}
+ */
+export async function autoResolve({
+ input,
+ chainIds = DEFAULT_FAN_OUT_CHAINS,
+ ethProvider,
+ onProgress = () => {},
+}) {
+ const type = detectInputType(input);
+ const trimmed = String(input).trim();
+
+ switch (type) {
+ case INPUT_TYPES.AGENT_URI: {
+ const results = await resolveByAgentURI(trimmed, ethProvider);
+ return { type, results };
+ }
+ case INPUT_TYPES.TX_HASH: {
+ const results = await resolveByTxHash({ txHash: trimmed, chainIds, ethProvider, onProgress });
+ return { type, results };
+ }
+ case INPUT_TYPES.ADDRESS: {
+ const results = await resolveByAddress({
+ address: trimmed,
+ chainIds,
+ ethProvider,
+ onProgress,
+ });
+ return { type, resolvedAddress: getAddress(trimmed), results };
+ }
+ case INPUT_TYPES.AGENT_ID: {
+ const results = await resolveByAgentIdFanOut({
+ agentId: trimmed,
+ chainIds,
+ ethProvider,
+ onProgress,
+ });
+ return { type, results };
+ }
+ case INPUT_TYPES.ENS: {
+ const address = await resolveENSAddress(trimmed);
+ const results = await resolveByAddress({ address, chainIds, ethProvider, onProgress });
+ return { type, resolvedAddress: address, results };
+ }
+ default:
+ throw new Error(`Unrecognized input: "${trimmed}". Paste an address, ENS name, tx hash, or agent ID.`);
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Convenience: all chains with a deployed registry (for UI toggle row)
+// ───────────────────────────────────────────────────────────────────────────
+
+export function allSupportedChains() {
+ return supportedChainIds();
+}
+
+/** Split supported chains into mainnets vs testnets for UI grouping. */
+export function splitChainsByNet() {
+ const all = allSupportedChains();
+ const mainnet = all.filter((id) => !CHAIN_META[id]?.testnet);
+ const testnet = all.filter((id) => CHAIN_META[id]?.testnet);
+ return { mainnet, testnet };
+}
diff --git a/src/erc8004/thumbnail.js b/src/erc8004/thumbnail.js
new file mode 100644
index 000000000..8ac61594a
--- /dev/null
+++ b/src/erc8004/thumbnail.js
@@ -0,0 +1,96 @@
+/**
+ * Client-side GLB → PNG thumbnail renderer.
+ *
+ * ERC-8004's `image` field is for 2D ERC-721 marketplace compatibility
+ * (OpenSea, wallets) which can't render GLB. When a user deploys a 3D agent
+ * without supplying a 2D poster, we render one from the GLB in an offscreen
+ * canvas and pin it alongside the body.
+ */
+
+import {
+ Scene,
+ PerspectiveCamera,
+ WebGLRenderer,
+ HemisphereLight,
+ DirectionalLight,
+ Color,
+ Box3,
+ Vector3,
+ SRGBColorSpace,
+ ACESFilmicToneMapping,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+/**
+ * Render a GLB/GLTF file to a PNG blob.
+ *
+ * @param {File|Blob} file GLB/GLTF file
+ * @param {object} [opts]
+ * @param {number} [opts.size=512]
+ * @param {string} [opts.background='#1a1a1a']
+ * @returns {Promise<Blob>} PNG blob (has `.name = 'thumbnail.png'`)
+ */
+export async function glbFileToThumbnail(file, { size = 512, background = '#1a1a1a' } = {}) {
+ const buffer = await file.arrayBuffer();
+ const loader = new GLTFLoader();
+ const gltf = await new Promise((resolve, reject) => {
+ loader.parse(buffer, '', resolve, reject);
+ });
+
+ const scene = new Scene();
+ scene.background = new Color(background);
+ scene.add(gltf.scene);
+
+ const box = new Box3().setFromObject(gltf.scene);
+ const center = box.getCenter(new Vector3());
+ const boxSize = box.getSize(new Vector3());
+ const maxDim = Math.max(boxSize.x, boxSize.y, boxSize.z) || 1;
+
+ const fov = 35;
+ const camera = new PerspectiveCamera(fov, 1, 0.01, 1000);
+ const dist = maxDim / (2 * Math.tan((Math.PI * fov) / 360));
+ // Mixamo-style framing: eye-level, slightly above center, pulled back.
+ camera.position.set(center.x, center.y + boxSize.y * 0.05, center.z + dist * 1.8);
+ camera.lookAt(center.x, center.y, center.z);
+
+ scene.add(new HemisphereLight(0xffffff, 0x444444, 2.0));
+ const dir = new DirectionalLight(0xffffff, 2.5);
+ dir.position.set(3, 10, 7);
+ scene.add(dir);
+
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false });
+ renderer.setPixelRatio(1);
+ renderer.setSize(size, size, false);
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.0;
+
+ try {
+ renderer.render(scene, camera);
+ const blob = await new Promise((resolve, reject) => {
+ canvas.toBlob(
+ (b) => (b ? resolve(b) : reject(new Error('toBlob returned null'))),
+ 'image/png',
+ );
+ });
+ // File-like name so pinFile can label the upload.
+ try {
+ Object.defineProperty(blob, 'name', { value: 'thumbnail.png' });
+ } catch {
+ /* Blob is usually writable; ignore if not */
+ }
+ return blob;
+ } finally {
+ renderer.dispose();
+ scene.traverse((obj) => {
+ if (obj.geometry) obj.geometry.dispose?.();
+ if (obj.material) {
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ for (const m of mats) m.dispose?.();
+ }
+ });
+ }
+}
diff --git a/style.css b/style.css
index fa1acb748..a9e06f9d7 100644
--- a/style.css
+++ b/style.css
@@ -1076,7 +1076,8 @@ footer .separator {
}
/* Page mode — /deploy renders inside app.html shell, not as a modal overlay. */
-.deploy-page {
+.deploy-page,
+.explore-page {
display: block;
width: 100%;
min-height: calc(100vh - var(--header-h));
@@ -1084,6 +1085,46 @@ footer .separator {
overflow-y: auto;
}
+/* /a/<chainId>/<agentId> — overlay card that tells the viewer whose agent they're looking at. */
+.onchain-card {
+ position: fixed;
+ left: var(--space-md);
+ bottom: var(--space-md);
+ z-index: 50;
+ max-width: 320px;
+ padding: var(--space-sm) var(--space-md);
+ background: rgba(8, 8, 20, 0.85);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ color: #fff;
+ font-size: var(--text-sm);
+ line-height: 1.35;
+ pointer-events: none;
+}
+.onchain-card__name {
+ font-weight: 600;
+}
+.onchain-card__sub {
+ margin-top: 2px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: var(--text-xs);
+}
+.onchain-card__desc {
+ margin-top: var(--space-xs);
+ color: rgba(255, 255, 255, 0.8);
+ font-size: var(--text-xs);
+ max-height: 4.2em;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+}
+.onchain-card__err {
+ color: #ff7a7a;
+}
+
.erc8004-register--page {
position: static;
inset: auto;
@@ -3991,6 +4032,172 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {
overflow-x: auto;
}
+/* Step 3 — avatar source picker */
+.erc8004-avatar-sources {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-xs);
+ margin: var(--space-sm) 0 var(--space-md);
+}
+
+@media (max-width: 640px) {
+ .erc8004-avatar-sources {
+ grid-template-columns: 1fr;
+ }
+}
+
+.erc8004-avatar-source {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-xs);
+ padding: var(--space-sm);
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s;
+}
+
+.erc8004-avatar-source:hover {
+ border-color: rgba(255, 255, 255, 0.18);
+}
+
+.erc8004-avatar-source--active {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+}
+
+.erc8004-avatar-source--disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.erc8004-avatar-source input[type='radio'] {
+ margin-top: 3px;
+ accent-color: var(--accent);
+}
+
+.erc8004-avatar-source-title {
+ font-size: var(--text-sm);
+ font-weight: 500;
+ color: #fff;
+}
+
+.erc8004-avatar-source-hint {
+ margin-top: 2px;
+ font-size: var(--text-xs);
+ color: rgba(255, 255, 255, 0.45);
+}
+
+.erc8004-avatar-source-hint code {
+ font-family: var(--font-mono);
+ font-size: 0.92em;
+ color: rgba(255, 255, 255, 0.6);
+ word-break: break-all;
+}
+
+.erc8004-avatar-panel {
+ margin-bottom: var(--space-md);
+}
+
+.erc8004-avatar-summary {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ background: rgba(139, 92, 246, 0.08);
+ border: 1px solid rgba(139, 92, 246, 0.25);
+ border-radius: var(--radius-md);
+ font-size: var(--text-sm);
+ color: #fff;
+}
+
+.erc8004-avatar-summary code {
+ font-family: var(--font-mono);
+ font-size: 0.9em;
+ word-break: break-all;
+}
+
+.erc8004-avatar-summary-badge {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ background: var(--accent);
+ color: #fff;
+ font-size: var(--text-xs);
+ font-weight: 700;
+ flex-shrink: 0;
+}
+
+.erc8004-avatar-summary-badge--muted {
+ background: rgba(255, 255, 255, 0.12);
+ color: rgba(255, 255, 255, 0.55);
+}
+
+.erc8004-saved-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
+ gap: var(--space-xs);
+ padding: var(--space-sm);
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-md);
+ min-height: 120px;
+}
+
+.erc8004-saved-card {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 4px;
+ padding: 4px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ text-align: left;
+ color: inherit;
+ font-family: inherit;
+ transition: border-color 0.15s, background 0.15s;
+}
+
+.erc8004-saved-card:hover {
+ border-color: rgba(255, 255, 255, 0.25);
+}
+
+.erc8004-saved-card--active {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+}
+
+.erc8004-saved-card img,
+.erc8004-saved-card-ph {
+ width: 100%;
+ aspect-ratio: 1 / 1;
+ object-fit: cover;
+ border-radius: var(--radius-sm);
+ background: rgba(255, 255, 255, 0.04);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: var(--text-xs);
+ color: rgba(255, 255, 255, 0.4);
+ font-weight: 600;
+ letter-spacing: 0.08em;
+}
+
+.erc8004-saved-card-name {
+ font-size: var(--text-xs);
+ color: rgba(255, 255, 255, 0.8);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ padding: 0 2px 2px;
+}
+
/* Accordion */
.erc8004-accordion {
margin-top: var(--space-md);
diff --git a/vercel.json b/vercel.json
index e5e363f50..f2305c7ee 100644
--- a/vercel.json
+++ b/vercel.json
@@ -71,6 +71,8 @@
{ "src": "/create", "dest": "/create.html" },
{ "src": "/create/", "dest": "/create.html" },
{ "src": "/home", "dest": "/home.html" },
+ { "src": "/explore", "dest": "/app.html" },
+ { "src": "/a/(.*)", "dest": "/app.html" },
{ "src": "/(.*)", "dest": "/public/$1" }
]
}
diff --git a/vite.config.js b/vite.config.js
index 7c6a5a375..915f77604 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -44,6 +44,7 @@ const appConfig = {
'/app': resolve(root, 'app.html'),
'/login': resolve(root, 'public/login.html'),
'/deploy': resolve(root, 'app.html'),
+ '/explore': resolve(root, 'app.html'),
'/features': resolve(root, 'features.html'),
'/create': resolve(root, 'create.html'),
'/dashboard': resolve(root, 'public/dashboard/index.html'),
@@ -58,6 +59,8 @@ const appConfig = {
if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path)) filePath = resolve(root, 'agent-edit.html');
else if (!filePath && /^\/agent\/[^/]+\/embed$/.test(path)) 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)) filePath = resolve(root, 'app.html');
if (!filePath) return next();
try {
const html = readFileSync(filePath, 'utf8');