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.

23.1 KB
Raw Blame
// Notification preference model — the single source of truth shared by the
// preference-center API, the push fan-out, and the email gating.
//
// A notification has a `type` (e.g. 'skill_purchased'). Types roll up into a
// small set of user-facing CATEGORIES. The user controls, per category, which
// CHANNELS deliver it. Channels: in_app (the bell inbox), push (Web Push),
// email (Resend transactional), telegram (per-account bot alerts), avatar (the
// corner companion walks on and says it out loud, see src/notification-herald.js).
//
// Preferences are stored sparsely in notification_preferences.prefs as
//   { categories: { sales: { push: false }, ... }, telegram_chat_id: '123' }
// Any key a user hasn't touched falls back to DEFAULTS below — so new
// categories light up without a backfill, and a user with no row at all gets
// sensible behaviour.

import { sql } from './db.js';

/** Ordered for display in the preference center. */
export const CATEGORIES = [
	{
		key: 'sales',
		label: 'Sales & earnings',
		description: 'Your launch filled, a skill or asset sold, a tip or payout arrived.',
	},
	{
		key: 'purchases',
		label: 'Your purchases',
		description: 'Receipts and confirmations for things you bought or were gifted.',
	},
	{
		key: 'social',
		label: 'Social & mentions',
		description: 'Your agent was embedded, forked, remixed, or replied to.',
	},
	{
		key: 'irl',
		label: 'In person (IRL)',
		description: 'Someone met, messaged, or paid your agent in the real world.',
	},
	{
		key: 'alerts',
		label: 'Market alerts',
		description: 'Pump.fun rules, token signals and the perps thresholds you set on your agents.',
	},
	{
		key: 'markets',
		label: 'Event markets',
		description: 'You are an entrant in an event market, with your odds and your share kit.',
	},
	{
		key: 'creations',
		label: 'Creations',
		description: 'A 3D generation you started finished (or failed) while you were away.',
	},
	{
		key: 'companion',
		label: 'Companion deliveries',
		description: 'Your 3D companion has something from your own inbox, calendar, or phone worth hearing.',
	},
	{
		key: 'knock',
		label: 'Knocks at your door',
		description: 'Someone paid your price to reach you through /knock. Your companion delivers it in person.',
	},
	{
		key: 'mail',
		label: 'Agent mail',
		description: 'An email arrived in one of your agents\' inboxes (spam is held back and never notifies).',
	},
	{
		key: 'orders',
		label: 'Orders',
		description: 'A limit, stop, trailing, ladder, OCO or DCA order on one of your agents filled, failed, or expired.',
	},
	{
		key: 'approvals',
		label: 'Approvals',
		description: 'An agent is waiting for your yes before it moves funds. Approve or deny from the notification, chat, or /approvals.',
		// A pending approval is a decision the owner owes; the bell row is the
		// one surface that always carries it, so it cannot be muted. Push, email
		// and chats stay togglable.
		lockedChannels: ['in_app'],
	},
	{
		key: 'account',
		label: 'Account & security',
		description: 'Withdrawals, payment issues, and security-sensitive events.',
		// The bell row for these is written even when the user mutes in_app: it
		// is the durable record of what happened to their account, and this
		// category is also the fallback for any type not yet in TYPE_CATEGORY,
		// so a mute here would silently hide future security events. Push,
		// email and telegram stay fully mutable, which is what "quiet" means.
		lockedChannels: ['in_app'],
	},
];

export const CHANNELS = ['in_app', 'push', 'email', 'telegram', 'discord', 'avatar'];

/**
 * Channels that always deliver for a category, regardless of preferences.
 * Single source of truth for the write path (api/_lib/notify.js), the
 * preferences API, and the settings UI, so none of them can drift into
 * showing a toggle that does nothing.
 */
export function lockedChannelsFor(categoryKey) {
	return CATEGORIES.find((c) => c.key === categoryKey)?.lockedChannels || [];
}

const CATEGORY_KEYS = new Set(CATEGORIES.map((c) => c.key));

// notification `type` → category. Unmapped types fall back to 'account' so a
// new notification type is never silently undeliverable.
const TYPE_CATEGORY = {
	skill_purchased: 'sales',
	asset_purchased: 'sales',
	sale: 'sales',
	'payment-earned': 'sales',
	payment_received: 'sales',
	referral_earned: 'sales',
	creator_payout_sent: 'sales',
	creator_payout_held: 'sales',
	creator_payout_wallet: 'account',
	referral_signup: 'sales',
	referral_reward: 'sales',
	pump_launch_filled: 'sales',
	royalty_paid: 'sales',
	// Agent commerce invoices (api/_lib/agent-commerce/invoices.js).
	invoice_paid: 'sales',
	invoice_underpaid: 'sales',
	invoice_expired: 'sales',
	// Revenue ledger (api/_lib/revenue-*.js).
	revenue_milestone: 'sales',
	reinvest_run: 'sales',
	reinvest_rule_failed: 'alerts',
	revenue_reconcile_drift: 'alerts',

	skill_purchase_confirmed: 'purchases',
	asset_purchase_confirmed: 'purchases',
	skill_gift_received: 'purchases',
	skill_gift_sent: 'purchases',
	// Materialize: one type carries the whole print lifecycle, quoted through
	// delivered. It is the buyer's own order, so it belongs with purchases.
	print_update: 'purchases',
	// An agent's purchase was paid, verified on-chain and its goods delivered.
	commerce_order_delivered: 'purchases',

	event_market_entrant: 'markets',
	remix: 'social',
	reply: 'social',
	comment: 'social',
	embed: 'social',
	mention: 'social',
	fork: 'social',
	follow: 'social',
	dm_received: 'social',
	agent_review: 'social',
	quest_complete: 'social',
	// Another owner challenged your agent to a duel, or answered your challenge.
	duel_challenge: 'social',
	// An agent you follow placed an Event Markets pick (api/_lib/event-markets/forecasters.js).
	event_market_agent_pick: 'social',

	irl_interaction: 'irl',
	irl_reply: 'irl',

	pump_alert: 'alerts',
	perps_alert: 'alerts',

	companion_delivery: 'companion',

	knock_received: 'knock',

	mail_received: 'mail',

	order_update: 'orders',

	forge_complete: 'creations',
	forge_failed: 'creations',

	withdrawal_completed: 'account',
	withdrawal_failed: 'account',
	// Labor-market escrow lifecycle (api/_lib/labor-evaluation.js).
	labor_escrow_update: 'account',
	labor_deadline_soon: 'account',
	labor_payout_delayed: 'account',
	payment_mismatch: 'account',
	asset_payment_mismatch: 'account',
	skill_payment_mismatch: 'account',
	security_alert: 'account',
	wallet_anomaly_frozen: 'account',
	approval_requested: 'approvals',
	// An agent proposed new spending limits; the owner decides with a step-up.
	commerce_limits_request: 'approvals',
	token_budget_paused: 'account',
	spend_cap_alert: 'account',
	whitelist_proposed: 'account',
	whitelist_pending: 'account',
	whitelist_active: 'account',
	whitelist_cancelled: 'account',
	whitelist_removed: 'account',
	whitelist_edited: 'account',
	whitelist_settings: 'account',
};

export function categoryForType(type) {
	return TYPE_CATEGORY[type] || 'account';
}

/**
 * The whole type to category map, for clients that have to resolve a category
 * without a round trip per notification (the avatar channel runs in the
 * browser). Served by GET /api/notifications/preferences so the browser never
 * keeps its own copy of this table.
 */
export function typeCategoryMap() {
	return { ...TYPE_CATEGORY };
}

// Default channel matrix. in_app is on everywhere (the bell is the baseline).
// push is on by default *for users who have subscribed a device* — a user with
// no push subscription simply never receives one, so defaulting it on is not
// spammy. email defaults on only for money + security; off for the higher-
// frequency social/irl/alerts categories. telegram is always opt-in (needs a
// linked chat id) so it defaults off. discord mirrors telegram: both deliver to
// chats paired through the chat gateways (api/_lib/gateway/notify.js).
// avatar is the most interruptive channel there is: the corner companion walks
// on screen and says the line out loud. It defaults on only for the three
// categories worth stopping the visitor for (money in, a creation that
// finished while they waited, account and security), and off for the
// higher-frequency ones. Every category stays togglable in the preference
// center either way.
const DEFAULTS = {
	sales:     { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: true  },
	purchases: { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: false },
	social:    { in_app: true,  push: true,  email: false, telegram: false, discord: false, avatar: false },
	irl:       { in_app: true,  push: true,  email: false, telegram: false, discord: false, avatar: false },
	alerts:    { in_app: true,  push: true,  email: false, telegram: true,  discord: true,  avatar: false },
	// Only unattended completions notify (api/cron/forge-finalize.js), so email
	// defaulting on is the feature, not spam: the user left the page and asked
	// to hear back.
	markets:   { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: false },
	creations: { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: true  },
	// The companion category exists to be spoken: a message the visitor's own
	// companion triaged as worth hearing (api/_lib/companion/triage.js). Email
	// and telegram would just relay what the user already gets in that inbox.
	companion: { in_app: true,  push: true,  email: false, telegram: false, discord: false, avatar: true  },
	knock:     { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: true  },
	mail:      { in_app: true,  push: true,  email: false, telegram: false, discord: false, avatar: false },
	// An order fires while the owner is away by design, so the paired chat is on
	// by default: it is where a trader expects to hear that a stop hit.
	orders:    { in_app: true,  push: true,  email: false, telegram: true,  discord: false, avatar: false },
	account:   { in_app: true,  push: true,  email: true,  telegram: false, discord: false, avatar: true  },
	// Approvals reach for every paired surface by default: an unanswered request
	// expires and the action never runs, so being reached is the feature. Email
	// is only the fallback (api/_lib/approvals.js sends it when no push device or
	// paired chat got the request).
	approvals: { in_app: true,  push: true,  email: true,  telegram: true,  discord: true,  avatar: true  },
};

/** The full default matrix, used to seed the preference-center UI. */
export function defaultMatrix() {
	return JSON.parse(JSON.stringify(DEFAULTS));
}

/**
 * Resolve the effective channel matrix for a user by overlaying their stored
 * sparse prefs onto DEFAULTS. Returns { categories, telegram_chat_id }.
 */
export async function resolvePrefs(userId) {
	return mergeWithDefaults(await readStoredPrefs(userId));
}

/**
 * The caller's stored sparse override exactly as persisted, or `{}` when they
 * have never saved. A partial update merges onto this rather than onto the
 * resolved matrix, so a save never materialises today's defaults into the row
 * and freezes them there.
 */
export async function readStoredPrefs(userId) {
	try {
		const [row] = await sql`
			select prefs from notification_preferences where user_id = ${userId}
		`;
		return row?.prefs && typeof row.prefs === 'object' ? row.prefs : {};
	} catch (err) {
		// A missing table or transient DB error must never block delivery. Fall
		// back to defaults (in_app + push on) rather than dropping the notice.
		console.error('[notify-prefs] resolve failed:', err.message);
		return {};
	}
}

export function mergeWithDefaults(stored) {
	const out = { categories: {}, telegram_chat_id: stored?.telegram_chat_id || null };
	const storedCats = (stored && stored.categories) || {};
	for (const { key } of CATEGORIES) {
		out.categories[key] = { ...DEFAULTS[key], ...(storedCats[key] || {}) };
	}
	return out;
}

/**
 * Destination-allowlist changes are the alarm that tells an owner a stolen session
 * or injected agent is adding a payout address, so the preference matrix cannot
 * mute them. They reach every connected channel regardless of category defaults.
 */
const ALWAYS_NOTIFY_TYPES = new Set(['whitelist_proposed', 'whitelist_pending', 'whitelist_active', 'whitelist_cancelled', 'whitelist_removed', 'whitelist_edited', 'whitelist_settings']);
const ALWAYS_NOTIFY_CHANNELS = new Set(['in_app', 'push', 'telegram', 'discord']);

/** Is `channel` enabled for the category that `type` belongs to? */
export function channelEnabled(prefs, type, channel) {
	if (ALWAYS_NOTIFY_TYPES.has(type) && ALWAYS_NOTIFY_CHANNELS.has(channel)) return true;
	const cat = categoryForType(type);
	const row = prefs?.categories?.[cat];
	if (!row) return DEFAULTS[cat]?.[channel] ?? false;
	// An explicit stored boolean (including `false`) wins; only fall back to the
	// default when the channel is unset (null/undefined). The previous form
	// short-circuited on `false` and wrongly returned the default — so a user who
	// turned a channel OFF still received it.
	return row[channel] != null ? !!row[channel] : (DEFAULTS[cat]?.[channel] ?? false);
}

/**
 * Sanitise an incoming preference body to the known category/channel shape.
 * Anything unrecognised is dropped, so the client can't smuggle arbitrary keys
 * into the JSONB. Returns the sparse object to store.
 */
export function sanitizePrefs(body) {
	const out = { categories: {} };
	const cats = body?.categories;
	if (cats && typeof cats === 'object') {
		for (const [cat, row] of Object.entries(cats)) {
			if (!CATEGORY_KEYS.has(cat) || !row || typeof row !== 'object') continue;
			const clean = {};
			for (const ch of CHANNELS) {
				if (typeof row[ch] === 'boolean') clean[ch] = row[ch];
			}
			if (Object.keys(clean).length) out.categories[cat] = clean;
		}
	}
	if (typeof body?.telegram_chat_id === 'string') {
		const t = body.telegram_chat_id.trim();
		if (/^-?\d{1,20}$/.test(t)) out.telegram_chat_id = t;
		else if (t === '') out.telegram_chat_id = null;
	}
	return out;
}

// ── Push payload shaping ─────────────────────────────────────────────────────
// Build the title/body/url shown in the OS notification from a stored
// notification row. Mirrors the labels in src/notifications.js so the push and
// the in-app inbox read identically. Only $THREE is ever referenced.

const PUSH_COPY = {
	event_market_entrant:     (p) => ['You are in a market', `${p.outcome_label || 'You'} ${p.even_prior ? 'is an entrant in' : `is at ${Math.round((p.probability || 0) * 100)}% in`} "${p.title || 'a market'}". Open your kit.`],
	skill_purchased:          (p) => ['You made a sale 💵', `Payment received for "${p.skill || 'a skill'}"`],
	skill_purchase_confirmed: (p) => ['Purchase confirmed ✅', `Your purchase of "${p.skill || 'a skill'}" is confirmed`],
	skill_gift_received:      (p) => ['You got a gift 🎁', p.from ? `${p.from} gifted you "${p.skill || 'a skill'}"` : `You received "${p.skill || 'a skill'}" as a gift`],
	skill_gift_sent:          (p) => ['Gift delivered 🎁', p.to ? `Your gift reached ${p.to}` : 'Your gift was delivered'],
	asset_purchased:          (p) => ['You made a sale 💵', `Someone purchased your ${p.item_type || 'asset'}`],
	asset_purchase_confirmed: ()  => ['Purchase confirmed ✅', 'Your asset purchase is confirmed'],
	referral_earned:          ()  => ['Referral earned 💰', 'You earned a referral commission'],
	'payment-earned':         (p) => ['Payment received 💸', p.actor ? `From ${p.actor}` : 'A payment landed in your account'],
	sale:                     ()  => ['You made a sale 🛒', 'Your agent made a sale'],
	pump_launch_filled:       (p) => ['Your launch filled 🚀', p.name ? `${p.name} hit its target` : 'Your launch reached its target'],
	embed:                    ()  => ['New embed 🔗', 'Your creation was embedded somewhere new'],
	remix:                    (p) => ['Remixed 🔄', p.royaltyPaid && p.royaltyUsd ? `Someone remixed your creation — you earned $${Number(p.royaltyUsd).toFixed(3)}` : 'Someone remixed your creation'],
	fork:                     ()  => ['Forked 🍴', 'Someone forked your agent'],
	reply:                    ()  => ['New reply 💬', 'New reply on your agent'],
	mention:                  ()  => ['You were mentioned 📣', 'Your agent was mentioned'],
	follow:                   (p) => ['New follower 👤', p.actor ? `${p.actor} started following you` : 'Someone started following you'],
	dm_received:              (p) => ['New message 💬', p.actor ? `${p.actor} sent you a message` : 'You have a new message'],
	agent_review:             (p) => ['New review ⭐', p.actor ? `${p.actor} reviewed your agent` : 'Your agent received a review'],
	quest_complete:           (p) => ['Quest complete 🏆', p.mission ? `You finished "${p.mission}"${p.gold ? ` — earned ${p.gold} gold` : ''}` : 'You finished a quest'],
	duel_challenge:           (p) => ['Duel challenge ⚔️', p.summary || 'Another agent challenged yours to a trading duel'],
	event_market_agent_pick:  (p) => [`${p.agent_name || 'An agent you follow'} made a call`, p.market_title ? `Picked ${p.outcome_label || 'an entrant'} in "${p.market_title}"` : 'A new pick is up on Event Markets'],
	royalty_paid:             (p) => ['Royalty earned 💰', p.usd ? `A fork paid you $${Number(p.usd).toFixed(3)} in royalties` : (p.sol ? `A fork paid you ${Number(p.sol).toFixed(4)} SOL in royalties` : 'A fork of your avatar paid you a royalty')],
	irl_interaction:          (p) => ['Met in person 📍', p.message ? `“${p.message}”` : 'Someone interacted with your agent in person'],
	irl_reply:                (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],
	pump_alert:               (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],
	perps_alert:              (p) => [p.title || 'Perps alert', p.summary || 'A perps threshold you set on your agent was crossed'],
	companion_delivery:       (p) => [p.sender ? `${p.sender} 👋` : 'Your companion 👋', p.line || p.title || 'Something worth your attention just came in'],
	mail_received:            (p) => [`${p.agent_name || 'Your agent'} got an email ✉️`, `${p.from_name || p.from || 'Someone'}: ${p.subject || '(no subject)'}`],
	knock_received:           (p) => [p.sender ? `${p.sender} is at your door 🚪` : 'Someone is at your door 🚪', p.title || p.body || 'Someone paid to reach you'],
	order_update:             (p) => [p.title || 'Order update', p.message || 'An order on your agent changed state'],
	forge_complete:           (p) => ['Your 3D model is ready ✨', p.prompt ? `"${String(p.prompt).slice(0, 80)}" finished generating` : 'Your generation finished. Tap to view it'],
	forge_failed:             (p) => ['Generation failed ⚠️', p.prompt ? `"${String(p.prompt).slice(0, 80)}" could not be generated. Tap to retry` : 'A generation could not be completed. Tap to retry'],
	withdrawal_completed:     ()  => ['Withdrawal complete ✅', 'Your withdrawal has been sent'],
	creator_payout_sent:      (p) => ['Creator fees sent', p.message || 'Your creator-fee share was sent to your payout wallet'],
	creator_payout_held:      (p) => ['Creator fees held', p.message || 'A creator-fee share is held. Open your payouts page to see why'],
	creator_payout_wallet:    (p) => ['Payout wallet changed', p.message || 'The payout wallet for your creator fees changed'],
	labor_escrow_update:      (p) => [p.title || 'Escrow update', p.message || 'A bounty escrow changed state'],
	labor_deadline_soon:      (p) => [p.title || 'Deadline approaching', p.message || 'A bounty deadline is close'],
	labor_payout_delayed:     (p) => [p.title || 'Payout delayed', p.message || 'An escrow payout is delayed and will retry'],
	withdrawal_failed:        ()  => ['Withdrawal failed ⚠️', 'A withdrawal could not be completed — tap to review'],
	payment_mismatch:         ()  => ['Payment mismatch ⚠️', 'Check your agent payment settings'],
	asset_payment_mismatch:   ()  => ['Payment mismatch ⚠️', 'Check your agent payment settings'],
	skill_payment_mismatch:   ()  => ['Payment mismatch ⚠️', 'Check your agent payment settings'],
	security_alert:           (p) => ['Security alert 🔒', p.message || 'A security-sensitive change was made to your account'],
	wallet_anomaly_frozen:    (p) => ['Wallet auto-frozen 🛡️', p.summary || 'Your agent wallet was frozen after an unusual action — tap to approve or keep frozen'],
	approval_requested:       (p) => ['Approval needed', [p.summary || 'An agent is waiting for your approval', p.confirmation].filter(Boolean).join('\n')],
	token_budget_paused:      (p) => ['Agent paused: token ceiling', `${p.agent_name || 'Your agent'} hit its ${p.window === 'hour' ? 'hourly' : p.window === 'day' ? 'daily' : 'per-run'} token ceiling. Resume it or extend the ceiling once.`],
	spend_cap_alert:          (p) => [`${Number(p.threshold) || 0}% of a spend cap used`, `${p.agent_name || 'Your agent'} has used ${Number(p.threshold) || 0}% of its ${p.window === 'month' ? 'monthly' : p.window === 'day' ? 'daily' : p.window === 'hour' ? 'hourly' : 'per-run'} ${p.cap === 'tokens' ? 'token' : 'spend'} cap.`],
	whitelist_proposed: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_pending: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_active: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_cancelled: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_removed: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_edited: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
	whitelist_settings: (p) => ['Wallet allowlist', p.message || 'A wallet destination changed. Tap to review'],
};

export function pushPayloadFor(type, payload, notificationId) {
	const p = payload || {};
	const fn = PUSH_COPY[type];
	const [title, body] = fn ? fn(p) : ['three.ws', String(type).replace(/_/g, ' ')];
	const url = pushUrlFor(p);
	const out = {
		title,
		body,
		url,
		tag: type,
		notificationId: notificationId || null,
		// Used by the SW to attribute the 'returned' funnel event.
		category: categoryForType(type),
	};
	// An approval push carries what the service worker needs to answer it in
	// place (Approve / Deny action buttons, public/push-sw.js): the request id,
	// the payload hash the owner is approving, and the signed link token. One
	// tag per request so two pending approvals never replace each other.
	if (type === 'approval_requested' && p.approval_id) {
		out.tag = `approval:${p.approval_id}`;
		out.approval = { id: p.approval_id, hash: p.payload_hash || null, token: p.link_token || null };
	}
	return out;
}

function pushUrlFor(p) {
	const raw = p.link
		|| (p.tx_signature ? `https://solscan.io/tx/${encodeURIComponent(p.tx_signature)}` : null)
		|| (p.agent_id ? `/agents/${encodeURIComponent(p.agent_id)}` : null)
		|| '/dashboard/';
	// Same allowlist as the inbox: same-origin path or absolute http(s).
	if (typeof raw !== 'string') return '/dashboard/';
	const s = raw.trim();
	if (s.startsWith('/') && !s.startsWith('//')) return s;
	if (/^https?:\/\//i.test(s)) return s;
	return '/dashboard/';
}