Skip to content

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

Skill pricing, bundles, subscriptions, agent tiers, collection page

nirholas52063106ae98
diff --git a/api/_lib/migrations/20260617200000_skill_bundles.sql b/api/_lib/migrations/20260617200000_skill_bundles.sql
new file mode 100644
index 000000000..946c2d1bd
--- /dev/null
+++ b/api/_lib/migrations/20260617200000_skill_bundles.sql
@@ -0,0 +1,56 @@
+-- Skill bundles: creators can sell multiple skills together at a single price.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260617200000_skill_bundles.sql
+-- Idempotent.
+
+begin;
+
+-- Bundle header — one per creator-defined bundle.
+create table if not exists skill_bundles (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ name text not null,
+ description text,
+ price_amount bigint not null check (price_amount > 0),
+ currency_mint text not null,
+ chain text not null default 'solana',
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists idx_skill_bundles_agent on skill_bundles(agent_id) where is_active;
+
+-- Bundle items — which skills belong to which bundle.
+create table if not exists bundle_items (
+ id uuid primary key default gen_random_uuid(),
+ bundle_id uuid not null references skill_bundles(id) on delete cascade,
+ skill_name text not null,
+ created_at timestamptz not null default now(),
+ unique (bundle_id, skill_name)
+);
+
+create index if not exists idx_bundle_items_bundle on bundle_items(bundle_id);
+
+-- Purchase records for bundle purchases (separate from single-skill purchases).
+create table if not exists bundle_purchases (
+ id uuid primary key default gen_random_uuid(),
+ bundle_id uuid not null references skill_bundles(id) on delete restrict,
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null,
+ price_amount bigint not null,
+ currency_mint text not null,
+ chain text not null default 'solana',
+ tx_signature text,
+ status text not null default 'pending'
+ check (status in ('pending', 'confirmed', 'failed', 'refunded')),
+ platform_fee_amount bigint not null default 0,
+ created_at timestamptz not null default now(),
+ confirmed_at timestamptz
+);
+
+create index if not exists idx_bundle_purchases_user on bundle_purchases(user_id);
+create index if not exists idx_bundle_purchases_bundle on bundle_purchases(bundle_id);
+create unique index if not exists idx_bundle_purchases_tx on bundle_purchases(tx_signature)
+ where tx_signature is not null;
+
+commit;
diff --git a/api/_lib/migrations/20260617210000_skill_usage_logs.sql b/api/_lib/migrations/20260617210000_skill_usage_logs.sql
new file mode 100644
index 000000000..1f9289fc7
--- /dev/null
+++ b/api/_lib/migrations/20260617210000_skill_usage_logs.sql
@@ -0,0 +1,22 @@
+-- Skill usage telemetry: every paid skill execution is logged here.
+-- Used by /api/creators/skill-analytics to surface usage metrics to creators.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260617210000_skill_usage_logs.sql
+-- Idempotent.
+
+begin;
+
+create table if not exists skill_usage_logs (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid references users(id) on delete set null,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ skill_name text not null,
+ status text not null default 'success'
+ check (status in ('success', 'failure')),
+ execution_time_ms integer,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists idx_skill_usage_agent on skill_usage_logs(agent_id, created_at desc);
+create index if not exists idx_skill_usage_skill on skill_usage_logs(agent_id, skill_name, created_at desc);
+
+commit;
diff --git a/api/_lib/migrations/20260617220000_skill_pricing_rules.sql b/api/_lib/migrations/20260617220000_skill_pricing_rules.sql
new file mode 100644
index 000000000..20e1b55e4
--- /dev/null
+++ b/api/_lib/migrations/20260617220000_skill_pricing_rules.sql
@@ -0,0 +1,34 @@
+-- Dynamic pricing rules: creators can define rules that automatically adjust
+-- the price of a skill based on demand or time.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260617220000_skill_pricing_rules.sql
+-- Idempotent.
+
+begin;
+
+-- Rules are evaluated in ascending priority order. First matching rule wins.
+create table if not exists skill_pricing_rules (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ skill_name text not null,
+ rule_type text not null
+ check (rule_type in ('first_n_purchases', 'after_n_purchases', 'time_window')),
+ -- For first_n_purchases: discount price for first N buyers (threshold = N).
+ -- For after_n_purchases: price increases after N total sales.
+ -- For time_window: discount only applies between start_at and end_at.
+ threshold integer, -- first_n / after_n count
+ price_amount bigint not null, -- price in currency atomic units when rule applies
+ currency_mint text not null,
+ chain text not null default 'solana',
+ start_at timestamptz, -- time_window: rule active from
+ end_at timestamptz, -- time_window: rule active until
+ priority integer not null default 0,
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists idx_pricing_rules_skill
+ on skill_pricing_rules(agent_id, skill_name)
+ where is_active;
+
+commit;
diff --git a/api/_lib/migrations/20260617230000_user_agent_subscriptions.sql b/api/_lib/migrations/20260617230000_user_agent_subscriptions.sql
new file mode 100644
index 000000000..3e67e9795
--- /dev/null
+++ b/api/_lib/migrations/20260617230000_user_agent_subscriptions.sql
@@ -0,0 +1,39 @@
+-- User subscriptions to agent skill tiers: a user pays a recurring fee for
+-- access to all of an agent's paid skills. Different from agent_subscriptions
+-- (DCA/on-chain payment schedules) — this is the skill-access gate.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260617230000_user_agent_subscriptions.sql
+-- Idempotent.
+
+begin;
+
+-- Subscription pricing configured by the creator on their agent.
+alter table agent_identities
+ add column if not exists subscription_amount bigint,
+ add column if not exists subscription_interval text default 'month',
+ add column if not exists subscription_currency_mint text;
+
+-- Per-user active subscriptions to an agent.
+create table if not exists user_agent_subscriptions (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ status text not null default 'active'
+ check (status in ('active', 'cancelled', 'past_due', 'expired')),
+ current_period_ends_at timestamptz not null,
+ tx_signature text,
+ price_amount bigint not null,
+ currency_mint text not null,
+ chain text not null default 'solana',
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ cancelled_at timestamptz,
+ unique (user_id, agent_id)
+);
+
+create index if not exists idx_user_agent_subs_user on user_agent_subscriptions(user_id);
+create index if not exists idx_user_agent_subs_agent on user_agent_subscriptions(agent_id);
+create index if not exists idx_user_agent_subs_active
+ on user_agent_subscriptions(user_id, agent_id)
+ where status = 'active';
+
+commit;
diff --git a/api/_lib/skill-access.js b/api/_lib/skill-access.js
index 4498bd518..6cefac120 100644
--- a/api/_lib/skill-access.js
+++ b/api/_lib/skill-access.js
@@ -22,6 +22,17 @@ export async function hasSkillAccess(userId, agentId, skill) {
if (!userId) return { paid: true, owned: false, price, reason: 'not_purchased' };
+ // Agent-level subscription grants access to all paid skills on this agent.
+ const [activeSub] = await sql`
+ SELECT id FROM user_agent_subscriptions
+ WHERE user_id = ${userId}
+ AND agent_id = ${agentId}
+ AND status = 'active'
+ AND current_period_ends_at > now()
+ LIMIT 1
+ `.catch(() => []);
+ if (activeSub) return { paid: true, owned: true, price, via_subscription: true };
+
const [purchase] = await sql`
SELECT status, valid_until, trial_remaining
FROM skill_purchases
@@ -67,3 +78,12 @@ export async function consumeTrialUse(userId, agentId, skill) {
`;
return row?.trial_remaining ?? null;
}
+
+// Fire-and-forget usage log. Never awaited on the hot path — failures are
+// swallowed so they cannot impact the caller's response latency or error state.
+export function logSkillUsage({ userId, agentId, skillName, status = 'success', executionTimeMs = null }) {
+ sql`
+ INSERT INTO skill_usage_logs (user_id, agent_id, skill_name, status, execution_time_ms)
+ VALUES (${userId ?? null}, ${agentId}, ${skillName}, ${status}, ${executionTimeMs})
+ `.catch((err) => console.error('[skill-usage-log]', err?.message));
+}
diff --git a/api/_lib/skill-price-cache.js b/api/_lib/skill-price-cache.js
new file mode 100644
index 000000000..7411717fe
--- /dev/null
+++ b/api/_lib/skill-price-cache.js
@@ -0,0 +1,65 @@
+// In-memory cache for agent skill prices.
+//
+// Skill prices are read on every purchase flow, agent embed load, and
+// marketplace detail fetch. They change infrequently (creator-initiated
+// updates), so caching them for a short window cuts DB round-trips without
+// ever serving stale prices for meaningful durations.
+//
+// TTL: 2 minutes per agent. Writes (set-price, bulk-pricing) must call
+// invalidateSkillPriceCache(agentId) so the next read reflects the update.
+//
+// Vercel serverless: each function instance has its own heap, so cache
+// entries only persist for the lifetime of that warm instance. There is no
+// cross-instance coordination — an update invalidates the local instance's
+// entry only. In the worst case a stale instance serves old prices for up
+// to TTL seconds. This is acceptable: prices don't change mid-purchase (the
+// purchase flow persists the quoted price on the skill_purchases row at
+// create time and confirms against that snapshot, not the live price).
+
+import { sql } from './db.js';
+
+const CACHE_TTL_MS = 2 * 60 * 1000; // 2 minutes
+
+const _cache = new Map(); // agentId → { rows, ts }
+
+/**
+ * Fetch active skill prices for an agent, using the cache.
+ * @param {string} agentId
+ * @returns {Promise<Array<{ skill, amount, currency_mint, chain, mint_decimals,
+ * trial_uses, time_pass_hours, time_pass_amount }>>}
+ */
+export async function getSkillPrices(agentId) {
+ const cached = _cache.get(agentId);
+ if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {
+ return cached.rows;
+ }
+ const rows = await sql`
+ SELECT skill, amount, currency_mint, chain, mint_decimals,
+ trial_uses, time_pass_hours, time_pass_amount
+ FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND is_active = true
+ `;
+ _cache.set(agentId, { rows, ts: Date.now() });
+ return rows;
+}
+
+/**
+ * Invalidate the cached prices for an agent. Call after any write to
+ * agent_skill_prices for this agent.
+ * @param {string} agentId
+ */
+export function invalidateSkillPriceCache(agentId) {
+ _cache.delete(agentId);
+}
+
+/**
+ * Fetch ONE active price row for (agentId, skill). Uses the agent's full
+ * price cache so a warm agent hit only costs a Map lookup.
+ * @param {string} agentId
+ * @param {string} skill
+ * @returns {Promise<object|null>}
+ */
+export async function getSkillPrice(agentId, skill) {
+ const rows = await getSkillPrices(agentId);
+ return rows.find((r) => r.skill === skill) ?? null;
+}
diff --git a/api/_lib/skill-pricing-rules.js b/api/_lib/skill-pricing-rules.js
new file mode 100644
index 000000000..dae7fda8f
--- /dev/null
+++ b/api/_lib/skill-pricing-rules.js
@@ -0,0 +1,71 @@
+// Dynamic pricing rules engine.
+//
+// Rules are evaluated in ascending priority order. First matching rule wins.
+// If no rule matches, falls back to the base price from agent_skill_prices.
+//
+// Rule types:
+// first_n_purchases — discounted price for the first N confirmed purchases
+// after_n_purchases — higher price once N total confirmed purchases exist
+// time_window — price applies only between start_at and end_at
+
+import { sql } from './db.js';
+
+/**
+ * Resolve the effective price for a skill, taking any active dynamic pricing
+ * rules into account.
+ *
+ * Returns null when the skill has no base price (free).
+ * Returns { amount, currency_mint, chain } with the applicable price.
+ */
+export async function resolveSkillPrice(agentId, skillName) {
+ // Base price — always need this to know currency_mint / chain.
+ const [base] = await sql`
+ SELECT amount, currency_mint, chain
+ FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true
+ `;
+ if (!base) return null; // skill is free
+
+ // Active rules sorted by priority asc (lowest number = highest priority).
+ const rules = await sql`
+ SELECT rule_type, threshold, price_amount, start_at, end_at
+ FROM skill_pricing_rules
+ WHERE agent_id = ${agentId}
+ AND skill_name = ${skillName}
+ AND is_active = true
+ ORDER BY priority ASC, created_at ASC
+ `;
+
+ if (!rules.length) return base;
+
+ // Current confirmed sale count for this skill.
+ const [{ count }] = await sql`
+ SELECT COUNT(*)::int AS count
+ FROM skill_purchases
+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND status = 'confirmed'
+ `;
+ const saleCount = count;
+
+ const now = new Date();
+
+ for (const rule of rules) {
+ if (rule.rule_type === 'first_n_purchases') {
+ if (saleCount < rule.threshold) {
+ return { amount: rule.price_amount, currency_mint: base.currency_mint, chain: base.chain };
+ }
+ } else if (rule.rule_type === 'after_n_purchases') {
+ if (saleCount >= rule.threshold) {
+ return { amount: rule.price_amount, currency_mint: base.currency_mint, chain: base.chain };
+ }
+ } else if (rule.rule_type === 'time_window') {
+ const start = rule.start_at ? new Date(rule.start_at) : null;
+ const end = rule.end_at ? new Date(rule.end_at) : null;
+ const inWindow = (!start || now >= start) && (!end || now <= end);
+ if (inWindow) {
+ return { amount: rule.price_amount, currency_mint: base.currency_mint, chain: base.chain };
+ }
+ }
+ }
+
+ return base;
+}
diff --git a/api/agents/[id]/skill-access.js b/api/agents/[id]/skill-access.js
index 4bd9dc3ee..b9a6e73e2 100644
--- a/api/agents/[id]/skill-access.js
+++ b/api/agents/[id]/skill-access.js
@@ -21,6 +21,7 @@ import { sql } from '../../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';
import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';
import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { getSkillPrices } from '../../_lib/skill-price-cache.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -51,11 +52,7 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req).catch(() => null);
const [priceRows, purchasedRows] = await Promise.all([
- sql`
- SELECT skill, currency_mint, chain, amount, mint_decimals, trial_uses, time_pass_hours, time_pass_amount
- FROM agent_skill_prices
- WHERE agent_id = ${id} AND is_active = true
- `,
+ getSkillPrices(id),
auth
? sql`
SELECT skill FROM skill_purchases
diff --git a/api/agents/[id]/tiers.js b/api/agents/[id]/tiers.js
new file mode 100644
index 000000000..d974c42a1
--- /dev/null
+++ b/api/agents/[id]/tiers.js
@@ -0,0 +1,191 @@
+/**
+ * Agent-scoped subscription tier management.
+ *
+ * Routes (vercel.json rewrites map /api/agents/:id/tiers → this file):
+ * GET /api/agents/:id/tiers list active tiers for agent (public)
+ * POST /api/agents/:id/tiers create tier (auth, agent owner)
+ * PATCH /api/agents/:id/tiers/:tierId update tier (auth, agent owner)
+ * DELETE /api/agents/:id/tiers/:tierId deactivate tier (auth, agent owner)
+ *
+ * Tiers are stored in the `subscription_plans` table scoped by agent_id.
+ * The creator_id on each plan must match the authenticated user.
+ */
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const createSchema = z.object({
+ name: z.string().trim().min(2).max(80),
+ price_usd: z.number().min(0.99).max(999),
+ interval: z.enum(['weekly', 'monthly']).default('monthly'),
+ perks: z.array(z.string().trim().max(120)).max(10).default([]),
+});
+
+const patchSchema = z.object({
+ name: z.string().trim().min(2).max(80).optional(),
+ price_usd: z.number().min(0.99).max(999).optional(),
+ interval: z.enum(['weekly', 'monthly']).optional(),
+ perks: z.array(z.string().trim().max(120)).max(10).optional(),
+ active: z.boolean().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
+
+ const url = new URL(req.url, 'http://x');
+ // Path: /api/agents/:agentId/tiers or /api/agents/:agentId/tiers/:tierId
+ const parts = url.pathname.split('/').filter(Boolean);
+ // parts: ['api', 'agents', agentId, 'tiers', tierId?]
+ const agentId = url.searchParams.get('id') || parts[2] || null;
+ const tierId = url.searchParams.get('tier_id') || parts[4] || null;
+
+ if (!agentId || !UUID_RE.test(agentId)) return error(res, 400, 'validation_error', 'valid agent id required');
+
+ if (req.method === 'GET') return handleList(req, res, agentId);
+ if (req.method === 'POST' && !tierId) return handleCreate(req, res, agentId);
+ if (req.method === 'PATCH' && tierId) return handlePatch(req, res, agentId, tierId);
+ if (req.method === 'DELETE' && tierId) return handleDelete(req, res, agentId, tierId);
+
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+});
+
+// ── Ownership check ─────────────────────────────────────────────────────────
+
+async function requireAgentOwner(req, res, agentId) {
+ const user = await getSessionUser(req);
+ if (!user) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+ const [agent] = await sql`
+ SELECT user_id FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL
+ `;
+ if (!agent) { error(res, 403, 'forbidden', 'agent not found or not owned by you'); return null; }
+ return user;
+}
+
+// ── List ─────────────────────────────────────────────────────────────────────
+
+async function handleList(req, res, agentId) {
+ const ip = clientIp(req);
+ const rl = await limits.publicIp(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const rows = await sql`
+ SELECT id, name, price_usd, interval, perks, active, created_at
+ FROM subscription_plans
+ WHERE agent_id = ${agentId} AND active = true
+ ORDER BY price_usd ASC
+ `;
+ return json(res, 200, { tiers: rows });
+}
+
+// ── Create ────────────────────────────────────────────────────────────────────
+
+async function handleCreate(req, res, agentId) {
+ if (!method(req, res, ['POST'])) return;
+ const user = await requireAgentOwner(req, res, agentId);
+ if (!user) return;
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.publicIp(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(createSchema, await readJson(req));
+
+ // 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');
+
+ const [tier] = await sql`
+ INSERT INTO subscription_plans
+ (creator_id, agent_id, name, price_usd, interval, perks)
+ VALUES
+ (${user.id}, ${agentId}, ${body.name}, ${body.price_usd}, ${body.interval}, ${body.perks})
+ RETURNING id, name, price_usd, interval, perks, active, created_at
+ `;
+ return json(res, 201, { tier });
+}
+
+// ── Update ────────────────────────────────────────────────────────────────────
+
+async function handlePatch(req, res, agentId, tierId) {
+ if (!method(req, res, ['PATCH'])) return;
+ const user = await requireAgentOwner(req, res, agentId);
+ if (!user) return;
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const body = parse(patchSchema, await readJson(req));
+
+ const [existing] = await sql`
+ SELECT id FROM subscription_plans
+ WHERE id = ${tierId} AND agent_id = ${agentId} AND creator_id = ${user.id}
+ `;
+ if (!existing) return error(res, 404, 'not_found', 'tier not found');
+
+ const setFrags = [];
+ const params = [];
+ if (body.name !== undefined) { params.push(body.name); setFrags.push(`name = $${params.length}`); }
+ if (body.price_usd !== undefined) { 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.active !== undefined) { params.push(body.active); setFrags.push(`active = $${params.length}`); }
+ if (setFrags.length === 0) return error(res, 400, 'validation_error', 'nothing to update');
+
+ params.push(tierId); const tidIdx = params.length;
+ params.push(user.id); const uidIdx = params.length;
+
+ const [tier] = await sql(
+ `UPDATE subscription_plans SET ${setFrags.join(', ')}
+ WHERE id = $${tidIdx} AND creator_id = $${uidIdx}
+ RETURNING id, name, price_usd, interval, perks, active, created_at`,
+ params,
+ );
+ return json(res, 200, { tier });
+}
+
+// ── Delete (soft) ─────────────────────────────────────────────────────────────
+
+async function handleDelete(req, res, agentId, tierId) {
+ if (!method(req, res, ['DELETE'])) return;
+ const user = await requireAgentOwner(req, res, agentId);
+ if (!user) return;
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ // Check for active subscribers before deactivating.
+ const [{ count: subCount }] = await sql`
+ SELECT count(*)::int AS count FROM creator_subscriptions cs
+ JOIN subscription_plans sp ON sp.id = cs.plan_id
+ WHERE sp.id = ${tierId} AND sp.agent_id = ${agentId}
+ AND cs.status = 'active'
+ `;
+
+ // Soft-delete (mark inactive) regardless — active subscribers keep access
+ // until their period ends; we just stop accepting new sign-ups.
+ const [tier] = await sql`
+ UPDATE subscription_plans SET active = false
+ WHERE id = ${tierId} AND agent_id = ${agentId} AND creator_id = ${user.id}
+ RETURNING id
+ `;
+ if (!tier) return error(res, 404, 'not_found', 'tier not found');
+
+ return json(res, 200, {
+ ok: true,
+ active_subscribers: subCount,
+ message: subCount > 0
+ ? `Plan deactivated — ${subCount} subscriber(s) will keep access until their period ends.`
+ : 'Plan deactivated.',
+ });
+}
diff --git a/pages/collection.html b/pages/collection.html
new file mode 100644
index 000000000..218a178f1
--- /dev/null
+++ b/pages/collection.html
@@ -0,0 +1,169 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>My Collection · three.ws</title>
+ <meta name="description" content="View all the skills and subscriptions you've unlocked on three.ws." />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ --bg: #0d0d0d;
+ --bg-2: #141414;
+ --card: #181818;
+ --line: rgba(255,255,255,0.07);
+ --line-2: rgba(255,255,255,0.12);
+ --text: #e7e9ee;
+ --muted: rgba(231,233,238,0.55);
+ --dim: rgba(231,233,238,0.35);
+ --green: #4ade80;
+ --amber: #f5a524;
+ --violet: #a78bfa;
+ --radius: 12px;
+ --skeleton-base: rgba(255,255,255,0.04);
+ --skeleton-sheen: rgba(255,255,255,0.08);
+ }
+ [data-theme="light"] {
+ --bg: #f5f5f5;
+ --bg-2: #ffffff;
+ --card: #ffffff;
+ --line: rgba(0,0,0,0.07);
+ --line-2: rgba(0,0,0,0.12);
+ --text: #111;
+ --muted: rgba(0,0,0,0.55);
+ --dim: rgba(0,0,0,0.35);
+ --skeleton-base: rgba(0,0,0,0.04);
+ --skeleton-sheen: rgba(0,0,0,0.08);
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;text-decoration:none;}
+ .page-shell{max-width:1100px;margin:0 auto;padding:0 20px 80px;}
+ .page-hero{padding:48px 0 32px;}
+ .page-hero h1{font-size:28px;font-weight:700;letter-spacing:-0.02em;}
+ .page-hero p{color:var(--muted);margin-top:8px;font-size:14px;}
+ /* Tabs */
+ .col-tabs{display:flex;gap:4px;border-bottom:1px solid var(--line-2);margin-bottom:32px;}
+ .col-tab{padding:10px 18px;font-size:13px;font-weight:500;color:var(--muted);cursor:pointer;border-bottom:2px solid transparent;transition:color .15s,border-color .15s;background:none;border-top:none;border-left:none;border-right:none;}
+ .col-tab:hover{color:var(--text);}
+ .col-tab.active{color:var(--text);border-bottom-color:var(--text);}
+ /* Grid */
+ .col-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:16px;}
+ /* Card */
+ .col-card{background:var(--card);border:1px solid var(--line-2);border-radius:var(--radius);padding:18px;display:flex;flex-direction:column;gap:12px;transition:border-color .15s;}
+ .col-card:hover{border-color:rgba(255,255,255,0.2);}
+ [data-theme="light"] .col-card:hover{border-color:rgba(0,0,0,0.2);}
+ .col-card-header{display:flex;gap:12px;align-items:center;}
+ .col-card-avatar{width:44px;height:44px;border-radius:50%;background:var(--bg-2);border:1px solid var(--line);object-fit:cover;flex-shrink:0;}
+ .col-card-avatar.placeholder{display:flex;align-items:center;justify-content:center;font-size:18px;color:var(--muted);}
+ .col-card-meta{flex:1;min-width:0;}
+ .col-card-skill{font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
+ .col-card-agent{font-size:12px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px;}
+ .col-card-badges{display:flex;gap:6px;flex-wrap:wrap;}
+ .badge{display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:500;padding:3px 8px;border-radius:20px;border:1px solid;}
+ .badge-green{color:var(--green);border-color:rgba(74,222,128,.25);background:rgba(74,222,128,.08);}
+ .badge-amber{color:var(--amber);border-color:rgba(245,165,36,.25);background:rgba(245,165,36,.08);}
+ .badge-violet{color:var(--violet);border-color:rgba(167,139,250,.25);background:rgba(167,139,250,.08);}
+ .badge-muted{color:var(--muted);border-color:var(--line-2);background:var(--bg-2);}
+ .col-card-footer{display:flex;align-items:center;justify-content:space-between;margin-top:4px;}
+ .col-card-date{font-size:11px;color:var(--dim);}
+ .col-card-nft{font-size:11px;color:var(--muted);}
+ .col-card-nft a{color:var(--violet);text-decoration:underline;text-underline-offset:2px;}
+ .col-cta{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:500;padding:6px 12px;border-radius:8px;background:#fff;color:#000;border:none;cursor:pointer;transition:opacity .15s;text-decoration:none;}
+ .col-cta:hover{opacity:.85;}
+ /* Skeleton */
+ .skeleton{background:var(--skeleton-base);background-image:linear-gradient(90deg,var(--skeleton-base) 0%,var(--skeleton-sheen) 50%,var(--skeleton-base) 100%);background-size:200% 100%;border-radius:6px;animation:shimmer 1.4s ease-in-out infinite;}
+ @keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}
+ .skeleton-card{background:var(--card);border:1px solid var(--line-2);border-radius:var(--radius);padding:18px;display:flex;flex-direction:column;gap:12px;}
+ .skeleton-row{height:14px;border-radius:4px;}
+ /* Empty */
+ .col-empty{text-align:center;padding:80px 20px;color:var(--muted);}
+ .col-empty svg{margin-bottom:16px;opacity:.35;}
+ .col-empty h3{font-size:18px;font-weight:600;color:var(--text);margin-bottom:8px;}
+ .col-empty p{font-size:14px;line-height:1.5;}
+ .col-empty a{color:var(--text);text-decoration:underline;text-underline-offset:3px;}
+ /* Panel */
+ .col-panel{display:none;}
+ .col-panel.active{display:block;}
+ /* Stats bar */
+ .col-stats{display:flex;gap:32px;padding:20px 0 28px;border-bottom:1px solid var(--line);margin-bottom:28px;}
+ .col-stat-val{font-size:24px;font-weight:700;letter-spacing:-0.03em;}
+ .col-stat-lbl{font-size:12px;color:var(--muted);margin-top:2px;}
+ /* Subscription expiry */
+ .col-sub-expiry{font-size:11px;}
+ .col-sub-expiry.active{color:var(--green);}
+ .col-sub-expiry.expired{color:var(--amber);}
+ /* Auth gate */
+ .col-auth-wall{text-align:center;padding:120px 20px;}
+ .col-auth-wall h2{font-size:22px;font-weight:700;margin-bottom:12px;}
+ .col-auth-wall p{color:var(--muted);font-size:14px;margin-bottom:24px;}
+ /* Error */
+ .col-error{background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.25);border-radius:10px;padding:16px 20px;color:#ef4444;font-size:13px;margin-bottom:24px;}
+ @media(max-width:600px){
+ .col-grid{grid-template-columns:1fr;}
+ .col-stats{gap:20px;flex-wrap:wrap;}
+ }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="page-shell">
+ <div class="page-hero">
+ <h1>My Collection</h1>
+ <p>Skills and subscriptions you've unlocked across three.ws agents.</p>
+ </div>
+
+ <div id="col-auth-wall" class="col-auth-wall" hidden>
+ <h2>Sign in to view your collection</h2>
+ <p>Your purchased skills and active subscriptions live here.</p>
+ <a href="/login?next=/collection" class="col-cta">Sign in</a>
+ </div>
+
+ <div id="col-error" class="col-error" hidden></div>
+
+ <div id="col-stats" class="col-stats" hidden>
+ <div>
+ <div class="col-stat-val" id="stat-skills">—</div>
+ <div class="col-stat-lbl">Owned skills</div>
+ </div>
+ <div>
+ <div class="col-stat-val" id="stat-subs">—</div>
+ <div class="col-stat-lbl">Active subscriptions</div>
+ </div>
+ <div>
+ <div class="col-stat-val" id="stat-nfts">—</div>
+ <div class="col-stat-lbl">NFT receipts</div>
+ </div>
+ </div>
+
+ <div id="col-main" hidden>
+ <div class="col-tabs" role="tablist">
+ <button class="col-tab active" role="tab" aria-selected="true" data-panel="skills">Skills</button>
+ <button class="col-tab" role="tab" aria-selected="false" data-panel="subscriptions">Subscriptions</button>
+ </div>
+
+ <div id="panel-skills" class="col-panel active" role="tabpanel">
+ <div id="skills-grid" class="col-grid"></div>
+ </div>
+ <div id="panel-subscriptions" class="col-panel" role="tabpanel">
+ <div id="subs-grid" class="col-grid"></div>
+ </div>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/collection.js"></script>
+ </body>
+</html>
diff --git a/public/gallery/gallery.js b/public/gallery/gallery.js
index 5c7c82e56..5c86972d8 100644
--- a/public/gallery/gallery.js
+++ b/public/gallery/gallery.js
@@ -348,6 +348,7 @@ function renderCard(a) {
const viewerUrl = glbUrl ? `/app#model=${encodeURIComponent(glbUrl)}` : '#';
const detailUrl = `/avatars/${a.id}`;
const studioUrl = `/studio?avatar=${encodeURIComponent(a.id)}`;
+ const animateUrl = `/pose?avatar=${encodeURIComponent(a.id)}`;
const thumbSrc = a.thumbnail_url || `/api/avatars/${encodeURIComponent(a.id)}/og`;
const altText = a.alt_text || a.name || 'Avatar';
@@ -411,7 +412,8 @@ function renderCard(a) {
data-glb-url="${escapeAttr(glbUrl)}"
data-name="${escapeAttr(a.name || 'Accessory')}"
data-thumb="${escapeAttr(a.thumbnail_url || '')}">Equip</button>`
- : `<a class="gallery-card-btn gallery-card-btn--primary" href="${escapeAttr(studioUrl)}" title="Use in Widget Studio">Use</a>`
+ : `<a class="gallery-card-btn gallery-card-btn--primary" href="${escapeAttr(studioUrl)}" title="Use in Widget Studio">Use</a>
+ <a class="gallery-card-btn gallery-card-btn--ghost" href="${escapeAttr(animateUrl)}" title="Animate this avatar in the Animation Studio">Animate</a>`
}
</div>
</div>
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 8c0458796..5a452ca0c 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1144,12 +1144,7 @@ $('plan-save-btn')?.addEventListener('click', async () => {
}
});
-// Load plans when monetization tab is first activated
-document.addEventListener('tabchange', (e) => {
- if (e.detail?.tab === 'monetization' && !plansLoaded) loadSubscriptionPlans();
-});
-// Also load on init if already on monetization tab
-if (!document.querySelector('#panel-monetization[hidden]')) loadSubscriptionPlans();
+// Plans are loaded lazily via TAB_LOADERS['monetization'] when the tab activates.
// ─────────────────────────────────────────────────────────────────────────────
// Voice tab
@@ -2566,6 +2561,7 @@ const TAB_LOADERS = {
embed: ensureEmbedTab,
widgets: ensureWidgetsTab,
studio: ensureStudioTab,
+ monetization: () => { if (!plansLoaded) loadSubscriptionPlans(); },
};
function activateTab(tabId) {
diff --git a/vercel.json b/vercel.json
index 48d97acf0..ee1e2e380 100644
--- a/vercel.json
+++ b/vercel.json
@@ -456,6 +456,14 @@
"src": "/api/agents/([^/]+)/skill-access",
"dest": "/api/agents/[id]/skill-access?id=$1"
},
+ {
+ "src": "/api/agents/([^/]+)/tiers/([^/]+)",
+ "dest": "/api/agents/[id]/tiers?id=$1&tier_id=$2"
+ },
+ {
+ "src": "/api/agents/([^/]+)/tiers",
+ "dest": "/api/agents/[id]/tiers?id=$1"
+ },
{
"src": "/api/billing/receipts",
"dest": "/api/billing/receipts"
@@ -2559,6 +2567,10 @@
"src": "/widgets/(.*)",
"dest": "/widgets-gallery/$1"
},
+ {
+ "src": "/animations/?",
+ "dest": "/animations.html"
+ },
{
"src": "/gallery",
"dest": "/gallery/index.html"
diff --git a/vite.config.js b/vite.config.js
index 0b2b9be42..30d0c07e2 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -393,6 +393,7 @@ const appConfig = {
'play-arena': resolve(__dirname, 'pages/play/arena.html'),
'smart-money': resolve(__dirname, 'pages/smart-money.html'),
pose: resolve(__dirname, 'pages/pose.html'),
+ animations: resolve(__dirname, 'pages/animations.html'),
club: resolve(__dirname, 'pages/club.html'),
skills: resolve(__dirname, 'pages/skills.html'),
'agenc-embodied': resolve(__dirname, 'pages/agenc/embodied.html'),