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.

6.2 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" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
		<title data-i18n="embodiment_embed.meta_title">Agent — three.ws</title>
		<!-- sandboxed: no index, allow framing by any host (ChatGPT, Claude, etc.) -->
		<meta name="robots" content="noindex" />
		<link rel="icon" href="/favicon.ico" sizes="any" />
		<style>
			:root { color-scheme: dark; }
			*, *::before, *::after { box-sizing: border-box; }
			html, body {
				margin: 0; padding: 0;
				width: 100%; height: 100%;
				overflow: hidden;
				background: radial-gradient(120% 120% at 50% 0%, #141420 0%, #0a0a12 70%);
			}
			#stage-root {
				position: fixed;
				inset: 0;
				/* The overlay chrome sits on top; the canvas fills below it. */
			}
		</style>
	</head>
	<body>
		<div id="stage-root"></div>
		<script type="module">
			import { EmbodimentStage } from '/apps-sdk/embodiment/embodiment-stage.js';
			import { mountOverlay } from '/apps-sdk/embodiment/overlay.js';

			// ── URL params ──────────────────────────────────────────────────────
			const q = new URLSearchParams(location.search);
			const personaId  = q.get('persona')   || null;
			const glbUrl     = q.get('glb')        || null;
			const name       = q.get('name')       || 'Agent';
			// The label the overlay shows: the ?name param (or the generic default)
			// until a ?persona=<id> resolve returns the persona's real name. Every
			// later state change reads this, so a resolved name is never reverted to
			// the placeholder by the next idle/speaking/thinking transition.
			let displayName  = name;
			const initState  = q.get('state')      || 'idle';
			const speakText  = q.get('text')       || '';
			const emotion    = q.get('emotion')    || null;
			const intensity  = parseFloat(q.get('intensity') || '0.8');
			const gesture    = q.get('gesture')    || null;
			// Opt-in: only personas bound to a wallet (prompt 17 — persona_identity)
			// request the live chain-state poll. Everyone else renders exactly as
			// before — zero extra network calls for a plain embodied body.
			const showWallet = q.get('wallet') === '1';
			const walletNetwork = q.get('network') === 'devnet' ? 'devnet' : 'mainnet';

			if (!glbUrl && !personaId) {
				// Nothing to show — emit a minimal error surface.
				document.body.innerHTML =
					'<p style="color:#fb7185;font-family:system-ui;padding:24px;margin:0">No persona or GLB URL supplied.</p>';
				throw new Error('[embodiment-embed] missing glb or persona param');
			}

			// ── stage + overlay ─────────────────────────────────────────────────
			const root = document.getElementById('stage-root');

			// overlay sits above the canvas; stage mounts its canvas into root
			const overlay = mountOverlay(root, {
				onRetry: () => location.reload(),
			});
			overlay.setName(name);
			overlay.setState('loading');

			const stage = new EmbodimentStage(root, {
				background: q.get('bg') === 'transparent' ? null : undefined,
				onState: (state, detail) => overlay.setState(state, { ...detail, name: displayName }),
			});

			// ── load ─────────────────────────────────────────────────────────────
			// glbUrl is a direct param; persona_id resolution for durable reload
			// hits the persona API so the embed is always up to date.
			async function resolveGlb() {
				if (glbUrl) return { glbUrl, name };
				// Reload durable persona by id.
				const res = await fetch(`/api/mcp3d/persona?id=${encodeURIComponent(personaId)}`, {
					credentials: 'same-origin',
				});
				if (!res.ok) throw new Error(`persona ${res.status}`);
				const data = await res.json();
				return { glbUrl: data.glb_url, name: data.name || name };
			}

			(async () => {
				let resolved;
				try {
					resolved = await resolveGlb();
				} catch (err) {
					overlay.setState('error', { message: 'Could not load this persona. ' + (err?.message || '') });
					return;
				}

				displayName = resolved.name;
				overlay.setName(displayName);
				const ok = await stage.loadPersona({
					glbUrl: resolved.glbUrl,
					name: resolved.name,
					personaId,
				});
				if (!ok) return; // stage already set 'error'

				// Drive the requested initial state after loading.
				if (initState === 'speaking' && speakText) {
					await stage.speak({ text: speakText, emotion, intensity, gesture });
				} else if (initState === 'thinking') {
					stage.thinking();
				} else if (initState === 'listening') {
					stage.listening();
				}
				// else: idle is already set by loadPersona

				// ── live on-chain identity → visuals (opt-in, prompt 17) ────────────
				if (showWallet && personaId) {
					const applyIdentity = async () => {
						try {
							const res = await fetch(
								`/api/mcp3d/persona-identity?id=${encodeURIComponent(personaId)}&network=${walletNetwork}`,
								{ credentials: 'same-origin' },
							);
							if (!res.ok) return; // transient upstream hiccup — keep the last-known visuals
							const identity = await res.json();
							const visuals = stage.setChainState(identity);
							overlay.setIdentity(visuals);
						} catch {
							// Network hiccup — leave the body in its last-known chain state
							// rather than flashing an error over an otherwise-fine avatar.
						}
					};
					await applyIdentity();
					const pollMs = 20_000;
					const poll = setInterval(applyIdentity, pollMs);
					window.addEventListener('beforeunload', () => clearInterval(poll));
					document.addEventListener('visibilitychange', () => {
						if (document.visibilityState === 'visible') applyIdentity();
					});
				}
			})();
		</script>
		<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>