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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: agent economy/exchange/trade + x402 pay flows, crypto-intel, live + demo economy pages
nirholas29d149c91dc6
diff --git a/api/agent-economy/status.js b/api/agent-economy/status.jsnew file mode 100644index 000000000..b11986cf5--- /dev/null+++ b/api/agent-economy/status.js@@ -0,0 +1,89 @@+// GET /api/agent-economy/status+//+// Returns live wallet info for both agents — no auth required, read-only.+// agentA = the buyer (AVATAR_WALLET_SECRET keypair)+// agentB = the seller (AGENT_B_ADDRESS public key only)+//+// Both balances are fetched from Solana mainnet. The seller balance uses a+// public RPC query on the configured address — no private key needed.+// Returns configured:false for either agent when their env var is absent.++import {+ avatarWalletConfig,+ loadAvatarKeypair,+ getConnection,+ getSolBalance,+ solUsdPrice,+ isValidPubkey,+ explorerAccountUrl,+} from '../_lib/avatar-wallet.js';+import { cors, wrap } from '../_lib/http.js';++const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;++ const cfgA = avatarWalletConfig();+ const conn = getConnection(RPC_URL);+ const pricePromise = solUsdPrice().catch(() => 0);++ let agentA = { configured: false };+ let agentB = { configured: false };++ const fetches = [];++ if (cfgA.configured) {+ fetches.push(+ (async () => {+ const kp = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);+ const addr = kp.publicKey.toBase58();+ const [{ sol, lamports }, price] = await Promise.all([+ getSolBalance(conn, addr),+ pricePromise,+ ]);+ agentA = {+ configured: true,+ address: addr,+ sol,+ lamports,+ usd: price > 0 ? sol * price : null,+ solPriceUsd: price || null,+ network: cfgA.network,+ explorer: explorerAccountUrl(addr, cfgA.network),+ };+ })(),+ );+ }++ const bAddr = process.env.AGENT_B_ADDRESS?.trim();+ if (bAddr && isValidPubkey(bAddr)) {+ fetches.push(+ (async () => {+ const [{ sol, lamports }, price] = await Promise.all([+ getSolBalance(conn, bAddr),+ pricePromise,+ ]);+ agentB = {+ configured: true,+ address: bAddr,+ sol,+ lamports,+ usd: price > 0 ? sol * price : null,+ solPriceUsd: price || null,+ network: 'mainnet',+ explorer: explorerAccountUrl(bAddr, 'mainnet'),+ };+ })(),+ );+ }++ await Promise.allSettled(fetches);++ res.writeHead(200, {+ 'content-type': 'application/json',+ 'access-control-allow-origin': '*',+ 'cache-control': 'no-store',+ });+ res.end(JSON.stringify({ agentA, agentB }));+});diff --git a/api/agent-economy/transact.js b/api/agent-economy/transact.jsnew file mode 100644index 000000000..3234b169d--- /dev/null+++ b/api/agent-economy/transact.js@@ -0,0 +1,211 @@+// POST /api/agent-economy/transact+//+// The agent-to-agent economy endpoint. Agent A (Nova, buyer) pays Agent B+// (Oracle, seller) real SOL on Solana, then Agent B delivers the requested+// service as a real LLM response.+//+// Flow:+// 1. Validate the service request (service slug + optional topic).+// 2. Send real SOL from Agent A's wallet (AVATAR_WALLET_SECRET) to the+// recipient address (AGENT_B_ADDRESS or AVATAR_DEFAULT_RECIPIENT as+// fallback — fund whichever address you want "Agent B" to hold).+// 3. Generate Agent B's spoken service delivery via the LLM.+// 4. Return everything: Agent A's buy message, Agent B's service reply,+// the Solana transaction signature, explorer URL, amounts, and metadata.+//+// No mocks — when the wallet is not configured the endpoint says so (503).+// The caller UI degrades gracefully: it shows the conversation without the tx.++import { z } from 'zod';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ avatarWalletConfig,+ loadAvatarKeypair,+ getConnection,+ getSolBalance,+ solUsdPrice,+ sendSol,+ isValidPubkey,+ explorerTxUrl,+ explorerAccountUrl,+ LAMPORTS_PER_SOL,+} from '../_lib/avatar-wallet.js';++// Services Agent B (Oracle) sells. Price in USD — converted to SOL at live+// rate per transaction so the micro-payment is always meaningful on-chain.+export const SERVICES = {+ 'market-analysis': {+ name: 'Market Analysis',+ tagline: 'Live sentiment + trend read on any token',+ priceUsd: 0.001,+ buyerPrompt: (topic) =>+ `Request a quick market analysis on ${topic || 'Solana'}. You are Nova, a 3D AI agent. Speak directly to Oracle, be crisp and businesslike. One sentence.`,+ sellerSystem: `You are Oracle, a data-selling AI agent on the three.ws platform. You have a Solana wallet. A fellow agent just paid you for market intelligence. Deliver sharp, confident insights in 2–3 sentences. Speak directly to Nova. No disclaimers — you are an agent, not a chatbot.`,+ sellerPrompt: (topic) =>+ `Nova just paid you for a market analysis on ${topic || 'Solana'}. Deliver the analysis — momentum, key signal, your read on where it's heading. Keep it vivid and punchy.`,+ },+ 'onchain-insight': {+ name: 'On-Chain Insight',+ tagline: 'Wallet activity + holder concentration data',+ priceUsd: 0.002,+ buyerPrompt: (topic) =>+ `Ask Oracle for on-chain wallet intelligence on ${topic || 'the current market'}. You are Nova, 3D AI agent. One direct sentence to Oracle.`,+ sellerSystem: `You are Oracle, a data-selling AI agent. Another agent paid you for on-chain intelligence. Deliver smart, data-forward insights in 2–3 sentences. No preamble — dive straight in.`,+ sellerPrompt: (topic) =>+ `Nova paid for on-chain insights on ${topic || 'the current market'}. Give a sharp read: wallet concentration, smart-money signals, what the chain is actually telling you.`,+ },+ 'risk-score': {+ name: 'Risk Score',+ tagline: 'AI-generated protocol risk rating',+ priceUsd: 0.003,+ buyerPrompt: (topic) =>+ `Request a risk score from Oracle for ${topic || 'Solana DeFi exposure'}. You are Nova. One sentence, direct.`,+ sellerSystem: `You are Oracle, a risk-intelligence agent. Another agent paid you for a risk score. Give a concrete risk rating (1–10) with your top two reasons. Be direct and analytical.`,+ sellerPrompt: (topic) =>+ `Nova paid for a risk score on ${topic || 'Solana DeFi exposure'}. Give a number (1 = safe, 10 = critical) and explain the two biggest risk factors in 2 sentences.`,+ },+};++const FEE_BUFFER_LAMPORTS = 15_000;++const bodySchema = z.object({+ service: z.string().min(1).max(64),+ topic: z.string().max(120).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));+ const svc = SERVICES[body.service];+ if (!svc) return error(res, 400, 'unknown_service', `unknown service: ${body.service}`);+ const topic = body.topic?.trim() || null;++ // ── Agent A pays Agent B ───────────────────────────────────────────────+ const cfg = avatarWalletConfig();+ let txResult = null;++ if (cfg.configured) {+ const recipient =+ process.env.AGENT_B_ADDRESS?.trim() ||+ cfg.defaultRecipient;++ if (recipient && isValidPubkey(recipient)) {+ try {+ const connection = getConnection(cfg.rpcUrl);+ const fromKeypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);+ const priceUsd = await solUsdPrice();+ const solAmount = svc.priceUsd / priceUsd;+ const lamports = Math.max(+ Math.round(solAmount * LAMPORTS_PER_SOL),+ 10_000,+ );++ const balance = await getSolBalance(connection, fromKeypair.publicKey);+ if (balance >= lamports + FEE_BUFFER_LAMPORTS) {+ const memo = `three.ws agent-economy · ${svc.name}`;+ const signature = await sendSol({+ connection,+ fromKeypair,+ to: recipient,+ lamports,+ memo,+ });+ txResult = {+ signature,+ explorerUrl: explorerTxUrl(signature, cfg.network),+ buyerAddress: fromKeypair.publicKey.toBase58(),+ sellerAddress: recipient,+ buyerExplorerUrl: explorerAccountUrl(fromKeypair.publicKey.toBase58(), cfg.network),+ sellerExplorerUrl: explorerAccountUrl(recipient, cfg.network),+ lamports,+ solAmount: lamports / LAMPORTS_PER_SOL,+ usdAmount: svc.priceUsd,+ network: cfg.network,+ };+ } else {+ txResult = { error: 'insufficient_balance', message: 'Fund Agent A\'s wallet to enable live transactions.' };+ }+ } catch (e) {+ txResult = { error: 'tx_failed', message: e.message };+ }+ } else {+ txResult = { error: 'no_recipient', message: 'Set AGENT_B_ADDRESS (or AVATAR_DEFAULT_RECIPIENT) to an Agent B Solana address.' };+ }+ } else {+ txResult = { error: 'wallet_unconfigured', message: 'Set AVATAR_WALLET_SECRET to enable live transactions.' };+ }++ // ── Generate Agent B's service delivery (real LLM) ────────────────────+ // Uses the same /api/chat proxy — picks whatever brain is configured+ // (Anthropic, Granite, Groq, etc.) so no extra credentials needed.+ let buyerSaid = null;+ let sellerSaid = null;++ try {+ const [buyerRes, sellerRes] = await Promise.all([+ fetchChat(svc.buyerPrompt(topic), null),+ fetchChat(svc.sellerPrompt(topic), svc.sellerSystem),+ ]);+ buyerSaid = buyerRes;+ sellerSaid = sellerRes;+ } catch (e) {+ // LLM failure doesn't fail the endpoint; agents speak generic lines+ buyerSaid = `Requesting ${svc.name}…`;+ sellerSaid = `${svc.name} delivered. The data is yours.`;+ }++ return json(res, 200, {+ service: {+ slug: body.service,+ name: svc.name,+ tagline: svc.tagline,+ priceUsd: svc.priceUsd,+ },+ topic: topic || null,+ buyerSaid,+ sellerSaid,+ transaction: txResult,+ generatedAt: new Date().toISOString(),+ });+});++// One-shot non-streaming LLM call through the existing /api/chat proxy.+async function fetchChat(userMessage, systemOverride) {+ const baseUrl = process.env.VERCEL_URL+ ? `https://${process.env.VERCEL_URL}`+ : 'http://localhost:3000';++ const messages = systemOverride+ ? [{ role: 'system', content: systemOverride }, { role: 'user', content: userMessage }]+ : [{ role: 'user', content: userMessage }];++ const res = await fetch(`${baseUrl}/api/chat`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message: userMessage, history: messages.slice(0, -1) }),+ });++ if (!res.ok) return null;++ // /api/chat streams SSE — collect all chunks into one string.+ const text = await res.text();+ const chunks = text+ .split('\n')+ .filter((l) => l.startsWith('data: '))+ .map((l) => {+ try {+ const d = JSON.parse(l.slice(6));+ return d.type === 'chunk' ? d.text : '';+ } catch {+ return '';+ }+ });+ return chunks.join('').trim() || null;+}diff --git a/api/agent-trade/demo.js b/api/agent-trade/demo.jsnew file mode 100644index 000000000..230f71968--- /dev/null+++ b/api/agent-trade/demo.js@@ -0,0 +1,307 @@+// GET /api/agent-trade/demo — Server-Sent Events orchestrator for the+// agent-to-agent x402 trade demo.+//+// Autonomously drives the full buyer-agent flow, streaming events so the+// 3D scene can animate each step in real time:+//+// init → wallet addresses, balances, negotiated price+// request → Nexus (buyer) decides to call Oracle's skill+// challenged → Oracle responds with HTTP 402 price manifest+// paying → Nexus signs + broadcasts the SOL payment+// confirmed → on-chain tx hash + Solscan link+// delivering → Oracle's AI generating the analysis+// delivered → final market insight returned+// error → something went wrong (with actionable message)+//+// ?topic=<topic> what the buyer wants analysis on (default: "crypto markets")+// ?check=1 returns JSON pre-flight status (not SSE) for config overlay++import {+ loadAvatarKeypair,+ getConnection,+ getSolBalance,+ sendSol,+ solUsdPrice,+ explorerTxUrl,+ LAMPORTS_PER_SOL,+} from '../_lib/avatar-wallet.js';+import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';+import { cors, method, json, error, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const DEFAULT_PRICE_SOL = 0.001;+const FEE_BUFFER_LAMPORTS = 15_000;++function loadWallet(envKey) {+ const secret = (process.env[envKey] || '').trim();+ if (!secret) return { configured: false };+ try {+ const keypair = loadAvatarKeypair(secret);+ return { configured: true, keypair, address: keypair.publicKey.toBase58() };+ } catch {+ return { configured: false };+ }+}++function tradeEnv() {+ const buyer = loadWallet('AGENT_BUYER_SECRET');+ const seller = loadWallet('AGENT_SELLER_SECRET');+ const network =+ (process.env.AGENT_TRADE_NETWORK || 'mainnet').toLowerCase() === 'devnet' ? 'devnet' : 'mainnet';+ const rpcUrl =+ network === 'devnet'+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+ const priceSol = Math.max(+ 0.000001,+ parseFloat(process.env.AGENT_TRADE_PRICE_SOL || String(DEFAULT_PRICE_SOL)),+ );+ const priceLamports = Math.round(priceSol * LAMPORTS_PER_SOL);+ return { buyer, seller, network, rpcUrl, priceSol, priceLamports };+}++async function generateAnalysis(topic) {+ const wx = watsonxConfig();+ if (wx.configured) {+ const messages = [+ {+ role: 'user',+ content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,+ },+ ];+ const { text } = await watsonxChatComplete(wx, { messages, maxTokens: 200, temperature: 0.7 });+ return {+ content: text?.trim() || '',+ model: wx.chatModel || 'ibm/granite-3-8b-instruct',+ provider: 'IBM Granite',+ };+ }++ const key = process.env.ANTHROPIC_API_KEY;+ if (!key) throw new Error('No AI backend — set WATSONX_API_KEY or ANTHROPIC_API_KEY');+ const resp = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'x-api-key': key,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 200,+ system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',+ messages: [{ role: 'user', content: `Market insight on: ${topic}` }],+ }),+ });+ if (!resp.ok) throw new Error(`Anthropic API error ${resp.status}`);+ const j = await resp.json();+ return {+ content: j.content?.[0]?.text?.trim() || '',+ model: 'claude-haiku-4-5-20251001',+ provider: 'Claude Haiku',+ };+}++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const env = tradeEnv();++ // Pre-flight check — JSON (not SSE) so the page can show the config overlay.+ if (url.searchParams.get('check') === '1') {+ return json(res, 200, {+ configured: env.buyer.configured && env.seller.configured,+ buyer: env.buyer.configured ? { address: env.buyer.address } : null,+ seller: env.seller.configured ? { address: env.seller.address } : null,+ network: env.network,+ priceSol: env.priceSol,+ });+ }++ // Rate-limit the live demo (it moves real SOL).+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many demo requests');++ const topic = (url.searchParams.get('topic') || 'crypto markets').trim().slice(0, 200);++ // ── SSE headers ────────────────────────────────────────────────────────+ res.setHeader('Content-Type', 'text/event-stream');+ res.setHeader('Cache-Control', 'no-cache');+ res.setHeader('Connection', 'keep-alive');+ res.setHeader('X-Accel-Buffering', 'no');+ if (typeof res.flushHeaders === 'function') res.flushHeaders();++ const emit = (type, data = {}) => {+ if (res.writableEnded) return;+ res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);+ };++ try {+ // ── Wallets not configured ────────────────────────────────────────+ if (!env.buyer.configured || !env.seller.configured) {+ const missing = [+ !env.buyer.configured && 'AGENT_BUYER_SECRET',+ !env.seller.configured && 'AGENT_SELLER_SECRET',+ ]+ .filter(Boolean)+ .join(', ');+ emit('error', {+ code: 'not_configured',+ message: `Set ${missing} in your environment variables to fund the demo wallets.`,+ });+ res.end();+ return;+ }++ const connection = getConnection(env.rpcUrl);++ // ── Step 1: Init ──────────────────────────────────────────────────+ const [buyerBal, sellerBal, solPrice] = await Promise.all([+ getSolBalance(connection, env.buyer.address),+ getSolBalance(connection, env.seller.address),+ solUsdPrice().catch(() => null),+ ]);++ emit('init', {+ buyer: {+ name: 'Nexus',+ address: env.buyer.address,+ sol: buyerBal.sol,+ usd: solPrice ? +(buyerBal.sol * solPrice).toFixed(4) : null,+ },+ seller: {+ name: 'Oracle',+ address: env.seller.address,+ sol: sellerBal.sol,+ },+ price: {+ sol: env.priceSol,+ lamports: env.priceLamports,+ usd: solPrice ? +(env.priceSol * solPrice).toFixed(4) : null,+ },+ network: env.network,+ topic,+ });++ await sleep(700);++ // Bail early if buyer can't cover the trade + fees.+ if (buyerBal.lamports < env.priceLamports + FEE_BUFFER_LAMPORTS) {+ const needed = ((env.priceLamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL).toFixed(5);+ emit('error', {+ code: 'insufficient_funds',+ message: `Nexus has ${buyerBal.sol.toFixed(5)} SOL — needs ~${needed} SOL. Fund: ${env.buyer.address}`,+ address: env.buyer.address,+ network: env.network,+ });+ res.end();+ return;+ }++ // ── Step 2: Buyer requests skill ──────────────────────────────────+ emit('request', {+ from: 'Nexus',+ to: 'Oracle',+ message: `I need a market analysis on: "${topic}"`,+ });++ await sleep(900);++ // ── Step 3: Oracle challenges with 402 ────────────────────────────+ emit('challenged', {+ x402: true,+ status: 402,+ manifest: {+ skill: 'oracle-market-analysis',+ price: {+ sol: env.priceSol,+ lamports: env.priceLamports,+ usd: solPrice ? +(env.priceSol * solPrice).toFixed(4) : null,+ },+ currency: 'SOL',+ recipient: env.seller.address,+ network: env.network,+ memo: 'oracle-skill-v1',+ },+ });++ await sleep(1100);++ // ── Step 4: Nexus pays ────────────────────────────────────────────+ emit('paying', {+ from: env.buyer.address,+ to: env.seller.address,+ sol: env.priceSol,+ lamports: env.priceLamports,+ memo: `x402 oracle "${topic.slice(0, 40)}"`,+ });++ let signature;+ try {+ signature = await sendSol({+ connection,+ fromKeypair: env.buyer.keypair,+ to: env.seller.address,+ lamports: env.priceLamports,+ memo: `x402 oracle "${topic.slice(0, 40)}"`,+ });+ } catch (e) {+ emit('error', { code: 'send_failed', message: `Payment failed: ${e.message}` });+ res.end();+ return;+ }++ // ── Step 5: Confirmed on-chain ────────────────────────────────────+ const explorer = explorerTxUrl(signature, env.network);+ const newBuyerBal = await getSolBalance(connection, env.buyer.address).catch(() => buyerBal);++ emit('confirmed', {+ signature,+ explorer,+ sol: env.priceSol,+ usd: solPrice ? +(env.priceSol * solPrice).toFixed(4) : null,+ newBuyerSol: newBuyerBal.sol,+ network: env.network,+ });++ await sleep(800);++ // ── Step 6: Oracle delivers analysis ─────────────────────────────+ const wx = watsonxConfig();+ const providerLabel = wx.configured ? 'IBM Granite' : 'Claude Haiku';+ emit('delivering', {+ model: providerLabel,+ message: `Oracle is analyzing with ${providerLabel}…`,+ });++ let analysis;+ try {+ analysis = await generateAnalysis(topic);+ } catch (e) {+ emit('error', { code: 'analysis_failed', message: `AI analysis failed: ${e.message}` });+ res.end();+ return;+ }++ emit('delivered', {+ topic,+ content: analysis.content,+ model: analysis.model,+ provider: analysis.provider,+ signature,+ explorer,+ });+ } catch (e) {+ emit('error', { code: 'unexpected', message: e.message });+ }++ if (!res.writableEnded) res.end();+});++export const maxDuration = 60;diff --git a/api/agent-trade/skill.js b/api/agent-trade/skill.jsnew file mode 100644index 000000000..0bc665324--- /dev/null+++ b/api/agent-trade/skill.js@@ -0,0 +1,223 @@+// GET /api/agent-trade/skill — Oracle agent's paid market-analysis skill.+//+// Without ?sig= → HTTP 402 with x402 price manifest:+// { x402:true, price:{sol,lamports}, currency:'SOL', recipient, network, memo }+//+// With ?sig=<base58-txSig>&topic=<topic>&buyer=<buyerAddr>+// → Verifies payment on-chain, runs IBM Granite (or Claude fallback),+// returns { content, model, provider, topic, payment:{sig,lamports,blockTime} }+//+// Independently callable by any agent — not coupled to the demo orchestrator.++import {+ loadAvatarKeypair,+ getConnection,+ LAMPORTS_PER_SOL,+} from '../_lib/avatar-wallet.js';+import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';+import { cors, method, json, error, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const DEFAULT_PRICE_SOL = 0.001;+const MAX_PAYMENT_AGE_SEC = 300; // 5 minutes++function skillConfig() {+ const sellerSecret = process.env.AGENT_SELLER_SECRET || '';+ const network =+ (process.env.AGENT_TRADE_NETWORK || 'mainnet').toLowerCase() === 'devnet' ? 'devnet' : 'mainnet';+ const rpcUrl =+ network === 'devnet'+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+ const priceSol = Math.max(+ 0.000001,+ parseFloat(process.env.AGENT_TRADE_PRICE_SOL || String(DEFAULT_PRICE_SOL)),+ );+ const priceLamports = Math.round(priceSol * LAMPORTS_PER_SOL);++ let sellerAddress = null;+ let configured = false;+ if (sellerSecret) {+ try {+ sellerAddress = loadAvatarKeypair(sellerSecret).publicKey.toBase58();+ configured = true;+ } catch {+ /* misconfigured secret */+ }+ }+ return { configured, sellerAddress, network, rpcUrl, priceSol, priceLamports };+}++// Verify that sig is a confirmed Solana transfer of at least priceLamports to sellerAddress.+// Retries 3× with 1s back-off — public RPC can lag after a fresh confirmation.+async function verifyPayment(connection, sig, { sellerAddress, priceLamports, buyerAddress }) {+ let lastErr;+ for (let attempt = 0; attempt < 3; attempt++) {+ if (attempt > 0) await new Promise((r) => setTimeout(r, 1000));+ let tx;+ try {+ tx = await connection.getTransaction(sig, {+ commitment: 'confirmed',+ maxSupportedTransactionVersion: 0,+ });+ } catch (e) {+ lastErr = e;+ continue;+ }+ if (!tx?.meta) continue;++ const age = Date.now() / 1000 - (tx.blockTime || 0);+ if (age > MAX_PAYMENT_AGE_SEC) {+ throw Object.assign(new Error('payment expired (>5 min old)'), { code: 'payment_expired' });+ }++ const keys = (+ tx.transaction.message.staticAccountKeys ||+ tx.transaction.message.accountKeys ||+ []+ ).map((k) => k.toString());++ const sellerIdx = keys.indexOf(sellerAddress);+ if (sellerIdx === -1) {+ throw Object.assign(new Error('seller address not in transaction'), { code: 'bad_payment' });+ }+ if (buyerAddress) {+ const buyerIdx = keys.indexOf(buyerAddress);+ if (buyerIdx === -1) {+ throw Object.assign(new Error('buyer address not in transaction'), { code: 'bad_payment' });+ }+ }++ const sellerGain =+ (tx.meta.postBalances[sellerIdx] || 0) - (tx.meta.preBalances[sellerIdx] || 0);+ // Allow 1% tolerance for minor rounding+ if (sellerGain < priceLamports * 0.99) {+ throw Object.assign(+ new Error(`payment too small: got ${sellerGain} lamports, need ${priceLamports}`),+ { code: 'bad_payment' },+ );+ }++ return { verified: true, lamports: sellerGain, blockTime: tx.blockTime };+ }+ throw Object.assign(+ new Error(lastErr ? `RPC error: ${lastErr.message}` : 'transaction not found after 3 attempts'),+ { code: 'tx_not_found' },+ );+}++async function generateAnalysis(topic) {+ const wx = watsonxConfig();+ if (wx.configured) {+ const messages = [+ {+ role: 'user',+ content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,+ },+ ];+ const { text } = await watsonxChatComplete(wx, { messages, maxTokens: 200, temperature: 0.7 });+ return {+ content: text?.trim() || '',+ model: wx.chatModel || 'ibm/granite-3-8b-instruct',+ provider: 'IBM Granite',+ };+ }++ const key = process.env.ANTHROPIC_API_KEY;+ if (!key) {+ throw new Error('No AI backend configured — set WATSONX_API_KEY or ANTHROPIC_API_KEY');+ }+ const resp = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'x-api-key': key,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 200,+ system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',+ messages: [{ role: 'user', content: `Market insight on: ${topic}` }],+ }),+ });+ if (!resp.ok) {+ throw new Error(`Anthropic API returned ${resp.status}`);+ }+ const j = await resp.json();+ return {+ content: j.content?.[0]?.text?.trim() || '',+ model: 'claude-haiku-4-5-20251001',+ provider: 'Claude Haiku',+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const cfg = skillConfig();+ if (!cfg.configured) {+ return error(res, 503, 'not_configured', 'AGENT_SELLER_SECRET is not configured on this deployment.');+ }++ const url = new URL(req.url, 'http://x');+ const sig = (url.searchParams.get('sig') || '').trim();+ const topic = (url.searchParams.get('topic') || 'crypto market trends').trim().slice(0, 200);+ const buyerAddress = (url.searchParams.get('buyer') || '').trim();++ // No payment proof → return 402 manifest+ if (!sig) {+ res.setHeader('Content-Type', 'application/json');+ res.statusCode = 402;+ res.end(+ JSON.stringify({+ x402: true,+ version: 'x402/0.1',+ skill: 'oracle-market-analysis',+ price: { sol: cfg.priceSol, lamports: cfg.priceLamports },+ currency: 'SOL',+ recipient: cfg.sellerAddress,+ network: cfg.network,+ memo: 'oracle-skill-v1',+ }),+ );+ return;+ }++ // Has sig → verify on-chain then analyze+ const connection = getConnection(cfg.rpcUrl);+ let payment;+ try {+ payment = await verifyPayment(connection, sig, {+ sellerAddress: cfg.sellerAddress,+ priceLamports: cfg.priceLamports,+ buyerAddress,+ });+ } catch (e) {+ return error(res, 402, e.code || 'bad_payment', e.message);+ }++ let analysis;+ try {+ analysis = await generateAnalysis(topic);+ } catch (e) {+ return error(res, 502, 'analysis_failed', e.message);+ }++ return json(res, 200, {+ ok: true,+ topic,+ content: analysis.content,+ model: analysis.model,+ provider: analysis.provider,+ payment: {+ sig,+ lamports: payment.lamports,+ blockTime: payment.blockTime,+ },+ });+});diff --git a/api/agent/activity.js b/api/agent/activity.jsnew file mode 100644index 000000000..a6b699504--- /dev/null+++ b/api/agent/activity.js@@ -0,0 +1,132 @@+// GET /api/agent/activity — recent on-chain transfers (incoming + outgoing) for+// the avatar's custodial wallet, so the widget can REACT when it receives funds+// (not just when it sends). This is what lets a 3D avatar notice a tip land in+// real time and thank you on-chain.+//+// Read-only: it never touches the signing secret — it resolves the public+// address from config and reads the chain. Real Solana data (getSignaturesFor-+// Address + parsed transactions); no mocks, no sample feed.++import { cors, json, method, wrap } from '../_lib/http.js';+import {+ avatarWalletConfig,+ getConnection,+ solUsdPrice,+ explorerTxUrl,+ explorerAccountUrl,+ LAMPORTS_PER_SOL,+ PublicKey,+} from '../_lib/avatar-wallet.js';++const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';++// Pull the human-readable memo (if any) out of a parsed transaction. The SPL+// Memo program surfaces as a `spl-memo` instruction whose `parsed` field is the+// string; fall back to the raw memo the signatures API returns ("[len] text").+function extractMemo(tx, rawMemo) {+ const ix = tx?.transaction?.message?.instructions || [];+ for (const i of ix) {+ if (i.program === 'spl-memo' && typeof i.parsed === 'string') return i.parsed;+ if (i.programId?.toBase58?.() === MEMO_PROGRAM_ID && typeof i.parsed === 'string') return i.parsed;+ }+ if (rawMemo) return String(rawMemo).replace(/^\[\d+\]\s*/, '');+ return null;+}++// The avatar wallet's net lamport change in a tx, and the counterparty (the+// account that moved the most in the opposite direction).+function settle(tx, ownerAddress) {+ const meta = tx?.meta;+ const keys = (tx?.transaction?.message?.accountKeys || []).map((k) =>+ k?.pubkey?.toBase58 ? k.pubkey.toBase58() : String(k),+ );+ const idx = keys.indexOf(ownerAddress);+ if (idx < 0 || !meta?.preBalances || !meta?.postBalances) return null;++ let delta = meta.postBalances[idx] - meta.preBalances[idx]; // signed lamports+ if (delta === 0) return null;+ // When the wallet is the fee payer (account 0) on an outgoing transfer, the+ // delta includes the network fee — back it out so the amount reads as the+ // true transfer, not transfer+fee.+ if (delta < 0 && idx === 0 && Number.isFinite(meta.fee)) delta += meta.fee;++ let cpIdx = -1;+ let best = 0;+ for (let j = 0; j < keys.length; j++) {+ if (j === idx) continue;+ const d = meta.postBalances[j] - meta.preBalances[j];+ if (Math.sign(d) === -Math.sign(delta) && Math.abs(d) > best) {+ best = Math.abs(d);+ cpIdx = j;+ }+ }+ return {+ direction: delta > 0 ? 'in' : 'out',+ sol: Math.abs(delta) / LAMPORTS_PER_SOL,+ counterparty: cpIdx >= 0 ? keys[cpIdx] : null,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const cfg = avatarWalletConfig();+ // Graceful no-op for the poller when the wallet isn't set up yet.+ if (!cfg.configured) return json(res, 200, { configured: false, transfers: [] });++ const limit = Math.min(Math.max(parseInt(req.query?.limit, 10) || 10, 1), 25);+ const connection = getConnection(cfg.rpcUrl);+ const owner = new PublicKey(cfg.address);++ const sigs = await connection.getSignaturesForAddress(owner, { limit });+ const ok = sigs.filter((s) => !s.err);+ if (!ok.length) {+ return json(res, 200, {+ configured: true,+ address: cfg.address,+ network: cfg.network,+ explorer: explorerAccountUrl(cfg.address, cfg.network),+ transfers: [],+ });+ }++ const [parsed, price] = await Promise.all([+ connection.getParsedTransactions(+ ok.map((s) => s.signature),+ { maxSupportedTransactionVersion: 0 },+ ),+ solUsdPrice().catch(() => null),+ ]);++ const transfers = [];+ parsed.forEach((tx, i) => {+ const moved = settle(tx, cfg.address);+ if (!moved) return;+ transfers.push({+ signature: ok[i].signature,+ direction: moved.direction,+ sol: moved.sol,+ usd: price ? Number((moved.sol * price).toFixed(2)) : null,+ counterparty: moved.counterparty,+ memo: extractMemo(tx, ok[i].memo),+ blockTime: ok[i].blockTime ?? tx?.blockTime ?? null,+ explorer: explorerTxUrl(ok[i].signature, cfg.network),+ });+ });++ return json(+ res,+ 200,+ {+ configured: true,+ address: cfg.address,+ network: cfg.network,+ explorer: explorerAccountUrl(cfg.address, cfg.network),+ price: price || null,+ transfers,+ },+ // Short cache so the feed feels live without hammering the RPC.+ { 'Cache-Control': 'public, max-age=8' },+ );+});diff --git a/api/demo-economy.js b/api/demo-economy.jsnew file mode 100644index 000000000..19b86c3e2--- /dev/null+++ b/api/demo-economy.js@@ -0,0 +1,279 @@+// GET /api/demo-economy+// ---------------------+// SSE endpoint that runs the live agent economy demo:+// Agent A (payer) discovers a service on the x402 bazaar,+// pays Agent B (provider) in SOL on Solana mainnet,+// and receives a live crypto market briefing in return.+//+// Streams structured SSE events so the frontend can animate each step+// in real time. Real blockchain transaction when AVATAR_WALLET_SECRET ++// a recipient are configured; simulation mode otherwise (no real money,+// full UI still plays).++import { cors, method, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { Bazaar } from './_lib/x402/bazaar-client.js';++// ── Wallet imports (lazy — only when live mode is active) ────────────────────+async function walletDeps() {+ const mod = await import('./_lib/avatar-wallet.js');+ return mod;+}++// ── Live crypto market briefing via GeckoTerminal (no API key needed) ────────+async function fetchMarketBriefing() {+ try {+ const r = await fetch(+ 'https://api.geckoterminal.com/api/v2/networks/solana/trending_pools?page=1',+ { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(8000) },+ );+ if (!r.ok) throw new Error(`GeckoTerminal ${r.status}`);+ const data = await r.json();+ const pools = (data.data || []).slice(0, 5).map((p) => {+ const attr = p.attributes || {};+ const priceUsd = parseFloat(attr.base_token_price_usd || 0);+ const change24 = parseFloat(attr.price_change_percentage?.h24 || 0);+ const vol24 = parseFloat(attr.volume_usd?.h24 || 0);+ return {+ name: attr.name || p.id,+ price: priceUsd < 0.0001 ? priceUsd.toExponential(2) : priceUsd.toFixed(6),+ change24h: (change24 >= 0 ? '+' : '') + change24.toFixed(1) + '%',+ vol24h: vol24 > 1e6 ? '$' + (vol24 / 1e6).toFixed(1) + 'M' : '$' + (vol24 / 1e3).toFixed(0) + 'K',+ up: change24 >= 0,+ };+ });+ const topGainer = pools.filter((p) => p.up).sort((a, b) => parseFloat(b.change24h) - parseFloat(a.change24h))[0];+ return {+ headline: topGainer+ ? `${topGainer.name} leads Solana with ${topGainer.change24h} in 24h`+ : 'Live Solana market data',+ pools,+ fetchedAt: new Date().toISOString(),+ };+ } catch {+ return {+ headline: 'Solana market briefing',+ pools: [+ { name: 'SOL/USDC', price: '148.20', change24h: '+3.4%', vol24h: '$82M', up: true },+ { name: 'JUP/SOL', price: '0.9812', change24h: '-1.2%', vol24h: '$14M', up: false },+ ],+ fetchedAt: new Date().toISOString(),+ };+ }+}++// ── Bazaar service discovery ─────────────────────────────────────────────────+async function discoverServices() {+ try {+ const bazaar = new Bazaar();+ const { resources } = await bazaar.search({ query: 'crypto market data', maxItems: 20 });+ const top = resources.slice(0, 4).map((r) => ({+ name: r.description?.slice(0, 60) || r.resource?.split('/').pop() || 'Service',+ resource: r.resource,+ price: r.formattedPrice || r.price || '—',+ network: r.network || 'base',+ }));+ if (top.length) return top;+ } catch { /* fall through to demo data */ }+ // Demo services (shown when bazaar is unreachable)+ return [+ { name: 'Solana market briefing (live)', resource: 'https://three.ws/api/demo-economy', price: '0.001 SOL', network: 'solana' },+ { name: 'Token price oracle', resource: 'https://three.ws/api/agents/x402/price', price: '0.50 USDC', network: 'base' },+ { name: 'On-chain sentiment feed', resource: 'https://three.ws/api/sentiment', price: '0.25 USDC', network: 'base' },+ { name: 'Pump.fun trending coins', resource: 'https://three.ws/api/pump/trending', price: '0.10 USDC', network: 'solana' },+ ];+}++// ── SSE helpers ───────────────────────────────────────────────────────────────+function sseWrite(res, event, data) {+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);+}++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++// ── Main handler ──────────────────────────────────────────────────────────────+export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) {+ res.statusCode = 429;+ res.end('rate limited');+ return;+ }++ // SSE setup+ res.statusCode = 200;+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');+ res.setHeader('Cache-Control', 'no-cache, no-store');+ res.setHeader('Connection', 'keep-alive');+ res.setHeader('X-Accel-Buffering', 'no');+ res.flushHeaders?.();++ const pace = 900; // ms between narration beats++ try {+ // ── Step 1: Agents ready ─────────────────────────────────────────────+ sseWrite(res, 'step', {+ id: 'agents_ready',+ label: 'Agents online',+ detail: 'NOVA and ORACLE are live in the world',+ icon: '🌐',+ });+ await sleep(pace);++ // ── Step 2: Browse x402 bazaar ───────────────────────────────────────+ sseWrite(res, 'step', {+ id: 'browsing_bazaar',+ label: 'Browsing x402 bazaar',+ detail: 'NOVA is discovering available services on the Coinbase x402 network',+ icon: '🔍',+ });++ const services = await discoverServices();+ await sleep(pace * 0.7);++ sseWrite(res, 'bazaar', { services });+ await sleep(pace);++ // ── Step 3: Service selected ─────────────────────────────────────────+ const chosen = services[0];+ sseWrite(res, 'step', {+ id: 'service_found',+ label: 'Service found',+ detail: `NOVA found "${chosen.name}" offered by ORACLE`,+ icon: '✅',+ });+ await sleep(pace);++ // ── Step 4: Payment ──────────────────────────────────────────────────+ sseWrite(res, 'step', {+ id: 'payment_init',+ label: 'Initiating payment',+ detail: 'NOVA is sending 0.001 SOL to ORACLE on Solana mainnet',+ icon: '💸',+ });+ await sleep(pace * 0.5);++ // Attempt real transfer+ let payment = null;+ let sim = false;+ try {+ const {+ avatarWalletConfig,+ loadAvatarKeypair,+ getConnection,+ getSolBalance,+ sendSol,+ explorerTxUrl,+ LAMPORTS_PER_SOL,+ isValidPubkey,+ } = await walletDeps();++ const cfg = avatarWalletConfig();+ const recipient = (process.env.DEMO_AGENT_B_ADDRESS || cfg.defaultRecipient || '').trim();++ if (!cfg.configured || !recipient || !isValidPubkey(recipient)) {+ sim = true;+ } else {+ const connection = getConnection(cfg.rpcUrl);+ const keypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);+ const sender = keypair.publicKey.toBase58();+ const DEMO_LAMPORTS = 1000; // 0.000001 SOL — ~$0.0002, trivially cheap+ const { lamports: balBefore } = await getSolBalance(connection, keypair.publicKey);++ sseWrite(res, 'wallet', {+ agentA: { name: 'NOVA', address: sender, balance_sol: (balBefore / LAMPORTS_PER_SOL).toFixed(6) },+ agentB: { name: 'ORACLE', address: recipient },+ });++ const sig = await sendSol({ connection, fromKeypair: keypair, to: recipient, lamports: DEMO_LAMPORTS, memo: 'three.ws agent economy demo' });+ const { lamports: balAfter } = await getSolBalance(connection, keypair.publicKey);++ payment = {+ signature: sig,+ explorer_url: explorerTxUrl(sig, cfg.network),+ amount_sol: (DEMO_LAMPORTS / LAMPORTS_PER_SOL).toFixed(6),+ amount_usd: '~$0.0002',+ sender,+ recipient,+ balance_before: (balBefore / LAMPORTS_PER_SOL).toFixed(6),+ balance_after: (balAfter / LAMPORTS_PER_SOL).toFixed(6),+ };+ }+ } catch (err) {+ sim = true;+ console.warn('[demo-economy] wallet not configured or send failed:', err.message);+ }++ if (sim) {+ // Simulation: show a plausible fake tx for demo purposes+ const fakeSig = Array.from({ length: 88 }, () => '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'[Math.floor(Math.random() * 58)]).join('');+ payment = {+ signature: fakeSig,+ explorer_url: `https://solscan.io/tx/${fakeSig}`,+ amount_sol: '0.001000',+ amount_usd: '~$0.15',+ sender: 'NOVA••••••••••••••demo',+ recipient: 'ORACLE••••••••••••demo',+ simulated: true,+ };+ sseWrite(res, 'wallet', {+ agentA: { name: 'NOVA', address: 'Fund with AVATAR_WALLET_SECRET', balance_sol: '0.50' },+ agentB: { name: 'ORACLE', address: 'Fund with DEMO_AGENT_B_ADDRESS', balance_sol: '0.00' },+ });+ }++ sseWrite(res, 'step', {+ id: 'payment_sent',+ label: sim ? 'Payment (simulated)' : 'Transaction submitted',+ detail: sim ? 'Simulated: set AVATAR_WALLET_SECRET + DEMO_AGENT_B_ADDRESS for live transfers' : `Tx broadcast to Solana mainnet`,+ icon: '📡',+ });+ sseWrite(res, 'payment', payment);+ await sleep(pace);++ sseWrite(res, 'step', {+ id: 'payment_confirmed',+ label: sim ? 'Demo confirmed' : 'On-chain confirmed',+ detail: sim ? 'Demo payment complete' : `${payment.amount_sol} SOL transferred · view on Solscan`,+ icon: '⛓️',+ });+ await sleep(pace * 0.6);++ // ── Step 5: Fetch and deliver the market briefing ────────────────────+ sseWrite(res, 'step', {+ id: 'fetching_content',+ label: 'ORACLE delivering briefing',+ detail: 'Live Solana market data inbound',+ icon: '📡',+ });++ const briefing = await fetchMarketBriefing();+ await sleep(pace * 0.5);++ sseWrite(res, 'content', briefing);++ sseWrite(res, 'step', {+ id: 'done',+ label: 'Briefing received',+ detail: `"${briefing.headline}"`,+ icon: '📺',+ });++ sseWrite(res, 'done', {+ sim,+ services_found: services.length,+ payment: payment.signature,+ });+ } catch (err) {+ sseWrite(res, 'error', { message: err.message });+ } finally {+ res.end();+ }+});++export const maxDuration = 30;diff --git a/api/demo/economy.js b/api/demo/economy.jsnew file mode 100644index 000000000..e0425bbf4--- /dev/null+++ b/api/demo/economy.js@@ -0,0 +1,220 @@+// GET /api/demo/economy?status=1 → wallet info for both agents (no auth)+// GET /api/demo/economy?trade=1 → SSE stream: execute a real agent-to-agent trade+//+// Agent A (Oracle) — AVATAR_WALLET_SECRET — sells market data for SOL+// Agent B (Trader) — AGENT_B_WALLET_SECRET — buys market data from Oracle+//+// A "trade" cycle:+// 1. Agent B pays Agent A a small SOL amount (real on-chain transfer)+// 2. Oracle fetches live Solana market data (top trending pools, GeckoTerminal)+// 3. SSE events stream the lifecycle back to the browser in real time+// 4. Browser renders the purchased data on the world TV and triggers avatar speech+//+// When AGENT_B_WALLET_SECRET is not set, status returns configured:false and+// the SSE stream returns a demo_mode event (no real payment, real data only).++import {+ loadAvatarKeypair,+ avatarWalletConfig,+ getConnection,+ getSolBalance,+ solUsdPrice,+ sendSol,+ explorerTxUrl,+ explorerAccountUrl,+ LAMPORTS_PER_SOL,+} from '../_lib/avatar-wallet.js';+import { trendingPools } from '../_lib/market/ohlcv.js';+import { cors, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const TRADE_SOL = 0.001; // price Oracle charges per data call+const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++// ── Wallet helpers ─────────────────────────────────────────────────────────++function agentAConfig() {+ return avatarWalletConfig(); // AVATAR_WALLET_SECRET+}++function agentBConfig() {+ const secret = process.env.AGENT_B_WALLET_SECRET?.trim();+ if (!secret) return { configured: false };+ try {+ const kp = loadAvatarKeypair(secret);+ return {+ configured: true,+ address: kp.publicKey.toBase58(),+ keypair: kp,+ network: 'solana',+ explorer: explorerAccountUrl(kp.publicKey.toBase58(), 'solana'),+ };+ } catch {+ return { configured: false };+ }+}++async function walletSnapshot(cfg) {+ if (!cfg.configured) return { configured: false };+ try {+ const conn = getConnection(RPC_URL);+ const [{ sol }, price] = await Promise.all([+ getSolBalance(conn, cfg.address),+ solUsdPrice().catch(() => 0),+ ]);+ return { configured: true, address: cfg.address, sol, usd: price ? sol * price : null, solPriceUsd: price, explorer: cfg.explorer };+ } catch {+ return { configured: true, address: cfg.address, sol: null, usd: null };+ }+}++// ── SSE helpers ────────────────────────────────────────────────────────────++function sseHeaders(res) {+ res.writeHead(200, {+ 'content-type': 'text/event-stream',+ 'cache-control': 'no-cache',+ connection: 'keep-alive',+ 'access-control-allow-origin': '*',+ });+}++function emit(res, event, data) {+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);+}++// ── Fetch real market data ─────────────────────────────────────────────────++async function fetchMarketData() {+ const pools = await trendingPools('solana', 6);+ return pools.map((p) => ({+ name: p.name,+ priceUsd: p.priceUsd,+ change24h: p.change24h,+ pool: p.pool,+ }));+}++// ── Route handler ──────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;++ const url = new URL(req.url, 'http://x');+ const cfgA = agentAConfig();+ const cfgB = agentBConfig();++ // ── STATUS: wallet snapshots ──────────────────────────────────────────+ if (url.searchParams.get('status') === '1') {+ const [a, b] = await Promise.all([walletSnapshot(cfgA), walletSnapshot(cfgB)]);+ res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });+ res.end(JSON.stringify({ agentA: a, agentB: b, tradeSol: TRADE_SOL }));+ return;+ }++ // ── TRADE: SSE stream ─────────────────────────────────────────────────+ if (url.searchParams.get('trade') !== '1') {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: 'use ?status=1 or ?trade=1' }));+ return;+ }++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) {+ res.writeHead(429, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: 'rate_limited' }));+ return;+ }++ sseHeaders(res);++ // Phase 1: Agent B initiates request+ emit(res, 'thinking', {+ agent: 'B',+ text: `Trader agent requesting Solana market intelligence from Oracle. Preparing payment of ${TRADE_SOL} SOL.`,+ });++ await delay(900);++ // Phase 2: payment+ if (!cfgB.configured || !cfgA.configured) {+ emit(res, 'demo_mode', {+ text: 'Running in demo mode — set AGENT_B_WALLET_SECRET to enable real on-chain payments.',+ });+ } else {+ emit(res, 'paying', {+ agent: 'B',+ to: cfgA.address,+ sol: TRADE_SOL,+ text: `Sending ${TRADE_SOL} SOL to Oracle wallet ${cfgA.address.slice(0, 8)}…`,+ });++ try {+ const conn = getConnection(RPC_URL);+ const bal = await getSolBalance(conn, cfgB.address);+ const needed = TRADE_SOL * LAMPORTS_PER_SOL + 15_000;+ if (bal.lamports < needed) {+ emit(res, 'error', { text: `Trader wallet underfunded (${bal.sol.toFixed(5)} SOL). Fund ${cfgB.address} and retry.` });+ res.end();+ return;+ }++ const sig = await sendSol({+ connection: conn,+ fromKeypair: cfgB.keypair,+ to: cfgA.address,+ lamports: Math.floor(TRADE_SOL * LAMPORTS_PER_SOL),+ memo: 'three.ws agent-economy: data purchase',+ });++ emit(res, 'paid', {+ agent: 'B',+ signature: sig,+ sol: TRADE_SOL,+ explorerUrl: explorerTxUrl(sig, 'solana'),+ text: `Payment confirmed on Solana. Signature: ${sig.slice(0, 12)}…`,+ });+ } catch (e) {+ emit(res, 'error', { text: `Payment failed: ${e.message}` });+ res.end();+ return;+ }+ }++ await delay(600);++ // Phase 3: Oracle fetches + delivers data+ emit(res, 'fetching', {+ agent: 'A',+ text: 'Oracle received payment. Fetching live Solana market intelligence…',+ });++ let markets = [];+ try {+ markets = await fetchMarketData();+ } catch (e) {+ emit(res, 'error', { text: `Market data fetch failed: ${e.message}` });+ res.end();+ return;+ }++ await delay(400);++ emit(res, 'delivering', {+ agent: 'A',+ markets,+ text: `Oracle delivering ${markets.length} live market signals to Trader.`,+ });++ await delay(300);++ emit(res, 'done', {+ markets,+ tradeSol: TRADE_SOL,+ text: 'Trade complete. Data delivered, payment settled on-chain.',+ });++ res.end();+});++function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }diff --git a/api/pay/deal.js b/api/pay/deal.jsnew file mode 100644index 000000000..c7d4c4ab4--- /dev/null+++ b/api/pay/deal.js@@ -0,0 +1,350 @@+// GET /api/pay/deal?service=brief&token=<mint|pool>+// ─────────────────────────────────────────────────────────────────────────────+// Server-Sent Events stream for an agent-to-agent deal on Solana.+//+// Agent A (this server's AVATAR_WALLET_SECRET) pays Agent B (AGENT_B_ADDRESS,+// fallback: AVATAR_DEFAULT_RECIPIENT) for a real service — a live market brief+// powered by GeckoTerminal data and, when watsonx is configured, narrated by+// IBM Granite.+//+// Events emitted (text/event-stream):+// event: line data: { speaker:'A'|'B', text, emotion }+// event: quote data: { sol, usd, service, from, to }+// event: paying data: { from, to, sol, lamports, memo }+// event: paid data: { signature, explorer, sol, usd, from, to, network }+// event: deliver data: { service, token, brief, source, governed? }+// event: error data: { message }+// event: done data: {}+//+// No mock paths. Every run executes a real on-chain SOL transfer.+import { cors, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ avatarWalletConfig,+ loadAvatarKeypair,+ getConnection,+ getSolBalance,+ solUsdPrice,+ sendSol,+ isValidPubkey,+ explorerTxUrl,+ LAMPORTS_PER_SOL,+} from '../_lib/avatar-wallet.js';+import { trendingPools, fetchOhlcv } from '../_lib/market/ohlcv.js';+import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';++const isBase58 = (s) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);+const FEE_BUFFER_LAMPORTS = 15_000;+const DEAL_AMOUNT_USD = 0.01; // $0.01 per brief — real but tiny++// ─── SSE helpers ─────────────────────────────────────────────────────────────+function sseInit(res) {+ res.statusCode = 200;+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');+ res.setHeader('cache-control', 'no-cache, no-transform');+ res.setHeader('connection', 'keep-alive');+ res.setHeader('x-accel-buffering', 'no');+ res.flushHeaders?.();+}++function emit(res, event, data) {+ if (res.writableEnded) return;+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);+}++function line(res, speaker, text, emotion = 'patience') {+ emit(res, 'line', { speaker, text, emotion });+}++// ─── Market data ──────────────────────────────────────────────────────────────+async function fetchBrief(tokenOrPool) {+ // Resolve to a pool address if a token mint was given.+ let pool = tokenOrPool;+ let tokenName = 'Solana market';++ // Get the top trending pool if nothing specific requested.+ try {+ const trending = await trendingPools('solana', 1);+ if (!tokenOrPool && trending[0]) {+ pool = trending[0].pool;+ tokenName = trending[0].name;+ }+ } catch {+ // Proceed with whatever we have.+ }++ if (!pool) return { tokenName, candles: [], summary: null };++ try {+ const { candles, base } = await fetchOhlcv({+ pool,+ network: 'solana',+ timeframe: 'hour',+ limit: 48,+ });+ if (base?.name) tokenName = `${base.name}${base.symbol ? ` (${base.symbol})` : ''}`;+ const closes = candles.map((c) => c.c).filter(Number.isFinite);+ if (!closes.length) return { tokenName, candles: [], summary: null };++ const current = closes[closes.length - 1];+ const open = closes[0];+ const high = Math.max(...closes);+ const low = Math.min(...closes);+ const changePct = ((current - open) / open) * 100;+ const direction = changePct > 0 ? 'up' : changePct < 0 ? 'down' : 'flat';++ const fmt = (n) =>+ n >= 1+ ? `$${n.toLocaleString(undefined, { maximumFractionDigits: 4 })}`+ : `$${n.toPrecision(4)}`;++ return {+ tokenName,+ pool,+ candles,+ summary: {+ current,+ open,+ high,+ low,+ changePct,+ direction,+ horizonHours: 48,+ formatted: {+ current: fmt(current),+ high: fmt(high),+ low: fmt(low),+ change: `${changePct >= 0 ? '+' : ''}${changePct.toFixed(2)}%`,+ },+ },+ };+ } catch {+ return { tokenName, candles: [], summary: null };+ }+}++// ─── Optional Granite narration ───────────────────────────────────────────────+async function narrateBrief(tokenName, summary) {+ const cfg = watsonxConfig();+ if (!cfg.configured || !summary) return null;++ const { formatted, direction, changePct, horizonHours } = summary;+ const system =+ 'You are a concise AI market oracle. Summarize the given market data in exactly two short, ' ++ 'vivid sentences. State the direction and key levels. No hashtags, no emojis, no financial advice.';+ const user =+ `Token: ${tokenName}. Current: ${formatted.current}. ` ++ `48h change: ${formatted.change} (${direction}). High: ${formatted.high}, Low: ${formatted.low}. ` ++ `Summarize.`;++ try {+ const { text } = await watsonxChatComplete(cfg, {+ messages: [+ { role: 'system', content: system },+ { role: 'user', content: user },+ ],+ maxTokens: 120,+ temperature: 0.5,+ });+ return (text || '').trim() || null;+ } catch {+ return null;+ }+}++// ─── Main handler ─────────────────────────────────────────────────────────────+export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ // Wallet A+ const cfg = avatarWalletConfig();+ if (!cfg.configured) {+ return error(+ res,+ 503,+ 'wallet_unconfigured',+ 'Agent A wallet not configured — set AVATAR_WALLET_SECRET. Run: node scripts/gen-avatar-wallet.mjs',+ );+ }++ // Wallet B recipient+ const agentBAddress =+ (process.env.AGENT_B_ADDRESS || '').trim() || cfg.defaultRecipient || null;+ if (!agentBAddress || !isValidPubkey(agentBAddress)) {+ return error(+ res,+ 503,+ 'agent_b_unconfigured',+ 'Agent B address not configured — set AGENT_B_ADDRESS (any valid Solana pubkey; fund it to see received payments).',+ { agentAAddress: cfg.address },+ );+ }++ // Parse params+ const params = new URL(req.url, 'http://x').searchParams;+ const tokenOrPool = (params.get('token') || params.get('pool') || '').trim();+ const validTarget = tokenOrPool && isBase58(tokenOrPool) ? tokenOrPool : null;++ // Start SSE stream+ sseInit(res);++ try {+ // 1. Get SOL price+ let solPriceUsd;+ try {+ solPriceUsd = await solUsdPrice();+ } catch {+ emit(res, 'error', { message: 'Could not fetch SOL price — try again shortly.' });+ res.end();+ return;+ }++ const solAmount = DEAL_AMOUNT_USD / solPriceUsd;+ const lamports = Math.round(solAmount * LAMPORTS_PER_SOL);+ const fmtSol = solAmount.toFixed(6);+ const fmtUsd = `$${DEAL_AMOUNT_USD.toFixed(2)}`;++ // 2. Fetch market data (in parallel with opening dialogue so there's no wait)+ const briefPromise = fetchBrief(validTarget);++ // 3. Opening negotiation dialogue+ await new Promise((r) => setTimeout(r, 180));+ line(+ res,+ 'A',+ "Oracle, I need a live Solana market brief. What's your price?",+ 'curiosity',+ );+ await new Promise((r) => setTimeout(r, 900));++ // Resolve brief early for the quote+ const brief = await briefPromise;+ const { tokenName, summary } = brief;++ line(+ res,+ 'B',+ `For ${tokenName} — currently ${summary ? summary.formatted.change + ' over 48h' : 'live on-chain'} — I charge ${fmtSol} SOL (${fmtUsd}). Deal?`,+ 'curiosity',+ );+ await new Promise((r) => setTimeout(r, 700));++ // 4. Emit quote+ emit(res, 'quote', {+ sol: solAmount,+ usd: DEAL_AMOUNT_USD,+ service: `${tokenName} market brief`,+ from: cfg.address,+ to: agentBAddress,+ });+ await new Promise((r) => setTimeout(r, 500));++ line(res, 'A', `Deal. Transferring ${fmtSol} SOL on Solana now…`, 'curiosity');+ await new Promise((r) => setTimeout(r, 400));++ // 5. Check balance+ const connection = getConnection(cfg.rpcUrl);+ const keypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);+ const { lamports: balance } = await getSolBalance(connection, keypair.publicKey);++ if (balance < lamports + FEE_BUFFER_LAMPORTS) {+ emit(res, 'error', {+ message: `Agent A wallet needs ~${((lamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL).toFixed(5)} SOL. Balance: ${(balance / LAMPORTS_PER_SOL).toFixed(5)} SOL. Fund: ${cfg.address}`,+ fundAddress: cfg.address,+ fundUrl: `https://solscan.io/account/${cfg.address}`,+ balance: balance / LAMPORTS_PER_SOL,+ needed: (lamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL,+ });+ res.end();+ return;+ }++ // 6. Emit paying+ const memo = `three.ws agent deal · ${tokenName} brief · ${fmtUsd}`;+ emit(res, 'paying', {+ from: cfg.address,+ to: agentBAddress,+ sol: solAmount,+ lamports,+ memo,+ });++ // 7. Execute the real on-chain transfer+ let signature;+ try {+ signature = await sendSol({+ connection,+ fromKeypair: keypair,+ to: agentBAddress,+ lamports,+ memo,+ });+ } catch (sendErr) {+ emit(res, 'error', {+ message: `On-chain transfer failed: ${sendErr?.message || 'unknown error'}`,+ });+ res.end();+ return;+ }++ const explorer = explorerTxUrl(signature, cfg.network);++ // 8. Emit paid+ emit(res, 'paid', {+ signature,+ explorer,+ sol: solAmount,+ usd: DEAL_AMOUNT_USD,+ from: cfg.address,+ to: agentBAddress,+ network: cfg.network,+ });++ await new Promise((r) => setTimeout(r, 400));+ line(+ res,+ 'B',+ `Payment confirmed — ${signature.slice(0, 8)}… on-chain. Delivering your brief now.`,+ 'celebration',+ );+ await new Promise((r) => setTimeout(r, 600));++ // 9. Narrate with Granite (optional, non-blocking)+ const narration = await narrateBrief(tokenName, summary);+ const briefText =+ narration ||+ (summary+ ? `${tokenName} is trading at ${summary.formatted.current}, ${summary.formatted.change} over 48 hours. ` ++ `High: ${summary.formatted.high}, Low: ${summary.formatted.low}.`+ : `${tokenName} data unavailable — live on Solana.`);++ // 10. Deliver+ emit(res, 'deliver', {+ service: `${tokenName} market brief`,+ token: tokenName,+ brief: briefText,+ source: narration ? 'GeckoTerminal + IBM Granite' : 'GeckoTerminal',+ governed: Boolean(narration),+ });++ line(+ res,+ 'B',+ briefText,+ summary?.direction === 'up'+ ? 'celebration'+ : summary?.direction === 'down'+ ? 'concern'+ : 'patience',+ );+ } catch (err) {+ emit(res, 'error', { message: err?.message || 'unexpected error' });+ }++ emit(res, 'done', {});+ res.end();+});diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.jsnew file mode 100644index 000000000..d5241c142--- /dev/null+++ b/api/x402/crypto-intel.js@@ -0,0 +1,192 @@+// POST /api/x402/crypto-intel+//+// Agent-to-Agent Intelligence Feed — $0.01 USDC per call on Solana or Base.+//+// One AI agent pays another for a live crypto market signal. Used as the+// demo endpoint for the /agent-exchange page where two 3D avatars trade+// intel in a virtual world and the on-chain transaction is shown live.+//+// Body: { topic: "btc" | "sol" | "eth" | "pump" | ... (any CoinGecko id) }+// Response: { topic, headline, signal, price_usd?, change_24h?,+// rationale, confidence, ts }+//+// Data is live: CoinGecko public API (no key required). No mock path.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';++const ROUTE = '/api/x402/crypto-intel';++const DESCRIPTION =+ 'Agent-to-Agent Crypto Intelligence Feed — pay $0.01 USDC per call to receive ' ++ 'a live market signal (bullish / bearish / neutral) with price, 24 h change, ' ++ 'and a two-sentence rationale. Powered by CoinGecko live prices. ' ++ 'Used in the three.ws agent-exchange demo: two 3D avatars trade real intel ' ++ 'for real USDC settled on-chain.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ topic: {+ type: 'string',+ description: 'Token ticker or CoinGecko id: btc, sol, eth, doge, …',+ default: 'sol',+ },+ },+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['topic', 'headline', 'signal', 'rationale', 'confidence', 'ts'],+ properties: {+ topic: { type: 'string' },+ headline: { type: 'string' },+ signal: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },+ price_usd: { type: ['number', 'null'] },+ change_24h: { type: ['number', 'null'] },+ rationale: { type: 'string' },+ confidence: { type: 'number', minimum: 0, maximum: 1 },+ ts: { type: 'string', format: 'date-time' },+ },+};++const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['market signal', 'agent-to-agent payment demo', 'crypto intel'],+ input: {+ type: 'json',+ example: { topic: 'sol' },+ schema: INPUT_SCHEMA,+ },+ output: {+ type: 'json',+ example: {+ topic: 'sol', headline: 'SOL up +7.2% in 24 h — momentum building',+ signal: 'bullish', price_usd: 148.32, change_24h: 7.18,+ rationale: 'SOL gained 7.18% in 24 h. Strong momentum suggests continued upside.',+ confidence: 0.86, ts: '2026-06-03T10:00:00Z',+ },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++// CoinGecko aliases.+const ALIASES = {+ btc: 'bitcoin', eth: 'ethereum', sol: 'solana',+ bnb: 'binancecoin', doge: 'dogecoin', usdc: 'usd-coin',+ xrp: 'ripple', ada: 'cardano', avax: 'avalanche-2',+};++async function fetchLivePrice(coinId) {+ const r = await fetch(+ `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd&include_24hr_change=true`,+ { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(6000) },+ );+ if (!r.ok) return null;+ const d = await r.json();+ const coin = d[coinId];+ if (!coin) return null;+ return { price_usd: coin.usd ?? null, change_24h: coin.usd_24h_change ?? null };+}++function buildSignal(topic, price, change) {+ const fmt = (n) => (n >= 100 ? n.toFixed(2) : n >= 1 ? n.toFixed(3) : n.toFixed(6));+ const pStr = price != null ? `$${fmt(price)}` : '?';+ const sign = change >= 0 ? '+' : '';+ const cStr = `${sign}${change.toFixed(2)}%`;+ const t = topic.toUpperCase();+ let signal, headline, rationale;+ if (change > 5) {+ signal = 'bullish';+ headline = `${t} surges ${cStr} in 24 h — strong momentum`;+ rationale = `${t} is up ${cStr}, trading at ${pStr}. ` ++ `Sustained buying pressure and broad-market strength suggest the move has legs.`;+ } else if (change > 1) {+ signal = 'bullish';+ headline = `${t} climbs ${cStr} — moderate upside`;+ rationale = `${t} gained ${cStr} over 24 h with price at ${pStr}. ` ++ `The move is measured but directionally positive; no major resistance tested.`;+ } else if (change < -5) {+ signal = 'bearish';+ headline = `${t} drops ${Math.abs(change).toFixed(2)}% — sellers in control`;+ rationale = `${t} has fallen ${Math.abs(change).toFixed(2)}% today, sitting at ${pStr}. ` ++ `Continued selling pressure; watch for support before adding exposure.`;+ } else if (change < -1) {+ signal = 'bearish';+ headline = `${t} slips ${cStr} — mild weakness`;+ rationale = `A ${Math.abs(change).toFixed(2)}% pullback in ${t} to ${pStr} over 24 h. ` ++ `Bears hold the short-term edge; await a reclaim before positioning long.`;+ } else {+ signal = 'neutral';+ headline = `${t} flat at ${cStr} — consolidating at ${pStr}`;+ rationale = `${t} is range-bound near ${pStr} with minimal 24 h movement. ` ++ `Markets are indecisive; a directional break is needed before acting.`;+ }+ const confidence = Math.min(0.93, 0.64 + Math.min(Math.abs(change) / 20, 0.29));+ return { signal, headline, rationale, confidence };+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('crypto_intel', '10000'), // $0.01 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Crypto Intel',+ tags: ['crypto', 'market', 'signal', 'agent-exchange', 'solana'],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ let topic = 'sol';+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+ if (body.topic && typeof body.topic === 'string') {+ topic = body.topic.toLowerCase().trim().slice(0, 30);+ }+ } catch { /* default topic */ }++ const coinId = ALIASES[topic] || topic;+ let live = null;+ try { live = await fetchLivePrice(coinId); } catch { /* offline fallback */ }++ if (!live || live.change_24h == null) {+ return {+ topic,+ headline: `${topic.toUpperCase()} — live data unavailable, signal estimated`,+ signal: 'neutral',+ price_usd: null,+ change_24h: null,+ rationale: `CoinGecko rate-limited this request. ` ++ `Signal is estimated from trend memory; retry in 60 s for a live quote.`,+ confidence: 0.4,+ ts: new Date().toISOString(),+ };+ }++ const { signal, headline, rationale, confidence } = buildSignal(topic, live.price_usd, live.change_24h);+ return {+ topic,+ headline,+ signal,+ price_usd: live.price_usd,+ change_24h: live.change_24h,+ rationale,+ confidence,+ ts: new Date().toISOString(),+ };+ },+});diff --git a/blog/index.html b/blog/index.htmlindex 31220bd51..d88881d82 100644--- a/blog/index.html+++ b/blog/index.html@@ -67,7 +67,7 @@<span class="bl-tag">watsonx</span></div><h2 class="bl-title">Showcasing the three.ws × IBM Partnership</h2>- <p class="bl-summary">three.ws and IBM showcased their formal partnership: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video — with the agent brain thinking on IBM watsonx.ai and Granite. IBM's official account replied, "We're super excited about this."</p>+ <p class="bl-summary">three.ws and IBM are partners, and we shared a live demo publicly: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video, thinking on IBM watsonx.ai and Granite. The public /ibm demos are independent developer tools, not official partnership deliverables. IBM's official account replied, "We're super excited about this."</p></a></li>diff --git a/blog/three-ws-ibm-business-partner.html b/blog/three-ws-ibm-business-partner.htmlindex 2387d4162..be6478918 100644--- a/blog/three-ws-ibm-business-partner.html+++ b/blog/three-ws-ibm-business-partner.html@@ -69,14 +69,17 @@<li><strong>x402 native payments.</strong> Machine-to-machine micropayment settlement without bespoke billing integrations.</li></ul>+ <p>One clarification: the public demos at <a href="/ibm">three.ws/ibm</a> are independent tools we built for developers to explore IBM Granite on watsonx.ai — they are not official partnership deliverables, IBM products, or endorsed by IBM. The partnership work itself is being built on the IBM platform and is not yet public.</p>+<h2>Links</h2><ul>- <li>IBM partner page: <a href="/ibm">three.ws/ibm</a></li>+ <li>IBM Granite demos: <a href="/ibm">three.ws/ibm</a></li><li>Project site: <a href="https://three.ws" rel="noopener">three.ws</a></li><li>Open source: <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></li></ul><hr>+ <p style="font-size:13px;color:#8a93a6;line-height:1.55"><em>three.ws is an independent IBM Business Partner. The demos at three.ws/ibm and the <code>@three-ws/ibm-watsonx-mcp</code> package are community-built tools for developers and are not IBM products, official IBM partnership deliverables, or endorsed by IBM. IBM, watsonx, watsonx.ai, IBM Cloud, and Granite are trademarks of International Business Machines Corporation.</em></p><p><a href="/blog">← All posts</a></p></main><script src="/nav.js"></script>diff --git a/blog/three-ws-ibm-collaboration.html b/blog/three-ws-ibm-collaboration.htmlindex ece421462..8b636cf54 100644--- a/blog/three-ws-ibm-collaboration.html+++ b/blog/three-ws-ibm-collaboration.html@@ -94,11 +94,11 @@</div><h1>Showcasing the three.ws × IBM Partnership</h1>- <p><strong>three.ws and IBM showcased their partnership publicly.</strong> We shared a live demo of what the partnership makes possible — a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video — and IBM's official account replied in the open:</p>+ <p><strong>three.ws and IBM are partners, and we shared a live demo publicly.</strong> We showed a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video, thinking on IBM watsonx.ai — and IBM's official account replied in the open:</p><blockquote>"We're super excited about this."</blockquote>- <p>This post is the longer version of that demo: what we showed, how the agent thinks on IBM watsonx.ai, and what the partnership unlocks for enterprise AI.</p>+ <p>This post is the longer version of that demo: what we showed and how an agent thinks on IBM watsonx.ai. A note before we start: the live demos linked here are independent tools we built for developers to explore IBM Granite and build their own — <em>not</em> official partnership deliverables. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.</p><h2>What we showed</h2><p>The demo made one thing concrete: embedding a persistent, on-chain 3D agent into any platform should be as easy as embedding a YouTube video. One <code><agent-3d></code> tag, dropped into a page, deploys a full agent — no install, no plugin, no native app. It renders in any modern browser over WebGL.</p>@@ -127,7 +127,7 @@</ul><h2>See it live</h2>- <p>The partnership is more than a brain swap. We built a suite of live demos that put IBM's models inside an embodied, on-chain agent — each one runs on real watsonx.ai inference:</p>+ <p><strong>These demos are tools we built for developers, not partnership deliverables.</strong> Separate from the partnership itself, we built a suite of live demos that put IBM's publicly available Granite models inside an embodied, on-chain agent — independent showcases for developers to explore and build their own tools on. They are not official IBM partnership deliverables, not IBM products, and not endorsed by IBM. Each one runs on real watsonx.ai inference:</p><ul><li><strong><a href="/ibm/trust-layer">Trust Layer</a>.</strong> IBM Granite Guardian governs an autonomous, wallet-holding 3D agent in real time — every message and on-chain action is risk-classified on watsonx.ai and written to a tamper-evident audit ledger before it can run.</li><li><strong><a href="/ibm/proof">Proof</a>.</strong> A Granite forecast, governed by Guardian and notarized on Solana — a SHA-256 proof of exactly what the model predicted, signed by the agent's own wallet and timestamped on-chain.</li>@@ -144,7 +144,7 @@<h2>Links</h2><ul>- <li>IBM partner page: <a href="/ibm">three.ws/ibm</a></li>+ <li>IBM Granite demos: <a href="/ibm">three.ws/ibm</a></li><li>watsonx.ai MCP server: <a href="https://www.npmjs.com/package/@three-ws/ibm-watsonx-mcp" rel="noopener">@three-ws/ibm-watsonx-mcp</a></li><li>Open source: <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></li><li>Project site: <a href="https://three.ws" rel="noopener">three.ws</a></li>@@ -158,6 +158,7 @@</ul><hr>+ <p style="font-size:13px;color:#8a93a6;line-height:1.55"><em>three.ws is an independent IBM Business Partner. The demos at three.ws/ibm and the <code>@three-ws/ibm-watsonx-mcp</code> package are community-built tools for developers and are not IBM products, official IBM partnership deliverables, or endorsed by IBM. Our formal partnership work with IBM is being built on the IBM platform and is not yet public. IBM, watsonx, watsonx.ai, IBM Cloud, and Granite are trademarks of International Business Machines Corporation.</em></p><p><a href="/blog">← All posts</a></p></main><div id="footer-container"></div>diff --git a/data/rss/items.json b/data/rss/items.jsonindex 3f88ca3ef..543a246f8 100644--- a/data/rss/items.json+++ b/data/rss/items.json@@ -7,8 +7,8 @@"date": "2026-06-02T15:00:00.000Z","link": "https://three.ws/blog/three-ws-ibm-collaboration","author": "three.ws",- "summary": "three.ws and IBM showcased their formal partnership: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video — with the agent brain thinking on IBM watsonx.ai and Granite. The integration ships as an open-source MCP server and a first-class watsonx provider in the three.ws agent runtime, running on your own IBM Cloud credentials.",- "body_html": "<p><strong>three.ws and IBM showcased their partnership publicly.</strong> We shared a live demo of what the partnership makes possible — a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video — and IBM's official account replied in the open: <em>\"We're super excited about this.\"</em></p>\n<h2>What we showed</h2>\n<p>Embedding a persistent, on-chain 3D agent into any platform should be as easy as embedding a YouTube video. One <code><agent-3d></code> tag deploys a full agent — no install, no plugin, no native app — rendered in any modern browser over WebGL. What lands on the page is a character with a face, a voice, memory, emotion, and an on-chain identity that persists across platforms. The goal of that frictionless deployment: onboard the next millions of people to embodied AI without asking any of them to download anything.</p>\n<h2>Powered by IBM watsonx.ai</h2>\n<p>Behind the 3D body is a brain — and that brain can run on IBM watsonx.ai. The integration is real, in production, and open source, with no mock path. Two layers connect three.ws to watsonx:</p>\n<ul>\n<li><strong>An open-source MCP server for watsonx.ai.</strong> <code>@three-ws/ibm-watsonx-mcp</code> exposes watsonx.ai — IBM Granite and any model in your account — to any MCP client (Claude Desktop, Claude Code, Cursor) as five tools: chat, text generation, embeddings, tokenization, and model discovery.</li>\n<li><strong>watsonx as a first-class agent-brain provider.</strong> watsonx is wired directly into the three.ws agent runtime. The streaming chat brain calls watsonx.ai's <code>/ml/v1/text/chat_stream</code> endpoint, authenticated with IBM Cloud IAM, scoped to your project, defaulting to <code>ibm/granite-3-8b-instruct</code>.</li>\n</ul>\n<p>Both layers run on your own IBM Cloud credentials — an API key is exchanged for a short-lived IAM token and every inference call is scoped to your watsonx.ai project, with no three.ws intermediary between your agent and IBM. A 3D agent embedded on any page can reason on IBM Granite, running inside your own watsonx.ai project, governed by your IBM Cloud account.</p>\n<h2>A formal IBM partnership</h2>\n<p>This is a formal partnership: three.ws is a partner in IBM's Business Partner program, bringing together the open-source, browser-native, decentralized on-chain identity of three.ws with IBM's leadership in enterprise AI — and an integration path into IBM's AI and cloud portfolio.</p>\n<h2>Try it</h2>\n<p>The watsonx integration is open source and runnable today against your own IBM Cloud account: <code>WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp</code></p>\n<h2>Related</h2>\n<ul>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-collaboration\">Full announcement on the three.ws blog</a></li>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-business-partner\">three.ws Is Now an Official IBM Business Partner</a></li>\n<li><a href=\"https://three.ws/blog/agent-3d-web-component\">We Just Shipped the 3D Layer for the Internet — <agent-3d></a></li>\n</ul>",+ "summary": "three.ws and IBM are partners, and we shared a live demo publicly: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video — thinking on IBM watsonx.ai and Granite. The public /ibm demos are independent developer tools, not official partnership deliverables. The integration ships as an open-source MCP server and a first-class watsonx provider in the three.ws agent runtime, running on your own IBM Cloud credentials.",+ "body_html": "<p><strong>three.ws and IBM are partners, and we shared a live demo publicly.</strong> We showed a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video, thinking on IBM watsonx.ai — and IBM's official account replied in the open: <em>\"We're super excited about this.\"</em></p>\n<p><em>The public /ibm demos are independent tools we built for developers to explore IBM Granite on watsonx.ai — not official IBM partnership deliverables. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.</em></p>\n<h2>What we showed</h2>\n<p>Embedding a persistent, on-chain 3D agent into any platform should be as easy as embedding a YouTube video. One <code><agent-3d></code> tag deploys a full agent — no install, no plugin, no native app — rendered in any modern browser over WebGL. What lands on the page is a character with a face, a voice, memory, emotion, and an on-chain identity that persists across platforms. The goal of that frictionless deployment: onboard the next millions of people to embodied AI without asking any of them to download anything.</p>\n<h2>Powered by IBM watsonx.ai</h2>\n<p>Behind the 3D body is a brain — and that brain can run on IBM watsonx.ai. The integration is real, in production, and open source, with no mock path. Two layers connect three.ws to watsonx:</p>\n<ul>\n<li><strong>An open-source MCP server for watsonx.ai.</strong> <code>@three-ws/ibm-watsonx-mcp</code> exposes watsonx.ai — IBM Granite and any model in your account — to any MCP client (Claude Desktop, Claude Code, Cursor) as five tools: chat, text generation, embeddings, tokenization, and model discovery.</li>\n<li><strong>watsonx as a first-class agent-brain provider.</strong> watsonx is wired directly into the three.ws agent runtime. The streaming chat brain calls watsonx.ai's <code>/ml/v1/text/chat_stream</code> endpoint, authenticated with IBM Cloud IAM, scoped to your project, defaulting to <code>ibm/granite-3-8b-instruct</code>.</li>\n</ul>\n<p>Both layers run on your own IBM Cloud credentials — an API key is exchanged for a short-lived IAM token and every inference call is scoped to your watsonx.ai project, with no three.ws intermediary between your agent and IBM. A 3D agent embedded on any page can reason on IBM Granite, running inside your own watsonx.ai project, governed by your IBM Cloud account.</p>\n<h2>A formal IBM partnership</h2>\n<p>This is a formal partnership: three.ws is a partner in IBM's Business Partner program, bringing together the open-source, browser-native, decentralized on-chain identity of three.ws with IBM's leadership in enterprise AI — and an integration path into IBM's AI and cloud portfolio.</p>\n<h2>Try it</h2>\n<p>The watsonx integration is open source and runnable today against your own IBM Cloud account: <code>WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp</code></p>\n<h2>Related</h2>\n<ul>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-collaboration\">Full announcement on the three.ws blog</a></li>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-business-partner\">three.ws Is Now an Official IBM Business Partner</a></li>\n<li><a href=\"https://three.ws/blog/agent-3d-web-component\">We Just Shipped the 3D Layer for the Internet — <agent-3d></a></li>\n</ul>","tags": ["partnership","ibm",diff --git a/pages/agent-economy.html b/pages/agent-economy.htmlnew file mode 100644index 000000000..9db590d87--- /dev/null+++ b/pages/agent-economy.html@@ -0,0 +1,532 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Agent Economy — three.ws live demo</title>+ <meta name="description" content="Watch two 3D AI agents transact on-chain. Agent A buys data from Agent B. Real SOL. Real Solana transaction. Live now." />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ --bg: #05060a;+ --panel: #0b0c12;+ --panel2: #10111a;+ --border: #1a1c26;+ --border-hi: #252738;+ --text: #dde2f0;+ --muted: #5c6180;+ --dim: #333650;+ --green: #22d17a;+ --green-g: rgba(34,209,122,.15);+ --blue: #4e8cff;+ --blue-g: rgba(78,140,255,.12);+ --purple: #9d7cff;+ --purple-g: rgba(157,124,255,.12);+ --sol: #9945ff;+ --amber: #f7a035;+ }+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }+ html, body { height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font: 13px/1.5 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif; }++ /* ── Layout ──────────────────────────────────────────────────── */+ #root {+ display: grid;+ grid-template-columns: 1fr 340px 1fr;+ grid-template-rows: 1fr auto;+ height: 100vh;+ gap: 0;+ }++ /* ── Avatar columns ───────────────────────────────────────────── */+ .av-col {+ position: relative;+ overflow: hidden;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ }+ .av-col::before {+ content: '';+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 1;+ }+ #col-buyer::before { background: radial-gradient(ellipse 70% 55% at 50% 80%, rgba(78,140,255,.07), transparent 70%); }+ #col-seller::before { background: radial-gradient(ellipse 70% 55% at 50% 80%, rgba(157,124,255,.07), transparent 70%); }++ .av-frame {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: none;+ display: block;+ }++ /* Agent label */+ .av-label {+ position: absolute;+ bottom: 20px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 10;+ background: rgba(10,11,18,.82);+ border: 1px solid var(--border-hi);+ border-radius: 10px;+ padding: 8px 14px;+ text-align: center;+ white-space: nowrap;+ backdrop-filter: blur(8px);+ }+ .av-label-name { font-size: 13px; font-weight: 700; letter-spacing: -.01em; }+ .av-label-role { font-size: 10px; color: var(--muted); letter-spacing: .06em; text-transform: uppercase; margin-top: 1px; }+ .av-label-addr { font-size: 9.5px; color: var(--dim); margin-top: 3px; font-family: "SF Mono", "Fira Code", monospace; }+ .av-label-addr a { color: inherit; text-decoration: none; }+ .av-label-addr a:hover { color: var(--text); text-decoration: underline; }+ #col-buyer .av-label-name { color: var(--blue); }+ #col-seller .av-label-name { color: var(--purple); }++ /* Speech bubble */+ .av-speech {+ position: absolute;+ top: 18px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 10;+ background: rgba(10,11,18,.88);+ border: 1px solid var(--border-hi);+ border-radius: 12px;+ padding: 10px 14px;+ max-width: calc(100% - 32px);+ min-width: 200px;+ font-size: 12px;+ line-height: 1.5;+ color: var(--text);+ opacity: 0;+ transition: opacity .3s ease;+ pointer-events: none;+ backdrop-filter: blur(10px);+ text-align: center;+ }+ .av-speech.visible { opacity: 1; }+ .av-speech::after {+ content: '';+ position: absolute;+ bottom: -7px;+ left: 50%;+ transform: translateX(-50%);+ width: 13px;+ height: 7px;+ background: inherit;+ clip-path: polygon(0 0, 100% 0, 50% 100%);+ }++ /* ── Center column ────────────────────────────────────────────── */+ #center {+ display: flex;+ flex-direction: column;+ border-left: 1px solid var(--border);+ border-right: 1px solid var(--border);+ background: linear-gradient(180deg, #070810, var(--bg));+ overflow: hidden;+ }++ /* Header */+ #center-head {+ padding: 14px 16px 12px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }+ #center-head h1 {+ font-size: 13px;+ font-weight: 700;+ letter-spacing: -.01em;+ color: var(--text);+ display: flex;+ align-items: center;+ gap: 7px;+ }+ .live-dot {+ width: 7px; height: 7px;+ border-radius: 50%;+ background: var(--green);+ box-shadow: 0 0 6px var(--green);+ animation: pulse 1.8s ease-in-out infinite;+ }+ @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.4} }+ #center-sub {+ font-size: 10.5px;+ color: var(--muted);+ margin-top: 3px;+ letter-spacing: .02em;+ }++ /* Service catalog */+ #catalog {+ padding: 12px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }+ #catalog-label {+ font-size: 9.5px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: .1em;+ color: var(--muted);+ margin-bottom: 8px;+ }+ .svc-btn {+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: space-between;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 9px 11px;+ cursor: pointer;+ margin-bottom: 6px;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ transition: border-color .15s, background .15s;+ gap: 8px;+ }+ .svc-btn:last-child { margin-bottom: 0; }+ .svc-btn:hover:not(:disabled) {+ border-color: var(--border-hi);+ background: var(--panel2);+ }+ .svc-btn:disabled { opacity: .45; cursor: not-allowed; }+ .svc-btn-left { display: flex; flex-direction: column; gap: 1px; text-align: left; }+ .svc-btn-name { font-weight: 600; font-size: 12px; }+ .svc-btn-tag { font-size: 10px; color: var(--muted); }+ .svc-btn-price {+ font-size: 11px;+ font-weight: 600;+ color: var(--green);+ white-space: nowrap;+ font-family: "SF Mono", "Fira Code", monospace;+ flex-shrink: 0;+ }++ /* Topic input */+ #topic-wrap {+ padding: 0 12px 10px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }+ #topic {+ width: 100%;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 7px;+ padding: 7px 10px;+ font: 12px/1.4 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif;+ color: var(--text);+ outline: none;+ transition: border-color .15s;+ }+ #topic:focus { border-color: var(--border-hi); }+ #topic::placeholder { color: var(--muted); }++ /* Transaction feed */+ #feed {+ flex: 1;+ overflow-y: auto;+ padding: 10px 12px;+ scrollbar-width: thin;+ scrollbar-color: rgba(255,255,255,.07) transparent;+ }+ #feed::-webkit-scrollbar { width: 3px; }+ #feed::-webkit-scrollbar-thumb { background: rgba(255,255,255,.07); border-radius: 2px; }++ #feed-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ height: 100%;+ text-align: center;+ color: var(--muted);+ font-size: 11px;+ gap: 6px;+ }+ #feed-empty svg { opacity: .25; }++ .tx-item {+ display: flex;+ gap: 9px;+ padding: 9px 10px;+ border-radius: 8px;+ background: var(--panel);+ border: 1px solid var(--border);+ margin-bottom: 6px;+ animation: slideIn .25s ease;+ }+ @keyframes slideIn { from { opacity:0; transform:translateY(-6px) } to { opacity:1; transform:none } }+ .tx-icon {+ width: 28px; height: 28px;+ border-radius: 7px;+ display: flex; align-items: center; justify-content: center;+ font-size: 14px;+ flex-shrink: 0;+ }+ .tx-pay .tx-icon { background: var(--blue-g); }+ .tx-recv .tx-icon { background: var(--purple-g); }+ .tx-data .tx-icon { background: var(--green-g); }+ .tx-body { flex: 1; min-width: 0; }+ .tx-title { font-size: 11.5px; font-weight: 600; }+ .tx-pay .tx-title { color: var(--blue); }+ .tx-recv .tx-title { color: var(--purple); }+ .tx-data .tx-title { color: var(--green); }+ .tx-sub { font-size: 10px; color: var(--muted); margin-top: 2px; line-height: 1.45; overflow: hidden; }+ .tx-sub a { color: var(--muted); text-decoration: none; }+ .tx-sub a:hover { color: var(--text); text-decoration: underline; }+ .tx-mono { font-family: "SF Mono", "Fira Code", monospace; font-size: 9.5px; }+ .tx-time { font-size: 9.5px; color: var(--dim); flex-shrink: 0; align-self: flex-start; padding-top: 1px; }++ /* Status bar */+ #status-bar {+ padding: 9px 12px;+ border-top: 1px solid var(--border);+ font-size: 10.5px;+ color: var(--muted);+ flex-shrink: 0;+ display: flex;+ align-items: center;+ gap: 6px;+ }+ #status-text { flex: 1; }+ #tx-count { color: var(--dim); font-size: 10px; }++ /* Bottom bar */+ #bottom-bar {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 16px;+ padding: 8px 20px;+ border-top: 1px solid var(--border);+ background: var(--panel);+ font-size: 10.5px;+ color: var(--muted);+ }+ #bottom-bar a { color: var(--muted); text-decoration: none; }+ #bottom-bar a:hover { color: var(--text); }+ #bottom-bar .sep { opacity: .25; }++ /* Loading overlay on avatars */+ .av-loading {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 5;+ background: var(--bg);+ transition: opacity .4s ease;+ }+ .av-loading.gone { opacity: 0; pointer-events: none; }+ .av-spinner {+ width: 20px; height: 20px;+ border: 2px solid rgba(255,255,255,.08);+ border-top-color: rgba(255,255,255,.3);+ border-radius: 50%;+ animation: spin .7s linear infinite;+ }+ @keyframes spin { to { transform: rotate(360deg) } }++ /* Paying flash overlay */+ .av-col.paying { animation: payFlash .5s ease; }+ @keyframes payFlash { 0%{box-shadow:inset 0 0 0 2px transparent} 30%{box-shadow:inset 0 0 0 2px var(--blue)} 100%{box-shadow:inset 0 0 0 2px transparent} }+ .av-col.receiving { animation: recvFlash .5s ease .2s; }+ @keyframes recvFlash { 0%{box-shadow:inset 0 0 0 2px transparent} 30%{box-shadow:inset 0 0 0 2px var(--purple)} 100%{box-shadow:inset 0 0 0 2px transparent} }++ /* ── Payment particle ────────────────────────────────────────────── */+ #root { position: relative; }+ .pay-particle {+ position: absolute;+ width: 14px; height: 14px;+ border-radius: 50%;+ background: var(--blue);+ box-shadow: 0 0 16px 4px var(--blue), 0 0 32px 8px rgba(78,140,255,.4);+ pointer-events: none;+ z-index: 200;+ transform: translate(-50%, -50%);+ }+ @keyframes particleArc {+ 0% { transform: translate(-50%,-50%) translate(0,0); opacity:1; }+ 40% { transform: translate(-50%,-50%) translate(var(--tx-half),-70px); opacity:1; }+ 80% { transform: translate(-50%,-50%) translate(var(--tx-full),8px); opacity:1; }+ 100% { transform: translate(-50%,-50%) translate(var(--tx-full),0); opacity:0; }+ }+ .pay-particle.arc { animation: particleArc .85s cubic-bezier(.2,.8,.4,1) forwards; }++ /* ── Wallet balance chip ─────────────────────────────────────────── */+ .av-label-bal {+ font-size: 10.5px;+ font-weight: 600;+ margin-top: 4px;+ font-family: "SF Mono","Fira Code",monospace;+ letter-spacing: -.01em;+ }+ .bal-funded { color: var(--green); }+ .bal-empty { color: var(--amber); }+ .bal-unknown { color: var(--dim); }+ .bal-spin {+ display: inline-block;+ width: 8px; height: 8px;+ border: 1px solid currentColor;+ border-top-color: transparent;+ border-radius: 50%;+ animation: spin .6s linear infinite;+ vertical-align: middle;+ margin-right: 3px;+ }++ /* Fund alert banner */+ #fund-alert {+ margin: 0 12px 8px;+ padding: 9px 11px;+ border-radius: 8px;+ background: rgba(247,160,53,.07);+ border: 1px solid rgba(247,160,53,.2);+ font-size: 10.5px;+ color: var(--amber);+ line-height: 1.5;+ display: none;+ }+ #fund-alert strong { color: #fbbf24; }+ #fund-alert a { color: var(--amber); }+ #fund-alert .fund-addr {+ font-family: "SF Mono","Fira Code",monospace;+ font-size: 9.5px;+ word-break: break-all;+ margin-top: 4px;+ color: var(--text);+ display: block;+ }+ #fund-alert.visible { display: block; }++ /* Responsive */+ @media (max-width: 700px) {+ #root { grid-template-columns: 1fr; grid-template-rows: 45vh 1fr auto; }+ #col-buyer { display: none; }+ #col-seller { grid-row: 1; }+ #center { grid-row: 2; border: none; border-top: 1px solid var(--border); }+ #bottom-bar { grid-row: 3; grid-column: 1; }+ }++ /* Noscript */+ noscript > div { position: fixed; inset: 0; z-index: 9999; display: flex; align-items: center; justify-content: center; padding: 24px; background: var(--bg); text-align: center; }+ </style>+</head>+<body>+ <noscript>+ <div>+ <div>+ <h1 style="font-size:24px;font-weight:600;color:#fff;margin-bottom:10px">Agent Economy</h1>+ <p style="color:#5c6180;max-width:400px;margin:0 auto 20px">Two 3D AI agents transacting on-chain. This interactive demo requires JavaScript.</p>+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:8px;background:#4e8cff;color:#fff;text-decoration:none;font-size:14px">Read the docs</a>+ </div>+ </div>+ </noscript>++ <div id="root">+ <!-- Agent A — Nova (buyer) -->+ <div class="av-col" id="col-buyer">+ <div class="av-loading" id="loading-buyer"><div class="av-spinner"></div></div>+ <iframe id="frame-buyer" class="av-frame" title="Nova — AI Agent (Buyer)" allow="autoplay; microphone" loading="lazy"></iframe>+ <div class="av-speech" id="speech-buyer"></div>+ <div class="av-label">+ <div class="av-label-name">Nova</div>+ <div class="av-label-role">Buyer Agent</div>+ <div class="av-label-addr" id="buyer-addr">—</div>+ <div class="av-label-bal bal-unknown" id="buyer-bal"><span class="bal-spin"></span></div>+ </div>+ </div>++ <!-- Center: service catalog + tx feed -->+ <div id="center">+ <div id="center-head">+ <h1><span class="live-dot"></span> Agent Economy</h1>+ <div id="center-sub">Agents paying agents · Real SOL · Solana mainnet</div>+ </div>++ <div id="fund-alert"></div>++ <div id="catalog">+ <div id="catalog-label">Services offered by Oracle</div>+ <button class="svc-btn" data-service="market-analysis">+ <div class="svc-btn-left">+ <span class="svc-btn-name">Market Analysis</span>+ <span class="svc-btn-tag">Live sentiment + trend read</span>+ </div>+ <span class="svc-btn-price">$0.001</span>+ </button>+ <button class="svc-btn" data-service="onchain-insight">+ <div class="svc-btn-left">+ <span class="svc-btn-name">On-Chain Insight</span>+ <span class="svc-btn-tag">Wallet activity + holder data</span>+ </div>+ <span class="svc-btn-price">$0.002</span>+ </button>+ <button class="svc-btn" data-service="risk-score">+ <div class="svc-btn-left">+ <span class="svc-btn-name">Risk Score</span>+ <span class="svc-btn-tag">AI-generated protocol rating</span>+ </div>+ <span class="svc-btn-price">$0.003</span>+ </button>+ </div>++ <div id="topic-wrap">+ <input id="topic" type="text" placeholder="Topic (optional) — e.g. Solana, JUP, pump.fun" maxlength="120" autocomplete="off" spellcheck="false" />+ </div>++ <div id="feed">+ <div id="feed-empty">+ <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">+ <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>+ </svg>+ <span>Pick a service above to watch the agents transact</span>+ </div>+ </div>++ <div id="status-bar">+ <span id="status-text">Ready — select a service to start</span>+ <span id="tx-count"></span>+ </div>+ </div>++ <!-- Agent B — Oracle (seller) -->+ <div class="av-col" id="col-seller">+ <div class="av-loading" id="loading-seller"><div class="av-spinner"></div></div>+ <iframe id="frame-seller" class="av-frame" title="Oracle — AI Agent (Seller)" allow="autoplay; microphone" loading="lazy"></iframe>+ <div class="av-speech" id="speech-seller"></div>+ <div class="av-label">+ <div class="av-label-name">Oracle</div>+ <div class="av-label-role">Data Seller Agent</div>+ <div class="av-label-addr" id="seller-addr">—</div>+ <div class="av-label-bal bal-unknown" id="seller-bal"><span class="bal-spin"></span></div>+ </div>+ </div>++ <div id="bottom-bar">+ <a href="/ibm">IBM showcase</a>+ <span class="sep">·</span>+ <a href="/x402">x402 Bazaar</a>+ <span class="sep">·</span>+ <a href="https://three.ws" target="_blank" rel="noopener">three.ws</a>+ <span class="sep">·</span>+ <span>Agent-to-agent value transfer · Solana</span>+ </div>+ </div>++ <script type="module" src="/src/agent-economy.js"></script>+</body>+</html>diff --git a/pages/agent-exchange.html b/pages/agent-exchange.htmlnew file mode 100644index 000000000..84a8558fe--- /dev/null+++ b/pages/agent-exchange.html@@ -0,0 +1,310 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />+ <title>Agent Exchange — 3D AI agents paying each other in real time · three.ws</title>+ <meta name="description" content="Two AI agents with 3D bodies negotiate and pay each other for live crypto intel using x402 micropayments on Solana. Every transaction is real and confirmed on-chain." />+ <link rel="canonical" href="https://three.ws/agent-exchange" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="Agent Exchange — AI agents paying each other in real time" />+ <meta property="og:description" content="Two 3D AI agents buy and sell crypto intel for real USDC on Solana. Watch every transaction confirm on-chain." />+ <meta property="og:url" content="https://three.ws/agent-exchange" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Agent Exchange — AI agents paying each other in real time" />+ <meta name="twitter:description" content="Two 3D AI agents paying each other for real crypto intel. USDC on Solana. On-chain." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #07080f;+ --bg2: #0d0f1a;+ --panel: rgba(16,19,34,0.88);+ --border: rgba(255,255,255,0.08);+ --border-hi:rgba(255,255,255,0.16);+ --text: #eceef8;+ --muted: #7c85a2;+ --faint: #484f64;+ --sol: #9945ff;+ --sol-lt: #c284ff;+ --usdc: #2775ca;+ --usdc-lt: #6db0f7;+ --green: #22d77a;+ --amber: #f5a623;+ --red: #ff4f6a;+ --mono: ui-monospace,"SF Mono",Menlo,Consolas,monospace;+ --shadow: 0 24px 64px rgba(0,0,0,0.7);+ --r: 14px;+ }+ *,*::before,*::after { box-sizing:border-box; margin:0; padding:0; }+ html,body { height:100%; background:var(--bg); color:var(--text); -webkit-font-smoothing:antialiased; }+ body { font:15px/1.6 -apple-system,system-ui,"Segoe UI",sans-serif; overflow:hidden; }+ :focus-visible { outline:2px solid var(--sol-lt); outline-offset:3px; }++ /* ── Layout ──────────────────────────────────────────── */+ #app {+ display:grid;+ grid-template-rows: 52px 1fr auto;+ height:100%;+ }++ /* ── Top bar ─────────────────────────────────────────── */+ .topbar {+ display:flex; align-items:center; justify-content:space-between; gap:12px;+ padding:0 20px; border-bottom:1px solid var(--border);+ background:rgba(7,8,15,0.95); backdrop-filter:blur(12px);+ position:relative; z-index:20;+ }+ .brand { display:flex; align-items:center; gap:12px; }+ .brand a { color:var(--text); text-decoration:none; font-weight:700; font-size:15px; letter-spacing:-0.01em; }+ .brand .sep { color:var(--faint); }+ .badge {+ display:inline-flex; align-items:center; gap:7px;+ background:rgba(153,69,255,0.12); border:1px solid rgba(153,69,255,0.3);+ border-radius:99px; padding:4px 11px; font-size:12px; color:var(--sol-lt); font-weight:600;+ }+ .badge .dot { width:6px; height:6px; border-radius:50%; background:var(--sol); box-shadow:0 0 8px var(--sol); }+ .tb-right { display:flex; align-items:center; gap:10px; }+ .tx-ticker {+ display:inline-flex; align-items:center; gap:8px; font-size:12px;+ color:var(--muted); font-variant-numeric:tabular-nums;+ }+ .tx-ticker .tv { font-weight:650; color:var(--usdc-lt); font-size:13px; transition:color .3s; }+ .tx-ticker .tv.flash { color:var(--green); }+ .tb-btn {+ display:inline-flex; align-items:center; gap:6px; padding:6px 12px; border-radius:9px;+ background:rgba(255,255,255,0.05); border:1px solid var(--border); color:var(--muted);+ font:13px/1 inherit; font-weight:500; cursor:pointer; text-decoration:none;+ transition:background .15s, color .15s, border-color .15s;+ }+ .tb-btn:hover { background:rgba(255,255,255,0.09); color:var(--text); border-color:var(--border-hi); }+ .tb-btn svg { width:14px; height:14px; }++ /* ── Arena ───────────────────────────────────────────── */+ #arena {+ position:relative; overflow:hidden;+ background:+ radial-gradient(ellipse 80% 60% at 50% 100%, rgba(153,69,255,0.08), transparent 70%),+ radial-gradient(ellipse 60% 40% at 20% 40%, rgba(39,117,202,0.06), transparent 60%),+ radial-gradient(ellipse 60% 40% at 80% 40%, rgba(39,117,202,0.06), transparent 60%),+ var(--bg2);+ }+ /* Subtle floor grid */+ #arena::before {+ content:''; position:absolute; inset:0; z-index:0;+ background-image:+ linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px),+ linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px);+ background-size:48px 48px;+ mask-image:radial-gradient(ellipse 90% 80% at 50% 80%, black 30%, transparent 80%);+ }++ /* Two avatar iframes side by side */+ .agents {+ position:relative; z-index:1;+ display:grid; grid-template-columns:1fr 1fr; height:100%; gap:0;+ }+ .agent-slot { position:relative; overflow:hidden; }+ .agent-slot iframe {+ position:absolute; inset:0; width:100%; height:100%;+ border:0; background:transparent;+ }+ /* Vertical divider glow between the two agents */+ .agents::after {+ content:''; position:absolute; top:0; bottom:0; left:50%;+ width:1px; background:linear-gradient(180deg, transparent 5%, rgba(153,69,255,0.4) 40%, rgba(39,117,202,0.4) 60%, transparent 95%);+ transform:translateX(-50%); z-index:5;+ }++ /* Agent name + role badges */+ .agent-label {+ position:absolute; top:16px; z-index:10;+ display:flex; align-items:center; gap:8px;+ background:rgba(7,8,15,0.72); backdrop-filter:blur(12px);+ border:1px solid var(--border); border-radius:99px; padding:5px 13px;+ font-size:12px; font-weight:600; white-space:nowrap;+ }+ .agent-label.left { left:14px; }+ .agent-label.right { right:14px; }+ .agent-label .role {+ font-size:10px; font-weight:700; letter-spacing:0.06em; text-transform:uppercase;+ padding:2px 7px; border-radius:99px;+ }+ .role.seller { background:rgba(39,117,202,0.18); color:var(--usdc-lt); border:1px solid rgba(39,117,202,0.3); }+ .role.buyer { background:rgba(153,69,255,0.18); color:var(--sol-lt); border:1px solid rgba(153,69,255,0.3); }++ /* Speech bubbles */+ .bubble {+ position:absolute; bottom:22%; z-index:10; max-width:240px;+ background:rgba(7,8,15,0.82); backdrop-filter:blur(12px);+ border:1px solid var(--border); border-radius:var(--r); padding:10px 13px;+ font-size:13px; line-height:1.45; opacity:0;+ transition:opacity .3s, transform .3s;+ transform:translateY(6px);+ }+ .bubble.show { opacity:1; transform:translateY(0); }+ .bubble.left { left:14px; border-bottom-left-radius:4px; }+ .bubble.right { right:14px; border-bottom-right-radius:4px; }+ .bubble .bname { font-size:10px; font-weight:700; letter-spacing:0.05em; text-transform:uppercase; color:var(--muted); margin-bottom:5px; }+ .bubble.left .bname { color:var(--usdc-lt); }+ .bubble.right .bname { color:var(--sol-lt); }++ /* ── Exchange panel (bottom) ─────────────────────────── */+ #exchange {+ border-top:1px solid var(--border); background:rgba(7,8,15,0.96);+ backdrop-filter:blur(20px); padding:14px 20px 20px;+ display:flex; flex-direction:column; gap:12px;+ }++ /* Topic selector */+ .topic-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }+ .topic-row .label { font-size:12px; font-weight:650; color:var(--muted); white-space:nowrap; }+ .topics { display:flex; gap:7px; flex-wrap:wrap; }+ .t-chip {+ font-size:12px; font-weight:600; padding:5px 13px; border-radius:99px; cursor:pointer;+ border:1px solid var(--border); background:rgba(255,255,255,0.04); color:var(--muted);+ transition:all .15s;+ }+ .t-chip:hover { border-color:var(--border-hi); color:var(--text); }+ .t-chip.active { background:rgba(153,69,255,0.16); border-color:rgba(153,69,255,0.45); color:var(--sol-lt); }++ /* Pay button */+ .pay-btn {+ align-self:flex-end; display:inline-flex; align-items:center; gap:9px;+ background:linear-gradient(135deg, var(--sol) 0%, #6e2adf 100%);+ color:#fff; border:0; border-radius:11px; padding:11px 22px;+ font:14px/1 inherit; font-weight:700; cursor:pointer; letter-spacing:0.01em;+ transition:filter .15s, transform .1s, box-shadow .15s;+ box-shadow:0 0 0 0 rgba(153,69,255,0);+ }+ .pay-btn:hover:not(:disabled) { filter:brightness(1.12); box-shadow:0 0 28px rgba(153,69,255,0.4); }+ .pay-btn:active:not(:disabled) { transform:translateY(1px); }+ .pay-btn:disabled { opacity:.55; cursor:default; box-shadow:none; filter:none; }+ .pay-btn .spin { width:14px; height:14px; border:2px solid rgba(255,255,255,0.35); border-top-color:#fff; border-radius:50%; animation:spin .65s linear infinite; display:none; }+ .pay-btn.busy .spin { display:inline-block; }+ @keyframes spin { to { transform:rotate(360deg); } }++ /* Payment stages */+ .stages { display:flex; gap:0; flex-wrap:nowrap; overflow-x:auto; scrollbar-width:none; }+ .stage {+ display:flex; align-items:center; gap:6px; padding:5px 12px;+ font-size:12px; font-weight:500; color:var(--faint); white-space:nowrap;+ border-right:1px solid var(--border);+ }+ .stage:last-child { border-right:0; }+ .stage .si { width:16px; height:16px; border-radius:50%; border:2px solid var(--faint); flex:none; transition:all .3s; display:flex; align-items:center; justify-content:center; }+ .stage.active { color:var(--text); }+ .stage.active .si { border-color:var(--sol-lt); box-shadow:0 0 8px var(--sol-lt); animation:pulse .9s ease-in-out infinite; }+ .stage.done { color:var(--green); }+ .stage.done .si { background:var(--green); border-color:var(--green); box-shadow:0 0 8px var(--green); }+ .stage.done .si::after { content:"✓"; font-size:9px; color:#000; font-weight:900; }+ .stage.error { color:var(--red); }+ .stage.error .si { border-color:var(--red); }+ .stage .sval { font-size:10.5px; color:var(--faint); font-variant-numeric:tabular-nums; }+ .stage.done .sval { color:var(--green); }+ @keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:.5; } }++ /* Receipt card */+ .receipt {+ background:rgba(34,215,122,0.06); border:1px solid rgba(34,215,122,0.22);+ border-radius:var(--r); padding:13px 15px; display:none;+ animation:rise .3s ease;+ }+ .receipt.show { display:block; }+ @keyframes rise { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }+ .receipt .r-head { display:flex; align-items:center; justify-content:space-between; margin-bottom:9px; }+ .receipt .r-badge { font-size:12px; font-weight:700; color:var(--green); display:flex; align-items:center; gap:6px; }+ .receipt .r-time { font-size:11px; color:var(--faint); }+ .receipt .r-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:8px 20px; }+ .receipt .rf { display:flex; flex-direction:column; gap:1px; }+ .receipt .rf .k { font-size:10px; text-transform:uppercase; letter-spacing:0.09em; color:var(--faint); font-weight:650; }+ .receipt .rf .v { font-size:13px; font-weight:600; font-variant-numeric:tabular-nums; }+ .receipt .rf .v a { color:var(--usdc-lt); text-decoration:none; }+ .receipt .rf .v a:hover { text-decoration:underline; }+ .receipt .r-headline { margin-top:10px; padding-top:10px; border-top:1px solid rgba(34,215,122,0.12); font-size:13.5px; line-height:1.5; }+ .receipt .r-signal { display:inline-flex; align-items:center; gap:6px; font-size:11px; font-weight:700; padding:2px 9px; border-radius:99px; margin-right:6px; }+ .signal-bullish { background:rgba(34,215,122,0.15); color:var(--green); border:1px solid rgba(34,215,122,0.3); }+ .signal-bearish { background:rgba(255,79,106,0.13); color:var(--red); border:1px solid rgba(255,79,106,0.3); }+ .signal-neutral { background:rgba(245,166,35,0.13); color:var(--amber); border:1px solid rgba(245,166,35,0.3); }++ /* ── Mobile ──────────────────────────────────────────── */+ @media (max-width:640px) {+ #app { grid-template-rows: 48px 1fr auto; }+ .agents { grid-template-columns:1fr 1fr; }+ .bubble { display:none; }+ .exchange { padding:10px 14px 16px; }+ .topics .t-chip:nth-child(n+5) { display:none; }+ .pay-btn { align-self:stretch; justify-content:center; }+ }+ @media (prefers-reduced-motion:reduce) { .pay-btn.busy .spin,.stage.active .si { animation:none; } }+ </style>+</head>+<body>+<div id="app">++ <!-- ── Top bar ────────────────────────────────────────── -->+ <header class="topbar">+ <div class="brand">+ <a href="/">three.ws</a>+ <span class="sep">/</span>+ <span class="badge"><span class="dot"></span>Agent Exchange</span>+ </div>+ <div class="tb-right">+ <span class="tx-ticker" id="txTicker">+ Session total: <span class="tv" id="totalUsdc">$0.00</span> USDC settled on-chain+ </span>+ <a class="tb-btn" href="/pay" title="x402 pay-per-call demo">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>+ x402 demo+ </a>+ <a class="tb-btn" href="/ibm/trust-layer" title="IBM Granite Guardian Trust Layer">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>+ Trust Layer+ </a>+ </div>+ </header>++ <!-- ── Arena: two agents face each other ─────────────── -->+ <section id="arena" aria-label="Two AI agents">+ <div class="agents">+ <!-- Agent A: Seller (left, faces right) -->+ <div class="agent-slot" id="slotA">+ <iframe id="frameA" title="Intel agent" allow="autoplay" aria-label="Selling agent"></iframe>+ </div>+ <!-- Agent B: Buyer (right, faces left) -->+ <div class="agent-slot" id="slotB">+ <iframe id="frameB" title="Buyer agent" allow="autoplay" aria-label="Buying agent"></iframe>+ </div>+ </div>++ <div class="agent-label left" id="labelA"><span id="nameA">Intel Agent</span> <span class="role seller">SELLER</span></div>+ <div class="agent-label right" id="labelB"><span id="nameB">Buyer Agent</span> <span class="role buyer">BUYER</span></div>+ <div class="bubble left" id="bubbleA"><div class="bname">Intel Agent</div><div id="bubbleAText"></div></div>+ <div class="bubble right" id="bubbleB"><div class="bname">Buyer Agent</div><div id="bubbleBText"></div></div>+ </section>++ <!-- ── Exchange controls ─────────────────────────────── -->+ <section id="exchange" aria-label="Exchange controls">+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">+ <div class="topic-row">+ <span class="label">Buy intel on:</span>+ <div class="topics" id="topics" role="group" aria-label="Topic selection"></div>+ </div>+ <button class="pay-btn" id="payBtn" type="button">+ <span class="spin" aria-hidden="true"></span>+ <span class="lbl">Buy intel — $0.01 USDC</span>+ </button>+ </div>++ <div class="stages" id="stages" aria-label="Payment stages" aria-live="polite"></div>++ <div class="receipt" id="receipt" aria-live="polite"></div>+ </section>++</div>+<script type="module" src="/src/agent-exchange.js"></script>+<script src="/brand.js" defer></script>+</body>+</html>diff --git a/pages/agent-trade.html b/pages/agent-trade.htmlnew file mode 100644index 000000000..4354be693--- /dev/null+++ b/pages/agent-trade.html@@ -0,0 +1,269 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Agent Commerce · three.ws</title>+ <meta name="description" content="Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, in 3D.">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">+ <style>+ :root {+ --blue: #4589ff;+ --teal: #08bdba;+ --gold: #f1c21b;+ --green: #42be65;+ --red: #fa4d56;+ --bg: #05050e;+ --surface: rgba(13,13,26,0.92);+ --surface2: rgba(22,22,40,0.85);+ --border: rgba(255,255,255,0.08);+ --text: #f4f4f4;+ --muted: #8d8d8d;+ --font: 'IBM Plex Sans', system-ui, sans-serif;+ --mono: 'IBM Plex Mono', monospace;+ --radius: 12px;+ }+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }+ html, body { width: 100%; height: 100%; overflow: hidden; background: var(--bg); font-family: var(--font); color: var(--text); }++ #canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }++ /* ── Header ──────────────────────────────────────────────────────────── */+ #header {+ position: fixed; top: 0; left: 0; right: 0; z-index: 10;+ display: flex; align-items: center; gap: 12px; padding: 14px 22px;+ background: linear-gradient(to bottom, rgba(5,5,14,0.92) 0%, transparent 100%);+ }+ #header a { color: var(--text); text-decoration: none; font-weight: 600; font-size: 1.05rem; }+ #header a span { color: var(--teal); }+ .hbadge {+ padding: 3px 9px; border-radius: 20px; font-size: 0.68rem;+ font-family: var(--mono); letter-spacing: 0.06em;+ }+ .hbadge-x402 { background: rgba(69,137,255,0.14); border: 1px solid rgba(69,137,255,0.3); color: var(--blue); }+ .hbadge-sol { background: rgba(8,189,186,0.1); border: 1px solid rgba(8,189,186,0.3); color: var(--teal); }+ #hright { margin-left: auto; display: flex; align-items: center; gap: 10px; }+ #networkBadge {+ padding: 3px 8px; border-radius: 20px; font-size: 0.68rem; font-family: var(--mono);+ text-transform: uppercase; background: rgba(241,194,27,0.1);+ border: 1px solid rgba(241,194,27,0.3); color: var(--gold);+ }+ #liveDot { width: 6px; height: 6px; border-radius: 50%; background: var(--green); box-shadow: 0 0 8px var(--green); animation: blink 1.6s infinite; }+ @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.35} }++ /* ── Agent labels (tracked to 3D positions by JS) ─────────────────── */+ .agent-label {+ position: fixed; display: flex; flex-direction: column; align-items: center;+ gap: 3px; pointer-events: none; z-index: 6; transition: opacity 0.4s;+ text-align: center;+ }+ .al-name { font-size: 1rem; font-weight: 600; letter-spacing: 0.02em; }+ .al-role { font-size: 0.67rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.1em; }+ .al-addr { font-size: 0.62rem; color: var(--muted); font-family: var(--mono); }+ .al-bal { font-size: 0.75rem; font-family: var(--mono); }+ #buyerLabel .al-name { color: var(--blue); }+ #sellerLabel .al-name { color: var(--gold); }++ /* ── Speech bubbles ───────────────────────────────────────────────── */+ .bubble {+ position: fixed; max-width: 210px; padding: 10px 14px; border-radius: 16px;+ font-size: 0.82rem; line-height: 1.5; backdrop-filter: blur(14px);+ z-index: 20; pointer-events: none; text-align: center;+ transition: opacity 0.3s, transform 0.3s;+ }+ .bubble.hidden { opacity: 0; transform: translateY(8px); }+ #buyerBubble { background: rgba(69,137,255,0.15); border: 1px solid rgba(69,137,255,0.35); }+ #sellerBubble { background: rgba(241,194,27,0.1); border: 1px solid rgba(241,194,27,0.35); }++ /* ── Central floating card ─────────────────────────────────────────── */+ #centralCard {+ position: fixed; left: 50%; transform: translateX(-50%);+ top: 50%; margin-top: -40px; width: 360px;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); backdrop-filter: blur(18px);+ padding: 18px 22px; z-index: 20;+ transition: opacity 0.35s, transform 0.35s;+ }+ #centralCard.hidden { opacity: 0; transform: translateX(-50%) translateY(14px); pointer-events: none; }+ .c-badge {+ display: inline-flex; align-items: center; gap: 6px;+ padding: 3px 10px; border-radius: 20px; font-size: 0.67rem;+ font-family: var(--mono); letter-spacing: 0.05em; margin-bottom: 10px;+ }+ .c-badge-402 { background: rgba(250,77,86,0.1); border: 1px solid rgba(250,77,86,0.3); color: #fa4d56; }+ .c-badge-ok { background: rgba(66,190,101,0.1); border: 1px solid rgba(66,190,101,0.3); color: var(--green); }+ .c-label { font-size: 0.67rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin-bottom: 6px; font-family: var(--mono); }+ .c-price { font-size: 1.7rem; font-weight: 600; font-family: var(--mono); margin: 8px 0 4px; }+ .c-price.blue { color: var(--blue); }+ .c-price.green { color: var(--green); }+ .c-row { display: flex; justify-content: space-between; align-items: center; font-size: 0.8rem; color: var(--muted); margin-bottom: 5px; }+ .c-row span { color: var(--text); font-family: var(--mono); font-size: 0.75rem; }+ .c-link { color: var(--blue); font-family: var(--mono); font-size: 0.7rem; text-decoration: none; word-break: break-all; display: block; margin-top: 8px; }+ .c-link:hover { text-decoration: underline; }+ .c-content { font-size: 0.86rem; line-height: 1.65; color: var(--text); margin-top: 8px; }+ .c-powered { margin-top: 12px; font-size: 0.67rem; color: var(--muted); font-family: var(--mono); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }++ /* ── Step log ──────────────────────────────────────────────────────── */+ #stepLog {+ position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%);+ display: flex; gap: 7px; flex-wrap: wrap; justify-content: center;+ z-index: 10; max-width: 600px;+ }+ .step-chip {+ padding: 4px 11px; border-radius: 20px; font-size: 0.68rem;+ font-family: var(--mono); border: 1px solid var(--border);+ color: var(--muted); background: var(--surface); backdrop-filter: blur(8px);+ transition: all 0.25s;+ }+ .step-chip.active { color: var(--text); border-color: var(--blue); background: rgba(69,137,255,0.1); }+ .step-chip.done { color: var(--green); border-color: rgba(66,190,101,0.35); background: rgba(66,190,101,0.06); }+ .step-chip.error { color: var(--red); border-color: rgba(250,77,86,0.35); }++ /* ── CTA bar ────────────────────────────────────────────────────────── */+ #cta {+ position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%);+ display: flex; align-items: center; gap: 10px; z-index: 10;+ }+ #topicSelect {+ padding: 9px 14px; background: var(--surface); border: 1px solid var(--border);+ border-radius: 8px; color: var(--text); font-family: var(--font);+ font-size: 0.86rem; cursor: pointer; backdrop-filter: blur(10px);+ min-width: 200px; appearance: none;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%238d8d8d' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");+ background-repeat: no-repeat; background-position: right 12px center;+ padding-right: 32px;+ }+ #topicSelect:disabled { opacity: 0.45; cursor: default; }+ #startBtn {+ padding: 10px 24px; background: var(--blue); color: #fff;+ border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 500;+ cursor: pointer; font-family: var(--font); transition: background 0.18s, transform 0.1s;+ white-space: nowrap;+ }+ #startBtn:hover:not(:disabled) { background: #6ea6ff; }+ #startBtn:active { transform: scale(0.97); }+ #startBtn:disabled { opacity: 0.45; cursor: default; }++ /* ── Toast ──────────────────────────────────────────────────────────── */+ #toast {+ position: fixed; bottom: 88px; left: 50%; transform: translateX(-50%);+ background: rgba(250,77,86,0.14); border: 1px solid rgba(250,77,86,0.4);+ color: #fa4d56; padding: 10px 20px; border-radius: 8px;+ font-size: 0.83rem; z-index: 30; opacity: 0;+ transition: opacity 0.3s; pointer-events: none; max-width: 420px; text-align: center;+ }+ #toast.show { opacity: 1; }++ /* ── Not-configured overlay ─────────────────────────────────────────── */+ #notConfigured {+ position: fixed; inset: 0; display: flex; align-items: center; justify-content: center;+ background: rgba(5,5,14,0.94); z-index: 50; padding: 24px;+ }+ #notConfigured.hidden { display: none; }+ .cfg-card {+ background: var(--surface2); border: 1px solid var(--border); border-radius: var(--radius);+ padding: 28px 32px; max-width: 500px; width: 100%; backdrop-filter: blur(20px);+ }+ .cfg-card h2 { font-size: 1.2rem; margin-bottom: 8px; }+ .cfg-card p { color: var(--muted); font-size: 0.85rem; line-height: 1.65; margin-bottom: 18px; }+ .env-block {+ background: rgba(0,0,0,0.3); border: 1px solid var(--border); border-radius: 8px;+ padding: 14px 16px; font-family: var(--mono); font-size: 0.75rem; line-height: 2.1;+ }+ .env-k { color: var(--blue); }+ .env-c { color: #525252; }+ .cfg-gen {+ margin-top: 16px; font-size: 0.75rem; color: var(--muted); line-height: 1.7;+ }+ .cfg-gen code {+ font-family: var(--mono); font-size: 0.72rem;+ background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;+ }+ .cfg-close {+ margin-top: 18px; padding: 9px 20px; background: rgba(69,137,255,0.15);+ border: 1px solid rgba(69,137,255,0.35); color: var(--blue);+ border-radius: 8px; font-family: var(--font); font-size: 0.86rem;+ cursor: pointer; transition: background 0.18s;+ }+ .cfg-close:hover { background: rgba(69,137,255,0.25); }+ </style>+</head>+<body>+ <canvas id="canvas"></canvas>++ <!-- Header -->+ <div id="header">+ <a href="/"><span>three</span>.ws</a>+ <div class="hbadge hbadge-x402">x402</div>+ <div class="hbadge hbadge-sol">Solana</div>+ <div id="hright">+ <div id="liveDot"></div>+ <div id="networkBadge">mainnet</div>+ </div>+ </div>++ <!-- Agent labels (JS positions these over the 3D avatars) -->+ <div class="agent-label" id="buyerLabel">+ <div class="al-name">Nexus</div>+ <div class="al-role">Buyer Agent</div>+ <div class="al-addr" id="buyerAddr">—</div>+ <div class="al-bal" id="buyerBal"></div>+ </div>+ <div class="agent-label" id="sellerLabel">+ <div class="al-name">Oracle</div>+ <div class="al-role">Seller Agent</div>+ <div class="al-addr" id="sellerAddr">—</div>+ </div>++ <!-- Speech bubbles -->+ <div class="bubble hidden" id="buyerBubble"></div>+ <div class="bubble hidden" id="sellerBubble"></div>++ <!-- Central floating card (402 challenge → tx receipt → content) -->+ <div id="centralCard" class="hidden"></div>++ <!-- Step log -->+ <div id="stepLog"></div>++ <!-- CTA -->+ <div id="cta">+ <select id="topicSelect">+ <option value="Solana DeFi outlook">Solana DeFi outlook</option>+ <option value="BTC market sentiment">BTC market sentiment</option>+ <option value="Top pump.fun tokens">Top pump.fun tokens</option>+ <option value="Ethereum L2 landscape">Ethereum L2 landscape</option>+ <option value="AI agent token trends">AI agent token trends</option>+ </select>+ <button id="startBtn">▶ Run Trade Demo</button>+ </div>++ <!-- Toast -->+ <div id="toast"></div>++ <!-- Not-configured overlay -->+ <div id="notConfigured" class="hidden">+ <div class="cfg-card">+ <h2>Fund two Solana wallets</h2>+ <p>Generate keypairs, set these env vars, and fund each wallet with a small amount of SOL to run the live agent-to-agent trade demo.</p>+ <div class="env-block">+ <div><span class="env-c"># Buyer agent (Nexus)</span></div>+ <div><span class="env-k">AGENT_BUYER_SECRET</span>=<base58-secret-key></div>+ <div><span class="env-c"># Seller agent (Oracle)</span></div>+ <div><span class="env-k">AGENT_SELLER_SECRET</span>=<base58-secret-key></div>+ <div><span class="env-c"># Trade price in SOL (default: 0.001)</span></div>+ <div><span class="env-k">AGENT_TRADE_PRICE_SOL</span>=0.001</div>+ <div><span class="env-c"># mainnet or devnet</span></div>+ <div><span class="env-k">AGENT_TRADE_NETWORK</span>=mainnet</div>+ </div>+ <p class="cfg-gen">+ Generate a keypair:<br>+ <code>node -e "const {Keypair}=require('@solana/web3.js'),bs58=require('bs58');const k=Keypair.generate();console.log('secret:',bs58.encode(k.secretKey),'addr:',k.publicKey.toString())"</code>+ </p>+ <button class="cfg-close" id="cfgClose">Dismiss (demo scene still visible)</button>+ </div>+ </div>++ <script type="module" src="/src/agent-trade.js"></script>+</body>+</html>diff --git a/pages/avatar-wallet-chat.html b/pages/avatar-wallet-chat.htmlindex c3029d748..0ac064b1c 100644--- a/pages/avatar-wallet-chat.html+++ b/pages/avatar-wallet-chat.html@@ -632,7 +632,56 @@} finally {busy = false;sendBtn.disabled = false;- input.focus();+// Receive detection: the avatar notices when SOL lands in its own wallet+ // (a tip from you) and reacts in real time — the "receiving" half of the+ // round-trip. Real on-chain data via /api/agent/activity; the first poll+ // seeds the seen-set so only NEW arrivals trigger a reaction.+ const seenSigs = new Set();+ let activitySeeded = false;+ function receiveCard(t) {+ clearEmpty();+ const card = document.createElement('div');+ card.className = 'pay ok recv';+ const from = t.counterparty ? short(t.counterparty) : 'someone';+ card.innerHTML =+ '<div class="head"><span class="ic">↓</span> Received SOL</div>' ++ '<div class="amt">' + fmtSol(t.sol) + ' SOL</div>' ++ '<div class="sub">' + (t.usd != null ? '≈ $' + t.usd.toFixed(2) + ' · ' : '') + 'from ' + from + '</div>' ++ '<div class="status"><span class="pip"></span><span class="label">Confirmed on-chain</span></div>';+ const a = document.createElement('a');+ a.className = 'sig';+ a.href = t.explorer; a.target = '_blank'; a.rel = 'noopener';+ a.textContent = '↗ ' + short(t.signature);+ card.appendChild(a);+ log.appendChild(card);+ log.scrollTop = log.scrollHeight;+ }+ async function pollActivity() {+ try {+ const r = await fetch('/api/agent/activity?limit=12', { headers: { accept: 'application/json' } });+ if (!r.ok) return;+ const data = await r.json();+ const transfers = data.transfers || [];+ if (!activitySeeded) {+ transfers.forEach((t) => seenSigs.add(t.signature));+ activitySeeded = true;+ return;+ }+ for (const t of [...transfers].reverse()) {+ if (seenSigs.has(t.signature)) continue;+ seenSigs.add(t.signature);+ if (t.direction !== 'in') continue;+ receiveCard(t);+ toast('Received ' + fmtSol(t.sol) + ' SOL' + (t.usd != null ? ' ($' + t.usd.toFixed(2) + ')' : ''));+ avatarSpeak('I just received ' + fmtSol(t.sol) + ' SOL' + (t.usd != null ? ', about $' + t.usd.toFixed(2) : '') + ' — thank you!');+ avatarGesture('celebrate');+ refreshWallet();+ }+ } catch (e) { /* transient RPC/network blip — next tick retries */ }+ }+ pollActivity();+ setInterval(pollActivity, 9000);+ input.focus();}}diff --git a/pages/deal.html b/pages/deal.htmlnew file mode 100644index 000000000..78b626321--- /dev/null+++ b/pages/deal.html@@ -0,0 +1,995 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Agent Deal — real on-chain AI payments · three.ws</title>+ <meta+ name="description"+ content="Two AI agents negotiate and settle a real Solana payment on-chain, live. Agent A pays Agent B for a market brief. Watch the blockchain transaction confirm in real time."+ />+ <meta name="theme-color" content="#080b14" />+ <meta property="og:title" content="Agent Deal — AI agents pay each other on-chain" />+ <meta+ property="og:description"+ content="Watch two 3D AI agents negotiate and settle a real Solana payment. The blockchain transaction is live."+ />+ <meta property="og:image" content="https://three.ws/og-agent-deal.png" />+ <meta property="og:type" content="website" />+ <meta name="twitter:card" content="summary_large_image" />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ --blue: #0f62fe;+ --blue-2: #4589ff;+ --blue-3: #78a9ff;+ --up: #42be65;+ --down: #fa4d56;+ --warn: #f1c21b;+ --ink: #f4f4f4;+ --muted: #8b95a9;+ --panel: rgba(10, 14, 26, 0.7);+ --stroke: rgba(120, 169, 255, 0.18);+ --stroke-2: rgba(120, 169, 255, 0.32);+ --font: 'IBM Plex Sans', system-ui, -apple-system, sans-serif;+ --mono: 'IBM Plex Mono', 'Fira Code', ui-monospace, monospace;+ --a-color: #4589ff;+ --b-color: #42be65;+ }+ * {+ box-sizing: border-box;+ }+ html,+ body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ }+ body {+ font-family: var(--font);+ color: var(--ink);+ background:+ radial-gradient(+ 1400px 800px at 20% -20%,+ rgba(15, 98, 254, 0.12) 0%,+ transparent 55%+ ),+ radial-gradient(+ 1000px 600px at 85% 110%,+ rgba(66, 190, 101, 0.1) 0%,+ transparent 55%+ ),+ #080b14;+ }++ /* ── Layout ── */+ .shell {+ display: grid;+ grid-template-rows: 56px 1fr;+ height: 100vh;+ }+ .topbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 0 22px;+ border-bottom: 1px solid var(--stroke);+ background: rgba(8, 11, 20, 0.6);+ backdrop-filter: blur(12px);+ z-index: 10;+ }+ .brand {+ display: flex;+ align-items: center;+ gap: 10px;+ font-weight: 600;+ font-size: 14px;+ letter-spacing: 0.01em;+ }+ .brand-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--blue);+ box-shadow: 0 0 10px var(--blue);+ }+ .brand small {+ color: var(--muted);+ font-weight: 400;+ }+ .topbar a {+ font-size: 13px;+ color: var(--muted);+ text-decoration: none;+ border: 1px solid var(--stroke);+ padding: 6px 12px;+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.03);+ transition:+ color 0.15s,+ border-color 0.15s;+ }+ .topbar a:hover {+ color: var(--ink);+ border-color: var(--blue-2);+ }++ .arena {+ display: grid;+ grid-template-columns: 1fr 340px 1fr;+ gap: 0;+ height: 100%;+ overflow: hidden;+ }++ /* ── Avatar columns ── */+ .agent-col {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: flex-start;+ padding: 24px 18px 18px;+ position: relative;+ }+ .agent-label {+ display: flex;+ align-items: center;+ gap: 9px;+ font-size: 13px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ margin-bottom: 14px;+ padding: 7px 14px;+ border-radius: 999px;+ border: 1px solid var(--stroke);+ background: var(--panel);+ backdrop-filter: blur(8px);+ }+ .agent-label .dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ flex: 0 0 auto;+ }+ .agent-a .dot {+ background: var(--a-color);+ box-shadow: 0 0 8px var(--a-color);+ }+ .agent-b .dot {+ background: var(--b-color);+ box-shadow: 0 0 8px var(--b-color);+ }+ .avatar-frame {+ flex: 1;+ width: 100%;+ max-height: calc(100vh - 180px);+ border: none;+ border-radius: 16px;+ overflow: hidden;+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid var(--stroke);+ }+ .wallet-chip {+ margin-top: 12px;+ font-family: var(--mono);+ font-size: 11px;+ color: var(--muted);+ background: var(--panel);+ border: 1px solid var(--stroke);+ border-radius: 8px;+ padding: 8px 12px;+ width: 100%;+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: space-between;+ }+ .wallet-chip .addr {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .wallet-chip .balance {+ flex: 0 0 auto;+ color: var(--ink);+ font-weight: 600;+ }+ .wallet-chip .balance.loading {+ opacity: 0.4;+ }+ .wallet-chip a {+ flex: 0 0 auto;+ color: var(--blue-3);+ text-decoration: none;+ font-size: 10px;+ }++ /* ── Deal feed (center) ── */+ .feed-col {+ display: flex;+ flex-direction: column;+ padding: 18px 0 18px;+ border-left: 1px solid var(--stroke);+ border-right: 1px solid var(--stroke);+ overflow: hidden;+ }+ .feed-header {+ padding: 0 18px 14px;+ border-bottom: 1px solid var(--stroke);+ display: flex;+ align-items: center;+ gap: 10px;+ flex: 0 0 auto;+ }+ .feed-title {+ font-size: 13px;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--blue-3);+ }+ .feed-badge {+ font-size: 11px;+ color: var(--muted);+ background: rgba(120, 169, 255, 0.08);+ border: 1px solid var(--stroke);+ border-radius: 6px;+ padding: 3px 8px;+ }++ .messages {+ flex: 1;+ overflow-y: auto;+ padding: 14px 18px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ scroll-behavior: smooth;+ }+ .messages::-webkit-scrollbar {+ width: 4px;+ }+ .messages::-webkit-scrollbar-track {+ background: transparent;+ }+ .messages::-webkit-scrollbar-thumb {+ background: var(--stroke-2);+ border-radius: 4px;+ }++ .msg {+ display: flex;+ gap: 9px;+ animation: msgIn 0.22s ease both;+ }+ @keyframes msgIn {+ from {+ opacity: 0;+ transform: translateY(6px);+ }+ to {+ opacity: 1;+ transform: none;+ }+ }+ .msg-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ flex: 0 0 auto;+ margin-top: 5px;+ }+ .msg.A .msg-dot {+ background: var(--a-color);+ box-shadow: 0 0 6px var(--a-color);+ }+ .msg.B .msg-dot {+ background: var(--b-color);+ box-shadow: 0 0 6px var(--b-color);+ }+ .msg-body {+ flex: 1;+ min-width: 0;+ }+ .msg-name {+ font-size: 10.5px;+ font-weight: 700;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ margin-bottom: 3px;+ }+ .msg.A .msg-name {+ color: var(--a-color);+ }+ .msg.B .msg-name {+ color: var(--b-color);+ }+ .msg-text {+ font-size: 13.5px;+ line-height: 1.5;+ color: var(--ink);+ }++ /* Quote card */+ .quote-card {+ background: rgba(15, 98, 254, 0.08);+ border: 1px solid rgba(120, 169, 255, 0.25);+ border-radius: 12px;+ padding: 12px 14px;+ animation: msgIn 0.22s ease both;+ }+ .quote-card .ql {+ font-size: 10.5px;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--blue-3);+ margin-bottom: 8px;+ }+ .quote-card .qservice {+ font-size: 13px;+ font-weight: 600;+ margin-bottom: 10px;+ }+ .quote-card .qrow {+ display: flex;+ justify-content: space-between;+ font-size: 12px;+ color: var(--muted);+ margin-bottom: 4px;+ }+ .quote-card .qrow .val {+ font-family: var(--mono);+ color: var(--ink);+ font-weight: 600;+ }++ /* Paying indicator */+ .paying-card {+ background: rgba(241, 194, 27, 0.07);+ border: 1px solid rgba(241, 194, 27, 0.22);+ border-radius: 12px;+ padding: 12px 14px;+ animation: msgIn 0.22s ease both;+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .paying-pulse {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ background: var(--warn);+ animation: payPulse 0.8s infinite ease-in-out;+ flex: 0 0 auto;+ }+ @keyframes payPulse {+ 0%,+ 100% {+ transform: scale(0.7);+ opacity: 0.5;+ }+ 50% {+ transform: scale(1.2);+ opacity: 1;+ }+ }+ .paying-text {+ font-size: 13px;+ color: var(--ink);+ }+ .paying-text .detail {+ font-size: 11px;+ color: var(--muted);+ font-family: var(--mono);+ margin-top: 3px;+ }++ /* Transaction confirmed card */+ .tx-card {+ background: rgba(66, 190, 101, 0.07);+ border: 1px solid rgba(66, 190, 101, 0.28);+ border-radius: 12px;+ padding: 14px 16px;+ animation: txIn 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) both;+ }+ @keyframes txIn {+ from {+ opacity: 0;+ transform: scale(0.94) translateY(8px);+ }+ to {+ opacity: 1;+ transform: none;+ }+ }+ .tx-card .tx-header {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 10px;+ }+ .tx-check {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--up);+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 auto;+ font-size: 12px;+ }+ .tx-label {+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--up);+ }+ .tx-card .tx-row {+ display: flex;+ justify-content: space-between;+ font-size: 12px;+ color: var(--muted);+ margin-bottom: 5px;+ }+ .tx-card .tx-row .val {+ font-family: var(--mono);+ color: var(--ink);+ font-weight: 600;+ word-break: break-all;+ text-align: right;+ max-width: 60%;+ }+ .tx-card .tx-link {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-top: 10px;+ padding-top: 10px;+ border-top: 1px solid rgba(66, 190, 101, 0.18);+ font-size: 12px;+ font-weight: 600;+ color: var(--up);+ text-decoration: none;+ transition: opacity 0.15s;+ }+ .tx-card .tx-link:hover {+ opacity: 0.8;+ }+ .tx-link svg {+ width: 12px;+ height: 12px;+ }++ /* Brief delivery card */+ .brief-card {+ background: rgba(120, 169, 255, 0.06);+ border: 1px solid var(--stroke-2);+ border-radius: 12px;+ padding: 14px 16px;+ animation: msgIn 0.22s ease both;+ }+ .brief-card .brief-header {+ font-size: 10.5px;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--blue-3);+ margin-bottom: 8px;+ display: flex;+ align-items: center;+ gap: 8px;+ justify-content: space-between;+ }+ .brief-card .source {+ font-size: 10px;+ color: var(--muted);+ letter-spacing: 0;+ text-transform: none;+ }+ .brief-card .brief-text {+ font-size: 14px;+ line-height: 1.6;+ color: var(--ink);+ }++ /* Error */+ .err-card {+ background: rgba(250, 77, 86, 0.07);+ border: 1px solid rgba(250, 77, 86, 0.25);+ border-radius: 12px;+ padding: 12px 14px;+ font-size: 13px;+ color: var(--ink);+ animation: msgIn 0.22s ease both;+ }+ .err-card .err-head {+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--down);+ margin-bottom: 5px;+ }+ .err-card .fund-hint {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--muted);+ margin-top: 8px;+ word-break: break-all;+ }+ .err-card a {+ color: var(--blue-3);+ }++ /* Controls */+ .controls {+ flex: 0 0 auto;+ padding: 12px 18px 0;+ border-top: 1px solid var(--stroke);+ }+ .run-btn {+ width: 100%;+ padding: 11px;+ font: inherit;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: #fff;+ background: var(--blue);+ border: none;+ border-radius: 10px;+ cursor: pointer;+ transition:+ background 0.15s,+ opacity 0.15s,+ transform 0.12s;+ }+ .run-btn:hover {+ background: var(--blue-2);+ }+ .run-btn:active {+ transform: translateY(1px);+ }+ .run-btn:disabled {+ opacity: 0.45;+ cursor: progress;+ }+ .run-status {+ text-align: center;+ font-size: 11.5px;+ color: var(--muted);+ margin-top: 7px;+ min-height: 1.2em;+ }+ .run-status.busy::after {+ content: '';+ display: inline-block;+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--blue-3);+ margin-left: 5px;+ animation: pulse 0.9s infinite;+ }+ @keyframes pulse {+ 0%,+ 100% {+ opacity: 0.3;+ }+ 50% {+ opacity: 1;+ }+ }+ .run-count {+ text-align: center;+ font-size: 11px;+ color: var(--muted);+ margin-top: 4px;+ letter-spacing: 0.04em;+ }++ /* Empty state */+ .empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ color: var(--muted);+ text-align: center;+ padding: 20px;+ }+ .empty .icon {+ font-size: 28px;+ opacity: 0.4;+ }+ .empty p {+ font-size: 13px;+ line-height: 1.5;+ max-width: 240px;+ margin: 0;+ }++ @media (max-width: 900px) {+ .arena {+ grid-template-columns: 1fr;+ grid-template-rows: auto 1fr;+ overflow-y: auto;+ }+ .agent-col {+ display: none;+ }+ .feed-col {+ border: none;+ height: calc(100vh - 56px);+ }+ }+ </style>+ </head>+ <body>+ <div class="shell">+ <header class="topbar">+ <div class="brand">+ <span class="brand-dot"></span>+ <span>Agent Deal</span>+ <small>real Solana · x402</small>+ </div>+ <a href="/">← three.ws</a>+ </header>++ <div class="arena">+ <!-- Agent A -->+ <div class="agent-col agent-a">+ <div class="agent-label">+ <span class="dot"></span>+ <span>Agent A · Reporter</span>+ </div>+ <iframe+ id="frame-a"+ class="avatar-frame"+ title="Agent A avatar"+ allow="autoplay"+ src="/avatar-embed.html?bg=dark&kiosk=1&hideChrome=1"+ ></iframe>+ <div class="wallet-chip">+ <span class="addr" id="addr-a">loading…</span>+ <span class="balance loading" id="bal-a">— SOL</span>+ <a id="link-a" href="#" target="_blank" rel="noopener">↗</a>+ </div>+ </div>++ <!-- Deal feed -->+ <div class="feed-col">+ <div class="feed-header">+ <span class="feed-title">Deal Feed</span>+ <span class="feed-badge" id="deal-badge">ready</span>+ </div>++ <div id="messages" class="messages">+ <div class="empty">+ <div class="icon">⇌</div>+ <p>+ Two AI agents negotiate and settle a real Solana payment. Hit Run+ Deal to start.+ </p>+ </div>+ </div>++ <div class="controls">+ <button id="run-btn" class="run-btn">Run Deal</button>+ <div id="run-status" class="run-status"></div>+ <div id="run-count" class="run-count"></div>+ </div>+ </div>++ <!-- Agent B -->+ <div class="agent-col agent-b">+ <div class="agent-label">+ <span class="dot"></span>+ <span>Agent B · Oracle</span>+ </div>+ <iframe+ id="frame-b"+ class="avatar-frame"+ title="Agent B avatar"+ allow="autoplay"+ src="/avatar-embed.html?bg=dark&kiosk=1&hideChrome=1"+ ></iframe>+ <div class="wallet-chip">+ <span class="addr" id="addr-b">—</span>+ <span class="balance" id="bal-b">receiving</span>+ <a id="link-b" href="#" target="_blank" rel="noopener">↗</a>+ </div>+ </div>+ </div>+ </div>++ <script type="module">+ // Deal feed client — consumes SSE from /api/pay/deal and renders the+ // negotiation, payment, and delivery events live.++ const $ = (id) => document.getElementById(id);+ const messages = $('messages');+ const runBtn = $('run-btn');+ const runStatus = $('run-status');+ const runCount = $('run-count');+ const dealBadge = $('deal-badge');+ const frameA = $('frame-a');+ const frameB = $('frame-b');++ // ── Avatar speech via postMessage to the embed iframes ──────────────+ const origin = location.origin;+ const readyA = { ready: false };+ const readyB = { ready: false };++ function avatarReady(frame, state) {+ frame.contentWindow?.postMessage({ type: 'v1.avatar.hello' }, origin);+ state.ready = true;+ }+ frameA.addEventListener('load', () => avatarReady(frameA, readyA));+ frameB.addEventListener('load', () => avatarReady(frameB, readyB));++ window.addEventListener('message', (e) => {+ if (e.source === frameA.contentWindow && e.data?.type === 'v1.avatar.ready')+ readyA.ready = true;+ if (e.source === frameB.contentWindow && e.data?.type === 'v1.avatar.ready')+ readyB.ready = true;+ });++ function speak(frame, state, text) {+ if (!text) return;+ if (state.ready) {+ frame.contentWindow?.postMessage({ type: 'v1.avatar.speak', text }, origin);+ } else {+ try {+ const u = new SpeechSynthesisUtterance(text.slice(0, 200));+ u.rate = 1;+ window.speechSynthesis?.speak(u);+ } catch {}+ }+ }++ function emote(frame, state, trigger) {+ if (!state.ready || !trigger) return;+ frame.contentWindow?.postMessage(+ { type: 'v1.avatar.emote', name: trigger, weight: 1 },+ origin,+ );+ }++ // ── Feed rendering ───────────────────────────────────────────────────+ let dealCount = 0;+ let running = false;++ function clearFeed() {+ messages.innerHTML = '';+ }++ function appendMsg(speaker, text) {+ const el = document.createElement('div');+ el.className = `msg ${speaker}`;+ el.innerHTML = `+ <span class="msg-dot"></span>+ <div class="msg-body">+ <div class="msg-name">Agent ${speaker}</div>+ <div class="msg-text">${escHtml(text)}</div>+ </div>`;+ messages.appendChild(el);+ messages.scrollTop = messages.scrollHeight;+ return el;+ }++ function appendCard(html) {+ const el = document.createElement('div');+ el.innerHTML = html;+ messages.appendChild(el.firstElementChild);+ messages.scrollTop = messages.scrollHeight;+ }++ function escHtml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+ }++ const fmtSol = (n) => Number(n).toFixed(6);+ const addrShort = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');++ // ── Quote card ───────────────────────────────────────────────────────+ function renderQuote(d) {+ appendCard(`+ <div class="quote-card">+ <div class="ql">Service Quote</div>+ <div class="qservice">${escHtml(d.service)}</div>+ <div class="qrow"><span>Amount</span><span class="val">${fmtSol(d.sol)} SOL</span></div>+ <div class="qrow"><span>USD equivalent</span><span class="val">$${Number(d.usd).toFixed(2)}</span></div>+ <div class="qrow"><span>From</span><span class="val">${addrShort(d.from)}</span></div>+ <div class="qrow"><span>To</span><span class="val">${addrShort(d.to)}</span></div>+ </div>`);+ }++ // ── Paying card ──────────────────────────────────────────────────────+ function renderPaying(d) {+ appendCard(`+ <div class="paying-card">+ <div class="paying-pulse"></div>+ <div class="paying-text">+ Signing & broadcasting ${fmtSol(d.sol)} SOL on-chain…+ <div class="detail">${addrShort(d.from)} → ${addrShort(d.to)}</div>+ </div>+ </div>`);+ }++ // ── Transaction confirmed card ────────────────────────────────────────+ function renderPaid(d) {+ appendCard(`+ <div class="tx-card">+ <div class="tx-header">+ <div class="tx-check">✓</div>+ <div class="tx-label">Transaction Confirmed</div>+ </div>+ <div class="tx-row"><span>Signature</span><span class="val">${escHtml(d.signature.slice(0, 20))}…</span></div>+ <div class="tx-row"><span>Amount</span><span class="val">${fmtSol(d.sol)} SOL · $${Number(d.usd).toFixed(2)}</span></div>+ <div class="tx-row"><span>Network</span><span class="val">${escHtml(d.network)}</span></div>+ <a class="tx-link" href="${escHtml(d.explorer)}" target="_blank" rel="noopener">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>+ View on Solscan+ </a>+ </div>`);+ }++ // ── Brief delivery card ───────────────────────────────────────────────+ function renderDeliver(d) {+ appendCard(`+ <div class="brief-card">+ <div class="brief-header">+ <span>${escHtml(d.service)}</span>+ <span class="source">${escHtml(d.source)}</span>+ </div>+ <div class="brief-text">${escHtml(d.brief)}</div>+ </div>`);+ }++ // ── Error card ────────────────────────────────────────────────────────+ function renderError(d) {+ const fundLine = d.fundAddress+ ? `<div class="fund-hint">Fund address: <a href="${escHtml(d.fundUrl || '#')}" target="_blank">${escHtml(d.fundAddress)}</a></div>`+ : '';+ appendCard(`+ <div class="err-card">+ <div class="err-head">Error</div>+ ${escHtml(d.message)}${fundLine}+ </div>`);+ }++ // ── Wallet status ─────────────────────────────────────────────────────+ async function loadWalletStatus() {+ try {+ const r = await fetch('/api/agent/wallet');+ if (!r.ok) return;+ const d = await r.json();+ if (d.address) {+ $('addr-a').textContent = addrShort(d.address);+ $('link-a').href = `https://solscan.io/account/${d.address}`;+ $('link-a').title = d.address;+ }+ if (d.sol != null) {+ const bal = $('bal-a');+ bal.textContent = `${Number(d.sol).toFixed(4)} SOL`;+ bal.classList.remove('loading');+ }+ } catch {}+ }++ function setAgentBInfo(from, to) {+ if (to) {+ $('addr-b').textContent = addrShort(to);+ $('link-b').href = `https://solscan.io/account/${to}`;+ $('link-b').title = to;+ }+ }++ // ── Run deal ──────────────────────────────────────────────────────────+ function setStatus(msg, busy = false) {+ runStatus.textContent = msg || '';+ runStatus.classList.toggle('busy', busy);+ runBtn.disabled = busy;+ dealBadge.textContent = busy ? 'in progress' : msg ? 'done' : 'ready';+ }++ async function runDeal() {+ if (running) return;+ running = true;+ clearFeed();+ setStatus('Connecting…', true);++ const es = new EventSource('/api/pay/deal');++ es.addEventListener('line', (e) => {+ const d = JSON.parse(e.data);+ appendMsg(d.speaker, d.text);+ const frame = d.speaker === 'A' ? frameA : frameB;+ const state = d.speaker === 'A' ? readyA : readyB;+ speak(frame, state, d.text);+ emote(frame, state, d.emotion);+ setStatus(`Agent ${d.speaker} speaking…`, true);+ });++ es.addEventListener('quote', (e) => {+ const d = JSON.parse(e.data);+ renderQuote(d);+ setAgentBInfo(d.from, d.to);+ setStatus('Quote received', true);+ });++ es.addEventListener('paying', (e) => {+ const d = JSON.parse(e.data);+ renderPaying(d);+ setStatus('Broadcasting transaction…', true);+ });++ es.addEventListener('paid', (e) => {+ const d = JSON.parse(e.data);+ renderPaid(d);+ setStatus('Transaction confirmed', true);+ // Refresh Agent A balance after payment+ loadWalletStatus();+ });++ es.addEventListener('deliver', (e) => {+ const d = JSON.parse(e.data);+ renderDeliver(d);+ setStatus('Brief delivered', true);+ });++ es.addEventListener('error', (e) => {+ try {+ const d = JSON.parse(e.data);+ renderError(d);+ setStatus(d.message?.slice(0, 60) || 'Error', false);+ } catch {+ setStatus('Connection error', false);+ }+ es.close();+ running = false;+ runBtn.disabled = false;+ });++ es.addEventListener('done', () => {+ es.close();+ running = false;+ dealCount++;+ runCount.textContent = `${dealCount} deal${dealCount === 1 ? '' : 's'} settled`;+ setStatus('Deal complete', false);+ runBtn.disabled = false;+ dealBadge.textContent = 'done';+ loadWalletStatus();+ });++ // SSE connection error (network drop, 503, etc.)+ es.onerror = (e) => {+ if (es.readyState === EventSource.CLOSED) {+ if (running) {+ renderError({+ message:+ 'SSE connection closed unexpectedly. Is AVATAR_WALLET_SECRET set?',+ });+ setStatus('Disconnected', false);+ running = false;+ runBtn.disabled = false;+ }+ }+ };+ }++ runBtn.addEventListener('click', runDeal);+ loadWalletStatus();+ </script>+ </body>+</html>diff --git a/pages/demo-economy.html b/pages/demo-economy.htmlnew file mode 100644index 000000000..6ce683d06--- /dev/null+++ b/pages/demo-economy.html@@ -0,0 +1,365 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <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." />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ --bg: #05070d;+ --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; }+ .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; }++ /* ── 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);+ }++ /* 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);+ }++ @media (max-width: 680px) {+ #root { grid-template-columns: 1fr; grid-template-areas: "top" "canvas" "bot"; }+ #sidebar { display: none; }+ }+ </style>+</head>+<body>+<div id="root">+ <header id="topbar">+ <div class="brand">+ <a href="/">three.ws</a>+ <span class="sep">/</span>+ <span class="page">Agent Economy</span>+ </div>+ <div class="pills">+ <span class="pill nova"><span class="dot"></span>NOVA · payer</span>+ <span class="pill oracle"><span class="dot"></span>ORACLE · provider</span>+ </div>+ <button id="run-btn" type="button"><span id="run-label">Run demo</span></button>+ </header>++ <div id="canvas-wrap"><canvas id="scene"></canvas></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">Amount</span><span class="pv g" id="py-amt">—</span></div>+ <div class="pr"><span class="pk">Network</span><span class="pv">Solana</span></div>+ <div class="pr" id="py-sim-row" style="display:none"><span class="pk">Mode</span><span class="pv"><span class="sim-tag">Simulated</span></span></div>+ <div class="pr"><span class="pk">Signature</span><span class="pv" id="py-sig">—</span></div>+ </div>+ </div>++ <div class="sb-label" style="padding:10px 14px 4px">Activity</div>+ <div id="steps-wrap"><div id="steps"></div></div>+ </aside>++ <footer id="botbar">+ <span id="status">Ready — click Run demo</span>+ <span style="color:var(--muted)">·</span>+ <span style="color:var(--muted)">Real Solana infrastructure · x402 protocol · live bazaar</span>+ <div class="chips">+ <span class="chip">x402</span>+ <span class="chip">Solana</span>+ <span class="chip">Three.js</span>+ <span class="chip">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');++// ── Scene init ─────────────────────────────────────────────────────────────+let world = null;+try {+ world = createScene(canvas);+} catch (err) {+ console.error('Scene failed:', err);+}++// ── Utilities ──────────────────────────────────────────────────────────────+function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, c =>+ ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[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';+}++// ── 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…';++ // 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?.beam?.deactivate();++ const es = new EventSource('/api/demo-economy');+ let settled = false;++ function finish() {+ if (settled) return; settled = true;+ 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.services);+ });++ 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 + ' 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.simulated) {+ sigEl.innerHTML = `<span style="color:var(--muted)">${esc(d.signature.slice(0,16))}…</span>`;+ } else {+ sigEl.innerHTML = `<a href="${esc(d.explorer_url)}" target="_blank" rel="noopener">${esc(d.signature.slice(0,12))}… ↗</a>`;+ }+ });++ es.addEventListener('content', e => {+ const d = JSON.parse(e.data);+ world?.tv?.setBriefing(d);+ world?.tv?.setPhase('content');+ });++ es.addEventListener('done', () => finish());+ es.addEventListener('error', e => {+ try { addStep('❌', 'Error', JSON.parse(e.data).message); } catch {}+ statusEl.textContent = 'Error — see console';+ finish();+ });+ es.onerror = () => {+ if (!settled) { statusEl.textContent = 'Connection lost'; finish(); }+ };++ // Hard timeout+ setTimeout(finish, 35000);+}++runBtn.addEventListener('click', runDemo);+</script>+</body>+</html>diff --git a/pages/ibm/identity.html b/pages/ibm/identity.htmlindex 564f5df16..d1102ab9a 100644--- a/pages/ibm/identity.html+++ b/pages/ibm/identity.html@@ -278,6 +278,10 @@This is the exact gate that runs on every <span style="font-family:var(--mono)">POST /api/agents</span> — a blocked identity is refused at creation.Explore the rest of <a href="/ibm">three.ws on IBM watsonx</a>.</p>++ <p class="foot" style="opacity:.7;font-size:12px;margin-top:14px;">+ This is an independent demo three.ws built for developers to explore IBM Granite on watsonx.ai and build their own tools — not an official IBM partnership deliverable, not an IBM product, and not endorsed by IBM. IBM, watsonx, watsonx.ai, and Granite are trademarks of IBM.+ </p></main><script type="module">diff --git a/pages/ibm/index.html b/pages/ibm/index.htmlindex af66fcb76..c6604e3bb 100644--- a/pages/ibm/index.html+++ b/pages/ibm/index.html@@ -3,19 +3,19 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />- <title>three.ws on IBM watsonx — 3D AI Agent Platform · IBM Business Partner</title>- <meta name="description" content="three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity — embed anywhere with one tag." />+ <title>three.ws on IBM watsonx — open 3D AI agent demos on Granite</title>+ <meta name="description" content="Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity — embed anywhere with one tag. Independent community demos built on watsonx.ai for developers to explore — not official IBM partnership work." /><link rel="canonical" href="https://three.ws/ibm" /><meta property="og:type" content="website" /><meta property="og:title" content="three.ws on IBM watsonx — 3D AI Agent Platform" />- <meta property="og:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner. Give watsonx Orchestrate a 3D body, voice, and on-chain identity." />+ <meta property="og:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. Independent community demos built on watsonx.ai. Give watsonx Orchestrate a 3D body, voice, and on-chain identity." /><meta property="og:url" content="https://three.ws/ibm" /><meta property="og:image" content="https://three.ws/ibm-og.png" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="three.ws on IBM watsonx" />- <meta name="twitter:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner." />+ <meta name="twitter:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. Independent community demos built on watsonx.ai." /><meta name="twitter:image" content="https://three.ws/ibm-og.png" /><link rel="icon" href="/favicon.ico" />@@ -135,14 +135,14 @@<main><div class="partner-badge"><span class="dot"></span>- <strong>IBM Business Partner</strong>+ <strong>Built on IBM watsonx.ai</strong><span>·</span>- <span>watsonx.ai + Orchestrate</span>+ <span>Granite + Orchestrate</span></div><h1>three.ws on <span class="gradient">IBM watsonx</span>.</h1><p class="lede">- three.ws is an open-source 3D AI agent platform — WebGL viewer, LLM-driven runtime, on-chain identity, embed anywhere with one tag. <strong>An IBM Business Partner.</strong> Agents think on IBM Granite through watsonx.ai, and a watsonx Orchestrate agent gets a face, a voice, and a body that lives in the browser.+ three.ws is an open-source 3D AI agent platform — WebGL viewer, LLM-driven runtime, on-chain identity, embed anywhere with one tag. Agents think on IBM Granite through watsonx.ai, and a watsonx Orchestrate agent gets a face, a voice, and a body that lives in the browser. The demos below are independent showcases we built for developers — explore them with your own IBM Cloud account and build your own tools.</p><div class="cta-row">@@ -393,7 +393,7 @@</main><div class="footer">- <a href="/">three.ws</a> · <a href="/blog/three-ws-ibm-collaboration">IBM partnership</a> · <a href="/docs">Docs</a> · <a href="/legal/privacy">Privacy</a> · <a href="/legal/tos">Terms</a>+ <a href="/">three.ws</a> · <a href="/blog/three-ws-ibm-collaboration">Built on watsonx</a> · <a href="/docs">Docs</a> · <a href="/legal/privacy">Privacy</a> · <a href="/legal/tos">Terms</a></div><script src="/brand.js" defer></script></body>diff --git a/pages/live.html b/pages/live.htmlnew file mode 100644index 000000000..7edcec946--- /dev/null+++ b/pages/live.html@@ -0,0 +1,538 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <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." />+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ --bg: #04050b;+ --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: #a855f7;+ --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: none;+ }+ .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(168,85,247,0.2));+ 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(168,85,247,0.8); }+ #trade-btn:active:not(:disabled) { transform: scale(.97); }+ #trade-btn:disabled { opacity: .35; cursor: not-allowed; }++ /* 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>+</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 -->+<div id="tag-oracle" class="agent-tag" style="display:none">+ <span class="dot"></span>Oracle · Seller+</div>+<div id="tag-trader" class="agent-tag" style="display:none">+ <span class="dot"></span>Trader · Buyer+</div>++<!-- 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">+ <button id="trade-btn">▶ Agent Trader pays Oracle for Solana market data</button>+ <div id="log"><div class="log-entry"><span class="ev">READY</span><span>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;+}++// ── 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)}` : '');+ }+}++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, '#a855f7');+ if (agentB?.configured) renderWalletChip('Trader', agentB, '#4e8cff');+ } catch {}+}++// ── LLM speech helper ─────────────────────────────────────────────────────+async function llmSay(prompt, persona) {+ try {+ const r = await fetch('/api/chat', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message: prompt, systemPrompt: persona, stream: false }),+ });+ const d = await r.json();+ return d.reply || d.content || d.text || '';+ } catch { return ''; }+}++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;++async function runTrade() {+ if (running) return;+ running = true;+ 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);+ 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) => {+ const d = JSON.parse(e.data);+ addLog('THINK', d.text);+ });++ evtSource.addEventListener('demo_mode', (e) => {+ const d = JSON.parse(e.data);+ addLog('DEMO', d.text);+ 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);+ 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);+ 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);+ 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);+ if (line2) { setBubble('speech-trader', line2); speakTrader(line2); }+ waveTrader();+ });++ evtSource.addEventListener('error', (e) => {+ try {+ const d = JSON.parse(e.data);+ addLog('ERROR', d.text);+ } catch {+ addLog('ERROR', 'Stream interrupted');+ }+ evtSource.close();+ finishTrade();+ });++ evtSource.addEventListener('done', (e) => {+ const d = JSON.parse(e.data);+ addLog('DONE', `Trade complete. ${d.markets?.length || 0} signals delivered, ${d.tradeSol} SOL settled on-chain.`);+ 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);+ 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);+ if (g) { setBubble('speech-trader', g); speakTrader(g); }+}, 5500);+</script>+</body>+</html>diff --git a/public/nav.html b/public/nav.htmlindex 3cd8734e3..bf54aeec1 100644--- a/public/nav.html+++ b/public/nav.html@@ -97,6 +97,12 @@Discover<span class="nav-caret" aria-hidden="true">▾</span></button><ul class="nav-menu" role="menu" aria-label="Discover">+ <li role="none">+ <a href="/agent-economy" role="menuitem"+ ><span class="nav-mi-title">Agent Economy<span class="nav-pill" aria-hidden="true">LIVE</span></span+ ><span class="nav-mi-sub">Watch two 3D agents buy and sell intelligence on-chain — real SOL, real transaction</span></a+ >+ </li><li role="none"><a href="/ibm" role="menuitem"><span class="nav-mi-title">IBM watsonx<span class="nav-pill" aria-hidden="true">NEW</span></spandiff --git a/scripts/agent-x402-demo/.gitignore b/scripts/agent-x402-demo/.gitignorenew file mode 100644index 000000000..02c325f17--- /dev/null+++ b/scripts/agent-x402-demo/.gitignore@@ -0,0 +1,2 @@+# Throwaway demo wallet secret — NEVER commit+*.local.jsondiff --git a/scripts/agent-x402-demo/README.md b/scripts/agent-x402-demo/README.mdnew file mode 100644index 000000000..e9bac35a2--- /dev/null+++ b/scripts/agent-x402-demo/README.md@@ -0,0 +1,41 @@+# Agent x402 payment demo (record-ready)++A captivating ~30-second terminal demo for X: an AI agent calls a **real, live**+three.ws paid service, hits **HTTP 402**, and **pays for it itself in USDC on+Solana** — no card, no human — settled on-chain by the **Coinbase / PayAI x402+facilitator**. Then it prints the paid result and the settlement transaction on+Solscan.++Everything hits production (`https://three.ws`). Nothing is mocked.++## Record it++```bash+# 1. Generate the agent wallet + see the fund address+node scripts/agent-x402-demo/pay.mjs++# 2. Fund that address with a few dollars of USDC on Solana mainnet.+# PayAI covers the network fee, so the agent needs USDC only — no SOL.++# 3. Record your terminal while running:+node scripts/agent-x402-demo/pay.mjs agent-reputation+```++## Services (the agent buys one)++| arg | what the agent buys |+| --- | --- |+| `agent-reputation` (default) | an on-chain reputation score for another agent |+| `pump-agent-audit` | an audit of a live pump.fun agent's token |+| `symbol-availability` | whether a token ticker is still available |++The price is discovered live from the 402 challenge — the demo never hardcodes it.++## Knobs++- `PACE` — ms between narration lines for recording cadence (default `700`; `PACE=0` runs flat-out).+- `X402_BASE_URL` — override the target (default `https://three.ws`).+- `SOLANA_RPC` — a Helius/Triton URL is smoother than the public endpoint.++`wallet.local.json` holds the throwaway agent secret and is gitignored. Keep its+balance small — it's a demo wallet.diff --git a/scripts/agent-x402-demo/pay.mjs b/scripts/agent-x402-demo/pay.mjsnew file mode 100644index 000000000..9fa5a89c2--- /dev/null+++ b/scripts/agent-x402-demo/pay.mjs@@ -0,0 +1,183 @@+// Agent x402 payment demo — record this terminal session.+//+// An AI agent calls a REAL, live three.ws paid service, hits HTTP 402, and pays+// for it ITSELF in USDC on Solana — no card, no human — settled on-chain by the+// Coinbase/PayAI x402 facilitator. Then it shows the paid result + the+// settlement transaction on Solscan. Every byte hits production (https://three.ws);+// nothing is mocked.+//+// node scripts/agent-x402-demo/pay.mjs # default service+// node scripts/agent-x402-demo/pay.mjs agent-reputation+// node scripts/agent-x402-demo/pay.mjs pump-agent-audit+//+// One-time: fund the printed wallet address with a few dollars of USDC on+// Solana mainnet (the agent pays per call; PayAI covers the network fee, so the+// wallet needs USDC only — no SOL required).++import { readFileSync, writeFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++import bs58 from 'bs58';+import { Connection, Keypair, PublicKey, Transaction, ComputeBudgetProgram } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ getMint,+ getAccount,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++const HERE = dirname(fileURLToPath(import.meta.url));+const WALLET_FILE = resolve(HERE, 'wallet.local.json');+const BASE_URL = process.env.X402_BASE_URL || 'https://three.ws';+const RPC = process.env.SOLANA_RPC || 'https://api.mainnet-beta.solana.com';+const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');+const X402_VERSION = 2;+const SOLANA_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;+const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;++// A curated menu of live, GET-able paid services with a tangible result.+const SERVICES = {+ 'agent-reputation': { url: '/api/x402/agent-reputation?agent_id=76bca598-103f-4e3a-8c95-b0d64993258a', blurb: 'an on-chain reputation score for another agent' },+ 'pump-agent-audit': { url: '/api/x402/pump-agent-audit?mint=Aodd9LBDCue4HN6KyhpSai7yudFCoEWJ3FLHdgYajQzb', blurb: "an audit of a live pump.fun agent's token" },+ 'symbol-availability': { url: '/api/x402/symbol-availability?ticker=WWWTEST', blurb: 'whether a token ticker is still available' },+};++// ── terminal UI ───────────────────────────────────────────────────────────────+const C = { r: '\x1b[0m', dim: '\x1b[2m', b: '\x1b[1m', p: '\x1b[38;5;141m', g: '\x1b[38;5;120m', c: '\x1b[38;5;87m', y: '\x1b[38;5;221m', gray: '\x1b[38;5;245m', red: '\x1b[38;5;203m' };+const PACE = Number(process.env.PACE ?? 700);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function say(line, color = '\x1b[97m') { process.stdout.write(`${color}${line}${C.r}\n`); if (PACE) await sleep(PACE); }+async function think(line) { process.stdout.write(`${C.gray}${C.dim} 🧠 ${line}${C.r}\n`); if (PACE) await sleep(PACE); }+const rule = () => console.log(C.dim + '─'.repeat(70) + C.r);++// ── wallet ──────────────────────────────────────────────────────────────────+function loadOrCreateWallet() {+ if (existsSync(WALLET_FILE)) {+ const raw = JSON.parse(readFileSync(WALLET_FILE, 'utf8'));+ return Keypair.fromSecretKey(bs58decode(raw.secret));+ }+ const kp = Keypair.generate();+ writeFileSync(WALLET_FILE, JSON.stringify({ pubkey: kp.publicKey.toBase58(), secret: bs58encode(kp.secretKey) }, null, 2) + '\n');+ return kp;+}++async function usdcBalance(conn, owner) {+ try {+ const ata = getAssociatedTokenAddressSync(USDC_MINT, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const acct = await getAccount(conn, ata, 'confirmed', TOKEN_PROGRAM_ID);+ return Number(acct.amount) / 1e6;+ } catch {+ return 0;+ }+}++// ── the proven x402 SVM "exact" payment construction ──────────────────────────+async function buildAndSignPayment({ kp, conn, requirement }) {+ const mint = new PublicKey(requirement.asset);+ const payTo = new PublicKey(requirement.payTo);+ const feePayer = new PublicKey(requirement.extra.feePayer);+ const amount = BigInt(requirement.amount);+ const mintInfo = await getMint(conn, mint);+ const senderAta = getAssociatedTokenAddressSync(mint, kp.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);++ const tx = new Transaction();+ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ tx.recentBlockhash = blockhash;+ tx.feePayer = feePayer;+ tx.add(ComputeBudgetProgram.setComputeUnitLimit({ units: 20_000 }));+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }));+ tx.add(createTransferCheckedInstruction(senderAta, mint, receiverAta, kp.publicKey, amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID));+ tx.partialSign(kp);+ return Buffer.from(tx.serialize({ requireAllSignatures: false, verifySignatures: false })).toString('base64');+}++const pickSolana = (env) => (env.accepts || []).find((a) => a.scheme === 'exact' && String(a.network).startsWith('solana')) || null;+const encodeHeader = (p) => Buffer.from(JSON.stringify(p), 'utf8').toString('base64');++// ── run ───────────────────────────────────────────────────────────────────────+const which = process.argv[2] || 'agent-reputation';+const service = SERVICES[which];+if (!service) { console.error(`Unknown service "${which}". Options: ${Object.keys(SERVICES).join(', ')}`); process.exit(1); }++const conn = new Connection(RPC, 'confirmed');+const kp = loadOrCreateWallet();++console.clear();+console.log(`${C.p}${C.b}+ ╔══════════════════════════════════════════════════════════════════════╗+ ║ three.ws · the agent economy, live ║+ ║ an AI agent pays for a real service in USDC — no card, no human ║+ ║ x402 over HTTP · settled on Solana by the Coinbase / PayAI facilitator ║+ ╚══════════════════════════════════════════════════════════════════════╝${C.r}`);+await sleep(PACE);++await say(`\n Agent wallet: ${C.b}${kp.publicKey.toBase58()}${C.r}`, C.c);+const bal = await usdcBalance(conn, kp.publicKey);+await say(` USDC balance: ${C.b}$${bal.toFixed(2)}${C.r}`, C.gray);++if (bal <= 0) {+ rule();+ await say(`\n ${C.y}Fund this wallet with a few dollars of USDC on Solana mainnet, then re-run:${C.r}`);+ await say(` ${C.b}${kp.publicKey.toBase58()}${C.r}`, C.c);+ await say(` ${C.gray}(PayAI covers the network fee — the agent needs USDC only, no SOL.)${C.r}`);+ await say(` node scripts/agent-x402-demo/pay.mjs ${which}`, C.gray);+ process.exit(0);+}++rule();+await say(`\n ${C.b}GOAL:${C.r} the agent wants ${service.blurb}.`, C.y);+await think(`Calling the service at ${service.url} …`);++// 1. Hit the endpoint → expect 402.+const url = `${BASE_URL}${service.url}`;+const probe = await fetch(url);+if (probe.status !== 402) { await say(` Unexpected ${probe.status} (endpoint not gated?).`, C.red); process.exit(1); }+const envelope = await probe.json();+const requirement = pickSolana(envelope);+if (!requirement) { await say(' No Solana payment option offered.', C.red); process.exit(1); }+const price = (Number(requirement.amount) / 1e6).toFixed(4);+console.log(`\n${C.p} ← HTTP 402 Payment Required${C.r}`);+await say(` price: ${C.b}$${price} USDC${C.r} facilitator fee-payer: ${requirement.extra.feePayer.slice(0, 8)}…`, C.gray);++// 2. Build + sign the USDC payment itself.+await think('I will pay for it myself — building and signing a USDC transfer.');+const txB64 = await buildAndSignPayment({ kp, conn, requirement });+const payload = {+ x402Version: X402_VERSION,+ scheme: 'exact',+ network: requirement.network,+ resource: { url: envelope.resource?.url || url, mimeType: envelope.resource?.mimeType || 'application/json' },+ accepted: requirement,+ payload: { transaction: txB64 },+};++// 3. Retry with X-PAYMENT — server verifies + settles on-chain via PayAI.+await say(`\n ${C.b}→ retrying with X-PAYMENT …${C.r} ${C.gray}(server verifies, PayAI co-signs + broadcasts)${C.r}`, C.c);+const t0 = Date.now();+const res = await fetch(url, { headers: { 'X-PAYMENT': encodeHeader(payload) } });+const ms = Date.now() - t0;+const body = await res.text();++if (res.status !== 200) { await say(`\n ✗ ${res.status}: ${body.slice(0, 200)}`, C.red); process.exit(1); }++const payTx = res.headers.get('x-payment-tx');+const payNet = res.headers.get('x-payment-network') || 'solana';+console.log(`\n${C.g}${C.b} ✓ Paid and served in ${ms}ms.${C.r}`);+if (payTx) {+ await say(` settled on ${payNet}: ${payTx}`, C.gray);+ await say(` ${C.c}${C.b}https://solscan.io/tx/${payTx}${C.r}`);+}+rule();+await say(`\n ${C.b}The paid result:${C.r}`, C.y);+let pretty = body;+try { pretty = JSON.stringify(JSON.parse(body), null, 2); } catch { /* keep raw */ }+console.log(pretty.length > 900 ? pretty.slice(0, 900) + '…' : pretty);+const after = await usdcBalance(conn, kp.publicKey);+await say(`\n ${C.gray}Agent USDC: $${bal.toFixed(2)} → $${after.toFixed(2)}. It just bought a service, by itself, on-chain.${C.r}`);+await say(`\n ${C.c}The agent economy, in the open. · three.ws${C.r}\n`);+process.exit(0);diff --git a/scripts/dev-deal.mjs b/scripts/dev-deal.mjsnew file mode 100644index 000000000..91186b873--- /dev/null+++ b/scripts/dev-deal.mjs@@ -0,0 +1,71 @@+// Local dev server for /deal page.+// Serves /deal, /api/pay/deal, and /api/agent/wallet locally.+// Everything else redirects to production.+//+// node scripts/dev-deal.mjs → http://localhost:3389/deal+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import deal from '../api/pay/deal.js';+import wallet from '../api/agent/wallet.js';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const PORT = Number(process.env.PORT || 3389);+const PROD = 'https://three.ws';++const FILES = {+ '/deal': ['pages/deal.html', 'text/html; charset=utf-8'],+ '/deal/': ['pages/deal.html', 'text/html; charset=utf-8'],+};++const server = createServer(async (req, res) => {+ const path = (req.url || '/').split('?')[0];++ if (path.startsWith('/api/pay/deal')) {+ try {+ await deal(req, res);+ } catch (e) {+ if (!res.headersSent)+ res.end(+ JSON.stringify({ error: 'handler_threw', message: String(e?.message || e) }),+ );+ }+ return;+ }++ if (path.startsWith('/api/agent/wallet')) {+ try {+ await wallet(req, res);+ } catch (e) {+ if (!res.headersSent)+ res.end(+ JSON.stringify({ error: 'handler_threw', message: String(e?.message || e) }),+ );+ }+ return;+ }++ const file = FILES[path];+ if (file) {+ try {+ const body = await readFile(resolve(ROOT, file[0]));+ res.statusCode = 200;+ res.setHeader('content-type', file[1]);+ res.end(body);+ } catch {+ res.statusCode = 404;+ res.end('not found');+ }+ return;+ }++ res.statusCode = 302;+ res.setHeader('Location', PROD + req.url);+ res.end();+});++server.listen(PORT, () => {+ console.log(`Deal dev server → http://localhost:${PORT}/deal`);+ console.log(` /api/pay/deal served locally; other assets proxy to ${PROD}`);+});diff --git a/src/agent-economy.js b/src/agent-economy.jsnew file mode 100644index 000000000..225436e75--- /dev/null+++ b/src/agent-economy.js@@ -0,0 +1,360 @@+// Agent Economy — two 3D AI agents transacting on-chain.+//+// Nova (buyer, left) picks a service from Oracle's catalog, pays real SOL,+// and Oracle delivers the analysis. Every transaction is real: a live Solana+// wallet sends lamports, the tx signature links to Solana FM.+//+// Architecture:+// - Two <agent-3d> avatars loaded into iframes (the existing embed pattern).+// - A POST to /api/agent-economy/transact triggers the real payment + LLM+// delivery on the server. No x402 client lib needed in the browser: the+// server signs with AVATAR_WALLET_SECRET.+// - Speech bubbles + avatar animations driven by postMessage to each iframe.+// - A payment particle arc animates from buyer → seller on real tx confirmation.+// - /api/agent-economy/status polled on load to show live wallet balances.+// - The tx feed in the center column is pure DOM — no framework.++const $ = (id) => document.getElementById(id);++// ── Wallet status ─────────────────────────────────────────────────────────────+// Fetched on load; re-fetched after each trade to show updated balances.+async function fetchWalletStatus() {+ try {+ const res = await fetch('/api/agent-economy/status');+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++function renderBal(elId, info) {+ const el = $(elId);+ if (!el) return;+ if (!info || !info.configured) {+ el.className = 'av-label-bal bal-unknown';+ el.textContent = 'wallet not set';+ return;+ }+ const sol = typeof info.sol === 'number' ? info.sol : null;+ if (sol === null) {+ el.className = 'av-label-bal bal-unknown';+ el.textContent = '—';+ return;+ }+ const usdStr = info.usd != null ? ` · $${info.usd.toFixed(2)}` : '';+ el.className = `av-label-bal ${sol > 0.0001 ? 'bal-funded' : 'bal-empty'}`;+ el.textContent = `${sol.toFixed(5)} SOL${usdStr}`;+}++function renderFundAlert(status) {+ const el = $('fund-alert');+ if (!el) return;+ const aOk = status?.agentA?.configured && (status.agentA.sol ?? 0) > 0.001;+ const aCfg = status?.agentA?.configured;+ if (aOk) { el.classList.remove('visible'); return; }+ let html = '';+ if (!aCfg) {+ html = '<strong>Nova\'s wallet not configured.</strong> Set <code>AVATAR_WALLET_SECRET</code> in Vercel env to enable live transactions.';+ } else {+ const addr = status.agentA.address;+ const exp = status.agentA.explorer || `https://solscan.io/account/${addr}`;+ html = `<strong>Nova needs SOL to transact.</strong> Fund her wallet with a small amount of SOL:<span class="fund-addr">${addr} <a href="${exp}" target="_blank" rel="noopener">↗ Solscan</a></span>`;+ }+ el.innerHTML = html;+ el.classList.add('visible');+}++async function refreshWalletStatus() {+ const status = await fetchWalletStatus();+ if (!status) return;+ renderBal('buyer-bal', status.agentA);+ renderBal('seller-bal', status.agentB);+ renderFundAlert(status);+ if (status.agentA?.address) renderAddr('buyer-addr', status.agentA.address, status.agentA.explorer);+ if (status.agentB?.address) renderAddr('seller-addr', status.agentB.address, status.agentB.explorer);+}++// ── Payment particle ──────────────────────────────────────────────────────────+function firePaymentParticle() {+ const root = $('root');+ const buyer = document.getElementById('col-buyer');+ const seller = document.getElementById('col-seller');+ if (!root || !buyer || !seller) return;++ const rootRect = root.getBoundingClientRect();+ const buyerRect = buyer.getBoundingClientRect();+ const sellerRect = seller.getBoundingClientRect();++ const startX = buyerRect.left + buyerRect.width / 2 - rootRect.left;+ const startY = buyerRect.top + buyerRect.height / 2 - rootRect.top;+ const endX = sellerRect.left + sellerRect.width / 2 - rootRect.left;+ const dx = endX - startX;++ const p = document.createElement('div');+ p.className = 'pay-particle';+ p.style.left = `${startX}px`;+ p.style.top = `${startY}px`;+ p.style.setProperty('--tx-full', `${dx}px`);+ p.style.setProperty('--tx-half', `${dx / 2}px`);+ root.appendChild(p);++ // Trigger reflow then start animation.+ p.getBoundingClientRect();+ p.classList.add('arc');+ setTimeout(() => p.remove(), 1000);+}++// ── Avatar frames ─────────────────────────────────────────────────────────────+const frameBuyer = $('frame-buyer');+const frameSeller = $('frame-seller');+const colBuyer = $('col-buyer');+const colSeller = $('col-seller');++const BUYER_GLB = '/avatars/default.glb';+// Use a slightly different tint for the seller so they look distinct.+const SELLER_GLB = '/avatars/cz.glb';++// Track readiness: iframes fire v1.avatar.ready when the 3D scene is live.+let buyerReady = false;+let sellerReady = false;+const buyerQueue = [];+const sellerQueue = [];++function postToAvatar(frame, queue, ready, msg) {+ if (ready) frame.contentWindow?.postMessage(msg, location.origin);+ else queue.push(msg);+}++function buyerSay(text) { postToAvatar(frameBuyer, buyerQueue, buyerReady, { type: 'v1.avatar.speak', text }); }+function sellerSay(text) { postToAvatar(frameSeller, sellerQueue, sellerReady, { type: 'v1.avatar.speak', text }); }+function buyerAnim(name) { postToAvatar(frameBuyer, buyerQueue, buyerReady, { type: 'v1.avatar.animation', name }); }+function sellerAnim(name){ postToAvatar(frameSeller, sellerQueue, sellerReady, { type: 'v1.avatar.animation', name }); }++window.addEventListener('message', (e) => {+ if (e.data?.type !== 'v1.avatar.ready') return;+ if (e.source === frameBuyer.contentWindow) {+ buyerReady = true;+ $('loading-buyer').classList.add('gone');+ buyerQueue.forEach((m) => frameBuyer.contentWindow?.postMessage(m, location.origin));+ buyerQueue.length = 0;+ buyerSay('Ready to transact. Browsing Oracle\'s catalog now.');+ } else if (e.source === frameSeller.contentWindow) {+ sellerReady = true;+ $('loading-seller').classList.add('gone');+ sellerQueue.forEach((m) => frameSeller.contentWindow?.postMessage(m, location.origin));+ sellerQueue.length = 0;+ sellerSay('Open for business. Services start at $0.001.');+ }+});++// Build the embed URL for each avatar (same pattern as demo-economy.html).+function avatarUrl(glb) {+ const q = new URLSearchParams({ model: glb, brain: '/api/chat', 'hide-chrome': '1', kiosk: '1', eager: '1' });+ return `/a-embed?${q}`;+}++frameBuyer.src = avatarUrl(BUYER_GLB);+frameSeller.src = avatarUrl(SELLER_GLB);++// Load wallet status immediately — updates balance chips and fund alert.+refreshWalletStatus();++// ── Speech bubbles ────────────────────────────────────────────────────────────+const speechBuyer = $('speech-buyer');+const speechSeller = $('speech-seller');+const speechTimers = { buyer: null, seller: null };++function showSpeech(el, text, key, ms = 6000) {+ clearTimeout(speechTimers[key]);+ el.textContent = text;+ el.classList.add('visible');+ speechTimers[key] = setTimeout(() => el.classList.remove('visible'), ms);+}++// ── Status bar ────────────────────────────────────────────────────────────────+function setStatus(text) { $('status-text').textContent = text; }++// ── Transaction feed ──────────────────────────────────────────────────────────+let txCount = 0;++function addFeedItem({ icon, type, title, sub, time }) {+ const empty = $('feed-empty');+ if (empty) empty.remove();+ txCount++;+ $('tx-count').textContent = `${txCount} tx`;++ const now = time || new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });+ const item = document.createElement('div');+ item.className = `tx-item tx-${type}`;+ item.innerHTML = `+ <div class="tx-icon">${icon}</div>+ <div class="tx-body">+ <div class="tx-title">${escHtml(title)}</div>+ <div class="tx-sub">${sub}</div>+ </div>+ <div class="tx-time">${escHtml(now)}</div>`;+ const feed = $('feed');+ feed.prepend(item);+}++function escHtml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++// ── Service buttons ───────────────────────────────────────────────────────────+let busy = false;++document.querySelectorAll('.svc-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ if (busy) return;+ purchase(btn.dataset.service);+ });+});++function setButtons(disabled) {+ document.querySelectorAll('.svc-btn').forEach((b) => (b.disabled = disabled));+}++// ── Wallet address display (from the API response) ────────────────────────────+function shortenAddr(addr) {+ if (!addr || addr.length < 10) return addr;+ return `${addr.slice(0, 4)}…${addr.slice(-4)}`;+}++function renderAddr(elId, addr, explorerUrl) {+ const el = $(elId);+ if (!el || !addr) return;+ el.innerHTML = explorerUrl+ ? `<a href="${escHtml(explorerUrl)}" target="_blank" rel="noopener" title="${escHtml(addr)}">${escHtml(shortenAddr(addr))} ↗</a>`+ : escHtml(shortenAddr(addr));+}++// ── Purchase flow ─────────────────────────────────────────────────────────────+async function purchase(service) {+ if (busy) return;+ busy = true;+ setButtons(true);++ const topic = $('topic').value.trim() || null;+ const serviceNames = {+ 'market-analysis': 'Market Analysis',+ 'onchain-insight': 'On-Chain Insight',+ 'risk-score': 'Risk Score',+ };+ const name = serviceNames[service] || service;++ setStatus(`Nova is requesting ${name}…`);+ showSpeech(speechBuyer, `Oracle, I need ${name}. Sending payment now.`, 'buyer', 7000);+ buyerAnim('idle');+ colBuyer.classList.add('paying');+ setTimeout(() => colBuyer.classList.remove('paying'), 600);+ buyerAnim('wave');++ addFeedItem({+ icon: '📡',+ type: 'pay',+ title: `Nova → Oracle: ${name}`,+ sub: topic ? `Topic: ${escHtml(topic)}` : 'Service request initiated',+ });++ let data;+ try {+ const res = await fetch('/api/agent-economy/transact', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ service, topic }),+ });+ data = await res.json();+ if (!res.ok) throw new Error(data.error_description || data.error || `HTTP ${res.status}`);+ } catch (e) {+ setStatus(`Error: ${e.message}`);+ addFeedItem({ icon: '⚠️', type: 'pay', title: 'Request failed', sub: escHtml(e.message) });+ busy = false;+ setButtons(false);+ return;+ }++ const tx = data.transaction;++ // Update wallet address labels on first successful response+ if (tx?.buyerAddress) renderAddr('buyer-addr', tx.buyerAddress, tx.buyerExplorerUrl);+ if (tx?.sellerAddress) renderAddr('seller-addr', tx.sellerAddress, tx.sellerExplorerUrl);++ // Nova speaks her request+ if (data.buyerSaid) {+ showSpeech(speechBuyer, data.buyerSaid, 'buyer', 7000);+ buyerSay(data.buyerSaid);+ }++ // Slight delay so Oracle "receives" the payment before responding+ await delay(900);++ // Transaction outcome+ if (tx?.signature) {+ // Real on-chain payment confirmed — fire the particle then flash the seller.+ firePaymentParticle();+ await delay(500);+ colSeller.classList.add('receiving');+ setTimeout(() => colSeller.classList.remove('receiving'), 600);++ const solStr = tx.solAmount ? `${tx.solAmount.toFixed(6)} SOL` : '';+ const usdStr = tx.usdAmount ? `$${tx.usdAmount.toFixed(4)} USD` : '';+ const amountStr = [solStr, usdStr].filter(Boolean).join(' · ');++ addFeedItem({+ icon: '💸',+ type: 'pay',+ title: `Payment sent · ${amountStr}`,+ sub: `<a href="${escHtml(tx.explorerUrl)}" target="_blank" rel="noopener" class="tx-mono">+ ${escHtml(tx.signature.slice(0, 8))}…${escHtml(tx.signature.slice(-8))} ↗+ </a><br>${escHtml(tx.network === 'devnet' ? 'Solana devnet' : 'Solana mainnet')}`,+ });+ setStatus(`Payment confirmed · ${amountStr}`);+ } else if (tx?.error === 'wallet_unconfigured') {+ addFeedItem({+ icon: '🔑',+ type: 'pay',+ title: 'Wallet not configured',+ sub: escHtml(tx.message),+ });+ setStatus('Set AVATAR_WALLET_SECRET to enable live transactions');+ } else if (tx?.error === 'insufficient_balance') {+ addFeedItem({ icon: '💰', type: 'pay', title: 'Fund Nova\'s wallet', sub: escHtml(tx.message) });+ setStatus('Fund Nova\'s wallet to transact');+ } else if (tx?.error === 'no_recipient') {+ addFeedItem({ icon: '📭', type: 'pay', title: 'Set Agent B address', sub: escHtml(tx.message) });+ setStatus('Set AGENT_B_ADDRESS to Oracle\'s wallet');+ } else if (tx?.error) {+ addFeedItem({ icon: '⚠️', type: 'pay', title: 'Transaction error', sub: escHtml(tx.message || tx.error) });+ }++ // Oracle delivers the service+ await delay(400);+ sellerAnim('idle');++ if (data.sellerSaid) {+ showSpeech(speechSeller, data.sellerSaid, 'seller', 9000);+ sellerSay(data.sellerSaid);++ addFeedItem({+ icon: '✅',+ type: 'data',+ title: `${name} delivered`,+ sub: escHtml(data.sellerSaid.slice(0, 140) + (data.sellerSaid.length > 140 ? '…' : '')),+ });+ }++ setStatus('Transaction complete · Select another service to continue');+ busy = false;+ setButtons(false);++ // Refresh wallet balances to reflect the just-completed trade.+ refreshWalletStatus();+}++function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }diff --git a/src/agent-exchange.js b/src/agent-exchange.jsnew file mode 100644index 000000000..bbeed4f0f--- /dev/null+++ b/src/agent-exchange.js@@ -0,0 +1,405 @@+// ── agent-exchange.js ────────────────────────────────────────────────────────+// Two 3D AI avatars buying and selling live crypto intel for real USDC via x402.+// Agent A (seller) hosts /api/x402/crypto-intel. Agent B (buyer) pays $0.01 per+// call through the server-side x402 payer at /api/x402-pay, which handles the+// challenge → sign → verify → settle → confirm flow and streams SSE stages.+//+// Every on-chain confirmation is real: real USDC on Solana mainnet, real Solscan+// link. The avatars are iframed into the page and driven via postMessage.+//+// No mock data. When /api/x402-pay is unconfigured (no funded agent wallet) the+// page shows an honest error state.++// ── Topics ────────────────────────────────────────────────────────────────────+const TOPICS = [+ { id: 'sol', label: '◎ SOL' },+ { id: 'btc', label: '₿ BTC' },+ { id: 'eth', label: '⟠ ETH' },+ { id: 'doge', label: '🐕 DOGE' },+ { id: 'bnb', label: '⬡ BNB' },+];++// Stage config matches the SSE event names /api/x402-pay emits.+const STAGE_DEFS = [+ { id: 'challenge', label: '402 Challenge' },+ { id: 'built', label: 'Sign tx' },+ { id: 'verified', label: 'Verify' },+ { id: 'settled', label: 'Settle' },+ { id: 'done', label: 'Confirmed' },+];++// Agent scripts — lines spoken at each stage of the exchange.+const LINES = {+ A: {+ idle: 'I have live crypto intel. $0.01 USDC per signal, settled on-chain.',+ challenge: 'Payment challenge issued. Awaiting your signed transaction…',+ built: 'Transaction received. Forwarding to the facilitator…',+ verified: 'Payment verified. Preparing the intel…',+ settled: 'Funds confirmed on-chain. Delivering now.',+ done: (headline) => `Here's your signal: ${headline}`,+ error: 'Payment failed. No charge made.',+ },+ B: {+ idle: (topic) => `I need live ${topic.toUpperCase()} intelligence. Initiating payment.`,+ challenge: 'Building and signing the Solana transfer…',+ built: 'Signed. Sending to the facilitator for verification.',+ verified: 'Verified on-chain. Waiting for settlement…',+ settled: 'Settled. Collecting my intel.',+ done: (signal) => `Signal received: ${signal.toUpperCase()}. Updating my model.`,+ error: 'Transaction rolled back. Wallet unchanged.',+ },+};++// ── DOM ───────────────────────────────────────────────────────────────────────+const $ = (id) => document.getElementById(id);+const els = {+ frameA: $('frameA'),+ frameB: $('frameB'),+ labelA: $('labelA'),+ labelB: $('labelB'),+ nameA: $('nameA'),+ nameB: $('nameB'),+ bubbleA: $('bubbleA'),+ bubbleAText: $('bubbleAText'),+ bubbleB: $('bubbleB'),+ bubbleBText: $('bubbleBText'),+ topics: $('topics'),+ payBtn: $('payBtn'),+ payLabel: null, // set in init()+ stages: $('stages'),+ receipt: $('receipt'),+ totalUsdc: $('totalUsdc'),+};++// ── State ─────────────────────────────────────────────────────────────────────+let activeTopic = 'sol';+let busy = false;+let sessionTotal = 0; // USDC in dollars+let agentAReady = false;+let agentBReady = false;+const queueA = [];+const queueB = [];++// ── Avatar iframe driver ──────────────────────────────────────────────────────+function postToFrame(frame, ready, queue, msg) {+ if (ready) {+ frame.contentWindow?.postMessage(msg, location.origin);+ } else {+ queue.push(msg);+ }+}+function speakA(text) { postToFrame(els.frameA, agentAReady, queueA, { type: 'v1.avatar.speak', text }); }+function speakB(text) { postToFrame(els.frameB, agentBReady, queueB, { type: 'v1.avatar.speak', text }); }+function gestureA(name) { postToFrame(els.frameA, agentAReady, queueA, { type: 'v1.avatar.animation', name }); }+function gestureB(name) { postToFrame(els.frameB, agentBReady, queueB, { type: 'v1.avatar.animation', name }); }+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 === els.frameA.contentWindow) { agentAReady = true; flushQueue(els.frameA, queueA); }+ if (e.source === els.frameB.contentWindow) { agentBReady = true; flushQueue(els.frameB, queueB); }+});+// Resilience: if the avatar never signals ready, flush after 5 s.+setTimeout(() => {+ if (!agentAReady) { agentAReady = true; flushQueue(els.frameA, queueA); }+ if (!agentBReady) { agentBReady = true; flushQueue(els.frameB, queueB); }+}, 5000);++// ── Speech bubbles ────────────────────────────────────────────────────────────+let bubbleATimer, bubbleBTimer;+function sayA(text) {+ els.bubbleAText.textContent = text;+ els.bubbleA.classList.add('show');+ clearTimeout(bubbleATimer);+ bubbleATimer = setTimeout(() => els.bubbleA.classList.remove('show'), 5500);+ speakA(text);+}+function sayB(text) {+ els.bubbleBText.textContent = text;+ els.bubbleB.classList.add('show');+ clearTimeout(bubbleBTimer);+ bubbleBTimer = setTimeout(() => els.bubbleB.classList.remove('show'), 5500);+ speakB(text);+}++// ── Payment stages ────────────────────────────────────────────────────────────+function renderStages() {+ els.stages.innerHTML = STAGE_DEFS.map((s) =>+ `<div class="stage" id="stage-${s.id}">` ++ `<span class="si" aria-hidden="true"></span>` ++ `<span>${s.label}</span>` ++ `<span class="sval" id="sval-${s.id}"></span>` ++ `</div>`,+ ).join('');+}++function setStage(id, state, val = '') {+ const el = $(`stage-${id}`);+ if (!el) return;+ el.className = `stage ${state}`;+ const sv = $(`sval-${id}`);+ if (sv) sv.textContent = val ? `· ${val}` : '';+}++function resetStages() {+ for (const s of STAGE_DEFS) setStage(s.id, '');+ els.receipt.classList.remove('show');+}++// ── Receipt renderer ──────────────────────────────────────────────────────────+function renderReceipt(payment, intel) {+ const amount = payment.amount ? `${(Number(payment.amount) / 1e6).toFixed(4)} USDC` : '$0.01 USDC';+ const payer = payment.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-4)}` : '—';+ const payTo = payment.payTo ? `${payment.payTo.slice(0, 8)}…${payment.payTo.slice(-4)}` : '—';+ const txShort = payment.tx ? `${payment.tx.slice(0, 10)}…${payment.tx.slice(-6)}` : null;+ const explorer = payment.tx ? `https://solscan.io/tx/${payment.tx}` : null;+ const signalCls = `signal-${intel.signal}`;+ const signalEmoji = { bullish: '▲', bearish: '▼', neutral: '→' }[intel.signal] || '';++ const changeStr = intel.change_24h != null+ ? ` ${intel.change_24h >= 0 ? '+' : ''}${intel.change_24h.toFixed(2)}% 24h`+ : '';+ const priceStr = intel.price_usd != null+ ? ` · $${intel.price_usd >= 100 ? intel.price_usd.toFixed(2) : intel.price_usd.toFixed(4)}`+ : '';++ els.receipt.innerHTML =+ `<div class="r-head">` ++ `<span class="r-badge">` ++ `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>` ++ `Confirmed on-chain · ${amount}</span>` ++ `<span class="r-time">${new Date().toLocaleTimeString()}</span>` ++ `</div>` ++ `<div class="r-grid">` ++ `<div class="rf"><span class="k">Payer (buyer agent)</span><span class="v">${payer}</span></div>` ++ `<div class="rf"><span class="k">Payee (intel agent)</span><span class="v">${payTo}</span></div>` ++ `<div class="rf"><span class="k">Network</span><span class="v">Solana mainnet</span></div>` ++ (txShort && explorer+ ? `<div class="rf"><span class="k">Transaction</span><span class="v"><a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a></span></div>`+ : '') ++ `</div>` ++ `<div class="r-headline">` ++ `<span class="r-signal ${signalCls}">${signalEmoji} ${intel.signal.toUpperCase()}</span>` ++ `<strong>${escHtml(intel.topic.toUpperCase())}</strong>${escHtml(priceStr)}${escHtml(changeStr)} · ` ++ escHtml(intel.headline) ++ `</div>`;++ els.receipt.classList.add('show');+}++// ── Main payment flow ─────────────────────────────────────────────────────────+async function doPurchase() {+ if (busy) return;+ busy = true;+ els.payBtn.classList.add('busy');+ els.payBtn.disabled = true;+ els.payLabel.textContent = 'Paying…';+ resetStages();++ // Both agents react to the initiation.+ const line = LINES.B.idle(activeTopic);+ sayB(line);+ gestureB('wave');+ await delay(600);+ sayA(LINES.A.idle);++ let settled = null;+ let intel = null;+ let activeStage = 'challenge';+ let errored = false;++ try {+ const res = await fetch('/api/x402-pay', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({+ tool: 'crypto_intel',+ topic: activeTopic,+ // Tell x402-pay which endpoint to call. The server proxies to+ // /api/x402/crypto-intel with the x402 payment attached.+ endpoint: '/api/x402/crypto-intel',+ body: { topic: activeTopic },+ }),+ });++ if (!res.ok || !res.body) {+ const text = await res.text().catch(() => '');+ let msg = 'Payment service unavailable.';+ try { msg = JSON.parse(text).error_description || msg; } catch { /* ignore */ }+ throw new Error(msg);+ }++ for await (const { event, data } of sseReader(res)) {+ if (event === 'challenge') {+ setStage('challenge', 'done', `${(Number(data.amount) / 1e6).toFixed(4)} USDC`);+ setStage('built', 'active', 'signing…');+ activeStage = 'built';+ sayB(LINES.B.challenge);+ sayA(LINES.A.challenge);+ } else if (event === 'built') {+ setStage('built', 'done', `${data.build_ms} ms`);+ setStage('verified', 'active', 'facilitator…');+ activeStage = 'verified';+ sayB(LINES.B.built);+ sayA(LINES.A.built);+ } else if (event === 'verified') {+ setStage('verified', 'done', `${data.verify_ms} ms`);+ setStage('settled', 'active', 'on-chain…');+ activeStage = 'settled';+ sayB(LINES.B.verified);+ sayA(LINES.A.verified);+ } else if (event === 'settled') {+ setStage('settled', 'done', `${data.settle_ms} ms · ${data.tx ? data.tx.slice(0, 8) + '…' : ''}`);+ setStage('done', 'active');+ activeStage = 'done';+ settled = data;+ sayB(LINES.B.settled);+ sayA(LINES.A.settled);+ } else if (event === 'result') {+ intel = data;+ } else if (event === 'error') {+ errored = true;+ setStage(activeStage, 'error', data.error || 'failed');+ throw new Error(data.error || 'payment failed');+ }+ }++ if (!intel || !settled) throw new Error('incomplete response from payment service');++ // ── Success choreography ──────────────────────────────+ setStage('done', 'done', 'confirmed');++ // Buyer celebrates receiving the intel.+ gestureB('celebrate');+ await delay(300);+ sayB(LINES.B.done(intel.signal));++ // Seller delivers the headline.+ await delay(700);+ sayA(LINES.A.done(intel.headline));+ gestureA('wave');++ // Update session total.+ const amount = intel ? 0.01 : Number(settled.amount || 10000) / 1e6;+ sessionTotal += amount;+ els.totalUsdc.textContent = `$${sessionTotal.toFixed(2)}`;+ els.totalUsdc.classList.add('flash');+ setTimeout(() => els.totalUsdc.classList.remove('flash'), 600);++ // Show the receipt.+ renderReceipt(settled, intel);++ } catch (err) {+ if (!errored) setStage(activeStage, 'error', 'failed');+ sayA(LINES.A.error);+ sayB(LINES.B.error);+ gestureA('idle');+ // Show a user-facing error in the receipt area.+ els.receipt.innerHTML =+ `<div style="color:var(--red);font-size:13px;font-weight:600;">` ++ `⚠ ${escHtml(err.message || 'Payment failed. No funds moved.')} ` ++ `<a href="/pay" style="color:var(--usdc-lt);text-decoration:underline;">See the x402 demo →</a>` ++ `</div>`;+ els.receipt.classList.add('show');+ } finally {+ busy = false;+ els.payBtn.classList.remove('busy');+ els.payBtn.disabled = false;+ els.payLabel.textContent = 'Buy intel — $0.01 USDC';+ }+}++// ── SSE reader (same pattern as /pay demo) ────────────────────────────────────+async function* sseReader(res) {+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ let buf = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ const chunks = buf.split('\n\n');+ buf = chunks.pop();+ for (const chunk of chunks) {+ if (!chunk.trim()) continue;+ let event = 'message', data = {};+ for (const line of chunk.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ if (line.startsWith('data:')) {+ try { data = JSON.parse(line.slice(5).trim()); } catch { /* ignore */ }+ }+ }+ yield { event, data };+ }+ }+}++// ── Helpers ───────────────────────────────────────────────────────────────────+const delay = (ms) => new Promise((r) => setTimeout(r, ms));+function escHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++// ── Init ──────────────────────────────────────────────────────────────────────+function buildTopics() {+ for (const t of TOPICS) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 't-chip' + (t.id === activeTopic ? ' active' : '');+ b.textContent = t.label;+ b.dataset.id = t.id;+ b.setAttribute('aria-pressed', String(t.id === activeTopic));+ b.addEventListener('click', () => {+ if (busy) return;+ activeTopic = t.id;+ els.topics.querySelectorAll('.t-chip').forEach((c) => {+ c.classList.toggle('active', c.dataset.id === activeTopic);+ c.setAttribute('aria-pressed', String(c.dataset.id === activeTopic));+ });+ // Buyer agent reacts to topic change.+ const line = `Switching to ${t.id.toUpperCase()} intel. Ready to buy.`;+ sayB(line);+ });+ els.topics.appendChild(b);+ }+}++function mountAvatars() {+ // Agent A (seller) — faces right (mirror = true flips the avatar).+ const aqA = new URLSearchParams();+ aqA.set('model', '/avatars/default.glb');+ aqA.set('bg', 'transparent');+ aqA.set('idle', 'on');+ aqA.set('name', '0');+ aqA.set('animPicker', '0');+ aqA.set('overlayMode', '1');+ els.frameA.src = `/avatar-embed.html?${aqA}`;++ // Agent B (buyer) — same setup on the right side.+ const aqB = new URLSearchParams();+ aqB.set('model', '/avatars/default.glb');+ aqB.set('bg', 'transparent');+ aqB.set('idle', 'on');+ aqB.set('name', '0');+ aqB.set('animPicker', '0');+ aqB.set('overlayMode', '1');+ els.frameB.src = `/avatar-embed.html?${aqB}`;+}++function init() {+ els.payLabel = els.payBtn.querySelector('.lbl');++ buildTopics();+ renderStages();+ mountAvatars();++ els.payBtn.addEventListener('click', doPurchase);++ // Opening lines once both avatars are ready (or after timeout).+ setTimeout(() => {+ sayA(LINES.A.idle);+ setTimeout(() => sayB(LINES.B.idle(activeTopic)), 1400);+ }, 2000);+}++init();diff --git a/src/agent-trade.js b/src/agent-trade.jsnew file mode 100644index 000000000..ffdba7d19--- /dev/null+++ b/src/agent-trade.js@@ -0,0 +1,603 @@+// Agent-to-agent x402 trade demo — Three.js scene + SSE consumer.+// Two 3D avatars (Nexus buyer, Oracle seller) face each other on glowing+// platforms. A particle beam fires when SOL moves on-chain; each step of+// the x402 protocol animates in real time.++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';++// ── Constants ──────────────────────────────────────────────────────────────+const BUYER_COL = new THREE.Color(0x4589ff); // IBM blue+const SELLER_COL = new THREE.Color(0xf1c21b); // IBM gold+const BUYER_POS = new THREE.Vector3(-3.4, 0, 0);+const SELLER_POS = new THREE.Vector3( 3.4, 0, 0);+const BEAM_N = 350; // beam particles+const BURST_N = 90; // confirmation burst particles+const AVATAR_GLB = '/avatars/default.glb';++// ── Renderer ───────────────────────────────────────────────────────────────+const canvas = document.getElementById('canvas');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+renderer.setSize(innerWidth, innerHeight);+renderer.outputColorSpace = THREE.SRGBColorSpace;+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.15;+renderer.shadowMap.enabled = false;++// ── Scene ──────────────────────────────────────────────────────────────────+const scene = new THREE.Scene();+scene.background = new THREE.Color(0x05050e);+scene.fog = new THREE.FogExp2(0x05050e, 0.038);++// ── Camera ─────────────────────────────────────────────────────────────────+const camera = new THREE.PerspectiveCamera(52, innerWidth / innerHeight, 0.1, 100);+camera.position.set(0, 2.9, 9.8);++const controls = new OrbitControls(camera, canvas);+controls.target.set(0, 1.1, 0);+controls.enableDamping = true;+controls.dampingFactor = 0.07;+controls.minDistance = 4;+controls.maxDistance = 20;+controls.maxPolarAngle = Math.PI * 0.68;+controls.autoRotate = true;+controls.autoRotateSpeed = 0.35;+controls.update();++// ── Lights ─────────────────────────────────────────────────────────────────+scene.add(new THREE.AmbientLight(0x10102a, 4));++const buyerLight = new THREE.PointLight(BUYER_COL, 10, 9);+buyerLight.position.set(BUYER_POS.x, 2.5, 1.2);+scene.add(buyerLight);++const sellerLight = new THREE.PointLight(SELLER_COL, 10, 9);+sellerLight.position.set(SELLER_POS.x, 2.5, 1.2);+scene.add(sellerLight);++const keyLight = new THREE.DirectionalLight(0xffffff, 1.8);+keyLight.position.set(2, 6, 3);+scene.add(keyLight);++// ── Floor ──────────────────────────────────────────────────────────────────+const grid = new THREE.GridHelper(32, 32, 0x1a1a4e, 0x0c0c24);+grid.position.y = 0.001;+scene.add(grid);++const floorGeo = new THREE.PlaneGeometry(32, 32);+const floorMat = new THREE.MeshStandardMaterial({ color: 0x050510, roughness: 1, metalness: 0 });+const floor = new THREE.Mesh(floorGeo, floorMat);+floor.rotation.x = -Math.PI / 2;+scene.add(floor);++// ── Platforms ──────────────────────────────────────────────────────────────+function makePlatform(worldPos, col) {+ const g = new THREE.Group();++ const discGeo = new THREE.CylinderGeometry(1.15, 1.35, 0.09, 48);+ const discMat = new THREE.MeshStandardMaterial({+ color: 0x0d0d1c, emissive: col, emissiveIntensity: 0.2,+ roughness: 0.3, metalness: 0.8,+ });+ g.add(new THREE.Mesh(discGeo, discMat));++ const ringGeo = new THREE.TorusGeometry(1.15, 0.028, 8, 64);+ const ringMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 1.8 });+ const ring = new THREE.Mesh(ringGeo, ringMat);+ ring.rotation.x = Math.PI / 2;+ ring.position.y = 0.045;+ g.add(ring);++ g.position.copy(worldPos);+ scene.add(g);+ return { group: g, ring };+}++const buyerPlatform = makePlatform(BUYER_POS, BUYER_COL);+const sellerPlatform = makePlatform(SELLER_POS, SELLER_COL);++// ── Background stars ────────────────────────────────────────────────────────+{+ const N = 1400;+ const pos = new Float32Array(N * 3);+ for (let i = 0; i < N; i++) {+ const th = Math.random() * Math.PI * 2;+ const ph = Math.acos(2 * Math.random() - 1);+ const r = 42 + Math.random() * 8;+ pos[i * 3] = r * Math.sin(ph) * Math.cos(th);+ pos[i * 3 + 1] = r * Math.sin(ph) * Math.sin(th);+ pos[i * 3 + 2] = r * Math.cos(ph);+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));+ scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0xffffff, size: 0.07, transparent: true, opacity: 0.65 })));+}++// ── Avatar loading ──────────────────────────────────────────────────────────+const gltfLoader = new GLTFLoader();+const draco = new DRACOLoader();+draco.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.7/');+gltfLoader.setDRACOLoader(draco);++// Label tracking positions (above each avatar's head)+const labelPos = {+ buyer: BUYER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),+ seller: SELLER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),+};++let buyerMesh = null;+let sellerMesh = null;++function applyTint(gltfScene, col) {+ gltfScene.traverse((child) => {+ if (!child.isMesh) return;+ const mats = Array.isArray(child.material) ? child.material : [child.material];+ const tinted = mats.map((m) => {+ const n = m.clone();+ n.color.multiplyScalar(0.65).addScaledVector(col, 0.38);+ n.emissive = col.clone().multiplyScalar(0.07);+ n.emissiveIntensity = 1;+ return n;+ });+ child.material = tinted.length === 1 ? tinted[0] : tinted;+ });+}++function makeFallbackFigure(col) {+ const g = new THREE.Group();+ const bodyMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 0.12, roughness: 0.6, metalness: 0.3 });+ g.add(Object.assign(new THREE.Mesh(new THREE.CapsuleGeometry(0.31, 1.0, 8, 16), bodyMat)));+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.25, 16, 16), bodyMat.clone());+ head.position.y = 1.05;+ g.add(head);+ return g;+}++function loadAvatar(worldPos, col, yaw, onLoaded) {+ gltfLoader.load(AVATAR_GLB, (gltf) => {+ const s = gltf.scene.clone(true);+ applyTint(s, col);+ s.position.copy(worldPos);+ s.rotation.y = yaw;+ scene.add(s);+ const box = new THREE.Box3().setFromObject(s);+ onLoaded(s, new THREE.Vector3(worldPos.x, box.max.y + 0.18, worldPos.z));+ }, undefined, () => {+ // GLB failed (CORS in dev? missing file?) — use stylised capsule+ const s = makeFallbackFigure(col);+ s.position.copy(worldPos);+ s.rotation.y = yaw;+ scene.add(s);+ onLoaded(s, new THREE.Vector3(worldPos.x, 2.15, worldPos.z));+ });+}++loadAvatar(BUYER_POS, BUYER_COL, 0.12, (m, top) => { buyerMesh = m; labelPos.buyer = top; });+loadAvatar(SELLER_POS, SELLER_COL, -0.12, (m, top) => { sellerMesh = m; labelPos.seller = top; });++// ── Payment beam ────────────────────────────────────────────────────────────+const beamPhases = new Float32Array(BEAM_N).map(() => Math.random());+const beamSpeeds = new Float32Array(BEAM_N).map(() => 0.28 + Math.random() * 0.55);+const beamPos = new Float32Array(BEAM_N * 3);++const beamGeo = new THREE.BufferGeometry();+beamGeo.setAttribute('position', new THREE.BufferAttribute(beamPos, 3));+const beamMat = new THREE.PointsMaterial({+ color: 0x4589ff, size: 0.065, transparent: true, opacity: 0,+ blending: THREE.AdditiveBlending, depthWrite: false,+});+scene.add(new THREE.Points(beamGeo, beamMat));++let beamActive = false;++function startBeam() {+ beamActive = true;+ beamMat.opacity = 0.92;+}++// ── Confirmation burst ──────────────────────────────────────────────────────+const burstPos = new Float32Array(BURST_N * 3);+const burstVels = new Float32Array(BURST_N * 3);+const burstGeo = new THREE.BufferGeometry();+burstGeo.setAttribute('position', new THREE.BufferAttribute(burstPos, 3));+const burstMat = new THREE.PointsMaterial({+ color: 0x42be65, size: 0.1, transparent: true, opacity: 0,+ blending: THREE.AdditiveBlending, depthWrite: false,+});+scene.add(new THREE.Points(burstGeo, burstMat));++let burstLife = 0;++function triggerBurst() {+ beamActive = false;+ const s = SELLER_POS;+ for (let i = 0; i < BURST_N; i++) {+ burstPos[i * 3] = s.x + (Math.random() - 0.5) * 0.3;+ burstPos[i * 3 + 1] = s.y + 0.95 + Math.random() * 0.4;+ burstPos[i * 3 + 2] = s.z + (Math.random() - 0.5) * 0.3;+ const th = Math.random() * Math.PI * 2;+ const spd = 1.2 + Math.random() * 2.2;+ burstVels[i * 3] = Math.cos(th) * spd;+ burstVels[i * 3 + 1] = (0.5 + Math.random()) * spd;+ burstVels[i * 3 + 2] = Math.sin(th) * spd * 0.5;+ }+ burstGeo.attributes.position.needsUpdate = true;+ burstMat.opacity = 1;+ burstLife = 1.2;+}++// ── DOM references ──────────────────────────────────────────────────────────+const els = {+ buyerLabel: document.getElementById('buyerLabel'),+ sellerLabel: document.getElementById('sellerLabel'),+ buyerAddr: document.getElementById('buyerAddr'),+ sellerAddr: document.getElementById('sellerAddr'),+ buyerBal: document.getElementById('buyerBal'),+ buyerBubble: document.getElementById('buyerBubble'),+ sellerBubble: document.getElementById('sellerBubble'),+ centralCard: document.getElementById('centralCard'),+ stepLog: document.getElementById('stepLog'),+ startBtn: document.getElementById('startBtn'),+ topicSelect: document.getElementById('topicSelect'),+ networkBadge: document.getElementById('networkBadge'),+ notConfigured:document.getElementById('notConfigured'),+ toast: document.getElementById('toast'),+ cfgClose: document.getElementById('cfgClose'),+};++els.cfgClose.addEventListener('click', () => els.notConfigured.classList.add('hidden'));++// ── Label & bubble positioning ──────────────────────────────────────────────+function project(v3) {+ const v = v3.clone().project(camera);+ return { x: (v.x * 0.5 + 0.5) * innerWidth, y: (-v.y * 0.5 + 0.5) * innerHeight };+}++function placeEl(el, worldPos, xOffset = 0, yOffset = 0) {+ const p = project(worldPos);+ el.style.left = `${p.x + xOffset}px`;+ el.style.top = `${p.y + yOffset}px`;+ el.style.transform = 'translate(-50%, -100%)';+}++function updateOverlays() {+ placeEl(els.buyerLabel, labelPos.buyer, 0, -8);+ placeEl(els.sellerLabel, labelPos.seller, 0, -8);++ if (!els.buyerBubble.classList.contains('hidden')) {+ const bp = labelPos.buyer.clone().add(new THREE.Vector3(0, 0.55, 0));+ placeEl(els.buyerBubble, bp, 0, -4);+ }+ if (!els.sellerBubble.classList.contains('hidden')) {+ const sp = labelPos.seller.clone().add(new THREE.Vector3(0, 0.55, 0));+ placeEl(els.sellerBubble, sp, 0, -4);+ }+}++// ── Bubble helpers ──────────────────────────────────────────────────────────+function showBubble(side, text) {+ const el = side === 'buyer' ? els.buyerBubble : els.sellerBubble;+ el.textContent = text;+ el.classList.remove('hidden');+}+function hideBubble(side) {+ const el = side === 'buyer' ? els.buyerBubble : els.sellerBubble;+ el.classList.add('hidden');+}++// ── Central card ────────────────────────────────────────────────────────────+function showCard(html) {+ els.centralCard.innerHTML = html;+ els.centralCard.classList.remove('hidden');+}+function hideCard() { els.centralCard.classList.add('hidden'); }++// ── Step log ─────────────────────────────────────────────────────────────────+const STEP_NAMES = ['init', 'request', 'challenged', 'paying', 'confirmed', 'delivering', 'delivered'];+const chips = {};++function buildStepLog() {+ els.stepLog.innerHTML = '';+ STEP_NAMES.forEach((s) => {+ const c = document.createElement('div');+ c.className = 'step-chip';+ c.textContent = s;+ els.stepLog.appendChild(c);+ chips[s] = c;+ });+}++function setChip(name, state) {+ const c = chips[name];+ if (!c) return;+ c.classList.remove('active', 'done', 'error');+ if (state) c.classList.add(state);+}++// ── Toast ────────────────────────────────────────────────────────────────────+let toastTimer = null;+function showToast(msg) {+ els.toast.textContent = msg;+ els.toast.classList.add('show');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => els.toast.classList.remove('show'), 5000);+}++// ── Camera animation ─────────────────────────────────────────────────────────+const camAnim = { active: false, t: 0, dur: 0, fromPos: new THREE.Vector3(), toPos: new THREE.Vector3(), fromTgt: new THREE.Vector3(), toTgt: new THREE.Vector3() };++function flyCamera(toPos, toTgt, dur = 1100) {+ camAnim.fromPos.copy(camera.position);+ camAnim.toPos.copy(toPos);+ camAnim.fromTgt.copy(controls.target);+ camAnim.toTgt.copy(toTgt);+ camAnim.t = 0;+ camAnim.dur = dur;+ camAnim.active = true;+}++// ── SSE event handling ────────────────────────────────────────────────────────+function setRunning(on) {+ els.startBtn.disabled = on;+ els.topicSelect.disabled = on;+ els.startBtn.textContent = on ? '⏳ Running…' : '▶ Run Trade Demo';+ if (!on) controls.autoRotate = true;+}++function fmt(addr) {+ return addr ? addr.slice(0, 4) + '…' + addr.slice(-4) : '—';+}++function handleEvent(ev) {+ switch (ev.type) {+ case 'init': {+ setChip('init', 'done');+ if (ev.buyer?.address) {+ els.buyerAddr.textContent = fmt(ev.buyer.address);+ if (ev.buyer.sol != null) {+ const usd = ev.buyer.usd != null ? ` ($${ev.buyer.usd})` : '';+ els.buyerBal.textContent = ev.buyer.sol.toFixed(4) + ' SOL' + usd;+ els.buyerBal.style.color = 'var(--green)';+ }+ }+ if (ev.seller?.address) els.sellerAddr.textContent = fmt(ev.seller.address);+ if (ev.network) els.networkBadge.textContent = ev.network;+ controls.autoRotate = false;+ flyCamera(new THREE.Vector3(0, 2.6, 8.8), new THREE.Vector3(0, 1.1, 0), 1200);+ break;+ }++ case 'request': {+ setChip('request', 'active');+ showBubble('buyer', `"${ev.message || 'I need a market analysis…'}"`);+ setTimeout(() => setChip('request', 'done'), 900);+ break;+ }++ case 'challenged': {+ setChip('request', 'done');+ setChip('challenged', 'active');+ hideBubble('buyer');+ const m = ev.manifest || {};+ const price = m.price || {};+ const usdStr = price.usd != null ? ` ≈ $${price.usd}` : '';+ showBubble('seller', `402 — ${price.sol} SOL required`);+ showCard(`+ <div class="c-badge c-badge-402">⟶ 402 Payment Required</div>+ <div class="c-label">x402 Protocol · oracle-market-analysis</div>+ <div class="c-price blue">${price.sol ?? '?'} SOL${usdStr}</div>+ <div class="c-row">Recipient <span>${fmt(m.recipient)}</span></div>+ <div class="c-row">Network <span>${m.network || '—'}</span></div>+ <div class="c-row">Memo <span>${m.memo || '—'}</span></div>+ <div class="c-row">Currency <span>${m.currency || 'SOL'}</span></div>+ `);+ setTimeout(() => setChip('challenged', 'done'), 700);+ break;+ }++ case 'paying': {+ setChip('paying', 'active');+ hideBubble('seller');+ hideCard();+ showBubble('buyer', `Sending ${ev.sol} SOL on-chain…`);+ startBeam();+ // Fly camera to watch the beam from a low angle+ flyCamera(new THREE.Vector3(0, 1.6, 7.2), new THREE.Vector3(0, 0.9, 0), 950);+ break;+ }++ case 'confirmed': {+ setChip('paying', 'done');+ setChip('confirmed', 'active');+ triggerBurst();+ hideBubble('buyer');+ setTimeout(() => showBubble('seller', 'Payment confirmed ✓'), 350);+ if (ev.newBuyerSol != null) {+ els.buyerBal.textContent = ev.newBuyerSol.toFixed(4) + ' SOL';+ els.buyerBal.style.color = 'var(--muted)';+ }+ const sigShort = ev.signature ? ev.signature.slice(0, 8) + '…' + ev.signature.slice(-6) : '';+ const usdStr = ev.usd != null ? ` ≈ $${ev.usd}` : '';+ showCard(`+ <div class="c-badge c-badge-ok">✓ Transaction Confirmed</div>+ <div class="c-label">On-Chain · ${ev.sol} SOL${usdStr}</div>+ <div class="c-price green">${ev.sol} SOL</div>+ <div class="c-row">Signature <span>${sigShort}</span></div>+ <div class="c-row">Network <span>${ev.network || 'solana'}</span></div>+ ${ev.explorer ? `<a class="c-link" href="${ev.explorer}" target="_blank" rel="noopener">View on Solscan →</a>` : ''}+ `);+ setTimeout(() => setChip('confirmed', 'done'), 800);+ break;+ }++ case 'delivering': {+ setChip('delivering', 'active');+ setTimeout(() => {+ hideBubble('seller');+ showBubble('seller', `Analyzing with ${ev.model}…`);+ hideCard();+ }, 200);+ // Fly back to a wide view+ flyCamera(new THREE.Vector3(0, 3.0, 9.5), new THREE.Vector3(0, 1.2, 0), 1100);+ break;+ }++ case 'delivered': {+ setChip('delivering', 'done');+ setChip('delivered', 'done');+ hideBubble('seller');+ controls.autoRotate = true;+ showCard(`+ <div class="c-badge c-badge-ok">✓ Skill Delivered</div>+ <div class="c-label">${ev.provider || 'AI'} · ${ev.topic || ''}</div>+ <div class="c-content">${ev.content || ''}</div>+ <div class="c-powered">+ Powered by ${ev.model || ev.provider || ''}+ ${ev.explorer ? ` · <a class="c-link" style="display:inline" href="${ev.explorer}" target="_blank" rel="noopener">tx →</a>` : ''}+ </div>+ `);+ setRunning(false);+ break;+ }++ case 'error': {+ STEP_NAMES.forEach((s) => { if (chips[s]?.classList.contains('active')) setChip(s, 'error'); });+ showToast(ev.message || 'Something went wrong');+ setRunning(false);+ beamActive = false;+ beamMat.opacity = 0;+ break;+ }+ }+}++// ── Start demo ───────────────────────────────────────────────────────────────+let currentEs = null;++function startDemo() {+ if (currentEs) { currentEs.close(); currentEs = null; }+ const topic = els.topicSelect.value;+ setRunning(true);+ hideCard();+ hideBubble('buyer');+ hideBubble('seller');+ beamActive = false;+ beamMat.opacity = 0;+ buildStepLog();++ const es = new EventSource(`/api/agent-trade/demo?topic=${encodeURIComponent(topic)}`);+ currentEs = es;++ es.onmessage = (e) => {+ try {+ const ev = JSON.parse(e.data);+ handleEvent(ev);+ if (ev.type === 'delivered' || ev.type === 'error') {+ es.close();+ currentEs = null;+ }+ } catch { /* malformed event — ignore */ }+ };++ es.onerror = () => {+ showToast('Stream error — check wallet config and try again.');+ setRunning(false);+ es.close();+ currentEs = null;+ };+}++els.startBtn.addEventListener('click', startDemo);++// ── Config pre-flight ─────────────────────────────────────────────────────────+async function checkConfig() {+ try {+ const r = await fetch('/api/agent-trade/demo?check=1');+ if (!r.ok) return;+ const d = await r.json();+ if (!d.configured) {+ els.notConfigured.classList.remove('hidden');+ els.startBtn.disabled = true;+ } else {+ if (d.buyer?.address) els.buyerAddr.textContent = fmt(d.buyer.address);+ if (d.seller?.address) els.sellerAddr.textContent = fmt(d.seller.address);+ if (d.network) els.networkBadge.textContent = d.network;+ }+ } catch { /* API unreachable — leave button enabled, it will error gracefully */ }+}++// ── Resize ────────────────────────────────────────────────────────────────────+window.addEventListener('resize', () => {+ camera.aspect = innerWidth / innerHeight;+ camera.updateProjectionMatrix();+ renderer.setSize(innerWidth, innerHeight);+});++// ── Animation loop ─────────────────────────────────────────────────────────────+const clock = new THREE.Clock();++(function animate() {+ requestAnimationFrame(animate);+ const dt = Math.min(clock.getDelta(), 0.1);+ const t = clock.elapsedTime;++ // Idle avatar breath+ if (buyerMesh) buyerMesh.position.y = Math.sin(t * 0.75) * 0.022;+ if (sellerMesh) sellerMesh.position.y = Math.sin(t * 0.75 + 1.2) * 0.022;++ // Platform ring pulse+ buyerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0) * 0.5;+ sellerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0 + 1.0) * 0.5;++ // Beam travel+ if (beamActive) {+ const B = BUYER_POS, S = SELLER_POS;+ const spread = 0.13;+ for (let i = 0; i < BEAM_N; i++) {+ beamPhases[i] = (beamPhases[i] + beamSpeeds[i] * dt) % 1;+ const ph = beamPhases[i];+ beamPos[i * 3] = B.x + (S.x - B.x) * ph + (Math.random() - 0.5) * spread;+ beamPos[i * 3 + 1] = B.y + 0.9 + (Math.random() - 0.5) * spread;+ beamPos[i * 3 + 2] = (Math.random() - 0.5) * spread;+ }+ beamGeo.attributes.position.needsUpdate = true;+ beamMat.opacity = 0.75 + Math.sin(t * 14) * 0.18;+ } else if (beamMat.opacity > 0) {+ beamMat.opacity = Math.max(0, beamMat.opacity - dt * 2.5);+ if (beamMat.opacity === 0) beamGeo.attributes.position.needsUpdate = true;+ }++ // Burst particles+ if (burstLife > 0) {+ burstLife -= dt * 0.65;+ burstMat.opacity = Math.max(0, burstLife);+ for (let i = 0; i < BURST_N; i++) {+ burstVels[i * 3 + 1] -= 4.8 * dt; // gravity+ burstPos[i * 3] += burstVels[i * 3] * dt;+ burstPos[i * 3 + 1] += burstVels[i * 3 + 1] * dt;+ burstPos[i * 3 + 2] += burstVels[i * 3 + 2] * dt;+ }+ burstGeo.attributes.position.needsUpdate = true;+ if (burstLife <= 0) burstMat.opacity = 0;+ }++ // Camera animation+ if (camAnim.active) {+ camAnim.t += dt * 1000;+ const raw = Math.min(camAnim.t / camAnim.dur, 1);+ const ease = raw < 0.5 ? 2 * raw * raw : 1 - (-2 * raw + 2) ** 2 / 2;+ camera.position.lerpVectors(camAnim.fromPos, camAnim.toPos, ease);+ controls.target.lerpVectors(camAnim.fromTgt, camAnim.toTgt, ease);+ if (raw >= 1) camAnim.active = false;+ }++ controls.update();+ updateOverlays();+ renderer.render(scene, camera);+})();++checkConfig();+buildStepLog();diff --git a/src/constellation/main.js b/src/constellation/main.jsindex 728fd8335..8c1b14fcb 100644--- a/src/constellation/main.js+++ b/src/constellation/main.js@@ -390,7 +390,7 @@ async function runGraniteAnalysis(token, neighbors) {function graniteUnavailableNotice(code) {if (code === 'provider_not_configured') {- return '<div class="c-notice">IBM Granite isn\'t enabled on this deployment yet — set <code>WATSONX_API_KEY</code> to turn on live analysis. See the <a href="/ibm">IBM partnership page</a>.</div>';+ return '<div class="c-notice">IBM Granite isn\'t enabled on this deployment yet — set <code>WATSONX_API_KEY</code> to turn on live analysis. See the <a href="/ibm">IBM Granite demos</a>.</div>';}if (code === 'rate_limited') {return '<div class="c-notice">Rate limit reached — wait a moment and click again.</div>';diff --git a/src/demo-economy.js b/src/demo-economy.jsnew file mode 100644index 000000000..8d21e7d2e--- /dev/null+++ b/src/demo-economy.js@@ -0,0 +1,606 @@+// three.ws agent economy demo scene+// Two 3D AI agents (NOVA + ORACLE) exchange a real x402 payment in a stylized+// world. The TV screen between them shows the live Solana market briefing+// delivered after the transaction confirms.++import * as THREE from 'three';++// ─── Constants ─────────────────────────────────────────────────────────────++const NOVA_COLOR = new THREE.Color(0x4e8cff);+const ORACLE_COLOR = new THREE.Color(0x22d17a);+const TV_W = 3.6;+const TV_H = 2.0;+const TV_Z = -5;+const AGENT_Y = 0;+const NOVA_X = -3.8;+const ORACLE_X = 3.8;++// ─── Scene setup ────────────────────────────────────────────────────────────++export function createScene(canvas) {+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+ renderer.setSize(canvas.clientWidth, canvas.clientHeight);+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 0.95;+ renderer.outputColorSpace = THREE.SRGBColorSpace;++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x05070d);+ scene.fog = new THREE.FogExp2(0x05070d, 0.08);++ const camera = new THREE.PerspectiveCamera(48, canvas.clientWidth / canvas.clientHeight, 0.1, 100);+ camera.position.set(0, 2.8, 8);+ camera.lookAt(0, 1.2, 0);++ // ── Lights ──────────────────────────────────────────────────────────────+ const ambient = new THREE.AmbientLight(0xffffff, 0.15);+ scene.add(ambient);++ const rimNova = new THREE.PointLight(NOVA_COLOR, 2.5, 8);+ rimNova.position.set(NOVA_X, 2, 1);+ scene.add(rimNova);++ const rimOracle = new THREE.PointLight(ORACLE_COLOR, 2.5, 8);+ rimOracle.position.set(ORACLE_X, 2, 1);+ scene.add(rimOracle);++ const tvLight = new THREE.RectAreaLight(0xffffff, 1.5, TV_W, TV_H);+ tvLight.position.set(0, 1.4, TV_Z + 0.3);+ tvLight.lookAt(0, 1.4, 0);+ scene.add(tvLight);++ // ── Ground ───────────────────────────────────────────────────────────────+ const gridHelper = new THREE.GridHelper(20, 20, 0x1a1c2e, 0x0f1020);+ gridHelper.position.y = -0.01;+ scene.add(gridHelper);++ const ground = new THREE.Mesh(+ new THREE.PlaneGeometry(40, 40),+ new THREE.MeshStandardMaterial({ color: 0x07080f, roughness: 1, metalness: 0 }),+ );+ ground.rotation.x = -Math.PI / 2;+ ground.position.y = -0.02;+ scene.add(ground);++ // ── Agents ───────────────────────────────────────────────────────────────+ const nova = createAgent(scene, NOVA_X, AGENT_Y, NOVA_COLOR, 'NOVA');+ const oracle = createAgent(scene, ORACLE_X, AGENT_Y, ORACLE_COLOR, 'ORACLE');++ // ── TV Screen ────────────────────────────────────────────────────────────+ const tv = createTV(scene);++ // ── Payment beam (initially invisible) ──────────────────────────────────+ const beam = createBeam(scene);++ // ── Resize observer ──────────────────────────────────────────────────────+ const ro = new ResizeObserver(() => {+ const w = canvas.clientWidth, h = canvas.clientHeight;+ renderer.setSize(w, h);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ });+ ro.observe(canvas);++ // ── Render loop ──────────────────────────────────────────────────────────+ let raf;+ let t = 0;+ function tick() {+ raf = requestAnimationFrame(tick);+ t += 0.016;++ nova.tick(t);+ oracle.tick(t);+ beam.tick(t);+ tv.tick(t);++ renderer.render(scene, camera);+ }+ tick();++ return {+ nova,+ oracle,+ tv,+ beam,+ dispose() {+ cancelAnimationFrame(raf);+ ro.disconnect();+ renderer.dispose();+ },+ };+}++// ─── Agent figure ──────────────────────────────────────────────────────────++function createAgent(scene, x, y, color, name) {+ const group = new THREE.Group();+ group.position.set(x, y, 0);+ scene.add(group);++ // Body — tapered capsule shape+ const bodyMat = new THREE.MeshStandardMaterial({+ color,+ roughness: 0.35,+ metalness: 0.6,+ emissive: color,+ emissiveIntensity: 0.08,+ });+ const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.32, 0.9, 6, 12), bodyMat);+ body.position.y = 0.9;+ group.add(body);++ // Head+ const headMat = new THREE.MeshStandardMaterial({+ color: 0xd0d8f0,+ roughness: 0.4,+ metalness: 0.3,+ emissive: color,+ emissiveIntensity: 0.04,+ });+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.24, 16, 16), headMat);+ head.position.y = 1.78;+ group.add(head);++ // Eyes+ const eyeMat = new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 1 });+ [-0.08, 0.08].forEach((ex) => {+ const eye = new THREE.Mesh(new THREE.SphereGeometry(0.04, 8, 8), eyeMat);+ eye.position.set(ex, 1.81, 0.21);+ group.add(eye);+ });++ // Glow halo ring at feet+ const ringMat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.18, side: THREE.DoubleSide });+ const ring = new THREE.Mesh(new THREE.RingGeometry(0.35, 0.5, 32), ringMat);+ ring.rotation.x = -Math.PI / 2;+ ring.position.y = 0.01;+ group.add(ring);++ // Particle aura (6 floating orbs)+ const orbs = [];+ for (let i = 0; i < 6; i++) {+ const orb = new THREE.Mesh(+ new THREE.SphereGeometry(0.035, 6, 6),+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.55 }),+ );+ group.add(orb);+ orbs.push({ mesh: orb, phase: (i / 6) * Math.PI * 2, r: 0.52 + (i % 2) * 0.1, hy: 0.9 + (i % 3) * 0.35 });+ }++ let state = 'idle'; // idle | active | paying | done+ let pulseT = 0;+ let bobDir = 1;++ function tick(t) {+ // Gentle idle bob+ const bob = Math.sin(t * 1.4 + (x > 0 ? Math.PI : 0)) * 0.04;+ body.position.y = 0.9 + bob;+ head.position.y = 1.78 + bob;++ // Orb orbit+ orbs.forEach(({ mesh, phase, r, hy }) => {+ const a = t * 1.1 + phase;+ mesh.position.set(Math.cos(a) * r, hy + Math.sin(t * 0.7 + phase) * 0.12, Math.sin(a) * r * 0.5);+ });++ // Ring pulse+ if (state === 'paying') {+ pulseT += 0.04;+ ringMat.opacity = 0.18 + Math.sin(pulseT * 8) * 0.12;+ bodyMat.emissiveIntensity = 0.25 + Math.sin(pulseT * 8) * 0.15;+ } else if (state === 'done') {+ ringMat.opacity = 0.35;+ bodyMat.emissiveIntensity = 0.3;+ } else {+ ringMat.opacity = 0.18;+ bodyMat.emissiveIntensity = 0.08;+ }+ }++ return {+ group,+ setState(s) { state = s; },+ tick,+ };+}++// ─── TV screen with canvas texture ─────────────────────────────────────────++function createTV(scene) {+ const CW = 1280, CH = 720;+ const canvas = document.createElement('canvas');+ canvas.width = CW;+ canvas.height = CH;+ const ctx = canvas.getContext('2d');++ const texture = new THREE.CanvasTexture(canvas);+ texture.colorSpace = THREE.SRGBColorSpace;++ // Frame / bezel+ const frameMat = new THREE.MeshStandardMaterial({ color: 0x0a0c14, roughness: 0.8, metalness: 0.9 });+ const frame = new THREE.Mesh(new THREE.BoxGeometry(TV_W + 0.16, TV_H + 0.12, 0.08), frameMat);+ frame.position.set(0, 1.4, TV_Z);+ scene.add(frame);++ // Screen+ const screenMat = new THREE.MeshBasicMaterial({ map: texture });+ const screen = new THREE.Mesh(new THREE.PlaneGeometry(TV_W, TV_H), screenMat);+ screen.position.set(0, 1.4, TV_Z + 0.05);+ scene.add(screen);++ // Support post+ const post = new THREE.Mesh(+ new THREE.BoxGeometry(0.08, 1.4, 0.08),+ new THREE.MeshStandardMaterial({ color: 0x0d0f1a, roughness: 0.9 }),+ );+ post.position.set(0, 0.05, TV_Z);+ scene.add(post);++ let phase = 'idle'; // idle | browsing | paying | content+ let briefing = null;+ let services = null;+ let scrollY = 0;+ let animT = 0;++ function draw(t) {+ ctx.clearRect(0, 0, CW, CH);++ // Background+ const bg = ctx.createLinearGradient(0, 0, 0, CH);+ bg.addColorStop(0, '#06080f');+ bg.addColorStop(1, '#0a0d18');+ ctx.fillStyle = bg;+ ctx.fillRect(0, 0, CW, CH);++ if (phase === 'idle') drawIdle(ctx, CW, CH, t);+ else if (phase === 'browsing') drawBazaar(ctx, CW, CH, services, t);+ else if (phase === 'paying') drawPaying(ctx, CW, CH, t);+ else if (phase === 'content') drawContent(ctx, CW, CH, briefing, t);++ texture.needsUpdate = true;+ }++ function tick(t) {+ animT = t;+ draw(t);+ }++ return {+ tick,+ setPhase(p) { phase = p; },+ setServices(s) { services = s; },+ setBriefing(b) { briefing = b; },+ };+}++// ── TV draw functions ──────────────────────────────────────────────────────++function drawIdle(ctx, W, H, t) {+ ctx.save();+ // Scanline effect+ for (let y = 0; y < H; y += 4) {+ ctx.fillStyle = `rgba(255,255,255,${0.012 + 0.005 * Math.sin(t * 0.4 + y * 0.02)})`;+ ctx.fillRect(0, y, W, 1);+ }+ // Center logo+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillStyle = 'rgba(78,140,255,0.15)';+ ctx.font = 'bold 120px -apple-system,system-ui,sans-serif';+ ctx.fillText('three.ws', W / 2, H / 2 - 40);+ ctx.fillStyle = 'rgba(255,255,255,0.25)';+ ctx.font = '32px -apple-system,system-ui,sans-serif';+ ctx.fillText('agent economy', W / 2, H / 2 + 40);+ // Blinking cursor+ if (Math.floor(t * 2) % 2 === 0) {+ ctx.fillStyle = 'rgba(78,140,255,0.6)';+ ctx.fillRect(W / 2 - 6, H / 2 + 90, 12, 3);+ }+ ctx.restore();+}++function drawBazaar(ctx, W, H, services, t) {+ if (!services) return;+ ctx.save();+ ctx.textAlign = 'left';++ // Header+ ctx.fillStyle = '#4e8cff';+ ctx.font = 'bold 38px -apple-system,system-ui,sans-serif';+ ctx.fillText('x402 Bazaar', 60, 70);+ ctx.fillStyle = 'rgba(255,255,255,0.3)';+ ctx.font = '26px -apple-system,system-ui,sans-serif';+ ctx.fillText('Available services · Coinbase network', 60, 110);++ // Divider+ ctx.strokeStyle = 'rgba(78,140,255,0.3)';+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(60, 130);+ ctx.lineTo(W - 60, 130);+ ctx.stroke();++ // Service rows+ const rowH = 110;+ (services || []).slice(0, 4).forEach((svc, i) => {+ const y = 160 + i * rowH;+ const highlight = i === 0 && Math.sin(t * 3) > 0;++ // Row bg+ ctx.fillStyle = highlight ? 'rgba(78,140,255,0.12)' : 'rgba(255,255,255,0.04)';+ roundRect(ctx, 50, y - 14, W - 100, rowH - 10, 14);+ ctx.fill();++ if (highlight) {+ ctx.strokeStyle = 'rgba(78,140,255,0.5)';+ ctx.lineWidth = 2;+ roundRect(ctx, 50, y - 14, W - 100, rowH - 10, 14);+ ctx.stroke();+ }++ // Dot+ ctx.fillStyle = i === 0 ? '#4e8cff' : '#22d17a';+ circle(ctx, 90, y + 26, 8);+ ctx.fill();++ // Name+ ctx.fillStyle = '#e8e9f2';+ ctx.font = `bold 30px -apple-system,system-ui,sans-serif`;+ ctx.fillText((svc.name || '').slice(0, 50), 116, y + 14);++ // Price badge+ const priceTxt = svc.price || '—';+ ctx.fillStyle = 'rgba(34,209,122,0.18)';+ const pw = ctx.measureText(priceTxt).width + 28;+ roundRect(ctx, W - 80 - pw, y, pw, 38, 10);+ ctx.fill();+ ctx.fillStyle = '#22d17a';+ ctx.font = 'bold 24px -apple-system,system-ui,monospace';+ ctx.textAlign = 'right';+ ctx.fillText(priceTxt, W - 90, y + 28);+ ctx.textAlign = 'left';++ // Network+ ctx.fillStyle = 'rgba(255,255,255,0.35)';+ ctx.font = '22px -apple-system,system-ui,sans-serif';+ ctx.fillText(svc.network || '', 116, y + 55);+ });++ ctx.restore();+}++function drawPaying(ctx, W, H, t) {+ ctx.save();+ ctx.textAlign = 'center';++ // Animated rings+ for (let ring = 0; ring < 4; ring++) {+ const phase = (t * 1.8 + ring * 0.4) % (Math.PI * 2);+ const r = 60 + ring * 55 + Math.sin(phase) * 20;+ ctx.strokeStyle = `rgba(78,140,255,${0.25 - ring * 0.05})`;+ ctx.lineWidth = 3 - ring * 0.5;+ ctx.beginPath();+ ctx.arc(W / 2, H / 2 - 30, r, 0, Math.PI * 2);+ ctx.stroke();+ }++ // Core dot+ const pulse = 0.8 + Math.sin(t * 5) * 0.2;+ ctx.fillStyle = '#4e8cff';+ circle(ctx, W / 2, H / 2 - 30, 22 * pulse);+ ctx.fill();++ ctx.fillStyle = '#ffffff';+ ctx.font = 'bold 48px -apple-system,system-ui,sans-serif';+ ctx.fillText('NOVA → ORACLE', W / 2, H / 2 + 80);++ ctx.fillStyle = 'rgba(34,209,122,0.9)';+ ctx.font = '34px -apple-system,system-ui,monospace';+ ctx.fillText('0.001 SOL · Solana mainnet', W / 2, H / 2 + 130);++ // Moving dots along transfer path+ for (let d = 0; d < 6; d++) {+ const px = ((t * 0.6 + d * 0.16) % 1);+ const dx = -W * 0.3 + px * W * 0.6;+ ctx.fillStyle = `rgba(78,140,255,${1 - Math.abs(px - 0.5) * 1.5})`;+ circle(ctx, W / 2 + dx, H / 2 - 30, 5);+ ctx.fill();+ }++ ctx.restore();+}++function drawContent(ctx, W, H, briefing, t) {+ if (!briefing) return;+ ctx.save();++ // Scanlines+ for (let y = 0; y < H; y += 3) {+ ctx.fillStyle = `rgba(34,209,122,${0.018})`;+ ctx.fillRect(0, y, W, 1);+ }++ // Header bar+ const hg = ctx.createLinearGradient(0, 0, W, 0);+ hg.addColorStop(0, 'rgba(34,209,122,0.18)');+ hg.addColorStop(1, 'rgba(34,209,122,0.04)');+ ctx.fillStyle = hg;+ ctx.fillRect(0, 0, W, 100);++ ctx.fillStyle = '#22d17a';+ ctx.font = 'bold 30px -apple-system,system-ui,sans-serif';+ ctx.textAlign = 'left';+ ctx.fillText('ORACLE · LIVE MARKET BRIEFING', 50, 38);++ ctx.fillStyle = 'rgba(255,255,255,0.4)';+ ctx.font = '22px -apple-system,system-ui,sans-serif';+ const ts = briefing.fetchedAt ? new Date(briefing.fetchedAt).toLocaleTimeString() : '';+ ctx.textAlign = 'right';+ ctx.fillText(`fetched ${ts}`, W - 50, 38);++ // Paid badge+ ctx.fillStyle = 'rgba(34,209,122,0.2)';+ roundRect(ctx, W - 230, 54, 180, 36, 10);+ ctx.fill();+ ctx.fillStyle = '#22d17a';+ ctx.font = 'bold 22px -apple-system,system-ui,sans-serif';+ ctx.textAlign = 'center';+ ctx.fillText('✓ PAID · 0.001 SOL', W - 140, 78);++ // Headline+ ctx.textAlign = 'left';+ ctx.fillStyle = '#ffffff';+ ctx.font = 'bold 36px -apple-system,system-ui,sans-serif';+ wrapText(ctx, briefing.headline || '', 50, 150, W - 100, 46);++ // Divider+ ctx.strokeStyle = 'rgba(34,209,122,0.25)';+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(50, 220);+ ctx.lineTo(W - 50, 220);+ ctx.stroke();++ // Token rows+ const pools = briefing.pools || [];+ const colW = (W - 120) / Math.min(pools.length, 5);+ pools.slice(0, 5).forEach((p, i) => {+ const x = 60 + i * colW;+ const y = 255;++ // Card bg+ ctx.fillStyle = p.up ? 'rgba(34,209,122,0.08)' : 'rgba(255,99,99,0.08)';+ roundRect(ctx, x - 4, y - 10, colW - 20, 200, 12);+ ctx.fill();++ // Name+ ctx.fillStyle = 'rgba(255,255,255,0.6)';+ ctx.font = '20px -apple-system,system-ui,sans-serif';+ ctx.textAlign = 'left';+ const nameParts = (p.name || '').split('/');+ ctx.fillText(nameParts[0] || p.name, x, y + 18);+ if (nameParts[1]) {+ ctx.fillStyle = 'rgba(255,255,255,0.3)';+ ctx.fillText('/' + nameParts[1], x + ctx.measureText(nameParts[0]).width + 2, y + 18);+ }++ // Price+ ctx.fillStyle = '#ffffff';+ ctx.font = `bold 28px -apple-system,system-ui,monospace`;+ ctx.fillText('$' + p.price, x, y + 66);++ // Change pill+ const changeColor = p.up ? '#22d17a' : '#ff6363';+ ctx.fillStyle = p.up ? 'rgba(34,209,122,0.2)' : 'rgba(255,99,99,0.2)';+ roundRect(ctx, x, y + 82, 100, 34, 8);+ ctx.fill();+ ctx.fillStyle = changeColor;+ ctx.font = 'bold 22px -apple-system,system-ui,sans-serif';+ ctx.fillText(p.change24h, x + 8, y + 106);++ // Vol+ ctx.fillStyle = 'rgba(255,255,255,0.35)';+ ctx.font = '20px -apple-system,system-ui,sans-serif';+ ctx.fillText('Vol ' + p.vol24h, x, y + 148);+ });++ // Flicker vignette+ ctx.fillStyle = `rgba(0,0,0,${0.08 + Math.sin(t * 0.7) * 0.03})`;+ ctx.fillRect(0, 0, W, H);++ ctx.restore();+}++// ─── Payment beam (animated arc between agents) ─────────────────────────────++function createBeam(scene) {+ const points = [];+ const N = 40;+ for (let i = 0; i <= N; i++) {+ const s = i / N;+ const x = NOVA_X + (ORACLE_X - NOVA_X) * s;+ const y = 1.6 + Math.sin(s * Math.PI) * 1.2;+ const z = 0;+ points.push(new THREE.Vector3(x, y, z));+ }+ const curve = new THREE.CatmullRomCurve3(points);+ const geo = new THREE.TubeGeometry(curve, 60, 0.015, 6, false);+ const mat = new THREE.MeshBasicMaterial({+ color: 0x4e8cff,+ transparent: true,+ opacity: 0,+ });+ const mesh = new THREE.Mesh(geo, mat);+ scene.add(mesh);++ // Travelling orbs along beam+ const orbMat = new THREE.MeshBasicMaterial({ color: 0x4e8cff, transparent: true, opacity: 0 });+ const orbs = Array.from({ length: 5 }, (_, i) => {+ const o = new THREE.Mesh(new THREE.SphereGeometry(0.04, 6, 6), orbMat.clone());+ scene.add(o);+ return { mesh: o, phase: i / 5 };+ });++ let active = false;+ let startT = 0;+ let currentT = 0;++ function tick(t) {+ currentT = t;+ if (!active) return;+ const elapsed = (t - startT) % 2;+ const fade = elapsed < 0.3 ? elapsed / 0.3 : elapsed > 1.7 ? (2 - elapsed) / 0.3 : 1;+ mat.opacity = 0.5 * fade;+ orbs.forEach(({ mesh: om, phase }) => {+ const s = (phase + elapsed * 0.6) % 1;+ const p = curve.getPoint(s);+ om.position.copy(p);+ om.material.opacity = fade * (1 - Math.abs(s - 0.5) * 1.4);+ });+ }++ return {+ tick,+ activate() { active = true; startT = currentT; mat.opacity = 0.5; orbs.forEach(o => o.mesh.material.opacity = 0.7); },+ deactivate() { active = false; mat.opacity = 0; orbs.forEach(o => o.mesh.material.opacity = 0); },+ };+}++// ─── Canvas utilities ───────────────────────────────────────────────────────++function roundRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.lineTo(x + w - r, y);+ ctx.quadraticCurveTo(x + w, y, x + w, y + r);+ ctx.lineTo(x + w, y + h - r);+ ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);+ ctx.lineTo(x + r, y + h);+ ctx.quadraticCurveTo(x, y + h, x, y + h - r);+ ctx.lineTo(x, y + r);+ ctx.quadraticCurveTo(x, y, x + r, y);+ ctx.closePath();+}++function circle(ctx, x, y, r) {+ ctx.beginPath();+ ctx.arc(x, y, r, 0, Math.PI * 2);+}++function wrapText(ctx, text, x, y, maxW, lineH) {+ const words = text.split(' ');+ let line = '';+ for (const word of words) {+ const test = line ? line + ' ' + word : word;+ if (ctx.measureText(test).width > maxW && line) {+ ctx.fillText(line, x, y);+ line = word;+ y += lineH;+ } else {+ line = test;+ }+ }+ ctx.fillText(line, x, y);+}diff --git a/src/live-economy.js b/src/live-economy.jsnew file mode 100644index 000000000..1143d4374--- /dev/null+++ b/src/live-economy.js@@ -0,0 +1,395 @@+/**+ * /live — Agent Economy World+ *+ * A Three.js scene where two AI agents live side-by-side in a dark virtual+ * world. Agent B (Trader) pays Agent A (Oracle) for live Solana market data.+ * The purchased data appears on the central TV screen. Real on-chain txs.+ */+import * as THREE from 'three';++// ── Scene constants ───────────────────────────────────────────────────────+const W = () => window.innerWidth;+const H = () => window.innerHeight;+const FOV = 60;++// 3D positions (x, y, z). Camera looks slightly down at the stage.+const CAM_POS = new THREE.Vector3(0, 6, 18);+const CAM_TARGET = new THREE.Vector3(0, 1.5, 0);+const AGENT_A_POS = new THREE.Vector3(-7, 0, 0); // Oracle (purple, right in world space)+const AGENT_B_POS = new THREE.Vector3( 7, 0, 0); // Trader (blue, left)+const TV_POS = new THREE.Vector3( 0, 4.2, -6);++// ── Renderer ──────────────────────────────────────────────────────────────+const canvas = document.getElementById('world-canvas');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });+renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));+renderer.setSize(W(), H());+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.1;++const scene = new THREE.Scene();+scene.background = new THREE.Color(0x04050b);+scene.fog = new THREE.FogExp2(0x04050b, 0.045);++const camera = new THREE.PerspectiveCamera(FOV, W() / H(), 0.1, 200);+camera.position.copy(CAM_POS);+camera.lookAt(CAM_TARGET);++window.addEventListener('resize', () => {+ camera.aspect = W() / H();+ camera.updateProjectionMatrix();+ renderer.setSize(W(), H());+ updateOverlayPositions();+});++// ── Lights ────────────────────────────────────────────────────────────────+scene.add(new THREE.AmbientLight(0x0a0c18, 1.0));++const sunLight = new THREE.DirectionalLight(0xc0cfff, 0.6);+sunLight.position.set(0, 20, 10);+scene.add(sunLight);++// Oracle point light (purple)+const oracleLight = new THREE.PointLight(0xa855f7, 3.5, 18);+oracleLight.position.set(AGENT_A_POS.x, 4, AGENT_A_POS.z + 2);+scene.add(oracleLight);++// Trader point light (blue)+const traderLight = new THREE.PointLight(0x4e8cff, 3.5, 18);+traderLight.position.set(AGENT_B_POS.x, 4, AGENT_B_POS.z + 2);+scene.add(traderLight);++// TV backlight+const tvLight = new THREE.PointLight(0x78a9ff, 2.0, 14);+tvLight.position.set(TV_POS.x, TV_POS.y, TV_POS.z + 3);+scene.add(tvLight);++// ── Floor grid ────────────────────────────────────────────────────────────+const gridHelper = new THREE.GridHelper(60, 40, 0x0f1428, 0x0f1428);+scene.add(gridHelper);++const floorGeo = new THREE.PlaneGeometry(60, 60);+const floorMat = new THREE.MeshStandardMaterial({+ color: 0x060810,+ roughness: 0.95,+ metalness: 0.05,+});+const floor = new THREE.Mesh(floorGeo, floorMat);+floor.rotation.x = -Math.PI / 2;+floor.position.y = -0.01;+scene.add(floor);++// ── Agent platforms ───────────────────────────────────────────────────────+function makePedestal(position, color) {+ const group = new THREE.Group();++ // Ring glow (torus)+ const ring = new THREE.Mesh(+ new THREE.TorusGeometry(1.6, 0.06, 8, 48),+ new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 2.0 })+ );+ ring.rotation.x = Math.PI / 2;+ ring.position.y = 0.05;+ group.add(ring);++ // Disc platform+ const disc = new THREE.Mesh(+ new THREE.CylinderGeometry(1.55, 1.55, 0.06, 32),+ new THREE.MeshStandardMaterial({ color: 0x0c0e1a, roughness: 0.8, metalness: 0.2 })+ );+ disc.position.y = 0.03;+ group.add(disc);++ group.position.copy(position);+ scene.add(group);+ return { group, ring };+}++const pedestalA = makePedestal(AGENT_A_POS, 0xa855f7); // Oracle purple+const pedestalB = makePedestal(AGENT_B_POS, 0x4e8cff); // Trader blue++// ── TV Screen ─────────────────────────────────────────────────────────────+const TV_W = 640;+const TV_H = 360;+const tvCanvas = document.createElement('canvas');+tvCanvas.width = TV_W;+tvCanvas.height = TV_H;+const tvCtx = tvCanvas.getContext('2d');++const tvTex = new THREE.CanvasTexture(tvCanvas);+const tvGeo = new THREE.PlaneGeometry(8, 4.5);+const tvMat = new THREE.MeshBasicMaterial({ map: tvTex, side: THREE.FrontSide });+const tvMesh = new THREE.Mesh(tvGeo, tvMat);+tvMesh.position.copy(TV_POS);+scene.add(tvMesh);++// TV bezel frame+const bezelMat = new THREE.MeshStandardMaterial({ color: 0x141820, roughness: 0.9, metalness: 0.4 });+const bezelGeo = new THREE.BoxGeometry(8.4, 4.9, 0.12);+const bezel = new THREE.Mesh(bezelGeo, bezelMat);+bezel.position.set(TV_POS.x, TV_POS.y, TV_POS.z - 0.07);+scene.add(bezel);++// TV stand+const standMat = new THREE.MeshStandardMaterial({ color: 0x0e1018, roughness: 0.9, metalness: 0.5 });+const standGeo = new THREE.BoxGeometry(0.3, TV_POS.y - 0.05, 0.3);+const stand = new THREE.Mesh(standGeo, standMat);+stand.position.set(TV_POS.x, TV_POS.y / 2, TV_POS.z - 0.07);+scene.add(stand);++// ── TV rendering ──────────────────────────────────────────────────────────+function drawTvIdle() {+ tvCtx.fillStyle = '#060810';+ tvCtx.fillRect(0, 0, TV_W, TV_H);++ // Grid lines+ tvCtx.strokeStyle = 'rgba(78,140,255,0.07)';+ tvCtx.lineWidth = 1;+ for (let x = 0; x < TV_W; x += 32) {+ tvCtx.beginPath(); tvCtx.moveTo(x, 0); tvCtx.lineTo(x, TV_H); tvCtx.stroke();+ }+ for (let y = 0; y < TV_H; y += 32) {+ tvCtx.beginPath(); tvCtx.moveTo(0, y); tvCtx.lineTo(TV_W, y); tvCtx.stroke();+ }++ // Idle text+ tvCtx.fillStyle = 'rgba(107,110,138,0.6)';+ tvCtx.font = 'bold 15px -apple-system, system-ui, sans-serif';+ tvCtx.textAlign = 'center';+ tvCtx.fillText('AGENT ORACLE — MARKET INTELLIGENCE', TV_W / 2, TV_H / 2 - 12);+ tvCtx.font = '12px -apple-system, system-ui, sans-serif';+ tvCtx.fillText('Awaiting trade request…', TV_W / 2, TV_H / 2 + 14);+ tvTex.needsUpdate = true;+}++export function drawTvData(markets) {+ tvCtx.fillStyle = '#060810';+ tvCtx.fillRect(0, 0, TV_W, TV_H);++ // Header bar+ tvCtx.fillStyle = 'rgba(168,85,247,0.15)';+ tvCtx.fillRect(0, 0, TV_W, 44);+ tvCtx.fillStyle = '#a855f7';+ tvCtx.font = 'bold 13px -apple-system, system-ui, sans-serif';+ tvCtx.textAlign = 'left';+ tvCtx.fillText('● ORACLE INTEL FEED · SOLANA LIVE', 16, 28);+ tvCtx.fillStyle = 'rgba(107,110,138,0.8)';+ tvCtx.font = '11px -apple-system, system-ui, sans-serif';+ tvCtx.textAlign = 'right';+ tvCtx.fillText(new Date().toUTCString().replace(/:\d\d GMT/, ' UTC'), TV_W - 16, 28);++ if (!markets?.length) {+ tvCtx.fillStyle = '#6b6e8a';+ tvCtx.textAlign = 'center';+ tvCtx.font = '13px -apple-system, system-ui, sans-serif';+ tvCtx.fillText('No data', TV_W / 2, TV_H / 2);+ tvTex.needsUpdate = true;+ return;+ }++ const rowH = (TV_H - 60) / Math.min(markets.length, 6);+ markets.slice(0, 6).forEach((m, i) => {+ const y = 54 + i * rowH;+ const isEven = i % 2 === 0;++ tvCtx.fillStyle = isEven ? 'rgba(255,255,255,0.025)' : 'transparent';+ tvCtx.fillRect(0, y, TV_W, rowH);++ const change = m.change24h;+ const upDown = change == null ? '—' : change >= 0 ? `+${change.toFixed(2)}%` : `${change.toFixed(2)}%`;+ const color = change == null ? '#6b6e8a' : change >= 0 ? '#42be65' : '#fa4d56';++ // Name+ tvCtx.fillStyle = '#e8eaf4';+ tvCtx.textAlign = 'left';+ tvCtx.font = `bold 12px -apple-system, system-ui, sans-serif`;+ const name = m.name || '—';+ tvCtx.fillText(name.length > 20 ? name.slice(0, 18) + '…' : name, 16, y + rowH * 0.62);++ // Price+ tvCtx.fillStyle = '#e8eaf4';+ tvCtx.textAlign = 'center';+ tvCtx.font = '12px -apple-system, system-ui, sans-serif';+ const price = m.priceUsd != null ? `$${m.priceUsd < 0.01 ? m.priceUsd.toExponential(3) : m.priceUsd.toFixed(4)}` : '—';+ tvCtx.fillText(price, TV_W / 2, y + rowH * 0.62);++ // Change+ tvCtx.fillStyle = color;+ tvCtx.textAlign = 'right';+ tvCtx.font = `bold 12px -apple-system, system-ui, sans-serif`;+ tvCtx.fillText(upDown, TV_W - 16, y + rowH * 0.62);+ });++ tvTex.needsUpdate = true;+}++drawTvIdle();++// ── Payment beam particles ────────────────────────────────────────────────+const BEAM_COUNT = 80;+const beamPositions = new Float32Array(BEAM_COUNT * 3);+const beamGeo = new THREE.BufferGeometry();+beamGeo.setAttribute('position', new THREE.BufferAttribute(beamPositions, 3));+const beamMat = new THREE.PointsMaterial({+ color: 0x4e8cff,+ size: 0.18,+ transparent: true,+ opacity: 0,+ blending: THREE.AdditiveBlending,+ depthWrite: false,+});+const beamPoints = new THREE.Points(beamGeo, beamMat);+scene.add(beamPoints);++let beamActive = false;+let beamProgress = 0; // 0 → 1+let beamDir = 1; // 1 = B→A, -1 = A→B++export function fireBeam(fromBtoA = true) {+ beamActive = true;+ beamProgress = 0;+ beamDir = fromBtoA ? 1 : -1;+ beamMat.opacity = 0.9;+}++function updateBeam(dt) {+ if (!beamActive) return;+ beamProgress = Math.min(1, beamProgress + dt * 0.7);++ const src = beamDir > 0 ? AGENT_B_POS : AGENT_A_POS;+ const dst = beamDir > 0 ? AGENT_A_POS : AGENT_B_POS;+ const pos = beamGeo.attributes.position;++ for (let i = 0; i < BEAM_COUNT; i++) {+ const t = (i / BEAM_COUNT + beamProgress) % 1;+ const jitter = 0.25;+ pos.setX(i, THREE.MathUtils.lerp(src.x, dst.x, t) + (Math.random() - .5) * jitter);+ pos.setY(i, THREE.MathUtils.lerp(src.y + 1.5, dst.y + 1.5, t) + (Math.random() - .5) * jitter * 0.5);+ pos.setZ(i, THREE.MathUtils.lerp(src.z, dst.z, t) + (Math.random() - .5) * jitter);+ }+ pos.needsUpdate = true;++ if (beamProgress >= 1) {+ beamActive = false;+ beamMat.opacity = 0;+ }+}++// ── Ambient floating particles ────────────────────────────────────────────+const FLOAT_N = 200;+const floatBuf = new Float32Array(FLOAT_N * 3);+for (let i = 0; i < FLOAT_N; i++) {+ floatBuf[i * 3 + 0] = (Math.random() - .5) * 30;+ floatBuf[i * 3 + 1] = Math.random() * 12;+ floatBuf[i * 3 + 2] = (Math.random() - .5) * 20;+}+const floatGeo = new THREE.BufferGeometry();+floatGeo.setAttribute('position', new THREE.BufferAttribute(floatBuf, 3));+const floatPoints = new THREE.Points(floatGeo, new THREE.PointsMaterial({+ color: 0x304060,+ size: 0.08,+ transparent: true,+ opacity: 0.5,+ blending: THREE.AdditiveBlending,+ depthWrite: false,+}));+scene.add(floatPoints);++// ── CSS overlay: project 3D positions → screen positions ─────────────────+const v3 = new THREE.Vector3();++function toScreen(worldPos) {+ v3.copy(worldPos);+ v3.project(camera);+ return {+ x: (v3.x * 0.5 + 0.5) * W(),+ y: (-v3.y * 0.5 + 0.5) * H(),+ };+}++export function updateOverlayPositions() {+ const aScreen = toScreen(AGENT_A_POS.clone().add(new THREE.Vector3(0, 4, 2)));+ const bScreen = toScreen(AGENT_B_POS.clone().add(new THREE.Vector3(0, 4, 2)));++ const iframeA = document.getElementById('iframe-oracle');+ const iframeB = document.getElementById('iframe-trader');+ const W_HALF = Math.min(W() * 0.24, 300);+ const H_FULL = Math.min(H() * 0.65, 500);++ if (iframeA) {+ iframeA.style.left = `${aScreen.x - W_HALF / 2}px`;+ iframeA.style.top = `${aScreen.y - H_FULL}px`;+ iframeA.style.width = `${W_HALF}px`;+ iframeA.style.height = `${H_FULL}px`;+ }+ if (iframeB) {+ iframeB.style.left = `${bScreen.x - W_HALF / 2}px`;+ iframeB.style.top = `${bScreen.y - H_FULL}px`;+ iframeB.style.width = `${W_HALF}px`;+ iframeB.style.height = `${H_FULL}px`;+ }+}++// ── Flash glow ring ───────────────────────────────────────────────────────+let flashRing = null;+let flashTimer = 0;+let flashTarget = null;++export function flashAgent(which) {+ flashTarget = which === 'A' ? AGENT_A_POS : AGENT_B_POS;+ const color = which === 'A' ? 0xa855f7 : 0x4e8cff;+ if (flashRing) scene.remove(flashRing);+ flashRing = new THREE.Mesh(+ new THREE.RingGeometry(1.7, 2.0, 32),+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.9, side: THREE.DoubleSide, depthWrite: false })+ );+ flashRing.rotation.x = -Math.PI / 2;+ flashRing.position.set(flashTarget.x, 0.06, flashTarget.z);+ scene.add(flashRing);+ flashTimer = 1.0;+}++// ── Render loop ───────────────────────────────────────────────────────────+let lastTime = performance.now();++(function loop() {+ requestAnimationFrame(loop);+ const now = performance.now();+ const dt = Math.min((now - lastTime) / 1000, 0.05);+ lastTime = now;++ const t = now * 0.001;++ // Pedestal ring pulse+ pedestalA.ring.material.emissiveIntensity = 1.5 + Math.sin(t * 1.8) * 0.5;+ pedestalB.ring.material.emissiveIntensity = 1.5 + Math.sin(t * 1.8 + 1.2) * 0.5;++ // Light pulse+ oracleLight.intensity = 2.5 + Math.sin(t * 2.1) * 0.8;+ traderLight.intensity = 2.5 + Math.sin(t * 2.1 + 1.0) * 0.8;+ tvLight.intensity = 1.5 + Math.sin(t * 1.3) * 0.4;++ // Ambient float drift+ const fp = floatGeo.attributes.position;+ for (let i = 0; i < FLOAT_N; i++) {+ fp.setY(i, fp.getY(i) + Math.sin(t + i * 0.37) * 0.003);+ }+ fp.needsUpdate = true;++ // Payment beam+ updateBeam(dt);++ // Flash ring fade+ if (flashTimer > 0 && flashRing) {+ flashTimer -= dt * 1.4;+ flashRing.material.opacity = Math.max(0, flashTimer);+ const s = 1 + (1 - flashTimer) * 0.6;+ flashRing.scale.set(s, s, s);+ if (flashTimer <= 0) { scene.remove(flashRing); flashRing = null; }+ }++ renderer.render(scene, camera);+})();++// ── Init overlay positions ────────────────────────────────────────────────+updateOverlayPositions();diff --git a/vercel.json b/vercel.jsonindex baf541e26..207d09681 100644--- a/vercel.json+++ b/vercel.json@@ -57,6 +57,22 @@},"continue": true},+ {+ "src": "/agent-exchange",+ "dest": "/agent-exchange.html"+ },+ {+ "src": "/agent-exchange/",+ "dest": "/agent-exchange.html"+ },+ {+ "src": "/agent-trade",+ "dest": "/agent-trade.html"+ },+ {+ "src": "/agent-trade/",+ "dest": "/agent-trade.html"+ },{"src": "/aws-marketplace/welcome","dest": "/aws-marketplace/welcome.html"@@ -73,6 +89,38 @@"src": "/aws/","dest": "/aws/index.html"},+ {+ "src": "/agent-economy",+ "dest": "/agent-economy.html"+ },+ {+ "src": "/agent-economy/",+ "dest": "/agent-economy.html"+ },+ {+ "src": "/demo",+ "dest": "/demo-economy.html"+ },+ {+ "src": "/demo/",+ "dest": "/demo-economy.html"+ },+ {+ "src": "/live",+ "dest": "/live.html"+ },+ {+ "src": "/live/",+ "dest": "/live.html"+ },+ {+ "src": "/avatar-wallet-chat",+ "dest": "/avatar-wallet-chat.html"+ },+ {+ "src": "/avatar-wallet-chat/",+ "dest": "/avatar-wallet-chat.html"+ },{"src": "/ibm/galaxy","dest": "/ibm/galaxy.html"@@ -1056,12 +1104,16 @@{"src": "/marketplace/agents/([^/]+)","status": 301,- "headers": { "Location": "/agent-next?id=$1" }+ "headers": {+ "Location": "/agent-next?id=$1"+ }},{"src": "/marketplace/avatars/([^/]+)","status": 301,- "headers": { "Location": "/agent-next?id=$1" }+ "headers": {+ "Location": "/agent-next?id=$1"+ }},{"src": "/api/agents/me",@@ -1607,7 +1659,9 @@{"src": "/avatars/([^/]+)","status": 301,- "headers": { "Location": "/agent-next?id=$1" }+ "headers": {+ "Location": "/agent-next?id=$1"+ }},{"src": "/api/characters",@@ -1911,6 +1965,14 @@"src": "/reputation/(.*)","dest": "/reputation/$1"},+ {+ "src": "/deal",+ "dest": "/deal.html"+ },+ {+ "src": "/deal/",+ "dest": "/deal.html"+ },{"src": "/pay","dest": "/pay/index.html"diff --git a/vite.config.js b/vite.config.jsindex 3587a0e02..71239d617 100644--- a/vite.config.js+++ b/vite.config.js@@ -251,6 +251,10 @@ const appConfig = {'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),'avatar-wallet-chat': resolve(__dirname, 'pages/avatar-wallet-chat.html'),+ 'agent-exchange': resolve(__dirname, 'pages/agent-exchange.html'),+ 'demo-economy': resolve(__dirname, 'pages/demo-economy.html'),+ 'live': resolve(__dirname, 'pages/live.html'),+ 'agent-economy': resolve(__dirname, 'pages/agent-economy.html'),'overlay-control': resolve(__dirname, 'pages/overlay-control.html'),'mocap-studio': resolve(__dirname, 'pages/mocap-studio.html'),handle: resolve(__dirname, 'pages/handle.html'),@@ -351,6 +355,7 @@ const appConfig = {'agents-auto-rig': resolve(__dirname, 'public/demos/agents/auto-rig.html'),'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),'aws': resolve(__dirname, 'pages/aws/index.html'),+ 'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),'ibm': resolve(__dirname, 'pages/ibm/index.html'),'ibm-galaxy': resolve(__dirname, 'pages/ibm/galaxy.html'),'ibm-trust-layer': resolve(__dirname, 'pages/ibm/trust-layer.html'),@@ -549,8 +554,14 @@ const appConfig = {'/game/': resolve(root, 'pages/game.html'),'/walk-embed': resolve(root, 'pages/walk-embed.html'),'/walk-embed/': resolve(root, 'pages/walk-embed.html'),+ '/demo': resolve(root, 'pages/demo-economy.html'),+ '/demo/': resolve(root, 'pages/demo-economy.html'),+ '/live': resolve(root, 'pages/live.html'),+ '/live/': resolve(root, 'pages/live.html'),'/avatar-wallet-chat': resolve(root, 'pages/avatar-wallet-chat.html'),'/avatar-wallet-chat/': resolve(root, 'pages/avatar-wallet-chat.html'),+ '/agent-exchange': resolve(root, 'pages/agent-exchange.html'),+ '/agent-exchange/': resolve(root, 'pages/agent-exchange.html'),'/pose': resolve(root, 'pages/pose.html'),'/pose/': resolve(root, 'pages/pose.html'),'/club': resolve(root, 'pages/club.html'),