Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(marketplace): sell the generated animation collection, with a free subset that rotates weekly
nirholase23150b13fed
diff --git a/api/_lib/generated-clip-market.js b/api/_lib/generated-clip-market.jsnew file mode 100644index 000000000..5a2375b44--- /dev/null+++ b/api/_lib/generated-clip-market.js@@ -0,0 +1,142 @@+// @ts-check+// The generated animation collection as a marketplace product line.+//+// Generated clips (gen-*, api/_lib/motion-seed.js) are listed in animation_clips+// under the platform's own account, so they surface in GET+// /api/marketplace/animations and sell through the existing x402 route+// (api/x402/animation-download.js) exactly like a creator listing. What is sold+// is the motion baked onto the platform rig as one portable GLB+// (api/_lib/motion-glb.js); the clip JSON stays public and free, because it is+// what drives every avatar on the site.+//+// POLICY (docs/animation-seeding.md, "Pricing and the rotating free subset"):+// every generated listing carries the Animation Bazaar's advertised price, and a+// fixed-size subset is free for one epoch at a time. The subset is decided at+// READ time by hashing each clip's name with the epoch number (freeClipNames),+// so the stored price never changes, every server instance agrees without a+// database write, and the free slot rotates on its own every week.+//+// A listing counts as generated only when BOTH hold: it is owned by the platform+// account and it carries the `generated` tag. A creator tagging their own clip+// `generated` does not put it in the rotation, and nothing the platform lists by+// hand is ever given away by accident.++import { sql } from './db.js';+import { freeClipNames, FREE_ROTATION, rotationEpoch } from './motion-seed.js';+import { PLATFORM_AGENT_OWNER_EMAIL } from './custodial-key-health.js';+import { priceFor } from './x402-prices.js';++/** The platform account generated listings are owned by. */+export const PLATFORM_CREATOR_EMAIL = PLATFORM_AGENT_OWNER_EMAIL;+/** Tag that marks a platform listing as part of the generated collection. */+export const GENERATED_TAG = 'generated';+/** Wire format stamped on every generated listing row. */+export const GENERATED_FORMAT = 'three.ws.animation.v1';+/** Where the baked GLBs live in object storage. */+export const GENERATED_GLB_PREFIX = 'animations/library/generated/glb';++/**+ * The listing price in human USDC. It is the Animation Bazaar's advertised+ * price (the same number the route's 402 discovery challenge and+ * /.well-known/x402.json quote), so a generated clip is priced exactly like the+ * product the storefront describes. X402_PRICE_ANIMATION_DOWNLOAD overrides it.+ */+export function generatedListingPrice() {+ return Number(priceFor('animation-download', '10000')) / 1_000_000;+}++/** When the current free epoch ends, as an ISO string. */+export function freeEpochEndsAt(now = Date.now()) {+ return new Date((rotationEpoch(now) + 1) * FREE_ROTATION.EPOCH_MS).toISOString();+}++/**+ * Build the animation_clips row for one generated clip. Pure, so the listing+ * sync and the tests produce the same row.+ *+ * @param {{ name: string, label?: string, category?: string, loop?: boolean, duration?: number }} entry manifest row+ * @param {{ tracks?: Array<{ times?: ArrayLike<number> }>, duration?: number, userData?: Record<string, any> }} clip the library clip JSON+ * @param {{ ownerId: string, price: number, artifactKey: string, artifactBytes: number, tags?: string[] }} listing+ */+export function generatedListingRow(entry, clip, { ownerId, price, artifactKey, artifactBytes, tags = [] }) {+ const duration = Number(clip?.duration ?? entry.duration ?? 0);+ let frames = 0;+ for (const track of clip?.tracks ?? []) frames = Math.max(frames, track?.times?.length ?? 0);+ const fps = duration > 0 && frames > 1 ? Math.round((frames - 1) / duration) : null;+ const loop = entry.loop === true;+ const category = entry.category || clip?.userData?.category || null;+ const prompt = typeof clip?.userData?.prompt === 'string' ? clip.userData.prompt : '';+ const tagSet = new Set([GENERATED_TAG, ...(category ? [category] : []), ...tags]);+ return {+ owner_id: ownerId,+ slug: entry.name,+ name: entry.label || entry.name,+ description: prompt+ ? `Generated on the three.ws motion lane from the prompt "${prompt}". Baked onto the three.ws rig as a GLB.`+ : 'Generated on the three.ws motion lane. Baked onto the three.ws rig as a GLB.',+ kind: loop ? 'loop' : 'animation',+ format: GENERATED_FORMAT,+ duration_ms: Math.round(duration * 1000),+ frame_count: frames,+ fps,+ loop,+ tags: [...tagSet].map((t) => String(t).slice(0, 40)).slice(0, 12),+ visibility: 'public',+ price_amount: price > 0 ? price : null,+ price_currency: price > 0 ? 'USDC' : null,+ artifact_key: artifactKey,+ artifact_bytes: artifactBytes,+ artifact_mime: 'model/gltf-binary',+ listed: true,+ };+}++// ── Read side ────────────────────────────────────────────────────────────────++const CACHE_MS = 5 * 60_000;+let cache = null;++/**+ * The platform account id and the slugs free this epoch. Cached for five+ * minutes and never across an epoch boundary, so a rotation takes effect on+ * time. A missing platform account yields an empty set rather than an error:+ * with no generated listings there is nothing to rotate.+ *+ * @returns {Promise<{ platformId: string|null, free: Set<string>, epoch: number }>}+ */+export async function generatedRotation(now = Date.now()) {+ const epoch = rotationEpoch(now);+ if (cache && cache.epoch === epoch && now - cache.at < CACHE_MS) return cache.value;++ const [owner] = await sql`select id from users where lower(email::text) = ${PLATFORM_CREATOR_EMAIL} limit 1`;+ const platformId = owner?.id ?? null;+ let free = new Set();+ if (platformId) {+ const rows = await sql`+ select slug from animation_clips+ where owner_id = ${platformId} and ${GENERATED_TAG} = any(tags)+ and listed = true and deleted_at is null and artifact_key is not null+ `;+ free = new Set(freeClipNames(rows.map((r) => r.slug), { now }));+ }+ const value = { platformId, free, epoch };+ cache = { at: now, epoch, value };+ return value;+}++/** Forget the cached rotation (tests, and the listing sync after it writes). */+export function resetGeneratedRotationCache() {+ cache = null;+}++/**+ * True when this row is a generated listing that is free this epoch.+ *+ * @param {{ owner_id?: string, slug?: string, tags?: string[] }} row+ * @param {{ platformId: string|null, free: Set<string> }} rotation+ */+export function isFreeGeneratedListing(row, rotation) {+ if (!rotation?.platformId || row?.owner_id !== rotation.platformId) return false;+ if (!Array.isArray(row.tags) || !row.tags.includes(GENERATED_TAG)) return false;+ return rotation.free.has(String(row.slug));+}diff --git a/api/marketplace/animations.js b/api/marketplace/animations.jsindex d43cff6fe..a26279899 100644--- a/api/marketplace/animations.js+++ b/api/marketplace/animations.js@@ -13,19 +13,60 @@// ?sort= recent (default) | popular | price_low | price_high// ?limit= 1..60 (default 24)// ?cursor= opaque pagination cursor+//+// The platform's generated collection (api/_lib/generated-clip-market.js) is+// listed here too, under the platform account. A rotating subset of it is free+// for the current week: those rows report `free: true` with `free_rotation`+// set, and the price filters and price sorts treat them as free.import { sql } from '../_lib/db.js';import { cors, error, json, method, wrap } from '../_lib/http.js';import { thumbnailUrl } from '../_lib/r2.js';import { isUuid } from '../_lib/validate.js';-+import {+ freeEpochEndsAt,+ generatedRotation,+ GENERATED_TAG,+ isFreeGeneratedListing,+} from '../_lib/generated-clip-market.js';++// `effective_price` is the price a buyer pays right now: the stored price,+// except for a generated listing in this week's free rotation (see+// rotationFreeSql below).const SORTS = {- recent: 'created_at desc',- popular: 'purchase_count desc, created_at desc',- price_low: 'price_amount asc nulls first, created_at desc',- price_high: 'price_amount desc nulls last, created_at desc',+ recent: 'c.created_at desc',+ popular: 'c.purchase_count desc, c.created_at desc',+ price_low: 'effective_price asc nulls first, c.created_at desc',+ price_high: 'effective_price desc nulls last, c.created_at desc',};+/**+ * SQL that is true for a generated listing free this epoch, appending its+ * parameters to `params`. With no platform account there is no rotation and+ * the predicate is constant false.+ */+function rotationFreeSql(rotation, params) {+ if (!rotation.platformId || rotation.free.size === 0) return 'false';+ params.push(rotation.platformId);+ const owner = params.length;+ params.push(GENERATED_TAG);+ const tag = params.length;+ params.push([...rotation.free]);+ const slugs = params.length;+ return `(c.owner_id = $${owner} and $${tag} = any(c.tags) and c.slug = any($${slugs}::text[]))`;+}++// The rotation is read from the database, so a failure there must not take the+// whole feed down: without it every listing simply reports its stored price.+async function rotationOrNone() {+ try {+ return await generatedRotation();+ } catch (err) {+ console.warn('[marketplace/animations] free rotation unavailable', err?.message || err);+ return { platformId: null, free: new Set(), epoch: 0 };+ }+}+const DOWNLOAD_ROUTE = '/api/x402/animation-download';export default wrap(async (req, res) => {@@ -49,7 +90,10 @@ export default wrap(async (req, res) => {// Positional-parameter WHERE — the Neon client doesn't interpolate nested// sql`` fragments (same pattern as api/animations/clips.js).+ const rotation = await rotationOrNone();const params = [];+ const rotationFree = rotationFreeSql(rotation, params);+ const effectivePrice = `(case when ${rotationFree} then null else c.price_amount end)`;const conds = ['c.listed = true', 'c.deleted_at is null', 'c.artifact_key is not null'];if (q) {@@ -64,8 +108,8 @@ export default wrap(async (req, res) => {params.push(kind);conds.push(`c.kind = $${params.length}`);}- if (price === 'free') conds.push('(c.price_amount is null or c.price_amount <= 0)');- if (price === 'paid') conds.push('c.price_amount > 0');+ if (price === 'free') conds.push(`(${effectivePrice} is null or ${effectivePrice} <= 0)`);+ if (price === 'paid') conds.push(`${effectivePrice} > 0`);if (cursor) {const decoded = decodeCursor(cursor);if (decoded) {@@ -78,10 +122,11 @@ export default wrap(async (req, res) => {let rows;try {rows = await sql(- `select c.id, c.slug, c.name, c.description, c.kind, c.duration_ms,+ `select c.id, c.owner_id, c.slug, c.name, c.description, c.kind, c.duration_ms,c.frame_count, c.fps, c.loop, c.tags, c.thumbnail_key,c.price_amount, c.price_currency, c.artifact_bytes,c.play_count, c.purchase_count, c.created_at,+ ${effectivePrice} as effective_price,u.display_name as creator_name, u.username as creator_username,u.avatar_url as creator_avatarfrom animation_clips c@@ -98,7 +143,7 @@ export default wrap(async (req, res) => {const hasMore = rows.length > limit;const page = hasMore ? rows.slice(0, limit) : rows;- const items = page.map(shape);+ const items = page.map((row) => shape(row, rotation));const nextCursor = hasMore ? encodeCursor({ createdAt: rows[limit - 1].created_at }) : null;res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');@@ -110,7 +155,7 @@ async function handleOne(res, id) {let row;try {[row] = await sql`- select c.id, c.slug, c.name, c.description, c.kind, c.duration_ms,+ select c.id, c.owner_id, c.slug, c.name, c.description, c.kind, c.duration_ms,c.frame_count, c.fps, c.loop, c.tags, c.thumbnail_key,c.price_amount, c.price_currency, c.artifact_bytes,c.play_count, c.purchase_count, c.created_at,@@ -127,12 +172,16 @@ async function handleOne(res, id) {return error(res, 500, 'db_error', 'Failed to load animation');}if (!row) return error(res, 404, 'not_found', 'animation listing not found');+ const rotation = await rotationOrNone();res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');- return json(res, 200, { item: shape(row) });+ return json(res, 200, { item: shape(row, rotation) });}-function shape(row) {- const paid = row.price_amount != null && Number(row.price_amount) > 0;+function shape(row, rotation = { platformId: null, free: new Set() }) {+ const listPaid = row.price_amount != null && Number(row.price_amount) > 0;+ const rotating = listPaid && isFreeGeneratedListing(row, rotation);+ const paid = listPaid && !rotating;+ const generated = !!rotation.platformId && row.owner_id === rotation.platformId && (row.tags || []).includes(GENERATED_TAG);return {id: row.id,slug: row.slug,@@ -148,6 +197,12 @@ function shape(row) {thumbnail_url: thumbnailUrl(row.thumbnail_key),price: paid ? { amount: String(row.price_amount), currency: row.price_currency || 'USDC' } : null,free: !paid,+ // Set only while a generated listing is in this week's free rotation:+ // what it normally costs, and when the rotation moves on.+ free_rotation: rotating+ ? { regular_price: { amount: String(row.price_amount), currency: row.price_currency || 'USDC' }, until: freeEpochEndsAt() }+ : null,+ generated,size_bytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : null,play_count: Number(row.play_count || 0),purchase_count: Number(row.purchase_count || 0),@@ -181,4 +236,4 @@ function decodeCursor(cursor) {}}-export const __test__ = { shape, encodeCursor, decodeCursor, SORTS };+export const __test__ = { shape, encodeCursor, decodeCursor, SORTS, rotationFreeSql };diff --git a/api/x402/animation-download.js b/api/x402/animation-download.jsindex d8cd9fd60..33c7ca027 100644--- a/api/x402/animation-download.js+++ b/api/x402/animation-download.js@@ -20,6 +20,7 @@ import { presignGet } from '../_lib/r2.js';import { cors, error, json } from '../_lib/http.js';import { env } from '../_lib/env.js';import animationDownloadListing from '../_lib/service-catalog/services/animation-download.js';+import { generatedRotation, isFreeGeneratedListing } from '../_lib/generated-clip-market.js';const ROUTE = '/api/x402/animation-download';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -85,7 +86,7 @@ const BAZAAR = {async function loadListing(id) {const rows = await sql`- select id, slug, name, listed, price_amount, price_currency, artifact_key,+ select id, owner_id, slug, tags, name, listed, price_amount, price_currency, artifact_key,artifact_mime, artifact_bytes, creator_payto_base,creator_payto_solana, creator_payto_bscfrom animation_clips@@ -157,6 +158,17 @@ function sendDiscoveryChallenge(res, errText) {});}+// The rotation is a DB read; if it fails the clip is charged its stored price,+// which is the safe direction to fail in for a paid product.+async function inFreeRotation(row) {+ try {+ return isFreeGeneratedListing(row, await generatedRotation());+ } catch (err) {+ console.warn('[animation-download] free rotation unavailable', err?.message || err);+ return false;+ }+}+// Exported for contract tests (price/statement/payout logic) without a live DB.export const __test__ = { priceAtomics, buildSiwxStatement, buildPayToOverride, UUID_RE };@@ -199,8 +211,10 @@ export default async function handler(req, res) {);}- // Free listing — no paywall, hand back the presigned URL directly.- if (!row.price_amount || Number(row.price_amount) <= 0) {+ // Free listing — no paywall, hand back the presigned URL directly. That+ // includes a generated listing in this week's free rotation, which keeps its+ // stored price and is simply not charged while the rotation holds it.+ if (!row.price_amount || Number(row.price_amount) <= 0 || (await inFreeRotation(row))) {try {res.setHeader('Cache-Control', 'no-store');return json(res, 200, await presignPayload(row));diff --git a/scripts/gcp/seed-motion.mjs b/scripts/gcp/seed-motion.mjsindex 36a6c2636..1325cc12e 100644--- a/scripts/gcp/seed-motion.mjs+++ b/scripts/gcp/seed-motion.mjs@@ -24,6 +24,7 @@* node scripts/gcp/seed-motion.mjs --publish # upload + manifest* node scripts/gcp/seed-motion.mjs --report # checkpoint stats only* node scripts/gcp/seed-motion.mjs --repair --publish # fix the live library+ * node scripts/gcp/seed-motion.mjs --list # list the keepers for sale** REPAIRING THE PUBLISHED SET. --repair reads every generated clip already live* in the library, converts it out of the generator's identity rest basis into the@@ -40,6 +41,15 @@* third-party lane the batch aborts immediately rather than quietly billing a* few hundred generations to someone else's API.*+ * LISTING. --list bakes every published keeper onto the platform rig+ * (public/avatars/default.glb) as a GLB, uploads it under+ * animations/library/generated/glb/, and upserts one animation_clips row per+ * clip under the platform account, so the collection sells through+ * GET /api/marketplace/animations and the x402 animation-download route. A clip+ * that is no longer published is delisted. Price and the rotating free subset+ * follow api/_lib/generated-clip-market.js; --price=<USDC> overrides the price.+ * Needs the storage credentials below plus DATABASE_URL.+ ** PUBLISHING. --publish needs the R2 credentials the production API uses* (S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET,* S3_PUBLIC_DOMAIN). Clips go to animations/library/generated/clips/ and the@@ -90,6 +100,7 @@ const RETRY_REJECTS = !!args['retry-rejects'];const PUBLISH = !!args.publish;const REPORT_ONLY = !!args.report;const REPAIR = !!args.repair;+const LIST = !!args.list;// Independent samples to draw per prompt. The sampler is stochastic, so the// same prompt yields a different take every time; several takes per prompt is// how a 137-prompt library grows into several hundred clips while the gate@@ -411,6 +422,15 @@ function gateWithBasis(clip, prompt) {return verdict;}+/** Accepted takes recorded for a prompt so far. */+function keepersOf(state, promptId) {+ let n = 0;+ for (const record of Object.values(state.prompts)) {+ if (record.status === 'accepted' && record.prompt_id === promptId) n++;+ }+ return n;+}+/** Checkpoint key for one take of one prompt. Take 0 keeps the bare id, so* checkpoints written before --samples existed resume unchanged. */function sampleKey(prompt) {@@ -468,8 +488,14 @@ function report(state) {function stagedManifestEntries(state, publicDomain) {const entries = [];- for (const record of Object.values(state.prompts)) {- if (record.status !== 'accepted') continue;+ const perPrompt = {};+ // Lowest take first, so the cap keeps the same clips on every publish.+ const accepted = Object.values(state.prompts)+ .filter((r) => r.status === 'accepted')+ .sort((a, b) => (a.sample ?? 0) - (b.sample ?? 0) || a.name.localeCompare(b.name));+ for (const record of accepted) {+ perPrompt[record.prompt_id] = (perPrompt[record.prompt_id] || 0) + 1;+ if (perPrompt[record.prompt_id] > KEEP_PER_PROMPT) continue;const file = join(CLIPS_DIR, `${record.name}.json`);if (!existsSync(file)) continue;entries.push({@@ -487,7 +513,7 @@ function stagedManifestEntries(state, publicDomain) {return entries.sort((a, b) => a.name.localeCompare(b.name));}-async function publish(state) {+async function storage(step) {const endpoint =process.env.S3_ENDPOINT ||(process.env.R2_ACCOUNT_ID ? `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com` : null);@@ -497,14 +523,20 @@ async function publish(state) {const publicDomain = (process.env.S3_PUBLIC_DOMAIN || '').replace(/\/+$/, '');if (!endpoint || !accessKeyId || !secretAccessKey || !bucket || !publicDomain) {- log(' publish skipped: storage credentials are not set in this environment.');+ log(` ${step} skipped: storage credentials are not set in this environment.`);log(' Needs S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET, S3_PUBLIC_DOMAIN');log(' (they live on the three-ws-api Cloud Run service, not in the repo).');- return { published: 0 };+ return null;}-const { S3Client, PutObjectCommand } = await import('@aws-sdk/client-s3');const client = new S3Client({ region: 'auto', endpoint, credentials: { accessKeyId, secretAccessKey } });+ return { client, PutObjectCommand, bucket, publicDomain };+}++async function publish(state) {+ const store = await storage('publish');+ if (!store) return { published: 0 };+ const { client, PutObjectCommand, bucket, publicDomain } = store;const entries = stagedManifestEntries(state, publicDomain);let uploaded = 0;@@ -536,6 +568,98 @@ async function publish(state) {return { published: entries.length };}+// ── List for sale ────────────────────────────────────────────────────────────++/**+ * Bake every published keeper onto the platform rig and list it in the+ * marketplace under the platform account. Idempotent: a re-run re-bakes and+ * updates rows in place (purchase and play counts survive), and a clip that is+ * no longer in the published set is delisted rather than deleted, so a buyer's+ * SIWX re-download grant still resolves to a row.+ */+async function listForSale(state) {+ const store = await storage('listing');+ if (!store) return { listed: 0 };+ if (!process.env.DATABASE_URL) {+ log(' listing skipped: DATABASE_URL is not set (it lives in .env.local).');+ return { listed: 0 };+ }+ const { client, PutObjectCommand, bucket, publicDomain } = store;+ const { sql } = await import('../../api/_lib/db.js');+ const { bakeMotionGlb } = await import('../../api/_lib/motion-glb.js');+ const market = await import('../../api/_lib/generated-clip-market.js');++ const [owner] = await sql`select id from users where lower(email::text) = ${market.PLATFORM_CREATOR_EMAIL} limit 1`;+ if (!owner) throw new Error(`platform account ${market.PLATFORM_CREATOR_EMAIL} does not exist; nothing can be listed under it`);++ const price = args.price !== undefined ? Number(args.price) : market.generatedListingPrice();+ if (!Number.isFinite(price) || price < 0) throw new Error(`--price must be a non-negative USDC amount, got ${args.price}`);+ const rig = readFileSync(join(ROOT, 'public/avatars/default.glb'));+ const entries = stagedManifestEntries(state, publicDomain);+ const prompts = new Map(loadPrompts().map((p) => [p.id, p]));+ log(`Listing ${entries.length} generated clips at ${price} USDC under ${market.PLATFORM_CREATOR_EMAIL}`);++ let listed = 0;+ for (const entry of entries) {+ const clip = JSON.parse(readFileSync(join(CLIPS_DIR, `${entry.name}.json`), 'utf8'));+ // A clip already in the library basis has had its drift removed and, for+ // a travelling clip, its real root motion restored; flattening it again+ // would turn a walk back into a treadmill. Only a legacy clip is flattened.+ const { glb } = bakeMotionGlb({ rig, clip, name: entry.label || entry.name, flatten: needsRebase(clip) });+ const artifactKey = `${market.GENERATED_GLB_PREFIX}/${entry.name}.glb`;+ await client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: artifactKey,+ Body: glb,+ ContentType: 'model/gltf-binary',+ CacheControl: 'private, max-age=31536000, immutable',+ }),+ );+ const promptId = clip.userData?.prompt_id;+ const row = market.generatedListingRow(entry, clip, {+ ownerId: owner.id,+ price,+ artifactKey,+ artifactBytes: glb.length,+ tags: prompts.get(promptId)?.tags ?? [],+ });+ const storageKey = `${R2_PREFIX}/clips/${entry.name}.json`;+ await sql`+ insert into animation_clips+ (owner_id, slug, name, description, kind, format, duration_ms, frame_count, fps, loop,+ storage_key, tags, visibility, price_amount, price_currency,+ artifact_key, artifact_bytes, artifact_mime, listed)+ values+ (${row.owner_id}, ${row.slug}, ${row.name}, ${row.description}, ${row.kind}, ${row.format},+ ${row.duration_ms}, ${row.frame_count}, ${row.fps}, ${row.loop},+ ${storageKey}, ${row.tags}, ${row.visibility}, ${row.price_amount}, ${row.price_currency},+ ${row.artifact_key}, ${row.artifact_bytes}, ${row.artifact_mime}, ${row.listed})+ on conflict (owner_id, slug) do update set+ name = excluded.name, description = excluded.description, kind = excluded.kind,+ format = excluded.format, duration_ms = excluded.duration_ms,+ frame_count = excluded.frame_count, fps = excluded.fps, loop = excluded.loop,+ storage_key = excluded.storage_key, tags = excluded.tags,+ visibility = excluded.visibility, price_amount = excluded.price_amount,+ price_currency = excluded.price_currency, artifact_key = excluded.artifact_key,+ artifact_bytes = excluded.artifact_bytes, artifact_mime = excluded.artifact_mime,+ listed = true, deleted_at = null+ `;+ listed++;+ if (listed % 25 === 0) log(` listed ${listed}/${entries.length}`);+ }++ const names = entries.map((e) => e.name);+ const delisted = await sql`+ update animation_clips set listed = false+ where owner_id = ${owner.id} and ${market.GENERATED_TAG} = any(tags) and listed = true+ and not (slug = any(${names}::text[]))+ returning slug+ `;+ log(` ${listed} listed, ${delisted.length} delisted (no longer published)`);+ return { listed, delisted: delisted.length };+}+// ── Main ─────────────────────────────────────────────────────────────────────/**@@ -639,6 +763,11 @@ async function main() {return;}+ if (LIST && !PUBLISH && !REPAIR && !args.limit && !args.categories && !args.samples) {+ await listForSale(state);+ return;+ }+if (REPAIR) {const outcome = await repair(state);if (PUBLISH) await publish(state);@@ -658,12 +787,8 @@ async function main() {// partial run covers the whole library before it deepens any one prompt.const takes = [];for (let sample = 0; sample < SAMPLES; sample++) for (const p of prompts) takes.push({ ...p, sample });- const keepers = {};- for (const record of Object.values(state.prompts)) {- if (record.status === 'accepted') keepers[record.prompt_id] = (keepers[record.prompt_id] || 0) + 1;- }const queue = takes- .filter((p) => (keepers[p.id] || 0) < KEEP_PER_PROMPT && shouldRun(state.prompts[sampleKey(p)]))+ .filter((p) => keepersOf(state, p.id) < KEEP_PER_PROMPT && shouldRun(state.prompts[sampleKey(p)])).slice(0, LIMIT);log(`Seeding motion from ${PROMPTS_PATH.replace(`${ROOT}/`, '')}`);@@ -679,6 +804,9 @@ async function main() {const worker = async () => {while (index < queue.length && !aborted) {const prompt = queue[index++];+ // Re-checked at dispatch, not only when the queue was built: an+ // earlier take of this prompt may have landed its last keeper since.+ if (keepersOf(state, prompt.id) >= KEEP_PER_PROMPT) continue;try {const record = await runPrompt(prompt);state.prompts[sampleKey(prompt)] = record;@@ -716,6 +844,7 @@ async function main() {const stats = report(state);if (PUBLISH) await publish(state);+ if (LIST) await listForSale(state);// A batch that gated nothing at all is an infrastructure failure dressed up// as a clean run, so it exits non-zero rather than reporting "0 accepted".diff --git a/src/marketplace.js b/src/marketplace.jsindex 33769e356..38d65d9d2 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -3717,7 +3717,7 @@ function renderCreatorListings() {}grid.innerHTML = filtered.map((it) => {- const priceLabel = it.free ? 'Free' : `${formatPrice(it.price.amount)} ${it.price.currency}`;+ const priceLabel = listingPriceLabel(it);const dur = it.duration ? `${it.duration.toFixed(it.duration % 1 ? 1 : 0)}s` : '';const typeLabel = it.loop !== false ? 'Loop' : 'Action';const thumb = it.thumbnail_url@@ -3751,6 +3751,23 @@ function renderCreatorListings() {});}+// A generated listing in this week's free rotation says so, rather than+// reading as permanently free: the label is what tells a visitor to grab it now.+function listingPriceLabel(it) {+ if (it.free_rotation) return 'Free this week';+ return it.free ? 'Free' : `${formatPrice(it.price.amount)} ${it.price.currency}`;+}++function rotationNote(it) {+ const regular = it.free_rotation?.regular_price;+ const until = it.free_rotation?.until ? new Date(it.free_rotation.until) : null;+ const when = until && !Number.isNaN(until.getTime())+ ? until.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })+ : 'the end of the week';+ const price = regular ? `${formatPrice(regular.amount)} ${regular.currency}` : 'its listed price';+ return `Free this week as part of the rotating generated collection, until ${when}. After that it returns to ${price}. The GLB plays on any three.ws avatar and opens in Blender, Unity or Unreal.`;+}+function formatPrice(amount) {const n = Number(amount);if (!isFinite(n)) return amount;@@ -3845,7 +3862,7 @@ async function openAnimationPurchase(id) {overlay.setAttribute('aria-modal', 'true');overlay.setAttribute('aria-label', `Get ${item.name}`);- const priceLabel = item.free ? 'Free' : `${formatPrice(item.price.amount)} ${item.price.currency}`;+ const priceLabel = listingPriceLabel(item);const endpoint = `${location.origin}${item.download_url}`;const dur = item.duration ? `${item.duration.toFixed(item.duration % 1 ? 1 : 0)}s` : '';const snippet =@@ -3876,7 +3893,9 @@ async function openAnimationPurchase(id) {<div class="anim-buy-actions"><button class="btn-primary anim-buy-go" type="button">${item.free ? 'Download GLB' : `Buy for ${escapeHtml(priceLabel)}`}</button></div>- <p class="anim-buy-note" id="anim-buy-note">${item.free+ <p class="anim-buy-note" id="anim-buy-note">${item.free_rotation+ ? escapeHtml(rotationNote(item))+ : item.free? 'Free download — a self-contained animated GLB that plays on any three.ws avatar.': 'Pay once in USDC (Base or Solana). Re-download free anytime by signing in with the same wallet.'}</p>${item.free ? '' : `diff --git a/tests/api/generated-clip-market.test.js b/tests/api/generated-clip-market.test.jsnew file mode 100644index 000000000..70876acd6--- /dev/null+++ b/tests/api/generated-clip-market.test.js@@ -0,0 +1,266 @@+// The generated animation collection as a marketplace product line+// (api/_lib/generated-clip-market.js): listing rows, the rotating free subset,+// and the two routes that honour it, the marketplace feed and the x402 paid+// download. Driven through the real handlers with the database and object+// storage mocked, so the suite stays offline.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { invoke } from '../_helpers/monetization.js';+import { freeClipNames, FREE_ROTATION } from '../../api/_lib/motion-seed.js';++const PLATFORM_ID = '0a0a0a0a-0000-4000-8000-000000000001';+const CREATOR_ID = '0b0b0b0b-0000-4000-8000-000000000002';+const CLIP_ID = '11111111-2222-4333-8444-555555555555';++// Twenty generated slugs: more than the free subset, so some are paid.+const SLUGS = Array.from({ length: 20 }, (_, i) => `gen-wave-hello-${String(i).padStart(12, '0')}`);++let platformExists = true;+let listingRow = null;+let lastFeedQuery = null;+const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/from users where lower\(email::text\)/i.test(q)) {+ return Promise.resolve(platformExists ? [{ id: PLATFORM_ID }] : []);+ }+ if (/select slug from animation_clips/i.test(q)) return Promise.resolve(SLUGS.map((slug) => ({ slug })));+ if (/creator_payto_base/i.test(q)) return Promise.resolve(listingRow ? [listingRow] : []);+ if (/from animation_clips c/i.test(q)) {+ lastFeedQuery = { q, params: values[0] };+ return Promise.resolve([]);+ }+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));+vi.mock('../../api/_lib/r2.js', () => ({+ presignGet: vi.fn(async ({ key }) => `https://storage.example/${key}?signed=1`),+ thumbnailUrl: (key) => (key ? `https://cdn.example/${key}` : null),+}));++const market = await import('../../api/_lib/generated-clip-market.js');+const { __test__: feed } = await import('../../api/marketplace/animations.js');+const { default: marketplaceAnimations } = await import('../../api/marketplace/animations.js');+const { default: animationDownload } = await import('../../api/x402/animation-download.js');++const freeNow = () => new Set(freeClipNames(SLUGS));++beforeEach(() => {+ platformExists = true;+ listingRow = null;+ lastFeedQuery = null;+ market.resetGeneratedRotationCache();+});++describe('generatedListingRow', () => {+ const clip = {+ duration: 4,+ tracks: [{ name: 'Hips.quaternion', times: Array.from({ length: 121 }, (_, i) => i / 30), values: [] }],+ userData: { prompt: 'a person waves hello', category: 'emote', prompt_id: 'wave-hello' },+ };++ it('lists a clip under the platform account, public, priced, with the generated tag', () => {+ const row = market.generatedListingRow(+ { name: SLUGS[0], label: 'Wave Hello', category: 'emote', loop: false },+ clip,+ { ownerId: PLATFORM_ID, price: 0.01, artifactKey: 'k.glb', artifactBytes: 1234, tags: ['wave'] },+ );+ expect(row).toMatchObject({+ owner_id: PLATFORM_ID,+ slug: SLUGS[0],+ name: 'Wave Hello',+ kind: 'animation',+ loop: false,+ duration_ms: 4000,+ frame_count: 121,+ fps: 30,+ visibility: 'public',+ price_amount: 0.01,+ price_currency: 'USDC',+ artifact_key: 'k.glb',+ artifact_bytes: 1234,+ artifact_mime: 'model/gltf-binary',+ listed: true,+ });+ expect(row.tags).toEqual(['generated', 'emote', 'wave']);+ expect(row.description).toContain('a person waves hello');+ });++ it('marks loops as loops and a zero price as free', () => {+ const row = market.generatedListingRow({ name: SLUGS[1], loop: true }, clip, {+ ownerId: PLATFORM_ID,+ price: 0,+ artifactKey: 'k.glb',+ artifactBytes: 1,+ });+ expect(row.kind).toBe('loop');+ expect(row.price_amount).toBeNull();+ expect(row.price_currency).toBeNull();+ expect(row.name).toBe(SLUGS[1]);+ });++ it('prices at the Animation Bazaar advertised price, overridable by env', () => {+ expect(market.generatedListingPrice()).toBe(0.01);+ process.env.X402_PRICE_ANIMATION_DOWNLOAD = '250000';+ try {+ expect(market.generatedListingPrice()).toBe(0.25);+ } finally {+ delete process.env.X402_PRICE_ANIMATION_DOWNLOAD;+ }+ });+});++describe('generatedRotation', () => {+ it('frees exactly the hashed subset of the whole collection', async () => {+ const rotation = await market.generatedRotation();+ expect(rotation.platformId).toBe(PLATFORM_ID);+ expect(rotation.free.size).toBe(FREE_ROTATION.SIZE);+ expect(rotation.free).toEqual(freeNow());+ });++ it('rotates to a different subset next epoch', async () => {+ const now = Date.now();+ const here = await market.generatedRotation(now);+ const next = await market.generatedRotation(now + FREE_ROTATION.EPOCH_MS);+ expect(next.epoch).toBe(here.epoch + 1);+ expect([...next.free]).not.toEqual([...here.free]);+ });++ it('has nothing to rotate when the platform account is missing', async () => {+ platformExists = false;+ const rotation = await market.generatedRotation();+ expect(rotation.platformId).toBeNull();+ expect(rotation.free.size).toBe(0);+ });++ it('only a platform-owned, generated-tagged listing can be free', async () => {+ const rotation = await market.generatedRotation();+ const slug = [...rotation.free][0];+ const row = { owner_id: PLATFORM_ID, slug, tags: ['generated', 'emote'] };+ expect(market.isFreeGeneratedListing(row, rotation)).toBe(true);+ // A creator tagging their own clip "generated" is not in the rotation.+ expect(market.isFreeGeneratedListing({ ...row, owner_id: CREATOR_ID }, rotation)).toBe(false);+ // Nothing the platform lists by hand is given away by accident.+ expect(market.isFreeGeneratedListing({ ...row, tags: ['emote'] }, rotation)).toBe(false);+ const paidSlug = SLUGS.find((s) => !rotation.free.has(s));+ expect(market.isFreeGeneratedListing({ ...row, slug: paidSlug }, rotation)).toBe(false);+ });+});++describe('marketplace feed', () => {+ const baseRow = {+ id: CLIP_ID,+ owner_id: PLATFORM_ID,+ name: 'Wave Hello',+ kind: 'animation',+ duration_ms: 4000,+ tags: ['generated', 'emote'],+ price_amount: '0.010000000',+ price_currency: 'USDC',+ creator_name: 'three-ws',+ };++ it('reports a rotating clip as free with its regular price and end date', async () => {+ const rotation = await market.generatedRotation();+ const slug = [...rotation.free][0];+ const out = feed.shape({ ...baseRow, slug }, rotation);+ expect(out.free).toBe(true);+ expect(out.price).toBeNull();+ expect(out.generated).toBe(true);+ expect(out.free_rotation.regular_price).toEqual({ amount: '0.010000000', currency: 'USDC' });+ expect(new Date(out.free_rotation.until).getTime()).toBeGreaterThan(Date.now());+ });++ it('reports the rest of the collection at its price', async () => {+ const rotation = await market.generatedRotation();+ const slug = SLUGS.find((s) => !rotation.free.has(s));+ const out = feed.shape({ ...baseRow, slug }, rotation);+ expect(out.free).toBe(false);+ expect(out.price).toEqual({ amount: '0.010000000', currency: 'USDC' });+ expect(out.free_rotation).toBeNull();+ expect(out.generated).toBe(true);+ });++ it('leaves creator listings untouched', async () => {+ const rotation = await market.generatedRotation();+ const out = feed.shape({ ...baseRow, owner_id: CREATOR_ID, slug: [...rotation.free][0] }, rotation);+ expect(out.free).toBe(false);+ expect(out.generated).toBe(false);+ });++ it('builds a parameterised rotation predicate, constant false without a rotation', () => {+ const params = ['x'];+ const sqlText = feed.rotationFreeSql({ platformId: PLATFORM_ID, free: new Set(['a', 'b']) }, params);+ expect(sqlText).toBe('(c.owner_id = $2 and $3 = any(c.tags) and c.slug = any($4::text[]))');+ expect(params).toEqual(['x', PLATFORM_ID, 'generated', ['a', 'b']]);+ expect(feed.rotationFreeSql({ platformId: null, free: new Set() }, [])).toBe('false');+ });++ it('treats rotating clips as free in the ?price= filter', async () => {+ const { status } = await invoke(marketplaceAnimations, { url: '/api/marketplace/animations?price=free' });+ expect(status).toBe(200);+ expect(lastFeedQuery.q).toMatch(/case when \(c\.owner_id = \$1 and \$2 = any\(c\.tags\) and c\.slug = any\(\$3::text\[\]\)\) then null else c\.price_amount end\) is null/);+ expect(lastFeedQuery.params.slice(0, 3)).toEqual([PLATFORM_ID, 'generated', [...freeNow()]]);+ });+});++describe('x402 animation download', () => {+ // The paid path needs a platform payout address to quote in its challenge.+ // A synthetic one: the challenge is only built, nothing is ever settled.+ let prevPayTo;+ beforeEach(() => {+ prevPayTo = process.env.X402_PAY_TO_SOLANA;+ process.env.X402_PAY_TO_SOLANA = 'THREEsynthetic111111111111111111111111111111';+ });+ afterEach(() => {+ if (prevPayTo === undefined) delete process.env.X402_PAY_TO_SOLANA;+ else process.env.X402_PAY_TO_SOLANA = prevPayTo;+ });++ const listing = (slug, ownerId = PLATFORM_ID) => ({+ id: CLIP_ID,+ owner_id: ownerId,+ slug,+ tags: ['generated', 'emote'],+ name: 'Wave Hello',+ listed: true,+ price_amount: '0.010000000',+ price_currency: 'USDC',+ artifact_key: `animations/library/generated/glb/${slug}.glb`,+ artifact_mime: 'model/gltf-binary',+ artifact_bytes: '4096',+ creator_payto_base: null,+ creator_payto_solana: null,+ creator_payto_bsc: null,+ });++ it('hands a rotating clip over without payment', async () => {+ const slug = [...freeNow()][0];+ listingRow = listing(slug);+ const { status, body } = await invoke(animationDownload, {+ url: `/api/x402/animation-download?id=${CLIP_ID}`,+ query: { id: CLIP_ID },+ });+ expect(status).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.downloadUrl).toContain(`${slug}.glb`);+ });++ it('charges for a generated clip outside the rotation', async () => {+ const slug = SLUGS.find((s) => !freeNow().has(s));+ listingRow = listing(slug);+ const { status } = await invoke(animationDownload, {+ url: `/api/x402/animation-download?id=${CLIP_ID}`,+ query: { id: CLIP_ID },+ });+ expect(status).toBe(402);+ });++ it('charges a creator listing even when its slug collides with a free one', async () => {+ listingRow = listing([...freeNow()][0], CREATOR_ID);+ const { status } = await invoke(animationDownload, {+ url: `/api/x402/animation-download?id=${CLIP_ID}`,+ query: { id: CLIP_ID },+ });+ expect(status).toBe(402);+ });+});diff --git a/tests/motion-seed.test.js b/tests/motion-seed.test.jsindex 37178a05f..fa36d535a 100644--- a/tests/motion-seed.test.js+++ b/tests/motion-seed.test.js@@ -38,6 +38,10 @@ import {maxUprightGap,uprightGap,CLIP_BASIS,+ despikeFootFlicks,+ lockRootToContacts,+ forwardKinematicsFrame,+ ROOT_LOCK,} from '../api/_lib/motion-seed.js';import { CANONICAL_REST } from '../src/animation-canonical-rest.js';@@ -595,3 +599,120 @@ describe('root drift', () => {expect(result.clip).toBe(clip);});});++describe('foot flicks', () => {+ /** Toe position relative to its ankle, the quantity a flick disturbs. */+ function toeRel(clip, frame) {+ const w = forwardKinematicsFrame(clip, frame);+ return w.LeftToeBase.map((v, k) => v - w.LeftFoot[k]);+ }++ /** Swing the left foot away from its neighbours on the given frames only. */+ function flicked(frames) {+ const clip = buildClip();+ const track = clip.tracks.find((t) => t.name === 'LeftFoot.quaternion');+ for (const f of frames) {+ const q = track.values.slice(f * 4, f * 4 + 4);+ const swung = quatMul(q, quatX(1.4));+ for (let k = 0; k < 4; k += 1) track.values[f * 4 + k] = swung[k];+ }+ return clip;+ }++ it('repairs a one-frame flick back onto the line between its neighbours', () => {+ const clip = flicked([40]);+ const before = Math.hypot(...toeRel(clip, 40).map((v, k) => v - toeRel(clip, 39)[k]));+ expect(before).toBeGreaterThan(0.03);+ const { clip: fixed, repaired } = despikeFootFlicks(clip);+ expect(repaired).toBe(1);+ const after = Math.hypot(...toeRel(fixed, 40).map((v, k) => v - toeRel(fixed, 39)[k]));+ expect(after).toBeLessThan(0.01);+ });++ it('repairs a two-frame excursion as one span', () => {+ const { repaired } = despikeFootFlicks(flicked([60, 61]));+ expect(repaired).toBe(2);+ });++ it('leaves a clip with no flicks untouched', () => {+ const clip = buildClip();+ const result = despikeFootFlicks(clip);+ expect(result.repaired).toBe(0);+ expect(result.clip).toBe(clip);+ });++ it('does not treat a held change of foot pose as a flick', () => {+ // Frames 40 onward all turn the foot: a real, held movement, not a spike.+ const frames = Array.from({ length: 80 }, (_, i) => 40 + i);+ const { repaired } = despikeFootFlicks(flicked(frames));+ expect(repaired).toBe(0);+ });+});++describe('root travel from foot contact', () => {+ /**+ * A treadmill: the body stays put while the planted left leg sweeps under+ * it, and the right leg is held up off the floor so the left is always the+ * one bearing weight. With the root pinned, the planted foot skates.+ */+ function treadmill({ sweep = 0.3, frames = 31 } = {}) {+ const clip = buildClip({ frames, swing: 0 });+ const left = clip.tracks.find((t) => t.name === 'LeftUpLeg.quaternion');+ const right = clip.tracks.find((t) => t.name === 'RightUpLeg.quaternion');+ for (let i = 0; i < frames; i += 1) {+ const angle = -sweep / 2 + (sweep * i) / (frames - 1);+ const l = quatMul(CANONICAL_REST.LeftUpLeg, quatX(angle));+ const r = quatMul(CANONICAL_REST.RightUpLeg, quatX(0.6));+ for (let k = 0; k < 4; k += 1) {+ left.values[i * 4 + k] = l[k];+ right.values[i * 4 + k] = r[k];+ }+ }+ const hips = clip.tracks.find((t) => t.name === 'Hips.position');+ for (let i = 0; i < frames; i += 1) hips.values[i * 3 + 1] = 0.984;+ return clip;+ }++ it('gives a striding clip the travel its planted foot implies', () => {+ const clip = treadmill();+ const before = footContactMetrics(clip);+ const locked = lockRootToContacts(clip);+ expect(locked.applied).toBe(true);+ expect(locked.speed).toBeGreaterThan(ROOT_LOCK.MIN_SPEED);+ const after = footContactMetrics(locked.clip);+ expect(after.slide).toBeLessThan(before.slide * 0.25);+ expect(after.stride).toBeGreaterThan(before.stride);+ });++ it('keeps the root of a clip that stands still', () => {+ const clip = buildClip({ swing: 0.05 });+ const locked = lockRootToContacts(clip);+ expect(locked.applied).toBe(false);+ expect(locked.clip).toBe(clip);+ });++ it('never touches vertical travel', () => {+ const clip = treadmill();+ const y = (c) => c.tracks.find((t) => t.name === 'Hips.position').values.filter((_, i) => i % 3 === 1);+ expect(y(lockRootToContacts(clip).clip)).toEqual(y(clip));+ });++ it('trusts nothing when no foot is ever planted', () => {+ // Floor work: the hips pinned low with the knees folded under the body,+ // the same construction the foot-contact suite uses, so no foot bears+ // weight and there is no plant to derive travel from.+ const clip = treadmill();+ const hips = clip.tracks.find((t) => t.name === 'Hips.position');+ for (let i = 0; i < hips.values.length / 3; i += 1) hips.values[i * 3 + 1] = 0.15;+ for (const bone of ['LeftLeg', 'RightLeg']) {+ const track = clip.tracks.find((t) => t.name === `${bone}.quaternion`);+ const folded = quatMul(CANONICAL_REST[bone], quatX(2.2));+ for (let i = 0; i < track.values.length; i += 4) {+ [track.values[i], track.values[i + 1], track.values[i + 2], track.values[i + 3]] = folded;+ }+ }+ const locked = lockRootToContacts(clip);+ expect(locked.applied).toBe(false);+ expect(locked.contactShare).toBeLessThan(ROOT_LOCK.MIN_CONTACT_SHARE);+ });+});