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.

feat: self-sustaining Coin Intelligence observer for the radar feed

zprv64ea24836b76
diff --git a/api/cron/coin-intel-observe.js b/api/cron/coin-intel-observe.js
new file mode 100644
index 000000000..3e54f9d1f
--- /dev/null
+++ b/api/cron/coin-intel-observe.js
@@ -0,0 +1,188 @@
+// GET/POST /api/cron/coin-intel-observe — the serverless Coin Intelligence firehose.
+//
+// The /coin-intel feed reads observed launches from pump_coin_intel. Those rows
+// are written by observing pump.fun's live launch firehose for each new coin's
+// first seconds of trading. The always-on agent-sniper worker does this when it
+// is deployed; this cron makes the engine self-sustaining on Vercel alone, so
+// the feed populates without depending on a long-running host.
+//
+// Per run: open a PumpPortal WebSocket, subscribe to new tokens, accumulate each
+// new mint's create event + trades for a bounded budget, then finalize every
+// observed coin through the SAME shared path the worker uses
+// (workers/agent-sniper/intel/finalize.js) — compute signals, classify, resolve
+// the funding graph, cross-reference smart money, and upsert to Postgres.
+//
+// Bounded + idempotent: the budget is capped under the function's maxDuration,
+// finalize runs with a small concurrency pool, and persistIntel upserts by mint
+// so overlapping runs converge instead of duplicating.
+
+import WebSocket from 'ws';
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { finalizeObservation } from '../../workers/agent-sniper/intel/finalize.js';
+
+const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const NETWORK = 'mainnet';
+const META_TIMEOUT_MS = 2_500;
+
+// Budget must stay under the function maxDuration (120s in vercel.json) with
+// headroom for the finalize drain. Observe for OBSERVE_MS, then drain.
+const OBSERVE_MS = Number(process.env.COIN_INTEL_OBSERVE_MS) || 85_000;
+const MAX_OBSERVATIONS = Number(process.env.COIN_INTEL_MAX_OBS) || 300;
+const FINALIZE_CONCURRENCY = Number(process.env.COIN_INTEL_FINALIZE_CONCURRENCY) || 8;
+const USE_LLM = process.env.COIN_INTEL_LLM === '1' || process.env.COIN_INTEL_LLM === 'true';
+
+const solToLamports = (sol) => Math.round((Number(sol) || 0) * LAMPORTS_PER_SOL);
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+// Off-hot-path metadata fetch (description/socials) — best-effort, never blocks.
+async function fetchMeta(uri) {
+ if (!uri) return null;
+ try {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), META_TIMEOUT_MS);
+ const r = await fetch(uri, { signal: ctrl.signal });
+ clearTimeout(tid);
+ if (!r.ok) return null;
+ const d = await r.json();
+ return {
+ description: d.description || null,
+ twitter: d.twitter || null,
+ telegram: d.telegram || null,
+ website: d.website || null,
+ image_uri: d.image || d.image_uri || null,
+ };
+ } catch { return null; }
+}
+
+// Run the firehose for OBSERVE_MS, returning the map of observations collected.
+function collectObservations(budgetMs) {
+ return new Promise((resolve) => {
+ const observations = new Map(); // mint -> obs
+ const metaPending = [];
+ let settled = false;
+ let ws;
+
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(deadline);
+ try { ws?.close(); } catch {}
+ // Let any in-flight metadata enrich attach before we hand off.
+ Promise.allSettled(metaPending).then(() => resolve(observations));
+ };
+ const deadline = setTimeout(finish, budgetMs);
+
+ const send = (obj) => {
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ try { ws.send(JSON.stringify(obj)); } catch {}
+ }
+ };
+
+ try { ws = new WebSocket(PUMPPORTAL_WS); }
+ catch { finish(); return; }
+
+ ws.on('open', () => send({ method: 'subscribeNewToken' }));
+
+ ws.on('message', (raw) => {
+ let msg;
+ try { msg = JSON.parse(raw.toString()); } catch { return; }
+ if (msg.message) return; // ack
+
+ if (msg.txType === 'create') {
+ const mint = msg.mint;
+ if (!mint || observations.has(mint)) return;
+ if (observations.size >= MAX_OBSERVATIONS) return;
+ const now = Date.now();
+ const obs = {
+ mint,
+ createdAtSec: Math.floor(now / 1000),
+ firstSeenAtMs: now,
+ creator: msg.traderPublicKey || null,
+ devBuyLamports: msg.solAmount != null ? solToLamports(msg.solAmount) : null,
+ mcSolFirstSeen: typeof msg.marketCapSol === 'number' ? msg.marketCapSol : null,
+ meta: {
+ name: msg.name || null,
+ symbol: msg.symbol || null,
+ bonding_curve: msg.bondingCurveKey || null,
+ image_uri: msg.uri || null,
+ uri: msg.uri || null,
+ description: null, twitter: null, telegram: null, website: null,
+ },
+ // Seed the creator's launch buy as the first trade so dev sizing /
+ // concentration include it.
+ trades: msg.solAmount
+ ? [{ trader: msg.traderPublicKey || null, isBuy: true, lamports: solToLamports(msg.solAmount), baseAmount: Number(msg.tokenAmount) || 0, ts: now, signature: msg.signature }]
+ : [],
+ };
+ observations.set(mint, obs);
+ send({ method: 'subscribeTokenTrade', keys: [mint] });
+ metaPending.push(fetchMeta(obs.meta.uri).then((m) => { if (m) Object.assign(obs.meta, m); }).catch(() => {}));
+ } else if (msg.txType === 'buy' || msg.txType === 'sell') {
+ const obs = observations.get(msg.mint);
+ if (!obs) return;
+ obs.trades.push({
+ trader: msg.traderPublicKey || null,
+ isBuy: msg.txType === 'buy',
+ lamports: msg.solAmount != null ? solToLamports(msg.solAmount) : 0,
+ baseAmount: Number(msg.tokenAmount) || 0,
+ ts: Date.now(),
+ signature: msg.signature,
+ });
+ }
+ });
+
+ ws.on('error', () => { /* close handler resolves; reconnect not worth it in a bounded run */ });
+ ws.on('close', () => { if (!settled && observations.size === 0) finish(); });
+ });
+}
+
+// Finalize observations with a bounded concurrency pool.
+async function drain(observations, endedAtMs) {
+ const items = [...observations.values()];
+ let i = 0, persisted = 0, failed = 0;
+ async function worker() {
+ while (i < items.length) {
+ const obs = items[i++];
+ try {
+ await finalizeObservation(obs, { network: NETWORK, useLlm: USE_LLM, endedAtMs });
+ persisted++;
+ } catch { failed++; }
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(FINALIZE_CONCURRENCY, items.length || 1) }, worker));
+ return { persisted, failed };
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const started = Date.now();
+ const observations = await collectObservations(OBSERVE_MS);
+ const endedAtMs = Date.now();
+ const { persisted, failed } = await drain(observations, endedAtMs);
+
+ return json(res, 200, {
+ ok: true,
+ observed: observations.size,
+ persisted,
+ failed,
+ observe_ms: endedAtMs - started,
+ total_ms: Date.now() - started,
+ llm: USE_LLM,
+ });
+});
diff --git a/vercel.json b/vercel.json
index bdc6ea3cd..2823bcdf7 100644
--- a/vercel.json
+++ b/vercel.json
@@ -83,6 +83,9 @@
"api/cron/pulse-tick.js": {
"maxDuration": 120
},
+ "api/cron/coin-intel-observe.js": {
+ "maxDuration": 120
+ },
"api/cron/launcher-tick.js": {
"maxDuration": 120
},
@@ -4781,6 +4784,10 @@
"path": "/api/cron/pulse-tick",
"schedule": "*/2 * * * *"
},
+ {
+ "path": "/api/cron/coin-intel-observe",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/launcher-tick",
"schedule": "* * * * *"
diff --git a/workers/agent-sniper/intel/watcher.js b/workers/agent-sniper/intel/watcher.js
index 45164c349..a0eeff392 100644
--- a/workers/agent-sniper/intel/watcher.js
+++ b/workers/agent-sniper/intel/watcher.js
@@ -147,123 +147,10 @@ export function startIntelWatcher({
send({ method: 'unsubscribeTokenTrade', keys: [mint] });
try {
- const endedAtMs = Date.now();
-
- // ── Phase 1: deterministic signal computation (sync, no I/O) ─────────
- const { signals, quality_score, risk_flags, walletAgg } = computeSignals({
- mint,
- creator: obs.creator,
- createdAtMs: obs.firstSeenAtMs,
- firstSeenAtMs: obs.firstSeenAtMs,
- endedAtMs,
- devBuyLamports: obs.devBuyLamports,
- trades: obs.trades,
- });
- if (obs.mcSolFirstSeen != null) signals.mc_sol_first_seen = obs.mcSolFirstSeen;
-
- // ── Phase 2: parallel enrichment (network I/O, best-effort) ──────────
- // All three run concurrently; any failure degrades gracefully to null.
- const buyerWallets = [...walletAgg.keys()].filter((w) => {
- const a = walletAgg.get(w);
- return a && a.buyCount > 0;
- });
-
- const [cls, funderMap, smartMoneyResult] = await Promise.allSettled([
- // 2a. LLM/heuristic classification
- classifyCoin({
- name: obs.meta.name,
- symbol: obs.meta.symbol,
- description: obs.meta.description,
- twitter: obs.meta.twitter,
- telegram: obs.meta.telegram,
- website: obs.meta.website,
- }, { useLlm }),
-
- // 2b. Funding-graph: resolve SOL funder for each buyer wallet.
- // We skip wallets with no buy activity and cap at 60 to stay within
- // Helius rate limits. The most active/suspicious wallets are scored
- // first because walletAgg preserves insertion order (arrival time).
- resolveWalletFunders(buyerWallets.slice(0, 60)),
-
- // 2c. Smart-money cross-reference: which observed buyers have a proven
- // track record in wallet_reputation? Runs a single batched DB query.
- crossReferenceSmartMoney(buyerWallets),
- ]);
-
- // Unwrap settled results — never let a single failure abort the record.
- const classification = cls.status === 'fulfilled' ? cls.value
- : { category: 'unknown', tags: [], narrative: null, is_news_meme: false, confidence: 0.15, source: 'heuristic' };
-
- const resolvedFunders = funderMap.status === 'fulfilled' ? funderMap.value : new Map();
- const { clusters, connectivity } = buildClusters(resolvedFunders);
-
- const smartMoney = smartMoneyResult.status === 'fulfilled' ? smartMoneyResult.value
- : { count: 0, notable: [], top_label: null };
-
- // Push funder into walletAgg so persistIntel writes it to pump_coin_wallets
- for (const [wallet, funder] of resolvedFunders) {
- const entry = walletAgg.get(wallet);
- if (entry) entry.funder = funder || null;
- }
-
- // ── Phase 3: upgrade signals with enrichment results ─────────────────
- if (connectivity != null) signals.bubblemap_connectivity = connectivity;
- signals.smart_money_count = smartMoney.count;
- signals.smart_money_score = smartMoney.score ?? null;
- // Re-derive organic score with connectivity and fresh_wallet_ratio if available.
- // (bubblemap_connectivity penalises coordination; smart money boosts confidence.)
- if (connectivity != null) {
- const existing = signals.organic_score ?? 0;
- signals.organic_score = Math.max(0, Math.min(1,
- existing * (1 - 0.3 * connectivity) + (smartMoney.count > 0 ? 0.05 * Math.min(smartMoney.count, 3) : 0)
- ));
- signals.organic_score = Math.round(signals.organic_score * 10000) / 10000;
- }
-
- // Flag coordinated cluster in risk_flags if connectivity is high.
- if (connectivity != null && connectivity >= 0.4 && !risk_flags.includes('coordinated_cluster')) {
- risk_flags.push('coordinated_cluster');
- }
- // Smart money entering is an additive signal, not a risk flag — store in signals only.
-
- const record = {
- mint,
- network,
- symbol: obs.meta.symbol,
- name: obs.meta.name,
- creator: obs.creator,
- bonding_curve: obs.meta.bonding_curve,
- image_uri: obs.meta.image_uri,
- description: obs.meta.description,
- twitter: obs.meta.twitter,
- telegram: obs.meta.telegram,
- website: obs.meta.website,
- created_at_sec: obs.createdAtSec,
- first_seen_at_ms: obs.firstSeenAtMs,
- dev_buy_lamports: obs.devBuyLamports,
- dev_sell_lamports: solToLamports(signals.dev_sell_sol || 0),
- buy_volume_lamports: solToLamports(signals.buy_volume_sol || 0),
- sell_volume_lamports: solToLamports(signals.sell_volume_sol || 0),
- largest_buy_lamports: solToLamports(signals.largest_buy_sol || 0),
- signals,
- quality_score: recomputeQuality(quality_score, signals, smartMoney.count),
- risk_flags,
- category: classification.category,
- tags: classification.tags,
- narrative: classification.narrative,
- is_news_meme: classification.is_news_meme,
- classify_confidence: classification.confidence,
- classify_source: classification.source,
- // Smart-money enrichment fields (stored in record, persisted via new migration)
- smart_money_count: smartMoney.count,
- smart_money_score: smartMoney.score ?? null,
- smart_money_notable: smartMoney.notable,
- // Cluster summary
- cluster_count: clusters.size,
- bubblemap_connectivity: connectivity,
- };
-
- await persistIntel(record, walletAgg);
+ // Signal computation, enrichment, scoring and persistence all live in the
+ // shared finalize module so the serverless cron observer produces byte-for-byte
+ // identical records (api/cron/coin-intel-observe.js).
+ const { record, summary } = await finalizeObservation(obs, { network, useLlm });
if (active && onIntel) { try { onIntel(record); } catch {} }
log.info?.('intel finalized', {
@@ -271,27 +158,16 @@ export function startIntelWatcher({
symbol: obs.meta.symbol,
quality: record.quality_score,
category: record.category,
- smart_money: smartMoney.count,
- connectivity: connectivity != null ? connectivity.toFixed(3) : null,
- clusters: clusters.size,
- buyers: buyerWallets.length,
+ smart_money: summary.smartMoney,
+ connectivity: summary.connectivity != null ? summary.connectivity.toFixed(3) : null,
+ clusters: summary.clusters,
+ buyers: summary.buyers,
});
} catch (err) {
log.error?.('intel finalize failed', { mint, err: err?.message });
}
}
- // Recompute quality score incorporating smart-money signal.
- // Smart money entering early is the strongest positive signal we have.
- function recomputeQuality(baseScore, signals, smartMoneyCount) {
- let q = baseScore;
- if (smartMoneyCount >= 1) q += 8;
- if (smartMoneyCount >= 2) q += 6;
- if (smartMoneyCount >= 3) q += 4;
- // connectivity penalty already applied to organic_score; don't double-count.
- return Math.max(0, Math.min(100, Math.round(q)));
- }
-
function connect() {
if (!active) return;
ws = new WebSocket(PUMPPORTAL_WS);