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.

26.7 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>
	<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width,initial-scale=1" />
	<title data-i18n="demo_economy.meta_title">Agent Economy — two AI agents pay each other on-chain · three.ws</title>
	<meta name="description" content="Watch NOVA and ORACLE — two three.ws AI agents with real Solana wallets — discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world."  data-i18n-attr="content:demo_economy.meta_description"/>
	<meta property="og:type" content="website" />
	<meta property="og:site_name" content="three.ws" />
	<meta property="og:url" content="https://three.ws/demo-economy" />
	<meta property="og:title" content="Agent Economy Demo — two AI agents pay each other on-chain · three.ws"  data-i18n-attr="content:demo_economy.meta_og_title"/>
	<meta property="og:description" content="Watch NOVA and ORACLE — two three.ws AI agents with real Solana wallets — discover services, pay each other in SOL, and display a live market briefing."  data-i18n-attr="content:demo_economy.meta_og_description"/>
	<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Economy%3A+NOVA+%26+ORACLE&amp;d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&amp;p=%2Fdemo" />
	<meta property="og:image:width" content="1200" />
	<meta property="og:image:height" content="630" />
	<meta name="twitter:card" content="summary_large_image" />
	<meta name="twitter:site" content="@trythreews" />
	<meta name="twitter:title" content="Agent Economy Demo — two AI agents pay each other on-chain · three.ws"  data-i18n-attr="content:demo_economy.meta_twitter_title"/>
	<meta name="twitter:description" content="Watch NOVA and ORACLE — two three.ws AI agents with real Solana wallets — discover services, pay each other in SOL, and display a live market briefing."  data-i18n-attr="content:demo_economy.meta_twitter_description"/>
	<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Economy%3A+NOVA+%26+ORACLE&amp;d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&amp;p=%2Fdemo" />
		<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" />
	<style>
		:root {
			--bg: #070707;
			--panel: rgba(10,13,24,0.9);
			--border: rgba(255,255,255,0.08);
			--text: #e8e9f2;
			--muted: #6b6d82;
			--nova: #4e8cff;
			--oracle: #22d17a;
			--mono: ui-monospace,"SF Mono",Menlo,Consolas,monospace;
		}
		* { box-sizing: border-box; margin: 0; padding: 0; }
		html, body {
			height: 100%; overflow: hidden;
			background: var(--bg); color: var(--text);
			font: 14px/1.5 -apple-system,system-ui,"Segoe UI",sans-serif;
			-webkit-font-smoothing: antialiased;
		}
		#root {
			display: grid; height: 100vh;
			grid-template-rows: 52px 1fr 44px;
			grid-template-columns: 1fr 300px;
			grid-template-areas: "top top" "canvas sidebar" "bot bot";
		}

		/* ── Top bar ── */
		#topbar {
			grid-area: top;
			display: flex; align-items: center; gap: 14px;
			padding: 0 18px;
			background: rgba(5,7,13,0.95); border-bottom: 1px solid var(--border);
			z-index: 10;
		}
		.brand { display: flex; align-items: center; gap: 10px; }
		.brand a { color: var(--text); text-decoration: none; font-weight: 600; font-size: 15px; }
		.brand .sep { color: var(--muted); }
		.brand .page { color: var(--muted); font-size: 13px; }
		.pills { display: flex; gap: 7px; }
		.topnav { display: flex; gap: 4px; margin-left: 14px; }
		.topnav a {
			color: var(--muted); text-decoration: none; font-size: 12px; font-weight: 600;
			padding: 5px 10px; border-radius: 7px; border: 1px solid transparent;
			transition: color .15s, border-color .15s, background .15s;
		}
		.topnav a:hover { color: var(--text); border-color: var(--border); background: rgba(255,255,255,0.04); }
		.topnav a:focus-visible { outline: 2px solid var(--nova); outline-offset: 2px; }
		@media (max-width: 680px) { .topnav { display: none; } }
		.pill {
			display: inline-flex; align-items: center; gap: 6px;
			padding: 4px 11px; border-radius: 99px; font-size: 11px; font-weight: 700;
			letter-spacing: 0.04em; border: 1px solid;
		}
		.pill .dot { width: 6px; height: 6px; border-radius: 50%; }
		.nova { color: var(--nova); border-color: rgba(78,140,255,0.35); background: rgba(78,140,255,0.07); }
		.nova .dot { background: var(--nova); box-shadow: 0 0 6px var(--nova); }
		.oracle { color: var(--oracle); border-color: rgba(34,209,122,0.35); background: rgba(34,209,122,0.07); }
		.oracle .dot { background: var(--oracle); box-shadow: 0 0 6px var(--oracle); }
		#run-btn {
			margin-left: auto;
			display: inline-flex; align-items: center; gap: 8px;
			padding: 8px 18px; border: none; border-radius: 9px;
			background: var(--nova); color: #fff;
			font: 600 13px -apple-system,system-ui,sans-serif;
			cursor: pointer; transition: filter .15s, opacity .15s;
		}
		#run-btn:hover:not(:disabled) { filter: brightness(1.12); }
		#run-btn:disabled { opacity: .5; cursor: not-allowed; }
		.spinner {
			width: 13px; height: 13px; border-radius: 50%;
			border: 2px solid rgba(255,255,255,.3); border-top-color: #fff;
			animation: spin .65s linear infinite;
		}
		@keyframes spin { to { transform: rotate(360deg); } }

		/* ── Canvas ── */
		#canvas-wrap { grid-area: canvas; position: relative; overflow: hidden; }
		#scene { width: 100%; height: 100%; display: block; }
		/* WebGL can be unavailable (old GPU, blocklisted driver, hardened browser).
		   The narrated economy still runs in the sidebar, so say what is missing
		   instead of leaving a black rectangle. */
		#scene-fallback {
			display: none;
			position: absolute; inset: 0;
			flex-direction: column; align-items: center; justify-content: center;
			gap: 8px; padding: 24px; text-align: center;
			background: radial-gradient(circle at 50% 40%, rgba(78,140,255,0.08), transparent 60%), #05070d;
		}
		#scene-fallback.show { display: flex; }
		#scene-fallback .sf-title { font-size: 15px; font-weight: 700; }
		#scene-fallback .sf-body { font-size: 12px; color: var(--muted); max-width: 42ch; line-height: 1.6; }

		/* ── Sidebar ── */
		#sidebar {
			grid-area: sidebar;
			display: flex; flex-direction: column;
			border-left: 1px solid var(--border); background: var(--panel);
			overflow: hidden; font-size: 13px;
		}
		.sb-block { padding: 12px 14px; border-bottom: 1px solid var(--border); }
		.sb-label {
			font-size: 9px; font-weight: 800; letter-spacing: 0.1em;
			text-transform: uppercase; color: var(--muted); margin-bottom: 9px;
		}

		/* Wallet rows */
		.w-row { display: flex; align-items: center; gap: 9px; padding: 6px 0; }
		.w-row + .w-row { border-top: 1px solid var(--border); }
		.w-dot { width: 8px; height: 8px; border-radius: 50%; flex: 0 0 auto; }
		.w-info { flex: 1; min-width: 0; }
		.w-name { font-size: 11px; font-weight: 700; }
		.w-addr { font: 9px/1.4 var(--mono); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
		.w-bal { font: 700 12px var(--mono); white-space: nowrap; }

		/* Payment card */
		#pay-card { display: none; flex-direction: column; gap: 5px; }
		#pay-card.show { display: flex; }
		#pay-empty { color: var(--muted); font-size: 11px; }
		.pr { display: flex; justify-content: space-between; align-items: flex-start; gap: 6px; font-size: 11px; }
		.pk { color: var(--muted); flex: 0 0 auto; }
		.pv { font-family: var(--mono); font-size: 10px; text-align: right; word-break: break-all; }
		.pv.g { color: var(--oracle); font-size: 12px; }
		.pv a { color: var(--nova); text-decoration: none; }
		.pv a:hover { text-decoration: underline; }
		.sim-tag {
			font-size: 9px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase;
			padding: 2px 6px; border-radius: 4px;
			color: #f0a030; background: rgba(240,160,48,0.12); border: 1px solid rgba(240,160,48,0.28);
		}

		/* Run error: actionable, never a bare "see console" */
		#run-error { display: none; padding: 12px 14px; border-bottom: 1px solid rgba(255,99,99,0.28); background: rgba(255,99,99,0.06); }
		#run-error.show { display: block; }
		#run-error .re-title { font-size: 12px; font-weight: 700; color: #ff8a8a; }
		#run-error .re-body { font-size: 11px; color: var(--muted); margin: 4px 0 9px; line-height: 1.5; }
		#retry-btn {
			display: inline-flex; align-items: center;
			padding: 6px 12px; border-radius: 8px; cursor: pointer;
			background: rgba(255,99,99,0.12); color: #ff8a8a;
			border: 1px solid rgba(255,99,99,0.35);
			font: 700 11px -apple-system,system-ui,sans-serif;
			transition: background .15s, border-color .15s;
		}
		#retry-btn:hover { background: rgba(255,99,99,0.2); border-color: rgba(255,99,99,0.55); }
		#retry-btn:focus-visible { outline: 2px solid #ff8a8a; outline-offset: 2px; }

		/* Activity log */
		#steps-wrap { flex: 1; overflow-y: auto; }
		.step {
			display: flex; align-items: flex-start; gap: 9px;
			padding: 7px 14px;
			opacity: 0; transform: translateY(5px);
			transition: opacity .3s, transform .3s;
		}
		.step.in { opacity: 1; transform: none; }
		.step-ico { font-size: 15px; flex: 0 0 auto; margin-top: 1px; }
		.step-txt .sl { font-size: 12px; font-weight: 600; }
		.step-txt .sd { font-size: 10px; color: var(--muted); margin-top: 2px; line-height: 1.4; }

		/* ── Bottom bar ── */
		#botbar {
			grid-area: bot;
			display: flex; align-items: center; gap: 12px;
			padding: 0 18px; background: rgba(5,7,13,0.95);
			border-top: 1px solid var(--border); font-size: 11px;
		}
		#status { font-weight: 600; color: var(--text); }
		.chips { display: flex; gap: 6px; margin-left: auto; }
		.chip {
			padding: 3px 8px; border-radius: 99px; font-size: 10px; font-weight: 700;
			letter-spacing: 0.04em; border: 1px solid var(--border); color: var(--muted);
		}

		/* Mobile sheet toggle — hidden on desktop */
		#sheet-toggle {
			display: none;
			margin-left: 8px;
			padding: 7px 12px; border-radius: 8px;
			background: transparent; color: var(--text);
			border: 1px solid var(--border);
			font: 600 12px -apple-system,system-ui,sans-serif; cursor: pointer;
			transition: background .15s, border-color .15s;
		}
		#sheet-toggle:hover { background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.18); }
		#sheet-toggle:focus-visible { outline: 2px solid var(--nova); outline-offset: 2px; }

		/* Narrow viewports: the topbar carried five items and pushed "Run demo"
		   off-screen at 320px, making the page's only action unreachable. Drop the
		   decorative pieces (the agent pills repeat in the Wallets panel, the tech
		   chips and mode line repeat in the Transaction panel) so the brand, the
		   sheet toggle and the primary button always fit. */
		@media (max-width: 560px) {
			#topbar { padding: 0 10px; gap: 8px; }
			.pills { display: none; }
			.brand a { font-size: 14px; }
			.brand .page { font-size: 12px; }
			#run-btn { padding: 8px 12px; font-size: 12px; }
			#sheet-toggle { padding: 6px 10px; font-size: 11px; }
			#botbar { padding: 0 12px; gap: 8px; }
			#botbar .bot-sep, #botline, .chips { display: none; }
			#status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
		}
		@media (max-width: 430px) {
			.brand .sep { display: none; }
			.brand .page {
				position: absolute; width: 1px; height: 1px;
				overflow: hidden; clip-path: inset(50%); white-space: nowrap;
			}
		}

		@media (max-width: 680px) {
			#root { grid-template-columns: 1fr; grid-template-areas: "top" "canvas" "bot"; }
			/* The payment proof is the point of the demo — keep it reachable on
			   mobile as a slide-up sheet instead of hiding it outright. */
			#sidebar {
				position: fixed; left: 0; right: 0; bottom: 44px; z-index: 20;
				max-height: 64vh;
				transform: translateY(calc(100% + 44px));
				transition: transform .28s cubic-bezier(.2,.7,.2,1);
				border-left: none; border-top: 1px solid var(--border);
				border-radius: 14px 14px 0 0;
				box-shadow: 0 -14px 34px rgba(0,0,0,0.55);
			}
			#sidebar.open { transform: translateY(0); }
			#sheet-toggle { display: inline-flex; align-items: center; }
		}
	</style>

	<link rel="canonical" href="https://three.ws/demo">
	<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Economy — NOVA & ORACLE","description":"Two three.ws AI agents with real Solana wallets discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world.","url":"https://three.ws/demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>

	<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
	<meta property="og:locale" content="en_US">
	<meta property="og:image:alt" content="Agent Economy — NOVA &amp; ORACLE — three.ws">
</head>
<body>
<div id="root">
	<header id="topbar">
		<div class="brand">
			<a href="/" data-i18n="demo_economy.three_ws">three.ws</a>
			<span class="sep">/</span>
			<h1 class="page" data-i18n="demo_economy.agent_economy">Agent Economy</h1>
		</div>
		<div class="pills">
			<span class="pill nova" data-i18n-html="demo_economy.nova_payer"><span class="dot"></span>NOVA · payer</span>
			<span class="pill oracle" data-i18n-html="demo_economy.oracle_provider"><span class="dot"></span>ORACLE · provider</span>
		</div>
		<nav class="topnav">
			<a href="/agents" data-i18n="demo_economy.agents">Agents</a>
			<a href="/launches" data-i18n="demo_economy.launches">Launches</a>
		</nav>
		<button id="sheet-toggle" type="button" aria-label="Show payment details" aria-expanded="false" data-i18n="demo_economy.details" data-i18n-attr="aria-label:demo_economy.show_payment_details_arialabel">Details</button>
		<button id="run-btn" type="button" data-i18n-html="demo_economy.run_demo"><span id="run-label">Run demo</span></button>
	</header>

	<div id="canvas-wrap">
		<canvas id="scene" role="img" aria-label="3D scene: the agents NOVA and ORACLE either side of a screen that shows the x402 bazaar, the payment, and the delivered market briefing" data-i18n-attr="aria-label:demo_economy.scene_arialabel"></canvas>
		<div id="scene-fallback">
			<div class="sf-title" data-i18n="demo_economy.scene_unavailable">3D scene unavailable</div>
			<p class="sf-body" data-i18n="demo_economy.scene_unavailable_body">This browser could not start WebGL, so the world is not rendering. The demo still runs: press Run demo and follow the payment and the market briefing in the panel beside it.</p>
		</div>
	</div>

	<aside id="sidebar">
		<div class="sb-block">
			<div class="sb-label">Wallets</div>
			<div class="w-row">
				<span class="w-dot" style="background:var(--nova);box-shadow:0 0 7px var(--nova)"></span>
				<div class="w-info">
					<div class="w-name" style="color:var(--nova)">NOVA</div>
					<div class="w-addr" id="addr-nova">not configured</div>
				</div>
				<div class="w-bal" id="bal-nova" style="color:var(--nova)">—</div>
			</div>
			<div class="w-row">
				<span class="w-dot" style="background:var(--oracle);box-shadow:0 0 7px var(--oracle)"></span>
				<div class="w-info">
					<div class="w-name" style="color:var(--oracle)">ORACLE</div>
					<div class="w-addr" id="addr-oracle">not configured</div>
				</div>
				<div class="w-bal" id="bal-oracle" style="color:var(--oracle)">—</div>
			</div>
		</div>

		<div class="sb-block">
			<div class="sb-label">Transaction</div>
			<div id="pay-empty">Run the demo to see the on-chain transfer.</div>
			<div id="pay-card">
				<div class="pr"><span class="pk" data-i18n="demo_economy.amount">Amount</span><span class="pv g" id="py-amt">—</span></div>
				<div class="pr"><span class="pk" data-i18n="demo_economy.network">Network</span><span class="pv" data-i18n="demo_economy.solana">Solana</span></div>
				<div class="pr" id="py-sim-row" style="display:none"><span class="pk" data-i18n="demo_economy.mode">Mode</span><span class="pv" data-i18n-html="demo_economy.simulated"><span class="sim-tag">Simulated</span></span></div>
				<div class="pr"><span class="pk" data-i18n="demo_economy.signature">Signature</span><span class="pv" id="py-sig">—</span></div>
			</div>
		</div>

		<div id="run-error" role="alert">
			<div class="re-title" data-i18n="demo_economy.demo_could_not_run">Demo could not run</div>
			<p class="re-body" id="re-body"></p>
			<button id="retry-btn" type="button" data-i18n="demo_economy.retry">Retry</button>
		</div>

		<div class="sb-label" style="padding:10px 14px 4px">Activity</div>
		<div id="steps-wrap"><div id="steps" role="log" aria-live="polite" aria-relevant="additions"></div></div>
	</aside>

	<footer id="botbar">
		<span id="status" aria-live="polite" data-i18n="demo_economy.ready_click_run_demo">Ready. Click Run demo</span>
		<span class="bot-sep" style="color:var(--muted)">·</span>
		<span id="botline" style="color:var(--muted)" data-i18n="demo_economy.real_solana_infrastructure_x402_protocol">Real Solana infrastructure · x402 protocol</span>
		<div class="chips">
			<span class="chip" data-i18n="demo_economy.x402">x402</span>
			<span class="chip" data-i18n="demo_economy.solana_2">Solana</span>
			<span class="chip" data-i18n="demo_economy.three_js">Three.js</span>
			<span class="chip" data-i18n="demo_economy.sse">SSE</span>
		</div>
	</footer>
</div>

<script type="module">
import { createScene } from '/src/demo-economy.js';

const canvas = document.getElementById('scene');
const runBtn = document.getElementById('run-btn');
const runLabel = document.getElementById('run-label');
const stepsEl = document.getElementById('steps');
const stepsWrap = document.getElementById('steps-wrap');
const statusEl = document.getElementById('status');
const botLineEl = document.getElementById('botline');

// Reflect the actual run mode in the bottom bar instead of always claiming a
// live on-chain bazaar/transfer. Anonymous visitors run the simulated path.
let bazaarOk = true;
function updateBotLine(simulated) {
	const bazaar = bazaarOk ? ' · live x402 bazaar' : ' · bazaar offline';
	botLineEl.textContent = simulated
		? 'Simulated payment — sign in to run a live on-chain transfer' + bazaar
		: 'Live on-chain transfer · Solana mainnet' + bazaar;
}

// ── Scene init ─────────────────────────────────────────────────────────────
let world = null;
try {
	world = createScene(canvas);
} catch (err) {
	// WebGL unavailable or the context was refused. The narrated economy is the
	// substance of this page and it does not need the renderer, so surface the
	// missing piece and keep the run path working.
	document.getElementById('scene-fallback').classList.add('show');
	canvas.style.display = 'none';
	console.warn('3D scene unavailable:', err?.message || err);
}

// ── Utilities ──────────────────────────────────────────────────────────────
function esc(s) {
	return String(s ?? '').replace(/[&<>"']/g, c =>
		({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c]);
}

function addStep(icon, label, detail) {
	const el = document.createElement('div');
	el.className = 'step';
	el.innerHTML = `<span class="step-ico">${icon}</span>
		<div class="step-txt"><div class="sl">${esc(label)}</div>${detail ? `<div class="sd">${esc(detail)}</div>` : ''}</div>`;
	stepsEl.appendChild(el);
	requestAnimationFrame(() => el.classList.add('in'));
	stepsWrap.scrollTop = stepsWrap.scrollHeight;
}

function updateWallet(side, { name, address, balance_sol }) {
	const addrEl = document.getElementById(side === 'A' ? 'addr-nova' : 'addr-oracle');
	const balEl  = document.getElementById(side === 'A' ? 'bal-nova'  : 'bal-oracle');
	if (address) addrEl.textContent = address.length > 20 ? address.slice(0,8)+'…'+address.slice(-6) : address;
	if (balance_sol != null) balEl.textContent = balance_sol + ' SOL';
}

// ── Error surface ──────────────────────────────────────────────────────────
// A run can fail for reasons the visitor can act on (offline, a blocked
// EventSource, an upstream blip), so name the cause and offer the retry rather
// than pointing at the developer console.
const errorCard = document.getElementById('run-error');
const errorBody = document.getElementById('re-body');
const retryBtn = document.getElementById('retry-btn');

function showError(message) {
	errorBody.textContent = message;
	errorCard.classList.add('show');
	openSheetOnMobile();
}

function clearError() {
	errorCard.classList.remove('show');
	errorBody.textContent = '';
}

// ── Demo runner ────────────────────────────────────────────────────────────
let running = false;

function runDemo() {
	if (running) return;
	running = true;
	runBtn.disabled = true;
	runBtn.insertAdjacentHTML('afterbegin', '<span class="spinner"></span>');
	runLabel.textContent = 'Running…';
	stepsEl.innerHTML = '';
	statusEl.textContent = 'Starting demo…';
	clearError();
	bazaarOk = true;
	botLineEl.textContent = 'Real Solana infrastructure · x402 protocol';

	// Reset
	document.getElementById('pay-card').classList.remove('show');
	document.getElementById('pay-empty').style.display = '';
	document.getElementById('py-sim-row').style.display = 'none';

	world?.nova?.setState('idle');
	world?.oracle?.setState('idle');
	world?.tv?.setPhase('idle');
	world?.tv?.setPayment(null);
	world?.tv?.setBriefing(null);
	world?.beam?.deactivate();

	const es = new EventSource('/api/demo-economy');
	let settled = false;
	let timeoutId = 0;

	function finish() {
		if (settled) return; settled = true;
		clearTimeout(timeoutId);
		es.close();
		runBtn.disabled = false;
		runBtn.querySelector('.spinner')?.remove();
		runLabel.textContent = 'Run again';
		running = false;
	}

	es.addEventListener('step', e => {
		const d = JSON.parse(e.data);
		addStep(d.icon, d.label, d.detail);
		statusEl.textContent = d.label;

		const id = d.id;
		if (id === 'agents_ready') {
			world?.nova?.setState('active');
			world?.oracle?.setState('active');
		} else if (id === 'browsing_bazaar') {
			world?.tv?.setPhase('browsing');
		} else if (id === 'payment_init') {
			world?.nova?.setState('paying');
			world?.oracle?.setState('paying');
			world?.beam?.activate();
			world?.tv?.setPhase('paying');
		} else if (id === 'payment_confirmed') {
			world?.beam?.deactivate();
		} else if (id === 'done') {
			world?.nova?.setState('done');
			world?.oracle?.setState('done');
			world?.tv?.setPhase('content');
			statusEl.textContent = '✓ Briefing received — live on TV';
		}
	});

	es.addEventListener('bazaar', e => {
		const d = JSON.parse(e.data);
		world?.tv?.setServices(d);
		bazaarOk = d.bazaarAvailable !== false;
	});

	es.addEventListener('wallet', e => {
		const d = JSON.parse(e.data);
		if (d.agentA) updateWallet('A', d.agentA);
		if (d.agentB) updateWallet('B', d.agentB);
	});

	es.addEventListener('payment', e => {
		const d = JSON.parse(e.data);
		document.getElementById('pay-empty').style.display = 'none';
		document.getElementById('pay-card').classList.add('show');
		document.getElementById('py-amt').textContent =
			(d.amount_sol ? d.amount_sol + ' SOL' : '—') + (d.amount_usd ? ' (' + d.amount_usd + ')' : '');
		if (d.simulated) document.getElementById('py-sim-row').style.display = '';
		const sigEl = document.getElementById('py-sig');
		if (d.signature) {
			sigEl.innerHTML = `<a href="${esc(d.explorer_url)}" target="_blank" rel="noopener">${esc(d.signature.slice(0,12))}… ↗</a>`;
		} else {
			sigEl.innerHTML = `<span style="color:var(--muted)">no on-chain tx — simulated</span>`;
		}
		world?.tv?.setPayment(d);
		updateBotLine(d.simulated);
		openSheetOnMobile();
	});

	es.addEventListener('content', e => {
		const d = JSON.parse(e.data);
		world?.tv?.setBriefing(d);
		world?.tv?.setPhase('content');
	});

	es.addEventListener('done', () => finish());

	// EventSource delivers BOTH a server-sent `error` event (which carries data)
	// and its own transport failure under the same event name, so branch on
	// whether a payload came with it.
	es.addEventListener('error', e => {
		if (settled) return;
		let serverMessage = null;
		try { serverMessage = JSON.parse(e.data).message; } catch {}
		if (serverMessage) {
			addStep('⚠️', 'Run failed', serverMessage);
			statusEl.textContent = 'Run failed';
			showError(serverMessage + ' Nothing was paid. Retry when you are ready.');
		} else {
			statusEl.textContent = 'Connection lost';
			showError(navigator.onLine === false
				? 'You appear to be offline. The demo streams live from three.ws, so reconnect and retry.'
				: 'The connection to the demo stream dropped before it finished. No payment was made. Retry to start a fresh run.');
		}
		finish();
	});

	// Hard timeout: a stream that stalls mid-run leaves the button spinning
	// forever otherwise.
	timeoutId = setTimeout(() => {
		if (settled) return;
		statusEl.textContent = 'Run timed out';
		showError('The run did not finish within 35 seconds. No payment was made. Retry to start a fresh run.');
		finish();
	}, 35000);
}

runBtn.addEventListener('click', runDemo);
retryBtn.addEventListener('click', runDemo);

// Mobile sheet — surface the payment proof instead of hiding it on small screens.
const sheetToggle = document.getElementById('sheet-toggle');
const sidebarEl = document.getElementById('sidebar');
function setSheet(open) {
	sidebarEl.classList.toggle('open', open);
	sheetToggle.setAttribute('aria-expanded', String(open));
	sheetToggle.textContent = open ? 'Hide' : 'Details';
}
sheetToggle.addEventListener('click', () => setSheet(!sidebarEl.classList.contains('open')));
function openSheetOnMobile() {
	if (window.matchMedia('(max-width: 680px)').matches) setSheet(true);
}
</script>
	<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>