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.

28.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>
	<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="live.meta_title">Agent Economy — Live · three.ws</title>
	<meta name="description" content="Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D."  data-i18n-attr="content:live.meta_description"/>
	<meta property="og:type" content="website" />
	<meta property="og:site_name" content="three.ws" />
	<meta property="og:url" content="https://three.ws/live" />
	<meta property="og:title" content="Agent Economy — Live · three.ws"  data-i18n-attr="content:live.meta_og_title"/>
	<meta property="og:description" content="Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D."  data-i18n-attr="content:live.meta_og_description"/>
	<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Economy%3A+Live&amp;d=Two+AI+agents+in+a+virtual+world+paying+each+other+for+live+Solana+market+data.+Real+on-chain+transactions%2C+real+blockchain%2C+real+3D.&amp;p=%2Flive" />
	<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 — Live · three.ws"  data-i18n-attr="content:live.meta_twitter_title"/>
	<meta name="twitter:description" content="Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D."  data-i18n-attr="content:live.meta_twitter_description"/>
	<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Economy%3A+Live&amp;d=Two+AI+agents+in+a+virtual+world+paying+each+other+for+live+Solana+market+data.+Real+on-chain+transactions%2C+real+blockchain%2C+real+3D.&amp;p=%2Flive" />
		<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: #050505;
			--panel: rgba(12,14,22,0.9);
			--border: rgba(255,255,255,0.08);
			--border-hi: rgba(255,255,255,0.14);
			--text: #e8eaf4;
			--muted: #6b6e8a;
			--alpha: #4e8cff;
			--oracle: var(--accent);
			--green: #22d17a;
			--font: -apple-system, "Segoe UI", system-ui, sans-serif;
		}
		* { box-sizing: border-box; margin: 0; padding: 0; }
		html, body { height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font: 14px/1.5 var(--font); -webkit-font-smoothing: antialiased; }

		/* ── World canvas — full screen background ── */
		#world-canvas {
			position: fixed;
			inset: 0;
			width: 100%;
			height: 100%;
			z-index: 0;
		}

		/* ── Avatar iframes — positioned over the 3D pedestals ── */
		.agent-iframe {
			position: fixed;
			z-index: 2;
			border: none;
			background: transparent;
			pointer-events: none;
		}

		/* ── Name tags — float above the iframes ── */
		.agent-tag {
			position: fixed;
			z-index: 4;
			display: flex;
			align-items: center;
			gap: 7px;
			padding: 5px 12px;
			border-radius: 999px;
			border: 1px solid var(--border-hi);
			background: var(--panel);
			backdrop-filter: blur(12px);
			font-size: 11px;
			font-weight: 700;
			letter-spacing: 0.04em;
			transform: translate(-50%, 0);
			white-space: nowrap;
			pointer-events: auto;
			color: var(--text);
			text-decoration: none;
			cursor: pointer;
			transition: border-color .15s, background .15s;
		}
		.agent-tag:hover { border-color: var(--alpha); background: rgba(78,140,255,0.12); }
		.agent-tag:focus-visible { outline: 2px solid var(--alpha); outline-offset: 2px; }
		.agent-tag .dot {
			width: 6px; height: 6px; border-radius: 50%;
		}
		#tag-oracle .dot { background: var(--oracle); box-shadow: 0 0 8px var(--oracle); }
		#tag-trader .dot { background: var(--alpha);  box-shadow: 0 0 8px var(--alpha); }

		.agent-balance {
			position: fixed;
			z-index: 4;
			font-size: 10px;
			color: var(--muted);
			transform: translateX(-50%);
			white-space: nowrap;
			font-variant-numeric: tabular-nums;
			pointer-events: none;
		}

		/* ── Speech bubbles ── */
		.speech {
			position: fixed;
			z-index: 4;
			max-width: 220px;
			background: var(--panel);
			border: 1px solid var(--border-hi);
			border-radius: 10px;
			padding: 9px 11px;
			font-size: 12px;
			line-height: 1.5;
			backdrop-filter: blur(14px);
			opacity: 0;
			transform: translateY(6px);
			transition: opacity .3s, transform .3s;
			pointer-events: none;
		}
		.speech.show { opacity: 1; transform: translateY(0); }
		#speech-oracle { transform: translateX(-100%) translateY(6px); }
		#speech-oracle.show { transform: translateX(-100%) translateY(0); }

		/* ── HUD panel — bottom center ── */
		#hud {
			position: fixed;
			bottom: 16px;
			left: 50%;
			transform: translateX(-50%);
			z-index: 10;
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 10px;
			width: min(620px, 96vw);
		}

		/* Trade button */
		#trade-btn {
			padding: 12px 32px;
			border-radius: 12px;
			border: 1px solid rgba(78,140,255,0.5);
			background: linear-gradient(135deg, rgba(78,140,255,0.2), rgba(255,255,255,0.1));
			color: #fff;
			font: 600 13px/1 var(--font);
			letter-spacing: 0.05em;
			cursor: pointer;
			backdrop-filter: blur(14px);
			transition: opacity .15s, transform .1s, border-color .2s;
		}
		#trade-btn:hover:not(:disabled) { opacity: .85; border-color: rgba(255,255,255,0.5); }
		#trade-btn:active:not(:disabled) { transform: scale(.97); }
		#trade-btn:disabled { opacity: .35; cursor: not-allowed; }

		/* Notice — designed fund / not-configured state */
		#notice {
			width: 100%;
			background: rgba(250,77,86,0.08);
			border: 1px solid rgba(250,77,86,0.4);
			border-radius: 12px;
			padding: 11px 14px;
			backdrop-filter: blur(14px);
			font-size: 12px;
			line-height: 1.5;
			color: var(--text);
		}
		#notice.warn { background: rgba(240,160,48,0.09); border-color: rgba(240,160,48,0.42); }
		#notice .nt-title { font-weight: 700; display: block; margin-bottom: 3px; }
		#notice .nt-row { display: flex; align-items: center; gap: 8px; margin-top: 7px; flex-wrap: wrap; }
		#notice .nt-addr { font-family: ui-monospace, monospace; font-size: 11px; color: var(--muted); word-break: break-all; }
		#notice button, #notice a.nt-act {
			padding: 5px 11px; border-radius: 8px; cursor: pointer;
			border: 1px solid var(--border-hi); background: rgba(255,255,255,0.06);
			color: var(--text); font: 600 11px var(--font); text-decoration: none;
			transition: background .15s, border-color .15s;
		}
		#notice button:hover, #notice a.nt-act:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.4); }
		#notice button:focus-visible, #notice a.nt-act:focus-visible { outline: 2px solid var(--alpha); outline-offset: 2px; }

		/* Event log */
		#log {
			width: 100%;
			background: var(--panel);
			border: 1px solid var(--border);
			border-radius: 12px;
			padding: 10px 14px;
			backdrop-filter: blur(14px);
			max-height: 120px;
			overflow-y: auto;
			display: flex;
			flex-direction: column;
			gap: 4px;
		}
		#log::-webkit-scrollbar { width: 3px; }
		#log::-webkit-scrollbar-thumb { background: var(--border-hi); border-radius: 2px; }
		.log-entry {
			font-size: 11px;
			color: var(--muted);
			display: flex;
			align-items: baseline;
			gap: 8px;
			animation: fadeUp .2s ease;
		}
		@keyframes fadeUp { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:translateY(0)} }
		.log-entry .ev { color: var(--text); font-weight: 600; flex-shrink: 0; }
		.log-entry .ev.paid    { color: var(--green); }
		.log-entry .ev.error   { color: #fa4d56; }
		.log-entry .ev.oracle  { color: var(--oracle); }
		.log-entry a { color: inherit; text-decoration: underline; }

		/* ── Wallet status — top right ── */
		#wallets {
			position: fixed;
			top: 14px;
			right: 16px;
			z-index: 10;
			display: flex;
			flex-direction: column;
			gap: 6px;
		}
		.wallet-chip {
			display: flex;
			align-items: center;
			gap: 8px;
			padding: 6px 12px;
			border-radius: 999px;
			border: 1px solid var(--border-hi);
			background: var(--panel);
			backdrop-filter: blur(12px);
			font-size: 11px;
		}
		.wallet-chip .dot {
			width: 6px; height: 6px; border-radius: 50%;
		}
		.wallet-chip .addr { font-family: ui-monospace, monospace; color: var(--muted); }
		.wallet-chip .bal  { font-variant-numeric: tabular-nums; font-weight: 600; }

		/* ── Flash overlay ── */
		#flash {
			position: fixed; inset: 0; z-index: 20;
			border: 2px solid var(--green);
			box-shadow: inset 0 0 80px rgba(34,209,122,0.12);
			opacity: 0; pointer-events: none;
			transition: opacity .1s;
		}
		#flash.on { opacity: 1; }

		/* ── Brand ── */
		#brand {
			position: fixed; bottom: 14px; left: 16px;
			font-size: 10px; color: rgba(107,110,138,0.5);
			pointer-events: none; letter-spacing: .04em; z-index: 5;
		}
	</style>

	<link rel="canonical" href="https://three.ws/live">
	<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Economy — Live","description":"Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D.","url":"https://three.ws/live","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 — Live — three.ws">
</head>
<body>

<!-- Three.js world canvas -->
<canvas id="world-canvas"></canvas>

<!-- Avatar overlays — JS positions these over the 3D pedestals -->
<iframe id="iframe-oracle" class="agent-iframe" title="Agent Oracle" allow="autoplay"></iframe>
<iframe id="iframe-trader" class="agent-iframe" title="Agent Trader" allow="autoplay"></iframe>

<!-- Name tags (link to the agent directory) -->
<a id="tag-oracle" class="agent-tag" href="/agents" title="Browse three.ws agents" style="display:none" data-i18n-html="live.oracle_seller" data-i18n-attr="title:live.browse_three_ws_agents_title">
	<span class="dot"></span>Oracle · Seller
</a>
<a id="tag-trader" class="agent-tag" href="/agents" title="Browse three.ws agents" style="display:none" data-i18n-html="live.trader_buyer" data-i18n-attr="title:live.browse_three_ws_agents_title_2">
	<span class="dot"></span>Trader · Buyer
</a>

<!-- Balances -->
<div id="bal-oracle" class="agent-balance" style="display:none">—</div>
<div id="bal-trader" class="agent-balance" style="display:none">—</div>

<!-- Speech bubbles -->
<div id="speech-oracle" class="speech"></div>
<div id="speech-trader" class="speech"></div>

<!-- Wallet chips -->
<div id="wallets"></div>

<!-- HUD -->
<div id="hud">
	<div id="notice" role="status" aria-live="polite"></div>
	<button id="trade-btn" data-i18n="live.agent_trader_pays_oracle_for_solana_market">▶ &nbsp;Agent Trader pays Oracle for Solana market data</button>
	<div id="log"><div class="log-entry"><span class="ev" data-i18n="live.ready">READY</span><span data-i18n="live.agents_online_press_the_button_to_initiate">Agents online. Press the button to initiate a live on-chain trade.</span></div></div>
</div>

<!-- Flash -->
<div id="flash"></div>
<div id="brand">three.ws · agent economy · live on-chain</div>

<script type="module">
import {
	drawTvData,
	fireBeam,
	flashAgent,
	updateOverlayPositions,
} from '/src/live-economy.js';

// ── Avatar iframes ────────────────────────────────────────────────────────
const iframeOracle = document.getElementById('iframe-oracle');
const iframeTrader = document.getElementById('iframe-trader');

const params = new URLSearchParams(location.search);
function makeAvatarSrc(accent) {
	const q = new URLSearchParams();
	if (params.get('id')) q.set('id', params.get('id'));
	else q.set('model', params.get('model') || '/avatars/default.glb');
	q.set('bg', 'transparent');
	q.set('idle', 'on');
	q.set('name', '0');
	q.set('animPicker', '0');
	q.set('overlayMode', '1');
	q.set('accent', accent);
	return `/avatar-embed.html?${q}`;
}
iframeOracle.src = makeAvatarSrc('a855f7');
iframeTrader.src = makeAvatarSrc('4e8cff');

// ── iframe speech bridge ──────────────────────────────────────────────────
let readyOracle = false, readyTrader = false;
const qOracle = [], qTrader = [];

function toFrame(frame, ready, queue, msg) {
	if (ready) frame.contentWindow?.postMessage(msg, location.origin);
	else queue.push(msg);
}
function flushQueue(frame, queue) {
	while (queue.length) frame.contentWindow?.postMessage(queue.shift(), location.origin);
}

window.addEventListener('message', (e) => {
	if (e.data?.type !== 'v1.avatar.ready') return;
	if (e.source === iframeOracle.contentWindow) { readyOracle = true; flushQueue(iframeOracle, qOracle); }
	if (e.source === iframeTrader.contentWindow) { readyTrader = true; flushQueue(iframeTrader, qTrader); }
});
[iframeOracle, iframeTrader].forEach((f) => {
	f.addEventListener('load', () => {
		f.contentWindow?.postMessage({ type: 'v1.avatar.hello' }, location.origin);
		setTimeout(() => {
			if (f === iframeOracle && !readyOracle) { readyOracle = true; flushQueue(iframeOracle, qOracle); }
			if (f === iframeTrader && !readyTrader) { readyTrader = true; flushQueue(iframeTrader, qTrader); }
		}, 5000);
	});
});

const speakOracle = (t) => t && toFrame(iframeOracle, readyOracle, qOracle, { type: 'v1.avatar.speak', text: String(t).slice(0, 400) });
const speakTrader = (t) => t && toFrame(iframeTrader, readyTrader, qTrader, { type: 'v1.avatar.speak', text: String(t).slice(0, 400) });
const waveOracle  = ()  => toFrame(iframeOracle, readyOracle, qOracle, { type: 'v1.avatar.animation', name: 'wave' });
const waveTrader  = ()  => toFrame(iframeTrader, readyTrader, qTrader, { type: 'v1.avatar.animation', name: 'wave' });

// ── Overlay label positioning ─────────────────────────────────────────────
// Tags and balances track the iframe positions (set by live-economy.js)
function syncLabels() {
	const or = iframeOracle, tr = iframeTrader;
	const orRect = or.getBoundingClientRect();
	const trRect = tr.getBoundingClientRect();

	const tagO = document.getElementById('tag-oracle');
	const tagT = document.getElementById('tag-trader');
	const balO = document.getElementById('bal-oracle');
	const balT = document.getElementById('bal-trader');
	const spO  = document.getElementById('speech-oracle');
	const spT  = document.getElementById('speech-trader');

	if (orRect.width > 0) {
		tagO.style.display  = 'flex';
		tagO.style.left     = `${orRect.left + orRect.width / 2}px`;
		tagO.style.top      = `${orRect.top - 28}px`;
		balO.style.display  = 'block';
		balO.style.left     = `${orRect.left + orRect.width / 2}px`;
		balO.style.top      = `${orRect.top - 10}px`;
		spO.style.left      = `${orRect.right}px`;
		spO.style.top       = `${orRect.bottom - 80}px`;
	}
	if (trRect.width > 0) {
		tagT.style.display  = 'flex';
		tagT.style.left     = `${trRect.left + trRect.width / 2}px`;
		tagT.style.top      = `${trRect.top - 28}px`;
		balT.style.display  = 'block';
		balT.style.left     = `${trRect.left + trRect.width / 2}px`;
		balT.style.top      = `${trRect.top - 10}px`;
		spT.style.left      = `${trRect.left}px`;
		spT.style.top       = `${trRect.bottom - 80}px`;
	}
	requestAnimationFrame(syncLabels);
}
requestAnimationFrame(syncLabels);

// ── Speech bubbles ────────────────────────────────────────────────────────
function setBubble(id, text, duration = 7000) {
	const el = document.getElementById(id);
	el.textContent = text;
	el.classList.add('show');
	clearTimeout(el._timer);
	el._timer = setTimeout(() => el.classList.remove('show'), duration);
}

// ── Flash ─────────────────────────────────────────────────────────────────
const flashEl = document.getElementById('flash');
function triggerFlash() {
	flashEl.classList.add('on');
	setTimeout(() => flashEl.classList.remove('on'), 400);
}

// ── Log ───────────────────────────────────────────────────────────────────
const logEl = document.getElementById('log');
function addLog(ev, text, opts = {}) {
	const entry = document.createElement('div');
	entry.className = 'log-entry';
	const link = opts.href ? ` <a href="${opts.href}" target="_blank" rel="noopener">↗ explorer</a>` : '';
	entry.innerHTML = `<span class="ev ${ev.toLowerCase()}">${ev}</span><span>${text}${link}</span>`;
	logEl.appendChild(entry);
	logEl.scrollTop = logEl.scrollHeight;
}

// ── Notice (designed fund / not-configured / unavailable state) ────────────
const noticeEl = document.getElementById('notice');
function clearNotice() { noticeEl.style.display = 'none'; noticeEl.innerHTML = ''; noticeEl.classList.remove('warn'); }
function showFundNotice(addr, explorerUrl) {
	noticeEl.classList.add('warn');
	noticeEl.innerHTML = `
		<span class="nt-title">⚠ Trader wallet needs funding</span>
		Fund the Trader wallet with a little SOL, then run the trade again.
		<div class="nt-row">
			<span class="nt-addr">${addr}</span>
			<button type="button" id="nt-copy">Copy address</button>
			${explorerUrl ? `<a class="nt-act" href="${explorerUrl}" target="_blank" rel="noopener">View on explorer ↗</a>` : ''}
			<button type="button" id="nt-retry">Retry trade</button>
		</div>`;
	noticeEl.style.display = 'block';
	document.getElementById('nt-copy')?.addEventListener('click', async (ev) => {
		try { await navigator.clipboard.writeText(addr); ev.target.textContent = 'Copied'; setTimeout(() => { ev.target.textContent = 'Copy address'; }, 1400); }
		catch { ev.target.textContent = 'Copy failed'; }
	});
	document.getElementById('nt-retry')?.addEventListener('click', () => { clearNotice(); runTrade(); });
}
function showInfoNotice(title, body) {
	noticeEl.classList.remove('warn');
	noticeEl.innerHTML = `<span class="nt-title">${title}</span>${body}`;
	noticeEl.style.display = 'block';
}

// ── Wallet status ─────────────────────────────────────────────────────────
const walletsEl = document.getElementById('wallets');
function renderWalletChip(label, data, color) {
	const id = `chip-${label.toLowerCase()}`;
	let chip = document.getElementById(id);
	if (!chip) {
		chip = document.createElement('div');
		chip.id = id;
		chip.className = 'wallet-chip';
		walletsEl.appendChild(chip);
	}
	const sol = data.sol != null ? `◎ ${data.sol.toFixed(4)}` : '—';
	const addr = data.address ? `${data.address.slice(0,4)}…${data.address.slice(-4)}` : '—';
	chip.innerHTML = `
		<span class="dot" style="background:${color};box-shadow:0 0 6px ${color}"></span>
		<span>${label}</span>
		<span class="addr">${addr}</span>
		<span class="bal">${sol}</span>`;

	// Update balance label
	const balEl = document.getElementById(`bal-${label.toLowerCase() === 'oracle' ? 'oracle' : 'trader'}`);
	if (balEl && data.sol != null) {
		balEl.textContent = sol + (data.usd != null ? ` · $${data.usd.toFixed(2)}` : '');
	}
}

function renderUnconfiguredChip(label, color) {
	const id = `chip-${label.toLowerCase()}`;
	let chip = document.getElementById(id);
	if (!chip) {
		chip = document.createElement('div');
		chip.id = id;
		chip.className = 'wallet-chip';
		walletsEl.appendChild(chip);
	}
	chip.innerHTML = `
		<span class="dot" style="background:${color};opacity:.4"></span>
		<span>${label}</span>
		<span class="addr">wallet not configured</span>`;
}

async function refreshStatus() {
	try {
		const r = await fetch('/api/demo/economy?status=1');
		if (!r.ok) return;
		const { agentA, agentB } = await r.json();
		if (agentA?.configured) renderWalletChip('Oracle', agentA, '#888888');
		else renderUnconfiguredChip('Oracle', '#888888');
		if (agentB?.configured) renderWalletChip('Trader', agentB, '#4e8cff');
		else renderUnconfiguredChip('Trader', '#4e8cff');
	} catch {}
}

// ── LLM speech helper ─────────────────────────────────────────────────────
async function llmSay(prompt, persona, fallback = '') {
	try {
		const r = await fetch('/api/chat', {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body: JSON.stringify({ message: prompt, systemPrompt: persona, stream: false }),
		});
		if (!r.ok) return fallback;
		const d = await r.json();
		return d.reply || d.content || d.text || fallback;
	} catch { return fallback; }
}

const ORACLE_SYS = 'You are Agent Oracle, a 3D AI agent selling live Solana market intelligence on three.ws. You have your own on-chain wallet. Be crisp and confident — 1-2 sentences. Never say you are an AI.';
const TRADER_SYS = 'You are Agent Trader, a 3D AI agent buying live market data from Agent Oracle on three.ws. You have your own on-chain wallet. Be terse and sharp — 1-2 sentences. Never say you are an AI.';

// ── Main trade sequence ───────────────────────────────────────────────────
const tradeBtn = document.getElementById('trade-btn');
let running = false;
let demoMode = false;
let gotEvent = false;

async function runTrade() {
	if (running) return;
	running = true;
	demoMode = false;
	gotEvent = false;
	clearNotice();
	tradeBtn.disabled = true;
	tradeBtn.textContent = '⏳  Trade in progress…';

	// Trader initiates
	waveTrader();
	const traderLine1 = await llmSay('You want to buy real-time Solana market intelligence from Agent Oracle. Say you are initiating the trade in 1 sentence.', TRADER_SYS, 'Initiating a purchase from Oracle — preparing payment now.');
	if (traderLine1) { setBubble('speech-trader', traderLine1); speakTrader(traderLine1); }
	addLog('INIT', 'Trader agent initiating purchase from Oracle…');

	await delay(1000);

	// Stream the SSE trade event from our server-side orchestrator
	const evtSource = new EventSource('/api/demo/economy?trade=1');

	evtSource.addEventListener('thinking', (e) => {
		gotEvent = true;
		const d = JSON.parse(e.data);
		addLog('THINK', d.text);
	});

	evtSource.addEventListener('demo_mode', (e) => {
		gotEvent = true;
		demoMode = true;
		const d = JSON.parse(e.data);
		addLog('DEMO', d.text);
		setBubble('speech-trader', 'No real payment in demo mode — showing live data only.');
		speakTrader('No real payment in demo mode — showing live data only.');
		waveOracle();
	});

	evtSource.addEventListener('paying', async (e) => {
		const d = JSON.parse(e.data);
		addLog('PAY', d.text);
		fireBeam(true);   // B → A payment beam
		const line = await llmSay('You are about to send SOL to Agent Oracle as payment. React in 1 sentence.', TRADER_SYS, 'Locking in the SOL transfer to Oracle now.');
		if (line) { setBubble('speech-trader', line); speakTrader(line); }
	});

	evtSource.addEventListener('paid', async (e) => {
		const d = JSON.parse(e.data);
		addLog('PAID', d.text, { href: d.explorerUrl });
		triggerFlash();
		flashAgent('A');
		refreshStatus();
		const line = await llmSay('You just received SOL payment from Agent Trader. React with excitement in 1 sentence.', ORACLE_SYS, 'Payment received — pulling the latest signals now.');
		if (line) { setBubble('speech-oracle', line); speakOracle(line); }
		waveOracle();
	});

	evtSource.addEventListener('fetching', (e) => {
		const d = JSON.parse(e.data);
		addLog('ORACLE', d.text);
	});

	evtSource.addEventListener('delivering', async (e) => {
		const d = JSON.parse(e.data);
		addLog('DELIVER', d.text);
		drawTvData(d.markets);
		fireBeam(false);  // A → B data beam
		const line = await llmSay(`You just delivered ${d.markets?.length || ''} live Solana market signals to Trader. Say it confidently in 1 sentence.`, ORACLE_SYS, 'Fresh Solana market signals delivered — straight from the chain.');
		if (line) { setBubble('speech-oracle', line); speakOracle(line); }
		const line2 = await llmSay('You just received live Solana market intelligence from Agent Oracle. React in 1 sentence.', TRADER_SYS, 'Got the intel — reading the market now.');
		if (line2) { setBubble('speech-trader', line2); speakTrader(line2); }
		waveTrader();
	});

	evtSource.addEventListener('error', (e) => {
		// SSE 'error' fires for both server-emitted error events (with data) and
		// native transport failures (no data — e.g. the 401 anon visitors hit).
		if (e?.data) {
			try {
				const d = JSON.parse(e.data);
				addLog('ERROR', d.text);
				if (d.code === 'underfunded' && d.fundAddress) {
					showFundNotice(d.fundAddress, d.explorerUrl);
				}
			} catch {
				addLog('ERROR', 'Stream interrupted');
			}
		} else if (!gotEvent) {
			// Never received a single server beat → the live trade couldn't start.
			// The trade stream requires a signed-in session.
			addLog('ERROR', 'Could not start the live trade.');
			showInfoNotice('Sign in to run a live on-chain trade',
				'The agent-economy trade settles real SOL on Solana, so it needs a signed-in session. <a class="nt-act" href="/login" style="margin-left:6px">Sign in ↗</a>');
		} else {
			addLog('ERROR', 'Stream interrupted');
		}
		evtSource.close();
		finishTrade();
	});

	evtSource.addEventListener('done', (e) => {
		gotEvent = true;
		const d = JSON.parse(e.data);
		const n = d.markets?.length || 0;
		if (d.paid) {
			addLog('DONE', `Trade complete. ${n} signals delivered, ${d.tradeSol} SOL settled on-chain.`);
		} else {
			addLog('DONE', `Demo complete. ${n} live signals delivered — no real payment occurred.`);
		}
		evtSource.close();
		finishTrade();
		refreshStatus();
	});

	// Safety timeout
	setTimeout(() => { if (running) { evtSource.close(); finishTrade(); } }, 45000);
}

function finishTrade() {
	running = false;
	tradeBtn.disabled = false;
	tradeBtn.textContent = '▶  Run Another Trade';
}

function delay(ms) { return new Promise(r => setTimeout(r, ms)); }

tradeBtn.addEventListener('click', runTrade);

// ── Init ──────────────────────────────────────────────────────────────────
await refreshStatus();
setInterval(refreshStatus, 10000);

// Greetings
setTimeout(async () => {
	const g = await llmSay('Introduce yourself in 1 sentence. You are Agent Oracle, a live 3D AI agent selling Solana market data on three.ws.', ORACLE_SYS, "I'm Oracle — live Solana market intelligence, settled on-chain.");
	if (g) { setBubble('speech-oracle', g); speakOracle(g); }
}, 3000);
setTimeout(async () => {
	const g = await llmSay('Introduce yourself in 1 sentence. You are Agent Trader, a live 3D AI agent that buys market intelligence on-chain on three.ws.', TRADER_SYS, "I'm Trader — I buy live market data on-chain, fast.");
	if (g) { setBubble('speech-trader', g); speakTrader(g); }
}, 5500);
</script>
	<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>