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 subscription management API and creator plan management
nirholas3794da82e860
diff --git a/.env.example b/.env.exampleindex b5ce28879..d2868f813 100644--- a/.env.example+++ b/.env.example@@ -147,3 +147,9 @@ X402_FACILITATOR_TOKEN_BASE=# zauthx402 — telemetry + monitoring for x402 endpoints. Optional; when unset# the SDK is not invoked. Get a key at https://zauthx402.com.ZAUTH_API_KEY=++# ── GitHub OAuth (social memory seeding) ─────────────────────────────────────+# Create an OAuth App at https://github.com/settings/developers.+# Callback URL: https://your-domain.com/api/auth/github/callback+GITHUB_OAUTH_CLIENT_ID=+GITHUB_OAUTH_CLIENT_SECRET=diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.jsindex 2bdbb83cd..7b85d51e2 100644--- a/api/_lib/agent-wallet.js+++ b/api/_lib/agent-wallet.js@@ -81,6 +81,198 @@ export async function recoverAgentKey(encryptedKey) {return decrypt(encryptedKey);}+// ── EVM on-chain balance + spend helpers ────────────────────────────────────++let _ethUsdPrice = null;+let _ethUsdPriceAt = 0;+const ETH_USD_CACHE_MS = 5 * 60_000;++async function fetchEthUsdPrice() {+ if (_ethUsdPrice && Date.now() - _ethUsdPriceAt < ETH_USD_CACHE_MS) return _ethUsdPrice;+ const r = await fetch(+ 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',+ );+ if (!r.ok) throw new Error('coingecko ETH/USD fetch failed');+ const { ethereum } = await r.json();+ _ethUsdPrice = ethereum.usd;+ _ethUsdPriceAt = Date.now();+ return _ethUsdPrice;+}++/**+ * Query the live ETH balance of an agent's wallet_address on its registered chain.+ * @returns {{ address: string, chain_id: number, balance_wei: string, balance_eth: string }}+ */+export async function getAgentBalance(agentId) {+ const { sql } = await import('./db.js');+ const [agent] = await sql`+ select wallet_address, chain_id+ from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!agent?.wallet_address) throw new Error('agent has no wallet_address');+ const chainId = agent.chain_id || 8453;++ const { env } = await import('./env.js');+ const rpcUrl = env.getRpcUrl(chainId);+ if (!rpcUrl) throw new Error(`no RPC URL for chain ${chainId}`);++ const { JsonRpcProvider, formatEther } = await import('ethers');+ const provider = new JsonRpcProvider(rpcUrl);+ const balanceBigInt = await provider.getBalance(agent.wallet_address);+ return {+ address: agent.wallet_address,+ chain_id: chainId,+ balance_wei: balanceBigInt.toString(),+ balance_eth: formatEther(balanceBigInt),+ };+}++/**+ * Returns true if the agent's EVM wallet can afford priceUsd (at current ETH/USD).+ */+export async function canAfford(agentId, priceUsd) {+ const { parseEther } = await import('ethers');+ const [bal, ethUsd] = await Promise.all([getAgentBalance(agentId), fetchEthUsdPrice()]);+ const priceEth = priceUsd / ethUsd;+ const priceWei = parseEther(priceEth.toFixed(18));+ return BigInt(bal.balance_wei) >= priceWei;+}++const SPEND_ABI = [+ 'function spend(uint256 agentId, address payable recipient, uint256 amountWei, string calldata memo) external',+];++/**+ * Calls IdentityRegistry.spend() via the agent's delegated signer key.+ * @param {{ agentId: string, recipient: string, amountWei: bigint|string, memo: string, signer: import('ethers').Signer }} opts+ * @returns {Promise<string>} tx hash+ */+export async function delegatedSpend({ agentId, recipient, amountWei, memo, signer }) {+ const { sql } = await import('./db.js');+ const [agent] = await sql`+ select erc8004_agent_id, chain_id from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!agent?.erc8004_agent_id) throw new Error('agent has no on-chain erc8004_agent_id');++ const chainId = agent.chain_id || 8453;+ const { CHAIN_BY_ID, IDENTITY_REGISTRY_MAINNET, IDENTITY_REGISTRY_TESTNET } = await import('./erc8004-chains.js');+ const chain = CHAIN_BY_ID[chainId];+ const registryAddress = chain?.testnet ? IDENTITY_REGISTRY_TESTNET : IDENTITY_REGISTRY_MAINNET;++ const { Contract } = await import('ethers');+ const registry = new Contract(registryAddress, SPEND_ABI, signer);+ const tx = await registry.spend(agent.erc8004_agent_id, recipient, amountWei, memo || '');+ return tx.hash;+}++/**+ * Fire-and-forget: charge an agent for a paid skill call.+ * Records in agent_payments; broadcasts on-chain via delegatedSpend if affordable.+ * Never throws — errors are logged and the payment row reflects the outcome.+ */+export async function triggerSkillPayment({ agentId, skillSlug, skillId }) {+ try {+ const { sql } = await import('./db.js');++ // Resolve skill price and author wallet+ const [skill] = await sql`+ select ms.id, ms.price_per_call_usd, ms.author_id,+ uw.address as author_wallet+ from marketplace_skills ms+ left join user_wallets uw on uw.user_id = ms.author_id+ and uw.chain_type = 'evm' and uw.is_primary = true+ where ms.slug = ${skillSlug}+ limit 1+ `;+ if (!skill || Number(skill.price_per_call_usd) <= 0) return;++ const priceUsd = Number(skill.price_per_call_usd);++ // Load agent to get chain + encrypted key+ const [agent] = await sql`+ select wallet_address, chain_id, erc8004_agent_id, meta+ from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!agent) return;++ const chainId = agent.chain_id || 8453;+ const encryptedKey = agent.meta?.encrypted_wallet_key;+ if (!encryptedKey) return;++ // Convert USD → wei+ const ethUsd = await fetchEthUsdPrice();+ const priceEth = priceUsd / ethUsd;+ const { parseEther, Wallet, JsonRpcProvider } = await import('ethers');+ const amountWei = parseEther(priceEth.toFixed(18));++ const affordable = BigInt(+ (await getAgentBalance(agentId).catch(() => ({ balance_wei: '0' }))).balance_wei,+ ) >= amountWei;++ if (!affordable) {+ await sql`+ insert into agent_payments+ (payer_agent_id, skill_id, amount_wei, chain_id, memo, status)+ values (+ ${agentId}, ${skill.id ?? null}, ${amountWei.toString()},+ ${chainId}, ${skillSlug}, 'failed'+ )+ `;+ console.warn(`[agent-payments] agent ${agentId} cannot afford skill ${skillSlug}`);+ return;+ }++ // Insert pending row first+ const [row] = await sql`+ insert into agent_payments+ (payer_agent_id, skill_id, amount_wei, chain_id, memo, status)+ values (+ ${agentId}, ${skill.id ?? null}, ${amountWei.toString()},+ ${chainId}, ${skillSlug}, 'pending'+ )+ returning id+ `;++ // Build signer + dispatch tx (fire-and-forget)+ (async () => {+ try {+ const { env } = await import('./env.js');+ const rpcUrl = env.getRpcUrl(chainId);+ if (!rpcUrl) throw new Error(`no RPC URL for chain ${chainId}`);+ const pkHex = await decrypt(encryptedKey);+ const provider = new JsonRpcProvider(rpcUrl);+ const signer = new Wallet(pkHex, provider);+ const recipient = skill.author_wallet || signer.address;+ const txHash = await delegatedSpend({+ agentId,+ recipient,+ amountWei,+ memo: skillSlug,+ signer,+ });+ await sql`+ update agent_payments set status = 'confirmed', tx_hash = ${txHash}+ where id = ${row.id}+ `;+ } catch (e) {+ await sql`+ update agent_payments set status = 'failed'+ where id = ${row.id}+ `.catch(() => {});+ console.error(`[agent-payments] tx failed for ${agentId}/${skillSlug}`, e?.message);+ }+ })();+ } catch (e) {+ console.error('[agent-payments] triggerSkillPayment error', e?.message);+ }+}+// ── Solana wallet ───────────────────────────────────────────────────────────/**diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 9bc415d61..29cfad143 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -190,6 +190,14 @@ export const env = {return opt('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');},+ // GitHub OAuth — social memory seeding. When unset, /api/auth/github/connect returns 501.+ get GITHUB_OAUTH_CLIENT_ID() {+ return opt('GITHUB_OAUTH_CLIENT_ID');+ },+ get GITHUB_OAUTH_CLIENT_SECRET() {+ return opt('GITHUB_OAUTH_CLIENT_SECRET');+ },+// Admin key for three.ws chat brand config endpoint. Optional — when unset// the POST /api/chat/config endpoint returns 503.get CHAT_ADMIN_KEY() {diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex d2d286939..fa5683884 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -120,7 +120,12 @@ export const limits = {newsletterIp: (ip) => getLimiter('newsletter:ip', { limit: 5, window: '1 h' }).limit(ip),// Voice cloning: expensive ElevenLabs API call — 3 per user per day.voiceClone: (userId) => getLimiter('voice:clone', { limit: 3, window: '1 d' }).limit(userId),+ // Persona extraction: Claude API call — 5 per user per day.+ personaExtract: (userId) =>+ getLimiter('persona:extract', { limit: 5, window: '1 d' }).limit(userId),agentDelegate: (key) => getLimiter('agent:delegate', { limit: 10, window: '1 m' }).limit(key),+ // GitHub memory seeding: expensive (GitHub API + Claude). 1 seed per agent per 24 hours.+ memorySeed: (agentId) => getLimiter('memory:seed', { limit: 1, window: '1 d' }).limit(agentId),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 182add6bf..6c1b597b2 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -760,6 +760,32 @@ create table if not exists skill_ratings (unique (user_id, skill_id));+-- ── agent_payments — autonomous agent-to-agent / agent-to-skill payment ledger ─+-- Inserted by skill-runtime after each paid skill call. status transitions:+-- pending → confirmed (on-chain tx broadcast succeeded)+-- pending → failed (insufficient balance or tx error)+create table if not exists agent_payments (+ id uuid primary key default gen_random_uuid(),+ payer_agent_id uuid not null references agent_identities(id),+ payee_agent_id uuid references agent_identities(id), -- null when paying a skill author+ skill_id uuid references marketplace_skills(id),+ amount_wei numeric(40) not null,+ chain_id integer not null,+ tx_hash text,+ memo text,+ status text not null default 'pending',+ created_at timestamptz not null default now(),+ constraint agent_payments_status_check+ check (status in ('pending', 'confirmed', 'failed'))+);++create index if not exists agent_payments_payer_time+ on agent_payments(payer_agent_id, created_at desc);+create index if not exists agent_payments_payee_time+ on agent_payments(payee_agent_id, created_at desc) where payee_agent_id is not null;+create index if not exists agent_payments_status+ on agent_payments(status, created_at desc);+-- Additive migration: royalty pricing on skills.alter table marketplace_skills add column if not exists price_per_call_usd numeric(10,6) not null default 0;@@ -835,3 +861,30 @@ create table if not exists subscription_payments (create index if not exists subscription_payments_subscription_idxon subscription_payments(subscription_id);++-- ── social_connections ────────────────────────────────────────────────────────+create table if not exists social_connections (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ provider text not null,+ provider_uid text not null,+ username text not null,+ access_token text not null,+ scopes text not null,+ connected_at timestamptz not null default now(),+ unique(user_id, provider)+);++create index if not exists social_connections_user_idx on social_connections(user_id);++-- Additive migrations for social_connections added after initial deployment.+alter table social_connections add column if not exists refresh_token text;+alter table social_connections add column if not exists expires_at timestamptz;+alter table social_connections add column if not exists raw_data jsonb not null default '{}'::jsonb;+alter table social_connections add column if not exists disconnected_at timestamptz;+alter table social_connections add column if not exists updated_at timestamptz not null default now();+-- provider_uid holds the provider's user ID (e.g. Twitter numeric ID)++-- Additive migrations for agent_identities — X social seeding+alter table agent_identities add column if not exists x_username text;+alter table agent_identities add column if not exists x_seeded_at timestamptz;diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.jsindex c1a14c32b..e6b26cf48 100644--- a/api/_lib/skill-runtime.js+++ b/api/_lib/skill-runtime.js@@ -151,6 +151,19 @@ export function makeRuntime(opts = {}) {.catch((e) => console.error('[skill-runtime] royalty billing failed', e?.message));});}++ // Record autonomous agent payment in agent_payments ledger.+ queueMicrotask(() => {+ import('./agent-wallet.js')+ .then(({ triggerSkillPayment }) =>+ triggerSkillPayment({+ agentId,+ skillSlug: skillName,+ skillId: skillMeta[skillName]?.skill_id ?? null,+ }),+ )+ .catch((e) => console.error('[skill-runtime] agent payment failed', e?.message));+ });}return result;diff --git a/api/_lib/subscription-billing.js b/api/_lib/subscription-billing.jsnew file mode 100644index 000000000..c60e8d1b4--- /dev/null+++ b/api/_lib/subscription-billing.js@@ -0,0 +1,130 @@+/**+ * Subscription billing — charge a creator subscription via x402.+ *+ * x402 is a request-payment protocol: the server emits a 402 challenge, and+ * the client pays. It does not support server-initiated pulls from a stored+ * wallet. So the flow here is:+ * 1. Record a `subscription_payments` row as 'pending'.+ * 2. If we can construct an x402 payment request from the subscriber's stored+ * wallet_address, include it in the response so the caller can forward it+ * to the subscriber for approval.+ * 3. Return { success: false, pending: true, paymentId } — the caller must+ * notify the subscriber out-of-band to approve the charge.+ *+ * When a subscriber approves (via the client) and the tx lands, the payment+ * status is updated to 'succeeded' by a future confirm endpoint (not yet built).+ */++import { sql } from './db.js';++/**+ * Attempt to charge a subscription for its current period.+ * Creates a subscription_payments record and returns the result.+ *+ * @param {string} subscriptionId+ * @returns {Promise<{ success: boolean, pending?: boolean, paymentId: string, error?: string }>}+ */+export async function chargeSubscription(subscriptionId) {+ const [row] = await sql`+ SELECT+ cs.id, cs.plan_id, cs.subscriber_user_id, cs.wallet_address,+ cs.current_period_end, cs.payment_method,+ sp.price_usd, sp.creator_id,+ u.email AS subscriber_email+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ JOIN users u ON u.id = cs.subscriber_user_id+ WHERE cs.id = ${subscriptionId}+ `;++ if (!row) {+ return { success: false, error: 'subscription_not_found' };+ }++ // Create the payment record.+ const [payment] = await sql`+ INSERT INTO subscription_payments (subscription_id, amount_usd, status)+ VALUES (${subscriptionId}, ${row.price_usd}, 'pending')+ RETURNING id, status, amount_usd+ `;++ // x402 does not support server-initiated pulls from a stored wallet.+ // Log clearly and return pending so the cron/caller knows to notify subscriber.+ if (row.payment_method === 'x402') {+ console.log(JSON.stringify({+ event: 'subscription_billing.pending',+ subscription_id: subscriptionId,+ payment_id: payment.id,+ amount_usd: row.price_usd,+ wallet_address: row.wallet_address || null,+ note: 'x402 server-pull not yet supported; subscriber must approve payment',+ }));+ return { success: false, pending: true, paymentId: payment.id };+ }++ // Future payment methods (e.g. pre-authorized Solana delegation) can be+ // added here. For now treat any unknown method as pending.+ return { success: false, pending: true, paymentId: payment.id };+}++/**+ * Mark a pending payment as succeeded (called from a webhook or confirm endpoint).+ *+ * @param {string} paymentId+ * @param {string} txHash+ */+export async function confirmPayment(paymentId, txHash) {+ const [payment] = await sql`+ UPDATE subscription_payments+ SET status = 'succeeded', tx_hash = ${txHash}, paid_at = now()+ WHERE id = ${paymentId} AND status = 'pending'+ RETURNING id, subscription_id+ `;+ if (!payment) return { ok: false, error: 'payment_not_found_or_already_processed' };++ // Advance current_period_end on the subscription.+ const [sub] = await sql`+ SELECT cs.current_period_end, sp.interval+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ WHERE cs.id = ${payment.subscription_id}+ `;+ if (sub) {+ const periodMs = sub.interval === 'weekly' ? 7 * 24 * 3600 * 1000 : 30 * 24 * 3600 * 1000;+ const nextEnd = new Date(new Date(sub.current_period_end).getTime() + periodMs).toISOString();+ await sql`+ UPDATE creator_subscriptions+ SET current_period_end = ${nextEnd}, status = 'active'+ WHERE id = ${payment.subscription_id}+ `;+ }++ return { ok: true, paymentId };+}++/**+ * Mark a payment as failed and optionally set subscription to past_due.+ *+ * @param {string} paymentId+ * @param {string} subscriptionId+ */+export async function failPayment(paymentId, subscriptionId) {+ await sql`+ UPDATE subscription_payments SET status = 'failed'+ WHERE id = ${paymentId}+ `;++ // Count failures for this subscription to decide whether to set past_due.+ const [{ failCount }] = await sql`+ SELECT count(*)::int AS "failCount"+ FROM subscription_payments+ WHERE subscription_id = ${subscriptionId} AND status = 'failed'+ `;++ if (failCount >= 3) {+ await sql`+ UPDATE creator_subscriptions SET status = 'past_due'+ WHERE id = ${subscriptionId} AND status = 'active'+ `;+ }+}diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 93fb7acc9..33045d5e2 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -87,6 +87,10 @@ export default wrap(async function handler(req, res) {const mod = await import('./_id/memory/pin.js');return mod.default(req, res);}+ if (action === 'seed') {+ const mod = await import('./_id/memory-seed-farcaster.js');+ return mod.default(req, res);+ }if (action && CID_RE.test(action)) {const mod = await import('./_id/memory/[cid].js');return mod.default(req, res);@@ -109,5 +113,15 @@ export default wrap(async function handler(req, res) {return mod.handleVoice(req, res, id, action);}+ if (sub === 'persona') {+ const mod = await import('./_id/persona.js');+ return mod.handlePersona(req, res, id, action);+ }++ if (sub === 'payments') {+ const mod = await import('./_id/payments.js');+ return mod.handlePayments(req, res, id);+ }+return handleGetOne(req, res, id);});diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.jsnew file mode 100644index 000000000..188584e2b--- /dev/null+++ b/api/agents/[id]/memory-seed-x.js@@ -0,0 +1,226 @@+// POST /api/agents/:id/memory/seed/x — fetch X tweets, distil to facts, seed agent memory.+// GET /api/agents/:id/memory/seed/x — return connection status and last seed info.+//+// Auth: session user must own the agent AND have an active 'x' social_connection.+// Rate limit: 1 seed per agent per 6 hours.++import Anthropic from '@anthropic-ai/sdk';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { decryptToken, encryptToken } from '../../auth/x/[action].js';++// ── Token refresh ─────────────────────────────────────────────────────────────++async function refreshXToken(conn) {+ if (!conn.refresh_token) throw Object.assign(new Error('no refresh token'), { status: 400 });+ const decRefresh = decryptToken(conn.refresh_token);+ const creds = Buffer.from(+ `${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`,+ ).toString('base64');+ const res = await fetch('https://api.twitter.com/2/oauth2/token', {+ method: 'POST',+ headers: {+ 'content-type': 'application/x-www-form-urlencoded',+ authorization: `Basic ${creds}`,+ },+ body: new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: decRefresh,+ client_id: env.X_OAUTH_CLIENT_ID,+ }).toString(),+ });+ if (!res.ok) {+ const txt = await res.text();+ throw Object.assign(new Error('token refresh failed: ' + txt), { status: 502 });+ }+ const tokens = await res.json();+ const expiresAt = new Date(Date.now() + (tokens.expires_in ?? 7200) * 1000).toISOString();+ const encAccess = encryptToken(tokens.access_token);+ const encRefresh = tokens.refresh_token ? encryptToken(tokens.refresh_token) : conn.refresh_token;+ await sql`+ UPDATE social_connections+ SET access_token = ${encAccess},+ refresh_token = ${encRefresh},+ expires_at = ${expiresAt},+ updated_at = now()+ WHERE id = ${conn.id}+ `;+ return tokens.access_token;+}++async function getAccessToken(conn) {+ if (!conn.expires_at || new Date(conn.expires_at) <= new Date(Date.now() + 60_000)) {+ return refreshXToken(conn);+ }+ return decryptToken(conn.access_token);+}++// ── Distil tweets → facts via Claude ─────────────────────────────────────────++async function distilFacts(profile, tweets) {+ const client = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY });+ const tweetLines = tweets.map((t) => t.text).join('\n');++ const msg = await client.messages.create({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 1024,+ system: 'You distill tweets into concise memory facts for an AI agent. Focus on: recurring topics, strong opinions, projects, communication style, humor.',+ messages: [+ {+ role: 'user',+ content: `Profile: @${profile.username} | ${profile.description || ''} | ${profile.public_metrics?.followers_count ?? 0} followers\n\nRecent tweets (newest first):\n${tweetLines}`,+ },+ ],+ tools: [+ {+ name: 'extract_memory_facts',+ description: 'Extract up to 15 concise single-sentence memory facts from the tweets.',+ input_schema: {+ type: 'object',+ properties: {+ facts: {+ type: 'array',+ items: { type: 'string' },+ maxItems: 15,+ },+ },+ required: ['facts'],+ },+ },+ ],+ tool_choice: { type: 'tool', name: 'extract_memory_facts' },+ });++ const toolUse = msg.content.find((b) => b.type === 'tool_use');+ return toolUse?.input?.facts ?? [];+}++// ── GET — status ──────────────────────────────────────────────────────────────++async function handleGet(req, res, agentId) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const [agent] = await sql`+ SELECT id, user_id, x_username, x_seeded_at FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');++ const [conn] = await sql`+ SELECT id, username FROM social_connections+ WHERE user_id = ${user.id} AND provider = 'x'+ AND (disconnected_at IS NULL OR disconnected_at > now())+ LIMIT 1+ `;++ const [{ count }] = await sql`+ SELECT count(*)::int AS count FROM agent_memories+ WHERE agent_id = ${agentId} AND tags && ARRAY['x']::text[]+ `;++ return json(res, 200, {+ connected: !!conn,+ username: conn?.username ?? agent.x_username ?? null,+ seeded_at: agent.x_seeded_at ?? null,+ fact_count: count,+ });+}++// ── POST — seed ───────────────────────────────────────────────────────────────++async function handlePost(req, res, agentId) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.xSeed(agentId);+ if (!rl.success) return error(res, 429, 'rate_limited', 'agent can only be re-seeded every 6 hours');++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');++ const [conn] = await sql`+ SELECT id, username, access_token, refresh_token, expires_at FROM social_connections+ WHERE user_id = ${user.id} AND provider = 'x'+ AND (disconnected_at IS NULL OR disconnected_at > now())+ LIMIT 1+ `;+ if (!conn) return error(res, 400, 'not_connected', 'connect your X account first');++ const accessToken = await getAccessToken(conn);++ // Fetch profile+ const profileRes = await fetch(+ 'https://api.twitter.com/2/users/me?user.fields=name,username,description,public_metrics',+ { headers: { authorization: `Bearer ${accessToken}` } },+ );+ if (!profileRes.ok) {+ throw Object.assign(new Error('X profile fetch failed'), { status: 502 });+ }+ const { data: profile } = await profileRes.json();++ // Fetch up to 100 recent original tweets+ const tweetsRes = await fetch(+ `https://api.twitter.com/2/users/${profile.id}/tweets?max_results=100&exclude=retweets,replies&tweet.fields=text,created_at`,+ { headers: { authorization: `Bearer ${accessToken}` } },+ );+ if (!tweetsRes.ok) {+ throw Object.assign(new Error('X tweets fetch failed'), { status: 502 });+ }+ const tweetsJson = await tweetsRes.json();+ const tweets = tweetsJson.data ?? [];++ const facts = await distilFacts(profile, tweets);++ // Delete old x-tagged memories for this agent, then insert fresh ones+ await sql`+ DELETE FROM agent_memories+ WHERE agent_id = ${agentId} AND tags && ARRAY['x']::text[]+ `;++ if (facts.length > 0) {+ const rows = facts.map((fact) => ({+ agent_id: agentId,+ type: 'reference',+ content: fact,+ tags: ['x', 'x_seed'],+ context: JSON.stringify({ source: 'x_seed', username: profile.username }),+ salience: 0.7,+ }));+ for (const row of rows) {+ await sql`+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)+ VALUES (${row.agent_id}, ${row.type}, ${row.content}, ${row.tags}, ${row.context}::jsonb, ${row.salience})+ `;+ }+ }++ // Update agent_identities with x_username and x_seeded_at+ await sql`+ UPDATE agent_identities+ SET x_username = ${profile.username}, x_seeded_at = now()+ WHERE id = ${agentId}+ `;++ return json(res, 200, { username: profile.username, seeded: facts.length, facts });+}++// ── dispatch ──────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ const agentId = req.query?.id;+ if (!agentId) return error(res, 400, 'validation_error', 'agent id required');++ if (req.method === 'GET') return handleGet(req, res, agentId);+ if (req.method === 'POST') return handlePost(req, res, agentId);+ return method(req, res, ['GET', 'POST']);+});diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.jsindex e1235795c..9a1dc7e6a 100644--- a/api/agents/_id/_sub.js+++ b/api/agents/_id/_sub.js@@ -136,7 +136,7 @@ export const handleManifest = wrap(async (req, res, id) => {if (!/^[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, a.voice_provider, a.voice_id, 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`;+ 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, a.voice_provider, a.voice_id, a.persona_prompt_hash, a.persona_tone_tags, a.persona_extracted_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 = '';@@ -163,6 +163,11 @@ export const handleManifest = wrap(async (req, res, id) => {voice: row.voice_id? { provider: row.voice_provider || 'elevenlabs', voice_id: row.voice_id }: { provider: 'browser' },+ persona: {+ has_persona: Boolean(row.persona_prompt_hash),+ tone_tags: row.persona_tone_tags || [],+ extracted_at: row.persona_extracted_at || null,+ },createdAt: row.created_at,};diff --git a/api/agents/_id/payments.js b/api/agents/_id/payments.jsnew file mode 100644index 000000000..17d5e7812--- /dev/null+++ b/api/agents/_id/payments.js@@ -0,0 +1,67 @@+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';++// GET /api/agents/:id/payments?direction=sent|received&limit=20&cursor=+export const handlePayments = wrap(async (req, res, id) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) 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 requests');++ const [agent] = await sql`+ select id from agent_identities+ where id = ${id} and user_id = ${user.id} and deleted_at is null+ limit 1+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ const url = new URL(req.url, 'http://x');+ const direction = url.searchParams.get('direction') === 'received' ? 'received' : 'sent';+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10), 100);+ const cursor = url.searchParams.get('cursor') || null;++ let rows;+ if (direction === 'sent') {+ rows = await sql`+ select+ ap.id, ap.payer_agent_id, ap.payee_agent_id,+ ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,+ ms.name as skill_name, ms.slug as skill_slug,+ payee.name as payee_name+ from agent_payments ap+ left join marketplace_skills ms on ms.id = ap.skill_id+ left join agent_identities payee on payee.id = ap.payee_agent_id+ where ap.payer_agent_id = ${id}+ and (${cursor}::uuid is null or ap.id < ${cursor}::uuid)+ order by ap.created_at desc+ limit ${limit + 1}+ `;+ } else {+ rows = await sql`+ select+ ap.id, ap.payer_agent_id, ap.payee_agent_id,+ ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,+ ms.name as skill_name, ms.slug as skill_slug,+ payer.name as payer_name+ from agent_payments ap+ left join marketplace_skills ms on ms.id = ap.skill_id+ left join agent_identities payer on payer.id = ap.payer_agent_id+ where ap.payee_agent_id = ${id}+ and (${cursor}::uuid is null or ap.id < ${cursor}::uuid)+ order by ap.created_at desc+ limit ${limit + 1}+ `;+ }++ const hasMore = rows.length > limit;+ const page = hasMore ? rows.slice(0, limit) : rows;+ const nextCursor = hasMore ? page[page.length - 1].id : null;++ return json(res, 200, { payments: page, next_cursor: nextCursor, direction });+});diff --git a/api/auth/github/[action].js b/api/auth/github/[action].jsnew file mode 100644index 000000000..99bf54ae8--- /dev/null+++ b/api/auth/github/[action].js@@ -0,0 +1,209 @@+// GitHub OAuth social connect.+// Routes: /api/auth/github/connect — redirect to GitHub OAuth+// /api/auth/github/callback — exchange code, store encrypted token+// /api/auth/github/status — connection status for the signed-in user++import { webcrypto } from 'node:crypto';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';+import { cors, json, redirect, error, wrap } from '../../_lib/http.js';+import { env } from '../../_lib/env.js';++const subtle = globalThis.crypto?.subtle || webcrypto.subtle;++// ── Key derivation (HKDF from JWT_SECRET, info = 'github-token') ──────────────++async function deriveKey() {+ const raw = new TextEncoder().encode(env.JWT_SECRET);+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);+ return subtle.deriveKey(+ {+ name: 'HKDF',+ hash: 'SHA-256',+ salt: new TextEncoder().encode('github-token'),+ info: new Uint8Array(0),+ },+ base,+ { name: 'AES-GCM', length: 256 },+ false,+ ['encrypt', 'decrypt'],+ );+}++async function encryptToken(plaintext) {+ const key = await deriveKey();+ const iv = new Uint8Array(12);+ (globalThis.crypto || webcrypto).getRandomValues(iv);+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));+ const buf = new Uint8Array(iv.length + ct.byteLength);+ buf.set(iv, 0);+ buf.set(new Uint8Array(ct), iv.length);+ return Buffer.from(buf).toString('base64');+}++// ── CSRF state (HMAC-signed payload) ─────────────────────────────────────────++async function makeState(payload) {+ const data = Buffer.from(JSON.stringify(payload)).toString('base64url');+ const sig = await hmacSha256(env.JWT_SECRET, data);+ return `${data}.${sig}`;+}++async function verifyState(state) {+ const dotIdx = state.lastIndexOf('.');+ if (dotIdx < 0) throw Object.assign(new Error('invalid state'), { status: 400 });+ const data = state.slice(0, dotIdx);+ const sig = state.slice(dotIdx + 1);+ const expected = await hmacSha256(env.JWT_SECRET, data);+ if (!constantTimeEquals(sig, expected)) throw Object.assign(new Error('invalid state signature'), { status: 400 });+ return JSON.parse(Buffer.from(data, 'base64url').toString());+}++// ── connect ───────────────────────────────────────────────────────────────────++async function handleConnect(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;++ if (!env.GITHUB_OAUTH_CLIENT_ID) {+ return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');+ }++ 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('agent_id') || '';++ const state = await makeState({ userId: session.id, agentId, ts: Date.now() });+ const redirectUri = `${env.APP_ORIGIN}/api/auth/github/callback`;++ const ghUrl = new URL('https://github.com/login/oauth/authorize');+ ghUrl.searchParams.set('client_id', env.GITHUB_OAUTH_CLIENT_ID);+ ghUrl.searchParams.set('redirect_uri', redirectUri);+ ghUrl.searchParams.set('scope', 'read:user,public_repo');+ ghUrl.searchParams.set('state', state);++ return redirect(res, ghUrl.toString());+}++// ── callback ──────────────────────────────────────────────────────────────────++async function handleCallback(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;++ if (!env.GITHUB_OAUTH_CLIENT_ID || !env.GITHUB_OAUTH_CLIENT_SECRET) {+ return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');+ }++ const url = new URL(req.url, 'http://x');+ const code = url.searchParams.get('code');+ const stateParam = url.searchParams.get('state');+ const ghError = url.searchParams.get('error');++ if (ghError) {+ return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=denied`);+ }+ if (!code || !stateParam) return error(res, 400, 'bad_request', 'missing code or state');++ let stateData;+ try {+ stateData = await verifyState(stateParam);+ } catch {+ return error(res, 400, 'invalid_state', 'invalid or tampered state parameter');+ }++ if (Date.now() - stateData.ts > 10 * 60 * 1000) {+ return error(res, 400, 'state_expired', 'OAuth state has expired — please try again');+ }++ // Exchange code for access token+ const tokenRes = await fetch('https://github.com/login/oauth/access_token', {+ method: 'POST',+ headers: { accept: 'application/json', 'content-type': 'application/json' },+ body: JSON.stringify({+ client_id: env.GITHUB_OAUTH_CLIENT_ID,+ client_secret: env.GITHUB_OAUTH_CLIENT_SECRET,+ code,+ redirect_uri: `${env.APP_ORIGIN}/api/auth/github/callback`,+ }),+ });+ if (!tokenRes.ok) {+ return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);+ }+ const tokenData = await tokenRes.json();+ if (tokenData.error || !tokenData.access_token) {+ return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);+ }++ // Fetch GitHub user profile+ const profileRes = await fetch('https://api.github.com/user', {+ headers: {+ authorization: `token ${tokenData.access_token}`,+ 'user-agent': 'three.ws/1.0',+ },+ });+ if (!profileRes.ok) {+ return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);+ }+ const profile = await profileRes.json();++ const encryptedToken = await encryptToken(tokenData.access_token);++ await sql`+ INSERT INTO social_connections (user_id, provider, provider_uid, username, access_token, scopes)+ VALUES (+ ${stateData.userId},+ 'github',+ ${String(profile.id)},+ ${profile.login},+ ${encryptedToken},+ ${tokenData.scope || 'read:user,public_repo'}+ )+ ON CONFLICT (user_id, provider) DO UPDATE SET+ provider_uid = EXCLUDED.provider_uid,+ username = EXCLUDED.username,+ access_token = EXCLUDED.access_token,+ scopes = EXCLUDED.scopes,+ connected_at = now()+ `;++ const dest = stateData.agentId+ ? `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=connected&agent_id=${encodeURIComponent(stateData.agentId)}`+ : `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=connected`;++ return redirect(res, dest);+}++// ── status ────────────────────────────────────────────────────────────────────++async function handleStatus(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const [row] = await sql`+ SELECT username, connected_at FROM social_connections+ WHERE user_id = ${session.id} AND provider = 'github'+ `;++ if (!row) return json(res, 200, { connected: false });+ return json(res, 200, {+ connected: true,+ username: row.username,+ connected_at: row.connected_at,+ });+}++// ── dispatch ──────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ const url = new URL(req.url, 'http://x');+ const action = url.searchParams.get('action') || url.pathname.split('/').filter(Boolean).pop();++ if (action === 'connect') return handleConnect(req, res);+ if (action === 'callback') return handleCallback(req, res);+ if (action === 'status') return handleStatus(req, res);+ return error(res, 404, 'not_found', 'unknown github auth action');+});diff --git a/api/auth/x/[action].js b/api/auth/x/[action].jsnew file mode 100644index 000000000..a78d71c02--- /dev/null+++ b/api/auth/x/[action].js@@ -0,0 +1,193 @@+// X (Twitter) OAuth 2.0 PKCE flow. Dispatches on ?action=connect|callback.+// Env required: X_OAUTH_CLIENT_ID, X_OAUTH_CLIENT_SECRET+// If unset, /connect returns 501 not_configured.++import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto';+import { Redis } from '@upstash/redis';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { sha256Base64Url, randomToken } from '../../_lib/crypto.js';+import { cors, method, wrap, error, redirect } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';++// ── Redis ─────────────────────────────────────────────────────────────────────++let _redis = null;+function getRedis() {+ if (_redis) return _redis;+ const url = env.UPSTASH_REDIS_REST_URL;+ const token = env.UPSTASH_REDIS_REST_TOKEN;+ if (!url || !token) throw Object.assign(new Error('Redis not configured'), { status: 503 });+ _redis = new Redis({ url, token });+ return _redis;+}++// ── Token encryption (AES-256-GCM, key from JWT_SECRET via HKDF) ─────────────++function _deriveKey() {+ return hkdfSync('sha256', Buffer.from(env.JWT_SECRET), '', 'x-token', 32);+}++export function encryptToken(plaintext) {+ const iv = randomBytes(12);+ const cipher = createCipheriv('aes-256-gcm', _deriveKey(), iv);+ const enc = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);+ const tag = cipher.getAuthTag();+ return `${iv.toString('base64url')}.${enc.toString('base64url')}.${tag.toString('base64url')}`;+}++export function decryptToken(ciphertext) {+ const parts = ciphertext.split('.');+ if (parts.length !== 3) throw new Error('malformed ciphertext');+ const [ivB64, encB64, tagB64] = parts;+ const decipher = createDecipheriv(+ 'aes-256-gcm',+ _deriveKey(),+ Buffer.from(ivB64, 'base64url'),+ );+ decipher.setAuthTag(Buffer.from(tagB64, 'base64url'));+ return Buffer.concat([+ decipher.update(Buffer.from(encB64, 'base64url')),+ decipher.final(),+ ]).toString('utf8');+}++// ── GET /api/auth/x/connect ───────────────────────────────────────────────────++async function handleConnect(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {+ return error(res, 501, 'not_configured', 'X OAuth is not configured');+ }++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const url = new URL(req.url, env.APP_ORIGIN);+ const agentId = url.searchParams.get('agent_id') || null;++ const codeVerifier = randomToken(32); // 43-char base64url+ const codeChallenge = await sha256Base64Url(codeVerifier);+ const state = randomToken(16);++ await getRedis().set(+ `x_oauth:${state}`,+ JSON.stringify({ code_verifier: codeVerifier, user_id: user.id, agent_id: agentId }),+ { ex: 600 },+ );++ const authUrl = new URL('https://twitter.com/i/oauth2/authorize');+ authUrl.searchParams.set('response_type', 'code');+ authUrl.searchParams.set('client_id', env.X_OAUTH_CLIENT_ID);+ authUrl.searchParams.set('redirect_uri', `${env.APP_ORIGIN}/api/auth/x/callback`);+ authUrl.searchParams.set('scope', 'tweet.read users.read offline.access');+ authUrl.searchParams.set('state', state);+ authUrl.searchParams.set('code_challenge', codeChallenge);+ authUrl.searchParams.set('code_challenge_method', 'S256');++ return redirect(res, authUrl.toString());+}++// ── GET /api/auth/x/callback ──────────────────────────────────────────────────++async function handleCallback(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {+ return error(res, 501, 'not_configured', 'X OAuth is not configured');+ }++ const url = new URL(req.url, env.APP_ORIGIN);+ const code = url.searchParams.get('code');+ const state = url.searchParams.get('state');++ if (url.searchParams.get('error')) {+ return redirect(res, `/settings?tab=connected-accounts&x=denied`);+ }+ if (!code || !state) return error(res, 400, 'validation_error', 'missing code or state');++ const r = getRedis();+ const raw = await r.get(`x_oauth:${state}`);+ if (!raw) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');+ await r.del(`x_oauth:${state}`);++ const stateData = typeof raw === 'string' ? JSON.parse(raw) : raw;+ const { code_verifier: codeVerifier, user_id: userId } = stateData;++ // Exchange code for tokens+ const creds = Buffer.from(`${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`).toString(+ 'base64',+ );+ const tokenRes = await fetch('https://api.twitter.com/2/oauth2/token', {+ method: 'POST',+ headers: {+ 'content-type': 'application/x-www-form-urlencoded',+ authorization: `Basic ${creds}`,+ },+ body: new URLSearchParams({+ code,+ grant_type: 'authorization_code',+ client_id: env.X_OAUTH_CLIENT_ID,+ redirect_uri: `${env.APP_ORIGIN}/api/auth/x/callback`,+ code_verifier: codeVerifier,+ }).toString(),+ });++ if (!tokenRes.ok) {+ console.error('[x-oauth] token exchange failed', await tokenRes.text());+ return redirect(res, `/settings?tab=connected-accounts&x=error`);+ }++ const tokens = await tokenRes.json();+ const { access_token, refresh_token, expires_in } = tokens;+ const expiresAt = new Date(Date.now() + (expires_in ?? 7200) * 1000).toISOString();++ // Fetch X profile+ const profileRes = await fetch(+ 'https://api.twitter.com/2/users/me?user.fields=name,username,description,public_metrics',+ { headers: { authorization: `Bearer ${access_token}` } },+ );+ if (!profileRes.ok) {+ console.error('[x-oauth] profile fetch failed', await profileRes.text());+ return redirect(res, `/settings?tab=connected-accounts&x=error`);+ }+ const { data: profile } = await profileRes.json();++ const encAccess = encryptToken(access_token);+ const encRefresh = refresh_token ? encryptToken(refresh_token) : null;++ // Upsert by (user_id, provider) — uses the existing unique constraint+ await sql`+ INSERT INTO social_connections+ (user_id, provider, provider_uid, username, access_token, refresh_token, expires_at, raw_data)+ VALUES+ (${userId}, 'x', ${profile.id}, ${profile.username}, ${encAccess}, ${encRefresh}, ${expiresAt}, ${JSON.stringify(profile)})+ ON CONFLICT (user_id, provider) DO UPDATE SET+ provider_uid = EXCLUDED.provider_uid,+ username = EXCLUDED.username,+ access_token = EXCLUDED.access_token,+ refresh_token = EXCLUDED.refresh_token,+ expires_at = EXCLUDED.expires_at,+ raw_data = EXCLUDED.raw_data,+ disconnected_at = NULL,+ updated_at = now()+ `;++ return redirect(res, `/settings?tab=connected-accounts&x=connected`);+}++// ── dispatch ──────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ const action = req.query?.action;+ if (action === 'connect') return handleConnect(req, res);+ if (action === 'callback') return handleCallback(req, res);+ return error(res, 404, 'not_found', 'unknown action');+});diff --git a/api/chat.js b/api/chat.jsindex 997142bd3..383acc2ed 100644--- a/api/chat.js+++ b/api/chat.js@@ -12,6 +12,7 @@ import { parse } from './_lib/validate.js';import { limits } from './_lib/rate-limit.js';import { recordEvent } from './_lib/usage.js';import { captureException } from './_lib/sentry.js';+import { sql } from './_lib/db.js';import { z } from 'zod';const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';@@ -42,6 +43,7 @@ const contextSchema = zconst chatBody = z.object({message: z.string().trim().min(1).max(4000),context: contextSchema,+ agentId: z.string().uuid().optional(),history: z.array(z.object({@@ -176,6 +178,15 @@ export default wrap(async (req, res) => {HARD_MAX_TOKENS,);+ let personaPrompt = null;+ if (body.agentId) {+ const [agentRow] = await sql`+ SELECT persona_prompt FROM agent_identities+ WHERE id = ${body.agentId} AND deleted_at IS NULL LIMIT 1+ `;+ if (agentRow?.persona_prompt) personaPrompt = agentRow.persona_prompt;+ }+const messages = [...body.history.map((m) => ({ role: m.role, content: m.content })),{ role: 'user', content: body.message },@@ -194,7 +205,7 @@ export default wrap(async (req, res) => {body: JSON.stringify({model,max_tokens: maxTokens,- system: buildSystemPrompt(body.context),+ system: buildSystemPrompt(body.context, personaPrompt),messages,tools: ACTION_TOOLS,}),@@ -243,7 +254,7 @@ export default wrap(async (req, res) => {return json(res, 200, { reply, actions, model });});-function buildSystemPrompt(ctx = {}) {+function buildSystemPrompt(ctx = {}, personaPrompt = null) {const loaded = ctx.modelName? `A model named "${ctx.modelName}" is loaded. Stats: ${fmt(ctx.vertices)} vertices, ${fmt(ctx.triangles)} triangles, ${fmt(ctx.materials)} materials, ${ctx.animations ?? 0} animations.`: 'No model is currently loaded in the viewer.';@@ -253,7 +264,9 @@ function buildSystemPrompt(ctx = {}) {: 'glTF validation has not been run yet for this model.';const settings = `Viewer settings — wireframe:${fmtBool(ctx.wireframe)}, skeleton:${fmtBool(ctx.skeleton)}, grid:${fmtBool(ctx.grid)}, autoRotate:${fmtBool(ctx.autoRotate)}, transparentBg:${fmtBool(ctx.transparentBg)}, bgColor:${ctx.bgColor || '?'}, environment:${ctx.currentEnvironment || '?'}.`;- return [+ const lines = [];+ if (personaPrompt) lines.push(personaPrompt, '');+ lines.push('You are the three.ws — an embodied AI assistant embedded inside a browser-native glTF/GLB viewer at three.ws.','Your job is to help the user inspect, understand, and modify the 3D scene. You have deep glTF 2.0, PBR materials, and three.js expertise.','When the user asks you to change the viewer (e.g. "enable wireframe", "make the background dark blue", "turn on auto rotate"), USE the provided tools to perform the change — do not just describe it.',@@ -263,7 +276,8 @@ function buildSystemPrompt(ctx = {}) {loaded,validation,settings,- ].join('\n');+ );+ return lines.join('\n');}function normalize(data) {diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 404cf23b1..5757e5356 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -9,6 +9,7 @@* Cron paths handled (kebab-case → handler):* erc8004-crawl → handleErc8004Crawl* index-delegations → handleIndexDelegations+ * process-subscriptions → handleProcessSubscriptions* pump-agent-stats → handlePumpAgentStats* pumpfun-monitor → handlePumpfunMonitor* pumpfun-signals → handlePumpfunSignals@@ -42,12 +43,15 @@ import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/attimport { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';import { crawlAgentAttestations } from '../_lib/solana-attestations.js';import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';+import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';+import { sendEmail } from '../_lib/email.js';// ─── Dispatcher ──────────────────────────────────────────────────────────────const HANDLERS = {'erc8004-crawl': handleErc8004Crawl,'index-delegations': handleIndexDelegations,+ 'process-subscriptions': handleProcessSubscriptions,'pump-agent-stats': handlePumpAgentStats,'pumpfun-monitor': handlePumpfunMonitor,'pumpfun-signals': handlePumpfunSignals,@@ -2149,3 +2153,120 @@ async function handleSolanaAttestationsCrawl(req, res) {return json(res, 200, report);}++// ═══════════════════════════════════════════════════════════════════════════+// process-subscriptions+// ═══════════════════════════════════════════════════════════════════════════++async function handleProcessSubscriptions(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const cronSecret = env.CRON_SECRET;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ const runId = `psub-${Date.now()}`;+ const report = { runId, processed: 0, charged: 0, pastDue: 0, errors: [] };++ // Find subscriptions whose period ends within the next hour (charge a bit+ // early to allow for retry windows before period actually expires).+ const dues = await sql`+ SELECT+ cs.id, cs.subscriber_user_id, cs.plan_id, cs.current_period_end,+ sp.price_usd,+ u.email AS subscriber_email,+ u.display_name AS subscriber_name+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ JOIN users u ON u.id = cs.subscriber_user_id+ WHERE cs.status = 'active'+ AND cs.current_period_end < now() + interval '1 hour'+ ORDER BY cs.current_period_end ASC+ LIMIT 200+ `;++ for (const row of dues) {+ report.processed++;+ try {+ // Count prior failed payments to decide retry vs. past_due.+ const [{ failCount }] = await sql`+ SELECT count(*)::int AS "failCount"+ FROM subscription_payments+ WHERE subscription_id = ${row.id} AND status = 'failed'+ `;++ if (failCount >= 3) {+ // Mark past_due and notify subscriber.+ await sql`+ UPDATE creator_subscriptions+ SET status = 'past_due'+ WHERE id = ${row.id} AND status = 'active'+ `;+ report.pastDue++;+ console.log(JSON.stringify({+ event: 'process_subscriptions.past_due',+ runId,+ subscriptionId: row.id,+ failCount,+ }));+ // Fire-and-forget email notification.+ sendEmail({+ to: row.subscriber_email,+ subject: 'Action required: subscription payment failed',+ html: `<p>Hi ${row.subscriber_name || 'there'},</p>+<p>We were unable to process your subscription payment of $${row.price_usd}. Your subscription has been paused. Please update your payment method to continue.</p>+<p><a href="${env.APP_ORIGIN}/dashboard#subscriptions">Manage subscriptions</a></p>`,+ text: `Your subscription payment of $${row.price_usd} could not be processed. Visit ${env.APP_ORIGIN}/dashboard#subscriptions to manage your subscriptions.`,+ }).catch((e) => console.error(JSON.stringify({+ event: 'process_subscriptions.email_failed',+ subscriptionId: row.id,+ error: e.message,+ })));+ continue;+ }++ const result = await chargeSubscription(row.id);+ if (result.pending) {+ report.charged++; // pending = payment request created+ } else if (!result.success) {+ await failPayment(result.paymentId, row.id);+ report.errors.push({ id: row.id, error: result.error || 'charge_failed' });+ } else {+ report.charged++;+ }+ } catch (e) {+ report.errors.push({ id: row.id, error: e.message || String(e) });+ console.error(JSON.stringify({+ event: 'process_subscriptions.row_error',+ runId,+ subscriptionId: row.id,+ error: e.message,+ }));+ }+ }++ console.log(JSON.stringify({ event: 'process_subscriptions.done', ...report }));+ return json(res, 200, report);+}++// ═══════════════════════════════════════════════════════════════════════════+// settle-royalties+// ═══════════════════════════════════════════════════════════════════════════++async function handleSettleRoyalties(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const cronSecret = env.CRON_SECRET;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ const { settleAllPendingRoyalties } = await import('../_lib/royalty.js');+ const report = await settleAllPendingRoyalties();+ return json(res, 200, { ok: true, ...report });+}diff --git a/api/subscriptions/index.js b/api/subscriptions/index.jsnew file mode 100644index 000000000..7034a8de1--- /dev/null+++ b/api/subscriptions/index.js@@ -0,0 +1,155 @@+/**+ * /api/subscriptions — subscriber-facing subscription management.+ *+ * Routes (via vercel.json):+ * POST /api/subscriptions subscribe to a plan (auth)+ * GET /api/subscriptions/mine list my active subscriptions (auth)+ * DELETE /api/subscriptions/:id cancel (auth, subscriber)+ * GET /api/subscriptions/:id detail (auth, subscriber or creator)+ */++import { z } from 'zod';+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 { chargeSubscription } from '../_lib/subscription-billing.js';++const subscribeSchema = z.object({+ plan_id: z.string().uuid(),+ wallet_address: z.string().min(1).max(200).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;++ const url = req.url || '';+ const pathMatch = url.match(/\/api\/subscriptions\/([^?/]+)/);+ const segment = pathMatch ? pathMatch[1] : null;++ if (segment === 'mine' && req.method === 'GET') return handleMine(req, res);+ if (!segment && req.method === 'POST') return handleSubscribe(req, res);+ if (segment && req.method === 'DELETE') return handleCancel(req, res, segment);+ if (segment && req.method === 'GET') return handleDetail(req, res, segment);++ return error(res, 405, 'method_not_allowed', 'method not allowed');+});++async function handleMine(req, res) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.publicIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const rows = await sql`+ SELECT+ cs.id, cs.plan_id, cs.status, cs.current_period_start, cs.current_period_end,+ cs.payment_method, cs.wallet_address, cs.created_at, cs.cancelled_at,+ sp.name AS plan_name, sp.price_usd, sp.interval,+ u.display_name AS creator_name, u.id AS creator_id+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ JOIN users u ON u.id = sp.creator_id+ WHERE cs.subscriber_user_id = ${user.id}+ ORDER BY cs.created_at DESC+ `;+ return json(res, 200, { subscriptions: rows });+}++async function handleSubscribe(req, res) {+ if (!method(req, res, ['POST'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.publicIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(subscribeSchema, await readJson(req));++ const [plan] = await sql`+ SELECT id, creator_id, price_usd, interval, active+ FROM subscription_plans WHERE id = ${body.plan_id}+ `;+ if (!plan) return error(res, 404, 'not_found', 'plan not found');+ if (!plan.active) return error(res, 409, 'conflict', 'plan is no longer active');+ if (plan.creator_id === user.id) return error(res, 409, 'conflict', 'cannot subscribe to your own plan');++ const periodMs = plan.interval === 'weekly' ? 7 * 24 * 3600 * 1000 : 30 * 24 * 3600 * 1000;+ const periodEnd = new Date(Date.now() + periodMs).toISOString();++ // Upsert guard: reject if already subscribed and active.+ const [existing] = await sql`+ SELECT id, status FROM creator_subscriptions+ WHERE plan_id = ${plan.id} AND subscriber_user_id = ${user.id}+ `;+ if (existing && existing.status === 'active') {+ return error(res, 409, 'conflict', 'already subscribed to this plan');+ }++ let sub;+ if (existing) {+ // Re-activate a cancelled subscription.+ [sub] = await sql`+ UPDATE creator_subscriptions+ SET status = 'active',+ current_period_start = now(),+ current_period_end = ${periodEnd},+ wallet_address = ${body.wallet_address ?? null},+ cancelled_at = NULL+ WHERE id = ${existing.id}+ RETURNING *+ `;+ } else {+ [sub] = await sql`+ INSERT INTO creator_subscriptions+ (plan_id, subscriber_user_id, current_period_end, wallet_address)+ VALUES (${plan.id}, ${user.id}, ${periodEnd}, ${body.wallet_address ?? null})+ RETURNING *+ `;+ }++ // Attempt first payment immediately (non-blocking on failure).+ const billing = await chargeSubscription(sub.id);++ return json(res, 201, { subscription: sub, payment: billing });+}++async function handleCancel(req, res, subId) {+ if (!method(req, res, ['DELETE'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const [sub] = await sql`+ UPDATE creator_subscriptions+ SET status = 'cancelled', cancelled_at = now()+ WHERE id = ${subId} AND subscriber_user_id = ${user.id}+ RETURNING id, status+ `;+ if (!sub) return error(res, 404, 'not_found', 'subscription not found');++ return json(res, 200, { ok: true, subscription: sub });+}++async function handleDetail(req, res, subId) {+ if (!method(req, res, ['GET'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const [sub] = await sql`+ SELECT+ cs.*, sp.name AS plan_name, sp.price_usd, sp.interval, sp.creator_id,+ u.display_name AS creator_name+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ JOIN users u ON u.id = sp.creator_id+ WHERE cs.id = ${subId}+ AND (cs.subscriber_user_id = ${user.id} OR sp.creator_id = ${user.id})+ `;+ if (!sub) return error(res, 404, 'not_found', 'subscription not found');++ return json(res, 200, { subscription: sub });+}diff --git a/api/subscriptions/plans.js b/api/subscriptions/plans.jsnew file mode 100644index 000000000..78a81b1c7--- /dev/null+++ b/api/subscriptions/plans.js@@ -0,0 +1,145 @@+/**+ * /api/subscriptions/plans — creator subscription plan management.+ *+ * Routes (via vercel.json):+ * GET /api/subscriptions/plans?creator_id= list active plans (public)+ * POST /api/subscriptions/plans create plan (auth, max 3)+ * PATCH /api/subscriptions/plans/:id update name/price/perks (auth, owner)+ * DELETE /api/subscriptions/plans/:id soft-delete (auth, owner)+ */++import { z } from 'zod';+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';++const planSchema = z.object({+ agent_id: z.string().uuid().optional(),+ name: z.string().trim().min(2).max(80),+ price_usd: z.number().min(0.99).max(999),+ interval: z.enum(['weekly', 'monthly']).default('monthly'),+ perks: z.array(z.string().trim().max(120)).max(10).default([]),+});++const patchSchema = z.object({+ name: z.string().trim().min(2).max(80).optional(),+ price_usd: z.number().min(0.99).max(999).optional(),+ perks: z.array(z.string().trim().max(120)).max(10).optional(),+ active: z.boolean().optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;++ // Extract path param: /api/subscriptions/plans/:id+ const url = req.url || '';+ const pathMatch = url.match(/\/api\/subscriptions\/plans\/([^?/]+)/);+ const planId = pathMatch ? pathMatch[1] : null;++ if (req.method === 'GET') return handleList(req, res);+ if (req.method === 'POST' && !planId) return handleCreate(req, res);+ if (req.method === 'PATCH' && planId) return handlePatch(req, res, planId);+ if (req.method === 'DELETE' && planId) return handleDelete(req, res, planId);++ return error(res, 405, 'method_not_allowed', 'method not allowed');+});++async function handleList(req, res) {+ const ip = clientIp(req);+ const rl = await limits.publicIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const creatorId = new URL(req.url, 'http://x').searchParams.get('creator_id');+ if (!creatorId) return error(res, 400, 'validation_error', 'creator_id required');++ const rows = await sql`+ SELECT id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ FROM subscription_plans+ WHERE creator_id = ${creatorId} AND active = true+ ORDER BY created_at ASC+ `;+ return json(res, 200, { plans: rows });+}++async function handleCreate(req, res) {+ if (!method(req, res, ['POST'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.publicIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(planSchema, await readJson(req));++ // Enforce max 3 active plans per creator.+ const [{ count }] = await sql`+ SELECT count(*)::int AS count FROM subscription_plans+ WHERE creator_id = ${user.id} AND active = true+ `;+ if (count >= 3) return error(res, 409, 'conflict', 'maximum 3 active plans per creator');++ // Verify agent_id belongs to creator if provided.+ if (body.agent_id) {+ const [agent] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${body.agent_id} AND user_id = ${user.id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 403, 'forbidden', 'agent not found or not owned by you');+ }++ const [plan] = await sql`+ INSERT INTO subscription_plans (creator_id, agent_id, name, price_usd, interval, perks)+ VALUES (${user.id}, ${body.agent_id ?? null}, ${body.name}, ${body.price_usd},+ ${body.interval}, ${body.perks})+ RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ `;+ return json(res, 201, { plan });+}++async function handlePatch(req, res, planId) {+ if (!method(req, res, ['PATCH'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const body = parse(patchSchema, await readJson(req));++ const [existing] = await sql`+ SELECT id FROM subscription_plans WHERE id = ${planId} AND creator_id = ${user.id}+ `;+ if (!existing) return error(res, 404, 'not_found', 'plan not found');++ const sets = [];+ if (body.name !== undefined) sets.push(sql`name = ${body.name}`);+ if (body.price_usd !== undefined) sets.push(sql`price_usd = ${body.price_usd}`);+ if (body.perks !== undefined) sets.push(sql`perks = ${body.perks}`);+ if (body.active !== undefined) sets.push(sql`active = ${body.active}`);++ if (sets.length === 0) return error(res, 400, 'validation_error', 'nothing to update');++ const [plan] = await sql`+ UPDATE subscription_plans+ SET ${sql.join(sets, sql`, `)}+ WHERE id = ${planId} AND creator_id = ${user.id}+ RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ `;+ return json(res, 200, { plan });+}++async function handleDelete(req, res, planId) {+ if (!method(req, res, ['DELETE'])) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const [plan] = await sql`+ UPDATE subscription_plans+ SET active = false+ WHERE id = ${planId} AND creator_id = ${user.id}+ RETURNING id+ `;+ if (!plan) return error(res, 404, 'not_found', 'plan not found');++ return json(res, 200, { ok: true });+}diff --git a/api/users/earnings.js b/api/users/earnings.jsnew file mode 100644index 000000000..0087a5afe--- /dev/null+++ b/api/users/earnings.js@@ -0,0 +1,51 @@+import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, error, method, wrap } 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: 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');+ const userId = session?.id ?? bearer.userId;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const rows = await sql`+ SELECT+ rl.id,+ rl.price_usd,+ rl.status,+ rl.created_at,+ ms.name AS skill_name,+ ai.name AS agent_name+ FROM royalty_ledger rl+ JOIN marketplace_skills ms ON ms.id = rl.skill_id+ JOIN agent_identities ai ON ai.id = rl.agent_id+ WHERE rl.author_user_id = ${userId}+ ORDER BY rl.created_at DESC+ LIMIT 100+ `;++ const pending_usd = rows+ .filter((r) => r.status === 'pending')+ .reduce((s, r) => s + Number(r.price_usd), 0);++ const settled_usd = rows+ .filter((r) => r.status === 'settled')+ .reduce((s, r) => s + Number(r.price_usd), 0);++ const entries = rows.map((r) => ({+ skill_name: r.skill_name,+ agent_name: r.agent_name,+ price_usd: Number(r.price_usd),+ status: r.status,+ created_at: r.created_at,+ }));++ return json(res, 200, { pending_usd, settled_usd, entries });+});diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelteindex a666ec5ff..994ebbd14 100644--- a/chat/src/SkillsMarketplaceModal.svelte+++ b/chat/src/SkillsMarketplaceModal.svelte@@ -48,7 +48,8 @@null,2),- isPublic: true+ isPublic: true,+ pricePerCallUsd: 0};let publishError = null;let publishLoading = false;@@ -312,7 +313,8 @@category: publishForm.category,tags,schema_json: JSON.parse(publishForm.schemaText),- is_public: publishForm.isPublic+ is_public: publishForm.isPublic,+ price_per_call_usd: Math.min(10, Math.max(0, Number(publishForm.pricePerCallUsd) || 0))})});if (!res.ok) {@@ -910,6 +912,24 @@</div></div>+ <div class="flex flex-col gap-y-1">+ <label for="pf-price" class="text-[12px] font-medium text-slate-600">Price per call (USD)</label>+ <div class="flex items-center gap-x-2">+ <span class="text-[12px] text-slate-500">$</span>+ <input+ id="pf-price"+ type="number"+ min="0"+ max="10"+ step="0.0001"+ bind:value={publishForm.pricePerCallUsd}+ class="w-28 rounded-md border border-slate-200 px-2 py-1 text-[13px] outline-none focus:border-indigo-400"+ placeholder="0.0000"+ />+ <span class="text-[11px] text-slate-400">Leave 0 for free</span>+ </div>+ </div>+<div class="flex items-center gap-x-2"><inputid="skill-public"diff --git a/contracts/src/IdentityRegistry.sol b/contracts/src/IdentityRegistry.solindex 14d2ab1dc..2c8c96aa4 100644--- a/contracts/src/IdentityRegistry.sol+++ b/contracts/src/IdentityRegistry.sol@@ -6,12 +6,13 @@ import {ERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";+import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";/// @title ERC-8004 Identity Registry/// @notice Agents are minted as ERC-721 tokens with a `tokenURI` pointing to an/// ERC-8004 registration JSON. Each agent can optionally delegate a/// separate wallet address and store arbitrary key/value metadata.-contract IdentityRegistry is ERC721Enumerable, EIP712 {+contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {// ---------------------------------------------------------------------// Types// ---------------------------------------------------------------------@@ -32,6 +33,9 @@ contract IdentityRegistry is ERC721Enumerable, EIP712 {mapping(uint256 => mapping(string => bytes)) private _metadata;mapping(address => uint256) public nonces;+ // Max spend per on-chain agent ID per authorized spender (set by agent NFT owner)+ mapping(uint256 => mapping(address => uint256)) public spendAllowance;+// EIP-712 typehash for delegated wallet binding.bytes32 private constant _SET_WALLET_TYPEHASH = keccak256("SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"@@ -45,6 +49,14 @@ contract IdentityRegistry is ERC721Enumerable, EIP712 {event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy);event WalletSet(uint256 indexed agentId, address indexed wallet);event WalletUnset(uint256 indexed agentId);+ event SpendAllowanceSet(uint256 indexed agentId, address indexed spender, uint256 maxWei);+ event AgentPayment(+ uint256 indexed agentId,+ address indexed spender,+ address indexed recipient,+ uint256 amountWei,+ string memo+ );event MetadataSet(uint256 indexed agentId,string indexed indexedMetadataKey,@@ -185,6 +197,37 @@ contract IdentityRegistry is ERC721Enumerable, EIP712 {return _metadata[agentId][metadataKey];}+ // ---------------------------------------------------------------------+ // Agent spend delegation+ // ---------------------------------------------------------------------++ receive() external payable {}++ /// @notice Agent NFT owner authorizes a spender (e.g. delegated server key) to+ /// spend up to maxWei from this contract on behalf of the agent.+ function setSpendAllowance(uint256 agentId, address spender, uint256 maxWei)+ external+ {+ if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();+ spendAllowance[agentId][spender] = maxWei;+ emit SpendAllowanceSet(agentId, spender, maxWei);+ }++ /// @notice Spend ETH held by this contract on behalf of an agent.+ /// Caller must have been granted allowance via setSpendAllowance.+ function spend(+ uint256 agentId,+ address payable recipient,+ uint256 amountWei,+ string calldata memo+ ) external nonReentrant {+ require(spendAllowance[agentId][msg.sender] >= amountWei, "allowance exceeded");+ require(address(this).balance >= amountWei, "contract balance insufficient");+ spendAllowance[agentId][msg.sender] -= amountWei;+ recipient.transfer(amountWei);+ emit AgentPayment(agentId, msg.sender, recipient, amountWei, memo);+ }+// ---------------------------------------------------------------------// Introspection helpers// ---------------------------------------------------------------------diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 35e0895f1..d69725e4c 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -96,8 +96,10 @@ const tabs = {keys: renderKeys,mcp: renderMcp,monetization: renderMonetization,+ subscriptions: renderSubscriptions,billing: renderBilling,revenue: renderRevenue,+ earnings: renderEarnings,account: renderAccount,};@@ -3435,3 +3437,83 @@ function esc(s) {function attr(s) {return esc(s);}++// ── Earnings ─────────────────────────────────────────────────────────────────+async function renderEarnings(root) {+ root.innerHTML = `+ <h1>Skill Earnings</h1>+ <p class="sub">Royalties earned when agents invoke your published skills.</p>+ <div id="earn-body"><div class="muted">Loading…</div></div>+ `;++ const body = root.querySelector('#earn-body');+ let data;+ try {+ const resp = await fetch('/api/users/me/earnings', { credentials: 'include' });+ if (!resp.ok) throw new Error(await resp.text());+ data = await resp.json();+ } catch (e) {+ body.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ return;+ }++ const { pending_usd, settled_usd, entries } = data;++ if (!entries.length) {+ body.innerHTML = `+ <div class="card" style="text-align:center;padding:48px 24px">+ <div style="font-size:40px;margin-bottom:12px">💎</div>+ <h3 style="margin:0 0 8px">No earnings yet</h3>+ <p class="muted" style="margin:0">Royalties appear here when agents call your paid skills.</p>+ </div>`;+ return;+ }++ const fmt = (n) => '$' + Number(n).toFixed(4);+ const statusBadge = (s) => {+ const colors = { pending: '#f59e0b', settled: '#22c55e', failed: '#ef4444' };+ return `<span style="font-size:11px;padding:2px 7px;border-radius:10px;background:${colors[s] ?? '#555'}22;color:${colors[s] ?? '#aaa'}">${esc(s)}</span>`;+ };++ body.innerHTML = `+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:20px">+ <div class="card">+ <div class="muted" style="font-size:12px;margin-bottom:4px">Pending</div>+ <div style="font-size:22px;font-weight:600;color:#f59e0b">${fmt(pending_usd)}</div>+ </div>+ <div class="card">+ <div class="muted" style="font-size:12px;margin-bottom:4px">Settled</div>+ <div style="font-size:22px;font-weight:600;color:#22c55e">${fmt(settled_usd)}</div>+ </div>+ <div class="card">+ <div class="muted" style="font-size:12px;margin-bottom:4px">Total</div>+ <div style="font-size:22px;font-weight:600">${fmt(pending_usd + settled_usd)}</div>+ </div>+ </div>+ <table style="width:100%;border-collapse:collapse;font-size:13px">+ <thead>+ <tr style="color:#888;text-align:left;border-bottom:1px solid var(--border)">+ <th style="padding:8px 10px">Skill</th>+ <th style="padding:8px 10px">Agent</th>+ <th style="padding:8px 10px">Amount</th>+ <th style="padding:8px 10px">Status</th>+ <th style="padding:8px 10px">Date</th>+ </tr>+ </thead>+ <tbody>+ ${entries+ .map(+ (e) => `+ <tr style="border-bottom:1px solid var(--border)">+ <td style="padding:8px 10px">${esc(e.skill_name)}</td>+ <td style="padding:8px 10px;color:#888">${esc(e.agent_name)}</td>+ <td style="padding:8px 10px;font-variant-numeric:tabular-nums">${fmt(e.price_usd)}</td>+ <td style="padding:8px 10px">${statusBadge(e.status)}</td>+ <td style="padding:8px 10px;color:#888">${new Date(e.created_at).toLocaleDateString()}</td>+ </tr>`,+ )+ .join('')}+ </tbody>+ </table>+ `;+}diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex d0f83ae6e..4275e78b2 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -1138,8 +1138,10 @@<a href="#keys" data-tab="keys">API keys</a><a href="#mcp" data-tab="mcp">MCP</a><a href="#monetization" data-tab="monetization">Monetization</a>+ <a href="#subscriptions" data-tab="subscriptions">Subscriptions</a><a href="#billing" data-tab="billing">Plan & usage</a><a href="#revenue" data-tab="revenue">Revenue</a>+ <a href="#earnings" data-tab="earnings">Earnings</a><a href="#account" data-tab="account">Account</a><a href="/dashboard/wallets">Wallets</a><a href="/vanity-wallet">Vanity wallet ✦</a>diff --git a/src/editor/manifest-builder.js b/src/editor/manifest-builder.jsindex 18fcc30e9..368ed1169 100644--- a/src/editor/manifest-builder.js+++ b/src/editor/manifest-builder.js@@ -4,6 +4,7 @@import { z } from 'zod';import '../element.js';+import { PersonaInterview } from './persona-interview.js';// ─── Constants ────────────────────────────────────────────────────────────────@@ -418,6 +419,8 @@ export function mountManifestBuilder(rootEl, options = {}) {// ── Form building ──────────────────────────────────────────────────────────+ const agentId = options.agentId || null;+function buildForm() {const scroll = $('#form-scroll');scroll.innerHTML = [@@ -425,6 +428,7 @@ export function mountManifestBuilder(rootEl, options = {}) {bodyHtml(),brainHtml(),voiceHtml(),+ personaHtml(),skillsHtml(),memoryHtml(),instructionsHtml(),@@ -596,6 +600,25 @@ export function mountManifestBuilder(rootEl, options = {}) {</details>`;}+ function personaHtml() {+ if (!agentId) {+ return `<details>+ <summary>Persona</summary>+ <div class="section-body">+ <p style="color:#6b7280;font-size:13px">Save the agent first to enable persona extraction.</p>+ </div>+ </details>`;+ }+ return `<details>+ <summary>Persona</summary>+ <div class="section-body">+ <div id="persona-status"></div>+ <div id="persona-interview-mount"></div>+ <button class="btn secondary" id="btn-persona-start" style="margin-top:10px">Run interview</button>+ </div>+ </details>`;+ }+function skillsHtml() {return `<details><summary>Skills</summary>@@ -790,6 +813,48 @@ export function mountManifestBuilder(rootEl, options = {}) {scheduleDraft();});+ if (agentId) {+ let _interview = null;+ on('#btn-persona-start', 'click', () => {+ const mount = $('#persona-interview-mount');+ const btn = $('#btn-persona-start');+ if (!mount) return;+ if (_interview) { _interview.destroy(); _interview = null; }+ btn.style.display = 'none';+ _interview = new PersonaInterview(mount, {+ agentId,+ onComplete: ({ tone_tags, extracted_at }) => {+ const status = $('#persona-status');+ if (status) {+ const chips = (tone_tags || [])+ .map((t) => `<span style="display:inline-block;background:#1f2937;border-radius:4px;padding:2px 8px;margin:2px;font-size:12px">${t}</span>`)+ .join('');+ status.innerHTML = `<p style="color:#10b981;margin-bottom:6px">Persona extracted ✓</p><div>${chips}</div>`;+ }+ btn.textContent = 'Re-run interview';+ btn.style.display = '';+ },+ });+ _interview.mount();+ });++ // Load existing persona status on open+ fetch(`/api/agents/${agentId}/persona`, { credentials: 'include' })+ .then((r) => r.ok ? r.json() : null)+ .then((data) => {+ if (!data?.has_persona) return;+ const status = $('#persona-status');+ if (!status) return;+ const chips = (data.tone_tags || [])+ .map((t) => `<span style="display:inline-block;background:#1f2937;border-radius:4px;padding:2px 8px;margin:2px;font-size:12px">${t}</span>`)+ .join('');+ status.innerHTML = `<p style="color:#10b981;margin-bottom:6px">Persona extracted ✓</p><div>${chips}</div>`;+ const btn = $('#btn-persona-start');+ if (btn) btn.textContent = 'Re-run interview';+ })+ .catch(() => {});+ }+on('#f-mem-mode', 'change', (e) => {state.memoryMode = e.target.value;scheduleDraft();diff --git a/src/editor/persona-interview.js b/src/editor/persona-interview.jsnew file mode 100644index 000000000..20221f7fa--- /dev/null+++ b/src/editor/persona-interview.js@@ -0,0 +1,132 @@+// Step-through persona interview: 5 questions → POST /api/agents/:id/persona/extract++const QUESTIONS = [+ 'How would your closest friend describe the way you communicate?',+ 'What topic could you talk about for hours without getting bored?',+ 'When someone misunderstands you, what do you usually say to clarify?',+ 'Describe your sense of humor in two sentences.',+ "What's something people always get wrong about you?",+];++export class PersonaInterview {+ constructor(containerEl, { agentId, onComplete }) {+ this._container = containerEl;+ this._agentId = agentId;+ this._onComplete = onComplete;+ this._step = 0;+ this._answers = Array(QUESTIONS.length).fill('');+ this._listeners = [];+ }++ mount() {+ this._render();+ }++ destroy() {+ for (const [el, type, fn] of this._listeners) el.removeEventListener(type, fn);+ this._listeners = [];+ this._container.innerHTML = '';+ }++ _on(el, type, fn) {+ el.addEventListener(type, fn);+ this._listeners.push([el, type, fn]);+ }++ _render() {+ const step = this._step;+ const isLast = step === QUESTIONS.length - 1;+ const answer = this._answers[step];+ const remaining = 1000 - answer.length;++ this._container.innerHTML = `+ <div class="persona-interview">+ <div class="pi-progress">${step + 1} / ${QUESTIONS.length}</div>+ <p class="pi-question">${QUESTIONS[step]}</p>+ <textarea class="pi-textarea" rows="4" maxlength="1000" placeholder="Your answer…">${this._escHtml(answer)}</textarea>+ <div class="pi-meta">+ <span class="pi-counter">${remaining} chars left</span>+ <button class="pi-next" ${answer.trim().length < 5 ? 'disabled' : ''}>${isLast ? 'Finish' : 'Next'}</button>+ </div>+ </div>+ `;++ const ta = this._container.querySelector('.pi-textarea');+ const btn = this._container.querySelector('.pi-next');+ const counter = this._container.querySelector('.pi-counter');++ this._on(ta, 'input', () => {+ this._answers[step] = ta.value;+ const rem = 1000 - ta.value.length;+ counter.textContent = `${rem} chars left`;+ btn.disabled = ta.value.trim().length < 5;+ });++ this._on(btn, 'click', () => {+ if (isLast) {+ this._submit();+ } else {+ this._step++;+ this._render();+ }+ });+ }++ async _submit() {+ this._container.innerHTML = `+ <div class="persona-interview pi-loading">+ <p>Extracting persona…</p>+ </div>+ `;++ let result;+ try {+ const resp = await fetch(`/api/agents/${this._agentId}/persona/extract`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ answers: this._answers }),+ });+ if (!resp.ok) {+ const err = await resp.json().catch(() => ({}));+ throw new Error(err.error_description || `HTTP ${resp.status}`);+ }+ result = await resp.json();+ } catch (err) {+ this._container.innerHTML = `+ <div class="persona-interview pi-error">+ <p>Extraction failed: ${this._escHtml(err.message)}</p>+ <button class="pi-retry">Try again</button>+ </div>+ `;+ const retry = this._container.querySelector('.pi-retry');+ this._on(retry, 'click', () => {+ this._step = 0;+ this._answers = Array(QUESTIONS.length).fill('');+ this._render();+ });+ return;+ }++ const tags = (result.tone_tags || [])+ .map((t) => `<span class="pi-tag">${this._escHtml(t)}</span>`)+ .join('');++ this._container.innerHTML = `+ <div class="persona-interview pi-done">+ <p>Persona extracted ✓</p>+ <div class="pi-tags">${tags}</div>+ </div>+ `;++ this._onComplete?.({ tone_tags: result.tone_tags, extracted_at: result.extracted_at });+ }++ _escHtml(str) {+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+ }+}diff --git a/src/erc8004/abi.js b/src/erc8004/abi.jsindex 03161fe28..d5ed07426 100644--- a/src/erc8004/abi.js+++ b/src/erc8004/abi.js@@ -27,6 +27,13 @@ export const IDENTITY_REGISTRY_ABI = [// --- Wallet ---'function getAgentWallet(uint256 agentId) external view returns (address)',+ // --- Agent spend delegation ---+ 'function setSpendAllowance(uint256 agentId, address spender, uint256 maxWei) external',+ 'function spend(uint256 agentId, address payable recipient, uint256 amountWei, string memo) external',+ 'function spendAllowance(uint256 agentId, address spender) external view returns (uint256)',+ 'event SpendAllowanceSet(uint256 indexed agentId, address indexed spender, uint256 maxWei)',+ 'event AgentPayment(uint256 indexed agentId, address indexed spender, address indexed recipient, uint256 amountWei, string memo)',+// --- ERC-721 basics ---'function ownerOf(uint256 tokenId) external view returns (address)','function balanceOf(address owner) external view returns (uint256)',diff --git a/src/pump/bonding-curve-chart.js b/src/pump/bonding-curve-chart.jsnew file mode 100644index 000000000..79952398b--- /dev/null+++ b/src/pump/bonding-curve-chart.js@@ -0,0 +1,99 @@+// Pump.fun launch bonding curve chart — plain SVG, no deps.+// price(supply) = supply / (1073000000 - supply) * 30 SOL+// X: 0 to 800M tokens, Y: price in SOL per token (normalized to chart height)++const MAX_SUPPLY = 800_000_000;+const VIRTUAL_TOKENS = 1_073_000_000;+const VIRTUAL_SOL = 30;+const W = 280, H = 120;+const PL = 36, PR = 8, PT = 8, PB = 22;+const PW = W - PL - PR;+const PH = H - PT - PB;+const BOT = PT + PH;++function _price(supply) {+ return supply / (VIRTUAL_TOKENS - supply) * VIRTUAL_SOL;+}++const MAX_PRICE = _price(MAX_SUPPLY);++function _cx(s) { return PL + (s / MAX_SUPPLY) * PW; }+function _cy(p) { return PT + PH * (1 - p / MAX_PRICE); }++const CURVE_PATH = (() => {+ const n = 80;+ let d = '';+ for (let i = 0; i <= n; i++) {+ const s = (i / n) * MAX_SUPPLY;+ const x = _cx(s).toFixed(1);+ const y = _cy(_price(s)).toFixed(1);+ d += `${i === 0 ? 'M' : 'L'}${x},${y} `;+ }+ return d.trimEnd();+})();++const FILL_PATH = `M${PL},${BOT} ${CURVE_PATH.slice(1)} L${(PL + PW).toFixed(1)},${BOT} Z`;++function _fmtSol(v) {+ if (v >= 100) return `${v.toFixed(0)} SOL`;+ if (v >= 1) return `${v.toFixed(2)} SOL`;+ return `${v.toFixed(4)} SOL`;+}++/**+ * Mount the pump.fun bonding curve chart into `el`.+ * Marks launch position at supply = 0 (price = 0).+ *+ * @param {HTMLElement} el+ * @returns {{ destroy: () => void }}+ */+export function mountLaunchBondingCurve(el) {+ const launchX = _cx(0).toFixed(1);+ const gradX = (PL + PW).toFixed(1);++ el.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}"+ style="width:100%;height:auto;display:block"+ role="img" aria-label="Bonding curve — price rises as tokens are bought">+ <defs>+ <linearGradient id="lbc-fill" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="rgba(120,200,140,0.2)"/>+ <stop offset="100%" stop-color="rgba(120,200,140,0.02)"/>+ </linearGradient>+ </defs>+ <!-- axes -->+ <line x1="${PL}" y1="${PT}" x2="${PL}" y2="${BOT}"+ stroke="rgba(255,255,255,0.07)" stroke-width="1"/>+ <line x1="${PL}" y1="${BOT}" x2="${PL + PW}" y2="${BOT}"+ stroke="rgba(255,255,255,0.07)" stroke-width="1"/>+ <!-- graduation line -->+ <line x1="${gradX}" y1="${PT}" x2="${gradX}" y2="${BOT}"+ stroke="rgba(164,240,188,0.22)" stroke-width="1" stroke-dasharray="3,3"/>+ <!-- area fill -->+ <path d="${FILL_PATH}" fill="url(#lbc-fill)" stroke="none"/>+ <!-- curve -->+ <path d="${CURVE_PATH}" fill="none"+ stroke="rgba(120,200,140,0.85)" stroke-width="2"+ stroke-linecap="round" stroke-linejoin="round"/>+ <!-- launch marker -->+ <circle cx="${launchX}" cy="${BOT}" r="4.5"+ fill="rgba(255,215,80,0.9)" stroke="rgba(0,0,0,0.4)" stroke-width="1.5"/>+ <text x="${parseFloat(launchX) + 7}" y="${BOT - 3}" font-size="8"+ fill="rgba(255,215,80,0.85)" font-family="ui-monospace,monospace">you are here</text>+ <!-- axis labels -->+ <text x="${PL - 2}" y="${BOT + 12}" text-anchor="end" font-size="7"+ fill="rgba(255,255,255,0.3)" font-family="ui-monospace,monospace">0</text>+ <text x="${gradX}" y="${BOT + 12}" text-anchor="end" font-size="7"+ fill="rgba(164,240,188,0.5)" font-family="ui-monospace,monospace">800M</text>+ <text x="${PL - 3}" y="${BOT}" text-anchor="end" font-size="7"+ fill="rgba(255,255,255,0.3)" font-family="ui-monospace,monospace">0</text>+ <text x="${PL - 3}" y="${PT + 7}" text-anchor="end" font-size="7"+ fill="rgba(255,255,255,0.3)" font-family="ui-monospace,monospace">${_fmtSol(MAX_PRICE)}</text>+ <!-- axis titles -->+ <text x="${PL + PW / 2}" y="${H - 2}" text-anchor="middle" font-size="7"+ fill="rgba(255,255,255,0.25)" font-family="ui-monospace,monospace">supply (tokens)</text>+</svg>`;++ return {+ destroy() { el.innerHTML = ''; },+ };+}diff --git a/vercel-fix-prompts/01-missing-zauthx402-sdk.md b/vercel-fix-prompts/01-missing-zauthx402-sdk.mdnew file mode 100644index 000000000..ab93244dd--- /dev/null+++ b/vercel-fix-prompts/01-missing-zauthx402-sdk.md@@ -0,0 +1,32 @@+# Fix: Missing @zauthx402/sdk Module in Vercel Deployment++## Problem++Vercel logs show 837+ instances of this error across nearly every API endpoint:++```+[zauth] failed to load @zauthx402/sdk: Cannot find module '/var/task/node_modules/@zauthx402/sdk/dist/middleware/index.js'+```++This prevents the zauth authentication middleware from loading, causing 401/402/403 responses on:+- `/api/agents/[id]`+- `/api/auth/*`+- `/api/mcp`+- `/api/widgets`+- `/api/agent-actions`+- `/api/agents/pumpfun`+- and many more++## What to investigate++1. Check if `@zauthx402/sdk` is listed as a dependency in `package.json` — it may be missing or listed under `devDependencies` instead of `dependencies`.+2. Check if there is a `.npmrc`, `.vercelignore`, or custom install script that might exclude it from the Vercel build.+3. Check `vercel.json` for any `includeFiles` or build config that might be stripping node_modules.+4. Confirm the import path used in the zauth middleware matches the actual export path in `@zauthx402/sdk/dist/middleware/index.js`.+5. If the package is a private/internal package, confirm it is accessible during Vercel's build step (correct npm token configured).++## Expected fix++- `@zauthx402/sdk` must appear in `dependencies` (not `devDependencies`) in `package.json`.+- After fixing, redeploy and confirm the error no longer appears in Vercel function logs.+- All auth-protected endpoints should return proper 200/401 responses instead of failing at middleware load time.diff --git a/vercel-fix-prompts/02-missing-jwt-secret-env-var.md b/vercel-fix-prompts/02-missing-jwt-secret-env-var.mdnew file mode 100644index 000000000..617b7f7b1--- /dev/null+++ b/vercel-fix-prompts/02-missing-jwt-secret-env-var.md@@ -0,0 +1,24 @@+# Fix: Missing JWT_SECRET Environment Variable++## Problem++Vercel logs show this error on `/api/agents` and `/api/auth/siwe/nonce`:++```+[api] unhandled Error: Missing required env var: JWT_SECRET+```++This causes 500 errors on any endpoint that issues or validates JWTs.++## What to investigate++1. Check all files that reference `JWT_SECRET` — confirm what environment variable name the code expects exactly (case-sensitive).+2. Go to the Vercel project dashboard → Settings → Environment Variables and confirm `JWT_SECRET` is set for the correct environments (Production, Preview, Development).+3. Check if the variable name in the code might differ from what's set in Vercel (e.g. `NEXT_PUBLIC_JWT_SECRET` vs `JWT_SECRET`).+4. Confirm the value is non-empty and correctly formatted (should be a long random secret string, not a placeholder).++## Expected fix++- Add `JWT_SECRET` to Vercel environment variables with a strong random secret value.+- Redeploy after adding the variable.+- `/api/agents` and `/api/auth/siwe/nonce` should no longer return 500 errors due to this missing variable.diff --git a/vercel-fix-prompts/03-missing-database-tables.md b/vercel-fix-prompts/03-missing-database-tables.mdnew file mode 100644index 000000000..0a0bd242c--- /dev/null+++ b/vercel-fix-prompts/03-missing-database-tables.md@@ -0,0 +1,36 @@+# Fix: Missing Database Tables (Incomplete Migrations)++## Problem++Multiple endpoints return 500 errors because expected database tables do not exist in production:++```+relation "pumpfun_signals" does not exist → /api/agents/solana/[action]+relation "dca_strategies" does not exist → /api/cron/run-dca+relation "agent_subscriptions" does not exist → /api/cron/run-subscriptions+relation "solana_attestations_cursor" does not exist → /api/cron/solana-attestations-crawl+```++## What to investigate++1. Find the migration files (likely in `migrations/`, `db/migrations/`, `prisma/migrations/`, or similar) for each of these four tables.+2. Confirm whether these migrations were ever run against the production database. Check if there is a migrations tracking table (e.g. `_prisma_migrations`, `knex_migrations`, or similar).+3. If using Prisma: run `npx prisma migrate status` against the production DB to see which migrations are pending.+4. If using raw SQL migrations: identify the SQL files for each missing table and run them in order.++## Tables to create++- `pumpfun_signals`+- `dca_strategies`+- `agent_subscriptions`+- `solana_attestations_cursor`++## Expected fix++- Run all pending migrations against the production database.+- Verify each table exists after migration.+- Re-test the affected endpoints:+ - `/api/agents/solana/[action]`+ - `/api/cron/run-dca`+ - `/api/cron/run-subscriptions`+ - `/api/cron/solana-attestations-crawl`diff --git a/vercel-fix-prompts/04-missing-avatars-columns.md b/vercel-fix-prompts/04-missing-avatars-columns.mdnew file mode 100644index 000000000..0ecae14e9--- /dev/null+++ b/vercel-fix-prompts/04-missing-avatars-columns.md@@ -0,0 +1,23 @@+# Fix: Missing Columns on avatars Table++## Problem++`/api/avatars` returns 500 errors due to missing columns in the `avatars` table:++```+column "parent_avatar_id" of relation "avatars" does not exist+column "storage_mode" of relation "avatars" does not exist+```++## What to investigate++1. Find the migration or schema file that should have added `parent_avatar_id` and `storage_mode` to the `avatars` table.+2. Confirm whether this migration was applied to production. Check the migration history table in the database.+3. Review the `avatars` table schema to understand the full expected structure including types and constraints for these columns.++## Expected fix++- Write and run a migration to add the two missing columns:+ - `parent_avatar_id` (likely a UUID foreign key referencing `avatars.id`, nullable)+ - `storage_mode` (likely a varchar/enum, check the codebase for what values are expected)+- After migration, confirm `/api/avatars` returns 200 without column errors.diff --git a/vercel-fix-prompts/05-invalid-uuid-routing.md b/vercel-fix-prompts/05-invalid-uuid-routing.mdnew file mode 100644index 000000000..cadac3980--- /dev/null+++ b/vercel-fix-prompts/05-invalid-uuid-routing.md@@ -0,0 +1,38 @@+# Fix: Non-UUID Strings Passed to UUID-Expecting Endpoints++## Problem++963+ instances of this error across multiple endpoints:++```+[api] unhandled NeonDbError: invalid input syntax for type uuid: "index.html"+[api] unhandled NeonDbError: invalid input syntax for type uuid: "agent-home.html"+[api] unhandled NeonDbError: invalid input syntax for type uuid: "pumpfun"+[api] unhandled NeonDbError: invalid input syntax for type uuid: "pumpfun-feed"+```++Affected endpoints:+- `/api/agents/[id]`+- `/api/agent-page`+- `/api/permissions/list`++These endpoints receive URL segments like `index.html`, `pumpfun`, etc., and pass them directly to database UUID queries without validation, causing unhandled 500 errors.++## What to investigate++1. Find the route handlers for `/api/agents/[id]`, `/api/agent-page`, and `/api/permissions/list`.+2. Locate where the `id` or slug parameter is extracted and passed to a DB query.+3. Determine the source of these invalid requests — are these browser fetches of static assets being intercepted by a catch-all API route? Or are clients genuinely sending bad IDs?+4. Check the routing config (`vercel.json` rewrites, Next.js routes, Express routing) to see if static asset requests like `index.html` are accidentally matching dynamic API routes.++## Expected fix++Option A (routing fix): Ensure static asset paths (`*.html`, named slugs like `pumpfun`) are not matched by the `[id]` catch-all route. Add a UUID format check early in the route handler and return 400 if the value is not a valid UUID.++Option B (validation fix): At the top of each affected handler, validate the `id` param is a valid UUID format before querying the DB:+```js+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+if (!UUID_RE.test(id)) return res.status(400).json({ error: 'Invalid id' });+```++Both options should be applied. Fix the routing AND add input validation.diff --git a/vercel-fix-prompts/06-missing-sub-module.md b/vercel-fix-prompts/06-missing-sub-module.mdnew file mode 100644index 000000000..1373a0b71--- /dev/null+++ b/vercel-fix-prompts/06-missing-sub-module.md@@ -0,0 +1,26 @@+# Fix: Missing _sub.js Internal Module in Deployment++## Problem++2,892 instances of this error causing 500 on `/api/agents/[id]`:++```+[api] unhandled Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/var/task/api/agents/_sub.js'+imported from /var/task/api/agents/[id].js+```++The deployed bundle is missing `api/agents/_sub.js` which is imported by `api/agents/[id].js`.++## What to investigate++1. Confirm `api/agents/_sub.js` (or `_sub.ts`) exists in the repo.+2. Check if the file is excluded from the Vercel deployment by `.vercelignore` or build config. Files prefixed with `_` may be intentionally excluded by some frameworks (e.g. Next.js excludes `_` prefixed pages from routing but should still include them as modules).+3. Check `vercel.json` for any `includeFiles` rules that might be too restrictive.+4. In Next.js: files starting with `_` inside `pages/api/` are not treated as routes but they should still be bundled if imported. Confirm the import path is correct relative to `[id].js`.++## Expected fix++- If the file exists but is excluded: update `.vercelignore` or build config to include it.+- If the import path is wrong: fix the relative import in `api/agents/[id].js`.+- If the file is missing entirely: create `api/agents/_sub.js` with the exports that `[id].js` expects.+- Redeploy and confirm `/api/agents/[id]` no longer returns `ERR_MODULE_NOT_FOUND`.diff --git a/vercel-fix-prompts/07-duplicate-email-key-violation.md b/vercel-fix-prompts/07-duplicate-email-key-violation.mdnew file mode 100644index 000000000..33abc5732--- /dev/null+++ b/vercel-fix-prompts/07-duplicate-email-key-violation.md@@ -0,0 +1,35 @@+# Fix: Duplicate Email Key Constraint Violation on User Registration++## Problem++`/api/auth/siwe/verify` returns 500 errors due to:++```+duplicate key value violates unique constraint "users_email_key"+```++This happens when a user tries to register or authenticate and the system attempts to INSERT a user record with an email that already exists.++## What to investigate++1. Find the handler for `/api/auth/siwe/verify`.+2. Locate where a new user record is inserted into the `users` table.+3. Determine if the code does an upsert (INSERT ... ON CONFLICT DO UPDATE) or a plain INSERT. If it's a plain INSERT, it will fail for returning users.+4. Check if the flow should be: look up existing user by wallet address or email → create only if not found → issue JWT. If a user reconnects their wallet, we should NOT try to create a new record.++## Expected fix++Replace the plain INSERT with an upsert:+```sql+INSERT INTO users (email, wallet_address, ...)+VALUES ($1, $2, ...)+ON CONFLICT (email) DO UPDATE SET updated_at = NOW()+RETURNING *;+```++Or add a lookup-before-insert pattern:+```js+let user = await db.users.findByEmail(email) ?? await db.users.create({ email, ... });+```++Ensure the error is handled gracefully (return the existing user, not a 500) even if the upsert approach is used.diff --git a/vercel-fix-prompts/08-noble-curves-package-export.md b/vercel-fix-prompts/08-noble-curves-package-export.mdnew file mode 100644index 000000000..693c9ad87--- /dev/null+++ b/vercel-fix-prompts/08-noble-curves-package-export.md@@ -0,0 +1,30 @@+# Fix: @noble/curves Package Subpath Export Error++## Problem++`/api/auth/siws/verify` returns 500 due to:++```+Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './ed25519' is not defined+by "exports" in /var/task/node_modules/@noble/curves/package.json+```++This is a package version incompatibility — the code imports `@noble/curves/ed25519` but the installed version of `@noble/curves` does not export that subpath.++## What to investigate++1. Find all imports of `@noble/curves` in the codebase, particularly any that import `@noble/curves/ed25519`.+2. Check the installed version of `@noble/curves` in `package.json` and `package-lock.json`/`yarn.lock`.+3. Check the `@noble/curves` changelog — the `./ed25519` subpath export was added in a specific version. Identify the minimum version that exports it.+4. Check if another dependency is pulling in an older version of `@noble/curves` that conflicts with the one declared in `package.json`.++## Expected fix++- Update `@noble/curves` to the version that supports `./ed25519` subpath export (likely `^1.0.0` or later).+- If a transitive dependency is pinning an older version, use `overrides` (npm) or `resolutions` (yarn) in `package.json` to force the correct version:+ ```json+ "overrides": {+ "@noble/curves": "^1.4.0"+ }+ ```+- Run `npm install` and redeploy. Confirm `/api/auth/siws/verify` no longer errors.diff --git a/vercel-fix-prompts/09-bonfida-spl-name-service-syntax-error.md b/vercel-fix-prompts/09-bonfida-spl-name-service-syntax-error.mdnew file mode 100644index 000000000..9651e6149--- /dev/null+++ b/vercel-fix-prompts/09-bonfida-spl-name-service-syntax-error.md@@ -0,0 +1,38 @@+# Fix: Syntax Error in @bonfida/spl-name-service ESM Bundle++## Problem++`/api/pump-fun-mcp` returns 500 due to a syntax error in a dependency's ESM bundle:++```+SyntaxError in /var/task/node_modules/@bonfida/spl-name-service/dist/esm/instructions/burnInstruction.js:1+```++The ESM build of `@bonfida/spl-name-service` has a syntax error, which means either:+- The installed version is corrupt or incompatible with the Node.js version on Vercel.+- There is an ESM/CJS conflict causing the wrong bundle to be loaded.++## What to investigate++1. Check the version of `@bonfida/spl-name-service` in `package.json`.+2. Look at the actual content of `burnInstruction.js:1` in `node_modules/@bonfida/spl-name-service/dist/esm/` to understand the specific syntax issue.+3. Check if a newer version of the package fixes this (look at the package's GitHub releases/changelog).+4. Check if the package is supposed to be imported as CJS instead of ESM — look at the package's `main` vs `module` fields in its `package.json`.++## Expected fix++Option A: Update `@bonfida/spl-name-service` to a version that has a valid ESM bundle.++Option B: If the package doesn't have a working ESM build, force CJS import by adding to your bundler/build config:+```json+// vercel.json or next.config.js+"transpilePackages": ["@bonfida/spl-name-service"]+```+or in Next.js `next.config.js`:+```js+experimental: { esmExternals: false }+```++Option C: Pin the last known-good version of the package.++After fixing, confirm `/api/pump-fun-mcp` loads without syntax errors.diff --git a/vercel-fix-prompts/10-pump-sdk-esm-cjs-mismatch.md b/vercel-fix-prompts/10-pump-sdk-esm-cjs-mismatch.mdnew file mode 100644index 000000000..c91211695--- /dev/null+++ b/vercel-fix-prompts/10-pump-sdk-esm-cjs-mismatch.md@@ -0,0 +1,38 @@+# Fix: @pump-fun/pump-sdk ESM Module Loading Failure++## Problem++`/api/agents/[id]` returns 500 with a warning about ES module loading failure:++```+[api] unhandled /var/task/node_modules/@pump-fun/pump-sdk/dist/esm/index.js:8905+Failed to load the ES module+```++This indicates an ESM/CJS interop issue where the bundler or runtime cannot load the ESM version of `@pump-fun/pump-sdk`.++## What to investigate++1. Check `@pump-fun/pump-sdk`'s `package.json` — look at the `exports`, `main`, and `module` fields to understand what module formats it publishes.+2. Check how the SDK is imported in the codebase (named imports, default import, dynamic import).+3. Check Node.js version on Vercel (set in `package.json` `engines` field or `.nvmrc`). ESM support varies by Node version.+4. Check if `vercel.json` or `next.config.js` has any `esmExternals` or `transpilePackages` config that might affect this package.++## Expected fix++Option A: Force the CJS build by importing from the CJS entry point:+```js+// Instead of: import { X } from '@pump-fun/pump-sdk'+const { X } = require('@pump-fun/pump-sdk');+// or import from CJS path:+import { X } from '@pump-fun/pump-sdk/dist/cjs/index.js';+```++Option B: Add the package to `transpilePackages` in `next.config.js`:+```js+transpilePackages: ['@pump-fun/pump-sdk']+```++Option C: Update to a version of the SDK that has proper dual CJS/ESM exports.++Confirm `/api/agents/[id]` no longer crashes with the ESM load failure after the fix.diff --git a/vercel-fix-prompts/11-rpc-missing-chain-configs.md b/vercel-fix-prompts/11-rpc-missing-chain-configs.mdnew file mode 100644index 000000000..95e2a41bd--- /dev/null+++ b/vercel-fix-prompts/11-rpc-missing-chain-configs.md@@ -0,0 +1,39 @@+# Fix: Missing RPC URLs for Chains 8453, 421614, 11155420++## Problem++The `/api/cron/[name]` (index-delegations) cron job logs 560+ errors per chain for:++```+{"stage":"index-delegations","chainId":8453,"error":"no RPC URL configured for chain 8453"}+{"stage":"index-delegations","chainId":421614,"error":"no RPC URL configured for chain 421614"}+{"stage":"index-delegations","chainId":11155420,"error":"no RPC URL configured for chain 11155420"}+```++Chain IDs:+- `8453` = Base Mainnet+- `421614` = Arbitrum Sepolia+- `11155420` = Optimism Sepolia++## What to investigate++1. Find where RPC URLs are configured in the codebase — likely an object/map keyed by chain ID, a config file, or environment variables like `RPC_URL_8453`.+2. Confirm whether RPC URLs for these chains are defined anywhere (env vars, config files, hardcoded maps).+3. Check if the environment variables are set in Vercel's dashboard for these chains.++## Expected fix++Add RPC URL configuration for the three missing chains. Options:++**Option A — Environment variables:**+```+RPC_URL_8453=https://mainnet.base.org # or Alchemy/Infura Base endpoint+RPC_URL_421614=https://sepolia-rollup.arbitrum.io/rpc+RPC_URL_11155420=https://sepolia.optimism.io+```++**Option B — Update the hardcoded chain config map** in the codebase to include these chain IDs with their RPC endpoints.++Use a reliable RPC provider (Alchemy, Infura, QuickNode) for production — public endpoints may have rate limits. Set these in Vercel environment variables and redeploy.++After fixing, the `index-delegations` cron should process all chains without "no RPC URL" errors.diff --git a/vercel-fix-prompts/12-rpc-rate-limiting-strategy.md b/vercel-fix-prompts/12-rpc-rate-limiting-strategy.mdnew file mode 100644index 000000000..23e8b4a0f--- /dev/null+++ b/vercel-fix-prompts/12-rpc-rate-limiting-strategy.md@@ -0,0 +1,35 @@+# Fix: RPC Rate Limiting (429) from Solana and Ethereum Providers++## Problem++Multiple endpoints hit RPC rate limits causing 502/500 errors:++```+[agents/solana/activity] RPC fetch failed Error: 429 Too Many Requests → /api/agents/[id]+{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 429 from https://1rpc.io/eth"}+```++The code already has retry logic with exponential backoff (500ms, 1000ms, 2000ms, 4000ms) but this isn't enough — requests still fail.++## What to investigate++1. Identify all RPC providers currently configured for Solana and Ethereum (mainnet chain 1).+2. Check if the app is using public/free-tier RPC endpoints (e.g. `1rpc.io`, `mainnet-beta.solana.com`) that have aggressive rate limits.+3. Find all places in the codebase that make RPC calls and check if they share a single connection or create new connections per request.+4. Check if cron jobs and user-facing requests share the same RPC quota.++## Expected fix++**Short-term:**+- Switch Solana RPC from public endpoint to a paid provider: Helius, QuickNode, or Triton.+- Switch Ethereum mainnet RPC from `1rpc.io` to Alchemy or Infura with a proper API key.+- Add RPC API keys as Vercel environment variables.++**Medium-term:**+- Add RPC request queuing with proper rate limiting using a library like `p-queue` or `bottleneck`.+- Cache RPC responses where possible (e.g. block numbers, account balances) to reduce call volume.+- Separate cron job RPC traffic from user-facing request RPC traffic using different API keys/quotas.++**For the cron job specifically:**+- Add jitter to retry backoff to avoid thundering herd.+- Consider reducing cron frequency if the data doesn't need real-time updates.diff --git a/vercel-fix-prompts/13-vercel-timeout-erc8004-crawl.md b/vercel-fix-prompts/13-vercel-timeout-erc8004-crawl.mdnew file mode 100644index 000000000..34b784e70--- /dev/null+++ b/vercel-fix-prompts/13-vercel-timeout-erc8004-crawl.md@@ -0,0 +1,48 @@+# Fix: Vercel 300-Second Timeout on erc8004-crawl Cron Job++## Problem++`/api/cron/erc8004-crawl` times out with:++```+Vercel Runtime Timeout Error: Task timed out after 300 seconds+```++Vercel's maximum function execution time is 300 seconds (5 minutes) on Pro plans. The crawl job exceeds this limit.++## What to investigate++1. Find the handler for `/api/cron/erc8004-crawl` and understand what it does — how many records it processes, what external calls it makes, and why it takes >300 seconds.+2. Identify the bottleneck: is it sequential processing of many items, slow external HTTP calls, or large data sets?+3. Check if there is a cursor/offset mechanism already in place to support incremental processing.++## Expected fix++**Option A — Incremental/chunked processing with cursor:**+Instead of processing everything in one run, process a fixed-size chunk per invocation and store a cursor in the database (`solana_attestations_cursor` table already exists for this pattern). The next cron invocation picks up where the last left off.++```js+// At start of cron handler:+const cursor = await db.getCursor('erc8004-crawl');+const items = await fetchItems({ after: cursor, limit: 100 });+await processItems(items);+await db.setCursor('erc8004-crawl', items.at(-1)?.id);+```++**Option B — Increase timeout via Vercel config:**+If on Vercel Enterprise or using Edge Functions, set `maxDuration` in `vercel.json`:+```json+{+ "functions": {+ "api/cron/erc8004-crawl.js": {+ "maxDuration": 800+ }+ }+}+```+Note: This only works on Enterprise plans and has a hard ceiling.++**Option C — Background processing:**+Offload the heavy work to a background queue (e.g. Inngest, QStash, or a DB-backed job queue) and have the cron job only enqueue work, not do it inline.++Recommended: Option A (cursor-based incremental crawl) is the most robust long-term solution.diff --git a/vercel-fix-prompts/14-null-reference-permissions-action.md b/vercel-fix-prompts/14-null-reference-permissions-action.mdnew file mode 100644index 000000000..c5bc189e9--- /dev/null+++ b/vercel-fix-prompts/14-null-reference-permissions-action.md@@ -0,0 +1,38 @@+# Fix: Null Reference Crash in /api/permissions/[action]++## Problem++250+ instances of process crashes with exit status 1:++```+Node.js process exited with exit status: 1+TypeError: Cannot read properties of null (reading 'topicHash')+at /var/task/api/permissions/[action].js:912+```++The code at line 912 of the permissions handler accesses `.topicHash` on a value that is `null`, causing an unhandled exception that crashes the entire Node.js process (not just the request).++## What to investigate++1. Open `api/permissions/[action].js` (or `.ts`) and find the code around line 912.+2. Identify what variable holds the null value — it's likely the result of a log lookup, event filter, or ABI decode operation.+3. Determine when this value can legitimately be null — is it an optional event, a missing log entry, or a misconfigured filter?++## Expected fix++Add a null check before accessing `.topicHash`:++```js+// Line ~912 — before the fix:+const hash = event.topicHash; // crashes if event is null++// After the fix:+if (!event) continue; // or return, or log and skip+const hash = event.topicHash;+```++The specific fix depends on the context:+- If iterating over a list: filter out nulls before the loop, or use `event?.topicHash` with a guard.+- If it's a single lookup: check for null and return an appropriate error response instead of crashing.++**Critical:** This crashes the Node.js process (not just the request), which means concurrent requests on the same instance also fail. Fix this immediately and add a top-level `try/catch` around the handler to prevent process crashes from unhandled errors.diff --git a/vercel-fix-prompts/15-type-error-solana-register-prep.md b/vercel-fix-prompts/15-type-error-solana-register-prep.mdnew file mode 100644index 000000000..16947289b--- /dev/null+++ b/vercel-fix-prompts/15-type-error-solana-register-prep.md@@ -0,0 +1,32 @@+# Fix: TypeError in /api/agents/solana-register-prep++## Problem++`/api/agents/solana-register-prep` returns 500 with:++```+TypeError: The first argument must be of type string or an instance of Buffer+```++This error typically comes from Node.js crypto functions, Buffer operations, or similar APIs that require a string or Buffer but received something else (undefined, null, object, number).++## What to investigate++1. Find the handler for `/api/agents/solana-register-prep`.+2. Search for Buffer operations, crypto calls (`crypto.createHash`, `crypto.sign`, etc.), or Solana SDK calls that take a key or data argument.+3. Identify which argument is receiving the wrong type — add logging before the failing call to print the actual type and value of the argument.+4. Trace back where that value comes from — request body, environment variable, database lookup, or derived value.++## Expected fix++- Add input validation at the top of the handler to verify all required fields are present and of the correct type before any crypto/Buffer operations.+- If the value comes from an environment variable, add a startup check with a clear error message if missing.+- If it comes from the request body, return 400 with a descriptive error instead of letting the TypeError propagate.++Example guard:+```js+const { publicKey } = req.body;+if (typeof publicKey !== 'string') {+ return res.status(400).json({ error: 'publicKey must be a string' });+}+```diff --git a/vercel-fix-prompts/16-deprecated-url-parse.md b/vercel-fix-prompts/16-deprecated-url-parse.mdnew file mode 100644index 000000000..efae69070--- /dev/null+++ b/vercel-fix-prompts/16-deprecated-url-parse.md@@ -0,0 +1,39 @@+# Fix: Deprecated url.parse() Usage (DEP0169)++## Problem++474+ instances of this deprecation warning across many endpoints:++```+(node:4) [DEP0169] DeprecationWarning: 'url.parse()' behavior is not standardized and may change.+Use the WHATWG URL API instead.+```++While this doesn't cause failures today, Node.js may remove `url.parse()` in a future version, and it's polluting logs making real errors harder to find.++## What to investigate++1. Search the entire codebase for `url.parse(` to find all usages.+2. Also check `node_modules` for the warning source — it may come from a dependency, not your own code. Run with `--trace-warnings` locally to get a stack trace pointing to the exact file.++## Expected fix++Replace `url.parse()` with the WHATWG URL API:++```js+// Before:+const { hostname, pathname, query } = url.parse(rawUrl, true);++// After:+const parsed = new URL(rawUrl);+const hostname = parsed.hostname;+const pathname = parsed.pathname;+const params = Object.fromEntries(parsed.searchParams);+```++If the warnings come from a dependency (not your code):+- Check if there's a newer version of the dependency that has switched to the WHATWG URL API.+- Update the dependency.+- If no fix is available, consider filing an issue with the upstream package.++Note: suppress the deprecation warning only as a last resort — prefer fixing the root cause.diff --git a/vercel-fix-prompts/17-http-403-erc8004-register-confirm.md b/vercel-fix-prompts/17-http-403-erc8004-register-confirm.mdnew file mode 100644index 000000000..7e825c6a2--- /dev/null+++ b/vercel-fix-prompts/17-http-403-erc8004-register-confirm.md@@ -0,0 +1,42 @@+# Fix: HTTP 403 from Upstream on /api/erc8004/register-confirm++## Problem++`/api/erc8004/register-confirm` returns 500 due to:++```+[api] unhandled Error: HTTP 403+```++The handler makes an external HTTP request that is returning 403 Forbidden from the upstream service. This unhandled error propagates as a 500 to the client.++## What to investigate++1. Find the handler for `/api/erc8004/register-confirm`.+2. Identify the external URL it calls (the one returning 403).+3. Determine why the upstream is returning 403 — common causes:+ - Missing or expired API key in request headers.+ - API key environment variable not set in Vercel production environment.+ - IP allowlist on the upstream service that doesn't include Vercel's IPs.+ - Request is missing a required authentication header or signature.+4. Check if the API key / credentials for this service are configured in Vercel environment variables.++## Expected fix++**If it's a missing/expired API key:**+- Obtain a valid API key for the ERC8004 registration service.+- Add it as a Vercel environment variable (e.g. `ERC8004_API_KEY`).+- Update the handler to include it in the request headers.++**For the unhandled error (immediate fix):**+Regardless of the upstream cause, wrap the external call so it returns a proper error response instead of a 500:++```js+const response = await fetch(upstreamUrl, { headers: { ... } });+if (response.status === 403) {+ return res.status(502).json({ error: 'Registration service rejected the request' });+}+if (!response.ok) {+ return res.status(502).json({ error: `Upstream error: ${response.status}` });+}+```diff --git a/vercel-fix-prompts/18-rpc-block-range-beyond-head.md b/vercel-fix-prompts/18-rpc-block-range-beyond-head.mdnew file mode 100644index 000000000..904298437--- /dev/null+++ b/vercel-fix-prompts/18-rpc-block-range-beyond-head.md@@ -0,0 +1,37 @@+# Fix: RPC eth_getLogs Block Range Exceeds Current Head Block++## Problem++The `index-delegations` cron job logs this error:++```+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: block range extends beyond current head block"}+```++The cron is requesting logs for a block range where the `toBlock` exceeds the current chain head. This happens when the stored "last processed block" cursor is ahead of the actual chain (e.g., due to a bug writing the cursor, or querying a testnet that is behind).++## What to investigate++1. Find the `index-delegations` cron handler — locate where `eth_getLogs` is called and how `fromBlock` and `toBlock` are determined.+2. Check how the cursor (last processed block) is stored and retrieved from the database.+3. Identify if there is a step that fetches the current head block (`eth_blockNumber`) and uses it to cap `toBlock`.++## Expected fix++Always cap `toBlock` to the current chain head before calling `eth_getLogs`:++```js+const currentBlock = await provider.getBlockNumber();+const fromBlock = await getLastProcessedBlock(chainId);+const toBlock = Math.min(fromBlock + MAX_BLOCK_RANGE, currentBlock);++if (fromBlock >= currentBlock) {+ // Nothing new to process+ return;+}++const logs = await provider.getLogs({ fromBlock, toBlock, ... });+await setLastProcessedBlock(chainId, toBlock);+```++Also add a sanity check: if the stored cursor is somehow greater than `currentBlock`, reset it to `currentBlock - 1` and log a warning rather than erroring out.diff --git a/vercel-fix-prompts/19-rpc-operation-aborted-timeouts.md b/vercel-fix-prompts/19-rpc-operation-aborted-timeouts.mdnew file mode 100644index 000000000..6ec789cbd--- /dev/null+++ b/vercel-fix-prompts/19-rpc-operation-aborted-timeouts.md@@ -0,0 +1,41 @@+# Fix: RPC Calls Timing Out / Being Aborted (2,770+ instances)++## Problem++The `index-delegations` cron job logs 2,770+ instances of:++```+{"stage":"index-delegations","chainId":11155111,"error":"This operation was aborted"}+```++`chainId 11155111` = Ethereum Sepolia testnet. The operation is being aborted, likely due to an `AbortController` timeout or the Vercel function timing out while RPC calls are in-flight.++## What to investigate++1. Find the `index-delegations` handler and look for `AbortController` usage — check if there's a timeout set that's too aggressive for Sepolia.+2. Check if Sepolia RPC calls are slower than mainnet (testnet nodes are often less performant).+3. Verify the Sepolia RPC endpoint being used is responsive and not overloaded.+4. Check if the Vercel function's overall 300-second timeout is being hit, which would abort all pending operations.++## Expected fix++**For AbortController timeout being too short:**+```js+// Increase the abort timeout for testnet RPCs+const controller = new AbortController();+const timeout = setTimeout(() => controller.abort(), 30_000); // 30s instead of default+try {+ const logs = await fetchWithAbort(url, { signal: controller.signal });+} finally {+ clearTimeout(timeout);+}+```++**For Vercel function timeout (if the overall cron times out):**+- Process fewer blocks per invocation to complete within time limits.+- Skip Sepolia in production if testnet data isn't needed in prod.+- Use a more reliable Sepolia RPC provider (Alchemy Sepolia, Infura Sepolia).++**For unreliable Sepolia RPC:**+- Switch the Sepolia RPC URL to a more reliable provider.+- Add it as a Vercel environment variable: `RPC_URL_11155111=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY`.diff --git a/vercel-fix-prompts/20-deprecated-fetchconnectioncache.md b/vercel-fix-prompts/20-deprecated-fetchconnectioncache.mdnew file mode 100644index 000000000..0f1a3c546--- /dev/null+++ b/vercel-fix-prompts/20-deprecated-fetchconnectioncache.md@@ -0,0 +1,30 @@+# Fix: Deprecated fetchConnectionCache Option in Web3 Connections++## Problem++Multiple endpoints log this warning:++```+The 'fetchConnectionCache' option is deprecated (now always 'true')+```++This comes from `@solana/web3.js` — the `fetchConnectionCache` option was made the default and the explicit option was deprecated. While it's a warning (not an error), it's cluttering logs.++## What to investigate++1. Search the codebase for `fetchConnectionCache` to find all occurrences.+2. They will likely be in `new Connection(rpcUrl, { fetchConnectionCache: true })` calls.++## Expected fix++Remove the `fetchConnectionCache` option from all `Connection` constructor calls — since it's now always `true` by default, explicitly passing it is unnecessary:++```js+// Before:+const connection = new Connection(rpcUrl, { fetchConnectionCache: true, commitment: 'confirmed' });++// After:+const connection = new Connection(rpcUrl, { commitment: 'confirmed' });+```++Search for all instances and remove the deprecated option. This is a cleanup-only change with no functional impact.diff --git a/vercel.json b/vercel.jsonindex 79cf31817..e3c72ce4b 100644--- a/vercel.json+++ b/vercel.json@@ -321,10 +321,18 @@"src": "/api/agents/([^/]+)/memory/pin","dest": "/api/agents/[id]"},+ {+ "src": "/api/agents/([^/]+)/memory/seed/farcaster",+ "dest": "/api/agents/[id]"+ },{"src": "/api/agents/([^/]+)/memory/([^/]+)","dest": "/api/agents/[id]"},+ {+ "src": "/api/agents/([^/]+)/payments",+ "dest": "/api/agents/[id]"+ },{"src": "/api/agents/([^/]+)/livekit-token","dest": "/api/agents/[id]"@@ -457,6 +465,10 @@"src": "/avatars/([^/]+)","dest": "/avatar-page.html"},+ {+ "src": "/api/users/me/earnings",+ "dest": "/api/users/earnings.js"+ },{"src": "/api/users/([^/]+)","dest": "/api/users/[username]?username=$1"@@ -682,6 +694,14 @@"src": "/api/erc8004/import","dest": "/api/erc8004/import.js"},+ {+ "src": "/api/subscriptions/plans(/.*)?",+ "dest": "/api/subscriptions/plans.js"+ },+ {+ "src": "/api/subscriptions(/.*)?",+ "dest": "/api/subscriptions/index.js"+ },{"src": "/api/dca-strategies/([^/]+)","dest": "/api/dca-strategies?id=$1"@@ -942,6 +962,14 @@{"path": "/api/cron/solana-attest-event-cleanup","schedule": "*/10 * * * *"+ },+ {+ "path": "/api/cron/settle-royalties",+ "schedule": "0 3 * * *"+ },+ {+ "path": "/api/cron/process-subscriptions",+ "schedule": "0 */6 * * *"}]}