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.

fix(onchain.js, prefs.js): implement caching in resolveOnChainAgent and add rate limiting for user preferences

nirholasde1d304361af
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index 42da6a8c7..479e2c8de 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -208,6 +208,9 @@ export const SERVER_CHAIN_META = {
const IPFS_GATEWAY = 'https://ipfs.io/ipfs/';
const AR_GATEWAY = 'https://arweave.net/';
+const _cache = new Map();
+const CACHE_TTL_MS = 10 * 60 * 1000;
+
/** @param {string} uri */
export function resolveURI(uri) {
if (!uri) return '';
@@ -250,6 +253,10 @@ export async function resolveOnChainAgent({
return _emptyResult(chainId, agentId, 'unsupported_chain');
}
+ const cacheKey = `${chainId}:${agentId}`;
+ const cached = _cache.get(cacheKey);
+ if (cached && cached.expiresAt > Date.now()) return cached.result;
+
const base = {
chainId,
chainName: meta.name,
@@ -310,6 +317,9 @@ export async function resolveOnChainAgent({
}
}
+ if (!base.error) {
+ _cache.set(cacheKey, { result: base, expiresAt: Date.now() + CACHE_TTL_MS });
+ }
return base;
}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 30d4d283c..c1cb0d96f 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -72,6 +72,7 @@ export const limits = {
getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),
upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),
avatarPatch: (userId) => getLimiter('avatar:patch', { limit: 20, window: '1 h' }).limit(userId),
+ prefsWrite: (userId) => getLimiter('prefs:write', { limit: 30, window: '1 h' }).limit(userId),
avatarRollback: (userId) =>
getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),
chatUser: (userId) => getLimiter('chat:user', { limit: 40, window: '1 m' }).limit(userId),
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 1d2903bb6..bb0ad7431 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -123,9 +123,12 @@ async function callFacilitator(network, path, body) {
}
}
if (!res.ok) {
+ // PayAI returns 400 with { isValid: false } for invalid payments —
+ // pass through so verifyPayment can emit a clean 402 to the caller.
+ if (path === '/verify' && data.isValid === false) return data;
throw new X402Error(
'facilitator_error',
- `facilitator ${path} ${res.status}: ${data.error || data.message || text.slice(0, 200)}`,
+ `facilitator ${path} ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,
502,
);
}
diff --git a/api/agents.js b/api/agents.js
index 0a74e721d..a14095ec2 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -110,6 +110,7 @@ async function handleGetOrCreateMe(req, res, auth) {
`;
}
+ await healStaleAvatarId(agent);
return json(res, 200, { agent: decorate(agent) });
} catch (err) {
// Any failure here (missing table, wallet generation error, missing env var)
@@ -182,6 +183,8 @@ export async function handleGetOne(req, res, id) {
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
+ await healStaleAvatarId(row);
+
// Public fields if not owner; full record if owner
const isOwner = auth?.userId === row.user_id;
return json(res, 200, { agent: decorate(row, isOwner) });
@@ -300,6 +303,21 @@ export async function handleWallet(req, res, id) {
// ── Helpers ────────────────────────────────────────────────────────────────
+// If the agent row's avatar_id references a deleted/missing avatar, null it out
+// in-place on the row and fire-and-forget a DB update so future reads are clean.
+async function healStaleAvatarId(row) {
+ if (!row?.avatar_id) return;
+ const [av] = await sql`
+ SELECT id FROM avatars WHERE id = ${row.avatar_id} AND deleted_at IS NULL LIMIT 1
+ `;
+ if (!av) {
+ const staleId = row.avatar_id;
+ row.avatar_id = null;
+ sql`UPDATE agent_identities SET avatar_id = NULL WHERE id = ${row.id} AND avatar_id = ${staleId}`
+ .catch((e) => console.error('[agents] healStaleAvatarId failed', e));
+ }
+}
+
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, source: 'session' };
diff --git a/api/agents/solana/[action].js b/api/agents/solana/[action].js
index 4b15c698b..3a7e4ede4 100644
--- a/api/agents/solana/[action].js
+++ b/api/agents/solana/[action].js
@@ -3,6 +3,7 @@ import {
handleAttestations,
handleAttestEvent,
handleCard,
+ handleMetadata,
handlePriceHistory,
handleRegisterPrep,
handleRegisterConfirm,
@@ -20,6 +21,7 @@ const DISPATCH = {
attestations: handleAttestations,
'attest-event': handleAttestEvent,
card: handleCard,
+ metadata: handleMetadata,
'price-history': handlePriceHistory,
'register-prep': handleRegisterPrep,
'register-confirm': handleRegisterConfirm,
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index 18ae713c6..96aedf187 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -155,6 +155,24 @@ export const handleAttestEvent = wrap(async (req, res) => {
return json(res, 202, { data: { deduped: true, status: 'in_progress' } });
});
+// ── solana-metadata ──────────────────────────────────────────────────────────
+
+export const handleMetadata = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const name = url.searchParams.get('name') || 'Agent';
+ const desc = url.searchParams.get('desc') || '';
+
+ return json(res, 200, {
+ name,
+ description: desc,
+ image: '',
+ attributes: [],
+ }, { 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' });
+});
+
// ── solana-card ───────────────────────────────────────────────────────────────
export const handleCard = wrap(async (req, res) => {
diff --git a/api/chat.js b/api/chat.js
index 9afaffa16..ab9f4f056 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -14,6 +14,8 @@ import { captureException } from './_lib/sentry.js';
import { sql } from './_lib/db.js';
import { z } from 'zod';
+export const maxDuration = 60;
+
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
const DEFAULT_MODEL = 'claude-sonnet-4-6';
const DEFAULT_MAX_TOKENS = 1024;
@@ -198,6 +200,7 @@ export default wrap(async (req, res) => {
system: buildSystemPrompt(body.context, personaPrompt),
messages,
tools: ACTION_TOOLS,
+ stream: true,
}),
});
} catch (err) {
@@ -222,9 +225,81 @@ export default wrap(async (req, res) => {
return error(res, status, 'upstream_error', `chat backend returned ${upstream.status}`);
}
- const data = await upstream.json();
- const { reply, actions } = normalize(data);
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ 'X-Accel-Buffering': 'no',
+ });
+
+ const reader = upstream.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let reply = '';
+ const actions = [];
+ const blocks = {};
+ let inputTokens = 0;
+ let outputTokens = 0;
+
+ function sendSSE(obj) {
+ res.write(`data: ${JSON.stringify(obj)}\n\n`);
+ }
+
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ const raw = line.slice(6).trim();
+ if (!raw) continue;
+ let evt;
+ try {
+ evt = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ if (evt.type === 'message_start') {
+ inputTokens = evt.message?.usage?.input_tokens ?? 0;
+ } else if (evt.type === 'content_block_start') {
+ const cb = evt.content_block;
+ blocks[evt.index] = { type: cb.type, name: cb.name, partialJson: '' };
+ } else if (evt.type === 'content_block_delta') {
+ const block = blocks[evt.index];
+ if (!block) continue;
+ if (evt.delta.type === 'text_delta') {
+ reply += evt.delta.text;
+ sendSSE({ type: 'chunk', text: evt.delta.text });
+ } else if (evt.delta.type === 'input_json_delta') {
+ block.partialJson += evt.delta.partial_json;
+ }
+ } else if (evt.type === 'content_block_stop') {
+ const block = blocks[evt.index];
+ if (block?.type === 'tool_use' && block.partialJson) {
+ try {
+ const input = JSON.parse(block.partialJson);
+ if (ACTION_NAMES.has(block.name)) {
+ actions.push({ type: block.name, ...input });
+ }
+ } catch {}
+ }
+ } else if (evt.type === 'message_delta') {
+ outputTokens = evt.usage?.output_tokens ?? 0;
+ }
+ }
+ }
+ } catch (err) {
+ captureException(err, { route: 'chat', stage: 'stream' });
+ sendSSE({ type: 'error', code: 'stream_error', message: 'stream interrupted' });
+ res.end();
+ return;
+ }
+
const latencyMs = Date.now() - started;
+ sendSSE({ type: 'done', reply: reply.trim(), actions, model });
+ res.end();
recordEvent({
userId: auth.userId,
@@ -234,14 +309,12 @@ export default wrap(async (req, res) => {
tool: model,
latencyMs,
meta: {
- input_tokens: data.usage?.input_tokens,
- output_tokens: data.usage?.output_tokens,
+ input_tokens: inputTokens,
+ output_tokens: outputTokens,
actions: actions.map((a) => a.type),
has_context: Boolean(body.context?.modelName),
},
});
-
- return json(res, 200, { reply, actions, model });
});
function buildSystemPrompt(ctx = {}, personaPrompt = null) {
@@ -270,18 +343,6 @@ function buildSystemPrompt(ctx = {}, personaPrompt = null) {
return lines.join('\n');
}
-function normalize(data) {
- let reply = '';
- const actions = [];
- for (const block of data.content || []) {
- if (block.type === 'text') {
- reply += block.text;
- } else if (block.type === 'tool_use' && ACTION_NAMES.has(block.name)) {
- actions.push({ type: block.name, ...(block.input || {}) });
- }
- }
- return { reply: reply.trim(), actions };
-}
async function resolveAuth(req) {
const session = await getSessionUser(req);
diff --git a/api/dashboard/prefs.js b/api/dashboard/prefs.js
index 2e53ea05d..04a83ae2d 100644
--- a/api/dashboard/prefs.js
+++ b/api/dashboard/prefs.js
@@ -12,8 +12,18 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { z } from 'zod';
-const MAX_BYTES = 16 * 1024; // hard ceiling on prefs blob size
+const MAX_BYTES = 16 * 1024;
+
+const prefsBody = z.object({
+ prefs: z.record(z.unknown()).refine(
+ (v) => JSON.stringify(v).length <= MAX_BYTES,
+ { message: `prefs exceed ${MAX_BYTES} bytes` },
+ ),
+});
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
@@ -30,20 +40,14 @@ export default wrap(async (req, res) => {
}
// POST — replace prefs
- const body = await readJson(req);
- const prefs = body?.prefs;
- if (!prefs || typeof prefs !== 'object' || Array.isArray(prefs)) {
- return error(res, 400, 'validation_error', 'prefs must be an object');
- }
+ const rl = await limits.prefsWrite(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const serialized = JSON.stringify(prefs);
- if (serialized.length > MAX_BYTES) {
- return error(res, 413, 'payload_too_large', `prefs exceed ${MAX_BYTES} bytes`);
- }
+ const { prefs } = parse(prefsBody, await readJson(req));
await sql`
INSERT INTO user_prefs (user_id, prefs, updated_at)
- VALUES (${auth.userId}, ${serialized}::jsonb, now())
+ VALUES (${auth.userId}, ${JSON.stringify(prefs)}::jsonb, now())
ON CONFLICT (user_id) DO UPDATE SET
prefs = EXCLUDED.prefs,
updated_at = now()
diff --git a/api/erc8004/register-confirm.js b/api/erc8004/register-confirm.js
index acd271d0e..824930a97 100644
--- a/api/erc8004/register-confirm.js
+++ b/api/erc8004/register-confirm.js
@@ -4,6 +4,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';
const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');
@@ -24,6 +25,8 @@ export default wrap(async (req, res) => {
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
if (bearer && !hasScope(bearer.scope, 'avatars:write'))
return error(res, 403, 'insufficient_scope', 'avatars:write scope required');
+ const rl = await limits.registerIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const body = parse(bodySchema, await readJson(req));
const chain = CHAIN_BY_ID[body.chainId];
if (!chain) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
diff --git a/vercel.json b/vercel.json
index 436664cf8..5b22b0b0f 100644
--- a/vercel.json
+++ b/vercel.json
@@ -44,6 +44,10 @@
"src": "/a/sol/([^/]+)/\\.well-known/agent-card\\.json",
"dest": "/api/agents/solana/[action]?action=card&asset=$1"
},
+ {
+ "src": "/api/agents/solana-metadata",
+ "dest": "/api/agents/solana/[action]?action=metadata"
+ },
{
"src": "/api/agents/solana-attestations",
"dest": "/api/agents/solana/[action]?action=attestations"