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
fix(mirror): filter the leaderboard by settled trades server side so a caller's window holds what it asked for
nirholas629fcbb94465
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 01e74b557..66a8d298f 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1727,6 +1727,11 @@ export const limits = {getLimiter('brain:chat:ip', { limit: 20, window: '1 m', critical: true }).limit(ip),// X (Twitter) memory seeding: 1 seed per agent per 6 hours.xSeed: (agentId) => getLimiter('memory:seed:x', { limit: 1, window: '6 h' }).limit(agentId),+ // Give the window back when a seed run stored nothing: X refused the read,+ // the token could not be refreshed, or the run produced no usable fact. The+ // agent's memories are untouched on all of those paths, so charging six hours+ // for them bills the owner for someone else's outage.+ xSeedRefund: (agentId) => refundLimit('memory:seed:x', { limit: 1, window: '6 h' }, agentId),// Consent-first GitHub memory seeding: reads the GitHub API and one LLM pass// per run. 1 seed per agent per 6 hours, matching the X lane.githubSeed: (agentId) =>diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.jsindex ffa944b1a..b4b01a3ca 100644--- a/api/agents/[id]/memory-seed-x.js+++ b/api/agents/[id]/memory-seed-x.js@@ -15,6 +15,9 @@//// Rate limit: 1 seed per agent per 6 hours, consumed only once the request is// authorized and consented, so a rejected call never burns the owner's window.+// A run that gets past that point and still stores nothing (X refused the read,+// the token would not refresh, no usable fact came back) hands the window back+// and leaves the existing memories exactly where they were.import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';@@ -166,6 +169,61 @@ function consentPayload(state) {};}+// ── Abandoning a charged run ─────────────────────────────────────────────────++// Every exit between "the window was charged" and "the new rows are written"+// comes through here. The run stored nothing, so the window goes back and the+// reply says so: the owner can act on the advice immediately instead of waiting+// out six hours for a failure that was never theirs.+async function abandonSeed(res, agentId, status, code, description, extra = {}) {+ const refunded = await limits.xSeedRefund(agentId).catch(() => false);+ return error(+ res,+ status,+ code,+ refunded+ ? `${description}. Your memories are unchanged and this attempt did not use up your six-hour window, so you can seed again as soon as it is fixed`+ : `${description}. Your memories are unchanged`,+ { ...extra, window_refunded: refunded },+ );+}++// Turn a non-ok X response into the honest reason the owner needs. X answers a+// revoked or narrowed connection with 401/403 and a throttled app with 429, and+// those want opposite actions (reconnect vs wait), so a single "X fetch failed"+// would send half of them the wrong way.+async function describeXFailure(response, what) {+ const detail = await response.text().catch(() => '');+ const reset = Number(response.headers?.get?.('x-rate-limit-reset'));+ if (response.status === 401 || response.status === 403) {+ return {+ status: 502,+ code: 'x_read_denied',+ description: `X would not let us read your ${what}, which usually means the connection was revoked or narrowed on X. Reconnect X and seed again`,+ extra: { x_status: response.status },+ };+ }+ if (response.status === 429) {+ const retryAt = Number.isFinite(reset) && reset > 0 ? new Date(reset * 1000).toISOString() : null;+ const minutes = retryAt ? Math.max(1, Math.ceil((reset * 1000 - Date.now()) / 60_000)) : null;+ return {+ status: 503,+ code: 'x_rate_limited',+ description: `X is rate limiting us and returned no ${what}${+ minutes ? `. X should accept the read again in about ${minutes} minute${minutes === 1 ? '' : 's'}` : ''+ }`,+ extra: { x_status: 429, retry_at: retryAt },+ };+ }+ console.warn(`[x-seed] ${what} read failed: ${response.status} ${detail.slice(0, 300)}`);+ return {+ status: 502,+ code: 'x_unavailable',+ description: `X did not return your ${what} and answered with ${response.status} instead`,+ extra: { x_status: response.status },+ };+}+async function countSeededMemories(agentId) {const [{ count }] = await sql`SELECT count(*)::int AS count FROM agent_memories@@ -272,21 +330,45 @@ async function handlePost(req, res, agentId) {const rl = await limits.xSeed(agentId);if (!rl.success) return rateLimited(res, rl, 'agent can only be re-seeded every 6 hours');- const accessToken = await getAccessToken(conn);+ // An expired access token that will not refresh is a dead connection, not a+ // seed the owner should be charged for.+ let accessToken;+ try {+ accessToken = await getAccessToken(conn);+ } catch (err) {+ console.warn('[x-seed] token refresh failed:', err?.message);+ return abandonSeed(+ res,+ agentId,+ 502,+ 'x_token_expired',+ 'your X sign-in could not be renewed, so nothing was read. Reconnect X and seed again',+ );+ }const profileRes = await fetch('https://api.twitter.com/2/users/me?user.fields=name,username,description,public_metrics',{ headers: { authorization: `Bearer ${accessToken}` } },);- if (!profileRes.ok) throw Object.assign(new Error('X profile fetch failed'), { status: 502 });+ if (!profileRes.ok) {+ const f = await describeXFailure(profileRes, 'profile');+ return abandonSeed(res, agentId, f.status, f.code, f.description, f.extra);+ }const { data: rawProfile } = await profileRes.json();- if (!rawProfile?.id) throw Object.assign(new Error('X profile unreadable'), { status: 502 });+ if (!rawProfile?.id) {+ return abandonSeed(res, agentId, 502, 'x_unavailable', 'X returned a profile we could not read');+ }// The account that consented must be the account being read.if (rawProfile.id !== consent.x_user_id) {- return error(res, 409, 'account_mismatch', 'consent was granted for a different X account', {- consent: consentPayload(consentState(consent, conn)),- });+ return abandonSeed(+ res,+ agentId,+ 409,+ 'account_mismatch',+ 'consent was granted for a different X account, so nothing was read. Review the consent screen for the account you are connected to now',+ { consent: consentPayload(consentState(consent, conn)) },+ );}const postsRes = await fetch(@@ -294,7 +376,10 @@ async function handlePost(req, res, agentId) {'&exclude=retweets,replies&tweet.fields=text,created_at',{ headers: { authorization: `Bearer ${accessToken}` } },);- if (!postsRes.ok) throw Object.assign(new Error('X posts fetch failed'), { status: 502 });+ if (!postsRes.ok) {+ const f = await describeXFailure(postsRes, 'posts');+ return abandonSeed(res, agentId, f.status, f.code, f.description, f.extra);+ }const postsJson = await postsRes.json();const seededAt = new Date().toISOString();@@ -305,6 +390,20 @@ async function handlePost(req, res, agentId) {seededAt,});+ // Nothing usable came back. The delete below would otherwise take the+ // previous batch out and put nothing in its place, so an account whose recent+ // timeline is all replies and reposts would wipe a good seed by re-seeding.+ if (!result.memories.length) {+ return abandonSeed(+ res,+ agentId,+ 502,+ 'seed_empty',+ 'your recent original posts and profile did not yield a single usable fact, so nothing was stored. Post something original, or widen what your profile says about you, and seed again',+ { posts_read: result.postsRead },+ );+ }+// Re-seeding replaces: the previous batch goes before the new one lands, so// the agent never carries two generations of facts about the same account.await sql`diff --git a/api/chat.js b/api/chat.jsindex 326dd6cb1..1eac8dcbd 100644--- a/api/chat.js+++ b/api/chat.js@@ -1690,7 +1690,7 @@ async function recallForChat(agentId, message, isOwner) {// the Anthropic route can put a prompt-cache breakpoint after it; `volatile`// (recalled memories + live viewer context) changes per message and stays// after the breakpoint. `text` is the joined form every other provider uses.-function buildSystemPrompt(ctx = {}, personaPrompt = null, recalled = [], installedSkills = []) {+export function buildSystemPrompt(ctx = {}, personaPrompt = null, recalled = [], installedSkills = []) {const loaded = ctx.modelName? `A model named "${ctx.modelName}" is loaded. Stats: ${fmt(ctx.vertices)} vertices, ${fmt(ctx.triangles)} triangles, ${fmt(ctx.materials)} materials, ${ctx.animations ?? 0} animations.`: 'No model is currently loaded in the viewer.';diff --git a/api/mirror/leaderboard.js b/api/mirror/leaderboard.jsindex 47c547dc9..a46ca8b32 100644--- a/api/mirror/leaderboard.js+++ b/api/mirror/leaderboard.js@@ -31,6 +31,14 @@ export default wrap(async function handler(req, res) {const network = NETWORKS.has(p.get('network')) ? p.get('network') : 'mainnet';const sort = SORTS.has(p.get('sort')) ? p.get('sort') : 'score';const limit = Math.min(50, Math.max(1, parseInt(p.get('limit') || '25', 10) || 25));+ // Callers that can only work with a realized track record (the Clip Director+ // mints a card from a closed round-trip, so an agent with none is unusable to+ // it) ask for `settled_min=1` instead of over-fetching and filtering client+ // side. That filter used to live in the caller, which silently broke: the+ // composite score does not correlate with having closed trades, so the only+ // eligible agent ranked below the caller's window and the page saw an empty+ // board. Filtering here makes the window hold what the caller asked for.+ const settledMin = Math.min(1000, Math.max(0, parseInt(p.get('settled_min') || '0', 10) || 0));// Realized stats per agent from closed sniper round-trips: the honest P&L// surface. LEFT JOIN follower counts + discretionary trade activity so an agent@@ -80,6 +88,7 @@ export default wrap(async function handler(req, res) {LEFT JOIN followers fl ON fl.agent_id = a.idWHERE a.deleted_at IS NULL AND a.is_public = trueAND (c.settled IS NOT NULL OR act.trades IS NOT NULL)+ AND COALESCE(c.settled, 0) >= ${settledMin}ORDER BY COALESCE(c.settled, 0) DESC,COALESCE(fl.followers, 0) DESC,COALESCE(act.trades, 0) DESC,@@ -88,17 +97,21 @@ export default wrap(async function handler(req, res) {`;res.setHeader?.('cache-control', 'public, max-age=30, s-maxage=60');- return json(res, 200, { data: { network, sort, leaders: rankLeaders(rows, { sort, limit }) } });+ return json(res, 200, {+ data: { network, sort, settled_min: settledMin, leaders: rankLeaders(rows, { sort, limit, settledMin }) },+ });});/*** Rank raw leaderboard rows. Pure: same rows in, same ranking out, so the 60s* edge cache never serves two different orderings of the same data.* @param {Array<object>} rows raw SQL rows (lamport sums arrive as strings)- * @param {{sort?: string, limit?: number}} opts+ * @param {{sort?: string, limit?: number, settledMin?: number}} opts settledMin drops+ * agents with fewer closed round-trips, so a caller that needs a realized+ * track record never has to filter (and mis-window) the ranking itself* @returns {Array<object>} ranked leaders, rank 1 first*/-export function rankLeaders(rows, { sort = 'score', limit = 25 } = {}) {+export function rankLeaders(rows, { sort = 'score', limit = 25, settledMin = 0 } = {}) {const leaders = rows.map((r) => {const pnlSol = lamToSol(r.pnl_lamports);const entrySol = lamToSol(r.entry_lamports);@@ -129,7 +142,7 @@ export function rankLeaders(rows, { sort = 'score', limit = 25 } = {}) {last_trade_at: r.last_trade_at || null,score,};- });+ }).filter((l) => l.settled >= settledMin);const cmp = COMPARATORS[sort] || COMPARATORS.score;// Tiebreak on agent_id so equal-scoring agents rank in one fixed order