Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Refactor code structure for improved readability and maintainability

nirholas83388bb89067
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 526576d41..4b3957e7e 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -5,9 +5,12 @@
* /api/agents/:id/solana/activity — recent on-chain signatures for the wallet
* /api/agents/:id/solana/airdrop — devnet airdrop (1 SOL)
* /api/agents/:id/sns — list owned .sol domains and attach one as the agent's SNS id
- * /api/agents/:id/sns/register — register a .sol; agent wallet pays USDC
- * /api/agents/:id/sns/register-prep — build unsigned tx for user wallet to sign
- * /api/agents/:id/sns/register-confirm — confirm a user-wallet registration and attach
+ * /api/agents/:id/actions — paginated signed action log
+ * /api/agents/:id/animations — owner-only: replace meta.animations
+ * /api/agents/:id/embed-policy — read/write embed policy
+ * /api/agents/:id/manifest — public canonical manifest JSON
+ * /api/agents/:id/sign — owner-only: sign message with server wallet
+ * /api/agents/:id/usage — owner-only: LLM usage stats
*
* /api/agents/:id/pumpfun/* is routed directly to api/agents/pumpfun/[action].js
* by vercel.json — see the rewrite for that path family.
@@ -39,5 +42,35 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'actions') {
+ const mod = await import('./_sub.js');
+ return mod.handleActions(req, res, id);
+ }
+
+ if (sub === 'animations') {
+ const mod = await import('./_sub.js');
+ return mod.handleAnimations(req, res, id);
+ }
+
+ if (sub === 'embed-policy') {
+ const mod = await import('./_sub.js');
+ return mod.handleEmbedPolicy(req, res, id);
+ }
+
+ if (sub === 'manifest') {
+ const mod = await import('./_sub.js');
+ return mod.handleManifest(req, res, id);
+ }
+
+ if (sub === 'sign') {
+ const mod = await import('./_sub.js');
+ return mod.handleSign(req, res, id);
+ }
+
+ if (sub === 'usage') {
+ const mod = await import('./_sub.js');
+ return mod.handleUsage(req, res, id);
+ }
+
return handleGetOne(req, res, id);
});
diff --git a/api/agents/[id]/_sub.js b/api/agents/[id]/_sub.js
new file mode 100644
index 000000000..8ebf1d2e7
--- /dev/null
+++ b/api/agents/[id]/_sub.js
@@ -0,0 +1,223 @@
+// Private module: agent sub-resource handlers dispatched from [id].js.
+// Not a Vercel function (underscore prefix). Handlers accept (req, res, id).
+
+import { verifyMessage } from 'ethers';
+import { Wallet } from 'ethers';
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { recoverAgentKey } from '../../_lib/agent-wallet.js';
+import { readEmbedPolicy, validateEmbedPolicy } from '../../_lib/embed-policy.js';
+import { resolveAvatarUrl } from '../../_lib/avatars.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// ── actions ───────────────────────────────────────────────────────────────────
+
+export const handleActions = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+
+ const [agent] = await sql`SELECT id, user_id, name, wallet_address FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!userId || agent.user_id !== userId) return error(res, 403, 'forbidden', 'not authorized to view this agent');
+
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+ const cursor = url.searchParams.get('cursor');
+
+ const actions = cursor
+ ? await sql`SELECT id, type, payload, source_skill, signature, signer_address, created_at FROM agent_actions WHERE agent_id = ${id} AND created_at < ${cursor} ORDER BY created_at DESC LIMIT ${limit + 1}`
+ : await sql`SELECT id, type, payload, source_skill, signature, signer_address, created_at FROM agent_actions WHERE agent_id = ${id} ORDER BY created_at DESC LIMIT ${limit + 1}`;
+
+ const hasMore = actions.length > limit;
+ const trimmed = hasMore ? actions.slice(0, limit) : actions;
+
+ const decorated = trimmed.map((row) => {
+ let verified = null;
+ if (row.signature && row.signer_address && row.payload) {
+ try {
+ const recovered = verifyMessage(JSON.stringify(row.payload) + row.created_at.toISOString(), row.signature);
+ verified = recovered.toLowerCase() === row.signer_address.toLowerCase();
+ } catch { verified = false; }
+ }
+ return { id: String(row.id), type: row.type, payload: row.payload, sourceSkill: row.source_skill, timestamp: row.created_at.toISOString(), signature: row.signature || null, signer: row.signer_address || null, verified };
+ });
+
+ res.setHeader('Cache-Control', 'private, max-age=10');
+ return json(res, 200, { actions: decorated, nextCursor: hasMore ? trimmed[trimmed.length - 1].created_at.toISOString() : null });
+});
+
+// ── animations ────────────────────────────────────────────────────────────────
+
+const animationEntrySchema = z.object({
+ name: z.string().trim().min(1).max(60),
+ url: z.string().trim().min(1).max(2048).refine((u) => /^(https?|ipfs|ar):\/\//.test(u) || u.startsWith('/') || /^u\//.test(u), 'url must be http, https, ipfs, ar, root-relative, or storage key'),
+ loop: z.boolean().default(true),
+ clipName: z.string().trim().max(120).optional(),
+ source: z.enum(['mixamo', 'preset', 'custom']),
+ addedAt: z.string().optional(),
+});
+
+const animationsBodySchema = z.object({ animations: z.array(animationEntrySchema).max(30) });
+
+export const handleAnimations = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PUT'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [existing] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ let parsed;
+ try { parsed = animationsBodySchema.parse(await readJson(req)); }
+ catch (err) { if (err.name === 'ZodError') return error(res, 400, 'validation_error', err.errors[0]?.message || 'invalid body', { fields: err.errors }); throw err; }
+
+ await sql`UPDATE agent_identities SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{animations}', ${JSON.stringify(parsed.animations)}::jsonb, true) WHERE id = ${id}`;
+ return json(res, 200, { animations: parsed.animations });
+});
+
+// ── embed-policy ──────────────────────────────────────────────────────────────
+
+export const handleEmbedPolicy = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;
+
+ if (req.method === 'GET') {
+ const policy = await readEmbedPolicy(id);
+ if (policy === null) {
+ const [row] = await sql`SELECT id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ }
+ return json(res, 200, { policy: policy ?? null });
+ }
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [existing] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (existing.user_id !== session.id) return error(res, 403, 'forbidden', 'not your agent');
+
+ if (req.method === 'DELETE') {
+ await sql`UPDATE agent_identities SET embed_policy = NULL WHERE id = ${id}`;
+ return json(res, 200, { policy: null });
+ }
+
+ let normalized;
+ try { normalized = validateEmbedPolicy(await readJson(req)); }
+ catch (err) { if (err.name === 'ZodError') return error(res, 400, 'validation_error', err.errors[0]?.message || 'invalid policy', { fields: err.errors }); throw err; }
+
+ const [updated] = await sql`UPDATE agent_identities SET embed_policy = ${JSON.stringify(normalized)}::jsonb WHERE id = ${id} RETURNING embed_policy`;
+ return json(res, 200, { policy: updated.embed_policy });
+});
+
+// ── manifest ──────────────────────────────────────────────────────────────────
+
+export const handleManifest = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ 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, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+
+ let bodyUri = '';
+ if (row.avatar_db_id) {
+ try { const urlInfo = await resolveAvatarUrl({ storage_key: row.storage_key, visibility: 'public' }); bodyUri = urlInfo?.url || ''; } catch {}
+ }
+
+ const proto = req.headers['x-forwarded-proto'] || 'https';
+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ const origin = process.env.PUBLIC_APP_ORIGIN?.replace(/\/$/, '') || `${proto}://${host}`;
+
+ const manifest = {
+ $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',
+ spec: 'agent-manifest/0.1',
+ id: row.id,
+ name: row.name || 'Agent',
+ description: row.description || '',
+ image: '',
+ tags: Array.isArray(row.meta?.tags) ? row.meta.tags : [],
+ body: bodyUri ? { uri: bodyUri, format: row.content_type || 'gltf-binary' } : undefined,
+ skills: Array.isArray(row.skills) ? row.skills : [],
+ homeUrl: `${origin}/agent/${row.id}`,
+ registrations: row.chain_id && row.erc8004_agent_id ? [{ agentRegistry: `eip155:${row.chain_id}:${row.erc8004_registry}`, agentId: row.erc8004_agent_id }] : [],
+ createdAt: row.created_at,
+ };
+
+ return json(res, 200, manifest, { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400', 'access-control-allow-origin': '*' });
+});
+
+// ── sign ──────────────────────────────────────────────────────────────────────
+
+const signBody = z.object({ message: z.string().min(1).max(8192), kind: z.enum(['personal']).default('personal') });
+
+export const handleSign = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many sign requests');
+
+ const [row] = await sql`SELECT id, user_id, wallet_address, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL LIMIT 1`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const encryptedKey = row.meta?.encrypted_wallet_key;
+ if (!encryptedKey) return error(res, 409, 'no_wallet', 'agent has no server wallet');
+
+ const body = parse(signBody, await readJson(req));
+
+ let signature;
+ try {
+ const pkHex = await recoverAgentKey(encryptedKey);
+ signature = await new Wallet(pkHex).signMessage(body.message);
+ } catch (e) {
+ console.error('[agents/sign] signing failed', e);
+ return error(res, 500, 'sign_failed', 'could not sign message');
+ }
+
+ return json(res, 200, { address: row.wallet_address, signature });
+});
+
+// ── usage ─────────────────────────────────────────────────────────────────────
+
+export const handleUsage = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] = await sql`SELECT id FROM agent_identities WHERE id = ${id} AND user_id = ${session.id} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const policy = await readEmbedPolicy(id);
+ const monthlyQuota = policy?.brain?.monthly_quota ?? null;
+
+ const [monthRow] = await sql`SELECT COUNT(*)::int AS total FROM usage_events WHERE agent_id = ${id} AND kind = 'llm' AND created_at >= date_trunc('month', now())`;
+ const dailyRows = await sql`SELECT date_trunc('day', created_at)::date AS day, COUNT(*)::int AS calls FROM usage_events WHERE agent_id = ${id} AND kind = 'llm' AND created_at >= now() - interval '30 days' GROUP BY 1 ORDER BY 1`;
+
+ return json(res, 200, { agentId: id, monthlyQuota, currentMonthCalls: monthRow?.total ?? 0, dailyBreakdown: dailyRows.map((r) => ({ day: r.day, calls: r.calls })) });
+});
diff --git a/api/agents/register/[action].js b/api/agents/register/[action].js
new file mode 100644
index 000000000..9c4c7524a
--- /dev/null
+++ b/api/agents/register/[action].js
@@ -0,0 +1,139 @@
+// Consolidated ERC-8004 agent registration endpoints.
+// prep: build metadata + pin + store record
+// confirm: verify on-chain tx, upsert agent_identities
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+import { r2 } from '../../_lib/r2.js';
+import { SERVER_CHAIN_META } from '../../_lib/onchain.js';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';
+import { z } from 'zod';
+import { createHash } from 'crypto';
+
+// ── prep ──────────────────────────────────────────────────────────────────────
+
+const prepSchema = z.object({
+ name: z.string().trim().min(1).max(60),
+ description: z.string().trim().max(280),
+ avatarId: z.string().uuid(),
+ brain: z.object({ provider: z.string().optional(), model: z.string().optional(), instructions: z.string().optional() }).optional(),
+ skills: z.array(z.string().regex(/^[a-z0-9-]{1,40}$/i)).max(16).optional(),
+ embedPolicy: z.record(z.any()).optional(),
+ demoSlug: z.string().optional(),
+});
+
+async function pinRegistrationJson(jsonObj) {
+ const jsonStr = JSON.stringify(jsonObj);
+ const jsonBytes = Buffer.from(jsonStr, 'utf-8');
+ const token = process.env.WEB3_STORAGE_TOKEN;
+ if (token) {
+ try {
+ const res = await fetch('https://api.web3.storage/upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: jsonBytes });
+ if (res.ok) {
+ const r = await res.json();
+ if (r.cid) return { cid: r.cid, metadataURI: `ipfs://${r.cid}` };
+ }
+ } catch {}
+ }
+ const contentHash = createHash('sha256').update(jsonStr).digest('hex');
+ const stubCid = `bafkreigenerated${contentHash.slice(0, 40)}`;
+ const key = `agent-registrations/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
+ await r2.send(new PutObjectCommand({ Bucket: env.S3_BUCKET, Key: key, Body: jsonBytes, ContentType: 'application/json' }));
+ return { cid: stubCid, metadataURI: `ipfs://${stubCid}` };
+}
+
+async function handlePrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const body = parse(prepSchema, await readJson(req));
+ const [avatar] = await sql`select id from avatars where id = ${body.avatarId} and owner_id = ${session.id} and deleted_at is null limit 1`;
+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
+ const registrationJson = {
+ $schema: 'https://3d-agent.io/schemas/manifest/0.1.json', spec: 'agent-manifest/0.1',
+ name: body.name, description: body.description, image: '', tags: [],
+ body: { uri: '', format: 'gltf-binary' }, _baseURI: `ipfs://`,
+ ...(body.brain && { brain: body.brain }),
+ ...(body.skills?.length > 0 && { skills: body.skills }),
+ ...(body.embedPolicy && { embedPolicy: body.embedPolicy }),
+ ...(body.demoSlug && { demoSlug: body.demoSlug }),
+ };
+ const { cid, metadataURI } = await pinRegistrationJson(registrationJson);
+ const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
+ const [prep] = await sql`insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at) values (${session.id}, ${cid}, ${metadataURI}, ${JSON.stringify(registrationJson)}::jsonb, ${expiresAt}) returning id`;
+ return json(res, 200, { ok: true, cid, metadataURI, prepId: prep.id });
+}
+
+// ── confirm ───────────────────────────────────────────────────────────────────
+
+const confirmSchema = z.object({
+ prepId: z.string().uuid(),
+ chainId: z.number().int().positive(),
+ agentId: z.union([z.string(), z.number()]),
+ txHash: z.string().regex(/^0x[a-f0-9]{64}$/i),
+});
+
+function eventSignatureHash(sig) { return keccak256(toUtf8Bytes(sig)); }
+
+async function fetchTransactionReceipt(rpcUrl, txHash) {
+ const res = await fetch(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getTransactionReceipt', params: [txHash] }) });
+ const data = await res.json();
+ if (data.error) throw new Error(`RPC error: ${data.error.message}`);
+ return data.result;
+}
+
+function parseRegisteredEvent(logs, registryAddress) {
+ const registryAddr = getAddress(registryAddress);
+ const topic0 = eventSignatureHash('Registered(uint256,string,address)');
+ for (const log of logs) {
+ if (getAddress(log.address) === registryAddr && log.topics[0] === topic0) {
+ return AbiCoder.defaultAbiCoder().decode(['string'], log.data)[0];
+ }
+ }
+ throw new Error('Registered event not found in receipt');
+}
+
+async function handleConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const body = parse(confirmSchema, await readJson(req));
+ const chainMeta = SERVER_CHAIN_META[body.chainId];
+ if (!chainMeta) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
+ const [prep] = await sql`select id, cid, metadata_uri, payload from agent_registrations_pending where id = ${body.prepId} and user_id = ${session.id} and expires_at > now() limit 1`;
+ if (!prep) return error(res, 404, 'not_found', 'prep record not found or expired');
+ let receipt;
+ try { receipt = await fetchTransactionReceipt(chainMeta.rpc, body.txHash); }
+ catch (err) { return error(res, 400, 'bad_request', `tx verification failed: ${err.message}`); }
+ if (!receipt) return error(res, 400, 'bad_request', 'tx not found or still pending');
+ if (receipt.status !== 1) return error(res, 400, 'bad_request', 'tx failed on-chain');
+ let agentURI;
+ try { agentURI = parseRegisteredEvent(receipt.logs, chainMeta.registry); }
+ catch (err) { return error(res, 400, 'bad_request', `failed to parse event: ${err.message}`); }
+ if (agentURI !== prep.metadata_uri) return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`);
+ const [updated] = await sql`insert into agent_identities (user_id, name, description, avatar_id, chain_id, erc8004_agent_id, erc8004_registry, registration_cid) values (${session.id}, ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)}, ${(prep.payload.description || '').slice(0, 1000)}, null, ${body.chainId}, ${String(body.agentId)}, ${chainMeta.registry}, ${prep.cid}) on conflict (user_id) do update set name=excluded.name, description=excluded.description, chain_id=excluded.chain_id, erc8004_agent_id=excluded.erc8004_agent_id, erc8004_registry=excluded.erc8004_registry, registration_cid=excluded.registration_cid, updated_at=now() returning id`;
+ await sql`delete from agent_registrations_pending where id = ${body.prepId}`;
+ return json(res, 200, { ok: true, agentId: updated.id });
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = { prep: handlePrep, confirm: handleConfirm };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown register action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/agents/sas/[action].js b/api/agents/sas/[action].js
new file mode 100644
index 000000000..95362209b
--- /dev/null
+++ b/api/agents/sas/[action].js
@@ -0,0 +1,88 @@
+// Consolidated SAS credential endpoints (credentials + issue-credential).
+
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { requireAdmin } from '../../_lib/admin.js';
+import { sasIssue, SAS_CONFIG } from '../../_lib/sas.js';
+import { z } from 'zod';
+
+// ── credentials (GET) ─────────────────────────────────────────────────────────
+
+async function handleCredentials(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const subject = url.searchParams.get('subject');
+ const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
+ const kind = url.searchParams.get('kind') || null;
+ const includeClosed = url.searchParams.get('include_closed') === '1';
+
+ if (!subject) return error(res, 400, 'validation_error', 'subject required');
+
+ const rows = kind
+ ? await sql`select attestation_pda, schema_pda, credential_pda, kind, subject, issuer_signature, data, expiry, closed, issued_at from solana_credentials where subject = ${subject} and network = ${network} and kind = ${kind} and (${includeClosed} or closed = false) and (expiry is null or expiry > now()) order by issued_at desc`
+ : await sql`select attestation_pda, schema_pda, credential_pda, kind, subject, issuer_signature, data, expiry, closed, issued_at from solana_credentials where subject = ${subject} and network = ${network} and (${includeClosed} or closed = false) and (expiry is null or expiry > now()) order by issued_at desc`;
+
+ return json(res, 200, { subject, network, kind, count: rows.length, data: rows });
+}
+
+// ── issue-credential (POST, admin-only) ───────────────────────────────────────
+
+const SCHEMAS = Object.keys(SAS_CONFIG.schemas);
+
+const issueSchema = z.object({
+ kind: z.enum(SCHEMAS),
+ subject: z.string().min(32).max(44),
+ data: z.record(z.any()).default({}),
+ expiry: z.number().int().nonnegative().default(0),
+ network: z.enum(['devnet', 'mainnet']).default('devnet'),
+});
+
+async function handleIssueCredential(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(issueSchema, await readJson(req));
+ const def = SAS_CONFIG.schemas[body.kind];
+ for (let i = 0; i < def.fieldNames.length; i++) {
+ const fname = def.fieldNames[i];
+ const v = body.data[fname];
+ if (v === undefined) return error(res, 400, 'validation_error', `missing field: ${fname}`);
+ const t = def.layout[i];
+ if (t === 12 && typeof v !== 'string') return error(res, 400, 'validation_error', `${fname} must be string`);
+ if (t === 10 && typeof v !== 'boolean') return error(res, 400, 'validation_error', `${fname} must be bool`);
+ if (t === 0 && (!Number.isInteger(v) || v < 0 || v > 255)) return error(res, 400, 'validation_error', `${fname} must be u8`);
+ }
+
+ let result;
+ try { result = await sasIssue({ kind: body.kind, subject: body.subject, data: body.data, expiry: body.expiry, network: body.network }); }
+ catch (e) { return error(res, 500, 'sas_issue_failed', e.message || String(e)); }
+
+ const expiryDate = body.expiry > 0 ? new Date(body.expiry * 1000) : null;
+ await sql`insert into solana_credentials (attestation_pda, network, schema_pda, credential_pda, kind, subject, issuer_signature, data, expiry) values (${result.attestation_pda}, ${body.network}, ${result.schema_pda}, ${result.credential_pda}, ${body.kind}, ${body.subject}, ${result.signature}, ${JSON.stringify(body.data)}::jsonb, ${expiryDate}) on conflict (attestation_pda) do update set data=excluded.data, expiry=excluded.expiry, issuer_signature=excluded.issuer_signature, closed=false, closed_at=null`;
+
+ return json(res, 201, { signature: result.signature, attestation_pda: result.attestation_pda, schema_pda: result.schema_pda, credential_pda: result.credential_pda, kind: body.kind, subject: body.subject });
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = { credentials: handleCredentials, 'issue-credential': handleIssueCredential };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown sas action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
new file mode 100644
index 000000000..3f7e082d5
--- /dev/null
+++ b/api/agents/x402/[action].js
@@ -0,0 +1,96 @@
+// Consolidated x402 payment endpoints (invoke + manifest).
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';
+
+const HANDLERS = { echo: async (args) => ({ ok: true, echoed: args }) };
+
+function priceFor(agent, skill) {
+ const prices = agent.meta?.skill_prices || {};
+ const defaultPrice = agent.meta?.payments?.default_price;
+ const fromMap = prices[skill];
+ if (fromMap?.amount && fromMap?.currency) return fromMap;
+ if (defaultPrice?.amount && defaultPrice?.currency) return defaultPrice;
+ const cluster = agent.meta?.payments?.cluster || 'mainnet';
+ return { amount: '10000', currency: cluster === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' };
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, scope: bearer.scope };
+ return null;
+}
+
+// ── invoke ────────────────────────────────────────────────────────────────────
+
+const invokeSchema = z.object({ agent_id: z.string().min(1).max(80), skill: z.string().min(1).max(64), args: z.record(z.any()).default({}) });
+
+async function handleInvoke(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(invokeSchema, await readJson(req));
+ const [agent] = await sql`select id, name, meta from agent_identities where id = ${body.agent_id} and deleted_at is null limit 1`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
+ if (!HANDLERS[body.skill]) return error(res, 404, 'unknown_skill', `skill "${body.skill}" is not registered`);
+
+ const price = priceFor(agent, body.skill);
+ const paid = await verifyPaid(req, { agentId: agent.id, skill: body.skill, expectedAmount: price.amount, expectedCurrency: price.currency });
+ if (!paid) return emit402(res, { agent, skill: body.skill, amount: price.amount, currency: price.currency });
+
+ await consumeIntent(paid.intentId);
+ const result = await HANDLERS[body.skill](body.args, { agent, caller: auth });
+ return json(res, 200, { ok: true, intent_id: paid.intentId, amount: paid.amount, currency: paid.currency, result });
+}
+
+// ── manifest ──────────────────────────────────────────────────────────────────
+
+async function handleManifest(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const agent_id = url.searchParams.get('agent_id');
+ const skill = url.searchParams.get('skill');
+ if (!agent_id || !skill) return error(res, 400, 'validation_error', 'agent_id and skill required');
+
+ const [agent] = await sql`select id, name, meta from agent_identities where id = ${agent_id} and deleted_at is null limit 1`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) return error(res, 409, 'no_payments', 'agent has not enabled payments');
+
+ const cluster = agent.meta.payments.cluster || 'mainnet';
+ const fallbackCurrency = cluster === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+ const prices = agent.meta.skill_prices || {};
+ const def = agent.meta.payments.default_price;
+ const price = prices[skill] || def || { amount: '10000', currency: fallbackCurrency };
+
+ return manifestOnly(res, { agent, skill, amount: price.amount, currency: price.currency });
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = { invoke: handleInvoke, manifest: handleManifest };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown x402 action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/auth/wallet/[action].js b/api/auth/wallet/[action].js
new file mode 100644
index 000000000..a3db1ef86
--- /dev/null
+++ b/api/auth/wallet/[action].js
@@ -0,0 +1,115 @@
+// Consolidated wallet link/unlink endpoints.
+
+import { verifyMessage, getAddress } from 'ethers';
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+import { parse } from '../../_lib/validate.js';
+import { parseSiweMessage } from '../../_lib/siwe.js';
+
+// ── link ──────────────────────────────────────────────────────────────────────
+
+const linkSchema = z.object({ message: z.string().min(64).max(4000), signature: z.string().regex(/^0x[a-fA-F0-9]+$/) });
+
+async function handleLink(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.walletLink(String(user.id));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');
+
+ const body = parse(linkSchema, await readJson(req));
+ const fields = parseSiweMessage(body.message);
+ if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');
+
+ const appOrigin = env.APP_ORIGIN;
+ const appHost = new URL(appOrigin).host;
+ const vercelHost = process.env.VERCEL_URL || null;
+ const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
+ if (!allowedHosts.has(fields.domain)) return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);
+
+ try {
+ const u = new URL(fields.uri);
+ const allowedOrigins = new Set([appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean));
+ if (!allowedOrigins.has(u.origin)) return error(res, 400, 'invalid_uri', 'uri origin mismatch');
+ } catch { return error(res, 400, 'invalid_uri', 'uri not a valid URL'); }
+
+ const now = Date.now();
+ if (fields.expirationTime && Date.parse(fields.expirationTime) < now) return error(res, 400, 'expired', 'message expired');
+ if (fields.notBefore && Date.parse(fields.notBefore) > now) return error(res, 400, 'not_yet_valid', 'message not yet valid');
+
+ const [nonceRow] = await sql`select nonce, expires_at, consumed_at from siwe_nonces where nonce = ${fields.nonce} limit 1`;
+ if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');
+ if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');
+ if (new Date(nonceRow.expires_at) < new Date()) return error(res, 400, 'nonce_expired', 'nonce expired');
+
+ let recovered;
+ try { recovered = verifyMessage(body.message, body.signature); } catch { return error(res, 401, 'invalid_signature', 'signature verification failed'); }
+ let claimed;
+ try { claimed = getAddress(fields.address); } catch { return error(res, 400, 'invalid_address', 'address not checksummed correctly'); }
+ if (recovered.toLowerCase() !== claimed.toLowerCase()) return error(res, 401, 'invalid_signature', 'signer does not match address');
+
+ const burned = await sql`update siwe_nonces set consumed_at = now(), address = ${claimed.toLowerCase()} where nonce = ${fields.nonce} and consumed_at is null returning nonce`;
+ if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');
+
+ const addrLower = claimed.toLowerCase();
+ const [existing] = await sql`select user_id from user_wallets where address = ${addrLower} limit 1`;
+ if (existing) {
+ if (String(existing.user_id) !== String(user.id)) return error(res, 409, 'wallet_taken', 'wallet already linked to another account');
+ return json(res, 200, { ok: true, address: claimed, chainId: fields.chainId || null });
+ }
+
+ await sql`insert into user_wallets (user_id, address, chain_id, is_primary) values (${user.id}, ${addrLower}, ${fields.chainId || null}, false)`;
+ return json(res, 200, { ok: true, address: claimed, chainId: fields.chainId || null });
+}
+
+// ── unlink ────────────────────────────────────────────────────────────────────
+
+const unlinkSchema = z.object({ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/) });
+
+async function handleUnlink(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');
+
+ const body = parse(unlinkSchema, await readJson(req));
+ const addrLower = body.address.toLowerCase();
+
+ const [walletRow] = await sql`select address, is_primary from user_wallets where user_id = ${user.id} and address = ${addrLower} limit 1`;
+ if (!walletRow) return error(res, 404, 'not_found', 'wallet not linked to your account');
+
+ const [userRow] = await sql`select password_hash from users where id = ${user.id} limit 1`;
+ if (!userRow?.password_hash) {
+ const [{ count }] = await sql`select count(*)::int as count from user_wallets where user_id = ${user.id}`;
+ if (count <= 1) return error(res, 409, 'last_auth_method', 'cannot remove your only authentication method');
+ }
+
+ if (walletRow.is_primary) {
+ await sql`update user_wallets set is_primary = true where user_id = ${user.id} and address != ${addrLower} and address = (select address from user_wallets where user_id = ${user.id} and address != ${addrLower} order by last_used_at desc nulls last limit 1)`;
+ }
+
+ await sql`delete from user_wallets where user_id = ${user.id} and address = ${addrLower}`;
+ return json(res, 200, { ok: true });
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = { link: handleLink, unlink: handleUnlink };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown wallet action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index ab161bd1d..5814a0324 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -1,6 +1,7 @@
-// GET /api/avatars/:id — fetch one (public if visibility allows, else requires auth)
-// PATCH /api/avatars/:id — update metadata (owner only)
-// DELETE /api/avatars/:id — soft-delete (owner only)
+// GET /api/avatars/:id — fetch one (public if visibility allows, else requires auth)
+// PATCH /api/avatars/:id — update metadata (owner only)
+// DELETE /api/avatars/:id — soft-delete (owner only)
+// Also dispatches: presign, public, regenerate, regenerate-status (action endpoints)
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import {
@@ -25,13 +26,22 @@ const patchSchema = z.object({
tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
});
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+// Action endpoints that share this file (no id needed)
+const ACTION_ENDPOINTS = new Set(['presign', 'public', 'regenerate', 'regenerate-status']);
+export default wrap(async (req, res) => {
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').pop();
if (!id) return error(res, 400, 'invalid_request', 'id required');
+ // Dispatch named action endpoints (presign, public, regenerate, regenerate-status)
+ if (ACTION_ENDPOINTS.has(id)) {
+ const mod = await import('./_actions.js');
+ return mod.dispatch(id, req, res);
+ }
+
+ if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+
const auth = await resolveAuth(req);
if (req.method === 'GET') {
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
new file mode 100644
index 000000000..52bbc7dfa
--- /dev/null
+++ b/api/avatars/_actions.js
@@ -0,0 +1,128 @@
+// Private module: avatar action endpoints dispatched from [id].js.
+// presign, public, regenerate, regenerate-status
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { presignUpload, headObject, r2 } from '../_lib/r2.js';
+import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';
+import { listAvatars, createAvatar } from '../_lib/avatars.js';
+import { HeadObjectCommand } from '@aws-sdk/client-s3';
+import { env } from '../_lib/env.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from '../_lib/validate.js';
+import { recordEvent } from '../_lib/usage.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { z } from 'zod';
+import { randomUUID } from 'crypto';
+
+// ── presign ───────────────────────────────────────────────────────────────────
+
+async function resolvePresignUser(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });
+ if (!bearer || !hasScope(bearer.scope, requiredScope)) return null;
+ return bearer.userId;
+}
+
+const handlePresign = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolvePresignUser(req, 'avatars:write');
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+ const rl = await limits.upload(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');
+ const body = parse(presignUploadBody, await readJson(req));
+ try { await enforceQuotas(userId, body.size_bytes); }
+ catch (err) { return error(res, err.status || 402, err.code || 'plan_limit', err.message); }
+ const bodyAny = body;
+ const slug = bodyAny.slug ? slugSchema.parse(bodyAny.slug) : `draft-${Math.random().toString(36).slice(2, 8)}`;
+ const key = storageKeyFor({ userId, slug });
+ const url = await presignUpload({ key, contentType: body.content_type, contentLength: body.size_bytes });
+ return json(res, 200, { storage_key: key, upload_url: url, method: 'PUT', headers: { 'content-type': body.content_type }, expires_in: 300 });
+});
+
+// ── public ────────────────────────────────────────────────────────────────────
+
+const handlePublic = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const url = new URL(req.url, 'http://x');
+ const result = await searchPublicAvatars({ q: url.searchParams.get('q') || undefined, tag: url.searchParams.get('tag') || undefined, limit: Number(url.searchParams.get('limit')) || 24, cursor: url.searchParams.get('cursor') || undefined });
+ result.avatars = result.avatars.map((a) => stripOwnerFor(a, null));
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=60');
+ return json(res, 200, result);
+});
+
+// ── regenerate ────────────────────────────────────────────────────────────────
+
+const regenerateSchema = z.object({
+ sourceAvatarId: z.string().trim().min(1).max(100),
+ mode: z.enum(['remesh', 'retex', 'rerig', 'restyle']),
+ params: z.record(z.unknown()).optional(),
+});
+
+async function resolveRegenUser(req) {
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return null;
+ if (bearer && !hasScope(bearer.scope, 'avatars:write')) return null;
+ return session?.id ?? bearer?.userId;
+}
+
+const handleRegenerate = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolveRegenUser(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+ const rl = await limits.upload(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const body = parse(regenerateSchema, await readJson(req));
+ const rows = await sql`select id, name, storage_key from avatars where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null limit 1`;
+ if (!rows[0]) return error(res, 404, 'not_found', 'source avatar not found or not owned');
+ const provider = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();
+ if (provider === 'none' || !provider) return error(res, 501, 'regen_unconfigured', 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.');
+ if (provider === 'stub') {
+ const jobId = `stub-${randomUUID()}`;
+ await sql`insert into avatar_regen_jobs (job_id, user_id, source_avatar_id, mode, params, status, created_at) values (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', now())`;
+ return json(res, 202, { ok: true, jobId, status: 'queued', eta: null });
+ }
+ return error(res, 501, 'regen_provider_error', `Unknown provider: ${provider}`);
+});
+
+// ── regenerate-status ─────────────────────────────────────────────────────────
+
+const handleRegenerateStatus = 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 or provide a valid bearer token');
+ if (bearer && !hasScope(bearer.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', 'avatars:read scope required');
+ const userId = session?.id ?? bearer?.userId;
+ const url = new URL(req.url, 'http://x');
+ const jobId = url.searchParams.get('jobId');
+ if (!jobId) return error(res, 400, 'invalid_request', 'jobId required');
+ const rows = await sql`select job_id, status, result_avatar_id, error, created_at from avatar_regen_jobs where job_id = ${jobId} and user_id = ${userId} limit 1`;
+ if (!rows[0]) return error(res, 404, 'not_found', 'job not found');
+ const job = rows[0];
+ const response = { ok: true, jobId: job.job_id, status: job.status };
+ if (job.result_avatar_id) response.resultAvatarId = job.result_avatar_id;
+ if (job.error) response.error = job.error;
+ return json(res, 200, response);
+});
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = {
+ presign: handlePresign,
+ public: handlePublic,
+ regenerate: handleRegenerate,
+ 'regenerate-status': handleRegenerateStatus,
+};
+
+export function dispatch(action, req, res) {
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown avatar action: ${action}`);
+ return fn(req, res);
+}
diff --git a/api/onboarding/[action].js b/api/onboarding/[action].js
new file mode 100644
index 000000000..ec84e0c8c
--- /dev/null
+++ b/api/onboarding/[action].js
@@ -0,0 +1,93 @@
+// Consolidated onboarding endpoints (avaturn-session + link-avatar).
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { env } from '../_lib/env.js';
+
+// ── avaturn-session ───────────────────────────────────────────────────────────
+
+const dataUrl = z.string().max(2_500_000).regex(/^data:image\/(jpeg|png);base64,/i, 'must be a data:image/(jpeg|png);base64 url');
+const avaturnSchema = z.object({
+ photos: z.object({ frontal: dataUrl, left: dataUrl, right: dataUrl }),
+ body_type: z.enum(['male', 'female']).default('male'),
+ avatar_type: z.enum(['v1', 'v2']).default('v1'),
+});
+
+async function resolveAvaturnUser(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });
+ if (!bearer || !hasScope(bearer.scope, 'avatars:write')) return null;
+ return bearer.userId;
+}
+
+async function handleAvaturnSession(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolveAvaturnUser(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to create an avatar');
+ const rlUser = await limits.upload(userId);
+ if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many avatar attempts, try again later');
+ const rlIp = await limits.authIp(clientIp(req));
+ if (!rlIp.success) return error(res, 429, 'rate_limited', 'too many requests from this network');
+ if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.');
+ const body = parse(avaturnSchema, await readJson(req, 8_000_000));
+ try {
+ const url = `${env.AVATURN_API_URL}/api/v1/sessions`;
+ const upstream = await fetch(url, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${env.AVATURN_API_KEY}`, 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ external_user_id: userId, photos: body.photos, body_type: body.body_type, version: body.avatar_type }),
+ });
+ if (!upstream.ok) {
+ const text = await upstream.text().catch(() => '');
+ const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);
+ err.status = upstream.status >= 500 ? 502 : upstream.status;
+ err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';
+ throw err;
+ }
+ const data = await upstream.json();
+ const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
+ if (!sessionUrl) { const e = new Error('avaturn response missing session_url'); e.status = 502; e.code = 'upstream_error'; throw e; }
+ return json(res, 200, { session_url: sessionUrl, expires_at: data.expires_at ?? null });
+ } catch (err) {
+ if (err.status >= 500) console.error('[avaturn-session] upstream failure:', err);
+ return error(res, err.status || 502, err.code || 'upstream_error', err.message || 'avatar provider rejected request');
+ }
+}
+
+// ── link-avatar ───────────────────────────────────────────────────────────────
+
+const linkAvatarSchema = z.object({ avatarId: z.string().uuid(), force: z.boolean().default(false) });
+
+async function handleLinkAvatar(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) 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 body = parse(linkAvatarSchema, await readJson(req));
+ const [avatar] = await sql`select id from avatars where id = ${body.avatarId} and owner_id = ${userId} and deleted_at is null limit 1`;
+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found or not owned by you');
+ const [agent] = await sql`select id, avatar_id from agent_identities where user_id = ${userId} and deleted_at is null order by created_at asc limit 1`;
+ if (!agent) return error(res, 404, 'not_found', 'no agent identity found for user');
+ if (agent.avatar_id && agent.avatar_id !== body.avatarId && !body.force) return error(res, 409, 'already_linked', 'agent already has an avatar; pass force: true to override', { current_avatar_id: agent.avatar_id });
+ const [updated] = await sql`update agent_identities set avatar_id = ${body.avatarId}, updated_at = now() where id = ${agent.id} returning id, avatar_id, updated_at`;
+ return json(res, 200, { agent: updated });
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────
+
+const DISPATCH = { 'avaturn-session': handleAvaturnSession, 'link-avatar': handleLinkAvatar };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown onboarding action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 159515f59..d23959b73 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -91,19 +91,18 @@ const wrapped = wrap(async (req, res) => {
case 'strategy-backtest': return handleStrategyBacktest(req, res);
case 'strategy-close-all': return handleStrategyCloseAll(req, res);
case 'strategy-validate': return handleStrategyValidate(req, res);
+ case 'channel-feed': return handleChannelFeed(req, res);
+ case 'deliver-telegram': return handleDeliverTelegram(req, res);
+ case 'first-claims': return handleFirstClaims(req, res);
default:
return error(res, 404, 'not_found', 'unknown pump action');
}
});
-// strategy-run is SSE — it manages its own response writes and must bypass
-// wrap()'s JSON-error fallback once the stream is open. Route it before the
-// wrapped dispatcher to preserve the original endpoint's exported shape
-// (default async function handler).
+// strategy-run and vanity-keygen are SSE — bypass wrap()'s JSON-error fallback.
export default async function dispatcher(req, res) {
- if (req.query?.action === 'strategy-run') {
- return handleStrategyRun(req, res);
- }
+ if (req.query?.action === 'strategy-run') return handleStrategyRun(req, res);
+ if (req.query?.action === 'vanity-keygen') return handleVanityKeygen(req, res);
return wrapped(req, res);
}
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 3e8e3ea5b..6006bd732 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -53,7 +53,7 @@
feUser,
feX,
} from './feather.js';
- import { defaultToolSchema, agentToolSchema } from './tools.js';
+ import { defaultToolSchema, agentToolSchema, pumpToolSchema } from './tools.js';
import { debounce, readFileAsDataURL } from './util.js';
import { flash } from './actions';
import Message from './Message.svelte';
@@ -1051,9 +1051,13 @@
// Init client tools with default values
if ($toolSchema.length === 0 && !window.localStorage.getItem('initializedClientTools')) {
- $toolSchema = defaultToolSchema;
+ $toolSchema = [...defaultToolSchema, pumpToolSchema];
window.localStorage.setItem('initializedClientTools', 'true');
} else {
+ // Add pump tool group for existing users who already initialized
+ if (!$toolSchema.some(g => g.name === 'Pump.fun & Crypto')) {
+ $toolSchema = [...$toolSchema, pumpToolSchema];
+ }
// Add any missing client tools to the client-side group
const clientGroup = $toolSchema.find((g) => g.name === 'Client-side');
const defaultClientGroup = defaultToolSchema.find((g) => g.name === 'Client-side');
@@ -1211,7 +1215,7 @@
{#if generating && new URLSearchParams(window.location.search).get('vibe') === 'true'}
<video
transition:fade={{ duration: 1000 }}
- src="/peace.mp4"
+ src="{import.meta.env.BASE_URL}peace.mp4"
class="fixed left-0 top-0 z-[1000] h-screen w-screen object-cover"
autoplay
loop
diff --git a/chat/src/CompanyLogo.svelte b/chat/src/CompanyLogo.svelte
index 6bb9ef2c1..86a1f7390 100644
--- a/chat/src/CompanyLogo.svelte
+++ b/chat/src/CompanyLogo.svelte
@@ -4,40 +4,41 @@
export let rounded = null;
// Remember to update hasCompanyLogo from convo.js when adding new logos.
+ const base = import.meta.env.BASE_URL;
</script>
{#if model && model.provider}
{#if model.provider === 'OpenAI' || model.id.startsWith('openai')}
- <img src="/logos/openai.ico" loading="lazy" class="{size} {rounded || 'rounded-sm'}" alt="" />
+ <img src="{base}logos/openai.ico" loading="lazy" class="{size} {rounded || 'rounded-sm'}" alt="" />
{:else if model.provider === 'Anthropic' || model.id.startsWith('anthropic')}
<img
- src="/logos/anthropic.jpeg"
+ src="{base}logos/anthropic.jpeg"
loading="lazy"
class="{size} {rounded || 'rounded-sm'}"
alt=""
/>
{:else if model.id.startsWith('meta-llama')}
- <img src="/logos/meta.png" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/meta.png" loading="lazy" class={size} alt="" />
{:else if model.provider === 'Mistral' || model.id.startsWith('mistralai')}
- <img src="/logos/mistral.png" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/mistral.png" loading="lazy" class={size} alt="" />
{:else if model.id.startsWith('cohere')}
- <img src="/logos/cohere.png" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/cohere.png" loading="lazy" class={size} alt="" />
{:else if model.provider === 'Groq'}
- <img src="/logos/groq.png" loading="lazy" class="{size} {rounded || 'rounded-sm'}" alt="" />
+ <img src="{base}logos/groq.png" loading="lazy" class="{size} {rounded || 'rounded-sm'}" alt="" />
{:else if model.id.startsWith('nous')}
- <img src="/logos/nous.png" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/nous.png" loading="lazy" class={size} alt="" />
{:else if model.id.startsWith('google')}
- <img src="/logos/google.png" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/google.png" loading="lazy" class={size} alt="" />
{:else if model.id.startsWith('perplexity')}
<img
- src="/logos/perplexity.svg"
+ src="{base}logos/perplexity.svg"
loading="lazy"
class="{size} {rounded || 'rounded-sm'}"
alt=""
/>
{:else if model.id.startsWith('deepseek')}
- <img src="/logos/deepseek.ico" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/deepseek.ico" loading="lazy" class={size} alt="" />
{:else if model.id.startsWith('qwen')}
- <img src="/logos/qwen.svg" loading="lazy" class={size} alt="" />
+ <img src="{base}logos/qwen.svg" loading="lazy" class={size} alt="" />
{/if}
{/if}
diff --git a/chat/src/tools.js b/chat/src/tools.js
index 6b585b02f..e9fda48d5 100644
--- a/chat/src/tools.js
+++ b/chat/src/tools.js
@@ -180,3 +180,263 @@ export const agentToolSchema = {
},
],
};
+
+const _pumpMcp = `
+const _r = await fetch('/api/pump-fun-mcp', {method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name:_TOOL_,arguments:args}})});
+const _d = await _r.json();
+if (_d.error) return JSON.stringify({error: _d.error.message});
+const _c = _d.result?.content;
+return Array.isArray(_c) ? _c.map(x => x.text || JSON.stringify(x)).join('\\n') : JSON.stringify(_c, null, 2);
+`.trim();
+
+function pumpBody(toolName) {
+ return _pumpMcp.replace('_TOOL_', JSON.stringify(toolName));
+}
+
+export const pumpToolSchema = {
+ name: 'Pump.fun & Crypto',
+ schema: [
+ {
+ clientDefinition: {
+ id: 'pump-trending-001',
+ name: 'getTrendingTokens',
+ description: 'Top pump.fun tokens by market cap.',
+ arguments: [{ name: 'limit', type: 'number', description: 'Number of tokens (max 50, default 10)' }],
+ body: pumpBody('getTrendingTokens'),
+ },
+ type: 'function',
+ function: {
+ name: 'getTrendingTokens',
+ description: 'Get the top trending pump.fun tokens by market cap right now.',
+ parameters: {
+ type: 'object',
+ properties: { limit: { type: 'integer', default: 10, description: 'How many tokens to return (max 50)' } },
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-new-002',
+ name: 'getNewTokens',
+ description: 'Most recently launched pump.fun tokens.',
+ arguments: [{ name: 'limit', type: 'number', description: 'Number of tokens (max 50, default 10)' }],
+ body: pumpBody('getNewTokens'),
+ },
+ type: 'function',
+ function: {
+ name: 'getNewTokens',
+ description: 'Get the most recently launched pump.fun tokens.',
+ parameters: {
+ type: 'object',
+ properties: { limit: { type: 'integer', default: 10, description: 'How many tokens to return (max 50)' } },
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-koth-003',
+ name: 'getKingOfTheHill',
+ description: 'Highest-market-cap token still on the bonding curve.',
+ arguments: [],
+ body: pumpBody('getKingOfTheHill'),
+ },
+ type: 'function',
+ function: {
+ name: 'getKingOfTheHill',
+ description: 'Get the king of the hill — the highest market cap pump.fun token still on the bonding curve.',
+ parameters: { type: 'object', properties: {} },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-search-004',
+ name: 'searchTokens',
+ description: 'Search pump.fun tokens by name, symbol, or mint address.',
+ arguments: [
+ { name: 'query', type: 'string', description: 'Search query' },
+ { name: 'limit', type: 'number', description: 'Number of results (max 50, default 10)' },
+ ],
+ body: pumpBody('searchTokens'),
+ },
+ type: 'function',
+ function: {
+ name: 'searchTokens',
+ description: 'Search pump.fun tokens by name, symbol, or mint address.',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Token name, symbol, or mint address' },
+ limit: { type: 'integer', default: 10, description: 'Number of results (max 50)' },
+ },
+ required: ['query'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-details-005',
+ name: 'getTokenDetails',
+ description: 'Full details for a specific pump.fun token by mint address.',
+ arguments: [{ name: 'mint', type: 'string', description: 'Token mint address (base58)' }],
+ body: pumpBody('getTokenDetails'),
+ },
+ type: 'function',
+ function: {
+ name: 'getTokenDetails',
+ description: 'Get full details for a pump.fun token: price, market cap, description, socials, creator.',
+ parameters: {
+ type: 'object',
+ properties: { mint: { type: 'string', description: 'Token mint address (base58)' } },
+ required: ['mint'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-curve-006',
+ name: 'getBondingCurve',
+ description: 'Bonding curve analysis: reserves and graduation progress.',
+ arguments: [{ name: 'mint', type: 'string', description: 'Token mint address (base58)' }],
+ body: pumpBody('getBondingCurve'),
+ },
+ type: 'function',
+ function: {
+ name: 'getBondingCurve',
+ description: 'Get bonding curve reserves and graduation progress (0-100%) for a pump.fun token.',
+ parameters: {
+ type: 'object',
+ properties: { mint: { type: 'string', description: 'Token mint address (base58)' } },
+ required: ['mint'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-trades-007',
+ name: 'getTokenTrades',
+ description: 'Recent buy/sell history for a token.',
+ arguments: [
+ { name: 'mint', type: 'string', description: 'Token mint address (base58)' },
+ { name: 'limit', type: 'number', description: 'Number of trades (max 200, default 50)' },
+ ],
+ body: pumpBody('getTokenTrades'),
+ },
+ type: 'function',
+ function: {
+ name: 'getTokenTrades',
+ description: 'Get recent buy/sell trade history for a pump.fun token.',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'Token mint address (base58)' },
+ limit: { type: 'integer', default: 50, description: 'Number of trades (max 200)' },
+ },
+ required: ['mint'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-holders-008',
+ name: 'getTokenHolders',
+ description: 'Token holder distribution and concentration.',
+ arguments: [{ name: 'mint', type: 'string', description: 'Token mint address (base58)' }],
+ body: pumpBody('getTokenHolders'),
+ },
+ type: 'function',
+ function: {
+ name: 'getTokenHolders',
+ description: 'Get top token holders and concentration metrics for a pump.fun token.',
+ parameters: {
+ type: 'object',
+ properties: { mint: { type: 'string', description: 'Token mint address (base58)' } },
+ required: ['mint'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-quote-009',
+ name: 'pumpfun_quote_swap',
+ description: 'Read-only price quote for a pump.fun swap.',
+ arguments: [
+ { name: 'inputMint', type: 'string', description: 'Input token mint (use So11111111111111111111111111111111111111112 for SOL)' },
+ { name: 'outputMint', type: 'string', description: 'Output token mint' },
+ { name: 'amountIn', type: 'number', description: 'Amount in lamports (1 SOL = 1000000000)' },
+ ],
+ body: pumpBody('pumpfun_quote_swap'),
+ },
+ type: 'function',
+ function: {
+ name: 'pumpfun_quote_swap',
+ description: 'Get a read-only price quote for swapping on pump.fun. Use SOL mint So11111111111111111111111111111111111111112 for SOL side.',
+ parameters: {
+ type: 'object',
+ properties: {
+ inputMint: { type: 'string', description: 'Input token mint address' },
+ outputMint: { type: 'string', description: 'Output token mint address' },
+ amountIn: { type: 'number', description: 'Input amount in raw lamports (1 SOL = 1_000_000_000)' },
+ slippageBps: { type: 'number', description: 'Slippage in basis points (default 100 = 1%)' },
+ },
+ required: ['inputMint', 'outputMint', 'amountIn'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-sns-010',
+ name: 'sns_resolve',
+ description: 'Resolve a .sol domain to a wallet address.',
+ arguments: [{ name: 'name', type: 'string', description: '.sol domain name e.g. "bonfida.sol"' }],
+ body: pumpBody('sns_resolve'),
+ },
+ type: 'function',
+ function: {
+ name: 'sns_resolve',
+ description: 'Resolve a Solana Name Service (.sol) domain to its owner wallet address.',
+ parameters: {
+ type: 'object',
+ properties: { name: { type: 'string', description: '.sol domain name, e.g. "bonfida.sol"' } },
+ required: ['name'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-sns-rev-011',
+ name: 'sns_reverseLookup',
+ description: 'Reverse-lookup a Solana wallet to its .sol domain.',
+ arguments: [{ name: 'address', type: 'string', description: 'Base58 Solana wallet address' }],
+ body: pumpBody('sns_reverseLookup'),
+ },
+ type: 'function',
+ function: {
+ name: 'sns_reverseLookup',
+ description: 'Look up the .sol domain name for a Solana wallet address.',
+ parameters: {
+ type: 'object',
+ properties: { address: { type: 'string', description: 'Base58 Solana wallet address' } },
+ required: ['address'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'pump-kol-012',
+ name: 'kol_radar',
+ description: 'Early-detection signals for memecoins from KOL wallets.',
+ arguments: [{ name: 'limit', type: 'number', description: 'Number of signals (default 20)' }],
+ body: pumpBody('kol_radar'),
+ },
+ type: 'function',
+ function: {
+ name: 'kol_radar',
+ description: 'Get early-detection alpha signals from key opinion leader (KOL) wallets on pump.fun.',
+ parameters: {
+ type: 'object',
+ properties: { limit: { type: 'integer', default: 20, description: 'Number of signals to return' } },
+ },
+ },
+ },
+ ],
+};
diff --git a/public/chat/index.html b/public/chat/index.html
index 4fcabc314..53e0257f3 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -31,7 +31,7 @@
crossorigin="anonymous"
/>
<title>three.ws chat</title>
- <script type="module" crossorigin src="/chat/assets/index-B9zrrbu9.js"></script>
+ <script type="module" crossorigin src="/chat/assets/index-D6_3efiB.js"></script>
<link rel="stylesheet" crossorigin href="/chat/assets/index-BIPsb8P7.css">
</head>
<body>
diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.js
index 29339b8ac..9758f33b2 100644
--- a/src/agent-solana-wallet.js
+++ b/src/agent-solana-wallet.js
@@ -124,8 +124,13 @@ export async function requestAgentSolanaAirdrop(agentId) {
// ── UI card ─────────────────────────────────────────────────────────────────
const STYLE = `
-.agent-sol-wallet { border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; padding: .85rem 1rem; margin: .85rem 0; font: 13px/1.4 system-ui, sans-serif; background: rgba(255,255,255,0.03); color: #e6e6ea; }
-.agent-sol-wallet h3 { margin: 0 0 .25rem; font-size: .95rem; font-weight: 600; color: #f2f2f5; }
+.agent-sol-wallet-details { margin: .85rem 0; }
+.agent-sol-wallet-summary { font: 11px/1.4 system-ui, sans-serif; color: rgba(230,230,234,0.4); cursor: pointer; list-style: none; padding: .2rem 0; user-select: none; }
+.agent-sol-wallet-summary::-webkit-details-marker { display: none; }
+.agent-sol-wallet-summary::before { content: '▸ '; font-size: .65rem; }
+.agent-sol-wallet-details[open] .agent-sol-wallet-summary::before { content: '▾ '; }
+.agent-sol-wallet { border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; padding: .85rem 1rem; margin: .4rem 0 0; font: 13px/1.4 system-ui, sans-serif; background: rgba(255,255,255,0.03); color: #e6e6ea; }
+.agent-sol-wallet h3 { margin: 0 0 .25rem; font-size: .85rem; font-weight: 600; color: #f2f2f5; }
.agent-sol-wallet .sub { color: rgba(230,230,234,0.6); font-size: .78rem; margin: 0 0 .65rem; }
.agent-sol-wallet .addr { font-family: ui-monospace, monospace; font-size: .8rem; background: rgba(255,255,255,0.05); color: #e6e6ea; padding: .4rem .55rem; border-radius: 5px; word-break: break-all; border: 1px solid rgba(255,255,255,0.06); }
.agent-sol-wallet .addr .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 2px; border-radius: 2px; font-weight: 600; }
@@ -507,7 +512,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
loadFromServer().catch((e) => {
state.err = e.message || 'failed to load wallet';
state.loaded = true;
- root.hidden = false;
+ wrapper.hidden = false;
render();
});
@@ -515,7 +520,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
destroy: () => {
stopBalancePoll();
abort?.abort();
- root.remove();
+ wrapper.remove();
},
};
}