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(spotlight): back success stories with verified, server-computed results and owner consent

nirholas1ef826a160e6
diff --git a/api/_lib/spotlight-metrics.js b/api/_lib/spotlight-metrics.js
new file mode 100644
index 000000000..c06afb1d9
--- /dev/null
+++ b/api/_lib/spotlight-metrics.js
@@ -0,0 +1,209 @@
+// Verified results for Agent Spotlight entries and /stories.
+//
+// A spotlight write-up is a claim in the builder's own words. The figures in
+// this module are the opposite: computed server-side from tables the builder
+// cannot type into, keyed by agent_id, each with the source a reader can check.
+//
+// coins pump_agent_mints (mainnet): every coin the agent launched,
+// with its mint, a Solscan link and its three.ws launch page.
+// service_income agent_revenue_events (x402 skill sales, USDC net of the
+// platform fee) plus agent_hires (completed hires by other
+// agents). USDC is valued 1:1 in USD. Same definition as the
+// agent earnings read model, so the two never disagree.
+// creator_fees pump.fun creator fees from the agent earnings read model
+// (api/_lib/agent-earnings.js, served at
+// GET /api/agents/:id/earnings). Loaded lazily: when that
+// module or its snapshot is not available on a deployment,
+// the metric reports `available: false` and says so, rather
+// than showing a zero nobody measured.
+// activity conversations and logged actions, already carried on the
+// entry itself (agent.chat_count / agent.action_count).
+//
+// `qualifies` is true when the agent has a RESULT to show: at least one coin
+// launched, creator fees above zero, or service income above zero. Activity
+// counts alone never make a story.
+
+import { sql } from './db.js';
+import { SOLANA_USDC_MINT } from '../payments/_config.js';
+
+const USDC_DECIMALS = 6;
+
+const round2 = (n) => Math.round(Number(n) * 100) / 100;
+
+function emptyMetrics(agentId) {
+ return {
+ coins: { count: 0, items: [], source: 'pump_agent_mints', source_url: `/launches` },
+ service_income: {
+ usd: 0,
+ skill_sales_usd: 0,
+ skill_sales_count: 0,
+ hires_usd: 0,
+ hires_count: 0,
+ source: 'agent_revenue_events + agent_hires',
+ source_url: `/api/agents/${agentId}/earnings`,
+ },
+ creator_fees: {
+ available: false,
+ sol: null,
+ usd: null,
+ reason: 'not_loaded',
+ source_url: `/api/agents/${agentId}/earnings`,
+ },
+ };
+}
+
+function coinItem(row) {
+ return {
+ mint: row.mint,
+ name: row.name || null,
+ symbol: row.symbol || null,
+ launched_at: row.created_at,
+ launch_url: `/launches/${row.mint}`,
+ solscan_url: `https://solscan.io/token/${row.mint}`,
+ };
+}
+
+/**
+ * Coins and service income for many agents in three queries.
+ * @param {string[]} agentIds
+ * @returns {Promise<Map<string, ReturnType<typeof emptyMetrics>>>}
+ */
+export async function baseMetrics(agentIds) {
+ const ids = [...new Set((agentIds || []).filter(Boolean))];
+ const out = new Map(ids.map((id) => [id, emptyMetrics(id)]));
+ if (!ids.length) return out;
+
+ const [coins, sales, hires] = await Promise.all([
+ sql`
+ select agent_id, mint, name, symbol, created_at
+ from pump_agent_mints
+ where agent_id = any(${ids}::uuid[]) and network = 'mainnet'
+ order by created_at desc
+ `,
+ sql`
+ select agent_id, coalesce(sum(net_amount), 0)::text as atomics, count(*)::int as n
+ from agent_revenue_events
+ where agent_id = any(${ids}::uuid[]) and currency_mint = ${SOLANA_USDC_MINT}
+ group by agent_id
+ `,
+ sql`
+ select provider_agent_id as agent_id, coalesce(sum(usd), 0)::float8 as usd, count(*)::int as n
+ from agent_hires
+ where provider_agent_id = any(${ids}::uuid[]) and status = 'completed'
+ group by provider_agent_id
+ `,
+ ]);
+
+ for (const row of coins) {
+ const m = out.get(row.agent_id);
+ if (!m) continue;
+ m.coins.items.push(coinItem(row));
+ m.coins.count += 1;
+ }
+ for (const row of sales) {
+ const m = out.get(row.agent_id);
+ if (!m) continue;
+ m.service_income.skill_sales_usd = round2(Number(BigInt(row.atomics)) / 10 ** USDC_DECIMALS);
+ m.service_income.skill_sales_count = row.n;
+ }
+ for (const row of hires) {
+ const m = out.get(row.agent_id);
+ if (!m) continue;
+ m.service_income.hires_usd = round2(row.usd);
+ m.service_income.hires_count = row.n;
+ }
+ for (const m of out.values()) {
+ m.service_income.usd = round2(m.service_income.skill_sales_usd + m.service_income.hires_usd);
+ }
+ return out;
+}
+
+// The earnings read model is loaded on first use. A deployment that does not
+// carry it (or whose snapshot table is missing) degrades creator fees to
+// "not available" instead of failing the whole entry.
+let earningsModule;
+async function loadEarnings() {
+ if (earningsModule === undefined) {
+ earningsModule = await import('./agent-earnings.js').catch((err) => {
+ console.warn('[spotlight-metrics] agent earnings read model unavailable:', err?.message || err);
+ return null;
+ });
+ }
+ return earningsModule?.getAgentEarnings ? earningsModule : null;
+}
+
+/**
+ * Attach creator fees for the given agents (in place).
+ * @param {Map<string, ReturnType<typeof emptyMetrics>>} metrics
+ */
+export async function attachCreatorFees(metrics) {
+ const mod = await loadEarnings();
+ if (!mod) {
+ for (const m of metrics.values()) m.creator_fees.reason = 'earnings_unavailable';
+ return metrics;
+ }
+ const ids = [...metrics.keys()];
+ if (!ids.length) return metrics;
+ const agents = await sql`
+ select id, name, is_public, meta->>'solana_address' as solana_address
+ from agent_identities
+ where id = any(${ids}::uuid[]) and deleted_at is null
+ `;
+ await Promise.all(
+ agents.map(async (agent) => {
+ const m = metrics.get(agent.id);
+ if (!m) return;
+ try {
+ const e = await mod.getAgentEarnings(agent, { window: 'all' });
+ const sol = Number(e?.lifetime_creator_fees?.earned_sol);
+ m.creator_fees = {
+ available: Number.isFinite(sol),
+ sol: Number.isFinite(sol) ? sol : null,
+ usd: e?.lifetime_creator_fees?.earned_usd ?? null,
+ refreshed_at: e?.refreshed_at ?? null,
+ reason: Number.isFinite(sol) ? null : 'no_figure',
+ source_url: `/api/agents/${agent.id}/earnings`,
+ };
+ } catch (err) {
+ console.warn(`[spotlight-metrics] creator fees for ${agent.id} failed:`, err?.message || err);
+ m.creator_fees.reason = 'earnings_unavailable';
+ }
+ }),
+ );
+ return metrics;
+}
+
+/** True when the agent has a result a story can stand on. */
+export function qualifies(m) {
+ if (!m) return false;
+ return (
+ m.coins.count > 0 ||
+ m.service_income.usd > 0 ||
+ (m.creator_fees.available && Number(m.creator_fees.sol) > 0)
+ );
+}
+
+/**
+ * Shape metrics for the API: the three result metrics plus which of them are
+ * live on this deployment, so a client can say "creator fees are not measured
+ * here yet" instead of printing a zero.
+ */
+export function shapeVerified(m) {
+ return {
+ coins: m.coins,
+ service_income: m.service_income,
+ creator_fees: m.creator_fees,
+ live: ['coins', 'service_income', ...(m.creator_fees.available ? ['creator_fees'] : [])],
+ qualifies: qualifies(m),
+ };
+}
+
+/**
+ * Full verified metrics (coins, service income, creator fees) for many agents.
+ * @param {string[]} agentIds
+ */
+export async function verifiedMetrics(agentIds) {
+ const metrics = await baseMetrics(agentIds);
+ await attachCreatorFees(metrics);
+ return metrics;
+}
diff --git a/api/_lib/spotlight-store.js b/api/_lib/spotlight-store.js
index 409460ca0..5f0a47adf 100644
--- a/api/_lib/spotlight-store.js
+++ b/api/_lib/spotlight-store.js
@@ -136,6 +136,11 @@ export function mapEntry(row, { now = Date.now() } = {}) {
},
builder: builderOf(row),
editable_by_me: Boolean(row.editable_by_me),
+ // Only the agent's owner can consent to a story; a submitter who does not
+ // own the agent can edit the pitch but never claim results for it.
+ owned_by_me: Boolean(row.owned_by_me),
+ story_consent: Boolean(row.featured_story_at),
+ story_consented_at: row.featured_story_at || null,
};
}
@@ -160,6 +165,7 @@ export async function listEntries({
select
s.id, s.title, s.tagline, s.story, s.demo_url, s.category, s.tags,
s.source, s.featured_at, s.view_count, s.created_at, s.submitted_by,
+ s.featured_story_at,
i.id as agent_id,
i.name as agent_name,
i.description as agent_description,
@@ -176,7 +182,8 @@ export async function listEntries({
coalesce(ch.n, 0) as chat_count,
coalesce(ac.n, 0) as action_count,
${viewerId ? sql`(mv.user_id is not null)` : sql`false`} as voted_by_me,
- ${viewerId ? sql`(s.submitted_by = ${viewerId} or i.user_id = ${viewerId})` : sql`false`} as editable_by_me
+ ${viewerId ? sql`(s.submitted_by = ${viewerId} or i.user_id = ${viewerId})` : sql`false`} as editable_by_me,
+ ${viewerId ? sql`(i.user_id = ${viewerId})` : sql`false`} as owned_by_me
from agent_showcase s
join agent_identities i on i.id = s.agent_id and i.deleted_at is null and i.is_public = true
left join avatars a on a.id = i.avatar_id and a.deleted_at is null
@@ -257,6 +264,7 @@ export async function getEntry(id, { viewerId = null } = {}) {
select
s.id, s.title, s.tagline, s.story, s.demo_url, s.category, s.tags,
s.source, s.featured_at, s.view_count, s.created_at, s.submitted_by,
+ s.featured_story_at,
i.id as agent_id,
i.name as agent_name,
i.description as agent_description,
@@ -273,7 +281,8 @@ export async function getEntry(id, { viewerId = null } = {}) {
coalesce(ch.n, 0) as chat_count,
coalesce(ac.n, 0) as action_count,
${viewerId ? sql`(mv.user_id is not null)` : sql`false`} as voted_by_me,
- ${viewerId ? sql`(s.submitted_by = ${viewerId} or i.user_id = ${viewerId})` : sql`false`} as editable_by_me
+ ${viewerId ? sql`(s.submitted_by = ${viewerId} or i.user_id = ${viewerId})` : sql`false`} as editable_by_me,
+ ${viewerId ? sql`(i.user_id = ${viewerId})` : sql`false`} as owned_by_me
from agent_showcase s
join agent_identities i on i.id = s.agent_id and i.deleted_at is null and i.is_public = true
left join avatars a on a.id = i.avatar_id and a.deleted_at is null
@@ -382,13 +391,18 @@ export async function upsertEntry({
demoUrl = null,
category,
tags = [],
+ featureStory = false,
}) {
+ // Story consent rides on the owner's own submission: the endpoint only
+ // reaches here after ownsAgent() passed, so the submitter IS the owner.
const [row] = await sql`
insert into agent_showcase
- (agent_id, submitted_by, source, title, tagline, story, demo_url, category, tags)
+ (agent_id, submitted_by, source, title, tagline, story, demo_url, category, tags,
+ featured_story_at, featured_story_by)
values
(${agentId}, ${userId}, 'community', ${title}, ${tagline}, ${story}, ${demoUrl},
- ${category}, ${tags}::text[])
+ ${category}, ${tags}::text[],
+ ${featureStory ? sql`now()` : sql`null`}, ${featureStory ? userId : null})
on conflict (agent_id) where deleted_at is null
do update set
title = excluded.title,
@@ -400,6 +414,16 @@ export async function upsertEntry({
-- A curated write-up that the builder later claims becomes theirs.
source = 'community',
submitted_by = excluded.submitted_by,
+ -- Keep the original consent time on an edit that keeps consenting;
+ -- unticking the box withdraws it.
+ featured_story_at = case
+ when excluded.featured_story_at is null then null
+ else coalesce(agent_showcase.featured_story_at, excluded.featured_story_at)
+ end,
+ featured_story_by = case
+ when excluded.featured_story_at is null then null
+ else coalesce(agent_showcase.featured_story_by, excluded.featured_story_by)
+ end,
updated_at = now()
returning id
`;
@@ -466,6 +490,100 @@ export async function softDeleteEntry(entryId, userId) {
return rows.length > 0;
}
+/* ── stories + moderation ─────────────────────────────────────────────── */
+
+// Consented, published entries on public agents: the /stories candidate set.
+// Whether a candidate is SHOWN also depends on it having a verified result,
+// which api/_lib/spotlight-metrics.js decides; this query never widens past
+// consent, so a curated entry without its owner's yes can never reach /stories.
+export async function listStoryEntries({ limit = 60 } = {}) {
+ const rows = await sql`
+ select
+ s.id, s.title, s.tagline, s.story, s.demo_url, s.category, s.tags,
+ s.source, s.featured_at, s.view_count, s.created_at, s.submitted_by,
+ s.featured_story_at,
+ i.id as agent_id,
+ i.name as agent_name,
+ i.description as agent_description,
+ i.skills as agent_skills,
+ i.meta as agent_meta,
+ i.erc8004_agent_id,
+ i.created_at as agent_created_at,
+ a.thumbnail_key as avatar_thumbnail_key,
+ a.storage_key as avatar_storage_key,
+ a.visibility as avatar_visibility,
+ u.display_name as builder_display_name,
+ u.username as builder_username,
+ coalesce(v.n, 0) as vote_count,
+ coalesce(ch.n, 0) as chat_count,
+ coalesce(ac.n, 0) as action_count,
+ false as voted_by_me,
+ false as editable_by_me,
+ false as owned_by_me
+ from agent_showcase s
+ join agent_identities i on i.id = s.agent_id and i.deleted_at is null and i.is_public = true
+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null
+ left join users u on u.id = i.user_id and u.deleted_at is null
+ left join lateral (
+ select count(*)::int n from agent_showcase_votes sv where sv.entry_id = s.id
+ ) v on true
+ left join lateral (
+ select count(*)::int n from usage_events ue where ue.agent_id = i.id and ue.kind = 'llm'
+ ) ch on true
+ left join lateral (
+ select count(*)::int n from agent_actions aa where aa.agent_id = i.id
+ ) ac on true
+ where s.deleted_at is null
+ and s.status = 'published'
+ and s.featured_story_at is not null
+ -- Consent must come from the agent's current owner. If the agent changed
+ -- hands after consent was given, the new owner has not said yes.
+ and s.featured_story_by = i.user_id
+ order by s.featured_story_at desc, s.id
+ limit ${limit}
+ `;
+ const now = Date.now();
+ return rows.map((r) => mapEntry(r, { now }));
+}
+
+// Owner-only consent toggle. Returns the new state, or null when the caller
+// does not own the agent behind a live entry (the endpoint answers 403).
+export async function setStoryConsent(entryId, userId, consent) {
+ const rows = await sql`
+ update agent_showcase s
+ set featured_story_at = ${consent ? sql`coalesce(s.featured_story_at, now())` : sql`null`},
+ featured_story_by = ${consent ? userId : null},
+ updated_at = now()
+ from agent_identities i
+ where s.id = ${entryId}
+ and s.deleted_at is null
+ and i.id = s.agent_id
+ and i.deleted_at is null
+ and i.user_id = ${userId}
+ returning s.featured_story_at
+ `;
+ if (!rows.length) return null;
+ return { story_consent: Boolean(rows[0].featured_story_at), story_consented_at: rows[0].featured_story_at };
+}
+
+// Moderation: an admin hides or restores an entry. Hidden entries are retained
+// (the builder's words are not destroyed) but drop out of every public read,
+// because each read filters on status = 'published'. Returns the row's new
+// state, or null when no live entry has that id.
+export async function setEntryVisibility(entryId, { hidden, adminId, reason = null }) {
+ const rows = await sql`
+ update agent_showcase
+ set status = ${hidden ? 'hidden' : 'published'},
+ hidden_at = ${hidden ? sql`now()` : sql`null`},
+ hidden_by = ${hidden ? adminId : null},
+ hidden_reason = ${hidden ? reason : null},
+ updated_at = now()
+ where id = ${entryId} and deleted_at is null
+ returning id, status, hidden_at, hidden_reason
+ `;
+ return rows[0] || null;
+}
+
// Best-effort view counter. A failure here must never break the page it counts,
// so the caller fires it without awaiting the result.
export async function bumpViews(entryId) {
diff --git a/api/spotlight/[action].js b/api/spotlight/[action].js
index fa3ed72d9..c2bb7fc61 100644
--- a/api/spotlight/[action].js
+++ b/api/spotlight/[action].js
@@ -7,6 +7,9 @@
// POST /api/spotlight/submit { agentId, title, tagline, story?, demoUrl?, category, tags[] }
// POST /api/spotlight/vote { id } (toggle)
// POST /api/spotlight/remove { id } (submitter or agent owner)
+// GET /api/spotlight/stories (consented entries with a verified result, by category)
+// POST /api/spotlight/consent { id, consent } (agent owner: feature as a story, or withdraw)
+// POST /api/spotlight/moderate { id, action: 'hide'|'unhide', reason? } (admin)
//
// Reads are public and CDN-cached; writes need a session plus CSRF. The ranking
// and every query live in api/_lib/spotlight-store.js; this file is the HTTP
@@ -17,6 +20,9 @@ import { requireCsrf } from '../_lib/csrf.js';
import { getSessionUser } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { isUuid } from '../_lib/validate.js';
+import { requireAdmin } from '../_lib/admin.js';
+import { logAudit } from '../_lib/audit.js';
+import { verifiedMetrics, shapeVerified } from '../_lib/spotlight-metrics.js';
import {
CATEGORIES,
SORTS,
@@ -29,7 +35,10 @@ import {
getEntry,
isCategory,
listEntries,
+ listStoryEntries,
ownsAgent,
+ setEntryVisibility,
+ setStoryConsent,
showcaseConfigured,
showcaseTotals,
softDeleteEntry,
@@ -62,6 +71,12 @@ export default wrap(async (req, res) => {
return await handleVote(req, res);
case 'remove':
return await handleRemove(req, res);
+ case 'stories':
+ return await handleStories(req, res);
+ case 'consent':
+ return await handleConsent(req, res);
+ case 'moderate':
+ return await handleModerate(req, res);
default:
return error(res, 404, 'not_found', `unknown spotlight action "${actionOf(req)}"`);
}
@@ -148,9 +163,57 @@ async function handleGet(req, res) {
if (!entry) return error(res, 404, 'not_found', 'no such showcase entry');
void bumpViews(id);
+ entry.verified = await entryVerified(entry.agent.id);
return json(res, 200, { entry }, { 'Cache-Control': 'private, no-store' });
}
+// Verified results for one entry's agent. A failure here degrades to null (the
+// page shows "results unavailable") rather than failing the whole entry: the
+// write-up is still worth reading while a metrics table is unreachable.
+async function entryVerified(agentId) {
+ try {
+ const metrics = await verifiedMetrics([agentId]);
+ return shapeVerified(metrics.get(agentId));
+ } catch (err) {
+ console.error('[spotlight] verified metrics failed:', err?.message || err);
+ return null;
+ }
+}
+
+async function handleStories(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const candidates = await listStoryEntries({ limit: 60 });
+ const metrics = await verifiedMetrics(candidates.map((e) => e.agent.id));
+ const stories = [];
+ for (const e of candidates) {
+ const verified = shapeVerified(metrics.get(e.agent.id));
+ // Consent alone is not enough: a story needs a result anyone can check.
+ if (!verified.qualifies) continue;
+ stories.push({ ...e, verified });
+ }
+ const groups = CATEGORIES.map((c) => ({
+ ...c,
+ entries: stories.filter((s) => s.category === c.slug),
+ })).filter((g) => g.entries.length);
+
+ return json(
+ res,
+ 200,
+ {
+ groups,
+ total: stories.length,
+ consented: candidates.length,
+ method:
+ 'Only entries whose agent owner opted in appear here, and only when the agent has a verified result: a coin launched (pump_agent_mints), service income (agent_revenue_events and completed agent_hires, USDC at 1:1), or creator fees (the agent earnings read model). Every figure is computed server-side from those tables; none is typed by the builder.',
+ generated_at: new Date().toISOString(),
+ },
+ { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=300' },
+ );
+}
+
async function handleCategories(req, res) {
if (!method(req, res, ['GET'])) return;
const rl = await limits.publicIp(clientIp(req));
@@ -228,6 +291,8 @@ async function handleSubmit(req, res) {
const tags = normalizeTags(body?.tags);
if (tags === false) return error(res, 400, 'bad_request', 'tags must be up to 6 short labels');
+ // Off unless the owner explicitly ticked it: only a literal true consents.
+ const featureStory = body?.featureStory === true;
const id = await upsertEntry({
agentId,
@@ -238,6 +303,7 @@ async function handleSubmit(req, res) {
demoUrl: demoUrl || null,
category,
tags,
+ featureStory,
});
if (!id) return error(res, 500, 'write_failed', 'the entry could not be saved');
@@ -280,6 +346,67 @@ async function handleRemove(req, res) {
return json(res, 200, { removed: true }, { 'Cache-Control': 'private, no-store' });
}
+async function handleConsent(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ const user = await sessionOr401(req, res, 'sign in to feature your agent as a story');
+ if (!user) return;
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.showcaseWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl, 'too many showcase changes; slow down');
+
+ const body = await readJson(req, 2_000);
+ const id = String(body?.id || '').trim();
+ if (!isUuid(id)) return error(res, 400, 'bad_request', 'id must be a uuid');
+ if (typeof body?.consent !== 'boolean') return error(res, 400, 'bad_request', 'consent must be true or false');
+
+ const result = await setStoryConsent(id, user.id, body.consent);
+ if (!result) {
+ return error(res, 403, 'forbidden', 'only the owner of the agent can feature it as a story');
+ }
+ logAudit({
+ userId: user.id,
+ action: body.consent ? 'spotlight_story_consent' : 'spotlight_story_withdraw',
+ resourceId: id,
+ req,
+ });
+ return json(res, 200, result, { 'Cache-Control': 'private, no-store' });
+}
+
+async function handleModerate(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+ if (!(await requireCsrf(req, res, admin.id))) return;
+
+ const body = await readJson(req, 4_000);
+ const id = String(body?.id || '').trim();
+ if (!isUuid(id)) return error(res, 400, 'bad_request', 'id must be a uuid');
+ const action = String(body?.action || '');
+ if (action !== 'hide' && action !== 'unhide') {
+ return error(res, 400, 'bad_request', "action must be 'hide' or 'unhide'");
+ }
+ const reason = trimmed(body?.reason) || null;
+ if (reason && reason.length > 280) return error(res, 400, 'bad_request', 'reason must be 280 characters or fewer');
+
+ const row = await setEntryVisibility(id, { hidden: action === 'hide', adminId: admin.id, reason });
+ if (!row) return error(res, 404, 'not_found', 'no such showcase entry');
+
+ logAudit({
+ userId: admin.id,
+ action: action === 'hide' ? 'spotlight_hide' : 'spotlight_unhide',
+ resourceId: id,
+ meta: reason ? { reason } : null,
+ req,
+ });
+ return json(
+ res,
+ 200,
+ { id: row.id, status: row.status, hidden_at: row.hidden_at, hidden_reason: row.hidden_reason },
+ { 'Cache-Control': 'private, no-store' },
+ );
+}
+
/* ── input helpers ────────────────────────────────────────────────────────── */
async function sessionOr401(req, res, message) {