Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Real-time SSE for activity feed + Oracle conviction on launch cards

nirholasc49d339d2e22
diff --git a/api/oracle/action-stream.js b/api/oracle/action-stream.js
new file mode 100644
index 000000000..07d7f0f93
--- /dev/null
+++ b/api/oracle/action-stream.js
@@ -0,0 +1,162 @@
+/**
+ * Oracle — live agent action stream (SSE).
+ *
+ * GET /api/oracle/action-stream?network=mainnet&mode=live|simulate
+ *
+ * Polls oracle_watch_actions for rows inserted since a cursor (~3s) and fans
+ * new entries + outcome updates to every connected client. This powers the
+ * /activity trading-floor page with sub-5-second latency instead of 30s polling.
+ *
+ * Events:
+ * hello — sent on connect with network + ts
+ * action — a new oracle_watch_actions row (entry or outcome update)
+ * settle — an existing action whose outcome just changed (win/loss/flat)
+ * ping — keepalive every 15s
+ * bye — server rotating the connection after MAX_DURATION_MS
+ *
+ * The client reconnects automatically via EventSource's built-in retry.
+ * It passes `?since=<iso>` on reconnect so no events are missed.
+ */
+
+import { cors, method, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const MODES = new Set(['live', 'simulate']);
+const MAX_DURATION_MS = 90_000;
+const PING_MS = 15_000;
+const POLL_MS = 3_000;
+
+function shapeAction(r) {
+ return {
+ id: r.id,
+ agent_id: r.agent_id,
+ agent_name: r.agent_name || 'Agent',
+ agent_image: r.agent_image || r.agent_avatar || null,
+ network: r.network,
+ mint: r.mint,
+ symbol: r.symbol,
+ conviction: r.conviction != null ? Number(r.conviction) : null,
+ tier: r.tier,
+ mode: r.mode,
+ size_sol: r.size_sol != null ? Number(r.size_sol) : null,
+ status: r.status,
+ outcome: r.outcome || 'open',
+ peak_multiple: r.peak_multiple != null ? Number(r.peak_multiple) : null,
+ realized_pnl_sol: r.realized_pnl_sol != null ? Number(r.realized_pnl_sol) : null,
+ acted_at: r.acted_at,
+ settled_at: r.settled_at || null,
+ pump_url: `https://pump.fun/coin/${r.mint}`,
+ agent_url: `/agents/${r.agent_id}`,
+ };
+}
+
+async function pollActions(network, mode, cursor, limit = 30) {
+ const rows = await sql`
+ select
+ a.id, a.agent_id, a.network, a.mint, a.symbol,
+ a.conviction, a.tier, a.mode, a.size_sol, a.status,
+ a.outcome, a.peak_multiple, a.realized_pnl_sol,
+ a.acted_at, a.settled_at,
+ ai.name as agent_name,
+ ai.avatar_url as agent_avatar,
+ ai.profile_image_url as agent_image
+ from oracle_watch_actions a
+ left join agent_identities ai on ai.id = a.agent_id and ai.deleted_at is null
+ where a.network = ${network}
+ and a.acted_at > ${cursor}::timestamptz
+ and ${mode ? sql`a.mode = ${mode}` : sql`true`}
+ order by a.acted_at asc
+ limit ${limit}
+ `.catch(() => []);
+ return rows;
+}
+
+// Poll for settlements: actions updated since cursor whose outcome is now resolved.
+async function pollSettlements(network, cursor, limit = 20) {
+ const rows = await sql`
+ select
+ a.id, a.agent_id, a.network, a.mint, a.symbol,
+ a.conviction, a.tier, a.mode, a.size_sol, a.status,
+ a.outcome, a.peak_multiple, a.realized_pnl_sol,
+ a.acted_at, a.settled_at,
+ ai.name as agent_name,
+ ai.avatar_url as agent_avatar,
+ ai.profile_image_url as agent_image
+ from oracle_watch_actions a
+ left join agent_identities ai on ai.id = a.agent_id and ai.deleted_at is null
+ where a.network = ${network}
+ and a.settled_at > ${cursor}::timestamptz
+ and a.outcome in ('win', 'loss', 'flat')
+ order by a.settled_at asc
+ limit ${limit}
+ `.catch(() => []);
+ return rows;
+}
+
+export default async function handleActionStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ const mode = MODES.has(url.searchParams.get('mode')) ? url.searchParams.get('mode') : null;
+ // Client passes `since` on reconnect to avoid gaps.
+ const sinceParam = url.searchParams.get('since');
+ let cursor = sinceParam ? sinceParam : new Date(Date.now() - 10_000).toISOString();
+ let settleCursor = cursor;
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active || res.writableEnded) return;
+ try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { /* client gone */ }
+ };
+
+ send('hello', { ts: Date.now(), network, mode: mode || 'all' });
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const [actions, settles] = await Promise.all([
+ pollActions(network, mode, cursor),
+ pollSettlements(network, settleCursor),
+ ]);
+ for (const r of actions) {
+ send('action', shapeAction(r));
+ }
+ if (actions.length) cursor = actions[actions.length - 1].acted_at;
+ for (const r of settles) {
+ send('settle', shapeAction(r));
+ }
+ if (settles.length) settleCursor = settles[settles.length - 1].settled_at;
+ } catch { /* transient — next tick */ }
+ };
+
+ const pollTimer = setInterval(poll, POLL_MS);
+ const pingTimer = setInterval(() => send('ping', { ts: Date.now() }), PING_MS);
+ const stopTimer = setTimeout(() => { send('bye', { reason: 'rotate', since: cursor }); cleanup(); }, MAX_DURATION_MS);
+
+ function cleanup() {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(pingTimer);
+ clearTimeout(stopTimer);
+ try { res.end(); } catch { /* already closed */ }
+ }
+
+ req.on('close', cleanup);
+ req.on('error', cleanup);
+}
diff --git a/pages/activity.html b/pages/activity.html
index 9b0cc31b1..24b44c36a 100644
--- a/pages/activity.html
+++ b/pages/activity.html
@@ -233,8 +233,9 @@
<script src="/brand.js" defer></script>
<script type="module">
- const API = '/api/oracle/activity';
- const REFRESH_MS = 30_000;
+ const API = '/api/oracle/activity';
+ const STREAM_API = '/api/oracle/action-stream';
+ const REFRESH_MS = 60_000;
const TIER_EMOJI = { prime: '🟣', strong: '🔵', lean: '🟡', watch: '⚪', avoid: '🔴' };
const sol = (n) => n == null ? '—' : (Math.abs(Number(n)) >= 1 ? Number(n).toFixed(2) : Number(n).toFixed(3)) + ' ◎';
@@ -270,7 +271,7 @@
const verb = outcome === 'win' ? 'closed ↑' : outcome === 'loss' ? 'closed ↓' : outcome === 'flat' ? 'closed' : 'entered';
const convScore = item.conviction != null ? ` · ${item.conviction}` : '';
- return `<div class="ac-row oc-${outcome}" data-agent="${esc(item.agent_id)}">
+ return `<div class="ac-row oc-${outcome}" data-id="${esc(item.id)}" data-agent="${esc(item.agent_id)}">
<span class="outcome-edge"></span>
<img class="ac-av" src="${esc(av)}" alt="" onerror="${imgErr}" loading="lazy" />
<div class="ac-body">
@@ -399,20 +400,90 @@
loadMoreBtn.addEventListener('click', () => { loadMoreBtn.disabled = true; load(false); });
- // ── boot + auto-refresh ──
- load(true);
+ // ── SSE — real-time updates ──────────────────────────────────────────
const note = document.getElementById('ac-refresh-note');
- let tick = REFRESH_MS / 1000;
- const countdown = setInterval(() => {
- tick--;
- note.textContent = `Refreshes in ${tick}s`;
- if (tick <= 0) {
- tick = REFRESH_MS / 1000;
- if (!state.cursor && !state.loading) load(true); // only refresh if on first page
- }
- }, 1000);
+ const seenIds = new Set();
+ let sseActive = false;
+ let sseLastCursor = null;
+
+ function startSse() {
+ const url = new URL('/api/oracle/action-stream', location.origin);
+ url.searchParams.set('network', 'mainnet');
+ if (state.mode) url.searchParams.set('mode', state.mode);
+ if (sseLastCursor) url.searchParams.set('since', sseLastCursor);
+
+ const es = new EventSource(url.toString());
+ sseActive = false;
+ es.addEventListener('hello', () => {
+ sseActive = true;
+ note.textContent = '⚡ Live';
+ });
+
+ es.addEventListener('action', (e) => {
+ const item = JSON.parse(e.data);
+ if (seenIds.has(item.id)) return;
+ // Only show if passes current filters
+ if (state.tier && item.tier !== state.tier) return;
+ if (state.mode && item.mode !== state.mode) return;
+ if (state.cursor) return; // user is paginated — don't disrupt
+ seenIds.add(item.id);
+ sseLastCursor = item.acted_at;
+ state.items.unshift(item);
+ const div = document.createElement('div');
+ div.innerHTML = renderRow(item);
+ const row = div.firstElementChild;
+ // Animate in from top
+ row.style.animationDelay = '0ms';
+ feed.prepend(row);
+ });
+
+ es.addEventListener('settle', (e) => {
+ const item = JSON.parse(e.data);
+ const existing = feed.querySelector(`[data-id="${CSS.escape(item.id)}"]`);
+ if (!existing) return;
+ // Replace the row in-place with updated outcome
+ const div = document.createElement('div');
+ div.innerHTML = renderRow(item);
+ const updated = div.firstElementChild;
+ existing.replaceWith(updated);
+ });
+
+ es.addEventListener('bye', (e) => {
+ const d = JSON.parse(e.data || '{}');
+ if (d.since) sseLastCursor = d.since;
+ es.close();
+ sseActive = false;
+ // Reconnect after 500ms
+ setTimeout(startSse, 500);
+ });
+
+ es.addEventListener('error', () => {
+ sseActive = false;
+ note.textContent = 'Reconnecting…';
+ es.close();
+ // Fallback to polling if SSE fails
+ setTimeout(() => { if (!sseActive) startSse(); }, 5000);
+ });
+
+ return es;
+ }
+
+ // ── boot ──
+ load(true).then(() => {
+ // Seed seen IDs from initial load
+ state.items.forEach((it) => seenIds.add(it.id));
+ // Start SSE
+ if (typeof EventSource !== 'undefined') startSse();
+ });
+
+ // Fallback polling (fires if SSE is down and we're on first page)
+ setInterval(() => {
+ if (!sseActive && !state.cursor && !state.loading) load(true);
+ if (!sseActive) note.textContent = 'Reconnecting…';
+ }, REFRESH_MS);
+
document.addEventListener('visibilitychange', () => {
- if (!document.hidden && !state.cursor && !state.loading) load(true);
+ if (!document.hidden && !sseActive && !state.cursor && !state.loading) load(true);
});
</script>
</body>
diff --git a/src/launches.css b/src/launches.css
index eafb1f5cd..b0c9ac8e2 100644
--- a/src/launches.css
+++ b/src/launches.css
@@ -952,6 +952,31 @@ body {
margin-top: var(--space-lg);
}
+/* ── Oracle conviction badge on launch cards ─────────────────────────────── */
+.lx-oracle-badge {
+ position: absolute;
+ bottom: var(--space-sm);
+ right: var(--space-sm);
+ z-index: 2;
+ pointer-events: none;
+}
+.lx-ob-link {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ background: rgba(0, 0, 0, 0.7);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 6px;
+ padding: 3px 7px;
+ text-decoration: none;
+ backdrop-filter: blur(4px);
+ pointer-events: all;
+ transition: background 0.12s, border-color 0.12s;
+}
+.lx-ob-link:hover { background: rgba(0, 0, 0, 0.85); border-color: rgba(255, 255, 255, 0.22); }
+.lx-ob-score { font: 700 12px/1 var(--font-mono); font-variant-numeric: tabular-nums; }
+.lx-ob-tier { font: 600 8.5px/1 var(--font-mono); text-transform: uppercase; letter-spacing: .06em; opacity: .85; }
+
/* ── Responsive ───────────────────────────────────────────────────────────── */
@media (max-width: 640px) {
@@ -980,3 +1005,44 @@ body {
margin-left: 0;
}
}
+
+/* ── Oracle conviction badge on feed cards ──────────────────────────────── */
+
+.lx-oracle-badge {
+ position: absolute;
+ top: var(--space-sm, 10px);
+ right: var(--space-sm, 10px);
+ z-index: 3;
+ pointer-events: none;
+}
+.lx-ob-link {
+ pointer-events: all;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ background: rgba(0,0,0,0.52);
+ border: 1px solid rgba(255,255,255,0.09);
+ border-radius: 7px;
+ padding: 5px 8px 4px;
+ text-decoration: none;
+ line-height: 1;
+ backdrop-filter: blur(5px);
+ transition: background 0.13s, border-color 0.13s, transform 0.13s;
+}
+.lx-ob-link:hover { background: rgba(0,0,0,0.72); border-color: rgba(255,255,255,0.2); transform: scale(1.06); }
+.lx-ob-score {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 15px;
+ font-weight: 800;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.01em;
+}
+.lx-ob-tier {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 8px;
+ font-weight: 700;
+ letter-spacing: 0.07em;
+ text-transform: uppercase;
+ opacity: 0.85;
+ margin-top: 2px;
+}
diff --git a/src/launches.js b/src/launches.js
index 62884487e..f03f1efc8 100644
--- a/src/launches.js
+++ b/src/launches.js
@@ -21,6 +21,7 @@
import { mountCoinStatus } from './pump/coin-status-card.js';
const PAGE_SIZE = 24;
+const ORACLE_TIER_COLOR = { prime: '#c084fc', strong: '#34d399', lean: '#fbbf24', watch: '#94a3b8', avoid: '#f87171' };
const LIVE_REFRESH_MS = 60_000;
const state = {
@@ -347,6 +348,46 @@ function teardownStatusHandles() {
cardStatusHandles.clear();
}
+// ── Oracle conviction batch enrichment ───────────────────────────────────────
+// After each page of cards renders, batch-fetch Oracle conviction for all
+// visible mints (≤20 per request) and paint a tier badge on each card.
+// Non-blocking: a fetch failure leaves cards untouched.
+
+async function enrichCardsWithOracle(cards) {
+ const mints = cards
+ .map((c) => c.dataset.mint)
+ .filter(Boolean);
+ if (!mints.length) return;
+ const chunks = [];
+ for (let i = 0; i < mints.length; i += 20) chunks.push(mints.slice(i, i + 20));
+ let results = {};
+ try {
+ const resps = await Promise.all(
+ chunks.map((ch) =>
+ fetch(`/api/oracle/batch?mints=${ch.map(encodeURIComponent).join(',')}&network=mainnet`)
+ .then((r) => r.ok ? r.json() : null)
+ .catch(() => null),
+ ),
+ );
+ for (const r of resps) {
+ if (r?.results) Object.assign(results, r.results);
+ }
+ } catch { return; }
+
+ for (const card of cards) {
+ const mint = card.dataset.mint;
+ const data = results[mint];
+ if (!data || data.score == null) continue;
+ const badge = card.querySelector('.lx-oracle-badge');
+ if (!badge) continue;
+ const color = ORACLE_TIER_COLOR[data.tier] || '#94a3b8';
+ badge.innerHTML = `<a class="lx-ob-link" href="/oracle?mint=${encodeURIComponent(mint)}" title="Oracle conviction: ${data.score} — ${data.tier || 'unscored'}" tabindex="-1" aria-hidden="true">
+ <span class="lx-ob-score" style="color:${color}">${data.score}</span>
+ <span class="lx-ob-tier" style="color:${color}">${data.tier || ''}</span>
+ </a>`;
+ }
+}
+
// ── card rendering ───────────────────────────────────────────────────────────
function agentChip(agent) {
@@ -477,7 +518,7 @@ function launchCard(launch, index, { featured = false } = {}) {
'aria-label': `Open ${launch.symbol ? `$${launch.symbol}` : launch.name || 'coin'} profile`,
});
- const card = el('article', { class: `lx-card${featured ? ' lx-card-featured' : ''}` }, [
+ const card = el('article', { class: `lx-card${featured ? ' lx-card-featured' : ''}`, 'data-mint': launch.mint }, [
cardLink,
featured ? el('span', { class: 'lx-feat-tag', text: 'Latest' }) : null,
featured && launch.symbol
@@ -488,6 +529,7 @@ function launchCard(launch, index, { featured = false } = {}) {
agentChip(launch.agent),
el('div', { class: 'lx-card-actions' }, actions),
el('span', { class: 'lx-mint', text: launch.mint, title: launch.mint }),
+ el('div', { class: 'lx-oracle-badge', 'aria-hidden': 'true' }),
]);
reveal(card, index);
@@ -653,10 +695,14 @@ async function loadPage({ reset = false } = {}) {
const { launches = [], has_more: hasMore = false } = await fetchLaunches(state.offset, PAGE_SIZE);
clearSkeletons();
+ const newCards = [];
launches.forEach((l, i) => {
state.seenMints.add(l.mint);
- feedEl.appendChild(launchCard(l, i, { featured: isFirstPage && i === 0 }));
+ const card = launchCard(l, i, { featured: isFirstPage && i === 0 });
+ feedEl.appendChild(card);
+ newCards.push(card);
});
+ enrichCardsWithOracle(newCards);
state.offset += launches.length;
state.count += launches.length;
state.hasMore = hasMore;
@@ -697,13 +743,16 @@ async function liveRefresh() {
if (!fresh.length) return;
const anchor = feedEl.querySelector('.lx-card');
+ const freshCards = [];
// Newest-first: insert in reverse so the very newest ends up on top.
for (let i = fresh.length - 1; i >= 0; i--) {
const l = fresh[i];
state.seenMints.add(l.mint);
const card = launchCard(l, 0);
feedEl.insertBefore(card, anchor || feedEl.firstChild);
+ freshCards.push(card);
}
+ enrichCardsWithOracle(freshCards);
state.count += fresh.length;
state.offset += fresh.length;
state.latestCreatedAt = fresh[0].created_at;
diff --git a/vercel.json b/vercel.json
index 24299221e..f368a0f1b 100644
--- a/vercel.json
+++ b/vercel.json
@@ -159,6 +159,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
},
+ "api/oracle/action-stream.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 300
+ },
"api/oracle/wallet.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
@@ -1837,6 +1841,10 @@
"src": "/api/oracle/stream",
"dest": "/api/oracle/stream.js"
},
+ {
+ "src": "/api/oracle/action-stream",
+ "dest": "/api/oracle/action-stream.js"
+ },
{
"src": "/api/oracle/wallet",
"dest": "/api/oracle/wallet.js"