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
Subscription plans: bundle agent skills into a plan, with creator UI
nirholasc1268dc4c7ff
diff --git a/api/_lib/migrations/20260618000000_subscription_plan_skills.sql b/api/_lib/migrations/20260618000000_subscription_plan_skills.sqlnew file mode 100644index 000000000..17e881ff1--- /dev/null+++ b/api/_lib/migrations/20260618000000_subscription_plan_skills.sql@@ -0,0 +1,16 @@+-- Migration: add included_skills to creator subscription plans (tiers).+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260618000000_subscription_plan_skills.sql+-- Idempotent.+--+-- A subscription tier bundles access to a chosen set of the agent's paid+-- skills. Creators pick which skills are included from the agent-edit+-- Monetization tab; the array holds skill names (matching the keys used in+-- agent_identities.skill_prices). The user-facing subscription flow grants a+-- subscriber access to exactly these skills for the life of their period.++begin;++alter table subscription_plans+ add column if not exists included_skills text[] not null default '{}';++commit;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 3575152a0..77df75fc3 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1141,6 +1141,7 @@ create table if not exists subscription_plans (price_usd numeric(8,2) not null check (price_usd >= 0.99),interval text not null default 'monthly' check (interval in ('weekly','monthly')),perks text[],+ included_skills text[] not null default '{}',active boolean not null default true,created_at timestamptz not null default now());diff --git a/api/subscriptions/plans.js b/api/subscriptions/plans.jsindex c18d58380..7e7971615 100644--- a/api/subscriptions/plans.js+++ b/api/subscriptions/plans.js@@ -22,12 +22,16 @@ const planSchema = z.object({price_usd: z.number().min(0.99).max(999),interval: z.enum(['weekly', 'monthly']).default('monthly'),perks: z.array(z.string().trim().max(120)).max(10).default([]),+ included_skills: z.array(z.string().trim().min(1).max(120)).max(50).default([]),+ active: z.boolean().default(true),});const patchSchema = z.object({name: z.string().trim().min(2).max(80).optional(),price_usd: z.number().min(0.99).max(999).optional(),+ interval: z.enum(['weekly', 'monthly']).optional(),perks: z.array(z.string().trim().max(120)).max(10).optional(),+ included_skills: z.array(z.string().trim().min(1).max(120)).max(50).optional(),active: z.boolean().optional(),});@@ -68,22 +72,45 @@ async function handleList(req, res) {return error(res, 400, 'validation_error', 'agent_id must be a valid UUID');}+ // Public callers only ever see active plans. The owner may pass+ // include_inactive=1 to also receive deactivated plans (so the edit UI can+ // surface and reactivate them). We confirm ownership before honouring it.+ const wantsInactive = ['1', 'true'].includes(params.get('include_inactive') || '');+ let includeInactive = false;+ if (wantsInactive) {+ const user = await getSessionUser(req);+ if (user) {+ if (agentId) {+ const [owned] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL+ `;+ includeInactive = !!owned;+ } else {+ includeInactive = creatorId === user.id;+ }+ }+ }+let rows;if (agentId) {// Look up all plans belonging to this agent's creator (agent_id is public).+ // Active plans first, then most-recent drafts, so the owner's list reads top-down.rows = await sql`- SELECT sp.id, sp.creator_id, sp.agent_id, sp.name, sp.price_usd, sp.interval, sp.perks, sp.active, sp.created_at+ SELECT sp.id, sp.creator_id, sp.agent_id, sp.name, sp.price_usd, sp.interval, sp.perks, sp.included_skills, sp.active, sp.created_atFROM subscription_plans spJOIN agent_identities ai ON ai.user_id = sp.creator_id- WHERE ai.id = ${agentId} AND ai.deleted_at IS NULL AND sp.active = true- ORDER BY sp.created_at ASC+ WHERE ai.id = ${agentId} AND ai.deleted_at IS NULL+ AND (${includeInactive} OR sp.active = true)+ ORDER BY sp.active DESC, sp.created_at ASC`;} else {rows = await sql`- SELECT id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ SELECT id, creator_id, agent_id, name, price_usd, interval, perks, included_skills, active, created_atFROM subscription_plans- WHERE creator_id = ${creatorId} AND active = true- ORDER BY created_at ASC+ WHERE creator_id = ${creatorId}+ AND (${includeInactive} OR active = true)+ ORDER BY active DESC, created_at ASC`;}return json(res, 200, { plans: rows });@@ -104,12 +131,15 @@ async function handleCreate(req, res) {const body = parse(planSchema, await readJson(req));- // Enforce max 3 active plans per creator.- const [{ count }] = await sql`- SELECT count(*)::int AS count FROM subscription_plans- WHERE creator_id = ${user.id} AND active = true- `;- if (count >= 3) return error(res, 409, 'conflict', 'maximum 3 active plans per creator');+ // Enforce max 3 active plans per creator — only counts toward the cap if the+ // new plan is being created active. Drafts (active=false) don't consume a slot.+ if (body.active) {+ const [{ count }] = await sql`+ SELECT count(*)::int AS count FROM subscription_plans+ WHERE creator_id = ${user.id} AND active = true+ `;+ if (count >= 3) return error(res, 409, 'conflict', 'maximum 3 active plans per creator');+ }// Verify agent_id belongs to creator if provided.if (body.agent_id) {@@ -121,10 +151,10 @@ async function handleCreate(req, res) {}const [plan] = await sql`- INSERT INTO subscription_plans (creator_id, agent_id, name, price_usd, interval, perks)+ INSERT INTO subscription_plans (creator_id, agent_id, name, price_usd, interval, perks, included_skills, active)VALUES (${user.id}, ${body.agent_id ?? null}, ${body.name}, ${body.price_usd},- ${body.interval}, ${body.perks})- RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ ${body.interval}, ${body.perks}, ${body.included_skills}, ${body.active})+ RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, included_skills, active, created_at`;return json(res, 201, { plan });}@@ -140,10 +170,21 @@ async function handlePatch(req, res, planId) {const body = parse(patchSchema, await readJson(req));const [existing] = await sql`- SELECT id FROM subscription_plans WHERE id = ${planId} AND creator_id = ${user.id}+ SELECT id, active FROM subscription_plans WHERE id = ${planId} AND creator_id = ${user.id}`;if (!existing) return error(res, 404, 'not_found', 'plan not found');+ // Reactivating a plan must respect the max-3-active cap (the create path+ // enforces the same invariant). Already-active plans toggling other fields+ // don't re-check, and deactivating is always allowed.+ if (body.active === true && existing.active === false) {+ const [{ count }] = await sql`+ SELECT count(*)::int AS count FROM subscription_plans+ WHERE creator_id = ${user.id} AND active = true AND id <> ${planId}+ `;+ if (count >= 3) return error(res, 409, 'conflict', 'maximum 3 active plans per creator');+ }+const setFrags = [];const params = [];if (body.name !== undefined) {@@ -154,10 +195,18 @@ async function handlePatch(req, res, planId) {params.push(body.price_usd);setFrags.push(`price_usd = $${params.length}`);}+ if (body.interval !== undefined) {+ params.push(body.interval);+ setFrags.push(`interval = $${params.length}`);+ }if (body.perks !== undefined) {params.push(body.perks);setFrags.push(`perks = $${params.length}`);}+ if (body.included_skills !== undefined) {+ params.push(body.included_skills);+ setFrags.push(`included_skills = $${params.length}`);+ }if (body.active !== undefined) {params.push(body.active);setFrags.push(`active = $${params.length}`);@@ -175,7 +224,7 @@ async function handlePatch(req, res, planId) {UPDATE subscription_plansSET ${setFrags.join(', ')}WHERE id = $${planIdIdx} AND creator_id = $${userIdIdx}- RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at+ RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, included_skills, active, created_at`,params,);diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex cef67a7c3..8c552558b 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -728,6 +728,40 @@align-items: center;gap: 1rem;}+ .plan-skills-checklist {+ display: flex;+ flex-direction: column;+ gap: 0.15rem;+ max-height: 180px;+ overflow-y: auto;+ padding: 0.5rem;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.02);+ }+ .plan-skill-check {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.764rem;+ color: rgba(255, 255, 255, 0.7);+ padding: 0.25rem 0.3rem;+ border-radius: 4px;+ cursor: pointer;+ transition: background 0.15s ease;+ }+ .plan-skill-check:hover {+ background: rgba(255, 255, 255, 0.04);+ }+ .plan-skill-check input {+ accent-color: #a4f0bc;+ cursor: pointer;+ flex-shrink: 0;+ }+ .plan-skills-empty {+ font-size: 0.7rem;+ color: rgba(255, 255, 255, 0.4);+ }.toggle-switch {position: relative;display: inline-block;@@ -1291,6 +1325,23 @@<label class="form-label" style="font-size: 0.764rem;" for="plan-perks-input">Perks (one per line)</label><textarea class="form-textarea" id="plan-perks-input" rows="3" placeholder="Unlimited API calls Priority queue Early access to new skills" style="font-size: 0.764rem;"></textarea></div>+ <div class="form-group" style="margin-bottom: 0.75rem;">+ <label class="form-label" style="font-size: 0.764rem;">Included Skills</label>+ <p class="note" style="font-size: 0.7rem; color: rgba(255,255,255,0.4); margin: -0.25rem 0 0.4rem;">Subscribers get unlimited access to the skills you tick here for the life of their plan.</p>+ <div id="plan-skills-checklist" class="plan-skills-checklist" role="group" aria-label="Skills included in this plan">+ <span class="muted" style="font-size: 0.7rem;">Loading skills…</span>+ </div>+ </div>+ <div class="form-group" style="margin-bottom: 0.75rem; flex-direction: row; align-items: center; justify-content: space-between; gap: 0.75rem;">+ <div>+ <label class="form-label" style="font-size: 0.764rem; margin: 0;" for="plan-active-input">Active</label>+ <p class="note" style="font-size: 0.7rem; color: rgba(255,255,255,0.4); margin: 0.15rem 0 0;">Inactive plans are hidden from subscribers. Existing subscribers keep access.</p>+ </div>+ <label class="toggle-switch" title="Toggle whether this plan is offered to subscribers">+ <input type="checkbox" id="plan-active-input" checked>+ <span class="slider"></span>+ </label>+ </div><div style="display: flex; gap: 0.5rem; align-items: center;"><button class="btn-primary" id="plan-save-btn" style="font-size: 0.764rem; padding: 0.4rem 0.9rem;">Save Plan</button><button class="btn-ghost" id="plan-cancel-btn" style="font-size: 0.764rem; padding: 0.4rem 0.9rem;">Cancel</button>diff --git a/prompts/monetization/14-ui-for-subscription-tiers.md b/prompts/monetization/14-ui-for-subscription-tiers.mddeleted file mode 100644index 913cb517a..000000000--- a/prompts/monetization/14-ui-for-subscription-tiers.md+++ /dev/null@@ -1,104 +0,0 @@-# Prompt 14: UI for Subscription Tiers--## Objective-Implement the UI in the creator's dashboard that allows them to create, view, and manage subscription tiers for their agents.--## Explanation-Building on the subscription database schema, we now need a user interface for creators. This UI will live in the "Monetization" tab and will provide a form to define a new subscription tier (name, price, included skills) and a list to display existing tiers.--## Instructions-1. **Add UI Structure:**- * In `agent-edit.html`, within the "Monetization" tab panel, add a new section for "Subscription Tiers".- * This section should contain a button "Create New Tier" which reveals a form.- * Also, include a container to list the existing tiers, e.g., `#subscription-tiers-list`.--2. **Create Tier Form:**- * The form should have inputs for tier `name`, `description`, `price`, `currency`, and `billing interval` (monthly/yearly).- * A crucial part will be a multi-select box or a list of checkboxes for the creator to choose which of the agent's skills are included in this tier.--3. **Frontend Logic:**- * In `src/agent-edit.js`, write a function to fetch the agent's skills and existing subscription tiers.- * Populate the skills multi-select in the form.- * Render the list of existing tiers with an "Edit" or "Deactivate" button for each.- * Handle the form submission to collect the data for a new tier, which will be sent to the backend (to be created in the next prompt).--## HTML Example (`agent-edit.html`)--```html-<!-- Inside the 'monetization' tab-content -->-<div class="card">- <h3>Subscription Tiers</h3>- <div id="subscription-tiers-list">- <!-- Existing tiers will be rendered here -->- </div>- <button id="show-create-tier-form-btn">Create New Tier</button>- <div id="create-tier-form-container" style="display:none;">- <h4>New Subscription Tier</h4>- <div class="form-field">- <label for="tier-name">Tier Name</label>- <input type="text" id="tier-name" placeholder="e.g., Pro">- </div>- <div class="form-field">- <label for="tier-price">Price</label>- <input type="number" id="tier-price" placeholder="9.99">- <select id="tier-currency">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d">USDC</option>- </select>- <select id="tier-interval">- <option value="month">per month</option>- <option value="year">per year</option>- </select>- </div>- <div class="form-field">- <label>Included Skills</label>- <div id="tier-skills-checklist">- <!-- Checkboxes for skills will be rendered here -->- </div>- </div>- <button id="save-tier-btn">Save Tier</button>- <button id="cancel-create-tier-btn" type="button">Cancel</button>- </div>-</div>-```--## JavaScript Example (`src/agent-edit.js`)--```javascript-const showCreateTierBtn = document.getElementById('show-create-tier-form-btn');-const createTierContainer = document.getElementById('create-tier-form-container');-const saveTierBtn = document.getElementById('save-tier-btn');--showCreateTierBtn.addEventListener('click', () => {- createTierContainer.style.display = 'block';- showCreateTierBtn.style.display = 'none';- populateSkillsForTierForm(); // a function that fetches and renders skills as checkboxes-});--saveTierBtn.addEventListener('click', async () => {- const tierData = {- name: document.getElementById('tier-name').value,- price_amount: Math.round(parseFloat(document.getElementById('tier-price').value) * 1e6),- price_currency_mint: document.getElementById('tier-currency').value,- billing_interval: document.getElementById('tier-interval').value,- included_skills: Array.from(document.querySelectorAll('#tier-skills-checklist input:checked')).map(cb => cb.value)- };-- const agentId = /* get agent id from context */;- // Backend call will be implemented next- await createSubscriptionTier(agentId, tierData);-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/14-ui-for-subscription-tiers.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 5a452ca0c..30f1c8907 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -1042,7 +1042,7 @@ async function loadSubscriptionPlans() {const list = $('subscription-plans-list');if (!list) return;try {- const r = await apiFetch(`${API_BASE}/subscriptions/plans?agent_id=${encodeURIComponent(agentId)}`, { credentials: 'include' });+ const r = await apiFetch(`${API_BASE}/subscriptions/plans?agent_id=${encodeURIComponent(agentId)}&include_inactive=1`, { credentials: 'include' });const j = await r.json().catch(() => ({}));const plans = j.plans || [];plansLoaded = true;@@ -1060,19 +1060,52 @@ function renderPlansList(plans) {list.innerHTML = `<span class="muted" style="font-size:0.764rem;">No plans yet — create one below.</span>`;return;}- list.innerHTML = plans.map(p => `- <div class="plan-row" style="display:flex; align-items:center; justify-content:space-between; padding:0.5rem 0.75rem; border:1px solid rgba(255,255,255,0.08); border-radius:6px; background:rgba(255,255,255,0.02);">+ list.innerHTML = plans.map(p => {+ const isActive = p.active !== false;+ const planJson = JSON.stringify(p).replace(/"/g, '"');+ const action = isActive+ ? `<button class="btn-ghost danger" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="deletePlan('${p.id}')">Deactivate</button>`+ : `<button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem; color:#86efac; border-color:rgba(134,239,172,0.4);" onclick="reactivatePlan('${p.id}')">Reactivate</button>`;+ return `+ <div class="plan-row" style="display:flex; align-items:center; justify-content:space-between; padding:0.5rem 0.75rem; border:1px solid rgba(255,255,255,${isActive ? '0.08' : '0.05'}); border-radius:6px; background:rgba(255,255,255,0.02); opacity:${isActive ? '1' : '0.6'};"><div><span style="font-weight:600; font-size:0.875rem;">${escHtml(p.name)}</span><span style="color:rgba(255,255,255,0.45); font-size:0.764rem; margin-left:0.5rem;">$${Number(p.price_usd).toFixed(2)} / ${p.interval}</span>+ ${isActive ? '' : `<span style="font-size:0.6rem; text-transform:uppercase; letter-spacing:0.05em; color:rgba(255,255,255,0.5); background:rgba(255,255,255,0.08); padding:0.1rem 0.4rem; border-radius:4px; margin-left:0.5rem;">Inactive</span>`}${p.perks?.length ? `<div style="font-size:0.7rem; color:rgba(255,255,255,0.35); margin-top:0.15rem;">${escHtml(p.perks.join(' · '))}</div>` : ''}+ ${p.included_skills?.length ? `<div style="font-size:0.7rem; color:rgba(164,240,188,0.65); margin-top:0.15rem;">Includes ${p.included_skills.length} skill${p.included_skills.length === 1 ? '' : 's'}: ${escHtml(p.included_skills.join(' · '))}</div>` : ''}</div><div style="display:flex; gap:0.4rem;">- <button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="openPlanEditor(${JSON.stringify(p).replace(/"/g, '"')})">Edit</button>- <button class="btn-ghost danger" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="deletePlan('${p.id}')">Delete</button>+ <button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="openPlanEditor(${planJson})">Edit</button>+ ${action}</div>- </div>- `).join('');+ </div>`;+ }).join('');+}++// Skill names available on this agent (skills may be strings or {name} objects).+function planSkillNames() {+ return (agentData.skills || [])+ .map((s) => (typeof s === 'string' ? s : s?.name))+ .filter(Boolean);+}++// Render the agent's skills as a checklist inside the plan editor, pre-checking+// the ones already bundled into the plan being edited.+function renderPlanSkillsChecklist(selected = []) {+ const host = $('plan-skills-checklist');+ if (!host) return;+ const selectedSet = new Set(selected);+ const names = planSkillNames();+ if (!names.length) {+ host.innerHTML = `<span class="plan-skills-empty">This agent has no skills yet. Add skills in the Skills tab to bundle them into a plan.</span>`;+ return;+ }+ host.innerHTML = names.map((name) => `+ <label class="plan-skill-check">+ <input type="checkbox" value="${escHtml(name)}" ${selectedSet.has(name) ? 'checked' : ''}>+ <span>${escHtml(name)}</span>+ </label>`).join('');}window.openPlanEditor = function openPlanEditor(plan) {@@ -1083,6 +1116,8 @@ window.openPlanEditor = function openPlanEditor(plan) {$('plan-price-input').value = plan?.price_usd ?? '';$('plan-interval-input').value = plan?.interval ?? 'monthly';$('plan-perks-input').value = (plan?.perks ?? []).join('\n');+ $('plan-active-input').checked = plan?.active !== false;+ renderPlanSkillsChecklist(plan?.included_skills ?? []);$('plan-status').textContent = '';editor.style.display = 'block';$('show-create-plan-btn').style.display = 'none';@@ -1090,13 +1125,31 @@ window.openPlanEditor = function openPlanEditor(plan) {};window.deletePlan = async function deletePlan(planId) {- if (!confirm('Delete this plan? Subscribers will keep access until their period ends.')) return;+ if (!confirm('Deactivate this plan? It will be hidden from new subscribers; existing subscribers keep access until their period ends. You can reactivate it later.')) return;try {const r = await apiFetch(`${API_BASE}/subscriptions/plans/${planId}`, { method: 'DELETE', credentials: 'include' });if (!r.ok) throw new Error(`HTTP ${r.status}`);loadSubscriptionPlans();} catch (err) {- alert(`Error deleting plan: ${err.message}`);+ alert(`Error deactivating plan: ${err.message}`);+ }+};++window.reactivatePlan = async function reactivatePlan(planId) {+ try {+ const r = await apiFetch(`${API_BASE}/subscriptions/plans/${planId}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ active: true }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ }+ loadSubscriptionPlans();+ } catch (err) {+ alert(`Could not reactivate plan: ${err.message}`);}};@@ -1116,19 +1169,25 @@ $('plan-save-btn')?.addEventListener('click', async () => {const price_usd = parseFloat($('plan-price-input').value);const interval = $('plan-interval-input').value;const perks = $('plan-perks-input').value.split('\n').map(s => s.trim()).filter(Boolean);+ const active = $('plan-active-input').checked;+ const included_skills = Array.from(+ document.querySelectorAll('#plan-skills-checklist input[type="checkbox"]:checked'),+ ).map((cb) => cb.value);if (!name) { status.textContent = 'Name is required.'; status.className = 'form-status err'; return; }if (!price_usd || price_usd < 0.99) { status.textContent = 'Price must be at least $0.99.'; status.className = 'form-status err'; return; }status.textContent = 'Saving…'; status.className = 'form-status';try {- const payload = { name, price_usd, interval, perks, agent_id: agentId };const url = planId ? `${API_BASE}/subscriptions/plans/${planId}` : `${API_BASE}/subscriptions/plans`;+ const body = planId+ ? { name, price_usd, interval, perks, included_skills, active }+ : { name, price_usd, interval, perks, included_skills, active, agent_id: agentId };const r = await apiFetch(url, {method: planId ? 'PATCH' : 'POST',headers: { 'Content-Type': 'application/json' },credentials: 'include',- body: JSON.stringify(planId ? { name, price_usd, interval, perks } : payload),+ body: JSON.stringify(body),});if (!r.ok) {const j = await r.json().catch(() => ({}));