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.

11.4 KB
Raw Blame
<!doctype html>
<html lang="en">
	<head>
		<style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
		<meta charset="utf-8" />
		<link rel="icon" href="/favicon.ico" sizes="any" />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
		<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
		<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
		<link rel="manifest" href="/manifest.webmanifest" />
		<title data-i18n="a_embed.meta_title">three.ws</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta name="description" content="Embedded three.ws avatar — on-chain."  data-i18n-attr="content:a_embed.meta_description"/>
		<meta name="robots" content="noindex" />
		<style>
			html,
			body {
				margin: 0;
				padding: 0;
				height: 100%;
				width: 100%;
				background: transparent;
				overflow: hidden;
				font-family: system-ui, sans-serif;
			}
			#stage {
				position: absolute;
				inset: 0;
			}
			#stage canvas {
				display: block;
				width: 100% !important;
				height: 100% !important;
			}
			#stage .gui-wrap,
			#stage .gui-toggle,
			#stage .annotation-canvas {
				display: none !important;
			}
			#stage .model-info {
				display: none !important;
			}
			#name-plate {
				position: absolute;
				left: 12px;
				bottom: 10px;
				z-index: 2;
				pointer-events: none;
				font-size: 11px;
				color: rgba(255, 255, 255, 0.55);
				letter-spacing: 0.04em;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
			}
			#chain-plate {
				position: absolute;
				right: 12px;
				bottom: 10px;
				z-index: 2;
				pointer-events: none;
				font-size: 10px;
				color: rgba(255, 255, 255, 0.4);
				letter-spacing: 0.08em;
				text-transform: uppercase;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
			}
			#open-link {
				position: absolute;
				right: 12px;
				top: 10px;
				z-index: 3;
				font-size: 10px;
				color: rgba(255, 255, 255, 0.55);
				letter-spacing: 0.05em;
				text-decoration: none;
				padding: 4px 8px;
				border-radius: 4px;
				background: rgba(0, 0, 0, 0.35);
				backdrop-filter: blur(4px);
			}
			#open-link:hover {
				color: rgba(255, 255, 255, 0.9);
				background: rgba(0, 0, 0, 0.5);
			}
			#loading {
				position: absolute;
				inset: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				color: rgba(255, 255, 255, 0.5);
				font-size: 12px;
			}
			#loading::after {
				content: '';
				width: 18px;
				height: 18px;
				margin-left: 8px;
				border: 2px solid rgba(255, 255, 255, 0.15);
				border-top-color: rgba(255, 255, 255, 0.5);
				border-radius: 50%;
				animation: spin 0.8s linear infinite;
			}
			@keyframes spin {
				to {
					transform: rotate(360deg);
				}
			}
			#error,
			#blocked {
				position: absolute;
				inset: 0;
				display: none;
				align-items: center;
				justify-content: center;
				color: rgba(255, 255, 255, 0.55);
				font-size: 12px;
				padding: 1rem;
				text-align: center;
				flex-direction: column;
				gap: 6px;
			}
			#blocked a {
				color: rgba(180, 200, 255, 0.9);
				text-decoration: none;
			}
			body.bg-dark {
				background: #0d0d0d;
			}
			body.bg-light {
				background: #f5f5f5;
			}
			/* OBS browser-source: solid chromakey colour for streamers whose
			   compositor can't keep alpha. ?chromakey=%2300ff00 → bg green. */
			body.bg-chromakey {
				background: var(--chromakey-color, #00ff00) !important;
			}
			/* ?hide-chrome=1 — for kiosk / OBS / app-shell usage where the
			   embed is the whole frame and chrome (name plate, link, etc) is
			   redundant. Doesn't affect postMessage handshake. */
			body.hide-chrome #name-plate,
			body.hide-chrome #chain-plate,
			body.hide-chrome #open-link,
			body.hide-chrome #loading {
				display: none !important;
			}
			body.bg-light #name-plate {
				color: rgba(0, 0, 0, 0.65);
				text-shadow: none;
			}
			body.bg-light #chain-plate {
				color: rgba(0, 0, 0, 0.45);
				text-shadow: none;
			}
			body.bg-light #open-link {
				color: rgba(0, 0, 0, 0.65);
				background: rgba(255, 255, 255, 0.6);
			}
		</style>
	</head>
	<body>
		<div id="stage"></div>
		<div id="name-plate"></div>
		<div id="chain-plate"></div>
		<a id="open-link" target="_blank" rel="noopener" style="display: none" data-i18n="a_embed.open">Open ↗</a>
		<div id="loading">Loading agent</div>
		<div id="error"></div>
		<div id="blocked"></div>

		<script type="module">
			import { Viewer } from '/src/viewer.js';
			import {
				parseAgentRef,
				resolveOnchainAgent,
				toManifest,
				resolveUrlCandidates,
				isEmbedAllowed,
				toPublicUrl,
			} from '/src/erc8004/resolver.js';

			const params = new URL(location.href).searchParams;
			const bg = params.get('bg') || 'transparent';
			const chromakey = params.get('chromakey');
			if (chromakey) {
				// Validate hex (#rgb / #rrggbb) or three named colours we
				// support out of the box. Anything else falls back to the
				// default OBS green.
				const safe = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(chromakey)
					? chromakey
					: { green: '#00ff00', blue: '#0000ff', magenta: '#ff00ff' }[chromakey.toLowerCase()] ||
						'#00ff00';
				document.documentElement.style.setProperty('--chromakey-color', safe);
				document.body.classList.add('bg-chromakey');
			} else if (bg === 'dark') document.body.classList.add('bg-dark');
			else if (bg === 'light') document.body.classList.add('bg-light');

			const hideChrome = params.get('hide-chrome') === '1' || params.get('chrome') === '0';
			if (hideChrome) document.body.classList.add('hide-chrome');

			const avatar = params.get('avatar');
			const startAnimation = params.get('animation') || params.get('pose') || null;

			const plateOn = !hideChrome && params.get('name') !== '0';
			const chainOn = !hideChrome && params.get('chain-plate') !== '0';
			const openLinkOn = !hideChrome && params.get('open-link') !== '0';

			// URL: /a/:chainId/:agentId/embed
			const ref = parseAgentRef(location.pathname);

			// Best-effort parent origin from referrer; never use '*'.
			const parentOrigin = (() => {
				try {
					if (window.parent === window) return location.origin;
					if (document.referrer) return new URL(document.referrer).origin;
				} catch {}
				return null;
			})();

			function postToParent(msg) {
				if (!parent || parent === window) return;
				if (!parentOrigin) return;
				try { parent.postMessage(msg, parentOrigin); } catch {}
			}

			function showError(msg) {
				document.getElementById('loading').style.display = 'none';
				const el = document.getElementById('error');
				el.textContent = msg || 'Could not load agent';
				el.style.display = 'flex';
				postToParent({ __agent: true, type: 'error', message: msg });
			}

			function showBlocked(host) {
				document.getElementById('loading').style.display = 'none';
				const el = document.getElementById('blocked');
				const link = ref ? toPublicUrl(ref) : '/';
				el.innerHTML = `
				<div>This agent does not allow embedding on <b>${host || 'this site'}</b>.</div>
				<a href="${link}" target="_blank" rel="noopener">Open on three.ws ↗</a>
			`;
				el.style.display = 'flex';
				postToParent({ __agent: true, type: 'blocked', host });
			}

			// Best-effort parent hostname — referrer is the only cross-origin signal.
			function getParentHost() {
				try {
					if (window.parent === window) return location.hostname;
					if (document.referrer) return new URL(document.referrer).hostname;
				} catch {}
				return '';
			}

			// Try a list of candidate URLs; resolve with the first that succeeds.
			async function loadWithFallback(viewer, uris) {
				let lastErr;
				for (const u of uris) {
					try {
						await viewer.load(u, '', new Map());
						return u;
					} catch (err) {
						lastErr = err;
						console.warn('[a-embed] load failed, trying next:', u, err?.message);
					}
				}
				throw lastErr || new Error('All candidate URLs failed');
			}

			async function main() {
				if (avatar) {
					const r = await fetch(`/api/avatars/${encodeURIComponent(avatar)}`, {
						credentials: 'include',
					});
					if (!r.ok) return showError(`Avatar not found (${r.status})`);
					const { avatar: a } = await r.json();
					const glbUrl = a?.url || a?.model_url;
					if (!glbUrl) return showError('Avatar has no 3D body');

					const stage = document.getElementById('stage');
					const viewer = new Viewer(stage, { kiosk: true, postToParent });
					if (bg === 'transparent') {
						viewer.state.transparentBg = true;
						viewer.updateBackground();
					}

					if (plateOn && a?.name) {
						document.getElementById('name-plate').textContent = a.name;
					}
					if (openLinkOn) {
						const ol = document.getElementById('open-link');
						ol.href = `/avatars/${encodeURIComponent(avatar)}`;
						ol.style.display = 'inline-block';
					}

					const candidates = resolveUrlCandidates(glbUrl);
					await loadWithFallback(viewer, candidates);

					document.getElementById('loading').style.display = 'none';
					if (startAnimation) {
						try { await viewer.onGesture({ name: startAnimation, loop: true }); }
						catch (err) { console.warn('[a-embed] start animation failed', err); }
					}
					postToParent({
						__agent: true,
						type: 'ready',
						avatar,
						name: a?.name || '',
					});
					return;
				}

				if (!ref) return showError('Invalid agent URL');

				const resolved = await resolveOnchainAgent(ref);
				if (resolved.error && !resolved.glbUrl && !resolved.image) {
					return showError(`On-chain resolve failed: ${resolved.error}`);
				}

				// Embed-policy gate
				const parentHost = getParentHost();
				const policy = resolved.metadata?.embedPolicy;
				if (policy && !isEmbedAllowed(policy, parentHost)) {
					return showBlocked(parentHost);
				}

				if (plateOn) {
					document.getElementById('name-plate').textContent = resolved.name;
				}
				if (chainOn) {
					const chainName = resolved.chain?.name || `chain ${ref.chainId}`;
					document.getElementById('chain-plate').textContent =
						`${chainName} · #${ref.agentId}`;
				}
				if (openLinkOn) {
					const ol = document.getElementById('open-link');
					ol.href = toPublicUrl(ref);
					ol.style.display = 'inline-block';
				}

				const bodyURI = resolved.glbUrl || resolved.image;
				if (!bodyURI) return showError('Agent has no 3D body');

				const stage = document.getElementById('stage');
				const viewer = new Viewer(stage, { kiosk: true, postToParent });
				if (bg === 'transparent') {
					viewer.state.transparentBg = true;
					viewer.updateBackground();
				}

				const candidates = resolveUrlCandidates(bodyURI);
				await loadWithFallback(viewer, candidates);

				document.getElementById('loading').style.display = 'none';

				if (startAnimation) {
					try { await viewer.onGesture({ name: startAnimation, loop: true }); }
					catch (err) { console.warn('[a-embed] start animation failed', err); }
				}

				postToParent({
					__agent: true,
					type: 'ready',
					caip: resolved.caip,
					chainId: ref.chainId,
					agentId: ref.agentId,
					name: resolved.name,
					owner: resolved.onchain.owner,
				});
			}

			main().catch((err) => {
				console.error('[a-embed]', err);
				showError(err.message || 'Could not load agent');
			});
		</script>
		<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>