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: add pumpfun-feed and pumpfun-metadata handlers with updated routing in vercel.json
nirholas8c5c6306c4af
diff --git a/api/agents/[id]/actions.js b/api/agents/[id]/actions.jsdeleted file mode 100644index 6531591af..000000000--- a/api/agents/[id]/actions.js+++ /dev/null@@ -1,94 +0,0 @@-/**- * GET /api/agents/:id/actions?limit=100&cursor=<timestamp>- * -------- * Paginated signed action log for an agent. Verifies EIP-191 signatures.- * Auth: caller must own the agent OR agent visibility must be 'public'.- */--import { verifyMessage } from 'ethers';-import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, error, wrap } from '../../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');-- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];- if (!id) return error(res, 400, 'invalid_request', 'agent id required');-- // Auth: session or bearer- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- const userId = session?.id ?? bearer?.userId;-- // Check agent exists and access- const [agent] = await sql`- SELECT id, user_id, name, wallet_address- FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');-- // Auth check: must be owner (agents don't have visibility field yet)- if (!userId || agent.user_id !== userId) {- return error(res, 403, 'forbidden', 'not authorized to view this agent');- }-- const url = new URL(req.url, 'http://x');- const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);- const cursor = url.searchParams.get('cursor'); // ISO timestamp cursor-- // Query actions ordered by timestamp DESC- const actions = cursor- ? await sql`- SELECT id, type, payload, source_skill, signature, signer_address, created_at- FROM agent_actions- WHERE agent_id = ${id} AND created_at < ${cursor}- ORDER BY created_at DESC- LIMIT ${limit + 1}- `- : await sql`- SELECT id, type, payload, source_skill, signature, signer_address, created_at- FROM agent_actions- WHERE agent_id = ${id}- ORDER BY created_at DESC- LIMIT ${limit + 1}- `;-- const hasMore = actions.length > limit;- const trimmed = hasMore ? actions.slice(0, limit) : actions;- const nextCursor = hasMore ? trimmed[trimmed.length - 1].created_at.toISOString() : null;-- // Verify signatures for each action- const decorated = trimmed.map((row) => {- let verified = null;- if (row.signature && row.signer_address && row.payload) {- try {- const message = JSON.stringify(row.payload) + row.created_at.toISOString();- const recovered = verifyMessage(message, row.signature);- verified = recovered.toLowerCase() === row.signer_address.toLowerCase();- } catch {- verified = false;- }- }- return {- id: String(row.id),- type: row.type,- payload: row.payload,- sourceSkill: row.source_skill,- timestamp: row.created_at.toISOString(),- signature: row.signature || null,- signer: row.signer_address || null,- verified,- };- });-- // Cache: private, 10 seconds- res.setHeader('Cache-Control', 'private, max-age=10');-- return json(res, 200, {- actions: decorated,- nextCursor,- });-});diff --git a/api/agents/[id]/animations.js b/api/agents/[id]/animations.jsdeleted file mode 100644index 9c0e369c8..000000000--- a/api/agents/[id]/animations.js+++ /dev/null@@ -1,83 +0,0 @@-// PUT /api/agents/:id/animations — owner-only; atomically replaces meta.animations-//-// Uses jsonb_set so the rest of `meta` (including encrypted_wallet_key) is never-// read by the client or overwritten. The generic PUT /api/agents/:id handler-// overwrites `meta` wholesale which would leak/clobber sibling fields — this-// endpoint exists specifically to avoid that.--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 { z } from 'zod';--const animationEntrySchema = z.object({- name: z.string().trim().min(1).max(60),- url: z- .string()- .trim()- .min(1)- .max(2048)- .refine(- (u) => /^(https?|ipfs|ar):\/\//.test(u) || u.startsWith('/') || /^u\//.test(u),- 'url must be http, https, ipfs, ar, a root-relative path, or a storage key',- ),- loop: z.boolean().default(true),- clipName: z.string().trim().max(120).optional(),- source: z.enum(['mixamo', 'preset', 'custom']),- addedAt: z.string().optional(),-});--const bodySchema = z.object({- animations: z.array(animationEntrySchema).max(30),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'PUT,OPTIONS', credentials: true })) return;- if (!method(req, res, ['PUT'])) return;-- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];- if (!id) return error(res, 400, 'invalid_request', 'agent id required');-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');-- const [existing] = await sql`- SELECT id, user_id FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- `;- if (!existing) return error(res, 404, 'not_found', 'agent not found');- if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');-- let parsed;- try {- parsed = bodySchema.parse(await readJson(req));- } catch (err) {- if (err.name === 'ZodError') {- return error(res, 400, 'validation_error', err.errors[0]?.message || 'invalid body', {- fields: err.errors,- });- }- throw err;- }-- await sql`- UPDATE agent_identities- SET meta = jsonb_set(- COALESCE(meta, '{}'::jsonb),- '{animations}',- ${JSON.stringify(parsed.animations)}::jsonb,- true- )- WHERE id = ${id}- `;-- return json(res, 200, { animations: parsed.animations });-});--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}diff --git a/api/agents/[id]/embed-policy.js b/api/agents/[id]/embed-policy.jsdeleted file mode 100644index 6e5be3212..000000000--- a/api/agents/[id]/embed-policy.js+++ /dev/null@@ -1,63 +0,0 @@-// GET /api/agents/:id/embed-policy — public; returns { policy } (extended normalized shape)-// PUT /api/agents/:id/embed-policy — owner-only; accepts extended or legacy shape-// DELETE /api/agents/:id/embed-policy — owner-only; clears the policy--import { getSessionUser } from '../../_lib/auth.js';-import { sql } from '../../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { readEmbedPolicy, validateEmbedPolicy } from '../../_lib/embed-policy.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;-- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];- if (!id) return error(res, 400, 'invalid_request', 'agent id required');-- if (req.method === 'GET') {- const policy = await readEmbedPolicy(id);- if (policy === null) {- // Check if agent actually exists vs column missing- const [row] = await sql`- SELECT id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL- `;- if (!row) return error(res, 404, 'not_found', 'agent not found');- }- return json(res, 200, { policy: policy ?? null });- }-- const session = await getSessionUser(req);- if (!session) return error(res, 401, 'unauthorized', 'sign in required');-- const [existing] = await sql`- SELECT id, user_id FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- `;- if (!existing) return error(res, 404, 'not_found', 'agent not found');- if (existing.user_id !== session.id) return error(res, 403, 'forbidden', 'not your agent');-- if (req.method === 'DELETE') {- await sql`UPDATE agent_identities SET embed_policy = NULL WHERE id = ${id}`;- return json(res, 200, { policy: null });- }-- let normalized;- try {- normalized = validateEmbedPolicy(await readJson(req));- } catch (err) {- if (err.name === 'ZodError') {- return error(res, 400, 'validation_error', err.errors[0]?.message || 'invalid policy', {- fields: err.errors,- });- }- throw err;- }-- const [updated] = await sql`- UPDATE agent_identities- SET embed_policy = ${JSON.stringify(normalized)}::jsonb- WHERE id = ${id}- RETURNING embed_policy- `;- return json(res, 200, { policy: updated.embed_policy });-});diff --git a/api/agents/[id]/manifest.js b/api/agents/[id]/manifest.jsdeleted file mode 100644index a02fff247..000000000--- a/api/agents/[id]/manifest.js+++ /dev/null@@ -1,96 +0,0 @@-/**- * GET /api/agents/:id/manifest- *- * Public, canonical agent manifest JSON. Served as the off-chain `agentURI`- * on ERC-8004 registries when the user opts for `https://` over `ipfs://`.- * Stable URL shape so on-chain tokens don't break when the underlying- * record is edited.- *- * No auth — intentionally public so any consumer (block explorer, Lobehub- * plugin, third-party renderer) can resolve the manifest.- */--import { sql } from '../../_lib/db.js';-import { resolveAvatarUrl } from '../../_lib/avatars.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;- if (!method(req, res, ['GET'])) return;-- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').slice(-2, -1)[0];- if (!id || !/^[0-9a-f-]{36}$/i.test(id)) {- return error(res, 400, 'invalid_request', 'agent id required');- }-- const [row] = await sql`- select- a.id, a.name, a.description, a.avatar_id, a.skills, a.meta,- a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid,- a.created_at,- av.id as avatar_db_id, av.storage_key, av.content_type- from agent_identities a- left join avatars av on av.id = a.avatar_id and av.deleted_at is null- where a.id = ${id} and a.deleted_at is null- limit 1- `;-- if (!row) return error(res, 404, 'not_found', 'agent not found');-- let bodyUri = '';- if (row.avatar_db_id) {- try {- const urlInfo = await resolveAvatarUrl({- storage_key: row.storage_key,- visibility: 'public',- });- bodyUri = urlInfo?.url || '';- } catch {- /* fall through with empty body uri */- }- }-- const origin = _origin(req);-- const manifest = {- $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',- spec: 'agent-manifest/0.1',- id: row.id,- name: row.name || 'Agent',- description: row.description || '',- image: '',- tags: Array.isArray(row.meta?.tags) ? row.meta.tags : [],- body: bodyUri ? { uri: bodyUri, format: row.content_type || 'gltf-binary' } : undefined,- skills: Array.isArray(row.skills) ? row.skills : [],- homeUrl: `${origin}/agent/${row.id}`,- // Surface registrations array so consumers can find every chain this- // agent lives on. For now we only have a single canonical record on- // agent_identities; a junction table is the next step.- registrations:- row.chain_id && row.erc8004_agent_id- ? [- {- agentRegistry: `eip155:${row.chain_id}:${row.erc8004_registry}`,- agentId: row.erc8004_agent_id,- },- ]- : [],- createdAt: row.created_at,- };-- // Cache moderately — manifest changes when the user edits name/desc, but- // it's safe to serve stale for a few minutes. The headers arg here wins- // over the helper's default `cache-control: no-store`.- return json(res, 200, manifest, {- 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400',- 'access-control-allow-origin': '*',- });-});--function _origin(req) {- const env = process.env.PUBLIC_APP_ORIGIN;- if (env) return env.replace(/\/$/, '');- const proto = req.headers['x-forwarded-proto'] || 'https';- const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';- return `${proto}://${host}`;-}diff --git a/api/agents/[id]/sign.js b/api/agents/[id]/sign.jsdeleted file mode 100644index 3c6962f9a..000000000--- a/api/agents/[id]/sign.js+++ /dev/null@@ -1,71 +0,0 @@-// POST /api/agents/:id/sign — owner-only; signs an arbitrary message with the-// agent's server-held wallet. The key is encrypted at rest with JWT_SECRET--// derived AES-GCM and decrypted in-memory just long enough to sign.-//-// Request: { message: string, kind?: 'personal'|'eip191' (default personal) }-// Response: { address, signature }--import { z } from 'zod';-import { Wallet } from 'ethers';-import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { recoverAgentKey } from '../../_lib/agent-wallet.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';--const signBody = z.object({- // EIP-191 personal messages — what wallets sign today. Keep the upper bound- // generous for signed action JSON / SIWE-like payloads the agent emits.- message: z.string().min(1).max(8192),- kind: z.enum(['personal']).default('personal'),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];- if (!id) return error(res, 400, 'invalid_request', 'agent id required');-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');-- // Rate limit — signing decrypts a private key; keep the budget tight.- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many sign requests');-- const [row] = await sql`- SELECT id, user_id, wallet_address, meta- FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- LIMIT 1- `;- if (!row) return error(res, 404, 'not_found', 'agent not found');- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');-- const encryptedKey = row.meta?.encrypted_wallet_key;- if (!encryptedKey) return error(res, 409, 'no_wallet', 'agent has no server wallet');-- const body = parse(signBody, await readJson(req));-- let signature;- try {- const pkHex = await recoverAgentKey(encryptedKey);- const wallet = new Wallet(pkHex);- signature = await wallet.signMessage(body.message);- } catch (e) {- console.error('[agents/sign] signing failed', e);- return error(res, 500, 'sign_failed', 'could not sign message');- }-- return json(res, 200, { address: row.wallet_address, signature });-});--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}diff --git a/api/agents/[id]/usage.js b/api/agents/[id]/usage.jsdeleted file mode 100644index edffaf224..000000000--- a/api/agents/[id]/usage.js+++ /dev/null@@ -1,59 +0,0 @@-// GET /api/agents/:id/usage — owner-only usage stats for the LLM proxy.-// Returns current-month call count, quota, and a 30-day daily breakdown.--import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';-import { readEmbedPolicy } from '../../_lib/embed-policy.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;-- const session = await getSessionUser(req);- if (!session) return error(res, 401, 'unauthorized', 'sign in required');-- const url = new URL(req.url, 'http://x');- const agentId = url.searchParams.get('id');- if (!agentId) return error(res, 400, 'validation_error', 'id query param required');-- // Verify caller owns the agent- const [agent] = await sql`- SELECT id FROM agent_identities- WHERE id = ${agentId} AND user_id = ${session.id} AND deleted_at IS NULL- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');-- // Read embed policy for the monthly quota value- const policy = await readEmbedPolicy(agentId);- const monthlyQuota = policy?.brain?.monthly_quota ?? null;-- // Current-month total- const [monthRow] = await sql`- SELECT COUNT(*)::int AS total- FROM usage_events- WHERE agent_id = ${agentId}- AND kind = 'llm'- AND created_at >= date_trunc('month', now())- `;-- // 30-day daily breakdown- const dailyRows = await sql`- SELECT- date_trunc('day', created_at)::date AS day,- COUNT(*)::int AS calls- FROM usage_events- WHERE agent_id = ${agentId}- AND kind = 'llm'- AND created_at >= now() - interval '30 days'- GROUP BY 1- ORDER BY 1- `;-- return json(res, 200, {- agentId,- monthlyQuota,- currentMonthCalls: monthRow?.total ?? 0,- dailyBreakdown: dailyRows.map((r) => ({ day: r.day, calls: r.calls })),- });-});diff --git a/api/agents/pumpfun-feed.js b/api/agents/pumpfun-feed.jsdeleted file mode 100644index 1cb5ac70f..000000000--- a/api/agents/pumpfun-feed.js+++ /dev/null@@ -1,122 +0,0 @@-/**- * GET /api/agents/pumpfun-feed- * ---------------------------------- * Live pump.fun activity feed. Streams `mint`, `graduation`, and `claim`- * events as Server-Sent Events.- *- * Auth: session OR bearer (scope `mcp` or `profile`).- * Query: ?kind=all|mint|graduation|claims (default all)- * ?minTier=notable|influencer|mega (claim filter, optional)- *- * Sources (in priority order):- * 1. pump.fun public WebSocket (always available — mint + graduation)- * 2. Redis/pumpfun-bot (optional — adds claim events when configured)- */--import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, method, error, wrap } from '../_lib/http.js';-import { limits } from '../_lib/rate-limit.js';-import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';-import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';--const POLL_MS = 4000;-const MAX_DURATION_MS = 90_000;-const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;-- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');- if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {- return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');- }-- const userId = session?.id ?? bearer.userId;- const rl = await limits.mcpUser(String(userId));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many feed connections');-- const url = new URL(req.url, 'http://x');- const kind = url.searchParams.get('kind') || 'all';- const minTierParam = url.searchParams.get('minTier');- const minTier = TIER_RANK[minTierParam] || 0;-- res.statusCode = 200;- res.setHeader('content-type', 'text/event-stream; charset=utf-8');- res.setHeader('cache-control', 'no-store');- res.setHeader('connection', 'keep-alive');- res.setHeader('x-accel-buffering', 'no');- res.flushHeaders?.();-- const started = Date.now();- let active = true;- req.on('close', () => { active = false; });-- const wsAbort = new AbortController();- req.on('close', () => wsAbort.abort());-- // Event queue fed by the pump.fun WebSocket- const queue = [];- const wsKind = kind === 'claims' ? 'graduation' : kind; // claims come from bot only- const stopWs = connectPumpFunFeed({- kind: wsKind,- signal: wsAbort.signal,- onEvent: ({ kind: evKind, data }) => {- if (active) queue.push({ evKind, data });- },- });-- writeSse(res, 'open', { kind, minTier: minTierParam || null, source: 'websocket' });-- // Optional: also poll Redis/bot for claim events if configured- const seen = new Set();- let lastSig = null;-- const tickClaims = pumpfunBotEnabled()- ? async () => {- if (kind !== 'claims' && kind !== 'all') return;- const r = await pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 });- if (!r.ok) return;- const items = Array.isArray(r.data) ? r.data : r.data?.items || [];- for (const ev of items) {- const id = ev.tx_signature || ev.signature || ev.id;- if (!id || seen.has(id)) continue;- seen.add(id);- if (minTier && TIER_RANK[(ev.tier || '').toLowerCase()] < minTier) continue;- lastSig = id;- writeSse(res, 'claim', ev);- }- }- : null;-- while (active && Date.now() - started < MAX_DURATION_MS) {- // Drain WebSocket event queue- while (queue.length > 0 && active) {- const { evKind, data } = queue.shift();- writeSse(res, evKind, data);- }-- // Pull claim events from Redis/bot if available- if (tickClaims) {- try { await tickClaims(); } catch {}- }-- writeSse(res, 'ping', { t: Date.now() });- await sleep(POLL_MS);- }-- stopWs();- writeSse(res, 'close', { reason: 'duration_limit' });- res.end();-});--function writeSse(res, event, data) {- res.write(`event: ${event}\n`);- res.write(`data: ${JSON.stringify(data)}\n\n`);-}--function sleep(ms) {- return new Promise((r) => setTimeout(r, ms));-}diff --git a/api/agents/pumpfun-metadata.js b/api/agents/pumpfun-metadata.jsdeleted file mode 100644index 5be85b9d4..000000000--- a/api/agents/pumpfun-metadata.js+++ /dev/null@@ -1,70 +0,0 @@-/**- * GET /api/agents/pumpfun-metadata?id=<agent_id>- *- * Returns Metaplex-compatible token metadata JSON for a three.ws agent so it- * can be used as the `uri` field for a pump.fun token mint. The agent's GLB- * + name + bio become the token's identity.- *- * Public, cacheable, read-only.- */--import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { env } from '../_lib/env.js';--export default 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 id = url.searchParams.get('id');- if (!id) return error(res, 400, 'validation_error', 'id required');-- const [a] = await sql`- select id, name, description, avatar_id, meta, wallet_address- from agent_identities- where id = ${id} and deleted_at is null limit 1- `;- if (!a) return error(res, 404, 'not_found', 'agent not found');-- const origin = env.APP_ORIGIN;- const image = a.meta?.image_url || `${origin}/api/agents/${a.id}/og`;- const animation = a.avatar_id ? `${origin}/api/avatars/${a.avatar_id}/glb` : null;-- const metadata = {- name: a.name,- symbol: deriveSymbol(a.name),- description:- a.description ||- `${a.name} is a 3D AI agent on three.ws with onchain identity and signed action history.`,- image,- animation_url: animation,- external_url: `${origin}/agent/${a.id}`,- attributes: [- { trait_type: 'platform', value: 'three.ws' },- { trait_type: 'agent_id', value: a.id },- ...(a.wallet_address ? [{ trait_type: 'owner', value: a.wallet_address }] : []),- ],- properties: {- category: 'video',- files: [- ...(animation- ? [{ uri: animation, type: 'model/gltf-binary' }]- : []),- { uri: image, type: 'image/png' },- ],- },- };-- return json(res, 200, metadata, {- 'cache-control': 'public, max-age=300',- 'access-control-allow-origin': '*',- });-});--function deriveSymbol(name) {- const cleaned = String(name || 'AGENT')- .toUpperCase()- .replace(/[^A-Z0-9]/g, '');- return cleaned.slice(0, 10) || 'AGENT';-}diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.jsindex f58b7d6f3..0563676ce 100644--- a/api/agents/pumpfun.js+++ b/api/agents/pumpfun.js@@ -22,6 +22,11 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';export default wrap(async (req, res) => {+ // Dispatch pumpfun-feed and pumpfun-metadata via _handler param (set by vercel.json rewrite)+ const _handler = req.query?._handler;+ if (_handler === 'feed') return handleFeed(req, res);+ if (_handler === 'metadata') return handleMetadata(req, res);+if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;@@ -82,3 +87,91 @@ export default wrap(async (req, res) => {function clamp(n, lo, hi) {return Math.max(lo, Math.min(hi, n));}++// ── pumpfun-feed (SSE) ────────────────────────────────────────────────────────++import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';+const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };++async function handleFeed(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');+ const userId = session?.id ?? bearer.userId;+ const rl = await limits.mcpUser(String(userId));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many feed connections');+ const url = new URL(req.url, 'http://x');+ const kind = url.searchParams.get('kind') || 'all';+ const minTierParam = url.searchParams.get('minTier');+ const minTier = TIER_RANK[minTierParam] || 0;+ res.statusCode = 200;+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.setHeader('connection', 'keep-alive');+ res.setHeader('x-accel-buffering', 'no');+ res.flushHeaders?.();+ const started = Date.now();+ let active = true;+ req.on('close', () => { active = false; });+ const wsAbort = new AbortController();+ req.on('close', () => wsAbort.abort());+ const queue = [];+ const wsKind = kind === 'claims' ? 'graduation' : kind;+ const stopWs = connectPumpFunFeed({ kind: wsKind, signal: wsAbort.signal, onEvent: ({ kind: evKind, data }) => { if (active) queue.push({ evKind, data }); } });+ _writeSse(res, 'open', { kind, minTier: minTierParam || null, source: 'websocket' });+ const seen = new Set();+ let lastSig = null;+ const tickClaims = pumpfunBotEnabled() ? async () => {+ if (kind !== 'claims' && kind !== 'all') return;+ const r = await pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 });+ if (!r.ok) return;+ const items = Array.isArray(r.data) ? r.data : r.data?.items || [];+ for (const ev of items) {+ const id = ev.tx_signature || ev.signature || ev.id;+ if (!id || seen.has(id)) continue;+ seen.add(id);+ if (minTier && TIER_RANK[(ev.tier || '').toLowerCase()] < minTier) continue;+ lastSig = id;+ _writeSse(res, 'claim', ev);+ }+ } : null;+ while (active && Date.now() - started < 90_000) {+ while (queue.length > 0 && active) { const { evKind, data } = queue.shift(); _writeSse(res, evKind, data); }+ if (tickClaims) { try { await tickClaims(); } catch {} }+ _writeSse(res, 'ping', { t: Date.now() });+ await new Promise((r) => setTimeout(r, 4000));+ }+ stopWs();+ _writeSse(res, 'close', { reason: 'duration_limit' });+ res.end();+}+function _writeSse(res, event, data) { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); }++// ── pumpfun-metadata ──────────────────────────────────────────────────────────++import { sql as _sql } from '../_lib/db.js';+import { env as _env } from '../_lib/env.js';++async function handleMetadata(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 id = url.searchParams.get('id');+ if (!id) return error(res, 400, 'validation_error', 'id required');+ const [a] = await _sql`select id, name, description, avatar_id, meta, wallet_address from agent_identities where id = ${id} and deleted_at is null limit 1`;+ if (!a) return error(res, 404, 'not_found', 'agent not found');+ const origin = _env.APP_ORIGIN;+ const image = a.meta?.image_url || `${origin}/api/agents/${a.id}/og`;+ const animation = a.avatar_id ? `${origin}/api/avatars/${a.avatar_id}/glb` : null;+ const symbol = String(a.name || 'AGENT').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 10) || 'AGENT';+ return json(res, 200, {+ name: a.name, symbol,+ description: a.description || `${a.name} is a 3D AI agent on three.ws with onchain identity and signed action history.`,+ image, animation_url: animation, external_url: `${origin}/agent/${a.id}`,+ attributes: [{ trait_type: 'platform', value: 'three.ws' }, { trait_type: 'agent_id', value: a.id }, ...(a.wallet_address ? [{ trait_type: 'owner', value: a.wallet_address }] : [])],+ properties: { category: 'video', files: [...(animation ? [{ uri: animation, type: 'model/gltf-binary' }] : []), { uri: image, type: 'image/png' }] },+ }, { 'cache-control': 'public, max-age=300', 'access-control-allow-origin': '*' });+}diff --git a/api/agents/register-confirm.js b/api/agents/register-confirm.jsdeleted file mode 100644index 8e34f5402..000000000--- a/api/agents/register-confirm.js+++ /dev/null@@ -1,188 +0,0 @@-/**- * POST /api/agents/register-confirm- *- * Verifies on-chain registration tx, confirms metadata CID matches prep record,- * then upserts the agent_identities row.- *- * Requires: session auth, valid prepId, txHash, chainId, agentId- * Returns: { ok: true, agentId } or { ok: false, error }- */--import { sql } from '../_lib/db.js';-import { getSessionUser } 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 { SERVER_CHAIN_META } from '../_lib/onchain.js';-import { z } from 'zod';-import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';--const bodySchema = z.object({- prepId: z.string().uuid(),- chainId: z.number().int().positive(),- agentId: z.union([z.string(), z.number()]),- txHash: z.string().regex(/^0x[a-f0-9]{64}$/i),-});--// ERC-721 Transfer event (emitted when token is minted)-const REGISTERED_EVENT_ABI =- 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const session = await getSessionUser(req);- if (!session) return error(res, 401, 'unauthorized', 'sign in required');-- const ip = clientIp(req);- const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const chainMeta = SERVER_CHAIN_META[body.chainId];- if (!chainMeta) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);-- // Verify prep record exists, belongs to user, not expired- const [prep] = await sql`- select id, cid, metadata_uri, payload from agent_registrations_pending- where id = ${body.prepId} and user_id = ${session.id} and expires_at > now()- limit 1- `;- if (!prep) return error(res, 404, 'not_found', 'prep record not found or expired');-- // Fetch tx receipt from RPC- let receipt;- try {- receipt = await fetchTransactionReceipt(chainMeta.rpc, body.txHash);- } catch (err) {- return error(res, 400, 'bad_request', `tx verification failed: ${err.message}`);- }-- if (!receipt) {- return error(res, 400, 'bad_request', 'tx not found or still pending');- }-- if (receipt.status !== 1) {- return error(res, 400, 'bad_request', 'tx failed on-chain');- }-- // Parse Registered event from logs- let agentURI;- try {- agentURI = parseRegisteredEvent(receipt.logs, chainMeta.registry);- } catch (err) {- return error(res, 400, 'bad_request', `failed to parse event: ${err.message}`);- }-- // Verify metadataURI matches prep record- if (agentURI !== prep.metadata_uri) {- return error(- res,- 409,- 'conflict',- `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`,- );- }-- // Upsert agent_identities- const agentId = String(body.agentId);- const [updated] = await sql`- insert into agent_identities (- user_id, name, description, avatar_id,- chain_id, erc8004_agent_id, erc8004_registry, registration_cid- )- values (- ${session.id},- ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)},- ${(prep.payload.description || '').slice(0, 1000)},- null,- ${body.chainId},- ${agentId},- ${chainMeta.registry},- ${prep.cid}- )- on conflict (user_id) do update set- name = excluded.name,- description = excluded.description,- chain_id = excluded.chain_id,- erc8004_agent_id = excluded.erc8004_agent_id,- erc8004_registry = excluded.erc8004_registry,- registration_cid = excluded.registration_cid,- updated_at = now()- returning id- `;-- // Consume the prep record so it can't be reused- await sql`delete from agent_registrations_pending where id = ${body.prepId}`;-- return json(res, 200, {- ok: true,- agentId: updated.id,- });-});--/**- * Fetch transaction receipt from JSON-RPC.- * @param {string} rpcUrl- * @param {string} txHash- * @returns {Promise<object|null>}- */-async function fetchTransactionReceipt(rpcUrl, txHash) {- const res = await fetch(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'eth_getTransactionReceipt',- params: [txHash],- }),- });-- const data = await res.json();- if (data.error) throw new Error(`RPC error: ${data.error.message}`);- return data.result;-}--/**- * Parse Registered event from receipt logs.- * Returns the agentURI (metadataURI) from the event.- *- * Event signature: Registered(uint256 indexed agentId, string agentURI, address indexed owner)- * Topic hash: keccak256('Registered(uint256,string,address)')- *- * @param {array} logs- * @param {string} registryAddress- * @returns {string} agentURI- */-function parseRegisteredEvent(logs, registryAddress) {- const registryAddr = getAddress(registryAddress);- const topic0 = eventSignatureHash('Registered(uint256,string,address)');-- for (const log of logs) {- // Match registry address and Registered event topic- if (getAddress(log.address) === registryAddr && log.topics[0] === topic0) {- // Decode the data field which contains the string agentURI- // For Registered(uint256 indexed agentId, string agentURI, address indexed owner),- // the data field contains (agentURI). The string is ABI-encoded as offset + length + data.- const abi = ['string'];- const coder = AbiCoder.defaultAbiCoder();- const decoded = coder.decode(abi, log.data);- return decoded[0];- }- }-- throw new Error('Registered event not found in receipt');-}--/**- * Compute keccak256 hash of event signature string.- * Used to match event topic0.- *- * @param {string} signature e.g., 'Registered(uint256,string,address)'- * @returns {string} hex digest with 0x prefix- */-function eventSignatureHash(signature) {- return keccak256(toUtf8Bytes(signature));-}diff --git a/api/agents/register-prep.js b/api/agents/register-prep.jsdeleted file mode 100644index 9d7872a2a..000000000--- a/api/agents/register-prep.js+++ /dev/null@@ -1,172 +0,0 @@-/**- * POST /api/agents/register-prep- *- * Server-side registration prep: builds canonical registration JSON,- * pins to IPFS, stores a transient record, returns CID for client signing.- *- * Requires: session auth, valid avatarId owned by user, metadata fields.- * Rate limit: authedWrite per user.- * Returns: { ok: true, cid, metadataURI, prepId } or { ok: false, error }- */--import { sql } from '../_lib/db.js';-import { getSessionUser } 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 { env } from '../_lib/env.js';-import { r2 } from '../_lib/r2.js';-import { PutObjectCommand } from '@aws-sdk/client-s3';-import { z } from 'zod';-import { createHash } from 'crypto';--const bodySchema = z.object({- name: z.string().trim().min(1).max(60),- description: z.string().trim().max(280),- avatarId: z.string().uuid(),- brain: z- .object({- provider: z.string().optional(),- model: z.string().optional(),- instructions: z.string().optional(),- })- .optional(),- skills: z- .array(z.string().regex(/^[a-z0-9-]{1,40}$/i))- .max(16)- .optional(),- embedPolicy: z.record(z.any()).optional(),- demoSlug: z.string().optional(),-});--const PREP_EXPIRY_HOURS = 1;--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const session = await getSessionUser(req);- if (!session) return error(res, 401, 'unauthorized', 'sign in required');-- const ip = clientIp(req);- const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));-- // Verify avatar belongs to user- const [avatar] = await sql`- select id from avatars- where id = ${body.avatarId} and owner_id = ${session.id} and deleted_at is null- limit 1- `;- if (!avatar) return error(res, 404, 'not_found', 'avatar not found');-- // Build canonical registration JSON per ERC-8004 spec- const registrationJson = {- $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',- spec: 'agent-manifest/0.1',- name: body.name,- description: body.description,- image: '',- tags: [],- body: {- uri: '', // filled by client-side GLB pinning if needed- format: 'gltf-binary',- },- _baseURI: `ipfs://`, // CRITICAL: must end with / per invariants- ...(body.brain && { brain: body.brain }),- ...(body.skills && body.skills.length > 0 && { skills: body.skills }),- ...(body.embedPolicy && { embedPolicy: body.embedPolicy }),- ...(body.demoSlug && { demoSlug: body.demoSlug }),- };-- // Pin to IPFS- const { cid, metadataURI } = await pinRegistrationJson(registrationJson);-- // Store prep record (1-hour expiry)- const expiresAt = new Date(Date.now() + PREP_EXPIRY_HOURS * 60 * 60 * 1000);- const [prep] = await sql`- insert into agent_registrations_pending- (user_id, cid, metadata_uri, payload, expires_at)- values- (${session.id}, ${cid}, ${metadataURI}, ${JSON.stringify(registrationJson)}::jsonb, ${expiresAt})- returning id- `;-- return json(res, 200, {- ok: true,- cid,- metadataURI,- prepId: prep.id,- });-});--/**- * Pin registration JSON to IPFS.- *- * Strategy:- * 1. Try web3.storage if WEB3_STORAGE_TOKEN is available- * 2. Otherwise store to R2 and generate a content-hash-based stub CID- *- * @param {object} json Registration JSON- * @returns {Promise<{cid: string, metadataURI: string}>}- */-async function pinRegistrationJson(json) {- const jsonStr = JSON.stringify(json);- const jsonBytes = Buffer.from(jsonStr, 'utf-8');-- // Try web3.storage first- const token = process.env.WEB3_STORAGE_TOKEN;- if (token) {- try {- const cid = await pinToWeb3Storage(jsonBytes, token);- return { cid, metadataURI: `ipfs://${cid}` };- } catch (err) {- console.error('[register-prep] web3.storage pin failed:', err.message);- // fall through to fallback- }- }-- // Fallback: store to R2 and generate stub CID from content hash- const contentHash = createHash('sha256').update(jsonStr).digest('hex');- const stubCid = `bafkreigenerated${contentHash.slice(0, 40)}`; // mock bafk-prefixed CID- const key = `agent-registrations/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;-- await r2.send(- new PutObjectCommand({- Bucket: env.S3_BUCKET,- Key: key,- Body: jsonBytes,- ContentType: 'application/json',- }),- );-- return { cid: stubCid, metadataURI: `ipfs://${stubCid}` };-}--/**- * Pin to web3.storage via HTTP API.- * @param {Buffer} data- * @param {string} token- * @returns {Promise<string>} CID- */-async function pinToWeb3Storage(data, token) {- // web3.storage expects car format; for now use direct multipart upload- const res = await fetch('https://api.web3.storage/upload', {- method: 'POST',- headers: {- Authorization: `Bearer ${token}`,- },- body: data,- });-- if (!res.ok) {- const text = await res.text().catch(() => res.status);- throw new Error(`web3.storage upload failed (${res.status}): ${text}`);- }-- const result = await res.json();- if (!result.cid) throw new Error('web3.storage returned no CID');- return result.cid;-}diff --git a/api/agents/sas-credentials.js b/api/agents/sas-credentials.jsdeleted file mode 100644index c40b7d2ca..000000000--- a/api/agents/sas-credentials.js+++ /dev/null@@ -1,50 +0,0 @@-/**- * GET /api/agents/sas-credentials?subject=<pubkey>&network=devnet|mainnet&kind=...- *- * Read SAS credentials issued to a wallet or agent (subject = nonce).- * Public; backed by solana_credentials cache.- */--import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const subject = url.searchParams.get('subject');- const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';- const kind = url.searchParams.get('kind') || null;- const includeClosed = url.searchParams.get('include_closed') === '1';-- if (!subject) return error(res, 400, 'validation_error', 'subject required');-- const rows = kind- ? await sql`- select attestation_pda, schema_pda, credential_pda, kind, subject,- issuer_signature, data, expiry, closed, issued_at- from solana_credentials- where subject = ${subject} and network = ${network} and kind = ${kind}- and (${includeClosed} or closed = false)- and (expiry is null or expiry > now())- order by issued_at desc- `- : await sql`- select attestation_pda, schema_pda, credential_pda, kind, subject,- issuer_signature, data, expiry, closed, issued_at- from solana_credentials- where subject = ${subject} and network = ${network}- and (${includeClosed} or closed = false)- and (expiry is null or expiry > now())- order by issued_at desc- `;-- return json(res, 200, {- subject, network, kind, count: rows.length, data: rows,- });-});diff --git a/api/agents/sas-issue-credential.js b/api/agents/sas-issue-credential.jsdeleted file mode 100644index 5715342ec..000000000--- a/api/agents/sas-issue-credential.js+++ /dev/null@@ -1,97 +0,0 @@-/**- * POST /api/agents/sas-issue-credential- *- * Admin-only. Issues a credentialed SAS attestation under the three.ws- * credential authority, then caches it in solana_credentials so the- * reputation weighting can use it without an RPC roundtrip.- *- * Body:- * { kind: 'threews.verified-client.v1' | 'threews.audited-validation.v1',- * subject: <base58 pubkey>,- * data: { ...schema fields },- * expiry?: <unix seconds>,- * network?: 'devnet' | 'mainnet' }- */--import { z } from 'zod';-import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { parse } from '../_lib/validate.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { requireAdmin } from '../_lib/admin.js';-import { sasIssue, SAS_CONFIG } from '../_lib/sas.js';--const SCHEMAS = Object.keys(SAS_CONFIG.schemas);--const bodySchema = z.object({- kind: z.enum(SCHEMAS),- subject: z.string().min(32).max(44),- data: z.record(z.any()).default({}),- expiry: z.number().int().nonnegative().default(0),- network: z.enum(['devnet', 'mainnet']).default('devnet'),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const admin = await requireAdmin(req, res);- if (!admin) return;-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));-- // Validate required fields are present and types are right.- const def = SAS_CONFIG.schemas[body.kind];- for (let i = 0; i < def.fieldNames.length; i++) {- const fname = def.fieldNames[i];- const v = body.data[fname];- if (v === undefined) return error(res, 400, 'validation_error', `missing field: ${fname}`);- const t = def.layout[i];- if (t === 12 && typeof v !== 'string') return error(res, 400, 'validation_error', `${fname} must be string`);- if (t === 10 && typeof v !== 'boolean') return error(res, 400, 'validation_error', `${fname} must be bool`);- if (t === 0 && (!Number.isInteger(v) || v < 0 || v > 255)) return error(res, 400, 'validation_error', `${fname} must be u8`);- }-- let result;- try {- result = await sasIssue({- kind: body.kind,- subject: body.subject,- data: body.data,- expiry: body.expiry,- network: body.network,- });- } catch (e) {- return error(res, 500, 'sas_issue_failed', e.message || String(e));- }-- const expiryDate = body.expiry > 0 ? new Date(body.expiry * 1000) : null;- await sql`- insert into solana_credentials- (attestation_pda, network, schema_pda, credential_pda, kind, subject,- issuer_signature, data, expiry)- values (- ${result.attestation_pda}, ${body.network}, ${result.schema_pda},- ${result.credential_pda}, ${body.kind}, ${body.subject},- ${result.signature}, ${JSON.stringify(body.data)}::jsonb, ${expiryDate}- )- on conflict (attestation_pda) do update set- data = excluded.data,- expiry = excluded.expiry,- issuer_signature = excluded.issuer_signature,- closed = false,- closed_at = null- `;-- return json(res, 201, {- signature: result.signature,- attestation_pda: result.attestation_pda,- schema_pda: result.schema_pda,- credential_pda: result.credential_pda,- kind: body.kind,- subject: body.subject,- });-});diff --git a/api/agents/x402/invoke.js b/api/agents/x402/invoke.jsdeleted file mode 100644index 8ae594b51..000000000--- a/api/agents/x402/invoke.js+++ /dev/null@@ -1,125 +0,0 @@-/**- * POST /api/agents/x402/invoke- *- * Reference paid-skill endpoint. Demonstrates the x402 flow end-to-end:- *- * 1. Caller POSTs { agent_id, skill, args } with no payment header.- * 2. We compute the price for (agent, skill) from the agent's skill- * manifest (defaulting to a flat per-call price), and emit 402 with- * the canonical manifest.- * 3. Caller pays via the payments endpoints, retries with- * `x-payment-intent: <intent_id>`. We verify, mark the intent- * consumed, then dispatch the actual skill.- *- * Skill dispatch is deliberately stub-like — production paid skills will- * register handlers via `registerPaidSkill('summarize', handler)` once we- * wire this into the runtime. For now: an `echo` skill returns the args.- */--import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';-import { emit402, verifyPaid, consumeIntent } from '../../_lib/x402.js';--const bodySchema = z.object({- agent_id: z.string().min(1).max(80),- skill: z.string().min(1).max(64),- args: z.record(z.any()).default({}),-});--// ── Skill registry (stub) ──────────────────────────────────────────────────-//-// In a future runtime hook, these are registered via the agent's skill-// manifest; here we hardcode a single demo skill so the e2e flow is real.--const HANDLERS = {- echo: async (args) => ({ ok: true, echoed: args }),-};--function priceFor(agent, skill) {- // Look up per-skill price from agent.meta.skill_prices, fall back to a- // flat per-call default declared at meta.payments.default_price.- const prices = agent.meta?.skill_prices || {};- const defaultPrice = agent.meta?.payments?.default_price;- const fromMap = prices[skill];- if (fromMap?.amount && fromMap?.currency) return fromMap;- if (defaultPrice?.amount && defaultPrice?.currency) return defaultPrice;- // Hard default: 0.01 USDC = 10000 raw (6 decimals). Demo-only.- const cluster = agent.meta?.payments?.cluster || 'mainnet';- return {- amount: '10000',- currency:- cluster === 'devnet'- ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'- : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',- };-}--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId, scope: bearer.scope };- return null;-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));-- const [agent] = await sql`- select id, name, meta from agent_identities- where id = ${body.agent_id} and deleted_at is null- limit 1- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');- if (!agent.meta?.payments?.configured) {- return error(res, 409, 'precondition_failed', 'agent has not enabled payments');- }- if (!HANDLERS[body.skill]) {- return error(res, 404, 'unknown_skill', `skill "${body.skill}" is not registered`);- }-- const price = priceFor(agent, body.skill);-- // Verify payment header — emit 402 if missing or invalid.- const paid = await verifyPaid(req, {- agentId: agent.id,- skill: body.skill,- expectedAmount: price.amount,- expectedCurrency: price.currency,- });- if (!paid) {- return emit402(res, {- agent,- skill: body.skill,- amount: price.amount,- currency: price.currency,- });- }-- // Single-shot: consume the intent before dispatch so a retry of the same- // intent fails. (Skill failures don't refund — the intent paid for the- // attempt, not the success. Future work: idempotency keys for retries.)- await consumeIntent(paid.intentId);-- const result = await HANDLERS[body.skill](body.args, { agent, caller: auth });- return json(res, 200, {- ok: true,- intent_id: paid.intentId,- amount: paid.amount,- currency: paid.currency,- result,- });-});diff --git a/api/agents/x402/manifest.js b/api/agents/x402/manifest.jsdeleted file mode 100644index f56b18865..000000000--- a/api/agents/x402/manifest.js+++ /dev/null@@ -1,61 +0,0 @@-/**- * GET /api/agents/x402/manifest?agent_id=...&skill=...- *- * Returns the x402 payment manifest for a given (agent, skill) pair *without*- * issuing 402. Useful for x402 clients that want to prefetch the price before- * making the real call, and for discovery tooling (x402scan, etc).- *- * Public — anyone can read pricing.- */--import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { manifestOnly } from '../../_lib/x402.js';--const querySchema = z.object({- agent_id: z.string().min(1).max(80),- skill: z.string().min(1).max(64),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, 'http://x');- const q = querySchema.parse({- agent_id: url.searchParams.get('agent_id'),- skill: url.searchParams.get('skill'),- });-- const [agent] = await sql`- select id, name, meta from agent_identities- where id = ${q.agent_id} and deleted_at is null limit 1- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');- if (!agent.meta?.payments?.configured) {- return error(res, 409, 'no_payments', 'agent has not enabled payments');- }-- // Same pricing rule as invoke.js — keep in sync.- const cluster = agent.meta.payments.cluster || 'mainnet';- const fallbackCurrency =- cluster === 'devnet'- ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'- : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';- const prices = agent.meta.skill_prices || {};- const def = agent.meta.payments.default_price;- const price =- prices[q.skill] || def || { amount: '10000', currency: fallbackCurrency };-- return manifestOnly(res, {- agent,- skill: q.skill,- amount: price.amount,- currency: price.currency,- });-});diff --git a/api/auth/wallet/link.js b/api/auth/wallet/link.jsdeleted file mode 100644index e1d7d24db..000000000--- a/api/auth/wallet/link.js+++ /dev/null@@ -1,123 +0,0 @@-// Link a wallet to an existing session-authenticated account via SIWE.--import { verifyMessage, getAddress } from 'ethers';-import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { env } from '../../_lib/env.js';-import { parse } from '../../_lib/validate.js';-import { parseSiweMessage } from '../../_lib/siwe.js';--const bodySchema = z.object({- message: z.string().min(64).max(4000),- signature: z.string().regex(/^0x[a-fA-F0-9]+$/),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.walletLink(String(user.id));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');-- const body = parse(bodySchema, await readJson(req));-- // 1. Parse the SIWE message.- const fields = parseSiweMessage(body.message);- if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');-- // 2. Domain + URI must match this deployment (replay protection).- const appOrigin = env.APP_ORIGIN;- const appHost = new URL(appOrigin).host;- const vercelHost = process.env.VERCEL_URL || null;- const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));- if (!allowedHosts.has(fields.domain)) {- return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);- }- try {- const u = new URL(fields.uri);- const allowedOrigins = new Set(- [appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean),- );- if (!allowedOrigins.has(u.origin))- return error(res, 400, 'invalid_uri', 'uri origin mismatch');- } catch {- return error(res, 400, 'invalid_uri', 'uri not a valid URL');- }-- // 3. Temporal checks.- const now = Date.now();- if (fields.expirationTime && Date.parse(fields.expirationTime) < now) {- return error(res, 400, 'expired', 'message expired');- }- if (fields.notBefore && Date.parse(fields.notBefore) > now) {- return error(res, 400, 'not_yet_valid', 'message not yet valid');- }-- // 4. Nonce: must exist, be unconsumed, and not expired. Burn on success.- const [nonceRow] = await sql`- select nonce, expires_at, consumed_at- from siwe_nonces- where nonce = ${fields.nonce}- limit 1- `;- if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');- if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');- if (new Date(nonceRow.expires_at) < new Date()) {- return error(res, 400, 'nonce_expired', 'nonce expired');- }-- // 5. Verify signature recovers the claimed address.- let recovered;- try {- recovered = verifyMessage(body.message, body.signature);- } catch {- return error(res, 401, 'invalid_signature', 'signature verification failed');- }- let claimed;- try {- claimed = getAddress(fields.address);- } catch {- return error(res, 400, 'invalid_address', 'address not checksummed correctly');- }- if (recovered.toLowerCase() !== claimed.toLowerCase()) {- return error(res, 401, 'invalid_signature', 'signer does not match address');- }-- // Burn the nonce (race-safe: reject if already consumed).- const burned = await sql`- update siwe_nonces- set consumed_at = now(), address = ${claimed.toLowerCase()}- where nonce = ${fields.nonce} and consumed_at is null- returning nonce- `;- if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');-- const addrLower = claimed.toLowerCase();- const chainId = fields.chainId || null;-- // 6. Check if the address is already linked to any account.- const [existing] = await sql`- select user_id from user_wallets where address = ${addrLower} limit 1- `;- if (existing) {- if (String(existing.user_id) !== String(user.id)) {- return error(res, 409, 'wallet_taken', 'wallet already linked to another account');- }- // Already linked to this user — idempotent success.- return json(res, 200, { ok: true, address: claimed, chainId });- }-- // 7. Link the wallet to the current session user.- await sql`- insert into user_wallets (user_id, address, chain_id, is_primary)- values (${user.id}, ${addrLower}, ${chainId}, false)- `;-- return json(res, 200, { ok: true, address: claimed, chainId });-});diff --git a/api/auth/wallet/unlink.js b/api/auth/wallet/unlink.jsdeleted file mode 100644index 52629ccb2..000000000--- a/api/auth/wallet/unlink.js+++ /dev/null@@ -1,78 +0,0 @@-// Unlink a wallet address from the current session-authenticated account.--import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';--const bodySchema = z.object({- address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');-- const body = parse(bodySchema, await readJson(req));- const addrLower = body.address.toLowerCase();-- // 1. Confirm this wallet belongs to the current user.- const [walletRow] = await sql`- select address, is_primary- from user_wallets- where user_id = ${user.id} and address = ${addrLower}- limit 1- `;- if (!walletRow) return error(res, 404, 'not_found', 'wallet not linked to your account');-- // 2. Refuse if this is the last auth method available.- const [userRow] = await sql`- select password_hash from users where id = ${user.id} limit 1- `;- const hasPassword = !!userRow?.password_hash;-- if (!hasPassword) {- const [{ count }] = await sql`- select count(*)::int as count from user_wallets where user_id = ${user.id}- `;- if (count <= 1) {- return error(- res,- 409,- 'last_auth_method',- 'cannot remove your only authentication method',- );- }- }-- // 3. If removing the primary wallet, promote the most-recently-used remaining one.- if (walletRow.is_primary) {- await sql`- update user_wallets- set is_primary = true- where user_id = ${user.id}- and address != ${addrLower}- and address = (- select address from user_wallets- where user_id = ${user.id} and address != ${addrLower}- order by last_used_at desc nulls last- limit 1- )- `;- }-- // 4. Delete the wallet row.- await sql`- delete from user_wallets where user_id = ${user.id} and address = ${addrLower}- `;-- return json(res, 200, { ok: true });-});diff --git a/api/avatars/presign.js b/api/avatars/presign.jsdeleted file mode 100644index 73887aacd..000000000--- a/api/avatars/presign.js+++ /dev/null@@ -1,57 +0,0 @@-// Returns a short-lived R2 presigned PUT URL for direct browser upload.-// After uploading, the client calls POST /api/avatars with the returned storage_key.--import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { presignUpload } from '../_lib/r2.js';-import { storageKeyFor, enforceQuotas } from '../_lib/avatars.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits } from '../_lib/rate-limit.js';-import { parse, presignUploadBody, slug as slugSchema } from '../_lib/validate.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const userId = await resolveUser(req, 'avatars:write');- if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');-- const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');-- const body = parse(presignUploadBody, await readJson(req));-- try {- await enforceQuotas(userId, body.size_bytes);- } catch (err) {- return error(res, err.status || 402, err.code || 'plan_limit', err.message);- }-- const bodyAny = body;- const slug = bodyAny.slug- ? slugSchema.parse(bodyAny.slug)- : `draft-${Math.random().toString(36).slice(2, 8)}`;-- const key = storageKeyFor({ userId, slug });- const url = await presignUpload({- key,- contentType: body.content_type,- contentLength: body.size_bytes,- });-- return json(res, 200, {- storage_key: key,- upload_url: url,- method: 'PUT',- headers: { 'content-type': body.content_type },- expires_in: 300,- });-});--async function resolveUser(req, requiredScope) {- const session = await getSessionUser(req);- if (session) return session.id;- const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });- if (!bearer) return null;- if (!hasScope(bearer.scope, requiredScope)) return null;- return bearer.userId;-}diff --git a/api/avatars/public.js b/api/avatars/public.jsdeleted file mode 100644index a1a08f6a7..000000000--- a/api/avatars/public.js+++ /dev/null@@ -1,20 +0,0 @@-// GET /api/avatars/public — browse public avatar gallery (no auth)--import { searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';-import { cors, json, method, wrap } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;- const url = new URL(req.url, 'http://x');- const result = await searchPublicAvatars({- q: url.searchParams.get('q') || undefined,- tag: url.searchParams.get('tag') || undefined,- limit: Number(url.searchParams.get('limit')) || 24,- cursor: url.searchParams.get('cursor') || undefined,- });- // Unauthenticated endpoint — never leak raw owner UUIDs (used as R2 path prefix).- result.avatars = result.avatars.map((a) => stripOwnerFor(a, null));- res.setHeader('cache-control', 'public, max-age=60, s-maxage=60');- return json(res, 200, result);-});diff --git a/api/avatars/regenerate-status.js b/api/avatars/regenerate-status.jsdeleted file mode 100644index c1f66cbb9..000000000--- a/api/avatars/regenerate-status.js+++ /dev/null@@ -1,52 +0,0 @@-// GET /api/avatars/regenerate-status?jobId=<id> — poll job status--import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { sql } from '../_lib/db.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;-- // Auth: session OR bearer- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer)- return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');- if (bearer && !hasScope(bearer.scope, 'avatars:read')) {- return error(res, 403, 'insufficient_scope', 'avatars:read scope required');- }- const userId = session?.id ?? bearer?.userId;-- const url = new URL(req.url, 'http://x');- const jobId = url.searchParams.get('jobId');- if (!jobId) return error(res, 400, 'invalid_request', 'jobId required');-- // Fetch job status — must be owned by the authenticated user- const rows = await sql`- select job_id, status, result_avatar_id, error, created_at- from avatar_regen_jobs- where job_id = ${jobId} and user_id = ${userId}- limit 1- `;-- if (!rows[0]) {- return error(res, 404, 'not_found', 'job not found');- }-- const job = rows[0];- const response = {- ok: true,- jobId: job.job_id,- status: job.status,- };-- if (job.result_avatar_id) {- response.resultAvatarId = job.result_avatar_id;- }- if (job.error) {- response.error = job.error;- }-- return json(res, 200, response);-});diff --git a/api/avatars/regenerate.js b/api/avatars/regenerate.jsdeleted file mode 100644index 470130d71..000000000--- a/api/avatars/regenerate.js+++ /dev/null@@ -1,81 +0,0 @@-// POST /api/avatars/regenerate — initiate avatar regeneration-// Pluggable provider architecture. Currently returns 501 until provider is configured.--import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { sql } from '../_lib/db.js';-import { env } from '../_lib/env.js';-import { parse } from '../_lib/validate.js';-import { z } from 'zod';-import { randomUUID } from 'crypto';--const regenerateSchema = z.object({- sourceAvatarId: z.string().trim().min(1).max(100),- mode: z.enum(['remesh', 'retex', 'rerig', 'restyle']),- params: z.record(z.unknown()).optional(),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- // Auth: session OR bearer- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer)- return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');- if (bearer && !hasScope(bearer.scope, 'avatars:write')) {- return error(res, 403, 'insufficient_scope', 'avatars:write scope required');- }- const userId = session?.id ?? bearer?.userId;-- // Rate limit- const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(regenerateSchema, await readJson(req));-- // Verify source avatar exists and is owned by this user- const rows = await sql`- select id, name, storage_key from avatars- where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null- limit 1- `;- if (!rows[0]) {- return error(res, 404, 'not_found', 'source avatar not found or not owned');- }- const sourceAvatar = rows[0];-- // Check if provider is configured- const provider = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();-- if (provider === 'none' || !provider) {- return error(- res,- 501,- 'regen_unconfigured',- 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',- );- }-- // Provider stub — always return success with deterministic fake job- if (provider === 'stub') {- const jobId = `stub-${randomUUID()}`;- // In a real implementation, this would queue the job with the ML provider- // and store metadata in a `avatar_regen_jobs` table.- await sql`- insert into avatar_regen_jobs (job_id, user_id, source_avatar_id, mode, params, status, created_at)- values (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', now())- `;- return json(res, 202, {- ok: true,- jobId,- status: 'queued',- eta: null,- });- }-- // Unknown provider — return error- return error(res, 501, 'regen_provider_error', `Unknown provider: ${provider}`);-});diff --git a/api/onboarding/avaturn-session.js b/api/onboarding/avaturn-session.jsdeleted file mode 100644index dd36ed44a..000000000--- a/api/onboarding/avaturn-session.js+++ /dev/null@@ -1,147 +0,0 @@-// Exchanges 3 selfies (frontal/left/right) for an Avaturn session URL that the-// client hands to `@avaturn/sdk`'s iframe. Photos arrive as JSON base64 data-// URLs — small enough after client-side downscaling to skip multipart parsing.-//-// Contract with client:-// POST /api/onboarding/avaturn-session-// body: { photos: { frontal, left, right } (data URLs), body_type, avatar_type }-// 200: { session_url: string, expires_at?: string }-// 501: { error: 'not_configured' } when AVATURN_API_KEY is unset--import { z } from 'zod';-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';-import { env } from '../_lib/env.js';--const dataUrl = z- .string()- .max(2_500_000) // ~1.8MB binary per photo after base64 expansion; generous ceiling- .regex(/^data:image\/(jpeg|png);base64,/i, 'must be a data:image/(jpeg|png);base64 url');--const bodySchema = z.object({- photos: z.object({- frontal: dataUrl,- left: dataUrl,- right: dataUrl,- }),- body_type: z.enum(['male', 'female']).default('male'),- avatar_type: z.enum(['v1', 'v2']).default('v1'),-});--// Client payloads can be up to ~7.5MB (3 × 2.5MB). Set explicit ceiling on readJson.-const BODY_LIMIT = 8_000_000;--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- // Auth (session cookie OR bearer with avatars:write).- const userId = await resolveUser(req);- if (!userId) return error(res, 401, 'unauthorized', 'sign in to create an avatar');-- // Rate-limit on the same bucket as other uploads — 60/hour/user is plenty- // for onboarding and bounds abuse cost on the Avaturn API.- const rlUser = await limits.upload(userId);- if (!rlUser.success)- return error(res, 429, 'rate_limited', 'too many avatar attempts, try again later');- const rlIp = await limits.authIp(clientIp(req));- if (!rlIp.success)- return error(res, 429, 'rate_limited', 'too many requests from this network');-- if (!env.AVATURN_API_KEY) {- return error(- res,- 501,- 'not_configured',- 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',- );- }-- const body = parse(bodySchema, await readJson(req, BODY_LIMIT));-- // Forward to Avaturn. The exact request shape should be verified against- // the current Avaturn REST API docs before production traffic — fields- // labelled below reflect v1 of their hosted pipeline and may move.- // See https://docs.avaturn.me for the authoritative spec.- try {- const result = await createAvaturnSession({- apiKey: env.AVATURN_API_KEY,- apiUrl: env.AVATURN_API_URL,- userId,- photos: body.photos,- bodyType: body.body_type,- avatarType: body.avatar_type,- });- return json(res, 200, result);- } catch (err) {- const status = err?.status || 502;- const code = err?.code || 'upstream_error';- const message = err?.message || 'avatar provider rejected request';- if (status >= 500) console.error('[avaturn-session] upstream failure:', err);- return error(res, status === 502 ? 502 : status, code, message);- }-});--async function resolveUser(req) {- const session = await getSessionUser(req);- if (session) return session.id;- const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });- if (!bearer) return null;- if (!hasScope(bearer.scope, 'avatars:write')) return null;- return bearer.userId;-}--/**- * Calls Avaturn's session-creation API. Kept in its own function so the exact- * request/response mapping is easy to audit and swap when Avaturn revs.- *- * Expected behaviour (to verify against live docs):- * POST {AVATURN_API_URL}/api/v1/sessions- * Authorization: Bearer {apiKey}- * Content-Type: application/json- * body: { photos: { frontal, left, right }, body_type, version }- * → 200 { session_url, expires_at? }- */-async function createAvaturnSession({ apiKey, apiUrl, userId, photos, bodyType, avatarType }) {- const url = `${apiUrl}/api/v1/sessions`;- const payload = {- external_user_id: userId,- photos: {- frontal: photos.frontal,- left: photos.left,- right: photos.right,- },- body_type: bodyType,- version: avatarType, // 'v1' | 'v2'- };-- const upstream = await fetch(url, {- method: 'POST',- headers: {- authorization: `Bearer ${apiKey}`,- 'content-type': 'application/json',- accept: 'application/json',- },- body: JSON.stringify(payload),- });-- if (!upstream.ok) {- const text = await upstream.text().catch(() => '');- const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);- err.status = upstream.status >= 500 ? 502 : upstream.status;- err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';- throw err;- }-- const data = await upstream.json();- const sessionUrl = data?.session_url || data?.url || data?.iframe_url;- if (!sessionUrl) {- const err = new Error('avaturn response missing session_url');- err.status = 502;- err.code = 'upstream_error';- throw err;- }- return { session_url: sessionUrl, expires_at: data.expires_at ?? null };-}diff --git a/api/onboarding/link-avatar.js b/api/onboarding/link-avatar.jsdeleted file mode 100644index 6605f8c74..000000000--- a/api/onboarding/link-avatar.js+++ /dev/null@@ -1,65 +0,0 @@-// POST /api/onboarding/link-avatar — link an avatar to the user's primary agent--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 { parse } from '../_lib/validate.js';-import { z } from 'zod';--const bodySchema = z.object({- avatarId: z.string().uuid(),- force: z.boolean().default(false),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- // Auth: session OR bearer- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');- const userId = session?.id ?? bearer.userId;-- const body = parse(bodySchema, await readJson(req));-- // Verify the caller owns the avatar.- const [avatar] = await sql`- select id from avatars- where id = ${body.avatarId} and owner_id = ${userId} and deleted_at is null- limit 1- `;- if (!avatar) return error(res, 404, 'not_found', 'avatar not found or not owned by you');-- // Get the user's primary agent (first created).- const [agent] = await sql`- select id, avatar_id from agent_identities- where user_id = ${userId} and deleted_at is null- order by created_at asc- limit 1- `;- if (!agent) return error(res, 404, 'not_found', 'no agent identity found for user');-- // If the agent already has a different avatar, require force flag.- if (agent.avatar_id && agent.avatar_id !== body.avatarId && !body.force) {- return error(- res,- 409,- 'already_linked',- 'agent already has an avatar; pass force: true to override',- {- current_avatar_id: agent.avatar_id,- },- );- }-- // Update the agent's avatar.- const [updated] = await sql`- update agent_identities- set avatar_id = ${body.avatarId}, updated_at = now()- where id = ${agent.id}- returning id, avatar_id, updated_at- `;-- return json(res, 200, { agent: updated });-});diff --git a/api/pump/[action].js b/api/pump/[action].jsindex d23959b73..90d09ca51 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -1681,3 +1681,175 @@ async function handleStrategyValidate(req, res) {if (!r.ok) return error(res, 400, 'validation_error', r.error);return json(res, 200, { data: r.data });}++// ── channel-feed ──────────────────────────────────────────────────────────────++async function handleChannelFeed(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const url = new URL(req.url, `http://${req.headers.host}`);+ const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 200);+ const kinds = url.searchParams.get('kinds') || null;+ const { getMints, getWhales, getClaims } = await import('../_lib/channel-feed-sources.js');+ const { buildFeed } = await import('../../src/pump/channel-feed.js');+ const [mints, whales, claims] = await Promise.all([getMints(limit), getWhales(limit), getClaims(limit)]);+ const items = buildFeed([{ kind: 'mint', items: mints }, { kind: 'whale', items: whales }, { kind: 'claim', items: claims }], { limit, kinds });+ return json(res, 200, { items });+}++// ── deliver-telegram ──────────────────────────────────────────────────────────++import { z as _z } from 'zod';+const _deliverSchema = _z.object({+ chatId: _z.union([_z.string(), _z.number()]),+ signal: _z.object({ kind: _z.enum(['mint', 'whale', 'claim', 'graduation']), mint: _z.string(), summary: _z.string(), refs: _z.array(_z.string()).optional(), ts: _z.number().optional() }),+});++async function handleDeliverTelegram(req, res) {+ if (!method(req, res, ['POST'])) return;+ const botToken = process.env.TELEGRAM_BOT_TOKEN;+ if (!botToken) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');+ const raw = await readJson(req);+ const { chatId, signal } = parse(_deliverSchema, raw);+ const { sendTelegramSignal } = await import('../../src/pump/telegram-delivery.js');+ const result = await sendTelegramSignal({ botToken, chatId, signal });+ return json(res, 200, result);+}++// ── first-claims ──────────────────────────────────────────────────────────────++import bs58 from 'bs58';+import { filterFirstClaims } from '../../src/pump/first-claims.js';++const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';+const CLAIM_DISCS = new Set(['e8f5c2eeeada3a59', '7a027f010ebf0caf', 'a537817004b3ca28']);+const LOOKBACK_MULT = 8;++export async function scanFirstClaims({ sinceTs, limit }) {+ const lim = Math.max(1, Math.min(50, limit));+ const lookbackTs = sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);+ const allClaims = process.env.PUMPFUN_BOT_URL ? await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT) : await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);+ return filterFirstClaims(allClaims, sinceTs, lim);+}++async function handleFirstClaims(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const url = new URL(req.url, 'http://x');+ const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 50));+ let sinceTs;+ if (url.searchParams.has('sinceTs')) { sinceTs = Number(url.searchParams.get('sinceTs')); }+ else { const sinceMinutes = Math.max(1, Math.min(1440, Number(url.searchParams.get('sinceMinutes')) || 60)); sinceTs = Math.floor(Date.now() / 1000) - sinceMinutes * 60; }+ if (!Number.isFinite(sinceTs) || sinceTs <= 0) return error(res, 400, 'validation_error', 'invalid sinceTs');+ const items = await scanFirstClaims({ sinceTs, limit });+ return json(res, 200, { items });+}++async function _fetchFromBot(lookbackTs, maxItems) {+ const r = await _botCall('getFirstClaims', { sinceTs: lookbackTs, limit: maxItems });+ if (r.ok) return _normalise(r.data);+ const r2 = await _botCall('getRecentClaims', { limit: maxItems });+ if (r2.ok) return _normalise(r2.data);+ return [];+}+async function _botCall(tool, args) {+ const url = process.env.PUMPFUN_BOT_URL;+ if (!url) return { ok: false };+ const headers = { 'content-type': 'application/json', accept: 'application/json' };+ if (process.env.PUMPFUN_BOT_TOKEN) headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), 8000);+ try {+ const resp = await fetch(url.replace(/\/$/, ''), { method: 'POST', headers, signal: ctrl.signal, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) });+ if (!resp.ok) return { ok: false, error: `bot ${resp.status}` };+ const j = await resp.json();+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };+ const data = j.result?.structuredContent ?? j.result?.content ?? j.result;+ return { ok: true, data: Array.isArray(data) ? data : (data?.items ?? []) };+ } catch (err) { return { ok: false, error: err?.message || 'fetch failed' }; }+ finally { clearTimeout(t); }+}+function _normalise(items) {+ return (items || []).map((x) => ({ creator: String(x.claimerWallet || x.creator || x.wallet || ''), mint: String(x.tokenMint || x.mint || ''), signature: String(x.txSignature || x.tx_signature || x.signature || ''), lamports: Number(x.amountLamports || x.lamports || 0), ts: Number(x.timestamp || x.ts || 0) })).filter((x) => x.creator && x.signature && x.ts > 0);+}+async function _fetchFromRpc(lookbackTs, maxItems) {+ try {+ const connection = getConnection({ network: 'mainnet' });+ const { PublicKey } = await import('@solana/web3.js');+ const sigs = await connection.getSignaturesForAddress(new PublicKey(PUMP_PROGRAM), { limit: 200 });+ const inWindow = sigs.filter((s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err);+ if (!inWindow.length) return [];+ const toFetch = inWindow.slice(0, Math.min(30, maxItems * 2));+ const settled = await Promise.allSettled(toFetch.map((s) => connection.getParsedTransaction(s.signature, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' })));+ const claims = [];+ for (let i = 0; i < settled.length; i++) {+ if (settled[i].status !== 'fulfilled' || !settled[i].value) continue;+ const claim = _parseClaim(settled[i].value, toFetch[i].signature, toFetch[i].blockTime ?? 0);+ if (claim) claims.push(claim);+ }+ return claims;+ } catch { return []; }+}+function _parseClaim(tx, signature, ts) {+ if (tx?.meta?.err) return null;+ const ixs = tx?.transaction?.message?.instructions ?? [];+ const accountKeys = tx?.transaction?.message?.accountKeys ?? [];+ const pre = tx?.meta?.preBalances ?? [], post = tx?.meta?.postBalances ?? [];+ for (const ix of ixs) {+ if (!ix.data || typeof ix.data !== 'string') continue;+ const progKey = accountKeys[ix.programIdIndex];+ const progId = progKey?.pubkey?.toString?.() ?? String(progKey ?? '');+ if (progId !== PUMP_PROGRAM) continue;+ let bytes;+ try { bytes = bs58.decode(ix.data); } catch { continue; }+ if (bytes.length < 8) continue;+ const disc = Buffer.from(bytes.subarray(0, 8)).toString('hex');+ if (!CLAIM_DISCS.has(disc)) continue;+ const creator = (accountKeys[0]?.pubkey?.toString?.() ?? String(accountKeys[0] ?? ''));+ if (!creator) continue;+ let lamports = 0;+ for (let i = 0; i < accountKeys.length; i++) { const delta = (post[i] ?? 0) - (pre[i] ?? 0); if (delta > lamports) lamports = delta; }+ let mint = '';+ if (disc === 'a537817004b3ca28' && bytes.length >= 48) { try { mint = bs58.encode(bytes.slice(16, 48)); } catch {} }+ return { creator, mint, signature, lamports, ts };+ }+ return null;+}++// ── vanity-keygen (SSE) ───────────────────────────────────────────────────────++async function handleVanityKeygen(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (req.method !== 'POST') { res.setHeader('allow', 'POST'); return error(res, 405, 'method_not_allowed', 'method POST required'); }+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ let body;+ try { body = await readJson(req); } catch (e) { return error(res, e.status || 400, 'bad_request', e.message); }+ const { suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 } = body || {};+ if (!suffix && !prefix) return error(res, 400, 'validation_error', 'at least one of suffix or prefix is required');+ res.statusCode = 200;+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.setHeader('connection', 'keep-alive');+ res.setHeader('x-accel-buffering', 'no');+ const ac = new AbortController();+ const timeout = setTimeout(() => { ac.abort(); _sse(res, 'error', { error: 'request_timeout', error_description: 'vanity search exceeded 60 s limit' }); res.statusCode = 408; res.end(); }, 60_000);+ req.on('close', () => ac.abort());+ const progressInterval = setInterval(() => { if (ac.signal.aborted) return clearInterval(progressInterval); _sse(res, 'progress', { elapsed: Date.now() }); }, 2_000);+ try {+ const { generateVanityKey } = await import('../../src/pump/vanity-keygen.js');+ const _bs58 = (await import('bs58')).default;+ const result = await generateVanityKey({ suffix, prefix, caseSensitive, maxAttempts, signal: ac.signal });+ clearTimeout(timeout); clearInterval(progressInterval);+ if (!result) _sse(res, 'error', { error: 'max_attempts_reached', error_description: `no match found in ${maxAttempts} attempts` });+ else _sse(res, 'result', { publicKey: result.publicKey, secretKey: _bs58.encode(result.secretKey), attempts: result.attempts, ms: result.ms });+ } catch (err) {+ clearTimeout(timeout); clearInterval(progressInterval);+ if (!res.writableEnded) _sse(res, 'error', { error: 'internal_error', error_description: err.message || 'unexpected error' });+ } finally { if (!res.writableEnded) res.end(); }+}+function _sse(res, event, data) { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); }diff --git a/api/pump/channel-feed.js b/api/pump/channel-feed.jsdeleted file mode 100644index d332d586b..000000000--- a/api/pump/channel-feed.js+++ /dev/null@@ -1,44 +0,0 @@-// GET /api/pump/channel-feed?limit=50&kinds=mint,whale,claim-//-// Returns a normalized, deduped, newest-first array of recent pump.fun signals:-// { items: [{ kind, mint, signature, ts, summary, refs }] }-//-// kinds: comma-separated subset of mint|whale|claim (default: all three)-// limit: max items returned (default 50, max 200)-//-// Read-through — no persistence. Data comes from Upstash Redis lists populated-// by the pumpkit worker. Missing/unconfigured Redis returns empty arrays.--import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';-import { buildFeed } from '../../src/pump/channel-feed.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 200);- const kinds = url.searchParams.get('kinds') || null;-- const [mints, whales, claims] = await Promise.all([- getMints(limit),- getWhales(limit),- getClaims(limit),- ]);-- const items = buildFeed(- [- { kind: 'mint', items: mints },- { kind: 'whale', items: whales },- { kind: 'claim', items: claims },- ],- { limit, kinds },- );-- return json(res, 200, { items });-});diff --git a/api/pump/deliver-telegram.js b/api/pump/deliver-telegram.jsdeleted file mode 100644index 8ece9f6b6..000000000--- a/api/pump/deliver-telegram.js+++ /dev/null@@ -1,28 +0,0 @@-import { z } from 'zod';-import { json, error, wrap, method, readJson } from '../_lib/http.js';-import { parse } from '../_lib/validate.js';-import { sendTelegramSignal } from '../../src/pump/telegram-delivery.js';--const bodySchema = z.object({- chatId: z.union([z.string(), z.number()]),- signal: z.object({- kind: z.enum(['mint', 'whale', 'claim', 'graduation']),- mint: z.string(),- summary: z.string(),- refs: z.array(z.string()).optional(),- ts: z.number().optional(),- }),-});--export default wrap(async (req, res) => {- if (!method(req, res, ['POST'])) return;-- const botToken = process.env.TELEGRAM_BOT_TOKEN;- if (!botToken) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');-- const raw = await readJson(req);- const { chatId, signal } = parse(bodySchema, raw);-- const result = await sendTelegramSignal({ botToken, chatId, signal });- return json(res, 200, result);-});diff --git a/api/pump/first-claims.js b/api/pump/first-claims.jsdeleted file mode 100644index f46417b30..000000000--- a/api/pump/first-claims.js+++ /dev/null@@ -1,224 +0,0 @@-// GET /api/pump/first-claims?sinceMinutes=60&limit=50-// OR ?sinceTs=<unix-seconds>&limit=50-//-// Returns { items: [...] } where each item is:-// { creator, mint, signature, lamports, ts }-//-// "First-time" = creator has no observed claim before sinceTs in the-// wider lookback window scanned this request (in-memory dedupe, no DB).-//-// Primary data source: PUMPFUN_BOT_URL (pumpfun-claims-bot MCP).-// Fallback: Solana RPC limited scan (best-effort, up to 200 signatures).-//-// Auth: none — read-only public feed. Rate-limited by IP.--import bs58 from 'bs58';-import { cors, json, method, error, wrap } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { getConnection } from '../_lib/pump.js';-import { filterFirstClaims } from '../../src/pump/first-claims.js';--const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';--// Anchor 8-byte discriminators for fee-claim instructions (hex).-const CLAIM_DISCS = new Set([- 'e8f5c2eeeada3a59', // collect_coin_creator_fee- '7a027f010ebf0caf', // collect_creator_fee- 'a537817004b3ca28', // distribute_creator_fees-]);--// Scan 8× the request window to surface prior claimers.-const LOOKBACK_MULT = 8;--// ── Named export used by api/pump-fun-mcp.js ──────────────────────────────--/**- * Scan for first-time fee claims, apply dedupe, return items array.- * @param {{ sinceTs: number, limit: number }} opts- * @returns {Promise<Array<{creator,mint,signature,lamports,ts}>>}- */-export async function scanFirstClaims({ sinceTs, limit }) {- const lim = Math.max(1, Math.min(50, limit));- const lookbackTs = sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);- let allClaims;- if (process.env.PUMPFUN_BOT_URL) {- allClaims = await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT);- } else {- allClaims = await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);- }- return filterFirstClaims(allClaims, sinceTs, lim);-}--// ── HTTP handler ──────────────────────────────────────────────────────────--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, 'http://x');- const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 50));-- let sinceTs;- if (url.searchParams.has('sinceTs')) {- sinceTs = Number(url.searchParams.get('sinceTs'));- } else {- const sinceMinutes = Math.max(1, Math.min(1440, Number(url.searchParams.get('sinceMinutes')) || 60));- sinceTs = Math.floor(Date.now() / 1000) - sinceMinutes * 60;- }-- if (!Number.isFinite(sinceTs) || sinceTs <= 0) {- return error(res, 400, 'validation_error', 'invalid sinceTs');- }-- const items = await scanFirstClaims({ sinceTs, limit });- return json(res, 200, { items });-});--// ── Bot-backed path ────────────────────────────────────────────────────────--async function _fetchFromBot(lookbackTs, maxItems) {- // Try a dedicated first-claims tool first, then fall back to recent claims.- const r = await _botCall('getFirstClaims', { sinceTs: lookbackTs, limit: maxItems });- if (r.ok) return _normalise(r.data);-- const r2 = await _botCall('getRecentClaims', { limit: maxItems });- if (r2.ok) return _normalise(r2.data);-- return [];-}--async function _botCall(tool, args) {- const url = process.env.PUMPFUN_BOT_URL;- if (!url) return { ok: false };- const headers = { 'content-type': 'application/json', accept: 'application/json' };- if (process.env.PUMPFUN_BOT_TOKEN) headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;- const ctrl = new AbortController();- const t = setTimeout(() => ctrl.abort(), 8000);- try {- const resp = await fetch(url.replace(/\/$/, ''), {- method: 'POST',- headers,- signal: ctrl.signal,- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'tools/call',- params: { name: tool, arguments: args || {} },- }),- });- if (!resp.ok) return { ok: false, error: `bot ${resp.status}` };- const j = await resp.json();- if (j.error) return { ok: false, error: j.error.message || 'rpc error' };- const data = j.result?.structuredContent ?? j.result?.content ?? j.result;- const items = Array.isArray(data) ? data : (data?.items ?? []);- return { ok: true, data: items };- } catch (err) {- return { ok: false, error: err?.message || 'fetch failed' };- } finally {- clearTimeout(t);- }-}--function _normalise(items) {- return (items || [])- .map((x) => ({- creator: String(x.claimerWallet || x.creator || x.wallet || ''),- mint: String(x.tokenMint || x.mint || ''),- signature: String(x.txSignature || x.tx_signature || x.signature || ''),- lamports: Number(x.amountLamports || x.lamports || 0),- ts: Number(x.timestamp || x.ts || 0),- }))- .filter((x) => x.creator && x.signature && x.ts > 0);-}--// ── Solana RPC fallback ────────────────────────────────────────────────────--async function _fetchFromRpc(lookbackTs, maxItems) {- try {- const connection = getConnection({ network: 'mainnet' });- const { PublicKey } = await import('@solana/web3.js');- const pk = new PublicKey(PUMP_PROGRAM);-- // Fetch recent signatures; filter by block time.- const sigs = await connection.getSignaturesForAddress(pk, { limit: 200 });- const inWindow = sigs.filter((s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err);- if (inWindow.length === 0) return [];-- // Batch-fetch up to 30 transactions to stay within Vercel timeout.- const toFetch = inWindow.slice(0, Math.min(30, maxItems * 2));- const settled = await Promise.allSettled(- toFetch.map((s) =>- connection.getParsedTransaction(s.signature, {- maxSupportedTransactionVersion: 0,- commitment: 'confirmed',- }),- ),- );-- const claims = [];- for (let i = 0; i < settled.length; i++) {- if (settled[i].status !== 'fulfilled' || !settled[i].value) continue;- const claim = _parseClaim(settled[i].value, toFetch[i].signature, toFetch[i].blockTime ?? 0);- if (claim) claims.push(claim);- }- return claims;- } catch {- return [];- }-}--function _parseClaim(tx, signature, ts) {- if (tx?.meta?.err) return null;-- const ixs = tx?.transaction?.message?.instructions ?? [];- const accountKeys = tx?.transaction?.message?.accountKeys ?? [];- const pre = tx?.meta?.preBalances ?? [];- const post = tx?.meta?.postBalances ?? [];-- for (const ix of ixs) {- if (!ix.data || typeof ix.data !== 'string') continue;-- // Verify it's the PumpFun program.- const progKey = accountKeys[ix.programIdIndex];- const progId = progKey?.pubkey?.toString?.() ?? String(progKey ?? '');- if (progId !== PUMP_PROGRAM) continue;-- // Match discriminator (first 8 bytes of base58-decoded data).- let bytes;- try {- bytes = bs58.decode(ix.data);- } catch {- continue;- }- if (bytes.length < 8) continue;-- const disc = Buffer.from(bytes.subarray(0, 8)).toString('hex');- if (!CLAIM_DISCS.has(disc)) continue;-- // Creator = first account key (the signer).- const creatorKey = accountKeys[0];- const creator = creatorKey?.pubkey?.toString?.() ?? String(creatorKey ?? '');- if (!creator) continue;-- // Lamports = largest positive balance delta (creator receives the fee).- let lamports = 0;- for (let i = 0; i < accountKeys.length; i++) {- const delta = (post[i] ?? 0) - (pre[i] ?? 0);- if (delta > lamports) lamports = delta;- }-- // Mint: for distribute_creator_fees, it's embedded at bytes 16-48 (32-byte Pubkey).- let mint = '';- if (disc === 'a537817004b3ca28' && bytes.length >= 48) {- try {- mint = bs58.encode(bytes.slice(16, 48));- } catch { /* leave empty */ }- }-- return { creator, mint, signature, lamports, ts };- }- return null;-}diff --git a/api/pump/vanity-keygen.js b/api/pump/vanity-keygen.jsdeleted file mode 100644index 1dcb2f1e6..000000000--- a/api/pump/vanity-keygen.js+++ /dev/null@@ -1,118 +0,0 @@-// POST /api/pump/vanity-keygen-//-// Streams progress via Server-Sent Events; final event delivers the result.-//-// body: { suffix?, prefix?, caseSensitive?, maxAttempts? }-// - at least one of suffix / prefix must be non-empty-// - hard cap: 60 s wallclock; aborts with 408 if exceeded-//-// SSE event stream:-// event: progress data: { attempts, elapsed } (every ~50k attempts)-// event: result data: { publicKey, secretKey: base58, attempts, ms }-// event: error data: { error, error_description }-//-// Secret keys are never logged.--import { cors, readJson, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { generateVanityKey } from '../../src/pump/vanity-keygen.js';-import bs58 from 'bs58';--const TIMEOUT_MS = 60_000;--function sseEvent(res, event, data) {- res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);-}--export default async function handler(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;-- if (req.method !== 'POST') {- res.setHeader('allow', 'POST');- return error(res, 405, 'method_not_allowed', 'method POST required');- }-- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- let body;- try {- body = await readJson(req);- } catch (e) {- return error(res, e.status || 400, 'bad_request', e.message);- }-- const { suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 } = body || {};-- if (!suffix && !prefix) {- return error(res, 400, 'validation_error', 'at least one of suffix or prefix is required');- }-- // Start SSE stream- res.statusCode = 200;- res.setHeader('content-type', 'text/event-stream; charset=utf-8');- res.setHeader('cache-control', 'no-store');- res.setHeader('connection', 'keep-alive');- res.setHeader('x-accel-buffering', 'no');-- const ac = new AbortController();-- const timeout = setTimeout(() => {- ac.abort();- sseEvent(res, 'error', {- error: 'request_timeout',- error_description: 'vanity search exceeded 60 s limit',- });- res.statusCode = 408;- res.end();- }, TIMEOUT_MS);-- req.on('close', () => ac.abort());-- // Progress ticker — emit every 50k attempts via a periodic callback wired- // through the AbortSignal so it stops naturally when we're done.- let lastReported = 0;- const progressInterval = setInterval(() => {- if (ac.signal.aborted) return clearInterval(progressInterval);- // We can't read the exact attempt count here — just emit elapsed time.- sseEvent(res, 'progress', { elapsed: Date.now() });- }, 2_000);-- try {- const result = await generateVanityKey({- suffix,- prefix,- caseSensitive,- maxAttempts,- signal: ac.signal,- });-- clearTimeout(timeout);- clearInterval(progressInterval);-- if (!result) {- sseEvent(res, 'error', {- error: 'max_attempts_reached',- error_description: `no match found in ${maxAttempts} attempts`,- });- } else {- sseEvent(res, 'result', {- publicKey: result.publicKey,- secretKey: bs58.encode(result.secretKey),- attempts: result.attempts,- ms: result.ms,- });- }- } catch (err) {- clearTimeout(timeout);- clearInterval(progressInterval);- if (!res.writableEnded) {- sseEvent(res, 'error', {- error: 'internal_error',- error_description: err.message || 'unexpected error',- });- }- } finally {- if (!res.writableEnded) res.end();- }-}diff --git a/vercel.json b/vercel.jsonindex 6277cda05..f3125ff5e 100644--- a/vercel.json+++ b/vercel.json@@ -87,23 +87,34 @@},{ "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },{ "src": "/dashboard/storage", "dest": "/dashboard/storage.html" },- {- "src": "/api/agents/([^/]+)/embed-policy",- "dest": "/api/agents/[id]/embed-policy?id=$1"- },- { "src": "/api/agents/([^/]+)/sign", "dest": "/api/agents/[id]/sign?id=$1" },- { "src": "/api/agents/([^/]+)/animations", "dest": "/api/agents/[id]/animations?id=$1" },- { "src": "/api/agents/([^/]+)/manifest", "dest": "/api/agents/[id]/manifest?id=$1" },+ { "src": "/api/agents/([^/]+)/embed-policy", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/([^/]+)/sign", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/([^/]+)/animations", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/([^/]+)/manifest", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/([^/]+)/actions", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]" },+ { "src": "/api/agents/pumpfun-feed", "dest": "/api/agents/pumpfun?_handler=feed" },+ { "src": "/api/agents/pumpfun-metadata", "dest": "/api/agents/pumpfun?_handler=metadata" },{ "src": "/api/agents/pumpfun", "dest": "/api/agents/pumpfun" },- { "src": "/api/agents/pumpfun-feed", "dest": "/api/agents/pumpfun-feed" },- { "src": "/api/agents/pumpfun-metadata", "dest": "/api/agents/pumpfun-metadata" },- { "src": "/api/agents/solana-register-prep", "dest": "/api/agents/solana-register-prep" },- { "src": "/api/agents/solana-register-confirm", "dest": "/api/agents/solana-register-confirm" },- { "src": "/api/agents/register-prep", "dest": "/api/agents/register-prep" },- { "src": "/api/agents/register-confirm", "dest": "/api/agents/register-confirm" },+ { "src": "/api/agents/register-prep", "dest": "/api/agents/register/[action]?action=prep" },+ { "src": "/api/agents/register-confirm", "dest": "/api/agents/register/[action]?action=confirm" },+ { "src": "/api/agents/sas-credentials", "dest": "/api/agents/sas/[action]?action=credentials" },+ { "src": "/api/agents/sas-issue-credential", "dest": "/api/agents/sas/[action]?action=issue-credential" },+ { "src": "/api/agents/x402/invoke", "dest": "/api/agents/x402/[action]?action=invoke" },+ { "src": "/api/agents/x402/manifest", "dest": "/api/agents/x402/[action]?action=manifest" },{ "src": "/api/agents/check-name", "dest": "/api/agents/check-name" },- { "src": "/api/agents/sas-credentials", "dest": "/api/agents/sas-credentials" },- { "src": "/api/agents/sas-issue-credential", "dest": "/api/agents/sas-issue-credential" },+ { "src": "/api/auth/wallet/link", "dest": "/api/auth/wallet/[action]?action=link" },+ { "src": "/api/auth/wallet/unlink", "dest": "/api/auth/wallet/[action]?action=unlink" },+ { "src": "/api/onboarding/avaturn-session", "dest": "/api/onboarding/[action]?action=avaturn-session" },+ { "src": "/api/onboarding/link-avatar", "dest": "/api/onboarding/[action]?action=link-avatar" },+ { "src": "/api/pump/channel-feed", "dest": "/api/pump/[action]?action=channel-feed" },+ { "src": "/api/pump/deliver-telegram", "dest": "/api/pump/[action]?action=deliver-telegram" },+ { "src": "/api/pump/first-claims", "dest": "/api/pump/[action]?action=first-claims" },+ { "src": "/api/pump/vanity-keygen", "dest": "/api/pump/[action]?action=vanity-keygen" },+ { "src": "/api/avatars/presign", "dest": "/api/avatars/[id]" },+ { "src": "/api/avatars/public", "dest": "/api/avatars/[id]" },+ { "src": "/api/avatars/regenerate-status", "dest": "/api/avatars/[id]" },+ { "src": "/api/avatars/regenerate", "dest": "/api/avatars/[id]" },{ "src": "/api/agents/([^/]+)", "dest": "/api/agents/[id]" },{ "src": "/api/agents", "dest": "/api/agents" },{ "src": "/api/agent-actions", "dest": "/api/agent-actions" },@@ -187,7 +198,6 @@{ "src": "/api/llm/anthropic", "dest": "/api/llm/anthropic.js" },- { "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]/usage?id=$1" },{ "src": "/dashboard/usage", "dest": "/dashboard/usage.html" },{ "src": "/api/erc8004/hydrate", "dest": "/api/erc8004/hydrate.js" },{ "src": "/api/erc8004/import", "dest": "/api/erc8004/import.js" },