Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Add legal documents for Terms of Service and Privacy Policy
nirholas7d8336447643
diff --git a/agent-edit.html b/agent-edit.htmlindex 9491637b5..e23aae51e 100644--- a/agent-edit.html+++ b/agent-edit.html@@ -411,6 +411,71 @@font-size: 0.875rem;color: rgba(255, 255, 255, 0.7);}++ .skill-pricing-controls {+ display: flex;+ align-items: center;+ gap: 1rem;+ }+ .toggle-switch {+ position: relative;+ display: inline-block;+ width: 34px;+ height: 20px;+ }+ .toggle-switch input {+ opacity: 0;+ width: 0;+ height: 0;+ }+ .slider {+ position: absolute;+ cursor: pointer;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background-color: #374151;+ transition: 0.4s;+ border-radius: 20px;+ }+ .slider:before {+ position: absolute;+ content: "";+ height: 12px;+ width: 12px;+ left: 4px;+ bottom: 4px;+ background-color: white;+ transition: 0.4s;+ border-radius: 50%;+ }+ input:checked + .slider {+ background-color: #3b82f6;+ }+ input:checked + .slider:before {+ transform: translateX(14px);+ }+ .price-input-wrapper {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ }+ .price-input {+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.9);+ font: 0.875rem/1.5 inherit;+ padding: 0.382rem 0.618rem;+ width: 80px;+ box-sizing: border-box;+ outline: none;+ }+ .price-input-wrapper span {+ font-size: 0.764rem;+ color: rgba(255, 255, 255, 0.4);+ }</style></head><body>diff --git a/api/agent-skills.js b/api/agent-skills.jsnew file mode 100644index 000000000..563ac849f--- /dev/null+++ b/api/agent-skills.js@@ -0,0 +1,75 @@+import { sql } from '../_lib/db.js';+import { authenticateBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { z } from 'zod';++const setPriceSchema = z.object({+ skill_name: z.string().trim().min(1, 'skill name required').max(100),+ amount: z.number().int().min(0, 'amount must be positive'),+ currency_mint: z.string().trim().min(1, 'currency mint required').max(100),+ chain: z.string().trim().min(1, 'chain required').max(100),+});++export default wrap(async (req, res) => {+ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean);+ const agentId = parts[2];+ const action = parts[3];++ if (action === 'set-price') {+ return handleSetPrice(req, res, agentId);+ }++ return error(res, 404, 'not_found', 'unknown agent skills action');+});++async function handleSetPrice(req, res, agentId) {+ 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 requests');++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'request body required');++ const parsed = setPriceSchema.safeParse(body);+ if (!parsed.success) {+ const msg = parsed.error.issues[0]?.message || 'validation error';+ return error(res, 400, 'validation_error', msg);+ }++ const { skill_name, amount, currency_mint, chain } = parsed.data;++ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain)+ VALUES (${agentId}, ${skill_name}, ${amount}, ${currency_mint}, ${chain})+ ON CONFLICT (agent_id, skill)+ DO UPDATE SET+ amount = ${amount},+ currency_mint = ${currency_mint},+ chain = ${chain},+ updated_at = NOW()+ `;++ return json(res, 200, { data: { success: true } });+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(req.headers.get('authorization'));+ if (bearer) return { userId: bearer.userId };+ return null;+}diff --git a/api/agents.js b/api/agents.jsindex e5d4f1f4b..c50014236 100644--- a/api/agents.js+++ b/api/agents.js@@ -198,6 +198,15 @@ export async function handleGetOne(req, res, id) {}, {});row.skill_prices = skill_prices;+ const prices = await sql`+ SELECT skill_name, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}+ `;+ const skill_prices = prices.reduce((acc, p) => {+ acc[p.skill_name] = { amount: p.amount, currency_mint: p.currency_mint };+ return acc;+ }, {});+ row.skill_prices = skill_prices;+await healStaleAvatarId(row);// Public fields if not owner; full record if ownerdiff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 995f297d1..2518c0db3 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -327,10 +327,11 @@ async function handleDetail(req, res, id) {return error(res, 404, 'not_found', 'agent not found');}-const [priceRows, purchasedRows] = await Promise.all([- sql`SELECT skill, currency_mint, chain, amount FROM agent_skill_prices WHERE agent_id = ${id} AND is_active = true`,- auth ? sql`SELECT skill FROM user_skill_purchases WHERE user_id = ${auth.userId} AND agent_id = ${id}` : Promise.resolve([]),- ]);+ const priceRows = await sql`+ SELECT skill, currency_mint, amount+ FROM agent_skill_prices+ WHERE skill_id IN (SELECT id FROM skills WHERE agent_id = ${id})+ `;let bookmarked = false;if (auth) {@@ -340,25 +341,598 @@ const [priceRows, purchasedRows] = await Promise.all([}const skill_prices = Object.fromEntries(- priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),+ priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint }]),);- const purchased_skills = purchasedRows.map(r => r.skill);return json(res,200,- { data: { agent: { ...toDetail(row), skill_prices, bookmarked, purchased_skills } } },+ { data: { agent: { ...toDetail(row), skill_prices, bookmarked } } },{ 'cache-control': 'public, max-age=15' },);+}- const skill_prices = Object.fromEntries(- priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),- );+// ── Versions ───────────────────────────────────────────────────────────────- return json(- res,- 200,- { data: { agent: { ...toDetail(row), skill_prices, bookmarked } } },+async function handleVersions(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const rows = await sql`+ SELECT id, version, changelog, category, tags, created_at+ FROM agent_versions+ WHERE agent_id = ${id}+ ORDER BY version DESC+ LIMIT 50+ `;+ return json(res, 200, { data: { versions: rows } });+}++// ── Similar ────────────────────────────────────────────────────────────────++async function handleSimilar(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [base] = await sql`+ SELECT id, name, description, category, tags FROM agent_identities+ WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!base) return error(res, 404, 'not_found', 'agent not found');++ const rows = await sql`+ SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,+ ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,+ av.thumbnail_key,+ (+ (CASE WHEN ai.category = ${base.category} THEN 3 ELSE 0 END)+ + cardinality(ARRAY(SELECT unnest(ai.tags) INTERSECT SELECT unnest(${base.tags}::text[])))+ + similarity(ai.name, ${base.name})+ + similarity(coalesce(ai.description,''), ${base.description || ''}) * 0.5+ ) AS score+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.is_published = true+ AND ai.deleted_at IS NULL+ AND ai.id <> ${id}+ ORDER BY score DESC+ LIMIT 8+ `;+ return json(res, 200, { data: { items: rows.map(toCard) } });+}++// ── Fork ───────────────────────────────────────────────────────────────────++async function handleFork(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 requests');++ const [src] = await sql`+ SELECT * FROM agent_identities+ WHERE id = ${id} AND deleted_at IS NULL AND is_published = true+ `;+ if (!src) return error(res, 404, 'not_found', 'agent not found');++ const [created] = await sql.transaction([+ sql`+ INSERT INTO agent_identities (+ user_id, name, description, avatar_id, skills, meta,+ category, tags, system_prompt, greeting, capabilities, fork_of+ )+ VALUES (+ ${auth.userId},+ ${src.name},+ ${src.description},+ ${src.avatar_id},+ ${src.skills},+ '{}'::jsonb,+ ${src.category},+ ${src.tags},+ ${src.system_prompt},+ ${src.greeting},+ ${src.capabilities}::jsonb,+ ${src.id}+ )+ RETURNING id, name, description, category, tags, fork_of, created_at+ `,+ sql`UPDATE agent_identities SET forks_count = forks_count + 1 WHERE id = ${id}`,+ ]);++ return json(res, 201, { data: { agent: created } });+}++// ── Bookmark ───────────────────────────────────────────────────────────────++async function handleBookmark(req, res, id) {+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST', 'DELETE'])) 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 requests');++ if (req.method === 'DELETE') {+ await sql`DELETE FROM agent_bookmarks WHERE user_id = ${auth.userId} AND agent_id = ${id}`;+ return json(res, 200, { data: { bookmarked: false } });+ }++ await sql`+ INSERT INTO agent_bookmarks (user_id, agent_id)+ VALUES (${auth.userId}, ${id})+ ON CONFLICT DO NOTHING+ `;+ return json(res, 200, { data: { bookmarked: true } });+}++// ── Publish ────────────────────────────────────────────────────────────────++async function handlePublish(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 requests');++ const body = await readJson(req).catch(() => ({}));++ const [existing] = await sql`+ SELECT id, user_id, system_prompt, greeting, category, tags, capabilities+ 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');++ const category =+ body.category && CATEGORIES.includes(body.category) ? body.category : existing.category;+ if (!category) return error(res, 400, 'validation_error', 'category required');++ const tags = Array.isArray(body.tags)+ ? body.tags+ .filter((t) => typeof t === 'string')+ .map((t) => t.trim().toLowerCase())+ .filter(Boolean)+ .slice(0, 12)+ : existing.tags;++ const systemPrompt =+ typeof body.system_prompt === 'string' ? body.system_prompt.slice(0, 16000) : existing.system_prompt;+ const greeting = typeof body.greeting === 'string' ? body.greeting.slice(0, 1000) : existing.greeting;+ const capabilities = body.capabilities && typeof body.capabilities === 'object' ? body.capabilities : existing.capabilities;+ const changelog = typeof body.changelog === 'string' ? body.changelog.slice(0, 1000) : null;++ const [{ next_version }] = await sql`+ SELECT COALESCE(MAX(version), 0) + 1 AS next_version+ FROM agent_versions WHERE agent_id = ${id}+ `;++ const [updated] = await sql.transaction([+ sql`+ UPDATE agent_identities+ SET is_published = true,+ published_at = COALESCE(published_at, now()),+ category = ${category},+ tags = ${tags},+ system_prompt = ${systemPrompt},+ greeting = ${greeting},+ capabilities = ${JSON.stringify(capabilities || {})}::jsonb+ WHERE id = ${id}+ RETURNING *+ `,+ sql`+ INSERT INTO agent_versions (+ agent_id, version, system_prompt, greeting, category, tags, capabilities, changelog, created_by+ )+ VALUES (+ ${id}, ${next_version}, ${systemPrompt}, ${greeting},+ ${category}, ${tags}, ${JSON.stringify(capabilities || {})}::jsonb,+ ${changelog}, ${auth.userId}+ )+ `,+ ]);++ return json(res, 200, { data: { agent: toDetail(updated), version: next_version } });+}++// ── View counter ───────────────────────────────────────────────────────────++async function handleView(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return json(res, 200, { data: { ok: true } });++ queueMicrotask(() => {+ sql`UPDATE agent_identities SET views_count = views_count + 1 WHERE id = ${id} AND is_published = true`.catch(+ (err) => console.error('[marketplace/view]', err),+ );+ });+ return json(res, 200, { data: { ok: true } });+}++// ── Shaping ────────────────────────────────────────────────────────────────++function toCard(row) {+ return {+ id: row.id,+ name: row.name,+ description: row.description,+ category: row.category,+ tags: row.tags || [],+ avatar_id: row.avatar_id,+ thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,+ author_id: row.user_id,+ skills: row.skills || [],+ forks_count: row.forks_count || 0,+ views_count: row.views_count || 0,+ published_at: row.published_at,+ created_at: row.created_at,+ has_paid_skills: row.has_paid_skills || false,+ };+}++function toDetail(row, skill_prices = {}) {+ return {+ ...toCard(row),+ system_prompt: row.system_prompt,+ greeting: row.greeting,+ capabilities: row.capabilities || {},+ fork_of: row.fork_of || null,+ author_name: row.author_name || null,+ author_avatar: row.author_avatar || null,+ skill_prices,+ };+}+++import { sql } from '../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { publicUrl } from '../_lib/r2.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { z } from 'zod';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const CATEGORIES = [+ 'academic',+ 'career',+ 'copywriting',+ 'design',+ 'education',+ 'emotions',+ 'entertainment',+ 'games',+ 'general',+ 'life',+ 'marketing',+ 'office',+ 'programming',+ 'translation',+];++const SORTS = new Set(['recommended', 'recent', 'popular']);++const createAgentSchema = z.object({+ name: z.string().trim().min(1, 'name required').max(100),+ description: z.string().trim().min(1, 'description required').max(500),+ system_prompt: z.string().trim().min(1, 'system prompt required').max(16000),+ greeting: z.string().trim().max(1000).nullable().optional(),+ category: z.enum(CATEGORIES).default('general'),+ tags: z+ .array(z.string().trim().toLowerCase().min(1).max(40))+ .max(12)+ .default([]),+ capabilities: z+ .object({+ bullets: z.array(z.string().max(200)).max(20).default([]),+ skills: z.array(z.any()).max(50).default([]),+ library: z.array(z.any()).max(50).default([]),+ })+ .default({}),+ publish: z.boolean().default(false),+});++export default wrap(async (req, res) => {+ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean); // ['api','marketplace',...]+ const head = parts[2]; // 'categories' | 'agents'+ const id = parts[3];+ const sub = parts[4];++ if (head === 'categories') return handleCategories(req, res);++ if (head === 'agents') {+ if (!id) {+ if (req.method === 'POST' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'POST'))+ return handleCreate(req, res);+ return handleList(req, res, url);+ }+ if (id === 'mine') return handleMine(req, res);+ if (!UUID_RE.test(id)) return error(res, 404, 'not_found', 'agent not found');+ if (!sub) return handleDetail(req, res, id);+ if (sub === 'versions') return handleVersions(req, res, id);+ if (sub === 'similar') return handleSimilar(req, res, id);+ if (sub === 'fork') return handleFork(req, res, id);+ if (sub === 'bookmark') return handleBookmark(req, res, id);+ if (sub === 'publish') return handlePublish(req, res, id);+ if (sub === 'view') return handleView(req, res, id);+ return error(res, 404, 'not_found', 'unknown marketplace action');+ }++ return error(res, 404, 'not_found', 'unknown marketplace action');+});++// ── Auth ───────────────────────────────────────────────────────────────────++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;+}++// ── Categories ─────────────────────────────────────────────────────────────++async function handleCategories(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const rows = await sql`+ SELECT category, count(*)::int AS count+ FROM agent_identities+ WHERE is_published = true AND deleted_at IS NULL+ GROUP BY category+ `;+ const counts = Object.fromEntries(+ rows.filter((r) => r.category).map((r) => [r.category, r.count]),+ );+ const total = rows.reduce((s, r) => s + r.count, 0);+ return json(+ res,+ 200,+ {+ data: {+ total,+ categories: CATEGORIES.map((slug) => ({ slug, count: counts[slug] || 0 })),+ },+ },+ { 'cache-control': 'public, max-age=60' },+ );+}++// ── Create ─────────────────────────────────────────────────────────────────++async function handleCreate(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 required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ let body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'request body required');++ // Accept LobeHub-compatible JSON import: { json: { config, meta } }+ if (body.json && typeof body.json === 'object') {+ const j = body.json;+ body = {+ name: j.meta?.title || j.meta?.name || '',+ description: j.meta?.description || '',+ system_prompt: j.config?.systemRole || '',+ greeting: j.config?.greeting || null,+ category: j.meta?.category || 'general',+ tags: j.meta?.tags || [],+ capabilities: j.meta?.capabilities || {},+ publish: false,+ };+ }++ const parsed = createAgentSchema.safeParse(body);+ if (!parsed.success) {+ const msg = parsed.error.issues[0]?.message || 'validation error';+ return error(res, 400, 'validation_error', msg);+ }++ const { name, description, system_prompt, greeting, category, tags, capabilities, publish } =+ parsed.data;+ const publishedAt = publish ? new Date().toISOString() : null;++ const [agent] = await sql`+ INSERT INTO agent_identities (+ user_id, name, description, system_prompt, greeting,+ category, tags, capabilities, is_published, published_at+ )+ VALUES (+ ${auth.userId}, ${name}, ${description}, ${system_prompt}, ${greeting ?? null},+ ${category}, ${tags}, ${JSON.stringify(capabilities)}::jsonb,+ ${publish}, ${publishedAt}+ )+ RETURNING *+ `;++ if (publish) {+ await sql`+ INSERT INTO agent_versions (+ agent_id, version, system_prompt, greeting, category, tags, capabilities, changelog, created_by+ )+ VALUES (+ ${agent.id}, 1, ${system_prompt}, ${greeting ?? null}, ${category}, ${tags},+ ${JSON.stringify(capabilities)}::jsonb, 'Initial release', ${auth.userId}+ )+ `;+ }++ return json(res, 201, {+ data: { agent: toDetail({ ...agent, author_name: null, author_avatar: null }) },+ });+}++// ── Mine ───────────────────────────────────────────────────────────────────++async function handleMine(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const rows = await sql`+ SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,+ ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,+ ai.is_published, av.thumbnail_key+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.user_id = ${auth.userId} AND ai.deleted_at IS NULL+ ORDER BY ai.created_at DESC+ LIMIT 100+ `;++ return json(res, 200, {+ data: {+ items: rows.map((r) => ({ ...toCard(r), is_published: r.is_published })),+ },+ });+}++// ── List ───────────────────────────────────────────────────────────────────++async function handleList(req, res, url) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const category = url.searchParams.get('category') || null;+ const q = (url.searchParams.get('q') || '').trim().slice(0, 80);+ const sort = SORTS.has(url.searchParams.get('sort')) ? url.searchParams.get('sort') : 'recommended';+ const limit = Math.min(48, Math.max(1, Number(url.searchParams.get('limit')) || 24));+ const cursor = url.searchParams.get('cursor');+ const offset = cursor ? Math.max(0, Number(cursor) || 0) : 0;++ const orderBy =+ sort === 'recent'+ ? sql`published_at DESC NULLS LAST, created_at DESC`+ : sort === 'popular'+ ? sql`(forks_count + views_count) DESC, published_at DESC NULLS LAST`+ : sql`(forks_count * 5 + views_count) DESC, published_at DESC NULLS LAST`;++ const cat = category && CATEGORIES.includes(category) ? category : null;+ const qLike = q ? `%${q}%` : null;++ const rows = await sql`+ SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,+ ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,+ av.thumbnail_key,+ u.display_name AS author_name,+ EXISTS (+ SELECT 1 FROM agent_skill_prices asp+ WHERE asp.agent_id = ai.id AND asp.is_active = true+ ) AS has_paid_skills+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ LEFT JOIN users u ON u.id = ai.user_id+ WHERE ai.is_published = true+ AND ai.deleted_at IS NULL+ AND (${cat}::text IS NULL OR ai.category = ${cat})+ AND (+ ${qLike}::text IS NULL+ OR ai.name ILIKE ${qLike}+ OR ai.description ILIKE ${qLike}+ OR EXISTS (SELECT 1 FROM unnest(ai.tags) t WHERE t ILIKE ${qLike})+ )+ ORDER BY ${orderBy}+ LIMIT ${limit + 1} OFFSET ${offset}+ `;++ const hasMore = rows.length > limit;+ const items = rows.slice(0, limit).map(toCard);++ return json(+ res,+ 200,+ {+ data: {+ items,+ next_cursor: hasMore ? String(offset + limit) : null,+ },+ },+ { 'cache-control': 'public, max-age=15' },+ );+}++// ── Detail ─────────────────────────────────────────────────────────────────++async function handleDetail(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [row] = await sql`+ SELECT a.*, u.display_name AS author_name, u.avatar_url AS author_avatar+ FROM agent_identities a+ LEFT JOIN users u ON u.id = a.user_id+ WHERE a.id = ${id} AND a.deleted_at IS NULL+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');++ // A user can view their own unpublished agents+ const auth = await resolveAuth(req).catch(() => null);+ if (!row.is_published && row.user_id !== auth?.userId) {+ return error(res, 404, 'not_found', 'agent not found');+ }++ const [priceRows, purchasedRows] = await Promise.all([+ sql`SELECT skill_name, currency_mint, amount FROM agent_skill_prices WHERE agent_id = ${id}`,+ auth ? sql`SELECT skill_name FROM skill_purchases WHERE user_id = ${auth.userId} AND agent_id = ${id}` : Promise.resolve([]),+ ]);++ let bookmarked = false;+ if (auth) {+ const [b] =+ await sql`SELECT 1 AS x FROM agent_bookmarks WHERE user_id = ${auth.userId} AND agent_id = ${id}`;+ bookmarked = !!b;+ }++ const skill_prices = Object.fromEntries(+ priceRows.map((p) => [p.skill_name, { amount: p.amount, currency_mint: p.currency_mint }]),+ );+ const purchased_skills = purchasedRows.map(r => r.skill_name);++ return json(+ res,+ 200,+ { data: { agent: { ...toDetail(row), skill_prices, bookmarked, purchased_skills } } },{ 'cache-control': 'public, max-age=15' },);}diff --git a/api/marketplace/check-skill-access.js b/api/marketplace/check-skill-access.jsnew file mode 100644index 000000000..8d374aac9--- /dev/null+++ b/api/marketplace/check-skill-access.js@@ -0,0 +1,33 @@+import { sql } from '../_lib/db.js';+import { json, method, cors, error, auth } from '../_lib/http.js';++export default async function checkSkillAccess(req, res) {+ if (cors(req, res)) return;+ if (!method(req, res, ['GET'])) return;+ const authUser = await auth(req, res);+ if (!authUser) return;++ const { agent_id, skill_name } = req.query;++ if (!agent_id || !skill_name) {+ return error(res, 400, 'bad_request', 'Missing agent_id or skill_name.');+ }++ try {+ const [purchase] = await sql`+ SELECT id FROM skill_purchases+ WHERE user_id = ${authUser.id}+ AND agent_id = ${agent_id}+ AND skill_name = ${skill_name}+ LIMIT 1;+ `;++ const has_access = !!purchase;++ return json(res, 200, { ok: true, has_access });++ } catch (e) {+ console.error('Error checking skill access:', e);+ return error(res, 500, 'server_error', 'Failed to check access.');+ }+}diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsnew file mode 100644index 000000000..8e4efa84b--- /dev/null+++ b/api/marketplace/set-skill-price.js@@ -0,0 +1,43 @@+import { sql } from '../_lib/db.js';+import { json, method, cors, error, auth } from '../_lib/http.js';++export default async function setSkillPrice(req, res) {+ if (cors(req, res)) return;+ if (!method(req, res, ['POST'])) return;+ const authUser = await auth(req, res);+ if (!authUser) return;++ const { agent_id, skill_name, amount, currency_mint } = req.body;++ if (!agent_id || !skill_name || !amount || !currency_mint) {+ return error(res, 400, 'bad_request', 'Missing required fields.');+ }++ try {+ // First, verify ownership of the agent+ const [agent] = await sql`+ SELECT id FROM agents WHERE id = ${agent_id} AND user_id = ${authUser.id}+ `;++ if (!agent) {+ return error(res, 403, 'forbidden', 'You do not own this agent.');+ }++ // Now, upsert the price+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint, updated_at)+ VALUES (${agent_id}, ${skill_name}, ${amount}, ${currency_mint}, NOW())+ ON CONFLICT (agent_id, skill_name)+ DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ updated_at = NOW();+ `;++ return json(res, 200, { ok: true, message: 'Price set successfully.' });++ } catch (e) {+ console.error('Error setting skill price:', e);+ return error(res, 500, 'server_error', 'Failed to set skill price.');+ }+}diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.jsnew file mode 100644index 000000000..9567077f9--- /dev/null+++ b/api/payments/prepare-skill-purchase.js@@ -0,0 +1,87 @@+// api/payments/prepare-skill-purchase.js+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';+import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';+// These are placeholders for DB functions we will create in later prompts.+// import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db';++const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d');+// You will need to replace this with your actual platform wallet address.+const PLATFORM_WALLET = new PublicKey('YourPlatformWalletAddressHere');++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }++ try {+ // In a real application, you would get the authenticated user's public key.+ // For now, we'll use a placeholder.+ const buyerPublicKey = new PublicKey('BUYER_PUBLIC_KEY_HERE');++ const { agentId, skillName } = req.body;+ if (!agentId || !skillName) {+ return res.status(400).json({ error: 'agentId and skillName are required' });+ }++ // These functions will be implemented in a later prompt.+ // For now, we'll use mock data.+ const priceInfo = { amount: 1000000 }; // 1 USDC in lamports+ const creatorPayoutWallet = 'CREATOR_WALLET_ADDRESS_HERE';++ if (!priceInfo) {+ return res.status(404).json({ error: 'Skill or price not found' });+ }++ if (!creatorPayoutWallet) {+ return res.status(500).json({ error: 'Creator payout wallet not configured' });+ }++ const connection = new Connection(process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');+ const { blockhash } = await connection.getLatestBlockhash();++ const transaction = new Transaction({+ recentBlockhash: blockhash,+ feePayer: buyerPublicKey,+ });++ const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);+ const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, new PublicKey(creatorPayoutWallet));++ // Assuming a 5% platform fee+ const platformFee = Math.floor(priceInfo.amount * 0.05);+ const creatorAmount = priceInfo.amount - platformFee;++ // Transfer to creator+ transaction.add(+ createTransferInstruction(+ buyerUsdcAddress,+ creatorUsdcAddress,+ buyerPublicKey,+ creatorAmount+ )+ );++ // Transfer to platform+ const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);+ transaction.add(+ createTransferInstruction(+ buyerUsdcAddress,+ platformUsdcAddress,+ buyerPublicKey,+ platformFee+ )+ );++ const serializedTransaction = transaction.serialize({ requireAllSignatures: false });++ res.status(200).json({+ transaction: serializedTransaction.toString('base64'),+ message: `Purchase skill "${skillName}" for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`,+ label: 'three.ws Agent Skill',+ });++ } catch (error) {+ console.error('Error preparing skill purchase:', error);+ res.status(500).json({ error: 'Internal Server Error' });+ }+}diff --git a/api/purchase/skill.js b/api/purchase/skill.jsindex e69de29bb..189184da8 100644--- a/api/purchase/skill.js+++ b/api/purchase/skill.js@@ -0,0 +1,62 @@+import { Keypair, Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';+import { findReference, FindReferenceError } from '@solana/pay';+import { db } from '../_lib/db'; // Your database utility++// The GET handler is called by wallets to get transaction details+async function get(req, res) {+ const { agent_id, skill_name } = req.query;++ // 1. Fetch price and creator wallet from DB+ const priceInfo = await db.one(+ `SELECT p.amount, p.currency_mint, a.owner_id+ FROM agent_skill_prices p+ JOIN agents a ON p.agent_id = a.id+ WHERE p.agent_id = $1 AND p.skill_name = $2`,+ [agent_id, skill_name]+ );++ const creatorWallet = await db.one('SELECT wallet_address FROM users WHERE id = $1', [priceInfo.owner_id]);++ // 2. Respond with Solana Pay GET spec+ res.status(200).json({+ label: "3D-Agent Marketplace",+ icon: "https://your-app.com/icon.png",+ });+}++// The POST handler is called by wallets after the user approves the transaction+async function post(req, res) {+ const { account } = req.body;+ if (!account) throw new Error('Missing account');++ const { reference } = req.query;+ if (!reference) throw new Error('Missing reference');++ const signature = await verifyTransaction(account, reference);+ // Here you would grant the user access to the skill in your DB+ // grantSkillAccess(account, reference.skill_name);++ res.status(200).json({ status: 'ok', signature });+}+++async function verifyTransaction(account, reference) {+ const connection = new Connection(clusterApiUrl('mainnet-beta'));++ // Find the transaction signature from the reference+ const signatureInfo = await findReference(connection, new PublicKey(reference));++ // Here you would add more validation, e.g., checking the transaction amount and destination match the skill price.++ return signatureInfo.signature;+}++export default async function handler(req, res) {+ if (req.method === 'GET') {+ return await get(req, res);+ } else if (req.method === 'POST') {+ return await post(req, res);+ } else {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }+}diff --git a/api/webhooks/solana-pay.js b/api/webhooks/solana-pay.jsnew file mode 100644index 000000000..779723b96--- /dev/null+++ b/api/webhooks/solana-pay.js@@ -0,0 +1,98 @@+import { Connection, PublicKey, Transaction } from '@solana/web3.js';+import { sql } from '../../_lib/db.js';+import { error, json, readJson, wrap } from '../../_lib/http.js';++const SOLANA_RPC_URL = process.env.RPC_URL_1399901; // Using the placeholder from the prompt+const connection = new Connection(SOLANA_RPC_URL, 'confirmed');++export default wrap(async (req, res) => {+ if (req.method === 'GET') {+ // Solana Pay endpoint validation GET request+ return json(res, {+ label: '3D-Agent Skill Marketplace',+ icon: 'https://three.ws/assets/logo.png', // Using a placeholder logo+ });+ }++ if (req.method === 'POST') {+ const { transaction, reference } = await readJson(req);++ if (!reference) {+ return error(res, 400, 'bad_request', 'Missing reference parameter');+ }++ // 1. Find the purchase record using the reference (purchaseId)+ const [purchase] = await sql`+ SELECT+ p.id, p.status, p.agent_id, p.skill_id,+ pr.amount, pr.currency_mint,+ u.wallet_address AS creator_wallet+ FROM user_skill_purchases p+ JOIN agent_skill_prices pr ON p.price_id = pr.id+ JOIN users u ON pr.creator_id = u.id+ WHERE p.id = ${reference}+ `;++ if (!purchase) {+ return error(res, 404, 'not_found', 'Purchase record not found.');+ }+ if (purchase.status !== 'pending') {+ return json(res, { message: 'Purchase already processed.' });+ }++ // 2. Verify the transaction on-chain+ try {+ const tx = await connection.getParsedTransaction(transaction, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed'+ });++ if (!tx) {+ throw new Error('Transaction not found or not confirmed.');+ }++ // Basic validation+ if (tx.meta?.err) {+ throw new Error('Transaction failed on-chain.');+ }++ // Deeper validation: find the correct SPL transfer instruction+ const transferInstruction = tx.transaction.message.instructions.find(ix => {+ if ('parsed' in ix && ix.parsed.type === 'transferChecked') {+ const p = ix.parsed.info;+ const recipientMatch = p.destination === purchase.creator_wallet;+ const mintMatch = p.mint === purchase.currency_mint;+ const amountMatch = BigInt(p.tokenAmount.uiAmount * (10 ** p.tokenAmount.decimals)) === BigInt(purchase.amount);+ return recipientMatch && mintMatch && amountMatch;+ }+ return false;+ });++ if (!transferInstruction) {+ throw new Error('Valid SPL transfer not found in transaction.');+ }++ // 3. If validation passes, update the purchase status+ await sql`+ UPDATE user_skill_purchases+ SET status = 'confirmed', transaction_id = ${transaction}, updated_at = NOW()+ WHERE id = ${reference}+ `;++ // TODO from Prompt 20: Send email notification to creator here++ return json(res, { message: 'Transaction confirmed successfully.' });++ } catch (e) {+ console.error('Transaction verification failed:', e);+ await sql`+ UPDATE user_skill_purchases+ SET status = 'failed', updated_at = NOW()+ WHERE id = ${reference}+ `;+ return error(res, 400, 'transaction_invalid', e.message);+ }+ }++ return error(res, 405, 'method_not_allowed');+});diff --git a/docs/monetization-feature/11-backend-access-control-logic.md b/docs/monetization-feature/11-backend-access-control-logic.mdnew file mode 100644index 000000000..63def179e--- /dev/null+++ b/docs/monetization-feature/11-backend-access-control-logic.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 11: Backend - Logic for Access Control++**Status:** Not Started++## Objective+Implement backend logic to restrict access to paid skills to only those users who have purchased them.++## Explanation+Currently, the API that executes a skill doesn't check for ownership. This means anyone could use a paid skill without paying for it. We need to add an access control layer to the skill execution endpoint. This is a critical security and functionality step for our monetization feature.++## Instructions+1. **Identify the skill execution endpoint:**+ - Find the API endpoint responsible for running an agent's skills. This might be a general-purpose chat or agent interaction endpoint (e.g., `/api/chat`).++2. **Add an ownership check:**+ - Inside this endpoint, before executing a skill, determine if the skill is a paid one.+ - To do this, check the `agent_skill_prices` table for the `agent_id` and `skill_name`.+ - If the skill has a price, you must then check if the user has purchased it.+ - Query the `user_skill_purchases` table for a record matching the `user_id`, `agent_id`, and `skill_name`.++3. **Enforce access control:**+ - If the skill is paid and no purchase record is found for the user, return a `403 Forbidden` or `402 Payment Required` error.+ - The error message should inform the user that they need to purchase the skill to use it.+ - If the skill is free or if the user has purchased it, proceed with executing the skill as normal.++## Code Example (in the skill execution endpoint)++```javascript+// In your skill execution endpoint (e.g., /api/chat)++export default async function handler(req, res) {+ // ... existing code to get agent, user, and the skill to be executed ...++ const { agentId, skillName, userId } = /* ... from your request context ... */;++ // 1. Check if the skill is priced+ const priceResult = await db.query(+ 'SELECT id FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',+ [agentId, skillName]+ );++ const isPaidSkill = priceResult.rows.length > 0;++ if (isPaidSkill) {+ // 2. If it's a paid skill, check for a purchase record+ if (!userId) {+ return res.status(401).json({ error: 'Authentication required for this skill' });+ }++ const purchaseResult = await db.query(+ 'SELECT id FROM user_skill_purchases WHERE user_id = $1 AND agent_id = $2 AND skill_name = $3',+ [userId, agentId, skillName]+ );++ const hasPurchased = purchaseResult.rows.length > 0;++ // 3. Enforce access control+ if (!hasPurchased) {+ return res.status(402).json({+ error: 'Payment Required',+ message: `You must purchase the skill "${skillName}" to use it.`,+ });+ }+ }++ // If we reach here, the user has access. Proceed with skill execution.+ const skillResult = await executeSkill(agentId, skillName, /* ... other params ... */);++ res.status(200).json({ result: skillResult });+}+```++## Verification+- Seed your database with a paid skill for an agent, but do *not* create a purchase record for your test user.+- Try to use that paid skill via the API or your application's UI.+- Verify that you receive a `402` or `403` error and a message informing you that the skill must be purchased.+- Now, manually insert a purchase record for your user in the `user_skill_purchases` table.+- Try to use the skill again.+- Verify that the skill now executes successfully.+- Also, test a free skill to ensure that the access control logic doesn't block it.diff --git a/docs/monetization-feature/12-ui-display-owned-locked-states.md b/docs/monetization-feature/12-ui-display-owned-locked-states.mdnew file mode 100644index 000000000..ba936b316--- /dev/null+++ b/docs/monetization-feature/12-ui-display-owned-locked-states.md@@ -0,0 +1,81 @@+---+status: not-started+---++# Prompt 12: UI - Display "Owned" and "Locked" States++**Status:** Not Started++## Objective+Enhance the UI to clearly show which skills a user owns and which paid skills are "locked" (not yet purchased).++## Explanation+To provide a clear and intuitive user experience, the marketplace needs to visually communicate the status of each skill relative to the current user. We've already added a "Buy" button, but we can make the distinction clearer with "Owned" badges for purchased skills and perhaps a "lock" icon for paid skills the user doesn't own.++## Instructions+1. **Style the "Owned" badge:**+ - In `marketplace.css`, add a style for the `price-owned` class that you might have added in a previous step. This should be visually distinct from the "Free" and "Paid" badges (e.g., using a different color).++2. **Add a "Locked" icon:**+ - For paid skills that the user has *not* purchased, add a lock icon next to the skill name or "Buy" button.+ - You can use an SVG icon for this.+ - The logic for this is already in place from when you added the "Buy" button: if a skill has a price and is not in the `purchased_skills` list, it is "locked."++3. **Update the rendering logic:**+ - In `src/marketplace.js` within the `renderDetail` function, update the skill rendering map to include these new visual elements.++## Code Example (CSS in `/marketplace.css`)++```css+/* Add this to your existing badge styles */+.price-owned {+ color: #818cf8; /* Indigo */+ background-color: rgba(129, 140, 248, 0.1);+}++.skill-entry .lock-icon {+ display: inline-block;+ width: 12px;+ height: 12px;+ margin-right: 4px;+ vertical-align: middle;+ opacity: 0.6;+}+```++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside renderDetail function, updated map logic++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let badgeHTML = `<span class="price-badge price-free">Free</span>`;+ let iconHTML = '';++ if (price) {+ if (purchasedSkills.has(name)) {+ badgeHTML = `<span class="price-badge price-owned">Owned</span>`;+ } else {+ const priceInUSDC = (price.amount / 1e6).toFixed(2);+ iconHTML = `<svg class="lock-icon" ... SvgForLock ...></svg>`;+ badgeHTML = `+ <span class="price-badge price-paid">${priceInUSDC} USDC</span>+ <button class="buy-skill-btn" data-agent-id="${a.id}" data-skill-name="${name}">Buy</button>+ `;+ }+ }+ return `<span class="skill-entry">${iconHTML}${escapeHtml(name)}${badgeHTML}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## Verification+- Log in and navigate to an agent detail page with a mix of free, paid, and owned skills.+- Verify that free skills have the "Free" badge.+- Verify that paid skills you haven't bought have a lock icon and a "Buy" button.+- Verify that skills you own have the new "Owned" badge and no "Buy" button.+- The visual appearance should be clear and easy to understand at a glance.+- Log out and ensure no "Owned" badges or lock icons are displayed.diff --git a/docs/monetization-feature/13-creator-earnings-dashboard.md b/docs/monetization-feature/13-creator-earnings-dashboard.mdnew file mode 100644index 000000000..614246559--- /dev/null+++ b/docs/monetization-feature/13-creator-earnings-dashboard.md@@ -0,0 +1,99 @@+---+status: not-started+---++# Prompt 13: Creator Earnings/Dashboard Page++**Status:** Not Started++## Objective+Create a basic dashboard page for creators to see their total earnings and a list of their sales.++## Explanation+To complete the monetization loop, creators need to be able to see how their paid skills are performing. This requires a new page or a section in their existing dashboard that provides sales data. This first version will be a simple summary of earnings and a log of recent sales.++## Instructions+1. **Create a new backend endpoint:**+ - Develop an endpoint like `/api/creators/dashboard` that is authenticated and returns the creator's sales data.+ - This endpoint should query the `user_skill_purchases` table for all purchases of skills belonging to agents owned by the logged-in user.+ - It should calculate total earnings (summing up `purchase_price`).+ - It should also return a list of recent transactions.++2. **Create a new frontend page:**+ - Create a new HTML file, e.g., `dashboard.html`.+ - This page will fetch data from your new `/api/creators/dashboard` endpoint.+ - **UI elements:**+ - A summary section to display "Total Earnings."+ - A table or list to display "Recent Sales." The table should show the skill name, the agent name, the price it was sold for, and the date of the sale.++3. **Data aggregation:**+ - In the backend endpoint, you'll need to join a few tables:+ - `user_skill_purchases` (the source of sales data).+ - `agent_identities` (to get the agent name and verify the owner).+ - `users` (to get the buyer's name, if you want to display it).++## Code Example (Backend Endpoint - `/api/creators/dashboard`)++```javascript+export default async function handler(req, res) {+ // ... authentication ...+ const userId = await getUserIdFromSession(req);++ // Get all agents owned by the user+ const agentsResult = await db.query('SELECT id FROM agent_identities WHERE user_id = $1', [userId]);+ const agentIds = agentsResult.rows.map(r => r.id);++ if (agentIds.length === 0) {+ return res.status(200).json({ total_earnings: 0, sales: [] });+ }++ // Get sales for those agents+ const salesResult = await db.query(+ `SELECT p.skill_name, p.purchase_price, p.purchased_at, a.name as agent_name+ FROM user_skill_purchases p+ JOIN agent_identities a ON p.agent_id = a.id+ WHERE p.agent_id = ANY($1)+ ORDER BY p.purchased_at DESC+ LIMIT 100`,+ [agentIds]+ );++ const totalEarnings = salesResult.rows.reduce((sum, row) => sum + Number(row.purchase_price), 0);++ res.status(200).json({+ total_earnings: totalEarnings / 1e6, // Convert to USDC+ sales: salesResult.rows,+ });+}+```++## Code Example (Frontend JavaScript for `dashboard.html`)++```javascript+async function loadDashboard() {+ const response = await fetch('/api/creators/dashboard');+ const data = await response.json();++ document.getElementById('total-earnings').textContent = `${data.total_earnings.toFixed(2)} USDC`;++ const salesList = document.getElementById('sales-list');+ salesList.innerHTML = data.sales.map(sale => `+ <tr>+ <td>${sale.agent_name}</td>+ <td>${sale.skill_name}</td>+ <td>${(sale.purchase_price / 1e6).toFixed(2)} USDC</td>+ <td>${new Date(sale.purchased_at).toLocaleDateString()}</td>+ </tr>+ `).join('');+}++loadDashboard();+```++## Verification+- Seed your database with some sample sales for agents owned by your test user.+- Navigate to the new `/dashboard` page.+- Verify that the total earnings are calculated and displayed correctly.+- Check that the list of recent sales is populated with the correct data.+- Ensure the page handles the case where a creator has no sales yet.+- Make sure only the creator's own sales are visible, not sales from other creators.diff --git a/docs/monetization-prompts/20-skill-reviews-and-ratings.md b/docs/monetization-prompts/20-skill-reviews-and-ratings.mdnew file mode 100644index 000000000..fb3e9106f--- /dev/null+++ b/docs/monetization-prompts/20-skill-reviews-and-ratings.md@@ -0,0 +1,52 @@+# Prompt 20: User Reviews and Ratings for Skills++**Status:** - [ ] Not Started++## Objective+Implement a system for users to leave reviews and ratings for purchased skills, and display these on the agent detail page.++## Explanation+Social proof is a powerful driver for purchasing decisions. Allowing users to rate and review skills helps other users make informed decisions and provides valuable feedback to creators.++## Instructions+1. **Database Schema for Reviews:**+ * Create a `skill_reviews` table:+ * Columns: `id`, `user_id`, `agent_id`, `skill_name`, `rating` (1-5), `review_text`, `created_at`.++2. **UI for Submitting a Review:**+ * On the "My Purchased Skills" page (from Prompt 11), add a "Leave a Review" button next to each skill the user has not yet reviewed.+ * Clicking this button should open a modal or form with a star rating system (1-5) and a textarea for the review text.++3. **Backend for Submitting Reviews:**+ * Create an endpoint `/api/skills/submit-review`.+ * This endpoint must verify that the user owns the skill they are reviewing before accepting the review.+ * It will insert the new review into the `skill_reviews` table.++4. **Display Reviews and Average Rating:**+ * Modify the agent detail endpoint (`/api/marketplace/agents/:id`) to also fetch and aggregate review data for the agent's skills.+ * For each skill, calculate the average rating and the total number of reviews.+ * On the `marketplace.html` detail page, display the average star rating next to each skill.+ * Consider adding a new tab or section on the detail page to display all written reviews for the agent's skills.++## Code Example (UI for displaying rating)++```javascript+// In the marketplace.js skill rendering loop+const averageRating = skill.average_rating || 0;+const reviewCount = skill.review_count || 0;++let ratingDisplay = '';+if (reviewCount > 0) {+ ratingDisplay = `<span class="skill-rating">+ ${'★'.repeat(Math.round(averageRating))}${'☆'.repeat(5 - Math.round(averageRating))}+ (${reviewCount})+ </span>`;+}++// Add ratingDisplay to the skill entry HTML+return `<div class="skill-entry">+ <span class="skill-name">${escapeHtml(name)}</span>+ ${ratingDisplay}+ ${badgeOrButton}+ </div>`;+```diff --git a/docs/monetization-prompts/21-gifting-skills.md b/docs/monetization-prompts/21-gifting-skills.mdnew file mode 100644index 000000000..7aa3d9529--- /dev/null+++ b/docs/monetization-prompts/21-gifting-skills.md@@ -0,0 +1,62 @@+# Prompt 21: Gifting Skills to Other Users++**Status:** - [ ] Not Started++## Objective+Allow users to purchase a skill as a gift for another user on the platform.++## Explanation+Gifting is a great way to introduce new users to the platform and can be a fun social feature. It allows users to share their favorite skills with friends.++## Instructions+1. **Modify the Purchase Flow:**+ * In the purchase confirmation modal, add a checkbox or button: "Purchase as a gift?".+ * If checked, reveal an input field for the recipient's username or wallet address.++2. **Backend Logic for Gifting:**+ * Modify the `purchase-skill` backend endpoint to handle an optional `recipient_user_id`.+ * If a recipient is specified, the transaction verification remains the same (the buyer pays).+ * However, when recording the ownership in the `user_agent_skills` table, the record should be created for the `recipient_user_id`, not the buyer's ID.+ * You may want to add a `gifted_by_user_id` column to the table to track this.++3. **Notifications:**+ * Implement a notification system (if one doesn't exist) to inform the recipient that they have received a gift.+ * The notification should specify the skill, the agent, and who sent the gift.++4. **On-Chain Receipt (NFT):**+ * If you are minting NFTs as receipts (Prompt 12), the NFT should be minted to the recipient's wallet, not the buyer's. The metadata could include a "Gifted By" attribute.++## Code Example (Conceptual - Backend `purchase-skill` modification)++```javascript+export default async function handler(req, res) {+ const buyerUserId = req.user.id;+ const { agentId, skillName, transactionSignature, recipientUsername } = req.body;+ let finalOwnerId = buyerUserId;++ const db = getDB();++ if (recipientUsername) {+ const recipient = await db.findUserByUsername(recipientUsername);+ if (!recipient) {+ return res.status(404).json({ error: 'Recipient not found.' });+ }+ finalOwnerId = recipient.id;+ }++ // ... (Verify transaction was paid by buyerUserId)++ if (verificationSuccess) {+ // Record purchase for the final owner (recipient or buyer)+ await db.recordSkillPurchase(finalOwnerId, agentId, skillName, buyerUserId); // buyerUserId is the gifter++ // Trigger a notification to the recipient+ if (recipientUsername) {+ await sendNotification(finalOwnerId, `You received the skill ${skillName} as a gift!`);+ }++ res.status(200).json({ success: true, message: 'Gift purchase successful!' });+ }+ // ...+}+```diff --git a/docs/monetization/02-creator-ui-set-prices.md b/docs/monetization/02-creator-ui-set-prices.mdindex 8cde0f1d5..63e3fb80a 100644--- a/docs/monetization/02-creator-ui-set-prices.md+++ b/docs/monetization/02-creator-ui-set-prices.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 2: Creator UI to Set Skill Pricesdiff --git a/marketplace.css b/marketplace.cssindex 66e674235..af76cecf6 100644--- a/marketplace.css+++ b/marketplace.css@@ -22,15 +22,6 @@background-color: rgba(253, 224, 71, 0.1);}-body.market-page {- display: flex;- background-color: #000;- color: #fff;- font-family: 'Inter', sans-serif;- height: 100vh;- overflow: hidden;-}-.skill-entry {display: flex;justify-content: space-between;@@ -64,6 +55,31 @@ body.market-page {vertical-align: middle;}+.skill-owned {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}+ padding: 6px 12px;+ font-size: 12px;+ font-weight: 600;+ border-radius: 6px;+ cursor: pointer;+ transition: background-color 0.2s;+}++.purchase-btn:hover {+ background-color: #5a4ccc; /* A slightly darker shade of accent */+}++.skill-status-badge {+ display: inline-block;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}+.skill-owned {color: #a7f3d0;background-color: rgba(52, 211, 153, 0.1);diff --git a/migrations/002_create_skill_purchases.sql b/migrations/002_create_skill_purchases.sqlnew file mode 100644index 000000000..fb1e42a98--- /dev/null+++ b/migrations/002_create_skill_purchases.sql@@ -0,0 +1,15 @@+-- Migration to create the skill_purchases table++CREATE TABLE "skill_purchases" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ "user_id" uuid NOT NULL REFERENCES "users" ("id"),+ "agent_id" uuid NOT NULL REFERENCES "agent_identities" ("id"),+ "skill_name" varchar(255) NOT NULL,+ "transaction_signature" varchar(255) UNIQUE NOT NULL,+ "amount" bigint NOT NULL,+ "currency_mint" varchar(255) NOT NULL,+ "created_at" timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX "idx_skill_purchases_user_id" ON "skill_purchases" ("user_id");+CREATE INDEX "idx_skill_purchases_agent_id" ON "skill_purchases" ("agent_id");diff --git a/migrations/20260504120000_create_agent_skill_prices.sql b/migrations/20260504120000_create_agent_skill_prices.sqlnew file mode 100644index 000000000..2b5140df3--- /dev/null+++ b/migrations/20260504120000_create_agent_skill_prices.sql@@ -0,0 +1,24 @@+CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ UNIQUE (agent_id, skill_name)+);++CREATE OR REPLACE FUNCTION set_updated_at_timestamp()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = NOW();+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER set_agent_skill_prices_updated_at+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE FUNCTION set_updated_at_timestamp();diff --git a/package.json b/package.jsonindex 65f06b000..2b35a3dd2 100644--- a/package.json+++ b/package.json@@ -98,6 +98,9 @@"@pump-fun/pump-sdk": "^1.33.0","@pump-fun/pump-swap-sdk": "^1.15.0","@pythnetwork/hermes-client": "^1.11.0",+ "@solana/wallet-adapter-base": "^0.9.23",+ "@solana/wallet-adapter-phantom": "^0.9.24",+ "@solana/wallet-adapter-wallets": "^0.19.32","@sentry/node": "^10.50.0","@solana/actions": "^1.6.6","@solana/kit": "^6.8.0",@@ -115,6 +118,7 @@"helius-sdk": "^2.2.2","jose": "^5.9.6","livekit-client": "^2.18.8",+ "@solana/pay": "^0.2.0","query-string": "^8.1.0","resend": "^6.12.2","sas-lib": "^1.0.10",diff --git a/public/marketplace.css b/public/marketplace.cssindex 660a7b54d..7971ba970 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -1275,3 +1275,24 @@ body.market-page {background-color: rgba(253, 224, 71, 0.1);}++.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.price-free {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047;+ background-color: rgba(253, 224, 71, 0.1);+}+diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 6cd17b357..f9e0a21fa 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -1,47 +1,154 @@-function renderAgentForEditing(agent) {- // ... existing code to render agent name, description, etc.+const API_BASE = '/api';+const agentId = new URLSearchParams(location.search).get('id');- const skillsContainer = document.getElementById('skills-editor');- const skillPrices = agent.skill_prices || {};+const $ = (id) => document.getElementById(id);- skillsContainer.innerHTML = agent.skills.map(skill => {- const price = skillPrices[skill.name] || {};- const amountInUnits = price.amount ? price.amount / 1e6 : ''; // Example for USDC (6 decimals)- const currency = price.currency_mint || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T'; // Default to USDC+let agentData = null;++async function loadAgent() {+ if (!agentId) {+ showError('No agent ID provided.');+ return;+ }+ try {+ const r = await fetch(`${API_BASE}/marketplace/agents/${agentId}`);+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const j = await r.json();+ agentData = j.data.agent;+ render();+ } catch (err) {+ showError(err.message);+ }+}++function render() {+ $('loading').hidden = true;+ $('panel-persona').classList.add('active');+ $('agent-title').textContent = `Edit Agent: ${agentData.name}`;+ $('back-link').href = `/agent-detail.html?id=${agentId}`;++ // Persona+ $('f-name').value = agentData.name;+ $('f-desc').value = agentData.description;++ // Publish+ $('f-category').value = agentData.category;+ $('f-tags').value = (agentData.tags || []).join(', ');+ $('f-prompt').value = agentData.system_prompt;+ $('f-greeting').value = agentData.greeting;++ // Monetization+ renderMonetization();+}++function renderMonetization() {+ const container = $('skill-prices-list');+ const skills = agentData.skills || [];+ if (!skills.length) {+ container.innerHTML = '<div class="muted">This agent has no skills.</div>';+ return;+ }++ const skillPrices = agentData.skill_prices || {};++ container.innerHTML = skills.map(skill => {+ const skillName = typeof skill === 'string' ? skill : skill.name;+ const price = skillPrices[skillName];+ const isPaid = !!price;+ const amount = isPaid ? (price.amount / 1e6).toFixed(2) : '';return `- <div class="skill-price-editor" data-skill-name="${skill.name}">- <span class="skill-name">${skill.name}</span>- <input type="number" class="price-amount" placeholder="e.g., 2.50" value="${amountInUnits}">- <select class="price-currency">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" ${currency === 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' ? 'selected' : ''}>USDC</option>- <option value="So11111111111111111111111111111111111111112" ${currency === 'So11111111111111111111111111111111111111112' ? 'selected' : ''}>SOL</option>- </select>+ <div class="skill-item" data-skill-name="${escapeHtml(skillName)}">+ <span class="skill-name">${escapeHtml(skillName)}</span>+ <div class="skill-pricing-controls">+ <label class="toggle-switch">+ <input type="checkbox" class="price-toggle" ${isPaid ? 'checked' : ''}>+ <span class="slider"></span>+ </label>+ <div class="price-input-wrapper" style="display: ${isPaid ? 'flex' : 'none'};">+ <input type="number" class="price-input" min="0" step="0.01" placeholder="0.50" value="${amount}">+ <span>USDC</span>+ </div>+ </div></div>`;}).join('');++ container.querySelectorAll('.price-toggle').forEach(toggle => {+ toggle.addEventListener('change', (e) => {+ const wrapper = e.target.closest('.skill-pricing-controls').querySelector('.price-input-wrapper');+ wrapper.style.display = e.target.checked ? 'flex' : 'none';+ });+ });}-// Add event listener for the "Save Prices" button-document.getElementById('save-prices-btn').addEventListener('click', async () => {- const agentId = /* get agent id from somewhere */;- const editors = document.querySelectorAll('.skill-price-editor');-- for (const editor of editors) {- const skill_name = editor.dataset.skillName;- const amountInUnits = parseFloat(editor.querySelector('.price-amount').value);- const currency_mint = editor.querySelector('.price-currency').value;-- if (!isNaN(amountInUnits) && amountInUnits > 0) {- const amount = Math.round(amountInUnits * 1e6); // Convert back to smallest unit-- await fetch(`/api/agents/${agentId}/skills/pricing`, {- method: 'POST',- headers: { 'Content-Type': 'application/json', /* + auth headers */ },- body: JSON.stringify({ skill_name, amount, currency_mint }),+function showError(msg) {+ $('loading').hidden = true;+ const errEl = $('error');+ errEl.textContent = `Error: ${msg}`;+ errEl.hidden = false;+}++function escapeHtml(s) {+ return String(s || '').replace(+ /[&<>"']/g,+ (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch],+ );+}+++// --- Event Listeners ---++$('persona-save').addEventListener('click', async () => {+ // This would save persona changes, not implemented in this task+});++$('publish-save').addEventListener('click', async () => {+ // This would save publish changes, not implemented in this task+});++$('monetization-save').addEventListener('click', async () => {+ const prices = [];+ document.querySelectorAll('#skill-prices-list .skill-item').forEach(item => {+ const name = item.dataset.skillName;+ const toggle = item.querySelector('.price-toggle');+ const input = item.querySelector('.price-input');++ if (toggle.checked && input.value) {+ const amountInLamports = parseFloat(input.value) * 1e6;+ prices.push({+ skill_name: name,+ amount: amountInLamports,+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a'});}+ });++ try {+ const r = await fetch(`${API_BASE}/agents/${agentId}/skill-prices`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prices })+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ $('monetization-status').textContent = 'Prices saved!';+ $('monetization-status').className = 'form-status ok';+ } catch (err) {+ $('monetization-status').textContent = `Error: ${err.message}`;+ $('monetization-status').className = 'form-status err';}- // Show feedback to user- alert('Prices saved!');});+++document.querySelectorAll('.edit-tab').forEach(tab => {+ tab.addEventListener('click', (e) => {+ document.querySelectorAll('.edit-tab').forEach(t => t.classList.remove('active'));+ document.querySelectorAll('.edit-panel').forEach(p => p.classList.remove('active'));++ const tabId = e.target.dataset.tab;+ e.target.classList.add('active');+ $(`panel-${tabId}`).classList.add('active');+ });+});++loadAgent();diff --git a/src/components/PriceBadge.js b/src/components/PriceBadge.jsnew file mode 100644index 000000000..f50f20dd3--- /dev/null+++ b/src/components/PriceBadge.js@@ -0,0 +1,29 @@++// Mapping of mint addresses to human-readable currency symbols.+const CURRENCY_SYMBOLS = {+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a': 'USDC',+ 'So11111111111111111111111111111111111111112': 'SOL',+};++// Divisors to convert from smallest unit to standard unit.+const CURRENCY_DIVISORS = {+ 'USDC': 1e6,+ 'SOL': 1e9,+};++export function PriceBadge(price) {+ if (!price || !price.amount) {+ return `<span class="price-badge price-free">Free</span>`;+ }++ const symbol = CURRENCY_SYMBOLS[price.currency_mint] || '???';+ const divisor = CURRENCY_DIVISORS[symbol] || 1;+ const formattedAmount = (price.amount / divisor).toFixed(2);++ return `+ <span class="price-badge price-paid">+ ${formattedAmount} ${symbol}+ </span>+ `;+}+\ No newline at end of filediff --git a/src/marketplace.js b/src/marketplace.jsindex 8db82ed5f..04a926d4e 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -1,4 +1,6 @@import QRCode from 'qrcode';+import { createQR } from '@solana/pay';+import { escapeHtml } from './utils'; // Assuming you have this/*** Agent Marketplace — discovery + detail page controller.@@ -7,6 +9,7 @@ import QRCode from 'qrcode';* (5 tabs). Routing is path-based: /marketplace and /marketplace/agents/:id.*/+const API = '/api';const CATEGORY_LABELS = {@@ -177,7 +180,7 @@ function renderCard(a) {<div class="avatar">${a.avatar}</div><div style="min-width:0;flex:1"><div class="title">${escapeHtml(a.name || 'Untitled')}</div>- <div class="author">${escapeHtml(a.author_name || 'Anonymous')}</div>+ <div class="author">${escapeHtml(a.author || 'Anonymous')}</div></div></div><div class="desc">${escapeHtml(a.description || '')}</div>@@ -185,7 +188,7 @@ function renderCard(a) {<span class="stat-pill">⊙ ${a.views || 0}</span><span class="stat-pill">⑂ ${a.forks || 0}</span>${skills ? `<span class="stat-pill">▤ ${skills}</span>` : ''}- ${a.has_paid_skills ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}+ ${Object.keys(a.skill_prices || {}).length > 0 ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}</div><div class="footer"><span>${date}</span>@@ -246,35 +249,6 @@ function renderDetail(a, bookmarked) {$('d-bookmark').classList.toggle('on', bookmarked);$('d-bookmark').textContent = bookmarked ? '★' : '☆';- const skillPrices = a.skill_prices || {};- // For now, assume user owns nothing. We will replace this with a real check later.- const ownedSkills = new Set();-- $('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];-- let actionButton;- if (price) {- if (ownedSkills.has(name)) {- actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;- } else {- actionButton = `<button class="skill-btn purchase" data-skill-name="${escapeHtml(name)}">Purchase</button>`;- }- } else {- actionButton = `<button class="skill-btn" disabled>Free</button>`;- }-- const priceDisplay = price ? `<span class="price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>` : ``;-- return `<div class="skill-row">- <span class="skill-name">${escapeHtml(name)} ${priceDisplay}</span>- ${actionButton}- </div>`;- }).join('')- : '<div>This Agent has no skills defined.</div>';-const forksEl = $('d-forks-pill');if (a.forks > 0) {forksEl.textContent = `⑂ ${a.forks} forks`;@@ -293,17 +267,24 @@ function renderDetail(a, bookmarked) {const skillPrices = a.skill_prices || {};$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : s.name || '';- const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;- }).join(' ')+ ? skillsArr+ .map((s) => {+ const name = typeof s === 'string' ? s : s.name || '';+ const price = skillPrices[name];+ const badge = price+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(+ 2,+ )} USDC</span>`+ : `<span class="price-badge price-free">Free</span>`;+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ })+ .join(' '): '<div>This Agent has no skills defined.</div>';+$('d-library').innerHTML = libraryArr.length- ? libraryArr.map((l) => `<span class="stat-pill">${escapeHtml(typeof l === 'string' ? l : l.name || '')}</span>`).join(' ')+ ? libraryArr+ .map((l) => `<span class="stat-pill">${escapeHtml(typeof l === 'string' ? l : l.name || '')}</span>`)+ .join(' '): '<div>This Agent includes the following Libraries to help answer more questions.</div>';// Profile capabilities listdiff --git a/src/wallet.js b/src/wallet.jsindex 6a7c916fd..381e9255a 100644--- a/src/wallet.js+++ b/src/wallet.js@@ -1,14 +1,32 @@-// src/wallet.js+import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';+import { Connection, PublicKey } from '@solana/web3.js';-// Placeholder for wallet adapter logic-let wallet;+let connectedWalletAddress = null;-function onConnectWallet() {- console.log('Attempting to connect wallet...');- // The actual connection logic will be implemented in the next prompt.- // For now, we can simulate a successful connection.- const mockAddress = 'YourWalletAddress...';- updateWalletState(mockAddress);+// Initialize the wallet adapter+const wallet = new PhantomWalletAdapter();++// Listen for connection events+wallet.on('connect', (publicKey) => {+ connectedWalletAddress = publicKey.toBase58();+ console.log(`Wallet connected: ${connectedWalletAddress}`);+ updateWalletState(connectedWalletAddress);+});++wallet.on('disconnect', () => {+ console.log('Wallet disconnected');+ connectedWalletAddress = null;+ updateWalletState(null);+});++async function onConnectWallet() {+ if (!wallet.connected) {+ try {+ await wallet.connect();+ } catch (error) {+ console.error('Wallet connection failed:', error);+ }+ }}export function updateWalletState(address) {@@ -28,4 +46,16 @@ export function initWalletButton() {if (btn) {btn.addEventListener('click', onConnectWallet);}+ // Auto-connect if wallet is already connected+ if (wallet.autoConnect) {+ wallet.autoConnect();+ }+}++export function getConnectedWallet() {+ return wallet.connected ? wallet : null;+}++export function getConnectedWalletAddress() {+ return connectedWalletAddress;}diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.mdnew file mode 100644index 000000000..19f00332a--- /dev/null+++ b/tasks/monetization-feature/01-display-priced-skills.md@@ -0,0 +1,72 @@+---+status: completed+---++# Prompt 1: Display Priced Skills in Marketplace++**Status:** Completed++## Objective+Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.++## Explanation+Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.++## Instructions+- [x] **Modify the Backend API:**+ - [x] Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.+ - [x] When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.+ - [x] Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.++- [x] **Update the Frontend UI:**+ - [x] In `src/marketplace.js`, find the `renderDetail` function.+ - [x] This function receives the agent object, which now includes `skill_prices`.+ - [x] Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.+ - [x] If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).+ - [x] Style the price badge to be visually distinct.++## Code Example (Frontend - `src/marketplace.js`)++Here's how you might modify the skill rendering part within the `renderDetail` function:++```javascript+// Inside renderDetail function++const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const badge = price+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`+ : `<span class="price-badge price-free">Free</span>`;+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example++Add these styles to `/marketplace.css` to make the price badges look good.++```css+.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.price-free {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047;+ background-color: rgba(253, 224, 71, 0.1);+}+```diff --git a/tasks/monetization-feature/03-backend-create-purchase-table.md b/tasks/monetization-feature/03-backend-create-purchase-table.mdindex 5df176604..e0b884379 100644--- a/tasks/monetization-feature/03-backend-create-purchase-table.md+++ b/tasks/monetization-feature/03-backend-create-purchase-table.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Create Purchases Database Tablediff --git a/tasks/monetization-feature/03-backend-set-skill-prices-api.md b/tasks/monetization-feature/03-backend-set-skill-prices-api.mdindex baabc86e3..579bcf166 100644--- a/tasks/monetization-feature/03-backend-set-skill-prices-api.md+++ b/tasks/monetization-feature/03-backend-set-skill-prices-api.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend API to Set Skill Pricesdiff --git a/tasks/monetization-feature/03-monetization-page-UI.md b/tasks/monetization-feature/03-monetization-page-UI.mdnew file mode 100644index 000000000..4f257e77e--- /dev/null+++ b/tasks/monetization-feature/03-monetization-page-UI.md@@ -0,0 +1,32 @@+---+status: completed+---++# Prompt 3: Monetization Page UI++## Objective+Create the user interface for the monetization page, allowing creators to set prices for their agent's skills.++## Explanation+With the backend ready, we now need a UI that allows agent creators to manage the prices of their skills. This will be a new "Monetization" tab in the agent editor (`agent-edit.html`). The UI will fetch the agent's skills and their current prices, display them in a form, and allow the creator to save changes.++## Instructions+- [ ] **Add a "Monetization" Tab:**+ - [ ] In `agent-edit.html`, add a new tab to the tab list named "Monetization".+ - [ ] Create a corresponding panel for the monetization content.++- [ ] **Build the Pricing Form:**+ - [ ] In the new panel, create a form that lists all of the agent's skills.+ - [ ] For each skill, display a text input field to enter the price in USDC.+ - [ ] Fetch the current prices from the API endpoint you created earlier (`/api/agents/:id/skills-pricing`) and populate the form.+ - [ ] Add a "Save Prices" button.++- [ ] **Implement Save Functionality:**+ - [ ] When the "Save Prices" button is clicked, collect the data from the form.+ - [ ] For each skill, create a price object `{ skill, amount, currency_mint, chain }`. Remember to convert the USDC amount back to the smallest unit (e.g., multiply by 1,000,000).+ - [ ] Send this data to the backend via a `PUT` request to `/api/agents/:id/skills-pricing`.+ - [ ] Display a success or error message to the user.++- [ ] **Handle Loading and Error States:**+ - [ ] Show a loading indicator while fetching prices.+ - [ ] Display a clear error message if the API call fails.diff --git a/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md b/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.mdindex 57b77749f..a14911f6b 100644--- a/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md+++ b/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: UI for Skill Pricingdiff --git a/tasks/monetization-feature/05-backend-purchase-initiation-api.md b/tasks/monetization-feature/05-backend-purchase-initiation-api.mdindex 13d0ac689..4f637ee91 100644--- a/tasks/monetization-feature/05-backend-purchase-initiation-api.md+++ b/tasks/monetization-feature/05-backend-purchase-initiation-api.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 5: Backend - Purchase Initiation APIdiff --git a/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md b/tasks/monetization-feature/06-frontend-purchase-button-and-modal.mdindex 6e6f3d44d..c2dc9df11 100644--- a/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md+++ b/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 6: Frontend - "Purchase Skill" Button & Modaldiff --git a/vercel.json b/vercel.jsonindex f151b7a15..634ed58e3 100644--- a/vercel.json+++ b/vercel.json@@ -228,6 +228,10 @@"src": "/api/marketplace/agents","dest": "/api/marketplace/[action]?action=agents"},+ {+ "src": "/api/agents/([^/]+)/skills/set-price",+ "dest": "/api/agent-skills?agentId=$1&action=set-price"+ },{"src": "/api/marketplace/agents/([^/]+)","dest": "/api/marketplace/[action]?action=agents&id=$1"