Skip to content

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

feat(bundles): price a bundle from the seller's own ledger, not a rule of thumb

nirholasae51c09a3685
diff --git a/api/_lib/bundle-pricing.js b/api/_lib/bundle-pricing.js
new file mode 100644
index 000000000..b1f659147
--- /dev/null
+++ b/api/_lib/bundle-pricing.js
@@ -0,0 +1,97 @@
+/**
+ * Bundle pricing math, as pure functions.
+ *
+ * "What should I charge for this bundle?" is the question that stops a seller
+ * from ever publishing one. The usual answer is a percentage off the sum of the
+ * parts, which is a guess dressed as advice. A better answer is already sitting
+ * in the agent's own ledger: some buyers bought two or three of these skills
+ * separately, and what they actually paid is real evidence of what the
+ * combination is worth to the population that would buy it.
+ *
+ * These functions take that history and a candidate price and answer two things
+ * a seller can act on: what the bundle would have collected from the same people,
+ * and how many of them would have come out ahead. Kept separate from the handler
+ * so the arithmetic is testable without a database, which matters because the
+ * evidence path cannot be exercised against production yet: the marketplace has
+ * no multi-skill basket at all, precisely because bundles were unreachable.
+ *
+ * Amounts are ATOMIC integers throughout (the currency's smallest unit). Mixing
+ * atomic and whole-token numbers is the classic way to publish a price 10^6 off,
+ * so nothing here ever divides by decimals; formatting is the caller's job.
+ */
+
+/** Discount below this reads as a rounding artifact rather than an offer. */
+export const MIN_MEANINGFUL_DISCOUNT_PERCENT = 1;
+
+/** Fallback discount when there is no history to learn from. */
+export const DEFAULT_DISCOUNT = 0.8;
+
+/**
+ * Median of an integer list, rounded to an integer so it stays a spendable price.
+ * @param {number[]} sorted ascending
+ * @returns {number|null} null for an empty list
+ */
+export function median(sorted) {
+ const n = sorted.length;
+ if (!n) return null;
+ if (n % 2) return sorted[(n - 1) / 2];
+ return Math.round((sorted[n / 2 - 1] + sorted[n / 2]) / 2);
+}
+
+/**
+ * Backtest one candidate price against the real baskets.
+ *
+ * @param {number} price candidate bundle price, atomic
+ * @param {number} sumOfParts list price of every bundled skill added up, atomic
+ * @param {number[]} basketTotals what each multi-skill buyer actually paid, atomic
+ * @returns {{price:number, discount_atomic:number, discount_percent:number,
+ * backtest_revenue_atomic:string, revenue_delta_atomic:string, buyers_better_off:number}}
+ */
+export function simulatePrice(price, sumOfParts, basketTotals) {
+ const historicalRevenue = basketTotals.reduce((sum, n) => sum + n, 0);
+ const bundleRevenue = price * basketTotals.length;
+ return {
+ price,
+ discount_atomic: sumOfParts - price,
+ // One decimal place: a seller reads "17.5% off", not "17.4832%".
+ discount_percent: sumOfParts ? Math.round(((sumOfParts - price) / sumOfParts) * 1000) / 10 : 0,
+ // Amounts cross the wire as strings. These are atomic token amounts and can
+ // exceed Number.MAX_SAFE_INTEGER on a 9-decimal mint, where JSON parsing
+ // would silently round the seller's revenue.
+ backtest_revenue_atomic: String(bundleRevenue),
+ revenue_delta_atomic: String(bundleRevenue - historicalRevenue),
+ // Buyers who spent MORE than this price buying the skills piecemeal: the
+ // ones the bundle would have won on value, and the likeliest converts.
+ buyers_better_off: basketTotals.filter((total) => total > price).length,
+ };
+}
+
+/**
+ * Suggest a price, and say what the suggestion is based on.
+ *
+ * With real multi-skill history, anchor on the median basket: a price that
+ * population has already demonstrated it will pay. Without it there is nothing to
+ * learn from, so fall back to a flat discount off list and label the basis
+ * `discount_off_list`, so a seller with no sales is never shown a default dressed
+ * up as a finding.
+ *
+ * The median is capped at the sum of the parts. A bundle costing more than buying
+ * the same skills one at a time is not a bundle.
+ *
+ * @param {number} sumOfParts atomic
+ * @param {number[]} basketTotals atomic, any order
+ * @returns {{price:number, basis:'median_basket'|'discount_off_list', median_basket:number|null}}
+ */
+export function suggestPrice(sumOfParts, basketTotals) {
+ const sorted = [...basketTotals].sort((a, b) => a - b);
+ const medianBasket = median(sorted);
+ if (medianBasket !== null) {
+ return { price: Math.min(medianBasket, sumOfParts), basis: 'median_basket', median_basket: medianBasket };
+ }
+ // Never suggest 0: a free bundle is a giveaway, not a price.
+ return {
+ price: Math.max(1, Math.round(sumOfParts * DEFAULT_DISCOUNT)),
+ basis: 'discount_off_list',
+ median_basket: null,
+ };
+}
diff --git a/api/agents/[id]/bundles.js b/api/agents/[id]/bundles.js
index b62957908..5c38597f0 100644
--- a/api/agents/[id]/bundles.js
+++ b/api/agents/[id]/bundles.js
@@ -23,6 +23,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { isUuid } from '../../_lib/validate.js';
import { MARKET_PAID_KINDS } from '../../_lib/marketplace-kinds.js';
+import { simulatePrice, suggestPrice } from '../../_lib/bundle-pricing.js';
const createSchema = z.object({
name: z.string().trim().min(2).max(80),
@@ -52,6 +53,8 @@ export default wrap(async (req, res) => {
if (!agentId || !isUuid(agentId))
return error(res, 400, 'validation_error', 'valid agent id required');
+ if (req.method === 'GET' && url.searchParams.get('action') === 'pricing')
+ return handlePricing(req, res, agentId, url);
if (req.method === 'GET') return handleList(req, res, agentId);
if (req.method === 'POST' && !bundleId) return handleCreate(req, res, agentId);
if (req.method === 'PATCH' && bundleId) return handlePatch(req, res, agentId, bundleId);
@@ -89,6 +92,136 @@ async function handleList(req, res, agentId) {
return json(res, 200, { data: { bundles } });
}
+// ── GET pricing simulation ──────────────────────────────────────────────────
+//
+// "What should I charge for this bundle?" is the question that stops a seller
+// from publishing one, and the honest answer is not a percentage off the sum of
+// the parts. It is in the agent's own ledger: some buyers already bought two or
+// three of these skills separately, and what they paid is the only real evidence
+// of what the combination is worth.
+//
+// So this endpoint backtests a candidate price against actual history. It finds
+// every buyer who purchased 2+ of the chosen skills, sums what each of them
+// really paid, and reports what the bundle would have collected from those same
+// people instead. A seller sees revenue delta and buyer count from their own
+// sales rather than a guess, and a bundle priced above the historical basket is
+// shown as the revenue loss it would have been.
+//
+// Public on purpose: it reads only aggregate counts and the agent's own list
+// prices, both of which the marketplace already publishes per skill. No buyer
+// identity, and no row-level history, leaves this handler.
+
+const MAX_SIMULATED_SKILLS = 50;
+
+async function handlePricing(req, res, agentId, url) {
+ if (!method(req, res, ['GET'])) return;
+
+ const skills = [...new Set(
+ (url.searchParams.get('skills') || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean),
+ )];
+ if (skills.length < 2)
+ return error(res, 400, 'validation_error', 'skills must name at least 2 skills, comma separated');
+ if (skills.length > MAX_SIMULATED_SKILLS)
+ return error(res, 400, 'validation_error', `at most ${MAX_SIMULATED_SKILLS} skills can be simulated at once`);
+
+ const rawPrice = url.searchParams.get('price');
+ const askedPrice = rawPrice == null || rawPrice === '' ? null : Number(rawPrice);
+ if (askedPrice !== null && (!Number.isInteger(askedPrice) || askedPrice < 1))
+ return error(res, 400, 'validation_error', 'price must be a positive integer in atomic units');
+
+ // Per-skill list price and real sales. Money and buyer counts filter to paid
+ // kinds, matching the definition /pulse publishes, so a trial or an access row
+ // from an earlier bundle can never inflate what a seller sees here.
+ const paid = sql`sp.status = 'confirmed' AND sp.kind = ANY(${MARKET_PAID_KINDS})`;
+ const parts = await sql`
+ SELECT p.skill,
+ MAX(p.amount) AS list_amount,
+ MAX(p.currency_mint) AS currency_mint,
+ MAX(p.chain) AS chain,
+ COUNT(*) FILTER (WHERE ${paid})::int AS units,
+ COALESCE(SUM(sp.amount) FILTER (WHERE ${paid}), 0)::text AS gross_atomic,
+ COUNT(DISTINCT sp.user_id) FILTER (WHERE ${paid})::int AS buyers
+ FROM agent_skill_prices p
+ LEFT JOIN skill_purchases sp
+ ON sp.agent_id = p.agent_id AND sp.skill = p.skill
+ WHERE p.agent_id = ${agentId} AND p.is_active = true AND p.skill = ANY(${skills})
+ GROUP BY p.skill
+ ORDER BY p.skill
+ `;
+
+ if (!parts.length)
+ return error(res, 404, 'not_found', 'none of those skills have an active price on this agent');
+
+ // A skill with no active price cannot be summed, so say which ones were left
+ // out rather than quietly pricing a smaller bundle than the seller asked for.
+ const pricedSkills = parts.map((p) => p.skill);
+ const unpricedSkills = skills.filter((s) => !pricedSkills.includes(s));
+
+ // Currency has to be uniform: adding a $THREE price to a USDC price would
+ // produce a number that means nothing.
+ const mints = [...new Set(parts.map((p) => p.currency_mint))];
+ if (mints.length > 1)
+ return error(res, 409, 'mixed_currency', `these skills are priced in ${mints.length} different currencies and cannot be bundled together`);
+
+ const sumOfParts = parts.reduce((sum, p) => sum + Number(p.list_amount), 0);
+
+ // The historical basket: buyers who took 2+ of these skills, and what each
+ // actually paid across them. This is the population a bundle would have
+ // converted, so it is the only population worth pricing against.
+ const baskets = await sql`
+ SELECT sp.user_id,
+ COUNT(DISTINCT sp.skill)::int AS skills_bought,
+ SUM(sp.amount)::text AS paid_atomic
+ FROM skill_purchases sp
+ WHERE sp.agent_id = ${agentId}
+ AND sp.skill = ANY(${pricedSkills})
+ AND ${paid}
+ GROUP BY sp.user_id
+ HAVING COUNT(DISTINCT sp.skill) >= 2
+ `;
+
+ const basketTotals = baskets.map((b) => Number(b.paid_atomic));
+ const multiBuyers = basketTotals.length;
+ const historicalRevenue = basketTotals.reduce((sum, n) => sum + n, 0);
+
+ // The arithmetic lives in api/_lib/bundle-pricing.js so it can be tested
+ // without a database. That matters here: the marketplace has no multi-skill
+ // basket at all yet, precisely because bundles were unreachable, so the
+ // evidence path has no production rows to exercise it.
+ const { price: suggested, basis, median_basket: medianBasket } = suggestPrice(sumOfParts, basketTotals);
+ const simulate = (price) => simulatePrice(price, sumOfParts, basketTotals);
+
+ return json(res, 200, {
+ data: {
+ agent_id: agentId,
+ currency_mint: mints[0],
+ chain: parts[0].chain,
+ skills: parts.map((p) => ({
+ skill: p.skill,
+ list_amount: String(p.list_amount),
+ units_sold: p.units,
+ gross_atomic: p.gross_atomic,
+ buyers: p.buyers,
+ })),
+ unpriced_skills: unpricedSkills,
+ sum_of_parts_atomic: String(sumOfParts),
+ history: {
+ multi_skill_buyers: multiBuyers,
+ revenue_atomic: String(historicalRevenue),
+ median_basket_atomic: medianBasket === null ? null : String(medianBasket),
+ // Says out loud whether the suggestion is evidence or a default, so a
+ // seller with no history is never misled into reading it as a finding.
+ basis,
+ },
+ suggested: simulate(suggested),
+ asked: askedPrice === null ? null : simulate(askedPrice),
+ },
+ });
+}
+
// ── POST create ─────────────────────────────────────────────────────────────
async function handleCreate(req, res, agentId) {
diff --git a/tests/bundle-pricing.test.js b/tests/bundle-pricing.test.js
new file mode 100644
index 000000000..20cd83438
--- /dev/null
+++ b/tests/bundle-pricing.test.js
@@ -0,0 +1,134 @@
+// Bundle pricing math.
+//
+// These are the numbers a seller reads before deciding what to charge, so a
+// wrong one costs them real revenue. They are also the numbers the marketplace
+// has no production rows to exercise: there is not a single multi-skill basket
+// on the platform yet, precisely because bundles were unreachable until the
+// routing fix. So the evidence path is pinned here rather than by observation.
+//
+// The DB half is verified separately: both queries in
+// api/agents/[id]/bundles.js were run against the live schema on 2026-07-31, and
+// the basket query was proved to exclude trial and bundle-access rows using real
+// inserts under a sentinel reference, deleted afterwards.
+
+import { describe, it, expect } from 'vitest';
+import {
+ median,
+ simulatePrice,
+ suggestPrice,
+ DEFAULT_DISCOUNT,
+} from '../api/_lib/bundle-pricing.js';
+
+describe('median', () => {
+ it('is null for no history, so callers must handle the empty case explicitly', () => {
+ expect(median([])).toBeNull();
+ });
+
+ it('takes the middle of an odd list', () => {
+ expect(median([100, 200, 900])).toBe(200);
+ });
+
+ it('averages the two middles of an even list, rounded to a spendable integer', () => {
+ // 100000 and 150000 average to 125000 exactly.
+ expect(median([100000, 150000])).toBe(125000);
+ // An odd sum must not leak a fraction into a price.
+ expect(median([100, 101])).toBe(101);
+ expect(Number.isInteger(median([100, 101]))).toBe(true);
+ });
+});
+
+describe('suggestPrice', () => {
+ it('anchors on the median basket when buyers have real history', () => {
+ // Two real baskets, measured in the rolled-back probe: one buyer took two
+ // skills for 100000, another took three for 150000.
+ const s = suggestPrice(150000, [100000, 150000]);
+ expect(s.basis).toBe('median_basket');
+ expect(s.price).toBe(125000);
+ expect(s.median_basket).toBe(125000);
+ });
+
+ it('never prices a bundle above buying the parts one at a time', () => {
+ // A population that historically overspent (repeat buys, time passes) can
+ // push the median past list. A bundle that costs more than the sum is not a
+ // bundle, so the suggestion is capped.
+ const s = suggestPrice(150000, [400000, 500000]);
+ expect(s.price).toBe(150000);
+ // The raw median is still reported, so the cap is visible rather than hidden.
+ expect(s.median_basket).toBe(450000);
+ });
+
+ it('falls back to a labelled discount when there is no history to learn from', () => {
+ const s = suggestPrice(150000, []);
+ expect(s.basis).toBe('discount_off_list');
+ expect(s.price).toBe(Math.round(150000 * DEFAULT_DISCOUNT));
+ // null, not 0: a seller must be able to tell "no evidence" from "median 0".
+ expect(s.median_basket).toBeNull();
+ });
+
+ it('never suggests a free bundle', () => {
+ // Rounding a tiny sum toward zero would publish a giveaway as a price.
+ expect(suggestPrice(1, []).price).toBe(1);
+ expect(suggestPrice(2, []).price).toBeGreaterThan(0);
+ });
+
+ it('does not mutate the caller\'s basket array', () => {
+ // The handler reuses this array for simulatePrice; an in-place sort here
+ // would reorder it underneath that call.
+ const baskets = [300, 100, 200];
+ suggestPrice(1000, baskets);
+ expect(baskets).toEqual([300, 100, 200]);
+ });
+});
+
+describe('simulatePrice', () => {
+ const baskets = [100000, 150000];
+
+ it('backtests revenue against what those buyers actually paid', () => {
+ // At 125000, two historical buyers would have paid 250000; they paid 250000.
+ const s = simulatePrice(125000, 150000, baskets);
+ expect(s.backtest_revenue_atomic).toBe('250000');
+ expect(s.revenue_delta_atomic).toBe('0');
+ });
+
+ it('reports a loss as a negative delta rather than hiding it', () => {
+ // Underpricing is the mistake a discount rule of thumb makes, so it has to
+ // be legible: at 90000 the bundle collects 180000 against 250000 actual.
+ const s = simulatePrice(90000, 150000, baskets);
+ expect(s.revenue_delta_atomic).toBe('-70000');
+ });
+
+ it('counts only the buyers who would have come out ahead', () => {
+ // At 120000 the 150000 basket wins, the 100000 basket does not.
+ expect(simulatePrice(120000, 150000, baskets).buyers_better_off).toBe(1);
+ // Strictly greater: a buyer who paid exactly the bundle price gained nothing.
+ expect(simulatePrice(100000, 150000, baskets).buyers_better_off).toBe(1);
+ expect(simulatePrice(150000, 150000, baskets).buyers_better_off).toBe(0);
+ });
+
+ it('reports the discount to one decimal place', () => {
+ const s = simulatePrice(125000, 150000, baskets);
+ expect(s.discount_atomic).toBe(25000);
+ expect(s.discount_percent).toBe(16.7);
+ });
+
+ it('returns zero revenue, not NaN, when there is no history', () => {
+ const s = simulatePrice(125000, 150000, []);
+ expect(s.backtest_revenue_atomic).toBe('0');
+ expect(s.revenue_delta_atomic).toBe('0');
+ expect(s.buyers_better_off).toBe(0);
+ });
+
+ it('does not divide by zero when nothing in the bundle has a list price', () => {
+ expect(simulatePrice(500, 0, []).discount_percent).toBe(0);
+ });
+
+ it('keeps atomic amounts as strings so a 9-decimal mint cannot lose precision', () => {
+ // 9_007_199_254_740_993 atomic units exceeds Number.MAX_SAFE_INTEGER; the
+ // value has to survive as text or JSON.parse silently rounds the seller's
+ // revenue on the way to the page.
+ const big = 9_007_199_254_740_993;
+ const s = simulatePrice(big, big, [big]);
+ expect(typeof s.backtest_revenue_atomic).toBe('string');
+ expect(typeof s.revenue_delta_atomic).toBe('string');
+ });
+});