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(ops): crawl agent events on the Solana cron and alarm when the index goes stale
nirholasa1a008579449
diff --git a/api/_lib/ops/index-lag.js b/api/_lib/ops/index-lag.jsnew file mode 100644index 000000000..f5331e47d--- /dev/null+++ b/api/_lib/ops/index-lag.js@@ -0,0 +1,185 @@+// @ts-check+// Agent index freshness — how far behind the chains the platform's own index is.+//+// The indexers are crons: erc8004-crawl walks EVM registry block ranges every+// 15 minutes, solana-attestations-crawl walks Solana account signatures every+// 10 minutes. When one of them stops (a dead RPC lane, a cron that quietly+// 404s, a scheduler job deleted in a console) nothing about the platform looks+// broken. /agents keeps rendering, every endpoint keeps answering 200, and the+// directory just silently stops learning about the world. That failure mode has+// no reachability signature at all, which is exactly why it belongs on the+// status surface as a NUMBER rather than a green dot.+//+// Everything here is a cheap read of cursor tables the crawls already maintain.+// No RPC calls: asking twenty chains for their head block on a public status+// endpoint would be both slow and a great way to get rate-limited.+//+// Solana leads: its lag is the one that decides the verdict when both legs are+// behind, and it is reported first.++import { sql } from '../db.js';++/** Solana leg: worst per-agent cursor age tolerated before the index is stale. */+export const SOLANA_LAG_DEGRADED_MIN = 90;+export const SOLANA_LAG_DOWN_MIN = 360;+/** EVM leg: the crawl runs every 15 min across all chains, so it is slower. */+export const EVM_LAG_DEGRADED_MIN = 120;+export const EVM_LAG_DOWN_MIN = 480;++const QUERY_TIMEOUT_MS = 4_000;++const minutesSince = (ts) => (ts ? Math.round((Date.now() - new Date(ts).getTime()) / 60_000) : null);++function withTimeout(promise, ms) {+ return Promise.race([+ promise,+ new Promise((_, reject) => setTimeout(() => reject(new Error('index lag query timed out')), ms)),+ ]);+}++/**+ * Read the freshness of every indexer leg.+ *+ * @returns {Promise<{+ * solana: { medianLagMin: number|null, worstLagMin: number|null, agents: number, uncrawled: number, events: number },+ * evm: { lagMin: number|null, chains: number, staleChains: number, events: number },+ * lastEventAt: string|null,+ * lastIndexedAt: string|null,+ * }>}+ */+export async function readIndexLag() {+ const [solana, evm, totals] = await Promise.all([+ withTimeout(+ sql`+ SELECT+ count(*)::int AS agents,+ count(*) FILTER (WHERE cur.last_indexed_at IS NULL)::int AS uncrawled,+ max(extract(epoch FROM now() - cur.last_indexed_at) / 60)::int AS worst_lag_min,+ percentile_disc(0.5) WITHIN GROUP (+ ORDER BY extract(epoch FROM now() - cur.last_indexed_at) / 60+ )::int AS median_lag_min+ FROM agent_event_cursor cur+ WHERE cur.chain = 'solana'+ `,+ QUERY_TIMEOUT_MS,+ ),+ withTimeout(+ sql`+ SELECT+ count(*)::int AS chains,+ count(*) FILTER (+ WHERE updated_at < now() - (${EVM_LAG_DEGRADED_MIN} || ' minutes')::interval+ )::int AS stale_chains,+ max(extract(epoch FROM now() - updated_at) / 60)::int AS lag_min+ FROM erc8004_crawl_cursor+ `,+ QUERY_TIMEOUT_MS,+ ),+ withTimeout(+ sql`+ SELECT+ count(*) FILTER (WHERE chain = 'solana')::int AS solana_events,+ count(*) FILTER (WHERE chain = 'evm')::int AS evm_events,+ max(occurred_at) AS last_event_at,+ max(indexed_at) AS last_indexed_at+ FROM agent_onchain_events+ `,+ QUERY_TIMEOUT_MS,+ ),+ ]);++ const s = solana[0] || {};+ const e = evm[0] || {};+ const t = totals[0] || {};++ return {+ solana: {+ medianLagMin: s.median_lag_min ?? null,+ worstLagMin: s.worst_lag_min ?? null,+ agents: s.agents ?? 0,+ uncrawled: s.uncrawled ?? 0,+ events: t.solana_events ?? 0,+ },+ evm: {+ lagMin: e.lag_min ?? null,+ chains: e.chains ?? 0,+ staleChains: e.stale_chains ?? 0,+ events: t.evm_events ?? 0,+ },+ lastEventAt: t.last_event_at ? new Date(t.last_event_at).toISOString() : null,+ lastIndexedAt: t.last_indexed_at ? new Date(t.last_indexed_at).toISOString() : null,+ };+}++/**+ * Roll index freshness into a subsystem verdict for /status and /api/healthz.+ * Never throws: an unreadable index reports `unknown`, like every other check.+ *+ * @returns {Promise<{ name: string, label: string, status: string, detail: string,+ * hint?: string, metrics?: object }>}+ */+export async function gatherIndexLagHealth() {+ const base = { name: 'agent_index', label: 'Agent index freshness' };+ let lag;+ try {+ lag = await readIndexLag();+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'index lag unreadable' };+ }++ // Nothing crawled yet is a warming-up state, not a fault: a fresh database+ // or a just-applied migration lands here before the first cron tick.+ if (lag.solana.agents === 0 && lag.evm.chains === 0) {+ return {+ ...base,+ status: 'unknown',+ detail: 'no crawl cursors yet — indexers have not run since the index was created',+ hint: 'Wait one cron tick (solana-attestations-crawl every 10 min, erc8004-crawl every 15 min).',+ metrics: lag,+ };+ }++ const solStatus = legStatus(lag.solana.medianLagMin, SOLANA_LAG_DEGRADED_MIN, SOLANA_LAG_DOWN_MIN);+ const evmStatus = legStatus(lag.evm.lagMin, EVM_LAG_DEGRADED_MIN, EVM_LAG_DOWN_MIN);+ const status = worst(solStatus, evmStatus);++ const solPart =+ lag.solana.agents === 0+ ? 'Solana: no agents queued'+ : `Solana: ${fmt(lag.solana.medianLagMin)} median lag across ${lag.solana.agents} agents` ++ (lag.solana.uncrawled ? `, ${lag.solana.uncrawled} never crawled` : '');+ const evmPart =+ lag.evm.chains === 0+ ? 'EVM: no chain cursors'+ : `EVM: ${fmt(lag.evm.lagMin)} worst lag across ${lag.evm.chains} chains` ++ (lag.evm.staleChains ? `, ${lag.evm.staleChains} stale` : '');+ const eventPart = `${lag.solana.events + lag.evm.events} events indexed`;++ const detail = `${solPart}. ${evmPart}. ${eventPart}.`;+ const hint =+ status === 'ok'+ ? undefined+ : 'Check the crawl crons: /api/cron/solana-attestations-crawl and /api/cron/erc8004-crawl. A stale cursor means the job is failing or no longer scheduled.';++ return { ...base, status, detail, ...(hint ? { hint } : {}), metrics: lag };+}++function legStatus(lagMin, degradedAt, downAt) {+ if (lagMin == null) return 'unknown';+ if (lagMin >= downAt) return 'down';+ if (lagMin >= degradedAt) return 'degraded';+ return 'ok';+}++const RANK = { down: 3, degraded: 2, unknown: 1, ok: 0 };+function worst(a, b) {+ return RANK[a] >= RANK[b] ? a : b;+}++function fmt(min) {+ if (min == null) return 'unknown';+ if (min < 60) return `${min}m`;+ const h = Math.floor(min / 60);+ const m = min % 60;+ return m ? `${h}h${m}m` : `${h}h`;+}diff --git a/api/_lib/ops/subsystem-health.js b/api/_lib/ops/subsystem-health.jsindex f8cf4b73c..4304f8d5d 100644--- a/api/_lib/ops/subsystem-health.js+++ b/api/_lib/ops/subsystem-health.js@@ -37,6 +37,7 @@ import { rateLimiterHealth } from '../rate-limit.js';import { checkRingInvariants } from '../x402/ring-allowlist.js';import { gatherX402SettleHealth } from './x402-settle-health.js';import { gatherForgeHealth } from './forge-health-sensor.js';+import { gatherIndexLagHealth } from './index-lag.js';import { describeSolvency } from '../sniper-solvency.js';const DB_PING_TIMEOUT_MS = 2_500;@@ -547,6 +548,11 @@ export async function gatherSubsystemHealth({ probeDb = true } = {}) {// Generation SUCCESS RATE, not just lane liveness — reads forge_creations.// DB-gated like the settle sensor; skipped-DB callers get `unknown`.probeDb ? gatherForgeHealth() : Promise.resolve({ name: 'forge_generation', label: 'Forge 3D generation', status: 'unknown', detail: 'forge read skipped' }),+ // Agent index freshness. A dead crawl cron has NO reachability signature:+ // every surface still answers 200 while the directory quietly stops+ // learning about the chains. Reads cursor tables only, so it shares the+ // probeDb gate with the other DB-backed sensors.+ probeDb ? gatherIndexLagHealth() : Promise.resolve({ name: 'agent_index', label: 'Agent index freshness', status: 'unknown', detail: 'index read skipped' }),checkWorld(),Promise.resolve(checkX402Config()),probeDb ? checkSniper() : Promise.resolve({ name: 'sniper', label: 'Sniper worker (Cloud Run)', status: 'unknown', detail: 'probe skipped' }),diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 4b7675f40..3fc6cf642 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -3164,6 +3164,14 @@ async function handleSolanaAttestEventCleanup(req, res) {// ═══════════════════════════════════════════════════════════════════════════const SOL_ATTEST_PER_RUN_MAX = 50; // bound RPC fan-out per cron tick+// Agents whose full event history (registration, token launch, delegation,+// transfer, metadata) is walked per tick. Separate from the attestation budget+// because this half covers the external registry directory too, which is two+// orders of magnitude larger than the platform's own Solana agents.+const SOL_EVENT_PER_RUN_MAX = 40;+// Hard wall-clock budget for the event half, leaving the attestation half its+// own share of the function's 300s ceiling.+const SOL_EVENT_BUDGET_MS = 120_000;async function handleSolanaAttestationsCrawl(req, res) {if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;@@ -3187,7 +3195,7 @@ async function handleSolanaAttestationsCrawl(req, res) {limit ${SOL_ATTEST_PER_RUN_MAX}`;- const report = { agents: [], errors: [] };+ const report = { agents: [], errors: [], events: null };for (const row of agents) {try {const r = await crawlAgentAttestations({@@ -3201,9 +3209,55 @@ async function handleSolanaAttestationsCrawl(req, res) {}}+ // Second half: the cross-chain event index. Draws its batch from the+ // platform's own agents AND the external Solana registry directory, which+ // had no event coverage at all before this ran.+ report.events = await solanaEventSweep();+return json(res, 200, report);}+async function solanaEventSweep() {+ const { crawlAgentEvents, markAgentEventError, nextAgentBatch } = await import(+ '../_lib/solana-agent-events.js'+ );++ const startedAt = Date.now();+ const summary = { agents: 0, scanned: 0, inserted: 0, rejected: 0, failed: 0, truncated: false };++ let batch;+ try {+ batch = await nextAgentBatch({ limit: SOL_EVENT_PER_RUN_MAX });+ } catch (err) {+ return { ...summary, error: err.message || String(err) };+ }++ for (const row of batch) {+ if (Date.now() - startedAt > SOL_EVENT_BUDGET_MS) {+ summary.truncated = true;+ break;+ }+ try {+ const r = await crawlAgentEvents({ agentRef: row.agent_ref, network: row.network });+ summary.agents += 1;+ summary.scanned += r.scanned;+ summary.inserted += r.inserted;+ summary.rejected += r.rejected;+ } catch (err) {+ summary.failed += 1;+ // Stamp the cursor even on failure so one permanently unreadable+ // account cannot hold the oldest-first queue head forever.+ await markAgentEventError({+ agentRef: row.agent_ref,+ network: row.network,+ error: err.message || String(err),+ }).catch(() => {});+ }+ }++ return summary;+}+// ═══════════════════════════════════════════════════════════════════════════// process-subscriptions// ═══════════════════════════════════════════════════════════════════════════diff --git a/api/status.js b/api/status.jsindex 139f3ca66..a1f030a5c 100644--- a/api/status.js+++ b/api/status.js@@ -195,6 +195,10 @@ export default wrap(async (req, res) => {status: s.status,detail: s.detail ?? null,hint: s.hint ?? null,+ // Structured numbers for the checks that carry them (agent+ // index lag). Integrators reading this feed should not have+ // to parse a human sentence to get the lag in minutes.+ ...(s.metrics ? { metrics: s.metrics } : {}),})),}: null,diff --git a/pages/status.html b/pages/status.htmlindex 4495b9fdf..f42d77125 100644--- a/pages/status.html+++ b/pages/status.html@@ -492,6 +492,34 @@const esc = (s) =>String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);+ // Minutes → a compact human duration for the metric pills.+ const lagWord = (min) => {+ if (min == null) return 'no data';+ if (min < 60) return `${min}m`;+ const h = Math.floor(min / 60);+ const m = min % 60;+ return m ? `${h}h ${m}m` : `${h}h`;+ };++ // Structured numbers a subsystem chose to publish (currently the agent+ // index lag). Rendered as pills so the freshness of the on-chain index is+ // a figure you can read at a glance, not prose buried in the detail line.+ function subMetrics(m) {+ if (!m || !m.solana || !m.evm) return '';+ const pills = [+ ['Solana lag', lagWord(m.solana.medianLagMin)],+ ['Solana agents', String(m.solana.agents)],+ ['EVM lag', lagWord(m.evm.lagMin)],+ ['Events indexed', String((m.solana.events || 0) + (m.evm.events || 0))],+ ];+ return `<span class="st-sub-metrics">${pills+ .map(+ ([k, v]) =>+ `<span class="st-metric"><span class="st-metric-k">${esc(k)}</span><b class="st-metric-v">${esc(v)}</b></span>`,+ )+ .join('')}</span>`;+ }+function renderSubsystems(subs) {// Older API shapes / warming-up omit the block — keep it hidden then.if (!subs || !Array.isArray(subs.items) || subs.items.length === 0) {@@ -510,6 +538,7 @@<span class="st-sub-name">${esc(it.label || it.name)}</span><span class="st-sub-state">${esc(word)}</span>${it.detail ? `<span class="st-sub-detail">${esc(it.detail)}</span>` : ''}+ ${subMetrics(it.metrics)}${showHint ? `<span class="st-sub-hint">${esc(it.hint)}</span>` : ''}</div>`;})