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.

feat: add embedding and voice management endpoints for agents

nirholasdc9bb1e2778d
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 840d11b4f..93fb7acc9 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -48,64 +48,64 @@ export default wrap(async function handler(req, res) {
}
if (sub === 'actions') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleActions(req, res, id);
}
if (sub === 'animations') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleAnimations(req, res, id);
}
if (sub === 'embed-policy') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleEmbedPolicy(req, res, id);
}
if (sub === 'manifest') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleManifest(req, res, id);
}
if (sub === 'sign') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleSign(req, res, id);
}
if (sub === 'usage') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleUsage(req, res, id);
}
if (sub === 'memories') {
- const mod = await import('./_sub.js');
+ const mod = await import('./_id/_sub.js');
return mod.handleMemories(req, res, id, action);
}
if (sub === 'memory') {
if (action === 'pin') {
- const mod = await import('./memory/pin.js');
+ const mod = await import('./_id/memory/pin.js');
return mod.default(req, res);
}
if (action && CID_RE.test(action)) {
- const mod = await import('./memory/[cid].js');
+ const mod = await import('./_id/memory/[cid].js');
return mod.default(req, res);
}
return error(res, 404, 'not_found', 'unknown memory sub-resource');
}
if (sub === 'livekit-token') {
- const mod = await import('./livekit-token.js');
+ const mod = await import('./_id/livekit-token.js');
return mod.handleLiveKitToken(req, res, id);
}
if (sub === 'embed') {
- const mod = await import('./embed.js');
+ const mod = await import('./_id/embed.js');
return mod.handleEmbed(req, res, id);
}
if (sub === 'voice') {
- const mod = await import('./voice.js');
+ const mod = await import('./_id/voice.js');
return mod.handleVoice(req, res, id, action);
}
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
new file mode 100644
index 000000000..e1235795c
--- /dev/null
+++ b/api/agents/_id/_sub.js
@@ -0,0 +1,279 @@
+// 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, 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`;
+ 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 }] : [],
+ voice: row.voice_id
+ ? { provider: row.voice_provider || 'elevenlabs', voice_id: row.voice_id }
+ : { provider: 'browser' },
+ 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 })) });
+});
+
+// ── memories ──────────────────────────────────────────────────────────────────
+
+const memoryBodySchema = z.object({
+ type: z.enum(['user', 'feedback', 'project', 'reference']),
+ content: z.string().trim().min(1).max(4000),
+ tags: z.array(z.string().trim().max(100)).max(20).optional().default([]),
+ salience: z.number().min(0).max(1).optional(),
+ expiresAt: z.string().datetime().optional().nullable(),
+});
+
+export const handleMemories = wrap(async (req, res, id, memoryId) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] = await sql`SELECT id FROM agent_identities WHERE id = ${id} AND user_id = ${userId} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ if (req.method === 'GET') {
+ const rows = await sql`
+ SELECT id, type, content, tags, salience, expires_at, created_at
+ FROM agent_memories
+ WHERE agent_id = ${id}
+ AND (expires_at IS NULL OR expires_at > now())
+ ORDER BY created_at DESC
+ LIMIT 200
+ `;
+ return json(res, 200, { data: rows });
+ }
+
+ if (req.method === 'DELETE') {
+ if (!memoryId) return error(res, 400, 'bad_request', 'memory id required');
+ await sql`DELETE FROM agent_memories WHERE id = ${memoryId} AND agent_id = ${id}`;
+ return json(res, 200, { deleted: true });
+ }
+
+ // POST
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(memoryBodySchema, await readJson(req));
+ const [row] = await sql`
+ INSERT INTO agent_memories (id, agent_id, type, content, tags, salience, expires_at)
+ VALUES (gen_random_uuid(), ${id}, ${body.type}, ${body.content}, ${body.tags}, ${body.salience ?? 0.5}, ${body.expiresAt ?? null})
+ RETURNING id
+ `;
+ return json(res, 201, { id: row.id });
+});
diff --git a/api/agents/_id/embed.js b/api/agents/_id/embed.js
new file mode 100644
index 000000000..dcb725ca2
--- /dev/null
+++ b/api/agents/_id/embed.js
@@ -0,0 +1,58 @@
+// POST /api/agents/:id/embed
+// Generates a text embedding via Voyage AI (voyage-3-lite, 1024-dim).
+// Used by AgentMemory.recall() for semantic similarity search.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+
+const VOYAGE_URL = 'https://api.voyageai.com/v1/embeddings';
+
+export async function handleEmbed(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 rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req);
+ const text = body?.text;
+ if (!text || typeof text !== 'string' || !text.trim()) {
+ return error(res, 400, 'validation_error', 'text is required');
+ }
+ if (text.length > 8192) {
+ return error(res, 400, 'validation_error', 'text exceeds 8192 character limit');
+ }
+
+ const upstream = await fetch(VOYAGE_URL, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${env.ANTHROPIC_API_KEY}`,
+ },
+ body: JSON.stringify({
+ model: 'voyage-3-lite',
+ input: [text.trim()],
+ input_type: 'query',
+ }),
+ });
+
+ if (!upstream.ok) {
+ const msg = await upstream.text().catch(() => '');
+ console.error('[embed] voyage error', upstream.status, msg.slice(0, 200));
+ return error(res, 502, 'upstream_error', 'embedding service unavailable');
+ }
+
+ const data = await upstream.json();
+ const embedding = data?.data?.[0]?.embedding;
+ if (!Array.isArray(embedding)) {
+ return error(res, 502, 'upstream_error', 'unexpected embedding response shape');
+ }
+
+ return json(res, 200, { embedding });
+}
diff --git a/api/agents/_id/livekit-token.js b/api/agents/_id/livekit-token.js
new file mode 100644
index 000000000..07c386fb6
--- /dev/null
+++ b/api/agents/_id/livekit-token.js
@@ -0,0 +1,49 @@
+// Handler for GET /api/agents/:id/livekit-token
+// Returns a short-lived LiveKit room access token for the given agent room.
+// Requires auth (session or bearer). Uses jose to sign the JWT directly —
+// livekit-server-sdk is not a project dependency.
+
+import { SignJWT } from 'jose';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, error } from '../../_lib/http.js';
+
+const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY;
+const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET;
+const LIVEKIT_SERVER_URL = process.env.LIVEKIT_SERVER_URL;
+
+export async function handleLiveKitToken(req, res, agentId) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_SERVER_URL) {
+ return error(res, 503, 'livekit_not_configured', 'LiveKit is not configured on this server');
+ }
+
+ 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 ?? 'anon';
+ const roomName = `agent-${agentId}`;
+ const participantId = `user-${userId}`;
+
+ const secret = new TextEncoder().encode(LIVEKIT_API_SECRET);
+ const now = Math.floor(Date.now() / 1000);
+
+ const token = await new SignJWT({
+ video: {
+ roomJoin: true,
+ room: roomName,
+ canPublish: true,
+ canSubscribe: true,
+ },
+ sub: participantId,
+ iss: LIVEKIT_API_KEY,
+ nbf: now,
+ exp: now + 3600,
+ })
+ .setProtectedHeader({ alg: 'HS256' })
+ .sign(secret);
+
+ return json(res, 200, { token, serverUrl: LIVEKIT_SERVER_URL });
+}
diff --git a/api/agents/_id/memory/[cid].js b/api/agents/_id/memory/[cid].js
new file mode 100644
index 000000000..31237f4d1
--- /dev/null
+++ b/api/agents/_id/memory/[cid].js
@@ -0,0 +1,63 @@
+import { sql } from '../../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib/auth.js';
+import { cors, method, wrap, error } from '../../../_lib/http.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+
+const IPFS_GATEWAYS = [
+ 'https://dweb.link/ipfs/',
+ 'https://cloudflare-ipfs.com/ipfs/',
+ 'https://ipfs.io/ipfs/',
+];
+
+const CID_RE = /^[a-zA-Z0-9]+$/;
+
+async function fetchFromIPFS(cid) {
+ let lastErr;
+ for (const gw of IPFS_GATEWAYS) {
+ try {
+ const resp = await fetch(gw + cid);
+ if (resp.ok) return resp;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr || new Error('All IPFS gateways failed for ' + cid);
+}
+
+// GET /api/agents/:id/memory/:cid
+// Returns the raw encrypted bytes for a pinned memory file.
+// Requires agent ownership to prevent CID enumeration.
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ const agentId = parts[2];
+ const cid = parts[4];
+
+ if (!cid || !CID_RE.test(cid)) {
+ return error(res, 400, 'validation_error', 'invalid or missing CID');
+ }
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] =
+ await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const ipfsResp = await fetchFromIPFS(cid);
+ const buf = Buffer.from(await ipfsResp.arrayBuffer());
+
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'application/octet-stream');
+ res.setHeader('Content-Length', buf.byteLength);
+ res.setHeader('Cache-Control', 'private, max-age=86400');
+ res.end(buf);
+});
diff --git a/api/agents/_id/memory/pin.js b/api/agents/_id/memory/pin.js
new file mode 100644
index 000000000..700de2992
--- /dev/null
+++ b/api/agents/_id/memory/pin.js
@@ -0,0 +1,77 @@
+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';
+
+const MAX_BYTES = 512 * 1024; // 512 KB per encrypted file
+
+const bodySchema = z.object({
+ filename: z
+ .string()
+ .trim()
+ .min(1)
+ .max(260)
+ .regex(/^[A-Za-z0-9._-]+$/, 'invalid filename characters'),
+ data: z.string().min(1), // base64-encoded bytes (encrypted or plaintext for MEMORY.md)
+});
+
+async function pinViaPinata(buf, filename) {
+ const form = new FormData();
+ form.append('file', new Blob([buf]), filename);
+ const resp = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${process.env.PINATA_JWT}` },
+ body: form,
+ });
+ if (!resp.ok) {
+ const detail = await resp.text().catch(() => '');
+ throw Object.assign(new Error(`Pinata error ${resp.status}`), { status: 502, detail });
+ }
+ const data = await resp.json();
+ return data.IpfsHash;
+}
+
+// POST /api/agents/:id/memory/pin
+// Body: { filename, data } — data is base64-encoded bytes
+// Returns: { cid }
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ const agentId = parts[2];
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] =
+ await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const rl = await limits.upload(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');
+
+ const body = parse(bodySchema, await readJson(req));
+
+ let buf;
+ try {
+ buf = Buffer.from(body.data, 'base64');
+ } catch {
+ return error(res, 400, 'validation_error', 'data must be valid base64');
+ }
+ if (buf.byteLength > MAX_BYTES) {
+ return error(res, 413, 'payload_too_large', 'file exceeds 512 KB limit');
+ }
+
+ if (!process.env.PINATA_JWT) {
+ return error(res, 503, 'pinning_unconfigured', 'no pinning provider configured');
+ }
+
+ const cid = await pinViaPinata(buf, body.filename);
+ return json(res, 200, { cid });
+});
diff --git a/api/agents/_id/pricing/[skill].js b/api/agents/_id/pricing/[skill].js
new file mode 100644
index 000000000..d4b310cf7
--- /dev/null
+++ b/api/agents/_id/pricing/[skill].js
@@ -0,0 +1,95 @@
+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 { parse } from '../../../_lib/validate.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+
+// First char must be alphanumeric; rest may include hyphens; total 1–64 chars.
+const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;
+
+const pricingBody = z.object({
+ currency_mint: z.string().trim().min(1),
+ chain: z.enum(['solana', 'base', 'evm']),
+ amount: z.number().int().gt(0),
+ is_active: z.boolean().default(true),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+// PUT /api/agents/:id/pricing/:skill — create or update a skill price (owner only)
+// DELETE /api/agents/:id/pricing/:skill — soft-delete; ?hard=true for permanent removal
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PUT', 'DELETE'])) return;
+
+ const urlParts = new URL(req.url, 'http://x').pathname.split('/').filter(Boolean);
+ // /api/agents/{id}/pricing/{skill}
+ const id = urlParts[2];
+ const skill = urlParts[4];
+
+ if (!skill || !SKILL_RE.test(skill)) {
+ return error(res, 400, 'validation_error', 'skill must be alphanumeric + hyphens, max 64 chars');
+ }
+
+ const userId = await resolveUserId(req);
+ if (!userId) 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, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ if (req.method === 'PUT') {
+ const body = parse(pricingBody, await readJson(req));
+
+ const [existing] = await sql`
+ SELECT id FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+
+ await sql`
+ INSERT INTO agent_skill_prices
+ (agent_id, skill, currency_mint, chain, amount, is_active, updated_at)
+ VALUES
+ (${id}, ${skill}, ${body.currency_mint}, ${body.chain}, ${body.amount}, ${body.is_active}, now())
+ ON CONFLICT (agent_id, skill) DO UPDATE SET
+ currency_mint = EXCLUDED.currency_mint,
+ chain = EXCLUDED.chain,
+ amount = EXCLUDED.amount,
+ is_active = EXCLUDED.is_active,
+ updated_at = now()
+ `;
+
+ const [row] = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active
+ FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+
+ return json(res, existing ? 200 : 201, row);
+ }
+
+ // DELETE
+ const url = new URL(req.url, 'http://x');
+ const hard = url.searchParams.get('hard') === 'true';
+
+ if (hard) {
+ await sql`DELETE FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}`;
+ } else {
+ await sql`
+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()
+ WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+ }
+
+ return json(res, 200, { deleted: true });
+});
diff --git a/api/agents/_id/pricing/index.js b/api/agents/_id/pricing/index.js
new file mode 100644
index 000000000..d2b24b72e
--- /dev/null
+++ b/api/agents/_id/pricing/index.js
@@ -0,0 +1,26 @@
+import { sql } from '../../../_lib/db.js';
+import { cors, json, method, wrap, error } from '../../../_lib/http.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+
+// GET /api/agents/:id/pricing — public for all agents (x402 manifest reads this)
+export default wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.pricingPerIp(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 deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const prices = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active
+ FROM agent_skill_prices
+ WHERE agent_id = ${id} AND is_active = true
+ ORDER BY skill
+ `;
+
+ return json(res, 200, { prices });
+});
diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.js
new file mode 100644
index 000000000..b516a8a78
--- /dev/null
+++ b/api/agents/_id/voice.js
@@ -0,0 +1,188 @@
+// Voice clone management for an agent.
+//
+// GET /api/agents/:id/voice — current voice status
+// POST /api/agents/:id/voice/clone — clone voice from uploaded audio
+// DELETE /api/agents/:id/voice — remove cloned voice
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } 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';
+
+const MAX_AUDIO_BYTES = 10 * 1024 * 1024; // 10 MB
+const MIN_DURATION_SEC = 30;
+const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
+
+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;
+}
+
+function readRawBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (chunk) => {
+ total += chunk.length;
+ if (total > MAX_AUDIO_BYTES) {
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks)));
+ req.on('error', reject);
+ });
+}
+
+export const handleVoice = wrap(async (req, res, id, action) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] =
+ await sql`SELECT id, user_id, name FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ // ── GET — voice status ───────────────────────────────────────────────────
+
+ if (req.method === 'GET') {
+ const [row] =
+ await sql`SELECT voice_provider, voice_id, voice_cloned_at FROM agent_identities WHERE id = ${id}`;
+ return json(res, 200, {
+ voice_provider: row.voice_provider || 'browser',
+ voice_id: row.voice_id || null,
+ voice_cloned_at: row.voice_cloned_at || null,
+ });
+ }
+
+ // ── DELETE — remove cloned voice ─────────────────────────────────────────
+
+ if (req.method === 'DELETE') {
+ const [row] = await sql`SELECT voice_id FROM agent_identities WHERE id = ${id}`;
+ if (row?.voice_id) {
+ // Best-effort: free the quota slot on ElevenLabs.
+ const apiKey = env.ELEVENLABS_API_KEY;
+ if (apiKey) {
+ fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(row.voice_id)}`, {
+ method: 'DELETE',
+ headers: { 'xi-api-key': apiKey },
+ }).catch(() => {});
+ }
+ }
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL
+ WHERE id = ${id}
+ `;
+ return json(res, 200, { voice_provider: 'browser', voice_id: null });
+ }
+
+ // ── POST /clone ──────────────────────────────────────────────────────────
+
+ if (req.method === 'POST' && action === 'clone') {
+ const apiKey = env.ELEVENLABS_API_KEY;
+ if (!apiKey)
+ return error(res, 503, 'not_configured', 'voice cloning is not configured on this server');
+
+ // Rate limit: 3 clones per user per day.
+ const rl = await limits.voiceClone(auth.userId);
+ if (!rl.success)
+ return error(res, 429, 'rate_limited', 'voice clone limit reached (3 per day)');
+
+ // Client can send recording duration in seconds so we can reject short clips
+ // without decoding the audio.
+ const durationSec = Number(req.headers['x-recording-duration'] || '0');
+ if (durationSec > 0 && durationSec < MIN_DURATION_SEC) {
+ return error(
+ res,
+ 400,
+ 'audio_too_short',
+ `recording must be at least ${MIN_DURATION_SEC} seconds (got ${Math.round(durationSec)}s)`,
+ );
+ }
+
+ const ct = (req.headers['content-type'] || '').split(';')[0].trim();
+ if (!ct.startsWith('audio/')) {
+ return error(res, 415, 'unsupported_media_type', 'content-type must be audio/*');
+ }
+
+ let audioBuf;
+ try {
+ audioBuf = await readRawBody(req);
+ } catch (err) {
+ if (err.status === 413)
+ return error(res, 413, 'payload_too_large', 'audio file must be under 10 MB');
+ throw err;
+ }
+
+ if (audioBuf.length === 0) return error(res, 400, 'validation_error', 'audio body is empty');
+
+ // Fallback size check when no duration header. WebM/Opus at 64 kbps:
+ // 3 s ≈ 24 KB, 30 s ≈ 240 KB. 50 KB catches sub-6-second clips.
+ if (!durationSec && audioBuf.length < 50_000) {
+ return error(res, 400, 'audio_too_short', 'recording must be at least 30 seconds');
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const voiceName = url.searchParams.get('name') || agent.name || 'Agent Voice';
+ const voiceDescription = url.searchParams.get('description') || '';
+
+ // Map MIME type to a filename extension ElevenLabs can identify.
+ const ext = ct.includes('webm')
+ ? 'audio.webm'
+ : ct.includes('mpeg') || ct.includes('mp3')
+ ? 'audio.mp3'
+ : ct.includes('wav')
+ ? 'audio.wav'
+ : ct.includes('mp4') || ct.includes('m4a')
+ ? 'audio.m4a'
+ : 'audio.webm';
+
+ const form = new FormData();
+ form.append('name', voiceName);
+ if (voiceDescription) form.append('description', voiceDescription);
+ form.append('files', new Blob([audioBuf], { type: ct }), ext);
+
+ let elevenResp;
+ try {
+ elevenResp = await fetch(`${ELEVEN_BASE}/voices/add`, {
+ method: 'POST',
+ headers: { 'xi-api-key': apiKey },
+ body: form,
+ });
+ } catch (err) {
+ console.error('[voice/clone] elevenlabs fetch failed', err);
+ return error(res, 502, 'upstream_error', 'voice cloning service unavailable');
+ }
+
+ if (!elevenResp.ok) {
+ const body = await elevenResp.text().catch(() => '');
+ console.error('[voice/clone] elevenlabs error', elevenResp.status, body);
+ if (elevenResp.status === 422)
+ return error(res, 400, 'audio_too_short', 'audio is too short or low quality for cloning');
+ return error(res, 502, 'upstream_error', 'voice cloning failed');
+ }
+
+ const { voice_id } = await elevenResp.json();
+ if (!voice_id) return error(res, 502, 'upstream_error', 'unexpected response from voice service');
+
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'elevenlabs', voice_id = ${voice_id}, voice_cloned_at = now()
+ WHERE id = ${id}
+ `;
+
+ return json(res, 201, { voice_id, name: voiceName });
+ }
+
+ return error(res, 404, 'not_found', 'unknown voice action');
+});
diff --git a/vercel.json b/vercel.json
index 767003178..6c4152c34 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1,6 +1,11 @@
{
"public": true,
"installCommand": "npm ci --prefer-offline --no-audit --no-fund",
+ "functions": {
+ "api/**/*.js": {
+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**"
+ }
+ },
"routes": [
{
"src": "/openapi\\.json",