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
Oracle: follower alerts, MCP oracle tools, drawer enhancements
nirholasd45b4e094897
diff --git a/api/_lib/migrations/20260616230000_oracle_followers.sql b/api/_lib/migrations/20260616230000_oracle_followers.sqlnew file mode 100644index 000000000..6ef9211d7--- /dev/null+++ b/api/_lib/migrations/20260616230000_oracle_followers.sql@@ -0,0 +1,25 @@+begin;++-- Oracle agent followers: lets any Telegram user subscribe to an agent's+-- conviction signals without arming their own agent. When an armed agent+-- executes (or simulates) a buy, all followers of that agent receive a+-- real-time Telegram alert with the coin, score, and deep link to Oracle.+create table if not exists oracle_followers (+ id bigserial primary key,+ agent_id uuid not null,+ chat_id text not null, -- Telegram chat ID (user or group)+ network text not null default 'mainnet',+ min_score int not null default 54, -- only signal at this score++ created_at timestamptz not null default now(),+ unique (agent_id, chat_id, network)+);++create index if not exists oracle_followers_agent+ on oracle_followers (agent_id, network);++comment on table oracle_followers is+ 'Telegram subscribers for Oracle agent conviction signals. '+ 'Separate from oracle_agent_watch (that table is for the agent owner arming their own bot). '+ 'Followers get a read-only feed of an armed agent''s buys — the Watch tier of social copy-trading.';++commit;diff --git a/api/_lib/oracle/alerts.js b/api/_lib/oracle/alerts.jsindex 9a1297550..456ce5fac 100644--- a/api/_lib/oracle/alerts.js+++ b/api/_lib/oracle/alerts.js@@ -301,6 +301,51 @@ export async function alertPersonalConvictionDrop(chatId, drop) {await sendTo(chatId, text);}+/**+ * Fan-out entry alert to all Telegram subscribers of a given agent.+ * Called by the agent-loop after every filled action (simulate or live).+ * Each follower only receives the alert if the coin's score meets their+ * personal min_score threshold.+ *+ * @param {string} agentId UUID of the agent that acted+ * @param {{ symbol:string, mint:string, tier:string, score:number, size_sol?:number, mode:string, network:string }} entry+ * @returns {Promise<number>} followers alerted+ */+export async function alertFollowers(agentId, entry) {+ const token = process.env.TELEGRAM_BOT_TOKEN;+ if (!token || !agentId) return 0;++ const network = entry.network || 'mainnet';+ const score = Number(entry.score) || 0;++ const rows = await sql`+ select f.chat_id+ from oracle_followers f+ where f.agent_id = ${agentId}+ and f.network = ${network}+ and f.min_score <= ${score}+ `.catch(() => []);+ if (!rows.length) return 0;++ const tierE = tierEmoji(entry.tier);+ const sym = escHtml((entry.symbol || entry.mint.slice(0, 6)).toUpperCase());+ const sizeStr = entry.size_sol != null ? `${Number(entry.size_sol).toFixed(3)} SOL` : '?';+ const modeLabel = entry.mode === 'simulate' ? ' <i>[sim]</i>' : '';++ const text = [+ `${tierE} Followed agent entered <b>$${sym}</b>${modeLabel}`,+ `${escHtml(entry.tier)} conviction (${score}) · ${escHtml(sizeStr)}`,+ `<a href="https://pump.fun/coin/${encodeURIComponent(entry.mint)}">pump.fun</a> · <a href="https://three.ws/oracle?mint=${encodeURIComponent(entry.mint)}">Oracle ↗</a>`,+ ].join('\n');++ let sent = 0;+ for (const { chat_id } of rows) {+ sendTo(chat_id, text).catch(() => {});+ sent++;+ }+ return sent;+}+/** Send to a specific chat ID (not the platform channel). */async function sendTo(chatId, text) {const token = process.env.TELEGRAM_BOT_TOKEN;diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex abd5c5814..fca59c569 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -552,6 +552,12 @@ export const limits = {// retries while blocking scripted abuse.oracleTelegramTestIp: (ip) =>getLimiter('oracle:tg-test:ip', { limit: 5, window: '10 m' }).limit(ip),++ // Oracle follower subscribe/update — write path creates a DB row and will+ // eventually fan out Telegram messages, so keep post-rate tight.+ // 10 per hour per IP is enough for manual setup; bots would need more.+ oracleFollowIp: (ip) =>+ getLimiter('oracle:follow:ip', { limit: 10, window: '1 h' }).limit(ip),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex d619b480a..4e1dc3e8b 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -11,6 +11,7 @@ import { toolDefs as agentDefs } from './tools/agents.js';import { toolDefs as animationDefs } from './tools/animations.js';import { toolDefs as memoryDefs } from './tools/memory.js';import { toolDefs as embedDefs } from './tools/embed.js';+import { toolDefs as oracleDefs } from './tools/oracle.js';const baseDefs = [...avatarDefs,@@ -21,6 +22,7 @@ const baseDefs = [...pumpfunDefs,...agentDefs,...memoryDefs,+ ...oracleDefs,];// Free, public entry point — listed first so discovery clients see it up top.@@ -32,7 +34,7 @@ const gettingStarted = {...buildGettingStartedTool({server: 'three.ws',tagline:- 'The main three.ws MCP server: render and manage 3D avatars and models, animations, an agent registry, agent memory, and live pump.fun market data.',+ 'The main three.ws MCP server: render and manage 3D avatars and models, animations, an agent registry, agent memory, live pump.fun market data, and Oracle conviction signals.',tools: baseDefs,priceFor,access: [diff --git a/api/_mcp/tools/oracle.js b/api/_mcp/tools/oracle.jsnew file mode 100644index 000000000..b19512315--- /dev/null+++ b/api/_mcp/tools/oracle.js@@ -0,0 +1,351 @@+// Oracle MCP tools — conviction signal for autonomous agents.+//+// Three tools, one mission: give any 3D AI agent on three.ws access to the+// same Oracle conviction intelligence that drives the platform's own sniper+// strategy and copy-trading systems.+//+// oracle_top_plays — public, no auth needed. Returns the current top-scoring+// pump.fun launches ranked by Oracle conviction. Each play+// carries a machine-readable recommendation: action (buy /+// watch / skip), confidence, and a suggested size factor+// so the agent never has to re-derive the trading signal.+//+// oracle_coin — public. Full conviction verdict for one specific mint:+// score, tier, four pillar scores, badges, and the same+// agent-ready recommendation envelope.+//+// oracle_arm_watch — requires account auth (scope: agents:write). Arms (or+// updates) the caller's agent to act on the live Oracle+// stream. Sets the conviction floor, category filters,+// per-trade SOL cap, and simulate-vs-live mode. The+// cron runs every 2 min and will execute actions on behalf+// of the agent without further intervention.++import { sql } from '../../_lib/db.js';+import { limits } from '../../_lib/rate-limit.js';+import { readFeed, scoreCoin, getWatch, upsertWatch, recentActions, actionsSummary } from '../../_lib/oracle/store.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const CATEGORIES = new Set([+ 'meme', 'tech', 'ai', 'culture', 'community', 'political',+ 'news', 'animal', 'celebrity', 'utility', 'unknown',+]);+const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const REC = {+ prime: { action: 'buy', confidence: 'high', size_factor: 1.0, note: 'top-conviction play — proven smart money + clean structure + on-narrative' },+ strong: { action: 'buy', confidence: 'medium', size_factor: 0.75, note: 'strong conviction — favorable across multiple pillars' },+ lean: { action: 'watch', confidence: 'low', size_factor: 0, note: 'leaning positive but not decisive — watch for confirmation' },+ watch: { action: 'skip', confidence: 'low', size_factor: 0, note: 'inconclusive — no edge yet' },+ avoid: { action: 'skip', confidence: 'high', size_factor: 0, note: 'structural or pedigree red flags — avoid' },+};++function shapePlay(it) {+ return {+ mint: it.mint,+ symbol: it.symbol,+ conviction: it.score,+ tier: it.tier,+ category: it.category,+ smart_wallet_count: it.smart_wallet_count ?? 0,+ pillars: it.pillars,+ badges: it.badges ?? [],+ recommendation: REC[it.tier] || REC.avoid,+ scored_at: it.scored_at,+ };+}++function mcpOk(payload) {+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],+ structuredContent: payload,+ };+}++function mcpErr(msg) {+ return { content: [{ type: 'text', text: msg }], isError: true };+}++async function ownsAgent(userId, agentId) {+ const rows = await sql`+ select id from agent_identities+ where id = ${agentId} and user_id = ${userId} and deleted_at is null+ limit 1+ `.catch(() => []);+ return rows.length > 0;+}++const LIVE_ANNOTATIONS = {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+};++export const toolDefs = [+ // ── oracle_top_plays ────────────────────────────────────────────────────+ {+ name: 'oracle_top_plays',+ title: 'Oracle top conviction plays',+ annotations: LIVE_ANNOTATIONS,+ description:+ "Get the current top pump.fun launches ranked by Oracle conviction score. Each play includes a score (0–100), tier (prime/strong/lean/watch/avoid), four pillar scores (pedigree/structure/narrative/momentum), and an agent-ready recommendation with a suggested size_factor. Use this to decide which coins to buy before they move. Filter by min_score or category to narrow the signal.",+ inputSchema: {+ type: 'object',+ properties: {+ limit: { type: 'integer', minimum: 1, maximum: 20, default: 5, description: 'Number of plays to return (default 5, max 20).' },+ min_score: { type: 'integer', minimum: 0, maximum: 100, default: 72, description: 'Minimum conviction score (0–100). Default 72 (strong+).' },+ category: { type: 'string', enum: [...CATEGORIES], description: 'Filter by narrative category (optional).' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ },+ additionalProperties: false,+ },+ async handler(args, auth) {+ const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';+ const minScore = Math.max(0, Math.min(100, Number(args?.min_score ?? 72)));+ const limit = Math.min(20, Math.max(1, Number(args?.limit ?? 5)));+ const category = CATEGORIES.has(args?.category) ? args.category : null;++ const rl = await limits.mcpIp(auth.rateKey || 'anon');+ if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');++ const items = await readFeed({+ network, limit, minScore, category, sinceSeconds: 6 * 3600,+ }).catch(() => []);++ const plays = items.map(shapePlay);+ const payload = {+ network,+ count: plays.length,+ top: plays[0] || null,+ plays,+ generated_at: new Date().toISOString(),+ hint: plays.length === 0+ ? 'No plays found at this conviction floor. Try lowering min_score or broadening the category.'+ : `Top play: ${plays[0]?.symbol || plays[0]?.mint} at ${plays[0]?.conviction}/100 (${plays[0]?.tier}).`,+ };+ return mcpOk(payload);+ },+ },++ // ── oracle_coin ─────────────────────────────────────────────────────────+ {+ name: 'oracle_coin',+ title: 'Oracle verdict for one coin',+ annotations: LIVE_ANNOTATIONS,+ description:+ "Get Oracle's full conviction verdict for a specific pump.fun coin by mint address. Returns the fused 0–100 conviction score, tier (prime/strong/lean/watch/avoid), all four pillar scores (pedigree = who's behind it, structure = how it's built, narrative = cultural fit, momentum = early trading signal), active badges (e.g. smart_money_early, narrative_match), and a machine-readable buy/watch/skip recommendation. If the coin isn't in the Oracle cache yet, it will be scored on-demand (may add ~1s latency).",+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string', description: 'SPL mint pubkey (base58) of the pump.fun coin.' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ },+ required: ['mint'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';+ const mint = (args?.mint || '').trim();++ if (!MINT_RE.test(mint)) return mcpErr('Invalid mint: must be a base58 Solana address (32–44 chars).');++ const rl = await limits.mcpIp(auth.rateKey || 'anon');+ if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');++ const scored = await scoreCoin(mint, { network, classify: true, persist: true }).catch(() => null);+ if (!scored) {+ return mcpErr(`Coin ${mint} not found in Oracle — it may not have been observed on pump.fun yet.`);+ }++ const v = scored.verdict;+ const play = shapePlay({+ mint, symbol: scored.intel?.symbol, score: v.score, tier: v.tier,+ category: scored.intel?.category,+ smart_wallet_count: scored.intel?.smartMoney?.smartWalletCount ?? 0,+ pillars: v.pillars, badges: v.badges,+ scored_at: new Date().toISOString(),+ });++ const payload = {+ network, ...play,+ market_cap_usd: scored.intel?.marketCapUsd ?? null,+ graduated: scored.intel?.graduated ?? false,+ creator: scored.intel?.creator ?? null,+ generated_at: new Date().toISOString(),+ };+ return mcpOk(payload);+ },+ },++ // ── oracle_arm_watch ────────────────────────────────────────────────────+ {+ name: 'oracle_arm_watch',+ title: 'Arm agent Oracle watch',+ scope: 'agents:write',+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ },+ description:+ "Arm your agent to automatically act on Oracle conviction signals. Once armed, the Oracle cron (every 2 min) will detect high-conviction launches that cross your floor and execute buys from your agent's custodial Solana wallet. Set mode='simulate' (default, safe) to log what it would have bought without spending. Set mode='live' to spend real SOL. The agent acts at most once per mint, per-trade SOL is capped, and you can disarm at any time by passing armed=false.",+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'Your agent UUID (from /api/agents or the dashboard).' },+ armed: { type: 'boolean', default: true, description: 'true to arm, false to disarm.' },+ mode: { type: 'string', enum: ['simulate', 'live'], default: 'simulate', description: "simulate = no real spend (safe default). live = real SOL from agent's wallet." },+ min_score: { type: 'integer', minimum: 0, maximum: 100, default: 72, description: 'Conviction floor to act on (72 = strong+; 90 = prime only).' },+ min_tier: { type: 'string', enum: ['prime', 'strong', 'lean', 'watch'], description: 'Alternative to min_score — acts on this tier and above.' },+ categories: { type: 'array', items: { type: 'string', enum: [...CATEGORIES] }, description: 'Only act on coins in these narrative categories. Omit to act on all.' },+ per_trade_sol: { type: 'number', minimum: 0.001, maximum: 1, default: 0.05, description: 'Max SOL per single trade (default 0.05). Ignored in simulate mode.' },+ max_daily_sol: { type: 'number', minimum: 0, maximum: 10, default: 0.5, description: 'Daily SOL budget cap (default 0.5). The loop will not spend more in one day.' },+ max_open: { type: 'integer', minimum: 1, maximum: 50, default: 10, description: 'Max simultaneous open positions (default 10).' },+ require_smart_money: { type: 'boolean', default: false, description: 'Only act when at least one proven smart-money wallet is in early.' },+ size_scaling: { type: 'boolean', default: true, description: 'Scale position size with conviction (prime = full, strong = 75%, lean = 50%).' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ if (!auth.userId) return mcpErr('You must be signed in with a three.ws account to arm an agent watch.');++ const agentId = (args?.agent_id || '').trim();+ if (!UUID_RE.test(agentId)) return mcpErr('Invalid agent_id — must be a UUID (get it from /api/agents or your dashboard).');++ if (!(await ownsAgent(auth.userId, agentId))) {+ return mcpErr(`Agent ${agentId} does not belong to your account.`);+ }++ const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';++ const cfg = {+ armed: args?.armed !== false,+ mode: args?.mode === 'live' ? 'live' : 'simulate',+ min_score: Math.max(0, Math.min(100, Number(args?.min_score ?? 72))),+ min_tier: (args?.min_tier && TIERS.has(args.min_tier)) ? args.min_tier : 'strong',+ categories: Array.isArray(args?.categories) ? args.categories.filter((c) => CATEGORIES.has(c)) : [],+ per_trade_sol: Math.max(0.001, Math.min(1, Number(args?.per_trade_sol ?? 0.05))),+ max_daily_sol: Math.max(0, Math.min(10, Number(args?.max_daily_sol ?? 0.5))),+ max_open: Math.max(1, Math.min(50, Number(args?.max_open ?? 10))),+ require_smart_money: !!args?.require_smart_money,+ size_scaling: args?.size_scaling !== false,+ };++ await upsertWatch(agentId, auth.userId, network, cfg);++ const [watch, summary] = await Promise.all([+ getWatch(agentId, network),+ actionsSummary(agentId, network),+ ]);++ const payload = {+ success: true,+ agent_id: agentId,+ network,+ watch: watch || { agent_id: agentId, network, ...cfg },+ track_record: summary || { total: 0, wins: 0, losses: 0, win_rate: null, realized_pnl_sol: 0 },+ message: cfg.armed+ ? `Agent armed in ${cfg.mode} mode. The Oracle cron runs every 2 min — your first action will appear in /oracle?tab=activity once a qualifying coin is scored.`+ : `Agent disarmed. No further Oracle actions will be taken.`,+ links: {+ activity: `https://three.ws/activity`,+ oracle: `https://three.ws/oracle`,+ trader: `https://three.ws/trader/${agentId}`,+ },+ };+ return mcpOk(payload);+ },+ },++ // ── oracle_watch_status ─────────────────────────────────────────────────+ {+ name: 'oracle_watch_status',+ title: 'Oracle watch status + track record',+ scope: 'agents:read',+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ },+ description:+ "Check your agent's current Oracle watch configuration and its realized track record: win rate, PnL, ROI, plus the 10 most recent actions with their outcomes. Use this to verify the agent is armed correctly and to review its performance before scaling up.",+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'Your agent UUID.' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ if (!auth.userId) return mcpErr('Sign in to check your agent watch status.');++ const agentId = (args?.agent_id || '').trim();+ if (!UUID_RE.test(agentId)) return mcpErr('Invalid agent_id — must be a UUID.');++ if (!(await ownsAgent(auth.userId, agentId))) {+ return mcpErr(`Agent ${agentId} does not belong to your account.`);+ }++ const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';++ const [watch, summary, actions] = await Promise.all([+ getWatch(agentId, network),+ actionsSummary(agentId, network),+ recentActions(agentId, network, 10),+ ]);++ if (!watch) {+ return mcpOk({+ agent_id: agentId, network,+ armed: false,+ message: "No Oracle watch configured yet. Use oracle_arm_watch to get started.",+ track_record: null,+ recent_actions: [],+ });+ }++ const payload = {+ agent_id: agentId,+ network,+ armed: watch.armed,+ mode: watch.mode,+ config: {+ min_score: watch.min_score,+ min_tier: watch.min_tier,+ categories: watch.categories,+ per_trade_sol: watch.per_trade_sol,+ max_daily_sol: watch.max_daily_sol,+ max_open: watch.max_open,+ require_smart_money: watch.require_smart_money,+ size_scaling: watch.size_scaling,+ },+ track_record: summary || { total: 0, wins: 0, losses: 0, win_rate: null, realized_pnl_sol: 0 },+ recent_actions: (actions || []).map((a) => ({+ mint: a.mint,+ symbol: a.symbol,+ tier: a.tier,+ conviction: a.conviction_score,+ size_sol: a.size_sol,+ mode: a.mode,+ outcome: a.outcome,+ pnl_sol: a.realized_pnl_sol,+ acted_at: a.acted_at,+ })),+ links: {+ trader: `https://three.ws/trader/${agentId}`,+ oracle: `https://three.ws/oracle`,+ },+ };+ return mcpOk(payload);+ },+ },+];diff --git a/api/oracle/follow.js b/api/oracle/follow.jsnew file mode 100644index 000000000..5e41a6fc1--- /dev/null+++ b/api/oracle/follow.js@@ -0,0 +1,133 @@+/**+ * Oracle — agent follower subscriptions (the Watch tier of social copy-trading).+ *+ * GET /api/oracle/follow?agent_id=<uuid>&chat_id=<telegram>&network=mainnet+ * → { following: bool, min_score: int|null }+ *+ * POST /api/oracle/follow { agent_id, chat_id, min_score? }+ * → { ok: true, action: 'subscribed'|'updated' }+ * Idempotent: posting again updates min_score on an existing row.+ *+ * DELETE /api/oracle/follow { agent_id, chat_id }+ * → { ok: true }+ *+ * No auth required: the Telegram chat_id is the caller-supplied identity.+ * Rate-limited per IP and per (agent_id, chat_id) pair to prevent spam.+ *+ * How the signals are delivered: when an armed Oracle agent makes a conviction+ * buy (in `workers/oracle/agent-loop.js`), the agent-loop calls+ * `alertFollowers()` (api/_lib/oracle/alerts.js) which fans out a Telegram+ * message to every follower subscribed to that agent above their min_score.+ */++import { cors, json, method, readJson, wrap, error, 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 CHAT_ID_RE = /^-?\d{1,20}$|^@[a-zA-Z0-9_]{5,32}$/;+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function validateChatId(v) {+ return typeof v === 'string' && CHAT_ID_RE.test(v.trim());+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', origins: '*' })) return;+ const ip = clientIp(req);++ // ── GET — check follow status ─────────────────────────────────────────────+ if (method(req, res, ['GET'], { silent: true })) {+ const rl = await limits.publicIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const agentId = params.get('agent_id') || '';+ const chatId = (params.get('chat_id') || '').trim();+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';++ if (!UUID_RE.test(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');+ if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric ID or @handle');++ const rows = await sql`+ select min_score from oracle_followers+ where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}+ limit 1+ `.catch(() => []);++ return json(res, 200, {+ following: rows.length > 0,+ min_score: rows.length > 0 ? Number(rows[0].min_score) : null,+ });+ }++ // ── POST — subscribe or update ────────────────────────────────────────────+ if (method(req, res, ['POST'], { silent: true })) {+ const rl = await limits.oracleFollowIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, res);+ if (!body) return;++ const agentId = (body.agent_id || '').trim();+ const chatId = (body.chat_id || '').trim();+ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';+ const minScore = Math.min(100, Math.max(0, Number(body.min_score ?? 54) || 54));++ if (!UUID_RE.test(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');+ if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric Telegram ID or @handle');++ // Ensure the agent exists (guard against phantom subscriptions)+ const agentRows = await sql`+ select id from agent_identities where id = ${agentId} and deleted_at is null limit 1+ `.catch(() => []);+ if (!agentRows.length) return error(res, 404, 'not_found', 'agent not found');++ const existing = await sql`+ select id from oracle_followers+ where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}+ limit 1+ `.catch(() => []);++ if (existing.length) {+ await sql`+ update oracle_followers+ set min_score = ${minScore}+ where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}+ `;+ return json(res, 200, { ok: true, action: 'updated', min_score: minScore });+ }++ await sql`+ insert into oracle_followers (agent_id, chat_id, network, min_score)+ values (${agentId}, ${chatId}, ${network}, ${minScore})+ on conflict (agent_id, chat_id, network) do update set min_score = excluded.min_score+ `;+ return json(res, 201, { ok: true, action: 'subscribed', min_score: minScore });+ }++ // ── DELETE — unsubscribe ──────────────────────────────────────────────────+ if (method(req, res, ['DELETE'], { silent: true })) {+ const rl = await limits.publicIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, res);+ if (!body) return;++ const agentId = (body.agent_id || '').trim();+ const chatId = (body.chat_id || '').trim();+ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';++ if (!UUID_RE.test(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');+ if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric Telegram ID or @handle');++ await sql`+ delete from oracle_followers+ where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}+ `.catch(() => {});++ return json(res, 200, { ok: true });+ }++ error(res, 405, 'method_not_allowed', 'GET, POST or DELETE required');+});diff --git a/src/oracle.js b/src/oracle.jsindex 9d5c49e5a..593b2e66f 100644--- a/src/oracle.js+++ b/src/oracle.js@@ -1015,7 +1015,9 @@ function renderDrawer(d) {<div class="dr-actions"><a class="dr-act" href="${pumpUrl(c.mint)}" target="_blank" rel="noopener">pump.fun ↗</a><a class="dr-act" href="${solscan(c.mint)}" target="_blank" rel="noopener">solscan ↗</a>+ <a class="dr-act" href="/launches/${esc(c.mint)}" target="_blank" rel="noopener">Details ↗</a><button class="dr-act dr-watch" id="drWatch" data-mint="${esc(c.mint)}" type="button" aria-pressed="${watchedMints().has(c.mint)}">${watchedMints().has(c.mint) ? '★ Watching' : '☆ Watch'}</button>+ <button class="dr-act" id="drCopyMint" type="button" title="Copy mint address" data-mint="${esc(c.mint)}">Copy mint</button><a class="dr-act dr-share" href="${tweetConviction(c)}" target="_blank" rel="noopener" title="Share conviction on X">Share ↗</a>${c.structure_cap != null && c.structure_cap < 60 ? `<span class="note warn">structural cap ${c.structure_cap}</span>` : ''}</div>@@ -1082,8 +1084,77 @@ function renderDrawer(d) {}});}++ // Copy mint address+ const copyMintBtn = $('#drCopyMint');+ if (copyMintBtn) {+ copyMintBtn.addEventListener('click', () => {+ navigator.clipboard.writeText(c.mint).then(() => {+ const orig = copyMintBtn.textContent;+ copyMintBtn.textContent = 'Copied!';+ setTimeout(() => { copyMintBtn.textContent = orig; }, 1800);+ }).catch(() => {});+ });+ }++ // Load related coins in same category (async — does not block drawer)+ if (c.category) loadRelatedCoins(c.mint, c.category);}+async function loadRelatedCoins(mint, category) {+ const whosSec = $('#drBody')?.querySelector('.dr-sec:last-of-type');+ if (!whosSec || !$('#drBody')) return;++ const { ok, data } = await api(+ `/api/oracle/feed?network=${NETWORK}&category=${encodeURIComponent(category)}&limit=6&min_score=60`+ );+ if (!ok || !data?.items?.length) return;+ if (!$('#drBody')) return; // drawer closed while fetching++ const related = data.items.filter((it) => it.mint !== mint).slice(0, 3);+ if (!related.length) return;++ const TIER_META = { prime: { color: '#c084fc' }, strong: { color: '#34d399' }, lean: { color: '#fbbf24' }, watch: { color: '#94a3b8' }, avoid: { color: '#f87171' } };++ const html = `<div class="dr-sec" style="margin-top:16px">Related · ${esc(category)}</div>+ <div style="display:flex;flex-direction:column;gap:6px">+ ${related.map((r) => {+ const tc = (TIER_META[r.tier] || TIER_META.watch).color;+ const imgEl = r.image_uri+ ? `<img src="${esc(r.image_uri)}" alt="" style="width:28px;height:28px;border-radius:7px;object-fit:cover;flex:none;border:1px solid var(--line)" loading="lazy">`+ : `<div style="width:28px;height:28px;border-radius:7px;background:var(--line);display:grid;place-items:center;font:700 11px/1 var(--mono);color:var(--faint);flex:none">${esc((r.symbol||'?')[0])}</div>`;+ return `<button type="button" onclick="window.__oracleOpenRelated('${esc(r.mint)}')"+ style="display:flex;align-items:center;gap:10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px;cursor:pointer;text-align:left;width:100%;transition:background .12s"+ onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='var(--panel)'">+ ${imgEl}+ <span style="flex:1;min-width:0">+ <span style="font-weight:700;font-size:13px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(r.symbol || r.mint.slice(0,8))}</span>+ <span style="font-size:11px;color:var(--muted)">${esc(r.name||'')}</span>+ </span>+ <span style="display:flex;flex-direction:column;align-items:flex-end;flex:none">+ <span style="font:700 14px/1 var(--mono);color:${tc}">${r.score}</span>+ <span class="tierpill tp-${esc(r.tier)}" style="margin-top:3px;padding:1px 5px;font-size:9px">${esc(r.tier)}</span>+ </span>+ </button>`;+ }).join('')}+ </div>`;++ // Insert before the "Who's in" section.+ const body = $('#drBody');+ if (!body) return;+ const whosSecEl = Array.from(body.querySelectorAll('.dr-sec')).find((el) => el.textContent.startsWith("Who's in"));+ if (whosSecEl) {+ whosSecEl.insertAdjacentHTML('beforebegin', html);+ } else {+ body.insertAdjacentHTML('beforeend', html);+ }+}++window.__oracleOpenRelated = (mint) => openCoin(mint);++function whoRow(w) {+ const title = ARCH_TITLE[w.label] || 'Unproven';+function whoRow(w) {const title = ARCH_TITLE[w.label] || 'Unproven';const sub = [diff --git a/workers/oracle/agent-loop.js b/workers/oracle/agent-loop.jsindex 73ab1647e..63f72faa1 100644--- a/workers/oracle/agent-loop.js+++ b/workers/oracle/agent-loop.js@@ -9,7 +9,7 @@ import { sql } from '../../api/_lib/db.js';import { log } from './log.js';import { evaluateWatch } from '../../api/_lib/oracle/agent-eval.js';import { executeAction, agentBudget } from './executor.js';-import { alertAgentEntry, alertPersonalEntry, alertPersonalSignal, alertPersonalConvictionDrop } from '../../api/_lib/oracle/alerts.js';+import { alertAgentEntry, alertPersonalEntry, alertPersonalSignal, alertPersonalConvictionDrop, alertFollowers } from '../../api/_lib/oracle/alerts.js';// Module cursor — only consider verdicts scored since the last pass.let cursor = new Date(Date.now() - 60_000).toISOString();@@ -159,6 +159,16 @@ export async function actOnFreshCoins(cfg, coins) {network: cfg.network,}).catch(() => {});}+ // Follower fan-out: alert all subscribers of this agent.+ alertFollowers(watch.agent_id, {+ symbol: coin.symbol,+ mint: coin.mint,+ tier: coin.tier,+ score: coin.score,+ size_sol: decision.size,+ mode: watch.mode,+ network: cfg.network,+ }).catch(() => {});}}}