Skip to content

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

feat: three-token page, live cohorts, forge job tokens

nirholasf95d55152a9b
diff --git a/api/_lib/coin/cohorts-live.js b/api/_lib/coin/cohorts-live.js
new file mode 100644
index 000000000..88c5dc854
--- /dev/null
+++ b/api/_lib/coin/cohorts-live.js
@@ -0,0 +1,169 @@
+// Live holder cohorts — for agent tokens that have no coin_holders snapshot.
+//
+// Agent tokens launched through three.ws live in agent_identities.meta.token
+// and are NOT registered in coin_launches, so the snapshot pipeline in
+// cohorts.js (which reads coin_holders by coin_id) has nothing to query for
+// them. Rather than show empty cohorts, we compute the snapshot-independent
+// cohorts directly from the live holder set Helius indexes for the mint
+// (fetchHolderBalances → current balances).
+//
+// What's computable live: anything that needs only CURRENT balances — the full
+// holder count, the whale slice (top-fraction by balance), and concentration.
+// What's NOT: tenure cohorts (diamond-hands / new-buyers / exited) need
+// first_seen / last_seen history, which only exists once a mint is snapshotted.
+// Those are reported as `null` (unknown) — never fabricated as zero.
+//
+// Sampling reuses the same deterministic bucketing as the snapshot path
+// (sampleBucket / inSample from cohorts.js), so a "10% of whales" draw is
+// stable whether it runs against live data or a snapshot.
+
+import { fetchHolderBalances } from './holders.js';
+import { sampleBucket, inSample } from './cohorts.js';
+
+// Cohorts derivable from current balances alone (the rest need snapshot history).
+const LIVE_COHORT_IDS = new Set(['holders', 'whales']);
+
+/** True when a cohort can be computed without snapshot history. */
+export function isLiveCohort(cohortId) {
+ return LIVE_COHORT_IDS.has(cohortId);
+}
+
+function numOr(value, fallback) {
+ const n = typeof value === 'number' ? value : parseFloat(value);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+function clampTopPct(value) {
+ return Math.min(Math.max(numOr(value, 0.1), 0.0001), 1);
+}
+
+// share of a BigInt amount in a BigInt total as a float with ~9 sig digits —
+// computed in integer space first so huge supplies never overflow Number.
+function shareOf(units, total) {
+ if (total <= 0n) return 0;
+ return Number((units * 1_000_000_000n) / total) / 1_000_000_000;
+}
+
+function round4(x) {
+ return Math.round(x * 10000) / 10000;
+}
+
+function concentrationLabel(holderCount, top10Share) {
+ if (holderCount === 0) return 'none';
+ if (top10Share >= 0.8) return 'very-high';
+ if (top10Share >= 0.5) return 'high';
+ if (top10Share >= 0.25) return 'moderate';
+ return 'healthy';
+}
+
+// The balance at the top-`topPct` rank. ceil(n × topPct) wallets qualify; ties
+// at the boundary are included (so the set is at-least-topPct). Mirrors
+// whaleThreshold() in cohorts.js, but over the already-fetched live list.
+function whaleCutoff(holders, topPct) {
+ if (holders.length === 0) return null;
+ const rank = Math.max(1, Math.ceil(holders.length * topPct));
+ return holders[Math.min(rank, holders.length) - 1].units;
+}
+
+/**
+ * Fetch the live holder set for a mint once, sorted by balance desc, with the
+ * total supply held. Shared by the counts overview and member export so a
+ * single Helius fetch serves both.
+ *
+ * @param {object} opts
+ * @param {string} opts.mint
+ * @param {'mainnet'|'devnet'} [opts.network]
+ * @returns {Promise<{holders: Array<{wallet:string, units:bigint}>, totalUnits: bigint}>}
+ */
+export async function liveHolderSet({ mint, network = 'mainnet' }) {
+ const balances = await fetchHolderBalances({ mint, network });
+ const holders = [...balances.entries()]
+ .map(([wallet, units]) => ({ wallet, units }))
+ .filter((h) => h.units > 0n)
+ .sort((a, b) => (b.units > a.units ? 1 : b.units < a.units ? -1 : 0));
+ const totalUnits = holders.reduce((sum, h) => sum + h.units, 0n);
+ return { holders, totalUnits };
+}
+
+/**
+ * Per-cohort counts + concentration computed from a live holder set. Tenure
+ * cohorts (diamond-hands / new-buyers / exited) are null — unknown without a
+ * snapshot — so callers can render "needs snapshot" instead of a fake 0.
+ *
+ * @param {{holders: Array, totalUnits: bigint}} set
+ * @param {object} [params] cohort tunables (topPct)
+ */
+export function liveCohortCounts(set, params = {}) {
+ const { holders, totalUnits } = set;
+ const holderCount = holders.length;
+ const topPct = clampTopPct(params.topPct);
+
+ let whales = 0;
+ const cutoff = whaleCutoff(holders, topPct);
+ if (cutoff != null) whales = holders.filter((h) => h.units >= cutoff).length;
+
+ const top1Share = holderCount ? shareOf(holders[0].units, totalUnits) : 0;
+ const top10Share = holders.slice(0, 10).reduce((s, h) => s + shareOf(h.units, totalUnits), 0);
+
+ return {
+ holderCount,
+ counts: {
+ holders: holderCount,
+ whales,
+ 'diamond-hands': null,
+ 'new-buyers': null,
+ exited: null,
+ },
+ concentration: {
+ top1Share: round4(top1Share),
+ top10Share: round4(top10Share),
+ label: concentrationLabel(holderCount, top10Share),
+ },
+ };
+}
+
+/**
+ * Live member export for a snapshot-independent cohort (holders | whales),
+ * sorted by balance desc, with optional deterministic sampling. Throws for
+ * tenure cohorts, which require snapshot history.
+ *
+ * @param {{holders: Array}} set
+ * @param {object} opts
+ * @param {string} opts.cohortId
+ * @param {object} [opts.params]
+ * @param {number} [opts.limit] max members returned (1–1000, default 200)
+ * @param {number} [opts.sample] 0–1 fraction to keep via deterministic bucketing
+ * @param {string} [opts.salt] sampling salt (defaults to the mint)
+ * @returns {{members: Array, sampled: boolean, total: number, truncated: boolean}}
+ */
+export function liveCohortMembers(set, { cohortId, params = {}, limit = 200, sample, salt = 'live' }) {
+ if (!isLiveCohort(cohortId)) {
+ const err = new Error(`cohort "${cohortId}" requires a holder snapshot`);
+ err.code = 'snapshot_required';
+ throw err;
+ }
+ let pool = set.holders;
+ if (cohortId === 'whales') {
+ const cutoff = whaleCutoff(pool, clampTopPct(params.topPct));
+ pool = cutoff == null ? [] : pool.filter((h) => h.units >= cutoff);
+ }
+
+ const doSample = sample != null && sample > 0 && sample < 1;
+ if (doSample) {
+ pool = pool.filter((h) => inSample(sampleBucket(h.wallet, cohortId, salt), sample));
+ }
+
+ const pageSize = Math.min(Math.max(Math.floor(limit) || 200, 1), 1000);
+ const page = pool.slice(0, pageSize);
+ return {
+ members: page.map((h) => ({
+ wallet: h.wallet,
+ balance: h.units.toString(),
+ firstSeen: null,
+ lastSeen: null,
+ })),
+ sampled: doSample,
+ total: pool.length,
+ truncated: pool.length > pageSize,
+ };
+}
diff --git a/api/_lib/coin/index.js b/api/_lib/coin/index.js
index 6ac410831..c7c920ac8 100644
--- a/api/_lib/coin/index.js
+++ b/api/_lib/coin/index.js
@@ -25,6 +25,12 @@ export {
sampleBucket,
inSample,
} from './cohorts.js';
+export {
+ isLiveCohort,
+ liveHolderSet,
+ liveCohortCounts,
+ liveCohortMembers,
+} from './cohorts-live.js';
export {
DRAND,
roundForTime,
diff --git a/api/_lib/forge-job-token.js b/api/_lib/forge-job-token.js
new file mode 100644
index 000000000..7c3378844
--- /dev/null
+++ b/api/_lib/forge-job-token.js
@@ -0,0 +1,23 @@
+// Forge generation job-handle codec — shared by the /api/forge endpoint and the
+// 3D Studio MCP server (/api/mcp-3d).
+//
+// Jobs from the geometry providers (Meshy / Tripo) and the self-hosted GCP
+// backend are polled on a different upstream than the default Replicate path, so
+// callers are handed an opaque token that records which provider + task-kind to
+// poll. The legacy Replicate path keeps returning its bare prediction id (which
+// matches JOB_ID_RE), so old links and existing job handles never break.
+
+export function encodeJobToken({ provider, kind, taskId }) {
+ return `f1.${Buffer.from(JSON.stringify({ p: provider, k: kind, t: taskId }), 'utf8').toString('base64url')}`;
+}
+
+export function decodeJobToken(token) {
+ if (typeof token !== 'string' || !token.startsWith('f1.')) return null;
+ try {
+ const obj = JSON.parse(Buffer.from(token.slice(3), 'base64url').toString('utf8'));
+ if (!obj?.p || !obj?.t) return null;
+ return { provider: obj.p, kind: obj.k || null, taskId: String(obj.t) };
+ } catch {
+ return null;
+ }
+}
diff --git a/api/_lib/forge-provider-key.js b/api/_lib/forge-provider-key.js
new file mode 100644
index 000000000..178f08b61
--- /dev/null
+++ b/api/_lib/forge-provider-key.js
@@ -0,0 +1,36 @@
+// BYOK key resolution for the geometry generation providers (Meshy / Tripo) —
+// shared by the /api/forge endpoint and the 3D Studio MCP server (/api/mcp-3d).
+//
+// No platform key exists for these backends, so the key must come from the
+// caller. Two real sources, in priority order:
+// 1. An inline key on the request — header `x-forge-provider-key` (preferred,
+// kept out of URLs/logs) or `provider_key` in the POST body. Used
+// transiently and never persisted.
+// 2. The signed-in user's stored, encrypted key (the dashboard BYOK store),
+// when the request carries a session cookie.
+// Returns the plaintext key or null when none is available.
+
+import { getSessionUser } from './auth.js';
+import { sql } from './db.js';
+import { loadUserProviderKeys } from './provider-keys.js';
+
+export async function resolveProviderKey(req, body, providerName) {
+ const header = req.headers['x-forge-provider-key'];
+ const inline =
+ (typeof header === 'string' && header) ||
+ (Array.isArray(header) && header[0]) ||
+ (typeof body?.provider_key === 'string' ? body.provider_key : '');
+ if (inline && inline.trim()) return inline.trim();
+
+ try {
+ const session = await getSessionUser(req);
+ if (session?.id) {
+ const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${session.id}`;
+ const keys = await loadUserProviderKeys(row?.provider_keys);
+ if (keys[providerName]) return keys[providerName];
+ }
+ } catch {
+ // No DB / no session — fall through to "no key".
+ }
+ return null;
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 7b8f27660..4299fd63d 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -163,6 +163,11 @@ export const limits = {
// `authIp` budget shared by on-chain buy/sell/launch actions. Iterating in
// the launch wizard would otherwise lock the user out of trading for 10 min.
pumpMetaIp: (ip) => getLimiter('pump:meta:ip', { limit: 60, window: '10 m' }).limit(ip),
+ // Live holder-cohort reads (api/coin/:mint/cohorts for un-snapshotted agent
+ // tokens) fan out to a paid Helius getTokenAccounts walk. Responses are CDN-
+ // cached, so this only gates cache-miss origin hits — generous for an
+ // interactive panel, tight enough that one IP can't run up the Helius bill.
+ cohortsIp: (ip) => getLimiter('cohorts:ip', { limit: 45, window: '5 m' }).limit(ip),
oauthRegisterIp: (ip) =>
getLimiter('oauth:register:ip', { limit: 10, window: '1 h' }).limit(ip),
// aixbt intelligence bridge (api/aixbt/*). Each call may fall through to the
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index dc0643075..24bcf241d 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -1,18 +1,42 @@
// three.ws 3D Studio MCP — generation tools.
//
// text_to_3d / image_to_3d submit a reconstruction job and return a job handle.
-// generation_status polls that job. preview_3d renders any GLB inline.
-// remove_background strips image backgrounds (rembg/BRIA RMBG-2.0).
+// Both accept a quality tier (draft/standard/high) and a generation path:
+// "image" (FLUX→TRELLIS, the platform-keyed default) or "geometry" (native
+// text/image→mesh via Meshy/Tripo, BYOK). generation_status polls any job —
+// it is provider-aware, decoding the forge job token to route geometry jobs.
+// auto_rig_model adds a skeleton + skin weights to a static mesh (rerig).
+// preview_3d renders any GLB inline. remove_background strips image backgrounds.
// remesh_model converts, simplifies, and repairs meshes.
// stylize_model applies one-click geometric filters (voxel/brick/voronoi/lowpoly).
// retexture_model paints a new texture onto a mesh from a text prompt.
// retexture_region (magic brush) repaints only a masked UV region, preserving the rest.
+// pose_model maps a prompt to a deterministic pose-studio seed + joint rotations.
+// direct_prompt (IBM Granite) rewrites a rough idea into an optimized 3D spec.
+// generate_material (IBM Granite) emits a glTF PBR material from a description.
import { limits } from '../../_lib/rate-limit.js';
import { assertSafePublicUrl } from '../../_lib/ssrf-guard.js';
import { createRegenProvider as createReplicateProvider } from '../../_providers/replicate.js';
import { createRegenProvider as createGcpProvider } from '../../_providers/gcp.js';
+import { createMeshyProvider } from '../../_providers/meshy.js';
+import { createTripoProvider } from '../../_providers/tripo.js';
import { textToImage } from '../text-to-image.js';
+import {
+ PATHS,
+ DEFAULT_PATH,
+ TIER_IDS,
+ DEFAULT_TIER,
+ BACKENDS,
+ resolveTier,
+ resolveBackendId,
+ estimateEtaSeconds,
+ estimateCredits,
+} from '../../_lib/forge-tiers.js';
+import { resolveProviderKey } from '../../_lib/forge-provider-key.js';
+import { encodeJobToken, decodeJobToken } from '../../_lib/forge-job-token.js';
+import { watsonxConfig, watsonxChatComplete } from '../../_lib/watsonx.js';
+import { PRESETS, PRESET_GROUPS } from '../../../src/pose-presets.js';
import {
renderModelViewerHtml,
safeCssValue,
@@ -114,6 +138,105 @@ function viewerArtifact({ glbUrl, name, options = {} }) {
};
}
+// ── Quality tier + generation path/backend (shared by text_to_3d/image_to_3d) ──
+// Mirrors the /api/forge axes: `path` ("image" vs "geometry"), `tier`
+// (draft/standard/high poly budget), `backend` (trellis/meshy/tripo/hunyuan3d).
+// The default — path "image", backend "trellis" — keeps the existing fast
+// platform-keyed reconstruction untouched.
+function parsePathArg(args) {
+ const p = typeof args?.path === 'string' ? args.path.trim() : '';
+ return PATHS.includes(p) ? p : DEFAULT_PATH;
+}
+function parseTierArg(args) {
+ const t = typeof args?.tier === 'string' ? args.tier.trim() : '';
+ return TIER_IDS.includes(t) ? t : DEFAULT_TIER;
+}
+
+const TIER_PROP = {
+ type: 'string',
+ enum: TIER_IDS,
+ default: DEFAULT_TIER,
+ description:
+ 'Quality tier: draft (~12k poly, fast), standard (~30k, balanced), high (~200k + PBR, slower). Honoured by poly-aware backends (Meshy/Tripo/Hunyuan3D); the TRELLIS default records it as provenance.',
+};
+const PATH_PROP = {
+ type: 'string',
+ enum: PATHS,
+ default: DEFAULT_PATH,
+ description:
+ 'Generation path: "image" (FLUX→TRELLIS reference-image reconstruction, the platform-keyed default) or "geometry" (native text/image→mesh via Meshy/Tripo — cleaner topology, but BYOK: needs your own provider key).',
+};
+const BACKEND_PROP = {
+ type: 'string',
+ enum: Object.keys(BACKENDS),
+ description:
+ 'Force a specific backend (trellis, meshy, tripo, hunyuan3d). Defaults to the best one for the chosen path. Backends outside the path are ignored.',
+};
+
+// "needs a BYOK key" — a designed, branchable result (mirrors /api/forge's
+// needs_key state), not an error: the geometry providers have no platform key,
+// so a caller without one is told exactly how to enable the path.
+function needsKeyResult(backendId) {
+ const meta = BACKENDS[backendId];
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `The geometry path uses ${meta?.label || backendId}, which needs your own API key. ` +
+ `Send it as the "x-forge-provider-key" request header (or store a ${meta?.byok || backendId} key on your three.ws account) and retry, ` +
+ 'or use the default image path (omit "path", or set path="image").',
+ },
+ ],
+ structuredContent: { status: 'needs_key', backend: backendId, provider: meta?.byok || backendId },
+ isError: true,
+ };
+}
+
+// Submit a native geometry-first job (Meshy/Tripo, BYOK) and shape the MCP
+// response. Returns a needs_key result when no key is available. The job handle
+// is a forge token so generation_status routes the poll back to this provider.
+async function submitGeometryJob({ req, args, backendId, isImageMode, prompt, primaryImage, tier, path }) {
+ const providerName = BACKENDS[backendId].byok; // 'meshy' | 'tripo'
+ const key = await resolveProviderKey(req, args, providerName);
+ if (!key) return needsKeyResult(backendId);
+
+ let gp;
+ try {
+ gp = backendId === 'tripo' ? createTripoProvider(key) : createMeshyProvider(key);
+ } catch {
+ return needsKeyResult(backendId);
+ }
+
+ const submitted = isImageMode
+ ? await gp.imageTo3d({ imageUrl: primaryImage, prompt: prompt || undefined, tier })
+ : await gp.textToGeometry({ prompt, tier });
+ const token = encodeJobToken({ provider: providerName, kind: submitted.kind, taskId: submitted.taskId });
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Started ${isImageMode ? 'image-to-3D' : 'text-to-3D'} on ${BACKENDS[backendId].label} ` +
+ `(${path} path, ${tier.id} tier).\nJob ID: ${token}\n${POLL_HINT}`,
+ },
+ ],
+ structuredContent: {
+ job_id: token,
+ status: 'queued',
+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
+ path,
+ tier: tier.id,
+ backend: backendId,
+ prompt: prompt || null,
+ source_image_url: isImageMode ? primaryImage : null,
+ eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ estimated_credits: estimateCredits({ backendId, path, tier }),
+ },
+ };
+}
+
export const toolDefs = [
{
name: 'text_to_3d',
diff --git a/api/forge.js b/api/forge.js
index 37baf745f..a3ca9a1e3 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -45,9 +45,8 @@ import {
estimateCredits,
buildCatalog,
} from './_lib/forge-tiers.js';
-import { getSessionUser } from './_lib/auth.js';
-import { sql } from './_lib/db.js';
-import { loadUserProviderKeys } from './_lib/provider-keys.js';
+import { resolveProviderKey } from './_lib/forge-provider-key.js';
+import { encodeJobToken, decodeJobToken } from './_lib/forge-job-token.js';
import {
hashClient,
hashIp,
@@ -92,54 +91,6 @@ function parseTier(body) {
return TIER_IDS.includes(t) ? t : DEFAULT_TIER;
}
-// BYOK key resolution for the geometry providers (Meshy / Tripo). No platform
-// key exists for these, so the key must come from the caller. Two real sources,
-// in priority order:
-// 1. An inline key on the request — header `x-forge-provider-key` (preferred,
-// kept out of URLs/logs) or `provider_key` in the POST body. Used
-// transiently and never persisted.
-// 2. The signed-in user's stored, encrypted key (the dashboard BYOK store),
-// when the request carries a session cookie.
-// Returns the plaintext key or null when none is available.
-async function resolveProviderKey(req, body, providerName) {
- const header = req.headers['x-forge-provider-key'];
- const inline =
- (typeof header === 'string' && header) ||
- (Array.isArray(header) && header[0]) ||
- (typeof body?.provider_key === 'string' ? body.provider_key : '');
- if (inline && inline.trim()) return inline.trim();
-
- try {
- const session = await getSessionUser(req);
- if (session?.id) {
- const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${session.id}`;
- const keys = await loadUserProviderKeys(row?.provider_keys);
- if (keys[providerName]) return keys[providerName];
- }
- } catch {
- // No DB / no session — fall through to "no key".
- }
- return null;
-}
-
-// Jobs from the geometry providers are polled on a different upstream than the
-// default Replicate path, so we hand the browser an opaque token that records
-// which provider + task-kind to poll. The legacy Replicate path keeps returning
-// its bare prediction id (it matches JOB_ID_RE), so old links never break.
-function encodeJobToken({ provider, kind, taskId }) {
- return `f1.${Buffer.from(JSON.stringify({ p: provider, k: kind, t: taskId }), 'utf8').toString('base64url')}`;
-}
-function decodeJobToken(token) {
- if (typeof token !== 'string' || !token.startsWith('f1.')) return null;
- try {
- const obj = JSON.parse(Buffer.from(token.slice(3), 'base64url').toString('utf8'));
- if (!obj?.p || !obj?.t) return null;
- return { provider: obj.p, kind: obj.k || null, taskId: String(obj.t) };
- } catch {
- return null;
- }
-}
-
// "needs a BYOK key" — a designed, branchable state (mirrors rig_unconfigured)
// rather than a generic error, so the page can prompt for the key inline.
function needsKey(res, providerName) {
diff --git a/pages/three-live.html b/pages/three-live.html
index 88c512065..4b4c29e1a 100644
--- a/pages/three-live.html
+++ b/pages/three-live.html
@@ -199,6 +199,11 @@
<span>BUSY</span>
<span class="reading" id="pl-activity-reading">—</span>
</div>
+ <div class="pl-links" style="display:flex;gap:14px;margin-top:12px;flex-wrap:wrap;font-family:var(--pl-mono);font-size:11.5px">
+ <a href="/three-token" style="color:var(--pl-faint);text-decoration:none">▸ Price &amp; trades</a>
+ <a href="/dashboard/holders" style="color:var(--pl-faint);text-decoration:none">▸ Holder leaderboard</a>
+ <a href="https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener" style="color:var(--pl-faint);text-decoration:none">▸ Buy $THREE ↗</a>
+ </div>
</section>
<!-- Live trade ticker -->
diff --git a/pages/three-token.html b/pages/three-token.html
new file mode 100644
index 000000000..d20b174d3
--- /dev/null
+++ b/pages/three-token.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>$THREE · Live price, chart & trades · three.ws</title>
+ <meta name="description" content="The $THREE protocol token — live price, bonding-curve chart, streaming trades, and one-click buy. The only coin powering the three.ws agent economy." />
+ <meta property="og:title" content="$THREE · three.ws protocol token" />
+ <meta property="og:description" content="Live price, bonding-curve chart, and streaming trades for $THREE." />
+ <meta name="theme-color" content="#0a0a0d" />
+ <link rel="icon" href="/favicon.ico" />
+ </head>
+ <body>
+ <script type="module" src="/src/three-token-page.js"></script>
+ </body>
+</html>
diff --git a/prompts/tripo-gap/00-README.md b/prompts/tripo-gap/00-README.md
new file mode 100644
index 000000000..77026584a
--- /dev/null
+++ b/prompts/tripo-gap/00-README.md
@@ -0,0 +1,49 @@
+# Tripo-gap build set
+
+Four self-contained agent prompts. Each closes a specific gap against Tripo AI
+(tripo3d.ai) or extends a strength they cannot match. Run each in its own fresh
+chat — they are independent and do not share context.
+
+## The strategic picture
+
+We are **not** behind Tripo overall. We lead on the avatar / animation / video
+axis (audio-driven talking-avatar video, ARKit-52 blendshape rigs, in-browser
+pose studio + retargetable animation library, multi-model generation ensemble,
+x402 agent-payments). Tripo leads on the **general 3D-asset production pipeline**
+axis (clean game-ready topology generation, engine/DCC plugins, a mature paid
+API, hero-detail high-poly). These prompts attack the four highest-leverage
+items.
+
+## The prompts (run in this priority order)
+
+| # | File | Closes | Effort | Why |
+|---|------|--------|--------|-----|
+| 01 | `01-text-to-animation.md` | Tripo has **no** text-to-animation | Large | Strongest differentiator. Reuses our rig + retarget + pose studio. Compounds into the video generator. |
+| 02 | `02-game-ready-export-tier.md` | Tripo's Smart-Mesh / clean topology | Small | Cheapest visible win. The pieces (QuadriFlow quad-remesh, smart low-poly, FBX export) already exist in `workers/remesh/` — they just aren't surfaced. |
+| 03 | `03-blender-comfyui-plugins.md` | Tripo's plugin ecosystem (Blender, Unity, Unreal, ComfyUI) | Medium | Pure distribution. We have zero plugin coverage; this is how Tripo reaches game/film devs. |
+| 04 | `04-monetized-3d-api-mcp.md` | Tripo's paid API + official MCP gen tools | Medium | Turns our forge pipeline into a documented, x402-gated paid API + MCP tools. A moat Tripo structurally can't copy. |
+
+## Run order rationale
+
+- **01 first** if you want the biggest moat — it is the one capability Tripo
+ cannot ship without rebuilding their whole animation stack.
+- **02 first** if you want a fast, shippable win this week.
+- **03 and 04 reinforce each other**: the plugins (03) are far more valuable once
+ the API is publicly documented and authenticated (04). If you run both, do 04
+ before 03 so the plugins target the finished public surface — but 03 can also
+ ship against the existing internal `api/forge.js` with an API key.
+
+## Rails that apply to every prompt
+
+Each file restates these, but they are non-negotiable and come from
+`/workspaces/three.ws/CLAUDE.md` — read that file in full before starting any of
+these tasks:
+
+- No mocks, no fake data, no placeholders, no fallback sample arrays. Real
+ models, real APIs, real endpoints.
+- No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.
+- The only coin is `$three` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference any other coin anywhere.
+- Done = wired 100% into the UI, reachable, exercised for real, `npm test` green,
+ `git diff` self-reviewed. Run the **completionist** subagent before stopping.
+- Push only when the user says so, then to BOTH remotes (`threeD` and `threews`).
diff --git a/prompts/tripo-gap/01-text-to-animation.md b/prompts/tripo-gap/01-text-to-animation.md
new file mode 100644
index 000000000..9a855b4f2
--- /dev/null
+++ b/prompts/tripo-gap/01-text-to-animation.md
@@ -0,0 +1,177 @@
+# Task: Text-to-animation — generate motion from a prompt, retarget onto the user's avatar
+
+## Why this exists
+
+Tripo AI cannot generate animation from a text description. Their animation is
+limited to applying preset clips and Mixamo/Tripo retargeting. We already own
+every downstream piece — a rigged humanoid skeleton on every avatar, a runtime
+retargeting engine, a pose studio with animated-GLB export, and an animation
+library. The only missing link is a **motion-diffusion model** that turns a text
+prompt ("waving confidently", "a slow tai-chi sweep", "celebratory jump") into a
+motion clip we can retarget onto the user's avatar and preview live.
+
+This is our single most defensible feature versus Tripo. Build it completely.
+
+## Rails (CLAUDE.md — non-negotiable; read the full file first)
+
+- **No mocks, no fake data, no placeholders, no fallback sample arrays.** Use a
+ real motion-diffusion model running in a real worker. If a credential or model
+ weight is missing, find it in `.env` / `vercel env` / the worker's deploy
+ config or ask once, then proceed.
+- **No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.**
+ If you write it, finish it and wire it 100% — worker → API → UI → export.
+- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference any other coin anywhere.
+- **Every state designed** (loading/empty/error/populated); every control has
+ hover/active/focus; responsive; accessible; real async indicators.
+- **Done = reachable in the browser, exercised end-to-end, `npm test` green,
+ `git diff` self-reviewed.** Run the **completionist** subagent before stopping.
+- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
+
+## Explore first (spawn these before writing code)
+
+### Subagent A (Explore) — the worker pattern
+> In `/workspaces/three.ws/workers/`, read `model-trellis/`, `model-hunyuan3d/`,
+> and `model-triposr/` and document the exact worker contract they share: HTTP
+> framework, the `POST /infer` request/response shape, the queued-job model
+> (`GET /tasks/:id` polling), how they fetch inputs and upload outputs (GCS/R2),
+> how Firestore/job state is tracked, the Dockerfile/deploy layout, and the
+> GPU/runtime assumptions. Quote `requirements.txt` / `Dockerfile` / the main
+> entry file for one of them verbatim. I am adding a new sibling worker that must
+> match this contract exactly.
+
+### Subagent B (Explore) — the retarget + animation surface
+> In `/workspaces/three.ws`, read and quote the public API of:
+> 1. `src/animation-retarget.js` — the retargeting engine. What skeleton/bone
+> naming does it expect as the *source*? How does it map onto our Wolf3D
+> 25-joint humanoid? What is the minimum-coverage rule?
+> 2. `src/animation-library.js` — how clips are stored, listed, and applied.
+> 3. `src/pose-studio.js` — how it loads a rigged GLB, plays an animation, and
+> exports an animated GLB (the glTF animation-track baking path).
+> 4. `api/_mcp/tools/animations.js` — the existing `apply_animation`,
+> `list_animations`, `create_animation_clip` tools.
+> 5. The existing `prompts/animation-studio/` prompt set — what was already built
+> vs. planned. Quote `00-README.md`.
+> Also report where `/public/animations/` clips live and their format (GLB/FBX),
+> and the exact bone names of our target rig (from `workers/unirig/rig_glb.py`).
+
+Wait for both before starting.
+
+## What to build
+
+### Step 1 — the motion-diffusion worker
+
+Create `workers/model-text2motion/` matching the `model-*` worker contract
+Subagent A documented (same framework, same `POST /infer` → `GET /tasks/:id`
+queued-job shape, same output-upload path).
+
+Model selection — pick a **commercially-licensed** text-to-motion model and state
+the license in the worker README. Evaluate, in order of preference:
+- **MDM (Motion Diffusion Model)** — MIT, HumanML3D skeleton, well-supported.
+- **MoMask** / **T2M-GPT** — higher quality; verify the license is
+ commercial-safe before adopting. If the license is non-commercial, do **not**
+ use it — fall back to MDM.
+
+Contract:
+- `POST /infer { prompt, length_seconds?=4, fps?=30, job_id? }` → `202 { task_id }`
+- `GET /tasks/:id` → `{ status, clip_url }` where `clip_url` is a GLB (or BVH)
+ carrying the generated motion on the model's native skeleton
+ (HumanML3D/SMPL 22-joint).
+- Output upload to the same bucket the other workers use.
+- Real GPU inference. No canned/sample motion. Sanitize NaN/Inf the way
+ `rig_glb.py` does.
+
+Convert the model's native motion output into a clip on a **standard skeleton**
+(HumanML3D/SMPL joint names) so the existing retarget engine can map it — do the
+SMPL→named-skeleton conversion in the worker, not in the browser.
+
+### Step 2 — the API endpoint
+
+Add a backend endpoint that ties prompt → worker → retarget → user's avatar.
+Reuse `api/forge.js`'s job conventions (`?job=<id>` polling, the queued-status
+shape) and the existing R2/DB helpers (`api/_lib/r2.js`, `api/_lib/db.js`).
+Prefer extending `api/_mcp/tools/animations.js`'s `create_animation_clip` to
+accept a `prompt`, plus a thin public route (e.g. `api/animate.js` or a
+`path: "text"` branch on the animation API) that:
+
+1. Submits the prompt to the text2motion worker, returns a `job_id`.
+2. On completion, retargets the generated clip onto the requesting avatar's rig
+ using the engine from `src/animation-retarget.js` (run it server-side in Node
+ — Subagent B confirmed it runs in Node as well as the browser).
+3. Stores the retargeted animated GLB in R2 under the avatar's namespace and
+ records the clip in the animation library so it shows up in the user's list.
+4. Returns the clip URL + metadata.
+
+Handle errors at the boundary: bad prompt, worker timeout, a rig the retargeter
+can't cover (<50% bone coverage) → a real, actionable error, never a fake clip.
+
+### Step 3 — wire the UI
+
+In the pose/animation studio (`src/pose-studio.js` + its page, and/or the
+`prompts/animation-studio/` surface), add a **"Generate from text"** control:
+
+- A prompt input with a length slider and a Generate button.
+- Loading state: a real progress indicator tied to the job poll (skeleton/au
+ progress, not a fake timer).
+- On success: the clip auto-loads onto the avatar in the viewport and plays,
+ with the existing scrub/speed/loop controls.
+- Save to library (reuses `animation-library.js`) and **Export animated GLB**
+ (reuses the pose-studio baking path).
+- Empty state explains what to type; error state explains failure + recovery.
+- Hover/active/focus on every control; keyboard-operable; responsive at 320 /
+ 768 / 1440.
+
+### Step 4 — MCP + monetization hooks
+
+- Expose `text_to_animation(avatar_id, prompt, length?)` as an MCP tool
+ alongside the existing animation tools in `api/_mcp/tools/animations.js`.
+- Respect the existing usage/plan gating pattern (see how
+ `api/avatar/video-generate` meters free vs. paid in `usage_events`). Free tier
+ gets a small quota; paid is unlimited. No new coin references — billing is in
+ the platform's existing units / `$three` only where a token is surfaced.
+
+### Step 5 — deploy config
+
+- Add the worker to whatever deploy manifest the other `model-*` workers use
+ (`workers/deploy/` or each worker's own deploy file — match the pattern).
+- If the retarget step runs in a Vercel function, confirm its `maxDuration` in
+ `vercel.json` is sufficient (retarget is fast; the wait is the worker job,
+ which is polled, not held).
+
+### Step 6 — tests
+
+- Unit-test the SMPL→named-skeleton conversion with a tiny synthetic motion
+ array (assert joint count, no NaN, monotonic time track).
+- Unit-test the retarget call on a fixture rig (reuse any rig fixture the repo
+ already has; otherwise build a minimal rigged GLB the way
+ `tests/render-glb.test.js` builds its triangle GLB).
+- Gate the real-worker GPU path behind an env flag (e.g.
+ `RUN_GPU_TESTS=1`) and document the skip, mirroring the headful-render test
+ convention in `tests/render-glb.test.js`.
+- Endpoint test: stub the worker call at the module boundary, assert the
+ endpoint submits the job, retargets, writes R2, records the library row.
+
+### Step 7 — docs
+
+- `workers/model-text2motion/README.md`: model, license, contract, deploy.
+- Add a PROGRESS.md item describing what shipped.
+- If `prompts/animation-studio/` lists text-to-animation as future work, mark it
+ done there.
+
+## Definition of done
+
+- A user types a prompt in the studio and a real, model-generated motion plays on
+ their own avatar within the job's normal latency — no canned clips.
+- The clip saves to their library and exports as an animated GLB.
+- `text_to_animation` works as an MCP tool with plan gating.
+- `npm test` green (GPU path skipped in CI, documented).
+- The new worker matches the existing `model-*` contract exactly.
+- `git diff` self-reviewed; completionist subagent run and its findings fixed.
+
+## Constraints
+
+- Use a real, commercially-licensed motion model. State the license. If unsure,
+ use MDM (MIT). Never ship a non-commercial model in production.
+- Do the SMPL→skeleton conversion in the worker, not the browser.
+- Reuse `src/animation-retarget.js` — do not write a second retargeter.
+- No fake/sample motion anywhere, including tests' "happy path."
diff --git a/prompts/tripo-gap/02-game-ready-export-tier.md b/prompts/tripo-gap/02-game-ready-export-tier.md
new file mode 100644
index 000000000..53b667a96
--- /dev/null
+++ b/prompts/tripo-gap/02-game-ready-export-tier.md
@@ -0,0 +1,141 @@
+# Task: "Game-Ready" export tier in Forge — surface the topology pipeline we already built
+
+## Why this exists
+
+Tripo markets clean, game-ready topology (Smart Mesh / smart retopology) as a
+flagship differentiator. We already have the hard parts shipped and tested in
+`workers/remesh/` — QuadriFlow quad remeshing (MIT, commercial-safe),
+silhouette-preserving smart low-poly with UV re-unwrap + texture re-bake, target
+face-count decimation, and **FBX export that preserves rigs via headless
+Blender**. They are buried behind a raw worker endpoint and never surfaced in the
+product. This task wires a one-click **Game-Ready** output into Forge so any
+generated or uploaded model can be turned into an engine-ready asset.
+
+This is the cheapest high-visibility win in the set. Do it completely and make it
+feel polished.
+
+## Rails (CLAUDE.md — non-negotiable; read the full file first)
+
+- **No mocks, no fake data, no placeholders, no fallback sample arrays.** Real
+ remesh worker, real output. If a credential is missing, find it or ask once.
+- **No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.**
+ Wire 100%: UI → API → worker → result download.
+- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference any other coin anywhere.
+- **Every state designed** (loading/empty/error/populated); hover/active/focus on
+ every control; responsive; accessible; real async indicators (skeletons, not
+ fake progress bars).
+- **Done = reachable, exercised in a real browser, `npm test` green, `git diff`
+ self-reviewed.** Run the **completionist** subagent before stopping.
+- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
+
+## Explore first (spawn before writing code)
+
+### Subagent A (Explore) — the remesh worker contract
+> In `/workspaces/three.ws/workers/remesh/`, read `main.py` (and any README) and
+> quote: the exact `POST /process` request body (`mesh`, `remesh_mode`,
+> `operation`, `target_faces`, `texture_size`, `output_format`, anything else),
+> the `202 { task_id }` + `GET /tasks/:id` polling shape, the full list of
+> supported `output_format` values, the quad-remesh (QuadriFlow) options, the
+> smart-lowpoly options, and how FBX export preserves skeleton/skin/blendshapes
+> via Blender. State which input formats it fetches by URL.
+
+### Subagent B (Explore) — the Forge surface
+> In `/workspaces/three.ws`, quote:
+> 1. `api/forge.js` — the job submit/poll contract, and `?catalog` output.
+> 2. `api/_lib/forge-tiers.js` — the tier/backend registry shape (how
+> draft/standard/high are defined, ETA + credit cost fields).
+> 3. `src/forge.js` + `pages/forge.html` — how results render, where the
+> download / segment / stylize buttons live, and how a post-generation action
+> (like segment) is invoked and polled from the result view.
+> 4. `api/forge-segment.js` — the pattern for a "take the generated GLB and run a
+> worker on it" follow-up endpoint. This is the template to copy.
+> 5. The R2/DB helpers used by those endpoints (`api/_lib/r2.js`, `api/_lib/db.js`).
+
+Wait for both before starting.
+
+## What to build
+
+### Step 1 — the follow-up endpoint
+
+Create `api/forge-gameready.js` modeled on `api/forge-segment.js` (Subagent B's
+template). It takes a generated/uploaded GLB URL plus options and drives the
+remesh worker:
+
+- `POST /api/forge-gameready { mesh_url, topology: "quad"|"tri", poly_budget,
+ texture_size, formats: ["glb","fbx"] }` → `202 { job_id }`.
+- Calls the remesh worker with the right `remesh_mode` / `operation` (quad →
+ QuadriFlow; tri → smart-lowpoly decimation), the poly budget as `target_faces`,
+ and bakes PBR at the chosen `texture_size`.
+- Produces **both** a GLB and (when requested) a rigged FBX via the worker's
+ Blender path.
+- Uploads results to R2 under the model's namespace; returns the URLs.
+- `GET /api/forge-gameready?job=<id>` polls, matching `api/forge.js`'s status
+ shape.
+- Boundary error handling: worker failure / unreachable mesh / impossible budget
+ → a real actionable error, never a silent or faked result.
+
+### Step 2 — register it as a Forge output option
+
+In `api/_lib/forge-tiers.js`, add the Game-Ready output as a first-class,
+catalog-visible option (with realistic ETA + cost fields consistent with the
+existing tiers) so `GET /api/forge?catalog` advertises it.
+
+### Step 3 — wire the Forge UI
+
+In `src/forge.js` + `pages/forge.html`, add a **"Game-Ready"** action to the
+result view, next to the existing Segment / Stylize / Download buttons:
+
+- Opens a small panel: topology toggle (Quad / Tri), a poly-budget slider with
+ sensible presets (e.g. 5k / 15k / 50k), texture-size selector (1k/2k), and
+ format checkboxes (GLB, FBX).
+- Submit → real job poll with a skeleton/progress indicator.
+- On success: show before/after poly counts, a live preview of the retopologized
+ mesh in the viewport, and download buttons for each format.
+- Empty/disabled state explains it needs a generated or loaded model; error state
+ explains failure + how to retry with a different budget.
+- Hover/active/focus on every control; keyboard-operable; responsive at 320 /
+ 768 / 1440.
+
+### Step 4 — quality details that make it feel finished
+
+- Show the **poly-count delta** ("28,400 → 5,012 tris, quad-dominant") — this is
+ the proof-of-value game devs screenshot.
+- Surface a topology wireframe toggle on the preview so users can see the clean
+ quads.
+- Default the budget to a value appropriate to the model's current size, not a
+ fixed number.
+
+### Step 5 — tests
+
+- Endpoint test: stub the worker at the module boundary; assert
+ `forge-gameready` submits with the correct `remesh_mode`/`target_faces`,
+ polls, writes R2, returns both formats when requested.
+- Catalog test: assert the Game-Ready option appears in `?catalog` with valid
+ ETA/cost fields.
+- If a real worker round-trip test is added, gate it behind an env flag and
+ document the skip, mirroring `tests/render-glb.test.js`.
+
+### Step 6 — docs
+
+- Add a PROGRESS.md item.
+- Note the new option in any Forge user-facing copy/help.
+
+## Definition of done
+
+- From a Forge result, a user clicks Game-Ready, picks quad + a poly budget, and
+ downloads a real retopologized GLB **and** a rigged FBX produced by the remesh
+ worker.
+- The before/after poly counts and a wireframe preview are shown.
+- The option appears in `?catalog`.
+- `npm test` green.
+- `git diff` self-reviewed; completionist subagent run and findings fixed.
+
+## Constraints
+
+- Reuse `workers/remesh/` — do not write new retopology logic. This task is
+ wiring + UI, not research.
+- FBX must preserve the rig (the worker's Blender path already does this — pass
+ the right flags).
+- No placeholder/sample mesh in the result path, including tests' happy path.
+- Keep QuadriFlow (MIT) — do not introduce a non-commercial remesher.
diff --git a/prompts/tripo-gap/03-blender-comfyui-plugins.md b/prompts/tripo-gap/03-blender-comfyui-plugins.md
new file mode 100644
index 000000000..b372b7bcc
--- /dev/null
+++ b/prompts/tripo-gap/03-blender-comfyui-plugins.md
@@ -0,0 +1,143 @@
+# Task: Blender add-on + ComfyUI node for three.ws generation
+
+## Why this exists
+
+Tripo's biggest distribution advantage is its plugin ecosystem — Blender, Unity,
+Unreal, ComfyUI, Godot, Cocos. We have **zero** plugin coverage. Game and film
+artists never have to leave their tool to use Tripo; they have to leave their
+tool entirely to use us. This task ships the two highest-leverage plugins — a
+**Blender add-on** and a **ComfyUI custom node** — both driving our existing
+`api/forge.js` generation pipeline, so an artist can generate a three.ws model
+without leaving their DCC.
+
+## Rails (CLAUDE.md — non-negotiable; read the full file first)
+
+- **No mocks, no fake data, no placeholders.** The plugins call the real forge
+ API and import the real returned GLB. No bundled sample models, no fake
+ progress. If an API key flow is needed, build the real one.
+- **No TODOs, no stubs, no commented-out code, no `raise NotImplementedError`.**
+ Wire 100%: auth → submit → poll → import.
+- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference any other coin anywhere.
+- **Repo hygiene:** plugins live in a dedicated top-level dir (`integrations/`),
+ not the repo root. No scratch files committed.
+- **Done = installable and exercised** against a running API, README with install
+ steps, `npm test` still green (no regressions to the web app). Run the
+ **completionist** subagent before stopping.
+- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
+
+## Explore first (spawn before writing code)
+
+### Subagent A (Explore) — the forge API surface
+> In `/workspaces/three.ws`, quote the complete external contract of
+> `api/forge.js`: the `POST /api/forge` request body (`prompt`, `image_urls`,
+> `path`, `tier`, `backend`, `aspect_ratio`), the `?job=<id>` poll response
+> (`status`, `glb_url`, `image_url`, `preview_image_url`, `error`, `backend`),
+> and `?catalog`. Then document the authentication model for external callers:
+> how does an API key / token get issued and verified? Look for an API-keys
+> system (the git status referenced `tests/api/api-keys.test.js`) — quote how a
+> key is created and how an endpoint authenticates one. The plugins must use the
+> real auth path, not an unauthenticated backdoor.
+
+### Subagent B (Explore) — existing SDK / packaging conventions
+> In `/workspaces/three.ws`, check `sdk/`, `solana-agent-sdk/`,
+> `agent-payments-sdk/`, and any existing `integrations/` or `plugins/` dir for
+> packaging conventions (how a distributable artifact is structured, versioned,
+> and documented). Also confirm the public base URL of the deployed API (check
+> `vercel.json` rewrites, `api/_lib/env.js` for APP_ORIGIN, and any docs). The
+> plugins need a correct default endpoint.
+
+Wait for both before starting.
+
+## What to build
+
+### Step 1 — Blender add-on
+
+Create `integrations/blender/three_ws/` — a proper Blender add-on package:
+
+- `__init__.py` with `bl_info` (name "three.ws", category "Import-Export",
+ Blender ≥ 4.0).
+- A preferences panel for the **API base URL** and **API key** (using the real
+ key system Subagent A documented).
+- An N-panel UI in the 3D viewport sidebar with:
+ - A prompt field + Generate (text → 3D).
+ - An image picker + Generate (image → 3D).
+ - Tier / backend dropdowns populated from `GET /api/forge?catalog`.
+ - A real progress readout driven by polling `?job=<id>` on a modal/timer
+ operator (Blender's `modal()` pattern — never block the UI thread).
+- On completion: download the `glb_url` and import it into the current scene via
+ Blender's glTF importer, selected and framed.
+- Real error surfacing in the Blender report system (auth failure, generation
+ failure, network) — actionable, never swallowed.
+- `README.md` with install steps (zip the folder → Edit ▸ Preferences ▸ Add-ons ▸
+ Install) and a key-setup walkthrough.
+
+### Step 2 — ComfyUI custom node
+
+Create `integrations/comfyui/three_ws_nodes/`:
+
+- `__init__.py` exporting `NODE_CLASS_MAPPINGS` / `NODE_DISPLAY_NAME_MAPPINGS`.
+- A **"three.ws Text→3D"** node: inputs `prompt`, `tier`, `backend`, `api_key`,
+ `api_url`; output the path to the downloaded GLB (a `STRING`/path output other
+ nodes can consume) plus the preview image as an `IMAGE` output.
+- A **"three.ws Image→3D"** node: `IMAGE` input → GLB path output.
+- Both submit to forge, poll to completion inside the node's execution, and
+ download the result to ComfyUI's output dir. Honor ComfyUI's caching so a
+ re-run with identical inputs doesn't re-generate.
+- Real error raising with clear messages on failure.
+- `requirements.txt` (just `requests` if that's all that's needed) and a
+ `README.md` with install steps (clone into `ComfyUI/custom_nodes/`).
+
+### Step 3 — shared client (avoid duplication)
+
+Factor the submit-and-poll logic into one small Python module reused by both
+plugins (e.g. `integrations/_pyclient/three_ws_client.py`) so the forge contract
+lives in one place. Keep it dependency-light (stdlib `urllib` or `requests`).
+
+### Step 4 — make the API external-ready (only if needed)
+
+If Subagent A finds the forge API is currently locked to same-origin /
+session-cookie auth and has no API-key path for external callers, add **real**
+API-key authentication to `api/forge.js` using the existing key system — issue,
+store (hashed), and verify a key, with a scope for generation. Do not open an
+unauthenticated route. (If prompt `04-monetized-3d-api-mcp.md` has already
+shipped, target that public surface instead and skip this step.)
+
+### Step 5 — tests + verification
+
+- Python: a unit test for the shared client against a stubbed HTTP server
+ (assert it submits the right body and polls to completion). No live network in
+ CI.
+- If you touched `api/forge.js` auth, add/extend a JS test (see
+ `tests/api/api-keys.test.js`) asserting a valid key authenticates and an
+ invalid one is rejected. `npm test` must stay green.
+- Manually verify the Blender add-on installs and generates against a running
+ API; verify the ComfyUI node loads and outputs a GLB path. Document the manual
+ steps you ran.
+
+### Step 6 — docs
+
+- `integrations/README.md` indexing both plugins.
+- A PROGRESS.md item.
+
+## Definition of done
+
+- `integrations/blender/three_ws/` installs as a Blender add-on, authenticates
+ with a real key, generates from text and image, and imports the GLB into the
+ scene with live progress.
+- `integrations/comfyui/three_ws_nodes/` loads in ComfyUI and outputs a real GLB
+ from Text→3D and Image→3D nodes.
+- Shared Python client; no duplicated forge logic.
+- API-key auth is real (existing system or new, hashed, scoped) — no
+ unauthenticated generation route.
+- `npm test` green; Python client test green.
+- `git diff` self-reviewed; completionist subagent run and findings fixed.
+
+## Constraints
+
+- Plugins live under `integrations/` — never the repo root.
+- No bundled sample/placeholder models or fake progress in either plugin.
+- Blender polling must use the modal/timer pattern — never block Blender's UI.
+- Respect ComfyUI caching semantics.
+- If you add external auth, use the existing key system; never ship an open
+ generation endpoint.
diff --git a/prompts/tripo-gap/04-monetized-3d-api-mcp.md b/prompts/tripo-gap/04-monetized-3d-api-mcp.md
new file mode 100644
index 000000000..7a34a7053
--- /dev/null
+++ b/prompts/tripo-gap/04-monetized-3d-api-mcp.md
@@ -0,0 +1,142 @@
+# Task: Monetized public 3D-generation API + MCP tools (x402-gated)
+
+## Why this exists
+
+Tripo's commercial moat is a documented, credit-metered public API plus official
+MCP generation tools (`text_to_3d`, `image_to_3d`). We have the generation
+pipeline (`api/forge.js`) but it isn't packaged as a public, paid, documented
+product, and our MCP server is pump-focused rather than exposing 3D generation.
+
+Our structural advantage is **x402 + agent-payments**: an API that AI agents can
+discover and pay for **autonomously**, in USDC, without a human signing up for a
+credit plan. Tripo cannot copy this without rebuilding their billing around
+agent payments. This task turns forge into that product: an x402-gated public
+generation API and matching MCP tools.
+
+## Rails (CLAUDE.md — non-negotiable; read the full file first)
+
+- **No mocks, no fake data, no placeholders.** Real forge pipeline, real x402
+ payment verification, real USDC settlement via the existing payment stack. No
+ fake "payment accepted" path.
+- **No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.**
+ Wire 100%: x402 challenge → payment → generation → result.
+- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference, hardcode, or surface any other coin or token. Payments settle
+ in USDC via the existing x402 plumbing where USDC is the protocol unit — that
+ is generic payment rails, not a coin reference. Never display another token.
+- **Done = a third-party caller (and an MCP client) can pay and generate
+ end-to-end**, with docs, `npm test` green, `git diff` self-reviewed. Run the
+ **completionist** subagent before stopping.
+- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
+
+## Explore first (spawn before writing code)
+
+### Subagent A (Explore) — the x402 / payment surface
+> In `/workspaces/three.ws`, quote how an existing x402-gated endpoint works
+> end-to-end. Read `api/x402/pump-launch.js` and `api/x402/vanity.js` (and any
+> `api/x402/_lib`): the 402 challenge/response shape, how a payment proof is
+> verified, what settles the USDC, and how price is declared. Also quote the
+> `agent-payments-sdk/` public API and how `api/_lib` exposes payment helpers.
+> I am adding a new x402-gated generation endpoint that must reuse this exactly.
+
+### Subagent B (Explore) — forge internals + MCP server
+> In `/workspaces/three.ws`, quote:
+> 1. `api/forge.js` — the full submit/poll contract and `?catalog`, plus
+> `api/_lib/forge-tiers.js` cost/ETA fields.
+> 2. The MCP server: where tools are defined (`api/_mcp/tools/` and the
+> `@3d-agent/mcp-server` package — find its source), how a tool is registered,
+> its input schema, and how it authenticates/meters. Quote one existing tool
+> (e.g. `api/_mcp/tools/animations.js`) verbatim as the template.
+> 3. How usage/billing is currently metered (`usage_events`, plan gating — see
+> `api/avatar/video-generate`).
+
+Wait for both before starting.
+
+## What to build
+
+### Step 1 — the x402-gated generation endpoint
+
+Create `api/x402/forge.js` (or `api/x402/generate.js`) reusing the exact x402
+pattern from Subagent A:
+
+- Unpaid request → `402` with a price challenge derived from
+ `api/_lib/forge-tiers.js` (draft/standard/high each priced; image vs text vs
+ geometry path priced per the catalog).
+- Valid payment proof → submit to the forge pipeline, return `202 { job_id }`.
+- `GET` poll returns the forge status shape (`status`, `glb_url`,
+ `preview_image_url`, `error`, `backend`).
+- Price must be declared in the response and in `?catalog` so callers (human or
+ agent) know the cost before paying.
+- Real settlement via the existing payment stack — no bypass, no "free if header
+ X" backdoor.
+
+### Step 2 — MCP generation tools
+
+Add to the MCP server (matching the `api/_mcp/tools/` registration pattern and
+the `@3d-agent/mcp-server` package):
+
+- `text_to_3d(prompt, tier?, backend?, aspect_ratio?)` → returns a job handle /
+ result URL.
+- `image_to_3d(image_url|image_urls, tier?, backend?)` → same.
+- Each tool declares its price and pays via the agent-payments path so an agent
+ using the MCP server settles autonomously. Reuse the metering/plan logic for
+ any platform-account callers.
+- Keep input schemas tight and validated; real errors on failure.
+
+### Step 3 — OpenAPI + docs
+
+- Publish an OpenAPI schema for the public generation API (submit, poll,
+ catalog, pricing). Put it where the repo keeps API docs (check existing docs
+ layout; otherwise `docs/api/forge-openapi.json` + a short `docs/api/forge.md`).
+- The docs must include: auth/payment flow, pricing table (sourced from
+ `forge-tiers.js`), request/response examples, and a worked x402 example using
+ the agent-payments path. No other-coin references; USDC only where the protocol
+ unit appears.
+
+### Step 4 — rate / abuse guards
+
+- Reuse the existing rate-limit + SSRF patterns already used by the public
+ renderers (`api/render/glb.js` has a real SSRF guard + per-IP limit — match
+ it). Image URLs supplied by callers must pass the SSRF guard before the worker
+ fetches them.
+- Set a sane `maxDuration` in `vercel.json` for the new endpoint consistent with
+ other forge routes (generation is polled, not held — the function returns a
+ job id quickly).
+
+### Step 5 — tests
+
+- Endpoint test: unpaid request → 402 with correct price; valid stubbed payment
+ proof → job submitted; poll returns the forge shape. Stub the payment verifier
+ and the forge submit at module boundaries.
+- MCP tool test: `text_to_3d` / `image_to_3d` validate input, declare price,
+ and route to the generation path (forge submit stubbed).
+- Pricing test: catalog prices match `forge-tiers.js` (single source of truth —
+ do not hardcode prices in two places).
+- `npm test` green.
+
+### Step 6 — docs / progress
+
+- PROGRESS.md item.
+- If this supersedes the API-key step in `03-blender-comfyui-plugins.md`, note
+ that the plugins should target this public surface.
+
+## Definition of done
+
+- A third-party `curl` (or agent) hits the endpoint, receives a 402 with a real
+ price, pays via x402/USDC, and gets a generated GLB — fully real, no bypass.
+- `text_to_3d` and `image_to_3d` work as MCP tools with autonomous payment.
+- OpenAPI schema + docs published; prices sourced solely from `forge-tiers.js`.
+- SSRF guard + rate limit on caller-supplied inputs.
+- `npm test` green; `git diff` self-reviewed; completionist run and findings fixed.
+
+## Constraints
+
+- Reuse the existing x402 + agent-payments stack — do not invent a parallel
+ payment flow.
+- Single source of truth for pricing (`forge-tiers.js`). No duplicated price
+ constants.
+- USDC is the only token surfaced, and only as the x402 protocol unit. Never
+ reference any coin other than `$three`.
+- No unpaid/backdoor generation route. No fake payment-accepted path, including
+ in tests' happy path (stub at the verifier boundary, not by faking success
+ inside the endpoint).
diff --git a/public/agents/boot.js b/public/agents/boot.js
index ed5d800cb..1cb124d74 100644
--- a/public/agents/boot.js
+++ b/public/agents/boot.js
@@ -10,7 +10,9 @@ import { AgentsDirectory } from '../../src/agents-directory.js';
const idParam = new URLSearchParams(window.location.search).get('id');
if (idParam && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(idParam)) {
window.location.replace(`/agents/${idParam}`);
- throw new Error('redirecting to agent detail'); // halt directory boot
+ // Halt the rest of the directory boot while the browser navigates away —
+ // avoids a wasted list fetch and a flash of the empty directory.
+ await new Promise(() => {});
}
const directory = new AgentsDirectory('#agents');
diff --git a/src/three-token-page.js b/src/three-token-page.js
new file mode 100644
index 000000000..62b3a9a3c
--- /dev/null
+++ b/src/three-token-page.js
@@ -0,0 +1,265 @@
+// Public $THREE coin page (/three-token).
+//
+// The canonical, trustworthy page for the protocol token: a live price header,
+// the real bonding-curve chart, a streaming trade tape, and a one-click buy.
+// Reuses the shared $THREE store (single source of truth) for the header, the
+// bonding-curve widget, the SSE trade stream, and the Jupiter swap modal — no
+// bespoke data plumbing, no mock data.
+
+import { createThreeTokenData, THREE_MINT } from './pump/three-token-data.js';
+import { mountBondingCurve } from './widgets/bonding-curve.js';
+import { openSwapModal } from './swap-jupiter.js';
+
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+const PUMP_URL = `https://pump.fun/coin/${THREE_MINT}`;
+const MAX_TAPE_ROWS = 40;
+const REDUCED_MOTION = matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+// ── formatters ──────────────────────────────────────────────────────────────
+const fmtUsd = (n, max = 2) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '—';
+ return v.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: v !== 0 && Math.abs(v) < 1 ? 6 : max });
+};
+const fmtCompactUsd = (n) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '—';
+ if (Math.abs(v) >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;
+ if (Math.abs(v) >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;
+ if (Math.abs(v) >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;
+ return fmtUsd(v);
+};
+const fmtNum = (n) => (Number.isFinite(Number(n)) ? Number(n).toLocaleString('en-US', { maximumFractionDigits: 2 }) : '—');
+const fmtPct = (n) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '';
+ const s = v >= 0 ? '+' : '';
+ return `${s}${v.toFixed(2)}%`;
+};
+const shortAddr = (a) => { const s = String(a || ''); return s.length > 9 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s; };
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+const relTime = (sec) => {
+ const d = Math.max(0, Math.floor(Date.now() / 1000 - Number(sec || 0)));
+ if (d < 60) return `${d}s`;
+ if (d < 3600) return `${Math.floor(d / 60)}m`;
+ return `${Math.floor(d / 3600)}h`;
+};
+
+// ── styles ──────────────────────────────────────────────────────────────────
+function injectStyles() {
+ const css = `
+ :root { color-scheme: dark; }
+ * { box-sizing: border-box; }
+ body { margin:0; background:#0a0a0d; color:#f5f5f7; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif; -webkit-font-smoothing:antialiased; }
+ a { color:inherit; }
+ .tk-wrap { max-width:1080px; margin:0 auto; padding:24px 18px 64px; }
+ .tk-head { display:flex; align-items:center; gap:14px; margin-bottom:4px; }
+ .tk-logo { width:46px; height:46px; border-radius:12px; background:linear-gradient(135deg,#fff,#888); display:grid; place-items:center; font-weight:800; color:#000; font-size:18px; flex-shrink:0; }
+ .tk-title { font-size:26px; font-weight:800; margin:0; letter-spacing:-0.02em; }
+ .tk-sub { margin:0; color:#9a9aa3; font-size:13px; }
+ .tk-ca { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:#8a8a93; cursor:pointer; border:1px solid #232329; border-radius:8px; padding:3px 8px; background:none; }
+ .tk-ca:hover { color:#fff; border-color:#3a3a42; }
+ .tk-stats { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:10px; margin:18px 0 22px; }
+ .tk-stat { background:#111116; border:1px solid #1d1d24; border-radius:12px; padding:14px 16px; }
+ .tk-stat-l { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin-bottom:5px; }
+ .tk-stat-v { font-size:22px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }
+ .tk-grid { display:grid; grid-template-columns:1.1fr 0.9fr; gap:18px; }
+ @media (max-width:820px){ .tk-grid { grid-template-columns:1fr; } }
+ .tk-card { background:#111116; border:1px solid #1d1d24; border-radius:14px; padding:18px; }
+ .tk-card h2 { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin:0 0 12px; }
+ .tk-buy { display:flex; gap:10px; margin-top:16px; flex-wrap:wrap; }
+ .tk-btn { appearance:none; border:1px solid #2a2a32; background:#1a1a20; color:#fff; border-radius:10px; padding:11px 18px; font-size:14px; font-weight:600; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; gap:8px; transition:background .15s,border-color .15s,transform .1s; }
+ .tk-btn:hover { background:#23232b; border-color:#3a3a44; }
+ .tk-btn:active { transform:translateY(1px); }
+ .tk-btn.primary { background:linear-gradient(135deg,#fff,#cfcfd6); color:#000; border:none; }
+ .tk-btn.primary:hover { filter:brightness(0.95); }
+ .tk-btn:focus-visible { outline:2px solid #7CC4FF; outline-offset:2px; }
+ .tk-tape { display:flex; flex-direction:column; gap:2px; max-height:430px; overflow-y:auto; }
+ .tk-trade { display:grid; grid-template-columns:54px 1fr auto; gap:8px; align-items:center; padding:8px 10px; border-radius:8px; font-size:13px; }
+ .tk-trade.buy { background:rgba(74,222,128,0.07); }
+ .tk-trade.sell { background:rgba(248,113,113,0.07); }
+ .tk-trade.in { animation:tkIn .35s ease; }
+ @keyframes tkIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }
+ .tk-side { font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:0.04em; }
+ .tk-side.buy { color:#4ade80; } .tk-side.sell { color:#f87171; }
+ .tk-trader { font-family:ui-monospace,Menlo,monospace; color:#b8b8c0; text-decoration:none; }
+ .tk-trader:hover { color:#fff; }
+ .tk-amt { font-family:ui-monospace,Menlo,monospace; text-align:right; }
+ .tk-amt small { color:#7d7d86; }
+ .tk-status { display:inline-flex; align-items:center; gap:6px; font-size:11.5px; color:#7d7d86; }
+ .tk-dot { width:7px; height:7px; border-radius:50%; background:#4ade80; box-shadow:0 0 8px #4ade80; }
+ .tk-dot.off { background:#f87171; box-shadow:none; }
+ .tk-empty { text-align:center; color:#7d7d86; font-size:13px; padding:40px 0; }
+ .tk-skel { background:linear-gradient(90deg,#16161c,#1d1d24,#16161c); background-size:200% 100%; animation:tkSh 1.4s infinite; border-radius:10px; }
+ @keyframes tkSh { from { background-position:200% 0; } to { background-position:-200% 0; } }
+ .tk-foot { display:flex; gap:18px; flex-wrap:wrap; margin-top:26px; font-size:13px; }
+ .tk-foot a { color:#9a9aa3; text-decoration:none; } .tk-foot a:hover { color:#fff; }
+ @media (prefers-reduced-motion: reduce){ .tk-trade.in { animation:none; } .tk-skel { animation:none; } }
+ `;
+ const el = document.createElement('style');
+ el.textContent = css;
+ document.head.appendChild(el);
+}
+
+// ── header (price + protocol stats) from the shared store ───────────────────
+function renderHeaderStats(token) {
+ const stats = [
+ { l: 'Price', v: fmtUsd(token.price_usd, 6), sub: token.price_change_24h != null ? fmtPct(token.price_change_24h) : '' },
+ { l: 'Market Cap', v: fmtCompactUsd(token.market_cap) },
+ { l: '24h Volume', v: fmtCompactUsd(token.volume_24h) },
+ { l: 'Holders', v: token.holders != null ? fmtNum(token.holders) : '—' },
+ ];
+ return stats.map((s) => {
+ const up = s.sub?.startsWith('+');
+ return `<div class="tk-stat">
+ <div class="tk-stat-l">${esc(s.l)}</div>
+ <div class="tk-stat-v">${s.v}</div>
+ ${s.sub ? `<div style="font-size:12px;margin-top:3px;color:${up ? '#4ade80' : '#f87171'}">${s.sub} 24h</div>` : ''}
+ </div>`;
+ }).join('');
+}
+
+// ── live trade tape via SSE (reconnecting) ───────────────────────────────────
+function startTradeTape(tapeEl, statusEl) {
+ let es = null;
+ let stopped = false;
+ let retry = null;
+ let everConnected = false;
+
+ const setStatus = (online) => {
+ statusEl.innerHTML = `<span class="tk-dot ${online ? '' : 'off'}"></span>${online ? 'Live' : 'Reconnecting…'}`;
+ };
+
+ const addTrade = (t) => {
+ if (!t || (t.mint && t.mint !== THREE_MINT)) return;
+ // Drop the empty-state placeholder on first real trade.
+ const empty = tapeEl.querySelector('[data-empty]');
+ if (empty) empty.remove();
+
+ const isBuy = t.is_buy ?? t.txType === 'buy';
+ const usd = t.sol_value_usd != null ? fmtUsd(t.sol_value_usd) : null;
+ const sol = t.sol_amount != null ? `${Number(t.sol_amount).toFixed(3)} SOL` : '';
+ const row = document.createElement('div');
+ row.className = `tk-trade ${isBuy ? 'buy' : 'sell'}${REDUCED_MOTION ? '' : ' in'}`;
+ row.innerHTML = `
+ <span class="tk-side ${isBuy ? 'buy' : 'sell'}">${isBuy ? 'Buy' : 'Sell'}</span>
+ <a class="tk-trader" href="https://solscan.io/account/${esc(t.trader || '')}" target="_blank" rel="noopener">${esc(shortAddr(t.trader))}</a>
+ <span class="tk-amt">${usd || sol}${usd && sol ? ` <small>${sol}</small>` : ''} <small>· ${relTime(t.timestamp)}</small></span>`;
+ tapeEl.prepend(row);
+ while (tapeEl.children.length > MAX_TAPE_ROWS) tapeEl.lastElementChild.remove();
+ };
+
+ const connect = () => {
+ if (stopped) return;
+ es = new EventSource(`/api/pump/trades-stream?mint=${encodeURIComponent(THREE_MINT)}`);
+ es.addEventListener('open', () => { everConnected = true; setStatus(true); });
+ es.addEventListener('trade', (e) => { try { addTrade(JSON.parse(e.data)); } catch {} });
+ es.addEventListener('close', () => { es.close(); scheduleReconnect(); });
+ es.onerror = () => { setStatus(false); es.close(); scheduleReconnect(); };
+ };
+
+ const scheduleReconnect = () => {
+ if (stopped) return;
+ setStatus(false);
+ clearTimeout(retry);
+ // The server caps each stream at 90s, so a reconnect is normal, not an error.
+ retry = setTimeout(connect, everConnected ? 1200 : 4000);
+ };
+
+ setStatus(false);
+ connect();
+ return () => { stopped = true; clearTimeout(retry); es?.close(); };
+}
+
+// ── buy flow: Phantom → in-page swap, else pump.fun ─────────────────────────
+async function buyThree() {
+ const provider = window.solana || window.phantom?.solana;
+ if (!provider?.isPhantom) {
+ window.open(PUMP_URL, '_blank', 'noopener');
+ return;
+ }
+ try {
+ const resp = provider.publicKey ? { publicKey: provider.publicKey } : await provider.connect();
+ const wallet = resp.publicKey.toString();
+ openSwapModal({ wallet, getProvider: () => provider, defaultInputMint: SOL_MINT, defaultOutputMint: THREE_MINT });
+ } catch {
+ window.open(PUMP_URL, '_blank', 'noopener');
+ }
+}
+
+// ── boot ─────────────────────────────────────────────────────────────────────
+function boot() {
+ injectStyles();
+ document.title = '$THREE · Live price, chart & trades · three.ws';
+
+ const wrap = document.createElement('div');
+ wrap.className = 'tk-wrap';
+ wrap.innerHTML = `
+ <div class="tk-head">
+ <div class="tk-logo">$3</div>
+ <div style="flex:1;min-width:0">
+ <h1 class="tk-title">$THREE</h1>
+ <p class="tk-sub">The protocol token powering the three.ws agent economy</p>
+ </div>
+ <button class="tk-ca" data-ca title="Copy contract address">${esc(shortAddr(THREE_MINT))} · copy</button>
+ </div>
+ <div class="tk-stats" data-stats>
+ ${Array.from({ length: 4 }, () => `<div class="tk-stat"><div class="tk-skel" style="height:48px"></div></div>`).join('')}
+ </div>
+ <div class="tk-grid">
+ <div class="tk-card">
+ <h2>Bonding curve</h2>
+ <div data-curve></div>
+ <div class="tk-buy">
+ <button class="tk-btn primary" data-buy>Buy $THREE</button>
+ <a class="tk-btn" href="${PUMP_URL}" target="_blank" rel="noopener">View on pump.fun ↗</a>
+ </div>
+ </div>
+ <div class="tk-card">
+ <h2 style="display:flex;align-items:center;justify-content:space-between">Live trades <span class="tk-status" data-tape-status></span></h2>
+ <div class="tk-tape" data-tape>
+ <div class="tk-empty" data-empty>Waiting for the next trade…</div>
+ </div>
+ </div>
+ </div>
+ <div class="tk-foot">
+ <a href="/dashboard/holders">🏆 Holder leaderboard</a>
+ <a href="/three-live">⚡ Protocol Pulse (live 3D)</a>
+ <a href="/dashboard/three-token">📊 $THREE dashboard</a>
+ <a href="https://solscan.io/token/${THREE_MINT}" target="_blank" rel="noopener">🔎 Solscan ↗</a>
+ </div>
+ `;
+ document.body.appendChild(wrap);
+
+ // Copy CA
+ wrap.querySelector('[data-ca]').addEventListener('click', async (e) => {
+ try {
+ await navigator.clipboard.writeText(THREE_MINT);
+ const b = e.currentTarget;
+ const prev = b.textContent;
+ b.textContent = 'Copied ✓';
+ setTimeout(() => { b.textContent = prev; }, 1400);
+ } catch {}
+ });
+
+ // Buy
+ wrap.querySelector('[data-buy]').addEventListener('click', () => { buyThree().catch(() => window.open(PUMP_URL, '_blank', 'noopener')); });
+
+ // Bonding curve — real on-chain reads for the $THREE mint.
+ mountBondingCurve(wrap.querySelector('[data-curve]'), { mint: THREE_MINT, network: 'mainnet', showUsd: true, refreshMs: 15_000 });
+
+ // Header stats from the shared store (price/mcap/volume/holders).
+ const statsEl = wrap.querySelector('[data-stats]');
+ const store = createThreeTokenData({ pollMs: 30_000, anchorEl: wrap });
+ store.subscribe((state) => {
+ const p = state.protocol;
+ if (p.status === 'ok' && p.token) statsEl.innerHTML = renderHeaderStats(p.token);
+ else if (p.status === 'error') statsEl.innerHTML = `<div class="tk-empty" style="grid-column:1/-1">Couldn’t load $THREE market data. <a href="${PUMP_URL}" target="_blank" rel="noopener" style="color:#7CC4FF">View on pump.fun ↗</a></div>`;
+ });
+
+ // Live trade tape.
+ startTradeTape(wrap.querySelector('[data-tape]'), wrap.querySelector('[data-tape-status]'));
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
+else boot();
diff --git a/tasks/week-2026-06-08/C4-token-page-upgrade.md b/tasks/week-2026-06-08/C4-token-page-upgrade.md
deleted file mode 100644
index 7cf6e2d73..000000000
--- a/tasks/week-2026-06-08/C4-token-page-upgrade.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# C4 — $THREE token page upgrade: real curve + live trade tape + swap (wow-sprint Task 16)
-
-**Track:** C — build next · **Priority:** P2 · **Effort:** 1–2 days · **Depends on:** **C1** (price header)
-
-## Context
-
-`tasks/wow-sprint/16-token-page-upgrade.md` wants a canonical $THREE coin page that is trustworthy:
-a real bonding-curve/price header, a **live trade tape**, and a working swap. The pieces exist but
-are scattered; the canonical page does **not**. Read the task doc fully first.
-
-The `/api/pump/trades-stream` P0 (broken SSE contract) was **already fixed** — the live tape is now
-buildable.
-
-### Existing pieces to assemble (do NOT rebuild)
-
-- Price/curve: `src/pump/bonding-curve-chart.js`, `src/components/bonding-curve.js`,
- `api/pump/curve.js` (note: also being hardened in **A1** — coordinate; for $THREE, which is a real
- pump mint, the curve endpoint works normally).
-- Swap quote/exec: `src/pump/pump-swap-quote.js`, `src/swap-jupiter.js` (after **B1** trims its
- tiles).
-- Live trades: `api/pump/trades-stream.js` (SSE, fixed) and/or `api/pump/coin-trades.js` (REST),
- with the polling pattern in `src/home-live-token.js` as a reference.
-- Price header data: the **C1** store (`protocol.token` price/market-cap/volume). Use it — don't
- add another price fetch.
-- $THREE mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.
-
-## What to build
-
-1. **New canonical page** `pages/three-token.html` (route in `vite.config.js`) + `src/pages/three-token-coin.js`,
- assembling:
- - A **price header** fed by the C1 store (price, 24h change, market cap, volume, holders).
- - The **bonding-curve / price chart** for $THREE (reuse `bonding-curve-chart.js`).
- - A **live trade tape**: subscribe to `api/pump/trades-stream.js` (SSE) with a reconnect loop and
- a REST fallback to `coin-trades.js`; render buys/sells with amount + USD + relative time;
- respect `prefers-reduced-motion` for any tape animation.
- - A **working swap** widget for $THREE (reuse `pump-swap-quote.js` / `swap-jupiter.js`); SOL/USDC
- are the allowed quote/settlement assets.
-2. **Cross-link** the page from the holder dashboard (C2), the leaderboard (C3 "acquire $THREE"
- CTA), and nav — no dead ends.
-3. **All states + motion + a11y + responsive** per CLAUDE.md. Empty trade tape = a designed "no
- recent trades" state. Graduated-token edge case handled (if/when the curve completes).
-
-## Acceptance criteria
-
-- [ ] `pages/three-token.html` exists, is routed, and is reachable from nav + holder surfaces.
-- [ ] Price header reads from the C1 store (no separate price fetch).
-- [ ] Live trade tape streams real trades via SSE with a working reconnect + REST fallback.
-- [ ] Swap widget executes a real $THREE swap (quote → confirm) with SOL/USDC as quote/settlement.
-- [ ] All states designed (loading/empty/error/graduated); responsive; accessible; reduced-motion
- respected.
-- [ ] No console errors; Network tab shows real curve/trades/quote calls.
-
-## Verification
-
-1. `npm run dev`; open `/three-token` (or the chosen route).
-2. Confirm the price header matches `/api/three-token/stats`, the tape shows live trades and
- reconnects after a forced disconnect, and a swap quote returns a real route.
-3. Test at 320 / 768 / 1440px; toggle reduced-motion; throttle to confirm the error/empty states.
-4. `npx vitest run` for any new tests.
-
-## Rules
-
-Obey [CLAUDE.md](../../CLAUDE.md). Only $THREE on the page. No mock trades, no fake price. Real SSE,
-real swap. Coordinate with **A1** if you touch `api/pump/curve.js`.
-
-## Completion protocol
-
-1. Re-read your diff (`git diff`) and confirm every line is justified.
-2. Delete this file: `tasks/week-2026-06-08/C4-token-page-upgrade.md`.
-3. Commit your code **and** this file's deletion together, e.g.:
- `git add -A && git commit -m "feat(token): canonical $THREE coin page — curve + live tape + swap; close C4"`
-4. Do **not** push — the human controls pushes.
diff --git a/tests/api/http-rate-limited.test.js b/tests/api/http-rate-limited.test.js
new file mode 100644
index 000000000..b9d74194a
--- /dev/null
+++ b/tests/api/http-rate-limited.test.js
@@ -0,0 +1,110 @@
+// Unit tests for the rateLimited() / setRateLimitHeaders() helpers in
+// api/_lib/http.js. These back the standardized 429 responses now emitted by
+// 200+ endpoints, so the header + body contract is asserted directly here
+// rather than per-endpoint.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { rateLimited, setRateLimitHeaders } from '../../api/_lib/http.js';
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ ended: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = String(v);
+ },
+ end(payload) {
+ this.ended = true;
+ this.body = payload ? JSON.parse(payload) : null;
+ },
+ };
+}
+
+describe('setRateLimitHeaders', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-08T00:00:00Z'));
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it('advertises limit, remaining, and seconds-until-reset', () => {
+ const res = mockRes();
+ const sec = setRateLimitHeaders(res, {
+ limit: 60,
+ remaining: 12,
+ reset: Date.now() + 30_000,
+ });
+ expect(sec).toBe(30);
+ expect(res.headers['ratelimit-limit']).toBe('60');
+ expect(res.headers['ratelimit-remaining']).toBe('12');
+ expect(res.headers['ratelimit-reset']).toBe('30');
+ });
+
+ it('never reports negative remaining or reset', () => {
+ const res = mockRes();
+ const sec = setRateLimitHeaders(res, {
+ limit: 10,
+ remaining: -3,
+ reset: Date.now() - 5_000,
+ });
+ expect(sec).toBe(0);
+ expect(res.headers['ratelimit-remaining']).toBe('0');
+ expect(res.headers['ratelimit-reset']).toBe('0');
+ });
+
+ it('rounds partial seconds up so clients never retry early', () => {
+ const res = mockRes();
+ setRateLimitHeaders(res, { reset: Date.now() + 1_200 });
+ expect(res.headers['ratelimit-reset']).toBe('2');
+ });
+
+ it('tolerates a missing result', () => {
+ const res = mockRes();
+ expect(setRateLimitHeaders(res, undefined)).toBe(0);
+ expect(res.headers['ratelimit-reset']).toBeUndefined();
+ });
+});
+
+describe('rateLimited', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-08T00:00:00Z'));
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it('emits a 429 with Retry-After and the standard error envelope', () => {
+ const res = mockRes();
+ rateLimited(res, { limit: 60, remaining: 0, reset: Date.now() + 45_000 });
+ expect(res.statusCode).toBe(429);
+ expect(res.headers['retry-after']).toBe('45');
+ expect(res.headers['ratelimit-limit']).toBe('60');
+ expect(res.headers['ratelimit-remaining']).toBe('0');
+ expect(res.body).toMatchObject({
+ error: 'rate_limited',
+ error_description: 'too many requests',
+ retry_after: 45,
+ });
+ });
+
+ it('clamps Retry-After to at least 1 second', () => {
+ const res = mockRes();
+ rateLimited(res, { reset: Date.now() }); // already expired
+ expect(res.headers['retry-after']).toBe('1');
+ expect(res.body.retry_after).toBe(1);
+ });
+
+ it('carries a custom message and merges extra body fields', () => {
+ const res = mockRes();
+ rateLimited(
+ res,
+ { limit: 5, remaining: 0, reset: Date.now() + 10_000 },
+ 'slow down',
+ { scope: 'chat' },
+ );
+ expect(res.body.error_description).toBe('slow down');
+ expect(res.body.scope).toBe('chat');
+ expect(res.body.retry_after).toBe(10);
+ });
+});
diff --git a/tests/api/x402-discovery-parity.test.js b/tests/api/x402-discovery-parity.test.js
index 2dc663260..1ac285c8d 100644
--- a/tests/api/x402-discovery-parity.test.js
+++ b/tests/api/x402-discovery-parity.test.js
@@ -24,8 +24,8 @@ const EXCLUSIONS = new Map([
[
'/api/x402/permit2-paid-demo',
'CDP-only: its sole accept is a Permit2 sibling that permit2VariantOf() ' +
- 'returns null for without CDP creds, so the live 402 (and thus the catalog) ' +
- 'catalog) omits the route entirely in non-CDP environments.',
+ 'returns null without CDP creds, so the live 402 (and thus the catalog) ' +
+ 'omits the route entirely in non-CDP environments.',
],
]);
diff --git a/vercel.json b/vercel.json
index e38a1c2c9..e6a9952c5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -447,6 +447,10 @@
"src": "/three-live/?",
"dest": "/three-live.html"
},
+ {
+ "src": "/three-token/?",
+ "dest": "/three-token.html"
+ },
{
"src": "/go/?",
"dest": "/go.html"
diff --git a/vite.config.js b/vite.config.js
index 0d05574ef..fa211f540 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -292,6 +292,7 @@ const appConfig = {
autopilot: resolve(__dirname, 'pages/autopilot.html'),
'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),
'three-live': resolve(__dirname, 'pages/three-live.html'),
+ 'three-token': resolve(__dirname, 'pages/three-token.html'),
'avatar-artifact': resolve(__dirname, 'pages/avatar-artifact.html'),
'launch-week': resolve(__dirname, 'pages/three-ws-launch-week.html'),
community: resolve(__dirname, 'pages/community.html'),
@@ -595,6 +596,8 @@ const appConfig = {
'/pump-visualizer/': resolve(root, 'pages/pump-visualizer.html'),
'/three-live': resolve(root, 'pages/three-live.html'),
'/three-live/': resolve(root, 'pages/three-live.html'),
+ '/three-token': resolve(root, 'pages/three-token.html'),
+ '/three-token/': resolve(root, 'pages/three-token.html'),
'/avatar-artifact': resolve(root, 'pages/avatar-artifact.html'),
'/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),
'/walk': resolve(root, 'pages/walk.html'),