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.

Add embed.html for Embodiment Stage with dynamic persona loading and overlay support

udvkf49b2f92b4ce
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index a4f33ba6c..7ca4c91b3 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -405,6 +405,93 @@ export async function getPublicCreation({ id }) {
}
}
+// Record a refinement: a new creation derived from an existing one. Inserts into
+// forge_creations with parent_creation_id + refine_instruction + lineage_index.
+// Returns the new creation id or null when the store is unavailable.
+export async function createRefinement({
+ clientKey,
+ ipHash,
+ parentCreationId,
+ prompt,
+ refineInstruction,
+ lineageIndex,
+ aspect,
+ backend,
+ tier,
+ path,
+ modelCategory,
+}) {
+ if (!forgeStoreEnabled()) return null;
+ const id = randomUUID();
+ const category = validModelCategory(modelCategory) ?? 'other';
+ try {
+ await sql`
+ insert into forge_creations
+ (id, client_key, ip_hash, prompt, aspect, backend, tier, path,
+ parent_creation_id, refine_instruction, lineage_index,
+ status, outcome, model_category)
+ values
+ (${id}, ${clientKey}, ${ipHash ?? null}, ${prompt}, ${aspect ?? null},
+ ${backend ?? null}, ${tier ?? null}, ${path ?? null},
+ ${parentCreationId ?? null}, ${refineInstruction ?? null},
+ ${typeof lineageIndex === 'number' ? lineageIndex : 0},
+ 'generating', 'generated', ${category})
+ `;
+ await recordGenerationEvent({ phase: 'start', backend, tier, path, source: 'refine' });
+ return id;
+ } catch (err) {
+ console.error('[forge-store] createRefinement failed:', err?.message);
+ return null;
+ }
+}
+
+// Return the full lineage thread rooted at rootCreationId: the root itself plus
+// all descendants in lineage_index order. Fails soft (returns []) when the store
+// is unavailable or the root doesn't exist. The caller reconstructs the tree
+// structure using parent_creation_id + lineage_index.
+export async function getLineage({ rootCreationId, clientKey }) {
+ if (!forgeStoreEnabled() || !rootCreationId) return [];
+ try {
+ // Recursive CTE: walk descendants of the root creation. Up to 50 versions
+ // per thread (a hard cap so a misbehaving recursive loop can't exhaust the
+ // connection pool). Rows are returned newest-first within each lineage_index
+ // so the latest refinement at each depth comes first.
+ const rows = await sql`
+ with recursive thread as (
+ select id, parent_creation_id, prompt, refine_instruction, lineage_index,
+ glb_url, preview_image_url, status, backend, created_at
+ from forge_creations
+ where id = ${rootCreationId}
+ and (${clientKey}::text is null or client_key = ${clientKey})
+ union all
+ select fc.id, fc.parent_creation_id, fc.prompt, fc.refine_instruction,
+ fc.lineage_index, fc.glb_url, fc.preview_image_url, fc.status,
+ fc.backend, fc.created_at
+ from forge_creations fc
+ join thread t on fc.parent_creation_id = t.id
+ )
+ select * from thread
+ order by lineage_index asc, created_at asc
+ limit 50
+ `;
+ return rows.map((r) => ({
+ id: r.id,
+ parent_creation_id: r.parent_creation_id,
+ prompt: r.prompt,
+ refine_instruction: r.refine_instruction,
+ lineage_index: r.lineage_index,
+ glb_url: r.glb_url,
+ preview_image_url: r.preview_image_url,
+ status: r.status,
+ backend: r.backend,
+ created_at: r.created_at,
+ }));
+ } catch (err) {
+ console.error('[forge-store] getLineage failed:', err?.message);
+ return [];
+ }
+}
+
// Newest durable creations for one anonymous client — powers the gallery.
export async function listCreations({ clientKey, limit = 24 }) {
if (!forgeStoreEnabled()) return [];
diff --git a/api/_lib/migrations/20260625000000_forge_refine_lineage.sql b/api/_lib/migrations/20260625000000_forge_refine_lineage.sql
new file mode 100644
index 000000000..4e6ba62d8
--- /dev/null
+++ b/api/_lib/migrations/20260625000000_forge_refine_lineage.sql
@@ -0,0 +1,77 @@
+begin;
+
+-- Forge conversational refinement + remix provenance
+-- ===================================================
+-- Adds the columns needed to record that a forge_creation was produced by
+-- refining or remixing an earlier one:
+--
+-- parent_creation_id — the creation this was derived from (UUID foreign key).
+-- NULL for original (non-derived) generations.
+-- refine_instruction — the natural-language change the user requested, e.g.
+-- "make it metallic". Stored verbatim (not the composed
+-- prompt — the composed prompt is still in `prompt`).
+-- lineage_index — this version's position in the conversation thread
+-- (0 = origin, 1 = first refinement, …). Combined with
+-- parent_creation_id, a full tree can be reconstructed.
+-- remixable — true when the creator opts this model into the
+-- remix bazaar. Only 'done' rows with a stored GLB are
+-- ever surfaced by api/remix-feed.js.
+-- remix_royalty_bps — the creator-set royalty rate in basis points (0–2000).
+-- Stored here so it travels with the record at the time
+-- a remix is initiated; changing it later does not
+-- retroactively alter in-flight remix payments. Capped
+-- and enforced in api/_lib/remix-royalty.js.
+-- creator_wallet_solana — the Solana wallet address to receive remix royalties.
+-- May be set server-side from the authenticated session;
+-- never required for the free lane.
+-- remix_settlement_ref — the last royalty settlement reference for this row as
+-- a REMIX SOURCE (i.e. when another creation derived
+-- from it and the royalty transfer completed). Stored as
+-- JSONB so it can carry { tx_signature, usdc_atomics,
+-- settled_at, remix_creation_id }.
+
+alter table forge_creations
+ add column if not exists parent_creation_id uuid references forge_creations(id) on delete set null,
+ add column if not exists refine_instruction text,
+ add column if not exists lineage_index integer not null default 0,
+ add column if not exists remixable boolean not null default false,
+ add column if not exists remix_royalty_bps integer not null default 1000
+ check (remix_royalty_bps >= 0 and remix_royalty_bps <= 2000),
+ add column if not exists creator_wallet_solana text,
+ add column if not exists remix_settlement_ref jsonb;
+
+-- Walk the parent chain for a thread view (e.g. getLineage).
+create index if not exists forge_creations_parent
+ on forge_creations (parent_creation_id)
+ where parent_creation_id is not null;
+
+-- Power the remix feed: done, stored, opted-in models only.
+create index if not exists forge_creations_remixable
+ on forge_creations (created_at desc)
+ where remixable = true and status = 'done' and glb_url is not null;
+
+comment on column forge_creations.parent_creation_id is
+ 'The creation this was derived from via refine_model or remix. NULL for '
+ 'original (non-derived) generations.';
+comment on column forge_creations.refine_instruction is
+ 'The raw user instruction that produced this refinement ("make it metallic"). '
+ 'The composed prompt (parent prompt + instruction) is stored in the `prompt` '
+ 'column as usual.';
+comment on column forge_creations.lineage_index is
+ 'Position in the conversational thread: 0 = origin, 1 = first refinement, …. '
+ 'Depth in the tree, not a global sequence — two branches from the same parent '
+ 'can share a lineage_index. Use parent_creation_id to reconstruct the full tree.';
+comment on column forge_creations.remixable is
+ 'True when the creator has opted this model into the remix bazaar. The feed '
+ '(api/remix-feed.js) only surfaces done rows with a stored GLB and this flag.';
+comment on column forge_creations.remix_royalty_bps is
+ 'Creator-set royalty rate (0–2000 bps = 0–20%). Clamped at write time. '
+ 'Snapshot in api/x402/remix-asset.js at the moment the remix is paid.';
+comment on column forge_creations.creator_wallet_solana is
+ 'Solana wallet address for remix royalty payouts (set from authenticated '
+ 'session; never required on the free lane).';
+comment on column forge_creations.remix_settlement_ref is
+ 'JSONB record of the last royalty settlement on this creation as a remix '
+ 'SOURCE: { tx_signature, usdc_atomics, settled_at, remix_creation_id }.';
+
+commit;
diff --git a/api/creations.js b/api/creations.js
new file mode 100644
index 000000000..c0ae61bf4
--- /dev/null
+++ b/api/creations.js
@@ -0,0 +1,799 @@
+// Creations — the creator-gallery + remix-economy backend.
+//
+// This is the discovery/remix surface layered ON TOP OF the existing Loom
+// gallery (api/loom.js): Loom remains the single source of truth for "a creation
+// is a forged GLB + prompt + attribution", and this endpoint enriches that feed
+// with the things a *creator-facing* product needs and Loom deliberately omits:
+//
+// · gallery metadata — title, tags, license, type/style, creator binding
+// · remix lineage — parent→child edges, ancestry + descendants
+// · creator aggregates — per-creator creation count, remixes earned, follows
+// · discovery ranking — trending (most-remixed) assets, top creators
+// · signed-ready provenance — an append-only per-creation trail (origin + remix)
+//
+// It never forks Loom: it imports Loom's storage + validators directly so a
+// publish writes one canonical record to the same feed every other surface
+// reads, then attaches the overlay metadata keyed by that record's id. The Loom
+// HTTP/MCP contract is unchanged.
+//
+// ── Storage (Upstash Redis when configured, in-process maps otherwise) ─────────
+// cre:meta:<id> — gallery overlay JSON for a creation
+// cre:children:<parentId> — list of child creation ids (remix lineage)
+// cre:prov:<id> — append-only provenance entries for a creation
+// cre:creator:<key> — creator aggregate record
+// cre:followers:<key> — set (list) of follower ids
+// cre:index — capped list of all overlaid creation ids (newest-first)
+// cre:remixfeed — capped list of recent remix events (for trending window)
+// In dev / tests without Redis the same operations run against module-level maps
+// so the endpoint is fully functional offline — mirroring api/loom.js exactly.
+
+import { randomUUID } from 'node:crypto';
+import { cors, json, error, readJson, wrap, method, setRateLimitHeaders } from './_lib/http.js';
+import { getRedis } from './_lib/redis.js';
+import { clientIp } from './_lib/rate-limit.js';
+import {
+ writeCreation,
+ readOne as loomReadOne,
+ readFeed as loomReadFeed,
+ validateGlbUrl,
+ sanitizePrompt,
+ sanitizeAuthor,
+ sanitizeOptionalString,
+} from './loom.js';
+
+// ── keys + limits ─────────────────────────────────────────────────────────────
+const META_KEY = (id) => `cre:meta:${id}`;
+const CHILDREN_KEY = (id) => `cre:children:${id}`;
+const PROV_KEY = (id) => `cre:prov:${id}`;
+const CREATOR_KEY = (key) => `cre:creator:${key}`;
+const FOLLOWERS_KEY = (key) => `cre:followers:${key}`;
+const INDEX_KEY = 'cre:index';
+const REMIX_FEED_KEY = 'cre:remixfeed';
+
+const INDEX_CAP = 4000;
+const REMIX_FEED_CAP = 2000;
+const DEFAULT_LIMIT = 36;
+const MAX_LIMIT = 120;
+const SCAN_CAP = 600; // how deep we read the Loom feed for aggregation/search
+const TITLE_MAX = 80;
+const TAG_MAX = 24;
+const TAGS_MAX = 8;
+const NOTE_MAX = 240;
+
+// License terms a creator can attach. Kept as a closed vocabulary so the gallery
+// can render a consistent, legible badge + remix-permission signal per item.
+const LICENSES = {
+ 'remix-cc': { label: 'Remix freely', remixable: true, commercial: true, note: 'Anyone may remix and use commercially.' },
+ 'remix-nc': { label: 'Remix · non-commercial', remixable: true, commercial: false, note: 'Remix freely; no commercial use.' },
+ 'remix-royalty': { label: 'Remix · royalty', remixable: true, commercial: true, note: 'Remix allowed; royalties route to the original creator on mint.' },
+ 'all-rights': { label: 'All rights reserved', remixable: false, commercial: false, note: 'Display only — no remixing.' },
+};
+const DEFAULT_LICENSE = 'remix-cc';
+
+// Style + type vocabularies power the discovery filters. Free-text tags still
+// flow through search; these are the curated facets.
+const STYLES = ['realistic', 'stylized', 'lowpoly', 'voxel', 'sci-fi', 'fantasy', 'cute', 'abstract'];
+const TYPES = ['avatar', 'character', 'creature', 'prop', 'vehicle', 'environment', 'scene', 'object'];
+
+// ── in-memory fallback ─────────────────────────────────────────────────────────
+const mem = {
+ meta: new Map(),
+ children: new Map(), // parentId -> string[] childIds
+ prov: new Map(), // id -> entry[]
+ creators: new Map(),
+ followers: new Map(), // key -> Set
+ index: [], // newest-first ids
+ remixFeed: [], // newest-first remix events
+};
+
+function safeParse(s) {
+ if (s && typeof s === 'object') return s;
+ try {
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
+}
+
+// ── overlay storage abstraction ────────────────────────────────────────────────
+
+async function getMeta(id) {
+ if (!id) return null;
+ const r = getRedis();
+ if (!r) return mem.meta.get(id) || null;
+ const raw = await r.get(META_KEY(id));
+ return raw ? safeParse(raw) : null;
+}
+
+async function putMeta(meta) {
+ const r = getRedis();
+ if (!r) {
+ mem.meta.set(meta.id, meta);
+ mem.index.unshift(meta.id);
+ if (mem.index.length > INDEX_CAP) mem.index.length = INDEX_CAP;
+ return meta;
+ }
+ const payload = JSON.stringify(meta);
+ await r.set(META_KEY(meta.id), payload);
+ await r.lpush(INDEX_KEY, meta.id);
+ await r.ltrim(INDEX_KEY, 0, INDEX_CAP - 1);
+ return meta;
+}
+
+async function getChildren(id) {
+ const r = getRedis();
+ if (!r) return mem.children.get(id) || [];
+ const raw = await r.lrange(CHILDREN_KEY(id), 0, 199);
+ return (raw || []).filter(Boolean);
+}
+
+async function addChild(parentId, childId) {
+ const r = getRedis();
+ if (!r) {
+ const arr = mem.children.get(parentId) || [];
+ if (!arr.includes(childId)) arr.unshift(childId);
+ mem.children.set(parentId, arr);
+ return;
+ }
+ await r.lpush(CHILDREN_KEY(parentId), childId);
+ await r.ltrim(CHILDREN_KEY(parentId), 0, 199);
+}
+
+async function appendProvenance(id, entry) {
+ const r = getRedis();
+ if (!r) {
+ const arr = mem.prov.get(id) || [];
+ arr.push(entry);
+ mem.prov.set(id, arr);
+ return;
+ }
+ await r.rpush(PROV_KEY(id), JSON.stringify(entry));
+ await r.ltrim(PROV_KEY(id), -50, -1);
+}
+
+async function getProvenance(id) {
+ const r = getRedis();
+ if (!r) return mem.prov.get(id) || [];
+ const raw = await r.lrange(PROV_KEY(id), 0, 49);
+ return (raw || []).map(safeParse).filter(Boolean);
+}
+
+async function getCreator(key) {
+ const r = getRedis();
+ if (!r) return mem.creators.get(key) || null;
+ const raw = await r.get(CREATOR_KEY(key));
+ return raw ? safeParse(raw) : null;
+}
+
+async function putCreator(rec) {
+ const r = getRedis();
+ if (!r) {
+ mem.creators.set(rec.key, rec);
+ return rec;
+ }
+ await r.set(CREATOR_KEY(rec.key), JSON.stringify(rec));
+ return rec;
+}
+
+// Touch (create or update) a creator aggregate as creations/remixes land.
+async function touchCreator({ key, displayName, agentId, creationId, earnedRemix }) {
+ const existing = (await getCreator(key)) || {
+ key,
+ displayName: displayName || key,
+ agentId: agentId || null,
+ creationIds: [],
+ remixesEarned: 0,
+ createdAt: Date.now(),
+ };
+ if (displayName) existing.displayName = displayName;
+ if (agentId) existing.agentId = agentId;
+ if (creationId && !existing.creationIds.includes(creationId)) {
+ existing.creationIds.unshift(creationId);
+ if (existing.creationIds.length > 500) existing.creationIds.length = 500;
+ }
+ if (earnedRemix) existing.remixesEarned = (existing.remixesEarned || 0) + 1;
+ existing.updatedAt = Date.now();
+ await putCreator(existing);
+ return existing;
+}
+
+async function followerCount(key) {
+ const r = getRedis();
+ if (!r) return (mem.followers.get(key) || new Set()).size;
+ return (await r.scard(FOLLOWERS_KEY(key))) || 0;
+}
+
+async function isFollowing(key, followerId) {
+ if (!followerId) return false;
+ const r = getRedis();
+ if (!r) return (mem.followers.get(key) || new Set()).has(followerId);
+ return Boolean(await r.sismember(FOLLOWERS_KEY(key), followerId));
+}
+
+async function setFollow(key, followerId, follow) {
+ const r = getRedis();
+ if (!r) {
+ const set = mem.followers.get(key) || new Set();
+ if (follow) set.add(followerId);
+ else set.delete(followerId);
+ mem.followers.set(key, set);
+ return;
+ }
+ if (follow) await r.sadd(FOLLOWERS_KEY(key), followerId);
+ else await r.srem(FOLLOWERS_KEY(key), followerId);
+}
+
+async function pushRemixEvent(ev) {
+ const r = getRedis();
+ if (!r) {
+ mem.remixFeed.unshift(ev);
+ if (mem.remixFeed.length > REMIX_FEED_CAP) mem.remixFeed.length = REMIX_FEED_CAP;
+ return;
+ }
+ await r.lpush(REMIX_FEED_KEY, JSON.stringify(ev));
+ await r.ltrim(REMIX_FEED_KEY, 0, REMIX_FEED_CAP - 1);
+}
+
+async function readRemixEvents(limit = REMIX_FEED_CAP) {
+ const r = getRedis();
+ if (!r) return mem.remixFeed.slice(0, limit);
+ const raw = await r.lrange(REMIX_FEED_KEY, 0, limit - 1);
+ return (raw || []).map(safeParse).filter(Boolean);
+}
+
+// ── identity helpers ───────────────────────────────────────────────────────────
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function slugifyAuthor(author) {
+ const s = String(author || 'anon')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+ return s || 'anon';
+}
+
+// A creator key is either an agent UUID (when a creation is bound to an agent) or
+// a slug derived from the free-text author. Resolving a creation to its creator
+// prefers an explicit agent binding, then the slug.
+function creatorKeyFor(creation, meta) {
+ if (meta?.agentId && UUID_RE.test(meta.agentId)) return meta.agentId;
+ if (meta?.creatorKey) return meta.creatorKey;
+ return slugifyAuthor(creation?.author);
+}
+
+function isAgentKey(key) {
+ return UUID_RE.test(String(key || ''));
+}
+
+// ── creation enrichment ─────────────────────────────────────────────────────────
+
+// Merge a raw Loom creation with its gallery overlay + lineage counts into the
+// shape the creator gallery renders. Defensive: a creation with no overlay (every
+// pre-existing Loom item) still renders fully — title falls back to the prompt,
+// license to the open default, type/style inferred from tags/prompt.
+async function enrich(creation, { withChildren = false } = {}) {
+ if (!creation) return null;
+ const meta = await getMeta(creation.id);
+ const childIds = await getChildren(creation.id);
+ const creatorKey = creatorKeyFor(creation, meta);
+ const inferred = inferFacets(creation, meta);
+ const out = {
+ id: creation.id,
+ prompt: creation.prompt,
+ title: meta?.title || titleFromPrompt(creation.prompt),
+ glbUrl: creation.glbUrl,
+ previewImageUrl: creation.previewImageUrl || null,
+ author: creation.author || 'anon',
+ creatorKey,
+ creatorIsAgent: isAgentKey(creatorKey),
+ tier: creation.tier || null,
+ backend: creation.backend || null,
+ type: meta?.type || inferred.type,
+ style: meta?.style || inferred.style,
+ tags: meta?.tags || inferred.tags,
+ license: meta?.license || DEFAULT_LICENSE,
+ licenseInfo: LICENSES[meta?.license || DEFAULT_LICENSE],
+ parentId: meta?.parentId || null,
+ royalty: meta?.royalty || null,
+ createdAt: Number(creation.createdAt) || meta?.publishedAt || 0,
+ remixCount: childIds.length,
+ viewerUrl: `/creation/${creation.id}`,
+ embedUrl: `/forge/embed?src=${encodeURIComponent(creation.glbUrl)}&title=${encodeURIComponent(meta?.title || titleFromPrompt(creation.prompt))}`,
+ };
+ if (withChildren) out.childIds = childIds;
+ return out;
+}
+
+function titleFromPrompt(prompt) {
+ const p = String(prompt || '').trim();
+ if (!p) return 'Untitled creation';
+ const firstClause = p.split(/[.,;\n]/)[0].trim();
+ const words = firstClause.split(/\s+/).slice(0, 7).join(' ');
+ return (words || p.slice(0, 48)).replace(/^[a-z]/, (c) => c.toUpperCase());
+}
+
+// Best-effort facet inference for legacy/un-overlaid creations so filters and
+// badges still have something real to show. Keyword-matched against prompt+tags.
+function inferFacets(creation, meta) {
+ const hay = `${creation?.prompt || ''} ${(meta?.tags || []).join(' ')}`.toLowerCase();
+ const type = TYPES.find((t) => hay.includes(t)) || (hay.match(/\b(robot|knight|hero|girl|boy|man|woman|warrior)\b/) ? 'character' : 'object');
+ const style = STYLES.find((s) => hay.includes(s.replace('-', ' ')) || hay.includes(s)) || null;
+ const tags = Array.from(
+ new Set(
+ String(creation?.prompt || '')
+ .toLowerCase()
+ .replace(/[^a-z0-9\s]/g, ' ')
+ .split(/\s+/)
+ .filter((w) => w.length >= 4)
+ .slice(0, 4),
+ ),
+ );
+ return { type, style, tags };
+}
+
+// ── feed / discovery ─────────────────────────────────────────────────────────
+
+function matchesFilters(c, { q, type, style, creator, license }) {
+ if (type && c.type !== type) return false;
+ if (style && c.style !== style) return false;
+ if (license && c.license !== license) return false;
+ if (creator && c.creatorKey !== creator && slugifyAuthor(c.author) !== creator) return false;
+ if (q) {
+ const hay = `${c.title} ${c.prompt} ${c.author} ${(c.tags || []).join(' ')}`.toLowerCase();
+ if (!hay.includes(q.toLowerCase())) return false;
+ }
+ return true;
+}
+
+async function handleFeed(req, res, url) {
+ const limit = Math.min(MAX_LIMIT, Math.max(1, parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10) || DEFAULT_LIMIT));
+ const page = Math.max(0, parseInt(url.searchParams.get('page') || '0', 10) || 0);
+ const sort = ['new', 'trending', 'remixed'].includes(url.searchParams.get('sort')) ? url.searchParams.get('sort') : 'new';
+ const filters = {
+ q: (url.searchParams.get('q') || '').trim().slice(0, 80),
+ type: TYPES.includes(url.searchParams.get('type')) ? url.searchParams.get('type') : null,
+ style: STYLES.includes(url.searchParams.get('style')) ? url.searchParams.get('style') : null,
+ creator: sanitizeOptionalString(url.searchParams.get('creator'), 64),
+ license: LICENSES[url.searchParams.get('license')] ? url.searchParams.get('license') : null,
+ };
+
+ // Pull a deep slice of the canonical Loom feed, enrich, filter, then rank.
+ // SCAN_CAP bounds the work; the feed is itself capped at 2000 upstream.
+ const raw = await loomReadFeed(SCAN_CAP, NaN);
+ const enriched = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ let items = enriched.filter((c) => matchesFilters(c, filters));
+
+ if (sort === 'new') items.sort((a, b) => b.createdAt - a.createdAt);
+ else if (sort === 'remixed' || sort === 'trending') {
+ // trending blends remix count with recency so a brand-new asset with one
+ // remix can out-rank an old asset with two; remixed is pure count.
+ if (sort === 'trending') {
+ const now = Date.now();
+ const score = (c) => c.remixCount * 10 + Math.max(0, 5 - (now - c.createdAt) / 86_400_000);
+ items.sort((a, b) => score(b) - score(a) || b.createdAt - a.createdAt);
+ } else {
+ items.sort((a, b) => b.remixCount - a.remixCount || b.createdAt - a.createdAt);
+ }
+ }
+
+ const total = items.length;
+ const start = page * limit;
+ const slice = items.slice(start, start + limit);
+ const hasMore = start + limit < total;
+
+ res.setHeader('cache-control', 'public, s-maxage=15, stale-while-revalidate=60');
+ return json(res, 200, {
+ creations: slice,
+ page,
+ limit,
+ total,
+ hasMore,
+ facets: { styles: STYLES, types: TYPES, licenses: Object.entries(LICENSES).map(([id, v]) => ({ id, ...v })) },
+ });
+}
+
+async function handleItem(req, res, url) {
+ const id = url.searchParams.get('id');
+ if (!id) return error(res, 400, 'bad_request', 'id is required');
+ const creation = await loomReadOne(id);
+ if (!creation) return error(res, 404, 'not_found', 'creation not found');
+
+ const item = await enrich(creation, { withChildren: true });
+ const provenance = await getProvenance(id);
+
+ // Lineage: walk up to the root following parentId, and list direct children.
+ const ancestors = [];
+ let cursorMeta = await getMeta(id);
+ let guard = 0;
+ while (cursorMeta?.parentId && guard++ < 12) {
+ const pc = await loomReadOne(cursorMeta.parentId);
+ if (!pc) break;
+ ancestors.push(await enrich(pc));
+ cursorMeta = await getMeta(cursorMeta.parentId);
+ }
+ const children = (await Promise.all((item.childIds || []).slice(0, 24).map((cid) => loomReadOne(cid).then((c) => (c ? enrich(c) : null))))).filter(Boolean);
+
+ // Creator card: aggregate + follower count + (for agents) on-chain reputation.
+ const creator = await buildCreatorCard(item.creatorKey, creation);
+
+ res.setHeader('cache-control', 'public, s-maxage=10, stale-while-revalidate=30');
+ return json(res, 200, {
+ creation: item,
+ lineage: { ancestors: ancestors.reverse(), children, parentId: item.parentId },
+ provenance,
+ creator,
+ });
+}
+
+async function buildCreatorCard(key, sampleCreation) {
+ const rec = await getCreator(key);
+ const followers = await followerCount(key);
+ const displayName = rec?.displayName || sampleCreation?.author || (isAgentKey(key) ? 'Agent' : key);
+ const card = {
+ key,
+ displayName,
+ isAgent: isAgentKey(key),
+ agentId: rec?.agentId || (isAgentKey(key) ? key : null),
+ creationCount: rec?.creationIds?.length || null,
+ remixesEarned: rec?.remixesEarned || 0,
+ followers,
+ profileUrl: `/creator/${encodeURIComponent(key)}`,
+ };
+ return card;
+}
+
+async function handleCreator(req, res, url) {
+ const key = sanitizeOptionalString(url.searchParams.get('id'), 64);
+ if (!key) return error(res, 400, 'bad_request', 'id is required');
+ const followerId = sanitizeOptionalString(url.searchParams.get('follower'), 80);
+
+ // Gather this creator's creations from the canonical feed (match by agent
+ // binding or author slug) — bounded scan, newest-first.
+ const raw = await loomReadFeed(SCAN_CAP, NaN);
+ const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const creations = all
+ .filter((c) => c.creatorKey === key || slugifyAuthor(c.author) === key)
+ .sort((a, b) => b.createdAt - a.createdAt);
+
+ const remixesEarned = creations.reduce((n, c) => n + c.remixCount, 0);
+ const rec = await getCreator(key);
+ const followers = await followerCount(key);
+ const following = await isFollowing(key, followerId);
+
+ const creator = {
+ key,
+ displayName: rec?.displayName || creations[0]?.author || (isAgentKey(key) ? 'Agent' : key),
+ isAgent: isAgentKey(key),
+ agentId: rec?.agentId || (isAgentKey(key) ? key : null),
+ creationCount: creations.length,
+ remixesEarned,
+ followers,
+ following,
+ createdAt: rec?.createdAt || creations[creations.length - 1]?.createdAt || null,
+ };
+
+ res.setHeader('cache-control', 'public, s-maxage=15, stale-while-revalidate=60');
+ return json(res, 200, { creator, creations });
+}
+
+async function handleCreators(req, res, url) {
+ const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit') || '12', 10) || 12));
+ const sort = ['remixed', 'prolific', 'followed'].includes(url.searchParams.get('sort')) ? url.searchParams.get('sort') : 'remixed';
+
+ const raw = await loomReadFeed(SCAN_CAP, NaN);
+ const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+
+ // Aggregate by creator key across the scanned feed.
+ const byKey = new Map();
+ for (const c of all) {
+ const k = c.creatorKey;
+ const agg = byKey.get(k) || { key: k, displayName: c.author, isAgent: c.creatorIsAgent, creationCount: 0, remixesEarned: 0, latest: 0, sample: c };
+ agg.creationCount += 1;
+ agg.remixesEarned += c.remixCount;
+ agg.latest = Math.max(agg.latest, c.createdAt);
+ if (!agg.isAgent && c.creatorIsAgent) agg.isAgent = true;
+ byKey.set(k, agg);
+ }
+
+ let creators = Array.from(byKey.values());
+ // Decorate with persisted display name + follower count.
+ creators = await Promise.all(
+ creators.map(async (c) => {
+ const rec = await getCreator(c.key);
+ return {
+ key: c.key,
+ displayName: rec?.displayName || c.displayName || c.key,
+ isAgent: c.isAgent,
+ agentId: rec?.agentId || (c.isAgent ? c.key : null),
+ creationCount: c.creationCount,
+ remixesEarned: c.remixesEarned,
+ followers: await followerCount(c.key),
+ latest: c.latest,
+ profileUrl: `/creator/${encodeURIComponent(c.key)}`,
+ sampleGlb: c.sample?.glbUrl || null,
+ samplePreview: c.sample?.previewImageUrl || null,
+ };
+ }),
+ );
+
+ if (sort === 'prolific') creators.sort((a, b) => b.creationCount - a.creationCount || b.remixesEarned - a.remixesEarned);
+ else if (sort === 'followed') creators.sort((a, b) => b.followers - a.followers || b.remixesEarned - a.remixesEarned);
+ else creators.sort((a, b) => b.remixesEarned - a.remixesEarned || b.creationCount - a.creationCount);
+
+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');
+ return json(res, 200, { creators: creators.slice(0, limit), sort });
+}
+
+async function handleTrending(req, res, url) {
+ const limit = Math.min(24, Math.max(1, parseInt(url.searchParams.get('limit') || '8', 10) || 8));
+ const raw = await loomReadFeed(SCAN_CAP, NaN);
+ const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const now = Date.now();
+ const score = (c) => c.remixCount * 10 + Math.max(0, 5 - (now - c.createdAt) / 86_400_000);
+ const trending = all
+ .filter((c) => c.remixCount > 0)
+ .sort((a, b) => score(b) - score(a))
+ .slice(0, limit);
+ const recentRemixes = (await readRemixEvents(20)).slice(0, 20);
+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');
+ return json(res, 200, { trending, recentRemixes });
+}
+
+// ── writes ──────────────────────────────────────────────────────────────────
+
+function sanitizeTags(raw) {
+ if (!Array.isArray(raw)) return [];
+ return Array.from(
+ new Set(
+ raw
+ .map((t) => sanitizeOptionalString(t, TAG_MAX))
+ .filter(Boolean)
+ .map((t) => t.toLowerCase()),
+ ),
+ ).slice(0, TAGS_MAX);
+}
+
+function sanitizeRoyalty(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const bps = Math.max(0, Math.min(2000, Math.round(Number(raw.bps) || 0))); // cap at 20%
+ if (!bps) return null;
+ const beneficiaryKey = sanitizeOptionalString(raw.beneficiaryKey, 64);
+ return { bps, beneficiaryKey: beneficiaryKey || null, settlement: 'USDC' };
+}
+
+// Publish a creation INTO the gallery. Writes the canonical Loom record (so it
+// shows in the shared feed every surface reads), then attaches the gallery
+// overlay (title/tags/license/type/style/creator/lineage) and a provenance entry.
+// When parentId is present this is the persisted tail of a remix.
+async function handlePublish(req, res, body, ip) {
+ const prompt = sanitizePrompt(body?.prompt ?? '');
+ if (!prompt) return error(res, 400, 'bad_request', 'prompt is required');
+ if (prompt.length > 1000) return error(res, 400, 'bad_request', 'prompt too long (max 1000)');
+
+ const glbUrl = validateGlbUrl(body?.glbUrl);
+ if (!glbUrl) return error(res, 400, 'invalid_glb_url', 'glbUrl must be an https URL on an allowed host');
+
+ const author = sanitizeAuthor(body?.author);
+ const agentId = body?.agentId && UUID_RE.test(body.agentId) ? body.agentId : null;
+ const title = sanitizeOptionalString(body?.title, TITLE_MAX) || titleFromPrompt(prompt);
+ const tags = sanitizeTags(body?.tags);
+ const type = TYPES.includes(body?.type) ? body.type : null;
+ const style = STYLES.includes(body?.style) ? body.style : null;
+ const license = LICENSES[body?.license] ? body.license : DEFAULT_LICENSE;
+ const royalty = sanitizeRoyalty(body?.royalty);
+ const parentId = sanitizeOptionalString(body?.parentId, 64);
+ const previewImageUrl = sanitizeOptionalString(body?.previewImageUrl, 600);
+ const tier = sanitizeOptionalString(body?.tier, 40);
+ const backend = sanitizeOptionalString(body?.backend, 40);
+
+ // Write the canonical record to Loom (single source of truth for the feed).
+ const creation = await writeCreation({
+ id: randomUUID(),
+ prompt,
+ glbUrl,
+ previewImageUrl,
+ author,
+ tier,
+ backend,
+ createdAt: Date.now(),
+ });
+
+ const creatorKey = agentId || slugifyAuthor(author);
+
+ const meta = {
+ id: creation.id,
+ title,
+ tags,
+ type,
+ style,
+ license,
+ royalty,
+ parentId: parentId || null,
+ agentId,
+ creatorKey,
+ author,
+ publishedAt: Date.now(),
+ };
+ await putMeta(meta);
+ await touchCreator({ key: creatorKey, displayName: author, agentId, creationId: creation.id });
+
+ await appendProvenance(creation.id, {
+ event: parentId ? 'remix' : 'origin',
+ creatorKey,
+ author,
+ license,
+ parentId: parentId || null,
+ at: Date.now(),
+ });
+
+ // If this is a remix, record the lineage edge + bump the parent's creator.
+ if (parentId) {
+ const parent = await loomReadOne(parentId);
+ if (parent) {
+ await addChild(parentId, creation.id);
+ const parentMeta = await getMeta(parentId);
+ const parentKey = creatorKeyFor(parent, parentMeta);
+ await touchCreator({ key: parentKey, displayName: parent.author, earnedRemix: true });
+ await pushRemixEvent({
+ parentId,
+ childId: creation.id,
+ parentTitle: parentMeta?.title || titleFromPrompt(parent.prompt),
+ childTitle: title,
+ byKey: creatorKey,
+ byName: author,
+ royalty,
+ at: Date.now(),
+ });
+ await appendProvenance(parentId, {
+ event: 'remixed-by',
+ childId: creation.id,
+ byKey: creatorKey,
+ royalty,
+ at: Date.now(),
+ });
+ }
+ }
+
+ const enriched = await enrich(creation);
+ return json(res, 201, { creation: enriched, royalty });
+}
+
+// Record a lineage edge for an EXISTING child creation (e.g. one already in the
+// feed) without re-publishing. Idempotent on (parentId, childId).
+async function handleRemixLink(req, res, body) {
+ const parentId = sanitizeOptionalString(body?.parentId, 64);
+ const childId = sanitizeOptionalString(body?.childId, 64);
+ if (!parentId || !childId) return error(res, 400, 'bad_request', 'parentId and childId are required');
+ if (parentId === childId) return error(res, 400, 'bad_request', 'a creation cannot remix itself');
+
+ const parent = await loomReadOne(parentId);
+ const child = await loomReadOne(childId);
+ if (!parent || !child) return error(res, 404, 'not_found', 'parent or child creation not found');
+
+ const existing = await getChildren(parentId);
+ if (!existing.includes(childId)) {
+ await addChild(parentId, childId);
+ const royalty = sanitizeRoyalty(body?.royalty);
+ const childMeta = (await getMeta(childId)) || { id: childId };
+ childMeta.parentId = parentId;
+ if (royalty) childMeta.royalty = royalty;
+ await putMeta(childMeta);
+
+ const parentMeta = await getMeta(parentId);
+ const parentKey = creatorKeyFor(parent, parentMeta);
+ const childKey = creatorKeyFor(child, childMeta);
+ await touchCreator({ key: parentKey, displayName: parent.author, earnedRemix: true });
+ await pushRemixEvent({
+ parentId,
+ childId,
+ parentTitle: parentMeta?.title || titleFromPrompt(parent.prompt),
+ childTitle: childMeta.title || titleFromPrompt(child.prompt),
+ byKey: childKey,
+ byName: child.author,
+ royalty,
+ at: Date.now(),
+ });
+ await appendProvenance(childId, { event: 'remix', parentId, royalty, at: Date.now() });
+ await appendProvenance(parentId, { event: 'remixed-by', childId, royalty, at: Date.now() });
+ }
+
+ const updated = await enrich(parent);
+ return json(res, 200, { ok: true, parent: updated });
+}
+
+async function handleFollow(req, res, body) {
+ const key = sanitizeOptionalString(body?.creatorKey, 64);
+ const followerId = sanitizeOptionalString(body?.follower, 80);
+ if (!key || !followerId) return error(res, 400, 'bad_request', 'creatorKey and follower are required');
+ const follow = body?.follow !== false;
+ await setFollow(key, followerId, follow);
+ const followers = await followerCount(key);
+ return json(res, 200, { ok: true, following: follow, followers });
+}
+
+// ── rate limit for writes (shared with Loom's posture: ~30/hr/ip) ──────────────
+const WRITE_LIMIT = 30;
+const WRITE_WINDOW_MS = 60 * 60 * 1000;
+const memWriteBuckets = new Map();
+
+function memoryWriteLimit(ip) {
+ const now = Date.now();
+ const cutoff = now - WRITE_WINDOW_MS;
+ const kept = (memWriteBuckets.get(ip) || []).filter((t) => t > cutoff);
+ if (kept.length >= WRITE_LIMIT) {
+ memWriteBuckets.set(ip, kept);
+ return { success: false, limit: WRITE_LIMIT, remaining: 0, reset: kept[0] + WRITE_WINDOW_MS };
+ }
+ kept.push(now);
+ memWriteBuckets.set(ip, kept);
+ return { success: true, limit: WRITE_LIMIT, remaining: WRITE_LIMIT - kept.length, reset: now + WRITE_WINDOW_MS };
+}
+
+async function writeRateLimit(ip) {
+ const r = getRedis();
+ if (!r) return memoryWriteLimit(ip);
+ const key = `cre:write:${ip}`;
+ try {
+ const count = await r.incr(key);
+ if (count === 1) await r.pexpire(key, WRITE_WINDOW_MS);
+ const ttl = await r.pttl(key);
+ const reset = Date.now() + (ttl > 0 ? ttl : WRITE_WINDOW_MS);
+ if (count > WRITE_LIMIT) return { success: false, limit: WRITE_LIMIT, remaining: 0, reset };
+ return { success: true, limit: WRITE_LIMIT, remaining: WRITE_LIMIT - count, reset };
+ } catch {
+ return memoryWriteLimit(ip);
+ }
+}
+
+// ── handler ────────────────────────────────────────────────────────────────────
+
+export default wrap(async (req, res) => {
+ if (cors(req, res)) return;
+
+ if (req.method === 'GET') {
+ const url = new URL(req.url, 'http://localhost');
+ const op = url.searchParams.get('op') || 'feed';
+ switch (op) {
+ case 'feed':
+ return handleFeed(req, res, url);
+ case 'item':
+ return handleItem(req, res, url);
+ case 'creator':
+ return handleCreator(req, res, url);
+ case 'creators':
+ return handleCreators(req, res, url);
+ case 'trending':
+ return handleTrending(req, res, url);
+ default:
+ return error(res, 400, 'bad_request', `unknown op "${op}"`);
+ }
+ }
+
+ if (req.method === 'POST') {
+ const ip = clientIp(req);
+ const rl = await writeRateLimit(ip);
+ if (!rl.success) {
+ setRateLimitHeaders(res, rl);
+ return error(res, 429, 'rate_limited', 'too many writes, slow down', {
+ retry_after: Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000)),
+ });
+ }
+ const body = await readJson(req, 12_000);
+ const op = body?.op || 'publish';
+ setRateLimitHeaders(res, rl);
+ switch (op) {
+ case 'publish':
+ return handlePublish(req, res, body, ip);
+ case 'remix':
+ return handleRemixLink(req, res, body);
+ case 'follow':
+ return handleFollow(req, res, body);
+ default:
+ return error(res, 400, 'bad_request', `unknown op "${op}"`);
+ }
+ }
+
+ if (!method(req, res, ['GET', 'POST'])) return;
+});
diff --git a/api/input-multiview.js b/api/input-multiview.js
new file mode 100644
index 000000000..2bc402175
--- /dev/null
+++ b/api/input-multiview.js
@@ -0,0 +1,207 @@
+/**
+ * POST /api/input-multiview — multi-image validation + 3D reconstruction.
+ *
+ * Accepts 2–4 photos of an object from different angles, validates each with
+ * vision (clear subject? in focus? same object?), then submits them to
+ * /api/forge as a multi-view reconstruction job. The validation step catches
+ * mismatched images, blank uploads, and text screenshots before burning a
+ * generation slot.
+ *
+ * Privacy — same transient-by-default policy as /api/input-photo:
+ * All uploaded images are processed transiently. No image bytes are written
+ * to logs. With privacy_opt_in:false (default) and storage_keys provided,
+ * all R2 objects are deleted after the forge job is created.
+ *
+ * Request:
+ * POST /api/input-multiview
+ * Content-Type: application/json
+ * {
+ * image_urls: string[], // 2–4 public https URLs (required)
+ * storage_keys?: string[], // R2 keys from /api/forge-upload (for transient delete)
+ * prompt?: string, // optional guidance text (max 1000 chars)
+ * tier?: string, // "draft" | "standard" | "high"
+ * privacy_opt_in?: boolean, // default false
+ * skip_validation?: boolean // bypass per-image vision check
+ * }
+ *
+ * Response 200:
+ * { job_id, creation_id, views_used, multiview:true,
+ * validation:[{url, ok, issue?, description}], privacy_note }
+ *
+ * Error 422 invalid_views — one or more images failed validation
+ * Error 400 too_few_images — fewer than 2 images provided
+ */
+
+import { cors, json, method, readJson, wrap, rateLimited, error } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { visionConfigured, describeImage } from './_lib/vision.js';
+import { deleteObject } from './_lib/r2.js';
+import { env } from './_lib/env.js';
+
+export const maxDuration = 90; // vision validation × N images + generation submit
+
+const MIN_VIEWS = 2;
+const MAX_VIEWS = 4;
+const HTTP_URL_RE = /^https?:\/\/.{1,2044}$/;
+const R2_KEY_RE = /^forge\/uploads\/[a-f0-9]{12}\/[a-f0-9-]{36}\.(png|jpg|webp)$/;
+
+// Per-image validation prompt. We ask for a JSON verdict with the subject name
+// so we can cross-check that all images depict the same object.
+const VIEW_CHECK_PROMPT =
+ 'You are the input checker for a multi-view 3D reconstruction tool. ' +
+ 'The user uploaded this image as one view of a physical object to reconstruct.\n\n' +
+ 'Reply ONLY with compact JSON, no prose:\n' +
+ '{"ok":true|false,"issue":"none"|"no_subject"|"text_screenshot"|"too_dark_or_blurry"|"abstract_or_diagram",' +
+ '"subject":"<3-6 word description of the main object, or empty string>"}\n\n' +
+ 'Mark ok:false when the image is genuinely not usable as a reconstruction view: ' +
+ 'no clear physical object (no_subject), screenshot of UI or text (text_screenshot), ' +
+ 'too dark or blurry (too_dark_or_blurry), abstract pattern/chart (abstract_or_diagram). ' +
+ 'When in doubt, mark ok:true.';
+
+const ISSUE_MESSAGES = {
+ no_subject:
+ 'That image has no clear single object. Upload a photo where one object fills most of the frame.',
+ text_screenshot:
+ 'That looks like a screenshot of text or an interface, not a photo of an object.',
+ too_dark_or_blurry:
+ 'That image is too dark or blurry. Retake it in good light with the subject in focus.',
+ abstract_or_diagram:
+ 'That image looks like an abstract pattern or diagram, not a physical object.',
+};
+
+async function validateView(imageUrl, index) {
+ try {
+ const vision = await describeImage({
+ prompt: VIEW_CHECK_PROMPT,
+ imageUrl,
+ maxTokens: 80,
+ timeoutMs: 12_000,
+ track: { tool: 'api/input-multiview' },
+ });
+ let parsed = null;
+ try {
+ const clean = vision.text.replace(/^```[a-z]*\n?|\n?```$/g, '').trim();
+ parsed = JSON.parse(clean);
+ } catch { /* malformed — fail open */ }
+
+ if (!parsed) return { url: imageUrl, index, ok: true, subject: '' };
+ return {
+ url: imageUrl,
+ index,
+ ok: parsed.ok !== false,
+ issue: parsed.issue !== 'none' ? parsed.issue : undefined,
+ message: parsed.ok === false ? (ISSUE_MESSAGES[parsed.issue] || 'Image not usable.') : undefined,
+ subject: parsed.subject || '',
+ };
+ } catch {
+ // Vision unavailable — fail open.
+ return { url: imageUrl, index, ok: true, subject: '' };
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
+ }
+
+ const body = await readJson(req, 12_000).catch(() => null);
+
+ const rawUrls = Array.isArray(body?.image_urls) ? body.image_urls : [];
+ const imageUrls = rawUrls
+ .map((u) => (typeof u === 'string' ? u.trim() : ''))
+ .filter((u) => HTTP_URL_RE.test(u) && u.length <= 2048)
+ .slice(0, MAX_VIEWS);
+
+ if (imageUrls.length < MIN_VIEWS) {
+ return error(res, 400, 'too_few_images',
+ `Provide between ${MIN_VIEWS} and ${MAX_VIEWS} photos of the object from different angles.`);
+ }
+
+ const rawKeys = Array.isArray(body?.storage_keys) ? body.storage_keys : [];
+ const storageKeys = rawKeys
+ .map((k) => (typeof k === 'string' ? k.trim() : ''))
+ .filter((k) => R2_KEY_RE.test(k));
+ const privacyOptIn = body?.privacy_opt_in === true;
+ const skipValidation = body?.skip_validation === true;
+
+ const prompt = typeof body?.prompt === 'string'
+ ? body.prompt.trim().slice(0, 1000)
+ : '';
+ const tier = ['draft', 'standard', 'high'].includes(body?.tier) ? body.tier : 'standard';
+
+ // Per-image vision validation (in parallel for speed).
+ let validation = imageUrls.map((url, i) => ({ url, index: i, ok: true, subject: '' }));
+ if (!skipValidation && visionConfigured()) {
+ validation = await Promise.all(imageUrls.map(validateView));
+ }
+
+ const failures = validation.filter((v) => !v.ok);
+ if (failures.length > 0) {
+ return json(res, 422, {
+ error: 'invalid_views',
+ message:
+ `${failures.length} of your images can't be used for reconstruction. ` +
+ 'Review the details below and replace the flagged photos.',
+ validation,
+ override: { field: 'skip_validation', value: true },
+ });
+ }
+
+ // Submit to forge.
+ const forgeBody = {
+ image_urls: imageUrls,
+ ...(prompt ? { prompt } : {}),
+ path: 'image',
+ tier,
+ skip_validation: true,
+ };
+
+ const forgeOrigin = env.APP_ORIGIN || 'http://localhost:3000';
+ let forgeResp;
+ try {
+ forgeResp = await fetch(`${forgeOrigin}/api/forge`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-forwarded-for': ip,
+ 'x-forge-client': req.headers['x-forge-client'] || '',
+ },
+ body: JSON.stringify(forgeBody),
+ });
+ } catch (e) {
+ return error(res, 502, 'generation_unreachable',
+ 'Could not reach the generation service. Please try again.');
+ }
+
+ const forgeData = await forgeResp.json().catch(() => null);
+
+ if (!forgeResp.ok || !forgeData) {
+ const code = forgeData?.error || 'generation_failed';
+ const msg = forgeData?.message || 'Generation failed. Please try again.';
+ return json(res, forgeResp.status >= 500 ? 502 : forgeResp.status, {
+ error: code,
+ message: msg,
+ });
+ }
+
+ // Transient cleanup: delete all R2 objects after the provider has the URLs.
+ if (!privacyOptIn && storageKeys.length > 0) {
+ Promise.all(storageKeys.map((k) => deleteObject(k).catch(() => { /* best-effort */ })));
+ }
+
+ const privacyNote = privacyOptIn
+ ? 'You opted in to retaining your photos. They are stored as preview images for this creation.'
+ : 'Your photos were processed transiently and were not stored. They will not appear in creation history.';
+
+ return json(res, 200, {
+ ...forgeData,
+ validation,
+ privacy_retained: privacyOptIn,
+ privacy_note: privacyNote,
+ }, { 'cache-control': 'no-store' });
+});
diff --git a/api/loom.js b/api/loom.js
index 60cbe335b..9296a0570 100644
Binary files a/api/loom.js and b/api/loom.js differ
diff --git a/data/changelog.json b/data/changelog.json
index 22b2610c2..aa33c2bf0 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,12 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-25",
+ "title": "Self-hosted GPU lanes are now the resilient default for 3D generation",
+ "summary": "Our own Cloud Run GPU workers (TRELLIS, Hunyuan3D, TripoSG on NVIDIA L4s) are now the default generation backend — routing prefers a healthy self-hosted lane, then another free external lane, and only falls back to a paid Replicate lane when every free option is confirmed down. A cached liveness probe picks up cold-start containers and widens the ETA estimate honestly instead of showing a fake timer. If a self-hosted worker errors at submit time, the handler cools that lane and transparently retries the next configured one before surfacing any error. The /forge?health dashboard now shows a real free-vs-paid serve split so you can see how many generations ran at zero vendor cost.",
+ "tags": ["improvement", "infra"]
+ },
{
"date": "2026-06-25",
"title": "Pose studio: HumanIK rig support, 3 new poses, FK-verified preset geometry",
diff --git a/docs/store-submissions/_generated/apps-sdk-empty.png b/docs/store-submissions/_generated/apps-sdk-empty.png
new file mode 100644
index 000000000..79db7dade
Binary files /dev/null and b/docs/store-submissions/_generated/apps-sdk-empty.png differ
diff --git a/docs/store-submissions/_generated/apps-sdk-error.png b/docs/store-submissions/_generated/apps-sdk-error.png
new file mode 100644
index 000000000..b3840b5c8
Binary files /dev/null and b/docs/store-submissions/_generated/apps-sdk-error.png differ
diff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.js
index 01f93b939..8731e5bd1 100644
--- a/mcp-server/src/tools/_studio-core.js
+++ b/mcp-server/src/tools/_studio-core.js
@@ -20,6 +20,7 @@
// neither the @x402 stack nor zod-to-json-schema) unchanged.
import { classifyHumanoidPrompt } from './_humanoid.js';
+import { composeRefinement, seedLineage, appendVersion } from './_lineage.js';
// Standard tool error envelope — identical shape to payments.js `toolError`, so
// a core's error is indistinguishable whether it is surfaced through the paid
@@ -947,3 +948,127 @@ export async function runTextToAvatar({ prompt, images, seed, texture }) {
fetchedAt: new Date().toISOString(),
};
}
+
+// ---------------------------------------------------------------------------
+// refine_model — conversational refinement: carry a model forward with a
+// natural-language change instruction. The prior prompt is folded into the new
+// generation prompt so form, material, and subject carry forward. A reference
+// image (2D preview/screenshot of the parent) anchors the generation when
+// provided; otherwise text-only re-generation is used — still real, still
+// anchored through the composed prompt.
+//
+// Lineage: pass parent_lineage to extend an existing version history, or omit
+// to start a fresh lineage rooted at glb_url. The returned lineage array
+// supports revert (pointer move, no mutation) and branch (parentIndex override).
+// ---------------------------------------------------------------------------
+export async function runRefineModel({
+ glb_url,
+ instruction,
+ parent_prompt,
+ parent_lineage,
+ parent_index,
+ reference_image_url,
+}) {
+ if (!glb_url || typeof glb_url !== 'string' || !glb_url.trim()) {
+ return coreError('invalid_input', 'Provide glb_url of the model to refine.');
+ }
+ const instructionTrimmed = typeof instruction === 'string' ? instruction.trim() : '';
+ if (!instructionTrimmed) {
+ return coreError('invalid_input', 'Provide an instruction describing the change to make.');
+ }
+
+ const parentPromptStr = typeof parent_prompt === 'string' ? parent_prompt.trim() : '';
+ const composedPrompt = composeRefinement(parentPromptStr, instructionTrimmed);
+
+ // Resolve starting lineage: extend an existing one, or seed from the parent.
+ const baseLineage =
+ Array.isArray(parent_lineage) && parent_lineage.length > 0
+ ? parent_lineage
+ : seedLineage({ glbUrl: glb_url.trim(), prompt: parentPromptStr || null });
+
+ const effectiveParentIndex =
+ Number.isInteger(parent_index) && parent_index >= 0 && parent_index < baseLineage.length
+ ? parent_index
+ : undefined;
+
+ const base = apiBaseFrom(['MESH_FORGE_API_BASE']);
+ const started = Date.now();
+
+ const refImageUrl =
+ typeof reference_image_url === 'string' && reference_image_url.trim()
+ ? reference_image_url.trim()
+ : null;
+
+ let job;
+ try {
+ job = await submitForge({
+ base,
+ payload: refImageUrl
+ ? { image_urls: [refImageUrl], prompt: composedPrompt }
+ : { prompt: composedPrompt },
+ submitTimeoutMs: 30_000,
+ allowSyncDone: false,
+ });
+ } catch (err) {
+ return coreError(err.code || 'provider_error', err.message, {
+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),
+ });
+ }
+
+ const timeoutMs = Number(env('REFINE_MODEL_TIMEOUT_MS', '180000'));
+ const intervalMs = Number(env('REFINE_MODEL_POLL_MS', '3000'));
+ let final;
+ try {
+ final = await pollForge(job.job_id, { base, timeoutMs, intervalMs });
+ } catch (err) {
+ return coreError(err.code || 'provider_error', err.message, {
+ jobId: job.job_id,
+ creationId: job.creation_id ?? null,
+ durationMs: Date.now() - started,
+ });
+ }
+
+ const durationMs = Date.now() - started;
+ if (final._timedOut) {
+ return coreError('timeout', `refinement did not finish within ${timeoutMs}ms`, {
+ jobId: job.job_id,
+ creationId: job.creation_id ?? null,
+ status: final.status || 'running',
+ resumeUrl: `${base}/api/forge?job=${job.job_id}`,
+ durationMs,
+ });
+ }
+
+ const newGlbUrl = final.glb_url;
+ const viewerUrl = `${base}/viewer?src=${encodeURIComponent(newGlbUrl)}`;
+
+ const lineage = appendVersion(baseLineage, {
+ glbUrl: newGlbUrl,
+ viewerUrl,
+ prompt: composedPrompt,
+ instruction: instructionTrimmed,
+ refKind: refImageUrl ? 'image' : 'text',
+ ...(effectiveParentIndex !== undefined ? { parentIndex: effectiveParentIndex } : {}),
+ });
+ const activeIndex = lineage.length - 1;
+
+ return {
+ ok: true,
+ mode: 'refine',
+ glbUrl: newGlbUrl,
+ viewerUrl,
+ composedPrompt,
+ instruction: instructionTrimmed,
+ parentGlbUrl: glb_url.trim(),
+ anchored: Boolean(refImageUrl),
+ referenceImageUrl: refImageUrl,
+ backend: (final.backend ?? job.backend) ?? null,
+ jobId: job.job_id,
+ creationId: final.creation_id ?? job.creation_id ?? null,
+ durable: Boolean(final.durable),
+ lineage,
+ activeIndex,
+ durationMs,
+ fetchedAt: new Date().toISOString(),
+ };
+}
diff --git a/pages/embodiment/embed.html b/pages/embodiment/embed.html
new file mode 100644
index 000000000..2cd4ecb71
--- /dev/null
+++ b/pages/embodiment/embed.html
@@ -0,0 +1,108 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <title>Agent — three.ws</title>
+ <!-- sandboxed: no index, allow framing by any host (ChatGPT, Claude, etc.) -->
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <style>
+ :root { color-scheme: dark; }
+ *, *::before, *::after { box-sizing: border-box; }
+ html, body {
+ margin: 0; padding: 0;
+ width: 100%; height: 100%;
+ overflow: hidden;
+ background: radial-gradient(120% 120% at 50% 0%, #141420 0%, #0a0a12 70%);
+ }
+ #stage-root {
+ position: fixed;
+ inset: 0;
+ /* The overlay chrome sits on top; the canvas fills below it. */
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage-root"></div>
+ <script type="module">
+ import { EmbodimentStage } from '/apps-sdk/embodiment/embodiment-stage.js';
+ import { mountOverlay } from '/apps-sdk/embodiment/overlay.js';
+
+ // ── URL params ──────────────────────────────────────────────────────
+ const q = new URLSearchParams(location.search);
+ const personaId = q.get('persona') || null;
+ const glbUrl = q.get('glb') || null;
+ const name = q.get('name') || 'Agent';
+ const initState = q.get('state') || 'idle';
+ const speakText = q.get('text') || '';
+ const emotion = q.get('emotion') || null;
+ const intensity = parseFloat(q.get('intensity') || '0.8');
+ const gesture = q.get('gesture') || null;
+
+ if (!glbUrl && !personaId) {
+ // Nothing to show — emit a minimal error surface.
+ document.body.innerHTML =
+ '<p style="color:#fb7185;font-family:system-ui;padding:24px;margin:0">No persona or GLB URL supplied.</p>';
+ throw new Error('[embodiment-embed] missing glb or persona param');
+ }
+
+ // ── stage + overlay ─────────────────────────────────────────────────
+ const root = document.getElementById('stage-root');
+
+ // overlay sits above the canvas; stage mounts its canvas into root
+ const overlay = mountOverlay(root, {
+ onRetry: () => location.reload(),
+ });
+ overlay.setName(name);
+ overlay.setState('loading');
+
+ const stage = new EmbodimentStage(root, {
+ background: q.get('bg') === 'transparent' ? null : undefined,
+ onState: (state, detail) => overlay.setState(state, { ...detail, name }),
+ });
+
+ // ── load ─────────────────────────────────────────────────────────────
+ // glbUrl is a direct param; persona_id resolution for durable reload
+ // hits the persona API so the embed is always up to date.
+ async function resolveGlb() {
+ if (glbUrl) return { glbUrl, name };
+ // Reload durable persona by id.
+ const res = await fetch(`/api/mcp3d/persona?id=${encodeURIComponent(personaId)}`, {
+ credentials: 'same-origin',
+ });
+ if (!res.ok) throw new Error(`persona ${res.status}`);
+ const data = await res.json();
+ return { glbUrl: data.glb_url, name: data.name || name };
+ }
+
+ (async () => {
+ let resolved;
+ try {
+ resolved = await resolveGlb();
+ } catch (err) {
+ overlay.setState('error', { message: 'Could not load this persona. ' + (err?.message || '') });
+ return;
+ }
+
+ overlay.setName(resolved.name);
+ const ok = await stage.loadPersona({
+ glbUrl: resolved.glbUrl,
+ name: resolved.name,
+ personaId,
+ });
+ if (!ok) return; // stage already set 'error'
+
+ // Drive the requested initial state after loading.
+ if (initState === 'speaking' && speakText) {
+ await stage.speak({ text: speakText, emotion, intensity, gesture });
+ } else if (initState === 'thinking') {
+ stage.thinking();
+ } else if (initState === 'listening') {
+ stage.listening();
+ }
+ // else: idle is already set by loadPersona
+ })();
+ </script>
+ </body>
+</html>