Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: neural TTS runtime, buyback updates, and feature-tour guide refinements
nirholasc15d268a9faf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0e399234b..13deba61c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,11 +26,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry** — Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real "~Ns left" countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly "high demand" notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you. (`/forge`) `[improvement, fix]`- **forge_avatar — one call turns a prompt into a rigged, animation-ready avatar** — A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced. (`/docs/mcp`) `[sdk, feature]`- **Free 3D generation keeps working when the paid engines are down** — The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable. `[fix]`+- **Free neural voice for agents — high-quality speech, no API key** — Agents now have a third voice option, 'neural', alongside browser and ElevenLabs. It runs a neural text-to-speech model entirely in your browser (on the GPU where available), so it sounds far better than the robotic built-in browser voice while costing nothing — no API key, no per-word charges, and the audio never leaves your device. Because the model returns exact phoneme timings, lip-sync is locked to the actual speech instead of estimated from text. Pick it under Voice in the agent builder and choose a Kokoro voice like af_bella or am_fenrir. First use downloads the model once. `[feature, improvement]`- **Free photo → 3D is now a one-click engine in Forge** — Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing. (`/forge`) `[feature, improvement]`+- **Free roam: walk the tour guide around the page yourself** — The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends. (`/tour`) `[feature, improvement]`- **Grind an agent's vanity wallet right on its page — with your CPU cores** — Giving an agent a custom wallet address used to run on our servers, so it was capped at short patterns and would time out and error on anything harder. Now the agent's Wallet → Vanity tab grinds the address in your own browser, exactly like the standalone /vanity-wallet tool: choose how many CPU cores to spend, match case-insensitively for a faster find, watch the live tries-per-second and ETA, and pause or resume anytime. Longer, rarer patterns are now possible with no timeouts. When a match is found, any SOL or tokens in the old wallet are still automatically swept to the new address before the key is swapped — funds are never stranded — and the server verifies the new address truly matches your pattern before storing it. `[fix, feature, improvement]`- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, improvement]`- **Imported avatars now animate with correct arm and leg orientation** — Animations are authored on one reference rig and retargeted onto whatever avatar you bring — Mixamo, Ready Player Me, VRoid, and more. We found that limbs on those rigs could play roughly 30° off from where they should be, because the retarget replayed each joint's motion in the wrong frame when a rig's rest pose differed from ours. The retarget now preserves each joint's true world-space motion, so idle, walk, and every other clip drive a foreign rig's arms and legs the way they were animated. Avatars matching the reference rig are byte-for-byte unchanged. `[fix, improvement]`- **Live market feed stays up through provider blips** — The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups. `[infra, improvement]`+- **My Collection page now loads** — The /collection page — where your unlocked skills and active subscriptions live — was returning a 404 because its route pointed at the wrong build path, and its subscriptions list was calling an endpoint that rejected the request. Both are fixed: the page loads, your purchased skills and NFT receipts render, and the Subscriptions tab now shows your active creator subscriptions with plan, price, renewal date, and a link to each creator. The marketplace analytics page had the same routing fault and now loads too. (`/collection`) `[fix]`- **Our paid services are properly discoverable by AI agents again** — Every three.ws paid endpoint and MCP tool is published to the x402 discovery indexes (Coinbase's Bazaar, x402scan, agentic.market) so AI agents can find and pay for them automatically. A stray invisible character in the published Solana receiving address was making indexers reject the entire catalog, and our MCP tools weren't flagged as discoverable — both are fixed, service names were tidied to meet listing limits, and we added a checker that catches these issues before they ship. Result: agents can discover and call our services across the ecosystem. `[improvement]`- **Pay-per-call endpoints accept Solana USDC payments again** — Paying for any x402 endpoint with Solana USDC was failing the moment the wallet tried to build the payment — the platform's receiving address was being published with a stray invisible character, so a correctly-built payment got rejected as going to the wrong recipient. Payment addresses are now cleaned before they're ever advertised, so Solana USDC payments to paid endpoints go through and settle as expected. `[fix]`- **Payment hardening and a steadier holder leaderboard** — Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end. (`/leaderboard`) `[security, fix, infra]`diff --git a/api/_lib/pump-launch.js b/api/_lib/pump-launch.jsindex 90ba6cac7..139b199a7 100644--- a/api/_lib/pump-launch.js+++ b/api/_lib/pump-launch.js@@ -13,10 +13,10 @@// • launchPumpToken() — grind the mint (optional vanity), build the// create-only instruction, send + confirm.-import { Keypair, PublicKey, Transaction } from '@solana/web3.js';+import { Keypair, PublicKey } from '@solana/web3.js';import { env } from './env.js';import { solanaConnection } from './agent-pumpfun.js';-import { confirmOrThrow } from './solana/confirm.js';+import { submitProtected } from './execution-engine.js';import { grindMintKeypair } from './pump-vanity.js';const PUMP_IPFS_ENDPOINT = 'https://pump.fun/api/ipfs';@@ -235,16 +235,17 @@ export async function launchPumpToken({throw launchError(422, 'build_failed', err.message || 'could not build create instruction');}- const tx = new Transaction().add(...instructions);- tx.feePayer = launcher.publicKey;- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(launcher, mint);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');+ // Protected send: the launcher pays + signs, the new mint co-signs. Priority+ // fee + CU estimate, rebroadcast with blockhash refresh, hard throw on revert.+ ({ signature } = await submitProtected({+ network,+ connection: conn,+ payer: launcher,+ instructions,+ opts: { extraSigners: [mint] },+ }));} catch (err) {throw launchError(502, 'rpc_error', err.message || 'create-coin transaction failed');}diff --git a/api/_lib/sealed-drop-funding.js b/api/_lib/sealed-drop-funding.jsindex cc6833978..dbc833b9c 100644--- a/api/_lib/sealed-drop-funding.js+++ b/api/_lib/sealed-drop-funding.js@@ -35,7 +35,6 @@ import bs58 from 'bs58';import {Keypair,PublicKey,- Transaction,SystemProgram,LAMPORTS_PER_SOL,} from '@solana/web3.js';@@ -48,7 +47,7 @@ import {import { env } from './env.js';import { solanaConnection } from './agent-pumpfun.js';-import { confirmOrThrow } from './solana/confirm.js';+import { submitProtected } from './execution-engine.js';import { SOLANA_USDC_MINT } from '../payments/_config.js';import { recordReclaim } from './sealed-drop-store.js';@@ -178,26 +177,23 @@ export async function fundDropAddress({ toAddress, asset, atomics }) {const recipient = new PublicKey(toAddress);const conn = solanaConnection('mainnet');- const tx = new Transaction();+ const instructions = [];if (asset === 'SOL') {- tx.add(SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: recipient, lamports: amount }));+ instructions.push(SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: recipient, lamports: amount }));} else {const mint = new PublicKey(mintForAsset(asset));const fromATA = await getAssociatedTokenAddress(mint, payer.publicKey);const toATA = await getAssociatedTokenAddress(mint, recipient);const toInfo = await conn.getAccountInfo(toATA);if (!toInfo) {- tx.add(createAssociatedTokenAccountInstruction(payer.publicKey, toATA, recipient, mint));+ instructions.push(createAssociatedTokenAccountInstruction(payer.publicKey, toATA, recipient, mint));}- tx.add(createTransferInstruction(fromATA, toATA, payer.publicKey, amount));+ instructions.push(createTransferInstruction(fromATA, toATA, payer.publicKey, amount));}- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- tx.feePayer = payer.publicKey;- tx.recentBlockhash = blockhash;- tx.sign(payer);- const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });- await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on revert.+ const { signature: sig } = await submitProtected({ network: 'mainnet', connection: conn, payer, instructions });return { fundingTx: sig, atomics: amount.toString(), asset };}@@ -262,7 +258,7 @@ export async function sweepReclaim({ record, dropSecretKey, toAddress }) {const conn = solanaConnection('mainnet');const asset = record.asset;- const tx = new Transaction();+ const instructions = [];if (asset === 'SOL') {const lamports = await conn.getBalance(dropKp.publicKey, 'confirmed');if (lamports <= 0) {@@ -271,7 +267,7 @@ export async function sweepReclaim({ record, dropSecretKey, toAddress }) {return { reclaimTx: 'empty', alreadyReclaimed: false };}// Fee is paid by the platform fee-payer, so the full drop balance moves.- tx.add(SystemProgram.transfer({ fromPubkey: dropKp.publicKey, toPubkey: recipient, lamports }));+ instructions.push(SystemProgram.transfer({ fromPubkey: dropKp.publicKey, toPubkey: recipient, lamports }));} else {const mint = new PublicKey(mintForAsset(asset));const fromATA = await getAssociatedTokenAddress(mint, dropKp.publicKey);@@ -288,17 +284,21 @@ export async function sweepReclaim({ record, dropSecretKey, toAddress }) {const toATA = await getAssociatedTokenAddress(mint, recipient);const toInfo = await conn.getAccountInfo(toATA);if (!toInfo) {- tx.add(createAssociatedTokenAccountInstruction(feePayer.publicKey, toATA, recipient, mint));+ instructions.push(createAssociatedTokenAccountInstruction(feePayer.publicKey, toATA, recipient, mint));}- tx.add(createTransferInstruction(fromATA, toATA, dropKp.publicKey, amount));+ instructions.push(createTransferInstruction(fromATA, toATA, dropKp.publicKey, amount));}- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- tx.feePayer = feePayer.publicKey;- tx.recentBlockhash = blockhash;- tx.sign(feePayer, dropKp);- const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });- await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ // Protected send: platform fee-payer pays + signs, the drop wallet co-signs the+ // transfer of its own balance. Priority fee + CU estimate, rebroadcast with+ // blockhash refresh, hard throw on an on-chain revert.+ const { signature: sig } = await submitProtected({+ network: 'mainnet',+ connection: conn,+ payer: feePayer,+ instructions,+ opts: { extraSigners: [dropKp] },+ });await recordReclaim({ id: record.id, reclaimTx: sig });return { reclaimTx: sig, alreadyReclaimed: false };}diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.jsindex 3c18d5857..23dbabd22 100644--- a/api/_lib/token/buyback.js+++ b/api/_lib/token/buyback.js@@ -26,6 +26,7 @@ import {import { sql } from '../db.js';import { getConnection, solanaPubkey } from '../pump.js';import { confirmOrThrow } from '../solana/confirm.js';+import { submitProtected } from '../execution-engine.js';import { SOLANA_USDC_MINT } from '../../payments/_config.js';import { TOKEN_MINT, TOKEN_DECIMALS } from './config.js';import { treasuryWallet, treasuryWalletOrNull } from './config.js';@@ -207,7 +208,7 @@ export async function planBuyback(signerPubkey) {* 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 { VersionedTransaction, TransactionInstruction, PublicKey } = await import('@solana/web3.js');const connection = getConnection({ network: 'mainnet' });const payer = signer.publicKey;@@ -237,23 +238,21 @@ export async function executeBuyback(signer, plan) {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 });+ const sweepIxs = [+ createAssociatedTokenAccountIdempotentInstruction(payer, toAta, treasuryPk, mintPk),+ createTransferInstruction(fromAta, toAta, payer, boughtAtomics),+ new TransactionInstruction({ keys: [], programId: new PublicKey(MEMO_PROGRAM_ID), data: Buffer.from(tag, 'utf8') }),+ ];try {- await confirmOrThrow(connection, sweepSig, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on revert.+ ({ signature: sweepSig } = await submitProtected({ network: 'mainnet', connection, payer: signer, instructions: sweepIxs }));} 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})`),+ new Error(`buyback bought $THREE (${buySig}) but treasury sweep did not confirm (${waitErr?.message || waitErr})`),{ code: 'sweep_failed', status: 'pending', buySignature: buySig, sweepSignature: sweepSig, boughtAtomics },);}@@ -276,7 +275,7 @@ export async function executeBuyback(signer, plan) {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 { TransactionInstruction, PublicKey } = await import('@solana/web3.js');const connection = getConnection({ network: 'mainnet' });const payer = signer.publicKey;const mintPk = new PublicKey(TOKEN_MINT);@@ -286,16 +285,14 @@ export async function sweepStrandedThree(signer) {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 confirmOrThrow(connection, sig, 'confirmed');+ const strandedIxs = [+ createAssociatedTokenAccountIdempotentInstruction(payer, toAta, treasuryPk, mintPk),+ createTransferInstruction(fromAta, toAta, payer, stranded),+ new TransactionInstruction({ keys: [], programId: new PublicKey(MEMO_PROGRAM_ID), data: Buffer.from('three.ws buyback → treasury (recover)', 'utf8') }),+ ];+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on revert.+ const { signature: sig } = await submitProtected({ network: 'mainnet', connection, payer: signer, instructions: strandedIxs });return sig;}diff --git a/api/agents/sns.js b/api/agents/sns.jsindex 99fdd3d38..a92c4251d 100644--- a/api/agents/sns.js+++ b/api/agents/sns.js@@ -26,7 +26,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { submitProtected } from '../_lib/execution-engine.js';import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';@@ -138,7 +138,6 @@ async function handleRegisterAgent(req, res, id, auth) {const { keypair } = loaded;let meta = { ...(loaded.meta || {}) };- const { Transaction } = await import('@solana/web3.js');const conn = solanaConnection('mainnet');try {@@ -146,13 +145,9 @@ async function handleRegisterAgent(req, res, id, auth) {return error(res, 409, 'conflict', `${domain}.sol is already registered`);}const ixs = await buildRegisterIxs({ connection: conn, domain, buyer: keypair.publicKey, space });- const tx = new Transaction().add(...ixs);- tx.feePayer = keypair.publicKey;- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;- tx.sign(keypair);- const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on an on-chain revert.+ const { signature: sig } = await submitProtected({ network: 'mainnet', connection: conn, payer: keypair, instructions: ixs });meta = { ...meta, sns_domain: domain };await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 08fe39d4a..22e7afb16 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -30,7 +30,7 @@ import { evmTransport } from '../_lib/evm/rpc.js';import { baseSepolia, base } from 'viem/chains';import { sql } from '../_lib/db.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { submitProtected } from '../_lib/execution-engine.js';import { cors, error, json, method, wrap } from '../_lib/http.js';import { env } from '../_lib/env.js';import { llmComplete } from '../_lib/llm.js';@@ -1763,15 +1763,9 @@ async function handleRunBuyback(req, res) {}const connection = getConnection({ network: m.network });- const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);- 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());- await confirmOrThrow(connection, sig, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on an on-chain revert.+ const { signature: sig } = await submitProtected({ network: m.network, connection, payer: relayer, instructions: [ix] });const [run] = await sql`insert into pump_buyback_runs@@ -2514,17 +2508,9 @@ async function handleRunDistributePayments(req, res) {currencyMint: currency,});const connection = getConnection({ network: m.network });- const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);- const tx = new Transaction();- tx.add(...(Array.isArray(ixs) ? ixs : [ixs]));- const { blockhash } = await connection.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;- tx.feePayer = relayer.publicKey;- tx.sign(relayer);- const sig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- });- await confirmOrThrow(connection, sig, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on an on-chain revert.+ const { signature: sig } = await submitProtected({ network: m.network, connection, payer: relayer, instructions: Array.isArray(ixs) ? ixs : [ixs] });const balancesAfter = await agent.getBalances(currency);const [run] = await sql`diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 562eb8e23..0da4206f9 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -54,7 +54,7 @@import { z } from 'zod';import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';import { sql } from '../_lib/db.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { submitProtected } from '../_lib/execution-engine.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, method, readJson, wrap, error, rateLimited, respondError } from '../_lib/http.js';import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';@@ -1757,35 +1757,6 @@ async function handleLaunchAgent(req, res) {instructions.push(createIx);}- // Build a v0 transaction so we use the same SDK call path as launch-prep.- const { TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');- const { blockhash } = await conn.getLatestBlockhash('confirmed');- // Compile + sign defensively. When the coin name/uri push the message past- // Solana's 1232-byte packet limit, compileToV0Message()/sign() throws a raw- // RangeError ("encoding overruns Uint8Array" / "Transaction too large") that- // would otherwise surface as an opaque 500. Convert it to a typed 413 with an- // actionable message instead.- let vtx;- try {- const msg = new TransactionMessage({- payerKey: creator,- recentBlockhash: blockhash,- instructions,- }).compileToV0Message();- vtx = new VersionedTransaction(msg);- vtx.sign([agentKeypair, mintKeypair]);- } catch (err) {- if (/too large|overruns/i.test(err?.message || '')) {- return error(- res,- 413,- 'launch_payload_too_large',- 'token launch transaction exceeds Solana size limits — shorten the token name or metadata URI',- );- }- throw err;- }-// Spend-policy gate: this path signs server-side with the agent's custodial// wallet, so a stolen session could otherwise drive an arbitrarily large SOL// dev-buy (up to the schema max) to drain the wallet. Reserve the SOL outflow@@ -1811,11 +1782,24 @@ async function handleLaunchAgent(req, res) {let signature;try {- signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: the agent custodial wallet pays + signs, the new mint+ // co-signs. Priority fee + CU estimate, rebroadcast with blockhash refresh,+ // hard throw on an on-chain revert.+ ({ signature } = await submitProtected({+ network: body.network,+ connection: conn,+ payer: agentKeypair,+ instructions,+ opts: { extraSigners: [mintKeypair] },+ }));} catch (err) {- console.error('[pump/launch-agent] send failed', err);await releaseSpend(reservation.reservationId);+ // A message too large for Solana's packet limit now surfaces here (compile+ // happens inside submitProtected) — keep the actionable 413 rather than 502.+ if (/too large|overruns/i.test(err?.message || '')) {+ return error(res, 413, 'launch_payload_too_large', 'token launch transaction exceeds Solana size limits — shorten the token name or metadata URI');+ }+ console.error('[pump/launch-agent] send failed', err);return respondError(res, 502, 'rpc_error', err);}@@ -4548,17 +4532,15 @@ async function handleFeeInfo(req, res) {// every server-signed pump action uses the same RPC handling.async function signSendWithAgent({ network, agentKeypair, instructions, extraSigners = [] }) {const conn = solanaConnection(network);- const { TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- const msg = new TransactionMessage({- payerKey: agentKeypair.publicKey,- recentBlockhash: blockhash,+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on an on-chain revert.+ const { signature } = await submitProtected({+ network,+ connection: conn,+ payer: agentKeypair,instructions,- }).compileToV0Message();- const vtx = new VersionedTransaction(msg);- vtx.sign([agentKeypair, ...extraSigners]);- const signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');+ opts: { extraSigners },+ });return signature;}diff --git a/data/changelog.json b/data/changelog.jsonindex fc1d12c4a..71277605d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,34 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-21",+ "title": "My Collection page now loads",+ "summary": "The /collection page — where your unlocked skills and active subscriptions live — was returning a 404 because its route pointed at the wrong build path, and its subscriptions list was calling an endpoint that rejected the request. Both are fixed: the page loads, your purchased skills and NFT receipts render, and the Subscriptions tab now shows your active creator subscriptions with plan, price, renewal date, and a link to each creator. The marketplace analytics page had the same routing fault and now loads too.",+ "tags": [+ "fix"+ ],+ "link": "/collection"+ },+ {+ "date": "2026-06-21",+ "title": "Free roam: walk the tour guide around the page yourself",+ "summary": "The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/tour"+ },+ {+ "date": "2026-06-21",+ "title": "Free neural voice for agents — high-quality speech, no API key",+ "summary": "Agents now have a third voice option, 'neural', alongside browser and ElevenLabs. It runs a neural text-to-speech model entirely in your browser (on the GPU where available), so it sounds far better than the robotic built-in browser voice while costing nothing — no API key, no per-word charges, and the audio never leaves your device. Because the model returns exact phoneme timings, lip-sync is locked to the actual speech instead of estimated from text. Pick it under Voice in the agent builder and choose a Kokoro voice like af_bella or am_fenrir. First use downloads the model once.",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-21","title": "Imported avatars now animate with correct arm and leg orientation",diff --git a/public/changelog.json b/public/changelog.jsonindex fd4304ce4..309547cd4 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:50:59.849Z",+ "generated_at": "2026-06-21T07:55:33.519Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -215,6 +215,17 @@"fix"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Free neural voice for agents — high-quality speech, no API key",+ "summary": "Agents now have a third voice option, 'neural', alongside browser and ElevenLabs. It runs a neural text-to-speech model entirely in your browser (on the GPU where available), so it sounds far better than the robotic built-in browser voice while costing nothing — no API key, no per-word charges, and the audio never leaves your device. Because the model returns exact phoneme timings, lip-sync is locked to the actual speech instead of estimated from text. Pick it under Voice in the agent builder and choose a Kokoro voice like af_bella or am_fenrir. First use downloads the model once.",+ "link": null,+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -226,6 +237,17 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Free roam: walk the tour guide around the page yourself",+ "summary": "The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends.",+ "link": "/tour",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -272,6 +294,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "My Collection page now loads",+ "summary": "The /collection page — where your unlocked skills and active subscriptions live — was returning a 404 because its route pointed at the wrong build path, and its subscriptions list was calling an endpoint that rejected the request. Both are fixed: the page loads, your purchased skills and NFT receipts render, and the Subscriptions tab now shows your active creator subscriptions with plan, price, renewal date, and a link to each creator. The marketplace analytics page had the same routing fault and now loads too.",+ "link": "/collection",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex a1f6247a4..f8e4c946d 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -166,6 +166,14 @@<category>fix</category><description>The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable.</description></item>+ <item>+ <title>Free neural voice for agents — high-quality speech, no API key</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Free neural voice for agents — high-quality speech, no API key</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agents now have a third voice option, 'neural', alongside browser and ElevenLabs. It runs a neural text-to-speech model entirely in your browser (on the GPU where available), so it sounds far better than the robotic built-in browser voice while costing nothing — no API key, no per-word charges, and the audio never leaves your device. Because the model returns exact phoneme timings, lip-sync is locked to the actual speech instead of estimated from text. Pick it under Voice in the agent builder and choose a Kokoro voice like af_bella or am_fenrir. First use downloads the model once.</description>+ </item><item><title>Free photo → 3D is now a one-click engine in Forge</title><link>https://three.ws/forge</link>@@ -174,6 +182,14 @@<category>feature</category><description>Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing.</description></item>+ <item>+ <title>Free roam: walk the tour guide around the page yourself</title>+ <link>https://three.ws/tour</link>+ <guid isPermaLink="false">2026-06-21:Free roam: walk the tour guide around the page yourself</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends.</description>+ </item><item><title>Grind an agent's vanity wallet right on its page — with your CPU cores</title><link>https://three.ws/changelog</link>@@ -206,6 +222,14 @@<category>infra</category><description>The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.</description></item>+ <item>+ <title>My Collection page now loads</title>+ <link>https://three.ws/collection</link>+ <guid isPermaLink="false">2026-06-21:My Collection page now loads</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The /collection page — where your unlocked skills and active subscriptions live — was returning a 404 because its route pointed at the wrong build path, and its subscriptions list was calling an endpoint that rejected the request. Both are fixed: the page loads, your purchased skills and NFT receipts render, and the Subscriptions tab now shows your active creator subscriptions with plan, price, renewal date, and a link to each creator. The marketplace analytics page had the same routing fault and now loads too.</description>+ </item><item><title>Our paid services are properly discoverable by AI agents again</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex c141b8de2..9d41f5b20 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:50:59.814Z",+ "generated_at": "2026-06-21T07:55:33.454Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/tour/curriculum.json b/public/tour/curriculum.jsonindex dfcc11211..84e390dfe 100644--- a/public/tour/curriculum.json+++ b/public/tour/curriculum.json@@ -1,6 +1,6 @@{"version": 2,- "generatedAt": "2026-06-21T07:32:34.837Z",+ "generatedAt": "2026-06-21T07:55:23.284Z","generatedBy": "scripts/build-tour.mjs from data/pages.json","title": "The three.ws Guided Tour","tagline": "A 3D guide walks you through every feature, live, on the real site.",diff --git a/src/avatar-studio-colorpicker.js b/src/avatar-studio-colorpicker.jsindex b9fb53552..58ea873f7 100644--- a/src/avatar-studio-colorpicker.js+++ b/src/avatar-studio-colorpicker.js@@ -217,38 +217,6 @@ export async function openColorPopover({ anchorEl, title, current, onInput, onChonChange?.(norm);};- // Lazy-build the iro wheel. If it fails to load, the hex field + eyedropper- // still work, so the popover degrades gracefully instead of breaking.- try {- const iro = await loadIro();- if (!el.isConnected) return { close: () => {} }; // closed during load- cp = new iro.ColorPicker(wheelHost, {- width: 200,- color: startHex,- borderWidth: 1,- borderColor: 'rgba(255,255,255,0.12)',- layout: [- { component: iro.ui.Wheel },- { component: iro.ui.Slider, options: { sliderType: 'value' } },- ],- });- cp.on('color:change', (color) => {- if (suppressInput) return;- const hex = color.hexString.toLowerCase();- lastHex = hex;- hexInput.value = hex.toUpperCase();- hexInput.classList.remove('bad');- onInput?.(hex);- });- cp.on('input:end', (color) => commit(color.hexString));- } catch (err) {- log.warn('[avatar-studio] iro picker failed to load; hex-only fallback', err);- const note = document.createElement('div');- note.className = 'as-cp-empty';- note.textContent = 'Wheel unavailable — type a hex value below.';- wheelHost.replaceWith(note);- }-const setFromHex = (raw, { live = false } = {}) => {const norm = normalizeHex(raw);if (!norm) {@@ -354,6 +322,43 @@ export async function openColorPopover({ anchorEl, title, current, onInput, onChel.querySelector('.as-cp-close').addEventListener('click', close);activePopover = { el, close };++ // Lazy-build the iro wheel LAST, so the hex field, eyedropper, recents, and+ // dismiss controls above are all interactive the instant the popover opens —+ // they never wait on the wheel's dynamic import. If iro fails to load, the+ // popover degrades to a hex-only picker instead of breaking.+ try {+ const iro = await loadIro();+ if (closed || !el.isConnected) return { close };+ cp = new iro.ColorPicker(wheelHost, {+ width: 200,+ color: lastHex,+ borderWidth: 1,+ borderColor: 'rgba(255,255,255,0.12)',+ layout: [+ { component: iro.ui.Wheel },+ { component: iro.ui.Slider, options: { sliderType: 'value' } },+ ],+ });+ cp.on('color:change', (color) => {+ if (suppressInput) return;+ const hex = color.hexString.toLowerCase();+ lastHex = hex;+ hexInput.value = hex.toUpperCase();+ hexInput.classList.remove('bad');+ onInput?.(hex);+ });+ cp.on('input:end', (color) => commit(color.hexString));+ // Re-fit position now that the wheel has given the popover its full height.+ positionPopover(el, anchorEl);+ } catch (err) {+ log.warn('[avatar-studio] iro picker failed to load; hex-only fallback', err);+ const note = document.createElement('div');+ note.className = 'as-cp-empty';+ note.textContent = 'Wheel unavailable — type a hex value below.';+ wheelHost.replaceWith(note);+ }+return { close };}diff --git a/src/collection.js b/src/collection.jsindex b9f4c3561..25876edf4 100644--- a/src/collection.js+++ b/src/collection.js@@ -19,6 +19,17 @@ function fmtAmount(amount, mint) {return symbol ? `${val} ${symbol}` : val;}+function fmtUsd(n) {+ if (n == null || Number.isNaN(Number(n))) return '';+ return `$${Number(n).toFixed(2)}`;+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}+function explorerUrl(mint, network) {const base = network === 'devnet'? 'https://explorer.solana.com/address/'@@ -80,34 +91,45 @@ function skillCard(p) {function subCard(s) {const now = Date.now();- const expiresAt = s.next_charge_at ? new Date(s.next_charge_at) : null;- const isActive = s.status === 'active' && (!expiresAt || expiresAt > now);+ const periodEnd = s.current_period_end ? new Date(s.current_period_end) : null;+ const isActive = s.status === 'active' && (!periodEnd || periodEnd > now);+ const isCancelled = s.status === 'cancelled' || s.status === 'canceled';+const expiryClass = isActive ? 'active' : 'expired';- const expiryText = expiresAt- ? (isActive ? `Renews ${fmtDate(s.next_charge_at)}` : `Expired ${fmtDate(s.next_charge_at)}`)+ const expiryText = periodEnd+ ? (isActive+ ? `Renews ${fmtDate(s.current_period_end)}`+ : `${isCancelled ? 'Ends' : 'Ended'} ${fmtDate(s.current_period_end)}`): '';const statusBadge = isActive? '<span class="badge badge-green">Active</span>'- : '<span class="badge badge-amber">Expired</span>';+ : isCancelled+ ? '<span class="badge badge-muted">Cancelled</span>'+ : '<span class="badge badge-amber">Expired</span>';- const amountLine = s.amount_per_period- ? `<span class="badge badge-muted">${fmtAmount(s.amount_per_period, null)}/period</span>`+ const priceLine = s.price_usd != null+ ? `<span class="badge badge-muted">${esc(fmtUsd(s.price_usd))}${s.interval ? ` / ${esc(s.interval)}` : ''}</span>`: '';+ const planName = s.plan_name || 'Subscription';+ const creator = s.creator_name || 'Creator';+ const creatorHref = s.creator_username ? `/u/${encodeURIComponent(s.creator_username)}` : '/marketplace';+ const initial = esc((planName[0] || '🔄').toUpperCase());+return `<article class="col-card"><div class="col-card-header">- <div class="col-card-avatar placeholder">🔄</div>+ <div class="col-card-avatar placeholder">${initial}</div><div class="col-card-meta">- <div class="col-card-skill">Agent Subscription</div>- <div class="col-card-agent">ID: ${s.agent_id?.slice(0, 8)}…</div>+ <div class="col-card-skill">${esc(planName)}</div>+ <div class="col-card-agent">by ${esc(creator)}</div></div></div>- <div class="col-card-badges">${statusBadge}${amountLine}</div>+ <div class="col-card-badges">${statusBadge}${priceLine}</div><div class="col-card-footer">- <span class="col-sub-expiry ${expiryClass}">${expiryText}</span>- <a href="/marketplace/agents/${s.agent_id}" class="col-cta">View agent</a>+ <span class="col-sub-expiry ${expiryClass}">${esc(expiryText)}</span>+ <a href="${creatorHref}" class="col-cta">View creator</a></div></article>`;}@@ -184,7 +206,7 @@ async function load() {try {[skillsRes, subsRes] = await Promise.all([fetch('/api/users/me/purchased-skills', { credentials: 'include' }),- fetch('/api/subscriptions', { credentials: 'include' }),+ fetch('/api/subscriptions/mine', { credentials: 'include' }),]);} catch (err) {// Network-level failure (offline, DNS, aborted): without this the awaited@@ -209,7 +231,7 @@ async function load() {let skillsData, subsData;try {({ data: skillsData } = await skillsRes.json());- ({ data: subsData } = await subsRes.json());+ ({ subscriptions: subsData } = await subsRes.json());} catch (err) {renderLoadError(errorEl, skillsGrid, subsGrid, err?.message);return;@@ -218,7 +240,10 @@ async function load() {const purchases = skillsData?.purchases ?? [];const subs = subsData ?? [];const nftCount = purchases.filter(p => p.skill_nft_mint).length;- const activeSubs = subs.filter(s => s.status === 'active').length;+ const now = Date.now();+ const activeSubs = subs.filter(s =>+ s.status === 'active' && (!s.current_period_end || new Date(s.current_period_end) > now)+ ).length;// Update statsdocument.getElementById('stat-skills').textContent = purchases.length;diff --git a/src/editor/manifest-builder.js b/src/editor/manifest-builder.jsindex 59fc3d746..8bde12ac1 100644--- a/src/editor/manifest-builder.js+++ b/src/editor/manifest-builder.js@@ -32,7 +32,7 @@ const OPENAI_MODELS = [{ id: 'gpt-4-turbo', label: 'GPT-4 Turbo' },];const BRAIN_PROVIDERS = ['anthropic', 'openai', 'local', 'none'];-const TTS_PROVIDERS = ['browser', 'elevenlabs', 'openai', 'none'];+const TTS_PROVIDERS = ['browser', 'neural', 'elevenlabs', 'openai', 'none'];const STT_PROVIDERS = ['browser', 'whisper', 'none'];const MEMORY_MODES = ['local', 'ipfs', 'encrypted-ipfs', 'none'];const RIG_TYPES = ['mixamo', 'vrm', 'custom'];@@ -69,7 +69,7 @@ const ManifestSchema = z.object({.object({tts: z.object({- provider: z.enum(['browser', 'elevenlabs', 'openai', 'none']),+ provider: z.enum(['browser', 'neural', 'elevenlabs', 'openai', 'none']),voiceId: z.string().optional(),rate: z.number().min(0.5).max(2).optional(),pitch: z.number().min(0).max(2).optional(),@@ -575,8 +575,9 @@ export function mountManifestBuilder(rootEl, options = {}) {</div><div id="tts-secondary"><div class="field" id="tts-voiceid-wrap" style="display:none">- <label>Voice ID (ElevenLabs)</label>+ <label id="f-tts-voiceid-label">Voice ID</label><input id="f-tts-voiceid" type="text" placeholder="21m00Tcm4TlvDq8ikWAM">+ <span class="hint" id="f-tts-voiceid-hint"></span></div><div class="field-row"><div class="field">@@ -998,7 +999,22 @@ export function mountManifestBuilder(rootEl, options = {}) {function refreshTtsSecondary() {const wrap = $('#tts-voiceid-wrap');- if (wrap) wrap.style.display = state.ttsProvider === 'elevenlabs' ? '' : 'none';+ const needsVoiceId = state.ttsProvider === 'elevenlabs' || state.ttsProvider === 'neural';+ if (wrap) wrap.style.display = needsVoiceId ? '' : 'none';+ const label = $('#f-tts-voiceid-label');+ const input = $('#f-tts-voiceid');+ const hint = $('#f-tts-voiceid-hint');+ if (state.ttsProvider === 'neural') {+ if (label) label.textContent = 'Voice (Kokoro)';+ if (input) input.placeholder = 'af_bella';+ if (hint)+ hint.textContent =+ 'Free, runs in the browser (WebGPU) — no API key, no per-word cost. e.g. af_bella, am_fenrir, bf_emma.';+ } else if (state.ttsProvider === 'elevenlabs') {+ if (label) label.textContent = 'Voice ID (ElevenLabs)';+ if (input) input.placeholder = '21m00Tcm4TlvDq8ikWAM';+ if (hint) hint.textContent = '';+ }}function refreshSttSecondary() {@@ -1337,7 +1353,8 @@ export function mountManifestBuilder(rootEl, options = {}) {}const tts = { provider: state.ttsProvider };- if (state.ttsProvider === 'elevenlabs' && state.voiceId) tts.voiceId = state.voiceId;+ if ((state.ttsProvider === 'elevenlabs' || state.ttsProvider === 'neural') && state.voiceId)+ tts.voiceId = state.voiceId;if (state.ttsRate !== 1.0) tts.rate = state.ttsRate;if (state.ttsPitch !== 1.0) tts.pitch = state.ttsPitch;const stt = { provider: state.sttProvider, language: state.sttLanguage };diff --git a/src/feature-tour/director.js b/src/feature-tour/director.jsindex ecfad36b8..d15badec6 100644--- a/src/feature-tour/director.js+++ b/src/feature-tour/director.js@@ -490,12 +490,15 @@ export class TourDirector {this._stopBeam();this._beam?.remove();document.removeEventListener('keydown', this._onKey);+ this.roam = false;+ this.freeRoam?.disable();this.narrator?.dispose();this.spotlight?.dispose();this.avatar?.dispose();this.controls?.dispose();this.panel?.dispose();this._doneCard?.remove();+ this._restoreCompanion();this.mounted = false;}@@ -595,8 +598,11 @@ export class TourDirector {this._toggleMute();} else if (e.key === 'c' || e.key === 'C') {this.panel?.toggle();+ } else if (e.key === 'r' || e.key === 'R') {+ this._toggleRoam();} else if (e.key === 'Escape') {- this.exit();+ if (this.roam) this._exitRoam();+ else this.exit();}}}diff --git a/src/feature-tour/guide-avatar.js b/src/feature-tour/guide-avatar.jsindex 948cf036e..61e7f1d0b 100644--- a/src/feature-tour/guide-avatar.js+++ b/src/feature-tour/guide-avatar.js@@ -292,6 +292,7 @@ export class GuideAvatar {dispose() {cancelAnimationFrame(this._raf);clearTimeout(this._walkTimer);+ clearTimeout(this._settleTimer);this._raf = 0;try {this.controller?.dispose();diff --git a/src/runtime/neural-tts.js b/src/runtime/neural-tts.jsnew file mode 100644index 000000000..66b07b983--- /dev/null+++ b/src/runtime/neural-tts.js@@ -0,0 +1,247 @@+// Neural TTS lane — free, in-browser, neural-quality speech with real phoneme+// timestamps. Wraps met4citizen/HeadTTS (MIT), which runs the Kokoro 82M ONNX+// model on WebGPU (with a WASM fallback) entirely client-side: no API key, no+// per-call cost, no audio leaving the device. Unlike the browser SpeechSynthesis+// lane it returns Oculus viseme timings, so lip-sync is locked to the actual+// audio instead of a text heuristic; unlike the ElevenLabs lane it costs nothing.+//+// HeadTTS and the model weights are loaded lazily from a CDN on first speak, so+// the main bundle stays small and avatars that never use this voice pay nothing.+// First use downloads the model (~tens of MB) — surface `onProgress` in the UI.+//+// Implements the same provider contract as BrowserTTS / ElevenLabsTTS in+// speech.js: speak(), cancel(), `speaking`, onStart/onEnd, analyserNode,+// setPositionalAudio().++import { playVisemeSequence } from './lipsync.js';+import { ACTION_TYPES } from '../agent-protocol.js';++const HEADTTS_VERSION = '1.3';+const CDN = `https://cdn.jsdelivr.net/npm/@met4citizen/headtts@${HEADTTS_VERSION}`;++// Convert one HeadTTS `audio` message's viseme arrays into the timed sequence the+// shared viseme driver consumes. Oculus IDs ('aa','E','PP',…) map 1:1 onto our+// `viseme_*` morph names. Silence ('sil') is dropped — a gap in the sequence is+// already rendered as a closed mouth.+export function headttsToSequence(data) {+ const visemes = data?.visemes;+ const vtimes = data?.vtimes;+ const vdurations = data?.vdurations;+ if (!Array.isArray(visemes) || !Array.isArray(vtimes)) return [];+ const seq = [];+ for (let i = 0; i < visemes.length; i++) {+ const id = visemes[i];+ if (!id || id === 'sil') continue;+ const startMs = Number(vtimes[i]) || 0;+ const dur = Number(vdurations?.[i]) || 80;+ seq.push({ viseme: `viseme_${id}`, startMs, endMs: startMs + dur });+ }+ return seq;+}++export class NeuralTTS {+ constructor({+ voiceId = 'af_bella',+ lang = 'en-us',+ rate = 1,+ endpoints = ['webgpu', 'wasm'],+ onProgress = null,+ moduleURL = null, // override for tests / self-hosting+ } = {}) {+ this.voiceId = voiceId;+ this.lang = lang;+ this.rate = rate;+ this.endpoints = endpoints;+ this.onProgress = onProgress;+ this.moduleURL = moduleURL;++ this._tts = null;+ this._readyPromise = null;+ this._audioCtx = null;+ this._analyserNode = null;+ this._currentSource = null;+ this._lipsync = null;+ this._speaking = false;+ this._cancelled = false;+ this._positionalAudio = null;+ // Global hooks — set by callers that manage lipsync externally (e.g. AgentAvatar).+ this.onStart = null;+ this.onEnd = null;+ }++ /** Shared AnalyserNode, so an external LipSyncAnalyser can read it (parity with ElevenLabsTTS). */+ get analyserNode() {+ return this._analyserNode;+ }++ /** @param {import('three').PositionalAudio|null} pa */+ setPositionalAudio(pa) {+ this._positionalAudio = pa;+ }++ get speaking() {+ return this._speaking;+ }++ // Lazily create the audio graph + load/connect HeadTTS. Cached after the first+ // successful call; a failed load rejects and is retried on the next speak().+ async _ensureReady() {+ if (this._tts) return this._tts;+ if (this._readyPromise) return this._readyPromise;+ this._readyPromise = (async () => {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) throw new Error('NeuralTTS requires Web Audio support');+ this._audioCtx = new AC();+ this._analyserNode = this._audioCtx.createAnalyser();+ this._analyserNode.fftSize = 256;+ this._analyserNode.smoothingTimeConstant = 0.7;+ this._analyserNode.connect(this._audioCtx.destination);++ const { HeadTTS } = await import(/* @vite-ignore */ this.moduleURL || `${CDN}/+esm`);+ const tts = new HeadTTS({+ endpoints: this.endpoints,+ languages: [this.lang],+ voices: [this.voiceId],+ audioCtx: this._audioCtx,+ workerModule: `${CDN}/modules/worker-tts.mjs`,+ dictionaryURL: `${CDN}/dictionaries/`,+ });+ await tts.connect(null, this.onProgress || null);+ tts.setup({ voice: this.voiceId, language: this.lang, speed: this.rate, audioEncoding: 'wav' });+ this._tts = tts;+ return tts;+ })().catch((err) => {+ // Reset so a transient failure (offline, model fetch) can be retried.+ this._readyPromise = null;+ throw err;+ });+ return this._readyPromise;+ }++ async speak(text, { onStart, onEnd, scene } = {}) {+ this.cancel();+ if (!text) return;+ this._speaking = true;+ this._cancelled = false;++ let tts;+ try {+ tts = await this._ensureReady();+ } catch (err) {+ this._speaking = false;+ throw err;+ }+ if (this._cancelled) {+ this._speaking = false;+ return;+ }++ let messages;+ try {+ messages = await tts.synthesize({ input: String(text) });+ } catch (err) {+ this._speaking = false;+ if (err?.name === 'AbortError') return;+ throw err;+ }++ const chunks = (messages || []).filter((m) => m?.type === 'audio' && m.data);+ if (this._cancelled || !chunks.length) {+ this._speaking = false;+ this.onEnd?.();+ onEnd?.();+ return;+ }++ // Play chunks (HeadTTS splits long text into sentences) back to back; the+ // first chunk that actually starts fires onStart.+ let started = false;+ const fireStart = () => {+ if (started) return;+ started = true;+ this.onStart?.();+ onStart?.();+ };+ for (const chunk of chunks) {+ if (this._cancelled) break;+ await this._playChunk(chunk.data, scene, fireStart);+ }++ this._speaking = false;+ this._lipsync?.stop();+ this._lipsync = null;+ this.onEnd?.();+ onEnd?.();+ }++ // Play one decoded AudioBuffer through the analyser (and the spatial panner when+ // set), driving the mouth from the chunk's viseme timeline on the audio clock.+ _playChunk(data, scene, onChunkStart) {+ return new Promise((resolve) => {+ const ctx = this._audioCtx;+ const buffer = data?.audio; // AudioBuffer — HeadTTS decodes it (audioCtx was supplied)+ if (!ctx || !buffer) {+ resolve();+ return;+ }++ // Re-point the analyser's terminal each chunk: spatial panner when an+ // avatar provided PositionalAudio, otherwise straight to the speakers.+ const sink = this._positionalAudio?.panner || ctx.destination;+ try {+ this._analyserNode.disconnect();+ } catch {}+ this._analyserNode.connect(sink);++ const src = ctx.createBufferSource();+ src.buffer = buffer;+ src.connect(this._analyserNode);+ this._currentSource = src;++ const t0 = ctx.currentTime;+ const seq = headttsToSequence(data);+ let lip = null;+ if (scene && seq.length) {+ lip = playVisemeSequence(scene, seq, () => (ctx.currentTime - t0) * 1000);+ this._lipsync = lip;+ }++ src.onended = () => {+ lip?.stop();+ if (this._lipsync === lip) this._lipsync = null;+ if (this._currentSource === src) this._currentSource = null;+ resolve();+ };++ ctx.resume?.().catch(() => {});+ if (this._positionalAudio?.context?.state === 'suspended') {+ this._positionalAudio.context.resume().catch(() => {});+ }+ onChunkStart?.();+ try {+ src.start();+ } catch {+ lip?.stop();+ resolve();+ }+ });+ }++ cancel(protocol) {+ const wasSpeaking = this._speaking;+ this._cancelled = true;+ this._lipsync?.stop();+ this._lipsync = null;+ if (this._currentSource) {+ try {+ this._currentSource.onended = null;+ this._currentSource.stop();+ } catch {}+ this._currentSource = null;+ }+ this._speaking = false;+ if (wasSpeaking && protocol) {+ protocol.emit?.({ type: ACTION_TYPES.INTERRUPTED, payload: {} });+ }+ }+}diff --git a/src/runtime/speech.js b/src/runtime/speech.jsindex b240c1004..47ace0153 100644--- a/src/runtime/speech.js+++ b/src/runtime/speech.js@@ -1,6 +1,8 @@// Speech I/O — TTS and STT. Browser-native by default; provider-swappable.export { LiveKitVoice } from './livekit-voice.js';+export { NeuralTTS } from './neural-tts.js';+import { NeuralTTS } from './neural-tts.js';import { startLipsync } from './lipsync.js';import { ACTION_TYPES } from '../agent-protocol.js';@@ -512,6 +514,7 @@ export class ElevenLabsTTS {const TTS_FACTORIES = {none: () => null,browser: (cfg) => new BrowserTTS(cfg),+ neural: (cfg) => new NeuralTTS(cfg),elevenlabs: (cfg) => new ElevenLabsTTS(cfg),};diff --git a/tests/feature-tour-curriculum.test.js b/tests/feature-tour-curriculum.test.jsindex fa08da01d..3060de4df 100644--- a/tests/feature-tour-curriculum.test.js+++ b/tests/feature-tour-curriculum.test.js@@ -13,7 +13,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { JSDOM } from 'jsdom';import { buildPlaylist, trackMeta } from '../src/feature-tour/curriculum.js';const curriculum = JSON.parse(@@ -79,3 +80,46 @@ describe('buildPlaylist', () => {expect(buildPlaylist(flat, 'quick')).toEqual([0, 1]);});});++describe('free-roam activation guard', () => {+ let dom;+ let isInteractiveTarget;++ beforeAll(async () => {+ dom = new JSDOM('<!doctype html><body></body>');+ global.window = dom.window;+ global.document = dom.window.document;+ global.matchMedia = () => ({ matches: false });+ dom.window.matchMedia = global.matchMedia;+ ({ isInteractiveTarget } = await import('../src/feature-tour/free-roam.js'));+ });++ afterAll(() => {+ delete global.window;+ delete global.document;+ delete global.matchMedia;+ });++ function make(html) {+ document.body.innerHTML = html;+ return document.body.firstElementChild;+ }++ it('treats links, buttons, inputs and canvases as page interactions', () => {+ expect(isInteractiveTarget(make('<a href="/x">x</a>'))).toBe(true);+ expect(isInteractiveTarget(make('<button>x</button>'))).toBe(true);+ expect(isInteractiveTarget(make('<input>'))).toBe(true);+ expect(isInteractiveTarget(make('<canvas></canvas>'))).toBe(true);+ expect(isInteractiveTarget(make('<div data-walk-block>x</div>'))).toBe(true);+ });++ it('counts a child of an interactive element as interactive', () => {+ const a = make('<a href="/x"><span>deep</span></a>');+ expect(isInteractiveTarget(a.querySelector('span'))).toBe(true);+ });++ it('treats plain empty space as walkable (not interactive)', () => {+ expect(isInteractiveTarget(make('<div><p>just text</p></div>'))).toBe(false);+ expect(isInteractiveTarget(null)).toBe(false);+ });+});diff --git a/tests/runtime/neural-tts.test.js b/tests/runtime/neural-tts.test.jsnew file mode 100644index 000000000..cfa6861ed--- /dev/null+++ b/tests/runtime/neural-tts.test.js@@ -0,0 +1,102 @@+// Neural TTS lane — unit tests for the pure logic that bridges HeadTTS's viseme+// output to our morph-target driver. The HeadTTS model load + WebGPU audio path+// only runs in a real browser; what's testable in Node is the data mapping+// (Oculus viseme → morph name + timing) and the shared viseme driver's lerp.++import { describe, it, expect } from 'vitest';+import { Mesh, BufferGeometry, Object3D } from 'three';+import { headttsToSequence } from '../../src/runtime/neural-tts.js';+import { activeVisemeAt, createVisemeDriver } from '../../src/runtime/lipsync.js';++// A real HeadTTS `audio` message payload (from its README example).+const HEADTTS_DATA = {+ words: ['This ', 'is ', 'an ', 'example.'],+ wtimes: [440, 656, 876, 1050],+ visemes: ['TH', 'I', 'SS', 'I', 'SS', 'aa', 'nn', 'I', 'kk', 'SS', 'aa', 'PP', 'PP', 'E', 'RR'],+ vtimes: [440, 472, 562, 656, 753, 876, 993, 1050, 1097, 1149, 1200, 1322, 1372, 1423, 1499],+ vdurations: [52, 110, 74, 117, 75, 137, 47, 67, 72, 71, 142, 70, 71, 96, 399],+};++describe('headttsToSequence', () => {+ it('maps Oculus viseme IDs onto viseme_* morph names with start/end times', () => {+ const seq = headttsToSequence(HEADTTS_DATA);+ expect(seq).toHaveLength(HEADTTS_DATA.visemes.length); // no 'sil' in this sample+ expect(seq[0]).toEqual({ viseme: 'viseme_TH', startMs: 440, endMs: 492 });+ expect(seq[5]).toEqual({ viseme: 'viseme_aa', startMs: 876, endMs: 1013 });+ // Every name is one our lipsync driver recognises.+ expect(seq.every((s) => s.viseme.startsWith('viseme_'))).toBe(true);+ });++ it("drops 'sil' (silence) — a gap already renders as a closed mouth", () => {+ const seq = headttsToSequence({ visemes: ['aa', 'sil', 'E'], vtimes: [0, 50, 100], vdurations: [50, 50, 50] });+ expect(seq.map((s) => s.viseme)).toEqual(['viseme_aa', 'viseme_E']);+ });++ it('falls back to an 80ms duration when vdurations is missing', () => {+ const seq = headttsToSequence({ visemes: ['aa'], vtimes: [10] });+ expect(seq[0]).toEqual({ viseme: 'viseme_aa', startMs: 10, endMs: 90 });+ });++ it('returns [] for malformed input', () => {+ expect(headttsToSequence(null)).toEqual([]);+ expect(headttsToSequence({})).toEqual([]);+ expect(headttsToSequence({ visemes: 'nope' })).toEqual([]);+ });+});++describe('activeVisemeAt', () => {+ const seq = headttsToSequence(HEADTTS_DATA);+ it('returns the viseme whose window contains the time', () => {+ expect(activeVisemeAt(seq, 460)).toBe('viseme_TH'); // [440,492)+ expect(activeVisemeAt(seq, 900)).toBe('viseme_aa'); // [876,1013)+ });+ it('returns null before the first and after the last viseme', () => {+ expect(activeVisemeAt(seq, 0)).toBeNull();+ expect(activeVisemeAt(seq, 100000)).toBeNull();+ });++ it('resolves overlapping windows to the earlier-listed viseme (first match wins)', () => {+ // HeadTTS windows overlap (TH [440,492), I [472,582)); 480 is in both.+ expect(activeVisemeAt(seq, 480)).toBe('viseme_TH');+ });+});++describe('createVisemeDriver', () => {+ function avatarWithMorphs(names) {+ const root = new Object3D();+ const mesh = new Mesh(new BufferGeometry());+ mesh.morphTargetDictionary = Object.fromEntries(names.map((n, i) => [n, i]));+ mesh.morphTargetInfluences = names.map(() => 0);+ root.add(mesh);+ return { root, mesh };+ }++ it('lerps the active viseme toward 1 and others toward 0', () => {+ const { root, mesh } = avatarWithMorphs(['viseme_aa', 'viseme_E']);+ const driver = createVisemeDriver(root);+ expect(driver.mode).toBe('arkit');+ for (let i = 0; i < 20; i++) driver.step('viseme_aa');+ expect(mesh.morphTargetInfluences[0]).toBeGreaterThan(0.9); // viseme_aa opened+ expect(mesh.morphTargetInfluences[1]).toBeLessThan(0.1); // viseme_E stayed shut+ });++ it('reset() zeroes every morph', () => {+ const { root, mesh } = avatarWithMorphs(['viseme_aa', 'viseme_E']);+ const driver = createVisemeDriver(root);+ for (let i = 0; i < 10; i++) driver.step('viseme_aa');+ driver.reset();+ expect(mesh.morphTargetInfluences).toEqual([0, 0]);+ });++ it('falls back to jaw-open mode when the rig has only jawOpen', () => {+ const { root, mesh } = avatarWithMorphs(['jawOpen']);+ const driver = createVisemeDriver(root);+ expect(driver.mode).toBe('jaw');+ for (let i = 0; i < 20; i++) driver.step('viseme_aa'); // any active viseme opens the jaw+ expect(mesh.morphTargetInfluences[0]).toBeGreaterThan(0.5);+ });++ it('returns null for an avatar with no mouth morphs', () => {+ expect(createVisemeDriver(new Object3D())).toBeNull();+ });+});