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: pump-swap buyback, pose studio, WASM vanity grinder, x402 bazaar schema

nirholasee271afdc974
diff --git a/agent-payments-sdk/src/solana/PumpTradeClient.ts b/agent-payments-sdk/src/solana/PumpTradeClient.ts
index 6ba41e8a0..a3f091a57 100644
--- a/agent-payments-sdk/src/solana/PumpTradeClient.ts
+++ b/agent-payments-sdk/src/solana/PumpTradeClient.ts
@@ -165,11 +165,11 @@ export class PumpTradeClient {
const mintSupply = bondingCurve.tokenTotalSupply;
const expectedBaseTokens = getBuyTokenAmountFromSolAmount({
- global, feeConfig, mintSupply, bondingCurve, amount: quoteAmount,
+ global, feeConfig, mintSupply, bondingCurve, amount: quoteAmount, quoteMint,
});
const preciseQuoteAmount = getBuySolAmountFromTokenAmount({
- global, feeConfig, mintSupply, bondingCurve, amount: expectedBaseTokens,
+ global, feeConfig, mintSupply, bondingCurve, amount: expectedBaseTokens, quoteMint,
});
const maxQuoteCost = new BN(
@@ -276,7 +276,7 @@ export class PumpTradeClient {
const mintSupply = bondingCurve.tokenTotalSupply;
const expectedBaseTokens = getBuyTokenAmountFromSolAmount({
- global, feeConfig, mintSupply, bondingCurve, amount: quoteAmount,
+ global, feeConfig, mintSupply, bondingCurve, amount: quoteAmount, quoteMint,
});
if (expectedBaseTokens.lte(new BN(0))) {
@@ -286,7 +286,7 @@ export class PumpTradeClient {
}
const preciseQuoteAmount = getBuySolAmountFromTokenAmount({
- global, feeConfig, mintSupply, bondingCurve, amount: expectedBaseTokens,
+ global, feeConfig, mintSupply, bondingCurve, amount: expectedBaseTokens, quoteMint,
});
const mayhemMode = bondingCurve.isMayhemMode ?? false;
diff --git a/api/_lib/bake.js b/api/_lib/bake.js
index 1ba98c5b2..aa33fe93e 100644
--- a/api/_lib/bake.js
+++ b/api/_lib/bake.js
@@ -208,7 +208,9 @@ export async function bakeAppearance(baseGlbBytes, appearance) {
quantizeWeight: 8,
quantizeGeneric: 12,
}),
- meshopt({ encoder: MeshoptEncoder }),
+ // level: 'medium' — keeps bake time bounded. 'high' adds a small
+ // extra reduction at substantial encoder-time cost.
+ meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
textureCompress({
encoder: sharp,
targetFormat: 'webp',
diff --git a/api/_lib/email.js b/api/_lib/email.js
index 9fbcb7c1a..2d7ad722f 100644
--- a/api/_lib/email.js
+++ b/api/_lib/email.js
@@ -2,7 +2,7 @@
// them on the critical path. Import sendEmail and call without await.
//
// Required env: RESEND_API_KEY, EMAIL_FROM (e.g. "three.ws <[email protected]>")
-// Optional env: EMAIL_REPLY_TO
+// Optional env: EMAIL_REPLY_TO, APP_ORIGIN
import { Resend } from 'resend';
import { captureException } from './sentry.js';
@@ -17,72 +17,104 @@ const FROM = process.env.EMAIL_FROM || 'three.ws <[email protected]>';
const REPLY = process.env.EMAIL_REPLY_TO || null;
const APP_URL = process.env.APP_ORIGIN || 'https://three.ws';
+// ─── Payload builder ──────────────────────────────────────────────────────────
+// Pure function — builds the exact object passed to Resend's emails.send.
+// Exported so tests can assert the payload without mocking the Resend SDK.
+
+export function buildPayload({ to, subject, html, text }) {
+ return {
+ from: FROM,
+ ...(REPLY ? { replyTo: REPLY } : {}),
+ to,
+ subject,
+ html,
+ text,
+ };
+}
+
// ─── Low-level send ───────────────────────────────────────────────────────────
+// Returns { skipped: true, reason: 'missing_api_key' } when RESEND_API_KEY is
+// unset (dev / preview deploys). Returns the Resend SDK response on success.
+// Throws on transport failure — fire-and-forget callers must .catch().
export async function sendEmail({ to, subject, html, text }) {
- if (!process.env.RESEND_API_KEY) return; // no-op if not configured
+ if (!process.env.RESEND_API_KEY) {
+ return { skipped: true, reason: 'missing_api_key' };
+ }
+ const payload = buildPayload({ to, subject, html, text });
try {
- await client().emails.send({
- from: FROM,
- ...(REPLY ? { replyTo: REPLY } : {}),
- to,
- subject,
- html,
- text,
- });
+ return await client().emails.send(payload);
} catch (err) {
console.error('[email] send failed', err?.message);
captureException(err, { to, subject });
- // Re-throw so callers can return 5xx instead of silently succeeding.
throw err;
}
}
-// ─── Templates ───────────────────────────────────────────────────────────────
+// ─── Renderers ────────────────────────────────────────────────────────────────
+// Each returns { subject, html, text }. Exposed so tests can assert the
+// rendered content directly without going through the send path.
-export function sendWelcomeEmail({ to, displayName }) {
+export function renderWelcome({ displayName }) {
const name = displayName || 'there';
- return sendEmail({
- to,
+ return {
subject: 'Welcome to three.ws',
html: welcomeHtml(name),
text: welcomeText(name),
- });
+ };
}
-export function sendVerificationEmail({ to, code, expiresInMinutes = 30 }) {
- return sendEmail({
- to,
+export function renderVerify({ code, expiresInMinutes = 30 }) {
+ return {
subject: `${code} — verify your email`,
html: verifyHtml(code, expiresInMinutes),
text: verifyText(code, expiresInMinutes),
- });
+ };
}
-export function sendPasswordResetEmail({ to, resetUrl, expiresInMinutes = 60 }) {
- return sendEmail({
- to,
+export function renderPasswordReset({ resetUrl, expiresInMinutes = 60 }) {
+ return {
subject: 'Reset your three.ws password',
html: resetHtml(resetUrl, expiresInMinutes),
text: resetText(resetUrl, expiresInMinutes),
- });
+ };
}
-export function sendSubscriptionConfirmEmail({ to, plan, chain, txId }) {
- return sendEmail({
- to,
+export function renderSubscriptionConfirm({ plan, chain, txId }) {
+ return {
subject: `three.ws ${capitalize(plan)} plan activated`,
html: subscriptionHtml(plan, chain, txId),
text: subscriptionText(plan, chain, txId),
- });
+ };
+}
+
+// ─── Template wrappers ────────────────────────────────────────────────────────
+
+export function sendWelcomeEmail({ to, displayName }) {
+ return sendEmail({ to, ...renderWelcome({ displayName }) });
+}
+
+export function sendVerificationEmail({ to, code, expiresInMinutes = 30 }) {
+ return sendEmail({ to, ...renderVerify({ code, expiresInMinutes }) });
+}
+
+export function sendPasswordResetEmail({ to, resetUrl, expiresInMinutes = 60 }) {
+ return sendEmail({ to, ...renderPasswordReset({ resetUrl, expiresInMinutes }) });
+}
+
+export function sendSubscriptionConfirmEmail({ to, plan, chain, txId }) {
+ return sendEmail({ to, ...renderSubscriptionConfirm({ plan, chain, txId }) });
}
// ─── HTML helpers ─────────────────────────────────────────────────────────────
-function layout(body) {
+function layout(title, body) {
return `<!DOCTYPE html>
<html lang="en">
-<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>${esc(title)}</title>
<style>
body{font-family:-apple-system,system-ui,'Segoe UI',sans-serif;background:#080814;color:#eee;margin:0;padding:32px 16px}
.card{max-width:520px;margin:0 auto;background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:36px 32px}
@@ -93,14 +125,16 @@ function layout(body) {
.code{font-family:monospace;font-size:32px;letter-spacing:.15em;color:#fff;background:#0f0f17;border:1px solid #2a2a36;border-radius:8px;padding:12px 20px;display:inline-block;margin:8px 0 20px}
.muted{color:#555;font-size:13px}
hr{border:none;border-top:1px solid #2a2a36;margin:24px 0}
-</style></head>
-<body><div class="card">${body}</div></body></html>`;
+</style>
+</head>
+<body><div class="card">${body}</div></body>
+</html>`;
}
function welcomeHtml(name) {
- return layout(`
+ return layout('Welcome to three.ws', `
<p class="brand">three.ws</p>
- <h1>Welcome, ${esc(name)} 👋</h1>
+ <h1>Welcome, ${esc(name)}</h1>
<p>Your account is ready. Start by uploading your first 3D avatar or connecting an on-chain agent identity.</p>
<a class="btn" href="${APP_URL}/dashboard/">Open Dashboard</a>
<hr>
@@ -113,7 +147,7 @@ function welcomeText(name) {
}
function verifyHtml(code, mins) {
- return layout(`
+ return layout('Verify your email', `
<p class="brand">three.ws</p>
<h1>Verify your email</h1>
<p>Enter this code to verify your email address. It expires in ${mins} minutes.</p>
@@ -127,7 +161,7 @@ function verifyText(code, mins) {
}
function resetHtml(url, mins) {
- return layout(`
+ return layout('Reset your three.ws password', `
<p class="brand">three.ws</p>
<h1>Reset your password</h1>
<p>Click below to set a new password. This link expires in ${mins} minutes.</p>
@@ -141,9 +175,9 @@ function resetText(url, mins) {
}
function subscriptionHtml(plan, chain, txId) {
- return layout(`
+ return layout(`${capitalize(plan)} plan activated`, `
<p class="brand">three.ws</p>
- <h1>${capitalize(plan)} plan activated 🎉</h1>
+ <h1>${capitalize(plan)} plan activated</h1>
<p>Your <strong>${capitalize(plan)}</strong> subscription is now active on ${capitalize(chain)}.</p>
${txId ? `<p class="muted">Transaction: <code>${esc(txId)}</code></p>` : ''}
<a class="btn" href="${APP_URL}/dashboard/">Go to Dashboard</a>
diff --git a/api/_lib/env.js b/api/_lib/env.js
index fd2ac2e23..a6f553487 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -386,6 +386,16 @@ export const env = {
return opt('MEDIUM_AUTHOR_ID');
},
+ // Override URL for the @sparticuz/chromium-min binary pack. The "-min"
+ // build excludes the chromium tarball from the npm package to keep the
+ // function bundle small; this URL is downloaded once per warm container
+ // and cached in /tmp. Default in render-glb.js tracks the version pinned
+ // in package.json — set this only when upgrading chromium-min and the
+ // upstream Sparticuz release tag drifts.
+ get CHROMIUM_PACK_URL() {
+ return opt('CHROMIUM_PACK_URL');
+ },
+
getRpcUrl(chainId) {
return (
opt(`RPC_URL_${chainId}`) ||
diff --git a/api/_lib/migrations/2026-05-20-pump-buyback-fullswap.sql b/api/_lib/migrations/2026-05-20-pump-buyback-fullswap.sql
new file mode 100644
index 000000000..00961d343
--- /dev/null
+++ b/api/_lib/migrations/2026-05-20-pump-buyback-fullswap.sql
@@ -0,0 +1,17 @@
+-- Migration: per-mint buyback full-swap + slippage config.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-20-pump-buyback-fullswap.sql
+-- Idempotent.
+
+begin;
+
+-- ── pump_agent_mints: per-mint buyback config ───────────────────────────────
+-- full_swap: when true, the buyback cron CPIs a buy-on-curve before burn.
+-- when false (default), the cron only burns whatever sits in
+-- the burn-currency-mint vault — no swap.
+-- slippage_bps: floor for `min_tokens_out` in the inner buy. 500 = 5%.
+alter table pump_agent_mints
+ add column if not exists full_swap boolean not null default false,
+ add column if not exists slippage_bps int not null default 500
+ check (slippage_bps between 0 and 10000);
+
+commit;
diff --git a/api/_lib/pump-swap-ix.js b/api/_lib/pump-swap-ix.js
new file mode 100644
index 000000000..8e82b9ef1
--- /dev/null
+++ b/api/_lib/pump-swap-ix.js
@@ -0,0 +1,323 @@
+// api/_lib/pump-swap-ix.js
+//
+// Builds the raw `data` + `accounts` for the pump bonding-curve
+// `buy_exact_quote_in_v2` instruction, intended to be passed to
+// `offline.buybackTrigger(...)` via its `swapInstructionData` /
+// `remainingAccounts` slots so the outer agent_buyback_trigger CPI invokes a
+// real buy before the burn.
+//
+// We do NOT wrap into a TransactionInstruction; the outer ix consumes the data
+// + accounts independently. `user` is the buyback-authority PDA: the outer ix
+// signs for it via invoke_signed.
+//
+// Reference: agent-payments-sdk/src/solana/PumpTradeClient.ts
+// (buildBuyExactQuoteInInstructions — same on-chain ix, but with a human
+// signer + ATA-create prefix we strip for the inner-CPI variant).
+
+import {
+ PublicKey,
+ SystemProgram,
+} from '@solana/web3.js';
+import {
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ NATIVE_MINT,
+ TOKEN_2022_PROGRAM_ID,
+ TOKEN_PROGRAM_ID,
+ getAssociatedTokenAddressSync,
+} from '@solana/spl-token';
+import BN from 'bn.js';
+import {
+ GLOBAL_PDA,
+ GLOBAL_VOLUME_ACCUMULATOR_PDA,
+ PUMP_EVENT_AUTHORITY_PDA,
+ PUMP_FEE_CONFIG_PDA,
+ PUMP_FEE_PROGRAM_ID,
+ PUMP_PROGRAM_ID,
+ PUMP_SDK,
+ bondingCurvePda,
+ creatorVaultPda,
+ feeSharingConfigPda,
+ getBuyTokenAmountFromSolAmount,
+ userVolumeAccumulatorPda,
+} from '@pump-fun/pump-sdk';
+import { getBuybackAuthorityPDA } from '@pump-fun/agent-payments-sdk';
+
+import { getConnection } from './pump.js';
+
+// Anchor discriminator for `buy_exact_quote_in_v2` — see
+// agent-payments-sdk/src/solana/idl/pump.json (instruction definition).
+const BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR = Buffer.from([
+ 194, 171, 28, 70, 104, 77, 91, 47,
+]);
+
+// Static buyback-fee-recipient pool. Mirrors
+// `BUYBACK_FEE_RECIPIENTS` in agent-payments-sdk/src/solana/constants.ts
+// (not re-exported from the SDK index, so duplicated here verbatim).
+const BUYBACK_FEE_RECIPIENTS = [
+ '5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD',
+ '9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7',
+ 'GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL',
+ '3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR',
+ '5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6',
+ 'EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL',
+ '5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD',
+ 'A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW',
+].map((s) => new PublicKey(s));
+
+const KNOWN_TOKEN_PROGRAMS = new Set([
+ TOKEN_PROGRAM_ID.toBase58(),
+ TOKEN_2022_PROGRAM_ID.toBase58(),
+]);
+
+function toPubkey(value) {
+ if (value instanceof PublicKey) return value;
+ return new PublicKey(value);
+}
+
+function toBN(value) {
+ if (BN.isBN(value)) return value;
+ return new BN(value.toString());
+}
+
+function resolveQuoteMintFromCurve(quoteMintOnChain) {
+ if (!quoteMintOnChain || quoteMintOnChain.equals(PublicKey.default)) {
+ return NATIVE_MINT;
+ }
+ return quoteMintOnChain;
+}
+
+function pickRandom(arr) {
+ return arr[Math.floor(Math.random() * arr.length)];
+}
+
+function pickFeeRecipient(global, mayhemMode) {
+ const pool = mayhemMode
+ ? [global.reservedFeeRecipient, ...global.reservedFeeRecipients]
+ : [global.feeRecipient, ...global.feeRecipients];
+ return pickRandom(pool);
+}
+
+function pickBuybackFeeRecipient() {
+ return pickRandom(BUYBACK_FEE_RECIPIENTS);
+}
+
+/**
+ * Build the raw inner-ix data + AccountMeta[] for a pump bonding-curve
+ * `buy_exact_quote_in_v2` to be CPI'd by `agent_buyback_trigger`.
+ *
+ * @param {object} params
+ * @param {string|PublicKey} params.mint Base mint (the agent's token).
+ * @param {string|PublicKey} params.currency Quote currency mint (USDC, etc.).
+ * Must equal the curve's quoteMint.
+ * @param {BN|bigint|string|number} params.amountIn Quote units to spend.
+ * @param {BN|bigint|string|number|null} [params.minAmountOut]
+ * Explicit floor on base tokens received. If null/undefined, computed from
+ * `slippageBps` against current curve state.
+ * @param {number} [params.slippageBps=500] Used only when minAmountOut is
+ * not supplied. Default 5%.
+ * @param {'devnet'|'mainnet'|'mainnet-beta'} [params.cluster='mainnet']
+ * @param {import('@solana/web3.js').Connection} [params.connection] Injected
+ * for tests; falls back to `getConnection({ network: <normalized cluster> })`.
+ * @returns {Promise<{ data: Buffer, accounts: Array<{ pubkey: PublicKey, isSigner: boolean, isWritable: boolean }>, expectedBaseTokens: BN, minTokensOut: BN }>}
+ */
+export async function buildPumpSwapInnerIx({
+ mint,
+ currency,
+ amountIn,
+ minAmountOut,
+ slippageBps,
+ cluster = 'mainnet',
+ connection: injectedConnection,
+}) {
+ const mintPk = toPubkey(mint);
+ const currencyPk = toPubkey(currency);
+ const amountInBn = toBN(amountIn);
+
+ const network = cluster === 'mainnet-beta' ? 'mainnet' : cluster;
+ const connection = injectedConnection ?? getConnection({ network });
+
+ const [burnAuthority] = getBuybackAuthorityPDA(mintPk);
+ const bcAddr = bondingCurvePda(mintPk);
+
+ const [globalInfo, feeConfigInfo, bcInfo, baseMintInfo, quoteMintInfo] =
+ await connection.getMultipleAccountsInfo([
+ GLOBAL_PDA,
+ PUMP_FEE_CONFIG_PDA,
+ bcAddr,
+ mintPk,
+ currencyPk,
+ ]);
+
+ if (!globalInfo) {
+ throw new Error(
+ `pump-swap-ix: Global PDA not found on ${network} — wrong network?`,
+ );
+ }
+ if (!bcInfo) {
+ throw new Error(
+ `pump-swap-ix: bonding curve not found for mint ${mintPk.toBase58()} on ${network}`,
+ );
+ }
+ if (!baseMintInfo) {
+ throw new Error(
+ `pump-swap-ix: base mint account ${mintPk.toBase58()} not found on ${network}`,
+ );
+ }
+
+ const global = PUMP_SDK.decodeGlobal(globalInfo);
+ const feeConfig = feeConfigInfo
+ ? PUMP_SDK.decodeFeeConfig(feeConfigInfo)
+ : null;
+ const bondingCurve = PUMP_SDK.decodeBondingCurve(bcInfo);
+
+ if (bondingCurve.complete) {
+ throw new Error(
+ `pump-swap-ix: bonding curve for ${mintPk.toBase58()} has graduated — use AMM instead`,
+ );
+ }
+
+ const quoteMint = resolveQuoteMintFromCurve(bondingCurve.quoteMint);
+ if (!quoteMint.equals(currencyPk)) {
+ throw new Error(
+ `pump-swap-ix: currency mint mismatch — caller passed ${currencyPk.toBase58()} but curve expects ${quoteMint.toBase58()}`,
+ );
+ }
+
+ const baseOwner = baseMintInfo.owner;
+ if (!KNOWN_TOKEN_PROGRAMS.has(baseOwner.toBase58())) {
+ throw new Error(
+ `pump-swap-ix: base mint owned by unknown program ${baseOwner.toBase58()}`,
+ );
+ }
+ const baseTokenProgram = baseOwner;
+
+ let quoteTokenProgram;
+ if (quoteMint.equals(NATIVE_MINT)) {
+ quoteTokenProgram = TOKEN_PROGRAM_ID;
+ } else {
+ if (!quoteMintInfo) {
+ throw new Error(
+ `pump-swap-ix: quote mint account ${quoteMint.toBase58()} not found`,
+ );
+ }
+ const quoteOwner = quoteMintInfo.owner;
+ if (!KNOWN_TOKEN_PROGRAMS.has(quoteOwner.toBase58())) {
+ throw new Error(
+ `pump-swap-ix: quote mint owned by unknown program ${quoteOwner.toBase58()}`,
+ );
+ }
+ quoteTokenProgram = quoteOwner;
+ }
+
+ const expectedBaseTokens = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig,
+ mintSupply: bondingCurve.tokenTotalSupply,
+ bondingCurve,
+ amount: amountInBn,
+ quoteMint,
+ });
+
+ if (expectedBaseTokens.lte(new BN(0))) {
+ throw new Error(
+ `pump-swap-ix: computed expectedBaseTokens=${expectedBaseTokens.toString()} for amountIn=${amountInBn.toString()} — amount too small or reserves exhausted`,
+ );
+ }
+
+ let minTokensOut;
+ if (minAmountOut !== undefined && minAmountOut !== null) {
+ minTokensOut = toBN(minAmountOut);
+ } else {
+ const bps = Number.isFinite(slippageBps) ? Math.max(0, Math.min(10000, slippageBps)) : 500;
+ minTokensOut = expectedBaseTokens
+ .mul(new BN(10000 - bps))
+ .div(new BN(10000));
+ }
+
+ const mayhemMode = bondingCurve.isMayhemMode ?? false;
+ const feeRecipient = pickFeeRecipient(global, mayhemMode);
+ const buybackFeeRecipient = pickBuybackFeeRecipient();
+ const creatorVault = creatorVaultPda(bondingCurve.creator);
+ const userVolAcc = userVolumeAccumulatorPda(burnAuthority);
+
+ const ata = (mintPub, owner, tkProg) =>
+ getAssociatedTokenAddressSync(mintPub, owner, true, tkProg);
+
+ // Account list — exact program-required order per IDL definition of
+ // `buy_exact_quote_in_v2`. 27 entries. Flags mirror the IDL.
+ const accounts = [
+ { pubkey: GLOBAL_PDA, isSigner: false, isWritable: false },
+ { pubkey: mintPk, isSigner: false, isWritable: false },
+ { pubkey: quoteMint, isSigner: false, isWritable: false },
+ { pubkey: baseTokenProgram, isSigner: false, isWritable: false },
+ { pubkey: quoteTokenProgram, isSigner: false, isWritable: false },
+ { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
+ { pubkey: feeRecipient, isSigner: false, isWritable: true },
+ {
+ pubkey: ata(quoteMint, feeRecipient, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: buybackFeeRecipient, isSigner: false, isWritable: true },
+ {
+ pubkey: ata(quoteMint, buybackFeeRecipient, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: bcAddr, isSigner: false, isWritable: true },
+ {
+ pubkey: ata(mintPk, bcAddr, baseTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ {
+ pubkey: ata(quoteMint, bcAddr, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: burnAuthority, isSigner: true, isWritable: true },
+ {
+ pubkey: ata(mintPk, burnAuthority, baseTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ {
+ pubkey: ata(quoteMint, burnAuthority, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: creatorVault, isSigner: false, isWritable: true },
+ {
+ pubkey: ata(quoteMint, creatorVault, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: feeSharingConfigPda(mintPk), isSigner: false, isWritable: false },
+ { pubkey: GLOBAL_VOLUME_ACCUMULATOR_PDA, isSigner: false, isWritable: false },
+ { pubkey: userVolAcc, isSigner: false, isWritable: true },
+ {
+ pubkey: ata(quoteMint, userVolAcc, quoteTokenProgram),
+ isSigner: false,
+ isWritable: true,
+ },
+ { pubkey: PUMP_FEE_CONFIG_PDA, isSigner: false, isWritable: false },
+ { pubkey: PUMP_FEE_PROGRAM_ID, isSigner: false, isWritable: false },
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
+ { pubkey: PUMP_EVENT_AUTHORITY_PDA, isSigner: false, isWritable: false },
+ { pubkey: PUMP_PROGRAM_ID, isSigner: false, isWritable: false },
+ ];
+
+ const data = Buffer.concat([
+ BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR,
+ amountInBn.toArrayLike(Buffer, 'le', 8),
+ minTokensOut.toArrayLike(Buffer, 'le', 8),
+ ]);
+
+ return { data, accounts, expectedBaseTokens, minTokensOut };
+}
+
+export {
+ BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR,
+ BUYBACK_FEE_RECIPIENTS,
+ PUMP_PROGRAM_ID,
+};
diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.js
new file mode 100644
index 000000000..5ad311b04
--- /dev/null
+++ b/api/_lib/render-glb.js
@@ -0,0 +1,170 @@
+// Server-side GLB → PNG renderer for OG cards.
+// ---------------------------------------------
+// Boots headless chromium via puppeteer-core + @sparticuz/chromium-min,
+// loads a tiny inlined three.js viewer page, points it at a GLB URL,
+// waits for the model to render one frame, then returns the canvas PNG.
+//
+// Used by api/avatar-og.js when an avatar has no client-uploaded
+// thumbnail yet. After the first render the PNG is cached in R2 and the
+// avatar row's thumbnail_key is updated — subsequent crawls hit the
+// redirect path and never re-launch chromium.
+
+import puppeteer from 'puppeteer-core';
+import chromium from '@sparticuz/chromium-min';
+import { env } from './env.js';
+
+// The "-min" build of @sparticuz/chromium ships without the chromium binary
+// to keep the function bundle small. The binary is downloaded on first use
+// from this URL (cached under /tmp on the Vercel runtime so cold-start cost
+// is paid once per container, not per invocation). Match the chromium release
+// to the @sparticuz/chromium-min version in package.json — see the project's
+// release matrix at github.com/Sparticuz/chromium/releases.
+// Keep in lockstep with @sparticuz/chromium-min in package.json. v148.0.0 → v148.0.0.
+const DEFAULT_CHROMIUM_PACK =
+ 'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';
+const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;
+
+// three.js version pinned in package-lock — must match what the in-app viewer
+// renders so the server-side preview is faithful (camera, lighting, material
+// behavior are all version-sensitive).
+const THREE_VERSION = '0.176.0';
+
+// One browser per warm container. puppeteer.launch is the slow step
+// (~1s on warm chromium, ~3s cold); reusing the instance across renders
+// in the same lambda invocation amortizes it.
+let _browserPromise = null;
+async function getBrowser() {
+ if (_browserPromise) return _browserPromise;
+ _browserPromise = (async () => {
+ const executablePath = await chromium.executablePath(CHROMIUM_PACK);
+ return puppeteer.launch({
+ args: chromium.args,
+ defaultViewport: { width: 1200, height: 630, deviceScaleFactor: 1 },
+ executablePath,
+ headless: chromium.headless,
+ });
+ })().catch((err) => {
+ _browserPromise = null;
+ throw err;
+ });
+ return _browserPromise;
+}
+
+// Inline viewer HTML — bundled into the function so the renderer needs no
+// extra static assets. three.js + GLTFLoader load from unpkg pinned to the
+// installed version. window.__renderDone signals readiness to puppeteer.
+function viewerHtml({ glbUrl, width, height, background }) {
+ const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
+ return `<!doctype html>
+<html><head><meta charset="utf-8" />
+<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>
+</head><body>
+<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>
+<script type="importmap">{ "imports": {
+ "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",
+ "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"
+}}</script>
+<script type="module">
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+window.__renderDone = false;
+window.__renderError = null;
+
+const canvas = document.getElementById('c');
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
+renderer.setSize(${width}, ${height}, false);
+renderer.setPixelRatio(1);
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+renderer.toneMapping = THREE.ACESFilmicToneMapping;
+renderer.toneMappingExposure = 1.0;
+
+const scene = new THREE.Scene();
+const bgColor = ${bg};
+if (bgColor !== null) scene.background = new THREE.Color(bgColor);
+
+const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);
+
+// Three-light rig: key from front-right, fill from front-left, rim from behind.
+scene.add(new THREE.AmbientLight(0xffffff, 0.55));
+const key = new THREE.DirectionalLight(0xffffff, 1.4); key.position.set(2, 3, 4); scene.add(key);
+const fill = new THREE.DirectionalLight(0xbfd6ff, 0.6); fill.position.set(-3, 1, 2); scene.add(fill);
+const rim = new THREE.DirectionalLight(0xc7a8ff, 0.5); rim.position.set(0, 2, -4); scene.add(rim);
+
+new GLTFLoader().load(${JSON.stringify(glbUrl)}, (gltf) => {
+ try {
+ const root = gltf.scene;
+ scene.add(root);
+ // Frame the model: compute bounds, center it, position camera so it
+ // fills the frame with a small margin.
+ const box = new THREE.Box3().setFromObject(root);
+ const size = new THREE.Vector3(); box.getSize(size);
+ const center = new THREE.Vector3(); box.getCenter(center);
+ root.position.sub(center);
+ root.position.y += size.y * 0.05; // tiny lift so feet aren't dead-center
+ const maxDim = Math.max(size.x, size.y, size.z);
+ const fov = THREE.MathUtils.degToRad(camera.fov);
+ const dist = (maxDim / 2) / Math.tan(fov / 2) * 1.45;
+ camera.position.set(0, size.y * 0.05, dist);
+ camera.lookAt(0, 0, 0);
+ // Two paints guard against partial first-frame artifacts (textures
+ // still uploading, skinned meshes pre-bind). Cheap on a single GLB.
+ renderer.render(scene, camera);
+ requestAnimationFrame(() => {
+ renderer.render(scene, camera);
+ window.__renderDone = true;
+ });
+ } catch (err) {
+ window.__renderError = err.message || String(err);
+ }
+}, undefined, (err) => {
+ window.__renderError = 'glb load failed: ' + (err?.message || err);
+});
+</script></body></html>`;
+}
+
+/**
+ * Render a GLB to a PNG buffer via headless chromium.
+ *
+ * @param {object} opts
+ * @param {string} opts.glbUrl - publicly reachable URL of the .glb
+ * @param {number} [opts.width=1200]
+ * @param {number} [opts.height=630]
+ * @param {string} [opts.background='#0a0a0a'] - 'transparent' or hex color
+ * @returns {Promise<Buffer>} PNG buffer
+ */
+export async function renderGlbToPng({ glbUrl, width = 1200, height = 630, background = '#0a0a0a' } = {}) {
+ if (!glbUrl || typeof glbUrl !== 'string') {
+ throw Object.assign(new Error('glbUrl required'), { status: 400, code: 'invalid_args' });
+ }
+ const browser = await getBrowser();
+ const page = await browser.newPage();
+ try {
+ await page.setViewport({ width, height, deviceScaleFactor: 1 });
+ const html = viewerHtml({ glbUrl, width, height, background });
+ // data: URL avoids needing a network fetch for the bootstrap page itself.
+ // importmap dependencies (three, GLTFLoader) still come from unpkg.
+ await page.setContent(html, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(
+ 'window.__renderDone === true || window.__renderError !== null',
+ { timeout: 15_000 },
+ );
+ const err = await page.evaluate(() => window.__renderError);
+ if (err) {
+ throw Object.assign(new Error(`render failed: ${err}`), { status: 502, code: 'render_failed' });
+ }
+ return await page.screenshot({
+ type: 'png',
+ omitBackground: background === 'transparent',
+ clip: { x: 0, y: 0, width, height },
+ });
+ } finally {
+ await page.close().catch(() => {});
+ }
+}
+
+// Test seam — let test suites bypass the real launcher without monkey-patching
+// the module path. Production code never sets this.
+export function __setBrowserForTests(browser) {
+ _browserPromise = browser ? Promise.resolve(browser) : null;
+}
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 3b664c001..b1e4ff9a1 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -450,10 +450,62 @@ export function encodePaymentResponseHeader(settleResult) {
export const RESOURCE_DESCRIPTION =
'three.ws MCP — Streamable HTTP transport (MCP 2025-06-18) exposing 3D avatar viewer, glTF/GLB model validation/inspection/optimization, and Solana agent data as JSON-RPC 2.0 tool calls. Pay-per-call in USDC on Base mainnet (eip155:8453) or Solana mainnet. ≤256 tools/call output, ≤32-message JSON-RPC batches. Operated by three.ws.';
+// Build the bazaar.schema *meta-schema* — the JSON Schema that validates the
+// `{input, output}` shape of the extension itself, NOT the endpoint's response
+// body. The user's response-body schema gets nested at
+// `schema.properties.output.properties.example`. Matches the reference
+// @x402/extensions/bazaar createDiscoveryExtension output exactly; deviating
+// from it causes agentic.market's parser to reject the endpoint with
+// "v2 discovery extension validation failed" even when all surface-level
+// checks (Transport, Payment Requirements, Bazaar Extension) pass.
+export function buildBazaarSchema({ method, queryParamsSchema, bodyType, bodySchema, outputSchema }) {
+ const upperMethod = String(method || 'GET').toUpperCase();
+ const isBodyMethod = ['POST', 'PUT', 'PATCH'].includes(upperMethod);
+ const inputProperties = {
+ type: { type: 'string', const: 'http' },
+ method: {
+ type: 'string',
+ enum: isBodyMethod ? ['POST', 'PUT', 'PATCH'] : ['GET', 'HEAD', 'DELETE'],
+ },
+ };
+ const inputRequired = ['type', 'method'];
+ if (isBodyMethod) {
+ inputProperties.bodyType = { type: 'string', enum: ['json', 'form-data', 'text'] };
+ inputProperties.body = bodySchema && typeof bodySchema === 'object' ? bodySchema : { type: 'object' };
+ inputRequired.push('bodyType', 'body');
+ } else if (queryParamsSchema && typeof queryParamsSchema === 'object') {
+ inputProperties.queryParams = { type: 'object', ...queryParamsSchema };
+ }
+ const schema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ input: {
+ type: 'object',
+ properties: inputProperties,
+ required: inputRequired,
+ additionalProperties: false,
+ },
+ },
+ required: ['input'],
+ };
+ if (outputSchema && typeof outputSchema === 'object') {
+ schema.properties.output = {
+ type: 'object',
+ properties: {
+ type: { type: 'string' },
+ example: { type: 'object', ...outputSchema },
+ },
+ required: ['type'],
+ };
+ }
+ return schema;
+}
+
// Bazaar discovery extension — shape required by agentic.market's validator.
// `info.input.{type,method,body|queryParams|pathParams}` describes how to call
// the resource; `info.output.{type,example}` shows what comes back; top-level
-// `schema` is the JSON Schema for the response body.
+// `schema` is the meta-schema built by `buildBazaarSchema` above.
//
// This is the v2 `declareDiscoveryExtension` shape. The flat
// `{method,input,inputSchema,output:{example,schema}}` shape v1 used is no
@@ -477,6 +529,56 @@ export function bazaarExtension() {
],
},
};
+ const requestBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['jsonrpc', 'method'],
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ method: {
+ type: 'string',
+ enum: ['initialize', 'tools/list', 'tools/call', 'ping'],
+ description: 'MCP JSON-RPC method.',
+ },
+ params: {
+ type: 'object',
+ description:
+ 'For tools/call: { name, arguments }. Tool names include validate_model, inspect_model, optimize_model, search_public_avatars, solana_register, solana_reputation, and others — see tools/list.',
+ },
+ },
+ };
+ const responseBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ result: {
+ type: 'object',
+ properties: {
+ content: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['type', 'text'],
+ properties: {
+ type: { type: 'string', enum: ['text'] },
+ text: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ error: {
+ type: 'object',
+ properties: {
+ code: { type: 'number' },
+ message: { type: 'string' },
+ },
+ },
+ },
+ };
return {
discoverable: true,
info: {
@@ -485,62 +587,18 @@ export function bazaarExtension() {
method: 'POST',
body: exampleBody,
bodyType: 'json',
- bodySchema: {
- $schema: 'https://json-schema.org/draft/2020-12/schema',
- type: 'object',
- required: ['jsonrpc', 'method'],
- properties: {
- jsonrpc: { type: 'string', const: '2.0' },
- id: { type: ['string', 'number'] },
- method: {
- type: 'string',
- enum: ['initialize', 'tools/list', 'tools/call', 'ping'],
- description: 'MCP JSON-RPC method.',
- },
- params: {
- type: 'object',
- description:
- 'For tools/call: { name, arguments }. Tool names include validate_model, inspect_model, optimize_model, search_public_avatars, solana_register, solana_reputation, and others — see tools/list.',
- },
- },
- },
},
output: {
type: 'json',
example: exampleResponse,
},
},
- schema: {
- $schema: 'https://json-schema.org/draft/2020-12/schema',
- type: 'object',
- properties: {
- jsonrpc: { type: 'string', const: '2.0' },
- id: { type: ['string', 'number'] },
- result: {
- type: 'object',
- properties: {
- content: {
- type: 'array',
- items: {
- type: 'object',
- required: ['type', 'text'],
- properties: {
- type: { type: 'string', enum: ['text'] },
- text: { type: 'string' },
- },
- },
- },
- },
- },
- error: {
- type: 'object',
- properties: {
- code: { type: 'number' },
- message: { type: 'string' },
- },
- },
- },
- },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: requestBodySchema,
+ outputSchema: responseBodySchema,
+ }),
};
}
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 036453ef5..592195e67 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -72,6 +72,32 @@ async function handleLogoutEverywhere(req, res) {
// ── register ──────────────────────────────────────────────────────────────────
+// Bounded retry to ride out the rare collision against the unique index on
+// users.referral_code. The index is the authoritative guard; this loop is the
+// UX shield so simultaneous signups don't surface a 500. The generator is a
+// CSPRNG over a 32-char alphabet at length 8, so the chance of MAX_TRIES
+// consecutive collisions is astronomically low — if we ever exhaust, something
+// upstream is wrong (truncated alphabet, broken RNG) and we want to surface it.
+const MAX_REFERRAL_CODE_TRIES = 8;
+
+async function insertUserWithUniqueReferralCode({ email, passwordHash, displayName, referredById }) {
+ for (let i = 0; i < MAX_REFERRAL_CODE_TRIES; i += 1) {
+ const code = generateReferralCode();
+ try {
+ const [row] = await sql`
+ insert into users (email, password_hash, display_name, referred_by_id, referral_code)
+ values (${email}, ${passwordHash}, ${displayName}, ${referredById}, ${code})
+ returning id, display_name, plan, created_at, referral_code
+ `;
+ return row;
+ } catch (err) {
+ if (err && err.code === '23505' && /referral_code/.test(err.message || '')) continue;
+ throw err;
+ }
+ }
+ throw new Error('referral_code_generation_exhausted');
+}
+
async function handleRegister(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -106,9 +132,12 @@ async function handleRegister(req, res) {
}
const hash = await hashPassword(passwordVal);
- // TODO: loop until referral code is unique
- const newReferralCode = generateReferralCode();
- const [user] = await sql`insert into users (email, password_hash, display_name, referred_by_id, referral_code) values (${email_val}, ${hash}, ${displayName_val}, ${referred_by_id}, ${newReferralCode}) returning id, display_name, plan, created_at, referral_code`;
+ const user = await insertUserWithUniqueReferralCode({
+ email: email_val,
+ passwordHash: hash,
+ displayName: displayName_val,
+ referredById: referred_by_id,
+ });
// Fire-and-forget: every new account gets a starter draft agent so the
// marketplace's "My Agents" tab and onboarding flow have something to show.
queueMicrotask(() => seedDefaultAgent(user.id));
diff --git a/api/auth/siwe/[action].js b/api/auth/siwe/[action].js
index d300ff9ff..0f421befb 100644
--- a/api/auth/siwe/[action].js
+++ b/api/auth/siwe/[action].js
@@ -11,7 +11,6 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { randomToken, hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { env } from '../../_lib/env.js';
import { parse } from '../../_lib/validate.js';
-import { sendWelcomeEmail } from '../../_lib/email.js';
import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';
const NONCE_TTL_SEC = 5 * 60;
@@ -245,9 +244,8 @@ async function handleVerify(req, res) {
chain_id = coalesce(${chainId}, user_wallets.chain_id)
`;
if (user.inserted) {
- queueMicrotask(() =>
- sendWelcomeEmail({ to: placeholderEmail, displayName: shortAddr(claimed) }),
- );
+ // No welcome email here — placeholderEmail is a synthetic
+ // @wallet.local address and is not deliverable.
queueMicrotask(() => seedDefaultAgent(userId));
}
}
diff --git a/api/auth/siws/[action].js b/api/auth/siws/[action].js
index dc0dd4d7e..45d2e7580 100644
--- a/api/auth/siws/[action].js
+++ b/api/auth/siws/[action].js
@@ -11,7 +11,6 @@ import { env } from '../../_lib/env.js';
import { parse } from '../../_lib/validate.js';
import { randomToken, hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { parseSiwsMessage, verifySiwsSignature } from '../../_lib/siws.js';
-import { sendWelcomeEmail } from '../../_lib/email.js';
import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';
const NONCE_TTL_SEC = 5 * 60;
@@ -224,9 +223,8 @@ async function handleVerify(req, res) {
set last_used_at = now()
`;
if (user.inserted) {
- queueMicrotask(() =>
- sendWelcomeEmail({ to: placeholderEmail, displayName: shortAddr(addr) }),
- );
+ // No welcome email here — placeholderEmail is a synthetic
+ // @wallet.local address and is not deliverable.
queueMicrotask(() => seedDefaultAgent(userId));
}
}
diff --git a/api/avatar-og.js b/api/avatar-og.js
index e38ee794b..774245501 100644
--- a/api/avatar-og.js
+++ b/api/avatar-og.js
@@ -3,22 +3,44 @@
* ------------------------
* GET /api/avatar/:id/og
*
- * Strategy: prefer a real PNG (avatar's R2-hosted thumbnail) when one exists,
- * fall back to a rich SVG card otherwise. Slack/X/Discord all accept
- * image/svg+xml for OG images, so the fallback never reaches a renderer.
+ * Strategy, in order:
+ * 1. If the avatar has a cached thumbnail in R2 (set by the customizer-save
+ * snapshot flow or by a previous server render), 302 to its public URL.
+ * 2. Otherwise, if the avatar's GLB is publicly reachable, render a PNG
+ * preview via headless chromium, cache it in R2, write back the
+ * thumbnail_key, and stream the PNG response.
+ * 3. Demo avatars (avatar_demo_*) and not-found IDs get the SVG card.
+ * 4. Any failure of the renderer (timeout, too-large GLB, private avatar,
+ * unreachable model URL) falls through to the site OG logo. CLAUDE.md
+ * forbids placeholder data — the logo is a real, branded image, not a
+ * synthetic "no preview" SVG.
*
- * Demo avatars (avatar_demo_*) are seeded fixtures and have no thumbnails —
- * they always get the SVG card, which still includes the avatar name,
- * description, attribution, and a 3D-themed gradient backdrop.
+ * The renderer is amortized: only the first crawl of an avatar pays the
+ * chromium cost. Every subsequent crawl hits step (1) and 302s out.
*/
+import { sql } from './_lib/db.js';
import { getAvatar } from './_lib/avatars.js';
import { DEMO_AVATARS } from './_lib/demo-avatars.js';
import { cors, wrap } from './_lib/http.js';
+import { publicUrl, putObject } from './_lib/r2.js';
+import { renderGlbToPng } from './_lib/render-glb.js';
const CACHE_CARD_OK = 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800';
const CACHE_CARD_404 = 'public, max-age=60';
const CACHE_REDIR = 'public, max-age=3600';
+const CACHE_RENDERED = 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=604800';
+const CACHE_FALLBACK = 'public, max-age=300';
+
+// Anything bigger than this would dominate the 15s render budget — and
+// Vercel's 30s function ceiling means a single oversized GLB risks killing
+// the request. Falls back to the site logo instead.
+const MAX_GLB_BYTES = 10 * 1024 * 1024;
+
+// Per-avatar lock so two simultaneous crawls don't both spin up chromium.
+// In-memory only — multiple lambda containers may each render once, but
+// they settle to the same cached R2 object via the DB write-back.
+const _renderLocks = new Map();
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -58,6 +80,8 @@ export default wrap(async (req, res) => {
});
}
+ // Cached thumbnail — either client-uploaded (customizer save) or a
+ // previous server render. Either way it's a real R2 object; redirect.
if (avatar.thumbnail_url) {
res.statusCode = 302;
res.setHeader('location', avatar.thumbnail_url);
@@ -66,13 +90,91 @@ export default wrap(async (req, res) => {
return;
}
- return sendCardSvg(res, 200, CACHE_CARD_OK, {
- name: avatar.name || 'Avatar',
- description: avatar.description || 'A 3D avatar on three.ws',
- tags: avatar.tags || [],
- });
+ // Private avatars have no public model_url, so headless chromium can't
+ // fetch the GLB. Serve the SVG card with whatever name/desc/tags exist.
+ if (!avatar.model_url) {
+ return sendCardSvg(res, 200, CACHE_CARD_OK, {
+ name: avatar.name || 'Avatar',
+ description: avatar.description || 'A 3D avatar on three.ws',
+ tags: avatar.tags || [],
+ });
+ }
+
+ // Server render path. Anything that goes wrong falls back to the site
+ // logo — a 200/302 with the brand logo is strictly better than a 500
+ // to a Twitter/Slack/Discord crawler, which would cache the failure.
+ try {
+ const png = await renderAndCache({ avatar });
+ res.statusCode = 200;
+ res.setHeader('content-type', 'image/png');
+ res.setHeader('cache-control', CACHE_RENDERED);
+ res.end(png);
+ return;
+ } catch (err) {
+ console.warn('[avatar-og] render fallback', { avatarId, err: err?.message });
+ return sendFallbackLogo(req, res);
+ }
});
+// Render + upload + DB write-back, sharing in-flight work across concurrent
+// crawls. The returned PNG buffer is what every caller receives.
+async function renderAndCache({ avatar }) {
+ const existing = _renderLocks.get(avatar.id);
+ if (existing) return existing;
+
+ const promise = (async () => {
+ // Size precheck. A 50 MB GLB would blow the render budget and risk
+ // OOM; kick those out to the fallback before launching chromium.
+ const head = await fetch(avatar.model_url, { method: 'HEAD' }).catch(() => null);
+ const contentLength = Number(head?.headers?.get('content-length') || 0);
+ if (head?.ok && contentLength > MAX_GLB_BYTES) {
+ throw Object.assign(new Error(`glb too large: ${contentLength} bytes`), {
+ code: 'glb_too_large',
+ });
+ }
+ // Don't blow up on a missing content-length — some R2 deployments
+ // omit it; we lose the precheck and rely on the render timeout.
+
+ const png = await renderGlbToPng({
+ glbUrl: avatar.model_url,
+ width: 1200,
+ height: 630,
+ background: '#0a0a0a',
+ });
+
+ const ogKey = ogKeyFor(avatar);
+ await putObject({
+ key: ogKey,
+ body: png,
+ contentType: 'image/png',
+ metadata: { source: 'server-render', avatar_id: avatar.id },
+ });
+ // Single UPDATE — bypasses ownership/visibility checks in
+ // updateAvatar() because this is an internal cache write, not a
+ // user-initiated edit. Guarded by `thumbnail_key is null` so a
+ // concurrent customizer-save snapshot isn't clobbered.
+ await sql`
+ update avatars set thumbnail_key = ${ogKey}, updated_at = now()
+ where id = ${avatar.id} and deleted_at is null and thumbnail_key is null
+ `;
+ return png;
+ })();
+
+ _renderLocks.set(avatar.id, promise);
+ try {
+ return await promise;
+ } finally {
+ _renderLocks.delete(avatar.id);
+ }
+}
+
+// OG cache key: lives alongside the GLB in the user's namespace so it
+// shares lifetime + deletion semantics. _og.png distinguishes from
+// _thumb.jpg (the client-uploaded customizer snapshot).
+function ogKeyFor(avatar) {
+ return avatar.storage_key.replace(/\.glb$/i, '') + '_og.png';
+}
+
// Vercel routes /api/avatar/:id/og → here. Read the id from the URL path
// when the rewrite leaves it as a path segment instead of a query param.
function extractIdFromPath(pathname) {
@@ -80,6 +182,17 @@ function extractIdFromPath(pathname) {
return m ? m[1] : null;
}
+function sendFallbackLogo(req, res) {
+ // 302 to the static brand logo. The crawler then fetches
+ // /assets/og-image.png directly from Vercel's edge.
+ const proto = String(req.headers['x-forwarded-proto'] || 'https').split(',')[0].trim();
+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ res.statusCode = 302;
+ res.setHeader('location', `${proto}://${host}/assets/og-image.png`);
+ res.setHeader('cache-control', CACHE_FALLBACK);
+ res.end();
+}
+
function sendCardSvg(res, status, cacheControl, payload) {
res.statusCode = status;
res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
@@ -140,3 +253,6 @@ function escapeXml(s) {
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
+
+// Test seam — let suites assert against the in-memory render lock map.
+export const __testInternals = { renderAndCache, ogKeyFor, _renderLocks };
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 957bea54b..3de97dfab 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -1134,17 +1134,17 @@ async function handleRunBuyback(req, res) {
return error(res, 401, 'unauthorized', 'cron auth required');
}
- const fullSwap = process.env.PUMP_BUYBACK_FULL_SWAP === 'true';
const relayer = await buybackLoadRelayer();
const mints = await sql`
- select id, mint, network from pump_agent_mints limit 200
+ select id, mint, network, full_swap, slippage_bps from pump_agent_mints limit 200
`;
const results = [];
for (const m of mints) {
const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
const currency = solanaPubkey(currencyStr);
+ const fullSwap = m.full_swap === true;
try {
const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
@@ -1169,14 +1169,22 @@ async function handleRunBuyback(req, res) {
const params = {
globalBuybackAuthority: payerPk, // gated by globalConfig — for skipped-swap form, can be relayer
currencyMint: currency,
- swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel program for skip-swap path
+ swapProgramToInvoke: PUMP_PROGRAM_ID, // pump bonding-curve program (same for burn-only and full-swap)
swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
remainingAccounts: [],
};
if (fullSwap) {
- // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
- // keepers should supply this off-chain until tested on devnet.
+ const { buildPumpSwapInnerIx } = await import('../_lib/pump-swap-ix.js');
+ const inner = await buildPumpSwapInnerIx({
+ mint: m.mint,
+ currency,
+ amountIn: buyback,
+ slippageBps: m.slippage_bps ?? 500,
+ cluster: m.network,
+ });
+ params.swapInstructionData = inner.data;
+ params.remainingAccounts = inner.accounts;
}
let ix;
@@ -1184,8 +1192,8 @@ async function handleRunBuyback(req, res) {
ix = await offline.buybackTrigger(params);
} catch (e) {
const [run] = await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status, error)
- values (${m.id}, ${currencyStr}, 'failed', ${'buybackTrigger build failed: ' + e.message})
+ insert into pump_buyback_runs (mint_id, currency_mint, swap_program, status, error)
+ values (${m.id}, ${currencyStr}, ${PUMP_PROGRAM_ID.toBase58()}, 'failed', ${'buybackTrigger build failed: ' + e.message})
returning id
`;
results.push({ mint: m.mint, status: 'failed', error: e.message, run_id: run.id });
@@ -1199,8 +1207,8 @@ async function handleRunBuyback(req, res) {
instructions: [ix],
});
const [run] = await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status, burn_amount)
- values (${m.id}, ${currencyStr}, 'pending', ${buyback.toString()})
+ insert into pump_buyback_runs (mint_id, currency_mint, swap_program, status, burn_amount)
+ values (${m.id}, ${currencyStr}, ${PUMP_PROGRAM_ID.toBase58()}, 'pending', ${buyback.toString()})
returning id
`;
results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
@@ -1220,9 +1228,9 @@ async function handleRunBuyback(req, res) {
const [run] = await sql`
insert into pump_buyback_runs
- (mint_id, currency_mint, tx_signature, status, burn_amount)
+ (mint_id, currency_mint, swap_program, tx_signature, status, burn_amount)
values
- (${m.id}, ${currencyStr}, ${sig}, 'confirmed', ${buyback.toString()})
+ (${m.id}, ${currencyStr}, ${PUMP_PROGRAM_ID.toBase58()}, ${sig}, 'confirmed', ${buyback.toString()})
returning id
`;
results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
diff --git a/api/healthz.js b/api/healthz.js
index 02dea9169..9519abaef 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -11,17 +11,65 @@ import { cors, json, method, wrap } from './_lib/http.js';
const STARTED_AT = Date.now();
const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_version || 'dev';
+const RESEND_CACHE_TTL_MS = 5 * 60 * 1000;
+let _resendCache = { value: null, expiresAt: 0 };
+
+// Exported for tests so each case starts with a cold cache.
+export function _resetResendCache() {
+ _resendCache = { value: null, expiresAt: 0 };
+}
+
+async function probeResend() {
+ const now = Date.now();
+ if (_resendCache.value && _resendCache.expiresAt > now) {
+ return _resendCache.value;
+ }
+
+ const key = process.env.RESEND_API_KEY;
+ if (!key) {
+ _resendCache = { value: 'missing', expiresAt: now + RESEND_CACHE_TTL_MS };
+ return 'missing';
+ }
+
+ let result;
+ try {
+ const r = await fetch('https://api.resend.com/domains', {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${key}` },
+ signal: AbortSignal.timeout(3000),
+ });
+ if (r.ok) {
+ result = 'configured';
+ } else if (r.status === 401) {
+ // Send-only ("restricted") keys legitimately can't list domains.
+ const body = await r.text().catch(() => '');
+ result = body.includes('restricted_api_key') ? 'configured' : 'key_invalid';
+ } else if (r.status === 403) {
+ result = 'configured';
+ } else {
+ result = 'key_invalid';
+ }
+ } catch {
+ result = 'key_invalid';
+ }
+
+ _resendCache = { value: result, expiresAt: now + RESEND_CACHE_TTL_MS };
+ return result;
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const uptimeMs = Date.now() - STARTED_AT;
+ const resend = await probeResend();
return json(res, 200, {
status: 'ok',
service: '3d-agent',
version: VERSION,
uptime: Math.floor(uptimeMs / 1000),
uptimeMs,
+ resend,
// Match the pump-dashboard health shape so the existing UI binding works
// without conditional logic.
monitor: { running: true, mode: 'serverless', claimsDetected: 0 },
diff --git a/api/payments/evm/[action].js b/api/payments/evm/[action].js
index abe0ed24f..a9b1d264c 100644
--- a/api/payments/evm/[action].js
+++ b/api/payments/evm/[action].js
@@ -87,7 +87,7 @@ async function handleConfirm(req, res) {
const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);
await sql`insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;
await sql`update users set plan=${intent.plan} where id=${user.id}`;
- queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `EVM chain ${chainId}`, txId: tx_hash }));
+ queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `EVM chain ${chainId}`, txId: tx_hash }).catch(() => {}));
return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_hash });
}
diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].js
index 1169088c8..b451107e3 100644
--- a/api/payments/solana/[action].js
+++ b/api/payments/solana/[action].js
@@ -114,7 +114,7 @@ async function handleConfirm(req, res) {
const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);
await sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;
await sql`update users set plan=${intent.plan} where id=${user.id}`;
- queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `Solana ${network}`, txId: tx_signature }));
+ queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `Solana ${network}`, txId: tx_signature }).catch(() => {}));
return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_signature });
}
diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.js
index 14eba0550..b3caeec68 100644
--- a/api/x402/agent-reputation.js
+++ b/api/x402/agent-reputation.js
@@ -13,6 +13,7 @@
// canonical source for any AI agent vetting a three.ws-registered agent.
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/agent-reputation';
@@ -139,11 +140,14 @@ const BAZAAR = {
type: 'http',
method: 'GET',
queryParams: INPUT_EXAMPLE,
- queryParamsSchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
diff --git a/api/x402/mint-to-mesh-batch.js b/api/x402/mint-to-mesh-batch.js
index 1875615d3..35336c3f9 100644
--- a/api/x402/mint-to-mesh-batch.js
+++ b/api/x402/mint-to-mesh-batch.js
@@ -13,6 +13,7 @@
// so the buyer always gets a useful response after paying.
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { readJson } from '../_lib/http.js';
import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
@@ -80,11 +81,15 @@ const BAZAAR = {
method: 'POST',
body: INPUT_EXAMPLE,
bodyType: 'json',
- bodySchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index a6f4f7d41..3ea65d731 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -24,6 +24,7 @@ import {
settlePayment,
encodePaymentResponseHeader,
resolveResourceUrl,
+ buildBazaarSchema,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
@@ -124,11 +125,14 @@ const ROUTE_BAZAAR = {
type: 'http',
method: 'GET',
queryParams: DISCOVERY_INPUT_EXAMPLE,
- queryParamsSchema: DISCOVERY_INPUT_SCHEMA,
},
output: { type: 'json', example: DISCOVERY_OUTPUT_EXAMPLE },
},
- schema: DISCOVERY_OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: DISCOVERY_INPUT_SCHEMA,
+ outputSchema: DISCOVERY_OUTPUT_SCHEMA,
+ }),
};
function buildRequirements(resourceUrl) {
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 1459d6bb5..59b9bcb2d 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -20,6 +20,7 @@ import {
settlePayment,
encodePaymentResponseHeader,
resolveResourceUrl,
+ buildBazaarSchema,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
@@ -141,11 +142,14 @@ const ROUTE_BAZAAR = {
type: 'http',
method: 'GET',
queryParams: DISCOVERY_INPUT_EXAMPLE,
- queryParamsSchema: DISCOVERY_INPUT_SCHEMA,
},
output: { type: 'json', example: DISCOVERY_OUTPUT_EXAMPLE },
},
- schema: DISCOVERY_OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: DISCOVERY_INPUT_SCHEMA,
+ outputSchema: DISCOVERY_OUTPUT_SCHEMA,
+ }),
};
function buildRequirements(resourceUrl) {
diff --git a/api/x402/onchain-identity-verify.js b/api/x402/onchain-identity-verify.js
index e183186c1..6d404e48e 100644
--- a/api/x402/onchain-identity-verify.js
+++ b/api/x402/onchain-identity-verify.js
@@ -13,6 +13,7 @@
// agent really own the contract it claims?"
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/onchain-identity-verify';
@@ -93,11 +94,14 @@ const BAZAAR = {
type: 'http',
method: 'GET',
queryParams: INPUT_EXAMPLE,
- queryParamsSchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.js
index c6dd6dfb5..e076d0eb0 100644
--- a/api/x402/pump-agent-audit.js
+++ b/api/x402/pump-agent-audit.js
@@ -13,6 +13,7 @@
// trusting a pump-agent token; otherwise they're flying blind on op risk.
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/pump-agent-audit';
@@ -98,11 +99,14 @@ const BAZAAR = {
type: 'http',
method: 'GET',
queryParams: INPUT_EXAMPLE,
- queryParamsSchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.js
index 1182e0a48..b807d307d 100644
--- a/api/x402/skill-marketplace.js
+++ b/api/x402/skill-marketplace.js
@@ -11,6 +11,7 @@
// to the cheapest competent provider — saving real USDC vs. picking blindly.
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/skill-marketplace';
@@ -86,11 +87,14 @@ const BAZAAR = {
type: 'http',
method: 'GET',
queryParams: INPUT_EXAMPLE,
- queryParamsSchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
function rowToListing(r) {
diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.js
index d7aa7ba1c..c2777470d 100644
--- a/api/x402/symbol-availability.js
+++ b/api/x402/symbol-availability.js
@@ -13,6 +13,7 @@
// enough that humans confuse them" which exact-match APIs miss.
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/symbol-availability';
@@ -76,11 +77,14 @@ const BAZAAR = {
type: 'http',
method: 'GET',
queryParams: INPUT_EXAMPLE,
- queryParamsSchema: INPUT_SCHEMA,
},
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
- schema: OUTPUT_SCHEMA,
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
};
const SIMILARITY_THRESHOLD = 0.4;
diff --git a/crates/vanity-grinder/.gitignore b/crates/vanity-grinder/.gitignore
new file mode 100644
index 000000000..96ef6c0b9
--- /dev/null
+++ b/crates/vanity-grinder/.gitignore
@@ -0,0 +1,2 @@
+/target
+Cargo.lock
diff --git a/crates/vanity-grinder/Cargo.toml b/crates/vanity-grinder/Cargo.toml
new file mode 100644
index 000000000..aef3a3752
--- /dev/null
+++ b/crates/vanity-grinder/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "vanity-grinder"
+version = "0.1.0"
+edition = "2021"
+description = "WASM-backed Solana ed25519 vanity address grinder"
+license = "MIT"
+publish = false
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+wasm-bindgen = "0.2"
+js-sys = "0.3"
+sha2 = { version = "0.10", default-features = false }
+curve25519-dalek = { version = "4", default-features = false, features = ["alloc", "precomputed-tables"] }
+bs58 = { version = "0.5", default-features = false, features = ["alloc"] }
+
+[profile.release]
+opt-level = 3
+lto = "fat"
+codegen-units = 1
+strip = true
+panic = "abort"
+
+[package.metadata.wasm-pack.profile.release]
+wasm-opt = ["-O3", "--enable-bulk-memory", "--enable-nontrapping-float-to-int", "--enable-simd"]
diff --git a/crates/vanity-grinder/src/lib.rs b/crates/vanity-grinder/src/lib.rs
new file mode 100644
index 000000000..e4a891184
--- /dev/null
+++ b/crates/vanity-grinder/src/lib.rs
@@ -0,0 +1,141 @@
+//! WASM-backed Solana ed25519 vanity address grinder.
+//!
+//! Exposes a single `grind` function callable from JS. Each call tries up to
+//! `batch` keypairs derived deterministically from `start_seed` by treating
+//! the low 4 bytes of the seed as a little-endian counter; the JS caller is
+//! expected to supply a fresh cryptographically-random 32-byte `start_seed`
+//! for each batch so resulting keys are unpredictable.
+//!
+//! Returns `null` if no match is found in the batch, or a `{ secretKey,
+//! publicKey }` object on match. The 64-byte `secretKey` matches Solana's
+//! standard layout: `[32-byte seed][32-byte public key]`, compatible with
+//! `Keypair.fromSecretKey()` in `@solana/web3.js`.
+//!
+//! The hot loop derives each pubkey via raw curve25519-dalek primitives
+//! (`SHA-512(seed) → clamp → scalar * G → compress`) — exactly the ed25519
+//! keypair derivation but without constructing the full `SigningKey` struct
+//! that ed25519-dalek would normally hand back. The output pubkey is
+//! bit-for-bit identical to `ed25519_dalek::SigningKey::from_bytes(seed)
+//! .verifying_key().to_bytes()`.
+
+use curve25519_dalek::edwards::EdwardsPoint;
+use js_sys::{Object, Reflect, Uint8Array};
+use sha2::{Digest, Sha512};
+use wasm_bindgen::prelude::*;
+
+#[inline(always)]
+fn pubkey_from_seed(seed: &[u8; 32]) -> [u8; 32] {
+ let mut h = Sha512::new();
+ h.update(seed);
+ let digest = h.finalize();
+
+ let mut scalar_bytes = [0u8; 32];
+ scalar_bytes.copy_from_slice(&digest[..32]);
+
+ // mul_base_clamped internally applies the ed25519 clamp (clear 3 low bits,
+ // clear high bit, set 254th bit) and multiplies by the basepoint — exactly
+ // what `ed25519_dalek::SigningKey::from_bytes(seed).verifying_key()` does,
+ // minus the SigningKey-struct overhead we don't need for grinding.
+ EdwardsPoint::mul_base_clamped(scalar_bytes)
+ .compress()
+ .to_bytes()
+}
+
+#[wasm_bindgen]
+pub fn grind(
+ prefix: &str,
+ suffix: &str,
+ ignore_case: bool,
+ batch: u32,
+ start_seed: &[u8],
+) -> JsValue {
+ if start_seed.len() != 32 {
+ return JsValue::NULL;
+ }
+
+ let want_prefix: Vec<u8> = if ignore_case {
+ prefix.to_lowercase().into_bytes()
+ } else {
+ prefix.as_bytes().to_vec()
+ };
+ let want_suffix: Vec<u8> = if ignore_case {
+ suffix.to_lowercase().into_bytes()
+ } else {
+ suffix.as_bytes().to_vec()
+ };
+ let p_len = want_prefix.len();
+ let s_len = want_suffix.len();
+
+ let mut seed = [0u8; 32];
+ seed.copy_from_slice(start_seed);
+ let base_counter = u32::from_le_bytes([seed[0], seed[1], seed[2], seed[3]]);
+
+ for i in 0..batch {
+ let counter = base_counter.wrapping_add(i);
+ let bytes = counter.to_le_bytes();
+ seed[0] = bytes[0];
+ seed[1] = bytes[1];
+ seed[2] = bytes[2];
+ seed[3] = bytes[3];
+
+ let pub_bytes = pubkey_from_seed(&seed);
+
+ let addr_string = bs58::encode(&pub_bytes).into_string();
+ let addr = addr_string.as_bytes();
+
+ let prefix_ok = if p_len == 0 {
+ true
+ } else if addr.len() < p_len {
+ false
+ } else if ignore_case {
+ eq_ignore_ascii_case(&addr[..p_len], &want_prefix)
+ } else {
+ &addr[..p_len] == want_prefix.as_slice()
+ };
+ if !prefix_ok {
+ continue;
+ }
+
+ let suffix_ok = if s_len == 0 {
+ true
+ } else if addr.len() < s_len {
+ false
+ } else if ignore_case {
+ eq_ignore_ascii_case(&addr[addr.len() - s_len..], &want_suffix)
+ } else {
+ &addr[addr.len() - s_len..] == want_suffix.as_slice()
+ };
+ if !suffix_ok {
+ continue;
+ }
+
+ let mut secret_key = [0u8; 64];
+ secret_key[..32].copy_from_slice(&seed);
+ secret_key[32..].copy_from_slice(&pub_bytes);
+
+ let secret_array = Uint8Array::new_with_length(64);
+ secret_array.copy_from(&secret_key);
+
+ let result = Object::new();
+ Reflect::set(&result, &JsValue::from_str("secretKey"), &secret_array.into())
+ .expect("set secretKey");
+ Reflect::set(
+ &result,
+ &JsValue::from_str("publicKey"),
+ &JsValue::from_str(&addr_string),
+ )
+ .expect("set publicKey");
+ return result.into();
+ }
+
+ JsValue::NULL
+}
+
+fn eq_ignore_ascii_case(a: &[u8], b: &[u8]) -> bool {
+ if a.len() != b.len() {
+ return false;
+ }
+ a.iter()
+ .zip(b.iter())
+ .all(|(x, y)| x.eq_ignore_ascii_case(y))
+}
diff --git a/docs/demo-routes.md b/docs/demo-routes.md
new file mode 100644
index 000000000..ebc70f650
--- /dev/null
+++ b/docs/demo-routes.md
@@ -0,0 +1,101 @@
+# Demo routes
+
+The canonical map of every `/demo/*` and `/demos/*` route as of
+2026-05-20. Update whenever a route is added, removed, or moved.
+
+The demo namespace splits in two:
+
+- `/demo/<slug>/` — full standalone demos that own their URL space
+ (multiple sub-pages, dynamic segments). Each lives in
+ `public/demo/<slug>/`.
+- `/demos/<slug>` — single-page lab demos. Index hub is
+ `/demos/`. Each lives in `public/demos/<slug>.html`.
+
+Production routing is in [vercel.json](../vercel.json); the matching
+Vite dev-server middleware is in [vite.config.js](../vite.config.js).
+Both must be kept in sync.
+
+## Routes
+
+| Route | Page file | What it does |
+|---|---|---|
+| `/demo/coin` | `public/demo/coin/index.html` | Lottery + reflection demo on a single Pump.fun coin (real-time holder feed, payout history). |
+| `/demo/coin/<mint>` | `public/demo/coin/index.html` | Same page hydrated for a specific base58 mint address (32–44 chars). |
+| `/demo/avatar-os/` | `public/demo/avatar-os/index.html` | OSS avatar pipeline hub linking to the four sub-pages below. |
+| `/demo/avatar-os/studio.html` | `public/demo/avatar-os/studio.html` | Avatar Studio (rebranded Character Studio fork) embed. |
+| `/demo/avatar-os/selfie.html` | `public/demo/avatar-os/selfie.html` | Selfie-to-avatar flow. |
+| `/demo/avatar-os/combined.html` | `public/demo/avatar-os/combined.html` | Studio + selfie shown side-by-side. |
+| `/demo/avatar-os/live.html` | `public/demo/avatar-os/live.html` | Live capture / streaming variant. |
+| `/demos/` | `public/demos/index.html` | Index of all lab demos. |
+| `/demos/3d-home` | `public/demos/3d-home.html` | "Give your AI a body" homepage demo. |
+| `/demos/avatar-sdk` | `public/demos/avatar-sdk.html` | `@three-ws/avatar` SDK walkthrough. |
+| `/demos/bonding-curve` | `public/demos/bonding-curve.html` | Bonding curve simulator. |
+| `/demos/brain` | `public/demos/brain.html` | Multi-LLM brain router. |
+| `/demos/button` | `public/demos/button.html` | Tactile button experiment. |
+| `/demos/button-jump` | `public/demos/button-jump.html` | Tactile button + jump animation variant. |
+| `/demos/create-v2` | `public/demos/create-v2.html` | Create-avatar v2 flow. |
+| `/demos/eas-reputation` | `public/demos/eas-reputation.html` | Reputation attestations on Base via EAS. |
+| `/demos/erc8004` | `public/demos/erc8004.html` | ERC-8004 registry browser. |
+| `/demos/gallery-picker` | `public/demos/gallery-picker.html` | Avatar gallery picker UI. |
+| `/demos/gemini-jump` | `public/demos/gemini-jump.html` | Tactile button (Gemini concept). |
+| `/demos/halfbody-xr` | `public/demos/halfbody-xr.html` | Half-body avatar in WebXR. |
+| `/demos/lipsync-mic` | `public/demos/lipsync-mic.html` | Audio-driven lipsync from microphone. |
+| `/demos/lipsync-tts` | `public/demos/lipsync-tts.html` | TTS-driven lipsync. |
+| `/demos/livepeer-inference` | `public/demos/livepeer-inference.html` | Decentralized inference via Livepeer. |
+| `/demos/memory-seed` | `public/demos/memory-seed.html` | Agent memory seeding flow. |
+| `/demos/persona-extract` | `public/demos/persona-extract.html` | Persona extraction from social handles. |
+| `/demos/react-sdk` | `public/demos/react-sdk.html` | `@three-ws/avatar/react` SDK walkthrough. |
+| `/demos/selfie-fit` | `public/demos/selfie-fit.html` | Selfie-fit avatar pipeline. |
+| `/demos/skill-royalty` | `public/demos/skill-royalty.html` | Skill royalty distribution demo. |
+| `/demos/usdz-ar` | `public/demos/usdz-ar.html` | USDZ + AR Quick Look (iOS). |
+| `/demos/voice-clone` | `public/demos/voice-clone.html` | Voice cloning demo. |
+| `/demos/walkaround` | `public/demos/walkaround.html` | 3D walkaround scene. |
+
+The legacy `/walkaround`, `/brain`, `/lipsync`, `/lipsync/mic`
+shortcuts in `vercel.json` still resolve to the `/demos/*.html` files
+above. They predate the `/demos/` namespace and are kept for backward
+compatibility — prefer the `/demos/<slug>` form for new links.
+
+## Legacy redirects
+
+| Old | New | Configured in |
+|---|---|---|
+| `/coin` | `/demo/coin` | `vercel.json` (301), mirrored in `vite.config.js` middleware for dev. |
+| `/coin/` | `/demo/coin` | `vercel.json` (301), mirrored in `vite.config.js` middleware for dev. |
+
+`pages/pump-coin-page.html` predates the `/demo/coin` rewrite and is
+not wired into the canonical demo nav. It still resolves at
+`/pump-coin-page` via the generic `pages/<slug>.html` fallback in the
+Vite middleware, but new links should point at `/demo/coin`.
+
+## Adding a new demo
+
+1. Create the page under `public/demos/<slug>.html` (single-page lab
+ demo) or `public/demo/<slug>/index.html` (multi-page demo with its
+ own URL space).
+2. If the demo has inline `<script type="module">` blocks that import
+ from `/src/*` or pull in heavy SDKs, register it under
+ `build.rollupOptions.input` in `vite.config.js` so the bundler
+ processes its scripts. (Most `/demos/<slug>` pages do not need this
+ — they're served as plain HTML.)
+3. For multi-page demos (`/demo/<slug>/`), add entries to both
+ `fileMap` and the `dirRoutes` set in `vite.config.js` so the dev
+ server serves the directory index and adds the trailing-slash
+ redirect that lets relative imports resolve.
+4. Add the production route to `vercel.json` if the URL does not match
+ the file path directly:
+ - For `/demos/<slug>` the regex
+ `"/demos/([^/.]+)" → "/demos/$1.html"` already covers it.
+ - For `/demo/<slug>/*` add explicit `dest` rewrites following the
+ `/demo/avatar-os/*` pattern.
+5. Add a row to the table above.
+6. Curl-verify locally:
+
+ ```bash
+ npm run dev
+ curl -sIL -o /dev/null -w "%{http_code} %{url_effective}\n" \
+ http://localhost:3000/<route>
+ ```
+
+ The route must return `200` (or `301` → 200 for a documented
+ legacy redirect).
diff --git a/docs/internal/NEXT.md b/docs/internal/NEXT.md
index 78e528395..a15eaf7ab 100644
--- a/docs/internal/NEXT.md
+++ b/docs/internal/NEXT.md
@@ -2,19 +2,4 @@
Items the autonomous loop deferred because they need your call.
-## Server-side GLB → PNG render (true OG-card path)
-
-**Status:** deferred — shipped the client-side capture + upload alternative instead (see `src/voice/avatar-snapshot.js` and PROGRESS.md item 4).
-
-**Why deferred:** a real headless GLB renderer needs one of:
-- `puppeteer-core` + `@sparticuz/chromium-min` — adds ~60 MB to every Vercel function bundle and ~1–2s of cold-start. Best ergonomics, worst footprint.
-- `gl` + `@napi-rs/canvas` + custom three.js bootstrap — leaner but needs native build (libGL, libX11) that Vercel's runtime doesn't ship.
-- Render via Cloudflare Workers using their `Browser Rendering` beta — needs a Workers plan + a separate deployment.
-
-Picking one is a deployment-cost decision (function size, latency, $$) that I shouldn't make autonomously. The current client-side path makes thumbnails work on the customizer save — once you decide on a server-renderer, the new endpoint can replace `presign-thumbnail` + `auto-tag` for crawl-time OG generation without changing any of the client wiring.
-
-**Recommendation:** `puppeteer-core` + `@sparticuz/chromium-min` is the lowest-friction path if the function-size hit is acceptable. The chromium binary is downloaded once at deploy time, not on every cold start.
-
-## meshoptimizer / draco3d peer deps
-
-The compression pass in `bake.js` uses `weld + quantize + textureCompress`. Adding `meshoptimizer` and `draco3d` (`npm i meshoptimizer draco3d`) would unlock the more aggressive `meshopt()` and `draco()` transforms — typically 2–3× further reduction on top of what we already get. ~5 MB combined dep cost.
+_No open items._
diff --git a/docs/internal/PROGRESS.md b/docs/internal/PROGRESS.md
index a2bebae81..4cfda2a44 100644
--- a/docs/internal/PROGRESS.md
+++ b/docs/internal/PROGRESS.md
@@ -26,10 +26,16 @@ Rails:
**Build:** `npx vite build` → ✓ 20.29s, no new warnings.
**Caveats:**
-- `meshoptimizer` and `draco3d` peer deps are NOT installed, so the more aggressive `meshopt()` and `draco()` transforms are not in the pipeline. Adding them is `npm i meshoptimizer draco3d` (~5 MB combined) — left to the user since it's a dep decision.
-- Compression-vs-baseline size delta isn't unit-tested. Could add a regression test against a fixed GLB if size becomes flaky.
+- Compression-vs-baseline size delta isn't unit-tested. `scripts/measure-bake-size.mjs` runs the diff on demand. Could add a regression test against a fixed GLB if size becomes flaky.
- `textureCompress` converts everything to WebP. Every browser model-viewer ships in supports WebP natively, but pre-r136 three.js loaders won't — three.ws ships current three so this is safe.
+**Follow-up — meshopt() added on top of the baseline pipeline:**
+`meshoptimizer` is now installed; `meshopt({ encoder, level: 'medium' })` runs between `quantize()` and `textureCompress()` in the same try/fallback. Browser-side, every viewer that loads baked GLBs (`marketplace-lobby`, `voice/talk-scene` and therefore `avatar-edit`) calls `getMeshoptDecoder()` from `src/viewer/internal.js` and wires it on the GLTFLoader. The main `viewer.js` already wires it via the full `getDecoders()`. Measured deltas on top of the baseline (`scripts/measure-bake-size.mjs`):
+- `public/avatars/default.glb`: 1.95 MB → 737 KB (**63% smaller** on top of baseline; 2.74 MB source → 737 KB end-to-end ≈ 3.7×).
+- `public/avatars/cz.glb`: 766 KB → 556 KB (**27% smaller** on top of baseline). Smaller meshes get less from meshopt; the full-body avatar is the realistic case.
+
+`draco3d` was uninstalled — `npm ls draco3d` showed only the direct dep with nothing referencing it (`api/avatar/optimize.js` declares the `KHRDracoMeshCompression` extension on primitives but never registers the encoder via `io.registerDependencies`, so that codepath would fail at write time regardless of whether `draco3d` is installed). `draco()` is **not** wired into the bake pipeline because EXT_meshopt decodes faster in the browser at avatar scale.
+
## Item 2 — ARKit blendshape vocabulary + cross-format resolver ✅
@@ -90,3 +96,28 @@ Rails:
- `preserveDrawingBuffer: true` carries a small perf cost. Acceptable at avatar scale; would be wrong at fullscreen-game scale.
- Auto-tag uses `ANTHROPIC_API_KEY`. If unset on the server, the auto-tag call returns `{ ok: false, reason: 'vision_api_error' }` and the thumbnail is still written by the next call. Manual `PATCH /api/avatars/:id { thumbnail_key }` would also work as a fallback.
- Server-side rendering for OG crawl-time generation is deferred (see NEXT.md).
+
+## Item 5 — Server-side GLB → PNG renderer for OG cards ✅
+
+**What:** Headless-chromium renderer that turns any avatar's GLB into a 1200×630 PNG at crawl time, with R2 caching + DB write-back so the chromium cost is paid once per avatar. `api/_lib/render-glb.js` exports `renderGlbToPng({ glbUrl, width, height, background })`; `api/avatar-og.js` now serves (a) the cached thumbnail if present, (b) a freshly-rendered PNG if not, (c) the site logo at `/assets/og-image.png` only if the GLB is too large or rendering fails. Replaces the prior SVG fallback for accounts/avatars that never opened the customizer.
+
+**Why this completes the OG flow:** The Item-4 client-side capture only fires when the user opens the customizer + saves. Avatars created via API, by other users, or that pre-date customizer-save shipping had no `thumbnail_key`, so OG crawlers landed on the SVG card. Twitter/Slack/Discord renders that card fine, but the GLB itself is the actual content — the server renderer makes the OG preview faithful to what the user gets in-app, with no client interaction required.
+
+**Files touched:**
+- `api/_lib/render-glb.js` — new module. Bundles a tiny inlined HTML viewer that loads three.js + GLTFLoader from `unpkg.com/[email protected]/...`, renders one frame at the target resolution with deterministic three-light rig + auto-framed camera, signals `window.__renderDone = true`, then `page.screenshot({ type: 'png', clip })`. Caches the puppeteer Browser per warm container to amortize launch cost.
+- `api/avatar-og.js` — wired the renderer in: thumbnail-cache check first (302 redirect), then GLB size precheck (HEAD, 10 MB cap), then `renderGlbToPng()`, then `putObject({ key: '<storage_key>_og.png' })`, then `UPDATE avatars SET thumbnail_key` guarded by `WHERE thumbnail_key IS NULL` so a concurrent customizer-save snapshot isn't clobbered. Per-avatar in-memory `Promise` lock (Map) so two simultaneous crawls share one render. Any failure → 302 to `/assets/og-image.png` (the real site logo, per CLAUDE.md rule on no placeholder data).
+- `api/_lib/env.js` — `CHROMIUM_PACK_URL` getter for overriding the chromium-min binary download URL when upgrading the package.
+- `vercel.json` — `api/avatar-og.js` function config bumped to `maxDuration: 30`, `memory: 2048` (chromium needs RAM; render budget is 15s + overhead).
+- `package.json` — added `puppeteer-core@^25.0.4` and `@sparticuz/chromium-min@^148.0.0` to runtime dependencies.
+
+**Tests added:**
+- `tests/render-glb.test.js` — input-validation suite (always runs) + headful render path gated on `RUN_HEADFUL_TESTS=1` that generates a triangle GLB via `@gltf-transform/core`, serves it from a localhost HTTP server, calls the real renderer, and asserts the returned buffer starts with the PNG magic header. Skipped in CI because chromium download is large.
+- `tests/api/avatar-og.test.js` — 11 tests with `renderGlbToPng` stubbed at the module boundary: cached-thumbnail redirect, 404 paths, demo SVG, private-avatar SVG fallback, full server-render path (with R2 + DB write-back assertions), GLB-too-large precheck, render-error fallback to the brand logo, in-memory concurrency lock (verifies two simultaneous crawls share one render), forwarded-host handling for the fallback redirect.
+
+**Tests:** `npx vitest run tests/api/avatar-og.test.js tests/render-glb.test.js tests/api/all-modules-load.test.js` → 257 passed, 1 skipped (headful test). Existing unrelated failures (branding, email templates, validate visibility default) are pre-existing on `main`.
+
+**Caveats:**
+- The chromium binary (`@sparticuz/chromium-min`) is downloaded from GitHub at first cold start in each Vercel container and cached in `/tmp`. The default URL in `render-glb.js` points at the v148.0.0 Sparticuz release that matches the npm version pinned in `package.json`. When bumping the npm package, also bump `DEFAULT_CHROMIUM_PACK` (or set `CHROMIUM_PACK_URL` in env) — otherwise puppeteer.launch() will fail to find the matching binary.
+- three.js is loaded into the viewer page from `unpkg.com/[email protected]/build/three.module.js` via importmap. If the in-app three.js version bumps, also bump `THREE_VERSION` in `render-glb.js` so the server-rendered preview stays faithful to what the customizer shows.
+- The in-memory render lock is per-lambda-container. Two Vercel containers seeing the same first-crawl request will each render once, then both write `thumbnail_key`. The `WHERE thumbnail_key IS NULL` guard makes the second write a no-op; the redundant R2 object is overwritten in place. Acceptable redundancy for the cold-start case.
+- Private avatars (visibility=`private`) have no public `model_url`, so the renderer is skipped and the SVG card is served instead — the public OG endpoint never holds a presigned URL.
diff --git a/docs/persona-hub.md b/docs/persona-hub.md
index b3550d988..43e251226 100644
--- a/docs/persona-hub.md
+++ b/docs/persona-hub.md
@@ -1,8 +1,10 @@
# Persona Hub
-Persona Hub is three.ws's cross-app sign-in: a user creates and stores their three.ws avatar once, then any site that embeds the `<three-ws-signin>` widget can ask the user to share that avatar in a single click. The user's three.ws session never leaves three.ws; the tenant receives only a short-lived JWT bearing the avatar URL.
+## Overview
-This is the architectural answer to "what Ready Player Me's Hub was, before it was acquired" — same pattern (one avatar, hundreds of sites), redesigned around three.ws's auth stack.
+Persona Hub is three.ws's cross-app sign-in: a user creates and stores their three.ws avatar once, then any tenant site embedding the `<three-ws-signin>` widget can request a short-lived JWT that bears the user's avatar URL. three.ws itself **issues** the token — from a popup served on `three.ws`, against the user's session cookie — and tenants **verify** it server-side, either offline against the published JWKS (when the deployment is running in ES256 mode) or by calling the public `/api/auth/persona/verify` endpoint. ES256 is the preferred algorithm because the public key is published at [/.well-known/jwks.json](https://three.ws/.well-known/jwks.json) and tenants can verify without a network round-trip.
+
+The architectural analogue is Ready Player Me's Hub before its acquisition — one avatar, many sites — redesigned around three.ws's own auth stack.
---
@@ -36,7 +38,7 @@ This is the architectural answer to "what Ready Player Me's Hub was, before it w
│ ◄────────────── { sub, avatar, exp } │
```
-The cookie carrying the user's three.ws session is `__Host-sid` — locked to the exact host. The popup runs on three.ws so the consent screen can read it; the tenant never sees it. Cross-site avatar sharing happens entirely via the postMessage-delivered JWT.
+The cookie carrying the user's three.ws session is `__Host-sid` — locked to the exact host. The popup runs on `three.ws` so the consent screen can read it; the tenant never sees it. Cross-site avatar sharing happens entirely via the postMessage-delivered JWT.
---
@@ -67,8 +69,6 @@ el.addEventListener('three-ws:cancelled', () => {
### Programmatic API
-If you don't want a custom element, use the promise wrapper:
-
```js
const result = await window.ThreeWsPersona.signIn({
clientOrigin: 'https://coolgame.three.ws',
@@ -78,88 +78,307 @@ const result = await window.ThreeWsPersona.signIn({
---
-## Allowed tenant origins
+## Key generation
-`/api/auth/persona/issue` accepts these origins for `tenant_origin`:
+Run [scripts/generate-persona-key.mjs](../scripts/generate-persona-key.mjs) once per deployment to produce an ES256 (P-256) keypair:
-- `https://three.ws`
-- `https://<anything>.three.ws`
-- `http://localhost[:port]` and `http://127.0.0.1[:port]` (dev only)
+```bash
+node scripts/generate-persona-key.mjs
+# or pin a custom key id:
+node scripts/generate-persona-key.mjs --kid=persona-2026-05
+```
-Other origins return `400 invalid_request`. This is the chokepoint that prevents arbitrary sites from minting tokens claiming any user's three.ws avatar. Add subdomains by updating `validateTenantOrigin()` in [api/auth/persona/[action].js](../api/auth/persona/%5Baction%5D.js).
+The script writes nothing to disk. It prints a copy-pasteable block to stdout:
----
+```
+PERSONA_JWKS_KID=persona-2026-05-20
+PERSONA_JWKS_PRIVATE_KEY_PEM="-----BEGIN PRIVATE KEY-----\nMIGH…\n-----END PRIVATE KEY-----"
+# Optional — derived from private key if omitted:
+# PERSONA_JWKS_PUBLIC_KEY_PEM="-----BEGIN PUBLIC KEY-----\nMFkw…\n-----END PUBLIC KEY-----"
+```
-## Verifying tokens server-side
+followed by the public JWK that `/.well-known/jwks.json` will publish once the env vars take effect. Three env vars are involved:
-Tenants verify the token from their backend:
+| Variable | Required | Purpose |
+|---|---|---|
+| `PERSONA_JWKS_PRIVATE_KEY_PEM` | yes (to enable ES256) | PKCS8 PEM with `\n` escaped. The server signs persona tokens with this key. Without it, the server falls back to HS256. |
+| `PERSONA_JWKS_KID` | no (defaults to `persona-es256-1`) | Key id published in the JWK and embedded in the JWT header so tenants can pick the right key after rotation. |
+| `PERSONA_JWKS_PUBLIC_KEY_PEM` | no | SPKI PEM. If omitted, the public JWK is derived from the private key at runtime. Set this only if you want to publish a different public key (rare). |
-```js
-const res = await fetch(
- `https://three.ws/api/auth/persona/verify?token=${encodeURIComponent(token)}&audience=${encodeURIComponent('https://coolgame.three.ws')}`,
-);
-const claims = await res.json();
-if (!res.ok) throw new Error(claims.error_description);
+Paste the block into the deployment's environment (Vercel project settings, `.env.local` for dev), redeploy, and confirm the new key is live with:
-// claims.sub — three.ws user id (stable across sessions)
-// claims.aud — must match the tenant origin you embedded with
-// claims.avatar — { id, url, thumbnail_url, name }
-// claims.scope — "persona:read avatar:read"
-// claims.exp — Unix timestamp
+```bash
+curl https://three.ws/.well-known/jwks.json
```
-### Two signing modes
+The response should contain one entry under `keys` whose `kid` matches `PERSONA_JWKS_KID`. The private key must never leave the server — it is the sole signer for every persona token issued by this deployment.
-| Mode | Algorithm | When | Verification |
-|---|---|---|---|
-| **ES256** (preferred) | EC P-256 asymmetric | `PERSONA_JWKS_PRIVATE_KEY_PEM` env var set | Offline via [JWKS endpoint](https://three.ws/.well-known/jwks.json), or `/verify` |
-| **HS256** (fallback) | HMAC-SHA256 with `JWT_SECRET` | No persona keypair configured | Must hit `/verify` — secret can't be published |
+---
+
+## Issuing a token
+
+`POST /api/auth/persona/issue` — defined in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js) (`handleIssue`).
+
+| | |
+|---|---|
+| Method | `POST` |
+| Auth | three.ws session: a valid `__Host-sid` cookie sent with `credentials: 'include'` |
+| Body | `{ "tenant_origin": "<https origin>", "avatar_id"?: "<uuid>" }` |
+| Success | `200` with `{ token, expires_in, avatar, tenant_origin, alg }` |
+| Errors | `401 unauthorized` — no session. `400 invalid_request` — `tenant_origin` is not a `three.ws` subdomain or `localhost`. `404 no_avatar` — user has no avatar yet. |
-Generate an ES256 keypair with:
+`tenant_origin` must be a bare origin (no path, no query, no fragment), `https://*.three.ws` or `https://three.ws`, or — for dev — `http://localhost[:port]` / `http://127.0.0.1[:port]`. Anything else is rejected with `400 invalid_request`. The validator is `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js); add a subdomain by editing that function.
+
+When `avatar_id` is omitted, the user's most recently created avatar is used. Pass `avatar_id` from the consent UI's picker to bind a specific avatar to the token.
+
+### curl
+
+The endpoint requires a real session, so this only succeeds when the caller is signed in to `three.ws` (the cookie value below is illustrative — copy yours from the browser's devtools after signing in):
```bash
-node scripts/generate-persona-key.mjs
+curl -sS -X POST https://three.ws/api/auth/persona/issue \
+ -H 'content-type: application/json' \
+ -H 'cookie: __Host-sid=<your session cookie value>' \
+ --data '{"tenant_origin":"https://coolgame.three.ws"}'
+```
+
+Without a session you get `401 unauthorized`:
+
+```json
+{ "error": "unauthorized", "error_description": "sign in to three.ws first" }
+```
+
+A successful response looks like:
+
+```json
+{
+ "token": "eyJhbGciOiJIUzI1NiIsImtpZCI6ImsxIiwidHlwIjoiSldUIn0…",
+ "expires_in": 86400,
+ "avatar": {
+ "id": "a-1",
+ "name": "My Avatar",
+ "url": "https://cdn.three.ws/u/<user>/avatar.glb",
+ "thumbnail_url": "https://cdn.three.ws/u/<user>/avatar.png"
+ },
+ "tenant_origin": "https://coolgame.three.ws",
+ "alg": "ES256"
+}
+```
+
+`alg` reflects the signing mode this deployment is currently in (`ES256` when a persona keypair is configured, `HS256` otherwise — see [ES256 vs HS256 fallback](#es256-vs-hs256-fallback)).
+
+### fetch (from the consent popup)
+
+```js
+const res = await fetch('/api/auth/persona/issue', {
+ method: 'POST',
+ credentials: 'include', // sends __Host-sid
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ tenant_origin: 'https://coolgame.three.ws',
+ avatar_id: 'a-1', // optional — defaults to newest
+ }),
+});
+if (!res.ok) {
+ const { error, error_description } = await res.json();
+ throw new Error(`${error}: ${error_description}`);
+}
+const { token, avatar, expires_in, alg } = await res.json();
+```
+
+### Decoded JWT claims
+
+The base64url payload of the issued token decodes to:
+
+```json
+{
+ "scope": "persona:read avatar:read",
+ "token_use": "persona",
+ "avatar": {
+ "id": "a-1",
+ "name": "My Avatar",
+ "url": "https://cdn.three.ws/u/<user>/avatar.glb",
+ "thumbnail_url": "https://cdn.three.ws/u/<user>/avatar.png"
+ },
+ "iss": "https://three.ws",
+ "sub": "<three.ws user id>",
+ "aud": "https://coolgame.three.ws",
+ "iat": 1747699200,
+ "exp": 1747785600,
+ "jti": "<16-byte random hex>"
+}
+```
+
+Header:
+
+```json
+{ "alg": "ES256", "kid": "persona-2026-05-20", "typ": "JWT" }
```
-then paste the output into Vercel env. The verify endpoint accepts both algorithms during rotation so tokens minted before key install keep working until they expire.
+`alg` is `ES256` in ES mode and `HS256` in fallback. `kid` is `PERSONA_JWKS_KID` in ES mode and `JWT_KID` (defaults to `k1`) in fallback. Both modes set the same payload claims — the only thing that changes is how the signature is produced and verified.
+
+---
+
+## Verifying a token (tenant side)
+
+A persona token must always be verified before the tenant trusts any claim on it. There are two paths:
-### Offline verification (ES256 only)
+1. **Offline against the JWKS** (`ES256` only). The tenant fetches [https://three.ws/.well-known/jwks.json](https://three.ws/.well-known/jwks.json) once, caches it, and verifies the signature locally.
+2. **Online against the verify endpoint** (works for both `ES256` and `HS256`). The tenant calls `GET /api/auth/persona/verify?token=…&audience=…` and trusts the response.
+
+Use path 1 in production when ES256 is active — it's free, cache-friendly, and doesn't depend on three.ws being reachable on the verify path. Use path 2 as a universal fallback.
+
+### Node.js (offline, JWKS) — recommended
```js
import { jwtVerify, createRemoteJWKSet } from 'jose';
-const JWKS = createRemoteJWKSet(new URL('https://three.ws/.well-known/jwks.json'));
+// createRemoteJWKSet fetches the JWKS once and caches it in memory.
+// The cache invalidates on `kid` miss so key rotation is automatic.
+const JWKS = createRemoteJWKSet(
+ new URL('https://three.ws/.well-known/jwks.json'),
+);
+
+export async function verifyPersonaToken(token, tenantOrigin) {
+ const { payload } = await jwtVerify(token, JWKS, {
+ issuer: 'https://three.ws',
+ audience: tenantOrigin, // must match what you embedded with
+ algorithms: ['ES256'],
+ });
+ // payload.sub — three.ws user id (stable across sessions)
+ // payload.avatar — { id, name, url, thumbnail_url }
+ // payload.scope — "persona:read avatar:read"
+ // payload.exp — unix timestamp
+ return payload;
+}
+```
-const { payload } = await jwtVerify(token, JWKS, {
- issuer: 'https://three.ws',
- audience: 'https://coolgame.three.ws',
- algorithms: ['ES256'],
-});
-// payload.sub, payload.avatar, etc.
+Install `jose` (`npm install jose`) — that's the only dependency. The JWKS handle is reusable across requests; do not construct a new one per call.
+
+### Browser (offline, JWKS via ESM CDN)
+
+```html
+<script type="module">
+ import { jwtVerify, createRemoteJWKSet } from 'https://esm.sh/jose@5';
+
+ const JWKS = createRemoteJWKSet(
+ new URL('https://three.ws/.well-known/jwks.json'),
+ );
+
+ async function verify(token, tenantOrigin) {
+ const { payload } = await jwtVerify(token, JWKS, {
+ issuer: 'https://three.ws',
+ audience: tenantOrigin,
+ algorithms: ['ES256'],
+ });
+ return payload;
+ }
+
+ // example wiring against the widget
+ document.querySelector('three-ws-signin')
+ .addEventListener('three-ws:authorized', async (e) => {
+ const claims = await verify(e.detail.token, 'https://coolgame.three.ws');
+ console.log('signed in as', claims.sub, claims.avatar);
+ });
+</script>
+```
+
+If you bundle (Vite / webpack / esbuild), drop the CDN URL and import from `jose` directly — same API. Browser-side verification is only safe for UI hints — anything privileged on the tenant must still re-verify on the tenant's server. The browser cannot keep an audience binding honest if the calling page is compromised.
+
+### Online verify (works for ES256 *and* HS256)
+
+```js
+const url = new URL('https://three.ws/api/auth/persona/verify');
+url.searchParams.set('token', token);
+url.searchParams.set('audience', 'https://coolgame.three.ws');
+const res = await fetch(url);
+if (!res.ok) {
+ const { error, error_description } = await res.json();
+ throw new Error(`${error}: ${error_description}`);
+}
+const claims = await res.json();
+// claims: { ok, sub, aud, scope, exp, avatar }
+```
+
+The verify endpoint applies the same checks as `jose.jwtVerify` — signature, issuer (`https://three.ws`), audience match, expiry — and additionally rejects tokens whose `token_use` claim is not `"persona"`.
+
+---
+
+## ES256 vs HS256 fallback
+
+The signing algorithm is decided at issue time by [api/auth/persona/\[action\].js:158-161](../api/auth/persona/%5Baction%5D.js):
+
+```js
+const es = await esKeys(); // null if PERSONA_JWKS_PRIVATE_KEY_PEM is unset
+const alg = es ? 'ES256' : 'HS256';
+const kid = es ? es.kid : env.JWT_KID;
+const signingKey = es ? es.privateKey : hsKey();
```
+- **ES256 (preferred).** Active when `PERSONA_JWKS_PRIVATE_KEY_PEM` is set. The server signs with the EC P-256 private key; the public key is published at `/.well-known/jwks.json` so tenants verify offline.
+- **HS256 (fallback).** Active when `PERSONA_JWKS_PRIVATE_KEY_PEM` is **unset**. The server signs with the `JWT_SECRET` HMAC secret. `/.well-known/jwks.json` returns `{"keys": []}` and includes a diagnostic header `x-three-ws-status: no PERSONA_JWKS_PRIVATE_KEY_PEM configured; persona tokens are HS256, verify via /api/auth/persona/verify`.
+
+Verification accepts both algorithms in either order — the `/verify` endpoint tries ES256 first and falls back to HS256 — so tokens minted just before a key rollover keep working until they expire. The `alg` field in the issue response tells the client which mode was used; tenants do not need to branch on it (the offline path simply requires `ES256`).
+
+**What tenants should do in an HS256 deployment.** Skip JWKS entirely — the HMAC secret cannot be published, so offline verification is impossible. Always call `GET /api/auth/persona/verify?token=…&audience=…` from your server. If a tenant's runtime requires offline verification (e.g. an edge worker that must not call out to three.ws on the hot path), file an issue against the deployment owner to install a persona keypair before launch.
+
+---
+
+## Tokens in practice
+
+- **TTL.** 24 hours (`PERSONA_TTL_SEC = 60 * 60 * 24`, [api/auth/persona/\[action\].js:42](../api/auth/persona/%5Baction%5D.js#L42)). Tenants that need a longer-lived session must mint their own session from the persona token's `sub` after verifying — do not extend the persona JWT itself.
+- **Rotation.** Generate a new keypair with `node scripts/generate-persona-key.mjs`, deploy with a new `PERSONA_JWKS_KID`, and the JWKS publishes the new key. Old tokens continue to verify against `/api/auth/persona/verify` while they live; once the longest possible token TTL has elapsed (24h), no token in the wild still references the old `kid`. The deployment can serve both old and new keys side by side by adding extra entries to the `keys` array — the current handler emits a single key but the verifier accepts any matching `kid` from the published set.
+- **Revocation.** There is **no** revocation list. Defense is the short TTL: 24 hours. If a token must be invalidated sooner, the tenant should treat its own server-issued session as the source of truth and invalidate that. If a private key is leaked, rotate `PERSONA_JWKS_PRIVATE_KEY_PEM` and `PERSONA_JWKS_KID`; verification of any token signed with the old key will fail as soon as the old JWK is removed from the published set.
+
+---
+
+## Troubleshooting
+
+| Symptom | What to check |
+|---|---|
+| `jwks_uri unreachable` (browser console / fetch failure) | Confirm `https://three.ws/.well-known/jwks.json` returns `200`. If it returns `{"keys":[]}` *and* the response carries `x-three-ws-status: …HS256…`, the deployment is in HS256 fallback — offline verification cannot work, switch to the `/api/auth/persona/verify` path. |
+| `JWKSNoMatchingKey` / `kid not found` | The token was signed with a key the JWKS no longer publishes (key was rotated and the old entry removed). Either redeploy with the old key added back to the published set, or have the user re-authorize so a fresh token is minted under the current `kid`. |
+| `alg mismatch` from `jwtVerify` | The token's `alg` header doesn't match `algorithms: ['ES256']`. If the issue response returned `alg: "HS256"`, the deployment is in fallback — call `/api/auth/persona/verify` instead. Never pass `algorithms: ['HS256']` to a remote-JWKS verifier; HS256 is symmetric and the secret cannot be published. |
+| `JWTClaimValidationFailed: "aud" claim check failed` | The `audience` you passed to `jwtVerify` (or to `/verify`) doesn't match the token's `aud`. Audience is the exact `tenant_origin` used at issue time — case-sensitive, no trailing slash. |
+| `JWTExpired: "exp" claim timestamp check failed` | Token is older than 24 h. Have the user re-authorize through the widget. There is no refresh endpoint — persona tokens are not refreshable by design. |
+| `invalid_token: token is not a persona token` from `/verify` | The token validates cryptographically but its `token_use` claim is not `"persona"`. Tokens issued by the main three.ws auth stack are not accepted on this endpoint. |
+| `400 invalid_request` on `/issue` with `tenant_origin must be a https three.ws subdomain or localhost dev origin` | The origin contains a path / query / fragment, is not `https`, or is not a `three.ws` subdomain. Pass a bare origin like `https://coolgame.three.ws`. Add a new subdomain by editing `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js). |
+
+---
+
+## Allowed tenant origins
+
+`/api/auth/persona/issue` accepts these origins for `tenant_origin`:
+
+- `https://three.ws`
+- `https://<anything>.three.ws`
+- `http://localhost[:port]` and `http://127.0.0.1[:port]` (dev only)
+
+Other origins return `400 invalid_request`. This is the chokepoint that prevents arbitrary sites from minting tokens claiming any user's three.ws avatar.
+
---
## Endpoint reference
-| Endpoint | Auth | Description |
-|---|---|---|
-| `GET /api/auth/persona/me` | three.ws session | Lists the user's avatars for the consent UI. |
-| `POST /api/auth/persona/issue` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
-| `GET /api/auth/persona/verify?token=&audience=` | none | Verifies a token's signature, issuer, audience, expiry. |
+| Endpoint | Method | Auth | Description |
+|---|---|---|---|
+| [/api/auth/persona/me](../api/auth/persona/%5Baction%5D.js) | `GET` | three.ws session | Lists the user's avatars for the consent UI. |
+| [/api/auth/persona/issue](../api/auth/persona/%5Baction%5D.js) | `POST` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
+| [/api/auth/persona/verify](../api/auth/persona/%5Baction%5D.js) | `GET` | none | Verifies a token's signature, issuer, audience, expiry, and `token_use`. |
+| [/.well-known/jwks.json](https://three.ws/.well-known/jwks.json) | `GET` | none | Publishes the active persona public key (empty array in HS256 fallback). |
JWT claims:
| Claim | Value |
|---|---|
-| `iss` | `https://three.ws` |
+| `iss` | `https://three.ws` (the deployment's `PUBLIC_APP_ORIGIN`) |
| `sub` | three.ws user id |
-| `aud` | tenant origin (validated against the issued audience) |
+| `aud` | tenant origin (validated against the issued audience on verify) |
| `scope` | `persona:read avatar:read` |
| `token_use` | `persona` |
-| `avatar` | `{ id, url, thumbnail_url, name }` |
+| `avatar` | `{ id, name, url, thumbnail_url }` |
| `iat` / `exp` | issued at / expires at (24h TTL) |
-| `jti` | unique token id |
+| `jti` | unique token id (16 random bytes) |
---
diff --git a/package-lock.json b/package-lock.json
index 61e2618c0..6bfba7957 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -60,6 +60,7 @@
"@solana/wallet-adapter-phantom": "^0.9.24",
"@solana/wallet-adapter-wallets": "^0.19.32",
"@solana/web3.js": "latest",
+ "@sparticuz/chromium-min": "^148.0.0",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
"@vercel/og": "^0.11.1",
@@ -75,7 +76,6 @@
"bs58": "^6.0.0",
"colyseus.js": "^0.16.22",
"dat.gui": "^0.7.9",
- "draco3d": "^1.5.7",
"elevenlabs": "^1.59.0",
"ethers": "^6.16.0",
"express": "^4.22.1",
@@ -89,6 +89,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.2",
"node-fetch": "^3.3.2",
+ "puppeteer-core": "^25.0.4",
"qrcode": "^1.5.4",
"query-string": "^8.1.0",
"qwen-ai-provider": "^0.1.1",
@@ -21533,6 +21534,18 @@
"uuid": "dist/bin/uuid"
}
},
+ "node_modules/@sparticuz/chromium-min": {
+ "version": "148.0.0",
+ "resolved": "https://registry.npmjs.org/@sparticuz/chromium-min/-/chromium-min-148.0.0.tgz",
+ "integrity": "sha512-3RW2gPJrOIutXdTtwLDuIFOZwKKq4YU2zwt73U75QmgYaDVSYfSC1xLksou71sAy1B/MgZhLSmU+wCZDLW4MFg==",
+ "license": "MIT",
+ "dependencies": {
+ "tar-fs": "^3.1.2"
+ },
+ "engines": {
+ "node": ">=22.17.0"
+ }
+ },
"node_modules/@speed-highlight/core": {
"version": "1.2.15",
"resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.15.tgz",
@@ -32092,12 +32105,6 @@
"node": ">=10"
}
},
- "node_modules/draco3d": {
- "version": "1.5.7",
- "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",
- "integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==",
- "license": "Apache-2.0"
- },
"node_modules/draggabilly": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/draggabilly/-/draggabilly-3.0.0.tgz",
@@ -45953,21 +45960,82 @@
}
},
"node_modules/puppeteer-core": {
- "version": "24.42.0",
- "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.42.0.tgz",
- "integrity": "sha512-T4zXokk/izH01fYPhyyev1A4piWiOKrYq7CUFpdoYQxmOnXoV6YjUabmfIjCYkNspSoAXIxRid3Tw+Vg0fthYg==",
+ "version": "25.0.4",
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.0.4.tgz",
+ "integrity": "sha512-K1LQKDP6w1rIr1jUyN9obH16TO/DCy86k3q+FBd2prGY+TStxhFySxmaZZuRF+0D3BJXjwCYFke7tMHCH4olTA==",
"license": "Apache-2.0",
"dependencies": {
- "@puppeteer/browsers": "2.13.0",
- "chromium-bidi": "14.0.0",
+ "@puppeteer/browsers": "3.0.3",
+ "chromium-bidi": "16.0.1",
"debug": "^4.4.3",
- "devtools-protocol": "0.0.1595872",
- "typed-query-selector": "^2.12.1",
+ "devtools-protocol": "0.0.1608973",
+ "typed-query-selector": "^2.12.2",
"webdriver-bidi-protocol": "0.4.1",
- "ws": "^8.19.0"
+ "ws": "^8.20.0"
},
"engines": {
- "node": ">=18"
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/puppeteer-core/node_modules/@puppeteer/browsers": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.0.3.tgz",
+ "integrity": "sha512-v3YaiGpzUTgOZkHBFR0iZg58Vto25SqBQxfLUXDiofJccwVl6Mlr7BdLCS1NZgxikdeIHf936cxYWL9IZp3tow==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "progress": "^2.0.3",
+ "semver": "^7.7.4",
+ "tar-fs": "^3.1.1",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "browsers": "lib/main-cli.js"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ },
+ "peerDependencies": {
+ "proxy-agent": ">=8.0.1"
+ },
+ "peerDependenciesMeta": {
+ "proxy-agent": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/puppeteer-core/node_modules/chromium-bidi": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-16.0.1.tgz",
+ "integrity": "sha512-J63PGu/9PpeCwLIcKYyzWP6yaVL5pxuBc0shlYCYM8BaAkmlwiQboXO1iNbOgSDbVklEyYFfNEcHD8oOAWacUA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "mitt": "^3.0.1",
+ "zod": "^3.24.1"
+ },
+ "engines": {
+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "devtools-protocol": "*"
+ }
+ },
+ "node_modules/puppeteer-core/node_modules/devtools-protocol": {
+ "version": "0.0.1608973",
+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1608973.tgz",
+ "integrity": "sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/puppeteer-core/node_modules/semver": {
+ "version": "7.8.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
+ "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
}
},
"node_modules/puppeteer-extra": {
@@ -46120,6 +46188,24 @@
}
}
},
+ "node_modules/puppeteer/node_modules/puppeteer-core": {
+ "version": "24.42.0",
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.42.0.tgz",
+ "integrity": "sha512-T4zXokk/izH01fYPhyyev1A4piWiOKrYq7CUFpdoYQxmOnXoV6YjUabmfIjCYkNspSoAXIxRid3Tw+Vg0fthYg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@puppeteer/browsers": "2.13.0",
+ "chromium-bidi": "14.0.0",
+ "debug": "^4.4.3",
+ "devtools-protocol": "0.0.1595872",
+ "typed-query-selector": "^2.12.1",
+ "webdriver-bidi-protocol": "0.4.1",
+ "ws": "^8.19.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/pure-rand": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-7.0.1.tgz",
diff --git a/package.json b/package.json
index e4254342c..713815b41 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
"build:news": "node scripts/build-news.mjs",
"prebuild": "node scripts/build-news.mjs && node scripts/build-page-index.mjs",
"build": "vite build",
+ "build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore",
"build:animations": "node scripts/build-animations.mjs",
"build:artifact-viewer": "node scripts/build-artifact-viewer.mjs",
"build:lib": "TARGET=lib vite build",
@@ -132,6 +133,7 @@
"@solana/wallet-adapter-phantom": "^0.9.24",
"@solana/wallet-adapter-wallets": "^0.19.32",
"@solana/web3.js": "latest",
+ "@sparticuz/chromium-min": "^148.0.0",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
"@vercel/og": "^0.11.1",
@@ -147,7 +149,6 @@
"bs58": "^6.0.0",
"colyseus.js": "^0.16.22",
"dat.gui": "^0.7.9",
- "draco3d": "^1.5.7",
"elevenlabs": "^1.59.0",
"ethers": "^6.16.0",
"express": "^4.22.1",
@@ -161,6 +162,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.2",
"node-fetch": "^3.3.2",
+ "puppeteer-core": "^25.0.4",
"qrcode": "^1.5.4",
"query-string": "^8.1.0",
"qwen-ai-provider": "^0.1.1",
diff --git a/pages/pose.html b/pages/pose.html
new file mode 100644
index 000000000..80a5dd60d
--- /dev/null
+++ b/pages/pose.html
@@ -0,0 +1,566 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Pose Studio · three.ws</title>
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
+ />
+ <meta name="author" content="nirholas" />
+ <meta
+ name="description"
+ content="Free 3D pose-reference studio. Click body parts to pose them, pick from preset poses, add floor props, export PNG."
+ />
+ <meta name="theme-color" content="#0b0b10" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Pose Studio · three.ws" />
+ <meta
+ property="og:description"
+ content="Free 3D pose-reference studio. Click body parts to pose them, pick from preset poses, export PNG."
+ />
+ <meta property="og:url" content="https://three.ws/pose" />
+
+ <style>
+ :root {
+ --bg: #07070b;
+ --panel: rgba(17, 17, 22, 0.78);
+ --panel-solid: #14141a;
+ --border: rgba(255, 255, 255, 0.08);
+ --border-strong: rgba(255, 255, 255, 0.16);
+ --text: #fafafa;
+ --text-2: #a1a1aa;
+ --text-3: #71717a;
+ --accent: #a78bfa;
+ --accent-2: #7dd3fc;
+ --danger: #f87171;
+ --ok: #34d399;
+ }
+ html, body {
+ margin: 0;
+ padding: 0;
+ width: 100%;
+ height: 100%;
+ background: var(--bg);
+ color: var(--text);
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ overflow: hidden;
+ }
+
+ #pose-app {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ grid-template-columns: 280px 1fr 320px;
+ grid-template-rows: 52px 1fr;
+ grid-template-areas:
+ "top top top"
+ "left stage right";
+ gap: 0;
+ }
+
+ /* ── Top bar ─────────────────────────────────────────── */
+ #pose-top {
+ grid-area: top;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 14px;
+ border-bottom: 1px solid var(--border);
+ background: rgba(7, 7, 11, 0.85);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ z-index: 10;
+ }
+ #pose-top .brand {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-weight: 600;
+ font-size: 14px;
+ letter-spacing: 0.01em;
+ color: var(--text);
+ }
+ #pose-top .brand a {
+ color: var(--text-2);
+ text-decoration: none;
+ font-weight: 500;
+ font-size: 13px;
+ }
+ #pose-top .brand a:hover { color: var(--text); }
+ #pose-top .sep {
+ width: 1px;
+ height: 22px;
+ background: var(--border);
+ margin: 0 4px;
+ }
+ .mode-group {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ }
+ .mode-btn {
+ appearance: none;
+ border: none;
+ background: transparent;
+ color: var(--text-2);
+ font: inherit;
+ font-size: 12.5px;
+ padding: 5px 11px;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.12s ease, color 0.12s ease;
+ }
+ .mode-btn:hover { color: var(--text); }
+ .mode-btn[aria-pressed="true"] {
+ background: rgba(167, 139, 250, 0.18);
+ color: #e9d5ff;
+ }
+ .spacer { flex: 1; }
+ .pose-btn {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ font: inherit;
+ font-size: 12.5px;
+ font-weight: 500;
+ padding: 6px 12px;
+ border-radius: 999px;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ transition: background 0.12s ease, border-color 0.12s ease;
+ }
+ .pose-btn:hover {
+ background: rgba(255, 255, 255, 0.08);
+ border-color: var(--border-strong);
+ }
+ .pose-btn-primary {
+ background: rgba(167, 139, 250, 0.22);
+ border-color: rgba(167, 139, 250, 0.45);
+ color: #ede9fe;
+ }
+ .pose-btn-primary:hover { background: rgba(167, 139, 250, 0.32); }
+ .pose-btn-ghost {
+ background: transparent;
+ border-style: dashed;
+ color: var(--text-2);
+ width: 100%;
+ justify-content: center;
+ margin-top: 8px;
+ }
+
+ .file-label {
+ cursor: pointer;
+ }
+ .file-label input[type="file"] {
+ display: none;
+ }
+
+ /* ── Left panel: joint picker + controls ──────────────── */
+ #pose-left {
+ grid-area: left;
+ border-right: 1px solid var(--border);
+ background: var(--panel-solid);
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ }
+ .pose-section {
+ border-bottom: 1px solid var(--border);
+ padding: 14px;
+ }
+ .pose-section h2 {
+ margin: 0 0 10px 0;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-3);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ }
+ .pose-section h3 {
+ margin: 6px 0;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-2);
+ }
+ #pose-selection-label {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--accent);
+ margin-bottom: 10px;
+ }
+ .pose-hint {
+ color: var(--text-3);
+ font-size: 12px;
+ line-height: 1.5;
+ margin: 4px 0;
+ }
+ .pose-joint-group {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-3);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ margin-top: 12px;
+ margin-bottom: 6px;
+ }
+ .pose-joint-group:first-child { margin-top: 0; }
+ .pose-joint-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+ }
+ .pose-joint-btn {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.02);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 11.5px;
+ padding: 6px 8px;
+ border-radius: 8px;
+ cursor: pointer;
+ text-align: left;
+ transition: background 0.1s ease, color 0.1s ease, border-color 0.1s ease;
+ }
+ .pose-joint-btn:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--text);
+ border-color: var(--border-strong);
+ }
+
+ .pose-slider-row {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .pose-slider-row label {
+ font-size: 12px;
+ color: var(--text-2);
+ grid-column: 1;
+ }
+ .pose-slider-value {
+ grid-column: 2;
+ font-size: 11.5px;
+ color: var(--text-3);
+ font-variant-numeric: tabular-nums;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ .pose-slider-row input[type="range"] {
+ grid-column: 1 / -1;
+ width: 100%;
+ margin: 0;
+ appearance: none;
+ background: transparent;
+ }
+ .pose-slider-row input[type="range"]::-webkit-slider-runnable-track {
+ height: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ }
+ .pose-slider-row input[type="range"]::-webkit-slider-thumb {
+ appearance: none;
+ width: 14px;
+ height: 14px;
+ margin-top: -5px;
+ background: var(--accent);
+ border-radius: 50%;
+ cursor: pointer;
+ box-shadow: 0 0 0 3px rgba(167, 139, 250, 0.18);
+ }
+ .pose-slider-row input[type="range"]::-moz-range-track {
+ height: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ }
+ .pose-slider-row input[type="range"]::-moz-range-thumb {
+ width: 14px;
+ height: 14px;
+ background: var(--accent);
+ border-radius: 50%;
+ border: none;
+ cursor: pointer;
+ }
+
+ .pose-form-row {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 8px;
+ font-size: 12px;
+ color: var(--text-2);
+ }
+ .pose-form-row select,
+ .pose-form-row input[type="color"],
+ .pose-form-row input[type="range"] {
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px 6px;
+ font: inherit;
+ font-size: 12px;
+ }
+ .pose-form-row input[type="color"] {
+ padding: 0;
+ width: 32px;
+ height: 22px;
+ cursor: pointer;
+ }
+ .pose-form-row input[type="checkbox"] {
+ accent-color: var(--accent);
+ }
+
+ /* ── Stage (3D canvas) ─────────────────────────────── */
+ #pose-stage {
+ grid-area: stage;
+ position: relative;
+ background: #0b0b10;
+ overflow: hidden;
+ }
+ #pose-canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ cursor: grab;
+ touch-action: none;
+ }
+ #pose-canvas:active { cursor: grabbing; }
+ #pose-status {
+ position: absolute;
+ left: 50%;
+ bottom: 14px;
+ transform: translateX(-50%);
+ background: rgba(7, 7, 11, 0.86);
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ padding: 6px 14px;
+ font-size: 11.5px;
+ color: var(--text-2);
+ pointer-events: none;
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ transition: opacity 0.2s ease;
+ }
+ #pose-status[data-kind="error"] { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
+
+ /* ── Right panel: presets + props ──────────────────── */
+ #pose-right {
+ grid-area: right;
+ border-left: 1px solid var(--border);
+ background: var(--panel-solid);
+ overflow-y: auto;
+ }
+ .pose-preset-group {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-3);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ margin-top: 14px;
+ margin-bottom: 8px;
+ }
+ .pose-preset-group:first-child { margin-top: 0; }
+ .pose-preset-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+ }
+ .pose-preset-btn {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.02);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ text-align: left;
+ transition: background 0.12s ease, border-color 0.12s ease;
+ }
+ .pose-preset-btn:hover {
+ background: rgba(125, 211, 252, 0.10);
+ border-color: rgba(125, 211, 252, 0.35);
+ }
+ .pose-prop-btn {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.02);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 12px;
+ padding: 6px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background 0.12s ease;
+ }
+ .pose-prop-btn:hover { background: rgba(255, 255, 255, 0.06); color: var(--text); }
+ .pose-prop-btn[aria-pressed="true"] {
+ background: rgba(167, 139, 250, 0.18);
+ border-color: rgba(167, 139, 250, 0.45);
+ color: #ede9fe;
+ }
+ .pose-prop-grid {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+
+ /* ── Responsive ─────────────────────────────────────── */
+ @media (max-width: 1100px) {
+ #pose-app {
+ grid-template-columns: 240px 1fr 260px;
+ }
+ }
+ @media (max-width: 900px) {
+ #pose-app {
+ grid-template-columns: 1fr;
+ grid-template-rows: 52px 1fr auto;
+ grid-template-areas:
+ "top"
+ "stage"
+ "left";
+ }
+ #pose-right { display: none; }
+ #pose-left {
+ border-right: none;
+ border-top: 1px solid var(--border);
+ max-height: 40vh;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <div id="pose-app">
+ <!-- TOP BAR -->
+ <header id="pose-top">
+ <div class="brand">
+ <a href="/" title="three.ws home">three.ws</a>
+ <span>/</span>
+ <span>Pose Studio</span>
+ </div>
+ <span class="sep"></span>
+
+ <div class="mode-group" role="group" aria-label="Drag mode">
+ <button type="button" class="mode-btn" data-mode="bend" aria-pressed="true" title="Bend — drag to flex forwards/back">Bend</button>
+ <button type="button" class="mode-btn" data-mode="tilt" aria-pressed="false" title="Tilt — drag to swing sideways">Tilt</button>
+ <button type="button" class="mode-btn" data-mode="twist" aria-pressed="false" title="Twist — drag to rotate around the limb axis">Twist</button>
+ <button type="button" class="mode-btn" data-mode="move" aria-pressed="false" title="Move — disables drag-to-rotate so you can orbit the camera">Camera</button>
+ </div>
+
+ <span class="spacer"></span>
+
+ <button type="button" id="pose-reset" class="pose-btn" title="Reset the pose to standing">Reset pose</button>
+
+ <label class="pose-btn file-label" title="Load a pose from JSON">
+ Import
+ <input type="file" id="pose-import-json" accept="application/json,.json" />
+ </label>
+ <button type="button" id="pose-export-json" class="pose-btn" title="Save pose as JSON">Export JSON</button>
+ <button type="button" id="pose-screenshot" class="pose-btn pose-btn-primary" title="Download a PNG of the current view">PNG screenshot</button>
+ </header>
+
+ <!-- LEFT PANEL -->
+ <aside id="pose-left">
+ <section class="pose-section">
+ <h2>Selection</h2>
+ <div id="pose-selection-label">Click a body part</div>
+ <div id="pose-controls-host"></div>
+ </section>
+
+ <section class="pose-section">
+ <h2>Joints</h2>
+ <div id="pose-joint-picker"></div>
+ </section>
+
+ <section class="pose-section">
+ <h2>Model</h2>
+ <div class="pose-form-row">
+ <label for="pose-build">Body type</label>
+ <select id="pose-build">
+ <option value="male" selected>Male</option>
+ <option value="female">Female</option>
+ </select>
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-skin">Skin tone</label>
+ <input id="pose-skin" type="color" value="#d4d4d8" />
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-constraints">Biological constraints</label>
+ <input id="pose-constraints" type="checkbox" checked />
+ </div>
+ </section>
+
+ <section class="pose-section">
+ <h2>Camera &amp; environment</h2>
+ <div class="pose-form-row">
+ <label for="pose-bg">Background</label>
+ <input id="pose-bg" type="color" value="#0b0b10" />
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-fov">FOV</label>
+ <input id="pose-fov" type="range" min="20" max="100" step="1" value="45" />
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-grid">Show floor grid</label>
+ <input id="pose-grid" type="checkbox" checked />
+ </div>
+ <h3>Key light</h3>
+ <div class="pose-form-row">
+ <label for="pose-light-azimuth">Direction</label>
+ <input id="pose-light-azimuth" type="range" min="-180" max="180" step="1" value="52" />
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-light-elevation">Height</label>
+ <input id="pose-light-elevation" type="range" min="-10" max="89" step="1" value="55" />
+ </div>
+ <div class="pose-form-row">
+ <label for="pose-light-intensity">Intensity</label>
+ <input id="pose-light-intensity" type="range" min="0" max="3" step="0.05" value="1.4" />
+ </div>
+ </section>
+ </aside>
+
+ <!-- STAGE -->
+ <main id="pose-stage">
+ <canvas id="pose-canvas"></canvas>
+ <div id="pose-status">Loading…</div>
+ </main>
+
+ <!-- RIGHT PANEL -->
+ <aside id="pose-right">
+ <section class="pose-section">
+ <h2>Pose presets</h2>
+ <div id="pose-presets-host"></div>
+ </section>
+ <section class="pose-section">
+ <h2>Floor props</h2>
+ <div class="pose-prop-grid" id="pose-prop-host"></div>
+ </section>
+ </aside>
+ </div>
+
+ <script type="module" src="/src/pose-studio.js"></script>
+ </body>
+</html>
diff --git a/prompts/finish-features/README.md b/prompts/finish-features/README.md
new file mode 100644
index 000000000..94581c9e9
--- /dev/null
+++ b/prompts/finish-features/README.md
@@ -0,0 +1,65 @@
+# Finish-features queue
+
+Each file below is a **fully self-contained prompt**. You can hand any one of
+them to a fresh Claude Code session (or to yourself in a future turn) without
+loading anything else from this directory — they restate all the context they
+need.
+
+**Run any file at any time.** Files do not depend on each other. There is no
+ordering between them.
+
+## Rails every prompt repeats (CLAUDE.md, non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code, no
+ `setTimeout` fake-loading, no fallback sample arrays.
+- Real APIs only: Pump.fun, Solana RPC, OpenAI/Anthropic via worker proxies,
+ Resend, Neon Postgres, R2.
+- Errors handled at boundaries only (network, user input).
+- Done = code wired, dev server confirms feature in a real browser with no
+ console errors, `npm test` green, `git diff` reviewed.
+- Push to **both** `origin` (nirholas/3D-Agent) and `threews` (nirholas/three.ws)
+ only when the user explicitly says push.
+
+## The queue
+
+### From `docs/internal/TODO.md` (curated, agent-doable)
+
+| File | Subagents? | Estimate |
+|---|---|---|
+| [finish-resend-integration.md](finish-resend-integration.md) | Yes — Explore to map callers | medium |
+| [add-healthz-resend-probe.md](add-healthz-resend-probe.md) | No | small |
+| [document-persona-hub.md](document-persona-hub.md) | Yes — Explore to read all persona code | medium |
+| [expand-lipsync-tests.md](expand-lipsync-tests.md) | No | small |
+| [verify-demo-routes.md](verify-demo-routes.md) | No | small |
+| [stale-todo-sweep.md](stale-todo-sweep.md) | Yes — Explore for the grep, recurring task | small |
+
+### Real code TODOs found in `src/` and `api/`
+
+| File | Subagents? | Estimate |
+|---|---|---|
+| [fix-referral-code-uniqueness.md](fix-referral-code-uniqueness.md) | No | small |
+| [implement-pump-swap-inner-ix.md](implement-pump-swap-inner-ix.md) | Yes — Explore for pump-swap SDK + Solana CPI | large |
+| [clarify-speech-provider-errors.md](clarify-speech-provider-errors.md) | No | small |
+| [wasm-vanity-grinder.md](wasm-vanity-grinder.md) | Yes — Explore for Rust crate + wasm-pack | large |
+| [resolve-viewer-light-todo.md](resolve-viewer-light-todo.md) | No | small |
+
+### Decisions deferred in `docs/internal/NEXT.md`
+
+| File | Subagents? | Estimate |
+|---|---|---|
+| [server-side-glb-render.md](server-side-glb-render.md) | Yes — Explore for OG card flow + puppeteer integration | large |
+| [add-mesh-compression-deps.md](add-mesh-compression-deps.md) | No | small |
+
+## What is NOT in this queue and why
+
+- **Abstract base classes** (`src/onchain/adapters/base.js`,
+ `src/onchain/tokens/base.js`): the `throw new Error('not implemented')`
+ calls there are the documented abstract contract that family-specific
+ subclasses override. They are not stubs.
+- **JSON-RPC `-32601 method not found`** in `api/pump-fun-mcp.js` and
+ `workers/pump-fun-mcp/worker.js`: standard JSON-RPC sentinel. Not a stub.
+- **Human-blocked items** (3D-Agent mirror PAT, Resend domain verify,
+ `RESEND_AUDIENCE_ID`, confirm Resend test email delivery): need credentials
+ or dashboard access only the user has. Tracked in
+ `docs/internal/TODO.md` under "Human-blocked".
diff --git a/prompts/finish-features/add-healthz-resend-probe.md b/prompts/finish-features/add-healthz-resend-probe.md
new file mode 100644
index 000000000..84ed00c47
--- /dev/null
+++ b/prompts/finish-features/add-healthz-resend-probe.md
@@ -0,0 +1,148 @@
+# Task: Add Resend probe to `/api/healthz`
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. Backend: Vercel functions in `api/`.
+The existing health endpoint is `api/healthz.js`. It already reports the
+status of the things the app depends on (database, R2, etc.). Email is
+sent through Resend via `api/_lib/email.js`. There is no Resend probe
+yet, so a broken / missing key only surfaces when a user-facing flow
+tries to send.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code, no
+ `setTimeout` fake-loading, no fallback sample arrays.
+- Real APIs only — the probe must hit Resend over the network.
+- Errors handled at boundaries only.
+- Done = `curl /api/healthz` against `npm run dev` returns the new field,
+ `npm test` green, `git diff` reviewed.
+- Push to both remotes only when the user says push.
+
+## Problem
+
+`api/healthz.js` should expose a `resend` field with one of three values:
+
+- `"configured"` — `RESEND_API_KEY` is set and the key is accepted by
+ Resend.
+- `"missing"` — `RESEND_API_KEY` is unset or empty.
+- `"key_invalid"` — `RESEND_API_KEY` is set but Resend rejected it as
+ invalid (HTTP 401 with `restricted_api_key` is treated as **valid**,
+ since send-only keys legitimately can't list domains).
+
+The probe must be cheap and rate-limited — Resend will complain if we
+hammer it. Cache the result for **5 minutes** in module scope.
+
+## What to implement
+
+### Step 1 — read the current endpoint
+
+Open `api/healthz.js`. Note how existing probes (db, r2) are structured.
+Match the same pattern.
+
+### Step 2 — add the Resend probe
+
+Inside the handler (or as a small module-scoped helper above the
+handler):
+
+```js
+// Module-scoped cache: { value, expiresAt }
+let _resendCache = { value: null, expiresAt: 0 };
+
+async function probeResend() {
+ const now = Date.now();
+ if (_resendCache.value && _resendCache.expiresAt > now) {
+ return _resendCache.value;
+ }
+
+ const key = process.env.RESEND_API_KEY;
+ if (!key) {
+ _resendCache = { value: 'missing', expiresAt: now + 5 * 60 * 1000 };
+ return 'missing';
+ }
+
+ let result;
+ try {
+ const r = await fetch('https://api.resend.com/domains', {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${key}` },
+ // 3s upper bound — healthz must stay fast
+ signal: AbortSignal.timeout(3000),
+ });
+ if (r.ok) result = 'configured';
+ else if (r.status === 401) {
+ // Could be a restricted (send-only) key, which is still valid.
+ const body = await r.text().catch(() => '');
+ result = body.includes('restricted_api_key') ? 'configured' : 'key_invalid';
+ } else if (r.status === 403) result = 'configured'; // send-only often returns 403
+ else result = 'key_invalid';
+ } catch {
+ // Network error / timeout — don't fail healthz, report as missing-signal.
+ // Caller treats this conservatively as "unknown" → 'key_invalid'.
+ result = 'key_invalid';
+ }
+
+ _resendCache = { value: result, expiresAt: now + 5 * 60 * 1000 };
+ return result;
+}
+```
+
+Call `probeResend()` inside the handler and include the result under
+the key `resend` in the JSON response. Place it alongside the other
+dependency-status fields.
+
+### Step 3 — add a test
+
+`tests/healthz.test.js` (create if it does not exist). Use `vitest`
+(the repo's test runner — confirm by reading `package.json`). The test
+should:
+
+1. Stub `globalThis.fetch` for the Resend call only (other healthz
+ probes hit the real db; do not mock those — instead skip the test
+ under no-db env, the same way other tests in the repo skip).
+ Override `fetch` with a small function that returns `{ ok: true,
+ status: 200 }` to assert `resend === 'configured'`.
+2. Reset the module-scoped cache between cases. Either re-import with
+ `vi.resetModules()`, or export a `_resetResendCache` helper from
+ `api/healthz.js` for test use. Pick whichever fits the existing
+ pattern in `tests/`.
+3. Cases: `missing`, `configured` (200), `configured` (401 with
+ `restricted_api_key` body), `key_invalid` (401 without it),
+ `key_invalid` (500), `key_invalid` (timeout — reject fetch).
+
+Do **not** call the real Resend API in tests. The probe itself in
+production hits the real API; tests assert the dispatch logic.
+
+### Step 4 — verify in dev
+
+```bash
+npm run dev
+curl http://localhost:3000/api/healthz
+```
+
+Confirm the response includes `resend: "..."`. If `RESEND_API_KEY` is
+set in `.env`, expect `configured`. If unset, expect `missing`.
+
+### Step 5 — run the full suite
+
+```bash
+npm test
+```
+
+## Definition of done
+
+- `api/healthz.js` returns a `resend` field with one of the three
+ documented values.
+- The result is cached for 5 minutes in module scope.
+- `tests/healthz.test.js` covers all five branches without calling the
+ real Resend API.
+- `curl /api/healthz` against `npm run dev` shows the new field.
+- `npm test` is green.
+
+## Constraints
+
+- Do not increase healthz latency beyond ~3 seconds upper bound.
+- Do not log the API key value anywhere.
+- Do not delete or rewrite the existing probes — only add `resend`.
+- Cache TTL is exactly 5 minutes, not configurable via env. Hard-code it.
diff --git a/prompts/finish-features/add-mesh-compression-deps.md b/prompts/finish-features/add-mesh-compression-deps.md
new file mode 100644
index 000000000..575bd5541
--- /dev/null
+++ b/prompts/finish-features/add-mesh-compression-deps.md
@@ -0,0 +1,186 @@
+# Task: Add `meshoptimizer` + `draco3d` to the GLB bake pipeline
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The bake pipeline at
+`api/_lib/bake.js` already runs a `weld + quantize + textureCompress`
+compression pass on every baked avatar GLB (see `docs/internal/
+PROGRESS.md` item 1). That ships an ~5-10× reduction over the
+uncompressed source. The pipeline could do another 2-3× by adding the
+`meshopt()` and `draco()` transforms from `@gltf-transform/functions`
+— but those transforms require the optional peer dependencies
+`meshoptimizer` and `draco3d`, which are not currently installed
+(~5 MB combined).
+
+`docs/internal/NEXT.md` documents the deferred decision.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks. No fake data. No placeholders.
+- Real APIs only — the compression must actually decode in the
+ browser, which means we must verify the in-browser GLTFLoader has
+ the matching decoders wired.
+- Done = baked GLBs are 2-3× smaller than the current baseline, every
+ avatar still renders correctly in the viewer, `npm test` green.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — install the deps
+
+```bash
+npm install meshoptimizer draco3d
+```
+
+These go into runtime `dependencies` because they are used by the
+serverless bake function at request time. (`@gltf-transform/
+functions` is already in `package.json`.)
+
+### Step 2 — wire `meshopt()` and `draco()` into `api/_lib/bake.js`
+
+Read the existing transform chain:
+
+```bash
+cat api/_lib/bake.js | head -200
+```
+
+The current pass (per `docs/internal/PROGRESS.md` item 1):
+
+```js
+await doc.transform(
+ weld(),
+ quantize({ ... }),
+ textureCompress({ encoder: sharp, ... }),
+);
+```
+
+Add the meshopt + draco transforms. Order matters:
+
+```js
+import { MeshoptEncoder } from 'meshoptimizer';
+import draco3d from 'draco3d';
+
+await MeshoptEncoder.ready;
+
+await doc.transform(
+ weld(),
+ quantize({ /* same as before */ }),
+ // EXT_meshopt_compression — fast browser decode, ~2× extra reduction
+ meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
+ textureCompress({ encoder: sharp, ... }),
+);
+```
+
+`draco3d` is for `KHR_draco_mesh_compression`, which yields a bit
+more reduction than meshopt but decodes slower in the browser. **Pick
+one, not both.** Meshopt is the right call for avatars (small, many,
+decoded on page load) — draco is better for large static models.
+
+Use meshopt only. Keep the `draco3d` install for now because gltf-
+transform may transitively require it; but do not add a `draco()`
+transform to the chain. If after install `npm ls draco3d` shows it
+is unused, `npm uninstall draco3d` in the same diff.
+
+### Step 3 — preserve the fallback
+
+The existing pipeline has a try/catch fallback to a minimal
+`unpartition + prune + dedup` chain for pathological inputs. Keep it.
+If the new meshopt pass throws on some weird input, the fallback path
+saves the bake. Do not remove safety nets to chase max compression.
+
+### Step 4 — verify browser decoders are wired
+
+The in-app viewer (`src/viewer/internal.js` or wherever
+`getDecoders()` lives) must register the MeshoptDecoder:
+
+```js
+import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
+gltfLoader.setMeshoptDecoder(MeshoptDecoder);
+```
+
+`docs/internal/PROGRESS.md` notes the main viewer already has this.
+Confirm by reading the file. If the marketplace lobby viewer
+(`src/marketplace-lobby.js`) does **not** have it, add it — otherwise
+meshopt-compressed avatars will fail to load there.
+
+### Step 5 — run the existing tests
+
+```bash
+npm test -- tests/avatar-bake.test.js
+```
+
+These 9 tests assert correctness invariants (morph weights baked,
+accessory parented to bone, hash stability, etc.). They should all
+still pass — meshopt is transparent to those guarantees. If any fail,
+the compression broke a structural invariant; fix the transform
+parameters until they all pass.
+
+### Step 6 — measure size change
+
+`scripts/measure-bake-size.mjs` (create if it does not exist).
+Reads a known avatar from R2 (or `tests/fixtures/`), bakes it once
+**before** the new transforms (via `git stash` of just this change,
+or a copy of the old function), and **after**. Reports both sizes
+and the ratio.
+
+If the after/before ratio is worse than 0.6 (i.e. less than 40%
+reduction), something is wrong — meshopt should yield 30-50%
+reduction on top of the existing pipeline for typical avatars.
+
+If the script existed before this task, just extend it. Do not
+duplicate.
+
+### Step 7 — manual browser smoke
+
+```bash
+npm run dev
+```
+
+Open the avatar customizer, load an existing avatar, Save (triggers
+a re-bake), then reload the page from a clean browser cache and
+confirm:
+
+1. Network tab shows the baked GLB is meaningfully smaller than
+ before.
+2. The avatar renders with no console errors.
+3. Morph targets still work (facial expressions visibly change when
+ the agent-avatar empathy layer activates).
+4. Animations still play.
+
+Also check the marketplace lobby route — that viewer was flagged in
+`docs/internal/PROGRESS.md` as historically lacking decoders. Verify
+it loads meshopt-compressed avatars correctly.
+
+### Step 8 — clean up `docs/internal/NEXT.md`
+
+Remove the "meshoptimizer / draco3d peer deps" section. Add a line
+under `docs/internal/PROGRESS.md` describing the new compression
+ratio measured in Step 6.
+
+## Definition of done
+
+- `meshoptimizer` is in `dependencies`.
+- `draco3d` is in `dependencies` only if something transitively
+ requires it; otherwise uninstalled.
+- `api/_lib/bake.js` applies `meshopt()` after `quantize()` and
+ before `textureCompress()`.
+- The fallback path is preserved.
+- Browser-side decoder is registered in every viewer that loads
+ baked avatars.
+- `tests/avatar-bake.test.js` (all 9 tests) still passes.
+- A measurement script shows 30-50% additional size reduction on a
+ reference avatar.
+- Manual browser smoke confirms no rendering regression.
+- `docs/internal/NEXT.md` no longer lists this as deferred.
+
+## Constraints
+
+- Do not enable `KHR_draco_mesh_compression` (`draco()`) — it decodes
+ slower in the browser and the meshopt path is already a clear win.
+- Do not raise meshopt `level` above `'medium'`. `'high'` increases
+ bake time substantially with marginal extra reduction.
+- Do not change the bake API surface (function signatures, R2 key
+ layout). This is internal pipeline only.
+- If meshopt breaks for a specific avatar, **fix the input** or
+ **tune the transform** — do not silently skip meshopt for that
+ case. A silently-uncompressed GLB is a regression.
diff --git a/prompts/finish-features/clarify-speech-provider-errors.md b/prompts/finish-features/clarify-speech-provider-errors.md
new file mode 100644
index 000000000..e9a4b1623
--- /dev/null
+++ b/prompts/finish-features/clarify-speech-provider-errors.md
@@ -0,0 +1,159 @@
+# Task: Clarify speech-provider error wording in `src/runtime/speech.js`
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The speech runtime is in
+`src/runtime/speech.js`. Around lines 500-513:
+
+```js
+export function createTTS(config = {}) {
+ const provider = config.provider || 'browser';
+ if (provider === 'none') return null;
+ if (provider === 'browser') return new BrowserTTS(config);
+ if (provider === 'elevenlabs') return new ElevenLabsTTS(config);
+ throw new Error(`TTS provider "${provider}" not implemented yet`);
+}
+
+export function createSTT(config = {}) {
+ const provider = config.provider || 'browser';
+ if (provider === 'none') return null;
+ if (provider === 'browser') return new BrowserSTT(config);
+ throw new Error(`STT provider "${provider}" not implemented yet`);
+}
+```
+
+The message `"not implemented yet"` is misleading. It triggers on **any
+unknown provider name** — typos, copy-pasted configs from another
+project, future provider names. The user thinks the system is
+incomplete; in reality their config is wrong.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Real APIs only.
+- Errors handled at boundaries only.
+- Done = error messages are honest, `npm test` green.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — read the current file
+
+```
+src/runtime/speech.js
+```
+
+Confirm the supported providers for TTS and STT. As of today: TTS
+supports `browser`, `elevenlabs`, `none`; STT supports `browser`,
+`none`.
+
+### Step 2 — rewrite the rejection branches
+
+Replace the two trailing `throw new Error(...)` lines with:
+
+```js
+const supportedTTS = ['none', 'browser', 'elevenlabs'];
+const supportedSTT = ['none', 'browser'];
+
+// inside createTTS:
+throw new Error(
+ `Unknown TTS provider "${provider}". Supported: ${supportedTTS.join(', ')}.`
+);
+
+// inside createSTT:
+throw new Error(
+ `Unknown STT provider "${provider}". Supported: ${supportedSTT.join(', ')}.`
+);
+```
+
+Two upgrades over the current wording:
+
+1. "Unknown provider" is honest — these branches fire on typos.
+2. The list of supported providers is shown, so the user can fix
+ their config without grepping the source.
+
+Keep the `supportedTTS` / `supportedSTT` arrays as module-scoped
+constants near the top of the factory functions so they are the single
+source of truth (currently they are encoded twice — once in the `if`
+chain, once implicitly in the error). Refactor the `if` chain to
+iterate the constant if it stays readable:
+
+```js
+const TTS_FACTORIES = {
+ none: () => null,
+ browser: (cfg) => new BrowserTTS(cfg),
+ elevenlabs: (cfg) => new ElevenLabsTTS(cfg),
+};
+
+export function createTTS(config = {}) {
+ const provider = config.provider || 'browser';
+ const factory = TTS_FACTORIES[provider];
+ if (!factory) {
+ throw new Error(
+ `Unknown TTS provider "${provider}". Supported: ${Object.keys(TTS_FACTORIES).join(', ')}.`
+ );
+ }
+ return factory(config);
+}
+```
+
+Apply the same shape to `createSTT`.
+
+### Step 3 — add a test
+
+Either extend an existing `tests/speech*.test.js` or create a small
+one. Cases:
+
+1. `createTTS({ provider: 'browser' })` returns a `BrowserTTS`
+ instance.
+2. `createTTS({ provider: 'elevenlabs' })` returns an
+ `ElevenLabsTTS` instance.
+3. `createTTS({ provider: 'none' })` returns `null`.
+4. `createTTS({ provider: 'azure' })` throws an error whose message
+ contains "Unknown TTS provider" and "browser, elevenlabs".
+5. Symmetric for `createSTT`.
+
+Do not stub `BrowserTTS` / `ElevenLabsTTS` — just assert
+`instanceof`. They have constructors that should run in jsdom; if not,
+read the file and adjust accordingly (the simpler way is to check
+constructor name).
+
+### Step 4 — run the suite
+
+```bash
+npm test
+```
+
+### Step 5 — verify in dev
+
+```bash
+npm run dev
+```
+
+If the user's app has a TTS / STT config UI, ensure it still works.
+Specifically: change the provider to `browser` and confirm voice
+synthesis still happens. Then deliberately set it to `azure` and
+confirm the new error is shown to the user (if there is user-facing
+error surfacing — otherwise check the console).
+
+## Definition of done
+
+- `src/runtime/speech.js` no longer says "not implemented yet" for
+ unknown providers.
+- Error messages now say "Unknown ... provider" and list supported
+ values.
+- The supported-provider list is encoded in a single place per
+ factory.
+- A test covers both the success and the unknown-provider branches.
+- `npm test` is green.
+- Manual smoke in dev confirms no regression.
+
+## Constraints
+
+- Do not add new providers in this task. Adding OpenAI TTS, PlayHT,
+ Deepgram STT, etc. is out of scope — file a follow-up if you want
+ to add them later.
+- Do not change the public function signatures (`createTTS`,
+ `createSTT`).
+- Do not silently swallow unknown providers (returning `null`) — keep
+ the throw so a misconfigured runtime fails loudly.
diff --git a/prompts/finish-features/document-persona-hub.md b/prompts/finish-features/document-persona-hub.md
new file mode 100644
index 000000000..62e1c151a
--- /dev/null
+++ b/prompts/finish-features/document-persona-hub.md
@@ -0,0 +1,130 @@
+# Task: Complete `docs/persona-hub.md`
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The "Persona Hub" is a feature that
+issues short-lived signed identity tokens to tenant applications so they
+can verify which user is making a request without re-implementing auth.
+Pieces involved:
+
+- `scripts/generate-persona-key.mjs` — generates a keypair for ES256
+ signing.
+- `api/auth/persona/issue.js` (or under `api/auth/[action].js`) — issues
+ the persona token after the user authenticates here.
+- `api/auth/persona/verify.js` (or under `api/auth/[action].js`) —
+ verifies a token presented by a tenant.
+- `/.well-known/jwks.json` — publishes the active public keys so tenants
+ can verify offline.
+- HS256 fallback for dev / when no ES256 key is configured.
+
+`docs/persona-hub.md` exists but is partial. This task is **docs only**
+— do not change any code.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Examples in the doc must be **real code that runs** against the
+ shipped endpoints. Test every snippet end-to-end before committing
+ the doc.
+- Done = doc renders cleanly, every snippet has been executed once.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — read the current code (delegate to subagent)
+
+Spawn an **Explore** subagent with this prompt:
+
+> In `/workspaces/three.ws`, find and summarize the Persona Hub
+> implementation. Return:
+>
+> 1. Where `scripts/generate-persona-key.mjs` lives and what it does
+> (output format, env vars set).
+> 2. The exact path + HTTP method of the issue endpoint, request body
+> shape, response body shape, auth requirement.
+> 3. The exact path + HTTP method of the verify endpoint, request body
+> shape, response body shape.
+> 4. The path serving `/.well-known/jwks.json` and the JWK format it
+> publishes.
+> 5. The ES256 → HS256 fallback logic: under which condition does it
+> fall back? Where in the code is that decided?
+> 6. Any rate limits, scopes, or audience claims enforced.
+>
+> Quote file paths with line numbers. Do not modify anything.
+
+### Step 2 — read the current doc
+
+```bash
+cat docs/persona-hub.md
+```
+
+Identify what is already covered vs missing.
+
+### Step 3 — rewrite `docs/persona-hub.md` to cover
+
+The final doc must include, in this order:
+
+1. **Overview** — one paragraph: what Persona Hub is, who issues
+ tokens, who verifies them, what a tenant is, why ES256 (offline
+ verification via JWKS).
+2. **Key generation** — how to run `scripts/generate-persona-key.mjs`,
+ what files / env vars it produces, where the private key must live
+ (Vercel env var name), where the public key is published.
+3. **Issuing a token** — full request/response with a curl example and
+ a fetch example. Include the auth requirement (session cookie?
+ bearer? CSRF?). Show the decoded JWT claims (iss, aud, sub, exp,
+ custom claims).
+4. **Verifying a token (tenant side)** — two complete code examples:
+ - Node.js using `jose` (verify against JWKS). Show the import,
+ the JWKS fetch + cache, and the verify call.
+ - Browser using `jose` from a CDN (or a bundler import). Same
+ shape.
+ Both examples must be runnable as-is once the reader fills in the
+ issuer URL.
+5. **ES256 vs HS256 fallback** — explain exactly when the server falls
+ back to HS256 (e.g. no ES256 private key set), and what tenants
+ should do in that environment (they can't verify offline; they must
+ call the verify endpoint).
+6. **Tokens in practice** — a one-paragraph note on rotation, TTL,
+ revocation (or explicit "no revocation list — short TTL only").
+7. **Troubleshooting** — list of common errors (`jwks_uri unreachable`,
+ `kid not found`, `alg mismatch`, `aud mismatch`, `expired`) with the
+ one-line fix for each.
+
+### Step 4 — verify every snippet
+
+For each code snippet in the doc:
+
+1. Copy it into a scratch file (do not commit the scratch).
+2. Fill in the issuer URL with `http://localhost:3000` (or wherever the
+ local dev server runs).
+3. Run it against `npm run dev`.
+4. Confirm it does what the doc says it does.
+
+If a snippet fails, fix the doc (or the snippet) until it works. Never
+ship a "should work" example you have not executed.
+
+### Step 5 — sanity check links
+
+Every relative link in the doc must resolve to a file that exists.
+Every external link must return 200.
+
+## Definition of done
+
+- `docs/persona-hub.md` covers all seven sections listed above.
+- Every code snippet in the doc has been executed at least once
+ against the local dev server.
+- All links resolve.
+- No code changes (only the doc and possibly a `.gitignore` line if a
+ generated key file path needs ignoring).
+- `git diff` shows only the doc changing.
+
+## Constraints
+
+- Do not add code under `src/` or `api/`. Docs only.
+- Do not include screenshots — keep it text + code.
+- Do not invent endpoint shapes — read the actual handlers via the
+ Explore subagent and quote them.
+- If the Explore subagent reports that an endpoint is missing or
+ broken, stop and report — do not paper over a broken endpoint with
+ doc text.
diff --git a/prompts/finish-features/expand-lipsync-tests.md b/prompts/finish-features/expand-lipsync-tests.md
new file mode 100644
index 000000000..18067ace8
--- /dev/null
+++ b/prompts/finish-features/expand-lipsync-tests.md
@@ -0,0 +1,127 @@
+# Task: Expand lip-sync analyser test coverage
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The lip-sync analyser drives the
+avatar's mouth shapes from an audio stream. Pieces involved:
+
+- `src/lip-sync-analyser.js` — reads `AnalyserNode` FFT bins, computes
+ open/wide/round channel intensities.
+- `src/agent-avatar.js` — consumes the analyser output and applies it
+ to the avatar's mouth morph targets.
+- `tests/agent-avatar-lipsync.test.js` — current test file. New; not
+ exhaustive.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks of the production code under test. Stub only the host
+ environment (Web Audio API), not the analyser itself.
+- No fake data — feed the analyser real PCM samples shaped to exercise
+ each branch.
+- Done = `npm test` green and the new cases visibly exercise the
+ branches they claim to cover.
+- Push to both remotes only when the user says push.
+
+## Problem
+
+The existing test file covers the happy path. The following behaviors
+are likely uncovered and matter in production:
+
+1. **Very short audio** (< 200 ms). The analyser may not have enough
+ samples to settle; output should be defined and bounded, not NaN.
+2. **Silence** (audio playing but all samples ≈ 0). Mouth channels
+ should report ~0, not random noise from the FFT floor.
+3. **Multiple back-to-back utterances**. State from utterance N must
+ not bleed into utterance N+1. Tear-down and re-attach must work.
+4. **Browser without `AnalyserNode`**. Older / restricted browsers
+ (Safari iOS pre-15 lock-screen contexts, some embedded WebViews).
+ The driver should degrade to a no-op without throwing, and the
+ avatar's mouth should sit at rest, not freeze in an odd shape.
+
+## What to implement
+
+### Step 1 — read the existing tests + source
+
+```
+src/lip-sync-analyser.js
+src/agent-avatar.js
+tests/agent-avatar-lipsync.test.js
+```
+
+Note which of the four behaviors above are already tested and which
+are missing. Skip cases that are already covered — do not duplicate.
+
+### Step 2 — add the missing tests
+
+For each uncovered behavior, add one or more tests in
+`tests/agent-avatar-lipsync.test.js`. Use the same setup pattern as
+the existing tests (vitest, jsdom). Where the test needs a fake audio
+source, construct one against the real Web Audio spec:
+
+- For the silence test: an `AnalyserNode` whose `getByteFrequencyData`
+ fills the buffer with zeros. Assert all three mouth channels are
+ ≤ 0.05 (small epsilon for FFT floor).
+- For the short-audio test: drive the analyser for ~5 frames
+ (`requestAnimationFrame` equivalents) and assert outputs are finite
+ numbers in `[0, 1]`.
+- For the back-to-back test: attach analyser A to source A, detach,
+ attach analyser B to source B, assert output reflects only B.
+ Inspect any module-scoped state (smoothing buffers, etc.) and
+ confirm it resets cleanly on detach.
+- For the no-`AnalyserNode` test: temporarily delete `AnalyserNode`
+ from the global (or replace `window.AnalyserNode` with undefined).
+ Construct the driver, drive a frame, assert it returned zeros and
+ did not throw. Restore the global in `afterEach`.
+
+Keep each test focused. One assertion per behavior, plus the
+"doesn't throw" guard.
+
+### Step 3 — run the suite
+
+```bash
+npm test -- tests/agent-avatar-lipsync.test.js
+npm test
+```
+
+Both must be green. The first call confirms your new tests pass in
+isolation; the second confirms nothing else regressed.
+
+### Step 4 — verify in a real browser
+
+```bash
+npm run dev
+```
+
+Open the Talk overlay (the route documented in
+`src/voice/talk-mode.js` — typically `/talk` or similar). Speak one
+utterance, then another. Open devtools, confirm:
+
+- No console errors.
+- The avatar's mouth animates during each utterance.
+- The mouth returns to rest between utterances (not stuck in the
+ shape of the last frame of N when N+1 begins).
+
+If you can test in Safari iOS or a restricted WebView, do so. If you
+cannot (most likely case), say so explicitly in your final summary
+rather than claiming it works there.
+
+## Definition of done
+
+- `tests/agent-avatar-lipsync.test.js` covers all four behaviors that
+ were not already covered.
+- `npm test` is green.
+- Manual verification in `npm run dev` showed no regression for the
+ happy path.
+- The summary explicitly notes which environments were and were not
+ manually tested.
+
+## Constraints
+
+- Do not change `src/lip-sync-analyser.js` or `src/agent-avatar.js`
+ unless the new tests reveal a real bug. If they do, fix it — but
+ call it out clearly in the summary.
+- Do not add a real audio fixture binary to the repo. Generate audio
+ programmatically inside the test (zeros for silence; a sine for
+ signal).
+- If the existing test setup already covers a behavior, **delete that
+ case from this prompt's scope** rather than adding a duplicate.
diff --git a/prompts/finish-features/finish-resend-integration.md b/prompts/finish-features/finish-resend-integration.md
new file mode 100644
index 000000000..d52695831
--- /dev/null
+++ b/prompts/finish-features/finish-resend-integration.md
@@ -0,0 +1,123 @@
+# Task: Audit Resend integration end-to-end
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. Vanilla JS + Vite frontend
+(`npm run dev` → port 3000). Backend: Vercel functions in `api/`, workers in
+`workers/`. Email is sent through Resend via `api/_lib/email.js`. The
+codebase ships email for: auth (signup, password reset), SIWE/SIWS auth flows,
+payments (EVM + Solana), cron jobs, newsletter subscribe.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code, no
+ `setTimeout` fake-loading, no fallback sample arrays.
+- Real APIs only — for tests, use fixture-based assertions against real
+ Resend response shapes, not mocked Resend clients.
+- Errors handled at boundaries only.
+- Done = `npm test` green, `git diff` reviewed.
+- Push to both remotes only when the user says push.
+
+## Problem
+
+`api/_lib/email.js` is the single send path, but call sites have drifted.
+Some risks:
+
+1. `RESEND_API_KEY` is unset in dev and on preview deploys. Every caller
+ must handle that without throwing — return early, no-op, log once.
+2. Template names and argument shapes may have diverged between caller and
+ the helper (a renamed prop silently breaks the rendered HTML).
+3. Some templates may render invalid HTML (unclosed tags, broken URLs,
+ missing alt text) — never noticed because no one inspects the rendered
+ output.
+4. There are no fixture-based unit tests under `tests/email.test.js`.
+
+## What to implement
+
+### Step 1 — map every caller (delegate to subagent)
+
+Spawn an **Explore** subagent with this prompt:
+
+> Find every file in `/workspaces/three.ws` that imports from
+> `api/_lib/email.js` or calls `sendEmail` / `sendTemplate` / similar
+> exports. For each hit, return: file path, line number, the exact call
+> shape (function name + arg keys), and the calling endpoint or job name.
+> Exclude `node_modules`, `dist`, `publish`, `agent-voice-chat/` (vendored),
+> `agent-payments-sdk/` (vendored). Return as a markdown table.
+
+Use the returned table as the audit checklist.
+
+### Step 2 — audit each call site sequentially
+
+For each caller in the table:
+
+1. Read the file. Confirm it handles the no-API-key case **without
+ throwing**. The helper itself should already return early on missing
+ key — the caller should likewise not block the user-facing flow.
+2. Confirm the template name passed to the helper exists in
+ `api/_lib/email.js` (or wherever templates live).
+3. Confirm the argument shape matches what the template expects (no
+ missing keys; no extra keys silently dropped).
+4. Render the template once locally (via a script under `scripts/` if
+ one helps) and visually scan the HTML for: unclosed tags, broken
+ image URLs (must be absolute https), broken action URLs, missing
+ `<title>`, missing plain-text alternative.
+
+Fix any issue you find in place. Do not leave a TODO. Do not stub a
+template.
+
+### Step 3 — write fixture-based unit tests
+
+Create `tests/email.test.js` (or extend it if it exists). For each
+template, write a test that:
+
+1. Calls the template-render function with a realistic argument set.
+2. Asserts the rendered HTML contains the key user-facing strings
+ (subject, action URL, recipient display name).
+3. Asserts the HTML parses as a valid DOM (use `linkedom` or `jsdom`
+ — both are in the repo's deps; check `package.json` before adding).
+4. Asserts that when `RESEND_API_KEY` is unset, the public `sendEmail`
+ export returns the documented "skipped" shape and does not throw.
+
+Do not mock the Resend client itself. Use the helper's documented
+no-key short-circuit behavior to exercise the skipped path. For the
+"would-send" path, assert the payload constructed before the network
+call (the helper should expose this either by returning it under a
+`debug` key in test mode, or via a separate `buildPayload` export — if
+neither exists, add the export rather than mocking fetch).
+
+### Step 4 — run the suite
+
+```bash
+npm test
+```
+
+All existing tests must still pass. New tests must pass.
+
+### Step 5 — summarize what changed
+
+Write to the response: which call sites were broken, how you fixed each
+one, what tests you added. Do not commit unless the user asks.
+
+## Definition of done
+
+- Every call site of `api/_lib/email.js` is documented and audited.
+- Every caller handles missing `RESEND_API_KEY` without throwing.
+- Every template renders valid HTML with the expected user-facing
+ strings.
+- `tests/email.test.js` exists with at least one fixture-based test per
+ template.
+- `npm test` is green.
+- `git diff` shows only intentional changes.
+
+## Constraints
+
+- Do not mock the Resend SDK. Use real payload assertions.
+- Do not add new templates unless an existing caller is broken because
+ the template it references is missing.
+- Do not change the public signature of `sendEmail` unless every caller
+ is updated in the same diff.
+- If you discover that the audit reveals more than ~6 broken call sites,
+ stop and report — the user may want to triage rather than fix all in
+ one pass.
diff --git a/prompts/finish-features/fix-referral-code-uniqueness.md b/prompts/finish-features/fix-referral-code-uniqueness.md
new file mode 100644
index 000000000..e0e00c226
--- /dev/null
+++ b/prompts/finish-features/fix-referral-code-uniqueness.md
@@ -0,0 +1,150 @@
+# Task: Fix referral-code uniqueness race in signup
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The signup handler is in
+`api/auth/[action].js`. Around line 109, after the user is inserted,
+a referral code is generated for the new account:
+
+```js
+// TODO: loop until referral code is unique
+const newReferralCode = generateReferralCode();
+const [user] = await sql`insert into users (... referral_code) values (... ${newReferralCode}) returning ...`;
+```
+
+`generateReferralCode()` returns a short string (likely 6-8 alphanumeric
+chars). The `users.referral_code` column has a unique index — so two
+simultaneous signups can collide and the second one will fail with a
+Postgres unique-violation, returning a confusing 500 to the user.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Real APIs only — the fix must work against the real Postgres unique
+ index, not a sentinel check.
+- Errors handled at boundaries only — the loop is at the boundary
+ (insert), so a try/catch on the unique-violation error code is the
+ right level.
+- Done = the TODO comment is gone, the race is closed, `npm test`
+ green.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — confirm the unique index exists
+
+```bash
+grep -rn "referral_code" /workspaces/three.ws/migrations/
+```
+
+If `users.referral_code` has a unique index, the retry loop is the
+fix. If it does not, **add a migration that creates the unique index**
+first, then add the retry loop. Both pieces ship in the same diff.
+
+A unique partial index is fine if `referral_code` is nullable:
+
+```sql
+CREATE UNIQUE INDEX IF NOT EXISTS users_referral_code_unique
+ ON users (referral_code)
+ WHERE referral_code IS NOT NULL;
+```
+
+### Step 2 — implement the retry loop
+
+Replace the current single-shot generation with a bounded retry. The
+postgres unique-violation `SQLSTATE` is `23505`.
+
+```js
+async function insertUserWithUniqueReferralCode(fields) {
+ const MAX_TRIES = 8;
+ for (let i = 0; i < MAX_TRIES; i += 1) {
+ const code = generateReferralCode();
+ try {
+ const [row] = await sql`
+ insert into users (email, password_hash, display_name, referred_by_id, referral_code)
+ values (${fields.email}, ${fields.passwordHash}, ${fields.displayName}, ${fields.referredById}, ${code})
+ returning id, display_name, plan, created_at, referral_code
+ `;
+ return row;
+ } catch (err) {
+ // Postgres unique-violation
+ if (err && err.code === '23505' && /referral_code/.test(err.message || '')) {
+ continue; // try a new code
+ }
+ throw err;
+ }
+ }
+ throw new Error('referral_code_generation_exhausted');
+}
+```
+
+Use it in place of the existing `const newReferralCode = ...; const
+[user] = await sql\`insert ...\`;` block. Delete the TODO comment.
+
+The `referral_code_generation_exhausted` error should be caught
+upstream in the handler and converted into a 500 with a short message
+— but in practice the probability of 8 consecutive collisions on an
+8-char alphanumeric space (62^8 ≈ 2.18e14) is vanishingly small unless
+`generateReferralCode()` itself is broken.
+
+### Step 3 — confirm `generateReferralCode()` has enough entropy
+
+```bash
+grep -rn "generateReferralCode" /workspaces/three.ws/src /workspaces/three.ws/api
+```
+
+Read the implementation. It must use a CSPRNG (`crypto.randomUUID()`
+substring, or `crypto.getRandomValues()`, or Node's `crypto.
+randomBytes`). It must **not** use `Math.random()`. If it does, fix it
+in the same diff — that is a real bug.
+
+### Step 4 — add a unit test
+
+Create or extend `tests/auth-signup.test.js`. Use vitest. The test:
+
+1. Sets up an in-memory or test-db connection (read other tests in
+ `tests/` to find the pattern used; do not invent a new DB harness).
+2. Inserts a user with a known referral_code.
+3. Stubs `generateReferralCode` to return the same code on the first
+ call and a different code on the second call.
+4. Calls the signup handler.
+5. Asserts the inserted user has the **second** referral_code.
+6. Asserts no error was returned to the client.
+
+If the repo's other tests use Vercel handler harnesses (`node-mocks-
+http` or similar), match that pattern.
+
+### Step 5 — run the suite
+
+```bash
+npm test
+```
+
+### Step 6 — manual smoke
+
+```bash
+npm run dev
+# signup with curl, confirm 201 and a referral_code in the response
+```
+
+Run the curl twice with two different emails; confirm both succeed.
+
+## Definition of done
+
+- The `// TODO: loop until referral code is unique` comment in
+ `api/auth/[action].js` is gone.
+- The collision-retry loop is in place and bounded.
+- `generateReferralCode()` uses a CSPRNG.
+- A test covers the collision path.
+- `npm test` is green.
+- Two consecutive signups via `curl` both return 201.
+
+## Constraints
+
+- Do not raise `MAX_TRIES` above 8. If you find yourself wanting to,
+ the generator's entropy is too low — fix the generator instead.
+- Do not log the referral code at error level. It's user-facing data;
+ keep it out of error logs.
+- Do not change the response shape of the signup endpoint.
+- Do not remove the unique index even if you add the retry loop. The
+ index is the authoritative guard; the retry loop is the UX shield.
diff --git a/prompts/finish-features/implement-pump-swap-inner-ix.md b/prompts/finish-features/implement-pump-swap-inner-ix.md
new file mode 100644
index 000000000..454eee6a6
--- /dev/null
+++ b/prompts/finish-features/implement-pump-swap-inner-ix.md
@@ -0,0 +1,227 @@
+# Task: Implement the pump-swap inner instruction in the buyback cron
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The buyback cron at
+`api/cron/[name].js` (around line 1178) currently runs only the
+**burn** path of the Pump.fun buyback program. The **full-swap** path
+is stubbed:
+
+```js
+const params = {
+ globalBuybackAuthority: payerPk,
+ currencyMint: currency,
+ swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel for skip-swap
+ swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
+ remainingAccounts: [],
+};
+
+if (fullSwap) {
+ // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
+ // keepers should supply this off-chain until tested on devnet.
+}
+
+let ix;
+try {
+ ix = await offline.buybackTrigger(params);
+ // ...
+}
+```
+
+`fullSwap` is a configured boolean per buyback mint. When true, the
+cron is supposed to build a real pump-swap inner instruction
+(buy-on-curve → burn), populate `swapInstructionData` + `remaining-
+Accounts`, then let `offline.buybackTrigger(params)` wrap them into the
+outer buyback CPI. Today it does nothing in the `fullSwap` branch,
+which means buybacks configured for full-swap silently fall back to
+burn-only.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks. The implementation must build a **real** pump-swap ix
+ against the on-chain program, not a placeholder buffer.
+- No fake data. Account lists are derived from real on-chain state
+ (PDA derivations against the actual program).
+- Done = the `TODO(Phase 3.1)` comment is gone, an end-to-end devnet
+ run completes a full-swap buyback successfully, `npm test` green.
+- Push to both remotes only when the user says push.
+- **No on-chain operations against mainnet without explicit user
+ approval.** Devnet only for testing.
+
+## Subagent delegation
+
+This task is big and research-heavy. Spawn subagents in parallel for
+the research phase, then implement sequentially.
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, find every reference to pump-swap and
+> the buyback program. Return:
+>
+> 1. The exact import path and exported surface of `@pump-fun/agent-
+> payments-sdk`. Quote the `buybackTrigger` signature and the
+> expected shapes of `swapInstructionData` and `remainingAccounts`.
+> 2. Every existing builder for a pump-swap or pump-fun program ix
+> in the repo (likely under `solana-agent-sdk/`, `sdk/`, or
+> `agent-payments-sdk/`). Quote the function names and signatures.
+> 3. Any existing devnet test or script that exercises a full-swap
+> buyback. Even partial / disabled tests count — quote the path.
+> 4. The `PUMP_PROGRAM_ID` value (mainnet vs devnet) and any other
+> program-ID constants used by the swap path.
+
+### Subagent B (Explore)
+
+> In `/workspaces/three.ws`, find the schema for the `pump_buyback_
+> mints` table (or whatever the buyback config table is named).
+> Return:
+>
+> 1. The column list, especially anything indicating `fullSwap`,
+> pool/curve identity, slippage tolerance, max-buy-amount, and
+> devnet-vs-mainnet flag.
+> 2. Every place where `fullSwap` is read or written, including the
+> admin UI that toggles it.
+
+### Subagent C (Plan)
+
+> Given the pump-swap program's published ix surface (research it
+> via the SDK source under `agent-payments-sdk/` and any pump-fun
+> docs), produce a step-by-step plan for building a buy-on-curve
+> inner ix that fits into `offline.buybackTrigger`'s
+> `swapInstructionData` + `remainingAccounts` slots. Specifically:
+>
+> 1. Which pump-swap ix (buy? exact-out buy?) we should use.
+> 2. The full account list for that ix (in order, with PDA seeds).
+> 3. The data layout (discriminator + args).
+> 4. How slippage / min-amount-out is encoded.
+> 5. What we need to fetch on-chain before building it (curve PDA
+> state for current price, etc.).
+
+Wait for all three subagents to return before starting Step 1.
+
+## What to implement
+
+### Step 1 — build the inner-ix helper
+
+In `api/cron/[name].js` (or a small new module imported from there,
+e.g. `api/_lib/pump-swap-ix.js`), implement:
+
+```js
+async function buildPumpSwapInnerIx({
+ mint, // base58 string
+ currency, // PublicKey of quote currency (USDC etc.)
+ amountIn, // BigInt or BN — quote-currency in
+ minAmountOut, // BigInt or BN — base-token out floor (slippage guard)
+ cluster, // 'devnet' | 'mainnet-beta'
+}) {
+ // Returns: { data: Buffer, accounts: AccountMeta[] }
+}
+```
+
+The function:
+
+1. Derives the curve PDA for `mint` against the pump-swap program.
+2. Fetches its current state (read-only RPC call) to confirm the curve
+ exists and is in a state that accepts buys.
+3. Builds the buy-on-curve ix data buffer (discriminator + `amount_in`
+ + `min_amount_out` in the wire layout produced by Subagent C).
+4. Builds the `AccountMeta[]` list in program order: payer, curve PDA,
+ base mint, base vault, quote mint, quote vault, fee recipient,
+ program id, token program, system program, rent — adapt to the
+ actual list Subagent C returns.
+5. Returns the raw `data` + `accounts` — **not** a `TransactionInstruction`
+ wrapper, because `buybackTrigger` consumes them via
+ `swapInstructionData` + `remainingAccounts` independently.
+
+### Step 2 — call it from the buyback cron
+
+Replace the empty `if (fullSwap) { ... }` block with:
+
+```js
+if (fullSwap) {
+ const inner = await buildPumpSwapInnerIx({
+ mint: m.mint,
+ currency,
+ amountIn: m.buy_amount_lamports, // or whatever column holds it
+ minAmountOut: m.min_out_lamports,
+ cluster: m.network,
+ });
+ params.swapProgramToInvoke = PUMP_SWAP_PROGRAM_ID; // not PUMP_PROGRAM_ID
+ params.swapInstructionData = inner.data;
+ params.remainingAccounts = inner.accounts;
+}
+```
+
+`PUMP_SWAP_PROGRAM_ID` is exported by `@pump-fun/agent-payments-sdk`
+(confirm via Subagent A). Use the real export — do not hard-code the
+base58 string.
+
+Delete the `TODO(Phase 3.1)` comment.
+
+### Step 3 — slippage / amount columns
+
+If the buyback-config table is missing `buy_amount` / `min_out_lamports`
+columns (Subagent B will tell you), add a migration that introduces
+them. The cron should read them per mint, not hard-code values.
+
+### Step 4 — unit test the builder
+
+`tests/pump-swap-ix.test.js`. Without hitting the chain, assert:
+
+1. `buildPumpSwapInnerIx` produces a `data` buffer whose first bytes
+ are the documented discriminator.
+2. `min_amount_out` is encoded in the documented offset and is exactly
+ the value passed in (little-endian, 8-byte).
+3. `accounts` length matches the program's expected list length, and
+ key accounts (curve PDA, mints) appear at the right index.
+
+For the curve-state fetch, stub the RPC client at the boundary (the
+`Connection` instance), not the builder. Provide a fake account-info
+return value shaped like a real curve account.
+
+### Step 5 — devnet end-to-end run
+
+```bash
+SOLANA_CLUSTER=devnet npm run dev
+# or whatever script invokes the buyback cron locally
+```
+
+Configure a devnet test mint with `full_swap = true`, a tiny
+`buy_amount`, and a high slippage tolerance. Trigger the cron path
+(there should be an admin endpoint or a script under `scripts/` —
+check existing `scripts/` for a buyback runner).
+
+Watch:
+
+- The transaction succeeds on devnet.
+- `pump_buyback_runs` row records `status = 'success'`.
+- A Solana explorer link to the tx shows the inner pump-swap ix
+ executed before the outer burn.
+
+If it fails, debug — do not paper over with a try/catch and a TODO.
+
+### Step 6 — keep the burn-only path working
+
+Run the existing burn-only path (a mint with `full_swap = false`) on
+devnet too. Confirm it still works — your changes must not regress it.
+
+## Definition of done
+
+- The `TODO(Phase 3.1)` comment is gone.
+- `buildPumpSwapInnerIx` exists, is tested, and is called from the
+ cron when `fullSwap` is true.
+- A real devnet full-swap buyback run is recorded as success.
+- A real devnet burn-only buyback run still works.
+- `npm test` is green.
+- The summary includes the devnet tx signatures for both runs so a
+ reviewer can verify on the explorer.
+
+## Constraints
+
+- Devnet only for testing. Do not run against mainnet.
+- Do not hard-code program IDs as base58 strings — import them from
+ `@pump-fun/agent-payments-sdk`.
+- Do not catch the inner-ix builder's errors and silently fall back
+ to burn-only. If `fullSwap` is configured and the inner ix fails,
+ record `status = 'failed'` and surface the error.
+- Do not raise the outer cron timeout to mask a slow RPC. Investigate
+ the slow RPC.
diff --git a/prompts/finish-features/resolve-viewer-light-todo.md b/prompts/finish-features/resolve-viewer-light-todo.md
new file mode 100644
index 000000000..6ff484ac0
--- /dev/null
+++ b/prompts/finish-features/resolve-viewer-light-todo.md
@@ -0,0 +1,133 @@
+# Task: Resolve `TODO(#116)` in `src/viewer.js`
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. `src/viewer.js` is the in-app
+GLTF viewer / inspector. At two sites (lines 92 and 1187) there is a
+comment:
+
+```js
+directIntensity: 0.8 * Math.PI, // TODO(#116)
+```
+
+and
+
+```js
+lightFolder.add(this.state, 'directIntensity', 0, 4), // TODO(#116)
+```
+
+`#116` refers to an issue. This file appears to be derived from (or
+inspired by) the KhronosGroup `glTF-Sample-Viewer` — that repo's
+issue #116 is the original tracker for "direct light intensity factor
+of π is non-physical."
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Real APIs only.
+- Done = the TODO comment is either resolved (with a real fix) or
+ explicitly retired (with a one-line doc note explaining the choice),
+ `npm test` green.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — confirm provenance
+
+```bash
+git log --diff-filter=A -- src/viewer.js | head -20
+git log -p src/viewer.js | head -200
+```
+
+Confirm whether this file was vendored from
+`KhronosGroup/glTF-Sample-Viewer` or written in-house. Read the top
+of the file for any attribution comment.
+
+### Step 2 — read the actual issue
+
+If the file is vendored: open
+`https://github.com/KhronosGroup/glTF-Sample-Viewer/issues/116` (or
+the issue tracker the file's upstream uses). Read what the issue is
+actually about. The `0.8 * Math.PI` factor is a known fudge to
+compensate for a missing pre-Lambertian factor — the proper fix is
+to multiply *inside* the lighting math, not at the input, but that
+requires touching shader code.
+
+If the file is in-house: the TODO might be unrelated to upstream. Read
+the surrounding shader / light code to understand what `#116` refers
+to in this codebase's issue tracker (GitHub issues on
+nirholas/three.ws or nirholas/3D-Agent).
+
+### Step 3 — decide one of three outcomes
+
+A. **Implement the fix.** If the upstream issue has a resolved fix
+ (a commit / PR in glTF-Sample-Viewer), port it. The fix typically
+ involves removing the `* Math.PI` from the intensity multiplier
+ and adjusting the shader uniform that consumes it. Validate
+ visually: load `public/avatars/default.glb` (or whatever scene the
+ viewer renders), confirm the lighting is approximately the same
+ brightness, not 3× brighter or darker.
+
+B. **Retire the TODO with a doc note.** If the fix is too invasive
+ for this task and the current behavior matches user expectation,
+ replace the inline `TODO(#116)` with a one-line comment explaining
+ why the magic factor stays:
+
+ ```js
+ // 0.8 * π keeps direct lights visually matched to the Sample-Viewer
+ // reference baseline. Removing the π factor requires a shader-side
+ // adjustment — see KhronosGroup/glTF-Sample-Viewer#116.
+ directIntensity: 0.8 * Math.PI,
+ ```
+
+ This is allowed under CLAUDE.md: the rule forbids `TODO`, not
+ informational comments. A `WHY` comment is fine.
+
+C. **Delete the lights folder feature.** Only if the viewer UI no
+ longer exposes direct-light controls to the user.
+
+Pick the outcome based on what you find in Step 2.
+
+### Step 4 — apply the change
+
+Edit `src/viewer.js` at both line 92 and line 1187. Be consistent —
+either both lines fix the math, or both lines get the doc note.
+
+### Step 5 — verify visually
+
+```bash
+npm run dev
+```
+
+Open the viewer route (typically `/viewer` or `/playground` — confirm
+in `pages/` or `vite.config.js`). Load a known scene. Compare to a
+screenshot of the same scene before your change. The two should look
+visually similar — if not, you went with outcome A and the lighting
+should now match a physical reference, which means it will look a bit
+different. Either way, no console errors, no obviously-wrong shading.
+
+### Step 6 — run the suite
+
+```bash
+npm test
+```
+
+## Definition of done
+
+- Neither `// TODO(#116)` comment remains in `src/viewer.js`.
+- The replacement (real fix, doc note, or removal) is explained in
+ the commit message body.
+- Viewer renders without console errors.
+- `npm test` is green.
+
+## Constraints
+
+- Do not change the public API of `Viewer` (the exported class /
+ function in `src/viewer.js`) unless option C is chosen and the
+ callers are updated in the same diff.
+- Do not silently delete the inline comment without explanation. The
+ comment is load-bearing context for the next reader — replace it
+ with either a real fix or a documented rationale, not nothing.
+- Do not pursue option A if you cannot test the visual outcome in a
+ real browser. Without a visual comparison, you cannot verify the
+ fix is correct — fall back to option B in that case.
diff --git a/prompts/finish-features/server-side-glb-render.md b/prompts/finish-features/server-side-glb-render.md
new file mode 100644
index 000000000..be8636a5a
--- /dev/null
+++ b/prompts/finish-features/server-side-glb-render.md
@@ -0,0 +1,222 @@
+# Task: Server-side GLB → PNG renderer for OG cards
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The avatar thumbnail flow today
+(after the recent `avatar-snapshot` ship documented in
+`docs/internal/PROGRESS.md` item 4):
+
+- Client renders a JPEG snapshot of the current three.js frame
+ (`src/voice/avatar-snapshot.js`) after the customizer Save lands.
+- The snapshot is presigned + uploaded to R2 via
+ `/api/avatars/...` (presign-thumbnail).
+- `/api/avatars/...?action=auto-tag` runs Claude Haiku vision on the
+ snapshot to generate tags + a description.
+- `thumbnail_key` on the avatar row points to the R2 object.
+
+What's missing: **crawl-time OG card generation.** When Twitter,
+Discord, Slack, etc. crawl an avatar's public page, they fetch
+`/api/avatar-og.js?id=...` (or similar). If the avatar has no
+client-uploaded thumbnail yet (the customizer was never saved, or the
+avatar was created via API), the OG endpoint cannot produce a real
+PNG. Today it likely falls back to a generic placeholder.
+
+`docs/internal/NEXT.md` documents the deferred decision and recommends
+`puppeteer-core` + `@sparticuz/chromium-min` as the lowest-friction
+path despite the ~60 MB function bundle hit.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks. No fake data. No placeholders. No fallback sample
+ arrays.
+- Real APIs only — the renderer must actually render the avatar GLB
+ in a real browser engine, not an SVG approximation.
+- Done = a server-side render endpoint returns a real PNG for any
+ avatar; OG crawlers fetching the avatar page see a real preview
+ image; `npm test` green.
+- Push to both remotes only when the user says push.
+
+## Subagent delegation
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, map the existing OG card and thumbnail
+> flow. Return:
+>
+> 1. The path + signature of the avatar OG endpoint (likely
+> `api/avatar-og.js` or `api/a-og.js`). Quote the file.
+> 2. The path + signature of `api/avatars/...?action=auto-tag` and
+> `api/avatars/...?action=presign-thumbnail`.
+> 3. `src/voice/avatar-snapshot.js` — its exported API and where
+> it's called.
+> 4. The avatar page handler that emits OG meta tags (likely
+> `api/avatar-page.js` or `pages/avatar-page.html` + a runtime
+> that injects meta).
+> 5. The R2 / storage path scheme: what key does the client-uploaded
+> thumbnail land at? What key would a server-rendered PNG land at?
+
+### Subagent B (Explore)
+
+> Read `docs/internal/NEXT.md` and quote the section on server-side
+> GLB → PNG render. Then assess feasibility:
+>
+> 1. Current Vercel function size budget for this repo (check
+> `vercel.json`, `package.json` for any `maxDuration` /
+> `regions` / size hints, and any existing large dep).
+> 2. The current cold-start latency of a similarly-sized function
+> in this repo (look at any function that imports puppeteer-core
+> or @sparticuz/chromium today — there may already be one).
+> 3. Whether the function should live under `api/` (Vercel) or in a
+> separate worker. The size budget answer determines this.
+
+Wait for both before starting Step 1.
+
+## What to implement
+
+### Step 1 — install deps
+
+```bash
+npm install puppeteer-core @sparticuz/chromium-min
+```
+
+These go into runtime `dependencies`, not devDependencies — they
+ship with the function.
+
+### Step 2 — build the renderer
+
+Create `api/_lib/render-glb.js` (or co-located under the existing
+`api/_lib/` patterns Subagent A surfaces). Export:
+
+```js
+export async function renderGlbToPng({ glbUrl, width = 1200, height = 630, background = 'transparent' }) {
+ // Launches headless chromium, loads a tiny static viewer HTML page,
+ // posts the glb URL into it, waits for the model to load + first
+ // paint, screenshots the canvas, returns a PNG Buffer.
+}
+```
+
+Implementation:
+
+1. Use `chromium.executablePath` from `@sparticuz/chromium-min`.
+2. Launch `puppeteer-core` with `chromium.args` and
+ `headless: chromium.headless`.
+3. Navigate to a tiny static HTML page bundled into the function.
+ The HTML loads three.js + GLTFLoader + the provided GLB, renders
+ one frame at the target resolution with deterministic camera +
+ lighting, and exposes `window.__renderDone = true` when ready.
+4. `page.waitForFunction('window.__renderDone === true', { timeout:
+ 15_000 })`.
+5. `page.screenshot({ type: 'png', omitBackground: background ===
+ 'transparent', clip: { x: 0, y: 0, width, height } })`.
+6. Close the browser. Return the buffer.
+
+The tiny static HTML page should be **inlined as a string constant**
+in `render-glb.js` so the function bundle does not need a separate
+file. The string can reference three.js from a known CDN
+(`https://unpkg.com/three@0.<ver>/...`) — version must match
+`package.json` so the renderer behaves the same as the in-app viewer.
+
+### Step 3 — wire it into the avatar OG endpoint
+
+In whichever file Subagent A identified as the OG endpoint:
+
+1. Try the client-uploaded thumbnail first. If `thumbnail_key` is
+ set and the R2 object exists, redirect (or stream) the existing
+ PNG/JPEG.
+2. If no thumbnail exists, fall through to the server renderer:
+ - Look up the avatar's GLB URL (the same URL the viewer loads).
+ - Call `renderGlbToPng({ glbUrl, width: 1200, height: 630 })`.
+ - Upload the resulting PNG to R2 under the documented key.
+ - Update `thumbnail_key` on the avatar row.
+ - Stream the PNG back to the crawler with the correct
+ `Content-Type` and cache headers.
+
+Subsequent crawls of the same avatar should hit the cached thumbnail
+in R2 — the server render is amortized.
+
+### Step 4 — concurrency + budget guards
+
+Cold-start latency for chromium is real. Guard against:
+
+1. Concurrent renders for the same avatar: use a simple in-memory
+ lock (Map of `avatarId → Promise`) so two simultaneous crawls do
+ not both spin up chromium. The second one awaits the first.
+2. Function timeout: set `maxDuration: 30` in `vercel.json` for this
+ endpoint (or whatever the platform's max allows). Render budget
+ is 15s + 5s overhead.
+3. Bytes returned: if the GLB itself is >10 MB, the renderer will
+ be slow and may OOM. Add a size precheck — head request the GLB
+ URL, abort with a fallback placeholder if Content-Length > 10 MB.
+ The placeholder is the **generic site logo**, not a synthetic
+ "no preview" SVG.
+
+### Step 5 — manual end-to-end test
+
+```bash
+npm run dev
+```
+
+(Note: `puppeteer-core` + `@sparticuz/chromium-min` are designed for
+Vercel runtime; on local dev the chromium binary download from
+`@sparticuz/chromium-min` is a one-time blob.)
+
+1. Pick an avatar that has no `thumbnail_key` yet (or set
+ `thumbnail_key = null` on a test row in dev).
+2. `curl -o /tmp/og.png 'http://localhost:3000/api/avatar-og.js?id=
+ <id>'`
+3. Open `/tmp/og.png` — confirm it shows the avatar, not a
+ placeholder.
+4. Curl again, confirm the second call is faster (cached path).
+5. Check Twitter's card validator / a meta-tag inspector against the
+ public avatar page URL once deployed.
+
+### Step 6 — tests
+
+`tests/render-glb.test.js`. The full render path needs a real
+chromium and a real GLB, which makes it slow and CI-unfriendly. Two
+test layers:
+
+1. Unit: assert that `renderGlbToPng({ glbUrl: '...' })` returns a
+ Buffer whose first 8 bytes are the PNG magic
+ (`\x89PNG\r\n\x1a\n`). Use a tiny test GLB committed under
+ `tests/fixtures/` (or generate one programmatically). Skip the
+ test under CI by checking an env var (e.g. `process.env.CI &&
+ !process.env.RUN_HEADFUL_TESTS`); document the skip.
+2. Integration with the OG endpoint: stub `renderGlbToPng` at the
+ module boundary (since the unit test exercises the real path).
+ Assert the endpoint reads `thumbnail_key`, falls through correctly,
+ uploads to R2, updates the row.
+
+### Step 7 — clean up `docs/internal/NEXT.md`
+
+Remove the "deferred — server-side GLB → PNG render" section. Add a
+line under PROGRESS.md (item N+1) describing what was implemented.
+
+## Definition of done
+
+- `api/_lib/render-glb.js` exists and renders real GLB files to real
+ PNGs via headless chromium.
+- The avatar OG endpoint serves: (a) the client thumbnail if
+ present, (b) a freshly-rendered PNG if not, (c) a real fallback
+ image (site logo) only if the GLB is too large.
+- Subsequent OG crawls hit the cached R2 object.
+- `npm test` is green (with the headful test appropriately skipped
+ in CI).
+- A real social-media-card debugger shows the rendered preview for
+ the avatar's public page.
+- `docs/internal/NEXT.md` no longer lists this as a deferred decision.
+
+## Constraints
+
+- Do not bundle `puppeteer` (full). Only `puppeteer-core` +
+ `@sparticuz/chromium-min`. The full puppeteer ships a chromium
+ download — incompatible with Vercel.
+- Do not call this renderer on every request. Always check the R2
+ cache first.
+- Do not use a sentinel PNG (single-color or "no preview" SVG) as
+ the fallback. CLAUDE.md forbids placeholder data — either render
+ the avatar, or serve the real site logo, full stop.
+- Do not lock the function for >20s waiting for a render. If it
+ times out, return the fallback and surface the timeout in logs
+ (not as an error to the crawler — a 200 with the logo is better
+ than a 500).
diff --git a/prompts/finish-features/stale-todo-sweep.md b/prompts/finish-features/stale-todo-sweep.md
new file mode 100644
index 000000000..9ae19b49d
--- /dev/null
+++ b/prompts/finish-features/stale-todo-sweep.md
@@ -0,0 +1,134 @@
+# Task: Stale-TODO sweep (recurring)
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. CLAUDE.md forbids `TODO`,
+`// implement later`, stub functions, and `throw new Error("not
+implemented")` in shipped code. This sweep is a **recurring task** —
+run it whenever the prompt is loaded, even if a previous run cleaned
+the repo.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code, no
+ `setTimeout` fake-loading, no fallback sample arrays.
+- Real APIs only.
+- Done = every grep hit is either resolved or explicitly classified
+ as legitimate (abstract base, JSON-RPC sentinel, vendored code).
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — delegate the grep to a subagent
+
+Spawn an **Explore** subagent with this prompt:
+
+> In `/workspaces/three.ws`, grep these directories only:
+>
+> - `src/`
+> - `api/`
+> - `workers/`
+> - `pages/`
+> - `services/`
+> - `tasks/` (excluding the markdown task files)
+> - `scripts/`
+>
+> Skip: `node_modules/`, `dist/`, `publish/`, `agent-voice-chat/`,
+> `agent-payments-sdk/`, `agent-protocol-sdk/`, `agent-voice-chat/`,
+> `solana-agent-sdk/`, `sdk/`, `avatar-sdk/`, `chat-plugin/`,
+> `multiplayer/`, `experiments/`, `scratch/`, `examples/`, all
+> `*.test.js` / `*.spec.js` files, and `docs/`.
+>
+> Find every match for these patterns in `.js`, `.ts`, `.mjs`,
+> `.cjs`, `.jsx`, `.tsx`, `.html`, `.css`:
+>
+> - `\bTODO\b`
+> - `\bFIXME\b`
+> - `\bXXX\b`
+> - `\bHACK\b`
+> - `implement later`
+> - `not implemented`
+> - `throw new Error\((['"])(not implemented|unimplemented|todo|stub)`
+>
+> Also find every match for these patterns in the same scope:
+>
+> - `const fake[A-Z]` (fake-data arrays)
+> - `const sample[A-Z][a-z]+` (sample-data arrays)
+> - `setTimeout\([^)]+,\s*\d+\).*//.*(fake|simulate|placeholder)`
+>
+> Return a markdown table: `file:line | pattern | one-line context`.
+
+### Step 2 — classify each hit
+
+For each row in the table, classify into exactly one of:
+
+- **real-unfinished** — a feature or fix that was started and stopped.
+ Must be implemented now.
+- **abstract-base** — `throw new Error('not implemented')` inside an
+ `@abstract` class whose method is the documented interface for
+ subclasses. Legitimate. Skip.
+- **jsonrpc-sentinel** — `throw rpcError(-32601, ...)` for "method
+ not found" in a JSON-RPC handler. Legitimate. Skip.
+- **vendor-tracked** — a TODO referencing an upstream issue number
+ (e.g. `TODO(#116)` in vendored code like the glTF Sample Viewer).
+ Leave the comment; do not implement. Skip with note.
+- **perf-tracked** — a `TODO(perf):` comment for an optimization that
+ is not currently broken (e.g. WASM grinder upgrade). Leave the
+ comment; surface to user. Do not silently delete.
+
+### Step 3 — implement every real-unfinished item
+
+For each `real-unfinished` hit:
+
+1. Read the file and surrounding context.
+2. Implement the missing behavior with real wires per CLAUDE.md.
+3. Delete the comment / replace the throw with the implementation.
+4. Add a test if the file under `tests/` has a sibling for this
+ module — extend it. Do not create a brand-new test file just for
+ the comment removal unless the behavior change is non-trivial.
+
+If a `real-unfinished` item is genuinely out of scope (depends on
+infra you cannot touch, or needs credentials only the user has),
+stop and surface it. Do not delete the comment to silence the lint.
+
+### Step 4 — run the suite
+
+```bash
+npm test
+npx vite build
+```
+
+Both must succeed.
+
+### Step 5 — write a summary
+
+Return a markdown summary with:
+
+- A table of every hit, its classification, and the action taken.
+- A list of items left as `perf-tracked` so the user sees them.
+- A list of items escalated as out-of-scope (if any).
+
+Do not commit unless the user asks.
+
+## Definition of done
+
+- Every `real-unfinished` hit is implemented or escalated.
+- No `real-unfinished` hit remains in the codebase.
+- `vendor-tracked`, `abstract-base`, `jsonrpc-sentinel`, and
+ `perf-tracked` items remain documented in their inline form.
+- `npm test` and `npx vite build` both succeed.
+- Summary report includes every grep hit and what happened to it.
+
+## Constraints
+
+- Do not delete code to silence the grep. Either finish it or
+ escalate it.
+- Do not add new `TODO` comments to replace the old ones. If
+ something is deferred, escalate it — do not re-encode it.
+- Do not touch vendored code (`agent-voice-chat/`,
+ `agent-payments-sdk/`, etc.) even when matches appear under those
+ trees if a stray grep slipped through.
+- This sweep is recurring. If a previous run already implemented the
+ obvious items, you may find zero `real-unfinished` hits — that is
+ the success state. Report it and stop.
diff --git a/prompts/finish-features/verify-demo-routes.md b/prompts/finish-features/verify-demo-routes.md
new file mode 100644
index 000000000..6c7eccd5b
--- /dev/null
+++ b/prompts/finish-features/verify-demo-routes.md
@@ -0,0 +1,160 @@
+# Task: Verify the demo route reorg + write `docs/demo-routes.md`
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. A recent refactor (commit
+`2071392c refactor(routes): use canonical clean URLs across JS, pages, and api
+redirects`) moved demo routes around:
+
+- `/coin` → `/demo/coin` (legacy URL should redirect, not 404)
+- `/demo/avatar-os/*` added
+- `/demos/*` added (plural index of demos)
+
+Routes are wired in two places:
+
+- `vercel.json` — production redirects/rewrites.
+- `vite.config.js` — dev-server entry points and aliases.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks. The verification must hit the **real** dev server and the
+ **real** redirects, not a simulated router.
+- No fake data — read actual responses from `curl` and inspect them.
+- Done = every route returns a 200 (or the documented redirect to a
+ 200), the new doc exists, `git diff` reviewed.
+- Push to both remotes only when the user says push.
+
+## What to implement
+
+### Step 1 — list every route to test
+
+Read `vercel.json` and `vite.config.js`. Enumerate:
+
+- Every entry under `/demo/*`.
+- Every entry under `/demos/*`.
+- Every redirect whose source contains `coin` (to verify the legacy
+ `/coin` → `/demo/coin` mapping).
+- Every page file under `pages/` whose name starts with `demo-` or
+ contains `coin`.
+
+Build a single markdown table with columns: `route`, `expected status`,
+`expected final URL` (after redirects).
+
+### Step 2 — start the dev server
+
+```bash
+npm run dev
+```
+
+Wait for it to come up (the build banner prints the port — typically
+`http://localhost:3000`). Run subsequent curl commands in another shell
+or with `&`.
+
+### Step 3 — curl each route
+
+For each row in the table:
+
+```bash
+curl -sIL -o /dev/null -w "%{http_code} %{url_effective}\n" http://localhost:3000<route>
+```
+
+`-L` follows redirects. `%{http_code}` is the final status.
+`%{url_effective}` is the final URL after any 30x bounces.
+
+Fill in the actual values in the table.
+
+### Step 4 — for each 200, inspect the rendered HTML
+
+```bash
+curl -sL http://localhost:3000<route> | grep -i -E "<title>|error|404"
+```
+
+Confirm:
+
+- A `<title>` exists and is not the generic Vite placeholder.
+- No "error" or "404" text in the rendered HTML.
+- The page loads its JS bundle (look for a `<script type="module"
+ src=`).
+
+If any of these fail, **fix the underlying route**:
+
+- If `vercel.json` is missing a rewrite, add it. Match the convention
+ of the entries already there.
+- If `vite.config.js` is missing an entry under `build.rollupOptions.
+ input`, add it. Match the convention.
+- Then re-curl until the row passes.
+
+### Step 5 — verify in a real browser
+
+```bash
+# server already running
+```
+
+For each route, open `http://localhost:3000<route>` in a browser.
+Confirm:
+
+- No console errors in devtools.
+- Network tab shows the expected HTML + JS + GLB / asset fetches all
+ succeeding.
+
+The user can see things curl can't — do this step honestly.
+
+### Step 6 — write `docs/demo-routes.md`
+
+Structure:
+
+```markdown
+# Demo routes
+
+The canonical map of every `/demo/*` and `/demos/*` route as of
+<today's date>. Update whenever a route is added, removed, or moved.
+
+## Routes
+
+| Route | Page file | What it does |
+|---|---|---|
+| `/demo/coin` | `pages/pump-coin-page.html` | ... |
+| ... | | |
+
+## Legacy redirects
+
+| Old | New | Configured in |
+|---|---|---|
+| `/coin` | `/demo/coin` | `vercel.json` |
+| ... | | |
+
+## Adding a new demo
+
+1. Create the page under `pages/demo-foo.html`.
+2. Add to `vite.config.js` under `build.rollupOptions.input`.
+3. Add to `vercel.json` rewrites if the URL is not the file name.
+4. Add a row to the table above.
+5. Curl-verify the route returns 200.
+```
+
+Fill in every row from the verified table.
+
+### Step 7 — kill the dev server
+
+```bash
+# Ctrl-C / kill the background pid
+```
+
+## Definition of done
+
+- Every route in the table returns the expected status (200 or
+ documented 30x).
+- Every legacy redirect lands on a 200.
+- `docs/demo-routes.md` exists and reflects the live state.
+- `git diff` shows only intentional changes (the new doc, and any
+ route fixes in `vercel.json` / `vite.config.js`).
+
+## Constraints
+
+- Do not change page content. Only fix routing (`vercel.json`,
+ `vite.config.js`) when a route is broken.
+- If a page file is missing entirely for a route the config tries to
+ serve, do not invent the page. Report and stop — the user may have
+ removed it intentionally.
+- Do not generate the route table by reading config alone. Verify
+ every row with a real curl. Config can lie; HTTP cannot.
diff --git a/prompts/finish-features/wasm-vanity-grinder.md b/prompts/finish-features/wasm-vanity-grinder.md
new file mode 100644
index 000000000..ddd666e1f
--- /dev/null
+++ b/prompts/finish-features/wasm-vanity-grinder.md
@@ -0,0 +1,184 @@
+# Task: WASM-backed vanity-address grinder
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. `src/solana/vanity/grinder.js` is
+a pure-JS Solana keypair vanity grinder — it generates ed25519 keypairs
+in a loop until the public key's base58 representation matches a
+user-supplied prefix. Today it runs ~50-200k keypairs/sec depending on
+device; a WASM build of the same loop typically runs ~10× faster.
+
+A `TODO(perf)` comment at line 138 says:
+
+> TODO(perf): drop in a WASM grinder backed by the toolkit's Rust crate
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Real builds — the WASM must be produced from real Rust source, not
+ copied from a CDN of unverified origin.
+- Done = the TODO comment is gone, a real WASM grinder is wired in
+ with a measurable speedup, `npm test` green.
+- Push to both remotes only when the user says push.
+
+## Subagent delegation
+
+This task crosses Rust + WASM + JS, which is a large surface. Spawn
+subagents for research; implement sequentially.
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, find:
+>
+> 1. The exact API surface of `src/solana/vanity/grinder.js`: every
+> exported function with its signature, return shape, callers.
+> 2. Every caller (likely `src/erc8004/vanity-modal.js` and possibly
+> a Web Worker).
+> 3. Whether the grinder runs in the main thread or a Web Worker
+> today (read the call site).
+> 4. Any existing Rust / WASM build steps in the repo (`Cargo.toml`,
+> `wasm-pack`, `vite.config.js` WASM plugins).
+
+### Subagent B (Explore)
+
+> Survey existing open-source Solana ed25519 vanity grinders that
+> compile to WASM. Specifically:
+>
+> 1. Is there a published npm package (e.g. `@solana/vanity-wasm`,
+> `solana-vanity-wasm`) we can install instead of building our
+> own? If so, quote its API.
+> 2. If we must build our own, identify a small audited Rust crate
+> (e.g. `ed25519-dalek` + `bs58`) that compiles cleanly to WASM
+> with `wasm-pack`.
+> 3. Note any licensing constraints.
+
+Wait for both subagents before deciding the path.
+
+## What to implement
+
+### Path A — published package (preferred if Subagent B finds one)
+
+1. `npm install <package>` (devDependency or dependency depending on
+ whether the grinder is shipped to the browser; it is — so prod
+ dep).
+2. Replace the JS grinding loop in `src/solana/vanity/grinder.js`
+ with a call into the WASM package. Keep the exported function
+ signature identical so callers do not need to change.
+3. Add a `await initWasm()` step at module load if the package
+ requires it.
+4. Skip to **Step 5 — benchmark**.
+
+### Path B — build from Rust source (if no good published package)
+
+1. Create `crates/vanity-grinder/` with:
+ - `Cargo.toml` declaring `crate-type = ["cdylib"]`, dependencies
+ `wasm-bindgen`, `ed25519-dalek`, `bs58`, `getrandom = { version =
+ "*", features = ["js"] }`.
+ - `src/lib.rs` exposing one function:
+ ```rust
+ #[wasm_bindgen]
+ pub fn grind(prefix: &str, batch: u32) -> JsValue { ... }
+ ```
+ Grinds up to `batch` keypairs; returns `null` if no hit, else
+ `{ secretKey: Uint8Array, publicKey: string }`.
+2. Add `wasm-pack` to devDependencies via npm script:
+ ```json
+ "build:wasm": "wasm-pack build crates/vanity-grinder --target web --out-dir ../../src/solana/vanity/wasm"
+ ```
+3. Commit the generated `src/solana/vanity/wasm/` output (`.wasm`,
+ `.js`, `.d.ts`). Add an `.npmrc`-style note in
+ `src/solana/vanity/wasm/README.md` that it is generated from the
+ Rust crate and must not be edited.
+4. Wire the wasm into `grinder.js`:
+ ```js
+ import init, { grind } from './wasm/vanity_grinder.js';
+ let _ready = false;
+ async function ensure() { if (!_ready) { await init(); _ready = true; } }
+ export async function grindKeypair(prefix, opts = {}) {
+ await ensure();
+ const batchSize = opts.batchSize ?? 50_000;
+ while (!opts.signal?.aborted) {
+ const hit = grind(prefix, batchSize);
+ if (hit) return hit;
+ await new Promise((r) => setTimeout(r, 0)); // yield to event loop
+ }
+ throw new Error('aborted');
+ }
+ ```
+ The exact shape depends on Subagent A's findings about the current
+ exported signature — match it.
+
+### Step 5 — benchmark
+
+Run the existing pure-JS grinder once on a known prefix (3 chars,
+e.g. `"abc"`), record the wall-clock time. Then run the WASM grinder
+on the same prefix, record the time. Document both in the PR / commit
+message. Expected speedup is at least 5×; if it is below that, the
+WASM build is not configured right (likely a debug build instead of
+release).
+
+### Step 6 — preserve abort semantics
+
+The current grinder accepts an `AbortSignal` so the modal can cancel
+when the user closes it. Verify your WASM path honors abort within a
+reasonable latency (one batch at most). If the WASM `grind()` call
+blocks for several seconds per batch, lower `batchSize` to keep abort
+latency under 200 ms.
+
+### Step 7 — Web Worker
+
+If Subagent A reports the grinder runs in a Web Worker today (likely),
+keep it in the Worker. WASM works inside Workers — make sure the
+Worker imports the same wasm-bindgen output. Verify the modal's UI
+stays responsive while grinding.
+
+### Step 8 — tests
+
+Extend whatever `tests/` covers `grinder.js`. Cases:
+
+1. Grinding for a known prefix returns a keypair whose public key
+ starts with that prefix.
+2. The secret key, when used to sign a known message and verified
+ against the returned public key, validates.
+3. Aborting via the AbortSignal returns within 200 ms.
+
+Test against the real WASM; do not stub it.
+
+### Step 9 — run the full suite + dev smoke
+
+```bash
+npm test
+npm run dev
+# Open the vanity modal in the UI, grind a 2-char prefix, watch it
+# finish in well under a second. Confirm no console errors.
+```
+
+### Step 10 — clean up
+
+- Delete the `TODO(perf)` comment.
+- If Path B was taken, add a CI step (or a doc note) that
+ `npm run build:wasm` must run after any Rust change. Vite must not
+ silently serve a stale wasm.
+
+## Definition of done
+
+- The `TODO(perf)` comment in `src/solana/vanity/grinder.js` is gone.
+- The grinder uses a real WASM implementation (path A or path B).
+- A benchmark shows at least 5× speedup on a 3-char prefix.
+- Tests pass.
+- Manual UI smoke test confirms no regression in the vanity modal.
+- `git diff` reviewed.
+
+## Constraints
+
+- Do not copy a pre-built `.wasm` from an unverified source. Either
+ install a published npm package or build from Rust source in this
+ repo.
+- Do not freeze the main thread. The grinder must yield (Worker or
+ batched microtasks) so the UI stays responsive.
+- Do not log secret keys at any level. Even in dev.
+- This task is **perf**, not a feature. If the WASM grinder is more
+ trouble than the speedup is worth (Subagent B finds no clean path,
+ Rust toolchain not available, etc.), report and stop — leave the
+ JS grinder in place and convert the `TODO(perf)` comment into a
+ doc note explaining the decision.
diff --git a/public/og-image.png b/public/og-image.png
index 3ed7bc860..3b56ee917 100644
Binary files a/public/og-image.png and b/public/og-image.png differ
diff --git a/scripts/buyback-devnet-smoke.mjs b/scripts/buyback-devnet-smoke.mjs
new file mode 100644
index 000000000..e4b3e0e2b
--- /dev/null
+++ b/scripts/buyback-devnet-smoke.mjs
@@ -0,0 +1,115 @@
+#!/usr/bin/env node
+// Devnet smoke for the pump-swap inner-ix + outer agent_buyback_trigger path.
+//
+// Bypasses the HTTP cron entrypoint and the postgres lookup — drives the same
+// builder + signer path the cron uses, against whatever mint the operator
+// points at. Use after applying migrations/2026-05-20-pump-buyback-fullswap.sql
+// in prod; this script is for one-off devnet verification.
+//
+// Env:
+// PUMP_CRON_RELAYER_SECRET_KEY_B64 base64 of the 64-byte secret-key bytes
+// SOLANA_RPC_URL_DEVNET optional, defaults to api.devnet.solana.com
+// MINT base58 devnet pump.fun mint
+// CURRENCY base58 quote currency mint (e.g. USDC devnet)
+// FULL_SWAP=true|false when true, builds the buy-on-curve inner ix
+// SLIPPAGE_BPS default 500 (5%)
+// DRY_RUN=true build but do not submit
+//
+// Examples:
+// PUMP_CRON_RELAYER_SECRET_KEY_B64=... MINT=<mint> CURRENCY=<usdc-devnet> \
+// FULL_SWAP=true node scripts/buyback-devnet-smoke.mjs
+//
+// ... FULL_SWAP=false node scripts/buyback-devnet-smoke.mjs # burn-only
+
+import { Keypair, Transaction } from '@solana/web3.js';
+
+function need(name) {
+ const v = process.env[name];
+ if (!v) throw new Error(`missing required env: ${name}`);
+ return v;
+}
+
+const network = 'devnet';
+const mintStr = need('MINT');
+const currencyStr = need('CURRENCY');
+const fullSwap = process.env.FULL_SWAP === 'true';
+const slippageBps = Number(process.env.SLIPPAGE_BPS) || 500;
+const dryRun = process.env.DRY_RUN === 'true';
+const relayerB64 = need('PUMP_CRON_RELAYER_SECRET_KEY_B64');
+
+const relayer = Keypair.fromSecretKey(Buffer.from(relayerB64, 'base64'));
+console.log(`relayer: ${relayer.publicKey.toBase58()}`);
+console.log(`mint: ${mintStr}`);
+console.log(`currency: ${currencyStr}`);
+console.log(`mode: ${fullSwap ? 'full-swap' : 'burn-only'}`);
+console.log(`slippageBps: ${slippageBps}`);
+console.log('');
+
+const { PUMP_PROGRAM_ID } = await import('@pump-fun/agent-payments-sdk');
+const {
+ getConnection,
+ getPumpAgent,
+ getPumpAgentOffline,
+ solanaPubkey,
+} = await import('../api/_lib/pump.js');
+const { buildPumpSwapInnerIx } = await import('../api/_lib/pump-swap-ix.js');
+
+const currency = solanaPubkey(currencyStr);
+const connection = getConnection({ network });
+
+const { agent } = await getPumpAgent({ network, mint: mintStr });
+const balances = await agent.getBalances(currency);
+const buyback = BigInt(balances.buybackVault?.balance ?? 0);
+console.log(`buybackVault balance: ${buyback.toString()}`);
+if (buyback === 0n) {
+ console.log('nothing to buy back, exiting');
+ process.exit(0);
+}
+
+const { offline } = await getPumpAgentOffline({ network, mint: mintStr });
+
+const params = {
+ globalBuybackAuthority: relayer.publicKey,
+ currencyMint: currency,
+ swapProgramToInvoke: PUMP_PROGRAM_ID,
+ swapInstructionData: Buffer.alloc(0),
+ remainingAccounts: [],
+};
+
+if (fullSwap) {
+ console.log('building pump-swap inner ix...');
+ const inner = await buildPumpSwapInnerIx({
+ mint: mintStr,
+ currency,
+ amountIn: buyback,
+ slippageBps,
+ cluster: network,
+ });
+ params.swapInstructionData = inner.data;
+ params.remainingAccounts = inner.accounts;
+ console.log(` inner ix: ${inner.data.length}-byte data, ${inner.accounts.length} accounts`);
+ console.log(` expectedBaseTokens: ${inner.expectedBaseTokens.toString()}`);
+ console.log(` minTokensOut: ${inner.minTokensOut.toString()}`);
+}
+
+const ix = await offline.buybackTrigger(params);
+console.log(`outer ix built: ${ix.keys.length} keys, ${ix.data.length}-byte data`);
+
+if (dryRun) {
+ console.log('DRY_RUN=true — exiting before submit');
+ process.exit(0);
+}
+
+const tx = new Transaction();
+tx.add(ix);
+const { blockhash } = await connection.getLatestBlockhash('confirmed');
+tx.recentBlockhash = blockhash;
+tx.feePayer = relayer.publicKey;
+tx.sign(relayer);
+const sig = await connection.sendRawTransaction(tx.serialize());
+console.log('');
+console.log(`submitted: ${sig}`);
+console.log(`https://explorer.solana.com/tx/${sig}?cluster=devnet`);
+
+await connection.confirmTransaction(sig, 'confirmed');
+console.log('confirmed');
diff --git a/scripts/measure-bake-size.mjs b/scripts/measure-bake-size.mjs
new file mode 100644
index 000000000..843c4564c
--- /dev/null
+++ b/scripts/measure-bake-size.mjs
@@ -0,0 +1,136 @@
+// scripts/measure-bake-size.mjs
+//
+// Measures the size reduction the meshopt() transform contributes to the
+// avatar bake pipeline. Bakes a reference avatar GLB twice — once through
+// the production transform chain in api/_lib/bake.js, once through the
+// same chain with meshopt() removed — and reports both byte sizes plus
+// the after/before ratio.
+//
+// Usage:
+// node scripts/measure-bake-size.mjs # default rig (default.glb)
+// node scripts/measure-bake-size.mjs <path.glb> # explicit GLB path
+//
+// Defaults to public/avatars/default.glb because that's the rig three.ws
+// hands every new user — its profile (full-body, skinned, multiple meshes)
+// is the realistic case for the bake pipeline. Smaller / hand-modeled
+// avatars get less from meshopt and are not a fair benchmark.
+//
+// The "after" pipeline mirrors bakeAppearance() in api/_lib/bake.js
+// exactly except for the level: 'medium' meshopt() step. The "before"
+// pipeline runs the same steps minus that one transform, so the delta is
+// fully attributable to meshopt.
+
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import {
+ unpartition,
+ prune,
+ dedup,
+ weld,
+ quantize,
+ meshopt,
+ textureCompress,
+} from '@gltf-transform/functions';
+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
+import sharp from 'sharp';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+const QUANTIZE_OPTS = {
+ quantizePosition: 14,
+ quantizeNormal: 10,
+ quantizeTexcoord: 12,
+ quantizeColor: 8,
+ quantizeWeight: 8,
+ quantizeGeneric: 12,
+};
+
+const TEXTURE_OPTS = {
+ encoder: sharp,
+ targetFormat: 'webp',
+ resize: [1024, 1024],
+ quality: 85,
+};
+
+async function makeIO() {
+ await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready]);
+ return new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
+ 'meshopt.encoder': MeshoptEncoder,
+ 'meshopt.decoder': MeshoptDecoder,
+ });
+}
+
+async function bake(bytes, { withMeshopt }) {
+ const io = await makeIO();
+ const doc = await io.readBinary(new Uint8Array(bytes));
+ const steps = [
+ unpartition(),
+ prune(),
+ dedup(),
+ weld(),
+ quantize(QUANTIZE_OPTS),
+ ];
+ if (withMeshopt) {
+ steps.push(meshopt({ encoder: MeshoptEncoder, level: 'medium' }));
+ }
+ steps.push(textureCompress(TEXTURE_OPTS));
+ await doc.transform(...steps);
+ return io.writeBinary(doc);
+}
+
+function fmt(bytes) {
+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${bytes} B`;
+}
+
+async function main() {
+ const inputPath =
+ process.argv[2] || path.resolve(process.cwd(), 'public/avatars/default.glb');
+ const sourceBytes = await readFile(inputPath);
+
+ console.log(`Source: ${inputPath}`);
+ console.log(` size: ${fmt(sourceBytes.byteLength)}`);
+ console.log('');
+
+ const t0 = Date.now();
+ const baselineBytes = await bake(sourceBytes, { withMeshopt: false });
+ const t1 = Date.now();
+ const meshoptBytes = await bake(sourceBytes, { withMeshopt: true });
+ const t2 = Date.now();
+
+ const baseline = baselineBytes.byteLength;
+ const after = meshoptBytes.byteLength;
+ const ratio = after / baseline;
+ const reduction = 1 - ratio;
+
+ console.log(`Baseline (weld+quantize+textureCompress):`);
+ console.log(` size: ${fmt(baseline)}`);
+ console.log(` bake time: ${t1 - t0} ms`);
+ console.log('');
+ console.log(`With meshopt() (level=medium):`);
+ console.log(` size: ${fmt(after)}`);
+ console.log(` bake time: ${t2 - t1} ms`);
+ console.log('');
+ console.log(`Δ: ${fmt(baseline - after)} smaller`);
+ console.log(`Ratio after/before: ${ratio.toFixed(3)}`);
+ console.log(`Reduction: ${(reduction * 100).toFixed(1)}%`);
+ console.log('');
+
+ // Sanity gate matching the task's expected band.
+ if (ratio > 0.6) {
+ console.warn(
+ `WARN: after/before ratio ${ratio.toFixed(3)} is worse than 0.6.`,
+ );
+ console.warn(
+ 'meshopt should yield 30–50% reduction on top of the existing pipeline.',
+ );
+ console.warn('Investigate the transform parameters.');
+ process.exitCode = 1;
+ }
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/scripts/x402-test.mjs b/scripts/x402-test.mjs
new file mode 100644
index 000000000..a21bb8c00
--- /dev/null
+++ b/scripts/x402-test.mjs
@@ -0,0 +1,75 @@
+// Manual x402 client — pays /api/x402/model-check on Base mainnet using the
+// vanity wallet's private key and verifies the endpoint returns the model
+// inspection JSON.
+import { Wallet, randomBytes, hexlify } from 'ethers';
+
+const PRIVATE_KEY = '0x5e306b436ea9cf2e9840eb9922094cc4a32beebc23588a8856ab75aab3f3f7b5';
+const ENDPOINT = 'https://three.ws/api/x402/model-check?url=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';
+
+const wallet = new Wallet(PRIVATE_KEY);
+console.log('Payer:', wallet.address);
+
+// 1. Get 402 challenge.
+const challenge = await fetch(ENDPOINT);
+console.log('Step 1 — challenge status:', challenge.status);
+const challengeBody = await challenge.json();
+const required = JSON.parse(Buffer.from(challenge.headers.get('payment-required'), 'base64').toString());
+const accept = required.accepts.find(a => a.network === 'eip155:8453' && a.scheme === 'exact');
+if (!accept) throw new Error('no Base accept');
+console.log(' payTo:', accept.payTo, 'amount:', accept.amount, 'asset:', accept.asset);
+
+// 2. Build EIP-3009 TransferWithAuthorization.
+const now = Math.floor(Date.now() / 1000);
+const authorization = {
+ from: wallet.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter: String(now - 600),
+ validBefore: String(now + Math.max(60, accept.maxTimeoutSeconds || 60)),
+ nonce: hexlify(randomBytes(32)),
+};
+const domain = {
+ name: accept.extra.name,
+ version: accept.extra.version,
+ chainId: 8453,
+ verifyingContract: accept.asset,
+};
+const types = {
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+};
+const signature = await wallet.signTypedData(domain, types, authorization);
+console.log('Step 2 — signed payload, sig length:', signature.length);
+
+const payment = {
+ x402Version: 2,
+ payload: { authorization, signature },
+ extensions: {},
+ resource: required.resource,
+ accepted: accept,
+};
+const header = Buffer.from(JSON.stringify(payment)).toString('base64');
+
+// 3. Retry with X-PAYMENT.
+const paid = await fetch(ENDPOINT, { headers: { 'X-PAYMENT': header } });
+console.log('Step 3 — paid status:', paid.status);
+const paymentResponse = paid.headers.get('x-payment-response');
+const network = paid.headers.get('x-payment-network');
+const tx = paid.headers.get('x-payment-tx');
+if (paymentResponse) {
+ const decoded = JSON.parse(Buffer.from(paymentResponse, 'base64').toString());
+ console.log(' X-PAYMENT-RESPONSE:', JSON.stringify(decoded, null, 2));
+}
+if (network) console.log(' X-PAYMENT-NETWORK:', network);
+if (tx) console.log(' X-PAYMENT-TX:', tx);
+const body = await paid.json();
+console.log(' body keys:', Object.keys(body));
+if (body.model?.counts) console.log(' model.counts:', body.model.counts);
+if (body.suggestions) console.log(' suggestions:', body.suggestions.length, 'item(s)');
+if (paid.status !== 200) console.log(' ERROR body:', JSON.stringify(body, null, 2));
diff --git a/src/marketplace-lobby.js b/src/marketplace-lobby.js
index f15c894b9..ca01639ed 100644
--- a/src/marketplace-lobby.js
+++ b/src/marketplace-lobby.js
@@ -34,6 +34,7 @@ import {
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { getMeshoptDecoder } from './viewer/internal.js';
const SLOT_SPACING = 1.6; // metres between avatar centres
const PODIUM_RADIUS = 0.55;
@@ -103,23 +104,28 @@ export async function mountLobby(canvas, avatars, options = {}) {
});
// Lazy-load GLBs in parallel; if one fails, the other slots still render.
+ // Baked avatars use EXT_meshopt_compression, so the loader needs the
+ // matching decoder before it can parse them.
const loader = new GLTFLoader();
+ const decoderReady = getMeshoptDecoder().then((dec) => loader.setMeshoptDecoder(dec));
slots.forEach((avatar, i) => {
const url = avatar?.glbUrl;
if (!url) return;
- loader.load(
- url,
- (gltf) => {
- const root = gltf.scene || gltf.scenes?.[0];
- if (!root) return;
- fitToHeight(root, TARGET_HEIGHT);
- slotMeta[i].group.add(root);
- slotMeta[i].model = root;
- slotMeta[i].avatar = avatar;
- },
- undefined,
- (err) => console.warn('[lobby] failed to load', url, err?.message),
- );
+ decoderReady.then(() => {
+ loader.load(
+ url,
+ (gltf) => {
+ const root = gltf.scene || gltf.scenes?.[0];
+ if (!root) return;
+ fitToHeight(root, TARGET_HEIGHT);
+ slotMeta[i].group.add(root);
+ slotMeta[i].model = root;
+ slotMeta[i].avatar = avatar;
+ },
+ undefined,
+ (err) => console.warn('[lobby] failed to load', url, err?.message),
+ );
+ });
});
// Mouse-parallax: camera drifts a little toward the cursor.
diff --git a/src/pose-mannequin.js b/src/pose-mannequin.js
new file mode 100644
index 000000000..ed58ed3e7
--- /dev/null
+++ b/src/pose-mannequin.js
@@ -0,0 +1,509 @@
+// Articulated 3D mannequin for /pose — a hierarchical skeleton built from
+// Three.js primitives. Each joint is a Group whose rotation drives the body
+// part below it; meshes (limbs, head, hands, feet) are anchored to those
+// groups so adjusting a joint's Euler rotation moves the whole chain.
+//
+// Convention: every limb mesh extends along the joint group's LOCAL -Y axis
+// (downward from the joint origin). That way the rest pose (all rotations
+// zero) puts the figure standing upright with arms at its sides — so user-
+// facing rotations are interpreted relative to that intuitive resting frame.
+
+import {
+ BoxGeometry,
+ CapsuleGeometry,
+ Color,
+ Group,
+ Mesh,
+ MeshStandardMaterial,
+ SphereGeometry,
+} from 'three';
+
+// Joint names are stable identifiers used by presets, serialization, and the
+// UI. Order matters for the panel rendering — head → spine → arms → legs.
+export const JOINT_NAMES = [
+ 'pelvis',
+ 'spine',
+ 'chest',
+ 'neck',
+ 'head',
+ 'shoulderL', 'elbowL', 'wristL',
+ 'shoulderR', 'elbowR', 'wristR',
+ 'hipL', 'kneeL', 'ankleL',
+ 'hipR', 'kneeR', 'ankleR',
+];
+
+// Human-readable labels for the selection HUD.
+export const JOINT_LABELS = {
+ pelvis: 'Pelvis',
+ spine: 'Spine (lower)',
+ chest: 'Spine (upper)',
+ neck: 'Neck',
+ head: 'Head',
+ shoulderL: 'Shoulder L',
+ elbowL: 'Elbow L',
+ wristL: 'Wrist L',
+ shoulderR: 'Shoulder R',
+ elbowR: 'Elbow R',
+ wristR: 'Wrist R',
+ hipL: 'Hip L',
+ kneeL: 'Knee L',
+ ankleL: 'Ankle L',
+ hipR: 'Hip R',
+ kneeR: 'Knee R',
+ ankleR: 'Ankle R',
+};
+
+// Per-axis hints for the UI sliders — describes what each Euler axis does
+// for a given joint so the controls panel can label them meaningfully.
+export const JOINT_AXIS_LABELS = {
+ default: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ pelvis: { x: 'Pitch', y: 'Yaw', z: 'Roll' },
+ spine: { x: 'Bend', y: 'Twist', z: 'Side' },
+ chest: { x: 'Bend', y: 'Twist', z: 'Side' },
+ neck: { x: 'Bend', y: 'Turn', z: 'Tilt' },
+ head: { x: 'Nod', y: 'Turn', z: 'Tilt' },
+ shoulderL: { x: 'Raise', y: 'Twist', z: 'Out/In' },
+ shoulderR: { x: 'Raise', y: 'Twist', z: 'In/Out' },
+ elbowL: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ elbowR: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ wristL: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ wristR: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ hipL: { x: 'Raise', y: 'Twist', z: 'Out/In' },
+ hipR: { x: 'Raise', y: 'Twist', z: 'In/Out' },
+ kneeL: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ kneeR: { x: 'Bend', y: 'Twist', z: 'Tilt' },
+ ankleL: { x: 'Flex', y: 'Twist', z: 'Tilt' },
+ ankleR: { x: 'Flex', y: 'Twist', z: 'Tilt' },
+};
+
+// Body proportions. Lengths are in metres so the camera and grid in Three.js
+// units roughly match a ~1.75 m tall figure.
+const PROPORTIONS = {
+ male: {
+ scale: 1.0,
+ shoulderHalf: 0.21,
+ hipHalf: 0.13,
+ neckLen: 0.10,
+ headRadius: 0.115,
+ spineLen: 0.22,
+ chestLen: 0.26,
+ upperArmLen: 0.30,
+ forearmLen: 0.28,
+ handLen: 0.18,
+ thighLen: 0.44,
+ shinLen: 0.42,
+ footLen: 0.25,
+ limbRadius: 0.058,
+ torsoRadius: 0.115,
+ },
+ female: {
+ scale: 0.95,
+ shoulderHalf: 0.18,
+ hipHalf: 0.14,
+ neckLen: 0.09,
+ headRadius: 0.110,
+ spineLen: 0.21,
+ chestLen: 0.25,
+ upperArmLen: 0.28,
+ forearmLen: 0.27,
+ handLen: 0.17,
+ thighLen: 0.43,
+ shinLen: 0.41,
+ footLen: 0.24,
+ limbRadius: 0.052,
+ torsoRadius: 0.105,
+ },
+};
+
+// Biological constraints — soft limits applied when constraintsEnabled = true.
+// Values are radians per Euler axis (x, y, z). null means unrestricted on
+// that axis. Ranges are generous; SetPose itself lets users toggle them off
+// because tight limits frustrate creative posing.
+const CONSTRAINTS = {
+ pelvis: { x: [-0.8, 0.8], y: [-Math.PI, Math.PI], z: [-0.6, 0.6] },
+ spine: { x: [-0.6, 0.6], y: [-0.6, 0.6], z: [-0.5, 0.5] },
+ chest: { x: [-0.6, 0.6], y: [-0.6, 0.6], z: [-0.5, 0.5] },
+ neck: { x: [-0.7, 0.7], y: [-0.8, 0.8], z: [-0.4, 0.4] },
+ head: { x: [-0.9, 0.9], y: [-1.3, 1.3], z: [-0.6, 0.6] },
+ // Shoulder x: arm forward(+)/back(-). z: arm out to side (away from torso).
+ shoulderL: { x: [-2.4, 2.4], y: [-1.6, 1.6], z: [-0.4, Math.PI] },
+ shoulderR: { x: [-2.4, 2.4], y: [-1.6, 1.6], z: [-Math.PI, 0.4] },
+ elbowL: { x: [-2.4, 0.0], y: [-1.6, 1.6], z: null },
+ elbowR: { x: [-2.4, 0.0], y: [-1.6, 1.6], z: null },
+ wristL: { x: [-1.0, 1.0], y: [-0.6, 0.6], z: [-0.6, 0.6] },
+ wristR: { x: [-1.0, 1.0], y: [-0.6, 0.6], z: [-0.6, 0.6] },
+ hipL: { x: [-2.0, 0.6], y: [-1.0, 1.0], z: [-0.6, Math.PI / 2] },
+ hipR: { x: [-2.0, 0.6], y: [-1.0, 1.0], z: [-Math.PI / 2, 0.6] },
+ kneeL: { x: [0, 2.6], y: null, z: null },
+ kneeR: { x: [0, 2.6], y: null, z: null },
+ ankleL: { x: [-0.6, 0.9], y: [-0.4, 0.4], z: [-0.3, 0.3] },
+ ankleR: { x: [-0.6, 0.9], y: [-0.4, 0.4], z: [-0.3, 0.3] },
+};
+
+function clamp(v, lo, hi) {
+ return Math.min(hi, Math.max(lo, v));
+}
+
+// A limb mesh is a capsule oriented along -Y. The joint group sits at the
+// PROXIMAL end (the rotation pivot, at the top of the limb), and the capsule
+// is translated so its top cap touches that origin and its body hangs below.
+// The next joint group is then placed at the distal end (y = -length).
+function downLimb(length, radius, material) {
+ const geom = new CapsuleGeometry(radius, Math.max(0.001, length - radius * 2), 8, 16);
+ const mesh = new Mesh(geom, material);
+ mesh.position.y = -length / 2;
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ return mesh;
+}
+
+function ballMesh(radius, material) {
+ const m = new Mesh(new SphereGeometry(radius, 18, 14), material);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ return m;
+}
+
+// A limb that extends UP from its joint (used for spine, neck) — same as
+// downLimb but mirrored. Spine goes up because its joint is at the pelvis
+// and the chest joint sits at the top of the spine.
+function upLimb(length, radius, material) {
+ const geom = new CapsuleGeometry(radius, Math.max(0.001, length - radius * 2), 8, 16);
+ const mesh = new Mesh(geom, material);
+ mesh.position.y = length / 2;
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ return mesh;
+}
+
+// Tag a joint group and its descendant meshes so a raycaster can map a hit
+// back to the owning joint name.
+function tagJoint(group, name) {
+ group.userData.jointName = name;
+ group.traverse((child) => {
+ if (child !== group && child instanceof Mesh) {
+ child.userData.jointName = name;
+ }
+ });
+}
+
+export class Mannequin {
+ constructor({ build = 'male', color = '#d4d4d8' } = {}) {
+ this.build = build;
+ this.constraintsEnabled = true;
+ this.material = new MeshStandardMaterial({
+ color: new Color(color),
+ roughness: 0.62,
+ metalness: 0.05,
+ });
+ this.jointMaterial = new MeshStandardMaterial({
+ color: new Color(color).offsetHSL(0, 0, -0.06),
+ roughness: 0.55,
+ metalness: 0.05,
+ });
+
+ this.joints = {};
+ this.selectableMeshes = [];
+ this.root = new Group();
+ this.root.name = 'mannequin-root';
+ this._build();
+ }
+
+ // Walk a hit object back up to the nearest tagged joint group.
+ jointFromHit(object) {
+ let o = object;
+ while (o) {
+ if (o.userData?.jointName && this.joints[o.userData.jointName]) {
+ return o.userData.jointName;
+ }
+ o = o.parent;
+ }
+ return null;
+ }
+
+ setBuild(build) {
+ if (build === this.build) return;
+ const prev = this.getPose();
+ this.build = build;
+ this.root.clear();
+ this.joints = {};
+ this.selectableMeshes = [];
+ this._build();
+ this.applyPose(prev);
+ }
+
+ setColor(hex) {
+ this.material.color.set(hex);
+ this.jointMaterial.color.set(hex).offsetHSL(0, 0, -0.06);
+ }
+
+ setConstraintsEnabled(enabled) {
+ this.constraintsEnabled = !!enabled;
+ if (this.constraintsEnabled) {
+ for (const name of Object.keys(CONSTRAINTS)) {
+ const j = this.joints[name];
+ if (j) this._applyConstraint(name, j.rotation);
+ }
+ }
+ }
+
+ setJointRotation(name, axis, radians) {
+ const j = this.joints[name];
+ if (!j) return;
+ j.rotation[axis] = radians;
+ if (this.constraintsEnabled) this._applyConstraint(name, j.rotation);
+ }
+
+ getJointRotation(name) {
+ const j = this.joints[name];
+ if (!j) return { x: 0, y: 0, z: 0 };
+ return { x: j.rotation.x, y: j.rotation.y, z: j.rotation.z };
+ }
+
+ // A pose is a flat map of jointName → {x, y, z} rotations (radians),
+ // plus an optional "rootPosition" for translating the whole figure.
+ applyPose(pose) {
+ if (!pose) return;
+ // Reset everything first so a partial preset doesn't leak previous
+ // rotations on unmentioned joints.
+ this.resetPose();
+ for (const [name, rot] of Object.entries(pose)) {
+ if (name === 'rootPosition' && rot) {
+ this.root.position.set(rot.x || 0, rot.y || 0, rot.z || 0);
+ continue;
+ }
+ const j = this.joints[name];
+ if (!j) continue;
+ j.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);
+ if (this.constraintsEnabled) this._applyConstraint(name, j.rotation);
+ }
+ }
+
+ getPose() {
+ const pose = {};
+ for (const name of Object.keys(this.joints)) {
+ const r = this.joints[name].rotation;
+ pose[name] = { x: r.x, y: r.y, z: r.z };
+ }
+ pose.rootPosition = {
+ x: this.root.position.x,
+ y: this.root.position.y,
+ z: this.root.position.z,
+ };
+ return pose;
+ }
+
+ resetPose() {
+ for (const j of Object.values(this.joints)) {
+ j.rotation.set(0, 0, 0);
+ }
+ this.root.position.set(0, 0, 0);
+ }
+
+ _applyConstraint(name, rot) {
+ const c = CONSTRAINTS[name];
+ if (!c) return;
+ if (c.x) rot.x = clamp(rot.x, c.x[0], c.x[1]);
+ if (c.y) rot.y = clamp(rot.y, c.y[0], c.y[1]);
+ if (c.z) rot.z = clamp(rot.z, c.z[0], c.z[1]);
+ }
+
+ _build() {
+ const p = PROPORTIONS[this.build];
+ this.root.scale.setScalar(p.scale);
+
+ // Standing height: legs + spine + chest + neck + head. Place the
+ // pelvis at hip height so the feet rest on y = 0.
+ const pelvisY = p.thighLen + p.shinLen;
+
+ // Pelvis — owns the whole figure's translation/rotation in body
+ // space. Body yaw (turning the figure left/right) maps to pelvis.y.
+ const pelvis = new Group();
+ pelvis.name = 'pelvis';
+ pelvis.position.y = pelvisY;
+ this.root.add(pelvis);
+ this.joints.pelvis = pelvis;
+
+ // Pelvis block (flattened sphere).
+ const pelvisMesh = new Mesh(
+ new SphereGeometry(p.torsoRadius * 1.05, 18, 14),
+ this.jointMaterial,
+ );
+ pelvisMesh.scale.set(1, 0.6, 0.8);
+ pelvisMesh.castShadow = true;
+ pelvisMesh.receiveShadow = true;
+ pelvis.add(pelvisMesh);
+ this.selectableMeshes.push(pelvisMesh);
+ tagJoint(pelvis, 'pelvis');
+
+ // Spine — extends UP from the pelvis. Rotation here flexes the
+ // lower back.
+ const spine = new Group();
+ spine.name = 'spine';
+ pelvis.add(spine);
+ this.joints.spine = spine;
+ const spineMesh = upLimb(p.spineLen, p.torsoRadius * 0.95, this.material);
+ spine.add(spineMesh);
+ this.selectableMeshes.push(spineMesh);
+ tagJoint(spine, 'spine');
+
+ // Chest — extends UP from the top of the spine. The rib-cage mesh
+ // is slightly wider front-to-back than side-to-side via scale.
+ const chest = new Group();
+ chest.name = 'chest';
+ chest.position.y = p.spineLen;
+ spine.add(chest);
+ this.joints.chest = chest;
+ const chestMesh = upLimb(p.chestLen, p.torsoRadius, this.material);
+ chestMesh.scale.set(1.05, 1.0, 0.85);
+ chest.add(chestMesh);
+ this.selectableMeshes.push(chestMesh);
+ tagJoint(chest, 'chest');
+
+ // Neck — up from the top of the chest.
+ const neck = new Group();
+ neck.name = 'neck';
+ neck.position.y = p.chestLen;
+ chest.add(neck);
+ this.joints.neck = neck;
+ const neckMesh = upLimb(p.neckLen, p.limbRadius * 0.9, this.material);
+ neck.add(neckMesh);
+ this.selectableMeshes.push(neckMesh);
+ tagJoint(neck, 'neck');
+
+ // Head — sphere at the top of the neck, plus a small wedge so the
+ // front of the head is visible (helps a poser tell which way the
+ // figure is looking).
+ const head = new Group();
+ head.name = 'head';
+ head.position.y = p.neckLen;
+ neck.add(head);
+ this.joints.head = head;
+ const headMesh = ballMesh(p.headRadius, this.material);
+ headMesh.position.y = p.headRadius;
+ head.add(headMesh);
+ this.selectableMeshes.push(headMesh);
+ const nose = new Mesh(
+ new BoxGeometry(p.headRadius * 0.25, p.headRadius * 0.3, p.headRadius * 0.4),
+ this.jointMaterial,
+ );
+ nose.position.set(0, p.headRadius * 0.95, p.headRadius * 0.85);
+ nose.castShadow = true;
+ head.add(nose);
+ this.selectableMeshes.push(nose);
+ tagJoint(head, 'head');
+
+ // Arms — anchored at the top of the chest, extend DOWN from the
+ // shoulder joint along -Y. Rest pose: arms at sides.
+ this._buildArm('L', chest, p, +1);
+ this._buildArm('R', chest, p, -1);
+
+ // Legs — hang off the pelvis (not the spine, so spinal flexion
+ // doesn't carry the legs with it).
+ this._buildLeg('L', pelvis, p, +1);
+ this._buildLeg('R', pelvis, p, -1);
+ }
+
+ _buildArm(side, chest, p, sign) {
+ // sign: +1 for left, -1 for right (in world +X / -X).
+ const shoulderName = 'shoulder' + side;
+ const elbowName = 'elbow' + side;
+ const wristName = 'wrist' + side;
+
+ const shoulder = new Group();
+ shoulder.name = shoulderName;
+ shoulder.position.set(sign * p.shoulderHalf, p.chestLen * 0.92, 0);
+ chest.add(shoulder);
+ this.joints[shoulderName] = shoulder;
+
+ const shoulderBall = ballMesh(p.limbRadius * 1.1, this.jointMaterial);
+ shoulder.add(shoulderBall);
+ this.selectableMeshes.push(shoulderBall);
+
+ const upperArm = downLimb(p.upperArmLen, p.limbRadius, this.material);
+ shoulder.add(upperArm);
+ this.selectableMeshes.push(upperArm);
+ tagJoint(shoulder, shoulderName);
+
+ const elbow = new Group();
+ elbow.name = elbowName;
+ elbow.position.y = -p.upperArmLen;
+ shoulder.add(elbow);
+ this.joints[elbowName] = elbow;
+ const forearm = downLimb(p.forearmLen, p.limbRadius * 0.92, this.material);
+ elbow.add(forearm);
+ this.selectableMeshes.push(forearm);
+ tagJoint(elbow, elbowName);
+
+ const wrist = new Group();
+ wrist.name = wristName;
+ wrist.position.y = -p.forearmLen;
+ elbow.add(wrist);
+ this.joints[wristName] = wrist;
+ const hand = new Mesh(
+ new BoxGeometry(p.limbRadius * 1.6, p.handLen, p.limbRadius * 0.7),
+ this.material,
+ );
+ hand.position.y = -p.handLen / 2;
+ hand.castShadow = true;
+ hand.receiveShadow = true;
+ wrist.add(hand);
+ this.selectableMeshes.push(hand);
+ tagJoint(wrist, wristName);
+ }
+
+ _buildLeg(side, pelvis, p, sign) {
+ const hipName = 'hip' + side;
+ const kneeName = 'knee' + side;
+ const ankleName = 'ankle' + side;
+
+ const hip = new Group();
+ hip.name = hipName;
+ hip.position.set(sign * p.hipHalf, -p.torsoRadius * 0.2, 0);
+ pelvis.add(hip);
+ this.joints[hipName] = hip;
+
+ const hipBall = ballMesh(p.limbRadius * 1.15, this.jointMaterial);
+ hip.add(hipBall);
+ this.selectableMeshes.push(hipBall);
+
+ const thigh = downLimb(p.thighLen, p.limbRadius * 1.15, this.material);
+ hip.add(thigh);
+ this.selectableMeshes.push(thigh);
+ tagJoint(hip, hipName);
+
+ const knee = new Group();
+ knee.name = kneeName;
+ knee.position.y = -p.thighLen;
+ hip.add(knee);
+ this.joints[kneeName] = knee;
+ const shin = downLimb(p.shinLen, p.limbRadius * 0.95, this.material);
+ knee.add(shin);
+ this.selectableMeshes.push(shin);
+ tagJoint(knee, kneeName);
+
+ const ankle = new Group();
+ ankle.name = ankleName;
+ ankle.position.y = -p.shinLen;
+ knee.add(ankle);
+ this.joints[ankleName] = ankle;
+ // Foot: box extended forward (toward +Z in default world frame).
+ const foot = new Mesh(
+ new BoxGeometry(p.limbRadius * 1.7, p.limbRadius * 0.6, p.footLen),
+ this.material,
+ );
+ foot.position.set(0, -p.limbRadius * 0.3, p.footLen * 0.3);
+ foot.castShadow = true;
+ foot.receiveShadow = true;
+ ankle.add(foot);
+ this.selectableMeshes.push(foot);
+ tagJoint(ankle, ankleName);
+ }
+
+ getApproxHeight() {
+ const p = PROPORTIONS[this.build];
+ return (p.thighLen + p.shinLen + p.spineLen + p.chestLen + p.neckLen + p.headRadius * 2) * p.scale;
+ }
+}
+
+export { PROPORTIONS as MANNEQUIN_PROPORTIONS, CONSTRAINTS as MANNEQUIN_CONSTRAINTS };
diff --git a/src/pose-presets.js b/src/pose-presets.js
new file mode 100644
index 000000000..53ca680fc
--- /dev/null
+++ b/src/pose-presets.js
@@ -0,0 +1,416 @@
+// Preset poses for /pose. Each entry is { id, label, group, pose } where
+// `pose` is a flat map of jointName → { x, y, z } Euler rotations in
+// radians, optionally with a rootPosition translating the whole figure.
+//
+// Convention reminder: in rest pose every rotation is 0 and the mannequin
+// stands upright with arms at its sides. Limbs extend along their joint
+// group's local -Y axis. Positive shoulderL.z opens the left arm outward
+// (to the figure's left); negative shoulderR.z opens the right arm outward.
+// shoulderX is forward(-) / back(+); elbow.x is bend (negative bends the
+// elbow naturally so the forearm comes up toward the shoulder).
+
+const PI = Math.PI;
+const HALF = PI / 2;
+
+export const PRESET_GROUPS = ['Standing', 'Action', 'Sitting & Floor', 'Expressive'];
+
+export const PRESETS = [
+ // ─── STANDING ───
+ {
+ id: 'tpose',
+ label: 'T-pose',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: 0, y: 0, z: HALF },
+ shoulderR: { x: 0, y: 0, z: -HALF },
+ },
+ },
+ {
+ id: 'apose',
+ label: 'A-pose',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: 0, y: 0, z: 0.55 },
+ shoulderR: { x: 0, y: 0, z: -0.55 },
+ },
+ },
+ {
+ id: 'relaxed',
+ label: 'Relaxed stand',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: -0.08, y: 0, z: 0.10 },
+ shoulderR: { x: -0.08, y: 0, z: -0.10 },
+ elbowL: { x: -0.18, y: 0, z: 0 },
+ elbowR: { x: -0.18, y: 0, z: 0 },
+ hipL: { x: 0.04, y: 0, z: 0.04 },
+ hipR: { x: -0.04, y: 0, z: -0.04 },
+ head: { x: 0.06, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'contrapposto',
+ label: 'Contrapposto',
+ group: 'Standing',
+ pose: {
+ pelvis: { x: 0, y: 0, z: 0.10 },
+ spine: { x: 0, y: 0, z: -0.06 },
+ chest: { x: 0, y: -0.10, z: -0.04 },
+ head: { x: 0, y: 0.20, z: -0.05 },
+ shoulderL: { x: -0.12, y: 0, z: 0.18 },
+ shoulderR: { x: -0.10, y: 0, z: -0.10 },
+ elbowL: { x: -0.30, y: 0, z: 0 },
+ elbowR: { x: -0.18, y: 0, z: 0 },
+ hipL: { x: 0.05, y: 0, z: -0.05 },
+ hipR: { x: -0.20, y: 0, z: 0.05 },
+ kneeR: { x: 0.40, y: 0, z: 0 },
+ ankleR: { x: -0.25, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'hands-up',
+ label: 'Arms up (cheer)',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: 0, y: 0, z: PI * 0.92 },
+ shoulderR: { x: 0, y: 0, z: -PI * 0.92 },
+ elbowL: { x: -0.10, y: 0, z: 0 },
+ elbowR: { x: -0.10, y: 0, z: 0 },
+ head: { x: -0.20, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'wave',
+ label: 'Wave hello',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: 0, y: 0, z: 0.10 },
+ shoulderR: { x: 0, y: 0, z: -PI * 0.78 },
+ elbowR: { x: -1.20, y: 0, z: 0 },
+ wristR: { x: 0, y: 0, z: -0.30 },
+ head: { x: 0, y: -0.20, z: 0 },
+ },
+ },
+ {
+ id: 'hands-on-hips',
+ label: 'Hands on hips',
+ group: 'Standing',
+ pose: {
+ shoulderL: { x: 0, y: -1.2, z: 0.55 },
+ shoulderR: { x: 0, y: 1.2, z: -0.55 },
+ elbowL: { x: -1.40, y: 0, z: 0 },
+ elbowR: { x: -1.40, y: 0, z: 0 },
+ chest: { x: -0.05, y: 0, z: 0 },
+ },
+ },
+
+ // ─── ACTION ───
+ {
+ id: 'walk-step',
+ label: 'Walking step',
+ group: 'Action',
+ pose: {
+ shoulderL: { x: -0.55, y: 0, z: 0.05 },
+ shoulderR: { x: 0.55, y: 0, z: -0.05 },
+ elbowL: { x: -0.50, y: 0, z: 0 },
+ elbowR: { x: -0.50, y: 0, z: 0 },
+ hipL: { x: -0.55, y: 0, z: 0 },
+ hipR: { x: 0.35, y: 0, z: 0 },
+ kneeR: { x: 0.55, y: 0, z: 0 },
+ ankleL: { x: -0.10, y: 0, z: 0 },
+ ankleR: { x: 0.25, y: 0, z: 0 },
+ chest: { x: 0.08, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'run',
+ label: 'Running',
+ group: 'Action',
+ pose: {
+ chest: { x: 0.18, y: 0, z: 0 },
+ shoulderL: { x: -1.10, y: 0, z: 0.10 },
+ shoulderR: { x: 1.10, y: 0, z: -0.10 },
+ elbowL: { x: -1.50, y: 0, z: 0 },
+ elbowR: { x: -1.50, y: 0, z: 0 },
+ hipL: { x: -1.10, y: 0, z: 0 },
+ hipR: { x: 0.50, y: 0, z: 0 },
+ kneeL: { x: 1.20, y: 0, z: 0 },
+ kneeR: { x: 0.30, y: 0, z: 0 },
+ ankleL: { x: -0.30, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'jump',
+ label: 'Jumping',
+ group: 'Action',
+ pose: {
+ shoulderL: { x: 0, y: 0, z: PI * 0.85 },
+ shoulderR: { x: 0, y: 0, z: -PI * 0.85 },
+ elbowL: { x: -0.20, y: 0, z: 0 },
+ elbowR: { x: -0.20, y: 0, z: 0 },
+ hipL: { x: -0.55, y: 0, z: 0 },
+ hipR: { x: -0.55, y: 0, z: 0 },
+ kneeL: { x: 1.10, y: 0, z: 0 },
+ kneeR: { x: 1.10, y: 0, z: 0 },
+ ankleL: { x: -0.40, y: 0, z: 0 },
+ ankleR: { x: -0.40, y: 0, z: 0 },
+ chest: { x: -0.10, y: 0, z: 0 },
+ rootPosition: { x: 0, y: 0.20, z: 0 },
+ },
+ },
+ {
+ id: 'punch',
+ label: 'Punch (right)',
+ group: 'Action',
+ pose: {
+ chest: { x: 0, y: -0.30, z: 0 },
+ shoulderL: { x: -0.40, y: 0, z: 0.20 },
+ shoulderR: { x: -HALF, y: 0, z: -0.30 },
+ elbowL: { x: -1.80, y: 0, z: 0 },
+ elbowR: { x: -0.15, y: 0, z: 0 },
+ wristL: { x: -0.20, y: 0, z: 0 },
+ hipL: { x: -0.10, y: 0, z: 0.10 },
+ hipR: { x: -0.20, y: 0, z: 0 },
+ kneeL: { x: 0.30, y: 0, z: 0 },
+ kneeR: { x: 0.20, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'archery',
+ label: 'Archery',
+ group: 'Action',
+ pose: {
+ chest: { x: 0, y: -0.35, z: 0 },
+ head: { x: 0, y: 0.10, z: 0 },
+ shoulderL: { x: 0, y: 0, z: HALF + 0.05 },
+ shoulderR: { x: 0, y: 0, z: -0.40 },
+ elbowL: { x: -0.05, y: 0, z: 0 },
+ elbowR: { x: -2.10, y: 0, z: 0 },
+ wristR: { x: 0, y: 0.20, z: 0 },
+ hipL: { x: 0, y: 0, z: 0.10 },
+ hipR: { x: 0, y: 0, z: -0.10 },
+ },
+ },
+ {
+ id: 'superhero-landing',
+ label: 'Superhero landing',
+ group: 'Action',
+ pose: {
+ pelvis: { x: 0, y: 0.25, z: 0 },
+ spine: { x: 0.20, y: 0, z: 0 },
+ chest: { x: 0.25, y: 0, z: 0 },
+ head: { x: 0.30, y: 0, z: 0 },
+ shoulderL: { x: 0, y: 0, z: HALF + 0.30 },
+ shoulderR: { x: -0.20, y: 0, z: -0.15 },
+ elbowL: { x: -0.40, y: 0, z: 0 },
+ elbowR: { x: -1.20, y: 0, z: 0 },
+ hipL: { x: -1.20, y: 0, z: 0.30 },
+ hipR: { x: -0.30, y: 0, z: -0.10 },
+ kneeL: { x: 2.20, y: 0, z: 0 },
+ kneeR: { x: 0.40, y: 0, z: 0 },
+ ankleL: { x: -0.30, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.42, z: 0 },
+ },
+ },
+
+ // ─── SITTING & FLOOR ───
+ {
+ id: 'sit-chair',
+ label: 'Sitting (chair)',
+ group: 'Sitting & Floor',
+ pose: {
+ hipL: { x: -HALF, y: 0, z: 0 },
+ hipR: { x: -HALF, y: 0, z: 0 },
+ kneeL: { x: HALF, y: 0, z: 0 },
+ kneeR: { x: HALF, y: 0, z: 0 },
+ shoulderL: { x: -0.20, y: 0, z: 0.15 },
+ shoulderR: { x: -0.20, y: 0, z: -0.15 },
+ elbowL: { x: -0.40, y: 0, z: 0 },
+ elbowR: { x: -0.40, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.42, z: 0 },
+ },
+ },
+ {
+ id: 'sit-floor',
+ label: 'Sitting (floor)',
+ group: 'Sitting & Floor',
+ pose: {
+ hipL: { x: -1.85, y: 0.35, z: 0.40 },
+ hipR: { x: -1.85, y: -0.35, z: -0.40 },
+ kneeL: { x: 1.80, y: 0, z: 0 },
+ kneeR: { x: 1.80, y: 0, z: 0 },
+ shoulderL: { x: 0, y: 0, z: 0.20 },
+ shoulderR: { x: 0, y: 0, z: -0.20 },
+ elbowL: { x: -0.40, y: 0, z: 0 },
+ elbowR: { x: -0.40, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.80, z: 0 },
+ },
+ },
+ {
+ id: 'kneel',
+ label: 'Kneeling',
+ group: 'Sitting & Floor',
+ pose: {
+ hipL: { x: -0.10, y: 0, z: 0 },
+ hipR: { x: -HALF, y: 0, z: 0 },
+ kneeL: { x: 0.20, y: 0, z: 0 },
+ kneeR: { x: HALF + 0.40, y: 0, z: 0 },
+ ankleL: { x: -0.20, y: 0, z: 0 },
+ shoulderL: { x: -0.20, y: 0, z: 0.10 },
+ shoulderR: { x: -0.20, y: 0, z: -0.10 },
+ elbowL: { x: -0.30, y: 0, z: 0 },
+ elbowR: { x: -0.30, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.42, z: 0 },
+ },
+ },
+ {
+ id: 'crouch',
+ label: 'Crouching',
+ group: 'Sitting & Floor',
+ pose: {
+ hipL: { x: -1.50, y: 0, z: 0.30 },
+ hipR: { x: -1.50, y: 0, z: -0.30 },
+ kneeL: { x: 2.20, y: 0, z: 0 },
+ kneeR: { x: 2.20, y: 0, z: 0 },
+ ankleL: { x: -0.40, y: 0, z: 0 },
+ ankleR: { x: -0.40, y: 0, z: 0 },
+ chest: { x: 0.30, y: 0, z: 0 },
+ shoulderL: { x: -0.30, y: 0, z: 0.20 },
+ shoulderR: { x: -0.30, y: 0, z: -0.20 },
+ elbowL: { x: -0.60, y: 0, z: 0 },
+ elbowR: { x: -0.60, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.55, z: 0 },
+ },
+ },
+ {
+ id: 'thinker',
+ label: 'The thinker',
+ group: 'Sitting & Floor',
+ pose: {
+ hipL: { x: -HALF, y: 0, z: 0 },
+ hipR: { x: -HALF, y: 0.20, z: -0.05 },
+ kneeL: { x: HALF, y: 0, z: 0 },
+ kneeR: { x: HALF, y: 0, z: 0 },
+ chest: { x: 0.30, y: -0.20, z: 0 },
+ spine: { x: 0.15, y: 0, z: 0 },
+ head: { x: 0.40, y: 0, z: 0 },
+ shoulderL: { x: -0.60, y: 0, z: 0.05 },
+ shoulderR: { x: -1.30, y: 0, z: -0.25 },
+ elbowL: { x: -0.50, y: 0, z: 0 },
+ elbowR: { x: -2.20, y: 0, z: 0 },
+ wristR: { x: -0.30, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.42, z: 0 },
+ },
+ },
+
+ // ─── EXPRESSIVE ───
+ {
+ id: 'praying',
+ label: 'Praying',
+ group: 'Expressive',
+ pose: {
+ head: { x: 0.20, y: 0, z: 0 },
+ chest: { x: 0.05, y: 0, z: 0 },
+ shoulderL: { x: -0.30, y: -0.45, z: 0.45 },
+ shoulderR: { x: -0.30, y: 0.45, z: -0.45 },
+ elbowL: { x: -1.80, y: 0, z: 0 },
+ elbowR: { x: -1.80, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'meditate',
+ label: 'Meditation',
+ group: 'Expressive',
+ pose: {
+ hipL: { x: -1.40, y: 0.50, z: 0.55 },
+ hipR: { x: -1.40, y: -0.50, z: -0.55 },
+ kneeL: { x: 2.10, y: 0, z: 0 },
+ kneeR: { x: 2.10, y: 0, z: 0 },
+ shoulderL: { x: -0.20, y: 0, z: 0.15 },
+ shoulderR: { x: -0.20, y: 0, z: -0.15 },
+ elbowL: { x: -0.30, y: 0, z: 0 },
+ elbowR: { x: -0.30, y: 0, z: 0 },
+ wristL: { x: -0.40, y: 0, z: 0 },
+ wristR: { x: -0.40, y: 0, z: 0 },
+ head: { x: 0.10, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.80, z: 0 },
+ },
+ },
+ {
+ id: 'warrior2',
+ label: 'Warrior II (yoga)',
+ group: 'Expressive',
+ pose: {
+ pelvis: { x: 0, y: 0.30, z: 0 },
+ chest: { x: 0, y: -0.30, z: 0 },
+ head: { x: 0, y: 0.50, z: 0 },
+ shoulderL: { x: 0, y: 0, z: HALF },
+ shoulderR: { x: 0, y: 0, z: -HALF },
+ hipL: { x: -0.10, y: 0.35, z: 0.20 },
+ hipR: { x: -0.15, y: 0, z: -0.45 },
+ kneeL: { x: 1.40, y: 0, z: 0 },
+ ankleL: { x: -0.20, y: 0, z: 0 },
+ rootPosition: { x: 0, y: -0.18, z: 0 },
+ },
+ },
+ {
+ id: 'arabesque',
+ label: 'Arabesque (ballet)',
+ group: 'Expressive',
+ pose: {
+ pelvis: { x: 0.25, y: 0, z: 0 },
+ spine: { x: 0.10, y: 0, z: 0 },
+ chest: { x: -0.10, y: 0, z: 0 },
+ head: { x: -0.30, y: 0, z: 0 },
+ shoulderL: { x: 0, y: 0, z: 0.95 },
+ shoulderR: { x: 0, y: 0, z: -0.95 },
+ elbowL: { x: -0.20, y: 0, z: 0 },
+ elbowR: { x: -0.20, y: 0, z: 0 },
+ hipL: { x: 0.50, y: 0, z: 0.10 },
+ hipR: { x: 0, y: 0, z: -0.10 },
+ ankleR: { x: -0.30, y: 0, z: 0 },
+ },
+ },
+ {
+ id: 'flex',
+ label: 'Flex (muscle pose)',
+ group: 'Expressive',
+ pose: {
+ chest: { x: 0, y: -0.10, z: 0 },
+ shoulderL: { x: 0, y: -0.40, z: HALF + 0.10 },
+ shoulderR: { x: 0, y: 0.40, z: -HALF - 0.10 },
+ elbowL: { x: -2.00, y: 0, z: 0 },
+ elbowR: { x: -2.00, y: 0, z: 0 },
+ wristL: { x: -0.30, y: 0, z: 0 },
+ wristR: { x: -0.30, y: 0, z: 0 },
+ head: { x: 0, y: -0.20, z: -0.05 },
+ },
+ },
+ {
+ id: 'point',
+ label: 'Pointing',
+ group: 'Expressive',
+ pose: {
+ chest: { x: 0, y: 0.20, z: 0 },
+ shoulderL: { x: 0, y: 0, z: 0.15 },
+ shoulderR: { x: -HALF + 0.20, y: 0, z: -0.40 },
+ elbowR: { x: -0.10, y: 0, z: 0 },
+ wristR: { x: -0.15, y: 0, z: 0 },
+ head: { x: 0, y: -0.30, z: 0 },
+ },
+ },
+];
+
+export function getPresetById(id) {
+ return PRESETS.find((p) => p.id === id) || null;
+}
+
+export function getPresetsByGroup() {
+ const map = {};
+ for (const group of PRESET_GROUPS) map[group] = [];
+ for (const preset of PRESETS) {
+ if (!map[preset.group]) map[preset.group] = [];
+ map[preset.group].push(preset);
+ }
+ return map;
+}
diff --git a/src/pose-studio.js b/src/pose-studio.js
new file mode 100644
index 000000000..2b526fc04
--- /dev/null
+++ b/src/pose-studio.js
@@ -0,0 +1,605 @@
+// /pose — 3D pose-reference studio inspired by setpose.com. Builds a
+// Three.js scene with an articulated Mannequin, orbit camera, ground +
+// grid, and a control panel that lets the user pick presets, drag joints
+// to pose them, tweak sliders for fine control, swap body type, add floor
+// props, change lighting and FOV, and export a PNG screenshot.
+
+import {
+ AmbientLight,
+ BoxGeometry,
+ CircleGeometry,
+ Color,
+ CylinderGeometry,
+ DirectionalLight,
+ GridHelper,
+ Group,
+ HemisphereLight,
+ Mesh,
+ MeshStandardMaterial,
+ PCFSoftShadowMap,
+ PerspectiveCamera,
+ Raycaster,
+ Scene,
+ ShadowMaterial,
+ SphereGeometry,
+ Vector2,
+ Vector3,
+ WebGLRenderer,
+} from 'three';
+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+
+import { JOINT_AXIS_LABELS, JOINT_LABELS, Mannequin } from './pose-mannequin.js';
+import { PRESETS, getPresetsByGroup, getPresetById } from './pose-presets.js';
+
+// ─── DOM helpers ────────────────────────────────────────────────────────
+const $ = (sel) => document.querySelector(sel);
+const el = (tag, attrs = {}, children = []) => {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else if (v !== false && v != null) node.setAttribute(k, v);
+ }
+ for (const child of children) {
+ if (child == null) continue;
+ node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);
+ }
+ return node;
+};
+
+// ─── Floor props ────────────────────────────────────────────────────────
+// Simple primitive-based props the user can drop into the scene as drawing
+// references. Each prop is a function that returns a Group positioned so
+// its base sits on y = 0.
+const FLOOR_PROPS = {
+ none: { label: 'None', build: null },
+ chair: {
+ label: 'Chair',
+ build: () => {
+ const g = new Group();
+ const wood = new MeshStandardMaterial({ color: '#8b6f47', roughness: 0.8 });
+ const seat = new Mesh(new BoxGeometry(0.46, 0.05, 0.46), wood);
+ seat.position.y = 0.45;
+ seat.castShadow = true;
+ seat.receiveShadow = true;
+ g.add(seat);
+ const legGeom = new BoxGeometry(0.05, 0.45, 0.05);
+ for (const [x, z] of [[+0.19, +0.19], [+0.19, -0.19], [-0.19, +0.19], [-0.19, -0.19]]) {
+ const leg = new Mesh(legGeom, wood);
+ leg.position.set(x, 0.225, z);
+ leg.castShadow = true;
+ leg.receiveShadow = true;
+ g.add(leg);
+ }
+ const back = new Mesh(new BoxGeometry(0.46, 0.55, 0.04), wood);
+ back.position.set(0, 0.75, -0.22);
+ back.castShadow = true;
+ back.receiveShadow = true;
+ g.add(back);
+ return g;
+ },
+ },
+ stool: {
+ label: 'Stool',
+ build: () => {
+ const g = new Group();
+ const mat = new MeshStandardMaterial({ color: '#3f3f46', roughness: 0.6 });
+ const top = new Mesh(new CylinderGeometry(0.22, 0.22, 0.05, 24), mat);
+ top.position.y = 0.45;
+ top.castShadow = true;
+ top.receiveShadow = true;
+ g.add(top);
+ const post = new Mesh(new CylinderGeometry(0.04, 0.04, 0.42, 14), mat);
+ post.position.y = 0.21;
+ post.castShadow = true;
+ g.add(post);
+ const base = new Mesh(new CylinderGeometry(0.18, 0.20, 0.03, 24), mat);
+ base.position.y = 0.015;
+ base.receiveShadow = true;
+ g.add(base);
+ return g;
+ },
+ },
+ cube: {
+ label: 'Cube',
+ build: () => {
+ const g = new Group();
+ const mat = new MeshStandardMaterial({ color: '#ef4444', roughness: 0.7 });
+ const box = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), mat);
+ box.position.y = 0.25;
+ box.castShadow = true;
+ box.receiveShadow = true;
+ g.add(box);
+ return g;
+ },
+ },
+ ball: {
+ label: 'Ball',
+ build: () => {
+ const g = new Group();
+ const mat = new MeshStandardMaterial({ color: '#facc15', roughness: 0.5 });
+ const ball = new Mesh(new SphereGeometry(0.18, 24, 16), mat);
+ ball.position.y = 0.18;
+ ball.castShadow = true;
+ ball.receiveShadow = true;
+ g.add(ball);
+ return g;
+ },
+ },
+ plinth: {
+ label: 'Plinth',
+ build: () => {
+ const g = new Group();
+ const mat = new MeshStandardMaterial({ color: '#a8a29e', roughness: 0.85 });
+ const box = new Mesh(new BoxGeometry(0.7, 0.8, 0.7), mat);
+ box.position.y = 0.4;
+ box.castShadow = true;
+ box.receiveShadow = true;
+ g.add(box);
+ return g;
+ },
+ },
+};
+
+// ─── Scene setup ────────────────────────────────────────────────────────
+function setupScene(canvas, hudStatus) {
+ const scene = new Scene();
+ scene.background = new Color('#0b0b10');
+
+ const camera = new PerspectiveCamera(45, 1, 0.05, 100);
+ camera.position.set(2.2, 1.65, 3.0);
+
+ const renderer = new WebGLRenderer({
+ canvas,
+ antialias: true,
+ preserveDrawingBuffer: true, // needed for toDataURL screenshots
+ });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = PCFSoftShadowMap;
+
+ const controls = new OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.08;
+ controls.minDistance = 0.6;
+ controls.maxDistance = 12;
+ controls.maxPolarAngle = Math.PI * 0.96;
+ controls.target.set(0, 0.95, 0);
+
+ // Lighting — a hemisphere + key directional light produces the soft
+ // silhouette/shadow look that pose references need.
+ const hemi = new HemisphereLight('#f1f5f9', '#0a0a0f', 0.55);
+ scene.add(hemi);
+ const ambient = new AmbientLight('#ffffff', 0.18);
+ scene.add(ambient);
+
+ const key = new DirectionalLight('#ffffff', 1.4);
+ key.position.set(3, 5, 2.5);
+ key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048);
+ key.shadow.camera.near = 0.5;
+ key.shadow.camera.far = 18;
+ key.shadow.camera.left = -3.5;
+ key.shadow.camera.right = 3.5;
+ key.shadow.camera.top = 4;
+ key.shadow.camera.bottom = -1;
+ key.shadow.bias = -0.0008;
+ scene.add(key);
+
+ const fill = new DirectionalLight('#9bb1ff', 0.35);
+ fill.position.set(-2.5, 2, -2);
+ scene.add(fill);
+
+ // Ground — invisible shadow catcher + grid for reference.
+ const ground = new Mesh(new CircleGeometry(12, 64), new ShadowMaterial({ opacity: 0.35 }));
+ ground.rotation.x = -Math.PI / 2;
+ ground.position.y = 0;
+ ground.receiveShadow = true;
+ scene.add(ground);
+
+ const grid = new GridHelper(8, 32, 0x2a2a35, 0x1a1a22);
+ grid.position.y = 0.001;
+ scene.add(grid);
+
+ const propLayer = new Group();
+ scene.add(propLayer);
+
+ function resize() {
+ const w = canvas.clientWidth;
+ const h = canvas.clientHeight;
+ renderer.setSize(w, h, false);
+ camera.aspect = w / Math.max(1, h);
+ camera.updateProjectionMatrix();
+ }
+ window.addEventListener('resize', resize);
+ resize();
+
+ function setStatus(text, kind = 'info') {
+ if (!hudStatus) return;
+ hudStatus.textContent = text;
+ hudStatus.dataset.kind = kind;
+ }
+
+ return { scene, camera, renderer, controls, key, hemi, ambient, propLayer, setStatus };
+}
+
+// ─── State ──────────────────────────────────────────────────────────────
+const state = {
+ selectedJoint: null,
+ dragMode: 'bend', // 'bend' | 'tilt' | 'twist' | 'move'
+ dragging: null, // { joint, startX, startY, startRot }
+ prop: 'none',
+ propGroup: null,
+ keyLight: null,
+ keyAzimuth: 0.9, // radians around Y
+ keyElevation: 0.95, // radians from +Y down
+ keyDistance: 5.8,
+};
+
+// ─── App boot ───────────────────────────────────────────────────────────
+function boot() {
+ const canvas = $('#pose-canvas');
+ const hudStatus = $('#pose-status');
+ if (!canvas) {
+ console.error('[pose] missing #pose-canvas');
+ return;
+ }
+
+ const ctx = setupScene(canvas, hudStatus);
+ const { scene, camera, renderer, controls, key, propLayer, setStatus } = ctx;
+ state.keyLight = key;
+
+ const mannequin = new Mannequin({ build: 'male', color: '#d4d4d8' });
+ scene.add(mannequin.root);
+
+ // Pick a reasonable starting pose so the figure looks alive on load.
+ const intro = getPresetById('contrapposto');
+ if (intro) mannequin.applyPose(intro.pose);
+
+ // Render loop.
+ function tick() {
+ requestAnimationFrame(tick);
+ controls.update();
+ renderer.render(scene, camera);
+ }
+ tick();
+
+ // ── Raycast selection + drag-to-rotate ──────────────────────────────
+ const raycaster = new Raycaster();
+ const ndc = new Vector2();
+
+ function pickJointAt(clientX, clientY) {
+ const rect = canvas.getBoundingClientRect();
+ ndc.x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ ndc.y = -((clientY - rect.top) / rect.height) * 2 + 1;
+ raycaster.setFromCamera(ndc, camera);
+ const hits = raycaster.intersectObjects(mannequin.selectableMeshes, false);
+ if (!hits.length) return null;
+ return mannequin.jointFromHit(hits[0].object);
+ }
+
+ function selectJoint(name) {
+ state.selectedJoint = name;
+ renderControlsPanel();
+ updateSelectionLabel();
+ }
+
+ canvas.addEventListener('pointerdown', (ev) => {
+ // Left button only — right/middle stay with OrbitControls.
+ if (ev.button !== 0) return;
+ const joint = pickJointAt(ev.clientX, ev.clientY);
+ if (!joint) return;
+ selectJoint(joint);
+ if (state.dragMode === 'move') return;
+ controls.enabled = false;
+ const rot = mannequin.getJointRotation(joint);
+ state.dragging = {
+ joint,
+ startX: ev.clientX,
+ startY: ev.clientY,
+ startRot: { ...rot },
+ };
+ canvas.setPointerCapture(ev.pointerId);
+ ev.preventDefault();
+ });
+
+ canvas.addEventListener('pointermove', (ev) => {
+ const d = state.dragging;
+ if (!d) return;
+ const dx = (ev.clientX - d.startX) / 140;
+ const dy = (ev.clientY - d.startY) / 140;
+ const r = { ...d.startRot };
+ if (state.dragMode === 'bend') {
+ r.x = d.startRot.x + dy;
+ r.z = d.startRot.z + dx;
+ } else if (state.dragMode === 'tilt') {
+ r.z = d.startRot.z + dx;
+ r.x = d.startRot.x + dy * 0.3;
+ } else if (state.dragMode === 'twist') {
+ r.y = d.startRot.y + dx;
+ }
+ mannequin.setJointRotation(d.joint, 'x', r.x);
+ mannequin.setJointRotation(d.joint, 'y', r.y);
+ mannequin.setJointRotation(d.joint, 'z', r.z);
+ // Re-read so constraint clamping is reflected in the sliders.
+ if (state.selectedJoint === d.joint) renderControlsPanel();
+ });
+
+ function endDrag(ev) {
+ if (!state.dragging) return;
+ try { canvas.releasePointerCapture(ev.pointerId); } catch {}
+ state.dragging = null;
+ controls.enabled = true;
+ }
+ canvas.addEventListener('pointerup', endDrag);
+ canvas.addEventListener('pointercancel', endDrag);
+
+ // ── Controls panel rendering ────────────────────────────────────────
+ const sliderHost = $('#pose-controls-host');
+ const selectionLabel = $('#pose-selection-label');
+
+ function updateSelectionLabel() {
+ if (!selectionLabel) return;
+ selectionLabel.textContent = state.selectedJoint
+ ? JOINT_LABELS[state.selectedJoint] || state.selectedJoint
+ : 'Click a body part';
+ }
+
+ function renderControlsPanel() {
+ if (!sliderHost) return;
+ sliderHost.innerHTML = '';
+ const joint = state.selectedJoint;
+ if (!joint) {
+ sliderHost.appendChild(
+ el('p', { class: 'pose-hint' }, [
+ 'Click any body part in the scene, or pick a preset on the right, to start posing.',
+ ]),
+ );
+ return;
+ }
+ const rot = mannequin.getJointRotation(joint);
+ const axisLabels = JOINT_AXIS_LABELS[joint] || JOINT_AXIS_LABELS.default;
+ for (const axis of ['x', 'y', 'z']) {
+ const value = rot[axis];
+ const row = el('div', { class: 'pose-slider-row' }, [
+ el('label', {}, [`${axisLabels[axis]} (${axis.toUpperCase()})`]),
+ el('div', { class: 'pose-slider-value', 'data-axis': axis }, [
+ `${((value * 180) / Math.PI).toFixed(0)}°`,
+ ]),
+ ]);
+ const slider = el('input', {
+ type: 'range',
+ min: '-3.14159',
+ max: '3.14159',
+ step: '0.01',
+ value: String(value),
+ });
+ slider.addEventListener('input', () => {
+ const v = parseFloat(slider.value);
+ mannequin.setJointRotation(joint, axis, v);
+ const next = mannequin.getJointRotation(joint);
+ row.querySelector(`.pose-slider-value[data-axis="${axis}"]`).textContent =
+ `${((next[axis] * 180) / Math.PI).toFixed(0)}°`;
+ // If constraint clamped the value, snap the slider back.
+ slider.value = String(next[axis]);
+ });
+ row.appendChild(slider);
+ sliderHost.appendChild(row);
+ }
+ // Reset-this-joint button.
+ const resetBtn = el('button', {
+ class: 'pose-btn pose-btn-ghost',
+ type: 'button',
+ }, ['Reset this joint']);
+ resetBtn.addEventListener('click', () => {
+ mannequin.setJointRotation(joint, 'x', 0);
+ mannequin.setJointRotation(joint, 'y', 0);
+ mannequin.setJointRotation(joint, 'z', 0);
+ renderControlsPanel();
+ });
+ sliderHost.appendChild(resetBtn);
+ }
+ renderControlsPanel();
+ updateSelectionLabel();
+
+ // ── Joint-list quick picker (left panel) ────────────────────────────
+ const jointPicker = $('#pose-joint-picker');
+ if (jointPicker) {
+ const order = [
+ ['Head', ['head', 'neck']],
+ ['Torso', ['chest', 'spine', 'pelvis']],
+ ['Arms', ['shoulderL', 'elbowL', 'wristL', 'shoulderR', 'elbowR', 'wristR']],
+ ['Legs', ['hipL', 'kneeL', 'ankleL', 'hipR', 'kneeR', 'ankleR']],
+ ];
+ for (const [group, names] of order) {
+ jointPicker.appendChild(el('div', { class: 'pose-joint-group' }, [group]));
+ const row = el('div', { class: 'pose-joint-row' }, []);
+ for (const name of names) {
+ const btn = el('button', {
+ class: 'pose-joint-btn',
+ type: 'button',
+ 'data-joint': name,
+ }, [JOINT_LABELS[name] || name]);
+ btn.addEventListener('click', () => selectJoint(name));
+ row.appendChild(btn);
+ }
+ jointPicker.appendChild(row);
+ }
+ }
+
+ // ── Preset picker (right panel) ─────────────────────────────────────
+ const presetHost = $('#pose-presets-host');
+ if (presetHost) {
+ const grouped = getPresetsByGroup();
+ for (const [groupName, presets] of Object.entries(grouped)) {
+ if (!presets.length) continue;
+ presetHost.appendChild(el('div', { class: 'pose-preset-group' }, [groupName]));
+ const wrap = el('div', { class: 'pose-preset-grid' }, []);
+ for (const preset of presets) {
+ const btn = el('button', {
+ class: 'pose-preset-btn',
+ type: 'button',
+ 'data-preset': preset.id,
+ }, [preset.label]);
+ btn.addEventListener('click', () => {
+ mannequin.applyPose(preset.pose);
+ selectJoint(state.selectedJoint); // re-render sliders
+ setStatus(`Applied preset: ${preset.label}`);
+ });
+ wrap.appendChild(btn);
+ }
+ presetHost.appendChild(wrap);
+ }
+ }
+
+ // ── Top toolbar wiring ──────────────────────────────────────────────
+ const modeButtons = document.querySelectorAll('[data-mode]');
+ modeButtons.forEach((btn) => {
+ btn.addEventListener('click', () => {
+ state.dragMode = btn.dataset.mode;
+ modeButtons.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
+ });
+ });
+ const initialMode = document.querySelector(`[data-mode="${state.dragMode}"]`);
+ if (initialMode) initialMode.setAttribute('aria-pressed', 'true');
+
+ $('#pose-reset')?.addEventListener('click', () => {
+ mannequin.resetPose();
+ setStatus('Pose reset.');
+ renderControlsPanel();
+ });
+
+ $('#pose-screenshot')?.addEventListener('click', async () => {
+ // Force one synchronous render so the WebGL backbuffer is fresh
+ // before we grab a data URL (preserveDrawingBuffer keeps it valid).
+ renderer.render(scene, camera);
+ const url = canvas.toDataURL('image/png');
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `pose-${Date.now()}.png`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setStatus('Screenshot saved.');
+ });
+
+ $('#pose-export-json')?.addEventListener('click', () => {
+ const pose = mannequin.getPose();
+ const blob = new Blob([JSON.stringify(pose, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `pose-${Date.now()}.json`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ setStatus('Pose JSON saved.');
+ });
+
+ $('#pose-import-json')?.addEventListener('change', (ev) => {
+ const file = ev.target.files?.[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = () => {
+ try {
+ const pose = JSON.parse(String(reader.result));
+ mannequin.applyPose(pose);
+ renderControlsPanel();
+ setStatus(`Imported pose from ${file.name}.`);
+ } catch (err) {
+ setStatus(`Import failed: ${err.message}`, 'error');
+ }
+ };
+ reader.readAsText(file);
+ ev.target.value = '';
+ });
+
+ // ── Settings panel ──────────────────────────────────────────────────
+ $('#pose-build')?.addEventListener('change', (ev) => {
+ mannequin.setBuild(ev.target.value);
+ });
+
+ $('#pose-skin')?.addEventListener('input', (ev) => {
+ mannequin.setColor(ev.target.value);
+ });
+
+ $('#pose-bg')?.addEventListener('input', (ev) => {
+ scene.background = new Color(ev.target.value);
+ });
+
+ $('#pose-constraints')?.addEventListener('change', (ev) => {
+ mannequin.setConstraintsEnabled(ev.target.checked);
+ setStatus(ev.target.checked ? 'Biological constraints on.' : 'Constraints off — full rotation allowed.');
+ });
+
+ $('#pose-fov')?.addEventListener('input', (ev) => {
+ camera.fov = parseFloat(ev.target.value);
+ camera.updateProjectionMatrix();
+ });
+
+ $('#pose-grid')?.addEventListener('change', (ev) => {
+ ctx.scene.traverse((o) => {
+ if (o.isGridHelper) o.visible = ev.target.checked;
+ });
+ });
+
+ // Light direction — azimuth (around Y) and elevation. Distance fixed
+ // to the value set in state.keyDistance. Updating these moves the key
+ // light around the figure to change shadow direction.
+ function syncKeyLight() {
+ const r = state.keyDistance;
+ const az = state.keyAzimuth;
+ const el = state.keyElevation; // angle from horizon
+ const x = r * Math.cos(el) * Math.sin(az);
+ const z = r * Math.cos(el) * Math.cos(az);
+ const y = r * Math.sin(el);
+ state.keyLight.position.set(x, y, z);
+ state.keyLight.target.position.set(0, 0.9, 0);
+ state.keyLight.target.updateMatrixWorld();
+ }
+ syncKeyLight();
+
+ $('#pose-light-azimuth')?.addEventListener('input', (ev) => {
+ state.keyAzimuth = (parseFloat(ev.target.value) / 180) * Math.PI;
+ syncKeyLight();
+ });
+ $('#pose-light-elevation')?.addEventListener('input', (ev) => {
+ state.keyElevation = (parseFloat(ev.target.value) / 180) * Math.PI;
+ syncKeyLight();
+ });
+ $('#pose-light-intensity')?.addEventListener('input', (ev) => {
+ state.keyLight.intensity = parseFloat(ev.target.value);
+ });
+
+ // ── Floor props ─────────────────────────────────────────────────────
+ const propHost = $('#pose-prop-host');
+ if (propHost) {
+ for (const [id, def] of Object.entries(FLOOR_PROPS)) {
+ const btn = el('button', {
+ class: 'pose-prop-btn',
+ type: 'button',
+ 'data-prop': id,
+ 'aria-pressed': String(state.prop === id),
+ }, [def.label]);
+ btn.addEventListener('click', () => {
+ state.prop = id;
+ propLayer.clear();
+ if (def.build) {
+ const g = def.build();
+ propLayer.add(g);
+ state.propGroup = g;
+ }
+ document.querySelectorAll('[data-prop]').forEach((b) => {
+ b.setAttribute('aria-pressed', String(b.dataset.prop === id));
+ });
+ });
+ propHost.appendChild(btn);
+ }
+ }
+
+ setStatus('Ready. Click a body part to pose.');
+}
+
+document.addEventListener('DOMContentLoaded', boot);
diff --git a/src/runtime/speech.js b/src/runtime/speech.js
index 504aace05..45583c857 100644
--- a/src/runtime/speech.js
+++ b/src/runtime/speech.js
@@ -497,19 +497,37 @@ export class ElevenLabsTTS {
}
}
+const TTS_FACTORIES = {
+ none: () => null,
+ browser: (cfg) => new BrowserTTS(cfg),
+ elevenlabs: (cfg) => new ElevenLabsTTS(cfg),
+};
+
+const STT_FACTORIES = {
+ none: () => null,
+ browser: (cfg) => new BrowserSTT(cfg),
+};
+
export function createTTS(config = {}) {
const provider = config.provider || 'browser';
- if (provider === 'none') return null;
- if (provider === 'browser') return new BrowserTTS(config);
- if (provider === 'elevenlabs') return new ElevenLabsTTS(config);
- throw new Error(`TTS provider "${provider}" not implemented yet`);
+ const factory = TTS_FACTORIES[provider];
+ if (!factory) {
+ throw new Error(
+ `Unknown TTS provider "${provider}". Supported: ${Object.keys(TTS_FACTORIES).join(', ')}.`,
+ );
+ }
+ return factory(config);
}
export function createSTT(config = {}) {
const provider = config.provider || 'browser';
- if (provider === 'none') return null;
- if (provider === 'browser') return new BrowserSTT(config);
- throw new Error(`STT provider "${provider}" not implemented yet`);
+ const factory = STT_FACTORIES[provider];
+ if (!factory) {
+ throw new Error(
+ `Unknown STT provider "${provider}". Supported: ${Object.keys(STT_FACTORIES).join(', ')}.`,
+ );
+ }
+ return factory(config);
}
export async function createVoice(config = {}) {
diff --git a/src/solana/vanity/grinder-worker.js b/src/solana/vanity/grinder-worker.js
index eda6790e4..d26ea6184 100644
--- a/src/solana/vanity/grinder-worker.js
+++ b/src/solana/vanity/grinder-worker.js
@@ -1,58 +1,40 @@
/**
- * Vanity grinder Web Worker.
+ * Vanity grinder Web Worker — WASM backend.
*
- * Loops keypair generation and reports matches + progress back to the host.
- * The host owns the matcher predicate (passed as serialized config); this
- * worker only decides "does the base58 address match?".
+ * Loops keypair generation inside a WASM module (Rust + ed25519-dalek)
+ * and reports matches + progress back to the host. The hot loop runs
+ * entirely inside WASM in fixed-size batches; between batches the worker
+ * yields to its event loop so 'stop' messages from the host can be
+ * processed promptly (bounded abort latency).
*
* Algorithm parity with nirholas/solana-wallet-toolkit
- * (typescript/src/lib/generator.ts).
- *
- * Uses SubtleCrypto Ed25519 instead of @solana/web3.js so this file can be
- * served as a raw ES module (no bundler / import-map required).
+ * (typescript/src/lib/generator.ts). The WASM module is built from
+ * `/crates/vanity-grinder` via `npm run build:wasm`.
*/
-// ── Crypto helpers ────────────────────────────────────────────────────────────
-
-const _B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+import init, { grind } from './wasm/vanity_grinder.js';
+import wasmUrl from './wasm/vanity_grinder_bg.wasm?url';
-function _base58(bytes) {
- let n = 0n;
- for (const b of bytes) n = (n << 8n) | BigInt(b);
- let s = '';
- while (n > 0n) { s = _B58[Number(n % 58n)] + s; n /= 58n; }
- for (const b of bytes) { if (b) break; s = '1' + s; }
- return s;
-}
+// Keep batches small enough that one WASM call returns within ~200 ms even
+// on slow CPUs — abort latency is bounded by one batch.
+const BATCH_SIZE = 5000;
+const PROGRESS_INTERVAL_MS = 250;
-function _b64u(s) {
- return Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
-}
+let running = false;
+let wasmReady = null;
-async function _generateKeypair() {
- const { privateKey, publicKey } = await crypto.subtle.generateKey(
- { name: 'Ed25519' }, true, ['sign'],
- );
- const [privJwk, pubRaw] = await Promise.all([
- crypto.subtle.exportKey('jwk', privateKey),
- crypto.subtle.exportKey('raw', publicKey),
- ]);
- const pub = new Uint8Array(pubRaw);
- const sk = new Uint8Array(64);
- sk.set(_b64u(privJwk.d)); // 32-byte seed
- sk.set(pub, 32); // 32-byte public key
- return { address: _base58(pub), secretKey: sk };
+function ensureWasm() {
+ if (!wasmReady) {
+ wasmReady = init({ module_or_path: wasmUrl });
+ }
+ return wasmReady;
}
-const PROGRESS_INTERVAL = 5000;
-
-let running = false;
-
self.onmessage = (e) => {
const msg = e.data;
if (msg?.type === 'start') {
running = true;
- grind(msg.prefix || '', msg.suffix || '', !!msg.ignoreCase);
+ grindLoop(msg.prefix || '', msg.suffix || '', !!msg.ignoreCase);
} else if (msg?.type === 'stop') {
running = false;
}
@@ -63,46 +45,42 @@ self.onmessage = (e) => {
* @param {string} suffix
* @param {boolean} ignoreCase
*/
-async function grind(prefix, suffix, ignoreCase) {
- const wantPrefix = ignoreCase ? prefix.toLowerCase() : prefix;
- const wantSuffix = ignoreCase ? suffix.toLowerCase() : suffix;
- const pLen = prefix.length;
- const sLen = suffix.length;
+async function grindLoop(prefix, suffix, ignoreCase) {
+ try {
+ await ensureWasm();
+ } catch (err) {
+ self.postMessage({ type: 'error', message: String(err?.message || err) });
+ return;
+ }
let attempts = 0;
- let intervalStart = performance.now();
- let intervalAttempts = 0;
+ let lastProgress = performance.now();
+ let lastProgressAttempts = 0;
+ const seed = new Uint8Array(32);
while (running) {
- const { address, secretKey } = await _generateKeypair();
- attempts++;
- intervalAttempts++;
-
- const head = pLen
- ? (ignoreCase ? address.substring(0, pLen).toLowerCase() : address.substring(0, pLen))
- : '';
- const tail = sLen
- ? (ignoreCase ? address.slice(-sLen).toLowerCase() : address.slice(-sLen))
- : '';
+ crypto.getRandomValues(seed);
+ const hit = grind(prefix, suffix, ignoreCase, BATCH_SIZE, seed);
+ attempts += BATCH_SIZE;
- if ((!pLen || head === wantPrefix) && (!sLen || tail === wantSuffix)) {
+ if (hit) {
self.postMessage({
type: 'match',
- publicKey: address,
- secretKey,
+ publicKey: hit.publicKey,
+ secretKey: hit.secretKey,
attempts,
- }, [secretKey.buffer]);
+ }, [hit.secretKey.buffer]);
running = false;
return;
}
- if (intervalAttempts >= PROGRESS_INTERVAL) {
- const now = performance.now();
- const elapsed = (now - intervalStart) / 1000;
- const rate = elapsed > 0 ? intervalAttempts / elapsed : 0;
+ const now = performance.now();
+ if (now - lastProgress >= PROGRESS_INTERVAL_MS) {
+ const elapsed = (now - lastProgress) / 1000;
+ const rate = elapsed > 0 ? (attempts - lastProgressAttempts) / elapsed : 0;
self.postMessage({ type: 'progress', attempts, rate });
- intervalStart = now;
- intervalAttempts = 0;
+ lastProgress = now;
+ lastProgressAttempts = attempts;
// Yield to the event loop so 'stop' messages get processed.
await new Promise((r) => setTimeout(r, 0));
}
diff --git a/src/solana/vanity/grinder.js b/src/solana/vanity/grinder.js
index 5330a6f93..849e04e13 100644
--- a/src/solana/vanity/grinder.js
+++ b/src/solana/vanity/grinder.js
@@ -15,8 +15,9 @@
* The returned `secretKey` is a Uint8Array(64) — Solana's standard
* Ed25519 keypair format, compatible with `Keypair.fromSecretKey()`.
*
- * Algorithm parity with nirholas/solana-wallet-toolkit. WASM backend
- * (~10× faster) is a future optimization — see TODO at bottom.
+ * Each worker drives a WASM grinder (Rust + ed25519-dalek + bs58) built
+ * from `/crates/vanity-grinder`. Run `npm run build:wasm` after any Rust
+ * change to refresh `src/solana/vanity/wasm/`.
*/
import { validatePattern, estimateAttempts, formatTimeEstimate } from './validation.js';
@@ -134,8 +135,3 @@ export function grindVanity(opts = {}) {
}
});
}
-
-// TODO(perf): drop in a WASM grinder backed by the toolkit's Rust crate
-// (nirholas/solana-wallet-toolkit/rust). Expected ~10× over JS Keypair.generate().
-// Public API of grindVanity() is intentionally backend-agnostic so the swap is
-// transparent to callers.
diff --git a/src/solana/vanity/wasm/.gitignore b/src/solana/vanity/wasm/.gitignore
new file mode 100644
index 000000000..776e61c4a
--- /dev/null
+++ b/src/solana/vanity/wasm/.gitignore
@@ -0,0 +1,6 @@
+# wasm-pack writes a default `*` gitignore that excludes everything.
+# Override it: the generated files in this directory ARE checked in so the
+# app builds without requiring a Rust toolchain at install time. Run
+# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to
+# refresh these artifacts.
+!*
diff --git a/src/solana/vanity/wasm/README.md b/src/solana/vanity/wasm/README.md
new file mode 100644
index 000000000..8e8969c31
--- /dev/null
+++ b/src/solana/vanity/wasm/README.md
@@ -0,0 +1,39 @@
+# Generated WASM grinder
+
+This directory contains the wasm-bindgen output of [`/crates/vanity-grinder`](../../../../crates/vanity-grinder).
+
+**Do not edit by hand.** Edit the Rust source at `crates/vanity-grinder/src/lib.rs`,
+then regenerate with:
+
+```bash
+npm run build:wasm
+```
+
+The artifacts are checked into the repo so the app builds without a Rust
+toolchain at install time. CI / Vercel only need `npm install` + `npm run build`.
+
+## Files
+
+- `vanity_grinder.js` — wasm-bindgen glue (default export `init`, named export `grind`)
+- `vanity_grinder_bg.wasm` — the compiled WebAssembly module
+- `vanity_grinder.d.ts` — TypeScript declarations
+- `vanity_grinder_bg.wasm.d.ts` — low-level wasm imports declarations
+- `package.json` — generated package metadata (not published)
+
+## API
+
+```ts
+import init, { grind } from './vanity_grinder.js';
+import wasmUrl from './vanity_grinder_bg.wasm?url';
+
+await init({ module_or_path: wasmUrl });
+
+const seed = new Uint8Array(32);
+crypto.getRandomValues(seed);
+const hit = grind(prefix, suffix, ignoreCase, batchSize, seed);
+// hit is either null or { secretKey: Uint8Array(64), publicKey: string }
+```
+
+The 64-byte `secretKey` is Solana's standard layout
+(`[32-byte seed][32-byte public key]`), compatible with
+`Keypair.fromSecretKey()` in `@solana/web3.js`.
diff --git a/src/solana/vanity/wasm/package.json b/src/solana/vanity/wasm/package.json
new file mode 100644
index 000000000..2bcc6374e
--- /dev/null
+++ b/src/solana/vanity/wasm/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "vanity-grinder",
+ "type": "module",
+ "description": "WASM-backed Solana ed25519 vanity address grinder",
+ "version": "0.1.0",
+ "license": "MIT",
+ "files": [
+ "vanity_grinder_bg.wasm",
+ "vanity_grinder.js",
+ "vanity_grinder.d.ts"
+ ],
+ "main": "vanity_grinder.js",
+ "types": "vanity_grinder.d.ts",
+ "sideEffects": [
+ "./snippets/*"
+ ]
+}
\ No newline at end of file
diff --git a/src/solana/vanity/wasm/vanity_grinder.d.ts b/src/solana/vanity/wasm/vanity_grinder.d.ts
new file mode 100644
index 000000000..7a5c18c77
--- /dev/null
+++ b/src/solana/vanity/wasm/vanity_grinder.d.ts
@@ -0,0 +1,36 @@
+/* tslint:disable */
+/* eslint-disable */
+
+export function grind(prefix: string, suffix: string, ignore_case: boolean, batch: number, start_seed: Uint8Array): any;
+
+export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
+
+export interface InitOutput {
+ readonly memory: WebAssembly.Memory;
+ readonly grind: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => number;
+ readonly __wbindgen_export: (a: number, b: number) => number;
+ readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
+ readonly __wbindgen_export3: (a: number) => void;
+}
+
+export type SyncInitInput = BufferSource | WebAssembly.Module;
+
+/**
+ * Instantiates the given `module`, which can either be bytes or
+ * a precompiled `WebAssembly.Module`.
+ *
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
+ *
+ * @returns {InitOutput}
+ */
+export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
+
+/**
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
+ * for everything else, calls `WebAssembly.instantiate` directly.
+ *
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
+ *
+ * @returns {Promise<InitOutput>}
+ */
+export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
diff --git a/src/solana/vanity/wasm/vanity_grinder.js b/src/solana/vanity/wasm/vanity_grinder.js
new file mode 100644
index 000000000..2ec97e064
--- /dev/null
+++ b/src/solana/vanity/wasm/vanity_grinder.js
@@ -0,0 +1,358 @@
+/* @ts-self-types="./vanity_grinder.d.ts" */
+
+/**
+ * @param {string} prefix
+ * @param {string} suffix
+ * @param {boolean} ignore_case
+ * @param {number} batch
+ * @param {Uint8Array} start_seed
+ * @returns {any}
+ */
+export function grind(prefix, suffix, ignore_case, batch, start_seed) {
+ const ptr0 = passStringToWasm0(prefix, wasm.__wbindgen_export, wasm.__wbindgen_export2);
+ const len0 = WASM_VECTOR_LEN;
+ const ptr1 = passStringToWasm0(suffix, wasm.__wbindgen_export, wasm.__wbindgen_export2);
+ const len1 = WASM_VECTOR_LEN;
+ const ptr2 = passArray8ToWasm0(start_seed, wasm.__wbindgen_export);
+ const len2 = WASM_VECTOR_LEN;
+ const ret = wasm.grind(ptr0, len0, ptr1, len1, ignore_case, batch, ptr2, len2);
+ return takeObject(ret);
+}
+function __wbg_get_imports() {
+ const import0 = {
+ __proto__: null,
+ __wbg___wbindgen_debug_string_edece8177ad01481: function(arg0, arg1) {
+ const ret = debugString(getObject(arg1));
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
+ const len1 = WASM_VECTOR_LEN;
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
+ },
+ __wbg___wbindgen_throw_9c31b086c2b26051: function(arg0, arg1) {
+ throw new Error(getStringFromWasm0(arg0, arg1));
+ },
+ __wbg_length_56fcd3e2b7e0299d: function(arg0) {
+ const ret = getObject(arg0).length;
+ return ret;
+ },
+ __wbg_new_02d162bc6cf02f60: function() {
+ const ret = new Object();
+ return addHeapObject(ret);
+ },
+ __wbg_new_with_length_99887c91eae4abab: function(arg0) {
+ const ret = new Uint8Array(arg0 >>> 0);
+ return addHeapObject(ret);
+ },
+ __wbg_set_24d0fa9e104112f9: function(arg0, arg1, arg2) {
+ getObject(arg0).set(getArrayU8FromWasm0(arg1, arg2));
+ },
+ __wbg_set_a0e911be3da02782: function() { return handleError(function (arg0, arg1, arg2) {
+ const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));
+ return ret;
+ }, arguments); },
+ __wbindgen_cast_0000000000000001: function(arg0, arg1) {
+ // Cast intrinsic for `Ref(String) -> Externref`.
+ const ret = getStringFromWasm0(arg0, arg1);
+ return addHeapObject(ret);
+ },
+ __wbindgen_object_drop_ref: function(arg0) {
+ takeObject(arg0);
+ },
+ };
+ return {
+ __proto__: null,
+ "./vanity_grinder_bg.js": import0,
+ };
+}
+
+function addHeapObject(obj) {
+ if (heap_next === heap.length) heap.push(heap.length + 1);
+ const idx = heap_next;
+ heap_next = heap[idx];
+
+ heap[idx] = obj;
+ return idx;
+}
+
+function debugString(val) {
+ // primitive types
+ const type = typeof val;
+ if (type == 'number' || type == 'boolean' || val == null) {
+ return `${val}`;
+ }
+ if (type == 'string') {
+ return `"${val}"`;
+ }
+ if (type == 'symbol') {
+ const description = val.description;
+ if (description == null) {
+ return 'Symbol';
+ } else {
+ return `Symbol(${description})`;
+ }
+ }
+ if (type == 'function') {
+ const name = val.name;
+ if (typeof name == 'string' && name.length > 0) {
+ return `Function(${name})`;
+ } else {
+ return 'Function';
+ }
+ }
+ // objects
+ if (Array.isArray(val)) {
+ const length = val.length;
+ let debug = '[';
+ if (length > 0) {
+ debug += debugString(val[0]);
+ }
+ for(let i = 1; i < length; i++) {
+ debug += ', ' + debugString(val[i]);
+ }
+ debug += ']';
+ return debug;
+ }
+ // Test for built-in
+ const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
+ let className;
+ if (builtInMatches && builtInMatches.length > 1) {
+ className = builtInMatches[1];
+ } else {
+ // Failed to match the standard '[object ClassName]'
+ return toString.call(val);
+ }
+ if (className == 'Object') {
+ // we're a user defined class or Object
+ // JSON.stringify avoids problems with cycles, and is generally much
+ // easier than looping through ownProperties of `val`.
+ try {
+ return 'Object(' + JSON.stringify(val) + ')';
+ } catch (_) {
+ return 'Object';
+ }
+ }
+ // errors
+ if (val instanceof Error) {
+ return `${val.name}: ${val.message}\n${val.stack}`;
+ }
+ // TODO we could test for more things here, like `Set`s and `Map`s.
+ return className;
+}
+
+function dropObject(idx) {
+ if (idx < 1028) return;
+ heap[idx] = heap_next;
+ heap_next = idx;
+}
+
+function getArrayU8FromWasm0(ptr, len) {
+ ptr = ptr >>> 0;
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
+}
+
+let cachedDataViewMemory0 = null;
+function getDataViewMemory0() {
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
+ }
+ return cachedDataViewMemory0;
+}
+
+function getStringFromWasm0(ptr, len) {
+ return decodeText(ptr >>> 0, len);
+}
+
+let cachedUint8ArrayMemory0 = null;
+function getUint8ArrayMemory0() {
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
+ }
+ return cachedUint8ArrayMemory0;
+}
+
+function getObject(idx) { return heap[idx]; }
+
+function handleError(f, args) {
+ try {
+ return f.apply(this, args);
+ } catch (e) {
+ wasm.__wbindgen_export3(addHeapObject(e));
+ }
+}
+
+let heap = new Array(1024).fill(undefined);
+heap.push(undefined, null, true, false);
+
+let heap_next = heap.length;
+
+function passArray8ToWasm0(arg, malloc) {
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
+ getUint8ArrayMemory0().set(arg, ptr / 1);
+ WASM_VECTOR_LEN = arg.length;
+ return ptr;
+}
+
+function passStringToWasm0(arg, malloc, realloc) {
+ if (realloc === undefined) {
+ const buf = cachedTextEncoder.encode(arg);
+ const ptr = malloc(buf.length, 1) >>> 0;
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
+ WASM_VECTOR_LEN = buf.length;
+ return ptr;
+ }
+
+ let len = arg.length;
+ let ptr = malloc(len, 1) >>> 0;
+
+ const mem = getUint8ArrayMemory0();
+
+ let offset = 0;
+
+ for (; offset < len; offset++) {
+ const code = arg.charCodeAt(offset);
+ if (code > 0x7F) break;
+ mem[ptr + offset] = code;
+ }
+ if (offset !== len) {
+ if (offset !== 0) {
+ arg = arg.slice(offset);
+ }
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
+ const ret = cachedTextEncoder.encodeInto(arg, view);
+
+ offset += ret.written;
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
+ }
+
+ WASM_VECTOR_LEN = offset;
+ return ptr;
+}
+
+function takeObject(idx) {
+ const ret = getObject(idx);
+ dropObject(idx);
+ return ret;
+}
+
+let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
+cachedTextDecoder.decode();
+const MAX_SAFARI_DECODE_BYTES = 2146435072;
+let numBytesDecoded = 0;
+function decodeText(ptr, len) {
+ numBytesDecoded += len;
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
+ cachedTextDecoder.decode();
+ numBytesDecoded = len;
+ }
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
+}
+
+const cachedTextEncoder = new TextEncoder();
+
+if (!('encodeInto' in cachedTextEncoder)) {
+ cachedTextEncoder.encodeInto = function (arg, view) {
+ const buf = cachedTextEncoder.encode(arg);
+ view.set(buf);
+ return {
+ read: arg.length,
+ written: buf.length
+ };
+ };
+}
+
+let WASM_VECTOR_LEN = 0;
+
+let wasmModule, wasmInstance, wasm;
+function __wbg_finalize_init(instance, module) {
+ wasmInstance = instance;
+ wasm = instance.exports;
+ wasmModule = module;
+ cachedDataViewMemory0 = null;
+ cachedUint8ArrayMemory0 = null;
+ return wasm;
+}
+
+async function __wbg_load(module, imports) {
+ if (typeof Response === 'function' && module instanceof Response) {
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
+ try {
+ return await WebAssembly.instantiateStreaming(module, imports);
+ } catch (e) {
+ const validResponse = module.ok && expectedResponseType(module.type);
+
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
+
+ } else { throw e; }
+ }
+ }
+
+ const bytes = await module.arrayBuffer();
+ return await WebAssembly.instantiate(bytes, imports);
+ } else {
+ const instance = await WebAssembly.instantiate(module, imports);
+
+ if (instance instanceof WebAssembly.Instance) {
+ return { instance, module };
+ } else {
+ return instance;
+ }
+ }
+
+ function expectedResponseType(type) {
+ switch (type) {
+ case 'basic': case 'cors': case 'default': return true;
+ }
+ return false;
+ }
+}
+
+function initSync(module) {
+ if (wasm !== undefined) return wasm;
+
+
+ if (module !== undefined) {
+ if (Object.getPrototypeOf(module) === Object.prototype) {
+ ({module} = module)
+ } else {
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
+ }
+ }
+
+ const imports = __wbg_get_imports();
+ if (!(module instanceof WebAssembly.Module)) {
+ module = new WebAssembly.Module(module);
+ }
+ const instance = new WebAssembly.Instance(module, imports);
+ return __wbg_finalize_init(instance, module);
+}
+
+async function __wbg_init(module_or_path) {
+ if (wasm !== undefined) return wasm;
+
+
+ if (module_or_path !== undefined) {
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
+ ({module_or_path} = module_or_path)
+ } else {
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
+ }
+ }
+
+ if (module_or_path === undefined) {
+ module_or_path = new URL('vanity_grinder_bg.wasm', import.meta.url);
+ }
+ const imports = __wbg_get_imports();
+
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
+ module_or_path = fetch(module_or_path);
+ }
+
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
+
+ return __wbg_finalize_init(instance, module);
+}
+
+export { initSync, __wbg_init as default };
diff --git a/src/solana/vanity/wasm/vanity_grinder_bg.wasm b/src/solana/vanity/wasm/vanity_grinder_bg.wasm
new file mode 100644
index 000000000..594caf190
Binary files /dev/null and b/src/solana/vanity/wasm/vanity_grinder_bg.wasm differ
diff --git a/src/solana/vanity/wasm/vanity_grinder_bg.wasm.d.ts b/src/solana/vanity/wasm/vanity_grinder_bg.wasm.d.ts
new file mode 100644
index 000000000..67855d0e4
--- /dev/null
+++ b/src/solana/vanity/wasm/vanity_grinder_bg.wasm.d.ts
@@ -0,0 +1,7 @@
+/* tslint:disable */
+/* eslint-disable */
+export const memory: WebAssembly.Memory;
+export const grind: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => number;
+export const __wbindgen_export: (a: number, b: number) => number;
+export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
+export const __wbindgen_export3: (a: number) => void;
diff --git a/src/viewer.js b/src/viewer.js
index 7773b98eb..6f54fedde 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -89,7 +89,12 @@ export class Viewer {
toneMapping: LinearToneMapping,
ambientIntensity: 0.3,
ambientColor: '#FFFFFF',
- directIntensity: 0.8 * Math.PI, // TODO(#116)
+ // The 0.8 * π factor compensates for three.js's historical
+ // `irradiance *= PI` step on punctual lights and keeps direct
+ // lighting visually matched to the upstream three-gltf-viewer
+ // baseline. See donmccurdy/three-gltf-viewer#116 — closed as a
+ // question; removing π would require a shader-side adjustment.
+ directIntensity: 0.8 * Math.PI,
directColor: '#FFFFFF',
bgColor: '#000000',
transparentBg: false,
@@ -1184,7 +1189,8 @@ export class Viewer {
lightFolder.add(this.state, 'punctualLights').listen(),
lightFolder.add(this.state, 'ambientIntensity', 0, 2),
lightFolder.addColor(this.state, 'ambientColor'),
- lightFolder.add(this.state, 'directIntensity', 0, 4), // TODO(#116)
+ // Slider range tracks the π-scaled default above (see #116 note).
+ lightFolder.add(this.state, 'directIntensity', 0, 4),
lightFolder.addColor(this.state, 'directColor'),
].forEach((ctrl) => ctrl.onChange(() => this.updateLights()));
diff --git a/src/viewer/internal.js b/src/viewer/internal.js
index 53eeaa723..cc3483296 100644
--- a/src/viewer/internal.js
+++ b/src/viewer/internal.js
@@ -32,6 +32,19 @@ export function getDecoders() {
return _decodersPromise;
}
+// Focused helper for viewers that only load avatars baked through the
+// server-side pipeline. The bake emits EXT_meshopt_compression but never
+// KHR_draco_mesh_compression or KTX2 textures (textureCompress targets WebP),
+// so loading the heavier draco / ktx2 decoders would be wasted bytes.
+let _meshoptDecoderPromise = null;
+export function getMeshoptDecoder() {
+ if (_meshoptDecoderPromise) return _meshoptDecoderPromise;
+ _meshoptDecoderPromise = import('three/addons/libs/meshopt_decoder.module.js').then(
+ (m) => m.MeshoptDecoder,
+ );
+ return _meshoptDecoderPromise;
+}
+
export function traverseMaterials(object, callback) {
const seen = new Set();
object.traverse((node) => {
diff --git a/src/voice/talk-scene.js b/src/voice/talk-scene.js
index 498fcee72..6d8e5f213 100644
--- a/src/voice/talk-scene.js
+++ b/src/voice/talk-scene.js
@@ -21,6 +21,7 @@ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { computeFraming, CAMERA_PRESETS } from './camera-presets.js';
import { TalkEmotes } from './talk-emotes.js';
+import { getMeshoptDecoder } from '../viewer/internal.js';
export class TalkScene {
constructor() {
@@ -96,8 +97,10 @@ export class TalkScene {
this.controls.maxDistance = 6;
this.controls.update();
- // Load the GLB.
+ // Load the GLB. Baked avatars carry EXT_meshopt_compression; the
+ // loader can only decode them once the meshopt decoder is wired.
const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(await getMeshoptDecoder());
const gltf = await new Promise((resolve, reject) => {
loader.load(glbUrl, resolve, undefined, reject);
});
diff --git a/tests/agent-avatar-lipsync.test.js b/tests/agent-avatar-lipsync.test.js
index 57e4584b7..377d3be62 100644
--- a/tests/agent-avatar-lipsync.test.js
+++ b/tests/agent-avatar-lipsync.test.js
@@ -15,7 +15,7 @@
* plus the `none` no-op path and the disconnect/zero-out behaviour.
*/
-import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
+import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
// ARKit canonical viseme morph names (LipSyncAnalyser writes these).
const VISEMES = [
@@ -259,4 +259,124 @@ describe('AgentAvatar × LipSyncAnalyser — integration', () => {
expect(avatar._morphTarget.jawOpen ?? 0).toBe(0);
});
});
+
+ // ── Edge cases ─────────────────────────────────────────────────────────────
+ // The following four describes cover production scenarios the happy-path
+ // tests above don't reach: very short audio bursts, true silence (FFT floor),
+ // back-to-back utterances (state isolation across reconnect), and browsers
+ // without AnalyserNode (graceful no-op). See tests/agent-avatar-lipsync —
+ // each block targets one of those four behaviours.
+
+ describe('very short audio (< 200 ms)', () => {
+ it('after only ~5 frames, every viseme weight is a finite number in [0, 1]', () => {
+ const mesh = makeMesh([...VISEMES, 'jawOpen', 'mouthSmileLeft', 'browInnerUp']);
+ const { avatar, runStage5 } = makeAvatar({ meshes: [mesh] });
+
+ const analyser = new FakeAnalyserNode({ spectrum: makeBand(220, 0, 500) });
+ avatar.connectLipSync(analyser);
+ for (let i = 0; i < 5; i++) runStage5();
+
+ for (const v of VISEMES) {
+ const w = avatar._morphTarget[v] ?? 0;
+ expect(Number.isFinite(w)).toBe(true);
+ expect(w).toBeGreaterThanOrEqual(0);
+ expect(w).toBeLessThanOrEqual(1);
+ }
+ // Amplitude tracking should also be bounded and finite this early.
+ const amp = avatar._lipSync.getAmplitude();
+ expect(Number.isFinite(amp)).toBe(true);
+ expect(amp).toBeGreaterThanOrEqual(0);
+ expect(amp).toBeLessThanOrEqual(1);
+ });
+ });
+
+ describe('silence — all FFT bins read 0 from the start', () => {
+ it('every band-driven viseme stays ≤ 0.05 (no FFT-floor leakage to the mouth)', () => {
+ const mesh = makeMesh([...VISEMES, 'jawOpen', 'mouthSmileLeft', 'browInnerUp']);
+ const { avatar, runStage5 } = makeAvatar({ meshes: [mesh] });
+
+ const analyser = new FakeAnalyserNode({ spectrum: () => 0 });
+ avatar.connectLipSync(analyser);
+ for (let i = 0; i < 20; i++) runStage5();
+
+ // All three band groups (low → aa/O, mid → E/I/nn, high → SS/FF/CH)
+ // plus the bilabial PP must stay near zero — the small epsilon allows
+ // for the silence-branch lerp residual without permitting real motion.
+ for (const v of VISEMES) {
+ expect(avatar._morphTarget[v] ?? 0).toBeLessThanOrEqual(0.05);
+ }
+ expect(avatar._lipSync.getAmplitude()).toBeLessThanOrEqual(0.05);
+ });
+ });
+
+ describe('back-to-back utterances — no state bleed across reconnect', () => {
+ it('detach after utterance A, attach for utterance B → output reflects only B', () => {
+ const mesh = makeMesh([...VISEMES, 'jawOpen', 'mouthSmileLeft', 'browInnerUp']);
+ const { avatar, runStage5 } = makeAvatar({ meshes: [mesh] });
+
+ // Utterance A: low-frequency energy → drives viseme_aa up, viseme_SS stays cold.
+ const sourceA = new FakeAnalyserNode({ spectrum: makeBand(220, 0, 500) });
+ avatar.connectLipSync(sourceA);
+ for (let i = 0; i < 40; i++) runStage5();
+ expect(avatar._morphTarget.viseme_aa).toBeGreaterThan(avatar._morphTarget.viseme_SS);
+
+ // Tear down. AgentAvatar.disconnectLipSync() drops the analyser and zeros
+ // every viseme target — confirms detach side of the contract.
+ avatar.disconnectLipSync();
+ expect(avatar._lipSync).toBeNull();
+ for (const v of VISEMES) expect(avatar._morphTarget[v]).toBe(0);
+
+ // Re-attach with utterance B: high-frequency sibilant energy. The new
+ // LipSyncAnalyser instance must start with clean smoothing buffers —
+ // otherwise residual viseme_aa weight from A would survive the swap.
+ const sourceB = new FakeAnalyserNode({ spectrum: makeBand(220, 2000, 8000) });
+ avatar.connectLipSync(sourceB);
+ expect(avatar._lipSync._prevAmplitude).toBe(0);
+ for (const v of VISEMES) expect(avatar._lipSync._prev[v]).toBe(0);
+
+ for (let i = 0; i < 40; i++) runStage5();
+
+ // B's signal is sibilant, so viseme_SS must now dominate viseme_aa —
+ // the opposite ordering from utterance A. If A's state had bled through,
+ // viseme_aa would still carry weight from the first 40 frames.
+ expect(avatar._morphTarget.viseme_SS).toBeGreaterThan(avatar._morphTarget.viseme_aa);
+ });
+ });
+
+ describe('browser without AnalyserNode — graceful no-op', () => {
+ let savedAnalyserNode;
+ beforeEach(() => {
+ savedAnalyserNode = globalThis.AnalyserNode;
+ // Older Safari iOS lock-screen contexts and some embedded WebViews
+ // don't expose AnalyserNode. Simulate that here.
+ globalThis.AnalyserNode = undefined;
+ });
+ afterEach(() => {
+ globalThis.AnalyserNode = savedAnalyserNode;
+ });
+
+ it('connectLipSync + Stage 5 do not throw; mouth sits at rest (all zeros)', () => {
+ const mesh = makeMesh([...VISEMES, 'jawOpen', 'mouthSmileLeft', 'browInnerUp']);
+ const { avatar, runStage5 } = makeAvatar({ meshes: [mesh] });
+
+ // Even a structurally-valid analyser object can't pass `instanceof
+ // AnalyserNode` once the constructor is gone, so connect() returns
+ // early and the driver stays inactive — exactly the production fallback.
+ const source = new FakeAnalyserNode({ spectrum: makeBand(220, 0, 500) });
+
+ expect(() => avatar.connectLipSync(source)).not.toThrow();
+ expect(avatar._lipSync).not.toBeNull();
+ expect(avatar._lipSync._active).toBe(false);
+
+ expect(() => {
+ for (let i = 0; i < 5; i++) runStage5();
+ }).not.toThrow();
+
+ // Driver inactive → sample() returns null → Stage 5 writes nothing →
+ // mouth sits at rest at all the targets the lipsync path touches.
+ for (const v of VISEMES) expect(avatar._morphTarget[v] ?? 0).toBe(0);
+ expect(avatar._morphTarget.jawOpen ?? 0).toBe(0);
+ expect(avatar._morphTarget.mouthOpen ?? 0).toBe(0);
+ });
+ });
});
diff --git a/tests/api/auth-email.test.js b/tests/api/auth-email.test.js
index 5cc736070..160156f08 100644
--- a/tests/api/auth-email.test.js
+++ b/tests/api/auth-email.test.js
@@ -245,4 +245,56 @@ describe('POST /api/auth/register', () => {
expect(status).toBe(429);
expect(body.error).toBe('rate_limited');
});
+
+ it('retries when the first generated referral_code collides with the unique index', async () => {
+ // SELECT existing-user check → empty
+ sqlState.queue.push([]);
+ // First INSERT collides with the users_referral_code unique index.
+ const uniqueViolation = Object.assign(new Error(
+ 'duplicate key value violates unique constraint "users_referral_code_key"',
+ ), { code: '23505' });
+ sqlState.queue.push(uniqueViolation);
+ // Second INSERT succeeds.
+ sqlState.queue.push([{
+ id: 'user-new',
+ display_name: 'Carol',
+ plan: 'free',
+ created_at: '2024-01-01',
+ referral_code: 'SECONDOK',
+ }]);
+
+ const { status, body } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'supersecret123', display_name: 'Carol' },
+ });
+
+ expect(status).toBe(201);
+ expect(body.user.id).toBe('user-new');
+ expect(body.user.referral_code).toBe('SECONDOK');
+
+ // Two INSERTs attempted, each with a distinct referral_code (last value
+ // in the bound-parameters array). The CSPRNG should not repeat — and if
+ // it did, the handler would have surfaced the unique violation instead.
+ const inserts = sqlState.calls.filter((c) => /insert into users/.test(c.query));
+ expect(inserts).toHaveLength(2);
+ const firstCode = inserts[0].values.at(-1);
+ const secondCode = inserts[1].values.at(-1);
+ expect(typeof firstCode).toBe('string');
+ expect(firstCode).not.toBe(secondCode);
+ });
+
+ it('propagates non-collision insert errors instead of looping', async () => {
+ sqlState.queue.push([]); // no existing user
+ const fatal = Object.assign(new Error('connection terminated'), { code: '57P01' });
+ sqlState.queue.push(fatal);
+
+ const { status, body } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'supersecret123', display_name: 'Dora' },
+ });
+
+ expect(status).toBe(500);
+ const inserts = sqlState.calls.filter((c) => /insert into users/.test(c.query));
+ expect(inserts).toHaveLength(1);
+ });
});
diff --git a/tests/api/avatar-og.test.js b/tests/api/avatar-og.test.js
new file mode 100644
index 000000000..f174b3ca9
--- /dev/null
+++ b/tests/api/avatar-og.test.js
@@ -0,0 +1,288 @@
+// Integration tests for /api/avatar/:id/og.
+//
+// The renderer itself (puppeteer + chromium) is exercised in
+// tests/render-glb.test.js. Here we stub it at the module boundary and
+// assert the endpoint's responsibilities: cache-first redirect, fallback
+// rules, R2 + DB write-back on cache miss, in-memory concurrency lock.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+const getAvatarMock = vi.fn();
+const renderGlbToPngMock = vi.fn();
+const putObjectMock = vi.fn(async () => {});
+const publicUrlMock = vi.fn((k) => `https://cdn.test/${k}`);
+
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+vi.mock('../../api/_lib/avatars.js', () => ({ getAvatar: getAvatarMock }));
+vi.mock('../../api/_lib/render-glb.js', () => ({ renderGlbToPng: renderGlbToPngMock }));
+vi.mock('../../api/_lib/r2.js', () => ({ putObject: putObjectMock, publicUrl: publicUrlMock }));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000' },
+}));
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../../api/_lib/demo-avatars.js', () => ({
+ DEMO_AVATARS: [
+ { avatarId: 'avatar_demo_alice', name: 'Alice', description: 'A demo', tags: ['demo'] },
+ ],
+}));
+
+const { default: handler, __testInternals } = await import('../../api/avatar-og.js');
+
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+function mkReq({ url = '/api/avatar/avatar_demo_alice/og', method = 'GET', headers = {} } = {}) {
+ return { url, method, headers: { host: 'three.ws', ...headers } };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ _body: undefined,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(b) { this._body = b; this.writableEnded = true; },
+ };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ getAvatarMock.mockReset();
+ renderGlbToPngMock.mockReset();
+ putObjectMock.mockReset();
+ putObjectMock.mockResolvedValue(undefined);
+ publicUrlMock.mockReset();
+ publicUrlMock.mockImplementation((k) => `https://cdn.test/${k}`);
+ __testInternals._renderLocks.clear();
+});
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+describe('GET /api/avatar/:id/og — demo + 404 paths', () => {
+ it('returns SVG card for known demo avatar', async () => {
+ const req = mkReq({ url: '/api/avatar/avatar_demo_alice/og' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ expect(String(res._body)).toContain('Alice');
+ });
+
+ it('returns SVG 404 for unknown demo id', async () => {
+ const req = mkReq({ url: '/api/avatar/avatar_demo_nope/og' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ });
+
+ it('returns SVG 404 when DB lookup misses', async () => {
+ getAvatarMock.mockResolvedValueOnce(null);
+ const req = mkReq({ url: '/api/avatar/00000000-0000-0000-0000-000000000000/og' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ expect(getAvatarMock).toHaveBeenCalledWith({ id: '00000000-0000-0000-0000-000000000000' });
+ });
+
+ it('returns SVG card for private avatars (no model_url)', async () => {
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a1',
+ name: 'Private One',
+ description: 'shh',
+ thumbnail_url: null,
+ model_url: null,
+ storage_key: 'u/uid/x/abc.glb',
+ tags: [],
+ });
+ const req = mkReq({ url: '/api/avatar/a1/og' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ expect(String(res._body)).toContain('Private One');
+ expect(renderGlbToPngMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/avatar/:id/og — cached thumbnail path', () => {
+ it('302-redirects to thumbnail_url when set', async () => {
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a2',
+ name: 'X',
+ thumbnail_url: 'https://cdn.test/u/uid/x/abc_thumb.jpg',
+ model_url: 'https://cdn.test/u/uid/x/abc.glb',
+ storage_key: 'u/uid/x/abc.glb',
+ });
+ const req = mkReq({ url: '/api/avatar/a2/og' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(302);
+ expect(res._h.location).toBe('https://cdn.test/u/uid/x/abc_thumb.jpg');
+ expect(renderGlbToPngMock).not.toHaveBeenCalled();
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/avatar/:id/og — server render path', () => {
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+ beforeEach(() => {
+ // Stub the GLB HEAD request — content-length under the 10 MB cap.
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ headers: { get: (h) => (h.toLowerCase() === 'content-length' ? '1024' : null) },
+ }));
+ });
+
+ it('renders, uploads to R2, updates DB, streams PNG', async () => {
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a3',
+ name: 'Bob',
+ thumbnail_url: null,
+ model_url: 'https://cdn.test/u/uid/bob/123.glb',
+ storage_key: 'u/uid/bob/123.glb',
+ tags: [],
+ });
+ renderGlbToPngMock.mockResolvedValueOnce(PNG_MAGIC);
+
+ const req = mkReq({ url: '/api/avatar/a3/og' });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toBe('image/png');
+ expect(res._h['cache-control']).toMatch(/max-age/);
+ expect(res._body).toEqual(PNG_MAGIC);
+
+ // Renderer called with the avatar's GLB URL.
+ expect(renderGlbToPngMock).toHaveBeenCalledTimes(1);
+ expect(renderGlbToPngMock.mock.calls[0][0].glbUrl).toBe(
+ 'https://cdn.test/u/uid/bob/123.glb',
+ );
+
+ // R2 write: sibling key with _og.png suffix.
+ expect(putObjectMock).toHaveBeenCalledTimes(1);
+ expect(putObjectMock.mock.calls[0][0].key).toBe('u/uid/bob/123_og.png');
+ expect(putObjectMock.mock.calls[0][0].contentType).toBe('image/png');
+ expect(putObjectMock.mock.calls[0][0].body).toEqual(PNG_MAGIC);
+
+ // DB write: update statement was issued.
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ const sqlArgs = sqlMock.mock.calls[0];
+ expect(sqlArgs[0].join('?')).toMatch(/update avatars set thumbnail_key/);
+ expect(sqlArgs).toContain('u/uid/bob/123_og.png');
+ expect(sqlArgs).toContain('a3');
+ });
+
+ it('falls back to logo on GLB-too-large precheck', async () => {
+ // 50 MB content-length triggers the 10 MB cap.
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ headers: { get: (h) => (h.toLowerCase() === 'content-length' ? String(50 * 1024 * 1024) : null) },
+ }));
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a4',
+ name: 'Big',
+ thumbnail_url: null,
+ model_url: 'https://cdn.test/u/uid/big/123.glb',
+ storage_key: 'u/uid/big/123.glb',
+ });
+
+ const req = mkReq({ url: '/api/avatar/a4/og' });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(302);
+ expect(res._h.location).toMatch(/\/assets\/og-image\.png$/);
+ expect(renderGlbToPngMock).not.toHaveBeenCalled();
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('falls back to logo when the renderer throws', async () => {
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a5',
+ name: 'Err',
+ thumbnail_url: null,
+ model_url: 'https://cdn.test/u/uid/err/123.glb',
+ storage_key: 'u/uid/err/123.glb',
+ });
+ renderGlbToPngMock.mockRejectedValueOnce(new Error('chromium crashed'));
+
+ const req = mkReq({ url: '/api/avatar/a5/og' });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(302);
+ expect(res._h.location).toMatch(/\/assets\/og-image\.png$/);
+ expect(putObjectMock).not.toHaveBeenCalled();
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('serializes concurrent renders for the same avatar id', async () => {
+ const avatar = {
+ id: 'a6',
+ name: 'Once',
+ thumbnail_url: null,
+ model_url: 'https://cdn.test/u/uid/once/123.glb',
+ storage_key: 'u/uid/once/123.glb',
+ };
+ getAvatarMock.mockResolvedValue(avatar);
+
+ // Block the render until both requests have started.
+ let resolveRender;
+ renderGlbToPngMock.mockImplementation(
+ () => new Promise((resolve) => { resolveRender = resolve; }),
+ );
+
+ const req1 = mkReq({ url: '/api/avatar/a6/og' });
+ const req2 = mkReq({ url: '/api/avatar/a6/og' });
+ const res1 = mkRes();
+ const res2 = mkRes();
+ const p1 = handler(req1, res1);
+ const p2 = handler(req2, res2);
+ // Give microtasks a chance to hit the lock check.
+ await new Promise((r) => setImmediate(r));
+ resolveRender(PNG_MAGIC);
+ await Promise.all([p1, p2]);
+
+ // Renderer invoked once despite two concurrent requests.
+ expect(renderGlbToPngMock).toHaveBeenCalledTimes(1);
+ expect(putObjectMock).toHaveBeenCalledTimes(1);
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ // Both responses got the PNG.
+ expect(res1._body).toEqual(PNG_MAGIC);
+ expect(res2._body).toEqual(PNG_MAGIC);
+ expect(res1.statusCode).toBe(200);
+ expect(res2.statusCode).toBe(200);
+ });
+
+ it('uses forwarded host + proto for the fallback redirect origin', async () => {
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a7',
+ name: 'X',
+ thumbnail_url: null,
+ model_url: 'https://cdn.test/u/uid/x/x.glb',
+ storage_key: 'u/uid/x/x.glb',
+ });
+ renderGlbToPngMock.mockRejectedValueOnce(new Error('boom'));
+ const req = mkReq({
+ url: '/api/avatar/a7/og',
+ headers: {
+ host: 'three.ws',
+ 'x-forwarded-host': 'staging.three.ws',
+ 'x-forwarded-proto': 'https',
+ },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(302);
+ expect(res._h.location).toBe('https://staging.three.ws/assets/og-image.png');
+ });
+});
diff --git a/tests/api/healthz.test.js b/tests/api/healthz.test.js
index 942e27723..0545cc0df 100644
--- a/tests/api/healthz.test.js
+++ b/tests/api/healthz.test.js
@@ -1,13 +1,13 @@
-// Smoke test for /api/healthz. Stays free of any DB/RPC dependencies — this
-// endpoint is the canary that uptime probes will hit, so it must stay green
-// even when downstream systems are degraded.
+// Smoke + Resend-probe tests for /api/healthz. The handler dispatches its
+// Resend check against the real API in production; here we stub fetch and
+// assert the dispatch logic. No network calls leave the test.
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
-import healthz from '../../api/healthz.js';
+import healthz, { _resetResendCache } from '../../api/healthz.js';
function makeReq({ method = 'GET' } = {}) { return { url: '/api/healthz', method, headers: {} }; }
function makeRes() {
@@ -20,12 +20,30 @@ function makeRes() {
};
}
+async function callHealthz() {
+ const res = makeRes();
+ await healthz(makeReq(), res);
+ return { res, body: JSON.parse(res._body) };
+}
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ORIGINAL_KEY = process.env.RESEND_API_KEY;
+
+beforeEach(() => {
+ _resetResendCache();
+ delete process.env.RESEND_API_KEY;
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ if (ORIGINAL_KEY === undefined) delete process.env.RESEND_API_KEY;
+ else process.env.RESEND_API_KEY = ORIGINAL_KEY;
+});
+
describe('GET /api/healthz', () => {
it('returns 200 with status=ok and uptime fields', async () => {
- const res = makeRes();
- await healthz(makeReq(), res);
+ const { res, body } = await callHealthz();
expect(res.statusCode).toBe(200);
- const body = JSON.parse(res._body);
expect(body.status).toBe('ok');
expect(body.service).toBe('3d-agent');
expect(typeof body.uptime).toBe('number');
@@ -40,8 +58,83 @@ describe('GET /api/healthz', () => {
});
it('cache-control allows brief edge caching', async () => {
- const res = makeRes();
- await healthz(makeReq(), res);
+ const { res } = await callHealthz();
expect(res.getHeader('cache-control')).toMatch(/max-age=/);
});
});
+
+describe('GET /api/healthz — resend probe', () => {
+ it('reports "missing" when RESEND_API_KEY is unset', async () => {
+ globalThis.fetch = vi.fn(); // must not be called
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('missing');
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it('reports "configured" when Resend returns 200', async () => {
+ process.env.RESEND_API_KEY = 're_test_key';
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ text: async () => '',
+ }));
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('configured');
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ const [url, opts] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe('https://api.resend.com/domains');
+ expect(opts.headers.Authorization).toBe('Bearer re_test_key');
+ });
+
+ it('reports "configured" on 401 with restricted_api_key body (send-only key)', async () => {
+ process.env.RESEND_API_KEY = 're_restricted_key';
+ globalThis.fetch = vi.fn(async () => ({
+ ok: false,
+ status: 401,
+ text: async () => '{"name":"restricted_api_key","message":"send only"}',
+ }));
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('configured');
+ });
+
+ it('reports "key_invalid" on 401 without restricted_api_key body', async () => {
+ process.env.RESEND_API_KEY = 're_bad_key';
+ globalThis.fetch = vi.fn(async () => ({
+ ok: false,
+ status: 401,
+ text: async () => '{"name":"invalid_api_key","message":"nope"}',
+ }));
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('key_invalid');
+ });
+
+ it('reports "key_invalid" on a 500 from Resend', async () => {
+ process.env.RESEND_API_KEY = 're_test_key';
+ globalThis.fetch = vi.fn(async () => ({
+ ok: false,
+ status: 500,
+ text: async () => 'server error',
+ }));
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('key_invalid');
+ });
+
+ it('reports "key_invalid" when the fetch rejects (timeout / network error)', async () => {
+ process.env.RESEND_API_KEY = 're_test_key';
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('timeout');
+ });
+ const { body } = await callHealthz();
+ expect(body.resend).toBe('key_invalid');
+ });
+
+ it('caches the probe result for 5 minutes (no second fetch within the window)', async () => {
+ process.env.RESEND_API_KEY = 're_test_key';
+ globalThis.fetch = vi.fn(async () => ({ ok: true, status: 200, text: async () => '' }));
+ const first = await callHealthz();
+ const second = await callHealthz();
+ expect(first.body.resend).toBe('configured');
+ expect(second.body.resend).toBe('configured');
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tests/email.test.js b/tests/email.test.js
new file mode 100644
index 000000000..4be3cdcd2
--- /dev/null
+++ b/tests/email.test.js
@@ -0,0 +1,389 @@
+// Fixture-based tests for api/_lib/email.js — exercise every template and
+// the no-API-key short-circuit without mocking the Resend SDK.
+//
+// Module-level constants (FROM, REPLY, APP_URL) snapshot env at import time,
+// so each suite uses vi.resetModules() + dynamic import to load a fresh
+// instance with the env it wants to assert against.
+
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
+import { JSDOM } from 'jsdom';
+
+const TEST_ENV = {
+ EMAIL_FROM: 'three.ws <[email protected]>',
+ APP_ORIGIN: 'https://three.ws.test',
+};
+
+const RESEND_KEY = 'rk_test_fixture_value';
+
+async function loadEmail(envOverrides = {}) {
+ const merged = { ...TEST_ENV, ...envOverrides };
+ const saved = {};
+ for (const k of Object.keys(merged)) {
+ saved[k] = process.env[k];
+ if (merged[k] === null) delete process.env[k];
+ else process.env[k] = merged[k];
+ }
+ vi.resetModules();
+ const mod = await import('../api/_lib/email.js');
+ const restore = () => {
+ for (const k of Object.keys(merged)) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ };
+ return { mod, restore };
+}
+
+function parseHtml(html) {
+ const dom = new JSDOM(html, { contentType: 'text/html' });
+ return dom.window.document;
+}
+
+// Helper — sanity-check that the rendered HTML is a real, parseable document
+// with the basic transactional-email scaffolding (lang attr, charset meta,
+// viewport meta, <title>, <body>, single .card root). Used by every template.
+function assertCommonScaffolding(doc, expectedTitle) {
+ expect(doc.documentElement.tagName.toLowerCase()).toBe('html');
+ expect(doc.documentElement.getAttribute('lang')).toBe('en');
+ expect(doc.querySelector('meta[charset="utf-8"]')).not.toBeNull();
+ expect(doc.querySelector('meta[name="viewport"]')).not.toBeNull();
+ expect(doc.querySelector('title')).not.toBeNull();
+ expect(doc.querySelector('title').textContent).toBe(expectedTitle);
+ expect(doc.querySelector('body')).not.toBeNull();
+ expect(doc.querySelectorAll('div.card')).toHaveLength(1);
+}
+
+// Helper — every action link in the email must be an absolute https URL.
+// Catches the class of bug where APP_URL is unset and href becomes "/dashboard/".
+function assertAllLinksAbsoluteHttps(doc) {
+ const anchors = doc.querySelectorAll('a[href]');
+ expect(anchors.length).toBeGreaterThan(0);
+ for (const a of anchors) {
+ const href = a.getAttribute('href');
+ expect(href).toMatch(/^https:\/\//);
+ }
+}
+
+// ─── Welcome template ────────────────────────────────────────────────────────
+
+describe('email — welcome template', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail());
+ });
+ afterAll(() => restore());
+
+ it('renderWelcome includes the recipient display name and dashboard link', () => {
+ const { subject, html, text } = mod.renderWelcome({ displayName: 'Alice' });
+ expect(subject).toBe('Welcome to three.ws');
+ expect(html).toContain('Welcome, Alice');
+ expect(text).toContain('Welcome to three.ws, Alice');
+ expect(html).toContain('https://three.ws.test/dashboard/');
+ expect(text).toContain('https://three.ws.test/dashboard/');
+ });
+
+ it('falls back to "there" when displayName is missing', () => {
+ const { html, text } = mod.renderWelcome({});
+ expect(html).toContain('Welcome, there');
+ expect(text).toContain('Welcome to three.ws, there');
+ });
+
+ it('html-escapes the display name to prevent injection', () => {
+ const { html } = mod.renderWelcome({ displayName: '<script>x</script>' });
+ expect(html).not.toContain('<script>x</script>');
+ expect(html).toContain('&lt;script&gt;x&lt;/script&gt;');
+ });
+
+ it('produces parseable HTML with the expected scaffolding', () => {
+ const { html } = mod.renderWelcome({ displayName: 'Bob' });
+ const doc = parseHtml(html);
+ assertCommonScaffolding(doc, 'Welcome to three.ws');
+ assertAllLinksAbsoluteHttps(doc);
+ expect(doc.querySelector('h1').textContent).toContain('Welcome, Bob');
+ });
+});
+
+// ─── Verify template ─────────────────────────────────────────────────────────
+
+describe('email — verification template', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail());
+ });
+ afterAll(() => restore());
+
+ it('renderVerify embeds the code and expiry in subject/html/text', () => {
+ const { subject, html, text } = mod.renderVerify({ code: '482913', expiresInMinutes: 30 });
+ expect(subject).toBe('482913 — verify your email');
+ expect(html).toContain('482913');
+ expect(html).toContain('30 minutes');
+ expect(text).toContain('482913');
+ expect(text).toContain('30 minutes');
+ });
+
+ it('defaults expiresInMinutes to 30', () => {
+ const { html } = mod.renderVerify({ code: '000000' });
+ expect(html).toContain('30 minutes');
+ });
+
+ it('html-escapes the code', () => {
+ const { html } = mod.renderVerify({ code: '<x>' });
+ expect(html).toContain('&lt;x&gt;');
+ expect(html).not.toContain('<div class="code"><x>');
+ });
+
+ it('produces parseable HTML with the verify scaffolding', () => {
+ const { html } = mod.renderVerify({ code: '482913', expiresInMinutes: 15 });
+ const doc = parseHtml(html);
+ assertCommonScaffolding(doc, 'Verify your email');
+ expect(doc.querySelector('div.code').textContent).toBe('482913');
+ expect(doc.querySelector('h1').textContent).toBe('Verify your email');
+ });
+});
+
+// ─── Password reset template ─────────────────────────────────────────────────
+
+describe('email — password reset template', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail());
+ });
+ afterAll(() => restore());
+
+ const url = 'https://three.ws.test/reset-password?token=abcdef1234567890';
+
+ it('renderPasswordReset embeds the reset URL and expiry', () => {
+ const { subject, html, text } = mod.renderPasswordReset({ resetUrl: url, expiresInMinutes: 60 });
+ expect(subject).toBe('Reset your three.ws password');
+ expect(html).toContain(url);
+ expect(html).toContain('60 minutes');
+ expect(text).toContain(url);
+ expect(text).toContain('60 minutes');
+ });
+
+ it('defaults expiresInMinutes to 60', () => {
+ const { html } = mod.renderPasswordReset({ resetUrl: url });
+ expect(html).toContain('60 minutes');
+ });
+
+ it('escapes the reset URL in the href attribute (defence in depth)', () => {
+ const { html } = mod.renderPasswordReset({ resetUrl: 'https://example.test/r?token=a"b&c<' });
+ expect(html).toContain('&quot;');
+ expect(html).toContain('&amp;');
+ expect(html).toContain('&lt;');
+ });
+
+ it('renders the action button as an absolute https link', () => {
+ const { html } = mod.renderPasswordReset({ resetUrl: url });
+ const doc = parseHtml(html);
+ assertCommonScaffolding(doc, 'Reset your three.ws password');
+ const btn = doc.querySelector('a.btn');
+ expect(btn).not.toBeNull();
+ expect(btn.getAttribute('href')).toBe(url);
+ expect(btn.textContent).toBe('Reset password');
+ });
+});
+
+// ─── Subscription confirm template ───────────────────────────────────────────
+
+describe('email — subscription confirmation template', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail());
+ });
+ afterAll(() => restore());
+
+ it('renderSubscriptionConfirm includes plan, chain, and transaction id', () => {
+ const { subject, html, text } = mod.renderSubscriptionConfirm({
+ plan: 'pro',
+ chain: 'solana',
+ txId: '5a3xJv8K9LmNbqRtUvWxYz1234567890abcdefghijklmno',
+ });
+ expect(subject).toBe('three.ws Pro plan activated');
+ expect(html).toContain('Pro plan activated');
+ expect(html).toContain('Solana');
+ expect(html).toContain('5a3xJv8K9LmNbqRtUvWxYz1234567890abcdefghijklmno');
+ expect(text).toContain('pro plan');
+ expect(text).toContain('solana');
+ expect(text).toContain('5a3xJv8K9LmNbqRtUvWxYz1234567890abcdefghijklmno');
+ });
+
+ it('omits the transaction row when txId is empty', () => {
+ const { html } = mod.renderSubscriptionConfirm({ plan: 'pro', chain: 'evm', txId: '' });
+ expect(html).not.toContain('Transaction:');
+ });
+
+ it('html-escapes the transaction id', () => {
+ const { html } = mod.renderSubscriptionConfirm({ plan: 'pro', chain: 'evm', txId: '<tx>' });
+ expect(html).toContain('&lt;tx&gt;');
+ });
+
+ it('produces parseable HTML with the subscription scaffolding', () => {
+ const { html } = mod.renderSubscriptionConfirm({ plan: 'creator', chain: 'evm', txId: '0xabc' });
+ const doc = parseHtml(html);
+ assertCommonScaffolding(doc, 'Creator plan activated');
+ assertAllLinksAbsoluteHttps(doc);
+ const btn = doc.querySelector('a.btn');
+ expect(btn.textContent).toBe('Go to Dashboard');
+ expect(btn.getAttribute('href')).toBe('https://three.ws.test/dashboard/');
+ });
+});
+
+// ─── buildPayload ────────────────────────────────────────────────────────────
+
+describe('email — buildPayload', () => {
+ it('constructs the Resend payload with from/to/subject/html/text', async () => {
+ const { mod, restore } = await loadEmail();
+ try {
+ const payload = mod.buildPayload({
+ subject: 'hi',
+ html: '<p>hi</p>',
+ text: 'hi',
+ });
+ expect(payload).toEqual({
+ from: 'three.ws <[email protected]>',
+ subject: 'hi',
+ html: '<p>hi</p>',
+ text: 'hi',
+ });
+ expect(payload).not.toHaveProperty('replyTo');
+ } finally {
+ restore();
+ }
+ });
+
+ it('includes replyTo only when EMAIL_REPLY_TO is set', async () => {
+ const { mod, restore } = await loadEmail({ EMAIL_REPLY_TO: '[email protected]' });
+ try {
+ const payload = mod.buildPayload({
+ subject: 'hi',
+ html: '<p>hi</p>',
+ text: 'hi',
+ });
+ expect(payload.replyTo).toBe('[email protected]');
+ expect(payload.from).toBe('three.ws <[email protected]>');
+ } finally {
+ restore();
+ }
+ });
+
+ it('falls back to the default sender when EMAIL_FROM is unset', async () => {
+ const { mod, restore } = await loadEmail({ EMAIL_FROM: null });
+ try {
+ const payload = mod.buildPayload({
+ subject: 'hi',
+ html: '<p>hi</p>',
+ text: 'hi',
+ });
+ expect(payload.from).toBe('three.ws <[email protected]>');
+ } finally {
+ restore();
+ }
+ });
+});
+
+// ─── sendEmail no-API-key short-circuit ──────────────────────────────────────
+
+describe('email — sendEmail short-circuits when RESEND_API_KEY is unset', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail({ RESEND_API_KEY: null }));
+ });
+ afterAll(() => restore());
+
+ it('sendEmail returns the documented skipped shape', async () => {
+ const result = await mod.sendEmail({
+ subject: 'hi',
+ html: '<p>hi</p>',
+ text: 'hi',
+ });
+ expect(result).toEqual({ skipped: true, reason: 'missing_api_key' });
+ });
+
+ it('sendWelcomeEmail skips without throwing', async () => {
+ await expect(
+ mod.sendWelcomeEmail({ to: '[email protected]', displayName: 'A' }),
+ ).resolves.toEqual({ skipped: true, reason: 'missing_api_key' });
+ });
+
+ it('sendVerificationEmail skips without throwing', async () => {
+ await expect(
+ mod.sendVerificationEmail({ to: '[email protected]', code: '123456' }),
+ ).resolves.toEqual({ skipped: true, reason: 'missing_api_key' });
+ });
+
+ it('sendPasswordResetEmail skips without throwing', async () => {
+ await expect(
+ mod.sendPasswordResetEmail({
+ resetUrl: 'https://three.ws.test/reset-password?token=x',
+ }),
+ ).resolves.toEqual({ skipped: true, reason: 'missing_api_key' });
+ });
+
+ it('sendSubscriptionConfirmEmail skips without throwing', async () => {
+ await expect(
+ mod.sendSubscriptionConfirmEmail({
+ plan: 'pro',
+ chain: 'solana',
+ txId: 'tx-id-1',
+ }),
+ ).resolves.toEqual({ skipped: true, reason: 'missing_api_key' });
+ });
+});
+
+// ─── End-to-end payload assembly through send* wrappers ──────────────────────
+// With RESEND_API_KEY set, every template wrapper should compose the same
+// payload buildPayload produces. We assert by reconstructing the payload from
+// the renderer output — proves the wrapper and the renderer agree, without
+// any network call or Resend mock.
+
+describe('email — template wrappers compose payloads via buildPayload', () => {
+ let mod, restore;
+ beforeAll(async () => {
+ ({ mod, restore } = await loadEmail({ RESEND_API_KEY: RESEND_KEY }));
+ });
+ afterAll(() => restore());
+
+ it('welcome payload', () => {
+ const rendered = mod.renderWelcome({ displayName: 'Alice' });
+ const payload = mod.buildPayload({ to: '[email protected]', ...rendered });
+ expect(payload.subject).toBe('Welcome to three.ws');
+ expect(payload.html).toContain('Welcome, Alice');
+ expect(payload.text).toContain('Welcome to three.ws, Alice');
+ expect(payload.to).toBe('[email protected]');
+ expect(payload.from).toBe('three.ws <[email protected]>');
+ });
+
+ it('verify payload', () => {
+ const rendered = mod.renderVerify({ code: '482913', expiresInMinutes: 30 });
+ const payload = mod.buildPayload({ to: '[email protected]', ...rendered });
+ expect(payload.subject).toBe('482913 — verify your email');
+ expect(payload.html).toContain('482913');
+ expect(payload.text).toContain('482913');
+ });
+
+ it('password reset payload', () => {
+ const url = 'https://three.ws.test/reset-password?token=abc';
+ const rendered = mod.renderPasswordReset({ resetUrl: url, expiresInMinutes: 60 });
+ const payload = mod.buildPayload({ to: '[email protected]', ...rendered });
+ expect(payload.subject).toBe('Reset your three.ws password');
+ expect(payload.html).toContain(url);
+ expect(payload.text).toContain(url);
+ });
+
+ it('subscription payload', () => {
+ const rendered = mod.renderSubscriptionConfirm({ plan: 'pro', chain: 'solana', txId: 'tx-1' });
+ const payload = mod.buildPayload({ to: '[email protected]', ...rendered });
+ expect(payload.subject).toBe('three.ws Pro plan activated');
+ expect(payload.html).toContain('Pro plan activated');
+ expect(payload.html).toContain('Solana');
+ expect(payload.html).toContain('tx-1');
+ });
+});
diff --git a/tests/pump-swap-ix.test.js b/tests/pump-swap-ix.test.js
new file mode 100644
index 000000000..f5e290a6d
--- /dev/null
+++ b/tests/pump-swap-ix.test.js
@@ -0,0 +1,330 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import BN from 'bn.js';
+import { PublicKey } from '@solana/web3.js';
+import {
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ NATIVE_MINT,
+ TOKEN_PROGRAM_ID,
+ getAssociatedTokenAddressSync,
+} from '@solana/spl-token';
+
+// ── Module-level mocks ─────────────────────────────────────────────────────
+//
+// We mock `@pump-fun/pump-sdk` to control the curve / global decoder return
+// values without having to encode synthetic Anchor account buffers. PDAs and
+// program-id constants stay real — those are pure functions.
+
+const mockDecodeGlobal = vi.fn();
+const mockDecodeFeeConfig = vi.fn();
+const mockDecodeBondingCurve = vi.fn();
+const mockGetBuyTokenAmount = vi.fn();
+
+vi.mock('@pump-fun/pump-sdk', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PUMP_SDK: {
+ decodeGlobal: (...a) => mockDecodeGlobal(...a),
+ decodeFeeConfig: (...a) => mockDecodeFeeConfig(...a),
+ decodeBondingCurve: (...a) => mockDecodeBondingCurve(...a),
+ },
+ getBuyTokenAmountFromSolAmount: (...a) => mockGetBuyTokenAmount(...a),
+ };
+});
+
+// Import the module under test AFTER the mock registers.
+const {
+ buildPumpSwapInnerIx,
+ BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR,
+ PUMP_PROGRAM_ID,
+} = await import('../api/_lib/pump-swap-ix.js');
+const {
+ GLOBAL_PDA,
+ GLOBAL_VOLUME_ACCUMULATOR_PDA,
+ PUMP_EVENT_AUTHORITY_PDA,
+ PUMP_FEE_CONFIG_PDA,
+ PUMP_FEE_PROGRAM_ID,
+ bondingCurvePda,
+ creatorVaultPda,
+ feeSharingConfigPda,
+ userVolumeAccumulatorPda,
+} = await import('@pump-fun/pump-sdk');
+const { getBuybackAuthorityPDA } = await import('@pump-fun/agent-payments-sdk');
+
+// ── Fixtures ───────────────────────────────────────────────────────────────
+
+// Real-shaped pubkeys so PDA derivations stay deterministic across runs.
+const MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC mainnet — stand-in
+const CURRENCY = new PublicKey('So11111111111111111111111111111111111111112'); // wSOL
+const CREATOR = new PublicKey('11111111111111111111111111111111');
+const FEE_RECIPIENT = new PublicKey('5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD');
+
+function fakeAccountInfo(owner) {
+ return {
+ owner: owner ?? TOKEN_PROGRAM_ID,
+ lamports: 1,
+ executable: false,
+ rentEpoch: 0,
+ data: Buffer.alloc(8),
+ };
+}
+
+function fakeConnection({ baseOwner = TOKEN_PROGRAM_ID, quoteOwner = TOKEN_PROGRAM_ID } = {}) {
+ return {
+ getMultipleAccountsInfo: vi.fn(async () => [
+ fakeAccountInfo(), // global
+ fakeAccountInfo(), // feeConfig
+ fakeAccountInfo(), // bondingCurve
+ fakeAccountInfo(baseOwner), // base mint
+ fakeAccountInfo(quoteOwner), // quote mint
+ ]),
+ };
+}
+
+function setDecodedDefaults() {
+ mockDecodeGlobal.mockReturnValue({
+ feeRecipient: FEE_RECIPIENT,
+ feeRecipients: [],
+ reservedFeeRecipient: FEE_RECIPIENT,
+ reservedFeeRecipients: [],
+ });
+ mockDecodeFeeConfig.mockReturnValue(null);
+ mockDecodeBondingCurve.mockReturnValue({
+ complete: false,
+ creator: CREATOR,
+ quoteMint: CURRENCY,
+ isMayhemMode: false,
+ tokenTotalSupply: new BN('1000000000000000'),
+ virtualQuoteReserves: new BN('1000000000'),
+ virtualTokenReserves: new BN('800000000000000'),
+ });
+ mockGetBuyTokenAmount.mockReturnValue(new BN('5000000'));
+}
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+describe('buildPumpSwapInnerIx', () => {
+ beforeEach(() => {
+ mockDecodeGlobal.mockReset();
+ mockDecodeFeeConfig.mockReset();
+ mockDecodeBondingCurve.mockReset();
+ mockGetBuyTokenAmount.mockReset();
+ setDecodedDefaults();
+ // Deterministic random for fee-recipient picks.
+ vi.spyOn(Math, 'random').mockReturnValue(0);
+ });
+
+ it('returns 24-byte data starting with the buy_exact_quote_in_v2 discriminator', async () => {
+ const { data } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: new BN('1000000'),
+ minAmountOut: new BN('900000'),
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+
+ expect(data.length).toBe(24);
+ const disc = data.subarray(0, 8);
+ expect(Buffer.compare(disc, BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR)).toBe(0);
+ // Sanity-check the documented byte values too.
+ expect(Array.from(disc)).toEqual([194, 171, 28, 70, 104, 77, 91, 47]);
+ });
+
+ it('encodes amountIn as u64 LE at byte offset 8', async () => {
+ const amountIn = 1234567890n;
+ const { data } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn,
+ minAmountOut: new BN('0'),
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ expect(data.readBigUInt64LE(8)).toBe(amountIn);
+ });
+
+ it('encodes min_tokens_out as u64 LE at byte offset 16 — verbatim when provided', async () => {
+ const minOut = 4242424242n;
+ const { data, minTokensOut } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ minAmountOut: minOut,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ expect(data.readBigUInt64LE(16)).toBe(minOut);
+ expect(minTokensOut.toString()).toBe(minOut.toString());
+ });
+
+ it('derives min_tokens_out from slippageBps when minAmountOut is omitted', async () => {
+ // Mocked quote returns 5_000_000. 5% slippage → floor = 4_750_000.
+ const { data, minTokensOut } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ slippageBps: 500,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ expect(data.readBigUInt64LE(16)).toBe(4_750_000n);
+ expect(minTokensOut.toString()).toBe('4750000');
+ });
+
+ it('returns exactly 27 AccountMeta entries in the program-required order', async () => {
+ const { accounts } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+
+ expect(accounts).toHaveLength(27);
+
+ const bcAddr = bondingCurvePda(MINT);
+ const [burnAuthority] = getBuybackAuthorityPDA(MINT);
+ const burnMintVault = getAssociatedTokenAddressSync(MINT, burnAuthority, true, TOKEN_PROGRAM_ID);
+ const burnCurrencyMintVault = getAssociatedTokenAddressSync(CURRENCY, burnAuthority, true, TOKEN_PROGRAM_ID);
+ const userVolAcc = userVolumeAccumulatorPda(burnAuthority);
+
+ // Index-by-index key positions per IDL.
+ expect(accounts[0].pubkey.equals(GLOBAL_PDA)).toBe(true);
+ expect(accounts[1].pubkey.equals(MINT)).toBe(true);
+ expect(accounts[2].pubkey.equals(CURRENCY)).toBe(true);
+ expect(accounts[3].pubkey.equals(TOKEN_PROGRAM_ID)).toBe(true);
+ expect(accounts[4].pubkey.equals(TOKEN_PROGRAM_ID)).toBe(true);
+ expect(accounts[5].pubkey.equals(ASSOCIATED_TOKEN_PROGRAM_ID)).toBe(true);
+ expect(accounts[6].pubkey.equals(FEE_RECIPIENT)).toBe(true);
+ expect(accounts[10].pubkey.equals(bcAddr)).toBe(true);
+ expect(accounts[13].pubkey.equals(burnAuthority)).toBe(true);
+ expect(accounts[14].pubkey.equals(burnMintVault)).toBe(true);
+ expect(accounts[15].pubkey.equals(burnCurrencyMintVault)).toBe(true);
+ expect(accounts[16].pubkey.equals(creatorVaultPda(CREATOR))).toBe(true);
+ expect(accounts[18].pubkey.equals(feeSharingConfigPda(MINT))).toBe(true);
+ expect(accounts[19].pubkey.equals(GLOBAL_VOLUME_ACCUMULATOR_PDA)).toBe(true);
+ expect(accounts[20].pubkey.equals(userVolAcc)).toBe(true);
+ expect(accounts[22].pubkey.equals(PUMP_FEE_CONFIG_PDA)).toBe(true);
+ expect(accounts[23].pubkey.equals(PUMP_FEE_PROGRAM_ID)).toBe(true);
+ expect(accounts[25].pubkey.equals(PUMP_EVENT_AUTHORITY_PDA)).toBe(true);
+ expect(accounts[26].pubkey.equals(PUMP_PROGRAM_ID)).toBe(true);
+ });
+
+ it('marks `user` (burn-authority PDA) as signer + writable; mints as read-only', async () => {
+ const { accounts } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+
+ // user (index 13) — outer ix invoke_signed supplies the PDA signature.
+ expect(accounts[13].isSigner).toBe(true);
+ expect(accounts[13].isWritable).toBe(true);
+ // base/quote mint reads (1, 2) — non-writable.
+ expect(accounts[1].isWritable).toBe(false);
+ expect(accounts[2].isWritable).toBe(false);
+ // Bonding curve, vaults — all writable.
+ expect(accounts[10].isWritable).toBe(true);
+ expect(accounts[14].isWritable).toBe(true);
+ expect(accounts[15].isWritable).toBe(true);
+ });
+
+ it('exact writable mask matches the IDL', async () => {
+ const { accounts } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ // Writable indices per `buy_exact_quote_in_v2` IDL:
+ const writableSet = new Set([6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21]);
+ accounts.forEach((acct, i) => {
+ expect(acct.isWritable, `account ${i} writable flag`).toBe(writableSet.has(i));
+ });
+ // `user` (13) is the only signer — invoke_signed by the outer ix.
+ const signerIdxs = accounts
+ .map((a, i) => (a.isSigner ? i : -1))
+ .filter((i) => i >= 0);
+ expect(signerIdxs).toEqual([13]);
+ });
+
+ it('throws when the bonding curve has graduated', async () => {
+ mockDecodeBondingCurve.mockReturnValueOnce({
+ complete: true,
+ creator: CREATOR,
+ quoteMint: CURRENCY,
+ isMayhemMode: false,
+ tokenTotalSupply: new BN('1'),
+ virtualQuoteReserves: new BN('1'),
+ virtualTokenReserves: new BN('1'),
+ });
+ await expect(
+ buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ }),
+ ).rejects.toThrow(/graduated/i);
+ });
+
+ it('throws when the caller-supplied currency does not match the curve quote mint', async () => {
+ const wrongCurrency = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); // some other mint
+ await expect(
+ buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: wrongCurrency,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ }),
+ ).rejects.toThrow(/currency mint mismatch/i);
+ });
+
+ it('normalizes legacy quote-mint default (PublicKey.default) to NATIVE_MINT', async () => {
+ mockDecodeBondingCurve.mockReturnValueOnce({
+ complete: false,
+ creator: CREATOR,
+ quoteMint: PublicKey.default,
+ isMayhemMode: false,
+ tokenTotalSupply: new BN('1000000'),
+ virtualQuoteReserves: new BN('1'),
+ virtualTokenReserves: new BN('1'),
+ });
+ const { accounts } = await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: NATIVE_MINT,
+ amountIn: 1_000_000n,
+ minAmountOut: 0n,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ // quote_mint slot (index 2) resolves to NATIVE_MINT.
+ expect(accounts[2].pubkey.equals(NATIVE_MINT)).toBe(true);
+ });
+
+ it('passes amountIn through to the quote helper as a BN', async () => {
+ await buildPumpSwapInnerIx({
+ mint: MINT,
+ currency: CURRENCY,
+ amountIn: 9_999_999n,
+ slippageBps: 1000,
+ cluster: 'devnet',
+ connection: fakeConnection(),
+ });
+ expect(mockGetBuyTokenAmount).toHaveBeenCalledOnce();
+ const call = mockGetBuyTokenAmount.mock.calls[0][0];
+ expect(call.amount.toString()).toBe('9999999');
+ expect(call.quoteMint.equals(CURRENCY)).toBe(true);
+ });
+});
diff --git a/tests/render-glb.test.js b/tests/render-glb.test.js
new file mode 100644
index 000000000..9743240e3
--- /dev/null
+++ b/tests/render-glb.test.js
@@ -0,0 +1,86 @@
+// Tests for the server-side GLB → PNG renderer.
+//
+// The full render path needs a real chromium binary, a real GLB, and ~3s of
+// boot time, so the deep test is gated on RUN_HEADFUL_TESTS=1. CI runs the
+// fast input-validation suite only. Integration with the OG endpoint is
+// tested separately in tests/api/avatar-og.test.js with the renderer stubbed.
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { createServer } from 'node:http';
+import { Document, NodeIO } from '@gltf-transform/core';
+
+const HEADFUL = process.env.RUN_HEADFUL_TESTS === '1';
+
+describe('renderGlbToPng — input validation', () => {
+ it('rejects when glbUrl is missing', async () => {
+ const { renderGlbToPng } = await import('../api/_lib/render-glb.js');
+ await expect(renderGlbToPng({})).rejects.toThrow(/glbUrl required/);
+ await expect(renderGlbToPng({ glbUrl: '' })).rejects.toThrow(/glbUrl required/);
+ await expect(renderGlbToPng({ glbUrl: null })).rejects.toThrow(/glbUrl required/);
+ await expect(renderGlbToPng({ glbUrl: 42 })).rejects.toThrow(/glbUrl required/);
+ });
+});
+
+describe.skipIf(!HEADFUL)('renderGlbToPng — headful render', () => {
+ // Generate a minimal-but-valid GLB at module-load time: a single-triangle mesh.
+ // Served from a localhost http server so chromium can fetch it the same way
+ // production would fetch from R2's public CDN.
+ let server;
+ let glbUrl;
+
+ beforeAll(async () => {
+ const glbBuf = await buildTriangleGlb();
+ server = createServer((req, res) => {
+ if (req.url?.endsWith('.glb')) {
+ res.writeHead(200, {
+ 'content-type': 'model/gltf-binary',
+ 'content-length': String(glbBuf.length),
+ 'access-control-allow-origin': '*',
+ });
+ res.end(glbBuf);
+ } else {
+ res.writeHead(404).end();
+ }
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ const { port } = server.address();
+ glbUrl = `http://127.0.0.1:${port}/triangle.glb`;
+ }, 30_000);
+
+ afterAll(() => {
+ server?.close();
+ });
+
+ it('renders a GLB to a PNG buffer with the PNG magic header', async () => {
+ const { renderGlbToPng } = await import('../api/_lib/render-glb.js');
+ const png = await renderGlbToPng({ glbUrl, width: 400, height: 300 });
+ expect(Buffer.isBuffer(png) || png instanceof Uint8Array).toBe(true);
+ // PNG magic: 89 50 4E 47 0D 0A 1A 0A
+ expect(png[0]).toBe(0x89);
+ expect(png[1]).toBe(0x50);
+ expect(png[2]).toBe(0x4e);
+ expect(png[3]).toBe(0x47);
+ expect(png[4]).toBe(0x0d);
+ expect(png[5]).toBe(0x0a);
+ expect(png[6]).toBe(0x1a);
+ expect(png[7]).toBe(0x0a);
+ }, 60_000);
+});
+
+// Smallest legal GLB containing a single triangle mesh — used as a render
+// target. Avoids committing a binary fixture by building it from scratch.
+async function buildTriangleGlb() {
+ const doc = new Document();
+ const buf = doc.createBuffer();
+ const positions = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]))
+ .setBuffer(buf);
+ const prim = doc.createPrimitive().setAttribute('POSITION', positions);
+ const mesh = doc.createMesh().addPrimitive(prim);
+ const node = doc.createNode().setMesh(mesh);
+ doc.createScene().addChild(node);
+ const io = new NodeIO();
+ return Buffer.from(await io.writeBinary(doc));
+}
diff --git a/tests/speech-factories.test.js b/tests/speech-factories.test.js
new file mode 100644
index 000000000..591b7fe54
--- /dev/null
+++ b/tests/speech-factories.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import {
+ createTTS,
+ createSTT,
+ BrowserTTS,
+ BrowserSTT,
+ ElevenLabsTTS,
+} from '../src/runtime/speech.js';
+
+describe('createTTS', () => {
+ it('returns a BrowserTTS for provider "browser"', () => {
+ const tts = createTTS({ provider: 'browser' });
+ expect(tts).toBeInstanceOf(BrowserTTS);
+ });
+
+ it('returns an ElevenLabsTTS for provider "elevenlabs"', () => {
+ const tts = createTTS({ provider: 'elevenlabs', voiceId: 'test-voice' });
+ expect(tts).toBeInstanceOf(ElevenLabsTTS);
+ });
+
+ it('returns null for provider "none"', () => {
+ expect(createTTS({ provider: 'none' })).toBeNull();
+ });
+
+ it('defaults to BrowserTTS when no provider is given', () => {
+ expect(createTTS({})).toBeInstanceOf(BrowserTTS);
+ });
+
+ it('throws an honest error for an unknown provider', () => {
+ expect(() => createTTS({ provider: 'azure' })).toThrowError(
+ /Unknown TTS provider "azure"\..*browser.*elevenlabs/,
+ );
+ });
+});
+
+describe('createSTT', () => {
+ it('returns a BrowserSTT for provider "browser"', () => {
+ expect(createSTT({ provider: 'browser' })).toBeInstanceOf(BrowserSTT);
+ });
+
+ it('returns null for provider "none"', () => {
+ expect(createSTT({ provider: 'none' })).toBeNull();
+ });
+
+ it('defaults to BrowserSTT when no provider is given', () => {
+ expect(createSTT({})).toBeInstanceOf(BrowserSTT);
+ });
+
+ it('throws an honest error for an unknown provider', () => {
+ expect(() => createSTT({ provider: 'deepgram' })).toThrowError(
+ /Unknown STT provider "deepgram"\..*browser/,
+ );
+ });
+});
diff --git a/tests/vanity-wasm-grinder.test.js b/tests/vanity-wasm-grinder.test.js
new file mode 100644
index 000000000..2db5ddee2
--- /dev/null
+++ b/tests/vanity-wasm-grinder.test.js
@@ -0,0 +1,96 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { webcrypto } from 'node:crypto';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+globalThis.crypto ??= webcrypto;
+
+const wasmPath = fileURLToPath(
+ new URL('../src/solana/vanity/wasm/vanity_grinder_bg.wasm', import.meta.url),
+);
+const wasmBytes = readFileSync(wasmPath);
+
+let grind;
+
+beforeAll(async () => {
+ const mod = await import('../src/solana/vanity/wasm/vanity_grinder.js');
+ await mod.default({ module_or_path: wasmBytes });
+ grind = mod.grind;
+});
+
+function findOne(prefix, ignoreCase = false, maxIters = 200, batch = 5000) {
+ for (let i = 0; i < maxIters; i++) {
+ const seed = new Uint8Array(32);
+ crypto.getRandomValues(seed);
+ const hit = grind(prefix, '', ignoreCase, batch, seed);
+ if (hit) return hit;
+ }
+ return null;
+}
+
+describe('vanity-grinder WASM', () => {
+ it('returns a keypair whose public key starts with the requested prefix', () => {
+ // 'A' is in the high-probability bucket (first 17 base58 chars), so
+ // a single 5000-key batch lands a hit on essentially every run.
+ const hit = findOne('A');
+ expect(hit).not.toBeNull();
+ expect(hit.publicKey.startsWith('A')).toBe(true);
+ expect(hit.secretKey).toBeInstanceOf(Uint8Array);
+ expect(hit.secretKey.length).toBe(64);
+ });
+
+ it('honors ignoreCase: prefix "ab" matches addresses starting with "AB" or "ab"', () => {
+ const hit = findOne('ab', true, 500);
+ expect(hit).not.toBeNull();
+ expect(hit.publicKey.slice(0, 2).toLowerCase()).toBe('ab');
+ });
+
+ it('secret key signs a message that verifies against the returned public key', () => {
+ const hit = findOne('B');
+ expect(hit).not.toBeNull();
+
+ // Solana secret key = 32-byte seed || 32-byte public key
+ const seed = hit.secretKey.slice(0, 32);
+ const pubFromSecret = hit.secretKey.slice(32);
+
+ // The embedded pubkey matches what the seed derives
+ const derivedPub = ed25519.getPublicKey(seed);
+ expect(Buffer.from(derivedPub).equals(Buffer.from(pubFromSecret))).toBe(true);
+
+ // The base58 publicKey decodes to the same 32 bytes
+ const decoded = bs58.decode(hit.publicKey);
+ expect(Buffer.from(decoded).equals(Buffer.from(pubFromSecret))).toBe(true);
+
+ // Sign / verify roundtrip
+ const msg = new TextEncoder().encode('hello vanity grinder');
+ const sig = ed25519.sign(msg, seed);
+ expect(ed25519.verify(sig, msg, pubFromSecret)).toBe(true);
+
+ // Tampered message must NOT verify
+ const tampered = new TextEncoder().encode('hello vanity grinde');
+ expect(ed25519.verify(sig, tampered, pubFromSecret)).toBe(false);
+ });
+
+ it('one batch (5000) returns within 1s — bounds the worker abort latency', () => {
+ // The worker drives grind() in 5000-key batches and only checks the
+ // abort flag between batches. Real-browser WASM hits ~50ms per batch;
+ // even on slow Codespace CPUs a batch finishes well under a second.
+ const seed = new Uint8Array(32);
+ crypto.getRandomValues(seed);
+ const t0 = performance.now();
+ grind('zzzzzz', '', false, 5000, seed); // 6-char — won't match
+ const elapsed = performance.now() - t0;
+ expect(elapsed).toBeLessThan(1000);
+ });
+
+ it('returns null when no match in batch', () => {
+ // 6-char lowercase prefix is statistically near-impossible to hit in
+ // a single 5000-key batch (P ≈ 10^-12).
+ const seed = new Uint8Array(32);
+ crypto.getRandomValues(seed);
+ const hit = grind('zzzzzz', '', false, 5000, seed);
+ expect(hit).toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index e1e7200f8..cb2e78d6f 100644
--- a/vercel.json
+++ b/vercel.json
@@ -9,6 +9,11 @@
"functions": {
"api/**/*.js": {
"includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**"
+ },
+ "api/avatar-og.js": {
+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**",
+ "maxDuration": 30,
+ "memory": 2048
}
},
"routes": [
@@ -220,6 +225,10 @@
"src": "/walk/?",
"dest": "/walk.html"
},
+ {
+ "src": "/pose/?",
+ "dest": "/pose.html"
+ },
{
"src": "/walkaround/?",
"dest": "/demos/walkaround.html"
@@ -848,6 +857,20 @@
"src": "/api/demo/coin/holders",
"dest": "/api/demo/coin/[action]?action=holders"
},
+ {
+ "src": "/coin",
+ "status": 301,
+ "headers": {
+ "Location": "/demo/coin"
+ }
+ },
+ {
+ "src": "/coin/",
+ "status": 301,
+ "headers": {
+ "Location": "/demo/coin"
+ }
+ },
{
"src": "/demo/coin",
"dest": "/demo/coin/index.html"
diff --git a/vite.config.js b/vite.config.js
index a22040e16..f0e69b42b 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -143,6 +143,7 @@ const appConfig = {
'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),
'widget-studio': resolve(__dirname, 'pages/widget-studio.html'),
walk: resolve(__dirname, 'pages/walk.html'),
+ pose: resolve(__dirname, 'pages/pose.html'),
studio: resolve(__dirname, 'public/studio/index.html'),
reputation: resolve(__dirname, 'public/reputation/index.html'),
hydrate: resolve(__dirname, 'public/hydrate/index.html'),
@@ -241,6 +242,8 @@ const appConfig = {
'/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),
'/walk': resolve(root, 'pages/walk.html'),
'/walk/': resolve(root, 'pages/walk.html'),
+ '/pose': resolve(root, 'pages/pose.html'),
+ '/pose/': resolve(root, 'pages/pose.html'),
'/walkaround': resolve(root, 'public/demos/walkaround.html'),
'/walkaround/': resolve(root, 'public/demos/walkaround.html'),
'/brain': resolve(root, 'public/demos/brain.html'),
@@ -269,6 +272,8 @@ const appConfig = {
'/demos/': resolve(root, 'public/demos/index.html'),
'/demo/avatar-os': resolve(root, 'public/demo/avatar-os/index.html'),
'/demo/avatar-os/': resolve(root, 'public/demo/avatar-os/index.html'),
+ '/demo/coin': resolve(root, 'public/demo/coin/index.html'),
+ '/demo/coin/': resolve(root, 'public/demo/coin/index.html'),
'/': resolve(root, 'pages/home.html'),
'/home': resolve(root, 'pages/home.html'),
'/features': resolve(root, 'pages/features.html'),
@@ -294,6 +299,7 @@ const appConfig = {
'/gallery',
'/docs',
'/demo/avatar-os',
+ '/demo/coin',
]);
server.middlewares.use(async (req, res, next) => {
const url = req.url || '/';
@@ -315,6 +321,13 @@ const appConfig = {
res.setHeader('Location', '/discover/');
return res.end();
}
+ // /coin is the legacy URL for /demo/coin (the lottery+reflection
+ // demo). Kept as a 301 so old links and shares keep working.
+ if (path === '/coin' || path === '/coin/') {
+ res.statusCode = 301;
+ res.setHeader('Location', '/demo/coin');
+ return res.end();
+ }
// Chat sub-app is proxied to its own Vite dev server at :5174
// which serves under /chat/. Redirect /chat → /chat/ so the
// proxy can forward the trailing-slash form upstream.
@@ -334,6 +347,11 @@ const appConfig = {
const slug = path.replace(/^\/demos\//, '').replace(/\.html$/, '').replace(/\/$/, '');
filePath = resolve(root, `public/demos/${slug}.html`);
}
+ // /demo/coin/<base58 mint> → demo/coin index hydrates from the
+ // mint address in the URL path. Mirrors vercel.json.
+ else if (!filePath && /^\/demo\/coin\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)) {
+ filePath = resolve(root, 'public/demo/coin/index.html');
+ }
// /tutorials/<slug> → dedicated tutorial viewer template
else if (!filePath && /^\/tutorials\/[a-z0-9-]+\/?$/.test(path))
filePath = resolve(root, 'pages/tutorial.html');