Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
THREE buyback, cron, solana signers, element, onboard scripts, and changelog updates
nirholasbd9a37781405
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6cd6bd8ba..3ff4fe8ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Coin community worlds no longer get stuck on “Connecting…”** — Opening a coin community world could occasionally hang on “Connecting…” forever — you'd see only yourself, with chat, voice, and shared building all stalled and no way to recover short of a reload. It happened when the game server accepted the connection but never finished the join handshake, for instance while a server instance was waking from idle. The connection now has a firm time limit: if the handshake doesn't complete in time it retries on its own, and if the server stays unreachable it drops you cleanly into single-player so you can still explore and build locally — with the status pill tappable to reconnect. The same safeguard covers the open /walk world and the IRL map. `[fix]`- **Connect a wallet and your $THREE tier is recognized — no account needed** — You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before. (`/forge`) `[improvement]`+- **Embedded 3D agents animate on any site, not just three.ws** — When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site. `[fix, sdk]`- **Forge checkout no longer dead-ends when generation is briefly busy** — When the 3D generator was momentarily rate-limited mid-checkout, Forge could show a raw technical error and look like the payment had failed for good. Now a brief upstream slowdown shows a clear message — your payment was not taken, and the generation retries in a few seconds — and the checkout auto-retries on its own before ever asking you to try again. Your payment only settles once the model is actually produced, so a busy moment never costs you anything. (`/forge`) `[fix]`- **Graduated coins show a live price on agent and community cards** — The bonding-curve card — the compact one on agent profiles, community coin pages, and embeddable widgets — used to go blank with a “No active bonding curve” message the moment a coin graduated to a DEX. Now it reads the coin's live on-chain price instead, marks it “Graduated” at 100%, and shows a real market cap, so $THREE and any other migrated coin display a refreshing price rather than empty space. Those cards also stopped opening a background websocket that could never connect — it had been silently retrying and logging errors on every load. Vault balances now refresh by polling directly and update within seconds. `[improvement, fix]`- **Holding $THREE now unlocks a premium feature** — $THREE gets its first hard utility: High-quality 3D generation on Forge — the 200k-polygon, PBR-textured tier — is now reserved for $THREE holders. Reach the Bronze holder tier (the entry tier) by holding $THREE and the High tier unlocks automatically, with no payment step. Draft and Standard generation stay free forever, and bring-your-own-key generation is unaffected. Sign in, link your Solana wallet, and the economy page shows your live holder tier and exactly what it unlocks. (`/three`) `[feature]`@@ -23,6 +24,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The homepage avatar now prays, then walks** — Tap “🙏 Pray” on the homepage hero and the avatar finishes the prayer and rises straight into a walk — one smooth motion instead of snapping back to a standing idle at the end of the clip. After the walk plays out, the avatar eases back into its gentle idle-and-stroll rhythm. The other one-tap emotes (wave, dance, jump, and the rest) also return to that ambient motion now instead of freezing on their last frame. `[improvement]`- **Tipping a dancer goes straight to the wallet now** — Tapping Tip in the Pole Club used to open a three-step “Before you go on-chain” explainer first, and dismissing it cancelled the tip entirely — so first-time visitors couldn't pay without sitting through the wizard. That gate is gone. Tip now opens the wallet-and-amount checkout directly, where you pick Phantom or a browser wallet, see the exact USDC amount, and approve with one signature. The checkout already shows everything the explainer did, so there's no reason to stack a lecture in front of a fraction-of-a-cent tip. (`/club`) `[improvement]`- **Token swaps now confirm success or failure clearly** — When you buy $THREE (or swap any pair) from the swap window, it now tells you exactly how it went. After you approve in your wallet, a banner shows it submitting and confirming on-chain, then resolves to a clear result: a green “Swap confirmed” with the amount you received and a Solscan link, a red on-chain failure with the reason (and a hint to widen slippage when that's the cause), or a “still confirming” notice with a link if the network is slow. Previously a swap could land successfully but the window sat on “Confirming…” indefinitely with no confirmation — because it was waiting on a live socket the swap proxy doesn't carry. It now polls the chain directly and gives you a definite answer in seconds. (`/three-token`) `[fix]`+- **You can move the moment a Coin Communities world loads** — On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not. (`/play`) `[fix]`- **Your $THREE holder tier now shows across the site** — Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors. (`/forge`) `[feature, improvement]`## 2026-06-17diff --git a/api/_lib/migrations/2026-06-18-three-buyback.sql b/api/_lib/migrations/2026-06-18-three-buyback.sqlnew file mode 100644index 000000000..31c221720--- /dev/null+++ b/api/_lib/migrations/2026-06-18-three-buyback.sql@@ -0,0 +1,50 @@+-- Programmatic $THREE buyback ledger.+--+-- The run-three-buyback cron (api/cron/[name].js) converts accumulated platform+-- USDC revenue into onchain buy pressure: it market-buys $THREE on Jupiter and+-- routes the bought tokens into the treasury. This is the documented economy+-- policy ("the treasury funds buybacks … buy pressure without deflation",+-- api/_lib/token/config.js) made programmatic, onchain, and publicly auditable.+-- NO platform burn — supply is never destroyed by this lane.+--+-- One immutable row per run. Confirmed rows are the source of truth for the+-- public "revenue → $THREE bought back" figure on the $THREE token page. Skipped+-- and failed runs are recorded too (never a silent no-op), so an operator can see+-- exactly why a scheduled run did or didn't deploy capital.++begin;++create table if not exists three_buyback_runs (+ id uuid primary key default gen_random_uuid(),+ -- 'confirmed' | 'pending' | 'skipped' | 'failed' | 'dry_run'+ status text not null,+ -- machine-readable skip/fail reason: 'disabled' | 'not_configured' | 'empty'+ -- | 'below_threshold' | 'no_quote' | 'price_unavailable' | 'swap_failed'+ -- | 'sweep_failed' | 'tx_unconfirmed'+ reason text,+ -- Platform USDC fee revenue accrued to date at run time (atomics, 6dp). Context+ -- for the public ratio; the spend itself is driven by the wallet's USDC balance.+ revenue_fee_atomics bigint not null default 0,+ -- USDC deployed into this buyback (atomics, 6dp).+ usdc_spent_atomics bigint not null default 0,+ -- $THREE received from the swap (atomics).+ three_bought_atomics bigint not null default 0,+ -- Effective execution price (USD per whole $THREE) derived from the fill.+ price_usd numeric,+ slippage_bps integer,+ -- Jupiter buy tx, and the treasury sweep tx (null when the buyback wallet IS the+ -- treasury, or when there was nothing to sweep).+ buy_signature text,+ sweep_signature text,+ treasury_wallet text,+ error text,+ created_at timestamptz not null default now()+);++create index if not exists three_buyback_runs_created+ on three_buyback_runs (created_at desc);++create index if not exists three_buyback_runs_status_created+ on three_buyback_runs (status, created_at desc);++commit;diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsindex eab648bad..c44fd9561 100644--- a/api/_lib/solana-signers.js+++ b/api/_lib/solana-signers.js@@ -53,6 +53,13 @@ export const SOLANA_SIGNERS = [purpose: 'signs lottery/reflection distribution txs for launched coins',network: 'mainnet',},+ {+ name: 'three-buyback',+ env: 'THREE_BUYBACK_SECRET_KEY_B64',+ minSol: 0.05,+ purpose: 'holds platform USDC revenue; pays gas for the run-three-buyback cron (market-buy $THREE → treasury)',+ network: 'mainnet',+ },{name: 'club-treasury',env: 'CLUB_SOLANA_TREASURY_SECRET_KEY_B64',diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.jsnew file mode 100644index 000000000..34a9a4118--- /dev/null+++ b/api/_lib/token/buyback.js@@ -0,0 +1,349 @@+// Programmatic $THREE buyback engine.+//+// Converts accumulated platform USDC revenue into onchain buy pressure: market-buy+// $THREE on Jupiter and route the bought tokens into the treasury. This is the+// documented economy policy — "the treasury funds buybacks … buy pressure without+// deflation" (./config.js) — made programmatic, onchain, and publicly auditable.+// NO platform burn: supply is never destroyed by this lane.+//+// Custody vs. accounting are deliberately decoupled:+// • SPEND is driven by the buyback wallet's live USDC balance (capped per run).+// The wallet is funded by routing platform revenue into it.+// • The public "revenue earned" figure reads the agent_revenue_events fee ledger.+// This keeps execution robust (we only ever spend USDC we actually hold) while the+// public ratio stays honest (earned vs. deployed).+//+// The buyback wallet pays SOL tx fees, so it is registered in solana-signers.js+// for the balance-check cron. EXECUTION is gated by THREE_BUYBACK_ENABLED — a+// scheduled run is a recorded no-op until an operator funds the wallet and opts in.++import {+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferInstruction,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';++import { sql } from '../db.js';+import { getConnection, solanaPubkey } from '../pump.js';+import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { TOKEN_MINT, TOKEN_DECIMALS } from './config.js';+import { treasuryWallet, treasuryWalletOrNull } from './config.js';++const JUP_QUOTE_URL = 'https://lite-api.jup.ag/swap/v1/quote';+const JUP_SWAP_URL = 'https://lite-api.jup.ag/swap/v1/swap';+const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';++const USDC_DECIMALS = 6;+const USDC_ATOMICS = 10n ** BigInt(USDC_DECIMALS);+const THREE_ATOMICS = 10n ** BigInt(TOKEN_DECIMALS);++// ── policy knobs (env, with safe defaults) ──────────────────────────────────++/** Execution gate. A scheduled run is a recorded no-op unless this is truthy. */+export function isEnabled() {+ return ['1', 'true', 'yes', 'on'].includes(String(process.env.THREE_BUYBACK_ENABLED || '').toLowerCase());+}++function positiveEnvUsd(key, fallback) {+ const raw = process.env[key];+ if (raw === undefined || String(raw).trim() === '') return fallback;+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 ? n : fallback;+}++/** Max USD a single run may deploy — bounds a runaway/over-funded sweep. */+export function maxUsdPerRun() {+ return positiveEnvUsd('THREE_BUYBACK_MAX_USD', 250);+}++/** Below this, a run is skipped so dust doesn't pay more in fees than it buys. */+export function minUsdPerRun() {+ return positiveEnvUsd('THREE_BUYBACK_MIN_USD', 10);+}++/** Jupiter slippage tolerance in basis points (default 3%). */+export function slippageBps() {+ const raw = process.env.THREE_BUYBACK_SLIPPAGE_BPS;+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 && n <= 5000 ? Math.round(n) : 300;+}++/** Load the buyback signer (base64 of 64 secret-key bytes). Null when unset. */+export async function loadBuybackSigner() {+ const b64 = process.env.THREE_BUYBACK_SECRET_KEY_B64;+ if (!b64) return null;+ const { Keypair } = await import('@solana/web3.js');+ const raw = Buffer.from(b64, 'base64');+ if (raw.byteLength !== 64) {+ throw Object.assign(+ new Error(`THREE_BUYBACK_SECRET_KEY_B64: expected 64-byte secret key, got ${raw.byteLength}`),+ { code: 'bad_signer' },+ );+ }+ return Keypair.fromSecretKey(raw);+}++// ── helpers ─────────────────────────────────────────────────────────────────++const usd = (atomics) => Number(BigInt(atomics)) / Number(USDC_ATOMICS);+const threeTokens = (atomics) => Number(BigInt(atomics)) / Number(THREE_ATOMICS);++/** SPL balance of `owner` for `mint`, in atomics. Missing ATA → 0n (never throws). */+async function splBalanceAtomics(connection, ownerPk, mintPk) {+ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, true);+ try {+ const bal = await connection.getTokenAccountBalance(ata);+ return BigInt(bal.value.amount);+ } catch {+ return 0n; // ATA not yet created → zero balance+ }+}++async function fetchJson(url, opts) {+ const r = await fetch(url, opts);+ const body = await r.json().catch(() => ({}));+ if (!r.ok) {+ throw Object.assign(new Error(`jupiter ${r.status}: ${JSON.stringify(body).slice(0, 200)}`), {+ code: 'jupiter_error',+ status: r.status,+ });+ }+ return body;+}++/** ExactIn quote: how much $THREE `usdcAtomics` of USDC buys. */+async function jupiterQuote(usdcAtomics) {+ const u = new URL(JUP_QUOTE_URL);+ u.searchParams.set('inputMint', SOLANA_USDC_MINT);+ u.searchParams.set('outputMint', TOKEN_MINT);+ u.searchParams.set('amount', String(usdcAtomics));+ u.searchParams.set('slippageBps', String(slippageBps()));+ u.searchParams.set('swapMode', 'ExactIn');+ return fetchJson(u.toString(), { headers: { accept: 'application/json' } });+}++/** Build the signed-by-us swap transaction (base64) for `quote`. */+async function jupiterSwapTx(quote, userPublicKey) {+ const data = await fetchJson(JUP_SWAP_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({+ quoteResponse: quote,+ userPublicKey,+ // USDC→$THREE never touches wrapped SOL; let Jupiter manage the $THREE ATA.+ wrapAndUnwrapSol: false,+ dynamicComputeUnitLimit: true,+ prioritizationFeeLamports: {+ priorityLevelWithMaxLamports: { maxLamports: 1_000_000, priorityLevel: 'medium' },+ },+ }),+ });+ if (!data.swapTransaction) {+ throw Object.assign(new Error('jupiter returned no swapTransaction'), { code: 'no_swap_tx' });+ }+ return data.swapTransaction;+}++// ── plan ──────────────────────────────────────────────────────────────────-++/**+ * Decide how much to deploy this run and quote it. Pure of any signing/sending.+ * @param {string} signerPubkey base58 of the buyback wallet+ * @returns {Promise<object>} { ok, reason?, spendUsdcAtomics, walletUsdcAtomics, quote?, expectedThreeAtomics?, priceUsd? }+ */+export async function planBuyback(signerPubkey) {+ const connection = getConnection({ network: 'mainnet' });+ const walletUsdc = await splBalanceAtomics(connection, solanaPubkey(signerPubkey), solanaPubkey(SOLANA_USDC_MINT));++ const capAtomics = BigInt(Math.floor(maxUsdPerRun() * Number(USDC_ATOMICS)));+ const minAtomics = BigInt(Math.floor(minUsdPerRun() * Number(USDC_ATOMICS)));+ const spend = walletUsdc > capAtomics ? capAtomics : walletUsdc;++ if (spend < minAtomics) {+ return {+ ok: false,+ reason: walletUsdc === 0n ? 'empty' : 'below_threshold',+ walletUsdcAtomics: walletUsdc,+ spendUsdcAtomics: 0n,+ };+ }++ const quote = await jupiterQuote(spend);+ const expectedThree = BigInt(quote.outAmount ?? 0);+ if (expectedThree <= 0n) {+ return { ok: false, reason: 'no_quote', walletUsdcAtomics: walletUsdc, spendUsdcAtomics: spend };+ }+ const priceUsd = usd(spend) / threeTokens(expectedThree);++ return {+ ok: true,+ walletUsdcAtomics: walletUsdc,+ spendUsdcAtomics: spend,+ quote,+ expectedThreeAtomics: expectedThree,+ priceUsd,+ };+}++// ── execute ─────────────────────────────────────────────────────────────────++/**+ * Sign + send the Jupiter buy, then sweep the bought $THREE into the treasury+ * when the buyback wallet is not itself the treasury. Returns a receipt; throws+ * with a `.code` on hard failure so the caller records the precise reason.+ */+export async function executeBuyback(signer, plan) {+ const { VersionedTransaction, Transaction, TransactionInstruction, PublicKey } = await import('@solana/web3.js');+ const connection = getConnection({ network: 'mainnet' });+ const payer = signer.publicKey;++ // 1) Buy: deserialize Jupiter's tx, sign as the buyer, broadcast, confirm.+ const swapB64 = await jupiterSwapTx(plan.quote, payer.toBase58());+ const buyTx = VersionedTransaction.deserialize(Buffer.from(swapB64, 'base64'));+ buyTx.sign([signer]);+ const buySig = await connection.sendRawTransaction(buyTx.serialize(), { maxRetries: 5 });+ try {+ await connection.confirmTransaction(buySig, 'confirmed');+ } catch (waitErr) {+ throw Object.assign(+ new Error(`buyback ${buySig} submitted but confirmation timed out (${waitErr?.message || waitErr})`),+ { code: 'tx_unconfirmed', status: 'pending', buySignature: buySig },+ );+ }++ const mintPk = new PublicKey(TOKEN_MINT);+ const boughtAtomics = await splBalanceAtomics(connection, payer, mintPk);++ // 2) Sweep to treasury — unless the buyback wallet IS the treasury (then the+ // $THREE already lives there). treasuryWallet() fails closed in production.+ const treasury = treasuryWallet();+ let sweepSig = null;+ if (treasury !== payer.toBase58() && boughtAtomics > 0n) {+ const treasuryPk = new PublicKey(treasury);+ const fromAta = getAssociatedTokenAddressSync(mintPk, payer, true);+ const toAta = getAssociatedTokenAddressSync(mintPk, treasuryPk, true);+ const tx = new Transaction();+ tx.add(createAssociatedTokenAccountIdempotentInstruction(payer, toAta, treasuryPk, mintPk));+ tx.add(createTransferInstruction(fromAta, toAta, payer, boughtAtomics));+ const tag = `three.ws buyback → treasury $${usd(plan.spendUsdcAtomics).toFixed(2)}`.slice(0, 180);+ tx.add(new TransactionInstruction({ keys: [], programId: new PublicKey(MEMO_PROGRAM_ID), data: Buffer.from(tag, 'utf8') }));+ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ tx.recentBlockhash = blockhash;+ tx.feePayer = payer;+ tx.sign(signer);+ sweepSig = await connection.sendRawTransaction(tx.serialize(), { maxRetries: 5 });+ try {+ await connection.confirmTransaction(sweepSig, 'confirmed');+ } catch (waitErr) {+ // The buy already landed; surface a sweep-specific failure so the next+ // run self-heals (it sweeps any pre-existing $THREE before buying more).+ throw Object.assign(+ new Error(`buyback bought $THREE (${buySig}) but treasury sweep ${sweepSig} did not confirm (${waitErr?.message || waitErr})`),+ { code: 'sweep_failed', status: 'pending', buySignature: buySig, sweepSignature: sweepSig, boughtAtomics },+ );+ }+ }++ return {+ buySignature: buySig,+ sweepSignature: sweepSig,+ boughtAtomics,+ treasury,+ priceUsd: plan.priceUsd,+ };+}++/**+ * Self-heal: if a prior run bought $THREE but the treasury sweep didn't land, the+ * tokens sit in the buyback wallet. Sweep them before buying more. Returns the+ * sweep signature, or null when there's nothing to sweep / wallet is the treasury.+ */+export async function sweepStrandedThree(signer) {+ const treasury = treasuryWalletOrNull();+ if (!treasury || treasury === signer.publicKey.toBase58()) return null;+ const { Transaction, TransactionInstruction, PublicKey } = await import('@solana/web3.js');+ const connection = getConnection({ network: 'mainnet' });+ const payer = signer.publicKey;+ const mintPk = new PublicKey(TOKEN_MINT);+ const stranded = await splBalanceAtomics(connection, payer, mintPk);+ if (stranded <= 0n) return null;++ const treasuryPk = new PublicKey(treasury);+ const fromAta = getAssociatedTokenAddressSync(mintPk, payer, true);+ const toAta = getAssociatedTokenAddressSync(mintPk, treasuryPk, true);+ const tx = new Transaction();+ tx.add(createAssociatedTokenAccountIdempotentInstruction(payer, toAta, treasuryPk, mintPk));+ tx.add(createTransferInstruction(fromAta, toAta, payer, stranded));+ tx.add(new TransactionInstruction({ keys: [], programId: new PublicKey(MEMO_PROGRAM_ID), data: Buffer.from('three.ws buyback → treasury (recover)', 'utf8') }));+ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ tx.recentBlockhash = blockhash;+ tx.feePayer = payer;+ tx.sign(signer);+ const sig = await connection.sendRawTransaction(tx.serialize(), { maxRetries: 5 });+ await connection.confirmTransaction(sig, 'confirmed');+ return sig;+}++// ── accounting / public stats ────────────────────────────────────────────────++/** Lifetime platform USDC fee revenue (atomics, 6dp) — the "earned" figure. */+export async function revenueFeeAtomicsToDate() {+ const rows = await sql`+ select coalesce(sum(fee_amount), 0)::bigint as total+ from agent_revenue_events+ where currency_mint = ${SOLANA_USDC_MINT} and chain = 'solana'+ `.catch(() => [{ total: 0 }]);+ return BigInt(rows[0]?.total ?? 0);+}++/**+ * Public buyback summary for the $THREE token page: revenue earned vs. USDC+ * deployed into $THREE buybacks, $THREE accumulated, and the latest run.+ */+export async function buybackStats() {+ const [agg, lastRow, revenueAtomics] = await Promise.all([+ sql`+ select+ coalesce(sum(usdc_spent_atomics), 0)::bigint as usdc_spent,+ coalesce(sum(three_bought_atomics), 0)::bigint as three_bought,+ count(*)::int as runs+ from three_buyback_runs+ where status = 'confirmed'+ `.catch(() => [{ usdc_spent: 0, three_bought: 0, runs: 0 }]),+ sql`+ select status, usdc_spent_atomics, three_bought_atomics, price_usd, buy_signature, created_at+ from three_buyback_runs+ where status = 'confirmed'+ order by created_at desc+ limit 1+ `.catch(() => []),+ revenueFeeAtomicsToDate(),+ ]);++ const usdcSpent = BigInt(agg[0]?.usdc_spent ?? 0);+ const threeBought = BigInt(agg[0]?.three_bought ?? 0);+ const revenueUsd = usd(revenueAtomics);+ const deployedUsd = usd(usdcSpent);+ const last = lastRow[0] || null;++ return {+ enabled: isEnabled(),+ revenue_usd: revenueUsd,+ deployed_usd: deployedUsd,+ // Share of platform revenue already converted to onchain buy pressure.+ deployed_pct: revenueUsd > 0 ? Math.min(100, (deployedUsd / revenueUsd) * 100) : 0,+ three_bought: threeTokens(threeBought),+ runs: agg[0]?.runs ?? 0,+ last_run: last+ ? {+ at: last.created_at,+ usdc: usd(last.usdc_spent_atomics),+ three: threeTokens(last.three_bought_atomics),+ price_usd: last.price_usd != null ? Number(last.price_usd) : null,+ signature: last.buy_signature,+ }+ : null,+ };+}++export { usd as usdcAtomicsToUsd, threeTokens as threeAtomicsToTokens };diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 62b6025cc..711bb1784 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -16,6 +16,7 @@* pumpfun-signals → handlePumpfunSignals* pumpfun-graduations-sync → handlePumpfunGraduationsSync* run-buyback → handleRunBuyback+ * run-three-buyback → handleRunThreeBuyback* run-dca → handleRunDca* run-distribute-payments → handleRunDistributePayments* run-subscriptions → handleRunSubscriptions@@ -90,6 +91,7 @@ const HANDLERS = {'pumpfun-signals': handlePumpfunSignals,'pumpfun-graduations-sync': handlePumpfunGraduationsSync,'run-buyback': handleRunBuyback,+ 'run-three-buyback': handleRunThreeBuyback,'run-dca': handleRunDca,'run-distribute-payments': handleRunDistributePayments,'run-subscriptions': handleRunSubscriptions,@@ -1775,6 +1777,155 @@ async function handleRunBuyback(req, res) {return json(res, 200, { ok: true, processed: results.length, results });}+// ═══════════════════════════════════════════════════════════════════════════+// run-three-buyback — programmatic $THREE buyback (revenue → buy → treasury)+//+// Converts accumulated platform USDC revenue into onchain buy pressure: market-buy+// $THREE on Jupiter and route the bought tokens into the treasury. This is the+// documented economy policy ("the treasury funds buybacks … buy pressure without+// deflation", api/_lib/token/config.js) made programmatic, onchain, and publicly+// auditable. NO platform burn — supply is never destroyed by this lane.+//+// Every run records a row in three_buyback_runs (never a silent no-op). Execution+// is gated by THREE_BUYBACK_ENABLED + THREE_BUYBACK_SECRET_KEY_B64; `?dry_run=1`+// sizes + quotes the buy without signing, so the wiring is verifiable before a+// single dollar moves.+// ═══════════════════════════════════════════════════════════════════════════++async function handleRunThreeBuyback(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const bb = await import('../_lib/token/buyback.js');+ const dryRunRaw = String(req.query?.dry_run ?? '').toLowerCase();+ const dryRun = dryRunRaw === '1' || dryRunRaw === 'true';+ const slippage = bb.slippageBps();+ const revenueAtomics = await bb.revenueFeeAtomicsToDate();+ const revStr = revenueAtomics.toString();++ // Execution gate: a scheduled run is a recorded no-op until an operator funds+ // the wallet and opts in. A dry run is always allowed (it never signs).+ if (!dryRun && !bb.isEnabled()) {+ const [run] = await sql`+ insert into three_buyback_runs (status, reason, revenue_fee_atomics)+ values ('skipped', 'disabled', ${revStr}) returning id+ `;+ return json(res, 200, { ok: true, status: 'skipped', reason: 'disabled', run_id: run.id });+ }++ const signer = await bb.loadBuybackSigner();+ if (!signer) {+ const [run] = await sql`+ insert into three_buyback_runs (status, reason, revenue_fee_atomics)+ values ('skipped', 'not_configured', ${revStr}) returning id+ `;+ return json(res, 200, {+ ok: true,+ status: 'skipped',+ reason: 'not_configured',+ run_id: run.id,+ message: 'set THREE_BUYBACK_SECRET_KEY_B64 and fund the wallet with USDC to enable buybacks',+ });+ }++ // Self-heal a prior partial run (bought $THREE that never reached the treasury)+ // before sizing a new buy. Non-fatal: the main flow sweeps to treasury anyway.+ let recoverSig = null;+ if (!dryRun) {+ try {+ recoverSig = await bb.sweepStrandedThree(signer);+ } catch {+ recoverSig = null;+ }+ }++ let plan;+ try {+ plan = await bb.planBuyback(signer.publicKey.toBase58());+ } catch (e) {+ const code = e.code || 'plan_failed';+ const [run] = await sql`+ insert into three_buyback_runs (status, reason, revenue_fee_atomics, error)+ values ('failed', ${code}, ${revStr}, ${e.message || String(e)}) returning id+ `;+ return json(res, 200, { ok: false, status: 'failed', reason: code, error: e.message, run_id: run.id });+ }++ if (!plan.ok) {+ const [run] = await sql`+ insert into three_buyback_runs (status, reason, revenue_fee_atomics, usdc_spent_atomics)+ values ('skipped', ${plan.reason}, ${revStr}, 0) returning id+ `;+ return json(res, 200, {+ ok: true,+ status: 'skipped',+ reason: plan.reason,+ run_id: run.id,+ wallet_usdc: bb.usdcAtomicsToUsd(plan.walletUsdcAtomics),+ });+ }++ if (dryRun) {+ const [run] = await sql`+ insert into three_buyback_runs+ (status, revenue_fee_atomics, usdc_spent_atomics, three_bought_atomics, price_usd, slippage_bps)+ values+ ('dry_run', ${revStr}, ${plan.spendUsdcAtomics.toString()}, ${plan.expectedThreeAtomics.toString()}, ${plan.priceUsd}, ${slippage})+ returning id+ `;+ return json(res, 200, {+ ok: true,+ status: 'dry_run',+ run_id: run.id,+ usdc_to_spend: bb.usdcAtomicsToUsd(plan.spendUsdcAtomics),+ expected_three: bb.threeAtomicsToTokens(plan.expectedThreeAtomics),+ price_usd: plan.priceUsd,+ slippage_bps: slippage,+ });+ }++ try {+ const receipt = await bb.executeBuyback(signer, plan);+ const [run] = await sql`+ insert into three_buyback_runs+ (status, revenue_fee_atomics, usdc_spent_atomics, three_bought_atomics, price_usd, slippage_bps, buy_signature, sweep_signature, treasury_wallet)+ values+ ('confirmed', ${revStr}, ${plan.spendUsdcAtomics.toString()}, ${receipt.boughtAtomics.toString()}, ${receipt.priceUsd}, ${slippage}, ${receipt.buySignature}, ${receipt.sweepSignature}, ${receipt.treasury})+ returning id+ `;+ return json(res, 200, {+ ok: true,+ status: 'confirmed',+ run_id: run.id,+ recover_signature: recoverSig,+ buy_signature: receipt.buySignature,+ sweep_signature: receipt.sweepSignature,+ usdc_spent: bb.usdcAtomicsToUsd(plan.spendUsdcAtomics),+ three_bought: bb.threeAtomicsToTokens(receipt.boughtAtomics),+ price_usd: receipt.priceUsd,+ });+ } catch (e) {+ const code = e.code || 'swap_failed';+ const status = e.status === 'pending' ? 'pending' : 'failed';+ const [run] = await sql`+ insert into three_buyback_runs+ (status, reason, revenue_fee_atomics, usdc_spent_atomics, three_bought_atomics, price_usd, slippage_bps, buy_signature, sweep_signature, error)+ values+ (${status}, ${code}, ${revStr}, ${plan.spendUsdcAtomics.toString()}, ${(e.boughtAtomics ?? 0n).toString()}, ${plan.priceUsd}, ${slippage}, ${e.buySignature ?? null}, ${e.sweepSignature ?? null}, ${e.message || String(e)})+ returning id+ `;+ return json(res, 200, {+ ok: false,+ status,+ reason: code,+ error: e.message,+ run_id: run.id,+ buy_signature: e.buySignature ?? null,+ });+ }+}+// ═══════════════════════════════════════════════════════════════════════════// run-dca// ═══════════════════════════════════════════════════════════════════════════diff --git a/data/changelog.json b/data/changelog.jsonindex 73d9066f3..cf7e36dc4 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-18",+ "title": "Embedded 3D agents animate on any site, not just three.ws",+ "summary": "When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site.",+ "tags": [+ "fix",+ "sdk"+ ]+ },+ {+ "date": "2026-06-18",+ "title": "You can move the moment a Coin Communities world loads",+ "summary": "On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not.",+ "tags": [+ "fix"+ ],+ "link": "/play"+ },{"date": "2026-06-18","title": "Leaving a review on an agent profile works again",diff --git a/public/changelog.json b/public/changelog.jsonindex 1e3397a65..775386e2a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T04:13:28.939Z",+ "generated_at": "2026-06-18T04:45:54.243Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,17 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Embedded 3D agents animate on any site, not just three.ws",+ "summary": "When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site.",+ "link": null,+ "tags": [+ "fix",+ "sdk"+ ]+ },{"date": "2026-06-18","type": "update",@@ -177,6 +188,16 @@"fix"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "You can move the moment a Coin Communities world loads",+ "summary": "On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not.",+ "link": "/play",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex a5691bd18..5f27fd12c 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>improvement</category><description>You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before.</description></item>+ <item>+ <title>Embedded 3D agents animate on any site, not just three.ws</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-18:Embedded 3D agents animate on any site, not just three.ws</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site.</description>+ </item><item><title>Forge checkout no longer dead-ends when generation is briefly busy</title><link>https://three.ws/forge</link>@@ -142,6 +150,14 @@<category>fix</category><description>When you buy $THREE (or swap any pair) from the swap window, it now tells you exactly how it went. After you approve in your wallet, a banner shows it submitting and confirming on-chain, then resolves to a clear result: a green “Swap confirmed” with the amount you received and a Solscan link, a red on-chain failure with the reason (and a hint to widen slippage when that's the cause), or a “still confirming” notice with a link if the network is slow. Previously a swap could land successfully but the window sat on “Confirming…” indefinitely with no confirmation — because it was waiting on a live socket the swap proxy doesn't carry. It now polls the chain directly and gives you a definite answer in seconds.</description></item>+ <item>+ <title>You can move the moment a Coin Communities world loads</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-06-18:You can move the moment a Coin Communities world loads</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not.</description>+ </item><item><title>Your $THREE holder tier now shows across the site</title><link>https://three.ws/forge</link>diff --git a/public/features.json b/public/features.jsonindex 30ce687f1..fb49e53e2 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T04:13:28.922Z",+ "generated_at": "2026-06-18T04:45:54.225Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/play-chat-layout.mjs b/scripts/play-chat-layout.mjsnew file mode 100644index 000000000..4642eb96c--- /dev/null+++ b/scripts/play-chat-layout.mjs@@ -0,0 +1,102 @@+// Reproduce the chat assistant-message layout (avatar + reasoning + tool pills + split-view inspector)+// via a share link, then screenshot + dump layout metrics. Used to verify the layout fix.+import { chromium } from 'playwright';+import { gzipSync } from 'node:zlib';++const BASE = process.env.CHAT_URL || 'http://localhost:5173/chat/';++function b64url(buf) {+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++const model = { id: 'nex-n2-pro', name: 'Nex-N2-Pro', provider: 'three.ws' };++const tc = (name, args) => ({ id: 'tc-' + Math.random().toString(36).slice(2), name, arguments: args, finished: true });++const forgeAvatarArgs = {+ name: 'Cyberpunk Trader',+ prompt:+ 'A cyberpunk trader character, full body, neon jacket, holographic trading visor, futuristic streetwear, confident pose, dark city lighting, 3D stylized',+ save: 'true',+};++const messages = [+ { id: 'u1', role: 'user', content: 'Give me 3 crypto avatar ideas', submitted: true },+ {+ id: 'a1',+ role: 'assistant',+ model,+ content:+ 'Here are three directions worth exploring:\n\n- **Solana-themed avatar**\n- **Pump.fun frog mascot**\n- **Crypto robot**',+ },+ { id: 'u2', role: 'user', content: 'do 1 of each', submitted: true },+ {+ id: 'a2',+ role: 'assistant',+ model,+ content: '',+ reasoning: true,+ thinking: false,+ thinkingTime: 31,+ thoughts:+ 'The user wants one of each idea. I will forge a Solana-themed avatar, a pump.fun frog mascot, and a crypto robot, then a cyberpunk trader for good measure.',+ toolcalls: [+ tc('ForgeTextTo3D', { prompt: 'A Solana-themed avatar, glowing teal and purple, 3D stylized', save: 'true' }),+ tc('ForgeAvatar', { name: 'Frog Mascot', prompt: 'A pump.fun frog mascot, cute, big eyes, 3D stylized', save: 'true' }),+ tc('ForgeAvatar', { name: 'Crypto Robot', prompt: 'A friendly crypto robot, chrome body, LED eyes, 3D stylized', save: 'true' }),+ tc('ForgeAvatar', { name: 'Neon Punk', prompt: 'A neon punk avatar, mohawk, jacket, 3D stylized', save: 'true' }),+ tc('ForgeAvatar', forgeAvatarArgs),+ tc('ForgeTextTo3D', { prompt: 'A crypto robot statue, marble, 3D stylized', save: 'true' }),+ ],+ },+];++const convo = { name: 'Crypto avatars', models: [model], messages };+const share = b64url(gzipSync(Buffer.from(JSON.stringify(convo), 'utf8')));+const url = `${BASE}?s=${share}`;++const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1512, height: 850 }, deviceScaleFactor: 2 });+const page = await ctx.newPage();++await page.addInitScript(() => {+ localStorage.setItem('localAgentId', JSON.stringify('demo-agent'));+ localStorage.setItem('talkingHeadAvatarUrl', JSON.stringify('/avatars/cz.glb'));+ localStorage.setItem('config', JSON.stringify({ explicitToolView: false, messageAnimation: 'snap' }));+});++page.on('console', (m) => { if (m.type() === 'error') console.log('PAGE ERR:', m.text()); });++await page.goto(url, { waitUntil: 'domcontentloaded' });+await page.waitForSelector('li[data-role="assistant"]', { timeout: 20000 });+// open the active toolcall (ForgeAvatar Cyberpunk Trader = 5th pill) to engage split view+await page.waitForSelector('button[data-trigger="toolcall"]', { timeout: 20000 });+const pills = await page.$$('button[data-trigger="toolcall"]');+if (pills[4]) await pills[4].click();+// let the avatar walk-in / load settle+await page.waitForTimeout(7000);++const metrics = await page.evaluate(() => {+ const r = (el) => { if (!el) return null; const b = el.getBoundingClientRect(); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.width), h: Math.round(b.height) }; };+ const lastAssistant = [...document.querySelectorAll('li[data-role="assistant"]')].pop();+ const slot = lastAssistant?.querySelector('agent-3d')?.parentElement;+ const contentCol = lastAssistant?.querySelector('.flex.w-full.flex-col');+ const pillWrap = [...(lastAssistant?.querySelectorAll('div') || [])].find((d) => d.querySelector('button[data-trigger="toolcall"]'));+ const pills = [...(lastAssistant?.querySelectorAll('button[data-trigger="toolcall"]') || [])].map((p) => r(p));+ const rows = new Set(pills.map((p) => p && p.y));+ return {+ viewport: { w: window.innerWidth, h: window.innerHeight },+ splitView: !!document.querySelector('.scrollable')?.parentElement?.className?.includes('w-[50%]'),+ assistantRow: r(lastAssistant),+ avatarSlot: r(slot),+ contentCol: r(contentCol),+ pillWrap: r(pillWrap),+ pillRows: rows.size,+ pillCount: pills.length,+ };+});+console.log(JSON.stringify(metrics, null, 2));++await page.screenshot({ path: '/tmp/chat-layout.png', fullPage: false });+console.log('screenshot -> /tmp/chat-layout.png');+await browser.close();diff --git a/scripts/play-onboard-verify.mjs b/scripts/play-onboard-verify.mjsindex 16a586622..1e8d1cc8d 100644--- a/scripts/play-onboard-verify.mjs+++ b/scripts/play-onboard-verify.mjs@@ -7,7 +7,7 @@ const page = await ctx.newPage();await page.goto(URL, { waitUntil: 'domcontentloaded' });await page.waitForSelector('.cc-card', { timeout: 15000 });await page.tap('.cc-card');-const phase = await page.waitForFunction(() => window.__CC__?.phase === 'world', { timeout: 60000 }).then(() => 'world').catch(() => 'TIMEOUT');+const phase = await page.waitForFunction(() => window.__CC__?.phase === 'world', { timeout: 120000 }).then(() => 'world').catch(() => 'TIMEOUT');// Force the onboarding overlay visible immediately (deterministic — bypasses the// 650ms timer + flaky connect timing). _showOverlay is idempotent.@@ -32,12 +32,15 @@ const r = await page.evaluate(() => {return t ? (t.id ? '#' + t.id : t.tagName + '.' + String(t.className).split(' ').filter(Boolean)[0]) : null;};const primaryBtn = document.querySelector('#po-overlay .po-btn-primary') || document.querySelector('#po-overlay .po-close');+ const b = joy.getBoundingClientRect();+ const topAtJoy = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2);return {bodyOnboarding: document.body.classList.contains('po-onboarding'),overlayPE: cs(ov)?.pointerEvents,cardPE: cs(card)?.pointerEvents,joyZ: cs(joy)?.zIndex,hitAtJoystick: hit(joy),+ hitInsideJoystick: !!topAtJoy?.closest('#cc-joystick'),primaryBtnInCard: primaryBtn ? !!primaryBtn.closest('.po-card') : false,};});@@ -48,9 +51,10 @@ console.log('body.po-onboarding :', r.bodyOnboarding);console.log('#po-overlay pointerEv :', r.overlayPE, '(want none)');console.log('.po-card pointerEv :', r.cardPE, '(want auto)');console.log('#cc-joystick z-index :', r.joyZ, '(want 60 while onboarding)');-console.log('hit @ joystick centre :', r.hitAtJoystick, '(want #cc-joystick)');+console.log('hit @ joystick centre :', r.hitAtJoystick, '(joystick or its child)');+console.log('hit inside #cc-joystick:', r.hitInsideJoystick, '(want true — input reaches the stick)');console.log('primary btn in card :', r.primaryBtnInCard);-const pass = r.overlayPE === 'none' && r.cardPE === 'auto' && r.joyZ === '60' && r.hitAtJoystick === '#cc-joystick' && r.primaryBtnInCard;+const pass = r.overlayPE === 'none' && r.cardPE === 'auto' && r.joyZ === '60' && r.hitInsideJoystick && r.primaryBtnInCard;console.log('\nRESULT:', pass ? 'PASS' : 'FAIL');await browser.close();diff --git a/scripts/play-phase-debug.mjs b/scripts/play-phase-debug.mjsindex 9d3389271..e1092250d 100644--- a/scripts/play-phase-debug.mjs+++ b/scripts/play-phase-debug.mjs@@ -3,25 +3,23 @@ const URL = process.env.PROBE_URL || 'http://localhost:3100/play';const browser = await chromium.launch();const ctx = await browser.newContext({ viewport: { width: 390, height: 780 }, hasTouch: true, isMobile: true });const page = await ctx.newPage();-const errs = [];-page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });-page.on('pageerror', (e) => errs.push('PAGEERROR: ' + e.message));-await page.goto(URL, { waitUntil: 'domcontentloaded' });-await page.waitForSelector('.cc-card', { timeout: 15000 });-const cardInfo = await page.evaluate(() => {- const c = document.querySelector('.cc-card');- return { count: document.querySelectorAll('.cc-card').length, firstText: c?.textContent?.slice(0, 60) };+const t0 = Date.now();+const stamp = () => ((Date.now() - t0) / 1000).toFixed(1).padStart(5);+page.on('console', (m) => {+ const txt = m.text();+ if (/GL Driver|ReadPixels|GPU stall|\[vite\]|favicon/.test(txt)) return;+ if (/avatar|meshopt|manifest|loadAll|stand-in|connect|net|onboard|world|phase|gate|access|pass/i.test(txt))+ console.log(`${stamp()}s [${m.type()}] ${txt.slice(0, 110)}`);});+page.on('pageerror', (e) => console.log(`${stamp()}s PAGEERROR ${e.message.slice(0, 110)}`));+await page.goto(URL, { waitUntil: 'domcontentloaded' });+await page.waitForSelector('.cc-card', { timeout: 20000 });await page.tap('.cc-card');-for (let i = 0; i < 16; i++) {- await page.waitForTimeout(1500);- const s = await page.evaluate(() => {- const g = window.__CC__;- return { phase: g?.phase, net: g?.net?.status, hasRig: !!g?.localRig };- });- console.log(`t+${((i + 1) * 1.5).toFixed(1)}s phase=${s.phase} net=${s.net} rig=${s.hasRig}`);- if (s.phase === 'world') break;+console.log(`${stamp()}s clicked card`);+for (let i = 0; i < 40; i++) {+ await page.waitForTimeout(2000);+ const s = await page.evaluate(() => ({ phase: window.__CC__?.phase, net: window.__CC__?.net?.status }));+ if (s.phase === 'world') { console.log(`${stamp()}s REACHED world (net=${s.net})`); break; }+ if (i % 3 === 0) console.log(`${stamp()}s phase=${s.phase} net=${s.net}`);}-console.log('cards:', JSON.stringify(cardInfo));-console.log('errors:', errs.slice(0, 8).join(' | ') || 'none');await browser.close();diff --git a/src/element.js b/src/element.jsindex 6d60cedc0..41e6875d5 100644--- a/src/element.js+++ b/src/element.js@@ -1540,7 +1540,25 @@ class Agent3DElement extends HTMLElement {const _animBase = _scriptOrigin || window.location.origin;try {const _animRes = await fetch(`${_animBase}/animations/manifest.json`);- if (_animRes.ok) viewer.setAnimationDefs(await _animRes.json());+ if (_animRes.ok) {+ const _defs = await _animRes.json();+ // Clip URLs in the manifest are root-relative (`/animations/clips/x.json`).+ // Fetched verbatim they resolve against the *host page* origin, so when+ // <agent-3d> is embedded cross-origin (e.g. on a partner's domain) every+ // clip 404s. Rebase each onto the bundle's own origin — where the clips+ // actually live, co-located with the manifest we just loaded — so gestures+ // play anywhere the tag is dropped in.+ if (Array.isArray(_defs)) {+ for (const _d of _defs) {+ if (_d && typeof _d.url === 'string') {+ try {+ _d.url = new URL(_d.url, _animBase).href;+ } catch {}+ }+ }+ }+ viewer.setAnimationDefs(_defs);+ }} catch {}const bodyURI = resolveURI(manifest.body?.uri);